@akanjs/devkit 3.3.0-rc.3 → 3.3.0-rc.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -0,0 +1,173 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { DictionaryKeys } from "./dictionaryKeys";
3
+
4
+ const read = (source: string, fileName = "apps/demo/lib/memo/Memo.Unit.tsx") => DictionaryKeys.read(source, fileName);
5
+
6
+ describe("DictionaryKeys", () => {
7
+ test("follows a literal key, a template whose group is written, and a key chosen from a table the file holds", () => {
8
+ const keys = read(`
9
+ import { usePage } from "akanjs/client";
10
+ const tabs = [{ id: "all", label: "memo.tab.all" }, { id: "mine", label: "comment.tab.mine" }] as const;
11
+ export const MemoTitle = ({ field }: { field: "title" | "content" }) => {
12
+ const { l } = usePage();
13
+ return (
14
+ <>
15
+ {l("memo.modelName")}
16
+ {l(\`memo.\${field}\`)}
17
+ {tabs.map((tab) => l(tab.label))}
18
+ </>
19
+ );
20
+ };
21
+ `);
22
+ expect(keys.unread).toEqual([]);
23
+ expect(keys.anyModule).toBeNull();
24
+ expect(keys.names).toEqual(expect.arrayContaining(["comment", "memo"]));
25
+ });
26
+
27
+ test("follows a key typed as a union of written keys, and a prop of such a type", () => {
28
+ const keys = read(`
29
+ type MemoKey = "memo.title" | "memo.content";
30
+ interface Props { label: \`user.\${string}\`; fallback?: MemoKey }
31
+ export const Label = ({ label, fallback }: Props) => {
32
+ const { l } = usePage();
33
+ return <>{l(label)}{fallback ? l(fallback) : null}</>;
34
+ };
35
+ `);
36
+ expect(keys.unread).toEqual([]);
37
+ });
38
+
39
+ test("names the file's line and the reason for a key it cannot follow", () => {
40
+ const keys = read(
41
+ [
42
+ `import { usePage } from "akanjs/client";`,
43
+ `export const Any = ({ name }: { name: string }) => {`,
44
+ ` const { l } = usePage();`,
45
+ ` return <>{l(name)}</>;`,
46
+ `};`,
47
+ ].join("\n"),
48
+ );
49
+ expect(keys.unread).toEqual([{ line: 4, why: "name is a parameter or prop whose type names no key" }]);
50
+ });
51
+
52
+ test("reads a key built from data, a call's result and an import as unread", () => {
53
+ const keys = read(`
54
+ import { keyOf } from "./keys";
55
+ export const View = ({ memo }: { memo: { status: string } }) => {
56
+ const { l } = usePage();
57
+ return <>{l(memo.status)}{l(keyOf(memo))}{l(keyOf)}</>;
58
+ };
59
+ `);
60
+ expect(keys.unread.map(({ why }) => why)).toEqual([
61
+ "memo.status is read from data at run time",
62
+ "keyOf(memo) is a call's result",
63
+ "keyOf is imported from another file",
64
+ ]);
65
+ });
66
+
67
+ test("reads a translator handed to another function as unread, under any name it is destructured as", () => {
68
+ const keys = read(`
69
+ export const View = () => {
70
+ const { l: t } = usePage();
71
+ return <>{format(t, "memo.title")}</>;
72
+ };
73
+ `);
74
+ expect(keys.unread.map(({ why }) => why)).toEqual(["t passes the translator on"]);
75
+ });
76
+
77
+ test("counts the property names of an object the file holds when a key is built from them", () => {
78
+ const shapes = {
79
+ keys: `Object.keys(tabs).map((name) => l(\`\${name}.modelName\`))`,
80
+ entries: `Object.entries(tabs).map(([name]) => l(\`\${name}.modelName\`))`,
81
+ forIn: `(() => { for (const name in tabs) return l(\`\${name}.modelName\`); })()`,
82
+ };
83
+ for (const [shape, use] of Object.entries(shapes)) {
84
+ const keys = read(`
85
+ const tabs = { order: BiBox, "refund": BiUndo, [\`note\`]: 1, 7: 2 };
86
+ export const Nav = () => { const { l } = usePage(); return <>{${use}}</>; };
87
+ `);
88
+ expect(keys.unread, shape).toEqual([]);
89
+ expect(keys.names, shape).toEqual(expect.arrayContaining(["order", "refund", "note"]));
90
+ }
91
+ const typed = read(`
92
+ const tabs = { order: 1, refund: 2 };
93
+ export const Nav = ({ name }: { name: keyof typeof tabs }) => { const { l } = usePage(); return l(\`\${name}.modelName\`); };
94
+ `);
95
+ expect(typed.unread).toEqual([]);
96
+ expect(typed.names).toEqual(expect.arrayContaining(["order", "refund"]));
97
+ });
98
+
99
+ test("fails to the whole dictionary for property names it cannot count", () => {
100
+ const wrap = (table: string, use: string) =>
101
+ read(`
102
+ import { other } from "./other";
103
+ ${table}
104
+ export const Nav = ({ name }: { name: keyof typeof tabs }) => { const { l } = usePage(); return <>{${use}}</>; };
105
+ `);
106
+ const use = `Object.keys(tabs).map((name) => l(\`\${name}.modelName\`))`;
107
+ expect(wrap("const tabs = { [dynamic()]: 1 };", use).unread).toHaveLength(1);
108
+ expect(wrap("const tabs = { ...other, order: 1 };", use).unread).toHaveLength(1);
109
+ expect(wrap("const tabs = other;", use).unread).toHaveLength(1);
110
+ expect(
111
+ wrap("const tabs = { order: 1 };", `Object.keys(other).map((name) => l(\`\${name}.modelName\`))`).unread,
112
+ ).toHaveLength(1);
113
+ expect(
114
+ wrap("const tabs = { a: { order: 1 } };", `Object.keys(tabs.a).map((name) => l(\`\${name}.modelName\`))`).unread,
115
+ ).toHaveLength(1);
116
+ expect(wrap("const tabs = { [dynamic()]: 1 };", `l(\`\${name}.modelName\`)`).unread).toHaveLength(1);
117
+ });
118
+
119
+ test("counts the literal head of a template type as its group, and fails a head with none", () => {
120
+ const keys = read(`
121
+ interface Props { label: \`memo.\${string}\` }
122
+ export const Label = ({ label }: Props) => { const { l } = usePage(); return l(label); };
123
+ `);
124
+ expect(keys.unread).toEqual([]);
125
+ expect(keys.names).toContain("memo");
126
+ const headless = read(`
127
+ export const Label = ({ label }: { label: \`\${string}.title\` }) => { const { l } = usePage(); return l(label); };
128
+ `);
129
+ expect(headless.unread).toHaveLength(1);
130
+ });
131
+
132
+ test("reads a translator used other than as a call or a member call it understands as unread", () => {
133
+ const uses = [
134
+ "const t = l; return t('memo.title');",
135
+ "const page = usePage(); const t = page.l; return t('memo.title');",
136
+ "return <Row t={l} />;",
137
+ "return helper({ l });",
138
+ "return [l];",
139
+ "return l._ ? 1 : 0;",
140
+ ];
141
+ for (const use of uses) {
142
+ const keys = read(`export const A = () => { const { l } = usePage(); ${use} };`);
143
+ expect(keys.unread.length, use).toBeGreaterThan(0);
144
+ }
145
+ expect(read(`export const useT = () => { const { l } = usePage(); return l; };`).unread).toHaveLength(1);
146
+ const understood = read(`
147
+ export const A = ({ m }: { m: string }) => {
148
+ const page = usePage();
149
+ const { l } = page;
150
+ return <>{l("memo.title")}{l._("memo.title")}{l.rich("memo.title")}{l.trans({ en: "a", ko: "b" })}{page.l("memo.title")}{l.field(m, "title")}{l.enum(m, "x")}</>;
151
+ };
152
+ `);
153
+ expect(understood.unread).toEqual([]);
154
+ });
155
+
156
+ test("marks a framework surface that shows the texts of any module", () => {
157
+ expect(read(`import { Signal } from "akanjs/ui";`).anyModule).toContain("Signal from akanjs/ui");
158
+ expect(read(`import { Field } from "akanjs/ui/Constant";`).anyModule).toContain("Constant from akanjs/ui/Constant");
159
+ expect(read(`import { Data, Field } from "akanjs/ui";`).anyModule).toBeNull();
160
+ expect(read(`import type { Signal } from "akanjs/ui";`).anyModule).toBeNull();
161
+ });
162
+
163
+ test("collects the class names a constant table maps to groups, the one-name props, and the API keys", () => {
164
+ const keys = read(`
165
+ export const List = () => (
166
+ <Data.Dashboard modelName="memo" sliceName="memoInAdmin" filter={MemoStatus} title={l("memo.signal.getMemo.desc")} />
167
+ );
168
+ `);
169
+ expect(keys.classNames).toEqual(expect.arrayContaining(["MemoStatus"]));
170
+ expect(keys.propNames).toEqual(["memo", "memoInAdmin", "summary"]);
171
+ expect(keys.api).toBe(true);
172
+ });
173
+ });
@@ -0,0 +1,415 @@
1
+ import ts from "typescript";
2
+ import { RuntimeLexicalScope } from "./runtimeLexicalScope";
3
+
4
+ export interface DictionaryKeyUnread {
5
+ line: number;
6
+ why: string;
7
+ }
8
+
9
+ export interface DictionaryKeyRead {
10
+ //? The first segment of every string the file holds, and every string that is one name: a superset of its groups.
11
+ names: string[];
12
+ //? PascalCase names, which a constant table turns into the groups of the enums, scalars and models they name.
13
+ classNames: string[];
14
+ //? One-name strings handed to a component as a prop (`modelName="memo"`): what a server module tells client UI.
15
+ propNames: string[];
16
+ api: boolean;
17
+ unread: DictionaryKeyUnread[];
18
+ //? A framework surface that shows the texts of whichever module its data names, not of the modules a page loads.
19
+ anyModule: string | null;
20
+ }
21
+
22
+ const leadName = /^([A-Za-z_$][\w$]*)(?:\.|$)/;
23
+ const className = /^[A-Z][A-Za-z0-9]*$/;
24
+ const apiKey = /\.signal\.[^.\s]*\.(?:desc|arg)\b/;
25
+ const anyModuleSurfaces = new Set(["Signal", "Constant"]);
26
+ const frameworkUi = /^akanjs\/ui(?:\/(Signal|Constant)(?:\/|$)|$)/;
27
+ const oneName = /^[A-Za-z_$][\w$]*$/;
28
+ //? `Data.Dashboard` labels its columns `summary.<column>` unless it is handed another `summaryRefName`.
29
+ const impliedNames = new Map([["Dashboard", "summary"]]);
30
+ const tableMethods = new Set(["map", "forEach", "filter", "flatMap", "find", "findLast", "some", "every"]);
31
+ const subsetMethods = new Set(["filter", "slice", "sort", "toSorted", "reverse", "toReversed", "concat", "at"]);
32
+ const objectReaders = new Set(["keys", "values", "entries"]);
33
+ const memberCalls = new Set(["field", "enum", "trans"]);
34
+ const translatorChain = new Set(["_", "rich"]);
35
+ const groupHead = /^[A-Za-z_$][\w$]*\./;
36
+ const maxDepth = 16;
37
+
38
+ const strip = (node: ts.Expression): ts.Expression =>
39
+ ts.isParenthesizedExpression(node) ||
40
+ ts.isAsExpression(node) ||
41
+ ts.isSatisfiesExpression(node) ||
42
+ ts.isNonNullExpression(node) ||
43
+ ts.isTypeAssertionExpression(node)
44
+ ? strip(node.expression)
45
+ : node;
46
+
47
+ //* Which dictionary groups a client file can show: the keys it hands `l`, `l._`, `l.rich` or `translate` must come from
48
+ //* strings written in the file (a literal, a template with a literal group, a table or a typed union it holds).
49
+ export class DictionaryKeys {
50
+ readonly #sourceFile: ts.SourceFile;
51
+ readonly #scope = new RuntimeLexicalScope();
52
+ readonly #translators = new Set(["l"]);
53
+ readonly #names = new Set<string>();
54
+ readonly #classNames = new Set<string>();
55
+ readonly #propNames = new Set<string>();
56
+ readonly #unread: DictionaryKeyUnread[] = [];
57
+ #api = false;
58
+ #anyModule: string | null = null;
59
+
60
+ private constructor(sourceFile: ts.SourceFile) {
61
+ this.#sourceFile = sourceFile;
62
+ }
63
+
64
+ static read(text: string, fileName: string): DictionaryKeyRead {
65
+ const kind = fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
66
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, kind);
67
+ return new DictionaryKeys(sourceFile).#read();
68
+ }
69
+
70
+ #read(): DictionaryKeyRead {
71
+ this.#collectAliases(this.#sourceFile);
72
+ this.#visit(this.#sourceFile);
73
+ return {
74
+ names: [...this.#names].sort(),
75
+ classNames: [...this.#classNames].sort(),
76
+ propNames: [...this.#propNames].sort(),
77
+ api: this.#api,
78
+ unread: this.#unread,
79
+ anyModule: this.#anyModule,
80
+ };
81
+ }
82
+
83
+ #collectAliases(node: ts.Node) {
84
+ if (ts.isBindingElement(node) && node.propertyName && ts.isIdentifier(node.name)) {
85
+ const property = node.propertyName;
86
+ if (ts.isIdentifier(property) && property.text === "l") this.#translators.add(node.name.text);
87
+ }
88
+ ts.forEachChild(node, (child) => this.#collectAliases(child));
89
+ }
90
+
91
+ #visit(node: ts.Node) {
92
+ if (ts.isExpression(node) && this.#isTranslator(node) && this.#isReference(node)) this.#checkTranslatorUse(node);
93
+ if (ts.isImportDeclaration(node)) this.#readImport(node);
94
+ else if (ts.isStringLiteralLike(node)) this.#addText(node.text, node.text);
95
+ else if (ts.isTemplateExpression(node))
96
+ this.#addText(node.head.text, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join("*"));
97
+ else if (ts.isTemplateLiteralTypeNode(node))
98
+ this.#addText(node.head.text, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join("*"));
99
+ else if (ts.isIdentifier(node) && className.test(node.text)) this.#classNames.add(node.text);
100
+ else if (ts.isCallExpression(node)) this.#readCall(node);
101
+ else if (ts.isJsxAttribute(node) && node.initializer && ts.isStringLiteral(node.initializer)) {
102
+ if (oneName.test(node.initializer.text)) this.#propNames.add(node.initializer.text);
103
+ }
104
+ const implied = ts.isPropertyAccessExpression(node) ? impliedNames.get(node.name.text) : undefined;
105
+ if (implied) {
106
+ this.#names.add(implied);
107
+ this.#propNames.add(implied);
108
+ }
109
+ ts.forEachChild(node, (child) => this.#visit(child));
110
+ }
111
+
112
+ #addText(lead: string, pattern: string) {
113
+ const name = lead.match(leadName)?.[1];
114
+ if (name) this.#names.add(name);
115
+ if (apiKey.test(pattern)) this.#api = true;
116
+ }
117
+
118
+ #readImport(node: ts.ImportDeclaration) {
119
+ if (!ts.isStringLiteral(node.moduleSpecifier) || node.importClause?.isTypeOnly) return;
120
+ const specifier = node.moduleSpecifier.text;
121
+ const [matched, surface] = specifier.match(frameworkUi) ?? [];
122
+ if (!matched) return;
123
+ const bindings = node.importClause?.namedBindings;
124
+ const named =
125
+ bindings && ts.isNamedImports(bindings)
126
+ ? bindings.elements
127
+ .filter((element) => !element.isTypeOnly)
128
+ .map((element) => (element.propertyName ?? element.name).text)
129
+ : [];
130
+ const shown = surface ?? named.find((name) => anyModuleSurfaces.has(name));
131
+ if (shown) this.#anyModule ??= `${shown} from ${specifier} shows the texts of any module its data names`;
132
+ }
133
+
134
+ #readCall(call: ts.CallExpression) {
135
+ const key = this.#keyOf(call);
136
+ if (!key || this.#follows(key, 0)) return;
137
+ this.#fail(key, this.#whyOf(strip(key)));
138
+ }
139
+
140
+ #isReference(node: ts.Expression): boolean {
141
+ const { parent } = node;
142
+ if (ts.isShorthandPropertyAssignment(parent)) return true;
143
+ if ((parent as { name?: ts.Node }).name === node) return false;
144
+ if (ts.isBindingElement(parent) || ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))
145
+ return parent.propertyName !== node;
146
+ return !ts.isTypeQueryNode(parent) && !ts.isQualifiedName(parent);
147
+ }
148
+
149
+ #checkTranslatorUse(node: ts.Expression) {
150
+ const outerOf = (inner: ts.Node): ts.Node => {
151
+ let outer = inner;
152
+ while (
153
+ ts.isParenthesizedExpression(outer.parent) ||
154
+ ts.isAsExpression(outer.parent) ||
155
+ ts.isSatisfiesExpression(outer.parent) ||
156
+ ts.isNonNullExpression(outer.parent) ||
157
+ ts.isTypeAssertionExpression(outer.parent)
158
+ )
159
+ outer = outer.parent;
160
+ return outer;
161
+ };
162
+ const outer = outerOf(node);
163
+ const { parent } = outer;
164
+ if (ts.isCallExpression(parent) && parent.expression === outer) return;
165
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === outer) {
166
+ if (translatorChain.has(parent.name.text)) return;
167
+ const access = outerOf(parent);
168
+ if (
169
+ memberCalls.has(parent.name.text) &&
170
+ ts.isCallExpression(access.parent) &&
171
+ access.parent.expression === access
172
+ )
173
+ return;
174
+ }
175
+ this.#fail(
176
+ node,
177
+ ts.isCallExpression(parent)
178
+ ? "passes the translator on"
179
+ : "is used other than as a call, which no key can be read from",
180
+ );
181
+ }
182
+
183
+ #isTranslator(node: ts.Expression): boolean {
184
+ if (ts.isIdentifier(node)) return this.#translators.has(node.text);
185
+ if (!ts.isPropertyAccessExpression(node)) return false;
186
+ const name = node.name.text;
187
+ if (name === "l") return true;
188
+ return (name === "_" || name === "rich") && this.#isTranslator(strip(node.expression));
189
+ }
190
+
191
+ #keyOf(call: ts.CallExpression): ts.Expression | undefined {
192
+ const callee = strip(call.expression);
193
+ if (this.#isTranslator(callee)) return call.arguments[0];
194
+ const name = ts.isIdentifier(callee)
195
+ ? callee.text
196
+ : ts.isPropertyAccessExpression(callee)
197
+ ? callee.name.text
198
+ : null;
199
+ if (name === "translate" || name === "translateByLocale")
200
+ return call.arguments.length > 1 ? call.arguments[1] : undefined;
201
+ return undefined;
202
+ }
203
+
204
+ #fail(node: ts.Node, why: string) {
205
+ const { line } = this.#sourceFile.getLineAndCharacterOfPosition(node.getStart(this.#sourceFile));
206
+ const text = node.getText(this.#sourceFile).replace(/\s+/g, " ");
207
+ this.#unread.push({ line: line + 1, why: `${text.length > 60 ? `${text.slice(0, 57)}...` : text} ${why}` });
208
+ }
209
+
210
+ #whyOf(node: ts.Expression): string {
211
+ if (ts.isCallExpression(node)) return "is a call's result";
212
+ if (ts.isIdentifier(node)) {
213
+ const declared = this.#scope.resolve(node)?.parent;
214
+ if (!declared) return "is not declared in this file";
215
+ if (ts.isImportSpecifier(declared) || ts.isImportClause(declared) || ts.isNamespaceImport(declared))
216
+ return "is imported from another file";
217
+ if (ts.isParameter(this.#rootOf(declared) ?? declared)) return "is a parameter or prop whose type names no key";
218
+ return "is a variable this file does not hold as a written key";
219
+ }
220
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
221
+ return "is read from data at run time";
222
+ return "is built from data at run time";
223
+ }
224
+
225
+ #rootOf(node: ts.Node): ts.Node | null {
226
+ let at: ts.Node = node;
227
+ while (ts.isBindingElement(at) || ts.isObjectBindingPattern(at) || ts.isArrayBindingPattern(at)) at = at.parent;
228
+ return at === node ? null : at;
229
+ }
230
+
231
+ #follows(expression: ts.Expression, depth: number): boolean {
232
+ if (depth > maxDepth) return false;
233
+ const next = (inner: ts.Expression) => this.#follows(inner, depth + 1);
234
+ const node = strip(expression);
235
+ if (ts.isStringLiteralLike(node)) return true;
236
+ if (ts.isTemplateExpression(node)) {
237
+ if (node.head.text.includes(".")) return true;
238
+ const [first] = node.templateSpans;
239
+ return !node.head.text && !!first && first.literal.text.startsWith(".") && next(first.expression);
240
+ }
241
+ if (ts.isConditionalExpression(node)) return next(node.whenTrue) && next(node.whenFalse);
242
+ if (ts.isBinaryExpression(node)) {
243
+ const operator = node.operatorToken.kind;
244
+ if (operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken)
245
+ return next(node.left) && next(node.right);
246
+ if (operator === ts.SyntaxKind.AmpersandAmpersandToken) return next(node.right);
247
+ if (operator !== ts.SyntaxKind.PlusToken) return false;
248
+ const left = strip(node.left);
249
+ const right = strip(node.right);
250
+ if (ts.isStringLiteralLike(left)) return left.text.includes(".");
251
+ return next(left) && ts.isStringLiteralLike(right) && right.text.startsWith(".");
252
+ }
253
+ if (ts.isIdentifier(node)) return this.#bindingFollows(node, depth + 1, false);
254
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
255
+ return this.#isTable(node.expression, depth + 1);
256
+ return false;
257
+ }
258
+
259
+ //? With `names`, the property names are the keys: each one is added to the groups, and a name that is not written fails.
260
+ #isTable(expression: ts.Expression, depth: number, names = false): boolean {
261
+ if (depth > maxDepth) return false;
262
+ const node = strip(expression);
263
+ const value = (inner: ts.Expression) => this.#isValue(inner, depth + 1);
264
+ if (ts.isArrayLiteralExpression(node))
265
+ return node.elements.every((element) =>
266
+ ts.isSpreadElement(element) ? this.#isTable(element.expression, depth + 1, names) : value(element),
267
+ );
268
+ if (ts.isObjectLiteralExpression(node))
269
+ return node.properties.every((property) => {
270
+ if (names && !this.#addPropertyName(property)) return false;
271
+ if (ts.isPropertyAssignment(property)) return value(property.initializer);
272
+ if (ts.isShorthandPropertyAssignment(property)) return value(property.name);
273
+ if (ts.isSpreadAssignment(property)) return this.#isTable(property.expression, depth + 1, names);
274
+ return ts.isMethodDeclaration(property);
275
+ });
276
+ if (ts.isIdentifier(node)) return this.#bindingFollows(node, depth + 1, true, names);
277
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
278
+ return !names && this.#isTable(node.expression, depth + 1);
279
+ if (!ts.isCallExpression(node)) return false;
280
+ const callee = strip(node.expression);
281
+ if (!ts.isPropertyAccessExpression(callee)) return false;
282
+ const method = callee.name.text;
283
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === "Object" && objectReaders.has(method))
284
+ return !!node.arguments[0] && this.#isTable(node.arguments[0], depth + 1, method !== "values");
285
+ if (!subsetMethods.has(method)) return false;
286
+ const own = this.#isTable(callee.expression, depth + 1, names);
287
+ return own && (method !== "concat" || node.arguments.every((argument) => this.#isTable(argument, depth + 1)));
288
+ }
289
+
290
+ #addPropertyName(property: ts.ObjectLiteralElementLike): boolean {
291
+ if (ts.isSpreadAssignment(property)) return true;
292
+ const { name } = property;
293
+ if (ts.isComputedPropertyName(name)) {
294
+ const inner = strip(name.expression);
295
+ if (!ts.isStringLiteralLike(inner) && !ts.isNumericLiteral(inner)) return false;
296
+ this.#addText(inner.text, inner.text);
297
+ return true;
298
+ }
299
+ if (ts.isPrivateIdentifier(name)) return false;
300
+ this.#addText(name.text, name.text);
301
+ return true;
302
+ }
303
+
304
+ //? A value in a table is either text the file writes or something no key is made from (a number, an icon, a handler).
305
+ #isValue(expression: ts.Expression, depth: number): boolean {
306
+ const node = strip(expression);
307
+ if (
308
+ ts.isNumericLiteral(node) ||
309
+ node.kind === ts.SyntaxKind.TrueKeyword ||
310
+ node.kind === ts.SyntaxKind.FalseKeyword ||
311
+ node.kind === ts.SyntaxKind.NullKeyword ||
312
+ ts.isArrowFunction(node) ||
313
+ ts.isFunctionExpression(node) ||
314
+ ts.isJsxElement(node) ||
315
+ ts.isJsxSelfClosingElement(node) ||
316
+ ts.isJsxFragment(node) ||
317
+ (ts.isIdentifier(node) && (node.text === "undefined" || className.test(node.text)))
318
+ )
319
+ return true;
320
+ return this.#follows(node, depth) || this.#isTable(node, depth);
321
+ }
322
+
323
+ #bindingFollows(identifier: ts.Identifier, depth: number, asTable: boolean, names = false): boolean {
324
+ const declared = this.#scope.resolve(identifier);
325
+ if (!declared) return false;
326
+ const declaration = declared.parent;
327
+ const root = this.#rootOf(declaration) ?? declaration;
328
+ if (ts.isParameter(root)) return !names && this.#parameterFollows(root, declaration, depth, asTable);
329
+ if (!ts.isVariableDeclaration(root)) return false;
330
+ const list = root.parent;
331
+ if (ts.isVariableDeclarationList(list) && ts.isForInStatement(list.parent))
332
+ return !asTable && !names && root === declaration && this.#isTable(list.parent.expression, depth + 1, true);
333
+ if (ts.isVariableDeclarationList(list) && ts.isForOfStatement(list.parent))
334
+ return !names && this.#isTable(list.parent.expression, depth + 1);
335
+ if (!ts.isVariableDeclarationList(list) || !(list.flags & ts.NodeFlags.Const) || !root.initializer) return false;
336
+ if (root !== declaration) return !names && this.#isTable(root.initializer, depth + 1);
337
+ return asTable ? this.#isTable(root.initializer, depth + 1, names) : this.#follows(root.initializer, depth + 1);
338
+ }
339
+
340
+ #parameterFollows(parameter: ts.ParameterDeclaration, declaration: ts.Node, depth: number, asTable: boolean) {
341
+ if (parameter.type) {
342
+ const property = ts.isBindingElement(declaration) ? (declaration.propertyName ?? declaration.name) : null;
343
+ if (!property) return this.#typeFollows(parameter.type, depth + 1, asTable);
344
+ const member = ts.isIdentifier(property) ? this.#memberType(parameter.type, property.text, depth) : null;
345
+ return !!member && this.#typeFollows(member, depth + 1, asTable);
346
+ }
347
+ const callback = parameter.parent;
348
+ const call = callback.parent;
349
+ if (!(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) || !ts.isCallExpression(call))
350
+ return false;
351
+ const callee = strip(call.expression);
352
+ return (
353
+ ts.isPropertyAccessExpression(callee) &&
354
+ tableMethods.has(callee.name.text) &&
355
+ callback.parameters[0] === parameter &&
356
+ this.#isTable(callee.expression, depth + 1)
357
+ );
358
+ }
359
+
360
+ #memberType(type: ts.TypeNode, name: string, depth: number): ts.TypeNode | null {
361
+ if (depth > maxDepth) return null;
362
+ if (ts.isTypeLiteralNode(type))
363
+ for (const member of type.members)
364
+ if (ts.isPropertySignature(member) && member.name.getText(this.#sourceFile) === name)
365
+ return member.type ?? null;
366
+ if (ts.isIntersectionTypeNode(type)) {
367
+ for (const part of type.types) {
368
+ const found = this.#memberType(part, name, depth + 1);
369
+ if (found) return found;
370
+ }
371
+ return null;
372
+ }
373
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName)) return null;
374
+ const declared = this.#typeDeclaration(type.typeName.text);
375
+ if (declared && ts.isTypeAliasDeclaration(declared)) return this.#memberType(declared.type, name, depth + 1);
376
+ if (!declared || !ts.isInterfaceDeclaration(declared)) return null;
377
+ for (const member of declared.members)
378
+ if (ts.isPropertySignature(member) && member.name.getText(this.#sourceFile) === name) return member.type ?? null;
379
+ return null;
380
+ }
381
+
382
+ #typeFollows(type: ts.TypeNode, depth: number, asTable: boolean): boolean {
383
+ if (depth > maxDepth) return false;
384
+ const next = (inner: ts.TypeNode) => this.#typeFollows(inner, depth + 1, asTable);
385
+ if (ts.isParenthesizedTypeNode(type)) return next(type.type);
386
+ if (ts.isUnionTypeNode(type)) return type.types.every(next);
387
+ if (ts.isLiteralTypeNode(type)) return true;
388
+ if (type.kind === ts.SyntaxKind.UndefinedKeyword || type.kind === ts.SyntaxKind.NullKeyword) return true;
389
+ if (ts.isTemplateLiteralTypeNode(type)) return groupHead.test(type.head.text);
390
+ if (ts.isArrayTypeNode(type)) return asTable && next(type.elementType);
391
+ if (ts.isTypeOperatorNode(type) && type.operator === ts.SyntaxKind.ReadonlyKeyword) return next(type.type);
392
+ if (ts.isTypeOperatorNode(type) && type.operator === ts.SyntaxKind.KeyOfKeyword)
393
+ return ts.isTypeQueryNode(type.type) && this.#queryIsTable(type.type, depth, true);
394
+ if (ts.isIndexedAccessTypeNode(type)) {
395
+ let object = type.objectType;
396
+ while (ts.isParenthesizedTypeNode(object)) object = object.type;
397
+ return ts.isTypeQueryNode(object) && this.#queryIsTable(object, depth, false);
398
+ }
399
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName)) return false;
400
+ const declared = this.#typeDeclaration(type.typeName.text);
401
+ return !!declared && ts.isTypeAliasDeclaration(declared) && next(declared.type);
402
+ }
403
+
404
+ #queryIsTable(query: ts.TypeQueryNode, depth: number, names: boolean): boolean {
405
+ const name = query.exprName;
406
+ return ts.isIdentifier(name) && this.#isTable(name, depth + 1, names);
407
+ }
408
+
409
+ #typeDeclaration(name: string): ts.TypeAliasDeclaration | ts.InterfaceDeclaration | undefined {
410
+ return this.#sourceFile.statements.find(
411
+ (statement): statement is ts.TypeAliasDeclaration | ts.InterfaceDeclaration =>
412
+ (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name.text === name,
413
+ );
414
+ }
415
+ }
@@ -0,0 +1,36 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { ObjectImportReport } from "./objectImportReport";
3
+
4
+ describe("ObjectImportReport.format", () => {
5
+ test("prints one line per scope with its reasons by count, and where the files are listed", () => {
6
+ const kept = {
7
+ file: "apps/demo/page/_index.tsx",
8
+ line: 3,
9
+ object: "Scroll",
10
+ objectFile: "libs/util/ui/Scroll/index.tsx",
11
+ };
12
+
13
+ expect(
14
+ ObjectImportReport.format({
15
+ scopes: [
16
+ {
17
+ scope: "apps/demo",
18
+ app: "demo",
19
+ narrowed: 12,
20
+ kept: 4,
21
+ reasons: { call: 1, "rendered-or-called": 2, "passed-on": 1 },
22
+ },
23
+ { scope: "libs/util", app: "demo", narrowed: 3, kept: 0, reasons: {} },
24
+ ],
25
+ kept: [{ ...kept, reason: "rendered-or-called" }],
26
+ }),
27
+ ).toBe(
28
+ [
29
+ "apps/demo: 12 object imports load only the members they name, 4 load the whole object (rendered-or-called 2, call 1, passed-on 1)",
30
+ "libs/util: 3 object imports load only the members they name, 0 load the whole object",
31
+ "--format json lists each import that loads the whole object, with its file and line",
32
+ ].join("\n"),
33
+ );
34
+ expect(ObjectImportReport.format({ scopes: [], kept: [] })).toBe("");
35
+ });
36
+ });