@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,234 @@
1
+ import { rm } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ApplicationBuildReporter } from "@akanjs/devkit/app/applicationBuildReporter";
4
+ import type { App } from "@akanjs/devkit/commandDecorators";
5
+ import { CsrDevBundler } from "@akanjs/devkit/frontendBuild/csrDevBundler";
6
+ import { CsrDevPatcher } from "@akanjs/devkit/frontendBuild/csrDevPatcher";
7
+ import type { Logger } from "akanjs/common";
8
+ import type { BaseBuildArtifact, BuilderCsrReq, HmrTrace } from "akanjs/server";
9
+ import { CSR_DEV_PATCHING_MARKER } from "akanjs/server/hmr/csrDevManifest";
10
+ import type { BatchWork, BuildBatchRequest } from "./buildBatchProtocol";
11
+ import type { BuildBatchRunner } from "./buildBatchRunner";
12
+ import { isCompileError, sendBuildStatus } from "./builderBuildStatus";
13
+ import { BuilderChannel } from "./builderChannel";
14
+ import type { BuilderLanes } from "./builderLanes";
15
+
16
+ interface CsrRegistryLinks {
17
+ generation: () => number;
18
+ artifact: () => BaseBuildArtifact;
19
+ batchRequest: (work: BatchWork) => Promise<BuildBatchRequest>;
20
+ countDelegation: (registry: "csr" | "ssr", reason: string) => string;
21
+ }
22
+
23
+ export class CsrRegistry {
24
+ readonly #app: App;
25
+ readonly #logger: Logger;
26
+ readonly #lanes: BuilderLanes;
27
+ readonly #batchRunner: BuildBatchRunner;
28
+ readonly #links: CsrRegistryLinks;
29
+ #shellKey: string | null = null;
30
+ #csrActive = CsrRegistry.#csrArmedByEnv();
31
+ #csrBundler: CsrDevBundler;
32
+ /** Null when `AKAN_DEV_CSR_PATCHER=off`: every CSR save then goes to a build worker, as before the patcher. */
33
+ #patcher: CsrDevPatcher | null;
34
+ /** A worker's full CSR build (arming, re-arming) that a patch must not race for the csr-dev directory. */
35
+ #csrGate: Promise<void> = Promise.resolve();
36
+ #csrArming = false;
37
+ #csrArms = 0;
38
+ #csrWasActive = false;
39
+ #csrArmSucceeded = false;
40
+
41
+ constructor(
42
+ app: App,
43
+ { logger, lanes, batchRunner }: { logger: Logger; lanes: BuilderLanes; batchRunner: BuildBatchRunner },
44
+ links: CsrRegistryLinks,
45
+ ) {
46
+ this.#app = app;
47
+ this.#logger = logger;
48
+ this.#lanes = lanes;
49
+ this.#batchRunner = batchRunner;
50
+ this.#links = links;
51
+ this.#csrBundler = new CsrDevBundler(app);
52
+ this.#patcher =
53
+ process.env.AKAN_DEV_CSR_PATCHER === "off" ? null : new CsrDevPatcher(this.#csrBundler, { resident: true });
54
+ }
55
+
56
+ get csrActive(): boolean {
57
+ return this.#csrActive;
58
+ }
59
+
60
+ get csrArming(): boolean {
61
+ return this.#csrArming;
62
+ }
63
+
64
+ get patcher(): CsrDevPatcher | null {
65
+ return this.#patcher;
66
+ }
67
+
68
+ // True when the save has to go to a build worker: the patcher handed it back, or threw (the worker reports why).
69
+ async patchCsr(generation: number, files: string[], trace: HmrTrace): Promise<boolean> {
70
+ const patcher = this.#patcher;
71
+ if (!patcher) return true;
72
+ await this.#csrGate;
73
+ // The arming build this save waited for failed: CSR is off again, and the next request arms it anew.
74
+ if (!this.#csrActive) return false;
75
+ const started = Date.now();
76
+ const marker = path.join(this.#csrBundler.outDir, CSR_DEV_PATCHING_MARKER);
77
+ await Bun.write(marker, String(process.pid));
78
+ try {
79
+ const result = await patcher.update(files, {
80
+ announce: (update) => {
81
+ const now = Date.now();
82
+ BuilderChannel.emit({
83
+ type: "csr-updated",
84
+ data: {
85
+ generation: update.generation,
86
+ mode: "registry",
87
+ reload: update.reload,
88
+ reason: update.reason,
89
+ patchUrl: update.patchUrl,
90
+ changedIds: update.changedIds,
91
+ trace: { ...trace, patchAt: now, sentAt: now },
92
+ },
93
+ });
94
+ },
95
+ });
96
+ if (result.kind === "delegate") {
97
+ this.#logger.verbose(
98
+ `csr-patch handed to a build worker (${this.#links.countDelegation("csr", result.reason)}): ${result.reason}`,
99
+ );
100
+ return true;
101
+ }
102
+ sendBuildStatus("csr", { generation, ok: true, files });
103
+ this.#logger.verbose(
104
+ result.kind === "unchanged"
105
+ ? `csr-patch unchanged (${Date.now() - started}ms)`
106
+ : `csr-patch generation=${result.update.generation} ${result.update.reload ? `reload (${result.update.reason})` : `patch modules=${result.update.changedIds.length}`} (${Date.now() - started}ms)`,
107
+ );
108
+ return false;
109
+ } catch (err) {
110
+ const message = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
111
+ if (isCompileError(err)) {
112
+ sendBuildStatus("csr", { generation, ok: false, files, message });
113
+ return false;
114
+ }
115
+ this.#logger.verbose(`csr-patch threw; a build worker takes this save: ${message}`);
116
+ patcher.forget();
117
+ return true;
118
+ } finally {
119
+ await rm(marker, { force: true });
120
+ }
121
+ }
122
+
123
+ // On demand: dev serves CSR only via the opt-in `/__csr` and `?csr=true` routes; once built, it rebuilds every save.
124
+ async handleBuildCsr(msg: BuilderCsrReq): Promise<void> {
125
+ if (msg.shell) {
126
+ await this.#buildShell(msg);
127
+ return;
128
+ }
129
+ //? Armed now, not when the build lands: a save handled meanwhile then patches CSR behind #csrGate instead of skipping.
130
+ this.#beginCsrArm();
131
+ this.#csrActive = true;
132
+ const armed = this.#lanes.workQueue.enqueue("build-csr", async (): Promise<void> => {
133
+ const started = Date.now();
134
+ let error: string | undefined;
135
+ try {
136
+ // Not relayed: an on-demand CSR build is request/response, and its error travels in the response.
137
+ const result = await this.#batchRunner.run(
138
+ await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }),
139
+ );
140
+ error = result.errors.csr;
141
+ } catch (err) {
142
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
143
+ }
144
+ if (error) {
145
+ this.#logger.error(`csr-build failed: ${error}`);
146
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: false, error });
147
+ return;
148
+ }
149
+ this.#csrArmSucceeded = true;
150
+ this.#patcher?.forget();
151
+ this.#logger.info(`csr-build ok on demand (${Date.now() - started}ms); rebuilding CSR on every save now`);
152
+ await BuilderChannel.send({ type: "build-csr-res", id: msg.id, ok: true });
153
+ });
154
+ this.#csrGate = this.#armingCsr(armed);
155
+ await armed;
156
+ }
157
+
158
+ // Asked on every view read and rebuilt only when a save moved the generation or the css it inlines, instead of armed
159
+ // per save: a restarted builder has no last build to trust, and so rebuilds once on the next read.
160
+ async #buildShell(msg: BuilderCsrReq): Promise<void> {
161
+ await this.#lanes.workQueue.enqueue("build-shell", async (): Promise<void> => {
162
+ const generation = this.#links.generation();
163
+ //? A save moves the generation before its css compile lands, so a shell built in between holds the old css.
164
+ const shellKey = `${generation}:${JSON.stringify(this.#links.artifact().cssAssets)}`;
165
+ let error: string | undefined;
166
+ if (this.#shellKey !== shellKey)
167
+ try {
168
+ const result = await this.#batchRunner.run(
169
+ await this.#links.batchRequest({ generation, needs: ["shell"], changedFiles: [] }),
170
+ );
171
+ error = result.errors.shell;
172
+ if (!error) this.#shellKey = shellKey;
173
+ } catch (err) {
174
+ error = ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot);
175
+ }
176
+ await BuilderChannel.send(
177
+ error
178
+ ? { type: "build-csr-res", id: msg.id, ok: false, error }
179
+ : { type: "build-csr-res", id: msg.id, ok: true },
180
+ );
181
+ });
182
+ }
183
+
184
+ //? Settled by the last of the arming builds in flight, not by each: two requests that both fail would otherwise leave
185
+ //? CSR on (the second saw the first's optimistic flag as where it started), and the first to finish would let saves
186
+ //? patch CSR first while the second still builds.
187
+ #beginCsrArm(): void {
188
+ if (this.#csrArms === 0) {
189
+ this.#csrWasActive = this.#csrActive;
190
+ this.#csrArmSucceeded = false;
191
+ }
192
+ this.#csrArms += 1;
193
+ this.#csrArming = true;
194
+ }
195
+
196
+ #armingCsr(armed: Promise<void>): Promise<void> {
197
+ const settle = () => {
198
+ this.#csrArms -= 1;
199
+ if (this.#csrArms > 0) return;
200
+ this.#csrArming = false;
201
+ this.#csrActive = this.#csrWasActive || this.#csrArmSucceeded;
202
+ };
203
+ return armed.then(settle, settle);
204
+ }
205
+
206
+ static #csrArmedByEnv() {
207
+ return process.env.AKAN_DEV_CSR_REBUILD === "1";
208
+ }
209
+
210
+ // The env flag carries an armed CSR session across builder restarts, so the replacement rebuilds it after ready.
211
+ async rearmCsrFromEnv(): Promise<void> {
212
+ if (!CsrRegistry.#csrArmedByEnv()) return;
213
+ this.#beginCsrArm();
214
+ this.#csrActive = true;
215
+ //? The env keeps CSR armed whatever this build does, as it did before the builder restarted.
216
+ this.#csrArmSucceeded = true;
217
+ const rearmed = this.#lanes.workQueue.enqueue("build-csr-rearm", async () => {
218
+ //? Relayed, unlike an on-demand build: a rebuild for a metadata save must reach the CSR tabs as their reload.
219
+ const result = await this.#batchRunner.run(
220
+ await this.#links.batchRequest({ generation: this.#links.generation(), needs: ["csr"], changedFiles: [] }),
221
+ (msg) => BuilderChannel.emit(msg),
222
+ );
223
+ this.#patcher?.forget();
224
+ if (result.errors.csr) this.#logger.error(`csr-rearm failed: ${result.errors.csr}`);
225
+ else this.#logger.verbose("csr-rearm ok; this session had CSR armed before the builder restarted");
226
+ });
227
+ this.#csrGate = this.#armingCsr(rearmed);
228
+ await rearmed.catch((err: unknown) =>
229
+ this.#logger.error(
230
+ `csr-rearm failed: ${ApplicationBuildReporter.formatError(err, this.#app.workspace.workspaceRoot)}`,
231
+ ),
232
+ );
233
+ }
234
+ }
@@ -68,6 +68,31 @@ describe("IncrementalBuilderHost", () => {
68
68
  host.stop();
69
69
  });
