@linguacode/cli 1.5.1 → 1.6.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 (2) hide show
  1. package/bin/lingua.cjs +1870 -1176
  2. package/package.json +1 -1
package/bin/lingua.cjs CHANGED
@@ -35,14 +35,16 @@ __export(lingua_exports, {
35
35
  });
36
36
  module.exports = __toCommonJS(lingua_exports);
37
37
 
38
- // src/cli/exit-codes.ts
39
- var CLI_EXIT_CODES = {
40
- ok: 0,
41
- userInputError: 1,
42
- runtimeError: 2,
43
- unsupportedCapability: 3,
44
- internal: 4
45
- };
38
+ // src/shared/contentHash.ts
39
+ async function computeContentHash(content) {
40
+ const subtle = globalThis.crypto?.subtle;
41
+ if (!subtle || typeof subtle.digest !== "function") {
42
+ throw new Error("computeContentHash: Web Crypto unavailable (no globalThis.crypto.subtle)");
43
+ }
44
+ const bytes = new TextEncoder().encode(content);
45
+ const digest = await subtle.digest("SHA-256", bytes);
46
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
47
+ }
46
48
 
47
49
  // src/shared/utf8.ts
48
50
  var encoder = new TextEncoder();
@@ -51,15 +53,20 @@ function utf8ByteLength(value) {
51
53
  return encoder.encode(value).byteLength;
52
54
  }
53
55
  function truncateUtf8(value, maxBytes) {
54
- if (maxBytes <= 0) return "";
56
+ const budget = Math.floor(maxBytes);
57
+ if (!(budget > 0)) return "";
55
58
  const bytes = encoder.encode(value);
56
- if (bytes.byteLength <= maxBytes) return value;
59
+ if (bytes.byteLength <= budget) return value;
60
+ return decodePrefix(bytes, budget);
61
+ }
62
+ function decodePrefix(bytes, maxBytes) {
57
63
  let end = maxBytes;
58
64
  while (end > 0 && (bytes[end] & 192) === 128) end -= 1;
59
65
  return decoder.decode(bytes.subarray(0, end));
60
66
  }
61
67
 
62
68
  // src/shared/runCapsule.ts
69
+ var MAX_STREAM_BYTES = 1048576;
63
70
  var MAX_CAPSULE_BYTES = 4194304;
64
71
  function isRecord(value) {
65
72
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -169,6 +176,13 @@ function parseRunCapsule(json) {
169
176
  };
170
177
  }
171
178
  }
