@akanjs/devkit 3.3.0-rc.9 → 4.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +269 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +212 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +358 -5
  28. package/app/applicationBuildRunner.ts +221 -31
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.ts +49 -1
  80. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  81. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  82. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  83. package/frontendBuild/clientEntryGroups.ts +61 -0
  84. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  85. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  86. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  87. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  88. package/frontendBuild/csrDevPatcher.ts +37 -11
  89. package/frontendBuild/csrDevTypes.ts +9 -0
  90. package/frontendBuild/devBarrelImports.test.ts +124 -0
  91. package/frontendBuild/devBarrelImports.ts +81 -21
  92. package/frontendBuild/devChangePlanner.ts +0 -1
  93. package/frontendBuild/devRegistryBundler.ts +4 -2
  94. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  95. package/frontendBuild/devRouteRuntime.ts +167 -0
  96. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  97. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  98. package/frontendBuild/dictionaryConstants.ts +136 -0
  99. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  100. package/frontendBuild/dictionaryPackState.ts +131 -0
  101. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  102. package/frontendBuild/dictionaryPacking.ts +160 -0
  103. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  104. package/frontendBuild/dictionaryRoutes.ts +227 -0
  105. package/frontendBuild/frontendBuild.test.ts +5 -3
  106. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  107. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  108. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  109. package/frontendBuild/precompressArtifacts.ts +34 -8
  110. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  111. package/frontendBuild/renderedEntries.ts +144 -0
  112. package/frontendBuild/routeClientBuilder.ts +407 -43
  113. package/frontendBuild/routeHandoffs.test.ts +155 -0
  114. package/frontendBuild/routeHandoffs.ts +117 -0
  115. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  116. package/frontendBuild/routeModulePreloads.ts +20 -11
  117. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  118. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  119. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  120. package/frontendBuild/routeRuntimePays.ts +117 -0
  121. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  122. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  123. package/frontendBuild/ssrDevBundler.ts +66 -11
  124. package/frontendBuild/vendorFileImports.test.ts +254 -0
  125. package/frontendBuild/vendorFileImports.ts +163 -0
  126. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  127. package/frontendBuild/vendorNarrowing.ts +38 -2
  128. package/frontendBuild/vendorSpecifiers.ts +2 -0
  129. package/guideline/agentAssets.ts +1 -1
  130. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  131. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  132. package/incrementalBuilder/builderWatch.ts +11 -1
  133. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  134. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  135. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  136. package/incrementalBuilder/pendingMetadata.ts +19 -0
  137. package/integration/devStability.integration.test.ts +46 -21
  138. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  139. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  140. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  141. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  142. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  143. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  144. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  145. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  146. package/lint/biomeBase.test.ts +50 -3
  147. package/lint/biomeBase.ts +1 -1
  148. package/lint/biomeCheck.test.ts +162 -0
  149. package/lint/biomeCheck.ts +131 -0
  150. package/lint/linter.test.ts +16 -11
  151. package/lint/no-arbitrary-color.grit +5 -0
  152. package/lint/no-conditional-st-hook.grit +5 -1
  153. package/lint/no-daisyui-legacy-class.grit +8 -0
  154. package/lint/no-document-cookie.grit +3 -0
  155. package/lint/no-inline-color.grit +10 -2
  156. package/lint/no-oversized-list-limit.grit +2 -0
  157. package/lint/no-raw-palette-class.grit +7 -0
  158. package/lint/no-unpublished-form-setter.grit +2 -0
  159. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  160. package/lint/no-web-storage.grit +3 -0
  161. package/lint/withheldEnvFile.ts +17 -0
  162. package/mobile/desktopBin.ts +2 -2
  163. package/mobile/desktopServerStage.test.ts +18 -3
  164. package/mobile/desktopServerStage.ts +7 -2
  165. package/mobile/nativeApp.test.ts +7 -5
  166. package/mobile/nativeApp.ts +2 -2
  167. package/mobile/nativeConfig.test.ts +17 -1
  168. package/mobile/nativeConfig.ts +11 -6
  169. package/mobile/nativePublicEnv.ts +1 -1
  170. package/mobile/serverBundleSecrets.ts +43 -0
  171. package/package.json +11 -12
  172. package/packageExports.test.ts +3 -2
  173. package/preview/PreviewView.ts +25 -3
  174. package/quality/dictionaryKeys.test.ts +356 -0
  175. package/quality/dictionaryKeys.ts +488 -0
  176. package/quality/objectImportReport.test.ts +36 -0
  177. package/quality/objectImportReport.ts +105 -0
  178. package/quality/qualityScanner.ts +1 -1
  179. package/quality/routeRuntimeReport.test.ts +91 -0
  180. package/quality/routeRuntimeReport.ts +121 -0
  181. package/quality/runtimeConstantFacts.ts +71 -0
  182. package/quality/runtimeConstantGraph.ts +123 -0
  183. package/quality/runtimeConstantReads.ts +116 -0
  184. package/quality/runtimeImports.test.ts +190 -0
  185. package/quality/runtimeImports.ts +233 -0
  186. package/quality/runtimeKeyNames.ts +46 -0
  187. package/quality/runtimeLexicalScope.ts +132 -0
  188. package/quality/runtimeMarkerReach.test.ts +84 -0
  189. package/quality/runtimeMarkerReach.ts +255 -0
  190. package/quality/runtimeModuleFacts.ts +290 -0
  191. package/quality/runtimeNameTable.test.ts +172 -0
  192. package/quality/runtimeNameTable.ts +477 -0
  193. package/quality/runtimeScopeReport.test.ts +123 -0
  194. package/quality/runtimeScopeReport.ts +167 -0
  195. package/quality/runtimeSliceKey.ts +269 -0
  196. package/quality/runtimeSyntax.ts +133 -0
  197. package/quality/runtimeTable.fixture.ts +189 -0
  198. package/quality/runtimeUse.test.ts +737 -0
  199. package/quality/runtimeUse.ts +696 -0
  200. package/quality/runtimeUseReadable.test.ts +393 -0
  201. package/quality/ssrScanner.test.ts +13 -0
  202. package/quality/ssrScanner.ts +1 -1
  203. package/quality/translatorBindings.ts +187 -0
  204. package/test/fakeTerminal.ts +45 -0
  205. package/test/secretEnvFixture.ts +134 -0
  206. package/test/testHelpers.ts +11 -0
  207. package/transforms/barrelAnalyzer.ts +24 -2
  208. package/transforms/barrelImportsPlugin.ts +121 -32
  209. package/transforms/exportReach.test.ts +162 -0
  210. package/transforms/exportReach.ts +308 -0
  211. package/transforms/frameworkObjects.fixture.tsx +58 -0
  212. package/transforms/frameworkObjects.test.ts +54 -0
  213. package/transforms/modelReference.test.ts +196 -0
  214. package/transforms/modelReference.ts +39 -0
  215. package/transforms/moduleParts.test.ts +225 -0
  216. package/transforms/moduleParts.ts +418 -0
  217. package/transforms/objectImportEdits.ts +150 -0
  218. package/transforms/objectMemberImports.test.ts +633 -0
  219. package/transforms/objectMemberImports.ts +571 -0
  220. package/transforms/objectMemberLookup.ts +150 -0
  221. package/transforms/objectModule.test.ts +307 -0
  222. package/transforms/objectModule.ts +482 -0
  223. package/transforms/objectModuleAnalyzer.ts +104 -0
  224. package/transforms/partImports.test.ts +76 -0
  225. package/transforms/partImports.ts +110 -0
  226. package/transforms/partModules.test.ts +187 -0
  227. package/transforms/partModules.ts +90 -0
  228. package/transforms/partPurity.ts +124 -0
  229. package/transforms/reactIconImports.test.ts +231 -0
  230. package/transforms/reactIconImports.ts +325 -0
  231. package/transforms/routeConstants.ts +122 -0
  232. package/transforms/routeRuntime.test.ts +835 -0
  233. package/transforms/routeRuntime.ts +703 -0
  234. package/transforms/routeRuntimeEdits.ts +92 -0
  235. package/transforms/routeRuntimeGraph.ts +66 -0
  236. package/transforms/routeRuntimePlan.ts +244 -0
  237. package/transforms/secretEnvDeclaration.test.ts +208 -0
  238. package/transforms/secretEnvDeclaration.ts +213 -0
  239. package/transforms/secretEnvFile.test.ts +117 -0
  240. package/transforms/secretEnvFile.ts +113 -0
  241. package/transforms/secretEnvName.test.ts +54 -0
  242. package/transforms/secretEnvName.ts +29 -0
  243. package/transforms/secretEnvSource.test.ts +148 -0
  244. package/transforms/secretEnvSource.ts +166 -0
  245. package/transforms/serverEnvEvaluationError.ts +11 -0
  246. package/transforms/serverEnvPlugin.test.ts +2 -1
  247. package/transforms/serverEnvPlugin.ts +13 -0
  248. package/transforms/serverEnvProfile.test.ts +129 -2
  249. package/transforms/serverEnvProfile.ts +126 -40
  250. package/transforms/serverEnvSecrets.test.ts +292 -0
  251. package/transforms/signalDescriptors.test.ts +280 -0
  252. package/transforms/signalDescriptors.ts +227 -0
  253. package/transforms/thisFreeExports.ts +87 -0
  254. package/transforms/transforms.test.ts +177 -0
  255. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  256. package/tunnel/createTunnel.ts +5 -1
  257. package/tunnel/ssh2Module.test.ts +37 -0
  258. package/tunnel/ssh2Module.ts +28 -0
  259. package/tunnel/sshTunnel.ts +4 -2
  260. package/typecheck/projectTypecheck.test.ts +32 -1
  261. package/typecheck/projectTypecheck.ts +3 -3
  262. package/typecheck/typeChecker.test.ts +49 -0
  263. package/typecheck/typeChecker.ts +9 -7
  264. package/typecheck/withheldDiagnostics.ts +41 -0
  265. package/util/devInstallCommand.ts +7 -0
  266. package/util/jsonFormatter.test.ts +13 -9
  267. package/workflow/executor.ts +6 -2
  268. package/workflow/index.ts +1 -0
  269. package/workflow/plan.ts +36 -7
  270. package/workflow/types.ts +1 -1
  271. package/workflow/uiTarget.ts +50 -0
  272. package/workspace/envSeed.test.ts +30 -1
  273. package/workspace/envSeed.ts +30 -1
  274. package/workspace/mainCheckout.test.ts +55 -0
  275. package/workspace/mainCheckout.ts +38 -0
  276. package/workspace/scanInfo.test.ts +39 -0
  277. package/workspace/scanInfo.ts +55 -6
  278. package/workspace/slicePlanner.ts +2 -1
  279. package/workspace/workspaceLayout.test.ts +22 -1
  280. package/workspace/workspaceLayout.ts +3 -3
  281. package/CHANGELOG.md +0 -2904
  282. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  283. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  284. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  285. package/codeAgent/agent/CodeAgent.ts +0 -626
  286. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  287. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  288. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  289. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  290. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  291. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  292. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  293. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  294. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  295. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  296. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  297. package/codeAgent/agent/CodeMailbox.ts +0 -148
  298. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  299. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  300. package/codeAgent/agent/SubagentPool.ts +0 -219
  301. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  302. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  303. package/codeAgent/agent/akanCodeModel.ts +0 -47
  304. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  305. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  306. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  307. package/codeAgent/agent/codeAgent.test.ts +0 -337
  308. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  309. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  310. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  311. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  312. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  313. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  314. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  315. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  316. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  317. package/codeAgent/agent/consoleToStderr.ts +0 -8
  318. package/codeAgent/agent/jsonLines.ts +0 -29
  319. package/codeAgent/agent/stringArg.ts +0 -5
  320. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  321. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  322. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  323. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  324. package/codeAgent/tools/AkanCli.ts +0 -51
  325. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  326. package/codeAgent/tools/AkanEditScope.ts +0 -53
  327. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  328. package/codeAgent/tools/AkanToolPack.ts +0 -86
  329. package/codeAgent/tools/AkanVerifier.ts +0 -30
  330. package/codeAgent/tools/AskToolPack.ts +0 -99
  331. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  332. package/codeAgent/tools/MailToolPack.ts +0 -76
  333. package/codeAgent/tools/McpClient.ts +0 -209
  334. package/codeAgent/tools/McpOAuth.ts +0 -233
  335. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  336. package/codeAgent/tools/McpServerConfig.ts +0 -131
  337. package/codeAgent/tools/McpSignIn.ts +0 -158
  338. package/codeAgent/tools/McpTokenStore.ts +0 -128
  339. package/codeAgent/tools/McpToolPack.ts +0 -206
  340. package/codeAgent/tools/SessionToolPack.ts +0 -91
  341. package/codeAgent/tools/WebToolPack.ts +0 -315
  342. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  343. package/codeAgent/tools/askToolPack.test.ts +0 -116
  344. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  345. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  346. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  347. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,155 @@
