@canonical/summon 0.37.0 → 0.40.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.
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +16 -0
- package/dist/src/index.js.map +1 -0
- package/package.json +17 -12
- package/src/bin.tsx +238 -0
- package/src/completion.test.ts +202 -0
- package/src/completion.ts +492 -0
- package/src/components/App.askMissing.test.tsx +164 -0
- package/src/components/App.confirmGate.test.tsx +111 -0
- package/src/components/App.escBack.test.tsx +98 -0
- package/src/components/App.invalidAnswer.test.tsx +71 -0
- package/src/components/App.tsx +1305 -0
- package/src/components/ExecutionProgress.tsx +222 -0
- package/src/components/FileTreePreview.tsx +97 -0
- package/src/components/PromptSequence.tsx +558 -0
- package/src/components/Spinner.tsx +36 -0
- package/src/components/index.ts +16 -0
- package/src/components/undoPlan.test.ts +99 -0
- package/src/components/undoPlan.ts +70 -0
- package/src/discovery/index.ts +1 -0
- package/src/discovery/loadGenerator.ts +40 -0
- package/src/display/index.ts +2 -0
- package/src/display/printGeneratorHelp.ts +130 -0
- package/src/display/printNode.ts +76 -0
- package/src/index.ts +16 -0
- package/src/registration/buildCommandBarrel.test.ts +80 -0
- package/src/registration/buildCommandBarrel.ts +66 -0
- package/src/registration/conformance.subprocess.test.ts +192 -0
- package/src/registration/index.ts +2 -0
- package/src/registration/interaction.subprocess.test.ts +458 -0
- package/src/registration/registerFromBarrel.tsx +501 -0
- package/src/registration/resolveMode.test.ts +118 -0
- package/src/registration/resolveMode.ts +52 -0
- package/src/testing/globalSetup.test.ts +165 -0
- package/src/testing/globalSetup.ts +501 -0
- package/src/ui/index.tsx +31 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit pins for the gate's per-root build-or-destroy wrapper — the loop's
|
|
3
|
+
* one confirmed false-green producer (round 12), previously guarded by
|
|
4
|
+
* nothing: a dropped rmSync (restoring the false green) or a restored
|
|
5
|
+
* destroy-on-spawn-error (deleting a good dist the builder never touched)
|
|
6
|
+
* stayed invisible to every suite until a real CI build failed. Drives the
|
|
7
|
+
* EXPORTED wrapper in a tmpdir with an injected runner — no real builds,
|
|
8
|
+
* no subprocesses. TWIN: cli/pragma's perf globalSetup.test.ts pins the
|
|
9
|
+
* sibling copy the same way.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
existsSync,
|
|
14
|
+
mkdirSync,
|
|
15
|
+
mkdtempSync,
|
|
16
|
+
readFileSync,
|
|
17
|
+
rmSync,
|
|
18
|
+
statSync,
|
|
19
|
+
utimesSync,
|
|
20
|
+
writeFileSync,
|
|
21
|
+
} from "node:fs";
|
|
22
|
+
import { tmpdir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
25
|
+
import { buildDistOrDestroy, TEMPLATE_COPIER } from "./globalSetup.js";
|
|
26
|
+
|
|
27
|
+
describe("buildDistOrDestroy — the per-root build-or-destroy wrapper", () => {
|
|
28
|
+
let root: string;
|
|
29
|
+
let artifact: string;
|
|
30
|
+
// The wrapper judges freshness only UNDER the lock; always-stale makes
|
|
31
|
+
// every cell take the build path.
|
|
32
|
+
const stale = (): boolean => false;
|
|
33
|
+
|
|
34
|
+
beforeEach(() => {
|
|
35
|
+
root = mkdtempSync(join(tmpdir(), "gate-wrapper-"));
|
|
36
|
+
mkdirSync(join(root, "dist", "esm"), { recursive: true });
|
|
37
|
+
artifact = join(root, "dist", "esm", "index.js");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
rmSync(root, { recursive: true, force: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("a build that RAN and failed destroys the artifact it emitted — the round-12 rule", () => {
|
|
45
|
+
expect(() =>
|
|
46
|
+
buildDistOrDestroy(root, artifact, stale, () => {
|
|
47
|
+
// tsc's failure shape: EMIT the served entry, then exit nonzero
|
|
48
|
+
// (nothing sets noEmitOnError).
|
|
49
|
+
writeFileSync(artifact, "// compiled from erroring sources\n");
|
|
50
|
+
return { status: 2, signal: null, stdout: "out", stderr: "err" };
|
|
51
|
+
}),
|
|
52
|
+
).toThrowError(
|
|
53
|
+
`summon globalSetup: failed to build ${root}'s dist:\nouterr`,
|
|
54
|
+
);
|
|
55
|
+
// The destroy: a fresh-looking dist compiled from erroring sources
|
|
56
|
+
// must read STALE to the contender's re-stat and every later run.
|
|
57
|
+
expect(existsSync(artifact)).toBe(false);
|
|
58
|
+
expect(existsSync(join(root, ".dist-build.lock"))).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("a builder that never STARTED preserves the previous good artifact and names the spawn error", () => {
|
|
62
|
+
writeFileSync(artifact, "// previous good generation\n");
|
|
63
|
+
expect(() =>
|
|
64
|
+
buildDistOrDestroy(root, artifact, stale, () => ({
|
|
65
|
+
// spawnSync's spawn-failure shape with NO child (ENOENT/EACCES):
|
|
66
|
+
// status unset, signal null (no child was ever killed), both
|
|
67
|
+
// streams null, the reason ONLY in `error`. NOT the only
|
|
68
|
+
// `error`-carrying shape — spawnSync's own kills of a RUNNING
|
|
69
|
+
// child set `error` too, WITH a signal (the cell below).
|
|
70
|
+
status: undefined,
|
|
71
|
+
signal: null,
|
|
72
|
+
stdout: null,
|
|
73
|
+
stderr: null,
|
|
74
|
+
error: new Error("spawn bun ENOENT"),
|
|
75
|
+
})),
|
|
76
|
+
).toThrowError(
|
|
77
|
+
`summon globalSetup: failed to RUN the build for ${root}: spawn bun ENOENT`,
|
|
78
|
+
);
|
|
79
|
+
// No child ever ran, so nothing was emitted: the dist on disk is
|
|
80
|
+
// still the previous good generation — pre-fix this was destroyed
|
|
81
|
+
// and the message interpolated the null streams as `nullnull`.
|
|
82
|
+
expect(readFileSync(artifact, "utf-8")).toBe(
|
|
83
|
+
"// previous good generation\n",
|
|
84
|
+
);
|
|
85
|
+
expect(existsSync(join(root, ".dist-build.lock"))).toBe(false);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("a build KILLED mid-run destroys what it emitted — `error` alone is not `never started`", () => {
|
|
89
|
+
expect(() =>
|
|
90
|
+
buildDistOrDestroy(root, artifact, stale, () => {
|
|
91
|
+
// spawnSync's OWN kill of a running child (ENOBUFS at a
|
|
92
|
+
// maxBuffer cap, or a timeout): the child RAN, emitted the
|
|
93
|
+
// entry, and was then SIGTERMed — `status` null, `signal` set,
|
|
94
|
+
// `error` set, a stream captured. Pre-fix the error-first
|
|
95
|
+
// branch read this as "never started" and PRESERVED the
|
|
96
|
+
// poisoned dist, which the next run's stats blessed FRESH: the
|
|
97
|
+
// round-12 false green, reintroduced.
|
|
98
|
+
writeFileSync(artifact, "// compiled from erroring sources\n");
|
|
99
|
+
return {
|
|
100
|
+
status: null,
|
|
101
|
+
signal: "SIGTERM",
|
|
102
|
+
stdout: "1 MiB of diagnostics…",
|
|
103
|
+
stderr: "",
|
|
104
|
+
error: new Error("spawnSync bun ENOBUFS"),
|
|
105
|
+
};
|
|
106
|
+
}),
|
|
107
|
+
).toThrowError(
|
|
108
|
+
`summon globalSetup: failed to build ${root}'s dist: ` +
|
|
109
|
+
"(killed mid-run: spawnSync bun ENOBUFS)\n1 MiB of diagnostics…",
|
|
110
|
+
);
|
|
111
|
+
// The destroy: the poisoned emit must read STALE to every later run.
|
|
112
|
+
expect(existsSync(artifact)).toBe(false);
|
|
113
|
+
expect(existsSync(join(root, ".dist-build.lock"))).toBe(false);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("success leaves the artifact as built — no destroy, no lock residue", () => {
|
|
117
|
+
buildDistOrDestroy(root, artifact, stale, () => {
|
|
118
|
+
writeFileSync(artifact, "// good generation\n");
|
|
119
|
+
return { status: 0, signal: null, stdout: "", stderr: "" };
|
|
120
|
+
});
|
|
121
|
+
expect(readFileSync(artifact, "utf-8")).toBe("// good generation\n");
|
|
122
|
+
expect(existsSync(join(root, ".dist-build.lock"))).toBe(false);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("a FRESH root's lock cycle never invokes the runner and never moves the artifact's parent-dir mtime chain", () => {
|
|
126
|
+
writeFileSync(artifact, "// previous good generation\n");
|
|
127
|
+
// Pin the watched dirs to a past instant: any directory mutation inside
|
|
128
|
+
// them — e.g. a lockfile created and unlinked beside the artifact, the
|
|
129
|
+
// round-14 regression that marked the sibling gate's `dist/pragma`
|
|
130
|
+
// stale on EVERY run — moves them to NOW and fails the equality below.
|
|
131
|
+
// The lock must live at the ROOT, whose own mtime no freshness rule
|
|
132
|
+
// reads.
|
|
133
|
+
const watched = [join(root, "dist"), join(root, "dist", "esm")];
|
|
134
|
+
const past = new Date(Date.now() - 60_000);
|
|
135
|
+
for (const dir of watched) {
|
|
136
|
+
utimesSync(dir, past, past);
|
|
137
|
+
}
|
|
138
|
+
const before = watched.map((dir) => statSync(dir).mtimeMs);
|
|
139
|
+
let invoked = false;
|
|
140
|
+
buildDistOrDestroy(
|
|
141
|
+
root,
|
|
142
|
+
artifact,
|
|
143
|
+
() => true,
|
|
144
|
+
() => {
|
|
145
|
+
invoked = true;
|
|
146
|
+
return { status: 0, signal: null, stdout: "", stderr: "" };
|
|
147
|
+
},
|
|
148
|
+
);
|
|
149
|
+
expect(invoked).toBe(false);
|
|
150
|
+
expect(watched.map((dir) => statSync(dir).mtimeMs)).toEqual(before);
|
|
151
|
+
expect(existsSync(join(root, ".dist-build.lock"))).toBe(false);
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
describe("TEMPLATE_COPIER — the watched repo-root constant", () => {
|
|
156
|
+
it("resolves to a real file — a dangling constant would stat 0 and silently un-watch the copier", () => {
|
|
157
|
+
// The gate's isFresh uses `newestMtime(TEMPLATE_COPIER) < built`, and
|
|
158
|
+
// newestMtime returns 0 for a missing path — always true against an
|
|
159
|
+
// existing artifact, i.e. the clause becomes a NO-OP with no red cell.
|
|
160
|
+
// The module also throws at load when the path is missing; this pin
|
|
161
|
+
// fails the suite loudly at the moment a relocation (PRA-138) orphans
|
|
162
|
+
// the constant instead of quietly returning to the round-15 F8 hole.
|
|
163
|
+
expect(existsSync(TEMPLATE_COPIER)).toBe(true);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vitest global setup: rebuild every STALE workspace dependency dist before
|
|
3
|
+
* any worker starts.
|
|
4
|
+
*
|
|
5
|
+
* The subprocess suites spawn the REAL bin (`bun src/bin.tsx`), which
|
|
6
|
+
* resolves `@canonical/summon-core` and `@canonical/task` through their
|
|
7
|
+
* `exports` maps into `dist/esm/…` — and the interaction fixtures hard-code
|
|
8
|
+
* those same dist entry files — so a projection edit in summon-core's `src`
|
|
9
|
+
* is invisible to every spawned cell until that dist is rebuilt. Without
|
|
10
|
+
* this gate the two hosts of the parity PR could return opposite verdicts
|
|
11
|
+
* on one change: cli/pragma's suites rebuild their dep dists in their own
|
|
12
|
+
* globalSetup while this package's cells stayed green against the previous
|
|
13
|
+
* generation of the very file under edit.
|
|
14
|
+
*
|
|
15
|
+
* This is cli/pragma's gate (src/testing/perf/globalSetup.ts) minus its
|
|
16
|
+
* compiled-binary half — a faithful SIBLING rather than an import: pulling
|
|
17
|
+
* the shared helpers from `@canonical/pragma-cli` would point a dependency
|
|
18
|
+
* edge summon → pragma-cli, closing a cycle with pragma-cli's declared
|
|
19
|
+
* devDependency on this package. Same honest mtime staleness rule, same
|
|
20
|
+
* main-process-before-any-worker placement (a `beforeAll` inside a worker
|
|
21
|
+
* would race sibling workers importing the same in-place-rewritten files),
|
|
22
|
+
* same loud topo-cycle throw, same cross-process build lock. Runs for full
|
|
23
|
+
* suites and single-file `vitest run <file>` invocations alike.
|
|
24
|
+
*
|
|
25
|
+
* The main-process placement serializes only THIS process's workers. The
|
|
26
|
+
* sibling gate rebuilds four of the same dists (task, ds-types, utils,
|
|
27
|
+
* summon-core) from ITS process, and nothing orders the two suites — so
|
|
28
|
+
* every root ALWAYS enters {@link buildUnderLock}, which takes an O_EXCL
|
|
29
|
+
* lockfile at the root's top level — OUTSIDE every tree the freshness
|
|
30
|
+
* rules stat — and judges freshness only UNDER it: a second process
|
|
31
|
+
* finding the lock waits for release and RE-STATS instead of
|
|
32
|
+
* double-building (two in-place `tsc` rewrites truncating one dist under
|
|
33
|
+
* a live importer). A pre-lock freshness skip existed once and let a
|
|
34
|
+
* contender bless another process's mid-flight emit (the entry lands
|
|
35
|
+
* before `tsc` can fail — measured live), proceeding with no lock
|
|
36
|
+
* against an artifact about to be destroyed; deleting it is what makes
|
|
37
|
+
* one consistent pre-worker generation true. A lock that never clears
|
|
38
|
+
* fails loudly after a timeout instead of forever.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { spawnSync } from "node:child_process";
|
|
42
|
+
import {
|
|
43
|
+
closeSync,
|
|
44
|
+
existsSync,
|
|
45
|
+
lstatSync,
|
|
46
|
+
openSync,
|
|
47
|
+
readdirSync,
|
|
48
|
+
readFileSync,
|
|
49
|
+
realpathSync,
|
|
50
|
+
rmSync,
|
|
51
|
+
statSync,
|
|
52
|
+
writeSync,
|
|
53
|
+
} from "node:fs";
|
|
54
|
+
import { join, sep } from "node:path";
|
|
55
|
+
import { fileURLToPath } from "node:url";
|
|
56
|
+
|
|
57
|
+
/** How long a contender waits on another process's build lock (ms). */
|
|
58
|
+
const LOCK_TIMEOUT_MS = 120_000;
|
|
59
|
+
|
|
60
|
+
/** Contention poll interval (ms). */
|
|
61
|
+
const LOCK_POLL_MS = 200;
|
|
62
|
+
|
|
63
|
+
/** Synchronous sleep — the gate is sync, in the main process, pre-worker. */
|
|
64
|
+
function sleepSync(ms: number): void {
|
|
65
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Serialize one root's rebuild across PROCESSES with an `O_EXCL` lockfile
|
|
70
|
+
* at `<root>/.dist-build.lock` — the root's top level, deliberately
|
|
71
|
+
* OUTSIDE every tree the freshness rules stat. The lock's own
|
|
72
|
+
* create/unlink is a directory mutation, and a lock kept beside the
|
|
73
|
+
* served artifact inside `dist/**` bumped a directory the sibling gate's
|
|
74
|
+
* `DEP_INPUTS` watches on EVERY entry, so a fully fresh tree re-judged
|
|
75
|
+
* `dist/pragma` stale and rebuilt the binary on every vitest invocation
|
|
76
|
+
* (measured); the root's own mtime, by contrast, is watched by nothing —
|
|
77
|
+
* only its named children are. The file must also stay UNTRACKED: the
|
|
78
|
+
* root-level home sits outside the ignored `dist/`, so `.dist-build.lock`
|
|
79
|
+
* has its own root `.gitignore` rule — a committed lock (crash residue
|
|
80
|
+
* swept into a `git add -A`) would block every clone's every run for the
|
|
81
|
+
* full timeout, with a "delete the file" remedy git keeps undoing. The
|
|
82
|
+
* next relocation must keep BOTH properties: outside every watched tree,
|
|
83
|
+
* and inside an ignore rule. One root serves ONE dist artifact, so
|
|
84
|
+
* root-scoped is artifact-scoped, and both sibling gates compute the
|
|
85
|
+
* same path for the same root — contention still meets contention.
|
|
86
|
+
* Freshness is decided ONLY under the lock: callers enter
|
|
87
|
+
* unconditionally, with no pre-lock fast path — a stat taken outside the
|
|
88
|
+
* lock can land inside another process's emit-to-exit window (`tsc`
|
|
89
|
+
* emits the entry before it can fail) and bless a mid-flight artifact
|
|
90
|
+
* without waiting on anything. The holder stats after acquiring and
|
|
91
|
+
* builds only if stale, so an uncontended fresh root pays one
|
|
92
|
+
* open/unlink and nothing else; a contender waits for release and then
|
|
93
|
+
* loops back to ACQUIRE the lock itself and re-stat UNDER it — a
|
|
94
|
+
* lock-free existence-then-freshness probe is two unsynchronised
|
|
95
|
+
* observations, and between them a new holder can take the lock and
|
|
96
|
+
* begin an in-place rebuild whose mid-flight mtimes the probe blesses —
|
|
97
|
+
* building only when the re-stat still reads stale, which a FAILED
|
|
98
|
+
* holder guarantees: a `build` callback whose build RAN and failed
|
|
99
|
+
* destroys the served artifact before
|
|
100
|
+
* rethrowing, because a failed build can still EMIT it (nothing sets
|
|
101
|
+
* `noEmitOnError`, so `tsc` writes output and exits nonzero, and the
|
|
102
|
+
* two-step builds' first step writes the entry before the second can
|
|
103
|
+
* fail) — mtime alone cannot tell a failed build from a clean one —
|
|
104
|
+
* while a spawn failure with NO child (`error` set and `signal == null`)
|
|
105
|
+
* leaves the artifact alone: no builder ever ran, nothing was emitted,
|
|
106
|
+
* and the dist on disk is still the previous good generation, stale by
|
|
107
|
+
* the same stats that sent the holder in. A
|
|
108
|
+
* lockfile that never clears (a killed builder) fails loudly after
|
|
109
|
+
* {@link LOCK_TIMEOUT_MS} naming the file, rather than double-building
|
|
110
|
+
* or waiting forever. RESIDUAL, accepted: since every entry takes the
|
|
111
|
+
* lock, crash residue blocks EVERY later run for the full timeout until
|
|
112
|
+
* the file is removed (pre-existing wait semantics — no stale-lock
|
|
113
|
+
* reclaim is attempted).
|
|
114
|
+
*
|
|
115
|
+
* TWIN: cli/pragma's perf globalSetup carries the same helper — the two
|
|
116
|
+
* gates are deliberate SIBLINGS with no import edge (see the file
|
|
117
|
+
* docblock); keep the copies in step.
|
|
118
|
+
*
|
|
119
|
+
* @param root - The package root the lock scopes (one served dist each).
|
|
120
|
+
* @param isFresh - Re-stats the artifact against its inputs.
|
|
121
|
+
* @param build - Rebuilds the artifact (throws loudly on failure).
|
|
122
|
+
* @note Impure — creates and removes `<root>/.dist-build.lock`; blocks
|
|
123
|
+
* while waiting.
|
|
124
|
+
*/
|
|
125
|
+
function buildUnderLock(
|
|
126
|
+
root: string,
|
|
127
|
+
isFresh: () => boolean,
|
|
128
|
+
build: () => void,
|
|
129
|
+
): void {
|
|
130
|
+
const lockPath = join(root, ".dist-build.lock");
|
|
131
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
132
|
+
for (;;) {
|
|
133
|
+
let fd: number;
|
|
134
|
+
try {
|
|
135
|
+
fd = openSync(lockPath, "wx");
|
|
136
|
+
} catch (cause) {
|
|
137
|
+
if ((cause as NodeJS.ErrnoException).code !== "EEXIST") throw cause;
|
|
138
|
+
if (Date.now() >= deadline) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
`summon globalSetup: build lock ${lockPath} still held after ` +
|
|
141
|
+
`${LOCK_TIMEOUT_MS}ms — a killed build may have left it behind; ` +
|
|
142
|
+
"delete the file and re-run",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
sleepSync(LOCK_POLL_MS);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
writeSync(fd, `${process.pid}\n`);
|
|
150
|
+
if (!isFresh()) build();
|
|
151
|
+
return;
|
|
152
|
+
} finally {
|
|
153
|
+
closeSync(fd);
|
|
154
|
+
rmSync(lockPath, { force: true });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The newest modification time under `path`, or 0 when it does not exist.
|
|
161
|
+
* A nested `node_modules` is never descended into (a dep's own deps are
|
|
162
|
+
* enumerated as roots of their own by {@link workspaceDepRoots}).
|
|
163
|
+
*
|
|
164
|
+
* @param path - A file or directory.
|
|
165
|
+
* @returns Epoch milliseconds of the newest entry beneath it.
|
|
166
|
+
* @note Impure — stats the source tree.
|
|
167
|
+
*/
|
|
168
|
+
function newestMtime(path: string): number {
|
|
169
|
+
let stats: ReturnType<typeof statSync>;
|
|
170
|
+
try {
|
|
171
|
+
stats = statSync(path);
|
|
172
|
+
} catch {
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
if (!stats.isDirectory()) return stats.mtimeMs;
|
|
176
|
+
let newest = stats.mtimeMs;
|
|
177
|
+
for (const entry of readdirSync(path)) {
|
|
178
|
+
if (entry === "node_modules") continue;
|
|
179
|
+
newest = Math.max(newest, newestMtime(join(path, entry)));
|
|
180
|
+
}
|
|
181
|
+
return newest;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Every workspace package this one links, transitively: follow each
|
|
186
|
+
* `node_modules/<name>` symlink whose target lives OUTSIDE any
|
|
187
|
+
* `node_modules` store (what distinguishes a workspace link from a registry
|
|
188
|
+
* install), then repeat from the target's own `node_modules`. Cycles are
|
|
189
|
+
* cut by the visited set.
|
|
190
|
+
*
|
|
191
|
+
* @param pkgRoot - This package's root directory.
|
|
192
|
+
* @returns Absolute real paths of the linked workspace dependency roots.
|
|
193
|
+
* @note Impure — reads `node_modules` link farms.
|
|
194
|
+
*/
|
|
195
|
+
function workspaceDepRoots(pkgRoot: string): string[] {
|
|
196
|
+
const visited = new Set<string>([realpathSync(pkgRoot)]);
|
|
197
|
+
const queue = [realpathSync(pkgRoot)];
|
|
198
|
+
while (queue.length > 0) {
|
|
199
|
+
const dir = queue.pop() as string;
|
|
200
|
+
const nm = join(dir, "node_modules");
|
|
201
|
+
let entries: string[];
|
|
202
|
+
try {
|
|
203
|
+
entries = readdirSync(nm);
|
|
204
|
+
} catch {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const links = entries.flatMap((entry) => {
|
|
208
|
+
if (!entry.startsWith("@")) return [join(nm, entry)];
|
|
209
|
+
try {
|
|
210
|
+
return readdirSync(join(nm, entry)).map((e) => join(nm, entry, e));
|
|
211
|
+
} catch {
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
for (const link of links) {
|
|
216
|
+
let real: string;
|
|
217
|
+
try {
|
|
218
|
+
if (!lstatSync(link).isSymbolicLink()) continue;
|
|
219
|
+
real = realpathSync(link);
|
|
220
|
+
} catch {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (real.split(sep).includes("node_modules")) continue;
|
|
224
|
+
if (visited.has(real)) continue;
|
|
225
|
+
visited.add(real);
|
|
226
|
+
queue.push(real);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const root = realpathSync(pkgRoot);
|
|
230
|
+
return [...visited].filter((dir) => dir !== root);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* What one dep's dist is built from (a missing entry stats 0). Every
|
|
235
|
+
* `tsconfig.build.json` here is a thin override extending the package's own
|
|
236
|
+
* `tsconfig.json`, which supplies the compiler options that shape the emit —
|
|
237
|
+
* so both are watched. The repo-root template copier is a build input too —
|
|
238
|
+
* see {@link TEMPLATE_COPIER}, statted separately because no
|
|
239
|
+
* `join(root, input)` path can reach it. RESIDUAL, accepted: the shared
|
|
240
|
+
* `@canonical/typescript-config` base those extend is NOT watched — the
|
|
241
|
+
* packages reach it inconsistently (most via their own `node_modules` link,
|
|
242
|
+
* summon-application by relative path), so no one entry covers it; an edit
|
|
243
|
+
* there without a per-package tsconfig change can leave a dist judged fresh.
|
|
244
|
+
*/
|
|
245
|
+
const DIST_INPUTS = [
|
|
246
|
+
"src",
|
|
247
|
+
"generators",
|
|
248
|
+
"package.json",
|
|
249
|
+
"tsconfig.build.json",
|
|
250
|
+
"tsconfig.json",
|
|
251
|
+
];
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The repo-root template copier — the SECOND build step of four gated dists
|
|
255
|
+
* (`bun ../../../scripts/copy-templates.ts` in summon-component/-package/
|
|
256
|
+
* -application and cli/summon): a ROOT-OWNED build input (the r12-F4 class,
|
|
257
|
+
* one directory up) that {@link DIST_INPUTS}' root-relative paths can never
|
|
258
|
+
* reach, so an edit to the copier's glob or filter left every dist judged
|
|
259
|
+
* FRESH and the suites green against copies the OLD copier produced. It is
|
|
260
|
+
* statted as one absolute constant, UNCONDITIONALLY for every dep root (a
|
|
261
|
+
* cheap single stat; roots whose build never runs it just carry a harmless
|
|
262
|
+
* extra input).
|
|
263
|
+
*
|
|
264
|
+
* WATCHED-CONSTANT RULE: for one absolute constant a stat of 0 is ALWAYS a
|
|
265
|
+
* bug — the copier moved (the filed PRA-138 relocation is the standing
|
|
266
|
+
* trigger) and the constant dangles — never a legitimate absence like
|
|
267
|
+
* {@link DIST_INPUTS}' root-relative entries. `newestMtime`'s 0 would make
|
|
268
|
+
* `0 < built` vacuously true, silently deleting the clause from every
|
|
269
|
+
* gate, so the module THROWS at load while the path is missing. EXPORTED
|
|
270
|
+
* for the existsSync pin in globalSetup.test.ts.
|
|
271
|
+
* TWIN: cli/pragma's perf globalSetup carries the same constant and rule.
|
|
272
|
+
*/
|
|
273
|
+
export const TEMPLATE_COPIER = fileURLToPath(
|
|
274
|
+
new URL("../../../../../scripts/copy-templates.ts", import.meta.url),
|
|
275
|
+
);
|
|
276
|
+
if (!existsSync(TEMPLATE_COPIER)) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
`summon globalSetup: the watched template copier is MISSING at ${TEMPLATE_COPIER} — ` +
|
|
279
|
+
"the TEMPLATE_COPIER constant dangles (copier moved?); fix the path, " +
|
|
280
|
+
"or its freshness clause silently stops watching",
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Every string leaf of a package.json `exports` value (conditions walked). */
|
|
285
|
+
function exportTargets(exportsField: unknown): string[] {
|
|
286
|
+
if (typeof exportsField === "string") return [exportsField];
|
|
287
|
+
if (exportsField && typeof exportsField === "object") {
|
|
288
|
+
return Object.values(exportsField).flatMap(exportTargets);
|
|
289
|
+
}
|
|
290
|
+
return [];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* EVERY dist artifact one workspace package serves, absolute, entry first —
|
|
295
|
+
* or `[]` for a package that serves no compiled dist (no `build` script, or
|
|
296
|
+
* an entry outside `dist/`, e.g. a source-served config package), which the
|
|
297
|
+
* gate skips.
|
|
298
|
+
*
|
|
299
|
+
* The entry (`module` ?? `main`) alone was the whole freshness subject once,
|
|
300
|
+
* and that was too narrow: the suites also consume `types` (a dependent's
|
|
301
|
+
* tsc reads summon-core's `dist/types`), the export-map subpaths
|
|
302
|
+
* (`@canonical/summon-core/projection` resolves into `dist/esm/
|
|
303
|
+
* projection/`), and the template copier's destination (this package's own
|
|
304
|
+
* `dist/generators`) — so a TORN build could leave the entry newer than
|
|
305
|
+
* every input while another served output was missing or stale, and the
|
|
306
|
+
* gate blessed it. Freshness is judged against the OLDEST of these (a
|
|
307
|
+
* missing one stats 0 and reads stale). RESIDUAL, accepted: a torn emit
|
|
308
|
+
* that wrote a SUBSET of one directory's files carries fresh mtimes on
|
|
309
|
+
* what it did write — mtimes cannot prove set-completeness.
|
|
310
|
+
*/
|
|
311
|
+
function servedDistOutputs(root: string): string[] {
|
|
312
|
+
let manifest: {
|
|
313
|
+
module?: string;
|
|
314
|
+
main?: string;
|
|
315
|
+
types?: string;
|
|
316
|
+
exports?: unknown;
|
|
317
|
+
scripts?: Record<string, string>;
|
|
318
|
+
};
|
|
319
|
+
try {
|
|
320
|
+
manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
|
|
321
|
+
} catch {
|
|
322
|
+
return [];
|
|
323
|
+
}
|
|
324
|
+
const entry = manifest.module ?? manifest.main;
|
|
325
|
+
if (!entry?.startsWith("dist") || !manifest.scripts?.build) {
|
|
326
|
+
return [];
|
|
327
|
+
}
|
|
328
|
+
const outputs = new Set<string>([entry]);
|
|
329
|
+
if (manifest.types?.startsWith("dist")) outputs.add(manifest.types);
|
|
330
|
+
for (const target of exportTargets(manifest.exports)) {
|
|
331
|
+
const relative = target.replace(/^\.\//, "");
|
|
332
|
+
if (relative.startsWith("dist")) outputs.add(relative);
|
|
333
|
+
}
|
|
334
|
+
// The template copier's destination, when this package's build runs it
|
|
335
|
+
// (`bun ../../../scripts/copy-templates.ts <src> <dest>`).
|
|
336
|
+
const copyDest = /copy-templates\.ts\s+\S+\s+(\S+)/.exec(
|
|
337
|
+
manifest.scripts.build,
|
|
338
|
+
)?.[1];
|
|
339
|
+
if (copyDest?.startsWith("dist")) outputs.add(copyDest);
|
|
340
|
+
return [...outputs].map((output) => join(root, output));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The slice of `spawnSync`'s result the build wrapper judges. */
|
|
344
|
+
interface BuildResult {
|
|
345
|
+
status: number | null | undefined;
|
|
346
|
+
/**
|
|
347
|
+
* The never-started/ran-then-killed discriminator: spawnSync's
|
|
348
|
+
* `NodeJS.Signals | null` — `null` when no child ever ran, a signal
|
|
349
|
+
* (e.g. `SIGTERM`) when spawnSync KILLED a running child itself
|
|
350
|
+
* (maxBuffer/timeout — `error` is set in BOTH cases). Bun may leave it
|
|
351
|
+
* `undefined` on a spawn failure; judged `== null` either way.
|
|
352
|
+
*/
|
|
353
|
+
signal: NodeJS.Signals | null | undefined;
|
|
354
|
+
stdout: string | null;
|
|
355
|
+
stderr: string | null;
|
|
356
|
+
error?: Error | undefined;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Runs one root's build and reports the spawn result. */
|
|
360
|
+
type BuildRunner = (root: string) => BuildResult;
|
|
361
|
+
|
|
362
|
+
/** The real runner: the package's own `bun run build`, streams captured. */
|
|
363
|
+
function runBuild(root: string): BuildResult {
|
|
364
|
+
return spawnSync("bun", ["run", "build"], {
|
|
365
|
+
cwd: root,
|
|
366
|
+
stdio: "pipe",
|
|
367
|
+
encoding: "utf-8",
|
|
368
|
+
// Uncapped: at the 1 MiB default a diagnostic FLOOD had spawnSync
|
|
369
|
+
// kill a child that had already emitted (ENOBUFS), instead of the
|
|
370
|
+
// flood reaching the nonzero arm intact.
|
|
371
|
+
maxBuffer: Number.POSITIVE_INFINITY,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Build one root's served dist under the cross-process lock, destroying the
|
|
377
|
+
* artifact only when the build RAN and failed.
|
|
378
|
+
*
|
|
379
|
+
* The per-root build-or-destroy rule, extracted and EXPORTED so a unit cell
|
|
380
|
+
* can drive it with an injected runner (globalSetup.test.ts, beside this
|
|
381
|
+
* file): this wrapper is the loop's one confirmed false-green producer
|
|
382
|
+
* (round 12), and unexported it was pinned by nothing — a dropped rmSync or
|
|
383
|
+
* a restored destroy-on-spawn-error stayed green until a real CI build
|
|
384
|
+
* failed. Three shapes:
|
|
385
|
+
* - spawn failure with NO child (`result.error` with `signal == null` —
|
|
386
|
+
* ENOENT/EACCES): throw naming the error, artifact PRESERVED (no child
|
|
387
|
+
* ever ran, so nothing was emitted; the dist on disk is the previous
|
|
388
|
+
* good generation). `error` ALONE does not mean this — spawnSync also
|
|
389
|
+
* sets it when it KILLS a build that ran (maxBuffer/timeout), and
|
|
390
|
+
* there `signal` carries the evidence.
|
|
391
|
+
* - nonzero exit / signal kill — spawnSync's own mid-run kills included
|
|
392
|
+
* (`error` set WITH a signal: the child RAN and can have emitted
|
|
393
|
+
* before dying): destroy the artifact (a failed build can still have
|
|
394
|
+
* EMITTED it — see {@link buildUnderLock}), then throw naming the
|
|
395
|
+
* root, the kill when there was one, and both captured streams.
|
|
396
|
+
* - success: the artifact is left as built, the lock released.
|
|
397
|
+
*
|
|
398
|
+
* TWIN: cli/pragma's perf globalSetup carries the same function; keep in
|
|
399
|
+
* step.
|
|
400
|
+
*
|
|
401
|
+
* @param root - The workspace package being built (the lock lives at its
|
|
402
|
+
* top level, outside the watched trees).
|
|
403
|
+
* @param artifact - Its served dist entry.
|
|
404
|
+
* @param isFresh - Re-stats the artifact against its inputs (under the lock).
|
|
405
|
+
* @param runner - The build runner ({@link runBuild}; injectable for tests).
|
|
406
|
+
* @note Impure — takes the lock, builds, and may remove the artifact.
|
|
407
|
+
*/
|
|
408
|
+
export function buildDistOrDestroy(
|
|
409
|
+
root: string,
|
|
410
|
+
artifact: string,
|
|
411
|
+
isFresh: () => boolean,
|
|
412
|
+
runner: BuildRunner = runBuild,
|
|
413
|
+
): void {
|
|
414
|
+
buildUnderLock(root, isFresh, () => {
|
|
415
|
+
const result = runner(root);
|
|
416
|
+
if (result.error && result.signal == null) {
|
|
417
|
+
// A spawn failure with NO child (ENOENT/EACCES — no signal, and
|
|
418
|
+
// `status` unset): nothing can have been emitted, so the artifact
|
|
419
|
+
// on disk is still the previous good generation — preserve it,
|
|
420
|
+
// and name the failure's only carrier. `error` with a SIGNAL is
|
|
421
|
+
// the opposite case: spawnSync killed a build that RAN
|
|
422
|
+
// (maxBuffer/timeout) — that shape falls through to the destroy
|
|
423
|
+
// arm below.
|
|
424
|
+
throw new Error(
|
|
425
|
+
`summon globalSetup: failed to RUN the build for ${root}: ${result.error.message}`,
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
if (result.status !== 0) {
|
|
429
|
+
// The build RAN and failed — a nonzero exit, or a kill after the
|
|
430
|
+
// child started — and it can still have EMITTED the artifact (see
|
|
431
|
+
// buildUnderLock's docblock): destroy the evidence so the
|
|
432
|
+
// contender's re-stat and every later run see STALE instead of a
|
|
433
|
+
// fresh-looking dist compiled from erroring sources.
|
|
434
|
+
rmSync(artifact, { force: true });
|
|
435
|
+
const killed = result.error
|
|
436
|
+
? ` (killed mid-run: ${result.error.message})`
|
|
437
|
+
: "";
|
|
438
|
+
throw new Error(
|
|
439
|
+
`summon globalSetup: failed to build ${root}'s dist:${killed}\n${result.stdout}${result.stderr}`,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Rebuild every STALE workspace dep dist, dependencies before dependents.
|
|
447
|
+
* Staleness is the honest per-package mtime rule: the served entry artifact
|
|
448
|
+
* must be newer than every {@link DIST_INPUTS} entry.
|
|
449
|
+
*
|
|
450
|
+
* @param pkgRoot - This package's root directory (the closure's seed).
|
|
451
|
+
* @note Impure — stats and rebuilds workspace dists.
|
|
452
|
+
*/
|
|
453
|
+
function buildStaleDepDists(pkgRoot: string): void {
|
|
454
|
+
const deps = workspaceDepRoots(pkgRoot);
|
|
455
|
+
// Dependencies before dependents. `workspaceDepRoots` follows
|
|
456
|
+
// devDependency links too, so a future dev-edge cycle is an ordinary
|
|
457
|
+
// event — it must throw with its members named, never spin the
|
|
458
|
+
// synchronous loop forever.
|
|
459
|
+
const depsOf = new Map(
|
|
460
|
+
deps.map((root) => [root, new Set(workspaceDepRoots(root))] as const),
|
|
461
|
+
);
|
|
462
|
+
const remaining = new Set(deps);
|
|
463
|
+
const ordered: string[] = [];
|
|
464
|
+
while (remaining.size > 0) {
|
|
465
|
+
const next = [...remaining].find((root) =>
|
|
466
|
+
[...(depsOf.get(root) ?? [])].every((dep) => !remaining.has(dep)),
|
|
467
|
+
);
|
|
468
|
+
if (next === undefined) {
|
|
469
|
+
throw new Error(
|
|
470
|
+
`summon globalSetup: dependency cycle among ${[...remaining].join(", ")}`,
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
ordered.push(next);
|
|
474
|
+
remaining.delete(next);
|
|
475
|
+
}
|
|
476
|
+
for (const root of ordered) {
|
|
477
|
+
const outputs = servedDistOutputs(root);
|
|
478
|
+
const artifact = outputs[0];
|
|
479
|
+
if (!artifact) continue;
|
|
480
|
+
const isFresh = (): boolean => {
|
|
481
|
+
// The OLDEST served output is the build's honest age: a missing one
|
|
482
|
+
// stats 0 (stale), and every input must predate ALL of them — the
|
|
483
|
+
// entry alone let a torn build pass on its freshest file.
|
|
484
|
+
const built = Math.min(...outputs.map(newestMtime));
|
|
485
|
+
return (
|
|
486
|
+
built > 0 &&
|
|
487
|
+
newestMtime(TEMPLATE_COPIER) < built &&
|
|
488
|
+
DIST_INPUTS.every((input) => newestMtime(join(root, input)) < built)
|
|
489
|
+
);
|
|
490
|
+
};
|
|
491
|
+
// No pre-lock isFresh() skip: freshness is decided UNDER the lock —
|
|
492
|
+
// a fresh-looking artifact out here can be another process's
|
|
493
|
+
// mid-flight emit (see buildUnderLock's docblock).
|
|
494
|
+
buildDistOrDestroy(root, artifact, isFresh);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export default function setup(): void {
|
|
499
|
+
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
500
|
+
buildStaleDepDists(root);
|
|
501
|
+
}
|