UNPKG

vlt

Version:
1,245 lines (1,230 loc) 36.2 kB
var global = globalThis; import {Buffer} from "node:buffer"; import {setTimeout,clearTimeout,setImmediate,clearImmediate,setInterval,clearInterval} from "node:timers"; import {createRequire as _vlt_createRequire} from "node:module"; var require = _vlt_createRequire(import.meta.filename); import { require_emoji_regex } from "./chunk-3X64PWHW.js"; import { createHostContextsMap } from "./chunk-4ADJWTGC.js"; import { stderr, stdout, styleTextStdout } from "./chunk-KNHO4BUR.js"; import { Query, actual, isRunResult } from "./chunk-QALMFIGC.js"; import { Monorepo } from "./chunk-GTAUGWLW.js"; import { isErrorWithCause } from "./chunk-JBBINXAZ.js"; import { error } from "./chunk-KVH5ECIG.js"; import { __toESM } from "./chunk-AECDW3EJ.js"; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/fix-emoji.js var import_emoji_regex = __toESM(require_emoji_regex(), 1); var EMOJI_RE = (0, import_emoji_regex.default)(); var replaceWide = (c) => replaceNarrow(c) + " "; var replaceNarrow = (c) => `<span style="position:absolute;line-height:1;margin-top:0.3ex">${c}</span> `; var fixEmoji = (s) => { return s.replace(/[\u2500-\u25FF]/g, replaceNarrow).replace(EMOJI_RE, replaceWide); }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/default-colors.js var COLOR = "#eeeeee"; var BACKGROUND = "#222222"; var defaultColor = (s) => { if (s) COLOR = s; return COLOR; }; var defaultBackground = (s) => { if (s) BACKGROUND = s; return BACKGROUND; }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/hex-to-rgb.js var hexToRgb = (c) => { c = c.replace(/^#/, ""); if (c.length === 3) { const r2 = c.charAt(0); const g2 = c.charAt(1); const b2 = c.charAt(2); return hexToRgb(`${r2}${r2}${g2}${g2}${b2}${b2}`); } if (c.length !== 6) { throw new Error("invalid hex string: " + c); } const r = parseInt(c.substring(0, 2), 16); const g = parseInt(c.substring(2, 4), 16); const b = parseInt(c.substring(4, 6), 16); if (r !== r || g !== g || b !== b) { throw new Error("invalid hex string: " + c); } return [r, g, b]; }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/rgb-to-hex.js var rgbToHex = ([r, g, b]) => { if (r !== r || g !== g || b !== b) { throw new Error("invalid RGB: " + [r, g, b].join(",")); } return `#${Math.max(0, Math.min(r, 255)).toString(16).padStart(2, "0") + Math.max(0, Math.min(g, 255)).toString(16).padStart(2, "0") + Math.max(0, Math.min(b, 255)).toString(16).padStart(2, "0")}`; }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/dim-color.js var DIMLEVEL = 0.75; var dimColor = (c) => rgbToHex(hexToRgb(c).map((c2) => Math.floor(c2 * DIMLEVEL))); // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/html-escape.js var htmlEscape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/named.js var nameCodes = { black: 0, red: 1, green: 2, yellow: 3, blue: 4, magenta: 5, cyan: 6, white: 7 }; var namedColors = [ "#000000", "#ff0000", "#00a000", "#e0e000", "#0040e0", "#e000e0", "#00b0b0", "#e0e0e0" ]; var namedBrightColors = [ "#404040", "#ff3030", "#00ff00", "#ffff00", "#0080ff", "#ff33ff", "#00ffff", "#ffffff" ]; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/xterm.js var hex = (n) => n.toString(16).padStart(2, "0"); var colors = [ ...(function* () { for (let red = 0; red < 6; red++) { for (let green = 0; green < 6; green++) { for (let blue = 0; blue < 6; blue++) { const r = red ? red * 40 + 55 : 0; const g = green ? green * 40 + 55 : 0; const b = blue ? blue * 40 + 55 : 0; yield `#${hex(r)}${hex(g)}${hex(b)}`; } } } })() ]; var grays = [ ...(function* () { for (let gray = 0; gray < 24; gray++) { const g = gray * 10 + 8; yield `#${hex(g).repeat(3)}`; } })() ]; var xtermCode = (n) => { if (n < 8) return namedColors[n]; if (n < 16) return namedBrightColors[n - 8]; if (n < Math.pow(6, 3)) return colors[n - 16]; if (n < 256) return grays[n - 232]; }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/style.js var ALL_END = "0"; var BG_END = "49"; var BG_START = "48"; var BOLD_END = "22"; var BOLD_START = "1"; var DIM_START = "2"; var FG_END = "39"; var FG_START = "38"; var INV_END = "27"; var INV_START = "7"; var ITALIC_END = "23"; var ITALIC_START = "3"; var OVER_END = "55"; var OVER_START = "53"; var STRIKE_END = "29"; var STRIKE_START = "9"; var UNDERLINE_END = "24"; var UNDERLINE_START = "4"; var UNDERLINE_START_2 = "21"; var NAMED_RE = /^(3|4|9|10)([0-7])$/; var NAMED_FG = "3"; var NAMED_BG = "4"; var NAMED_FG_BRIGHT = "9"; var NAMED_BG_BRIGHT = "10"; var VALID_CODE = () => new RegExp( "\x1B\\]8;;(.*?)(?:\x1B|\x07)|\x1B\\[([0-9]*(?:;[0-9]*)*)m", // end style codes "g" ); var RESET_STYLE = { background: "", bold: false, color: "", dim: false, inverse: false, italic: false, overline: false, strike: false, underline: false }; var RESET_PROPS = { ...RESET_STYLE, href: "" }; var namedColor = (c, bright = false) => { if (!c) return c; c = c.toLowerCase(); const code = nameCodes[c]; if (typeof code === "number") { return bright ? namedBrightColors[code] : namedColors[code]; } if (c.includes("bright") && !bright) { return namedColor(c.replace(/bright/g, ""), true); } return rgbToHex(hexToRgb(c)); }; var SEEN = /* @__PURE__ */ new Map(); var Style = class _Style { #css; #background; #bold; #color; #dim; #inverse; #italic; #overline; #strike; #underline; #ansi; #href; constructor(styles) { const { background = "", bold = false, color = "", dim = false, inverse = false, italic = false, overline = false, strike = false, underline = false, href = "" } = typeof styles !== "string" ? styles : _Style.ansiProperties(styles); const ansi = _Style.propertiesAnsi({ background, bold, color, dim, inverse, italic, overline, strike, underline, href }); const seen = SEEN.get(ansi); if (seen) return seen; SEEN.set(ansi, this); this.#ansi = ansi; this.#background = namedColor(background); this.#bold = bold; this.#color = namedColor(color); this.#dim = dim; this.#inverse = inverse; this.#italic = italic; this.#overline = overline; this.#strike = strike; this.#underline = underline; try { this.#href = href && String(new URL(href)); } catch { this.#href = ""; } } /** * True if this style is a full reset of all properties. */ get isReset() { return this === RESET; } /** corresponding ANSI code sequence for this style */ get ansi() { return this.#ansi; } /** Convert a set of properties to an ANSI style code */ static propertiesAnsi(styles) { const { background, bold, color, dim, inverse, italic, overline, strike, underline, href = "" } = styles; const codes = [ // always do a reset at the start 0, ...color ? [FG_START, 2, ...hexToRgb(namedColor(color))] : [], ...background ? [BG_START, 2, ...hexToRgb(namedColor(background))] : [], ...bold ? [BOLD_START] : [], ...dim ? [DIM_START] : [], ...inverse ? [INV_START] : [], ...italic ? [ITALIC_START] : [], ...overline ? [OVER_START] : [], ...strike ? [STRIKE_START] : [], ...underline ? [UNDERLINE_START] : [] ]; return `\x1B]8;;${href}\x1B\\\x1B[${codes.join(";")}m`; } /** * If the input string is a sequence of *only* ANSI style and * OSC href codes, returns the array of codes and their parameters. * Otherwise, returns false. */ static validStyleCodes(s) { let c = 0; let m; const results = []; const vc = VALID_CODE(); while (m = vc.exec(s)) { if (c !== m.index) { return null; } c += m[0].length; results.push([m[0], m[1] ?? m[2]]); } return results.length === 0 ? null : results; } /** a Style object that resets all properties */ static get RESET() { return RESET; } /** Convert an ANSI style code to a set of properties */ static ansiProperties(code) { const codes = _Style.validStyleCodes(code); if (!codes) { throw new Error("invalid ansi style code: " + JSON.stringify(code)); } const style = {}; for (const code2 of codes) { if (code2[0].startsWith("\x1B]8;;")) { style.href = code2[1]; continue; } const codes2 = code2[1].split(";"); for (let i = 0; i < codes2.length; i++) { const c = codes2[i]; switch (c) { case "": case ALL_END: Object.assign(style, RESET_STYLE); continue; case BOLD_END: style.bold = false; style.dim = false; continue; case ITALIC_END: style.italic = false; continue; case STRIKE_END: style.strike = false; continue; case OVER_END: style.overline = false; continue; case UNDERLINE_END: style.underline = false; continue; case INV_END: style.inverse = false; continue; case FG_END: style.color = ""; continue; case BG_END: style.background = ""; continue; case BOLD_START: style.bold = true; continue; case INV_START: style.inverse = true; continue; case UNDERLINE_START: case UNDERLINE_START_2: style.underline = true; continue; case DIM_START: style.dim = true; continue; case OVER_START: style.overline = true; continue; case ITALIC_START: style.italic = true; continue; case STRIKE_START: style.strike = true; continue; case BG_START: case FG_START: { const next = codes2[i + 1]; const prop = c == FG_START ? "color" : "background"; switch (next) { case "5": const xt = codes2[i + 2]; const code3 = xt && xtermCode(parseInt(xt, 10)); if (code3) { i += 2; style[prop] = code3; } continue; case "2": const sr = codes2[i + 2]; const sg = codes2[i + 3]; const sb = codes2[i + 4]; if (sr && sg && sb) { const r = parseInt(sr, 10); const g = parseInt(sg, 10); const b = parseInt(sb, 10); const hex2 = rgbToHex([r, g, b]); if (r <= 255 && r >= 0 && g <= 255 && g >= 0 && b <= 255 && b >= 0) { i += 4; style[prop] = hex2; } } } continue; } // named color/bg default: { const m = c.match(NAMED_RE); if (!m) continue; const color = parseInt(m[2], 10); switch (m[1]) { case NAMED_FG: style.color = namedColors[color]; continue; case NAMED_BG: style.background = namedColors[color]; continue; case NAMED_FG_BRIGHT: style.color = namedBrightColors[color]; continue; case NAMED_BG_BRIGHT: style.background = namedBrightColors[color]; continue; } } } } } return style; } /** * Return a new Style with this one plus the updated properties. * * If a string is provided, must be a valid set of style and OSC hyperlink * ANSI code, though unrecognized parameters within that code will be ignored * rather than throwing an error. */ update(properties) { const { background = this.#background, bold = this.#bold, color = this.#color, dim = this.#dim, inverse = this.#inverse, italic = this.#italic, overline = this.#overline, strike = this.#strike, underline = this.#underline, href = this.#href } = typeof properties === "string" ? _Style.ansiProperties(properties) : properties; return background === this.#background && bold === this.#bold && color === this.#color && dim === this.#dim && inverse === this.#inverse && italic === this.#italic && overline === this.#overline && strike === this.#strike && underline === this.#underline && href === this.#href ? this : new _Style({ background, bold, color, dim, inverse, italic, overline, strike, underline, href }); } [Symbol.for("nodejs.util.inspect.custom")](_, { colors: colors2 } = { colors: false }) { const { ansi } = this; return `Style { ${colors2 ? ansi : ""}${ansi.replace(/\x1b/g, "^[")}${colors2 ? "\x1B]8;;\x1B\\\x1B[m" : ""} }`; } /** * Wrap the input string in the appropriate HTML for this style */ wrap(s) { const css = this.toString(); const href = this.#href; if (!css && !href) return htmlEscape(s); const tag = href ? `a` : "span"; return `<${tag}${href ? ` href="${href}"` : ""}${css ? ` style="${css}"` : ""}>${htmlEscape(s)}</${tag}>`; } /** * Return just the CSS for the styles. Href is not relevant. */ toString() { if (this.#css) return this.#css; let color = this.#inverse ? this.#background : this.#color; let background = this.#inverse ? this.#color : this.#background; if (this.#inverse) { color ||= defaultBackground(); background ||= defaultColor(); } if (this.#dim && !(color && color === background)) { color = dimColor(color || defaultColor()); } const textDecoration = [ ...this.#underline ? ["underline"] : [], ...this.#overline ? ["overline"] : [], ...this.#strike ? ["line-through"] : [] ].join(" "); return this.#css = [ ...textDecoration ? [`text-decoration:${textDecoration}`] : [], ...this.#bold ? ["font-weight:bold"] : this.#dim ? ["font-weight:100"] : [], ...this.#italic ? ["font-style:italic"] : [], ...color ? [`color:${color}`] : [], ...background ? [`background:${background}`] : [] ].join(";"); } }; var RESET = new Style(RESET_PROPS); // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/block.js var Block = class { #style; #text; constructor(text, style) { this.#text = text; this.#style = style; } [Symbol.for("nodejs.util.inspect.custom")](_, opts, inspect) { return `Block {${this.#style ? " " + inspect(this.#style, opts) : ""} ${inspect(this.#text, opts)} }`; } /** return the block as a styled `<span>` tag */ toString() { return this.#toString(false); } /** a representation of the block as an ANSI styled string */ get ansi() { return this.#toString(true); } #toString(ansi) { return !this.#text ? "" : ansi ? (this.#style ?? Style.RESET).ansi + this.#text : fixEmoji((this.#style ?? Style.RESET).wrap(this.#text)); } /** append text to the block */ write(c) { this.#text += c; return this; } /** the raw text that will be written */ get text() { return this.#text; } /** the Style used by this block */ get style() { return this.#style; } }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/terminal.js var CODES_RE = /^\u001b\[([0-9]*[A-GJKSTg]|([0-9;]*)m|([0-9]*;?[0-9]*)?[Hf]|\?[0-9]+[hl])/; var OSC_RE = /^\u001b\](.*?)(?:\u0007|\u001b\\)/; var OSC_TITLE = "0;"; var OSC_HREF = "8;;"; var Terminal = class { // note: 0-indexed, but all the ansi codes are 1-indexed #cursor = [0, 0]; // character data #text = []; // the style used to write it #style = []; // the current style we use to paint characters to our "screen" #brush = new Style({}); #title = ""; #blocks; constructor(input) { if (input) this.write(input); } /** * Set the style that the terminal will use for text writes. * * If a string, must be a valid `\x1b[...m` ANSI style code. * * The styles provided will be appended onto the current style in use, just * as they would be by a real terminal if the relevant ANSI code is * encountered. */ setStyle(style) { this.#brush = this.#brush.update(style); return this; } /** Move the cursor up `n` lines, stopping at the top. */ up(n) { this.#cursor[0] = Math.max(this.#cursor[0] - n, 0); return this; } /** Move the cursor down `n` lines, without limit. */ down(n) { this.#cursor[0] += n; return this; } /** * Prepend `n` empty lines at the start of the buffer, effectively moving the * cursor up as a result. */ scrollUp(n) { for (let i = 0; i < n; i++) { this.#text.unshift([]); this.#style.unshift([]); } return this; } /** * Remove `n` lines from the start of the buffer, effectively moving the * cursor down as a result. */ scrollDown(n) { for (let i = 0; i < n; i++) { this.#text.shift(); this.#style.shift(); } return this; } /** Move the cursor forward `n` columns, without limit. */ forward(n) { this.#cursor[1] += n; return this; } /** Move the cursor back `n` columns, stopping at the first column. */ back(n) { this.#cursor[1] = Math.max(0, this.#cursor[1] - n); return this; } /** Move to the start of the `n`-th next line. */ nextLine(n) { this.#cursor[0] += n; this.#cursor[1] = 0; return this; } /** * Move to the start of the `n`-th previous line, stopping at the top of the * screen. */ prevLine(n) { this.#cursor[0] = Math.max(0, this.#cursor[0] - n); this.#cursor[1] = 0; return this; } /** * Move to the `n`-th column (1-indexed), limited by the left-most column. */ horizontalPosition(n) { this.#cursor[1] = Math.max(0, n - 1); return this; } /** * Move to the 1-indexed row and column specified, limited by the top and * left sides of the screen. */ position(row, col) { this.#cursor[0] = Math.max(row - 1, 0); this.#cursor[1] = Math.max(col - 1, 0); return this; } /** * Delete all printed data from the screen. * * Note that this is used for both `\x1b[2J` _and_ `\x1b[3J`, because there * is no scrollback buffer in this virtual terminal. */ eraseScreen() { this.#text.length = 0; this.#style.length = 0; return this; } /** Delete all printed data from the cursor to the end of the screen. */ eraseScreenToEnd() { this.#text.splice(this.#cursor[0] + 1); this.#style.splice(this.#cursor[0] + 1); this.eraseLineToEnd(); return this; } /** Delete all printed data from the top of the screen to the cursor. */ eraseScreenFromStart() { let i; for (i = 0; i < this.#cursor[0]; i++) { const line = this.#text[i]; const sline = this.#style[i]; if (!line || !sline) continue; line.length = 0; sline.length = 0; } this.eraseLineFromStart(); return this; } /** Delete the contents of the current line. */ eraseLine() { const line = this.#text[this.#cursor[0]]; const sline = this.#style[this.#cursor[0]]; if (!line || !sline) return this; line.length = 0; sline.length = 0; return this; } /** * Delete printed data from the cursor to the end of the current line. */ eraseLineToEnd() { const line = this.#text[this.#cursor[0]]; const sline = this.#style[this.#cursor[0]]; if (!line || !sline) return this; line.splice(this.#cursor[1]); sline.splice(this.#cursor[1]); return this; } /** * Delete printed data from the start of the current line to the cursor. */ eraseLineFromStart() { if (this.#cursor[1] === 0) return this.eraseLine(); const line = this.#text[this.#cursor[0]]; const sline = this.#style[this.#cursor[0]]; if (!line || !sline) return this; for (let i = 0; i < this.#cursor[1]; i++) { line[i] = " "; sline[i] = void 0; } return this; } /** * Parse the ANSI encoded string provided, updating the internal character * and style buffers appropriately. */ write(input) { this.#blocks = void 0; for (let c = 0; c < input.length; ) { while (input.charAt(c) === "\x1B") { switch (input.charAt(c + 1)) { case "B": this.horizontalPosition(1); c += 2; continue; case "H": c += 2; continue; case "D": this.scrollDown(1); c += 2; continue; case "M": this.scrollUp(1); c += 2; continue; } const code = input.substring(c).match(CODES_RE); if (code) { c += code[0].length; if (code[1].endsWith("m")) { this.setStyle(code[0]); continue; } else { const x = code[1].charAt(code[1].length - 1); if (x === "H" || x === "f") { const [n2, m] = code[1].replace(/[Hf]$/, "").split(";"); const row = Math.max(1, parseInt(n2 || "1", 10)); const col = Math.max(1, parseInt(m || "1", 10)); this.position(row, col); continue; } const p = code[1].match(/^([0-9]+)/)?.[1]; const n = parseInt(p || "1", 10); const z = parseInt(p || "0", 10); switch (x) { case "A": this.up(n); continue; case "T": this.scrollUp(n); continue; case "B": this.down(n); continue; case "S": this.scrollDown(n); continue; case "C": this.forward(n); continue; case "D": this.back(n); continue; case "E": this.nextLine(n); continue; case "F": this.prevLine(n); continue; case "G": this.horizontalPosition(n); continue; case "J": { switch (z) { case 0: this.eraseScreenToEnd(); continue; case 1: this.eraseScreenFromStart(); continue; case 2: case 3: this.eraseScreen(); continue; } continue; } case "K": { switch (z) { case 0: this.eraseLineToEnd(); continue; case 1: this.eraseLineFromStart(); continue; case 2: this.eraseLine(); continue; } continue; } } } continue; } const osc = input.substring(c).match(OSC_RE); if (osc?.index === 0) { c += osc[0].length; const cmd = osc[1]; if (cmd.startsWith(OSC_TITLE)) { this.setTitle(cmd.substring(OSC_TITLE.length)); continue; } if (cmd.startsWith(OSC_HREF)) { this.setStyle({ href: cmd.substring(OSC_HREF.length) }); continue; } continue; } break; } if (c >= input.length) break; const ch = input.charAt(c++); if (ch === "\r") { this.horizontalPosition(1); continue; } if (ch === "\n") { this.nextLine(1); continue; } while (this.#text.length < this.#cursor[0]) { this.#text.push([]); this.#style.push([]); } const sline = this.#style[this.#cursor[0]] || []; const line = this.#text[this.#cursor[0]] || []; while (line.length < this.#cursor[1]) { line.push(" "); } while (sline.length < this.#cursor[1]) { sline.push(void 0); } line[this.#cursor[1]] = ch; sline[this.#cursor[1]] = this.#brush.isReset ? void 0 : this.#brush; this.#style[this.#cursor[0]] = sline; this.#text[this.#cursor[0]] = line; this.forward(1); } return this; } /** * Called when an OSC code of `\x1b]0;...\x1b\` is encountered. * * Sets the `title` attribute on the root `<pre>` in html output, * and creates a corresponding OSC title sequence in the ansi output. */ setTitle(s) { this.#title = s; return this; } /** the raw unstyled text of each line */ get text() { return this.#text.map((l) => l.join("")); } [Symbol.for("nodejs.util.inspect.custom")](_, opts, inspect) { const ins = inspect({ cursor: this.#cursor, brush: this.#brush, text: this.#text.map((l) => l.join("")), blocks: this.blocks }, opts); return `Terminal ${ins}`; } /** * Output the results of the style and character buffers as ANSI * styled text. This effectively normalizes all color codes to explicit * RGB values and resolves all cursor motions and other control codes, * and styling runs of identical styles with a single code. */ get ansi() { return this.#toString(true); } /** * Output the results of the style and character buffers as a `<pre>` * tag with `<span>` elements setting effective styles. */ toString() { return this.#toString(false); } /** * An array of `Block` objects each representing a string of text with a * given style. */ get blocks() { if (this.#blocks) return this.#blocks; let cur = new Block(""); const blocks = [cur]; for (let i = 0; i < this.#text.length; i++) { const line = this.#text[i] || []; const sline = this.#style[i] || []; for (let j = 0; j < line.length; j++) { const st = sline[j]; const ch = line[j] || ""; if (st === cur.style) cur.write(ch); else blocks.push(cur = new Block(ch, st)); } if (this.#text[i + 1]) cur.write("\n"); } return this.#blocks = blocks.filter((b) => !!b.text); } #toString(ansi) { const contents = this.blocks.map((b) => ansi ? b.ansi : b.toString()).join(""); if (ansi) { const title = this.#title ? `\x1B]0;${this.#title}\x1B\\` : ""; return title + contents + "\x1B[m"; } const css = Object.entries({ color: defaultColor(), background: defaultBackground(), position: "relative" }).map((kv) => kv.join(":")).join(";"); const preStyle = `style="${css}"`; const preTitle = this.#title ? ` title="${this.#title}"` : ""; return `<pre ${preStyle}${preTitle}>${contents}</pre>`; } }; // ../../node_modules/.pnpm/ansi-to-pre@1.0.6/node_modules/ansi-to-pre/dist/esm/index.js var ansiToAnsi = (input) => new Terminal(input).ansi; // ../../src/cli-sdk/src/exec-command.ts import assert from "node:assert"; import { resolve } from "node:path"; var isScriptSet = (o) => { if (!o || typeof o !== "object") return false; for (const v of Object.values(o)) { if (typeof v !== "string") return false; } return true; }; var isMultiScriptSet = (o) => { for (const v of Object.values(o)) { if (!isScriptSet(v)) return false; } return true; }; var isSingleSuccess = (o) => o.signal === null && o.status === 0; var setExitCode = (result) => { process.exitCode ||= result.status ?? 1; }; var views = { // run results for single or multiple will be printed along the way. human: (result) => { if (isScriptSet(result)) stdout("Scripts available:", result); else if (isMultiScriptSet(result)) { stdout("Scripts available:"); for (const [path, scripts] of Object.entries(result)) { stdout(path, scripts); } } }, json: (result) => isRunResult(result) && isSingleSuccess(result) ? void 0 : result }; var ExecCommand = class { bg; fg; arg0; args; env; #monorepo; #nodes; #defaultIgnoreMissing = false; conf; projectRoot; view; validViewValues = /* @__PURE__ */ new Map([ ["human", "human"], ["json", "json"], ["inspect", "inspect"], ["silent", "silent"] ]); constructor(conf, bg, fg) { this.conf = conf; this.bg = bg; this.fg = fg; this.view = this.validViewValues.get(conf.values.view) ?? "human"; const { projectRoot, positionals: [arg0, ...args] } = conf; this.arg0 = arg0; this.args = args; this.projectRoot = projectRoot; } #targetCount() { if (this.#nodes) return this.#nodes.length; return this.#monorepo?.size ?? 1; } hasArg0() { return !!this.arg0; } async run() { const { conf } = this; const queryString = conf.get("scope"); const paths = conf.get("workspace"); const groups = conf.get("workspace-group"); const recursive = conf.get("recursive"); if (queryString) { this.#defaultIgnoreMissing = true; const mainManifest = conf.options.packageJson.maybeRead( this.projectRoot ); let graph; if (mainManifest) { graph = actual.load({ ...conf.options, mainManifest, monorepo: Monorepo.load(this.projectRoot), loadManifests: false }); } const hostContexts = await createHostContextsMap(conf); const query = new Query({ /* c8 ignore start */ nodes: graph ? new Set(graph.nodes.values()) : /* @__PURE__ */ new Set(), edges: graph?.edges ?? /* @__PURE__ */ new Set(), importers: graph?.importers ?? /* @__PURE__ */ new Set(), /* c8 ignore stop */ securityArchive: void 0, hostContexts }); const { nodes } = await query.search(queryString, { signal: new AbortController().signal }); this.#nodes = []; for (const node of nodes) { const { location } = node.toJSON(); assert( location, error(`node ${node.id} has no location`, { found: node }) ); this.#nodes.push(location); } } else if (paths?.length || groups?.length || recursive) { this.#defaultIgnoreMissing = true; this.#monorepo = Monorepo.load(this.projectRoot, { load: { paths, groups } }); } if (this.#targetCount() === 1) { const arg = this.fgArg(); if (!arg) return this.noArgsSingle(); const result = await this.fg(arg); if (isRunResult(result)) { setExitCode(result); } return result; } if (this.#targetCount() === 0) { if (queryString) { throw error("no matching nodes found for query", { found: queryString }); } else { throw error("no matching workspaces found", { /* c8 ignore next - already guarded */ validOptions: [...this.#monorepo?.load().paths() ?? []] }); } } if (!this.hasArg0()) { return this.noArgsMulti(); } let failed = false; const runInDir = async (cwd, label) => { const result = await this.bg(this.bgArg(cwd)).catch( (er) => { if (isErrorWithCause(er) && isRunResult(er.cause)) { this.printResult(label, er.cause); } failed = true; throw er; } ); if (!result.command) return null; if (!failed) this.printResult(label, result); return result; }; const resultMap = /* @__PURE__ */ new Map(); if (this.#nodes) { for (const { label, cwd } of this.getTargets()) { const result = await runInDir(cwd, label); if (result) resultMap.set(label, result); } } else if (this.#monorepo) { const wsResultMap = await this.#monorepo.run( (ws) => runInDir(ws.fullpath, ws.path) ); for (const [ws, result] of wsResultMap) { if (result) resultMap.set(ws.path, result); } } const results = {}; for (const [path, result] of resultMap) { if (result.status === 0 && result.signal === null) { result.stdout = ""; result.stderr = ""; } results[path] = result; } return results; } printResult(path, result) { if (this.view !== "human") return; if (result.status === 0 && result.signal === null) { stdout(path, "ok"); } else { stdout( styleTextStdout( ["bgWhiteBright", "black", "bold"], path + " failure" ), { status: result.status, signal: result.signal } ); if (result.stderr) stderr(ansiToAnsi(result.stderr)); if (result.stdout) stdout(ansiToAnsi(result.stdout)); setExitCode(result); } } /* c8 ignore start - env specific */ interactiveShell() { return process.env.SHELL ?? this.conf.get("script-shell") ?? (process.platform === "win32" ? "cmd.exe" : "/bin/sh"); } /* c8 ignore stop */ // overridden by 'vlt run' which returns undefined defaultArg0() { return this.interactiveShell(); } getCwd() { if (this.#nodes) { const [first] = this.#nodes; assert(first, error("no nodes found")); return resolve(this.projectRoot, first); } return this.#monorepo?.values().next().value?.fullpath ?? this.projectRoot; } fgArg() { const cwd = this.getCwd(); const arg0 = this.arg0 ?? this.defaultArg0(); if (typeof arg0 !== "string") return; return { cwd, arg0, args: this.args, env: this.env, projectRoot: this.projectRoot, packageJson: this.conf.options.packageJson, "script-shell": this.arg0 ? this.conf.get("script-shell") : false }; } bgArg(cwd) { return { cwd, acceptFail: !this.conf.get("bail"), ignoreMissing: this.conf.get("if-present") ?? this.#defaultIgnoreMissing, arg0: this.arg0, args: this.args, env: this.env, projectRoot: this.projectRoot, packageJson: this.conf.options.packageJson, "script-shell": this.conf.get("script-shell") }; } /* c8 ignore start - not used, only here to override */ noArgsSingle() { throw error("Failed to determine interactive shell to spawn"); } /* c8 ignore stop - not used, only here to override */ noArgsMulti() { throw error( "Cannot spawn interactive shells in multiple workspaces" ); } getTargets() { const targets = []; if (this.#nodes) { for (const location of this.#nodes) { const manifest = this.conf.options.packageJson.read(location); const label = ( /* c8 ignore next */ location.startsWith("./") ? location.slice(2) : location ); const cwd = resolve(this.projectRoot, location); targets.push({ label, cwd, manifest }); } } else if (this.#monorepo) { this.#monorepo.runSync((ws) => { targets.push({ label: ws.path, cwd: ws.fullpath, manifest: ws.manifest }); }); } return targets; } }; export { views, ExecCommand }; //# sourceMappingURL=chunk-ZCZ3GGEV.js.map