@akanjs/devkit 3.3.0-rc.8 → 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 -2903
  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,136 @@
1
+ import path from "node:path";
2
+ import { createAst, createFactReader } from "@akanjs/language";
3
+ import { Glob } from "bun";
4
+ import ts from "typescript";
5
+
6
+ type GroupKind = "model" | "service" | "scalar" | "enum";
7
+
8
+ const constantFile = /(?:^|\/)lib\/(?:(__scalar)\/)?(_?)([A-Za-z0-9]+)\/\3\.constant\.ts$/;
9
+ const enumClass = /class\s+([A-Za-z0-9_$]+)\s+extends\s+enumOf\(\s*["'`]([A-Za-z0-9_$]+)["'`]/g;
10
+
11
+ //* The dictionary groups a model's texts reach: a framework view, list or form labels the model's fields, the enums
12
+ //* and scalars they hold, and the models they refer to (a relation shows the other model's name).
13
+ export class DictionaryConstants {
14
+ static readonly #reader = createFactReader(ts, createAst(ts));
15
+ readonly #groupOfClass = new Map<string, Set<string>>();
16
+ readonly #kindOf = new Map<string, GroupKind>();
17
+ readonly #typesOf = new Map<string, Set<string>>();
18
+ readonly #reach = new Map<string, string[]>();
19
+ readonly #statics = new Map<string, (string[] | null)[]>();
20
+ readonly #classCount = new Map<string, number>();
21
+
22
+ static async read(workspaceRoot: string, scopes: string[]): Promise<DictionaryConstants> {
23
+ const constants = new DictionaryConstants();
24
+ for (const scope of scopes)
25
+ for await (const rel of new Glob("lib/**/*.constant.ts").scan({ cwd: path.join(workspaceRoot, scope) })) {
26
+ const file = path.join(workspaceRoot, scope, rel);
27
+ constants.add(`${scope}/${rel}`, await Bun.file(file).text());
28
+ }
29
+ return constants;
30
+ }
31
+
32
+ add(fileName: string, text: string) {
33
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
34
+ this.#addStatics(sourceFile);
35
+ const [, scalar, underscore, group] = fileName.match(constantFile) ?? [];
36
+ if (!group) return;
37
+ this.#kindOf.set(group, scalar ? "scalar" : underscore ? "service" : "model");
38
+ const types = this.#typesOf.get(group) ?? new Set<string>();
39
+ for (const constant of DictionaryConstants.#reader.read(sourceFile, null).constants) {
40
+ this.#classTo(constant.name, group);
41
+ for (const field of constant.fields) if (field.type) types.add(field.type);
42
+ }
43
+ this.#typesOf.set(group, types);
44
+ for (const [, name, ref] of text.matchAll(enumClass))
45
+ if (name && ref) {
46
+ this.#classTo(name, ref);
47
+ this.#kindOf.set(ref, "enum");
48
+ }
49
+ }
50
+
51
+ #addStatics(sourceFile: ts.SourceFile) {
52
+ for (const statement of sourceFile.statements) {
53
+ if (!ts.isClassDeclaration(statement) || !statement.name) continue;
54
+ this.#classCount.set(statement.name.text, (this.#classCount.get(statement.name.text) ?? 0) + 1);
55
+ for (const member of statement.members) {
56
+ const name =
57
+ member.name && (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && member.name.text;
58
+ if (!name || !(ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static)) continue;
59
+ const key = `${statement.name.text}.${name}`;
60
+ const table = ts.isPropertyDeclaration(member) ? DictionaryConstants.#tableOf(member) : null;
61
+ this.#statics.set(key, [...(this.#statics.get(key) ?? []), table]);
62
+ }
63
+ }
64
+ }
65
+
66
+ //? `as const` with no annotation types the static as its literals, so nothing but the written keys is assignable to it.
67
+ static #tableOf(member: ts.PropertyDeclaration): string[] | null {
68
+ let node = member.initializer;
69
+ while (node && (ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node))) node = node.expression;
70
+ if (member.type || !node || !ts.isAsExpression(node) || !ts.isConstTypeReference(node.type)) return null;
71
+ let table = node.expression;
72
+ while (ts.isParenthesizedExpression(table)) table = table.expression;
73
+ const values = ts.isArrayLiteralExpression(table)
74
+ ? [...table.elements]
75
+ : ts.isObjectLiteralExpression(table)
76
+ ? table.properties.map((property) =>
77
+ ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name)
78
+ ? property.initializer
79
+ : null,
80
+ )
81
+ : [null];
82
+ const keys: string[] = [];
83
+ for (const value of values) {
84
+ if (!value || !ts.isStringLiteralLike(value)) return null;
85
+ keys.push(value.text);
86
+ }
87
+ return keys;
88
+ }
89
+
90
+ //? An app and a lib may each declare a class of the name, and one that leaves the static out may inherit another.
91
+ staticKeysOf(className: string, member: string): string[] | null {
92
+ const tables = this.#statics.get(`${className}.${member}`);
93
+ if (!tables || tables.length !== this.#classCount.get(className)) return null;
94
+ const keys = new Set<string>();
95
+ for (const table of tables) {
96
+ if (!table) return null;
97
+ for (const key of table) keys.add(key);
98
+ }
99
+ return [...keys];
100
+ }
101
+
102
+ #classTo(name: string, group: string) {
103
+ this.#groupOfClass.set(name, (this.#groupOfClass.get(name) ?? new Set()).add(group));
104
+ }
105
+
106
+ groupsOfClass(name: string): string[] {
107
+ return [...(this.#groupOfClass.get(name) ?? [])];
108
+ }
109
+
110
+ //? A relation is followed one step: the other model's name and its own enums and scalars, not its relations.
111
+ reachOf(group: string): string[] {
112
+ const known = this.#reach.get(group);
113
+ if (known) return known;
114
+ const reached = new Set<string>([group]);
115
+ this.#holds(group, reached, true);
116
+ const result = [...reached].sort();
117
+ this.#reach.set(group, result);
118
+ return result;
119
+ }
120
+
121
+ #holds(group: string, reached: Set<string>, followRelations: boolean) {
122
+ for (const type of this.#typesOf.get(group) ?? [])
123
+ for (const held of this.groupsOfClass(type)) {
124
+ if (reached.has(held)) continue;
125
+ const kind = this.#kindOf.get(held);
126
+ if (kind === "model" || kind === "service") {
127
+ if (!followRelations) continue;
128
+ reached.add(held);
129
+ this.#holds(held, reached, false);
130
+ } else {
131
+ reached.add(held);
132
+ this.#holds(held, reached, followRelations);
133
+ }
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,88 @@
1
+ export interface DictionaryOwnNeed {
2
+ routeId: string;
3
+ groups: string[];
4
+ //? What the route may still download of texts it does not show, after the shared files it keeps.
5
+ left: number;
6
+ }
7
+
8
+ interface OwnCluster {
9
+ groups: Set<string>;
10
+ bytes: number;
11
+ members: { routeId: string; left: number }[];
12
+ }
13
+
14
+ //? Two own files become one where that adds their routes fewer bytes than the files share, so neighbouring pages reuse it.
15
+ export class DictionaryOwnParts {
16
+ static share(
17
+ needs: readonly DictionaryOwnNeed[],
18
+ bytesOf: (group: string) => number,
19
+ ): { parts: string[][]; partOf: Map<string, number> } {
20
+ const byKey = new Map<string, OwnCluster>();
21
+ for (const { routeId, groups, left } of needs) {
22
+ const key = groups.join("\n");
23
+ const cluster = byKey.get(key) ?? {
24
+ groups: new Set(groups),
25
+ bytes: groups.reduce((sum, group) => sum + bytesOf(group), 0),
26
+ members: [],
27
+ };
28
+ cluster.members.push({ routeId, left });
29
+ byKey.set(key, cluster);
30
+ }
31
+ const clusters = [...byKey.values()];
32
+ const shared = clusters.map((a) => clusters.map((b) => DictionaryOwnParts.#sharedBytes(a, b, bytesOf)));
33
+ for (;;) {
34
+ const pair = DictionaryOwnParts.#bestPair(clusters, shared);
35
+ if (!pair) break;
36
+ DictionaryOwnParts.#merge(clusters, shared, pair, bytesOf);
37
+ }
38
+ const live = clusters.filter(({ members }) => members.length);
39
+ const parts = live.map(({ groups }) => [...groups].sort());
40
+ const partOf = new Map(live.flatMap(({ members }, idx) => members.map(({ routeId }) => [routeId, idx] as const)));
41
+ return { parts, partOf };
42
+ }
43
+
44
+ static #bestPair(clusters: OwnCluster[], shared: number[][]): { p: number; q: number } | null {
45
+ let best: { p: number; q: number; saved: number } | null = null;
46
+ for (let p = 0; p < clusters.length; p++)
47
+ for (let q = p + 1; q < clusters.length; q++) {
48
+ const [a, b] = [clusters[p] as OwnCluster, clusters[q] as OwnCluster];
49
+ if (!a.members.length || !b.members.length) continue;
50
+ const both = shared[p]?.[q] ?? 0;
51
+ const [toA, toB] = [b.bytes - both, a.bytes - both];
52
+ if (a.members.some(({ left }) => left < toA) || b.members.some(({ left }) => left < toB)) continue;
53
+ if (toA * a.members.length + toB * b.members.length >= both) continue;
54
+ if (!best || both > best.saved) best = { p, q, saved: both };
55
+ }
56
+ return best;
57
+ }
58
+
59
+ static #merge(
60
+ clusters: OwnCluster[],
61
+ shared: number[][],
62
+ { p, q }: { p: number; q: number },
63
+ bytesOf: (group: string) => number,
64
+ ) {
65
+ const [a, b] = [clusters[p] as OwnCluster, clusters[q] as OwnCluster];
66
+ const both = shared[p]?.[q] ?? 0;
67
+ const [toA, toB] = [b.bytes - both, a.bytes - both];
68
+ for (const member of a.members) member.left -= toA;
69
+ for (const member of b.members) member.left -= toB;
70
+ for (const group of b.groups) a.groups.add(group);
71
+ a.bytes += toA;
72
+ a.members.push(...b.members);
73
+ b.members = [];
74
+ b.groups = new Set();
75
+ b.bytes = 0;
76
+ clusters.forEach((other, idx) => {
77
+ const bytes = DictionaryOwnParts.#sharedBytes(a, other, bytesOf);
78
+ (shared[p] as number[])[idx] = bytes;
79
+ (shared[idx] as number[])[p] = bytes;
80
+ });
81
+ }
82
+
83
+ static #sharedBytes(a: OwnCluster, b: OwnCluster, bytesOf: (group: string) => number): number {
84
+ let bytes = 0;
85
+ for (const group of a.groups) if (b.groups.has(group)) bytes += bytesOf(group);
86
+ return bytes;
87
+ }
88
+ }
@@ -0,0 +1,131 @@
1
+ interface PairCost {
2
+ p: number;
3
+ q: number;
4
+ cost: number;
5
+ }
6
+
7
+ export class DictionaryPackState {
8
+ readonly #routeCount: number;
9
+ readonly #words: number;
10
+ readonly #groups: string[][];
11
+ readonly #bytes: number[];
12
+ readonly #routes: Uint32Array[];
13
+ readonly #alive: boolean[];
14
+ readonly #overfetch: Float64Array;
15
+ readonly #budget: number;
16
+ //? |routes of p ∩ routes of q|, so a merge's cost needs no pass over the routes.
17
+ readonly #shared: Int32Array;
18
+
19
+ constructor(
20
+ routeCount: number,
21
+ parts: readonly (readonly [groups: string[], routes: number[]])[],
22
+ bytesOf: (group: string) => number,
23
+ budget: number,
24
+ ) {
25
+ this.#routeCount = routeCount;
26
+ this.#words = Math.ceil(routeCount / 32);
27
+ this.#groups = parts.map(([groups]) => [...groups]);
28
+ this.#bytes = parts.map(([groups]) => groups.reduce((sum, group) => sum + bytesOf(group), 0));
29
+ this.#routes = parts.map(([, routes]) => {
30
+ const bits = new Uint32Array(this.#words);
31
+ for (const route of routes) bits[route >>> 5] = (bits[route >>> 5] ?? 0) | (1 << (route & 31));
32
+ return bits;
33
+ });
34
+ this.#alive = parts.map(() => true);
35
+ this.#overfetch = new Float64Array(routeCount);
36
+ this.#budget = budget;
37
+ this.#shared = new Int32Array(parts.length * parts.length);
38
+ for (let p = 0; p < parts.length; p++) this.#countRow(p);
39
+ }
40
+
41
+ parts(): string[][] {
42
+ return this.#groups.filter((_, p) => this.#alive[p]);
43
+ }
44
+
45
+ //? Only a pair whose merge pays for itself, the cheapest first, passing over one that puts a route over its budget.
46
+ mergeCheapest(requestBytes: number): boolean {
47
+ const alive = this.#groups.flatMap((_, p) => (this.#alive[p] ? [p] : []));
48
+ const pairs: PairCost[] = [];
49
+ let best: PairCost | null = null;
50
+ for (let x = 0; x < alive.length; x++)
51
+ for (let y = x + 1; y < alive.length; y++) {
52
+ const [p, q] = [alive[x] as number, alive[y] as number];
53
+ const both = this.#count(p, q);
54
+ const cost =
55
+ (this.#bytes[q] ?? 0) * (this.#count(p, p) - both) +
56
+ (this.#bytes[p] ?? 0) * (this.#count(q, q) - both) -
57
+ requestBytes * both;
58
+ if (cost >= 0) continue;
59
+ const pair = { p, q, cost };
60
+ pairs.push(pair);
61
+ if (!best || cost < best.cost) best = pair;
62
+ }
63
+ if (best && this.#fits(best)) return this.#merge(best);
64
+ pairs.sort((a, b) => a.cost - b.cost);
65
+ const fitting = pairs.find((pair) => pair !== best && this.#fits(pair));
66
+ return fitting ? this.#merge(fitting) : false;
67
+ }
68
+
69
+ #fits({ p, q }: PairCost): boolean {
70
+ const [rp, rq] = [this.#routes[p] as Uint32Array, this.#routes[q] as Uint32Array];
71
+ const [bp, bq] = [this.#bytes[p] ?? 0, this.#bytes[q] ?? 0];
72
+ for (let word = 0; word < this.#words; word++) {
73
+ const [onlyP, onlyQ] = [(rp[word] ?? 0) & ~(rq[word] ?? 0), (rq[word] ?? 0) & ~(rp[word] ?? 0)];
74
+ if (!this.#within(word, onlyP, bq) || !this.#within(word, onlyQ, bp)) return false;
75
+ }
76
+ return true;
77
+ }
78
+
79
+ #within(word: number, bits: number, added: number): boolean {
80
+ for (let set = bits >>> 0; set; set = (set & (set - 1)) >>> 0)
81
+ if ((this.#overfetch[word * 32 + 31 - Math.clz32(set & -set)] ?? 0) + added > this.#budget) return false;
82
+ return true;
83
+ }
84
+
85
+ #merge({ p, q }: PairCost): true {
86
+ const [rp, rq] = [this.#routes[p] as Uint32Array, this.#routes[q] as Uint32Array];
87
+ const [bp, bq] = [this.#bytes[p] ?? 0, this.#bytes[q] ?? 0];
88
+ for (let word = 0; word < this.#words; word++) {
89
+ this.#add(word, (rp[word] ?? 0) & ~(rq[word] ?? 0), bq);
90
+ this.#add(word, (rq[word] ?? 0) & ~(rp[word] ?? 0), bp);
91
+ rp[word] = (rp[word] ?? 0) | (rq[word] ?? 0);
92
+ }
93
+ this.#groups[p] = [...(this.#groups[p] ?? []), ...(this.#groups[q] ?? [])].sort();
94
+ this.#bytes[p] = bp + bq;
95
+ this.#alive[q] = false;
96
+ this.#countRow(p);
97
+ return true;
98
+ }
99
+
100
+ #add(word: number, bits: number, added: number) {
101
+ for (let set = bits >>> 0; set; set = (set & (set - 1)) >>> 0) {
102
+ const route = word * 32 + 31 - Math.clz32(set & -set);
103
+ if (route < this.#routeCount) this.#overfetch[route] = (this.#overfetch[route] ?? 0) + added;
104
+ }
105
+ }
106
+
107
+ #countRow(p: number) {
108
+ const size = this.#groups.length;
109
+ const rp = this.#routes[p] as Uint32Array;
110
+ for (let q = 0; q < size; q++) {
111
+ if (!this.#alive[q]) continue;
112
+ const rq = this.#routes[q] as Uint32Array;
113
+ let count = 0;
114
+ for (let word = 0; word < this.#words; word++)
115
+ count += DictionaryPackState.#popcount((rp[word] ?? 0) & (rq[word] ?? 0));
116
+ this.#shared[p * size + q] = count;
117
+ this.#shared[q * size + p] = count;
118
+ }
119
+ }
120
+
121
+ #count(p: number, q: number): number {
122
+ return this.#shared[p * this.#groups.length + q] ?? 0;
123
+ }
124
+
125
+ static #popcount(value: number): number {
126
+ let v = value >>> 0;
127
+ v -= (v >>> 1) & 0x55555555;
128
+ v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
129
+ return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;
130
+ }
131
+ }
@@ -0,0 +1,207 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { DictionaryPacking } from "./dictionaryPacking";
3
+
4
+ const seeded = (seed: number) => () => {
5
+ seed = (seed * 1103515245 + 12345) % 2147483648;
6
+ return seed / 2147483648;
7
+ };
8
+
9
+ const manyModules = () => {
10
+ const random = seeded(7);
11
+ const groups = Array.from({ length: 80 }, (_, idx) => `module${idx}`);
12
+ const routes = new Map<string, string[]>();
13
+ for (let idx = 0; idx < 300; idx++) {
14
+ const shown = groups.filter(() => random() < 0.12);
15
+ routes.set(`/:lang/route${idx}`, ["base", ...shown]);
16
+ }
17
+ routes.set("/:lang/everything", ["base", ...groups]);
18
+ const sizes = new Map(["base", ...groups].map((group) => [group, 200 + Math.floor(random() * 6000)]));
19
+ return { groups: ["base", ...groups, "unshown"], routes, bytesOf: (group: string) => sizes.get(group) ?? 100 };
20
+ };
21
+
22
+ type Pack = ReturnType<typeof DictionaryPacking.pack>;
23
+
24
+ const filesOf = (routeId: string, { partsByRoute }: Pack) => partsByRoute[routeId] ?? [];
25
+
26
+ const heldOf = (routeId: string, pack: Pack) => {
27
+ const files = [...pack.parts, ...pack.ownParts];
28
+ return filesOf(routeId, pack).flatMap((idx) => files[idx] ?? []);
29
+ };
30
+
31
+ const overfetchOf = (routeId: string, pack: Pack, shown: readonly string[], bytesOf: (group: string) => number) =>
32
+ heldOf(routeId, pack).reduce((sum, group) => sum + bytesOf(group), 0) -
33
+ [...new Set(shown)].reduce((sum, group) => sum + bytesOf(group), 0);
34
+
35
+ describe("DictionaryPacking", () => {
36
+ test("loads every route's groups in at most four files, over a workspace of many modules", () => {
37
+ const { groups, routes, bytesOf } = manyModules();
38
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
39
+
40
+ for (const [routeId, shown] of routes) {
41
+ const files = filesOf(routeId, pack);
42
+ expect(files.length).toBeLessThanOrEqual(DictionaryPacking.bound);
43
+ const held = new Set(heldOf(routeId, pack));
44
+ for (const group of shown) expect(held.has(group)).toBe(true);
45
+ }
46
+ });
47
+
48
+ test("no route downloads more than the over-fetch budget of texts it does not show", () => {
49
+ const { groups, routes, bytesOf } = manyModules();
50
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
51
+
52
+ for (const [routeId, shown] of routes)
53
+ expect(overfetchOf(routeId, pack, shown, bytesOf)).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
54
+ expect(pack.ownParts.length).toBeGreaterThan(0);
55
+ });
56
+
57
+ test("removing an unrelated route moves no other route's download by more than the over-fetch budget", () => {
58
+ const { groups, routes, bytesOf } = manyModules();
59
+ const before = DictionaryPacking.pack(routes, bytesOf, groups);
60
+ const downloadOf = (routeId: string, pack: Pack) =>
61
+ heldOf(routeId, pack).reduce((sum, group) => sum + bytesOf(group), 0);
62
+ for (const removed of ["/:lang/route3", "/:lang/route150", "/:lang/everything"]) {
63
+ const after = DictionaryPacking.pack(
64
+ new Map([...routes].filter(([routeId]) => routeId !== removed)),
65
+ bytesOf,
66
+ groups,
67
+ );
68
+ for (const routeId of routes.keys()) {
69
+ if (routeId === removed) continue;
70
+ const moved = Math.abs(downloadOf(routeId, after) - downloadOf(routeId, before));
71
+ expect(moved).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
72
+ }
73
+ }
74
+ });
75
+
76
+ test("a route past the bound takes the rest of its groups in one file, which a near-identical route shares", () => {
77
+ const modules = Array.from({ length: 6 }, (_, idx) => `module${idx}`);
78
+ const routes = new Map([
79
+ ["/:lang/list", ["base", ...modules]],
80
+ ["/:lang/detail", ["base", ...modules, "extra"]],
81
+ ...modules.map((module) => [`/:lang/${module}`, [module]] as [string, string[]]),
82
+ ]);
83
+ const bytesOf = () => 5000;
84
+ const groups = ["base", "extra", ...modules];
85
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
86
+ const list = filesOf("/:lang/list", pack);
87
+ const detail = filesOf("/:lang/detail", pack);
88
+
89
+ expect(pack.ownParts.length).toBe(1);
90
+ expect(list.at(-1)).toBe(pack.parts.length);
91
+ expect(detail.at(-1)).toBe(pack.parts.length);
92
+ for (const [routeId, shown] of routes) {
93
+ expect(filesOf(routeId, pack).length).toBeLessThanOrEqual(DictionaryPacking.bound);
94
+ expect(new Set(heldOf(routeId, pack))).toEqual(new Set(shown));
95
+ expect(overfetchOf(routeId, pack, shown, bytesOf)).toBeLessThanOrEqual(DictionaryPacking.overfetchBytes);
96
+ }
97
+ for (const module of modules) expect(heldOf(`/:lang/${module}`, pack)).toEqual([module]);
98
+ });
99
+
100
+ test("puts each group in one file, and a group no route shows in the last, which no route loads", () => {
101
+ const { groups, routes, bytesOf } = manyModules();
102
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
103
+
104
+ expect(pack.parts.flat().sort()).toEqual([...groups].sort());
105
+ expect(pack.parts.at(-1)).toEqual(["unshown"]);
106
+ const last = pack.parts.length - 1;
107
+ for (const files of Object.values(pack.partsByRoute)) expect(files).not.toContain(last);
108
+ });
109
+
110
+ test("keeps apart groups that routes take apart when merging them would cost more than a request", () => {
111
+ const routes = new Map([
112
+ ["/:lang/a", ["base", "big"]],
113
+ ["/:lang/b", ["base", "other"]],
114
+ ]);
115
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 8000);
116
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "big", "other"]);
117
+
118
+ expect(pack.parts).toEqual([["base"], ["big"], ["other"]]);
119
+ expect(pack.partsByRoute).toEqual({ "/:lang/a": [0, 1], "/:lang/b": [0, 2] });
120
+ });
121
+
122
+ test("merges small files every route takes together, as a request costs more than their bytes", () => {
123
+ const routes = new Map([
124
+ ["/:lang/a", ["base", "tiny"]],
125
+ ["/:lang/b", ["base", "tiny", "small"]],
126
+ ]);
127
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 40);
128
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "small", "tiny"]);
129
+
130
+ expect(pack.parts).toEqual([["base", "small", "tiny"]]);
131
+ expect(pack.partsByRoute).toEqual({ "/:lang/a": [0], "/:lang/b": [0] });
132
+ });
133
+
134
+ describe("held under the whole dictionary", () => {
135
+ const fileOverhead = 300;
136
+ const servedOf = (bytesOf: (group: string) => number) => (held: readonly string[]) =>
137
+ fileOverhead + held.reduce((sum, group) => sum + bytesOf(group), 0);
138
+
139
+ test("a route whose files would not be smaller than the whole loads the whole file, the others their own texts", () => {
140
+ const modules = Array.from({ length: 8 }, (_, idx) => `module${idx}`);
141
+ const groups = ["base", ...modules];
142
+ const light = new Map(modules.map((module) => [`/:lang/${module}`, ["base", module]]));
143
+ const routes = new Map([...light, ["/:lang/everything", groups]]);
144
+ const bytesOf = (group: string) => (group === "base" ? 2000 : 5000);
145
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedOf(bytesOf));
146
+ const alone = DictionaryPacking.pack(routes, bytesOf, groups);
147
+
148
+ expect(pack.wholeRoutes).toEqual(["/:lang/everything"]);
149
+ expect(pack.partsByRoute["/:lang/everything"]).toBeUndefined();
150
+ expect({ parts: pack.parts, ownParts: pack.ownParts, partsByRoute: pack.partsByRoute }).toEqual(
151
+ DictionaryPacking.pack(light, bytesOf, groups),
152
+ );
153
+ for (const module of modules) {
154
+ expect(heldOf(`/:lang/${module}`, pack).sort()).toEqual(["base", module]);
155
+ expect(heldOf(`/:lang/${module}`, alone).sort()).toEqual(["base", module]);
156
+ }
157
+ });
158
+
159
+ test("no route left on files loads the whole or more, and all routes together load no more than before", () => {
160
+ const { groups, routes, bytesOf } = manyModules();
161
+ const served = servedOf(bytesOf);
162
+ const whole = served(groups);
163
+ const costOf = ({ parts, ownParts, partsByRoute }: Pack) =>
164
+ [...routes.keys()].reduce((sum, routeId) => {
165
+ const files = partsByRoute[routeId];
166
+ const all = [...parts, ...ownParts];
167
+ const own = files?.reduce((bytes, idx) => bytes + served(all[idx] ?? []), 0) ?? whole;
168
+ return sum + Math.min(own, whole);
169
+ }, 0);
170
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, served);
171
+
172
+ expect(pack.wholeRoutes).toContain("/:lang/everything");
173
+ expect(Object.keys(pack.partsByRoute).length).toBe(routes.size - pack.wholeRoutes.length);
174
+ const files = [...pack.parts, ...pack.ownParts];
175
+ for (const held of Object.values(pack.partsByRoute))
176
+ expect(held.reduce((sum, idx) => sum + served(files[idx] ?? []), 0)).toBeLessThan(whole);
177
+ for (const idx of pack.ownParts.keys())
178
+ expect(Object.values(pack.partsByRoute).some((held) => held.includes(pack.parts.length + idx))).toBe(true);
179
+ expect(costOf(pack)).toBeLessThanOrEqual(costOf(DictionaryPacking.pack(routes, bytesOf, groups)));
180
+ });
181
+
182
+ test("every route loads the whole file where each shows every group", () => {
183
+ const routes = new Map([
184
+ ["/:lang/a", ["base", "memo", "user"]],
185
+ ["/:lang/b", ["base", "user", "memo"]],
186
+ ]);
187
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 300);
188
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, ["base", "memo", "user"], servedOf(bytesOf));
189
+
190
+ expect(pack.wholeRoutes).toEqual(["/:lang/a", "/:lang/b"]);
191
+ expect(pack.partsByRoute).toEqual({});
192
+ });
193
+ });
194
+
195
+ test("a second route reuses the files the first one loaded where they share groups", () => {
196
+ const routes = new Map([
197
+ ["/:lang/memo", ["base", "memo", "user"]],
198
+ ["/:lang/memo/:memoId", ["base", "memo", "user", "comment"]],
199
+ ]);
200
+ const bytesOf = () => 5000;
201
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "comment", "memo", "user"]);
202
+ const first = filesOf("/:lang/memo", pack);
203
+ const second = filesOf("/:lang/memo/:memoId", pack);
204
+
205
+ expect(second.filter((idx) => !first.includes(idx)).flatMap((idx) => pack.parts[idx] ?? [])).toEqual(["comment"]);
206
+ });
207
+ });