@akanjs/devkit 3.3.0-rc.3 → 3.3.0-rc.30

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 (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -95,3 +95,87 @@ describe("PagesBundleBuilder.transformServerUseClientFetchSource", () => {
95
95
  }
96
96
  });
97
97
  });
98
+
99
+ describe("PagesBundleBuilder on the generated layout with lib/usePage.ts", () => {
100
+ const emptyBuild = "const fetchProto = FetchClient.build<typeof signal>({}, {});";
101
+ const generatedPage = (fetchProtoLine = emptyBuild) =>
102
+ [
103
+ 'import { makePageProto, registerClientRuntime } from "akanjs/client";',
104
+ 'import { FetchClient } from "akanjs/fetch";',
105
+ 'import { getAllDictionary } from "./dict" with { type: "macro" };',
106
+ 'import type * as dict from "./dict";',
107
+ 'import type * as signal from "./sig";',
108
+ "",
109
+ 'const dictionary = process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? getAllDictionary() : {};',
110
+ "const pageProto = makePageProto<typeof dict>(dictionary);",
111
+ fetchProtoLine,
112
+ 'export const runtime = registerClientRuntime({ ...pageProto, ...fetchProto }, { scope: "app" });',
113
+ "",
114
+ "export const { msg, Err, usePage, sig, fetch } = runtime;",
115
+ "",
116
+ ].join("\n");
117
+ const generatedUseClientOnPage = (lines: { importLine?: string; signalArg?: string } = {}) =>
118
+ [
119
+ 'import { FetchClient } from "akanjs/fetch";',
120
+ 'import * as cnst from "./cnst";',
121
+ 'import { fetch as pageFetch, sig as pageSig } from "./usePage";',
122
+ lines.importLine ?? macroImport,
123
+ 'import type * as signal from "./sig";',
124
+ "",
125
+ `Object.assign(pageSig, FetchClient.build<typeof signal>(cnst, ${lines.signalArg ?? "getSerializedSignal()"}, { base: pageFetch }).sig);`,
126
+ "",
127
+ "export const fetch = pageFetch;",
128
+ "export const sig = pageSig;",
129
+ 'export { Err, msg, runtime, usePage } from "./usePage";',
130
+ "",
131
+ ].join("\n");
132
+
133
+ test("builds usePage.ts's client onto the live server fetch, so a server render calls what it calls today", () => {
134
+ expect(PagesBundleBuilder.transformServerPageFetchSource(generatedPage())).toBe(
135
+ `${serverImport}\n${generatedPage("const fetchProto = FetchClient.build<typeof signal>({}, {}, { base: serverFetch });")}`,
136
+ );
137
+ });
138
+
139
+ test("applies the server fetch's own signal in useClient.ts instead of the signal macro", () => {
140
+ expect(transform(generatedUseClientOnPage())).toBe(
141
+ generatedUseClientOnPage({ importLine: serverImport, signalArg: "serverFetch.serializedSignal" }),
142
+ );
143
+ });
144
+
145
+ test("leaves a usePage.ts or useClient.ts it does not recognise unchanged", () => {
146
+ const withDescriptors = generatedPage("const fetchProto = FetchClient.build<typeof signal>(cnst, {});");
147
+ expect(PagesBundleBuilder.transformServerPageFetchSource(withDescriptors)).toBe(withDescriptors);
148
+ const commented = generatedPage(`// ${emptyBuild}`);
149
+ expect(PagesBundleBuilder.transformServerPageFetchSource(commented)).toBe(commented);
150
+ const withoutMacroImport = generatedUseClientOnPage({ importLine: 'import { getSerializedSignal } from "./sig";' });
151
+ expect(transform(withoutMacroImport)).toBe(withoutMacroImport);
152
+ });
153
+ });
154
+
155
+ describe("PagesBundleBuilder on a generated lib/__client fetch piece", () => {
156
+ const pieceMacroImport = `import { getSerializedSignalOf } from "../sig" with { type: "macro" };`;
157
+ const generatedPiece = (importLine = pieceMacroImport) =>
158
+ [
159
+ 'import { FetchClient } from "akanjs/fetch";',
160
+ 'import * as cnst from "../cnst";',
161
+ 'import { fetch, sig } from "../usePage";',
162
+ importLine,
163
+ 'import type * as signal from "../sig";',
164
+ "",
165
+ 'Object.assign(sig, FetchClient.build<typeof signal>(cnst, getSerializedSignalOf("memo"), { base: fetch }).sig);',
166
+ "",
167
+ ].join("\n");
168
+
169
+ test("reads the module's descriptors from the live server signal instead of the build-time macro", () => {
170
+ expect(PagesBundleBuilder.transformServerClientPieceSource(generatedPiece())).toBe(
171
+ generatedPiece('import { getSerializedSignalOf } from "../sig";'),
172
+ );
173
+ });
174
+
175
+ test("leaves a piece it does not recognise unchanged", () => {
176
+ const commented = generatedPiece(`// ${pieceMacroImport}`);
177
+ expect(PagesBundleBuilder.transformServerClientPieceSource(commented)).toBe(commented);
178
+ const otherMacro = generatedPiece(`import { getSerializedSignal } from "../sig" with { type: "macro" };`);
179
+ expect(PagesBundleBuilder.transformServerClientPieceSource(otherMacro)).toBe(otherMacro);
180
+ });
181
+ });
@@ -13,6 +13,7 @@ import { createUseClientBundlePlugin } from "../transforms/useClientBundlePlugin
13
13
  import { bundleDefine } from "./bundleDefine";
