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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +126 -5
  22. package/app/dictionarySizes.ts +94 -0
  23. package/artifact/implicitRootLayout.test.ts +19 -0
  24. package/artifact/implicitRootLayout.ts +16 -2
  25. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  26. package/artifact/storeBootstrap.test.ts +28 -0
  27. package/artifact/storeBootstrap.ts +60 -8
  28. package/biome.base.json +5 -1
  29. package/codeAgent/agent/CodeAgent.ts +36 -16
  30. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  31. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  32. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  33. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  34. package/codeAgent/agent/codeAgent.test.ts +62 -0
  35. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  36. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  37. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  38. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  39. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  40. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  41. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  42. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  43. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  44. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  45. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  46. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  47. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  48. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  49. package/context/akanContext.ts +2 -0
  50. package/docs/apiReference.test.ts +9 -0
  51. package/docs/apiReference.ts +14 -0
  52. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  53. package/executors/clientRuntimeKeys.fixture.json +393 -0
  54. package/executors/clientRuntimeKeys.test.ts +1591 -0
  55. package/executors/executors.test.ts +2 -0
  56. package/executors/sysExecutor.ts +66 -3
  57. package/executors/workspaceExecutor.ts +7 -4
  58. package/frontendBuild/allRoutesBuilder.ts +72 -3
  59. package/frontendBuild/autoImportSync.ts +3 -2
  60. package/frontendBuild/buildRouteClient.test.ts +515 -12
  61. package/frontendBuild/clientBuildTypes.ts +15 -0
  62. package/frontendBuild/clientEntriesBundler.ts +38 -0
  63. package/frontendBuild/clientEntryDiscovery.test.ts +95 -1
  64. package/frontendBuild/clientEntryDiscovery.ts +88 -7
  65. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  66. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  67. package/frontendBuild/csrDevPatcher.ts +33 -7
  68. package/frontendBuild/csrDevTypes.ts +9 -0
  69. package/frontendBuild/devBarrelImports.test.ts +100 -0
  70. package/frontendBuild/devBarrelImports.ts +82 -23
  71. package/frontendBuild/devRegistryBundler.ts +4 -2
  72. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  73. package/frontendBuild/devRouteRuntime.ts +167 -0
  74. package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
  75. package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
  76. package/frontendBuild/dictionaryConstants.ts +82 -0
  77. package/frontendBuild/dictionaryPacking.test.ts +84 -0
  78. package/frontendBuild/dictionaryPacking.ts +92 -0
  79. package/frontendBuild/dictionaryRoutes.test.ts +186 -0
  80. package/frontendBuild/dictionaryRoutes.ts +225 -0
  81. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  82. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  83. package/frontendBuild/precompressArtifacts.ts +7 -0
  84. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  85. package/frontendBuild/routeClientBuilder.ts +288 -15
  86. package/frontendBuild/routeHandoffs.test.ts +145 -0
  87. package/frontendBuild/routeHandoffs.ts +115 -0
  88. package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
  89. package/frontendBuild/routeRuntimeCheck.ts +241 -0
  90. package/frontendBuild/routeRuntimePays.test.ts +137 -0
  91. package/frontendBuild/routeRuntimePays.ts +117 -0
  92. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  93. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  94. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  95. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  96. package/frontendBuild/ssrDevBundler.ts +66 -11
  97. package/frontendBuild/vendorFileImports.test.ts +254 -0
  98. package/frontendBuild/vendorFileImports.ts +163 -0
  99. package/frontendBuild/vendorNarrowing.ts +28 -0
  100. package/frontendBuild/vendorSpecifiers.ts +2 -0
  101. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  102. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  103. package/incrementalBuilder/builderBoot.ts +5 -5
  104. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  105. package/incrementalBuilder/builderLanes.ts +2 -2
  106. package/incrementalBuilder/builderWatch.ts +8 -8
  107. package/incrementalBuilder/csrRegistry.ts +4 -4
  108. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  109. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  110. package/incrementalBuilder/ssrRegistry.ts +6 -6
  111. package/index.ts +1 -1
  112. package/integration/renderAdmissionSoak.test.ts +99 -0
  113. package/integration/renderAdmissionSoak.ts +609 -0
  114. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  115. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  116. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  117. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  118. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  119. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  120. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  121. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  122. package/lint/biomeCheck.test.ts +145 -0
  123. package/lint/biomeCheck.ts +131 -0
  124. package/lint/no-arbitrary-color.grit +5 -0
  125. package/lint/no-conditional-st-hook.grit +5 -1
  126. package/lint/no-daisyui-legacy-class.grit +8 -0
  127. package/lint/no-document-cookie.grit +3 -0
  128. package/lint/no-inline-color.grit +10 -2
  129. package/lint/no-oversized-list-limit.grit +2 -0
  130. package/lint/no-raw-palette-class.grit +7 -0
  131. package/lint/no-unpublished-form-setter.grit +2 -0
  132. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  133. package/lint/no-web-storage.grit +3 -0
  134. package/lint/withheldEnvFile.ts +17 -0
  135. package/mobile/desktopBin.ts +2 -2
  136. package/mobile/desktopServerStage.ts +1 -0
  137. package/mobile/nativeApp.test.ts +7 -5
  138. package/mobile/nativeApp.ts +2 -2
  139. package/mobile/nativeConfig.test.ts +96 -1
  140. package/mobile/nativeConfig.ts +46 -12
  141. package/mobile/serverBundleSecrets.ts +43 -0
  142. package/package.json +15 -169
  143. package/packageExports.test.ts +38 -24
  144. package/quality/dictionaryKeys.test.ts +173 -0
  145. package/quality/dictionaryKeys.ts +415 -0
  146. package/quality/objectImportReport.test.ts +36 -0
  147. package/quality/objectImportReport.ts +102 -0
  148. package/quality/qualityScanner.ts +1 -1
  149. package/quality/routeRuntimeReport.test.ts +91 -0
  150. package/quality/routeRuntimeReport.ts +121 -0
  151. package/quality/runtimeConstantFacts.ts +71 -0
  152. package/quality/runtimeConstantGraph.ts +123 -0
  153. package/quality/runtimeConstantReads.ts +116 -0
  154. package/quality/runtimeImports.test.ts +190 -0
  155. package/quality/runtimeImports.ts +233 -0
  156. package/quality/runtimeKeyNames.ts +46 -0
  157. package/quality/runtimeLexicalScope.ts +132 -0
  158. package/quality/runtimeMarkerReach.test.ts +84 -0
  159. package/quality/runtimeMarkerReach.ts +255 -0
  160. package/quality/runtimeModuleFacts.ts +290 -0
  161. package/quality/runtimeNameTable.test.ts +172 -0
  162. package/quality/runtimeNameTable.ts +477 -0
  163. package/quality/runtimeScopeReport.test.ts +123 -0
  164. package/quality/runtimeScopeReport.ts +167 -0
  165. package/quality/runtimeSliceKey.ts +269 -0
  166. package/quality/runtimeSyntax.ts +133 -0
  167. package/quality/runtimeTable.fixture.ts +189 -0
  168. package/quality/runtimeUse.test.ts +737 -0
  169. package/quality/runtimeUse.ts +696 -0
  170. package/quality/runtimeUseReadable.test.ts +393 -0
  171. package/quality/ssrScanner.test.ts +13 -0
  172. package/quality/ssrScanner.ts +1 -1
  173. package/test/secretEnvFixture.ts +134 -0
  174. package/test/testHelpers.ts +11 -0
  175. package/transforms/barrelAnalyzer.ts +26 -4
  176. package/transforms/barrelImportsPlugin.ts +82 -14
  177. package/transforms/frameworkObjects.fixture.tsx +58 -0
  178. package/transforms/frameworkObjects.test.ts +54 -0
  179. package/transforms/modelReference.test.ts +196 -0
  180. package/transforms/modelReference.ts +39 -0
  181. package/transforms/objectImportEdits.ts +150 -0
  182. package/transforms/objectMemberImports.test.ts +347 -0
  183. package/transforms/objectMemberImports.ts +537 -0
  184. package/transforms/objectModule.test.ts +237 -0
  185. package/transforms/objectModule.ts +458 -0
  186. package/transforms/objectModuleAnalyzer.ts +104 -0
  187. package/transforms/reactIconImports.test.ts +231 -0
  188. package/transforms/reactIconImports.ts +325 -0
  189. package/transforms/routeConstants.ts +122 -0
  190. package/transforms/routeRuntime.test.ts +835 -0
  191. package/transforms/routeRuntime.ts +703 -0
  192. package/transforms/routeRuntimeEdits.ts +92 -0
  193. package/transforms/routeRuntimeGraph.ts +66 -0
  194. package/transforms/routeRuntimePlan.ts +244 -0
  195. package/transforms/secretEnvDeclaration.test.ts +208 -0
  196. package/transforms/secretEnvDeclaration.ts +213 -0
  197. package/transforms/secretEnvFile.test.ts +117 -0
  198. package/transforms/secretEnvFile.ts +113 -0
  199. package/transforms/secretEnvName.test.ts +54 -0
  200. package/transforms/secretEnvName.ts +29 -0
  201. package/transforms/secretEnvSource.test.ts +148 -0
  202. package/transforms/secretEnvSource.ts +166 -0
  203. package/transforms/serverEnvEvaluationError.ts +11 -0
  204. package/transforms/serverEnvPlugin.test.ts +2 -1
  205. package/transforms/serverEnvPlugin.ts +13 -0
  206. package/transforms/serverEnvProfile.test.ts +115 -2
  207. package/transforms/serverEnvProfile.ts +117 -40
  208. package/transforms/serverEnvSecrets.test.ts +292 -0
  209. package/transforms/signalDescriptors.test.ts +280 -0
  210. package/transforms/signalDescriptors.ts +227 -0
  211. package/transforms/thisFreeExports.ts +87 -0
  212. package/transforms/transforms.test.ts +180 -3
  213. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  214. package/tunnel/createTunnel.test.ts +29 -8
  215. package/tunnel/createTunnel.ts +18 -11
  216. package/typecheck/projectTypecheck.test.ts +29 -0
  217. package/typecheck/typeChecker.test.ts +49 -0
  218. package/typecheck/typeChecker.ts +9 -7
  219. package/typecheck/withheldDiagnostics.ts +41 -0
  220. package/util/fileEditor.ts +1 -0
  221. package/util/selectModel.ts +1 -0
  222. package/workflow/executor.ts +6 -2
  223. package/workflow/index.ts +1 -0
  224. package/workflow/plan.ts +36 -7
  225. package/workflow/types.ts +1 -1
  226. package/workflow/uiTarget.ts +50 -0
  227. package/workspace/getRelatedCnsts.ts +7 -0
  228. package/workspace/scanInfo.ts +1 -1
  229. package/workspace/workspaceLayout.ts +1 -0
