@akanjs/devkit 3.3.0-rc.6 → 3.3.0-rc.60

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 (278) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +8 -2
  3. package/README.md +8 -3
  4. package/akanApp/akanApp.host.test.ts +4 -2
  5. package/akanApp/akanApp.host.ts +11 -0
  6. package/akanConfig/akanBin.ts +4 -0
  7. package/akanConfig/akanConfig.test.ts +280 -19
  8. package/akanConfig/akanConfig.ts +96 -270
  9. package/akanConfig/akanWorkers.test.ts +73 -0
  10. package/akanConfig/akanWorkers.ts +61 -0
  11. package/akanConfig/desktopServerConfig.ts +96 -0
  12. package/akanConfig/dockerImage.ts +216 -0
  13. package/akanConfig/index.ts +2 -0
  14. package/akanConfig/nativeFileSettings.ts +33 -0
  15. package/akanConfig/nativeKeys.ts +52 -0
  16. package/akanConfig/types.ts +2 -0
  17. package/app/appBin.test.ts +63 -0
  18. package/app/appBin.ts +50 -0
  19. package/app/applicationBuildReporter.test.ts +51 -1
  20. package/app/applicationBuildReporter.ts +6 -1
  21. package/app/applicationBuildRunner.test.ts +358 -5
  22. package/app/applicationBuildRunner.ts +204 -30
  23. package/app/dictionarySizes.test.ts +40 -0
  24. package/app/dictionarySizes.ts +95 -0
  25. package/app/routeFilesReport.test.ts +59 -0
  26. package/app/routeFilesReport.ts +46 -0
  27. package/app/routeJsBudget.ts +18 -4
  28. package/artifact/implicitRootLayout.test.ts +19 -0
  29. package/artifact/implicitRootLayout.ts +16 -2
  30. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  31. package/artifact/storeBootstrap.test.ts +28 -0
  32. package/artifact/storeBootstrap.ts +64 -8
  33. package/biome.base.json +7 -5
  34. package/codeAgent/agent/CodeAgent.ts +36 -16
  35. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  36. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  37. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  38. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  39. package/codeAgent/agent/codeAgent.test.ts +62 -0
  40. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  41. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  42. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  43. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  44. package/codeAgent/skills/akan-debug/SKILL.md +1 -1
  45. package/codeAgent/skills/akan-deps/SKILL.md +3 -2
  46. package/codeAgent/skills/akan-err/SKILL.md +13 -8
  47. package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
  48. package/codeAgent/skills/akan-module/SKILL.md +2 -2
  49. package/codeAgent/skills/akan-page/SKILL.md +46 -29
  50. package/codeAgent/skills/akan-query/SKILL.md +13 -20
  51. package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
  52. package/codeAgent/skills/akan-service/SKILL.md +10 -11
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/commandDecorators/command.ts +28 -12
  56. package/commandDecorators/commandBuilder.ts +8 -1
  57. package/commandDecorators/commandDecorators.test.ts +70 -3
  58. package/commandDecorators/helpFormatter.ts +14 -12
  59. package/context/akanContext.ts +2 -0
  60. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  61. package/docs/apiReference.test.ts +9 -0
  62. package/docs/apiReference.ts +15 -0
  63. package/executors/appExecutor.ts +26 -12
  64. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  65. package/executors/clientRuntimeKeys.fixture.json +393 -0
  66. package/executors/clientRuntimeKeys.test.ts +1690 -0
  67. package/executors/executor.ts +14 -6
  68. package/executors/executors.test.ts +140 -1
  69. package/executors/sysExecutor.ts +112 -8
  70. package/executors/workspaceExecutor.ts +7 -4
  71. package/frontendBuild/allRoutesBuilder.ts +99 -7
  72. package/frontendBuild/autoImportSync.ts +3 -2
  73. package/frontendBuild/buildRouteClient.test.ts +686 -13
  74. package/frontendBuild/clientBuildTypes.ts +26 -0
  75. package/frontendBuild/clientEntriesBundler.ts +49 -1
  76. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  77. package/frontendBuild/clientEntryDiscovery.ts +136 -14
  78. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  79. package/frontendBuild/clientEntryGroups.ts +61 -0
  80. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  81. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  82. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  83. package/frontendBuild/csrDevPatcher.test.ts +1 -1
  84. package/frontendBuild/csrDevPatcher.ts +33 -7
  85. package/frontendBuild/csrDevTypes.ts +9 -0
  86. package/frontendBuild/devBarrelImports.test.ts +154 -0
  87. package/frontendBuild/devBarrelImports.ts +83 -23
  88. package/frontendBuild/devRegistryBundler.ts +4 -2
  89. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  90. package/frontendBuild/devRouteRuntime.ts +167 -0
  91. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  92. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  93. package/frontendBuild/dictionaryConstants.ts +136 -0
  94. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  95. package/frontendBuild/dictionaryPackState.ts +131 -0
  96. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  97. package/frontendBuild/dictionaryPacking.ts +160 -0
  98. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  99. package/frontendBuild/dictionaryRoutes.ts +227 -0
  100. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  101. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  102. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  103. package/frontendBuild/precompressArtifacts.ts +34 -8
  104. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  105. package/frontendBuild/renderedEntries.ts +144 -0
  106. package/frontendBuild/routeClientBuilder.ts +407 -43
  107. package/frontendBuild/routeHandoffs.test.ts +155 -0
  108. package/frontendBuild/routeHandoffs.ts +117 -0
  109. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  110. package/frontendBuild/routeModulePreloads.ts +20 -11
  111. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  112. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  113. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  114. package/frontendBuild/routeRuntimePays.ts +117 -0
  115. package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
  116. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  117. package/frontendBuild/ssrDevBundler.ts +66 -11
  118. package/frontendBuild/vendorFileImports.test.ts +254 -0
  119. package/frontendBuild/vendorFileImports.ts +163 -0
  120. package/frontendBuild/vendorNarrowing.ts +28 -0
  121. package/frontendBuild/vendorSpecifiers.ts +2 -0
  122. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  123. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  124. package/incrementalBuilder/builderBoot.ts +5 -5
  125. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  126. package/incrementalBuilder/builderLanes.ts +2 -2
  127. package/incrementalBuilder/builderWatch.ts +8 -8
  128. package/incrementalBuilder/csrRegistry.ts +4 -4
  129. package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
  130. package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
  131. package/incrementalBuilder/ssrRegistry.ts +6 -6
  132. package/index.ts +1 -1
  133. package/integration/renderAdmissionSoak.test.ts +99 -0
  134. package/integration/renderAdmissionSoak.ts +609 -0
  135. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  136. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  137. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  138. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  139. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  140. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  141. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  142. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  143. package/lint/biomeBase.test.ts +50 -3
  144. package/lint/biomeBase.ts +1 -1
  145. package/lint/biomeCheck.test.ts +162 -0
  146. package/lint/biomeCheck.ts +131 -0
  147. package/lint/linter.test.ts +16 -11
  148. package/lint/no-arbitrary-color.grit +5 -0
  149. package/lint/no-conditional-st-hook.grit +5 -1
  150. package/lint/no-daisyui-legacy-class.grit +8 -0
  151. package/lint/no-document-cookie.grit +3 -0
  152. package/lint/no-inline-color.grit +10 -2
  153. package/lint/no-oversized-list-limit.grit +2 -0
  154. package/lint/no-raw-palette-class.grit +7 -0
  155. package/lint/no-unpublished-form-setter.grit +2 -0
  156. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  157. package/lint/no-web-storage.grit +3 -0
  158. package/lint/withheldEnvFile.ts +17 -0
  159. package/mobile/desktopBin.ts +2 -2
  160. package/mobile/desktopServerStage.test.ts +18 -3
  161. package/mobile/desktopServerStage.ts +7 -2
  162. package/mobile/nativeApp.test.ts +7 -5
  163. package/mobile/nativeApp.ts +2 -2
  164. package/mobile/nativeConfig.test.ts +96 -1
  165. package/mobile/nativeConfig.ts +46 -12
  166. package/mobile/nativePublicEnv.ts +1 -1
  167. package/mobile/serverBundleSecrets.ts +43 -0
  168. package/package.json +20 -171
  169. package/packageExports.test.ts +38 -24
  170. package/quality/dictionaryKeys.test.ts +356 -0
  171. package/quality/dictionaryKeys.ts +488 -0
  172. package/quality/objectImportReport.test.ts +36 -0
  173. package/quality/objectImportReport.ts +105 -0
  174. package/quality/qualityScanner.ts +1 -1
  175. package/quality/routeRuntimeReport.test.ts +91 -0
  176. package/quality/routeRuntimeReport.ts +121 -0
  177. package/quality/runtimeConstantFacts.ts +71 -0
  178. package/quality/runtimeConstantGraph.ts +123 -0
  179. package/quality/runtimeConstantReads.ts +116 -0
  180. package/quality/runtimeImports.test.ts +190 -0
  181. package/quality/runtimeImports.ts +233 -0
  182. package/quality/runtimeKeyNames.ts +46 -0
  183. package/quality/runtimeLexicalScope.ts +132 -0
  184. package/quality/runtimeMarkerReach.test.ts +84 -0
  185. package/quality/runtimeMarkerReach.ts +255 -0
  186. package/quality/runtimeModuleFacts.ts +290 -0
  187. package/quality/runtimeNameTable.test.ts +172 -0
  188. package/quality/runtimeNameTable.ts +477 -0
  189. package/quality/runtimeScopeReport.test.ts +123 -0
  190. package/quality/runtimeScopeReport.ts +167 -0
  191. package/quality/runtimeSliceKey.ts +269 -0
  192. package/quality/runtimeSyntax.ts +133 -0
  193. package/quality/runtimeTable.fixture.ts +189 -0
  194. package/quality/runtimeUse.test.ts +737 -0
  195. package/quality/runtimeUse.ts +696 -0
  196. package/quality/runtimeUseReadable.test.ts +393 -0
  197. package/quality/ssrScanner.test.ts +13 -0
  198. package/quality/ssrScanner.ts +1 -1
  199. package/quality/translatorBindings.ts +187 -0
  200. package/test/secretEnvFixture.ts +134 -0
  201. package/test/testHelpers.ts +11 -0
  202. package/transforms/barrelAnalyzer.ts +26 -4
  203. package/transforms/barrelImportsPlugin.ts +121 -32
  204. package/transforms/exportReach.test.ts +162 -0
  205. package/transforms/exportReach.ts +308 -0
  206. package/transforms/frameworkObjects.fixture.tsx +58 -0
  207. package/transforms/frameworkObjects.test.ts +54 -0
  208. package/transforms/modelReference.test.ts +196 -0
  209. package/transforms/modelReference.ts +39 -0
  210. package/transforms/moduleParts.test.ts +225 -0
  211. package/transforms/moduleParts.ts +418 -0
  212. package/transforms/objectImportEdits.ts +150 -0
  213. package/transforms/objectMemberImports.test.ts +633 -0
  214. package/transforms/objectMemberImports.ts +571 -0
  215. package/transforms/objectMemberLookup.ts +150 -0
  216. package/transforms/objectModule.test.ts +307 -0
  217. package/transforms/objectModule.ts +482 -0
  218. package/transforms/objectModuleAnalyzer.ts +104 -0
  219. package/transforms/partImports.test.ts +76 -0
  220. package/transforms/partImports.ts +110 -0
  221. package/transforms/partModules.test.ts +187 -0
  222. package/transforms/partModules.ts +90 -0
  223. package/transforms/partPurity.ts +124 -0
  224. package/transforms/reactIconImports.test.ts +231 -0
  225. package/transforms/reactIconImports.ts +325 -0
  226. package/transforms/routeConstants.ts +122 -0
  227. package/transforms/routeRuntime.test.ts +835 -0
  228. package/transforms/routeRuntime.ts +703 -0
  229. package/transforms/routeRuntimeEdits.ts +92 -0
  230. package/transforms/routeRuntimeGraph.ts +66 -0
  231. package/transforms/routeRuntimePlan.ts +244 -0
  232. package/transforms/secretEnvDeclaration.test.ts +208 -0
  233. package/transforms/secretEnvDeclaration.ts +213 -0
  234. package/transforms/secretEnvFile.test.ts +117 -0
  235. package/transforms/secretEnvFile.ts +113 -0
  236. package/transforms/secretEnvName.test.ts +54 -0
  237. package/transforms/secretEnvName.ts +29 -0
  238. package/transforms/secretEnvSource.test.ts +148 -0
  239. package/transforms/secretEnvSource.ts +166 -0
  240. package/transforms/serverEnvEvaluationError.ts +11 -0
  241. package/transforms/serverEnvPlugin.test.ts +2 -1
  242. package/transforms/serverEnvPlugin.ts +13 -0
  243. package/transforms/serverEnvProfile.test.ts +129 -2
  244. package/transforms/serverEnvProfile.ts +126 -40
  245. package/transforms/serverEnvSecrets.test.ts +292 -0
  246. package/transforms/signalDescriptors.test.ts +280 -0
  247. package/transforms/signalDescriptors.ts +227 -0
  248. package/transforms/thisFreeExports.ts +87 -0
  249. package/transforms/transforms.test.ts +180 -3
  250. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  251. package/tunnel/createTunnel.test.ts +29 -8
  252. package/tunnel/createTunnel.ts +22 -11
  253. package/tunnel/ssh2Module.test.ts +37 -0
  254. package/tunnel/ssh2Module.ts +32 -0
  255. package/tunnel/sshTunnel.ts +4 -2
  256. package/typecheck/projectTypecheck.test.ts +32 -1
  257. package/typecheck/projectTypecheck.ts +3 -3
  258. package/typecheck/typeChecker.test.ts +49 -0
  259. package/typecheck/typeChecker.ts +9 -7
  260. package/typecheck/withheldDiagnostics.ts +41 -0
  261. package/util/fileEditor.ts +1 -0
  262. package/util/selectModel.ts +1 -0
  263. package/workflow/executor.ts +6 -2
  264. package/workflow/index.ts +1 -0
  265. package/workflow/plan.ts +36 -7
  266. package/workflow/types.ts +1 -1
  267. package/workflow/uiTarget.ts +50 -0
  268. package/workspace/envSeed.test.ts +30 -1
  269. package/workspace/envSeed.ts +30 -1
  270. package/workspace/getRelatedCnsts.ts +7 -0
  271. package/workspace/mainCheckout.test.ts +55 -0
  272. package/workspace/mainCheckout.ts +38 -0
  273. package/workspace/scanInfo.test.ts +39 -0
  274. package/workspace/scanInfo.ts +55 -6
  275. package/workspace/slicePlanner.ts +1 -1
  276. package/workspace/workspaceLayout.test.ts +5 -1
  277. package/workspace/workspaceLayout.ts +3 -0
  278. package/CHANGELOG.md +0 -2717
