@akanjs/devkit 3.3.0-rc.4 → 3.3.0-rc.40

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 (250) hide show
  1. package/CHANGELOG.md +618 -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 +133 -6
  22. package/app/dictionarySizes.ts +91 -0
  23. package/app/routeFilesReport.test.ts +59 -0
  24. package/app/routeFilesReport.ts +46 -0
  25. package/app/routeJsBudget.ts +18 -4
  26. package/artifact/implicitRootLayout.test.ts +19 -0
  27. package/artifact/implicitRootLayout.ts +16 -2
  28. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  29. package/artifact/storeBootstrap.test.ts +28 -0
  30. package/artifact/storeBootstrap.ts +64 -8
  31. package/biome.base.json +6 -4
  32. package/codeAgent/agent/CodeAgent.ts +36 -16
  33. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  34. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  35. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  36. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  37. package/codeAgent/agent/codeAgent.test.ts +62 -0
  38. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  39. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  40. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  41. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  42. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  43. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  44. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  46. package/codeAgent/skills/akan-page/SKILL.md +31 -20
  47. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  48. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  49. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  50. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  51. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  52. package/context/akanContext.ts +2 -0
  53. package/docs/apiReference.test.ts +9 -0
  54. package/docs/apiReference.ts +14 -0
  55. package/executors/appExecutor.ts +3 -1
  56. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  57. package/executors/clientRuntimeKeys.fixture.json +393 -0
  58. package/executors/clientRuntimeKeys.test.ts +1690 -0
  59. package/executors/executors.test.ts +2 -0
  60. package/executors/sysExecutor.ts +70 -4
  61. package/executors/workspaceExecutor.ts +7 -4
  62. package/frontendBuild/allRoutesBuilder.ts +88 -7
  63. package/frontendBuild/autoImportSync.ts +3 -2
  64. package/frontendBuild/buildRouteClient.test.ts +580 -12
  65. package/frontendBuild/clientBuildTypes.ts +26 -0
  66. package/frontendBuild/clientEntriesBundler.ts +49 -1
  67. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  68. package/frontendBuild/clientEntryDiscovery.ts +135 -13
  69. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  70. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  71. package/frontendBuild/csrDevPatcher.ts +33 -7
  72. package/frontendBuild/csrDevTypes.ts +9 -0
  73. package/frontendBuild/devBarrelImports.test.ts +154 -0
  74. package/frontendBuild/devBarrelImports.ts +83 -23
  75. package/frontendBuild/devRegistryBundler.ts +4 -2
  76. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  77. package/frontendBuild/devRouteRuntime.ts +167 -0
  78. package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
  79. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  80. package/frontendBuild/dictionaryConstants.ts +136 -0
  81. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  82. package/frontendBuild/dictionaryPacking.ts +135 -0
  83. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  84. package/frontendBuild/dictionaryRoutes.ts +227 -0
  85. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  86. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  87. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  88. package/frontendBuild/precompressArtifacts.ts +22 -8
  89. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  90. package/frontendBuild/renderedEntries.ts +144 -0
  91. package/frontendBuild/routeClientBuilder.ts +340 -29
  92. package/frontendBuild/routeHandoffs.test.ts +155 -0
  93. package/frontendBuild/routeHandoffs.ts +117 -0
  94. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  95. package/frontendBuild/routeModulePreloads.ts +20 -11
  96. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  97. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  98. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  99. package/frontendBuild/routeRuntimePays.ts +117 -0
  100. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  101. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  102. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  103. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  104. package/frontendBuild/ssrDevBundler.ts +66 -11
  105. package/frontendBuild/vendorFileImports.test.ts +254 -0
  106. package/frontendBuild/vendorFileImports.ts +163 -0
  107. package/frontendBuild/vendorNarrowing.ts +28 -0
  108. package/frontendBuild/vendorSpecifiers.ts +2 -0
  109. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  110. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  111. package/incrementalBuilder/builderBoot.ts +5 -5
  112. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  113. package/incrementalBuilder/builderLanes.ts +2 -2
  114. package/incrementalBuilder/builderWatch.ts +8 -8
  115. package/incrementalBuilder/csrRegistry.ts +4 -4
  116. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  117. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  118. package/incrementalBuilder/ssrRegistry.ts +6 -6
  119. package/index.ts +1 -1
  120. package/integration/renderAdmissionSoak.test.ts +99 -0
  121. package/integration/renderAdmissionSoak.ts +609 -0
  122. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  123. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  124. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  125. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  126. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  127. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  128. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  129. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  130. package/lint/biomeBase.test.ts +23 -3
  131. package/lint/biomeCheck.test.ts +145 -0
  132. package/lint/biomeCheck.ts +131 -0
  133. package/lint/no-arbitrary-color.grit +5 -0
  134. package/lint/no-conditional-st-hook.grit +5 -1
  135. package/lint/no-daisyui-legacy-class.grit +8 -0
  136. package/lint/no-document-cookie.grit +3 -0
  137. package/lint/no-inline-color.grit +10 -2
  138. package/lint/no-oversized-list-limit.grit +2 -0
  139. package/lint/no-raw-palette-class.grit +7 -0
  140. package/lint/no-unpublished-form-setter.grit +2 -0
  141. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  142. package/lint/no-web-storage.grit +3 -0
  143. package/lint/withheldEnvFile.ts +17 -0
  144. package/mobile/desktopBin.ts +2 -2
  145. package/mobile/desktopServerStage.ts +1 -0
  146. package/mobile/nativeApp.test.ts +7 -5
  147. package/mobile/nativeApp.ts +2 -2
  148. package/mobile/nativeConfig.test.ts +96 -1
  149. package/mobile/nativeConfig.ts +46 -12
  150. package/mobile/serverBundleSecrets.ts +43 -0
  151. package/package.json +15 -169
  152. package/packageExports.test.ts +38 -24
  153. package/quality/dictionaryKeys.test.ts +356 -0
  154. package/quality/dictionaryKeys.ts +488 -0
  155. package/quality/objectImportReport.test.ts +36 -0
  156. package/quality/objectImportReport.ts +105 -0
  157. package/quality/qualityScanner.ts +1 -1
  158. package/quality/routeRuntimeReport.test.ts +91 -0
  159. package/quality/routeRuntimeReport.ts +121 -0
  160. package/quality/runtimeConstantFacts.ts +71 -0
  161. package/quality/runtimeConstantGraph.ts +123 -0
  162. package/quality/runtimeConstantReads.ts +116 -0
  163. package/quality/runtimeImports.test.ts +190 -0
  164. package/quality/runtimeImports.ts +233 -0
  165. package/quality/runtimeKeyNames.ts +46 -0
  166. package/quality/runtimeLexicalScope.ts +132 -0
  167. package/quality/runtimeMarkerReach.test.ts +84 -0
  168. package/quality/runtimeMarkerReach.ts +255 -0
  169. package/quality/runtimeModuleFacts.ts +290 -0
  170. package/quality/runtimeNameTable.test.ts +172 -0
  171. package/quality/runtimeNameTable.ts +477 -0
  172. package/quality/runtimeScopeReport.test.ts +123 -0
  173. package/quality/runtimeScopeReport.ts +167 -0
  174. package/quality/runtimeSliceKey.ts +269 -0
  175. package/quality/runtimeSyntax.ts +133 -0
  176. package/quality/runtimeTable.fixture.ts +189 -0
  177. package/quality/runtimeUse.test.ts +737 -0
  178. package/quality/runtimeUse.ts +696 -0
  179. package/quality/runtimeUseReadable.test.ts +393 -0
  180. package/quality/ssrScanner.test.ts +13 -0
  181. package/quality/ssrScanner.ts +1 -1
  182. package/quality/translatorBindings.ts +187 -0
  183. package/test/secretEnvFixture.ts +134 -0
  184. package/test/testHelpers.ts +11 -0
  185. package/transforms/barrelAnalyzer.ts +26 -4
  186. package/transforms/barrelImportsPlugin.ts +121 -32
  187. package/transforms/exportReach.test.ts +162 -0
  188. package/transforms/exportReach.ts +308 -0
  189. package/transforms/frameworkObjects.fixture.tsx +58 -0
  190. package/transforms/frameworkObjects.test.ts +54 -0
  191. package/transforms/modelReference.test.ts +196 -0
  192. package/transforms/modelReference.ts +39 -0
  193. package/transforms/moduleParts.test.ts +225 -0
  194. package/transforms/moduleParts.ts +418 -0
  195. package/transforms/objectImportEdits.ts +150 -0
  196. package/transforms/objectMemberImports.test.ts +629 -0
  197. package/transforms/objectMemberImports.ts +571 -0
  198. package/transforms/objectMemberLookup.ts +150 -0
  199. package/transforms/objectModule.test.ts +307 -0
  200. package/transforms/objectModule.ts +482 -0
  201. package/transforms/objectModuleAnalyzer.ts +104 -0
  202. package/transforms/partImports.test.ts +76 -0
  203. package/transforms/partImports.ts +110 -0
  204. package/transforms/partModules.test.ts +187 -0
  205. package/transforms/partModules.ts +90 -0
  206. package/transforms/partPurity.ts +124 -0
  207. package/transforms/reactIconImports.test.ts +231 -0
  208. package/transforms/reactIconImports.ts +325 -0
  209. package/transforms/routeConstants.ts +122 -0
  210. package/transforms/routeRuntime.test.ts +835 -0
  211. package/transforms/routeRuntime.ts +703 -0
  212. package/transforms/routeRuntimeEdits.ts +92 -0
  213. package/transforms/routeRuntimeGraph.ts +66 -0
  214. package/transforms/routeRuntimePlan.ts +244 -0
  215. package/transforms/secretEnvDeclaration.test.ts +208 -0
  216. package/transforms/secretEnvDeclaration.ts +213 -0
  217. package/transforms/secretEnvFile.test.ts +117 -0
  218. package/transforms/secretEnvFile.ts +113 -0
  219. package/transforms/secretEnvName.test.ts +54 -0
  220. package/transforms/secretEnvName.ts +29 -0
  221. package/transforms/secretEnvSource.test.ts +148 -0
  222. package/transforms/secretEnvSource.ts +166 -0
  223. package/transforms/serverEnvEvaluationError.ts +11 -0
  224. package/transforms/serverEnvPlugin.test.ts +2 -1
  225. package/transforms/serverEnvPlugin.ts +13 -0
  226. package/transforms/serverEnvProfile.test.ts +115 -2
  227. package/transforms/serverEnvProfile.ts +117 -40
  228. package/transforms/serverEnvSecrets.test.ts +292 -0
  229. package/transforms/signalDescriptors.test.ts +280 -0
  230. package/transforms/signalDescriptors.ts +227 -0
  231. package/transforms/thisFreeExports.ts +87 -0
  232. package/transforms/transforms.test.ts +180 -3
  233. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  234. package/tunnel/createTunnel.test.ts +29 -8
  235. package/tunnel/createTunnel.ts +18 -11
  236. package/typecheck/projectTypecheck.test.ts +29 -0
  237. package/typecheck/typeChecker.test.ts +49 -0
  238. package/typecheck/typeChecker.ts +9 -7
  239. package/typecheck/withheldDiagnostics.ts +41 -0
  240. package/util/fileEditor.ts +1 -0
  241. package/util/selectModel.ts +1 -0
  242. package/workflow/executor.ts +6 -2
  243. package/workflow/index.ts +1 -0
  244. package/workflow/plan.ts +36 -7
  245. package/workflow/types.ts +1 -1
  246. package/workflow/uiTarget.ts +50 -0
  247. package/workspace/getRelatedCnsts.ts +7 -0
  248. package/workspace/scanInfo.test.ts +39 -0
  249. package/workspace/scanInfo.ts +48 -5
  250. package/workspace/workspaceLayout.ts +1 -0
