@akanjs/devkit 3.2.0-rc.2 → 3.2.0-rc.20

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 (365) hide show
  1. package/CHANGELOG.md +315 -11
  2. package/DEV_RUNTIME_KNOBS.md +4 -3
  3. package/README.ko.md +3 -2
  4. package/README.md +4 -2
  5. package/akanApp/BackendImportGraph.test.ts +1 -1
  6. package/akanApp/akanApp.host.test.ts +257 -1
  7. package/akanApp/akanApp.host.ts +146 -1223
  8. package/akanApp/akanApp.host.wiring.test.ts +727 -0
  9. package/akanApp/builderGap.ts +68 -0
  10. package/akanApp/builderRequestRelay.test.ts +93 -0
  11. package/akanApp/builderRequestRelay.ts +100 -0
  12. package/akanApp/builderRssRecycler.ts +182 -0
  13. package/akanApp/devBackend.ts +392 -0
  14. package/akanApp/devBuildStatusBoard.ts +128 -0
  15. package/akanApp/devBuilder.ts +196 -0
  16. package/akanApp/devHostPolicy.test.ts +11 -11
  17. package/akanApp/devHostPolicy.ts +2 -4
  18. package/akanApp/devIdleSuspend.test.ts +221 -0
  19. package/akanApp/devIdleSuspend.ts +192 -0
  20. package/akanApp/devIdleSuspend.watcher.test.ts +120 -0
  21. package/akanApp/devRecycler.test.ts +66 -0
  22. package/akanApp/devRecycler.ts +305 -0
  23. package/akanApp/processRss.ts +61 -0
  24. package/akanConfig/akanConfig.test.ts +24 -1
  25. package/akanConfig/akanConfig.ts +10 -10
  26. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  27. package/akanConfig/productionLockfile.ts +1 -1
  28. package/apiReport/apiDeclarationPrinter.ts +120 -0
  29. package/apiReport/apiReport.test.ts +526 -0
  30. package/apiReport/apiReport.ts +232 -0
  31. package/apiReport/apiReportDiff.ts +160 -0
  32. package/apiReport/apiReportPolicy.ts +65 -0
  33. package/apiReport/apiTargets.ts +311 -0
  34. package/apiReport/changesetBump.ts +19 -0
  35. package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +21 -0
  36. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +10 -49
  37. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +74 -7
  38. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +20 -15
  39. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  40. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +48 -12
  41. package/{routeJsBudget.ts → app/routeJsBudget.ts} +90 -27
  42. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  43. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  44. package/artifact/implicitRootLayout.test.ts +71 -3
  45. package/artifact/implicitRootLayout.ts +21 -4
  46. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  47. package/biome.base.json +2 -1
  48. package/cloud/cloudApi.test.ts +1 -1
  49. package/cloud/configLock.test.ts +1 -1
  50. package/cloud/globalConfig.test.ts +1 -1
  51. package/cloud/globalConfig.ts +1 -1
  52. package/cloud/updatePackUpload.test.ts +1 -1
  53. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  54. package/codeAgent/agent/akanCodePaths.ts +1 -1
  55. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  56. package/codeAgent/agent/codeAgent.test.ts +1 -1
  57. package/codeAgent/skills/akan-debug/SKILL.md +10 -3
  58. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  59. package/codeAgent/skills/akan-mcp/SKILL.md +10 -1
  60. package/codeAgent/skills/akan-scaffold/SKILL.md +2 -2
  61. package/codeAgent/skills/akan-transport/SKILL.md +2 -0
  62. package/codeAgent/skills/akan-validate/SKILL.md +1 -0
  63. package/codeAgent/tools/AkanCli.ts +1 -1
  64. package/codeAgent/tools/AkanToolPack.ts +1 -1
  65. package/codeAgent/tools/McpClient.ts +28 -6
  66. package/codeAgent/tools/McpToolPack.ts +1 -1
  67. package/codeAgent/tools/akanCodePlugins.test.ts +14 -2
  68. package/commandDecorators/argMeta.ts +4 -0
  69. package/commandDecorators/cliError.ts +72 -0
  70. package/commandDecorators/command.ts +165 -91
  71. package/commandDecorators/commandBuilder.ts +1 -1
  72. package/commandDecorators/commandDecorators.test.ts +191 -16
  73. package/commandDecorators/exitCodeError.ts +6 -7
  74. package/commandDecorators/index.ts +1 -0
  75. package/commandDecorators/targetMeta.ts +1 -0
  76. package/commandDecorators/workspaceVersionCheck.test.ts +1 -1
  77. package/commandDecorators/workspaceVersionCheck.ts +1 -1
  78. package/context/akanContext.ts +576 -0
  79. package/context/akanContextInspection.ts +296 -0
  80. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  81. package/{akanMcpContract.ts → context/akanMcpContract.ts} +33 -263
  82. package/context/akanMcpToolError.ts +16 -0
  83. package/context/doctor/agentGuideCheck.ts +81 -0
  84. package/context/doctor/configLeftoverCheck.ts +35 -0
  85. package/context/doctor/doctorFindings.ts +70 -0
  86. package/context/doctor/generatedFreshness.ts +56 -0
  87. package/context/doctor/moduleShapeCheck.ts +88 -0
  88. package/context/doctor/recipeDuplicateCheck.ts +39 -0
  89. package/context/doctor/recipeIndexCheck.ts +87 -0
  90. package/context/doctor/rootShapeCheck.ts +55 -0
  91. package/context/doctor/workflowScope.ts +97 -0
  92. package/{constantFieldNames.test.ts → context/moduleFieldNames.test.ts} +24 -2
  93. package/context/moduleFieldNames.ts +25 -0
  94. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  95. package/context/safeRead.ts +9 -0
  96. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  97. package/devkitUtils.test.ts +39 -5
  98. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  99. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  100. package/docs/errorCodeReference.test.ts +282 -0
  101. package/docs/errorCodeReference.ts +71 -0
  102. package/docs/errorCodeScan.ts +551 -0
  103. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  104. package/executors/appExecutor.ts +448 -0
  105. package/executors/commandExecutionError.ts +53 -0
  106. package/executors/executor.ts +527 -0
  107. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  108. package/{executors.test.ts → executors/executors.test.ts} +76 -15
  109. package/executors/index.ts +8 -0
  110. package/executors/libExecutor.ts +23 -0
  111. package/executors/moduleExecutor.ts +18 -0
  112. package/executors/pkgExecutor.ts +129 -0
  113. package/executors/sysExecutor.ts +301 -0
  114. package/executors/workspaceExecutor.ts +277 -0
  115. package/frontendBuild/allRoutesBuilder.test.ts +17 -5
  116. package/frontendBuild/allRoutesBuilder.ts +24 -6
  117. package/frontendBuild/autoImportSync.test.ts +1 -1
  118. package/frontendBuild/autoImportSync.ts +1 -1
  119. package/frontendBuild/buildRouteClient.test.ts +1 -1
  120. package/frontendBuild/bundleDefine.ts +2 -0
  121. package/frontendBuild/clientBuildTypes.ts +5 -2
  122. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  123. package/frontendBuild/clientEntryDiscovery.test.ts +58 -0
  124. package/frontendBuild/clientEntryDiscovery.ts +25 -6
  125. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  126. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  127. package/frontendBuild/cssCompiler.test.ts +1 -1
  128. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  129. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  130. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  131. package/frontendBuild/fontOptimizer.test.ts +1 -1
  132. package/frontendBuild/fontPruner.test.ts +1 -1
  133. package/frontendBuild/frontendBuild.test.ts +3 -3
  134. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  135. package/frontendBuild/hmrWatcher.test.ts +1 -1
  136. package/frontendBuild/hmrWatcher.ts +22 -1
  137. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  138. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  139. package/frontendBuild/nativeCore.test.ts +148 -0
  140. package/frontendBuild/optionalPeers.test.ts +36 -8
  141. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  142. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  143. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  144. package/frontendBuild/precompressArtifacts.ts +1 -1
  145. package/frontendBuild/serverGraphFile.ts +1 -1
  146. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  147. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +26 -0
  148. package/frontendBuild/ssrBaseArtifactBuilder.ts +23 -19
  149. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  150. package/frontendBuild/vendorImportScanner.test.ts +25 -4
  151. package/frontendBuild/vendorImportScanner.ts +25 -10
  152. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  153. package/frontendBuild/watchRootResolver.test.ts +1 -1
  154. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  155. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  156. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  157. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  158. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  159. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  160. package/{prompter.ts → guideline/prompter.ts} +2 -3
  161. package/incrementalBuilder/buildBatch.proc.ts +14 -4
  162. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  163. package/incrementalBuilder/buildBatchRunner.test.ts +108 -1
  164. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  165. package/incrementalBuilder/builderBoot.ts +106 -0
  166. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  167. package/incrementalBuilder/builderChannel.test.ts +1 -1
  168. package/incrementalBuilder/builderChannel.ts +11 -0
  169. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  170. package/incrementalBuilder/builderLanes.ts +157 -0
  171. package/incrementalBuilder/builderWatch.ts +213 -0
  172. package/incrementalBuilder/csrRegistry.ts +234 -0
  173. package/incrementalBuilder/incrementalBuilder.host.test.ts +30 -1
  174. package/incrementalBuilder/incrementalBuilder.host.ts +10 -22
  175. package/incrementalBuilder/incrementalBuilder.proc.test.ts +93 -2
  176. package/incrementalBuilder/incrementalBuilder.proc.ts +81 -823
  177. package/incrementalBuilder/ssrRegistry.ts +278 -0
  178. package/index.ts +22 -22
  179. package/integration/devStability.integration.test.ts +62 -56
  180. package/integration/devStabilityHarness.test.ts +1 -1
  181. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  182. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  183. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  184. package/lint/gritRules.test.ts +1 -1
  185. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  186. package/lint/no-import-common-err.grit +31 -0
  187. package/lint/no-init-fetch-in-client.grit +1 -1
  188. package/lint/no-web-only-api-outside-webkit.grit +3 -3
  189. package/mobile/desktopBin.test.ts +1 -1
  190. package/mobile/desktopRelease.test.ts +1 -1
  191. package/mobile/desktopServerStage.test.ts +2 -2
  192. package/mobile/desktopServerStage.ts +1 -1
  193. package/mobile/nativeApi.test.ts +1 -1
  194. package/mobile/nativeApp.test.ts +1 -1
  195. package/mobile/nativeConfig.test.ts +1 -1
  196. package/mobile/nativePluginFolders.test.ts +1 -1
  197. package/mobile/nativePublicEnv.test.ts +1 -1
  198. package/mobile/nativeWebDir.test.ts +1 -1
  199. package/mobile/serverBundleSecrets.test.ts +1 -1
  200. package/mobile/tarWriter.test.ts +1 -1
  201. package/mobile/updatePackFolder.test.ts +1 -1
  202. package/package.json +167 -3
  203. package/packageExports.test.ts +20 -2
  204. package/piDependencyPins.test.ts +1 -1
  205. package/pipeline/PipelineDefinition.ts +1 -1
  206. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  207. package/platformTest/PlatformTestRun.test.ts +1 -1
  208. package/platformTest/TestSnapshot.test.ts +1 -1
  209. package/preview/PreviewView.ts +32 -11
  210. package/preview/previewView.test.ts +76 -9
  211. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  212. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  213. package/quality/bareErrorScanner.ts +126 -0
  214. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  215. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  216. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  217. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  218. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  219. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  220. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  221. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  222. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +1 -1
  223. package/{qualityScanner.ts → quality/qualityScanner.ts} +8 -8
  224. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  225. package/{subspace.test.ts → subspace/subspace.test.ts} +9 -3
  226. package/{subspace.ts → subspace/subspace.ts} +5 -5
  227. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  228. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  229. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  230. package/transforms/barrelAnalyzer.ts +26 -8
  231. package/transforms/browserDirnamePlugin.test.ts +1 -1
  232. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  233. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  234. package/transforms/pureLazyMarker.test.ts +1 -1
  235. package/transforms/serverEnvPlugin.test.ts +1 -1
  236. package/transforms/serverEnvProfile.test.ts +1 -1
  237. package/transforms/sideEffectImportOrder.test.ts +1 -1
  238. package/transforms/transforms.test.ts +29 -2
  239. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  240. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  241. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  242. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  243. package/typecheck/projectTypecheck.test.ts +1 -1
  244. package/typecheck/projectTypecheck.ts +6 -2
  245. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  246. package/{typeChecker.ts → typecheck/typeChecker.ts} +1 -1
  247. package/typecheck/typecheck.proc.ts +4 -3
  248. package/typecheck/typecheckFailure.ts +7 -2
  249. package/util/errorReport.ts +66 -0
  250. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  251. package/workflow/artifacts.ts +8 -7
  252. package/workflow/constantSource.ts +187 -0
  253. package/workflow/dictionarySource.ts +184 -0
  254. package/workflow/executor.ts +6 -9
  255. package/workflow/fieldExpression.ts +153 -0
  256. package/workflow/fieldLabel.ts +61 -0
  257. package/workflow/fieldOrder.ts +117 -0
  258. package/workflow/fieldType.ts +93 -0
  259. package/workflow/guardCatalog.test.ts +1 -1
  260. package/workflow/index.ts +2 -0
  261. package/workflow/keyRename.ts +1 -1
  262. package/workflow/moduleIndex.test.ts +2 -2
  263. package/workflow/moduleIndex.ts +2 -2
  264. package/workflow/modulePaths.ts +27 -0
  265. package/workflow/mutationScaffold.ts +7 -15
  266. package/workflow/mutationSource.ts +2 -1
  267. package/workflow/plainName.ts +28 -0
  268. package/workflow/plan.ts +15 -9
  269. package/workflow/primitiveReport.ts +78 -0
  270. package/workflow/rolloutGate.test.ts +1 -1
  271. package/workflow/rolloutGate.ts +1 -1
  272. package/workflow/serviceSource.ts +33 -0
  273. package/workflow/signalSource.ts +96 -0
  274. package/workflow/source.ts +50 -1105
  275. package/workflow/sourceAst.ts +30 -0
  276. package/workflow/sourceImports.ts +105 -0
  277. package/workflow/sourceText.ts +13 -0
  278. package/workflow/templateSource.ts +30 -0
  279. package/workflow/testSource.ts +31 -0
  280. package/workflow/types.ts +1 -1
  281. package/workflow/uiPolicy.ts +1 -1
  282. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  283. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  284. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  285. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  286. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  287. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  288. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  289. package/{libSource.ts → workspace/libSource.ts} +1 -1
  290. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  291. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  292. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  293. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +85 -1
  294. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +41 -6
  295. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  296. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  297. package/akanContext.ts +0 -1084
  298. package/constantFieldNames.ts +0 -18
  299. package/executors.ts +0 -1749
  300. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  301. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  302. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  303. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  304. /package/{linter.ts → lint/linter.ts} +0 -0
  305. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  306. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  307. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  308. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  309. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  310. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  311. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  312. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  313. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  314. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  315. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  316. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  317. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  318. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  319. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  320. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  321. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  322. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  323. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  324. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  325. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  326. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  327. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  328. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  329. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  330. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  331. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  332. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  333. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  334. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  335. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  336. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  337. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  338. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  339. /package/{writePath.ts → quality/writePath.ts} +0 -0
  340. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  341. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  342. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  343. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  344. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  345. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  346. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  347. /package/{fileSys.test.ts → util/fileSys.test.ts} +0 -0
  348. /package/{fileSys.ts → util/fileSys.ts} +0 -0
  349. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  350. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  351. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  352. /package/{semver.ts → util/semver.ts} +0 -0
  353. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  354. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  355. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  356. /package/{spinner.ts → util/spinner.ts} +0 -0
  357. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  358. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  359. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  360. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  361. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  362. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  363. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  364. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  365. /package/{types.ts → workspace/types.ts} +0 -0
