@ultimat3/cli 30.9.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CLAUDE.md +75 -64
  2. package/README.md +4 -1
  3. package/package.json +30 -29
  4. package/src/admin-registration.ts +1 -1
  5. package/src/affected.ts +5 -1
  6. package/src/app-boundaries.ts +88 -9
  7. package/src/app-load-async.ts +133 -0
  8. package/src/app-load-batch.ts +203 -0
  9. package/src/app-load-prebuilt.ts +147 -0
  10. package/src/app-load-register.ts +175 -0
  11. package/src/app-load.ts +143 -175
  12. package/src/app-loader-imports.ts +31 -0
  13. package/src/app-root.ts +13 -0
  14. package/src/app-runtime.ts +5 -1
  15. package/src/boundary-findings.ts +12 -0
  16. package/src/browser-launcher-port.ts +3 -7
  17. package/src/browser-launcher.ts +1 -1
  18. package/src/budgets-scan.ts +8 -0
  19. package/src/budgets.ts +10 -1
  20. package/src/build-registry-background.ts +59 -0
  21. package/src/build-registry.ts +207 -0
  22. package/src/cdp-shot-clock.ts +3 -11
  23. package/src/cdp-shot-driver.ts +3 -2
  24. package/src/cdp-shot-element.ts +3 -2
  25. package/src/cdp-shot-page.ts +2 -2
  26. package/src/cdp-shot-watch.ts +4 -3
  27. package/src/cmd-auth.ts +3 -3
  28. package/src/cmd-db-recount.ts +15 -0
  29. package/src/cmd-drill.ts +10 -6
  30. package/src/cmd-exercise.ts +2 -1
  31. package/src/cmd-generate-spec.ts +6 -0
  32. package/src/cmd-generate.ts +22 -4
  33. package/src/cmd-mail.ts +1 -1
  34. package/src/cmd-routes.ts +2 -2
  35. package/src/cmd-secrets-spec.ts +4 -1
  36. package/src/cmd-shot.ts +14 -4
  37. package/src/cmd-verify-spec.ts +21 -1
  38. package/src/cmd-verify.ts +16 -4
  39. package/src/coverage-source.ts +4 -1
  40. package/src/db-diagnostics.ts +8 -1
  41. package/src/dev-boot.ts +29 -15
  42. package/src/dev-dashboard-invalidations.ts +43 -0
  43. package/src/dev-dashboard.ts +13 -16
  44. package/src/dev-n-plus-one.ts +7 -3
  45. package/src/dev-rebuild.ts +2 -1
  46. package/src/dev-route-table.ts +1 -1
  47. package/src/dev-traces.ts +16 -15
  48. package/src/document-options.ts +12 -1
  49. package/src/drift-store.ts +55 -0
  50. package/src/error-catalog.ts +8 -3
  51. package/src/error-codes-boundary.ts +32 -0
  52. package/src/error-codes.ts +23 -19
  53. package/src/errors.ts +17 -7
  54. package/src/exercise-database.ts +13 -1
  55. package/src/exercise-findings.ts +36 -18
  56. package/src/exercise-services.ts +84 -0
  57. package/src/exercise-subject.ts +38 -13
  58. package/src/failure-capture-boot.ts +9 -5
  59. package/src/framework-schema.ts +5 -5
  60. package/src/generate-exercise.ts +1 -1
  61. package/src/generate-files.ts +27 -7
  62. package/src/generate-kinds.ts +5 -0
  63. package/src/generate-refresh.ts +53 -0
  64. package/src/generate-workspace.ts +169 -0
  65. package/src/generate-write.ts +8 -2
  66. package/src/hold.ts +19 -8
  67. package/src/image-prepare.ts +6 -2
  68. package/src/index.ts +5 -20
  69. package/src/island-bundle.ts +7 -3
  70. package/src/island-capture.ts +2 -2
  71. package/src/island-harness.ts +1 -1
  72. package/src/job-registration.ts +43 -6
  73. package/src/jobs-driver.ts +4 -5
  74. package/src/mcp-errors.ts +18 -4
  75. package/src/mcp-host.ts +5 -1
  76. package/src/mcp-ui-interact.ts +3 -0
  77. package/src/messages-gate.ts +4 -0
  78. package/src/new-shapes-generate.ts +1 -1
  79. package/src/otlp-export.ts +94 -29
  80. package/src/output.ts +3 -7
  81. package/src/page-sync.ts +3 -1
  82. package/src/role-load.ts +17 -11
  83. package/src/role-start.ts +5 -4
  84. package/src/role-sync.ts +7 -8
  85. package/src/route-islands-preload.ts +46 -0
  86. package/src/route-islands.ts +6 -2
  87. package/src/runtime-admin.ts +5 -1
  88. package/src/runtime-bindings.ts +25 -19
  89. package/src/runtime-boot-ports.ts +66 -0
  90. package/src/runtime-bus.ts +29 -5
  91. package/src/runtime-cache-bus.ts +53 -0
  92. package/src/runtime-cache.ts +43 -13
  93. package/src/runtime-isr-outcome.ts +5 -4
  94. package/src/runtime-jobs.ts +2 -2
  95. package/src/runtime-keys.ts +37 -0
  96. package/src/runtime-overrides.ts +148 -42
  97. package/src/runtime-port-bindings-queue.ts +36 -0
  98. package/src/runtime-port-bindings.ts +117 -0
  99. package/src/runtime-ports.ts +164 -0
  100. package/src/runtime-purge.ts +41 -28
  101. package/src/runtime-push.ts +7 -3
  102. package/src/runtime-queue.ts +70 -55
  103. package/src/runtime-realtime.ts +5 -5
  104. package/src/runtime-render-document.ts +4 -1
  105. package/src/runtime-services.ts +110 -158
  106. package/src/runtime-storage-boot.ts +111 -0
  107. package/src/runtime-storage-upload.ts +9 -7
  108. package/src/runtime-storage.ts +7 -1
  109. package/src/serve-boot.ts +8 -4
  110. package/src/serve-entry.ts +3 -0
  111. package/src/serve-env.ts +47 -14
  112. package/src/serve-prebuilt-paths.ts +3 -0
  113. package/src/serve-prebuilt.ts +15 -4
  114. package/src/serve.ts +2 -2
  115. package/src/static-cards.ts +3 -2
  116. package/src/static-report.ts +2 -2
  117. package/src/style-bundle.ts +1 -1
  118. package/src/sync-authenticator.ts +17 -18
  119. package/src/templates/action-tests.ts +4 -4
  120. package/src/templates/backfill.ts +5 -8
  121. package/src/templates/entity.ts +3 -0
  122. package/src/templates/github/ci.yml.ts +3 -1
  123. package/src/templates/github/dependabot.yml.ts +73 -0
  124. package/src/templates/job.ts +13 -22
  125. package/src/templates/naming.ts +20 -1
  126. package/src/templates/pinned/docker-compose.yml +1 -1
  127. package/src/templates/query.ts +7 -8
  128. package/src/templates/route.ts +5 -3
  129. package/src/templates/scaffold-api.ts +1 -1
  130. package/src/templates/scaffold-auth.ts +5 -3
  131. package/src/templates/scaffold-claude-commands.ts +6 -3
  132. package/src/templates/scaffold-claude.ts +4 -4
  133. package/src/templates/scaffold-container-compose.ts +2 -4
  134. package/src/templates/scaffold-domain-package.ts +1 -1
  135. package/src/templates/scaffold-entries.ts +6 -1
  136. package/src/templates/scaffold-helm-fences.ts +3 -2
  137. package/src/templates/scaffold-helm.ts +35 -6
  138. package/src/templates/scaffold-repo.ts +47 -135
  139. package/src/templates/scaffold-runtime-ports.ts +62 -0
  140. package/src/templates/scaffold-verify-floor.ts +97 -0
  141. package/src/templates/shapes/overlay.ts +1 -1
  142. package/src/templates/sign-in-oidc.ts +5 -3
  143. package/src/templates/sign-in-shared.ts +28 -10
  144. package/src/templates/workspace.ts +75 -0
  145. package/src/test-ignores.ts +5 -2
  146. package/src/test-select.ts +4 -1
  147. package/src/upgrade-gate.ts +30 -5
  148. package/src/upgrade-report.ts +7 -1
  149. package/src/verify-changed-facts.ts +53 -0
  150. package/src/verify-changed-scope.ts +161 -0
  151. package/src/verify-changed.ts +174 -0
  152. package/src/verify-checks.ts +31 -19
  153. package/src/verify-drift-owner.ts +30 -0
  154. package/src/verify-e2e.ts +2 -1
  155. package/src/verify-factories.ts +86 -0
  156. package/src/verify-run.ts +13 -11
  157. package/src/verify-step.ts +13 -0
  158. package/src/verify-tests.ts +58 -6
  159. package/src/write-line.ts +21 -6
  160. package/wiki/Actions.md +2 -2
  161. package/wiki/Adapters.md +400 -0
  162. package/wiki/Admin-Dashboard.md +1 -1
  163. package/wiki/Agents.md +9 -9
  164. package/wiki/Auth.md +78 -2
  165. package/wiki/Building-Your-Own-Base.md +1 -1
  166. package/wiki/CLI-Reference.md +34 -7
  167. package/wiki/Caching-And-Invalidation.md +17 -5
  168. package/wiki/Compared.md +8 -2
  169. package/wiki/Configuration.md +14 -14
  170. package/wiki/Deployment.md +28 -1
  171. package/wiki/Entities-And-Migrations.md +47 -1
  172. package/wiki/FAQ.md +8 -2
  173. package/wiki/Feature-Flags.md +1 -1
  174. package/wiki/Home.md +3 -2
  175. package/wiki/Jobs-And-Workflows.md +107 -6
  176. package/wiki/Known-Gaps.md +4 -3
  177. package/wiki/MCP-And-AI.md +18 -4
  178. package/wiki/Mail.md +14 -5
  179. package/wiki/Migrations-And-Backfills.md +29 -4
  180. package/wiki/Money.md +2 -0
  181. package/wiki/N-Plus-One-Detection.md +24 -22
  182. package/wiki/Notify.md +28 -4
  183. package/wiki/Observability.md +121 -15
  184. package/wiki/Queries-And-Live-Queries.md +2 -2
  185. package/wiki/Realtime.md +9 -4
  186. package/wiki/Routes-And-Render-Modes.md +5 -0
  187. package/wiki/Scraping.md +57 -11
  188. package/wiki/Shapes.md +2 -2
  189. package/wiki/Stability.md +7 -5
  190. package/wiki/Storage-And-Uploads.md +56 -4
  191. package/wiki/Testing.md +65 -52
  192. package/wiki/Troubleshooting.md +1 -1
  193. package/wiki/Tutorial-01-First-App.md +1 -1
  194. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  195. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  196. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  197. package/wiki/Upgrading.md +129 -4
