@akanjs/devkit 3.3.0-rc.7 → 3.3.0-rc.71

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 (360) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +10 -3
  3. package/README.md +10 -4
  4. package/akanApp/akanApp.host.test.ts +4 -2
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +358 -21
  13. package/akanConfig/akanConfig.ts +113 -272
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +250 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/nativeKeys.ts +52 -0
  23. package/akanConfig/types.ts +4 -0
  24. package/app/appBin.test.ts +63 -0
  25. package/app/appBin.ts +50 -0
  26. package/app/applicationBuildReporter.test.ts +51 -1
  27. package/app/applicationBuildReporter.ts +6 -1
  28. package/app/applicationBuildRunner.test.ts +427 -5
  29. package/app/applicationBuildRunner.ts +232 -37
  30. package/app/clientServerBoundary.test.ts +115 -0
  31. package/app/clientServerBoundary.ts +89 -0
  32. package/app/dictionarySizes.test.ts +40 -0
  33. package/app/dictionarySizes.ts +95 -0
  34. package/app/routeFilesReport.test.ts +59 -0
  35. package/app/routeFilesReport.ts +46 -0
  36. package/app/routeJsBudget.ts +18 -4
  37. package/artifact/implicitRootLayout.test.ts +19 -0
  38. package/artifact/implicitRootLayout.ts +16 -2
  39. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  40. package/artifact/storeBootstrap.test.ts +28 -0
  41. package/artifact/storeBootstrap.ts +64 -8
  42. package/biome.base.json +7 -5
  43. package/codeAgent/index.ts +1 -34
  44. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  45. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  46. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  47. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  48. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  49. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  50. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  51. package/codeAgent/skills/akan-page/SKILL.md +65 -30
  52. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  53. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  54. package/codeAgent/skills/akan-service/SKILL.md +21 -20
  55. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  56. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  57. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  58. package/commandDecorators/command.ts +28 -12
  59. package/commandDecorators/commandBuilder.ts +8 -1
  60. package/commandDecorators/commandDecorators.test.ts +70 -3
  61. package/commandDecorators/helpFormatter.ts +14 -12
  62. package/context/akanContext.ts +2 -0
  63. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  64. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  65. package/docs/apiReference.test.ts +25 -0
  66. package/docs/apiReference.ts +38 -5
  67. package/docs/declarationReader.ts +30 -0
  68. package/executors/appExecutor.ts +26 -12
  69. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  70. package/executors/clientRuntimeKeys.fixture.json +393 -0
  71. package/executors/clientRuntimeKeys.test.ts +1690 -0
  72. package/executors/executor.ts +14 -6
  73. package/executors/executors.test.ts +155 -1
  74. package/executors/pkgExecutor.ts +2 -1
  75. package/executors/sysExecutor.ts +112 -8
  76. package/executors/workspaceExecutor.ts +7 -4
  77. package/frontendBuild/allRoutesBuilder.ts +99 -7
  78. package/frontendBuild/autoImportSync.ts +3 -2
  79. package/frontendBuild/buildRouteClient.test.ts +686 -13
  80. package/frontendBuild/clientBuildTypes.ts +26 -0
  81. package/frontendBuild/clientEntriesBundler.ts +49 -1
  82. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  83. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  84. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  85. package/frontendBuild/clientEntryGroups.ts +61 -0
  86. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  87. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  88. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  89. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  90. package/frontendBuild/csrDevPatcher.ts +37 -11
  91. package/frontendBuild/csrDevTypes.ts +9 -0
  92. package/frontendBuild/devBarrelImports.test.ts +154 -0
  93. package/frontendBuild/devBarrelImports.ts +83 -23
  94. package/frontendBuild/devChangePlanner.ts +0 -1
  95. package/frontendBuild/devRegistryBundler.ts +4 -2
  96. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  97. package/frontendBuild/devRouteRuntime.ts +167 -0
  98. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  99. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  100. package/frontendBuild/dictionaryConstants.ts +136 -0
  101. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  102. package/frontendBuild/dictionaryPackState.ts +131 -0
  103. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  104. package/frontendBuild/dictionaryPacking.ts +160 -0
  105. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  106. package/frontendBuild/dictionaryRoutes.ts +227 -0
  107. package/frontendBuild/frontendBuild.test.ts +5 -3
  108. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  109. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  110. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  111. package/frontendBuild/precompressArtifacts.ts +34 -8
  112. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  113. package/frontendBuild/renderedEntries.ts +144 -0
  114. package/frontendBuild/routeClientBuilder.ts +407 -43
  115. package/frontendBuild/routeHandoffs.test.ts +155 -0
  116. package/frontendBuild/routeHandoffs.ts +117 -0
  117. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  118. package/frontendBuild/routeModulePreloads.ts +20 -11
  119. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  120. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  121. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  122. package/frontendBuild/routeRuntimePays.ts +117 -0
  123. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  124. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  125. package/frontendBuild/ssrDevBundler.ts +66 -11
  126. package/frontendBuild/vendorFileImports.test.ts +254 -0
  127. package/frontendBuild/vendorFileImports.ts +163 -0
  128. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  129. package/frontendBuild/vendorNarrowing.ts +38 -2
  130. package/frontendBuild/vendorSpecifiers.ts +2 -0
  131. package/guideline/agentAssets.ts +1 -1
  132. package/incrementalBuilder/buildBatch.proc.ts +35 -9
  133. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  134. package/incrementalBuilder/builderBoot.ts +5 -5
  135. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  136. package/incrementalBuilder/builderLanes.ts +2 -2
  137. package/incrementalBuilder/builderWatch.ts +19 -9
  138. package/incrementalBuilder/csrRegistry.ts +4 -4
  139. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  140. package/incrementalBuilder/incrementalBuilder.proc.ts +38 -10
  141. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  142. package/incrementalBuilder/pendingMetadata.ts +19 -0
  143. package/incrementalBuilder/ssrRegistry.ts +6 -6
  144. package/index.ts +1 -1
  145. package/integration/devResourceProbe.ts +14 -0
  146. package/integration/devStability.integration.test.ts +46 -21
  147. package/integration/renderAdmissionSoak.test.ts +99 -0
  148. package/integration/renderAdmissionSoak.ts +615 -0
  149. package/integration/ssrMemoryProbe.ts +5 -0
  150. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  151. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  152. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  153. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  154. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  155. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  156. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  157. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  158. package/lint/biomeBase.test.ts +50 -3
  159. package/lint/biomeBase.ts +1 -1
  160. package/lint/biomeCheck.test.ts +162 -0
  161. package/lint/biomeCheck.ts +131 -0
  162. package/lint/linter.test.ts +16 -11
  163. package/lint/no-arbitrary-color.grit +5 -0
  164. package/lint/no-conditional-st-hook.grit +5 -1
  165. package/lint/no-daisyui-legacy-class.grit +8 -0
  166. package/lint/no-document-cookie.grit +3 -0
  167. package/lint/no-inline-color.grit +10 -2
  168. package/lint/no-oversized-list-limit.grit +2 -0
  169. package/lint/no-raw-palette-class.grit +7 -0
  170. package/lint/no-unpublished-form-setter.grit +2 -0
  171. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  172. package/lint/no-web-storage.grit +3 -0
  173. package/lint/withheldEnvFile.ts +17 -0
  174. package/mobile/desktopBin.ts +2 -2
  175. package/mobile/desktopServerStage.test.ts +18 -3
  176. package/mobile/desktopServerStage.ts +7 -2
  177. package/mobile/nativeApp.test.ts +13 -5
  178. package/mobile/nativeApp.ts +9 -4
  179. package/mobile/nativeConfig.test.ts +96 -1
  180. package/mobile/nativeConfig.ts +46 -12
  181. package/mobile/nativePublicEnv.ts +1 -1
  182. package/mobile/serverBundleSecrets.ts +43 -0
  183. package/package.json +22 -178
  184. package/packageExports.test.ts +39 -24
  185. package/preview/PreviewView.ts +25 -3
  186. package/quality/dictionaryKeys.test.ts +356 -0
  187. package/quality/dictionaryKeys.ts +488 -0
  188. package/quality/objectImportReport.test.ts +36 -0
  189. package/quality/objectImportReport.ts +105 -0
  190. package/quality/qualityScanner.ts +1 -1
  191. package/quality/routeRuntimeReport.test.ts +91 -0
  192. package/quality/routeRuntimeReport.ts +121 -0
  193. package/quality/runtimeConstantFacts.ts +71 -0
  194. package/quality/runtimeConstantGraph.ts +123 -0
  195. package/quality/runtimeConstantReads.ts +116 -0
  196. package/quality/runtimeImports.test.ts +190 -0
  197. package/quality/runtimeImports.ts +233 -0
  198. package/quality/runtimeKeyNames.ts +46 -0
  199. package/quality/runtimeLexicalScope.ts +132 -0
  200. package/quality/runtimeMarkerReach.test.ts +84 -0
  201. package/quality/runtimeMarkerReach.ts +255 -0
  202. package/quality/runtimeModuleFacts.ts +290 -0
  203. package/quality/runtimeNameTable.test.ts +172 -0
  204. package/quality/runtimeNameTable.ts +477 -0
  205. package/quality/runtimeScopeReport.test.ts +123 -0
  206. package/quality/runtimeScopeReport.ts +167 -0
  207. package/quality/runtimeSliceKey.ts +269 -0
  208. package/quality/runtimeSyntax.ts +133 -0
  209. package/quality/runtimeTable.fixture.ts +189 -0
  210. package/quality/runtimeUse.test.ts +737 -0
  211. package/quality/runtimeUse.ts +696 -0
  212. package/quality/runtimeUseReadable.test.ts +393 -0
  213. package/quality/ssrScanner.test.ts +13 -0
  214. package/quality/ssrScanner.ts +1 -1
  215. package/quality/translatorBindings.ts +187 -0
  216. package/test/fakeTerminal.ts +45 -0
  217. package/test/secretEnvFixture.ts +134 -0
  218. package/test/testHelpers.ts +11 -0
  219. package/transforms/barrelAnalyzer.ts +26 -4
  220. package/transforms/barrelImportsPlugin.ts +121 -32
  221. package/transforms/exportReach.test.ts +162 -0
  222. package/transforms/exportReach.ts +308 -0
  223. package/transforms/frameworkObjects.fixture.tsx +58 -0
  224. package/transforms/frameworkObjects.test.ts +54 -0
  225. package/transforms/modelReference.test.ts +196 -0
  226. package/transforms/modelReference.ts +39 -0
  227. package/transforms/moduleParts.test.ts +225 -0
  228. package/transforms/moduleParts.ts +418 -0
  229. package/transforms/objectImportEdits.ts +150 -0
  230. package/transforms/objectMemberImports.test.ts +633 -0
  231. package/transforms/objectMemberImports.ts +571 -0
  232. package/transforms/objectMemberLookup.ts +150 -0
  233. package/transforms/objectModule.test.ts +307 -0
  234. package/transforms/objectModule.ts +482 -0
  235. package/transforms/objectModuleAnalyzer.ts +104 -0
  236. package/transforms/partImports.test.ts +76 -0
  237. package/transforms/partImports.ts +110 -0
  238. package/transforms/partModules.test.ts +187 -0
  239. package/transforms/partModules.ts +90 -0
  240. package/transforms/partPurity.ts +124 -0
  241. package/transforms/reactIconImports.test.ts +231 -0
  242. package/transforms/reactIconImports.ts +325 -0
  243. package/transforms/routeConstants.ts +122 -0
  244. package/transforms/routeRuntime.test.ts +835 -0
  245. package/transforms/routeRuntime.ts +703 -0
  246. package/transforms/routeRuntimeEdits.ts +92 -0
  247. package/transforms/routeRuntimeGraph.ts +66 -0
  248. package/transforms/routeRuntimePlan.ts +244 -0
  249. package/transforms/secretEnvDeclaration.test.ts +211 -0
  250. package/transforms/secretEnvDeclaration.ts +219 -0
  251. package/transforms/secretEnvFile.test.ts +117 -0
  252. package/transforms/secretEnvFile.ts +113 -0
  253. package/transforms/secretEnvName.test.ts +54 -0
  254. package/transforms/secretEnvName.ts +29 -0
  255. package/transforms/secretEnvSource.test.ts +152 -0
  256. package/transforms/secretEnvSource.ts +197 -0
  257. package/transforms/serverEnvEvaluationError.ts +11 -0
  258. package/transforms/serverEnvPlugin.test.ts +118 -1
  259. package/transforms/serverEnvPlugin.ts +95 -2
  260. package/transforms/serverEnvProfile.test.ts +129 -2
  261. package/transforms/serverEnvProfile.ts +133 -43
  262. package/transforms/serverEnvSecrets.test.ts +268 -0
  263. package/transforms/signalDescriptors.test.ts +280 -0
  264. package/transforms/signalDescriptors.ts +227 -0
  265. package/transforms/thisFreeExports.ts +87 -0
  266. package/transforms/transforms.test.ts +180 -3
  267. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  268. package/tunnel/createTunnel.test.ts +29 -8
  269. package/tunnel/createTunnel.ts +22 -11
  270. package/tunnel/ssh2Module.test.ts +37 -0
  271. package/tunnel/ssh2Module.ts +28 -0
  272. package/tunnel/sshTunnel.ts +4 -2
  273. package/typecheck/projectTypecheck.test.ts +32 -1
  274. package/typecheck/projectTypecheck.ts +3 -3
  275. package/typecheck/typeChecker.test.ts +49 -0
  276. package/typecheck/typeChecker.ts +9 -7
  277. package/typecheck/withheldDiagnostics.ts +41 -0
  278. package/util/devInstallCommand.ts +7 -0
  279. package/util/fileEditor.ts +1 -0
  280. package/util/jsonFormatter.test.ts +13 -9
  281. package/util/selectModel.ts +1 -0
  282. package/workflow/executor.ts +6 -2
  283. package/workflow/index.ts +1 -0
  284. package/workflow/plan.ts +36 -7
  285. package/workflow/types.ts +1 -1
  286. package/workflow/uiTarget.ts +50 -0
  287. package/workspace/envSeed.test.ts +30 -1
  288. package/workspace/envSeed.ts +30 -1
  289. package/workspace/getRelatedCnsts.ts +7 -0
  290. package/workspace/mainCheckout.test.ts +55 -0
  291. package/workspace/mainCheckout.ts +38 -0
  292. package/workspace/scanInfo.test.ts +39 -0
  293. package/workspace/scanInfo.ts +55 -6
  294. package/workspace/slicePlanner.ts +2 -1
  295. package/workspace/workspaceLayout.test.ts +22 -1
  296. package/workspace/workspaceLayout.ts +3 -3
  297. package/CHANGELOG.md +0 -2718
  298. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  299. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  300. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  301. package/codeAgent/agent/CodeAgent.ts +0 -606
  302. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  303. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  304. package/codeAgent/agent/CodeAgentGate.ts +0 -239
  305. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  306. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  307. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  308. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  309. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  310. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  311. package/codeAgent/agent/CodeMailbox.ts +0 -148
  312. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  313. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  314. package/codeAgent/agent/SubagentPool.ts +0 -219
  315. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  316. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  317. package/codeAgent/agent/akanCodeModel.ts +0 -47
  318. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  319. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  320. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  321. package/codeAgent/agent/codeAgent.test.ts +0 -275
  322. package/codeAgent/agent/codeAgentContract.test.ts +0 -643
  323. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  324. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  325. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  326. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  327. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  328. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  329. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  330. package/codeAgent/agent/consoleToStderr.ts +0 -8
  331. package/codeAgent/agent/jsonLines.ts +0 -29
  332. package/codeAgent/agent/stringArg.ts +0 -5
  333. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  334. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  335. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  336. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  337. package/codeAgent/tools/AkanCli.ts +0 -51
  338. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  339. package/codeAgent/tools/AkanEditScope.ts +0 -53
  340. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  341. package/codeAgent/tools/AkanToolPack.ts +0 -86
  342. package/codeAgent/tools/AkanVerifier.ts +0 -30
  343. package/codeAgent/tools/AskToolPack.ts +0 -99
  344. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  345. package/codeAgent/tools/MailToolPack.ts +0 -76
  346. package/codeAgent/tools/McpClient.ts +0 -209
  347. package/codeAgent/tools/McpOAuth.ts +0 -233
  348. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  349. package/codeAgent/tools/McpServerConfig.ts +0 -131
  350. package/codeAgent/tools/McpSignIn.ts +0 -158
  351. package/codeAgent/tools/McpTokenStore.ts +0 -128
  352. package/codeAgent/tools/McpToolPack.ts +0 -206
  353. package/codeAgent/tools/SessionToolPack.ts +0 -91
  354. package/codeAgent/tools/WebToolPack.ts +0 -315
  355. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  356. package/codeAgent/tools/askToolPack.test.ts +0 -116
  357. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  358. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  359. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  360. package/piDependencyPins.test.ts +0 -45
