@akanjs/devkit 3.2.0-rc.17 → 3.2.0-rc.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +74 -5
- package/DEV_RUNTIME_KNOBS.md +4 -3
- package/akanApp/akanApp.host.test.ts +18 -2
- package/akanApp/akanApp.host.wiring.test.ts +723 -0
- package/akanApp/devIdleSuspend.test.ts +107 -20
- package/akanApp/devIdleSuspend.ts +31 -14
- package/akanApp/devIdleSuspend.watcher.test.ts +77 -0
- package/apiReport/apiReport.test.ts +29 -0
- package/apiReport/apiReportDiff.ts +35 -1
- package/app/applicationBuildReporter.ts +2 -49
- package/app/routeSourceValidator.test.ts +17 -0
- package/app/routeSourceValidator.ts +5 -1
- package/artifact/implicitRootLayout.test.ts +67 -3
- package/artifact/implicitRootLayout.ts +9 -4
- package/artifact/implicitRootLayoutRender.test.tsx +297 -0
- package/codeAgent/agent/akanSystemPrompt.ts +1 -1
- package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
- package/commandDecorators/command.ts +2 -1
- package/commandDecorators/commandBuilder.ts +1 -1
- package/commandDecorators/commandDecorators.test.ts +28 -4
- package/context/akanContext.ts +20 -527
- package/context/akanContextInspection.ts +296 -0
- package/context/akanMcpContract.ts +13 -253
- package/context/doctor/agentGuideCheck.ts +81 -0
- package/context/doctor/configLeftoverCheck.ts +35 -0
- package/context/doctor/doctorFindings.ts +70 -0
- package/context/doctor/generatedFreshness.ts +56 -0
- package/context/doctor/moduleShapeCheck.ts +88 -0
- package/context/doctor/recipeDuplicateCheck.ts +39 -0
- package/context/doctor/recipeIndexCheck.ts +87 -0
- package/context/doctor/rootShapeCheck.ts +55 -0
- package/context/doctor/workflowScope.ts +97 -0
- package/context/safeRead.ts +9 -0
- package/devkitUtils.test.ts +34 -0
- package/executors/executors.test.ts +28 -4
- package/executors/workspaceExecutor.ts +1 -2
- package/frontendBuild/devGeneratedIndexSync.ts +5 -36
- package/frontendBuild/hmrWatcher.stop.test.ts +36 -0
- package/frontendBuild/hmrWatcher.ts +2 -0
- package/frontendBuild/optionalPeers.test.ts +35 -7
- package/incrementalBuilder/buildBatch.proc.ts +13 -3
- package/incrementalBuilder/buildBatchProtocol.ts +2 -0
- package/incrementalBuilder/buildBatchRunner.test.ts +61 -0
- package/incrementalBuilder/buildBatchRunner.ts +6 -3
- package/incrementalBuilder/builderBoot.ts +106 -0
- package/incrementalBuilder/builderBuildStatus.ts +23 -0
- package/incrementalBuilder/builderChannel.ts +11 -0
- package/incrementalBuilder/builderLanes.ts +157 -0
- package/incrementalBuilder/builderWatch.ts +213 -0
- package/incrementalBuilder/csrRegistry.ts +234 -0
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +92 -1
- package/incrementalBuilder/incrementalBuilder.proc.ts +80 -822
- package/incrementalBuilder/ssrRegistry.ts +278 -0
- package/integration/devStability.integration.test.ts +62 -56
- package/package.json +3 -3
- package/test/testHelpers.ts +36 -0
- package/util/errorReport.ts +66 -0
- package/workflow/constantSource.ts +187 -0
- package/workflow/dictionarySource.ts +184 -0
- package/workflow/executor.ts +5 -8
- package/workflow/fieldExpression.ts +153 -0
- package/workflow/fieldLabel.ts +61 -0
- package/workflow/fieldOrder.ts +117 -0
- package/workflow/fieldType.ts +2 -1
- package/workflow/keyRename.ts +1 -1
- package/workflow/moduleIndex.ts +1 -1
- package/workflow/modulePaths.ts +27 -0
- package/workflow/mutationScaffold.ts +7 -15
- package/workflow/mutationSource.ts +2 -1
- package/workflow/plan.ts +2 -1
- package/workflow/primitiveReport.ts +78 -0
- package/workflow/serviceSource.ts +33 -0
- package/workflow/signalSource.ts +96 -0
- package/workflow/source.ts +50 -1100
- package/workflow/sourceAst.ts +30 -0
- package/workflow/sourceImports.ts +105 -0
- package/workflow/sourceText.ts +13 -0
- package/workflow/templateSource.ts +30 -0
- package/workflow/testSource.ts +31 -0
- package/workflow/types.ts +1 -1
- package/workflow/uiPolicy.ts +1 -1
- package/workspace/workspaceLayout.ts +3 -1
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import { mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { capitalize } from "akanjs/common";
|
|
3
|
+
import { barrelFacetDirs, capitalize, facetBarrelOf } from "akanjs/common";
|
|
4
4
|
import { FileSys } from "../util/fileSys";
|
|
5
5
|
|
|
6
|
-
const BARREL_FACETS = new Set(
|
|
7
|
-
const FACET_SOURCE_FILE_RE = /\.(ts|tsx)$/;
|
|
8
|
-
const FACET_EXCLUDED_FILE_RE = /(^index\.tsx?$|\.d\.ts$|\.(test|spec)\.(ts|tsx)$|\.css$|\.scss$|\.sass$)/;
|
|
9
|
-
const FACET_PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
|
|
10
|
-
const FACET_CAMEL_CASE_RE = /^[a-z][A-Za-z0-9]*$/;
|
|
6
|
+
const BARREL_FACETS = new Set<string>(barrelFacetDirs);
|
|
11
7
|
const MODULE_UI_TYPES = ["Template", "Unit", "Util", "View", "Zone"] as const;
|
|
12
8
|
const SERVICE_UI_TYPES = ["Util", "Zone"] as const;
|
|
13
9
|
const SCALAR_UI_TYPES = ["Template", "Unit"] as const;
|
|
@@ -113,22 +109,11 @@ export class DevGeneratedIndexSync {
|
|
|
113
109
|
}
|
|
114
110
|
|
|
115
111
|
async #facetContent(dir: string): Promise<string | null> {
|
|
116
|
-
const nameCasePattern = path.basename(dir) === "ui" ? FACET_PASCAL_CASE_RE : FACET_CAMEL_CASE_RE;
|
|
117
112
|
const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);
|
|
118
113
|
if (!entries) return null;
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if (name.startsWith(".")) return [];
|
|
123
|
-
if (entry.isDirectory()) return nameCasePattern.test(name) ? [name] : [];
|
|
124
|
-
if (!entry.isFile()) return [];
|
|
125
|
-
if (!FACET_SOURCE_FILE_RE.test(name) || FACET_EXCLUDED_FILE_RE.test(name)) return [];
|
|
126
|
-
const exportName = name.replace(FACET_SOURCE_FILE_RE, "");
|
|
127
|
-
return nameCasePattern.test(exportName) ? [exportName] : [];
|
|
128
|
-
})
|
|
129
|
-
.sort(compareExportNames);
|
|
130
|
-
if (exportNames.length === 0) return "export {};\n";
|
|
131
|
-
return `${exportNames.map((name) => `export * from "./${name}";`).join("\n")}\n`;
|
|
114
|
+
const files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
|
|
115
|
+
const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
116
|
+
return facetBarrelOf(path.basename(dir), files, dirs);
|
|
132
117
|
}
|
|
133
118
|
|
|
134
119
|
async #moduleContent(dir: string): Promise<string | null> {
|
|
@@ -154,22 +139,6 @@ export class DevGeneratedIndexSync {
|
|
|
154
139
|
}
|
|
155
140
|
}
|
|
156
141
|
|
|
157
|
-
//? Biome's organizeImports order, or `akan lint` reorders the barrel: A < a < B < b, a digit before a letter, and a
|
|
158
|
-
//? run of digits compared by its length first. The facetIndex template sorts the same way.
|
|
159
|
-
const letterRankOf = (char: string) => char.toLowerCase().charCodeAt(0) * 2 + (char === char.toLowerCase() ? 1 : 0);
|
|
160
|
-
const digitRunAt = (name: string, idx: number) => /^\d+/.exec(name.slice(idx))?.[0] ?? "";
|
|
161
|
-
const compareExportNames = (a: string, b: string) => {
|
|
162
|
-
for (let idx = 0; idx < a.length && idx < b.length; ) {
|
|
163
|
-
const [runA, runB] = [digitRunAt(a, idx), digitRunAt(b, idx)];
|
|
164
|
-
if (runA && runB && runA !== runB) return runA.length - runB.length || (runA < runB ? -1 : 1);
|
|
165
|
-
if (runA && runB) idx += runA.length;
|
|
166
|
-
else if (runA || runB) return runA ? -1 : 1;
|
|
167
|
-
else if (a.charAt(idx) !== b.charAt(idx)) return letterRankOf(a.charAt(idx)) - letterRankOf(b.charAt(idx));
|
|
168
|
-
else idx++;
|
|
169
|
-
}
|
|
170
|
-
return a.length - b.length;
|
|
171
|
-
};
|
|
172
|
-
|
|
173
142
|
const exists = async (file: string) =>
|
|
174
143
|
stat(file)
|
|
175
144
|
.then(() => true)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, mock, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { Logger } from "akanjs/common";
|
|
4
|
+
import { heldMtimeIndex, saveUntil, tempDirs, writeText } from "../test/testHelpers";
|
|
5
|
+
import type { ChangeBatch } from "./hmrWatcher";
|
|
6
|
+
|
|
7
|
+
const held = heldMtimeIndex();
|
|
8
|
+
mock.module("./sourceMtimeIndex", () => ({ SourceMtimeIndex: held.SourceMtimeIndex }));
|
|
9
|
+
|
|
10
|
+
const { HmrWatcher } = await import("./hmrWatcher");
|
|
11
|
+
|
|
12
|
+
const logger = {
|
|
13
|
+
verbose: () => undefined,
|
|
14
|
+
info: () => undefined,
|
|
15
|
+
warn: () => undefined,
|
|
16
|
+
error: () => undefined,
|
|
17
|
+
} as unknown as Logger;
|
|
18
|
+
const makeRoot = tempDirs("akan-hmr-watcher-stop-");
|
|
19
|
+
|
|
20
|
+
describe("HmrWatcher stopped while a scan runs", () => {
|
|
21
|
+
test("hands over no batch, though the scan settles with an edit made while it primed", async () => {
|
|
22
|
+
const root = await makeRoot();
|
|
23
|
+
const source = path.join(root, "lib/a.ts");
|
|
24
|
+
await writeText(source, "export const x = 0;\n");
|
|
25
|
+
const batches: ChangeBatch[] = [];
|
|
26
|
+
const watcher = new HmrWatcher({ roots: [root], logger, onBatch: (batch) => void batches.push(batch) });
|
|
27
|
+
const starting = watcher.start();
|
|
28
|
+
expect(await saveUntil(source, () => held.scans.length > 0)).toBe(true);
|
|
29
|
+
watcher.stop();
|
|
30
|
+
held.primes[0].resolve();
|
|
31
|
+
await starting;
|
|
32
|
+
held.scans[0].resolve([]);
|
|
33
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
34
|
+
expect(batches).toEqual([]);
|
|
35
|
+
}, 15_000);
|
|
36
|
+
});
|
|
@@ -143,6 +143,8 @@ export class HmrWatcher {
|
|
|
143
143
|
try {
|
|
144
144
|
while (!this.#stopped) {
|
|
145
145
|
await this.#mergeDetectedChanges();
|
|
146
|
+
//? stop() can land while the scan runs; a batch handed over after it reaches an owner that has moved on.
|
|
147
|
+
if (this.#stopped) break;
|
|
146
148
|
if (this.#pending.size === 0) {
|
|
147
149
|
this.#windowStartedAt = null;
|
|
148
150
|
break;
|
|
@@ -69,19 +69,37 @@ const buildCsr = async (indexPage: string) => {
|
|
|
69
69
|
logger: { warn: () => undefined },
|
|
70
70
|
};
|
|
71
71
|
const reached: string[] = [];
|
|
72
|
+
const metafiles: Bun.BuildMetafile[] = [];
|
|
72
73
|
const build = Bun.build;
|
|
73
|
-
const recorded = spyOn(Bun, "build").mockImplementation((config) =>
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
const recorded = spyOn(Bun, "build").mockImplementation(async (config) => {
|
|
75
|
+
const result = await build({
|
|
76
|
+
...config,
|
|
77
|
+
metafile: true,
|
|
78
|
+
plugins: [recordOptionalPeers(reached), ...(config.plugins ?? [])],
|
|
79
|
+
});
|
|
80
|
+
if (result.metafile) metafiles.push(result.metafile);
|
|
81
|
+
return result;
|
|
82
|
+
});
|
|
76
83
|
|
|
77
84
|
try {
|
|
78
85
|
await new CsrArtifactBuilder(app as never, "build").build();
|
|
79
86
|
} finally {
|
|
80
87
|
recorded.mockRestore();
|
|
81
88
|
}
|
|
82
|
-
return { root, reached };
|
|
89
|
+
return { root, reached, metafiles };
|
|
83
90
|
};
|
|
84
91
|
|
|
92
|
+
const mcpAppPage =
|
|
93
|
+
'import { page } from "akanjs/client";\nimport { Link } from "akanjs/ui";\n\nexport default page()\n .app("showHome", "Show the home link.", () => <Link href="/">home</Link>)\n .render(() => null);\n';
|
|
94
|
+
|
|
95
|
+
const bytesFrom = (metafiles: Bun.BuildMetafile[], entry: string, input: string) =>
|
|
96
|
+
metafiles
|
|
97
|
+
.flatMap((metafile) => Object.values(metafile.outputs))
|
|
98
|
+
.filter((output) => output.entryPoint?.endsWith(entry))
|
|
99
|
+
.flatMap((output) => Object.entries(output.inputs))
|
|
100
|
+
.filter(([file]) => file.endsWith(input))
|
|
101
|
+
.reduce((sum, [, { bytesInOutput }]) => sum + bytesInOutput, 0);
|
|
102
|
+
|
|
85
103
|
describe("optional peers of akanjs", () => {
|
|
86
104
|
test("the generated root layout, the _overrides.tsx wrapper and the runtime entries import none", async () => {
|
|
87
105
|
const { appDir, pageKeys } = await writeApp("export default function Page() {\n return null;\n}\n");
|
|
@@ -122,11 +140,21 @@ describe("optional peers of akanjs", () => {
|
|
|
122
140
|
});
|
|
123
141
|
|
|
124
142
|
test("the MCP App view build of a page drawing akanjs/ui components imports none", async () => {
|
|
125
|
-
const { root, reached } = await buildCsr(
|
|
126
|
-
'import { page } from "akanjs/client";\nimport { Link } from "akanjs/ui";\n\nexport default page()\n .app("showHome", "Show the home link.", () => <Link href="/">home</Link>)\n .render(() => null);\n',
|
|
127
|
-
);
|
|
143
|
+
const { root, reached } = await buildCsr(mcpAppPage);
|
|
128
144
|
|
|
129
145
|
expect(await Bun.file(path.join(root, "dist/apps/demo/mcp-apps/showHome.html")).exists()).toBe(true);
|
|
130
146
|
expect(reached).toEqual([]);
|
|
131
147
|
});
|
|
132
148
|
});
|
|
149
|
+
|
|
150
|
+
describe("the CSR shell and the MCP App view", () => {
|
|
151
|
+
test("leave out the route-level boundary class, which only a server render draws, and keep RenderFailure", async () => {
|
|
152
|
+
const { metafiles } = await buildCsr(mcpAppPage);
|
|
153
|
+
|
|
154
|
+
for (const entry of ["generated/csr/index.html", "generated/mcp-apps/showHome.html"]) {
|
|
155
|
+
expect(bytesFrom(metafiles, entry, "webkit/RenderFailure.tsx")).toBeGreaterThan(0);
|
|
156
|
+
//? What stays of the module is its React import binding; the class alone is several hundred bytes.
|
|
157
|
+
expect(bytesFrom(metafiles, entry, "webkit/RouteLevelBoundary.tsx")).toBeLessThan(40);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
});
|
|
@@ -47,7 +47,7 @@ class BuildBatch {
|
|
|
47
47
|
return this.#result;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
// A bare `process.send` is safe only because
|
|
50
|
+
// A bare `process.send` is safe only because `main` exits once the runner has read the result sent after it;
|
|
51
51
|
// an explicit `process.exit` after an emit would silently drop payloads (route through BuilderChannel then).
|
|
52
52
|
#emit(message: BuilderMessage): void {
|
|
53
53
|
process.send?.(message);
|
|
@@ -294,6 +294,16 @@ class BuildBatch {
|
|
|
294
294
|
});
|
|
295
295
|
}
|
|
296
296
|
|
|
297
|
+
// Bounded, so a runner that never releases this process cannot keep the bundler arenas alive.
|
|
298
|
+
static #report(result: BuildBatchResult): Promise<void> {
|
|
299
|
+
if (!process.send) return Promise.resolve();
|
|
300
|
+
return new Promise((resolve) => {
|
|
301
|
+
process.once("disconnect", () => resolve());
|
|
302
|
+
process.send?.({ type: "build-batch-result", data: result });
|
|
303
|
+
setTimeout(() => process.disconnect?.(), 5_000).unref();
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
297
307
|
static async main(): Promise<void> {
|
|
298
308
|
const raw = process.argv[2];
|
|
299
309
|
if (!raw) throw new Error("[build-batch] missing request argument");
|
|
@@ -312,12 +322,12 @@ class BuildBatch {
|
|
|
312
322
|
// Seeded, not rediscovered: route discovery would be the largest cost of spawning this process.
|
|
313
323
|
if (request.pageKeys) app.setPageKeys(request.pageKeys);
|
|
314
324
|
//? Exits with the builder that spawned it (a kill, a crash, a restart for a metadata save): left running, it would
|
|
315
|
-
//? write a registry its replacement is rebuilding. Removed before
|
|
325
|
+
//? write a registry its replacement is rebuilding. Removed before reporting, as the runner's release is a disconnect.
|
|
316
326
|
const orphaned = () => process.exit(1);
|
|
317
327
|
process.on("disconnect", orphaned);
|
|
318
328
|
const result = await new BuildBatch(request, app).run();
|
|
319
|
-
process.send?.({ type: "build-batch-result", data: result });
|
|
320
329
|
process.off("disconnect", orphaned);
|
|
330
|
+
await BuildBatch.#report(result);
|
|
321
331
|
}
|
|
322
332
|
}
|
|
323
333
|
|
|
@@ -22,6 +22,8 @@ export interface BuildBatchRequest {
|
|
|
22
22
|
trace?: HmrTrace;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
export type BatchWork = Pick<BuildBatchRequest, "generation" | "needs" | "changedFiles" | "trace">;
|
|
26
|
+
|
|
25
27
|
export type PagesBatchCssAssets = CssPayload["cssAssets"];
|
|
26
28
|
|
|
27
29
|
// Browser payloads stream as each need finishes; only state the next batch needs travels back here.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createTempApp, tempRoots, writeText } from "../test/testHelpers";
|
|
4
|
+
import type { BuildBatchMessage, BuildBatchRequest, BuildBatchResult } from "./buildBatchProtocol";
|
|
4
5
|
import { BuildBatchRunner } from "./buildBatchRunner";
|
|
5
6
|
|
|
6
7
|
const track = tempRoots();
|
|
@@ -62,4 +63,64 @@ setTimeout(() => process.exit(1), 50);
|
|
|
62
63
|
expect(result.errors.css).toBe("css broke");
|
|
63
64
|
expect(result.errors.pages).toContain("exited with code 1");
|
|
64
65
|
}, 30_000);
|
|
66
|
+
|
|
67
|
+
test("releases a worker as soon as its result arrives, so one that holds its exit for that is not left waiting", async () => {
|
|
68
|
+
const { root } = track(await createTempApp("demo"));
|
|
69
|
+
const appDir = path.join(root, "apps/demo");
|
|
70
|
+
const released = path.join(root, "released");
|
|
71
|
+
await writeText(
|
|
72
|
+
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
73
|
+
`import fs from "node:fs";
|
|
74
|
+
const { generation } = JSON.parse(process.argv[2]);
|
|
75
|
+
process.once("disconnect", () => fs.writeFileSync(${JSON.stringify(released)}, ""));
|
|
76
|
+
process.send({ type: "build-batch-result", data: { generation, errors: {} } });
|
|
77
|
+
setTimeout(() => process.exit(1), 2_000).unref();
|
|
78
|
+
`,
|
|
79
|
+
);
|
|
80
|
+
const result = await new BuildBatchRunner({ workspaceRoot: root, cwd: appDir }).run({
|
|
81
|
+
appName: "demo",
|
|
82
|
+
workspaceRoot: root,
|
|
83
|
+
repoName: "repo",
|
|
84
|
+
generation: 3,
|
|
85
|
+
needs: ["pages"],
|
|
86
|
+
changedFiles: [],
|
|
87
|
+
pageKeys: null,
|
|
88
|
+
optimizedFonts: null,
|
|
89
|
+
cssAssets: null,
|
|
90
|
+
artifactDir: path.join(appDir, ".akan/artifact"),
|
|
91
|
+
});
|
|
92
|
+
expect(result).toEqual({ generation: 3, errors: {} });
|
|
93
|
+
expect(await Bun.file(released).exists()).toBe(true);
|
|
94
|
+
}, 30_000);
|
|
95
|
+
|
|
96
|
+
test("the build worker stays up after reporting its result until its runner releases it", async () => {
|
|
97
|
+
const { root } = track(await createTempApp("demo", path.join(import.meta.dir, "..", "local")));
|
|
98
|
+
const appDir = path.join(root, "apps/demo");
|
|
99
|
+
const request = {
|
|
100
|
+
appName: "demo",
|
|
101
|
+
workspaceRoot: root,
|
|
102
|
+
repoName: "repo",
|
|
103
|
+
generation: 4,
|
|
104
|
+
needs: [],
|
|
105
|
+
changedFiles: [],
|
|
106
|
+
pageKeys: [],
|
|
107
|
+
optimizedFonts: null,
|
|
108
|
+
cssAssets: null,
|
|
109
|
+
artifactDir: path.join(appDir, ".akan/artifact"),
|
|
110
|
+
} satisfies BuildBatchRequest;
|
|
111
|
+
const { promise: reported, resolve: report } = Promise.withResolvers<BuildBatchResult>();
|
|
112
|
+
const worker = Bun.spawn(["bun", path.join(import.meta.dir, "buildBatch.proc.ts"), JSON.stringify(request)], {
|
|
113
|
+
cwd: appDir,
|
|
114
|
+
stdio: ["ignore", "inherit", "inherit"],
|
|
115
|
+
serialization: "advanced",
|
|
116
|
+
ipc: (message: BuildBatchMessage) => {
|
|
117
|
+
if (message.type === "build-batch-result") report(message.data);
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
expect(await reported).toEqual({ generation: 4, errors: {} });
|
|
121
|
+
const unreleased = await Promise.race([worker.exited.then(() => "exited"), Bun.sleep(300).then(() => "running")]);
|
|
122
|
+
worker.disconnect();
|
|
123
|
+
expect(unreleased).toBe("running");
|
|
124
|
+
expect(await worker.exited).toBe(0);
|
|
125
|
+
}, 30_000);
|
|
65
126
|
});
|
|
@@ -47,10 +47,13 @@ export class BuildBatchRunner {
|
|
|
47
47
|
env: process.env,
|
|
48
48
|
stdio: ["ignore", "inherit", "inherit"],
|
|
49
49
|
serialization: "advanced",
|
|
50
|
-
ipc: (message: BuildBatchMessage | BuilderMessage) => {
|
|
50
|
+
ipc: (message: BuildBatchMessage | BuilderMessage, worker) => {
|
|
51
51
|
if (!message || typeof message !== "object") return;
|
|
52
|
-
if (message.type === "build-batch-result")
|
|
53
|
-
|
|
52
|
+
if (message.type === "build-batch-result") {
|
|
53
|
+
result = message.data;
|
|
54
|
+
// On Bun 1.4 a worker that exits within ms of spawning can lose everything it sent: it exits on this release.
|
|
55
|
+
worker.disconnect();
|
|
56
|
+
} else {
|
|
54
57
|
if (message.type === "build-status") reported.set(message.data.phase, message.data.message);
|
|
55
58
|
onMessage(message);
|
|
56
59
|
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { App } from "@akanjs/devkit/commandDecorators";
|
|
3
|
+
import type { ClientEntryDiscovery } from "@akanjs/devkit/frontendBuild/clientBuildTypes";
|
|
4
|
+
import { GraphClientEntryDiscovery } from "@akanjs/devkit/frontendBuild/clientEntryDiscovery";
|
|
5
|
+
import { HmrWatcher } from "@akanjs/devkit/frontendBuild/hmrWatcher";
|
|
6
|
+
import { WatchRootResolver } from "@akanjs/devkit/frontendBuild/watchRootResolver";
|
|
7
|
+
import type { Logger } from "akanjs/common";
|
|
8
|
+
import type { BaseBuildArtifact } from "akanjs/server";
|
|
9
|
+
import type { OptimizedFonts } from "./buildBatchProtocol";
|
|
10
|
+
import type { BuildBatchRunner } from "./buildBatchRunner";
|
|
11
|
+
import { BuilderChannel } from "./builderChannel";
|
|
12
|
+
|
|
13
|
+
export interface IncrementalBuilderOptions {
|
|
14
|
+
app: App;
|
|
15
|
+
artifact: BaseBuildArtifact;
|
|
16
|
+
watch: boolean;
|
|
17
|
+
optimizedFonts: OptimizedFonts;
|
|
18
|
+
discovery: ClientEntryDiscovery;
|
|
19
|
+
initialGeneration?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type IncrementalBuilderBootDeps = Pick<IncrementalBuilderOptions, "artifact" | "optimizedFonts" | "discovery">;
|
|
23
|
+
|
|
24
|
+
export class BuilderBoot {
|
|
25
|
+
// Discovery stays in-process because route builds need it live; it is free at boot, building its graph lazily.
|
|
26
|
+
static async buildBootDeps(app: App, runner: BuildBatchRunner): Promise<IncrementalBuilderBootDeps> {
|
|
27
|
+
const result = await runner.run({
|
|
28
|
+
appName: app.name,
|
|
29
|
+
workspaceRoot: app.workspace.workspaceRoot,
|
|
30
|
+
repoName: app.workspace.repoName,
|
|
31
|
+
generation: 0,
|
|
32
|
+
needs: ["base"],
|
|
33
|
+
changedFiles: [],
|
|
34
|
+
pageKeys: null,
|
|
35
|
+
optimizedFonts: null,
|
|
36
|
+
cssAssets: null,
|
|
37
|
+
artifactDir: path.resolve(`${app.cwdPath}/.akan/artifact`),
|
|
38
|
+
});
|
|
39
|
+
// Throws rather than degrading quietly: `main` catches it to enter degraded watch mode.
|
|
40
|
+
if (result.errors.base) throw new Error(result.errors.base);
|
|
41
|
+
if (!result.artifact || !result.optimizedFonts)
|
|
42
|
+
throw new Error("boot build reported success without an artifact; the build worker likely died");
|
|
43
|
+
const discovery = await GraphClientEntryDiscovery.create(app);
|
|
44
|
+
return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A boot compile error must not kill the builder, the dev server's only file watcher: report it, emit builder-ready
|
|
48
|
+
// so the backend keeps the last-good artifact, and retry the boot build on every change.
|
|
49
|
+
static recoverBoot<Builder>(
|
|
50
|
+
app: App,
|
|
51
|
+
bootError: unknown,
|
|
52
|
+
logger: Logger,
|
|
53
|
+
runner: BuildBatchRunner,
|
|
54
|
+
initialGeneration: number,
|
|
55
|
+
create: (options: IncrementalBuilderOptions) => Builder,
|
|
56
|
+
): Promise<{ builder: Builder; changedFiles: string[] }> {
|
|
57
|
+
const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
|
|
58
|
+
logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
|
|
59
|
+
let generation = initialGeneration;
|
|
60
|
+
const sendFailure = (files: string[], message: string) => {
|
|
61
|
+
BuilderChannel.emit({
|
|
62
|
+
type: "build-status",
|
|
63
|
+
data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` },
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
sendFailure([], firstMessage);
|
|
67
|
+
BuilderChannel.emit({ type: "builder-ready" });
|
|
68
|
+
// Nothing builds until a save fixes the boot, so the next app's boot need not wait for this one.
|
|
69
|
+
BuilderChannel.emit({ type: "boot-armed" });
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
void (async () => {
|
|
72
|
+
const roots = await new WatchRootResolver(app).resolve();
|
|
73
|
+
const watcher = new HmrWatcher({
|
|
74
|
+
roots,
|
|
75
|
+
logger,
|
|
76
|
+
onBatch: async (batch) => {
|
|
77
|
+
generation += 1;
|
|
78
|
+
const files = [...batch.files].sort();
|
|
79
|
+
try {
|
|
80
|
+
// A broken akan.config.ts caches its import failure; re-import it before rebuilding.
|
|
81
|
+
if (new Set(batch.kinds).has("config")) await app.getConfig({ refresh: true });
|
|
82
|
+
const deps = await BuilderBoot.buildBootDeps(app, runner);
|
|
83
|
+
const builder = create({ app, watch: true, initialGeneration: generation, ...deps });
|
|
84
|
+
watcher.stop();
|
|
85
|
+
logger.info(`boot build recovered generation=${generation}`);
|
|
86
|
+
resolve({ builder, changedFiles: files });
|
|
87
|
+
} catch (err) {
|
|
88
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
89
|
+
logger.error(`boot build retry failed: ${message}`);
|
|
90
|
+
sendFailure(files, message);
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
await watcher.start();
|
|
95
|
+
logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
|
|
96
|
+
})().catch(reject);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
//? A replacement builder continues past the host's last generation: from 0, the save fixing an error read older than
|
|
101
|
+
//? the failure the tabs hold, and from that generation itself its arming builds' ok did not read as the fix either.
|
|
102
|
+
static initialGeneration(): number {
|
|
103
|
+
const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
|
|
104
|
+
return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { BuildPhase } from "akanjs/server";
|
|
2
|
+
import { BuilderChannel } from "./builderChannel";
|
|
3
|
+
|
|
4
|
+
export const sendBuildStatus = (
|
|
5
|
+
phase: BuildPhase,
|
|
6
|
+
{
|
|
7
|
+
generation,
|
|
8
|
+
ok,
|
|
9
|
+
files,
|
|
10
|
+
message,
|
|
11
|
+
scope,
|
|
12
|
+
}: { generation?: number; ok: boolean; files?: string[]; message?: string; scope?: string },
|
|
13
|
+
): void => {
|
|
14
|
+
if (typeof generation !== "number") return;
|
|
15
|
+
BuilderChannel.emit({
|
|
16
|
+
type: "build-status",
|
|
17
|
+
data: { generation, phase, ok, files: files ?? [], message, ...(scope !== undefined ? { scope } : {}) },
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
//? A save the user broke fails the same way in a worker, so it is reported here and the patcher keeps its state: the
|
|
22
|
+
//? modules it could not compile stay pending in the graph and the fixing save compiles them.
|
|
23
|
+
export const isCompileError = (error: unknown): boolean => error instanceof AggregateError;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Logger } from "akanjs/common";
|
|
1
2
|
import type { BuilderMessage } from "akanjs/server";
|
|
2
3
|
|
|
3
4
|
// `process.exit` drops an ipc write that has not flushed (a natural exit does not), and whether one survives
|
|
@@ -28,6 +29,16 @@ export class BuilderChannel {
|
|
|
28
29
|
void BuilderChannel.send(message);
|
|
29
30
|
}
|
|
30
31
|
|
|
32
|
+
//? `AKAN_DEV_BUILDER_READY_GATE` is a test hook: the dev-stability suite holds a replacement short of ready.
|
|
33
|
+
static async announceReady(logger: Logger): Promise<void> {
|
|
34
|
+
const gate = process.env.AKAN_DEV_BUILDER_READY_GATE;
|
|
35
|
+
if (gate && !(await Bun.file(gate).exists())) {
|
|
36
|
+
logger.warn(`AKAN_DEV_BUILDER_READY_GATE is set: holding builder-ready until ${gate} exists`);
|
|
37
|
+
while (!(await Bun.file(gate).exists())) await Bun.sleep(100);
|
|
38
|
+
}
|
|
39
|
+
BuilderChannel.emit({ type: "builder-ready" });
|
|
40
|
+
}
|
|
41
|
+
|
|
31
42
|
// Loops because `#reportMetrics` can send from a work item's `finally` after the drain has begun.
|
|
32
43
|
static async drain(): Promise<number> {
|
|
33
44
|
let flushed = 0;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { ApplicationBuildReporter } from "@akanjs/devkit/app/applicationBuildReporter";
|
|
2
|
+
import type { App } from "@akanjs/devkit/commandDecorators";
|
|
3
|
+
import type { Logger } from "akanjs/common";
|
|
4
|
+
import type { BatchWork, BuildBatchResult } from "./buildBatchProtocol";
|
|
5
|
+
import { sendBuildStatus } from "./builderBuildStatus";
|
|
6
|
+
import { BuilderChannel } from "./builderChannel";
|
|
7
|
+
import { type BatchJob, BuilderWorkQueue } from "./builderWorkQueue";
|
|
8
|
+
|
|
9
|
+
interface BuilderLanesLinks {
|
|
10
|
+
generation: () => number;
|
|
11
|
+
runQueuedBatch: (batch: BatchJob) => Promise<void>;
|
|
12
|
+
runBatch: (work: BatchWork) => Promise<BuildBatchResult>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class BuilderLanes {
|
|
16
|
+
readonly #app: App;
|
|
17
|
+
readonly #logger: Logger;
|
|
18
|
+
readonly #links: BuilderLanesLinks;
|
|
19
|
+
/** Arming and the route entries deferred behind it run beside both lanes; a recycle waits for them too. */
|
|
20
|
+
readonly #beside = new Set<Promise<void>>();
|
|
21
|
+
//* Two lanes: a save's codegen and CSR patch in the fast one, which the watcher waits for; build workers, route
|
|
22
|
+
//* builds and discovery in the slow one, which folds queued batches. A save no longer waits behind pages and css.
|
|
23
|
+
#fastQueue: Promise<void> = Promise.resolve();
|
|
24
|
+
readonly #workQueue: BuilderWorkQueue;
|
|
25
|
+
#inFlight = 0;
|
|
26
|
+
#workCount = 0;
|
|
27
|
+
#shuttingDown = false;
|
|
28
|
+
#cssRebuildQueue: Promise<void> = Promise.resolve();
|
|
29
|
+
#cssRebuildTimer: ReturnType<typeof setTimeout> | null = null;
|
|
30
|
+
#pendingCssRebuild: { generation?: number; changedFiles?: string[] } | null = null;
|
|
31
|
+
|
|
32
|
+
constructor(app: App, { logger }: { logger: Logger }, links: BuilderLanesLinks) {
|
|
33
|
+
this.#app = app;
|
|
34
|
+
this.#logger = logger;
|
|
35
|
+
this.#links = links;
|
|
36
|
+
this.#workQueue = new BuilderWorkQueue({
|
|
37
|
+
runBatch: async (batch) => await this.#links.runQueuedBatch(batch),
|
|
38
|
+
onSettled: (label, ms) => {
|
|
39
|
+
this.#workCount += 1;
|
|
40
|
+
this.#logger.verbose(`[work-queue] ${label} finished in ${ms}ms`);
|
|
41
|
+
this.#reportMetrics();
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
get workQueue(): BuilderWorkQueue {
|
|
47
|
+
return this.#workQueue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
get inFlight(): number {
|
|
51
|
+
return this.#inFlight;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
get shuttingDown(): boolean {
|
|
55
|
+
return this.#shuttingDown;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
markShuttingDown(): void {
|
|
59
|
+
this.#shuttingDown = true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async enqueueFast<T>(label: string, fn: () => Promise<T>): Promise<T> {
|
|
63
|
+
const started = Date.now();
|
|
64
|
+
this.#inFlight += 1;
|
|
65
|
+
const run = this.#fastQueue.then(fn, fn);
|
|
66
|
+
this.#fastQueue = run.then(() => undefined).catch(() => undefined);
|
|
67
|
+
try {
|
|
68
|
+
return await run;
|
|
69
|
+
} finally {
|
|
70
|
+
this.#inFlight -= 1;
|
|
71
|
+
this.#workCount += 1;
|
|
72
|
+
this.#logger.verbose(`[fast-queue] ${label} finished in ${Date.now() - started}ms`);
|
|
73
|
+
this.#reportMetrics();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
get #idle(): boolean {
|
|
78
|
+
return this.#inFlight === 0 && this.#workQueue.size === 0 && this.#cssRebuildTimer === null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Callers catch their own errors: the promise handed in never rejects.
|
|
82
|
+
runBeside(work: Promise<void>): Promise<void> {
|
|
83
|
+
this.#inFlight += 1;
|
|
84
|
+
const tracked: Promise<void> = work.finally(() => {
|
|
85
|
+
this.#inFlight -= 1;
|
|
86
|
+
this.#beside.delete(tracked);
|
|
87
|
+
this.#reportMetrics();
|
|
88
|
+
});
|
|
89
|
+
this.#beside.add(tracked);
|
|
90
|
+
return tracked;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Idle only: the host recycles on these metrics, and a recycle decided mid-work would truncate it or race the drain.
|
|
94
|
+
#reportMetrics(): void {
|
|
95
|
+
if (!this.#idle || this.#shuttingDown) return;
|
|
96
|
+
BuilderChannel.emit({
|
|
97
|
+
type: "builder-metrics",
|
|
98
|
+
data: { rssBytes: process.memoryUsage.rss(), generation: this.#links.generation(), workCount: this.#workCount },
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async drain(): Promise<void> {
|
|
103
|
+
if (this.#cssRebuildTimer) {
|
|
104
|
+
// Only if css landed after the idle report; the replacement's boot build recompiles css, so nothing is lost.
|
|
105
|
+
clearTimeout(this.#cssRebuildTimer);
|
|
106
|
+
this.#cssRebuildTimer = null;
|
|
107
|
+
this.#pendingCssRebuild = null;
|
|
108
|
+
}
|
|
109
|
+
// The fast lane first: a save it is still handling may queue a batch in the slow one.
|
|
110
|
+
await this.#fastQueue.catch(() => undefined);
|
|
111
|
+
await this.#workQueue.drain();
|
|
112
|
+
await this.#cssRebuildQueue.catch(() => undefined);
|
|
113
|
+
while (this.#beside.size > 0) await Promise.all([...this.#beside]);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Voided so the fast lane need not wait; unhandled, a rejection would exit the builder and drop the watcher with it.
|
|
117
|
+
slowLaneFailed(label: string) {
|
|
118
|
+
return (error: unknown) =>
|
|
119
|
+
this.#logger.error(
|
|
120
|
+
`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
scheduleCssRebuild({ generation, changedFiles }: { generation?: number; changedFiles?: string[] }) {
|
|
125
|
+
this.#pendingCssRebuild = { generation, changedFiles };
|
|
126
|
+
if (this.#cssRebuildTimer) clearTimeout(this.#cssRebuildTimer);
|
|
127
|
+
this.#cssRebuildTimer = setTimeout(() => {
|
|
128
|
+
this.#cssRebuildTimer = null;
|
|
129
|
+
const next = this.#pendingCssRebuild;
|
|
130
|
+
this.#pendingCssRebuild = null;
|
|
131
|
+
if (!next) return;
|
|
132
|
+
this.#inFlight += 1;
|
|
133
|
+
this.#cssRebuildQueue = this.#cssRebuildQueue
|
|
134
|
+
.then(async () => {
|
|
135
|
+
await this.#links.runBatch({
|
|
136
|
+
generation: next.generation ?? this.#links.generation(),
|
|
137
|
+
needs: ["css"],
|
|
138
|
+
changedFiles: next.changedFiles ?? [],
|
|
139
|
+
});
|
|
140
|
+
})
|
|
141
|
+
.catch((err) => {
|
|
142
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
143
|
+
this.#logger.error(`css-rebuild failed: ${message}`);
|
|
144
|
+
sendBuildStatus("css", {
|
|
145
|
+
generation: next.generation,
|
|
146
|
+
ok: false,
|
|
147
|
+
files: next.changedFiles,
|
|
148
|
+
message,
|
|
149
|
+
});
|
|
150
|
+
})
|
|
151
|
+
.finally(() => {
|
|
152
|
+
this.#inFlight -= 1;
|
|
153
|
+
this.#reportMetrics();
|
|
154
|
+
});
|
|
155
|
+
}, 150);
|
|
156
|
+
}
|
|
157
|
+
}
|