@akanjs/devkit 3.0.0-alpha.9 → 3.0.0-alpha.91

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 (183) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/DEV_RUNTIME_KNOBS.md +27 -0
  3. package/README.ko.md +1 -1
  4. package/README.md +1 -1
  5. package/agentsIndex.test.ts +10 -0
  6. package/agentsIndex.ts +21 -1
  7. package/aiEditor.ts +1 -1
  8. package/akanApp/BackendImportGraph.test.ts +120 -0
  9. package/akanApp/BackendImportGraph.ts +167 -0
  10. package/akanApp/akanApp.host.test.ts +16 -678
  11. package/akanApp/akanApp.host.ts +113 -578
  12. package/akanApp/devHostPolicy.test.ts +542 -0
  13. package/akanApp/devHostPolicy.ts +442 -0
  14. package/akanApp/index.ts +2 -0
  15. package/akanConfig/akanConfig.test.ts +182 -14
  16. package/akanConfig/akanConfig.ts +143 -47
  17. package/akanConfig/types.ts +9 -0
  18. package/akanContext.ts +30 -14
  19. package/akanMcpContract.ts +25 -4
  20. package/appSelectionMemory.ts +28 -0
  21. package/applicationBuildRunner.test.ts +1 -1
  22. package/applicationBuildRunner.ts +45 -21
  23. package/artifact/implicitRootLayout.test.ts +67 -0
  24. package/artifact/implicitRootLayout.ts +27 -7
  25. package/artifact/routeSeedIndex.test.ts +1 -0
  26. package/biome.base.json +86 -47
  27. package/biomeBase.ts +6 -5
  28. package/capacitorApp.ts +10 -0
  29. package/cloud/globalConfig.ts +9 -2
  30. package/codegenLock.test.ts +137 -0
  31. package/codegenLock.ts +136 -0
  32. package/commandDecorators/argMeta.ts +9 -1
  33. package/commandDecorators/command.ts +94 -7
  34. package/commandDecorators/commandBuilder.ts +20 -5
  35. package/commandDecorators/commandDecorators.test.ts +115 -3
  36. package/commandDecorators/helpFormatter.ts +4 -0
  37. package/dependencyScanner.test.ts +99 -0
  38. package/dependencyScanner.ts +27 -24
  39. package/devkitUtils.test.ts +0 -104
  40. package/executors.test.ts +129 -4
  41. package/executors.ts +105 -24
  42. package/fileEditor.ts +19 -19
  43. package/fileSys.ts +19 -1
  44. package/formSetterScanner.test.ts +80 -0
  45. package/formSetterScanner.ts +92 -0
  46. package/frontendBuild/autoImportSync.test.ts +58 -0
  47. package/frontendBuild/autoImportSync.ts +7 -2
  48. package/frontendBuild/buildRouteClient.test.ts +47 -24
  49. package/frontendBuild/clientBuildTypes.ts +4 -0
  50. package/frontendBuild/clientEntriesBundler.ts +4 -1
  51. package/frontendBuild/clientEntryDiscovery.ts +2 -2
  52. package/frontendBuild/csrArtifactBuilder.ts +116 -84
  53. package/frontendBuild/cssCompiler.ts +123 -12
  54. package/frontendBuild/cssImportResolver.ts +8 -7
  55. package/frontendBuild/devGeneratedIndexSync.ts +3 -2
  56. package/frontendBuild/fontOptimizer.ts +37 -18
  57. package/frontendBuild/fontPruner.test.ts +220 -0
  58. package/frontendBuild/fontPruner.ts +206 -0
  59. package/frontendBuild/frontendBuild.test.ts +178 -10
  60. package/frontendBuild/hmrWatcher.ts +1 -1
  61. package/frontendBuild/index.ts +1 -1
  62. package/frontendBuild/pagesBundleBuilder.ts +3 -3
  63. package/frontendBuild/pagesEntrySourceGenerator.ts +11 -88
  64. package/frontendBuild/routeClientBuilder.ts +12 -5
  65. package/frontendBuild/sourceMtimeIndex.ts +1 -1
  66. package/frontendBuild/ssrBaseArtifactBuilder.ts +21 -4
  67. package/frontendBuild/styleContract.ts +14 -20
  68. package/frontendBuild/themeValidator.ts +22 -17
  69. package/frontendBuild/vendorSpecifiers.ts +1 -0
  70. package/frontendBuild/watchRootResolver.test.ts +67 -0
  71. package/frontendBuild/watchRootResolver.ts +13 -1
  72. package/incrementalBuilder/devWatchBatch.test.ts +18 -20
  73. package/incrementalBuilder/devWatchBatch.ts +6 -2
  74. package/incrementalBuilder/incrementalBuilder.host.ts +51 -7
  75. package/incrementalBuilder/incrementalBuilder.proc.ts +17 -6
  76. package/index.ts +0 -7
  77. package/integration/devStabilityHarness.ts +2 -10
  78. package/libSource.test.ts +112 -0
  79. package/libSource.ts +126 -0
  80. package/lint/__fixtures__/README.md +40 -0
  81. package/lint/__fixtures__/no-arbitrary-color/bad.tsx +3 -0
  82. package/lint/__fixtures__/no-arbitrary-color/good.tsx +4 -0
  83. package/lint/__fixtures__/no-async-component-in-ui/bad.tsx +4 -0
  84. package/lint/__fixtures__/no-async-component-in-ui/good.tsx +4 -0
  85. package/lint/__fixtures__/no-bang-comment-in-client/bad.tsx +4 -0
  86. package/lint/__fixtures__/no-bang-comment-in-client/fixture.json +1 -0
  87. package/lint/__fixtures__/no-bang-comment-in-client/good.tsx +3 -0
  88. package/lint/__fixtures__/no-daisyui-legacy-class/bad.tsx +7 -0
  89. package/lint/__fixtures__/no-daisyui-legacy-class/good.tsx +5 -0
  90. package/lint/__fixtures__/no-deep-internal-import/bad.tsx +3 -0
  91. package/lint/__fixtures__/no-deep-internal-import/fixture.json +1 -0
  92. package/lint/__fixtures__/no-deep-internal-import/good.tsx +3 -0
  93. package/lint/__fixtures__/no-deprecated-log-level/bad.tsx +4 -0
  94. package/lint/__fixtures__/no-deprecated-log-level/good.tsx +4 -0
  95. package/lint/__fixtures__/no-import-client-functions/bad.tsx +2 -0
  96. package/lint/__fixtures__/no-import-client-functions/good.tsx +4 -0
  97. package/lint/__fixtures__/no-import-client-in-server/bad.tsx +6 -0
  98. package/lint/__fixtures__/no-import-client-in-server/good.tsx +5 -0
  99. package/lint/__fixtures__/no-import-external-library/bad.tsx +4 -0
  100. package/lint/__fixtures__/no-import-external-library/good.tsx +5 -0
  101. package/lint/__fixtures__/no-import-server-in-client/bad.tsx +6 -0
  102. package/lint/__fixtures__/no-import-server-in-client/good.tsx +4 -0
  103. package/lint/__fixtures__/no-init-fetch-in-client/store-file/bad.ts +1 -0
  104. package/lint/__fixtures__/no-init-fetch-in-client/store-file/fixture.json +1 -0
  105. package/lint/__fixtures__/no-init-fetch-in-client/store-file/good.ts +1 -0
  106. package/lint/__fixtures__/no-init-fetch-in-client/use-client/bad.tsx +4 -0
  107. package/lint/__fixtures__/no-init-fetch-in-client/use-client/good.tsx +5 -0
  108. package/lint/__fixtures__/no-inline-color/bad.tsx +3 -0
  109. package/lint/__fixtures__/no-inline-color/good.tsx +3 -0
  110. package/lint/__fixtures__/no-interpolated-arbitrary-class/bad.tsx +3 -0
  111. package/lint/__fixtures__/no-interpolated-arbitrary-class/good.tsx +3 -0
  112. package/lint/__fixtures__/no-js-private-class-method/bad.tsx +3 -0
  113. package/lint/__fixtures__/no-js-private-class-method/good.tsx +3 -0
  114. package/lint/__fixtures__/no-model-type-in-util-zone/bad.tsx +3 -0
  115. package/lint/__fixtures__/no-model-type-in-util-zone/good.tsx +6 -0
  116. package/lint/__fixtures__/no-raw-palette-class/bad.tsx +6 -0
  117. package/lint/__fixtures__/no-raw-palette-class/good.tsx +8 -0
  118. package/lint/__fixtures__/no-redeclare-predefined-endpoint/bad.ts +10 -0
  119. package/lint/__fixtures__/no-redeclare-predefined-endpoint/fixture.json +1 -0
  120. package/lint/__fixtures__/no-redeclare-predefined-endpoint/good.ts +6 -0
  121. package/lint/__fixtures__/no-return-in-store-action/bad.tsx +2 -0
  122. package/lint/__fixtures__/no-return-in-store-action/good.tsx +6 -0
  123. package/lint/__fixtures__/no-throw-raw-error/bad.tsx +4 -0
  124. package/lint/__fixtures__/no-throw-raw-error/good.tsx +4 -0
  125. package/lint/__fixtures__/no-unpublished-form-setter/bad.tsx +3 -0
  126. package/lint/__fixtures__/no-unpublished-form-setter/good.tsx +5 -0
  127. package/lint/__fixtures__/no-use-client-in-server/bad.tsx +3 -0
  128. package/lint/__fixtures__/no-use-client-in-server/good.tsx +2 -0
  129. package/lint/__fixtures__/non-scalar-props-restricted/bad.tsx +5 -0
  130. package/lint/__fixtures__/non-scalar-props-restricted/good.tsx +4 -0
  131. package/lint/gritRules.test.ts +178 -0
  132. package/lint/no-arbitrary-color.grit +1 -1
  133. package/lint/no-async-component-in-ui.grit +35 -0
  134. package/lint/no-bang-comment-in-client.grit +23 -10
  135. package/lint/no-daisyui-legacy-class.grit +26 -9
  136. package/lint/no-deprecated-log-level.grit +17 -0
  137. package/lint/no-init-fetch-in-client.grit +47 -0
  138. package/lint/no-inline-color.grit +10 -8
  139. package/lint/no-interpolated-arbitrary-class.grit +3 -3
  140. package/lint/no-model-type-in-util-zone.grit +58 -0
  141. package/lint/no-raw-palette-class.grit +3 -3
  142. package/lint/no-unpublished-form-setter.grit +41 -0
  143. package/lint/non-scalar-props-restricted.grit +16 -7
  144. package/linter.test.ts +80 -0
  145. package/linter.ts +99 -25
  146. package/package.json +5 -8
  147. package/prompter.ts +9 -4
  148. package/qualityScanner.test.ts +116 -0
  149. package/qualityScanner.ts +89 -21
  150. package/recipeScanner.ts +4 -1
  151. package/scanInfo.ts +32 -26
  152. package/semver.test.ts +26 -0
  153. package/semver.ts +31 -0
  154. package/slicePlanner.test.ts +182 -0
  155. package/slicePlanner.ts +235 -0
  156. package/ssrScanner.test.ts +301 -0
  157. package/subspace.test.ts +418 -0
  158. package/subspace.ts +723 -0
  159. package/subspaceConfig.ts +76 -0
  160. package/transforms/asyncDefaultExportDetector.ts +103 -0
  161. package/transforms/barrelImportsPlugin.ts +1 -1
  162. package/transforms/externalizeFrameworkPlugin.ts +0 -1
  163. package/transforms/transforms.test.ts +5 -5
  164. package/transforms/tsconfigPackageResolver.test.ts +230 -0
  165. package/tsconfig.json +6 -2
  166. package/typeChecker.ts +1 -1
  167. package/types.ts +1 -0
  168. package/uploadRelease.ts +2 -2
  169. package/workflow/executor.test.ts +146 -0
  170. package/workspaceLayout.test.ts +56 -4
  171. package/workspaceLayout.ts +48 -2
  172. package/builder.ts +0 -164
  173. package/extractDeps.ts +0 -86
  174. package/frontendBuild/styleGuard.test.ts +0 -165
  175. package/frontendBuild/styleGuard.ts +0 -322
  176. package/getCredentials.ts +0 -19
  177. package/getModelFileData.ts +0 -62
  178. package/src/capacitorApp.ts +0 -282
  179. package/streamAi.ts +0 -45
  180. package/ui/MultiScrollList.tsx +0 -242
  181. package/ui/ScrollList.tsx +0 -107
  182. package/ui/index.ts +0 -2
  183. package/useStdoutDimensions.ts +0 -20
