@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
@@ -1,19 +1,24 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { realpath } from "node:fs/promises";
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import { readdir, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { tempDirs, writeText as write } from "../test/testHelpers";
4
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
5
+ import { RouteRuntimeReport } from "../quality/routeRuntimeReport";
6
+ import { printedInOwnProcess, tempDirs, writeText as write } from "../test/testHelpers";
5
7
  import { createTsconfigPackageResolver } from "../transforms/barrelImportsPlugin";
8
+ import { ModelReference } from "../transforms/modelReference";
9
+ import { RouteRuntime } from "../transforms/routeRuntime";
6
10
  import { CLIENT_BUNDLE_NAMING } from "./clientBuildTypes";
7
11
  import { ClientEntriesBundler } from "./clientEntriesBundler";
8
12
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
9
13
  import { RouteClientBuilder } from "./routeClientBuilder";
14
+ import { RouteModulePreloads } from "./routeModulePreloads";
10
15
 
11
16
  const makeTempRoot = tempDirs("akan-client-entry-");
12
17
 
13
18
  const fixtureBarrels = ["@apps/demo/client", "@libs/kit/client"];
14
19
 
15
- const writeBarrelFixture = async () => {
16
- const root = await makeTempRoot();
20
+ const writeBarrelFixture = async (rootDir?: string) => {
21
+ const root = rootDir ?? (await makeTempRoot());
17
22
  const appDir = path.join(root, "apps/demo");
18
23
  const libDir = path.join(root, "libs/kit");
19
24
  const paths = { "@apps/*": ["./apps/*"], "@libs/*": ["./libs/*"] };
@@ -79,10 +84,20 @@ const writeBarrelFixture = async () => {
79
84
  getConfig: async () => ({ barrelImports: fixtureBarrels, optimizeImports: [] }),
80
85
  getTsConfig: async () => ({ compilerOptions: { paths } }),
81
86
  getPublicEnv: () => ({}),
87
+ logger: { warn: () => undefined },
82
88
  } as never;
83
89
  return { root, appDir, app };
84
90
  };
85
91
 
92
+ const signalFixture = `const serialized = { draft: { endpoint: { draftOf: { type: "query", args: [], returns: { refName: "draft-descriptor-ref" } } } } };
93
+ export const fetch = { ownSerializedSignal: serialized };
94
+ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : { [name]: serialized[name as "draft"] });
95
+ `;
96
+
97
+ const signalPiece = `import { getSerializedSignalOf } from "../sig" with { type: "macro" };
98
+ export const descriptors = getSerializedSignalOf("draft");
99
+ `;
100
+
86
101
  const bundledText = async (dir: string) =>
87
102
  (
88
103
  await Promise.all([...new Bun.Glob("**/*.js").scanSync(dir)].map((file) => Bun.file(path.join(dir, file)).text()))
@@ -232,6 +247,7 @@ describe("route client store bootstrap", () => {
232
247
  getConfig: async () => ({ barrelImports: [], optimizeImports: [] }),
233
248
  getTsConfig: async () => ({ compilerOptions: { paths: {} } }),
234
249
  getPublicEnv: () => ({}),
250
+ logger: { warn: () => undefined },
235
251
  } as never;
236
252
  const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, async () => null);
237
253
  const build = (seeds: string[], knownEntries: Set<string>) =>
@@ -386,6 +402,498 @@ describe("route client store bootstrap", () => {
386
402
  ]);
387
403
  });
388
404
 
405
+ describe("loading per module", () => {
406
+ const routeFixture = async () => {
407
+ const fixture = await writeBarrelFixture(await realpath(await makeTempRoot()));
408
+ await write(
409
+ path.join(fixture.appDir, `lib/${StoreBootstrap.pageRuntime}.ts`),
410
+ 'export const mark = Object.freeze({ mark: "page-runtime-only" });\n',
411
+ );
412
+ await write(
413
+ path.join(fixture.appDir, `lib/${StoreBootstrap.baseDescriptors}.ts`),
414
+ 'export const base = Object.freeze({ mark: "base-descriptors" });\n',
415
+ );
416
+ await write(path.join(fixture.appDir, `lib/${ModelReference.registry}.ts`), "export {};\n");
417
+ for (const file of StoreBootstrap.assembled)
418
+ await write(
419
+ path.join(fixture.appDir, `lib/${file}.ts`),
420
+ `export const st = Object.freeze({ mark: "assembled:${file}" });\nexport const { fetch, sig } = st as never;\n`,
421
+ );
422
+ const akanjsRoot = path.dirname(Bun.resolveSync("akanjs/package.json", import.meta.dir));
423
+ for (const file of ["package.json", "store/baseSt.ts", "signal/base.signal.ts", "signal/agent.signal.ts"])
424
+ await write(
425
+ path.join(fixture.root, "node_modules/akanjs", file),
426
+ await Bun.file(path.join(akanjsRoot, file)).text(),
427
+ );
428
+ const warnings: string[] = [];
429
+ const said: string[] = [];
430
+ const app = {
431
+ ...(fixture.app as object),
432
+ logger: { warn: (message: string) => warnings.push(message) },
433
+ log: (message: string) => said.push(message),
434
+ verbose: () => undefined,
435
+ } as never;
436
+ return { ...fixture, app, warnings, said };
437
+ };
438
+ const build = (app: never, entry: string) =>
439
+ new RouteClientBuilder({ app, seeds: [], entries: [entry], artifact: {} as never, browser: "chunks" }).build();
440
+
441
+ test("a store-free route's browser chunks carry the page runtime and the framework's own descriptors, its SSR chunks the whole runtime", async () => {
442
+ const { appDir, app, warnings } = await routeFixture();
443
+ const entry = path.join(appDir, "ui/A.tsx");
444
+
445
+ const result = await build(app, entry);
446
+
447
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
448
+ const ssr = await bundledText(path.join(appDir, ".akan/artifact/client-ssr"));
449
+ for (const marker of ["page-runtime-only", "base-descriptors"]) expect(browser).toContain(marker);
450
+ for (const marker of ['"runtime-marker"', '"store-marker"', "lib-store-marker"])
451
+ expect(browser).not.toContain(marker);
452
+ for (const marker of ['"runtime-marker"', '"store-marker"', "lib-store-marker"]) expect(ssr).toContain(marker);
453
+ expect(warnings).toEqual([]);
454
+ expect(Object.keys(result.manifestDelta)).toEqual(["apps/demo/ui/A.tsx#A"]);
455
+ const row = result.manifestDelta["apps/demo/ui/A.tsx#A"];
456
+ expect(result.ssrManifestDelta.moduleMap[row?.id ?? ""]?.A?.id).toContain(`${path.sep}client-ssr${path.sep}`);
457
+ });
458
+
459
+ const assembledMarkers = StoreBootstrap.assembled.map((file) => `assembled:${file}`);
460
+
461
+ test("a framework file importing the model runtime marker keeps the whole runtime a build of every module loads", async () => {
462
+ const { root, appDir, app } = await routeFixture();
463
+ const entry = path.join(root, "node_modules/akanjs/ui/Data/List.tsx");
464
+ await write(path.join(root, "node_modules/akanjs/ui/modelRuntime.ts"), "export {};\n");
465
+ await write(entry, '"use client";\nimport "../modelRuntime";\nexport const List = () => "list-marker";\n');
466
+
467
+ await build(app, entry);
468
+
469
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
470
+ for (const marker of ["list-marker", '"runtime-marker"', '"store-marker"']) expect(browser).toContain(marker);
471
+ for (const marker of assembledMarkers) expect(browser).not.toContain(marker);
472
+ });
473
+
474
+ test("a file reading a store by a name picked at run time keeps the whole runtime, with no copy assembled from pieces", async () => {
475
+ const { appDir, app } = await routeFixture();
476
+ const entry = path.join(appDir, "ui/Pick.tsx");
477
+ await write(
478
+ entry,
479
+ '"use client";\nimport { st } from "@apps/demo/client";\nexport const Pick = (name: string) => [st.use[name], "pick-marker"];\n',
480
+ );
481
+
482
+ await build(app, entry);
483
+
484
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
485
+ for (const marker of ["pick-marker", '"runtime-marker"', '"store-marker"']) expect(browser).toContain(marker);
486
+ for (const marker of assembledMarkers) expect(browser).not.toContain(marker);
487
+ });
488
+
489
+ const writeStorePieces = async (appDir: string) => {
490
+ for (const [name, key] of [
491
+ ["draft", "draftText"],
492
+ ["tally", "tallyCount"],
493
+ ]) {
494
+ await write(
495
+ path.join(appDir, `lib/_${name}/${name}.store.ts`),
496
+ `import { store } from "akanjs/store";\nexport class ${name}Store extends store("${name}" as const, () => ({ ${key}: 0 })) {}\n`,
497
+ );
498
+ await write(
499
+ path.join(appDir, `lib/__client/${name}.st.ts`),
500
+ `export const ${name} = Object.freeze({ mark: "piece:${name}.st" });\n(globalThis as { pieces?: unknown[] }).pieces?.push(${name});\n`,
501
+ );
502
+ }
503
+ await write(
504
+ path.join(appDir, `lib/${StoreBootstrap.pageRuntime}.ts`),
505
+ 'export const st = Object.freeze({ mark: "page-runtime-only", use: { draftText: () => 0 } });\n',
506
+ );
507
+ };
508
+ const writeDraftEntry = async (appDir: string) => {
509
+ const entry = path.join(appDir, "ui/Draft.tsx");
510
+ await write(
511
+ entry,
512
+ '"use client";\nimport { st } from "@apps/demo/client";\nexport const Draft = () => [st.use.draftText(), "draft-ui-marker"];\n',
513
+ );
514
+ return entry;
515
+ };
516
+ const wholeOrOtherPieces = ["piece:tally.st", ...assembledMarkers, '"runtime-marker"', '"store-marker"'];
517
+
518
+ test("a file naming one module's state brings that module's store piece, no other module's and no assembled runtime", async () => {
519
+ const { appDir, app } = await routeFixture();
520
+ await writeStorePieces(appDir);
521
+
522
+ await build(app, await writeDraftEntry(appDir));
523
+
524
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
525
+ for (const marker of ["draft-ui-marker", "page-runtime-only", "piece:draft.st"])
526
+ expect(browser).toContain(marker);
527
+ for (const marker of wholeOrOtherPieces) expect(browser).not.toContain(marker);
528
+ });
529
+
530
+ test("a file importing one module's store piece by hand brings that piece and keeps the whole runtime", async () => {
531
+ const { appDir, app } = await routeFixture();
532
+ await writeStorePieces(appDir);
533
+ const entry = path.join(appDir, "ui/Hand.tsx");
534
+ await write(
535
+ entry,
536
+ '"use client";\nimport "@apps/demo/lib/__client/draft.st";\nexport const Hand = () => "hand-ui-marker";\n',
537
+ );
538
+
539
+ await build(app, entry);
540
+
541
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
542
+ for (const marker of ["hand-ui-marker", "piece:draft.st", '"runtime-marker"', '"store-marker"'])
543
+ expect(browser).toContain(marker);
544
+ for (const marker of ["piece:tally.st", ...assembledMarkers]) expect(browser).not.toContain(marker);
545
+ });
546
+
547
+ describe("a build told which entries each route loads", () => {
548
+ const seen = "((globalThis as { __akanSeen?: string[] }).__akanSeen ??= [])";
549
+ const weightOf = (hashes: number, salt: string) =>
550
+ hashes > 0
551
+ ? `(globalThis as { __akanWeight?: string[] }).__akanWeight = ["${Array.from({ length: hashes }, (_, index) => Bun.hash(`${salt}-${index}`).toString(36)).join("")}"];\n`
552
+ : "";
553
+ const describedSignal = `const serialized = {
554
+ draft: { endpoint: { draftOf: { type: "query", args: [], returns: { refName: "draft-descriptor-ref" } } } },
555
+ tally: { endpoint: { tallyOf: { type: "query", args: [], returns: { refName: "tally-descriptor-ref" } } } },
556
+ };
557
+ export const fetch = { ownSerializedSignal: serialized };
558
+ export const getSerializedSignal = () => serialized;
559
+ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : { [name]: serialized[name as "draft"] });
560
+ `;
561
+ const picking =
562
+ '"use client";\nimport { st } from "@apps/demo/client";\nexport const Pick = (name: string) => [st.use[name], "pick-marker"];\n';
563
+ const namingDraft =
564
+ 'import { st } from "@apps/demo/client";\nexport const shared = () => [st.use.draftText(), "shared-marker"];\n';
565
+ const describedFixture = async ({ whole = 600, draft = 0, tally = 0 } = {}) => {
566
+ const fixture = await routeFixture();
567
+ const { appDir } = fixture;
568
+ await writeStorePieces(appDir);
569
+ await write(path.join(appDir, "lib/sig.ts"), describedSignal);
570
+ await write(path.join(fixture.root, "libs/kit/lib/sig.ts"), signalFixture);
571
+ for (const [facet, source] of [
572
+ ["base", "export const loadedAfter = (..._modules: unknown[]): void => {};\n"],
573
+ ["store", "export const st = { use: {} };\nexport const store = (..._args: unknown[]) => class {};\n"],
574
+ ])
575
+ await write(path.join(fixture.root, `node_modules/akanjs/${facet}/index.ts`), source);
576
+ for (const [file, name] of [
577
+ ["_base", "base"],
578
+ ["draft", "draft"],
579
+ ["tally", "tally"],
580
+ ])
581
+ await write(
582
+ path.join(appDir, `lib/__client/${file}.fetch.ts`),
583
+ `import { getSerializedSignalOf } from "../sig" with { type: "macro" };\nexport const loaded = getSerializedSignalOf("${name}");\n${seen}.push(...Object.keys(loaded).map((key) => "piece:" + key));\n`,
584
+ );
585
+ await write(
586
+ path.join(appDir, "lib/useClient.ts"),
587
+ `import { getSerializedSignal } from "./sig" with { type: "macro" };\nconst whole = getSerializedSignal();\n${seen}.push(...Object.keys(whole).map((key) => "whole:" + key));\nexport const { msg, Err, usePage, fetch, sig } = { usePage: () => "page" } as Record<string, unknown>;\n`,
588
+ );
589
+ await write(
590
+ path.join(appDir, "lib/st.ts"),
591
+ `export class RootStore {}\nexport const st = Object.freeze({ mark: "store-marker" });\n${weightOf(whole, "whole")}`,
592
+ );
593
+ for (const [name, hashes] of Object.entries({ draft, tally }))
594
+ await write(
595
+ path.join(appDir, `lib/__client/${name}.st.ts`),
596
+ `export const ${name} = Object.freeze({ mark: "piece:${name}.st" });\n${weightOf(hashes, name)}`,
597
+ );
598
+ const file = (name: string) => path.join(appDir, `ui/${name}.tsx`);
599
+ const buildRoutes = async (routes: Record<string, string[]>) => {
600
+ const entriesByRoute = new Map(Object.entries(routes));
601
+ const entries = [...new Set(Object.values(routes).flat())];
602
+ const result = await new RouteClientBuilder({
603
+ app: fixture.app,
604
+ seeds: [],
605
+ entries,
606
+ artifact: {} as never,
607
+ browser: "chunks",
608
+ entriesByRoute,
609
+ }).build();
610
+ const clientOut = path.join(appDir, ".akan/artifact/client");
611
+ const state = globalThis as { __akanSeen?: string[]; $RefreshReg$?: unknown; $RefreshSig$?: unknown };
612
+ const seenNow = () => [...(state.__akanSeen ?? [])].sort();
613
+ const load = async (route: string) => {
614
+ state.__akanSeen = [];
615
+ state.$RefreshReg$ ??= () => undefined;
616
+ state.$RefreshSig$ ??= () => (type: unknown) => type;
617
+ const ids = new Set(
618
+ (routes[route] ?? []).map((entry) => `${path.relative(fixture.root, entry).split(path.sep).join("/")}#`),
619
+ );
620
+ const exported: Record<string, unknown> = {};
621
+ for (const [key, row] of Object.entries(result.manifestDelta))
622
+ if ([...ids].some((id) => key.startsWith(id)))
623
+ Object.assign(exported, await import(path.join(clientOut, path.basename(row.chunks[0] ?? ""))));
624
+ return exported;
625
+ };
626
+ const run = async (route: string) => {
627
+ await load(route);
628
+ return seenNow();
629
+ };
630
+ return { browser: await bundledText(clientOut), run, load, seenNow };
631
+ };
632
+ return { ...fixture, file, buildRoutes };
633
+ };
634
+ const timesIn = (text: string, marker: string) => text.split(marker).length - 1;
635
+ const mixed =
636
+ "[client-runtime] 1 route loads per module, 0 keep the whole runtime because per module would not be smaller, 1 keeps it for a reason `akan quality runtime` names";
637
+
638
+ test("a route with an entry keeping the whole runtime and a narrowed entry sharing a file holds each module's descriptors once, and runs them once", async () => {
639
+ const { file, buildRoutes, warnings, said } = await describedFixture();
640
+ await write(file("Shared"), namingDraft);
641
+ await write(file("Pick"), `${picking}export { shared } from "./Shared";\n`);
642
+ await write(
643
+ file("Draft"),
644
+ '"use client";\nimport { shared } from "./Shared";\nexport const Draft = () => [shared, "draft-ui-marker"];\n',
645
+ );
646
+
647
+ const { browser, run } = await buildRoutes({
648
+ "/pick": [file("Pick"), file("Draft")],
649
+ "/draft": [file("Draft")],
650
+ });
651
+
652
+ expect(said).toEqual([mixed]);
653
+ expect(warnings).toEqual([]);
654
+ for (const marker of ["draft-descriptor-ref", "tally-descriptor-ref"]) expect(timesIn(browser, marker)).toBe(1);
655
+ expect(await run("/pick")).toEqual(["piece:draft", "whole:tally"]);
656
+ expect(await run("/draft")).toEqual([]);
657
+ }, 30_000);
658
+
659
+ test("a page loading per module that asks with import() for a file needing every module gets the whole runtime then, and no module's descriptors twice", async () => {
660
+ const { file, buildRoutes, warnings, said } = await describedFixture();
661
+ await write(file("Shared"), namingDraft);
662
+ await write(
663
+ file("Later"),
664
+ 'import { st } from "@apps/demo/client";\nexport const later = (name: string) => [st.use[name], "later-marker"];\n',
665
+ );
666
+ await write(
667
+ file("Draft"),
668
+ '"use client";\nimport { shared } from "./Shared";\nexport const Draft = () => [shared, "draft-ui-marker"];\nexport const ask = () => import("./Later");\n',
669
+ );
670
+
671
+ const { browser, load, seenNow } = await buildRoutes({ "/draft": [file("Draft")] });
672
+
673
+ expect(said).toEqual([
674
+ "[client-runtime] 1 route loads per module, 0 keep the whole runtime because per module would not be smaller",
675
+ ]);
676
+ expect(warnings).toEqual([]);
677
+ for (const marker of ["draft-descriptor-ref", "tally-descriptor-ref"]) expect(timesIn(browser, marker)).toBe(1);
678
+ const { ask } = (await load("/draft")) as { ask: () => Promise<unknown> };
679
+ expect(seenNow()).toEqual(["piece:draft"]);
680
+ await ask();
681
+ expect(seenNow()).toEqual(["piece:draft", "whole:tally"]);
682
+ }, 30_000);
683
+
684
+ test("a reference handed over on a whole page and on a page loading per module brings no second copy to the whole page", async () => {
685
+ const { appDir, file, buildRoutes, warnings, said } = await describedFixture();
686
+ await write(
687
+ path.join(appDir, "lib/_draft/draft.store.ts"),
688
+ 'import { store } from "akanjs/store";\nexport class draftStore extends store("draft" as const, () => ({ draftText: 0, draft: null })) {}\n',
689
+ );
690
+ const reference = path.join(appDir, "lib/__client/draft.ref.ts");
691
+ await write(reference, '"use client";\n\nexport const reference = "draft";\n');
692
+ await write(file("Pick"), picking);
693
+ await write(file("Plain"), '"use client";\nexport const Plain = () => "plain-ui-marker";\n');
694
+
695
+ const { browser } = await buildRoutes({
696
+ "/pick": [file("Pick"), reference],
697
+ "/plain": [file("Plain"), reference],
698
+ });
699
+
700
+ expect(said).toEqual([mixed]);
701
+ expect(warnings).toEqual([]);
702
+ expect(browser).toContain("piece:draft.st");
703
+ expect(timesIn(browser, "draft-descriptor-ref")).toBe(1);
704
+ }, 30_000);
705
+
706
+ test("a route that would be no smaller loading per module keeps the whole runtime, and the build it was measured against leaves nothing behind", async () => {
707
+ const { appDir, file, buildRoutes, warnings, said } = await describedFixture({ whole: 0, draft: 600 });
708
+ await write(file("Draft"), `"use client";\n${namingDraft}`);
709
+
710
+ const { browser, run } = await buildRoutes({ "/draft": [file("Draft")] });
711
+
712
+ expect(said).toEqual([
713
+ "[client-runtime] 0 routes load per module, 1 keeps the whole runtime because per module would not be smaller",
714
+ ]);
715
+ expect(warnings).toEqual([]);
716
+ expect(browser).toContain("shared-marker");
717
+ expect(browser).not.toContain("piece:draft.st");
718
+ expect(await run("/draft")).toEqual(["whole:draft", "whole:tally"]);
719
+ expect(await Bun.file(path.join(appDir, ".akan/artifact/client-whole")).exists()).toBe(false);
720
+ expect((await readdir(path.join(appDir, ".akan/artifact"))).sort()).toEqual(["client", "client-ssr"]);
721
+ }, 30_000);
722
+
723
+ test("a route no smaller per module than where every page is whole, yet larger still keeping the whole runtime beside a page that loads per module, loads per module", async () => {
724
+ const { appDir, file, buildRoutes, warnings, said } = await describedFixture({
725
+ whole: 500,
726
+ draft: 450,
727
+ tally: 100,
728
+ });
729
+ await write(file("Shared"), namingDraft);
730
+ await write(file("Draft"), '"use client";\nexport { shared } from "./Shared";\n');
731
+ await write(
732
+ file("Board"),
733
+ '"use client";\nimport { st } from "@apps/demo/client";\nimport { shared } from "./Shared";\nexport const Board = () => [shared, st.use.tallyCount(), "board-marker"];\n',
734
+ );
735
+
736
+ const { browser } = await buildRoutes({ "/draft": [file("Draft")], "/board": [file("Board")] });
737
+
738
+ expect(said).toEqual([
739
+ "[client-runtime] 2 routes load per module, 0 keep the whole runtime because per module would not be smaller",
740
+ ]);
741
+ expect(warnings).toEqual([]);
742
+ for (const marker of ["piece:draft.st", "piece:tally.st", "board-marker"]) expect(browser).toContain(marker);
743
+ expect(browser).not.toContain("store-marker");
744
+ const report = await Bun.file(path.join(appDir, RouteRuntimeReport.file)).json();
745
+ expect(report).toMatchObject({ perModule: ["/draft", "/board"], notSmaller: [], refused: ["/board"] });
746
+ }, 30_000);
747
+ });
748
+
749
+ test("the files a route is sized by hold the store piece of the module its client code names, and no assembled runtime", async () => {
750
+ const { root, appDir, app } = await routeFixture();
751
+ await writeStorePieces(appDir);
752
+ const entry = await writeDraftEntry(appDir);
753
+
754
+ const { manifestDelta } = await build(app, entry);
755
+
756
+ const sizedUrls = new RouteModulePreloads({
757
+ runtimeChunks: { runtime: [], vendors: {} },
758
+ entriesByRoute: new Map([["/:lang/draft", [entry]]]),
759
+ clientManifest: manifestDelta,
760
+ externalsByChunkUrl: {},
761
+ workspaceRoot: root,
762
+ }).modulesByRoute()["/:lang/draft"];
763
+ const sized = (
764
+ await Promise.all(
765
+ (sizedUrls ?? []).map((url) =>
766
+ Bun.file(path.join(appDir, ".akan/artifact", url.replace(/^\/_akan\//, ""))).text(),
767
+ ),
768
+ )
769
+ ).join("\n");
770
+ for (const marker of ["draft-ui-marker", "page-runtime-only", "piece:draft.st"]) expect(sized).toContain(marker);
771
+ for (const marker of wholeOrOtherPieces) expect(sized).not.toContain(marker);
772
+ });
773
+
774
+ test.each([
775
+ ["the object first", "Memo, cnst"],
776
+ ["the constants first", "cnst, Memo"],
777
+ ])(
778
+ "a file naming one component of an object and one constant, %s, brings that component's file and that model's registration, never every constant",
779
+ async (_, names) => {
780
+ const { appDir, app } = await routeFixture();
781
+ await write(
782
+ path.join(appDir, "client.ts"),
783
+ [
784
+ 'export * as cnst from "./lib/cnst";',
785
+ 'export { msg, Err, usePage } from "./lib/usePage";',
786
+ 'export { fetch, sig } from "./lib/useClient";',
787
+ 'export { st, RootStore } from "./lib/st";',
788
+ 'export { Memo } from "./lib/memo";',
789
+ "",
790
+ ].join("\n"),
791
+ );
792
+ await write(
793
+ path.join(appDir, "lib/memo/Memo.Zone.tsx"),
794
+ '"use client";\nexport const View = Object.freeze({ mark: "memo-view-marker" });\n',
795
+ );
796
+ await write(
797
+ path.join(appDir, "lib/memo/memo.constant.ts"),
798
+ 'export const MemoStatus = Object.freeze({ mark: "memo-status-marker" });\n',
799
+ );
800
+ await write(
801
+ path.join(appDir, "lib/__client/memo.cnst.ts"),
802
+ 'import * as cnst from "../memo/memo.constant";\nexport const memo = Object.freeze({ mark: "piece:memo.cnst", cnst });\n',
803
+ );
804
+ const entry = path.join(appDir, "ui/Status.tsx");
805
+ await write(
806
+ entry,
807
+ `"use client";\nimport { ${names} } from "@apps/demo/client";\nexport const Status = () => [Memo.Zone.View, cnst.MemoStatus, "status-ui-marker"];\n`,
808
+ );
809
+ await build(app, entry);
810
+
811
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
812
+ for (const marker of ["status-ui-marker", "memo-view-marker", "memo-status-marker", "piece:memo.cnst"])
813
+ expect(browser).toContain(marker);
814
+ for (const marker of ["cnst-marker", "other-ui-marker", ...assembledMarkers, '"runtime-marker"'])
815
+ expect(browser).not.toContain(marker);
816
+ },
817
+ );
818
+
819
+ for (const file of [StoreBootstrap.pageRuntime, StoreBootstrap.baseDescriptors, ...StoreBootstrap.assembled])
820
+ test(`an app not synced to lib/${file}.ts keeps the whole runtime in its browser chunks and is told to sync`, async () => {
821
+ const { appDir, app, warnings } = await routeFixture();
822
+ await Bun.file(path.join(appDir, `lib/${file}.ts`)).delete();
823
+
824
+ await build(app, path.join(appDir, "ui/A.tsx"));
825
+
826
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
827
+ for (const marker of ['"runtime-marker"', '"store-marker"']) expect(browser).toContain(marker);
828
+ expect(warnings).toEqual([expect.stringContaining("Run `akan sync demo`")]);
829
+ expect(warnings[0]).toContain("runtime files of demo or a lib it mounts are missing");
830
+ });
831
+
832
+ test("a route's browser build answers a module piece with descriptors read from the signal, not by its macro", async () => {
833
+ const { root, appDir } = await routeFixture();
834
+ for (const scope of ["apps/demo", "libs/kit"]) await write(path.join(root, scope, "lib/sig.ts"), signalFixture);
835
+ await write(path.join(appDir, "lib/__client/draft.fetch.ts"), signalPiece);
836
+ const entry = path.join(appDir, "ui/Fetch.tsx");
837
+ await write(
838
+ entry,
839
+ '"use client";\nimport { descriptors } from "@apps/demo/lib/__client/draft.fetch";\nexport const Fetch = () => descriptors;\n',
840
+ );
841
+
842
+ const built = await printedInOwnProcess(
843
+ `
844
+ const { RouteClientBuilder } = await import(${JSON.stringify(path.join(import.meta.dir, "routeClientBuilder.ts"))});
845
+ const { SignalDescriptors } = await import(${JSON.stringify(path.join(import.meta.dir, "../transforms/signalDescriptors.ts"))});
846
+ const [root, entry, barrelImports] = ${JSON.stringify([root, entry, fixtureBarrels])};
847
+ let answered = 0;
848
+ const inline = SignalDescriptors.prototype.inline;
849
+ SignalDescriptors.prototype.inline = async function (...args) {
850
+ const contents = await inline.apply(this, args);
851
+ if (contents !== null) answered += 1;
852
+ return contents;
853
+ };
854
+ const warnings = [];
855
+ const app = {
856
+ name: "demo",
857
+ cwdPath: root + "/apps/demo",
858
+ dist: { cwdPath: root + "/dist/apps/demo" },
859
+ workspace: { workspaceRoot: root },
860
+ getConfig: async () => ({ barrelImports, optimizeImports: [] }),
861
+ getTsConfig: async () => ({ compilerOptions: { paths: { "@apps/*": ["./apps/*"], "@libs/*": ["./libs/*"] } } }),
862
+ getPublicEnv: () => ({}),
863
+ logger: { warn: (message) => warnings.push(message) },
864
+ verbose: () => undefined,
865
+ };
866
+ await new RouteClientBuilder({ app, seeds: [], entries: [entry], artifact: {}, browser: "chunks" }).build();
867
+ console.log(JSON.stringify({ answered, warnings }));
868
+ `,
869
+ root,
870
+ );
871
+
872
+ expect(built).toEqual({ answered: 1, warnings: [] });
873
+ expect(await bundledText(path.join(appDir, ".akan/artifact/client"))).toContain("draft-descriptor-ref");
874
+ }, 30_000);
875
+
876
+ test("an app whose modules cannot be read keeps the whole runtime in its browser chunks and is told what failed", async () => {
877
+ const { appDir, app, warnings } = await routeFixture();
878
+ const read = spyOn(RouteRuntime, "read").mockRejectedValue(new Error("memo.store.ts is unreadable"));
879
+ try {
880
+ await build(app, path.join(appDir, "ui/A.tsx"));
881
+ } finally {
882
+ read.mockRestore();
883
+ }
884
+
885
+ const browser = await bundledText(path.join(appDir, ".akan/artifact/client"));
886
+ for (const marker of ['"runtime-marker"', '"store-marker"']) expect(browser).toContain(marker);
887
+ expect(warnings).toEqual([
888
+ expect.stringContaining(
889
+ "the modules of demo or a lib it mounts could not be read (memo.store.ts is unreadable)",
890
+ ),
891
+ ]);
892
+ expect(warnings[0]).toContain("Fix that, then run `akan sync demo` and build again.");
893
+ expect(warnings[0]).not.toContain("missing");
894
+ });
895
+ });
896
+
389
897
  test("a route reaching a lib's cnst through its client barrel carries no module UI", async () => {
390
898
  const { root, appDir, app } = await writeBarrelFixture();
391
899
 
@@ -428,14 +936,9 @@ describe("route client store bootstrap", () => {
428
936
  await write(uiEntry, 'export { ClientPathWrapper } from "./System/Client";\n');
429
937
  await write(clientEntry, '"use client";\nexport const ClientPathWrapper = () => null;\n');
430
938
 
431
- const entryFiles = new Map([
432
- ["akanjs/ui", uiEntry],
433
- ["akanjs/ui/System/Client.tsx", clientEntry],
434
- ]);
435
939
  const discovery = new GraphClientEntryDiscovery({ barrelImports: ["akanjs/ui"] }, async (specifier) => {
436
- const entryFile = entryFiles.get(specifier);
437
- if (!entryFile) return null;
438
- return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
940
+ if (specifier !== "akanjs/ui") return null;
941
+ return { pkgName: specifier, entryFile: uiEntry, pkgDir: path.dirname(uiEntry), preserveFilePath: true };
439
942
  });
440
943
 
441
944
  expect(await discovery.discover([seed])).toEqual([clientEntry]);
@@ -77,6 +77,21 @@ export interface BundleClientEntriesResult {
77
77
  externalsByChunkUrl: Map<string, string[]>;
78
78
  /** Workspace-relative client reference id per absolute source entry. */
79
79
  clientReferenceIdByAbsPath: Map<string, string>;
80
+ graph: ClientBundleGraph;
81
+ }
82
+
83
+ /** What one bundle linked, by absolute path: no import the bundle left external. */
84
+ export interface ClientBundleGraph {
85
+ importsByModule: Map<string, ClientModuleImport[]>;
86
+ chunksByModule: Map<string, string[]>;
87
+ /** Static imports only: a chunk loaded by `import()` runs after the chunk asking for it. */
88
+ importsByChunk: Map<string, string[]>;
89
+ }
90
+
91
+ export interface ClientModuleImport {
92
+ path: string;
93
+ /** Asked for by `import()`, so it loads when that call runs. */
94
+ lazy: boolean;
80
95
  }
81
96
 
82
97
  export type AkanConfig = Awaited<ReturnType<App["getConfig"]>>;
@@ -8,8 +8,10 @@ import {
8
8
  type BundleClientEntriesInternalOptions,
9
9
  type BundleClientEntriesResult,
10
10
  CLIENT_BUNDLE_NAMING,
11
+ type ClientBundleGraph,
11
12
  type ClientBundleTarget,
12
13
  type ClientManifest,
14
+ type ClientModuleImport,
13
15
  type MetafileInput,
14
16
  type MetafileOutput,
15
17
  type OpaqueEntryAliases,
@@ -102,9 +104,45 @@ export class ClientEntriesBundler {
102
104
  entryChunkUrlsByAbsPath: this.#entryChunkUrlsByAbsPath,
103
105
  externalsByChunkUrl: this.#collectExternalsByChunkUrl(),
104
106
  clientReferenceIdByAbsPath: this.#clientReferenceIdByAbsPath,
107
+ graph: this.#graph(),
105
108
  };
106
109
  }
107
110
 
111
+ #graph(): ClientBundleGraph {
112
+ const absByInput = new Map<string, string>();
113
+ const absOf = (input: string) => {
114
+ const known = absByInput.get(input);
115
+ if (known) return known;
116
+ const abs = this.#absFromEntryPoint(input);
117
+ absByInput.set(input, abs);
118
+ return abs;
119
+ };
120
+ const importsByModule = new Map<string, ClientModuleImport[]>();
121
+ for (const [input, { imports = [] }] of Object.entries(this.#metafileInputs))
122
+ importsByModule.set(
123
+ absOf(input),
124
+ imports
125
+ .filter((imported) => !imported.external)
126
+ .map((imported) => ({ path: absOf(imported.path), lazy: imported.kind === "dynamic-import" })),
127
+ );
128
+ const chunksByModule = new Map<string, string[]>();
129
+ const importsByChunk = new Map<string, string[]>();
130
+ for (const [chunk, info] of this.#metafileOutputsByAbs) {
131
+ if (!chunk.endsWith(".js")) continue;
132
+ for (const input of Object.keys(info.inputs ?? {})) {
133
+ const module = absOf(input);
134
+ chunksByModule.set(module, [...(chunksByModule.get(module) ?? []), chunk]);
135
+ }
136
+ importsByChunk.set(
137
+ chunk,
138
+ info.imports
139
+ .filter((imported) => imported.kind !== "dynamic-import" && imported.path.endsWith(".js"))
140
+ .map((imported) => this.#absFromOutdir(imported.path)),
141
+ );
142
+ }
143
+ return { importsByModule, chunksByModule, importsByChunk };
144
+ }
145
+
108
146
  async #createOpaqueEntryAliases(): Promise<OpaqueEntryAliases> {
109
147
  const aliasDir = path.join(this.#app.cwdPath, ".akan", "generated", "client-entry-alias", this.#outputSubdir);
110
148
  fs.mkdirSync(aliasDir, { recursive: true });