@akanjs/cli 3.2.0-rc.8 → 3.2.0

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.
Files changed (143) hide show
  1. package/.build-stamp +2 -2
  2. package/CodeAgent-fx6088tv.js +11 -0
  3. package/{CodeTui-qstk5vpj.js → CodeTui-zee8atsr.js} +822 -666
  4. package/README.ko.md +7 -0
  5. package/README.md +7 -0
  6. package/TunnelShare-9ry4vh0y.js +18 -0
  7. package/agent.command-x65f2ags.js +61 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-79azsb2w.js +11 -0
  10. package/{application.command-m4rq4wc2.js → application.command-azbd1pb2.js} +83 -37
  11. package/{applicationBuildRunner-df7rx3ra.js → applicationBuildRunner-trfxv3pd.js} +49 -18
  12. package/buildBatch.proc.js +25 -11
  13. package/{cloud.command-a0gy0qq2.js → cloud.command-gapp4634.js} +33 -29
  14. package/cloud.script-3b401efv.js +35 -0
  15. package/{code.command-5rsdqw8s.js → code.command-5smx61yf.js} +13 -9
  16. package/context.command-ym5jbkny.js +64 -0
  17. package/context.runner-kctbfsde.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-h77zrjv5.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-mffxknbr.js → guideline.command-zwypaqsh.js} +9 -5
  22. package/guidelines/agentRule/agentRule.instruction.md +25 -9
  23. package/guidelines/akanApi/akanApi.instruction.md +6 -4
  24. package/guidelines/conventions/core.md +23 -5
  25. package/guidelines/conventions/rules/app.md +4 -1
  26. package/guidelines/conventions/rules/page.md +5 -4
  27. package/guidelines/conventions/rules/ts.md +3 -3
  28. package/guidelines/errorCodes/errorCodes.instruction.md +165 -0
  29. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  30. package/guidelines/mcpRule/mcpRule.instruction.md +225 -5
  31. package/guidelines/pageRule/pageRule.instruction.md +10 -1
  32. package/guidelines/queryRule/queryRule.instruction.md +3 -1
  33. package/guidelines/runtimeRule/runtimeRule.instruction.md +14 -8
  34. package/guidelines/transportRule/transportRule.instruction.md +31 -1
  35. package/incrementalBuilder.proc.js +577 -411
  36. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  37. package/{index-0gg15zwa.js → index-0s7w2085.js} +6 -6
  38. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  39. package/{index-swwjakt0.js → index-275a4r3n.js} +11 -11
  40. package/{index-j6gc8n14.js → index-2jmvfa62.js} +11 -9
  41. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  42. package/{index-exn38bzx.js → index-2yn3r67f.js} +116 -54
  43. package/{index-34792nh7.js → index-3txdtztz.js} +1 -1
  44. package/{index-28x1aszt.js → index-41a03gkj.js} +149 -53
  45. package/{index-2mf1aen9.js → index-4ss4gkv3.js} +2 -2
  46. package/{index-an76bdrv.js → index-612fdtbk.js} +1 -1
  47. package/{index-5radqwn2.js → index-67sd09ag.js} +12 -12
  48. package/{index-0hbtve0a.js → index-6dzjer7p.js} +32 -28
  49. package/{index-3ghdb7p5.js → index-71y6176j.js} +2777 -3676
  50. package/{index-xyn02k0w.js → index-78y75t0a.js} +662 -433
  51. package/index-7wf8snar.js +80 -0
  52. package/{index-skmtj8rm.js → index-8jtqfye2.js} +27 -10
  53. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  54. package/{index-nmvhjn8c.js → index-9wh04mqy.js} +93 -82
  55. package/{index-xvk2a75m.js → index-a860mx0m.js} +3 -3
  56. package/{index-5zwr4n6k.js → index-baccvws5.js} +65 -8
  57. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  58. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  59. package/{index-r0a604h4.js → index-c669pbyb.js} +5 -4
  60. package/{index-x40bdsca.js → index-dadwp2aw.js} +33 -98
  61. package/{index-vm0dn0mt.js → index-dmcpetwe.js} +200 -138
  62. package/{index-43f4h4cm.js → index-ebn9kgea.js} +6 -6
  63. package/{index-hqv34wzq.js → index-gt8phqpt.js} +10 -10
  64. package/{index-yckz5t8b.js → index-h901f24n.js} +516 -434
  65. package/{index-j3v29pq7.js → index-j0wr4e32.js} +219 -175
  66. package/{index-gcx48get.js → index-j592zfqc.js} +2 -2
  67. package/{index-grxs6fts.js → index-j6jjmn2r.js} +57 -31
  68. package/{index-w8yasvpc.js → index-jek2re5k.js} +2136 -2175
  69. package/{index-ny2k80mv.js → index-jf4vk1s0.js} +9 -2
  70. package/{index-gxav1bjz.js → index-k6vwww45.js} +9 -9
  71. package/{index-99qvtff2.js → index-kfvjzk8r.js} +5 -5
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2r9ff9qm.js → index-nc3br31y.js} +2 -2
  74. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  75. package/{index-cmg5ngqa.js → index-p7beqww9.js} +2 -2
  76. package/{index-b4qq3rq0.js → index-rwgqba9p.js} +1 -1
  77. package/{index-rfzp4pqs.js → index-s885g0jj.js} +3 -3
  78. package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
  79. package/{index-k92x3vne.js → index-v7ajmsh3.js} +1 -1
  80. package/index-w1zexzpx.js +127 -0
  81. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  82. package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
  83. package/{index-rp4yf32g.js → index-xwwex8rf.js} +36 -29
  84. package/{index-ra9fvn7s.js → index-ybcb9wc8.js} +74 -38
  85. package/index-z92zm3wd.js +788 -0
  86. package/{index-j9790rhk.js → index-z96ks033.js} +1509 -1121
  87. package/index-zfnz878d.js +30 -0
  88. package/{index-2vgv7fs7.js → index-zmd9xxgd.js} +727 -693
  89. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  90. package/index.js +28 -24
  91. package/libExecutor-jc6f8hm6.js +10 -0
  92. package/{library.command-bmd7zc5m.js → library.command-nxvesvhb.js} +12 -5
  93. package/{localRegistry.command-y6en1599.js → localRegistry.command-xz62e4ng.js} +29 -24
  94. package/{module.command-7exfffqw.js → module.command-aaws9byg.js} +11 -7
  95. package/{package.command-adskw2rj.js → package.command-j7hv26p0.js} +14 -10
  96. package/package.json +8 -8
  97. package/{page.command-dw01272p.js → page.command-7yffs7n9.js} +8 -4
  98. package/{pipeline.command-0b1r3y5r.js → pipeline.command-7yk0zcng.js} +15 -9
  99. package/pkgExecutor-arxmvx4t.js +10 -0
  100. package/{primitive.command-byw6vc04.js → primitive.command-7a1pt715.js} +12 -8
  101. package/{projectTypecheck-kkrpq60a.js → projectTypecheck-f4qhbecd.js} +1 -1
  102. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  103. package/{quality.command-6rqnhzct.js → quality.command-c6mvrjh1.js} +25 -16
  104. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  105. package/{repair.command-rw5zymak.js → repair.command-093adzt9.js} +12 -8
  106. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  107. package/{scalar.command-2dyp9nh9.js → scalar.command-2ex84spb.js} +10 -6
  108. package/skills/akan-debug/SKILL.md +8 -5
  109. package/skills/akan-err/SKILL.md +7 -0
  110. package/skills/akan-mcp/SKILL.md +19 -1
  111. package/skills/akan-scaffold/SKILL.md +1 -1
  112. package/skills/akan-validate/SKILL.md +3 -3
  113. package/{subspace.command-111ynwv1.js → subspace.command-4n4n4jpv.js} +32 -24
  114. package/templates/app/page/_layout.tsx +13 -0
  115. package/templates/app/page/styles.css.template +40 -0
  116. package/templates/appSample/page/_index.tsx +9 -9
  117. package/templates/appSample/page/_layout.tsx +1 -0
  118. package/templates/appSample/page/styles.css.template +40 -5
  119. package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
  120. package/templates/biomeForm.ts +1 -1
  121. package/templates/env/_env.server.type.ts +1 -1
  122. package/templates/facetIndex/index.ts +2 -37
  123. package/templates/lib/sig.ts +0 -4
  124. package/templates/lib/useClient.ts +1 -1
  125. package/templates/workspaceRoot/.devcontainer/devcontainer.json.template +1 -1
  126. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  127. package/templates/workspaceRoot/README.ts +4 -2
  128. package/{tunnel.command-2gcpfbdj.js → tunnel.command-f7ep1qfa.js} +17 -13
  129. package/{typeChecker-s640r6c0.js → typeChecker-7jt6abrs.js} +1 -1
  130. package/typecheck.proc.js +3 -2
  131. package/{verify.command-djgs86ma.js → verify.command-zrkxnvct.js} +21 -17
  132. package/{workflow.command-n0k2mxr5.js → workflow.command-ks16jegk.js} +21 -14
  133. package/{workspace.command-fh1qwxfx.js → workspace.command-ahhfpaag.js} +60 -54
  134. package/CodeAgent-x2p3a3e0.js +0 -11
  135. package/TunnelShare-c4xsfzg5.js +0 -15
  136. package/agent.command-9et2e27p.js +0 -52
  137. package/cloud.script-xze4zh7n.js +0 -31
  138. package/context.command-rk1dwrg4.js +0 -57
  139. package/context.runner-83ky5m1b.js +0 -30
  140. /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
  141. /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
  142. /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
  143. /package/templates/{appSample → app}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