70
70
 
71
+ test("a stop while a restart is pending leaves the builder down once the delay passes", async () => {
72
+ const { spawns, host } = startRecordingHost();
73
+ spawns[0]?.options.onExit?.();
74
+ expect(host.status).toBe("restarting");
75
+
76
+ host.stop();
77
+ await wait(1_050);
78
+ expect(spawns).toHaveLength(1);
79
+ expect(host.status).toBe("stopped");
80
+ });
81
+
82
+ test("a builder that crashes again after coming back ready waits the first delay again", async () => {
83
+ const { spawns, host } = startRecordingHost();
84
+ spawns[0]?.options.onExit?.();
85
+ await wait(1_050);
86
+ expect(spawns).toHaveLength(2);
87
+
88
+ spawns[1]?.options.ipc?.({ type: "builder-ready" });
89
+ spawns[1]?.options.onExit?.();
90
+ await wait(1_050);
91
+ expect(spawns).toHaveLength(3);
92
+
93
+ host.stop();
94
+ });
95
+
71
96
  test("recycles a ready builder gracefully and replaces it immediately", async () => {
72
97
  const spawns = mockSpawns();
73
98
  const onRestartReady = mock();
@@ -123,18 +148,21 @@ describe("IncrementalBuilderHost", () => {
123
148
  id: 1,
124
149
  ok: false,
125
150
  error: "builder exited to release bundler memory before answering; reload to retry",
151
+ kind: "unavailable",
126
152
  },
127
153
  {
128
154
  type: "build-csr-res",
129
155
  id: 2,
130
156
  ok: false,
131
157
  error: "builder exited to release bundler memory before answering; reload to retry",
158
+ kind: "unavailable",
132
159
  },
133
160
  {
134
161
  type: "build-graph-res",
135
162
  id: 4,
136
163
  ok: false,
137
164
  error: "builder exited to release bundler memory before answering; reload to retry",
165
+ kind: "unavailable",
138
166
  },
139
167
  ]);
140
168
 
@@ -159,6 +187,7 @@ describe("IncrementalBuilderHost", () => {
159
187
  id: 1,
160
188
  ok: false,
161
189
  error: "builder exited unexpectedly before answering; reload once it is back",
190
+ kind: "unavailable",
162
191
  },
163
192
  ]);