179
+ if (typeof candidate.capsuleId !== "string" || typeof candidate.createdAt !== "string" || typeof candidate.appVersion !== "string") {
180
+ return {
181
+ ok: false,
182
+ reason: "invalid-field-type",
183
+ detail: "capsuleId / createdAt / appVersion"
184
+ };
185
+ }
172
186
  if (!isRecord(candidate.tab)) {
173
187
  return {
174
188
  ok: false,
@@ -230,7 +244,8 @@ function parseRunCapsule(json) {
230
244
  };
231
245
  }
232
246
  const environment = candidate.environment;
233
- if (environment.platform !== "web" && environment.platform !== "desktop" || typeof environment.runner !== "string") {
247
+ const git = environment.git;
248
+ if (environment.platform !== "web" && environment.platform !== "desktop" || typeof environment.runner !== "string" || git !== void 0 && (!isRecord(git) || git.branch !== void 0 && typeof git.branch !== "string" || git.commit !== void 0 && typeof git.commit !== "string")) {
234
249
  return {
235
250
  ok: false,
236
251
  reason: "invalid-field-type",
@@ -267,7 +282,7 @@ function parseRunCapsule(json) {
267
282
  };
268
283
  }
269
284
  const privacy = candidate.privacy;
270
- if (typeof privacy.redactionVersion !== "string" || !Array.isArray(privacy.omittedFields)) {
285
+ if (typeof privacy.redactionVersion !== "string" || !Array.isArray(privacy.omittedFields) || privacy.omittedFields.some((field) => typeof field !== "string")) {
271
286
  return {
272
287
  ok: false,
273
288
  reason: "invalid-field-type",
@@ -280,560 +295,146 @@ function summarizeRunCapsule(capsule) {
280
295
  const ms = Math.max(0, Math.round(capsule.result.durationMs));
281
296
  return `${capsule.tab.language} \xB7 ${capsule.result.status} \xB7 ${ms}ms \xB7 ${capsule.createdAt}`;
282
297
  }
283
- async function computeContentHash(content) {
284
- const subtle = globalThis.crypto?.subtle;
285
- if (!subtle || typeof subtle.digest !== "function") {
286
- throw new Error(
287
- "computeContentHash: Web Crypto unavailable (no globalThis.crypto.subtle)"
288
- );
289
- }
290
- const bytes = new TextEncoder().encode(content);
291
- const digest = await subtle.digest("SHA-256", bytes);
292
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
298
+
299
+ // src/shared/capsuleRegressionSuite.ts
300
+ var MAX_REGRESSION_SUITE_BYTES = 4 * 1024 * 1024;
301
+ var MAX_REGRESSION_CASES = 20;
302
+ function isRegressionTarget(target) {
303
+ return typeof target === "string" && target.length > 0 && target.length <= 4096 && !Array.from(target).some((character) => character.charCodeAt(0) < 32) && !/^[\\/]|^[a-zA-Z]:/.test(target) && !target.split(/[\\/]/).some((part) => part === ".." || part === "." || part === "");
304
+ }
305
+ function parseCapsuleRegressionSuite(raw) {
306
+ if (utf8ByteLength(raw) > MAX_REGRESSION_SUITE_BYTES)
307
+ return { ok: false, reason: "suite-too-large" };
308
+ let value;
309
+ try {
310
+ value = JSON.parse(raw);
311
+ } catch {
312
+ return { ok: false, reason: "invalid-suite-json" };
313
+ }
314
+ if (!value || value.kind !== "lingua-regression-suite" || value.suiteVersion !== 1 || Object.keys(value).some((key) => !["kind", "suiteVersion", "cases"].includes(key)) || !Array.isArray(value.cases) || value.cases.length === 0 || value.cases.length > MAX_REGRESSION_CASES)
315
+ return { ok: false, reason: "invalid-suite" };
316
+ const cases = [];
317
+ const ids = /* @__PURE__ */ new Set();
318
+ for (const entry of value.cases) {
319
+ if (!entry || Object.keys(entry).some((key) => !["id", "name", "target", "baseline"].includes(key)) || typeof entry.id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(entry.id) || ids.has(entry.id) || typeof entry.name !== "string" || !entry.name.trim() || entry.name.length > 200 || !isRegressionTarget(entry.target))
320
+ return { ok: false, reason: "invalid-suite-case" };
321
+ const baseline = parseRunCapsule(JSON.stringify(entry.baseline));
322
+ if (!baseline.ok) return { ok: false, reason: `invalid-baseline:${baseline.reason}` };
323
+ ids.add(entry.id);
324
+ cases.push({ id: entry.id, name: entry.name, target: entry.target, baseline: baseline.value });
325
+ }
326
+ return { ok: true, suite: { kind: "lingua-regression-suite", suiteVersion: 1, cases } };
293
327
  }
294
328
 
295
- // src/cli/presentation.ts
296
- var ANSI = {
297
- reset: "\x1B[0m",
298
- bold: "\x1B[1m",
299
- cyan: "\x1B[36m",
300
- green: "\x1B[32m",
301
- red: "\x1B[31m",
302
- yellow: "\x1B[33m"
329
+ // src/cli/exit-codes.ts
330
+ var CLI_EXIT_CODES = {
331
+ ok: 0,
332
+ userInputError: 1,
333
+ runtimeError: 2,
334
+ unsupportedCapability: 3,
335
+ internal: 4,
336
+ verificationFailed: 5,
337
+ verificationInconclusive: 6
303
338
  };
304
- function shouldUseColor(io, mode = "auto", stream) {
305
- if (mode === "always") return true;
306
- if (mode === "never") return false;
307
- if (io.getEnvironmentValue("NO_COLOR") !== void 0) return false;
308
- return stream === "stdout" ? io.stdoutSupportsColor : io.stderrSupportsColor;
309
- }
310
- function styleCliText(io, mode, stream, style, text) {
311
- if (!shouldUseColor(io, mode, stream)) return text;
312
- return `${ANSI[style]}${text}${ANSI.reset}`;
313
- }
314
- function emitCliFailure(io, options, failure) {
315
- if (options.json) {
316
- io.writeStdout(
317
- `${JSON.stringify({ ok: false, ...failure.extra ?? {}, reason: failure.reason, detail: failure.detail })}
318
- `
319
- );
320
- return;
321
- }
322
- if (options.quiet) return;
323
- const label = styleCliText(io, options.color, "stderr", "bold", failure.label);
324
- const marker = styleCliText(io, options.color, "stderr", "red", `error[${failure.reason}]`);
325
- io.writeStderr(`${label}: ${marker}: ${failure.detail}
326
- `);
327
- }
328
- function renderCliHelp(io, mode, helpText) {
329
- if (!shouldUseColor(io, mode, "stdout")) return helpText;
330
- const lines = helpText.split("\n");
331
- return lines.map((line, index) => {
332
- if (index === 0) return styleCliText(io, mode, "stdout", "cyan", line);
333
- if (/^(Usage|Commands|Flags|Exit codes|Examples):$/u.test(line)) {
334
- return styleCliText(io, mode, "stdout", "bold", line);
339
+
340
+ // src/cli/runtime/regressionTargets.ts
341
+ var import_node_path3 = __toESM(require("node:path"));
342
+ var import_promises2 = require("node:fs/promises");
343
+ var import_node_fs2 = require("node:fs");
344
+
345
+ // src/cli/runtime/targets.ts
346
+ var import_node_fs = require("node:fs");
347
+ var import_promises = require("node:fs/promises");
348
+ var import_node_os = __toESM(require("node:os"));
349
+ var import_node_path2 = __toESM(require("node:path"));
350
+ var import_node_sea = require("node:sea");
351
+
352
+ // node_modules/acorn/dist/acorn.mjs
353
+ var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
354
+ var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
355
+ var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
356
+ var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
357
+ var reservedWords = {
358
+ 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
359
+ 5: "class enum extends super const export import",
360
+ 6: "enum",
361
+ strict: "implements interface let package private protected public static yield",
362
+ strictBind: "eval arguments"
363
+ };
364
+ var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
365
+ var keywords$1 = {
366
+ 5: ecma5AndLessKeywords,
367
+ "5module": ecma5AndLessKeywords + " export import",
368
+ 6: ecma5AndLessKeywords + " const class extends export import super"
369
+ };
370
+ var keywordRelationalOperator = /^in(stanceof)?$/;
371
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
372
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
373
+ function isInAstralSet(code, set) {
374
+ var pos = 65536;
375
+ for (var i2 = 0; i2 < set.length; i2 += 2) {
376
+ pos += set[i2];
377
+ if (pos > code) {
378
+ return false;
335
379
  }
336
- return line;
337
- }).join("\n");
338
- }
339
- function renderCliSuccess(io, mode, text) {
340
- return styleCliText(io, mode, "stdout", "green", text);
380
+ pos += set[i2 + 1];
381
+ if (pos >= code) {
382
+ return true;
383
+ }
384
+ }
385
+ return false;
341
386
  }
342
- function renderCliNotice(io, mode, text, tone = "warning") {
343
- return styleCliText(io, mode, "stderr", tone === "success" ? "green" : "yellow", text);
387
+ function isIdentifierStart(code, astral) {
388
+ if (code < 65) {
389
+ return code === 36;
390
+ }
391
+ if (code < 91) {
392
+ return true;
393
+ }
394
+ if (code < 97) {
395
+ return code === 95;
396
+ }
397
+ if (code < 123) {
398
+ return true;
399
+ }
400
+ if (code <= 65535) {
401
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
402
+ }
403
+ if (astral === false) {
404
+ return false;
405
+ }
406
+ return isInAstralSet(code, astralIdentifierStartCodes);
344
407
  }
345
-
346
- // src/cli/runtime/environment.ts
347
- var COMMON_KEYS = ["PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "TEMP", "TMP"];
348
- var TOOLCHAIN_KEYS = [
349
- "NODE_PATH",
350
- "NPM_CONFIG_CACHE",
351
- "NPM_CONFIG_PREFIX",
352
- "PYTHON",
353
- "VIRTUAL_ENV",
354
- "PYTHONPATH",
355
- "PYENV_VERSION",
356
- "GOROOT",
357
- "GOPATH",
358
- "GOMODCACHE",
359
- "GOCACHE",
360
- "GOTMPDIR",
361
- "GOPROXY",
362
- "GOSUMDB",
363
- "GOFLAGS",
364
- "GOTOOLCHAIN",
365
- "CARGO_HOME",
366
- "RUSTUP_HOME",
367
- "RUSTUP_TOOLCHAIN",
368
- "RUSTC",
369
- "CARGO",
370
- "GEM_HOME",
371
- "GEM_PATH",
372
- "BUNDLE_GEMFILE",
373
- "RBENV_VERSION",
374
- "RBENV_ROOT",
375
- "ASDF_RUBY_VERSION"
376
- ];
377
- var WINDOWS_KEYS = ["SYSTEMROOT", "USERPROFILE", "PATHEXT", "COMSPEC"];
378
- var BLOCKED_EXPLICIT_KEYS = /* @__PURE__ */ new Set([
379
- "LD_PRELOAD",
380
- "LD_AUDIT",
381
- "LD_LIBRARY_PATH",
382
- "DYLD_INSERT_LIBRARIES",
383
- "DYLD_LIBRARY_PATH",
384
- "DYLD_FRAMEWORK_PATH",
385
- "NODE_OPTIONS"
386
- ]);
387
- var CliEnvironmentError = class extends Error {
388
- constructor(key) {
389
- super(`Environment variable ${key} is blocked because it can inject code into the runtime.`);
390
- this.key = key;
391
- this.name = "CliEnvironmentError";
408
+ function isIdentifierChar(code, astral) {
409
+ if (code < 48) {
410
+ return code === 36;
392
411
  }
393
- key;
394
- reason = "blocked-environment-variable";
395
- };
396
- function buildCliRuntimeEnvironment(explicit) {
397
- const result = {};
398
- const keys = [
399
- ...COMMON_KEYS,
400
- ...TOOLCHAIN_KEYS,
401
- ...process.platform === "win32" ? WINDOWS_KEYS : []
402
- ];
403
- for (const key of keys) {
404
- const value = process.env[key];
405
- if (typeof value === "string" && value.length > 0) result[key] = value;
412
+ if (code < 58) {
413
+ return true;
406
414
  }
407
- for (const { key, value } of explicit) {
408
- if (BLOCKED_EXPLICIT_KEYS.has(key.toUpperCase())) {
409
- throw new CliEnvironmentError(key);
410
- }
411
- result[key] = value;
415
+ if (code < 65) {
416
+ return false;
412
417
  }
413
- return result;
418
+ if (code < 91) {
419
+ return true;
420
+ }
421
+ if (code < 97) {
422
+ return code === 95;
423
+ }
424
+ if (code < 123) {
425
+ return true;
426
+ }
427
+ if (code <= 65535) {
428
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
429
+ }
430
+ if (astral === false) {
431
+ return false;
432
+ }
433
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
414
434
  }
415
-
416
- // src/cli/runtime/execution.ts
417
- var import_node_child_process = require("node:child_process");
418
- var import_promises = require("node:fs/promises");
419
-
420
- // src/shared/runnerLimits.ts
421
- var MAX_NATIVE_STDERR_BYTES = 1024 * 1024;
422
- var MAX_STDIN_WRITE_BYTES = 256 * 1024;
423
- var MAX_COMPILE_OUTPUT_BYTES = 1024 * 1024;
424
- var MAX_GO_WASM_BYTES = 10 * 1024 * 1024;
425
-
426
- // src/cli/runtime/runtimeRecovery.ts
427
- var import_node_path = __toESM(require("node:path"));
428
- var CLI_RUNTIME_HELP_URL = "https://linguacode.dev/cli/troubleshooting#missing-runtimes";
429
- var RUNTIMES = {
430
- python: {
431
- name: "Python",
432
- verifyExecutable: "python3",
433
- homebrewFormula: "python",
434
- installGuide: "https://www.python.org/downloads/"
435
- },
436
- go: {
437
- name: "Go",
438
- verifyExecutable: "go",
439
- homebrewFormula: "go",
440
- installGuide: "https://go.dev/doc/install"
441
- },
442
- rust: {
443
- name: "Rust",
444
- verifyExecutable: "rustc",
445
- homebrewFormula: "rust",
446
- installGuide: "https://www.rust-lang.org/tools/install"
447
- },
448
- ruby: {
449
- name: "Ruby",
450
- verifyExecutable: "ruby",
451
- homebrewFormula: "ruby",
452
- installGuide: "https://www.ruby-lang.org/en/documentation/installation/"
453
- },
454
- lua: {
455
- name: "Lua",
456
- verifyExecutable: "lua",
457
- homebrewFormula: "lua",
458
- installGuide: "https://www.lua.org/download.html"
459
- },
460
- node: {
461
- name: "Node.js",
462
- verifyExecutable: "node",
463
- homebrewFormula: "node@24",
464
- installGuide: "https://nodejs.org/en/download"
465
- }
466
- };
467
- function buildMissingRuntimeRecovery(command, runtime, platform = process.platform) {
468
- const executable = executableName(command);
469
- const key = runtimeKey(executable, runtime);
470
- const descriptor = RUNTIMES[key] ?? {
471
- name: runtime || executable,
472
- verifyExecutable: executable,
473
- installGuide: CLI_RUNTIME_HELP_URL
474
- };
475
- const verifyExecutable = key === "python" ? executable : descriptor.verifyExecutable;
476
- const installCommand = platform === "darwin" && descriptor.homebrewFormula ? `brew install ${descriptor.homebrewFormula}` : void 0;
477
- const verifyCommand = `${verifyExecutable} --version`;
478
- const recovery = {
479
- runtime: descriptor.name,
480
- executable,
481
- ...installCommand ? { installCommand } : {},
482
- installGuide: descriptor.installGuide,
483
- verifyCommand
484
- };
485
- const install = installCommand ? `Install on macOS with Homebrew:
486
- ${installCommand}` : `Install ${descriptor.name} for your operating system:
487
- ${descriptor.installGuide}`;
488
- const guide = descriptor.installGuide === CLI_RUNTIME_HELP_URL ? "" : `
489
- Setup guide:
490
- ${descriptor.installGuide}`;
491
- return {
492
- detail: [
493
- `${descriptor.name} is required for this run, but Lingua could not find \`${executable}\` on PATH.`,
494
- install,
495
- `Verify the setup:
496
- ${verifyCommand}`,
497
- `Then retry the same Lingua command.${guide}`,
498
- `Lingua runtime help:
499
- ${CLI_RUNTIME_HELP_URL}`
500
- ].join("\n\n"),
501
- recovery
502
- };
503
- }
504
- function executableName(command) {
505
- const basename = import_node_path.default.basename(command).toLowerCase();
506
- return basename.replace(/\.exe$/u, "").replace(/\.cmd$/u, "");
507
- }
508
- function runtimeKey(executable, runtime) {
509
- const normalizedRuntime = runtime.toLowerCase();
510
- if (executable === "py" || executable.startsWith("python") || normalizedRuntime.startsWith("python")) {
511
- return "python";
512
- }
513
- if (executable === "go" || normalizedRuntime.startsWith("go")) return "go";
514
- if (["rustc", "cargo"].includes(executable) || normalizedRuntime.startsWith("rust")) return "rust";
515
- if (executable === "ruby" || normalizedRuntime.startsWith("ruby")) return "ruby";
516
- if (executable === "lua" || normalizedRuntime.startsWith("lua")) return "lua";
517
- if (["node", "npm", "npx"].includes(executable) || normalizedRuntime.startsWith("node")) {
518
- return "node";
519
- }
520
- return normalizedRuntime;
521
- }
522
-
523
- // src/cli/runtime/execution.ts
524
- var DEFAULT_CLI_RUN_TIMEOUT_MS = 3e4;
525
- var MIN_CLI_RUN_TIMEOUT_MS = 100;
526
- var MAX_CLI_RUN_TIMEOUT_MS = 5 * 6e4;
527
- var KILL_ESCALATION_MS = 1500;
528
- var OUTPUT_TRUNCATION_MARKER = "\n[output truncated by Lingua CLI]\n";
529
- function clampCliRunTimeout(value) {
530
- if (value === void 0 || !Number.isFinite(value)) return DEFAULT_CLI_RUN_TIMEOUT_MS;
531
- return Math.min(MAX_CLI_RUN_TIMEOUT_MS, Math.max(MIN_CLI_RUN_TIMEOUT_MS, Math.floor(value)));
532
- }
533
- async function executeCliPlan(plan, options) {
534
- const startedAt = Date.now();
535
- const timeoutMs = clampCliRunTimeout(options.timeoutMs);
536
- const stdout = new CappedOutput();
537
- const stderr = new CappedOutput();
538
- try {
539
- for (const step of plan.steps) {
540
- const elapsed = Date.now() - startedAt;
541
- const remaining = Math.max(1, timeoutMs - elapsed);
542
- const result = await runStep(step, {
543
- cwd: plan.cwd,
544
- env: options.env,
545
- timeoutMs: remaining,
546
- stdin: step.kind === "execute" ? options.stdin : void 0,
547
- onStdout: (chunk) => forwardOutput(stdout, chunk, options.onStdout),
548
- onStderr: (chunk) => forwardOutput(stderr, chunk, options.onStderr)
549
- });
550
- if (result.spawnError) {
551
- const missing = result.spawnError.code === "ENOENT";
552
- const missingRuntime = missing ? buildMissingRuntimeRecovery(step.command, plan.runtime) : void 0;
553
- return finish(plan, startedAt, result, stdout.value, stderr.value, "error", {
554
- reason: missing ? "missing-runtime" : "spawn-failed",
555
- detail: missingRuntime?.detail ?? `Failed to start ${step.command}: ${result.spawnError.message}`,
556
- ...missingRuntime ? { recovery: missingRuntime.recovery } : {}
557
- });
558
- }
559
- if (result.timedOut) {
560
- return finish(plan, startedAt, result, stdout.value, stderr.value, "timeout", {
561
- reason: "timeout",
562
- detail: `Run timed out after ${timeoutMs}ms.`
563
- });
564
- }
565
- if (result.stopped) {
566
- return finish(plan, startedAt, result, stdout.value, stderr.value, "stopped", {
567
- reason: "stopped",
568
- detail: "Run stopped by SIGINT or SIGTERM."
569
- });
570
- }
571
- if (result.exitCode !== 0) {
572
- return finish(plan, startedAt, result, stdout.value, stderr.value, "error", {
573
- reason: step.kind === "prepare" ? "prepare-failed" : "non-zero-exit",
574
- detail: step.kind === "prepare" ? `Runtime preparation exited with code ${result.exitCode ?? result.signal ?? "unknown"}.` : `Program exited with code ${result.exitCode ?? result.signal ?? "unknown"}.`
575
- });
576
- }
577
- }
578
- const last = plan.steps.at(-1);
579
- return {
580
- status: "success",
581
- target: plan.displayTarget,
582
- runtime: plan.runtime,
583
- durationMs: Date.now() - startedAt,
584
- exitCode: 0,
585
- signal: null,
586
- stdout: stdout.value,
587
- stderr: stderr.value,
588
- ...last ? {} : { detail: "Execution plan contained no steps." }
589
- };
590
- } finally {
591
- await Promise.all(
592
- (plan.cleanupPaths ?? []).map(
593
- (cleanupPath) => (0, import_promises.rm)(cleanupPath, { recursive: true, force: true }).catch(() => {
594
- })
595
- )
596
- );
597
- }
598
- }
599
- function finish(plan, startedAt, result, stdout, stderr, status, diagnostic) {
600
- return {
601
- status,
602
- target: plan.displayTarget,
603
- runtime: plan.runtime,
604
- durationMs: Date.now() - startedAt,
605
- exitCode: result.exitCode,
606
- signal: result.signal,
607
- stdout,
608
- stderr,
609
- ...diagnostic
610
- };
611
- }
612
- function runStep(step, options) {
613
- return new Promise((resolve) => {
614
- const startedAt = Date.now();
615
- let child;
616
- let settled = false;
617
- let timedOut = false;
618
- let stopped = false;
619
- let escalationTimer = null;
620
- const finishStep = (exitCode, signal, spawnError) => {
621
- if (settled) return;
622
- settled = true;
623
- clearTimeout(timeoutTimer);
624
- if (escalationTimer) clearTimeout(escalationTimer);
625
- process.off("SIGINT", onSigint);
626
- process.off("SIGTERM", onSigterm);
627
- resolve({
628
- exitCode,
629
- signal,
630
- durationMs: Date.now() - startedAt,
631
- timedOut,
632
- stopped,
633
- ...spawnError ? { spawnError } : {}
634
- });
635
- };
636
- const terminate = (reason) => {
637
- if (settled) return;
638
- if (reason === "timeout") timedOut = true;
639
- else stopped = true;
640
- killProcessTree(child, "SIGTERM");
641
- escalationTimer ??= setTimeout(() => {
642
- killProcessTree(child, "SIGKILL");
643
- }, KILL_ESCALATION_MS);
644
- };
645
- const onSigint = () => terminate("stopped");
646
- const onSigterm = () => terminate("stopped");
647
- try {
648
- child = (0, import_node_child_process.spawn)(step.command, step.args, {
649
- cwd: options.cwd,
650
- env: options.env,
651
- stdio: ["pipe", "pipe", "pipe"],
652
- detached: process.platform !== "win32",
653
- windowsHide: true
654
- });
655
- } catch (error) {
656
- const spawnError = asErrno(error);
657
- resolve({
658
- exitCode: null,
659
- signal: null,
660
- durationMs: Date.now() - startedAt,
661
- timedOut,
662
- stopped,
663
- spawnError
664
- });
665
- return;
666
- }
667
- const timeoutTimer = setTimeout(() => terminate("timeout"), options.timeoutMs);
668
- process.once("SIGINT", onSigint);
669
- process.once("SIGTERM", onSigterm);
670
- child.stdin.on("error", () => {
671
- });
672
- try {
673
- if (options.stdin) child.stdin.write(options.stdin);
674
- child.stdin.end();
675
- } catch {
676
- }
677
- child.stdout.setEncoding("utf8");
678
- child.stderr.setEncoding("utf8");
679
- child.stdout.on("data", options.onStdout);
680
- child.stderr.on("data", options.onStderr);
681
- child.once("error", (error) => finishStep(null, null, asErrno(error)));
682
- child.once("close", (code, signal) => finishStep(code, signal));
683
- });
684
- }
685
- var CappedOutput = class {
686
- value = "";
687
- truncated = false;
688
- /** Returns exactly the bounded fragment newly accepted from this chunk. */
689
- append(chunk) {
690
- if (this.truncated || !chunk) return "";
691
- const currentBytes = Buffer.byteLength(this.value, "utf8");
692
- const chunkBytes = Buffer.byteLength(chunk, "utf8");
693
- const markerBytes = Buffer.byteLength(OUTPUT_TRUNCATION_MARKER, "utf8");
694
- const payloadCap = MAX_NATIVE_STDERR_BYTES - markerBytes;
695
- if (currentBytes + chunkBytes <= payloadCap) {
696
- this.value += chunk;
697
- return chunk;
698
- }
699
- const remainingBytes = Math.max(0, payloadCap - currentBytes);
700
- const prefix = truncateUtf8(chunk, remainingBytes);
701
- const accepted = `${prefix}${OUTPUT_TRUNCATION_MARKER}`;
702
- this.value += accepted;
703
- this.truncated = true;
704
- return accepted;
705
- }
706
- };
707
- function forwardOutput(output, chunk, listener) {
708
- const accepted = output.append(chunk);
709
- if (accepted) listener?.(accepted);
710
- }
711
- function asErrno(error) {
712
- return error instanceof Error ? error : new Error(String(error));
713
- }
714
- function killProcessTree(child, signal) {
715
- const pid = child.pid;
716
- if (process.platform === "win32") {
717
- if (signal === "SIGKILL" && typeof pid === "number" && pid > 0) {
718
- try {
719
- (0, import_node_child_process.execFile)("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
720
- });
721
- return;
722
- } catch {
723
- }
724
- }
725
- try {
726
- child.kill(signal);
727
- } catch {
728
- }
729
- return;
730
- }
731
- if (typeof pid === "number" && pid > 0) {
732
- try {
733
- process.kill(-pid, signal);
734
- return;
735
- } catch {
736
- }
737
- }
738
- try {
739
- child.kill(signal);
740
- } catch {
741
- }
742
- }
743
-
744
- // src/cli/runtime/targets.ts
745
- var import_node_fs = require("node:fs");
746
- var import_promises2 = require("node:fs/promises");
747
- var import_node_os = __toESM(require("node:os"));
748
- var import_node_path3 = __toESM(require("node:path"));
749
- var import_node_sea = require("node:sea");
750
-
751
- // node_modules/acorn/dist/acorn.mjs
752
- var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
753
- var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
754
- var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
755
- var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
756
- var reservedWords = {
757
- 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
758
- 5: "class enum extends super const export import",
759
- 6: "enum",
760
- strict: "implements interface let package private protected public static yield",
761
- strictBind: "eval arguments"
762
- };
763
- var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
764
- var keywords$1 = {
765
- 5: ecma5AndLessKeywords,
766
- "5module": ecma5AndLessKeywords + " export import",
767
- 6: ecma5AndLessKeywords + " const class extends export import super"
768
- };
769
- var keywordRelationalOperator = /^in(stanceof)?$/;
770
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
771
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
772
- function isInAstralSet(code, set) {
773
- var pos = 65536;
774
- for (var i2 = 0; i2 < set.length; i2 += 2) {
775
- pos += set[i2];
776
- if (pos > code) {
777
- return false;
778
- }
779
- pos += set[i2 + 1];
780
- if (pos >= code) {
781
- return true;
782
- }
783
- }
784
- return false;
785
- }
786
- function isIdentifierStart(code, astral) {
787
- if (code < 65) {
788
- return code === 36;
789
- }
790
- if (code < 91) {
791
- return true;
792
- }
793
- if (code < 97) {
794
- return code === 95;
795
- }
796
- if (code < 123) {
797
- return true;
798
- }
799
- if (code <= 65535) {
800
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
801
- }
802
- if (astral === false) {
803
- return false;
804
- }
805
- return isInAstralSet(code, astralIdentifierStartCodes);
806
- }
807
- function isIdentifierChar(code, astral) {
808
- if (code < 48) {
809
- return code === 36;
810
- }
811
- if (code < 58) {
812
- return true;
813
- }
814
- if (code < 65) {
815
- return false;
816
- }
817
- if (code < 91) {
818
- return true;
819
- }
820
- if (code < 97) {
821
- return code === 95;
822
- }
823
- if (code < 123) {
824
- return true;
825
- }
826
- if (code <= 65535) {
827
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
828
- }
829
- if (astral === false) {
830
- return false;
831
- }
832
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
833
- }
834
- var TokenType = function TokenType2(label, conf) {
435
+ var TokenType = function TokenType2(label2, conf) {
835
436
  if (conf === void 0) conf = {};
836
- this.label = label;
437
+ this.label = label2;
837
438
  this.keyword = conf.keyword;
838
439
  this.beforeExpr = !!conf.beforeExpr;
839
440
  this.startsExpr = !!conf.startsExpr;
@@ -1979,8 +1580,8 @@ pp$8.parseEmptyStatement = function(node) {
1979
1580
  };
1980
1581
  pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
1981
1582
  for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
1982
- var label = list2[i$1];
1983
- if (label.name === maybeName) {
1583
+ var label2 = list2[i$1];
1584
+ if (label2.name === maybeName) {
1984
1585
  this.raise(expr.start, "Label '" + maybeName + "' is already declared");
1985
1586
  }
1986
1587
  }
@@ -6380,527 +5981,1162 @@ pp.readHexChar = function(len) {
6380
5981
  if (n === null) {
6381
5982
  this.invalidStringToken(codePos, "Bad character escape sequence");
6382
5983
  }
6383
- return n;
5984
+ return n;
5985
+ };
5986
+ pp.readWord1 = function() {
5987
+ this.containsEsc = false;
5988
+ var word = "", first = true, chunkStart = this.pos;
5989
+ var astral = this.options.ecmaVersion >= 6;
5990
+ while (this.pos < this.input.length) {
5991
+ var ch = this.fullCharCodeAtPos();
5992
+ if (isIdentifierChar(ch, astral)) {
5993
+ this.pos += ch <= 65535 ? 1 : 2;
5994
+ } else if (ch === 92) {
5995
+ this.containsEsc = true;
5996
+ word += this.input.slice(chunkStart, this.pos);
5997
+ var escStart = this.pos;
5998
+ if (this.input.charCodeAt(++this.pos) !== 117) {
5999
+ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
6000
+ }
6001
+ ++this.pos;
6002
+ var esc = this.readCodePoint();
6003
+ if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
6004
+ this.invalidStringToken(escStart, "Invalid Unicode escape");
6005
+ }
6006
+ word += codePointToString(esc);
6007
+ chunkStart = this.pos;
6008
+ } else {
6009
+ break;
6010
+ }
6011
+ first = false;
6012
+ }
6013
+ return word + this.input.slice(chunkStart, this.pos);
6014
+ };
6015
+ pp.readWord = function() {
6016
+ var word = this.readWord1();
6017
+ var type = types$1.name;
6018
+ if (this.keywords.test(word)) {
6019
+ type = keywords[word];
6020
+ }
6021
+ return this.finishToken(type, word);
6022
+ };
6023
+ var version = "8.18.0";
6024
+ Parser.acorn = {
6025
+ Parser,
6026
+ version,
6027
+ defaultOptions,
6028
+ Position,
6029
+ SourceLocation,
6030
+ getLineInfo,
6031
+ Node,
6032
+ TokenType,
6033
+ tokTypes: types$1,
6034
+ keywordTypes: keywords,
6035
+ TokContext,
6036
+ tokContexts: types,
6037
+ isIdentifierChar,
6038
+ isIdentifierStart,
6039
+ Token,
6040
+ isNewLine,
6041
+ lineBreak,
6042
+ lineBreakG,
6043
+ nonASCIIwhitespace
6044
+ };
6045
+ function parse3(input, options) {
6046
+ return Parser.parse(input, options);
6047
+ }
6048
+
6049
+ // src/shared/nodeSourceMode.ts
6050
+ function isAcornNode(value) {
6051
+ return typeof value === "object" && value !== null && typeof value.type === "string";
6052
+ }
6053
+ function isFunctionScope(node) {
6054
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
6055
+ }
6056
+ function nodeContainsModuleOnlyExpression(node) {
6057
+ if (node.type === "AwaitExpression") return true;
6058
+ if (node.type === "MetaProperty") {
6059
+ const meta = node.meta;
6060
+ const property = node.property;
6061
+ if (meta?.name === "import" && property?.name === "meta") return true;
6062
+ }
6063
+ if (isFunctionScope(node)) return false;
6064
+ for (const value of Object.values(node)) {
6065
+ if (Array.isArray(value)) {
6066
+ if (value.some((entry) => isAcornNode(entry) && nodeContainsModuleOnlyExpression(entry))) {
6067
+ return true;
6068
+ }
6069
+ } else if (isAcornNode(value) && nodeContainsModuleOnlyExpression(value)) {
6070
+ return true;
6071
+ }
6072
+ }
6073
+ return false;
6074
+ }
6075
+ function sourceRequiresModuleInput(source) {
6076
+ try {
6077
+ const program = parse3(source, {
6078
+ allowHashBang: true,
6079
+ ecmaVersion: "latest",
6080
+ sourceType: "module"
6081
+ });
6082
+ return program.body.some((statement) => {
6083
+ if (statement.type === "ImportDeclaration" || statement.type === "ExportAllDeclaration" || statement.type === "ExportDefaultDeclaration" || statement.type === "ExportNamedDeclaration") {
6084
+ return true;
6085
+ }
6086
+ return nodeContainsModuleOnlyExpression(statement);
6087
+ });
6088
+ } catch {
6089
+ return false;
6090
+ }
6091
+ }
6092
+
6093
+ // src/shared/python/interpreter.ts
6094
+ var import_node_path = __toESM(require("node:path"), 1);
6095
+ function pythonCommandCandidates(platform) {
6096
+ return platform === "win32" ? ["python", "py", "python3"] : ["python3", "python"];
6097
+ }
6098
+ function pythonVenvRelativePaths(platform) {
6099
+ const pathApi = platform === "win32" ? import_node_path.default.win32 : import_node_path.default.posix;
6100
+ return platform === "win32" ? [
6101
+ pathApi.join(".venv", "Scripts", "python.exe"),
6102
+ pathApi.join("venv", "Scripts", "python.exe")
6103
+ ] : [pathApi.join(".venv", "bin", "python"), pathApi.join("venv", "bin", "python")];
6104
+ }
6105
+ function pythonInterpreterCandidates(options) {
6106
+ const { startDirectory, platform, env, walkUp = false, respectPythonEnv = false } = options;
6107
+ const pathApi = platform === "win32" ? import_node_path.default.win32 : import_node_path.default.posix;
6108
+ const relatives = pythonVenvRelativePaths(platform);
6109
+ const candidates = [];
6110
+ let current2 = startDirectory;
6111
+ for (; ; ) {
6112
+ for (const relative of relatives) {
6113
+ candidates.push({ command: pathApi.join(current2, relative), source: "venv" });
6114
+ }
6115
+ if (!walkUp) break;
6116
+ const parent = pathApi.dirname(current2);
6117
+ if (parent === current2) break;
6118
+ current2 = parent;
6119
+ }
6120
+ const pythonEnv = respectPythonEnv ? env?.PYTHON : void 0;
6121
+ if (pythonEnv) candidates.push({ command: pythonEnv, source: "python-env" });
6122
+ for (const name of pythonCommandCandidates(platform)) {
6123
+ candidates.push({ command: name, source: "path" });
6124
+ }
6125
+ return candidates;
6126
+ }
6127
+ async function resolvePythonInterpreter(options, probe) {
6128
+ for (const candidate of pythonInterpreterCandidates(options)) {
6129
+ const resolved = await probe(candidate);
6130
+ if (resolved !== null) return resolved;
6131
+ }
6132
+ return null;
6133
+ }
6134
+
6135
+ // src/cli/runtime/targets.ts
6136
+ var ExecutionTargetError = class extends Error {
6137
+ constructor(reason, message) {
6138
+ super(message);
6139
+ this.reason = reason;
6140
+ this.name = "ExecutionTargetError";
6141
+ }
6142
+ reason;
6143
+ };
6144
+ async function resolveExecutionTarget(target, programArgs, env = process.env) {
6145
+ const absolute = import_node_path2.default.resolve(target);
6146
+ let targetStat;
6147
+ try {
6148
+ targetStat = await (0, import_promises.stat)(absolute);
6149
+ } catch (error) {
6150
+ const code = errnoCode(error);
6151
+ throw new ExecutionTargetError(
6152
+ code === "ENOENT" ? "target-not-found" : "target-read-failed",
6153
+ code === "ENOENT" ? `Target was not found: ${target}` : `Could not inspect target ${target}: ${errorMessage(error)}`
6154
+ );
6155
+ }
6156
+ if (targetStat.isFile()) {
6157
+ return planFile(absolute, target, programArgs, env);
6158
+ }
6159
+ if (targetStat.isDirectory()) {
6160
+ return planProject(absolute, target, programArgs, env);
6161
+ }
6162
+ throw new ExecutionTargetError(
6163
+ "unsupported-file-type",
6164
+ `Target must be a regular file or directory: ${target}`
6165
+ );
6166
+ }
6167
+ async function resolveCapsuleSource(input, programArgs, env = process.env) {
6168
+ if (input.runtimeMode === "browser-preview") {
6169
+ throw new ExecutionTargetError(
6170
+ "unsupported-runtime-mode",
6171
+ "Browser-preview Capsules require a DOM and cannot replay in the headless CLI."
6172
+ );
6173
+ }
6174
+ const displayTarget = `capsule:${input.capsuleId}`;
6175
+ const cwd = process.cwd();
6176
+ switch (input.language) {
6177
+ case "javascript": {
6178
+ return planJavaScriptCapsule(displayTarget, cwd, input, programArgs, false);
6179
+ }
6180
+ case "typescript": {
6181
+ return planJavaScriptCapsule(displayTarget, cwd, input, programArgs, true);
6182
+ }
6183
+ case "python":
6184
+ return planScriptSource(
6185
+ { displayTarget, runtime: "python", cwd, command: await findPython(cwd, env) },
6186
+ input.source,
6187
+ programArgs,
6188
+ { inline: (source) => ["-c", source], filename: "main.py" }
6189
+ );
6190
+ case "ruby":
6191
+ return planScriptSource(
6192
+ { displayTarget, runtime: "ruby", cwd, command: commandName("ruby") },
6193
+ input.source,
6194
+ programArgs,
6195
+ { inline: (source) => ["-e", source, "--"], filename: "main.rb" }
6196
+ );
6197
+ case "lua":
6198
+ return planScriptSource(
6199
+ { displayTarget, runtime: "lua", cwd, command: commandName("lua") },
6200
+ input.source,
6201
+ programArgs,
6202
+ { inline: programArgs.length === 0 ? (source) => ["-e", source] : null, filename: "main.lua" }
6203
+ );
6204
+ case "go":
6205
+ return stageCompiledSource(displayTarget, "go", "main.go", input.source, programArgs);
6206
+ case "rust":
6207
+ return stageCompiledSource(displayTarget, "rust", "main.rs", input.source, programArgs);
6208
+ default:
6209
+ throw new ExecutionTargetError(
6210
+ "unsupported-language",
6211
+ `Capsule language ${JSON.stringify(input.language)} is not executable by the CLI.`
6212
+ );
6213
+ }
6214
+ }
6215
+ async function planProject(root, displayTarget, programArgs, env) {
6216
+ const packageJson = import_node_path2.default.join(root, "package.json");
6217
+ if (await exists(packageJson)) {
6218
+ let manifest;
6219
+ try {
6220
+ manifest = JSON.parse(await (0, import_promises.readFile)(packageJson, "utf8"));
6221
+ } catch (error) {
6222
+ throw new ExecutionTargetError(
6223
+ "invalid-project-manifest",
6224
+ `Could not parse ${packageJson}: ${errorMessage(error)}`
6225
+ );
6226
+ }
6227
+ const scripts = isRecord2(manifest) && isRecord2(manifest.scripts) ? manifest.scripts : {};
6228
+ const script = typeof scripts.start === "string" ? "start" : typeof scripts.dev === "string" ? "dev" : null;
6229
+ if (script) {
6230
+ const npm = await npmScriptCommand(script, programArgs, env);
6231
+ return {
6232
+ displayTarget,
6233
+ runtime: `npm:${script}`,
6234
+ cwd: root,
6235
+ steps: [{ ...npm, kind: "execute" }]
6236
+ };
6237
+ }
6238
+ if (isRecord2(manifest) && typeof manifest.main === "string") {
6239
+ const mainPath = import_node_path2.default.resolve(root, manifest.main);
6240
+ if (await isFile(mainPath)) return planFile(mainPath, displayTarget, programArgs, env);
6241
+ }
6242
+ }
6243
+ if (await exists(import_node_path2.default.join(root, "go.mod"))) {
6244
+ return singleStep(displayTarget, "go-project", root, commandName("go"), [
6245
+ "run",
6246
+ ".",
6247
+ ...programArgs
6248
+ ]);
6249
+ }
6250
+ if (await exists(import_node_path2.default.join(root, "Cargo.toml"))) {
6251
+ return singleStep(displayTarget, "cargo", root, commandName("cargo"), [
6252
+ "run",
6253
+ "--quiet",
6254
+ "--",
6255
+ ...programArgs
6256
+ ]);
6257
+ }
6258
+ for (const candidate of PROJECT_ENTRY_CANDIDATES) {
6259
+ const entry = import_node_path2.default.join(root, candidate);
6260
+ if (await isFile(entry)) return planFile(entry, displayTarget, programArgs, env);
6261
+ }
6262
+ throw new ExecutionTargetError(
6263
+ "no-project-entry",
6264
+ [
6265
+ `No executable project entry was found in ${displayTarget}.`,
6266
+ "Supported roots expose package.json scripts.start/scripts.dev, go.mod, Cargo.toml,",
6267
+ `or one conventional entry: ${PROJECT_ENTRY_CANDIDATES.join(", ")}.`,
6268
+ "Pass a specific source file when the project uses a framework-specific launcher."
6269
+ ].join(" ")
6270
+ );
6271
+ }
6272
+ var PROJECT_ENTRY_CANDIDATES = [
6273
+ "main.py",
6274
+ "app.py",
6275
+ "explore.py",
6276
+ "src/main.py",
6277
+ "app/main.py",
6278
+ "main.rb",
6279
+ "app.rb",
6280
+ "index.js",
6281
+ "src/index.js",
6282
+ "index.ts",
6283
+ "src/index.ts"
6284
+ ];
6285
+ var CLI_SOURCE_EXTENSIONS = {
6286
+ javascript: [".js", ".mjs", ".cjs"],
6287
+ typescript: [".ts", ".mts", ".cts"],
6288
+ python: [".py"],
6289
+ go: [".go"],
6290
+ rust: [".rs"],
6291
+ ruby: [".rb"],
6292
+ lua: [".lua"]
6384
6293
  };
6385
- pp.readWord1 = function() {
6386
- this.containsEsc = false;
6387
- var word = "", first = true, chunkStart = this.pos;
6388
- var astral = this.options.ecmaVersion >= 6;
6389
- while (this.pos < this.input.length) {
6390
- var ch = this.fullCharCodeAtPos();
6391
- if (isIdentifierChar(ch, astral)) {
6392
- this.pos += ch <= 65535 ? 1 : 2;
6393
- } else if (ch === 92) {
6394
- this.containsEsc = true;
6395
- word += this.input.slice(chunkStart, this.pos);
6396
- var escStart = this.pos;
6397
- if (this.input.charCodeAt(++this.pos) !== 117) {
6398
- this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
6399
- }
6400
- ++this.pos;
6401
- var esc = this.readCodePoint();
6402
- if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
6403
- this.invalidStringToken(escStart, "Invalid Unicode escape");
6404
- }
6405
- word += codePointToString(esc);
6406
- chunkStart = this.pos;
6407
- } else {
6408
- break;
6294
+ async function planFile(absolute, displayTarget, programArgs, env) {
6295
+ const cwd = import_node_path2.default.dirname(absolute);
6296
+ const extension = import_node_path2.default.extname(absolute).toLowerCase();
6297
+ const language = Object.keys(CLI_SOURCE_EXTENSIONS).find(
6298
+ (key) => CLI_SOURCE_EXTENSIONS[key].includes(extension)
6299
+ );
6300
+ switch (language) {
6301
+ case "javascript":
6302
+ return singleStep(displayTarget, "node", cwd, nodeRuntimeExecutable(), [
6303
+ absolute,
6304
+ ...programArgs
6305
+ ]);
6306
+ case "typescript":
6307
+ return singleStep(displayTarget, "node-typescript", cwd, nodeRuntimeExecutable(), [
6308
+ "--experimental-strip-types",
6309
+ absolute,
6310
+ ...programArgs
6311
+ ]);
6312
+ case "python":
6313
+ return singleStep(displayTarget, "python", cwd, await findPython(cwd, env), [
6314
+ absolute,
6315
+ ...programArgs
6316
+ ]);
6317
+ case "go":
6318
+ return singleStep(displayTarget, "go", cwd, commandName("go"), [
6319
+ "run",
6320
+ absolute,
6321
+ ...programArgs
6322
+ ]);
6323
+ case "ruby":
6324
+ return singleStep(displayTarget, "ruby", cwd, commandName("ruby"), [
6325
+ absolute,
6326
+ ...programArgs
6327
+ ]);
6328
+ case "lua":
6329
+ return singleStep(displayTarget, "lua", cwd, commandName("lua"), [absolute, ...programArgs]);
6330
+ case "rust": {
6331
+ const temporaryRoot = await (0, import_promises.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), "lingua-cli-rust-"));
6332
+ const binary = import_node_path2.default.join(
6333
+ temporaryRoot,
6334
+ process.platform === "win32" ? "program.exe" : "program"
6335
+ );
6336
+ return {
6337
+ displayTarget,
6338
+ runtime: "rust",
6339
+ cwd,
6340
+ cleanupPaths: [temporaryRoot],
6341
+ steps: [
6342
+ {
6343
+ command: commandName("rustc"),
6344
+ args: [absolute, "-o", binary],
6345
+ kind: "prepare"
6346
+ },
6347
+ { command: binary, args: [...programArgs], kind: "execute" }
6348
+ ]
6349
+ };
6409
6350
  }
6410
- first = false;
6351
+ default:
6352
+ throw new ExecutionTargetError(
6353
+ "unsupported-file-type",
6354
+ `Unsupported source extension ${extension || "(none)"} for ${displayTarget}. Supported: .js, .mjs, .cjs, .ts, .mts, .cts, .py, .go, .rs, .rb, .lua.`
6355
+ );
6411
6356
  }
6412
- return word + this.input.slice(chunkStart, this.pos);
6413
- };
6414
- pp.readWord = function() {
6415
- var word = this.readWord1();
6416
- var type = types$1.name;
6417
- if (this.keywords.test(word)) {
6418
- type = keywords[word];
6357
+ }
6358
+ async function stageCompiledSource(displayTarget, language, filename, source, programArgs) {
6359
+ const temporaryRoot = await (0, import_promises.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), `lingua-cli-${language}-`));
6360
+ const sourcePath = import_node_path2.default.join(temporaryRoot, filename);
6361
+ await (0, import_promises.writeFile)(sourcePath, source, "utf8");
6362
+ if (language === "go") {
6363
+ return {
6364
+ displayTarget,
6365
+ runtime: "go",
6366
+ cwd: temporaryRoot,
6367
+ cleanupPaths: [temporaryRoot],
6368
+ steps: [
6369
+ {
6370
+ command: commandName("go"),
6371
+ args: ["run", sourcePath, ...programArgs],
6372
+ kind: "execute"
6373
+ }
6374
+ ]
6375
+ };
6419
6376
  }
6420
- return this.finishToken(type, word);
6421
- };
6422
- var version = "8.18.0";
6423
- Parser.acorn = {
6424
- Parser,
6425
- version,
6426
- defaultOptions,
6427
- Position,
6428
- SourceLocation,
6429
- getLineInfo,
6430
- Node,
6431
- TokenType,
6432
- tokTypes: types$1,
6433
- keywordTypes: keywords,
6434
- TokContext,
6435
- tokContexts: types,
6436
- isIdentifierChar,
6437
- isIdentifierStart,
6438
- Token,
6439
- isNewLine,
6440
- lineBreak,
6441
- lineBreakG,
6442
- nonASCIIwhitespace
6443
- };
6444
- function parse3(input, options) {
6445
- return Parser.parse(input, options);
6377
+ const binary = import_node_path2.default.join(temporaryRoot, process.platform === "win32" ? "program.exe" : "program");
6378
+ return {
6379
+ displayTarget,
6380
+ runtime: "rust",
6381
+ cwd: temporaryRoot,
6382
+ cleanupPaths: [temporaryRoot],
6383
+ steps: [
6384
+ { command: commandName("rustc"), args: [sourcePath, "-o", binary], kind: "prepare" },
6385
+ { command: binary, args: [...programArgs], kind: "execute" }
6386
+ ]
6387
+ };
6446
6388
  }
6447
-
6448
- // src/shared/nodeSourceMode.ts
6449
- function isAcornNode(value) {
6450
- return typeof value === "object" && value !== null && typeof value.type === "string";
6389
+ function singleStep(displayTarget, runtime, cwd, command, args) {
6390
+ return {
6391
+ displayTarget,
6392
+ runtime,
6393
+ cwd,
6394
+ steps: [{ command, args, kind: "execute" }]
6395
+ };
6451
6396
  }
6452
- function isFunctionScope(node) {
6453
- return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
6397
+ var INLINE_SOURCE_MAX_BYTES = process.platform === "win32" ? 8 * 1024 : 64 * 1024;
6398
+ var NODE_ARGV_SHIM = "process.argv.splice(1, 1);\n";
6399
+ async function planScriptSource(target, source, programArgs, options) {
6400
+ const { displayTarget, runtime, cwd, command } = target;
6401
+ if (options.inline && Buffer.byteLength(source, "utf8") <= INLINE_SOURCE_MAX_BYTES) {
6402
+ return singleStep(displayTarget, runtime, cwd, command, [
6403
+ ...options.inline(source),
6404
+ ...programArgs
6405
+ ]);
6406
+ }
6407
+ const temporaryRoot = await (0, import_promises.mkdtemp)(import_node_path2.default.join(import_node_os.default.tmpdir(), "lingua-cli-source-"));
6408
+ const entry = import_node_path2.default.join(temporaryRoot, options.filename);
6409
+ try {
6410
+ await (0, import_promises.writeFile)(entry, source, "utf8");
6411
+ for (const [name, content] of Object.entries(options.extraFiles ?? {})) {
6412
+ await (0, import_promises.writeFile)(import_node_path2.default.join(temporaryRoot, name), content, "utf8");
6413
+ }
6414
+ } catch (error) {
6415
+ await (0, import_promises.rm)(temporaryRoot, { recursive: true, force: true }).catch(() => {
6416
+ });
6417
+ throw error;
6418
+ }
6419
+ return {
6420
+ displayTarget,
6421
+ runtime,
6422
+ cwd,
6423
+ cleanupPaths: [temporaryRoot],
6424
+ steps: [
6425
+ {
6426
+ command,
6427
+ args: [...options.stagedArgs?.(entry, temporaryRoot) ?? [entry], ...programArgs],
6428
+ kind: "execute"
6429
+ }
6430
+ ]
6431
+ };
6454
6432
  }
6455
- function nodeContainsModuleOnlyExpression(node) {
6456
- if (node.type === "AwaitExpression") return true;
6457
- if (node.type === "MetaProperty") {
6458
- const meta = node.meta;
6459
- const property = node.property;
6460
- if (meta?.name === "import" && property?.name === "meta") return true;
6433
+ function planJavaScriptCapsule(displayTarget, cwd, input, programArgs, typescript) {
6434
+ const worker = input.runtimeMode === "worker";
6435
+ if (worker || input.runtimeMode === "node") {
6436
+ const source = worker ? [
6437
+ "(async () => {",
6438
+ input.source,
6439
+ "})().catch(error => {",
6440
+ " console.error(error instanceof Error ? error.stack : String(error));",
6441
+ " process.exitCode = 1;",
6442
+ "});"
6443
+ ].join("\n") : input.source;
6444
+ const detectTypeScript = typescript && !worker;
6445
+ const module2 = !worker && !typescript && sourceRequiresModuleInput(input.source);
6446
+ const inputType = detectTypeScript ? [] : [`--input-type=${module2 ? "module" : "commonjs"}${typescript ? "-typescript" : ""}`];
6447
+ const extension = detectTypeScript ? ".ts" : `.${module2 ? "m" : "c"}${typescript ? "ts" : "js"}`;
6448
+ const flags = typescript ? ["--experimental-strip-types"] : [];
6449
+ return planScriptSource(
6450
+ {
6451
+ displayTarget,
6452
+ runtime: `node${typescript ? "-typescript" : ""}${worker ? "-worker" : ""}`,
6453
+ cwd,
6454
+ command: nodeRuntimeExecutable()
6455
+ },
6456
+ source,
6457
+ programArgs,
6458
+ {
6459
+ inline: (inlineSource) => [...flags, ...inputType, "-e", inlineSource, "--"],
6460
+ filename: `entry${extension}`,
6461
+ stagedArgs: (entry, root) => [
6462
+ ...flags,
6463
+ "--require",
6464
+ import_node_path2.default.join(root, "argv-shim.cjs"),
6465
+ entry
6466
+ ],
6467
+ extraFiles: { "argv-shim.cjs": NODE_ARGV_SHIM }
6468
+ }
6469
+ );
6461
6470
  }
6462
- if (isFunctionScope(node)) return false;
6463
- for (const value of Object.values(node)) {
6464
- if (Array.isArray(value)) {
6465
- if (value.some((entry) => isAcornNode(entry) && nodeContainsModuleOnlyExpression(entry))) {
6466
- return true;
6471
+ throw new ExecutionTargetError(
6472
+ "unsupported-runtime-mode",
6473
+ `Capsule runtime mode ${JSON.stringify(input.runtimeMode)} is not replayable by the CLI for ${typescript ? "TypeScript" : "JavaScript"}; supported modes are worker and node.`
6474
+ );
6475
+ }
6476
+ function nodeRuntimeExecutable(options) {
6477
+ const sea = options?.sea ?? (0, import_node_sea.isSea)();
6478
+ return sea ? commandName("node") : options?.execPath ?? process.execPath;
6479
+ }
6480
+ async function findPython(startDirectory, env = process.env, platform = process.platform) {
6481
+ const resolved = await resolvePythonInterpreter(
6482
+ { startDirectory, platform, env, walkUp: true, respectPythonEnv: true },
6483
+ async (candidate) => {
6484
+ if (candidate.source === "path") {
6485
+ return await executableIsOnPath(candidate.command, platform, env) ? commandName(candidate.command) : null;
6467
6486
  }
6468
- } else if (isAcornNode(value) && nodeContainsModuleOnlyExpression(value)) {
6469
- return true;
6487
+ if (candidate.source === "python-env") return candidate.command;
6488
+ return await isFile(candidate.command) ? candidate.command : null;
6489
+ }
6490
+ );
6491
+ return resolved ?? commandName(pythonCommandCandidates(platform)[0]);
6492
+ }
6493
+ async function executableIsOnPath(executable, platform = process.platform, env = process.env) {
6494
+ const pathValue = env.PATH ?? env.Path ?? env.path;
6495
+ if (!pathValue) return false;
6496
+ const windows = platform === "win32";
6497
+ const pathApi = windows ? import_node_path2.default.win32 : import_node_path2.default.posix;
6498
+ const delimiter = windows ? ";" : ":";
6499
+ const extensions = windows ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()) : [""];
6500
+ const hasExtension = pathApi.extname(executable).length > 0;
6501
+ for (const rawEntry of pathValue.split(delimiter)) {
6502
+ const entry = rawEntry.trim().replace(/^"|"$/gu, "");
6503
+ if (!entry) continue;
6504
+ const base = pathApi.join(entry, executable);
6505
+ const candidates = windows && !hasExtension ? extensions.map((extension) => base + extension) : [base];
6506
+ for (const candidate of candidates) {
6507
+ if (await isExecutableFile(candidate, platform)) return true;
6470
6508
  }
6471
6509
  }
6472
6510
  return false;
6473
6511
  }
6474
- function sourceRequiresModuleInput(source) {
6512
+ function commandName(name) {
6513
+ return process.platform === "win32" && ["npm", "npx"].includes(name) ? `${name}.cmd` : name;
6514
+ }
6515
+ var CMD_META_CHARACTERS = /([()\][%!^"`<>&|;, *?])/gu;
6516
+ function escapeCmdArgument(argument) {
6517
+ const quoted = `"${argument.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\*)$/u, "$1$1")}"`;
6518
+ return quoted.replace(CMD_META_CHARACTERS, "^$1").replace(CMD_META_CHARACTERS, "^$1");
6519
+ }
6520
+ async function npmScriptCommand(script, programArgs, env, platform = process.platform, fileExists = isFile) {
6521
+ const npmArgs = ["run", script, "--", ...programArgs];
6522
+ if (platform !== "win32") return { command: "npm", args: npmArgs };
6523
+ const comspec = env.COMSPEC ?? env.ComSpec;
6524
+ const npmCmd = await resolveAbsoluteOnPath("npm.cmd", env, fileExists);
6525
+ if (!comspec || !import_node_path2.default.win32.isAbsolute(comspec) || !npmCmd) {
6526
+ return { command: "npm", args: npmArgs };
6527
+ }
6528
+ const commandLine = [
6529
+ npmCmd.replace(CMD_META_CHARACTERS, "^$1"),
6530
+ ...npmArgs.map(escapeCmdArgument)
6531
+ ];
6532
+ return {
6533
+ command: comspec,
6534
+ args: ["/d", "/s", "/c", `"${commandLine.join(" ")}"`],
6535
+ windowsVerbatimArguments: true
6536
+ };
6537
+ }
6538
+ async function resolveAbsoluteOnPath(executable, env, fileExists) {
6539
+ const pathValue = env.PATH ?? env.Path ?? env.path ?? "";
6540
+ for (const rawEntry of pathValue.split(";")) {
6541
+ const entry = rawEntry.trim().replace(/^"|"$/gu, "");
6542
+ if (!import_node_path2.default.win32.isAbsolute(entry)) continue;
6543
+ const candidate = import_node_path2.default.win32.join(entry, executable);
6544
+ if (await fileExists(candidate)) return candidate;
6545
+ }
6546
+ return null;
6547
+ }
6548
+ async function exists(filePath) {
6475
6549
  try {
6476
- const program = parse3(source, {
6477
- allowHashBang: true,
6478
- ecmaVersion: "latest",
6479
- sourceType: "module"
6480
- });
6481
- return program.body.some((statement) => {
6482
- if (statement.type === "ImportDeclaration" || statement.type === "ExportAllDeclaration" || statement.type === "ExportDefaultDeclaration" || statement.type === "ExportNamedDeclaration") {
6483
- return true;
6484
- }
6485
- return nodeContainsModuleOnlyExpression(statement);
6486
- });
6550
+ await (0, import_promises.access)(filePath);
6551
+ return true;
6487
6552
  } catch {
6488
6553
  return false;
6489
6554
  }
6490
6555
  }
6491
-
6492
- // src/shared/python/interpreter.ts
6493
- var import_node_path2 = __toESM(require("node:path"));
6494
- function pythonCommandCandidates(platform) {
6495
- return platform === "win32" ? ["python", "py", "python3"] : ["python3", "python"];
6496
- }
6497
- function pythonVenvRelativePaths(platform) {
6498
- const pathApi = platform === "win32" ? import_node_path2.default.win32 : import_node_path2.default.posix;
6499
- return platform === "win32" ? [
6500
- pathApi.join(".venv", "Scripts", "python.exe"),
6501
- pathApi.join("venv", "Scripts", "python.exe")
6502
- ] : [pathApi.join(".venv", "bin", "python"), pathApi.join("venv", "bin", "python")];
6503
- }
6504
- function pythonInterpreterCandidates(options) {
6505
- const { startDirectory, platform, env, walkUp = false, respectPythonEnv = false } = options;
6506
- const pathApi = platform === "win32" ? import_node_path2.default.win32 : import_node_path2.default.posix;
6507
- const relatives = pythonVenvRelativePaths(platform);
6508
- const candidates = [];
6509
- let current2 = startDirectory;
6510
- for (; ; ) {
6511
- for (const relative of relatives) {
6512
- candidates.push({ command: pathApi.join(current2, relative), source: "venv" });
6513
- }
6514
- if (!walkUp) break;
6515
- const parent = pathApi.dirname(current2);
6516
- if (parent === current2) break;
6517
- current2 = parent;
6518
- }
6519
- const pythonEnv = respectPythonEnv ? env?.PYTHON : void 0;
6520
- if (pythonEnv) candidates.push({ command: pythonEnv, source: "python-env" });
6521
- for (const name of pythonCommandCandidates(platform)) {
6522
- candidates.push({ command: name, source: "path" });
6556
+ async function isFile(filePath) {
6557
+ try {
6558
+ return (await (0, import_promises.stat)(filePath)).isFile();
6559
+ } catch {
6560
+ return false;
6523
6561
  }
6524
- return candidates;
6525
6562
  }
6526
- async function resolvePythonInterpreter(options, probe) {
6527
- for (const candidate of pythonInterpreterCandidates(options)) {
6528
- const resolved = await probe(candidate);
6529
- if (resolved !== null) return resolved;
6563
+ async function isExecutableFile(filePath, platform = process.platform) {
6564
+ if (!await isFile(filePath)) return false;
6565
+ if (platform === "win32") return true;
6566
+ try {
6567
+ await (0, import_promises.access)(filePath, import_node_fs.constants.X_OK);
6568
+ return true;
6569
+ } catch {
6570
+ return false;
6530
6571
  }
6531
- return null;
6572
+ }
6573
+ function isRecord2(value) {
6574
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6575
+ }
6576
+ function errnoCode(error) {
6577
+ return error && typeof error === "object" && "code" in error ? String(error.code) : void 0;
6578
+ }
6579
+ function errorMessage(error) {
6580
+ return error instanceof Error ? error.message : String(error);
6532
6581
  }
6533
6582
 
6534
- // src/cli/runtime/targets.ts
6535
- var ExecutionTargetError = class extends Error {
6536
- constructor(reason, message) {
6537
- super(message);
6538
- this.reason = reason;
6539
- this.name = "ExecutionTargetError";
6540
- }
6541
- reason;
6542
- };
6543
- async function resolveExecutionTarget(target, programArgs, env = process.env) {
6544
- const absolute = import_node_path3.default.resolve(target);
6545
- let targetStat;
6546
- try {
6547
- targetStat = await (0, import_promises2.stat)(absolute);
6548
- } catch (error) {
6549
- const code = errnoCode(error);
6550
- throw new ExecutionTargetError(
6551
- code === "ENOENT" ? "target-not-found" : "target-read-failed",
6552
- code === "ENOENT" ? `Target was not found: ${target}` : `Could not inspect target ${target}: ${errorMessage(error)}`
6583
+ // src/cli/runtime/regressionTargets.ts
6584
+ var RegressionTargetError = class extends Error {
6585
+ };
6586
+ async function resolveRegressionTarget(root, target, language) {
6587
+ if (!isRegressionTarget(target))
6588
+ throw new RegressionTargetError("Target must be a relative path without traversal.");
6589
+ const base = await (0, import_promises2.realpath)(root).catch(() => {
6590
+ throw new RegressionTargetError("Could not resolve the suite root.");
6591
+ });
6592
+ const candidate = import_node_path3.default.resolve(base, target.replaceAll("\\", "/"));
6593
+ const actual = await (0, import_promises2.realpath)(candidate).catch(() => {
6594
+ throw new RegressionTargetError("Target was not found or could not be read.");
6595
+ });
6596
+ const relative = import_node_path3.default.relative(base, actual);
6597
+ if (!relative || relative === ".." || relative.startsWith(`..${import_node_path3.default.sep}`) || import_node_path3.default.isAbsolute(relative))
6598
+ throw new RegressionTargetError("Target escapes the authorized suite root.");
6599
+ if (!(await (0, import_promises2.stat)(actual)).isFile() || !CLI_SOURCE_EXTENSIONS[language]?.includes(import_node_path3.default.extname(actual).toLowerCase()))
6600
+ throw new RegressionTargetError(
6601
+ "Target must be a regular file compatible with the baseline language."
6553
6602
  );
6554
- }
6555
- if (targetStat.isFile()) {
6556
- return planFile(absolute, target, programArgs, env);
6557
- }
6558
- if (targetStat.isDirectory()) {
6559
- return planProject(absolute, target, programArgs, env);
6560
- }
6561
- throw new ExecutionTargetError(
6562
- "unsupported-file-type",
6563
- `Target must be a regular file or directory: ${target}`
6564
- );
6603
+ return actual;
6565
6604
  }
6566
- async function resolveCapsuleSource(input, programArgs, env = process.env) {
6567
- if (input.runtimeMode === "browser-preview") {
6568
- throw new ExecutionTargetError(
6569
- "unsupported-runtime-mode",
6570
- "Browser-preview Capsules require a DOM and cannot replay in the headless CLI."
6571
- );
6572
- }
6573
- const displayTarget = `capsule:${input.capsuleId}`;
6574
- const cwd = process.cwd();
6575
- switch (input.language) {
6576
- case "javascript": {
6577
- return planJavaScriptCapsule(displayTarget, cwd, input, programArgs, false);
6578
- }
6579
- case "typescript": {
6580
- return planJavaScriptCapsule(displayTarget, cwd, input, programArgs, true);
6581
- }
6582
- case "python":
6583
- return singleStep(displayTarget, "python", cwd, await findPython(cwd, env), [
6584
- "-c",
6585
- input.source,
6586
- ...programArgs
6587
- ]);
6588
- case "ruby":
6589
- return singleStep(displayTarget, "ruby", cwd, commandName("ruby"), [
6590
- "-e",
6591
- input.source,
6592
- ...programArgs
6593
- ]);
6594
- case "lua":
6595
- return singleStep(displayTarget, "lua", cwd, commandName("lua"), [
6596
- "-e",
6597
- input.source,
6598
- ...programArgs
6599
- ]);
6600
- case "go":
6601
- return stageCompiledSource(displayTarget, "go", "main.go", input.source, programArgs);
6602
- case "rust":
6603
- return stageCompiledSource(displayTarget, "rust", "main.rs", input.source, programArgs);
6604
- default:
6605
- throw new ExecutionTargetError(
6606
- "unsupported-language",
6607
- `Capsule language ${JSON.stringify(input.language)} is not executable by the CLI.`
6608
- );
6605
+ async function readRegressionTarget(root, target, language, limit) {
6606
+ const actual = await resolveRegressionTarget(root, target, language);
6607
+ try {
6608
+ return await readBoundedSuite(actual, limit);
6609
+ } catch {
6610
+ throw new RegressionTargetError("Target is too large or is not valid UTF-8 text.");
6609
6611
  }
6610
6612
  }
6611
- async function planProject(root, displayTarget, programArgs, env) {
6612
- const packageJson = import_node_path3.default.join(root, "package.json");
6613
- if (await exists(packageJson)) {
6614
- let manifest;
6615
- try {
6616
- manifest = JSON.parse(await (0, import_promises2.readFile)(packageJson, "utf8"));
6617
- } catch (error) {
6618
- throw new ExecutionTargetError(
6619
- "invalid-project-manifest",
6620
- `Could not parse ${packageJson}: ${errorMessage(error)}`
6621
- );
6622
- }
6623
- const scripts = isRecord2(manifest) && isRecord2(manifest.scripts) ? manifest.scripts : {};
6624
- const script = typeof scripts.start === "string" ? "start" : typeof scripts.dev === "string" ? "dev" : null;
6625
- if (script) {
6626
- return singleStep(displayTarget, `npm:${script}`, root, commandName("npm"), [
6627
- "run",
6628
- script,
6629
- "--",
6630
- ...programArgs
6631
- ]);
6632
- }
6633
- if (isRecord2(manifest) && typeof manifest.main === "string") {
6634
- const mainPath = import_node_path3.default.resolve(root, manifest.main);
6635
- if (await isFile(mainPath)) return planFile(mainPath, displayTarget, programArgs, env);
6636
- }
6613
+ async function readBoundedSuite(file, limit) {
6614
+ let bytes = 0;
6615
+ const chunks = [];
6616
+ for await (const chunk of (0, import_node_fs2.createReadStream)(file)) {
6617
+ bytes += chunk.length;
6618
+ if (bytes > limit) throw new Error("suite-too-large");
6619
+ chunks.push(chunk);
6637
6620
  }
6638
- if (await exists(import_node_path3.default.join(root, "go.mod"))) {
6639
- return singleStep(displayTarget, "go-project", root, commandName("go"), [
6640
- "run",
6641
- ".",
6642
- ...programArgs
6643
- ]);
6621
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
6622
+ }
6623
+
6624
+ // src/cli/commands/capsuleVerify.ts
6625
+ var import_promises4 = require("node:fs/promises");
6626
+
6627
+ // src/shared/runnerLimits.ts
6628
+ var MAX_NATIVE_STDERR_BYTES = 1024 * 1024;
6629
+ var MAX_STDIN_WRITE_BYTES = 256 * 1024;
6630
+ var MAX_COMPILE_OUTPUT_BYTES = 1024 * 1024;
6631
+ var MAX_GO_WASM_BYTES = 10 * 1024 * 1024;
6632
+
6633
+ // src/shared/capsuleVerification.ts
6634
+ var CLI_OUTPUT_TRUNCATION_MARKER = "\n[output truncated by Lingua CLI]\n";
6635
+ var CLI_OUTPUT_PAYLOAD_BYTES = MAX_NATIVE_STDERR_BYTES - utf8ByteLength(CLI_OUTPUT_TRUNCATION_MARKER);
6636
+ function capsuleVerificationBlocker(capsule, maxStreamBytes = MAX_STREAM_BYTES) {
6637
+ if (capsule.result.status !== "success") return "unsupported-baseline-status";
6638
+ if (capsule.privacy.omittedFields.some(
6639
+ (field) => /^(source|input)(\.|$)|^result\.(stdout|stderr|lineResults|richOutputs)(\.|$)/.test(field)
6640
+ ))
6641
+ return "incomplete-baseline";
6642
+ if (capsule.result.lineResults?.length || capsule.result.richOutputs?.length)
6643
+ return "unsupported-baseline-output";
6644
+ if (utf8ByteLength(capsule.result.stdout ?? "") > maxStreamBytes || utf8ByteLength(capsule.result.stderr ?? "") > maxStreamBytes)
6645
+ return "incomplete-baseline";
6646
+ return null;
6647
+ }
6648
+ function capsuleEngineDivergence(capsule) {
6649
+ const { language } = capsule.tab;
6650
+ const divergent = language === "python" || language === "go" || language === "ruby" && capsule.environment.platform === "web";
6651
+ return divergent ? "engine-divergent-baseline" : null;
6652
+ }
6653
+ function compareCapsuleStreams(capsule, actual) {
6654
+ const status = capsule.result.status === actual.status;
6655
+ const stdout = (capsule.result.stdout ?? "") === actual.stdout;
6656
+ const stderr = (capsule.result.stderr ?? "") === actual.stderr;
6657
+ return { matches: status && stdout && stderr, status, stdout, stderr };
6658
+ }
6659
+ function capsuleStrictVerificationRefusal(capsule) {
6660
+ return capsuleVerificationBlocker(capsule, CLI_OUTPUT_PAYLOAD_BYTES) ?? capsuleEngineDivergence(capsule) ?? (capsule.tab.runtimeMode === "browser-preview" ? "unsupported-runtime-mode" : null);
6661
+ }
6662
+
6663
+ // src/cli/runtime/execution.ts
6664
+ var import_node_child_process = require("node:child_process");
6665
+ var import_promises3 = require("node:fs/promises");
6666
+
6667
+ // src/cli/runtime/runtimeRecovery.ts
6668
+ var import_node_path4 = __toESM(require("node:path"));
6669
+ var CLI_RUNTIME_HELP_URL = "https://linguacode.dev/cli/troubleshooting#missing-runtimes";
6670
+ var RUNTIMES = {
6671
+ python: {
6672
+ name: "Python",
6673
+ verifyExecutable: "python3",
6674
+ homebrewFormula: "python",
6675
+ installGuide: "https://www.python.org/downloads/"
6676
+ },
6677
+ go: {
6678
+ name: "Go",
6679
+ verifyExecutable: "go",
6680
+ homebrewFormula: "go",
6681
+ installGuide: "https://go.dev/doc/install"
6682
+ },
6683
+ rust: {
6684
+ name: "Rust",
6685
+ verifyExecutable: "rustc",
6686
+ homebrewFormula: "rust",
6687
+ installGuide: "https://www.rust-lang.org/tools/install"
6688
+ },
6689
+ ruby: {
6690
+ name: "Ruby",
6691
+ verifyExecutable: "ruby",
6692
+ homebrewFormula: "ruby",
6693
+ installGuide: "https://www.ruby-lang.org/en/documentation/installation/"
6694
+ },
6695
+ lua: {
6696
+ name: "Lua",
6697
+ verifyExecutable: "lua",
6698
+ homebrewFormula: "lua",
6699
+ installGuide: "https://www.lua.org/download.html"
6700
+ },
6701
+ node: {
6702
+ name: "Node.js",
6703
+ verifyExecutable: "node",
6704
+ homebrewFormula: "node@24",
6705
+ installGuide: "https://nodejs.org/en/download"
6644
6706
  }
6645
- if (await exists(import_node_path3.default.join(root, "Cargo.toml"))) {
6646
- return singleStep(displayTarget, "cargo", root, commandName("cargo"), [
6647
- "run",
6648
- "--quiet",
6649
- "--",
6650
- ...programArgs
6651
- ]);
6707
+ };
6708
+ function buildMissingRuntimeRecovery(command, runtime, platform = process.platform) {
6709
+ const executable = executableName(command);
6710
+ const key = runtimeKey(executable, runtime);
6711
+ const descriptor = RUNTIMES[key] ?? {
6712
+ name: runtime || executable,
6713
+ verifyExecutable: executable,
6714
+ installGuide: CLI_RUNTIME_HELP_URL
6715
+ };
6716
+ const verifyExecutable = key === "python" ? executable : descriptor.verifyExecutable;
6717
+ const installCommand = platform === "darwin" && descriptor.homebrewFormula ? `brew install ${descriptor.homebrewFormula}` : void 0;
6718
+ const verifyCommand = `${verifyExecutable} --version`;
6719
+ const recovery = {
6720
+ runtime: descriptor.name,
6721
+ executable,
6722
+ ...installCommand ? { installCommand } : {},
6723
+ installGuide: descriptor.installGuide,
6724
+ verifyCommand
6725
+ };
6726
+ const install = installCommand ? `Install on macOS with Homebrew:
6727
+ ${installCommand}` : `Install ${descriptor.name} for your operating system:
6728
+ ${descriptor.installGuide}`;
6729
+ const guide = descriptor.installGuide === CLI_RUNTIME_HELP_URL ? "" : `
6730
+ Setup guide:
6731
+ ${descriptor.installGuide}`;
6732
+ return {
6733
+ detail: [
6734
+ `${descriptor.name} is required for this run, but Lingua could not find \`${executable}\` on PATH.`,
6735
+ install,
6736
+ `Verify the setup:
6737
+ ${verifyCommand}`,
6738
+ `Then retry the same Lingua command.${guide}`,
6739
+ `Lingua runtime help:
6740
+ ${CLI_RUNTIME_HELP_URL}`
6741
+ ].join("\n\n"),
6742
+ recovery
6743
+ };
6744
+ }
6745
+ function executableName(command) {
6746
+ const basename = import_node_path4.default.basename(command).toLowerCase();
6747
+ return basename.replace(/\.exe$/u, "").replace(/\.cmd$/u, "");
6748
+ }
6749
+ function runtimeKey(executable, runtime) {
6750
+ const normalizedRuntime = runtime.toLowerCase();
6751
+ if (executable === "py" || executable.startsWith("python") || normalizedRuntime.startsWith("python")) {
6752
+ return "python";
6652
6753
  }
6653
- for (const candidate of PROJECT_ENTRY_CANDIDATES) {
6654
- const entry = import_node_path3.default.join(root, candidate);
6655
- if (await isFile(entry)) return planFile(entry, displayTarget, programArgs, env);
6754
+ if (executable === "go" || normalizedRuntime.startsWith("go")) return "go";
6755
+ if (["rustc", "cargo"].includes(executable) || normalizedRuntime.startsWith("rust")) return "rust";
6756
+ if (executable === "ruby" || normalizedRuntime.startsWith("ruby")) return "ruby";
6757
+ if (executable === "lua" || normalizedRuntime.startsWith("lua")) return "lua";
6758
+ if (["node", "npm", "npx"].includes(executable) || normalizedRuntime.startsWith("node")) {
6759
+ return "node";
6656
6760
  }
6657
- throw new ExecutionTargetError(
6658
- "no-project-entry",
6659
- [
6660
- `No executable project entry was found in ${displayTarget}.`,
6661
- "Supported roots expose package.json scripts.start/scripts.dev, go.mod, Cargo.toml,",
6662
- `or one conventional entry: ${PROJECT_ENTRY_CANDIDATES.join(", ")}.`,
6663
- "Pass a specific source file when the project uses a framework-specific launcher."
6664
- ].join(" ")
6665
- );
6761
+ return normalizedRuntime;
6666
6762
  }
6667
- var PROJECT_ENTRY_CANDIDATES = [
6668
- "main.py",
6669
- "app.py",
6670
- "explore.py",
6671
- "src/main.py",
6672
- "app/main.py",
6673
- "main.rb",
6674
- "app.rb",
6675
- "index.js",
6676
- "src/index.js",
6677
- "index.ts",
6678
- "src/index.ts"
6679
- ];
6680
- async function planFile(absolute, displayTarget, programArgs, env) {
6681
- const cwd = import_node_path3.default.dirname(absolute);
6682
- const extension = import_node_path3.default.extname(absolute).toLowerCase();
6683
- switch (extension) {
6684
- case ".js":
6685
- case ".mjs":
6686
- case ".cjs":
6687
- return singleStep(displayTarget, "node", cwd, nodeRuntimeExecutable(), [
6688
- absolute,
6689
- ...programArgs
6690
- ]);
6691
- case ".ts":
6692
- case ".mts":
6693
- case ".cts":
6694
- return singleStep(displayTarget, "node-typescript", cwd, nodeRuntimeExecutable(), [
6695
- "--experimental-strip-types",
6696
- absolute,
6697
- ...programArgs
6698
- ]);
6699
- case ".py":
6700
- return singleStep(displayTarget, "python", cwd, await findPython(cwd, env), [
6701
- absolute,
6702
- ...programArgs
6703
- ]);
6704
- case ".go":
6705
- return singleStep(displayTarget, "go", cwd, commandName("go"), [
6706
- "run",
6707
- absolute,
6708
- ...programArgs
6709
- ]);
6710
- case ".rb":
6711
- return singleStep(displayTarget, "ruby", cwd, commandName("ruby"), [
6712
- absolute,
6713
- ...programArgs
6714
- ]);
6715
- case ".lua":
6716
- return singleStep(displayTarget, "lua", cwd, commandName("lua"), [absolute, ...programArgs]);
6717
- case ".rs": {
6718
- const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path3.default.join(import_node_os.default.tmpdir(), "lingua-cli-rust-"));
6719
- const binary = import_node_path3.default.join(
6720
- temporaryRoot,
6721
- process.platform === "win32" ? "program.exe" : "program"
6722
- );
6723
- return {
6724
- displayTarget,
6725
- runtime: "rust",
6726
- cwd,
6727
- cleanupPaths: [temporaryRoot],
6728
- steps: [
6729
- {
6730
- command: commandName("rustc"),
6731
- args: [absolute, "-o", binary],
6732
- kind: "prepare"
6733
- },
6734
- { command: binary, args: [...programArgs], kind: "execute" }
6735
- ]
6736
- };
6737
- }
6738
- default:
6739
- throw new ExecutionTargetError(
6740
- "unsupported-file-type",
6741
- `Unsupported source extension ${extension || "(none)"} for ${displayTarget}. Supported: .js, .mjs, .cjs, .ts, .mts, .cts, .py, .go, .rs, .rb, .lua.`
6742
- );
6743
- }
6763
+
6764
+ // src/cli/runtime/execution.ts
6765
+ var DEFAULT_CLI_RUN_TIMEOUT_MS = 3e4;
6766
+ var MIN_CLI_RUN_TIMEOUT_MS = 100;
6767
+ var MAX_CLI_RUN_TIMEOUT_MS = 5 * 6e4;
6768
+ var KILL_ESCALATION_MS = 1500;
6769
+ var FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
6770
+ function clampCliRunTimeout(value) {
6771
+ if (value === void 0 || !Number.isFinite(value)) return DEFAULT_CLI_RUN_TIMEOUT_MS;
6772
+ return Math.min(MAX_CLI_RUN_TIMEOUT_MS, Math.max(MIN_CLI_RUN_TIMEOUT_MS, Math.floor(value)));
6744
6773
  }
6745
- async function stageCompiledSource(displayTarget, language, filename, source, programArgs) {
6746
- const temporaryRoot = await (0, import_promises2.mkdtemp)(import_node_path3.default.join(import_node_os.default.tmpdir(), `lingua-cli-${language}-`));
6747
- const sourcePath = import_node_path3.default.join(temporaryRoot, filename);
6748
- await (0, import_promises2.writeFile)(sourcePath, source, "utf8");
6749
- if (language === "go") {
6774
+ async function executeCliPlan(plan, options) {
6775
+ const startedAt = options.startedAt ?? Date.now();
6776
+ const timeoutMs = clampCliRunTimeout(options.timeoutMs);
6777
+ const stdout = new CappedOutput();
6778
+ const stderr = new CappedOutput();
6779
+ try {
6780
+ for (const step of plan.steps) {
6781
+ const elapsed = Date.now() - startedAt;
6782
+ const remaining = Math.max(1, timeoutMs - elapsed);
6783
+ const result = await runStep(step, {
6784
+ cwd: plan.cwd,
6785
+ env: options.env,
6786
+ timeoutMs: remaining,
6787
+ stdin: step.kind === "execute" ? options.stdin : void 0,
6788
+ onStdout: (chunk) => forwardOutput(stdout, chunk, options.onStdout),
6789
+ onStderr: (chunk) => forwardOutput(stderr, chunk, options.onStderr)
6790
+ });
6791
+ if (result.spawnError) {
6792
+ const missing = result.spawnError.code === "ENOENT";
6793
+ const missingRuntime = missing ? buildMissingRuntimeRecovery(step.command, plan.runtime) : void 0;
6794
+ return finish(plan, startedAt, result, stdout, stderr, "error", {
6795
+ reason: missing ? "missing-runtime" : "spawn-failed",
6796
+ detail: missingRuntime?.detail ?? `Failed to start ${step.command}: ${result.spawnError.message}`,
6797
+ ...missingRuntime ? { recovery: missingRuntime.recovery } : {}
6798
+ });
6799
+ }
6800
+ if (result.timedOut) {
6801
+ return finish(plan, startedAt, result, stdout, stderr, "timeout", {
6802
+ reason: "timeout",
6803
+ detail: `Run timed out after ${timeoutMs}ms.`
6804
+ });
6805
+ }
6806
+ if (result.stopped) {
6807
+ return finish(plan, startedAt, result, stdout, stderr, "stopped", {
6808
+ reason: "stopped",
6809
+ detail: "Run stopped by SIGINT, SIGTERM, or SIGHUP."
6810
+ });
6811
+ }
6812
+ if (result.exitCode !== 0) {
6813
+ return finish(plan, startedAt, result, stdout, stderr, "error", {
6814
+ reason: step.kind === "prepare" ? "prepare-failed" : "non-zero-exit",
6815
+ detail: step.kind === "prepare" ? `Runtime preparation exited with code ${result.exitCode ?? result.signal ?? "unknown"}.` : `Program exited with code ${result.exitCode ?? result.signal ?? "unknown"}.`
6816
+ });
6817
+ }
6818
+ }
6819
+ const last = plan.steps.at(-1);
6750
6820
  return {
6751
- displayTarget,
6752
- runtime: "go",
6753
- cwd: temporaryRoot,
6754
- cleanupPaths: [temporaryRoot],
6755
- steps: [
6756
- {
6757
- command: commandName("go"),
6758
- args: ["run", sourcePath, ...programArgs],
6759
- kind: "execute"
6760
- }
6761
- ]
6821
+ status: "success",
6822
+ target: plan.displayTarget,
6823
+ runtime: plan.runtime,
6824
+ durationMs: Date.now() - startedAt,
6825
+ exitCode: 0,
6826
+ signal: null,
6827
+ stdout: stdout.value,
6828
+ stderr: stderr.value,
6829
+ ...stdout.truncated || stderr.truncated ? { truncated: { stdout: stdout.truncated, stderr: stderr.truncated } } : {},
6830
+ ...last ? {} : { detail: "Execution plan contained no steps." }
6762
6831
  };
6832
+ } finally {
6833
+ await Promise.all(
6834
+ (plan.cleanupPaths ?? []).map(
6835
+ (cleanupPath) => (0, import_promises3.rm)(cleanupPath, { recursive: true, force: true }).catch(() => {
6836
+ })
6837
+ )
6838
+ );
6763
6839
  }
6764
- const binary = import_node_path3.default.join(temporaryRoot, process.platform === "win32" ? "program.exe" : "program");
6765
- return {
6766
- displayTarget,
6767
- runtime: "rust",
6768
- cwd: temporaryRoot,
6769
- cleanupPaths: [temporaryRoot],
6770
- steps: [
6771
- { command: commandName("rustc"), args: [sourcePath, "-o", binary], kind: "prepare" },
6772
- { command: binary, args: [...programArgs], kind: "execute" }
6773
- ]
6774
- };
6775
6840
  }
6776
- function singleStep(displayTarget, runtime, cwd, command, args) {
6841
+ function finish(plan, startedAt, result, stdout, stderr, status, diagnostic) {
6777
6842
  return {
6778
- displayTarget,
6779
- runtime,
6780
- cwd,
6781
- steps: [{ command, args, kind: "execute" }]
6843
+ status,
6844
+ target: plan.displayTarget,
6845
+ runtime: plan.runtime,
6846
+ durationMs: Date.now() - startedAt,
6847
+ exitCode: result.exitCode,
6848
+ signal: result.signal,
6849
+ stdout: stdout.value,
6850
+ stderr: stderr.value,
6851
+ ...stdout.truncated || stderr.truncated ? { truncated: { stdout: stdout.truncated, stderr: stderr.truncated } } : {},
6852
+ ...diagnostic
6782
6853
  };
6783
6854
  }
6784
- function planJavaScriptCapsule(displayTarget, cwd, input, programArgs, typescript) {
6785
- if (input.runtimeMode === "worker") {
6786
- const wrappedSource = [
6787
- "(async () => {",
6788
- input.source,
6789
- "})().catch(error => {",
6790
- " console.error(error instanceof Error ? error.stack : String(error));",
6791
- " process.exitCode = 1;",
6792
- "});"
6793
- ].join("\n");
6794
- return singleStep(
6795
- displayTarget,
6796
- typescript ? "node-typescript-worker" : "node-worker",
6797
- cwd,
6798
- nodeRuntimeExecutable(),
6799
- [
6800
- ...typescript ? ["--experimental-strip-types"] : [],
6801
- "--input-type=commonjs",
6802
- "-e",
6803
- wrappedSource,
6804
- ...programArgs
6805
- ]
6806
- );
6807
- }
6808
- if (input.runtimeMode === "node") {
6809
- return singleStep(
6810
- displayTarget,
6811
- typescript ? "node-typescript" : "node",
6812
- cwd,
6813
- nodeRuntimeExecutable(),
6814
- [
6815
- ...typescript ? ["--experimental-strip-types"] : [],
6816
- `--input-type=${sourceRequiresModuleInput(input.source) ? "module" : "commonjs"}`,
6817
- "-e",
6818
- input.source,
6819
- ...programArgs
6820
- ]
6821
- );
6855
+ function runStep(step, options) {
6856
+ return new Promise((resolve) => {
6857
+ const startedAt = Date.now();
6858
+ let child;
6859
+ let settled = false;
6860
+ let timedOut = false;
6861
+ let stopped = false;
6862
+ let escalationTimer = null;
6863
+ let exitGraceTimer = null;
6864
+ let exited = false;
6865
+ let childExitCode = null;
6866
+ let childExitSignal = null;
6867
+ const finishStep = (exitCode, signal, spawnError) => {
6868
+ if (settled) return;
6869
+ settled = true;
6870
+ if (timedOut || stopped) killProcessTree(child, "SIGKILL");
6871
+ clearTimeout(timeoutTimer);
6872
+ if (escalationTimer) clearTimeout(escalationTimer);
6873
+ if (exitGraceTimer) clearTimeout(exitGraceTimer);
6874
+ for (const name of FORWARDED_SIGNALS) process.off(name, onSignal);
6875
+ resolve({
6876
+ exitCode,
6877
+ signal,
6878
+ durationMs: Date.now() - startedAt,
6879
+ timedOut,
6880
+ stopped,
6881
+ ...spawnError ? { spawnError } : {}
6882
+ });
6883
+ };
6884
+ const terminate = (reason) => {
6885
+ if (settled) return;
6886
+ if (reason === "timeout") timedOut = true;
6887
+ else stopped = true;
6888
+ killProcessTree(child, "SIGTERM");
6889
+ escalationTimer ??= setTimeout(() => {
6890
+ killProcessTree(child, "SIGKILL");
6891
+ }, KILL_ESCALATION_MS);
6892
+ if (exited) scheduleFinishAfterExit();
6893
+ };
6894
+ function scheduleFinishAfterExit() {
6895
+ if (settled || exitGraceTimer) return;
6896
+ exitGraceTimer = setTimeout(() => {
6897
+ child.stdout.destroy();
6898
+ child.stderr.destroy();
6899
+ finishStep(childExitCode, childExitSignal);
6900
+ }, KILL_ESCALATION_MS);
6901
+ }
6902
+ let signalCount = 0;
6903
+ const onSignal = () => {
6904
+ signalCount += 1;
6905
+ if (signalCount === 1) terminate("stopped");
6906
+ else killProcessTree(child, "SIGKILL");
6907
+ };
6908
+ try {
6909
+ child = (0, import_node_child_process.spawn)(step.command, step.args, {
6910
+ cwd: options.cwd,
6911
+ env: options.env,
6912
+ stdio: ["pipe", "pipe", "pipe"],
6913
+ detached: process.platform !== "win32",
6914
+ windowsHide: true,
6915
+ ...step.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
6916
+ });
6917
+ } catch (error) {
6918
+ const spawnError = asErrno(error);
6919
+ resolve({
6920
+ exitCode: null,
6921
+ signal: null,
6922
+ durationMs: Date.now() - startedAt,
6923
+ timedOut,
6924
+ stopped,
6925
+ spawnError
6926
+ });
6927
+ return;
6928
+ }
6929
+ const timeoutTimer = setTimeout(() => terminate("timeout"), options.timeoutMs);
6930
+ for (const name of FORWARDED_SIGNALS) process.on(name, onSignal);
6931
+ child.stdin.on("error", () => {
6932
+ });
6933
+ try {
6934
+ if (options.stdin) child.stdin.write(options.stdin);
6935
+ child.stdin.end();
6936
+ } catch {
6937
+ }
6938
+ child.stdout.setEncoding("utf8");
6939
+ child.stderr.setEncoding("utf8");
6940
+ child.stdout.on("data", options.onStdout);
6941
+ child.stderr.on("data", options.onStderr);
6942
+ child.once("error", (error) => finishStep(null, null, asErrno(error)));
6943
+ child.once("exit", (code, signal) => {
6944
+ exited = true;
6945
+ childExitCode = code;
6946
+ childExitSignal = signal;
6947
+ if (timedOut || stopped) scheduleFinishAfterExit();
6948
+ });
6949
+ child.once("close", (code, signal) => finishStep(code, signal));
6950
+ });
6951
+ }
6952
+ var CappedOutput = class {
6953
+ value = "";
6954
+ truncated = false;
6955
+ /** Returns exactly the bounded fragment newly accepted from this chunk. */
6956
+ append(chunk) {
6957
+ if (this.truncated || !chunk) return "";
6958
+ const currentBytes = Buffer.byteLength(this.value, "utf8");
6959
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
6960
+ const payloadCap = CLI_OUTPUT_PAYLOAD_BYTES;
6961
+ if (currentBytes + chunkBytes <= payloadCap) {
6962
+ this.value += chunk;
6963
+ return chunk;
6964
+ }
6965
+ const remainingBytes = Math.max(0, payloadCap - currentBytes);
6966
+ const prefix = truncateUtf8(chunk, remainingBytes);
6967
+ const accepted = `${prefix}${CLI_OUTPUT_TRUNCATION_MARKER}`;
6968
+ this.value += accepted;
6969
+ this.truncated = true;
6970
+ return accepted;
6822
6971
  }
6823
- throw new ExecutionTargetError(
6824
- "unsupported-runtime-mode",
6825
- `Capsule runtime mode ${JSON.stringify(input.runtimeMode)} is not replayable by the CLI for ${typescript ? "TypeScript" : "JavaScript"}; supported modes are worker and node.`
6826
- );
6972
+ };
6973
+ function forwardOutput(output, chunk, listener) {
6974
+ const accepted = output.append(chunk);
6975
+ if (accepted) listener?.(accepted);
6827
6976
  }
6828
- function nodeRuntimeExecutable(options) {
6829
- const sea = options?.sea ?? (0, import_node_sea.isSea)();
6830
- return sea ? commandName("node") : options?.execPath ?? process.execPath;
6977
+ function asErrno(error) {
6978
+ return error instanceof Error ? error : new Error(String(error));
6831
6979
  }
6832
- async function findPython(startDirectory, env = process.env, platform = process.platform) {
6833
- const resolved = await resolvePythonInterpreter(
6834
- { startDirectory, platform, env, walkUp: true, respectPythonEnv: true },
6835
- async (candidate) => {
6836
- if (candidate.source === "path") {
6837
- return await executableIsOnPath(candidate.command, platform, env) ? commandName(candidate.command) : null;
6980
+ function killProcessTree(child, signal) {
6981
+ const pid = child.pid;
6982
+ if (process.platform === "win32") {
6983
+ if (typeof child.exitCode === "number" || typeof child.signalCode === "string") return;
6984
+ if (typeof pid === "number" && pid > 0) {
6985
+ try {
6986
+ (0, import_node_child_process.execFile)("taskkill", ["/pid", String(pid), "/T", "/F"], (error) => {
6987
+ if (!error) return;
6988
+ try {
6989
+ child.kill(signal);
6990
+ } catch {
6991
+ }
6992
+ });
6993
+ return;
6994
+ } catch {
6838
6995
  }
6839
- if (candidate.source === "python-env") return candidate.command;
6840
- return await isFile(candidate.command) ? candidate.command : null;
6841
6996
  }
6842
- );
6843
- return resolved ?? commandName(pythonCommandCandidates(platform)[0]);
6844
- }
6845
- async function executableIsOnPath(executable, platform = process.platform, env = process.env) {
6846
- const pathValue = env.PATH ?? env.Path ?? env.path;
6847
- if (!pathValue) return false;
6848
- const windows = platform === "win32";
6849
- const pathApi = windows ? import_node_path3.default.win32 : import_node_path3.default.posix;
6850
- const delimiter = windows ? ";" : ":";
6851
- const extensions = windows ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()) : [""];
6852
- const hasExtension = pathApi.extname(executable).length > 0;
6853
- for (const rawEntry of pathValue.split(delimiter)) {
6854
- const entry = rawEntry.trim().replace(/^"|"$/gu, "");
6855
- if (!entry) continue;
6856
- const base = pathApi.join(entry, executable);
6857
- const candidates = windows && !hasExtension ? extensions.map((extension) => base + extension) : [base];
6858
- for (const candidate of candidates) {
6859
- if (await isExecutableFile(candidate, platform)) return true;
6997
+ try {
6998
+ child.kill(signal);
6999
+ } catch {
6860
7000
  }
7001
+ return;
6861
7002
  }
6862
- return false;
6863
- }
6864
- function commandName(name) {
6865
- return process.platform === "win32" && ["npm", "npx"].includes(name) ? `${name}.cmd` : name;
6866
- }
6867
- async function exists(filePath) {
6868
- try {
6869
- await (0, import_promises2.access)(filePath);
6870
- return true;
6871
- } catch {
6872
- return false;
7003
+ if (typeof pid === "number" && pid > 0) {
7004
+ try {
7005
+ process.kill(-pid, signal);
7006
+ return;
7007
+ } catch {
7008
+ }
6873
7009
  }
6874
- }
6875
- async function isFile(filePath) {
6876
7010
  try {
6877
- return (await (0, import_promises2.stat)(filePath)).isFile();
7011
+ child.kill(signal);
6878
7012
  } catch {
6879
- return false;
6880
7013
  }
6881
7014
  }
6882
- async function isExecutableFile(filePath, platform = process.platform) {
6883
- if (!await isFile(filePath)) return false;
6884
- if (platform === "win32") return true;
6885
- try {
6886
- await (0, import_promises2.access)(filePath, import_node_fs.constants.X_OK);
6887
- return true;
6888
- } catch {
6889
- return false;
7015
+
7016
+ // src/cli/presentation.ts
7017
+ var ANSI = {
7018
+ reset: "\x1B[0m",
7019
+ bold: "\x1B[1m",
7020
+ cyan: "\x1B[36m",
7021
+ green: "\x1B[32m",
7022
+ red: "\x1B[31m",
7023
+ yellow: "\x1B[33m"
7024
+ };
7025
+ function shouldUseColor(io, mode = "auto", stream) {
7026
+ if (mode === "always") return true;
7027
+ if (mode === "never") return false;
7028
+ if (io.getEnvironmentValue("NO_COLOR") !== void 0) return false;
7029
+ return stream === "stdout" ? io.stdoutSupportsColor : io.stderrSupportsColor;
7030
+ }
7031
+ function styleCliText(io, mode, stream, style, text) {
7032
+ if (!shouldUseColor(io, mode, stream)) return text;
7033
+ return `${ANSI[style]}${text}${ANSI.reset}`;
7034
+ }
7035
+ function emitCliFailure(io, options, failure) {
7036
+ if (options.json) {
7037
+ io.writeStdout(
7038
+ `${JSON.stringify({ ok: false, ...failure.extra ?? {}, reason: failure.reason, detail: failure.detail })}
7039
+ `
7040
+ );
7041
+ return;
6890
7042
  }
7043
+ if (options.quiet) return;
7044
+ const label2 = styleCliText(io, options.color, "stderr", "bold", failure.label);
7045
+ const marker = styleCliText(io, options.color, "stderr", "red", `error[${failure.reason}]`);
7046
+ io.writeStderr(`${label2}: ${marker}: ${failure.detail}
7047
+ `);
6891
7048
  }
6892
- function isRecord2(value) {
6893
- return typeof value === "object" && value !== null && !Array.isArray(value);
7049
+ function renderCliHelp(io, mode, helpText) {
7050
+ if (!shouldUseColor(io, mode, "stdout")) return helpText;
7051
+ const lines = helpText.split("\n");
7052
+ return lines.map((line, index) => {
7053
+ if (index === 0) return styleCliText(io, mode, "stdout", "cyan", line);
7054
+ if (/^(Usage|Commands|Flags|Exit codes|Examples):$/u.test(line)) {
7055
+ return styleCliText(io, mode, "stdout", "bold", line);
7056
+ }
7057
+ return line;
7058
+ }).join("\n");
6894
7059
  }
6895
- function errnoCode(error) {
6896
- return error && typeof error === "object" && "code" in error ? String(error.code) : void 0;
7060
+ function renderCliSuccess(io, mode, text) {
7061
+ return styleCliText(io, mode, "stdout", "green", text);
6897
7062
  }
6898
- function errorMessage(error) {
6899
- return error instanceof Error ? error.message : String(error);
7063
+ function renderCliNotice(io, mode, text, tone = "warning") {
7064
+ return styleCliText(io, mode, "stderr", tone === "success" ? "green" : "yellow", text);
7065
+ }
7066
+
7067
+ // src/cli/runtime/environment.ts
7068
+ var COMMON_KEYS = ["PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "TEMP", "TMP"];
7069
+ var TOOLCHAIN_KEYS = [
7070
+ "NODE_PATH",
7071
+ "NPM_CONFIG_CACHE",
7072
+ "NPM_CONFIG_PREFIX",
7073
+ "PYTHON",
7074
+ "VIRTUAL_ENV",
7075
+ "PYTHONPATH",
7076
+ "PYENV_VERSION",
7077
+ "GOROOT",
7078
+ "GOPATH",
7079
+ "GOMODCACHE",
7080
+ "GOCACHE",
7081
+ "GOTMPDIR",
7082
+ "GOPROXY",
7083
+ "GOSUMDB",
7084
+ "GOFLAGS",
7085
+ "GOTOOLCHAIN",
7086
+ "CARGO_HOME",
7087
+ "RUSTUP_HOME",
7088
+ "RUSTUP_TOOLCHAIN",
7089
+ "RUSTC",
7090
+ "CARGO",
7091
+ "GEM_HOME",
7092
+ "GEM_PATH",
7093
+ "BUNDLE_GEMFILE",
7094
+ "RBENV_VERSION",
7095
+ "RBENV_ROOT",
7096
+ "ASDF_RUBY_VERSION"
7097
+ ];
7098
+ var WINDOWS_KEYS = ["SYSTEMROOT", "USERPROFILE", "PATHEXT", "COMSPEC"];
7099
+ var BLOCKED_EXPLICIT_KEYS = /* @__PURE__ */ new Set([
7100
+ "LD_PRELOAD",
7101
+ "LD_AUDIT",
7102
+ "LD_LIBRARY_PATH",
7103
+ "DYLD_INSERT_LIBRARIES",
7104
+ "DYLD_LIBRARY_PATH",
7105
+ "DYLD_FRAMEWORK_PATH",
7106
+ "NODE_OPTIONS"
7107
+ ]);
7108
+ var CliEnvironmentError = class extends Error {
7109
+ constructor(key) {
7110
+ super(`Environment variable ${key} is blocked because it can inject code into the runtime.`);
7111
+ this.key = key;
7112
+ this.name = "CliEnvironmentError";
7113
+ }
7114
+ key;
7115
+ reason = "blocked-environment-variable";
7116
+ };
7117
+ function buildCliRuntimeEnvironment(explicit) {
7118
+ const result = {};
7119
+ const keys = [
7120
+ ...COMMON_KEYS,
7121
+ ...TOOLCHAIN_KEYS,
7122
+ ...process.platform === "win32" ? WINDOWS_KEYS : []
7123
+ ];
7124
+ for (const key of keys) {
7125
+ const value = process.env[key];
7126
+ if (typeof value === "string" && value.length > 0) result[key] = value;
7127
+ }
7128
+ for (const { key, value } of explicit) {
7129
+ if (BLOCKED_EXPLICIT_KEYS.has(key.toUpperCase())) {
7130
+ throw new CliEnvironmentError(key);
7131
+ }
7132
+ result[key] = value;
7133
+ }
7134
+ return result;
6900
7135
  }
6901
7136
 
6902
7137
  // src/cli/commands/run.ts
6903
7138
  async function runTargetCommand(args, io) {
7139
+ const timeoutMs = clampCliRunTimeout(args.timeoutMs);
6904
7140
  let stdin;
6905
7141
  if (args.stdinPath) {
6906
7142
  try {
@@ -6916,7 +7152,17 @@ async function runTargetCommand(args, io) {
6916
7152
  }
6917
7153
  } else {
6918
7154
  try {
6919
- stdin = await io.readStdin() ?? void 0;
7155
+ const piped = await readStdinWithin(io, timeoutMs);
7156
+ if (piped === STDIN_TIMED_OUT) {
7157
+ return emitPreflightError(
7158
+ args,
7159
+ io,
7160
+ "timeout",
7161
+ `Run timed out after ${timeoutMs}ms while waiting for piped stdin to close.`,
7162
+ CLI_EXIT_CODES.runtimeError
7163
+ );
7164
+ }
7165
+ stdin = piped ?? void 0;
6920
7166
  } catch (error) {
6921
7167
  return emitPreflightError(
6922
7168
  args,
@@ -6962,7 +7208,7 @@ async function runTargetCommand(args, io) {
6962
7208
  }
6963
7209
  const result = await executeCliPlan(plan, {
6964
7210
  ...stdin !== void 0 ? { stdin } : {},
6965
- ...args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : {},
7211
+ timeoutMs,
6966
7212
  env,
6967
7213
  ...!args.json ? { onStdout: io.writeStdout, onStderr: io.writeStderr } : {}
6968
7214
  });
@@ -6971,7 +7217,7 @@ async function runTargetCommand(args, io) {
6971
7217
  if (result.reason === "missing-runtime") return CLI_EXIT_CODES.unsupportedCapability;
6972
7218
  return CLI_EXIT_CODES.runtimeError;
6973
7219
  }
6974
- function emitExecution(args, io, result, extra = {}, label = "lingua run", streamsAlreadyEmitted = false) {
7220
+ function emitExecution(args, io, result, extra = {}, label2 = "lingua run", streamsAlreadyEmitted = false) {
6975
7221
  if (args.json) {
6976
7222
  const failure = result.status === "success" ? {} : {
6977
7223
  reason: result.reason ?? result.status,
@@ -6989,16 +7235,35 @@ function emitExecution(args, io, result, extra = {}, label = "lingua run", strea
6989
7235
  if (result.status !== "success" && !args.quiet) {
6990
7236
  const detail = result.detail ?? `Run failed with status ${result.status}.`;
6991
7237
  emitCliFailure(io, args, {
6992
- label,
7238
+ label: label2,
6993
7239
  reason: result.reason ?? result.status,
6994
7240
  detail
6995
7241
  });
6996
7242
  }
6997
7243
  }
6998
- function emitPreflightError(args, io, reason, detail, exitCode, extra = {}, label = "lingua run") {
6999
- emitCliFailure(io, args, { label, reason, detail, extra });
7244
+ function emitPreflightError(args, io, reason, detail, exitCode, extra = {}, label2 = "lingua run") {
7245
+ emitCliFailure(io, args, { label: label2, reason, detail, extra });
7000
7246
  return exitCode;
7001
7247
  }
7248
+ var STDIN_TIMED_OUT = /* @__PURE__ */ Symbol("stdin-timed-out");
7249
+ async function readStdinWithin(io, timeoutMs) {
7250
+ const controller = new AbortController();
7251
+ const reading = io.readStdin({ signal: controller.signal });
7252
+ reading.catch(() => {
7253
+ });
7254
+ let timer;
7255
+ const timedOut = new Promise((resolve) => {
7256
+ timer = setTimeout(() => {
7257
+ resolve(STDIN_TIMED_OUT);
7258
+ controller.abort();
7259
+ }, timeoutMs);
7260
+ });
7261
+ try {
7262
+ return await Promise.race([reading, timedOut]);
7263
+ } finally {
7264
+ clearTimeout(timer);
7265
+ }
7266
+ }
7002
7267
  function errorMessage2(error) {
7003
7268
  return error instanceof Error ? error.message : String(error);
7004
7269
  }
@@ -7023,50 +7288,88 @@ async function runValidateCapsuleCommand(args, io) {
7023
7288
  return CLI_EXIT_CODES.ok;
7024
7289
  }
7025
7290
  async function runReplayCapsuleCommand(args, io) {
7026
- const label = "lingua capsule replay";
7291
+ const label2 = "lingua capsule replay";
7292
+ const prepared = await prepareCapsuleExecution(args, io, label2, { command: "capsule-replay" });
7293
+ if (!prepared.ok) return prepared.exitCode;
7294
+ const { capsule, env, plan } = prepared;
7295
+ const result = await executeCliPlan(plan, {
7296
+ ...capsule.input.stdin !== void 0 ? { stdin: capsule.input.stdin } : {},
7297
+ ...args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : {},
7298
+ env,
7299
+ ...!args.json ? { onStdout: io.writeStdout, onStderr: io.writeStderr } : {}
7300
+ });
7301
+ const comparison = compareCapsuleStreams(capsule, result);
7302
+ emitExecution(
7303
+ args,
7304
+ io,
7305
+ result,
7306
+ {
7307
+ command: "capsule-replay",
7308
+ capsuleId: capsule.capsuleId,
7309
+ recordedStatus: capsule.result.status,
7310
+ comparison
7311
+ },
7312
+ label2,
7313
+ !args.json
7314
+ );
7315
+ if (!args.json && !args.quiet) {
7316
+ const comparisonNotice = `${label2}: ${comparison.matches ? "recorded output matches" : "recorded output differs"} (status=${comparison.status}, stdout=${comparison.stdout}, stderr=${comparison.stderr})`;
7317
+ io.writeStderr(
7318
+ `${renderCliNotice(io, args.color, comparisonNotice, comparison.matches ? "success" : "warning")}
7319
+ `
7320
+ );
7321
+ }
7322
+ if (result.status === "success") return CLI_EXIT_CODES.ok;
7323
+ if (result.reason === "missing-runtime") return CLI_EXIT_CODES.unsupportedCapability;
7324
+ return CLI_EXIT_CODES.runtimeError;
7325
+ }
7326
+ async function prepareCapsuleExecution(args, io, label2, extra, options = {}) {
7027
7327
  const loaded = await loadCapsule(args.filePath, io);
7028
7328
  if (!loaded.ok) {
7029
- return emitPreflightError(
7030
- args,
7031
- io,
7032
- loaded.reason,
7033
- loaded.detail ?? "Capsule validation failed.",
7034
- CLI_EXIT_CODES.userInputError,
7035
- { command: "capsule-replay" },
7036
- label
7037
- );
7329
+ return {
7330
+ ok: false,
7331
+ exitCode: emitPreflightError(
7332
+ args,
7333
+ io,
7334
+ loaded.reason,
7335
+ loaded.detail ?? "Capsule validation failed.",
7336
+ CLI_EXIT_CODES.userInputError,
7337
+ extra,
7338
+ label2
7339
+ )
7340
+ };
7038
7341
  }
7039
- const capsule = loaded.value;
7040
- const actualHash = await computeContentHash(capsule.source.content);
7041
- if (actualHash !== capsule.source.contentHash) {
7042
- return emitPreflightError(
7043
- args,
7044
- io,
7342
+ return prepareLoadedCapsuleExecution(loaded.value, args, io, label2, extra, options);
7343
+ }
7344
+ async function prepareLoadedCapsuleExecution(capsule, args, io, label2, extra, { gate, resolvePlan, classifyResolveError } = {}) {
7345
+ const refuse = (reason, detail, exitCode, fields = extra) => ({
7346
+ ok: false,
7347
+ exitCode: emitPreflightError(args, io, reason, detail, exitCode, fields, label2)
7348
+ });
7349
+ const identified = { ...extra, capsuleId: capsule.capsuleId };
7350
+ if (await computeContentHash(capsule.source.content) !== capsule.source.contentHash) {
7351
+ return refuse(
7045
7352
  "content-hash-mismatch",
7046
7353
  "Capsule source content does not match its recorded SHA-256 hash; refusing to execute it.",
7047
7354
  CLI_EXIT_CODES.userInputError,
7048
- { command: "capsule-replay", capsuleId: capsule.capsuleId },
7049
- label
7355
+ identified
7050
7356
  );
7051
7357
  }
7358
+ const refusal = gate?.(capsule);
7359
+ if (refusal) return refuse(refusal.reason, refusal.detail, refusal.exitCode, identified);
7052
7360
  let env;
7053
7361
  try {
7054
7362
  env = buildCliRuntimeEnvironment(args.env);
7055
7363
  } catch (error) {
7056
- const reason = error instanceof CliEnvironmentError ? error.reason : "environment-resolution-failed";
7057
- return emitPreflightError(
7058
- args,
7059
- io,
7060
- reason,
7364
+ return refuse(
7365
+ error instanceof CliEnvironmentError ? error.reason : "environment-resolution-failed",
7061
7366
  errorMessage3(error),
7062
7367
  CLI_EXIT_CODES.userInputError,
7063
- { command: "capsule-replay", capsuleId: capsule.capsuleId },
7064
- label
7368
+ identified
7065
7369
  );
7066
7370
  }
7067
- let plan;
7068
7371
  try {
7069
- plan = await resolveCapsuleSource(
7372
+ const plan = resolvePlan ? await resolvePlan(capsule, env) : await resolveCapsuleSource(
7070
7373
  {
7071
7374
  language: capsule.tab.language,
7072
7375
  runtimeMode: capsule.tab.runtimeMode,
@@ -7076,58 +7379,22 @@ async function runReplayCapsuleCommand(args, io) {
7076
7379
  capsule.input.args ?? [],
7077
7380
  env
7078
7381
  );
7382
+ return { ok: true, capsule, env, plan };
7079
7383
  } catch (error) {
7384
+ const classified = classifyResolveError?.(error);
7385
+ if (classified) {
7386
+ return refuse(classified.reason, classified.detail, classified.exitCode, identified);
7387
+ }
7080
7388
  if (error instanceof ExecutionTargetError) {
7081
- return emitPreflightError(
7082
- args,
7083
- io,
7084
- error.reason,
7085
- error.message,
7086
- CLI_EXIT_CODES.unsupportedCapability,
7087
- { command: "capsule-replay", capsuleId: capsule.capsuleId },
7088
- label
7089
- );
7389
+ return refuse(error.reason, error.message, CLI_EXIT_CODES.unsupportedCapability, identified);
7090
7390
  }
7091
- return emitPreflightError(
7092
- args,
7093
- io,
7391
+ return refuse(
7094
7392
  "target-resolution-failed",
7095
7393
  errorMessage3(error),
7096
7394
  CLI_EXIT_CODES.internal,
7097
- { command: "capsule-replay", capsuleId: capsule.capsuleId },
7098
- label
7099
- );
7100
- }
7101
- const result = await executeCliPlan(plan, {
7102
- ...capsule.input.stdin !== void 0 ? { stdin: capsule.input.stdin } : {},
7103
- ...args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : {},
7104
- env,
7105
- ...!args.json ? { onStdout: io.writeStdout, onStderr: io.writeStderr } : {}
7106
- });
7107
- const comparison = compareReplay(capsule, result);
7108
- emitExecution(
7109
- args,
7110
- io,
7111
- result,
7112
- {
7113
- command: "capsule-replay",
7114
- capsuleId: capsule.capsuleId,
7115
- recordedStatus: capsule.result.status,
7116
- comparison
7117
- },
7118
- label,
7119
- !args.json
7120
- );
7121
- if (!args.json && !args.quiet) {
7122
- const comparisonNotice = `${label}: ${comparison.matches ? "recorded output matches" : "recorded output differs"} (status=${comparison.status}, stdout=${comparison.stdout}, stderr=${comparison.stderr})`;
7123
- io.writeStderr(
7124
- `${renderCliNotice(io, args.color, comparisonNotice, comparison.matches ? "success" : "warning")}
7125
- `
7395
+ identified
7126
7396
  );
7127
7397
  }
7128
- if (result.status === "success") return CLI_EXIT_CODES.ok;
7129
- if (result.reason === "missing-runtime") return CLI_EXIT_CODES.unsupportedCapability;
7130
- return CLI_EXIT_CODES.runtimeError;
7131
7398
  }
7132
7399
  async function loadCapsule(filePath, io) {
7133
7400
  let raw;
@@ -7143,12 +7410,6 @@ async function loadCapsule(filePath, io) {
7143
7410
  }
7144
7411
  return parseRunCapsule(raw);
7145
7412
  }
7146
- function compareReplay(capsule, result) {
7147
- const status = capsule.result.status === result.status;
7148
- const stdout = (capsule.result.stdout ?? "") === result.stdout;
7149
- const stderr = (capsule.result.stderr ?? "") === result.stderr;
7150
- return { matches: status && stdout && stderr, status, stdout, stderr };
7151
- }
7152
7413
  function emit(io, args, ok, reasonOrSummary, detail) {
7153
7414
  if (args.json) {
7154
7415
  const body = ok ? { ok: true, summary: reasonOrSummary } : detail !== void 0 ? { ok: false, reason: reasonOrSummary, detail } : { ok: false, reason: reasonOrSummary };
@@ -7172,11 +7433,242 @@ function errorMessage3(error) {
7172
7433
  return error instanceof Error ? error.message : String(error);
7173
7434
  }
7174
7435
 
7436
+ // src/cli/commands/capsuleVerify.ts
7437
+ var label = "lingua capsule verify";
7438
+ var preflightFields = { command: "capsule-verify", verdict: "inconclusive" };
7439
+ async function runVerifyCapsuleCommand(args, io) {
7440
+ const loaded = await loadCapsule(args.filePath, io);
7441
+ if (!loaded.ok)
7442
+ return emitPreflightError(
7443
+ args,
7444
+ io,
7445
+ loaded.reason,
7446
+ loaded.detail ?? "Capsule validation failed.",
7447
+ CLI_EXIT_CODES.userInputError,
7448
+ preflightFields,
7449
+ label
7450
+ );
7451
+ return verifyCapsuleBaseline(loaded.value, args, io);
7452
+ }
7453
+ var refusalDetails = {
7454
+ "engine-divergent-baseline": {
7455
+ detail: "The recording came from a different engine than the CLI runtime, so its output is not a comparable baseline.",
7456
+ exitCode: CLI_EXIT_CODES.verificationInconclusive
7457
+ },
7458
+ "unsupported-runtime-mode": {
7459
+ detail: "Browser-preview baselines require a DOM unavailable to the CLI.",
7460
+ exitCode: CLI_EXIT_CODES.unsupportedCapability
7461
+ }
7462
+ };
7463
+ function verificationGate(capsule) {
7464
+ const reason = capsuleStrictVerificationRefusal(capsule);
7465
+ if (!reason) return null;
7466
+ return {
7467
+ reason,
7468
+ ...refusalDetails[reason] ?? {
7469
+ detail: "The recording cannot supply a complete successful stdout/stderr baseline.",
7470
+ exitCode: CLI_EXIT_CODES.verificationInconclusive
7471
+ }
7472
+ };
7473
+ }
7474
+ async function verifyCapsuleBaseline(capsule, args, io) {
7475
+ const { targetPath } = args;
7476
+ const prepared = await prepareLoadedCapsuleExecution(capsule, args, io, label, preflightFields, {
7477
+ gate: verificationGate,
7478
+ ...targetPath !== void 0 ? {
7479
+ resolvePlan: async (recorded, env2) => resolveCapsuleSource(
7480
+ {
7481
+ language: recorded.tab.language,
7482
+ runtimeMode: recorded.tab.runtimeMode,
7483
+ source: await readRegressionTarget(
7484
+ args.rootDirectory ?? process.cwd(),
7485
+ targetPath,
7486
+ recorded.tab.language,
7487
+ MAX_REGRESSION_SUITE_BYTES
7488
+ ),
7489
+ capsuleId: recorded.capsuleId
7490
+ },
7491
+ recorded.input.args ?? [],
7492
+ env2
7493
+ ),
7494
+ classifyResolveError: (error) => error instanceof RegressionTargetError ? {
7495
+ reason: "invalid-regression-target",
7496
+ detail: error.message,
7497
+ exitCode: CLI_EXIT_CODES.userInputError
7498
+ } : null
7499
+ } : {}
7500
+ });
7501
+ if (!prepared.ok) return prepared.exitCode;
7502
+ const { env, plan } = prepared;
7503
+ const remaining = args.deadline === void 0 ? void 0 : args.deadline - Date.now();
7504
+ const requestedTimeout = args.timeoutMs ?? DEFAULT_CLI_RUN_TIMEOUT_MS;
7505
+ const budgetCapped = remaining !== void 0 && remaining < requestedTimeout;
7506
+ if (remaining !== void 0 && remaining < MIN_CLI_RUN_TIMEOUT_MS) {
7507
+ await Promise.all(
7508
+ (plan.cleanupPaths ?? []).map(
7509
+ (file) => (0, import_promises4.rm)(file, { recursive: true, force: true }).catch(() => {
7510
+ })
7511
+ )
7512
+ );
7513
+ return emitPreflightError(
7514
+ args,
7515
+ io,
7516
+ "suite-budget-exhausted",
7517
+ "The total suite execution budget is exhausted.",
7518
+ CLI_EXIT_CODES.verificationInconclusive,
7519
+ { ...preflightFields, capsuleId: capsule.capsuleId },
7520
+ label
7521
+ );
7522
+ }
7523
+ const run = await executeCliPlan(plan, {
7524
+ env,
7525
+ ...capsule.input.stdin !== void 0 ? { stdin: capsule.input.stdin } : {},
7526
+ ...remaining !== void 0 ? { timeoutMs: Math.min(requestedTimeout, remaining) } : args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : {}
7527
+ });
7528
+ const budgetExhausted = budgetCapped && run.status === "timeout";
7529
+ const comparison = compareCapsuleStreams(capsule, run);
7530
+ const incomplete = Boolean(
7531
+ run.truncated?.stdout || run.truncated?.stderr || run.status === "timeout" || run.status === "stopped" || run.reason === "missing-runtime" || run.reason === "spawn-failed" || run.reason === "prepare-failed"
7532
+ );
7533
+ const verdict = incomplete ? "inconclusive" : comparison.matches ? "pass" : "fail";
7534
+ const result = {
7535
+ ok: verdict === "pass",
7536
+ command: "capsule-verify",
7537
+ capsuleId: capsule.capsuleId,
7538
+ sourceMode: targetPath === void 0 ? "captured" : "current-target",
7539
+ ...targetPath !== void 0 ? { target: targetPath } : {},
7540
+ verdict,
7541
+ comparison,
7542
+ recordedRuntime: capsule.environment.runner,
7543
+ actualRuntime: run.runtime,
7544
+ ...budgetExhausted ? { reason: "suite-budget-exhausted" } : incomplete ? { reason: run.reason ?? "incomplete-execution" } : run.reason ? { reason: run.reason } : verdict === "fail" ? { reason: "output-drift" } : {},
7545
+ run
7546
+ };
7547
+ if (args.json) io.writeStdout(`${JSON.stringify(result)}
7548
+ `);
7549
+ else {
7550
+ emitExecution(args, io, run, {}, label, true);
7551
+ if (!args.quiet) {
7552
+ const notice = `${label}: ${verdict}${result.reason ? ` (${result.reason})` : ""} (status=${comparison.status}, stdout=${comparison.stdout}, stderr=${comparison.stderr}, recorded=${result.recordedRuntime}, actual=${result.actualRuntime})`;
7553
+ io.writeStderr(
7554
+ `${renderCliNotice(io, args.color, notice, verdict === "pass" ? "success" : "warning")}
7555
+ `
7556
+ );
7557
+ }
7558
+ }
7559
+ if (budgetExhausted) return CLI_EXIT_CODES.verificationInconclusive;
7560
+ if (run.status !== "success")
7561
+ return run.reason === "missing-runtime" ? CLI_EXIT_CODES.unsupportedCapability : CLI_EXIT_CODES.runtimeError;
7562
+ return verdict === "pass" ? CLI_EXIT_CODES.ok : verdict === "fail" ? CLI_EXIT_CODES.verificationFailed : CLI_EXIT_CODES.verificationInconclusive;
7563
+ }
7564
+
7565
+ // src/cli/commands/capsuleSuite.ts
7566
+ var REGRESSION_SUITE_BUDGET_MS = 5 * 6e4;
7567
+ async function runVerifyCapsuleSuiteCommand(args, io) {
7568
+ const deadline = Date.now() + REGRESSION_SUITE_BUDGET_MS;
7569
+ const fail = (reason) => emitPreflightError(
7570
+ args,
7571
+ io,
7572
+ reason,
7573
+ "Invalid regression suite; no code executed.",
7574
+ CLI_EXIT_CODES.userInputError,
7575
+ { command: "capsule-verify-suite", verdict: "inconclusive" },
7576
+ "lingua capsule verify-suite"
7577
+ );
7578
+ let raw;
7579
+ try {
7580
+ raw = await readBoundedSuite(args.filePath, MAX_REGRESSION_SUITE_BYTES);
7581
+ } catch (error) {
7582
+ return fail(
7583
+ error instanceof Error && error.message === "suite-too-large" ? "suite-too-large" : "suite-read-failed"
7584
+ );
7585
+ }
7586
+ const parsed = parseCapsuleRegressionSuite(raw);
7587
+ if (!parsed.ok) return fail(parsed.reason);
7588
+ for (const testCase of parsed.suite.cases) {
7589
+ if (await computeContentHash(testCase.baseline.source.content) !== testCase.baseline.source.contentHash)
7590
+ return fail("content-hash-mismatch");
7591
+ try {
7592
+ await readRegressionTarget(
7593
+ args.rootDirectory ?? process.cwd(),
7594
+ testCase.target,
7595
+ testCase.baseline.tab.language,
7596
+ MAX_REGRESSION_SUITE_BYTES
7597
+ );
7598
+ } catch {
7599
+ return fail("invalid-regression-target");
7600
+ }
7601
+ }
7602
+ const cases = [];
7603
+ const exits = [];
7604
+ for (const testCase of parsed.suite.cases) {
7605
+ if (Date.now() >= deadline - 100) {
7606
+ exits.push(CLI_EXIT_CODES.verificationInconclusive);
7607
+ cases.push({
7608
+ id: testCase.id,
7609
+ name: testCase.name,
7610
+ target: testCase.target,
7611
+ ok: false,
7612
+ verdict: "inconclusive",
7613
+ skipped: true,
7614
+ reason: "suite-budget-exhausted"
7615
+ });
7616
+ continue;
7617
+ }
7618
+ let report = "";
7619
+ const code = await verifyCapsuleBaseline(
7620
+ testCase.baseline,
7621
+ { ...args, targetPath: testCase.target, deadline, json: true, quiet: false },
7622
+ {
7623
+ ...io,
7624
+ writeStdout: (text) => {
7625
+ report += text;
7626
+ },
7627
+ writeStderr: () => {
7628
+ }
7629
+ }
7630
+ );
7631
+ exits.push(code);
7632
+ cases.push({
7633
+ ...JSON.parse(report),
7634
+ id: testCase.id,
7635
+ name: testCase.name,
7636
+ target: testCase.target,
7637
+ exitCode: code
7638
+ });
7639
+ }
7640
+ const summary = {
7641
+ total: cases.length,
7642
+ passed: cases.filter((c) => c.verdict === "pass").length,
7643
+ failed: cases.filter((c) => c.verdict === "fail").length,
7644
+ inconclusive: cases.filter((c) => c.verdict === "inconclusive").length,
7645
+ skipped: cases.filter((c) => c.skipped).length
7646
+ };
7647
+ const verdict = summary.failed ? "fail" : summary.inconclusive ? "inconclusive" : "pass";
7648
+ const result = {
7649
+ ok: verdict === "pass",
7650
+ command: "capsule-verify-suite",
7651
+ suiteVersion: 1,
7652
+ verdict,
7653
+ summary,
7654
+ cases
7655
+ };
7656
+ if (args.json) io.writeStdout(`${JSON.stringify(result)}
7657
+ `);
7658
+ else if (!args.quiet)
7659
+ io.writeStdout(
7660
+ `lingua capsule verify-suite: ${verdict} (${summary.passed}/${summary.total} passed, ${summary.failed} drift, ${summary.inconclusive} inconclusive)
7661
+ `
7662
+ );
7663
+ if (verdict === "fail") return CLI_EXIT_CODES.verificationFailed;
7664
+ return exits.find((code) => code > 0 && code < 5) ?? (verdict === "inconclusive" ? CLI_EXIT_CODES.verificationInconclusive : CLI_EXIT_CODES.ok);
7665
+ }
7666
+
7175
7667
  // src/cli/commands/completionInstall.ts
7176
- var import_node_fs2 = require("node:fs");
7177
- var import_promises3 = require("node:fs/promises");
7668
+ var import_node_fs3 = require("node:fs");
7669
+ var import_promises5 = require("node:fs/promises");
7178
7670
  var import_node_os2 = __toESM(require("node:os"));
7179
- var import_node_path4 = __toESM(require("node:path"));
7671
+ var import_node_path5 = __toESM(require("node:path"));
7180
7672
 
7181
7673
  // src/cli/commandModel.ts
7182
7674
  var CLI_COLOR_MODES = ["auto", "always", "never"];
@@ -7198,7 +7690,7 @@ var UTILITY_ADAPTER_IDS = [
7198
7690
  "url-parse",
7199
7691
  "regex-replace",
7200
7692
  "diff-text",
7201
- // implementation — adapter-vocabulary expansion. Core 4 transforms
7693
+ // adapter-vocabulary expansion. Core 4 transforms
7202
7694
  // plus the folded-in timestamp / color / string-case / html-entity
7203
7695
  // adapters. Each is a pure shared reimplementation (the shared layer
7204
7696
  // cannot import the renderer helpers; mirrors the base64 precedent).
@@ -7211,7 +7703,7 @@ var UTILITY_ADAPTER_IDS = [
7211
7703
  "string-case",
7212
7704
  "html-entity-encode",
7213
7705
  "html-entity-decode",
7214
- // implementation — vocabulary expansion round 2. Pure text→text
7706
+ // Vocabulary expansion round 2. Pure text→text
7215
7707
  // transforms (number radix, line sort, slugify, JSON minify, text
7216
7708
  // stats). Each is a self-contained shared reimplementation.
7217
7709
  "number-base",
@@ -7219,11 +7711,11 @@ var UTILITY_ADAPTER_IDS = [
7219
7711
  "slugify",
7220
7712
  "json-minify",
7221
7713
  "text-stats",
7222
- // implementation — generator-style holdouts. `uuid` + `lorem-ipsum`
7714
+ // generator-style holdouts. `uuid` + `lorem-ipsum`
7223
7715
  // are generators (they ignore the chained input and emit fresh data);
7224
7716
  // `string-inspect` is a transform. Their pure logic is shared with the
7225
7717
  // renderer panels via `src/shared/utilities/{uuid,loremIpsum,stringInspect}.ts`
7226
- // (the renderer utils now re-export — implementation note, no drift).
7718
+ // (the renderer utils now re-export, so no drift).
7227
7719
  "uuid",
7228
7720
  "lorem-ipsum",
7229
7721
  "string-inspect",
@@ -7289,7 +7781,7 @@ _lingua() {
7289
7781
  COMPREPLY=( $(compgen -W "${colorWords}" -- "$cur") )
7290
7782
  return
7291
7783
  ;;
7292
- --input|--stdin)
7784
+ --input|--stdin|--target|--root)
7293
7785
  compopt -o filenames 2>/dev/null || true
7294
7786
  COMPREPLY=( $(compgen -f -- "$cur") )
7295
7787
  return
@@ -7327,9 +7819,14 @@ _lingua() {
7327
7819
  capsule)
7328
7820
  relative=$(( COMP_CWORD - command_index ))
7329
7821
  if (( relative == 1 )); then
7330
- COMPREPLY=( $(compgen -W "validate replay" -- "$cur") )
7822
+ COMPREPLY=( $(compgen -W "validate replay verify verify-suite" -- "$cur") )
7331
7823
  elif [[ "$cur" == -* ]]; then
7332
- COMPREPLY=( $(compgen -W "--timeout --env --json --quiet --color --help" -- "$cur") )
7824
+ local flags="--timeout --env --json --quiet --color --help"
7825
+ case "\${COMP_WORDS[command_index+1]}" in
7826
+ verify) flags="$flags --target" ;;
7827
+ verify-suite) flags="$flags --root" ;;
7828
+ esac
7829
+ COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
7333
7830
  else
7334
7831
  compopt -o filenames 2>/dev/null || true
7335
7832
  COMPREPLY=( $(compgen -f -- "$cur") )
@@ -7362,7 +7859,7 @@ function renderZshCompletion() {
7362
7859
  _lingua() {
7363
7860
  local context state state_descr line
7364
7861
  typeset -A opt_args
7365
- local -a commands utilities color_modes completion_targets
7862
+ local -a commands utilities color_modes completion_targets capsule_flags
7366
7863
  local command_index index
7367
7864
  commands=(
7368
7865
  'utility:Run a shared utility adapter'
@@ -7434,11 +7931,17 @@ _lingua() {
7434
7931
  ;;
7435
7932
  capsule)
7436
7933
  if (( CURRENT == 2 )); then
7437
- _values 'capsule action' validate replay
7934
+ _values 'capsule action' validate replay verify verify-suite
7438
7935
  else
7936
+ capsule_flags=()
7937
+ case "\${words[2]}" in
7938
+ verify) capsule_flags=('--target=[Current relative source file]:file:_files') ;;
7939
+ verify-suite) capsule_flags=('--root=[Suite target root]:directory:_files -/') ;;
7940
+ esac
7439
7941
  _arguments \\
7440
7942
  '2:capsule file:_files' \\
7441
- '--timeout=[Set replay timeout in milliseconds]:milliseconds:' \\
7943
+ "\${capsule_flags[@]}" \\
7944
+ '--timeout=[Set per-case execution timeout in milliseconds]:milliseconds:' \\
7442
7945
  '*--env=[Add an explicit NAME=value environment entry]:environment:' \\
7443
7946
  '--json[Emit structured JSON]' \\
7444
7947
  '--quiet[Suppress Lingua diagnostics]' \\
@@ -7497,6 +8000,14 @@ function __fish_lingua_using_command
7497
8000
  test -n "$command_index"; and test "$tokens[$command_index]" = "$argv[1]"
7498
8001
  end
7499
8002
 
8003
+ function __fish_lingua_using_capsule_action
8004
+ set -l tokens (commandline -opc)
8005
+ set -l command_index (__fish_lingua_command_index)
8006
+ test -n "$command_index"; or return 1
8007
+ set -l action_index (math $command_index + 1)
8008
+ test "$tokens[$command_index]" = capsule; and test "$tokens[$action_index]" = "$argv[1]"
8009
+ end
8010
+
7500
8011
  function __fish_lingua_needs_first_argument
7501
8012
  set -l tokens (commandline -opc)
7502
8013
  set -l command_index (__fish_lingua_command_index)
@@ -7542,8 +8053,10 @@ complete -c lingua -n '__fish_lingua_using_command run' -l stdin -r -F -d 'Forwa
7542
8053
  complete -c lingua -n '__fish_lingua_using_command run' -l timeout -r -d 'Set wall-clock timeout in milliseconds'
7543
8054
  complete -c lingua -n '__fish_lingua_using_command run' -l env -r -d 'Add an explicit NAME=value environment entry'
7544
8055
 
7545
- complete -c lingua -n '__fish_lingua_needs_first_argument capsule' -a 'validate replay'
7546
- complete -c lingua -n '__fish_lingua_using_command capsule' -l timeout -r -d 'Set replay timeout in milliseconds'
8056
+ complete -c lingua -n '__fish_lingua_needs_first_argument capsule' -a 'validate replay verify verify-suite'
8057
+ complete -c lingua -n '__fish_lingua_using_capsule_action verify' -l target -r -d 'Current relative source file'
8058
+ complete -c lingua -n '__fish_lingua_using_capsule_action verify-suite' -l root -r -d 'Suite target root'
8059
+ complete -c lingua -n '__fish_lingua_using_command capsule' -l timeout -r -d 'Set per-case execution timeout in milliseconds'
7547
8060
  complete -c lingua -n '__fish_lingua_using_command capsule' -l env -r -d 'Add an explicit NAME=value environment entry'
7548
8061
 
7549
8062
  complete -c lingua -n '__fish_lingua_needs_first_argument list' -a 'utilities'
@@ -7565,55 +8078,55 @@ var defaultDependencies = {
7565
8078
  homedir: import_node_os2.default.homedir,
7566
8079
  async isExecutable(filePath) {
7567
8080
  try {
7568
- await (0, import_promises3.access)(filePath, import_node_fs2.constants.X_OK);
8081
+ await (0, import_promises5.access)(filePath, import_node_fs3.constants.X_OK);
7569
8082
  return true;
7570
8083
  } catch {
7571
8084
  return false;
7572
8085
  }
7573
8086
  },
7574
8087
  async mkdir(directoryPath) {
7575
- await (0, import_promises3.mkdir)(directoryPath, { recursive: true });
8088
+ await (0, import_promises5.mkdir)(directoryPath, { recursive: true });
7576
8089
  },
7577
8090
  async writeFile(filePath, contents) {
7578
- await (0, import_promises3.writeFile)(filePath, contents, "utf8");
8091
+ await (0, import_promises5.writeFile)(filePath, contents, "utf8");
7579
8092
  },
7580
8093
  async readFileIfPresent(filePath) {
7581
8094
  try {
7582
- return await (0, import_promises3.readFile)(filePath, "utf8");
8095
+ return await (0, import_promises5.readFile)(filePath, "utf8");
7583
8096
  } catch (error) {
7584
8097
  if (error.code === "ENOENT") return null;
7585
8098
  throw error;
7586
8099
  }
7587
8100
  },
7588
8101
  async appendFile(filePath, contents) {
7589
- await (0, import_promises3.appendFile)(filePath, contents, "utf8");
8102
+ await (0, import_promises5.appendFile)(filePath, contents, "utf8");
7590
8103
  }
7591
8104
  };
7592
8105
  function shellFromExecutable(executablePath) {
7593
8106
  if (!executablePath) return void 0;
7594
- const name = import_node_path4.default.basename(executablePath);
8107
+ const name = import_node_path5.default.basename(executablePath);
7595
8108
  return CLI_COMPLETION_SHELLS.includes(name) ? name : void 0;
7596
8109
  }
7597
8110
  function completionPathForShell(shell, io, dependencies) {
7598
8111
  const home = io.getEnvironmentValue("HOME") || dependencies.homedir();
7599
8112
  switch (shell) {
7600
8113
  case "bash": {
7601
- const dataHome = io.getEnvironmentValue("XDG_DATA_HOME") || import_node_path4.default.join(home, ".local/share");
8114
+ const dataHome = io.getEnvironmentValue("XDG_DATA_HOME") || import_node_path5.default.join(home, ".local/share");
7602
8115
  return {
7603
- completionPath: import_node_path4.default.join(dataHome, "bash-completion/completions/lingua")
8116
+ completionPath: import_node_path5.default.join(dataHome, "bash-completion/completions/lingua")
7604
8117
  };
7605
8118
  }
7606
8119
  case "zsh": {
7607
8120
  const zshHome = io.getEnvironmentValue("ZDOTDIR") || home;
7608
8121
  return {
7609
- completionPath: import_node_path4.default.join(zshHome, ".zfunc/_lingua"),
7610
- activationPath: import_node_path4.default.join(zshHome, ".zshrc")
8122
+ completionPath: import_node_path5.default.join(zshHome, ".zfunc/_lingua"),
8123
+ activationPath: import_node_path5.default.join(zshHome, ".zshrc")
7611
8124
  };
7612
8125
  }
7613
8126
  case "fish": {
7614
- const configHome = io.getEnvironmentValue("XDG_CONFIG_HOME") || import_node_path4.default.join(home, ".config");
8127
+ const configHome = io.getEnvironmentValue("XDG_CONFIG_HOME") || import_node_path5.default.join(home, ".config");
7615
8128
  return {
7616
- completionPath: import_node_path4.default.join(configHome, "fish/completions/lingua.fish")
8129
+ completionPath: import_node_path5.default.join(configHome, "fish/completions/lingua.fish")
7617
8130
  };
7618
8131
  }
7619
8132
  }
@@ -7623,9 +8136,9 @@ async function resolveExecutable(shell, io, dependencies) {
7623
8136
  if (shellFromExecutable(currentShellPath) === shell && currentShellPath !== void 0 && await dependencies.isExecutable(currentShellPath)) {
7624
8137
  return currentShellPath;
7625
8138
  }
7626
- const pathEntries = (io.getEnvironmentValue("PATH") || "").split(import_node_path4.default.delimiter).filter(Boolean);
8139
+ const pathEntries = (io.getEnvironmentValue("PATH") || "").split(import_node_path5.default.delimiter).filter(Boolean);
7627
8140
  for (const directory of pathEntries) {
7628
- const candidate = import_node_path4.default.join(directory, shell);
8141
+ const candidate = import_node_path5.default.join(directory, shell);
7629
8142
  if (await dependencies.isExecutable(candidate)) return candidate;
7630
8143
  }
7631
8144
  return void 0;
@@ -7708,7 +8221,7 @@ async function runCompletionInstallCommand(options, io, dependencies = defaultDe
7708
8221
  }
7709
8222
  }
7710
8223
  for (const target of targets) {
7711
- await dependencies.mkdir(import_node_path4.default.dirname(target.completionPath));
8224
+ await dependencies.mkdir(import_node_path5.default.dirname(target.completionPath));
7712
8225
  await dependencies.writeFile(target.completionPath, renderCompletion(target.shell));
7713
8226
  if (target.shell === "zsh" && target.activationPath) {
7714
8227
  await ensureZshActivation(target.activationPath, dependencies);
@@ -10024,7 +10537,7 @@ var cronPhraseAdapter = {
10024
10537
  function parseUrl(input) {
10025
10538
  try {
10026
10539
  const url = new URL(input);
10027
- const searchParams = {};
10540
+ const searchParams = /* @__PURE__ */ Object.create(null);
10028
10541
  for (const [key, value] of url.searchParams.entries()) {
10029
10542
  const existing = searchParams[key];
10030
10543
  if (existing === void 0) {
@@ -10159,7 +10672,7 @@ var UTILITY_ADAPTER_REGISTRY = {
10159
10672
  "url-parse": urlParseAdapter,
10160
10673
  "regex-replace": regexReplaceAdapter,
10161
10674
  "diff-text": diffTextAdapter,
10162
- // implementation — vocabulary expansion (core 4 + implementation note/B/C/E).
10675
+ // Vocabulary expansion (beyond the core 4).
10163
10676
  hash: hashAdapter,
10164
10677
  "jwt-decode": jwtDecodeAdapter,
10165
10678
  "url-encode": urlEncodeAdapter,
@@ -10169,13 +10682,13 @@ var UTILITY_ADAPTER_REGISTRY = {
10169
10682
  "string-case": stringCaseAdapter,
10170
10683
  "html-entity-encode": htmlEntityEncodeAdapter,
10171
10684
  "html-entity-decode": htmlEntityDecodeAdapter,
10172
- // implementation — vocabulary expansion round 2.
10685
+ // Vocabulary expansion round 2.
10173
10686
  "number-base": numberBaseAdapter,
10174
10687
  "line-sort": lineSortAdapter,
10175
10688
  slugify: slugifyAdapter,
10176
10689
  "json-minify": jsonMinifyAdapter,
10177
10690
  "text-stats": textStatsAdapter,
10178
- // implementation — generator-style holdouts (uuid / lorem / inspect).
10691
+ // generator-style holdouts (uuid / lorem / inspect).
10179
10692
  uuid: uuidAdapter,
10180
10693
  "lorem-ipsum": loremIpsumAdapter,
10181
10694
  "string-inspect": stringInspectAdapter,
@@ -10361,7 +10874,10 @@ var CLI_HELP_CATALOG = {
10361
10874
  description: "Uses the same shared utility adapters as the desktop app without loading Electron or a renderer.",
10362
10875
  flags: ["input", "option", "json", "quiet", "color", "help"],
10363
10876
  examples: [
10364
- { command: `echo '{"a":1}' | lingua utility json-format`, description: "Format piped JSON." },
10877
+ {
10878
+ command: `echo '{"a":1}' | lingua utility json-format`,
10879
+ description: "Format piped JSON."
10880
+ },
10365
10881
  {
10366
10882
  command: `echo 'cada 3 dias 8am' | lingua utility cron-phrase`,
10367
10883
  description: "Turn a plain-words schedule (English or Spanish) into a cron expression."
@@ -10404,6 +10920,34 @@ var CLI_HELP_CATALOG = {
10404
10920
  }
10405
10921
  ]
10406
10922
  },
10923
+ {
10924
+ id: "capsule-verify",
10925
+ topLevel: "capsule",
10926
+ invocation: "lingua capsule verify <file> [--target <file>] [--timeout <ms>] [--env NAME=value ...] [--json] [--quiet]",
10927
+ summary: "Strictly verify captured source or an explicit current file against recorded streams.",
10928
+ description: "Returns pass, fail, or inconclusive. Stream drift exits 5, incomplete evidence exits 6, and failed or timed-out runs keep exits 2-3. Execution uses the local CLI runtime, not a hermetic sandbox.",
10929
+ flags: ["target", "timeout", "env", "json", "quiet", "color", "help"],
10930
+ examples: [
10931
+ {
10932
+ command: "lingua capsule verify ./run.capsule.json --json",
10933
+ description: "Fail a CI gate when recorded stdout/stderr differs."
10934
+ }
10935
+ ]
10936
+ },
10937
+ {
10938
+ id: "capsule-verify-suite",
10939
+ topLevel: "capsule",
10940
+ invocation: "lingua capsule verify-suite <suite> [--root <directory>] [--timeout <ms>] [--env NAME=value ...] [--json] [--quiet]",
10941
+ summary: "Serially verify current files against independent Capsule baselines.",
10942
+ description: "Suite v1 allows 20 cases and 4 MiB, relative in-root targets and a five-minute total execution budget. Opening or importing a suite never executes it.",
10943
+ flags: ["root", "timeout", "env", "json", "quiet", "color", "help"],
10944
+ examples: [
10945
+ {
10946
+ command: "lingua capsule verify-suite ./regression.lingua-suite.json --root . --json",
10947
+ description: "Check current saved files, without updating expectations."
10948
+ }
10949
+ ]
10950
+ },
10407
10951
  {
10408
10952
  id: "run",
10409
10953
  topLevel: "run",
@@ -10430,7 +10974,10 @@ var CLI_HELP_CATALOG = {
10430
10974
  description: "Prints the live utility registry so people and scripts do not need to guess adapter names or supported options.",
10431
10975
  flags: ["json", "quiet", "color", "help"],
10432
10976
  examples: [
10433
- { command: "lingua list utilities --json", description: "Inspect the registry from a script." }
10977
+ {
10978
+ command: "lingua list utilities --json",
10979
+ description: "Inspect the registry from a script."
10980
+ }
10434
10981
  ]
10435
10982
  },
10436
10983
  {
@@ -10453,26 +11000,146 @@ var CLI_HELP_CATALOG = {
10453
11000
  }
10454
11001
  ],
10455
11002
  flags: [
10456
- { id: "input", syntax: "--input <file>", summary: "Read utility input from a file instead of stdin.", commands: ["utility"] },
10457
- { id: "stdin", syntax: "--stdin <file>", summary: "Forward a file as program stdin.", commands: ["run"] },
10458
- { id: "timeout", syntax: "--timeout <ms>", summary: "Stop run or replay after 100\u2013300000 ms.", commands: ["run", "capsule-replay"] },
10459
- { id: "env", syntax: "--env NAME=value", summary: "Repeat to add an explicit child-process environment value.", commands: ["run", "capsule-replay"] },
10460
- { id: "option", syntax: "--option key=value", summary: "Repeat to pass an adapter option.", commands: ["utility"] },
10461
- { id: "json", syntax: "--json", summary: "Emit a stable structured JSON body instead of plain text.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities"] },
10462
- { id: "quiet", syntax: "--quiet", summary: "Suppress Lingua diagnostics while preserving command output.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities"] },
10463
- { id: "yes", syntax: "--yes", summary: "Approve detected shell-completion changes without prompting.", commands: ["completion"] },
10464
- { id: "dry-run", syntax: "--dry-run", summary: "Show detected shells and target files without writing.", commands: ["completion"] },
10465
- { id: "color", syntax: "--color <auto|always|never>", summary: "Control diagnostic color. The default is auto.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities", "completion"] },
10466
- { id: "separator", syntax: "--", summary: "Forward every remaining token to the executed program unchanged.", commands: ["run"] },
10467
- { id: "help", syntax: "--help, -h", summary: "Show help.", commands: ["utility", "capsule-validate", "capsule-replay", "run", "list-utilities", "completion"] },
11003
+ {
11004
+ id: "target",
11005
+ syntax: "--target <file>",
11006
+ summary: "Execute an explicit current relative file instead of captured source.",
11007
+ commands: ["capsule-verify"]
11008
+ },
11009
+ {
11010
+ id: "root",
11011
+ syntax: "--root <directory>",
11012
+ summary: "Resolve suite targets inside this directory; defaults to cwd.",
11013
+ commands: ["capsule-verify-suite"]
11014
+ },
11015
+ {
11016
+ id: "input",
11017
+ syntax: "--input <file>",
11018
+ summary: "Read utility input from a file instead of stdin.",
11019
+ commands: ["utility"]
11020
+ },
11021
+ {
11022
+ id: "stdin",
11023
+ syntax: "--stdin <file>",
11024
+ summary: "Forward a file as program stdin.",
11025
+ commands: ["run"]
11026
+ },
11027
+ {
11028
+ id: "timeout",
11029
+ syntax: "--timeout <ms>",
11030
+ summary: "Stop run or replay after 100\u2013300000 ms.",
11031
+ commands: ["run", "capsule-replay", "capsule-verify", "capsule-verify-suite"]
11032
+ },
11033
+ {
11034
+ id: "env",
11035
+ syntax: "--env NAME=value",
11036
+ summary: "Repeat to add an explicit child-process environment value.",
11037
+ commands: ["run", "capsule-replay", "capsule-verify", "capsule-verify-suite"]
11038
+ },
11039
+ {
11040
+ id: "option",
11041
+ syntax: "--option key=value",
11042
+ summary: "Repeat to pass an adapter option.",
11043
+ commands: ["utility"]
11044
+ },
11045
+ {
11046
+ id: "json",
11047
+ syntax: "--json",
11048
+ summary: "Emit a stable structured JSON body instead of plain text.",
11049
+ commands: [
11050
+ "utility",
11051
+ "capsule-validate",
11052
+ "capsule-replay",
11053
+ "capsule-verify",
11054
+ "capsule-verify-suite",
11055
+ "run",
11056
+ "list-utilities"
11057
+ ]
11058
+ },
11059
+ {
11060
+ id: "quiet",
11061
+ syntax: "--quiet",
11062
+ summary: "Suppress Lingua diagnostics while preserving command output.",
11063
+ commands: [
11064
+ "utility",
11065
+ "capsule-validate",
11066
+ "capsule-replay",
11067
+ "capsule-verify",
11068
+ "capsule-verify-suite",
11069
+ "run",
11070
+ "list-utilities"
11071
+ ]
11072
+ },
11073
+ {
11074
+ id: "yes",
11075
+ syntax: "--yes",
11076
+ summary: "Approve detected shell-completion changes without prompting.",
11077
+ commands: ["completion"]
11078
+ },
11079
+ {
11080
+ id: "dry-run",
11081
+ syntax: "--dry-run",
11082
+ summary: "Show detected shells and target files without writing.",
11083
+ commands: ["completion"]
11084
+ },
11085
+ {
11086
+ id: "color",
11087
+ syntax: "--color <auto|always|never>",
11088
+ summary: "Control diagnostic color. The default is auto.",
11089
+ commands: [
11090
+ "utility",
11091
+ "capsule-validate",
11092
+ "capsule-replay",
11093
+ "capsule-verify",
11094
+ "capsule-verify-suite",
11095
+ "run",
11096
+ "list-utilities",
11097
+ "completion"
11098
+ ]
11099
+ },
11100
+ {
11101
+ id: "separator",
11102
+ syntax: "--",
11103
+ summary: "Forward every remaining token to the executed program unchanged.",
11104
+ commands: ["run"]
11105
+ },
11106
+ {
11107
+ id: "help",
11108
+ syntax: "--help, -h",
11109
+ summary: "Show help.",
11110
+ commands: [
11111
+ "utility",
11112
+ "capsule-validate",
11113
+ "capsule-replay",
11114
+ "capsule-verify",
11115
+ "capsule-verify-suite",
11116
+ "run",
11117
+ "list-utilities",
11118
+ "completion"
11119
+ ]
11120
+ },
10468
11121
  { id: "version", syntax: "--version, -v", summary: "Print the CLI version.", commands: [] }
10469
11122
  ],
10470
11123
  exitCodes: [
10471
11124
  { code: 0, name: "ok", summary: "Command completed successfully." },
10472
11125
  { code: 1, name: "userInputError", summary: "Arguments, input, file, or shape are invalid." },
10473
- { code: 2, name: "runtimeError", summary: "Execution failed, timed out, stopped, or exited non-zero." },
10474
- { code: 3, name: "unsupportedCapability", summary: "Runtime, mode, toolchain, or output is unsupported." },
10475
- { code: 4, name: "internal", summary: "An unexpected exception reached the CLI boundary." }
11126
+ {
11127
+ code: 2,
11128
+ name: "runtimeError",
11129
+ summary: "Execution failed, timed out, stopped, or exited non-zero."
11130
+ },
11131
+ {
11132
+ code: 3,
11133
+ name: "unsupportedCapability",
11134
+ summary: "Runtime, mode, toolchain, or output is unsupported."
11135
+ },
11136
+ { code: 4, name: "internal", summary: "An unexpected exception reached the CLI boundary." },
11137
+ { code: 5, name: "verificationFailed", summary: "Strict verification detected output drift." },
11138
+ {
11139
+ code: 6,
11140
+ name: "verificationInconclusive",
11141
+ summary: "Strict verification could not establish complete evidence."
11142
+ }
10476
11143
  ]
10477
11144
  };
10478
11145
  function pad(value, width) {
@@ -10506,8 +11173,8 @@ ${examples}
10506
11173
  }
10507
11174
 
10508
11175
  // src/cli/io.ts
10509
- var import_promises4 = require("node:fs/promises");
10510
- var import_promises5 = require("node:readline/promises");
11176
+ var import_promises6 = require("node:fs/promises");
11177
+ var import_promises7 = require("node:readline/promises");
10511
11178
  function createDefaultIo() {
10512
11179
  return {
10513
11180
  stdoutSupportsColor: process.stdout.isTTY === true && (typeof process.stdout.hasColors !== "function" || process.stdout.hasColors()),
@@ -10520,7 +11187,7 @@ function createDefaultIo() {
10520
11187
  return null;
10521
11188
  }
10522
11189
  const choices = defaultAnswer ? "Y/n" : "y/N";
10523
- const readline = (0, import_promises5.createInterface)({ input: process.stdin, output: process.stdout });
11190
+ const readline = (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
10524
11191
  try {
10525
11192
  const answer = (await readline.question(`${message} [${choices}] `)).trim().toLowerCase();
10526
11193
  if (answer.length === 0) return defaultAnswer;
@@ -10535,16 +11202,23 @@ function createDefaultIo() {
10535
11202
  writeStderr(text) {
10536
11203
  process.stderr.write(text);
10537
11204
  },
10538
- async readFile(path5) {
10539
- return (0, import_promises4.readFile)(path5, "utf8");
11205
+ async readFile(path6) {
11206
+ return (0, import_promises6.readFile)(path6, "utf8");
10540
11207
  },
10541
- async readStdin() {
11208
+ async readStdin(options) {
10542
11209
  if (process.stdin.isTTY) {
10543
11210
  return null;
10544
11211
  }
10545
11212
  const chunks = [];
10546
- for await (const chunk of process.stdin) {
10547
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
11213
+ const signal = options?.signal;
11214
+ const release = () => process.stdin.destroy();
11215
+ signal?.addEventListener("abort", release, { once: true });
11216
+ try {
11217
+ for await (const chunk of process.stdin) {
11218
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
11219
+ }
11220
+ } finally {
11221
+ signal?.removeEventListener("abort", release);
10548
11222
  }
10549
11223
  return Buffer.concat(chunks).toString("utf8");
10550
11224
  }
@@ -10621,6 +11295,8 @@ function finalize(command, positionals, flags) {
10621
11295
  ...flags.input !== void 0 ? { input: flags.input } : {},
10622
11296
  ...flags.stdin !== void 0 ? { stdin: flags.stdin } : {},
10623
11297
  ...flags.timeoutMs !== void 0 ? { timeoutMs: flags.timeoutMs } : {},
11298
+ ...flags.target !== void 0 ? { target: flags.target } : {},
11299
+ ...flags.root !== void 0 ? { root: flags.root } : {},
10624
11300
  options: flags.options,
10625
11301
  env: flags.env,
10626
11302
  programArgs: flags.programArgs,
@@ -10744,19 +11420,24 @@ function parseUtility(rest, color) {
10744
11420
  function parseCapsule(rest, color) {
10745
11421
  if (rest.length === 0) {
10746
11422
  throw new CliUsageError(
10747
- "lingua capsule requires a subcommand. Available: validate <file>, replay <file>"
11423
+ "lingua capsule requires a subcommand. Available: validate <file>, replay <file>, verify <file>, verify-suite <suite>"
10748
11424
  );
10749
11425
  }
10750
11426
  const sub = rest[0];
10751
11427
  if (sub === "--help" || sub === "-h") {
10752
11428
  return finalize("capsule-validate", [], { ...freshFlags(color), help: true });
10753
11429
  }
11430
+ if (sub === "verify-suite")
11431
+ return parseCapsuleReplay(rest.slice(1), color, "capsule-verify-suite");
11432
+ if (sub === "verify") {
11433
+ return parseCapsuleReplay(rest.slice(1), color, "capsule-verify");
11434
+ }
10754
11435
  if (sub === "replay") {
10755
11436
  return parseCapsuleReplay(rest.slice(1), color);
10756
11437
  }
10757
11438
  if (sub !== "validate") {
10758
11439
  throw new CliUsageError(
10759
- `Unknown capsule subcommand "${sub}". Available: validate <file>, replay <file>`
11440
+ `Unknown capsule subcommand "${sub}". Available: validate <file>, replay <file>, verify <file>, verify-suite <suite>`
10760
11441
  );
10761
11442
  }
10762
11443
  const flags = freshFlags(color);
@@ -10792,12 +11473,22 @@ function parseCapsule(rest, color) {
10792
11473
  }
10793
11474
  return finalize("capsule-validate", positionals, flags);
10794
11475
  }
10795
- function parseCapsuleReplay(rest, color) {
11476
+ function parseCapsuleReplay(rest, color, command = "capsule-replay") {
10796
11477
  const flags = freshFlags(color);
10797
11478
  const positionals = [];
10798
11479
  for (let index = 0; index < rest.length; index += 1) {
10799
11480
  const arg = rest[index];
10800
11481
  if (parseGlobalFlag(arg, flags)) continue;
11482
+ if ((arg === "--target" || arg.startsWith("--target=")) && command === "capsule-verify") {
11483
+ if (flags.target !== void 0) throw new CliUsageError("--target may be supplied once.");
11484
+ flags.target = arg === "--target" ? requireFlagValue(rest, index++, "--target") : nonEmptyInlineValue(arg, "--target");
11485
+ continue;
11486
+ }
11487
+ if ((arg === "--root" || arg.startsWith("--root=")) && command === "capsule-verify-suite") {
11488
+ if (flags.root !== void 0) throw new CliUsageError("--root may be supplied once.");
11489
+ flags.root = arg === "--root" ? requireFlagValue(rest, index++, "--root") : nonEmptyInlineValue(arg, "--root");
11490
+ continue;
11491
+ }
10801
11492
  if (arg === "--timeout") {
10802
11493
  flags.timeoutMs = parseTimeout(requireFlagValue(rest, index, "--timeout"));
10803
11494
  index += 1;
@@ -10818,24 +11509,24 @@ function parseCapsuleReplay(rest, color) {
10818
11509
  }
10819
11510
  if (arg.startsWith("-")) {
10820
11511
  throw new CliUsageError(
10821
- `Unknown flag "${arg}" for "lingua capsule replay". Allowed: --timeout, --env, --json, --quiet, --color, --help`
11512
+ `Unknown flag "${arg}" for "lingua capsule ${command.slice(8)}". Allowed: ${command === "capsule-verify" ? "--target, " : command === "capsule-verify-suite" ? "--root, " : ""}--timeout, --env, --json, --quiet, --color, --help`
10822
11513
  );
10823
11514
  }
10824
11515
  positionals.push(arg);
10825
11516
  }
10826
- assertSingleTarget("lingua capsule replay", positionals, flags.help, "<file>");
10827
- return finalize("capsule-replay", positionals, flags);
11517
+ assertSingleTarget(`lingua capsule ${command.slice(8)}`, positionals, flags.help, "<file>");
11518
+ return finalize(command, positionals, flags);
10828
11519
  }
10829
11520
  function parseList(rest, color) {
10830
11521
  if (rest.length === 0) {
10831
- throw new CliUsageError("lingua list requires a subcommand. implementation ships: utilities");
11522
+ throw new CliUsageError("lingua list requires a subcommand. Available: utilities");
10832
11523
  }
10833
11524
  const sub = rest[0];
10834
11525
  if (sub === "--help" || sub === "-h") {
10835
11526
  return finalize("list-utilities", [], { ...freshFlags(color), help: true });
10836
11527
  }
10837
11528
  if (sub !== "utilities") {
10838
- throw new CliUsageError(`Unknown list subcommand "${sub}". implementation ships: utilities`);
11529
+ throw new CliUsageError(`Unknown list subcommand "${sub}". Available: utilities`);
10839
11530
  }
10840
11531
  const flags = freshFlags(color);
10841
11532
  for (let i2 = 1; i2 < rest.length; i2 += 1) {
@@ -10994,21 +11685,21 @@ function parseEnvironmentKv(raw) {
10994
11685
  }
10995
11686
  return parsed;
10996
11687
  }
10997
- function assertSingleTarget(command, positionals, help, label) {
11688
+ function assertSingleTarget(command, positionals, help, label2) {
10998
11689
  if (!help && positionals.length === 0) {
10999
- throw new CliUsageError(`${command} requires a ${label} positional.`);
11690
+ throw new CliUsageError(`${command} requires a ${label2} positional.`);
11000
11691
  }
11001
11692
  if (positionals.length > 1) {
11002
11693
  throw new CliUsageError(
11003
- `${command} accepts one ${label}; got ${positionals.length}: ${positionals.join(", ")}`
11694
+ `${command} accepts one ${label2}; got ${positionals.length}: ${positionals.join(", ")}`
11004
11695
  );
11005
11696
  }
11006
11697
  }
11007
11698
 
11008
11699
  // src/cli/lingua.ts
11009
11700
  function resolveCliVersion() {
11010
- if ("1.5.1".length > 0) {
11011
- return "1.5.1";
11701
+ if ("1.6.0".length > 0) {
11702
+ return "1.6.0";
11012
11703
  }
11013
11704
  return "0.0.0-dev";
11014
11705
  }
@@ -11135,19 +11826,22 @@ async function dispatch(argv, io) {
11135
11826
  io
11136
11827
  );
11137
11828
  }
11138
- if (parsed.command === "capsule-replay") {
11829
+ if (parsed.command === "capsule-replay" || parsed.command === "capsule-verify" || parsed.command === "capsule-verify-suite") {
11139
11830
  const filePath = parsed.positionals[0];
11140
11831
  if (filePath === void 0) {
11141
11832
  emitCliFailure(io, parsed.flags, {
11142
- label: "lingua capsule replay",
11833
+ label: `lingua capsule ${parsed.command === "capsule-verify" ? "verify" : "replay"}`,
11143
11834
  reason: "missing-file",
11144
11835
  detail: "Expected a <file> positional."
11145
11836
  });
11146
11837
  return CLI_EXIT_CODES.userInputError;
11147
11838
  }
11148
- return runReplayCapsuleCommand(
11839
+ const command = parsed.command === "capsule-verify-suite" ? runVerifyCapsuleSuiteCommand : parsed.command === "capsule-verify" ? runVerifyCapsuleCommand : runReplayCapsuleCommand;
11840
+ return command(
11149
11841
  {
11150
11842
  filePath,
11843
+ ...parsed.flags.target !== void 0 ? { targetPath: parsed.flags.target } : {},
11844
+ ...parsed.flags.root !== void 0 ? { rootDirectory: parsed.flags.root } : {},
11151
11845
  ...parsed.flags.timeoutMs !== void 0 ? { timeoutMs: parsed.flags.timeoutMs } : {},
11152
11846
  env: parsed.flags.env,
11153
11847
  json: parsed.flags.json,