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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/CHANGELOG.md +618 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanApp/akanApp.host.ts +11 -0
  7. package/akanConfig/akanBin.ts +4 -0
  8. package/akanConfig/akanConfig.test.ts +66 -7
  9. package/akanConfig/akanConfig.ts +53 -204
  10. package/akanConfig/akanWorkers.test.ts +39 -0
  11. package/akanConfig/akanWorkers.ts +32 -0
  12. package/akanConfig/desktopServerConfig.ts +96 -0
  13. package/akanConfig/dockerImage.ts +37 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/akanConfig/types.ts +1 -0
  16. package/app/appBin.test.ts +63 -0
  17. package/app/appBin.ts +50 -0
  18. package/app/applicationBuildReporter.test.ts +32 -0
  19. package/app/applicationBuildReporter.ts +4 -0
  20. package/app/applicationBuildRunner.test.ts +275 -0
  21. package/app/applicationBuildRunner.ts +133 -6
  22. package/app/dictionarySizes.ts +91 -0
  23. package/app/routeFilesReport.test.ts +59 -0
  24. package/app/routeFilesReport.ts +46 -0
  25. package/app/routeJsBudget.ts +18 -4
  26. package/artifact/implicitRootLayout.test.ts +19 -0
  27. package/artifact/implicitRootLayout.ts +16 -2
  28. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  29. package/artifact/storeBootstrap.test.ts +28 -0
  30. package/artifact/storeBootstrap.ts +64 -8
  31. package/biome.base.json +6 -4
  32. package/codeAgent/agent/CodeAgent.ts +36 -16
  33. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  34. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  35. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  36. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  37. package/codeAgent/agent/codeAgent.test.ts +62 -0
  38. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  39. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  40. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  41. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  42. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  43. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  44. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  46. package/codeAgent/skills/akan-page/SKILL.md +31 -20
  47. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  48. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  49. package/codeAgent/skills/akan-service/SKILL.md +2 -5
  50. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  51. package/codeAgent/skills/akan-ui/SKILL.md +2 -5
  52. package/context/akanContext.ts +2 -0
  53. package/docs/apiReference.test.ts +9 -0
  54. package/docs/apiReference.ts +14 -0
  55. package/executors/appExecutor.ts +3 -1
  56. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  57. package/executors/clientRuntimeKeys.fixture.json +393 -0
  58. package/executors/clientRuntimeKeys.test.ts +1690 -0
  59. package/executors/executors.test.ts +2 -0
  60. package/executors/sysExecutor.ts +70 -4
  61. package/executors/workspaceExecutor.ts +7 -4
  62. package/frontendBuild/allRoutesBuilder.ts +88 -7
  63. package/frontendBuild/autoImportSync.ts +3 -2
  64. package/frontendBuild/buildRouteClient.test.ts +580 -12
  65. package/frontendBuild/clientBuildTypes.ts +26 -0
  66. package/frontendBuild/clientEntriesBundler.ts +49 -1
  67. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  68. package/frontendBuild/clientEntryDiscovery.ts +135 -13
  69. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  70. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  71. package/frontendBuild/csrDevPatcher.ts +33 -7
  72. package/frontendBuild/csrDevTypes.ts +9 -0
  73. package/frontendBuild/devBarrelImports.test.ts +154 -0
  74. package/frontendBuild/devBarrelImports.ts +83 -23
  75. package/frontendBuild/devRegistryBundler.ts +4 -2
  76. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  77. package/frontendBuild/devRouteRuntime.ts +167 -0
  78. package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
  79. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  80. package/frontendBuild/dictionaryConstants.ts +136 -0
  81. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  82. package/frontendBuild/dictionaryPacking.ts +135 -0
  83. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  84. package/frontendBuild/dictionaryRoutes.ts +227 -0
  85. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  86. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  87. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  88. package/frontendBuild/precompressArtifacts.ts +22 -8
  89. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  90. package/frontendBuild/renderedEntries.ts +144 -0
  91. package/frontendBuild/routeClientBuilder.ts +340 -29
  92. package/frontendBuild/routeHandoffs.test.ts +155 -0
  93. package/frontendBuild/routeHandoffs.ts +117 -0
  94. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  95. package/frontendBuild/routeModulePreloads.ts +20 -11
  96. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  97. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  98. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  99. package/frontendBuild/routeRuntimePays.ts +117 -0
  100. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  101. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  102. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  103. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  104. package/frontendBuild/ssrDevBundler.ts +66 -11
  105. package/frontendBuild/vendorFileImports.test.ts +254 -0
  106. package/frontendBuild/vendorFileImports.ts +163 -0
  107. package/frontendBuild/vendorNarrowing.ts +28 -0
  108. package/frontendBuild/vendorSpecifiers.ts +2 -0
  109. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  110. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  111. package/incrementalBuilder/builderBoot.ts +5 -5
  112. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  113. package/incrementalBuilder/builderLanes.ts +2 -2
  114. package/incrementalBuilder/builderWatch.ts +8 -8
  115. package/incrementalBuilder/csrRegistry.ts +4 -4
  116. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  117. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  118. package/incrementalBuilder/ssrRegistry.ts +6 -6
  119. package/index.ts +1 -1
  120. package/integration/renderAdmissionSoak.test.ts +99 -0
  121. package/integration/renderAdmissionSoak.ts +609 -0
  122. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  123. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  124. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  125. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  126. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  127. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  128. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  129. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  130. package/lint/biomeBase.test.ts +23 -3
  131. package/lint/biomeCheck.test.ts +145 -0
  132. package/lint/biomeCheck.ts +131 -0
  133. package/lint/no-arbitrary-color.grit +5 -0
  134. package/lint/no-conditional-st-hook.grit +5 -1
  135. package/lint/no-daisyui-legacy-class.grit +8 -0
  136. package/lint/no-document-cookie.grit +3 -0
  137. package/lint/no-inline-color.grit +10 -2
  138. package/lint/no-oversized-list-limit.grit +2 -0
  139. package/lint/no-raw-palette-class.grit +7 -0
  140. package/lint/no-unpublished-form-setter.grit +2 -0
  141. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  142. package/lint/no-web-storage.grit +3 -0
  143. package/lint/withheldEnvFile.ts +17 -0
  144. package/mobile/desktopBin.ts +2 -2
  145. package/mobile/desktopServerStage.ts +1 -0
  146. package/mobile/nativeApp.test.ts +7 -5
  147. package/mobile/nativeApp.ts +2 -2
  148. package/mobile/nativeConfig.test.ts +96 -1
  149. package/mobile/nativeConfig.ts +46 -12
  150. package/mobile/serverBundleSecrets.ts +43 -0
  151. package/package.json +15 -169
  152. package/packageExports.test.ts +38 -24
  153. package/quality/dictionaryKeys.test.ts +356 -0
  154. package/quality/dictionaryKeys.ts +488 -0
  155. package/quality/objectImportReport.test.ts +36 -0
  156. package/quality/objectImportReport.ts +105 -0
  157. package/quality/qualityScanner.ts +1 -1
  158. package/quality/routeRuntimeReport.test.ts +91 -0
  159. package/quality/routeRuntimeReport.ts +121 -0
  160. package/quality/runtimeConstantFacts.ts +71 -0
  161. package/quality/runtimeConstantGraph.ts +123 -0
  162. package/quality/runtimeConstantReads.ts +116 -0
  163. package/quality/runtimeImports.test.ts +190 -0
  164. package/quality/runtimeImports.ts +233 -0
  165. package/quality/runtimeKeyNames.ts +46 -0
  166. package/quality/runtimeLexicalScope.ts +132 -0
  167. package/quality/runtimeMarkerReach.test.ts +84 -0
  168. package/quality/runtimeMarkerReach.ts +255 -0
  169. package/quality/runtimeModuleFacts.ts +290 -0
  170. package/quality/runtimeNameTable.test.ts +172 -0
  171. package/quality/runtimeNameTable.ts +477 -0
  172. package/quality/runtimeScopeReport.test.ts +123 -0
  173. package/quality/runtimeScopeReport.ts +167 -0
  174. package/quality/runtimeSliceKey.ts +269 -0
  175. package/quality/runtimeSyntax.ts +133 -0
  176. package/quality/runtimeTable.fixture.ts +189 -0
  177. package/quality/runtimeUse.test.ts +737 -0
  178. package/quality/runtimeUse.ts +696 -0
  179. package/quality/runtimeUseReadable.test.ts +393 -0
  180. package/quality/ssrScanner.test.ts +13 -0
  181. package/quality/ssrScanner.ts +1 -1
  182. package/quality/translatorBindings.ts +187 -0
  183. package/test/secretEnvFixture.ts +134 -0
  184. package/test/testHelpers.ts +11 -0
  185. package/transforms/barrelAnalyzer.ts +26 -4
  186. package/transforms/barrelImportsPlugin.ts +121 -32
  187. package/transforms/exportReach.test.ts +162 -0
  188. package/transforms/exportReach.ts +308 -0
  189. package/transforms/frameworkObjects.fixture.tsx +58 -0
  190. package/transforms/frameworkObjects.test.ts +54 -0
  191. package/transforms/modelReference.test.ts +196 -0
  192. package/transforms/modelReference.ts +39 -0
  193. package/transforms/moduleParts.test.ts +225 -0
  194. package/transforms/moduleParts.ts +418 -0
  195. package/transforms/objectImportEdits.ts +150 -0
  196. package/transforms/objectMemberImports.test.ts +629 -0
  197. package/transforms/objectMemberImports.ts +571 -0
  198. package/transforms/objectMemberLookup.ts +150 -0
  199. package/transforms/objectModule.test.ts +307 -0
  200. package/transforms/objectModule.ts +482 -0
  201. package/transforms/objectModuleAnalyzer.ts +104 -0
  202. package/transforms/partImports.test.ts +76 -0
  203. package/transforms/partImports.ts +110 -0
  204. package/transforms/partModules.test.ts +187 -0
  205. package/transforms/partModules.ts +90 -0
  206. package/transforms/partPurity.ts +124 -0
  207. package/transforms/reactIconImports.test.ts +231 -0
  208. package/transforms/reactIconImports.ts +325 -0
  209. package/transforms/routeConstants.ts +122 -0
  210. package/transforms/routeRuntime.test.ts +835 -0
  211. package/transforms/routeRuntime.ts +703 -0
  212. package/transforms/routeRuntimeEdits.ts +92 -0
  213. package/transforms/routeRuntimeGraph.ts +66 -0
  214. package/transforms/routeRuntimePlan.ts +244 -0
  215. package/transforms/secretEnvDeclaration.test.ts +208 -0
  216. package/transforms/secretEnvDeclaration.ts +213 -0
  217. package/transforms/secretEnvFile.test.ts +117 -0
  218. package/transforms/secretEnvFile.ts +113 -0
  219. package/transforms/secretEnvName.test.ts +54 -0
  220. package/transforms/secretEnvName.ts +29 -0
  221. package/transforms/secretEnvSource.test.ts +148 -0
  222. package/transforms/secretEnvSource.ts +166 -0
  223. package/transforms/serverEnvEvaluationError.ts +11 -0
  224. package/transforms/serverEnvPlugin.test.ts +2 -1
  225. package/transforms/serverEnvPlugin.ts +13 -0
  226. package/transforms/serverEnvProfile.test.ts +115 -2
  227. package/transforms/serverEnvProfile.ts +117 -40
  228. package/transforms/serverEnvSecrets.test.ts +292 -0
  229. package/transforms/signalDescriptors.test.ts +280 -0
  230. package/transforms/signalDescriptors.ts +227 -0
  231. package/transforms/thisFreeExports.ts +87 -0
  232. package/transforms/transforms.test.ts +180 -3
  233. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  234. package/tunnel/createTunnel.test.ts +29 -8
  235. package/tunnel/createTunnel.ts +18 -11
  236. package/typecheck/projectTypecheck.test.ts +29 -0
  237. package/typecheck/typeChecker.test.ts +49 -0
  238. package/typecheck/typeChecker.ts +9 -7
  239. package/typecheck/withheldDiagnostics.ts +41 -0
  240. package/util/fileEditor.ts +1 -0
  241. package/util/selectModel.ts +1 -0
  242. package/workflow/executor.ts +6 -2
  243. package/workflow/index.ts +1 -0
  244. package/workflow/plan.ts +36 -7
  245. package/workflow/types.ts +1 -1
  246. package/workflow/uiTarget.ts +50 -0
  247. package/workspace/getRelatedCnsts.ts +7 -0
  248. package/workspace/scanInfo.test.ts +39 -0
  249. package/workspace/scanInfo.ts +48 -5
  250. package/workspace/workspaceLayout.ts +1 -0
