Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-presets-skip-framework-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@aziontech/presets': patch
---

Fix the `vue`, `react`, `preact`, `qwik`, `vitepress`, `vuepress` and `angular` presets leaving the storage folder empty (or with the build nested in a subfolder, for `angular`) when building with `--skip-framework-build`. The prebuild now copies the output of the previous framework build (`outDir` from the Vite config, `dist`, `build` for CRA, or the VitePress/VuePress `dist`) into `.edge/assets` instead of only creating the folder. The `angular` preset moves a plain `ng build` output (`dist/<project>` or `dist/<project>/browser`) to the `dist` root, like the regular build does. The `vuepress` preset no longer deletes its previous build output in this mode.
39 changes: 39 additions & 0 deletions packages/presets/src/presets/__helpers__/tempProject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join } from 'path';

/**
* Creates a temporary project directory and makes it the current working directory,
* so presets that resolve paths relative to `process.cwd()` run against it.
*/
export function createTempProject() {
const originalCwd = process.cwd();
const root = mkdtempSync(join(tmpdir(), 'preset-prebuild-'));
process.chdir(root);

return {
root,
/** Writes files (path -> content) relative to the project root, creating folders as needed. */
write(files: Record<string, string>) {
for (const [file, content] of Object.entries(files)) {
const target = join(root, file);
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, content);
}
},
/** Lists, recursively and sorted, the files inside a folder relative to the project root. */
list(dir: string): string[] {
const walk = (current: string): string[] =>
readdirSync(join(root, current), { withFileTypes: true }).flatMap((entry) =>
entry.isDirectory() ? walk(join(current, entry.name)) : [join(current, entry.name)],
);
return walk(dir)
.map((file) => file.slice(dir.length + 1))
.sort();
},
cleanup() {
process.chdir(originalCwd);
rmSync(root, { recursive: true, force: true });
},
};
}
52 changes: 52 additions & 0 deletions packages/presets/src/presets/angular/prebuild.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { afterEach, beforeEach, describe, expect, it } from '@jest/globals';
import type { BuildConfiguration, BuildContext } from '@aziontech/config';
import { createTempProject } from '../__helpers__/tempProject';
import prebuild from './prebuild';

const skipCtx = { skipFrameworkBuild: true } as BuildContext;
const buildConfig = {} as BuildConfiguration;

describe('angular prebuild with skipFrameworkBuild', () => {
let project: ReturnType<typeof createTempProject>;

beforeEach(() => {
project = createTempProject();
});

afterEach(() => {
project.cleanup();
});

it('keeps a build that is already at the dist root', async () => {
project.write({ 'dist/index.html': '<html></html>', 'dist/main.js': 'console.log(1)' });

await prebuild(buildConfig, skipCtx);

expect(project.list('dist')).toEqual(['index.html', 'main.js']);
});

it('moves dist/<project>/browser to the dist root (application builder)', async () => {
project.write({
'dist/my-app/browser/index.html': '<html></html>',
'dist/my-app/browser/chunk.js': 'console.log(1)',
});

await prebuild(buildConfig, skipCtx);

expect(project.list('dist')).toEqual(['chunk.js', 'index.html']);
});

it('moves dist/<project> to the dist root (browser builder)', async () => {
project.write({ 'dist/my-app/index.html': '<html></html>', 'dist/my-app/main.js': 'console.log(1)' });

await prebuild(buildConfig, skipCtx);

expect(project.list('dist')).toEqual(['index.html', 'main.js']);
});

it('creates an empty dist when there is no previous build', async () => {
await prebuild(buildConfig, skipCtx);

expect(project.list('dist')).toEqual([]);
});
});
56 changes: 54 additions & 2 deletions packages/presets/src/presets/angular/prebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,67 @@ async function moveBrowserFiles(browserFolder: string, storagePath: string): Pro
}
}

