@ultimat3/cli 31.26.0 → 31.28.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 (206) hide show
  1. package/CLAUDE.md +47 -37
  2. package/README.md +19 -8
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-mcp.ts +17 -3
  6. package/src/cmd-cache-spec.ts +5 -2
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +15 -4
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-repro-spec.ts +13 -1
  26. package/src/cmd-repro.ts +37 -5
  27. package/src/cmd-status-sample.ts +57 -0
  28. package/src/cmd-status-spec.ts +30 -0
  29. package/src/cmd-status.ts +108 -0
  30. package/src/cmd-token-spec.ts +5 -2
  31. package/src/cmd-token.ts +7 -3
  32. package/src/cmd-upgrade-codemods.ts +71 -0
  33. package/src/cmd-upgrade-spec.ts +19 -5
  34. package/src/cmd-upgrade.ts +91 -34
  35. package/src/codemods/agents-dev-mcp.ts +50 -0
  36. package/src/codemods/authenticator-session-refusal.ts +214 -0
  37. package/src/codemods/biome-no-default-export.ts +58 -0
  38. package/src/codemods/bunfig-island-coverage.ts +33 -0
  39. package/src/codemods/chart-dashboard.ts +73 -0
  40. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  41. package/src/codemods/ci-e2e-browser.ts +63 -0
  42. package/src/codemods/codemod.ts +58 -0
  43. package/src/codemods/define-error-leaf.ts +73 -0
  44. package/src/codemods/docs-ci-parts.ts +65 -0
  45. package/src/codemods/docs-gate-prose.ts +53 -0
  46. package/src/codemods/docs-island-rows.ts +31 -0
  47. package/src/codemods/docs-shipped-guards.ts +100 -0
  48. package/src/codemods/docs-test-services.ts +62 -0
  49. package/src/codemods/engine-diff.ts +104 -0
  50. package/src/codemods/engine-edits.ts +111 -0
  51. package/src/codemods/engine-fs.ts +95 -0
  52. package/src/codemods/engine.ts +191 -0
  53. package/src/codemods/format-edited-hook-3122.ts +28 -0
  54. package/src/codemods/format-edited-hook.ts +152 -0
  55. package/src/codemods/helm-alerts-objective.ts +105 -0
  56. package/src/codemods/helm-alerts-stock.ts +108 -0
  57. package/src/codemods/index.ts +56 -0
  58. package/src/codemods/metrics-probe-healthz.ts +47 -0
  59. package/src/codemods/pending.ts +36 -0
  60. package/src/codemods/repro-gitignore.ts +40 -0
  61. package/src/codemods/runtime-pin-lines.ts +109 -0
  62. package/src/codemods/runtime-pin.ts +116 -0
  63. package/src/codemods/solid-floor.ts +63 -0
  64. package/src/codemods/test-ports.ts +86 -0
  65. package/src/codemods/test-suites.ts +37 -0
  66. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  67. package/src/codemods/vendored-guards.ts +186 -0
  68. package/src/codemods/verify-floor-skips.ts +88 -0
  69. package/src/codemods/verify-floor-steps.ts +90 -0
  70. package/src/coverage-island.ts +121 -0
  71. package/src/coverage-lcov.ts +49 -5
  72. package/src/coverage-remap.ts +146 -0
  73. package/src/db-replay-engine-prepared.ts +66 -0
  74. package/src/db-replay-engine-template.ts +156 -0
  75. package/src/db-replay-engine.ts +4 -0
  76. package/src/db-replay-scratch-reap.ts +54 -0
  77. package/src/deploy-verify-flags.ts +9 -2
  78. package/src/deploy-verify-grade.ts +10 -3
  79. package/src/dev-boot.ts +14 -1
  80. package/src/dev-dashboard-guard.ts +57 -10
  81. package/src/dev-host.ts +46 -0
  82. package/src/dev-tls-cache.ts +103 -0
  83. package/src/dev-tls-der.ts +69 -0
  84. package/src/dev-tls.ts +120 -0
  85. package/src/doctor-advisory-floors.ts +113 -0
  86. package/src/doctor-browser.ts +60 -0
  87. package/src/doctor-guards.ts +39 -86
  88. package/src/doctor-superseded.ts +67 -0
  89. package/src/error-codes-doctor.ts +12 -4
  90. package/src/error-codes-verify.ts +47 -0
  91. package/src/error-codes.ts +20 -23
  92. package/src/exercise-database.ts +47 -9
  93. package/src/exercise-push-device.ts +51 -0
  94. package/src/exercise-route-api.ts +74 -0
  95. package/src/exercise-routes.ts +14 -5
  96. package/src/exercise-services.ts +3 -1
  97. package/src/exercise-shard-flag.ts +47 -0
  98. package/src/fix-command.ts +2 -2
  99. package/src/generate-factories.ts +5 -11
  100. package/src/generate-feature-required.ts +9 -4
  101. package/src/generate-files.ts +26 -7
  102. package/src/generate-kinds.ts +5 -1
  103. package/src/guards-built-in-codes.ts +36 -0
  104. package/src/guards-built-in-refusal.ts +25 -0
  105. package/src/guards-built-in.ts +134 -0
  106. package/src/guards-materialize.ts +42 -0
  107. package/src/guards-paths.ts +37 -0
  108. package/src/guards-shipped-names.ts +38 -0
  109. package/src/guards-vendored.ts +73 -0
  110. package/src/guards.ts +105 -34
  111. package/src/index.ts +10 -0
  112. package/src/island-bundle-options.ts +48 -0
  113. package/src/island-bundle.ts +18 -46
  114. package/src/island-link.ts +5 -0
  115. package/src/island-outputs.ts +5 -0
  116. package/src/lint-findings.ts +3 -3
  117. package/src/mcp-errors-verify.ts +35 -0
  118. package/src/mcp-errors.ts +21 -20
  119. package/src/mcp-host-logs.ts +121 -0
  120. package/src/mcp-host.ts +12 -73
  121. package/src/measure-scope.ts +23 -3
  122. package/src/messages-floor.ts +19 -0
  123. package/src/messages-repro.ts +16 -2
  124. package/src/messages-status.ts +10 -0
  125. package/src/messages-upgrade.ts +15 -0
  126. package/src/messages.ts +22 -1
  127. package/src/registry.ts +4 -0
  128. package/src/repro-archive-collect.ts +161 -0
  129. package/src/repro-archive-write.ts +96 -0
  130. package/src/repro-archive.ts +161 -0
  131. package/src/repro-bundle.ts +8 -16
  132. package/src/repro-errors.ts +14 -2
  133. package/src/repro-framework.ts +53 -0
  134. package/src/repro-parse.ts +87 -0
  135. package/src/repro-redact.ts +218 -0
  136. package/src/repro-scrub.ts +257 -0
  137. package/src/role-start-types.ts +7 -0
  138. package/src/role-start.ts +4 -0
  139. package/src/serve-boot.ts +7 -1
  140. package/src/serve-env-tls.ts +57 -0
  141. package/src/solid-loader.ts +27 -10
  142. package/src/superseded-match.ts +87 -0
  143. package/src/superseded.ts +84 -0
  144. package/src/templates/bun-image.ts +48 -0
  145. package/src/templates/generate-export-rows.ts +136 -0
  146. package/src/templates/generate-import-rows.ts +186 -0
  147. package/src/templates/generate-rows-slice.ts +95 -0
  148. package/src/templates/github/ci.yml.ts +5 -1
  149. package/src/templates/guard-released-forms.ts +112 -0
  150. package/src/templates/guard-runtime-pin-test.ts +54 -0
  151. package/src/templates/guard-runtime-pin.ts +189 -0
  152. package/src/templates/scaffold-claude-agents.ts +6 -6
  153. package/src/templates/scaffold-claude-commands.ts +1 -1
  154. package/src/templates/scaffold-claude-hook.ts +18 -8
  155. package/src/templates/scaffold-claude.ts +2 -2
  156. package/src/templates/scaffold-db-package.ts +3 -0
  157. package/src/templates/scaffold-docs.ts +34 -30
  158. package/src/templates/scaffold-guards.ts +73 -39
  159. package/src/templates/scaffold-repo.ts +4 -8
  160. package/src/templates/scaffold-site.ts +4 -1
  161. package/src/templates/scaffold-suites.ts +72 -0
  162. package/src/templates/scaffold-test-services.ts +35 -10
  163. package/src/templates/scaffold-verify-floor.ts +53 -31
  164. package/src/templates/shapes/api.ts +4 -0
  165. package/src/templates/slice-foundation.ts +3 -3
  166. package/src/unthrown-codes.ts +3 -1
  167. package/src/upgrade-bun-floor.ts +4 -0
  168. package/src/upgrade-clean-tree.ts +54 -0
  169. package/src/upgrade-gate-codemods-install.ts +40 -0
  170. package/src/upgrade-gate-codemods.ts +151 -0
  171. package/src/upgrade-gate.ts +44 -7
  172. package/src/upgrade-guards-baseline.ts +43 -0
  173. package/src/upgrade-guards.ts +37 -2
  174. package/src/upgrade-lock.ts +118 -0
  175. package/src/upgrade-plan.ts +2 -1
  176. package/src/upgrade-report-codemods.ts +54 -0
  177. package/src/upgrade-report.ts +55 -27
  178. package/src/upgrade-signals.ts +91 -0
  179. package/src/upgrade-unfinished.ts +61 -0
  180. package/src/verify-coverage-run.ts +42 -11
  181. package/src/verify-e2e.ts +115 -4
  182. package/src/verify-floor.ts +27 -0
  183. package/src/verify-guard-baseline.ts +109 -0
  184. package/src/verify-live.ts +72 -0
  185. package/src/verify-merge-skips.ts +51 -0
  186. package/src/verify-merge.ts +36 -2
  187. package/src/verify-run.ts +48 -7
  188. package/src/verify-services.ts +287 -0
  189. package/src/verify-skip-reason.ts +53 -0
  190. package/src/verify-strict.ts +108 -0
  191. package/src/verify-test-command.ts +129 -0
  192. package/src/verify-tests.ts +39 -126
  193. package/types/babel-modules.d.ts +2 -0
  194. package/wiki/CLI-Reference.md +200 -27
  195. package/wiki/Caching-And-Invalidation.md +1 -1
  196. package/wiki/Entities-And-Migrations.md +1 -1
  197. package/wiki/Interface-Rules.md +17 -8
  198. package/wiki/Jobs-And-Workflows.md +3 -3
  199. package/wiki/Known-Gaps.md +5 -1
  200. package/wiki/MCP-And-AI.md +1 -1
  201. package/wiki/Observability.md +1 -0
  202. package/wiki/PWA-And-Offline.md +1 -1
  203. package/wiki/Project-Layout.md +4 -4
  204. package/wiki/Troubleshooting.md +3 -3
  205. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  206. package/wiki/Upgrading.md +8 -0