@@ -0,0 +1,241 @@
1
+ import path from "node:path";
2
+ import type { ClientBundleGraph } from "./clientBuildTypes";
3
+
4
+ export interface RouteRuntimeNarrowed {
5
+ //? Build entry to the source entry it wraps, for each entry built to load only the modules its code names.
6
+ entries: ReadonlyMap<string, string>;
7
+ wholeReaders: ReadonlySet<string>;
8
+ //? The files `akan quality runtime` names for keeping every constant; only through one may a page reach `lib/cnst.ts`.
9
+ wholeConstantReaders?: ReadonlySet<string>;
10
+ routes?: ReadonlyMap<string, readonly string[]>;
11
+ }
12
+
13
+ const repeatable = [
14
+ {
15
+ whole: /^((?:apps|libs)\/[^/]+)\/lib\/useClient\.ts$/,
16
+ piece: /^((?:apps|libs)\/[^/]+)\/lib\/__client\/[^/]+\.fetch\.ts$/,
17
+ },
18
+ {
19
+ whole: /^((?:apps|libs)\/[^/]+)\/lib\/cnst\.ts$/,
20
+ piece: /^((?:apps|libs)\/[^/]+)\/lib\/__client\/[^/]+\.cnst\.ts$/,
21
+ },
22
+ ];
23
+
24
+ const pieceFile = /^(?:apps|libs)\/[^/]+\/lib\/__client\/[^/]+\.ts$/;
25
+ const constantPiece = /^(?:apps|libs)\/[^/]+\/lib\/__client\/[^/]+\.cnst\.ts$/;
26
+ const wholeFile = /^(?:apps|libs)\/[^/]+\/lib\/(?:useClient|st)\.ts$/;
27
+ const constantsFile = /^(?:apps|libs)\/[^/]+\/lib\/cnst\.ts$/;
28
+ const storeFile = /^(?:apps|libs)\/[^/]+\/lib\/_?[^/]+\/[^/]+\.store\.ts$/;
29
+ const consequence =
30
+ "Every page of this build loads the whole client runtime instead, not only what it uses. This is a bug in akan: report it with the lines above.";
31
+
32
+ //* What a build loading per module proves about its own output before it is served: each runtime piece loads before
33
+ //* the module importing it, no store file or registration piece is imported back by what it loads, and no page built
34
+ //* to load pieces reaches a file that needs the whole runtime, or every constant for no named reason.
35
+ export class RouteRuntimeCheck {
36
+ static readonly shown = 5;
37
+ readonly #workspaceRoot: string;
38
+ readonly #graph: ClientBundleGraph;
39
+ readonly #narrowed: RouteRuntimeNarrowed | null;
40
+ readonly #reached = new Map<string, Set<string>>();
41
+
42
+ constructor(workspaceRoot: string, graph: ClientBundleGraph, narrowed: RouteRuntimeNarrowed | null = null) {
43
+ this.#workspaceRoot = workspaceRoot;
44
+ this.#graph = graph;
45
+ this.#narrowed = narrowed;
46
+ }
47
+
48
+ get failures(): string[] {
49
+ return [...this.#unordered(), ...this.#cycles(), ...this.#unanswered()];
50
+ }
51
+
52
+ get refusal(): string | null {
53
+ const failures = this.failures;
54
+ if (failures.length === 0) return null;
55
+ const more = failures.length - RouteRuntimeCheck.shown;
56
+ return [
57
+ "[client-runtime] loading per module, this build would not load its modules in order:",
58
+ ...failures.slice(0, RouteRuntimeCheck.shown).map((failure) => ` - ${failure}`),
59
+ ...(more > 0 ? [` - and ${more} more`] : []),
60
+ consequence,
61
+ ].join("\n");
62
+ }
63
+
64
+ //* Each scope file a route loads with a piece of the same scope beside it that repeats part of it. A piece repeats
65
+ //* nothing where the file takes that part from the piece, or the piece answers from the file: one imports the other.
66
+ get repeated(): string[] {
67
+ const routesOf = new Map<string, string[]>();
68
+ for (const [route, entries] of this.#narrowed?.routes ?? []) {
69
+ const loaded = new Set(entries);
70
+ for (const module of loaded)
71
+ for (const { path: imported } of this.#graph.importsByModule.get(module) ?? []) loaded.add(imported);
72
+ const names = new Map([...loaded].map((module) => [module, this.#nameOf(module)]));
73
+ for (const { whole, piece } of repeatable)
74
+ for (const [file, fileName] of names) {
75
+ const scope = fileName.match(whole)?.[1];
76
+ if (!scope) continue;
77
+ for (const [other, otherName] of names) {
78
+ if (otherName.match(piece)?.[1] !== scope) continue;
79
+ if (this.#staticImportsOf(file).includes(other) || this.#staticImportsOf(other).includes(file)) continue;
80
+ const pair = `${fileName} and ${otherName}`;
81
+ routesOf.set(pair, [...(routesOf.get(pair) ?? []), route]);
82
+ }
83
+ }
84
+ }
85
+ return [...routesOf].map(
86
+ ([pair, routes]) =>
87
+ `${pair} both load on ${routes.length} route(s), the first ${routes[0]}: the piece holds again what the file holds`,
88
+ );
89
+ }
90
+
91
+ #nameOf(absPath: string) {
92
+ return path.relative(this.#workspaceRoot, absPath).split(path.sep).join("/");
93
+ }
94
+
95
+ #isPiece(absPath: string) {
96
+ return pieceFile.test(this.#nameOf(absPath));
97
+ }
98
+
99
+ #staticImportsOf(module: string): string[] {
100
+ return (this.#graph.importsByModule.get(module) ?? []).filter(({ lazy }) => !lazy).map((imported) => imported.path);
101
+ }
102
+
103
+ #reachedBy(chunk: string): Set<string> {
104
+ const known = this.#reached.get(chunk);
105
+ if (known) return known;
106
+ const reached = new Set([chunk]);
107
+ for (const next of reached)
108
+ for (const imported of this.#graph.importsByChunk.get(next) ?? []) reached.add(imported);
109
+ this.#reached.set(chunk, reached);
110
+ return reached;
111
+ }
112
+
113
+ //? A registration piece answering from `lib/cnst.ts` is a bare re-export, which the bundler may leave in a chunk
114
+ //? nothing imports: what has to load first is the file it re-exports.
115
+ #loadedFirstFor(piece: string): string[] {
116
+ const answered = constantPiece.test(this.#nameOf(piece)) && this.#narrowed?.wholeConstantReaders?.has(piece);
117
+ return answered ? this.#staticImportsOf(piece) : [piece];
118
+ }
119
+
120
+ #unordered(): string[] {
121
+ const failures: string[] = [];
122
+ for (const [module, chunks] of this.#graph.chunksByModule)
123
+ for (const piece of this.#staticImportsOf(module)) {
124
+ if (!this.#isPiece(piece)) continue;
125
+ const holdersOf = this.#loadedFirstFor(piece).map((first) => this.#graph.chunksByModule.get(first) ?? []);
126
+ const unlinked = chunks.find((chunk) =>
127
+ holdersOf.some((holders) => !holders.some((holder) => this.#reachedBy(chunk).has(holder))),
128
+ );
129
+ if (!unlinked) continue;
130
+ failures.push(
131
+ `${this.#nameOf(module)} needs ${this.#nameOf(piece)} loaded first, but its chunk ${path.basename(unlinked)} does not import the chunk holding that piece`,
132
+ );
133
+ }
134
+ return failures;
135
+ }
136
+
137
+ #cycles(): string[] {
138
+ const failures: string[] = [];
139
+ for (const component of this.#components()) {
140
+ const members = new Set(component);
141
+ const store = component.find((module) => storeFile.test(this.#nameOf(module)));
142
+ const registration = component.find(
143
+ (module) => constantPiece.test(this.#nameOf(module)) && !this.#narrowed?.wholeConstantReaders?.has(module),
144
+ );
145
+ if (!store && registration) {
146
+ const importer = component.find((module) => this.#staticImportsOf(module).includes(registration)) ?? "";
147
+ failures.push(
148
+ `${this.#nameOf(registration)} loads files that import it back through ${this.#nameOf(importer)}, which reads the model before it is registered`,
149
+ );
150
+ }
151
+ if (!store || !component.some((module) => this.#isPiece(module))) continue;
152
+ const pieceOf = (module: string) =>
153
+ this.#staticImportsOf(module).find((imported) => members.has(imported) && this.#isPiece(imported));
154
+ const importer = component.find((module) => !this.#isPiece(module) && pieceOf(module));
155
+ const piece = importer ? pieceOf(importer) : undefined;
156
+ failures.push(
157
+ importer && piece
158
+ ? `${this.#nameOf(store)} imports ${this.#nameOf(importer)}, which loads ${this.#nameOf(piece)}, and that piece imports the store file back before it is defined: move what ${this.#nameOf(importer)} reads from the store out of the files a store file imports`
159
+ : `${this.#nameOf(store)} is imported back by a runtime piece it loads`,
160
+ );
161
+ }
162
+ return failures;
163
+ }
164
+
165
+ #unanswered(): string[] {
166
+ if (!this.#narrowed) return [];
167
+ const failures: string[] = [];
168
+ const { entries, wholeReaders, wholeConstantReaders = new Set<string>() } = this.#narrowed;
169
+ for (const [buildEntry, entry] of entries) {
170
+ const importerOf = this.#importersFrom([buildEntry]);
171
+ const narrowed = `${this.#nameOf(entry)} was built to load only the modules its code names`;
172
+ const reader = [...importerOf.keys()].find((module) => wholeReaders.has(module));
173
+ const whole = [...importerOf.keys()].find((module) => wholeFile.test(this.#nameOf(module)));
174
+ const constantsOf = this.#importersFrom([buildEntry], wholeConstantReaders);
175
+ //? An entry no route holds takes its models from pieces answering from `lib/cnst.ts`, and their constant files
176
+ //? stay as written: what a named file already loads costs the page nothing by another path.
177
+ const named = this.#importersFrom([...constantsOf.keys()].filter((module) => wholeConstantReaders.has(module)));
178
+ const constants = [...constantsOf.keys()].find(
179
+ (module) => constantsFile.test(this.#nameOf(module)) && !named.has(module),
180
+ );
181
+ if (reader) failures.push(`${narrowed}, but it reaches ${this.#nameOf(reader)}, which needs every module`);
182
+ else if (whole)
183
+ failures.push(
184
+ `${narrowed}, but ${this.#nameOf(importerOf.get(whole) ?? whole)} imports ${this.#nameOf(whole)}, the runtime of every module`,
185
+ );
186
+ else if (constants)
187
+ failures.push(
188
+ `${narrowed}, but ${this.#nameOf(constantsOf.get(constants) ?? constants)} imports ${this.#nameOf(constants)}, the constants of every model, for no reason \`akan quality runtime\` names`,
189
+ );
190
+ }
191
+ return failures;
192
+ }
193
+
194
+ #importersFrom(roots: string[], stops: ReadonlySet<string> = new Set()): Map<string, string> {
195
+ const importerOf = new Map(roots.map((root) => [root, root]));
196
+ for (const module of importerOf.keys()) {
197
+ if (stops.has(module)) continue;
198
+ for (const imported of this.#staticImportsOf(module))
199
+ if (!importerOf.has(imported)) importerOf.set(imported, module);
200
+ }
201
+ return importerOf;
202
+ }
203
+
204
+ //? Tarjan's algorithm with its own stack: a real import chain is deeper than the call stack allows.
205
+ #components(): string[][] {
206
+ const index = new Map<string, number>();
207
+ const low = new Map<string, number>();
208
+ const open: string[] = [];
209
+ const onStack = new Set<string>();
210
+ const components: string[][] = [];
211
+ for (const root of this.#graph.importsByModule.keys()) {
212
+ if (index.has(root)) continue;
213
+ const frames: { module: string; imports: string[]; next: number }[] = [];
214
+ const enter = (module: string) => {
215
+ index.set(module, index.size);
216
+ low.set(module, index.size - 1);
217
+ open.push(module);
218
+ onStack.add(module);
219
+ frames.push({ module, imports: this.#staticImportsOf(module), next: 0 });
220
+ };
221
+ enter(root);
222
+ while (frames.length > 0) {
223
+ const frame = frames[frames.length - 1];
224
+ if (!frame) break;
225
+ const imported = frame.imports[frame.next++];
226
+ const lowOf = (module: string) => low.get(module) ?? 0;
227
+ if (imported === undefined) {
228
+ frames.pop();
229
+ const parent = frames[frames.length - 1];
230
+ if (parent) low.set(parent.module, Math.min(lowOf(parent.module), lowOf(frame.module)));
231
+ if (lowOf(frame.module) !== index.get(frame.module)) continue;
232
+ const component = open.splice(open.lastIndexOf(frame.module));
233
+ for (const module of component) onStack.delete(module);
234
+ if (component.length > 1) components.push(component);
235
+ } else if (!index.has(imported)) enter(imported);
236
+ else if (onStack.has(imported)) low.set(frame.module, Math.min(lowOf(frame.module), index.get(imported) ?? 0));
237
+ }
238
+ }
239
+ return components;
240
+ }
241
+ }
@@ -0,0 +1,137 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { tempDirs, writeText } from "../test/testHelpers";
4
+ import { RouteRuntimePays } from "./routeRuntimePays";
5
+
6
+ const makeTempRoot = tempDirs("akan-devkit-route-pays-");
7
+
8
+ interface Measured {
9
+ routes: Record<string, string[]>;
10
+ whole: Record<string, number>;
11
+ measured: Record<string, number>;
12
+ kept?: string[];
13
+ refused?: string[];
14
+ }
15
+
16
+ const decide = ({ routes, whole, measured, kept = [], refused = [] }: Measured) =>
17
+ RouteRuntimePays.decide({
18
+ entriesByRoute: new Map(Object.entries(routes)),
19
+ isKept: (entry) => kept.includes(entry),
20
+ isRefused: (entry) => refused.includes(entry),
21
+ whole: new Map(Object.entries(whole)),
22
+ measured: new Map(Object.entries(measured)),
23
+ });
24
+
25
+ describe("which entries keep the whole runtime because per module made a page no smaller", () => {
26
+ test("a route smaller per module keeps loading per module", () => {
27
+ expect(decide({ routes: { "/memo": ["Memo"] }, whole: { "/memo": 900 }, measured: { "/memo": 400 } })).toEqual([]);
28
+ });
29
+
30
+ test("a route no smaller per module keeps the whole runtime in the entries only such routes hold", () => {
31
+ const verdicts = decide({
32
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Memo"] },
33
+ whole: { "/board": 900, "/memo": 900 },
34
+ measured: { "/board": 900, "/memo": 400 },
35
+ });
36
+ expect(verdicts).toEqual([
37
+ { entry: "Board", route: "/board", whole: 900, perModule: 900 },
38
+ { entry: "Frame", route: "/board", whole: 900, perModule: 900 },
39
+ ]);
40
+ });
41
+
42
+ test("an entry shared with a route that got smaller stays narrowed while that route gained more than the others lose", () => {
43
+ const routes = { "/board": ["Frame"], "/memo": ["Frame", "Memo"] };
44
+ const whole = { "/board": 900, "/memo": 900 };
45
+ expect(decide({ routes, whole, measured: { "/board": 950, "/memo": 400 } })).toEqual([]);
46
+ expect(decide({ routes, whole, measured: { "/board": 1_500, "/memo": 850 } })).toEqual([
47
+ { entry: "Frame", route: "/board", whole: 900, perModule: 1_500 },
48
+ ]);
49
+ });
50
+
51
+ test("a route an entry already keeps whole is not judged, so judging the same sizes again after keeping changes nothing", () => {
52
+ const measured = {
53
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Frame", "Memo"] },
54
+ whole: { "/board": 900, "/memo": 900 },
55
+ measured: { "/board": 950, "/memo": 400 },
56
+ };
57
+ const first = decide(measured);
58
+ expect(first.map(({ entry }) => entry)).toEqual(["Board"]);
59
+ expect(decide({ ...measured, kept: first.map(({ entry }) => entry) })).toEqual([]);
60
+ });
61
+
62
+ test("an entry a build tried keeping, where a page came out larger, is not named again", () => {
63
+ const measured = {
64
+ routes: { "/board": ["Board", "Frame"], "/memo": ["Memo"] },
65
+ whole: { "/board": 900, "/memo": 900 },
66
+ measured: { "/board": 950, "/memo": 950 },
67
+ };
68
+ expect(decide(measured).map(({ entry }) => entry)).toEqual(["Board", "Frame", "Memo"]);
69
+ expect(decide({ ...measured, refused: ["Board", "Frame"] }).map(({ entry }) => entry)).toEqual(["Memo"]);
70
+ });
71
+
72
+ describe("the build that kept the named entries, against the one before it", () => {
73
+ const routes = { "/board": ["Board"], "/memo": ["Memo"], "/plain": ["Plain"] };
74
+ const larger = (after: Record<string, number>, was: string[] = []) =>
75
+ RouteRuntimePays.larger({
76
+ entriesByRoute: new Map(Object.entries(routes)),
77
+ wasKept: (entry) => was.includes(entry),
78
+ isKept: (entry) => ["Board", "Memo"].includes(entry),
79
+ before: new Map(Object.entries({ "/board": 950, "/memo": 950, "/plain": 400 })),
80
+ after: new Map(Object.entries(after)),
81
+ });
82
+
83
+ test("stands where every route it moved to the whole runtime came out smaller", () => {
84
+ expect(larger({ "/board": 900, "/memo": 949, "/plain": 400 })).toEqual([]);
85
+ });
86
+
87
+ test("names the routes it moved that came out no smaller", () => {
88
+ expect(larger({ "/board": 900, "/memo": 950, "/plain": 400 })).toEqual(["/memo"]);
89
+ expect(larger({ "/board": 1_200, "/memo": 990, "/plain": 300 })).toEqual(["/board", "/memo"]);
90
+ });
91
+
92
+ test("names every route it moved where they shrank and the routes together did not", () => {
93
+ expect(larger({ "/board": 940, "/memo": 940, "/plain": 420 })).toEqual(["/board", "/memo"]);
94
+ });
95
+
96
+ test("judges no route that kept the whole runtime before it", () => {
97
+ expect(larger({ "/board": 900, "/memo": 960, "/plain": 400 }, ["Memo"])).toEqual([]);
98
+ });
99
+ });
100
+
101
+ test("a route is sized by the chunks its entries import statically, a chunk two entries share counted once", async () => {
102
+ const root = await makeTempRoot();
103
+ const chunk = async (name: string, bytes: number) => {
104
+ const file = path.join(root, name);
105
+ await writeText(file, "x".repeat(bytes));
106
+ return file;
107
+ };
108
+ const [board, memo, shared, lazy] = await Promise.all([
109
+ chunk("board.js", 100),
110
+ chunk("memo.js", 200),
111
+ chunk("shared.js", 400),
112
+ chunk("lazy.js", 800),
113
+ ]);
114
+ const sizes = await new RouteRuntimePays().sizesOf(
115
+ {
116
+ entryOutputAbsByAbsPath: new Map([
117
+ ["Board", board],
118
+ ["Memo", memo],
119
+ ]),
120
+ graph: {
121
+ importsByModule: new Map(),
122
+ chunksByModule: new Map(),
123
+ importsByChunk: new Map([
124
+ [board, [shared]],
125
+ [memo, [shared]],
126
+ [lazy, []],
127
+ ]),
128
+ },
129
+ },
130
+ new Map([
131
+ ["/both", ["Board", "Memo"]],
132
+ ["/memo", ["Memo"]],
133
+ ]),
134
+ );
135
+ expect(Object.fromEntries(sizes)).toEqual({ "/both": 700, "/memo": 600 });
136
+ });
137
+ });
@@ -0,0 +1,117 @@
1
+ import type { BundleClientEntriesResult } from "./clientBuildTypes";
2
+ import { chunkBrotliBytesOf } from "./precompressArtifacts";
3
+
4
+ export interface RoutePaysInput {
5
+ //? Every entry a route may load: one of them kept makes the route load the whole runtime.
6
+ entriesByRoute: ReadonlyMap<string, readonly string[]>;
7
+ isKept: (entry: string) => boolean;
8
+ //? An entry a build already tried keeping whole, where a page it holds came out larger: it is never tried again.
9
+ isRefused?: (entry: string) => boolean;
10
+ //? Brotli bytes of the chunks a route loads first, in a build where every entry keeps the whole runtime.
11
+ whole: ReadonlyMap<string, number>;
12
+ //? The same in the build being judged.
13
+ measured: ReadonlyMap<string, number>;
14
+ }
15
+
16
+ export interface RoutePaysVerdict {
17
+ entry: string;
18
+ route: string;
19
+ whole: number;
20
+ perModule: number;
21
+ }
22
+
23
+ export interface RoutePaidInput {
24
+ entriesByRoute: ReadonlyMap<string, readonly string[]>;
25
+ wasKept: (entry: string) => boolean;
26
+ isKept: (entry: string) => boolean;
27
+ before: ReadonlyMap<string, number>;
28
+ after: ReadonlyMap<string, number>;
29
+ }
30
+
31
+ export class RouteRuntimePays {
32
+ readonly #sizes = new Map<string, number>();
33
+
34
+ //* An entry only pages that got no smaller hold is kept. One shared with a page that did get smaller is kept only
35
+ //* where the pages it would spare lose more bytes than the pages it takes the whole runtime to had gained.
36
+ static decide({ entriesByRoute, isKept, isRefused, whole, measured }: RoutePaysInput): RoutePaysVerdict[] {
37
+ const lossOf = (route: string) => (measured.get(route) ?? 0) - (whole.get(route) ?? 0);
38
+ const perModule = [...entriesByRoute].filter(([, entries]) => entries.length > 0 && !entries.some(isKept));
39
+ const gaining = new Map(perModule.filter(([route]) => lossOf(route) < 0));
40
+ const losing = new Map(perModule.filter(([route]) => lossOf(route) >= 0));
41
+ const verdicts = new Map<string, RoutePaysVerdict>();
42
+ const keep = (entry: string, route: string) => {
43
+ if (verdicts.has(entry) || isRefused?.(entry)) return;
44
+ verdicts.set(entry, { entry, route, whole: whole.get(route) ?? 0, perModule: measured.get(route) ?? 0 });
45
+ for (const [other, entries] of gaining) if (entries.includes(entry)) gaining.delete(other);
46
+ for (const [other, entries] of losing) if (entries.includes(entry)) losing.delete(other);
47
+ };
48
+ const heldByGaining = () => new Set([...gaining.values()].flat());
49
+ const shared = heldByGaining();
50
+ for (const [route, entries] of [...losing]) for (const entry of entries) if (!shared.has(entry)) keep(entry, route);
51
+ for (;;) {
52
+ const scores = new Map<string, { score: number; route: string }>();
53
+ for (const [route, entries] of losing)
54
+ for (const entry of entries) {
55
+ const known = scores.get(entry) ?? { score: 0, route };
56
+ scores.set(entry, { score: known.score + lossOf(route), route: known.route });
57
+ }
58
+ for (const [route, entries] of gaining)
59
+ for (const entry of entries) {
60
+ const known = scores.get(entry);
61
+ if (known) known.score += lossOf(route);
62
+ }
63
+ const [best] = [...scores]
64
+ .filter(([entry, { score }]) => score > 0 && !isRefused?.(entry))
65
+ .sort(([a, x], [b, y]) => y.score - x.score || (a < b ? -1 : a > b ? 1 : 0));
66
+ if (!best) break;
67
+ keep(best[0], best[1].route);
68
+ }
69
+ return [...verdicts.values()];
70
+ }
71
+
72
+ //* The all-whole build only nominates: among pages that share chunks, a page kept whole is not the size it has
73
+ //* where every page is. So the build keeping the nominated entries is measured too, and this names the routes it
74
+ //* moved to the whole runtime that came out no smaller than they were, all of them where the routes together did.
75
+ static larger({ entriesByRoute, wasKept, isKept, before, after }: RoutePaidInput): string[] {
76
+ const sizeIn = (sizes: ReadonlyMap<string, number>, route: string) => sizes.get(route) ?? 0;
77
+ const moved = [...entriesByRoute]
78
+ .filter(([, entries]) => !entries.some(wasKept) && entries.some(isKept))
79
+ .map(([route]) => route);
80
+ const larger = moved.filter((route) => sizeIn(after, route) >= sizeIn(before, route));
81
+ if (larger.length > 0) return larger;
82
+ const total = (sizes: ReadonlyMap<string, number>) =>
83
+ [...entriesByRoute.keys()].reduce((sum, route) => sum + sizeIn(sizes, route), 0);
84
+ return total(after) >= total(before) ? moved : [];
85
+ }
86
+
87
+ //? Only what a route's entries import statically counts: a chunk asked for with `import()` is not its first load.
88
+ async sizesOf(
89
+ bundle: Pick<BundleClientEntriesResult, "entryOutputAbsByAbsPath" | "graph">,
90
+ buildEntriesByRoute: ReadonlyMap<string, readonly string[]>,
91
+ ): Promise<Map<string, number>> {
92
+ const sizes = new Map<string, number>();
93
+ for (const [route, buildEntries] of buildEntriesByRoute) {
94
+ const chunks = new Set<string>();
95
+ for (const entry of buildEntries) {
96
+ const output = bundle.entryOutputAbsByAbsPath.get(entry);
97
+ if (output) chunks.add(output);
98
+ }
99
+ for (const chunk of chunks)
100
+ for (const imported of bundle.graph.importsByChunk.get(chunk) ?? []) chunks.add(imported);
101
+ let total = 0;
102
+ for (const chunk of chunks) total += await this.#sizeOf(chunk);
103
+ sizes.set(route, total);
104
+ }
105
+ return sizes;
106
+ }
107
+
108
+ async #sizeOf(chunk: string): Promise<number> {
109
+ const bytes = await Bun.file(chunk).bytes();
110
+ const key = `${bytes.byteLength}:${Bun.hash(bytes).toString(36)}`;
111
+ const known = this.#sizes.get(key);
112
+ if (known !== undefined) return known;
113
+ const size = chunkBrotliBytesOf(bytes);
114
+ this.#sizes.set(key, size);
115
+ return size;
116
+ }
117
+ }
@@ -0,0 +1,60 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { RscServerRendererGuard } from "./rscServerRendererGuard";
6
+
7
+ let root = "";
8
+
9
+ const files = {
10
+ "renderer.ts": `import { renderToReadableStream } from "react-dom/server.edge";\nexport const render = () => renderToReadableStream;\n`,
11
+ "server.ts": `import { render } from "./renderer";\nexport const boot = () => render;\nexport const migrations = ["m1"];\n`,
12
+ "service.ts": `export const report = async () => (await import("./server")).migrations;\n`,
13
+ "dynamicPage.ts": `import { report } from "./service";\nexport const page = () => report;\n`,
14
+ "lazyRenderer.ts": `export const render = async () => (await import("react-dom/server.browser")).renderToReadableStream;\n`,
15
+ "lazyPage.ts": `import { render } from "./lazyRenderer";\nexport const page = () => render;\n`,
16
+ "plainPage.ts": `export const page = () => "plain";\n`,
17
+ };
18
+
19
+ const metafileOf = async (entry: string) => {
20
+ const result = await Bun.build({
21
+ entrypoints: [path.join(root, entry)],
22
+ outdir: path.join(root, "out", entry),
23
+ target: "bun",
24
+ format: "esm",
25
+ metafile: true,
26
+ external: ["react-dom/*"],
27
+ });
28
+ expect(result.success).toBe(true);
29
+ return result.metafile;
30
+ };
31
+
32
+ beforeAll(async () => {
33
+ root = await mkdtemp(path.join(tmpdir(), "rsc-guard-"));
34
+ for (const [file, source] of Object.entries(files)) await writeFile(path.join(root, file), source);
35
+ });
36
+
37
+ afterAll(async () => {
38
+ await rm(root, { recursive: true, force: true });
39
+ });
40
+
41
+ describe("RscServerRendererGuard", () => {
42
+ test("names the chain from the page through the dynamic import of the server entry to the renderer", async () => {
43
+ const assertion = (async () => RscServerRendererGuard.assert(await metafileOf("dynamicPage.ts"), root))();
44
+
45
+ await expect(assertion).rejects.toThrow(
46
+ [
47
+ "where that import throws. It is reached through:",
48
+ " dynamicPage.ts",
49
+ " → service.ts",
50
+ " → import() server.ts",
51
+ " → renderer.ts",
52
+ ].join("\n"),
53
+ );
54
+ });
55
+
56
+ test("passes a page whose renderer import waits inside a function, and one that reaches no renderer", async () => {
57
+ for (const entry of ["lazyPage.ts", "plainPage.ts"])
58
+ expect(RscServerRendererGuard.offenders((await metafileOf(entry)) as Bun.BuildMetafile)).toEqual([]);
59
+ });
60
+ });
@@ -0,0 +1,68 @@
1
+ import { realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ interface ImportEdge {
5
+ from: string;
6
+ dynamic: boolean;
7
+ }
8
+
9
+ //? Every `react-dom/server` entry resolves to `server.react-server.js` under the react-server condition, which throws.
10
+ const SERVER_RENDERER_RE = /^react-dom\/server(?:\.\w+)?$/;
11
+
12
+ export class RscServerRendererGuard {
13
+ //? Bun keeps an external `import` after tree-shaking drops its bindings, and hoists one out of a lazily wrapped module.
14
+ static offenders(metafile: Bun.BuildMetafile): { input: string; specifier: string }[] {
15
+ const offenders: { input: string; specifier: string }[] = [];
16
+ const included = new Set(
17
+ Object.values(metafile.outputs).flatMap((output) =>
18
+ Object.entries(output.inputs)
19
+ .filter(([, { bytesInOutput }]) => bytesInOutput > 0)
20
+ .map(([input]) => input),
21
+ ),
22
+ );
23
+ for (const input of included)
24
+ for (const edge of metafile.inputs[input]?.imports ?? [])
25
+ if (edge.external && edge.kind === "import-statement" && SERVER_RENDERER_RE.test(edge.path))
26
+ offenders.push({ input, specifier: edge.path });
27
+ return offenders;
28
+ }
29
+
30
+ static chain(metafile: Bun.BuildMetafile, target: string): { input: string; dynamic: boolean }[] {
31
+ const entries = Object.values(metafile.outputs).flatMap((output) => (output.entryPoint ? [output.entryPoint] : []));
32
+ const reached = new Map<string, ImportEdge | null>(entries.map((entry) => [entry, null]));
33
+ const queue = [...entries];
34
+ for (let input = queue.shift(); input !== undefined && !reached.has(target); input = queue.shift())
35
+ for (const edge of metafile.inputs[input]?.imports ?? []) {
36
+ if (edge.external || reached.has(edge.path)) continue;
37
+ reached.set(edge.path, {
38
+ from: input,
39
+ dynamic: edge.kind === "dynamic-import" || edge.kind === "require-call",
40
+ });
41
+ queue.push(edge.path);
42
+ }
43
+ const chain: { input: string; dynamic: boolean }[] = [];
44
+ for (let input: string | undefined = target; input !== undefined; ) {
45
+ const edge: ImportEdge | null | undefined = reached.get(input);
46
+ chain.unshift({ input, dynamic: edge?.dynamic ?? false });
47
+ input = edge?.from;
48
+ }
49
+ return chain;
50
+ }
51
+
52
+ static assert(metafile: Bun.BuildMetafile | undefined, workspaceRoot: string) {
53
+ const [offender] = metafile ? RscServerRendererGuard.offenders(metafile) : [];
54
+ if (!metafile || !offender) return;
55
+ const root = realpathSync(workspaceRoot);
56
+ const shown = (input: string) => path.relative(root, path.resolve(input)) || input;
57
+ const lines = RscServerRendererGuard.chain(metafile, offender.input).map(
58
+ ({ input, dynamic }, idx) => ` ${idx === 0 ? "" : dynamic ? "→ import() " : "→ "}${shown(input)}`,
59
+ );
60
+ throw new Error(
61
+ [
62
+ `[PagesBundleBuilder] The server pages bundle imports ${offender.specifier} as it loads, and the RSC worker runs under the react-server condition, where that import throws. It is reached through:`,
63
+ ...lines,
64
+ "A module in the page graph that imports the app's server entry, or anything that starts the server, brings the SSR renderer with it: import only what that module uses, or hand it in from the code that boots the server.",
65
+ ].join("\n"),
66
+ );
67
+ }
68
+ }