@akanjs/cli 3.2.0-rc.9 → 3.2.1-rc.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 (145) hide show
  1. package/.build-stamp +2 -2
  2. package/CodeAgent-xdw73nbz.js +11 -0
  3. package/{CodeTui-qstk5vpj.js → CodeTui-0gewm71c.js} +822 -666
  4. package/README.ko.md +7 -0
  5. package/README.md +7 -0
  6. package/TunnelShare-cccfdgbm.js +16 -0
  7. package/agent.command-g1mj34wz.js +59 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-rrx10jya.js +11 -0
  10. package/{application.command-m4rq4wc2.js → application.command-3w4v7t40.js} +84 -40
  11. package/{applicationBuildRunner-df7rx3ra.js → applicationBuildRunner-y5xbetyz.js} +51 -20
  12. package/buildBatch.proc.js +31 -16
  13. package/{cloud.command-a0gy0qq2.js → cloud.command-ph0rz6sw.js} +28 -29
  14. package/cloud.script-8bs9tp4j.js +30 -0
  15. package/{code.command-5rsdqw8s.js → code.command-9b967qpg.js} +13 -9
  16. package/context.command-ndzs5rbf.js +62 -0
  17. package/context.runner-bmstpng2.js +32 -0
  18. package/csrArtifactBuilder-gtvff6k7.js +10 -0
  19. package/{index-qd7xn2bk.js → dependencyScanner-93g8tk0r.js} +7 -6
  20. package/{devTui-h77zrjv5.js → devTui-rf374y2w.js} +1 -1
  21. package/{fileSys-zpvt5gtf.js → fileSys-e5mwt73x.js} +1 -1
  22. package/frameworkGraph-aneq2nwy.js +8 -0
  23. package/{guideline.command-mffxknbr.js → guideline.command-y8qz9kxy.js} +9 -5
  24. package/guidelines/agentRule/agentRule.instruction.md +25 -9
  25. package/guidelines/akanApi/akanApi.instruction.md +6 -4
  26. package/guidelines/conventions/core.md +23 -5
  27. package/guidelines/conventions/rules/app.md +4 -1
  28. package/guidelines/conventions/rules/page.md +5 -4
  29. package/guidelines/conventions/rules/ts.md +3 -3
  30. package/guidelines/errorCodes/errorCodes.instruction.md +165 -0
  31. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  32. package/guidelines/mcpRule/mcpRule.instruction.md +225 -5
  33. package/guidelines/pageRule/pageRule.instruction.md +10 -1
  34. package/guidelines/queryRule/queryRule.instruction.md +3 -1
  35. package/guidelines/runtimeRule/runtimeRule.instruction.md +14 -8
  36. package/guidelines/transportRule/transportRule.instruction.md +31 -1
  37. package/incrementalBuilder.proc.js +609 -437
  38. package/{index-skmtj8rm.js → index-02v45hh9.js} +27 -10
  39. package/{index-j6gc8n14.js → index-0csk6jqm.js} +11 -9
  40. package/{index-2r9ff9qm.js → index-0wa5z6rm.js} +2 -2
  41. package/{index-nmvhjn8c.js → index-0z8sbdme.js} +93 -82
  42. package/{index-2vgv7fs7.js → index-1c2807kg.js} +727 -693
  43. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  44. package/{index-2mf1aen9.js → index-1p9bxjmt.js} +2 -2
  45. package/{index-an76bdrv.js → index-2kh4xj3m.js} +1 -1
  46. package/{index-99qvtff2.js → index-2vn0m9z5.js} +5 -5
  47. package/{index-rp4yf32g.js → index-3569fr49.js} +36 -29
  48. package/{index-xvk2a75m.js → index-38x8ynrx.js} +25 -25
  49. package/{index-cmg5ngqa.js → index-3fmzz9sf.js} +20 -20
  50. package/{index-rfzp4pqs.js → index-45aprybg.js} +3 -3
  51. package/{index-k92x3vne.js → index-4a1n0nym.js} +1 -1
  52. package/{index-ra9fvn7s.js → index-4zgm54wf.js} +76 -40
  53. package/{index-exn38bzx.js → index-652f3bs8.js} +116 -54
  54. package/{index-grxs6fts.js → index-6gepp8yn.js} +57 -31
  55. package/{index-vm0dn0mt.js → index-6j351de4.js} +294 -157
  56. package/{index-w15mg3km.js → index-7ssr7wq4.js} +1 -1
  57. package/{index-gxav1bjz.js → index-82cmbpxc.js} +9 -9
  58. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  59. package/{index-gcx48get.js → index-9rymt8d6.js} +2 -2
  60. package/{index-swwjakt0.js → index-ankyx6dj.js} +14 -18
  61. package/{index-28x1aszt.js → index-b0t92k71.js} +154 -58
  62. package/index-b372rck5.js +799 -0
  63. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  64. package/{index-r0a604h4.js → index-c669pbyb.js} +5 -4
  65. package/{index-xyn02k0w.js → index-cm9rb480.js} +662 -433
  66. package/{index-j9790rhk.js → index-d0n78fzc.js} +1635 -1139
  67. package/{index-hqv34wzq.js → index-dr1carpr.js} +10 -10
  68. package/index-f2arv0mv.js +30 -0
  69. package/{index-5radqwn2.js → index-gtydr9qc.js} +12 -12
  70. package/{index-j6eeh5d7.js → index-j3fqs8rc.js} +5 -5
  71. package/{index-yckz5t8b.js → index-jdw9m5c4.js} +516 -434
  72. package/{index-ny2k80mv.js → index-jf4vk1s0.js} +9 -2
  73. package/{index-x40bdsca.js → index-jg5rwrf7.js} +77 -115
  74. package/{index-5zwr4n6k.js → index-ktxdfqg5.js} +65 -8
  75. package/index-mnhrqjjq.js +127 -0
  76. package/{index-3ghdb7p5.js → index-pc42gxa5.js} +2777 -3676
  77. package/{index-0hbtve0a.js → index-q8h4eg5y.js} +32 -28
  78. package/{index-j3v29pq7.js → index-qh81drde.js} +219 -175
  79. package/{index-b4qq3rq0.js → index-rwgqba9p.js} +1 -1
  80. package/{index-w8yasvpc.js → index-scfsqen7.js} +2136 -2175
  81. package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
  82. package/{index-0gg15zwa.js → index-twjgmryg.js} +6 -6
  83. package/index-whvhsb5f.js +80 -0
  84. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  85. package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
  86. package/{index-35j83zkd.js → index-xv3pvdw4.js} +2 -2
  87. package/{index-34792nh7.js → index-y2g0s9tn.js} +1 -1
  88. package/{index-43f4h4cm.js → index-ymgsvhc5.js} +7 -8
  89. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  90. package/{index-bns3wcpc.js → index-zyjztrvc.js} +2 -2
  91. package/index.js +30 -24
  92. package/libExecutor-nstr00s7.js +10 -0
  93. package/{library.command-bmd7zc5m.js → library.command-b02aw1hm.js} +12 -5
  94. package/{localRegistry.command-y6en1599.js → localRegistry.command-3hg1p4aj.js} +24 -24
  95. package/{module.command-7exfffqw.js → module.command-bd9gz6cv.js} +11 -7
  96. package/{package.command-adskw2rj.js → package.command-xmr0mxze.js} +11 -10
  97. package/package.json +8 -8
  98. package/{page.command-dw01272p.js → page.command-x94qf58g.js} +8 -4
  99. package/{pipeline.command-0b1r3y5r.js → pipeline.command-n2843k6t.js} +15 -9
  100. package/pkgExecutor-cka27e3c.js +10 -0
  101. package/{primitive.command-byw6vc04.js → primitive.command-cs7v376h.js} +12 -8
  102. package/{projectTypecheck-kkrpq60a.js → projectTypecheck-za2n3nbr.js} +1 -1
  103. package/{prompter-qrwx1p17.js → prompter-d33wmdpa.js} +2 -2
  104. package/{quality.command-6rqnhzct.js → quality.command-nqngh1jd.js} +25 -16
  105. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  106. package/{repair.command-rw5zymak.js → repair.command-v2medwsm.js} +12 -8
  107. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  108. package/{scalar.command-2dyp9nh9.js → scalar.command-61cjmxn1.js} +10 -6
  109. package/skills/akan-debug/SKILL.md +8 -5
  110. package/skills/akan-err/SKILL.md +7 -0
  111. package/skills/akan-mcp/SKILL.md +19 -1
  112. package/skills/akan-scaffold/SKILL.md +1 -1
  113. package/skills/akan-validate/SKILL.md +3 -3
  114. package/{subspace.command-111ynwv1.js → subspace.command-dtv8nfh7.js} +30 -24
  115. package/templates/app/page/_layout.tsx +13 -0
  116. package/templates/app/page/styles.css.template +40 -0
  117. package/templates/appSample/page/_index.tsx +9 -9
  118. package/templates/appSample/page/_layout.tsx +1 -0
  119. package/templates/appSample/page/styles.css.template +40 -5
  120. package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
  121. package/templates/biomeForm.ts +1 -1
  122. package/templates/env/_env.server.type.ts +1 -1
  123. package/templates/facetIndex/index.ts +2 -37
  124. package/templates/lib/sig.ts +0 -4
  125. package/templates/lib/useClient.ts +1 -1
  126. package/templates/workspaceRoot/.devcontainer/devcontainer.json.template +1 -1
  127. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  128. package/templates/workspaceRoot/README.ts +4 -2
  129. package/{tunnel.command-2gcpfbdj.js → tunnel.command-fmwm5fgb.js} +15 -13
  130. package/{typeChecker-s640r6c0.js → typeChecker-7jt6abrs.js} +1 -1
  131. package/typecheck.proc.js +3 -2
  132. package/{verify.command-djgs86ma.js → verify.command-4f260t53.js} +19 -17
  133. package/{workflow.command-n0k2mxr5.js → workflow.command-tm5q9xsm.js} +21 -14
  134. package/{workspace.command-fh1qwxfx.js → workspace.command-75gc280j.js} +56 -54
  135. package/CodeAgent-x2p3a3e0.js +0 -11
  136. package/TunnelShare-c4xsfzg5.js +0 -15
  137. package/agent.command-9et2e27p.js +0 -52
  138. package/cloud.script-xze4zh7n.js +0 -31
  139. package/context.command-rk1dwrg4.js +0 -57
  140. package/context.runner-83ky5m1b.js +0 -30
  141. package/dependencyScanner-78sq8m4q.js +0 -8
  142. /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
  143. /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
  144. /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
  145. /package/templates/{appSample → app}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