package/src/app-load.ts CHANGED
@@ -5,22 +5,15 @@
5
5
 
6
6
  // Bun ships no `Bun.*` path API: `join`/`resolve` reach the files a scan imports.
7
7
  import { join, resolve } from 'node:path';
8
- import { isAction, isMutator, listActions, registerActions } from '@ultimat3/action';
8
+ import { listActions } from '@ultimat3/action';
9
9
  import { APP_CONFIG_FILE } from '@ultimat3/core';
10
- import { describeEntities, registeredEntities } from '@ultimat3/entity';
10
+ import { describeEntities } from '@ultimat3/entity';
11
11
  import type { AppLocaleSet } from '@ultimat3/i18n/app-catalogs';
12
12
  import { appLocaleSet, UNDECLARED_LOCALES } from '@ultimat3/i18n/app-catalogs';
13
- import { isJobHandle, isTaskHandle, registeredJobs, registeredTasks } from '@ultimat3/jobs';
13
+ import { registeredJobs, registeredTasks } from '@ultimat3/jobs';
14
14
  import type { ErrorCodeFact } from '@ultimat3/manifest';
15
- import { isQuery, listQueries, registerQueries } from '@ultimat3/query';
16
- import type { RouteConfig } from '@ultimat3/render';
17
- import {
18
- isRouteConfig,
19
- pageComponentOf,
20
- registerRoute,
21
- routeEntries,
22
- setAssetResolver,
23
- } from '@ultimat3/render';
15
+ import { listQueries } from '@ultimat3/query';
16
+ import { routeEntries, setAssetResolver } from '@ultimat3/render';
24
17
  // For the SIDE EFFECT, and it is this module's to hold: importing `@ultimat3/render/server`
