@akanjs/devkit 3.3.0-rc.5 → 3.3.0-rc.51

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 (264) hide show
  1. package/CHANGELOG.md +686 -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 +70 -10
  9. package/akanConfig/akanConfig.ts +71 -206
  10. package/akanConfig/akanWorkers.test.ts +73 -0
  11. package/akanConfig/akanWorkers.ts +61 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +39 -0
  14. package/akanConfig/index.ts +1 -0
  15. package/akanConfig/nativeKeys.ts +52 -0
  16. package/akanConfig/types.ts +1 -0
  17. package/app/appBin.test.ts +63 -0
  18. package/app/appBin.ts +50 -0
  19. package/app/applicationBuildReporter.test.ts +49 -0
  20. package/app/applicationBuildReporter.ts +5 -0
  21. package/app/applicationBuildRunner.test.ts +279 -4
  22. package/app/applicationBuildRunner.ts +147 -12
  23. package/app/dictionarySizes.ts +91 -0
  24. package/app/routeFilesReport.test.ts +59 -0
  25. package/app/routeFilesReport.ts +46 -0
  26. package/app/routeJsBudget.ts +18 -4
  27. package/artifact/implicitRootLayout.test.ts +19 -0
  28. package/artifact/implicitRootLayout.ts +16 -2
  29. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  30. package/artifact/storeBootstrap.test.ts +28 -0
  31. package/artifact/storeBootstrap.ts +64 -8
  32. package/biome.base.json +7 -5
  33. package/codeAgent/agent/CodeAgent.ts +36 -16
  34. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  35. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  36. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  37. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  38. package/codeAgent/agent/codeAgent.test.ts +62 -0
  39. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  40. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  41. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  42. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  43. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  44. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  45. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  46. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  47. package/codeAgent/skills/akan-page/SKILL.md +34 -26
  48. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  49. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  50. package/codeAgent/skills/akan-service/SKILL.md +10 -11
  51. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  52. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  53. package/context/akanContext.ts +2 -0
  54. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  55. package/docs/apiReference.test.ts +9 -0
  56. package/docs/apiReference.ts +14 -0
  57. package/executors/appExecutor.ts +10 -5
  58. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  59. package/executors/clientRuntimeKeys.fixture.json +393 -0
  60. package/executors/clientRuntimeKeys.test.ts +1690 -0
  61. package/executors/executor.ts +12 -4
  62. package/executors/executors.test.ts +24 -0
  63. package/executors/sysExecutor.ts +80 -5
  64. package/executors/workspaceExecutor.ts +7 -4
  65. package/frontendBuild/allRoutesBuilder.ts +99 -7
  66. package/frontendBuild/autoImportSync.ts +3 -2
  67. package/frontendBuild/buildRouteClient.test.ts +686 -13
  68. package/frontendBuild/clientBuildTypes.ts +26 -0
  69. package/frontendBuild/clientEntriesBundler.ts +49 -1
  70. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  71. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  72. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  73. package/frontendBuild/clientEntryGroups.ts +61 -0
  74. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  75. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  76. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  77. package/frontendBuild/csrDevPatcher.test.ts +1 -1
  78. package/frontendBuild/csrDevPatcher.ts +33 -7
  79. package/frontendBuild/csrDevTypes.ts +9 -0
  80. package/frontendBuild/devBarrelImports.test.ts +154 -0
  81. package/frontendBuild/devBarrelImports.ts +83 -23
  82. package/frontendBuild/devRegistryBundler.ts +4 -2
  83. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  84. package/frontendBuild/devRouteRuntime.ts +167 -0
  85. package/frontendBuild/dictionaryAssetBuilder.test.ts +329 -0
  86. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  87. package/frontendBuild/dictionaryConstants.ts +136 -0
  88. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  89. package/frontendBuild/dictionaryPacking.ts +135 -0
  90. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  91. package/frontendBuild/dictionaryRoutes.ts +227 -0
  92. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  93. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  94. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  95. package/frontendBuild/precompressArtifacts.ts +22 -8
  96. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  97. package/frontendBuild/renderedEntries.ts +144 -0
  98. package/frontendBuild/routeClientBuilder.ts +407 -43
  99. package/frontendBuild/routeHandoffs.test.ts +155 -0
  100. package/frontendBuild/routeHandoffs.ts +117 -0
  101. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  102. package/frontendBuild/routeModulePreloads.ts +20 -11
  103. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  104. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  105. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  106. package/frontendBuild/routeRuntimePays.ts +117 -0
  107. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  108. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  109. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  110. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  111. package/frontendBuild/ssrDevBundler.ts +66 -11
  112. package/frontendBuild/vendorFileImports.test.ts +254 -0
  113. package/frontendBuild/vendorFileImports.ts +163 -0
  114. package/frontendBuild/vendorNarrowing.ts +28 -0
  115. package/frontendBuild/vendorSpecifiers.ts +2 -0
  116. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  117. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  118. package/incrementalBuilder/builderBoot.ts +5 -5
  119. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  120. package/incrementalBuilder/builderLanes.ts +2 -2
  121. package/incrementalBuilder/builderWatch.ts +8 -8
  122. package/incrementalBuilder/csrRegistry.ts +4 -4
  123. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  124. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  125. package/incrementalBuilder/ssrRegistry.ts +6 -6
  126. package/index.ts +1 -1
  127. package/integration/renderAdmissionSoak.test.ts +99 -0
  128. package/integration/renderAdmissionSoak.ts +609 -0
  129. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  130. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  131. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  132. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  133. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  134. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  135. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  136. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  137. package/lint/biomeBase.test.ts +50 -3
  138. package/lint/biomeBase.ts +1 -1
  139. package/lint/biomeCheck.test.ts +162 -0
  140. package/lint/biomeCheck.ts +131 -0
  141. package/lint/linter.test.ts +16 -11
  142. package/lint/no-arbitrary-color.grit +5 -0
  143. package/lint/no-conditional-st-hook.grit +5 -1
  144. package/lint/no-daisyui-legacy-class.grit +8 -0
  145. package/lint/no-document-cookie.grit +3 -0
  146. package/lint/no-inline-color.grit +10 -2
  147. package/lint/no-oversized-list-limit.grit +2 -0
  148. package/lint/no-raw-palette-class.grit +7 -0
  149. package/lint/no-unpublished-form-setter.grit +2 -0
  150. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  151. package/lint/no-web-storage.grit +3 -0
  152. package/lint/withheldEnvFile.ts +17 -0
  153. package/mobile/desktopBin.ts +2 -2
  154. package/mobile/desktopServerStage.test.ts +9 -2
  155. package/mobile/desktopServerStage.ts +1 -0
  156. package/mobile/nativeApp.test.ts +7 -5
  157. package/mobile/nativeApp.ts +2 -2
  158. package/mobile/nativeConfig.test.ts +96 -1
  159. package/mobile/nativeConfig.ts +46 -12
  160. package/mobile/nativePublicEnv.ts +1 -1
  161. package/mobile/serverBundleSecrets.ts +43 -0
  162. package/package.json +15 -169
  163. package/packageExports.test.ts +38 -24
  164. package/quality/dictionaryKeys.test.ts +356 -0
  165. package/quality/dictionaryKeys.ts +488 -0
  166. package/quality/objectImportReport.test.ts +36 -0
  167. package/quality/objectImportReport.ts +105 -0
  168. package/quality/qualityScanner.ts +1 -1
  169. package/quality/routeRuntimeReport.test.ts +91 -0
  170. package/quality/routeRuntimeReport.ts +121 -0
  171. package/quality/runtimeConstantFacts.ts +71 -0
  172. package/quality/runtimeConstantGraph.ts +123 -0
  173. package/quality/runtimeConstantReads.ts +116 -0
  174. package/quality/runtimeImports.test.ts +190 -0
  175. package/quality/runtimeImports.ts +233 -0
  176. package/quality/runtimeKeyNames.ts +46 -0
  177. package/quality/runtimeLexicalScope.ts +132 -0
  178. package/quality/runtimeMarkerReach.test.ts +84 -0
  179. package/quality/runtimeMarkerReach.ts +255 -0
  180. package/quality/runtimeModuleFacts.ts +290 -0
  181. package/quality/runtimeNameTable.test.ts +172 -0
  182. package/quality/runtimeNameTable.ts +477 -0
  183. package/quality/runtimeScopeReport.test.ts +123 -0
  184. package/quality/runtimeScopeReport.ts +167 -0
  185. package/quality/runtimeSliceKey.ts +269 -0
  186. package/quality/runtimeSyntax.ts +133 -0
  187. package/quality/runtimeTable.fixture.ts +189 -0
  188. package/quality/runtimeUse.test.ts +737 -0
  189. package/quality/runtimeUse.ts +696 -0
  190. package/quality/runtimeUseReadable.test.ts +393 -0
  191. package/quality/ssrScanner.test.ts +13 -0
  192. package/quality/ssrScanner.ts +1 -1
  193. package/quality/translatorBindings.ts +187 -0
  194. package/test/secretEnvFixture.ts +134 -0
  195. package/test/testHelpers.ts +11 -0
  196. package/transforms/barrelAnalyzer.ts +26 -4
  197. package/transforms/barrelImportsPlugin.ts +121 -32
  198. package/transforms/exportReach.test.ts +162 -0
  199. package/transforms/exportReach.ts +308 -0
  200. package/transforms/frameworkObjects.fixture.tsx +58 -0
  201. package/transforms/frameworkObjects.test.ts +54 -0
  202. package/transforms/modelReference.test.ts +196 -0
  203. package/transforms/modelReference.ts +39 -0
  204. package/transforms/moduleParts.test.ts +225 -0
  205. package/transforms/moduleParts.ts +418 -0
  206. package/transforms/objectImportEdits.ts +150 -0
  207. package/transforms/objectMemberImports.test.ts +633 -0
  208. package/transforms/objectMemberImports.ts +571 -0
  209. package/transforms/objectMemberLookup.ts +150 -0
  210. package/transforms/objectModule.test.ts +307 -0
  211. package/transforms/objectModule.ts +482 -0
  212. package/transforms/objectModuleAnalyzer.ts +104 -0
  213. package/transforms/partImports.test.ts +76 -0
  214. package/transforms/partImports.ts +110 -0
  215. package/transforms/partModules.test.ts +187 -0
  216. package/transforms/partModules.ts +90 -0
  217. package/transforms/partPurity.ts +124 -0
  218. package/transforms/reactIconImports.test.ts +231 -0
  219. package/transforms/reactIconImports.ts +325 -0
  220. package/transforms/routeConstants.ts +122 -0
  221. package/transforms/routeRuntime.test.ts +835 -0
  222. package/transforms/routeRuntime.ts +703 -0
  223. package/transforms/routeRuntimeEdits.ts +92 -0
  224. package/transforms/routeRuntimeGraph.ts +66 -0
  225. package/transforms/routeRuntimePlan.ts +244 -0
  226. package/transforms/secretEnvDeclaration.test.ts +208 -0
  227. package/transforms/secretEnvDeclaration.ts +213 -0
  228. package/transforms/secretEnvFile.test.ts +117 -0
  229. package/transforms/secretEnvFile.ts +113 -0
  230. package/transforms/secretEnvName.test.ts +54 -0
  231. package/transforms/secretEnvName.ts +29 -0
  232. package/transforms/secretEnvSource.test.ts +148 -0
  233. package/transforms/secretEnvSource.ts +166 -0
  234. package/transforms/serverEnvEvaluationError.ts +11 -0
  235. package/transforms/serverEnvPlugin.test.ts +2 -1
  236. package/transforms/serverEnvPlugin.ts +13 -0
  237. package/transforms/serverEnvProfile.test.ts +115 -2
  238. package/transforms/serverEnvProfile.ts +117 -40
  239. package/transforms/serverEnvSecrets.test.ts +292 -0
  240. package/transforms/signalDescriptors.test.ts +280 -0
  241. package/transforms/signalDescriptors.ts +227 -0
  242. package/transforms/thisFreeExports.ts +87 -0
  243. package/transforms/transforms.test.ts +180 -3
  244. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  245. package/tunnel/createTunnel.test.ts +29 -8
  246. package/tunnel/createTunnel.ts +18 -11
  247. package/typecheck/projectTypecheck.test.ts +32 -1
  248. package/typecheck/projectTypecheck.ts +3 -3
  249. package/typecheck/typeChecker.test.ts +49 -0
  250. package/typecheck/typeChecker.ts +9 -7
  251. package/typecheck/withheldDiagnostics.ts +41 -0
  252. package/util/fileEditor.ts +1 -0
  253. package/util/selectModel.ts +1 -0
  254. package/workflow/executor.ts +6 -2
  255. package/workflow/index.ts +1 -0
  256. package/workflow/plan.ts +36 -7
  257. package/workflow/types.ts +1 -1
  258. package/workflow/uiTarget.ts +50 -0
  259. package/workspace/getRelatedCnsts.ts +7 -0
  260. package/workspace/scanInfo.test.ts +39 -0
  261. package/workspace/scanInfo.ts +55 -6
  262. package/workspace/slicePlanner.ts +1 -1
  263. package/workspace/workspaceLayout.test.ts +5 -1
  264. package/workspace/workspaceLayout.ts +3 -0
