vlt
Version:
The vlt CLI
461 lines (455 loc) • 13.6 kB
JavaScript
var global = globalThis;
import {Buffer} from "node:buffer";
import {setTimeout as _vlt_setTimeout,clearTimeout as _vlt_clearTimeout,setImmediate as _vlt_setImmediate,clearImmediate as _vlt_clearImmediate,setInterval as _vlt_setInterval,clearInterval as _vlt_clearInterval} from "node:timers";
globalThis.setTimeout = _vlt_setTimeout;
globalThis.clearTimeout = _vlt_clearTimeout;
globalThis.setImmediate = _vlt_setImmediate;
globalThis.clearImmediate = _vlt_clearImmediate;
globalThis.setInterval = _vlt_setInterval;
globalThis.clearInterval = _vlt_clearInterval;
import {createRequire as _vlt_createRequire} from "node:module";
var require = _vlt_createRequire(import.meta.filename);
import {
generateDefaultHelp,
generateFullHelp
} from "./chunk-RPYKRKJX.js";
import {
isViewClass
} from "./chunk-C476FDK4.js";
import {
parseError
} from "./chunk-QEOLSUUZ.js";
import {
isGraphRunError,
splitDepID
} from "./chunk-MBW6A3RQ.js";
import {
defaultView
} from "./chunk-TW6XJ6XF.js";
import {
isErrorWithCause,
isObject
} from "./chunk-TG2CR2PD.js";
import {
XDG
} from "./chunk-52JFXOJH.js";
// ../../src/cli-sdk/src/print-err.ts
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { formatWithOptions } from "node:util";
var formatOptions = {
depth: Infinity,
maxArrayLength: Infinity,
maxStringLength: Infinity
};
var isNonEmptyString = (v) => !!v && typeof v === "string";
var formatURL = (v, format) => v instanceof URL ? v.toString() : (
/* c8 ignore next */
format(v)
);
var formatArray = (v, format, joiner = ", ") => Array.isArray(v) ? v.join(joiner) : (
/* c8 ignore next */
format(v)
);
var indent = (lines, num = 2) => lines.split("\n").map((l) => " ".repeat(num) + l).join("\n");
var writeErrorLog = (e, format) => {
try {
const dir = new XDG("vlt/error-logs").data();
const file = join(dir, `error-${process.pid}.log`);
mkdirSync(dir, { recursive: true });
writeFileSync(
file,
format(e, {
colors: false,
maxLines: Infinity
})
);
return file;
} catch {
return null;
}
};
var printErr = (e, usage, stderr2, baseOpts) => {
const format = (arg, opts) => {
const { maxLines = 200, ...rest } = {
...formatOptions,
...baseOpts,
...opts
};
const lines = formatWithOptions(rest, arg).split("\n");
const totalLines = lines.length;
if (totalLines > maxLines) {
lines.length = maxLines;
lines.push(`... ${totalLines - maxLines} lines hidden ...`);
}
return lines.join("\n");
};
const err = parseError(e);
const knownError = printCode(err, usage, stderr2, format);
const fileWritten = !knownError || knownError.file ? writeErrorLog(e, format) : null;
if (!fileWritten && !knownError) {
return stderr2(format(e));
}
if (err && !knownError) {
stderr2(`${err.name}: ${err.message}`);
}
if (fileWritten) {
stderr2("");
stderr2(`Full details written to: ${fileWritten}`);
}
if (!knownError || knownError.bug) {
stderr2("");
stderr2("Open an issue with the full error details at:");
stderr2(indent("https://github.com/vltpkg/vltpkg/issues/new"));
}
};
var printCode = (err, usage, stderr2, format) => {
if (!err) return;
switch (err.cause?.code) {
case "GRAPHRUN_TRAVERSAL": {
if (!isGraphRunError(err)) break;
const { node, path, cause } = err.cause;
stderr2(
`Graph traversal failure at: ${splitDepID(node.id).join(" ")}`
);
if (Array.isArray(path) && path.length) {
stderr2(indent(`Path: ${path.map((n) => n.id).join(",")}`));
}
if (isErrorWithCause(cause) && isObject(cause.cause) && "command" in cause.cause && "stdout" in cause.cause && "stderr" in cause.cause && "status" in cause.cause && "signal" in cause.cause && "cwd" in cause.cause) {
const {
command,
args,
cwd,
stdout: cmdStdout,
stderr: cmdStderr,
status,
signal
} = cause.cause;
stderr2(`Command: ${command}`);
if (args && Array.isArray(args) && args.length) {
stderr2(
`Args: ${args.map((a) => JSON.stringify(a)).join(", ")}`
);
}
stderr2(`Cwd: ${cwd}`);
if (cmdStderr || cmdStdout) {
stderr2("");
if (isNonEmptyString(cmdStderr)) {
stderr2(cmdStderr);
}
if (isNonEmptyString(cmdStdout)) {
stderr2(cmdStdout);
}
stderr2("");
}
if (signal !== null) stderr2(`Signal: ${format(signal)}`);
if (status !== null) stderr2(`Status: ${format(status)}`);
}
return { file: true };
}
case "EUSAGE": {
const { found, validOptions } = err.cause;
stderr2(usage().usage());
stderr2(`Usage Error: ${err.message}`);
if (found) {
stderr2(indent(`Found: ${format(found)}`));
}
if (validOptions) {
stderr2(
indent(
`Valid options: ${formatArray(validOptions, format)}`
)
);
}
return {};
}
case "ERESOLVE": {
const { url, from, response, spec } = err.cause;
stderr2(`Resolve Error: ${err.message}`);
if (url) {
stderr2(indent(`While fetching: ${formatURL(url, format)}`));
}
if (spec) {
stderr2(indent(`To satisfy: ${format(spec)}`));
}
if (from) {
stderr2(indent(`From: ${format(from)}`));
}
if (response) {
stderr2(indent(`Response: ${format(response)}`));
}
return { file: true };
}
case "EREQUEST": {
const { url, method } = err.cause;
const { code, syscall } = err.cause.cause ?? {};
stderr2(`Request Error: ${err.message}`);
if (code) {
stderr2(indent(`Code: ${format(code)}`));
}
if (syscall) {
stderr2(indent(`Syscall: ${format(syscall)}`));
}
if (url) {
stderr2(indent(`URL: ${formatURL(url, format)}`));
}
if (method) {
stderr2(indent(`Method: ${format(method)}`));
}
return { file: true };
}
case "ECONFIG": {
const { found, wanted, validOptions } = err.cause;
stderr2(`Config Error: ${err.message}`);
if (found) {
stderr2(indent(`Found: ${format(found)}`));
}
if (wanted) {
stderr2(indent(`Wanted: ${format(wanted)}`));
}
if (validOptions) {
stderr2(indent(`Valid Options: ${format(validOptions)}`));
}
return {};
}
}
};
// ../../src/cli-sdk/src/output.ts
import {
formatWithOptions as formatWithOptions2,
styleText as utilStyleText
} from "node:util";
// ../../node_modules/.pnpm/supports-color@10.2.2/node_modules/supports-color/index.js
import process2 from "node:process";
import os from "node:os";
import tty from "node:tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
var { env } = process2;
var flagForceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
flagForceColor = 1;
}
function envForceColor() {
if (!("FORCE_COLOR" in env)) {
return;
}
if (env.FORCE_COLOR === "true") {
return 1;
}
if (env.FORCE_COLOR === "false") {
return 0;
}
if (env.FORCE_COLOR.length === 0) {
return 1;
}
const level = Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
if (![0, 1, 2, 3].includes(level)) {
return;
}
return level;
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== void 0) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
}
if ("TF_BUILD" in env && "AGENT_NAME" in env) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (process2.platform === "win32") {
const osRelease = os.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env) {
if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
return 3;
}
if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if (env.TERM === "xterm-kitty") {
return 3;
}
if (env.TERM === "xterm-ghostty") {
return 3;
}
if (env.TERM === "wezterm") {
return 3;
}
if ("TERM_PROGRAM" in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env.TERM_PROGRAM) {
case "iTerm.app": {
return version >= 3 ? 3 : 2;
}
case "Apple_Terminal": {
return 2;
}
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ("COLORTERM" in env) {
return 1;
}
return min;
}
function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options
});
return translateLevel(level);
}
var supportsColor = {
stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
stderr: createSupportsColor({ isTTY: tty.isatty(2) })
};
// ../../src/cli-sdk/src/output.ts
var supportsColor2 = (stream) => {
const res = createSupportsColor(stream, { sniffFlags: false });
if (res === false) return false;
return res.level > 0;
};
var stdout = (...args) => console.log(...args);
var stderr = (...args) => console.error(...args);
var styleText = (f, s) => utilStyleText(f, s, { validateStream: false });
var styleTextStdout = (_, s) => s;
var styleTextStderr = (_, s) => s;
var identity = (x) => x;
var getView = (conf, views) => {
const viewName = conf.values.view;
const viewFn = viewName === "inspect" ? identity : viewName === "silent" ? () => void 0 : typeof views === "function" ? views : views && typeof views === "object" ? views[viewName] : identity;
if (!viewFn && conf.values.view !== defaultView && conf.values.view !== "json" && conf.values.view !== "silent") {
conf.values.view = defaultView;
process.env.VLT_VIEW = defaultView;
return getView(conf, views);
}
return viewFn ?? identity;
};
var startView = (conf, opts, views, { start } = { start: Date.now() }) => {
const View = getView(conf, views);
if (isViewClass(View)) {
const view = new View(opts, conf);
view.start();
return {
async onDone(r) {
return view.done(r, { time: Date.now() - start });
},
onError(err) {
view.error(err);
}
};
}
return {
async onDone(r) {
if (r === void 0) return;
return View(r, opts, conf);
}
};
};
var outputCommand = async (cliCommand, conf, { start } = { start: Date.now() }) => {
const { usage, views, command } = cliCommand;
const stdoutColor = conf.values.color ?? supportsColor2(process.stdout);
const stderrColor = conf.values.color ?? supportsColor2(process.stderr);
if (conf.values.help) {
if (conf.command === "help" && conf.positionals.length === 0) {
if (conf.get("all")) {
return stdout(generateFullHelp(stdoutColor));
}
return stdout(generateDefaultHelp(stdoutColor));
}
return stdout(usage().usage());
}
if (stdoutColor) styleTextStdout = styleText;
if (stderrColor) styleTextStderr = styleText;
const { onDone, onError } = startView(
conf,
// assume views will always output to stdout so use color support from there
{ colors: stdoutColor },
views,
{ start }
);
try {
const output = await onDone(await command(conf));
if (output !== void 0 && conf.values.view !== "silent") {
stdout(
conf.values.view === "json" ? JSON.stringify(output, null, 2) : formatWithOptions2(
{
...formatOptions,
colors: stdoutColor
},
output
)
);
}
} catch (err) {
onError?.(err);
process.exitCode ||= 1;
printErr(err, usage, stderr, {
...formatOptions,
colors: stderrColor
});
process.exit(process.exitCode);
}
};
export {
indent,
stdout,
stderr,
styleTextStdout,
outputCommand
};
//# sourceMappingURL=chunk-PXEDENDA.js.map