@@ -4,39 +4,40 @@ 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";
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,
12
+ import { AkanWorkers, type LibWorkers } from "./akanWorkers";
13
+ import { DesktopServerConfig } from "./desktopServerConfig";
14
+ import { dockerfileOf, resolveDocker, resolveDockerVariants } from "./dockerImage";
15
+ import { NativeFileSettings } from "./nativeFileSettings";
16
+ import { nativeKeys } from "./nativeKeys";
17
+ import type {
18
+ AkanApiConfig,
19
+ AkanAssetsConfig,
20
+ AkanBinConfig,
21
+ AkanDatabaseConfig,
22
+ AkanNativeAppConfig,
23
+ AkanNativeAppResult,
24
+ AkanNativeDeepLinks,
25
+ AkanNativeSettings,
26
+ AkanNativeTarget,
27
+ AkanNativeUpdatesConfig,
28
+ AkanRouteConfig,
29
+ AkanWebConfig,
30
+ AkanWebOption,
31
+ AkanWorkersConfig,
32
+ AppConfigResult,
33
+ DatabaseMode,
34
+ DeepPartial,
35
+ DockerConfig,
36
+ DockerImageConfig,
37
+ DockerOption,
38
+ LibAssetsConfig,
39
+ LibConfigResult,
40
+ LibDockerConfig,
40
41
  } from "./types";