164
193
 
@@ -168,7 +197,7 @@ describe("IncrementalBuilderHost", () => {
168
197
  expect(host.send({ type: "build-route", id: 2, routeId: "b", seeds: [], knownEntries: [] })).toBe(true);
169
198
  host.stop();
170
199
  expect(messages).toEqual([
171
- { type: "build-route-res", id: 2, ok: false, error: "builder was stopped before answering" },
200
+ { type: "build-route-res", id: 2, ok: false, error: "builder was stopped before answering", kind: "unavailable" },
172
201
  ]);
173
202
  });
174
203
 
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { Logger } from "akanjs/common";
3
+ import { Logger, RestartSchedule } from "akanjs/common";
4
4
  import type { BuilderMessage, BuilderRequest } from "akanjs/server";
5
5
  import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
6
6
  import { MemoryLimit } from "akanjs/server/memoryLimit";
@@ -49,8 +49,6 @@ interface IncrementalBuilderStartOptions {
49
49
  }
50
50
 
51
51
  export class IncrementalBuilderHost {
52
- static readonly #restartBaseDelayMs = 1_000;
53
- static readonly #restartMaxDelayMs = 30_000;
54
52
  static readonly #recycleDrainTimeoutMs = 30_000;
55
53
  // apps/akan's builder peaks near 950MB holding the SSR registry's patcher through a route build, and arming CSR adds
56
54
  // a second patcher: this recycles only a builder grown well past both.
@@ -65,8 +63,7 @@ export class IncrementalBuilderHost {
65
63
  readonly #onOutput: ((kind: "stdout" | "stderr", text: string) => void) | null;
66
64
  #proc: Bun.Subprocess<"ignore", "inherit" | "pipe", "inherit" | "pipe"> | null = null;
67
65
  #status: IncrementalBuilderStatus = "stopped";
68
- #restartAttempts = 0;
69
- #restartTimer: ReturnType<typeof setTimeout> | null = null;
66
+ readonly #restart = new RestartSchedule({ min: 1_000, max: 30_000 });
70
67
  #recycleTimer: ReturnType<typeof setTimeout> | null = null;
71
68
  #recycleRequested: boolean = false;
72
69
  #spawnAfterRecycle: boolean = false;
@@ -136,7 +133,7 @@ export class IncrementalBuilderHost {
136
133
  if (msg.type === "builder-ready" && !this.ready) {
137
134
  this.ready = true;
138
135
  this.#status = "ready";
139
- this.#restartAttempts = 0;
136
+ this.#restart.reset();
140
137
  if (isRestart) this.#startOptions.onRestartReady?.();
141
138
  else this.#startOptions.onReady?.();
142
139
  }
@@ -210,20 +207,13 @@ export class IncrementalBuilderHost {
210
207
  }
211
208
  }
212
209
  #scheduleRestart() {
213
- if (this.#manualStop || this.#restartTimer) return;
210
+ if (this.#manualStop || this.#restart.pending) return;
214
211
  this.#status = "restarting";
215
- const attempt = this.#restartAttempts;
216
- const delay = Math.min(
217
- IncrementalBuilderHost.#restartBaseDelayMs * 2 ** attempt,
218
- IncrementalBuilderHost.#restartMaxDelayMs,
219
- );
220
- this.#restartAttempts = attempt + 1;
221
- this.logger.warn(`builder exited after ready; restarting in ${delay}ms (attempt ${this.#restartAttempts})`);
222
- this.#restartTimer = setTimeout(() => {
223
- this.#restartTimer = null;
212
+ const delay = this.#restart.schedule(() => {
224
213
  if (this.#manualStop) return;
225
214
  this.#spawn(true);
226
- }, delay);
215
+ });
216
+ this.logger.warn(`builder exited after ready; restarting in ${delay}ms (attempt ${this.#restart.attempts})`);
227
217
  }
