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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/CHANGELOG.md +618 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +133 -6
  22. package/app/dictionarySizes.ts +91 -0
  23. package/app/routeFilesReport.test.ts +59 -0
  24. package/app/routeFilesReport.ts +46 -0
  25. package/app/routeJsBudget.ts +18 -4
  26. package/artifact/implicitRootLayout.test.ts +19 -0
  27. package/artifact/implicitRootLayout.ts +16 -2
  28. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  29. package/artifact/storeBootstrap.test.ts +28 -0
  30. package/artifact/storeBootstrap.ts +64 -8
  31. package/biome.base.json +6 -4
  32. package/codeAgent/agent/CodeAgent.ts +36 -16
  33. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  34. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  35. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  36. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  37. package/codeAgent/agent/codeAgent.test.ts +62 -0
  38. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  39. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  40. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  41. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  42. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  43. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  44. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  46. package/codeAgent/skills/akan-page/SKILL.md +31 -20
  47. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  48. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  49. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  50. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  51. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  52. package/context/akanContext.ts +2 -0
  53. package/docs/apiReference.test.ts +9 -0
  54. package/docs/apiReference.ts +14 -0
  55. package/executors/appExecutor.ts +3 -1
  56. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  57. package/executors/clientRuntimeKeys.fixture.json +393 -0
  58. package/executors/clientRuntimeKeys.test.ts +1690 -0
  59. package/executors/executors.test.ts +2 -0
  60. package/executors/sysExecutor.ts +70 -4
  61. package/executors/workspaceExecutor.ts +7 -4
  62. package/frontendBuild/allRoutesBuilder.ts +88 -7
  63. package/frontendBuild/autoImportSync.ts +3 -2
  64. package/frontendBuild/buildRouteClient.test.ts +580 -12
  65. package/frontendBuild/clientBuildTypes.ts +26 -0
  66. package/frontendBuild/clientEntriesBundler.ts +49 -1
  67. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  68. package/frontendBuild/clientEntryDiscovery.ts +135 -13
  69. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  70. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  71. package/frontendBuild/csrDevPatcher.ts +33 -7
  72. package/frontendBuild/csrDevTypes.ts +9 -0
  73. package/frontendBuild/devBarrelImports.test.ts +154 -0
  74. package/frontendBuild/devBarrelImports.ts +83 -23
  75. package/frontendBuild/devRegistryBundler.ts +4 -2
  76. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  77. package/frontendBuild/devRouteRuntime.ts +167 -0
  78. package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
  79. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  80. package/frontendBuild/dictionaryConstants.ts +136 -0
  81. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  82. package/frontendBuild/dictionaryPacking.ts +135 -0
  83. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  84. package/frontendBuild/dictionaryRoutes.ts +227 -0
  85. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  86. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  87. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  88. package/frontendBuild/precompressArtifacts.ts +22 -8
  89. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  90. package/frontendBuild/renderedEntries.ts +144 -0
  91. package/frontendBuild/routeClientBuilder.ts +340 -29
  92. package/frontendBuild/routeHandoffs.test.ts +155 -0
  93. package/frontendBuild/routeHandoffs.ts +117 -0
  94. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  95. package/frontendBuild/routeModulePreloads.ts +20 -11
  96. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  97. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  98. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  99. package/frontendBuild/routeRuntimePays.ts +117 -0
  100. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  101. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  102. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  103. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  104. package/frontendBuild/ssrDevBundler.ts +66 -11
  105. package/frontendBuild/vendorFileImports.test.ts +254 -0
  106. package/frontendBuild/vendorFileImports.ts +163 -0
  107. package/frontendBuild/vendorNarrowing.ts +28 -0
  108. package/frontendBuild/vendorSpecifiers.ts +2 -0
  109. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  110. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  111. package/incrementalBuilder/builderBoot.ts +5 -5
  112. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  113. package/incrementalBuilder/builderLanes.ts +2 -2
  114. package/incrementalBuilder/builderWatch.ts +8 -8
  115. package/incrementalBuilder/csrRegistry.ts +4 -4
  116. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  117. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  118. package/incrementalBuilder/ssrRegistry.ts +6 -6
  119. package/index.ts +1 -1
  120. package/integration/renderAdmissionSoak.test.ts +99 -0
  121. package/integration/renderAdmissionSoak.ts +609 -0
  122. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  123. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  124. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  125. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  126. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  127. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  128. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  129. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  130. package/lint/biomeBase.test.ts +23 -3
  131. package/lint/biomeCheck.test.ts +145 -0
  132. package/lint/biomeCheck.ts +131 -0
  133. package/lint/no-arbitrary-color.grit +5 -0
  134. package/lint/no-conditional-st-hook.grit +5 -1
  135. package/lint/no-daisyui-legacy-class.grit +8 -0
  136. package/lint/no-document-cookie.grit +3 -0
  137. package/lint/no-inline-color.grit +10 -2
  138. package/lint/no-oversized-list-limit.grit +2 -0
  139. package/lint/no-raw-palette-class.grit +7 -0
  140. package/lint/no-unpublished-form-setter.grit +2 -0
  141. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  142. package/lint/no-web-storage.grit +3 -0
  143. package/lint/withheldEnvFile.ts +17 -0
  144. package/mobile/desktopBin.ts +2 -2
  145. package/mobile/desktopServerStage.ts +1 -0
  146. package/mobile/nativeApp.test.ts +7 -5
  147. package/mobile/nativeApp.ts +2 -2
  148. package/mobile/nativeConfig.test.ts +96 -1
  149. package/mobile/nativeConfig.ts +46 -12
  150. package/mobile/serverBundleSecrets.ts +43 -0
  151. package/package.json +15 -169
  152. package/packageExports.test.ts +38 -24
  153. package/quality/dictionaryKeys.test.ts +356 -0
  154. package/quality/dictionaryKeys.ts +488 -0
  155. package/quality/objectImportReport.test.ts +36 -0
  156. package/quality/objectImportReport.ts +105 -0
  157. package/quality/qualityScanner.ts +1 -1
  158. package/quality/routeRuntimeReport.test.ts +91 -0
  159. package/quality/routeRuntimeReport.ts +121 -0
  160. package/quality/runtimeConstantFacts.ts +71 -0
  161. package/quality/runtimeConstantGraph.ts +123 -0
  162. package/quality/runtimeConstantReads.ts +116 -0
  163. package/quality/runtimeImports.test.ts +190 -0
  164. package/quality/runtimeImports.ts +233 -0
  165. package/quality/runtimeKeyNames.ts +46 -0
  166. package/quality/runtimeLexicalScope.ts +132 -0
  167. package/quality/runtimeMarkerReach.test.ts +84 -0
  168. package/quality/runtimeMarkerReach.ts +255 -0
  169. package/quality/runtimeModuleFacts.ts +290 -0
  170. package/quality/runtimeNameTable.test.ts +172 -0
  171. package/quality/runtimeNameTable.ts +477 -0
  172. package/quality/runtimeScopeReport.test.ts +123 -0
  173. package/quality/runtimeScopeReport.ts +167 -0
  174. package/quality/runtimeSliceKey.ts +269 -0
  175. package/quality/runtimeSyntax.ts +133 -0
  176. package/quality/runtimeTable.fixture.ts +189 -0
  177. package/quality/runtimeUse.test.ts +737 -0
  178. package/quality/runtimeUse.ts +696 -0
  179. package/quality/runtimeUseReadable.test.ts +393 -0
  180. package/quality/ssrScanner.test.ts +13 -0
  181. package/quality/ssrScanner.ts +1 -1
  182. package/quality/translatorBindings.ts +187 -0
  183. package/test/secretEnvFixture.ts +134 -0
  184. package/test/testHelpers.ts +11 -0
  185. package/transforms/barrelAnalyzer.ts +26 -4
  186. package/transforms/barrelImportsPlugin.ts +121 -32
  187. package/transforms/exportReach.test.ts +162 -0
  188. package/transforms/exportReach.ts +308 -0
  189. package/transforms/frameworkObjects.fixture.tsx +58 -0
  190. package/transforms/frameworkObjects.test.ts +54 -0
  191. package/transforms/modelReference.test.ts +196 -0
  192. package/transforms/modelReference.ts +39 -0
  193. package/transforms/moduleParts.test.ts +225 -0
  194. package/transforms/moduleParts.ts +418 -0
  195. package/transforms/objectImportEdits.ts +150 -0
  196. package/transforms/objectMemberImports.test.ts +629 -0
  197. package/transforms/objectMemberImports.ts +571 -0
  198. package/transforms/objectMemberLookup.ts +150 -0
  199. package/transforms/objectModule.test.ts +307 -0
  200. package/transforms/objectModule.ts +482 -0
  201. package/transforms/objectModuleAnalyzer.ts +104 -0
  202. package/transforms/partImports.test.ts +76 -0
  203. package/transforms/partImports.ts +110 -0
  204. package/transforms/partModules.test.ts +187 -0
  205. package/transforms/partModules.ts +90 -0
  206. package/transforms/partPurity.ts +124 -0
  207. package/transforms/reactIconImports.test.ts +231 -0
  208. package/transforms/reactIconImports.ts +325 -0
  209. package/transforms/routeConstants.ts +122 -0
  210. package/transforms/routeRuntime.test.ts +835 -0
  211. package/transforms/routeRuntime.ts +703 -0
  212. package/transforms/routeRuntimeEdits.ts +92 -0
  213. package/transforms/routeRuntimeGraph.ts +66 -0
  214. package/transforms/routeRuntimePlan.ts +244 -0
  215. package/transforms/secretEnvDeclaration.test.ts +208 -0
  216. package/transforms/secretEnvDeclaration.ts +213 -0
  217. package/transforms/secretEnvFile.test.ts +117 -0
  218. package/transforms/secretEnvFile.ts +113 -0
  219. package/transforms/secretEnvName.test.ts +54 -0
  220. package/transforms/secretEnvName.ts +29 -0
  221. package/transforms/secretEnvSource.test.ts +148 -0
  222. package/transforms/secretEnvSource.ts +166 -0
  223. package/transforms/serverEnvEvaluationError.ts +11 -0
  224. package/transforms/serverEnvPlugin.test.ts +2 -1
  225. package/transforms/serverEnvPlugin.ts +13 -0
  226. package/transforms/serverEnvProfile.test.ts +115 -2
  227. package/transforms/serverEnvProfile.ts +117 -40
  228. package/transforms/serverEnvSecrets.test.ts +292 -0
  229. package/transforms/signalDescriptors.test.ts +280 -0
  230. package/transforms/signalDescriptors.ts +227 -0
  231. package/transforms/thisFreeExports.ts +87 -0
  232. package/transforms/transforms.test.ts +180 -3
  233. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  234. package/tunnel/createTunnel.test.ts +29 -8
  235. package/tunnel/createTunnel.ts +18 -11
  236. package/typecheck/projectTypecheck.test.ts +29 -0
  237. package/typecheck/typeChecker.test.ts +49 -0
  238. package/typecheck/typeChecker.ts +9 -7
  239. package/typecheck/withheldDiagnostics.ts +41 -0
  240. package/util/fileEditor.ts +1 -0
  241. package/util/selectModel.ts +1 -0
  242. package/workflow/executor.ts +6 -2
  243. package/workflow/index.ts +1 -0
  244. package/workflow/plan.ts +36 -7
  245. package/workflow/types.ts +1 -1
  246. package/workflow/uiTarget.ts +50 -0
  247. package/workspace/getRelatedCnsts.ts +7 -0
  248. package/workspace/scanInfo.test.ts +39 -0
  249. package/workspace/scanInfo.ts +48 -5
  250. package/workspace/workspaceLayout.ts +1 -0
