@locker/cli 0.28.3

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.
@@ -0,0 +1,166 @@
1
+ // Completion classification for CLI runs.
2
+ //
3
+ // Model: the JavaScript Completion Record (ECMA-262,
4
+ // sec-completion-record-specification-type). A run is evaluated at a Script
5
+ // top-level boundary, so the spec's five completion types collapse to a
6
+ // clean binary: a run either completes `normal` or it `throw`s. (`return`,
7
+ // `break`, and `continue` cannot escape a Script boundary, so they are not
8
+ // representable outcomes.)
9
+ //
10
+ // Only a `throw` completion carries a security verdict, classified from the
11
+ // thrown value:
12
+ // - `confirmed` : a LockerSecurityError was observed. LWS actively
13
+ // blocked an operation. In triage terms: vector CLOSED.
14
+ // - `unsignaled` : an ordinary error with no known tie to a distortion.
15
+ // This is the ABSENCE of a security verdict, NOT proof of
16
+ // safety. Naming it honestly is what keeps a machine
17
+ // consumer from over-reading a TypeError as "all clear".
18
+ // - `ambiguous` : reserved. A non-security error raised on a known
19
+ // soft-fail distorted API surface. Detection needs a
20
+ // distorted-API surface list and is a follow-up; the term
21
+ // and its exit code are reserved here so the contract is
22
+ // complete.
23
+ //
24
+ // Detection rule: LockerSecurityError is detected by the message PREFIX,
25
+ // never by `instanceof` or `error.name`. The near-membrane proxy boundary
26
+ // makes `instanceof` unreliable across realms, and LockerSecurityError does
27
+ // not set `this.name` (so `error.name` is "Error", not "LockerSecurityError").
28
+ // The boundary DOES prepend a stable prefix to the message, which is the only
29
+ // reliable signal and is legible when read in-page before the error crosses
30
+ // to the CLI.
31
+
32
+ // The prefix LockerSecurityError's constructor prepends to every message
33
+ // (see packages/@locker/shared/src/Error.ts). This is the load-bearing
34
+ // detection signal.
35
+ export const LWS_MESSAGE_PREFIX = 'Lightning Web Security: ';
36
+
37
+ // Window property where the in-page error listener stashes the first
38
+ // uncaught throw's `{ message, name }`. The runner reads it with a single
39
+ // browser.evaluate() once the run window closes. A global (rather than the
40
+ // console channel) makes the read deterministic: it does not depend on
41
+ // Playwright's asynchronous console-event delivery timing. Presence of this
42
+ // property after the run window is how the runner arbitrates throw-vs-normal.
43
+ //
44
+ // Capture covers any throw that has already surfaced as an uncaught window
45
+ // error by the time the run window closes: synchronous sandbox throws (eval,
46
+ // captured when addScriptTag settles) and throws raised through render
47
+ // stabilization (component, captured after the two-rAF wait, including async
48
+ // lifecycle callbacks like connectedCallback). A throw scheduled to fire
49
+ // AFTER the run window (e.g. a bare setTimeout in eval) is not captured, in
50
+ // line with the documented "lws eval does not await async sandbox code"
51
+ // behavior.
52
+ export const COMPLETION_GLOBAL = '__lwsCompletion';
53
+
54
+ export const COMPLETION_NORMAL = 'normal';
55
+ export const COMPLETION_THROW = 'throw';
56
+
57
+ export const VERDICT_CONFIRMED = 'confirmed';
58
+ export const VERDICT_UNSIGNALED = 'unsignaled';
59
+ // Reserved: detection is a follow-up (see module header).
60
+ export const VERDICT_AMBIGUOUS = 'ambiguous';
61
+
62
+ // Process exit codes. Semantic-verdict scheme ("School B", the grep/diff
63
+ // family): the exit code IS a verdict a script can branch on without parsing
64
+ // JSON. A confirmed security block is exit 10, deliberately NOT 0, because
65
+ // "success" is caller-relative (a block is the desired outcome in a triage
66
+ // run, a failure in a plain eval run).
67
+ //
68
+ // Harness/infra failures (browser launch, server bind, timeout, interrupt,
69
+ // usage) produce NO completion and stay at the existing generic code 1, so
70
+ // 1 keeps its current "the run broke" meaning and the semantic codes are
71
+ // purely additive on top. All semantic codes sit in the safe 3-125 user band.
72
+ export const EXIT_NORMAL = 0;
73
+ export const EXIT_HARNESS_FAILURE = 1;
74
+ export const EXIT_CONFIRMED = 10;
75
+ export const EXIT_UNSIGNALED = 20;
76
+ export const EXIT_AMBIGUOUS = 30;
77
+
78
+ // Detect a confirmed security verdict from a captured error's message. The
79
+ // message is read in-page (before the near-membrane boundary stringifies the
80
+ // thrown value to an opaque Proxy on the CLI side), so the prefix is intact.
81
+ //
82
+ // Spoofable by design: sandboxed code can throw an Error whose own message
83
+ // starts with the prefix and force a confirmed verdict. This is a
84
+ // self-inflicted spoof inside a triage harness, not a boundary the CLI
85
+ // defends; a confirmed verdict means "a LockerSecurityError-shaped throw
86
+ // occurred", which is exactly what triage consumes.
87
+ function isSecurityMessage(message) {
88
+ return typeof message === 'string' && message.startsWith(LWS_MESSAGE_PREFIX);
89
+ }
90
+
91
+ // Classify a throw completion's verdict from the captured error info.
92
+ function verdictFor(capturedError) {
93
+ const message = capturedError == null ? undefined : capturedError.message;
94
+ if (isSecurityMessage(message)) {
95
+ return VERDICT_CONFIRMED;
96
+ }
97
+ return VERDICT_UNSIGNALED;
98
+ }
99
+
100
+ // Build the Completion Report for a normal completion. `resultType`
101
+ // describes the shape of the produced value; the CLI does not transport the
102
+ // sandbox return value itself (sandbox code communicates via console), so
103
+ // `undefined` is the typical and default value.
104
+ export function normalCompletion({ resultType = 'undefined' } = {}) {
105
+ return {
106
+ type: COMPLETION_NORMAL,
107
+ value: { resultType },
108
+ };
109
+ }
110
+
111
+ // Build the Completion Report for a throw completion from captured error
112
+ // info `{ message, name, stack }`. Any field may be absent; the classifier
113
+ // only depends on `message` for the verdict. `name`/`stack` are carried
114
+ // through for machine and human consumers.
115
+ export function throwCompletion(capturedError) {
116
+ const info = capturedError == null ? {} : capturedError;
117
+ const value = {
118
+ securityVerdict: verdictFor(info),
119
+ errorName: typeof info.name === 'string' ? info.name : 'Error',
120
+ message: typeof info.message === 'string' ? info.message : '',
121
+ };
122
+ if (typeof info.stack === 'string') {
123
+ value.stack = info.stack;
124
+ }
125
+ return {
126
+ type: COMPLETION_THROW,
127
+ value,
128
+ };
129
+ }
130
+
131
+ // Map a Completion Report to its process exit code. A null/undefined report
132
+ // means no completion was produced (harness/infra failure) and maps to the
133
+ // generic failure code.
134
+ export function exitCodeFor(completion) {
135
+ if (completion == null) {
136
+ return EXIT_HARNESS_FAILURE;
137
+ }
138
+ if (completion.type === COMPLETION_NORMAL) {
139
+ return EXIT_NORMAL;
140
+ }
141
+ if (completion.type === COMPLETION_THROW) {
142
+ const verdict = completion.value?.securityVerdict;
143
+ if (verdict === VERDICT_CONFIRMED) {
144
+ return EXIT_CONFIRMED;
145
+ }
146
+ if (verdict === VERDICT_AMBIGUOUS) {
147
+ return EXIT_AMBIGUOUS;
148
+ }
149
+ return EXIT_UNSIGNALED;
150
+ }
151
+ return EXIT_HARNESS_FAILURE;
152
+ }
153
+
154
+ // One-line human-readable verdict summary for text mode, written to stderr
155
+ // alongside the existing console stream. JSON mode carries the structured
156
+ // `completion` field instead.
157
+ export function humanSummary(completion) {
158
+ if (completion == null || completion.type === COMPLETION_NORMAL || completion.value == null) {
159
+ return null;
160
+ }
161
+ const { securityVerdict, errorName, message } = completion.value;
162
+ if (securityVerdict === VERDICT_CONFIRMED) {
163
+ return `SECURITY (${errorName}): ${message}`;
164
+ }
165
+ return `ERROR (${errorName}): ${message}`;
166
+ }
@@ -0,0 +1,15 @@
1
+ // The set of browsers the CLI accepts via --browser. Keep this as the
2
+ // single source of truth — yargs imports it for `choices` validation;
3
+ // browser.mjs imports it for runtime checks. A divergence between the
4
+ // two is exactly the silent-skew failure this constant exists to prevent.
5
+ //
6
+ // Playwright has only three launchers (chromium / firefox / webkit). The
7
+ // branded browsers (chrome, msedge) are launched as channels of the
8
+ // chromium launcher. BROWSER_CHANNEL_MAP records which CLI value maps
9
+ // to which launcher + channel. CLI values not in the map use the
10
+ // launcher of the same name with no channel.
11
+ export const SUPPORTED_BROWSERS = ['chromium', 'firefox', 'webkit', 'chrome'];
12
+
13
+ export const BROWSER_CHANNEL_MAP = {
14
+ chrome: { launcher: 'chromium', channel: 'chrome' },
15
+ };
@@ -0,0 +1,189 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ // Resolve `--endowments <value>` to an object that the sandbox runtime
6
+ // will receive as the 4th argument of `evaluateInSandbox(key, source,
7
+ // context, endowments)`. Three forms are accepted:
8
+ //
9
+ // 1. A path to a `.json` file (read + JSON.parse).
10
+ // 2. A path to a `.js`/`.mjs`/`.cjs` file (dynamic-import; default
11
+ // export becomes the endowments object).
12
+ // 3. An inline JSON string.
13
+ //
14
+ // The .js form is the killer feature: endowments can contain functions,
15
+ // not just JSON-serializable values. The default export must be an object
16
+ // (or null/undefined, which collapse to {} per evaluate.ts's default).
17
+ export async function loadEndowments(value) {
18
+ if (value === undefined || value === null) {
19
+ return null;
20
+ }
21
+ if (typeof value !== 'string') {
22
+ throw new TypeError(`--endowments expects a string, got ${typeof value}`);
23
+ }
24
+ const trimmed = value.trim();
25
+ if (trimmed === '') {
26
+ return null;
27
+ }
28
+
29
+ const isPathShape = /\.(json|m?js|cjs)$/i.test(trimmed) || trimmed.includes('/');
30
+
31
+ if (isPathShape) {
32
+ const absolute = path.resolve(process.cwd(), trimmed);
33
+ if (!(await fileExists(absolute))) {
34
+ throw new Error(`--endowments file not found: ${absolute}`);
35
+ }
36
+ if (/\.json$/i.test(absolute)) {
37
+ const text = await fs.readFile(absolute, 'utf8');
38
+ return JSON.parse(text);
39
+ }
40
+ // .js/.mjs/.cjs: dynamic-import via file:// URL (avoids
41
+ // require-cache pollution and works for both ESM and CJS).
42
+ const url = pathToFileURL(absolute).href;
43
+ const mod = await import(url);
44
+ // Prefer `mod.default` if the file declared one (ESM `export
45
+ // default ...` or CJS `module.exports = ...`). If `default` is
46
+ // explicitly null/undefined, treat that as "no endowments"
47
+ // rather than falling through to the namespace object.
48
+ const hasDefault = Object.hasOwn(mod, 'default');
49
+ const def = hasDefault ? mod.default : mod;
50
+ if (def === null || def === undefined) {
51
+ return null;
52
+ }
53
+ if (typeof def !== 'object') {
54
+ throw new TypeError(
55
+ `--endowments file must export an object, got ${typeof def}: ${absolute}`,
56
+ );
57
+ }
58
+ return def;
59
+ }
60
+
61
+ // Inline form: JSON only. Inline JS expressions would require eval
62
+ // on the Node side, which is a security smell. Users who need a JS
63
+ // expression should put it in a `.js` file.
64
+ try {
65
+ return JSON.parse(trimmed);
66
+ } catch (err) {
67
+ throw new SyntaxError(
68
+ `--endowments inline value must be valid JSON (or a path ending in .json/.js/.mjs/.cjs): ${err.message}`,
69
+ );
70
+ }
71
+ }
72
+
73
+ async function fileExists(p) {
74
+ try {
75
+ const stat = await fs.stat(p);
76
+ return stat.isFile();
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ // Build the system-mode <script> source that registers the loaded
83
+ // endowments on `window.__lwsCLIEndowments`. The runner injects this
84
+ // script BEFORE the user's transformed bundle so `lib/evaluator.mjs`
85
+ // (bundled into the IIFE via the karma-pattern sandboxSpecifier
86
+ // override) reads the slot at module-init time.
87
+ //
88
+ // The script source emits an object literal where:
89
+ // - JSON-survivable values use JSON.stringify.
90
+ // - Function values use Function.prototype.toString() so the
91
+ // function source lands in the script literal as a real
92
+ // function expression. The browser parses it as a Function
93
+ // object, not a string. Closures created by the original Node-
94
+ // side function body do NOT survive (toString captures source,
95
+ // not lexical scope), but pure function values do.
96
+ //
97
+ // Throwing on unsupported values (Symbol, BigInt with no clean
98
+ // embedding, Map/Set) is preferred to silent dropping: D8.2 silently
99
+ // dropped functions and that became a documented limitation; doing
100
+ // the same with the karma-pattern refactor would defeat the point.
101
+ export function buildEndowmentsRegisterScript(endowments) {
102
+ if (endowments == null) {
103
+ return '';
104
+ }
105
+ if (typeof endowments !== 'object') {
106
+ throw new TypeError(`endowments must be an object, got ${typeof endowments}`);
107
+ }
108
+ const entries = Object.entries(endowments).map(
109
+ ([key, value]) => `${JSON.stringify(key)}: ${valueToJsLiteral(value, key)}`,
110
+ );
111
+ return `;window.__lwsCLIEndowments = { ${entries.join(', ')} };`;
112
+ }
113
+
114
+ // Build the source text that, when evaluated inside the sandbox realm,
115
+ // assigns each endowment property to `globalThis.KEY`. Used by the REPL
116
+ // path: REPL lines bypass the rollup compile pipeline (each line goes
117
+ // directly to `window.evaluateInSandbox(key, source)` via page.evaluate),
118
+ // so the karma-pattern wrapper module isn't on the call path. Instead,
119
+ // the runner runs ONE evaluation at session start that lands the
120
+ // endowments on the per-key SandboxRecord's globalThis. Subsequent
121
+ // REPL lines see the bindings as plain globals because globalThis
122
+ // persists across module evaluations.
123
+ //
124
+ // Bracket notation is used for all keys (`globalThis['KEY']`) to handle
125
+ // keys that aren't valid JS identifiers. A key with spaces, dashes, or
126
+ // other non-identifier chars stays addressable via square brackets.
127
+ // Inside the sandbox, the user can still read it as `globalThis['KEY']`
128
+ // or via destructuring; bare `KEY` only works for identifier-shaped
129
+ // keys.
130
+ export function buildEndowmentsReplAssignments(endowments) {
131
+ if (endowments == null) {
132
+ return '';
133
+ }
134
+ if (typeof endowments !== 'object') {
135
+ throw new TypeError(`endowments must be an object, got ${typeof endowments}`);
136
+ }
137
+ const stmts = Object.entries(endowments).map(
138
+ ([key, value]) => `globalThis[${JSON.stringify(key)}] = ${valueToJsLiteral(value, key)};`,
139
+ );
140
+ return stmts.join('\n');
141
+ }
142
+
143
+ // Convert a JS value to its source-text literal for embedding in a
144
+ // generated <script>. Recursive for plain objects and arrays.
145
+ function valueToJsLiteral(value, contextKey) {
146
+ if (value === undefined) {
147
+ return 'undefined';
148
+ }
149
+ if (value === null) {
150
+ return 'null';
151
+ }
152
+ const t = typeof value;
153
+ if (t === 'function') {
154
+ // Function.prototype.toString() returns the function's source.
155
+ // For arrow functions, methods, regular functions, and async
156
+ // variants this round-trips back to a real Function via the
157
+ // browser's parser. Wrap in parens so it's an expression in
158
+ // the object-literal value position (otherwise `function () {}`
159
+ // would be a function declaration and crash the parse).
160
+ return `(${value.toString()})`;
161
+ }
162
+ if (t === 'string' || t === 'number' || t === 'boolean') {
163
+ return JSON.stringify(value);
164
+ }
165
+ if (t === 'bigint') {
166
+ // BigInt literals use the `n` suffix.
167
+ return `${value.toString()}n`;
168
+ }
169
+ if (t === 'symbol') {
170
+ throw new TypeError(
171
+ `endowments[${JSON.stringify(contextKey)}] is a symbol; symbols cannot be transported to the sandbox`,
172
+ );
173
+ }
174
+ if (Array.isArray(value)) {
175
+ return `[${value.map((v, i) => valueToJsLiteral(v, `${contextKey}[${i}]`)).join(', ')}]`;
176
+ }
177
+ // Plain object. Skip Maps, Sets, Dates, RegExps, etc. for now;
178
+ // they need explicit transport encoding to round-trip cleanly.
179
+ const proto = Object.getPrototypeOf(value);
180
+ if (proto !== null && proto !== Object.prototype) {
181
+ throw new TypeError(
182
+ `endowments[${JSON.stringify(contextKey)}] is a non-plain-object (${value.constructor && value.constructor.name}); only plain objects, arrays, primitives, and functions are supported`,
183
+ );
184
+ }
185
+ const entries = Object.entries(value).map(
186
+ ([k, v]) => `${JSON.stringify(k)}: ${valueToJsLiteral(v, `${contextKey}.${k}`)}`,
187
+ );
188
+ return `{ ${entries.join(', ')} }`;
189
+ }
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>lws component</title>
6
+ </head>
7
+ <body>
8
+ <script src="/purify.js"></script>
9
+ <script src="/lws-sandbox.js"></script>
10
+ <script src="/_runtime/evaluator.js"></script>
11
+ <script src="/lwc-engine.js"></script>
12
+ <script src="/_bundle/component.js"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>lws eval</title>
6
+ </head>
7
+ <body>
8
+ <script src="/purify.js"></script>
9
+ <script src="/lws-sandbox.js"></script>
10
+ <script src="/_runtime/evaluator.js"></script>
11
+ </body>
12
+ </html>
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const STDIN_MARKER = '-';
5
+ const JS_EXTENSION_REGEX = /\.(m?js|cjs)$/i;
6
+
7
+ async function fileExists(p) {
8
+ try {
9
+ const stat = await fs.stat(p);
10
+ return stat.isFile();
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ function readStdin(stream = process.stdin) {
17
+ return new Promise((resolve, reject) => {
18
+ const chunks = [];
19
+ stream.setEncoding('utf8');
20
+ stream.on('data', (chunk) => chunks.push(chunk));
21
+ stream.on('end', () => resolve(chunks.join('')));
22
+ stream.on('error', reject);
23
+ });
24
+ }
25
+
26
+ // Resolve `value` to either file content or inline source.
27
+ //
28
+ // Rules, in order:
29
+ // 1. STDIN_MARKER (`-` or empty) → read from stdin.
30
+ // 2. Multi-line value → inline source (cannot be a file path).
31
+ // 3. Resolves to an existing file under cwd → read from disk.
32
+ // 4. Ends in .js / .mjs / .cjs → treat as a typo'd path and throw
33
+ // `file not found`. The extension is a strong intent signal; a
34
+ // missing file with that suffix is almost certainly a typo'd
35
+ // filename, not inline source.
36
+ // 5. Otherwise → inline source.
37
+ //
38
+ // This shape supports inline JS values that contain `/` (cookie path
39
+ // attributes, URLs, regex literals) without misclassifying them as
40
+ // path-shaped, while preserving typo-detection for explicit JS file
41
+ // extensions.
42
+ export async function resolveInput(value, { cwd = process.cwd(), stdin } = {}) {
43
+ if (value === STDIN_MARKER || value === '') {
44
+ const source = await readStdin(stdin);
45
+ return { source, origin: '<stdin>' };
46
+ }
47
+
48
+ if (value.includes('\n')) {
49
+ return { source: value, origin: '<inline>' };
50
+ }
51
+
52
+ const resolved = path.resolve(cwd, value);
53
+ if (await fileExists(resolved)) {
54
+ const source = await fs.readFile(resolved, 'utf8');
55
+ return { source, origin: resolved };
56
+ }
57
+
58
+ if (JS_EXTENSION_REGEX.test(value)) {
59
+ throw new Error(`file not found: ${resolved}`);
60
+ }
61
+
62
+ return { source: value, origin: '<inline>' };
63
+ }
@@ -0,0 +1,8 @@
1
+ // Re-import the LWC engine-dom surface and pin it on window.LWC so the
2
+ // compiled-component bundle on component.html can reference the engine as a
3
+ // system-mode global. This entry is bundled as an IIFE with no rollup `name`
4
+ // option, keeping the output a pure `(function () { ... }())` without a
5
+ // `var`-style wrapper.
6
+ import * as LWC from '@lwc/engine-dom';
7
+
8
+ window.LWC = LWC;
package/src/output.mjs ADDED
@@ -0,0 +1,168 @@
1
+ const VERBOSITY_QUIET = 0;
2
+ const VERBOSITY_NORMAL = 1;
3
+ const VERBOSITY_VERBOSE = 2;
4
+
5
+ const VERBOSITY_BY_NAME = {
6
+ quiet: VERBOSITY_QUIET,
7
+ normal: VERBOSITY_NORMAL,
8
+ verbose: VERBOSITY_VERBOSE,
9
+ };
10
+
11
+ export class Timing {
12
+ constructor(now = () => performance.now()) {
13
+ this.now = now;
14
+ this.marks = new Map();
15
+ this.spans = new Map();
16
+ }
17
+
18
+ start(label) {
19
+ this.marks.set(label, this.now());
20
+ }
21
+
22
+ end(label) {
23
+ const startedAt = this.marks.get(label);
24
+ if (startedAt === undefined) {
25
+ throw new Error(`Timing.end called without matching start: ${label}`);
26
+ }
27
+ const duration = this.now() - startedAt;
28
+ this.marks.delete(label);
29
+ this.spans.set(label, duration);
30
+ return duration;
31
+ }
32
+
33
+ toJSON() {
34
+ return Object.fromEntries(this.spans);
35
+ }
36
+ }
37
+
38
+ export class Output {
39
+ constructor({
40
+ json = false,
41
+ verbosity = 'normal',
42
+ stdout = process.stdout,
43
+ stderr = process.stderr,
44
+ } = {}) {
45
+ this.json = json;
46
+ const level = VERBOSITY_BY_NAME[verbosity];
47
+ if (level === undefined) {
48
+ throw new Error(`unknown verbosity: ${verbosity}`);
49
+ }
50
+ this.verbosity = level;
51
+ this.stdout = stdout;
52
+ this.stderr = stderr;
53
+ this.timing = new Timing();
54
+ // JSON mode buffers a single envelope and flushes it at exit. Text
55
+ // mode writes eagerly. Buffering matters because the runner emits
56
+ // the transformed source via result() right after compile, and a
57
+ // later step (sandbox throw, timeout, page error) may turn the
58
+ // run into a failure. JSON consumers expect exactly one envelope
59
+ // per invocation, so the success-then-failure sequence must
60
+ // collapse to a single fail() envelope.
61
+ this.pendingEnvelope = null;
62
+ // The compiled/transformed source, staged separately from the
63
+ // ok-vs-fail decision so it survives a later fail(). Without this,
64
+ // a run that compiles successfully and THEN throws would drop the
65
+ // compiled source from the envelope. Both success and failure
66
+ // envelopes carry it.
67
+ this.stagedResult = null;
68
+ this.hasStagedResult = false;
69
+ // The Completion Report (see completion.mjs), set by the runner once
70
+ // the run's outcome is known. Carried additively on the envelope; a
71
+ // null completion means none was produced (harness/infra failure).
72
+ this.completion = null;
73
+ }
74
+
75
+ info(message) {
76
+ if (this.json) return;
77
+ if (this.verbosity < VERBOSITY_NORMAL) return;
78
+ this.stderr.write(`${message}\n`);
79
+ }
80
+
81
+ debug(message) {
82
+ if (this.json) return;
83
+ if (this.verbosity < VERBOSITY_VERBOSE) return;
84
+ this.stderr.write(`${message}\n`);
85
+ }
86
+
87
+ error(message) {
88
+ this.stderr.write(`${message}\n`);
89
+ }
90
+
91
+ result(payload) {
92
+ if (this.json) {
93
+ // Buffer the success envelope; flush() emits it (or fail()
94
+ // replaces it before flush runs). Capturing payload now lets
95
+ // the runner stage the transformed source eagerly while
96
+ // deferring serialization until timing data is complete.
97
+ this.pendingEnvelope = { kind: 'ok', payload };
98
+ // Stage the payload independently of the ok-vs-fail decision so
99
+ // it survives a later fail(): the compiled source is never lost
100
+ // on the throw path.
101
+ this.stagedResult = payload;
102
+ this.hasStagedResult = true;
103
+ return;
104
+ }
105
+ if (this.verbosity < VERBOSITY_NORMAL) return;
106
+ const text = typeof payload === 'string' ? payload : JSON.stringify(payload);
107
+ this.stdout.write(`${text}\n`);
108
+ }
109
+
110
+ // Record the Completion Report for this run. Set by the runner once the
111
+ // outcome is known; carried additively on the JSON envelope. No-op effect
112
+ // in text mode beyond storage (the runner reads humanSummary() itself).
113
+ setCompletion(completion) {
114
+ this.completion = completion;
115
+ }
116
+
117
+ fail(error) {
118
+ if (this.json) {
119
+ // Replace any pending success envelope: a downstream throw
120
+ // means the run failed, regardless of whether result() was
121
+ // called earlier. The single emitted envelope reflects the
122
+ // final outcome.
123
+ this.pendingEnvelope = { kind: 'fail', error };
124
+ return;
125
+ }
126
+ this.stderr.write(`${error.message}\n`);
127
+ }
128
+
129
+ // Single sink for JSON mode. The runner calls flush() in its
130
+ // teardown path so the envelope reflects the most recent timing
131
+ // data (including total). In text mode flush() is a no-op:
132
+ // result() and fail() already wrote eagerly.
133
+ flush() {
134
+ if (!this.json) return;
135
+ if (this.pendingEnvelope === null) return;
136
+ let envelope;
137
+ if (this.pendingEnvelope.kind === 'ok') {
138
+ envelope = {
139
+ ok: true,
140
+ result: this.pendingEnvelope.payload,
141
+ timing: this.timing.toJSON(),
142
+ };
143
+ } else {
144
+ envelope = {
145
+ ok: false,
146
+ error: {
147
+ message: this.pendingEnvelope.error.message,
148
+ name: this.pendingEnvelope.error.name,
149
+ },
150
+ timing: this.timing.toJSON(),
151
+ };
152
+ // Carry the staged compiled source on the failure envelope too,
153
+ // so a compile-then-throw run does not lose it. `ok` already
154
+ // exposes it via `payload`; this only fills the fail path.
155
+ if (this.hasStagedResult) {
156
+ envelope.result = this.stagedResult;
157
+ }
158
+ }
159
+ // The Completion Report is additive: present on both ok and fail
160
+ // envelopes when the runner recorded one. `ok`/`result`/`error` keep
161
+ // their existing meaning so current consumers do not break.
162
+ if (this.completion !== null) {
163
+ envelope.completion = this.completion;
164
+ }
165
+ this.pendingEnvelope = null;
166
+ this.stdout.write(`${JSON.stringify(envelope)}\n`);
167
+ }
168
+ }