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

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 (252) hide show
  1. package/CHANGELOG.md +628 -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 +666 -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/clientEntryGroups.test.ts +77 -0
  70. package/frontendBuild/clientEntryGroups.ts +61 -0
  71. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  72. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  73. package/frontendBuild/csrDevPatcher.ts +33 -7
  74. package/frontendBuild/csrDevTypes.ts +9 -0
  75. package/frontendBuild/devBarrelImports.test.ts +154 -0
  76. package/frontendBuild/devBarrelImports.ts +83 -23
  77. package/frontendBuild/devRegistryBundler.ts +4 -2
  78. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  79. package/frontendBuild/devRouteRuntime.ts +167 -0
  80. package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
  81. package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
  82. package/frontendBuild/dictionaryConstants.ts +136 -0
  83. package/frontendBuild/dictionaryPacking.test.ts +142 -0
  84. package/frontendBuild/dictionaryPacking.ts +135 -0
  85. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  86. package/frontendBuild/dictionaryRoutes.ts +227 -0
  87. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  88. package/frontendBuild/pagesBundleBuilder.ts +81 -3
  89. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  90. package/frontendBuild/precompressArtifacts.ts +22 -8
  91. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  92. package/frontendBuild/renderedEntries.ts +144 -0
  93. package/frontendBuild/routeClientBuilder.ts +405 -43
  94. package/frontendBuild/routeHandoffs.test.ts +155 -0
  95. package/frontendBuild/routeHandoffs.ts +117 -0
  96. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  97. package/frontendBuild/routeModulePreloads.ts +20 -11
  98. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  99. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  100. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  101. package/frontendBuild/routeRuntimePays.ts +117 -0
  102. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  103. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  104. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  105. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  106. package/frontendBuild/ssrDevBundler.ts +66 -11
  107. package/frontendBuild/vendorFileImports.test.ts +254 -0
  108. package/frontendBuild/vendorFileImports.ts +163 -0
  109. package/frontendBuild/vendorNarrowing.ts +28 -0
  110. package/frontendBuild/vendorSpecifiers.ts +2 -0
  111. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  112. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  113. package/incrementalBuilder/builderBoot.ts +5 -5
  114. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  115. package/incrementalBuilder/builderLanes.ts +2 -2
  116. package/incrementalBuilder/builderWatch.ts +8 -8
  117. package/incrementalBuilder/csrRegistry.ts +4 -4
  118. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  119. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  120. package/incrementalBuilder/ssrRegistry.ts +6 -6
  121. package/index.ts +1 -1
  122. package/integration/renderAdmissionSoak.test.ts +99 -0
  123. package/integration/renderAdmissionSoak.ts +609 -0
  124. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  125. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  126. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  127. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  128. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  129. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  130. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  131. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  132. package/lint/biomeBase.test.ts +23 -3
  133. package/lint/biomeCheck.test.ts +145 -0
  134. package/lint/biomeCheck.ts +131 -0
  135. package/lint/no-arbitrary-color.grit +5 -0
  136. package/lint/no-conditional-st-hook.grit +5 -1
  137. package/lint/no-daisyui-legacy-class.grit +8 -0
  138. package/lint/no-document-cookie.grit +3 -0
  139. package/lint/no-inline-color.grit +10 -2
  140. package/lint/no-oversized-list-limit.grit +2 -0
  141. package/lint/no-raw-palette-class.grit +7 -0
  142. package/lint/no-unpublished-form-setter.grit +2 -0
  143. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  144. package/lint/no-web-storage.grit +3 -0
  145. package/lint/withheldEnvFile.ts +17 -0
  146. package/mobile/desktopBin.ts +2 -2
  147. package/mobile/desktopServerStage.ts +1 -0
  148. package/mobile/nativeApp.test.ts +7 -5
  149. package/mobile/nativeApp.ts +2 -2
  150. package/mobile/nativeConfig.test.ts +96 -1
  151. package/mobile/nativeConfig.ts +46 -12
  152. package/mobile/serverBundleSecrets.ts +43 -0
  153. package/package.json +15 -169
  154. package/packageExports.test.ts +38 -24
  155. package/quality/dictionaryKeys.test.ts +356 -0
  156. package/quality/dictionaryKeys.ts +488 -0
  157. package/quality/objectImportReport.test.ts +36 -0
  158. package/quality/objectImportReport.ts +105 -0
  159. package/quality/qualityScanner.ts +1 -1
  160. package/quality/routeRuntimeReport.test.ts +91 -0
  161. package/quality/routeRuntimeReport.ts +121 -0
  162. package/quality/runtimeConstantFacts.ts +71 -0
  163. package/quality/runtimeConstantGraph.ts +123 -0
  164. package/quality/runtimeConstantReads.ts +116 -0
  165. package/quality/runtimeImports.test.ts +190 -0
  166. package/quality/runtimeImports.ts +233 -0
  167. package/quality/runtimeKeyNames.ts +46 -0
  168. package/quality/runtimeLexicalScope.ts +132 -0
  169. package/quality/runtimeMarkerReach.test.ts +84 -0
  170. package/quality/runtimeMarkerReach.ts +255 -0
  171. package/quality/runtimeModuleFacts.ts +290 -0
  172. package/quality/runtimeNameTable.test.ts +172 -0
  173. package/quality/runtimeNameTable.ts +477 -0
  174. package/quality/runtimeScopeReport.test.ts +123 -0
  175. package/quality/runtimeScopeReport.ts +167 -0
  176. package/quality/runtimeSliceKey.ts +269 -0
  177. package/quality/runtimeSyntax.ts +133 -0
  178. package/quality/runtimeTable.fixture.ts +189 -0
  179. package/quality/runtimeUse.test.ts +737 -0
  180. package/quality/runtimeUse.ts +696 -0
  181. package/quality/runtimeUseReadable.test.ts +393 -0
  182. package/quality/ssrScanner.test.ts +13 -0
  183. package/quality/ssrScanner.ts +1 -1
  184. package/quality/translatorBindings.ts +187 -0
  185. package/test/secretEnvFixture.ts +134 -0
  186. package/test/testHelpers.ts +11 -0
  187. package/transforms/barrelAnalyzer.ts +26 -4
  188. package/transforms/barrelImportsPlugin.ts +121 -32
  189. package/transforms/exportReach.test.ts +162 -0
  190. package/transforms/exportReach.ts +308 -0
  191. package/transforms/frameworkObjects.fixture.tsx +58 -0
  192. package/transforms/frameworkObjects.test.ts +54 -0
  193. package/transforms/modelReference.test.ts +196 -0
  194. package/transforms/modelReference.ts +39 -0
  195. package/transforms/moduleParts.test.ts +225 -0
  196. package/transforms/moduleParts.ts +418 -0
  197. package/transforms/objectImportEdits.ts +150 -0
  198. package/transforms/objectMemberImports.test.ts +629 -0
  199. package/transforms/objectMemberImports.ts +571 -0
  200. package/transforms/objectMemberLookup.ts +150 -0
  201. package/transforms/objectModule.test.ts +307 -0
  202. package/transforms/objectModule.ts +482 -0
  203. package/transforms/objectModuleAnalyzer.ts +104 -0
  204. package/transforms/partImports.test.ts +76 -0
  205. package/transforms/partImports.ts +110 -0
  206. package/transforms/partModules.test.ts +187 -0
  207. package/transforms/partModules.ts +90 -0
  208. package/transforms/partPurity.ts +124 -0
  209. package/transforms/reactIconImports.test.ts +231 -0
  210. package/transforms/reactIconImports.ts +325 -0
  211. package/transforms/routeConstants.ts +122 -0
  212. package/transforms/routeRuntime.test.ts +835 -0
  213. package/transforms/routeRuntime.ts +703 -0
  214. package/transforms/routeRuntimeEdits.ts +92 -0
  215. package/transforms/routeRuntimeGraph.ts +66 -0
  216. package/transforms/routeRuntimePlan.ts +244 -0
  217. package/transforms/secretEnvDeclaration.test.ts +208 -0
  218. package/transforms/secretEnvDeclaration.ts +213 -0
  219. package/transforms/secretEnvFile.test.ts +117 -0
  220. package/transforms/secretEnvFile.ts +113 -0
  221. package/transforms/secretEnvName.test.ts +54 -0
  222. package/transforms/secretEnvName.ts +29 -0
  223. package/transforms/secretEnvSource.test.ts +148 -0
  224. package/transforms/secretEnvSource.ts +166 -0
  225. package/transforms/serverEnvEvaluationError.ts +11 -0
  226. package/transforms/serverEnvPlugin.test.ts +2 -1
  227. package/transforms/serverEnvPlugin.ts +13 -0
  228. package/transforms/serverEnvProfile.test.ts +115 -2
  229. package/transforms/serverEnvProfile.ts +117 -40
  230. package/transforms/serverEnvSecrets.test.ts +292 -0
  231. package/transforms/signalDescriptors.test.ts +280 -0
  232. package/transforms/signalDescriptors.ts +227 -0
  233. package/transforms/thisFreeExports.ts +87 -0
  234. package/transforms/transforms.test.ts +180 -3
  235. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  236. package/tunnel/createTunnel.test.ts +29 -8
  237. package/tunnel/createTunnel.ts +18 -11
  238. package/typecheck/projectTypecheck.test.ts +29 -0
  239. package/typecheck/typeChecker.test.ts +49 -0
  240. package/typecheck/typeChecker.ts +9 -7
  241. package/typecheck/withheldDiagnostics.ts +41 -0
  242. package/util/fileEditor.ts +1 -0
  243. package/util/selectModel.ts +1 -0
  244. package/workflow/executor.ts +6 -2
  245. package/workflow/index.ts +1 -0
  246. package/workflow/plan.ts +36 -7
  247. package/workflow/types.ts +1 -1
  248. package/workflow/uiTarget.ts +50 -0
  249. package/workspace/getRelatedCnsts.ts +7 -0
  250. package/workspace/scanInfo.test.ts +39 -0
  251. package/workspace/scanInfo.ts +48 -5
  252. package/workspace/workspaceLayout.ts +1 -0