/**
* Find where a previous `ng build` left its output inside the dist folder.
* A plain `ng build` writes to `dist/<project>` (browser builder) or `dist/<project>/browser`
* (application builder), while the storage dir expects the files directly in `dist`.
*/
async function findPreviousBuildOutput(outputDir: string): Promise<string | null> {
const root = path.join(process.cwd(), outputDir);
const projects = await fs.readdir(root, { withFileTypes: true });

for (const project of projects.filter((entry) => entry.isDirectory())) {
for (const candidate of [path.join(root, project.name, 'browser'), path.join(root, project.name)]) {
try {
await fs.access(path.join(candidate, 'index.html'));
return candidate;
} catch {
// index.html not found here, try the next candidate
}
}
}

return null;
}

/**
* Make sure a previous `ng build` output is at the storage root (dist), like the regular build flow does.
*/
async function prepareSkippedBuild(outputDir: string): Promise<void> {
const root = path.join(process.cwd(), outputDir);
await fs.mkdir(root, { recursive: true });

// Already at the storage root (e.g. built with --output-path=./dist)
try {
await fs.access(path.join(root, 'index.html'));
return;
} catch {
// not at the root, look for it inside dist/<project>
}

const source = await findPreviousBuildOutput(outputDir);
if (!source) {
return;
}

await moveBrowserFiles(source, root);

// remove the project folder left behind when it only contained the browser output
const projectFolder = path.dirname(source);
if (projectFolder !== root) {
await fs.rmdir(projectFolder).catch(() => undefined);
}
}

/**
* Runs custom prebuild actions for Angular
*/
async function prebuild(_: BuildConfiguration, ctx: BuildContext): Promise<void> {
try {
const outputDir = './dist';
// if skipFrameworkBuild is true, we need to create the dist folder
// If skipFrameworkBuild is true, reuse the output of a previous framework build
if (ctx.skipFrameworkBuild) {
await fs.mkdir(outputDir, { recursive: true });
await prepareSkippedBuild(outputDir);
return;
}
const packageManager: PackageManagerType = await getPackageManager();
Expand Down
58 changes: 58 additions & 0 deletions packages/presets/src/presets/preact/prebuild.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { afterEach, beforeEach, describe, expect, it } from '@jest/globals';
import type { BuildConfiguration, BuildContext } from '@aziontech/config';
import { createTempProject } from '../__helpers__/tempProject';
import prebuild from './prebuild';

const skipCtx = { skipFrameworkBuild: true } as BuildContext;
const buildConfig = {} as BuildConfiguration;

describe('preact prebuild with skipFrameworkBuild', () => {
let project: ReturnType<typeof createTempProject>;

beforeEach(() => {
project = createTempProject();
});

afterEach(() => {
project.cleanup();
});

it('copies the dist folder to .edge/assets', async () => {
project.write({
'vite.config.ts': `import { defineConfig } from 'vite';\nexport default defineConfig({ plugins: [] });\n`,
'dist/index.html': '<html></html>',
});

await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual(['index.html']);
});

it('copies the outDir declared in vite.config', async () => {
project.write({
'vite.config.ts': `import { defineConfig } from 'vite';\nexport default defineConfig({\n build: { outDir: 'out' },\n});\n`,
'out/index.html': '<html></html>',
});

await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual(['index.html']);
});

it('keeps the content already in .edge/assets when the outDir is gone', async () => {
project.write({
'vite.config.ts': `import { defineConfig } from 'vite';\nexport default defineConfig({ plugins: [] });\n`,
'.edge/assets/index.html': '<html></html>',
});

await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual(['index.html']);
});

it('creates an empty .edge/assets when there is no previous build', async () => {
await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual([]);
});
});
22 changes: 21 additions & 1 deletion packages/presets/src/presets/preact/prebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ async function viteConfigExists() {
return results.includes(true);
}

/**
* Check if a path exists
*/
async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path);
return true;
} catch {
return false;
}
}