@@ -0,0 +1,88 @@
1
+ // 31.27.0: a scaffold's x.verify.json names every gate step — required in `steps`, or excused in
2
+ // `skip` with its why — and sets `strict`. An older app gains the `skip` rows that hold for it
3
+ // (roadmap; job with no job suite; e2e with no page). `strict` is 31.28.0's (`verify-floor-steps`).
4
+
5
+ import { floorSteps } from '../templates/scaffold-verify-floor';
6
+ import { VERIFY_FLOOR_FILE } from '../verify-floor';
7
+ import type { Codemod, CodemodApp } from './codemod';
8
+
9
+ export type Floor = Record<string, unknown>;
10
+
11
+ export const isObject = (value: unknown): value is Floor =>
12
+ typeof value === 'object' && value !== null && !Array.isArray(value);
13
+
14
+ const any = async (app: CodemodApp, pattern: string): Promise<boolean> =>
15
+ (await app.glob(pattern)).length > 0;
16
+
17
+ /** What the app ships suites for, as `floorSteps` asks it: a job suite, a page to load. */
18
+ export async function floorSuites(
19
+ app: CodemodApp,
20
+ ): Promise<{ readonly jobs: boolean; readonly pages: boolean }> {
21
+ return {
22
+ jobs: await any(app, '{apps,packages}/**/*.job.test.ts'),
23
+ pages: await any(app, 'apps/*/{site,app}/**/page.tsx'),
24
+ };
25
+ }
26
+
27
+ /** The steps that cannot run in this app, each with the scaffold's own why. */
28
+ async function excused(app: CodemodApp): Promise<Readonly<Record<string, string>>> {
29
+ const { jobs, pages } = await floorSuites(app);
30
+ const why = floorSteps({ jobs: false, pages: false }).skip;
31
+ const out: Record<string, string> = {};
32
+ if (!jobs && why.job !== undefined) out['job'] = why.job;
33
+ if (!pages && why.e2e !== undefined) out['e2e'] = why.e2e;
34
+ if (!(await app.exists('docs/idea/14-roadmap.md')) && why.roadmap !== undefined) {
35
+ out['roadmap'] = why.roadmap;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /** `floor` with `skip` merged in, placed right after `steps` as the scaffold writes it. */
41
+ function withSkip(floor: Floor, skip: Readonly<Record<string, string>>): Floor {
42
+ const merged = { ...(isObject(floor['skip']) ? floor['skip'] : {}), ...skip };
43
+ const out: Floor = {};
44
+ for (const [key, value] of Object.entries(floor)) {
45
+ if (key === 'skip') continue;
46
+ out[key] = value;
47
+ if (key === 'steps') out['skip'] = merged;
48
+ }
49
+ if (!('skip' in out)) out['skip'] = merged;
50
+ return out;
51
+ }
52
+
53
+ export const renderFloor = (floor: Floor): string => `${JSON.stringify(floor, null, 2)}\n`;
54
+
55
+ export const codemod: Codemod = {
56
+ id: 'verify-floor-skips',
57
+ since: '31.27.0',
58
+ summary: `${VERIFY_FLOOR_FILE} excuses the gate steps this app cannot run (roadmap; job, e2e where it has none), each with its why`,
59
+ async run(app) {
60
+ const source = await app.read(VERIFY_FLOOR_FILE);
61
+ if (source === undefined) return { changed: [], skipped: [] };
62
+ let floor: unknown;
63
+ try {
64
+ floor = JSON.parse(source);
65
+ } catch {
66
+ floor = undefined;
67
+ }
68
+ if (!isObject(floor)) {
69
+ return {
70
+ changed: [],
71
+ skipped: [
72
+ { path: VERIFY_FLOOR_FILE, reason: 'it is not a JSON object, so no row was added to it' },
73
+ ],
74
+ };
75
+ }
76
+ const steps = Array.isArray(floor['steps']) ? floor['steps'] : [];
77
+ const held = isObject(floor['skip']) ? floor['skip'] : {};
78
+ const add = Object.fromEntries(
79
+ Object.entries(await excused(app)).filter(
80
+ ([step]) => !steps.includes(step) && !(step in held),
81
+ ),
82
+ );
83
+ const next = Object.keys(add).length === 0 ? floor : withSkip(floor, add);
84
+ if (Object.keys(add).length === 0) return { changed: [], skipped: [] };
85
+ await app.write(VERIFY_FLOOR_FILE, renderFloor(next));
86
+ return { changed: [VERIFY_FLOOR_FILE], skipped: [] };
87
+ },
88
+ };
@@ -0,0 +1,90 @@
1
+ // 31.28.0: x.verify.json floors every step the scaffold floors for an app like this one (the list
2
+ // is `floorSteps`, never restated here), so none is `X_VERIFY_STEP_UNFLOORED`; and once the floor
3
+ // names every gate step — required or excused — `strict` goes on. Short of that, `strict: false`
4
+ // is written once with a note: a decision recorded, not a question asked on every upgrade.
5
+
6
+ import { floorSteps } from '../templates/scaffold-verify-floor';
7
+ import { VERIFY_FLOOR_FILE } from '../verify-floor';
8
+ import { VERIFY_STEP_NAMES } from '../verify-step';
9
+ import type { Codemod, CodemodResult } from './codemod';
10
+ import { unifiedDiff } from './engine-diff';
11
+ import type { Floor } from './verify-floor-skips';
12
+ import { floorSuites, isObject, renderFloor } from './verify-floor-skips';
13
+
14
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
15
+
16
+ /** The scaffold's order for every step it floors, then the app's own steps in theirs. */
17
+ const ordered = (
18
+ held: readonly unknown[],
19
+ wanted: readonly string[],
20
+ added: readonly string[],
21
+ ): readonly unknown[] => [
22
+ ...wanted.filter((step) => held.includes(step) || added.includes(step)),
23
+ ...held.filter((step) => typeof step !== 'string' || !wanted.includes(step)),
24
+ ];
25
+
26
+ /** `floor` with `strict` set, placed after `skip` (or `steps`) as the scaffold writes it. */
27
+ function withStrict(floor: Floor, strict: boolean): Floor {
28
+ const anchor = 'skip' in floor ? 'skip' : 'steps';
29
+ const out: Floor = {};
30
+ for (const [key, value] of Object.entries(floor)) {
31
+ if (key === 'strict') continue;
32
+ out[key] = value;
33
+ if (key === anchor) out['strict'] = strict;
34
+ }
35
+ if (!('strict' in out)) out['strict'] = strict;
36
+ return out;
37
+ }
38
+
39
+ export const codemod: Codemod = {
40
+ id: 'verify-floor-steps',
41
+ since: '31.28.0',
42
+ summary: `${VERIFY_FLOOR_FILE} floors every step the scaffold floors, and is strict once it names the whole gate`,
43
+ async run(app) {
44
+ const source = await app.read(VERIFY_FLOOR_FILE);
45
+ if (source === undefined) return NOTHING;
46
+ let floor: unknown;
47
+ try {
48
+ floor = JSON.parse(source);
49
+ } catch {
50
+ return NOTHING;
51
+ }
52
+ // `verify-floor-skips` already reports a floor that is not a JSON object.
53
+ if (!isObject(floor) || !Array.isArray(floor['steps'])) return NOTHING;
54
+ const held: unknown[] = floor['steps'];
55
+ const skip = isObject(floor['skip']) ? floor['skip'] : {};
56
+ const wanted = floorSteps(await floorSuites(app)).steps;
57
+ const added = wanted.filter((step) => !held.includes(step) && !(step in skip));
58
+ // `steps` replaced where it stands: the app's key order kept.
59
+ let next: Floor =
60
+ added.length === 0
61
+ ? floor
62
+ : Object.fromEntries(
63
+ Object.entries(floor).map(([key, value]) => [
64
+ key,
65
+ key === 'steps' ? ordered(held, wanted, added) : value,
66
+ ]),
67
+ );
68
+ const skipped: CodemodResult['skipped'][number][] = [];
69
+ if (next['strict'] === undefined) {
70
+ const named = new Set([...(next['steps'] as unknown[]), ...Object.keys(skip)]);
71
+ const unnamed = VERIFY_STEP_NAMES.filter((step) => !named.has(step));
72
+ next = withStrict(next, unnamed.length === 0);
73
+ if (unnamed.length > 0) {
74
+ skipped.push({
75
+ path: VERIFY_FLOOR_FILE,
76
+ reason: `"strict": false recorded, once: ${unnamed.join(', ')} is in neither "steps" nor "skip", so strict would be red where those run nothing. Run x verify --json, give each its place, then set "strict": true`,
77
+ diff: unifiedDiff(
78
+ VERIFY_FLOOR_FILE,
79
+ renderFloor(next),
80
+ renderFloor(withStrict(next, true)),
81
+ ),
82
+ });
83
+ }
84
+ }
85
+ const text = renderFloor(next);
86
+ if (text === source) return { changed: [], skipped };
87
+ await app.write(VERIFY_FLOOR_FILE, text);
88
+ return { changed: [VERIFY_FLOOR_FILE], skipped };
89
+ },
90
+ };
@@ -0,0 +1,121 @@
1
+ // One coverage slice's island chunks, folded into its per-file facts: the source maps `mountIsland`
2
+ // recorded under `ISLAND_COVERAGE_ENV`, read, and each chunk's lcov record credited back to the
3
+ // app sources it was built from (`coverage-remap.ts`).
4
+
5
+ // why: Bun ships no directory-exists probe (`Bun.file` answers files only).
6
+ import { existsSync } from 'node:fs';
7
+ // why: Bun ships no path API; `posix` names a module, `resolve` places a map's sources.
8
+ import { join, posix, resolve, sep } from 'node:path';
9
+ import type { CoverageMap, FileCoverage, LcovRecord } from './coverage-lcov';
10
+ import type { ChunkLines, ChunkMap } from './coverage-remap';
11
+ import { chunkLines, withChunkLines } from './coverage-remap';
12
+ import { readSource } from './coverage-source';
13
+ import { posixRelative } from './posix-path';
14
+
15
+ /** The subdirectory of a slice's coverage directory its island maps land in. */
16
+ export const ISLAND_MAPS_DIR = 'islands';
17
+
18
+ const strings = (value: unknown): readonly string[] | undefined =>
19
+ Array.isArray(value) && value.every((one) => typeof one === 'string') ? value : undefined;
20
+
21
+ /**
22
+ * One sidecar `{ module, cwd, map }` as a `ChunkMap`, or nothing when it is not one — a map the
23
+ * builder handed over malformed credits no line, so the floor reads LOWER, never higher.
24
+ */
25
+ export function parseChunkMap(text: string): ChunkMap | undefined {
26
+ let outer: unknown;
27
+ let map: unknown;
28
+ try {
29
+ outer = JSON.parse(text);
30
+ const raw = (outer as Record<string, unknown> | null)?.['map'];
31
+ map = typeof raw === 'string' ? JSON.parse(raw) : undefined;
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ const { module, cwd } = (outer ?? {}) as { module?: unknown; cwd?: unknown };
36
+ const { sources, sourcesContent, mappings } = (map ?? {}) as Record<string, unknown>;
37
+ const listed = strings(sources);
38
+ if (typeof module !== 'string' || typeof cwd !== 'string' || typeof mappings !== 'string') {
39
+ return undefined;
40
+ }
41
+ if (listed === undefined || !Array.isArray(sourcesContent)) return undefined;
42
+ return {
43
+ module,
44
+ // Bun writes each source relative to the BUILDING process's cwd (`island-sources.ts`).
45
+ sources: listed.map((one) => resolve(cwd, one).split(sep).join('/')),
46
+ sourcesContent: sourcesContent.map((one: unknown) =>
47
+ typeof one === 'string' ? one : undefined,
48
+ ),
49
+ mappings,
50
+ };
51
+ }
52
+
53
+ /** Every map one slice recorded, by the module name its `SF:` line ends in. */
54
+ export async function readChunkMaps(dir: string): Promise<ReadonlyMap<string, ChunkMap>> {
55
+ const out = new Map<string, ChunkMap>();
56
+ const at = join(dir, ISLAND_MAPS_DIR);
57
+ // Absent: the slice mounted no island with a map, so there is nothing to fold.
58
+ if (!existsSync(at)) return out;
59
+ for await (const name of new Bun.Glob('*.json').scan({ cwd: at })) {
60
+ const parsed = parseChunkMap(await Bun.file(join(at, name)).text());
61
+ if (parsed !== undefined) out.set(parsed.module, parsed);
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /** The app's coverage key for an absolute path, when it is the app's own source. */
67
+ const appKey =
68
+ (root: string) =>
69
+ (absolute: string): string | undefined => {
70
+ const key = posixRelative(root, absolute);
71
+ return /^(?:apps|packages)\//.test(key) && !key.includes('/node_modules/') ? key : undefined;
72
+ };
73
+
74
+ /** One slice's lcov records and the island maps it recorded. */
75
+ export interface ChunkPart {
76
+ readonly records: readonly LcovRecord[];
77
+ readonly maps: ReadonlyMap<string, ChunkMap>;
78
+ }
79
+
80
+ /**
81
+ * `merged` — every slice's direct records already folded — with every chunk record that has a map
82
+ * credited to the sources behind it. After the fold, never per slice: a source one slice only
83
+ * mounted and another loaded directly then has the direct line set, rather than two line sets
84
+ * the fold would reconcile by dropping the misses one of them did not list. A record whose module
85
+ * has no map is left alone — a framework file or an island built without one.
86
+ */
87
+ export async function withIslandChunks(
88
+ root: string,
89
+ merged: CoverageMap,
90
+ parts: readonly ChunkPart[],
91
+ ): Promise<CoverageMap> {
92
+ if (parts.every((part) => part.maps.size === 0)) return merged;
93
+ const texts = new Map<string, string | undefined>();
94
+ const credited = new Map<string, { hit: Set<number>; miss: Set<number> }>();
95
+ for (const { records, maps } of parts)
96
+ for (const record of records) {
97
+ const map = maps.get(posix.basename(record.file));
98
+ if (map === undefined) continue;
99
+ for (const source of map.sources) {
100
+ const key = appKey(root)(source);
101
+ if (key !== undefined && !texts.has(key)) texts.set(key, await readSource(root, key));
102
+ }
103
+ for (const [key, lines] of chunkLines(record, map, appKey(root), (k) => texts.get(k))) {
104
+ const into = credited.get(key) ?? { hit: new Set<number>(), miss: new Set<number>() };
105
+ for (const line of lines.hit) into.hit.add(line);
106
+ for (const line of lines.miss) into.miss.add(line);
107
+ credited.set(key, into);
108
+ }
109
+ }
110
+ const out: Record<string, FileCoverage> = { ...merged };
111
+ for (const [key, lines] of credited) {
112
+ const source = texts.get(key);
113
+ if (source === undefined) continue;
114
+ const settled: ChunkLines = {
115
+ hit: lines.hit,
116
+ miss: new Set([...lines.miss].filter((line) => !lines.hit.has(line))),
117
+ };
118
+ out[key] = withChunkLines(merged[key], settled);
119
+ }
120
+ return out;
121
+ }
@@ -65,6 +65,12 @@ export interface FileCoverage {
65
65
  readonly miss: readonly number[];
66
66
  readonly funcsFound: number;
67
67
  readonly funcsHit: number;
68
+ /**
69
+ * Reached only through an island's built chunk (`coverage-remap.ts`): its lines are the ones the
70
+ * chunk's map names, not Bun's line set for the source. Folded under a direct record, never
71
+ * beside it (`mergeFileCoverage`).
72
+ */
73
+ readonly chunkOnly?: true;
68
74
  }
69
75
 
70
76
  export const fileCoverageOf = (record: LcovRecord): FileCoverage => {
@@ -93,6 +99,21 @@ export const fileCoverageOf = (record: LcovRecord): FileCoverage => {
93
99
  */
94
100
  export function mergeFileCoverage(parts: readonly FileCoverage[]): FileCoverage {
95
101
  if (parts.length === 1) return parts[0] as FileCoverage;
102
+ // A chunk-only part names a smaller line set, so beside a direct record it would drop every
103
+ // miss the direct one lists outside it. The direct line set wins, as in one run: the chunk only
104
+ // turns its misses into hits. Only when NO part loaded the file are chunk parts folded alone.
105
+ const direct = parts.filter((part) => part.chunkOnly !== true);
106
+ if (direct.length > 0 && direct.length < parts.length) {
107
+ const base = mergeFileCoverage(direct);
108
+ const ran = new Set(parts.flatMap((part) => (part.chunkOnly === true ? part.hit : [])));
109
+ const turned = base.miss.filter((line) => ran.has(line));
110
+ if (turned.length === 0) return base;
111
+ return {
112
+ ...base,
113
+ hit: [...base.hit, ...turned].sort((a, b) => a - b),
114
+ miss: base.miss.filter((line) => !ran.has(line)),
115
+ };
116
+ }
96
117
  const hit = new Set<number>();
97
118
  for (const part of parts) for (const line of part.hit) hit.add(line);
98
119
  const missIn = parts.map((part) => new Set(part.miss));
@@ -104,6 +125,7 @@ export function mergeFileCoverage(parts: readonly FileCoverage[]): FileCoverage
104
125
  miss: miss.sort((a, b) => a - b),
105
126
  funcsFound: Math.max(0, ...parts.map((part) => part.funcsFound)),
106
127
  funcsHit: Math.max(0, ...parts.map((part) => part.funcsHit)),
128
+ ...(direct.length === 0 ? { chunkOnly: true as const } : {}),
107
129
  };
108
130
  }
109
131
 
@@ -166,16 +188,32 @@ export function decodeLines(text: string): readonly number[] {
166
188
  return lines;
167
189
  }
168
190
 
169
- /** A file's facts as they cross `--json`: hit runs, miss runs, `[funcsFound, funcsHit]`. */
191
+ /**
192
+ * A file's facts as they cross `--json`: hit runs, miss runs, `[funcsFound, funcsHit]`, and
193
+ * `c: 1` on a chunk-only record. Absent `c` is a direct record — every part written before it.
194
+ */
170
195
  export type CoverageWire = Readonly<
171
- Record<string, { readonly h: string; readonly m: string; readonly f: readonly [number, number] }>
196
+ Record<
197
+ string,
198
+ {
199
+ readonly h: string;
200
+ readonly m: string;
201
+ readonly f: readonly [number, number];
202
+ readonly c?: 1;
203
+ }
204
+ >
172
205
  >;
173
206
 
174
207
  export const encodeCoverage = (map: CoverageMap): CoverageWire =>
175
208
  Object.fromEntries(
176
209
  Object.entries(map).map(([file, one]) => [
177
210
  file,
178
- { h: encodeLines(one.hit), m: encodeLines(one.miss), f: [one.funcsFound, one.funcsHit] },
211
+ {
212
+ h: encodeLines(one.hit),
213
+ m: encodeLines(one.miss),
214
+ f: [one.funcsFound, one.funcsHit],
215
+ ...(one.chunkOnly === true ? { c: 1 as const } : {}),
216
+ },
179
217
  ]),
180
218
  );
181
219
 
@@ -185,11 +223,17 @@ export function decodeCoverage(value: unknown): CoverageMap | undefined {
185
223
  const out = new Map<string, FileCoverage>();
186
224
  for (const [file, raw] of Object.entries(value)) {
187
225
  if (typeof raw !== 'object' || raw === null) return undefined;
188
- const { h, m, f } = raw as { h?: unknown; m?: unknown; f?: unknown };
226
+ const { h, m, f, c } = raw as { h?: unknown; m?: unknown; f?: unknown; c?: unknown };
189
227
  if (typeof h !== 'string' || typeof m !== 'string' || !Array.isArray(f)) return undefined;
190
228
  const [found, hit] = f as unknown[];
191
229
  if (typeof found !== 'number' || typeof hit !== 'number') return undefined;
192
- out.set(file, { hit: decodeLines(h), miss: decodeLines(m), funcsFound: found, funcsHit: hit });
230
+ out.set(file, {
231
+ hit: decodeLines(h),
232
+ miss: decodeLines(m),
233
+ funcsFound: found,
234
+ funcsHit: hit,
235
+ ...(c === 1 ? { chunkOnly: true as const } : {}),
236
+ });
193
237
  }
194
238
  return Object.fromEntries(out);
195
239
  }
@@ -0,0 +1,146 @@
1
+ // An island chunk's lcov lines, credited back to the app sources it was built from through the
2
+ // chunk's own source map. Pure: the sidecar text, the record and the files on disk come in, and
3
+ // per-source line facts go out. `coverage-island.ts` does the reading.
4
+
5
+ import type { FileCoverage, LcovRecord } from './coverage-lcov';
6
+
7
+ /** One chunk's map as `mountIsland` recorded it: the build's cwd, its `sources` and their text. */
8
+ export interface ChunkMap {
9
+ /** The chunk's file name as the test process imported it — the basename of its `SF:` line. */
10
+ readonly module: string;
11
+ /** Every `sources` entry resolved to an absolute POSIX path (Bun writes them cwd-relative). */
12
+ readonly sources: readonly string[];
13
+ readonly sourcesContent: readonly (string | undefined)[];
14
+ readonly mappings: string;
15
+ }
16
+
17
+ const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
18
+
19
+ /** One segment's base64-VLQ fields, or nothing when a character is not base64. */
20
+ function vlqFields(segment: string): readonly number[] | undefined {
21
+ const fields: number[] = [];
22
+ let value = 0;
23
+ let shift = 0;
24
+ for (const ch of segment) {
25
+ const digit = BASE64.indexOf(ch);
26
+ if (digit === -1) return undefined;
27
+ value += (digit & 31) * 2 ** shift;
28
+ if ((digit & 32) === 0) {
29
+ fields.push(value % 2 === 1 ? -(value - 1) / 2 : value / 2);
30
+ value = 0;
31
+ shift = 0;
32
+ } else shift += 5;
33
+ }
34
+ return fields;
35
+ }
36
+
37
+ /**
38
+ * Generated line (0-based) → the source index and 0-based original line of its FIRST mapped
39
+ * segment. The first segment only: a generated line that folds several original lines ran at least
40
+ * where it starts, and crediting every line it folds is how a minified two-line chunk would claim
41
+ * the whole island. An undercount, never a claim.
42
+ *
43
+ * A segment that names exactly the position the one before it named is skipped: Bun maps a line's
44
+ * leading indent back to where the PREVIOUS statement ended (`AAAA`), so taking it credited every
45
+ * indented line to the line above it (measured, Bun 1.4.4).
46
+ */
47
+ export function firstSegments(
48
+ mappings: string,
49
+ ): readonly (readonly [number, number] | undefined)[] {
50
+ const out: (readonly [number, number] | undefined)[] = [];
51
+ let source = 0;
52
+ let line = 0;
53
+ let seen = false;
54
+ for (const generated of mappings.split(';')) {
55
+ let first: readonly [number, number] | undefined;
56
+ for (const segment of generated.split(',')) {
57
+ const fields = segment === '' ? undefined : vlqFields(segment);
58
+ if (fields === undefined || fields.length < 4) continue;
59
+ source += fields[1] as number;
60
+ line += fields[2] as number;
61
+ const carried = seen && fields[1] === 0 && fields[2] === 0 && fields[3] === 0;
62
+ seen = true;
63
+ if (!carried) first ??= [source, line];
64
+ }
65
+ out.push(first);
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** What one chunk says about one source: the 1-based lines it ran and the ones it did not. */
71
+ export interface ChunkLines {
72
+ readonly hit: ReadonlySet<number>;
73
+ readonly miss: ReadonlySet<number>;
74
+ }
75
+
76
+ /**
77
+ * The chunk's `DA:` lines as lines of the app's sources. `relativeOf` keys a source (absolute
78
+ * path) the way the app's coverage is keyed, or refuses it; `disk` is that file's text now.
79
+ *
80
+ * A line is credited only when the text the chunk was built from holds, at that line number, the
81
+ * same non-blank text the file holds on disk. A plugin that rewrote the file (Babel's Solid
82
+ * transform without `retainLines`) moves every line, and a map then points at lines of code the
83
+ * file does not have there: those are dropped rather than credited to whatever sits at that number.
84
+ */
85
+ export function chunkLines(
86
+ record: LcovRecord,
87
+ map: ChunkMap,
88
+ relativeOf: (absolute: string) => string | undefined,
89
+ disk: (relative: string) => string | undefined,
90
+ ): ReadonlyMap<string, ChunkLines> {
91
+ const segments = firstSegments(map.mappings);
92
+ const keys = map.sources.map(relativeOf);
93
+ const built = map.sourcesContent.map((text) => text?.split('\n'));
94
+ const now = keys.map((key) => (key === undefined ? undefined : disk(key)?.split('\n')));
95
+ const out = new Map<string, { hit: Set<number>; miss: Set<number> }>();
96
+ for (const [generated, hits] of record.lines) {
97
+ const at = segments[generated - 1];
98
+ if (at === undefined) continue;
99
+ const [index, zeroLine] = at;
100
+ const key = keys[index];
101
+ const text = built[index]?.[zeroLine]?.trim();
102
+ if (key === undefined || text === undefined || text === '') continue;
103
+ if (now[index]?.[zeroLine]?.trim() !== text) continue;
104
+ const facts = out.get(key) ?? { hit: new Set<number>(), miss: new Set<number>() };
105
+ (hits > 0 ? facts.hit : facts.miss).add(zeroLine + 1);
106
+ out.set(key, facts);
107
+ }
108
+ for (const facts of out.values()) for (const line of facts.hit) facts.miss.delete(line);
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * A source's coverage once a chunk's lines are added to it.
114
+ *
115
+ * Loaded directly too (`base`): a line the direct record missed and the chunk ran becomes hit, and
116
+ * nothing else moves — the line set stays the one Bun counted, so the chunk can only turn misses
117
+ * into hits. Functions keep the direct record's counts: Bun's lcov names no function, so which of
118
+ * the chunk's functions belong to this file is unknowable, and the direct count is a lower bound.
119
+ *
120
+ * Not loaded directly anywhere: weighed by the lines the chunk MAPS — its executable lines, as Bun
121
+ * would have counted them had it loaded the source — hit where the chunk ran them. Never by text
122
+ * lines: an import, a type or a JSX line is no line a map can credit, so weighing them read a fully
123
+ * driven island at 9 of 36 lines (the scaffold's theme toggle). Functions are `0 / 0`, NOT the
124
+ * unloaded estimate: shards fold by taking the best function count any of them reached
125
+ * (`mergeFileCoverage`), so an estimate here beside a shard that loaded the file directly
126
+ * replaced its real denominator — measured on `examples/dummy`, functions fell 67.0% → 63.4%.
127
+ */
128
+ export function withChunkLines(base: FileCoverage | undefined, lines: ChunkLines): FileCoverage {
129
+ if (base !== undefined) {
130
+ const turned = base.miss.filter((line) => lines.hit.has(line));
131
+ if (turned.length === 0) return base;
132
+ return {
133
+ ...base,
134
+ hit: [...base.hit, ...turned].sort((a, b) => a - b),
135
+ miss: base.miss.filter((line) => !lines.hit.has(line)),
136
+ };
137
+ }
138
+ const byLine = (a: number, b: number): number => a - b;
139
+ return {
140
+ hit: [...lines.hit].sort(byLine),
141
+ miss: [...lines.miss].filter((line) => !lines.hit.has(line)).sort(byLine),
142
+ funcsFound: 0,
143
+ funcsHit: 0,
144
+ chunkOnly: true,
145
+ };
146
+ }
@@ -0,0 +1,66 @@
1
+ // A scratch database that starts PREPARED (framework tables and migrations applied) without paying
2
+ // for the preparation twice: on the embedded engine a data-directory snapshot keyed by what
3
+ // produced it (`@ultimat3/db`'s `dataSnapshot`), on Postgres a template database of that key cloned
4
+ // with `CREATE DATABASE … TEMPLATE`. The key IS the invalidation: a new migration is a new key.
5
+
6
+ // why: Bun ships no path joiner.
7
+ import { join } from 'node:path';
8
+ import type { DbClient } from '@ultimat3/db';
9
+ import { pgliteClient } from '@ultimat3/db';
10
+ import type { ReplayEngine } from './db-replay-engine';
11
+ import { withScratchDatabase } from './db-replay-engine';
12
+ import type { ScratchPreparation } from './db-replay-engine-template';
13
+ import { PREPARED_KEEP, withPreparedPostgres } from './db-replay-engine-template';
14
+
15
+ export type { ScratchPreparation } from './db-replay-engine-template';
16
+ export { PREPARED_KEEP, templateNameFor } from './db-replay-engine-template';
17
+
18
+ /** Where the embedded snapshots live: a directory of their own, under the app's state dir. */
19
+ export const preparedSnapshotDir = (stateDir: string): string => join(stateDir, 'cache', 'scratch');
20
+
21
+ async function withPreparedPglite<T>(
22
+ engine: Extract<ReplayEngine, { kind: 'embedded' }>,
23
+ stateDir: string,
24
+ preparation: ScratchPreparation,
25
+ work: (client: DbClient) => Promise<T>,
26
+ ): Promise<T> {
27
+ const client = pgliteClient({
28
+ extensions: engine.extensions,
29
+ snapshotDir: join(stateDir, 'cache'),
30
+ dataSnapshot: {
31
+ dir: preparedSnapshotDir(stateDir),
32
+ key: preparation.key,
33
+ keep: PREPARED_KEEP,
34
+ },
35
+ });
36
+ try {
37
+ if (!(await client.restoredDataSnapshot?.())) {
38
+ await preparation.prepare(client);
39
+ // After the preparation and before any row of the caller's: what is kept is the schema.
40
+ await client.saveDataSnapshot?.();
41
+ }
42
+ return await work(client);
43
+ } finally {
44
+ await client.close();
45
+ }
46
+ }
47
+
48
+ /**
49
+ * `work` on a scratch database `preparation` has been applied to — restored or cloned when its key
50
+ * was prepared before, prepared (and kept) when not. No `stateDir`, embedded: prepared every time.
51
+ */
52
+ export async function withPreparedScratch<T>(
53
+ engine: ReplayEngine,
54
+ stateDir: string | undefined,
55
+ preparation: ScratchPreparation,
56
+ work: (client: DbClient) => Promise<T>,
57
+ ): Promise<T> {
58
+ if (engine.kind === 'postgres') return withPreparedPostgres(engine.adminUrl, preparation, work);
59
+ if (stateDir === undefined) {
60
+ return withScratchDatabase(engine, stateDir, async (client) => {
61
+ await preparation.prepare(client);
62
+ return work(client);
63
+ });
64
+ }
65
+ return withPreparedPglite(engine, stateDir, preparation, work);
66
+ }