@@ -83,7 +83,7 @@ reporting ready until the file it names exists.
83
83
 
84
84
  | variable | default | what it does |
85
85
  |---|---|---|
86
- | `AKAN_MEMORY_LOG` | off | `=1` logs a periodic memory report from each server role. |
86
+ | `AKAN_MEMORY_LOG` | off | `=1` logs a periodic memory report from each server role, and adds `rscFirstRenderMemory` (each route's first-render growth and loaded modules) to the RSC worker's metrics. |
87
87
  | `AKAN_MEMORY_LOG_INTERVAL_MS` | `60000` | How often that report is written. |
88
88
  | `AKAN_MEMORY_GC_ON_REPORT` | off | `=1` forces a GC before each report, so the number is retained memory rather than garbage. Costs a full GC per report. |
89
89
 
package/README.ko.md CHANGED
@@ -39,8 +39,9 @@ await runner.build();
39
39
 
40
40
  값은 그것을 가진 facet에서 import합니다(`@akanjs/devkit/executors`, `@akanjs/devkit/akanConfig`,
41
41
  `@akanjs/devkit/workflow` 등). 루트 `@akanjs/devkit` 진입점은 타입만 내보내므로, 도구 하나를 불러도 모든 facet이
42
- 프로세스에 올라오지 않습니다. facet이 따로 없는 도구는 그 폴더에서 import합니다(`@akanjs/devkit/app/…`, `quality/`,
43
- `workspace/`, `util/` 등). 이 도구들이 패키지 루트에 있던 시절의 경로는 다음 minor 릴리스까지 계속 동작합니다.
42
+ 프로세스에 올라오지 않습니다. facet 외에는 `exports`가 이름을 붙인 몇몇 파일(`app/applicationBuildRunner`,
43
+ `cloud/cloudApi`, `mobile/desktopRelease` 등)만 공개되며, 그 밖의 파일은 `akan` 명령의 내부 구현이라 패키지 밖에서
44
+ resolve되지 않습니다.
44
45
 
45
46
  ## 제공하는 것
46
47
 
package/README.md CHANGED
@@ -38,9 +38,9 @@ await runner.build();
38
38
 
39
39
  Import values from the facet that owns them (`@akanjs/devkit/executors`, `@akanjs/devkit/akanConfig`,
40
40
  `@akanjs/devkit/workflow`, …). The root `@akanjs/devkit` entry exports types only, so loading a tool does not pull
41
- every facet into the process. A tool with no facet of its own is imported from its folder (`@akanjs/devkit/app/…`,
42
- `quality/`, `workspace/`, `util/`, …); the paths these tools had at the package root still resolve until the next
43
- minor release.
41
+ every facet into the process. Besides the facets, `exports` names a few files (`app/applicationBuildRunner`,
42
+ `cloud/cloudApi`, `mobile/desktopRelease`, …); any other file is internal to the `akan` command and does not resolve
43
+ from outside the package.
44
44
 
45
45
  ## What It Provides
46
46
 
@@ -52,7 +52,7 @@ describe("Redis tunnels during dev startup", () => {
52
52
  const listener = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } });
53
53
  const port = listener.port;
54
54
  listener.stop(true);
55
- process.env.SSH_TUNNEL_PORT = String(port);
55
+ Object.assign(process.env, { SSH_TUNNEL_PORT: String(port), SSH_TUNNEL_PASSWORD: "test-password" });
56
56
  if (mode === "local") process.env.AKAN_PUBLIC_ENV = "local";
57
57
  const create = IncrementalBuilderHost.create;
58
58
  IncrementalBuilderHost.create = async () =>
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Logger } from "akanjs/common";
4
4
  import type { BuilderMessage } from "akanjs/server";
5
+ import { AppBin } from "../app/appBin";
5
6
  import type { App } from "../commandDecorators";
6
7
  import { WorkspaceExecutor } from "../executors";
7
8
  import type { DevStdioMode } from "../incrementalBuilder";
@@ -199,8 +200,18 @@ export class AkanAppHost {
199
200
  }
200
201
  if (!this.#backend.running) this.#backend.start();
201
202
  this.#idle.arm();
203
+ void this.#warnMissingBin();
202
204
  return this;
203
205
  }
206
+ //? A bin two libs declare differently fails the build that carries it; a dev start has nothing to carry.
207
+ async #warnMissingBin() {
208
+ const names = await this.app
209
+ .getConfig()
210
+ .then((config) => new AppBin(this.app, config).names())
211
+ .catch(() => []);
212
+ const missing = AppBin.missing(names);
213
+ if (missing) this.logger.warn(missing);
214
+ }
204
215
  async stop() {
205
216
  //? Nothing reapplies once it stops: a pages ok received meanwhile would bring children back after it.
206
217
  this.#stopping = true;
@@ -23,6 +23,10 @@ export class AkanBin {
23
23
  );
24
24
  }
25
25
 
26
+ static imagePath(binDir: string) {
27
+ return `/workspace/${binDir}/$TARGETARCH:$PATH`;
28
+ }
29
+
26
30
  static isArchive(source: AkanBinSource): boolean {
27
31
  return AkanBin.archive.test("url" in source ? new URL(source.url).pathname : source.path);
28
32
  }
@@ -6,7 +6,9 @@ import { fileURLToPath } from "node:url";
6
6
  import { AppExecutor, WorkspaceExecutor } from "../executors";
7
7
  import { NativeConfig } from "../mobile/nativeConfig";
8
8
  import type { PackageJson } from "../workspace/types";
9
+ import { AkanBin } from "./akanBin";
9
10
  import { AkanAppConfig, AkanLibConfig, deriveDefaultAppId } from "./akanConfig";
11
+ import { BUN_IMAGE_PIN, DEFAULT_DOCKER_IMAGE } from "./dockerImage";
10
12
  import type { LibConfigInput } from "./types";
11
13
 