41
42
 
42
43
  const DEFAULT_BARREL_IMPORTS = ["akanjs/webkit", "akanjs/common", "akanjs/ui", "akanjs/server"];
@@ -47,8 +48,6 @@ const DEFAULT_OPTIMIZE_IMPORTS = [
47
48
  "@material-ui/icons @tabler/icons-react mui-core react-icons/*",
48
49
  ].flatMap((line) => line.split(" "));
49
50
  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
51
  const SSR_RUNTIME_PACKAGES = ["react", "react-dom", "react-server-dom-webpack"] as const;
53
52
  const DEFAULT_AKAN_IMAGE_CONFIG: AkanImageConfig = {
54
53
  deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
@@ -123,6 +122,7 @@ export interface LibContributions {
123
122
  trustedDependencies?: string[];
124
123
  /** Per lib, since an app carries only the entries of the libs it depends on. */
125
124
  bin?: { lib: string; bin: AkanBinConfig }[];
125
+ workers?: LibWorkers[];
126
126
  docker: LibDockerConfig;
127
127
  /** Keep globs rewritten to the app's own `public/`, where `akan sync` mounts each lib's assets. */
128
128
  keepFonts?: string[];
@@ -132,7 +132,8 @@ const emptyLibContributions = (): LibContributions => ({
132
132
  externalLibs: [],
133
133
  trustedDependencies: [],
134
134
  bin: [],
135
- docker: { preRuns: [], postRuns: [] },
135
+ workers: [],
136
+ docker: { preRuns: [], installRuns: [], postRuns: [] },
136
137
  keepFonts: [],
137
138
  });
138
139
 
@@ -147,13 +148,6 @@ const normalizeKeepFonts = (keepFonts: string[] | undefined) => [
147
148
  ...new Set((keepFonts ?? []).map((glob) => glob.trim().replace(/^\/+/, "")).filter(Boolean)),
148
149
  ];
149
150
 
150
- /** First occurrence wins, so a step a lib and its app both declare becomes one layer. */
151
- const dedupeDockerRuns = (runs: DockerRun[]): DockerRun[] => {
152
- const byKey = new Map<string, DockerRun>();
153
- for (const run of runs) byKey.set(typeof run === "string" ? run : JSON.stringify(run), run);
154
- return [...byKey.values()];
155
- };
156
-
157
151
  class LibConfigRefusal extends Error {}
158
152
 
159
153
  export class AkanAppConfig implements AppConfigResult {
@@ -162,6 +156,8 @@ export class AkanAppConfig implements AppConfigResult {
162
156
  docker: DockerConfig;
163
157
  /** The Dockerfile `akan build` writes: the declared string verbatim, or one assembled from the parts. */
164
158
  dockerfile: string;
159
+ /** Each is the app's `docker` with the variant's fields replaced; a lib's steps reach every one. */
160
+ dockerVariants: Record<string, DockerImageConfig>;
165
161
  database: AkanDatabaseConfig;
166
162
  web: AkanWebConfig;
167
163
  externalLibs: string[];
@@ -169,6 +165,8 @@ export class AkanAppConfig implements AppConfigResult {
169
165
  /** The app's own entries; the libs' are in `libBins`. */
170
166
  bin: AkanBinConfig;
171
167
  libBins: { lib: string; bin: AkanBinConfig }[];
168
+ /** The app's own entries; `App.selectWorkers` adds those of the libs it depends on. */
169
+ workers: AkanWorkersConfig;
172
170
  barrelImports: string[];
173
171
  optimizeImports: string[];
174
172
  images: AkanImageConfig;
@@ -189,6 +187,7 @@ export class AkanAppConfig implements AppConfigResult {
189
187
  domains = new Set<string>();
190
188
  subRoutes = new Map<string, Set<string>>();
191
189
  basePaths = new Set<string>();
190
+ routePageLibs = new Map<string, string[] | boolean>();
192
191
  branches = new Set<string>(["debug", "develop", "main"]);
193
192
  constructor(
194
193
  app: App,
@@ -216,6 +215,11 @@ export class AkanAppConfig implements AppConfigResult {
216
215
  ];
217
216
  this.bin = AkanBin.parse(config?.bin, owner, app.cwdPath);
218
217
  this.libBins = libContributions.bin ?? [];
218
+ this.workers = AkanWorkers.parse(config?.workers, owner, app.cwdPath);
219
+ //? The dependency scan reads this config, so every workspace lib's entry is published; a start, test or build names the mounted ones.
220
+ AkanWorkers.publish(
221
+ AkanWorkers.select({ owner, workers: this.workers }, libContributions.workers ?? [], libs, { strict: false }),
222
+ );
219
223
  this.barrelImports = [
220
224
  ...DEFAULT_BARREL_IMPORTS,
221
225
  ...WORKSPACE_BARREL_FACETS.map((facet) => `@apps/${app.name}/${facet}`),
@@ -251,7 +255,8 @@ export class AkanAppConfig implements AppConfigResult {
251
255
  this.hasNativeConfig = Boolean(config.native);
252
256
  this.native = this.#resolveNativeConfig(config.native);
253
257
  this.web = this.#resolveWebConfig(config.web);
254
- this.docker = AkanAppConfig.#resolveDocker(config.docker, libContributions.docker);
258
+ this.docker = resolveDocker(config.docker, libContributions.docker);
259
+ this.dockerVariants = resolveDockerVariants(config.docker, libContributions.docker);
255
260
  this.dockerfile = this.#makeDockerfile();
256
261
  }
257
262
  #resolveWebConfig(web: AkanWebOption | undefined): AkanWebConfig {
@@ -267,7 +272,7 @@ export class AkanAppConfig implements AppConfigResult {
267
272
  const configPath = `apps/${this.app.name}/akan.config.ts`;
268
273
  const { targets: rawTargets, ...root } = native ?? {};
269
274
  AkanAppConfig.#assertNativeKeys(root, "native", configPath);
270
- AkanAppConfig.#assertFiles(root, "native", configPath);
275
+ NativeFileSettings.assert(root, "native", configPath);
271
276
  const appName = root.appName ?? this.app.name;
272
277
  const appId = root.appId ?? deriveDefaultAppId(this.baseDevEnv.repoName, this.app.name);
273
278
  const version = root.version ?? "0.0.1";
@@ -295,7 +300,7 @@ export class AkanAppConfig implements AppConfigResult {
295
300
  throw new Error(
296
301
  `${where}.updates in ${configPath} has both publicKey and publicKeys${named ? ", native.updates merged in: give one, in native.updates' own form when overriding its keys" : ": give one"}.`,
297
302
  );
298
- AkanAppConfig.#assertFiles(own ?? {}, where, configPath);
303
+ NativeFileSettings.assert(own ?? {}, where, configPath);
299
304
  const {
300
305
  basePath: _basePath,
301
306
  indexPath: rawIndexPath,
@@ -323,7 +328,7 @@ export class AkanAppConfig implements AppConfigResult {
323
328
  : {}),
324
329
  ...(merged.desktop
325
330
  ? {
326
- desktop: AkanAppConfig.#desktopServer(
331
+ desktop: DesktopServerConfig.resolve(
327
332
  AkanAppConfig.#platformIndexPath(merged.desktop),
328
333
  `${where}.desktop.server`,
329
334
  configPath,
@@ -341,93 +346,6 @@ export class AkanAppConfig implements AppConfigResult {
341
346
  );
342
347
  return { appName, appId, ...(root.fileName ? { fileName: root.fileName } : {}), version, buildNum, targets };
343
348
  }
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
349
  static #platformIndexPath<T extends { indexPath?: string }>(section: T): T {
432
350
  const { indexPath: rawIndexPath, ...rest } = section;
433
351
  const indexPath = normalizeIndexPath(rawIndexPath);
@@ -452,56 +370,6 @@ export class AkanAppConfig implements AppConfigResult {
452
370
  static #isPlainObject(value: unknown): value is Record<string, unknown> {
453
371
  return typeof value === "object" && value !== null && !Array.isArray(value);
454
372
  }
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
373
  //* Settings that moved when `mobile` became `native` are named with where they went, instead of "unknown".
506
374
  static readonly #movedKeys: Readonly<Record<string, string>> = {
507
375
  native: "the platform sections and plugins sit directly in the native section: ios, android, desktop, plugins",
@@ -526,53 +394,32 @@ export class AkanAppConfig implements AppConfigResult {
526
394
  );
527
395
  }
528
396
  };
529
- check(section, AkanAppConfig.#nativeKeys.native, where, "native");
397
+ check(section, nativeKeys.native, where, "native");
530
398
  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");
542
- }
543
- static readonly #androidFilePattern = /^(?:res\/[^/]+\/[^/]+|assets\/.+)$/;
544
- static #assertFiles(settings: AkanNativeSettings, where: string, configPath: string) {
545
- const check = (
546
- files: Record<string, string> | undefined,
547
- at: string,
548
- valid: (to: string) => boolean,
549
- shape: string,
550
- ) => {
551
- for (const [to, from] of Object.entries(files ?? {})) {
552
- if (typeof from !== "string")
553
- throw new Error(
554
- `${at}["${to}"] in ${configPath} must name its source file, relative to the app folder, e.g. { "${shape}": "assets/chime.mp3" }.`,
555
- );
556
- if (!valid(to)) throw new Error(`${at}["${to}"] in ${configPath} must land at ${shape}.`);
557
- }
558
- };
559
- check(
560
- settings.ios?.files,
561
- `${where}.ios.files`,
562
- (to) => to.length > 0 && !to.startsWith("/") && !to.split("/").includes(".."),
563
- "<path in the app bundle>",
564
- );
565
- check(
566
- settings.android?.files,
567
- `${where}.android.files`,
568
- (to) => AkanAppConfig.#androidFilePattern.test(to),
569
- "res/<type>/<file> or assets/<path>",
570
- );
399
+ check(settings.ios, nativeKeys.ios, `${where}.ios`, "ios");
400
+ check(settings.android, nativeKeys.android, `${where}.android`, "android");
401
+ check(settings.desktop, nativeKeys.desktop, `${where}.desktop`, "desktop");
402
+ check(settings.desktop?.server, nativeKeys.desktopServer, `${where}.desktop.server`, "desktopServer");
403
+ check(settings.desktop?.dmg, nativeKeys.dmg, `${where}.desktop.dmg`, "dmg");
404
+ check(settings.desktop?.externalView, nativeKeys.externalView, `${where}.desktop.externalView`, "externalView");
405
+ check(settings.deepLinks, nativeKeys.deepLinks, `${where}.deepLinks`, "deepLinks");
571
406
  }
572
407
  #applyRoutes(routes: AkanRouteConfig[] = []) {
573
408
  for (const route of routes) {
574
409
  const basePath = route.basePath ? trimSlashes(route.basePath) : null;
575
410
  if (basePath !== null) this.basePaths.add(basePath);
411
+ if (route.syncPageLibs !== undefined) {
412
+ if (basePath === null)
413
+ throw new Error(
414
+ `A route in apps/${this.app.name}/akan.config.ts sets syncPageLibs without a basePath: only a basePath has lib pages of its own, so set the app's syncPageLibs.`,
415
+ );
416
+ const earlier = this.routePageLibs.get(basePath);
417
+ if (earlier !== undefined && JSON.stringify(earlier) !== JSON.stringify(route.syncPageLibs))
418
+ throw new Error(
419
+ `Two routes in apps/${this.app.name}/akan.config.ts share basePath "${basePath}" and set different syncPageLibs: a basePath mounts one set of lib pages, so set it on one of them.`,
420
+ );
421
+ this.routePageLibs.set(basePath, route.syncPageLibs);
422
+ }
576
423
  const domains = basePath !== null ? this.subRoutes.getOrInsert(basePath, new Set()) : this.domains;
577
424
  for (const branch of Object.keys(route.domains)) this.branches.add(branch);
578
425
  for (const domain of Object.values(route.domains).flat())
@@ -587,33 +434,6 @@ export class AkanAppConfig implements AppConfigResult {
587
434
  this.branches.forEach((domain) => void domains.add(`${basePath}-${domain}.${serveDomain}`));
588
435
  });
589
436
  }
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
- /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
608
- static #resolveDocker(docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig {
609
- if (typeof docker === "string") return docker;
610
- return {
611
- image: docker?.image ?? DEFAULT_DOCKER_IMAGE,
612
- preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker?.preRuns ?? [])]),
613
- postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker?.postRuns ?? [])]),
614
- command: docker?.command ?? ["bun", "main.js"],
615
- };
616
- }
617
437
  /** What the built server runs with in its image; a desktop app's carried server starts from the same values. */
618
438
  getProductionEnv(environment: string = this.baseDevEnv.env): Record<string, string> {
619
439
  return {
@@ -643,30 +463,24 @@ export class AkanAppConfig implements AppConfigResult {
643
463
  "ARG AKAN_ALLOW_LOCAL_IMAGE",
644
464
  `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
465
  ].join("\n");
646
- dockerfileFor(environment: string, { lockfile = true }: { lockfile?: boolean } = {}): string {
647
- return this.#makeDockerfile(environment, lockfile);
648
- }
649
- #makeDockerfile(environment?: string, lockfile = true): string {
466
+ dockerfileFor(
467
+ environment: string,
468
+ options: { lockfile?: boolean; env?: Record<string, string>; variant?: string } = {},
469
+ ): string {
470
+ return this.#makeDockerfile(environment, options.lockfile ?? true, options.env, options.variant);
471
+ }
472
+ #makeDockerfile(
473
+ environment?: string,
474
+ lockfile = true,
475
+ env = this.getProductionEnv(environment),
476
+ variant?: string,
477
+ ): string {
650
478
  if (typeof this.docker === "string") return this.docker;
651
- 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);
479
+ const docker = variant === undefined ? this.docker : this.dockerVariants[variant];
480
+ if (!docker)
481
+ throw new Error(`[docker] apps/${this.app.name}/akan.config.ts declares no docker variant "${variant}"`);
655
482
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
656
- const envLines = Object.entries(this.getProductionEnv(environment)).map(([key, value]) => `ENV ${key}=${value}`);
657
- return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
658
- 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
- RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
660
- ARG TARGETARCH
661
- ${preRunScripts.join("\n")}
662
- RUN mkdir -p /workspace
663
- WORKDIR /workspace
664
- ${lockfile ? "COPY ./package.json ./bun.lock ./" : "COPY ./package.json ./package.json"}
665
- RUN bun install --production${lockfile ? " --frozen-lockfile" : ""}
666
- ${postRunScripts.join("\n")}
667
- COPY . .
668
- ${envLines.join("\n")}
669
- CMD [${command.map((c) => `"${c}"`).join(",")}]`;
483
+ return dockerfileOf(docker, { env, lockfile, guard: isLocal ? AkanAppConfig.localImageGuard : undefined });
670
484
  }
671
485
  static #importGeneration = 0;
672
486
  // Bun caches dynamic imports by path; a fresh query string re-evaluates the config module (its imports stay cached).
@@ -726,8 +540,14 @@ CMD [${command.map((c) => `"${c}"`).join(",")}]`;
726
540
  bin: libConfigs.flatMap((libConfig) =>
727
541
  libConfig && Object.keys(libConfig.bin).length ? [{ lib: libConfig.lib.name, bin: libConfig.bin }] : [],
728
542
  ),
543
+ workers: libConfigs.flatMap((libConfig) =>
544
+ libConfig && Object.keys(libConfig.workers).length
545
+ ? [{ lib: libConfig.lib.name, workers: libConfig.workers }]
546
+ : [],
547
+ ),
729
548
  docker: {
730
549
  preRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.preRuns ?? []),
550
+ installRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.installRuns ?? []),
731
551
  postRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.postRuns ?? []),
732
552
  },
733
553
  //* A lib writes the glob against its own `public/`; `akan sync` mounts that at `public/libs/<lib>`.
@@ -864,6 +684,7 @@ export class AkanLibConfig implements LibConfigResult {
864
684
  externalLibs: string[];
865
685
  trustedDependencies: string[];
866
686
  bin: AkanBinConfig;
687
+ workers: AkanWorkersConfig;
867
688
  docker: LibDockerConfig;
868
689
  assets: LibAssetsConfig;
869
690
  /** Live-only: plugins declared in this lib's `akan.config.ts` (never serialized). */
@@ -874,7 +695,12 @@ export class AkanLibConfig implements LibConfigResult {
874
695
  const owner = `libs/${lib.name}/akan.config.ts`;
875
696
  this.trustedDependencies = normalizePackageNames(config?.trustedDependencies, owner);
876
697
  this.bin = AkanBin.parse(config?.bin, owner, lib.cwdPath);
877
- this.docker = { preRuns: config?.docker?.preRuns ?? [], postRuns: config?.docker?.postRuns ?? [] };
698
+ this.workers = AkanWorkers.parse(config?.workers, owner, lib.cwdPath);
699
+ this.docker = {
700
+ preRuns: config?.docker?.preRuns ?? [],
701
+ installRuns: config?.docker?.installRuns ?? [],
702
+ postRuns: config?.docker?.postRuns ?? [],
703
+ };
878
704
  this.assets = { keepFonts: normalizeKeepFonts(config?.assets?.keepFonts as string[] | undefined) };
879
705
  this.plugins = plugins;
880
706
  }
@@ -0,0 +1,73 @@
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, type LibWorkers } 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.parse({ vision: "visionWorker.ts" }, owner, "/repo/apps/face");
34
+
35
+ expect(AkanWorkers.publish(AkanWorkers.select({ owner, workers }, [], []))).toEqual(workers);
36
+ expect(AppWorkerPath.sources()).toEqual(workers);
37
+ AkanWorkers.publish(AkanWorkers.select({ owner, workers: {} }, [], []));
38
+ expect(process.env[AppWorkerPath.envKey]).toBeUndefined();
39
+ });
40
+
41
+ test("adds the workers of the libs named, and the declarer's own entry wins a name", () => {
42
+ const libWorkers: LibWorkers[] = [
43
+ {
44
+ lib: "edge",
45
+ workers: { vision: "/repo/libs/edge/srvkit/vision.worker.ts", encode: "/repo/libs/edge/encode.ts" },
46
+ },
47
+ { lib: "other", workers: { ocr: "/repo/libs/other/ocr.ts" } },
48
+ ];
49
+ const chosen = AkanWorkers.select({ owner, workers: { vision: "/repo/apps/face/vision.ts" } }, libWorkers, [
50
+ "edge",
51
+ ]);
52
+
53
+ expect(Object.fromEntries(chosen)).toEqual({
54
+ vision: { owner, entry: "/repo/apps/face/vision.ts" },
55
+ encode: { owner: "libs/edge/akan.config.ts", entry: "/repo/libs/edge/encode.ts" },
56
+ });
57
+ });
58
+
59
+ test("refuses one name two of the named libs declare differently, unless told to keep the first", () => {
60
+ const libWorkers: LibWorkers[] = [
61
+ { lib: "edge", workers: { vision: "/repo/libs/edge/vision.ts" } },
62
+ { lib: "lab", workers: { vision: "/repo/libs/lab/vision.ts" } },
63
+ ];
64
+ const select = (libs: string[], strict?: boolean) =>
65
+ AkanWorkers.select({ owner, workers: {} }, libWorkers, libs, { strict });
66
+
67
+ expect(() => select(["edge", "lab"])).toThrow(
68
+ `libs/edge/akan.config.ts and libs/lab/akan.config.ts declare workers.vision differently; declare it in ${owner} to pick one.`,
69
+ );
70
+ expect(select(["lab"]).get("vision")?.entry).toBe("/repo/libs/lab/vision.ts");
71
+ expect(select(["edge", "lab"], false).get("vision")?.entry).toBe("/repo/libs/edge/vision.ts");
72
+ });
73
+ });
@@ -0,0 +1,61 @@
1
+ import path from "node:path";
2
+ import { AppWorkerPath } from "akanjs/server/appWorkerPath";
3
+ import type { AkanWorkersConfig } from "./types";
4
+
5
+ export interface WorkerDeclarer {
6
+ owner: string;
7
+ workers: AkanWorkersConfig;
8
+ }
9
+
10
+ export interface LibWorkers {
11
+ lib: string;
12
+ workers: AkanWorkersConfig;
13
+ }
14
+
15
+ export class AkanWorkers {
16
+ static readonly entry = /\.(ts|mts|js|mjs)$/;
17
+
18
+ /** The declarer's own entries, then those of the libs named: its own wins a name, two libs may not differ on one. */
19
+ static select(own: WorkerDeclarer, libWorkers: LibWorkers[], libs: string[], { strict = true } = {}) {
20
+ const chosen = new Map<string, { owner: string; entry: string }>();
21
+ for (const [name, entry] of Object.entries(own.workers)) chosen.set(name, { owner: own.owner, entry });
22
+ for (const { lib, workers } of libWorkers) {
23
+ if (!libs.includes(lib)) continue;
24
+ const owner = `libs/${lib}/akan.config.ts`;
25
+ for (const [name, entry] of Object.entries(workers)) {
26
+ const held = chosen.get(name);
27
+ if (!held) chosen.set(name, { owner, entry });
28
+ else if (strict && held.owner !== own.owner && held.entry !== entry)
29
+ throw new Error(
30
+ `${held.owner} and ${owner} declare workers.${name} differently; declare it in ${own.owner} to pick one.`,
31
+ );
32
+ }
33
+ }
34
+ return chosen;
35
+ }
36
+
37
+ //? Published to `process.env`, as the route prefixes are: every process the CLI starts from source inherits it.
38
+ static publish(chosen: Map<string, { entry: string }>): AkanWorkersConfig {
39
+ const sources = Object.fromEntries([...chosen].map(([name, { entry }]) => [name, entry]));
40
+ if (chosen.size) process.env[AppWorkerPath.envKey] = JSON.stringify(sources);
41
+ else delete process.env[AppWorkerPath.envKey];
42
+ return sources;
43
+ }
44
+
45
+ static parse(declared: unknown, owner: string, baseDir: string): AkanWorkersConfig {
46
+ if (declared === undefined) return {};
47
+ if (!declared || typeof declared !== "object" || Array.isArray(declared))
48
+ throw new Error(`${owner}: workers maps each worker's name to its entry file`);
49
+ return Object.fromEntries(
50
+ Object.entries(declared).map(([name, entry]) => {
51
+ if (!AppWorkerPath.validName.test(name))
52
+ throw new Error(`${owner}: workers.${name} is not a name (letters, digits, - and _)`);
53
+ if (typeof entry !== "string" || !AkanWorkers.entry.test(entry) || path.isAbsolute(entry))
54
+ throw new Error(
55
+ `${owner}: workers.${name} must be a .ts or .js file, relative to this config (got ${JSON.stringify(entry)})`,
56
+ );
57
+ return [name, path.resolve(baseDir, entry)];
58
+ }),
59
+ );
60
+ }
61
+ }