1
+ import { beforeAll, describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { runtimeFixtureTables } from "../quality/runtimeTable.fixture";
4
+ import { tempDirs, writeText as write } from "../test/testHelpers";
5
+ import { RouteRuntime } from "../transforms/routeRuntime";
6
+ import { RouteHandoffs } from "./routeHandoffs";
7
+
8
+ const makeTempRoot = tempDirs("akan-route-handoffs-");
9
+ const models = ["memo", "note", "tag"];
10
+ const client = 'import { fetch } from "@apps/demo/client";\n';
11
+
12
+ let root = "";
13
+ let handoffs: RouteHandoffs;
14
+ const file = (name: string) => path.join(root, name);
15
+ const referenceOf = (model: string) => file(`apps/demo/lib/__client/${model}.ref.ts`);
16
+ const readOf = async (sources: Record<string, string>) => {
17
+ for (const [name, source] of Object.entries(sources)) await write(file(name), source);
18
+ return handoffs.read(Object.keys(sources).map(file));
19
+ };
20
+
21
+ beforeAll(async () => {
22
+ root = await makeTempRoot();
23
+ const { demo } = await runtimeFixtureTables();
24
+ const runtime = new RouteRuntime(root, demo, new Set());
25
+ handoffs = new RouteHandoffs(root, runtime, new Map(models.map((model) => [model, referenceOf(model)])));
26
+ });
27
+
28
+ describe("the models a route's server modules hand to client components", () => {
29
+ test("are those whose init, view, edit or slice a server module names, whichever module of the route names it", async () => {
30
+ const read = await readOf({
31
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
32
+ "apps/demo/ui/NoteCard.tsx": `${client}export const card = (id: string) => fetch.viewNote(id);\n`,
33
+ "apps/demo/ui/plain.ts": "export const plain = 1;\n",
34
+ });
35
+
36
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo"), referenceOf("note")], unread: null });
37
+ });
38
+
39
+ test("include a model whose slice is read from `fetch.slice`", async () => {
40
+ const read = await readOf({
41
+ "apps/demo/page/tags.tsx": `${client}export const Tags = () => [fetch.slice.tag, fetch.tagCount()];\n`,
42
+ });
43
+
44
+ expect(read.referenceFiles).toEqual([referenceOf("tag")]);
45
+ });
46
+
47
+ test("leave out a model whose endpoint is only called, since a plain result brings no component a store to read", async () => {
48
+ const read = await readOf({
49
+ "apps/demo/page/count.tsx": `${client}export const Count = async () => [await fetch.memoNote(), await fetch.tagCount()];\n`,
50
+ });
51
+
52
+ expect(read).toEqual({ referenceFiles: [], unread: null });
53
+ });
54
+
55
+ test("do not count every model for a server module that copies the names of a slice it was handed", async () => {
56
+ const read = await readOf({
57
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
58
+ "apps/demo/ui/copy.ts":
59
+ 'import type { SliceMeta } from "akanjs/fetch";\nexport const copy = (slice: SliceMeta) => ({ refName: slice.refName, sliceName: slice.sliceName, argLength: 0 });\n',
60
+ });
61
+
62
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo")], unread: null });
63
+ });
64
+
65
+ test("are every model once a server module picks the name at run time, and say which file and line", async () => {
66
+ const read = await readOf({
67
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
68
+ "apps/demo/page/any.tsx": `${client}\nexport const Any = (name: string) => (fetch as never)[name];\n`,
69
+ });
70
+
71
+ expect(read.referenceFiles).toEqual(models.map(referenceOf));
72
+ expect(read.unread?.file).toBe("apps/demo/page/any.tsx");
73
+ expect(read.unread?.why).toStartWith("line 3: ");
74
+ });
75
+
76
+ test("are every model once a server module takes `fetch` from the server barrel, where its names are not read", async () => {
77
+ const read = await readOf({
78
+ "apps/demo/page/served.tsx":
79
+ 'import { Memo } from "@apps/demo/client";\nimport { fetch } from "@apps/demo/server";\nexport const Served = (id: string) => [Memo, fetch.viewMemo(id)];\n',
80
+ });
81
+
82
+ expect(read.referenceFiles).toEqual(models.map(referenceOf));
83
+ expect(read.unread).toEqual({
84
+ file: "apps/demo/page/served.tsx",
85
+ why: "line 2: `fetch` comes from the server barrel, where the names read from it are not checked; take it from the client barrel",
86
+ });
87
+ });
88
+
89
+ test("do not count the server barrel's `fetch` where the file hands nothing over, nor a generated file", async () => {
90
+ const read = await readOf({
91
+ "apps/demo/page/ping.tsx":
92
+ 'import { fetch } from "@apps/demo/server";\nexport const ping = () => fetch.memoNote();\n',
93
+ "apps/demo/page/typed.tsx":
94
+ 'import type { fetch } from "@apps/demo/server";\nexport type View = ReturnType<typeof fetch.viewMemo>;\n',
95
+ "apps/demo/server.ts": 'import { fetch } from "./lib/useServer";\nexport const view = fetch.viewMemo;\n',
96
+ "apps/demo/lib/useServer.ts": 'import { fetch } from "./sig";\nexport const view = fetch.viewMemo;\n',
97
+ });
98
+
99
+ expect(read).toEqual({ referenceFiles: [], unread: null });
100
+ });
101
+
102
+ test("do not count a service that calls an endpoint through the server barrel and slices an array of its own", async () => {
103
+ const read = await readOf({
104
+ "apps/demo/lib/memo/memo.service.ts":
105
+ 'import { fetch } from "../useServer";\nexport const scan = async (ips: string[]) => [ips.slice(0, 1), await fetch.memoNote(), { fetch: 1 }.fetch];\n',
106
+ });
107
+
108
+ expect(read).toEqual({ referenceFiles: [], unread: null });
109
+ });
110
+
111
+ test("do not count a store, whose actions name and pick models only in the browser", async () => {
112
+ const read = await readOf({
113
+ "apps/demo/page/board.tsx": `${client}export const Board = () => fetch.initMemoInBoard();\n`,
114
+ "apps/demo/lib/note/note.store.ts": `${client}export const open = (id: string) => [fetch.viewNote(id), fetch.slice.tag];\n`,
115
+ "apps/demo/lib/tag/tag.store.ts": `${client}export const any = (name: string) => (fetch as never)[name];\n`,
116
+ });
117
+
118
+ expect(read).toEqual({ referenceFiles: [referenceOf("memo")], unread: null });
119
+ });
120
+
121
+ test("are every model once the server barrel's `fetch` is indexed, passed on or taken apart", async () => {
122
+ const taken = 'import { fetch } from "@apps/demo/server";\n';
123
+ const unreadOf = async (name: string, body: string) =>
124
+ (await readOf({ [`apps/demo/page/${name}.tsx`]: `${taken}${body}\n` })).unread?.file;
125
+
126
+ expect(
127
+ await unreadOf("indexed", "export const any = (name: string) => [name.slice(1), (fetch as never)[name]];"),
128
+ ).toBe("apps/demo/page/indexed.tsx");
129
+ expect(
130
+ await unreadOf("passed", "export const all = (use: (api: unknown) => void) => [[].slice(), use(fetch)];"),
131
+ ).toBe("apps/demo/page/passed.tsx");
132
+ expect(
133
+ await unreadOf("apart", "const { viewMemo } = fetch;\nexport const view = (id: string) => viewMemo(id);"),
134
+ ).toBe("apps/demo/page/apart.tsx");
135
+ expect(await unreadOf("sliced", "export const tags = () => fetch.slice.tag;")).toBe("apps/demo/page/sliced.tsx");
136
+ });
137
+
138
+ test("name only models with a reference file, so a model the app's sync wrote none for adds nothing", async () => {
139
+ const { demo } = await runtimeFixtureTables();
140
+ const only = new RouteHandoffs(
141
+ root,
142
+ new RouteRuntime(root, demo, new Set()),
143
+ new Map([["memo", referenceOf("memo")]]),
144
+ );
145
+ await write(
146
+ file("apps/demo/page/both.tsx"),
147
+ `${client}export const both = [fetch.initMemoInBoard(), fetch.viewNote("1")];\n`,
148
+ );
149
+
150
+ expect(await only.read([file("apps/demo/page/both.tsx")])).toEqual({
151
+ referenceFiles: [referenceOf("memo")],
152
+ unread: null,
153
+ });
154
+ });
155
+ });
@@ -0,0 +1,117 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import { RuntimeScopeReport } from "../quality/runtimeScopeReport";
4
+ import { RuntimeUse } from "../quality/runtimeUse";
5
+ import type { RouteRuntime } from "../transforms/routeRuntime";
6
+
7
+ export interface RouteHandoffRead {
8
+ referenceFiles: string[];
9
+ unread: { file: string; why: string } | null;
10
+ }
11
+
12
+ interface FileRead {
13
+ models: string[];
14
+ unread: string | null;
15
+ }
16
+
17
+ const capitalize = (name: string) => name.charAt(0).toUpperCase() + name.slice(1);
18
+ const serverFetchSource =
19
+ /^(?:@(?:apps|libs)\/[^/]+\/(?:server|lib\/(?:sig|useServer))|\.{1,2}\/(?:.+\/)?(?:server|sig|useServer))$/;
20
+ const generatedFile = /^(?:apps|libs)\/[^/]+\/(?:(?:server|client)\.ts$|lib\/[^/]+\.ts$|lib\/__client\/)/;
21
+ //? A store's actions run in the browser, so what one names is never handed over while the server renders.
22
+ const storeFile = /\.store\.ts$/;
23
+ const handoffName = /\b(?:init|view|edit)[A-Z]|\bget[A-Z]\w*(?:Init|View|Edit)\b|\bslice\b/;
24
+ const handoffMember = /^(?:(?:init|view|edit)[A-Z]|get[A-Z]\w*(?:Init|View|Edit)$|slice$)/;
25
+
26
+ //? Only `fetch.init<Model>`, `view<Model>`, `edit<Model>`, their `get` forms and `fetch.slice` build a handoff object.
27
+ export class RouteHandoffs {
28
+ readonly #workspaceRoot: string;
29
+ readonly #runtime: RouteRuntime;
30
+ readonly #references: Map<string, string>;
31
+ readonly #files = new Map<string, Promise<FileRead>>();
32
+
33
+ constructor(workspaceRoot: string, runtime: RouteRuntime, references: Map<string, string>) {
34
+ this.#workspaceRoot = workspaceRoot;
35
+ this.#runtime = runtime;
36
+ this.#references = references;
37
+ }
38
+
39
+ async read(serverModules: string[]): Promise<RouteHandoffRead> {
40
+ const models = new Set<string>();
41
+ for (const file of serverModules) {
42
+ const read = await this.#fileOf(file);
43
+ if (read.unread)
44
+ return {
45
+ referenceFiles: [...this.#references.values()].sort(),
46
+ unread: { file: path.relative(this.#workspaceRoot, file).split(path.sep).join("/"), why: read.unread },
47
+ };
48
+ for (const model of read.models) models.add(model);
49
+ }
50
+ return { referenceFiles: [...models].flatMap((model) => this.#references.get(model) ?? []).sort(), unread: null };
51
+ }
52
+
53
+ #fileOf(absPath: string): Promise<FileRead> {
54
+ const known = this.#files.get(absPath);
55
+ if (known) return known;
56
+ const read = (async (): Promise<FileRead> => {
57
+ const fileName = this.#runtime.fileNameOf(absPath);
58
+ if (!fileName || generatedFile.test(fileName) || storeFile.test(fileName)) return { models: [], unread: null };
59
+ const text = await Bun.file(absPath).text();
60
+ const serverFetchLine = RouteHandoffs.#serverFetchLineOf(fileName, text);
61
+ if (serverFetchLine)
62
+ return {
63
+ models: [],
64
+ unread: `line ${serverFetchLine}: \`fetch\` comes from the server barrel, where the names read from it are not checked; take it from the client barrel`,
65
+ };
66
+ if (!RuntimeScopeReport.isRuntimeSource(fileName)) return { models: [], unread: null };
67
+ const verdict = RuntimeUse.analyze({ fileName, text }, this.#runtime.table);
68
+ if (!verdict.resolvable) return { models: [], unread: `line ${verdict.line}: ${verdict.message}` };
69
+ const named = verdict.owners.map(({ module }) => module).filter((module) => this.#references.has(module));
70
+ //? Every name of a readable file is written out in it, so a model none of these names can hand nothing over.
71
+ const anySlice = /slice/i.test(text);
72
+ const hands = (module: string) => new RegExp(`(?:init|view|edit|get)${capitalize(module)}`).test(text);
73
+ return { models: named.filter((module) => anySlice || hands(module)), unread: null };
74
+ })();
75
+ this.#files.set(absPath, read);
76
+ return read;
77
+ }
78
+
79
+ //? The server barrel's `fetch` hands the same references over, and the analysis reads only a client barrel's.
80
+ static #serverFetchLineOf(fileName: string, text: string): number | null {
81
+ if (!text.includes("fetch") || !handoffName.test(text)) return null;
82
+ const kind = fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
83
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind);
84
+ for (const statement of source.statements) {
85
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
86
+ const clause = statement.importClause;
87
+ if (!clause || clause.isTypeOnly || !serverFetchSource.test(statement.moduleSpecifier.text)) continue;
88
+ const bindings = clause.namedBindings;
89
+ if (!bindings) continue;
90
+ const line = source.getLineAndCharacterOfPosition(statement.getStart(source)).line + 1;
91
+ if (ts.isNamespaceImport(bindings)) return line;
92
+ const taken = bindings.elements.find((el) => !el.isTypeOnly && (el.propertyName ?? el.name).text === "fetch");
93
+ if (taken && RouteHandoffs.#handsOver(source, taken.name.text)) return line;
94
+ }
95
+ return null;
96
+ }
97
+
98
+ //? Text alone took `ips.slice(0, 1)` in a service that calls an endpoint for a slice handed over, on every route.
99
+ static #handsOver(source: ts.SourceFile, local: string): boolean {
100
+ const visit = (node: ts.Node): boolean => {
101
+ if (ts.isImportDeclaration(node)) return false;
102
+ if (ts.isIdentifier(node) && node.text === local) {
103
+ const { parent } = node;
104
+ const named =
105
+ (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
106
+ ((ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent) || ts.isPropertyDeclaration(parent)) &&
107
+ parent.name === node);
108
+ if (named) return false;
109
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === node)
110
+ return handoffMember.test(parent.name.text);
111
+ return true;
112
+ }
113
+ return ts.forEachChild(node, visit) ?? false;
114
+ };
115
+ return visit(source);
116
+ }
117
+ }
@@ -56,4 +56,36 @@ describe("RouteModulePreloads", () => {
56
56
  ],
57
57
  });
58
58
  });
59
+
60
+ test("a route asking an entry for some exports lists the chunks of those alone, and of them all when it asks for the file", () => {
61
+ const pair = entry("Pair");
62
+ const byExport = new RouteModulePreloads({
63
+ runtimeChunks: { runtime: [], vendors: {} },
64
+ entriesByRoute: new Map([
65
+ ["/a", [pair]],
66
+ ["/b", [pair]],
67
+ ["/whole", [pair]],
68
+ ["/unasked", [pair]],
69
+ ]),
70
+ askedByRoute: new Map<string, Map<string, string[] | null>>([
71
+ ["/a", new Map([[pair, ["A"]]])],
72
+ ["/b", new Map([[pair, ["B", "Missing"]]])],
73
+ ["/whole", new Map([[pair, null]])],
74
+ ]),
75
+ clientManifest: {
76
+ "apps/demo/ui/Pair.tsx#A": { ...row("/_akan/client/a.js", "/_akan/client/chunks/s.js"), name: "A" },
77
+ "apps/demo/ui/Pair.tsx#B": { ...row("/_akan/client/b.js", "/_akan/client/chunks/s.js"), name: "B" },
78
+ },
79
+ externalsByChunkUrl: {},
80
+ workspaceRoot: root,
81
+ });
82
+ const both = ["/_akan/client/a.js", "/_akan/client/chunks/s.js", "/_akan/client/b.js"];
83
+
84
+ expect(byExport.modulesByRoute()).toEqual({
85
+ "/a": ["/_akan/client/a.js", "/_akan/client/chunks/s.js"],
86
+ "/b": ["/_akan/client/b.js", "/_akan/client/chunks/s.js"],
87
+ "/whole": both,
88
+ "/unasked": both,
89
+ });
90
+ });
59
91
  });
