@akanjs/devkit 3.3.0-rc.8 → 4.0.0-rc.0

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 (347) hide show
  1. package/DEV_RUNTIME_KNOBS.md +1 -1
  2. package/README.ko.md +7 -1
  3. package/README.md +7 -1
  4. package/akanApp/akanApp.host.test.ts +3 -1
  5. package/akanApp/akanApp.host.ts +26 -2
  6. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  7. package/akanApp/devHostPolicy.ts +5 -0
  8. package/akanApp/devMetadataRestart.ts +93 -0
  9. package/akanApp/devRecycler.test.ts +2 -0
  10. package/akanApp/devRecycler.ts +9 -0
  11. package/akanConfig/akanBin.ts +4 -0
  12. package/akanConfig/akanConfig.test.ts +269 -18
  13. package/akanConfig/akanConfig.ts +104 -210
  14. package/akanConfig/akanPreview.test.ts +28 -0
  15. package/akanConfig/akanPreview.ts +24 -0
  16. package/akanConfig/akanWorkers.test.ts +73 -0
  17. package/akanConfig/akanWorkers.ts +61 -0
  18. package/akanConfig/desktopServerConfig.ts +96 -0
  19. package/akanConfig/dockerImage.ts +212 -0
  20. package/akanConfig/index.ts +3 -0
  21. package/akanConfig/nativeFileSettings.ts +33 -0
  22. package/akanConfig/types.ts +4 -0
  23. package/app/appBin.test.ts +63 -0
  24. package/app/appBin.ts +50 -0
  25. package/app/applicationBuildReporter.test.ts +51 -1
  26. package/app/applicationBuildReporter.ts +6 -1
  27. package/app/applicationBuildRunner.test.ts +358 -5
  28. package/app/applicationBuildRunner.ts +221 -31
  29. package/app/clientServerBoundary.test.ts +115 -0
  30. package/app/clientServerBoundary.ts +89 -0
  31. package/app/dictionarySizes.test.ts +40 -0
  32. package/app/dictionarySizes.ts +95 -0
  33. package/app/routeFilesReport.test.ts +59 -0
  34. package/app/routeFilesReport.ts +46 -0
  35. package/app/routeJsBudget.ts +18 -4
  36. package/artifact/implicitRootLayout.test.ts +19 -0
  37. package/artifact/implicitRootLayout.ts +16 -2
  38. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  39. package/artifact/storeBootstrap.test.ts +28 -0
  40. package/artifact/storeBootstrap.ts +64 -8
  41. package/biome.base.json +7 -5
  42. package/codeAgent/index.ts +1 -34
  43. package/codeAgent/skills/akan-agent/SKILL.md +2 -2
  44. package/codeAgent/skills/akan-debug/SKILL.md +8 -3
  45. package/codeAgent/skills/akan-deps/SKILL.md +10 -3
  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 +65 -30
  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 +21 -20
  53. package/codeAgent/skills/akan-transport/SKILL.md +5 -14
  54. package/codeAgent/skills/akan-ui/SKILL.md +16 -21
  55. package/codeAgent/skills/akan-validate/SKILL.md +8 -2
  56. package/commandDecorators/command.ts +28 -12
  57. package/commandDecorators/commandBuilder.ts +8 -1
  58. package/commandDecorators/commandDecorators.test.ts +70 -3
  59. package/commandDecorators/helpFormatter.ts +14 -12
  60. package/context/akanContext.ts +2 -0
  61. package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
  62. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  63. package/docs/apiReference.test.ts +25 -0
  64. package/docs/apiReference.ts +38 -5
  65. package/docs/declarationReader.ts +30 -0
  66. package/executors/appExecutor.ts +26 -12
  67. package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
  68. package/executors/clientRuntimeKeys.fixture.json +393 -0
  69. package/executors/clientRuntimeKeys.test.ts +1690 -0
  70. package/executors/executor.ts +14 -6
  71. package/executors/executors.test.ts +155 -1
  72. package/executors/pkgExecutor.ts +2 -1
  73. package/executors/sysExecutor.ts +112 -8
  74. package/executors/workspaceExecutor.ts +7 -4
  75. package/frontendBuild/allRoutesBuilder.ts +99 -7
  76. package/frontendBuild/autoImportSync.ts +3 -2
  77. package/frontendBuild/buildRouteClient.test.ts +684 -6
  78. package/frontendBuild/clientBuildTypes.ts +26 -0
  79. package/frontendBuild/clientEntriesBundler.ts +49 -1
  80. package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
  81. package/frontendBuild/clientEntryDiscovery.ts +134 -12
  82. package/frontendBuild/clientEntryGroups.test.ts +77 -0
  83. package/frontendBuild/clientEntryGroups.ts +61 -0
  84. package/frontendBuild/csrDevArtifactWriter.ts +2 -2
  85. package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
  86. package/frontendBuild/csrDevModuleCompiler.ts +44 -8
  87. package/frontendBuild/csrDevPatcher.test.ts +4 -5
  88. package/frontendBuild/csrDevPatcher.ts +37 -11
  89. package/frontendBuild/csrDevTypes.ts +9 -0
  90. package/frontendBuild/devBarrelImports.test.ts +124 -0
  91. package/frontendBuild/devBarrelImports.ts +81 -21
  92. package/frontendBuild/devChangePlanner.ts +0 -1
  93. package/frontendBuild/devRegistryBundler.ts +4 -2
  94. package/frontendBuild/devRouteRuntime.test.ts +492 -0
  95. package/frontendBuild/devRouteRuntime.ts +167 -0
  96. package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
  97. package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
  98. package/frontendBuild/dictionaryConstants.ts +136 -0
  99. package/frontendBuild/dictionaryOwnParts.ts +88 -0
  100. package/frontendBuild/dictionaryPackState.ts +131 -0
  101. package/frontendBuild/dictionaryPacking.test.ts +207 -0
  102. package/frontendBuild/dictionaryPacking.ts +160 -0
  103. package/frontendBuild/dictionaryRoutes.test.ts +251 -0
  104. package/frontendBuild/dictionaryRoutes.ts +227 -0
  105. package/frontendBuild/frontendBuild.test.ts +5 -3
  106. package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
  107. package/frontendBuild/pagesBundleBuilder.ts +78 -2
  108. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  109. package/frontendBuild/precompressArtifacts.ts +34 -8
  110. package/frontendBuild/registryMetadataFingerprint.ts +3 -3
  111. package/frontendBuild/renderedEntries.ts +144 -0
  112. package/frontendBuild/routeClientBuilder.ts +407 -43
  113. package/frontendBuild/routeHandoffs.test.ts +155 -0
  114. package/frontendBuild/routeHandoffs.ts +117 -0
  115. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  116. package/frontendBuild/routeModulePreloads.ts +20 -11
  117. package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
  118. package/frontendBuild/routeRuntimeCheck.ts +248 -0
  119. package/frontendBuild/routeRuntimePays.test.ts +143 -0
  120. package/frontendBuild/routeRuntimePays.ts +117 -0
  121. package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
  122. package/frontendBuild/ssrDevBundler.test.ts +150 -1
  123. package/frontendBuild/ssrDevBundler.ts +66 -11
  124. package/frontendBuild/vendorFileImports.test.ts +254 -0
  125. package/frontendBuild/vendorFileImports.ts +163 -0
  126. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  127. package/frontendBuild/vendorNarrowing.ts +38 -2
  128. package/frontendBuild/vendorSpecifiers.ts +2 -0
  129. package/guideline/agentAssets.ts +1 -1
  130. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  131. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  132. package/incrementalBuilder/builderWatch.ts +11 -1
  133. package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
  134. package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
  135. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  136. package/incrementalBuilder/pendingMetadata.ts +19 -0
  137. package/integration/devStability.integration.test.ts +46 -21
  138. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  139. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  140. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  141. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  142. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  143. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  144. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  145. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  146. package/lint/biomeBase.test.ts +50 -3
  147. package/lint/biomeBase.ts +1 -1
  148. package/lint/biomeCheck.test.ts +162 -0
  149. package/lint/biomeCheck.ts +131 -0
  150. package/lint/linter.test.ts +16 -11
  151. package/lint/no-arbitrary-color.grit +5 -0
  152. package/lint/no-conditional-st-hook.grit +5 -1
  153. package/lint/no-daisyui-legacy-class.grit +8 -0
  154. package/lint/no-document-cookie.grit +3 -0
  155. package/lint/no-inline-color.grit +10 -2
  156. package/lint/no-oversized-list-limit.grit +2 -0
  157. package/lint/no-raw-palette-class.grit +7 -0
  158. package/lint/no-unpublished-form-setter.grit +2 -0
  159. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  160. package/lint/no-web-storage.grit +3 -0
  161. package/lint/withheldEnvFile.ts +17 -0
  162. package/mobile/desktopBin.ts +2 -2
  163. package/mobile/desktopServerStage.test.ts +18 -3
  164. package/mobile/desktopServerStage.ts +7 -2
  165. package/mobile/nativeApp.test.ts +7 -5
  166. package/mobile/nativeApp.ts +2 -2
  167. package/mobile/nativeConfig.test.ts +17 -1
  168. package/mobile/nativeConfig.ts +11 -6
  169. package/mobile/nativePublicEnv.ts +1 -1
  170. package/mobile/serverBundleSecrets.ts +43 -0
  171. package/package.json +11 -12
  172. package/packageExports.test.ts +3 -2
  173. package/preview/PreviewView.ts +25 -3
  174. package/quality/dictionaryKeys.test.ts +356 -0
  175. package/quality/dictionaryKeys.ts +488 -0
  176. package/quality/objectImportReport.test.ts +36 -0
  177. package/quality/objectImportReport.ts +105 -0
  178. package/quality/qualityScanner.ts +1 -1
  179. package/quality/routeRuntimeReport.test.ts +91 -0
  180. package/quality/routeRuntimeReport.ts +121 -0
  181. package/quality/runtimeConstantFacts.ts +71 -0
  182. package/quality/runtimeConstantGraph.ts +123 -0
  183. package/quality/runtimeConstantReads.ts +116 -0
  184. package/quality/runtimeImports.test.ts +190 -0
  185. package/quality/runtimeImports.ts +233 -0
  186. package/quality/runtimeKeyNames.ts +46 -0
  187. package/quality/runtimeLexicalScope.ts +132 -0
  188. package/quality/runtimeMarkerReach.test.ts +84 -0
  189. package/quality/runtimeMarkerReach.ts +255 -0
  190. package/quality/runtimeModuleFacts.ts +290 -0
  191. package/quality/runtimeNameTable.test.ts +172 -0
  192. package/quality/runtimeNameTable.ts +477 -0
  193. package/quality/runtimeScopeReport.test.ts +123 -0
  194. package/quality/runtimeScopeReport.ts +167 -0
  195. package/quality/runtimeSliceKey.ts +269 -0
  196. package/quality/runtimeSyntax.ts +133 -0
  197. package/quality/runtimeTable.fixture.ts +189 -0
  198. package/quality/runtimeUse.test.ts +737 -0
  199. package/quality/runtimeUse.ts +696 -0
  200. package/quality/runtimeUseReadable.test.ts +393 -0
  201. package/quality/ssrScanner.test.ts +13 -0
  202. package/quality/ssrScanner.ts +1 -1
  203. package/quality/translatorBindings.ts +187 -0
  204. package/test/fakeTerminal.ts +45 -0
  205. package/test/secretEnvFixture.ts +134 -0
  206. package/test/testHelpers.ts +11 -0
  207. package/transforms/barrelAnalyzer.ts +24 -2
  208. package/transforms/barrelImportsPlugin.ts +121 -32
  209. package/transforms/exportReach.test.ts +162 -0
  210. package/transforms/exportReach.ts +308 -0
  211. package/transforms/frameworkObjects.fixture.tsx +58 -0
  212. package/transforms/frameworkObjects.test.ts +54 -0
  213. package/transforms/modelReference.test.ts +196 -0
  214. package/transforms/modelReference.ts +39 -0
  215. package/transforms/moduleParts.test.ts +225 -0
  216. package/transforms/moduleParts.ts +418 -0
  217. package/transforms/objectImportEdits.ts +150 -0
  218. package/transforms/objectMemberImports.test.ts +633 -0
  219. package/transforms/objectMemberImports.ts +571 -0
  220. package/transforms/objectMemberLookup.ts +150 -0
  221. package/transforms/objectModule.test.ts +307 -0
  222. package/transforms/objectModule.ts +482 -0
  223. package/transforms/objectModuleAnalyzer.ts +104 -0
  224. package/transforms/partImports.test.ts +76 -0
  225. package/transforms/partImports.ts +110 -0
  226. package/transforms/partModules.test.ts +187 -0
  227. package/transforms/partModules.ts +90 -0
  228. package/transforms/partPurity.ts +124 -0
  229. package/transforms/reactIconImports.test.ts +231 -0
  230. package/transforms/reactIconImports.ts +325 -0
  231. package/transforms/routeConstants.ts +122 -0
  232. package/transforms/routeRuntime.test.ts +835 -0
  233. package/transforms/routeRuntime.ts +703 -0
  234. package/transforms/routeRuntimeEdits.ts +92 -0
  235. package/transforms/routeRuntimeGraph.ts +66 -0
  236. package/transforms/routeRuntimePlan.ts +244 -0
  237. package/transforms/secretEnvDeclaration.test.ts +208 -0
  238. package/transforms/secretEnvDeclaration.ts +213 -0
  239. package/transforms/secretEnvFile.test.ts +117 -0
  240. package/transforms/secretEnvFile.ts +113 -0
  241. package/transforms/secretEnvName.test.ts +54 -0
  242. package/transforms/secretEnvName.ts +29 -0
  243. package/transforms/secretEnvSource.test.ts +148 -0
  244. package/transforms/secretEnvSource.ts +166 -0
  245. package/transforms/serverEnvEvaluationError.ts +11 -0
  246. package/transforms/serverEnvPlugin.test.ts +2 -1
  247. package/transforms/serverEnvPlugin.ts +13 -0
  248. package/transforms/serverEnvProfile.test.ts +129 -2
  249. package/transforms/serverEnvProfile.ts +126 -40
  250. package/transforms/serverEnvSecrets.test.ts +292 -0
  251. package/transforms/signalDescriptors.test.ts +280 -0
  252. package/transforms/signalDescriptors.ts +227 -0
  253. package/transforms/thisFreeExports.ts +87 -0
  254. package/transforms/transforms.test.ts +177 -0
  255. package/transforms/tsconfigPackageResolver.test.ts +1 -0
  256. package/tunnel/createTunnel.ts +5 -1
  257. package/tunnel/ssh2Module.test.ts +37 -0
  258. package/tunnel/ssh2Module.ts +28 -0
  259. package/tunnel/sshTunnel.ts +4 -2
  260. package/typecheck/projectTypecheck.test.ts +32 -1
  261. package/typecheck/projectTypecheck.ts +3 -3
  262. package/typecheck/typeChecker.test.ts +49 -0
  263. package/typecheck/typeChecker.ts +9 -7
  264. package/typecheck/withheldDiagnostics.ts +41 -0
  265. package/util/devInstallCommand.ts +7 -0
  266. package/util/jsonFormatter.test.ts +13 -9
  267. package/workflow/executor.ts +6 -2
  268. package/workflow/index.ts +1 -0
  269. package/workflow/plan.ts +36 -7
  270. package/workflow/types.ts +1 -1
  271. package/workflow/uiTarget.ts +50 -0
  272. package/workspace/envSeed.test.ts +30 -1
  273. package/workspace/envSeed.ts +30 -1
  274. package/workspace/mainCheckout.test.ts +55 -0
  275. package/workspace/mainCheckout.ts +38 -0
  276. package/workspace/scanInfo.test.ts +39 -0
  277. package/workspace/scanInfo.ts +55 -6
  278. package/workspace/slicePlanner.ts +2 -1
  279. package/workspace/workspaceLayout.test.ts +22 -1
  280. package/workspace/workspaceLayout.ts +3 -3
  281. package/CHANGELOG.md +0 -2903
  282. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  283. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  284. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  285. package/codeAgent/agent/CodeAgent.ts +0 -626
  286. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  287. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  288. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  289. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  290. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  291. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  292. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  293. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  294. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  295. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  296. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  297. package/codeAgent/agent/CodeMailbox.ts +0 -148
  298. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  299. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  300. package/codeAgent/agent/SubagentPool.ts +0 -219
  301. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  302. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  303. package/codeAgent/agent/akanCodeModel.ts +0 -47
  304. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  305. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  306. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  307. package/codeAgent/agent/codeAgent.test.ts +0 -337
  308. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  309. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  310. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  311. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  312. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  313. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  314. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  315. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  316. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  317. package/codeAgent/agent/consoleToStderr.ts +0 -8
  318. package/codeAgent/agent/jsonLines.ts +0 -29
  319. package/codeAgent/agent/stringArg.ts +0 -5
  320. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  321. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  322. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  323. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  324. package/codeAgent/tools/AkanCli.ts +0 -51
  325. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  326. package/codeAgent/tools/AkanEditScope.ts +0 -53
  327. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  328. package/codeAgent/tools/AkanToolPack.ts +0 -86
  329. package/codeAgent/tools/AkanVerifier.ts +0 -30
  330. package/codeAgent/tools/AskToolPack.ts +0 -99
  331. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  332. package/codeAgent/tools/MailToolPack.ts +0 -76
  333. package/codeAgent/tools/McpClient.ts +0 -209
  334. package/codeAgent/tools/McpOAuth.ts +0 -233
  335. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  336. package/codeAgent/tools/McpServerConfig.ts +0 -131
  337. package/codeAgent/tools/McpSignIn.ts +0 -158
  338. package/codeAgent/tools/McpTokenStore.ts +0 -128
  339. package/codeAgent/tools/McpToolPack.ts +0 -206
  340. package/codeAgent/tools/SessionToolPack.ts +0 -91
  341. package/codeAgent/tools/WebToolPack.ts +0 -315
  342. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  343. package/codeAgent/tools/askToolPack.test.ts +0 -116
  344. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  345. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  346. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  347. package/piDependencyPins.test.ts +0 -45
