@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
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { App } from "@akanjs/devkit/commandDecorators";
|
|
3
|
+
import type { PageRoot } from "@akanjs/devkit/executors";
|
|
4
|
+
import { AutoImportSync } from "@akanjs/devkit/frontendBuild/autoImportSync";
|
|
5
|
+
import { DevChangePlanner } from "@akanjs/devkit/frontendBuild/devChangePlanner";
|
|
6
|
+
import { DevGeneratedIndexSync } from "@akanjs/devkit/frontendBuild/devGeneratedIndexSync";
|
|
7
|
+
import { HmrWatcher } from "@akanjs/devkit/frontendBuild/hmrWatcher";
|
|
8
|
+
import { WatchRootResolver } from "@akanjs/devkit/frontendBuild/watchRootResolver";
|
|
9
|
+
import { CodegenLock } from "@akanjs/devkit/workspace/codegenLock";
|
|
10
|
+
import type { Logger } from "akanjs/common";
|
|
11
|
+
import type { ChangeBatch } from "akanjs/server";
|
|
12
|
+
import type { BuildBatchNeed } from "./buildBatchProtocol";
|
|
13
|
+
import { sendBuildStatus } from "./builderBuildStatus";
|
|
14
|
+
import { BuilderChannel } from "./builderChannel";
|
|
15
|
+
import type { BuilderGraphPayloads } from "./builderGraphPayloads";
|
|
16
|
+
import type { BuilderLanes } from "./builderLanes";
|
|
17
|
+
import type { BatchJob, DiscoveryJob } from "./builderWorkQueue";
|
|
18
|
+
import type { CsrRegistry } from "./csrRegistry";
|
|
19
|
+
import { prepareDevWatchBatch } from "./devWatchBatch";
|
|
20
|
+
import type { SsrRegistry } from "./ssrRegistry";
|
|
21
|
+
|
|
22
|
+
interface BuilderWatchParts {
|
|
23
|
+
logger: Logger;
|
|
24
|
+
lanes: BuilderLanes;
|
|
25
|
+
csr: CsrRegistry;
|
|
26
|
+
ssr: SsrRegistry;
|
|
27
|
+
graphPayloads: BuilderGraphPayloads;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface BuilderWatchLinks {
|
|
31
|
+
nextGeneration: () => number;
|
|
32
|
+
refreshDiscovery: (job: DiscoveryJob) => Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class BuilderWatch {
|
|
36
|
+
readonly #app: App;
|
|
37
|
+
readonly #logger: Logger;
|
|
38
|
+
readonly #lanes: BuilderLanes;
|
|
39
|
+
readonly #csr: CsrRegistry;
|
|
40
|
+
readonly #ssr: SsrRegistry;
|
|
41
|
+
readonly #graphPayloads: BuilderGraphPayloads;
|
|
42
|
+
readonly #links: BuilderWatchLinks;
|
|
43
|
+
#changePlanner: DevChangePlanner;
|
|
44
|
+
#generatedIndexSync: DevGeneratedIndexSync;
|
|
45
|
+
#autoImportSync: AutoImportSync;
|
|
46
|
+
#watcher: HmrWatcher | null = null;
|
|
47
|
+
#barrelFailed = false;
|
|
48
|
+
|
|
49
|
+
constructor(app: App, { logger, lanes, csr, ssr, graphPayloads }: BuilderWatchParts, links: BuilderWatchLinks) {
|
|
50
|
+
this.#app = app;
|
|
51
|
+
this.#logger = logger;
|
|
52
|
+
this.#lanes = lanes;
|
|
53
|
+
this.#csr = csr;
|
|
54
|
+
this.#ssr = ssr;
|
|
55
|
+
this.#graphPayloads = graphPayloads;
|
|
56
|
+
this.#links = links;
|
|
57
|
+
this.#changePlanner = new DevChangePlanner({ workspaceRoot: app.workspace.workspaceRoot });
|
|
58
|
+
this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: app.workspace.workspaceRoot });
|
|
59
|
+
this.#autoImportSync = new AutoImportSync({ workspaceRoot: app.workspace.workspaceRoot });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
stop(): void {
|
|
63
|
+
this.#watcher?.stop();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
//* Watch events carry real paths: synced lib pages match by `realDir`, their keys keep the `(libs)/(<lib>)` prefix.
|
|
67
|
+
static #matchPageRoot(roots: PageRoot[], abs: string): PageRoot | null {
|
|
68
|
+
for (const root of roots) {
|
|
69
|
+
const absRoot = path.resolve(root.realDir);
|
|
70
|
+
if (abs === absRoot || abs.startsWith(`${absRoot}${path.sep}`)) return root;
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
batchTouchesPagesTree(roots: PageRoot[], batch: ChangeBatch): boolean {
|
|
75
|
+
for (const f of batch.files) {
|
|
76
|
+
const abs = path.resolve(f);
|
|
77
|
+
if (!BuilderWatch.#matchPageRoot(roots, abs)) continue;
|
|
78
|
+
if (/\.(tsx|ts|jsx|js)$/.test(abs)) return true;
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
async batchMayChangePageKeys(roots: PageRoot[], batch: ChangeBatch): Promise<boolean> {
|
|
83
|
+
const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path.normalize(key)));
|
|
84
|
+
for (const f of batch.files) {
|
|
85
|
+
const abs = path.resolve(f);
|
|
86
|
+
const root = BuilderWatch.#matchPageRoot(roots, abs);
|
|
87
|
+
if (!root) continue;
|
|
88
|
+
if (!/\.(tsx|ts|jsx|js)$/.test(abs)) continue;
|
|
89
|
+
const rel = path.normalize(`${root.keyPrefix}${path.relative(path.resolve(root.realDir), abs)}`);
|
|
90
|
+
if (!(await Bun.file(abs).exists()) || !pageKeys.has(rel)) return true;
|
|
91
|
+
}
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
async installWatcher() {
|
|
95
|
+
const roots = await new WatchRootResolver(this.#app).resolve();
|
|
96
|
+
const watcher = new HmrWatcher({
|
|
97
|
+
roots,
|
|
98
|
+
logger: this.#logger,
|
|
99
|
+
onBatch: async (batch: ChangeBatch) => {
|
|
100
|
+
await this.#lanes.enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
await watcher.start();
|
|
104
|
+
this.#watcher = watcher;
|
|
105
|
+
this.#logger.verbose(`watching ${roots.length} roots`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async #handleWatchBatch(batch: ChangeBatch) {
|
|
109
|
+
this.#graphPayloads.touched(batch.files);
|
|
110
|
+
const rawKinds = new Set(batch.kinds);
|
|
111
|
+
if (rawKinds.size === 0) return;
|
|
112
|
+
const generation = this.#links.nextGeneration();
|
|
113
|
+
const trace = { ...batch.trace, batchAt: Date.now() };
|
|
114
|
+
//* Auto-import edits touch only this batch's files, so they rebuild in this same generation.
|
|
115
|
+
const [autoImport, indexSync] = await CodegenLock.run(
|
|
116
|
+
this.#app.workspace.workspaceRoot,
|
|
117
|
+
`hmr-batch:${this.#app.name}`,
|
|
118
|
+
async () => {
|
|
119
|
+
const auto = await this.#autoImportSync.syncForBatch(batch.files);
|
|
120
|
+
return [auto, await this.#generatedIndexSync.syncForBatch(batch.files)] as const;
|
|
121
|
+
},
|
|
122
|
+
);
|
|
123
|
+
for (const error of autoImport.errors) this.#logger.error(error);
|
|
124
|
+
if (autoImport.changedFiles.length > 0)
|
|
125
|
+
this.#logger.verbose(`[auto-import] inserted imports into ${autoImport.changedFiles.length} file(s)`);
|
|
126
|
+
//* Absorbed so the watcher's verification scan does not replay these writes as a user edit next generation.
|
|
127
|
+
await this.#watcher?.absorb([...autoImport.changedFiles, ...indexSync.changedFiles]);
|
|
128
|
+
const { files, kinds, expandedBatch, devPlan, event, hasSyncErrors } = prepareDevWatchBatch({
|
|
129
|
+
generation,
|
|
130
|
+
batch,
|
|
131
|
+
indexSync,
|
|
132
|
+
changePlanner: this.#changePlanner,
|
|
133
|
+
});
|
|
134
|
+
this.#logger.verbose(
|
|
135
|
+
`[hmr] batch generation=${generation} kinds=${kinds.join(",")} files=${files.length} generated=${indexSync.changedFiles.length} roles=${devPlan.roles.join(",") || "(none)"} actions=${devPlan.actions.join(",") || "(none)"}`,
|
|
136
|
+
);
|
|
137
|
+
for (const error of indexSync.errors) this.#logger.error(error);
|
|
138
|
+
|
|
139
|
+
// Invalidated in the slow lane, under the route builds that read it; a registry check reading it beside them caches
|
|
140
|
+
// nothing a walk began before the invalidation (the discovery's epoch).
|
|
141
|
+
const discovery = kinds.includes("code") ? { files, refresh: kinds.includes("config"), generation } : undefined;
|
|
142
|
+
|
|
143
|
+
if (hasSyncErrors) {
|
|
144
|
+
this.#barrelFailed = true;
|
|
145
|
+
sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join("\n") });
|
|
146
|
+
BuilderChannel.emit(event);
|
|
147
|
+
if (discovery)
|
|
148
|
+
void this.#lanes.workQueue
|
|
149
|
+
.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery))
|
|
150
|
+
.catch(this.#lanes.slowLaneFailed("discovery"));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
// After a failure too, where nothing changed on disk: the host re-sends a phase still failing to every new tab.
|
|
154
|
+
if (indexSync.changedFiles.length > 0 || this.#barrelFailed)
|
|
155
|
+
sendBuildStatus("barrel", { generation, ok: true, files });
|
|
156
|
+
this.#barrelFailed = false;
|
|
157
|
+
|
|
158
|
+
// Server-only generations skip the client: a fresh pages buildId would rsc-refresh browsers for no visible change.
|
|
159
|
+
const rebuildClient = devPlan.actions.includes("rebuild-client");
|
|
160
|
+
if (kinds.includes("code") && !rebuildClient) {
|
|
161
|
+
this.#logger.verbose(`client rebuild skipped; devPlan actions=${devPlan.actions.join(",") || "(none)"}`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const pageRoots = await this.#app.getPageRoots();
|
|
165
|
+
if (kinds.includes("code") && rebuildClient && (await this.batchMayChangePageKeys(pageRoots, expandedBatch))) {
|
|
166
|
+
const started = Date.now();
|
|
167
|
+
await this.#app.getPageKeys({ refresh: true });
|
|
168
|
+
this.#logger.verbose(`pageKeys updated, app pageKeys are refreshed (${Date.now() - started}ms)`);
|
|
169
|
+
} else if (kinds.includes("code") && rebuildClient && this.batchTouchesPagesTree(pageRoots, expandedBatch)) {
|
|
170
|
+
this.#logger.verbose("pageKeys refresh skipped; changed page source cannot add/remove a route key");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
BuilderChannel.emit(event);
|
|
174
|
+
|
|
175
|
+
if (kinds.includes("code") && rebuildClient) {
|
|
176
|
+
// Css rides the pages batch rather than its own debounce: the slow lane folds a burst of saves into one batch.
|
|
177
|
+
const needs: BuildBatchNeed[] = ["pages", "css"];
|
|
178
|
+
if (!this.#csr.csrActive)
|
|
179
|
+
this.#logger.verbose(
|
|
180
|
+
`csr-rebundle skipped; request /__csr or ?csr=true (or set AKAN_DEV_CSR_REBUILD=1) to enable per-save CSR rebuilds`,
|
|
181
|
+
);
|
|
182
|
+
//? One after the other, since two compiles side by side slow both. CSR goes first unless its build is being armed:
|
|
183
|
+
//? a CSR patch then waits behind #csrGate, which SSR tabs must not.
|
|
184
|
+
const patchCsr = async () => (this.#csr.csrActive ? await this.#csr.patchCsr(generation, files, trace) : false);
|
|
185
|
+
const patchSsr = async () => await this.#ssr.patchSsr(generation, files, trace);
|
|
186
|
+
let csrToWorker: boolean;
|
|
187
|
+
let ssrToWorker: boolean;
|
|
188
|
+
if (this.#csr.csrArming) {
|
|
189
|
+
ssrToWorker = await patchSsr();
|
|
190
|
+
csrToWorker = await patchCsr();
|
|
191
|
+
} else {
|
|
192
|
+
csrToWorker = await patchCsr();
|
|
193
|
+
ssrToWorker = await patchSsr();
|
|
194
|
+
}
|
|
195
|
+
if (csrToWorker) needs.unshift("csr");
|
|
196
|
+
if (ssrToWorker) needs.unshift("ssr");
|
|
197
|
+
const batch: BatchJob = { generation, needs, changedFiles: files, trace, ...(discovery ? { discovery } : {}) };
|
|
198
|
+
// A worker's registry build rewrites the directory its patcher reads, so the next save waits for it.
|
|
199
|
+
if (needs.includes("csr") || needs.includes("ssr")) await this.#lanes.workQueue.enqueueBatch(batch);
|
|
200
|
+
else void this.#lanes.workQueue.enqueueBatch(batch).catch(this.#lanes.slowLaneFailed("batch"));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (discovery)
|
|
204
|
+
void this.#lanes.workQueue
|
|
205
|
+
.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery))
|
|
206
|
+
.catch(this.#lanes.slowLaneFailed("discovery"));
|
|
207
|
+
// Css-only batches keep the debounce: they arrive in bursts while a stylesheet is edited.
|
|
208
|
+
if (kinds.includes("css")) {
|
|
209
|
+
this.#lanes.scheduleCssRebuild({ generation, changedFiles: files });
|
|
210
|
+
this.#logger.verbose(`css-rebuild scheduled generation=${generation}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ApplicationBuildReporter } from "@akanjs/devkit/app/applicationBuildReporter";
|
|
4
|
+
import type { App } from "@akanjs/devkit/commandDecorators";
|
|
5
|
+
import { CsrDevBundler } from "@akanjs/devkit/frontendBuild/csrDevBundler";
|
|
6
|
+
import { CsrDevPatcher } from "@akanjs/devkit/frontendBuild/csrDevPatcher";
|
|
7
|
+
import type { Logger } from "akanjs/common";
|
|
8
|
+
import type { BaseBuildArtifact, BuilderCsrReq, HmrTrace } from "akanjs/server";
|
|
9
|
+
import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
|
|
10
|
+
import type { BatchWork, BuildBatchRequest } from "./buildBatchProtocol";
|
|
11
|
+
import type { BuildBatchRunner } from "./buildBatchRunner";
|
|
12
|
+
import { isCompileError, sendBuildStatus } from "./builderBuildStatus";
|
|
13
|
+
import { BuilderChannel } from "./builderChannel";
|
|
14
|
+
import type { BuilderLanes } from "./builderLanes";
|
|
15
|
+
|
|
16
|
+
interface CsrRegistryLinks {
|
|
17
|
+
generation: () => number;
|
|
18
|
+
artifact: () => BaseBuildArtifact;
|
|
19
|
+
batchRequest: (work: BatchWork) => Promise<BuildBatchRequest>;
|
|
20
|
+
countDelegation: (registry: "csr" | "ssr", reason: string) => string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class CsrRegistry {
|
|
24
|
+
readonly #app: App;
|
|
25
|
+
readonly #logger: Logger;
|
|
26
|
+
readonly #lanes: BuilderLanes;
|
|
27
|
+
readonly #batchRunner: BuildBatchRunner;
|
|
28
|
+
readonly #links: CsrRegistryLinks;
|
|
29
|
+
#shellKey: string | null = null;
|
|
30
|
+
#csrActive = CsrRegistry.#csrArmedByEnv();
|
|
31
|
+
#csrBundler: CsrDevBundler;
|
|
32
|
+
/** Null when `AKAN_DEV_CSR_PATCHER=off`: every CSR save then goes to a build worker, as before the patcher. */
|
|
33
|
+
#patcher: CsrDevPatcher | null;
|
|
34
|
+
/** A worker's full CSR build (arming, re-arming) that a patch must not race for the csr-dev directory. */
|
|
35
|
+
#csrGate: Promise<void> = Promise.resolve();
|
|
36
|
+
#csrArming = false;
|
|
37
|
+
#csrArms = 0;
|
|
38
|
+
#csrWasActive = false;
|
|
39
|
+
#csrArmSucceeded = false;
|
|
40
|
+
|
|
41
|
+
constructor(
|
|
42
|
+
app: App,
|
|
43
|
+
{ logger, lanes, batchRunner }: { logger: Logger; lanes: BuilderLanes; batchRunner: BuildBatchRunner },
|
|
44
|
+
links: CsrRegistryLinks,
|
|
45
|
+
) {
|
|
46
|
+
this.#app = app;
|
|
47
|
+
this.#logger = logger;
|
|
48
|
+
this.#lanes = lanes;
|
|
49
|
+
this.#batchRunner = batchRunner;
|
|
50
|
+
this.#links = links;
|
|
51
|
+
this.#csrBundler = new CsrDevBundler(app);
|
|
52
|
+
this.#patcher =
|
|
53
|
+
process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get csrActive(): boolean {
|
|
57
|
+
return this.#csrActive;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
get csrArming(): boolean {
|
|
61
|
+
return this.#csrArming;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get patcher(): CsrDevPatcher | null {
|
|
65
|
+
return this.#patcher;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// True when the save has to go to a build worker: the patcher handed it back, or threw (the worker reports why).
|
|
69
|
+
async patchCsr(generation: number, files: string[], trace: HmrTrace): Promise<boolean> {
|
|
70
|
+
const patcher = this.#patcher;
|
|
71
|
+
if (!patcher) return true;
|
|
72
|
+
await this.#csrGate;
|
|
73
|
+
// The arming build this save waited for failed: CSR is off again, and the next request arms it anew.
|
|
74
|
+
if (!this.#csrActive) return false;
|
|
75
|
+
const started = Date.now();
|
|
76
|
+
const marker = path.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
|
|
77
|
+
await Bun.write(marker, String(process.pid));
|
|
78
|
+
try {
|
|
79
|
+
const result = await patcher.update(files, {
|
|
80
|
+
announce: (update) => {
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
BuilderChannel.emit({
|
|
83
|
+
type: "csr-updated",
|
|
84
|
+
data: {
|
|
85
|
+
generation: update.generation,
|
|
86
|
+
mode: "registry",
|
|
87
|
+
reload: update.reload,
|
|
88
|
+
reason: update.reason,
|
|
89
|
+
patchUrl: update.patchUrl,
|
|
90
|
+
changedIds: update.changedIds,
|
|
91
|
+
trace: { ...trace, patchAt: now, sentAt: now },
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
if (result.kind === "delegate") {
|
|
97
|
+
this.#logger.verbose(
|
|
98
|
+
`csr-patch handed to a build worker (${this.#links.countDelegation("csr", result.reason)}): ${result.reason}`,
|
|
99
|
+
);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
sendBuildStatus("csr", { generation, ok: true, files });
|
|
103
|
+
this.#logger.verbose(
|
|
104
|
+
result.kind === "unchanged"
|
|
105
|
+
? `csr-patch unchanged (${Date.now() - started}ms)`
|
|
106
|
+
: `csr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`,
|
|
107
|
+
);
|
|
108
|
+
return false;
|
|
109
|
+
} catch (err) {
|
|
110
|
+
const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
|
|
111
|
+
if (isCompileError(err)) {
|
|
112
|
+
sendBuildStatus("csr", { generation, ok: false, files, message });
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
|
|
116
|
+
patcher.forget();
|
|
117
|
+
return true;
|
|
118
|
+
} finally {
|
|
119
|
+
await rm(marker, { force: true });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// On demand: dev serves CSR only via the opt-in `/__csr` and `?csr=true` routes; once built, it rebuilds every save.
|
|
124
|
+
async handleBuildCsr(msg: BuilderCsrReq): Promise<void> {
|
|
125
|
+
if (msg.shell) {
|
|
126
|
+
await this.#buildShell(msg);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
//? Armed now, not when the build lands: a save handled meanwhile then patches CSR behind #csrGate instead of skipping.
|
|
130
|
+
this.#beginCsrArm();
|
|
131
|
+
this.#csrActive = true;
|
|
132
|
+
const armed = this.#lanes.workQueue.enqueue("build-csr", async (): Promise<void> => {
|
|
133
|
+
const started = Date.now();
|
|
134
|
+
let error: string | undefined;
|
|
135
|
+
try {
|
|
136
|
+
// Not relayed: an on-demand CSR build is request/response, and its error travels in the response.
|
|
137
|
+
const result = await this.#batchRunner.run(
|
|
138
|
+
await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }),
|
|
139
|
+
);
|
|
140
|
+
error = result.errors.csr;
|
|
141
|
+
} catch (err) {
|
|
142
|
+
error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
|
|
143
|
+
}
|
|
144
|
+
if (error) {
|
|
145
|
+
this.#logger.error(`csr-build failed: ${error}`);
|
|
146
|
+
await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
this.#csrArmSucceeded = true;
|
|
150
|
+
this.#patcher?.forget();
|
|
151
|
+
this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
|
|
152
|
+
await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
|
|
153
|
+
});
|
|
154
|
+
this.#csrGate = this.#armingCsr(armed);
|
|
155
|
+
await armed;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Asked on every view read and rebuilt only when a save moved the generation or the css it inlines, instead of armed
|
|
159
|
+
// per save: a restarted builder has no last build to trust, and so rebuilds once on the next read.
|
|
160
|
+
async #buildShell(msg: BuilderCsrReq): Promise<void> {
|
|
161
|
+
await this.#lanes.workQueue.enqueue("build-shell", async (): Promise<void> => {
|
|
162
|
+
const generation = this.#links.generation();
|
|
163
|
+
//? A save moves the generation before its css compile lands, so a shell built in between holds the old css.
|
|
164
|
+
const shellKey = `${generation}:${JSON.stringify(this.#links.artifact().cssAssets)}`;
|
|
165
|
+
let error: string | undefined;
|
|
166
|
+
if (this.#shellKey !== shellKey)
|
|
167
|
+
try {
|
|
168
|
+
const result = await this.#batchRunner.run(
|
|
169
|
+
await this.#links.batchRequest({ generation, needs: ["shell"], changedFiles: [] }),
|
|
170
|
+
);
|
|
171
|
+
error = result.errors.shell;
|
|
172
|
+
if (!error) this.#shellKey = shellKey;
|
|
173
|
+
} catch (err) {
|
|
174
|
+
error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
|
|
175
|
+
}
|
|
176
|
+
await BuilderChannel.send(
|
|
177
|
+
error
|
|
178
|
+
? { type: "build-csr-res", id: msg.id, ok: false, error }
|
|
179
|
+
: { type: "build-csr-res", id: msg.id, ok: true },
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
//? Settled by the last of the arming builds in flight, not by each: two requests that both fail would otherwise leave
|
|
185
|
+
//? CSR on (the second saw the first's optimistic flag as where it started), and the first to finish would let saves
|
|
186
|
+
//? patch CSR first while the second still builds.
|
|
187
|
+
#beginCsrArm(): void {
|
|
188
|
+
if (this.#csrArms === 0) {
|
|
189
|
+
this.#csrWasActive = this.#csrActive;
|
|
190
|
+
this.#csrArmSucceeded = false;
|
|
191
|
+
}
|
|
192
|
+
this.#csrArms += 1;
|
|
193
|
+
this.#csrArming = true;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
#armingCsr(armed: Promise<void>): Promise<void> {
|
|
197
|
+
const settle = () => {
|
|
198
|
+
this.#csrArms -= 1;
|
|
199
|
+
if (this.#csrArms > 0) return;
|
|
200
|
+
this.#csrArming = false;
|
|
201
|
+
this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
|
|
202
|
+
};
|
|
203
|
+
return armed.then(settle, settle);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
static #csrArmedByEnv() {
|
|
207
|
+
return process.env.AKAN_DEV_CSR_REBUILD === "1";
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The env flag carries an armed CSR session across builder restarts, so the replacement rebuilds it after ready.
|
|
211
|
+
async rearmCsrFromEnv(): Promise<void> {
|
|
212
|
+
if (!CsrRegistry.#csrArmedByEnv()) return;
|
|
213
|
+
this.#beginCsrArm();
|
|
214
|
+
this.#csrActive = true;
|
|
215
|
+
//? The env keeps CSR armed whatever this build does, as it did before the builder restarted.
|
|
216
|
+
this.#csrArmSucceeded = true;
|
|
217
|
+
const rearmed = this.#lanes.workQueue.enqueue("build-csr-rearm", async () => {
|
|
218
|
+
//? Relayed, unlike an on-demand build: a rebuild for a metadata save must reach the CSR tabs as their reload.
|
|
219
|
+
const result = await this.#batchRunner.run(
|
|
220
|
+
await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }),
|
|
221
|
+
(msg) => BuilderChannel.emit(msg),
|
|
222
|
+
);
|
|
223
|
+
this.#patcher?.forget();
|
|
224
|
+
if (result.errors.csr) this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
|
|
225
|
+
else this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
|
|
226
|
+
});
|
|
227
|
+
this.#csrGate = this.#armingCsr(rearmed);
|
|
228
|
+
await rearmed.catch((err: unknown) =>
|
|
229
|
+
this.#logger.error(
|
|
230
|
+
`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
|
|
231
|
+
),
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -20,9 +20,11 @@ describe("incremental builder process", () => {
|
|
|
20
20
|
const { root } = track(await createTempApp("demo"));
|
|
21
21
|
const appDir = path.join(root, "apps/demo");
|
|
22
22
|
// The batch runner looks under the workspace root first: a stand-in for the boot build, which needs a whole app.
|
|
23
|
+
// Each stand-in waits for the runner's release, as the real worker does: one exiting at once can lose all it sent.
|
|
23
24
|
await writeText(
|
|
24
25
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
25
26
|
`const { generation } = JSON.parse(process.argv[2]);
|
|
27
|
+
process.once("disconnect", () => {});
|
|
26
28
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
27
29
|
`,
|
|
28
30
|
);
|
|
@@ -90,6 +92,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
|
|
|
90
92
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
91
93
|
`const { generation, needs } = JSON.parse(process.argv[2]);
|
|
92
94
|
const errors = needs.includes("base") ? {} : { shell: "handed " + needs.join(",") };
|
|
95
|
+
process.once("disconnect", () => {});
|
|
93
96
|
process.send({ type: "build-batch-result", data: { generation, errors, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
94
97
|
`,
|
|
95
98
|
);
|
|
@@ -135,6 +138,7 @@ process.send({ type: "build-batch-result", data: { generation, errors, artifact:
|
|
|
135
138
|
await writeText(
|
|
136
139
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
137
140
|
`const { generation } = JSON.parse(process.argv[2]);
|
|
141
|
+
process.once("disconnect", () => {});
|
|
138
142
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
139
143
|
`,
|
|
140
144
|
);
|
|
@@ -237,6 +241,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
|
|
|
237
241
|
await writeText(
|
|
238
242
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
239
243
|
`const { generation } = JSON.parse(process.argv[2]);
|
|
244
|
+
process.once("disconnect", () => {});
|
|
240
245
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
241
246
|
`,
|
|
242
247
|
);
|
|
@@ -299,6 +304,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
|
|
|
299
304
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
300
305
|
`const { generation, needs } = JSON.parse(process.argv[2]);
|
|
301
306
|
require("node:fs").appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + "\\n");
|
|
307
|
+
process.once("disconnect", () => {});
|
|
302
308
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
303
309
|
`,
|
|
304
310
|
);
|
|
@@ -357,6 +363,7 @@ process.on("disconnect", orphaned);
|
|
|
357
363
|
const deadline = Date.now() + 15_000;
|
|
358
364
|
if (needs.includes("ssr")) while (!fs.existsSync(${JSON.stringify(gate)}) && Date.now() < deadline) await Bun.sleep(20);
|
|
359
365
|
const css = needs.includes("ssr") ? { cssAssets: ${JSON.stringify(landed)} } : {};
|
|
366
|
+
process.once("disconnect", () => {});
|
|
360
367
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] }, ...css } });
|
|
361
368
|
process.off("disconnect", orphaned);
|
|
362
369
|
`,
|
|
@@ -417,6 +424,7 @@ if (needs.includes("ssr")) {
|
|
|
417
424
|
fs.appendFileSync(${JSON.stringify(runs)}, Date.now() + "\\n");
|
|
418
425
|
if (fs.readFileSync(${JSON.stringify(runs)}, "utf8").trim().split("\\n").length <= 2) process.exit(1);
|
|
419
426
|
}
|
|
427
|
+
process.once("disconnect", () => {});
|
|
420
428
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
421
429
|
`,
|
|
422
430
|
);
|
|
@@ -483,6 +491,7 @@ if (needs.includes("ssr")) {
|
|
|
483
491
|
fs.appendFileSync(${JSON.stringify(runs)}, Date.now() + "\\n");
|
|
484
492
|
if (fs.readFileSync(${JSON.stringify(runs)}, "utf8").trim().split("\\n").length === 2) process.exit(1);
|
|
485
493
|
}
|
|
494
|
+
process.once("disconnect", () => {});
|
|
486
495
|
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
487
496
|
`,
|
|
488
497
|
);
|
|
@@ -539,7 +548,10 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
|
|
|
539
548
|
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
540
549
|
`const { generation, needs } = JSON.parse(process.argv[2]);
|
|
541
550
|
if (needs.includes("ssr")) await import(${JSON.stringify(path.join(import.meta.dir, "buildBatch.proc.ts"))});
|
|
542
|
-
else
|
|
551
|
+
else {
|
|
552
|
+
process.once("disconnect", () => {});
|
|
553
|
+
process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
554
|
+
}
|
|
543
555
|
`,
|
|
544
556
|
);
|
|
545
557
|
await writeText(path.join(appDir, "env/env.client.ts"), "export const env = {} as const;\n");
|
|
@@ -588,4 +600,83 @@ else process.send({ type: "build-batch-result", data: { generation, errors: {},
|
|
|
588
600
|
await proc.exited;
|
|
589
601
|
}
|
|
590
602
|
}, 60_000);
|
|
603
|
+
|
|
604
|
+
test("a failed boot build waits for the save that fixes it, and the builder it recovers continues the generation and watches", async () => {
|
|
605
|
+
const { root } = track(await createTempApp("demo"));
|
|
606
|
+
const appDir = path.join(root, "apps/demo");
|
|
607
|
+
const ledger = path.join(root, "batches.log");
|
|
608
|
+
const fixed = path.join(root, "boot-fixed");
|
|
609
|
+
// A stand-in batch: the boot build fails until the fix lands, and every batch logs its needs and generation.
|
|
610
|
+
await writeText(
|
|
611
|
+
path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
|
|
612
|
+
`import fs from "node:fs";
|
|
613
|
+
const { generation, needs } = JSON.parse(process.argv[2]);
|
|
614
|
+
fs.appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + " " + generation + "\\n");
|
|
615
|
+
const errors = needs.includes("base") && !fs.existsSync(${JSON.stringify(fixed)}) ? { base: "the boot is broken" } : {};
|
|
616
|
+
process.once("disconnect", () => {});
|
|
617
|
+
process.send({ type: "build-batch-result", data: { generation, errors, artifact: {}, optimizedFonts: { css: "", files: [] } } });
|
|
618
|
+
`,
|
|
619
|
+
);
|
|
620
|
+
const page = path.join(appDir, "page/_index.tsx");
|
|
621
|
+
await writeText(page, "export default () => null;\n");
|
|
622
|
+
const messages: BuilderMessage[] = [];
|
|
623
|
+
const proc = Bun.spawn(["bun", path.join(import.meta.dir, "incrementalBuilder.proc.ts")], {
|
|
624
|
+
cwd: appDir,
|
|
625
|
+
env: {
|
|
626
|
+
...process.env,
|
|
627
|
+
AKAN_WORKSPACE_ROOT: root,
|
|
628
|
+
AKAN_PUBLIC_APP_NAME: "demo",
|
|
629
|
+
AKAN_PUBLIC_REPO_NAME: "repo",
|
|
630
|
+
AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
|
|
631
|
+
AKAN_PUBLIC_ENV: "local",
|
|
632
|
+
AKAN_BUILDER_INITIAL_GENERATION: "5",
|
|
633
|
+
AKAN_DEV_CSR_PATCHER: "off",
|
|
634
|
+
AKAN_LOG_STDOUT_LEVEL: "info",
|
|
635
|
+
},
|
|
636
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
637
|
+
serialization: "advanced",
|
|
638
|
+
ipc: (message: BuilderMessage) => {
|
|
639
|
+
messages.push(message);
|
|
640
|
+
},
|
|
641
|
+
});
|
|
642
|
+
let stdout = "";
|
|
643
|
+
const decoder = new TextDecoder();
|
|
644
|
+
const reading = (async () => {
|
|
645
|
+
for await (const chunk of proc.stdout) stdout += decoder.decode(chunk, { stream: true });
|
|
646
|
+
})();
|
|
647
|
+
const sent = (type: BuilderMessage["type"]) => messages.filter((message) => message.type === type);
|
|
648
|
+
try {
|
|
649
|
+
await until(proc, "boot-armed", () => sent("boot-armed").length === 1);
|
|
650
|
+
proc.send({ type: "build-graph", id: 1 } satisfies BuilderMessage);
|
|
651
|
+
await until(proc, "build-graph-res", () => sent("build-graph-res").length === 1);
|
|
652
|
+
//? Degraded mode sends boot-armed before its watcher starts, and a save made before then is never seen.
|
|
653
|
+
await until(proc, "the degraded watcher's log line", () => stdout.includes("[degraded] watching"));
|
|
654
|
+
await writeText(fixed, "");
|
|
655
|
+
await writeText(page, "export default () => 1;\n");
|
|
656
|
+
await until(proc, "the recovered builder's boot-armed", () => sent("boot-armed").length === 2);
|
|
657
|
+
await writeText(page, "export default () => 2;\n");
|
|
658
|
+
await until(proc, "the recovered builder's invalidate", () =>
|
|
659
|
+
messages.some((message) => message.type === "invalidate" && message.generation === 9),
|
|
660
|
+
);
|
|
661
|
+
} finally {
|
|
662
|
+
proc.kill();
|
|
663
|
+
await proc.exited;
|
|
664
|
+
await reading;
|
|
665
|
+
}
|
|
666
|
+
expect(sent("build-status")[0]).toMatchObject({
|
|
667
|
+
data: { generation: 6, phase: "pages", ok: false, message: "Boot build failed: the boot is broken" },
|
|
668
|
+
});
|
|
669
|
+
expect(sent("build-graph-res")[0]).toMatchObject({
|
|
670
|
+
id: 1,
|
|
671
|
+
ok: false,
|
|
672
|
+
error: expect.stringContaining("recovering from a failed boot build"),
|
|
673
|
+
});
|
|
674
|
+
expect(sent("builder-ready")).toHaveLength(2);
|
|
675
|
+
expect((await Bun.file(ledger).text()).trim().split("\n").slice(0, 4)).toEqual([
|
|
676
|
+
"base 0",
|
|
677
|
+
"base 0",
|
|
678
|
+
"pages,css 8",
|
|
679
|
+
"ssr 8",
|
|
680
|
+
]);
|
|
681
|
+
}, 60_000);
|
|
591
682
|
});
|