@@ -0,0 +1,727 @@
1
+ import { afterEach, describe, expect, jest, mock, spyOn, test } from "bun:test";
2
+ import path from "node:path";
3
+ import type { BuilderMessage, ChangeBatch, DevBuildStatus } from "akanjs/server";
4
+ import { IncrementalBuilderHost } from "../incrementalBuilder";
5
+ import { createTempApp, isolateEnv, tempRoots, writeText } from "../test/testHelpers";
6
+ import { backendRecoveryPolicy, type DevHostEvent } from "./devHostPolicy";
7
+
8
+ interface FakeWatcher {
9
+ onBatch: (batch: ChangeBatch) => void;
10
+ stopped: number;
11
+ }
12
+
13
+ const watchers: FakeWatcher[] = [];
14
+
15
+ mock.module("../frontendBuild/watchRootResolver", () => ({
16
+ WatchRootResolver: class {
17
+ async resolve() {
18
+ return ["/repo"];
19
+ }
20
+ },
21
+ }));
22
+ mock.module("../frontendBuild/hmrWatcher", () => ({
23
+ HmrWatcher: class {
24
+ readonly #watcher: FakeWatcher;
25
+ constructor({ onBatch }: { onBatch: (batch: ChangeBatch) => void }) {
26
+ this.#watcher = { onBatch, stopped: 0 };
27
+ watchers.push(this.#watcher);
28
+ }
29
+ async start() {}
30
+ stop() {
31
+ this.#watcher.stopped += 1;
32
+ }
33
+ async close() {
34
+ this.stop();
35
+ return null;
36
+ }
37
+ },
38
+ }));
39
+
40
+ const { AkanAppHost } = await import("./akanApp.host");
41
+
42
+ type Boot = "ready" | "exit" | "hold" | "starting";
43
+
44
+ interface BuilderStartOptions {
45
+ onExit?: () => void;
46
+ onReady?: () => void;
47
+ onRestartReady?: () => void;
48
+ onAway?: () => void;
49
+ }
50
+
51
+ interface FakeBuilder {
52
+ status: string;
53
+ sent: BuilderMessage[];
54
+ recycled: string[];
55
+ stopped: number;
56
+ toHost: (message: BuilderMessage) => void;
57
+ ready: () => void;
58
+ away: () => void;
59
+ restartReady: () => void;
60
+ }
61
+
62
+ interface FakeBackend {
63
+ sent: BuilderMessage[];
64
+ signals: string[];
65
+ lingers: boolean;
66
+ say: (message: BuilderMessage) => void;
67
+ crash: () => void;
68
+ exit: () => void;
69
+ }
70
+
71
+ interface BackendSpawnOptions {
72
+ ipc: (message: BuilderMessage) => void;
73
+ onExit?: (proc: unknown, code: number | null, signal: string | null) => void;
74
+ }
75
+
76
+ const track = tempRoots();
77
+ const hosts: InstanceType<typeof AkanAppHost>[] = [];
78
+ const restores: (() => void)[] = [];
79
+
80
+ afterEach(async () => {
81
+ try {
82
+ await Promise.all(hosts.splice(0).map((host) => host.stop()));
83
+ } finally {
84
+ for (const restore of restores.splice(0)) restore();
85
+ watchers.length = 0;
86
+ }
87
+ });
88
+
89
+ const until = async (done: () => boolean, timeoutMs = 5_000) => {
90
+ const deadline = performance.now() + timeoutMs;
91
+ while (!done() && performance.now() < deadline) await Bun.sleep(10);
92
+ return done();
93
+ };
94
+
95
+ const fakeBuilder = (toHost: (message: BuilderMessage) => void, boot: Boot) => {
96
+ let options: BuilderStartOptions = {};
97
+ const builder: FakeBuilder = {
98
+ status: "stopped",
99
+ sent: [],
100
+ recycled: [],
101
+ stopped: 0,
102
+ toHost,
103
+ ready: () => {
104
+ builder.status = "ready";
105
+ options.onReady?.();
106
+ },
107
+ away: () => {
108
+ builder.status = "restarting";
109
+ options.onAway?.();
110
+ },
111
+ restartReady: () => {
112
+ builder.status = "ready";
113
+ options.onRestartReady?.();
114
+ },
115
+ };
116
+ const host = {
117
+ patcherOff: false,
118
+ pid: process.pid,
119
+ get status() {
120
+ return builder.status;
121
+ },
122
+ start: (startOptions: BuilderStartOptions) => {
123
+ options = startOptions;
124
+ if (boot === "exit") {
125
+ builder.status = "stopped";
126
+ options.onExit?.();
127
+ } else if (boot === "ready") builder.ready();
128
+ else {
129
+ builder.status = "starting";
130
+ if (boot === "starting") options.onReady?.();
131
+ }
132
+ },
133
+ send: (message: BuilderMessage) => {
134
+ if (builder.status !== "ready") return false;
135
+ builder.sent.push(message);
136
+ return true;
137
+ },
138
+ stop: () => {
139
+ builder.stopped += 1;
140
+ builder.status = "stopped";
141
+ },
142
+ recycle: (reason: string) => {
143
+ if (builder.status !== "ready") return false;
144
+ builder.recycled.push(reason);
145
+ builder.status = "recycling";
146
+ return true;
147
+ },
148
+ };
149
+ return { builder, host: host as unknown as IncrementalBuilderHost };
150
+ };
151
+
152
+ const fakeBackends = () => {
153
+ const backends: FakeBackend[] = [];
154
+ const spawn = Bun.spawn;
155
+ const spawned = spyOn(Bun, "spawn").mockImplementation(((cmd: string[], options: BackendSpawnOptions) => {
156
+ if (cmd[0] !== "bun" || cmd[1] !== "apps/demo/main.ts") return spawn(cmd, options as Parameters<typeof spawn>[1]);
157
+ const exit = Promise.withResolvers<number>();
158
+ let exited = false;
159
+ const finish = (code: number, signal: string | null) => {
160
+ if (exited) return;
161
+ exited = true;
162
+ exit.resolve(code);
163
+ queueMicrotask(() => options.onExit?.(proc, code, signal));
164
+ };
165
+ const backend: FakeBackend = {
166
+ sent: [],
167
+ signals: [],
168
+ lingers: false,
169
+ say: (message) => options.ipc(message),
170
+ crash: () => finish(1, null),
171
+ exit: () => finish(0, "SIGTERM"),
172
+ };
173
+ const proc = {
174
+ pid: 5_000_000 + backends.length,
175
+ killed: false,
176
+ exited: exit.promise,
177
+ send: (message: BuilderMessage) => void backend.sent.push(message),
178
+ kill: (signal = "SIGTERM") => {
179
+ backend.signals.push(signal);
180
+ proc.killed = true;
181
+ if (!backend.lingers || signal === "SIGKILL") finish(0, signal);
182
+ },
183
+ };
184
+ backends.push(backend);
185
+ return proc;
186
+ }) as unknown as typeof Bun.spawn);
187
+ restores.push(() => spawned.mockRestore());
188
+ return backends;
189
+ };
190
+
191
+ const devHost = async (boots: Boot[] = []) => {
192
+ const { root, app } = track(await createTempApp("demo"));
193
+ const mainPath = path.join(root, "apps/demo/main.ts");
194
+ await writeText(mainPath, "export const version = 1;\n");
195
+ const backends = fakeBackends();
196
+ const builders: FakeBuilder[] = [];
197
+ const events: DevHostEvent[] = [];
198
+ const eventTimes: number[] = [];
199
+ const logs: string[] = [];
200
+ const create = IncrementalBuilderHost.create;
201
+ IncrementalBuilderHost.create = (async (_app: unknown, _env: unknown, toHost: (message: BuilderMessage) => void) => {
202
+ const { builder, host } = fakeBuilder(toHost, boots.shift() ?? "ready");
203
+ builders.push(builder);
204
+ return host;
205
+ }) as unknown as typeof IncrementalBuilderHost.create;
206
+ restores.push(() => {
207
+ IncrementalBuilderHost.create = create;
208
+ });
209
+ const host = new AkanAppHost(app, {
210
+ env: { ...process.env } as Record<string, string>,
211
+ onDevEvent: (event) => {
212
+ events.push(event);
213
+ eventTimes.push(performance.now());
214
+ },
215
+ });
216
+ hosts.push(host);
217
+ const awaited: { text: string; resolve: () => void }[] = [];
218
+ for (const level of ["verbose", "info", "warn", "error"] as const)
219
+ spyOn(host.logger, level).mockImplementation((message: string) => {
220
+ logs.push(message);
221
+ for (const waiter of awaited.filter(({ text }) => message.includes(text))) {
222
+ awaited.splice(awaited.indexOf(waiter), 1);
223
+ waiter.resolve();
224
+ }
225
+ });
226
+ return {
227
+ app,
228
+ host,
229
+ root,
230
+ mainPath,
231
+ backends,
232
+ builders,
233
+ events,
234
+ logs,
235
+ builder: () => builders.at(-1) as FakeBuilder,
236
+ backend: () => backends.at(-1) as FakeBackend,
237
+ logged: (text: string) => logs.some((line) => line.includes(text)),
238
+ nextLog: (text: string) => new Promise<void>((resolve) => void awaited.push({ text, resolve })),
239
+ suspended: () => events.some((event) => "state" in event && event.state === "suspended"),
240
+ suspendedAt: () => eventTimes[events.findIndex((event) => "state" in event && event.state === "suspended")],
241
+ lastState: () => events.flatMap((event) => ("state" in event ? [event.state] : [])).at(-1),
242
+ };
243
+ };
244
+
245
+ type DevHost = Awaited<ReturnType<typeof devHost>>;
246
+
247
+ const readyBackend = (dev: DevHost) => dev.backend().say({ type: "backend-ready", pid: 1 });
248
+
249
+ const startedHost = async (boots: Boot[] = []) => {
250
+ const dev = await devHost(boots);
251
+ await dev.host.start();
252
+ readyBackend(dev);
253
+ return dev;
254
+ };
255
+
256
+ const pages = (generation: number, reason?: "builder-recycle", bundle = generation) =>
257
+ ({
258
+ type: "pages-updated",
259
+ data: { bundlePath: `/app/pages-${bundle}.js`, buildId: bundle, generation, ...(reason ? { reason } : {}) },
260
+ }) as BuilderMessage;
261
+
262
+ const status = (generation: number, ok: boolean, files = ["/app/lib/a.ts"]): DevBuildStatus => ({
263
+ generation,
264
+ phase: "pages",
265
+ ok,
266
+ files,
267
+ ...(ok ? {} : { message: "Type error" }),
268
+ });
269
+
270
+ const invalidate = (generation: number, actions: string[], files: string[] = ["/app/lib/a.ts"]) =>
271
+ ({
272
+ type: "invalidate",
273
+ kinds: [],
274
+ files,
275
+ generation,
276
+ devPlan: { generation, files, generatedFiles: [], roles: ["server"], actions, reasonByFile: {} },
277
+ }) as unknown as BuilderMessage;
278
+
279
+ const metrics = (generation: number) =>
280
+ ({ type: "builder-metrics", data: { rssBytes: 64 * 1024 * 1024, generation, workCount: 3 } }) as BuilderMessage;
281
+
282
+ const sentOf = (messages: BuilderMessage[], type: BuilderMessage["type"]) =>
283
+ messages.filter((message) => message.type === type);
284
+
285
+ const statusesOf = (messages: BuilderMessage[]) =>
286
+ messages.flatMap((message) => (message.type === "build-status" ? [message.data] : []));
287
+
288
+ describe("AkanAppHost relays the builder to the backend", () => {
289
+ isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "local" });
290
+
291
+ test("hands the backend every builder event it does not act on itself", async () => {
292
+ const dev = await startedHost();
293
+ const events: BuilderMessage[] = [
294
+ { type: "builder-ready" },
295
+ { type: "csr-updated", data: { generation: 1, mode: "registry", reload: false } },
296
+ { type: "ssr-updated", data: { generation: 1, reload: false } },
297
+ ];
298
+ for (const event of events) dev.builder().toHost(event);
299
+
300
+ expect(await until(() => dev.backend().sent.length >= events.length)).toBe(true);
301
+ expect(dev.backend().sent).toEqual(events);
302
+ });
303
+
304
+ test("replays the last good pages and css to a backend that is ready only after they were built", async () => {
305
+ const dev = await devHost();
306
+ await dev.host.start();
307
+ const css = { type: "css-updated", data: { generation: 3, cssAssets: {} } } as unknown as BuilderMessage;
308
+ dev.builder().toHost(pages(2));
309
+ dev.builder().toHost(css);
310
+ expect(await until(() => dev.host.env.AKAN_BUILDER_INITIAL_GENERATION === "3")).toBe(true);
311
+ expect(dev.backend().sent).toEqual([]);
312
+
313
+ readyBackend(dev);
314
+
315
+ expect(dev.backend().sent).toEqual([css, pages(2)]);
316
+ });
317
+
318
+ test("passes on a recycled builder's pages only when its bundle moved", async () => {
319
+ const dev = await startedHost();
320
+ dev.builder().toHost(pages(2));
321
+ dev.builder().toHost(pages(9, "builder-recycle", 2));
322
+ expect(await until(() => dev.host.env.AKAN_BUILDER_INITIAL_GENERATION === "9")).toBe(true);
323
+ expect(sentOf(dev.backend().sent, "pages-updated")).toEqual([pages(2)]);
324
+
325
+ dev.builder().toHost(pages(10, "builder-recycle"));
326
+
327
+ expect(await until(() => sentOf(dev.backend().sent, "pages-updated").length === 2)).toBe(true);
328
+ });
329
+
330
+ test("relays a build status to the backend, and starts the next builder from its generation", async () => {
331
+ const dev = await startedHost();
332
+
333
+ dev.builder().toHost({ type: "build-status", data: status(5, true) });
334
+
335
+ expect(await until(() => statusesOf(dev.backend().sent).length > 0)).toBe(true);
336
+ expect(statusesOf(dev.backend().sent)).toEqual([status(5, true)]);
337
+ expect(dev.host.env.AKAN_BUILDER_INITIAL_GENERATION).toBe("5");
338
+ });
339
+
340
+ test("holds a builder restart whose generation failed to build, and tells the backend why", async () => {
341
+ const dev = await startedHost();
342
+ const onHold = () => statusesOf(dev.backend().sent).some((sent) => sent.phase === "scan" && !sent.ok);
343
+
344
+ dev.builder().toHost({ type: "build-status", data: status(7, false) });
345
+ dev.builder().toHost(invalidate(7, ["restart-builder"]));
346
+
347
+ expect(await until(() => onHold() || dev.builders.length > 1)).toBe(true);
348
+ expect(onHold()).toBe(true);
349
+ expect(dev.builders).toHaveLength(1);
350
+ });
351
+
352
+ test("retries a config restart that failed to apply once a green build touches its file", async () => {
353
+ const dev = await startedHost();
354
+ const configPath = path.join(dev.root, "apps/demo/akan.config.ts");
355
+ spyOn(dev.app, "getConfig").mockRejectedValue(new Error("akan.config.ts does not load"));
356
+ dev.builder().toHost({ type: "invalidate", kinds: ["config"], files: [configPath], generation: 2 });
357
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
358
+ readyBackend(dev);
359
+
360
+ dev.builder().toHost({ type: "build-status", data: status(3, true, [configPath]) });
361
+
362
+ expect(await until(() => dev.backends[1].signals.length > 0)).toBe(true);
363
+ });
364
+
365
+ test("restarts the backend for an invalidate whose plan restarts it", async () => {
366
+ const dev = await startedHost();
367
+
368
+ dev.builder().toHost(invalidate(4, ["restart-backend"]));
369
+
370
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
371
+ expect(dev.backends[0].signals).toEqual(["SIGTERM"]);
372
+ });
373
+
374
+ test("brings a backend that gave up back on the next green build", async () => {
375
+ const policy = { ...backendRecoveryPolicy };
376
+ Object.assign(backendRecoveryPolicy, { min: 5, max: 5, maxAttempts: 1 });
377
+ restores.push(() => Object.assign(backendRecoveryPolicy, policy));
378
+ const dev = await startedHost();
379
+ dev.backend().crash();
380
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
381
+ dev.backend().crash();
382
+ expect(await until(() => dev.lastState() === "failed")).toBe(true);
383
+
384
+ dev.builder().toHost({ type: "build-status", data: status(3, true) });
385
+
386
+ expect(await until(() => dev.backends.length === 3)).toBe(true);
387
+ });
388
+
389
+ test("reports the app booted once its backend is ready and the builder's boot builds settled", async () => {
390
+ const dev = await startedHost();
391
+
392
+ dev.builder().toHost({ type: "boot-armed" });
393
+
394
+ expect(await until(() => dev.events.some((event) => "booted" in event), 2_000)).toBe(true);
395
+ expect(dev.events.filter((event) => "booted" in event)).toEqual([{ app: "demo", booted: true }]);
396
+ });
397
+ });
398
+
399
+ describe("AkanAppHost through a builder's own restart", () => {
400
+ isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "local" });
401
+
402
+ test("hands the returning builder the requests held for it, and the backend its last good state again", async () => {
403
+ const dev = await startedHost();
404
+ dev.builder().toHost(pages(2));
405
+ expect(await until(() => sentOf(dev.backend().sent, "pages-updated").length === 1)).toBe(true);
406
+
407
+ dev.builder().away();
408
+ dev.backend().say({ type: "build-graph", id: 4 });
409
+ expect(dev.builder().sent).toEqual([]);
410
+ dev.builder().restartReady();
411
+
412
+ expect(sentOf(dev.builder().sent, "build-graph")).toHaveLength(1);
413
+ expect(sentOf(dev.backend().sent, "pages-updated")).toEqual([pages(2), pages(2)]);
414
+ });
415
+
416
+ test("restarts the backend for a backend file saved while the builder was away", async () => {
417
+ const dev = await startedHost();
418
+
419
+ dev.builder().away();
420
+ expect(await until(() => dev.logged("[builder-gap] stamped"))).toBe(true);
421
+ await writeText(dev.mainPath, "export const version = 22;\n");
422
+ dev.builder().restartReady();
423
+
424
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
425
+ });
426
+
427
+ test("drops the requests a restarted backend's predecessor left held for the builder", async () => {
428
+ const dev = await startedHost();
429
+ dev.builder().away();
430
+ dev.backend().say({ type: "build-graph", id: 1 });
431
+
432
+ dev.builder().toHost(invalidate(4, ["restart-backend"]));
433
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
434
+ dev.builder().restartReady();
435
+
436
+ expect(dev.builder().sent).toEqual([]);
437
+ });
438
+
439
+ test("recycles a builder past its rss ceiling, and counts a save made from that request as missed", async () => {
440
+ process.env.AKAN_BUILDER_MAX_RSS_MB = "1";
441
+ const dev = await startedHost();
442
+
443
+ dev.builder().toHost(metrics(1));
444
+ expect(await until(() => dev.builder().recycled.length > 0)).toBe(true);
445
+ expect(await until(() => dev.logged("[builder-gap] stamped"))).toBe(true);
446
+ await writeText(dev.mainPath, "export const version = 22;\n");
447
+ dev.builder().away();
448
+ dev.builder().restartReady();
449
+
450
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
451
+ expect(await until(() => dev.logged("a freshly recycled builder is already at"))).toBe(true);
452
+ });
453
+
454
+ test("skips an rss recycle while a builder restart is on hold", async () => {
455
+ process.env.AKAN_BUILDER_MAX_RSS_MB = "1";
456
+ const dev = await startedHost();
457
+ dev.builder().toHost({ type: "build-status", data: status(7, false) });
458
+ dev.builder().toHost(invalidate(7, ["restart-builder"]));
459
+
460
+ dev.builder().toHost(metrics(8));
461
+
462
+ const skipped = () => dev.logged("a dev restart is already pending");
463
+ expect(await until(() => skipped() || dev.builder().recycled.length > 0)).toBe(true);
464
+ expect(skipped()).toBe(true);
465
+ expect(dev.builder().recycled).toEqual([]);
466
+ });
467
+
468
+ test("forgets an armed rss recycle once the builder is replaced", async () => {
469
+ process.env.AKAN_BUILDER_MAX_RSS_MB = "1";
470
+ process.env.AKAN_DEV_IDLE_SUSPEND_MS = "50";
471
+ const dev = await devHost();
472
+ await dev.host.start();
473
+ dev.builder().toHost(metrics(1));
474
+ dev.builder().toHost(invalidate(2, ["restart-builder"]));
475
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
476
+
477
+ readyBackend(dev);
478
+
479
+ const restartPending = () => dev.logged("skipped (restart-pending)");
480
+ expect(await until(() => dev.suspended() || restartPending())).toBe(true);
481
+ expect(restartPending()).toBe(false);
482
+ });
483
+ });
484
+
485
+ describe("AkanAppHost through an idle suspend", () => {
486
+ isolateEnv({
487
+ AKAN_PUBLIC_REPO_NAME: "repo",
488
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
489
+ AKAN_PUBLIC_ENV: "local",
490
+ AKAN_DEV_IDLE_SUSPEND_MS: "50",
491
+ });
492
+
493
+ const suspendedHost = async (boots: Boot[] = []) => {
494
+ const dev = await startedHost(boots);
495
+ expect(await until(dev.suspended)).toBe(true);
496
+ return dev;
497
+ };
498
+
499
+ test("releases the builder, and comes back as ready on a new one", async () => {
500
+ const dev = await suspendedHost();
501
+ expect(dev.builders[0].stopped).toBe(1);
502
+
503
+ watchers[0].onBatch({ files: ["/app/ui/Button.css"], kinds: new Set(["css"]) });
504
+
505
+ expect(await until(() => dev.lastState() === "ready")).toBe(true);
506
+ expect(dev.builders).toHaveLength(2);
507
+ });
508
+
509
+ test("restarts the backend for a backend file saved while the builder was released", async () => {
510
+ const dev = await suspendedHost();
511
+ expect(await until(() => dev.logged("[builder-gap] stamped"))).toBe(true);
512
+ await writeText(dev.mainPath, "export const version = 22;\n");
513
+
514
+ dev.backend().say({ type: "build-graph", id: 3 });
515
+
516
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
517
+ });
518
+
519
+ test("answers a held request when the builder cannot start, and reports the builder recovered once it can", async () => {
520
+ const dev = await suspendedHost(["ready", "exit", "exit", "exit", "hold"]);
521
+ const backend = dev.backend();
522
+
523
+ backend.say({ type: "build-graph", id: 6 });
524
+ expect(await until(() => sentOf(backend.sent, "build-graph-res").length > 0)).toBe(true);
525
+ expect(sentOf(backend.sent, "build-graph-res")).toEqual([
526
+ { type: "build-graph-res", id: 6, ok: false, error: "builder failed to start", kind: "unavailable" },
527
+ ]);
528
+
529
+ expect(await until(() => dev.builders.length === 5)).toBe(true);
530
+ backend.say({ type: "build-graph", id: 8 });
531
+ expect(dev.builder().sent).toEqual([]);
532
+ dev.builder().ready();
533
+ expect(dev.builder().sent).toHaveLength(1);
534
+
535
+ expect(await until(() => statusesOf(backend.sent).some((sent) => sent.message === "Builder recovered"))).toBe(true);
536
+ }, 10_000);
537
+
538
+ test("stops watching for edits once the host stops", async () => {
539
+ const dev = await suspendedHost();
540
+ expect(watchers.map((watcher) => watcher.stopped)).toEqual([0]);
541
+
542
+ await dev.host.stop();
543
+
544
+ expect(watchers.map((watcher) => watcher.stopped)).toEqual([1]);
545
+ });
546
+
547
+ test.each([
548
+ ["the builder is not ready", "builder-not-ready", ["starting"], readyBackend],
549
+ ["the backend is not ready", "backend-not-ready", [], () => undefined],
550
+ [
551
+ "the build is failing",
552
+ "build-failed",
553
+ [],
554
+ (dev: DevHost) => {
555
+ dev.builder().toHost({ type: "build-status", data: status(2, false) });
556
+ readyBackend(dev);
557
+ },
558
+ ],
559
+ [
560
+ "a backend restart is pending",
561
+ "restart-pending",
562
+ [],
563
+ (dev: DevHost) => {
564
+ readyBackend(dev);
565
+ dev.builder().toHost(invalidate(3, ["restart-backend"]));
566
+ },
567
+ ],
568
+ [
569
+ "an rss recycle is armed",
570
+ "restart-pending",
571
+ [],
572
+ (dev: DevHost) => {
573
+ process.env.AKAN_BUILDER_MAX_RSS_MB = "1";
574
+ dev.builder().toHost(metrics(1));
575
+ readyBackend(dev);
576
+ },
577
+ ],
578
+ ] as [string, string, Boot[], (dev: DevHost) => void][])(
579
+ "keeps the builder while %s",
580
+ async (_when, decision, boots, arrange) => {
581
+ const dev = await devHost(boots);
582
+ await dev.host.start();
583
+ arrange(dev);
584
+
585
+ const skipped = () => dev.logged(`[idle-suspend] skipped (${decision})`);
586
+ expect(await until(() => skipped() || dev.suspended())).toBe(true);
587
+ expect(skipped()).toBe(true);
588
+ expect(dev.suspended()).toBe(false);
589
+ },
590
+ );
591
+
592
+ test("keeps the builder while a config change that failed to apply waits for its fix", async () => {
593
+ const dev = await devHost();
594
+ await dev.host.start();
595
+ const configPath = path.join(dev.root, "apps/demo/akan.config.ts");
596
+ spyOn(dev.app, "getConfig").mockRejectedValue(new Error("akan.config.ts does not load"));
597
+ dev.builder().toHost({ type: "invalidate", kinds: ["config"], files: [configPath], generation: 2 });
598
+ expect(await until(() => dev.logged("[builder-recovery] builder recovered"))).toBe(true);
599
+ readyBackend(dev);
600
+ const greenAt = dev.logs.length;
601
+
602
+ dev.builder().toHost({ type: "build-status", data: { generation: 3, phase: "scan", ok: true, files: [] } });
603
+
604
+ const skipped = () => dev.logs.slice(greenAt).some((line) => line.includes("skipped (restart-pending)"));
605
+ expect(await until(() => skipped() || dev.suspended())).toBe(true);
606
+ expect(dev.suspended()).toBe(false);
607
+ }, 10_000);
608
+
609
+ //? Activity only re-arms the idle timer, so the time the suspend lands is the one thing that shows it.
610
+ test.each([
611
+ ["a builder message", (dev: DevHost) => dev.builder().toHost({ type: "builder-ready" })],
612
+ ["a backend request", (dev: DevHost) => dev.backend().say({ type: "build-graph", id: 1 })],
613
+ ] as [string, (dev: DevHost) => void][])("%s puts the suspend off", async (_activity, poke) => {
614
+ process.env.AKAN_DEV_IDLE_SUSPEND_MS = "400";
615
+ const dev = await startedHost();
616
+ let pokes = 0;
617
+ let lastPokeAt = 0;
618
+ const poking = setInterval(() => {
619
+ if (pokes === 30) return clearInterval(poking);
620
+ pokes += 1;
621
+ lastPokeAt = performance.now();
622
+ poke(dev);
623
+ }, 20);
624
+ restores.push(() => clearInterval(poking));
625
+
626
+ expect(await until(() => pokes === 30 && dev.suspended())).toBe(true);
627
+ expect(dev.suspendedAt() - lastPokeAt).toBeGreaterThanOrEqual(400);
628
+ });
629
+ });
630
+
631
+ describe("AkanAppHost start and stop", () => {
632
+ isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "local" });
633
+
634
+ test("a stop answers the requests held for the builder, then stops the backend and the builder", async () => {
635
+ const dev = await startedHost();
636
+ dev.builder().away();
637
+ dev.backend().say({ type: "build-graph", id: 2 });
638
+
639
+ await dev.host.stop();
640
+
641
+ expect(dev.backend().sent).toEqual([
642
+ { type: "build-graph-res", id: 2, ok: false, error: "dev server is shutting down", kind: "unavailable" },
643
+ ]);
644
+ expect(dev.backend().signals).toEqual(["SIGTERM"]);
645
+ expect(dev.builder().stopped).toBe(1);
646
+ });
647
+
648
+ test("a stop while a builder restart waits on its new builder leaves no backend behind", async () => {
649
+ const dev = await startedHost(["ready", "hold"]);
650
+ dev.builder().toHost(invalidate(2, ["restart-builder"]));
651
+ expect(await until(() => dev.builders.length === 2)).toBe(true);
652
+
653
+ await dev.host.stop();
654
+
655
+ expect(await until(() => dev.logged("restart failed generation=2"))).toBe(true);
656
+ expect(dev.backends).toHaveLength(1);
657
+ });
658
+
659
+ test("a stop during a backend restart waits for it, and signals the backend once", async () => {
660
+ const dev = await startedHost();
661
+ dev.backend().lingers = true;
662
+ dev.builder().toHost(invalidate(4, ["restart-backend"]));
663
+ expect(await until(() => dev.backend().signals.length > 0)).toBe(true);
664
+
665
+ const stopping = dev.host.stop();
666
+ dev.backend().exit();
667
+ await stopping;
668
+
669
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"]]);
670
+ });
671
+
672
+ test("drops a builder message that lands after the stop", async () => {
673
+ const dev = await startedHost();
674
+ await dev.host.stop();
675
+ const seen = dev.events.length;
676
+
677
+ dev.builder().toHost(invalidate(5, ["restart-backend"]));
678
+ //? The dropped message and a handled one both settle in microtasks, so one macrotask turn shows either.
679
+ await new Promise((resolve) => setImmediate(resolve));
680
+
681
+ expect(dev.events.slice(seen)).toEqual([]);
682
+ });
683
+
684
+ test("a second start replaces the backend and the builder the first one started", async () => {
685
+ const dev = await startedHost();
686
+
687
+ await dev.host.start();
688
+
689
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"], []]);
690
+ expect(dev.builders.map((builder) => builder.stopped)).toEqual([1, 0]);
691
+ });
692
+ });
693
+
694
+ describe("AkanAppHost on a fake clock", () => {
695
+ isolateEnv({
696
+ AKAN_PUBLIC_REPO_NAME: "repo",
697
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
698
+ AKAN_PUBLIC_ENV: "local",
699
+ AKAN_BUILDER_MAX_RSS_MB: "1",
700
+ });
701
+
702
+ //? Every invalidate re-arms the recycle, so only a restart from the builder gap can land inside its quiet window.
703
+ test("skips an rss recycle that comes due while a backend restart waits out its debounce", async () => {
704
+ const dev = await startedHost();
705
+ const stamped = dev.nextLog("[builder-gap] stamped");
706
+ dev.builder().away();
707
+ await stamped;
708
+ await writeText(dev.mainPath, "export const version = 22;\n");
709
+ jest.useFakeTimers();
710
+ try {
711
+ const armed = dev.nextLog("[builder-recycle] armed");
712
+ dev.builder().toHost(metrics(1));
713
+ await armed;
714
+ jest.advanceTimersByTime(700);
715
+ const scheduled = dev.nextLog("-> restart-pending");
716
+ dev.builder().restartReady();
717
+ await scheduled;
718
+
719
+ jest.advanceTimersByTime(50);
720
+
721
+ expect(dev.logged("a dev restart is already pending")).toBe(true);
722
+ expect(dev.builder().recycled).toEqual([]);
723
+ } finally {
724
+ jest.useRealTimers();
725
+ }
726
+ });
727
+ });