storybook
Version:
Storybook: Develop, document, and test UI components in isolation
7,161 lines • 314 kB
JavaScript
import CJS_COMPAT_NODE_URL_qjinduibsyq from 'node:url';
import CJS_COMPAT_NODE_PATH_qjinduibsyq from 'node:path';
import CJS_COMPAT_NODE_MODULE_qjinduibsyq from "node:module";
var __filename = CJS_COMPAT_NODE_URL_qjinduibsyq.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_qjinduibsyq.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_qjinduibsyq.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
any,
up,
up2
} from "./chunk-7BA6K3X5.js";
import {
toPath,
traversePathUp
} from "./chunk-MC4KT4LA.js";
import {
Tag
} from "./chunk-PG6QDVJT.js";
import {
require_dist
} from "./chunk-FE5AV6EP.js";
import {
__commonJS,
__require,
__toESM
} from "./chunk-4US4PNS3.js";
// ../../node_modules/tinyglobby/node_modules/picomatch/lib/constants.js
var require_constants = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/lib/constants.js"(exports, module) {
"use strict";
var WIN_NO_SLASH = "[^\\\\/]", ONE_CHAR = "(?=.)", QMARK = "[^/]", END_ANCHOR = "(?:\\/|$)", START_ANCHOR = "(?:^|\\/)", DOTS_SLASH = `\\.{1,2}${END_ANCHOR}`, NO_DOT = "(?!\\.)", NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`, NO_DOT_SLASH = `(?!\\.{0,1}${END_ANCHOR})`, NO_DOTS_SLASH = `(?!${DOTS_SLASH})`, QMARK_NO_DOT = "[^.\\/]", STAR = `${QMARK}*?`, SEP = "/", POSIX_CHARS = {
DOT_LITERAL: "\\.",
PLUS_LITERAL: "\\+",
QMARK_LITERAL: "\\?",
SLASH_LITERAL: "\\/",
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR,
SEP
}, WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: "[\\\\/]",
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: "\\.{1,2}(?:[\\\\/]|$)",
NO_DOT: "(?!\\.)",
NO_DOTS: "(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",
NO_DOT_SLASH: "(?!\\.{0,1}(?:[\\\\/]|$))",
NO_DOTS_SLASH: "(?!\\.{1,2}(?:[\\\\/]|$))",
QMARK_NO_DOT: "[^.\\\\/]",
START_ANCHOR: "(?:^|[\\\\/])",
END_ANCHOR: "(?:[\\\\/]|$)",
SEP: "\\"
}, POSIX_REGEX_SOURCE = {
__proto__: null,
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
DEFAULT_MAX_EXTGLOB_RECURSION: 0,
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
__proto__: null,
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
// Digits
CHAR_0: 48,
/* 0 */
CHAR_9: 57,
/* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65,
/* A */
CHAR_LOWERCASE_A: 97,
/* a */
CHAR_UPPERCASE_Z: 90,
/* Z */
CHAR_LOWERCASE_Z: 122,
/* z */
CHAR_LEFT_PARENTHESES: 40,
/* ( */
CHAR_RIGHT_PARENTHESES: 41,
/* ) */
CHAR_ASTERISK: 42,
/* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38,
/* & */
CHAR_AT: 64,
/* @ */
CHAR_BACKWARD_SLASH: 92,
/* \ */
CHAR_CARRIAGE_RETURN: 13,
/* \r */
CHAR_CIRCUMFLEX_ACCENT: 94,
/* ^ */
CHAR_COLON: 58,
/* : */
CHAR_COMMA: 44,
/* , */
CHAR_DOT: 46,
/* . */
CHAR_DOUBLE_QUOTE: 34,
/* " */
CHAR_EQUAL: 61,
/* = */
CHAR_EXCLAMATION_MARK: 33,
/* ! */
CHAR_FORM_FEED: 12,
/* \f */
CHAR_FORWARD_SLASH: 47,
/* / */
CHAR_GRAVE_ACCENT: 96,
/* ` */
CHAR_HASH: 35,
/* # */
CHAR_HYPHEN_MINUS: 45,
/* - */
CHAR_LEFT_ANGLE_BRACKET: 60,
/* < */
CHAR_LEFT_CURLY_BRACE: 123,
/* { */
CHAR_LEFT_SQUARE_BRACKET: 91,
/* [ */
CHAR_LINE_FEED: 10,
/* \n */
CHAR_NO_BREAK_SPACE: 160,
/* \u00A0 */
CHAR_PERCENT: 37,
/* % */
CHAR_PLUS: 43,
/* + */
CHAR_QUESTION_MARK: 63,
/* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62,
/* > */
CHAR_RIGHT_CURLY_BRACE: 125,
/* } */
CHAR_RIGHT_SQUARE_BRACKET: 93,
/* ] */
CHAR_SEMICOLON: 59,
/* ; */
CHAR_SINGLE_QUOTE: 39,
/* ' */
CHAR_SPACE: 32,
/* */
CHAR_TAB: 9,
/* \t */
CHAR_UNDERSCORE: 95,
/* _ */
CHAR_VERTICAL_LINE: 124,
/* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
/* \uFEFF */
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
"!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
"?": { type: "qmark", open: "(?:", close: ")?" },
"+": { type: "plus", open: "(?:", close: ")+" },
"*": { type: "star", open: "(?:", close: ")*" },
"@": { type: "at", open: "(?:", close: ")" }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win32) {
return win32 === !0 ? WINDOWS_CHARS : POSIX_CHARS;
}
};
}
});
// ../../node_modules/tinyglobby/node_modules/picomatch/lib/utils.js
var require_utils = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/lib/utils.js"(exports) {
"use strict";
var {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require_constants();
exports.isObject = (val) => val !== null && typeof val == "object" && !Array.isArray(val);
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports.isWindows = () => {
if (typeof navigator < "u" && navigator.platform) {
let platform2 = navigator.platform.toLowerCase();
return platform2 === "win32" || platform2 === "windows";
}
return typeof process < "u" && process.platform ? process.platform === "win32" : !1;
};
exports.removeBackslashes = (str) => str.replace(REGEX_REMOVE_BACKSLASH, (match) => match === "\\" ? "" : match);
exports.escapeLast = (input, char, lastIdx) => {
let idx = input.lastIndexOf(char, lastIdx);
return idx === -1 ? input : input[idx - 1] === "\\" ? exports.escapeLast(input, char, idx - 1) : `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
return output.startsWith("./") && (output = output.slice(2), state.prefix = "./"), output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
let prepend = options.contains ? "" : "^", append = options.contains ? "" : "$", output = `${prepend}(?:${input})${append}`;
return state.negated === !0 && (output = `(?:^(?!${output}).*$)`), output;
};
exports.basename = (path5, { windows } = {}) => {
let segs = path5.split(windows ? /[\\/]/ : "/"), last = segs[segs.length - 1];
return last === "" ? segs[segs.length - 2] : last;
};
}
});
// ../../node_modules/tinyglobby/node_modules/picomatch/lib/scan.js
var require_scan = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/lib/scan.js"(exports, module) {
"use strict";
var utils = require_utils(), {
CHAR_ASTERISK,
/* * */
CHAR_AT,
/* @ */
CHAR_BACKWARD_SLASH,
/* \ */
CHAR_COMMA,
/* , */
CHAR_DOT,
/* . */
CHAR_EXCLAMATION_MARK,
/* ! */
CHAR_FORWARD_SLASH,
/* / */
CHAR_LEFT_CURLY_BRACE,
/* { */
CHAR_LEFT_PARENTHESES,
/* ( */
CHAR_LEFT_SQUARE_BRACKET,
/* [ */
CHAR_PLUS,
/* + */
CHAR_QUESTION_MARK,
/* ? */
CHAR_RIGHT_CURLY_BRACE,
/* } */
CHAR_RIGHT_PARENTHESES,
/* ) */
CHAR_RIGHT_SQUARE_BRACKET
/* ] */
} = require_constants(), isPathSeparator = (code) => code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH, depth = (token) => {
token.isPrefix !== !0 && (token.depth = token.isGlobstar ? 1 / 0 : 1);
}, scan = (input, options) => {
let opts = options || {}, length = input.length - 1, scanToEnd = opts.parts === !0 || opts.scanToEnd === !0, slashes = [], tokens = [], parts = [], str = input, index = -1, start = 0, lastIndex = 0, isBrace = !1, isBracket = !1, isGlob = !1, isExtglob = !1, isGlobstar = !1, braceEscaped = !1, backslashes = !1, negated = !1, negatedExtglob = !1, finished7 = !1, braces = 0, prev, code, token = { value: "", depth: 0, isGlob: !1 }, eos = () => index >= length, peek = () => str.charCodeAt(index + 1), advance = () => (prev = code, str.charCodeAt(++index));
for (; index < length; ) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = !0, code = advance(), code === CHAR_LEFT_CURLY_BRACE && (braceEscaped = !0);
continue;
}
if (braceEscaped === !0 || code === CHAR_LEFT_CURLY_BRACE) {
for (braces++; eos() !== !0 && (code = advance()); ) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = !0, advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== !0 && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
if (isBrace = token.isBrace = !0, isGlob = token.isGlob = !0, finished7 = !0, scanToEnd === !0)
continue;
break;
}
if (braceEscaped !== !0 && code === CHAR_COMMA) {
if (isBrace = token.isBrace = !0, isGlob = token.isGlob = !0, finished7 = !0, scanToEnd === !0)
continue;
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE && (braces--, braces === 0)) {
braceEscaped = !1, isBrace = token.isBrace = !0, finished7 = !0;
break;
}
}
if (scanToEnd === !0)
continue;
break;
}
if (code === CHAR_FORWARD_SLASH) {
if (slashes.push(index), tokens.push(token), token = { value: "", depth: 0, isGlob: !1 }, finished7 === !0) continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== !0 && (code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === !0 && peek() === CHAR_LEFT_PARENTHESES) {
if (isGlob = token.isGlob = !0, isExtglob = token.isExtglob = !0, finished7 = !0, code === CHAR_EXCLAMATION_MARK && index === start && (negatedExtglob = !0), scanToEnd === !0) {
for (; eos() !== !0 && (code = advance()); ) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = !0, code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = !0, finished7 = !0;
break;
}
}
continue;
}
break;
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK && (isGlobstar = token.isGlobstar = !0), isGlob = token.isGlob = !0, finished7 = !0, scanToEnd === !0)
continue;
break;
}
if (code === CHAR_QUESTION_MARK) {
if (isGlob = token.isGlob = !0, finished7 = !0, scanToEnd === !0)
continue;
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
for (; eos() !== !0 && (next = advance()); ) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = !0, advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = !0, isGlob = token.isGlob = !0, finished7 = !0;
break;
}
}
if (scanToEnd === !0)
continue;
break;
}
if (opts.nonegate !== !0 && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = !0, start++;
continue;
}
if (opts.noparen !== !0 && code === CHAR_LEFT_PARENTHESES) {
if (isGlob = token.isGlob = !0, scanToEnd === !0) {
for (; eos() !== !0 && (code = advance()); ) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = !0, code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished7 = !0;
break;
}
}
continue;
}
break;
}
if (isGlob === !0) {
if (finished7 = !0, scanToEnd === !0)
continue;
break;
}
}
opts.noext === !0 && (isExtglob = !1, isGlob = !1);
let base = str, prefix = "", glob = "";
start > 0 && (prefix = str.slice(0, start), str = str.slice(start), lastIndex -= start), base && isGlob === !0 && lastIndex > 0 ? (base = str.slice(0, lastIndex), glob = str.slice(lastIndex)) : isGlob === !0 ? (base = "", glob = str) : base = str, base && base !== "" && base !== "/" && base !== str && isPathSeparator(base.charCodeAt(base.length - 1)) && (base = base.slice(0, -1)), opts.unescape === !0 && (glob && (glob = utils.removeBackslashes(glob)), base && backslashes === !0 && (base = utils.removeBackslashes(base)));
let state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === !0 && (state.maxDepth = 0, isPathSeparator(code) || tokens.push(token), state.tokens = tokens), opts.parts === !0 || opts.tokens === !0) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
let n2 = prevIndex ? prevIndex + 1 : start, i2 = slashes[idx], value = input.slice(n2, i2);
opts.tokens && (idx === 0 && start !== 0 ? (tokens[idx].isPrefix = !0, tokens[idx].value = prefix) : tokens[idx].value = value, depth(tokens[idx]), state.maxDepth += tokens[idx].depth), (idx !== 0 || value !== "") && parts.push(value), prevIndex = i2;
}
if (prevIndex && prevIndex + 1 < input.length) {
let value = input.slice(prevIndex + 1);
parts.push(value), opts.tokens && (tokens[tokens.length - 1].value = value, depth(tokens[tokens.length - 1]), state.maxDepth += tokens[tokens.length - 1].depth);
}
state.slashes = slashes, state.parts = parts;
}
return state;
};
module.exports = scan;
}
});
// ../../node_modules/tinyglobby/node_modules/picomatch/lib/parse.js
var require_parse = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/lib/parse.js"(exports, module) {
"use strict";
var constants4 = require_constants(), utils = require_utils(), {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants4, expandRange = (args, options) => {
if (typeof options.expandRange == "function")
return options.expandRange(...args, options);
args.sort();
let value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch {
return args.map((v) => utils.escapeRegex(v)).join("..");
}
return value;
}, syntaxError = (type, char) => `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`, splitTopLevel = (input) => {
let parts = [], bracket = 0, paren = 0, quote = 0, value = "", escaped = !1;
for (let ch of input) {
if (escaped === !0) {
value += ch, escaped = !1;
continue;
}
if (ch === "\\") {
value += ch, escaped = !0;
continue;
}
if (ch === '"') {
quote = quote === 1 ? 0 : 1, value += ch;
continue;
}
if (quote === 0) {
if (ch === "[")
bracket++;
else if (ch === "]" && bracket > 0)
bracket--;
else if (bracket === 0) {
if (ch === "(")
paren++;
else if (ch === ")" && paren > 0)
paren--;
else if (ch === "|" && paren === 0) {
parts.push(value), value = "";
continue;
}
}
}
value += ch;
}
return parts.push(value), parts;
}, isPlainBranch = (branch) => {
let escaped = !1;
for (let ch of branch) {
if (escaped === !0) {
escaped = !1;
continue;
}
if (ch === "\\") {
escaped = !0;
continue;
}
if (/[?*+@!()[\]{}]/.test(ch))
return !1;
}
return !0;
}, normalizeSimpleBranch = (branch) => {
let value = branch.trim(), changed = !0;
for (; changed === !0; )
changed = !1, /^@\([^\\()[\]{}|]+\)$/.test(value) && (value = value.slice(2, -1), changed = !0);
if (isPlainBranch(value))
return value.replace(/\\(.)/g, "$1");
}, hasRepeatedCharPrefixOverlap = (branches) => {
let values = branches.map(normalizeSimpleBranch).filter(Boolean);
for (let i2 = 0; i2 < values.length; i2++)
for (let j = i2 + 1; j < values.length; j++) {
let a2 = values[i2], b = values[j], char = a2[0];
if (!(!char || a2 !== char.repeat(a2.length) || b !== char.repeat(b.length)) && (a2 === b || a2.startsWith(b) || b.startsWith(a2)))
return !0;
}
return !1;
}, parseRepeatedExtglob = (pattern, requireEnd = !0) => {
if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(")
return;
let bracket = 0, paren = 0, quote = 0, escaped = !1;
for (let i2 = 1; i2 < pattern.length; i2++) {
let ch = pattern[i2];
if (escaped === !0) {
escaped = !1;
continue;
}
if (ch === "\\") {
escaped = !0;
continue;
}
if (ch === '"') {
quote = quote === 1 ? 0 : 1;
continue;
}
if (quote !== 1) {
if (ch === "[") {
bracket++;
continue;
}
if (ch === "]" && bracket > 0) {
bracket--;
continue;
}
if (!(bracket > 0)) {
if (ch === "(") {
paren++;
continue;
}
if (ch === ")" && (paren--, paren === 0))
return requireEnd === !0 && i2 !== pattern.length - 1 ? void 0 : {
type: pattern[0],
body: pattern.slice(2, i2),
end: i2
};
}
}
}
}, getStarExtglobSequenceOutput = (pattern) => {
let index = 0, chars = [];
for (; index < pattern.length; ) {
let match = parseRepeatedExtglob(pattern.slice(index), !1);
if (!match || match.type !== "*")
return;
let branches = splitTopLevel(match.body).map((branch2) => branch2.trim());
if (branches.length !== 1)
return;
let branch = normalizeSimpleBranch(branches[0]);
if (!branch || branch.length !== 1)
return;
chars.push(branch), index += match.end + 1;
}
return chars.length < 1 ? void 0 : `${chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`}*`;
}, repeatedExtglobRecursion = (pattern) => {
let depth = 0, value = pattern.trim(), match = parseRepeatedExtglob(value);
for (; match; )
depth++, value = match.body.trim(), match = parseRepeatedExtglob(value);
return depth;
}, analyzeRepeatedExtglob = (body, options) => {
if (options.maxExtglobRecursion === !1)
return { risky: !1 };
let max = typeof options.maxExtglobRecursion == "number" ? options.maxExtglobRecursion : constants4.DEFAULT_MAX_EXTGLOB_RECURSION, branches = splitTopLevel(body).map((branch) => branch.trim());
if (branches.length > 1 && (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)))
return { risky: !0 };
for (let branch of branches) {
let safeOutput = getStarExtglobSequenceOutput(branch);
if (safeOutput)
return { risky: !0, safeOutput };
if (repeatedExtglobRecursion(branch) > max)
return { risky: !0 };
}
return { risky: !1 };
}, parse = (input, options) => {
if (typeof input != "string")
throw new TypeError("Expected a string");
input = REPLACEMENTS[input] || input;
let opts = { ...options }, max = typeof opts.maxLength == "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH, len = input.length;
if (len > max)
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
let bos = { type: "bos", value: "", output: opts.prepend || "" }, tokens = [bos], capture = opts.capture ? "" : "?:", PLATFORM_CHARS = constants4.globChars(opts.windows), EXTGLOB_CHARS = constants4.extglobChars(PLATFORM_CHARS), {
DOT_LITERAL,
PLUS_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK,
QMARK_NO_DOT,
STAR,
START_ANCHOR
} = PLATFORM_CHARS, globstar = (opts2) => `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`, nodot = opts.dot ? "" : NO_DOT, qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT, star = opts.bash === !0 ? globstar(opts) : STAR;
opts.capture && (star = `(${star})`), typeof opts.noext == "boolean" && (opts.noextglob = opts.noext);
let state = {
input,
index: -1,
start: 0,
dot: opts.dot === !0,
consumed: "",
output: "",
prefix: "",
backtrack: !1,
negated: !1,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: !1,
tokens
};
input = utils.removePrefix(input, state), len = input.length;
let extglobs = [], braces = [], stack = [], prev = bos, value, eos = () => state.index === len - 1, peek = state.peek = (n2 = 1) => input[state.index + n2], advance = state.advance = () => input[++state.index] || "", remaining = () => input.slice(state.index + 1), consume = (value2 = "", num = 0) => {
state.consumed += value2, state.index += num;
}, append = (token) => {
state.output += token.output != null ? token.output : token.value, consume(token.value);
}, negate = () => {
let count2 = 1;
for (; peek() === "!" && (peek(2) !== "(" || peek(3) === "?"); )
advance(), state.start++, count2++;
return count2 % 2 === 0 ? !1 : (state.negated = !0, state.start++, !0);
}, increment2 = (type) => {
state[type]++, stack.push(type);
}, decrement = (type) => {
state[type]--, stack.pop();
}, push = (tok) => {
if (prev.type === "globstar") {
let isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"), isExtglob = tok.extglob === !0 || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob && (state.output = state.output.slice(0, -prev.output.length), prev.type = "star", prev.value = "*", prev.output = star, state.output += prev.output);
}
if (extglobs.length && tok.type !== "paren" && (extglobs[extglobs.length - 1].inner += tok.value), (tok.value || tok.output) && append(tok), prev && prev.type === "text" && tok.type === "text") {
prev.output = (prev.output || prev.value) + tok.value, prev.value += tok.value;
return;
}
tok.prev = prev, tokens.push(tok), prev = tok;
}, extglobOpen = (type, value2) => {
let token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
token.prev = prev, token.parens = state.parens, token.output = state.output, token.startIndex = state.index, token.tokensIndex = tokens.length;
let output = (opts.capture ? "(" : "") + token.open;
increment2("parens"), push({ type, value: value2, output: state.output ? "" : ONE_CHAR }), push({ type: "paren", extglob: !0, value: advance(), output }), extglobs.push(token);
}, extglobClose = (token) => {
let literal = input.slice(token.startIndex, state.index + 1), body = input.slice(token.startIndex + 2, state.index), analysis = analyzeRepeatedExtglob(body, opts);
if ((token.type === "plus" || token.type === "star") && analysis.risky) {
let safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0, open = tokens[token.tokensIndex];
open.type = "text", open.value = literal, open.output = safeOutput || utils.escapeRegex(literal);
for (let i2 = token.tokensIndex + 1; i2 < tokens.length; i2++)
tokens[i2].value = "", tokens[i2].output = "", delete tokens[i2].suffix;
state.output = token.output + open.output, state.backtrack = !0, push({ type: "paren", extglob: !0, value, output: "" }), decrement("parens");
return;
}
let output = token.close + (opts.capture ? ")" : ""), rest;
if (token.type === "negate") {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes("/") && (extglobStar = globstar(opts)), (extglobStar !== star || eos() || /^\)+$/.test(remaining())) && (output = token.close = `)$))${extglobStar}`), token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
let expression = parse(rest, { ...options, fastpaths: !1 }).output;
output = token.close = `)${expression})${extglobStar})`;
}
token.prev.type === "bos" && (state.negatedExtglob = !0);
}
push({ type: "paren", extglob: !0, value, output }), decrement("parens");
};
if (opts.fastpaths !== !1 && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = !1, output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => first === "\\" ? (backslashes = !0, m) : first === "?" ? esc ? esc + first + (rest ? QMARK.repeat(rest.length) : "") : index === 0 ? qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "") : QMARK.repeat(chars.length) : first === "." ? DOT_LITERAL.repeat(chars.length) : first === "*" ? esc ? esc + first + (rest ? star : "") : star : esc ? m : `\\${m}`);
return backslashes === !0 && (opts.unescape === !0 ? output = output.replace(/\\/g, "") : output = output.replace(/\\+/g, (m) => m.length % 2 === 0 ? "\\\\" : m ? "\\" : "")), output === input && opts.contains === !0 ? (state.output = input, state) : (state.output = utils.wrapOutput(output, state, options), state);
}
for (; !eos(); ) {
if (value = advance(), value === "\0")
continue;
if (value === "\\") {
let next = peek();
if (next === "/" && opts.bash !== !0 || next === "." || next === ";")
continue;
if (!next) {
value += "\\", push({ type: "text", value });
continue;
}
let match = /^\\+/.exec(remaining()), slashes = 0;
if (match && match[0].length > 2 && (slashes = match[0].length, state.index += slashes, slashes % 2 !== 0 && (value += "\\")), opts.unescape === !0 ? value = advance() : value += advance(), state.brackets === 0) {
push({ type: "text", value });
continue;
}
}
if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== !1 && value === ":") {
let inner = prev.value.slice(1);
if (inner.includes("[") && (prev.posix = !0, inner.includes(":"))) {
let idx = prev.value.lastIndexOf("["), pre = prev.value.slice(0, idx), rest2 = prev.value.slice(idx + 2), posix2 = POSIX_REGEX_SOURCE[rest2];
if (posix2) {
prev.value = pre + posix2, state.backtrack = !0, advance(), !bos.output && tokens.indexOf(prev) === 1 && (bos.output = ONE_CHAR);
continue;
}
}
}
(value === "[" && peek() !== ":" || value === "-" && peek() === "]") && (value = `\\${value}`), value === "]" && (prev.value === "[" || prev.value === "[^") && (value = `\\${value}`), opts.posix === !0 && value === "!" && prev.value === "[" && (value = "^"), prev.value += value, append({ value });
continue;
}
if (state.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value), prev.value += value, append({ value });
continue;
}
if (value === '"') {
state.quotes = state.quotes === 1 ? 0 : 1, opts.keepQuotes === !0 && push({ type: "text", value });
continue;
}
if (value === "(") {
increment2("parens"), push({ type: "paren", value });
continue;
}
if (value === ")") {
if (state.parens === 0 && opts.strictBrackets === !0)
throw new SyntaxError(syntaxError("opening", "("));
let extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({ type: "paren", value, output: state.parens ? ")" : "\\)" }), decrement("parens");
continue;
}
if (value === "[") {
if (opts.nobracket === !0 || !remaining().includes("]")) {
if (opts.nobracket !== !0 && opts.strictBrackets === !0)
throw new SyntaxError(syntaxError("closing", "]"));
value = `\\${value}`;
} else
increment2("brackets");
push({ type: "bracket", value });
continue;
}
if (value === "]") {
if (opts.nobracket === !0 || prev && prev.type === "bracket" && prev.value.length === 1) {
push({ type: "text", value, output: `\\${value}` });
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === !0)
throw new SyntaxError(syntaxError("opening", "["));
push({ type: "text", value, output: `\\${value}` });
continue;
}
decrement("brackets");
let prevValue = prev.value.slice(1);
if (prev.posix !== !0 && prevValue[0] === "^" && !prevValue.includes("/") && (value = `/${value}`), prev.value += value, append({ value }), opts.literalBrackets === !1 || utils.hasRegexChars(prevValue))
continue;
let escaped = utils.escapeRegex(prev.value);
if (state.output = state.output.slice(0, -prev.value.length), opts.literalBrackets === !0) {
state.output += escaped, prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`, state.output += prev.value;
continue;
}
if (value === "{" && opts.nobrace !== !0) {
increment2("braces");
let open = {
type: "brace",
value,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open), push(open);
continue;
}
if (value === "}") {
let brace = braces[braces.length - 1];
if (opts.nobrace === !0 || !brace) {
push({ type: "text", value, output: value });
continue;
}
let output = ")";
if (brace.dots === !0) {
let arr = tokens.slice(), range = [];
for (let i2 = arr.length - 1; i2 >= 0 && (tokens.pop(), arr[i2].type !== "brace"); i2--)
arr[i2].type !== "dots" && range.unshift(arr[i2].value);
output = expandRange(range, opts), state.backtrack = !0;
}
if (brace.comma !== !0 && brace.dots !== !0) {
let out = state.output.slice(0, brace.outputIndex), toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{", value = output = "\\}", state.output = out;
for (let t of toks)
state.output += t.output || t.value;
}
push({ type: "brace", value, output }), decrement("braces"), braces.pop();
continue;
}
if (value === "|") {
extglobs.length > 0 && extglobs[extglobs.length - 1].conditions++, push({ type: "text", value });
continue;
}
if (value === ",") {
let output = value, brace = braces[braces.length - 1];
brace && stack[stack.length - 1] === "braces" && (brace.comma = !0, output = "|"), push({ type: "comma", value, output });
continue;
}
if (value === "/") {
if (prev.type === "dot" && state.index === state.start + 1) {
state.start = state.index + 1, state.consumed = "", state.output = "", tokens.pop(), prev = bos;
continue;
}
push({ type: "slash", value, output: SLASH_LITERAL });
continue;
}
if (value === ".") {
if (state.braces > 0 && prev.type === "dot") {
prev.value === "." && (prev.output = DOT_LITERAL);
let brace = braces[braces.length - 1];
prev.type = "dots", prev.output += value, prev.value += value, brace.dots = !0;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({ type: "text", value, output: DOT_LITERAL });
continue;
}
push({ type: "dot", value, output: DOT_LITERAL });
continue;
}
if (value === "?") {
if (!(prev && prev.value === "(") && opts.noextglob !== !0 && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value);
continue;
}
if (prev && prev.type === "paren") {
let next = peek(), output = value;
(prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) && (output = `\\${value}`), push({ type: "text", value, output });
continue;
}
if (opts.dot !== !0 && (prev.type === "slash" || prev.type === "bos")) {
push({ type: "qmark", value, output: QMARK_NO_DOT });
continue;
}
push({ type: "qmark", value, output: QMARK });
continue;
}
if (value === "!") {
if (opts.noextglob !== !0 && peek() === "(" && (peek(2) !== "?" || !/[!=<:]/.test(peek(3)))) {
extglobOpen("negate", value);
continue;
}
if (opts.nonegate !== !0 && state.index === 0) {
negate();
continue;
}
}
if (value === "+") {
if (opts.noextglob !== !0 && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value);
continue;
}
if (prev && prev.value === "(" || opts.regex === !1) {
push({ type: "plus", value, output: PLUS_LITERAL });
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push({ type: "plus", value });
continue;
}
push({ type: "plus", value: PLUS_LITERAL });
continue;
}
if (value === "@") {
if (opts.noextglob !== !0 && peek() === "(" && peek(2) !== "?") {
push({ type: "at", extglob: !0, value, output: "" });
continue;
}
push({ type: "text", value });
continue;
}
if (value !== "*") {
(value === "$" || value === "^") && (value = `\\${value}`);
let match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
match && (value += match[0], state.index += match[0].length), push({ type: "text", value });
continue;
}
if (prev && (prev.type === "globstar" || prev.star === !0)) {
prev.type = "star", prev.star = !0, prev.value += value, prev.output = star, state.backtrack = !0, state.globstar = !0, consume(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== !0 && /^\([^?]/.test(rest)) {
extglobOpen("star", value);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === !0) {
consume(value);
continue;
}
let prior = prev.prev, before = prior.prev, isStart = prior.type === "slash" || prior.type === "bos", afterStar = before && (before.type === "star" || before.type === "globstar");
if (opts.bash === !0 && (!isStart || rest[0] && rest[0] !== "/")) {
push({ type: "star", value, output: "" });
continue;
}
let isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"), isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
push({ type: "star", value, output: "" });
continue;
}
for (; rest.slice(0, 3) === "/**"; ) {
let after = input[state.index + 4];
if (after && after !== "/")
break;
rest = rest.slice(3), consume("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar", prev.value += value, prev.output = globstar(opts), state.output = prev.output, state.globstar = !0, consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length), prior.output = `(?:${prior.output}`, prev.type = "globstar", prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"), prev.value += value, state.globstar = !0, state.output += prior.output + prev.output, consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
let end = rest[1] !== void 0 ? "|$" : "";
state.output = state.output.slice(0, -(prior.output + prev.output).length), prior.output = `(?:${prior.output}`, prev.type = "globstar", prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`, prev.value += value, state.output += prior.output + prev.output, state.globstar = !0, consume(value + advance()), push({ type: "slash", value: "/", output: "" });
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar", prev.value += value, prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`, state.output = prev.output, state.globstar = !0, consume(value + advance()), push({ type: "slash", value: "/", output: "" });
continue;
}
state.output = state.output.slice(0, -prev.output.length), prev.type = "globstar", prev.output = globstar(opts), prev.value += value, state.output += prev.output, state.globstar = !0, consume(value);
continue;
}
let token = { type: "star", value, output: star };
if (opts.bash === !0) {
token.output = ".*?", (prev.type === "bos" || prev.type === "slash") && (token.output = nodot + token.output), push(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === !0) {
token.output = value, push(token);
continue;
}
(state.index === state.start || prev.type === "slash" || prev.type === "dot") && (prev.type === "dot" ? (state.output += NO_DOT_SLASH, prev.output += NO_DOT_SLASH) : opts.dot === !0 ? (state.output += NO_DOTS_SLASH, prev.output += NO_DOTS_SLASH) : (state.output += nodot, prev.output += nodot), peek() !== "*" && (state.output += ONE_CHAR, prev.output += ONE_CHAR)), push(token);
}
for (; state.brackets > 0; ) {
if (opts.strictBrackets === !0) throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils.escapeLast(state.output, "["), decrement("brackets");
}
for (; state.parens > 0; ) {
if (opts.strictBrackets === !0) throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils.escapeLast(state.output, "("), decrement("parens");
}
for (; state.braces > 0; ) {
if (opts.strictBrackets === !0) throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils.escapeLast(state.output, "{"), decrement("braces");
}
if (opts.strictSlashes !== !0 && (prev.type === "star" || prev.type === "bracket") && push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` }), state.backtrack === !0) {
state.output = "";
for (let token of state.tokens)
state.output += token.output != null ? token.output : token.value, token.suffix && (state.output += token.suffix);
}
return state;
};
parse.fastpaths = (input, options) => {
let opts = { ...options }, max = typeof opts.maxLength == "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH, len = input.length;
if (len > max)
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
input = REPLACEMENTS[input] || input;
let {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants4.globChars(opts.windows), nodot = opts.dot ? NO_DOTS : NO_DOT, slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT, capture = opts.capture ? "" : "?:", state = { negated: !1, prefix: "" }, star = opts.bash === !0 ? ".*?" : STAR;
opts.capture && (star = `(${star})`);
let globstar = (opts2) => opts2.noglobstar === !0 ? star : `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`, create = (str) => {
switch (str) {
case "*":
return `${nodot}${ONE_CHAR}${star}`;
case ".*":
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*.*":
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*/*":
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
case "**":
return nodot + globstar(opts);
case "**/*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
case "**/*.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "**/.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
default: {
let match = /^(.*?)\.(\w+)$/.exec(str);
if (!match) return;
let source2 = create(match[1]);
return source2 ? source2 + DOT_LITERAL + match[2] : void 0;
}
}
}, output = utils.removePrefix(input, state), source = create(output);
return source && opts.strictSlashes !== !0 && (source += `${SLASH_LITERAL}?`), source;
};
module.exports = parse;
}
});
// ../../node_modules/tinyglobby/node_modules/picomatch/lib/picomatch.js
var require_picomatch = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/lib/picomatch.js"(exports, module) {
"use strict";
var scan = require_scan(), parse = require_parse(), utils = require_utils(), constants4 = require_constants(), isObject2 = (val) => val && typeof val == "object" && !Array.isArray(val), picomatch2 = (glob, options, returnState = !1) => {
if (Array.isArray(glob)) {
let fns = glob.map((input) => picomatch2(input, options, returnState));
return (str) => {
for (let isMatch of fns) {
let state2 = isMatch(str);
if (state2) return state2;
}
return !1;
};
}
let isState = isObject2(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob != "string" && !isState)
throw new TypeError("Expected pattern to be a non-empty string");
let opts = options || {}, posix2 = opts.windows, regex = isState ? picomatch2.compileRe(glob, options) : picomatch2.makeRe(glob, options, !1, !0), state = regex.state;
delete regex.state;
let isIgnored = () => !1;
if (opts.ignore) {
let ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch2(opts.ignore, ignoreOpts, returnState);
}
let matcher = (input, returnObject = !1) => {
let { isMatch, match, output } = picomatch2.test(input, regex, options, { glob, posix: posix2 }), result = { glob, state, regex, posix: posix2, input, output, match, isMatch };
return typeof opts.onResult == "function" && opts.onResult(result), isMatch === !1 ? (result.isMatch = !1, returnObject ? result : !1) : isIgnored(input) ? (typeof opts.onIgnore == "function" && opts.onIgnore(result), result.isMatch = !1, returnObject ? result : !1) : (typeof opts.onMatch == "function" && opts.onMatch(result), returnObject ? result : !0);
};
return returnState && (matcher.state = state), matcher;
};
picomatch2.test = (input, regex, options, { glob, posix: posix2 } = {}) => {
if (typeof input != "string")
throw new TypeError("Expected input to be a string");
if (input === "")
return { isMatch: !1, output: "" };
let opts = options || {}, format2 = opts.format || (posix2 ? utils.toPosixSlashes : null), match = input === glob, output = match && format2 ? format2(input) : input;
return match === !1 && (output = format2 ? format2(input) : input, match = output === glob), (match === !1 || opts.capture === !0) && (opts.matchBase === !0 || opts.basename === !0 ? match = picomatch2.matchBase(input, regex, options, posix2) : match = regex.exec(output)), { isMatch: !!match, match, output };
};
picomatch2.matchBase = (input, glob, options) => (glob instanceof RegExp ? glob : picomatch2.makeRe(glob, options)).test(utils.basename(input));
picomatch2.isMatch = (str, patterns, options) => picomatch2(patterns, options)(str);
picomatch2.parse = (pattern, options) => Array.isArray(pattern) ? pattern.map((p) => picomatch2.parse(p, options)) : parse(pattern, { ...options, fastpaths: !1 });
picomatch2.scan = (input, options) => scan(input, options);
picomatch2.compileRe = (state, options, returnOutput = !1, returnState = !1) => {
if (returnOutput === !0)
return state.output;
let opts = options || {}, prepend = opts.contains ? "" : "^", append = opts.contains ? "" : "$", source = `${prepend}(?:${state.output})${append}`;
state && state.negated === !0 && (source = `^(?!${source}).*$`);
let regex = picomatch2.toRegex(source, options);
return returnState === !0 && (regex.state = state), regex;
};
picomatch2.makeRe = (input, options = {}, returnOutput = !1, returnState = !1) => {
if (!input || typeof input != "string")
throw new TypeError("Expected a non-empty string");
let parsed = { negated: !1, fastpaths: !0 };
return options.fastpaths !== !1 && (input[0] === "." || input[0] === "*") && (parsed.output = parse.fastpaths(input, options)), parsed.output || (parsed = parse(input, options)), picomatch2.compileRe(parsed, options, returnOutput, returnState);
};
picomatch2.toRegex = (source, options) => {
try {
let opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err) {
if (options && options.debug === !0) throw err;
return /$^/;
}
};
picomatch2.constants = constants4;
module.exports = picomatch2;
}
});
// ../../node_modules/tinyglobby/node_modules/picomatch/index.js
var require_picomatch2 = __commonJS({
"../../node_modules/tinyglobby/node_modules/picomatch/index.js"(exports, module) {
"use strict";
var pico = require_picomatch(), utils = require_utils();
function picomatch2(glob, options, returnState = !1) {
return options && (options.windows === null || options.windows === void 0) && (options = { ...options, windows: utils.isWindows() }), pico(glob, options, returnState);
}
Object.assign(picomatch2, pico);
module.exports = picomatch2;
}
});
// ../../node_modules/isexe/windows.js
var require_windows = __commonJS({
"../../node_modules/isexe/windows.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync2;
var fs = __require("fs");
function checkPathExt(path5, options) {
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
if (!pathext || (pathext = pathext.split(";"), pathext.indexOf("") !== -1))
return !0;
for (var i2 = 0; i2 < pathext.length; i2++) {
var p = pathext[i2].toLowerCase();
if (p && path5.substr(-p.length).toLowerCase() === p)
return !0;
}
return !1;
}
function checkStat(stat2, path5, options) {
return !stat2.isSymbolicLink() && !stat2.isFile() ? !1 : checkPathExt(path5, options);
}
function isexe(path5, options, cb) {
fs.stat(path5, function(er, stat2) {
cb(er, er ? !1 : checkStat(stat2, path5, options));
});
}
function sync2(path5, options) {
return checkStat(fs.statSync(path5), path5, options);
}
}
});
// ../../node_modules/isexe/mode.js
var require_mode = __commonJS({
"../../node_modules/isexe/mode.js"(exports, module) {
module.exports = isexe;
isexe.sync = sync2;
var fs = __require("fs");
function isexe(path5, options, cb) {
fs.stat(path5, function(er, stat2) {
cb(er, er ? !1 : checkStat(stat2, options));
});
}
function sync2(path5, options) {
return checkStat(fs.statSync(path5), options);
}
function checkStat(stat2, options) {
return stat2.isFile() && checkMode(stat2, options);
}
function checkMode(stat2, options) {
var mod = stat2.mode, uid = stat2.uid, gid = stat2.gid, myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(), myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(), u2 = parseInt("100", 8), g = parseInt("010", 8), o2 = parseInt("001", 8), ug = u2 | g, ret = mod & o2 || mod & g && gid === myGid || mod & u2 && uid === myUid || mod & ug && myUid === 0;
return ret;
}
}
});
// ../../node_modules/isexe/index.js
var require_isexe = __commonJS({
"../../node_modules/isexe/index.js"(exports, module) {
var fs = __require("fs"), core;
process.platform === "win32" || global.TESTING_WINDOWS ? core = require_windows() : core = require_mode();
module.exports = isexe;
isexe.sync = sync2;
function isexe(path5, options, cb) {
if (typeof options == "function" && (cb = options, options = {}), !cb) {
if (typeof Promise != "function")
throw new TypeError("callback not provided");
return new Promise(function(resolve4, reject) {
isexe(path5, options || {}, function(er, is) {
er ? reject(er) : resolve4(is);
});
});
}
core(path5, options || {}, function(er, is) {
er && (er.code === "EACCES" || options && options.ignoreErrors) && (er = null, is = !1), cb(er, is);
});
}
function sync2(path5, options) {
try {
return core.sync(path5, options || {});
} catch (er) {
if (options && options.ignoreErrors || er.code === "EACCES")
return !1;
throw er;
}
}
}
});
// ../../node_modules/which/which.js
var require_which = __commonJS({
"../../node_modules/which/which.js"(exports, module) {
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys", path5 = __require("path"), COLON = isWindows ? ";" : ":", isexe = require_isexe(), getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }), getPathInfo = (cmd, opt) => {
let colon = opt.colon || COLON, pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
// windows always checks the cwd first
...isWindows ? [process.cwd()] : [],
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
"").split(colon)
], pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "", pathExt = isWindows ? pathExtExe.split(colon) : [""];
return isWindows && cmd.indexOf(".") !== -1 && pathExt[0] !== "" && pathExt.unshift(""), {
pathEnv,
pathExt,
pathExtExe
};
}, which = (cmd, opt, cb) => {
typeof opt == "function" && (cb = opt, opt = {}), opt || (opt = {});
let { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt), found = [], step = (i2) => new Promise((resolve4, reject) => {
if (i2 === pathEnv.length)
return opt.all && found.length ? resolve4(found) : reject(getNotFoundError(cmd));
let ppRaw = pathEnv[i2], pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw, pCmd = path5.join(pathPart, cmd), p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
resolve4(subStep(p, i2, 0));
}), subStep = (p, i2, ii) => new Promise((resolve4, reject) => {
if (ii === pathExt.length)
return resolve4(step(i2 + 1));
let ext = pathExt[ii];
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is)
if (opt.all)
found.push(p + ext);
else
return resolve4(p + ext);
return resolve4(subStep(p, i2, ii + 1));
});
});
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
}, whichSync = (cmd, opt) => {
opt = opt || {};
let { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt), found = [];
for (let i2 = 0; i2 < pathEnv.length; i2++) {
let ppRaw = pathEnv[i2], pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw, pCmd = path5.join(pathPart, cmd), p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
for (let j = 0; j < pathExt.length; j++) {
let cur = p + pathExt[j];
try {
if (isexe.sync(cur, { pathExt: pathExtExe }))
if (opt.all)
found.push(cur);
else
return cur;
} catch {
}
}
}
if (opt.all && found.length)
return found;
if (opt.nothrow)
return null;
throw getNotFoundError(cmd);
};
module.exports = which;
which.sync = whichSync;
}
});
// ../../node_modules/path-key/index.js
var require_path_key = __commonJS({
"../../node_modules/path-key/index.js"(exports, module) {
"use strict";
var pathKey2 = (options = {}) => {
let environment = options.env || process.env;
return (options.platform || process.platform) !== "win32" ? "PATH" : Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
};
module.exports = pathKey2;
module.exports.default = pathKey2;
}
});
// ../../node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
"../../node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
"use strict";
var path5 = __require("path"), which = require_which(), getPathKey = require_path_key();
function resolveCommandAttempt(parsed, withoutPathExt) {
let env = parsed.options.env || process.env, cwd = process.cwd(), hasCustomCwd = parsed.options.cwd != null, shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
if (shouldSwitchCwd)
try {
process.chdir(parsed.options.cwd);
} catch {
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: env[getPathKey({ env })],
pathExt: withoutPathExt ? path5.delimiter : void 0
});
} catch {
} finally {
shouldSwitchCwd && process.chdir(cwd);
}
return resolved && (resolved = path5.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved)), resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, !0);
}
module.exports = resolveCommand;
}
});
// ../../node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
"../../node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
"use strict";
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
return arg = arg.replace(metaCharsRegExp, "^$1"), arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
return arg = `${arg}`, arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'), arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"), arg = `"${arg}"`, arg = arg.replace(metaCharsRegExp, "^$1"), doubleEscapeMetaChars && (arg = arg.replace(metaCharsRegExp, "^$1")), arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
}
});
// ../../node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
"../../node_modules/shebang-regex/index.js"(exports, module) {
"use strict";
module.exports = /^#!(.*)/;
}
});
// ../../node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
"../../node_modules/shebang-command/index.js"(exports, module) {
"use strict";
var shebangRegex = require_shebang_regex();
module.exports = (string = "") => {
let match = string.match(shebangRegex);
if (!match)
return null;
let [path5, argument] = match[0].replace(/#! ?/, "").split(" "), binary = path5.split("/").pop();
return binary === "env" ? argument : argument ? `${binary} ${argument}` : binary;
};
}
});
// ../../node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
"../../node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
"use strict";
var fs = __require("fs"), shebangCommand = require_shebang_command();
function readShebang(command) {
let buffer = Buffer.alloc(150), fd;
try {
fd = fs.openSync(command, "r"), fs.readSync(fd, buffer, 0, 150, 0), fs.closeSync(fd);
} catch {
}
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
}
});
// ../../node_modules/cross-spawn/lib/parse.js
var require_parse2 = __commonJS({
"../../node_modules/cross-spawn/lib/parse.js"(exports, module) {
"use strict";
var path5 = __require("path"), resolveCommand = require_resolveCommand(), escape = require_escape(), readShebang = require_readShebang(), isWin2 = process.platform === "win32", isExecutableRegExp = /\.(?:com|exe)$/i, isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
let shebang = parsed.file && readShebang(parsed.file);
return shebang ? (parsed.args.unshift(parsed.file), parsed.command = shebang, resolveCommand(parsed)) : parsed.file;
}
function parseNonShell(parsed) {
if (!isWin2)
return parsed;
let commandFile = detectShebang(parsed), needsShell = !isExecutableRegExp.test(commandFile);
if (parsed.options.forceShell || needsShell) {
let needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
parsed.command = path5.normalize(parsed.command), parsed.command = escape.command(parsed.command), parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
let shellCommand = [parsed.command].concat(parsed.args).join(" ");
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`], parsed.command = process.env.comspec || "cmd.exe", parsed.options.windowsVerbatimArguments = !0;
}
return parsed;
}
function parse(command, args, options) {
args && !Array.isArray(args) && (options = args, args = null), args = args ? args.slice(0) : [], options = Object.assign({}, options);
let parsed = {
command,
args,
options,
file: void 0,
original: {
command,
args
}
};
return options.shell ? parsed : parseNonShell(parsed);
}
module.exports = parse;
}
});
// ../../node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
"../../node_modules/cross-spawn/lib/enoent.js"(exports, module) {
"use strict";
var isWin2 = process.platform === "win32";
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: "ENOENT",
errno: "ENOENT",
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args
});
}
function hookChildProcess(cp, parsed) {
if (!isWin2)
return;
let originalEmit = cp.emit;
cp.emit = function(name, arg1) {
if (name === "exit") {
let err = verifyENOENT(arg1, parsed);
if (err)
return originalEmit.call(cp, "error", err);
}
return originalEmit.apply(cp, arguments);
};
}
function verifyENOENT(status, parsed) {
return isWin2 && status === 1 && !parsed.file ? notFoundError(parsed.original, "spawn") : null;
}
function verifyENOENTSync(status, parsed) {
return isWin2 && status === 1 && !parsed.file ? notFoundError(parsed.original, "spawnSync") : null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError
};
}
});
// ../../node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
"../../node_modules/cross-spawn/index.js"(exports, module) {
"use strict";
var cp = __require("child_process"), parse = require_parse2(), enoent = require_enoent();
function spawn2(command, args, options) {
let parsed = parse(command, args, options), spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
return enoent.hookChildProcess(spawned, parsed), spawned;
}
function spawnSync2(command, args, options) {
let parsed = parse(command, args, options), result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
return result.error = result.error || enoent.verifyENOENTSync(result.status, parsed), result;
}
module.exports = spawn2;
module.exports.spawn = spawn2;
module.exports.sync = spawnSync2;
module.exports._parse = parse;
module.exports._enoent = enoent;
}
});
// src/common/utils/paths.ts
import { join, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
// ../../node_modules/tinyglobby/dist/index.mjs
import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs";
import { isAbsolute, posix, resolve as resolve2 } from "path";
import { fileURLToPath } from "url";
// ../../node_modules/tinyglobby/node_modules/fdir/dist/index.mjs
import { createRequire } from "module";
import { basename, dirname, normalize, relative, resolve, sep } from "path";
import * as nativeFs from "fs";
var __require2 = createRequire(import.meta.url);
function cleanPath(path5) {
let normalized = normalize(path5);
return normalized.length > 1 && normalized[normalized.length - 1] === sep && (normalized = normalized.substring(0, normalized.length - 1)), normalized;
}
var SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path5, separator) {
return path5.replace(SLASHES_REGEX, separator);
}
var WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
function isRootDirectory(path5) {
return path5 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path5);
}
function normalizePath(path5, options) {
let { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options, pathNeedsCleaning = process.platform === "win32" && path5.includes("/") || path5.startsWith(".");
if (resolvePaths && (path5 = resolve(path5)), (normalizePath$1 || pathNeedsCleaning) && (path5 = cleanPath(path5)), path5 === ".") return "";
let needsSeperator = path5[path5.length - 1] !== pathSeparator;
return convertSlashes(needsSeperator ? path5 + pathSeparator : path5, pathSeparator);
}
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
function joinPathWithRelativePath(root, options) {
return function(filename, directoryPath) {
return directoryPath.startsWith(root) ? directoryPath.slice(root.length) + filename : convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
};
}
function joinPath(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
function build$7(root, options) {
let { relativePaths, includeBasePath } = options;
return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
}
function pushDirectoryWithRelativePath(root) {
return function(directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function(directoryPath, paths, filters) {
let relativePath = directoryPath.substring(root.length) || ".";
filters.every((filter) => filter(relativePath, !0)) && paths.push(relativePath);
};
}
var pushDirectory = (directoryPath, paths) => {
paths.push(directoryPath || ".");
}, pushDirectoryFilter = (directoryPath, paths, filters) => {
let path5 = directoryPath || ".";
filters.every((filter) => filter(path5, !0)) && paths.push(path5);
}, empty$2 = () => {
};
function build$6(root, options) {
let { includeDirs, filters, relativePaths } = options;
return includeDirs ? relativePaths ? filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root) : filters && filters.length ? pushDirectoryFilter : pushDirectory : empty$2;
}
var pushFileFilterAndCount = (filename, _paths, counts, filters) => {
filters.every((filter) => filter(filename, !1)) && counts.files++;
}, pushFileFilter = (filename, paths, _counts, filters) => {
filters.every((filter) => filter(filename, !1)) && paths.push(filename);
}, pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
}, pushFile = (filename, paths) => {
paths.push(filename);
}, empty$1 = () => {
};
function build$5(options) {
let { excludeFiles, filters, onlyCounts } = options;
return excludeFiles ? empty$1 : filters && filters.length ? onlyCounts ? pushFileFilterAndCount : pushFileFilter : onlyCounts ? pushFileCount : pushFile;
}
var getArray = (paths) => paths, getArrayGroup = () => [""].slice(0, 0);
function build$4(options) {
return options.group ? getArrayGroup : getArray;
}
var groupFiles = (groups, directory, files) => {
groups.push({
directory,
files,
dir: directory
});
}, empty = () => {
};
function build$3(options) {
return options.group ? groupFiles : empty;
}
var resolveSymlinksAsync = function(path5, state, callback$1) {
let { queue, fs, options: { suppressErrors } } = state;
queue.enqueue(), fs.realpath(path5, (error, resolvedPath) => {
if (error) return queue.dequeue(suppressErrors ? null : error, state);
fs.stat(resolvedPath, (error$1, stat2) => {
if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
if (stat2.isDirectory() && isRecursive(path5, resolvedPath, state)) return queue.dequeue(null, state);
callback$1(stat2, resolvedPath), queue.dequeue(null, state);
});
});
}, resolveSymlinks = function(path5, state, callback$1) {
let { queue, fs, options: { suppressErrors } } = state;
queue.enqueue();
try {
let resolvedPath = fs.realpathSync(path5), stat2 = fs.statSync(resolvedPath);
if (stat2.isDirectory() && isRecursive(path5, resolvedPath, state)) return;
callback$1(stat2, resolvedPath);
} catch (e) {
if (!suppressErrors) throw e;
}
};
function build$2(options, isSynchronous) {
return !options.resolveSymlinks || options.excludeSymlinks ? null : isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
function isRecursive(path5, resolved, state) {
if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
let parent = dirname(path5), depth = 1;
for (; parent !== state.root && depth < 2; ) {
let resolvedPath = state.symlinks.get(parent);
!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath)) ? depth++ : parent = dirname(parent);
}
return state.symlinks.set(path5, resolved), depth > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}
var onlyCountsSync = (state) => state.counts, groupsSync = (state) => state.groups, defaultSync = (state) => state.paths, limitFilesSync = (state) => state.paths.slice(0, state.options.maxFiles), onlyCountsAsync = (state, error, callback$1) => (report(error, callback$1, state.counts, state.options.suppressErrors), null), defaultAsync = (state, error, callback$1) => (report(error, callback$1, state.paths, state.options.suppressErrors), null), limitFilesAsync = (state, error, callback$1) => (report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors), null), groupsAsync = (state, error, callback$1) => (report(error, callback$1, state.groups, state.options.suppressErrors), null);
function report(error, callback$1, output, suppressErrors) {
callback$1(error && !suppressErrors ? error : null, output);
}
function build$1(options, isSynchronous) {
let { onlyCounts, group, maxFiles } = options;
return onlyCounts ? isSynchronous ? onlyCountsSync : onlyCountsAsync : group ? isSynchronous ? groupsSync : groupsAsync : maxFiles ? isSynchronous ? limitFilesSync : limitFilesAsync : isSynchronous ? defaultSync : defaultAsync;
}
var readdirOpts = { withFileTypes: !0 }, walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
if (state.queue.enqueue(), currentDepth < 0) return state.queue.dequeue(null, state);
let { fs } = state;
state.visited.push(crawlPath), state.counts.directories++, fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback$1(entries, directoryPath, currentDepth), state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
}, walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
let { fs } = state;
if (currentDepth < 0) return;
state.visited.push(crawlPath), state.counts.directories++;
let entries = [];
try {
entries = fs.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback$1(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
var Queue = class {
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
return this.count++, this.count;
}
dequeue(error, output) {
this.onQueueEmpty && (--this.count <= 0 || error) && (this.onQueueEmpty(error, output), error && (output.controller.abort(), this.onQueueEmpty = void 0));
}
}, Counter = class {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
}, Aborter = class {
aborted = !1;
abort() {
this.aborted = !0;
}
}, Walker = class {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback$1) {
this.isSynchronous = !callback$1, this.callbackInvoker = build$1(options, this.isSynchronous), this.root = normalizePath(root, options), this.state = {
root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
paths: [""].slice(0, 0),
groups: [],
counts: new Counter(),
options,
queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
symlinks: /* @__PURE__ */ new Map(),
visited: [""].slice(0, 0),
controller: new Aborter(),
fs: options.fs || nativeFs
}, this.joinPath = build$7(this.root, options), this.pushDirectory = build$6(this.root, options), this.pushFile = build$5(options), this.getArray = build$4(options), this.groupFiles = build$3(options), this.resolveSymlink = build$2(options, this.isSynchronous), this.walkDirectory = build(this.isSynchronous);
}
start() {
return this.pushDirectory(this.root, this.state.paths, this.state.options.filters), this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk), this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth) => {
let { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
let files = this.getArray(this.state.paths);
for (let i2 = 0; i2 < entries.length; ++i2) {
let entry = entries[i2];
if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
let filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
} else if (entry.isDirectory()) {
let path5 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path5)) continue;
this.pushDirectory(path5, paths, filters), this.walkDirectory(this.state, path5, path5, depth - 1, this.walk);
} else if (this.resolveSymlink && entry.isSymbolicLink()) {
let path5 = joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path5, this.state, (stat2, resolvedPath) => {
if (stat2.isDirectory()) {
if (resolvedPath = normalizePath(resolvedPath, this.state.options), exclude && exclude(entry.name, useRealPaths ? resolvedPath : path5 + pathSeparator)) return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path5 + pathSeparator, depth - 1, this.walk);
} else {
resolvedPath = useRealPaths ? resolvedPath : path5;
let filename = basename(resolvedPath), directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath$1), this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
};
function promise(root, options) {
return new Promise((resolve$1, reject) => {
callback(root, options, (err, output) => {
if (err) return reject(err);
resolve$1(output);
});
});
}
function callback(root, options, callback$1) {
new Walker(root, options, callback$1).start();
}
function sync(root, options) {
return new Walker(root, options).start();
}
var APIBuilder = class {
constructor(root, options) {
this.root = root, this.options = options;
}
withPromise() {
return promise(this.root, this.options);
}
withCallback(cb) {
callback(this.root, this.options, cb);
}
sync() {
return sync(this.root, this.options);
}
}, pm = null;
try {
__require2.resolve("picomatch"), pm = __require2("picomatch");
} catch {
}
var Builder = class {
globCache = {};
options = {
maxDepth: 1 / 0,
suppressErrors: !0,
pathSeparator: sep,
filters: []
};
globFunction;
constructor(options) {
this.options = {
...this.options,
...options
}, this.globFunction = this.options.globFunction;
}
group() {
return this.options.group = !0, this;
}
withPathSeparator(separator) {
return this.options.pathSeparator = separator, this;
}
withBasePath() {
return this.options.includeBasePath = !0, this;
}
withRelativePaths() {
return this.options.relativePaths = !0, this;
}
withDirs() {
return this.options.includeDirs = !0, this;
}
withMaxDepth(depth) {
return this.options.maxDepth = depth, this;
}
withMaxFiles(limit) {
return this.options.maxFiles = limit, this;
}
withFullPaths() {
return this.options.resolvePaths = !0, this.options.includeBasePath = !0, this;
}
withErrors() {
return this.options.suppressErrors = !1, this;
}
withSymlinks({ resolvePaths = !0 } = {}) {
return this.options.resolveSymlinks = !0, this.options.useRealPaths = resolvePaths, this.withFullPaths();
}
withAbortSignal(signal) {
return this.options.signal = signal, this;
}
normalize() {
return this.options.normalizePath = !0, this;
}
filter(predicate) {
return this.options.filters.push(predicate), this;
}
onlyDirs() {
return this.options.excludeFiles = !0, this.options.includeDirs = !0, this;
}
exclude(predicate) {
return this.options.exclude = predicate, this;
}
onlyCounts() {
return this.options.onlyCounts = !0, this;
}
crawl(root) {
return new APIBuilder(root || ".", this.options);
}
withGlobFunction(fn) {
return this.globFunction = fn, this;
}
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
/* c8 ignore next 4 */
crawlWithOptions(root, options) {
return this.options = {
...this.options,
...options
}, new APIBuilder(root || ".", this.options);
}
glob(...patterns) {
return this.globFunction ? this.globWithOptions(patterns) : this.globWithOptions(patterns, { dot: !0 });
}
globWithOptions(patterns, ...options) {
let globFn = this.globFunction || pm;
if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
var isMatch = this.globCache[patterns.join("\0")];
return isMatch || (isMatch = globFn(patterns, ...options), this.globCache[patterns.join("\0")] = isMatch), this.options.filters.push((path5) => isMatch(path5)), this;
}
};
// ../../node_modules/tinyglobby/dist/index.mjs
var import_picomatch = __toESM(require_picomatch2(), 1), isReadonlyArray = Array.isArray, BACKSLASHES = /\\/g, DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/, isWin = process.platform === "win32", ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
function getPartialMatcher(patterns, options = {}) {
let patternsCount = patterns.length, patternsParts = Array(patternsCount), matchers = Array(patternsCount), i2, j;
for (i2 = 0; i2 < patternsCount; i2++) {
let parts = splitPattern(patterns[i2]);
patternsParts[i2] = parts;
let partsCount = parts.length, partMatchers = Array(partsCount);
for (j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
matchers[i2] = partMatchers;
}
return (input) => {
let inputParts = input.split("/");
if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return !0;
for (i2 = 0; i2 < patternsCount; i2++) {
let patternParts = patternsParts[i2], matcher = matchers[i2], inputPatternCount = inputParts.length, minParts = Math.min(inputPatternCount, patternParts.length);
for (j = 0; j < minParts; ) {
let part = patternParts[j];
if (part.includes("/")) return !0;
if (!matcher[j](inputParts[j])) break;
if (!options.noglobstar && part === "**") return !0;
j++;
}
if (j === inputPatternCount) return !0;
}
return !1;
};
}
var WIN32_ROOT_DIR = /^[A-Z]:\/$/i, isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
function buildFormat(cwd, root, absolute) {
if (cwd === root || root.startsWith(`${cwd}/`)) {
if (absolute) {
let start = cwd.length + +!isRoot(cwd);
return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
}
let prefix = root.slice(cwd.length + 1);
return prefix ? (p, isDir) => {
if (p === ".") return prefix;
let result = `${prefix}/${p}`;
return isDir ? result.slice(0, -1) : result;
} : (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
}
return absolute ? (p) => posix.relative(cwd, p) || "." : (p) => posix.relative(cwd, `${root}/${p}`) || ".";
}
function buildRelative(cwd, root) {
if (root.startsWith(`${cwd}/`)) {
let prefix = root.slice(cwd.length + 1);
return (p) => `${prefix}/${p}`;
}
return (p) => {
let result = posix.relative(cwd, `${root}/${p}`);
return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
};
}
function ensureNonDriveRelativePath(path5) {
return path5.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
}
var splitPatternOptions = { parts: !0 };
function splitPattern(path5) {
var _result$parts;
let result = import_picomatch.default.scan(path5, splitPatternOptions);
return !((_result$parts = result.parts) === null || _result$parts === void 0) && _result$parts.length ? result.parts : [path5];
}
var POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g, WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g, escapePosixPath = (path5) => path5.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"), escapeWin32Path = (path5) => path5.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"), escapePath = isWin ? escapeWin32Path : escapePosixPath;
function isDynamicPattern(pattern, options) {
if (options?.caseSensitiveMatch === !1) return !0;
let scan = import_picomatch.default.scan(pattern);
return scan.isGlob || scan.negated;
}
function log(...tasks) {
console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
}
function ensureStringArray(value) {
return typeof value == "string" ? [value] : value ?? [];
}
var PARENT_DIRECTORY = /^(\/?\.\.)+/, ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
function normalizePattern(pattern, opts, props, isIgnore) {
var _PARENT_DIRECTORY$exe;
let cwd = opts.cwd, result = pattern;
pattern[pattern.length - 1] === "/" && (result = pattern.slice(0, -1)), result[result.length - 1] !== "*" && opts.expandDirectories && (result += "/**");
let escapedCwd = escapePath(cwd);
result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result);
let parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0], parts = splitPattern(result);
if (parentDir) {
let n2 = (parentDir.length + 1) / 3, i2 = 0, cwdParts = escapedCwd.split("/");
for (; i2 < n2 && parts[i2 + n2] === cwdParts[cwdParts.length + i2 - n2]; )
result = result.slice(0, (n2 - i2 - 1) * 3) + result.slice((n2 - i2) * 3 + parts[i2 + n2].length + 1) || ".", i2++;
let potentialRoot = posix.join(cwd, parentDir.slice(i2 * 3));
potentialRoot[0] !== "." && props.root.length > potentialRoot.length && (props.root = ensureNonDriveRelativePath(potentialRoot), props.depthOffset = -n2 + i2);
}
if (!isIgnore && props.depthOffset >= 0) {
var _props$commonPath;
(_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
let newCommonPath = [], length = Math.min(props.commonPath.length, parts.length);
for (let i2 = 0; i2 < length; i2++) {
let part = parts[i2];
if (part === "**" && !parts[i2 + 1]) {
newCommonPath.pop();
break;
}
if (i2 === parts.length - 1 || part !== props.commonPath[i2] || isDynamicPattern(part)) break;
newCommonPath.push(part);
}
props.depthOffset = newCommonPath.length, props.commonPath = newCommonPath, props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
}
return result;
}
function processPatterns(options, patterns, props) {
let matchPatterns = [], ignorePatterns = [];
for (let pattern of options.ignore)
pattern && (pattern[0] !== "!" || pattern[1] === "(") && ignorePatterns.push(normalizePattern(pattern, options, props, !0));
for (let pattern of patterns)
pattern && (pattern[0] !== "!" || pattern[1] === "(" ? matchPatterns.push(normalizePattern(pattern, options, props, !1)) : (pattern[1] !== "!" || pattern[2] === "(") && ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, !0)));
return {
match: matchPatterns,
ignore: ignorePatterns
};
}
function buildCrawler(options, patterns) {
let cwd = options.cwd, props = {
root: cwd,
depthOffset: 0
}, processed = processPatterns(options, patterns, props);
options.debug && log("internal processing patterns:", processed);
let { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options, root = props.root.replace(BACKSLASHES, ""), matchOptions = {
dot,
nobrace: options.braceExpansion === !1,
nocase: !caseSensitiveMatch,
noextglob: options.extglob === !1,
noglobstar: options.globstar === !1,
posix: !0
}, matcher = (0, import_picomatch.default)(processed.match, matchOptions), ignore = (0, import_picomatch.default)(processed.ignore, matchOptions), partialMatcher = getPartialMatcher(processed.match, matchOptions), format2 = buildFormat(cwd, root, absolute), excludeFormatter = absolute ? format2 : buildFormat(cwd, root, !0), excludePredicate = (_, p) => {
let relativePath = excludeFormatter(p, !0);
return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
}, maxDepth;
options.deep !== void 0 && (maxDepth = Math.round(options.deep - props.depthOffset));
let crawler = new Builder({
filters: [debug ? (p, isDirectory) => {
let path5 = format2(p, isDirectory), matches = matcher(path5) && !ignore(path5);
return matches && log(`matched ${path5}`), matches;
} : (p, isDirectory) => {
let path5 = format2(p, isDirectory);
return matcher(path5) && !ignore(path5);
}],
exclude: debug ? (_, p) => {
let skipped = excludePredicate(_, p);
return log(`${skipped ? "skipped" : "crawling"} ${p}`), skipped;
} : excludePredicate,
fs: options.fs,
pathSeparator: "/",
relativePaths: !absolute,
resolvePaths: absolute,
includeBasePath: absolute,
resolveSymlinks: followSymbolicLinks,
excludeSymlinks: !followSymbolicLinks,
excludeFiles: onlyDirectories,
includeDirs: onlyDirectories || !options.onlyFiles,
maxDepth,
signal: options.signal
}).crawl(root);
return options.debug && log("internal properties:", {
...props,
root
}), [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
}
function formatPaths(paths, mapper) {
if (mapper) for (let i2 = paths.length - 1; i2 >= 0; i2--) paths[i2] = mapper(paths[i2]);
return paths;
}
var defaultOptions = {
caseSensitiveMatch: !0,
debug: !!process.env.TINYGLOBBY_DEBUG,
expandDirectories: !0,
followSymbolicLinks: !0,
onlyFiles: !0
};
function getOptions(options) {
let opts = Object.assign({}, options);
for (let key in defaultOptions) opts[key] === void 0 && Object.assign(opts, { [key]: defaultOptions[key] });
return opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve2(opts.cwd || process.cwd())).replace(BACKSLASHES, "/"), opts.ignore = ensureStringArray(opts.ignore), opts.fs && (opts.fs = {
readdir: opts.fs.readdir || readdir,
readdirSync: opts.fs.readdirSync || readdirSync,
realpath: opts.fs.realpath || realpath,
realpathSync: opts.fs.realpathSync || realpathSync,
stat: opts.fs.stat || stat,
statSync: opts.fs.statSync || statSync
}), opts.debug && log("globbing with options:", opts), opts;
}
function getCrawler(globInput, inputOptions = {}) {
var _ref;
if (globInput && inputOptions?.patterns) throw new Error("Cannot pass patterns as both an argument and an option");
let isModern = isReadonlyArray(globInput) || typeof globInput == "string", patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*"), options = getOptions(isModern ? inputOptions : globInput);
return patterns.length > 0 ? buildCrawler(options, patterns) : [];
}
function globSync(globInput, options) {
let [crawler, relative3] = getCrawler(globInput, options);
return crawler ? formatPaths(crawler.sync(), relative3) : [];
}
// src/common/js-package-manager/constants.ts
var NPM_LOCKFILE = "package-lock.json", PNPM_LOCKFILE = "pnpm-lock.yaml", YARN_LOCKFILE = "yarn.lock", BUN_LOCKFILE = "bun.lock", BUN_LOCKFILE_BINARY = "bun.lockb", LOCK_FILES = [
NPM_LOCKFILE,
PNPM_LOCKFILE,
YARN_LOCKFILE,
BUN_LOCKFILE,
BUN_LOCKFILE_BINARY
];
// src/common/utils/paths.ts
var projectRoot, getProjectRoot = () => {
if (projectRoot)
return projectRoot;
if (process.env.STORYBOOK_PROJECT_ROOT)
return process.env.STORYBOOK_PROJECT_ROOT;
try {
let found = up2(".git") || up2(".svn") || up2(".hg");
if (found)
return projectRoot = join(found, ".."), projectRoot;
} catch (e) {
process.stdout.write(`
error searching for repository root: ${e}
`);
}
try {
let found = any(LOCK_FILES);
if (found)
return projectRoot = join(found, ".."), projectRoot;
} catch (e) {
process.stdout.write(`
error searching for lock file: ${e}
`);
}
try {
let [basePath, rest] = __dirname.split(`${sep2}node_modules${sep2}`, 2);
if (rest && !basePath.includes(`${sep2}npm-cache${sep2}`) && !relative2(basePath, process.cwd()).startsWith(".."))
return projectRoot = basePath, projectRoot;
} catch (e) {
process.stdout.write(`
error searching for splitDirname: ${e}
`);
}
return projectRoot = process.cwd(), projectRoot;
}, invalidateProjectRootCache = () => {
projectRoot = void 0;
}, findFilesUp = (matchers, baseDir = process.cwd()) => {
let matchingFiles = [];
for (let directory of up(baseDir, { last: getProjectRoot() }))
matchingFiles.push(...globSync(matchers, { cwd: directory, absolute: !0 }));
return matchingFiles;
}, nodePathsToArray = (nodePath) => nodePath.split(process.platform === "win32" ? ";" : ":").filter(Boolean).map((p) => resolve3("./", p)), relativePattern = /^\.{1,2}([/\\]|$)/;
function normalizeStoryPath(filename) {
return relativePattern.test(filename) ? filename : `.${sep2}${filename}`;
}
// src/common/utils/envs.ts
import { isWebContainer } from "@webcontainer/env";
async function loadEnvs(options = {}) {
let { getEnvironment } = await import("./lib-OBLZOLLS.js"), defaultNodeEnv = options.production ? "production" : "development", baseEnv = {
NODE_ENV: process.env.NODE_ENV || defaultNodeEnv,
NODE_PATH: process.env.NODE_PATH || "",
STORYBOOK: process.env.STORYBOOK || "true",
// This is to support CRA's public folder feature.
// In production we set this to dot(.) to allow the browser to access these assets
// even when deployed inside a subpath. (like in GitHub pages)
// In development this is just empty as we always serves from the root.
PUBLIC_URL: options.production ? "." : ""
}, dotenv = getEnvironment({ nodeEnv: baseEnv.NODE_ENV }), envEntries = Object.fromEntries(
Object.entries({
// TODO: it seems wrong that dotenv overrides process.env, but that's how it has always worked
...process.env,
...dotenv.raw
}).filter(([name]) => /^STORYBOOK_/.test(name))
), raw = { ...baseEnv, ...envEntries };
raw.NODE_PATH = nodePathsToArray(raw.NODE_PATH || "");
let stringified = Object.fromEntries(
Object.entries(raw).map(([key, value]) => [key, JSON.stringify(value)])
);
return { raw, stringified };
}
var stringifyEnvs = (raw) => Object.entries(raw).reduce((acc, [key, value]) => (acc[key] = JSON.stringify(value), acc), {}), stringifyProcessEnvs = (raw) => Object.entries(raw).reduce((acc, [key, value]) => (acc[`process.env.${key}`] = JSON.stringify(value), acc), {}), optionalEnvToBoolean = (input) => {
if (input !== void 0)
return input.toUpperCase() === "FALSE" || input === "0" ? !1 : input.toUpperCase() === "TRUE" || input === "1" ? !0 : !!input;
};
function isCI() {
return optionalEnvToBoolean(process.env.CI);
}
// src/common/utils/component-id.ts
function getComponentIdFromEntry(entry) {
return entry.id.split("--")[0];
}
// src/common/utils/select-component-entry.ts
var import_ts_dedent = __toESM(require_dist(), 1);
import { once } from "storybook/internal/node-logger";
var STORY_FILE_TEST_REGEXP = /(stories|story)\.(m?js|ts)x?$/;
function isAttachedDocsEntry(entry) {
return entry.type === "docs" && entry.tags?.includes(Tag.ATTACHED_MDX) === !0 && entry.storiesImports.length > 0;
}
function isEligibleStoryEntry(entry) {
return entry.type === "story" && entry.subtype === "story";
}
function getStoryImportPathFromEntry(entry) {
if (entry.type === "story")
return entry.importPath;
if (isAttachedDocsEntry(entry))
return entry.storiesImports[0];
}
function buildCollisionWarning(componentId, importPaths, winner) {
let sortedPaths = Array.from(importPaths).sort();
return import_ts_dedent.dedent`
Multiple story files share the component id '${componentId}':
${sortedPaths.map((path5) => ` - ${path5}`).join(`
`)}
Component-level docs (props tables, code snippets, manifests, MCP docs) for this id are generated from '${winner.importPath}' only, so stories in the other files are left out of them. If these files document different components, give each file a unique title so every component keeps its docs.
`;
}
function selectComponentEntriesByComponentId(indexEntries) {
let entriesByComponentId = /* @__PURE__ */ new Map(), storyImportPathsByComponentId = /* @__PURE__ */ new Map();
for (let entry of indexEntries) {
if (!isEligibleStoryEntry(entry))
continue;
let componentId = getComponentIdFromEntry(entry);
entriesByComponentId.set(componentId, entry);
let importPaths = storyImportPathsByComponentId.get(componentId) ?? /* @__PURE__ */ new Set();
importPaths.add(entry.importPath), storyImportPathsByComponentId.set(componentId, importPaths);
}
for (let [componentId, importPaths] of storyImportPathsByComponentId) {
let winner = entriesByComponentId.get(componentId);
importPaths.size > 1 && winner && once.warn(buildCollisionWarning(componentId, importPaths, winner));
}
for (let entry of indexEntries) {
if (!isAttachedDocsEntry(entry))
continue;
let componentId = getComponentIdFromEntry(entry);
entriesByComponentId.has(componentId) || entriesByComponentId.set(componentId, entry);
}
return entriesByComponentId;
}
// ../../node_modules/is-plain-obj/index.js
function isPlainObject(value) {
if (typeof value != "object" || value === null)
return !1;
let prototype = Object.getPrototypeOf(value);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
// ../../node_modules/execa/lib/arguments/file-url.js
import { fileURLToPath as fileURLToPath2 } from "node:url";
var safeNormalizeFileUrl = (file, name) => {
let fileString = normalizeFileUrl(normalizeDenoExecPath(file));
if (typeof fileString != "string")
throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`);
return fileString;
}, normalizeDenoExecPath = (file) => isDenoExecPath(file) ? file.toString() : file, isDenoExecPath = (file) => typeof file != "string" && file && Object.getPrototypeOf(file) === String.prototype, normalizeFileUrl = (file) => file instanceof URL ? fileURLToPath2(file) : file;
// ../../node_modules/execa/lib/methods/parameters.js
var normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {
let filePath = safeNormalizeFileUrl(rawFile, "First argument"), [commandArguments, options] = isPlainObject(rawArguments) ? [[], rawArguments] : [rawArguments, rawOptions];
if (!Array.isArray(commandArguments))
throw new TypeError(`Second argument must be either an array of arguments or an options object: ${commandArguments}`);
if (commandArguments.some((commandArgument) => typeof commandArgument == "object" && commandArgument !== null))
throw new TypeError(`Second argument must be an array of strings: ${commandArguments}`);
let normalizedArguments = commandArguments.map(String), nullByteArgument = normalizedArguments.find((normalizedArgument) => normalizedArgument.includes("\0"));
if (nullByteArgument !== void 0)
throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArgument}`);
if (!isPlainObject(options))
throw new TypeError(`Last argument must be an options object: ${options}`);
return [filePath, normalizedArguments, options];
};
// ../../node_modules/execa/lib/methods/template.js
import { ChildProcess } from "node:child_process";
// ../../node_modules/execa/lib/utils/uint-array.js
import { StringDecoder } from "node:string_decoder";
var { toString: objectToString } = Object.prototype, isArrayBuffer = (value) => objectToString.call(value) === "[object ArrayBuffer]", isUint8Array = (value) => objectToString.call(value) === "[object Uint8Array]", bufferToUint8Array = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), textEncoder = new TextEncoder(), stringToUint8Array = (string) => textEncoder.encode(string), textDecoder = new TextDecoder(), uint8ArrayToString = (uint8Array) => textDecoder.decode(uint8Array), joinToString = (uint8ArraysOrStrings, encoding) => uint8ArraysToStrings(uint8ArraysOrStrings, encoding).join(""), uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {
if (encoding === "utf8" && uint8ArraysOrStrings.every((uint8ArrayOrString) => typeof uint8ArrayOrString == "string"))
return uint8ArraysOrStrings;
let decoder = new StringDecoder(encoding), strings = uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString == "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString).map((uint8Array) => decoder.write(uint8Array)), finalString = decoder.end();
return finalString === "" ? strings : [...strings, finalString];
}, joinToUint8Array = (uint8ArraysOrStrings) => uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0]) ? uint8ArraysOrStrings[0] : concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings)), stringsToUint8Arrays = (uint8ArraysOrStrings) => uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString == "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString), concatUint8Arrays = (uint8Arrays) => {
let result = new Uint8Array(getJoinLength(uint8Arrays)), index = 0;
for (let uint8Array of uint8Arrays)
result.set(uint8Array, index), index += uint8Array.length;
return result;
}, getJoinLength = (uint8Arrays) => {
let joinLength = 0;
for (let uint8Array of uint8Arrays)
joinLength += uint8Array.length;
return joinLength;
};
// ../../node_modules/execa/lib/methods/template.js
var isTemplateString = (templates) => Array.isArray(templates) && Array.isArray(templates.raw), parseTemplates = (templates, expressions) => {
let tokens = [];
for (let [index, template] of templates.entries())
tokens = parseTemplate({
templates,
expressions,
tokens,
index,
template
});
if (tokens.length === 0)
throw new TypeError("Template script must not be empty");
let [file, ...commandArguments] = tokens;
return [file, commandArguments, {}];
}, parseTemplate = ({ templates, expressions, tokens, index, template }) => {
if (template === void 0)
throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);
let { nextTokens, leadingWhitespaces, trailingWhitespaces } = splitByWhitespaces(template, templates.raw[index]), newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);
if (index === expressions.length)
return newTokens;
let expression = expressions[index], expressionTokens = Array.isArray(expression) ? expression.map((expression2) => parseExpression(expression2)) : [parseExpression(expression)];
return concatTokens(newTokens, expressionTokens, trailingWhitespaces);
}, splitByWhitespaces = (template, rawTemplate) => {
if (rawTemplate.length === 0)
return { nextTokens: [], leadingWhitespaces: !1, trailingWhitespaces: !1 };
let nextTokens = [], templateStart = 0, leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);
for (let templateIndex = 0, rawIndex = 0; templateIndex < template.length; templateIndex += 1, rawIndex += 1) {
let rawCharacter = rawTemplate[rawIndex];
if (DELIMITERS.has(rawCharacter))
templateStart !== templateIndex && nextTokens.push(template.slice(templateStart, templateIndex)), templateStart = templateIndex + 1;
else if (rawCharacter === "\\") {
let nextRawCharacter = rawTemplate[rawIndex + 1];
nextRawCharacter === `
` ? (templateIndex -= 1, rawIndex += 1) : nextRawCharacter === "u" && rawTemplate[rawIndex + 2] === "{" ? rawIndex = rawTemplate.indexOf("}", rawIndex + 3) : rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;
}
}
let trailingWhitespaces = templateStart === template.length;
return trailingWhitespaces || nextTokens.push(template.slice(templateStart)), { nextTokens, leadingWhitespaces, trailingWhitespaces };
}, DELIMITERS = /* @__PURE__ */ new Set([" ", " ", "\r", `
`]), ESCAPE_LENGTH = { x: 3, u: 5 }, concatTokens = (tokens, nextTokens, isSeparated) => isSeparated || tokens.length === 0 || nextTokens.length === 0 ? [...tokens, ...nextTokens] : [
...tokens.slice(0, -1),
`${tokens.at(-1)}${nextTokens[0]}`,
...nextTokens.slice(1)
], parseExpression = (expression) => {
let typeOfExpression = typeof expression;
if (typeOfExpression === "string")
return expression;
if (typeOfExpression === "number")
return String(expression);
if (isPlainObject(expression) && ("stdout" in expression || "isMaxBuffer" in expression))
return getSubprocessResult(expression);
throw expression instanceof ChildProcess || Object.prototype.toString.call(expression) === "[object Promise]" ? new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.") : new TypeError(`Unexpected "${typeOfExpression}" in template expression`);
}, getSubprocessResult = ({ stdout }) => {
if (typeof stdout == "string")
return stdout;
if (isUint8Array(stdout))
return uint8ArrayToString(stdout);
throw stdout === void 0 ? new TypeError(`Missing result.stdout in template expression. This is probably due to the previous subprocess' "stdout" option.`) : new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);
};
// ../../node_modules/execa/lib/methods/main-sync.js
import { spawnSync } from "node:child_process";
// ../../node_modules/execa/lib/arguments/specific.js
import { debuglog } from "node:util";
// ../../node_modules/execa/lib/utils/standard-stream.js
import process2 from "node:process";
var isStandardStream = (stream) => STANDARD_STREAMS.includes(stream), STANDARD_STREAMS = [process2.stdin, process2.stdout, process2.stderr], STANDARD_STREAMS_ALIASES = ["stdin", "stdout", "stderr"], getStreamName = (fdNumber) => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;
// ../../node_modules/execa/lib/arguments/specific.js
var normalizeFdSpecificOptions = (options) => {
let optionsCopy = { ...options };
for (let optionName of FD_SPECIFIC_OPTIONS)
optionsCopy[optionName] = normalizeFdSpecificOption(options, optionName);
return optionsCopy;
}, normalizeFdSpecificOption = (options, optionName) => {
let optionBaseArray = Array.from({ length: getStdioLength(options) + 1 }), optionArray = normalizeFdSpecificValue(options[optionName], optionBaseArray, optionName);
return addDefaultValue(optionArray, optionName);
}, getStdioLength = ({ stdio }) => Array.isArray(stdio) ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length) : STANDARD_STREAMS_ALIASES.length, normalizeFdSpecificValue = (optionValue, optionArray, optionName) => isPlainObject(optionValue) ? normalizeOptionObject(optionValue, optionArray, optionName) : optionArray.fill(optionValue), normalizeOptionObject = (optionValue, optionArray, optionName) => {
for (let fdName of Object.keys(optionValue).sort(compareFdName))
for (let fdNumber of parseFdName(fdName, optionName, optionArray))
optionArray[fdNumber] = optionValue[fdName];
return optionArray;
}, compareFdName = (fdNameA, fdNameB) => getFdNameOrder(fdNameA) < getFdNameOrder(fdNameB) ? 1 : -1, getFdNameOrder = (fdName) => fdName === "stdout" || fdName === "stderr" ? 0 : fdName === "all" ? 2 : 1, parseFdName = (fdName, optionName, optionArray) => {
if (fdName === "ipc")
return [optionArray.length - 1];
let fdNumber = parseFd(fdName);
if (fdNumber === void 0 || fdNumber === 0)
throw new TypeError(`"${optionName}.${fdName}" is invalid.
It must be "${optionName}.stdout", "${optionName}.stderr", "${optionName}.all", "${optionName}.ipc", or "${optionName}.fd3", "${optionName}.fd4" (and so on).`);
if (fdNumber >= optionArray.length)
throw new TypeError(`"${optionName}.${fdName}" is invalid: that file descriptor does not exist.
Please set the "stdio" option to ensure that file descriptor exists.`);
return fdNumber === "all" ? [1, 2] : [fdNumber];
}, parseFd = (fdName) => {
if (fdName === "all")
return fdName;
if (STANDARD_STREAMS_ALIASES.includes(fdName))
return STANDARD_STREAMS_ALIASES.indexOf(fdName);
let regexpResult = FD_REGEXP.exec(fdName);
if (regexpResult !== null)
return Number(regexpResult[1]);
}, FD_REGEXP = /^fd(\d+)$/, addDefaultValue = (optionArray, optionName) => optionArray.map((optionValue) => optionValue === void 0 ? DEFAULT_OPTIONS[optionName] : optionValue), verboseDefault = debuglog("execa").enabled ? "full" : "none", DEFAULT_OPTIONS = {
lines: !1,
buffer: !0,
maxBuffer: 1e3 * 1e3 * 100,
verbose: verboseDefault,
stripFinalNewline: !0
}, FD_SPECIFIC_OPTIONS = ["lines", "buffer", "maxBuffer", "verbose", "stripFinalNewline"], getFdSpecificValue = (optionArray, fdNumber) => fdNumber === "ipc" ? optionArray.at(-1) : optionArray[fdNumber];
// ../../node_modules/execa/lib/verbose/values.js
var isVerbose = ({ verbose }, fdNumber) => getFdVerbose(verbose, fdNumber) !== "none", isFullVerbose = ({ verbose }, fdNumber) => !["none", "short"].includes(getFdVerbose(verbose, fdNumber)), getVerboseFunction = ({ verbose }, fdNumber) => {
let fdVerbose = getFdVerbose(verbose, fdNumber);
return isVerboseFunction(fdVerbose) ? fdVerbose : void 0;
}, getFdVerbose = (verbose, fdNumber) => fdNumber === void 0 ? getFdGenericVerbose(verbose) : getFdSpecificValue(verbose, fdNumber), getFdGenericVerbose = (verbose) => verbose.find((fdVerbose) => isVerboseFunction(fdVerbose)) ?? VERBOSE_VALUES.findLast((fdVerbose) => verbose.includes(fdVerbose)), isVerboseFunction = (fdVerbose) => typeof fdVerbose == "function", VERBOSE_VALUES = ["none", "short", "full"];
// ../../node_modules/execa/lib/verbose/log.js
import { inspect } from "node:util";
// ../../node_modules/execa/lib/arguments/escape.js
import { platform } from "node:process";
import { stripVTControlCharacters } from "node:util";
var joinCommand = (filePath, rawArguments) => {
let fileAndArguments = [filePath, ...rawArguments], command = fileAndArguments.join(" "), escapedCommand = fileAndArguments.map((fileAndArgument) => quoteString(escapeControlCharacters(fileAndArgument))).join(" ");
return { command, escapedCommand };
}, escapeLines = (lines) => stripVTControlCharacters(lines).split(`
`).map((line) => escapeControlCharacters(line)).join(`
`), escapeControlCharacters = (line) => line.replaceAll(SPECIAL_CHAR_REGEXP, (character) => escapeControlCharacter(character)), escapeControlCharacter = (character) => {
let commonEscape = COMMON_ESCAPES[character];
if (commonEscape !== void 0)
return commonEscape;
let codepoint = character.codePointAt(0), codepointHex = codepoint.toString(16);
return codepoint <= ASTRAL_START ? `\\u${codepointHex.padStart(4, "0")}` : `\\U${codepointHex}`;
}, getSpecialCharRegExp = () => {
try {
return new RegExp("\\p{Separator}|\\p{Other}", "gu");
} catch {
return /[\s\u0000-\u001F\u007F-\u009F\u00AD]/g;
}
}, SPECIAL_CHAR_REGEXP = getSpecialCharRegExp(), COMMON_ESCAPES = {
" ": " ",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t"
}, ASTRAL_START = 65535, quoteString = (escapedArgument) => NO_ESCAPE_REGEXP.test(escapedArgument) ? escapedArgument : platform === "win32" ? `"${escapedArgument.replaceAll('"', '""')}"` : `'${escapedArgument.replaceAll("'", "'\\''")}'`, NO_ESCAPE_REGEXP = /^[\w./-]+$/;
// ../../node_modules/is-unicode-supported/index.js
import process3 from "node:process";
function isUnicodeSupported() {
let { env } = process3, { TERM, TERM_PROGRAM } = env;
return process3.platform !== "win32" ? TERM !== "linux" : !!env.WT_SESSION || !!env.TERMINUS_SUBLIME || env.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
}
// ../../node_modules/execa/node_modules/figures/index.js
var common = {
circleQuestionMark: "(?)",
questionMarkPrefix: "(?)",
square: "\u2588",
squareDarkShade: "\u2593",
squareMediumShade: "\u2592",
squareLightShade: "\u2591",
squareTop: "\u2580",
squareBottom: "\u2584",
squareLeft: "\u258C",
squareRight: "\u2590",
squareCenter: "\u25A0",
bullet: "\u25CF",
dot: "\u2024",
ellipsis: "\u2026",
pointerSmall: "\u203A",
triangleUp: "\u25B2",
triangleUpSmall: "\u25B4",
triangleDown: "\u25BC",
triangleDownSmall: "\u25BE",
triangleLeftSmall: "\u25C2",
triangleRightSmall: "\u25B8",
home: "\u2302",
heart: "\u2665",
musicNote: "\u266A",
musicNoteBeamed: "\u266B",
arrowUp: "\u2191",
arrowDown: "\u2193",
arrowLeft: "\u2190",
arrowRight: "\u2192",
arrowLeftRight: "\u2194",
arrowUpDown: "\u2195",
almostEqual: "\u2248",
notEqual: "\u2260",
lessOrEqual: "\u2264",
greaterOrEqual: "\u2265",
identical: "\u2261",
infinity: "\u221E",
subscriptZero: "\u2080",
subscriptOne: "\u2081",
subscriptTwo: "\u2082",
subscriptThree: "\u2083",
subscriptFour: "\u2084",
subscriptFive: "\u2085",
subscriptSix: "\u2086",
subscriptSeven: "\u2087",
subscriptEight: "\u2088",
subscriptNine: "\u2089",
oneHalf: "\xBD",
oneThird: "\u2153",
oneQuarter: "\xBC",
oneFifth: "\u2155",
oneSixth: "\u2159",
oneEighth: "\u215B",
twoThirds: "\u2154",
twoFifths: "\u2156",
threeQuarters: "\xBE",
threeFifths: "\u2157",
threeEighths: "\u215C",
fourFifths: "\u2158",
fiveSixths: "\u215A",
fiveEighths: "\u215D",
sevenEighths: "\u215E",
line: "\u2500",
lineBold: "\u2501",
lineDouble: "\u2550",
lineDashed0: "\u2504",
lineDashed1: "\u2505",
lineDashed2: "\u2508",
lineDashed3: "\u2509",
lineDashed4: "\u254C",
lineDashed5: "\u254D",
lineDashed6: "\u2574",
lineDashed7: "\u2576",
lineDashed8: "\u2578",
lineDashed9: "\u257A",
lineDashed10: "\u257C",
lineDashed11: "\u257E",
lineDashed12: "\u2212",
lineDashed13: "\u2013",
lineDashed14: "\u2010",
lineDashed15: "\u2043",
lineVertical: "\u2502",
lineVerticalBold: "\u2503",
lineVerticalDouble: "\u2551",
lineVerticalDashed0: "\u2506",
lineVerticalDashed1: "\u2507",
lineVerticalDashed2: "\u250A",
lineVerticalDashed3: "\u250B",
lineVerticalDashed4: "\u254E",
lineVerticalDashed5: "\u254F",
lineVerticalDashed6: "\u2575",
lineVerticalDashed7: "\u2577",
lineVerticalDashed8: "\u2579",
lineVerticalDashed9: "\u257B",
lineVerticalDashed10: "\u257D",
lineVerticalDashed11: "\u257F",
lineDownLeft: "\u2510",
lineDownLeftArc: "\u256E",
lineDownBoldLeftBold: "\u2513",
lineDownBoldLeft: "\u2512",
lineDownLeftBold: "\u2511",
lineDownDoubleLeftDouble: "\u2557",
lineDownDoubleLeft: "\u2556",
lineDownLeftDouble: "\u2555",
lineDownRight: "\u250C",
lineDownRightArc: "\u256D",
lineDownBoldRightBold: "\u250F",
lineDownBoldRight: "\u250E",
lineDownRightBold: "\u250D",
lineDownDoubleRightDouble: "\u2554",
lineDownDoubleRight: "\u2553",
lineDownRightDouble: "\u2552",
lineUpLeft: "\u2518",
lineUpLeftArc: "\u256F",
lineUpBoldLeftBold: "\u251B",
lineUpBoldLeft: "\u251A",
lineUpLeftBold: "\u2519",
lineUpDoubleLeftDouble: "\u255D",
lineUpDoubleLeft: "\u255C",
lineUpLeftDouble: "\u255B",
lineUpRight: "\u2514",
lineUpRightArc: "\u2570",
lineUpBoldRightBold: "\u2517",
lineUpBoldRight: "\u2516",
lineUpRightBold: "\u2515",
lineUpDoubleRightDouble: "\u255A",
lineUpDoubleRight: "\u2559",
lineUpRightDouble: "\u2558",
lineUpDownLeft: "\u2524",
lineUpBoldDownBoldLeftBold: "\u252B",
lineUpBoldDownBoldLeft: "\u2528",
lineUpDownLeftBold: "\u2525",
lineUpBoldDownLeftBold: "\u2529",
lineUpDownBoldLeftBold: "\u252A",
lineUpDownBoldLeft: "\u2527",
lineUpBoldDownLeft: "\u2526",
lineUpDoubleDownDoubleLeftDouble: "\u2563",
lineUpDoubleDownDoubleLeft: "\u2562",
lineUpDownLeftDouble: "\u2561",
lineUpDownRight: "\u251C",
lineUpBoldDownBoldRightBold: "\u2523",
lineUpBoldDownBoldRight: "\u2520",
lineUpDownRightBold: "\u251D",
lineUpBoldDownRightBold: "\u2521",
lineUpDownBoldRightBold: "\u2522",
lineUpDownBoldRight: "\u251F",
lineUpBoldDownRight: "\u251E",
lineUpDoubleDownDoubleRightDouble: "\u2560",
lineUpDoubleDownDoubleRight: "\u255F",
lineUpDownRightDouble: "\u255E",
lineDownLeftRight: "\u252C",
lineDownBoldLeftBoldRightBold: "\u2533",
lineDownLeftBoldRightBold: "\u252F",
lineDownBoldLeftRight: "\u2530",
lineDownBoldLeftBoldRight: "\u2531",
lineDownBoldLeftRightBold: "\u2532",
lineDownLeftRightBold: "\u252E",
lineDownLeftBoldRight: "\u252D",
lineDownDoubleLeftDoubleRightDouble: "\u2566",
lineDownDoubleLeftRight: "\u2565",
lineDownLeftDoubleRightDouble: "\u2564",
lineUpLeftRight: "\u2534",
lineUpBoldLeftBoldRightBold: "\u253B",
lineUpLeftBoldRightBold: "\u2537",
lineUpBoldLeftRight: "\u2538",
lineUpBoldLeftBoldRight: "\u2539",
lineUpBoldLeftRightBold: "\u253A",
lineUpLeftRightBold: "\u2536",
lineUpLeftBoldRight: "\u2535",
lineUpDoubleLeftDoubleRightDouble: "\u2569",
lineUpDoubleLeftRight: "\u2568",
lineUpLeftDoubleRightDouble: "\u2567",
lineUpDownLeftRight: "\u253C",
lineUpBoldDownBoldLeftBoldRightBold: "\u254B",
lineUpDownBoldLeftBoldRightBold: "\u2548",
lineUpBoldDownLeftBoldRightBold: "\u2547",
lineUpBoldDownBoldLeftRightBold: "\u254A",
lineUpBoldDownBoldLeftBoldRight: "\u2549",
lineUpBoldDownLeftRight: "\u2540",
lineUpDownBoldLeftRight: "\u2541",
lineUpDownLeftBoldRight: "\u253D",
lineUpDownLeftRightBold: "\u253E",
lineUpBoldDownBoldLeftRight: "\u2542",
lineUpDownLeftBoldRightBold: "\u253F",
lineUpBoldDownLeftBoldRight: "\u2543",
lineUpBoldDownLeftRightBold: "\u2544",
lineUpDownBoldLeftBoldRight: "\u2545",
lineUpDownBoldLeftRightBold: "\u2546",
lineUpDoubleDownDoubleLeftDoubleRightDouble: "\u256C",
lineUpDoubleDownDoubleLeftRight: "\u256B",
lineUpDownLeftDoubleRightDouble: "\u256A",
lineCross: "\u2573",
lineBackslash: "\u2572",
lineSlash: "\u2571"
}, specialMainSymbols = {
tick: "\u2714",
info: "\u2139",
warning: "\u26A0",
cross: "\u2718",
squareSmall: "\u25FB",
squareSmallFilled: "\u25FC",
circle: "\u25EF",
circleFilled: "\u25C9",
circleDotted: "\u25CC",
circleDouble: "\u25CE",
circleCircle: "\u24DE",
circleCross: "\u24E7",
circlePipe: "\u24BE",
radioOn: "\u25C9",
radioOff: "\u25EF",
checkboxOn: "\u2612",
checkboxOff: "\u2610",
checkboxCircleOn: "\u24E7",
checkboxCircleOff: "\u24BE",
pointer: "\u276F",
triangleUpOutline: "\u25B3",
triangleLeft: "\u25C0",
triangleRight: "\u25B6",
lozenge: "\u25C6",
lozengeOutline: "\u25C7",
hamburger: "\u2630",
smiley: "\u32E1",
mustache: "\u0DF4",
star: "\u2605",
play: "\u25B6",
nodejs: "\u2B22",
oneSeventh: "\u2150",
oneNinth: "\u2151",
oneTenth: "\u2152"
}, specialFallbackSymbols = {
tick: "\u221A",
info: "i",
warning: "\u203C",
cross: "\xD7",
squareSmall: "\u25A1",
squareSmallFilled: "\u25A0",
circle: "( )",
circleFilled: "(*)",
circleDotted: "( )",
circleDouble: "( )",
circleCircle: "(\u25CB)",
circleCross: "(\xD7)",
circlePipe: "(\u2502)",
radioOn: "(*)",
radioOff: "( )",
checkboxOn: "[\xD7]",
checkboxOff: "[ ]",
checkboxCircleOn: "(\xD7)",
checkboxCircleOff: "( )",
pointer: ">",
triangleUpOutline: "\u2206",
triangleLeft: "\u25C4",
triangleRight: "\u25BA",
lozenge: "\u2666",
lozengeOutline: "\u25CA",
hamburger: "\u2261",
smiley: "\u263A",
mustache: "\u250C\u2500\u2510",
star: "\u2736",
play: "\u25BA",
nodejs: "\u2666",
oneSeventh: "1/7",
oneNinth: "1/9",
oneTenth: "1/10"
}, mainSymbols = { ...common, ...specialMainSymbols }, fallbackSymbols = { ...common, ...specialFallbackSymbols }, shouldUseMain = isUnicodeSupported(), figures = shouldUseMain ? mainSymbols : fallbackSymbols, figures_default = figures, replacements = Object.entries(specialMainSymbols);
// ../../node_modules/yoctocolors/base.js
import tty from "node:tty";
var hasColors = tty?.WriteStream?.prototype?.hasColors?.() ?? !1, format = (open, close) => {
if (!hasColors)
return (input) => input;
let openCode = `\x1B[${open}m`, closeCode = `\x1B[${close}m`;
return (input) => {
let string = input + "", index = string.indexOf(closeCode);
if (index === -1)
return openCode + string + closeCode;
let result = openCode, lastIndex = 0, replaceCode = (close === 22 ? closeCode : "") + openCode;
for (; index !== -1; )
result += string.slice(lastIndex, index) + replaceCode, lastIndex = index + closeCode.length, index = string.indexOf(closeCode, lastIndex);
return result += string.slice(lastIndex) + closeCode, result;
};
}, reset = format(0, 0), bold = format(1, 22), dim = format(2, 22), italic = format(3, 23), underline = format(4, 24), overline = format(53, 55), inverse = format(7, 27), hidden = format(8, 28), strikethrough = format(9, 29), black = format(30, 39), red = format(31, 39), green = format(32, 39), yellow = format(33, 39), blue = format(34, 39), magenta = format(35, 39), cyan = format(36, 39), white = format(37, 39), gray = format(90, 39), bgBlack = format(40, 49), bgRed = format(41, 49), bgGreen = format(42, 49), bgYellow = format(43, 49), bgBlue = format(44, 49), bgMagenta = format(45, 49), bgCyan = format(46, 49), bgWhite = format(47, 49), bgGray = format(100, 49), redBright = format(91, 39), greenBright = format(92, 39), yellowBright = format(93, 39), blueBright = format(94, 39), magentaBright = format(95, 39), cyanBright = format(96, 39), whiteBright = format(97, 39), bgRedBright = format(101, 49), bgGreenBright = format(102, 49), bgYellowBright = format(103, 49), bgBlueBright = format(104, 49), bgMagentaBright = format(105, 49), bgCyanBright = format(106, 49), bgWhiteBright = format(107, 49);
// ../../node_modules/execa/lib/verbose/default.js
var defaultVerboseFunction = ({
type,
message,
timestamp,
piped,
commandId,
result: { failed = !1 } = {},
options: { reject = !0 }
}) => {
let timestampString = serializeTimestamp(timestamp), icon = ICONS[type]({ failed, reject, piped }), color = COLORS[type]({ reject });
return `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`;
}, serializeTimestamp = (timestamp) => `${padField(timestamp.getHours(), 2)}:${padField(timestamp.getMinutes(), 2)}:${padField(timestamp.getSeconds(), 2)}.${padField(timestamp.getMilliseconds(), 3)}`, padField = (field, padding) => String(field).padStart(padding, "0"), getFinalIcon = ({ failed, reject }) => failed ? reject ? figures_default.cross : figures_default.warning : figures_default.tick, ICONS = {
command: ({ piped }) => piped ? "|" : "$",
output: () => " ",
ipc: () => "*",
error: getFinalIcon,
duration: getFinalIcon
}, identity = (string) => string, COLORS = {
command: () => bold,
output: () => identity,
ipc: () => identity,
error: ({ reject }) => reject ? redBright : yellowBright,
duration: () => gray
};
// ../../node_modules/execa/lib/verbose/custom.js
var applyVerboseOnLines = (printedLines, verboseInfo, fdNumber) => {
let verboseFunction = getVerboseFunction(verboseInfo, fdNumber);
return printedLines.map(({ verboseLine, verboseObject }) => applyVerboseFunction(verboseLine, verboseObject, verboseFunction)).filter((printedLine) => printedLine !== void 0).map((printedLine) => appendNewline(printedLine)).join("");
}, applyVerboseFunction = (verboseLine, verboseObject, verboseFunction) => {
if (verboseFunction === void 0)
return verboseLine;
let printedLine = verboseFunction(verboseLine, verboseObject);
if (typeof printedLine == "string")
return printedLine;
}, appendNewline = (printedLine) => printedLine.endsWith(`
`) ? printedLine : `${printedLine}
`;
// ../../node_modules/execa/lib/verbose/log.js
var verboseLog = ({ type, verboseMessage, fdNumber, verboseInfo, result }) => {
let verboseObject = getVerboseObject({ type, result, verboseInfo }), printedLines = getPrintedLines(verboseMessage, verboseObject), finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);
finalLines !== "" && console.warn(finalLines.slice(0, -1));
}, getVerboseObject = ({
type,
result,
verboseInfo: { escapedCommand, commandId, rawOptions: { piped = !1, ...options } }
}) => ({
type,
escapedCommand,
commandId: `${commandId}`,
timestamp: /* @__PURE__ */ new Date(),
piped,
result,
options
}), getPrintedLines = (verboseMessage, verboseObject) => verboseMessage.split(`
`).map((message) => getPrintedLine({ ...verboseObject, message })), getPrintedLine = (verboseObject) => ({ verboseLine: defaultVerboseFunction(verboseObject), verboseObject }), serializeVerboseMessage = (message) => {
let messageString = typeof message == "string" ? message : inspect(message);
return escapeLines(messageString).replaceAll(" ", " ".repeat(TAB_SIZE));
}, TAB_SIZE = 2;
// ../../node_modules/execa/lib/verbose/start.js
var logCommand = (escapedCommand, verboseInfo) => {
isVerbose(verboseInfo) && verboseLog({
type: "command",
verboseMessage: escapedCommand,
verboseInfo
});
};
// ../../node_modules/execa/lib/verbose/info.js
var getVerboseInfo = (verbose, escapedCommand, rawOptions) => {
validateVerbose(verbose);
let commandId = getCommandId(verbose);
return {
verbose,
escapedCommand,
commandId,
rawOptions
};
}, getCommandId = (verbose) => isVerbose({ verbose }) ? COMMAND_ID++ : void 0, COMMAND_ID = 0n, validateVerbose = (verbose) => {
for (let fdVerbose of verbose) {
if (fdVerbose === !1)
throw new TypeError(`The "verbose: false" option was renamed to "verbose: 'none'".`);
if (fdVerbose === !0)
throw new TypeError(`The "verbose: true" option was renamed to "verbose: 'short'".`);
if (!VERBOSE_VALUES.includes(fdVerbose) && !isVerboseFunction(fdVerbose)) {
let allowedValues = VERBOSE_VALUES.map((allowedValue) => `'${allowedValue}'`).join(", ");
throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues} or a function.`);
}
}
};
// ../../node_modules/execa/lib/return/duration.js
import { hrtime } from "node:process";
var getStartTime = () => hrtime.bigint(), getDurationMs = (startTime) => Number(hrtime.bigint() - startTime) / 1e6;
// ../../node_modules/execa/lib/arguments/command.js
var handleCommand = (filePath, rawArguments, rawOptions) => {
let startTime = getStartTime(), { command, escapedCommand } = joinCommand(filePath, rawArguments), verbose = normalizeFdSpecificOption(rawOptions, "verbose"), verboseInfo = getVerboseInfo(verbose, escapedCommand, { ...rawOptions });
return logCommand(escapedCommand, verboseInfo), {
command,
escapedCommand,
startTime,
verboseInfo
};
};
// ../../node_modules/execa/lib/arguments/options.js
var import_cross_spawn = __toESM(require_cross_spawn(), 1);
import path4 from "node:path";
import process6 from "node:process";
// ../../node_modules/execa/node_modules/npm-run-path/index.js
import process4 from "node:process";
import path from "node:path";
// ../../node_modules/execa/node_modules/path-key/index.js
function pathKey(options = {}) {
let {
env = process.env,
platform: platform2 = process.platform
} = options;
return platform2 !== "win32" ? "PATH" : Object.keys(env).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
}
// ../../node_modules/execa/node_modules/npm-run-path/index.js
var npmRunPath = ({
cwd = process4.cwd(),
path: pathOption = process4.env[pathKey()],
preferLocal = !0,
execPath: execPath2 = process4.execPath,
addExecPath = !0
} = {}) => {
let cwdPath = path.resolve(toPath(cwd)), result = [], pathParts = pathOption.split(path.delimiter);
return preferLocal && applyPreferLocal(result, pathParts, cwdPath), addExecPath && applyExecPath(result, pathParts, execPath2, cwdPath), pathOption === "" || pathOption === path.delimiter ? `${result.join(path.delimiter)}${pathOption}` : [...result, pathOption].join(path.delimiter);
}, applyPreferLocal = (result, pathParts, cwdPath) => {
for (let directory of traversePathUp(cwdPath)) {
let pathPart = path.join(directory, "node_modules/.bin");
pathParts.includes(pathPart) || result.push(pathPart);
}
}, applyExecPath = (result, pathParts, execPath2, cwdPath) => {
let pathPart = path.resolve(cwdPath, toPath(execPath2), "..");
pathParts.includes(pathPart) || result.push(pathPart);
}, npmRunPathEnv = ({ env = process4.env, ...options } = {}) => {
env = { ...env };
let pathName = pathKey({ env });
return options.path = env[pathName], env[pathName] = npmRunPath(options), env;
};
// ../../node_modules/execa/lib/terminate/kill.js
import { setTimeout } from "node:timers/promises";
// ../../node_modules/execa/lib/return/final-error.js
var getFinalError = (originalError, message, isSync) => {
let ErrorClass = isSync ? ExecaSyncError : ExecaError, options = originalError instanceof DiscardedError ? {} : { cause: originalError };
return new ErrorClass(message, options);
}, DiscardedError = class extends Error {
}, setErrorName = (ErrorClass, value) => {
Object.defineProperty(ErrorClass.prototype, "name", {
value,
writable: !0,
enumerable: !1,
configurable: !0
}), Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, {
value: !0,
writable: !1,
enumerable: !1,
configurable: !1
});
}, isExecaError = (error) => isErrorInstance(error) && execaErrorSymbol in error, execaErrorSymbol = /* @__PURE__ */ Symbol("isExecaError"), isErrorInstance = (value) => Object.prototype.toString.call(value) === "[object Error]", ExecaError = class extends Error {
};
setErrorName(ExecaError, ExecaError.name);
var ExecaSyncError = class extends Error {
};
setErrorName(ExecaSyncError, ExecaSyncError.name);
// ../../node_modules/execa/lib/terminate/signal.js
import { constants as constants3 } from "node:os";
// ../../node_modules/human-signals/build/src/main.js
import { constants as constants2 } from "node:os";
// ../../node_modules/human-signals/build/src/realtime.js
var getRealtimeSignals = () => {
let length = SIGRTMAX - SIGRTMIN + 1;
return Array.from({ length }, getRealtimeSignal);
}, getRealtimeSignal = (value, index) => ({
name: `SIGRT${index + 1}`,
number: SIGRTMIN + index,
action: "terminate",
description: "Application-specific signal (realtime)",
standard: "posix"
}), SIGRTMIN = 34, SIGRTMAX = 64;
// ../../node_modules/human-signals/build/src/signals.js
import { constants } from "node:os";
// ../../node_modules/human-signals/build/src/core.js
var SIGNALS = [
{
name: "SIGHUP",
number: 1,
action: "terminate",
description: "Terminal closed",
standard: "posix"
},
{
name: "SIGINT",
number: 2,
action: "terminate",
description: "User interruption with CTRL-C",
standard: "ansi"
},
{
name: "SIGQUIT",
number: 3,
action: "core",
description: "User interruption with CTRL-\\",
standard: "posix"
},
{
name: "SIGILL",
number: 4,
action: "core",
description: "Invalid machine instruction",
standard: "ansi"
},
{
name: "SIGTRAP",
number: 5,
action: "core",
description: "Debugger breakpoint",
standard: "posix"
},
{
name: "SIGABRT",
number: 6,
action: "core",
description: "Aborted",
standard: "ansi"
},
{
name: "SIGIOT",
number: 6,
action: "core",
description: "Aborted",
standard: "bsd"
},
{
name: "SIGBUS",
number: 7,
action: "core",
description: "Bus error due to misaligned, non-existing address or paging error",
standard: "bsd"
},
{
name: "SIGEMT",
number: 7,
action: "terminate",
description: "Command should be emulated but is not implemented",
standard: "other"
},
{
name: "SIGFPE",
number: 8,
action: "core",
description: "Floating point arithmetic error",
standard: "ansi"
},
{
name: "SIGKILL",
number: 9,
action: "terminate",
description: "Forced termination",
standard: "posix",
forced: !0
},
{
name: "SIGUSR1",
number: 10,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGSEGV",
number: 11,
action: "core",
description: "Segmentation fault",
standard: "ansi"
},
{
name: "SIGUSR2",
number: 12,
action: "terminate",
description: "Application-specific signal",
standard: "posix"
},
{
name: "SIGPIPE",
number: 13,
action: "terminate",
description: "Broken pipe or socket",
standard: "posix"
},
{
name: "SIGALRM",
number: 14,
action: "terminate",
description: "Timeout or timer",
standard: "posix"
},
{
name: "SIGTERM",
number: 15,
action: "terminate",
description: "Termination",
standard: "ansi"
},
{
name: "SIGSTKFLT",
number: 16,
action: "terminate",
description: "Stack is empty or overflowed",
standard: "other"
},
{
name: "SIGCHLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "posix"
},
{
name: "SIGCLD",
number: 17,
action: "ignore",
description: "Child process terminated, paused or unpaused",
standard: "other"
},
{
name: "SIGCONT",
number: 18,
action: "unpause",
description: "Unpaused",
standard: "posix",
forced: !0
},
{
name: "SIGSTOP",
number: 19,
action: "pause",
description: "Paused",
standard: "posix",
forced: !0
},
{
name: "SIGTSTP",
number: 20,
action: "pause",
description: 'Paused using CTRL-Z or "suspend"',
standard: "posix"
},
{
name: "SIGTTIN",
number: 21,
action: "pause",
description: "Background process cannot read terminal input",
standard: "posix"
},
{
name: "SIGBREAK",
number: 21,
action: "terminate",
description: "User interruption with CTRL-BREAK",
standard: "other"
},
{
name: "SIGTTOU",
number: 22,
action: "pause",
description: "Background process cannot write to terminal output",
standard: "posix"
},
{
name: "SIGURG",
number: 23,
action: "ignore",
description: "Socket received out-of-band data",
standard: "bsd"
},
{
name: "SIGXCPU",
number: 24,
action: "core",
description: "Process timed out",
standard: "bsd"
},
{
name: "SIGXFSZ",
number: 25,
action: "core",
description: "File too big",
standard: "bsd"
},
{
name: "SIGVTALRM",
number: 26,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGPROF",
number: 27,
action: "terminate",
description: "Timeout or timer",
standard: "bsd"
},
{
name: "SIGWINCH",
number: 28,
action: "ignore",
description: "Terminal window size changed",
standard: "bsd"
},
{
name: "SIGIO",
number: 29,
action: "terminate",
description: "I/O is available",
standard: "other"
},
{
name: "SIGPOLL",
number: 29,
action: "terminate",
description: "Watched event",
standard: "other"
},
{
name: "SIGINFO",
number: 29,
action: "ignore",
description: "Request for process information",
standard: "other"
},
{
name: "SIGPWR",
number: 30,
action: "terminate",
description: "Device running out of power",
standard: "systemv"
},
{
name: "SIGSYS",
number: 31,
action: "core",
description: "Invalid system call",
standard: "other"
},
{
name: "SIGUNUSED",
number: 31,
action: "terminate",
description: "Invalid system call",
standard: "other"
}
];
// ../../node_modules/human-signals/build/src/signals.js
var getSignals = () => {
let realtimeSignals = getRealtimeSignals();
return [...SIGNALS, ...realtimeSignals].map(normalizeSignal);
}, normalizeSignal = ({
name,
number: defaultNumber,
description,
action,
forced = !1,
standard
}) => {
let {
signals: { [name]: constantSignal }
} = constants, supported = constantSignal !== void 0;
return { name, number: supported ? constantSignal : defaultNumber, description, supported, action, forced, standard };
};
// ../../node_modules/human-signals/build/src/main.js
var getSignalsByName = () => {
let signals2 = getSignals();
return Object.fromEntries(signals2.map(getSignalByName));
}, getSignalByName = ({
name,
number,
description,
supported,
action,
forced,
standard
}) => [name, { name, number, description, supported, action, forced, standard }], signalsByName = getSignalsByName(), getSignalsByNumber = () => {
let signals2 = getSignals(), length = 65, signalsA = Array.from(
{ length },
(value, number) => getSignalByNumber(number, signals2)
);
return Object.assign({}, ...signalsA);
}, getSignalByNumber = (number, signals2) => {
let signal = findSignalByNumber(number, signals2);
if (signal === void 0)
return {};
let { name, description, supported, action, forced, standard } = signal;
return {
[number]: {
name,
number,
description,
supported,
action,
forced,
standard
}
};
}, findSignalByNumber = (number, signals2) => {
let signal = signals2.find(({ name }) => constants2.signals[name] === number);
return signal !== void 0 ? signal : signals2.find((signalA) => signalA.number === number);
}, signalsByNumber = getSignalsByNumber();
// ../../node_modules/execa/lib/terminate/signal.js
var normalizeKillSignal = (killSignal) => {
let optionName = "option `killSignal`";
if (killSignal === 0)
throw new TypeError(`Invalid ${optionName}: 0 cannot be used.`);
return normalizeSignal2(killSignal, optionName);
}, normalizeSignalArgument = (signal) => signal === 0 ? signal : normalizeSignal2(signal, "`subprocess.kill()`'s argument"), normalizeSignal2 = (signalNameOrInteger, optionName) => {
if (Number.isInteger(signalNameOrInteger))
return normalizeSignalInteger(signalNameOrInteger, optionName);
if (typeof signalNameOrInteger == "string")
return normalizeSignalName(signalNameOrInteger, optionName);
throw new TypeError(`Invalid ${optionName} ${String(signalNameOrInteger)}: it must be a string or an integer.
${getAvailableSignals()}`);
}, normalizeSignalInteger = (signalInteger, optionName) => {
if (signalsIntegerToName.has(signalInteger))
return signalsIntegerToName.get(signalInteger);
throw new TypeError(`Invalid ${optionName} ${signalInteger}: this signal integer does not exist.
${getAvailableSignals()}`);
}, getSignalsIntegerToName = () => new Map(Object.entries(constants3.signals).reverse().map(([signalName, signalInteger]) => [signalInteger, signalName])), signalsIntegerToName = getSignalsIntegerToName(), normalizeSignalName = (signalName, optionName) => {
if (signalName in constants3.signals)
return signalName;
throw signalName.toUpperCase() in constants3.signals ? new TypeError(`Invalid ${optionName} '${signalName}': please rename it to '${signalName.toUpperCase()}'.`) : new TypeError(`Invalid ${optionName} '${signalName}': this signal name does not exist.
${getAvailableSignals()}`);
}, getAvailableSignals = () => `Available signal names: ${getAvailableSignalNames()}.
Available signal numbers: ${getAvailableSignalIntegers()}.`, getAvailableSignalNames = () => Object.keys(constants3.signals).sort().map((signalName) => `'${signalName}'`).join(", "), getAvailableSignalIntegers = () => [...new Set(Object.values(constants3.signals).sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))].join(", "), getSignalDescription = (signal) => signalsByName[signal].description;
// ../../node_modules/execa/lib/terminate/kill.js
var normalizeForceKillAfterDelay = (forceKillAfterDelay) => {
if (forceKillAfterDelay === !1)
return forceKillAfterDelay;
if (forceKillAfterDelay === !0)
return DEFAULT_FORCE_KILL_TIMEOUT;
if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0)
throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);
return forceKillAfterDelay;
}, DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5, subprocessKill = ({ kill, options: { forceKillAfterDelay, killSignal }, onInternalError, context, controller }, signalOrError, errorArgument) => {
let { signal, error } = parseKillArguments(signalOrError, errorArgument, killSignal);
emitKillError(error, onInternalError);
let killResult = kill(signal);
return setKillTimeout({
kill,
signal,
forceKillAfterDelay,
killSignal,
killResult,
context,
controller
}), killResult;
}, parseKillArguments = (signalOrError, errorArgument, killSignal) => {
let [signal = killSignal, error] = isErrorInstance(signalOrError) ? [void 0, signalOrError] : [signalOrError, errorArgument];
if (typeof signal != "string" && !Number.isInteger(signal))
throw new TypeError(`The first argument must be an error instance or a signal name string/integer: ${String(signal)}`);
if (error !== void 0 && !isErrorInstance(error))
throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);
return { signal: normalizeSignalArgument(signal), error };
}, emitKillError = (error, onInternalError) => {
error !== void 0 && onInternalError.reject(error);
}, setKillTimeout = async ({ kill, signal, forceKillAfterDelay, killSignal, killResult, context, controller }) => {
signal === killSignal && killResult && killOnTimeout({
kill,
forceKillAfterDelay,
context,
controllerSignal: controller.signal
});
}, killOnTimeout = async ({ kill, forceKillAfterDelay, context, controllerSignal }) => {
if (forceKillAfterDelay !== !1)
try {
await setTimeout(forceKillAfterDelay, void 0, { signal: controllerSignal }), kill("SIGKILL") && (context.isForcefullyTerminated ??= !0);
} catch {
}
};
// ../../node_modules/execa/lib/utils/abort-signal.js
import { once as once2 } from "node:events";
var onAbortedSignal = async (mainSignal, stopSignal) => {
mainSignal.aborted || await once2(mainSignal, "abort", { signal: stopSignal });
};
// ../../node_modules/execa/lib/terminate/cancel.js
var validateCancelSignal = ({ cancelSignal }) => {
if (cancelSignal !== void 0 && Object.prototype.toString.call(cancelSignal) !== "[object AbortSignal]")
throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`);
}, throwOnCancel = ({ subprocess, cancelSignal, gracefulCancel, context, controller }) => cancelSignal === void 0 || gracefulCancel ? [] : [terminateOnCancel(subprocess, cancelSignal, context, controller)], terminateOnCancel = async (subprocess, cancelSignal, context, { signal }) => {
throw await onAbortedSignal(cancelSignal, signal), context.terminationReason ??= "cancel", subprocess.kill(), cancelSignal.reason;
};
// ../../node_modules/execa/lib/ipc/graceful.js
import { scheduler as scheduler2 } from "node:timers/promises";
// ../../node_modules/execa/lib/ipc/send.js
import { promisify } from "node:util";
// ../../node_modules/execa/lib/ipc/validation.js
var validateIpcMethod = ({ methodName, isSubprocess, ipc, isConnected: isConnected2 }) => {
validateIpcOption(methodName, isSubprocess, ipc), validateConnection(methodName, isSubprocess, isConnected2);
}, validateIpcOption = (methodName, isSubprocess, ipc) => {
if (!ipc)
throw new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \`ipc\` option is \`true\`.`);
}, validateConnection = (methodName, isSubprocess, isConnected2) => {
if (!isConnected2)
throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);
}, throwOnEarlyDisconnect = (isSubprocess) => {
throw new Error(`${getMethodName("getOneMessage", isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);
}, throwOnStrictDeadlockError = (isSubprocess) => {
throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.
This can be fixed by both sending a message and listening to incoming messages at the same time:
const [receivedMessage] = await Promise.all([
${getMethodName("getOneMessage", isSubprocess)},
${getMethodName("sendMessage", isSubprocess, "message, {strict: true}")},
]);`);
}, getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName("sendMessage", isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, { cause: error }), throwOnMissingStrict = (isSubprocess) => {
throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);
}, throwOnStrictDisconnect = (isSubprocess) => {
throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);
}, getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(!0)} disconnected.`), throwOnMissingParent = () => {
throw new Error("`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.");
}, handleEpipeError = ({ error, methodName, isSubprocess }) => {
if (error.code === "EPIPE")
throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, { cause: error });
}, handleSerializationError = ({ error, methodName, isSubprocess, message }) => {
if (isSerializationError(error))
throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, { cause: error });
}, isSerializationError = ({ code, message }) => SERIALIZATION_ERROR_CODES.has(code) || SERIALIZATION_ERROR_MESSAGES.some((serializationErrorMessage) => message.includes(serializationErrorMessage)), SERIALIZATION_ERROR_CODES = /* @__PURE__ */ new Set([
// Message is `undefined`
"ERR_MISSING_ARGS",
// Message is a function, a bigint, a symbol
"ERR_INVALID_ARG_TYPE"
]), SERIALIZATION_ERROR_MESSAGES = [
// Message is a promise or a proxy, with `serialization: 'advanced'`
"could not be cloned",
// Message has cycles, with `serialization: 'json'`
"circular structure",
// Message has cycles inside toJSON(), with `serialization: 'json'`
"call stack size exceeded"
], getMethodName = (methodName, isSubprocess, parameters = "") => methodName === "cancelSignal" ? "`cancelSignal`'s `controller.abort()`" : `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`, getNamespaceName = (isSubprocess) => isSubprocess ? "" : "subprocess.", getOtherProcessName = (isSubprocess) => isSubprocess ? "parent process" : "subprocess", disconnect = (anyProcess) => {
anyProcess.connected && anyProcess.disconnect();
};
// ../../node_modules/execa/lib/utils/deferred.js
var createDeferred = () => {
let methods = {}, promise2 = new Promise((resolve4, reject) => {
Object.assign(methods, { resolve: resolve4, reject });
});
return Object.assign(promise2, methods);
};
// ../../node_modules/execa/lib/arguments/fd-options.js
var getToStream = (destination, to = "stdin") => {
let { options, fileDescriptors } = SUBPROCESS_OPTIONS.get(destination), fdNumber = getFdNumber(fileDescriptors, to, !0), destinationStream = destination.stdio[fdNumber];
if (destinationStream === null)
throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, !0));
return destinationStream;
}, getFromStream = (source, from = "stdout") => {
let { options, fileDescriptors } = SUBPROCESS_OPTIONS.get(source), fdNumber = getFdNumber(fileDescriptors, from, !1), sourceStream = fdNumber === "all" ? source.all : source.stdio[fdNumber];
if (sourceStream == null)
throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, !1));
return sourceStream;
}, SUBPROCESS_OPTIONS = /* @__PURE__ */ new WeakMap(), getFdNumber = (fileDescriptors, fdName, isWritable) => {
let fdNumber = parseFdNumber(fdName, isWritable);
return validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors), fdNumber;
}, parseFdNumber = (fdName, isWritable) => {
let fdNumber = parseFd(fdName);
if (fdNumber !== void 0)
return fdNumber;
let { validOptions, defaultValue } = isWritable ? { validOptions: '"stdin"', defaultValue: "stdin" } : { validOptions: '"stdout", "stderr", "all"', defaultValue: "stdout" };
throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".
It must be ${validOptions} or "fd3", "fd4" (and so on).
It is optional and defaults to "${defaultValue}".`);
}, validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {
let fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];
if (fileDescriptor === void 0)
throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.
Please set the "stdio" option to ensure that file descriptor exists.`);
if (fileDescriptor.direction === "input" && !isWritable)
throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);
if (fileDescriptor.direction !== "input" && isWritable)
throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);
}, getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {
if (fdNumber === "all" && !options.all)
return `The "all" option must be true to use "from: 'all'".`;
let { optionName, optionValue } = getInvalidStdioOption(fdNumber, options);
return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".
Please set this option with "pipe" instead.`;
}, getInvalidStdioOption = (fdNumber, { stdin, stdout, stderr, stdio }) => {
let usedDescriptor = getUsedDescriptor(fdNumber);
return usedDescriptor === 0 && stdin !== void 0 ? { optionName: "stdin", optionValue: stdin } : usedDescriptor === 1 && stdout !== void 0 ? { optionName: "stdout", optionValue: stdout } : usedDescriptor === 2 && stderr !== void 0 ? { optionName: "stderr", optionValue: stderr } : { optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor] };
}, getUsedDescriptor = (fdNumber) => fdNumber === "all" ? 1 : fdNumber, getOptionName = (isWritable) => isWritable ? "to" : "from", serializeOptionValue = (value) => typeof value == "string" ? `'${value}'` : typeof value == "number" ? `${value}` : "Stream";
// ../../node_modules/execa/lib/ipc/strict.js
import { once as once4 } from "node:events";
// ../../node_modules/execa/lib/utils/max-listeners.js
import { addAbortListener } from "node:events";
var incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {
let maxListeners = eventEmitter.getMaxListeners();
maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY || (eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement), addAbortListener(signal, () => {
eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);
}));
};
// ../../node_modules/execa/lib/ipc/forward.js
import { EventEmitter } from "node:events";
// ../../node_modules/execa/lib/ipc/incoming.js
import { once as once3 } from "node:events";
import { scheduler } from "node:timers/promises";
// ../../node_modules/execa/lib/ipc/reference.js
var addReference = (channel, reference) => {
reference && addReferenceCount(channel);
}, addReferenceCount = (channel) => {
channel.refCounted();
}, removeReference = (channel, reference) => {
reference && removeReferenceCount(channel);
}, removeReferenceCount = (channel) => {
channel.unrefCounted();
}, undoAddedReferences = (channel, isSubprocess) => {
isSubprocess && (removeReferenceCount(channel), removeReferenceCount(channel));
}, redoAddedReferences = (channel, isSubprocess) => {
isSubprocess && (addReferenceCount(channel), addReferenceCount(channel));
};
// ../../node_modules/execa/lib/ipc/incoming.js
var onMessage = async ({ anyProcess, channel, isSubprocess, ipcEmitter }, wrappedMessage) => {
if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage))
return;
INCOMING_MESSAGES.has(anyProcess) || INCOMING_MESSAGES.set(anyProcess, []);
let incomingMessages = INCOMING_MESSAGES.get(anyProcess);
if (incomingMessages.push(wrappedMessage), !(incomingMessages.length > 1))
for (; incomingMessages.length > 0; ) {
await waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage), await scheduler.yield();
let message = await handleStrictRequest({
wrappedMessage: incomingMessages[0],
anyProcess,
channel,
isSubprocess,
ipcEmitter
});
incomingMessages.shift(), ipcEmitter.emit("message", message), ipcEmitter.emit("message:done");
}
}, onDisconnect = async ({ anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage }) => {
abortOnDisconnect();
let incomingMessages = INCOMING_MESSAGES.get(anyProcess);
for (; incomingMessages?.length > 0; )
await once3(ipcEmitter, "message:done");
anyProcess.removeListener("message", boundOnMessage), redoAddedReferences(channel, isSubprocess), ipcEmitter.connected = !1, ipcEmitter.emit("disconnect");
}, INCOMING_MESSAGES = /* @__PURE__ */ new WeakMap();
// ../../node_modules/execa/lib/ipc/forward.js
var getIpcEmitter = (anyProcess, channel, isSubprocess) => {
if (IPC_EMITTERS.has(anyProcess))
return IPC_EMITTERS.get(anyProcess);
let ipcEmitter = new EventEmitter();
return ipcEmitter.connected = !0, IPC_EMITTERS.set(anyProcess, ipcEmitter), forwardEvents({
ipcEmitter,
anyProcess,
channel,
isSubprocess
}), ipcEmitter;
}, IPC_EMITTERS = /* @__PURE__ */ new WeakMap(), forwardEvents = ({ ipcEmitter, anyProcess, channel, isSubprocess }) => {
let boundOnMessage = onMessage.bind(void 0, {
anyProcess,
channel,
isSubprocess,
ipcEmitter
});
anyProcess.on("message", boundOnMessage), anyProcess.once("disconnect", onDisconnect.bind(void 0, {
anyProcess,
channel,
isSubprocess,
ipcEmitter,
boundOnMessage
})), undoAddedReferences(channel, isSubprocess);
}, isConnected = (anyProcess) => {
let ipcEmitter = IPC_EMITTERS.get(anyProcess);
return ipcEmitter === void 0 ? anyProcess.channel !== null : ipcEmitter.connected;
};
// ../../node_modules/execa/lib/ipc/strict.js
var handleSendStrict = ({ anyProcess, channel, isSubprocess, message, strict }) => {
if (!strict)
return message;
let ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess), hasListeners = hasMessageListeners(anyProcess, ipcEmitter);
return {
id: count++,
type: REQUEST_TYPE,
message,
hasListeners
};
}, count = 0n, validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {
if (!(wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners))
for (let { id } of outgoingMessages)
id !== void 0 && STRICT_RESPONSES[id].resolve({ isDeadlock: !0, hasListeners: !1 });
}, handleStrictRequest = async ({ wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter }) => {
if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected)
return wrappedMessage;
let { id, message } = wrappedMessage, response = { id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter) };
try {
await sendMessage({
anyProcess,
channel,
isSubprocess,
ipc: !0
}, response);
} catch (error) {
ipcEmitter.emit("strict:error", error);
}
return message;
}, handleStrictResponse = (wrappedMessage) => {
if (wrappedMessage?.type !== RESPONSE_TYPE)
return !1;
let { id, message: hasListeners } = wrappedMessage;
return STRICT_RESPONSES[id]?.resolve({ isDeadlock: !1, hasListeners }), !0;
}, waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {
if (wrappedMessage?.type !== REQUEST_TYPE)
return;
let deferred = createDeferred();
STRICT_RESPONSES[wrappedMessage.id] = deferred;
let controller = new AbortController();
try {
let { isDeadlock, hasListeners } = await Promise.race([
deferred,
throwOnDisconnect(anyProcess, isSubprocess, controller)
]);
isDeadlock && throwOnStrictDeadlockError(isSubprocess), hasListeners || throwOnMissingStrict(isSubprocess);
} finally {
controller.abort(), delete STRICT_RESPONSES[wrappedMessage.id];
}
}, STRICT_RESPONSES = {}, throwOnDisconnect = async (anyProcess, isSubprocess, { signal }) => {
incrementMaxListeners(anyProcess, 1, signal), await once4(anyProcess, "disconnect", { signal }), throwOnStrictDisconnect(isSubprocess);
}, REQUEST_TYPE = "execa:ipc:request", RESPONSE_TYPE = "execa:ipc:response";
// ../../node_modules/execa/lib/ipc/outgoing.js
var startSendMessage = (anyProcess, wrappedMessage, strict) => {
OUTGOING_MESSAGES.has(anyProcess) || OUTGOING_MESSAGES.set(anyProcess, /* @__PURE__ */ new Set());
let outgoingMessages = OUTGOING_MESSAGES.get(anyProcess), onMessageSent = createDeferred(), id = strict ? wrappedMessage.id : void 0, outgoingMessage = { onMessageSent, id };
return outgoingMessages.add(outgoingMessage), { outgoingMessages, outgoingMessage };
}, endSendMessage = ({ outgoingMessages, outgoingMessage }) => {
outgoingMessages.delete(outgoingMessage), outgoingMessage.onMessageSent.resolve();
}, waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => {
for (; !hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0; ) {
let outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)];
validateStrictDeadlock(outgoingMessages, wrappedMessage), await Promise.all(outgoingMessages.map(({ onMessageSent }) => onMessageSent));
}
}, OUTGOING_MESSAGES = /* @__PURE__ */ new WeakMap(), hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount("message") > getMinListenerCount(anyProcess), getMinListenerCount = (anyProcess) => SUBPROCESS_OPTIONS.has(anyProcess) && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, "ipc") ? 1 : 0;
// ../../node_modules/execa/lib/ipc/send.js
var sendMessage = ({ anyProcess, channel, isSubprocess, ipc }, message, { strict = !1 } = {}) => {
let methodName = "sendMessage";
return validateIpcMethod({
methodName,
isSubprocess,
ipc,
isConnected: anyProcess.connected
}), sendMessageAsync({
anyProcess,
channel,
methodName,
isSubprocess,
message,
strict
});
}, sendMessageAsync = async ({ anyProcess, channel, methodName, isSubprocess, message, strict }) => {
let wrappedMessage = handleSendStrict({
anyProcess,
channel,
isSubprocess,
message,
strict
}), outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);
try {
await sendOneMessage({
anyProcess,
methodName,
isSubprocess,
wrappedMessage,
message
});
} catch (error) {
throw disconnect(anyProcess), error;
} finally {
endSendMessage(outgoingMessagesState);
}
}, sendOneMessage = async ({ anyProcess, methodName, isSubprocess, wrappedMessage, message }) => {
let sendMethod = getSendMethod(anyProcess);
try {
await Promise.all([
waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),
sendMethod(wrappedMessage)
]);
} catch (error) {
throw handleEpipeError({ error, methodName, isSubprocess }), handleSerializationError({
error,
methodName,
isSubprocess,
message
}), error;
}
}, getSendMethod = (anyProcess) => {
if (PROCESS_SEND_METHODS.has(anyProcess))
return PROCESS_SEND_METHODS.get(anyProcess);
let sendMethod = promisify(anyProcess.send.bind(anyProcess));
return PROCESS_SEND_METHODS.set(anyProcess, sendMethod), sendMethod;
}, PROCESS_SEND_METHODS = /* @__PURE__ */ new WeakMap();
// ../../node_modules/execa/lib/ipc/graceful.js
var sendAbort = (subprocess, message) => {
let methodName = "cancelSignal";
return validateConnection(methodName, !1, subprocess.connected), sendOneMessage({
anyProcess: subprocess,
methodName,
isSubprocess: !1,
wrappedMessage: { type: GRACEFUL_CANCEL_TYPE, message },
message
});
}, getCancelSignal = async ({ anyProcess, channel, isSubprocess, ipc }) => (await startIpc({
anyProcess,
channel,
isSubprocess,
ipc
}), cancelController.signal), startIpc = async ({ anyProcess, channel, isSubprocess, ipc }) => {
if (!cancelListening) {
if (cancelListening = !0, !ipc) {
throwOnMissingParent();
return;
}
if (channel === null) {
abortOnDisconnect();
return;
}
getIpcEmitter(anyProcess, channel, isSubprocess), await scheduler2.yield();
}
}, cancelListening = !1, handleAbort = (wrappedMessage) => wrappedMessage?.type !== GRACEFUL_CANCEL_TYPE ? !1 : (cancelController.abort(wrappedMessage.message), !0), GRACEFUL_CANCEL_TYPE = "execa:ipc:cancel", abortOnDisconnect = () => {
cancelController.abort(getAbortDisconnectError());
}, cancelController = new AbortController();
// ../../node_modules/execa/lib/terminate/graceful.js
var validateGracefulCancel = ({ gracefulCancel, cancelSignal, ipc, serialization }) => {
if (gracefulCancel) {
if (cancelSignal === void 0)
throw new Error("The `cancelSignal` option must be defined when setting the `gracefulCancel` option.");
if (!ipc)
throw new Error("The `ipc` option cannot be false when setting the `gracefulCancel` option.");
if (serialization === "json")
throw new Error("The `serialization` option cannot be 'json' when setting the `gracefulCancel` option.");
}
}, throwOnGracefulCancel = ({
subprocess,
cancelSignal,
gracefulCancel,
forceKillAfterDelay,
context,
controller
}) => gracefulCancel ? [sendOnAbort({
subprocess,
cancelSignal,
forceKillAfterDelay,
context,
controller
})] : [], sendOnAbort = async ({ subprocess, cancelSignal, forceKillAfterDelay, context, controller: { signal } }) => {
await onAbortedSignal(cancelSignal, signal);
let reason = getReason(cancelSignal);
throw await sendAbort(subprocess, reason), killOnTimeout({
kill: subprocess.kill,
forceKillAfterDelay,
context,
controllerSignal: signal
}), context.terminationReason ??= "gracefulCancel", cancelSignal.reason;
}, getReason = ({ reason }) => {
if (!(reason instanceof DOMException))
return reason;
let error = new Error(reason.message);
return Object.defineProperty(error, "stack", {
value: reason.stack,
enumerable: !1,
configurable: !0,
writable: !0
}), error;
};
// ../../node_modules/execa/lib/terminate/timeout.js
import { setTimeout as setTimeout2 } from "node:timers/promises";
var validateTimeout = ({ timeout }) => {
if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout < 0))
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}, throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === void 0 ? [] : [killAfterTimeout(subprocess, timeout, context, controller)], killAfterTimeout = async (subprocess, timeout, context, { signal }) => {
throw await setTimeout2(timeout, void 0, { signal }), context.terminationReason ??= "timeout", subprocess.kill(), new DiscardedError();
};
// ../../node_modules/execa/lib/methods/node.js
import { execPath, execArgv } from "node:process";
import path2 from "node:path";
var mapNode = ({ options }) => {
if (options.node === !1)
throw new TypeError('The "node" option cannot be false with `execaNode()`.');
return { options: { ...options, node: !0 } };
}, handleNodeOption = (file, commandArguments, {
node: shouldHandleNode = !1,
nodePath = execPath,
nodeOptions = execArgv.filter((nodeOption) => !nodeOption.startsWith("--inspect")),
cwd,
execPath: formerNodePath,
...options
}) => {
if (formerNodePath !== void 0)
throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');
let normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option'), resolvedNodePath = path2.resolve(cwd, normalizedNodePath), newOptions = {
...options,
nodePath: resolvedNodePath,
node: shouldHandleNode,
cwd
};
if (!shouldHandleNode)
return [file, commandArguments, newOptions];
if (path2.basename(file, ".exe") === "node")
throw new TypeError('When the "node" option is true, the first argument does not need to be "node".');
return [
resolvedNodePath,
[...nodeOptions, file, ...commandArguments],
{ ipc: !0, ...newOptions, shell: !1 }
];
};
// ../../node_modules/execa/lib/ipc/ipc-input.js
import { serialize } from "node:v8";
var validateIpcInputOption = ({ ipcInput, ipc, serialization }) => {
if (ipcInput !== void 0) {
if (!ipc)
throw new Error("The `ipcInput` option cannot be set unless the `ipc` option is `true`.");
validateIpcInput[serialization](ipcInput);
}
}, validateAdvancedInput = (ipcInput) => {
try {
serialize(ipcInput);
} catch (error) {
throw new Error("The `ipcInput` option is not serializable with a structured clone.", { cause: error });
}
}, validateJsonInput = (ipcInput) => {
try {
JSON.stringify(ipcInput);
} catch (error) {
throw new Error("The `ipcInput` option is not serializable with JSON.", { cause: error });
}
}, validateIpcInput = {
advanced: validateAdvancedInput,
json: validateJsonInput
}, sendIpcInput = async (subprocess, ipcInput) => {
ipcInput !== void 0 && await subprocess.sendMessage(ipcInput);
};
// ../../node_modules/execa/lib/arguments/encoding-option.js
var validateEncoding = ({ encoding }) => {
if (ENCODINGS.has(encoding))
return;
let correctEncoding = getCorrectEncoding(encoding);
if (correctEncoding !== void 0)
throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.
Please rename it to ${serializeEncoding(correctEncoding)}.`);
let correctEncodings = [...ENCODINGS].map((correctEncoding2) => serializeEncoding(correctEncoding2)).join(", ");
throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.
Please rename it to one of: ${correctEncodings}.`);
}, TEXT_ENCODINGS = /* @__PURE__ */ new Set(["utf8", "utf16le"]), BINARY_ENCODINGS = /* @__PURE__ */ new Set(["buffer", "hex", "base64", "base64url", "latin1", "ascii"]), ENCODINGS = /* @__PURE__ */ new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]), getCorrectEncoding = (encoding) => {
if (encoding === null)
return "buffer";
if (typeof encoding != "string")
return;
let lowerEncoding = encoding.toLowerCase();
if (lowerEncoding in ENCODING_ALIASES)
return ENCODING_ALIASES[lowerEncoding];
if (ENCODINGS.has(lowerEncoding))
return lowerEncoding;
}, ENCODING_ALIASES = {
// eslint-disable-next-line unicorn/text-encoding-identifier-case
"utf-8": "utf8",
"utf-16le": "utf16le",
"ucs-2": "utf16le",
ucs2: "utf16le",
binary: "latin1"
}, serializeEncoding = (encoding) => typeof encoding == "string" ? `"${encoding}"` : String(encoding);
// ../../node_modules/execa/lib/arguments/cwd.js
import { statSync as statSync2 } from "node:fs";
import path3 from "node:path";
import process5 from "node:process";
var normalizeCwd = (cwd = getDefaultCwd()) => {
let cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option');
return path3.resolve(cwdString);
}, getDefaultCwd = () => {
try {
return process5.cwd();
} catch (error) {
throw error.message = `The current directory does not exist.
${error.message}`, error;
}
}, fixCwdError = (originalMessage, cwd) => {
if (cwd === getDefaultCwd())
return originalMessage;
let cwdStat;
try {
cwdStat = statSync2(cwd);
} catch (error) {
return `The "cwd" option is invalid: ${cwd}.
${error.message}
${originalMessage}`;
}
return cwdStat.isDirectory() ? originalMessage : `The "cwd" option is not a directory: ${cwd}.
${originalMessage}`;
};
// ../../node_modules/execa/lib/arguments/options.js
var normalizeOptions = (filePath, rawArguments, rawOptions) => {
rawOptions.cwd = normalizeCwd(rawOptions.cwd);
let [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions), { command: file, args: commandArguments, options: initialOptions } = import_cross_spawn.default._parse(processedFile, processedArguments, processedOptions), fdOptions = normalizeFdSpecificOptions(initialOptions), options = addDefaultOptions(fdOptions);
return validateTimeout(options), validateEncoding(options), validateIpcInputOption(options), validateCancelSignal(options), validateGracefulCancel(options), options.shell = normalizeFileUrl(options.shell), options.env = getEnv(options), options.killSignal = normalizeKillSignal(options.killSignal), options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay), options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]), process6.platform === "win32" && path4.basename(file, ".exe") === "cmd" && commandArguments.unshift("/q"), { file, commandArguments, options };
}, addDefaultOptions = ({
extendEnv = !0,
preferLocal = !1,
cwd,
localDir: localDirectory = cwd,
encoding = "utf8",
reject = !0,
cleanup = !0,
all = !1,
windowsHide = !0,
killSignal = "SIGTERM",
forceKillAfterDelay = !0,
gracefulCancel = !1,
ipcInput,
ipc = ipcInput !== void 0 || gracefulCancel,
serialization = "advanced",
...options
}) => ({
...options,
extendEnv,
preferLocal,
cwd,
localDirectory,
encoding,
reject,
cleanup,
all,
windowsHide,
killSignal,
forceKillAfterDelay,
gracefulCancel,
ipcInput,
ipc,
serialization
}), getEnv = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath }) => {
let env = extendEnv ? { ...process6.env, ...envOption } : envOption;
return preferLocal || node ? npmRunPathEnv({
env,
cwd: localDirectory,
execPath: nodePath,
preferLocal,
addExecPath: node
}) : env;
};
// ../../node_modules/execa/lib/arguments/shell.js
var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options];
// ../../node_modules/execa/lib/return/message.js
import { inspect as inspect2 } from "node:util";
// ../../node_modules/execa/node_modules/strip-final-newline/index.js
function stripFinalNewline(input) {
if (typeof input == "string")
return stripFinalNewlineString(input);
if (!(ArrayBuffer.isView(input) && input.BYTES_PER_ELEMENT === 1))
throw new Error("Input must be a string or a Uint8Array");
return stripFinalNewlineBinary(input);
}
var stripFinalNewlineString = (input) => input.at(-1) === LF ? input.slice(0, input.at(-2) === CR ? -2 : -1) : input, stripFinalNewlineBinary = (input) => input.at(-1) === LF_BINARY ? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1) : input, LF = `
`, LF_BINARY = LF.codePointAt(0), CR = "\r", CR_BINARY = CR.codePointAt(0);
// ../../node_modules/execa/node_modules/get-stream/source/index.js
import { on } from "node:events";
import { finished } from "node:stream/promises";
// ../../node_modules/execa/node_modules/is-stream/index.js
function isStream(stream, { checkOpen = !0 } = {}) {
return stream !== null && typeof stream == "object" && (stream.writable || stream.readable || !checkOpen || stream.writable === void 0 && stream.readable === void 0) && typeof stream.pipe == "function";
}
function isWritableStream(stream, { checkOpen = !0 } = {}) {
return isStream(stream, { checkOpen }) && (stream.writable || !checkOpen) && typeof stream.write == "function" && typeof stream.end == "function" && typeof stream.writable == "boolean" && typeof stream.writableObjectMode == "boolean" && typeof stream.destroy == "function" && typeof stream.destroyed == "boolean";
}
function isReadableStream(stream, { checkOpen = !0 } = {}) {
return isStream(stream, { checkOpen }) && (stream.readable || !checkOpen) && typeof stream.read == "function" && typeof stream.readable == "boolean" && typeof stream.readableObjectMode == "boolean" && typeof stream.destroy == "function" && typeof stream.destroyed == "boolean";
}
function isDuplexStream(stream, options) {
return isWritableStream(stream, options) && isReadableStream(stream, options);
}
// ../../node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js
var a = Object.getPrototypeOf(
Object.getPrototypeOf(
/* istanbul ignore next */
async function* () {
}
).prototype
), c = class {
#t;
#n;
#r = !1;
#e = void 0;
constructor(e, t) {
this.#t = e, this.#n = t;
}
next() {
let e = () => this.#s();
return this.#e = this.#e ? this.#e.then(e, e) : e(), this.#e;
}
return(e) {
let t = () => this.#i(e);
return this.#e ? this.#e.then(t, t) : t();
}
async #s() {
if (this.#r)
return {
done: !0,
value: void 0
};
let e;
try {
e = await this.#t.read();
} catch (t) {
throw this.#e = void 0, this.#r = !0, this.#t.releaseLock(), t;
}
return e.done && (this.#e = void 0, this.#r = !0, this.#t.releaseLock()), e;
}
async #i(e) {
if (this.#r)
return {
done: !0,
value: e
};
if (this.#r = !0, !this.#n) {
let t = this.#t.cancel(e);
return this.#t.releaseLock(), await t, {
done: !0,
value: e
};
}
return this.#t.releaseLock(), {
done: !0,
value: e
};
}
}, n = /* @__PURE__ */ Symbol();
function i() {
return this[n].next();
}
Object.defineProperty(i, "name", { value: "next" });
function o(r) {
return this[n].return(r);
}
Object.defineProperty(o, "name", { value: "return" });
var u = Object.create(a, {
next: {
enumerable: !0,
configurable: !0,
writable: !0,
value: i
},
return: {
enumerable: !0,
configurable: !0,
writable: !0,
value: o
}
});
function h({ preventCancel: r = !1 } = {}) {
let e = this.getReader(), t = new c(
e,
r
), s = Object.create(u);
return s[n] = t, s;
}
// ../../node_modules/execa/node_modules/get-stream/source/stream.js
var getAsyncIterable = (stream) => {
if (isReadableStream(stream, { checkOpen: !1 }) && nodeImports.on !== void 0)
return getStreamIterable(stream);
if (typeof stream?.[Symbol.asyncIterator] == "function")
return stream;
if (toString.call(stream) === "[object ReadableStream]")
return h.call(stream);
throw new TypeError("The first argument must be a Readable, a ReadableStream, or an async iterable.");
}, { toString } = Object.prototype, getStreamIterable = async function* (stream) {
let controller = new AbortController(), state = {};
handleStreamEnd(stream, controller, state);
try {
for await (let [chunk] of nodeImports.on(stream, "data", { signal: controller.signal }))
yield chunk;
} catch (error) {
if (state.error !== void 0)
throw state.error;
if (!controller.signal.aborted)
throw error;
} finally {
stream.destroy();
}
}, handleStreamEnd = async (stream, controller, state) => {
try {
await nodeImports.finished(stream, {
cleanup: !0,
readable: !0,
writable: !1,
error: !1
});
} catch (error) {
state.error = error;
} finally {
controller.abort();
}
}, nodeImports = {};
// ../../node_modules/execa/node_modules/get-stream/source/contents.js
var getStreamContents = async (stream, { init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize }, { maxBuffer = Number.POSITIVE_INFINITY } = {}) => {
let asyncIterable = getAsyncIterable(stream), state = init();
state.length = 0;
try {
for await (let chunk of asyncIterable) {
let chunkType = getChunkType(chunk), convertedChunk = convertChunk[chunkType](chunk, state);
appendChunk({
convertedChunk,
state,
getSize,
truncateChunk,
addChunk,
maxBuffer
});
}
return appendFinalChunk({
state,
convertChunk,
getSize,
truncateChunk,
addChunk,
getFinalChunk,
maxBuffer
}), finalize(state);
} catch (error) {
let normalizedError = typeof error == "object" && error !== null ? error : new Error(error);
throw normalizedError.bufferedData = finalize(state), normalizedError;
}
}, appendFinalChunk = ({ state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer }) => {
let convertedChunk = getFinalChunk(state);
convertedChunk !== void 0 && appendChunk({
convertedChunk,
state,
getSize,
truncateChunk,
addChunk,
maxBuffer
});
}, appendChunk = ({ convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer }) => {
let chunkSize = getSize(convertedChunk), newLength = state.length + chunkSize;
if (newLength <= maxBuffer) {
addNewChunk(convertedChunk, state, addChunk, newLength);
return;
}
let truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length);
throw truncatedChunk !== void 0 && addNewChunk(truncatedChunk, state, addChunk, maxBuffer), new MaxBufferError();
}, addNewChunk = (convertedChunk, state, addChunk, newLength) => {
state.contents = addChunk(convertedChunk, state, newLength), state.length = newLength;
}, getChunkType = (chunk) => {
let typeOfChunk = typeof chunk;
if (typeOfChunk === "string")
return "string";
if (typeOfChunk !== "object" || chunk === null)
return "others";
if (globalThis.Buffer?.isBuffer(chunk))
return "buffer";
let prototypeName = objectToString2.call(chunk);
return prototypeName === "[object ArrayBuffer]" ? "arrayBuffer" : prototypeName === "[object DataView]" ? "dataView" : Number.isInteger(chunk.byteLength) && Number.isInteger(chunk.byteOffset) && objectToString2.call(chunk.buffer) === "[object ArrayBuffer]" ? "typedArray" : "others";
}, { toString: objectToString2 } = Object.prototype, MaxBufferError = class extends Error {
name = "MaxBufferError";
constructor() {
super("maxBuffer exceeded");
}
};
// ../../node_modules/execa/node_modules/get-stream/source/utils.js
var identity2 = (value) => value, noop = () => {
}, getContentsProperty = ({ contents }) => contents, throwObjectStream = (chunk) => {
throw new Error(`Streams in object mode are not supported: ${String(chunk)}`);
}, getLengthProperty = (convertedChunk) => convertedChunk.length;
// ../../node_modules/execa/node_modules/get-stream/source/array.js
async function getStreamAsArray(stream, options) {
return getStreamContents(stream, arrayMethods, options);
}
var initArray = () => ({ contents: [] }), increment = () => 1, addArrayChunk = (convertedChunk, { contents }) => (contents.push(convertedChunk), contents), arrayMethods = {
init: initArray,
convertChunk: {
string: identity2,
buffer: identity2,
arrayBuffer: identity2,
dataView: identity2,
typedArray: identity2,
others: identity2
},
getSize: increment,
truncateChunk: noop,
addChunk: addArrayChunk,
getFinalChunk: noop,
finalize: getContentsProperty
};
// ../../node_modules/execa/node_modules/get-stream/source/array-buffer.js
async function getStreamAsArrayBuffer(stream, options) {
return getStreamContents(stream, arrayBufferMethods, options);
}
var initArrayBuffer = () => ({ contents: new ArrayBuffer(0) }), useTextEncoder = (chunk) => textEncoder2.encode(chunk), textEncoder2 = new TextEncoder(), useUint8Array = (chunk) => new Uint8Array(chunk), useUint8ArrayWithOffset = (chunk) => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), addArrayBufferChunk = (convertedChunk, { contents, length: previousLength }, length) => {
let newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length);
return new Uint8Array(newContents).set(convertedChunk, previousLength), newContents;
}, resizeArrayBufferSlow = (contents, length) => {
if (length <= contents.byteLength)
return contents;
let arrayBuffer = new ArrayBuffer(getNewContentsLength(length));
return new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0), arrayBuffer;
}, resizeArrayBuffer = (contents, length) => {
if (length <= contents.maxByteLength)
return contents.resize(length), contents;
let arrayBuffer = new ArrayBuffer(length, { maxByteLength: getNewContentsLength(length) });
return new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0), arrayBuffer;
}, getNewContentsLength = (length) => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)), SCALE_FACTOR = 2, finalizeArrayBuffer = ({ contents, length }) => hasArrayBufferResize() ? contents : contents.slice(0, length), hasArrayBufferResize = () => "resize" in ArrayBuffer.prototype, arrayBufferMethods = {
init: initArrayBuffer,
convertChunk: {
string: useTextEncoder,
buffer: useUint8Array,
arrayBuffer: useUint8Array,
dataView: useUint8ArrayWithOffset,
typedArray: useUint8ArrayWithOffset,
others: throwObjectStream
},
getSize: getLengthProperty,
truncateChunk: truncateArrayBufferChunk,
addChunk: addArrayBufferChunk,
getFinalChunk: noop,
finalize: finalizeArrayBuffer
};
// ../../node_modules/execa/node_modules/get-stream/source/string.js
async function getStreamAsString(stream, options) {
return getStreamContents(stream, stringMethods, options);
}
var initString = () => ({ contents: "", textDecoder: new TextDecoder() }), useTextDecoder = (chunk, { textDecoder: textDecoder2 }) => textDecoder2.decode(chunk, { stream: !0 }), addStringChunk = (convertedChunk, { contents }) => contents + convertedChunk, truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), getFinalStringChunk = ({ textDecoder: textDecoder2 }) => {
let finalChunk = textDecoder2.decode();
return finalChunk === "" ? void 0 : finalChunk;
}, stringMethods = {
init: initString,
convertChunk: {
string: identity2,
buffer: useTextDecoder,
arrayBuffer: useTextDecoder,
dataView: useTextDecoder,
typedArray: useTextDecoder,
others: throwObjectStream
},
getSize: getLengthProperty,
truncateChunk: truncateStringChunk,
addChunk: addStringChunk,
getFinalChunk: getFinalStringChunk,
finalize: getContentsProperty
};
// ../../node_modules/execa/node_modules/get-stream/source/index.js
Object.assign(nodeImports, { on, finished });
// ../../node_modules/execa/lib/io/max-buffer.js
var handleMaxBuffer = ({ error, stream, readableObjectMode, lines, encoding, fdNumber }) => {
if (!(error instanceof MaxBufferError))
throw error;
if (fdNumber === "all")
return error;
let unit = getMaxBufferUnit(readableObjectMode, lines, encoding);
throw error.maxBufferInfo = { fdNumber, unit }, stream.destroy(), error;
}, getMaxBufferUnit = (readableObjectMode, lines, encoding) => readableObjectMode ? "objects" : lines ? "lines" : encoding === "buffer" ? "bytes" : "characters", checkIpcMaxBuffer = (subprocess, ipcOutput, maxBuffer) => {
if (ipcOutput.length !== maxBuffer)
return;
let error = new MaxBufferError();
throw error.maxBufferInfo = { fdNumber: "ipc" }, error;
}, getMaxBufferMessage = (error, maxBuffer) => {
let { streamName, threshold, unit } = getMaxBufferInfo(error, maxBuffer);
return `Command's ${streamName} was larger than ${threshold} ${unit}`;
}, getMaxBufferInfo = (error, maxBuffer) => {
if (error?.maxBufferInfo === void 0)
return { streamName: "output", threshold: maxBuffer[1], unit: "bytes" };
let { maxBufferInfo: { fdNumber, unit } } = error;
delete error.maxBufferInfo;
let threshold = getFdSpecificValue(maxBuffer, fdNumber);
return fdNumber === "ipc" ? { streamName: "IPC output", threshold, unit: "messages" } : { streamName: getStreamName(fdNumber), threshold, unit };
}, isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === "ENOBUFS" && output !== null && output.some((result) => result !== null && result.length > getMaxBufferSync(maxBuffer)), truncateMaxBufferSync = (result, isMaxBuffer, maxBuffer) => {
if (!isMaxBuffer)
return result;
let maxBufferValue = getMaxBufferSync(maxBuffer);
return result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result;
}, getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;
// ../../node_modules/execa/lib/return/message.js
var createMessages = ({
stdio,
all,
ipcOutput,
originalError,
signal,
signalDescription,
exitCode,
escapedCommand,
timedOut,
isCanceled,
isGracefullyCanceled,
isMaxBuffer,
isForcefullyTerminated,
forceKillAfterDelay,
killSignal,
maxBuffer,
timeout,
cwd
}) => {
let errorCode = originalError?.code, prefix = getErrorPrefix({
originalError,
timedOut,
timeout,
isMaxBuffer,
maxBuffer,
errorCode,
signal,
signalDescription,
exitCode,
isCanceled,
isGracefullyCanceled,
isForcefullyTerminated,
forceKillAfterDelay,
killSignal
}), originalMessage = getOriginalMessage(originalError, cwd), suffix = originalMessage === void 0 ? "" : `
${originalMessage}`, shortMessage = `${prefix}: ${escapedCommand}${suffix}`, messageStdio = all === void 0 ? [stdio[2], stdio[1]] : [all], message = [
shortMessage,
...messageStdio,
...stdio.slice(3),
ipcOutput.map((ipcMessage) => serializeIpcMessage(ipcMessage)).join(`
`)
].map((messagePart) => escapeLines(stripFinalNewline(serializeMessagePart(messagePart)))).filter(Boolean).join(`
`);
return { originalMessage, shortMessage, message };
}, getErrorPrefix = ({
originalError,
timedOut,
timeout,
isMaxBuffer,
maxBuffer,
errorCode,
signal,
signalDescription,
exitCode,
isCanceled,
isGracefullyCanceled,
isForcefullyTerminated,
forceKillAfterDelay,
killSignal
}) => {
let forcefulSuffix = getForcefulSuffix(isForcefullyTerminated, forceKillAfterDelay);
return timedOut ? `Command timed out after ${timeout} milliseconds${forcefulSuffix}` : isGracefullyCanceled ? signal === void 0 ? `Command was gracefully canceled with exit code ${exitCode}` : isForcefullyTerminated ? `Command was gracefully canceled${forcefulSuffix}` : `Command was gracefully canceled with ${signal} (${signalDescription})` : isCanceled ? `Command was canceled${forcefulSuffix}` : isMaxBuffer ? `${getMaxBufferMessage(originalError, maxBuffer)}${forcefulSuffix}` : errorCode !== void 0 ? `Command failed with ${errorCode}${forcefulSuffix}` : isForcefullyTerminated ? `Command was killed with ${killSignal} (${getSignalDescription(killSignal)})${forcefulSuffix}` : signal !== void 0 ? `Command was killed with ${signal} (${signalDescription})` : exitCode !== void 0 ? `Command failed with exit code ${exitCode}` : "Command failed";
}, getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds` : "", getOriginalMessage = (originalError, cwd) => {
if (originalError instanceof DiscardedError)
return;
let originalMessage = isExecaError(originalError) ? originalError.originalMessage : String(originalError?.message ?? originalError), escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));
return escapedOriginalMessage === "" ? void 0 : escapedOriginalMessage;
}, serializeIpcMessage = (ipcMessage) => typeof ipcMessage == "string" ? ipcMessage : inspect2(ipcMessage), serializeMessagePart = (messagePart) => Array.isArray(messagePart) ? messagePart.map((messageItem) => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join(`
`) : serializeMessageItem(messagePart), serializeMessageItem = (messageItem) => typeof messageItem == "string" ? messageItem : isUint8Array(messageItem) ? uint8ArrayToString(messageItem) : "";
// ../../node_modules/execa/lib/return/result.js
var makeSuccessResult = ({
command,
escapedCommand,
stdio,
all,
ipcOutput,
options: { cwd },
startTime
}) => omitUndefinedProperties({
command,
escapedCommand,
cwd,
durationMs: getDurationMs(startTime),
failed: !1,
timedOut: !1,
isCanceled: !1,
isGracefullyCanceled: !1,
isTerminated: !1,
isMaxBuffer: !1,
isForcefullyTerminated: !1,
exitCode: 0,
stdout: stdio[1],
stderr: stdio[2],
all,
stdio,
ipcOutput,
pipedFrom: []
}), makeEarlyError = ({
error,
command,
escapedCommand,
fileDescriptors,
options,
startTime,
isSync
}) => makeError({
error,
command,
escapedCommand,
startTime,
timedOut: !1,
isCanceled: !1,
isGracefullyCanceled: !1,
isMaxBuffer: !1,
isForcefullyTerminated: !1,
stdio: Array.from({ length: fileDescriptors.length }),
ipcOutput: [],
options,
isSync
}), makeError = ({
error: originalError,
command,
escapedCommand,
startTime,
timedOut,
isCanceled,
isGracefullyCanceled,
isMaxBuffer,
isForcefullyTerminated,
exitCode: rawExitCode,
signal: rawSignal,
stdio,
all,
ipcOutput,
options: {
timeoutDuration,
timeout = timeoutDuration,
forceKillAfterDelay,
killSignal,
cwd,
maxBuffer
},
isSync
}) => {
let { exitCode, signal, signalDescription } = normalizeExitPayload(rawExitCode, rawSignal), { originalMessage, shortMessage, message } = createMessages({
stdio,
all,
ipcOutput,
originalError,
signal,
signalDescription,
exitCode,
escapedCommand,
timedOut,
isCanceled,
isGracefullyCanceled,
isMaxBuffer,
isForcefullyTerminated,
forceKillAfterDelay,
killSignal,
maxBuffer,
timeout,
cwd
}), error = getFinalError(originalError, message, isSync);
return Object.assign(error, getErrorProperties({
error,
command,
escapedCommand,
startTime,
timedOut,
isCanceled,
isGracefullyCanceled,
isMaxBuffer,
isForcefullyTerminated,
exitCode,
signal,
signalDescription,
stdio,
all,
ipcOutput,
cwd,
originalMessage,
shortMessage
})), error;
}, getErrorProperties = ({
error,
command,
escapedCommand,
startTime,
timedOut,
isCanceled,
isGracefullyCanceled,
isMaxBuffer,
isForcefullyTerminated,
exitCode,
signal,
signalDescription,
stdio,
all,
ipcOutput,
cwd,
originalMessage,
shortMessage
}) => omitUndefinedProperties({
shortMessage,
originalMessage,
command,
escapedCommand,
cwd,
durationMs: getDurationMs(startTime),
failed: !0,
timedOut,
isCanceled,
isGracefullyCanceled,
isTerminated: signal !== void 0,
isMaxBuffer,
isForcefullyTerminated,
exitCode,
signal,
signalDescription,
code: error.cause?.code,
stdout: stdio[1],
stderr: stdio[2],
all,
stdio,
ipcOutput,
pipedFrom: []
}), omitUndefinedProperties = (result) => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== void 0)), normalizeExitPayload = (rawExitCode, rawSignal) => {
let exitCode = rawExitCode === null ? void 0 : rawExitCode, signal = rawSignal === null ? void 0 : rawSignal, signalDescription = signal === void 0 ? void 0 : getSignalDescription(rawSignal);
return { exitCode, signal, signalDescription };
};
// ../../node_modules/parse-ms/index.js
var toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0;
function parseNumber(milliseconds) {
return {
days: Math.trunc(milliseconds / 864e5),
hours: Math.trunc(milliseconds / 36e5 % 24),
minutes: Math.trunc(milliseconds / 6e4 % 60),
seconds: Math.trunc(milliseconds / 1e3 % 60),
milliseconds: Math.trunc(milliseconds % 1e3),
microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e3) % 1e3),
nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1e3)
};
}
function parseBigint(milliseconds) {
return {
days: milliseconds / 86400000n,
hours: milliseconds / 3600000n % 24n,
minutes: milliseconds / 60000n % 60n,
seconds: milliseconds / 1000n % 60n,
milliseconds: milliseconds % 1000n,
microseconds: 0n,
nanoseconds: 0n
};
}
function parseMilliseconds(milliseconds) {
switch (typeof milliseconds) {
case "number": {
if (Number.isFinite(milliseconds))
return parseNumber(milliseconds);
break;
}
case "bigint":
return parseBigint(milliseconds);
}
throw new TypeError("Expected a finite number or bigint");
}
// ../../node_modules/execa/node_modules/pretty-ms/index.js
var isZero = (value) => value === 0 || value === 0n, pluralize = (word, count2) => count2 === 1 || count2 === 1n ? word : `${word}s`, SECOND_ROUNDING_EPSILON = 1e-7, ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
function prettyMilliseconds(milliseconds, options) {
let isBigInt = typeof milliseconds == "bigint";
if (!isBigInt && !Number.isFinite(milliseconds))
throw new TypeError("Expected a finite number or bigint");
options = { ...options };
let sign = milliseconds < 0 ? "-" : "";
milliseconds = milliseconds < 0 ? -milliseconds : milliseconds, options.colonNotation && (options.compact = !1, options.formatSubMilliseconds = !1, options.separateMilliseconds = !1, options.verbose = !1), options.compact && (options.unitCount = 1, options.secondsDecimalDigits = 0, options.millisecondsDecimalDigits = 0);
let result = [], floorDecimals = (value, decimalDigits) => {
let flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON);
return (Math.round(flooredInterimValue) / 10 ** decimalDigits).toFixed(decimalDigits);
}, add = (value, long, short, valueString) => {
if (!((result.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === "m"))) {
if (valueString ??= String(value), options.colonNotation) {
let wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length, minLength = result.length > 0 ? 2 : 1;
valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString;
} else
valueString += options.verbose ? " " + pluralize(long, value) : short;
result.push(valueString);
}
}, parsed = parseMilliseconds(milliseconds), days = BigInt(parsed.days);
if (options.hideYearAndDays ? add(BigInt(days) * 24n + BigInt(parsed.hours), "hour", "h") : (options.hideYear ? add(days, "day", "d") : (add(days / 365n, "year", "y"), add(days % 365n, "day", "d")), add(Number(parsed.hours), "hour", "h")), add(Number(parsed.minutes), "minute", "m"), !options.hideSeconds)
if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1e3 && !options.subSecondsAsDecimals) {
let seconds = Number(parsed.seconds), milliseconds2 = Number(parsed.milliseconds), microseconds = Number(parsed.microseconds), nanoseconds = Number(parsed.nanoseconds);
if (add(seconds, "second", "s"), options.formatSubMilliseconds)
add(milliseconds2, "millisecond", "ms"), add(microseconds, "microsecond", "\xB5s"), add(nanoseconds, "nanosecond", "ns");
else {
let millisecondsAndBelow = milliseconds2 + microseconds / 1e3 + nanoseconds / 1e6, millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits == "number" ? options.millisecondsDecimalDigits : 0, roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow), millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds;
add(
Number.parseFloat(millisecondsString),
"millisecond",
"ms",
millisecondsString
);
}
} else {
let seconds = (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1e3 % 60, secondsDecimalDigits = typeof options.secondsDecimalDigits == "number" ? options.secondsDecimalDigits : 1, secondsFixed = floorDecimals(seconds, secondsDecimalDigits), secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
add(Number.parseFloat(secondsString), "second", "s", secondsString);
}
if (result.length === 0)
return sign + "0" + (options.verbose ? " milliseconds" : "ms");
let separator = options.colonNotation ? ":" : " ";
return typeof options.unitCount == "number" && (result = result.slice(0, Math.max(options.unitCount, 1))), sign + result.join(separator);
}
// ../../node_modules/execa/lib/verbose/error.js
var logError = (result, verboseInfo) => {
result.failed && verboseLog({
type: "error",
verboseMessage: result.shortMessage,
verboseInfo,
result
});
};
// ../../node_modules/execa/lib/verbose/complete.js
var logResult = (result, verboseInfo) => {
isVerbose(verboseInfo) && (logError(result, verboseInfo), logDuration(result, verboseInfo));
}, logDuration = (result, verboseInfo) => {
let verboseMessage = `(done in ${prettyMilliseconds(result.durationMs)})`;
verboseLog({
type: "duration",
verboseMessage,
verboseInfo,
result
});
};
// ../../node_modules/execa/lib/return/reject.js
var handleResult = (result, verboseInfo, { reject }) => {
if (logResult(result, verboseInfo), result.failed && reject)
throw result;
return result;
};
// ../../node_modules/execa/lib/stdio/handle-sync.js
import { readFileSync as readFileSync2 } from "node:fs";
// ../../node_modules/execa/lib/stdio/type.js
var getStdioItemType = (value, optionName) => isAsyncGenerator(value) ? "asyncGenerator" : isSyncGenerator(value) ? "generator" : isUrl(value) ? "fileUrl" : isFilePathObject(value) ? "filePath" : isWebStream(value) ? "webStream" : isStream(value, { checkOpen: !1 }) ? "native" : isUint8Array(value) ? "uint8Array" : isAsyncIterableObject(value) ? "asyncIterable" : isIterableObject(value) ? "iterable" : isTransformStream(value) ? getTransformStreamType({ transform: value }, optionName) : isTransformOptions(value) ? getTransformObjectType(value, optionName) : "native", getTransformObjectType = (value, optionName) => isDuplexStream(value.transform, { checkOpen: !1 }) ? getDuplexType(value, optionName) : isTransformStream(value.transform) ? getTransformStreamType(value, optionName) : getGeneratorObjectType(value, optionName), getDuplexType = (value, optionName) => (validateNonGeneratorType(value, optionName, "Duplex stream"), "duplex"), getTransformStreamType = (value, optionName) => (validateNonGeneratorType(value, optionName, "web TransformStream"), "webTransform"), validateNonGeneratorType = ({ final, binary, objectMode }, optionName, typeName) => {
checkUndefinedOption(final, `${optionName}.final`, typeName), checkUndefinedOption(binary, `${optionName}.binary`, typeName), checkBooleanOption(objectMode, `${optionName}.objectMode`);
}, checkUndefinedOption = (value, optionName, typeName) => {
if (value !== void 0)
throw new TypeError(`The \`${optionName}\` option can only be defined when using a generator, not a ${typeName}.`);
}, getGeneratorObjectType = ({ transform, final, binary, objectMode }, optionName) => {
if (transform !== void 0 && !isGenerator(transform))
throw new TypeError(`The \`${optionName}.transform\` option must be a generator, a Duplex stream or a web TransformStream.`);
if (isDuplexStream(final, { checkOpen: !1 }))
throw new TypeError(`The \`${optionName}.final\` option must not be a Duplex stream.`);
if (isTransformStream(final))
throw new TypeError(`The \`${optionName}.final\` option must not be a web TransformStream.`);
if (final !== void 0 && !isGenerator(final))
throw new TypeError(`The \`${optionName}.final\` option must be a generator.`);
return checkBooleanOption(binary, `${optionName}.binary`), checkBooleanOption(objectMode, `${optionName}.objectMode`), isAsyncGenerator(transform) || isAsyncGenerator(final) ? "asyncGenerator" : "generator";
}, checkBooleanOption = (value, optionName) => {
if (value !== void 0 && typeof value != "boolean")
throw new TypeError(`The \`${optionName}\` option must use a boolean.`);
}, isGenerator = (value) => isAsyncGenerator(value) || isSyncGenerator(value), isAsyncGenerator = (value) => Object.prototype.toString.call(value) === "[object AsyncGeneratorFunction]", isSyncGenerator = (value) => Object.prototype.toString.call(value) === "[object GeneratorFunction]", isTransformOptions = (value) => isPlainObject(value) && (value.transform !== void 0 || value.final !== void 0), isUrl = (value) => Object.prototype.toString.call(value) === "[object URL]", isRegularUrl = (value) => isUrl(value) && value.protocol !== "file:", isFilePathObject = (value) => isPlainObject(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => FILE_PATH_KEYS.has(key)) && isFilePathString(value.file), FILE_PATH_KEYS = /* @__PURE__ */ new Set(["file", "append"]), isFilePathString = (file) => typeof file == "string", isUnknownStdioString = (type, value) => type === "native" && typeof value == "string" && !KNOWN_STDIO_STRINGS.has(value), KNOWN_STDIO_STRINGS = /* @__PURE__ */ new Set(["ipc", "ignore", "inherit", "overlapped", "pipe"]), isReadableStream2 = (value) => Object.prototype.toString.call(value) === "[object ReadableStream]", isWritableStream2 = (value) => Object.prototype.toString.call(value) === "[object WritableStream]", isWebStream = (value) => isReadableStream2(value) || isWritableStream2(value), isTransformStream = (value) => isReadableStream2(value?.readable) && isWritableStream2(value?.writable), isAsyncIterableObject = (value) => isObject(value) && typeof value[Symbol.asyncIterator] == "function", isIterableObject = (value) => isObject(value) && typeof value[Symbol.iterator] == "function", isObject = (value) => typeof value == "object" && value !== null, TRANSFORM_TYPES = /* @__PURE__ */ new Set(["generator", "asyncGenerator", "duplex", "webTransform"]), FILE_TYPES = /* @__PURE__ */ new Set(["fileUrl", "filePath", "fileNumber"]), SPECIAL_DUPLICATE_TYPES_SYNC = /* @__PURE__ */ new Set(["fileUrl", "filePath"]), SPECIAL_DUPLICATE_TYPES = /* @__PURE__ */ new Set([...SPECIAL_DUPLICATE_TYPES_SYNC, "webStream", "nodeStream"]), FORBID_DUPLICATE_TYPES = /* @__PURE__ */ new Set(["webTransform", "duplex"]), TYPE_TO_MESSAGE = {
generator: "a generator",
asyncGenerator: "an async generator",
fileUrl: "a file URL",
filePath: "a file path string",
fileNumber: "a file descriptor number",
webStream: "a web stream",
nodeStream: "a Node.js stream",
webTransform: "a web TransformStream",
duplex: "a Duplex stream",
native: "any value",
iterable: "an iterable",
asyncIterable: "an async iterable",
string: "a string",
uint8Array: "a Uint8Array"
};
// ../../node_modules/execa/lib/transform/object-mode.js
var getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === "output" ? getOutputObjectModes(objectMode, index, newTransforms) : getInputObjectModes(objectMode, index, newTransforms), getOutputObjectModes = (objectMode, index, newTransforms) => {
let writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;
return { writableObjectMode, readableObjectMode: objectMode ?? writableObjectMode };
}, getInputObjectModes = (objectMode, index, newTransforms) => {
let writableObjectMode = index === 0 ? objectMode === !0 : newTransforms[index - 1].value.readableObjectMode, readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);
return { writableObjectMode, readableObjectMode };
}, getFdObjectMode = (stdioItems, direction) => {
let lastTransform = stdioItems.findLast(({ type }) => TRANSFORM_TYPES.has(type));
return lastTransform === void 0 ? !1 : direction === "input" ? lastTransform.value.writableObjectMode : lastTransform.value.readableObjectMode;
};
// ../../node_modules/execa/lib/transform/normalize.js
var normalizeTransforms = (stdioItems, optionName, direction, options) => [
...stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type)),
...getTransforms(stdioItems, optionName, direction, options)
], getTransforms = (stdioItems, optionName, direction, { encoding }) => {
let transforms = stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type)), newTransforms = Array.from({ length: transforms.length });
for (let [index, stdioItem] of Object.entries(transforms))
newTransforms[index] = normalizeTransform({
stdioItem,
index: Number(index),
newTransforms,
optionName,
direction,
encoding
});
return sortTransforms(newTransforms, direction);
}, normalizeTransform = ({ stdioItem, stdioItem: { type }, index, newTransforms, optionName, direction, encoding }) => type === "duplex" ? normalizeDuplex({ stdioItem, optionName }) : type === "webTransform" ? normalizeTransformStream({
stdioItem,
index,
newTransforms,
direction
}) : normalizeGenerator({
stdioItem,
index,
newTransforms,
direction,
encoding
}), normalizeDuplex = ({
stdioItem,
stdioItem: {
value: {
transform,
transform: { writableObjectMode, readableObjectMode },
objectMode = readableObjectMode
}
},
optionName
}) => {
if (objectMode && !readableObjectMode)
throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);
if (!objectMode && readableObjectMode)
throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);
return {
...stdioItem,
value: { transform, writableObjectMode, readableObjectMode }
};
}, normalizeTransformStream = ({ stdioItem, stdioItem: { value }, index, newTransforms, direction }) => {
let { transform, objectMode } = isPlainObject(value) ? value : { transform: value }, { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index, newTransforms, direction);
return {
...stdioItem,
value: { transform, writableObjectMode, readableObjectMode }
};
}, normalizeGenerator = ({ stdioItem, stdioItem: { value }, index, newTransforms, direction, encoding }) => {
let {
transform,
final,
binary: binaryOption = !1,
preserveNewlines = !1,
objectMode
} = isPlainObject(value) ? value : { transform: value }, binary = binaryOption || BINARY_ENCODINGS.has(encoding), { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index, newTransforms, direction);
return {
...stdioItem,
value: {
transform,
final,
binary,
preserveNewlines,
writableObjectMode,
readableObjectMode
}
};
}, sortTransforms = (newTransforms, direction) => direction === "input" ? newTransforms.reverse() : newTransforms;
// ../../node_modules/execa/lib/stdio/direction.js
import process7 from "node:process";
var getStreamDirection = (stdioItems, fdNumber, optionName) => {
let directions = stdioItems.map((stdioItem) => getStdioItemDirection(stdioItem, fdNumber));
if (directions.includes("input") && directions.includes("output"))
throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`);
return directions.find(Boolean) ?? DEFAULT_DIRECTION;
}, getStdioItemDirection = ({ type, value }, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value), KNOWN_DIRECTIONS = ["input", "output", "output"], anyDirection = () => {
}, alwaysInput = () => "input", guessStreamDirection = {
generator: anyDirection,
asyncGenerator: anyDirection,
fileUrl: anyDirection,
filePath: anyDirection,
iterable: alwaysInput,
asyncIterable: alwaysInput,
uint8Array: alwaysInput,
webStream: (value) => isWritableStream2(value) ? "output" : "input",
nodeStream(value) {
return isReadableStream(value, { checkOpen: !1 }) ? isWritableStream(value, { checkOpen: !1 }) ? void 0 : "input" : "output";
},
webTransform: anyDirection,
duplex: anyDirection,
native(value) {
let standardStreamDirection = getStandardStreamDirection(value);
if (standardStreamDirection !== void 0)
return standardStreamDirection;
if (isStream(value, { checkOpen: !1 }))
return guessStreamDirection.nodeStream(value);
}
}, getStandardStreamDirection = (value) => {
if ([0, process7.stdin].includes(value))
return "input";
if ([1, 2, process7.stdout, process7.stderr].includes(value))
return "output";
}, DEFAULT_DIRECTION = "output";
// ../../node_modules/execa/lib/ipc/array.js
var normalizeIpcStdioArray = (stdioArray, ipc) => ipc && !stdioArray.includes("ipc") ? [...stdioArray, "ipc"] : stdioArray;
// ../../node_modules/execa/lib/stdio/stdio-option.js
var normalizeStdioOption = ({ stdio, ipc, buffer, ...options }, verboseInfo, isSync) => {
let stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue2(stdioOption, fdNumber));
return isSync ? normalizeStdioSync(stdioArray, buffer, verboseInfo) : normalizeIpcStdioArray(stdioArray, ipc);
}, getStdioArray = (stdio, options) => {
if (stdio === void 0)
return STANDARD_STREAMS_ALIASES.map((alias) => options[alias]);
if (hasAlias(options))
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map((alias) => `\`${alias}\``).join(", ")}`);
if (typeof stdio == "string")
return [stdio, stdio, stdio];
if (!Array.isArray(stdio))
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
let length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);
return Array.from({ length }, (_, fdNumber) => stdio[fdNumber]);
}, hasAlias = (options) => STANDARD_STREAMS_ALIASES.some((alias) => options[alias] !== void 0), addDefaultValue2 = (stdioOption, fdNumber) => Array.isArray(stdioOption) ? stdioOption.map((item) => addDefaultValue2(item, fdNumber)) : stdioOption ?? (fdNumber >= STANDARD_STREAMS_ALIASES.length ? "ignore" : "pipe"), normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((stdioOption, fdNumber) => !buffer[fdNumber] && fdNumber !== 0 && !isFullVerbose(verboseInfo, fdNumber) && isOutputPipeOnly(stdioOption) ? "ignore" : stdioOption), isOutputPipeOnly = (stdioOption) => stdioOption === "pipe" || Array.isArray(stdioOption) && stdioOption.every((item) => item === "pipe");
// ../../node_modules/execa/lib/stdio/native.js
import { readFileSync } from "node:fs";
import tty2 from "node:tty";
var handleNativeStream = ({ stdioItem, stdioItem: { type }, isStdioArray, fdNumber, direction, isSync }) => !isStdioArray || type !== "native" ? stdioItem : isSync ? handleNativeStreamSync({ stdioItem, fdNumber, direction }) : handleNativeStreamAsync({ stdioItem, fdNumber }), handleNativeStreamSync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber, direction }) => {
let targetFd = getTargetFd({
value,
optionName,
fdNumber,
direction
});
if (targetFd !== void 0)
return targetFd;
if (isStream(value, { checkOpen: !1 }))
throw new TypeError(`The \`${optionName}: Stream\` option cannot both be an array and include a stream with synchronous methods.`);
return stdioItem;
}, getTargetFd = ({ value, optionName, fdNumber, direction }) => {
let targetFdNumber = getTargetFdNumber(value, fdNumber);
if (targetFdNumber !== void 0) {
if (direction === "output")
return { type: "fileNumber", value: targetFdNumber, optionName };
if (tty2.isatty(targetFdNumber))
throw new TypeError(`The \`${optionName}: ${serializeOptionValue(value)}\` option is invalid: it cannot be a TTY with synchronous methods.`);
return { type: "uint8Array", value: bufferToUint8Array(readFileSync(targetFdNumber)), optionName };
}
}, getTargetFdNumber = (value, fdNumber) => {
if (value === "inherit")
return fdNumber;
if (typeof value == "number")
return value;
let standardStreamIndex = STANDARD_STREAMS.indexOf(value);
if (standardStreamIndex !== -1)
return standardStreamIndex;
}, handleNativeStreamAsync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber }) => value === "inherit" ? { type: "nodeStream", value: getStandardStream(fdNumber, value, optionName), optionName } : typeof value == "number" ? { type: "nodeStream", value: getStandardStream(value, value, optionName), optionName } : isStream(value, { checkOpen: !1 }) ? { type: "nodeStream", value, optionName } : stdioItem, getStandardStream = (fdNumber, value, optionName) => {
let standardStream = STANDARD_STREAMS[fdNumber];
if (standardStream === void 0)
throw new TypeError(`The \`${optionName}: ${value}\` option is invalid: no such standard stream.`);
return standardStream;
};
// ../../node_modules/execa/lib/stdio/input-option.js
var handleInputOptions = ({ input, inputFile }, fdNumber) => fdNumber === 0 ? [
...handleInputOption(input),
...handleInputFileOption(inputFile)
] : [], handleInputOption = (input) => input === void 0 ? [] : [{
type: getInputType(input),
value: input,
optionName: "input"
}], getInputType = (input) => {
if (isReadableStream(input, { checkOpen: !1 }))
return "nodeStream";
if (typeof input == "string")
return "string";
if (isUint8Array(input))
return "uint8Array";
throw new Error("The `input` option must be a string, a Uint8Array or a Node.js Readable stream.");
}, handleInputFileOption = (inputFile) => inputFile === void 0 ? [] : [{
...getInputFileType(inputFile),
optionName: "inputFile"
}], getInputFileType = (inputFile) => {
if (isUrl(inputFile))
return { type: "fileUrl", value: inputFile };
if (isFilePathString(inputFile))
return { type: "filePath", value: { file: inputFile } };
throw new Error("The `inputFile` option must be a file path string or a file URL.");
};
// ../../node_modules/execa/lib/stdio/duplicate.js
var filterDuplicates = (stdioItems) => stdioItems.filter((stdioItemOne, indexOne) => stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value || indexOne >= indexTwo || stdioItemOne.type === "generator" || stdioItemOne.type === "asyncGenerator")), getDuplicateStream = ({ stdioItem: { type, value, optionName }, direction, fileDescriptors, isSync }) => {
let otherStdioItems = getOtherStdioItems(fileDescriptors, type);
if (otherStdioItems.length !== 0) {
if (isSync) {
validateDuplicateStreamSync({
otherStdioItems,
type,
value,
optionName,
direction
});
return;
}
if (SPECIAL_DUPLICATE_TYPES.has(type))
return getDuplicateStreamInstance({
otherStdioItems,
type,
value,
optionName,
direction
});
FORBID_DUPLICATE_TYPES.has(type) && validateDuplicateTransform({
otherStdioItems,
type,
value,
optionName
});
}
}, getOtherStdioItems = (fileDescriptors, type) => fileDescriptors.flatMap(({ direction, stdioItems }) => stdioItems.filter((stdioItem) => stdioItem.type === type).map(((stdioItem) => ({ ...stdioItem, direction })))), validateDuplicateStreamSync = ({ otherStdioItems, type, value, optionName, direction }) => {
SPECIAL_DUPLICATE_TYPES_SYNC.has(type) && getDuplicateStreamInstance({
otherStdioItems,
type,
value,
optionName,
direction
});
}, getDuplicateStreamInstance = ({ otherStdioItems, type, value, optionName, direction }) => {
let duplicateStdioItems = otherStdioItems.filter((stdioItem) => hasSameValue(stdioItem, value));
if (duplicateStdioItems.length === 0)
return;
let differentStdioItem = duplicateStdioItems.find((stdioItem) => stdioItem.direction !== direction);
return throwOnDuplicateStream(differentStdioItem, optionName, type), direction === "output" ? duplicateStdioItems[0].stream : void 0;
}, hasSameValue = ({ type, value }, secondValue) => type === "filePath" ? value.file === secondValue.file : type === "fileUrl" ? value.href === secondValue.href : value === secondValue, validateDuplicateTransform = ({ otherStdioItems, type, value, optionName }) => {
let duplicateStdioItem = otherStdioItems.find(({ value: { transform } }) => transform === value.transform);
throwOnDuplicateStream(duplicateStdioItem, optionName, type);
}, throwOnDuplicateStream = (stdioItem, optionName, type) => {
if (stdioItem !== void 0)
throw new TypeError(`The \`${stdioItem.optionName}\` and \`${optionName}\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`);
};
// ../../node_modules/execa/lib/stdio/handle.js
var handleStdio = (addProperties3, options, verboseInfo, isSync) => {
let initialFileDescriptors = normalizeStdioOption(options, verboseInfo, isSync).map((stdioOption, fdNumber) => getFileDescriptor({
stdioOption,
fdNumber,
options,
isSync
})), fileDescriptors = getFinalFileDescriptors({
initialFileDescriptors,
addProperties: addProperties3,
options,
isSync
});
return options.stdio = fileDescriptors.map(({ stdioItems }) => forwardStdio(stdioItems)), fileDescriptors;
}, getFileDescriptor = ({ stdioOption, fdNumber, options, isSync }) => {
let optionName = getStreamName(fdNumber), { stdioItems: initialStdioItems, isStdioArray } = initializeStdioItems({
stdioOption,
fdNumber,
options,
optionName
}), direction = getStreamDirection(initialStdioItems, fdNumber, optionName), stdioItems = initialStdioItems.map((stdioItem) => handleNativeStream({
stdioItem,
isStdioArray,
fdNumber,
direction,
isSync
})), normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options), objectMode = getFdObjectMode(normalizedStdioItems, direction);
return validateFileObjectMode(normalizedStdioItems, objectMode), { direction, objectMode, stdioItems: normalizedStdioItems };
}, initializeStdioItems = ({ stdioOption, fdNumber, options, optionName }) => {
let initialStdioItems = [
...(Array.isArray(stdioOption) ? stdioOption : [stdioOption]).map((value) => initializeStdioItem(value, optionName)),
...handleInputOptions(options, fdNumber)
], stdioItems = filterDuplicates(initialStdioItems), isStdioArray = stdioItems.length > 1;
return validateStdioArray(stdioItems, isStdioArray, optionName), validateStreams(stdioItems), { stdioItems, isStdioArray };
}, initializeStdioItem = (value, optionName) => ({
type: getStdioItemType(value, optionName),
value,
optionName
}), validateStdioArray = (stdioItems, isStdioArray, optionName) => {
if (stdioItems.length === 0)
throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);
if (isStdioArray) {
for (let { value, optionName: optionName2 } of stdioItems)
if (INVALID_STDIO_ARRAY_OPTIONS.has(value))
throw new Error(`The \`${optionName2}\` option must not include \`${value}\`.`);
}
}, INVALID_STDIO_ARRAY_OPTIONS = /* @__PURE__ */ new Set(["ignore", "ipc"]), validateStreams = (stdioItems) => {
for (let stdioItem of stdioItems)
validateFileStdio(stdioItem);
}, validateFileStdio = ({ type, value, optionName }) => {
if (isRegularUrl(value))
throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.
For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);
if (isUnknownStdioString(type, value))
throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);
}, validateFileObjectMode = (stdioItems, objectMode) => {
if (!objectMode)
return;
let fileStdioItem = stdioItems.find(({ type }) => FILE_TYPES.has(type));
if (fileStdioItem !== void 0)
throw new TypeError(`The \`${fileStdioItem.optionName}\` option cannot use both files and transforms in objectMode.`);
}, getFinalFileDescriptors = ({ initialFileDescriptors, addProperties: addProperties3, options, isSync }) => {
let fileDescriptors = [];
try {
for (let fileDescriptor of initialFileDescriptors)
fileDescriptors.push(getFinalFileDescriptor({
fileDescriptor,
fileDescriptors,
addProperties: addProperties3,
options,
isSync
}));
return fileDescriptors;
} catch (error) {
throw cleanupCustomStreams(fileDescriptors), error;
}
}, getFinalFileDescriptor = ({
fileDescriptor: { direction, objectMode, stdioItems },
fileDescriptors,
addProperties: addProperties3,
options,
isSync
}) => {
let finalStdioItems = stdioItems.map((stdioItem) => addStreamProperties({
stdioItem,
addProperties: addProperties3,
direction,
options,
fileDescriptors,
isSync
}));
return { direction, objectMode, stdioItems: finalStdioItems };
}, addStreamProperties = ({ stdioItem, addProperties: addProperties3, direction, options, fileDescriptors, isSync }) => {
let duplicateStream = getDuplicateStream({
stdioItem,
direction,
fileDescriptors,
isSync
});
return duplicateStream !== void 0 ? { ...stdioItem, stream: duplicateStream } : {
...stdioItem,
...addProperties3[direction][stdioItem.type](stdioItem, options)
};
}, cleanupCustomStreams = (fileDescriptors) => {
for (let { stdioItems } of fileDescriptors)
for (let { stream } of stdioItems)
stream !== void 0 && !isStandardStream(stream) && stream.destroy();
}, forwardStdio = (stdioItems) => {
if (stdioItems.length > 1)
return stdioItems.some(({ value: value2 }) => value2 === "overlapped") ? "overlapped" : "pipe";
let [{ type, value }] = stdioItems;
return type === "native" ? value : "pipe";
};
// ../../node_modules/execa/lib/stdio/handle-sync.js
var handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, !0), forbiddenIfSync = ({ type, optionName }) => {
throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);
}, forbiddenNativeIfSync = ({ optionName, value }) => ((value === "ipc" || value === "overlapped") && throwInvalidSyncValue(optionName, `"${value}"`), {}), throwInvalidSyncValue = (optionName, value) => {
throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);
}, addProperties = {
generator() {
},
asyncGenerator: forbiddenIfSync,
webStream: forbiddenIfSync,
nodeStream: forbiddenIfSync,
webTransform: forbiddenIfSync,
duplex: forbiddenIfSync,
asyncIterable: forbiddenIfSync,
native: forbiddenNativeIfSync
}, addPropertiesSync = {
input: {
...addProperties,
fileUrl: ({ value }) => ({ contents: [bufferToUint8Array(readFileSync2(value))] }),
filePath: ({ value: { file } }) => ({ contents: [bufferToUint8Array(readFileSync2(file))] }),
fileNumber: forbiddenIfSync,
iterable: ({ value }) => ({ contents: [...value] }),
string: ({ value }) => ({ contents: [value] }),
uint8Array: ({ value }) => ({ contents: [value] })
},
output: {
...addProperties,
fileUrl: ({ value }) => ({ path: value }),
filePath: ({ value: { file, append } }) => ({ path: file, append }),
fileNumber: ({ value }) => ({ path: value }),
iterable: forbiddenIfSync,
string: forbiddenIfSync,
uint8Array: forbiddenIfSync
}
};
// ../../node_modules/execa/lib/io/strip-newline.js
var stripNewline = (value, { stripFinalNewline: stripFinalNewline2 }, fdNumber) => getStripFinalNewline(stripFinalNewline2, fdNumber) && value !== void 0 && !Array.isArray(value) ? stripFinalNewline(value) : value, getStripFinalNewline = (stripFinalNewline2, fdNumber) => fdNumber === "all" ? stripFinalNewline2[1] || stripFinalNewline2[2] : stripFinalNewline2[fdNumber];
// ../../node_modules/execa/lib/transform/generator.js
import { Transform, getDefaultHighWaterMark } from "node:stream";
// ../../node_modules/execa/lib/transform/split.js
var getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped ? void 0 : initializeSplitLines(preserveNewlines, state), splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode ? chunk.flatMap((item) => splitLinesItemSync(item, preserveNewlines)) : splitLinesItemSync(chunk, preserveNewlines), splitLinesItemSync = (chunk, preserveNewlines) => {
let { transform, final } = initializeSplitLines(preserveNewlines, {});
return [...transform(chunk), ...final()];
}, initializeSplitLines = (preserveNewlines, state) => (state.previousChunks = "", {
transform: splitGenerator.bind(void 0, state, preserveNewlines),
final: linesFinal.bind(void 0, state)
}), splitGenerator = function* (state, preserveNewlines, chunk) {
if (typeof chunk != "string") {
yield chunk;
return;
}
let { previousChunks } = state, start = -1;
for (let end = 0; end < chunk.length; end += 1)
if (chunk[end] === `
`) {
let newlineLength = getNewlineLength(chunk, end, preserveNewlines, state), line = chunk.slice(start + 1, end + 1 - newlineLength);
previousChunks.length > 0 && (line = concatString(previousChunks, line), previousChunks = ""), yield line, start = end;
}
start !== chunk.length - 1 && (previousChunks = concatString(previousChunks, chunk.slice(start + 1))), state.previousChunks = previousChunks;
}, getNewlineLength = (chunk, end, preserveNewlines, state) => preserveNewlines ? 0 : (state.isWindowsNewline = end !== 0 && chunk[end - 1] === "\r", state.isWindowsNewline ? 2 : 1), linesFinal = function* ({ previousChunks }) {
previousChunks.length > 0 && (yield previousChunks);
}, getAppendNewlineGenerator = ({ binary, preserveNewlines, readableObjectMode, state }) => binary || preserveNewlines || readableObjectMode ? void 0 : { transform: appendNewlineGenerator.bind(void 0, state) }, appendNewlineGenerator = function* ({ isWindowsNewline = !1 }, chunk) {
let { unixNewline, windowsNewline, LF: LF2, concatBytes } = typeof chunk == "string" ? linesStringInfo : linesUint8ArrayInfo;
if (chunk.at(-1) === LF2) {
yield chunk;
return;
}
yield concatBytes(chunk, isWindowsNewline ? windowsNewline : unixNewline);
}, concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`, linesStringInfo = {
windowsNewline: `\r
`,
unixNewline: `
`,
LF: `
`,
concatBytes: concatString
}, concatUint8Array = (firstChunk, secondChunk) => {
let chunk = new Uint8Array(firstChunk.length + secondChunk.length);
return chunk.set(firstChunk, 0), chunk.set(secondChunk, firstChunk.length), chunk;
}, linesUint8ArrayInfo = {
windowsNewline: new Uint8Array([13, 10]),
unixNewline: new Uint8Array([10]),
LF: 10,
concatBytes: concatUint8Array
};
// ../../node_modules/execa/lib/transform/validate.js
import { Buffer as Buffer2 } from "node:buffer";
var getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode ? void 0 : validateStringTransformInput.bind(void 0, optionName), validateStringTransformInput = function* (optionName, chunk) {
if (typeof chunk != "string" && !isUint8Array(chunk) && !Buffer2.isBuffer(chunk))
throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`);
yield chunk;
}, getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode ? validateObjectTransformReturn.bind(void 0, optionName) : validateStringTransformReturn.bind(void 0, optionName), validateObjectTransformReturn = function* (optionName, chunk) {
validateEmptyReturn(optionName, chunk), yield chunk;
}, validateStringTransformReturn = function* (optionName, chunk) {
if (validateEmptyReturn(optionName, chunk), typeof chunk != "string" && !isUint8Array(chunk))
throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);
yield chunk;
}, validateEmptyReturn = (optionName, chunk) => {
if (chunk == null)
throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.
Instead, \`yield\` should either be called with a value, or not be called at all. For example:
if (condition) { yield value; }`);
};
// ../../node_modules/execa/lib/transform/encoding-transform.js
import { Buffer as Buffer3 } from "node:buffer";
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
var getEncodingTransformGenerator = (binary, encoding, skipped) => {
if (skipped)
return;
if (binary)
return { transform: encodingUint8ArrayGenerator.bind(void 0, new TextEncoder()) };
let stringDecoder = new StringDecoder2(encoding);
return {
transform: encodingStringGenerator.bind(void 0, stringDecoder),
final: encodingStringFinal.bind(void 0, stringDecoder)
};
}, encodingUint8ArrayGenerator = function* (textEncoder3, chunk) {
Buffer3.isBuffer(chunk) ? yield bufferToUint8Array(chunk) : typeof chunk == "string" ? yield textEncoder3.encode(chunk) : yield chunk;
}, encodingStringGenerator = function* (stringDecoder, chunk) {
yield isUint8Array(chunk) ? stringDecoder.write(chunk) : chunk;
}, encodingStringFinal = function* (stringDecoder) {
let lastChunk = stringDecoder.end();
lastChunk !== "" && (yield lastChunk);
};
// ../../node_modules/execa/lib/transform/run-async.js
import { callbackify } from "node:util";
var pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {
state.currentIterable = getChunks(...getChunksArguments);
try {
for await (let chunk of state.currentIterable)
transformStream.push(chunk);
} finally {
delete state.currentIterable;
}
}), transformChunk = async function* (chunk, generators, index) {
if (index === generators.length) {
yield chunk;
return;
}
let { transform = identityGenerator } = generators[index];
for await (let transformedChunk of transform(chunk))
yield* transformChunk(transformedChunk, generators, index + 1);
}, finalChunks = async function* (generators) {
for (let [index, { final }] of Object.entries(generators))
yield* generatorFinalChunks(final, Number(index), generators);
}, generatorFinalChunks = async function* (final, index, generators) {
if (final !== void 0)
for await (let finalChunk of final())
yield* transformChunk(finalChunk, generators, index + 1);
}, destroyTransform = callbackify(async ({ currentIterable }, error) => {
if (currentIterable !== void 0) {
await (error ? currentIterable.throw(error) : currentIterable.return());
return;
}
if (error)
throw error;
}), identityGenerator = function* (chunk) {
yield chunk;
};
// ../../node_modules/execa/lib/transform/run-sync.js
var pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => {
try {
for (let chunk of getChunksSync(...getChunksArguments))
transformStream.push(chunk);
done();
} catch (error) {
done(error);
}
}, runTransformSync = (generators, chunks) => [
...chunks.flatMap((chunk) => [...transformChunkSync(chunk, generators, 0)]),
...finalChunksSync(generators)
], transformChunkSync = function* (chunk, generators, index) {
if (index === generators.length) {
yield chunk;
return;
}
let { transform = identityGenerator2 } = generators[index];
for (let transformedChunk of transform(chunk))
yield* transformChunkSync(transformedChunk, generators, index + 1);
}, finalChunksSync = function* (generators) {
for (let [index, { final }] of Object.entries(generators))
yield* generatorFinalChunksSync(final, Number(index), generators);
}, generatorFinalChunksSync = function* (final, index, generators) {
if (final !== void 0)
for (let finalChunk of final())
yield* transformChunkSync(finalChunk, generators, index + 1);
}, identityGenerator2 = function* (chunk) {
yield chunk;
};
// ../../node_modules/execa/lib/transform/generator.js
var generatorToStream = ({
value,
value: { transform, final, writableObjectMode, readableObjectMode },
optionName
}, { encoding }) => {
let state = {}, generators = addInternalGenerators(value, encoding, optionName), transformAsync = isAsyncGenerator(transform), finalAsync = isAsyncGenerator(final), transformMethod = transformAsync ? pushChunks.bind(void 0, transformChunk, state) : pushChunksSync.bind(void 0, transformChunkSync), finalMethod = transformAsync || finalAsync ? pushChunks.bind(void 0, finalChunks, state) : pushChunksSync.bind(void 0, finalChunksSync), destroyMethod = transformAsync || finalAsync ? destroyTransform.bind(void 0, state) : void 0;
return { stream: new Transform({
writableObjectMode,
writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),
readableObjectMode,
readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),
transform(chunk, encoding2, done) {
transformMethod([chunk, generators, 0], this, done);
},
flush(done) {
finalMethod([generators], this, done);
},
destroy: destroyMethod
}) };
}, runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {
let generators = stdioItems.filter(({ type }) => type === "generator"), reversedGenerators = isInput ? generators.reverse() : generators;
for (let { value, optionName } of reversedGenerators) {
let generators2 = addInternalGenerators(value, encoding, optionName);
chunks = runTransformSync(generators2, chunks);
}
return chunks;
}, addInternalGenerators = ({ transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines }, encoding, optionName) => {
let state = {};
return [
{ transform: getValidateTransformInput(writableObjectMode, optionName) },
getEncodingTransformGenerator(binary, encoding, writableObjectMode),
getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),
{ transform, final },
{ transform: getValidateTransformReturn(readableObjectMode, optionName) },
getAppendNewlineGenerator({
binary,
preserveNewlines,
readableObjectMode,
state
})
].filter(Boolean);
};
// ../../node_modules/execa/lib/io/input-sync.js
var addInputOptionsSync = (fileDescriptors, options) => {
for (let fdNumber of getInputFdNumbers(fileDescriptors))
addInputOptionSync(fileDescriptors, fdNumber, options);
}, getInputFdNumbers = (fileDescriptors) => new Set(Object.entries(fileDescriptors).filter(([, { direction }]) => direction === "input").map(([fdNumber]) => Number(fdNumber))), addInputOptionSync = (fileDescriptors, fdNumber, options) => {
let { stdioItems } = fileDescriptors[fdNumber], allStdioItems = stdioItems.filter(({ contents }) => contents !== void 0);
if (allStdioItems.length === 0)
return;
if (fdNumber !== 0) {
let [{ type, optionName }] = allStdioItems;
throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);
}
let transformedContents = allStdioItems.map(({ contents }) => contents).map((contents) => applySingleInputGeneratorsSync(contents, stdioItems));
options.input = joinToUint8Array(transformedContents);
}, applySingleInputGeneratorsSync = (contents, stdioItems) => {
let newContents = runGeneratorsSync(contents, stdioItems, "utf8", !0);
return validateSerializable(newContents), joinToUint8Array(newContents);
}, validateSerializable = (newContents) => {
let invalidItem = newContents.find((item) => typeof item != "string" && !isUint8Array(item));
if (invalidItem !== void 0)
throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);
};
// ../../node_modules/execa/lib/io/output-sync.js
import { writeFileSync, appendFileSync } from "node:fs";
// ../../node_modules/execa/lib/verbose/output.js
var shouldLogOutput = ({ stdioItems, encoding, verboseInfo, fdNumber }) => fdNumber !== "all" && isFullVerbose(verboseInfo, fdNumber) && !BINARY_ENCODINGS.has(encoding) && fdUsesVerbose(fdNumber) && (stdioItems.some(({ type, value }) => type === "native" && PIPED_STDIO_VALUES.has(value)) || stdioItems.every(({ type }) => TRANSFORM_TYPES.has(type))), fdUsesVerbose = (fdNumber) => fdNumber === 1 || fdNumber === 2, PIPED_STDIO_VALUES = /* @__PURE__ */ new Set(["pipe", "overlapped"]), logLines = async (linesIterable, stream, fdNumber, verboseInfo) => {
for await (let line of linesIterable)
isPipingStream(stream) || logLine(line, fdNumber, verboseInfo);
}, logLinesSync = (linesArray, fdNumber, verboseInfo) => {
for (let line of linesArray)
logLine(line, fdNumber, verboseInfo);
}, isPipingStream = (stream) => stream._readableState.pipes.length > 0, logLine = (line, fdNumber, verboseInfo) => {
let verboseMessage = serializeVerboseMessage(line);
verboseLog({
type: "output",
verboseMessage,
fdNumber,
verboseInfo
});
};
// ../../node_modules/execa/lib/io/output-sync.js
var transformOutputSync = ({ fileDescriptors, syncResult: { output }, options, isMaxBuffer, verboseInfo }) => {
if (output === null)
return { output: Array.from({ length: 3 }) };
let state = {}, outputFiles = /* @__PURE__ */ new Set([]);
return { output: output.map((result, fdNumber) => transformOutputResultSync({
result,
fileDescriptors,
fdNumber,
state,
outputFiles,
isMaxBuffer,
verboseInfo
}, options)), ...state };
}, transformOutputResultSync = ({ result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo }, { buffer, encoding, lines, stripFinalNewline: stripFinalNewline2, maxBuffer }) => {
if (result === null)
return;
let truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer), uint8ArrayResult = bufferToUint8Array(truncatedResult), { stdioItems, objectMode } = fileDescriptors[fdNumber], chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state), { serializedResult, finalResult = serializedResult } = serializeChunks({
chunks,
objectMode,
encoding,
lines,
stripFinalNewline: stripFinalNewline2,
fdNumber
});
logOutputSync({
serializedResult,
fdNumber,
state,
verboseInfo,
encoding,
stdioItems,
objectMode
});
let returnedResult = buffer[fdNumber] ? finalResult : void 0;
try {
return state.error === void 0 && writeToFiles(serializedResult, stdioItems, outputFiles), returnedResult;
} catch (error) {
return state.error = error, returnedResult;
}
}, runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {
try {
return runGeneratorsSync(chunks, stdioItems, encoding, !1);
} catch (error) {
return state.error = error, chunks;
}
}, serializeChunks = ({ chunks, objectMode, encoding, lines, stripFinalNewline: stripFinalNewline2, fdNumber }) => {
if (objectMode)
return { serializedResult: chunks };
if (encoding === "buffer")
return { serializedResult: joinToUint8Array(chunks) };
let serializedResult = joinToString(chunks, encoding);
return lines[fdNumber] ? { serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline2[fdNumber], objectMode) } : { serializedResult };
}, logOutputSync = ({ serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode }) => {
if (!shouldLogOutput({
stdioItems,
encoding,
verboseInfo,
fdNumber
}))
return;
let linesArray = splitLinesSync(serializedResult, !1, objectMode);
try {
logLinesSync(linesArray, fdNumber, verboseInfo);
} catch (error) {
state.error ??= error;
}
}, writeToFiles = (serializedResult, stdioItems, outputFiles) => {
for (let { path: path5, append } of stdioItems.filter(({ type }) => FILE_TYPES.has(type))) {
let pathString = typeof path5 == "string" ? path5 : path5.toString();
append || outputFiles.has(pathString) ? appendFileSync(path5, serializedResult) : (outputFiles.add(pathString), writeFileSync(path5, serializedResult));
}
};
// ../../node_modules/execa/lib/resolve/all-sync.js
var getAllSync = ([, stdout, stderr], options) => {
if (options.all)
return stdout === void 0 ? stderr : stderr === void 0 ? stdout : Array.isArray(stdout) ? Array.isArray(stderr) ? [...stdout, ...stderr] : [...stdout, stripNewline(stderr, options, "all")] : Array.isArray(stderr) ? [stripNewline(stdout, options, "all"), ...stderr] : isUint8Array(stdout) && isUint8Array(stderr) ? concatUint8Arrays([stdout, stderr]) : `${stdout}${stderr}`;
};
// ../../node_modules/execa/lib/resolve/exit-async.js
import { once as once5 } from "node:events";
var waitForExit = async (subprocess, context) => {
let [exitCode, signal] = await waitForExitOrError(subprocess);
return context.isForcefullyTerminated ??= !1, [exitCode, signal];
}, waitForExitOrError = async (subprocess) => {
let [spawnPayload, exitPayload] = await Promise.allSettled([
once5(subprocess, "spawn"),
once5(subprocess, "exit")
]);
return spawnPayload.status === "rejected" ? [] : exitPayload.status === "rejected" ? waitForSubprocessExit(subprocess) : exitPayload.value;
}, waitForSubprocessExit = async (subprocess) => {
try {
return await once5(subprocess, "exit");
} catch {
return waitForSubprocessExit(subprocess);
}
}, waitForSuccessfulExit = async (exitPromise) => {
let [exitCode, signal] = await exitPromise;
if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal))
throw new DiscardedError();
return [exitCode, signal];
}, isSubprocessErrorExit = (exitCode, signal) => exitCode === void 0 && signal === void 0, isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
// ../../node_modules/execa/lib/resolve/exit-sync.js
var getExitResultSync = ({ error, status: exitCode, signal, output }, { maxBuffer }) => {
let resultError = getResultError(error, exitCode, signal), timedOut = resultError?.code === "ETIMEDOUT", isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);
return {
resultError,
exitCode,
signal,
timedOut,
isMaxBuffer
};
}, getResultError = (error, exitCode, signal) => error !== void 0 ? error : isFailedExit(exitCode, signal) ? new DiscardedError() : void 0;
// ../../node_modules/execa/lib/methods/main-sync.js
var execaCoreSync = (rawFile, rawArguments, rawOptions) => {
let { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors } = handleSyncArguments(rawFile, rawArguments, rawOptions), result = spawnSubprocessSync({
file,
commandArguments,
options,
command,
escapedCommand,
verboseInfo,
fileDescriptors,
startTime
});
return handleResult(result, verboseInfo, options);
}, handleSyncArguments = (rawFile, rawArguments, rawOptions) => {
let { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions), syncOptions = normalizeSyncOptions(rawOptions), { file, commandArguments, options } = normalizeOptions(rawFile, rawArguments, syncOptions);
validateSyncOptions(options);
let fileDescriptors = handleStdioSync(options, verboseInfo);
return {
file,
commandArguments,
command,
escapedCommand,
startTime,
verboseInfo,
options,
fileDescriptors
};
}, normalizeSyncOptions = (options) => options.node && !options.ipc ? { ...options, ipc: !1 } : options, validateSyncOptions = ({ ipc, ipcInput, detached, cancelSignal }) => {
ipcInput && throwInvalidSyncOption("ipcInput"), ipc && throwInvalidSyncOption("ipc: true"), detached && throwInvalidSyncOption("detached: true"), cancelSignal && throwInvalidSyncOption("cancelSignal");
}, throwInvalidSyncOption = (value) => {
throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);
}, spawnSubprocessSync = ({ file, commandArguments, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime }) => {
let syncResult = runSubprocessSync({
file,
commandArguments,
options,
command,
escapedCommand,
fileDescriptors,
startTime
});
if (syncResult.failed)
return syncResult;
let { resultError, exitCode, signal, timedOut, isMaxBuffer } = getExitResultSync(syncResult, options), { output, error = resultError } = transformOutputSync({
fileDescriptors,
syncResult,
options,
isMaxBuffer,
verboseInfo
}), stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber)), all = stripNewline(getAllSync(output, options), options, "all");
return getSyncResult({
error,
exitCode,
signal,
timedOut,
isMaxBuffer,
stdio,
all,
options,
command,
escapedCommand,
startTime
});
}, runSubprocessSync = ({ file, commandArguments, options, command, escapedCommand, fileDescriptors, startTime }) => {
try {
addInputOptionsSync(fileDescriptors, options);
let normalizedOptions = normalizeSpawnSyncOptions(options);
return spawnSync(...concatenateShell(file, commandArguments, normalizedOptions));
} catch (error) {
return makeEarlyError({
error,
command,
escapedCommand,
fileDescriptors,
options,
startTime,
isSync: !0
});
}
}, normalizeSpawnSyncOptions = ({ encoding, maxBuffer, ...options }) => ({ ...options, encoding: "buffer", maxBuffer: getMaxBufferSync(maxBuffer) }), getSyncResult = ({ error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime }) => error === void 0 ? makeSuccessResult({
command,
escapedCommand,
stdio,
all,
ipcOutput: [],
options,
startTime
}) : makeError({
error,
command,
escapedCommand,
timedOut,
isCanceled: !1,
isGracefullyCanceled: !1,
isMaxBuffer,
isForcefullyTerminated: !1,
exitCode,
signal,
stdio,
all,
ipcOutput: [],
options,
startTime,
isSync: !0
});
// ../../node_modules/execa/lib/methods/main-async.js
import { setMaxListeners } from "node:events";
import { spawn } from "node:child_process";
// ../../node_modules/execa/lib/ipc/methods.js
import process8 from "node:process";
// ../../node_modules/execa/lib/ipc/get-one.js
import { once as once6, on as on2 } from "node:events";
var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = !0, filter } = {}) => (validateIpcMethod({
methodName: "getOneMessage",
isSubprocess,
ipc,
isConnected: isConnected(anyProcess)
}), getOneMessageAsync({
anyProcess,
channel,
isSubprocess,
filter,
reference
})), getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter, reference }) => {
addReference(channel, reference);
let ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess), controller = new AbortController();
try {
return await Promise.race([
getMessage(ipcEmitter, filter, controller),
throwOnDisconnect2(ipcEmitter, isSubprocess, controller),
throwOnStrictError(ipcEmitter, isSubprocess, controller)
]);
} catch (error) {
throw disconnect(anyProcess), error;
} finally {
controller.abort(), removeReference(channel, reference);
}
}, getMessage = async (ipcEmitter, filter, { signal }) => {
if (filter === void 0) {
let [message] = await once6(ipcEmitter, "message", { signal });
return message;
}
for await (let [message] of on2(ipcEmitter, "message", { signal }))
if (filter(message))
return message;
}, throwOnDisconnect2 = async (ipcEmitter, isSubprocess, { signal }) => {
await once6(ipcEmitter, "disconnect", { signal }), throwOnEarlyDisconnect(isSubprocess);
}, throwOnStrictError = async (ipcEmitter, isSubprocess, { signal }) => {
let [error] = await once6(ipcEmitter, "strict:error", { signal });
throw getStrictResponseError(error, isSubprocess);
};
// ../../node_modules/execa/lib/ipc/get-each.js
import { once as once7, on as on3 } from "node:events";
var getEachMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = !0 } = {}) => loopOnMessages({
anyProcess,
channel,
isSubprocess,
ipc,
shouldAwait: !isSubprocess,
reference
}), loopOnMessages = ({ anyProcess, channel, isSubprocess, ipc, shouldAwait, reference }) => {
validateIpcMethod({
methodName: "getEachMessage",
isSubprocess,
ipc,
isConnected: isConnected(anyProcess)
}), addReference(channel, reference);
let ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess), controller = new AbortController(), state = {};
return stopOnDisconnect(anyProcess, ipcEmitter, controller), abortOnStrictError({
ipcEmitter,
isSubprocess,
controller,
state
}), iterateOnMessages({
anyProcess,
channel,
ipcEmitter,
isSubprocess,
shouldAwait,
controller,
state,
reference
});
}, stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {
try {
await once7(ipcEmitter, "disconnect", { signal: controller.signal }), controller.abort();
} catch {
}
}, abortOnStrictError = async ({ ipcEmitter, isSubprocess, controller, state }) => {
try {
let [error] = await once7(ipcEmitter, "strict:error", { signal: controller.signal });
state.error = getStrictResponseError(error, isSubprocess), controller.abort();
} catch {
}
}, iterateOnMessages = async function* ({ anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference }) {
try {
for await (let [message] of on3(ipcEmitter, "message", { signal: controller.signal }))
throwIfStrictError(state), yield message;
} catch {
throwIfStrictError(state);
} finally {
controller.abort(), removeReference(channel, reference), isSubprocess || disconnect(anyProcess), shouldAwait && await anyProcess;
}
}, throwIfStrictError = ({ error }) => {
if (error)
throw error;
};
// ../../node_modules/execa/lib/ipc/methods.js
var addIpcMethods = (subprocess, { ipc }) => {
Object.assign(subprocess, getIpcMethods(subprocess, !1, ipc));
}, getIpcExport = () => {
let anyProcess = process8, isSubprocess = !0, ipc = process8.channel !== void 0;
return {
...getIpcMethods(anyProcess, isSubprocess, ipc),
getCancelSignal: getCancelSignal.bind(void 0, {
anyProcess,
channel: anyProcess.channel,
isSubprocess,
ipc
})
};
}, getIpcMethods = (anyProcess, isSubprocess, ipc) => ({
sendMessage: sendMessage.bind(void 0, {
anyProcess,
channel: anyProcess.channel,
isSubprocess,
ipc
}),
getOneMessage: getOneMessage.bind(void 0, {
anyProcess,
channel: anyProcess.channel,
isSubprocess,
ipc
}),
getEachMessage: getEachMessage.bind(void 0, {
anyProcess,
channel: anyProcess.channel,
isSubprocess,
ipc
})
});
// ../../node_modules/execa/lib/return/early-error.js
import { ChildProcess as ChildProcess2 } from "node:child_process";
import {
PassThrough,
Readable,
Writable,
Duplex
} from "node:stream";
var handleEarlyError = ({ error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo }) => {
cleanupCustomStreams(fileDescriptors);
let subprocess = new ChildProcess2();
createDummyStreams(subprocess, fileDescriptors), Object.assign(subprocess, { readable, writable, duplex });
let earlyError = makeEarlyError({
error,
command,
escapedCommand,
fileDescriptors,
options,
startTime,
isSync: !1
}), promise2 = handleDummyPromise(earlyError, verboseInfo, options);
return { subprocess, promise: promise2 };
}, createDummyStreams = (subprocess, fileDescriptors) => {
let stdin = createDummyStream(), stdout = createDummyStream(), stderr = createDummyStream(), extraStdio = Array.from({ length: fileDescriptors.length - 3 }, createDummyStream), all = createDummyStream(), stdio = [stdin, stdout, stderr, ...extraStdio];
Object.assign(subprocess, {
stdin,
stdout,
stderr,
all,
stdio
});
}, createDummyStream = () => {
let stream = new PassThrough();
return stream.end(), stream;
}, readable = () => new Readable({ read() {
} }), writable = () => new Writable({ write() {
} }), duplex = () => new Duplex({ read() {
}, write() {
} }), handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);
// ../../node_modules/execa/lib/stdio/handle-async.js
import { createReadStream, createWriteStream } from "node:fs";
import { Buffer as Buffer4 } from "node:buffer";
import { Readable as Readable2, Writable as Writable2, Duplex as Duplex2 } from "node:stream";
var handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, !1), forbiddenIfAsync = ({ type, optionName }) => {
throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);
}, addProperties2 = {
fileNumber: forbiddenIfAsync,
generator: generatorToStream,
asyncGenerator: generatorToStream,
nodeStream: ({ value }) => ({ stream: value }),
webTransform({ value: { transform, writableObjectMode, readableObjectMode } }) {
let objectMode = writableObjectMode || readableObjectMode;
return { stream: Duplex2.fromWeb(transform, { objectMode }) };
},
duplex: ({ value: { transform } }) => ({ stream: transform }),
native() {
}
}, addPropertiesAsync = {
input: {
...addProperties2,
fileUrl: ({ value }) => ({ stream: createReadStream(value) }),
filePath: ({ value: { file } }) => ({ stream: createReadStream(file) }),
webStream: ({ value }) => ({ stream: Readable2.fromWeb(value) }),
iterable: ({ value }) => ({ stream: Readable2.from(value) }),
asyncIterable: ({ value }) => ({ stream: Readable2.from(value) }),
string: ({ value }) => ({ stream: Readable2.from(value) }),
uint8Array: ({ value }) => ({ stream: Readable2.from(Buffer4.from(value)) })
},
output: {
...addProperties2,
fileUrl: ({ value }) => ({ stream: createWriteStream(value) }),
filePath: ({ value: { file, append } }) => ({ stream: createWriteStream(file, append ? { flags: "a" } : {}) }),
webStream: ({ value }) => ({ stream: Writable2.fromWeb(value) }),
iterable: forbiddenIfAsync,
asyncIterable: forbiddenIfAsync,
string: forbiddenIfAsync,
uint8Array: forbiddenIfAsync
}
};
// ../../node_modules/@sindresorhus/merge-streams/index.js
import { on as on4, once as once8 } from "node:events";
import { PassThrough as PassThroughStream, getDefaultHighWaterMark as getDefaultHighWaterMark2 } from "node:stream";
import { finished as finished2 } from "node:stream/promises";
function mergeStreams(streams) {
if (!Array.isArray(streams))
throw new TypeError(`Expected an array, got \`${typeof streams}\`.`);
for (let stream of streams)
validateStream(stream);
let objectMode = streams.some(({ readableObjectMode }) => readableObjectMode), highWaterMark = getHighWaterMark(streams, objectMode), passThroughStream = new MergedStream({
objectMode,
writableHighWaterMark: highWaterMark,
readableHighWaterMark: highWaterMark
});
for (let stream of streams)
passThroughStream.add(stream);
return passThroughStream;
}
var getHighWaterMark = (streams, objectMode) => {
if (streams.length === 0)
return getDefaultHighWaterMark2(objectMode);
let highWaterMarks = streams.filter(({ readableObjectMode }) => readableObjectMode === objectMode).map(({ readableHighWaterMark }) => readableHighWaterMark);
return Math.max(...highWaterMarks);
}, MergedStream = class extends PassThroughStream {
#streams = /* @__PURE__ */ new Set([]);
#ended = /* @__PURE__ */ new Set([]);
#aborted = /* @__PURE__ */ new Set([]);
#onFinished;
#unpipeEvent = /* @__PURE__ */ Symbol("unpipe");
#streamPromises = /* @__PURE__ */ new WeakMap();
add(stream) {
if (validateStream(stream), this.#streams.has(stream))
return;
this.#streams.add(stream), this.#onFinished ??= onMergedStreamFinished(this, this.#streams, this.#unpipeEvent);
let streamPromise = endWhenStreamsDone({
passThroughStream: this,
stream,
streams: this.#streams,
ended: this.#ended,
aborted: this.#aborted,
onFinished: this.#onFinished,
unpipeEvent: this.#unpipeEvent
});
this.#streamPromises.set(stream, streamPromise), stream.pipe(this, { end: !1 });
}
async remove(stream) {
if (validateStream(stream), !this.#streams.has(stream))
return !1;
let streamPromise = this.#streamPromises.get(stream);
return streamPromise === void 0 ? !1 : (this.#streamPromises.delete(stream), stream.unpipe(this), await streamPromise, !0);
}
}, onMergedStreamFinished = async (passThroughStream, streams, unpipeEvent) => {
updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT);
let controller = new AbortController();
try {
await Promise.race([
onMergedStreamEnd(passThroughStream, controller),
onInputStreamsUnpipe(passThroughStream, streams, unpipeEvent, controller)
]);
} finally {
controller.abort(), updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT);
}
}, onMergedStreamEnd = async (passThroughStream, { signal }) => {
try {
await finished2(passThroughStream, { signal, cleanup: !0 });
} catch (error) {
throw errorOrAbortStream(passThroughStream, error), error;
}
}, onInputStreamsUnpipe = async (passThroughStream, streams, unpipeEvent, { signal }) => {
for await (let [unpipedStream] of on4(passThroughStream, "unpipe", { signal }))
streams.has(unpipedStream) && unpipedStream.emit(unpipeEvent);
}, validateStream = (stream) => {
if (typeof stream?.pipe != "function")
throw new TypeError(`Expected a readable stream, got: \`${typeof stream}\`.`);
}, endWhenStreamsDone = async ({ passThroughStream, stream, streams, ended, aborted: aborted2, onFinished, unpipeEvent }) => {
updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM);
let controller = new AbortController();
try {
await Promise.race([
afterMergedStreamFinished(onFinished, stream, controller),
onInputStreamEnd({
passThroughStream,
stream,
streams,
ended,
aborted: aborted2,
controller
}),
onInputStreamUnpipe({
stream,
streams,
ended,
aborted: aborted2,
unpipeEvent,
controller
})
]);
} finally {
controller.abort(), updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM);
}
streams.size > 0 && streams.size === ended.size + aborted2.size && (ended.size === 0 && aborted2.size > 0 ? abortStream(passThroughStream) : endStream(passThroughStream));
}, afterMergedStreamFinished = async (onFinished, stream, { signal }) => {
try {
await onFinished, signal.aborted || abortStream(stream);
} catch (error) {
signal.aborted || errorOrAbortStream(stream, error);
}
}, onInputStreamEnd = async ({ passThroughStream, stream, streams, ended, aborted: aborted2, controller: { signal } }) => {
try {
await finished2(stream, {
signal,
cleanup: !0,
readable: !0,
writable: !1
}), streams.has(stream) && ended.add(stream);
} catch (error) {
if (signal.aborted || !streams.has(stream))
return;
isAbortError(error) ? aborted2.add(stream) : errorStream(passThroughStream, error);
}
}, onInputStreamUnpipe = async ({ stream, streams, ended, aborted: aborted2, unpipeEvent, controller: { signal } }) => {
if (await once8(stream, unpipeEvent, { signal }), !stream.readable)
return once8(signal, "abort", { signal });
streams.delete(stream), ended.delete(stream), aborted2.delete(stream);
}, endStream = (stream) => {
stream.writable && stream.end();
}, errorOrAbortStream = (stream, error) => {
isAbortError(error) ? abortStream(stream) : errorStream(stream, error);
}, isAbortError = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
(stream.readable || stream.writable) && stream.destroy();
}, errorStream = (stream, error) => {
stream.destroyed || (stream.once("error", noop2), stream.destroy(error));
}, noop2 = () => {
}, updateMaxListeners = (passThroughStream, increment2) => {
let maxListeners = passThroughStream.getMaxListeners();
maxListeners !== 0 && maxListeners !== Number.POSITIVE_INFINITY && passThroughStream.setMaxListeners(maxListeners + increment2);
}, PASSTHROUGH_LISTENERS_COUNT = 2, PASSTHROUGH_LISTENERS_PER_STREAM = 1;
// ../../node_modules/execa/lib/io/pipeline.js
import { finished as finished3 } from "node:stream/promises";
var pipeStreams = (source, destination) => {
source.pipe(destination), onSourceFinish(source, destination), onDestinationFinish(source, destination);
}, onSourceFinish = async (source, destination) => {
if (!(isStandardStream(source) || isStandardStream(destination))) {
try {
await finished3(source, { cleanup: !0, readable: !0, writable: !1 });
} catch {
}
endDestinationStream(destination);
}
}, endDestinationStream = (destination) => {
destination.writable && destination.end();
}, onDestinationFinish = async (source, destination) => {
if (!(isStandardStream(source) || isStandardStream(destination))) {
try {
await finished3(destination, { cleanup: !0, readable: !1, writable: !0 });
} catch {
}
abortSourceStream(source);
}
}, abortSourceStream = (source) => {
source.readable && source.destroy();
};
// ../../node_modules/execa/lib/io/output-async.js
var pipeOutputAsync = (subprocess, fileDescriptors, controller) => {
let pipeGroups = /* @__PURE__ */ new Map();
for (let [fdNumber, { stdioItems, direction }] of Object.entries(fileDescriptors)) {
for (let { stream } of stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type)))
pipeTransform(subprocess, stream, direction, fdNumber);
for (let { stream } of stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type)))
pipeStdioItem({
subprocess,
stream,
direction,
fdNumber,
pipeGroups,
controller
});
}
for (let [outputStream, inputStreams] of pipeGroups.entries()) {
let inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);
pipeStreams(inputStream, outputStream);
}
}, pipeTransform = (subprocess, stream, direction, fdNumber) => {
direction === "output" ? pipeStreams(subprocess.stdio[fdNumber], stream) : pipeStreams(stream, subprocess.stdio[fdNumber]);
let streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];
streamProperty !== void 0 && (subprocess[streamProperty] = stream), subprocess.stdio[fdNumber] = stream;
}, SUBPROCESS_STREAM_PROPERTIES = ["stdin", "stdout", "stderr"], pipeStdioItem = ({ subprocess, stream, direction, fdNumber, pipeGroups, controller }) => {
if (stream === void 0)
return;
setStandardStreamMaxListeners(stream, controller);
let [inputStream, outputStream] = direction === "output" ? [stream, subprocess.stdio[fdNumber]] : [subprocess.stdio[fdNumber], stream], outputStreams = pipeGroups.get(inputStream) ?? [];
pipeGroups.set(inputStream, [...outputStreams, outputStream]);
}, setStandardStreamMaxListeners = (stream, { signal }) => {
isStandardStream(stream) && incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);
}, MAX_LISTENERS_INCREMENT = 2;
// ../../node_modules/execa/lib/terminate/cleanup.js
import { addAbortListener as addAbortListener2 } from "node:events";
// ../../node_modules/execa/node_modules/signal-exit/dist/mjs/signals.js
var signals = [];
signals.push("SIGHUP", "SIGINT", "SIGTERM");
process.platform !== "win32" && signals.push(
"SIGALRM",
"SIGABRT",
"SIGVTALRM",
"SIGXCPU",
"SIGXFSZ",
"SIGUSR2",
"SIGTRAP",
"SIGSYS",
"SIGQUIT",
"SIGIOT"
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
);
process.platform === "linux" && signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
// ../../node_modules/execa/node_modules/signal-exit/dist/mjs/index.js
var processOk = (process10) => !!process10 && typeof process10 == "object" && typeof process10.removeListener == "function" && typeof process10.emit == "function" && typeof process10.reallyExit == "function" && typeof process10.listeners == "function" && typeof process10.kill == "function" && typeof process10.pid == "number" && typeof process10.on == "function", kExitEmitter = /* @__PURE__ */ Symbol.for("signal-exit emitter"), global2 = globalThis, ObjectDefineProperty = Object.defineProperty.bind(Object), Emitter = class {
emitted = {
afterExit: !1,
exit: !1
};
listeners = {
afterExit: [],
exit: []
};
count = 0;
id = Math.random();
constructor() {
if (global2[kExitEmitter])
return global2[kExitEmitter];
ObjectDefineProperty(global2, kExitEmitter, {
value: this,
writable: !1,
enumerable: !1,
configurable: !1
});
}
on(ev, fn) {
this.listeners[ev].push(fn);
}
removeListener(ev, fn) {
let list = this.listeners[ev], i2 = list.indexOf(fn);
i2 !== -1 && (i2 === 0 && list.length === 1 ? list.length = 0 : list.splice(i2, 1));
}
emit(ev, code, signal) {
if (this.emitted[ev])
return !1;
this.emitted[ev] = !0;
let ret = !1;
for (let fn of this.listeners[ev])
ret = fn(code, signal) === !0 || ret;
return ev === "exit" && (ret = this.emit("afterExit", code, signal) || ret), ret;
}
}, SignalExitBase = class {
}, signalExitWrap = (handler) => ({
onExit(cb, opts) {
return handler.onExit(cb, opts);
},
load() {
return handler.load();
},
unload() {
return handler.unload();
}
}), SignalExitFallback = class extends SignalExitBase {
onExit() {
return () => {
};
}
load() {
}
unload() {
}
}, SignalExit = class extends SignalExitBase {
// "SIGHUP" throws an `ENOSYS` error on Windows,
// so use a supported signal instead
/* c8 ignore start */
#hupSig = process9.platform === "win32" ? "SIGINT" : "SIGHUP";
/* c8 ignore stop */
#emitter = new Emitter();
#process;
#originalProcessEmit;
#originalProcessReallyExit;
#sigListeners = {};
#loaded = !1;
constructor(process10) {
super(), this.#process = process10, this.#sigListeners = {};
for (let sig of signals)
this.#sigListeners[sig] = () => {
let listeners = this.#process.listeners(sig), { count: count2 } = this.#emitter, p = process10;
if (typeof p.__signal_exit_emitter__ == "object" && typeof p.__signal_exit_emitter__.count == "number" && (count2 += p.__signal_exit_emitter__.count), listeners.length === count2) {
this.unload();
let ret = this.#emitter.emit("exit", null, sig), s = sig === "SIGHUP" ? this.#hupSig : sig;
ret || process10.kill(process10.pid, s);
}
};
this.#originalProcessReallyExit = process10.reallyExit, this.#originalProcessEmit = process10.emit;
}
onExit(cb, opts) {
if (!processOk(this.#process))
return () => {
};
this.#loaded === !1 && this.load();
let ev = opts?.alwaysLast ? "afterExit" : "exit";
return this.#emitter.on(ev, cb), () => {
this.#emitter.removeListener(ev, cb), this.#emitter.listeners.exit.length === 0 && this.#emitter.listeners.afterExit.length === 0 && this.unload();
};
}
load() {
if (!this.#loaded) {
this.#loaded = !0, this.#emitter.count += 1;
for (let sig of signals)
try {
let fn = this.#sigListeners[sig];
fn && this.#process.on(sig, fn);
} catch {
}
this.#process.emit = (ev, ...a2) => this.#processEmit(ev, ...a2), this.#process.reallyExit = (code) => this.#processReallyExit(code);
}
}
unload() {
this.#loaded && (this.#loaded = !1, signals.forEach((sig) => {
let listener = this.#sigListeners[sig];
if (!listener)
throw new Error("Listener not defined for signal: " + sig);
try {
this.#process.removeListener(sig, listener);
} catch {
}
}), this.#process.emit = this.#originalProcessEmit, this.#process.reallyExit = this.#originalProcessReallyExit, this.#emitter.count -= 1);
}
#processReallyExit(code) {
return processOk(this.#process) ? (this.#process.exitCode = code || 0, this.#emitter.emit("exit", this.#process.exitCode, null), this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode)) : 0;
}
#processEmit(ev, ...args) {
let og = this.#originalProcessEmit;
if (ev === "exit" && processOk(this.#process)) {
typeof args[0] == "number" && (this.#process.exitCode = args[0]);
let ret = og.call(this.#process, ev, ...args);
return this.#emitter.emit("exit", this.#process.exitCode, null), ret;
} else
return og.call(this.#process, ev, ...args);
}
}, process9 = globalThis.process, {
/**
* Called when the process is exiting, whether via signal, explicit
* exit, or running out of stuff to do.
*
* If the global process object is not suitable for instrumentation,
* then this will be a no-op.
*
* Returns a function that may be used to unload signal-exit.
*/
onExit,
/**
* Load the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
load,
/**
* Unload the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
unload
} = signalExitWrap(processOk(process9) ? new SignalExit(process9) : new SignalExitFallback());
// ../../node_modules/execa/lib/terminate/cleanup.js
var cleanupOnExit = (subprocess, { cleanup, detached }, { signal }) => {
if (!cleanup || detached)
return;
let removeExitHandler = onExit(() => {
subprocess.kill();
});
addAbortListener2(signal, () => {
removeExitHandler();
});
};
// ../../node_modules/execa/lib/pipe/pipe-arguments.js
var normalizePipeArguments = ({ source, sourcePromise, boundOptions, createNested }, ...pipeArguments) => {
let startTime = getStartTime(), {
destination,
destinationStream,
destinationError,
from,
unpipeSignal
} = getDestinationStream(boundOptions, createNested, pipeArguments), { sourceStream, sourceError } = getSourceStream(source, from), { options: sourceOptions, fileDescriptors } = SUBPROCESS_OPTIONS.get(source);
return {
sourcePromise,
sourceStream,
sourceOptions,
sourceError,
destination,
destinationStream,
destinationError,
unpipeSignal,
fileDescriptors,
startTime
};
}, getDestinationStream = (boundOptions, createNested, pipeArguments) => {
try {
let {
destination,
pipeOptions: { from, to, unpipeSignal } = {}
} = getDestination(boundOptions, createNested, ...pipeArguments), destinationStream = getToStream(destination, to);
return {
destination,
destinationStream,
from,
unpipeSignal
};
} catch (error) {
return { destinationError: error };
}
}, getDestination = (boundOptions, createNested, firstArgument, ...pipeArguments) => {
if (Array.isArray(firstArgument))
return { destination: createNested(mapDestinationArguments, boundOptions)(firstArgument, ...pipeArguments), pipeOptions: boundOptions };
if (typeof firstArgument == "string" || firstArgument instanceof URL || isDenoExecPath(firstArgument)) {
if (Object.keys(boundOptions).length > 0)
throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');
let [rawFile, rawArguments, rawOptions] = normalizeParameters(firstArgument, ...pipeArguments);
return { destination: createNested(mapDestinationArguments)(rawFile, rawArguments, rawOptions), pipeOptions: rawOptions };
}
if (SUBPROCESS_OPTIONS.has(firstArgument)) {
if (Object.keys(boundOptions).length > 0)
throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");
return { destination: firstArgument, pipeOptions: pipeArguments[0] };
}
throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);
}, mapDestinationArguments = ({ options }) => ({ options: { ...options, stdin: "pipe", piped: !0 } }), getSourceStream = (source, from) => {
try {
return { sourceStream: getFromStream(source, from) };
} catch (error) {
return { sourceError: error };
}
};
// ../../node_modules/execa/lib/pipe/throw.js
var handlePipeArgumentsError = ({
sourceStream,
sourceError,
destinationStream,
destinationError,
fileDescriptors,
sourceOptions,
startTime
}) => {
let error = getPipeArgumentsError({
sourceStream,
sourceError,
destinationStream,
destinationError
});
if (error !== void 0)
throw createNonCommandError({
error,
fileDescriptors,
sourceOptions,
startTime
});
}, getPipeArgumentsError = ({ sourceStream, sourceError, destinationStream, destinationError }) => {
if (sourceError !== void 0 && destinationError !== void 0)
return destinationError;
if (destinationError !== void 0)
return abortSourceStream(sourceStream), destinationError;
if (sourceError !== void 0)
return endDestinationStream(destinationStream), sourceError;
}, createNonCommandError = ({ error, fileDescriptors, sourceOptions, startTime }) => makeEarlyError({
error,
command: PIPE_COMMAND_MESSAGE,
escapedCommand: PIPE_COMMAND_MESSAGE,
fileDescriptors,
options: sourceOptions,
startTime,
isSync: !1
}), PIPE_COMMAND_MESSAGE = "source.pipe(destination)";
// ../../node_modules/execa/lib/pipe/sequence.js
var waitForBothSubprocesses = async (subprocessPromises) => {
let [
{ status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason },
{ status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason }
] = await subprocessPromises;
if (destinationResult.pipedFrom.includes(sourceResult) || destinationResult.pipedFrom.push(sourceResult), destinationStatus === "rejected")
throw destinationResult;
if (sourceStatus === "rejected")
throw sourceResult;
return destinationResult;
};
// ../../node_modules/execa/lib/pipe/streaming.js
import { finished as finished4 } from "node:stream/promises";
var pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => {
let mergedStream = MERGED_STREAMS.has(destinationStream) ? pipeMoreSubprocessStream(sourceStream, destinationStream) : pipeFirstSubprocessStream(sourceStream, destinationStream);
return incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal), incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal), cleanupMergedStreamsMap(destinationStream), mergedStream;
}, pipeFirstSubprocessStream = (sourceStream, destinationStream) => {
let mergedStream = mergeStreams([sourceStream]);
return pipeStreams(mergedStream, destinationStream), MERGED_STREAMS.set(destinationStream, mergedStream), mergedStream;
}, pipeMoreSubprocessStream = (sourceStream, destinationStream) => {
let mergedStream = MERGED_STREAMS.get(destinationStream);
return mergedStream.add(sourceStream), mergedStream;
}, cleanupMergedStreamsMap = async (destinationStream) => {
try {
await finished4(destinationStream, { cleanup: !0, readable: !1, writable: !0 });
} catch {
}
MERGED_STREAMS.delete(destinationStream);
}, MERGED_STREAMS = /* @__PURE__ */ new WeakMap(), SOURCE_LISTENERS_PER_PIPE = 2, DESTINATION_LISTENERS_PER_PIPE = 1;
// ../../node_modules/execa/lib/pipe/abort.js
import { aborted } from "node:util";
var unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === void 0 ? [] : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)], unpipeOnSignalAbort = async (unpipeSignal, { sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime }) => {
await aborted(unpipeSignal, sourceStream), await mergedStream.remove(sourceStream);
let error = new Error("Pipe canceled by `unpipeSignal` option.");
throw createNonCommandError({
error,
fileDescriptors,
sourceOptions,
startTime
});
};
// ../../node_modules/execa/lib/pipe/setup.js
var pipeToSubprocess = (sourceInfo, ...pipeArguments) => {
if (isPlainObject(pipeArguments[0]))
return pipeToSubprocess.bind(void 0, {
...sourceInfo,
boundOptions: { ...sourceInfo.boundOptions, ...pipeArguments[0] }
});
let { destination, ...normalizedInfo } = normalizePipeArguments(sourceInfo, ...pipeArguments), promise2 = handlePipePromise({ ...normalizedInfo, destination });
return promise2.pipe = pipeToSubprocess.bind(void 0, {
...sourceInfo,
source: destination,
sourcePromise: promise2,
boundOptions: {}
}), promise2;
}, handlePipePromise = async ({
sourcePromise,
sourceStream,
sourceOptions,
sourceError,
destination,
destinationStream,
destinationError,
unpipeSignal,
fileDescriptors,
startTime
}) => {
let subprocessPromises = getSubprocessPromises(sourcePromise, destination);
handlePipeArgumentsError({
sourceStream,
sourceError,
destinationStream,
destinationError,
fileDescriptors,
sourceOptions,
startTime
});
let maxListenersController = new AbortController();
try {
let mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);
return await Promise.race([
waitForBothSubprocesses(subprocessPromises),
...unpipeOnAbort(unpipeSignal, {
sourceStream,
mergedStream,
sourceOptions,
fileDescriptors,
startTime
})
]);
} finally {
maxListenersController.abort();
}
}, getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);
// ../../node_modules/execa/lib/io/contents.js
import { setImmediate } from "node:timers/promises";
// ../../node_modules/execa/lib/io/iterate.js
import { on as on5 } from "node:events";
import { getDefaultHighWaterMark as getDefaultHighWaterMark3 } from "node:stream";
var iterateOnSubprocessStream = ({ subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines }) => {
let controller = new AbortController();
return stopReadingOnExit(subprocess, controller), iterateOnStream({
stream: subprocessStdout,
controller,
binary,
shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode,
encoding,
shouldSplit: !subprocessStdout.readableObjectMode,
preserveNewlines
});
}, stopReadingOnExit = async (subprocess, controller) => {
try {
await subprocess;
} catch {
} finally {
controller.abort();
}
}, iterateForResult = ({ stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewline2, allMixed }) => {
let controller = new AbortController();
stopReadingOnStreamEnd(onStreamEnd, controller, stream);
let objectMode = stream.readableObjectMode && !allMixed;
return iterateOnStream({
stream,
controller,
binary: encoding === "buffer",
shouldEncode: !objectMode,
encoding,
shouldSplit: !objectMode && lines,
preserveNewlines: !stripFinalNewline2
});
}, stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {
try {
await onStreamEnd;
} catch {
stream.destroy();
} finally {
controller.abort();
}
}, iterateOnStream = ({ stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => {
let onStdoutChunk = on5(stream, "data", {
signal: controller.signal,
highWaterMark: HIGH_WATER_MARK,
// Backward compatibility with older name for this option
// See https://github.com/nodejs/node/pull/52080#discussion_r1525227861
// @todo Remove after removing support for Node 21
highWatermark: HIGH_WATER_MARK
});
return iterateOnData({
onStdoutChunk,
controller,
binary,
shouldEncode,
encoding,
shouldSplit,
preserveNewlines
});
}, DEFAULT_OBJECT_HIGH_WATER_MARK = getDefaultHighWaterMark3(!0), HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK, iterateOnData = async function* ({ onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) {
let generators = getGenerators({
binary,
shouldEncode,
encoding,
shouldSplit,
preserveNewlines
});
try {
for await (let [chunk] of onStdoutChunk)
yield* transformChunkSync(chunk, generators, 0);
} catch (error) {
if (!controller.signal.aborted)
throw error;
} finally {
yield* finalChunksSync(generators);
}
}, getGenerators = ({ binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => [
getEncodingTransformGenerator(binary, encoding, !shouldEncode),
getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {})
].filter(Boolean);
// ../../node_modules/execa/lib/io/contents.js
var getStreamOutput = async ({ stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => {
let logPromise = logOutputAsync({
stream,
onStreamEnd,
fdNumber,
encoding,
allMixed,
verboseInfo,
streamInfo
});
if (!buffer) {
await Promise.all([resumeStream(stream), logPromise]);
return;
}
let stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline2, fdNumber), iterable = iterateForResult({
stream,
onStreamEnd,
lines,
encoding,
stripFinalNewline: stripFinalNewlineValue,
allMixed
}), [output] = await Promise.all([
getStreamContents2({
stream,
iterable,
fdNumber,
encoding,
maxBuffer,
lines
}),
logPromise
]);
return output;
}, logOutputAsync = async ({ stream, onStreamEnd, fdNumber, encoding, allMixed, verboseInfo, streamInfo: { fileDescriptors } }) => {
if (!shouldLogOutput({
stdioItems: fileDescriptors[fdNumber]?.stdioItems,
encoding,
verboseInfo,
fdNumber
}))
return;
let linesIterable = iterateForResult({
stream,
onStreamEnd,
lines: !0,
encoding,
stripFinalNewline: !0,
allMixed
});
await logLines(linesIterable, stream, fdNumber, verboseInfo);
}, resumeStream = async (stream) => {
await setImmediate(), stream.readableFlowing === null && stream.resume();
}, getStreamContents2 = async ({ stream, stream: { readableObjectMode }, iterable, fdNumber, encoding, maxBuffer, lines }) => {
try {
return readableObjectMode || lines ? await getStreamAsArray(iterable, { maxBuffer }) : encoding === "buffer" ? new Uint8Array(await getStreamAsArrayBuffer(iterable, { maxBuffer })) : await getStreamAsString(iterable, { maxBuffer });
} catch (error) {
return handleBufferedData(handleMaxBuffer({
error,
stream,
readableObjectMode,
lines,
encoding,
fdNumber
}));
}
}, getBufferedData = async (streamPromise) => {
try {
return await streamPromise;
} catch (error) {
return handleBufferedData(error);
}
}, handleBufferedData = ({ bufferedData }) => isArrayBuffer(bufferedData) ? new Uint8Array(bufferedData) : bufferedData;
// ../../node_modules/execa/lib/resolve/wait-stream.js
import { finished as finished5 } from "node:stream/promises";
var waitForStream = async (stream, fdNumber, streamInfo, { isSameDirection, stopOnExit = !1 } = {}) => {
let state = handleStdinDestroy(stream, streamInfo), abortController = new AbortController();
try {
await Promise.race([
...stopOnExit ? [streamInfo.exitPromise] : [],
finished5(stream, { cleanup: !0, signal: abortController.signal })
]);
} catch (error) {
state.stdinCleanedUp || handleStreamError(error, fdNumber, streamInfo, isSameDirection);
} finally {
abortController.abort();
}
}, handleStdinDestroy = (stream, { originalStreams: [originalStdin], subprocess }) => {
let state = { stdinCleanedUp: !1 };
return stream === originalStdin && spyOnStdinDestroy(stream, subprocess, state), state;
}, spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {
let { _destroy } = subprocessStdin;
subprocessStdin._destroy = (...destroyArguments) => {
setStdinCleanedUp(subprocess, state), _destroy.call(subprocessStdin, ...destroyArguments);
};
}, setStdinCleanedUp = ({ exitCode, signalCode }, state) => {
(exitCode !== null || signalCode !== null) && (state.stdinCleanedUp = !0);
}, handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {
if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection))
throw error;
}, shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = !0) => streamInfo.propagating ? isStreamEpipe(error) || isStreamAbort(error) : (streamInfo.propagating = !0, isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection ? isStreamEpipe(error) : isStreamAbort(error)), isInputFileDescriptor = ({ fileDescriptors }, fdNumber) => fdNumber !== "all" && fileDescriptors[fdNumber].direction === "input", isStreamAbort = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", isStreamEpipe = (error) => error?.code === "EPIPE";
// ../../node_modules/execa/lib/resolve/stdio.js
var waitForStdioStreams = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({
stream,
fdNumber,
encoding,
buffer: buffer[fdNumber],
maxBuffer: maxBuffer[fdNumber],
lines: lines[fdNumber],
allMixed: !1,
stripFinalNewline: stripFinalNewline2,
verboseInfo,
streamInfo
})), waitForSubprocessStream = async ({ stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => {
if (!stream)
return;
let onStreamEnd = waitForStream(stream, fdNumber, streamInfo);
if (isInputFileDescriptor(streamInfo, fdNumber)) {
await onStreamEnd;
return;
}
let [output] = await Promise.all([
getStreamOutput({
stream,
onStreamEnd,
fdNumber,
encoding,
buffer,
maxBuffer,
lines,
allMixed,
stripFinalNewline: stripFinalNewline2,
verboseInfo,
streamInfo
}),
onStreamEnd
]);
return output;
};
// ../../node_modules/execa/lib/resolve/all-async.js
var makeAllStream = ({ stdout, stderr }, { all }) => all && (stdout || stderr) ? mergeStreams([stdout, stderr].filter(Boolean)) : void 0, waitForAllStream = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => waitForSubprocessStream({
...getAllStream(subprocess, buffer),
fdNumber: "all",
encoding,
maxBuffer: maxBuffer[1] + maxBuffer[2],
lines: lines[1] || lines[2],
allMixed: getAllMixed(subprocess),
stripFinalNewline: stripFinalNewline2,
verboseInfo,
streamInfo
}), getAllStream = ({ stdout, stderr, all }, [, bufferStdout, bufferStderr]) => {
let buffer = bufferStdout || bufferStderr;
return buffer ? bufferStdout ? bufferStderr ? { stream: all, buffer } : { stream: stdout, buffer } : { stream: stderr, buffer } : { stream: all, buffer };
}, getAllMixed = ({ all, stdout, stderr }) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode;
// ../../node_modules/execa/lib/resolve/wait-subprocess.js
import { once as once9 } from "node:events";
// ../../node_modules/execa/lib/verbose/ipc.js
var shouldLogIpc = (verboseInfo) => isFullVerbose(verboseInfo, "ipc"), logIpcOutput = (message, verboseInfo) => {
let verboseMessage = serializeVerboseMessage(message);
verboseLog({
type: "ipc",
verboseMessage,
fdNumber: "ipc",
verboseInfo
});
};
// ../../node_modules/execa/lib/ipc/buffer-messages.js
var waitForIpcOutput = async ({
subprocess,
buffer: bufferArray,
maxBuffer: maxBufferArray,
ipc,
ipcOutput,
verboseInfo
}) => {
if (!ipc)
return ipcOutput;
let isVerbose2 = shouldLogIpc(verboseInfo), buffer = getFdSpecificValue(bufferArray, "ipc"), maxBuffer = getFdSpecificValue(maxBufferArray, "ipc");
for await (let message of loopOnMessages({
anyProcess: subprocess,
channel: subprocess.channel,
isSubprocess: !1,
ipc,
shouldAwait: !1,
reference: !0
}))
buffer && (checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer), ipcOutput.push(message)), isVerbose2 && logIpcOutput(message, verboseInfo);
return ipcOutput;
}, getBufferedIpcOutput = async (ipcOutputPromise, ipcOutput) => (await Promise.allSettled([ipcOutputPromise]), ipcOutput);
// ../../node_modules/execa/lib/resolve/wait-subprocess.js
var waitForSubprocessResult = async ({
subprocess,
options: {
encoding,
buffer,
maxBuffer,
lines,
timeoutDuration: timeout,
cancelSignal,
gracefulCancel,
forceKillAfterDelay,
stripFinalNewline: stripFinalNewline2,
ipc,
ipcInput
},
context,
verboseInfo,
fileDescriptors,
originalStreams,
onInternalError,
controller
}) => {
let exitPromise = waitForExit(subprocess, context), streamInfo = {
originalStreams,
fileDescriptors,
subprocess,
exitPromise,
propagating: !1
}, stdioPromises = waitForStdioStreams({
subprocess,
encoding,
buffer,
maxBuffer,
lines,
stripFinalNewline: stripFinalNewline2,
verboseInfo,
streamInfo
}), allPromise = waitForAllStream({
subprocess,
encoding,
buffer,
maxBuffer,
lines,
stripFinalNewline: stripFinalNewline2,
verboseInfo,
streamInfo
}), ipcOutput = [], ipcOutputPromise = waitForIpcOutput({
subprocess,
buffer,
maxBuffer,
ipc,
ipcOutput,
verboseInfo
}), originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo), customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);
try {
return await Promise.race([
Promise.all([
{},
waitForSuccessfulExit(exitPromise),
Promise.all(stdioPromises),
allPromise,
ipcOutputPromise,
sendIpcInput(subprocess, ipcInput),
...originalPromises,
...customStreamsEndPromises
]),
onInternalError,
throwOnSubprocessError(subprocess, controller),
...throwOnTimeout(subprocess, timeout, context, controller),
...throwOnCancel({
subprocess,
cancelSignal,
gracefulCancel,
context,
controller
}),
...throwOnGracefulCancel({
subprocess,
cancelSignal,
gracefulCancel,
forceKillAfterDelay,
context,
controller
})
]);
} catch (error) {
return context.terminationReason ??= "other", Promise.all([
{ error },
exitPromise,
Promise.all(stdioPromises.map((stdioPromise) => getBufferedData(stdioPromise))),
getBufferedData(allPromise),
getBufferedIpcOutput(ipcOutputPromise, ipcOutput),
Promise.allSettled(originalPromises),
Promise.allSettled(customStreamsEndPromises)
]);
}
}, waitForOriginalStreams = (originalStreams, subprocess, streamInfo) => originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber] ? void 0 : waitForStream(stream, fdNumber, streamInfo)), waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({ stdioItems }, fdNumber) => stdioItems.filter(({ value, stream = value }) => isStream(stream, { checkOpen: !1 }) && !isStandardStream(stream)).map(({ type, value, stream = value }) => waitForStream(stream, fdNumber, streamInfo, {
isSameDirection: TRANSFORM_TYPES.has(type),
stopOnExit: type === "native"
}))), throwOnSubprocessError = async (subprocess, { signal }) => {
let [error] = await once9(subprocess, "error", { signal });
throw error;
};
// ../../node_modules/execa/lib/convert/concurrent.js
var initializeConcurrentStreams = () => ({
readableDestroy: /* @__PURE__ */ new WeakMap(),
writableFinal: /* @__PURE__ */ new WeakMap(),
writableDestroy: /* @__PURE__ */ new WeakMap()
}), addConcurrentStream = (concurrentStreams, stream, waitName) => {
let weakMap = concurrentStreams[waitName];
weakMap.has(stream) || weakMap.set(stream, []);
let promises = weakMap.get(stream), promise2 = createDeferred();
return promises.push(promise2), { resolve: promise2.resolve.bind(promise2), promises };
}, waitForConcurrentStreams = async ({ resolve: resolve4, promises }, subprocess) => {
resolve4();
let [isSubprocessExit] = await Promise.race([
Promise.allSettled([!0, subprocess]),
Promise.all([!1, ...promises])
]);
return !isSubprocessExit;
};
// ../../node_modules/execa/lib/convert/readable.js
import { Readable as Readable3 } from "node:stream";
import { callbackify as callbackify2 } from "node:util";
// ../../node_modules/execa/lib/convert/shared.js
import { finished as finished6 } from "node:stream/promises";
var safeWaitForSubprocessStdin = async (subprocessStdin) => {
if (subprocessStdin !== void 0)
try {
await waitForSubprocessStdin(subprocessStdin);
} catch {
}
}, safeWaitForSubprocessStdout = async (subprocessStdout) => {
if (subprocessStdout !== void 0)
try {
await waitForSubprocessStdout(subprocessStdout);
} catch {
}
}, waitForSubprocessStdin = async (subprocessStdin) => {
await finished6(subprocessStdin, { cleanup: !0, readable: !1, writable: !0 });
}, waitForSubprocessStdout = async (subprocessStdout) => {
await finished6(subprocessStdout, { cleanup: !0, readable: !0, writable: !1 });
}, waitForSubprocess = async (subprocess, error) => {
if (await subprocess, error)
throw error;
}, destroyOtherStream = (stream, isOpen, error) => {
error && !isStreamAbort(error) ? stream.destroy(error) : isOpen && stream.destroy();
};
// ../../node_modules/execa/lib/convert/readable.js
var createReadable = ({ subprocess, concurrentStreams, encoding }, { from, binary: binaryOption = !0, preserveNewlines = !0 } = {}) => {
let binary = binaryOption || BINARY_ENCODINGS.has(encoding), { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams), { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary), { read, onStdoutDataDone } = getReadableMethods({
subprocessStdout,
subprocess,
binary,
encoding,
preserveNewlines
}), readable2 = new Readable3({
read,
destroy: callbackify2(onReadableDestroy.bind(void 0, { subprocessStdout, subprocess, waitReadableDestroy })),
highWaterMark: readableHighWaterMark,
objectMode: readableObjectMode,
encoding: readableEncoding
});
return onStdoutFinished({
subprocessStdout,
onStdoutDataDone,
readable: readable2,
subprocess
}), readable2;
}, getSubprocessStdout = (subprocess, from, concurrentStreams) => {
let subprocessStdout = getFromStream(subprocess, from), waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, "readableDestroy");
return { subprocessStdout, waitReadableDestroy };
}, getReadableOptions = ({ readableEncoding, readableObjectMode, readableHighWaterMark }, binary) => binary ? { readableEncoding, readableObjectMode, readableHighWaterMark } : { readableEncoding, readableObjectMode: !0, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK }, getReadableMethods = ({ subprocessStdout, subprocess, binary, encoding, preserveNewlines }) => {
let onStdoutDataDone = createDeferred(), onStdoutData = iterateOnSubprocessStream({
subprocessStdout,
subprocess,
binary,
shouldEncode: !binary,
encoding,
preserveNewlines
});
return {
read() {
onRead(this, onStdoutData, onStdoutDataDone);
},
onStdoutDataDone
};
}, onRead = async (readable2, onStdoutData, onStdoutDataDone) => {
try {
let { value, done } = await onStdoutData.next();
done ? onStdoutDataDone.resolve() : readable2.push(value);
} catch {
}
}, onStdoutFinished = async ({ subprocessStdout, onStdoutDataDone, readable: readable2, subprocess, subprocessStdin }) => {
try {
await waitForSubprocessStdout(subprocessStdout), await subprocess, await safeWaitForSubprocessStdin(subprocessStdin), await onStdoutDataDone, readable2.readable && readable2.push(null);
} catch (error) {
await safeWaitForSubprocessStdin(subprocessStdin), destroyOtherReadable(readable2, error);
}
}, onReadableDestroy = async ({ subprocessStdout, subprocess, waitReadableDestroy }, error) => {
await waitForConcurrentStreams(waitReadableDestroy, subprocess) && (destroyOtherReadable(subprocessStdout, error), await waitForSubprocess(subprocess, error));
}, destroyOtherReadable = (stream, error) => {
destroyOtherStream(stream, stream.readable, error);
};
// ../../node_modules/execa/lib/convert/writable.js
import { Writable as Writable3 } from "node:stream";
import { callbackify as callbackify3 } from "node:util";
var createWritable = ({ subprocess, concurrentStreams }, { to } = {}) => {
let { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams), writable2 = new Writable3({
...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),
destroy: callbackify3(onWritableDestroy.bind(void 0, {
subprocessStdin,
subprocess,
waitWritableFinal,
waitWritableDestroy
})),
highWaterMark: subprocessStdin.writableHighWaterMark,
objectMode: subprocessStdin.writableObjectMode
});
return onStdinFinished(subprocessStdin, writable2), writable2;
}, getSubprocessStdin = (subprocess, to, concurrentStreams) => {
let subprocessStdin = getToStream(subprocess, to), waitWritableFinal = addConcurrentStream(concurrentStreams, subprocessStdin, "writableFinal"), waitWritableDestroy = addConcurrentStream(concurrentStreams, subprocessStdin, "writableDestroy");
return { subprocessStdin, waitWritableFinal, waitWritableDestroy };
}, getWritableMethods = (subprocessStdin, subprocess, waitWritableFinal) => ({
write: onWrite.bind(void 0, subprocessStdin),
final: callbackify3(onWritableFinal.bind(void 0, subprocessStdin, subprocess, waitWritableFinal))
}), onWrite = (subprocessStdin, chunk, encoding, done) => {
subprocessStdin.write(chunk, encoding) ? done() : subprocessStdin.once("drain", done);
}, onWritableFinal = async (subprocessStdin, subprocess, waitWritableFinal) => {
await waitForConcurrentStreams(waitWritableFinal, subprocess) && (subprocessStdin.writable && subprocessStdin.end(), await subprocess);
}, onStdinFinished = async (subprocessStdin, writable2, subprocessStdout) => {
try {
await waitForSubprocessStdin(subprocessStdin), writable2.writable && writable2.end();
} catch (error) {
await safeWaitForSubprocessStdout(subprocessStdout), destroyOtherWritable(writable2, error);
}
}, onWritableDestroy = async ({ subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy }, error) => {
await waitForConcurrentStreams(waitWritableFinal, subprocess), await waitForConcurrentStreams(waitWritableDestroy, subprocess) && (destroyOtherWritable(subprocessStdin, error), await waitForSubprocess(subprocess, error));
}, destroyOtherWritable = (stream, error) => {
destroyOtherStream(stream, stream.writable, error);
};
// ../../node_modules/execa/lib/convert/duplex.js
import { Duplex as Duplex3 } from "node:stream";
import { callbackify as callbackify4 } from "node:util";
var createDuplex = ({ subprocess, concurrentStreams, encoding }, { from, to, binary: binaryOption = !0, preserveNewlines = !0 } = {}) => {
let binary = binaryOption || BINARY_ENCODINGS.has(encoding), { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams), { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams), { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary), { read, onStdoutDataDone } = getReadableMethods({
subprocessStdout,
subprocess,
binary,
encoding,
preserveNewlines
}), duplex2 = new Duplex3({
read,
...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),
destroy: callbackify4(onDuplexDestroy.bind(void 0, {
subprocessStdout,
subprocessStdin,
subprocess,
waitReadableDestroy,
waitWritableFinal,
waitWritableDestroy
})),
readableHighWaterMark,
writableHighWaterMark: subprocessStdin.writableHighWaterMark,
readableObjectMode,
writableObjectMode: subprocessStdin.writableObjectMode,
encoding: readableEncoding
});
return onStdoutFinished({
subprocessStdout,
onStdoutDataDone,
readable: duplex2,
subprocess,
subprocessStdin
}), onStdinFinished(subprocessStdin, duplex2, subprocessStdout), duplex2;
}, onDuplexDestroy = async ({ subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy }, error) => {
await Promise.all([
onReadableDestroy({ subprocessStdout, subprocess, waitReadableDestroy }, error),
onWritableDestroy({
subprocessStdin,
subprocess,
waitWritableFinal,
waitWritableDestroy
}, error)
]);
};
// ../../node_modules/execa/lib/convert/iterable.js
var createIterable = (subprocess, encoding, {
from,
binary: binaryOption = !1,
preserveNewlines = !1
} = {}) => {
let binary = binaryOption || BINARY_ENCODINGS.has(encoding), subprocessStdout = getFromStream(subprocess, from), onStdoutData = iterateOnSubprocessStream({
subprocessStdout,
subprocess,
binary,
shouldEncode: !0,
encoding,
preserveNewlines
});
return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);
}, iterateOnStdoutData = async function* (onStdoutData, subprocessStdout, subprocess) {
try {
yield* onStdoutData;
} finally {
subprocessStdout.readable && subprocessStdout.destroy(), await subprocess;
}
};
// ../../node_modules/execa/lib/convert/add.js
var addConvertedStreams = (subprocess, { encoding }) => {
let concurrentStreams = initializeConcurrentStreams();
subprocess.readable = createReadable.bind(void 0, { subprocess, concurrentStreams, encoding }), subprocess.writable = createWritable.bind(void 0, { subprocess, concurrentStreams }), subprocess.duplex = createDuplex.bind(void 0, { subprocess, concurrentStreams, encoding }), subprocess.iterable = createIterable.bind(void 0, subprocess, encoding), subprocess[Symbol.asyncIterator] = createIterable.bind(void 0, subprocess, encoding, {});
};
// ../../node_modules/execa/lib/methods/promise.js
var mergePromise = (subprocess, promise2) => {
for (let [property, descriptor] of descriptors) {
let value = descriptor.value.bind(promise2);
Reflect.defineProperty(subprocess, property, { ...descriptor, value });
}
}, nativePromisePrototype = (async () => {
})().constructor.prototype, descriptors = ["then", "catch", "finally"].map((property) => [
property,
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
]);
// ../../node_modules/execa/lib/methods/main-async.js
var execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {
let { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors } = handleAsyncArguments(rawFile, rawArguments, rawOptions), { subprocess, promise: promise2 } = spawnSubprocessAsync({
file,
commandArguments,
options,
startTime,
verboseInfo,
command,
escapedCommand,
fileDescriptors
});
return subprocess.pipe = pipeToSubprocess.bind(void 0, {
source: subprocess,
sourcePromise: promise2,
boundOptions: {},
createNested
}), mergePromise(subprocess, promise2), SUBPROCESS_OPTIONS.set(subprocess, { options, fileDescriptors }), subprocess;
}, handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {
let { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions), { file, commandArguments, options: normalizedOptions } = normalizeOptions(rawFile, rawArguments, rawOptions), options = handleAsyncOptions(normalizedOptions), fileDescriptors = handleStdioAsync(options, verboseInfo);
return {
file,
commandArguments,
command,
escapedCommand,
startTime,
verboseInfo,
options,
fileDescriptors
};
}, handleAsyncOptions = ({ timeout, signal, ...options }) => {
if (signal !== void 0)
throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');
return { ...options, timeoutDuration: timeout };
}, spawnSubprocessAsync = ({ file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors }) => {
let subprocess;
try {
subprocess = spawn(...concatenateShell(file, commandArguments, options));
} catch (error) {
return handleEarlyError({
error,
command,
escapedCommand,
fileDescriptors,
options,
startTime,
verboseInfo
});
}
let controller = new AbortController();
setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);
let originalStreams = [...subprocess.stdio];
pipeOutputAsync(subprocess, fileDescriptors, controller), cleanupOnExit(subprocess, options, controller);
let context = {}, onInternalError = createDeferred();
subprocess.kill = subprocessKill.bind(void 0, {
kill: subprocess.kill.bind(subprocess),
options,
onInternalError,
context,
controller
}), subprocess.all = makeAllStream(subprocess, options), addConvertedStreams(subprocess, options), addIpcMethods(subprocess, options);
let promise2 = handlePromise({
subprocess,
options,
startTime,
verboseInfo,
fileDescriptors,
originalStreams,
command,
escapedCommand,
context,
onInternalError,
controller
});
return { subprocess, promise: promise2 };
}, handlePromise = async ({ subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller }) => {
let [
errorInfo,
[exitCode, signal],
stdioResults,
allResult,
ipcOutput
] = await waitForSubprocessResult({
subprocess,
options,
context,
verboseInfo,
fileDescriptors,
originalStreams,
onInternalError,
controller
});
controller.abort(), onInternalError.resolve();
let stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber)), all = stripNewline(allResult, options, "all"), result = getAsyncResult({
errorInfo,
exitCode,
signal,
stdio,
all,
ipcOutput,
context,
options,
command,
escapedCommand,
startTime
});
return handleResult(result, verboseInfo, options);
}, getAsyncResult = ({ errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime }) => "error" in errorInfo ? makeError({
error: errorInfo.error,
command,
escapedCommand,
timedOut: context.terminationReason === "timeout",
isCanceled: context.terminationReason === "cancel" || context.terminationReason === "gracefulCancel",
isGracefullyCanceled: context.terminationReason === "gracefulCancel",
isMaxBuffer: errorInfo.error instanceof MaxBufferError,
isForcefullyTerminated: context.isForcefullyTerminated,
exitCode,
signal,
stdio,
all,
ipcOutput,
options,
startTime,
isSync: !1
}) : makeSuccessResult({
command,
escapedCommand,
stdio,
all,
ipcOutput,
options,
startTime
});
// ../../node_modules/execa/lib/methods/bind.js
var mergeOptions = (boundOptions, options) => {
let newOptions = Object.fromEntries(
Object.entries(options).map(([optionName, optionValue]) => [
optionName,
mergeOption(optionName, boundOptions[optionName], optionValue)
])
);
return { ...boundOptions, ...newOptions };
}, mergeOption = (optionName, boundOptionValue, optionValue) => DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue) ? { ...boundOptionValue, ...optionValue } : optionValue, DEEP_OPTIONS = /* @__PURE__ */ new Set(["env", ...FD_SPECIFIC_OPTIONS]);
// ../../node_modules/execa/lib/methods/create.js
var createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {
let createNested = (mapArguments2, boundOptions2, setBoundExeca2) => createExeca(mapArguments2, boundOptions2, deepOptions, setBoundExeca2), boundExeca = (...execaArguments) => callBoundExeca({
mapArguments,
deepOptions,
boundOptions,
setBoundExeca,
createNested
}, ...execaArguments);
return setBoundExeca !== void 0 && setBoundExeca(boundExeca, createNested, boundOptions), boundExeca;
}, callBoundExeca = ({ mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested }, firstArgument, ...nextArguments) => {
if (isPlainObject(firstArgument))
return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca);
let { file, commandArguments, options, isSync } = parseArguments({
mapArguments,
firstArgument,
nextArguments,
deepOptions,
boundOptions
});
return isSync ? execaCoreSync(file, commandArguments, options) : execaCoreAsync(file, commandArguments, options, createNested);
}, parseArguments = ({ mapArguments, firstArgument, nextArguments, deepOptions, boundOptions }) => {
let callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments], [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments), mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions), {
file = initialFile,
commandArguments = initialArguments,
options = mergedOptions,
isSync = !1
} = mapArguments({ file: initialFile, commandArguments: initialArguments, options: mergedOptions });
return {
file,
commandArguments,
options,
isSync
};
};
// ../../node_modules/execa/lib/methods/command.js
var mapCommandAsync = ({ file, commandArguments }) => parseCommand(file, commandArguments), mapCommandSync = ({ file, commandArguments }) => ({ ...parseCommand(file, commandArguments), isSync: !0 }), parseCommand = (command, unusedArguments) => {
if (unusedArguments.length > 0)
throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`);
let [file, ...commandArguments] = parseCommandString(command);
return { file, commandArguments };
}, parseCommandString = (command) => {
if (typeof command != "string")
throw new TypeError(`The command must be a string: ${String(command)}.`);
let trimmedCommand = command.trim();
if (trimmedCommand === "")
return [];
let tokens = [];
for (let token of trimmedCommand.split(SPACES_REGEXP)) {
let previousToken = tokens.at(-1);
previousToken && previousToken.endsWith("\\") ? tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}` : tokens.push(token);
}
return tokens;
}, SPACES_REGEXP = / +/g;
// ../../node_modules/execa/lib/methods/script.js
var setScriptSync = (boundExeca, createNested, boundOptions) => {
boundExeca.sync = createNested(mapScriptSync, boundOptions), boundExeca.s = boundExeca.sync;
}, mapScriptAsync = ({ options }) => getScriptOptions(options), mapScriptSync = ({ options }) => ({ ...getScriptOptions(options), isSync: !0 }), getScriptOptions = (options) => ({ options: { ...getScriptStdinOption(options), ...options } }), getScriptStdinOption = ({ input, inputFile, stdio }) => input === void 0 && inputFile === void 0 && stdio === void 0 ? { stdin: "inherit" } : {}, deepScriptOptions = { preferLocal: !0 };
// ../../node_modules/execa/index.js
var execa = createExeca(() => ({})), execaSync = createExeca(() => ({ isSync: !0 })), execaCommand = createExeca(mapCommandAsync), execaCommandSync = createExeca(mapCommandSync), execaNode = createExeca(mapNode), $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync), {
sendMessage: sendMessage2,
getOneMessage: getOneMessage2,
getEachMessage: getEachMessage2,
getCancelSignal: getCancelSignal2
} = getIpcExport();
export {
require_cross_spawn,
execa,
execaCommand,
execaCommandSync,
execaNode,
NPM_LOCKFILE,
PNPM_LOCKFILE,
YARN_LOCKFILE,
BUN_LOCKFILE,
BUN_LOCKFILE_BINARY,
getProjectRoot,
invalidateProjectRootCache,
findFilesUp,
nodePathsToArray,
normalizeStoryPath,
loadEnvs,
stringifyEnvs,
stringifyProcessEnvs,
optionalEnvToBoolean,
isCI,
isWebContainer,
getComponentIdFromEntry,
STORY_FILE_TEST_REGEXP,
getStoryImportPathFromEntry,
selectComponentEntriesByComponentId
};