@@ -1,16 +1,23 @@
1
1
  // @bun
2
+ import"./index-zyjztrvc.js";
3
+ import {
4
+ CodegenLock,
5
+ WorkspaceExecutor
6
+ } from "./index-pc42gxa5.js";
7
+ import"./index-j4yvgfhr.js";
2
8
  import {
3
9
  HmrWatcher,
4
10
  WatchRootResolver,
5
11
  ApplicationBuildReporter
6
- } from "./index-vm0dn0mt.js";
12
+ } from "./index-6j351de4.js";
7
13
  import {
8
- CodegenLock,
9
- WorkspaceExecutor,
10
- AppExecutor
11
- } from "./index-3ghdb7p5.js";
12
- import"./index-bns3wcpc.js";
13
- import"./index-j4yvgfhr.js";
14
+ AppExecutor2
15
+ } from "./index-b372rck5.js";
16
+ import"./index-f2arv0mv.js";
17
+ import"./index-mnhrqjjq.js";
18
+ import {
19
+ ServerGraphFile
20
+ } from "./index-0z8sbdme.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-scfsqen7.js";
31
+ import"./index-trffs83s.js";
28
32
  import {
29
- FrameworkGraph
30
- } from "./index-cmg5ngqa.js";
33
+ FrameworkGraph2
34
+ } from "./index-3fmzz9sf.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-whvhsb5f.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,98 @@ 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 {
198
+ artifact: result.artifact,
199
+ optimizedFonts: result.optimizedFonts,
200
+ discovery,
201
+ basePhaseMs: result.basePhaseMs ?? {}
202
+ };
203
+ }
204
+ static recoverBoot(app, bootError, logger, runner, initialGeneration, create) {
205
+ const firstMessage = bootError instanceof Error ? bootError.message : String(bootError);
206
+ logger.error(`boot build failed; entering degraded watch mode until the error is fixed: ${firstMessage}`);
207
+ let generation = initialGeneration;
208
+ const sendFailure = (files, message) => {
209
+ BuilderChannel.emit({
210
+ type: "build-status",
211
+ data: { generation, phase: "pages", ok: false, files, message: `Boot build failed: ${message}` }
212
+ });
213
+ };
214
+ sendFailure([], firstMessage);
215
+ BuilderChannel.emit({ type: "builder-ready" });
216
+ BuilderChannel.emit({ type: "boot-armed" });
217
+ return new Promise((resolve, reject) => {
218
+ (async () => {
219
+ const roots = await new WatchRootResolver(app).resolve();
220
+ const watcher = new HmrWatcher({
221
+ roots,
222
+ logger,
223
+ onBatch: async (batch) => {
224
+ generation += 1;
225
+ const files = [...batch.files].sort();
226
+ try {
227
+ if (new Set(batch.kinds).has("config"))
228
+ await app.getConfig({ refresh: true });
229
+ const deps = await BuilderBoot.buildBootDeps(app, runner);
230
+ const builder = create({ app, watch: true, initialGeneration: generation, ...deps });
231
+ watcher.stop();
232
+ logger.info(`boot build recovered generation=${generation}`);
233
+ resolve({ builder, changedFiles: files });
234
+ } catch (err) {
235
+ const message = err instanceof Error ? err.message : String(err);
236
+ logger.error(`boot build retry failed: ${message}`);
237
+ sendFailure(files, message);
238
+ }
239
+ }
240
+ });
241
+ await watcher.start();
242
+ logger.warn(`[degraded] watching ${roots.length} roots for a fix`);
243
+ })().catch(reject);
244
+ });
245
+ }
246
+ static initialGeneration() {
247
+ const generation = Number(process.env.AKAN_BUILDER_INITIAL_GENERATION);
248
+ return Number.isInteger(generation) && generation > 0 ? generation + 1 : 0;
249
+ }
250
+ }
251
+
252
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderBuildStatus.ts
253
+ var sendBuildStatus = (phase, {
254
+ generation,
255
+ ok,
256
+ files,
257
+ message,
258
+ scope
259
+ }) => {
260
+ if (typeof generation !== "number")
261
+ return;
262
+ BuilderChannel.emit({
263
+ type: "build-status",
264
+ data: { generation, phase, ok, files: files ?? [], message, ...scope !== undefined ? { scope } : {} }
265
+ });
266
+ };
267
+ var isCompileError = (error) => error instanceof AggregateError;
268
+
153
269
  // pkgs/@akanjs/devkit/incrementalBuilder/builderGraphPayloads.ts