@@ -8,6 +8,16 @@ import type { App } from "../commandDecorators";
8
8
  import { AppExecutor, Executor } from "../executors";
9
9
  import { AllRoutesBuilder, type BuildAllRoutesResult, VendorNarrowing } from "../frontendBuild";
10
10
  import { bundleDefine } from "../frontendBuild/bundleDefine";
11
+ import {
12
+ computedSecretKeys,
13
+ computedSecrets,
14
+ holdsSentinel,
15
+ secretEnvSentinels,
16
+ twinSecretEnv,
17
+ twinSecrets,
18
+ writeComputedSecretFixture,
19
+ writeSecretEnvFixture,
20
+ } from "../test/secretEnvFixture";
11
21
  import { createTempApp } from "../test/testHelpers";
12
22
  import { ProjectTypecheck } from "../typecheck/projectTypecheck";
13
23
  import { AKAN_BACKEND_MINIFY, AKAN_OPTIONAL_BACKEND_EXTERNALS, ApplicationBuildRunner } from "./applicationBuildRunner";
@@ -71,6 +81,7 @@ console.info(new SampleService().name);
71
81
  );
72
82
  const app = {
73
83
  getConfig: async () => config,
84
+ getScanInfo: () => ({ getLibs: () => [] }),
74
85
  dist: new Executor("dist", root),
75
86
  workspace: { workspaceRoot: root },
76
87
  logger: { warn: () => undefined },
@@ -96,6 +107,7 @@ console.info(new SampleService().name);
96
107
  );