@@ -1,44 +1,44 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import type { AkanPlugin } from "akanjs";
4
+ import type { AkanPlugin, AkanPreviewConfig } 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 { DEFAULT_DOCKER_IMAGE, DOCKER_RUN_USER, DOCKER_WRITE_DIRS } from "./dockerImage";
12
+ import { AkanPreview } from "./akanPreview";
13
+ import { AkanWorkers, type LibWorkers } from "./akanWorkers";
14
+ import { DesktopServerConfig } from "./desktopServerConfig";
15
+ import { dockerfileOf, resolveDocker, resolveDockerVariants } from "./dockerImage";
16
+ import { NativeFileSettings } from "./nativeFileSettings";
15
17
  import { nativeKeys } from "./nativeKeys";
16
- import {
17
- type AkanApiConfig,
18
- type AkanAssetsConfig,
19
- type AkanBinConfig,
20
- type AkanDatabaseConfig,
21
- type AkanNativeAppConfig,
22
- type AkanNativeAppResult,
23
- type AkanNativeDeepLinks,
24
- type AkanNativeDesktopConfig,
25
- type AkanNativeSettings,
26
- type AkanNativeTarget,
27
- type AkanNativeUpdatesConfig,
28
- type AkanRouteConfig,
29
- type AkanWebConfig,
30
- type AkanWebOption,
31
- type AppConfigResult,
32
- type Arch,
33
- archs,
34
- type DatabaseMode,
35
- type DeepPartial,
36
- type DockerConfig,
37
- type DockerOption,
38
- type DockerRun,
39
- type LibAssetsConfig,
40
- type LibConfigResult,
41
- type LibDockerConfig,
18
+ import type {
19
+ AkanApiConfig,
20
+ AkanAssetsConfig,
21
+ AkanBinConfig,
22
+ AkanDatabaseConfig,
23
+ AkanNativeAppConfig,
24
+ AkanNativeAppResult,
25
+ AkanNativeDeepLinks,
26
+ AkanNativeSettings,
27
+ AkanNativeTarget,
28
+ AkanNativeUpdatesConfig,
29
+ AkanRouteConfig,
30
+ AkanWebConfig,
31
+ AkanWebOption,
32
+ AkanWorkersConfig,
33
+ AppConfigResult,
34
+ DatabaseMode,
35
+ DeepPartial,
36
+ DockerConfig,
37
+ DockerImageConfig,
38
+ DockerOption,
39
+ LibAssetsConfig,
40
+ LibConfigResult,
41
+ LibDockerConfig,
42
42
  } from "./types";
43
43
 
44
44
  const DEFAULT_BARREL_IMPORTS = ["akanjs/webkit", "akanjs/common", "akanjs/ui", "akanjs/server"];
@@ -123,6 +123,7 @@ export interface LibContributions {
123
123
  trustedDependencies?: string[];
124
124
  /** Per lib, since an app carries only the entries of the libs it depends on. */
125
125
  bin?: { lib: string; bin: AkanBinConfig }[];
126
+ workers?: LibWorkers[];
126
127
  docker: LibDockerConfig;
127
128
  /** Keep globs rewritten to the app's own `public/`, where `akan sync` mounts each lib's assets. */
128
129
  keepFonts?: string[];
@@ -132,7 +133,8 @@ const emptyLibContributions = (): LibContributions => ({
132
133
  externalLibs: [],
133
134
  trustedDependencies: [],
134
135
  bin: [],
135
- docker: { preRuns: [], postRuns: [] },
136
+ workers: [],
137
+ docker: { preRuns: [], installRuns: [], postRuns: [] },
136
138
  keepFonts: [],
137
139
  });
138
140
 
@@ -147,13 +149,6 @@ const normalizeKeepFonts = (keepFonts: string[] | undefined) => [
147
149
  ...new Set((keepFonts ?? []).map((glob) => glob.trim().replace(/^\/+/, "")).filter(Boolean)),
148
150
  ];
149
151
 
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
152
  class LibConfigRefusal extends Error {}
158
153
 
159
154
  export class AkanAppConfig implements AppConfigResult {
@@ -162,6 +157,8 @@ export class AkanAppConfig implements AppConfigResult {
162
157
  docker: DockerConfig;
163
158
  /** The Dockerfile `akan build` writes: the declared string verbatim, or one assembled from the parts. */
164
159
  dockerfile: string;
160
+ /** Each is the app's `docker` with the variant's fields replaced; a lib's steps reach every one. */
161
+ dockerVariants: Record<string, DockerImageConfig>;
165
162
  database: AkanDatabaseConfig;
166
163
  web: AkanWebConfig;
167
164
  externalLibs: string[];
@@ -169,6 +166,8 @@ export class AkanAppConfig implements AppConfigResult {
169
166
  /** The app's own entries; the libs' are in `libBins`. */
170
167
  bin: AkanBinConfig;
171
168
  libBins: { lib: string; bin: AkanBinConfig }[];
169
+ /** The app's own entries; `App.selectWorkers` adds those of the libs it depends on. */
170
+ workers: AkanWorkersConfig;
172
171
  barrelImports: string[];
173
172
  optimizeImports: string[];
174
173
  images: AkanImageConfig;
@@ -186,9 +185,12 @@ export class AkanAppConfig implements AppConfigResult {
186
185
  libs: string[];
187
186
  /** Live-only: plugins declared in this app's `akan.config.ts` (never serialized). */
188
187
  plugins: AkanPlugin[];
188
+ /** Live-only: `akan preview` reads it from this app's `akan.config.ts` (never serialized). */
189
+ preview: AkanPreviewConfig = {};
189
190
  domains = new Set<string>();
190
191
  subRoutes = new Map<string, Set<string>>();
191
192
  basePaths = new Set<string>();
193
+ routePageLibs = new Map<string, string[] | boolean>();
192
194
  branches = new Set<string>(["debug", "develop", "main"]);
193
195
  constructor(
194
196
  app: App,
@@ -216,6 +218,11 @@ export class AkanAppConfig implements AppConfigResult {
216
218
  ];
217
219
  this.bin = AkanBin.parse(config?.bin, owner, app.cwdPath);
218
220
  this.libBins = libContributions.bin ?? [];
221
+ this.workers = AkanWorkers.parse(config?.workers, owner, app.cwdPath);
222
+ //? The dependency scan reads this config, so every workspace lib's entry is published; a start, test or build names the mounted ones.
223
+ AkanWorkers.publish(
224
+ AkanWorkers.select({ owner, workers: this.workers }, libContributions.workers ?? [], libs, { strict: false }),
225
+ );
219
226
  this.barrelImports = [
220
227
  ...DEFAULT_BARREL_IMPORTS,
221
228
  ...WORKSPACE_BARREL_FACETS.map((facet) => `@apps/${app.name}/${facet}`),
@@ -251,7 +258,8 @@ export class AkanAppConfig implements AppConfigResult {
251
258
  this.hasNativeConfig = Boolean(config.native);
252
259
  this.native = this.#resolveNativeConfig(config.native);
253
260
  this.web = this.#resolveWebConfig(config.web);
254
- this.docker = AkanAppConfig.#resolveDocker(config.docker, libContributions.docker);
261
+ this.docker = resolveDocker(config.docker, libContributions.docker);
262
+ this.dockerVariants = resolveDockerVariants(config.docker, libContributions.docker);
255
263
  this.dockerfile = this.#makeDockerfile();
256
264
  }
257
265
  #resolveWebConfig(web: AkanWebOption | undefined): AkanWebConfig {
@@ -267,7 +275,7 @@ export class AkanAppConfig implements AppConfigResult {
267
275
  const configPath = `apps/${this.app.name}/akan.config.ts`;
268
276
  const { targets: rawTargets, ...root } = native ?? {};
269
277
  AkanAppConfig.#assertNativeKeys(root, "native", configPath);
270
- AkanAppConfig.#assertFiles(root, "native", configPath);
278
+ NativeFileSettings.assert(root, "native", configPath);
271
279
  const appName = root.appName ?? this.app.name;
272
280
  const appId = root.appId ?? deriveDefaultAppId(this.baseDevEnv.repoName, this.app.name);
273
281
  const version = root.version ?? "0.0.1";
@@ -295,7 +303,7 @@ export class AkanAppConfig implements AppConfigResult {
295
303
  throw new Error(
296
304
  `${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
305
  );
298
- AkanAppConfig.#assertFiles(own ?? {}, where, configPath);
306
+ NativeFileSettings.assert(own ?? {}, where, configPath);
299
307
  const {
300
308
  basePath: _basePath,
301
309
  indexPath: rawIndexPath,
@@ -323,7 +331,7 @@ export class AkanAppConfig implements AppConfigResult {
323
331
  : {}),
324
332
  ...(merged.desktop
325
333
  ? {
326
- desktop: AkanAppConfig.#desktopServer(
334
+ desktop: DesktopServerConfig.resolve(
327
335
  AkanAppConfig.#platformIndexPath(merged.desktop),
328
336
  `${where}.desktop.server`,
329
337
  configPath,
@@ -341,93 +349,6 @@ export class AkanAppConfig implements AppConfigResult {
341
349
  );
342
350
  return { appName, appId, ...(root.fileName ? { fileName: root.fileName } : {}), version, buildNum, targets };
343
351
  }
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
352
  static #platformIndexPath<T extends { indexPath?: string }>(section: T): T {
432
353
  const { indexPath: rawIndexPath, ...rest } = section;
433
354
  const indexPath = normalizeIndexPath(rawIndexPath);
@@ -486,39 +407,22 @@ export class AkanAppConfig implements AppConfigResult {
486
407
  check(settings.desktop?.externalView, nativeKeys.externalView, `${where}.desktop.externalView`, "externalView");
487
408
  check(settings.deepLinks, nativeKeys.deepLinks, `${where}.deepLinks`, "deepLinks");
488
409
  }
489
- static readonly #androidFilePattern = /^(?:res\/[^/]+\/[^/]+|assets\/.+)$/;
490
- static #assertFiles(settings: AkanNativeSettings, where: string, configPath: string) {
491
- const check = (
492
- files: Record<string, string> | undefined,
493
- at: string,
494
- valid: (to: string) => boolean,
495
- shape: string,
496
- ) => {
497
- for (const [to, from] of Object.entries(files ?? {})) {
498
- if (typeof from !== "string")
499
- throw new Error(
500
- `${at}["${to}"] in ${configPath} must name its source file, relative to the app folder, e.g. { "${shape}": "assets/chime.mp3" }.`,
501
- );
502
- if (!valid(to)) throw new Error(`${at}["${to}"] in ${configPath} must land at ${shape}.`);
503
- }
504
- };
505
- check(
506
- settings.ios?.files,
507
- `${where}.ios.files`,
508
- (to) => to.length > 0 && !to.startsWith("/") && !to.split("/").includes(".."),
509
- "<path in the app bundle>",
510
- );
511
- check(
512
- settings.android?.files,
513
- `${where}.android.files`,
514
- (to) => AkanAppConfig.#androidFilePattern.test(to),
515
- "res/<type>/<file> or assets/<path>",
516
- );
517
- }
518
410
  #applyRoutes(routes: AkanRouteConfig[] = []) {
519
411
  for (const route of routes) {
520
412
  const basePath = route.basePath ? trimSlashes(route.basePath) : null;
521
413
  if (basePath !== null) this.basePaths.add(basePath);
414
+ if (route.syncPageLibs !== undefined) {
415
+ if (basePath === null)
416
+ throw new Error(
417
+ `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.`,
418
+ );
419
+ const earlier = this.routePageLibs.get(basePath);
420
+ if (earlier !== undefined && JSON.stringify(earlier) !== JSON.stringify(route.syncPageLibs))
421
+ throw new Error(
422
+ `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.`,
423
+ );
424
+ this.routePageLibs.set(basePath, route.syncPageLibs);
425
+ }
522
426
  const domains = basePath !== null ? this.subRoutes.getOrInsert(basePath, new Set()) : this.domains;
523
427
  for (const branch of Object.keys(route.domains)) this.branches.add(branch);
524
428
  for (const domain of Object.values(route.domains).flat())
@@ -533,33 +437,6 @@ export class AkanAppConfig implements AppConfigResult {
533
437
  this.branches.forEach((domain) => void domains.add(`${basePath}-${domain}.${serveDomain}`));
534
438
  });
535
439
  }
536
- #getDockerRunScripts(runs: DockerRun[]) {
537
- return runs.map((run) => {
538
- if (typeof run === "string") return `RUN ${run}`;
539
- else
540
- return Object.entries(run)
541
- .map(
542
- ([arch, script]) => `RUN if [ "$TARGETARCH" = "${arch}" ]; then \
543
- ${script}; \
544
- fi`,
545
- )
546
- .join("\n");
547
- });
548
- }
549
- #getDockerImageScript(image: string | { [key in Arch]?: string }, defaultImage: string) {
550
- if (typeof image === "string") return `FROM ${image}`;
551
- else return archs.map((arch) => `FROM ${image[arch] ?? defaultImage} AS ${arch}`).join("\n");
552
- }
553
- /** A declared Dockerfile string is verbatim, so a lib's steps are dropped rather than silently unapplied. */
554
- static #resolveDocker(docker: DockerOption | undefined, libDocker: LibDockerConfig): DockerConfig {
555
- if (typeof docker === "string") return docker;
556
- return {
557
- image: docker?.image ?? DEFAULT_DOCKER_IMAGE,
558
- preRuns: dedupeDockerRuns([...libDocker.preRuns, ...(docker?.preRuns ?? [])]),
559
- postRuns: dedupeDockerRuns([...libDocker.postRuns, ...(docker?.postRuns ?? [])]),
560
- command: docker?.command ?? ["bun", "main.js"],
561
- };
562
- }
563
440
  /** What the built server runs with in its image; a desktop app's carried server starts from the same values. */
564
441
  getProductionEnv(environment: string = this.baseDevEnv.env): Record<string, string> {
565
442
  return {
@@ -589,31 +466,24 @@ export class AkanAppConfig implements AppConfigResult {
589
466
  "ARG AKAN_ALLOW_LOCAL_IMAGE",
590
467
  `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`,
591
468
  ].join("\n");
592
- dockerfileFor(environment: string, { lockfile = true }: { lockfile?: boolean } = {}): string {
593
- return this.#makeDockerfile(environment, lockfile);
594
- }
595
- #makeDockerfile(environment?: string, lockfile = true): string {
469
+ dockerfileFor(
470
+ environment: string,
471
+ options: { lockfile?: boolean; env?: Record<string, string>; variant?: string } = {},
472
+ ): string {
473
+ return this.#makeDockerfile(environment, options.lockfile ?? true, options.env, options.variant);
474
+ }
475
+ #makeDockerfile(
476
+ environment?: string,
477
+ lockfile = true,
478
+ env = this.getProductionEnv(environment),
479
+ variant?: string,
480
+ ): string {
596
481
  if (typeof this.docker === "string") return this.docker;
597
- const { image, preRuns, postRuns, command } = this.docker;
598
- const preRunScripts = this.#getDockerRunScripts(preRuns);
599
- const postRunScripts = this.#getDockerRunScripts(postRuns);
600
- const imageScript = this.#getDockerImageScript(image, DEFAULT_DOCKER_IMAGE);
482
+ const docker = variant === undefined ? this.docker : this.dockerVariants[variant];
483
+ if (!docker)
484
+ throw new Error(`[docker] apps/${this.app.name}/akan.config.ts declares no docker variant "${variant}"`);
601
485
  const isLocal = (environment ?? this.baseDevEnv.env) === "local";
602
- const envLines = Object.entries(this.getProductionEnv(environment)).map(([key, value]) => `ENV ${key}=${value}`);
603
- return `${imageScript}${isLocal ? `\n${AkanAppConfig.localImageGuard}` : ""}
604
- RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends ca-certificates tzdata && rm -rf /var/lib/apt/lists/*
605
- RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
606
- ARG TARGETARCH
607
- ${preRunScripts.join("\n")}
608
- WORKDIR /workspace
609
- ${lockfile ? "COPY ./package.json ./bun.lock ./" : "COPY ./package.json ./package.json"}
610
- RUN bun install --production${lockfile ? " --frozen-lockfile" : ""}
611
- ${postRunScripts.join("\n")}
612
- COPY . .
613
- RUN mkdir -p ${DOCKER_WRITE_DIRS.join(" ")} && chown ${DOCKER_RUN_USER} ${DOCKER_WRITE_DIRS.join(" ")}
614
- ${envLines.join("\n")}
615
- USER ${DOCKER_RUN_USER}
616
- CMD [${command.map((c) => `"${c}"`).join(",")}]`;
486
+ return dockerfileOf(docker, { env, lockfile, guard: isLocal ? AkanAppConfig.localImageGuard : undefined });
617
487
  }
618
488
  static #importGeneration = 0;
619
489
  // Bun caches dynamic imports by path; a fresh query string re-evaluates the config module (its imports stay cached).
@@ -640,17 +510,29 @@ CMD [${command.map((c) => `"${c}"`).join(",")}]`;
640
510
  const {
641
511
  plugins,
642
512
  pipeline: _pipeline,
513
+ preview,
643
514
  ...config
644
515
  } = (resolved ?? {}) as AppConfigDeclaration & {
645
516
  plugins?: AkanPlugin[];
646
517
  pipeline?: unknown;
518
+ preview?: unknown;
647
519
  };
648
520
  if ("subspace" in config)
649
521
  throw new Error(
650
522
  `apps/${app.name}/akan.config.ts declares \`subspace\`, a workspace setting: it belongs in the workspace root akan.config.ts.`,
651
523
  );
652
524
  const libContributions = await AkanAppConfig.#collectLibContributions(app, libs, bustImportCache);
653
- return new AkanAppConfig(app, libs, rootPackageJson, config, baseDevEnv, plugins ?? [], libContributions);
525
+ const appConfig = new AkanAppConfig(
526
+ app,
527
+ libs,
528
+ rootPackageJson,
529
+ config,
530
+ baseDevEnv,
531
+ plugins ?? [],
532
+ libContributions,
533
+ );
534
+ appConfig.preview = AkanPreview.parse(preview, `apps/${app.name}/akan.config.ts`);
535
+ return appConfig;
654
536
  }
655
537
  //* Every workspace lib is read, not just this app's lib deps: narrowing the set needs the dependency
656
538
  //* scan, and the incremental page rebundle re-reads this config on every file change.
@@ -673,8 +555,14 @@ CMD [${command.map((c) => `"${c}"`).join(",")}]`;
673
555
  bin: libConfigs.flatMap((libConfig) =>
674
556
  libConfig && Object.keys(libConfig.bin).length ? [{ lib: libConfig.lib.name, bin: libConfig.bin }] : [],
675
557
  ),
558
+ workers: libConfigs.flatMap((libConfig) =>
559
+ libConfig && Object.keys(libConfig.workers).length
560
+ ? [{ lib: libConfig.lib.name, workers: libConfig.workers }]
561
+ : [],
562
+ ),
676
563
  docker: {
677
564
  preRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.preRuns ?? []),
565
+ installRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.installRuns ?? []),
678
566
  postRuns: libConfigs.flatMap((libConfig) => libConfig?.docker.postRuns ?? []),
679
567
  },
680
568
  //* A lib writes the glob against its own `public/`; `akan sync` mounts that at `public/libs/<lib>`.
@@ -811,6 +699,7 @@ export class AkanLibConfig implements LibConfigResult {
811
699
  externalLibs: string[];
812
700
  trustedDependencies: string[];
813
701
  bin: AkanBinConfig;
702
+ workers: AkanWorkersConfig;
814
703
  docker: LibDockerConfig;
815
704
  assets: LibAssetsConfig;
816
705
  /** Live-only: plugins declared in this lib's `akan.config.ts` (never serialized). */
@@ -821,7 +710,12 @@ export class AkanLibConfig implements LibConfigResult {
821
710
  const owner = `libs/${lib.name}/akan.config.ts`;
822
711
  this.trustedDependencies = normalizePackageNames(config?.trustedDependencies, owner);
823
712
  this.bin = AkanBin.parse(config?.bin, owner, lib.cwdPath);
824
- this.docker = { preRuns: config?.docker?.preRuns ?? [], postRuns: config?.docker?.postRuns ?? [] };
713
+ this.workers = AkanWorkers.parse(config?.workers, owner, lib.cwdPath);
714
+ this.docker = {
715
+ preRuns: config?.docker?.preRuns ?? [],
716
+ installRuns: config?.docker?.installRuns ?? [],
717
+ postRuns: config?.docker?.postRuns ?? [],
718
+ };
825
719
  this.assets = { keepFonts: normalizeKeepFonts(config?.assets?.keepFonts as string[] | undefined) };
826
720
  this.plugins = plugins;
827
721
  }
@@ -0,0 +1,28 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { AkanPreview } from "./akanPreview";
3
+
4
+ const owner = "apps/demo/akan.config.ts";
5
+
6
+ describe("AkanPreview.parse", () => {
7
+ test("keeps the sign-in function and the example paths, and reads a missing section as empty", () => {
8
+ const signIn = async () => ({ jwt: "token" });
9
+ expect(AkanPreview.parse(undefined, owner)).toEqual({});
10
+ expect(AkanPreview.parse({}, owner)).toEqual({});
11
+ expect(AkanPreview.parse({ signIn, examples: ["/chat/1?tab=files"] }, owner)).toEqual({
12
+ signIn,
13
+ examples: ["/chat/1?tab=files"],
14
+ });
15
+ });
16
+
17
+ test("refuses a section it cannot read, naming the file and the key", () => {
18
+ expect(() => AkanPreview.parse([], owner)).toThrow(`${owner} declares \`preview\`, which has to be an object`);
19
+ expect(() => AkanPreview.parse({ login: () => null }, owner)).toThrow(
20
+ "preview.login; it takes signIn and examples",
21
+ );
22
+ expect(() => AkanPreview.parse({ signIn: "/api/signin" }, owner)).toThrow(
23
+ "preview.signIn, which has to be a function",
24
+ );
25
+ for (const examples of ["/chat/1", ["chat/1"], ["//host/chat/1"], [1]])
26
+ expect(() => AkanPreview.parse({ examples }, owner)).toThrow("preview.examples, which has to list paths");
27
+ });
28
+ });
@@ -0,0 +1,24 @@
1
+ import type { AkanPreviewConfig } from "./types";
2
+
3
+ export class AkanPreview {
4
+ static parse(value: unknown, owner: string): AkanPreviewConfig {
5
+ if (value === undefined) return {};
6
+ if (typeof value !== "object" || value === null || Array.isArray(value))
7
+ throw new Error(`[preview] ${owner} declares \`preview\`, which has to be an object: { signIn, examples }`);
8
+ const { signIn, examples, ...unknown } = value as Record<string, unknown>;
9
+ const [stray] = Object.keys(unknown);
10
+ if (stray) throw new Error(`[preview] ${owner} declares preview.${stray}; it takes signIn and examples`);
11
+ if (signIn !== undefined && typeof signIn !== "function")
12
+ throw new Error(`[preview] ${owner} declares preview.signIn, which has to be a function`);
13
+ if (examples !== undefined && !(Array.isArray(examples) && examples.every(AkanPreview.#isPath)))
14
+ throw new Error(`[preview] ${owner} declares preview.examples, which has to list paths that start with "/"`);
15
+ return {
16
+ ...(signIn ? { signIn: signIn as AkanPreviewConfig["signIn"] } : {}),
17
+ ...(examples ? { examples: examples as string[] } : {}),
18
+ };
19
+ }
20
+
21
+ static #isPath(value: unknown) {
22
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//");
23
+ }
24
+ }
@@ -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
+ }