@@ -3,14 +3,21 @@ import {
3
3
  HmrWatcher,
4
4
  WatchRootResolver,
5
5
  ApplicationBuildReporter
6
- } from "./index-vm0dn0mt.js";
6
+ } from "./index-dmcpetwe.js";
7
7
  import {
8
8
  CodegenLock,
9
- WorkspaceExecutor,
10
- AppExecutor
11
- } from "./index-3ghdb7p5.js";
12
- import"./index-bns3wcpc.js";
9
+ WorkspaceExecutor
10
+ } from "./index-71y6176j.js";
11
+ import"./index-by2tvsq6.js";
13
12
  import"./index-j4yvgfhr.js";
13
+ import {
14
+ AppExecutor2
15
+ } from "./index-z92zm3wd.js";
16
+ import"./index-zfnz878d.js";
17
+ import"./index-w1zexzpx.js";
18
+ import {
19
+ ServerGraphFile
20
+ } from "./index-9wh04mqy.js";
14
21
  import {
15
22
  GraphClientEntryDiscovery,
16
23
  RouteClientBuilder,
@@ -20,35 +27,32 @@ import {
20
27
  DevChangePlanner,
21
28
  DevGeneratedIndexSync,
22
29
  SsrDevBundler
23
- } from "./index-w8yasvpc.js";
24
- import {
25
- ServerGraphFile
26
- } from "./index-nmvhjn8c.js";
27
- import"./index-9p260r4e.js";
30
+ } from "./index-jek2re5k.js";
31
+ import"./index-trffs83s.js";
28
32
  import {
29
33
  FrameworkGraph
30
- } from "./index-cmg5ngqa.js";
34
+ } from "./index-p7beqww9.js";
31
35
  import {
32
36
  GitRevision
33
- } from "./index-ygdbn9jn.js";
37
+ } from "./index-zyb0ebm4.js";
34
38
  import {
35
39
  WorkspaceGraph
36
- } from "./index-39jz41jb.js";
40
+ } from "./index-xs9a3ddt.js";
37
41
  import {
38
42
  prepareDevWatchBatch
39
43
  } from "./index-a5vmm6x4.js";
44
+ import"./index-7wf8snar.js";
40
45
 
41
46
  // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
42
- import { rm } from "fs/promises";
43
- import path2 from "path";
47
+ import path6 from "path";
44
48
  import { Logger as Logger2 } from "akanjs/common";
45
- import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
46
49
 
47
50
  // pkgs/@akanjs/devkit/incrementalBuilder/buildBatchRunner.ts
48
51
  import path from "path";
49
52
  import { Logger } from "akanjs/common";
50
53
 