154
270
  class BuilderGraphPayloads {
155
271
  #app;
@@ -161,7 +277,7 @@ class BuilderGraphPayloads {
161
277
  this.#generation = generation;
162
278
  }
163
279
  touched(files) {
164
- FrameworkGraph.touched(this.#app.workspace.workspaceRoot, files);
280
+ FrameworkGraph2.touched(this.#app.workspace.workspaceRoot, files);
165
281
  }
166
282
  async of(msg) {
167
283
  if (msg.framework)
@@ -179,7 +295,7 @@ class BuilderGraphPayloads {
179
295
  }
180
296
  async#framework() {
181
297
  const { workspaceRoot } = this.#app.workspace;
182
- return { workspaceRoot, framework: await FrameworkGraph.cached(workspaceRoot) };
298
+ return { workspaceRoot, framework: await FrameworkGraph2.cached(workspaceRoot) };
183
299
  }
184
300
  async#changesSince(since) {
185
301
  const { workspace, name } = this.#app;
@@ -287,43 +403,12 @@ class BuilderWorkQueue {
287
403
  }
288
404
  }
289
405
 
290
- // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
291
- class IncrementalBuilder {
292
- #logger = new Logger2("IncrementalBuilder");
406
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderLanes.ts
407
+ class BuilderLanes {
293
408
  #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;
409
+ #logger;
410
+ #links;
325
411
  #beside = new Set;
326
- #barrelFailed = false;
327
412
  #fastQueue = Promise.resolve();
328
413
  #workQueue;
329
414
  #inFlight = 0;
@@ -332,28 +417,12 @@ class IncrementalBuilder {
332
417
  #cssRebuildQueue = Promise.resolve();
333
418
  #cssRebuildTimer = null;
334
419
  #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 });
420
+ constructor(app, { logger }, links) {
421
+ this.#app = app;
422
+ this.#logger = logger;
423
+ this.#links = links;
355
424
  this.#workQueue = new BuilderWorkQueue({
356
- runBatch: async (batch) => await this.#runQueuedBatch(batch),
425
+ runBatch: async (batch) => await this.#links.runQueuedBatch(batch),
357
426
  onSettled: (label, ms) => {
358
427
  this.#workCount += 1;
359
428
  this.#logger.verbose(`[work-queue] ${label} finished in ${ms}ms`);
@@ -361,72 +430,19 @@ class IncrementalBuilder {
361
430
  }
362
431
  });
363
432
  }
364
- get #artifactDir() {
365
- return `${this.#app.cwdPath}/.akan/artifact`;
433
+ get workQueue() {
434
+ return this.#workQueue;
366
435
  }
367
- async handleBuildRoute(msg) {
368
- await this.#workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
436
+ get inFlight() {
437
+ return this.#inFlight;
369
438
  }
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
- }
439
+ get shuttingDown() {
440
+ return this.#shuttingDown;
414
441
  }
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
- });
442
+ markShuttingDown() {
443
+ this.#shuttingDown = true;
428
444
  }
429
- async#enqueueFast(label, fn) {
445
+ async enqueueFast(label, fn) {
430
446
  const started = Date.now();
431
447
  this.#inFlight += 1;
432
448
  const run = this.#fastQueue.then(fn, fn);
@@ -447,7 +463,7 @@ class IncrementalBuilder {
447
463
  get #idle() {
448
464
  return this.#inFlight === 0 && this.#workQueue.size === 0 && this.#cssRebuildTimer === null;
449
465
  }
450
- #runBeside(work) {
466
+ runBeside(work) {
451
467
  this.#inFlight += 1;
452
468
  const tracked = work.finally(() => {
453
469
  this.#inFlight -= 1;
@@ -462,16 +478,10 @@ class IncrementalBuilder {
462
478
  return;
463
479
  BuilderChannel.emit({
464
480
  type: "builder-metrics",
465
- data: { rssBytes: process.memoryUsage.rss(), generation: this.#generation, workCount: this.#workCount }
481
+ data: { rssBytes: process.memoryUsage.rss(), generation: this.#links.generation(), workCount: this.#workCount }
466
482
  });
467
483
  }
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();
484
+ async drain() {
475
485
  if (this.#cssRebuildTimer) {
476
486
  clearTimeout(this.#cssRebuildTimer);
477
487
  this.#cssRebuildTimer = null;
@@ -486,47 +496,9 @@ class IncrementalBuilder {
486
496
  });
487
497
  while (this.#beside.size > 0)
488
498
  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
- }
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
499
  }
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;
500
+ slowLaneFailed(label) {
501
+ return (error) => this.#logger.error(`${label} failed in the slow lane: ${ApplicationBuildReporter.formatError(error, this.#app.workspace.workspaceRoot)}`);
530
502
  }
531
503
  scheduleCssRebuild({ generation, changedFiles }) {
532
504
  this.#pendingCssRebuild = { generation, changedFiles };
@@ -540,15 +512,15 @@ class IncrementalBuilder {
540
512
  return;
541
513
  this.#inFlight += 1;
542
514
  this.#cssRebuildQueue = this.#cssRebuildQueue.then(async () => {
543
- await this.#runBatch({
544
- generation: next.generation ?? this.#generation,
515
+ await this.#links.runBatch({
516
+ generation: next.generation ?? this.#links.generation(),
545
517
  needs: ["css"],
546
518
  changedFiles: next.changedFiles ?? []
547
519
  });
548
520
  }).catch((err) => {
549
521
  const message = err instanceof Error ? err.message : String(err);
550
522
  this.#logger.error(`css-rebuild failed: ${message}`);
551
- this.#sendBuildStatus("css", {
523
+ sendBuildStatus("css", {
552
524
  generation: next.generation,
553
525
  ok: false,
554
526
  files: next.changedFiles,
@@ -560,31 +532,96 @@ class IncrementalBuilder {
560
532
  });
561
533
  }, 150);
562
534
  }
563
- async installWatcher() {
564
- const roots = await new WatchRootResolver(this.#app).resolve();
565
- const watcher = new HmrWatcher({
566
- roots,
567
- logger: this.#logger,
568
- onBatch: async (batch) => {
569
- await this.#enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
570
- }
571
- });
572
- await watcher.start();
573
- this.#watcher = watcher;
574
- this.#logger.verbose(`watching ${roots.length} roots`);
535
+ }
536
+
537
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderWatch.ts
538
+ import path3 from "path";
539
+ class BuilderWatch {
540
+ #app;
541
+ #logger;
542
+ #lanes;
543
+ #csr;
544
+ #ssr;
545
+ #graphPayloads;
546
+ #links;
547
+ #changePlanner;
548
+ #generatedIndexSync;
549
+ #autoImportSync;
550
+ #watcher = null;
551
+ #barrelFailed = false;
552
+ constructor(app, { logger, lanes, csr, ssr, graphPayloads }, links) {
553
+ this.#app = app;
554
+ this.#logger = logger;
555
+ this.#lanes = lanes;
556
+ this.#csr = csr;
557
+ this.#ssr = ssr;
558
+ this.#graphPayloads = graphPayloads;
559
+ this.#links = links;
560
+ this.#changePlanner = new DevChangePlanner({ workspaceRoot: app.workspace.workspaceRoot });
561
+ this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: app.workspace.workspaceRoot });
562
+ this.#autoImportSync = new AutoImportSync({ workspaceRoot: app.workspace.workspaceRoot });
563
+ }
564
+ stop() {
565
+ this.#watcher?.stop();
575
566
  }
576
- async#handleWatchBatch(batch) {
577
- this.#graphPayloads.touched(batch.files);
578
- const rawKinds = new Set(batch.kinds);
579
- if (rawKinds.size === 0)
580
- return;
581
- const generation = ++this.#generation;
582
- const trace = { ...batch.trace, batchAt: Date.now() };
583
- const [autoImport, indexSync] = await CodegenLock.run(this.#app.workspace.workspaceRoot, `hmr-batch:${this.#app.name}`, async () => {
584
- const auto = await this.#autoImportSync.syncForBatch(batch.files);
585
- return [auto, await this.#generatedIndexSync.syncForBatch(batch.files)];
586
- });
587
- for (const error of autoImport.errors)
567
+ static #matchPageRoot(roots, abs) {
568
+ for (const root of roots) {
569
+ const absRoot = path3.resolve(root.realDir);
570
+ if (abs === absRoot || abs.startsWith(`${absRoot}${path3.sep}`))
571
+ return root;
572
+ }
573
+ return null;
574
+ }
575
+ batchTouchesPagesTree(roots, batch) {
576
+ for (const f of batch.files) {
577
+ const abs = path3.resolve(f);
578
+ if (!BuilderWatch.#matchPageRoot(roots, abs))
579
+ continue;
580
+ if (/\.(tsx|ts|jsx|js)$/.test(abs))
581
+ return true;
582
+ }
583
+ return false;
584
+ }
585
+ async batchMayChangePageKeys(roots, batch) {
586
+ const pageKeys = new Set((await this.#app.getPageKeys()).map((key) => path3.normalize(key)));
587
+ for (const f of batch.files) {
588
+ const abs = path3.resolve(f);
589
+ const root = BuilderWatch.#matchPageRoot(roots, abs);
590
+ if (!root)
591
+ continue;
592
+ if (!/\.(tsx|ts|jsx|js)$/.test(abs))
593
+ continue;
594
+ const rel = path3.normalize(`${root.keyPrefix}${path3.relative(path3.resolve(root.realDir), abs)}`);
595
+ if (!await Bun.file(abs).exists() || !pageKeys.has(rel))
596
+ return true;
597
+ }
598
+ return false;
599
+ }
600
+ async installWatcher() {
601
+ const roots = await new WatchRootResolver(this.#app).resolve();
602
+ const watcher = new HmrWatcher({
603
+ roots,
604
+ logger: this.#logger,
605
+ onBatch: async (batch) => {
606
+ await this.#lanes.enqueueFast("hmr-batch", async () => this.#handleWatchBatch(batch));
607
+ }
608
+ });
609
+ await watcher.start();
610
+ this.#watcher = watcher;
611
+ this.#logger.verbose(`watching ${roots.length} roots`);
612
+ }
613
+ async#handleWatchBatch(batch) {
614
+ this.#graphPayloads.touched(batch.files);
615
+ const rawKinds = new Set(batch.kinds);
616
+ if (rawKinds.size === 0)
617
+ return;
618
+ const generation = this.#links.nextGeneration();
619
+ const trace = { ...batch.trace, batchAt: Date.now() };
620
+ const [autoImport, indexSync] = await CodegenLock.run(this.#app.workspace.workspaceRoot, `hmr-batch:${this.#app.name}`, async () => {
621
+ const auto = await this.#autoImportSync.syncForBatch(batch.files);
622
+ return [auto, await this.#generatedIndexSync.syncForBatch(batch.files)];
623
+ });
624
+ for (const error of autoImport.errors)
588
625
  this.#logger.error(error);
589
626
  if (autoImport.changedFiles.length > 0)
590
627
  this.#logger.verbose(`[auto-import] inserted imports into ${autoImport.changedFiles.length} file(s)`);
@@ -601,15 +638,15 @@ class IncrementalBuilder {
601
638
  const discovery = kinds.includes("code") ? { files, refresh: kinds.includes("config"), generation } : undefined;
602
639
  if (hasSyncErrors) {
603
640
  this.#barrelFailed = true;
604
- this.#sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
641
+ sendBuildStatus("barrel", { generation, ok: false, files, message: indexSync.errors.join(`
605
642
  `) });
606
643
  BuilderChannel.emit(event);
607
644
  if (discovery)
608
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
645
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
609
646
  return;
610
647
  }
611
648
  if (indexSync.changedFiles.length > 0 || this.#barrelFailed)
612
- this.#sendBuildStatus("barrel", { generation, ok: true, files });
649
+ sendBuildStatus("barrel", { generation, ok: true, files });
613
650
  this.#barrelFailed = false;
614
651
  const rebuildClient = devPlan.actions.includes("rebuild-client");
615
652
  if (kinds.includes("code") && !rebuildClient) {
@@ -626,13 +663,13 @@ class IncrementalBuilder {
626
663
  BuilderChannel.emit(event);
627
664
  if (kinds.includes("code") && rebuildClient) {
628
665
  const needs = ["pages", "css"];
629
- if (!this.#csrActive)
666
+ if (!this.#csr.csrActive)
630
667
  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);
668
+ const patchCsr = async () => this.#csr.csrActive ? await this.#csr.patchCsr(generation, files, trace) : false;
669
+ const patchSsr = async () => await this.#ssr.patchSsr(generation, files, trace);
633
670
  let csrToWorker;
634
671
  let ssrToWorker;
635
- if (this.#csrArming) {
672
+ if (this.#csr.csrArming) {
636
673
  ssrToWorker = await patchSsr();
637
674
  csrToWorker = await patchCsr();
638
675
  } else {
@@ -645,19 +682,58 @@ class IncrementalBuilder {
645
682
  needs.unshift("ssr");
646
683
  const batch = { generation, needs, changedFiles: files, trace, ...discovery ? { discovery } : {} };
647
684
  if (needs.includes("csr") || needs.includes("ssr"))
648
- await this.#workQueue.enqueueBatch(batch);
685
+ await this.#lanes.workQueue.enqueueBatch(batch);
649
686
  else
650
- this.#workQueue.enqueueBatch(batch).catch(this.#slowLaneFailed("batch"));
687
+ this.#lanes.workQueue.enqueueBatch(batch).catch(this.#lanes.slowLaneFailed("batch"));
651
688
  return;
652
689
  }
653
690
  if (discovery)
654
- this.#workQueue.enqueue("discovery", async () => await this.#refreshDiscovery(discovery)).catch(this.#slowLaneFailed("discovery"));
691
+ this.#lanes.workQueue.enqueue("discovery", async () => await this.#links.refreshDiscovery(discovery)).catch(this.#lanes.slowLaneFailed("discovery"));
655
692
  if (kinds.includes("css")) {
656
- this.scheduleCssRebuild({ generation, changedFiles: files });
693
+ this.#lanes.scheduleCssRebuild({ generation, changedFiles: files });
657
694
  this.#logger.verbose(`css-rebuild scheduled generation=${generation}`);
658
695
  }
659
696
  }
660
- async#patchCsr(generation, files, trace) {
697
+ }
698
+
699
+ // pkgs/@akanjs/devkit/incrementalBuilder/csrRegistry.ts
700
+ import { rm } from "fs/promises";
701
+ import path4 from "path";
702
+ import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
703
+ class CsrRegistry {
704
+ #app;
705
+ #logger;
706
+ #lanes;
707
+ #batchRunner;
708
+ #links;
709
+ #shellKey = null;
710
+ #csrActive = CsrRegistry.#csrArmedByEnv();
711
+ #csrBundler;
712
+ #patcher;
713
+ #csrGate = Promise.resolve();
714
+ #csrArming = false;
715
+ #csrArms = 0;
716
+ #csrWasActive = false;
717
+ #csrArmSucceeded = false;
718
+ constructor(app, { logger, lanes, batchRunner }, links) {
719
+ this.#app = app;
720
+ this.#logger = logger;
721
+ this.#lanes = lanes;
722
+ this.#batchRunner = batchRunner;
723
+ this.#links = links;
724
+ this.#csrBundler = new CsrDevBundler(app);
725
+ this.#patcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
726
+ }
727
+ get csrActive() {
728
+ return this.#csrActive;
729
+ }
730
+ get csrArming() {
731
+ return this.#csrArming;
732
+ }
733
+ get patcher() {
734
+ return this.#patcher;
735
+ }
736
+ async patchCsr(generation, files, trace) {
661
737
  const patcher = this.#patcher;
662
738
  if (!patcher)
663
739
  return true;
@@ -665,7 +741,7 @@ class IncrementalBuilder {
665
741
  if (!this.#csrActive)
666
742
  return false;
667
743
  const started = Date.now();
668
- const marker = path2.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
744
+ const marker = path4.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
669
745
  await Bun.write(marker, String(process.pid));
670
746
  try {
671
747
  const result = await patcher.update(files, {
@@ -686,16 +762,16 @@ class IncrementalBuilder {
686
762
  }
687
763
  });
688
764
  if (result.kind === "delegate") {
689
- this.#logger.verbose(`csr-patch handed to a build worker (${this.#countDelegation("csr", result.reason)}): ${result.reason}`);
765
+ this.#logger.verbose(`csr-patch handed to a build worker (${this.#links.countDelegation("csr", result.reason)}): ${result.reason}`);
690
766
  return true;
691
767
  }
692
- this.#sendBuildStatus("csr", { generation, ok: true, files });
768
+ sendBuildStatus("csr", { generation, ok: true, files });
693
769
  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
770
  return false;
695
771
  } catch (err) {
696
772
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
697
- if (IncrementalBuilder.#isCompileError(err)) {
698
- this.#sendBuildStatus("csr", { generation, ok: false, files, message });
773
+ if (isCompileError(err)) {
774
+ sendBuildStatus("csr", { generation, ok: false, files, message });
699
775
  return false;
700
776
  }
701
777
  this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
@@ -705,32 +781,152 @@ class IncrementalBuilder {
705
781
  await rm(marker, { force: true });
706
782
  }
707
783
  }
708
- async#patchSsr(generation, files, trace) {
784
+ async handleBuildCsr(msg) {
785
+ if (msg.shell) {
786
+ await this.#buildShell(msg);
787
+ return;
788
+ }
789
+ this.#beginCsrArm();
790
+ this.#csrActive = true;
791
+ const armed = this.#lanes.workQueue.enqueue("build-csr", async () => {
792
+ const started = Date.now();
793
+ let error;
794
+ try {
795
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }));
796
+ error = result.errors.csr;
797
+ } catch (err) {
798
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
799
+ }
800
+ if (error) {
801
+ this.#logger.error(`csr-build failed: ${error}`);
802
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
803
+ return;
804
+ }
805
+ this.#csrArmSucceeded = true;
806
+ this.#patcher?.forget();
807
+ this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
808
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
809
+ });
810
+ this.#csrGate = this.#armingCsr(armed);
811
+ await armed;
812
+ }
813
+ async#buildShell(msg) {
814
+ await this.#lanes.workQueue.enqueue("build-shell", async () => {
815
+ const generation = this.#links.generation();
816
+ const shellKey = `${generation}:${JSON.stringify(this.#links.artifact().cssAssets)}`;
817
+ let error;
818
+ if (this.#shellKey !== shellKey)
819
+ try {
820
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation, needs: ["shell"], changedFiles: [] }));
821
+ error = result.errors.shell;
822
+ if (!error)
823
+ this.#shellKey = shellKey;
824
+ } catch (err) {
825
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
826
+ }
827
+ await BuilderChannel.send(error ? { type: "build-csr-res", id: msg.id, ok: false, error } : { type: "build-csr-res", id: msg.id, ok: true });
828
+ });
829
+ }
830
+ #beginCsrArm() {
831
+ if (this.#csrArms === 0) {
832
+ this.#csrWasActive = this.#csrActive;
833
+ this.#csrArmSucceeded = false;
834
+ }
835
+ this.#csrArms += 1;
836
+ this.#csrArming = true;
837
+ }
838
+ #armingCsr(armed) {
839
+ const settle = () => {
840
+ this.#csrArms -= 1;
841
+ if (this.#csrArms > 0)
842
+ return;
843
+ this.#csrArming = false;
844
+ this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
845
+ };
846
+ return armed.then(settle, settle);
847
+ }
848
+ static #csrArmedByEnv() {
849
+ return process.env.AKAN_DEV_CSR_REBUILD === "1";
850
+ }
851
+ async rearmCsrFromEnv() {
852
+ if (!CsrRegistry.#csrArmedByEnv())
853
+ return;
854
+ this.#beginCsrArm();
855
+ this.#csrActive = true;
856
+ this.#csrArmSucceeded = true;
857
+ const rearmed = this.#lanes.workQueue.enqueue("build-csr-rearm", async () => {
858
+ const result = await this.#batchRunner.run(await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }), (msg) => BuilderChannel.emit(msg));
859
+ this.#patcher?.forget();
860
+ if (result.errors.csr)
861
+ this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
862
+ else
863
+ this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
864
+ });
865
+ this.#csrGate = this.#armingCsr(rearmed);
866
+ await rearmed.catch((err) => this.#logger.error(`csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`));
867
+ }
868
+ }
869
+
870
+ // pkgs/@akanjs/devkit/incrementalBuilder/ssrRegistry.ts
871
+ import { rm as rm2 } from "fs/promises";
872
+ import path5 from "path";
873
+ import { CSR_DEV_PATCHING_MARKER as CSR_DEV_PATCHING_MARKER2 } from "akanjs/server/hmr/csrDevManifest";
874
+ class SsrRegistry {
875
+ #app;
876
+ #logger;
877
+ #lanes;
878
+ #artifactDir;
879
+ #links;
880
+ #crashRetryTimer = null;
881
+ #crashRetryEntries = new Set;
882
+ #ssrBundler;
883
+ #ssrPatcher;
884
+ #ssrLock = Promise.resolve();
885
+ #ssrArming = null;
886
+ #ssrBroken = false;
887
+ #ssrCrashedAt = null;
888
+ static get #crashRetryMs() {
889
+ const ms = Number(process.env.AKAN_DEV_SSR_CRASH_RETRY_MS);
890
+ return Number.isInteger(ms) && ms > 0 ? ms : 1e4;
891
+ }
892
+ constructor(app, { logger, lanes, artifactDir }, links) {
893
+ this.#app = app;
894
+ this.#logger = logger;
895
+ this.#lanes = lanes;
896
+ this.#artifactDir = artifactDir;
897
+ this.#links = links;
898
+ this.#ssrBundler = new SsrDevBundler(app, { discovery: links.discovery });
899
+ this.#ssrPatcher = process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#ssrBundler, { resident: true });
900
+ }
901
+ get ssrPatcher() {
902
+ return this.#ssrPatcher;
903
+ }
904
+ async patchSsr(generation, files, trace) {
709
905
  const patcher = this.#ssrPatcher;
710
906
  if (!patcher)
711
907
  return true;
712
908
  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 }));
909
+ this.#links.discovery().invalidate?.(files);
910
+ return await this.withSsrLock(async () => await this.#runSsrPatcher(patcher, files, { trace, hold, batchGeneration: generation }));
715
911
  }
716
- async#ensureSsrEntries(entries, { crashRetry = false } = {}) {
912
+ async ensureSsrEntries(entries, { crashRetry = false } = {}) {
717
913
  if (entries.length === 0)
718
914
  return;
719
915
  const arming = this.#ssrArming;
720
916
  if (arming) {
721
- this.#runBeside(arming.then(async () => await this.#ensureSsrEntries(entries, { crashRetry })).catch(this.#slowLaneFailed("ssr-ensure")));
917
+ this.#lanes.runBeside(arming.then(async () => await this.ensureSsrEntries(entries, { crashRetry })).catch(this.#lanes.slowLaneFailed("ssr-ensure")));
722
918
  return;
723
919
  }
724
- await this.#withSsrLock(async () => {
920
+ await this.withSsrLock(async () => {
725
921
  const patcher = this.#ssrPatcher;
726
- const generation = this.#generation;
922
+ const generation = this.#links.generation();
727
923
  if (patcher && !await this.#runSsrPatcher(patcher, [], { roots: entries, onlyRoots: true, batchGeneration: generation }))
728
924
  return;
729
925
  if (!patcher && await this.#ssrBundler.holds(entries))
730
926
  return;
731
927
  if (this.#ssrBroken)
732
928
  return;
733
- if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < IncrementalBuilder.#crashRetryMs) {
929
+ if (this.#ssrCrashedAt !== null && Date.now() - this.#ssrCrashedAt < SsrRegistry.#crashRetryMs) {
734
930
  patcher?.releaseHandedOver();
735
931
  this.#retryAfterCrash(this.#ssrCrashedAt, entries);
736
932
  return;
@@ -751,10 +947,10 @@ class IncrementalBuilder {
751
947
  this.#crashRetryTimer = null;
752
948
  const retried = [...this.#crashRetryEntries];
753
949
  this.#crashRetryEntries.clear();
754
- if (this.shuttingDown || retried.length === 0)
950
+ if (this.#lanes.shuttingDown || retried.length === 0)
755
951
  return;
756
- this.#runBeside(this.#ensureSsrEntries(retried, { crashRetry: true })).catch(this.#slowLaneFailed("ssr-crash-retry"));
757
- }, Math.max(0, crashedAt + IncrementalBuilder.#crashRetryMs - Date.now()));
952
+ this.#lanes.runBeside(this.ensureSsrEntries(retried, { crashRetry: true })).catch(this.#lanes.slowLaneFailed("ssr-crash-retry"));
953
+ }, Math.max(0, crashedAt + SsrRegistry.#crashRetryMs - Date.now()));
758
954
  timer.unref?.();
759
955
  this.#crashRetryTimer = timer;
760
956
  }
@@ -762,41 +958,29 @@ class IncrementalBuilder {
762
958
  const delayMs = Number(process.env.AKAN_DEV_SSR_ARM_DELAY_MS);
763
959
  if (Number.isInteger(delayMs) && delayMs > 0)
764
960
  await Bun.sleep(delayMs);
765
- const arm = async () => await this.#withSsrLock(async () => {
766
- const generation = this.#generation;
961
+ const arm = async () => await this.withSsrLock(async () => {
962
+ const generation = this.#links.generation();
767
963
  if (this.#ssrPatcher && !await this.#runSsrPatcher(this.#ssrPatcher, [], { batchGeneration: generation }))
768
964
  return;
769
965
  await this.#runSsrWorker(generation);
770
966
  }).catch((err) => {
771
967
  this.#logger.error(`ssr-registry boot build failed; the next save retries it: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`);
772
968
  });
773
- const arming = this.#runBeside((async () => {
969
+ const arming = this.#lanes.runBeside((async () => {
774
970
  await arm();
775
971
  const crashedAt = this.#ssrCrashedAt;
776
972
  if (crashedAt === null)
777
973
  return;
778
- while (!this.shuttingDown && Date.now() < crashedAt + IncrementalBuilder.#crashRetryMs)
974
+ while (!this.#lanes.shuttingDown && Date.now() < crashedAt + SsrRegistry.#crashRetryMs)
779
975
  await Bun.sleep(250);
780
- if (!this.shuttingDown)
976
+ if (!this.#lanes.shuttingDown)
781
977
  await arm();
782
978
  })());
783
979
  this.#ssrArming = arming;
784
980
  await arming;
785
981
  this.#ssrArming = null;
786
982
  }
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) {
983
+ async withSsrLock(fn) {
800
984
  const run = this.#ssrLock.then(fn, fn);
801
985
  this.#ssrLock = run.then(() => {
802
986
  return;
@@ -808,15 +992,15 @@ class IncrementalBuilder {
808
992
  async#runSsrWorker(generation) {
809
993
  let result;
810
994
  try {
811
- result = await this.#runBatch({ generation, needs: ["ssr"], changedFiles: [] });
995
+ result = await this.#links.runBatch({ generation, needs: ["ssr"], changedFiles: [] });
812
996
  } finally {
813
997
  this.#ssrPatcher?.forget();
814
998
  }
815
- this.#noteSsrWorker(result);
999
+ this.noteSsrWorker(result);
816
1000
  if (result.errors.ssr)
817
1001
  throw new Error(result.errors.ssr);
818
1002
  }
819
- #noteSsrWorker(result) {
1003
+ noteSsrWorker(result) {
820
1004
  const crashed = !!result.crashed && (result.crashedNeeds ?? ["ssr"]).includes("ssr");
821
1005
  this.#ssrBroken = !!result.errors.ssr && !crashed;
822
1006
  this.#ssrCrashedAt = crashed ? Date.now() : null;
@@ -829,7 +1013,7 @@ class IncrementalBuilder {
829
1013
  batchGeneration
830
1014
  } = {}) {
831
1015
  const started = Date.now();
832
- const marker = path2.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER);
1016
+ const marker = path5.join(this.#ssrBundler.outDir, CSR_DEV_PATCHING_MARKER2);
833
1017
  await Bun.write(marker, String(process.pid));
834
1018
  try {
835
1019
  const result = await patcher.update(files, {
@@ -855,47 +1039,178 @@ class IncrementalBuilder {
855
1039
  }
856
1040
  });
857
1041
  if (result.kind === "delegate") {
858
- this.#logger.verbose(`ssr-patch handed to a build worker (${this.#countDelegation("ssr", result.reason)}): ${result.reason}`);
1042
+ this.#logger.verbose(`ssr-patch handed to a build worker (${this.#links.countDelegation("ssr", result.reason)}): ${result.reason}`);
859
1043
  return true;
860
1044
  }
861
1045
  if (!onlyRoots) {
862
1046
  this.#ssrBroken = false;
863
1047
  this.#ssrCrashedAt = null;
864
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
1048
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: true, files });
865
1049
  }
866
1050
  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
1051
  return false;
868
1052
  } catch (err) {
869
1053
  const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
870
- if (IncrementalBuilder.#isCompileError(err)) {
871
- this.#sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
1054
+ if (isCompileError(err)) {
1055
+ sendBuildStatus("ssr", { generation: batchGeneration, ok: false, files, message });
872
1056
  return false;
873
1057
  }
874
1058
  this.#logger.verbose(`ssr-patch threw; a build worker takes it: ${message}`);
875
1059
  patcher.forget();
876
1060
  return true;
877
1061
  } finally {
878
- await rm(marker, { force: true });
1062
+ await rm2(marker, { force: true });
1063
+ }
1064
+ }
1065
+ }
1066
+
1067
+ // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts
1068
+ class IncrementalBuilder {
1069
+ #logger = new Logger2("IncrementalBuilder");
1070
+ #app;
1071
+ #artifact;
1072
+ #watch;
1073
+ #optimizedFonts;
1074
+ #discovery;
1075
+ #batchRunner;
1076
+ #generation = 0;
1077
+ #graphPayloads;
1078
+ #discoveredThrough = 0;
1079
+ #delegations = new Map;
1080
+ #lanes;
1081
+ #csr;
1082
+ #ssr;
1083
+ #watcher;
1084
+ constructor(options) {
1085
+ this.#app = options.app;
1086
+ this.#artifact = options.artifact;
1087
+ this.#watch = options.watch;
1088
+ this.#optimizedFonts = options.optimizedFonts;
1089
+ this.#discovery = options.discovery;
1090
+ this.#generation = options.initialGeneration ?? 0;
1091
+ this.#discoveredThrough = this.#generation;
1092
+ this.#graphPayloads = new BuilderGraphPayloads(options.app, () => this.#generation);
1093
+ this.#batchRunner = new BuildBatchRunner({
1094
+ workspaceRoot: options.app.workspace.workspaceRoot,
1095
+ cwd: options.app.cwdPath
1096
+ });
1097
+ const logger = this.#logger;
1098
+ const generation = () => this.#generation;
1099
+ const countDelegation = (registry, reason) => this.#countDelegation(registry, reason);
1100
+ const runBatch = (work) => this.#runBatch(work);
1101
+ this.#lanes = new BuilderLanes(options.app, { logger }, { generation, runQueuedBatch: (batch) => this.#runQueuedBatch(batch), runBatch });
1102
+ const lanes = this.#lanes;
1103
+ this.#csr = new CsrRegistry(options.app, { logger, lanes, batchRunner: this.#batchRunner }, { generation, artifact: () => this.#artifact, batchRequest: (work) => this.#batchRequest(work), countDelegation });
1104
+ this.#ssr = new SsrRegistry(options.app, { logger, lanes, artifactDir: this.#artifactDir }, { generation, discovery: () => this.#discovery, runBatch, countDelegation });
1105
+ 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) });
1106
+ }
1107
+ get #artifactDir() {
1108
+ return `${this.#app.cwdPath}/.akan/artifact`;
1109
+ }
1110
+ async handleBuildRoute(msg) {
1111
+ await this.#lanes.workQueue.enqueue(`build-route:${msg.routeId}`, async () => BuilderChannel.send(await this.#handleBuildRoute(msg)));
1112
+ }
1113
+ async#handleBuildRoute(msg) {
1114
+ const seenGeneration = this.#discoveredThrough;
1115
+ try {
1116
+ const delta = await new RouteClientBuilder({
1117
+ app: this.#app,
1118
+ routeId: msg.routeId,
1119
+ seeds: msg.seeds,
1120
+ graphSeeds: msg.graphSeeds,
1121
+ artifact: this.#artifact,
1122
+ knownEntries: new Set(msg.knownEntries),
1123
+ discovery: this.#discovery,
1124
+ browser: "registry"
1125
+ }).build();
1126
+ await this.#ssr.ensureSsrEntries(delta.registryEntries ?? []);
1127
+ this.#logger.verbose(`build-route ok routeId=${msg.routeId} newEntries=${delta.newEntries.length}`);
1128
+ sendBuildStatus("route", { generation: this.#generation, ok: true, files: msg.seeds, scope: msg.routeId });
1129
+ return {
1130
+ type: "build-route-res",
1131
+ id: msg.id,
1132
+ ok: true,
1133
+ data: {
1134
+ manifestDelta: delta.manifestDelta,
1135
+ ssrManifestDelta: delta.ssrManifestDelta.moduleMap,
1136
+ newEntries: delta.newEntries,
1137
+ discoveredEntries: delta.discoveredEntries,
1138
+ clientDeps: delta.clientDeps,
1139
+ clientDepsByEntry: delta.clientDepsByEntry,
1140
+ routeId: msg.routeId,
1141
+ generation: msg.generation,
1142
+ seenGeneration
1143
+ }
1144
+ };
1145
+ } catch (err) {
1146
+ const errMsg = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
1147
+ this.#logger.error(`build-route failed routeId=${msg.routeId}: ${errMsg}`);
1148
+ sendBuildStatus("route", {
1149
+ generation: this.#generation,
1150
+ ok: false,
1151
+ files: msg.seeds,
1152
+ message: errMsg,
1153
+ scope: msg.routeId
1154
+ });
1155
+ return { type: "build-route-res", id: msg.id, ok: false, error: errMsg };
879
1156
  }
880
1157
  }
1158
+ async shutdown(reason) {
1159
+ if (this.#lanes.shuttingDown)
1160
+ return;
1161
+ this.#lanes.markShuttingDown();
1162
+ const started = Date.now();
1163
+ this.#logger.debug(`shutdown requested (${reason}); draining ${this.#lanes.inFlight} work item(s)`);
1164
+ this.#watcher.stop();
1165
+ await this.#lanes.drain();
1166
+ if (this.#delegations.size > 0)
1167
+ this.#logger.verbose(`registry saves handed to build workers this session: ${[...this.#delegations].map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
1168
+ const flushed = await BuilderChannel.drain();
1169
+ this.#logger.debug(`drained in ${Date.now() - started}ms${flushed ? ` after flushing ${flushed} ipc write(s)` : ""}; exiting for recycle`);
1170
+ process.exit(0);
1171
+ }
1172
+ get shuttingDown() {
1173
+ return this.#lanes.shuttingDown;
1174
+ }
1175
+ batchTouchesPagesTree(roots, batch) {
1176
+ return this.#watcher.batchTouchesPagesTree(roots, batch);
1177
+ }
1178
+ batchMayChangePageKeys(roots, batch) {
1179
+ return this.#watcher.batchMayChangePageKeys(roots, batch);
1180
+ }
1181
+ scheduleCssRebuild(rebuild) {
1182
+ this.#lanes.scheduleCssRebuild(rebuild);
1183
+ }
1184
+ installWatcher() {
1185
+ return this.#watcher.installWatcher();
1186
+ }
1187
+ armSsrRegistry() {
1188
+ return this.#ssr.armSsrRegistry();
1189
+ }
1190
+ #countDelegation(registry, reason) {
1191
+ const key = `${registry}:${reason.split(":")[0]}`;
1192
+ const count = (this.#delegations.get(key) ?? 0) + 1;
1193
+ this.#delegations.set(key, count);
1194
+ return `#${count} for this reason`;
1195
+ }
881
1196
  async#runQueuedBatch({ discovery, ...work }) {
882
1197
  if (discovery)
883
1198
  await this.#refreshDiscovery(discovery);
884
1199
  this.#discoveredThrough = Math.max(this.#discoveredThrough, work.generation);
885
1200
  try {
886
1201
  if (work.needs.includes("ssr"))
887
- await this.#withSsrLock(async () => {
1202
+ await this.#ssr.withSsrLock(async () => {
888
1203
  try {
889
- this.#noteSsrWorker(await this.#runBatch(work));
1204
+ this.#ssr.noteSsrWorker(await this.#runBatch(work));
890
1205
  } finally {
891
- this.#ssrPatcher?.forget();
1206
+ this.#ssr.ssrPatcher?.forget();
892
1207
  }
893
1208
  });
894
1209
  else
895
1210
  await this.#runBatch(work);
896
1211
  } finally {
897
1212
  if (work.needs.includes("csr"))
898
- this.#patcher?.forget();
1213
+ this.#csr.patcher?.forget();
899
1214
  }
900
1215
  }
901
1216
  async#refreshDiscovery({ files, refresh, generation }) {
@@ -918,12 +1233,12 @@ class IncrementalBuilder {
918
1233
  if (result.crashed) {
919
1234
  const crashedNeeds = result.crashedNeeds ?? needs;
920
1235
  if (crashedNeeds.includes("csr"))
921
- this.#patcher?.releaseHandedOver();
1236
+ this.#csr.patcher?.releaseHandedOver();
922
1237
  if (crashedNeeds.includes("ssr"))
923
- this.#ssrPatcher?.releaseHandedOver();
1238
+ this.#ssr.ssrPatcher?.releaseHandedOver();
924
1239
  for (const need of crashedNeeds)
925
1240
  if (need !== "base" && need !== "shell")
926
- this.#sendBuildStatus(need, {
1241
+ sendBuildStatus(need, {
927
1242
  generation,
928
1243
  ok: false,
929
1244
  files: changedFiles,
@@ -945,19 +1260,19 @@ class IncrementalBuilder {
945
1260
  pageKeys: await this.#app.getPageKeys(),
946
1261
  optimizedFonts: this.#optimizedFonts,
947
1262
  cssAssets: this.#artifact.cssAssets ?? null,
948
- artifactDir: path2.resolve(this.#artifactDir),
1263
+ artifactDir: path6.resolve(this.#artifactDir),
949
1264
  ...trace ? { trace } : {}
950
1265
  };
951
1266
  }
952
1267
  async boot() {
953
1268
  if (this.#watch)
954
1269
  await this.installWatcher();
955
- BuilderChannel.emit({ type: "builder-ready" });
1270
+ await BuilderChannel.announceReady(this.#logger);
956
1271
  this.#logger.verbose(`ready (watch=${this.#watch})`);
957
1272
  }
958
1273
  async announceRecoveredState(changedFiles) {
959
1274
  const generation = ++this.#generation;
960
- await this.#workQueue.enqueue("boot-recovered", async () => {
1275
+ await this.#lanes.workQueue.enqueue("boot-recovered", async () => {
961
1276
  await this.#runBatch({ generation, needs: ["pages", "css"], changedFiles });
962
1277
  });
963
1278
  }
@@ -977,7 +1292,7 @@ class IncrementalBuilder {
977
1292
  const cssAssets = this.#artifact.cssAssets ?? {};
978
1293
  const cssBase64ByUrl = Object.fromEntries(await Promise.all(Object.values(cssAssets).map(async ({ cssUrl, cssRelPath }) => [
979
1294
  cssUrl,
980
- Buffer.from(await Bun.file(path2.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
1295
+ Buffer.from(await Bun.file(path6.join(this.#artifactDir, cssRelPath)).arrayBuffer()).toString("base64")
981
1296
  ])));
982
1297
  await BuilderChannel.send({
983
1298
  type: "css-updated",
@@ -995,151 +1310,11 @@ class IncrementalBuilder {
995
1310
  await BuilderChannel.send({ type: "build-graph-res", id: msg.id, ok: false, error });
996
1311
  }
997
1312
  }
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;
1313
+ handleBuildCsr(msg) {
1314
+ return this.#csr.handleBuildCsr(msg);
1026
1315
  }
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);
1061
- }
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
- });
1316
+ rearmCsrFromEnv() {
1317
+ return this.#csr.rearmCsrFromEnv();
1143
1318
  }
1144
1319
  static async main() {
1145
1320
  const logger = new Logger2("IncrementalBuilder");
@@ -1147,7 +1322,7 @@ class IncrementalBuilder {
1147
1322
  if (!workspaceRoot || !appName)
1148
1323
  throw new Error("AKAN_WORKSPACE_ROOT or AKAN_PUBLIC_APP_NAME is not set");
1149
1324
  const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot, repoName });
1150
- const app = AppExecutor.from(workspace, appName);
1325
+ const app = AppExecutor2.from(workspace, appName);
1151
1326
  const watch = process.env.AKAN_WATCH !== "0";
1152
1327
  let builder = null;
1153
1328
  const bootingError = "builder is recovering from a failed boot build; retry after the build error is fixed";
@@ -1179,14 +1354,15 @@ class IncrementalBuilder {
1179
1354
  });
1180
1355
  let recoveredFiles = null;
1181
1356
  const bootRunner = new BuildBatchRunner({ workspaceRoot, cwd: app.cwdPath });
1182
- const initialGeneration = IncrementalBuilder.#initialGeneration();
1357
+ const initialGeneration = BuilderBoot.initialGeneration();
1183
1358
  try {
1184
- const deps = await IncrementalBuilder.#buildBootDeps(app, bootRunner);
1359
+ const deps = await BuilderBoot.buildBootDeps(app, bootRunner);
1360
+ BuilderChannel.emit({ type: "base-built", phaseMs: deps.basePhaseMs });
1185
1361
  builder = new IncrementalBuilder({ app, watch, initialGeneration, ...deps });
1186
1362
  } catch (err) {
1187
1363
  if (!watch)
1188
1364
  throw err;
1189
- const recovered = await IncrementalBuilder.#recoverBoot(app, err, logger, bootRunner, initialGeneration);
1365
+ const recovered = await BuilderBoot.recoverBoot(app, err, logger, bootRunner, initialGeneration, (options) => new IncrementalBuilder(options));
1190
1366
  builder = recovered.builder;
1191
1367
  recoveredFiles = recovered.changedFiles;
1192
1368
  }
@@ -1198,10 +1374,6 @@ class IncrementalBuilder {
1198
1374
  await Promise.all([builder.rearmCsrFromEnv(), builder.armSsrRegistry()]);
1199
1375
  BuilderChannel.emit({ type: "boot-armed" });
1200
1376
  }
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
1377
  }
1206
1378
  await IncrementalBuilder.main().catch((err) => {
1207
1379
  console.error(err);