@@ -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,142 @@
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
+ const filesOf = (routeId: string, { partsByRoute }: ReturnType<typeof DictionaryPacking.pack>) =>
23
+ partsByRoute[routeId] ?? [];
24
+
25
+ describe("DictionaryPacking", () => {
26
+ test("loads every route's groups in at most four files, over a workspace of many modules", () => {
27
+ const { groups, routes, bytesOf } = manyModules();
28
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
29
+
30
+ for (const [routeId, shown] of routes) {
31
+ const files = filesOf(routeId, pack);
32
+ expect(files.length).toBeLessThanOrEqual(DictionaryPacking.bound);
33
+ const held = new Set(files.flatMap((idx) => pack.parts[idx] ?? []));
34
+ for (const group of shown) expect(held.has(group)).toBe(true);
35
+ }
36
+ });
37
+
38
+ test("puts each group in one file, and a group no route shows in the last, which no route loads", () => {
39
+ const { groups, routes, bytesOf } = manyModules();
40
+ const pack = DictionaryPacking.pack(routes, bytesOf, groups);
41
+
42
+ expect(pack.parts.flat().sort()).toEqual([...groups].sort());
43
+ expect(pack.parts.at(-1)).toEqual(["unshown"]);
44
+ const last = pack.parts.length - 1;
45
+ for (const files of Object.values(pack.partsByRoute)) expect(files).not.toContain(last);
46
+ });
47
+
48
+ test("keeps apart groups that routes take apart when merging them would cost more than a request", () => {
49
+ const routes = new Map([
50
+ ["/:lang/a", ["base", "big"]],
51
+ ["/:lang/b", ["base", "other"]],
52
+ ]);
53
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 8000);
54
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "big", "other"]);
55
+
56
+ expect(pack.parts).toEqual([["base"], ["big"], ["other"]]);
57
+ expect(pack.partsByRoute).toEqual({ "/:lang/a": [0, 1], "/:lang/b": [0, 2] });
58
+ });
59
+
60
+ test("merges small files every route takes together, as a request costs more than their bytes", () => {
61
+ const routes = new Map([
62
+ ["/:lang/a", ["base", "tiny"]],
63
+ ["/:lang/b", ["base", "tiny", "small"]],
64
+ ]);
65
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 40);
66
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "small", "tiny"]);
67
+
68
+ expect(pack.parts).toEqual([["base", "small", "tiny"]]);
69
+ expect(pack.partsByRoute).toEqual({ "/:lang/a": [0], "/:lang/b": [0] });
70
+ });
71
+
72
+ describe("held under the whole dictionary", () => {
73
+ const fileOverhead = 300;
74
+ const servedOf = (bytesOf: (group: string) => number) => (held: readonly string[]) =>
75
+ fileOverhead + held.reduce((sum, group) => sum + bytesOf(group), 0);
76
+
77
+ test("a route whose files would not be smaller than the whole loads the whole file and no longer shapes the cut", () => {
78
+ const modules = Array.from({ length: 8 }, (_, idx) => `module${idx}`);
79
+ const groups = ["base", ...modules];
80
+ const light = new Map(modules.map((module) => [`/:lang/${module}`, ["base", module]]));
81
+ const routes = new Map([...light, ["/:lang/everything", groups]]);
82
+ const bytesOf = (group: string) => (group === "base" ? 2000 : 5000);
83
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedOf(bytesOf));
84
+ const alone = DictionaryPacking.pack(routes, bytesOf, groups);
85
+
86
+ expect(pack.wholeRoutes).toEqual(["/:lang/everything"]);
87
+ expect(pack.partsByRoute["/:lang/everything"]).toBeUndefined();
88
+ expect({ parts: pack.parts, partsByRoute: pack.partsByRoute }).toEqual(
89
+ DictionaryPacking.pack(light, bytesOf, groups),
90
+ );
91
+ for (const module of modules) {
92
+ const held = (files: number[] = [], parts: string[][]) => files.flatMap((idx) => parts[idx] ?? []).sort();
93
+ expect(held(pack.partsByRoute[`/:lang/${module}`], pack.parts)).toEqual(["base", module]);
94
+ expect(held(alone.partsByRoute[`/:lang/${module}`], alone.parts).length).toBeGreaterThan(2);
95
+ }
96
+ });
97
+
98
+ test("no route left on files loads the whole or more, and all routes together load no more than before", () => {
99
+ const { groups, routes, bytesOf } = manyModules();
100
+ const served = servedOf(bytesOf);
101
+ const whole = served(groups);
102
+ const costOf = ({ parts, partsByRoute }: ReturnType<typeof DictionaryPacking.pack>) =>
103
+ [...routes.keys()].reduce((sum, routeId) => {
104
+ const files = partsByRoute[routeId];
105
+ const own = files?.reduce((bytes, idx) => bytes + served(parts[idx] ?? []), 0) ?? whole;
106
+ return sum + Math.min(own, whole);
107
+ }, 0);
108
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, served);
109
+
110
+ expect(pack.wholeRoutes).toContain("/:lang/everything");
111
+ expect(Object.keys(pack.partsByRoute).length).toBe(routes.size - pack.wholeRoutes.length);
112
+ for (const files of Object.values(pack.partsByRoute))
113
+ expect(files.reduce((sum, idx) => sum + served(pack.parts[idx] ?? []), 0)).toBeLessThan(whole);
114
+ expect(costOf(pack)).toBeLessThanOrEqual(costOf(DictionaryPacking.pack(routes, bytesOf, groups)));
115
+ });
116
+
117
+ test("every route loads the whole file where each shows every group", () => {
118
+ const routes = new Map([
119
+ ["/:lang/a", ["base", "memo", "user"]],
120
+ ["/:lang/b", ["base", "user", "memo"]],
121
+ ]);
122
+ const bytesOf = (group: string) => (group === "base" ? 9000 : 300);
123
+ const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, ["base", "memo", "user"], servedOf(bytesOf));
124
+
125
+ expect(pack.wholeRoutes).toEqual(["/:lang/a", "/:lang/b"]);
126
+ expect(pack.partsByRoute).toEqual({});
127
+ });
128
+ });
129
+
130
+ test("a second route reuses the files the first one loaded where they share groups", () => {
131
+ const routes = new Map([
132
+ ["/:lang/memo", ["base", "memo", "user"]],
133
+ ["/:lang/memo/:memoId", ["base", "memo", "user", "comment"]],
134
+ ]);
135
+ const bytesOf = () => 5000;
136
+ const pack = DictionaryPacking.pack(routes, bytesOf, ["base", "comment", "memo", "user"]);
137
+ const first = filesOf("/:lang/memo", pack);
138
+ const second = filesOf("/:lang/memo/:memoId", pack);
139
+
140
+ expect(second.filter((idx) => !first.includes(idx)).flatMap((idx) => pack.parts[idx] ?? [])).toEqual(["comment"]);
141
+ });
142
+ });
@@ -0,0 +1,135 @@
1
+ export interface DictionaryPack {
2
+ //? Each file's groups. A group no route names sits in the last file, which only a translation miss asks for.
3
+ parts: string[][];
4
+ partsByRoute: Record<string, number[]>;
5
+ }
6
+
7
+ //* Packs a page dictionary's groups into files so that a route loads at most `bound` of them. It starts from the
8
+ //* groups every route takes or leaves together (no route downloads a text it does not show), merges two files while
9
+ //* the requests it saves routes needing both outweigh the bytes it adds to routes needing one, then, inside the route
10
+ //* needing the most files, merges the two whose merge adds the fewest bytes until every route is within the bound.
11
+ export class DictionaryPacking {
12
+ static readonly bound = 4;
13
+ //? What one more request costs a route in bytes of text: headers, a round trip's share, and the brotli window a
14
+ //? small file compresses without.
15
+ static readonly requestBytes = 1024;
16
+
17
+ static pack(
18
+ routes: ReadonlyMap<string, readonly string[]>,
19
+ bytesOf: (group: string) => number,
20
+ groups: readonly string[],
21
+ { bound = DictionaryPacking.bound, requestBytes = DictionaryPacking.requestBytes } = {},
22
+ ): DictionaryPack {
23
+ const known = new Set(groups);
24
+ const routeIds = [...routes.keys()].sort();
25
+ const needs = routeIds.map((routeId) => [...new Set(routes.get(routeId))].filter((group) => known.has(group)));
26
+ const bySignature = new Map<string, string[]>();
27
+ for (const group of [...known].sort()) {
28
+ const signature = needs.flatMap((need, idx) => (need.includes(group) ? [idx] : [])).join(",");
29
+ if (signature) bySignature.set(signature, [...(bySignature.get(signature) ?? []), group]);
30
+ }
31
+ const parts = [...bySignature.values()];
32
+ while (DictionaryPacking.#mergeCheapest(parts, needs, bytesOf, requestBytes, null));
33
+ for (let worst = DictionaryPacking.#widest(parts, needs, bound); worst; ) {
34
+ if (!DictionaryPacking.#mergeCheapest(parts, needs, bytesOf, 0, worst)) break;
35
+ worst = DictionaryPacking.#widest(parts, needs, bound);
36
+ }
37
+ parts.sort((a, b) => ((a[0] ?? "") < (b[0] ?? "") ? -1 : 1));
38
+ const used = new Set(parts.flat());
39
+ const rest = [...known].filter((group) => !used.has(group)).sort((a, b) => (a < b ? -1 : 1));
40
+ if (rest.length) parts.push(rest);
41
+ const partOf = new Map(parts.flatMap((part, idx) => part.map((group) => [group, idx] as const)));
42
+ const partsByRoute = Object.fromEntries(
43
+ routeIds.map((routeId, idx) => [
44
+ routeId,
45
+ [...new Set((needs[idx] ?? []).map((group) => partOf.get(group) as number))].sort((a, b) => a - b),
46
+ ]),
47
+ );
48
+ return { parts, partsByRoute };
49
+ }
50
+
51
+ //? Several files compress worse than one, so a route showing nearly every text is cheaper on the whole dictionary.
52
+ static packUnderWhole(
53
+ routes: ReadonlyMap<string, readonly string[]>,
54
+ bytesOf: (group: string) => number,
55
+ groups: readonly string[],
56
+ servedBytesOf: (groups: readonly string[]) => number,
57
+ options: { bound?: number; requestBytes?: number } = {},
58
+ ): DictionaryPack & { wholeRoutes: string[] } {
59
+ const whole = servedBytesOf([...new Set(groups)].sort());
60
+ const served = new Map<string, number>();
61
+ const servedOf = (part: readonly string[]) => {
62
+ const key = part.join("\n");
63
+ const known = served.get(key) ?? servedBytesOf(part);
64
+ served.set(key, known);
65
+ return known;
66
+ };
67
+ const shownBytesOf = (routeId: string) =>
68
+ [...new Set(routes.get(routeId))].reduce((sum, group) => sum + bytesOf(group), 0);
69
+ const partial = new Map(routes);
70
+ let best: { pack: DictionaryPack; over: string[]; cost: number } | null = null;
71
+ for (;;) {
72
+ const pack = DictionaryPacking.pack(partial, bytesOf, groups, options);
73
+ const costs = Object.entries(pack.partsByRoute).map(([routeId, files]) => ({
74
+ routeId,
75
+ cost: files.reduce((sum, idx) => sum + servedOf(pack.parts[idx] ?? []), 0),
76
+ }));
77
+ const over = costs.filter(({ cost }) => cost >= whole).map(({ routeId }) => routeId);
78
+ const cost =
79
+ costs.reduce((sum, route) => sum + Math.min(route.cost, whole), 0) + (routes.size - partial.size) * whole;
80
+ if (!best || cost < best.cost) best = { pack, over, cost };
81
+ if (!over.length) break;
82
+ //? Half at a time, the routes showing the most first: without them the rest may come out smaller after all.
83
+ over.sort((a, b) => shownBytesOf(b) - shownBytesOf(a) || (a < b ? -1 : 1));
84
+ for (const routeId of over.slice(0, Math.ceil(over.length / 2))) partial.delete(routeId);
85
+ }
86
+ const dropped = new Set(best.over);
87
+ const partsByRoute = Object.fromEntries(
88
+ Object.entries(best.pack.partsByRoute).filter(([routeId]) => !dropped.has(routeId)),
89
+ );
90
+ const wholeRoutes = [...routes.keys()].sort().filter((routeId) => !Object.hasOwn(partsByRoute, routeId));
91
+ return { parts: best.pack.parts, partsByRoute, wholeRoutes };
92
+ }
93
+
94
+ static #setsOf(parts: string[][], needs: string[][]) {
95
+ const partOf = new Map(parts.flatMap((part, idx) => part.map((group) => [group, idx] as const)));
96
+ return needs.map((need) => new Set(need.map((group) => partOf.get(group) as number)));
97
+ }
98
+
99
+ static #widest(parts: string[][], needs: string[][], bound: number): Set<number> | null {
100
+ let worst: Set<number> | null = null;
101
+ for (const set of DictionaryPacking.#setsOf(parts, needs))
102
+ if (set.size > Math.max(1, bound) && (!worst || set.size > worst.size)) worst = set;
103
+ return worst;
104
+ }
105
+
106
+ //? `within` set: any pair of its files merges, the cheapest first; otherwise only a pair whose merge pays for itself.
107
+ static #mergeCheapest(
108
+ parts: string[][],
109
+ needs: string[][],
110
+ bytesOf: (group: string) => number,
111
+ requestBytes: number,
112
+ within: Set<number> | null,
113
+ ): boolean {
114
+ const sets = DictionaryPacking.#setsOf(parts, needs);
115
+ const bytes = parts.map((part) => part.reduce((sum, group) => sum + bytesOf(group), 0));
116
+ const candidates = within ? [...within].sort((a, b) => a - b) : parts.map((_, idx) => idx);
117
+ let best: { p: number; q: number; cost: number } | null = null;
118
+ for (let x = 0; x < candidates.length; x++)
119
+ for (let y = x + 1; y < candidates.length; y++) {
120
+ const [p, q] = [candidates[x] as number, candidates[y] as number];
121
+ let cost = 0;
122
+ for (const set of sets) {
123
+ const [hasP, hasQ] = [set.has(p), set.has(q)];
124
+ if (hasP && hasQ) cost -= requestBytes;
125
+ else if (hasP) cost += bytes[q] ?? 0;
126
+ else if (hasQ) cost += bytes[p] ?? 0;
127
+ }
128
+ if (!best || cost < best.cost) best = { p, q, cost };
129
+ }
130
+ if (!best || (!within && best.cost >= 0)) return false;
131
+ parts[best.p] = [...(parts[best.p] ?? []), ...(parts[best.q] ?? [])].sort();
132
+ parts.splice(best.q, 1);
133
+ return true;
134
+ }
135
+ }
@@ -0,0 +1,251 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { runtimeFixtureTables } from "../quality/runtimeTable.fixture";
4
+ import { tempDirs, writeText } from "../test/testHelpers";
5
+ import { RouteRuntime } from "../transforms/routeRuntime";
6
+ import type { ClientModuleImport } from "./clientBuildTypes";
7
+ import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
8
+ import { DictionaryConstants } from "./dictionaryConstants";
9
+ import { type DictionaryPiecesOf, DictionaryRoutes } from "./dictionaryRoutes";
10
+ import { RouteHandoffs } from "./routeHandoffs";
11
+
12
+ const makeRoot = tempDirs("akan-devkit-dict-routes-");
13
+
14
+ const constantsOf = () => {
15
+ const constants = new DictionaryConstants();
16
+ constants.add(
17
+ "apps/demo/lib/memo/memo.constant.ts",
18
+ `export class MemoStatus extends enumOf("memoStatus", ["draft", "done"] as const) {}
19
+ export class MemoInput extends via((field) => ({ status: field(MemoStatus), place: field(Address), author: field(User) })) {}
20
+ export class Memo extends via(MemoInput, (field) => ({})) {}
21
+ `,
22
+ );
23
+ constants.add(
24
+ "apps/demo/lib/user/user.constant.ts",
25
+ `export class UserRole extends enumOf("userRole", ["admin", "member"] as const) {}
26
+ export class UserInput extends via((field) => ({ role: field(UserRole), team: field(Team) })) {}
27
+ export class User extends via(UserInput, (field) => ({})) {}
28
+ `,
29
+ );
30
+ constants.add(
31
+ "apps/demo/lib/team/team.constant.ts",
32
+ `export class Team extends via((field) => ({ name: field(String) })) {}`,
33
+ );
34
+ constants.add(
35
+ "apps/demo/lib/__scalar/address/address.constant.ts",
36
+ `export class Address extends via((field) => ({ city: field(String) })) {}`,
37
+ );
38
+ constants.add(
39
+ "apps/demo/lib/runnerBot/runnerBot.constant.ts",
40
+ `export class RunnerBot extends via((field) => ({ name: field(String) })) {
41
+ static readonly labelKeyOf = { reviewer: "runnerBot.reviewer", fixer: "task.fixer" } as const;
42
+ static stageKeys = ["project.stage.open", "project.stage.done"] as const satisfies readonly string[];
43
+ static loose = { reviewer: "runnerBot.reviewer" };
44
+ static typed: Record<string, string> = { reviewer: "runnerBot.reviewer" } as const;
45
+ static called = { reviewer: "runnerBot.reviewer", fixer: keyOf("fixer") } as const;
46
+ static computed = { reviewer: "runnerBot.reviewer", [fixer]: "runnerBot.fixer" } as const;
47
+ static spread = [...RunnerBotRole.values, "runnerBot.fixer"] as const;
48
+ static nested = { reviewer: { label: "runnerBot.reviewer" } } as const;
49
+ static get made() { return { reviewer: "runnerBot.reviewer" } as const; }
50
+ held = { reviewer: "runnerBot.reviewer" } as const;
51
+ }
52
+ `,
53
+ );
54
+ return constants;
55
+ };
56
+
57
+ const workspace = async (files: Record<string, string>) => {
58
+ const root = await makeRoot();
59
+ for (const [rel, text] of Object.entries(files)) await writeText(path.join(root, rel), text);
60
+ const abs = (rel: string) => path.join(root, rel);
61
+ return { root, abs };
62
+ };
63
+
64
+ const reader = (root: string, imports: Record<string, string[]>, piecesOf?: DictionaryPiecesOf): DictionaryRoutes => {
65
+ const importsByModule = new Map<string, ClientModuleImport[]>(
66
+ Object.entries(imports).map(([from, to]) => [
67
+ path.join(root, from),
68
+ to.map((rel) => ({ path: path.join(root, rel), lazy: false })),
69
+ ]),
70
+ );
71
+ return new DictionaryRoutes(root, { importsByModule, constants: constantsOf(), ...(piecesOf ? { piecesOf } : {}) });
72
+ };
73
+
74
+ describe("DictionaryRoutes", () => {
75
+ test("a route shows the framework's own texts even when its client modules name no key", async () => {
76
+ const { root, abs } = await workspace({ "apps/demo/page/Plain.tsx": `export const Plain = () => <div />;` });
77
+ const read = reader(root, {}).read({ entries: [abs("apps/demo/page/Plain.tsx")] });
78
+
79
+ expect(read).toEqual({ groups: ["base"], api: false, whole: null });
80
+ });
81
+
82
+ test("a route loading a module's client runtime shows its model, enums, scalars and the models it refers to", async () => {
83
+ const { root, abs } = await workspace({
84
+ "apps/demo/page/Memo.tsx": `export const Page = () => <>{l("memo.modelName")}</>;`,
85
+ });
86
+ const read = reader(root, { "apps/demo/page/Memo.tsx": ["apps/demo/lib/__client/memo.st.ts"] }).read({
87
+ entries: [abs("apps/demo/page/Memo.tsx")],
88
+ });
89
+
90
+ expect(read.whole).toBeNull();
91
+ expect(read.groups).toEqual(["address", "base", "memo", "memoStatus", "user", "userRole"]);
92
+ });
93
+
94
+ test("a route naming an enum's class shows that enum's texts, through the files its entry imports", async () => {
95
+ const { root, abs } = await workspace({
96
+ "apps/demo/page/Status.tsx": `export const Page = () => <Badge />;`,
97
+ "apps/demo/ui/Badge.tsx": `export const Badge = () => <Select options={MemoStatus.values} label={l("shared.status")} />;`,
98
+ });
99
+ const read = reader(root, { "apps/demo/page/Status.tsx": ["apps/demo/ui/Badge.tsx"] }).read({
100
+ entries: [abs("apps/demo/page/Status.tsx")],
101
+ });
102
+
103
+ expect(read.groups).toEqual(expect.arrayContaining(["base", "memoStatus", "shared"]));
104
+ expect(read.groups).not.toContain("memo");
105
+ });
106
+
107
+ test("a route with a key the build cannot follow loads the whole dictionary, naming the file and line", async () => {
108
+ const { root, abs } = await workspace({
109
+ "apps/demo/page/Any.tsx": `export const Page = () => <Label name="memo" />;`,
110
+ "apps/demo/ui/Label.tsx": [
111
+ `export const Label = ({ name }: { name: string }) => {`,
112
+ ` const { l } = usePage();`,
113
+ ` return <>{l(name)}</>;`,
114
+ `};`,
115
+ ].join("\n"),
116
+ });
117
+ const read = reader(root, { "apps/demo/page/Any.tsx": ["apps/demo/ui/Label.tsx"] }).read({
118
+ entries: [abs("apps/demo/page/Any.tsx")],
119
+ });
120
+
121
+ expect(read.groups).toEqual([]);
122
+ expect(read.whole).toEqual({
123
+ file: "apps/demo/ui/Label.tsx",
124
+ line: 3,
125
+ why: "name is a parameter or prop whose type names no key",
126
+ });
127
+ expect(read.whole && DictionaryRoutes.pinned(read.whole)).toBe(
128
+ "apps/demo/ui/Label.tsx:3 name is a parameter or prop whose type names no key",
129
+ );
130
+ });
131
+
132
+ test("a route loading every module's client runtime loads the whole dictionary, unless the build tells it which", async () => {
133
+ const files = {
134
+ "apps/demo/page/Memo.tsx": `export const Page = () => <>{st.use.memo()}</>;`,
135
+ "apps/demo/lib/memo/memo.store.ts": `export class MemoStore { label = "memo.title"; }`,
136
+ };
137
+ const { root, abs } = await workspace(files);
138
+ const imports = { "apps/demo/page/Memo.tsx": ["apps/demo/lib/st.ts"] };
139
+ const entries = [abs("apps/demo/page/Memo.tsx")];
140
+
141
+ expect(reader(root, imports).read({ entries }).whole).toEqual({
142
+ file: "apps/demo/lib/st.ts",
143
+ why: "loads every module's client runtime",
144
+ });
145
+ const piecesOf: DictionaryPiecesOf = () => ({ perModule: true, pieces: ["apps/demo/lib/__client/memo.st"] });
146
+ const read = reader(root, imports, piecesOf).read({ entries });
147
+ expect(read.whole).toBeNull();
148
+ expect(read.groups).toEqual(["address", "base", "memo", "memoStatus", "user", "userRole"]);
149
+ const everyModule: DictionaryPiecesOf = () => ({ perModule: false, pieces: [] });
150
+ expect(reader(root, imports, everyModule).read({ entries }).whole?.why).toBe("needs every module's client runtime");
151
+ });
152
+
153
+ test("a server module handing a client component a model's name adds that group, and a framework surface showing any module loads the whole dictionary", async () => {
154
+ const { root, abs } = await workspace({
155
+ "apps/demo/page/Client.tsx": `export const Client = () => null;`,
156
+ "apps/demo/page/Server.tsx": `export const Page = () => <Load.View modelName="team" />;`,
157
+ "apps/demo/page/Explorer.tsx": `import { Signal } from "akanjs/ui";\nexport const Page = () => <Signal.Doc />;`,
158
+ });
159
+ const routes = reader(root, {});
160
+ const entries = [abs("apps/demo/page/Client.tsx")];
161
+
162
+ expect(routes.read({ entries, serverModules: [abs("apps/demo/page/Server.tsx")] }).groups).toEqual([
163
+ "base",
164
+ "team",
165
+ ]);
166
+ expect(routes.read({ entries, serverModules: [abs("apps/demo/page/Explorer.tsx")] }).whole).toEqual({
167
+ file: "apps/demo/page/Explorer.tsx",
168
+ why: "Signal from akanjs/ui shows the texts of any module its data names",
169
+ });
170
+ });
171
+
172
+ test("a constant class's static table gives its written keys only when every entry is one", () => {
173
+ const constants = constantsOf();
174
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual(["runnerBot.reviewer", "task.fixer"]);
175
+ expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toEqual(["project.stage.open", "project.stage.done"]);
176
+ for (const member of ["loose", "typed", "called", "computed", "spread", "nested", "made", "held", "missing"])
177
+ expect(constants.staticKeysOf("RunnerBot", member), member).toBeNull();
178
+ expect(constants.staticKeysOf("Missing", "labelKeyOf")).toBeNull();
179
+
180
+ constants.add(
181
+ "libs/shared/lib/runnerBot/runnerBot.constant.ts",
182
+ `export class RunnerBot {
183
+ static readonly labelKeyOf = { planner: "runnerBot.planner", fixer: "task.fixer" } as const;
184
+ static stageKeys = load();
185
+ }
186
+ `,
187
+ );
188
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual([
189
+ "runnerBot.reviewer",
190
+ "task.fixer",
191
+ "runnerBot.planner",
192
+ ]);
193
+ expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toBeNull();
194
+
195
+ constants.add("libs/util/lib/runnerBot/runnerBot.constant.ts", `export class RunnerBot extends BaseBot {}`);
196
+ expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toBeNull();
197
+ });
198
+
199
+ test("a route picking a key from a constant class's static table shows the groups its keys name", async () => {
200
+ const page = (table: string) =>
201
+ [
202
+ `import { cnst } from "@apps/demo/client";`,
203
+ `export const Page = ({ role }: { role: string }) => <>{l(cnst.RunnerBot.${table}[role])}</>;`,
204
+ ].join("\n");
205
+ const { root, abs } = await workspace({
206
+ "apps/demo/page/Bots.tsx": page("labelKeyOf"),
207
+ "apps/demo/page/Loose.tsx": page("loose"),
208
+ });
209
+ const routes = reader(root, {});
210
+
211
+ const read = routes.read({ entries: [abs("apps/demo/page/Bots.tsx")] });
212
+ expect(read.whole).toBeNull();
213
+ expect(read.groups).toEqual(["base", "runnerBot", "task"]);
214
+ expect(routes.read({ entries: [abs("apps/demo/page/Loose.tsx")] }).whole).toEqual({
215
+ file: "apps/demo/page/Loose.tsx",
216
+ line: 2,
217
+ why: "cnst.RunnerBot.loose[role] is read from data at run time",
218
+ });
219
+ });
220
+
221
+ test("a route naming an API description key says so, for the API description file", async () => {
222
+ const { root, abs } = await workspace({
223
+ "apps/demo/page/Api.tsx": `export const Page = () => <>{l("memo.signal.getMemo.desc")}</>;`,
224
+ });
225
+ const read = reader(root, {}).read({ entries: [abs("apps/demo/page/Api.tsx")] });
226
+
227
+ expect(read.api).toBe(true);
228
+ expect(read.groups).toEqual([DictionaryAssetBuilder.apiGroup, "base", "memo"]);
229
+ });
230
+
231
+ test("a development route counts the model references its server modules hand over, not every one the root layout imports", async () => {
232
+ const { root, abs } = await workspace({
233
+ "apps/demo/page/Notes.tsx": `import { fetch } from "@apps/demo/client";\nexport const Page = (id: string) => fetch.viewNote(id);\n`,
234
+ "apps/demo/ui/Plain.tsx": `"use client";\nexport const Plain = () => null;\n`,
235
+ });
236
+ const { demo } = await runtimeFixtureTables();
237
+ const referenceOf = (model: string) => abs(`apps/demo/lib/__client/${model}.ref.ts`);
238
+ const handoffs = new RouteHandoffs(
239
+ root,
240
+ new RouteRuntime(root, demo, new Set()),
241
+ new Map(["memo", "note"].map((model) => [model, referenceOf(model)])),
242
+ );
243
+ const discovered = [abs("apps/demo/ui/Plain.tsx"), referenceOf("memo"), referenceOf("note")];
244
+ const serverModules = [abs("apps/demo/page/Notes.tsx")];
245
+
246
+ const entries = await DictionaryRoutes.handedEntries(discovered, serverModules, handoffs);
247
+ expect(entries).toEqual([abs("apps/demo/ui/Plain.tsx"), referenceOf("note")]);
248
+ expect(reader(root, {}).read({ entries }).groups).toEqual(["base", "note"]);
249
+ expect(await DictionaryRoutes.handedEntries(discovered, serverModules, null)).toEqual(discovered);
250
+ });
251
+ });