228
218
  /** Drain-and-exit rather than `kill()`, so no rebuild is truncated; false when the request was not sent. */
229
219
  recycle(reason: string): boolean {
@@ -287,16 +277,14 @@ export class IncrementalBuilderHost {
287
277
  const lost = [...this.#inFlight];
288
278
  this.#inFlight.clear();
289
279
  this.logger.warn(`failing ${lost.length} unanswered builder request(s): ${reason}`);
290
- for (const [id, type] of lost) this.#onMessage({ type: `${type}-res`, id, ok: false, error: reason });
280
+ for (const [id, type] of lost)
281
+ this.#onMessage({ type: `${type}-res`, id, ok: false, error: reason, kind: "unavailable" });
291
282
  }
292
283
  stop() {
293
284
  this.#manualStop = true;
294
285
  this.#clearRecycle();
295
286
  this.#failInFlight("builder was stopped before answering");
296
- if (this.#restartTimer) {
297
- clearTimeout(this.#restartTimer);
298
- this.#restartTimer = null;
299
- }
287
+ this.#restart.cancel();
300
288
  if (this.#proc) this.#proc.kill();
301
289
  this.#proc = null;
302
290
  this.ready = false;
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
3
  import type { BuilderMessage, BuilderReq } from "akanjs/server";
4
- import { createTempApp, tempRoots, writeText } from "../testHelpers";
4
+ import { createTempApp, tempRoots, writeText } from "../test/testHelpers";
5
5
 
6
6
  const track = tempRoots();
7
7
 
@@ -20,9 +20,11 @@ describe("incremental builder process", () => {
20
20
  const { root } = track(await createTempApp("demo"));
21
21
  const appDir = path.join(root, "apps/demo");
22
22
  // The batch runner looks under the workspace root first: a stand-in for the boot build, which needs a whole app.
23
+ // Each stand-in waits for the runner's release, as the real worker does: one exiting at once can lose all it sent.
23
24
  await writeText(
24
25
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
25
26
  `const { generation } = JSON.parse(process.argv[2]);
27
+ process.once("disconnect", () => {});
26
28
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
27
29
  `,
28
30
  );
@@ -90,6 +92,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
90
92
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
91
93
  `const { generation, needs } = JSON.parse(process.argv[2]);
92
94
  const errors = needs.includes("base") ? {} : { shell: "handed " + needs.join(",") };
95
+ process.once("disconnect", () => {});
93
96
  process.send({ type: "build-batch-result", data: { generation, errors, artifact: {}, optimizedFonts: { css: "", files: [] } } });
94
97
  `,
95
98
  );
@@ -135,6 +138,7 @@ process.send({ type: "build-batch-result", data: { generation, errors, artifact:
135
138
  await writeText(
136
139
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
137
140
  `const { generation } = JSON.parse(process.argv[2]);
141
+ process.once("disconnect", () => {});
138
142
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
139
143
  `,
140
144
  );
@@ -237,6 +241,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
237
241
  await writeText(
238
242
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
239
243
  `const { generation } = JSON.parse(process.argv[2]);
244
+ process.once("disconnect", () => {});
240
245
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
241
246
  `,
242
247
  );
@@ -299,6 +304,7 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
299
304
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
300
305
  `const { generation, needs } = JSON.parse(process.argv[2]);
301
306
  require("node:fs").appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + "\\n");
307
+ process.once("disconnect", () => {});
302
308
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
303
309
  `,
304
310
  );
@@ -357,6 +363,7 @@ process.on("disconnect", orphaned);
357
363
  const deadline = Date.now() + 15_000;
358
364
  if (needs.includes("ssr")) while (!fs.existsSync(${JSON.stringify(gate)}) && Date.now() < deadline) await Bun.sleep(20);
359
365
  const css = needs.includes("ssr") ? { cssAssets: ${JSON.stringify(landed)} } : {};
366
+ process.once("disconnect", () => {});
360
367
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] }, ...css } });
361
368
  process.off("disconnect", orphaned);
362
369
  `,
@@ -417,6 +424,7 @@ if (needs.includes("ssr")) {
417
424
  fs.appendFileSync(${JSON.stringify(runs)}, Date.now() + "\\n");
418
425
  if (fs.readFileSync(${JSON.stringify(runs)}, "utf8").trim().split("\\n").length <= 2) process.exit(1);
419
426
  }
427
+ process.once("disconnect", () => {});
420
428
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
421
429
  `,
422
430
  );
@@ -483,6 +491,7 @@ if (needs.includes("ssr")) {
483
491
  fs.appendFileSync(${JSON.stringify(runs)}, Date.now() + "\\n");
484
492
  if (fs.readFileSync(${JSON.stringify(runs)}, "utf8").trim().split("\\n").length === 2) process.exit(1);
485
493
  }
494
+ process.once("disconnect", () => {});
486
495
  process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
487
496
  `,
488
497
  );
@@ -539,7 +548,10 @@ process.send({ type: "build-batch-result", data: { generation, errors: {}, artif
539
548
  path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
540
549
  `const { generation, needs } = JSON.parse(process.argv[2]);
541
550
  if (needs.includes("ssr")) await import(${JSON.stringify(path.join(import.meta.dir, "buildBatch.proc.ts"))});
542
- else process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
551
+ else {
552
+ process.once("disconnect", () => {});
553
+ process.send({ type: "build-batch-result", data: { generation, errors: {}, artifact: {}, optimizedFonts: { css: "", files: [] } } });
554
+ }
543
555
  `,
544
556
  );
545
557
  await writeText(path.join(appDir, "env/env.client.ts"), "export const env = {} as const;\n");
@@ -588,4 +600,83 @@ else process.send({ type: "build-batch-result", data: { generation, errors: {},
588
600
  await proc.exited;
589
601
  }
590
602
  }, 60_000);
603
+
604
+ test("a failed boot build waits for the save that fixes it, and the builder it recovers continues the generation and watches", async () => {
605
+ const { root } = track(await createTempApp("demo"));
606
+ const appDir = path.join(root, "apps/demo");
607
+ const ledger = path.join(root, "batches.log");
608
+ const fixed = path.join(root, "boot-fixed");
609
+ // A stand-in batch: the boot build fails until the fix lands, and every batch logs its needs and generation.
610
+ await writeText(
611
+ path.join(root, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts"),
612
+ `import fs from "node:fs";
613
+ const { generation, needs } = JSON.parse(process.argv[2]);
614
+ fs.appendFileSync(${JSON.stringify(ledger)}, needs.join(",") + " " + generation + "\\n");
615
+ const errors = needs.includes("base") && !fs.existsSync(${JSON.stringify(fixed)}) ? { base: "the boot is broken" } : {};
616
+ process.once("disconnect", () => {});
617
+ process.send({ type: "build-batch-result", data: { generation, errors, artifact: {}, optimizedFonts: { css: "", files: [] } } });
618
+ `,
619
+ );
620
+ const page = path.join(appDir, "page/_index.tsx");
621
+ await writeText(page, "export default () => null;\n");
622
+ const messages: BuilderMessage[] = [];
623
+ const proc = Bun.spawn(["bun", path.join(import.meta.dir, "incrementalBuilder.proc.ts")], {
624
+ cwd: appDir,
625
+ env: {
626
+ ...process.env,
627
+ AKAN_WORKSPACE_ROOT: root,
628
+ AKAN_PUBLIC_APP_NAME: "demo",
629
+ AKAN_PUBLIC_REPO_NAME: "repo",
630
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
631
+ AKAN_PUBLIC_ENV: "local",
632
+ AKAN_BUILDER_INITIAL_GENERATION: "5",
633
+ AKAN_DEV_CSR_PATCHER: "off",
634
+ AKAN_LOG_STDOUT_LEVEL: "info",
635
+ },
636
+ stdio: ["ignore", "pipe", "ignore"],
637
+ serialization: "advanced",
638
+ ipc: (message: BuilderMessage) => {
639
+ messages.push(message);
640
+ },
641
+ });
642
+ let stdout = "";
643
+ const decoder = new TextDecoder();
644
+ const reading = (async () => {
645
+ for await (const chunk of proc.stdout) stdout += decoder.decode(chunk, { stream: true });
646
+ })();
647
+ const sent = (type: BuilderMessage["type"]) => messages.filter((message) => message.type === type);
648
+ try {
649
+ await until(proc, "boot-armed", () => sent("boot-armed").length === 1);
650
+ proc.send({ type: "build-graph", id: 1 } satisfies BuilderMessage);
651
+ await until(proc, "build-graph-res", () => sent("build-graph-res").length === 1);
652
+ //? Degraded mode sends boot-armed before its watcher starts, and a save made before then is never seen.
653
+ await until(proc, "the degraded watcher's log line", () => stdout.includes("[degraded] watching"));
654
+ await writeText(fixed, "");
655
+ await writeText(page, "export default () => 1;\n");
656
+ await until(proc, "the recovered builder's boot-armed", () => sent("boot-armed").length === 2);
657
+ await writeText(page, "export default () => 2;\n");
658
+ await until(proc, "the recovered builder's invalidate", () =>
659
+ messages.some((message) => message.type === "invalidate" && message.generation === 9),
660
+ );
661
+ } finally {
662
+ proc.kill();
663
+ await proc.exited;
664
+ await reading;
665
+ }
666
+ expect(sent("build-status")[0]).toMatchObject({
667
+ data: { generation: 6, phase: "pages", ok: false, message: "Boot build failed: the boot is broken" },
668
+ });
669
+ expect(sent("build-graph-res")[0]).toMatchObject({
670
+ id: 1,
671
+ ok: false,
672
+ error: expect.stringContaining("recovering from a failed boot build"),
673
+ });
674
+ expect(sent("builder-ready")).toHaveLength(2);
675
+ expect((await Bun.file(ledger).text()).trim().split("\n").slice(0, 4)).toEqual([
676
+ "base 0",
677
+ "base 0",
678
+ "pages,css 8",
679
+ "ssr 8",
680
+ ]);
681
+ }, 60_000);
591
682
  });