@@ -0,0 +1,231 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { createElement } from "react";
4
+ import { renderToStaticMarkup } from "react-dom/server";
5
+ import type { IconType } from "react-icons";
6
+ import { printedInOwnProcess, tempDirs, writeText } from "../test/testHelpers";
7
+ import { ReactIconImports } from "./reactIconImports";
8
+
9
+ const makeTempRoot = tempDirs("akan-react-icons-");
10
+
11
+ const iconOf = (name: string, d: string) =>
12
+ `export function ${name} (props) {\n return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"d":"${d}"},"child":[]}]})(props);\n};\n`;
13
+
14
+ const writeIconPackage = async (root: string) => {
15
+ const pkg = path.join(root, "node_modules", "react-icons");
16
+ await writeText(
17
+ path.join(pkg, "package.json"),
18
+ JSON.stringify({
19
+ name: "react-icons",
20
+ sideEffects: false,
21
+ exports: { "./lib": "./lib/index.mjs", "./bi": "./bi/index.mjs", "./xx": "./xx/index.mjs" },
22
+ }),
23
+ );
24
+ await writeText(
25
+ path.join(pkg, "lib", "index.mjs"),
26
+ "export const GenIcon = (data) => (props) => ({ data, props });\n",
27
+ );
28
+ const bi = ["alpha", "beta", "gamma", "delta"].map((d) => iconOf(`Bi${d[0]?.toUpperCase()}${d.slice(1)}`, d));
29
+ await writeText(
30
+ path.join(pkg, "bi", "index.mjs"),
31
+ `// THIS FILE IS AUTO GENERATED\nimport { GenIcon } from '../lib/index.mjs';\n${bi.join("")}`,
32
+ );
33
+ await writeText(
34
+ path.join(pkg, "xx", "index.mjs"),
35
+ `import { GenIcon } from '../lib/index.mjs';\nconst shared = 1;\n${iconOf("XxAlpha", "x")}`,
36
+ );
37
+ };
38
+
39
+ const importOf = (names: string[], name: string) =>
40
+ `import { ${names.join(", ")} } from "react-icons/bi";\nexport const ${name} = [${names.join(", ")}];\n`;
41
+
42
+ const setUp = async () => {
43
+ const root = await makeTempRoot();
44
+ await writeIconPackage(root);
45
+ const app = path.join(root, "app");
46
+ const files = {
47
+ page: path.join(app, "page.tsx"),
48
+ other: path.join(app, "other.tsx"),
49
+ lib: path.join(root, "libs", "ui", "Card.tsx"),
50
+ };
51
+ await writeText(files.page, importOf(["BiAlpha", "BiBeta"], "page"));
52
+ await writeText(files.other, importOf(["BiAlpha"], "other"));
53
+ await writeText(files.lib, importOf(["BiBeta", "BiGamma"], "card"));
54
+ return { icons: new ReactIconImports(path.join(root, "out"), app, [path.join(root, "libs")]), ...files };
55
+ };
56
+
57
+ const drawnBy = async (file: string | null) => {
58
+ const text = await Bun.file(file ?? "").text();
59
+ return ["alpha", "beta", "gamma", "delta"].filter((d) => text.includes(`"d":"${d}"`));
60
+ };
61
+
62
+ describe("ReactIconImports", () => {
63
+ test("puts an icon one file names with that file, one app files share in the app's module, one a library names in the shared module", async () => {
64
+ const { icons, page, other, lib } = await setUp();
65
+ const alpha = await icons.moduleOf("react-icons/bi", "BiAlpha", page);
66
+ const beta = await icons.moduleOf("react-icons/bi", "BiBeta", page);
67
+ const gamma = await icons.moduleOf("react-icons/bi", "BiGamma", lib);
68
+ expect(await drawnBy(alpha)).toEqual(["alpha"]);
69
+ expect(await drawnBy(beta)).toEqual(["beta"]);
70
+ expect(await drawnBy(gamma)).toEqual(["gamma"]);
71
+ expect(await icons.moduleOf("react-icons/bi", "BiAlpha", other)).toBe(alpha);
72
+ expect(await icons.moduleOf("react-icons/bi", "BiBeta", lib)).toBe(beta);
73
+ expect(new Set([alpha, beta, gamma]).size).toBe(3);
74
+ const source = 'import { BiAlpha, BiBeta as Beta } from "react-icons/bi";\nexport const list = [BiAlpha, Beta];\n';
75
+ expect(await icons.rewrite(source, page)).toBe(
76
+ `import { BiAlpha } from ${JSON.stringify(alpha)}; import { BiBeta as Beta } from ${JSON.stringify(beta)};\nexport const list = [BiAlpha, Beta];\n`,
77
+ );
78
+ const cut = await import(alpha ?? "");
79
+ expect(cut.BiAlpha({ size: 3 })).toEqual({ data: expect.objectContaining({ tag: "svg" }), props: { size: 3 } });
80
+ });
81
+
82
+ test("gives a file the census never read the module its icon already lives in, and an icon no file names one of its own", async () => {
83
+ const { icons, page } = await setUp();
84
+ const unread = path.join(path.dirname(page), "..", "elsewhere", "late.tsx");
85
+ expect(await icons.moduleOf("react-icons/bi", "BiAlpha", unread)).toBe(
86
+ await icons.moduleOf("react-icons/bi", "BiAlpha", page),
87
+ );
88
+ const delta = await icons.moduleOf("react-icons/bi", "BiDelta", unread);
89
+ expect(await drawnBy(delta)).toEqual(["delta"]);
90
+ expect(await icons.moduleOf("react-icons/bi", "BiDelta", page)).toBe(delta);
91
+ });
92
+
93
+ test("keeps every line where it was, and names it cannot cut on the set", async () => {
94
+ const { icons, page } = await setUp();
95
+ const source = [
96
+ "import {",
97
+ " BiAlpha,",
98
+ " BiMissing,",
99
+ " type BiType,",
100
+ '} from "react-icons/bi";',
101
+ "export const list = [BiAlpha, BiMissing];",
102
+ ].join("\n");
103
+ const alpha = await icons.moduleOf("react-icons/bi", "BiAlpha", page);
104
+ const rewritten = await icons.rewrite(source, page);
105
+ expect(rewritten).toBe(
106
+ `import { BiMissing, type BiType } from "react-icons/bi"; import { BiAlpha } from ${JSON.stringify(alpha)};\n\n\n\n\nexport const list = [BiAlpha, BiMissing];`,
107
+ );
108
+ expect(rewritten?.split("\n")).toHaveLength(source.split("\n").length);
109
+ });
110
+
111
+ test("leaves a namespace, default, type-only or re-export import, and a module that is no set, as written", async () => {
112
+ const { icons, page } = await setUp();
113
+ const source = [
114
+ 'import * as Bi from "react-icons/bi";',
115
+ 'import BiDefault from "react-icons/bi";',
116
+ 'import type { BiAlpha as AlphaType } from "react-icons/bi";',
117
+ 'export { BiBeta } from "react-icons/bi";',
118
+ 'import { GenIcon } from "react-icons/lib";',
119
+ 'import { XxAlpha } from "react-icons/xx";',
120
+ 'import { BiGamma } from "react-icons/none";',
121
+ "const text = 'import { BiAlpha } from \"react-icons/bi\"';",
122
+ ].join("\n");
123
+ expect(await icons.rewrite(source, page)).toBeNull();
124
+ expect(await icons.moduleOf("react-icons/xx", "XxAlpha", page)).toBeNull();
125
+ expect(await icons.moduleOf("react-icons/bi", "BiMissing", page)).toBeNull();
126
+ });
127
+
128
+ test("hands the rewritten source to the next transform, and keeps it when that one has nothing to change", async () => {
129
+ const { icons, lib } = await setUp();
130
+ const source = 'import { BiGamma } from "react-icons/bi";\n';
131
+ const seen: string[] = [];
132
+ const rewritten = await icons.pipe((code) => {
133
+ seen.push(code);
134
+ return null;
135
+ })(source, { path: lib });
136
+ expect(seen).toEqual([rewritten ?? ""]);
137
+ const gamma = await icons.moduleOf("react-icons/bi", "BiGamma", lib);
138
+ expect(rewritten).toBe(`import { BiGamma } from ${JSON.stringify(gamma)};\n`);
139
+ expect(await icons.pipe((code) => `${code}// next`)("export {};\n", { path: lib })).toBe("export {};\n// next");
140
+ });
141
+
142
+ test("cuts icons of the installed package that differ only in case into two files, each drawing as the set does", async () => {
143
+ const root = await makeTempRoot();
144
+ const icons = new ReactIconImports(root);
145
+ const importer = path.join(import.meta.dir, "page.tsx");
146
+ const names = ["ImPagebreak", "ImPageBreak"];
147
+ const files = await Promise.all(names.map((name) => icons.moduleOf("react-icons/im", name, importer)));
148
+ expect(new Set(files.map((file) => file?.toLowerCase())).size).toBe(2);
149
+ const set = (await import("react-icons/im")) as unknown as Record<string, IconType>;
150
+ for (const [idx, name] of names.entries()) {
151
+ const one = (await import(files[idx] ?? ""))[name] as IconType;
152
+ const props = { size: 20, className: "icon", title: name };
153
+ expect(renderToStaticMarkup(createElement(one, props))).toBe(
154
+ renderToStaticMarkup(createElement(set[name] as IconType, props)),
155
+ );
156
+ }
157
+ });
158
+
159
+ test("bundles each icon once into a route whose many files all name it, and never an icon the whole set's chunk lacked", async () => {
160
+ const root = await makeTempRoot();
161
+ await writeIconPackage(root);
162
+ const app = path.join(root, "app");
163
+ const many = ["f1", "f2", "f3", "f4", "f5", "f6"];
164
+ for (const name of many)
165
+ await writeText(
166
+ path.join(app, `${name}.ts`),
167
+ importOf(name === "f1" ? ["BiAlpha", "BiBeta", "BiGamma"] : ["BiAlpha", "BiBeta"], name),
168
+ );
169
+ await writeText(path.join(app, "g.ts"), importOf(["BiDelta"], "g"));
170
+ await writeText(path.join(root, "libs", "card.ts"), importOf(["BiBeta"], "card"));
171
+ await writeText(
172
+ path.join(app, "one.ts"),
173
+ `${many.map((name) => `import { ${name} } from "./${name}";`).join("\n")}\nexport const one = [${many.join(", ")}];\n`,
174
+ );
175
+ await writeText(
176
+ path.join(app, "two.ts"),
177
+ 'import { g } from "./g";\nimport { card } from "../libs/card";\nexport const two = [g, card];\n',
178
+ );
179
+ const dir = JSON.stringify(import.meta.dir);
180
+ const loaded = await printedInOwnProcess(
181
+ `
182
+ const path = await import("node:path");
183
+ const fs = await import("node:fs");
184
+ const { ReactIconImports } = await import(path.join(${dir}, "reactIconImports.ts"));
185
+ const root = ${JSON.stringify(root)};
186
+ const closureOf = (outdir, file, seen = new Set()) => {
187
+ if (seen.has(file)) return "";
188
+ seen.add(file);
189
+ const text = fs.readFileSync(path.join(outdir, file), "utf8");
190
+ const chunks = [...text.matchAll(/(?:from|import)\\s*["']\\.\\/([^"']+)["']/g)].map((match) => match[1]);
191
+ return [text, ...chunks.map((chunk) => closureOf(outdir, chunk, seen))].join("\\n");
192
+ };
193
+ const build = async (cut) => {
194
+ const icons = new ReactIconImports(path.join(root, "generated"), path.join(root, "app"), [path.join(root, "libs")]);
195
+ const outdir = path.join(root, cut ? "cut" : "whole");
196
+ const rewrite = {
197
+ name: "rewrite",
198
+ setup: (bundle) =>
199
+ bundle.onLoad({ filter: /[\\\\/](?:app|libs)[\\\\/]/ }, async (args) => {
200
+ const source = await Bun.file(args.path).text();
201
+ return { contents: (await icons.rewrite(source, args.path)) ?? source, loader: "ts" };
202
+ }),
203
+ };
204
+ const result = await Bun.build({
205
+ entrypoints: ["one", "two"].map((name) => path.join(root, "app", name + ".ts")),
206
+ outdir,
207
+ splitting: true,
208
+ format: "esm",
209
+ target: "browser",
210
+ plugins: cut ? [icons.plugin, rewrite] : [],
211
+ });
212
+ if (!result.success) throw new Error(result.logs.join("\\n"));
213
+ const drawn = (text) =>
214
+ Object.fromEntries(
215
+ ["alpha", "beta", "gamma", "delta"]
216
+ .map((d) => [d, text.split('"' + d + '"').length - 1])
217
+ .filter(([, count]) => count > 0),
218
+ );
219
+ return Object.fromEntries(["one", "two"].map((name) => [name, drawn(closureOf(outdir, name + ".js"))]));
220
+ };
221
+ console.log(JSON.stringify({ whole: await build(false), cut: await build(true) }));
222
+ `,
223
+ root,
224
+ );
225
+ const everyIcon = { alpha: 1, beta: 1, gamma: 1, delta: 1 };
226
+ expect(loaded).toEqual({
227
+ whole: { one: everyIcon, two: everyIcon },
228
+ cut: { one: { alpha: 1, beta: 1, gamma: 1 }, two: { beta: 1, delta: 1 } },
229
+ });
230
+ });
231
+ });
@@ -0,0 +1,325 @@
1
+ import fs from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { BunPlugin } from "bun";
5
+ import ts from "typescript";
6
+ import type { App } from "../commandDecorators";
7
+ import type { NamedItem } from "./moduleSyntax";
8
+
9
+ type Pipe = (source: string, args: { path: string }) => string | Promise<string | null> | null;
10
+ type Census = Map<string, Map<string, Set<string>>>;
11
+
12
+ interface IconSet {
13
+ file: string;
14
+ text: string;
15
+ spans: Map<string, [number, number]>;
16
+ outDir: string;
17
+ lib: string;
18
+ }
19
+
20
+ interface SetImport {
21
+ start: number;
22
+ end: number;
23
+ specifier: string;
24
+ named: NamedItem[];
25
+ }
26
+
27
+ //* An icon lives in one module only, so a route downloads it once and never more of a set than the set's own module.
28
+ //? Not one module per importer: an icon n files name was downloaded n times. Not one per set of naming files, nor
29
+ //? per icon: the sub-kilobyte chunks that made were served unbrotlied and outweighed the bytes saved.
30
+ export class ReactIconImports {
31
+ static readonly #specifier = /^react-icons\/[\w-]+$/;
32
+ //? The package generates every set as this one import followed by one `export function` per icon.
33
+ static readonly #header = "import { GenIcon } from '../lib/index.mjs';";
34
+ static readonly #iconStart = /^export function ([A-Za-z_$][\w$]*) \(props\) \{$/gm;
35
+ static readonly #iconBody = /^export function [\w$]+ \(props\) \{\n {2}return GenIcon\(\{.*\}\)\(props\);\n\};\n*$/;
36
+ static readonly #source = /\.(?:tsx?|jsx?|mjs)$/;
37
+ readonly #outRoot: string;
38
+ readonly #appDir: string | null;
39
+ readonly #roots: string[];
40
+ #census: Promise<Census> | null = null;
41
+ readonly #setFiles = new Map<string, string | null>();
42
+ readonly #sets = new Map<string, Promise<IconSet | null>>();
43
+ readonly #groups = new Map<string, Map<string, string[]>>();
44
+ readonly #files = new Map<string, Promise<string | null>>();
45
+ readonly #contents = new Map<string, string>();
46
+
47
+ constructor(outRoot: string, appDir: string | null = null, sharedDirs: string[] = []) {
48
+ this.#outRoot = outRoot;
49
+ this.#appDir = appDir === null ? null : ReactIconImports.#realPathOf(appDir);
50
+ this.#roots = [...(appDir === null ? [] : [appDir]), ...sharedDirs];
51
+ }
52
+
53
+ static forApp(app: App): ReactIconImports {
54
+ const { workspaceRoot } = app.workspace;
55
+ return new ReactIconImports(path.join(app.cwdPath, ".akan", "generated", "react-icons"), app.cwdPath, [
56
+ path.join(workspaceRoot, "libs"),
57
+ ReactIconImports.#packageDirOf("akanjs", workspaceRoot),
58
+ ]);
59
+ }
60
+
61
+ static #packageDirOf(name: string, from: string): string {
62
+ try {
63
+ return path.dirname(Bun.resolveSync(`${name}/package.json`, from));
64
+ } catch {
65
+ return path.join(from, "node_modules", name);
66
+ }
67
+ }
68
+
69
+ //? Bun's resolver caches a folder's listing, so an icon file written later in the same build cannot be resolved.
70
+ get plugin(): BunPlugin {
71
+ const filter = new RegExp(`^${this.#outRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\\\/]`);
72
+ return {
73
+ name: "react-icon-imports",
74
+ setup: (build) => {
75
+ build.onResolve({ filter }, (args) => ({ path: args.path }));
76
+ build.onLoad({ filter }, (args) => {
77
+ const contents = this.#contents.get(args.path);
78
+ return contents === undefined ? undefined : { contents, loader: "js" };
79
+ });
80
+ },
81
+ };
82
+ }
83
+
84
+ pipe(next?: Pipe): Pipe {
85
+ return async (source, args) => {
86
+ const rewritten = await this.rewrite(source, args.path);
87
+ const piped = next ? await next(rewritten ?? source, args) : null;
88
+ return piped ?? rewritten;
89
+ };
90
+ }
91
+
92
+ //? Every replacement keeps the statement's line count, so the importer's source map still lines up.
93
+ async rewrite(source: string, importer: string): Promise<string | null> {
94
+ if (!source.includes("react-icons/")) return null;
95
+ let out = source;
96
+ for (const statement of ReactIconImports.#importsOf(source, importer).reverse()) {
97
+ const set = await this.#setOf(statement.specifier, importer);
98
+ if (!set) continue;
99
+ const kept: NamedItem[] = [];
100
+ const moved = new Map<string, NamedItem[]>();
101
+ for (const item of statement.named) {
102
+ const file = item.isType ? null : await this.#moduleOf(set, item.imported);
103
+ if (file) moved.set(file, [...(moved.get(file) ?? []), item]);
104
+ else kept.push(item);
105
+ }
106
+ if (moved.size === 0) continue;
107
+ const lines = [...moved].map(
108
+ ([file, items]) => `import { ${items.map(ReactIconImports.#named).join(", ")} } from ${JSON.stringify(file)};`,
109
+ );
110
+ if (kept.length > 0) lines.unshift(ReactIconImports.#keptImport(kept, statement.specifier));
111
+ const newlines = source.slice(statement.start, statement.end).split("\n").length - 1;
112
+ out = `${out.slice(0, statement.start)}${lines.join(" ")}${"\n".repeat(newlines)}${out.slice(statement.end)}`;
113
+ }
114
+ return out === source ? null : out;
115
+ }
116
+
117
+ async moduleOf(specifier: string, name: string, importer: string): Promise<string | null> {
118
+ const set = await this.#setOf(specifier, importer);
119
+ return set ? await this.#moduleOf(set, name) : null;
120
+ }
121
+
122
+ async #moduleOf(set: IconSet, name: string): Promise<string | null> {
123
+ if (!ReactIconImports.#bodyOf(set, name)) return null;
124
+ const census = await this.#censusOf();
125
+ const namers = census.get(set.file)?.get(name);
126
+ if (!namers) return await this.#fileOf(set, `\0${name}`, [name]);
127
+ const key = this.#keyOf(namers);
128
+ return await this.#fileOf(set, key, this.#groupsOf(set, census).get(key) ?? [name]);
129
+ }
130
+
131
+ #groupsOf(set: IconSet, census: Census): Map<string, string[]> {
132
+ let groups = this.#groups.get(set.file);
133
+ if (!groups) {
134
+ groups = new Map();
135
+ for (const [name, namers] of census.get(set.file) ?? []) {
136
+ if (!ReactIconImports.#bodyOf(set, name)) continue;
137
+ const key = this.#keyOf(namers);
138
+ groups.set(key, [...(groups.get(key) ?? []), name]);
139
+ }
140
+ this.#groups.set(set.file, groups);
141
+ }
142
+ return groups;
143
+ }
144
+
145
+ #keyOf(namers: Set<string>): string {
146
+ if (namers.size === 1) return [...namers].join("");
147
+ const own = this.#appDir === null ? null : `${this.#appDir}${path.sep}`;
148
+ return own !== null && [...namers].every((file) => file.startsWith(own)) ? "\0app" : "\0shared";
149
+ }
150
+
151
+ #censusOf(): Promise<Census> {
152
+ this.#census ??= this.#readCensus();
153
+ return this.#census;
154
+ }
155
+
156
+ async #readCensus(): Promise<Census> {
157
+ const census: Census = new Map();
158
+ const roots = [...new Set(this.#roots.flatMap((root) => ReactIconImports.#realPathOrNot(root) ?? []))];
159
+ const files = (await Promise.all(roots.map((root) => ReactIconImports.#sourcesUnder(root)))).flat();
160
+ await Promise.all(
161
+ [...new Set(files)].map(async (file) => {
162
+ const source = await Bun.file(file)
163
+ .text()
164
+ .catch(() => "");
165
+ if (!source.includes("react-icons/")) return;
166
+ for (const statement of ReactIconImports.#importsOf(source, file)) {
167
+ const setFile = this.#setFileOf(statement.specifier, file);
168
+ if (!setFile) continue;
169
+ const names = census.get(setFile) ?? new Map<string, Set<string>>();
170
+ census.set(setFile, names);
171
+ for (const item of statement.named)
172
+ if (!item.isType) names.set(item.imported, (names.get(item.imported) ?? new Set()).add(file));
173
+ }
174
+ }),
175
+ );
176
+ return census;
177
+ }
178
+
179
+ static async #sourcesUnder(dir: string): Promise<string[]> {
180
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
181
+ const nested = await Promise.all(
182
+ entries.map((entry) => {
183
+ const full = path.join(dir, entry.name);
184
+ if (entry.isDirectory())
185
+ return entry.name === "node_modules" || entry.name.startsWith(".")
186
+ ? []
187
+ : ReactIconImports.#sourcesUnder(full);
188
+ return entry.isFile() && ReactIconImports.#source.test(entry.name) && !entry.name.endsWith(".d.ts")
189
+ ? [full]
190
+ : [];
191
+ }),
192
+ );
193
+ return nested.flat();
194
+ }
195
+
196
+ static #realPathOrNot(file: string): string | null {
197
+ try {
198
+ return fs.realpathSync(file);
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
204
+ static #realPathOf(file: string): string {
205
+ return ReactIconImports.#realPathOrNot(file) ?? file;
206
+ }
207
+
208
+ static #importsOf(source: string, importer: string): SetImport[] {
209
+ const kind = importer.endsWith(".tsx")
210
+ ? ts.ScriptKind.TSX
211
+ : importer.endsWith(".ts")
212
+ ? ts.ScriptKind.TS
213
+ : ts.ScriptKind.JSX;
214
+ const sourceFile = ts.createSourceFile(importer, source, ts.ScriptTarget.Latest, false, kind);
215
+ const found: SetImport[] = [];
216
+ for (const statement of sourceFile.statements) {
217
+ if (!ts.isImportDeclaration(statement) || statement.attributes) continue;
218
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
219
+ const specifier = statement.moduleSpecifier.text;
220
+ const clause = statement.importClause;
221
+ if (!ReactIconImports.#specifier.test(specifier) || !clause || clause.name) continue;
222
+ if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword) continue;
223
+ const bindings = clause.namedBindings;
224
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
225
+ if (bindings.elements.some((element) => element.propertyName && !ts.isIdentifier(element.propertyName))) continue;
226
+ found.push({
227
+ start: statement.getStart(sourceFile),
228
+ end: statement.end,
229
+ specifier,
230
+ named: bindings.elements.map((element) => ({
231
+ imported: (element.propertyName ?? element.name).text,
232
+ local: element.name.text,
233
+ isType: element.isTypeOnly,
234
+ })),
235
+ });
236
+ }
237
+ return found;
238
+ }
239
+
240
+ static #named(item: NamedItem): string {
241
+ return item.imported === item.local ? item.imported : `${item.imported} as ${item.local}`;
242
+ }
243
+
244
+ static #keptImport(kept: NamedItem[], specifier: string): string {
245
+ const typeOnly = kept.every((item) => item.isType);
246
+ const names = kept.map((item) => `${item.isType && !typeOnly ? "type " : ""}${ReactIconImports.#named(item)}`);
247
+ return `import ${typeOnly ? "type " : ""}{ ${names.join(", ")} } from ${JSON.stringify(specifier)};`;
248
+ }
249
+
250
+ #setFileOf(specifier: string, importer: string): string | null {
251
+ const dir = path.dirname(importer);
252
+ const key = `${dir}\0${specifier}`;
253
+ if (!this.#setFiles.has(key)) {
254
+ let file: string | null;
255
+ try {
256
+ file = path.join(fs.realpathSync(path.dirname(Bun.resolveSync(specifier, dir))), "index.mjs");
257
+ } catch {
258
+ file = null;
259
+ }
260
+ this.#setFiles.set(key, file);
261
+ }
262
+ return this.#setFiles.get(key) ?? null;
263
+ }
264
+
265
+ async #setOf(specifier: string, importer: string): Promise<IconSet | null> {
266
+ const setFile = this.#setFileOf(specifier, importer);
267
+ if (!setFile) return null;
268
+ let set = this.#sets.get(setFile);
269
+ if (!set) {
270
+ set = this.#readSet(setFile);
271
+ this.#sets.set(setFile, set);
272
+ }
273
+ return await set;
274
+ }
275
+
276
+ async #readSet(setFile: string): Promise<IconSet | null> {
277
+ const file = Bun.file(setFile);
278
+ if (!(await file.exists())) return null;
279
+ const text = await file.text();
280
+ const starts = [...text.matchAll(ReactIconImports.#iconStart)];
281
+ const first = starts[0]?.index;
282
+ if (first === undefined) return null;
283
+ const preamble = text.slice(0, first).replace(ReactIconImports.#header, "");
284
+ if (preamble.length === first || preamble.replace(/\/\/[^\n]*/g, "").trim()) return null;
285
+ const spans = new Map<string, [number, number]>();
286
+ starts.forEach((match, idx) => {
287
+ if (match[1]) spans.set(match[1], [match.index, starts[idx + 1]?.index ?? text.length]);
288
+ });
289
+ const setDir = path.dirname(setFile);
290
+ const lib = path.join(path.dirname(setDir), "lib", "index.mjs");
291
+ if (!fs.existsSync(lib)) return null;
292
+ const outDir = path.join(this.#outRoot, Bun.hash(path.dirname(setDir)).toString(36), path.basename(setDir));
293
+ return { file: setFile, text, spans, outDir, lib: fs.realpathSync(lib) };
294
+ }
295
+
296
+ static #bodyOf(set: IconSet, name: string): string | null {
297
+ const span = set.spans.get(name);
298
+ const body = span ? set.text.slice(...span) : null;
299
+ return body && ReactIconImports.#iconBody.test(body) ? body.trimEnd() : null;
300
+ }
301
+
302
+ async #fileOf(set: IconSet, key: string, names: string[]): Promise<string | null> {
303
+ const unique = [...new Set(names)].sort();
304
+ const file = path.join(set.outDir, `${Bun.hash(`${key}\0\0${unique.join(",")}`).toString(36)}.mjs`);
305
+ let written = this.#files.get(file);
306
+ if (!written) {
307
+ const bodies = unique.map((name) => ReactIconImports.#bodyOf(set, name) ?? "");
308
+ const contents = `import { GenIcon } from ${JSON.stringify(set.lib)};\n${bodies.join("\n")}\n`;
309
+ written = ReactIconImports.#write(file, contents);
310
+ this.#files.set(file, written);
311
+ if (await written) this.#contents.set(file, contents);
312
+ }
313
+ return await written;
314
+ }
315
+
316
+ static async #write(file: string, contents: string): Promise<string | null> {
317
+ try {
318
+ const existing = Bun.file(file);
319
+ if (!(await existing.exists()) || (await existing.text()) !== contents) await Bun.write(file, contents);
320
+ return file;
321
+ } catch {
322
+ return null;
323
+ }
324
+ }
325
+ }
@@ -0,0 +1,122 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ import type { RuntimeConstantGraph } from "../quality/runtimeConstantGraph";
4
+ import { RuntimeImports } from "../quality/runtimeImports";
5
+ import type { RuntimeOwner } from "../quality/runtimeNameTable";
6
+ import type { RuntimeConstantName, RuntimeConstantUse } from "../quality/runtimeUse";
7
+
8
+ export interface ConstantEdit {
9
+ start: number;
10
+ end: number;
11
+ text: string;
12
+ }
13
+
14
+ export interface ConstantRewrite {
15
+ edits: ConstantEdit[];
16
+ imports: string[];
17
+ pieces: string[];
18
+ }
19
+
20
+ const scopeOf = (fileName: string) => fileName.match(/^((?:apps|libs)\/[^/]+)\//)?.[1] ?? null;
21
+
22
+ export class RouteConstants {
23
+ readonly #graph: RuntimeConstantGraph;
24
+ readonly #pieces: ReadonlySet<string>;
25
+
26
+ constructor(graph: RuntimeConstantGraph, pieces: ReadonlySet<string>) {
27
+ this.#graph = graph;
28
+ this.#pieces = pieces;
29
+ }
30
+
31
+ get graph() {
32
+ return this.#graph;
33
+ }
34
+
35
+ static pieceOf({ owner }: { owner: RuntimeOwner }) {
36
+ return `${owner.scope}/lib/__client/${owner.module}.cnst`;
37
+ }
38
+
39
+ static isConstantImport(statement: ts.ImportDeclaration, fileName: string) {
40
+ return ts.isStringLiteral(statement.moduleSpecifier)
41
+ ? !!RuntimeImports.constantTargetOf(statement.moduleSpecifier.text, fileName)
42
+ : false;
43
+ }
44
+
45
+ //? A constant file never loads a piece of its own scope: that piece imports the file back.
46
+ rewrite(
47
+ sourceFile: ts.SourceFile,
48
+ fileName: string,
49
+ use: RuntimeConstantUse,
50
+ { constantFile = false }: { constantFile?: boolean } = {},
51
+ ): ConstantRewrite | null {
52
+ if (use.problems.length) return null;
53
+ const named = use.reads.flatMap((read): RuntimeConstantName[] => (read.kind === "member" ? [read] : read.keys));
54
+ if (constantFile && named.some(({ owner }) => owner.scope === scopeOf(fileName))) return null;
55
+ const registered = constantFile
56
+ ? named.map(({ owner }) => owner)
57
+ : [...use.imports, ...named.map(({ owner }) => owner)];
58
+ if (!registered.length) return { edits: [], imports: [], pieces: [] };
59
+ const pieces = [
60
+ ...new Set(
61
+ (constantFile ? registered : this.#graph.closureOf(registered)).map((owner) =>
62
+ RouteConstants.pieceOf({ owner }),
63
+ ),
64
+ ),
65
+ ];
66
+ const needed = [...pieces, ...named.filter(({ model }) => model).map((read) => RouteConstants.pieceOf(read))];
67
+ if (needed.some((piece) => !this.#pieces.has(piece))) return null;
68
+ const aliases = new Map<string, { alias: string; line: string }>();
69
+ const aliasOf = (read: RuntimeConstantName) => {
70
+ const piece = RouteConstants.pieceOf(read);
71
+ const [key, specifier] = read.model
72
+ ? [`${piece}#${read.name}`, `@${piece}`]
73
+ : [`${read.file}#${read.name}`, RouteConstants.#relative(fileName, read.file)];
74
+ const known = aliases.get(key);
75
+ if (known) return known.alias;
76
+ const alias = `__akanCnst${aliases.size}`;
77
+ aliases.set(key, { alias, line: `import { ${read.name} as ${alias} } from ${JSON.stringify(specifier)};` });
78
+ return alias;
79
+ };
80
+ const edits = use.reads.map((read): ConstantEdit => {
81
+ if (read.kind === "member") return { start: read.start, end: read.end, text: aliasOf(read) };
82
+ const fields = read.keys.map((key) => `${JSON.stringify(key.key)}: ${aliasOf(key)}`);
83
+ return { start: read.start, end: read.end, text: `{ ${fields.join(", ")} }` };
84
+ });
85
+ for (const statement of sourceFile.statements)
86
+ if (ts.isImportDeclaration(statement) && RouteConstants.isConstantImport(statement, fileName))
87
+ edits.push(...RouteConstants.typedEdits(statement, sourceFile, (element) => element === "cnst"));
88
+ return { edits, imports: [...aliases.values()].map(({ line }) => line), pieces };
89
+ }
90
+
91
+ static #relative(fileName: string, file: string) {
92
+ const relative = path.posix.relative(path.posix.dirname(fileName), file);
93
+ return relative.startsWith(".") ? relative : `./${relative}`;
94
+ }
95
+
96
+ //? Bun drops an import left only to types even under `verbatimModuleSyntax`; `import type` keeps that off the bundler.
97
+ static typedEdits(
98
+ statement: ts.ImportDeclaration,
99
+ sourceFile: ts.SourceFile,
100
+ isConstant: (imported: string) => boolean,
101
+ ): ConstantEdit[] {
102
+ const clause = statement.importClause;
103
+ if (!clause || clause.isTypeOnly) return [];
104
+ const bindings = clause.namedBindings;
105
+ const at = statement.getStart(sourceFile) + "import".length;
106
+ if (!bindings || !ts.isNamedImports(bindings)) return clause.name ? [] : [{ start: at, end: at, text: " type" }];
107
+ const constant = (element: ts.ImportSpecifier) =>
108
+ !element.isTypeOnly && isConstant((element.propertyName ?? element.name).text);
109
+ const targets = bindings.elements.filter(constant);
110
+ if (!targets.length) return [];
111
+ if (clause.name || bindings.elements.some((element) => !element.isTypeOnly && !constant(element)))
112
+ return targets.map((element) => {
113
+ const start = element.getStart(sourceFile);
114
+ return { start, end: start, text: "type " };
115
+ });
116
+ const names = bindings.elements.map((element) => element.getText(sourceFile).replace(/^type\s+/, ""));
117
+ const [start, end] = [statement.getStart(sourceFile), statement.end];
118
+ const newlines = sourceFile.text.slice(start, end).split("\n").length - 1;
119
+ const specifier = statement.moduleSpecifier.getText(sourceFile);
120
+ return [{ start, end, text: `import type { ${names.join(", ")} } from ${specifier};${"\n".repeat(newlines)}` }];
121
+ }
122
+ }