97
108
  const app = {
98
109
  getConfig: async () => config,
110
+ getScanInfo: () => ({ getLibs: () => [] }),
99
111
  dist: new Executor("dist", root),
100
112
  workspace: { workspaceRoot: root },
101
113
  logger: { warn: () => undefined },
@@ -121,6 +133,268 @@ console.info(new SampleService().name);
121
133
  }
122
134
  });
123
135
 
136
+ test("an image build names the secrets its server reads beside main.js and in its Dockerfile, and holds no value of them", async () => {
137
+ const { root, workspace } = await createTempApp("portal");
138
+ await writeSecretEnvFixture(root, { app: "portal" });
139
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
140
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
141
+ for (const key of keys) delete process.env[key];
142
+ await writeFile(
143
+ path.join(root, ".env"),
144
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
145
+ );
146
+ const metaOf = async (options: ConstructorParameters<typeof ApplicationBuildRunner>[1]) => {
147
+ const app = AppExecutor.from(workspace, "portal");
148
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
149
+ app.prepareCommand = async () => {
150
+ throw new Error("stopped before the phases");
151
+ };
152
+ const runner = new ApplicationBuildRunner(app, options);
153
+ await expect(runner.build()).rejects.toThrow("stopped before the phases");
154
+ await runner.buildAppMeta();
155
+ const env = JSON.parse(await readFile(path.join(app.dist.cwdPath, "akan.env.json"), "utf8")) as {
156
+ [key: string]: string;
157
+ };
158
+ const dockerfile = await readFile(path.join(app.dist.cwdPath, "Dockerfile"), "utf8");
159
+ const dockerfileEnv = Object.fromEntries(
160
+ dockerfile
161
+ .split("\n")
162
+ .filter((line) => line.startsWith("ENV "))
163
+ .map((line) => line.slice("ENV ".length).split(/=(.*)/s).slice(0, 2)),
164
+ );
165
+ expect(env).toEqual(dockerfileEnv);
166
+ expect(holdsSentinel(`${JSON.stringify(env)}${dockerfile}`)).toBe(false);
167
+ return env;
168
+ };
169
+ const names =
170
+ "JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,MAILER__AUTH__PASS,OBJECT_STORAGE__ENDPOINT,DISCORD__TOKENS:json,DISCORD__WEBHOOK,PUSH_NOTI__FIREBASE__PRIVATE_KEY:multiline,MESSAGE__API_SECRET,MESSAGE__SENDER_PASSWORD,POSTGRES_URL";
171
+ try {
172
+ const read = await metaOf({ secretEnv: "read" });
173
+ expect(read.AKAN_ENV_NAMES).toBe(names);
174
+ expect(read).not.toHaveProperty("AKAN_ENV_FALLBACK");
175
+ expect(await metaOf({ secretEnv: "inline" })).toMatchObject({
176
+ AKAN_ENV_NAMES: names,
177
+ AKAN_ENV_FALLBACK: "image",
178
+ });
179
+ const carried = await metaOf({});
180
+ expect(carried).not.toHaveProperty("AKAN_ENV_NAMES");
181
+ expect(carried).not.toHaveProperty("AKAN_ENV_FALLBACK");
182
+ } finally {
183
+ for (const key of keys) {
184
+ if (shellEnv[key] === undefined) delete process.env[key];
185
+ else process.env[key] = shellEnv[key];
186
+ }
187
+ await rm(root, { recursive: true, force: true });
188
+ }
189
+ });
190
+
191
+ test("an image build stops before any phase at a secret whose variable the platform owns, without printing it", async () => {
192
+ const { root, workspace } = await createTempApp("portal");
193
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n pwd: "sentinel-pwd-1b84",' });
194
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
195
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
196
+ for (const key of keys) delete process.env[key];
197
+ await writeFile(
198
+ path.join(root, ".env"),
199
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
200
+ );
201
+ const app = AppExecutor.from(workspace, "portal");
202
+ let prepared = false;
203
+ app.prepareCommand = async () => {
204
+ prepared = true;
205
+ throw new Error("prepared");
206
+ };
207
+ try {
208
+ const failure = await new ApplicationBuildRunner(app, { secretEnv: "read" })
209
+ .build()
210
+ .catch((error: Error) => error.message);
211
+ expect(failure).toContain("`pwd` is a secret a build would read from the environment variable PWD");
212
+ expect(holdsSentinel(String(failure))).toBe(false);
213
+ expect(prepared).toBe(false);
214
+ } finally {
215
+ for (const key of keys) {
216
+ if (shellEnv[key] === undefined) delete process.env[key];
217
+ else process.env[key] = shellEnv[key];
218
+ }
219
+ await rm(root, { recursive: true, force: true });
220
+ }
221
+ });
222
+
223
+ test("an env file that needs a variable of the shell to load builds with it set; without it a build stops at the place, and an --inline-secrets build warns and holds the env as written", async () => {
224
+ const { root, workspace } = await createTempApp("portal");
225
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: '\n hosts: process.env.ZQ_HOSTS!.split(","),' });
226
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN", "ZQ_HOSTS"] as const;
227
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
228
+ for (const key of keys) delete process.env[key];
229
+ await writeFile(
230
+ path.join(root, ".env"),
231
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
232
+ );
233
+ const started = async (secretEnv: "read" | "inline") => {
234
+ const app = AppExecutor.from(workspace, "portal");
235
+ const warnings: string[] = [];
236
+ spyOn(app.logger, "warn").mockImplementation((message: string) => {
237
+ warnings.push(message);
238
+ });
239
+ app.prepareCommand = async () => {
240
+ throw new Error("stopped before the phases");
241
+ };
242
+ const runner = new ApplicationBuildRunner(app, { secretEnv });
243
+ const failure = await runner.build().then(
244
+ () => "",
245
+ (error: Error) => error.message,
246
+ );
247
+ return { app, runner, failure, warnings };
248
+ };
249
+ const envOf = async ({ app, runner }: Awaited<ReturnType<typeof started>>) => {
250
+ await runner.buildAppMeta();
251
+ return JSON.parse(await readFile(path.join(app.dist.cwdPath, "akan.env.json"), "utf8")) as {
252
+ [key: string]: string;
253
+ };
254
+ };
255
+ const place =
256
+ /env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+/;
257
+ try {
258
+ const stopped = await started("read");
259
+ expect(stopped.failure).toMatch(place);
260
+ expect(stopped.failure).toContain("Make the file load at that line");
261
+ expect(holdsSentinel(stopped.failure)).toBe(false);
262
+
263
+ const inlined = await started("inline");
264
+ expect(inlined.failure).toBe("stopped before the phases");
265
+ expect(inlined.warnings).toHaveLength(1);
266
+ expect(inlined.warnings[0]).toMatch(place);
267
+ expect(inlined.warnings[0]).toStartWith("--inline-secrets: env.server.ts could not be evaluated");
268
+ expect(holdsSentinel(inlined.warnings.join())).toBe(false);
269
+ const written = await envOf(inlined);
270
+ expect(written).not.toHaveProperty("AKAN_ENV_NAMES");
271
+ expect(written).not.toHaveProperty("AKAN_ENV_FALLBACK");
272
+
273
+ process.env.ZQ_HOSTS = "a.example.test,b.example.test";
274
+ const built = await started("read");
275
+ expect(built.failure).toBe("stopped before the phases");
276
+ expect((await envOf(built)).AKAN_ENV_NAMES).toStartWith("JWT_SECRET,SECURITY__SSO__GOOGLE__CLIENT_SECRET,");
277
+ } finally {
278
+ for (const key of keys) {
279
+ if (shellEnv[key] === undefined) delete process.env[key];
280
+ else process.env[key] = shellEnv[key];
281
+ }
282
+ await rm(root, { recursive: true, force: true });
283
+ }
284
+ });
285
+
286
+ test("an image build stops before any phase at a secret the env file imports or computes, short or plain as it may be, naming the file and the keys alone", async () => {
287
+ const { root, workspace } = await createTempApp("portal");
288
+ await writeComputedSecretFixture(root, "portal");
289
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
290
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
291
+ for (const key of keys) delete process.env[key];
292
+ await writeFile(
293
+ path.join(root, ".env"),
294
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
295
+ );
296
+ const started = async (secretEnv: "read" | "inline") => {
297
+ const app = AppExecutor.from(workspace, "portal");
298
+ spyOn(app.logger, "warn").mockImplementation(() => undefined);
299
+ let prepared = false;
300
+ app.prepareCommand = async () => {
301
+ prepared = true;
302
+ throw new Error("stopped before the phases");
303
+ };
304
+ const failure = await new ApplicationBuildRunner(app, { secretEnv }).build().then(
305
+ () => "",
306
+ (error: Error) => error.message,
307
+ );
308
+ return { failure, prepared: () => prepared };
309
+ };
310
+ try {
311
+ const stopped = await started("read");
312
+ expect(stopped.prepared()).toBe(false);
313
+ expect(stopped.failure).toStartWith(
314
+ `The server env of portal (main) holds 4 secret values this build cannot leave out, so it stops here: ${computedSecretKeys.join(", ")} (apps/portal/env/env.server.ts and what it imports).\n`,
315
+ );
316
+ expect(holdsSentinel(stopped.failure)).toBe(false);
317
+ for (const value of Object.values(computedSecrets)) expect(stopped.failure).not.toContain(value);
318
+ const inlined = await started("inline");
319
+ expect(inlined.prepared()).toBe(true);
320
+ expect(inlined.failure).toBe("stopped before the phases");
321
+ } finally {
322
+ for (const key of keys) {
323
+ if (shellEnv[key] === undefined) delete process.env[key];
324
+ else process.env[key] = shellEnv[key];
325
+ }
326
+ await rm(root, { recursive: true, force: true });
327
+ }
328
+ });
329
+
330
+ test("an image build stops before its metadata when a file it wrote holds a secret it left out of the env, and warns of a short one a plain key holds as well", async () => {
331
+ const { root, workspace } = await createTempApp("portal");
332
+ await writeSecretEnvFixture(root, { app: "portal", mainExtra: twinSecretEnv.split("\n").slice(0, 3).join("\n") });
333
+ const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
334
+ const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
335
+ for (const key of keys) delete process.env[key];
336
+ await writeFile(
337
+ path.join(root, ".env"),
338
+ "AKAN_PUBLIC_ENV=main\nAKAN_PUBLIC_REPO_NAME=repo\nAKAN_PUBLIC_SERVE_DOMAIN=akanjs.com\n",
339
+ );
340
+ const runnerOf = async (secretEnv: "read" | "inline") => {
341
+ const app = AppExecutor.from(workspace, "portal");
342
+ const warnings: string[] = [];
343
+ spyOn(app.logger, "warn").mockImplementation((message: string) => {
344
+ warnings.push(message);
345
+ });
346
+ app.prepareCommand = async () => {
347
+ throw new Error("stopped before the phases");
348
+ };
349
+ const runner = new ApplicationBuildRunner(app, { secretEnv });
350
+ await expect(runner.build()).rejects.toThrow("stopped before the phases");
351
+ return { app, runner, warnings };
352
+ };
353
+ try {
354
+ const { app, runner, warnings } = await runnerOf("read");
355
+ await mkdir(app.dist.cwdPath, { recursive: true });
356
+ await writeFile(path.join(app.dist.cwdPath, "server.js"), 'const env = { hostname: "app.example.test" };\n');
357
+ await runner.assertSecretsLeftOut();
358
+ expect(warnings).toEqual([]);
359
+ await writeFile(
360
+ path.join(app.dist.cwdPath, "chunk-a.js"),
361
+ `const cache = { name: ${JSON.stringify(twinSecrets.plain)} };\n`,
362
+ );
363
+ await runner.assertSecretsLeftOut();
364
+ expect(warnings).toHaveLength(1);
365
+ expect(warnings[0]).toContain(
366
+ "\n cache.password (CACHE__PASSWORD): chunk-a.js; the env's cache.name holds the same string\n",
367
+ );
368
+ expect(holdsSentinel(warnings[0] ?? "")).toBe(false);
369
+ await writeFile(
370
+ path.join(app.dist.cwdPath, "chunk-b.js"),
371
+ `const key = ${JSON.stringify(secretEnvSentinels.google)};\nconst label = ${JSON.stringify(twinSecrets.long)};\n`,
372
+ );
373
+ const failure = await runner.assertSecretsLeftOut().then(
374
+ () => "",
375
+ (error: Error) => error.message,
376
+ );
377
+ expect(failure).toStartWith(
378
+ [
379
+ "The build holds secret values the server reads from its process env, so it stops here:",
380
+ " chunk-b.js holds the value of security.sso.google.clientSecret (SECURITY__SSO__GOOGLE__CLIENT_SECRET)",
381
+ " chunk-b.js holds the value of audit.password (AUDIT__PASSWORD), which the env's audit.label holds as well",
382
+ "",
383
+ ].join("\n"),
384
+ );
385
+ expect(holdsSentinel(failure)).toBe(false);
386
+ const inlined = await runnerOf("inline");
387
+ await inlined.runner.assertSecretsLeftOut();
388
+ expect(inlined.warnings.join("\n")).not.toContain("also in what this build wrote");
389
+ } finally {
390
+ for (const key of keys) {
391
+ if (shellEnv[key] === undefined) delete process.env[key];
392
+ else process.env[key] = shellEnv[key];
393
+ }
394
+ await rm(root, { recursive: true, force: true });
395
+ }
396
+ });
397
+
124
398
  test("writes the pruned lockfile beside package.json, or warns and leaves the image's install unlocked", async () => {
125
399
  const root = await mkdtemp(path.join(os.tmpdir(), "akan-build-meta-"));
126
400
  const config = new AkanAppConfig(
@@ -133,6 +407,7 @@ console.info(new SampleService().name);
133
407
  const warnings: string[] = [];
134
408
  const app = {
135
409
  getConfig: async () => config,
410
+ getScanInfo: () => ({ getLibs: () => [] }),
136
411
  dist: new Executor("dist", root),
137
412
  workspace: { workspaceRoot: root },
138
413
  logger: { warn: (message: string) => warnings.push(message) },
@@ -1,8 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { toError } from "akanjs/common";
3
+ import { AppWorkerPath } from "akanjs/server/appWorkerPath";
3
4
  import { BUILD_ENV_FILE } from "akanjs/server/lifecycle/buildEnv";
5
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
4
6
  import type { BunPlugin } from "bun";
7
+ import { AkanBin } from "../akanConfig/akanBin";
5
8
  import { ProductionLockfile } from "../akanConfig/productionLockfile";
9
+ import type { AkanWorkersConfig } from "../akanConfig/types";
6
10
  import type { App } from "../commandDecorators";
7
11
  import { parseEnvFile, WorkspaceExecutor } from "../executors";
8
12
  import {
@@ -14,16 +18,22 @@ import {
14
18
  SsrBaseArtifactBuilder,
15
19
  VendorImportScanner,
16
20
  } from "../frontendBuild";
21
+ import { ServerBundleSecrets } from "../mobile/serverBundleSecrets";
22
+ import { SecretEnvDeclaration, type SecretEnvDeclared } from "../transforms/secretEnvDeclaration";
23
+ import { SecretEnvFile } from "../transforms/secretEnvFile";
24
+ import { ServerEnvEvaluationError } from "../transforms/serverEnvEvaluationError";
17
25
  import { createServerEnvPlugin } from "../transforms/serverEnvPlugin";
18
26
  import { ServerEnvProfile } from "../transforms/serverEnvProfile";
19
27
  import { ProjectTypecheck } from "../typecheck/projectTypecheck";
20
28
  import { Spinner } from "../util/spinner";
21
29
  import type { BaseDevEnv, PackageJson } from "../workspace/types";
30
+ import { AppBin } from "./appBin";
22
31
  import type {
23
32
  ApplicationBuildPhaseResult,
24
33
  ApplicationBuildProgressReporter,
25
34
  ApplicationBuildResult,
26
35
  } from "./applicationBuildReporter";
36
+ import { RouteFilesReport } from "./routeFilesReport";
27
37
  import { RouteJsBudget, type RouteJsBudgetMode, type RouteJsBudgetStatus, type RouteJsSize } from "./routeJsBudget";
28
38
 
29
39
  export interface TypecheckOptions {
@@ -59,6 +69,12 @@ export interface ApplicationBuildRunnerOptions {
59
69
  environment?: string;
60
70
  /** Bundles `env/env.server.<environment>.<profile>.ts`, which may hold no secret, in place of the environment's file. */
61
71
  profile?: string;
72
+ /**
73
+ * An image build's: `read` leaves the server env's secret strings out of the server, which reads each from its process
74
+ * env, and `inline` keeps them in it as what an unset variable falls back to. Unset, as for the server a desktop app
75
+ * carries, or under a `profile`, the env files are bundled as written.
76
+ */
77
+ secretEnv?: "read" | "inline";
62
78
  /**
63
79
  * `enforce` fails on an overage, a route with no entry, or a missing or unreadable akan.budget.json; `update` and
64
80
  * `raise` rewrite the file first; `report` only warns.
@@ -109,6 +125,8 @@ export class ApplicationBuildRunner {
109
125
  #reporter?: BuildProgressReporter;
110
126
  #environment?: string;
111
127
  #profile?: string;
128
+ #secretEnv?: "read" | "inline";
129
+ #secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
112
130
  #budget: RouteJsBudgetMode;
113
131
  #modulesByRoute?: Record<string, string[]>;
114
132
  #spinner?: boolean;
@@ -123,6 +141,7 @@ export class ApplicationBuildRunner {
123
141
  reporter,
124
142
  environment,
125
143
  profile,
144
+ secretEnv,
126
145
  budget = "report",
127
146
  }: ApplicationBuildRunnerOptions = {},
128
147
  ) {
@@ -132,6 +151,7 @@ export class ApplicationBuildRunner {
132
151
  this.#reporter = reporter;
133
152
  this.#environment = environment;
134
153
  this.#profile = profile;
154
+ this.#secretEnv = profile ? undefined : secretEnv;
135
155
  this.#budget = budget;
136
156
  }
137
157
 
@@ -172,6 +192,7 @@ export class ApplicationBuildRunner {
172
192
  //? Before any phase: a profile that would ship a secret stops the build, not the image after it.
173
193
  if (this.#profile)
174
194
  await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile: this.#profile });
195
+ if (this.#secretEnv) await this.#declareSecrets(environment);
175
196
  await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
176
197
  if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
177
198
  await this.#runPhase(
@@ -221,10 +242,68 @@ export class ApplicationBuildRunner {
221
242
  : "no files",
222
243
  );
223
244
  const routeJs = await this.#runBudgetPhase(environment);
245
+ await this.assertSecretsLeftOut();
224
246
  await this.#runPhase("metadata", "Writing production metadata", () => this.buildAppMeta());
247
+ this.#reportSecretEnv(environment);
225
248
  return this.#resultOf(environment, routeJs);
226
249
  }
227
250
 
251
+ //* A build that cannot load the env file cannot say what it left out, so it stops; under --inline-secrets, which
252
+ //* leaves nothing out, it goes on as a build without the setting does.
253
+ async #declareSecrets(environment: string) {
254
+ try {
255
+ this.#secrets = await SecretEnvDeclaration.of(this.#envDir, environment);
256
+ } catch (error) {
257
+ if (!(error instanceof ServerEnvEvaluationError)) throw error;
258
+ if (this.#secretEnv === "read")
259
+ throw new Error(
260
+ `${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
261
+ );
262
+ this.#app.logger.warn(
263
+ `--inline-secrets: ${error.message}. The secret values of the server env could not be listed, so this build holds the env files as written: the server reads no secret from a variable of its process env, and names none at boot.`,
264
+ );
265
+ this.#secretEnv = undefined;
266
+ }
267
+ //? Before any phase, and by the env's value alone: a search of the files written misses a short or a plain one.
268
+ if (this.#secretEnv === "read" && this.#secrets.unmoved.length)
269
+ throw new Error(
270
+ SecretEnvFile.unmovedStop(
271
+ this.#app.name,
272
+ environment,
273
+ path
274
+ .relative(this.#app.workspace.workspaceRoot, path.join(this.#envDir, "env.server.ts"))
275
+ .replaceAll("\\", "/"),
276
+ this.#secrets.unmoved,
277
+ ),
278
+ );
279
+ }
280
+
281
+ //? Before the metadata phase: a build that still holds a secret gets no Dockerfile to build an image from.
282
+ async assertSecretsLeftOut() {
283
+ if (this.#secretEnv !== "read" || !this.#secrets.moved.length) return;
284
+ const { workspaceRoot } = this.#app.workspace;
285
+ const note = await new ServerBundleSecrets(workspaceRoot, this.#app.cwdPath).assertImageClean(
286
+ this.#app.dist.cwdPath,
287
+ this.#secrets.moved,
288
+ );
289
+ if (note) this.#app.logger.warn(note);
290
+ }
291
+
292
+ #reportSecretEnv(environment: string) {
293
+ const { variables } = this.#secrets;
294
+ const { logger, name } = this.#app;
295
+ const names = variables.map((variable) => variable.name).join(", ");
296
+ const count = `${variables.length} secret value${variables.length === 1 ? "" : "s"}`;
297
+ if (variables.length && this.#secretEnv === "inline")
298
+ logger.warn(
299
+ `--inline-secrets keeps ${count} of the server env in this build, where whoever can read the image reads them: ${names}. A variable the deployment sets still wins over the built-in value. akanjs 3.5.0 removes the flag: set them where the server is deployed and build without it.`,
300
+ );
301
+ else if (variables.length)
302
+ logger.info(
303
+ `The server reads ${count} from its process env when it starts, not from this build: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
304
+ );
305
+ }
306
+
228
307
  #runBudgetPhase(environment: string) {
229
308
  return this.#runPhase(
230
309
  "budget",
@@ -305,10 +384,21 @@ export class ApplicationBuildRunner {
305
384
  const environment = this.#environment ?? akanConfig.baseDevEnv.env;
306
385
  const packageJson = akanConfig.getProductionPackageJson();
307
386
  const lockfile = await this.#pruneLockfile(packageJson);
308
- const dockerfile = akanConfig.dockerfileFor(environment, { lockfile: lockfile !== null });
387
+ const env = { ...akanConfig.getProductionEnv(environment), ...this.#secretEnvList() };
388
+ const carried = await new AppBin(this.#app, akanConfig).stageImage(this.#app.dist.cwdPath);
389
+ if (carried.length)
390
+ this.#app.logger.info(
391
+ typeof akanConfig.docker === "string"
392
+ ? `The build carries ${carried.join(", ")} in ${AppBin.dir}/<TARGETARCH>/; apps/${this.#app.name}/akan.config.ts writes its own Dockerfile, which puts that folder on PATH itself (ENV PATH=${AkanBin.imagePath(AppBin.dir)}).`
393
+ : `The image carries ${carried.join(", ")} from bin, first on its PATH.`,
394
+ );
395
+ const dockerfile = akanConfig.dockerfileFor(environment, {
396
+ lockfile: lockfile !== null,
397
+ env: { ...(carried.length ? { PATH: AkanBin.imagePath(AppBin.dir) } : {}), ...env },
398
+ });
309
399
  await Promise.all([
310
400
  this.#app.dist.writeJson("package.json", packageJson),
311
- this.#app.dist.writeJson(BUILD_ENV_FILE, akanConfig.getProductionEnv(environment)),
401
+ this.#app.dist.writeJson(BUILD_ENV_FILE, env),
312
402
  ...(lockfile !== null
313
403
  ? [this.#app.dist.writeFile(`${this.#app.dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile)]
314
404
  : []),
@@ -321,6 +411,15 @@ export class ApplicationBuildRunner {
321
411
  ]);
322
412
  }
323
413
 
414
+ //? Names and kinds alone: the image carries the list of what its deployment owes, never a value.
415
+ #secretEnvList(): Record<string, string> {
416
+ if (!this.#secrets.variables.length) return {};
417
+ return {
418
+ [SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables),
419
+ ...(this.#secretEnv === "inline" ? { [SecretEnv.fallbackKey]: "image" } : {}),
420
+ };
421
+ }
422
+
324
423
  async #pruneLockfile(packageJson: PackageJson): Promise<string | null> {
325
424
  try {
326
425
  return await ProductionLockfile.prune(this.#app.workspace.workspaceRoot, packageJson);
@@ -356,6 +455,7 @@ export class ApplicationBuildRunner {
356
455
  environment: this.#environment ?? baseEnv,
357
456
  environments: ["local", "testing", ...branches],
358
457
  profile: this.#profile,
458
+ secrets: this.#secretEnv,
359
459
  onLibEnv: (file, { profileFile, stripped }) => {
360
460
  if (profileFile || !stripped.length || this.#warnedLibEnvs.has(file)) return;
361
461
  this.#warnedLibEnvs.add(file);
@@ -377,7 +477,7 @@ export class ApplicationBuildRunner {
377
477
  }
378
478
 
379
479
  async #buildBackend() {
380
- const { externalLibs, web, baseDevEnv, branches } = await this.#app.getConfig();
480
+ const { externalLibs, web, baseDevEnv, branches, workers } = await this.#app.getConfig();
381
481
  const backendEntryPoints = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
382
482
  for (const entrypoint of backendEntryPoints) {
383
483
  if (!(await Bun.file(entrypoint).exists())) throw new Error(`Backend entrypoint not found: ${entrypoint}`);
@@ -418,13 +518,34 @@ export class ApplicationBuildRunner {
418
518
  naming: { entry: "console-runtime.[ext]", chunk: "chunk-[hash].[ext]" },
419
519
  });
420
520
  await this.#writeConsoleShim();
421
- const results = [mainResult, serverResult, rscWorkerResult, consoleRuntimeResult];
521
+ const workerResults = await this.#buildWorkers(workers, backendConfig);
522
+ const results = [mainResult, serverResult, rscWorkerResult, consoleRuntimeResult, ...workerResults];
422
523
  return {
423
- entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1),
524
+ entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1) + workerResults.length,
424
525
  outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0), 1),
425
526
  };
426
527
  }
427
528
 
529
+ //* Never a chunk of server.js: the process that runs a worker loads nothing of the server, nor the server of it.
530
+ async #buildWorkers(workers: AkanWorkersConfig, backendConfig: Omit<Bun.BuildConfig, "entrypoints">) {
531
+ const results: Bun.BuildOutput[] = [];
532
+ for (const [name, entry] of Object.entries(workers)) {
533
+ if (!(await Bun.file(entry).exists()))
534
+ throw new Error(
535
+ `apps/${this.#app.name}/akan.config.ts: workers.${name} names ${path.relative(this.#app.workspace.workspaceRoot, entry)}, which does not exist.`,
536
+ );
537
+ results.push(
538
+ await this.#buildOrThrow(`worker ${name}`, {
539
+ ...backendConfig,
540
+ outdir: path.join(this.#app.dist.cwdPath, AppWorkerPath.dir),
541
+ entrypoints: [entry],
542
+ naming: { entry: `${name}.[ext]`, chunk: "chunk-[hash].[ext]" },
543
+ }),
544
+ );
545
+ }
546
+ return results;
547
+ }
548
+
428
549
  async #writeConsoleShim() {
429
550
  await Bun.write(
430
551
  path.join(this.#app.dist.cwdPath, "console.js"),
@@ -484,6 +605,7 @@ void run().catch((error) => {
484
605
  const base = await new SsrBaseArtifactBuilder(this.#app, "build", {
485
606
  serverEnv: this.#serverEnvPlugin(baseDevEnv.env, branches),
486
607
  vendorExports,
608
+ dictionaryRoutes: allRoutes.dictionaryRoutes,
487
609
  }).build();
488
610
  this.#modulesByRoute = (await routes.writeModulePreloads(base.runtimeChunks)).modulesByRoute();
489
611
  return { base, allRoutes };
@@ -493,11 +615,16 @@ void run().catch((error) => {
493
615
  //? verify build skips writing and measures in memory instead.
494
616
  async #measureRouteJs(environment: string): Promise<RouteJsMeasure | null> {
495
617
  if (this.#budget === "off" || !this.#modulesByRoute) return null;
496
- const sizes = await RouteJsBudget.measure(
618
+ const sizeByUrl = await RouteJsBudget.fileSizes(
497
619
  path.join(this.#app.dist.cwdPath, ".akan/artifact"),
498
620
  this.#modulesByRoute,
499
621
  { precompressed: !this.#verify },
500
622
  );
623
+ const sizes = RouteJsBudget.sizesOf(this.#modulesByRoute, sizeByUrl);
624
+ await RouteFilesReport.write(
625
+ this.#app.cwdPath,
626
+ RouteFilesReport.build(this.#app.name, this.#modulesByRoute, sizeByUrl),
627
+ );
501
628
  const budgetPath = path.join(this.#app.cwdPath, RouteJsBudget.fileName);
502
629
  const { summary: status, warnings } = await RouteJsBudget.check(sizes, {
503
630
  mode: this.#budget,
@@ -0,0 +1,91 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import zlib from "node:zlib";
4
+ import type { BaseBuildArtifact, DictAsset } from "akanjs/server";
5
+ import { FontPruner } from "../frontendBuild/fontPruner";
6
+
7
+ export interface DictionaryRouteBytes {
8
+ lightest: number;
9
+ median: number;
10
+ largest: number;
11
+ }
12
+
13
+ export interface DictionarySize {
14
+ lang: string;
15
+ pageBrotliBytes: number;
16
+ apiBrotliBytes?: number;
17
+ //? What a first visit downloads of the dictionary cut by route, over every route.
18
+ routeBrotliBytes?: DictionaryRouteBytes;
19
+ }
20
+
21
+ export class DictionarySizes {
22
+ static of(artifactDir: string): DictionarySize[] {
23
+ const artifactPath = path.join(artifactDir, "base-artifact.json");
24
+ if (!fs.existsSync(artifactPath)) return [];
25
+ const { dictAssets = {}, dictRoutes } = JSON.parse(fs.readFileSync(artifactPath, "utf8")) as Pick<
26
+ BaseBuildArtifact,
27
+ "dictAssets" | "dictRoutes"
28
+ >;
29
+ const brotliOf = (relPath: string) => DictionarySizes.#brotliBytesOf(path.join(artifactDir, relPath));
30
+ const routeIds = dictRoutes ? DictionarySizes.#routeIdsOf(artifactDir, dictRoutes) : [];
31
+ return Object.entries(dictAssets).map(([lang, asset]) => {
32
+ const api = asset.parts?.api;
33
+ const page = brotliOf(asset.relPath);
34
+ const routes =
35
+ dictRoutes && routeIds.length ? DictionarySizes.#routes(asset, page, routeIds, dictRoutes, brotliOf) : null;
36
+ return {
37
+ lang,
38
+ pageBrotliBytes: page,
39
+ ...(api ? { apiBrotliBytes: brotliOf(api.relPath) } : {}),
40
+ ...(routes ? { routeBrotliBytes: routes } : {}),
41
+ };
42
+ });
43
+ }
44
+
45
+ static format({ lang, pageBrotliBytes, apiBrotliBytes, routeBrotliBytes }: DictionarySize): string {
46
+ const { formatBytes } = FontPruner;
47
+ const api = apiBrotliBytes === undefined ? "" : `, API descriptions ${formatBytes(apiBrotliBytes)} where shown`;
48
+ if (!routeBrotliBytes) return `Dictionary ${lang}: ${formatBytes(pageBrotliBytes)} brotli on every page${api}`;
49
+ const { lightest, median, largest } = routeBrotliBytes;
50
+ const visit = `${formatBytes(lightest)} / ${formatBytes(median)} / ${formatBytes(largest)}`;
51
+ return `Dictionary ${lang}: first visit ${visit} brotli on the lightest / median / largest route (whole ${formatBytes(pageBrotliBytes)})${api}`;
52
+ }
53
+
54
+ //? A route the build could not read loads the whole page file, so it counts at that file's size.
55
+ static #routes(
56
+ asset: DictAsset,
57
+ pageBytes: number,
58
+ routeIds: string[],
59
+ dictRoutes: Record<string, number[]>,
60
+ brotliOf: (relPath: string) => number,
61
+ ): DictionaryRouteBytes | null {
62
+ const files = asset.routeParts?.files;
63
+ if (!files) return null;
64
+ const fileBytes = files.map(({ relPath }) => brotliOf(relPath));
65
+ const sizes = routeIds
66
+ .map((routeId) => {
67
+ const parts = dictRoutes[routeId];
68
+ return parts ? parts.reduce((total, idx) => total + (fileBytes[idx] ?? 0), 0) : pageBytes;
69
+ })
70
+ .sort((a, b) => a - b);
71
+ const at = (idx: number) => sizes[idx] ?? 0;
72
+ return { lightest: at(0), median: at(Math.floor((sizes.length - 1) / 2)), largest: at(sizes.length - 1) };
73
+ }
74
+
75
+ static #routeIdsOf(artifactDir: string, dictRoutes: Record<string, number[]>): string[] {
76
+ const seedIndexPath = path.join(artifactDir, "route-seed-index.json");
77
+ if (!fs.existsSync(seedIndexPath)) return Object.keys(dictRoutes);
78
+ const { entries = [] } = JSON.parse(fs.readFileSync(seedIndexPath, "utf8")) as { entries?: { routeId: string }[] };
79
+ return [...new Set(entries.map(({ routeId }) => routeId))];
80
+ }
81
+
82
+ //? The `.br` sidecar is what a browser gets; a build that stops before the compress phase has none.
83
+ static #brotliBytesOf(file: string): number {
84
+ const sidecar = `${file}.br`;
85
+ if (fs.existsSync(sidecar)) return fs.statSync(sidecar).size;
86
+ const raw = fs.readFileSync(file);
87
+ const params = { [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY };
88
+ //? precompressArtifacts writes no `.br` that would be larger than its file, so that file is served, and counted, raw.
89
+ return Math.min(raw.byteLength, zlib.brotliCompressSync(raw, { params }).byteLength);
90
+ }
91
+ }