@@ -1,12 +1,15 @@
1
1
  import type { ClientManifest } from "akanjs/server";
2
2
  import { ModulePreloadPlan, type ModulePreloadTable } from "akanjs/server/artifact/modulePreloadPlan";
3
3
  import { toClientReferencePath } from "../transforms/rscUseClientTransform";
4
+ import type { AskedExports } from "./clientBuildTypes";
4
5
 
5
6
  export type RuntimeChunks = Pick<ModulePreloadTable, "runtime" | "vendors">;
6
7
 
7
8
  export interface RouteModulePreloadsInput {
8
9
  runtimeChunks: RuntimeChunks;
9
10
  entriesByRoute: Map<string, string[]>;
11
+ /** The exports each route asks of its entries; an entry left out, or null, is preloaded with all of them. */
12
+ askedByRoute?: ReadonlyMap<string, AskedExports>;
10
13
  clientManifest: ClientManifest;
11
14
  externalsByChunkUrl: Record<string, string[]>;
12
15
  workspaceRoot: string;
@@ -15,13 +18,13 @@ export interface RouteModulePreloadsInput {
15
18
  export class RouteModulePreloads {
16
19
  readonly table: ModulePreloadTable;
17
20
  #input: RouteModulePreloadsInput;
18
- #chunksByReferenceId = new Map<string, Set<string>>();
21
+ #chunksByReferenceId = new Map<string, Map<string, string[]>>();
19
22
 
20
23
  constructor(input: RouteModulePreloadsInput) {
21
24
  this.#input = input;
22
25
  for (const [key, row] of Object.entries(input.clientManifest)) {
23
- const chunks = this.#chunksByReferenceId.getOrInsert(key.slice(0, key.lastIndexOf("#")), new Set());
24
- for (const url of row.chunks) chunks.add(url);
26
+ const hash = key.lastIndexOf("#");
27
+ this.#chunksByReferenceId.getOrInsert(key.slice(0, hash), new Map()).set(key.slice(hash + 1), row.chunks);
25
28
  }
26
29
  this.table = {
27
30
  ...input.runtimeChunks,
@@ -39,14 +42,20 @@ export class RouteModulePreloads {
39
42
  modulesByRoute(): Record<string, string[]> {
40
43
  const plan = new ModulePreloadPlan(this.table);
41
44
  return Object.fromEntries(
42
- [...this.#input.entriesByRoute].map(([routeId, entries]) => [
43
- routeId,
44
- plan.urlsOf(
45
- entries.flatMap((entry) => [
46
- ...(this.#chunksByReferenceId.get(toClientReferencePath(entry, this.#input.workspaceRoot)) ?? []),
47
- ]),
48
- ),
49
- ]),
45
+ [...this.#input.entriesByRoute].map(([routeId, entries]) => {
46
+ const asked = this.#input.askedByRoute?.get(routeId);
47
+ return [
48
+ routeId,
49
+ plan.urlsOf([...new Set(entries.flatMap((entry) => this.#chunksOf(entry, asked?.get(entry))))]),
50
+ ];
51
+ }),
50
52
  );
51
53
  }
54
+
55
+ #chunksOf(entry: string, names?: readonly string[] | null): string[] {
56
+ const chunksByName = this.#chunksByReferenceId.get(toClientReferencePath(entry, this.#input.workspaceRoot));
57
+ if (!chunksByName) return [];
58
+ const rows = names ? names.map((name) => chunksByName.get(name) ?? []) : [...chunksByName.values()];
59
+ return rows.flat();
60
+ }
52
61
  }
@@ -0,0 +1,280 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { ClientBundleGraph } from "./clientBuildTypes";
3
+ import { RouteRuntimeCheck } from "./routeRuntimeCheck";
4
+
5
+ const root = "/ws";
6
+ const abs = (file: string) => `${root}/${file}`;
7
+ const fetchPiece = "apps/demo/lib/__client/memo.fetch.ts";
8
+ const storePiece = "apps/demo/lib/__client/memo.st.ts";
9
+ const storeFile = "apps/demo/lib/memo/memo.store.ts";
10
+ const card = "apps/demo/ui/Card.tsx";
11
+
12
+ interface GraphShape {
13
+ imports: Record<string, (string | { lazy: string })[]>;
14
+ chunks?: Record<string, string[]>;
15
+ chunkImports?: Record<string, string[]>;
16
+ }
17
+
18
+ const graphOf = ({ imports, chunks = {}, chunkImports = {} }: GraphShape): ClientBundleGraph => ({
19
+ importsByModule: new Map(
20
+ Object.entries(imports).map(([module, list]) => [
21
+ abs(module),
22
+ list.map((imported) =>
23
+ typeof imported === "string" ? { path: abs(imported), lazy: false } : { path: abs(imported.lazy), lazy: true },
24
+ ),
25
+ ]),
26
+ ),
27
+ chunksByModule: new Map(Object.entries(chunks).map(([module, list]) => [abs(module), list])),
28
+ importsByChunk: new Map(Object.entries(chunkImports)),
29
+ });
30
+
31
+ interface NarrowedShape {
32
+ entries: Record<string, string>;
33
+ wholeReaders?: string[];
34
+ wholeConstantReaders?: string[];
35
+ }
36
+
37
+ const failuresOf = (shape: GraphShape, narrowed?: NarrowedShape) =>
38
+ new RouteRuntimeCheck(
39
+ root,
40
+ graphOf(shape),
41
+ narrowed
42
+ ? {
43
+ entries: new Map(Object.entries(narrowed.entries).map(([build, entry]) => [abs(build), abs(entry)])),
44
+ wholeReaders: new Set((narrowed.wholeReaders ?? []).map(abs)),
45
+ wholeConstantReaders: new Set((narrowed.wholeConstantReaders ?? []).map(abs)),
46
+ }
47
+ : null,
48
+ ).failures;
49
+
50
+ describe("what a build loading per module checks in its own output", () => {
51
+ const storeAndPiece = { [storeFile]: [fetchPiece], [fetchPiece]: [] };
52
+
53
+ test("a module's chunk reaches the chunk of each runtime piece it imports, directly, through another chunk or by holding it", () => {
54
+ const split = { [storeFile]: ["/out/store.js"], [fetchPiece]: ["/out/fetch.js"] };
55
+ expect(failuresOf({ imports: storeAndPiece, chunks: split })).toEqual([
56
+ "apps/demo/lib/memo/memo.store.ts needs apps/demo/lib/__client/memo.fetch.ts loaded first, but its chunk store.js does not import the chunk holding that piece",
57
+ ]);
58
+ const direct = { "/out/store.js": ["/out/fetch.js"] };
59
+ const through = { "/out/store.js": ["/out/shared.js"], "/out/shared.js": ["/out/fetch.js"] };
60
+ expect(failuresOf({ imports: storeAndPiece, chunks: split, chunkImports: direct })).toEqual([]);
61
+ expect(failuresOf({ imports: storeAndPiece, chunks: split, chunkImports: through })).toEqual([]);
62
+ const together = { [storeFile]: ["/out/store.js"], [fetchPiece]: ["/out/store.js"] };
63
+ expect(failuresOf({ imports: storeAndPiece, chunks: together })).toEqual([]);
64
+ });
65
+
66
+ test("every chunk a module is copied into reaches the piece, and a piece asked for with `import()` needs no order", () => {
67
+ const copied = { [storeFile]: ["/out/a.js", "/out/b.js"], [fetchPiece]: ["/out/fetch.js"] };
68
+ const onlyFirst = { "/out/a.js": ["/out/fetch.js"] };
69
+ expect(failuresOf({ imports: storeAndPiece, chunks: copied, chunkImports: onlyFirst })).toHaveLength(1);
70
+ const lazy = { [card]: [{ lazy: storePiece }], [storePiece]: [] };
71
+ const apart = { [card]: ["/out/card.js"], [storePiece]: ["/out/piece.js"] };
72
+ expect(failuresOf({ imports: lazy, chunks: apart })).toEqual([]);
73
+ });
74
+
75
+ test("a file bundled in parts is checked part by part: only the chunk of the part importing a piece has to reach it", () => {
76
+ const graph = graphOf({
77
+ imports: { [card]: [storePiece], [storePiece]: [] },
78
+ chunks: { [card]: ["/out/naming.js", "/out/plain.js"], [storePiece]: ["/out/piece.js"] },
79
+ chunkImports: { "/out/naming.js": ["/out/piece.js"] },
80
+ });
81
+ const part = (id: string) => `${abs(card)}?akan-part=${id}`;
82
+ const linked = [
83
+ { module: part("p0"), imports: [{ path: abs(storePiece), lazy: false }], chunks: ["/out/naming.js"] },
84
+ { module: part("p1"), imports: [], chunks: ["/out/plain.js"] },
85
+ { module: abs(storePiece), imports: [], chunks: ["/out/piece.js"] },
86
+ ];
87
+
88
+ expect(new RouteRuntimeCheck(root, graph, null).failures).toHaveLength(1);
89
+ expect(new RouteRuntimeCheck(root, { ...graph, linked }, null).failures).toEqual([]);
90
+ const misplaced = linked.map((input) =>
91
+ input.module === part("p0") ? { ...input, chunks: ["/out/plain.js"] } : input,
92
+ );
93
+ expect(new RouteRuntimeCheck(root, { ...graph, linked: misplaced }, null).failures).toEqual([
94
+ "apps/demo/ui/Card.tsx?akan-part=p0 needs apps/demo/lib/__client/memo.st.ts loaded first, but its chunk plain.js does not import the chunk holding that piece",
95
+ ]);
96
+ });
97
+
98
+ test("no store file is imported back by a runtime piece that a file it imports loads", () => {
99
+ const helper = "apps/demo/webkit/relabel.ts";
100
+ const cycle = { [storeFile]: [helper], [helper]: [storePiece], [storePiece]: [storeFile] };
101
+ expect(failuresOf({ imports: cycle })).toEqual([
102
+ "apps/demo/lib/memo/memo.store.ts imports apps/demo/webkit/relabel.ts, which loads apps/demo/lib/__client/memo.st.ts, and that piece imports the store file back before it is defined: move what apps/demo/webkit/relabel.ts reads from the store out of the files a store file imports",
103
+ ]);
104
+ expect(failuresOf({ imports: { ...cycle, [helper]: [] } })).toEqual([]);
105
+ const uiCycle = { [card]: ["apps/demo/ui/Frame.tsx"], "apps/demo/ui/Frame.tsx": [card, storePiece] };
106
+ expect(failuresOf({ imports: { ...uiCycle, [storePiece]: [storeFile], [storeFile]: [] } })).toEqual([]);
107
+ });
108
+
109
+ test("a page built to load only the modules its code names reaches neither a file needing every module nor the runtime of every module", () => {
110
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/Card.tsx";
111
+ const run = "apps/demo/ui/Run.tsx";
112
+ const whole = "apps/demo/lib/st.ts";
113
+ const entries = { [entry]: card };
114
+ expect(
115
+ failuresOf({ imports: { [entry]: [card], [card]: [run], [run]: [] } }, { entries, wholeReaders: [run] }),
116
+ ).toEqual([
117
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but it reaches apps/demo/ui/Run.tsx, which needs every module",
118
+ ]);
119
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [whole], [whole]: [] } }, { entries })).toEqual([
120
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but apps/demo/ui/Card.tsx imports apps/demo/lib/st.ts, the runtime of every module",
121
+ ]);
122
+ expect(
123
+ failuresOf(
124
+ { imports: { [entry]: [card], [card]: [{ lazy: run }], [run]: [] } },
125
+ { entries, wholeReaders: [run] },
126
+ ),
127
+ ).toEqual([]);
128
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [] } }, { entries, wholeReaders: [run] })).toEqual([]);
129
+ });
130
+
131
+ test("a registration piece loads before the file reading its model, and no file it loads imports it back", () => {
132
+ const registration = "apps/demo/lib/__client/memo.cnst.ts";
133
+ const constant = "apps/demo/lib/memo/memo.constant.ts";
134
+ const reads = { [card]: [registration], [registration]: [constant], [constant]: [] };
135
+ const apart = { [card]: ["/out/card.js"], [registration]: ["/out/cnst.js"] };
136
+ expect(failuresOf({ imports: reads, chunks: apart })).toEqual([
137
+ "apps/demo/ui/Card.tsx needs apps/demo/lib/__client/memo.cnst.ts loaded first, but its chunk card.js does not import the chunk holding that piece",
138
+ ]);
139
+ expect(failuresOf({ imports: reads, chunks: apart, chunkImports: { "/out/card.js": ["/out/cnst.js"] } })).toEqual(
140
+ [],
141
+ );
142
+ const helper = "apps/demo/common/label.ts";
143
+ const back = { [registration]: [constant], [constant]: [helper], [helper]: [registration] };
144
+ expect(failuresOf({ imports: back })).toEqual([
145
+ "apps/demo/lib/__client/memo.cnst.ts loads files that import it back through apps/demo/common/label.ts, which reads the model before it is registered",
146
+ ]);
147
+ expect(failuresOf({ imports: { ...back, [helper]: [] } })).toEqual([]);
148
+ });
149
+
150
+ test("a registration piece answering from `lib/cnst.ts` needs that file loaded first, wherever its bare re-export lands", () => {
151
+ const answering = "apps/demo/lib/__client/board.cnst.ts";
152
+ const constants = "apps/demo/lib/cnst.ts";
153
+ const imports = { [fetchPiece]: [answering], [answering]: [constants], [constants]: [] };
154
+ const chunks = { [fetchPiece]: ["/out/fetch.js"], [answering]: ["/out/empty.js"], [constants]: ["/out/cnst.js"] };
155
+ const toConstants = { "/out/fetch.js": ["/out/cnst.js"] };
156
+ const answered = { entries: {}, wholeConstantReaders: [answering] };
157
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants }, answered)).toEqual([]);
158
+ expect(failuresOf({ imports, chunks }, answered)).toEqual([
159
+ "apps/demo/lib/__client/memo.fetch.ts needs apps/demo/lib/__client/board.cnst.ts loaded first, but its chunk fetch.js does not import the chunk holding that piece",
160
+ ]);
161
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants }, { entries: {} })).toHaveLength(1);
162
+ expect(failuresOf({ imports, chunks, chunkImports: toConstants })).toHaveLength(1);
163
+ const together = { ...imports, [constants]: [answering] };
164
+ expect(failuresOf({ imports: together }, answered)).toEqual([]);
165
+ expect(failuresOf({ imports: together }, { entries: {} })).toHaveLength(1);
166
+ });
167
+
168
+ test("a page built to load only the modules its code names reaches every constant only through a file `akan quality runtime` names", () => {
169
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/Card.tsx";
170
+ const entries = { [entry]: card };
171
+ const registration = "apps/demo/lib/__client/board.cnst.ts";
172
+ const constant = "apps/demo/lib/board/board.constant.ts";
173
+ const barrel = "libs/kit/index.ts";
174
+ const libConstants = "libs/kit/lib/cnst.ts";
175
+ const throughBarrel = {
176
+ [entry]: [card],
177
+ [card]: [registration],
178
+ [registration]: [constant],
179
+ [constant]: [barrel],
180
+ [barrel]: [libConstants],
181
+ [libConstants]: [],
182
+ };
183
+ expect(failuresOf({ imports: throughBarrel }, { entries })).toEqual([
184
+ "apps/demo/ui/Card.tsx was built to load only the modules its code names, but libs/kit/index.ts imports libs/kit/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
185
+ ]);
186
+ expect(failuresOf({ imports: throughBarrel }, { entries, wholeConstantReaders: [constant] })).toEqual([]);
187
+ const own = "apps/demo/lib/cnst.ts";
188
+ const computed = { [entry]: [card], [card]: [own], [own]: [] };
189
+ expect(failuresOf({ imports: computed }, { entries })).toHaveLength(1);
190
+ expect(failuresOf({ imports: computed }, { entries, wholeConstantReaders: [card] })).toEqual([]);
191
+ expect(failuresOf({ imports: { [entry]: [card], [card]: [{ lazy: own }], [own]: [] } }, { entries })).toEqual([]);
192
+ });
193
+
194
+ test("a page a registration piece answering from `lib/cnst.ts` already makes load every constant may reach them through a constant file left as written, and no further than that piece loads", () => {
195
+ const entry = "apps/demo/.akan/generated/client-entry-bootstrap-route/board.ref.tsx";
196
+ const reference = "apps/demo/lib/__client/board.ref.ts";
197
+ const entries = { [entry]: reference };
198
+ const boardStorePiece = "apps/demo/lib/__client/board.st.ts";
199
+ const boardStore = "libs/kit/lib/board/board.store.ts";
200
+ const answering = "libs/kit/lib/__client/board.cnst.ts";
201
+ const constant = "libs/kit/lib/board/board.constant.ts";
202
+ const [kitConstants, appConstants] = ["libs/kit/lib/cnst.ts", "apps/demo/lib/cnst.ts"];
203
+ const [baseBarrel, baseConstants] = ["libs/base/index.ts", "libs/base/lib/cnst.ts"];
204
+ const handedOverByNoRoute = {
205
+ [entry]: [reference],
206
+ [reference]: [boardStorePiece],
207
+ [boardStorePiece]: [boardStore],
208
+ [boardStore]: [answering, constant],
209
+ [answering]: [kitConstants, appConstants],
210
+ [kitConstants]: [constant],
211
+ [constant]: [baseBarrel],
212
+ [baseBarrel]: [baseConstants],
213
+ [appConstants]: [kitConstants, baseBarrel],
214
+ [baseConstants]: [],
215
+ };
216
+ expect(failuresOf({ imports: handedOverByNoRoute }, { entries, wholeConstantReaders: [answering] })).toEqual([]);
217
+ expect(failuresOf({ imports: handedOverByNoRoute }, { entries })).toEqual([
218
+ "apps/demo/lib/__client/board.ref.ts was built to load only the modules its code names, but libs/kit/lib/__client/board.cnst.ts imports libs/kit/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
219
+ ]);
220
+ const ownScopeOnly = { ...handedOverByNoRoute, [answering]: [kitConstants], [kitConstants]: [] };
221
+ expect(failuresOf({ imports: ownScopeOnly }, { entries, wholeConstantReaders: [answering] })).toEqual([
222
+ "apps/demo/lib/__client/board.ref.ts was built to load only the modules its code names, but libs/base/index.ts imports libs/base/lib/cnst.ts, the constants of every model, for no reason `akan quality runtime` names",
223
+ ]);
224
+ });
225
+
226
+ test("a failing check names the first failures, how many more there are, what the build does instead and that it is a bug to report", () => {
227
+ const stores = Array.from(
228
+ { length: RouteRuntimeCheck.shown + 2 },
229
+ (_, index) => `apps/demo/lib/m${index}/m${index}.store.ts`,
230
+ );
231
+ const imports = { ...Object.fromEntries(stores.map((store) => [store, [fetchPiece]])), [fetchPiece]: [] };
232
+ const chunks = {
233
+ ...Object.fromEntries(stores.map((store) => [store, ["/out/store.js"]])),
234
+ [fetchPiece]: ["/out/fetch.js"],
235
+ };
236
+ const check = new RouteRuntimeCheck(root, graphOf({ imports, chunks }));
237
+ expect(check.refusal).toBe(
238
+ [
239
+ "[client-runtime] loading per module, this build would not load its modules in order:",
240
+ ...stores
241
+ .slice(0, RouteRuntimeCheck.shown)
242
+ .map(
243
+ (store) =>
244
+ ` - ${store} needs ${fetchPiece} loaded first, but its chunk store.js does not import the chunk holding that piece`,
245
+ ),
246
+ " - and 2 more",
247
+ "Every page of this build loads the whole client runtime instead, not only what it uses. This is a bug in akan: report it with the lines above.",
248
+ ].join("\n"),
249
+ );
250
+ expect(new RouteRuntimeCheck(root, graphOf({ imports: storeAndPiece })).refusal).toBeNull();
251
+ });
252
+
253
+ test("a route loading a scope's whole file and a piece of that scope is named, unless one of the two takes its part from the other", () => {
254
+ const whole = "apps/demo/lib/useClient.ts";
255
+ const constants = "apps/demo/lib/cnst.ts";
256
+ const constantPiece = "apps/demo/lib/__client/memo.cnst.ts";
257
+ const kitPiece = "libs/kit/lib/__client/memo.fetch.ts";
258
+ const frame = "apps/demo/ui/Frame.tsx";
259
+ const later = "apps/demo/ui/Later.tsx";
260
+ const repeatedOf = (imports: GraphShape["imports"], routes: Record<string, string[]>) =>
261
+ new RouteRuntimeCheck(root, graphOf({ imports }), {
262
+ entries: new Map(),
263
+ wholeReaders: new Set(),
264
+ routes: new Map(Object.entries(routes).map(([route, entries]) => [route, entries.map(abs)])),
265
+ }).repeated;
266
+ const both = { [frame]: [whole], [card]: [fetchPiece], [whole]: [], [fetchPiece]: [] };
267
+ expect(repeatedOf(both, { "/frame": [frame, card], "/plain": [frame], "/card": [card] })).toEqual([
268
+ `${whole} and ${fetchPiece} both load on 1 route(s), the first /frame: the piece holds again what the file holds`,
269
+ ]);
270
+ expect(repeatedOf({ ...both, [whole]: [fetchPiece] }, { "/frame": [frame, card] })).toEqual([]);
271
+ expect(repeatedOf({ ...both, [fetchPiece]: [whole] }, { "/frame": [frame, card] })).toEqual([]);
272
+ expect(repeatedOf({ ...both, [card]: [kitPiece], [kitPiece]: [] }, { "/frame": [frame, card] })).toEqual([]);
273
+ const asked = { [frame]: [whole, { lazy: later }], [later]: [fetchPiece], [whole]: [], [fetchPiece]: [] };
274
+ expect(repeatedOf(asked, { "/frame": [frame] })).toHaveLength(1);
275
+ const registered = { [frame]: [constants], [card]: [constantPiece], [constants]: [], [constantPiece]: [] };
276
+ expect(repeatedOf(registered, { "/frame": [frame, card] })).toEqual([
277
+ `${constants} and ${constantPiece} both load on 1 route(s), the first /frame: the piece holds again what the file holds`,
278
+ ]);
279
+ });
280
+ });