@@ -4,6 +4,7 @@ import { lstat, mkdir, readFile, readlink, rm, stat, utimes, writeFile } from "n
4
4
  import path from "node:path";
5
5
  import { AkanAppConfig } from "../akanConfig";
6
6
  import { DevGeneratedIndexSync } from "../frontendBuild/devGeneratedIndexSync";
7
+ import { RouteRuntimeReport } from "../quality/routeRuntimeReport";
7
8
  import {
8
9
  createTempApp,
9
10
  createTempLib,
@@ -629,6 +630,7 @@ describe("Workspace and app executor environment contracts", () => {
629
630
  "cache/cssCandidates.json",
630
631
  "cache/fontCache.json",
631
632
  "cache/fonts/Assistant-400-normal-abc.woff2",
633
+ path.relative(".akan", RouteRuntimeReport.file),
632
634
  ];
633
635
  const removed = [
634
636
  "artifact/client/app.js",
@@ -90,6 +90,68 @@ export class SysExecutor extends Executor {
90
90
  );
91
91
  return written;
92
92
  }
93
+ //? `synced` is the app or lib whose sync this is: a lib's files are written by the sync of each app mounting it.
94
+ async #syncClientPieces(scanInfo: AppInfo | LibInfo, synced: SysExecutor): Promise<FileContent[]> {
95
+ const pieceDir = "lib/__client";
96
+ const modulesOf = (info: AppInfo | LibInfo): string[] => [
97
+ ...[...info.getLibInfos().values()].flatMap(modulesOf),
98
+ ...info.getDatabaseModules(),
99
+ ...info.getServiceModules(),
100
+ ];
101
+ const scope = `${this.type}s/${this.name}`;
102
+ const scopesOf = (info: AppInfo | LibInfo, own: string): string[] => [
103
+ ...[...info.getLibInfos().values()].flatMap((libInfo) => scopesOf(libInfo, `libs/${libInfo.name}`)),
104
+ own,
105
+ ];
106
+ const { RuntimeNameTable } = await import("../quality/runtimeNameTable");
107
+ const { RuntimeConstantGraph } = await import("../quality/runtimeConstantGraph");
108
+ const table = await RuntimeNameTable.readScopes(this.workspace.workspaceRoot, [
109
+ ...new Set(scopesOf(scanInfo, scope)),
110
+ ]).catch((error: unknown) => {
111
+ if (synced.type === "app")
112
+ this.logger.warn(
113
+ `[client-runtime] The modules of ${scope} could not be read (${error instanceof Error ? error.message : String(error)}), so no store file under ${scope}/${pieceDir} loads the upload module's descriptors first, and a page naming only that store has no upload action. Run \`akan sync ${this.name}\` again once that is fixed.`,
114
+ );
115
+ return null;
116
+ });
117
+ const constants = table ? RuntimeConstantGraph.ofDisk(this.workspace.workspaceRoot, table) : null;
118
+ const written = (
119
+ await Promise.all([
120
+ this._applyTemplate({ basePath: pieceDir, template: "clientPiece/scope", scanInfo }),
121
+ ...[...new Set(modulesOf(scanInfo))].map((model) =>
122
+ this._applyTemplate({
123
+ basePath: pieceDir,
124
+ template: "clientPiece/module",
125
+ scanInfo,
126
+ dict: {
127
+ model,
128
+ Model: capitalize(model),
129
+ descriptorsFirst: (table?.dependenciesOf(scope, model) ?? []).map(({ module }) => module).join(","),
130
+ },
131
+ options: {
132
+ constants: constants?.fetchNeedsOf(model) ?? undefined,
133
+ registration: constants?.modelOf(model) ?? undefined,
134
+ },
135
+ }),
136
+ ),
137
+ ...(constants
138
+ ? [...scanInfo.getDatabaseModules(), ...scanInfo.getScalarModules()].map((model) =>
139
+ this._applyTemplate({
140
+ basePath: pieceDir,
141
+ template: "clientPiece/constant",
142
+ scanInfo,
143
+ dict: { model, Model: capitalize(model) },
144
+ options: constants.piecesBefore({ scope, module: model }),
145
+ }),
146
+ )
147
+ : []),
148
+ ])
149
+ ).flat();
150
+ const kept = new Set(written.map(({ filePath }) => path.basename(filePath)));
151
+ const stale = (await this.readdir(pieceDir)).filter((file) => !kept.has(file));
152
+ await Promise.all(stale.map((file) => this.remove(`${pieceDir}/${file}`)));
153
+ return written;
154
+ }
93
155
  #getScanTemplateTasks(scanInfo: AppInfo | LibInfo): (Promise<FileContent[]> | null)[] {
94
156
  return [
95
157
  this.#seedEnvFiles(),
@@ -133,16 +195,20 @@ export class SysExecutor extends Executor {
133
195
  : await LibInfo.fromExecutor(this as unknown as LibExecutor, {
134
196
  refresh,
135
197
  });
198
+ scanInfo.orderLibDeps();
136
199
  //* Locked: `writeLib` rewrites dependency-lib barrels that other dev servers regenerate and watch too.
137
200
  if (write)
138
201
  await CodegenLock.run(this.workspace.workspaceRoot, `scan:${this.name}`, async () => {
139
202
  await Promise.all(this.#getScanTemplateTasks(scanInfo));
140
203
  await this.writeJson(`akan.${this.type}.json`, scanInfo.getScanResult());
141
204
  await this.#updateDependencies(scanInfo);
142
- if (writeLib) {
143
- const libInfos = [...scanInfo.getLibInfos().values()];
144
- await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
145
- }
205
+ const libInfos = writeLib ? [...scanInfo.getLibInfos().values()] : [];
206
+ await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
207
+ //? A piece is shaped by each scope's generated `lib/cnst.ts`, which a new checkout has only once the above ran.
208
+ await Promise.all([
209
+ this.#syncClientPieces(scanInfo, this),
210
+ ...libInfos.map((libInfo) => libInfo.exec.#syncClientPieces(libInfo, this)),
211
+ ]);
146
212
  await this.syncAgentsIndex(scanInfo);
147
213
  });
148
214
  this.#scanInfo = scanInfo;
@@ -8,12 +8,15 @@ import type { BaseDevEnv, TsConfigJson } from "../workspace/types";
8
8
  import { Executor, execEmoji } from "./executor";
9
9
  import { SysExecutor } from "./sysExecutor";
10
10
 
11
- //? As Bun's own .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value even mid-word.
11
+ //? As Bun's .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value mid-word, `\$` is `$`.
12
12
  const parseEnvValue = (value: string) => {
13
13
  const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
14
- if (!quote) return value.replace(/#.*/, "").trim();
15
- if (quote !== '"') return inner;
16
- return inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
14
+ const text = !quote
15
+ ? value.replace(/#.*/, "").trim()
16
+ : quote !== '"'
17
+ ? inner
18
+ : inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
19
+ return text.replaceAll("\\$", "$");
17
20
  };
18
21
 
19
22
  export const parseEnvFile = (envPath: string): Record<string, string> => {
@@ -7,10 +7,16 @@ import {
7
7
  resolveSsrPageEntriesForApp,
8
8
  } from "../artifact/implicitRootLayout";
9
9
  import { computeRouteSeedIndex, type RouteSeedIndex } from "../artifact/routeSeedIndex";
10
+ import { StoreBootstrap } from "../artifact/storeBootstrap";
10
11
  import type { App } from "../commandDecorators";
11
- import type { ClientEntryDiscovery } from "./clientBuildTypes";
12
+ import { type RouteRuntimeDictionaryFallback, RouteRuntimeReport } from "../quality/routeRuntimeReport";
13
+ import { ModelReference } from "../transforms/modelReference";
14
+ import { RouteRuntime } from "../transforms/routeRuntime";
15
+ import type { AskedExports, ClientEntryDiscovery } from "./clientBuildTypes";
12
16
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
17
+ import { DictionaryRoutes } from "./dictionaryRoutes";
13
18
  import { type BuildRouteClientResult, RouteClientBuilder } from "./routeClientBuilder";
19
+ import { RouteHandoffs } from "./routeHandoffs";
14
20
  import { RouteModulePreloads, type RuntimeChunks } from "./routeModulePreloads";
15
21
  import { RoutesManifestArtifactSerializer } from "./routesManifestArtifactSerializer";
16
22
 
@@ -18,6 +24,8 @@ export interface BuildAllRoutesResult {
18
24
  manifest: RoutesManifest;
19
25
  manifestPath: string;
20
26
  seedIndex: RouteSeedIndex;
27
+ /** A production build: the dictionary groups each route can show; a route left out loads every group. */
28
+ dictionaryRoutes?: Map<string, string[]>;
21
29
  }
22
30
 
23
31
  export class AllRoutesBuilder {
@@ -32,6 +40,9 @@ export class AllRoutesBuilder {
32
40
  #knownSet = new Set<string>();
33
41
  #routeIds: string[] = [];
34
42
  #ssrEntriesByRoute = new Map<string, string[]>();
43
+ #entriesByRoute = new Map<string, string[]>();
44
+ #askedByRoute = new Map<string, AskedExports>();
45
+ #serverModulesByRoute = new Map<string, string[]>();
35
46
  #externalsByChunkUrl: Record<string, string[]> = {};
36
47
  #discovery: ClientEntryDiscovery | null = null;
37
48
 
@@ -46,9 +57,12 @@ export class AllRoutesBuilder {
46
57
  const pageEntries = await resolveSsrPageEntriesForApp(this.#app, pageKeys);
47
58
  const seedIndex = computeRouteSeedIndex(pageEntries);
48
59
  this.#app.verbose(`[build-all] discovered ${seedIndex.entries.length} routes`);
49
- const discovery = await GraphClientEntryDiscovery.create(this.#app);
60
+ const discovery = await GraphClientEntryDiscovery.create(this.#app, { byExport: this.#command === "build" });
50
61
  this.#discovery = discovery;
51
- const importsAs = await this.#ssrImportsAs(discovery, pageEntries);
62
+ const { importsAs, rendering } = await this.#ssrImportsAs(discovery, pageEntries);
63
+ const handoffs = await this.#readHandoffs();
64
+ const dictionary = this.#command === "build";
65
+ const unread = new Map<string, string[]>();
52
66
 
53
67
  // Every route's entries go into one Bun.build: chunk splitting only dedupes within a single build.
54
68
  const allEntries = new Set<string>();
@@ -56,13 +70,34 @@ export class AllRoutesBuilder {
56
70
  const seeds = Array.from(new Set([...seedIndex.globalLayoutFiles, ...entry.seeds]));
57
71
  const routeEntries = await discovery.discover(seeds);
58
72
  for (const discovered of routeEntries) allEntries.add(discovered);
59
- this.#ssrEntriesByRoute.set(entry.routeId, await discovery.discover(seeds, { importsAs }));
73
+ const serverModules = dictionary ? await discovery.serverModules(seeds, { importsAs }) : undefined;
74
+ const asked = await discovery.discoverAsked(seeds, { importsAs, serverModules });
75
+ const ssrEntries = [...asked.keys()].sort();
76
+ this.#askedByRoute.set(entry.routeId, asked);
77
+ if (serverModules) this.#serverModulesByRoute.set(entry.routeId, serverModules);
78
+ const handed = handoffs
79
+ ? await handoffs.read(await discovery.serverModules(seeds, { importsAs: rendering }))
80
+ : undefined;
81
+ const loaded = [...new Set([...ssrEntries, ...(handed?.referenceFiles ?? [])])].sort();
82
+ this.#ssrEntriesByRoute.set(entry.routeId, loaded);
83
+ const besidesReferences = handed ? routeEntries.filter((file) => !ModelReference.isFile(file)) : routeEntries;
84
+ this.#entriesByRoute.set(entry.routeId, [...new Set([...besidesReferences, ...loaded])]);
85
+ if (handed?.unread) {
86
+ const pinned = `${handed.unread.file} (${handed.unread.why})`;
87
+ unread.set(pinned, [...(unread.get(pinned) ?? []), entry.routeId]);
88
+ }
60
89
  this.#routeIds.push(entry.routeId);
61
90
  }
91
+ for (const [pinned, routeIds] of unread)
92
+ this.#app.logger.warn(
93
+ `[client-runtime] ${routeIds.length} route(s) count every model's runtime in the route table: what ${pinned} hands to client components cannot be read. Routes: ${routeIds.join(", ")}`,
94
+ );
62
95
  this.#app.verbose(`[build-all] ${allEntries.size} client entries across ${this.#routeIds.length} routes`);
63
96
 
64
97
  const delta = await this.#buildEntries([...allEntries]);
65
98
  this.#mergeDelta(delta);
99
+ const dictionaryRoutes =
100
+ dictionary && delta.clientGraph ? await this.#readDictionaryRoutes(delta.clientGraph) : null;
66
101
  this.#merged.knownEntries = Array.from(this.#knownSet);
67
102
  this.#externalsByChunkUrl = delta.externalsByChunkUrl ?? {};
68
103
 
@@ -75,24 +110,67 @@ export class AllRoutesBuilder {
75
110
  `[build-all] wrote ${manifestPath} routes=${this.#routeIds.length} entries=${this.#merged.knownEntries.length}`,
76
111
  );
77
112
 
78
- return { manifest, manifestPath, seedIndex };
113
+ return { manifest, manifestPath, seedIndex, ...(dictionaryRoutes ? { dictionaryRoutes } : {}) };
114
+ }
115
+
116
+ async #readDictionaryRoutes(importsByModule: NonNullable<BuildRouteClientResult["clientGraph"]>) {
117
+ const { workspaceRoot } = this.#app.workspace;
118
+ const reader = await DictionaryRoutes.forApp(workspaceRoot, `apps/${this.#app.name}`, { importsByModule });
119
+ const groupsByRoute = new Map<string, string[]>();
120
+ const whole = new Map<string, RouteRuntimeDictionaryFallback>();
121
+ for (const routeId of this.#routeIds) {
122
+ const entries = this.#entriesByRoute.get(routeId) ?? [];
123
+ const read = reader.read({ entries, serverModules: this.#serverModulesByRoute.get(routeId) });
124
+ if (!read.whole) groupsByRoute.set(routeId, read.groups);
125
+ else {
126
+ const pinned = DictionaryRoutes.pinned(read.whole);
127
+ const known = whole.get(pinned) ?? { ...read.whole, routes: [] };
128
+ whole.set(pinned, { ...known, routes: [...known.routes, routeId] });
129
+ }
130
+ }
131
+ for (const [pinned, { routes, line: key }] of whole) {
132
+ const line = `[dictionary] ${routes.length} route(s) load the whole page dictionary: ${pinned}. Routes: ${routes.join(", ")}`;
133
+ if (key !== undefined) this.#app.logger.warn(line);
134
+ else this.#app.verbose(line);
135
+ }
136
+ await RouteRuntimeReport.addDictionary(this.#app.cwdPath, [...whole.values()]);
137
+ return groupsByRoute;
79
138
  }
80
139
 
81
140
  async #ssrImportsAs(discovery: GraphClientEntryDiscovery, pageEntries: PageEntry[]) {
82
141
  const { specifier, ssrShell, importsNoSsrPageRenders } = ROOT_LAYOUT_SYSTEM;
83
142
  const importsAs = new Map<string, ReadonlyMap<string, string | null>>();
84
- const toShell = new Map([[specifier, ssrShell]]);
143
+ //? The root layout registers every model's reference; a route loads only those its own server modules hand over.
144
+ const toShell = new Map<string, string | null>([
145
+ [specifier, ssrShell],
146
+ [ModelReference.registrySpecifier(this.#app.name), null],
147
+ ]);
85
148
  for (const { key, moduleAbsPath } of pageEntries)
86
149
  if (isImplicitRootLayoutKey(key)) importsAs.set(path.resolve(moduleAbsPath), toShell);
87
150
  const system = await discovery.resolveImport(specifier, this.#app.cwdPath);
88
151
  if (system) importsAs.set(system, new Map(importsNoSsrPageRenders.map((spec) => [spec, null])));
89
- return importsAs;
152
+ //? The root layout also imports every store so the server holds them; no route's own render runs through one.
153
+ const stores = StoreBootstrap.serverSpecifiers(this.#app.name).map((spec) => [spec, null] as const);
154
+ const rendering = new Map(importsAs);
155
+ for (const { key, moduleAbsPath } of pageEntries)
156
+ if (isImplicitRootLayoutKey(key)) rendering.set(path.resolve(moduleAbsPath), new Map([...toShell, ...stores]));
157
+ return { importsAs, rendering };
158
+ }
159
+
160
+ async #readHandoffs(): Promise<RouteHandoffs | null> {
161
+ if (this.#command !== "build" || (await StoreBootstrap.scopeOf(this.#app)) !== "page") return null;
162
+ const { workspaceRoot } = this.#app.workspace;
163
+ const scope = `apps/${this.#app.name}`;
164
+ const runtime = await RouteRuntime.read(workspaceRoot, scope).catch(() => null);
165
+ if (!runtime) return null;
166
+ return new RouteHandoffs(workspaceRoot, runtime, await ModelReference.filesOf(workspaceRoot, scope));
90
167
  }
91
168
 
92
169
  async writeModulePreloads(runtimeChunks: RuntimeChunks): Promise<RouteModulePreloads> {
93
170
  const preloads = new RouteModulePreloads({
94
171
  runtimeChunks,
95
172
  entriesByRoute: this.#ssrEntriesByRoute,
173
+ askedByRoute: this.#askedByRoute,
96
174
  clientManifest: this.#merged.clientManifest,
97
175
  externalsByChunkUrl: this.#externalsByChunkUrl,
98
176
  workspaceRoot: this.#app.workspace.workspaceRoot,
@@ -133,6 +211,9 @@ export class AllRoutesBuilder {
133
211
  knownEntries: this.#knownSet,
134
212
  discovery: this.#discovery,
135
213
  command: this.#command,
214
+ entriesByRoute: this.#entriesByRoute,
215
+ sizedEntriesByRoute: this.#ssrEntriesByRoute,
216
+ askedByRoute: this.#askedByRoute,
136
217
  }).build();
137
218
  this.#app.verbose(`[build-all] bundled ${delta.newEntries.length} entries (${Date.now() - started}ms)`);
138
219
  return delta;
@@ -232,8 +232,9 @@ export class AutoImportSync {
232
232
  const parts = rel.split(path.sep).filter(Boolean);
233
233
  const [scope, project, facet] = parts;
234
234
  if ((scope !== "apps" && scope !== "libs") || !project || !facet) return null;
235
- //* `lib/__lib/` is rewritten by every `akan sync`, so an edit there is discarded; `lib/__scalar/` is real source.
236
- if (facet === "lib" && parts[3] === "__lib") return null;
235
+ //* `lib/__lib/` and `lib/__client/` are rewritten by every `akan sync`, so an edit there is discarded;
236
+ //* `lib/__scalar/` is real source.
237
+ if (facet === "lib" && (parts[3] === "__lib" || parts[3] === "__client")) return null;
237
238
  const role = roleFor(facet, base);
238
239
  if (!role) return null;
239
240