25
18
  // installs the `.tsx`/`.scss` Bun plugin, a plugin only transforms modules loaded AFTER it, and
26
19
  // every app module below is loaded by the dynamic `import()` in this file. Before the render
@@ -29,14 +22,11 @@ import {
29
22
  // accident one refactor away from compiling every app's `.tsx` to `React.createElement`. The named
30
23
  // import is a value import, so the side effect holds without the bare line it replaced.
31
24
  import { setStylesheetRoot } from '@ultimat3/render/server';
25
+ import { asyncModules } from './app-load-async';
26
+ import { importInOrder } from './app-load-batch';
27
+ import { isFirstPass, registeredAny, registerModule } from './app-load-register';
32
28
  import { unresolvedImportFinding } from './app-load-unresolved';
33
- import {
34
- evictChanged,
35
- pinModule,
36
- resetReloadGraph,
37
- trackModule,
38
- trackStylesheets,
39
- } from './app-reload-graph';
29
+ import { evictChanged, trackModule, trackStylesheets } from './app-reload-graph';
40
30
  import { API_INDEX } from './app-root';
41
31
  import { collectDeclaredCodes } from './error-contract';
42
32
  import type { Finding } from './output';
@@ -104,32 +94,8 @@ export interface LoadedApp {
104
94
  readonly findings: readonly Finding[];
105
95
  }
106
96
 
107
- // A module is imported and registered once per PROCESS: `import()` caches, and a registry rejects
108
- // a second registration of a name. So a rescan refreshes the facts DERIVED from the registries —
109
- // the manifest and its build id — and, for exactly one kind of module, the registration itself. A
110
- // rescan first evicts every changed module, and everything that imports it, from Bun's registry
111
- // (`app-reload-graph.ts`), so the loop's own `import()` evaluates the new chain; a ROUTE module
112
- // that comes back as a different instance has its entry replaced. A module that defines a
113
- // primitive (an action, a query, an entity, a job, a task) is pinned instead — its exports are held
114
- // by every importer and a second instance would be a duplicate name in its registry — so those
115
- // edits still need a restart. Until 2026-09-27 only the route module itself was re-imported, under
116
- // `?x-reload=<hash>`, and every component it imports stayed the cached one: `x dev` logged
117
- // "reloaded" and served the old component.
118
- const registered = new Set<string>();
119
- // A registration failure is sticky: the file is never retried, so the finding is replayed.
120
- const failures = new Map<string, Finding>();
121
- // Route modules only: the module instance each one registered from. A rescan that imports the same
122
- // instance registers nothing; a different one (the file or something it imports was evicted) is
123
- // the page the author saved.
124
- const routeModules = new Map<string, Record<string, unknown>>();
125
-
126
- /** Test seam, and what `x dev` would call if it ever restarted the registries in-process. */
127
- export function resetAppLoad(): void {
128
- registered.clear();
129
- failures.clear();
130
- routeModules.clear();
131
- resetReloadGraph();
132
- }
97
+ // Registration, and the once-per-process state behind it, is `app-load-register.ts`'s.
98
+ export { resetAppLoad } from './app-load-register';
133
99
 
134
100
  /**
135
101
  * One glob's hits in code-unit order of their POSIX spelling — never the host's. Sorted raw, `\`
@@ -197,6 +163,27 @@ export interface ScanOptions {
197
163
  * `loadAppForRole`, which decides what the role imports.
198
164
  */
199
165
  export async function scanAppModules(root: string, options: ScanOptions): Promise<AppScan> {
166
+ prepareAppImport(root);
167
+ // A rescan: whatever changed on disk since the last one, and everything importing it, leaves
168
+ // Bun's module registry before the loop below imports it again.
169
+ const rescan = options.track && registeredAny();
170
+ if (rescan) await evictChanged(root);
171
+ const candidates = (await appModulePaths(root)).filter((absolute) =>
172
+ isScannedModule(root, absolute),
173
+ );
174
+ // `include` is asked before each import, of the process as the PREVIOUS import left it — the
175
+ // role load and the gate's probe both read that state — so a scan that asks it is serial. A
176
+ // rescan is too: it imports what it evicted, and every other module answers from the cache.
177
+ const scan =
178
+ options.include === undefined && !rescan
179
+ ? await scanBatched(root, candidates, options.track)
180
+ : await scanSerial(root, candidates, options);
181
+ scan.files.sort();
182
+ return scan;
183
+ }
184
+
185
+ /** What every import of the app's modules needs first: the scan's, and the prebuilt registry's. */
186
+ export function prepareAppImport(root: string): void {
200
187
  // Before any import: a stylesheet's surface is read below the app root, never off its absolute
201
188
  // path — under the container's `WORKDIR /app` that path's first segment is `app/`, and every
202
189
  // sheet, the site's included, classified as app CSS.
@@ -205,28 +192,115 @@ export async function scanAppModules(root: string, options: ScanOptions): Promis
205
192
  // `x dev`, the container and the static build alike — one install, three processes.
206
193
  const assets = siteAssetTable(root);
207
194
  setAssetResolver((path) => assets.resolve(path).url);
208
- const files: string[] = [];
209
- const findings: Finding[] = [];
210
- // A rescan: whatever changed on disk since the last one, and everything importing it, leaves
211
- // Bun's module registry before the loop below imports it again.
212
- if (options.track && registered.size > 0) await evictChanged(root);
195
+ }
196
+
197
+ /** Mutable while a scan fills it; handed out as an `AppScan`. */
198
+ interface ScanResult {
199
+ readonly files: string[];
200
+ readonly findings: Finding[];
201
+ }
202
+
203
+ /**
204
+ * Whether the scan imports `absolute` at all — the one rule, for the scan, the prebuilt registry
205
+ * and `x g`'s "does this write change the manifest?" (`generate-refresh.ts`).
206
+ */
207
+ export function isScannedModule(root: string, absolute: string): boolean {
208
+ // A SEGMENT, never a substring: an app checked out under
209
+ // `~/dev/node_modules-experiments/myapp` answered `includes('node_modules')` for every
210
+ // file it holds, so this loop imported none of them and the app registered nothing.
211
+ // The ROOT-RELATIVE path is tested, never the absolute one: an app checked out under
212
+ // `~/work/my.test.app` matched `.test.` on every file and loaded none of them.
213
+ const file = posixRelative(root, absolute);
214
+ if (hasPathSegment(absolute, 'node_modules') || isTest(file)) return false;
215
+ return !(
216
+ ENTRY_POINT.test(file) ||
217
+ EXERCISE_FILE.test(file) ||
218
+ CLIENT_ENTRY_POINT.test(file) ||
219
+ STATES_FILE.test(file)
220
+ );
221
+ }
213
222
 
214
- for (const absolute of await appModulePaths(root)) {
215
- // A SEGMENT, never a substring: an app checked out under
216
- // `~/dev/node_modules-experiments/myapp` answered `includes('node_modules')` for every
217
- // file it holds, so this loop imported none of them and the app registered nothing.
218
- // The ROOT-RELATIVE path is tested, never the absolute one: an app checked out under
219
- // `~/work/my.test.app` matched `.test.` on every file and loaded none of them.
223
+ /**
224
+ * Whether the scan would import the file at `path` (app-root-relative) if it existed: one of the
225
+ * scan's globs matches it and `isScannedModule` admits it. For a caller holding a path, not a
226
+ * glob's answer — `x g` asking whether a file it wrote is an app module (`generate-refresh.ts`).
227
+ */
228
+ export function isAppModulePath(root: string, path: string): boolean {
229
+ const file = toPosix(path);
230
+ return (
231
+ APP_GLOBS.some((pattern) => new Bun.Glob(pattern).match(file)) &&
232
+ isScannedModule(root, resolve(root, file))
233
+ );
234
+ }
235
+
236
+ /** Every module the scan would import, in its order — what `x build` writes the registry from. */
237
+ export async function scannedModulePaths(root: string): Promise<readonly string[]> {
238
+ return (await appModulePaths(root)).filter((absolute) => isScannedModule(root, absolute));
239
+ }
240
+
241
+ /** A module that would not import, keyed by its file. */
242
+ const importFinding = (error: unknown, root: string, file: string): Finding =>
243
+ unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file };
244
+
245
+ /** Reads at most this many sources at once: a 12k-module app opened 12k descriptors otherwise. */
246
+ const READ_BATCH = 64;
247
+
248
+ /**
249
+ * Every candidate imported in `importInOrder`'s batches and registered as it evaluates — before
250
+ * the next module evaluates, as `scanSerial` does. The sources of a tracked scan are all read
251
+ * BEFORE any import, for the reason `scanSerial` reads each one before its own: what is recorded
252
+ * is bound to the bytes that module was evaluated from.
253
+ */
254
+ async function scanBatched(
255
+ root: string,
256
+ candidates: readonly string[],
257
+ track: boolean,
258
+ ): Promise<ScanResult> {
259
+ if (track) {
260
+ const first = candidates.filter(isFirstPass);
261
+ for (let start = 0; start < first.length; start += READ_BATCH) {
262
+ const batch = first.slice(start, start + READ_BATCH);
263
+ const sources = await Promise.all(batch.map((absolute) => Bun.file(absolute).text()));
264
+ for (const [index, absolute] of batch.entries()) {
265
+ await trackModule(absolute, sources[index] as string, root);
266
+ }
267
+ }
268
+ }
269
+ const registered = new Map<number, Finding>();
270
+ const register = (index: number, module: Record<string, unknown>): void => {
271
+ const absolute = candidates[index] as string;
272
+ const file = posixRelative(root, absolute);
273
+ const finding = registerModule(module, { absolute, file, track });
274
+ if (finding !== undefined) registered.set(index, finding);
275
+ };
276
+ // A module that can suspend is imported on its own, or a sibling would evaluate before it ends.
277
+ const alone = await asyncModules(root, candidates);
278
+ const imported = await importInOrder(candidates, alone, register);
279
+ const result: ScanResult = { files: [], findings: [] };
280
+ for (const [index, absolute] of candidates.entries()) {
220
281
  const file = posixRelative(root, absolute);
221
- if (hasPathSegment(absolute, 'node_modules') || isTest(file)) continue;
222
- if (
223
- ENTRY_POINT.test(file) ||
224
- EXERCISE_FILE.test(file) ||
225
- CLIENT_ENTRY_POINT.test(file) ||
226
- STATES_FILE.test(file)
227
- ) {
282
+ const one = imported[index];
283
+ if (one === undefined) continue;
284
+ if (!one.ok) {
285
+ result.findings.push(importFinding(one.error, root, file));
228
286
  continue;
229
287
  }
288
+ result.files.push(file);
289
+ const finding = registered.get(index);
290
+ if (finding !== undefined) result.findings.push(finding);
291
+ }
292
+ return result;
293
+ }
294
+
295
+ /** One module at a time: `include` asked, the source read, the module imported and registered. */
296
+ async function scanSerial(
297
+ root: string,
298
+ candidates: readonly string[],
299
+ options: ScanOptions,
300
+ ): Promise<ScanResult> {
301
+ const result: ScanResult = { files: [], findings: [] };
302
+ for (const absolute of candidates) {
303
+ const file = posixRelative(root, absolute);
230
304
  if (options.include !== undefined && !(await options.include(absolute))) continue;
231
305
  // The source is read BEFORE the import, on the file's first pass — a rescan of a registered
232
306
  // module reads nothing here. What is recorded is bound to the bytes the module was evaluated
@@ -234,23 +308,21 @@ export async function scanAppModules(root: string, options: ScanOptions): Promis
234
308
  // the two bound V1's component to V2's hash, so the next scan saw nothing to do and served V1
235
309
  // until the save after. Read first, the worst case is one re-import the next tick, of a file
236
310
  // that did change. An untracked scan reads nothing here: no save lands in an image.
237
- const first = !registered.has(absolute) && !failures.has(absolute);
311
+ const first = isFirstPass(absolute);
238
312
  const snapshot = options.track && first ? await Bun.file(absolute).text() : undefined;
239
313
  if (first && snapshot !== undefined) await trackModule(absolute, snapshot, root);
240
314
  let module: Record<string, unknown>;
241
315
  try {
242
316
  module = (await import(absolute)) as Record<string, unknown>;
243
317
  } catch (error) {
244
- findings.push(unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file });
318
+ result.findings.push(importFinding(error, root, file));
245
319
  continue;
246
320
  }
247
- files.push(file);
248
- const finding = await register(absolute, file, module, options.track);
249
- if (finding !== undefined) findings.push(finding);
321
+ result.files.push(file);
322
+ const finding = registerModule(module, { absolute, file, track: options.track });
323
+ if (finding !== undefined) result.findings.push(finding);
250
324
  }
251
-
252
- files.sort();
253
- return { files, findings };
325
+ return result;
254
326
  }
255
327
 
256
328
  export async function loadApp(root: string): Promise<LoadedApp> {
@@ -309,110 +381,6 @@ const emptyAppFinding = (root: string): Finding => ({
309
381
  at: APP_CONFIG_FILE,
310
382
  });
311
383
 
312
- /**
313
- * Registers a module once; every later call replays whatever the first one reported — except for
314
- * a route module, which a later call re-registers when the import handed back a new instance.
315
- */
316
- async function register(
317
- absolute: string,
318
- file: string,
319
- module: Record<string, unknown>,
320
- track: boolean,
321
- ): Promise<Finding | undefined> {
322
- const previous = failures.get(absolute);
323
- if (previous !== undefined) return previous;
324
- if (registered.has(absolute)) return track ? reloadRoute(absolute, file, module) : undefined;
325
- registered.add(absolute);
326
- try {
327
- const config = module['config'];
328
- const route = isRouteConfig(config) ? config : undefined;
329
- if (route !== undefined) {
330
- registerRouteModule(file, module, route);
331
- routeModules.set(absolute, module);
332
- }
333
- // A pin is the reload graph's: it stops an eviction a process that never rescans never runs,
334
- // and deciding it walks every export of every module against the entity registry.
335
- if (track && (definesPrimitive(module, route !== undefined) || file === API_INDEX)) {
336
- pinModule(absolute);
337
- }
338
- registerActions(module);
339
- registerQueries(module);
340
- return undefined;
341
- } catch (error) {
342
- const finding: Finding = { ...findingFrom(error), at: file };
343
- failures.set(absolute, finding);
344
- return finding;
345
- }
346
- }
347
-
348
- /**
349
- * A module whose instance must be the one every importer and every registry holds. A route module
350
- * may export an action beside its page — it has always been re-imported, and its actions stayed
351
- * registered from the first instance — so only an entity, a job or a task pins a route.
352
- */
353
- function definesPrimitive(module: Record<string, unknown>, route: boolean): boolean {
354
- // The registry holds an entry per entity; the value a module exports is the entry's `core`.
355
- const entities = new Set<unknown>(registeredEntities().flatMap((entry) => [entry, entry.core]));
356
- const defines = (value: unknown): boolean =>
357
- entities.has(value) ||
358
- isJobHandle(value) ||
359
- isTaskHandle(value) ||
360
- (!route && (isAction(value) || isQuery(value) || isMutator(value)));
361
- return Object.values(module).some((value) => {
362
- // A brand check reads a property, and an export may be a proxy whose every read throws until
363
- // the env is set — examples/dummy's typed client throws X_ENV_MISSING without APP_URL. A value
364
- // that cannot be asked is not a primitive: every primitive is a plain branded object.
365
- try {
366
- return defines(value);
367
- } catch {
368
- return false;
369
- }
370
- });
371
- }
372
-
373
- /** The route half of a registration, and the whole of a re-registration. */
374
- function registerRouteModule(
375
- file: string,
376
- module: Record<string, unknown>,
377
- config: RouteConfig,
378
- ): void {
379
- // The page component comes from the same module as its config, resolved by render's own
380
- // rule — the CLI does not decide which export is a page any more than it decides what a
381
- // route is. A module with no component registers without one, and renders a bare shell.
382
- const component = pageComponentOf(module);
383
- registerRoute({
384
- file,
385
- config,
386
- ...(component === undefined ? {} : { component }),
387
- });
388
- }
389
-
390
- /**
391
- * A registered route module, on a rescan: re-registered when the import handed back a different
392
- * instance — the file or something it imports was evicted — and left alone otherwise. A save that
393
- * will not import never reaches here (the loop reports it, not sticky), so the last page that did
394
- * import is the one served meanwhile.
395
- */
396
- function reloadRoute(
397
- absolute: string,
398
- file: string,
399
- module: Record<string, unknown>,
400
- ): Finding | undefined {
401
- const held = routeModules.get(absolute);
402
- if (held === undefined || held === module) return undefined;
403
- try {
404
- const config = module['config'];
405
- // A file that stopped being a route is not un-registered — the table has no verb for it, and a
406
- // deleted file needs a restart either way. Its instance is recorded so the same save is not
407
- // re-registered on every later tick.
408
- if (isRouteConfig(config)) registerRouteModule(file, module, config);
409
- routeModules.set(absolute, module);
410
- return undefined;
411
- } catch (error) {
412
- return { ...findingFrom(error), at: file };
413
- }
414
- }
415
-
416
384
  /**
417
385
  * `packages/db/src/errors.ts` → `packages/db`; `apps/web/app/posts/errors.ts` → `apps/web` — on
418
386
  * either separator. A manifest written on Windows split a `\`-path on `/`, kept the whole file as
@@ -0,0 +1,31 @@
1
+ // `X_BOUNDARY_LOADER_IMPORT`: an app module importing a registration loader. `defineApi` is an app's
2
+ // one registration path (axiom 1); `@ultimat3/{action,query}/loader` are `x`'s module scan's. The one
3
+ // boundary rule that also reads an app's TESTS — where an agent reaches for the loader first.
4
+
5
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
6
+ import type { SourceFile } from './app-boundaries';
7
+ import { commentSafe } from './comment-safe';
8
+ import { scanRuntimeImports } from './import-scan';
9
+ import type { Finding } from './output';
10
+
11
+ const LOADER_SUBPATH = /^@ultimat3\/(action|query)\/loader$/;
12
+ const LOADER_KEY: Readonly<Record<string, string>> = { action: 'actions', query: 'queries' };
13
+
14
+ /** One finding per loader import in `files`. Pure: runtime imports only, specifiers as written. */
15
+ export function loaderImportFindings(files: readonly SourceFile[]): readonly Finding[] {
16
+ const findings: Finding[] = [];
17
+ for (const file of files) {
18
+ for (const specifier of scanRuntimeImports(file)) {
19
+ const loader = LOADER_SUBPATH.exec(specifier)?.[1];
20
+ if (loader === undefined) continue;
21
+ findings.push({
22
+ code: 'X_BOUNDARY_LOADER_IMPORT',
23
+ cause: `an app module imports "${specifier}" — its registration functions are the boot's, and a call here is a second registration path beside defineApi`,
24
+ fix: `export const api = defineApi({ ${LOADER_KEY[loader] ?? 'actions'}: [yourModule] }); # in apps/web/api/index.ts — list the module there, then delete the import from ${commentSafe(file.path)}`,
25
+ docs: ERROR_DOCS_URL,
26
+ at: file.path,
27
+ });
28
+ }
29
+ }
30
+ return findings;
31
+ }
package/src/app-root.ts CHANGED
@@ -63,6 +63,7 @@ export function requireAppRoot(command: string, from: string): AppRoot {
63
63
  from: dir,
64
64
  below: appDirsBelow(dir),
65
65
  adopter: dependsOnFramework(dir),
66
+ xScript: hasXScript(dir),
66
67
  });
67
68
  }