/**
* Read vite.config build output
* @returns {object} The parsed configuration object or null if the file doesn't exist.
Expand Down Expand Up @@ -64,9 +76,17 @@ async function prebuild(_: BuildConfiguration, ctx: BuildContext) {
const packageManager = await getPackageManager();
const npmArgsForward = packageManager === 'npm' ? '--' : '';

// if skipFrameworkBuild is true, we need to create the dist folder
// If skipFrameworkBuild is true, reuse the output of a previous framework build.
// If the outDir is gone (a regular build removes it after copying), keep what is already in the storage dir.
if (ctx.skipFrameworkBuild) {
await mkdir(edgeStorageDir, { recursive: true });
if (await viteConfigExists()) {
const config = await readViteBuildOutput();
const outDir = config?.build?.outDir || defaultViteOutDir;
if (await pathExists(outDir)) {
copyDirectory(outDir, edgeStorageDir);
}
}
return;
}

Expand Down
33 changes: 33 additions & 0 deletions packages/presets/src/presets/qwik/prebuild.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { afterEach, beforeEach, describe, expect, it } from '@jest/globals';
import type { BuildConfiguration, BuildContext } from '@aziontech/config';
import { createTempProject } from '../__helpers__/tempProject';
import prebuild from './prebuild';

const skipCtx = { skipFrameworkBuild: true } as BuildContext;
const buildConfig = {} as BuildConfiguration;

describe('qwik prebuild with skipFrameworkBuild', () => {
let project: ReturnType<typeof createTempProject>;

beforeEach(() => {
project = createTempProject();
});

afterEach(() => {
project.cleanup();
});

it('copies the dist folder to .edge/assets', async () => {
project.write({ 'dist/index.html': '<html></html>', 'dist/build/q-abc.js': 'console.log(1)' });

await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual(['build/q-abc.js', 'index.html']);
});

it('creates an empty .edge/assets when there is no previous build', async () => {
await prebuild(buildConfig, skipCtx);

expect(project.list('.edge/assets')).toEqual([]);
});
});
49 changes: 36 additions & 13 deletions packages/presets/src/presets/qwik/prebuild.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,54 @@
import { BuildConfiguration, BuildContext } from '@aziontech/config';
import { copyDirectory, exec, getPackageManager } from '@aziontech/utils/node';
import { mkdir, readFile } from 'fs/promises';
import { lstat, mkdir, readFile } from 'fs/promises';

/**
* Runs custom prebuild actions for Qwik
* Check if a path exists
*/
async function prebuild(_: BuildConfiguration, ctx: BuildContext): Promise<void> {
const packageManager = await getPackageManager();
const newOutDir = '.edge/assets';
let outDir = 'dist';

// if skipFrameworkBuild is true, we need to create the dist folder
if (ctx.skipFrameworkBuild) {
await mkdir(newOutDir, { recursive: true });
return;
async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path);
return true;
} catch {
return false;
}
}

// Check if an output path is specified in config file
/**
* Read the outDir from the static adapter config, if specified
*/
async function readOutDir(defaultOutDir: string): Promise<string> {
try {
const configFileContent = await readFile('./adapters/static/vite.config.ts', 'utf-8');
const attributeMatch = Array.from(configFileContent.matchAll(/outDir:(.*)\n/g), (match) => match)[0];
if (attributeMatch) {
outDir = attributeMatch[1].trim();
return attributeMatch[1].trim();
}
} catch {
// Config file doesn't exist or doesn't have outDir specified
}
return defaultOutDir;
}

/**
* Runs custom prebuild actions for Qwik
*/
async function prebuild(_: BuildConfiguration, ctx: BuildContext): Promise<void> {
const packageManager = await getPackageManager();
const newOutDir = '.edge/assets';
const defaultOutDir = 'dist';

// If skipFrameworkBuild is true, reuse the output of a previous framework build
if (ctx.skipFrameworkBuild) {
await mkdir(newOutDir, { recursive: true });
const outDir = await readOutDir(defaultOutDir);
if (await pathExists(outDir)) {
copyDirectory(outDir, newOutDir);
}
return;
}

const outDir = await readOutDir(defaultOutDir);

await exec(`${packageManager} run build`, {
scope: 'Qwik',
Expand Down
Loading
Loading