14
14
  import { CsrDevPaths } from "./csrDevPaths";
15
15
  import { PagesEntrySourceGenerator } from "./pagesEntrySourceGenerator";
16
+ import { RscServerRendererGuard } from "./rscServerRendererGuard";
16
17
  import { ServerGraphFile } from "./serverGraphFile";
17
18
 
18
19
  export interface BuildPagesBundleResult {
@@ -74,7 +75,7 @@ export class PagesBundleBuilder {
74
75
  asset: "assets/[name]-[hash].[ext]",
75
76
  },
76
77
  define: bundleDefine(this.#app, this.#command, "ssr"),
77
- metafile: dev,
78
+ metafile: true,
78
79
  plugins: [
79
80
  //? First: the use-client plugins below load every module, and an env file must be swapped before they do.
80
81
  ...(this.#serverEnv ? [this.#serverEnv] : []),
@@ -96,6 +97,7 @@ export class PagesBundleBuilder {
96
97
  });
97
98
 
98
99
  if (!result.success) throw new AggregateError(result.logs, "[PagesBundleBuilder] Bun.build failed");
100
+ RscServerRendererGuard.assert(result.metafile, workspaceRoot);
99
101
 
100
102
  const entryArtifact = result.outputs.find((a) => a.kind === "entry-point");
101
103
  if (!entryArtifact) throw new Error("[PagesBundleBuilder] Bun.build emitted no entry-point artifact");
@@ -169,9 +171,15 @@ export class PagesBundleBuilder {
169
171
  return {
170
172
  name: "akan-server-use-client-fetch",
171
173
  setup(build) {
172
- build.onLoad({ filter: /[/\\]lib[/\\]useClient\.(ts|tsx|js|jsx)$/ }, async (args) => {
174
+ const filter = /[/\\]lib[/\\](?:useClient|usePage|__client[/\\][^/\\]+\.fetch)\.(ts|tsx|js|jsx)$/;
175
+ build.onLoad({ filter }, async (args) => {
173
176
  const source = await Bun.file(args.path).text();
174
- const transformed = PagesBundleBuilder.transformServerUseClientFetchSource(source);
177
+ const transformed =
178
+ path.basename(path.dirname(args.path)) === "__client"
179
+ ? PagesBundleBuilder.transformServerClientPieceSource(source)
180
+ : path.basename(args.path).startsWith("usePage.")
181
+ ? PagesBundleBuilder.transformServerPageFetchSource(source)
182
+ : PagesBundleBuilder.transformServerUseClientFetchSource(source);
175
183
  if (transformed === source) return undefined;
176
184
  return { contents: transformed, loader: loaderFor(args.path) };
177
185
  });
@@ -198,12 +206,47 @@ export class PagesBundleBuilder {
198
206
  end: fetchProtoEnd.end,
199
207
  text: "const fetchProto = FetchClient.build<typeof signal>(cnst, serverFetch.serializedSignal, { base: serverFetch });",
200
208
  });
209
+ const macroCallAt =
210
+ fetchProtoAt === -1 && importAt !== -1
211
+ ? PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#macroCallTokens)
212
+ : -1;
213
+ if (macroCallAt !== -1)
214
+ edits.push({
215
+ start: tokens[macroCallAt].start,
216
+ end: tokens[macroCallAt + PagesBundleBuilder.#macroCallTokens.length - 1].end,
217
+ text: "serverFetch.serializedSignal",
218
+ });
201
219
  let transformed = source;
202
220
  for (const { start, end, text } of edits.sort((a, b) => b.start - a.start))
203
221
  transformed = transformed.slice(0, start) + text + transformed.slice(end);
204
222
  return transformed;
205
223
  }
206
224
 
225
+ //? A piece reads its descriptors from the live server signal at render time instead of inlining them at build time.
226
+ static transformServerClientPieceSource(source: string): string {
227
+ if (!source.includes(`with { type: "macro" }`)) return source;
228
+ const tokens = PagesBundleBuilder.#tokenize(source);
229
+ const at = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#pieceMacroImportTokens);
230
+ if (at === -1) return source;
231
+ const end = tokens[at + PagesBundleBuilder.#pieceMacroImportTokens.length - 1].end;
232
+ return `${source.slice(0, tokens[at].start)}import { getSerializedSignalOf } from "../sig";${source.slice(end)}`;
233
+ }
234
+
235
+ static readonly #pieceMacroImportTokens = [
236
+ "import",
237
+ "{",
238
+ "getSerializedSignalOf",
239
+ "}",
240
+ "from",
241
+ '"../sig"',
242
+ "with",
243
+ "{",
244
+ "type",
245
+ ":",
246
+ '"macro"',
247
+ "}",
248
+ ";",
249
+ ] as const;
207
250
  static readonly #macroImportTokens = [
208
251
  "import",
209
252
  "{",
@@ -220,6 +263,41 @@ export class PagesBundleBuilder {
220
263
  ";",
221
264
  ] as const;
222
265
  static readonly #fetchProtoTokens = ["const", "fetchProto", "=", "FetchClient", ".", "build", "<"] as const;
266
+ static readonly #macroCallTokens = ["getSerializedSignal", "(", ")"] as const;
267
+ static readonly #pageFetchProtoTokens = [
268
+ "const",
269
+ "fetchProto",
270
+ "=",
271
+ "FetchClient",
272
+ ".",
273
+ "build",
274
+ "<",
275
+ "typeof",
276
+ "signal",
277
+ ">",
278
+ "(",
279
+ "{",
280
+ "}",
281
+ ",",
282
+ "{",
283
+ "}",
284
+ ")",
285
+ ";",
286
+ ] as const;
287
+
288
+ static transformServerPageFetchSource(source: string): string {
289
+ if (!source.includes("FetchClient.build")) return source;
290
+ const tokens = PagesBundleBuilder.#tokenize(source);
291
+ const at = PagesBundleBuilder.#indexOfTokens(tokens, PagesBundleBuilder.#pageFetchProtoTokens);
292
+ if (at === -1) return source;
293
+ const end = tokens[at + PagesBundleBuilder.#pageFetchProtoTokens.length - 1].end;
294
+ return [
295
+ `import { fetch as serverFetch } from "./sig";\n`,
296
+ source.slice(0, tokens[at].start),
297
+ "const fetchProto = FetchClient.build<typeof signal>({}, {}, { base: serverFetch });",
298
+ source.slice(end),
299
+ ].join("");
300
+ }
223
301
 
224
302
  //? The scanner, not the parser: parsing recurses per nesting level and overflows the stack on a deep `{` run.
225
303
  static #tokenize(source: string): TextSpan[] {
@@ -76,6 +76,13 @@ export async function servedBrotliBytesOf(artifactDir: string, filePath: string)
76
76
  return brotliCompress(buffer, quality).byteLength;
77
77
  }
78
78
 
79
+ export function chunkBrotliBytesOf(bytes: Uint8Array): number {
80
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
81
+ return bytes.byteLength < MIN_COMPRESS_BYTES
82
+ ? bytes.byteLength
83
+ : brotliCompress(buffer, brotliQualityOf(".js")).byteLength;
84
+ }
85
+
79
86
  function brotliQualityOf(ext: string): number {
80
87
  return BROTLI_QUALITY_BY_EXT[ext as keyof typeof BROTLI_QUALITY_BY_EXT] ?? DEFAULT_BROTLI_QUALITY;
81
88
  }
@@ -1,9 +1,9 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
- //* The sources `lib/useClient.ts` reads through its macros, which no registry graph lists as a dependency. A registry
5
- //* records their stamp, so a builder that loads one built before a signal or dictionary save rebuilds it, whichever
6
- //* process saw that save (a builder restarted for it never finishes the rebuild it started).
4
+ //* The sources `lib/useClient.ts` and `lib/usePage.ts` read through macros, which no registry graph lists as a
5
+ //* dependency. A registry records their stamp, so a builder that loads one built before a signal or dictionary save
6
+ //* rebuilds it, whichever process saw that save (a builder restarted for it never finishes the rebuild it started).
7
7
  export class RegistryMetadataFingerprint {
8
8
  static readonly #sources = new Bun.Glob("**/*.{signal,dictionary}.ts");
9
9
  static readonly #libFiles = ["sig.ts", "dict.ts", "useClient.ts"];
@@ -1,17 +1,24 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, rm } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { BaseBuildArtifact, ClientManifest, ClientManifestEntry, SsrManifest } from "akanjs/server";
4
4
  import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
5
- import { StoreBootstrap } from "../artifact/storeBootstrap";
5
+ import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootstrap";
6
6
  import type { App } from "../commandDecorators";
7
+ import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "../quality/routeRuntimeReport";
7
8
  import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
8
9
  import { loaderFor } from "../transforms/moduleSyntax";
10
+ import { ReactIconImports } from "../transforms/reactIconImports";
11
+ import { RouteRuntime } from "../transforms/routeRuntime";
12
+ import type { RouteRuntimeBundle } from "../transforms/routeRuntimeGraph";
9
13
  import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
10
- import type { ClientBundleTarget, ClientEntryDiscovery } from "./clientBuildTypes";
14
+ import { SignalDescriptors } from "../transforms/signalDescriptors";
15
+ import type { ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
11
16
  import { ClientEntriesBundler } from "./clientEntriesBundler";
12
17
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
13
18
  import { CsrDevPaths } from "./csrDevPaths";
14
- import { VENDOR_SPECIFIERS } from "./vendorSpecifiers";
19
+ import { RouteRuntimeCheck } from "./routeRuntimeCheck";
20
+ import { type RoutePaysVerdict, RouteRuntimePays } from "./routeRuntimePays";
21
+ import { VendorFileImports } from "./vendorFileImports";
15
22
 
16
23
  const SSR_CLIENT_ALIAS_EXTERNALS = [
17
24
  "react",
@@ -36,6 +43,10 @@ export interface BuildRouteClientOptions {
36
43
  entries?: string[];
37
44
  /** Defaults to `registry` under `start`: the browser loads each entry from the SSR dev registry, so only `client-ssr` builds. */
38
45
  browser?: "chunks" | "registry";
46
+ /** The entries each route loads: an entry only whole-runtime routes hold keeps the whole runtime too. */
47
+ entriesByRoute?: ReadonlyMap<string, readonly string[]>;
48
+ /** The entries each route loads first, which its size is measured over. Defaults to `entriesByRoute`. */
49
+ sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
39
50
  }
40
51
 
41
52
  export interface BuildRouteClientResult {
@@ -49,6 +60,8 @@ export interface BuildRouteClientResult {
49
60
  registryEntries?: string[];
50
61
  /** Chunks mode: the importmap specifiers each browser chunk imports statically. */
51
62
  externalsByChunkUrl?: Record<string, string[]>;
63
+ /** The imports of every module the browser loads, or in registry mode of the SSR bundle standing in for it. */
64
+ clientGraph?: ReadonlyMap<string, readonly ClientModuleImport[]>;
52
65
  }
53
66
 
54
67
  interface BootstrapEntries {
@@ -56,6 +69,20 @@ interface BootstrapEntries {
56
69
  originalByBuildEntry: Map<string, string>;
57
70
  }
58
71
 
72
+ interface NarrowedBuild {
73
+ entries: BootstrapEntries;
74
+ kept: ReadonlySet<string>;
75
+ bundle: Awaited<ReturnType<ClientEntriesBundler["bundle"]>>;
76
+ runtime: RouteRuntime;
77
+ report?: RouteRuntimeBuildReport;
78
+ }
79
+
80
+ type BundleOf = (runtime: RouteRuntime, kept: ReadonlySet<string>, outputSubdir?: string) => Promise<NarrowedBuild>;
81
+
82
+ const referenceSubdir = "client-whole";
83
+ //? Each trial bundles the whole app again, and the entries left to try shrink slowly where pages share most of them.
84
+ const measuredTrials = 6;
85
+
59
86
  export class RouteClientBuilder {
60
87
  #app: App;
61
88
  #seeds: string[];
@@ -65,6 +92,8 @@ export class RouteClientBuilder {
65
92
  #discovery?: ClientEntryDiscovery;
66
93
  #entries?: string[];
67
94
  #browser: "chunks" | "registry";
95
+ #entriesByRoute?: ReadonlyMap<string, readonly string[]>;
96
+ #sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
68
97
 
69
98
  constructor(options: BuildRouteClientOptions) {
70
99
  this.#app = options.app;
@@ -75,6 +104,8 @@ export class RouteClientBuilder {
75
104
  this.#discovery = options.discovery;
76
105
  this.#entries = options.entries;
77
106
  this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
107
+ this.#entriesByRoute = options.entriesByRoute;
108
+ this.#sizedEntriesByRoute = options.sizedEntriesByRoute;
78
109
  }
79
110
 
80
111
  async build(): Promise<BuildRouteClientResult> {
@@ -84,12 +115,34 @@ export class RouteClientBuilder {
84
115
  ? [...new Set([...discovered, ...(await (await this.#getDiscovery()).discover(this.#graphSeeds))])].sort()
85
116
  : discovered.filter((e) => !this.#knownEntries.has(e));
86
117
 
87
- const bootstrapEntries = await this.#createBootstrapEntries(entries);
88
118
  //? Registry mode builds no browser bundle: the SSR bundle has the same entries, exports and imports to read.
89
119
  const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
90
- const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
91
- const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
120
+ const routeRuntime = registry ? null : await this.#readRouteRuntime();
121
+ if (!registry && !routeRuntime) await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
122
+ const ssrEntries = await this.#createBootstrapEntries(entries, "whole");
123
+ //? First: its entries all load the whole runtime, so its graph says which of them a per-route build may narrow.
124
+ const ssrBundle = await this.#buildSsrBundle(ssrEntries);
125
+ const narrowed = routeRuntime
126
+ ? await this.#buildNarrowed(entries, ssrEntries, routeRuntime, {
127
+ importsByModule: ssrBundle.graph.importsByModule,
128
+ entries: entries.map((entry) => path.resolve(entry)),
129
+ entriesByRoute: this.#entriesByRoute,
130
+ })
131
+ : null;
132
+ const trusted = narrowed && this.#check(narrowed) ? narrowed : null;
133
+ const browserEntries = registry ? null : (trusted?.entries ?? ssrEntries);
134
+ const browserBundle =
135
+ trusted?.bundle ?? (browserEntries ? await this.#buildBrowserBundle(browserEntries, null) : null);
136
+ if (trusted?.report) await this.#say(trusted.report);
137
+ if (narrowed && !trusted && browserBundle) {
138
+ await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
139
+ await RouteClientBuilder.#removeChunks(narrowed.bundle, browserBundle);
140
+ }
92
141
  const referenceBundle = browserBundle ?? ssrBundle;
142
+ const bootstrapEntries = browserEntries ?? ssrEntries;
143
+ const ssrEntryByOriginal = new Map(
144
+ [...ssrEntries.originalByBuildEntry].map(([buildEntry, originalEntry]) => [originalEntry, buildEntry]),
145
+ );
93
146
 
94
147
  const acceptedEntries = new Set(entries);
95
148
  const routeEntries = new Set(discovered);
@@ -111,7 +164,9 @@ export class RouteClientBuilder {
111
164
  : bundleRow;
112
165
  manifestDelta[manifestEntry.key] = row;
113
166
 
114
- const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
167
+ const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(
168
+ ssrEntryByOriginal.get(manifestEntry.originalEntry) ?? manifestEntry.buildEntry,
169
+ );
115
170
  if (!ssrOutput) continue;
116
171
 
117
172
  ssrModuleMap[row.id] ??= {};
@@ -137,6 +192,7 @@ export class RouteClientBuilder {
137
192
  clientDepsByEntry,
138
193
  ...(registry ? { registryEntries: [...acceptedEntries].sort() } : {}),
139
194
  ...(browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}),
195
+ clientGraph: referenceBundle.graph.importsByModule,
140
196
  };
141
197
  }
142
198
 
@@ -165,23 +221,224 @@ export class RouteClientBuilder {
165
221
  };
166
222
  }
167
223
 
168
- async #buildBrowserBundle(bootstrapEntries: BootstrapEntries) {
224
+ async #readRouteRuntime(): Promise<RouteRuntime | null> {
225
+ const { name } = this.#app;
226
+ const whole = (why: string, first = "Run") => {
227
+ this.#app.logger.warn(
228
+ `[client-runtime] ${why}, so every page of this build loads the whole client runtime, not only what it uses. ${first} \`akan sync ${name}\` and build again.`,
229
+ );
230
+ return null;
231
+ };
232
+ const missing = `the per-module runtime files of ${name} or a lib it mounts are missing`;
233
+ if ((await StoreBootstrap.scopeOf(this.#app)) !== "page") return whole(missing);
234
+ try {
235
+ return (await RouteRuntime.read(this.#app.workspace.workspaceRoot, `apps/${name}`)) ?? whole(missing);
236
+ } catch (error) {
237
+ const reason = error instanceof Error ? error.message : String(error);
238
+ return whole(`the modules of ${name} or a lib it mounts could not be read (${reason})`, "Fix that, then run");
239
+ }
240
+ }
241
+
242
+ async #buildNarrowed(
243
+ entries: string[],
244
+ whole: BootstrapEntries,
245
+ runtime: RouteRuntime,
246
+ planned: RouteRuntimeBundle,
247
+ ): Promise<NarrowedBuild> {
248
+ const bundleOf: BundleOf = async (routeRuntime, kept, outputSubdir) => {
249
+ const started = Date.now();
250
+ const browserEntries = await this.#createBootstrapEntries(entries, "page", { kept, whole });
251
+ const bundle = await this.#buildBrowserBundle(browserEntries, routeRuntime, outputSubdir);
252
+ this.#app.verbose(`[client-runtime] bundled ${outputSubdir ?? "client"} (${Date.now() - started}ms)`);
253
+ return { entries: browserEntries, kept, bundle, runtime: routeRuntime };
254
+ };
255
+ const first = await bundleOf(runtime, runtime.plan(planned));
256
+ const routes = this.#entriesByRoute;
257
+ if (!routes || !runtime.decided) return first;
258
+ const perModuleIn = ({ kept }: NarrowedBuild) =>
259
+ [...routes].filter(([, held]) => !held.some((entry) => kept.has(entry))).map(([route]) => route);
260
+ const analysed = perModuleIn(first);
261
+ const { built, refused } =
262
+ analysed.length > 0
263
+ ? await this.#keptWhereNotSmaller(first, routes, planned, bundleOf)
264
+ : { built: first, refused: [] };
265
+ const perModule = perModuleIn(built);
266
+ return {
267
+ ...built,
268
+ report: {
269
+ app: this.#app.name,
270
+ routes: routes.size,
271
+ perModule,
272
+ notSmaller: analysed.filter((route) => !perModule.includes(route)),
273
+ refused,
274
+ causes: built.runtime.decided?.causes() ?? [],
275
+ },
276
+ };
277
+ }
278
+
279
+ async #say(report: RouteRuntimeBuildReport) {
280
+ await RouteRuntimeReport.write(this.#app.cwdPath, report);
281
+ this.#app.log(`[client-runtime] ${RouteRuntimeReport.summary(report)}`);
282
+ for (const route of report.notSmaller) this.#app.verbose(`[client-runtime] not smaller per module: ${route}`);
283
+ for (const route of report.refused ?? [])
284
+ this.#app.verbose(`[client-runtime] larger with the whole runtime here: ${route}`);
285
+ for (const route of report.perModule) this.#app.verbose(`[client-runtime] per module: ${route}`);
286
+ }
287
+
288
+ static async #removeChunks(replaced: NarrowedBuild["bundle"], served: NarrowedBuild["bundle"]) {
289
+ for (const chunk of replaced.graph.importsByChunk.keys())
290
+ if (!served.graph.importsByChunk.has(chunk)) await rm(chunk, { force: true });
291
+ }
292
+
293
+ //? A pass either keeps entries or refuses some for good, and neither set ever loses one, so the passes end.
294
+ async #keptWhereNotSmaller(
295
+ first: NarrowedBuild,
296
+ routes: ReadonlyMap<string, readonly string[]>,
297
+ planned: RouteRuntimeBundle,
298
+ bundleOf: BundleOf,
299
+ ): Promise<{ built: NarrowedBuild; refused: string[] }> {
300
+ const pays = new RouteRuntimePays();
301
+ const sizesOf = (build: NarrowedBuild) => pays.sizesOf(build.bundle, this.#sizedBuildEntries(build.entries));
302
+ //? A keep is never taken back, so a build that did not pay is replaced from a runtime read again.
303
+ const bundleWith = async (verdicts: readonly RoutePaysVerdict[], last: NarrowedBuild | null, subdir?: string) => {
304
+ const runtime = await this.#readRouteRuntime();
305
+ if (!runtime) return null;
306
+ let kept = runtime.plan(planned);
307
+ for (const { entry, ...measured } of verdicts) kept = runtime.keep([entry], { rule: "not-smaller", ...measured });
308
+ const build = await bundleOf(runtime, subdir ? runtime.keepAll() : kept, subdir);
309
+ if (last) await RouteClientBuilder.#removeChunks(last.bundle, build.bundle);
310
+ return build;
311
+ };
312
+ const reference = await bundleWith([], null, referenceSubdir);
313
+ if (!reference) return { built: first, refused: [] };
314
+ const wholeSizes = await sizesOf(reference);
315
+ await rm(path.join(this.#artifactDir, referenceSubdir), { recursive: true, force: true });
316
+ let current = { build: first, sizes: await sizesOf(first), verdicts: [] as RoutePaysVerdict[] };
317
+ let onDisk = first;
318
+ const refused = new Set<string>();
319
+ const refusedRoutes = new Set<string>();
320
+ for (let trial = 0; trial < measuredTrials; trial++) {
321
+ const verdicts = RouteRuntimePays.decide({
322
+ entriesByRoute: routes,
323
+ isKept: (entry) => current.build.kept.has(entry),
324
+ isRefused: (entry) => refused.has(entry),
325
+ whole: wholeSizes,
326
+ measured: current.sizes,
327
+ });
328
+ if (verdicts.length === 0) break;
329
+ const tried = await bundleWith([...current.verdicts, ...verdicts], onDisk);
330
+ if (!tried) break;
331
+ onDisk = tried;
332
+ const sizes = await sizesOf(tried);
333
+ const larger = RouteRuntimePays.larger({
334
+ entriesByRoute: routes,
335
+ wasKept: (entry) => current.build.kept.has(entry),
336
+ isKept: (entry) => tried.kept.has(entry),
337
+ before: current.sizes,
338
+ after: sizes,
339
+ });
340
+ if (larger.length === 0) {
341
+ current = { build: tried, sizes, verdicts: [...current.verdicts, ...verdicts] };
342
+ continue;
343
+ }
344
+ for (const route of larger) {
345
+ refusedRoutes.add(route);
346
+ for (const entry of routes.get(route) ?? []) refused.add(entry);
347
+ }
348
+ if (!verdicts.some(({ entry }) => refused.has(entry))) for (const { entry } of verdicts) refused.add(entry);
349
+ }
350
+ const built = onDisk === current.build ? onDisk : ((await bundleWith(current.verdicts, onDisk)) ?? onDisk);
351
+ return { built, refused: [...refusedRoutes] };
352
+ }
353
+
354
+ get #artifactDir() {
355
+ return path.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
356
+ }
357
+
358
+ #sizedBuildEntries({ originalByBuildEntry }: BootstrapEntries): Map<string, string[]> {
359
+ const buildEntryOf = new Map([...originalByBuildEntry].map(([buildEntry, original]) => [original, buildEntry]));
360
+ return new Map(
361
+ [...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) => [
362
+ route,
363
+ held.map((entry) => buildEntryOf.get(path.resolve(entry)) ?? path.resolve(entry)),
364
+ ]),
365
+ );
366
+ }
367
+
368
+ #check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
369
+ const { workspaceRoot } = this.#app.workspace;
370
+ const buildEntryOf = new Map(
371
+ [...entries.originalByBuildEntry].map(([buildEntry, original]) => [original, buildEntry]),
372
+ );
373
+ const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
374
+ entries: new Map([...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry))),
375
+ wholeReaders: routeRuntime.wholeReaders,
376
+ wholeConstantReaders: routeRuntime.wholeConstantReaders,
377
+ routes: new Map(
378
+ [...(this.#entriesByRoute ?? [])].map(([route, held]) => [
379
+ route,
380
+ held.map((entry) => buildEntryOf.get(path.resolve(entry)) ?? path.resolve(entry)),
381
+ ]),
382
+ ),
383
+ });
384
+ const { refusal, repeated } = check;
385
+ if (refusal) {
386
+ this.#app.logger.warn(refusal);
387
+ return false;
388
+ }
389
+ if (repeated.length === 0) return true;
390
+ const more = repeated.length - RouteRuntimeCheck.shown;
391
+ this.#app.logger.warn(
392
+ [
393
+ `[client-runtime] a page keeping the whole runtime loads a piece of what that runtime already holds:`,
394
+ ...repeated.slice(0, RouteRuntimeCheck.shown).map((line) => ` - ${line}`),
395
+ ...(more > 0 ? [` - and ${more} more`] : []),
396
+ ].join("\n"),
397
+ );
398
+ return true;
399
+ }
400
+
401
+ async #buildBrowserBundle(
402
+ bootstrapEntries: BootstrapEntries,
403
+ routeRuntime: RouteRuntime | null,
404
+ outputSubdir?: string,
405
+ ) {
169
406
  const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
407
+ const icons = ReactIconImports.forApp(this.#app);
408
+ const vendorFiles = await VendorFileImports.of(this.#app.workspace.workspaceRoot);
170
409
  return new ClientEntriesBundler({
171
410
  app: this.#app,
172
411
  entries: bootstrapEntries.buildEntries,
173
412
  plugins: [
413
+ icons.plugin,
414
+ ...(routeRuntime ? [this.#signalDescriptors(routeRuntime)] : []),
415
+ vendorFiles.plugin(),
174
416
  await createBarrelImportsPlugin(this.#app, {
175
- pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
176
- external: VENDOR_SPECIFIERS,
417
+ pipeAfter: icons.pipe(
418
+ reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
419
+ ),
420
+ external: vendorFiles.specifiers,
421
+ routeRuntime,
177
422
  }),
178
423
  ],
179
- external: VENDOR_SPECIFIERS,
424
+ external: vendorFiles.specifiers,
180
425
  command: this.#command,
181
426
  reactFastRefresh,
427
+ ...(outputSubdir ? { outputSubdir } : {}),
182
428
  }).bundle();
183
429
  }
184
430
 
431
+ #signalDescriptors(routeRuntime: RouteRuntime) {
432
+ const scopes = routeRuntime.table.layers.map(({ scope }) => scope);
433
+ return new SignalDescriptors(this.#app.workspace.workspaceRoot, scopes, {
434
+ onUnread: (reason) =>
435
+ this.#app.logger.warn(
436
+ `[client-runtime] ${reason}, so each of their pieces reads its signal again: a slower build of the same pages. Run \`akan sync ${this.#app.name}\` if their generated files are from an earlier release.`,
437
+ ),
438
+ takenFromPieces: (absPath) => routeRuntime.takenFromPieces(absPath),
439
+ }).plugin;
440
+ }
441
+
185
442
  async #buildSsrBundle(bootstrapEntries: BootstrapEntries) {
186
443
  return new ClientEntriesBundler({
187
444
  app: this.#app,
@@ -193,18 +450,32 @@ export class RouteClientBuilder {
193
450
  }).bundle();
194
451
  }
195
452
 
196
- async #createBootstrapEntries(entries: string[]): Promise<BootstrapEntries> {
453
+ //? `narrowed.kept`: an entry keeping the whole runtime is the same file a build of every page on it bundles.
454
+ async #createBootstrapEntries(
455
+ entries: string[],
456
+ scope: ClientRuntimeScope,
457
+ narrowed?: { kept: ReadonlySet<string>; whole: BootstrapEntries },
458
+ ): Promise<BootstrapEntries> {
197
459
  if (!(await Bun.file(path.join(this.#app.cwdPath, "lib", "st.ts")).exists())) {
198
460
  return { buildEntries: entries, originalByBuildEntry: new Map() };
199
461
  }
462
+ const wholeByOriginal = new Map(
463
+ [...(narrowed?.whole.originalByBuildEntry ?? [])].map(([buildEntry, original]) => [original, buildEntry]),
464
+ );
200
465
 
201
- const outdir = path.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
466
+ const dirName = scope === "page" ? "client-entry-bootstrap-route" : "client-entry-bootstrap";
467
+ const outdir = path.join(this.#app.cwdPath, ".akan", "generated", dirName);
202
468
  await mkdir(outdir, { recursive: true });
203
469
 
204
470
  const originalByBuildEntry = new Map<string, string>();
205
471
  const buildEntries = await Promise.all(
206
472
  entries.map(async (entry) => {
207
473
  const absEntry = path.resolve(entry);
474
+ const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
475
+ if (whole) {
476
+ originalByBuildEntry.set(whole, absEntry);
477
+ return whole;
478
+ }
208
479
  const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
209
480
  const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
210
481
  const wrapperEntry = path.join(outdir, `${base}-${hash}.tsx`);
@@ -215,6 +486,7 @@ export class RouteClientBuilder {
215
486
  appName: this.#app.name,
216
487
  originalEntry: absEntry,
217
488
  exportNames,
489
+ scope,
218
490
  }),
219
491
  );
220
492
  originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
@@ -317,11 +589,12 @@ export class RouteClientBuilder {
317
589
  appName: string;
318
590
  originalEntry: string;
319
591
  exportNames: string[];
592
+ scope?: ClientRuntimeScope;
320
593
  }): string {
321
594
  const originalEntry = JSON.stringify(path.resolve(args.originalEntry));
322
595
  const namedExports = args.exportNames.filter((name) => name !== "default");
323
596
  const lines = [
324
- ...StoreBootstrap.importLines(args.appName),
597
+ ...StoreBootstrap.importLines(args.appName, args.scope),
325
598
  ...(namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []),
326
599
  ];
327
600
  if (args.exportNames.includes("default")) lines.push(`export { default } from ${originalEntry};`);