68
69
  return root;
@@ -94,6 +95,18 @@ function dependsOnFramework(from: string): boolean {
94
95
  }
95
96
  }
96
97
 
98
+ /** Whether `from`'s manifest declares an `x` script — the framework repo's root does. Never throws. */
99
+ function hasXScript(from: string): boolean {
100
+ try {
101
+ const manifest: unknown = JSON.parse(readFileSync(join(from, 'package.json'), 'utf8'));
102
+ if (typeof manifest !== 'object' || manifest === null || !('scripts' in manifest)) return false;
103
+ const { scripts } = manifest;
104
+ return typeof scripts === 'object' && scripts !== null && 'x' in scripts;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
97
110
  /** Semver-lite compare, sufficient because both sides are plain `major.minor.patch`. */
98
111
  export function versionAtLeast(found: string, required: string): boolean {
99
112
  const parse = (input: string): readonly number[] =>
@@ -9,6 +9,7 @@
9
9
  import { existsSync } from 'node:fs';
10
10
  // why: Bun exposes no path-join primitive; each candidate is joined to the app root.
11
11
  import { join } from 'node:path';
12
+ import { assertRuntimeKeys } from './runtime-keys';
12
13
  import type { RuntimeOverrides } from './runtime-overrides';
13
14
 
14
15
  /** The one file an app writes, per app directory. */
@@ -40,7 +41,10 @@ export async function loadAppRuntime(root: string): Promise<RuntimeOverrides | u
40
41
  for (const file of files.sort()) {
41
42
  const module = (await import(join(root, file))) as Record<string, unknown>;
42
43
  const exported = module[APP_RUNTIME_EXPORT];
43
- if (isRecord(exported)) return exported as RuntimeOverrides;
44
+ if (isRecord(exported)) {
45
+ assertRuntimeKeys(file, exported);
46
+ return exported as RuntimeOverrides;
47
+ }
44
48
  }
45
49
  return undefined;
46
50
  }
@@ -3,9 +3,14 @@
3
3
  // was another command to run for the real one (plan 101 slice 11 j). The planner is the same one
4
4
  // `x fix boundary` prints from, so the gate and the command cannot disagree about the cut.
5
5
 
6
+ // why: a synchronous directory probe; Bun.file answers files.
7
+ import { existsSync } from 'node:fs';
8
+ // why: Bun exposes no path-join primitive; the probe takes a joined path.
9
+ import { join } from 'node:path';
6
10
  import type { SourceFile } from './app-boundaries';
7
11
  import { appImportGraph, checkImportRules, readAppSources } from './app-boundaries';
8
12
  import { siblingModuleFindings } from './app-layout';
13
+ import { loaderImportFindings } from './app-loader-imports';
9
14
  import { appTransportFindings } from './app-transport';
10
15
  import { planBoundaryCuts } from './boundary-cuts';
11
16
  import { handRolledSocketFindings } from './hand-rolled-socket';
@@ -52,5 +57,12 @@ export async function appBoundaryFindings(
52
57
  ...islandDisposerFindings(files),
53
58
  ...handRolledSocketFindings(files),
54
59
  ...(await packageBoundaryFindings(root)),
60
+ // The one rule an app's tests answer to as well (`app-loader-imports.ts`).
61
+ ...loaderImportFindings(await appTests(root)),
55
62
  ];
56
63
  }
64
+
65
+ /** The app's test files, for the loader rule — none where there is no `apps/` to glob. */
66
+ async function appTests(root: string): Promise<readonly SourceFile[]> {
67
+ return existsSync(join(root, 'apps')) ? readAppSources(root, 'tests') : [];
68
+ }
@@ -2,7 +2,7 @@
2
2
  // nowhere else. `cdp-shot-driver.ts` implements it over raw CDP; a test hands in a fake. Every
3
3
  // member is one a shot or a `ui.*` call reads. A member nothing reads is one the raw driver would
4
4
  // have to build and nothing would test, and that is how a port rots.
5
- import type { Clock } from '@ultimat3/core';
5
+ import type { SleepClock } from '@ultimat3/core';
6
6
 
7
7
  /** What the browser is told the OS prefers. `'no-preference'` CLEARS the override. */
8
8
  export type ShotColorScheme = 'light' | 'dark' | 'no-preference';
@@ -103,11 +103,6 @@ export interface AccessibilityOptions {
103
103
  readonly max?: number | undefined;
104
104
  }
105
105
 
106
- /** Every wait goes through this, so a test of a 30-second deadline finishes in microseconds. */
107
- export interface ShotClock extends Clock {
108
- sleep(ms: number, signal?: AbortSignal): Promise<void>;
109
- }
110
-
111
106
  export interface ShotPage {
112
107
  url(): string;
113
108
  /** Refused before a byte leaves when the host is outside the session's `allowHosts`. */
@@ -142,7 +137,8 @@ export interface ShotSessionInit {
142
137
  readonly name: string;
143
138
  /** Never `*` from a shot: a headless browser inside your network is an SSRF surface. */
144
139
  readonly rules: { readonly allowHosts: readonly string[] };
145
- readonly clock: ShotClock;
140
+ /** Every wait goes through it, so a test of a 30-second deadline finishes in microseconds. */
141
+ readonly clock: SleepClock;
146
142
  /** Per-operation default, in ms. */
147
143
  readonly timeoutMs: number;
148
144
  /** CSS pixels the page is laid out in. Absent: the driver's own default. */
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { existsSync } from 'node:fs';
8
8
  import { UltimateError } from '@ultimat3/core';
9
- import { CHROME_CANDIDATES } from '@ultimat3/testing';
9
+ import { CHROME_CANDIDATES } from '@ultimat3/scraping/cdp';
10
10
  import type { ShotDriver } from './browser-launcher-port';
11
11
  import { cdpShotDriver } from './cdp-shot-driver';
12
12
 
@@ -34,6 +34,14 @@ export const carriesJson = (attrs: string): boolean => {
34
34
  */
35
35
  export const ENTRY_ATTR = /\sdata-x-entry="(?<url>[^"]*)"/g;
36
36
 
37
+ /**
38
+ * `<link rel="modulepreload" href>` — what `route-islands-preload.ts` emits. A preload is a fetch
39
+ * the browser makes whether or not an island imports the file, so it is weighed like a `src`.
40
+ * Only `modulepreload`: a stylesheet or a plain `preload` link names no module to execute.
41
+ */
42
+ export const MODULEPRELOAD_TAG = /<link\s[^>]*\brel="modulepreload"[^>]*>/g;
43
+ export const HREF_ATTR = /\shref="(?<href>[^"]*)"/;
44
+
37
45
  /**
38
46
  * Static imports and `import()` both. A chunk reached by `import()` was INLINED into its island
39
47
  * before islands were split, so charging it keeps a route's number what it was; and it is fetched
package/src/budgets.ts CHANGED
@@ -17,7 +17,9 @@ import {
17
17
  artifactPath,
18
18
  carriesJson,
19
19
  ENTRY_ATTR,
20
+ HREF_ATTR,
20
21
  loadedBy,
22
+ MODULEPRELOAD_TAG,
21
23
  SCRIPT_TAG,
22
24
  SRC_ATTR,
23
25
  } from './budgets-scan';
@@ -79,8 +81,9 @@ export interface BuildStats {
79
81
  * `5`: a URL is weighed at the path a browser resolves it to (`\` is `/`, `//host` is another
80
82
  * origin), so two spellings of one fetch are charged once; and an app/ page is weighed as SERVED
81
83
  * — its page boot charged, the runtime chunk that boot makes unfetched not (plan 101 sweep 9).
84
+ * `6`: a `<link rel="modulepreload">` is a fetch and is charged, deduped with every other (B4).
82
85
  */