@@ -0,0 +1,442 @@
1
+ import path from "node:path";
2
+ import type {
3
+ BuilderMessage,
4
+ BuildPhase,
5
+ ChangeBatch,
6
+ DevBuildStatus,
7
+ DevChangePlan,
8
+ DevChangeRole,
9
+ } from "akanjs/server";
10
+ import type { IncrementalBuilderStatus } from "../incrementalBuilder";
11
+
12
+ const BACKEND_RECOVERY_MAX_ATTEMPTS = 5;
13
+
14
+ /**
15
+ * How many requests may wait for a builder that is coming back. Generous — a page load asks for
16
+ * several routes — but finite, so a builder that never returns cannot grow this without bound. Past
17
+ * it, requests are failed as they were before, which is the behaviour this limit falls back to.
18
+ */
19
+ const HELD_BUILDER_REQUEST_LIMIT = 64;
20
+
21
+ export const BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS = 30_000;
22
+
23
+ const BUILDER_TIGHT_RSS_REPORT_LIMIT = 2;
24
+
25
+ // Far enough above the ceiling that no purge would rescue it; recycle without waiting.
26
+ const BUILDER_RSS_HARD_MULTIPLE = 1.5;
27
+
28
+ // A sandbox between user turns pays for a watcher that is watching nothing change. Suspending build
29
+ // capacity after this long returns the builder's residency until the next edit or route request.
30
+ const DEV_IDLE_SUSPEND_MS = 300_000;
31
+
32
+ // A wake that immediately suspends again would flap around whatever woke it.
33
+ const DEV_IDLE_MIN_UPTIME_MS = 30_000;
34
+
35
+ export const SOURCE_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
36
+
37
+ /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav|html)$/i;
38
+ const SERVER_SUFFIXES = [".service.ts", ".document.ts"];
39
+
40
+ const SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
41
+
42
+ const RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
43
+
44
+ export const shouldRestartBackendByDevPlan = (
45
+ message: Extract<BuilderMessage, { type: "invalidate" }>,
46
+ ): boolean | null => {
47
+ if (!message.devPlan) return null;
48
+ if (message.devPlan.actions.includes("report-error")) return false;
49
+ if (message.devPlan.actions.includes("restart-builder")) return false;
50
+ return message.devPlan.actions.includes("restart-backend");
51
+ };
52
+
53
+ export const shouldRestartBuilderByDevPlan = (message: Extract<BuilderMessage, { type: "invalidate" }>): boolean =>
54
+ message.devPlan?.actions.includes("restart-builder") ?? false;
55
+
56
+ /**
57
+ * A backend that keeps dying isn't going to heal by retrying the same code; after this many
58
+ * consecutive attempts the host idles and the next server-side edit triggers a fresh restart.
59
+ */
60
+ export const shouldAbandonBackendRecovery = (attempts: number, maxAttempts = BACKEND_RECOVERY_MAX_ATTEMPTS): boolean =>
61
+ attempts >= maxAttempts;
62
+
63
+ /** The gateway reports backend failures with `generation: -1`; the host assigns its own counter then. */
64
+ export const normalizeBackendReportedGeneration = (generation: number): number | undefined =>
65
+ generation >= 0 ? generation : undefined;
66
+
67
+ export const shouldRestartDevHostByDevPlan = (message: Extract<BuilderMessage, { type: "invalidate" }>): boolean =>
68
+ message.devPlan?.actions.includes("restart-dev-host") ?? message.kinds.includes("config");
69
+
70
+ export type BackendLifecycleState = "starting" | "ready" | "restart-pending" | "stopping" | "recovering" | "stopped";
71
+
72
+ /**
73
+ * What a dev host tells a supervising process about itself. Reported rather than scraped: the parent
74
+ * gets one pipe of interleaved child output, in which "this app is up" is indistinguishable from a line
75
+ * that merely mentions it.
76
+ */
77
+ export type DevHostState = "starting" | "ready" | "restarting" | "recovering" | "suspended" | "failed" | "stopped";
78
+
79
+ export interface DevHostEvent {
80
+ app: string;
81
+ state: DevHostState;
82
+ detail?: string;
83
+ }
84
+
85
+ const devHostStateByBackendState = {
86
+ starting: "starting",
87
+ ready: "ready",
88
+ "restart-pending": "restarting",
89
+ recovering: "recovering",
90
+ stopping: "stopped",
91
+ stopped: "stopped",
92
+ } as const satisfies { [key in BackendLifecycleState]: DevHostState };
93
+
94
+ /**
95
+ * The backend's own lifecycle collapsed to what a supervisor can act on. `stopped` is the one state
96
+ * that is ambiguous on its own — a planned shutdown and a crash loop that ran out of retries both land
97
+ * there — so the give-up flag is what separates "gone" from "broken".
98
+ */
99
+ export const devHostStateOf = (state: BackendLifecycleState, gaveUp: boolean): DevHostState =>
100
+ state === "stopped" && gaveUp ? "failed" : devHostStateByBackendState[state];
101
+
102
+ export interface BackendRestartReason {
103
+ generation?: number;
104
+ files: string[];
105
+ roles: Extract<DevChangeRole, "server" | "shared" | "barrel" | "config">[];
106
+ }
107
+
108
+ const RESTART_ROLE_ORDER: BackendRestartReason["roles"] = ["server", "shared", "barrel", "config"];
109
+
110
+ const generationValue = (generation: number | undefined): number => generation ?? -1;
111
+
112
+ export const isLegacyBackendFallbackFile = (file: string, workspaceRoot: string): boolean => {
113
+ const abs = path.resolve(file);
114
+ const ext = path.extname(abs).toLowerCase();
115
+ if (!SOURCE_EXTS.has(ext)) return false;
116
+ const rel = path.relative(path.resolve(workspaceRoot), abs);
117
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false;
118
+ const parts = rel.split(path.sep).filter(Boolean);
119
+ const [scope] = parts;
120
+ if (scope !== "apps" && scope !== "libs" && scope !== "pkgs") return false;
121
+
122
+ const base = path.basename(abs);
123
+ return (
124
+ parts.includes("srvkit") ||
125
+ parts.includes("common") ||
126
+ SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) ||
127
+ SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) ||
128
+ RUNTIME_METADATA_BASENAMES.has(base) ||
129
+ base === "main.ts" ||
130
+ base === "server.ts"
131
+ );
132
+ };
133
+
134
+ export const shouldMarkBuildPhaseRecovered = (
135
+ previousByPhase: ReadonlyMap<BuildPhase, DevBuildStatus>,
136
+ status: DevBuildStatus,
137
+ ): boolean => {
138
+ const previous = previousByPhase.get(status.phase);
139
+ return Boolean(previous && status.ok && !previous.ok && generationValue(status.generation) >= previous.generation);
140
+ };
141
+
142
+ export const createBackendBuildStatus = ({
143
+ generation,
144
+ ok,
145
+ files = [],
146
+ message,
147
+ }: {
148
+ generation: number;
149
+ ok: boolean;
150
+ files?: string[];
151
+ message?: string;
152
+ }): DevBuildStatus => ({
153
+ generation,
154
+ phase: "backend",
155
+ ok,
156
+ files,
157
+ message,
158
+ });
159
+
160
+ export const backendRestartReasonFromMessage = (
161
+ message: Extract<BuilderMessage, { type: "invalidate" }>,
162
+ ): BackendRestartReason => {
163
+ const roleSet = new Set<BackendRestartReason["roles"][number]>();
164
+ for (const role of message.devPlan?.roles ?? []) {
165
+ if (role === "server" || role === "shared" || role === "barrel" || role === "config") roleSet.add(role);
166
+ }
167
+ return {
168
+ generation: message.devPlan?.generation ?? message.generation,
169
+ files: [...new Set(message.files)].sort(),
170
+ roles: RESTART_ROLE_ORDER.filter((role) => roleSet.has(role)),
171
+ };
172
+ };
173
+
174
+ export const mergeBackendRestartReasons = (
175
+ current: BackendRestartReason | null,
176
+ next: BackendRestartReason,
177
+ ): BackendRestartReason => ({
178
+ generation:
179
+ generationValue(next.generation) >= generationValue(current?.generation) ? next.generation : current?.generation,
180
+ files: [...new Set([...(current?.files ?? []), ...next.files])].sort(),
181
+ roles: RESTART_ROLE_ORDER.filter((role) => current?.roles.includes(role) || next.roles.includes(role)),
182
+ });
183
+
184
+ export const shouldReplaceLastGoodMessage = (
185
+ current:
186
+ | Extract<BuilderMessage, { type: "pages-updated" }>
187
+ | Extract<BuilderMessage, { type: "css-updated" }>
188
+ | undefined,
189
+ next: Extract<BuilderMessage, { type: "pages-updated" }> | Extract<BuilderMessage, { type: "css-updated" }>,
190
+ ): boolean => !current || generationValue(next.data.generation) >= generationValue(current.data.generation);
191
+
192
+ export const shouldQueueBuildStatusReplay = (backendReady: boolean, pendingReplayCount: number): boolean =>
193
+ !backendReady || pendingReplayCount > 0;
194
+
195
+ /**
196
+ * Recycling the builder/backend on a generation whose build already failed is guaranteed to strand
197
+ * the dev server: the rebooted builder hits the same compile error and exits before builder-ready.
198
+ * Failing phase statuses for a generation arrive over IPC before that generation's invalidate, so
199
+ * the host can check them here and defer the recycle until a healthy batch lands.
200
+ */
201
+ export const hasBuildFailureForGeneration = (
202
+ statusByPhase: ReadonlyMap<BuildPhase, DevBuildStatus>,
203
+ generation: number | undefined,
204
+ ): boolean => {
205
+ if (typeof generation !== "number") return false;
206
+ for (const status of statusByPhase.values()) {
207
+ if (!status.ok && status.generation === generation) return true;
208
+ }
209
+ return false;
210
+ };
211
+
212
+ export type BuilderRssRecycleDecision = "unbounded" | "below-ceiling" | "build-failed" | "too-soon" | "recycle";
213
+
214
+ /**
215
+ * Whether an over-ceiling builder should be replaced now.
216
+ *
217
+ * `Bun.build` never returns its native arenas, so the builder's RSS only comes back when the process
218
+ * exits. Recycling it is therefore the only bound available — but it costs a boot build, so the two
219
+ * cases where a recycle cannot help are excluded: a generation whose build already failed (the
220
+ * replacement would hit the same compile error), and a recycle so soon after the last one that the
221
+ * ceiling is evidently unreachable for this app.
222
+ */
223
+ export const decideBuilderRssRecycle = ({
224
+ rssBytes,
225
+ ceilingBytes,
226
+ buildFailed,
227
+ msSinceLastRecycle,
228
+ minIntervalMs = BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
229
+ }: {
230
+ rssBytes: number;
231
+ ceilingBytes: number | null;
232
+ buildFailed: boolean;
233
+ msSinceLastRecycle: number | null;
234
+ minIntervalMs?: number;
235
+ }): BuilderRssRecycleDecision => {
236
+ if (!ceilingBytes) return "unbounded";
237
+ if (rssBytes < ceilingBytes) return "below-ceiling";
238
+ if (buildFailed) return "build-failed";
239
+ if (msSinceLastRecycle !== null && msSinceLastRecycle < minIntervalMs) return "too-soon";
240
+ return "recycle";
241
+ };
242
+
243
+ export type BuilderRssSettleDecision = "recycle-now" | "wait-and-recheck";
244
+
245
+ /**
246
+ * Whether an armed recycle should wait out the allocator's purge window before committing. A builder
247
+ * far enough over the ceiling is not going to be rescued by a purge, so waiting there only delays a
248
+ * recycle that has to happen.
249
+ */
250
+ export const decideBuilderRssSettle = ({
251
+ rssBytes,
252
+ ceilingBytes,
253
+ hardMultiple = BUILDER_RSS_HARD_MULTIPLE,
254
+ }: {
255
+ rssBytes: number;
256
+ ceilingBytes: number;
257
+ hardMultiple?: number;
258
+ }): BuilderRssSettleDecision => (rssBytes >= ceilingBytes * hardMultiple ? "recycle-now" : "wait-and-recheck");
259
+
260
+ export type IdleSuspendDecision =
261
+ | "disabled"
262
+ | "already-suspended"
263
+ | "builder-not-ready"
264
+ | "backend-not-ready"
265
+ | "build-failed"
266
+ | "restart-pending"
267
+ | "too-soon"
268
+ | "suspend";
269
+
270
+ /**
271
+ * Whether the dev host may drop its build capacity now. Every "no" here is a case where suspending
272
+ * would either lose work or produce a wake that immediately re-suspends:
273
+ *
274
+ * - a red build means the developer is mid-fix and about to save again, and a wake would boot straight
275
+ * back into the same error via the degraded-boot path
276
+ * - a pending restart/recovery already has its own plan for the builder
277
+ * - `too-soon` keeps a wake from flapping around whatever triggered it
278
+ */
279
+ export const decideIdleSuspend = ({
280
+ enabled,
281
+ suspended,
282
+ builderReady,
283
+ backendReady,
284
+ buildFailed,
285
+ restartPending,
286
+ msSinceWake,
287
+ minUptimeMs = DEV_IDLE_MIN_UPTIME_MS,
288
+ }: {
289
+ enabled: boolean;
290
+ suspended: boolean;
291
+ builderReady: boolean;
292
+ backendReady: boolean;
293
+ buildFailed: boolean;
294
+ restartPending: boolean;
295
+ msSinceWake: number | null;
296
+ minUptimeMs?: number;
297
+ }): IdleSuspendDecision => {
298
+ if (!enabled) return "disabled";
299
+ if (suspended) return "already-suspended";
300
+ if (!builderReady) return "builder-not-ready";
301
+ if (!backendReady) return "backend-not-ready";
302
+ if (buildFailed) return "build-failed";
303
+ if (restartPending) return "restart-pending";
304
+ if (msSinceWake !== null && msSinceWake < minUptimeMs) return "too-soon";
305
+ return "suspend";
306
+ };
307
+
308
+ /** `undefined` env means the default is on; any non-positive value turns idle suspend off. */
309
+ export const resolveIdleSuspendMs = (raw: string | undefined): number | null => {
310
+ if (raw === undefined || raw === "") return DEV_IDLE_SUSPEND_MS;
311
+ const parsed = Number(raw);
312
+ if (!Number.isFinite(parsed) || parsed <= 0) return null;
313
+ return Math.round(parsed);
314
+ };
315
+
316
+ /** Any red phase blocks a suspend, unlike the rss recycle which only cares about one generation. */
317
+ export const hasAnyBuildFailure = (statusByPhase: ReadonlyMap<BuildPhase, DevBuildStatus>): boolean =>
318
+ [...statusByPhase.values()].some((status) => !status.ok);
319
+
320
+ /**
321
+ * A config change while suspended cannot be applied by restarting the builder alone — the dev host
322
+ * itself has to re-read the config, which is the same path an ordinary config save takes.
323
+ */
324
+ export const shouldRefreshConfigOnIdleWake = (batch: ChangeBatch | null): boolean =>
325
+ !!batch && batch.kinds.has("config");
326
+
327
+ /**
328
+ * Whether a request that arrived while the builder was away should wait for the one coming back.
329
+ *
330
+ * A recycle or a crash-restart is a gap, not a failure — the request that lands in it is the page a
331
+ * developer is waiting on. A stopped builder is a different thing: nothing is bringing it back, so
332
+ * waiting would only delay the error.
333
+ *
334
+ * `recycling` is in here for the same reason as `restarting`, and was the hole this decision shipped
335
+ * with: a draining builder is still alive, so the request reached it and came back refused while the
336
+ * host still thought there was nothing to wait for.
337
+ */
338
+ const RETURNING_BUILDER_STATUSES = new Set<IncrementalBuilderStatus>(["starting", "recycling", "restarting"]);
339
+ export const shouldHoldForReturningBuilder = ({
340
+ status,
341
+ heldCount,
342
+ limit = HELD_BUILDER_REQUEST_LIMIT,
343
+ }: {
344
+ status: IncrementalBuilderStatus;
345
+ heldCount: number;
346
+ limit?: number;
347
+ }): boolean => RETURNING_BUILDER_STATUSES.has(status) && heldCount < limit;
348
+
349
+ /**
350
+ * Whether a builder that is over the ceiling again this soon after being replaced is worth saying so
351
+ * about, once. Not a reason to stop enforcing the ceiling: the minimum interval already bounds what
352
+ * this costs at one recycle per interval, and dropping the bound is how a container gets OOM-killed.
353
+ *
354
+ * This used to disable the ceiling for the session, on a count that a single page load reaches — two
355
+ * route builds, two reports, both inside the interval. That is normal work on any app whose builds sit
356
+ * above the ceiling, which is the same app the ceiling was derived for.
357
+ */
358
+ export const shouldWarnBuilderRssCeilingTight = (
359
+ reportsSinceRecycle: number,
360
+ limit = BUILDER_TIGHT_RSS_REPORT_LIMIT,
361
+ ): boolean => reportsSinceRecycle >= limit;
362
+
363
+ /**
364
+ * Whether recycling can ever bring this builder under the ceiling.
365
+ *
366
+ * Measured on a replacement the moment it is ready, before it has built anything on demand: that is
367
+ * the floor every future replacement lands on, so a floor already over the ceiling is the one case
368
+ * where the recycle loop is pure cost. It is also the case the escape hatch was always described as
369
+ * being for — the previous rule inferred it from report timing and caught ordinary work instead.
370
+ */
371
+ export const isRssCeilingUnreachable = (freshRssBytes: number | null, ceilingBytes: number | null): boolean =>
372
+ freshRssBytes !== null && ceilingBytes !== null && freshRssBytes >= ceilingBytes;
373
+
374
+ /**
375
+ * Whether a recycled builder's re-announced boot artifact actually differs from what the backend
376
+ * already has. Both payload identities are content hashes — `pages-[hash].js` and
377
+ * `<name>-[hash].css` — so an unchanged recycle produces identical ones and needs no reload. Only a
378
+ * save that raced the recycle moves them, and that is the case worth pushing.
379
+ */
380
+ export const shouldRelayRecycledFrontendState = (
381
+ current:
382
+ | Extract<BuilderMessage, { type: "pages-updated" }>
383
+ | Extract<BuilderMessage, { type: "css-updated" }>
384
+ | undefined,
385
+ next: Extract<BuilderMessage, { type: "pages-updated" }> | Extract<BuilderMessage, { type: "css-updated" }>,
386
+ ): boolean => {
387
+ if (!current || current.type !== next.type) return true;
388
+ if (current.type === "pages-updated" && next.type === "pages-updated")
389
+ return current.data.bundlePath !== next.data.bundlePath;
390
+ if (current.type === "css-updated" && next.type === "css-updated")
391
+ return JSON.stringify(current.data.cssAssets) !== JSON.stringify(next.data.cssAssets);
392
+ return true;
393
+ };
394
+
395
+ const mergeDevPlans = (current?: DevChangePlan, next?: DevChangePlan): DevChangePlan | undefined => {
396
+ if (!current) return next;
397
+ if (!next) return current;
398
+ const reasonByFile: Record<string, string[]> = { ...current.reasonByFile };
399
+ for (const [file, reasons] of Object.entries(next.reasonByFile)) {
400
+ reasonByFile[file] = [...new Set([...(reasonByFile[file] ?? []), ...reasons])].sort();
401
+ }
402
+ return {
403
+ generation: Math.max(current.generation, next.generation),
404
+ files: [...new Set([...current.files, ...next.files])].sort(),
405
+ generatedFiles: [...new Set([...current.generatedFiles, ...next.generatedFiles])].sort(),
406
+ roles: [...new Set([...current.roles, ...next.roles])].sort(),
407
+ actions: [...new Set([...current.actions, ...next.actions])].sort(),
408
+ reasonByFile,
409
+ };
410
+ };
411
+
412
+ /** A deferred recycle accumulates every batch it skipped so the eventual restart covers them all. */
413
+ export const mergeInvalidateMessages = (
414
+ current: Extract<BuilderMessage, { type: "invalidate" }>,
415
+ next: Extract<BuilderMessage, { type: "invalidate" }>,
416
+ ): Extract<BuilderMessage, { type: "invalidate" }> => {
417
+ const generation = Math.max(generationValue(current.generation), generationValue(next.generation));
418
+ return {
419
+ type: "invalidate",
420
+ kinds: [...new Set([...current.kinds, ...next.kinds])].sort(),
421
+ files: [...new Set([...current.files, ...next.files])].sort(),
422
+ generation: generation >= 0 ? generation : undefined,
423
+ devPlan: mergeDevPlans(current.devPlan, next.devPlan),
424
+ };
425
+ };
426
+
427
+ export const buildStatusReplaySequence = (
428
+ pendingReplay: readonly DevBuildStatus[],
429
+ latestByPhase: ReadonlyMap<BuildPhase, DevBuildStatus>,
430
+ ): DevBuildStatus[] => [...pendingReplay, ...latestByPhase.values()];
431
+
432
+ /** `(mtimeMs, size)` per file — what a save moves, and what a rebuild of identical content does not. */
433
+ export type SourceFingerprints = ReadonlyMap<string, string>;
434
+
435
+ /**
436
+ * Which of the files in `before` are no longer stamped the way they were.
437
+ *
438
+ * Only files present in `before` are compared. The question this answers is which *running* code went
439
+ * stale while nothing was watching, and a file that did not exist then is not running anywhere.
440
+ */
441
+ export const filesChangedSince = (before: SourceFingerprints, after: SourceFingerprints): string[] =>
442
+ [...before].filter(([file, stamp]) => after.get(file) !== stamp).map(([file]) => file);
package/akanApp/index.ts CHANGED
@@ -1 +1,3 @@
1
1
  export * from "./akanApp.host";
2
+ export * from "./BackendImportGraph";
3
+ export * from "./devHostPolicy";