51
54
  class BuildBatchRunner {
55
+ static #exitGraceMs = 500;
52
56
  #logger = new Logger("BuildBatchRunner");
53
57
  #entry = null;
54
58
  #workspaceRoot;
@@ -80,6 +84,7 @@ class BuildBatchRunner {
80
84
  const started = Date.now();
81
85
  const entry = await this.#resolveEntry();
82
86
  let result = null;
87
+ const resultArrived = Promise.withResolvers();
83
88
  const reported = new Map;
84
89
  const payload = request.trace ? { ...request, trace: { ...request.trace, spawnAt: Date.now() } } : request;
85
90
  const proc = Bun.spawn(["bun", entry, JSON.stringify(payload)], {
@@ -87,19 +92,26 @@ class BuildBatchRunner {
87
92
  env: process.env,
88
93
  stdio: ["ignore", "inherit", "inherit"],
89
94
  serialization: "advanced",
90
- ipc: (message) => {
95
+ ipc: (message, worker) => {
91
96
  if (!message || typeof message !== "object")
92
97
  return;
93
- if (message.type === "build-batch-result")
98
+ if (message.type === "build-batch-result") {
94
99
  result = message.data;
95
- else {
100
+ worker.disconnect();
101
+ const lingering = setTimeout(() => {
102
+ this.#logger.verbose(`[build-batch] worker still up ${BuildBatchRunner.#exitGraceMs}ms after its result`);
103
+ worker.kill("SIGKILL");
104
+ }, BuildBatchRunner.#exitGraceMs);
105
+ worker.exited.then(() => clearTimeout(lingering));
106
+ resultArrived.resolve(null);
107
+ } else {
96
108
  if (message.type === "build-status")
97
109
  reported.set(message.data.phase, message.data.message);
98
110
  onMessage(message);
99
111
  }
100
112
  }
101
113
  });
102
- const exitCode = await proc.exited;
114
+ const exitCode = await Promise.race([proc.exited, resultArrived.promise]);
103
115
  if (result) {
104
116
  this.#logger.verbose(`[build-batch] generation=${request.generation} needs=${request.needs.join(",")} done in ${Date.now() - started}ms`);
105
117
  return result;
@@ -117,6 +129,9 @@ class BuildBatchRunner {
117
129
  }
118
130
  }
119
131
 
132
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBoot.ts
133
+ import path2 from "path";
134
+
120
135
  // pkgs/@akanjs/devkit/incrementalBuilder/builderChannel.ts
121
136
  class BuilderChannel {
122
137
  static #flushTimeoutMs = 5000;
@@ -139,6 +154,15 @@ class BuilderChannel {
139
154
  static emit(message) {
140
155
  BuilderChannel.send(message);
141
156
  }
157
+ static async announceReady(logger) {
158
+ const gate = process.env.AKAN_DEV_BUILDER_READY_GATE;
159
+ if (gate && !await Bun.file(gate).exists()) {
160
+ logger.warn(`AKAN_DEV_BUILDER_READY_GATE is set: holding builder-ready until ${gate} exists`);
161
+ while (!await Bun.file(gate).exists())
162
+ await Bun.sleep(100);
163
+ }
164
+ BuilderChannel.emit({ type: "builder-ready" });
165
+ }
142
166
  static async drain() {
143
167
  let flushed = 0;
144
168
  while (BuilderChannel.#flushing.size) {
@@ -150,6 +174,93 @@ class BuilderChannel {
150
174
  }
151
175
  }
152
176
 
177
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBoot.ts
178
+ class BuilderBoot {
179
+ static async buildBootDeps(app, runner) {
180
+ const result = await runner.run({
181
+ appName: app.name,
182
+ workspaceRoot: app.workspace.workspaceRoot,
183
+ repoName: app.workspace.repoName,
184
+ generation: 0,
185
+ needs: ["base"],
186
+ changedFiles: [],
187
+ pageKeys: null,
188
+ optimizedFonts: null,
189
+ cssAssets: null,
190
+ artifactDir: path2.resolve(`${app.cwdPath}/.akan/artifact`)
191
+ });
192
+ if (result.errors.base)
193
+ throw new Error(result.errors.base);
194
+ if (!result.artifact || !result.optimizedFonts)
195
+ throw new Error("boot build reported success without an artifact; the build worker likely died");
196
+ const discovery = await GraphClientEntryDiscovery.create(app);
197
+ return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
198
+ }
199
+ static recoverBoot(app, bootError, logger, runner, initialGeneration, create) {
200
+ const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
201
+ logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
202
+ let generation = initialGeneration;
203
+ const sendFailure = (files, message) => {
204
+ BuilderChannel.emit({
205
+ type: "build-status",
206
+ data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` }
207
+ });
208
+ };
209
+ sendFailure([], firstMessage);
210
+ BuilderChannel.emit({ type: "builder-ready" });
211
+ BuilderChannel.emit({ type: "boot-armed" });
212
+ return new Promise((resolve, reject) => {
213
+ (async () => {
214
+ const roots = await new WatchRootResolver(app).resolve();
215
+ const watcher = new HmrWatcher({
216
+ roots,
217
+ logger,
218
+ onBatch: async (batch) => {
219
+ generation += 1;
220
+ const files = [...batch.files].sort();
221
+ try {
222
+ if (new Set(batch.kinds).has("config"))
223
+ await app.getConfig({ refresh: true });
224
+ const deps = await BuilderBoot.buildBootDeps(app, runner);
225
+ const builder = create({ app, watch: true, initialGeneration: generation, ...deps });
226
+ watcher.stop();
227
+ logger.info(`boot build recovered generation=${generation}`);
228
+ resolve({ builder, changedFiles: files });
229
+ } catch (err) {
230
+ const message = err instanceof Error ? err.message : String(err);
231
+ logger.error(`boot build retry failed: ${message}`);
232
+ sendFailure(files, message);
233
+ }
234
+ }
235
+ });
236
+ await watcher.start();
237
+ logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
238
+ })().catch(reject);
239
+ });
240
+ }
241
+ static initialGeneration() {
242
+ const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
243
+ return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
244
+ }
245
+ }
246
+
247
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBuildStatus.ts
248
+ var sendBuildStatus = (phase, {
249
+ generation,
250
+ ok,
251
+ files,
252
+ message,
253
+ scope
254
+ }) => {
255
+ if (typeof generation !== "number")
256
+ return;
257
+ BuilderChannel.emit({
258
+ type: "build-status",
259
+ data: { generation, phase, ok, files: files ?? [], message, ...scope !== undefined ? { scope } : {} }
260
+ });
261
+ };
262
+ var isCompileError = (error) => error instanceof AggregateError;
263
+
153
264
  // pkgs/@akanjs/devkit/incrementalBuilder/builderGraphPayloads.ts
154
265
  class BuilderGraphPayloads {
155
266
  #app;
@@ -287,43 +398,12 @@ class BuilderWorkQueue {
287
398
  }
288
399
  }
289
400
 
290
- // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
291
- class IncrementalBuilder {
292
- #logger = new Logger2("IncrementalBuilder");
401
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderLanes.ts
402
+ class BuilderLanes {
293
403
  #app;
294
- #artifact;
295
- #watch;
296
- #optimizedFonts;
297
- #discovery;
298
- #batchRunner;
299
- #changePlanner;
300
- #generatedIndexSync;
301
- #autoImportSync;
302
- #watcher = null;
303
- #generation = 0;
304
- #shellKey = null;
305
- #graphPayloads;
306
- #discoveredThrough = 0;
307
- #csrActive = IncrementalBuilder.#csrArmedByEnv();
308
- #csrBundler;
309
- #patcher;
310
- #csrGate = Promise.resolve();
311
- #csrArming = false;
312
- #csrArms = 0;
313
- #crashRetryTimer = null;
314
- #crashRetryEntries = new Set;
315
- #csrWasActive = false;
316
- #csrArmSucceeded = false;
317
- #ssrBundler;
318
- #ssrPatcher;
319
- #ssrLock = Promise.resolve();
320
- #delegations = new Map;
321
- #ssrArming = null;
322
- #ssrBroken = false;
323
- #ssrCrashedAt = null;
324
- static #crashRetryMs = 1e4;
404
+ #logger;
405
+ #links;
325
406
  #beside = new Set;
326
- #barrelFailed = false;
327
407
  #fastQueue = Promise.resolve();
328
408
  #workQueue;
329
409
  #inFlight = 0;
@@ -332,28 +412,12 @@ class IncrementalBuilder {
332
412
  #cssRebuildQueue = Promise.resolve();
333
413
  #cssRebuildTimer = null;
334
414
  #pendingCssRebuild = null;
335
- constructor(options) {
336
- this.#app = options.app;
337
- this.#artifact = options.artifact;
338
- this.#watch = options.watch;
339
- this.#optimizedFonts = options.optimizedFonts;
340
- this.#discovery = options.discovery;
341
- this.#generation = options.initialGeneration ?? 0;
342
- this.#discoveredThrough = this.#generation;
343
- this.#graphPayloads = new BuilderGraphPayloads(options.app, () => this.#generation);
344
- this.#batchRunner = new BuildBatchRunner({
345
- workspaceRoot: options.app.workspace.workspaceRoot,
346
- cwd: options.app.cwdPath
347
- });
348
- this.#changePlanner = new DevChangePlanner({ workspaceRoot: options.app.workspace.workspaceRoot });
349
- this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: options.app.workspace.workspaceRoot });
350
- this.#autoImportSync = new AutoImportSync({ workspaceRoot: options.app.workspace.workspaceRoot });
351
- this.#csrBundler = new CsrDevBundler(options.app);
352
- this.#patcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
353
- this.#ssrBundler = new SsrDevBundler(options.app, { discovery: () => this.#discovery });
354
- this.#ssrPatcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
415
+ constructor(app, { logger }, links) {
416
+ this.#app = app;
417
+ this.#logger = logger;
418
+ this.#links = links;
355
419
  this.#workQueue = new BuilderWorkQueue({
356
- runBatch: async (batch) => await this.#runQueuedBatch(batch),
420
+ runBatch: async (batch) => await this.#links.runQueuedBatch(batch),
357
421
  onSettled: (label, ms) => {
358
422
  this.#workCount += 1;
359
423
  this.#logger.verbose(`[work-queue] ${label} finished in ${ms}ms`);
@@ -361,72 +425,19 @@ class IncrementalBuilder {
361
425
  }
362
426
  });
363
427
  }
364
- get #artifactDir() {
365
- return `${this.#app.cwdPath}/.akan/artifact`;
428
+ get workQueue() {
429
+ return this.#workQueue;
366
430
  }
367
- async handleBuildRoute(msg) {
368
- await this.#workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
431
+ get inFlight() {
432
+ return this.#inFlight;
369
433
  }
370
- async#handleBuildRoute(msg) {
371
- const seenGeneration = this.#discoveredThrough;
372
- try {
373
- const delta = await new RouteClientBuilder({
374
- app: this.#app,
375
- routeId: msg.routeId,
376
- seeds: msg.seeds,
377
- graphSeeds: msg.graphSeeds,
378
- artifact: this.#artifact,
379
- knownEntries: new Set(msg.knownEntries),
380
- discovery: this.#discovery,
381
- browser: "registry"
382
- }).build();
383
- await this.#ensureSsrEntries(delta.registryEntries ?? []);
384
- this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
385
- this.#sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
386
- return {
387
- type: "build-route-res",
388
- id: msg.id,
389
- ok: true,
390
- data: {
391
- manifestDelta: delta.manifestDelta,
392
- ssrManifestDelta: delta.ssrManifestDelta.moduleMap,
393
- newEntries: delta.newEntries,
394
- discoveredEntries: delta.discoveredEntries,
395
- clientDeps: delta.clientDeps,
396
- clientDepsByEntry: delta.clientDepsByEntry,
397
- routeId: msg.routeId,
398
- generation: msg.generation,
399
- seenGeneration
400
- }
401
- };
402
- } catch (err) {
403
- const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
404
- this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
405
- this.#sendBuildStatus("route", {
406
- generation: this.#generation,
407
- ok: false,
408
- files: msg.seeds,
409
- message: errMsg,
410
- scope: msg.routeId
411
- });
412
- return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
413
- }
434
+ get shuttingDown() {
435
+ return this.#shuttingDown;
414
436
  }
415
- #sendBuildStatus(phase, {
416
- generation,
417
- ok,
418
- files,
419
- message,
420
- scope
421
- }) {
422
- if (typeof generation !== "number")
423
- return;
424
- BuilderChannel.emit({
425
- type: "build-status",
426
- data: { generation, phase, ok, files: files ?? [], message, ...scope !== undefined ? { scope } : {} }
427
- });
437
+ markShuttingDown() {
438
+ this.#shuttingDown = true;
428
439
  }
429
- async#enqueueFast(label, fn) {
440
+ async enqueueFast(label, fn) {
430
441
  const started = Date.now();
431
442
  this.#inFlight += 1;
432
443
  const run = this.#fastQueue.then(fn, fn);
@@ -447,7 +458,7 @@ class IncrementalBuilder {
447
458
  get #idle() {
448
459
  return this.#inFlight === 0 && this.#workQueue.size === 0 && this.#cssRebuildTimer === null;
449
460
  }
450
- #runBeside(work) {
461
+ runBeside(work) {
451
462
  this.#inFlight += 1;
452
463
  const tracked = work.finally(() => {
453
464
  this.#inFlight -= 1;
@@ -462,16 +473,10 @@ class IncrementalBuilder {
462
473
  return;
463
474
  BuilderChannel.emit({
464
475
  type: "builder-metrics",
465
- data: { rssBytes: process.memoryUsage.rss(), generation: this.#generation, workCount: this.#workCount }
476
+ data: { rssBytes: process.memoryUsage.rss(), generation: this.#links.generation(), workCount: this.#workCount }
466
477
  });
467
478
  }
468
- async shutdown(reason) {
469
- if (this.#shuttingDown)
470
- return;
471
- this.#shuttingDown = true;
472
- const started = Date.now();
473
- this.#logger.debug(`shutdown requested (${reason}); draining ${this.#inFlight} work item(s)`);
474
- this.#watcher?.stop();
479
+ async drain() {
475
480
  if (this.#cssRebuildTimer) {
476
481
  clearTimeout(this.#cssRebuildTimer);
477
482
  this.#cssRebuildTimer = null;
@@ -486,47 +491,9 @@ class IncrementalBuilder {
486
491
  });
487
492
  while (this.#beside.size > 0)
488
493
  await Promise.all([...this.#beside]);
489
- if (this.#delegations.size > 0)
490
- this.#logger.verbose(`registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
491
- const flushed = await BuilderChannel.drain();
492
- this.#logger.debug(`drained in ${Date.now() - started}ms${flushed ? ` after flushing ${flushed} ipc write(s)` : ""}; exiting for recycle`);
493
- process.exit(0);
494
- }
495
- get shuttingDown() {
496
- return this.#shuttingDown;
497
494
  }
498
- static #matchPageRoot(roots, abs) {
499
- for (const root of roots) {
500
- const absRoot = path2.resolve(root.realDir);
501
- if (abs === absRoot || abs.startsWith(`${absRoot}${path2.sep}`))
502
- return root;
503
- }
504
- return null;
505
- }
506
- batchTouchesPagesTree(roots, batch) {
507
- for (const f of batch.files) {
508
- const abs = path2.resolve(f);
509
- if (!IncrementalBuilder.#matchPageRoot(roots, abs))
510
- continue;
511
- if (/\.(tsx|ts|jsx|js)$/.test(abs))
512
- return true;
513
- }
514
- return false;
515
- }
516
- async batchMayChangePageKeys(roots, batch) {
517
- const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path2.normalize(key)));
518
- for (const f of batch.files) {
519
- const abs = path2.resolve(f);
520
- const root = IncrementalBuilder.#matchPageRoot(roots, abs);
521
- if (!root)
522
- continue;
523
- if (!/\.(tsx|ts|jsx|js)$/.test(abs))
524
- continue;
525
- const rel = path2.normalize(`${root.keyPrefix}${path2.relative(path2.resolve(root.realDir), abs)}`);
526
- if (!await Bun.file(abs).exists() || !pageKeys.has(rel))
527
- return true;
528
- }
529
- return false;
495
+ slowLaneFailed(label) {
496
+ return (error) => this.#logger.error(`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`);
530
497
  }
531
498
  scheduleCssRebuild({ generation, changedFiles }) {
532
499
  this.#pendingCssRebuild = { generation, changedFiles };
@@ -540,15 +507,15 @@ class IncrementalBuilder {
540
507
  return;
541
508
  this.#inFlight += 1;
542
509
  this.#cssRebuildQueue = this.#cssRebuildQueue.then(async () => {
543
- await this.#runBatch({
544
- generation: next.generation ?? this.#generation,
510
+ await this.#links.runBatch({
511
+ generation: next.generation ?? this.#links.generation(),
545
512
  needs: ["css"],
546
513
  changedFiles: next.changedFiles ?? []
547
514
  });
548
515
  }).catch((err) => {
549
516
  const message = err instanceof Error ? err.message : String(err);
550
517
  this.#logger.error(`css-rebuild failed: ${message}`);
551
- this.#sendBuildStatus("css", {
518
+ sendBuildStatus("css", {
552
519
  generation: next.generation,
553
520
  ok: false,
554
521
  files: next.changedFiles,
@@ -560,13 +527,78 @@ class IncrementalBuilder {
560
527
  });
561
528
  }, 150);
562
529
  }
530
+ }
531
+
532
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderWatch.ts
533
+ import path3 from "path";
534
+ class BuilderWatch {
535
+ #app;
536
+ #logger;
537
+ #lanes;
538
+ #csr;
539
+ #ssr;
540
+ #graphPayloads;
541
+ #links;
542
+ #changePlanner;
543
+ #generatedIndexSync;
544
+ #autoImportSync;
545
+ #watcher = null;
546
+ #barrelFailed = false;
547
+ constructor(app, { logger, lanes, csr, ssr, graphPayloads }, links) {
548
+ this.#app = app;
549
+ this.#logger = logger;
550
+ this.#lanes = lanes;
551
+ this.#csr = csr;
552
+ this.#ssr = ssr;
553
+ this.#graphPayloads = graphPayloads;
554
+ this.#links = links;
555
+ this.#changePlanner = new DevChangePlanner({ workspaceRoot: app.workspace.workspaceRoot });
556
+ this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: app.workspace.workspaceRoot });
557
+ this.#autoImportSync = new AutoImportSync({ workspaceRoot: app.workspace.workspaceRoot });
558
+ }
559
+ stop() {
560
+ this.#watcher?.stop();
561
+ }
562
+ static #matchPageRoot(roots, abs) {
563
+ for (const root of roots) {
564
+ const absRoot = path3.resolve(root.realDir);
565
+ if (abs === absRoot || abs.startsWith(`${absRoot}${path3.sep}`))
566
+ return root;
567
+ }
568
+ return null;
569
+ }
570
+ batchTouchesPagesTree(roots, batch) {
571
+ for (const f of batch.files) {
572
+ const abs = path3.resolve(f);
573
+ if (!BuilderWatch.#matchPageRoot(roots, abs))
574
+ continue;
575
+ if (/\.(tsx|ts|jsx|js)$/.test(abs))
576
+ return true;
577
+ }
578
+ return false;
579
+ }
580
+ async batchMayChangePageKeys(roots, batch) {
581
+ const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path3.normalize(key)));
582
+ for (const f of batch.files) {
583
+ const abs = path3.resolve(f);
584
+ const root = BuilderWatch.#matchPageRoot(roots, abs);
585
+ if (!root)
586
+ continue;
587
+ if (!/\.(tsx|ts|jsx|js)$/.test(abs))
588
+ continue;
589
+ const rel = path3.normalize(`${root.keyPrefix}${path3.relative(path3.resolve(root.realDir), abs)}`);
590
+ if (!await Bun.file(abs).exists() || !pageKeys.has(rel))
591
+ return true;
592
+ }
593
+ return false;
594
+ }
563
595
  async installWatcher() {
564
596
  const roots = await new WatchRootResolver(this.#app).resolve();
565
597
  const watcher = new HmrWatcher({
566
598
  roots,
567
599
  logger: this.#logger,
568
600
  onBatch: async (batch) => {
569
- await this.#enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
601
+ await this.#lanes.enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
570
602
  }
571
603
  });
572
604
  await watcher.start();
@@ -578,7 +610,7 @@ class IncrementalBuilder {
578
610
  const rawKinds = new Set(batch.kinds);
579
611
  if (rawKinds.size === 0)
580
612
  return;
581
- const generation = ++this.#generation;
613
+ const generation = this.#links.nextGeneration();
582
614
  const trace = { ...batch.trace, batchAt: Date.now() };
583
615
  const [autoImport, indexSync] = await CodegenLock.run(this.#app.workspace.workspaceRoot, `hmr-batch:${this.#app.name}`, async () => {
584
616
  const auto = await this.#autoImportSync.syncForBatch(batch.files);
@@ -601,15 +633,15 @@ class IncrementalBuilder {
601
633
  const discovery = kinds.includes("code") ? { files, refresh: kinds.includes("config"), generation } : undefined;
602
634
  if (hasSyncErrors) {
603
635
  this.#barrelFailed = true;
604
- this.#sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
636
+ sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
605
637
  `) });
606
638
  BuilderChannel.emit(event);
607
639
  if (discovery)
608
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
640
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
609
641
  return;
610
642
  }
611
643
  if (indexSync.changedFiles.length > 0 || this.#barrelFailed)
612
- this.#sendBuildStatus("barrel", { generation, ok: true, files });
644
+ sendBuildStatus("barrel", { generation, ok: true, files });
613
645
  this.#barrelFailed = false;
614
646
  const rebuildClient = devPlan.actions.includes("rebuild-client");
615
647
  if (kinds.includes("code") && !rebuildClient) {
@@ -626,13 +658,13 @@ class IncrementalBuilder {
626
658
  BuilderChannel.emit(event);
627
659
  if (kinds.includes("code") && rebuildClient) {
628
660
  const needs = ["pages", "css"];
629
- if (!this.#csrActive)
661
+ if (!this.#csr.csrActive)
630
662
  this.#logger.verbose(`csr-rebundle skipped; request /__csr or ?csr=true (or set AKAN_DEV_CSR_REBUILD=1) to enable per-save CSR rebuilds`);
631
- const patchCsr = async () => this.#csrActive ? await this.#patchCsr(generation, files, trace) : false;
632
- const patchSsr = async () => await this.#patchSsr(generation, files, trace);
663
+ const patchCsr = async () => this.#csr.csrActive ? await this.#csr.patchCsr(generation, files, trace) : false;
664
+ const patchSsr = async () => await this.#ssr.patchSsr(generation, files, trace);
633
665
  let csrToWorker;
634
666
  let ssrToWorker;
635
- if (this.#csrArming) {
667
+ if (this.#csr.csrArming) {
636
668
  ssrToWorker = await patchSsr();
637
669
  csrToWorker = await patchCsr();
638
670
  } else {
@@ -645,27 +677,66 @@ class IncrementalBuilder {
645
677
  needs.unshift("ssr");
646
678
  const batch = { generation, needs, changedFiles: files, trace, ...discovery ? { discovery } : {} };
647
679
  if (needs.includes("csr") || needs.includes("ssr"))
648
- await this.#workQueue.enqueueBatch(batch);
680
+ await this.#lanes.workQueue.enqueueBatch(batch);
649
681
  else
650
- this.#workQueue.enqueueBatch(batch).catch(this.#slowLaneFailed("batch"));
682
+ this.#lanes.workQueue.enqueueBatch(batch).catch(this.#lanes.slowLaneFailed("batch"));
651
683
  return;
652
684
  }
653
685
  if (discovery)
654
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
686
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
655
687
  if (kinds.includes("css")) {
656
- this.scheduleCssRebuild({ generation, changedFiles: files });
688
+ this.#lanes.scheduleCssRebuild({ generation, changedFiles: files });
657
689
  this.#logger.verbose(`css-rebuild scheduled generation=${generation}`);
658
690
  }
659
691
  }
660
- async#patchCsr(generation, files, trace) {
661
- const patcher = this.#patcher;
692
+ }
693
+
694
+ // pkgs/@akanjs/devkit/incrementalBuilder/csrRegistry.ts
695
+ import { rm } from "fs/promises";
696
+ import path4 from "path";
697
+ import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
698
+ class CsrRegistry {
699
+ #app;
700
+ #logger;
701
+ #lanes;
702
+ #batchRunner;
703
+ #links;
704
+ #shellKey = null;
705
+ #csrActive = CsrRegistry.#csrArmedByEnv();
706
+ #csrBundler;
707
+ #patcher;
708
+ #csrGate = Promise.resolve();
709
+ #csrArming = false;
710
+ #csrArms = 0;
711
+ #csrWasActive = false;
712
+ #csrArmSucceeded = false;
713
+ constructor(app, { logger, lanes, batchRunner }, links) {
714
+ this.#app = app;
715
+ this.#logger = logger;
716
+ this.#lanes = lanes;
717
+ this.#batchRunner = batchRunner;
718
+ this.#links = links;
719
+ this.#csrBundler = new CsrDevBundler(app);
720
+ this.#patcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
721
+ }
722
+ get csrActive() {
723
+ return this.#csrActive;
724
+ }
725
+ get csrArming() {
726
+ return this.#csrArming;
727
+ }
728
+ get patcher() {
729
+ return this.#patcher;
730
+ }
731
+ async patchCsr(generation, files, trace) {
732
+ const patcher = this.#patcher;
662
733
  if (!patcher)
663
734
  return true;
664
735
  await this.#csrGate;
665
736
  if (!this.#csrActive)
666
737
  return false;
667
738
  const started = Date.now();
668
- const marker = path2.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
739
+ const marker = path4.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
669
740
  await Bun.write(marker, String(process.pid));
670
741
  try {
671
742
  const result = await patcher.update(files, {
@@ -686,16 +757,16 @@ class IncrementalBuilder {
686
757
  }
687
758
  });
688
759
  if (result.kind === "delegate") {
689
- this.#logger.verbose(`csr-patch handed to a build worker (${this.#countDelegation("csr", result.reason)}): ${result.reason}`);
760
+ this.#logger.verbose(`csr-patch handed to a build worker (${this.#links.countDelegation("csr", result.reason)}): ${result.reason}`);
690
761
  return true;
691
762
  }
692
- this.#sendBuildStatus("csr", { generation, ok: true, files });
763
+ sendBuildStatus("csr", { generation, ok: true, files });
693
764
  this.#logger.verbose(result.kind === "unchanged" ? `csr-patch unchanged (${Date.now() - started}ms)` : `csr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`);
694
765
  return false;
695
766
  } catch (err) {
696
767
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
697
- if (IncrementalBuilder.#isCompileError(err)) {
698
- this.#sendBuildStatus("csr", { generation, ok: false, files, message });
768
+ if (isCompileError(err)) {
769
+ sendBuildStatus("csr", { generation, ok: false, files, message });
699
770
  return false;
700
771
  }
701
772
  this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
@@ -705,32 +776,152 @@ class IncrementalBuilder {
705
776
  await rm(marker, { force: true });
706
777
  }
707
778
  }
708
- async#patchSsr(generation, files, trace) {
779
+ async handleBuildCsr(msg) {
780
+ if (msg.shell) {
781
+ await this.#buildShell(msg);
782
+ return;
783
+ }
784
+ this.#beginCsrArm();
785
+ this.#csrActive = true;
786
+ const armed = this.#lanes.workQueue.enqueue("build-csr", async () => {
787
+ const started = Date.now();
788
+ let error;
789
+ try {
790
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }));
791
+ error = result.errors.csr;
792
+ } catch (err) {
793
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
794
+ }
795
+ if (error) {
796
+ this.#logger.error(`csr-build failed: ${error}`);
797
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
798
+ return;
799
+ }
800
+ this.#csrArmSucceeded = true;
801
+ this.#patcher?.forget();
802
+ this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
803
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
804
+ });
805
+ this.#csrGate = this.#armingCsr(armed);
806
+ await armed;
807
+ }
808
+ async#buildShell(msg) {
809
+ await this.#lanes.workQueue.enqueue("build-shell", async () => {
810
+ const generation = this.#links.generation();
811
+ const shellKey = `${generation}:${JSON.stringify(this.#links.artifact().cssAssets)}`;
812
+ let error;
813
+ if (this.#shellKey !== shellKey)
814
+ try {
815
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation, needs: ["shell"], changedFiles: [] }));
816
+ error = result.errors.shell;
817
+ if (!error)
818
+ this.#shellKey = shellKey;
819
+ } catch (err) {
820
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
821
+ }
822
+ await BuilderChannel.send(error ? { type: "build-csr-res", id: msg.id, ok: false, error } : { type: "build-csr-res", id: msg.id, ok: true });
823
+ });
824
+ }
825
+ #beginCsrArm() {
826
+ if (this.#csrArms === 0) {
827
+ this.#csrWasActive = this.#csrActive;
828
+ this.#csrArmSucceeded = false;
829
+ }
830
+ this.#csrArms += 1;
831
+ this.#csrArming = true;
832
+ }
833
+ #armingCsr(armed) {
834
+ const settle = () => {
835
+ this.#csrArms -= 1;
836
+ if (this.#csrArms > 0)
837
+ return;
838
+ this.#csrArming = false;
839
+ this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
840
+ };
841
+ return armed.then(settle, settle);
842
+ }
843
+ static #csrArmedByEnv() {
844
+ return process.env.AKAN_DEV_CSR_REBUILD === "1";
845
+ }
846
+ async rearmCsrFromEnv() {
847
+ if (!CsrRegistry.#csrArmedByEnv())
848
+ return;
849
+ this.#beginCsrArm();
850
+ this.#csrActive = true;
851
+ this.#csrArmSucceeded = true;
852
+ const rearmed = this.#lanes.workQueue.enqueue("build-csr-rearm", async () => {
853
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }), (msg) => BuilderChannel.emit(msg));
854
+ this.#patcher?.forget();
855
+ if (result.errors.csr)
856
+ this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
857
+ else
858
+ this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
859
+ });
860
+ this.#csrGate = this.#armingCsr(rearmed);
861
+ await rearmed.catch((err) => this.#logger.error(`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`));
862
+ }
863
+ }
864
+
865
+ // pkgs/@akanjs/devkit/incrementalBuilder/ssrRegistry.ts
866
+ import { rm as rm2 } from "fs/promises";
867
+ import path5 from "path";
868
+ import { CSR_DEV_PATCHING_MARKER as CSR_DEV_PATCHING_MARKER2 } from "akanjs/server/hmr/csrDevManifest";
869
+ class SsrRegistry {
870
+ #app;
871
+ #logger;
872
+ #lanes;
873
+ #artifactDir;
874
+ #links;
875
+ #crashRetryTimer = null;
876
+ #crashRetryEntries = new Set;
877
+ #ssrBundler;
878
+ #ssrPatcher;
879
+ #ssrLock = Promise.resolve();
880
+ #ssrArming = null;
881
+ #ssrBroken = false;
882
+ #ssrCrashedAt = null;
883
+ static get #crashRetryMs() {
884
+ const ms = Number(process.env.AKAN_DEV_SSR_CRASH_RETRY_MS);
885
+ return Number.isInteger(ms) && ms > 0 ? ms : 1e4;
886
+ }
887
+ constructor(app, { logger, lanes, artifactDir }, links) {
888
+ this.#app = app;
889
+ this.#logger = logger;
890
+ this.#lanes = lanes;
891
+ this.#artifactDir = artifactDir;
892
+ this.#links = links;
893
+ this.#ssrBundler = new SsrDevBundler(app, { discovery: links.discovery });
894
+ this.#ssrPatcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
895
+ }
896
+ get ssrPatcher() {
897
+ return this.#ssrPatcher;
898
+ }
899
+ async patchSsr(generation, files, trace) {
709
900
  const patcher = this.#ssrPatcher;
710
901
  if (!patcher)
711
902
  return true;
712
903
  const hold = await ServerGraphFile.touches(await ServerGraphFile.read(this.#artifactDir), files, (file) => ServerGraphFile.clientExportsOf(file));
713
- this.#discovery.invalidate?.(files);
714
- return await this.#withSsrLock(async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }));
904
+ this.#links.discovery().invalidate?.(files);
905
+ return await this.withSsrLock(async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }));
715
906
  }
716
- async#ensureSsrEntries(entries, { crashRetry = false } = {}) {
907
+ async ensureSsrEntries(entries, { crashRetry = false } = {}) {
717
908
  if (entries.length === 0)
718
909
  return;
719
910
  const arming = this.#ssrArming;
720
911
  if (arming) {
721
- this.#runBeside(arming.then(async () => await this.#ensureSsrEntries(entries, { crashRetry })).catch(this.#slowLaneFailed("ssr-ensure")));
912
+ this.#lanes.runBeside(arming.then(async () => await this.ensureSsrEntries(entries, { crashRetry })).catch(this.#lanes.slowLaneFailed("ssr-ensure")));
722
913
  return;
723
914
  }
724
- await this.#withSsrLock(async () => {
915
+ await this.withSsrLock(async () => {
725
916
  const patcher = this.#ssrPatcher;
726
- const generation = this.#generation;
917
+ const generation = this.#links.generation();
727
918
  if (patcher && !await this.#runSsrPatcher(patcher, [], { roots: entries, onlyRoots: true, batchGeneration: generation }))
728
919
  return;
729
920
  if (!patcher && await this.#ssrBundler.holds(entries))
730
921
  return;
731
922
  if (this.#ssrBroken)
732
923
  return;
733
- if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < IncrementalBuilder.#crashRetryMs) {
924
+ if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < SsrRegistry.#crashRetryMs) {
734
925
  patcher?.releaseHandedOver();
735
926
  this.#retryAfterCrash(this.#ssrCrashedAt, entries);
736
927
  return;
@@ -751,10 +942,10 @@ class IncrementalBuilder {
751
942
  this.#crashRetryTimer = null;
752
943
  const retried = [...this.#crashRetryEntries];
753
944
  this.#crashRetryEntries.clear();
754
- if (this.shuttingDown || retried.length === 0)
945
+ if (this.#lanes.shuttingDown || retried.length === 0)
755
946
  return;
756
- this.#runBeside(this.#ensureSsrEntries(retried, { crashRetry: true })).catch(this.#slowLaneFailed("ssr-crash-retry"));
757
- }, Math.max(0, crashedAt + IncrementalBuilder.#crashRetryMs - Date.now()));
947
+ this.#lanes.runBeside(this.ensureSsrEntries(retried, { crashRetry: true })).catch(this.#lanes.slowLaneFailed("ssr-crash-retry"));
948
+ }, Math.max(0, crashedAt + SsrRegistry.#crashRetryMs - Date.now()));
758
949
  timer.unref?.();
759
950
  this.#crashRetryTimer = timer;
760
951
  }
@@ -762,41 +953,29 @@ class IncrementalBuilder {
762
953
  const delayMs = Number(process.env.AKAN_DEV_SSR_ARM_DELAY_MS);
763
954
  if (Number.isInteger(delayMs) && delayMs > 0)
764
955
  await Bun.sleep(delayMs);
765
- const arm = async () => await this.#withSsrLock(async () => {
766
- const generation = this.#generation;
956
+ const arm = async () => await this.withSsrLock(async () => {
957
+ const generation = this.#links.generation();
767
958
  if (this.#ssrPatcher && !await this.#runSsrPatcher(this.#ssrPatcher, [], { batchGeneration: generation }))
768
959
  return;
769
960
  await this.#runSsrWorker(generation);
770
961
  }).catch((err) => {
771
962
  this.#logger.error(`ssr-registry boot build failed; the next save retries it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`);
772
963
  });
773
- const arming = this.#runBeside((async () => {
964
+ const arming = this.#lanes.runBeside((async () => {
774
965
  await arm();
775
966
  const crashedAt = this.#ssrCrashedAt;
776
967
  if (crashedAt === null)
777
968
  return;
778
- while (!this.shuttingDown && Date.now() < crashedAt + IncrementalBuilder.#crashRetryMs)
969
+ while (!this.#lanes.shuttingDown && Date.now() < crashedAt + SsrRegistry.#crashRetryMs)
779
970
  await Bun.sleep(250);
780
- if (!this.shuttingDown)
971
+ if (!this.#lanes.shuttingDown)
781
972
  await arm();
782
973
  })());
783
974
  this.#ssrArming = arming;
784
975
  await arming;
785
976
  this.#ssrArming = null;
786
977
  }
787
- static #isCompileError(error) {
788
- return error instanceof AggregateError;
789
- }
790
- #slowLaneFailed(label) {
791
- return (error) => this.#logger.error(`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`);
792
- }
793
- #countDelegation(registry, reason) {
794
- const key = `${registry}:${reason.split(":")[0]}`;
795
- const count = (this.#delegations.get(key) ?? 0) + 1;
796
- this.#delegations.set(key, count);
797
- return `#${count} for this reason`;
798
- }
799
- async#withSsrLock(fn) {
978
+ async withSsrLock(fn) {
800
979
  const run = this.#ssrLock.then(fn, fn);
801
980
  this.#ssrLock = run.then(() => {
802
981
  return;
@@ -808,15 +987,15 @@ class IncrementalBuilder {
808
987
  async#runSsrWorker(generation) {
809
988
  let result;
810
989
  try {
811
- result = await this.#runBatch({ generation, needs: ["ssr"], changedFiles: [] });
990
+ result = await this.#links.runBatch({ generation, needs: ["ssr"], changedFiles: [] });
812
991
  } finally {
813
992
  this.#ssrPatcher?.forget();
814
993
  }
815
- this.#noteSsrWorker(result);
994
+ this.noteSsrWorker(result);
816
995
  if (result.errors.ssr)
817
996
  throw new Error(result.errors.ssr);
818
997
  }
819
- #noteSsrWorker(result) {
998
+ noteSsrWorker(result) {
820
999
  const crashed = !!result.crashed && (result.crashedNeeds ?? ["ssr"]).includes("ssr");
821
1000
  this.#ssrBroken = !!result.errors.ssr && !crashed;
822
1001
  this.#ssrCrashedAt = crashed ? Date.now() : null;
@@ -829,7 +1008,7 @@ class IncrementalBuilder {
829
1008
  batchGeneration
830
1009
  } = {}) {
831
1010
  const started = Date.now();
832
- const marker = path2.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER);
1011
+ const marker = path5.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER2);
833
1012
  await Bun.write(marker, String(process.pid));
834
1013
  try {
835
1014
  const result = await patcher.update(files, {
@@ -855,47 +1034,178 @@ class IncrementalBuilder {
855
1034
  }
856
1035
  });
857
1036
  if (result.kind === "delegate") {
858
- this.#logger.verbose(`ssr-patch handed to a build worker (${this.#countDelegation("ssr", result.reason)}): ${result.reason}`);
1037
+ this.#logger.verbose(`ssr-patch handed to a build worker (${this.#links.countDelegation("ssr", result.reason)}): ${result.reason}`);
859
1038
  return true;
860
1039
  }
861
1040
  if (!onlyRoots) {
862
1041
  this.#ssrBroken = false;
863
1042
  this.#ssrCrashedAt = null;
864
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
1043
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
865
1044
  }
866
1045
  this.#logger.verbose(result.kind === "unchanged" ? `ssr-patch unchanged (${Date.now() - started}ms)` : `ssr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`);
867
1046
  return false;
868
1047
  } catch (err) {
869
1048
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
870
- if (IncrementalBuilder.#isCompileError(err)) {
871
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
1049
+ if (isCompileError(err)) {
1050
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
872
1051
  return false;
873
1052
  }
874
1053
  this.#logger.verbose(`ssr-patch threw; a build worker takes it: ${message}`);
875
1054
  patcher.forget();
876
1055
  return true;
877
1056
  } finally {
878
- await rm(marker, { force: true });
1057
+ await rm2(marker, { force: true });
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
1063
+ class IncrementalBuilder {
1064
+ #logger = new Logger2("IncrementalBuilder");
1065
+ #app;
1066
+ #artifact;
1067
+ #watch;
1068
+ #optimizedFonts;
1069
+ #discovery;
1070
+ #batchRunner;
1071
+ #generation = 0;
1072
+ #graphPayloads;
1073
+ #discoveredThrough = 0;
1074
+ #delegations = new Map;
1075
+ #lanes;
1076
+ #csr;
1077
+ #ssr;
1078
+ #watcher;
1079
+ constructor(options) {
1080
+ this.#app = options.app;
1081
+ this.#artifact = options.artifact;
1082
+ this.#watch = options.watch;
1083
+ this.#optimizedFonts = options.optimizedFonts;
1084
+ this.#discovery = options.discovery;
1085
+ this.#generation = options.initialGeneration ?? 0;
1086
+ this.#discoveredThrough = this.#generation;
1087
+ this.#graphPayloads = new BuilderGraphPayloads(options.app, () => this.#generation);
1088
+ this.#batchRunner = new BuildBatchRunner({
1089
+ workspaceRoot: options.app.workspace.workspaceRoot,
1090
+ cwd: options.app.cwdPath
1091
+ });
1092
+ const logger = this.#logger;
1093
+ const generation = () => this.#generation;
1094
+ const countDelegation = (registry, reason) => this.#countDelegation(registry, reason);
1095
+ const runBatch = (work) => this.#runBatch(work);
1096
+ this.#lanes = new BuilderLanes(options.app, { logger }, { generation, runQueuedBatch: (batch) => this.#runQueuedBatch(batch), runBatch });
1097
+ const lanes = this.#lanes;
1098
+ this.#csr = new CsrRegistry(options.app, { logger, lanes, batchRunner: this.#batchRunner }, { generation, artifact: () => this.#artifact, batchRequest: (work) => this.#batchRequest(work), countDelegation });
1099
+ this.#ssr = new SsrRegistry(options.app, { logger, lanes, artifactDir: this.#artifactDir }, { generation, discovery: () => this.#discovery, runBatch, countDelegation });
1100
+ this.#watcher = new BuilderWatch(options.app, { logger, lanes, csr: this.#csr, ssr: this.#ssr, graphPayloads: this.#graphPayloads }, { nextGeneration: () => ++this.#generation, refreshDiscovery: (job) => this.#refreshDiscovery(job) });
1101
+ }
1102
+ get #artifactDir() {
1103
+ return `${this.#app.cwdPath}/.akan/artifact`;
1104
+ }
1105
+ async handleBuildRoute(msg) {
1106
+ await this.#lanes.workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
1107
+ }
1108
+ async#handleBuildRoute(msg) {
1109
+ const seenGeneration = this.#discoveredThrough;
1110
+ try {
1111
+ const delta = await new RouteClientBuilder({
1112
+ app: this.#app,
1113
+ routeId: msg.routeId,
1114
+ seeds: msg.seeds,
1115
+ graphSeeds: msg.graphSeeds,
1116
+ artifact: this.#artifact,
1117
+ knownEntries: new Set(msg.knownEntries),
1118
+ discovery: this.#discovery,
1119
+ browser: "registry"
1120
+ }).build();
1121
+ await this.#ssr.ensureSsrEntries(delta.registryEntries ?? []);
1122
+ this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
1123
+ sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
1124
+ return {
1125
+ type: "build-route-res",
1126
+ id: msg.id,
1127
+ ok: true,
1128
+ data: {
1129
+ manifestDelta: delta.manifestDelta,
1130
+ ssrManifestDelta: delta.ssrManifestDelta.moduleMap,
1131
+ newEntries: delta.newEntries,
1132
+ discoveredEntries: delta.discoveredEntries,
1133
+ clientDeps: delta.clientDeps,
1134
+ clientDepsByEntry: delta.clientDepsByEntry,
1135
+ routeId: msg.routeId,
1136
+ generation: msg.generation,
1137
+ seenGeneration
1138
+ }
1139
+ };
1140
+ } catch (err) {
1141
+ const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1142
+ this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
1143
+ sendBuildStatus("route", {
1144
+ generation: this.#generation,
1145
+ ok: false,
1146
+ files: msg.seeds,
1147
+ message: errMsg,
1148
+ scope: msg.routeId
1149
+ });
1150
+ return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
879
1151
  }
880
1152
  }
1153
+ async shutdown(reason) {
1154
+ if (this.#lanes.shuttingDown)
1155
+ return;
1156
+ this.#lanes.markShuttingDown();
1157
+ const started = Date.now();
1158
+ this.#logger.debug(`shutdown requested (${reason}); draining ${this.#lanes.inFlight} work item(s)`);
1159
+ this.#watcher.stop();
1160
+ await this.#lanes.drain();
1161
+ if (this.#delegations.size > 0)
1162
+ this.#logger.verbose(`registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
1163
+ const flushed = await BuilderChannel.drain();
1164
+ this.#logger.debug(`drained in ${Date.now() - started}ms${flushed ? ` after flushing ${flushed} ipc write(s)` : ""}; exiting for recycle`);
1165
+ process.exit(0);
1166
+ }
1167
+ get shuttingDown() {
1168
+ return this.#lanes.shuttingDown;
1169
+ }
1170
+ batchTouchesPagesTree(roots, batch) {
1171
+ return this.#watcher.batchTouchesPagesTree(roots, batch);
1172
+ }
1173
+ batchMayChangePageKeys(roots, batch) {
1174
+ return this.#watcher.batchMayChangePageKeys(roots, batch);
1175
+ }
1176
+ scheduleCssRebuild(rebuild) {
1177
+ this.#lanes.scheduleCssRebuild(rebuild);
1178
+ }
1179
+ installWatcher() {
1180
+ return this.#watcher.installWatcher();
1181
+ }
1182
+ armSsrRegistry() {
1183
+ return this.#ssr.armSsrRegistry();
1184
+ }
1185
+ #countDelegation(registry, reason) {
1186
+ const key = `${registry}:${reason.split(":")[0]}`;
1187
+ const count = (this.#delegations.get(key) ?? 0) + 1;
1188
+ this.#delegations.set(key, count);
1189
+ return `#${count} for this reason`;
1190
+ }
881
1191
  async#runQueuedBatch({ discovery, ...work }) {
882
1192
  if (discovery)
883
1193
  await this.#refreshDiscovery(discovery);
884
1194
  this.#discoveredThrough = Math.max(this.#discoveredThrough, work.generation);
885
1195
  try {
886
1196
  if (work.needs.includes("ssr"))
887
- await this.#withSsrLock(async () => {
1197
+ await this.#ssr.withSsrLock(async () => {
888
1198
  try {
889
- this.#noteSsrWorker(await this.#runBatch(work));
1199
+ this.#ssr.noteSsrWorker(await this.#runBatch(work));
890
1200
  } finally {
891
- this.#ssrPatcher?.forget();
1201
+ this.#ssr.ssrPatcher?.forget();
892
1202
  }
893
1203
  });
894
1204
  else
895
1205
  await this.#runBatch(work);
896
1206
  } finally {
897
1207
  if (work.needs.includes("csr"))
898
- this.#patcher?.forget();
1208
+ this.#csr.patcher?.forget();
899
1209
  }
900
1210
  }
901
1211
  async#refreshDiscovery({ files, refresh, generation }) {
@@ -918,12 +1228,12 @@ class IncrementalBuilder {
918
1228
  if (result.crashed) {
919
1229
  const crashedNeeds = result.crashedNeeds ?? needs;
920
1230
  if (crashedNeeds.includes("csr"))
921
- this.#patcher?.releaseHandedOver();
1231
+ this.#csr.patcher?.releaseHandedOver();
922
1232
  if (crashedNeeds.includes("ssr"))
923
- this.#ssrPatcher?.releaseHandedOver();
1233
+ this.#ssr.ssrPatcher?.releaseHandedOver();
924
1234
  for (const need of crashedNeeds)
925
1235
  if (need !== "base" && need !== "shell")
926
- this.#sendBuildStatus(need, {
1236
+ sendBuildStatus(need, {
927
1237
  generation,
928
1238
  ok: false,
929
1239
  files: changedFiles,
@@ -945,19 +1255,19 @@ class IncrementalBuilder {
945
1255
  pageKeys: await this.#app.getPageKeys(),
946
1256
  optimizedFonts: this.#optimizedFonts,
947
1257
  cssAssets: this.#artifact.cssAssets ?? null,
948
- artifactDir: path2.resolve(this.#artifactDir),
1258
+ artifactDir: path6.resolve(this.#artifactDir),
949
1259
  ...trace ? { trace } : {}
950
1260
  };
951
1261
  }
952
1262
  async boot() {
953
1263
  if (this.#watch)
954
1264
  await this.installWatcher();
955
- BuilderChannel.emit({ type: "builder-ready" });
1265
+ await BuilderChannel.announceReady(this.#logger);
956
1266
  this.#logger.verbose(`ready (watch=${this.#watch})`);
957
1267
  }
958
1268
  async announceRecoveredState(changedFiles) {
959
1269
  const generation = ++this.#generation;
960
- await this.#workQueue.enqueue("boot-recovered", async () => {
1270
+ await this.#lanes.workQueue.enqueue("boot-recovered", async () => {
961
1271
  await this.#runBatch({ generation, needs: ["pages", "css"], changedFiles });
962
1272
  });
963
1273
  }
@@ -977,7 +1287,7 @@ class IncrementalBuilder {
977
1287
  const cssAssets = this.#artifact.cssAssets ?? {};
978
1288
  const cssBase64ByUrl = Object.fromEntries(await Promise.all(Object.values(cssAssets).map(async ({ cssUrl, cssRelPath }) => [
979
1289
  cssUrl,
980
- Buffer.from(await Bun.file(path2.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
1290
+ Buffer.from(await Bun.file(path6.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
981
1291
  ])));
982
1292
  await BuilderChannel.send({
983
1293
  type: "css-updated",
@@ -995,151 +1305,11 @@ class IncrementalBuilder {
995
1305
  await BuilderChannel.send({ type: "build-graph-res", id: msg.id, ok: false, error });
996
1306
  }
997
1307
  }
998
- async handleBuildCsr(msg) {
999
- if (msg.shell) {
1000
- await this.#buildShell(msg);
1001
- return;
1002
- }
1003
- this.#beginCsrArm();
1004
- this.#csrActive = true;
1005
- const armed = this.#workQueue.enqueue("build-csr", async () => {
1006
- const started = Date.now();
1007
- let error;
1008
- try {
1009
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }));
1010
- error = result.errors.csr;
1011
- } catch (err) {
1012
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1013
- }
1014
- if (error) {
1015
- this.#logger.error(`csr-build failed: ${error}`);
1016
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
1017
- return;
1018
- }
1019
- this.#csrArmSucceeded = true;
1020
- this.#patcher?.forget();
1021
- this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
1022
- await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
1023
- });
1024
- this.#csrGate = this.#armingCsr(armed);
1025
- await armed;
1026
- }
1027
- async#buildShell(msg) {
1028
- await this.#workQueue.enqueue("build-shell", async () => {
1029
- const generation = this.#generation;
1030
- const shellKey = `${generation}:${JSON.stringify(this.#artifact.cssAssets)}`;
1031
- let error;
1032
- if (this.#shellKey !== shellKey)
1033
- try {
1034
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation, needs: ["shell"], changedFiles: [] }));
1035
- error = result.errors.shell;
1036
- if (!error)
1037
- this.#shellKey = shellKey;
1038
- } catch (err) {
1039
- error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1040
- }
1041
- await BuilderChannel.send(error ? { type: "build-csr-res", id: msg.id, ok: false, error } : { type: "build-csr-res", id: msg.id, ok: true });
1042
- });
1043
- }
1044
- #beginCsrArm() {
1045
- if (this.#csrArms === 0) {
1046
- this.#csrWasActive = this.#csrActive;
1047
- this.#csrArmSucceeded = false;
1048
- }
1049
- this.#csrArms += 1;
1050
- this.#csrArming = true;
1051
- }
1052
- #armingCsr(armed) {
1053
- const settle = () => {
1054
- this.#csrArms -= 1;
1055
- if (this.#csrArms > 0)
1056
- return;
1057
- this.#csrArming = false;
1058
- this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
1059
- };
1060
- return armed.then(settle, settle);
1308
+ handleBuildCsr(msg) {
1309
+ return this.#csr.handleBuildCsr(msg);
1061
1310
  }
1062
- static #csrArmedByEnv() {
1063
- return process.env.AKAN_DEV_CSR_REBUILD === "1";
1064
- }
1065
- static async#buildBootDeps(app, runner) {
1066
- const result = await runner.run({
1067
- appName: app.name,
1068
- workspaceRoot: app.workspace.workspaceRoot,
1069
- repoName: app.workspace.repoName,
1070
- generation: 0,
1071
- needs: ["base"],
1072
- changedFiles: [],
1073
- pageKeys: null,
1074
- optimizedFonts: null,
1075
- cssAssets: null,
1076
- artifactDir: path2.resolve(`${app.cwdPath}/.akan/artifact`)
1077
- });
1078
- if (result.errors.base)
1079
- throw new Error(result.errors.base);
1080
- if (!result.artifact || !result.optimizedFonts)
1081
- throw new Error("boot build reported success without an artifact; the build worker likely died");
1082
- const discovery = await GraphClientEntryDiscovery.create(app);
1083
- return { artifact: result.artifact, optimizedFonts: result.optimizedFonts, discovery };
1084
- }
1085
- async rearmCsrFromEnv() {
1086
- if (!IncrementalBuilder.#csrArmedByEnv())
1087
- return;
1088
- this.#beginCsrArm();
1089
- this.#csrActive = true;
1090
- this.#csrArmSucceeded = true;
1091
- const rearmed = this.#workQueue.enqueue("build-csr-rearm", async () => {
1092
- const result = await this.#batchRunner.run(await this.#batchRequest({ generation: this.#generation, needs: ["csr"], changedFiles: [] }), (msg) => BuilderChannel.emit(msg));
1093
- this.#patcher?.forget();
1094
- if (result.errors.csr)
1095
- this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
1096
- else
1097
- this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
1098
- });
1099
- this.#csrGate = this.#armingCsr(rearmed);
1100
- await rearmed.catch((err) => this.#logger.error(`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`));
1101
- }
1102
- static #recoverBoot(app, bootError, logger, runner, initialGeneration) {
1103
- const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
1104
- logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
1105
- let generation = initialGeneration;
1106
- const sendFailure = (files, message) => {
1107
- BuilderChannel.emit({
1108
- type: "build-status",
1109
- data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` }
1110
- });
1111
- };
1112
- sendFailure([], firstMessage);
1113
- BuilderChannel.emit({ type: "builder-ready" });
1114
- BuilderChannel.emit({ type: "boot-armed" });
1115
- return new Promise((resolve, reject) => {
1116
- (async () => {
1117
- const roots = await new WatchRootResolver(app).resolve();
1118
- const watcher = new HmrWatcher({
1119
- roots,
1120
- logger,
1121
- onBatch: async (batch) => {
1122
- generation += 1;
1123
- const files = [...batch.files].sort();
1124
- try {
1125
- if (new Set(batch.kinds).has("config"))
1126
- await app.getConfig({ refresh: true });
1127
- const deps = await IncrementalBuilder.#buildBootDeps(app, runner);
1128
- const builder = new IncrementalBuilder({ app, watch: true, initialGeneration: generation, ...deps });
1129
- watcher.stop();
1130
- logger.info(`boot build recovered generation=${generation}`);
1131
- resolve({ builder, changedFiles: files });
1132
- } catch (err) {
1133
- const message = err instanceof Error ? err.message : String(err);
1134
- logger.error(`boot build retry failed: ${message}`);
1135
- sendFailure(files, message);
1136
- }
1137
- }
1138
- });
1139
- await watcher.start();
1140
- logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
1141
- })().catch(reject);
1142
- });
1311
+ rearmCsrFromEnv() {
1312
+ return this.#csr.rearmCsrFromEnv();
1143
1313
  }
1144
1314
  static async main() {
1145
1315
  const logger = new Logger2("IncrementalBuilder");
@@ -1147,7 +1317,7 @@ class IncrementalBuilder {
1147
1317
  if (!workspaceRoot || !appName)
1148
1318
  throw new Error("AKAN_WORKSPACE_ROOT or AKAN_PUBLIC_APP_NAME is not set");
1149
1319
  const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot, repoName });
1150
- const app = AppExecutor.from(workspace, appName);
1320
+ const app = AppExecutor2.from(workspace, appName);
1151
1321
  const watch = process.env.AKAN_WATCH !== "0";
1152
1322
  let builder = null;
1153
1323
  const bootingError = "builder is recovering from a failed boot build; retry after the build error is fixed";
@@ -1179,14 +1349,14 @@ class IncrementalBuilder {
1179
1349
  });
1180
1350
  let recoveredFiles = null;
1181
1351
  const bootRunner = new BuildBatchRunner({ workspaceRoot, cwd: app.cwdPath });
1182
- const initialGeneration = IncrementalBuilder.#initialGeneration();
1352
+ const initialGeneration = BuilderBoot.initialGeneration();
1183
1353
  try {
1184
- const deps = await IncrementalBuilder.#buildBootDeps(app, bootRunner);
1354
+ const deps = await BuilderBoot.buildBootDeps(app, bootRunner);
1185
1355
  builder = new IncrementalBuilder({ app, watch, initialGeneration, ...deps });
1186
1356
  } catch (err) {
1187
1357
  if (!watch)
1188
1358
  throw err;
1189
- const recovered = await IncrementalBuilder.#recoverBoot(app, err, logger, bootRunner, initialGeneration);
1359
+ const recovered = await BuilderBoot.recoverBoot(app, err, logger, bootRunner, initialGeneration, (options) => new IncrementalBuilder(options));
1190
1360
  builder = recovered.builder;
1191
1361
  recoveredFiles = recovered.changedFiles;
1192
1362
  }
@@ -1198,10 +1368,6 @@ class IncrementalBuilder {
1198
1368
  await Promise.all([builder.rearmCsrFromEnv(), builder.armSsrRegistry()]);
1199
1369
  BuilderChannel.emit({ type: "boot-armed" });
1200
1370
  }
1201
- static #initialGeneration() {
1202
- const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
1203
- return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
1204
- }
1205
1371
  }
1206
1372
  await IncrementalBuilder.main().catch((err) => {
1207
1373
  console.error(err);