83
- export const BUILD_STATS_RULES = 5;
86
+ export const BUILD_STATS_RULES = 6;
84
87
 
85
88
  const chainOf = (stats: RouteStats): string =>
86
89
  stats.heaviestChain === undefined ? 'unknown import chain' : stats.heaviestChain.join(' -> ');
@@ -413,6 +416,12 @@ export async function measureDocumentJs(
413
416
  if (url === undefined) continue;
414
417
  await weigh(url);
415
418
  }
419
+ // Charged even when the boot supplies it: the boot rule says an island never FETCHES the runtime
420
+ // chunk, and a preload of it is a fetch. What the preloaded file loads follows the rule in `weigh`.
421
+ for (const match of html.matchAll(MODULEPRELOAD_TAG)) {
422
+ const href = HREF_ATTR.exec(match[0])?.groups?.['href'];
423
+ if (href !== undefined) await weigh(href);
424
+ }
416
425
  return { jsBytes, frameworkBytes, inlineBytes, entries };
417
426
  }
418
427
 
@@ -0,0 +1,59 @@
1
+ // Which of the app's modules a background role (`worker`, `scheduler`) imports, decided at image
2
+ // build time for the prebuilt registry: the same rule `scanBackground` applies module by module at
3
+ // boot (`role-load.ts`), with what the process has "already loaded" simulated from the static
4
+ // import graph instead of read from Bun's module cache — so the boot imports a list, not a walk.
5
+
6
+ // why: Bun ships no path API; the API index is named app-root-relative and compared absolute.
7
+ import { resolve } from 'node:path';
8
+ import { API_INDEX } from './app-root';
9
+ import { createDocumentGraph } from './document-graph';
10
+ import { resolvedImports } from './module-imports';
11
+ import { hasPathSegment } from './path-segments';
12
+
13
+ /** An installed framework package — walked, as the document graph walks it. */
14
+ const FRAMEWORK_SCOPE = '/node_modules/@ultimat3/';
15
+
16
+ /** The files evaluating `path` evaluates, by the document graph's own rule for what it follows. */
17
+ async function evaluatedImports(path: string): Promise<readonly string[]> {
18
+ const source = await Bun.file(path)
19
+ .text()
20
+ .catch(() => '');
21
+ return resolvedImports(path, source, 'evaluated').filter(
22
+ (target) => !hasPathSegment(target, 'node_modules') || target.includes(FRAMEWORK_SCOPE),
23
+ );
24
+ }
25
+
26
+ /**
27
+ * The subset of `modules` (absolute, scan order) a background role imports, in the same order:
28
+ * the API index, every module an earlier imported one already evaluated, and every module that
29
+ * reaches no document. "Already evaluated" is the static closure of what was imported before it —
30
+ * the runtime answer differs only by a top-level `await import()`, which makes the runtime import
31
+ * MORE; a job that leaves out is answered at boot by the manifest check (`X_ROLE_LOAD_INCOMPLETE`).
32
+ */
33
+ export async function backgroundModules(
34
+ root: string,
35
+ modules: readonly string[],
36
+ ): Promise<readonly string[]> {
37
+ const index = resolve(root, API_INDEX);
38
+ const evaluated = new Set<string>();
39
+ const graph = createDocumentGraph((absolute) => evaluated.has(absolute));
40
+ const evaluate = async (start: string): Promise<void> => {
41
+ const stack = [start];
42
+ while (stack.length > 0) {
43
+ const path = stack.pop();
44
+ if (path === undefined || evaluated.has(path)) continue;
45
+ evaluated.add(path);
46
+ stack.push(...(await evaluatedImports(path)));
47
+ }
48
+ };
49
+ const included: string[] = [];
50
+ for (const absolute of modules) {
51
+ // `evaluated.has` first only skips a walk: the graph's own oracle answers it the same way.
52
+ const take =
53
+ absolute === index || evaluated.has(absolute) || !(await graph.reachesDocument(absolute));
54
+ if (!take) continue;
55
+ included.push(absolute);
56
+ await evaluate(absolute);
57
+ }
58
+ return included;
59
+ }