@@ -0,0 +1,225 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { ModuleParts } from "./moduleParts";
3
+
4
+ const self = "/repo/apps/demo/ui/Pair.tsx";
5
+ const from = (id: string) => `"${self}?akan-part=${id}"`;
6
+ const read = (lines: string[]) => {
7
+ const parts = ModuleParts.read(`${lines.join("\n")}\n`, self);
8
+ if (!parts) throw new Error("the file stayed one module");
9
+ return parts;
10
+ };
11
+ const linesOf = (parts: ModuleParts, id: string) => (parts.sourceOf(id, self) ?? "").trimEnd().split("\n");
12
+ const partOf = (parts: ModuleParts, exported: string) => linesOf(parts, parts.partOf(exported) ?? "");
13
+
14
+ describe("ModuleParts", () => {
15
+ test("each export that only builds a value is a part holding the imports it alone reads", () => {
16
+ const parts = read([
17
+ '"use client";',
18
+ 'import { cn } from "./cn";',
19
+ 'import Heavy, { type Props, tune as tuned } from "./Heavy";',
20
+ 'import * as icons from "./icons";',
21
+ "export const A = () => cn(icons.a);",
22
+ "export const B = (props: Props) => [Heavy, tuned, props];",
23
+ ]);
24
+
25
+ expect(parts.ids).toEqual(["p0", "p1"]);
26
+ expect(parts.exports).toEqual(["A", "B"]);
27
+ expect(linesOf(parts, "p0")).toEqual([
28
+ '"use client";',
29
+ 'import { cn } from "./cn";',
30
+ 'import * as icons from "./icons";',
31
+ "export const A = () => cn(icons.a);",
32
+ ]);
33
+ expect(linesOf(parts, "p1")).toEqual([
34
+ '"use client";',
35
+ 'import Heavy, { tune as tuned } from "./Heavy";',
36
+ "export const B = (props: Props) => [Heavy, tuned, props];",
37
+ ]);
38
+ expect(parts.facade(self)).toBe(
39
+ ['"use client";', `export { A } from ${from("p0")};`, `export { B } from ${from("p1")};`, ""].join("\n"),
40
+ );
41
+ expect(parts.sourceOf("p9", self)).toBeNull();
42
+ });
43
+
44
+ test("what the file does when it loads is `rest`, which every part imports before anything else", () => {
45
+ const parts = read([
46
+ 'import "./side.css";',
47
+ 'import { track } from "./track";',
48
+ 'import { cn } from "./cn";',
49
+ "const registry = new Map<string, number>();",
50
+ 'registry.set("x", 1);',
51
+ "track();",
52
+ "export const A = () => cn();",
53
+ 'export const D = () => registry.get("x");',
54
+ ]);
55
+
56
+ expect(parts.ids).toEqual(["p0", "p1", "rest"]);
57
+ expect(linesOf(parts, "rest")).toEqual([
58
+ 'import "./side.css";',
59
+ 'import { track } from "./track";',
60
+ "const registry = new Map<string, number>();",
61
+ 'registry.set("x", 1);',
62
+ "track();",
63
+ "export { registry as __akanPart_registry };",
64
+ ]);
65
+ expect(linesOf(parts, "p0")).toEqual([
66
+ `import ${from("rest")};`,
67
+ 'import { cn } from "./cn";',
68
+ "export const A = () => cn();",
69
+ ]);
70
+ expect(linesOf(parts, "p1")).toEqual([
71
+ `import ${from("rest")};`,
72
+ `import { __akanPart_registry as registry } from ${from("rest")};`,
73
+ 'export const D = () => registry.get("x");',
74
+ ]);
75
+ });
76
+
77
+ test("a declaration no export names joins the one export reading it, and is lent out when two read it", () => {
78
+ const parts = read([
79
+ "const double = (value: number) => value * 2;",
80
+ "const only = { deep: true };",
81
+ "const unread = 1;",
82
+ "export const A = () => double(1);",
83
+ "export const B = () => double(2);",
84
+ "export const C = () => only;",
85
+ ]);
86
+
87
+ expect(parts.ids).toEqual(["p0", "p1", "p2", "p3"]);
88
+ expect(linesOf(parts, "p0")).toEqual([
89
+ "const double = (value: number) => value * 2;",
90
+ "export { double as __akanPart_double };",
91
+ ]);
92
+ for (const [name, call] of [
93
+ ["A", "double(1)"],
94
+ ["B", "double(2)"],
95
+ ] as const)
96
+ expect(partOf(parts, name)).toEqual([
97
+ `import { __akanPart_double as double } from ${from("p0")};`,
98
+ `export const ${name} = () => ${call};`,
99
+ ]);
100
+ expect(partOf(parts, "C")).toEqual(["const only = { deep: true };", "export const C = () => only;"]);
101
+ for (const id of parts.ids) expect(parts.sourceOf(id, self)).not.toContain("unread");
102
+ });
103
+
104
+ test("declarations reading each other in a cycle are one part", () => {
105
+ const parts = read([
106
+ "export function even(n: number): boolean {",
107
+ " return n === 0 || odd(n - 1);",
108
+ "}",
109
+ "export function odd(n: number): boolean {",
110
+ " return n !== 0 && even(n - 1);",
111
+ "}",
112
+ "export const other = 1;",
113
+ ]);
114
+
115
+ expect(parts.partOf("even")).toBe(parts.partOf("odd"));
116
+ expect(parts.partOf("other")).not.toBe(parts.partOf("even"));
117
+ });
118
+
119
+ test("a member given to a declared value stays in its part, and one built by a call moves it to `rest`", () => {
120
+ const parts = read([
121
+ 'import { Item } from "./Item";',
122
+ 'import { make } from "./make";',
123
+ "export const List = () => null;",
124
+ "List.Item = Item;",
125
+ "export const Menu = () => null;",
126
+ "Object.assign(Menu, { Item });",
127
+ "export const Made = () => null;",
128
+ "Made.extra = make();",
129
+ "export const Plain = () => null;",
130
+ ]);
131
+
132
+ expect(partOf(parts, "List")).toEqual([
133
+ `import ${from("rest")};`,
134
+ 'import { Item } from "./Item";',
135
+ "export const List = () => null;",
136
+ "List.Item = Item;",
137
+ ]);
138
+ expect(partOf(parts, "Menu")).toContain("Object.assign(Menu, { Item });");
139
+ expect(parts.partOf("Made")).toBe("rest");
140
+ expect(partOf(parts, "Plain")).toEqual([`import ${from("rest")};`, "export const Plain = () => null;"]);
141
+ });
142
+
143
+ test("a type is no export of any part, and every part carries the file's type declarations", () => {
144
+ const parts = read([
145
+ 'import type { Outer } from "./types";',
146
+ "export interface Props { a: Outer }",
147
+ "type Local = Props;",
148
+ 'export type { Other } from "./other";',
149
+ 'export { type Third, value } from "./third";',
150
+ "export const A = (props: Local) => props;",
151
+ ]);
152
+
153
+ expect(parts.exports).toEqual(["value", "A"]);
154
+ for (const name of ["Props", "Other", "Third"]) expect(parts.isType(name)).toBe(true);
155
+ expect(parts.isType("A")).toBe(false);
156
+ expect(partOf(parts, "value")).toEqual([
157
+ "export interface Props { a: Outer }",
158
+ "type Local = Props;",
159
+ 'export { value } from "./third";',
160
+ ]);
161
+ expect(partOf(parts, "A")).toEqual([
162
+ "export interface Props { a: Outer }",
163
+ "type Local = Props;",
164
+ "export const A = (props: Local) => props;",
165
+ ]);
166
+ });
167
+
168
+ test("an export list, a renamed export and a default export each go to the part of what they name", () => {
169
+ const parts = read([
170
+ 'import { outer } from "./outer";',
171
+ "const a = 1;",
172
+ "const b = () => a;",
173
+ "export { a, b as c, outer };",
174
+ "export default b;",
175
+ ]);
176
+
177
+ expect(new Set(parts.exports)).toEqual(new Set(["a", "c", "default", "outer"]));
178
+ expect(partOf(parts, "a")).toEqual(["const a = 1;", "export { a as __akanPart_a, a };"]);
179
+ expect(partOf(parts, "c")).toEqual([
180
+ `import { __akanPart_a as a } from ${from(parts.partOf("a") ?? "")};`,
181
+ "const b = () => a;",
182
+ "export { b as __akanPart_b, b as c };",
183
+ ]);
184
+ expect(partOf(parts, "default")).toEqual([
185
+ `import { __akanPart_b as b } from ${from(parts.partOf("c") ?? "")};`,
186
+ "export default b;",
187
+ ]);
188
+ expect(partOf(parts, "outer")).toEqual(['import { outer } from "./outer";', "export { outer };"]);
189
+ });
190
+
191
+ test("an overloaded function keeps its signatures with its body", () => {
192
+ const parts = read([
193
+ "export function pick(value: string): string;",
194
+ "export function pick(value: number): number;",
195
+ "export function pick(value: unknown) {",
196
+ " return value;",
197
+ "}",
198
+ "export const other = 1;",
199
+ ]);
200
+
201
+ expect(partOf(parts, "pick")).toEqual([
202
+ "export function pick(value: string): string;",
203
+ "export function pick(value: number): number;",
204
+ "export function pick(value: unknown) {",
205
+ " return value;",
206
+ "}",
207
+ ]);
208
+ });
209
+
210
+ test.each([
211
+ ["a single export", ["export const A = 1;"]],
212
+ ["everything running on load", ["export const A = make();", "export const B = make();"]],
213
+ ["a top-level `let`", ["export let count = 0;", "export const A = 1;", "export const B = 2;"]],
214
+ ["`export *`", ['export * from "./other";', "export const A = 1;", "export const B = 2;"]],
215
+ ["a namespace", ["namespace Inner {}", "export const A = 1;", "export const B = 2;"]],
216
+ ["`export =`", ["const A = 1;", "const B = 2;", "export = A;"]],
217
+ [
218
+ "a macro import",
219
+ ['import { read } from "./read" with { type: "macro" };', "export const A = 1;", "export const B = 2;"],
220
+ ],
221
+ ["an export of a name it does not hold", ["export { missing };", "export const A = 1;", "export const B = 2;"]],
222
+ ])("a file with %s stays one module", (_, lines) => {
223
+ expect(ModuleParts.read(`${lines.join("\n")}\n`, self)).toBeNull();
224
+ });
225
+ });
@@ -0,0 +1,418 @@
1
+ import ts from "typescript";
2
+ import { ExportReach } from "./exportReach";
3
+ import { ObjectModule } from "./objectModule";
4
+ import { PartPurity } from "./partPurity";
5
+
6
+ interface Unit {
7
+ at: number;
8
+ texts: string[];
9
+ declares: string[];
10
+ reads: Set<string>;
11
+ pure: boolean;
12
+ publics: string[];
13
+ listed: string[];
14
+ }
15
+
16
+ interface ValueImport {
17
+ from: string;
18
+ bare: boolean;
19
+ defaultName?: string;
20
+ namespace?: string;
21
+ named: { local: string; text: string }[];
22
+ }
23
+
24
+ interface Part {
25
+ id: string;
26
+ units: Unit[];
27
+ }
28
+
29
+ const REST = "rest";
30
+ const SHARED = "__akanPart_";
31
+ const MACRO_ATTRIBUTE = /with\s*\{\s*type\s*:\s*["']macro["']\s*\}/;
32
+
33
+ //* One source file as several modules, so a bundler placing whole modules can load one export without the others.
34
+ //* A top-level declaration that only builds a value is a part, with the declarations it alone reads and the ones it
35
+ //* is in a cycle with. Every other statement, and what those read, is the `rest` part each part imports, so what the
36
+ //* file does when it loads still happens before any of its exports is used. Names are matched by text, so a part can
37
+ //* import more than it reads, never less.
38
+ export class ModuleParts {
39
+ static readonly query = "?akan-part=";
40
+ static readonly specifier = /\?akan-part=([\w$]+)$/;
41
+
42
+ //? Dropped once the parts are placed: a build keeps the parts of every file it loads, and a syntax tree is large.
43
+ #tree: ts.SourceFile | null;
44
+ readonly #directives: string[] = [];
45
+ readonly #types: string[] = [];
46
+ readonly #typeNames = new Set<string>();
47
+ readonly #declaredTypes = new Set<string>();
48
+ readonly #imports: ValueImport[] = [];
49
+ readonly #importLocals = new Set<string>();
50
+ readonly #units: Unit[] = [];
51
+ readonly #ownerOf = new Map<string, Unit>();
52
+ readonly #lists: { local: string; exported: string }[] = [];
53
+ readonly #purity = new PartPurity();
54
+ #overloads: string[] = [];
55
+ #parts: Part[] = [];
56
+ #partOfLocal = new Map<string, string>();
57
+ #partOfPublic = new Map<string, string>();
58
+ #lent = new Set<string>();
59
+
60
+ private constructor(sourceFile: ts.SourceFile) {
61
+ this.#tree = sourceFile;
62
+ }
63
+
64
+ get #sourceFile(): ts.SourceFile {
65
+ if (!this.#tree) throw new Error("[akan] a module's parts are read from its source once");
66
+ return this.#tree;
67
+ }
68
+
69
+ //? null: the file stays one module (a shape this cannot place, or nothing to gain from parts).
70
+ static read(source: string, file: string): ModuleParts | null {
71
+ if (MACRO_ATTRIBUTE.test(source) || source.includes(SHARED)) return null;
72
+ const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ObjectModule.scriptKindOf(file));
73
+ const parts = new ModuleParts(sourceFile);
74
+ let prologue = true;
75
+ for (const statement of sourceFile.statements) {
76
+ if (prologue && ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) {
77
+ parts.#directives.push(statement.getText(sourceFile));
78
+ continue;
79
+ }
80
+ prologue = false;
81
+ if (!parts.#collect(statement)) return null;
82
+ }
83
+ const placed = parts.#place();
84
+ parts.#tree = null;
85
+ return placed ? parts : null;
86
+ }
87
+
88
+ get ids(): string[] {
89
+ return this.#parts.map(({ id }) => id);
90
+ }
91
+
92
+ get exports(): string[] {
93
+ return [...this.#partOfPublic.keys()];
94
+ }
95
+
96
+ partOf(exported: string): string | null {
97
+ return this.#partOfPublic.get(exported) ?? null;
98
+ }
99
+
100
+ isType(exported: string): boolean {
101
+ return this.#typeNames.has(exported);
102
+ }
103
+
104
+ facade(self: string): string {
105
+ const lines = [...this.#directives];
106
+ for (const { id } of this.#parts) {
107
+ const names = [...this.#partOfPublic].filter(([, part]) => part === id).map(([name]) => name);
108
+ if (names.length) lines.push(`export { ${names.join(", ")} } from ${ModuleParts.#from(self, id)};`);
109
+ }
110
+ return `${lines.join("\n")}\n`;
111
+ }
112
+
113
+ sourceOf(id: string, self: string): string | null {
114
+ const part = this.#parts.find((candidate) => candidate.id === id);
115
+ if (!part) return null;
116
+ const reads = new Set(part.units.flatMap((unit) => [...unit.reads]));
117
+ const own = new Set(part.units.flatMap((unit) => unit.declares));
118
+ const lines = [...this.#directives];
119
+ if (id !== REST && this.#parts.some((candidate) => candidate.id === REST))
120
+ lines.push(`import ${ModuleParts.#from(self, REST)};`);
121
+ for (const imported of this.#imports) {
122
+ const line = ModuleParts.#importOf(imported, reads, id === REST);
123
+ if (line) lines.push(line);
124
+ }
125
+ const borrowed = new Map<string, string[]>();
126
+ for (const name of reads) {
127
+ const from = this.#partOfLocal.get(name);
128
+ if (from && from !== id && !own.has(name)) borrowed.set(from, [...(borrowed.get(from) ?? []), name]);
129
+ }
130
+ for (const [from, names] of borrowed)
131
+ lines.push(
132
+ `import { ${names.map((name) => `${SHARED}${name} as ${name}`).join(", ")} } from ${ModuleParts.#from(self, from)};`,
133
+ );
134
+ lines.push(...this.#types, ...part.units.flatMap((unit) => unit.texts));
135
+ const lent = [...own].filter((name) => this.#lent.has(name)).map((name) => `${name} as ${SHARED}${name}`);
136
+ const listed = part.units.flatMap((unit) => unit.listed);
137
+ if (lent.length + listed.length) lines.push(`export { ${[...lent, ...listed].join(", ")} };`);
138
+ return `${lines.join("\n")}\n`;
139
+ }
140
+
141
+ static #from(self: string, id: string): string {
142
+ return JSON.stringify(`${self}${ModuleParts.query}${id}`);
143
+ }
144
+
145
+ //? `rest` keeps every import the file makes for its effect alone, in the order written.
146
+ static #importOf(
147
+ { from, bare, defaultName, namespace, named }: ValueImport,
148
+ reads: Set<string>,
149
+ rest: boolean,
150
+ ): string | null {
151
+ if (bare) return rest ? `import ${from};` : null;
152
+ const bound: string[] = [];
153
+ if (defaultName && reads.has(defaultName)) bound.push(defaultName);
154
+ if (namespace && reads.has(namespace)) bound.push(`* as ${namespace}`);
155
+ const read = named.filter(({ local }) => reads.has(local));
156
+ if (read.length) bound.push(`{ ${read.map(({ text }) => text).join(", ")} }`);
157
+ return bound.length ? `import ${bound.join(", ")} from ${from};` : null;
158
+ }
159
+
160
+ #collect(statement: ts.Statement): boolean {
161
+ const text = statement.getFullText(this.#sourceFile).replace(/^\s*\n/, "");
162
+ if (ts.isImportDeclaration(statement)) return this.#collectImport(statement);
163
+ if (ts.isEmptyStatement(statement)) return true;
164
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
165
+ this.#types.push(text);
166
+ this.#declaredTypes.add(statement.name.text);
167
+ if (ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword)) this.#typeNames.add(statement.name.text);
168
+ return true;
169
+ }
170
+ if (ModuleParts.#has(statement, ts.SyntaxKind.DeclareKeyword)) {
171
+ this.#types.push(text);
172
+ return true;
173
+ }
174
+ if (ts.isImportEqualsDeclaration(statement) || ts.isModuleDeclaration(statement)) return false;
175
+ if (ts.isExportDeclaration(statement)) return this.#collectExportList(statement);
176
+ if (ts.isExportAssignment(statement)) {
177
+ if (statement.isExportEquals) return false;
178
+ this.#add(statement, text, { publics: ["default"], pure: this.#purity.of(statement.expression) });
179
+ return true;
180
+ }
181
+ if (ts.isVariableStatement(statement)) return this.#collectVariables(statement, text);
182
+ if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement))
183
+ return this.#collectDeclaration(statement, text);
184
+ const given = ts.isExpressionStatement(statement) ? ModuleParts.#given(statement.expression) : null;
185
+ const owner = given && this.#ownerOf.get(given.to);
186
+ if (!given || !owner) {
187
+ this.#add(statement, text, { pure: false });
188
+ return true;
189
+ }
190
+ owner.texts.push(text);
191
+ for (const name of ExportReach.namesReadBy(statement)) owner.reads.add(name);
192
+ owner.pure &&= given.values.every((value) => this.#purity.of(value));
193
+ return true;
194
+ }
195
+
196
+ #collectImport(statement: ts.ImportDeclaration): boolean {
197
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) return false;
198
+ const clause = statement.importClause;
199
+ if (clause?.phaseModifier === ts.SyntaxKind.TypeKeyword) return true;
200
+ const bindings = clause?.namedBindings;
201
+ const namespace = bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : undefined;
202
+ const named = (bindings && ts.isNamedImports(bindings) ? [...bindings.elements] : [])
203
+ .filter((element) => !element.isTypeOnly)
204
+ .map((element) => ({ local: element.name.text, text: element.getText(this.#sourceFile) }));
205
+ const tail = statement.attributes ? ` ${statement.attributes.getText(this.#sourceFile)}` : "";
206
+ const from = `${statement.moduleSpecifier.getText(this.#sourceFile)}${tail}`;
207
+ const defaultName = clause?.name?.text;
208
+ for (const local of [defaultName, namespace, ...named.map(({ local }) => local)])
209
+ if (local) this.#importLocals.add(local);
210
+ //? `import {} from` binds nothing and still loads the module, as a bare import does.
211
+ const bare = !clause || (!defaultName && !!bindings && ts.isNamedImports(bindings) && !bindings.elements.length);
212
+ this.#imports.push({ from, bare, defaultName, namespace, named });
213
+ this.#purity.note(statement);
214
+ if (bare) this.#add(statement, "", { pure: false });
215
+ return true;
216
+ }
217
+
218
+ #collectExportList(statement: ts.ExportDeclaration): boolean {
219
+ const clause = statement.exportClause;
220
+ if (!clause) return statement.isTypeOnly;
221
+ if (ts.isNamespaceExport(clause)) {
222
+ if (statement.isTypeOnly) this.#typeNames.add(clause.name.text);
223
+ else this.#add(statement, statement.getText(this.#sourceFile), { publics: [clause.name.text] });
224
+ return true;
225
+ }
226
+ const values = clause.elements.filter((element) => !statement.isTypeOnly && !element.isTypeOnly);
227
+ for (const element of clause.elements) if (!values.includes(element)) this.#typeNames.add(element.name.text);
228
+ if (!statement.moduleSpecifier) {
229
+ for (const element of values)
230
+ this.#lists.push({ local: (element.propertyName ?? element.name).text, exported: element.name.text });
231
+ return true;
232
+ }
233
+ if (!values.length) return true;
234
+ const from = statement.moduleSpecifier.getText(this.#sourceFile);
235
+ const names = values.map((element) => element.getText(this.#sourceFile));
236
+ const tail = statement.attributes ? ` ${statement.attributes.getText(this.#sourceFile)}` : "";
237
+ this.#add(statement, `export { ${names.join(", ")} } from ${from}${tail};`, {
238
+ publics: values.map((element) => element.name.text),
239
+ });
240
+ return true;
241
+ }
242
+
243
+ #collectVariables(statement: ts.VariableStatement, text: string): boolean {
244
+ const { flags, declarations } = statement.declarationList;
245
+ if ((flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const) return false;
246
+ const declares = declarations.flatMap((declaration) => ModuleParts.#boundNames(declaration.name));
247
+ const pure = declarations.every(
248
+ (declaration) => declaration.initializer && this.#purity.of(declaration.initializer),
249
+ );
250
+ const exported = ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword);
251
+ this.#add(statement, text, { declares, pure, publics: exported ? declares : [] });
252
+ return true;
253
+ }
254
+
255
+ #collectDeclaration(
256
+ statement: ts.FunctionDeclaration | ts.ClassDeclaration | ts.EnumDeclaration,
257
+ text: string,
258
+ ): boolean {
259
+ if (ts.isFunctionDeclaration(statement) && !statement.body) {
260
+ this.#overloads.push(text);
261
+ return true;
262
+ }
263
+ const declares = statement.name ? [statement.name.text] : [];
264
+ const publics = ModuleParts.#has(statement, ts.SyntaxKind.DefaultKeyword)
265
+ ? ["default"]
266
+ : ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword)
267
+ ? declares
268
+ : [];
269
+ const pure = !ts.isClassDeclaration(statement) || this.#purity.ofClass(statement);
270
+ this.#add(statement, [...this.#overloads, text].join("\n"), { declares, pure, publics });
271
+ this.#overloads = [];
272
+ return true;
273
+ }
274
+
275
+ #add(
276
+ statement: ts.Statement,
277
+ text: string,
278
+ { declares = [], pure = true, publics = [] }: { declares?: string[]; pure?: boolean; publics?: string[] },
279
+ ) {
280
+ const reads = ts.isImportDeclaration(statement) ? new Set<string>() : ExportReach.namesReadBy(statement);
281
+ const known = declares.map((name) => this.#ownerOf.get(name)).find((unit) => unit !== undefined);
282
+ const unit = known ?? {
283
+ at: statement.pos,
284
+ texts: [],
285
+ declares: [],
286
+ reads: new Set(),
287
+ pure: true,
288
+ publics: [],
289
+ listed: [],
290
+ };
291
+ if (text) unit.texts.push(text);
292
+ unit.declares.push(...declares);
293
+ unit.publics.push(...publics);
294
+ unit.pure &&= pure;
295
+ for (const name of reads) unit.reads.add(name);
296
+ for (const name of declares) this.#ownerOf.set(name, unit);
297
+ if (!known) this.#units.push(unit);
298
+ }
299
+
300
+ #place(): boolean {
301
+ for (const { local, exported } of this.#lists) {
302
+ const owner = this.#ownerOf.get(local);
303
+ if (owner) owner.listed.push(local === exported ? local : `${local} as ${exported}`);
304
+ else if (this.#importLocals.has(local))
305
+ this.#units.push({
306
+ at: this.#sourceFile.end,
307
+ texts: [`export { ${local === exported ? local : `${local} as ${exported}`} };`],
308
+ declares: [],
309
+ reads: new Set([local]),
310
+ pure: true,
311
+ publics: [exported],
312
+ listed: [],
313
+ });
314
+ else if (this.#declaredTypes.has(local)) this.#typeNames.add(exported);
315
+ else return false;
316
+ if (owner) owner.publics.push(exported);
317
+ }
318
+ const dependencies = new Map<Unit, Set<Unit>>();
319
+ for (const unit of this.#units) {
320
+ const read = [...unit.reads].map((name) => this.#ownerOf.get(name));
321
+ dependencies.set(unit, new Set(read.filter((owner): owner is Unit => !!owner && owner !== unit)));
322
+ }
323
+ const rest = ModuleParts.#closureOf(
324
+ this.#units.filter((unit) => !unit.pure),
325
+ dependencies,
326
+ );
327
+ const groups = ModuleParts.#grouped(
328
+ this.#units.filter((unit) => !rest.has(unit)),
329
+ dependencies,
330
+ );
331
+ const parts = groups.map((units) => units.sort((a, b) => a.at - b.at)).sort(([a], [b]) => a.at - b.at);
332
+ this.#parts = parts.map((units, index) => ({ id: `p${index}`, units }));
333
+ if (rest.size) this.#parts.push({ id: REST, units: [...rest].sort((a, b) => a.at - b.at) });
334
+ if (this.#parts.length < 2) return false;
335
+ for (const { id, units } of this.#parts)
336
+ for (const unit of units) {
337
+ for (const name of unit.declares) this.#partOfLocal.set(name, id);
338
+ for (const name of unit.publics) this.#partOfPublic.set(name, id);
339
+ }
340
+ for (const { id, units } of this.#parts)
341
+ for (const unit of units)
342
+ for (const name of unit.reads) {
343
+ const from = this.#partOfLocal.get(name);
344
+ if (from && from !== id) this.#lent.add(name);
345
+ }
346
+ return true;
347
+ }
348
+
349
+ static #closureOf(starts: Unit[], dependencies: Map<Unit, Set<Unit>>): Set<Unit> {
350
+ const reached = new Set(starts);
351
+ for (const unit of reached) for (const dependency of dependencies.get(unit) ?? []) reached.add(dependency);
352
+ return reached;
353
+ }
354
+
355
+ //? Units in a cycle load together. One no export names, read by a single group, joins it; read by none, it is dropped.
356
+ static #grouped(units: Unit[], dependencies: Map<Unit, Set<Unit>>): Unit[][] {
357
+ const groupOf = new Map<Unit, Set<Unit>>();
358
+ for (const unit of units) {
359
+ if (groupOf.has(unit)) continue;
360
+ const down = ModuleParts.#closureOf([unit], dependencies);
361
+ const cycle = new Set(
362
+ units.filter((other) => down.has(other) && ModuleParts.#closureOf([other], dependencies).has(unit)),
363
+ );
364
+ for (const member of cycle) groupOf.set(member, cycle);
365
+ }
366
+ const groups = new Set(groupOf.values());
367
+ const readersOf = (group: Set<Unit>) =>
368
+ [...groups].filter(
369
+ (other) =>
370
+ other !== group && [...other].some((unit) => [...group].some((own) => dependencies.get(unit)?.has(own))),
371
+ );
372
+ for (let settled = false; !settled; ) {
373
+ settled = true;
374
+ for (const group of groups) {
375
+ if ([...group].some((unit) => unit.publics.length)) continue;
376
+ const readers = readersOf(group);
377
+ if (readers.length > 1) continue;
378
+ for (const unit of group) readers[0]?.add(unit);
379
+ groups.delete(group);
380
+ settled = false;
381
+ }
382
+ }
383
+ return [...groups].map((group) => [...group]);
384
+ }
385
+
386
+ //? `A.b = v` and `Object.assign(A, v)` belong to the part declaring `A`: they only add to a value it built.
387
+ static #given(expression: ts.Expression): { to: string; values: ts.Expression[] } | null {
388
+ let target: ts.Expression | undefined;
389
+ let values: ts.Expression[] = [];
390
+ if (ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
391
+ target = expression.left;
392
+ while (ts.isPropertyAccessExpression(target)) target = target.expression;
393
+ if (target === expression.left) return null;
394
+ values = [expression.right];
395
+ } else if (
396
+ ts.isCallExpression(expression) &&
397
+ ts.isPropertyAccessExpression(expression.expression) &&
398
+ expression.expression.name.text === "assign" &&
399
+ ts.isIdentifier(expression.expression.expression) &&
400
+ expression.expression.expression.text === "Object"
401
+ ) {
402
+ [target, ...values] = expression.arguments;
403
+ values = values.map((value) => (ts.isSpreadElement(value) ? value.expression : value));
404
+ }
405
+ return target && ts.isIdentifier(target) ? { to: target.text, values } : null;
406
+ }
407
+
408
+ static #boundNames(name: ts.BindingName): string[] {
409
+ if (ts.isIdentifier(name)) return [name.text];
410
+ return name.elements.flatMap((element) =>
411
+ ts.isOmittedExpression(element) ? [] : ModuleParts.#boundNames(element.name),
412
+ );
413
+ }
414
+
415
+ static #has(node: ts.Node, kind: ts.SyntaxKind) {
416
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
417
+ }
418
+ }