12
14
  const akanPackageJson = JSON.parse(
@@ -15,7 +17,14 @@ const akanPackageJson = JSON.parse(
15
17
  const rootPackageJson = JSON.parse(
16
18
  fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../../package.json"), "utf8"),
17
19
  ) as { engines: { bun: string } };
18
- const pinnedBunImage = `oven/bun:${rootPackageJson.engines.bun}-slim`;
20
+ const writeDirsStep =
21
+ "RUN mkdir -p /workspace/sqlite /workspace/local /workspace/runtime /workspace/data /workspace/.akan/artifact/image-cache && chown 1000:1000 /workspace/sqlite /workspace/local /workspace/runtime /workspace/data /workspace/.akan/artifact/image-cache";
22
+ const setupActionBunVersion = /bun-version:\s*(\S+)/.exec(
23
+ fs.readFileSync(
24
+ path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../../.github/actions/setup/action.yml"),
25
+ "utf8",
26
+ ),
27
+ )?.[1];
19
28
 
20
29
  const packageJson: PackageJson = {
21
30
  name: "repo",
@@ -166,6 +175,16 @@ describe("AkanAppConfig", () => {
166
175
  expect(unlocked).not.toContain("bun.lock");
167
176
  });
168
177
 
178
+ test("a PATH the build hands in lands after the TARGETARCH it reads and the files it points at", () => {
179
+ const config = new AkanAppConfig(app, [], packageJson, {}, baseDevEnv);
180
+ const carrying = config.dockerfileFor("main", { env: { PATH: AkanBin.imagePath("bin") } });
181
+
182
+ expect(carrying).toContain("ENV PATH=/workspace/bin/$TARGETARCH:$PATH\n");
183
+ expect(carrying.indexOf("ARG TARGETARCH")).toBeLessThan(carrying.indexOf("ENV PATH="));
184
+ expect(carrying.indexOf("COPY . .")).toBeLessThan(carrying.indexOf("ENV PATH="));
185
+ expect(config.dockerfileFor("main")).not.toContain("ENV PATH=");
186
+ });
187
+
169
188
  test.skipIf(process.platform === "win32")(
170
189
  "writes a Dockerfile for a local build that refuses docker build without an explicit build arg",
171
190
  () => {
@@ -180,7 +199,7 @@ describe("AkanAppConfig", () => {
180
199
  env: { PATH: process.env.PATH ?? "", ...(allow ? { AKAN_ALLOW_LOCAL_IMAGE: allow } : {}) },
181
200
  });
182
201
 
183
- expect(local).toContain(`FROM ${pinnedBunImage}\nARG AKAN_ALLOW_LOCAL_IMAGE\nRUN if`);
202
+ expect(local).toContain(`FROM ${DEFAULT_DOCKER_IMAGE}\nARG AKAN_ALLOW_LOCAL_IMAGE\nRUN if`);
184
203
  expect(config.dockerfileFor("main")).not.toContain("AKAN_ALLOW_LOCAL_IMAGE");
185
204
  expect(run().exitCode).toBe(1);
186
205
  expect(run().stderr.toString()).toContain("--build-arg AKAN_ALLOW_LOCAL_IMAGE=1");
@@ -240,7 +259,9 @@ describe("AkanAppConfig", () => {
240
259
  const envBlock = Object.entries(config.getProductionEnv())
241
260
  .map(([key, value]) => `ENV ${key}=${value}`)
242
261
  .join("\n");
243
- expect(config.dockerfile).toContain(`COPY . .\n${envBlock}\nCMD ["bun","main.js"]`);
262
+ expect(config.dockerfile).toContain(
263
+ `COPY . .\n${writeDirsStep}\n${envBlock}\nUSER 1000:1000\nCMD ["bun","main.js"]`,
264
+ );
244
265
  });
245
266
 
246
267
  test('publishes localePrefix "as-needed" to the bundles and the image, and leaves the default out of the image', () => {
@@ -255,19 +276,19 @@ describe("AkanAppConfig", () => {
255
276
  });
256
277
 
257
278
  test("writes the Dockerfile instructions it wrote before its env came from getProductionEnv", () => {
258
- //? 9adfb95c's output for this config, less the blank lines its empty interpolations left and its floating tag.
279
+ //? 9adfb95c's output for this config, less the blank lines its empty interpolations left, its floating tag and root.
259
280
  const before = [
260
- `FROM ${pinnedBunImage}`,
281
+ `FROM ${DEFAULT_DOCKER_IMAGE}`,
261
282
  "RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*",
262
283
  "RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime",
263
284
  "ARG TARGETARCH",
264
285
  "",
265
- "RUN mkdir -p /workspace",
266
286
  "WORKDIR /workspace",
267
287
  "COPY ./package.json ./bun.lock ./",
268
288
  "RUN bun install --production --frozen-lockfile",
269
289
  "",
270
290
  "COPY . .",
291
+ writeDirsStep,
271
292
  "ENV PORT=8282",
272
293
  "ENV NODE_ENV=production",
273
294
  "ENV AKAN_PUBLIC_REPO_NAME=akanjs",
@@ -283,6 +304,7 @@ describe("AkanAppConfig", () => {
283
304
  "ENV AKAN_DATABASE_MODES=single",
284
305
  "ENV AKAN_LOG_TO_FILE=0",
285
306
  "",
307
+ "USER 1000:1000",
286
308
  'CMD ["bun","main.js"]',
287
309
  ];
288
310
  const lines = (text: string) => text.split("\n").filter((line) => line !== "");
@@ -307,6 +329,33 @@ describe("AkanAppConfig", () => {
307
329
  expect(config.dockerfile).not.toContain(dropped);
308
330
  });
309
331
 
332
+ test("pins the default image to the Bun release the repo runs, by the digest kept beside that version", () => {
333
+ expect(rootPackageJson.engines.bun).toBe(BUN_IMAGE_PIN.version);
334
+ expect(setupActionBunVersion).toBe(rootPackageJson.engines.bun);
335
+ expect(BUN_IMAGE_PIN.digest).toMatch(/^sha256:[0-9a-f]{64}$/);
336
+ expect(DEFAULT_DOCKER_IMAGE).toBe(`oven/bun:${BUN_IMAGE_PIN.version}-slim@${BUN_IMAGE_PIN.digest}`);
337
+ });
338
+
339
+ test("runs the generated image as the bun user once every root step is done, owning only what it writes", () => {
340
+ const config = new AkanAppConfig(
341
+ app,
342
+ [],
343
+ packageJson,
344
+ { docker: { preRuns: ["apt-get install -y ffmpeg"], postRuns: ["echo after"] } },
345
+ baseDevEnv,
346
+ );
347
+ const instructions = config.dockerfile.split("\n").filter((line) => line !== "");
348
+ const userAt = instructions.indexOf("USER 1000:1000");
349
+
350
+ expect(instructions.filter((line) => line.startsWith("USER "))).toEqual(["USER 1000:1000"]);
351
+ expect(instructions.slice(userAt + 1)).toEqual(['CMD ["bun","main.js"]']);
352
+ for (const rootStep of ["apt-get update", "apt-get install -y ffmpeg", "bun install", "echo after"])
353
+ expect(instructions.findIndex((line) => line.includes(rootStep))).toBeLessThan(userAt);
354
+ expect(instructions.filter((line) => line.includes("--chown"))).toEqual([]);
355
+ expect(instructions[instructions.indexOf("COPY . .") + 1]).toBe(writeDirsStep);
356
+ expect(instructions.filter((line) => line.includes("chown") && / \/workspace( |$)/.test(line))).toEqual([]);
357
+ });
358
+
310
359
  test("keeps a declared Dockerfile string verbatim", () => {
311
360
  const dockerfile = 'FROM oven/bun:1-slim\nCOPY . .\nCMD ["bun","main.js"]';
312
361
  const config = new AkanAppConfig(app, [], packageJson, { docker: dockerfile }, baseDevEnv);
@@ -319,7 +368,7 @@ describe("AkanAppConfig", () => {
319
368
  const config = new AkanAppConfig(app, [], packageJson, { docker: { preRuns: ["echo hi"] } }, baseDevEnv);
320
369
 
321
370
  expect(config.docker).toEqual({
322
- image: pinnedBunImage,
371
+ image: DEFAULT_DOCKER_IMAGE,
323
372
  preRuns: ["echo hi"],
324
373
  postRuns: [],
325
374
  command: ["bun", "main.js"],
@@ -870,6 +919,16 @@ describe("AkanAppConfig", () => {
870
919
  expect(make({ native: { desktop: { dmg: { backgroundImage: "bg.png" } } } })).toThrow(
871
920
  "native.desktop.dmg.backgroundImage in apps/portal/akan.config.ts is not a native setting",
872
921
  );
922
+ expect(make({ native: { desktop: { externalView: { origins: ["https://board.example"] } } } })).toThrow(
923
+ "native.desktop.externalView.origins in apps/portal/akan.config.ts is not a native setting. Known: allowOrigins, evaluate, sendKey.",
924
+ );
925
+ expect(
926
+ make({
927
+ native: {
928
+ desktop: { externalView: { allowOrigins: ["https://board.example"], evaluate: true, sendKey: true } },
929
+ },
930
+ }),
931
+ ).not.toThrow();
873
932
  });
874
933
 
875
934
  test("derives a repo-scoped default appId and records an explicit native section", () => {
@@ -4,39 +4,45 @@ import { fileURLToPath } from "node:url";
4
4
  import type { AkanPlugin } from "akanjs";
5
5
  import { DatabaseModes, normalizeRoutePrefix } from "akanjs/base";
6
6
  import { type AkanI18nConfig, resolveAkanI18nConfig, trimSlashes } from "akanjs/common";
7
- import type { ServerPolicy } from "akanjs/native/api";
8
7
  import type { AkanImageConfig } from "akanjs/server";
9
8
  import type { App, Lib } from "../commandDecorators";
10
9
  import { WorkspaceExecutor } from "../executors/workspaceExecutor";
11
- import { ServerEnvProfile } from "../transforms/serverEnvProfile";
12
10
  import type { BaseDevEnv, PackageJson } from "../workspace/types";
13
11
  import { AkanBin } from "./akanBin";
12
+ import { AkanWorkers } from "./akanWorkers";
13
+ import { DesktopServerConfig } from "./desktopServerConfig";
14
14
  import {
15
- type AkanApiConfig,
16
- type AkanAssetsConfig,
17
- type AkanBinConfig,
18
- type AkanDatabaseConfig,
19
- type AkanNativeAppConfig,
20
- type AkanNativeAppResult,
21
- type AkanNativeDeepLinks,
22
- type AkanNativeDesktopConfig,
23
- type AkanNativeSettings,
24
- type AkanNativeTarget,
25
- type AkanNativeUpdatesConfig,
26
- type AkanRouteConfig,
27
- type AkanWebConfig,
28
- type AkanWebOption,
29
- type AppConfigResult,
30
- type Arch,
31
- archs,
32
- type DatabaseMode,
33
- type DeepPartial,
34
- type DockerConfig,
35
- type DockerOption,
36
- type DockerRun,
37
- type LibAssetsConfig,
38
- type LibConfigResult,
39
- type LibDockerConfig,
15
+ DEFAULT_DOCKER_IMAGE,
16
+ DOCKER_RUN_USER,
17
+ DOCKER_WRITE_DIRS,
18
+ dockerImageScript,
19
+ dockerRunScripts,
20
+ } from "./dockerImage";
21
+ import { nativeKeys } from "./nativeKeys";
22
+ import type {
23
+ AkanApiConfig,
24
+ AkanAssetsConfig,
25
+ AkanBinConfig,
26
+ AkanDatabaseConfig,
27
+ AkanNativeAppConfig,
28
+ AkanNativeAppResult,
29
+ AkanNativeDeepLinks,
30
+ AkanNativeSettings,
31
+ AkanNativeTarget,
32
+ AkanNativeUpdatesConfig,
33
+ AkanRouteConfig,
34
+ AkanWebConfig,
35
+ AkanWebOption,
36
+ AkanWorkersConfig,
37
+ AppConfigResult,
38
+ DatabaseMode,
39
+ DeepPartial,
40
+ DockerConfig,
41
+ DockerOption,
42
+ DockerRun,
43
+ LibAssetsConfig,
44
+ LibConfigResult,
45
+ LibDockerConfig,
40
46
  } from "./types";
41
47
 
42
48
  const DEFAULT_BARREL_IMPORTS = ["akanjs/webkit", "akanjs/common", "akanjs/ui", "akanjs/server"];
@@ -47,8 +53,6 @@ const DEFAULT_OPTIMIZE_IMPORTS = [
47
53
  "@material-ui/icons @tabler/icons-react mui-core react-icons/*",
48
54
  ].flatMap((line) => line.split(" "));
49
55
  const WORKSPACE_BARREL_FACETS = ["ui", "webkit", "common", "client", "server"] as const;
50
- // `1-slim` floats to whichever Bun is newest at build time, one the framework was never tested on.
51
- const DEFAULT_DOCKER_IMAGE = "oven/bun:1.4.4-slim";
52
56
  const SSR_RUNTIME_PACKAGES = ["react", "react-dom", "react-server-dom-webpack"] as const;
53
57
  const DEFAULT_AKAN_IMAGE_CONFIG: AkanImageConfig = {
54
58
  deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
@@ -169,6 +173,7 @@ export class AkanAppConfig implements AppConfigResult {
169
173
  /** The app's own entries; the libs' are in `libBins`. */
170
174
  bin: AkanBinConfig;
171
175
  libBins: { lib: string; bin: AkanBinConfig }[];
176
+ workers: AkanWorkersConfig;
172
177
  barrelImports: string[];
173
178
  optimizeImports: string[];
174
179
  images: AkanImageConfig;
@@ -216,6 +221,7 @@ export class AkanAppConfig implements AppConfigResult {
216
221
  ];
217
222
  this.bin = AkanBin.parse(config?.bin, owner, app.cwdPath);
218
223
  this.libBins = libContributions.bin ?? [];
224
+ this.workers = AkanWorkers.declare(config?.workers, owner, app.cwdPath);
219
225
  this.barrelImports = [
220
226
  ...DEFAULT_BARREL_IMPORTS,
221
227
  ...WORKSPACE_BARREL_FACETS.map((facet) => `@apps/${app.name}/${facet}`),
@@ -323,7 +329,7 @@ export class AkanAppConfig implements AppConfigResult {
323
329
  : {}),
324
330
  ...(merged.desktop
325
331
  ? {
326
- desktop: AkanAppConfig.#desktopServer(
332
+ desktop: DesktopServerConfig.resolve(
327
333
  AkanAppConfig.#platformIndexPath(merged.desktop),
328
334
  `${where}.desktop.server`,
329
335
  configPath,
@@ -341,93 +347,6 @@ export class AkanAppConfig implements AppConfigResult {
341
347
  );
342
348
  return { appName, appId, ...(root.fileName ? { fileName: root.fileName } : {}), version, buildNum, targets };
343
349
  }
344
- //? `true` or `{ omit, profile, modules }`: lists trimmed once, so two targets that agree on them stage one server.
345
- static #desktopServer<T extends { server?: AkanNativeDesktopConfig["server"] }>(
346
- desktop: T,
347
- where: string,
348
- configPath: string,
349
- ): T {
350
- const { server } = desktop;
351
- if (server === undefined || typeof server === "boolean") return desktop;
352
- if (!AkanAppConfig.#isPlainObject(server))
353
- throw new Error(`${where} in ${configPath} must be true or { omit, profile, modules }.`);
354
- const names = (list: unknown, key: string, what: string) => {
355
- if (list === undefined) return [];
356
- if (!Array.isArray(list) || list.some((name) => typeof name !== "string" || !name.trim()))
357
- throw new Error(`${where}.${key} in ${configPath} must be a list of ${what}.`);
358
- return [...new Set(list.map((name: string) => name.trim()))].sort();
359
- };
360
- const { profile } = server;
361
- if (profile !== undefined && (typeof profile !== "string" || !ServerEnvProfile.namePattern.test(profile)))
362
- throw new Error(
363
- `${where}.profile in ${configPath} names env/env.server.<env>.<profile>.ts: a lowercase-first name of letters, digits and dashes.`,
364
- );
365
- const modules = names(server.modules, "modules", "module names or @<operationMode> selectors");
366
- const env = AkanAppConfig.#desktopServerEnv(server.env, where, configPath);
367
- const { restart } = server;
368
- if (restart !== undefined && restart !== "forever" && !(Number.isInteger(restart) && (restart as number) > 0))
369
- throw new Error(`${where}.restart in ${configPath} must be "forever" or a count of crashes in a row from 1.`);
370
- const watchdog = AkanAppConfig.#desktopServerWatchdog(server.watchdog, where, configPath);
371
- return {
372
- ...desktop,
373
- server: {
374
- omit: names(server.omit, "omit", "package names"),
375
- ...(profile ? { profile } : {}),
376
- ...(modules.length ? { modules } : {}),
377
- ...(Object.keys(env).length ? { env } : {}),
378
- ...(restart !== undefined ? { restart } : {}),
379
- ...(watchdog ? { watchdog } : {}),
380
- },
381
- };
382
- }
383
- //? The stage owns these: the operation mode, the database mode, what is served and the shutdown budget the shell's
384
- //? quit waits on are what make it the carried server.
385
- static readonly #stagedServerEnv = new Set([
386
- "AKAN_PUBLIC_OPERATION_MODE",
387
- "AKAN_DATABASE_MODE",
388
- "AKAN_DATABASE_MODES",
389
- "AKAN_SSR",
390
- "AKAN_CSR",
391
- "AKAN_MCP",
392
- "AKAN_SHUTDOWN_TIMEOUT_MS",
393
- "AKAN_MODULES",
394
- ]);
395
- static #desktopServerEnv(env: unknown, where: string, configPath: string): Record<string, string> {
396
- if (env === undefined) return {};
397
- if (!AkanAppConfig.#isPlainObject(env) || Object.values(env).some((value) => typeof value !== "string"))
398
- throw new Error(`${where}.env in ${configPath} must be an object of strings.`);
399
- const staged = Object.keys(env).filter((key) => AkanAppConfig.#stagedServerEnv.has(key.toUpperCase()));
400
- if (staged.length)
401
- throw new Error(
402
- `${where}.env in ${configPath} sets ${staged.join(", ")}, which the carried server's stage owns (modules: desktop.server.modules).`,
403
- );
404
- const secrets = ServerEnvProfile.secretPaths(env);
405
- if (secrets.length)
406
- throw new Error(
407
- `${where}.env in ${configPath} holds secret-named values (${secrets.join(", ")}), and the app carries its env where anyone on the computer reads it. Leave them out.`,
408
- );
409
- return env as Record<string, string>;
410
- }
411
- //? The akan.config.ts shape, which takes `true` and fills in what is left out; the launcher reads what this returns
412
- //? with serverPolicyOf in @akanjs/native, which devkit cannot load while it reads a config.
413
- static #desktopServerWatchdog(watchdog: unknown, where: string, configPath: string): ServerPolicy["watchdog"] | null {
414
- if (watchdog === undefined || watchdog === false) return null;
415
- const options = watchdog === true ? {} : watchdog;
416
- const whole = (value: unknown) => value === undefined || (Number.isInteger(value) && (value as number) > 0);
417
- if (
418
- !AkanAppConfig.#isPlainObject(options) ||
419
- Object.keys(options).some((key) => key !== "intervalMs" && key !== "failures") ||
420
- !whole(options.intervalMs) ||
421
- !whole(options.failures)
422
- )
423
- throw new Error(
424
- `${where}.watchdog in ${configPath} must be true or { intervalMs, failures }, whole numbers from 1.`,
425
- );
426
- return {
427
- intervalMs: (options.intervalMs as number | undefined) ?? 10_000,
428
- failures: (options.failures as number | undefined) ?? 3,
429
- };
430
- }
431
350
  static #platformIndexPath<T extends { indexPath?: string }>(section: T): T {
432
351
  const { indexPath: rawIndexPath, ...rest } = section;
433
352
  const indexPath = normalizeIndexPath(rawIndexPath);
@@ -452,56 +371,6 @@ export class AkanAppConfig implements AppConfigResult {
452
371
  static #isPlainObject(value: unknown): value is Record<string, unknown> {
453
372
  return typeof value === "object" && value !== null && !Array.isArray(value);
454
373
  }
455
- static readonly #nativeKeys = {
456
- native: [
457
- "basePath",
458
- "indexPath",
459
- "appName",
460
- "appId",
461
- "fileName",
462
- "version",
463
- "buildNum",
464
- "icon",
465
- "splash",
466
- "backgroundColor",
467
- "permissions",
468
- "plugins",
469
- "deepLinks",
470
- "updates",
471
- "devtools",
472
- "csp",
473
- "openUrls",
474
- "ios",
475
- "android",
476
- "desktop",
477
- ],
478
- ios: ["indexPath", "teamId", "infoPlist", "entitlements", "privacy", "files", "hideFormAccessoryBar"],
479
- android: [
480
- "indexPath",
481
- "sha256CertFingerprints",
482
- "googleServices",
483
- "push",
484
- "autoplay",
485
- "manifest",
486
- "application",
487
- "activity",
488
- "files",
489
- ],
490
- desktop: [
491
- "indexPath",
492
- "server",
493
- "recovery",
494
- "window",
495
- "screenCapture",
496
- "webview2",
497
- "publisher",
498
- "entitlements",
499
- "dmg",
500
- ],
501
- desktopServer: ["omit", "profile", "modules", "env", "restart", "watchdog"],
502
- dmg: ["background", "background2x", "window", "iconSize", "textSize", "app", "applications"],
503
- deepLinks: ["schemes", "domains"],
504
- } as const;
505
374
  //* Settings that moved when `mobile` became `native` are named with where they went, instead of "unknown".
506
375
  static readonly #movedKeys: Readonly<Record<string, string>> = {
507
376
  native: "the platform sections and plugins sit directly in the native section: ios, android, desktop, plugins",
@@ -526,19 +395,15 @@ export class AkanAppConfig implements AppConfigResult {
526
395
  );
527
396
  }
528
397
  };
529
- check(section, AkanAppConfig.#nativeKeys.native, where, "native");
398
+ check(section, nativeKeys.native, where, "native");
530
399
  const settings = section as AkanNativeSettings;
531
- check(settings.ios, AkanAppConfig.#nativeKeys.ios, `${where}.ios`, "ios");
532
- check(settings.android, AkanAppConfig.#nativeKeys.android, `${where}.android`, "android");
533
- check(settings.desktop, AkanAppConfig.#nativeKeys.desktop, `${where}.desktop`, "desktop");
534
- check(
535
- settings.desktop?.server,
536
- AkanAppConfig.#nativeKeys.desktopServer,
537
- `${where}.desktop.server`,
538
- "desktopServer",
539
- );
540
- check(settings.desktop?.dmg, AkanAppConfig.#nativeKeys.dmg, `${where}.desktop.dmg`, "dmg");
541
- check(settings.deepLinks, AkanAppConfig.#nativeKeys.deepLinks, `${where}.deepLinks`, "deepLinks");
400
+ check(settings.ios, nativeKeys.ios, `${where}.ios`, "ios");
401
+ check(settings.android, nativeKeys.android, `${where}.android`, "android");
402
+ check(settings.desktop, nativeKeys.desktop, `${where}.desktop`, "desktop");
403
+ check(settings.desktop?.server, nativeKeys.desktopServer, `${where}.desktop.server`, "desktopServer");
404
+ check(settings.desktop?.dmg, nativeKeys.dmg, `${where}.desktop.dmg`, "dmg");
405
+ check(settings.desktop?.externalView, nativeKeys.externalView, `${where}.desktop.externalView`, "externalView");
406
+ check(settings.deepLinks, nativeKeys.deepLinks, `${where}.deepLinks`, "deepLinks");
542
407
  }
543
408
  static readonly #androidFilePattern = /^(?:res\/[^/]+\/[^/]+|assets\/.+)$/;
544
409
  static #assertFiles(settings: AkanNativeSettings, where: string, configPath: string) {
@@ -587,23 +452,6 @@ export class AkanAppConfig implements AppConfigResult {
587
452
  this.branches.forEach((domain) => void domains.add(`${basePath}-${domain}.${serveDomain}`));
588
453
  });
589
454
  }
590
- #getDockerRunScripts(runs: DockerRun[]) {
591
- return runs.map((run) => {
592
- if (typeof run === "string") return `RUN ${run}`;
593
- else
594
- return Object.entries(run)
595
- .map(
596
- ([arch, script]) => `RUN if [ "$TARGETARCH" = "${arch}" ]; then \
597
- ${script}; \
598
- fi`,
599
- )
600
- .join("\n");
601
- });
602
- }
603
- #getDockerImageScript(image: string | { [key in Arch]?: string }, defaultImage: string) {
604
- if (typeof image === "string") return `FROM ${image}`;
605
- else return archs.map((arch) => `FROM ${image[arch] ?? defaultImage} AS ${arch}`).join("\n");
606
- }
607
455
  /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
608
456
  static #resolveDocker(docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig {
609
457
  if (typeof docker === "string") return docker;
@@ -643,29 +491,30 @@ export class AkanAppConfig implements AppConfigResult {
643
491
  "ARG AKAN_ALLOW_LOCAL_IMAGE",
644
492
  `RUN if [ "$AKAN_ALLOW_LOCAL_IMAGE" != "1" ]; then echo "This build ran with AKAN_PUBLIC_ENV=local, so the server runs without endpoint rate limits and on local defaults for Redis and the database mode. Build for the environment it deploys to with akan build --env, or pass --build-arg AKAN_ALLOW_LOCAL_IMAGE=1." >&2; exit 1; fi`,
645
493
  ].join("\n");
646
- dockerfileFor(environment: string, { lockfile = true }: { lockfile?: boolean } = {}): string {
647
- return this.#makeDockerfile(environment, lockfile);
494
+ dockerfileFor(environment: string, options: { lockfile?: boolean; env?: Record<string, string> } = {}): string {
495
+ return this.#makeDockerfile(environment, options.lockfile ?? true, options.env);
648
496
  }
649
- #makeDockerfile(environment?: string, lockfile = true): string {
497
+ #makeDockerfile(environment?: string, lockfile = true, env = this.getProductionEnv(environment)): string {
650
498
  if (typeof this.docker === "string") return this.docker;
651
499
  const { image, preRuns, postRuns, command } = this.docker;
652
- const preRunScripts = this.#getDockerRunScripts(preRuns);
653
- const postRunScripts = this.#getDockerRunScripts(postRuns);
654
- const imageScript = this.#getDockerImageScript(image, DEFAULT_DOCKER_IMAGE);
500
+ const preRunScripts = dockerRunScripts(preRuns);
501
+ const postRunScripts = dockerRunScripts(postRuns);
502
+ const imageScript = dockerImageScript(image);
655
503
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
656
- const envLines = Object.entries(this.getProductionEnv(environment)).map(([key, value]) => `ENV ${key}=${value}`);
504
+ const envLines = Object.entries(env).map(([key, value]) => `ENV ${key}=${value}`);
657
505
  return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
658
506
  RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*
659
507
  RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
660
508
  ARG TARGETARCH
661
509
  ${preRunScripts.join("\n")}
662
- RUN mkdir -p /workspace
663
510
  WORKDIR /workspace
664
511
  ${lockfile ? "COPY ./package.json ./bun.lock ./" : "COPY ./package.json ./package.json"}
665
512
  RUN bun install --production${lockfile ? " --frozen-lockfile" : ""}
666
513
  ${postRunScripts.join("\n")}
667
514
  COPY . .
515
+ RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}
668
516
  ${envLines.join("\n")}
517
+ USER ${DOCKER_RUN_USER}
669
518
  CMD [${command.map((c) => `"${c}"`).join(",")}]`;
670
519
  }
671
520
  static #importGeneration = 0;
@@ -0,0 +1,39 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { AppWorkerPath } from "akanjs/server/appWorkerPath";
4
+ import { AkanWorkers } from "./akanWorkers";
5
+
6
+ const owner = "apps/face/akan.config.ts";
7
+ const published = process.env[AppWorkerPath.envKey];
8
+
9
+ afterEach(() => {
10
+ if (published === undefined) delete process.env[AppWorkerPath.envKey];
11
+ else process.env[AppWorkerPath.envKey] = published;
12
+ });
13
+
14
+ describe("AkanWorkers", () => {
15
+ test("resolves each entry against the folder that declares it", () => {
16
+ expect(AkanWorkers.parse({ vision: "srvkit/_vision/visionWorker.ts" }, owner, "/repo/apps/face")).toEqual({
17
+ vision: path.resolve("/repo/apps/face/srvkit/_vision/visionWorker.ts"),
18
+ });
19
+ expect(AkanWorkers.parse(undefined, owner, "/repo/apps/face")).toEqual({});
20
+ });
21
+
22
+ test("refuses a name that is no file name and an entry that is no relative source file", () => {
23
+ const parse = (declared: unknown) => () => AkanWorkers.parse(declared, owner, "/repo/apps/face");
24
+
25
+ expect(parse(["vision"])).toThrow(`${owner}: workers maps each worker's name to its entry file`);
26
+ expect(parse({ "../vision": "a.ts" })).toThrow("workers.../vision is not a name");
27
+ expect(parse({ vision: "/abs/visionWorker.ts" })).toThrow("workers.vision must be a .ts or .js file");
28
+ expect(parse({ vision: "srvkit/vision" })).toThrow("workers.vision must be a .ts or .js file");
29
+ expect(parse({ vision: 1 })).toThrow("workers.vision must be a .ts or .js file");
30
+ });
31
+
32
+ test("publishes the sources a source run spawns from, and takes them back when none is declared", () => {
33
+ const workers = AkanWorkers.declare({ vision: "visionWorker.ts" }, owner, "/repo/apps/face");
34
+
35
+ expect(AppWorkerPath.sources()).toEqual(workers);
36
+ AkanWorkers.declare(undefined, owner, "/repo/apps/face");
37
+ expect(process.env[AppWorkerPath.envKey]).toBeUndefined();
38
+ });
39
+ });
@@ -0,0 +1,32 @@
1
+ import path from "node:path";
2
+ import { AppWorkerPath } from "akanjs/server/appWorkerPath";
3
+ import type { AkanWorkersConfig } from "./types";
4
+
5
+ export class AkanWorkers {
6
+ static readonly entry = /\.(ts|mts|js|mjs)$/;
7
+
8
+ //? Published on load, as the route prefixes are: every process the CLI starts from source inherits it.
9
+ static declare(declared: unknown, owner: string, baseDir: string): AkanWorkersConfig {
10
+ const workers = AkanWorkers.parse(declared, owner, baseDir);
11
+ if (Object.keys(workers).length) process.env[AppWorkerPath.envKey] = JSON.stringify(workers);
12
+ else delete process.env[AppWorkerPath.envKey];
13
+ return workers;
14
+ }
15
+
16
+ static parse(declared: unknown, owner: string, baseDir: string): AkanWorkersConfig {
17
+ if (declared === undefined) return {};
18
+ if (!declared || typeof declared !== "object" || Array.isArray(declared))
19
+ throw new Error(`${owner}: workers maps each worker's name to its entry file`);
20
+ return Object.fromEntries(
21
+ Object.entries(declared).map(([name, entry]) => {
22
+ if (!AppWorkerPath.validName.test(name))
23
+ throw new Error(`${owner}: workers.${name} is not a name (letters, digits, - and _)`);
24
+ if (typeof entry !== "string" || !AkanWorkers.entry.test(entry) || path.isAbsolute(entry))
25
+ throw new Error(
26
+ `${owner}: workers.${name} must be a .ts or .js file, relative to this config (got ${JSON.stringify(entry)})`,
27
+ );
28
+ return [name, path.resolve(baseDir, entry)];
29
+ }),
30
+ );
31
+ }
32
+ }