11526 lines
446 KiB
JavaScript
11526 lines
446 KiB
JavaScript
import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "node:module";
|
||
|
||
;// external "assert"
|
||
const external_assert_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
|
||
;// ./node_modules/cliui/build/lib/index.js
|
||
|
||
const align = {
|
||
right: alignRight,
|
||
center: alignCenter
|
||
};
|
||
const lib_top = 0;
|
||
const right = 1;
|
||
const bottom = 2;
|
||
const left = 3;
|
||
class UI {
|
||
constructor(opts) {
|
||
var _a;
|
||
this.width = opts.width;
|
||
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||
this.rows = [];
|
||
}
|
||
span(...args) {
|
||
const cols = this.div(...args);
|
||
cols.span = true;
|
||
}
|
||
resetOutput() {
|
||
this.rows = [];
|
||
}
|
||
div(...args) {
|
||
if (args.length === 0) {
|
||
this.div('');
|
||
}
|
||
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||
return this.applyLayoutDSL(args[0]);
|
||
}
|
||
const cols = args.map(arg => {
|
||
if (typeof arg === 'string') {
|
||
return this.colFromString(arg);
|
||
}
|
||
return arg;
|
||
});
|
||
this.rows.push(cols);
|
||
return cols;
|
||
}
|
||
shouldApplyLayoutDSL(...args) {
|
||
return args.length === 1 && typeof args[0] === 'string' &&
|
||
/[\t\n]/.test(args[0]);
|
||
}
|
||
applyLayoutDSL(str) {
|
||
const rows = str.split('\n').map(row => row.split('\t'));
|
||
let leftColumnWidth = 0;
|
||
// simple heuristic for layout, make sure the
|
||
// second column lines up along the left-hand.
|
||
// don't allow the first column to take up more
|
||
// than 50% of the screen.
|
||
rows.forEach(columns => {
|
||
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||
}
|
||
});
|
||
// generate a table:
|
||
// replacing ' ' with padding calculations.
|
||
// using the algorithmically generated width.
|
||
rows.forEach(columns => {
|
||
this.div(...columns.map((r, i) => {
|
||
return {
|
||
text: r.trim(),
|
||
padding: this.measurePadding(r),
|
||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||
};
|
||
}));
|
||
});
|
||
return this.rows[this.rows.length - 1];
|
||
}
|
||
colFromString(text) {
|
||
return {
|
||
text,
|
||
padding: this.measurePadding(text)
|
||
};
|
||
}
|
||
measurePadding(str) {
|
||
// measure padding without ansi escape codes
|
||
const noAnsi = mixin.stripAnsi(str);
|
||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||
}
|
||
toString() {
|
||
const lines = [];
|
||
this.rows.forEach(row => {
|
||
this.rowToString(row, lines);
|
||
});
|
||
// don't display any lines with the
|
||
// hidden flag set.
|
||
return lines
|
||
.filter(line => !line.hidden)
|
||
.map(line => line.text)
|
||
.join('\n');
|
||
}
|
||
rowToString(row, lines) {
|
||
this.rasterize(row).forEach((rrow, r) => {
|
||
let str = '';
|
||
rrow.forEach((col, c) => {
|
||
const { width } = row[c]; // the width with padding.
|
||
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||
let ts = col; // temporary string used during alignment/padding.
|
||
if (wrapWidth > mixin.stringWidth(col)) {
|
||
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||
}
|
||
// align the string within its column.
|
||
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||
const fn = align[row[c].align];
|
||
ts = fn(ts, wrapWidth);
|
||
if (mixin.stringWidth(ts) < wrapWidth) {
|
||
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
|
||
}
|
||
}
|
||
// apply border and padding to string.
|
||
const padding = row[c].padding || [0, 0, 0, 0];
|
||
if (padding[left]) {
|
||
str += ' '.repeat(padding[left]);
|
||
}
|
||
str += addBorder(row[c], ts, '| ');
|
||
str += ts;
|
||
str += addBorder(row[c], ts, ' |');
|
||
if (padding[right]) {
|
||
str += ' '.repeat(padding[right]);
|
||
}
|
||
// if prior row is span, try to render the
|
||
// current row on the prior line.
|
||
if (r === 0 && lines.length > 0) {
|
||
str = this.renderInline(str, lines[lines.length - 1]);
|
||
}
|
||
});
|
||
// remove trailing whitespace.
|
||
lines.push({
|
||
text: str.replace(/ +$/, ''),
|
||
span: row.span
|
||
});
|
||
});
|
||
return lines;
|
||
}
|
||
// if the full 'source' can render in
|
||
// the target line, do so.
|
||
renderInline(source, previousLine) {
|
||
const match = source.match(/^ */);
|
||
const leadingWhitespace = match ? match[0].length : 0;
|
||
const target = previousLine.text;
|
||
const targetTextWidth = mixin.stringWidth(target.trimRight());
|
||
if (!previousLine.span) {
|
||
return source;
|
||
}
|
||
// if we're not applying wrapping logic,
|
||
// just always append to the span.
|
||
if (!this.wrap) {
|
||
previousLine.hidden = true;
|
||
return target + source;
|
||
}
|
||
if (leadingWhitespace < targetTextWidth) {
|
||
return source;
|
||
}
|
||
previousLine.hidden = true;
|
||
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
|
||
}
|
||
rasterize(row) {
|
||
const rrows = [];
|
||
const widths = this.columnWidths(row);
|
||
let wrapped;
|
||
// word wrap all columns, and create
|
||
// a data-structure that is easy to rasterize.
|
||
row.forEach((col, c) => {
|
||
// leave room for left and right padding.
|
||
col.width = widths[c];
|
||
if (this.wrap) {
|
||
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||
}
|
||
else {
|
||
wrapped = col.text.split('\n');
|
||
}
|
||
if (col.border) {
|
||
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||
}
|
||
// add top and bottom padding.
|
||
if (col.padding) {
|
||
wrapped.unshift(...new Array(col.padding[lib_top] || 0).fill(''));
|
||
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||
}
|
||
wrapped.forEach((str, r) => {
|
||
if (!rrows[r]) {
|
||
rrows.push([]);
|
||
}
|
||
const rrow = rrows[r];
|
||
for (let i = 0; i < c; i++) {
|
||
if (rrow[i] === undefined) {
|
||
rrow.push('');
|
||
}
|
||
}
|
||
rrow.push(str);
|
||
});
|
||
});
|
||
return rrows;
|
||
}
|
||
negatePadding(col) {
|
||
let wrapWidth = col.width || 0;
|
||
if (col.padding) {
|
||
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||
}
|
||
if (col.border) {
|
||
wrapWidth -= 4;
|
||
}
|
||
return wrapWidth;
|
||
}
|
||
columnWidths(row) {
|
||
if (!this.wrap) {
|
||
return row.map(col => {
|
||
return col.width || mixin.stringWidth(col.text);
|
||
});
|
||
}
|
||
let unset = row.length;
|
||
let remainingWidth = this.width;
|
||
// column widths can be set in config.
|
||
const widths = row.map(col => {
|
||
if (col.width) {
|
||
unset--;
|
||
remainingWidth -= col.width;
|
||
return col.width;
|
||
}
|
||
return undefined;
|
||
});
|
||
// any unset widths should be calculated.
|
||
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||
return widths.map((w, i) => {
|
||
if (w === undefined) {
|
||
return Math.max(unsetWidth, _minWidth(row[i]));
|
||
}
|
||
return w;
|
||
});
|
||
}
|
||
}
|
||
function addBorder(col, ts, style) {
|
||
if (col.border) {
|
||
if (/[.']-+[.']/.test(ts)) {
|
||
return '';
|
||
}
|
||
if (ts.trim().length !== 0) {
|
||
return style;
|
||
}
|
||
return ' ';
|
||
}
|
||
return '';
|
||
}
|
||
// calculates the minimum width of
|
||
// a column, based on padding preferences.
|
||
function _minWidth(col) {
|
||
const padding = col.padding || [];
|
||
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||
if (col.border) {
|
||
return minWidth + 4;
|
||
}
|
||
return minWidth;
|
||
}
|
||
function getWindowWidth() {
|
||
/* istanbul ignore next: depends on terminal */
|
||
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||
return process.stdout.columns;
|
||
}
|
||
return 80;
|
||
}
|
||
function alignRight(str, width) {
|
||
str = str.trim();
|
||
const strWidth = mixin.stringWidth(str);
|
||
if (strWidth < width) {
|
||
return ' '.repeat(width - strWidth) + str;
|
||
}
|
||
return str;
|
||
}
|
||
function alignCenter(str, width) {
|
||
str = str.trim();
|
||
const strWidth = mixin.stringWidth(str);
|
||
/* istanbul ignore next */
|
||
if (strWidth >= width) {
|
||
return str;
|
||
}
|
||
return ' '.repeat((width - strWidth) >> 1) + str;
|
||
}
|
||
let mixin;
|
||
function cliui(opts, _mixin) {
|
||
mixin = _mixin;
|
||
return new UI({
|
||
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||
});
|
||
}
|
||
|
||
;// ./node_modules/cliui/build/lib/string-utils.js
|
||
// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
|
||
// to facilitate ESM and Deno modules.
|
||
// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
|
||
// The npm application
|
||
// Copyright (c) npm, Inc. and Contributors
|
||
// Licensed on the terms of The Artistic License 2.0
|
||
// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
|
||
const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
|
||
'\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
|
||
function stripAnsi(str) {
|
||
return str.replace(ansi, '');
|
||
}
|
||
function wrap(str, width) {
|
||
const [start, end] = str.match(ansi) || ['', ''];
|
||
str = stripAnsi(str);
|
||
let wrapped = '';
|
||
for (let i = 0; i < str.length; i++) {
|
||
if (i !== 0 && (i % width) === 0) {
|
||
wrapped += '\n';
|
||
}
|
||
wrapped += str.charAt(i);
|
||
}
|
||
if (start && end) {
|
||
wrapped = `${start}${wrapped}${end}`;
|
||
}
|
||
return wrapped;
|
||
}
|
||
|
||
;// ./node_modules/cliui/index.mjs
|
||
// Bootstrap cliui with CommonJS dependencies:
|
||
|
||
|
||
|
||
function ui (opts) {
|
||
return cliui(opts, {
|
||
stringWidth: (str) => {
|
||
return [...str].length
|
||
},
|
||
stripAnsi: stripAnsi,
|
||
wrap: wrap
|
||
})
|
||
}
|
||
|
||
;// external "path"
|
||
const external_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
|
||
;// external "fs"
|
||
const external_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
|
||
;// ./node_modules/escalade/sync/index.mjs
|
||
|
||
|
||
|
||
/* harmony default export */ function sync(start, callback) {
|
||
let dir = (0,external_path_namespaceObject.resolve)('.', start);
|
||
let tmp, stats = (0,external_fs_namespaceObject.statSync)(dir);
|
||
|
||
if (!stats.isDirectory()) {
|
||
dir = (0,external_path_namespaceObject.dirname)(dir);
|
||
}
|
||
|
||
while (true) {
|
||
tmp = callback(dir, (0,external_fs_namespaceObject.readdirSync)(dir));
|
||
if (tmp) return (0,external_path_namespaceObject.resolve)(dir, tmp);
|
||
dir = (0,external_path_namespaceObject.dirname)(tmp = dir);
|
||
if (tmp === dir) break;
|
||
}
|
||
}
|
||
|
||
;// external "util"
|
||
const external_util_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
|
||
;// external "url"
|
||
const external_url_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
|
||
;// ./node_modules/yargs-parser/build/lib/string-utils.js
|
||
/**
|
||
* @license
|
||
* Copyright (c) 2016, Contributors
|
||
* SPDX-License-Identifier: ISC
|
||
*/
|
||
function camelCase(str) {
|
||
// Handle the case where an argument is provided as camel case, e.g., fooBar.
|
||
// by ensuring that the string isn't already mixed case:
|
||
const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
|
||
if (!isCamelCase) {
|
||
str = str.toLowerCase();
|
||
}
|
||
if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
|
||
return str;
|
||
}
|
||
else {
|
||
let camelcase = '';
|
||
let nextChrUpper = false;
|
||
const leadingHyphens = str.match(/^-+/);
|
||
for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
|
||
let chr = str.charAt(i);
|
||
if (nextChrUpper) {
|
||
nextChrUpper = false;
|
||
chr = chr.toUpperCase();
|
||
}
|
||
if (i !== 0 && (chr === '-' || chr === '_')) {
|
||
nextChrUpper = true;
|
||
}
|
||
else if (chr !== '-' && chr !== '_') {
|
||
camelcase += chr;
|
||
}
|
||
}
|
||
return camelcase;
|
||
}
|
||
}
|
||
function decamelize(str, joinString) {
|
||
const lowercase = str.toLowerCase();
|
||
joinString = joinString || '-';
|
||
let notCamelcase = '';
|
||
for (let i = 0; i < str.length; i++) {
|
||
const chrLower = lowercase.charAt(i);
|
||
const chrString = str.charAt(i);
|
||
if (chrLower !== chrString && i > 0) {
|
||
notCamelcase += `${joinString}${lowercase.charAt(i)}`;
|
||
}
|
||
else {
|
||
notCamelcase += chrString;
|
||
}
|
||
}
|
||
return notCamelcase;
|
||
}
|
||
function looksLikeNumber(x) {
|
||
if (x === null || x === undefined)
|
||
return false;
|
||
// if loaded from config, may already be a number.
|
||
if (typeof x === 'number')
|
||
return true;
|
||
// hexadecimal.
|
||
if (/^0x[0-9a-f]+$/i.test(x))
|
||
return true;
|
||
// don't treat 0123 as a number; as it drops the leading '0'.
|
||
if (/^0[^.]/.test(x))
|
||
return false;
|
||
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
|
||
}
|
||
|
||
;// ./node_modules/yargs-parser/build/lib/tokenize-arg-string.js
|
||
/**
|
||
* @license
|
||
* Copyright (c) 2016, Contributors
|
||
* SPDX-License-Identifier: ISC
|
||
*/
|
||
// take an un-split argv string and tokenize it.
|
||
function tokenizeArgString(argString) {
|
||
if (Array.isArray(argString)) {
|
||
return argString.map(e => typeof e !== 'string' ? e + '' : e);
|
||
}
|
||
argString = argString.trim();
|
||
let i = 0;
|
||
let prevC = null;
|
||
let c = null;
|
||
let opening = null;
|
||
const args = [];
|
||
for (let ii = 0; ii < argString.length; ii++) {
|
||
prevC = c;
|
||
c = argString.charAt(ii);
|
||
// split on spaces unless we're in quotes.
|
||
if (c === ' ' && !opening) {
|
||
if (!(prevC === ' ')) {
|
||
i++;
|
||
}
|
||
continue;
|
||
}
|
||
// don't split the string if we're in matching
|
||
// opening or closing single and double quotes.
|
||
if (c === opening) {
|
||
opening = null;
|
||
}
|
||
else if ((c === "'" || c === '"') && !opening) {
|
||
opening = c;
|
||
}
|
||
if (!args[i])
|
||
args[i] = '';
|
||
args[i] += c;
|
||
}
|
||
return args;
|
||
}
|
||
|
||
;// ./node_modules/yargs-parser/build/lib/yargs-parser-types.js
|
||
/**
|
||
* @license
|
||
* Copyright (c) 2016, Contributors
|
||
* SPDX-License-Identifier: ISC
|
||
*/
|
||
var DefaultValuesForTypeKey;
|
||
(function (DefaultValuesForTypeKey) {
|
||
DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
|
||
DefaultValuesForTypeKey["STRING"] = "string";
|
||
DefaultValuesForTypeKey["NUMBER"] = "number";
|
||
DefaultValuesForTypeKey["ARRAY"] = "array";
|
||
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
|
||
|
||
;// ./node_modules/yargs-parser/build/lib/yargs-parser.js
|
||
/**
|
||
* @license
|
||
* Copyright (c) 2016, Contributors
|
||
* SPDX-License-Identifier: ISC
|
||
*/
|
||
|
||
|
||
|
||
let yargs_parser_mixin;
|
||
class YargsParser {
|
||
constructor(_mixin) {
|
||
yargs_parser_mixin = _mixin;
|
||
}
|
||
parse(argsInput, options) {
|
||
const opts = Object.assign({
|
||
alias: undefined,
|
||
array: undefined,
|
||
boolean: undefined,
|
||
config: undefined,
|
||
configObjects: undefined,
|
||
configuration: undefined,
|
||
coerce: undefined,
|
||
count: undefined,
|
||
default: undefined,
|
||
envPrefix: undefined,
|
||
narg: undefined,
|
||
normalize: undefined,
|
||
string: undefined,
|
||
number: undefined,
|
||
__: undefined,
|
||
key: undefined
|
||
}, options);
|
||
// allow a string argument to be passed in rather
|
||
// than an argv array.
|
||
const args = tokenizeArgString(argsInput);
|
||
// tokenizeArgString adds extra quotes to args if argsInput is a string
|
||
// only strip those extra quotes in processValue if argsInput is a string
|
||
const inputIsString = typeof argsInput === 'string';
|
||
// aliases might have transitive relationships, normalize this.
|
||
const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
|
||
const configuration = Object.assign({
|
||
'boolean-negation': true,
|
||
'camel-case-expansion': true,
|
||
'combine-arrays': false,
|
||
'dot-notation': true,
|
||
'duplicate-arguments-array': true,
|
||
'flatten-duplicate-arrays': true,
|
||
'greedy-arrays': true,
|
||
'halt-at-non-option': false,
|
||
'nargs-eats-options': false,
|
||
'negation-prefix': 'no-',
|
||
'parse-numbers': true,
|
||
'parse-positional-numbers': true,
|
||
'populate--': false,
|
||
'set-placeholder-key': false,
|
||
'short-option-groups': true,
|
||
'strip-aliased': false,
|
||
'strip-dashed': false,
|
||
'unknown-options-as-args': false
|
||
}, opts.configuration);
|
||
const defaults = Object.assign(Object.create(null), opts.default);
|
||
const configObjects = opts.configObjects || [];
|
||
const envPrefix = opts.envPrefix;
|
||
const notFlagsOption = configuration['populate--'];
|
||
const notFlagsArgv = notFlagsOption ? '--' : '_';
|
||
const newAliases = Object.create(null);
|
||
const defaulted = Object.create(null);
|
||
// allow a i18n handler to be passed in, default to a fake one (util.format).
|
||
const __ = opts.__ || yargs_parser_mixin.format;
|
||
const flags = {
|
||
aliases: Object.create(null),
|
||
arrays: Object.create(null),
|
||
bools: Object.create(null),
|
||
strings: Object.create(null),
|
||
numbers: Object.create(null),
|
||
counts: Object.create(null),
|
||
normalize: Object.create(null),
|
||
configs: Object.create(null),
|
||
nargs: Object.create(null),
|
||
coercions: Object.create(null),
|
||
keys: []
|
||
};
|
||
const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
|
||
const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
|
||
[].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
|
||
const key = typeof opt === 'object' ? opt.key : opt;
|
||
// assign to flags[bools|strings|numbers]
|
||
const assignment = Object.keys(opt).map(function (key) {
|
||
const arrayFlagKeys = {
|
||
boolean: 'bools',
|
||
string: 'strings',
|
||
number: 'numbers'
|
||
};
|
||
return arrayFlagKeys[key];
|
||
}).filter(Boolean).pop();
|
||
// assign key to be coerced
|
||
if (assignment) {
|
||
flags[assignment][key] = true;
|
||
}
|
||
flags.arrays[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
[].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
|
||
flags.bools[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
[].concat(opts.string || []).filter(Boolean).forEach(function (key) {
|
||
flags.strings[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
[].concat(opts.number || []).filter(Boolean).forEach(function (key) {
|
||
flags.numbers[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
[].concat(opts.count || []).filter(Boolean).forEach(function (key) {
|
||
flags.counts[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
[].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
|
||
flags.normalize[key] = true;
|
||
flags.keys.push(key);
|
||
});
|
||
if (typeof opts.narg === 'object') {
|
||
Object.entries(opts.narg).forEach(([key, value]) => {
|
||
if (typeof value === 'number') {
|
||
flags.nargs[key] = value;
|
||
flags.keys.push(key);
|
||
}
|
||
});
|
||
}
|
||
if (typeof opts.coerce === 'object') {
|
||
Object.entries(opts.coerce).forEach(([key, value]) => {
|
||
if (typeof value === 'function') {
|
||
flags.coercions[key] = value;
|
||
flags.keys.push(key);
|
||
}
|
||
});
|
||
}
|
||
if (typeof opts.config !== 'undefined') {
|
||
if (Array.isArray(opts.config) || typeof opts.config === 'string') {
|
||
;
|
||
[].concat(opts.config).filter(Boolean).forEach(function (key) {
|
||
flags.configs[key] = true;
|
||
});
|
||
}
|
||
else if (typeof opts.config === 'object') {
|
||
Object.entries(opts.config).forEach(([key, value]) => {
|
||
if (typeof value === 'boolean' || typeof value === 'function') {
|
||
flags.configs[key] = value;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
// create a lookup table that takes into account all
|
||
// combinations of aliases: {f: ['foo'], foo: ['f']}
|
||
extendAliases(opts.key, aliases, opts.default, flags.arrays);
|
||
// apply default values to all aliases.
|
||
Object.keys(defaults).forEach(function (key) {
|
||
(flags.aliases[key] || []).forEach(function (alias) {
|
||
defaults[alias] = defaults[key];
|
||
});
|
||
});
|
||
let error = null;
|
||
checkConfiguration();
|
||
let notFlags = [];
|
||
const argv = Object.assign(Object.create(null), { _: [] });
|
||
// TODO(bcoe): for the first pass at removing object prototype we didn't
|
||
// remove all prototypes from objects returned by this API, we might want
|
||
// to gradually move towards doing so.
|
||
const argvReturn = {};
|
||
for (let i = 0; i < args.length; i++) {
|
||
const arg = args[i];
|
||
const truncatedArg = arg.replace(/^-{3,}/, '---');
|
||
let broken;
|
||
let key;
|
||
let letters;
|
||
let m;
|
||
let next;
|
||
let value;
|
||
// any unknown option (except for end-of-options, "--")
|
||
if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
|
||
pushPositional(arg);
|
||
// ---, ---=, ----, etc,
|
||
}
|
||
else if (truncatedArg.match(/^---+(=|$)/)) {
|
||
// options without key name are invalid.
|
||
pushPositional(arg);
|
||
continue;
|
||
// -- separated by =
|
||
}
|
||
else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
|
||
// Using [\s\S] instead of . because js doesn't support the
|
||
// 'dotall' regex modifier. See:
|
||
// http://stackoverflow.com/a/1068308/13216
|
||
m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
|
||
// arrays format = '--f=a b c'
|
||
if (m !== null && Array.isArray(m) && m.length >= 3) {
|
||
if (checkAllAliases(m[1], flags.arrays)) {
|
||
i = eatArray(i, m[1], args, m[2]);
|
||
}
|
||
else if (checkAllAliases(m[1], flags.nargs) !== false) {
|
||
// nargs format = '--f=monkey washing cat'
|
||
i = eatNargs(i, m[1], args, m[2]);
|
||
}
|
||
else {
|
||
setArg(m[1], m[2], true);
|
||
}
|
||
}
|
||
}
|
||
else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
|
||
m = arg.match(negatedBoolean);
|
||
if (m !== null && Array.isArray(m) && m.length >= 2) {
|
||
key = m[1];
|
||
setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
|
||
}
|
||
// -- separated by space.
|
||
}
|
||
else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
|
||
m = arg.match(/^--?(.+)/);
|
||
if (m !== null && Array.isArray(m) && m.length >= 2) {
|
||
key = m[1];
|
||
if (checkAllAliases(key, flags.arrays)) {
|
||
// array format = '--foo a b c'
|
||
i = eatArray(i, key, args);
|
||
}
|
||
else if (checkAllAliases(key, flags.nargs) !== false) {
|
||
// nargs format = '--foo a b c'
|
||
// should be truthy even if: flags.nargs[key] === 0
|
||
i = eatNargs(i, key, args);
|
||
}
|
||
else {
|
||
next = args[i + 1];
|
||
if (next !== undefined && (!next.match(/^-/) ||
|
||
next.match(negative)) &&
|
||
!checkAllAliases(key, flags.bools) &&
|
||
!checkAllAliases(key, flags.counts)) {
|
||
setArg(key, next);
|
||
i++;
|
||
}
|
||
else if (/^(true|false)$/.test(next)) {
|
||
setArg(key, next);
|
||
i++;
|
||
}
|
||
else {
|
||
setArg(key, defaultValue(key));
|
||
}
|
||
}
|
||
}
|
||
// dot-notation flag separated by '='.
|
||
}
|
||
else if (arg.match(/^-.\..+=/)) {
|
||
m = arg.match(/^-([^=]+)=([\s\S]*)$/);
|
||
if (m !== null && Array.isArray(m) && m.length >= 3) {
|
||
setArg(m[1], m[2]);
|
||
}
|
||
// dot-notation flag separated by space.
|
||
}
|
||
else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
|
||
next = args[i + 1];
|
||
m = arg.match(/^-(.\..+)/);
|
||
if (m !== null && Array.isArray(m) && m.length >= 2) {
|
||
key = m[1];
|
||
if (next !== undefined && !next.match(/^-/) &&
|
||
!checkAllAliases(key, flags.bools) &&
|
||
!checkAllAliases(key, flags.counts)) {
|
||
setArg(key, next);
|
||
i++;
|
||
}
|
||
else {
|
||
setArg(key, defaultValue(key));
|
||
}
|
||
}
|
||
}
|
||
else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
|
||
letters = arg.slice(1, -1).split('');
|
||
broken = false;
|
||
for (let j = 0; j < letters.length; j++) {
|
||
next = arg.slice(j + 2);
|
||
if (letters[j + 1] && letters[j + 1] === '=') {
|
||
value = arg.slice(j + 3);
|
||
key = letters[j];
|
||
if (checkAllAliases(key, flags.arrays)) {
|
||
// array format = '-f=a b c'
|
||
i = eatArray(i, key, args, value);
|
||
}
|
||
else if (checkAllAliases(key, flags.nargs) !== false) {
|
||
// nargs format = '-f=monkey washing cat'
|
||
i = eatNargs(i, key, args, value);
|
||
}
|
||
else {
|
||
setArg(key, value);
|
||
}
|
||
broken = true;
|
||
break;
|
||
}
|
||
if (next === '-') {
|
||
setArg(letters[j], next);
|
||
continue;
|
||
}
|
||
// current letter is an alphabetic character and next value is a number
|
||
if (/[A-Za-z]/.test(letters[j]) &&
|
||
/^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
|
||
checkAllAliases(next, flags.bools) === false) {
|
||
setArg(letters[j], next);
|
||
broken = true;
|
||
break;
|
||
}
|
||
if (letters[j + 1] && letters[j + 1].match(/\W/)) {
|
||
setArg(letters[j], next);
|
||
broken = true;
|
||
break;
|
||
}
|
||
else {
|
||
setArg(letters[j], defaultValue(letters[j]));
|
||
}
|
||
}
|
||
key = arg.slice(-1)[0];
|
||
if (!broken && key !== '-') {
|
||
if (checkAllAliases(key, flags.arrays)) {
|
||
// array format = '-f a b c'
|
||
i = eatArray(i, key, args);
|
||
}
|
||
else if (checkAllAliases(key, flags.nargs) !== false) {
|
||
// nargs format = '-f a b c'
|
||
// should be truthy even if: flags.nargs[key] === 0
|
||
i = eatNargs(i, key, args);
|
||
}
|
||
else {
|
||
next = args[i + 1];
|
||
if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
|
||
next.match(negative)) &&
|
||
!checkAllAliases(key, flags.bools) &&
|
||
!checkAllAliases(key, flags.counts)) {
|
||
setArg(key, next);
|
||
i++;
|
||
}
|
||
else if (/^(true|false)$/.test(next)) {
|
||
setArg(key, next);
|
||
i++;
|
||
}
|
||
else {
|
||
setArg(key, defaultValue(key));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
else if (arg.match(/^-[0-9]$/) &&
|
||
arg.match(negative) &&
|
||
checkAllAliases(arg.slice(1), flags.bools)) {
|
||
// single-digit boolean alias, e.g: xargs -0
|
||
key = arg.slice(1);
|
||
setArg(key, defaultValue(key));
|
||
}
|
||
else if (arg === '--') {
|
||
notFlags = args.slice(i + 1);
|
||
break;
|
||
}
|
||
else if (configuration['halt-at-non-option']) {
|
||
notFlags = args.slice(i);
|
||
break;
|
||
}
|
||
else {
|
||
pushPositional(arg);
|
||
}
|
||
}
|
||
// order of precedence:
|
||
// 1. command line arg
|
||
// 2. value from env var
|
||
// 3. value from config file
|
||
// 4. value from config objects
|
||
// 5. configured default value
|
||
applyEnvVars(argv, true); // special case: check env vars that point to config file
|
||
applyEnvVars(argv, false);
|
||
setConfig(argv);
|
||
setConfigObjects();
|
||
applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
|
||
applyCoercions(argv);
|
||
if (configuration['set-placeholder-key'])
|
||
setPlaceholderKeys(argv);
|
||
// for any counts either not in args or without an explicit default, set to 0
|
||
Object.keys(flags.counts).forEach(function (key) {
|
||
if (!hasKey(argv, key.split('.')))
|
||
setArg(key, 0);
|
||
});
|
||
// '--' defaults to undefined.
|
||
if (notFlagsOption && notFlags.length)
|
||
argv[notFlagsArgv] = [];
|
||
notFlags.forEach(function (key) {
|
||
argv[notFlagsArgv].push(key);
|
||
});
|
||
if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
|
||
Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
|
||
delete argv[key];
|
||
});
|
||
}
|
||
if (configuration['strip-aliased']) {
|
||
;
|
||
[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
|
||
if (configuration['camel-case-expansion'] && alias.includes('-')) {
|
||
delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
|
||
}
|
||
delete argv[alias];
|
||
});
|
||
}
|
||
// Push argument into positional array, applying numeric coercion:
|
||
function pushPositional(arg) {
|
||
const maybeCoercedNumber = maybeCoerceNumber('_', arg);
|
||
if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
|
||
argv._.push(maybeCoercedNumber);
|
||
}
|
||
}
|
||
// how many arguments should we consume, based
|
||
// on the nargs option?
|
||
function eatNargs(i, key, args, argAfterEqualSign) {
|
||
let ii;
|
||
let toEat = checkAllAliases(key, flags.nargs);
|
||
// NaN has a special meaning for the array type, indicating that one or
|
||
// more values are expected.
|
||
toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
|
||
if (toEat === 0) {
|
||
if (!isUndefined(argAfterEqualSign)) {
|
||
error = Error(__('Argument unexpected for: %s', key));
|
||
}
|
||
setArg(key, defaultValue(key));
|
||
return i;
|
||
}
|
||
let available = isUndefined(argAfterEqualSign) ? 0 : 1;
|
||
if (configuration['nargs-eats-options']) {
|
||
// classic behavior, yargs eats positional and dash arguments.
|
||
if (args.length - (i + 1) + available < toEat) {
|
||
error = Error(__('Not enough arguments following: %s', key));
|
||
}
|
||
available = toEat;
|
||
}
|
||
else {
|
||
// nargs will not consume flag arguments, e.g., -abc, --foo,
|
||
// and terminates when one is observed.
|
||
for (ii = i + 1; ii < args.length; ii++) {
|
||
if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
|
||
available++;
|
||
else
|
||
break;
|
||
}
|
||
if (available < toEat)
|
||
error = Error(__('Not enough arguments following: %s', key));
|
||
}
|
||
let consumed = Math.min(available, toEat);
|
||
if (!isUndefined(argAfterEqualSign) && consumed > 0) {
|
||
setArg(key, argAfterEqualSign);
|
||
consumed--;
|
||
}
|
||
for (ii = i + 1; ii < (consumed + i + 1); ii++) {
|
||
setArg(key, args[ii]);
|
||
}
|
||
return (i + consumed);
|
||
}
|
||
// if an option is an array, eat all non-hyphenated arguments
|
||
// following it... YUM!
|
||
// e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
|
||
function eatArray(i, key, args, argAfterEqualSign) {
|
||
let argsToSet = [];
|
||
let next = argAfterEqualSign || args[i + 1];
|
||
// If both array and nargs are configured, enforce the nargs count:
|
||
const nargsCount = checkAllAliases(key, flags.nargs);
|
||
if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
|
||
argsToSet.push(true);
|
||
}
|
||
else if (isUndefined(next) ||
|
||
(isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
|
||
// for keys without value ==> argsToSet remains an empty []
|
||
// set user default value, if available
|
||
if (defaults[key] !== undefined) {
|
||
const defVal = defaults[key];
|
||
argsToSet = Array.isArray(defVal) ? defVal : [defVal];
|
||
}
|
||
}
|
||
else {
|
||
// value in --option=value is eaten as is
|
||
if (!isUndefined(argAfterEqualSign)) {
|
||
argsToSet.push(processValue(key, argAfterEqualSign, true));
|
||
}
|
||
for (let ii = i + 1; ii < args.length; ii++) {
|
||
if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
|
||
(nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
|
||
break;
|
||
next = args[ii];
|
||
if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
|
||
break;
|
||
i = ii;
|
||
argsToSet.push(processValue(key, next, inputIsString));
|
||
}
|
||
}
|
||
// If both array and nargs are configured, create an error if less than
|
||
// nargs positionals were found. NaN has special meaning, indicating
|
||
// that at least one value is required (more are okay).
|
||
if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
|
||
(isNaN(nargsCount) && argsToSet.length === 0))) {
|
||
error = Error(__('Not enough arguments following: %s', key));
|
||
}
|
||
setArg(key, argsToSet);
|
||
return i;
|
||
}
|
||
function setArg(key, val, shouldStripQuotes = inputIsString) {
|
||
if (/-/.test(key) && configuration['camel-case-expansion']) {
|
||
const alias = key.split('.').map(function (prop) {
|
||
return camelCase(prop);
|
||
}).join('.');
|
||
addNewAlias(key, alias);
|
||
}
|
||
const value = processValue(key, val, shouldStripQuotes);
|
||
const splitKey = key.split('.');
|
||
setKey(argv, splitKey, value);
|
||
// handle populating aliases of the full key
|
||
if (flags.aliases[key]) {
|
||
flags.aliases[key].forEach(function (x) {
|
||
const keyProperties = x.split('.');
|
||
setKey(argv, keyProperties, value);
|
||
});
|
||
}
|
||
// handle populating aliases of the first element of the dot-notation key
|
||
if (splitKey.length > 1 && configuration['dot-notation']) {
|
||
;
|
||
(flags.aliases[splitKey[0]] || []).forEach(function (x) {
|
||
let keyProperties = x.split('.');
|
||
// expand alias with nested objects in key
|
||
const a = [].concat(splitKey);
|
||
a.shift(); // nuke the old key.
|
||
keyProperties = keyProperties.concat(a);
|
||
// populate alias only if is not already an alias of the full key
|
||
// (already populated above)
|
||
if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
|
||
setKey(argv, keyProperties, value);
|
||
}
|
||
});
|
||
}
|
||
// Set normalize getter and setter when key is in 'normalize' but isn't an array
|
||
if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
|
||
const keys = [key].concat(flags.aliases[key] || []);
|
||
keys.forEach(function (key) {
|
||
Object.defineProperty(argvReturn, key, {
|
||
enumerable: true,
|
||
get() {
|
||
return val;
|
||
},
|
||
set(value) {
|
||
val = typeof value === 'string' ? yargs_parser_mixin.normalize(value) : value;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
}
|
||
function addNewAlias(key, alias) {
|
||
if (!(flags.aliases[key] && flags.aliases[key].length)) {
|
||
flags.aliases[key] = [alias];
|
||
newAliases[alias] = true;
|
||
}
|
||
if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
|
||
addNewAlias(alias, key);
|
||
}
|
||
}
|
||
function processValue(key, val, shouldStripQuotes) {
|
||
// strings may be quoted, clean this up as we assign values.
|
||
if (shouldStripQuotes) {
|
||
val = stripQuotes(val);
|
||
}
|
||
// handle parsing boolean arguments --foo=true --bar false.
|
||
if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
|
||
if (typeof val === 'string')
|
||
val = val === 'true';
|
||
}
|
||
let value = Array.isArray(val)
|
||
? val.map(function (v) { return maybeCoerceNumber(key, v); })
|
||
: maybeCoerceNumber(key, val);
|
||
// increment a count given as arg (either no value or value parsed as boolean)
|
||
if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
|
||
value = increment();
|
||
}
|
||
// Set normalized value when key is in 'normalize' and in 'arrays'
|
||
if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
|
||
if (Array.isArray(val))
|
||
value = val.map((val) => { return yargs_parser_mixin.normalize(val); });
|
||
else
|
||
value = yargs_parser_mixin.normalize(val);
|
||
}
|
||
return value;
|
||
}
|
||
function maybeCoerceNumber(key, value) {
|
||
if (!configuration['parse-positional-numbers'] && key === '_')
|
||
return value;
|
||
if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
|
||
const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
|
||
if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
|
||
value = Number(value);
|
||
}
|
||
}
|
||
return value;
|
||
}
|
||
// set args from config.json file, this should be
|
||
// applied last so that defaults can be applied.
|
||
function setConfig(argv) {
|
||
const configLookup = Object.create(null);
|
||
// expand defaults/aliases, in-case any happen to reference
|
||
// the config.json file.
|
||
applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
|
||
Object.keys(flags.configs).forEach(function (configKey) {
|
||
const configPath = argv[configKey] || configLookup[configKey];
|
||
if (configPath) {
|
||
try {
|
||
let config = null;
|
||
const resolvedConfigPath = yargs_parser_mixin.resolve(yargs_parser_mixin.cwd(), configPath);
|
||
const resolveConfig = flags.configs[configKey];
|
||
if (typeof resolveConfig === 'function') {
|
||
try {
|
||
config = resolveConfig(resolvedConfigPath);
|
||
}
|
||
catch (e) {
|
||
config = e;
|
||
}
|
||
if (config instanceof Error) {
|
||
error = config;
|
||
return;
|
||
}
|
||
}
|
||
else {
|
||
config = yargs_parser_mixin.require(resolvedConfigPath);
|
||
}
|
||
setConfigObject(config);
|
||
}
|
||
catch (ex) {
|
||
// Deno will receive a PermissionDenied error if an attempt is
|
||
// made to load config without the --allow-read flag:
|
||
if (ex.name === 'PermissionDenied')
|
||
error = ex;
|
||
else if (argv[configKey])
|
||
error = Error(__('Invalid JSON config file: %s', configPath));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
// set args from config object.
|
||
// it recursively checks nested objects.
|
||
function setConfigObject(config, prev) {
|
||
Object.keys(config).forEach(function (key) {
|
||
const value = config[key];
|
||
const fullKey = prev ? prev + '.' + key : key;
|
||
// if the value is an inner object and we have dot-notation
|
||
// enabled, treat inner objects in config the same as
|
||
// heavily nested dot notations (foo.bar.apple).
|
||
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
|
||
// if the value is an object but not an array, check nested object
|
||
setConfigObject(value, fullKey);
|
||
}
|
||
else {
|
||
// setting arguments via CLI takes precedence over
|
||
// values within the config file.
|
||
if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
|
||
setArg(fullKey, value);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
// set all config objects passed in opts
|
||
function setConfigObjects() {
|
||
if (typeof configObjects !== 'undefined') {
|
||
configObjects.forEach(function (configObject) {
|
||
setConfigObject(configObject);
|
||
});
|
||
}
|
||
}
|
||
function applyEnvVars(argv, configOnly) {
|
||
if (typeof envPrefix === 'undefined')
|
||
return;
|
||
const prefix = typeof envPrefix === 'string' ? envPrefix : '';
|
||
const env = yargs_parser_mixin.env();
|
||
Object.keys(env).forEach(function (envVar) {
|
||
if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
|
||
// get array of nested keys and convert them to camel case
|
||
const keys = envVar.split('__').map(function (key, i) {
|
||
if (i === 0) {
|
||
key = key.substring(prefix.length);
|
||
}
|
||
return camelCase(key);
|
||
});
|
||
if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
|
||
setArg(keys.join('.'), env[envVar]);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
function applyCoercions(argv) {
|
||
let coerce;
|
||
const applied = new Set();
|
||
Object.keys(argv).forEach(function (key) {
|
||
if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
|
||
coerce = checkAllAliases(key, flags.coercions);
|
||
if (typeof coerce === 'function') {
|
||
try {
|
||
const value = maybeCoerceNumber(key, coerce(argv[key]));
|
||
([].concat(flags.aliases[key] || [], key)).forEach(ali => {
|
||
applied.add(ali);
|
||
argv[ali] = value;
|
||
});
|
||
}
|
||
catch (err) {
|
||
error = err;
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
function setPlaceholderKeys(argv) {
|
||
flags.keys.forEach((key) => {
|
||
// don't set placeholder keys for dot notation options 'foo.bar'.
|
||
if (~key.indexOf('.'))
|
||
return;
|
||
if (typeof argv[key] === 'undefined')
|
||
argv[key] = undefined;
|
||
});
|
||
return argv;
|
||
}
|
||
function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
|
||
Object.keys(defaults).forEach(function (key) {
|
||
if (!hasKey(obj, key.split('.'))) {
|
||
setKey(obj, key.split('.'), defaults[key]);
|
||
if (canLog)
|
||
defaulted[key] = true;
|
||
(aliases[key] || []).forEach(function (x) {
|
||
if (hasKey(obj, x.split('.')))
|
||
return;
|
||
setKey(obj, x.split('.'), defaults[key]);
|
||
});
|
||
}
|
||
});
|
||
}
|
||
function hasKey(obj, keys) {
|
||
let o = obj;
|
||
if (!configuration['dot-notation'])
|
||
keys = [keys.join('.')];
|
||
keys.slice(0, -1).forEach(function (key) {
|
||
o = (o[key] || {});
|
||
});
|
||
const key = keys[keys.length - 1];
|
||
if (typeof o !== 'object')
|
||
return false;
|
||
else
|
||
return key in o;
|
||
}
|
||
function setKey(obj, keys, value) {
|
||
let o = obj;
|
||
if (!configuration['dot-notation'])
|
||
keys = [keys.join('.')];
|
||
keys.slice(0, -1).forEach(function (key) {
|
||
// TODO(bcoe): in the next major version of yargs, switch to
|
||
// Object.create(null) for dot notation:
|
||
key = sanitizeKey(key);
|
||
if (typeof o === 'object' && o[key] === undefined) {
|
||
o[key] = {};
|
||
}
|
||
if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
|
||
// ensure that o[key] is an array, and that the last item is an empty object.
|
||
if (Array.isArray(o[key])) {
|
||
o[key].push({});
|
||
}
|
||
else {
|
||
o[key] = [o[key], {}];
|
||
}
|
||
// we want to update the empty object at the end of the o[key] array, so set o to that object
|
||
o = o[key][o[key].length - 1];
|
||
}
|
||
else {
|
||
o = o[key];
|
||
}
|
||
});
|
||
// TODO(bcoe): in the next major version of yargs, switch to
|
||
// Object.create(null) for dot notation:
|
||
const key = sanitizeKey(keys[keys.length - 1]);
|
||
const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
|
||
const isValueArray = Array.isArray(value);
|
||
let duplicate = configuration['duplicate-arguments-array'];
|
||
// nargs has higher priority than duplicate
|
||
if (!duplicate && checkAllAliases(key, flags.nargs)) {
|
||
duplicate = true;
|
||
if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
|
||
o[key] = undefined;
|
||
}
|
||
}
|
||
if (value === increment()) {
|
||
o[key] = increment(o[key]);
|
||
}
|
||
else if (Array.isArray(o[key])) {
|
||
if (duplicate && isTypeArray && isValueArray) {
|
||
o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
|
||
}
|
||
else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
|
||
o[key] = value;
|
||
}
|
||
else {
|
||
o[key] = o[key].concat([value]);
|
||
}
|
||
}
|
||
else if (o[key] === undefined && isTypeArray) {
|
||
o[key] = isValueArray ? value : [value];
|
||
}
|
||
else if (duplicate && !(o[key] === undefined ||
|
||
checkAllAliases(key, flags.counts) ||
|
||
checkAllAliases(key, flags.bools))) {
|
||
o[key] = [o[key], value];
|
||
}
|
||
else {
|
||
o[key] = value;
|
||
}
|
||
}
|
||
// extend the aliases list with inferred aliases.
|
||
function extendAliases(...args) {
|
||
args.forEach(function (obj) {
|
||
Object.keys(obj || {}).forEach(function (key) {
|
||
// short-circuit if we've already added a key
|
||
// to the aliases array, for example it might
|
||
// exist in both 'opts.default' and 'opts.key'.
|
||
if (flags.aliases[key])
|
||
return;
|
||
flags.aliases[key] = [].concat(aliases[key] || []);
|
||
// For "--option-name", also set argv.optionName
|
||
flags.aliases[key].concat(key).forEach(function (x) {
|
||
if (/-/.test(x) && configuration['camel-case-expansion']) {
|
||
const c = camelCase(x);
|
||
if (c !== key && flags.aliases[key].indexOf(c) === -1) {
|
||
flags.aliases[key].push(c);
|
||
newAliases[c] = true;
|
||
}
|
||
}
|
||
});
|
||
// For "--optionName", also set argv['option-name']
|
||
flags.aliases[key].concat(key).forEach(function (x) {
|
||
if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
|
||
const c = decamelize(x, '-');
|
||
if (c !== key && flags.aliases[key].indexOf(c) === -1) {
|
||
flags.aliases[key].push(c);
|
||
newAliases[c] = true;
|
||
}
|
||
}
|
||
});
|
||
flags.aliases[key].forEach(function (x) {
|
||
flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
|
||
return x !== y;
|
||
}));
|
||
});
|
||
});
|
||
});
|
||
}
|
||
function checkAllAliases(key, flag) {
|
||
const toCheck = [].concat(flags.aliases[key] || [], key);
|
||
const keys = Object.keys(flag);
|
||
const setAlias = toCheck.find(key => keys.includes(key));
|
||
return setAlias ? flag[setAlias] : false;
|
||
}
|
||
function hasAnyFlag(key) {
|
||
const flagsKeys = Object.keys(flags);
|
||
const toCheck = [].concat(flagsKeys.map(k => flags[k]));
|
||
return toCheck.some(function (flag) {
|
||
return Array.isArray(flag) ? flag.includes(key) : flag[key];
|
||
});
|
||
}
|
||
function hasFlagsMatching(arg, ...patterns) {
|
||
const toCheck = [].concat(...patterns);
|
||
return toCheck.some(function (pattern) {
|
||
const match = arg.match(pattern);
|
||
return match && hasAnyFlag(match[1]);
|
||
});
|
||
}
|
||
// based on a simplified version of the short flag group parsing logic
|
||
function hasAllShortFlags(arg) {
|
||
// if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
|
||
if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
|
||
return false;
|
||
}
|
||
let hasAllFlags = true;
|
||
let next;
|
||
const letters = arg.slice(1).split('');
|
||
for (let j = 0; j < letters.length; j++) {
|
||
next = arg.slice(j + 2);
|
||
if (!hasAnyFlag(letters[j])) {
|
||
hasAllFlags = false;
|
||
break;
|
||
}
|
||
if ((letters[j + 1] && letters[j + 1] === '=') ||
|
||
next === '-' ||
|
||
(/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
|
||
(letters[j + 1] && letters[j + 1].match(/\W/))) {
|
||
break;
|
||
}
|
||
}
|
||
return hasAllFlags;
|
||
}
|
||
function isUnknownOptionAsArg(arg) {
|
||
return configuration['unknown-options-as-args'] && isUnknownOption(arg);
|
||
}
|
||
function isUnknownOption(arg) {
|
||
arg = arg.replace(/^-{3,}/, '--');
|
||
// ignore negative numbers
|
||
if (arg.match(negative)) {
|
||
return false;
|
||
}
|
||
// if this is a short option group and all of them are configured, it isn't unknown
|
||
if (hasAllShortFlags(arg)) {
|
||
return false;
|
||
}
|
||
// e.g. '--count=2'
|
||
const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
|
||
// e.g. '-a' or '--arg'
|
||
const normalFlag = /^-+([^=]+?)$/;
|
||
// e.g. '-a-'
|
||
const flagEndingInHyphen = /^-+([^=]+?)-$/;
|
||
// e.g. '-abc123'
|
||
const flagEndingInDigits = /^-+([^=]+?\d+)$/;
|
||
// e.g. '-a/usr/local'
|
||
const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
|
||
// check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
|
||
return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
|
||
}
|
||
// make a best effort to pick a default value
|
||
// for an option based on name and type.
|
||
function defaultValue(key) {
|
||
if (!checkAllAliases(key, flags.bools) &&
|
||
!checkAllAliases(key, flags.counts) &&
|
||
`${key}` in defaults) {
|
||
return defaults[key];
|
||
}
|
||
else {
|
||
return defaultForType(guessType(key));
|
||
}
|
||
}
|
||
// return a default value, given the type of a flag.,
|
||
function defaultForType(type) {
|
||
const def = {
|
||
[DefaultValuesForTypeKey.BOOLEAN]: true,
|
||
[DefaultValuesForTypeKey.STRING]: '',
|
||
[DefaultValuesForTypeKey.NUMBER]: undefined,
|
||
[DefaultValuesForTypeKey.ARRAY]: []
|
||
};
|
||
return def[type];
|
||
}
|
||
// given a flag, enforce a default type.
|
||
function guessType(key) {
|
||
let type = DefaultValuesForTypeKey.BOOLEAN;
|
||
if (checkAllAliases(key, flags.strings))
|
||
type = DefaultValuesForTypeKey.STRING;
|
||
else if (checkAllAliases(key, flags.numbers))
|
||
type = DefaultValuesForTypeKey.NUMBER;
|
||
else if (checkAllAliases(key, flags.bools))
|
||
type = DefaultValuesForTypeKey.BOOLEAN;
|
||
else if (checkAllAliases(key, flags.arrays))
|
||
type = DefaultValuesForTypeKey.ARRAY;
|
||
return type;
|
||
}
|
||
function isUndefined(num) {
|
||
return num === undefined;
|
||
}
|
||
// check user configuration settings for inconsistencies
|
||
function checkConfiguration() {
|
||
// count keys should not be set as array/narg
|
||
Object.keys(flags.counts).find(key => {
|
||
if (checkAllAliases(key, flags.arrays)) {
|
||
error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
|
||
return true;
|
||
}
|
||
else if (checkAllAliases(key, flags.nargs)) {
|
||
error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
|
||
return true;
|
||
}
|
||
return false;
|
||
});
|
||
}
|
||
return {
|
||
aliases: Object.assign({}, flags.aliases),
|
||
argv: Object.assign(argvReturn, argv),
|
||
configuration: configuration,
|
||
defaulted: Object.assign({}, defaulted),
|
||
error: error,
|
||
newAliases: Object.assign({}, newAliases)
|
||
};
|
||
}
|
||
}
|
||
// if any aliases reference each other, we should
|
||
// merge them together.
|
||
function combineAliases(aliases) {
|
||
const aliasArrays = [];
|
||
const combined = Object.create(null);
|
||
let change = true;
|
||
// turn alias lookup hash {key: ['alias1', 'alias2']} into
|
||
// a simple array ['key', 'alias1', 'alias2']
|
||
Object.keys(aliases).forEach(function (key) {
|
||
aliasArrays.push([].concat(aliases[key], key));
|
||
});
|
||
// combine arrays until zero changes are
|
||
// made in an iteration.
|
||
while (change) {
|
||
change = false;
|
||
for (let i = 0; i < aliasArrays.length; i++) {
|
||
for (let ii = i + 1; ii < aliasArrays.length; ii++) {
|
||
const intersect = aliasArrays[i].filter(function (v) {
|
||
return aliasArrays[ii].indexOf(v) !== -1;
|
||
});
|
||
if (intersect.length) {
|
||
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
|
||
aliasArrays.splice(ii, 1);
|
||
change = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// map arrays back to the hash-lookup (de-dupe while
|
||
// we're at it).
|
||
aliasArrays.forEach(function (aliasArray) {
|
||
aliasArray = aliasArray.filter(function (v, i, self) {
|
||
return self.indexOf(v) === i;
|
||
});
|
||
const lastAlias = aliasArray.pop();
|
||
if (lastAlias !== undefined && typeof lastAlias === 'string') {
|
||
combined[lastAlias] = aliasArray;
|
||
}
|
||
});
|
||
return combined;
|
||
}
|
||
// this function should only be called when a count is given as an arg
|
||
// it is NOT called to set a default value
|
||
// thus we can start the count at 1 instead of 0
|
||
function increment(orig) {
|
||
return orig !== undefined ? orig + 1 : 1;
|
||
}
|
||
// TODO(bcoe): in the next major version of yargs, switch to
|
||
// Object.create(null) for dot notation:
|
||
function sanitizeKey(key) {
|
||
if (key === '__proto__')
|
||
return '___proto___';
|
||
return key;
|
||
}
|
||
function stripQuotes(val) {
|
||
return (typeof val === 'string' &&
|
||
(val[0] === "'" || val[0] === '"') &&
|
||
val[val.length - 1] === val[0])
|
||
? val.substring(1, val.length - 1)
|
||
: val;
|
||
}
|
||
|
||
;// ./node_modules/yargs-parser/build/lib/index.js
|
||
/**
|
||
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
||
* CJS and ESM environments.
|
||
*
|
||
* @license
|
||
* Copyright (c) 2016, Contributors
|
||
* SPDX-License-Identifier: ISC
|
||
*/
|
||
var _a, _b, _c;
|
||
|
||
|
||
|
||
|
||
|
||
// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
|
||
// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
|
||
const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
|
||
? Number(process.env.YARGS_MIN_NODE_VERSION)
|
||
: 12;
|
||
const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
|
||
if (nodeVersion) {
|
||
const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
|
||
if (major < minNodeVersion) {
|
||
throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
|
||
}
|
||
}
|
||
// Creates a yargs-parser instance using Node.js standard libraries:
|
||
const env = process ? process.env : {};
|
||
const parser = new YargsParser({
|
||
cwd: process.cwd,
|
||
env: () => {
|
||
return env;
|
||
},
|
||
format: external_util_namespaceObject.format,
|
||
normalize: external_path_namespaceObject.normalize,
|
||
resolve: external_path_namespaceObject.resolve,
|
||
// TODO: figure out a way to combine ESM and CJS coverage, such that
|
||
// we can exercise all the lines below:
|
||
require: (path) => {
|
||
if (typeof require !== 'undefined') {
|
||
return require(path);
|
||
}
|
||
else if (path.match(/\.json$/)) {
|
||
// Addresses: https://github.com/yargs/yargs/issues/2040
|
||
return JSON.parse((0,external_fs_namespaceObject.readFileSync)(path, 'utf8'));
|
||
}
|
||
else {
|
||
throw Error('only .json config files are supported in ESM');
|
||
}
|
||
}
|
||
});
|
||
const yargsParser = function Parser(args, opts) {
|
||
const result = parser.parse(args.slice(), opts);
|
||
return result.argv;
|
||
};
|
||
yargsParser.detailed = function (args, opts) {
|
||
return parser.parse(args.slice(), opts);
|
||
};
|
||
yargsParser.camelCase = camelCase;
|
||
yargsParser.decamelize = decamelize;
|
||
yargsParser.looksLikeNumber = looksLikeNumber;
|
||
/* harmony default export */ const lib = (yargsParser);
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/process-argv.js
|
||
function getProcessArgvBinIndex() {
|
||
if (isBundledElectronApp())
|
||
return 0;
|
||
return 1;
|
||
}
|
||
function isBundledElectronApp() {
|
||
return isElectronApp() && !process.defaultApp;
|
||
}
|
||
function isElectronApp() {
|
||
return !!process.versions.electron;
|
||
}
|
||
function hideBin(argv) {
|
||
return argv.slice(getProcessArgvBinIndex() + 1);
|
||
}
|
||
function getProcessArgvBin() {
|
||
return process.argv[getProcessArgvBinIndex()];
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/yerror.js
|
||
class YError extends Error {
|
||
constructor(msg) {
|
||
super(msg || 'yargs error');
|
||
this.name = 'YError';
|
||
if (Error.captureStackTrace) {
|
||
Error.captureStackTrace(this, YError);
|
||
}
|
||
}
|
||
}
|
||
|
||
;// ./node_modules/y18n/build/lib/platform-shims/node.js
|
||
|
||
|
||
|
||
/* harmony default export */ const node = ({
|
||
fs: {
|
||
readFileSync: external_fs_namespaceObject.readFileSync,
|
||
writeFile: external_fs_namespaceObject.writeFile
|
||
},
|
||
format: external_util_namespaceObject.format,
|
||
resolve: external_path_namespaceObject.resolve,
|
||
exists: (file) => {
|
||
try {
|
||
return (0,external_fs_namespaceObject.statSync)(file).isFile();
|
||
}
|
||
catch (err) {
|
||
return false;
|
||
}
|
||
}
|
||
});
|
||
|
||
;// ./node_modules/y18n/build/lib/index.js
|
||
let lib_shim;
|
||
class Y18N {
|
||
constructor(opts) {
|
||
// configurable options.
|
||
opts = opts || {};
|
||
this.directory = opts.directory || './locales';
|
||
this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
|
||
this.locale = opts.locale || 'en';
|
||
this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
|
||
// internal stuff.
|
||
this.cache = Object.create(null);
|
||
this.writeQueue = [];
|
||
}
|
||
__(...args) {
|
||
if (typeof arguments[0] !== 'string') {
|
||
return this._taggedLiteral(arguments[0], ...arguments);
|
||
}
|
||
const str = args.shift();
|
||
let cb = function () { }; // start with noop.
|
||
if (typeof args[args.length - 1] === 'function')
|
||
cb = args.pop();
|
||
cb = cb || function () { }; // noop.
|
||
if (!this.cache[this.locale])
|
||
this._readLocaleFile();
|
||
// we've observed a new string, update the language file.
|
||
if (!this.cache[this.locale][str] && this.updateFiles) {
|
||
this.cache[this.locale][str] = str;
|
||
// include the current directory and locale,
|
||
// since these values could change before the
|
||
// write is performed.
|
||
this._enqueueWrite({
|
||
directory: this.directory,
|
||
locale: this.locale,
|
||
cb
|
||
});
|
||
}
|
||
else {
|
||
cb();
|
||
}
|
||
return lib_shim.format.apply(lib_shim.format, [this.cache[this.locale][str] || str].concat(args));
|
||
}
|
||
__n() {
|
||
const args = Array.prototype.slice.call(arguments);
|
||
const singular = args.shift();
|
||
const plural = args.shift();
|
||
const quantity = args.shift();
|
||
let cb = function () { }; // start with noop.
|
||
if (typeof args[args.length - 1] === 'function')
|
||
cb = args.pop();
|
||
if (!this.cache[this.locale])
|
||
this._readLocaleFile();
|
||
let str = quantity === 1 ? singular : plural;
|
||
if (this.cache[this.locale][singular]) {
|
||
const entry = this.cache[this.locale][singular];
|
||
str = entry[quantity === 1 ? 'one' : 'other'];
|
||
}
|
||
// we've observed a new string, update the language file.
|
||
if (!this.cache[this.locale][singular] && this.updateFiles) {
|
||
this.cache[this.locale][singular] = {
|
||
one: singular,
|
||
other: plural
|
||
};
|
||
// include the current directory and locale,
|
||
// since these values could change before the
|
||
// write is performed.
|
||
this._enqueueWrite({
|
||
directory: this.directory,
|
||
locale: this.locale,
|
||
cb
|
||
});
|
||
}
|
||
else {
|
||
cb();
|
||
}
|
||
// if a %d placeholder is provided, add quantity
|
||
// to the arguments expanded by util.format.
|
||
const values = [str];
|
||
if (~str.indexOf('%d'))
|
||
values.push(quantity);
|
||
return lib_shim.format.apply(lib_shim.format, values.concat(args));
|
||
}
|
||
setLocale(locale) {
|
||
this.locale = locale;
|
||
}
|
||
getLocale() {
|
||
return this.locale;
|
||
}
|
||
updateLocale(obj) {
|
||
if (!this.cache[this.locale])
|
||
this._readLocaleFile();
|
||
for (const key in obj) {
|
||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||
this.cache[this.locale][key] = obj[key];
|
||
}
|
||
}
|
||
}
|
||
_taggedLiteral(parts, ...args) {
|
||
let str = '';
|
||
parts.forEach(function (part, i) {
|
||
const arg = args[i + 1];
|
||
str += part;
|
||
if (typeof arg !== 'undefined') {
|
||
str += '%s';
|
||
}
|
||
});
|
||
return this.__.apply(this, [str].concat([].slice.call(args, 1)));
|
||
}
|
||
_enqueueWrite(work) {
|
||
this.writeQueue.push(work);
|
||
if (this.writeQueue.length === 1)
|
||
this._processWriteQueue();
|
||
}
|
||
_processWriteQueue() {
|
||
const _this = this;
|
||
const work = this.writeQueue[0];
|
||
// destructure the enqueued work.
|
||
const directory = work.directory;
|
||
const locale = work.locale;
|
||
const cb = work.cb;
|
||
const languageFile = this._resolveLocaleFile(directory, locale);
|
||
const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
|
||
lib_shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
|
||
_this.writeQueue.shift();
|
||
if (_this.writeQueue.length > 0)
|
||
_this._processWriteQueue();
|
||
cb(err);
|
||
});
|
||
}
|
||
_readLocaleFile() {
|
||
let localeLookup = {};
|
||
const languageFile = this._resolveLocaleFile(this.directory, this.locale);
|
||
try {
|
||
// When using a bundler such as webpack, readFileSync may not be defined:
|
||
if (lib_shim.fs.readFileSync) {
|
||
localeLookup = JSON.parse(lib_shim.fs.readFileSync(languageFile, 'utf-8'));
|
||
}
|
||
}
|
||
catch (err) {
|
||
if (err instanceof SyntaxError) {
|
||
err.message = 'syntax error in ' + languageFile;
|
||
}
|
||
if (err.code === 'ENOENT')
|
||
localeLookup = {};
|
||
else
|
||
throw err;
|
||
}
|
||
this.cache[this.locale] = localeLookup;
|
||
}
|
||
_resolveLocaleFile(directory, locale) {
|
||
let file = lib_shim.resolve(directory, './', locale + '.json');
|
||
if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
|
||
// attempt fallback to language only
|
||
const languageFile = lib_shim.resolve(directory, './', locale.split('_')[0] + '.json');
|
||
if (this._fileExistsSync(languageFile))
|
||
file = languageFile;
|
||
}
|
||
return file;
|
||
}
|
||
_fileExistsSync(file) {
|
||
return lib_shim.exists(file);
|
||
}
|
||
}
|
||
function y18n(opts, _shim) {
|
||
lib_shim = _shim;
|
||
const y18n = new Y18N(opts);
|
||
return {
|
||
__: y18n.__.bind(y18n),
|
||
__n: y18n.__n.bind(y18n),
|
||
setLocale: y18n.setLocale.bind(y18n),
|
||
getLocale: y18n.getLocale.bind(y18n),
|
||
updateLocale: y18n.updateLocale.bind(y18n),
|
||
locale: y18n.locale
|
||
};
|
||
}
|
||
|
||
;// ./node_modules/y18n/index.mjs
|
||
|
||
|
||
|
||
const y18n_y18n = (opts) => {
|
||
return y18n(opts, node)
|
||
}
|
||
|
||
/* harmony default export */ const node_modules_y18n = (y18n_y18n);
|
||
|
||
;// ./node_modules/yargs/lib/platform-shims/esm.mjs
|
||
|
||
|
||
;
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
const REQUIRE_ERROR = 'require is not supported by ESM'
|
||
const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM'
|
||
|
||
let esm_dirname;
|
||
try {
|
||
esm_dirname = (0,external_url_namespaceObject.fileURLToPath)("file:///C:/Users/zx/Desktop/polymech/polymech-mono/packages/media/ref/node_modules/yargs/lib/platform-shims/esm.mjs");
|
||
} catch (e) {
|
||
esm_dirname = process.cwd();
|
||
}
|
||
const mainFilename = esm_dirname.substring(0, esm_dirname.lastIndexOf('node_modules'));
|
||
|
||
/* harmony default export */ const esm = ({
|
||
assert: {
|
||
notStrictEqual: external_assert_namespaceObject.notStrictEqual,
|
||
strictEqual: external_assert_namespaceObject.strictEqual
|
||
},
|
||
cliui: ui,
|
||
findUp: sync,
|
||
getEnv: (key) => {
|
||
return process.env[key]
|
||
},
|
||
inspect: external_util_namespaceObject.inspect,
|
||
getCallerFile: () => {
|
||
throw new YError(REQUIRE_DIRECTORY_ERROR)
|
||
},
|
||
getProcessArgvBin: getProcessArgvBin,
|
||
mainFilename: mainFilename || process.cwd(),
|
||
Parser: lib,
|
||
path: {
|
||
basename: external_path_namespaceObject.basename,
|
||
dirname: external_path_namespaceObject.dirname,
|
||
extname: external_path_namespaceObject.extname,
|
||
relative: external_path_namespaceObject.relative,
|
||
resolve: external_path_namespaceObject.resolve
|
||
},
|
||
process: {
|
||
argv: () => process.argv,
|
||
cwd: process.cwd,
|
||
emitWarning: (warning, type) => process.emitWarning(warning, type),
|
||
execPath: () => process.execPath,
|
||
exit: process.exit,
|
||
nextTick: process.nextTick,
|
||
stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
|
||
},
|
||
readFileSync: external_fs_namespaceObject.readFileSync,
|
||
require: () => {
|
||
throw new YError(REQUIRE_ERROR)
|
||
},
|
||
requireDirectory: () => {
|
||
throw new YError(REQUIRE_DIRECTORY_ERROR)
|
||
},
|
||
stringWidth: (str) => {
|
||
return [...str].length
|
||
},
|
||
y18n: node_modules_y18n({
|
||
directory: (0,external_path_namespaceObject.resolve)(esm_dirname, '../../../locales'),
|
||
updateFiles: false
|
||
})
|
||
});
|
||
|
||
;// ./node_modules/yargs/build/lib/typings/common-types.js
|
||
function assertNotStrictEqual(actual, expected, shim, message) {
|
||
shim.assert.notStrictEqual(actual, expected, message);
|
||
}
|
||
function assertSingleKey(actual, shim) {
|
||
shim.assert.strictEqual(typeof actual, 'string');
|
||
}
|
||
function objectKeys(object) {
|
||
return Object.keys(object);
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/is-promise.js
|
||
function isPromise(maybePromise) {
|
||
return (!!maybePromise &&
|
||
!!maybePromise.then &&
|
||
typeof maybePromise.then === 'function');
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/parse-command.js
|
||
function parseCommand(cmd) {
|
||
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
|
||
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
|
||
const bregex = /\.*[\][<>]/g;
|
||
const firstCommand = splitCommand.shift();
|
||
if (!firstCommand)
|
||
throw new Error(`No command found in: ${cmd}`);
|
||
const parsedCommand = {
|
||
cmd: firstCommand.replace(bregex, ''),
|
||
demanded: [],
|
||
optional: [],
|
||
};
|
||
splitCommand.forEach((cmd, i) => {
|
||
let variadic = false;
|
||
cmd = cmd.replace(/\s/g, '');
|
||
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
|
||
variadic = true;
|
||
if (/^\[/.test(cmd)) {
|
||
parsedCommand.optional.push({
|
||
cmd: cmd.replace(bregex, '').split('|'),
|
||
variadic,
|
||
});
|
||
}
|
||
else {
|
||
parsedCommand.demanded.push({
|
||
cmd: cmd.replace(bregex, '').split('|'),
|
||
variadic,
|
||
});
|
||
}
|
||
});
|
||
return parsedCommand;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/argsert.js
|
||
|
||
|
||
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
||
function argsert(arg1, arg2, arg3) {
|
||
function parseArgs() {
|
||
return typeof arg1 === 'object'
|
||
? [{ demanded: [], optional: [] }, arg1, arg2]
|
||
: [
|
||
parseCommand(`cmd ${arg1}`),
|
||
arg2,
|
||
arg3,
|
||
];
|
||
}
|
||
try {
|
||
let position = 0;
|
||
const [parsed, callerArguments, _length] = parseArgs();
|
||
const args = [].slice.call(callerArguments);
|
||
while (args.length && args[args.length - 1] === undefined)
|
||
args.pop();
|
||
const length = _length || args.length;
|
||
if (length < parsed.demanded.length) {
|
||
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
|
||
}
|
||
const totalCommands = parsed.demanded.length + parsed.optional.length;
|
||
if (length > totalCommands) {
|
||
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
|
||
}
|
||
parsed.demanded.forEach(demanded => {
|
||
const arg = args.shift();
|
||
const observedType = guessType(arg);
|
||
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
|
||
if (matchingTypes.length === 0)
|
||
argumentTypeError(observedType, demanded.cmd, position);
|
||
position += 1;
|
||
});
|
||
parsed.optional.forEach(optional => {
|
||
if (args.length === 0)
|
||
return;
|
||
const arg = args.shift();
|
||
const observedType = guessType(arg);
|
||
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
|
||
if (matchingTypes.length === 0)
|
||
argumentTypeError(observedType, optional.cmd, position);
|
||
position += 1;
|
||
});
|
||
}
|
||
catch (err) {
|
||
console.warn(err.stack);
|
||
}
|
||
}
|
||
function guessType(arg) {
|
||
if (Array.isArray(arg)) {
|
||
return 'array';
|
||
}
|
||
else if (arg === null) {
|
||
return 'null';
|
||
}
|
||
return typeof arg;
|
||
}
|
||
function argumentTypeError(observedType, allowedTypes, position) {
|
||
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/middleware.js
|
||
|
||
|
||
class GlobalMiddleware {
|
||
constructor(yargs) {
|
||
this.globalMiddleware = [];
|
||
this.frozens = [];
|
||
this.yargs = yargs;
|
||
}
|
||
addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) {
|
||
argsert('<array|function> [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length);
|
||
if (Array.isArray(callback)) {
|
||
for (let i = 0; i < callback.length; i++) {
|
||
if (typeof callback[i] !== 'function') {
|
||
throw Error('middleware must be a function');
|
||
}
|
||
const m = callback[i];
|
||
m.applyBeforeValidation = applyBeforeValidation;
|
||
m.global = global;
|
||
}
|
||
Array.prototype.push.apply(this.globalMiddleware, callback);
|
||
}
|
||
else if (typeof callback === 'function') {
|
||
const m = callback;
|
||
m.applyBeforeValidation = applyBeforeValidation;
|
||
m.global = global;
|
||
m.mutates = mutates;
|
||
this.globalMiddleware.push(callback);
|
||
}
|
||
return this.yargs;
|
||
}
|
||
addCoerceMiddleware(callback, option) {
|
||
const aliases = this.yargs.getAliases();
|
||
this.globalMiddleware = this.globalMiddleware.filter(m => {
|
||
const toCheck = [...(aliases[option] || []), option];
|
||
if (!m.option)
|
||
return true;
|
||
else
|
||
return !toCheck.includes(m.option);
|
||
});
|
||
callback.option = option;
|
||
return this.addMiddleware(callback, true, true, true);
|
||
}
|
||
getMiddleware() {
|
||
return this.globalMiddleware;
|
||
}
|
||
freeze() {
|
||
this.frozens.push([...this.globalMiddleware]);
|
||
}
|
||
unfreeze() {
|
||
const frozen = this.frozens.pop();
|
||
if (frozen !== undefined)
|
||
this.globalMiddleware = frozen;
|
||
}
|
||
reset() {
|
||
this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
|
||
}
|
||
}
|
||
function commandMiddlewareFactory(commandMiddleware) {
|
||
if (!commandMiddleware)
|
||
return [];
|
||
return commandMiddleware.map(middleware => {
|
||
middleware.applyBeforeValidation = false;
|
||
return middleware;
|
||
});
|
||
}
|
||
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
|
||
return middlewares.reduce((acc, middleware) => {
|
||
if (middleware.applyBeforeValidation !== beforeValidation) {
|
||
return acc;
|
||
}
|
||
if (middleware.mutates) {
|
||
if (middleware.applied)
|
||
return acc;
|
||
middleware.applied = true;
|
||
}
|
||
if (isPromise(acc)) {
|
||
return acc
|
||
.then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)]))
|
||
.then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
|
||
}
|
||
else {
|
||
const result = middleware(acc, yargs);
|
||
return isPromise(result)
|
||
? result.then(middlewareObj => Object.assign(acc, middlewareObj))
|
||
: Object.assign(acc, result);
|
||
}
|
||
}, argv);
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/maybe-async-result.js
|
||
|
||
function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
|
||
throw err;
|
||
}) {
|
||
try {
|
||
const result = isFunction(getResult) ? getResult() : getResult;
|
||
return isPromise(result)
|
||
? result.then((result) => resultHandler(result))
|
||
: resultHandler(result);
|
||
}
|
||
catch (err) {
|
||
return errorHandler(err);
|
||
}
|
||
}
|
||
function isFunction(arg) {
|
||
return typeof arg === 'function';
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/which-module.js
|
||
function whichModule(exported) {
|
||
if (typeof require === 'undefined')
|
||
return null;
|
||
for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
|
||
mod = require.cache[files[i]];
|
||
if (mod.exports === exported)
|
||
return mod;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/command.js
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
|
||
class CommandInstance {
|
||
constructor(usage, validation, globalMiddleware, shim) {
|
||
this.requireCache = new Set();
|
||
this.handlers = {};
|
||
this.aliasMap = {};
|
||
this.frozens = [];
|
||
this.shim = shim;
|
||
this.usage = usage;
|
||
this.globalMiddleware = globalMiddleware;
|
||
this.validation = validation;
|
||
}
|
||
addDirectory(dir, req, callerFile, opts) {
|
||
opts = opts || {};
|
||
if (typeof opts.recurse !== 'boolean')
|
||
opts.recurse = false;
|
||
if (!Array.isArray(opts.extensions))
|
||
opts.extensions = ['js'];
|
||
const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
|
||
opts.visit = (obj, joined, filename) => {
|
||
const visited = parentVisit(obj, joined, filename);
|
||
if (visited) {
|
||
if (this.requireCache.has(joined))
|
||
return visited;
|
||
else
|
||
this.requireCache.add(joined);
|
||
this.addHandler(visited);
|
||
}
|
||
return visited;
|
||
};
|
||
this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
|
||
}
|
||
addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
|
||
let aliases = [];
|
||
const middlewares = commandMiddlewareFactory(commandMiddleware);
|
||
handler = handler || (() => { });
|
||
if (Array.isArray(cmd)) {
|
||
if (isCommandAndAliases(cmd)) {
|
||
[cmd, ...aliases] = cmd;
|
||
}
|
||
else {
|
||
for (const command of cmd) {
|
||
this.addHandler(command);
|
||
}
|
||
}
|
||
}
|
||
else if (isCommandHandlerDefinition(cmd)) {
|
||
let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
|
||
? cmd.command
|
||
: this.moduleName(cmd);
|
||
if (cmd.aliases)
|
||
command = [].concat(command).concat(cmd.aliases);
|
||
this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
|
||
return;
|
||
}
|
||
else if (isCommandBuilderDefinition(builder)) {
|
||
this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
|
||
return;
|
||
}
|
||
if (typeof cmd === 'string') {
|
||
const parsedCommand = parseCommand(cmd);
|
||
aliases = aliases.map(alias => parseCommand(alias).cmd);
|
||
let isDefault = false;
|
||
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
|
||
if (DEFAULT_MARKER.test(c)) {
|
||
isDefault = true;
|
||
return false;
|
||
}
|
||
return true;
|
||
});
|
||
if (parsedAliases.length === 0 && isDefault)
|
||
parsedAliases.push('$0');
|
||
if (isDefault) {
|
||
parsedCommand.cmd = parsedAliases[0];
|
||
aliases = parsedAliases.slice(1);
|
||
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
|
||
}
|
||
aliases.forEach(alias => {
|
||
this.aliasMap[alias] = parsedCommand.cmd;
|
||
});
|
||
if (description !== false) {
|
||
this.usage.command(cmd, description, isDefault, aliases, deprecated);
|
||
}
|
||
this.handlers[parsedCommand.cmd] = {
|
||
original: cmd,
|
||
description,
|
||
handler,
|
||
builder: builder || {},
|
||
middlewares,
|
||
deprecated,
|
||
demanded: parsedCommand.demanded,
|
||
optional: parsedCommand.optional,
|
||
};
|
||
if (isDefault)
|
||
this.defaultCommand = this.handlers[parsedCommand.cmd];
|
||
}
|
||
}
|
||
getCommandHandlers() {
|
||
return this.handlers;
|
||
}
|
||
getCommands() {
|
||
return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
|
||
}
|
||
hasDefaultCommand() {
|
||
return !!this.defaultCommand;
|
||
}
|
||
runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
|
||
const commandHandler = this.handlers[command] ||
|
||
this.handlers[this.aliasMap[command]] ||
|
||
this.defaultCommand;
|
||
const currentContext = yargs.getInternalMethods().getContext();
|
||
const parentCommands = currentContext.commands.slice();
|
||
const isDefaultCommand = !command;
|
||
if (command) {
|
||
currentContext.commands.push(command);
|
||
currentContext.fullCommands.push(commandHandler.original);
|
||
}
|
||
const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
|
||
return isPromise(builderResult)
|
||
? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs))
|
||
: this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
|
||
}
|
||
applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
|
||
const builder = commandHandler.builder;
|
||
let innerYargs = yargs;
|
||
if (isCommandBuilderCallback(builder)) {
|
||
yargs.getInternalMethods().getUsageInstance().freeze();
|
||
const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
|
||
if (isPromise(builderOutput)) {
|
||
return builderOutput.then(output => {
|
||
innerYargs = isYargsInstance(output) ? output : yargs;
|
||
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
|
||
});
|
||
}
|
||
}
|
||
else if (isCommandBuilderOptionDefinitions(builder)) {
|
||
yargs.getInternalMethods().getUsageInstance().freeze();
|
||
innerYargs = yargs.getInternalMethods().reset(aliases);
|
||
Object.keys(commandHandler.builder).forEach(key => {
|
||
innerYargs.option(key, builder[key]);
|
||
});
|
||
}
|
||
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
|
||
}
|
||
parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
|
||
if (isDefaultCommand)
|
||
innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
|
||
if (this.shouldUpdateUsage(innerYargs)) {
|
||
innerYargs
|
||
.getInternalMethods()
|
||
.getUsageInstance()
|
||
.usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
|
||
}
|
||
const innerArgv = innerYargs
|
||
.getInternalMethods()
|
||
.runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly);
|
||
return isPromise(innerArgv)
|
||
? innerArgv.then(argv => ({
|
||
aliases: innerYargs.parsed.aliases,
|
||
innerArgv: argv,
|
||
}))
|
||
: {
|
||
aliases: innerYargs.parsed.aliases,
|
||
innerArgv: innerArgv,
|
||
};
|
||
}
|
||
shouldUpdateUsage(yargs) {
|
||
return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
|
||
yargs.getInternalMethods().getUsageInstance().getUsage().length === 0);
|
||
}
|
||
usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
|
||
const c = DEFAULT_MARKER.test(commandHandler.original)
|
||
? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
|
||
: commandHandler.original;
|
||
const pc = parentCommands.filter(c => {
|
||
return !DEFAULT_MARKER.test(c);
|
||
});
|
||
pc.push(c);
|
||
return `$0 ${pc.join(' ')}`;
|
||
}
|
||
handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
|
||
if (!yargs.getInternalMethods().getHasOutput()) {
|
||
const validation = yargs
|
||
.getInternalMethods()
|
||
.runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
|
||
innerArgv = maybeAsyncResult(innerArgv, result => {
|
||
validation(result);
|
||
return result;
|
||
});
|
||
}
|
||
if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
|
||
yargs.getInternalMethods().setHasOutput();
|
||
const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
|
||
yargs
|
||
.getInternalMethods()
|
||
.postProcess(innerArgv, populateDoubleDash, false, false);
|
||
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
|
||
innerArgv = maybeAsyncResult(innerArgv, result => {
|
||
const handlerResult = commandHandler.handler(result);
|
||
return isPromise(handlerResult)
|
||
? handlerResult.then(() => result)
|
||
: result;
|
||
});
|
||
if (!isDefaultCommand) {
|
||
yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
|
||
}
|
||
if (isPromise(innerArgv) &&
|
||
!yargs.getInternalMethods().hasParseCallback()) {
|
||
innerArgv.catch(error => {
|
||
try {
|
||
yargs.getInternalMethods().getUsageInstance().fail(null, error);
|
||
}
|
||
catch (_err) {
|
||
}
|
||
});
|
||
}
|
||
}
|
||
if (!isDefaultCommand) {
|
||
currentContext.commands.pop();
|
||
currentContext.fullCommands.pop();
|
||
}
|
||
return innerArgv;
|
||
}
|
||
applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
|
||
let positionalMap = {};
|
||
if (helpOnly)
|
||
return innerArgv;
|
||
if (!yargs.getInternalMethods().getHasOutput()) {
|
||
positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
|
||
}
|
||
const middlewares = this.globalMiddleware
|
||
.getMiddleware()
|
||
.slice(0)
|
||
.concat(commandHandler.middlewares);
|
||
const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
|
||
return isPromise(maybePromiseArgv)
|
||
? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap))
|
||
: this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
|
||
}
|
||
populatePositionals(commandHandler, argv, context, yargs) {
|
||
argv._ = argv._.slice(context.commands.length);
|
||
const demanded = commandHandler.demanded.slice(0);
|
||
const optional = commandHandler.optional.slice(0);
|
||
const positionalMap = {};
|
||
this.validation.positionalCount(demanded.length, argv._.length);
|
||
while (demanded.length) {
|
||
const demand = demanded.shift();
|
||
this.populatePositional(demand, argv, positionalMap);
|
||
}
|
||
while (optional.length) {
|
||
const maybe = optional.shift();
|
||
this.populatePositional(maybe, argv, positionalMap);
|
||
}
|
||
argv._ = context.commands.concat(argv._.map(a => '' + a));
|
||
this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
|
||
return positionalMap;
|
||
}
|
||
populatePositional(positional, argv, positionalMap) {
|
||
const cmd = positional.cmd[0];
|
||
if (positional.variadic) {
|
||
positionalMap[cmd] = argv._.splice(0).map(String);
|
||
}
|
||
else {
|
||
if (argv._.length)
|
||
positionalMap[cmd] = [String(argv._.shift())];
|
||
}
|
||
}
|
||
cmdToParseOptions(cmdString) {
|
||
const parseOptions = {
|
||
array: [],
|
||
default: {},
|
||
alias: {},
|
||
demand: {},
|
||
};
|
||
const parsed = parseCommand(cmdString);
|
||
parsed.demanded.forEach(d => {
|
||
const [cmd, ...aliases] = d.cmd;
|
||
if (d.variadic) {
|
||
parseOptions.array.push(cmd);
|
||
parseOptions.default[cmd] = [];
|
||
}
|
||
parseOptions.alias[cmd] = aliases;
|
||
parseOptions.demand[cmd] = true;
|
||
});
|
||
parsed.optional.forEach(o => {
|
||
const [cmd, ...aliases] = o.cmd;
|
||
if (o.variadic) {
|
||
parseOptions.array.push(cmd);
|
||
parseOptions.default[cmd] = [];
|
||
}
|
||
parseOptions.alias[cmd] = aliases;
|
||
});
|
||
return parseOptions;
|
||
}
|
||
postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
|
||
const options = Object.assign({}, yargs.getOptions());
|
||
options.default = Object.assign(parseOptions.default, options.default);
|
||
for (const key of Object.keys(parseOptions.alias)) {
|
||
options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
|
||
}
|
||
options.array = options.array.concat(parseOptions.array);
|
||
options.config = {};
|
||
const unparsed = [];
|
||
Object.keys(positionalMap).forEach(key => {
|
||
positionalMap[key].map(value => {
|
||
if (options.configuration['unknown-options-as-args'])
|
||
options.key[key] = true;
|
||
unparsed.push(`--${key}`);
|
||
unparsed.push(value);
|
||
});
|
||
});
|
||
if (!unparsed.length)
|
||
return;
|
||
const config = Object.assign({}, options.configuration, {
|
||
'populate--': false,
|
||
});
|
||
const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
|
||
configuration: config,
|
||
}));
|
||
if (parsed.error) {
|
||
yargs
|
||
.getInternalMethods()
|
||
.getUsageInstance()
|
||
.fail(parsed.error.message, parsed.error);
|
||
}
|
||
else {
|
||
const positionalKeys = Object.keys(positionalMap);
|
||
Object.keys(positionalMap).forEach(key => {
|
||
positionalKeys.push(...parsed.aliases[key]);
|
||
});
|
||
Object.keys(parsed.argv).forEach(key => {
|
||
if (positionalKeys.includes(key)) {
|
||
if (!positionalMap[key])
|
||
positionalMap[key] = parsed.argv[key];
|
||
if (!this.isInConfigs(yargs, key) &&
|
||
!this.isDefaulted(yargs, key) &&
|
||
Object.prototype.hasOwnProperty.call(argv, key) &&
|
||
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
|
||
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
|
||
argv[key] = [].concat(argv[key], parsed.argv[key]);
|
||
}
|
||
else {
|
||
argv[key] = parsed.argv[key];
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
isDefaulted(yargs, key) {
|
||
const { default: defaults } = yargs.getOptions();
|
||
return (Object.prototype.hasOwnProperty.call(defaults, key) ||
|
||
Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key)));
|
||
}
|
||
isInConfigs(yargs, key) {
|
||
const { configObjects } = yargs.getOptions();
|
||
return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) ||
|
||
configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key))));
|
||
}
|
||
runDefaultBuilderOn(yargs) {
|
||
if (!this.defaultCommand)
|
||
return;
|
||
if (this.shouldUpdateUsage(yargs)) {
|
||
const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
|
||
? this.defaultCommand.original
|
||
: this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
|
||
yargs
|
||
.getInternalMethods()
|
||
.getUsageInstance()
|
||
.usage(commandString, this.defaultCommand.description);
|
||
}
|
||
const builder = this.defaultCommand.builder;
|
||
if (isCommandBuilderCallback(builder)) {
|
||
return builder(yargs, true);
|
||
}
|
||
else if (!isCommandBuilderDefinition(builder)) {
|
||
Object.keys(builder).forEach(key => {
|
||
yargs.option(key, builder[key]);
|
||
});
|
||
}
|
||
return undefined;
|
||
}
|
||
moduleName(obj) {
|
||
const mod = whichModule(obj);
|
||
if (!mod)
|
||
throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
|
||
return this.commandFromFilename(mod.filename);
|
||
}
|
||
commandFromFilename(filename) {
|
||
return this.shim.path.basename(filename, this.shim.path.extname(filename));
|
||
}
|
||
extractDesc({ describe, description, desc }) {
|
||
for (const test of [describe, description, desc]) {
|
||
if (typeof test === 'string' || test === false)
|
||
return test;
|
||
assertNotStrictEqual(test, true, this.shim);
|
||
}
|
||
return false;
|
||
}
|
||
freeze() {
|
||
this.frozens.push({
|
||
handlers: this.handlers,
|
||
aliasMap: this.aliasMap,
|
||
defaultCommand: this.defaultCommand,
|
||
});
|
||
}
|
||
unfreeze() {
|
||
const frozen = this.frozens.pop();
|
||
assertNotStrictEqual(frozen, undefined, this.shim);
|
||
({
|
||
handlers: this.handlers,
|
||
aliasMap: this.aliasMap,
|
||
defaultCommand: this.defaultCommand,
|
||
} = frozen);
|
||
}
|
||
reset() {
|
||
this.handlers = {};
|
||
this.aliasMap = {};
|
||
this.defaultCommand = undefined;
|
||
this.requireCache = new Set();
|
||
return this;
|
||
}
|
||
}
|
||
function command(usage, validation, globalMiddleware, shim) {
|
||
return new CommandInstance(usage, validation, globalMiddleware, shim);
|
||
}
|
||
function isCommandBuilderDefinition(builder) {
|
||
return (typeof builder === 'object' &&
|
||
!!builder.builder &&
|
||
typeof builder.handler === 'function');
|
||
}
|
||
function isCommandAndAliases(cmd) {
|
||
return cmd.every(c => typeof c === 'string');
|
||
}
|
||
function isCommandBuilderCallback(builder) {
|
||
return typeof builder === 'function';
|
||
}
|
||
function isCommandBuilderOptionDefinitions(builder) {
|
||
return typeof builder === 'object';
|
||
}
|
||
function isCommandHandlerDefinition(cmd) {
|
||
return typeof cmd === 'object' && !Array.isArray(cmd);
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/obj-filter.js
|
||
|
||
function objFilter(original = {}, filter = () => true) {
|
||
const obj = {};
|
||
objectKeys(original).forEach(key => {
|
||
if (filter(key, original[key])) {
|
||
obj[key] = original[key];
|
||
}
|
||
});
|
||
return obj;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/set-blocking.js
|
||
function setBlocking(blocking) {
|
||
if (typeof process === 'undefined')
|
||
return;
|
||
[process.stdout, process.stderr].forEach(_stream => {
|
||
const stream = _stream;
|
||
if (stream._handle &&
|
||
stream.isTTY &&
|
||
typeof stream._handle.setBlocking === 'function') {
|
||
stream._handle.setBlocking(blocking);
|
||
}
|
||
});
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/usage.js
|
||
|
||
|
||
|
||
function isBoolean(fail) {
|
||
return typeof fail === 'boolean';
|
||
}
|
||
function usage(yargs, shim) {
|
||
const __ = shim.y18n.__;
|
||
const self = {};
|
||
const fails = [];
|
||
self.failFn = function failFn(f) {
|
||
fails.push(f);
|
||
};
|
||
let failMessage = null;
|
||
let globalFailMessage = null;
|
||
let showHelpOnFail = true;
|
||
self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
|
||
const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
|
||
if (yargs.getInternalMethods().isGlobalContext()) {
|
||
globalFailMessage = message;
|
||
}
|
||
failMessage = message;
|
||
showHelpOnFail = enabled;
|
||
return self;
|
||
};
|
||
let failureOutput = false;
|
||
self.fail = function fail(msg, err) {
|
||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||
if (fails.length) {
|
||
for (let i = fails.length - 1; i >= 0; --i) {
|
||
const fail = fails[i];
|
||
if (isBoolean(fail)) {
|
||
if (err)
|
||
throw err;
|
||
else if (msg)
|
||
throw Error(msg);
|
||
}
|
||
else {
|
||
fail(msg, err, self);
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
if (yargs.getExitProcess())
|
||
setBlocking(true);
|
||
if (!failureOutput) {
|
||
failureOutput = true;
|
||
if (showHelpOnFail) {
|
||
yargs.showHelp('error');
|
||
logger.error();
|
||
}
|
||
if (msg || err)
|
||
logger.error(msg || err);
|
||
const globalOrCommandFailMessage = failMessage || globalFailMessage;
|
||
if (globalOrCommandFailMessage) {
|
||
if (msg || err)
|
||
logger.error('');
|
||
logger.error(globalOrCommandFailMessage);
|
||
}
|
||
}
|
||
err = err || new YError(msg);
|
||
if (yargs.getExitProcess()) {
|
||
return yargs.exit(1);
|
||
}
|
||
else if (yargs.getInternalMethods().hasParseCallback()) {
|
||
return yargs.exit(1, err);
|
||
}
|
||
else {
|
||
throw err;
|
||
}
|
||
}
|
||
};
|
||
let usages = [];
|
||
let usageDisabled = false;
|
||
self.usage = (msg, description) => {
|
||
if (msg === null) {
|
||
usageDisabled = true;
|
||
usages = [];
|
||
return self;
|
||
}
|
||
usageDisabled = false;
|
||
usages.push([msg, description || '']);
|
||
return self;
|
||
};
|
||
self.getUsage = () => {
|
||
return usages;
|
||
};
|
||
self.getUsageDisabled = () => {
|
||
return usageDisabled;
|
||
};
|
||
self.getPositionalGroupName = () => {
|
||
return __('Positionals:');
|
||
};
|
||
let examples = [];
|
||
self.example = (cmd, description) => {
|
||
examples.push([cmd, description || '']);
|
||
};
|
||
let commands = [];
|
||
self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
|
||
if (isDefault) {
|
||
commands = commands.map(cmdArray => {
|
||
cmdArray[2] = false;
|
||
return cmdArray;
|
||
});
|
||
}
|
||
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
|
||
};
|
||
self.getCommands = () => commands;
|
||
let descriptions = {};
|
||
self.describe = function describe(keyOrKeys, desc) {
|
||
if (Array.isArray(keyOrKeys)) {
|
||
keyOrKeys.forEach(k => {
|
||
self.describe(k, desc);
|
||
});
|
||
}
|
||
else if (typeof keyOrKeys === 'object') {
|
||
Object.keys(keyOrKeys).forEach(k => {
|
||
self.describe(k, keyOrKeys[k]);
|
||
});
|
||
}
|
||
else {
|
||
descriptions[keyOrKeys] = desc;
|
||
}
|
||
};
|
||
self.getDescriptions = () => descriptions;
|
||
let epilogs = [];
|
||
self.epilog = msg => {
|
||
epilogs.push(msg);
|
||
};
|
||
let wrapSet = false;
|
||
let wrap;
|
||
self.wrap = cols => {
|
||
wrapSet = true;
|
||
wrap = cols;
|
||
};
|
||
self.getWrap = () => {
|
||
if (shim.getEnv('YARGS_DISABLE_WRAP')) {
|
||
return null;
|
||
}
|
||
if (!wrapSet) {
|
||
wrap = windowWidth();
|
||
wrapSet = true;
|
||
}
|
||
return wrap;
|
||
};
|
||
const deferY18nLookupPrefix = '__yargsString__:';
|
||
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
|
||
self.help = function help() {
|
||
if (cachedHelpMessage)
|
||
return cachedHelpMessage;
|
||
normalizeAliases();
|
||
const base$0 = yargs.customScriptName
|
||
? yargs.$0
|
||
: shim.path.basename(yargs.$0);
|
||
const demandedOptions = yargs.getDemandedOptions();
|
||
const demandedCommands = yargs.getDemandedCommands();
|
||
const deprecatedOptions = yargs.getDeprecatedOptions();
|
||
const groups = yargs.getGroups();
|
||
const options = yargs.getOptions();
|
||
let keys = [];
|
||
keys = keys.concat(Object.keys(descriptions));
|
||
keys = keys.concat(Object.keys(demandedOptions));
|
||
keys = keys.concat(Object.keys(demandedCommands));
|
||
keys = keys.concat(Object.keys(options.default));
|
||
keys = keys.filter(filterHiddenOptions);
|
||
keys = Object.keys(keys.reduce((acc, key) => {
|
||
if (key !== '_')
|
||
acc[key] = true;
|
||
return acc;
|
||
}, {}));
|
||
const theWrap = self.getWrap();
|
||
const ui = shim.cliui({
|
||
width: theWrap,
|
||
wrap: !!theWrap,
|
||
});
|
||
if (!usageDisabled) {
|
||
if (usages.length) {
|
||
usages.forEach(usage => {
|
||
ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` });
|
||
if (usage[1]) {
|
||
ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
|
||
}
|
||
});
|
||
ui.div();
|
||
}
|
||
else if (commands.length) {
|
||
let u = null;
|
||
if (demandedCommands._) {
|
||
u = `${base$0} <${__('command')}>\n`;
|
||
}
|
||
else {
|
||
u = `${base$0} [${__('command')}]\n`;
|
||
}
|
||
ui.div(`${u}`);
|
||
}
|
||
}
|
||
if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
|
||
ui.div(__('Commands:'));
|
||
const context = yargs.getInternalMethods().getContext();
|
||
const parentCommands = context.commands.length
|
||
? `${context.commands.join(' ')} `
|
||
: '';
|
||
if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
|
||
true) {
|
||
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
|
||
}
|
||
const prefix = base$0 ? `${base$0} ` : '';
|
||
commands.forEach(command => {
|
||
const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
|
||
ui.span({
|
||
text: commandString,
|
||
padding: [0, 2, 0, 2],
|
||
width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
|
||
}, { text: command[1] });
|
||
const hints = [];
|
||
if (command[2])
|
||
hints.push(`[${__('default')}]`);
|
||
if (command[3] && command[3].length) {
|
||
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
|
||
}
|
||
if (command[4]) {
|
||
if (typeof command[4] === 'string') {
|
||
hints.push(`[${__('deprecated: %s', command[4])}]`);
|
||
}
|
||
else {
|
||
hints.push(`[${__('deprecated')}]`);
|
||
}
|
||
}
|
||
if (hints.length) {
|
||
ui.div({
|
||
text: hints.join(' '),
|
||
padding: [0, 0, 0, 2],
|
||
align: 'right',
|
||
});
|
||
}
|
||
else {
|
||
ui.div();
|
||
}
|
||
});
|
||
ui.div();
|
||
}
|
||
const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
|
||
keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
|
||
aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
|
||
const defaultGroup = __('Options:');
|
||
if (!groups[defaultGroup])
|
||
groups[defaultGroup] = [];
|
||
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
|
||
const isLongSwitch = (sw) => /^--/.test(getText(sw));
|
||
const displayedGroups = Object.keys(groups)
|
||
.filter(groupName => groups[groupName].length > 0)
|
||
.map(groupName => {
|
||
const normalizedKeys = groups[groupName]
|
||
.filter(filterHiddenOptions)
|
||
.map(key => {
|
||
if (aliasKeys.includes(key))
|
||
return key;
|
||
for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
|
||
if ((options.alias[aliasKey] || []).includes(key))
|
||
return aliasKey;
|
||
}
|
||
return key;
|
||
});
|
||
return { groupName, normalizedKeys };
|
||
})
|
||
.filter(({ normalizedKeys }) => normalizedKeys.length > 0)
|
||
.map(({ groupName, normalizedKeys }) => {
|
||
const switches = normalizedKeys.reduce((acc, key) => {
|
||
acc[key] = [key]
|
||
.concat(options.alias[key] || [])
|
||
.map(sw => {
|
||
if (groupName === self.getPositionalGroupName())
|
||
return sw;
|
||
else {
|
||
return ((/^[0-9]$/.test(sw)
|
||
? options.boolean.includes(key)
|
||
? '-'
|
||
: '--'
|
||
: sw.length > 1
|
||
? '--'
|
||
: '-') + sw);
|
||
}
|
||
})
|
||
.sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
|
||
? 0
|
||
: isLongSwitch(sw1)
|
||
? 1
|
||
: -1)
|
||
.join(', ');
|
||
return acc;
|
||
}, {});
|
||
return { groupName, normalizedKeys, switches };
|
||
});
|
||
const shortSwitchesUsed = displayedGroups
|
||
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
|
||
.some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
|
||
if (shortSwitchesUsed) {
|
||
displayedGroups
|
||
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
|
||
.forEach(({ normalizedKeys, switches }) => {
|
||
normalizedKeys.forEach(key => {
|
||
if (isLongSwitch(switches[key])) {
|
||
switches[key] = addIndentation(switches[key], '-x, '.length);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
|
||
ui.div(groupName);
|
||
normalizedKeys.forEach(key => {
|
||
const kswitch = switches[key];
|
||
let desc = descriptions[key] || '';
|
||
let type = null;
|
||
if (desc.includes(deferY18nLookupPrefix))
|
||
desc = __(desc.substring(deferY18nLookupPrefix.length));
|
||
if (options.boolean.includes(key))
|
||
type = `[${__('boolean')}]`;
|
||
if (options.count.includes(key))
|
||
type = `[${__('count')}]`;
|
||
if (options.string.includes(key))
|
||
type = `[${__('string')}]`;
|
||
if (options.normalize.includes(key))
|
||
type = `[${__('string')}]`;
|
||
if (options.array.includes(key))
|
||
type = `[${__('array')}]`;
|
||
if (options.number.includes(key))
|
||
type = `[${__('number')}]`;
|
||
const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
|
||
? `[${__('deprecated: %s', deprecated)}]`
|
||
: `[${__('deprecated')}]`;
|
||
const extra = [
|
||
key in deprecatedOptions
|
||
? deprecatedExtra(deprecatedOptions[key])
|
||
: null,
|
||
type,
|
||
key in demandedOptions ? `[${__('required')}]` : null,
|
||
options.choices && options.choices[key]
|
||
? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
|
||
: null,
|
||
defaultString(options.default[key], options.defaultDescription[key]),
|
||
]
|
||
.filter(Boolean)
|
||
.join(' ');
|
||
ui.span({
|
||
text: getText(kswitch),
|
||
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
|
||
width: maxWidth(switches, theWrap) + 4,
|
||
}, desc);
|
||
const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
|
||
true;
|
||
if (extra && !shouldHideOptionExtras)
|
||
ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
|
||
else
|
||
ui.div();
|
||
});
|
||
ui.div();
|
||
});
|
||
if (examples.length) {
|
||
ui.div(__('Examples:'));
|
||
examples.forEach(example => {
|
||
example[0] = example[0].replace(/\$0/g, base$0);
|
||
});
|
||
examples.forEach(example => {
|
||
if (example[1] === '') {
|
||
ui.div({
|
||
text: example[0],
|
||
padding: [0, 2, 0, 2],
|
||
});
|
||
}
|
||
else {
|
||
ui.div({
|
||
text: example[0],
|
||
padding: [0, 2, 0, 2],
|
||
width: maxWidth(examples, theWrap) + 4,
|
||
}, {
|
||
text: example[1],
|
||
});
|
||
}
|
||
});
|
||
ui.div();
|
||
}
|
||
if (epilogs.length > 0) {
|
||
const e = epilogs
|
||
.map(epilog => epilog.replace(/\$0/g, base$0))
|
||
.join('\n');
|
||
ui.div(`${e}\n`);
|
||
}
|
||
return ui.toString().replace(/\s*$/, '');
|
||
};
|
||
function maxWidth(table, theWrap, modifier) {
|
||
let width = 0;
|
||
if (!Array.isArray(table)) {
|
||
table = Object.values(table).map(v => [v]);
|
||
}
|
||
table.forEach(v => {
|
||
width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
|
||
});
|
||
if (theWrap)
|
||
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
|
||
return width;
|
||
}
|
||
function normalizeAliases() {
|
||
const demandedOptions = yargs.getDemandedOptions();
|
||
const options = yargs.getOptions();
|
||
(Object.keys(options.alias) || []).forEach(key => {
|
||
options.alias[key].forEach(alias => {
|
||
if (descriptions[alias])
|
||
self.describe(key, descriptions[alias]);
|
||
if (alias in demandedOptions)
|
||
yargs.demandOption(key, demandedOptions[alias]);
|
||
if (options.boolean.includes(alias))
|
||
yargs.boolean(key);
|
||
if (options.count.includes(alias))
|
||
yargs.count(key);
|
||
if (options.string.includes(alias))
|
||
yargs.string(key);
|
||
if (options.normalize.includes(alias))
|
||
yargs.normalize(key);
|
||
if (options.array.includes(alias))
|
||
yargs.array(key);
|
||
if (options.number.includes(alias))
|
||
yargs.number(key);
|
||
});
|
||
});
|
||
}
|
||
let cachedHelpMessage;
|
||
self.cacheHelpMessage = function () {
|
||
cachedHelpMessage = this.help();
|
||
};
|
||
self.clearCachedHelpMessage = function () {
|
||
cachedHelpMessage = undefined;
|
||
};
|
||
self.hasCachedHelpMessage = function () {
|
||
return !!cachedHelpMessage;
|
||
};
|
||
function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
|
||
let groupedKeys = [];
|
||
let toCheck = null;
|
||
Object.keys(groups).forEach(group => {
|
||
groupedKeys = groupedKeys.concat(groups[group]);
|
||
});
|
||
keys.forEach(key => {
|
||
toCheck = [key].concat(aliases[key]);
|
||
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
|
||
groups[defaultGroup].push(key);
|
||
}
|
||
});
|
||
return groupedKeys;
|
||
}
|
||
function filterHiddenOptions(key) {
|
||
return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
|
||
yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
|
||
}
|
||
self.showHelp = (level) => {
|
||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||
if (!level)
|
||
level = 'error';
|
||
const emit = typeof level === 'function' ? level : logger[level];
|
||
emit(self.help());
|
||
};
|
||
self.functionDescription = fn => {
|
||
const description = fn.name
|
||
? shim.Parser.decamelize(fn.name, '-')
|
||
: __('generated-value');
|
||
return ['(', description, ')'].join('');
|
||
};
|
||
self.stringifiedValues = function stringifiedValues(values, separator) {
|
||
let string = '';
|
||
const sep = separator || ', ';
|
||
const array = [].concat(values);
|
||
if (!values || !array.length)
|
||
return string;
|
||
array.forEach(value => {
|
||
if (string.length)
|
||
string += sep;
|
||
string += JSON.stringify(value);
|
||
});
|
||
return string;
|
||
};
|
||
function defaultString(value, defaultDescription) {
|
||
let string = `[${__('default:')} `;
|
||
if (value === undefined && !defaultDescription)
|
||
return null;
|
||
if (defaultDescription) {
|
||
string += defaultDescription;
|
||
}
|
||
else {
|
||
switch (typeof value) {
|
||
case 'string':
|
||
string += `"${value}"`;
|
||
break;
|
||
case 'object':
|
||
string += JSON.stringify(value);
|
||
break;
|
||
default:
|
||
string += value;
|
||
}
|
||
}
|
||
return `${string}]`;
|
||
}
|
||
function windowWidth() {
|
||
const maxWidth = 80;
|
||
if (shim.process.stdColumns) {
|
||
return Math.min(maxWidth, shim.process.stdColumns);
|
||
}
|
||
else {
|
||
return maxWidth;
|
||
}
|
||
}
|
||
let version = null;
|
||
self.version = ver => {
|
||
version = ver;
|
||
};
|
||
self.showVersion = level => {
|
||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||
if (!level)
|
||
level = 'error';
|
||
const emit = typeof level === 'function' ? level : logger[level];
|
||
emit(version);
|
||
};
|
||
self.reset = function reset(localLookup) {
|
||
failMessage = null;
|
||
failureOutput = false;
|
||
usages = [];
|
||
usageDisabled = false;
|
||
epilogs = [];
|
||
examples = [];
|
||
commands = [];
|
||
descriptions = objFilter(descriptions, k => !localLookup[k]);
|
||
return self;
|
||
};
|
||
const frozens = [];
|
||
self.freeze = function freeze() {
|
||
frozens.push({
|
||
failMessage,
|
||
failureOutput,
|
||
usages,
|
||
usageDisabled,
|
||
epilogs,
|
||
examples,
|
||
commands,
|
||
descriptions,
|
||
});
|
||
};
|
||
self.unfreeze = function unfreeze(defaultCommand = false) {
|
||
const frozen = frozens.pop();
|
||
if (!frozen)
|
||
return;
|
||
if (defaultCommand) {
|
||
descriptions = { ...frozen.descriptions, ...descriptions };
|
||
commands = [...frozen.commands, ...commands];
|
||
usages = [...frozen.usages, ...usages];
|
||
examples = [...frozen.examples, ...examples];
|
||
epilogs = [...frozen.epilogs, ...epilogs];
|
||
}
|
||
else {
|
||
({
|
||
failMessage,
|
||
failureOutput,
|
||
usages,
|
||
usageDisabled,
|
||
epilogs,
|
||
examples,
|
||
commands,
|
||
descriptions,
|
||
} = frozen);
|
||
}
|
||
};
|
||
return self;
|
||
}
|
||
function isIndentedText(text) {
|
||
return typeof text === 'object';
|
||
}
|
||
function addIndentation(text, indent) {
|
||
return isIndentedText(text)
|
||
? { text: text.text, indentation: text.indentation + indent }
|
||
: { text, indentation: indent };
|
||
}
|
||
function getIndentation(text) {
|
||
return isIndentedText(text) ? text.indentation : 0;
|
||
}
|
||
function getText(text) {
|
||
return isIndentedText(text) ? text.text : text;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/completion-templates.js
|
||
const completionShTemplate = `###-begin-{{app_name}}-completions-###
|
||
#
|
||
# yargs command completion script
|
||
#
|
||
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
|
||
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
|
||
#
|
||
_{{app_name}}_yargs_completions()
|
||
{
|
||
local cur_word args type_list
|
||
|
||
cur_word="\${COMP_WORDS[COMP_CWORD]}"
|
||
args=("\${COMP_WORDS[@]}")
|
||
|
||
# ask yargs to generate completions.
|
||
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
|
||
|
||
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
|
||
|
||
# if no match was found, fall back to filename completion
|
||
if [ \${#COMPREPLY[@]} -eq 0 ]; then
|
||
COMPREPLY=()
|
||
fi
|
||
|
||
return 0
|
||
}
|
||
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
|
||
###-end-{{app_name}}-completions-###
|
||
`;
|
||
const completionZshTemplate = `#compdef {{app_name}}
|
||
###-begin-{{app_name}}-completions-###
|
||
#
|
||
# yargs command completion script
|
||
#
|
||
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
|
||
# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
|
||
#
|
||
_{{app_name}}_yargs_completions()
|
||
{
|
||
local reply
|
||
local si=$IFS
|
||
IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
|
||
IFS=$si
|
||
_describe 'values' reply
|
||
}
|
||
compdef _{{app_name}}_yargs_completions {{app_name}}
|
||
###-end-{{app_name}}-completions-###
|
||
`;
|
||
|
||
;// ./node_modules/yargs/build/lib/completion.js
|
||
|
||
|
||
|
||
|
||
|
||
class Completion {
|
||
constructor(yargs, usage, command, shim) {
|
||
var _a, _b, _c;
|
||
this.yargs = yargs;
|
||
this.usage = usage;
|
||
this.command = command;
|
||
this.shim = shim;
|
||
this.completionKey = 'get-yargs-completions';
|
||
this.aliases = null;
|
||
this.customCompletionFunction = null;
|
||
this.indexAfterLastReset = 0;
|
||
this.zshShell =
|
||
(_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) ||
|
||
((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false;
|
||
}
|
||
defaultCompletion(args, argv, current, done) {
|
||
const handlers = this.command.getCommandHandlers();
|
||
for (let i = 0, ii = args.length; i < ii; ++i) {
|
||
if (handlers[args[i]] && handlers[args[i]].builder) {
|
||
const builder = handlers[args[i]].builder;
|
||
if (isCommandBuilderCallback(builder)) {
|
||
this.indexAfterLastReset = i + 1;
|
||
const y = this.yargs.getInternalMethods().reset();
|
||
builder(y, true);
|
||
return y.argv;
|
||
}
|
||
}
|
||
}
|
||
const completions = [];
|
||
this.commandCompletions(completions, args, current);
|
||
this.optionCompletions(completions, args, argv, current);
|
||
this.choicesFromOptionsCompletions(completions, args, argv, current);
|
||
this.choicesFromPositionalsCompletions(completions, args, argv, current);
|
||
done(null, completions);
|
||
}
|
||
commandCompletions(completions, args, current) {
|
||
const parentCommands = this.yargs
|
||
.getInternalMethods()
|
||
.getContext().commands;
|
||
if (!current.match(/^-/) &&
|
||
parentCommands[parentCommands.length - 1] !== current &&
|
||
!this.previousArgHasChoices(args)) {
|
||
this.usage.getCommands().forEach(usageCommand => {
|
||
const commandName = parseCommand(usageCommand[0]).cmd;
|
||
if (args.indexOf(commandName) === -1) {
|
||
if (!this.zshShell) {
|
||
completions.push(commandName);
|
||
}
|
||
else {
|
||
const desc = usageCommand[1] || '';
|
||
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
optionCompletions(completions, args, argv, current) {
|
||
if ((current.match(/^-/) || (current === '' && completions.length === 0)) &&
|
||
!this.previousArgHasChoices(args)) {
|
||
const options = this.yargs.getOptions();
|
||
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
|
||
Object.keys(options.key).forEach(key => {
|
||
const negable = !!options.configuration['boolean-negation'] &&
|
||
options.boolean.includes(key);
|
||
const isPositionalKey = positionalKeys.includes(key);
|
||
if (!isPositionalKey &&
|
||
!options.hiddenOptions.includes(key) &&
|
||
!this.argsContainKey(args, key, negable)) {
|
||
this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
choicesFromOptionsCompletions(completions, args, argv, current) {
|
||
if (this.previousArgHasChoices(args)) {
|
||
const choices = this.getPreviousArgChoices(args);
|
||
if (choices && choices.length > 0) {
|
||
completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
|
||
}
|
||
}
|
||
}
|
||
choicesFromPositionalsCompletions(completions, args, argv, current) {
|
||
if (current === '' &&
|
||
completions.length > 0 &&
|
||
this.previousArgHasChoices(args)) {
|
||
return;
|
||
}
|
||
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
|
||
const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length +
|
||
1);
|
||
const positionalKey = positionalKeys[argv._.length - offset - 1];
|
||
if (!positionalKey) {
|
||
return;
|
||
}
|
||
const choices = this.yargs.getOptions().choices[positionalKey] || [];
|
||
for (const choice of choices) {
|
||
if (choice.startsWith(current)) {
|
||
completions.push(choice.replace(/:/g, '\\:'));
|
||
}
|
||
}
|
||
}
|
||
getPreviousArgChoices(args) {
|
||
if (args.length < 1)
|
||
return;
|
||
let previousArg = args[args.length - 1];
|
||
let filter = '';
|
||
if (!previousArg.startsWith('-') && args.length > 1) {
|
||
filter = previousArg;
|
||
previousArg = args[args.length - 2];
|
||
}
|
||
if (!previousArg.startsWith('-'))
|
||
return;
|
||
const previousArgKey = previousArg.replace(/^-+/, '');
|
||
const options = this.yargs.getOptions();
|
||
const possibleAliases = [
|
||
previousArgKey,
|
||
...(this.yargs.getAliases()[previousArgKey] || []),
|
||
];
|
||
let choices;
|
||
for (const possibleAlias of possibleAliases) {
|
||
if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
|
||
Array.isArray(options.choices[possibleAlias])) {
|
||
choices = options.choices[possibleAlias];
|
||
break;
|
||
}
|
||
}
|
||
if (choices) {
|
||
return choices.filter(choice => !filter || choice.startsWith(filter));
|
||
}
|
||
}
|
||
previousArgHasChoices(args) {
|
||
const choices = this.getPreviousArgChoices(args);
|
||
return choices !== undefined && choices.length > 0;
|
||
}
|
||
argsContainKey(args, key, negable) {
|
||
const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
|
||
if (argsContains(key))
|
||
return true;
|
||
if (negable && argsContains(`no-${key}`))
|
||
return true;
|
||
if (this.aliases) {
|
||
for (const alias of this.aliases[key]) {
|
||
if (argsContains(alias))
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
completeOptionKey(key, completions, current, negable) {
|
||
var _a, _b, _c, _d;
|
||
let keyWithDesc = key;
|
||
if (this.zshShell) {
|
||
const descs = this.usage.getDescriptions();
|
||
const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => {
|
||
const desc = descs[alias];
|
||
return typeof desc === 'string' && desc.length > 0;
|
||
});
|
||
const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
|
||
const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : '';
|
||
keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc
|
||
.replace('__yargsString__:', '')
|
||
.replace(/(\r\n|\n|\r)/gm, ' ')}`;
|
||
}
|
||
const startsByTwoDashes = (s) => /^--/.test(s);
|
||
const isShortOption = (s) => /^[^0-9]$/.test(s);
|
||
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
|
||
completions.push(dashes + keyWithDesc);
|
||
if (negable) {
|
||
completions.push(dashes + 'no-' + keyWithDesc);
|
||
}
|
||
}
|
||
customCompletion(args, argv, current, done) {
|
||
assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
|
||
if (isSyncCompletionFunction(this.customCompletionFunction)) {
|
||
const result = this.customCompletionFunction(current, argv);
|
||
if (isPromise(result)) {
|
||
return result
|
||
.then(list => {
|
||
this.shim.process.nextTick(() => {
|
||
done(null, list);
|
||
});
|
||
})
|
||
.catch(err => {
|
||
this.shim.process.nextTick(() => {
|
||
done(err, undefined);
|
||
});
|
||
});
|
||
}
|
||
return done(null, result);
|
||
}
|
||
else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
|
||
return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
|
||
done(null, completions);
|
||
});
|
||
}
|
||
else {
|
||
return this.customCompletionFunction(current, argv, completions => {
|
||
done(null, completions);
|
||
});
|
||
}
|
||
}
|
||
getCompletion(args, done) {
|
||
const current = args.length ? args[args.length - 1] : '';
|
||
const argv = this.yargs.parse(args, true);
|
||
const completionFunction = this.customCompletionFunction
|
||
? (argv) => this.customCompletion(args, argv, current, done)
|
||
: (argv) => this.defaultCompletion(args, argv, current, done);
|
||
return isPromise(argv)
|
||
? argv.then(completionFunction)
|
||
: completionFunction(argv);
|
||
}
|
||
generateCompletionScript($0, cmd) {
|
||
let script = this.zshShell
|
||
? completionZshTemplate
|
||
: completionShTemplate;
|
||
const name = this.shim.path.basename($0);
|
||
if ($0.match(/\.js$/))
|
||
$0 = `./${$0}`;
|
||
script = script.replace(/{{app_name}}/g, name);
|
||
script = script.replace(/{{completion_command}}/g, cmd);
|
||
return script.replace(/{{app_path}}/g, $0);
|
||
}
|
||
registerFunction(fn) {
|
||
this.customCompletionFunction = fn;
|
||
}
|
||
setParsed(parsed) {
|
||
this.aliases = parsed.aliases;
|
||
}
|
||
}
|
||
function completion(yargs, usage, command, shim) {
|
||
return new Completion(yargs, usage, command, shim);
|
||
}
|
||
function isSyncCompletionFunction(completionFunction) {
|
||
return completionFunction.length < 3;
|
||
}
|
||
function isFallbackCompletionFunction(completionFunction) {
|
||
return completionFunction.length > 3;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/levenshtein.js
|
||
function levenshtein(a, b) {
|
||
if (a.length === 0)
|
||
return b.length;
|
||
if (b.length === 0)
|
||
return a.length;
|
||
const matrix = [];
|
||
let i;
|
||
for (i = 0; i <= b.length; i++) {
|
||
matrix[i] = [i];
|
||
}
|
||
let j;
|
||
for (j = 0; j <= a.length; j++) {
|
||
matrix[0][j] = j;
|
||
}
|
||
for (i = 1; i <= b.length; i++) {
|
||
for (j = 1; j <= a.length; j++) {
|
||
if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
||
matrix[i][j] = matrix[i - 1][j - 1];
|
||
}
|
||
else {
|
||
if (i > 1 &&
|
||
j > 1 &&
|
||
b.charAt(i - 2) === a.charAt(j - 1) &&
|
||
b.charAt(i - 1) === a.charAt(j - 2)) {
|
||
matrix[i][j] = matrix[i - 2][j - 2] + 1;
|
||
}
|
||
else {
|
||
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return matrix[b.length][a.length];
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/validation.js
|
||
|
||
|
||
|
||
|
||
const specialKeys = ['$0', '--', '_'];
|
||
function validation(yargs, usage, shim) {
|
||
const __ = shim.y18n.__;
|
||
const __n = shim.y18n.__n;
|
||
const self = {};
|
||
self.nonOptionCount = function nonOptionCount(argv) {
|
||
const demandedCommands = yargs.getDemandedCommands();
|
||
const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
|
||
const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
|
||
if (demandedCommands._ &&
|
||
(_s < demandedCommands._.min || _s > demandedCommands._.max)) {
|
||
if (_s < demandedCommands._.min) {
|
||
if (demandedCommands._.minMsg !== undefined) {
|
||
usage.fail(demandedCommands._.minMsg
|
||
? demandedCommands._.minMsg
|
||
.replace(/\$0/g, _s.toString())
|
||
.replace(/\$1/, demandedCommands._.min.toString())
|
||
: null);
|
||
}
|
||
else {
|
||
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
|
||
}
|
||
}
|
||
else if (_s > demandedCommands._.max) {
|
||
if (demandedCommands._.maxMsg !== undefined) {
|
||
usage.fail(demandedCommands._.maxMsg
|
||
? demandedCommands._.maxMsg
|
||
.replace(/\$0/g, _s.toString())
|
||
.replace(/\$1/, demandedCommands._.max.toString())
|
||
: null);
|
||
}
|
||
else {
|
||
usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
|
||
}
|
||
}
|
||
}
|
||
};
|
||
self.positionalCount = function positionalCount(required, observed) {
|
||
if (observed < required) {
|
||
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
|
||
}
|
||
};
|
||
self.requiredArguments = function requiredArguments(argv, demandedOptions) {
|
||
let missing = null;
|
||
for (const key of Object.keys(demandedOptions)) {
|
||
if (!Object.prototype.hasOwnProperty.call(argv, key) ||
|
||
typeof argv[key] === 'undefined') {
|
||
missing = missing || {};
|
||
missing[key] = demandedOptions[key];
|
||
}
|
||
}
|
||
if (missing) {
|
||
const customMsgs = [];
|
||
for (const key of Object.keys(missing)) {
|
||
const msg = missing[key];
|
||
if (msg && customMsgs.indexOf(msg) < 0) {
|
||
customMsgs.push(msg);
|
||
}
|
||
}
|
||
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
|
||
usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
|
||
}
|
||
};
|
||
self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
|
||
var _a;
|
||
const commandKeys = yargs
|
||
.getInternalMethods()
|
||
.getCommandInstance()
|
||
.getCommands();
|
||
const unknown = [];
|
||
const currentContext = yargs.getInternalMethods().getContext();
|
||
Object.keys(argv).forEach(key => {
|
||
if (!specialKeys.includes(key) &&
|
||
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
|
||
!Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) &&
|
||
!self.isValidAndSomeAliasIsNotNew(key, aliases)) {
|
||
unknown.push(key);
|
||
}
|
||
});
|
||
if (checkPositionals &&
|
||
(currentContext.commands.length > 0 ||
|
||
commandKeys.length > 0 ||
|
||
isDefaultCommand)) {
|
||
argv._.slice(currentContext.commands.length).forEach(key => {
|
||
if (!commandKeys.includes('' + key)) {
|
||
unknown.push('' + key);
|
||
}
|
||
});
|
||
}
|
||
if (checkPositionals) {
|
||
const demandedCommands = yargs.getDemandedCommands();
|
||
const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0;
|
||
const expected = currentContext.commands.length + maxNonOptDemanded;
|
||
if (expected < argv._.length) {
|
||
argv._.slice(expected).forEach(key => {
|
||
key = String(key);
|
||
if (!currentContext.commands.includes(key) &&
|
||
!unknown.includes(key)) {
|
||
unknown.push(key);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
if (unknown.length) {
|
||
usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')));
|
||
}
|
||
};
|
||
self.unknownCommands = function unknownCommands(argv) {
|
||
const commandKeys = yargs
|
||
.getInternalMethods()
|
||
.getCommandInstance()
|
||
.getCommands();
|
||
const unknown = [];
|
||
const currentContext = yargs.getInternalMethods().getContext();
|
||
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
|
||
argv._.slice(currentContext.commands.length).forEach(key => {
|
||
if (!commandKeys.includes('' + key)) {
|
||
unknown.push('' + key);
|
||
}
|
||
});
|
||
}
|
||
if (unknown.length > 0) {
|
||
usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
|
||
return true;
|
||
}
|
||
else {
|
||
return false;
|
||
}
|
||
};
|
||
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
|
||
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
|
||
return false;
|
||
}
|
||
const newAliases = yargs.parsed.newAliases;
|
||
return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
|
||
};
|
||
self.limitedChoices = function limitedChoices(argv) {
|
||
const options = yargs.getOptions();
|
||
const invalid = {};
|
||
if (!Object.keys(options.choices).length)
|
||
return;
|
||
Object.keys(argv).forEach(key => {
|
||
if (specialKeys.indexOf(key) === -1 &&
|
||
Object.prototype.hasOwnProperty.call(options.choices, key)) {
|
||
[].concat(argv[key]).forEach(value => {
|
||
if (options.choices[key].indexOf(value) === -1 &&
|
||
value !== undefined) {
|
||
invalid[key] = (invalid[key] || []).concat(value);
|
||
}
|
||
});
|
||
}
|
||
});
|
||
const invalidKeys = Object.keys(invalid);
|
||
if (!invalidKeys.length)
|
||
return;
|
||
let msg = __('Invalid values:');
|
||
invalidKeys.forEach(key => {
|
||
msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
|
||
});
|
||
usage.fail(msg);
|
||
};
|
||
let implied = {};
|
||
self.implies = function implies(key, value) {
|
||
argsert('<string|object> [array|number|string]', [key, value], arguments.length);
|
||
if (typeof key === 'object') {
|
||
Object.keys(key).forEach(k => {
|
||
self.implies(k, key[k]);
|
||
});
|
||
}
|
||
else {
|
||
yargs.global(key);
|
||
if (!implied[key]) {
|
||
implied[key] = [];
|
||
}
|
||
if (Array.isArray(value)) {
|
||
value.forEach(i => self.implies(key, i));
|
||
}
|
||
else {
|
||
assertNotStrictEqual(value, undefined, shim);
|
||
implied[key].push(value);
|
||
}
|
||
}
|
||
};
|
||
self.getImplied = function getImplied() {
|
||
return implied;
|
||
};
|
||
function keyExists(argv, val) {
|
||
const num = Number(val);
|
||
val = isNaN(num) ? val : num;
|
||
if (typeof val === 'number') {
|
||
val = argv._.length >= val;
|
||
}
|
||
else if (val.match(/^--no-.+/)) {
|
||
val = val.match(/^--no-(.+)/)[1];
|
||
val = !Object.prototype.hasOwnProperty.call(argv, val);
|
||
}
|
||
else {
|
||
val = Object.prototype.hasOwnProperty.call(argv, val);
|
||
}
|
||
return val;
|
||
}
|
||
self.implications = function implications(argv) {
|
||
const implyFail = [];
|
||
Object.keys(implied).forEach(key => {
|
||
const origKey = key;
|
||
(implied[key] || []).forEach(value => {
|
||
let key = origKey;
|
||
const origValue = value;
|
||
key = keyExists(argv, key);
|
||
value = keyExists(argv, value);
|
||
if (key && !value) {
|
||
implyFail.push(` ${origKey} -> ${origValue}`);
|
||
}
|
||
});
|
||
});
|
||
if (implyFail.length) {
|
||
let msg = `${__('Implications failed:')}\n`;
|
||
implyFail.forEach(value => {
|
||
msg += value;
|
||
});
|
||
usage.fail(msg);
|
||
}
|
||
};
|
||
let conflicting = {};
|
||
self.conflicts = function conflicts(key, value) {
|
||
argsert('<string|object> [array|string]', [key, value], arguments.length);
|
||
if (typeof key === 'object') {
|
||
Object.keys(key).forEach(k => {
|
||
self.conflicts(k, key[k]);
|
||
});
|
||
}
|
||
else {
|
||
yargs.global(key);
|
||
if (!conflicting[key]) {
|
||
conflicting[key] = [];
|
||
}
|
||
if (Array.isArray(value)) {
|
||
value.forEach(i => self.conflicts(key, i));
|
||
}
|
||
else {
|
||
conflicting[key].push(value);
|
||
}
|
||
}
|
||
};
|
||
self.getConflicting = () => conflicting;
|
||
self.conflicting = function conflictingFn(argv) {
|
||
Object.keys(argv).forEach(key => {
|
||
if (conflicting[key]) {
|
||
conflicting[key].forEach(value => {
|
||
if (value && argv[key] !== undefined && argv[value] !== undefined) {
|
||
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
|
||
}
|
||
});
|
||
}
|
||
});
|
||
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
|
||
Object.keys(conflicting).forEach(key => {
|
||
conflicting[key].forEach(value => {
|
||
if (value &&
|
||
argv[shim.Parser.camelCase(key)] !== undefined &&
|
||
argv[shim.Parser.camelCase(value)] !== undefined) {
|
||
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
|
||
}
|
||
});
|
||
});
|
||
}
|
||
};
|
||
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
|
||
const threshold = 3;
|
||
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
|
||
let recommended = null;
|
||
let bestDistance = Infinity;
|
||
for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
|
||
const d = levenshtein(cmd, candidate);
|
||
if (d <= threshold && d < bestDistance) {
|
||
bestDistance = d;
|
||
recommended = candidate;
|
||
}
|
||
}
|
||
if (recommended)
|
||
usage.fail(__('Did you mean %s?', recommended));
|
||
};
|
||
self.reset = function reset(localLookup) {
|
||
implied = objFilter(implied, k => !localLookup[k]);
|
||
conflicting = objFilter(conflicting, k => !localLookup[k]);
|
||
return self;
|
||
};
|
||
const frozens = [];
|
||
self.freeze = function freeze() {
|
||
frozens.push({
|
||
implied,
|
||
conflicting,
|
||
});
|
||
};
|
||
self.unfreeze = function unfreeze() {
|
||
const frozen = frozens.pop();
|
||
assertNotStrictEqual(frozen, undefined, shim);
|
||
({ implied, conflicting } = frozen);
|
||
};
|
||
return self;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/utils/apply-extends.js
|
||
|
||
let previouslyVisitedConfigs = [];
|
||
let apply_extends_shim;
|
||
function applyExtends(config, cwd, mergeExtends, _shim) {
|
||
apply_extends_shim = _shim;
|
||
let defaultConfig = {};
|
||
if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
|
||
if (typeof config.extends !== 'string')
|
||
return defaultConfig;
|
||
const isPath = /\.json|\..*rc$/.test(config.extends);
|
||
let pathToDefault = null;
|
||
if (!isPath) {
|
||
try {
|
||
pathToDefault = require.resolve(config.extends);
|
||
}
|
||
catch (_err) {
|
||
return config;
|
||
}
|
||
}
|
||
else {
|
||
pathToDefault = getPathToDefaultConfig(cwd, config.extends);
|
||
}
|
||
checkForCircularExtends(pathToDefault);
|
||
previouslyVisitedConfigs.push(pathToDefault);
|
||
defaultConfig = isPath
|
||
? JSON.parse(apply_extends_shim.readFileSync(pathToDefault, 'utf8'))
|
||
: require(config.extends);
|
||
delete config.extends;
|
||
defaultConfig = applyExtends(defaultConfig, apply_extends_shim.path.dirname(pathToDefault), mergeExtends, apply_extends_shim);
|
||
}
|
||
previouslyVisitedConfigs = [];
|
||
return mergeExtends
|
||
? mergeDeep(defaultConfig, config)
|
||
: Object.assign({}, defaultConfig, config);
|
||
}
|
||
function checkForCircularExtends(cfgPath) {
|
||
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
|
||
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
|
||
}
|
||
}
|
||
function getPathToDefaultConfig(cwd, pathToExtend) {
|
||
return apply_extends_shim.path.resolve(cwd, pathToExtend);
|
||
}
|
||
function mergeDeep(config1, config2) {
|
||
const target = {};
|
||
function isObject(obj) {
|
||
return obj && typeof obj === 'object' && !Array.isArray(obj);
|
||
}
|
||
Object.assign(target, config1);
|
||
for (const key of Object.keys(config2)) {
|
||
if (isObject(config2[key]) && isObject(target[key])) {
|
||
target[key] = mergeDeep(config1[key], config2[key]);
|
||
}
|
||
else {
|
||
target[key] = config2[key];
|
||
}
|
||
}
|
||
return target;
|
||
}
|
||
|
||
;// ./node_modules/yargs/build/lib/yargs-factory.js
|
||
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
||
if (kind === "m") throw new TypeError("Private method is not writable");
|
||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
||
};
|
||
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
||
};
|
||
var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation;
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
function YargsFactory(_shim) {
|
||
return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => {
|
||
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
|
||
Object.defineProperty(yargs, 'argv', {
|
||
get: () => {
|
||
return yargs.parse();
|
||
},
|
||
enumerable: true,
|
||
});
|
||
yargs.help();
|
||
yargs.version();
|
||
return yargs;
|
||
};
|
||
}
|
||
const kCopyDoubleDash = Symbol('copyDoubleDash');
|
||
const kCreateLogger = Symbol('copyDoubleDash');
|
||
const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject');
|
||
const kEmitWarning = Symbol('emitWarning');
|
||
const kFreeze = Symbol('freeze');
|
||
const kGetDollarZero = Symbol('getDollarZero');
|
||
const kGetParserConfiguration = Symbol('getParserConfiguration');
|
||
const kGetUsageConfiguration = Symbol('getUsageConfiguration');
|
||
const kGuessLocale = Symbol('guessLocale');
|
||
const kGuessVersion = Symbol('guessVersion');
|
||
const kParsePositionalNumbers = Symbol('parsePositionalNumbers');
|
||
const kPkgUp = Symbol('pkgUp');
|
||
const kPopulateParserHintArray = Symbol('populateParserHintArray');
|
||
const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary');
|
||
const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary');
|
||
const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary');
|
||
const kSanitizeKey = Symbol('sanitizeKey');
|
||
const kSetKey = Symbol('setKey');
|
||
const kUnfreeze = Symbol('unfreeze');
|
||
const kValidateAsync = Symbol('validateAsync');
|
||
const kGetCommandInstance = Symbol('getCommandInstance');
|
||
const kGetContext = Symbol('getContext');
|
||
const kGetHasOutput = Symbol('getHasOutput');
|
||
const kGetLoggerInstance = Symbol('getLoggerInstance');
|
||
const kGetParseContext = Symbol('getParseContext');
|
||
const kGetUsageInstance = Symbol('getUsageInstance');
|
||
const kGetValidationInstance = Symbol('getValidationInstance');
|
||
const kHasParseCallback = Symbol('hasParseCallback');
|
||
const kIsGlobalContext = Symbol('isGlobalContext');
|
||
const kPostProcess = Symbol('postProcess');
|
||
const kRebase = Symbol('rebase');
|
||
const kReset = Symbol('reset');
|
||
const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands');
|
||
const kRunValidation = Symbol('runValidation');
|
||
const kSetHasOutput = Symbol('setHasOutput');
|
||
const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys');
|
||
class YargsInstance {
|
||
constructor(processArgs = [], cwd, parentRequire, shim) {
|
||
this.customScriptName = false;
|
||
this.parsed = false;
|
||
_YargsInstance_command.set(this, void 0);
|
||
_YargsInstance_cwd.set(this, void 0);
|
||
_YargsInstance_context.set(this, { commands: [], fullCommands: [] });
|
||
_YargsInstance_completion.set(this, null);
|
||
_YargsInstance_completionCommand.set(this, null);
|
||
_YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden');
|
||
_YargsInstance_exitError.set(this, null);
|
||
_YargsInstance_detectLocale.set(this, true);
|
||
_YargsInstance_emittedWarnings.set(this, {});
|
||
_YargsInstance_exitProcess.set(this, true);
|
||
_YargsInstance_frozens.set(this, []);
|
||
_YargsInstance_globalMiddleware.set(this, void 0);
|
||
_YargsInstance_groups.set(this, {});
|
||
_YargsInstance_hasOutput.set(this, false);
|
||
_YargsInstance_helpOpt.set(this, null);
|
||
_YargsInstance_isGlobalContext.set(this, true);
|
||
_YargsInstance_logger.set(this, void 0);
|
||
_YargsInstance_output.set(this, '');
|
||
_YargsInstance_options.set(this, void 0);
|
||
_YargsInstance_parentRequire.set(this, void 0);
|
||
_YargsInstance_parserConfig.set(this, {});
|
||
_YargsInstance_parseFn.set(this, null);
|
||
_YargsInstance_parseContext.set(this, null);
|
||
_YargsInstance_pkgs.set(this, {});
|
||
_YargsInstance_preservedGroups.set(this, {});
|
||
_YargsInstance_processArgs.set(this, void 0);
|
||
_YargsInstance_recommendCommands.set(this, false);
|
||
_YargsInstance_shim.set(this, void 0);
|
||
_YargsInstance_strict.set(this, false);
|
||
_YargsInstance_strictCommands.set(this, false);
|
||
_YargsInstance_strictOptions.set(this, false);
|
||
_YargsInstance_usage.set(this, void 0);
|
||
_YargsInstance_usageConfig.set(this, {});
|
||
_YargsInstance_versionOpt.set(this, null);
|
||
_YargsInstance_validation.set(this, void 0);
|
||
__classPrivateFieldSet(this, _YargsInstance_shim, shim, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
|
||
this.$0 = this[kGetDollarZero]();
|
||
this[kReset]();
|
||
__classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f");
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f");
|
||
}
|
||
addHelpOpt(opt, msg) {
|
||
const defaultHelpOpt = 'help';
|
||
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
|
||
if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) {
|
||
this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
|
||
__classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f");
|
||
}
|
||
if (opt === false && msg === undefined)
|
||
return this;
|
||
__classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f");
|
||
this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
|
||
this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help'));
|
||
return this;
|
||
}
|
||
help(opt, msg) {
|
||
return this.addHelpOpt(opt, msg);
|
||
}
|
||
addShowHiddenOpt(opt, msg) {
|
||
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
|
||
if (opt === false && msg === undefined)
|
||
return this;
|
||
const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
|
||
this.boolean(showHiddenOpt);
|
||
this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options'));
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
|
||
return this;
|
||
}
|
||
showHidden(opt, msg) {
|
||
return this.addShowHiddenOpt(opt, msg);
|
||
}
|
||
alias(key, value) {
|
||
argsert('<object|string|array> [string|array]', [key, value], arguments.length);
|
||
this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value);
|
||
return this;
|
||
}
|
||
array(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('array', keys);
|
||
this[kTrackManuallySetKeys](keys);
|
||
return this;
|
||
}
|
||
boolean(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('boolean', keys);
|
||
this[kTrackManuallySetKeys](keys);
|
||
return this;
|
||
}
|
||
check(f, global) {
|
||
argsert('<function> [boolean]', [f, global], arguments.length);
|
||
this.middleware((argv, _yargs) => {
|
||
return maybeAsyncResult(() => {
|
||
return f(argv, _yargs.getOptions());
|
||
}, (result) => {
|
||
if (!result) {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString()));
|
||
}
|
||
else if (typeof result === 'string' || result instanceof Error) {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result);
|
||
}
|
||
return argv;
|
||
}, (err) => {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
|
||
return argv;
|
||
});
|
||
}, false, global);
|
||
return this;
|
||
}
|
||
choices(key, value) {
|
||
argsert('<object|string|array> [string|array]', [key, value], arguments.length);
|
||
this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value);
|
||
return this;
|
||
}
|
||
coerce(keys, value) {
|
||
argsert('<object|string|array> [function]', [keys, value], arguments.length);
|
||
if (Array.isArray(keys)) {
|
||
if (!value) {
|
||
throw new YError('coerce callback must be provided');
|
||
}
|
||
for (const key of keys) {
|
||
this.coerce(key, value);
|
||
}
|
||
return this;
|
||
}
|
||
else if (typeof keys === 'object') {
|
||
for (const key of Object.keys(keys)) {
|
||
this.coerce(key, keys[key]);
|
||
}
|
||
return this;
|
||
}
|
||
if (!value) {
|
||
throw new YError('coerce callback must be provided');
|
||
}
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true;
|
||
__classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
|
||
let aliases;
|
||
const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
|
||
if (!shouldCoerce) {
|
||
return argv;
|
||
}
|
||
return maybeAsyncResult(() => {
|
||
aliases = yargs.getAliases();
|
||
return value(argv[keys]);
|
||
}, (result) => {
|
||
argv[keys] = result;
|
||
const stripAliased = yargs
|
||
.getInternalMethods()
|
||
.getParserConfiguration()['strip-aliased'];
|
||
if (aliases[keys] && stripAliased !== true) {
|
||
for (const alias of aliases[keys]) {
|
||
argv[alias] = result;
|
||
}
|
||
}
|
||
return argv;
|
||
}, (err) => {
|
||
throw new YError(err.message);
|
||
});
|
||
}, keys);
|
||
return this;
|
||
}
|
||
conflicts(key1, key2) {
|
||
argsert('<string|object> [string|array]', [key1, key2], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2);
|
||
return this;
|
||
}
|
||
config(key = 'config', msg, parseFn) {
|
||
argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
|
||
if (typeof key === 'object' && !Array.isArray(key)) {
|
||
key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key);
|
||
return this;
|
||
}
|
||
if (typeof msg === 'function') {
|
||
parseFn = msg;
|
||
msg = undefined;
|
||
}
|
||
this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file'));
|
||
(Array.isArray(key) ? key : [key]).forEach(k => {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true;
|
||
});
|
||
return this;
|
||
}
|
||
completion(cmd, desc, fn) {
|
||
argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
|
||
if (typeof desc === 'function') {
|
||
fn = desc;
|
||
desc = undefined;
|
||
}
|
||
__classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f");
|
||
if (!desc && desc !== false) {
|
||
desc = 'generate completion script';
|
||
}
|
||
this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc);
|
||
if (fn)
|
||
__classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn);
|
||
return this;
|
||
}
|
||
command(cmd, description, builder, handler, middlewares, deprecated) {
|
||
argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated);
|
||
return this;
|
||
}
|
||
commands(cmd, description, builder, handler, middlewares, deprecated) {
|
||
return this.command(cmd, description, builder, handler, middlewares, deprecated);
|
||
}
|
||
commandDir(dir, opts) {
|
||
argsert('<string> [object]', [dir, opts], arguments.length);
|
||
const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require;
|
||
__classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts);
|
||
return this;
|
||
}
|
||
count(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('count', keys);
|
||
this[kTrackManuallySetKeys](keys);
|
||
return this;
|
||
}
|
||
default(key, value, defaultDescription) {
|
||
argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
|
||
if (defaultDescription) {
|
||
assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
|
||
}
|
||
if (typeof value === 'function') {
|
||
assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key])
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] =
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value);
|
||
value = value.call();
|
||
}
|
||
this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value);
|
||
return this;
|
||
}
|
||
defaults(key, value, defaultDescription) {
|
||
return this.default(key, value, defaultDescription);
|
||
}
|
||
demandCommand(min = 1, max, minMsg, maxMsg) {
|
||
argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
|
||
if (typeof max !== 'number') {
|
||
minMsg = max;
|
||
max = Infinity;
|
||
}
|
||
this.global('_', false);
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = {
|
||
min,
|
||
max,
|
||
minMsg,
|
||
maxMsg,
|
||
};
|
||
return this;
|
||
}
|
||
demand(keys, max, msg) {
|
||
if (Array.isArray(max)) {
|
||
max.forEach(key => {
|
||
assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
this.demandOption(key, msg);
|
||
});
|
||
max = Infinity;
|
||
}
|
||
else if (typeof max !== 'number') {
|
||
msg = max;
|
||
max = Infinity;
|
||
}
|
||
if (typeof keys === 'number') {
|
||
assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
this.demandCommand(keys, max, msg, msg);
|
||
}
|
||
else if (Array.isArray(keys)) {
|
||
keys.forEach(key => {
|
||
assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
this.demandOption(key, msg);
|
||
});
|
||
}
|
||
else {
|
||
if (typeof msg === 'string') {
|
||
this.demandOption(keys, msg);
|
||
}
|
||
else if (msg === true || typeof msg === 'undefined') {
|
||
this.demandOption(keys);
|
||
}
|
||
}
|
||
return this;
|
||
}
|
||
demandOption(keys, msg) {
|
||
argsert('<object|string|array> [string]', [keys, msg], arguments.length);
|
||
this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg);
|
||
return this;
|
||
}
|
||
deprecateOption(option, message) {
|
||
argsert('<string> [string|boolean]', [option, message], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message;
|
||
return this;
|
||
}
|
||
describe(keys, description) {
|
||
argsert('<object|string|array> [string]', [keys, description], arguments.length);
|
||
this[kSetKey](keys, true);
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description);
|
||
return this;
|
||
}
|
||
detectLocale(detect) {
|
||
argsert('<boolean>', [detect], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f");
|
||
return this;
|
||
}
|
||
env(prefix) {
|
||
argsert('[string|boolean]', [prefix], arguments.length);
|
||
if (prefix === false)
|
||
delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix;
|
||
else
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || '';
|
||
return this;
|
||
}
|
||
epilogue(msg) {
|
||
argsert('<string>', [msg], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg);
|
||
return this;
|
||
}
|
||
epilog(msg) {
|
||
return this.epilogue(msg);
|
||
}
|
||
example(cmd, description) {
|
||
argsert('<string|array> [string]', [cmd, description], arguments.length);
|
||
if (Array.isArray(cmd)) {
|
||
cmd.forEach(exampleParams => this.example(...exampleParams));
|
||
}
|
||
else {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description);
|
||
}
|
||
return this;
|
||
}
|
||
exit(code, err) {
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_exitError, err, "f");
|
||
if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code);
|
||
}
|
||
exitProcess(enabled = true) {
|
||
argsert('[boolean]', [enabled], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f");
|
||
return this;
|
||
}
|
||
fail(f) {
|
||
argsert('<function|boolean>', [f], arguments.length);
|
||
if (typeof f === 'boolean' && f !== false) {
|
||
throw new YError("Invalid first argument. Expected function or boolean 'false'");
|
||
}
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f);
|
||
return this;
|
||
}
|
||
getAliases() {
|
||
return this.parsed ? this.parsed.aliases : {};
|
||
}
|
||
async getCompletion(args, done) {
|
||
argsert('<array> [function]', [args, done], arguments.length);
|
||
if (!done) {
|
||
return new Promise((resolve, reject) => {
|
||
__classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
|
||
if (err)
|
||
reject(err);
|
||
else
|
||
resolve(completions);
|
||
});
|
||
});
|
||
}
|
||
else {
|
||
return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done);
|
||
}
|
||
}
|
||
getDemandedOptions() {
|
||
argsert([], 0);
|
||
return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions;
|
||
}
|
||
getDemandedCommands() {
|
||
argsert([], 0);
|
||
return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands;
|
||
}
|
||
getDeprecatedOptions() {
|
||
argsert([], 0);
|
||
return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions;
|
||
}
|
||
getDetectLocale() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f");
|
||
}
|
||
getExitProcess() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f");
|
||
}
|
||
getGroups() {
|
||
return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"));
|
||
}
|
||
getHelp() {
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
|
||
if (!this.parsed) {
|
||
const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true);
|
||
if (isPromise(parse)) {
|
||
return parse.then(() => {
|
||
return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help();
|
||
});
|
||
}
|
||
}
|
||
const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
|
||
if (isPromise(builderResponse)) {
|
||
return builderResponse.then(() => {
|
||
return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help();
|
||
});
|
||
}
|
||
}
|
||
return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help());
|
||
}
|
||
getOptions() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_options, "f");
|
||
}
|
||
getStrict() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_strict, "f");
|
||
}
|
||
getStrictCommands() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f");
|
||
}
|
||
getStrictOptions() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f");
|
||
}
|
||
global(globals, global) {
|
||
argsert('<string|array> [boolean]', [globals, global], arguments.length);
|
||
globals = [].concat(globals);
|
||
if (global !== false) {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1);
|
||
}
|
||
else {
|
||
globals.forEach(g => {
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g))
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g);
|
||
});
|
||
}
|
||
return this;
|
||
}
|
||
group(opts, groupName) {
|
||
argsert('<string|array> <string>', [opts, groupName], arguments.length);
|
||
const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName];
|
||
if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) {
|
||
delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName];
|
||
}
|
||
const seen = {};
|
||
__classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => {
|
||
if (seen[key])
|
||
return false;
|
||
return (seen[key] = true);
|
||
});
|
||
return this;
|
||
}
|
||
hide(key) {
|
||
argsert('<string>', [key], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key);
|
||
return this;
|
||
}
|
||
implies(key, value) {
|
||
argsert('<string|object> [number|string|array]', [key, value], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value);
|
||
return this;
|
||
}
|
||
locale(locale) {
|
||
argsert('[string]', [locale], arguments.length);
|
||
if (locale === undefined) {
|
||
this[kGuessLocale]();
|
||
return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale();
|
||
}
|
||
__classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f");
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
|
||
return this;
|
||
}
|
||
middleware(callback, applyBeforeValidation, global) {
|
||
return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global);
|
||
}
|
||
nargs(key, value) {
|
||
argsert('<string|object|array> [number]', [key, value], arguments.length);
|
||
this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value);
|
||
return this;
|
||
}
|
||
normalize(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('normalize', keys);
|
||
return this;
|
||
}
|
||
number(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('number', keys);
|
||
this[kTrackManuallySetKeys](keys);
|
||
return this;
|
||
}
|
||
option(key, opt) {
|
||
argsert('<string|object> [object]', [key, opt], arguments.length);
|
||
if (typeof key === 'object') {
|
||
Object.keys(key).forEach(k => {
|
||
this.options(k, key[k]);
|
||
});
|
||
}
|
||
else {
|
||
if (typeof opt !== 'object') {
|
||
opt = {};
|
||
}
|
||
this[kTrackManuallySetKeys](key);
|
||
if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) {
|
||
this[kEmitWarning]([
|
||
'"version" is a reserved word.',
|
||
'Please do one of the following:',
|
||
'- Disable version with `yargs.version(false)` if using "version" as an option',
|
||
'- Use the built-in `yargs.version` method instead (if applicable)',
|
||
'- Use a different option key',
|
||
'https://yargs.js.org/docs/#api-reference-version',
|
||
].join('\n'), undefined, 'versionWarning');
|
||
}
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true;
|
||
if (opt.alias)
|
||
this.alias(key, opt.alias);
|
||
const deprecate = opt.deprecate || opt.deprecated;
|
||
if (deprecate) {
|
||
this.deprecateOption(key, deprecate);
|
||
}
|
||
const demand = opt.demand || opt.required || opt.require;
|
||
if (demand) {
|
||
this.demand(key, demand);
|
||
}
|
||
if (opt.demandOption) {
|
||
this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
|
||
}
|
||
if (opt.conflicts) {
|
||
this.conflicts(key, opt.conflicts);
|
||
}
|
||
if ('default' in opt) {
|
||
this.default(key, opt.default);
|
||
}
|
||
if (opt.implies !== undefined) {
|
||
this.implies(key, opt.implies);
|
||
}
|
||
if (opt.nargs !== undefined) {
|
||
this.nargs(key, opt.nargs);
|
||
}
|
||
if (opt.config) {
|
||
this.config(key, opt.configParser);
|
||
}
|
||
if (opt.normalize) {
|
||
this.normalize(key);
|
||
}
|
||
if (opt.choices) {
|
||
this.choices(key, opt.choices);
|
||
}
|
||
if (opt.coerce) {
|
||
this.coerce(key, opt.coerce);
|
||
}
|
||
if (opt.group) {
|
||
this.group(key, opt.group);
|
||
}
|
||
if (opt.boolean || opt.type === 'boolean') {
|
||
this.boolean(key);
|
||
if (opt.alias)
|
||
this.boolean(opt.alias);
|
||
}
|
||
if (opt.array || opt.type === 'array') {
|
||
this.array(key);
|
||
if (opt.alias)
|
||
this.array(opt.alias);
|
||
}
|
||
if (opt.number || opt.type === 'number') {
|
||
this.number(key);
|
||
if (opt.alias)
|
||
this.number(opt.alias);
|
||
}
|
||
if (opt.string || opt.type === 'string') {
|
||
this.string(key);
|
||
if (opt.alias)
|
||
this.string(opt.alias);
|
||
}
|
||
if (opt.count || opt.type === 'count') {
|
||
this.count(key);
|
||
}
|
||
if (typeof opt.global === 'boolean') {
|
||
this.global(key, opt.global);
|
||
}
|
||
if (opt.defaultDescription) {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
|
||
}
|
||
if (opt.skipValidation) {
|
||
this.skipValidation(key);
|
||
}
|
||
const desc = opt.describe || opt.description || opt.desc;
|
||
const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions();
|
||
if (!Object.prototype.hasOwnProperty.call(descriptions, key) ||
|
||
typeof desc === 'string') {
|
||
this.describe(key, desc);
|
||
}
|
||
if (opt.hidden) {
|
||
this.hide(key);
|
||
}
|
||
if (opt.requiresArg) {
|
||
this.requiresArg(key);
|
||
}
|
||
}
|
||
return this;
|
||
}
|
||
options(key, opt) {
|
||
return this.option(key, opt);
|
||
}
|
||
parse(args, shortCircuit, _parseFn) {
|
||
argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
|
||
this[kFreeze]();
|
||
if (typeof args === 'undefined') {
|
||
args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f");
|
||
}
|
||
if (typeof shortCircuit === 'object') {
|
||
__classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f");
|
||
shortCircuit = _parseFn;
|
||
}
|
||
if (typeof shortCircuit === 'function') {
|
||
__classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f");
|
||
shortCircuit = false;
|
||
}
|
||
if (!shortCircuit)
|
||
__classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f");
|
||
if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
|
||
__classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f");
|
||
const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
|
||
const tmpParsed = this.parsed;
|
||
__classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed);
|
||
if (isPromise(parsed)) {
|
||
return parsed
|
||
.then(argv => {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
|
||
__classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
|
||
return argv;
|
||
})
|
||
.catch(err => {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) {
|
||
__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
|
||
}
|
||
throw err;
|
||
})
|
||
.finally(() => {
|
||
this[kUnfreeze]();
|
||
this.parsed = tmpParsed;
|
||
});
|
||
}
|
||
else {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
|
||
__classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
|
||
this[kUnfreeze]();
|
||
this.parsed = tmpParsed;
|
||
}
|
||
return parsed;
|
||
}
|
||
parseAsync(args, shortCircuit, _parseFn) {
|
||
const maybePromise = this.parse(args, shortCircuit, _parseFn);
|
||
return !isPromise(maybePromise)
|
||
? Promise.resolve(maybePromise)
|
||
: maybePromise;
|
||
}
|
||
parseSync(args, shortCircuit, _parseFn) {
|
||
const maybePromise = this.parse(args, shortCircuit, _parseFn);
|
||
if (isPromise(maybePromise)) {
|
||
throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware');
|
||
}
|
||
return maybePromise;
|
||
}
|
||
parserConfiguration(config) {
|
||
argsert('<object>', [config], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f");
|
||
return this;
|
||
}
|
||
pkgConf(key, rootPath) {
|
||
argsert('<string> [string]', [key, rootPath], arguments.length);
|
||
let conf = null;
|
||
const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"));
|
||
if (obj[key] && typeof obj[key] === 'object') {
|
||
conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
|
||
}
|
||
return this;
|
||
}
|
||
positional(key, opts) {
|
||
argsert('<string> <object>', [key, opts], arguments.length);
|
||
const supportedOpts = [
|
||
'default',
|
||
'defaultDescription',
|
||
'implies',
|
||
'normalize',
|
||
'choices',
|
||
'conflicts',
|
||
'coerce',
|
||
'type',
|
||
'describe',
|
||
'desc',
|
||
'description',
|
||
'alias',
|
||
];
|
||
opts = objFilter(opts, (k, v) => {
|
||
if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
|
||
return false;
|
||
return supportedOpts.includes(k);
|
||
});
|
||
const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1];
|
||
const parseOptions = fullCommand
|
||
? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand)
|
||
: {
|
||
array: [],
|
||
alias: {},
|
||
default: {},
|
||
demand: {},
|
||
};
|
||
objectKeys(parseOptions).forEach(pk => {
|
||
const parseOption = parseOptions[pk];
|
||
if (Array.isArray(parseOption)) {
|
||
if (parseOption.indexOf(key) !== -1)
|
||
opts[pk] = true;
|
||
}
|
||
else {
|
||
if (parseOption[key] && !(pk in opts))
|
||
opts[pk] = parseOption[key];
|
||
}
|
||
});
|
||
this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName());
|
||
return this.option(key, opts);
|
||
}
|
||
recommendCommands(recommend = true) {
|
||
argsert('[boolean]', [recommend], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f");
|
||
return this;
|
||
}
|
||
required(keys, max, msg) {
|
||
return this.demand(keys, max, msg);
|
||
}
|
||
require(keys, max, msg) {
|
||
return this.demand(keys, max, msg);
|
||
}
|
||
requiresArg(keys) {
|
||
argsert('<array|string|object> [number]', [keys], arguments.length);
|
||
if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) {
|
||
return this;
|
||
}
|
||
else {
|
||
this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN);
|
||
}
|
||
return this;
|
||
}
|
||
showCompletionScript($0, cmd) {
|
||
argsert('[string] [string]', [$0, cmd], arguments.length);
|
||
$0 = $0 || this.$0;
|
||
__classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion'));
|
||
return this;
|
||
}
|
||
showHelp(level) {
|
||
argsert('[string|function]', [level], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
|
||
if (!this.parsed) {
|
||
const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true);
|
||
if (isPromise(parse)) {
|
||
parse.then(() => {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
|
||
});
|
||
return this;
|
||
}
|
||
}
|
||
const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
|
||
if (isPromise(builderResponse)) {
|
||
builderResponse.then(() => {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
|
||
});
|
||
return this;
|
||
}
|
||
}
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
|
||
return this;
|
||
}
|
||
scriptName(scriptName) {
|
||
this.customScriptName = true;
|
||
this.$0 = scriptName;
|
||
return this;
|
||
}
|
||
showHelpOnFail(enabled, message) {
|
||
argsert('[boolean|string] [string]', [enabled, message], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
|
||
return this;
|
||
}
|
||
showVersion(level) {
|
||
argsert('[string|function]', [level], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level);
|
||
return this;
|
||
}
|
||
skipValidation(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('skipValidation', keys);
|
||
return this;
|
||
}
|
||
strict(enabled) {
|
||
argsert('[boolean]', [enabled], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f");
|
||
return this;
|
||
}
|
||
strictCommands(enabled) {
|
||
argsert('[boolean]', [enabled], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f");
|
||
return this;
|
||
}
|
||
strictOptions(enabled) {
|
||
argsert('[boolean]', [enabled], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f");
|
||
return this;
|
||
}
|
||
string(keys) {
|
||
argsert('<array|string>', [keys], arguments.length);
|
||
this[kPopulateParserHintArray]('string', keys);
|
||
this[kTrackManuallySetKeys](keys);
|
||
return this;
|
||
}
|
||
terminalWidth() {
|
||
argsert([], 0);
|
||
return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns;
|
||
}
|
||
updateLocale(obj) {
|
||
return this.updateStrings(obj);
|
||
}
|
||
updateStrings(obj) {
|
||
argsert('<object>', [obj], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f");
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
|
||
return this;
|
||
}
|
||
usage(msg, description, builder, handler) {
|
||
argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
|
||
if (description !== undefined) {
|
||
assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
if ((msg || '').match(/^\$0( |$)/)) {
|
||
return this.command(msg, description, builder, handler);
|
||
}
|
||
else {
|
||
throw new YError('.usage() description must start with $0 if being used as alias for .command()');
|
||
}
|
||
}
|
||
else {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg);
|
||
return this;
|
||
}
|
||
}
|
||
usageConfiguration(config) {
|
||
argsert('<object>', [config], arguments.length);
|
||
__classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f");
|
||
return this;
|
||
}
|
||
version(opt, msg, ver) {
|
||
const defaultVersionOpt = 'version';
|
||
argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
|
||
if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) {
|
||
this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"));
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined);
|
||
__classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f");
|
||
}
|
||
if (arguments.length === 0) {
|
||
ver = this[kGuessVersion]();
|
||
opt = defaultVersionOpt;
|
||
}
|
||
else if (arguments.length === 1) {
|
||
if (opt === false) {
|
||
return this;
|
||
}
|
||
ver = opt;
|
||
opt = defaultVersionOpt;
|
||
}
|
||
else if (arguments.length === 2) {
|
||
ver = msg;
|
||
msg = undefined;
|
||
}
|
||
__classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f");
|
||
msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number');
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined);
|
||
this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"));
|
||
this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg);
|
||
return this;
|
||
}
|
||
wrap(cols) {
|
||
argsert('<number|null|undefined>', [cols], arguments.length);
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols);
|
||
return this;
|
||
}
|
||
[(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) {
|
||
if (!argv._ || !argv['--'])
|
||
return argv;
|
||
argv._.push.apply(argv._, argv['--']);
|
||
try {
|
||
delete argv['--'];
|
||
}
|
||
catch (_err) { }
|
||
return argv;
|
||
}
|
||
[kCreateLogger]() {
|
||
return {
|
||
log: (...args) => {
|
||
if (!this[kHasParseCallback]())
|
||
console.log(...args);
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length)
|
||
__classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f");
|
||
},
|
||
error: (...args) => {
|
||
if (!this[kHasParseCallback]())
|
||
console.error(...args);
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length)
|
||
__classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f");
|
||
},
|
||
};
|
||
}
|
||
[kDeleteFromParserHintObject](optionKey) {
|
||
objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => {
|
||
if (((key) => key === 'configObjects')(hintKey))
|
||
return;
|
||
const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey];
|
||
if (Array.isArray(hint)) {
|
||
if (hint.includes(optionKey))
|
||
hint.splice(hint.indexOf(optionKey), 1);
|
||
}
|
||
else if (typeof hint === 'object') {
|
||
delete hint[optionKey];
|
||
}
|
||
});
|
||
delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
|
||
}
|
||
[kEmitWarning](warning, type, deduplicationId) {
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
|
||
__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
|
||
}
|
||
}
|
||
[kFreeze]() {
|
||
__classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({
|
||
options: __classPrivateFieldGet(this, _YargsInstance_options, "f"),
|
||
configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0),
|
||
exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"),
|
||
groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"),
|
||
strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"),
|
||
strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"),
|
||
strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"),
|
||
completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"),
|
||
output: __classPrivateFieldGet(this, _YargsInstance_output, "f"),
|
||
exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"),
|
||
hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"),
|
||
parsed: this.parsed,
|
||
parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"),
|
||
parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"),
|
||
});
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_command, "f").freeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze();
|
||
}
|
||
[kGetDollarZero]() {
|
||
let $0 = '';
|
||
let default$0;
|
||
if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) {
|
||
default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
|
||
}
|
||
else {
|
||
default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
|
||
}
|
||
$0 = default$0
|
||
.map(x => {
|
||
const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x);
|
||
return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
|
||
})
|
||
.join(' ')
|
||
.trim();
|
||
if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') &&
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) {
|
||
$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f")
|
||
.getEnv('_')
|
||
.replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, '');
|
||
}
|
||
return $0;
|
||
}
|
||
[kGetParserConfiguration]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f");
|
||
}
|
||
[kGetUsageConfiguration]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f");
|
||
}
|
||
[kGuessLocale]() {
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"))
|
||
return;
|
||
const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') ||
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') ||
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') ||
|
||
__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') ||
|
||
'en_US';
|
||
this.locale(locale.replace(/[.:].*/, ''));
|
||
}
|
||
[kGuessVersion]() {
|
||
const obj = this[kPkgUp]();
|
||
return obj.version || 'unknown';
|
||
}
|
||
[kParsePositionalNumbers](argv) {
|
||
const args = argv['--'] ? argv['--'] : argv._;
|
||
for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) &&
|
||
Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
|
||
args[i] = Number(arg);
|
||
}
|
||
}
|
||
return argv;
|
||
}
|
||
[kPkgUp](rootPath) {
|
||
const npath = rootPath || '*';
|
||
if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath])
|
||
return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath];
|
||
let obj = {};
|
||
try {
|
||
let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename;
|
||
if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) {
|
||
startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir);
|
||
}
|
||
const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
|
||
if (names.includes('package.json')) {
|
||
return 'package.json';
|
||
}
|
||
else {
|
||
return undefined;
|
||
}
|
||
});
|
||
assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8'));
|
||
}
|
||
catch (_noop) { }
|
||
__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
|
||
return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath];
|
||
}
|
||
[kPopulateParserHintArray](type, keys) {
|
||
keys = [].concat(keys);
|
||
keys.forEach(key => {
|
||
key = this[kSanitizeKey](key);
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key);
|
||
});
|
||
}
|
||
[kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
|
||
this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value;
|
||
});
|
||
}
|
||
[kPopulateParserHintArrayDictionary](builder, type, key, value) {
|
||
this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value);
|
||
});
|
||
}
|
||
[kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
|
||
if (Array.isArray(key)) {
|
||
key.forEach(k => {
|
||
builder(k, value);
|
||
});
|
||
}
|
||
else if (((key) => typeof key === 'object')(key)) {
|
||
for (const k of objectKeys(key)) {
|
||
builder(k, key[k]);
|
||
}
|
||
}
|
||
else {
|
||
singleKeyHandler(type, this[kSanitizeKey](key), value);
|
||
}
|
||
}
|
||
[kSanitizeKey](key) {
|
||
if (key === '__proto__')
|
||
return '___proto___';
|
||
return key;
|
||
}
|
||
[kSetKey](key, set) {
|
||
this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set);
|
||
return this;
|
||
}
|
||
[kUnfreeze]() {
|
||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
|
||
const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop();
|
||
assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
|
||
let configObjects;
|
||
(_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
|
||
options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value,
|
||
configObjects,
|
||
exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value,
|
||
groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value,
|
||
output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value,
|
||
exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value,
|
||
hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value,
|
||
parsed: this.parsed,
|
||
strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value,
|
||
strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value,
|
||
strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value,
|
||
completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value,
|
||
parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value,
|
||
parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value,
|
||
} = frozen);
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects;
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze();
|
||
__classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze();
|
||
}
|
||
[kValidateAsync](validation, argv) {
|
||
return maybeAsyncResult(argv, result => {
|
||
validation(result);
|
||
return result;
|
||
});
|
||
}
|
||
getInternalMethods() {
|
||
return {
|
||
getCommandInstance: this[kGetCommandInstance].bind(this),
|
||
getContext: this[kGetContext].bind(this),
|
||
getHasOutput: this[kGetHasOutput].bind(this),
|
||
getLoggerInstance: this[kGetLoggerInstance].bind(this),
|
||
getParseContext: this[kGetParseContext].bind(this),
|
||
getParserConfiguration: this[kGetParserConfiguration].bind(this),
|
||
getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
|
||
getUsageInstance: this[kGetUsageInstance].bind(this),
|
||
getValidationInstance: this[kGetValidationInstance].bind(this),
|
||
hasParseCallback: this[kHasParseCallback].bind(this),
|
||
isGlobalContext: this[kIsGlobalContext].bind(this),
|
||
postProcess: this[kPostProcess].bind(this),
|
||
reset: this[kReset].bind(this),
|
||
runValidation: this[kRunValidation].bind(this),
|
||
runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
|
||
setHasOutput: this[kSetHasOutput].bind(this),
|
||
};
|
||
}
|
||
[kGetCommandInstance]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_command, "f");
|
||
}
|
||
[kGetContext]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_context, "f");
|
||
}
|
||
[kGetHasOutput]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f");
|
||
}
|
||
[kGetLoggerInstance]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_logger, "f");
|
||
}
|
||
[kGetParseContext]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {};
|
||
}
|
||
[kGetUsageInstance]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_usage, "f");
|
||
}
|
||
[kGetValidationInstance]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_validation, "f");
|
||
}
|
||
[kHasParseCallback]() {
|
||
return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f");
|
||
}
|
||
[kIsGlobalContext]() {
|
||
return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f");
|
||
}
|
||
[kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
|
||
if (calledFromCommand)
|
||
return argv;
|
||
if (isPromise(argv))
|
||
return argv;
|
||
if (!populateDoubleDash) {
|
||
argv = this[kCopyDoubleDash](argv);
|
||
}
|
||
const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] ||
|
||
this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
|
||
if (parsePositionalNumbers) {
|
||
argv = this[kParsePositionalNumbers](argv);
|
||
}
|
||
if (runGlobalMiddleware) {
|
||
argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
|
||
}
|
||
return argv;
|
||
}
|
||
[kReset](aliases = {}) {
|
||
__classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f");
|
||
const tmpOptions = {};
|
||
tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || [];
|
||
tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || [];
|
||
const localLookup = {};
|
||
tmpOptions.local.forEach(l => {
|
||
localLookup[l] = true;
|
||
(aliases[l] || []).forEach(a => {
|
||
localLookup[a] = true;
|
||
});
|
||
});
|
||
Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
|
||
const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup));
|
||
if (keys.length > 0) {
|
||
acc[groupName] = keys;
|
||
}
|
||
return acc;
|
||
}, {}));
|
||
__classPrivateFieldSet(this, _YargsInstance_groups, {}, "f");
|
||
const arrayOptions = [
|
||
'array',
|
||
'boolean',
|
||
'string',
|
||
'skipValidation',
|
||
'count',
|
||
'normalize',
|
||
'number',
|
||
'hiddenOptions',
|
||
];
|
||
const objectOptions = [
|
||
'narg',
|
||
'key',
|
||
'alias',
|
||
'default',
|
||
'defaultDescription',
|
||
'config',
|
||
'choices',
|
||
'demandedOptions',
|
||
'demandedCommands',
|
||
'deprecatedOptions',
|
||
];
|
||
arrayOptions.forEach(k => {
|
||
tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]);
|
||
});
|
||
objectOptions.forEach((k) => {
|
||
tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]);
|
||
});
|
||
tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix;
|
||
__classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f")
|
||
? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup)
|
||
: usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f")
|
||
? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup)
|
||
: validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f")
|
||
? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset()
|
||
: command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f"))
|
||
__classPrivateFieldSet(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
|
||
__classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset();
|
||
__classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_output, '', "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_exitError, null, "f");
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f");
|
||
this.parsed = false;
|
||
return this;
|
||
}
|
||
[kRebase](base, dir) {
|
||
return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir);
|
||
}
|
||
[kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
|
||
let skipValidation = !!calledFromCommand || helpOnly;
|
||
args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f");
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__;
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
|
||
const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--'];
|
||
const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, {
|
||
'populate--': true,
|
||
});
|
||
const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), {
|
||
configuration: { 'parse-positional-numbers': false, ...config },
|
||
}));
|
||
const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"));
|
||
let argvPromise = undefined;
|
||
const aliases = parsed.aliases;
|
||
let helpOptSet = false;
|
||
let versionOptSet = false;
|
||
Object.keys(argv).forEach(key => {
|
||
if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) {
|
||
helpOptSet = true;
|
||
}
|
||
else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) {
|
||
versionOptSet = true;
|
||
}
|
||
});
|
||
argv.$0 = this.$0;
|
||
this.parsed = parsed;
|
||
if (commandIndex === 0) {
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
|
||
}
|
||
try {
|
||
this[kGuessLocale]();
|
||
if (shortCircuit) {
|
||
return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
|
||
}
|
||
if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) {
|
||
const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")]
|
||
.concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || [])
|
||
.filter(k => k.length > 1);
|
||
if (helpCmds.includes('' + argv._[argv._.length - 1])) {
|
||
argv._.pop();
|
||
helpOptSet = true;
|
||
}
|
||
}
|
||
__classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f");
|
||
const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands();
|
||
const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv;
|
||
const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
|
||
if (argv._.length) {
|
||
if (handlerKeys.length) {
|
||
let firstUnknownCommand;
|
||
for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
|
||
cmd = String(argv._[i]);
|
||
if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) {
|
||
const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
|
||
return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
|
||
}
|
||
else if (!firstUnknownCommand &&
|
||
cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) {
|
||
firstUnknownCommand = cmd;
|
||
break;
|
||
}
|
||
}
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() &&
|
||
__classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") &&
|
||
firstUnknownCommand &&
|
||
!skipRecommendation) {
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
|
||
}
|
||
}
|
||
if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") &&
|
||
argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) &&
|
||
!requestCompletions) {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
|
||
setBlocking(true);
|
||
this.showCompletionScript();
|
||
this.exit(0);
|
||
}
|
||
}
|
||
if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
|
||
const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
|
||
return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
|
||
}
|
||
if (requestCompletions) {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
|
||
setBlocking(true);
|
||
args = [].concat(args);
|
||
const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1);
|
||
__classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
|
||
if (err)
|
||
throw new YError(err.message);
|
||
(completions || []).forEach(completion => {
|
||
__classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion);
|
||
});
|
||
this.exit(0);
|
||
});
|
||
return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
|
||
}
|
||
if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) {
|
||
if (helpOptSet) {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
|
||
setBlocking(true);
|
||
skipValidation = true;
|
||
this.showHelp('log');
|
||
this.exit(0);
|
||
}
|
||
else if (versionOptSet) {
|
||
if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
|
||
setBlocking(true);
|
||
skipValidation = true;
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log');
|
||
this.exit(0);
|
||
}
|
||
}
|
||
if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) {
|
||
skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
|
||
}
|
||
if (!skipValidation) {
|
||
if (parsed.error)
|
||
throw new YError(parsed.error.message);
|
||
if (!requestCompletions) {
|
||
const validation = this[kRunValidation](aliases, {}, parsed.error);
|
||
if (!calledFromCommand) {
|
||
argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
|
||
}
|
||
argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
|
||
if (isPromise(argvPromise) && !calledFromCommand) {
|
||
argvPromise = argvPromise.then(() => {
|
||
return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (err) {
|
||
if (err instanceof YError)
|
||
__classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err);
|
||
else
|
||
throw err;
|
||
}
|
||
return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
|
||
}
|
||
[kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) {
|
||
const demandedOptions = { ...this.getDemandedOptions() };
|
||
return (argv) => {
|
||
if (parseErrors)
|
||
throw new YError(parseErrors.message);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
|
||
let failedStrictCommands = false;
|
||
if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) {
|
||
failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv);
|
||
}
|
||
if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
|
||
}
|
||
else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) {
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
|
||
}
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv);
|
||
__classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv);
|
||
};
|
||
}
|
||
[kSetHasOutput]() {
|
||
__classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
|
||
}
|
||
[kTrackManuallySetKeys](keys) {
|
||
if (typeof keys === 'string') {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true;
|
||
}
|
||
else {
|
||
for (const k of keys) {
|
||
__classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
function isYargsInstance(y) {
|
||
return !!y && typeof y.getInternalMethods === 'function';
|
||
}
|
||
|
||
;// ./node_modules/yargs/index.mjs
|
||
|
||
|
||
// Bootstraps yargs for ESM:
|
||
|
||
|
||
|
||
const Yargs = YargsFactory(esm);
|
||
/* harmony default export */ const yargs = (Yargs);
|
||
|
||
;// ./node_modules/yargs/helpers/helpers.mjs
|
||
|
||
|
||
|
||
|
||
|
||
const helpers_applyExtends = (config, cwd, mergeExtends) => {
|
||
return _applyExtends(config, cwd, mergeExtends, shim);
|
||
};
|
||
|
||
|
||
|
||
;// external "node:child_process"
|
||
const external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:child_process");
|
||
;// external "node:util"
|
||
const external_node_util_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
|
||
;// external "node:fs"
|
||
const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs");
|
||
;// external "node:path"
|
||
const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path");
|
||
;// external "node:os"
|
||
const external_node_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
|
||
;// ./node_modules/tslog/dist/esm/prettyLogStyles.js
|
||
const prettyLogStyles = {
|
||
reset: [0, 0],
|
||
bold: [1, 22],
|
||
dim: [2, 22],
|
||
italic: [3, 23],
|
||
underline: [4, 24],
|
||
overline: [53, 55],
|
||
inverse: [7, 27],
|
||
hidden: [8, 28],
|
||
strikethrough: [9, 29],
|
||
black: [30, 39],
|
||
red: [31, 39],
|
||
green: [32, 39],
|
||
yellow: [33, 39],
|
||
blue: [34, 39],
|
||
magenta: [35, 39],
|
||
cyan: [36, 39],
|
||
white: [37, 39],
|
||
blackBright: [90, 39],
|
||
redBright: [91, 39],
|
||
greenBright: [92, 39],
|
||
yellowBright: [93, 39],
|
||
blueBright: [94, 39],
|
||
magentaBright: [95, 39],
|
||
cyanBright: [96, 39],
|
||
whiteBright: [97, 39],
|
||
bgBlack: [40, 49],
|
||
bgRed: [41, 49],
|
||
bgGreen: [42, 49],
|
||
bgYellow: [43, 49],
|
||
bgBlue: [44, 49],
|
||
bgMagenta: [45, 49],
|
||
bgCyan: [46, 49],
|
||
bgWhite: [47, 49],
|
||
bgBlackBright: [100, 49],
|
||
bgRedBright: [101, 49],
|
||
bgGreenBright: [102, 49],
|
||
bgYellowBright: [103, 49],
|
||
bgBlueBright: [104, 49],
|
||
bgMagentaBright: [105, 49],
|
||
bgCyanBright: [106, 49],
|
||
bgWhiteBright: [107, 49],
|
||
};
|
||
|
||
;// ./node_modules/tslog/dist/esm/formatTemplate.js
|
||
|
||
function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
|
||
const templateString = String(template);
|
||
const ansiColorWrap = (placeholderValue, code) => `\u001b[${code[0]}m${placeholderValue}\u001b[${code[1]}m`;
|
||
const styleWrap = (value, style) => {
|
||
if (style != null && typeof style === "string") {
|
||
return ansiColorWrap(value, prettyLogStyles[style]);
|
||
}
|
||
else if (style != null && Array.isArray(style)) {
|
||
return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
|
||
}
|
||
else {
|
||
if (style != null && style[value.trim()] != null) {
|
||
return styleWrap(value, style[value.trim()]);
|
||
}
|
||
else if (style != null && style["*"] != null) {
|
||
return styleWrap(value, style["*"]);
|
||
}
|
||
else {
|
||
return value;
|
||
}
|
||
}
|
||
};
|
||
const defaultStyle = null;
|
||
return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
|
||
const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
|
||
return settings.stylePrettyLogs
|
||
? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset)
|
||
: value;
|
||
});
|
||
}
|
||
|
||
;// ./node_modules/tslog/dist/esm/formatNumberAddZeros.js
|
||
function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
|
||
if (value != null && isNaN(value)) {
|
||
return "";
|
||
}
|
||
value = value != null ? value + addNumber : value;
|
||
return digits === 2
|
||
? value == null
|
||
? "--"
|
||
: value < 10
|
||
? "0" + value
|
||
: value.toString()
|
||
: value == null
|
||
? "---"
|
||
: value < 10
|
||
? "00" + value
|
||
: value < 100
|
||
? "0" + value
|
||
: value.toString();
|
||
}
|
||
|
||
;// ./node_modules/tslog/dist/esm/urlToObj.js
|
||
function urlToObject(url) {
|
||
return {
|
||
href: url.href,
|
||
protocol: url.protocol,
|
||
username: url.username,
|
||
password: url.password,
|
||
host: url.host,
|
||
hostname: url.hostname,
|
||
port: url.port,
|
||
pathname: url.pathname,
|
||
search: url.search,
|
||
searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
|
||
hash: url.hash,
|
||
origin: url.origin,
|
||
};
|
||
}
|
||
|
||
;// external "os"
|
||
const external_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
|
||
;// ./node_modules/tslog/dist/esm/runtime/nodejs/index.js
|
||
|
||
|
||
|
||
|
||
/* harmony default export */ const nodejs = ({
|
||
getCallerStackFrame,
|
||
getErrorTrace,
|
||
getMeta,
|
||
transportJSON,
|
||
transportFormatted,
|
||
isBuffer,
|
||
isError,
|
||
prettyFormatLogObj,
|
||
prettyFormatErrorObj,
|
||
});
|
||
const meta = {
|
||
runtime: "Nodejs",
|
||
runtimeVersion: process?.version,
|
||
hostname: external_os_namespaceObject.hostname ? (0,external_os_namespaceObject.hostname)() : undefined,
|
||
};
|
||
function getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
|
||
return Object.assign({}, meta, {
|
||
name,
|
||
parentNames,
|
||
date: new Date(),
|
||
logLevelId,
|
||
logLevelName,
|
||
path: !hideLogPositionForPerformance ? getCallerStackFrame(stackDepthLevel) : undefined,
|
||
});
|
||
}
|
||
function getCallerStackFrame(stackDepthLevel, error = Error()) {
|
||
return stackLineToStackFrame(error?.stack?.split("\n")?.filter((thisLine) => thisLine.includes(" at "))?.[stackDepthLevel]);
|
||
}
|
||
function getErrorTrace(error) {
|
||
return error?.stack?.split("\n")?.reduce((result, line) => {
|
||
if (line.includes(" at ")) {
|
||
result.push(stackLineToStackFrame(line));
|
||
}
|
||
return result;
|
||
}, []);
|
||
}
|
||
function stackLineToStackFrame(line) {
|
||
const pathResult = {
|
||
fullFilePath: undefined,
|
||
fileName: undefined,
|
||
fileNameWithLine: undefined,
|
||
fileColumn: undefined,
|
||
fileLine: undefined,
|
||
filePath: undefined,
|
||
filePathWithLine: undefined,
|
||
method: undefined,
|
||
};
|
||
if (line != null && line.includes(" at ")) {
|
||
line = line.replace(/^\s+at\s+/gm, "");
|
||
const errorStackLine = line.split(" (");
|
||
const fullFilePath = line?.slice(-1) === ")" ? line?.match(/\(([^)]+)\)/)?.[1] : line;
|
||
const pathArray = fullFilePath?.includes(":") ? fullFilePath?.replace("file://", "")?.replace(process.cwd(), "")?.split(":") : undefined;
|
||
const fileColumn = pathArray?.pop();
|
||
const fileLine = pathArray?.pop();
|
||
const filePath = pathArray?.pop();
|
||
const filePathWithLine = (0,external_path_namespaceObject.normalize)(`${filePath}:${fileLine}`);
|
||
const fileName = filePath?.split("/")?.pop();
|
||
const fileNameWithLine = `${fileName}:${fileLine}`;
|
||
if (filePath != null && filePath.length > 0) {
|
||
pathResult.fullFilePath = fullFilePath;
|
||
pathResult.fileName = fileName;
|
||
pathResult.fileNameWithLine = fileNameWithLine;
|
||
pathResult.fileColumn = fileColumn;
|
||
pathResult.fileLine = fileLine;
|
||
pathResult.filePath = filePath;
|
||
pathResult.filePathWithLine = filePathWithLine;
|
||
pathResult.method = errorStackLine?.[1] != null ? errorStackLine?.[0] : undefined;
|
||
}
|
||
}
|
||
return pathResult;
|
||
}
|
||
function isError(e) {
|
||
return external_util_namespaceObject.types?.isNativeError != null ? external_util_namespaceObject.types.isNativeError(e) : e instanceof Error;
|
||
}
|
||
function prettyFormatLogObj(maskedArgs, settings) {
|
||
return maskedArgs.reduce((result, arg) => {
|
||
isError(arg) ? result.errors.push(prettyFormatErrorObj(arg, settings)) : result.args.push(arg);
|
||
return result;
|
||
}, { args: [], errors: [] });
|
||
}
|
||
function prettyFormatErrorObj(error, settings) {
|
||
const errorStackStr = getErrorTrace(error).map((stackFrame) => {
|
||
return formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true);
|
||
});
|
||
const placeholderValuesError = {
|
||
errorName: ` ${error.name} `,
|
||
errorMessage: Object.getOwnPropertyNames(error)
|
||
.reduce((result, key) => {
|
||
if (key !== "stack") {
|
||
result.push(error[key]);
|
||
}
|
||
return result;
|
||
}, [])
|
||
.join(", "),
|
||
errorStack: errorStackStr.join("\n"),
|
||
};
|
||
return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
|
||
}
|
||
function transportFormatted(logMetaMarkup, logArgs, logErrors, settings) {
|
||
const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
|
||
settings.prettyInspectOptions.colors = settings.stylePrettyLogs;
|
||
console.log(logMetaMarkup + (0,external_util_namespaceObject.formatWithOptions)(settings.prettyInspectOptions, ...logArgs) + logErrorsStr);
|
||
}
|
||
function transportJSON(json) {
|
||
console.log(jsonStringifyRecursive(json));
|
||
function jsonStringifyRecursive(obj) {
|
||
const cache = new Set();
|
||
return JSON.stringify(obj, (key, value) => {
|
||
if (typeof value === "object" && value !== null) {
|
||
if (cache.has(value)) {
|
||
return "[Circular]";
|
||
}
|
||
cache.add(value);
|
||
}
|
||
if (typeof value === "bigint") {
|
||
return `${value}`;
|
||
}
|
||
if (typeof value === "undefined") {
|
||
return "[undefined]";
|
||
}
|
||
return value;
|
||
});
|
||
}
|
||
}
|
||
function isBuffer(arg) {
|
||
return Buffer.isBuffer(arg);
|
||
}
|
||
|
||
;// ./node_modules/tslog/dist/esm/BaseLogger.js
|
||
|
||
|
||
|
||
|
||
|
||
|
||
class BaseLogger {
|
||
constructor(settings, logObj, stackDepthLevel = 4) {
|
||
this.logObj = logObj;
|
||
this.stackDepthLevel = stackDepthLevel;
|
||
this.runtime = nodejs;
|
||
this.settings = {
|
||
type: settings?.type ?? "pretty",
|
||
name: settings?.name,
|
||
parentNames: settings?.parentNames,
|
||
minLevel: settings?.minLevel ?? 0,
|
||
argumentsArrayName: settings?.argumentsArrayName,
|
||
hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
|
||
prettyLogTemplate: settings?.prettyLogTemplate ??
|
||
"{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t",
|
||
prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
|
||
prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
|
||
prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
|
||
prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? "\t",
|
||
stylePrettyLogs: settings?.stylePrettyLogs ?? true,
|
||
prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
|
||
prettyLogStyles: settings?.prettyLogStyles ?? {
|
||
logLevelName: {
|
||
"*": ["bold", "black", "bgWhiteBright", "dim"],
|
||
SILLY: ["bold", "white"],
|
||
TRACE: ["bold", "whiteBright"],
|
||
DEBUG: ["bold", "green"],
|
||
INFO: ["bold", "blue"],
|
||
WARN: ["bold", "yellow"],
|
||
ERROR: ["bold", "red"],
|
||
FATAL: ["bold", "redBright"],
|
||
},
|
||
dateIsoStr: "white",
|
||
filePathWithLine: "white",
|
||
name: ["white", "bold"],
|
||
nameWithDelimiterPrefix: ["white", "bold"],
|
||
nameWithDelimiterSuffix: ["white", "bold"],
|
||
errorName: ["bold", "bgRedBright", "whiteBright"],
|
||
fileName: ["yellow"],
|
||
fileNameWithLine: "white",
|
||
},
|
||
prettyInspectOptions: settings?.prettyInspectOptions ?? {
|
||
colors: true,
|
||
compact: false,
|
||
depth: Infinity,
|
||
},
|
||
metaProperty: settings?.metaProperty ?? "_meta",
|
||
maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
|
||
maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
|
||
maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
|
||
maskValuesRegEx: settings?.maskValuesRegEx,
|
||
prefix: [...(settings?.prefix ?? [])],
|
||
attachedTransports: [...(settings?.attachedTransports ?? [])],
|
||
overwrite: {
|
||
mask: settings?.overwrite?.mask,
|
||
toLogObj: settings?.overwrite?.toLogObj,
|
||
addMeta: settings?.overwrite?.addMeta,
|
||
addPlaceholders: settings?.overwrite?.addPlaceholders,
|
||
formatMeta: settings?.overwrite?.formatMeta,
|
||
formatLogObj: settings?.overwrite?.formatLogObj,
|
||
transportFormatted: settings?.overwrite?.transportFormatted,
|
||
transportJSON: settings?.overwrite?.transportJSON,
|
||
},
|
||
};
|
||
}
|
||
log(logLevelId, logLevelName, ...args) {
|
||
if (logLevelId < this.settings.minLevel) {
|
||
return;
|
||
}
|
||
const logArgs = [...this.settings.prefix, ...args];
|
||
const maskedArgs = this.settings.overwrite?.mask != null
|
||
? this.settings.overwrite?.mask(logArgs)
|
||
: this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0
|
||
? this._mask(logArgs)
|
||
: logArgs;
|
||
const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : undefined;
|
||
const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
|
||
const logObjWithMeta = this.settings.overwrite?.addMeta != null
|
||
? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName)
|
||
: this._addMetaToLogObj(logObj, logLevelId, logLevelName);
|
||
let logMetaMarkup;
|
||
let logArgsAndErrorsMarkup = undefined;
|
||
if (this.settings.overwrite?.formatMeta != null) {
|
||
logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
|
||
}
|
||
if (this.settings.overwrite?.formatLogObj != null) {
|
||
logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
|
||
}
|
||
if (this.settings.type === "pretty") {
|
||
logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
|
||
logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? this.runtime.prettyFormatLogObj(maskedArgs, this.settings);
|
||
}
|
||
if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
|
||
this.settings.overwrite?.transportFormatted != null
|
||
? this.settings.overwrite?.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings)
|
||
: this.runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings);
|
||
}
|
||
else {
|
||
this.settings.overwrite?.transportJSON != null
|
||
? this.settings.overwrite?.transportJSON(logObjWithMeta)
|
||
: this.settings.type !== "hidden"
|
||
? this.runtime.transportJSON(logObjWithMeta)
|
||
: undefined;
|
||
}
|
||
if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
|
||
this.settings.attachedTransports.forEach((transportLogger) => {
|
||
transportLogger(logObjWithMeta);
|
||
});
|
||
}
|
||
return logObjWithMeta;
|
||
}
|
||
attachTransport(transportLogger) {
|
||
this.settings.attachedTransports.push(transportLogger);
|
||
}
|
||
getSubLogger(settings, logObj) {
|
||
const subLoggerSettings = {
|
||
...this.settings,
|
||
...settings,
|
||
parentNames: this.settings?.parentNames != null && this.settings?.name != null
|
||
? [...this.settings.parentNames, this.settings.name]
|
||
: this.settings?.name != null
|
||
? [this.settings.name]
|
||
: undefined,
|
||
prefix: [...this.settings.prefix, ...(settings?.prefix ?? [])],
|
||
};
|
||
const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
|
||
return subLogger;
|
||
}
|
||
_mask(args) {
|
||
const maskValuesOfKeys = this.settings.maskValuesOfKeysCaseInsensitive !== true ? this.settings.maskValuesOfKeys : this.settings.maskValuesOfKeys.map((key) => key.toLowerCase());
|
||
return args?.map((arg) => {
|
||
return this._recursiveCloneAndMaskValuesOfKeys(arg, maskValuesOfKeys);
|
||
});
|
||
}
|
||
_recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
|
||
if (seen.includes(source)) {
|
||
return { ...source };
|
||
}
|
||
if (typeof source === "object" && source !== null) {
|
||
seen.push(source);
|
||
}
|
||
if (this.runtime.isError(source) || this.runtime.isBuffer(source)) {
|
||
return source;
|
||
}
|
||
else if (source instanceof Map) {
|
||
return new Map(source);
|
||
}
|
||
else if (source instanceof Set) {
|
||
return new Set(source);
|
||
}
|
||
else if (Array.isArray(source)) {
|
||
return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
|
||
}
|
||
else if (source instanceof Date) {
|
||
return new Date(source.getTime());
|
||
}
|
||
else if (source instanceof URL) {
|
||
return urlToObject(source);
|
||
}
|
||
else if (source !== null && typeof source === "object") {
|
||
const baseObject = this.runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
|
||
return Object.getOwnPropertyNames(source).reduce((o, prop) => {
|
||
o[prop] = keys.includes(this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : prop.toLowerCase())
|
||
? this.settings.maskPlaceholder
|
||
: (() => {
|
||
try {
|
||
return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
|
||
}
|
||
catch (e) {
|
||
return null;
|
||
}
|
||
})();
|
||
return o;
|
||
}, baseObject);
|
||
}
|
||
else {
|
||
if (typeof source === "string") {
|
||
let modifiedSource = source;
|
||
for (const regEx of this.settings?.maskValuesRegEx || []) {
|
||
modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
|
||
}
|
||
return modifiedSource;
|
||
}
|
||
return source;
|
||
}
|
||
}
|
||
_recursiveCloneAndExecuteFunctions(source, seen = []) {
|
||
if (this.isObjectOrArray(source) && seen.includes(source)) {
|
||
return this.shallowCopy(source);
|
||
}
|
||
if (this.isObjectOrArray(source)) {
|
||
seen.push(source);
|
||
}
|
||
if (Array.isArray(source)) {
|
||
return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
|
||
}
|
||
else if (source instanceof Date) {
|
||
return new Date(source.getTime());
|
||
}
|
||
else if (this.isObject(source)) {
|
||
return Object.getOwnPropertyNames(source).reduce((o, prop) => {
|
||
const descriptor = Object.getOwnPropertyDescriptor(source, prop);
|
||
if (descriptor) {
|
||
Object.defineProperty(o, prop, descriptor);
|
||
const value = source[prop];
|
||
o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
|
||
}
|
||
return o;
|
||
}, Object.create(Object.getPrototypeOf(source)));
|
||
}
|
||
else {
|
||
return source;
|
||
}
|
||
}
|
||
isObjectOrArray(value) {
|
||
return typeof value === "object" && value !== null;
|
||
}
|
||
isObject(value) {
|
||
return typeof value === "object" && !Array.isArray(value) && value !== null;
|
||
}
|
||
shallowCopy(source) {
|
||
if (Array.isArray(source)) {
|
||
return [...source];
|
||
}
|
||
else {
|
||
return { ...source };
|
||
}
|
||
}
|
||
_toLogObj(args, clonedLogObj = {}) {
|
||
args = args?.map((arg) => (this.runtime.isError(arg) ? this._toErrorObject(arg) : arg));
|
||
if (this.settings.argumentsArrayName == null) {
|
||
if (args.length === 1 && !Array.isArray(args[0]) && this.runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
|
||
clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
|
||
}
|
||
else {
|
||
clonedLogObj = { ...clonedLogObj, ...args };
|
||
}
|
||
}
|
||
else {
|
||
clonedLogObj = {
|
||
...clonedLogObj,
|
||
[this.settings.argumentsArrayName]: args,
|
||
};
|
||
}
|
||
return clonedLogObj;
|
||
}
|
||
_cloneError(error) {
|
||
const cloned = new error.constructor();
|
||
Object.getOwnPropertyNames(error).forEach((key) => {
|
||
cloned[key] = error[key];
|
||
});
|
||
return cloned;
|
||
}
|
||
_toErrorObject(error) {
|
||
return {
|
||
nativeError: error,
|
||
name: error.name ?? "Error",
|
||
message: error.message,
|
||
stack: this.runtime.getErrorTrace(error),
|
||
};
|
||
}
|
||
_addMetaToLogObj(logObj, logLevelId, logLevelName) {
|
||
return {
|
||
...logObj,
|
||
[this.settings.metaProperty]: this.runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, this.settings.hideLogPositionForProduction, this.settings.name, this.settings.parentNames),
|
||
};
|
||
}
|
||
_prettyFormatLogObjMeta(logObjMeta) {
|
||
if (logObjMeta == null) {
|
||
return "";
|
||
}
|
||
let template = this.settings.prettyLogTemplate;
|
||
const placeholderValues = {};
|
||
if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
|
||
template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
|
||
}
|
||
else {
|
||
if (this.settings.prettyLogTimeZone === "UTC") {
|
||
placeholderValues["yyyy"] = logObjMeta?.date?.getUTCFullYear() ?? "----";
|
||
placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMonth(), 2, 1);
|
||
placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getUTCDate(), 2);
|
||
placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getUTCHours(), 2);
|
||
placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMinutes(), 2);
|
||
placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getUTCSeconds(), 2);
|
||
placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMilliseconds(), 3);
|
||
}
|
||
else {
|
||
placeholderValues["yyyy"] = logObjMeta?.date?.getFullYear() ?? "----";
|
||
placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getMonth(), 2, 1);
|
||
placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getDate(), 2);
|
||
placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getHours(), 2);
|
||
placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getMinutes(), 2);
|
||
placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getSeconds(), 2);
|
||
placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getMilliseconds(), 3);
|
||
}
|
||
}
|
||
const dateInSettingsTimeZone = this.settings.prettyLogTimeZone === "UTC" ? logObjMeta?.date : new Date(logObjMeta?.date?.getTime() - logObjMeta?.date?.getTimezoneOffset() * 60000);
|
||
placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString();
|
||
placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "");
|
||
placeholderValues["logLevelName"] = logObjMeta?.logLevelName;
|
||
placeholderValues["fileNameWithLine"] = logObjMeta?.path?.fileNameWithLine ?? "";
|
||
placeholderValues["filePathWithLine"] = logObjMeta?.path?.filePathWithLine ?? "";
|
||
placeholderValues["fullFilePath"] = logObjMeta?.path?.fullFilePath ?? "";
|
||
let parentNamesString = this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);
|
||
parentNamesString = parentNamesString != null && logObjMeta?.name != null ? parentNamesString + this.settings.prettyErrorParentNamesSeparator : undefined;
|
||
placeholderValues["name"] = logObjMeta?.name != null || parentNamesString != null ? (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
|
||
placeholderValues["nameWithDelimiterPrefix"] =
|
||
placeholderValues["name"].length > 0 ? this.settings.prettyErrorLoggerNameDelimiter + placeholderValues["name"] : "";
|
||
placeholderValues["nameWithDelimiterSuffix"] =
|
||
placeholderValues["name"].length > 0 ? placeholderValues["name"] + this.settings.prettyErrorLoggerNameDelimiter : "";
|
||
if (this.settings.overwrite?.addPlaceholders != null) {
|
||
this.settings.overwrite?.addPlaceholders(logObjMeta, placeholderValues);
|
||
}
|
||
return formatTemplate(this.settings, template, placeholderValues);
|
||
}
|
||
}
|
||
|
||
;// ./node_modules/tslog/dist/esm/index.js
|
||
|
||
|
||
|
||
class Logger extends BaseLogger {
|
||
constructor(settings, logObj) {
|
||
const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
||
const isBrowserBlinkEngine = isBrowser ? window.chrome !== undefined && window.CSS !== undefined && window.CSS.supports("color", "green") : false;
|
||
const isSafari = isBrowser ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
|
||
settings = settings || {};
|
||
settings.stylePrettyLogs = settings.stylePrettyLogs && isBrowser && !isBrowserBlinkEngine ? false : settings.stylePrettyLogs;
|
||
super(settings, logObj, isSafari ? 4 : 5);
|
||
}
|
||
log(logLevelId, logLevelName, ...args) {
|
||
return super.log(logLevelId, logLevelName, ...args);
|
||
}
|
||
silly(...args) {
|
||
return super.log(0, "SILLY", ...args);
|
||
}
|
||
trace(...args) {
|
||
return super.log(1, "TRACE", ...args);
|
||
}
|
||
debug(...args) {
|
||
return super.log(2, "DEBUG", ...args);
|
||
}
|
||
info(...args) {
|
||
return super.log(3, "INFO", ...args);
|
||
}
|
||
warn(...args) {
|
||
return super.log(4, "WARN", ...args);
|
||
}
|
||
error(...args) {
|
||
return super.log(5, "ERROR", ...args);
|
||
}
|
||
fatal(...args) {
|
||
return super.log(6, "FATAL", ...args);
|
||
}
|
||
getSubLogger(settings, logObj) {
|
||
return super.getSubLogger(settings, logObj);
|
||
}
|
||
}
|
||
|
||
;// ./src/logger.ts
|
||
|
||
// Configure log levels
|
||
var LogLevel;
|
||
(function (LogLevel) {
|
||
LogLevel["SILLY"] = "silly";
|
||
LogLevel["TRACE"] = "trace";
|
||
LogLevel["DEBUG"] = "debug";
|
||
LogLevel["INFO"] = "info";
|
||
LogLevel["WARN"] = "warn";
|
||
LogLevel["ERROR"] = "error";
|
||
LogLevel["FATAL"] = "fatal";
|
||
})(LogLevel || (LogLevel = {}));
|
||
// Mapping from string LogLevel to numeric values expected by tslog
|
||
const logLevelToTsLogLevel = {
|
||
[LogLevel.SILLY]: 0,
|
||
[LogLevel.TRACE]: 1,
|
||
[LogLevel.DEBUG]: 2,
|
||
[LogLevel.INFO]: 3,
|
||
[LogLevel.WARN]: 4,
|
||
[LogLevel.ERROR]: 5,
|
||
[LogLevel.FATAL]: 6
|
||
};
|
||
// Convert a LogLevel string to its corresponding numeric value
|
||
const getNumericLogLevel = (level) => {
|
||
return logLevelToTsLogLevel[level];
|
||
};
|
||
// Custom transport for logs if needed
|
||
const logToTransport = (logObject) => {
|
||
// Here you can implement custom transport like file or external service
|
||
// For example, log to file or send to a log management service
|
||
// console.log("Custom transport:", JSON.stringify(logObject));
|
||
};
|
||
// Create the logger instance
|
||
const logger = new Logger({
|
||
name: "yt-dlp-wrapper"
|
||
});
|
||
// Add transport if needed
|
||
// logger.attachTransport(
|
||
// {
|
||
// silly: logToTransport,
|
||
// debug: logToTransport,
|
||
// trace: logToTransport,
|
||
// info: logToTransport,
|
||
// warn: logToTransport,
|
||
// error: logToTransport,
|
||
// fatal: logToTransport,
|
||
// },
|
||
// LogLevel.INFO
|
||
// );
|
||
/* harmony default export */ const src_logger = ((/* unused pure expression or super */ null && (logger)));
|
||
|
||
;// ./src/ytdlp.ts
|
||
|
||
|
||
|
||
|
||
|
||
|
||
const execAsync = (0,external_node_util_namespaceObject.promisify)(external_node_child_process_namespaceObject.exec);
|
||
/**
|
||
* A wrapper class for the yt-dlp command line tool
|
||
*/
|
||
class YtDlp {
|
||
/**
|
||
* Create a new YtDlp instance
|
||
* @param options Configuration options for yt-dlp
|
||
*/
|
||
constructor(options = {}) {
|
||
this.options = options;
|
||
this.executable = 'yt-dlp';
|
||
if (options.executablePath) {
|
||
this.executable = options.executablePath;
|
||
}
|
||
logger.debug('YtDlp initialized with options:', options);
|
||
}
|
||
/**
|
||
* Check if yt-dlp is installed and accessible
|
||
* @returns Promise resolving to true if yt-dlp is installed, false otherwise
|
||
*/
|
||
async isInstalled() {
|
||
try {
|
||
const { stdout } = await execAsync(`${this.executable} --version`);
|
||
logger.debug(`yt-dlp version: ${stdout.trim()}`);
|
||
return true;
|
||
}
|
||
catch (error) {
|
||
logger.warn('yt-dlp is not installed or not found in PATH');
|
||
return false;
|
||
}
|
||
}
|
||
/**
|
||
* Download a video from a given URL
|
||
* @param url The URL of the video to download
|
||
* @param options Download options
|
||
* @returns Promise resolving to the path of the downloaded file
|
||
*/
|
||
async downloadVideo(url, options = {}) {
|
||
if (!url) {
|
||
logger.error('Download failed: No URL provided');
|
||
throw new Error('URL is required');
|
||
}
|
||
logger.info(`Downloading video from: ${url}`);
|
||
logger.debug(`Download options: ${JSON.stringify({
|
||
...options,
|
||
// Redact any sensitive information
|
||
userAgent: this.options.userAgent ? '[REDACTED]' : undefined
|
||
}, null, 2)}`);
|
||
// Prepare output directory
|
||
const outputDir = options.outputDir || '.';
|
||
if (!external_node_fs_namespaceObject.existsSync(outputDir)) {
|
||
logger.debug(`Creating output directory: ${outputDir}`);
|
||
try {
|
||
external_node_fs_namespaceObject.mkdirSync(outputDir, { recursive: true });
|
||
logger.debug(`Output directory created successfully`);
|
||
}
|
||
catch (error) {
|
||
logger.error(`Failed to create output directory: ${error.message}`);
|
||
throw new Error(`Failed to create output directory ${outputDir}: ${error.message}`);
|
||
}
|
||
}
|
||
else {
|
||
logger.debug(`Output directory already exists: ${outputDir}`);
|
||
}
|
||
// Build command arguments
|
||
const args = [];
|
||
// Add user agent if specified in global options
|
||
if (this.options.userAgent) {
|
||
args.push('--user-agent', this.options.userAgent);
|
||
}
|
||
// Format selection
|
||
if (options.format) {
|
||
args.push('-f', options.format);
|
||
}
|
||
// Output template
|
||
const outputTemplate = options.outputTemplate || '%(title)s.%(ext)s';
|
||
args.push('-o', external_node_path_namespaceObject.join(outputDir, outputTemplate));
|
||
// Add other options
|
||
if (options.audioOnly) {
|
||
logger.debug(`Audio-only mode enabled, extracting audio with format: ${options.audioFormat || 'default'}`);
|
||
logger.info(`Extracting audio in ${options.audioFormat || 'best available'} format`);
|
||
// Add extract audio flag
|
||
args.push('-x');
|
||
// Handle audio format
|
||
if (options.audioFormat) {
|
||
logger.debug(`Setting audio format to: ${options.audioFormat}`);
|
||
args.push('--audio-format', options.audioFormat);
|
||
// For MP3 format, ensure we're using the right audio quality
|
||
if (options.audioFormat.toLowerCase() === 'mp3') {
|
||
logger.debug('MP3 format requested, setting audio quality');
|
||
args.push('--audio-quality', '0'); // 0 is best quality
|
||
// Ensure ffmpeg installed message for MP3 conversion
|
||
logger.debug('MP3 conversion requires ffmpeg to be installed');
|
||
logger.info('Note: MP3 conversion requires ffmpeg to be installed on your system');
|
||
}
|
||
}
|
||
logger.debug(`Audio extraction command arguments: ${args.join(' ')}`);
|
||
}
|
||
if (options.subtitles) {
|
||
args.push('--write-subs');
|
||
if (Array.isArray(options.subtitles)) {
|
||
args.push('--sub-lang', options.subtitles.join(','));
|
||
}
|
||
}
|
||
if (options.maxFileSize) {
|
||
args.push('--max-filesize', options.maxFileSize.toString());
|
||
}
|
||
if (options.rateLimit) {
|
||
args.push('--limit-rate', options.rateLimit);
|
||
}
|
||
// Add custom arguments if provided
|
||
if (options.additionalArgs) {
|
||
args.push(...options.additionalArgs);
|
||
}
|
||
// Add the URL
|
||
args.push(url);
|
||
// Create a copy of args with sensitive information redacted for logging
|
||
const logSafeArgs = [...args].map(arg => {
|
||
if (arg === this.options.userAgent && this.options.userAgent) {
|
||
return '[REDACTED]';
|
||
}
|
||
return arg;
|
||
});
|
||
// Log the command for debugging
|
||
logger.debug(`Executing download command: ${this.executable} ${logSafeArgs.join(' ')}`);
|
||
logger.debug(`Download configuration: audioOnly=${!!options.audioOnly}, format=${options.format || 'default'}, audioFormat=${options.audioFormat || 'n/a'}`);
|
||
// Add additional debugging for audio extraction
|
||
if (options.audioOnly) {
|
||
logger.debug(`Audio extraction details: format=${options.audioFormat || 'auto'}, mp3=${options.audioFormat?.toLowerCase() === 'mp3'}`);
|
||
logger.info(`Audio extraction mode: ${options.audioFormat || 'best quality'}`);
|
||
}
|
||
// Print to console for user feedback
|
||
if (options.audioOnly) {
|
||
logger.info(`Downloading audio in ${options.audioFormat || 'best'} format from: ${url}`);
|
||
}
|
||
else {
|
||
logger.info(`Downloading video from: ${url}`);
|
||
}
|
||
logger.debug('Executing download command');
|
||
return new Promise((resolve, reject) => {
|
||
logger.debug('Spawning yt-dlp process');
|
||
try {
|
||
const ytdlpProcess = (0,external_node_child_process_namespaceObject.spawn)(this.executable, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let stdout = '';
|
||
let stderr = '';
|
||
let downloadedFile = null;
|
||
let progressData = {
|
||
percent: 0,
|
||
totalSize: '0',
|
||
downloadedSize: '0',
|
||
speed: '0',
|
||
eta: '0'
|
||
};
|
||
ytdlpProcess.stdout.on('data', (data) => {
|
||
const output = data.toString();
|
||
stdout += output;
|
||
logger.debug(`yt-dlp output: ${output.trim()}`);
|
||
// Try to extract the output filename
|
||
const destinationMatch = output.match(/Destination: (.+)/);
|
||
if (destinationMatch && destinationMatch[1]) {
|
||
downloadedFile = destinationMatch[1].trim();
|
||
logger.debug(`Detected output filename: ${downloadedFile}`);
|
||
}
|
||
// Alternative method to extract the output filename
|
||
const alreadyDownloadedMatch = output.match(/\[download\] (.+) has already been downloaded/);
|
||
if (alreadyDownloadedMatch && alreadyDownloadedMatch[1]) {
|
||
downloadedFile = alreadyDownloadedMatch[1].trim();
|
||
logger.debug(`Video was already downloaded: ${downloadedFile}`);
|
||
}
|
||
// Track download progress
|
||
const progressMatch = output.match(/\[download\]\s+(\d+\.?\d*)%\s+of\s+~?(\S+)\s+at\s+(\S+)\s+ETA\s+(\S+)/);
|
||
if (progressMatch) {
|
||
progressData = {
|
||
percent: parseFloat(progressMatch[1]),
|
||
totalSize: progressMatch[2],
|
||
downloadedSize: (parseFloat(progressMatch[1]) * parseFloat(progressMatch[2]) / 100).toFixed(2) + 'MB',
|
||
speed: progressMatch[3],
|
||
eta: progressMatch[4]
|
||
};
|
||
// Log progress more frequently for better user feedback
|
||
if (Math.floor(progressData.percent) % 5 === 0) {
|
||
logger.info(`Download progress: ${progressData.percent.toFixed(1)}% (${progressData.downloadedSize}/${progressData.totalSize}) at ${progressData.speed} (ETA: ${progressData.eta})`);
|
||
}
|
||
}
|
||
// Capture the file after extraction (important for audio conversions)
|
||
const extractingMatch = output.match(/\[ExtractAudio\] Destination: (.+)/);
|
||
if (extractingMatch && extractingMatch[1]) {
|
||
downloadedFile = extractingMatch[1].trim();
|
||
logger.debug(`Audio extraction destination: ${downloadedFile}`);
|
||
// Log audio conversion information
|
||
if (options.audioOnly) {
|
||
logger.info(`Converting to ${options.audioFormat || 'best format'}: ${downloadedFile}`);
|
||
}
|
||
}
|
||
// Also capture ffmpeg conversion progress for audio
|
||
const ffmpegMatch = output.match(/\[ffmpeg\] Destination: (.+)/);
|
||
if (ffmpegMatch && ffmpegMatch[1]) {
|
||
downloadedFile = ffmpegMatch[1].trim();
|
||
logger.debug(`ffmpeg conversion destination: ${downloadedFile}`);
|
||
if (options.audioOnly && options.audioFormat) {
|
||
logger.info(`Converting to ${options.audioFormat}: ${downloadedFile}`);
|
||
}
|
||
}
|
||
});
|
||
ytdlpProcess.stderr.on('data', (data) => {
|
||
const output = data.toString();
|
||
stderr += output;
|
||
logger.error(`yt-dlp error: ${output.trim()}`);
|
||
// Try to detect common error types for better error reporting
|
||
if (output.includes('No such file or directory')) {
|
||
logger.error('yt-dlp executable not found. Please make sure it is installed and in your PATH.');
|
||
}
|
||
else if (output.includes('HTTP Error 403: Forbidden')) {
|
||
logger.error('Access forbidden - the server denied access. This might be due to rate limiting or geo-restrictions.');
|
||
}
|
||
else if (output.includes('HTTP Error 404: Not Found')) {
|
||
logger.error('The requested video was not found. It might have been deleted or made private.');
|
||
}
|
||
else if (output.includes('Unsupported URL')) {
|
||
logger.error('The URL is not supported by yt-dlp. Check if the website is supported or if you need a newer version of yt-dlp.');
|
||
}
|
||
});
|
||
ytdlpProcess.on('close', (code) => {
|
||
logger.debug(`yt-dlp process exited with code ${code}`);
|
||
if (code === 0) {
|
||
if (downloadedFile) {
|
||
// Verify the file actually exists
|
||
try {
|
||
const stats = external_node_fs_namespaceObject.statSync(downloadedFile);
|
||
logger.info(`Successfully downloaded: ${downloadedFile} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);
|
||
resolve(downloadedFile);
|
||
}
|
||
catch (error) {
|
||
logger.warn(`File reported as downloaded but not found on disk: ${downloadedFile}`);
|
||
logger.debug(`File access error: ${error.message}`);
|
||
// Try to find an alternative filename
|
||
const possibleFiles = this.searchPossibleFilenames(stdout, outputDir);
|
||
if (possibleFiles.length > 0) {
|
||
logger.info(`Found alternative downloaded file: ${possibleFiles[0]}`);
|
||
resolve(possibleFiles[0]);
|
||
}
|
||
else {
|
||
logger.info('Download reported as successful, but could not locate the output file');
|
||
resolve('Download completed');
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
// Try to find the downloaded file from stdout if it wasn't captured
|
||
logger.debug('No downloadedFile captured, searching stdout for filename');
|
||
const possibleFiles = this.searchPossibleFilenames(stdout, outputDir);
|
||
if (possibleFiles.length > 0) {
|
||
logger.info(`Successfully downloaded: ${possibleFiles[0]}`);
|
||
resolve(possibleFiles[0]);
|
||
}
|
||
else {
|
||
logger.info('Download successful, but could not determine the output file name');
|
||
logger.debug('Full stdout for debugging:');
|
||
logger.debug(stdout);
|
||
resolve('Download completed');
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
logger.error(`Download failed with exit code ${code}`);
|
||
// Provide more context based on the error code
|
||
let errorContext = '';
|
||
if (code === 1) {
|
||
errorContext = 'General error - check URL and network connection';
|
||
}
|
||
else if (code === 2) {
|
||
errorContext = 'Network error - check your internet connection';
|
||
}
|
||
else if (code === 3) {
|
||
errorContext = 'File system error - check permissions and disk space';
|
||
}
|
||
reject(new Error(`yt-dlp exited with code ${code} (${errorContext}): ${stderr}`));
|
||
}
|
||
});
|
||
ytdlpProcess.on('error', (err) => {
|
||
logger.error(`Failed to start yt-dlp process: ${err.message}`);
|
||
logger.debug(`Error details: ${JSON.stringify(err)}`);
|
||
// Check for common spawn errors and provide helpful messages
|
||
if (err.message.includes('ENOENT')) {
|
||
reject(new Error(`yt-dlp executable not found. Make sure it's installed and available in your PATH. Error: ${err.message}`));
|
||
}
|
||
else if (err.message.includes('EACCES')) {
|
||
reject(new Error(`Permission denied when executing yt-dlp. Check file permissions. Error: ${err.message}`));
|
||
}
|
||
else {
|
||
reject(new Error(`Failed to start yt-dlp: ${err.message}`));
|
||
}
|
||
});
|
||
// Handle unexpected termination
|
||
process.on('SIGINT', () => {
|
||
logger.warn('Process interrupted, terminating download');
|
||
ytdlpProcess.kill('SIGINT');
|
||
});
|
||
}
|
||
catch (error) {
|
||
logger.error(`Exception during process spawn: ${error.message}`);
|
||
reject(new Error(`Failed to start download process: ${error.message}`));
|
||
}
|
||
});
|
||
}
|
||
/**
|
||
* Search for possible filenames in yt-dlp output
|
||
* @param stdout The stdout output from yt-dlp
|
||
* @param outputDir The output directory
|
||
* @returns Array of possible filenames found
|
||
*/
|
||
searchPossibleFilenames(stdout, outputDir) {
|
||
const possibleFiles = [];
|
||
// Various regex patterns to find filenames in the yt-dlp output
|
||
const patterns = [
|
||
/\[download\] (.+?) has already been downloaded/,
|
||
/\[download\] Destination: (.+)/,
|
||
/\[ffmpeg\] Destination: (.+)/,
|
||
/\[ExtractAudio\] Destination: (.+)/,
|
||
/\[Merger\] Merging formats into "(.+)"/,
|
||
/\[Merger\] Merged into (.+)/
|
||
];
|
||
// Try each pattern
|
||
for (const pattern of patterns) {
|
||
const matches = stdout.matchAll(new RegExp(pattern, 'g'));
|
||
for (const match of matches) {
|
||
if (match[1]) {
|
||
const filePath = match[1].trim();
|
||
// Check if it's a relative or absolute path
|
||
const fullPath = external_node_path_namespaceObject.isAbsolute(filePath) ? filePath : external_node_path_namespaceObject.join(outputDir, filePath);
|
||
if (external_node_fs_namespaceObject.existsSync(fullPath)) {
|
||
logger.debug(`Found output file: ${fullPath}`);
|
||
possibleFiles.push(fullPath);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return possibleFiles;
|
||
}
|
||
/**
|
||
* Get information about a video without downloading it
|
||
* @param url The URL of the video to get information for
|
||
* @returns Promise resolving to video information
|
||
*/
|
||
/**
|
||
* Escapes a string for shell use based on the current platform
|
||
* @param str The string to escape
|
||
* @returns The escaped string
|
||
*/
|
||
escapeShellArg(str) {
|
||
if (external_node_os_namespaceObject.platform() === 'win32') {
|
||
// Windows: Double quotes need to be escaped with backslash
|
||
// and the whole string wrapped in double quotes
|
||
return `"${str.replace(/"/g, '\\"')}"`;
|
||
}
|
||
else {
|
||
// Unix-like: Single quotes provide the strongest escaping
|
||
// Double any existing single quotes and wrap in single quotes
|
||
return `'${str.replace(/'/g, "'\\''")}'`;
|
||
}
|
||
}
|
||
async getVideoInfo(url, options = { dumpJson: false, flatPlaylist: false }) {
|
||
if (!url) {
|
||
throw new Error('URL is required');
|
||
}
|
||
logger.info(`Getting video info for: ${url}`);
|
||
try {
|
||
// Build command with options
|
||
const args = ['--dump-json'];
|
||
// Add user agent if specified in global options
|
||
if (this.options.userAgent) {
|
||
args.push('--user-agent', this.options.userAgent);
|
||
}
|
||
// Add VideoInfoOptions flags
|
||
if (options.flatPlaylist) {
|
||
args.push('--flat-playlist');
|
||
}
|
||
args.push(url);
|
||
// Properly escape arguments for the exec call
|
||
const escapedArgs = args.map(arg => {
|
||
// Only escape arguments that need escaping (contains spaces or special characters)
|
||
return /[\s"'$&()<>`|;]/.test(arg) ? this.escapeShellArg(arg) : arg;
|
||
});
|
||
const { stdout } = await execAsync(`${this.executable} ${escapedArgs.join(' ')}`);
|
||
const videoInfo = JSON.parse(stdout);
|
||
logger.debug('Video info retrieved successfully');
|
||
return videoInfo;
|
||
}
|
||
catch (error) {
|
||
logger.error('Failed to get video info:', error);
|
||
throw new Error(`Failed to get video info: ${error.message}`);
|
||
}
|
||
}
|
||
/**
|
||
* List available formats for a video
|
||
* @param url The URL of the video to get formats for
|
||
* @returns Promise resolving to an array of VideoFormat objects
|
||
*/
|
||
async listFormats(url, options = { all: false }) {
|
||
if (!url) {
|
||
throw new Error('URL is required');
|
||
}
|
||
logger.info(`Listing formats for: ${url}`);
|
||
try {
|
||
// Build command with options
|
||
const formatFlag = options.all ? '--list-formats-all' : '-F';
|
||
// Properly escape URL if needed
|
||
const escapedUrl = /[\s"'$&()<>`|;]/.test(url) ? this.escapeShellArg(url) : url;
|
||
const { stdout } = await execAsync(`${this.executable} ${formatFlag} ${escapedUrl}`);
|
||
logger.debug('Format list retrieved successfully');
|
||
// Parse the output to extract format information
|
||
return this.parseFormatOutput(stdout);
|
||
}
|
||
catch (error) {
|
||
logger.error('Failed to list formats:', error);
|
||
throw new Error(`Failed to list formats: ${error.message}`);
|
||
}
|
||
}
|
||
/**
|
||
* Parse the format list output from yt-dlp into an array of VideoFormat objects
|
||
* @param output The raw output from yt-dlp format listing
|
||
* @returns Array of VideoFormat objects
|
||
*/
|
||
parseFormatOutput(output) {
|
||
const formats = [];
|
||
const lines = output.split('\n');
|
||
// Find the line with table headers to determine where the format list starts
|
||
let formatListStartIndex = 0;
|
||
for (let i = 0; i < lines.length; i++) {
|
||
if (lines[i].includes('format code') || lines[i].includes('ID')) {
|
||
formatListStartIndex = i + 1;
|
||
break;
|
||
}
|
||
}
|
||
// Regular expressions to match various format components
|
||
const formatIdRegex = /^(\S+)/;
|
||
const extensionRegex = /(\w+)\s+/;
|
||
const resolutionRegex = /(\d+x\d+|\d+p)/;
|
||
const fpsRegex = /(\d+)fps/;
|
||
const filesizeRegex = /(\d+(\.\d+)?)(K|M|G|T)iB/;
|
||
const bitrateRegex = /(\d+(\.\d+)?)(k|m)bps/;
|
||
const codecRegex = /(mp4|webm|m4a|mp3|opus|vorbis)\s+([\w.]+)/i;
|
||
const formatNoteRegex = /(audio only|video only|tiny|small|medium|large|best)/i;
|
||
// Process each line that contains format information
|
||
for (let i = formatListStartIndex; i < lines.length; i++) {
|
||
const line = lines[i].trim();
|
||
if (!line || line.includes('----'))
|
||
continue; // Skip empty lines or separators
|
||
// Extract format ID - typically the first part of the line
|
||
const formatIdMatch = line.match(formatIdRegex);
|
||
if (!formatIdMatch)
|
||
continue;
|
||
const formatId = formatIdMatch[1];
|
||
// Create a base format object
|
||
const format = {
|
||
format_id: formatId,
|
||
format: line, // Use the full line as the format description
|
||
ext: 'unknown',
|
||
protocol: 'https',
|
||
vcodec: 'unknown',
|
||
acodec: 'unknown'
|
||
};
|
||
// Try to extract format components
|
||
// Extract extension
|
||
const extMatch = line.substring(formatId.length).match(extensionRegex);
|
||
if (extMatch) {
|
||
format.ext = extMatch[1];
|
||
}
|
||
// Extract resolution
|
||
const resMatch = line.match(resolutionRegex);
|
||
if (resMatch) {
|
||
format.resolution = resMatch[1];
|
||
// If resolution is in the form of "1280x720", extract width and height
|
||
const dimensions = format.resolution.split('x');
|
||
if (dimensions.length === 2) {
|
||
format.width = parseInt(dimensions[0], 10);
|
||
format.height = parseInt(dimensions[1], 10);
|
||
}
|
||
else if (format.resolution.endsWith('p')) {
|
||
// If resolution is like "720p", extract height
|
||
format.height = parseInt(format.resolution.replace('p', ''), 10);
|
||
}
|
||
}
|
||
// Extract FPS
|
||
const fpsMatch = line.match(fpsRegex);
|
||
if (fpsMatch) {
|
||
format.fps = parseInt(fpsMatch[1], 10);
|
||
}
|
||
// Extract filesize
|
||
const sizeMatch = line.match(filesizeRegex);
|
||
if (sizeMatch) {
|
||
let size = parseFloat(sizeMatch[1]);
|
||
const unit = sizeMatch[3];
|
||
// Convert to bytes
|
||
if (unit === 'K')
|
||
size *= 1024;
|
||
else if (unit === 'M')
|
||
size *= 1024 * 1024;
|
||
else if (unit === 'G')
|
||
size *= 1024 * 1024 * 1024;
|
||
else if (unit === 'T')
|
||
size *= 1024 * 1024 * 1024 * 1024;
|
||
format.filesize = Math.round(size);
|
||
}
|
||
// Extract bitrate
|
||
const bitrateMatch = line.match(bitrateRegex);
|
||
if (bitrateMatch) {
|
||
let bitrate = parseFloat(bitrateMatch[1]);
|
||
const unit = bitrateMatch[3];
|
||
// Convert to Kbps
|
||
if (unit === 'm')
|
||
bitrate *= 1000;
|
||
format.tbr = bitrate;
|
||
}
|
||
// Extract format note
|
||
const noteMatch = line.match(formatNoteRegex);
|
||
if (noteMatch) {
|
||
format.format_note = noteMatch[1];
|
||
}
|
||
// Determine audio/video codec
|
||
if (line.includes('audio only')) {
|
||
format.vcodec = 'none';
|
||
// Try to get audio codec
|
||
const codecMatch = line.match(codecRegex);
|
||
if (codecMatch) {
|
||
format.acodec = codecMatch[2] || format.acodec;
|
||
}
|
||
}
|
||
else if (line.includes('video only')) {
|
||
format.acodec = 'none';
|
||
// Try to get video codec
|
||
const codecMatch = line.match(codecRegex);
|
||
if (codecMatch) {
|
||
format.vcodec = codecMatch[2] || format.vcodec;
|
||
}
|
||
}
|
||
else {
|
||
// Both audio and video
|
||
const codecMatch = line.match(codecRegex);
|
||
if (codecMatch) {
|
||
format.container = codecMatch[1];
|
||
if (codecMatch[2]) {
|
||
if (line.includes('video')) {
|
||
format.vcodec = codecMatch[2];
|
||
}
|
||
else if (line.includes('audio')) {
|
||
format.acodec = codecMatch[2];
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// Add the format to our result array
|
||
formats.push(format);
|
||
}
|
||
return formats;
|
||
}
|
||
/**
|
||
* Set the path to the yt-dlp executable
|
||
* @param path Path to the yt-dlp executable
|
||
*/
|
||
setExecutablePath(path) {
|
||
if (!path) {
|
||
throw new Error('Executable path cannot be empty');
|
||
}
|
||
this.executable = path;
|
||
logger.debug(`yt-dlp executable path set to: ${path}`);
|
||
}
|
||
}
|
||
/* harmony default export */ const ytdlp = ((/* unused pure expression or super */ null && (YtDlp)));
|
||
|
||
;// ./node_modules/zod/lib/index.mjs
|
||
var util;
|
||
(function (util) {
|
||
util.assertEqual = (val) => val;
|
||
function assertIs(_arg) { }
|
||
util.assertIs = assertIs;
|
||
function assertNever(_x) {
|
||
throw new Error();
|
||
}
|
||
util.assertNever = assertNever;
|
||
util.arrayToEnum = (items) => {
|
||
const obj = {};
|
||
for (const item of items) {
|
||
obj[item] = item;
|
||
}
|
||
return obj;
|
||
};
|
||
util.getValidEnumValues = (obj) => {
|
||
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
||
const filtered = {};
|
||
for (const k of validKeys) {
|
||
filtered[k] = obj[k];
|
||
}
|
||
return util.objectValues(filtered);
|
||
};
|
||
util.objectValues = (obj) => {
|
||
return util.objectKeys(obj).map(function (e) {
|
||
return obj[e];
|
||
});
|
||
};
|
||
util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
|
||
? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
|
||
: (object) => {
|
||
const keys = [];
|
||
for (const key in object) {
|
||
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
||
keys.push(key);
|
||
}
|
||
}
|
||
return keys;
|
||
};
|
||
util.find = (arr, checker) => {
|
||
for (const item of arr) {
|
||
if (checker(item))
|
||
return item;
|
||
}
|
||
return undefined;
|
||
};
|
||
util.isInteger = typeof Number.isInteger === "function"
|
||
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
|
||
: (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
|
||
function joinValues(array, separator = " | ") {
|
||
return array
|
||
.map((val) => (typeof val === "string" ? `'${val}'` : val))
|
||
.join(separator);
|
||
}
|
||
util.joinValues = joinValues;
|
||
util.jsonStringifyReplacer = (_, value) => {
|
||
if (typeof value === "bigint") {
|
||
return value.toString();
|
||
}
|
||
return value;
|
||
};
|
||
})(util || (util = {}));
|
||
var objectUtil;
|
||
(function (objectUtil) {
|
||
objectUtil.mergeShapes = (first, second) => {
|
||
return {
|
||
...first,
|
||
...second, // second overwrites first
|
||
};
|
||
};
|
||
})(objectUtil || (objectUtil = {}));
|
||
const ZodParsedType = util.arrayToEnum([
|
||
"string",
|
||
"nan",
|
||
"number",
|
||
"integer",
|
||
"float",
|
||
"boolean",
|
||
"date",
|
||
"bigint",
|
||
"symbol",
|
||
"function",
|
||
"undefined",
|
||
"null",
|
||
"array",
|
||
"object",
|
||
"unknown",
|
||
"promise",
|
||
"void",
|
||
"never",
|
||
"map",
|
||
"set",
|
||
]);
|
||
const getParsedType = (data) => {
|
||
const t = typeof data;
|
||
switch (t) {
|
||
case "undefined":
|
||
return ZodParsedType.undefined;
|
||
case "string":
|
||
return ZodParsedType.string;
|
||
case "number":
|
||
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
|
||
case "boolean":
|
||
return ZodParsedType.boolean;
|
||
case "function":
|
||
return ZodParsedType.function;
|
||
case "bigint":
|
||
return ZodParsedType.bigint;
|
||
case "symbol":
|
||
return ZodParsedType.symbol;
|
||
case "object":
|
||
if (Array.isArray(data)) {
|
||
return ZodParsedType.array;
|
||
}
|
||
if (data === null) {
|
||
return ZodParsedType.null;
|
||
}
|
||
if (data.then &&
|
||
typeof data.then === "function" &&
|
||
data.catch &&
|
||
typeof data.catch === "function") {
|
||
return ZodParsedType.promise;
|
||
}
|
||
if (typeof Map !== "undefined" && data instanceof Map) {
|
||
return ZodParsedType.map;
|
||
}
|
||
if (typeof Set !== "undefined" && data instanceof Set) {
|
||
return ZodParsedType.set;
|
||
}
|
||
if (typeof Date !== "undefined" && data instanceof Date) {
|
||
return ZodParsedType.date;
|
||
}
|
||
return ZodParsedType.object;
|
||
default:
|
||
return ZodParsedType.unknown;
|
||
}
|
||
};
|
||
|
||
const ZodIssueCode = util.arrayToEnum([
|
||
"invalid_type",
|
||
"invalid_literal",
|
||
"custom",
|
||
"invalid_union",
|
||
"invalid_union_discriminator",
|
||
"invalid_enum_value",
|
||
"unrecognized_keys",
|
||
"invalid_arguments",
|
||
"invalid_return_type",
|
||
"invalid_date",
|
||
"invalid_string",
|
||
"too_small",
|
||
"too_big",
|
||
"invalid_intersection_types",
|
||
"not_multiple_of",
|
||
"not_finite",
|
||
]);
|
||
const quotelessJson = (obj) => {
|
||
const json = JSON.stringify(obj, null, 2);
|
||
return json.replace(/"([^"]+)":/g, "$1:");
|
||
};
|
||
class ZodError extends Error {
|
||
get errors() {
|
||
return this.issues;
|
||
}
|
||
constructor(issues) {
|
||
super();
|
||
this.issues = [];
|
||
this.addIssue = (sub) => {
|
||
this.issues = [...this.issues, sub];
|
||
};
|
||
this.addIssues = (subs = []) => {
|
||
this.issues = [...this.issues, ...subs];
|
||
};
|
||
const actualProto = new.target.prototype;
|
||
if (Object.setPrototypeOf) {
|
||
// eslint-disable-next-line ban/ban
|
||
Object.setPrototypeOf(this, actualProto);
|
||
}
|
||
else {
|
||
this.__proto__ = actualProto;
|
||
}
|
||
this.name = "ZodError";
|
||
this.issues = issues;
|
||
}
|
||
format(_mapper) {
|
||
const mapper = _mapper ||
|
||
function (issue) {
|
||
return issue.message;
|
||
};
|
||
const fieldErrors = { _errors: [] };
|
||
const processError = (error) => {
|
||
for (const issue of error.issues) {
|
||
if (issue.code === "invalid_union") {
|
||
issue.unionErrors.map(processError);
|
||
}
|
||
else if (issue.code === "invalid_return_type") {
|
||
processError(issue.returnTypeError);
|
||
}
|
||
else if (issue.code === "invalid_arguments") {
|
||
processError(issue.argumentsError);
|
||
}
|
||
else if (issue.path.length === 0) {
|
||
fieldErrors._errors.push(mapper(issue));
|
||
}
|
||
else {
|
||
let curr = fieldErrors;
|
||
let i = 0;
|
||
while (i < issue.path.length) {
|
||
const el = issue.path[i];
|
||
const terminal = i === issue.path.length - 1;
|
||
if (!terminal) {
|
||
curr[el] = curr[el] || { _errors: [] };
|
||
// if (typeof el === "string") {
|
||
// curr[el] = curr[el] || { _errors: [] };
|
||
// } else if (typeof el === "number") {
|
||
// const errorArray: any = [];
|
||
// errorArray._errors = [];
|
||
// curr[el] = curr[el] || errorArray;
|
||
// }
|
||
}
|
||
else {
|
||
curr[el] = curr[el] || { _errors: [] };
|
||
curr[el]._errors.push(mapper(issue));
|
||
}
|
||
curr = curr[el];
|
||
i++;
|
||
}
|
||
}
|
||
}
|
||
};
|
||
processError(this);
|
||
return fieldErrors;
|
||
}
|
||
static assert(value) {
|
||
if (!(value instanceof ZodError)) {
|
||
throw new Error(`Not a ZodError: ${value}`);
|
||
}
|
||
}
|
||
toString() {
|
||
return this.message;
|
||
}
|
||
get message() {
|
||
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
|
||
}
|
||
get isEmpty() {
|
||
return this.issues.length === 0;
|
||
}
|
||
flatten(mapper = (issue) => issue.message) {
|
||
const fieldErrors = {};
|
||
const formErrors = [];
|
||
for (const sub of this.issues) {
|
||
if (sub.path.length > 0) {
|
||
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
|
||
fieldErrors[sub.path[0]].push(mapper(sub));
|
||
}
|
||
else {
|
||
formErrors.push(mapper(sub));
|
||
}
|
||
}
|
||
return { formErrors, fieldErrors };
|
||
}
|
||
get formErrors() {
|
||
return this.flatten();
|
||
}
|
||
}
|
||
ZodError.create = (issues) => {
|
||
const error = new ZodError(issues);
|
||
return error;
|
||
};
|
||
|
||
const errorMap = (issue, _ctx) => {
|
||
let message;
|
||
switch (issue.code) {
|
||
case ZodIssueCode.invalid_type:
|
||
if (issue.received === ZodParsedType.undefined) {
|
||
message = "Required";
|
||
}
|
||
else {
|
||
message = `Expected ${issue.expected}, received ${issue.received}`;
|
||
}
|
||
break;
|
||
case ZodIssueCode.invalid_literal:
|
||
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
|
||
break;
|
||
case ZodIssueCode.unrecognized_keys:
|
||
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
|
||
break;
|
||
case ZodIssueCode.invalid_union:
|
||
message = `Invalid input`;
|
||
break;
|
||
case ZodIssueCode.invalid_union_discriminator:
|
||
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
|
||
break;
|
||
case ZodIssueCode.invalid_enum_value:
|
||
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
|
||
break;
|
||
case ZodIssueCode.invalid_arguments:
|
||
message = `Invalid function arguments`;
|
||
break;
|
||
case ZodIssueCode.invalid_return_type:
|
||
message = `Invalid function return type`;
|
||
break;
|
||
case ZodIssueCode.invalid_date:
|
||
message = `Invalid date`;
|
||
break;
|
||
case ZodIssueCode.invalid_string:
|
||
if (typeof issue.validation === "object") {
|
||
if ("includes" in issue.validation) {
|
||
message = `Invalid input: must include "${issue.validation.includes}"`;
|
||
if (typeof issue.validation.position === "number") {
|
||
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
|
||
}
|
||
}
|
||
else if ("startsWith" in issue.validation) {
|
||
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
|
||
}
|
||
else if ("endsWith" in issue.validation) {
|
||
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
|
||
}
|
||
else {
|
||
util.assertNever(issue.validation);
|
||
}
|
||
}
|
||
else if (issue.validation !== "regex") {
|
||
message = `Invalid ${issue.validation}`;
|
||
}
|
||
else {
|
||
message = "Invalid";
|
||
}
|
||
break;
|
||
case ZodIssueCode.too_small:
|
||
if (issue.type === "array")
|
||
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
|
||
else if (issue.type === "string")
|
||
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
|
||
else if (issue.type === "number")
|
||
message = `Number must be ${issue.exact
|
||
? `exactly equal to `
|
||
: issue.inclusive
|
||
? `greater than or equal to `
|
||
: `greater than `}${issue.minimum}`;
|
||
else if (issue.type === "date")
|
||
message = `Date must be ${issue.exact
|
||
? `exactly equal to `
|
||
: issue.inclusive
|
||
? `greater than or equal to `
|
||
: `greater than `}${new Date(Number(issue.minimum))}`;
|
||
else
|
||
message = "Invalid input";
|
||
break;
|
||
case ZodIssueCode.too_big:
|
||
if (issue.type === "array")
|
||
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
|
||
else if (issue.type === "string")
|
||
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
|
||
else if (issue.type === "number")
|
||
message = `Number must be ${issue.exact
|
||
? `exactly`
|
||
: issue.inclusive
|
||
? `less than or equal to`
|
||
: `less than`} ${issue.maximum}`;
|
||
else if (issue.type === "bigint")
|
||
message = `BigInt must be ${issue.exact
|
||
? `exactly`
|
||
: issue.inclusive
|
||
? `less than or equal to`
|
||
: `less than`} ${issue.maximum}`;
|
||
else if (issue.type === "date")
|
||
message = `Date must be ${issue.exact
|
||
? `exactly`
|
||
: issue.inclusive
|
||
? `smaller than or equal to`
|
||
: `smaller than`} ${new Date(Number(issue.maximum))}`;
|
||
else
|
||
message = "Invalid input";
|
||
break;
|
||
case ZodIssueCode.custom:
|
||
message = `Invalid input`;
|
||
break;
|
||
case ZodIssueCode.invalid_intersection_types:
|
||
message = `Intersection results could not be merged`;
|
||
break;
|
||
case ZodIssueCode.not_multiple_of:
|
||
message = `Number must be a multiple of ${issue.multipleOf}`;
|
||
break;
|
||
case ZodIssueCode.not_finite:
|
||
message = "Number must be finite";
|
||
break;
|
||
default:
|
||
message = _ctx.defaultError;
|
||
util.assertNever(issue);
|
||
}
|
||
return { message };
|
||
};
|
||
|
||
let overrideErrorMap = errorMap;
|
||
function setErrorMap(map) {
|
||
overrideErrorMap = map;
|
||
}
|
||
function getErrorMap() {
|
||
return overrideErrorMap;
|
||
}
|
||
|
||
const makeIssue = (params) => {
|
||
const { data, path, errorMaps, issueData } = params;
|
||
const fullPath = [...path, ...(issueData.path || [])];
|
||
const fullIssue = {
|
||
...issueData,
|
||
path: fullPath,
|
||
};
|
||
if (issueData.message !== undefined) {
|
||
return {
|
||
...issueData,
|
||
path: fullPath,
|
||
message: issueData.message,
|
||
};
|
||
}
|
||
let errorMessage = "";
|
||
const maps = errorMaps
|
||
.filter((m) => !!m)
|
||
.slice()
|
||
.reverse();
|
||
for (const map of maps) {
|
||
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
|
||
}
|
||
return {
|
||
...issueData,
|
||
path: fullPath,
|
||
message: errorMessage,
|
||
};
|
||
};
|
||
const EMPTY_PATH = [];
|
||
function addIssueToContext(ctx, issueData) {
|
||
const overrideMap = getErrorMap();
|
||
const issue = makeIssue({
|
||
issueData: issueData,
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
errorMaps: [
|
||
ctx.common.contextualErrorMap, // contextual error map is first priority
|
||
ctx.schemaErrorMap, // then schema-bound map if available
|
||
overrideMap, // then global override map
|
||
overrideMap === errorMap ? undefined : errorMap, // then global default map
|
||
].filter((x) => !!x),
|
||
});
|
||
ctx.common.issues.push(issue);
|
||
}
|
||
class ParseStatus {
|
||
constructor() {
|
||
this.value = "valid";
|
||
}
|
||
dirty() {
|
||
if (this.value === "valid")
|
||
this.value = "dirty";
|
||
}
|
||
abort() {
|
||
if (this.value !== "aborted")
|
||
this.value = "aborted";
|
||
}
|
||
static mergeArray(status, results) {
|
||
const arrayValue = [];
|
||
for (const s of results) {
|
||
if (s.status === "aborted")
|
||
return INVALID;
|
||
if (s.status === "dirty")
|
||
status.dirty();
|
||
arrayValue.push(s.value);
|
||
}
|
||
return { status: status.value, value: arrayValue };
|
||
}
|
||
static async mergeObjectAsync(status, pairs) {
|
||
const syncPairs = [];
|
||
for (const pair of pairs) {
|
||
const key = await pair.key;
|
||
const value = await pair.value;
|
||
syncPairs.push({
|
||
key,
|
||
value,
|
||
});
|
||
}
|
||
return ParseStatus.mergeObjectSync(status, syncPairs);
|
||
}
|
||
static mergeObjectSync(status, pairs) {
|
||
const finalObject = {};
|
||
for (const pair of pairs) {
|
||
const { key, value } = pair;
|
||
if (key.status === "aborted")
|
||
return INVALID;
|
||
if (value.status === "aborted")
|
||
return INVALID;
|
||
if (key.status === "dirty")
|
||
status.dirty();
|
||
if (value.status === "dirty")
|
||
status.dirty();
|
||
if (key.value !== "__proto__" &&
|
||
(typeof value.value !== "undefined" || pair.alwaysSet)) {
|
||
finalObject[key.value] = value.value;
|
||
}
|
||
}
|
||
return { status: status.value, value: finalObject };
|
||
}
|
||
}
|
||
const INVALID = Object.freeze({
|
||
status: "aborted",
|
||
});
|
||
const DIRTY = (value) => ({ status: "dirty", value });
|
||
const OK = (value) => ({ status: "valid", value });
|
||
const isAborted = (x) => x.status === "aborted";
|
||
const isDirty = (x) => x.status === "dirty";
|
||
const isValid = (x) => x.status === "valid";
|
||
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
|
||
|
||
/******************************************************************************
|
||
Copyright (c) Microsoft Corporation.
|
||
|
||
Permission to use, copy, modify, and/or distribute this software for any
|
||
purpose with or without fee is hereby granted.
|
||
|
||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||
PERFORMANCE OF THIS SOFTWARE.
|
||
***************************************************************************** */
|
||
|
||
function lib_classPrivateFieldGet(receiver, state, kind, f) {
|
||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
||
}
|
||
|
||
function lib_classPrivateFieldSet(receiver, state, value, kind, f) {
|
||
if (kind === "m") throw new TypeError("Private method is not writable");
|
||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
||
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
||
}
|
||
|
||
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
||
var e = new Error(message);
|
||
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
||
};
|
||
|
||
var errorUtil;
|
||
(function (errorUtil) {
|
||
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
||
errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
|
||
})(errorUtil || (errorUtil = {}));
|
||
|
||
var _ZodEnum_cache, _ZodNativeEnum_cache;
|
||
class ParseInputLazyPath {
|
||
constructor(parent, value, path, key) {
|
||
this._cachedPath = [];
|
||
this.parent = parent;
|
||
this.data = value;
|
||
this._path = path;
|
||
this._key = key;
|
||
}
|
||
get path() {
|
||
if (!this._cachedPath.length) {
|
||
if (this._key instanceof Array) {
|
||
this._cachedPath.push(...this._path, ...this._key);
|
||
}
|
||
else {
|
||
this._cachedPath.push(...this._path, this._key);
|
||
}
|
||
}
|
||
return this._cachedPath;
|
||
}
|
||
}
|
||
const handleResult = (ctx, result) => {
|
||
if (isValid(result)) {
|
||
return { success: true, data: result.value };
|
||
}
|
||
else {
|
||
if (!ctx.common.issues.length) {
|
||
throw new Error("Validation failed but no issues detected.");
|
||
}
|
||
return {
|
||
success: false,
|
||
get error() {
|
||
if (this._error)
|
||
return this._error;
|
||
const error = new ZodError(ctx.common.issues);
|
||
this._error = error;
|
||
return this._error;
|
||
},
|
||
};
|
||
}
|
||
};
|
||
function processCreateParams(params) {
|
||
if (!params)
|
||
return {};
|
||
const { errorMap, invalid_type_error, required_error, description } = params;
|
||
if (errorMap && (invalid_type_error || required_error)) {
|
||
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
|
||
}
|
||
if (errorMap)
|
||
return { errorMap: errorMap, description };
|
||
const customMap = (iss, ctx) => {
|
||
var _a, _b;
|
||
const { message } = params;
|
||
if (iss.code === "invalid_enum_value") {
|
||
return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
|
||
}
|
||
if (typeof ctx.data === "undefined") {
|
||
return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
|
||
}
|
||
if (iss.code !== "invalid_type")
|
||
return { message: ctx.defaultError };
|
||
return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
|
||
};
|
||
return { errorMap: customMap, description };
|
||
}
|
||
class ZodType {
|
||
get description() {
|
||
return this._def.description;
|
||
}
|
||
_getType(input) {
|
||
return getParsedType(input.data);
|
||
}
|
||
_getOrReturnCtx(input, ctx) {
|
||
return (ctx || {
|
||
common: input.parent.common,
|
||
data: input.data,
|
||
parsedType: getParsedType(input.data),
|
||
schemaErrorMap: this._def.errorMap,
|
||
path: input.path,
|
||
parent: input.parent,
|
||
});
|
||
}
|
||
_processInputParams(input) {
|
||
return {
|
||
status: new ParseStatus(),
|
||
ctx: {
|
||
common: input.parent.common,
|
||
data: input.data,
|
||
parsedType: getParsedType(input.data),
|
||
schemaErrorMap: this._def.errorMap,
|
||
path: input.path,
|
||
parent: input.parent,
|
||
},
|
||
};
|
||
}
|
||
_parseSync(input) {
|
||
const result = this._parse(input);
|
||
if (isAsync(result)) {
|
||
throw new Error("Synchronous parse encountered promise.");
|
||
}
|
||
return result;
|
||
}
|
||
_parseAsync(input) {
|
||
const result = this._parse(input);
|
||
return Promise.resolve(result);
|
||
}
|
||
parse(data, params) {
|
||
const result = this.safeParse(data, params);
|
||
if (result.success)
|
||
return result.data;
|
||
throw result.error;
|
||
}
|
||
safeParse(data, params) {
|
||
var _a;
|
||
const ctx = {
|
||
common: {
|
||
issues: [],
|
||
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
|
||
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
|
||
},
|
||
path: (params === null || params === void 0 ? void 0 : params.path) || [],
|
||
schemaErrorMap: this._def.errorMap,
|
||
parent: null,
|
||
data,
|
||
parsedType: getParsedType(data),
|
||
};
|
||
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
|
||
return handleResult(ctx, result);
|
||
}
|
||
"~validate"(data) {
|
||
var _a, _b;
|
||
const ctx = {
|
||
common: {
|
||
issues: [],
|
||
async: !!this["~standard"].async,
|
||
},
|
||
path: [],
|
||
schemaErrorMap: this._def.errorMap,
|
||
parent: null,
|
||
data,
|
||
parsedType: getParsedType(data),
|
||
};
|
||
if (!this["~standard"].async) {
|
||
try {
|
||
const result = this._parseSync({ data, path: [], parent: ctx });
|
||
return isValid(result)
|
||
? {
|
||
value: result.value,
|
||
}
|
||
: {
|
||
issues: ctx.common.issues,
|
||
};
|
||
}
|
||
catch (err) {
|
||
if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
|
||
this["~standard"].async = true;
|
||
}
|
||
ctx.common = {
|
||
issues: [],
|
||
async: true,
|
||
};
|
||
}
|
||
}
|
||
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
|
||
? {
|
||
value: result.value,
|
||
}
|
||
: {
|
||
issues: ctx.common.issues,
|
||
});
|
||
}
|
||
async parseAsync(data, params) {
|
||
const result = await this.safeParseAsync(data, params);
|
||
if (result.success)
|
||
return result.data;
|
||
throw result.error;
|
||
}
|
||
async safeParseAsync(data, params) {
|
||
const ctx = {
|
||
common: {
|
||
issues: [],
|
||
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
|
||
async: true,
|
||
},
|
||
path: (params === null || params === void 0 ? void 0 : params.path) || [],
|
||
schemaErrorMap: this._def.errorMap,
|
||
parent: null,
|
||
data,
|
||
parsedType: getParsedType(data),
|
||
};
|
||
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
|
||
const result = await (isAsync(maybeAsyncResult)
|
||
? maybeAsyncResult
|
||
: Promise.resolve(maybeAsyncResult));
|
||
return handleResult(ctx, result);
|
||
}
|
||
refine(check, message) {
|
||
const getIssueProperties = (val) => {
|
||
if (typeof message === "string" || typeof message === "undefined") {
|
||
return { message };
|
||
}
|
||
else if (typeof message === "function") {
|
||
return message(val);
|
||
}
|
||
else {
|
||
return message;
|
||
}
|
||
};
|
||
return this._refinement((val, ctx) => {
|
||
const result = check(val);
|
||
const setError = () => ctx.addIssue({
|
||
code: ZodIssueCode.custom,
|
||
...getIssueProperties(val),
|
||
});
|
||
if (typeof Promise !== "undefined" && result instanceof Promise) {
|
||
return result.then((data) => {
|
||
if (!data) {
|
||
setError();
|
||
return false;
|
||
}
|
||
else {
|
||
return true;
|
||
}
|
||
});
|
||
}
|
||
if (!result) {
|
||
setError();
|
||
return false;
|
||
}
|
||
else {
|
||
return true;
|
||
}
|
||
});
|
||
}
|
||
refinement(check, refinementData) {
|
||
return this._refinement((val, ctx) => {
|
||
if (!check(val)) {
|
||
ctx.addIssue(typeof refinementData === "function"
|
||
? refinementData(val, ctx)
|
||
: refinementData);
|
||
return false;
|
||
}
|
||
else {
|
||
return true;
|
||
}
|
||
});
|
||
}
|
||
_refinement(refinement) {
|
||
return new ZodEffects({
|
||
schema: this,
|
||
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
||
effect: { type: "refinement", refinement },
|
||
});
|
||
}
|
||
superRefine(refinement) {
|
||
return this._refinement(refinement);
|
||
}
|
||
constructor(def) {
|
||
/** Alias of safeParseAsync */
|
||
this.spa = this.safeParseAsync;
|
||
this._def = def;
|
||
this.parse = this.parse.bind(this);
|
||
this.safeParse = this.safeParse.bind(this);
|
||
this.parseAsync = this.parseAsync.bind(this);
|
||
this.safeParseAsync = this.safeParseAsync.bind(this);
|
||
this.spa = this.spa.bind(this);
|
||
this.refine = this.refine.bind(this);
|
||
this.refinement = this.refinement.bind(this);
|
||
this.superRefine = this.superRefine.bind(this);
|
||
this.optional = this.optional.bind(this);
|
||
this.nullable = this.nullable.bind(this);
|
||
this.nullish = this.nullish.bind(this);
|
||
this.array = this.array.bind(this);
|
||
this.promise = this.promise.bind(this);
|
||
this.or = this.or.bind(this);
|
||
this.and = this.and.bind(this);
|
||
this.transform = this.transform.bind(this);
|
||
this.brand = this.brand.bind(this);
|
||
this.default = this.default.bind(this);
|
||
this.catch = this.catch.bind(this);
|
||
this.describe = this.describe.bind(this);
|
||
this.pipe = this.pipe.bind(this);
|
||
this.readonly = this.readonly.bind(this);
|
||
this.isNullable = this.isNullable.bind(this);
|
||
this.isOptional = this.isOptional.bind(this);
|
||
this["~standard"] = {
|
||
version: 1,
|
||
vendor: "zod",
|
||
validate: (data) => this["~validate"](data),
|
||
};
|
||
}
|
||
optional() {
|
||
return ZodOptional.create(this, this._def);
|
||
}
|
||
nullable() {
|
||
return ZodNullable.create(this, this._def);
|
||
}
|
||
nullish() {
|
||
return this.nullable().optional();
|
||
}
|
||
array() {
|
||
return ZodArray.create(this);
|
||
}
|
||
promise() {
|
||
return ZodPromise.create(this, this._def);
|
||
}
|
||
or(option) {
|
||
return ZodUnion.create([this, option], this._def);
|
||
}
|
||
and(incoming) {
|
||
return ZodIntersection.create(this, incoming, this._def);
|
||
}
|
||
transform(transform) {
|
||
return new ZodEffects({
|
||
...processCreateParams(this._def),
|
||
schema: this,
|
||
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
||
effect: { type: "transform", transform },
|
||
});
|
||
}
|
||
default(def) {
|
||
const defaultValueFunc = typeof def === "function" ? def : () => def;
|
||
return new ZodDefault({
|
||
...processCreateParams(this._def),
|
||
innerType: this,
|
||
defaultValue: defaultValueFunc,
|
||
typeName: ZodFirstPartyTypeKind.ZodDefault,
|
||
});
|
||
}
|
||
brand() {
|
||
return new ZodBranded({
|
||
typeName: ZodFirstPartyTypeKind.ZodBranded,
|
||
type: this,
|
||
...processCreateParams(this._def),
|
||
});
|
||
}
|
||
catch(def) {
|
||
const catchValueFunc = typeof def === "function" ? def : () => def;
|
||
return new ZodCatch({
|
||
...processCreateParams(this._def),
|
||
innerType: this,
|
||
catchValue: catchValueFunc,
|
||
typeName: ZodFirstPartyTypeKind.ZodCatch,
|
||
});
|
||
}
|
||
describe(description) {
|
||
const This = this.constructor;
|
||
return new This({
|
||
...this._def,
|
||
description,
|
||
});
|
||
}
|
||
pipe(target) {
|
||
return ZodPipeline.create(this, target);
|
||
}
|
||
readonly() {
|
||
return ZodReadonly.create(this);
|
||
}
|
||
isOptional() {
|
||
return this.safeParse(undefined).success;
|
||
}
|
||
isNullable() {
|
||
return this.safeParse(null).success;
|
||
}
|
||
}
|
||
const cuidRegex = /^c[^\s-]{8,}$/i;
|
||
const cuid2Regex = /^[0-9a-z]+$/;
|
||
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
|
||
// const uuidRegex =
|
||
// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
||
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
|
||
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
|
||
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
|
||
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
||
// from https://stackoverflow.com/a/46181/1550155
|
||
// old version: too slow, didn't support unicode
|
||
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
|
||
//old email regex
|
||
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
|
||
// eslint-disable-next-line
|
||
// const emailRegex =
|
||
// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
|
||
// const emailRegex =
|
||
// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
|
||
// const emailRegex =
|
||
// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
|
||
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
|
||
// const emailRegex =
|
||
// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
|
||
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
|
||
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
|
||
let emojiRegex;
|
||
// faster, simpler, safer
|
||
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
||
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
|
||
// const ipv6Regex =
|
||
// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
|
||
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
|
||
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
|
||
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
|
||
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
|
||
// https://base64.guru/standards/base64url
|
||
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
|
||
// simple
|
||
// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
|
||
// no leap year validation
|
||
// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
|
||
// with leap year validation
|
||
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
|
||
const dateRegex = new RegExp(`^${dateRegexSource}$`);
|
||
function timeRegexSource(args) {
|
||
// let regex = `\\d{2}:\\d{2}:\\d{2}`;
|
||
let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
|
||
if (args.precision) {
|
||
regex = `${regex}\\.\\d{${args.precision}}`;
|
||
}
|
||
else if (args.precision == null) {
|
||
regex = `${regex}(\\.\\d+)?`;
|
||
}
|
||
return regex;
|
||
}
|
||
function timeRegex(args) {
|
||
return new RegExp(`^${timeRegexSource(args)}$`);
|
||
}
|
||
// Adapted from https://stackoverflow.com/a/3143231
|
||
function datetimeRegex(args) {
|
||
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
|
||
const opts = [];
|
||
opts.push(args.local ? `Z?` : `Z`);
|
||
if (args.offset)
|
||
opts.push(`([+-]\\d{2}:?\\d{2})`);
|
||
regex = `${regex}(${opts.join("|")})`;
|
||
return new RegExp(`^${regex}$`);
|
||
}
|
||
function isValidIP(ip, version) {
|
||
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
|
||
return true;
|
||
}
|
||
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
function isValidJWT(jwt, alg) {
|
||
if (!jwtRegex.test(jwt))
|
||
return false;
|
||
try {
|
||
const [header] = jwt.split(".");
|
||
// Convert base64url to base64
|
||
const base64 = header
|
||
.replace(/-/g, "+")
|
||
.replace(/_/g, "/")
|
||
.padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
|
||
const decoded = JSON.parse(atob(base64));
|
||
if (typeof decoded !== "object" || decoded === null)
|
||
return false;
|
||
if (!decoded.typ || !decoded.alg)
|
||
return false;
|
||
if (alg && decoded.alg !== alg)
|
||
return false;
|
||
return true;
|
||
}
|
||
catch (_a) {
|
||
return false;
|
||
}
|
||
}
|
||
function isValidCidr(ip, version) {
|
||
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
|
||
return true;
|
||
}
|
||
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
class ZodString extends ZodType {
|
||
_parse(input) {
|
||
if (this._def.coerce) {
|
||
input.data = String(input.data);
|
||
}
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.string) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.string,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const status = new ParseStatus();
|
||
let ctx = undefined;
|
||
for (const check of this._def.checks) {
|
||
if (check.kind === "min") {
|
||
if (input.data.length < check.value) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: check.value,
|
||
type: "string",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "max") {
|
||
if (input.data.length > check.value) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: check.value,
|
||
type: "string",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "length") {
|
||
const tooBig = input.data.length > check.value;
|
||
const tooSmall = input.data.length < check.value;
|
||
if (tooBig || tooSmall) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
if (tooBig) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: check.value,
|
||
type: "string",
|
||
inclusive: true,
|
||
exact: true,
|
||
message: check.message,
|
||
});
|
||
}
|
||
else if (tooSmall) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: check.value,
|
||
type: "string",
|
||
inclusive: true,
|
||
exact: true,
|
||
message: check.message,
|
||
});
|
||
}
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "email") {
|
||
if (!emailRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "email",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "emoji") {
|
||
if (!emojiRegex) {
|
||
emojiRegex = new RegExp(_emojiRegex, "u");
|
||
}
|
||
if (!emojiRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "emoji",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "uuid") {
|
||
if (!uuidRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "uuid",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "nanoid") {
|
||
if (!nanoidRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "nanoid",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "cuid") {
|
||
if (!cuidRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "cuid",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "cuid2") {
|
||
if (!cuid2Regex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "cuid2",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "ulid") {
|
||
if (!ulidRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "ulid",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "url") {
|
||
try {
|
||
new URL(input.data);
|
||
}
|
||
catch (_a) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "url",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "regex") {
|
||
check.regex.lastIndex = 0;
|
||
const testResult = check.regex.test(input.data);
|
||
if (!testResult) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "regex",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "trim") {
|
||
input.data = input.data.trim();
|
||
}
|
||
else if (check.kind === "includes") {
|
||
if (!input.data.includes(check.value, check.position)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: { includes: check.value, position: check.position },
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "toLowerCase") {
|
||
input.data = input.data.toLowerCase();
|
||
}
|
||
else if (check.kind === "toUpperCase") {
|
||
input.data = input.data.toUpperCase();
|
||
}
|
||
else if (check.kind === "startsWith") {
|
||
if (!input.data.startsWith(check.value)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: { startsWith: check.value },
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "endsWith") {
|
||
if (!input.data.endsWith(check.value)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: { endsWith: check.value },
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "datetime") {
|
||
const regex = datetimeRegex(check);
|
||
if (!regex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: "datetime",
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "date") {
|
||
const regex = dateRegex;
|
||
if (!regex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: "date",
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "time") {
|
||
const regex = timeRegex(check);
|
||
if (!regex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_string,
|
||
validation: "time",
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "duration") {
|
||
if (!durationRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "duration",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "ip") {
|
||
if (!isValidIP(input.data, check.version)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "ip",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "jwt") {
|
||
if (!isValidJWT(input.data, check.alg)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "jwt",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "cidr") {
|
||
if (!isValidCidr(input.data, check.version)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "cidr",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "base64") {
|
||
if (!base64Regex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "base64",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "base64url") {
|
||
if (!base64urlRegex.test(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
validation: "base64url",
|
||
code: ZodIssueCode.invalid_string,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else {
|
||
util.assertNever(check);
|
||
}
|
||
}
|
||
return { status: status.value, value: input.data };
|
||
}
|
||
_regex(regex, validation, message) {
|
||
return this.refinement((data) => regex.test(data), {
|
||
validation,
|
||
code: ZodIssueCode.invalid_string,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
_addCheck(check) {
|
||
return new ZodString({
|
||
...this._def,
|
||
checks: [...this._def.checks, check],
|
||
});
|
||
}
|
||
email(message) {
|
||
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
|
||
}
|
||
url(message) {
|
||
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
|
||
}
|
||
emoji(message) {
|
||
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
|
||
}
|
||
uuid(message) {
|
||
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
|
||
}
|
||
nanoid(message) {
|
||
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
|
||
}
|
||
cuid(message) {
|
||
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
|
||
}
|
||
cuid2(message) {
|
||
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
|
||
}
|
||
ulid(message) {
|
||
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
|
||
}
|
||
base64(message) {
|
||
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
|
||
}
|
||
base64url(message) {
|
||
// base64url encoding is a modification of base64 that can safely be used in URLs and filenames
|
||
return this._addCheck({
|
||
kind: "base64url",
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
jwt(options) {
|
||
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
|
||
}
|
||
ip(options) {
|
||
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
|
||
}
|
||
cidr(options) {
|
||
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
|
||
}
|
||
datetime(options) {
|
||
var _a, _b;
|
||
if (typeof options === "string") {
|
||
return this._addCheck({
|
||
kind: "datetime",
|
||
precision: null,
|
||
offset: false,
|
||
local: false,
|
||
message: options,
|
||
});
|
||
}
|
||
return this._addCheck({
|
||
kind: "datetime",
|
||
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
|
||
offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
|
||
local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
|
||
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
|
||
});
|
||
}
|
||
date(message) {
|
||
return this._addCheck({ kind: "date", message });
|
||
}
|
||
time(options) {
|
||
if (typeof options === "string") {
|
||
return this._addCheck({
|
||
kind: "time",
|
||
precision: null,
|
||
message: options,
|
||
});
|
||
}
|
||
return this._addCheck({
|
||
kind: "time",
|
||
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
|
||
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
|
||
});
|
||
}
|
||
duration(message) {
|
||
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
|
||
}
|
||
regex(regex, message) {
|
||
return this._addCheck({
|
||
kind: "regex",
|
||
regex: regex,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
includes(value, options) {
|
||
return this._addCheck({
|
||
kind: "includes",
|
||
value: value,
|
||
position: options === null || options === void 0 ? void 0 : options.position,
|
||
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
|
||
});
|
||
}
|
||
startsWith(value, message) {
|
||
return this._addCheck({
|
||
kind: "startsWith",
|
||
value: value,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
endsWith(value, message) {
|
||
return this._addCheck({
|
||
kind: "endsWith",
|
||
value: value,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
min(minLength, message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: minLength,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
max(maxLength, message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: maxLength,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
length(len, message) {
|
||
return this._addCheck({
|
||
kind: "length",
|
||
value: len,
|
||
...errorUtil.errToObj(message),
|
||
});
|
||
}
|
||
/**
|
||
* Equivalent to `.min(1)`
|
||
*/
|
||
nonempty(message) {
|
||
return this.min(1, errorUtil.errToObj(message));
|
||
}
|
||
trim() {
|
||
return new ZodString({
|
||
...this._def,
|
||
checks: [...this._def.checks, { kind: "trim" }],
|
||
});
|
||
}
|
||
toLowerCase() {
|
||
return new ZodString({
|
||
...this._def,
|
||
checks: [...this._def.checks, { kind: "toLowerCase" }],
|
||
});
|
||
}
|
||
toUpperCase() {
|
||
return new ZodString({
|
||
...this._def,
|
||
checks: [...this._def.checks, { kind: "toUpperCase" }],
|
||
});
|
||
}
|
||
get isDatetime() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "datetime");
|
||
}
|
||
get isDate() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "date");
|
||
}
|
||
get isTime() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "time");
|
||
}
|
||
get isDuration() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "duration");
|
||
}
|
||
get isEmail() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "email");
|
||
}
|
||
get isURL() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "url");
|
||
}
|
||
get isEmoji() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "emoji");
|
||
}
|
||
get isUUID() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "uuid");
|
||
}
|
||
get isNANOID() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
|
||
}
|
||
get isCUID() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "cuid");
|
||
}
|
||
get isCUID2() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
|
||
}
|
||
get isULID() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "ulid");
|
||
}
|
||
get isIP() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "ip");
|
||
}
|
||
get isCIDR() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "cidr");
|
||
}
|
||
get isBase64() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "base64");
|
||
}
|
||
get isBase64url() {
|
||
// base64url encoding is a modification of base64 that can safely be used in URLs and filenames
|
||
return !!this._def.checks.find((ch) => ch.kind === "base64url");
|
||
}
|
||
get minLength() {
|
||
let min = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "min") {
|
||
if (min === null || ch.value > min)
|
||
min = ch.value;
|
||
}
|
||
}
|
||
return min;
|
||
}
|
||
get maxLength() {
|
||
let max = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "max") {
|
||
if (max === null || ch.value < max)
|
||
max = ch.value;
|
||
}
|
||
}
|
||
return max;
|
||
}
|
||
}
|
||
ZodString.create = (params) => {
|
||
var _a;
|
||
return new ZodString({
|
||
checks: [],
|
||
typeName: ZodFirstPartyTypeKind.ZodString,
|
||
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
|
||
function floatSafeRemainder(val, step) {
|
||
const valDecCount = (val.toString().split(".")[1] || "").length;
|
||
const stepDecCount = (step.toString().split(".")[1] || "").length;
|
||
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
|
||
const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
|
||
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
|
||
return (valInt % stepInt) / Math.pow(10, decCount);
|
||
}
|
||
class ZodNumber extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
this.min = this.gte;
|
||
this.max = this.lte;
|
||
this.step = this.multipleOf;
|
||
}
|
||
_parse(input) {
|
||
if (this._def.coerce) {
|
||
input.data = Number(input.data);
|
||
}
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.number) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.number,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
let ctx = undefined;
|
||
const status = new ParseStatus();
|
||
for (const check of this._def.checks) {
|
||
if (check.kind === "int") {
|
||
if (!util.isInteger(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: "integer",
|
||
received: "float",
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "min") {
|
||
const tooSmall = check.inclusive
|
||
? input.data < check.value
|
||
: input.data <= check.value;
|
||
if (tooSmall) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: check.value,
|
||
type: "number",
|
||
inclusive: check.inclusive,
|
||
exact: false,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "max") {
|
||
const tooBig = check.inclusive
|
||
? input.data > check.value
|
||
: input.data >= check.value;
|
||
if (tooBig) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: check.value,
|
||
type: "number",
|
||
inclusive: check.inclusive,
|
||
exact: false,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "multipleOf") {
|
||
if (floatSafeRemainder(input.data, check.value) !== 0) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.not_multiple_of,
|
||
multipleOf: check.value,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "finite") {
|
||
if (!Number.isFinite(input.data)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.not_finite,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else {
|
||
util.assertNever(check);
|
||
}
|
||
}
|
||
return { status: status.value, value: input.data };
|
||
}
|
||
gte(value, message) {
|
||
return this.setLimit("min", value, true, errorUtil.toString(message));
|
||
}
|
||
gt(value, message) {
|
||
return this.setLimit("min", value, false, errorUtil.toString(message));
|
||
}
|
||
lte(value, message) {
|
||
return this.setLimit("max", value, true, errorUtil.toString(message));
|
||
}
|
||
lt(value, message) {
|
||
return this.setLimit("max", value, false, errorUtil.toString(message));
|
||
}
|
||
setLimit(kind, value, inclusive, message) {
|
||
return new ZodNumber({
|
||
...this._def,
|
||
checks: [
|
||
...this._def.checks,
|
||
{
|
||
kind,
|
||
value,
|
||
inclusive,
|
||
message: errorUtil.toString(message),
|
||
},
|
||
],
|
||
});
|
||
}
|
||
_addCheck(check) {
|
||
return new ZodNumber({
|
||
...this._def,
|
||
checks: [...this._def.checks, check],
|
||
});
|
||
}
|
||
int(message) {
|
||
return this._addCheck({
|
||
kind: "int",
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
positive(message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: 0,
|
||
inclusive: false,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
negative(message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: 0,
|
||
inclusive: false,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
nonpositive(message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: 0,
|
||
inclusive: true,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
nonnegative(message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: 0,
|
||
inclusive: true,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
multipleOf(value, message) {
|
||
return this._addCheck({
|
||
kind: "multipleOf",
|
||
value: value,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
finite(message) {
|
||
return this._addCheck({
|
||
kind: "finite",
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
safe(message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
inclusive: true,
|
||
value: Number.MIN_SAFE_INTEGER,
|
||
message: errorUtil.toString(message),
|
||
})._addCheck({
|
||
kind: "max",
|
||
inclusive: true,
|
||
value: Number.MAX_SAFE_INTEGER,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
get minValue() {
|
||
let min = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "min") {
|
||
if (min === null || ch.value > min)
|
||
min = ch.value;
|
||
}
|
||
}
|
||
return min;
|
||
}
|
||
get maxValue() {
|
||
let max = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "max") {
|
||
if (max === null || ch.value < max)
|
||
max = ch.value;
|
||
}
|
||
}
|
||
return max;
|
||
}
|
||
get isInt() {
|
||
return !!this._def.checks.find((ch) => ch.kind === "int" ||
|
||
(ch.kind === "multipleOf" && util.isInteger(ch.value)));
|
||
}
|
||
get isFinite() {
|
||
let max = null, min = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "finite" ||
|
||
ch.kind === "int" ||
|
||
ch.kind === "multipleOf") {
|
||
return true;
|
||
}
|
||
else if (ch.kind === "min") {
|
||
if (min === null || ch.value > min)
|
||
min = ch.value;
|
||
}
|
||
else if (ch.kind === "max") {
|
||
if (max === null || ch.value < max)
|
||
max = ch.value;
|
||
}
|
||
}
|
||
return Number.isFinite(min) && Number.isFinite(max);
|
||
}
|
||
}
|
||
ZodNumber.create = (params) => {
|
||
return new ZodNumber({
|
||
checks: [],
|
||
typeName: ZodFirstPartyTypeKind.ZodNumber,
|
||
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodBigInt extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
this.min = this.gte;
|
||
this.max = this.lte;
|
||
}
|
||
_parse(input) {
|
||
if (this._def.coerce) {
|
||
try {
|
||
input.data = BigInt(input.data);
|
||
}
|
||
catch (_a) {
|
||
return this._getInvalidInput(input);
|
||
}
|
||
}
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.bigint) {
|
||
return this._getInvalidInput(input);
|
||
}
|
||
let ctx = undefined;
|
||
const status = new ParseStatus();
|
||
for (const check of this._def.checks) {
|
||
if (check.kind === "min") {
|
||
const tooSmall = check.inclusive
|
||
? input.data < check.value
|
||
: input.data <= check.value;
|
||
if (tooSmall) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
type: "bigint",
|
||
minimum: check.value,
|
||
inclusive: check.inclusive,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "max") {
|
||
const tooBig = check.inclusive
|
||
? input.data > check.value
|
||
: input.data >= check.value;
|
||
if (tooBig) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
type: "bigint",
|
||
maximum: check.value,
|
||
inclusive: check.inclusive,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "multipleOf") {
|
||
if (input.data % check.value !== BigInt(0)) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.not_multiple_of,
|
||
multipleOf: check.value,
|
||
message: check.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else {
|
||
util.assertNever(check);
|
||
}
|
||
}
|
||
return { status: status.value, value: input.data };
|
||
}
|
||
_getInvalidInput(input) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.bigint,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
gte(value, message) {
|
||
return this.setLimit("min", value, true, errorUtil.toString(message));
|
||
}
|
||
gt(value, message) {
|
||
return this.setLimit("min", value, false, errorUtil.toString(message));
|
||
}
|
||
lte(value, message) {
|
||
return this.setLimit("max", value, true, errorUtil.toString(message));
|
||
}
|
||
lt(value, message) {
|
||
return this.setLimit("max", value, false, errorUtil.toString(message));
|
||
}
|
||
setLimit(kind, value, inclusive, message) {
|
||
return new ZodBigInt({
|
||
...this._def,
|
||
checks: [
|
||
...this._def.checks,
|
||
{
|
||
kind,
|
||
value,
|
||
inclusive,
|
||
message: errorUtil.toString(message),
|
||
},
|
||
],
|
||
});
|
||
}
|
||
_addCheck(check) {
|
||
return new ZodBigInt({
|
||
...this._def,
|
||
checks: [...this._def.checks, check],
|
||
});
|
||
}
|
||
positive(message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: BigInt(0),
|
||
inclusive: false,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
negative(message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: BigInt(0),
|
||
inclusive: false,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
nonpositive(message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: BigInt(0),
|
||
inclusive: true,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
nonnegative(message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: BigInt(0),
|
||
inclusive: true,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
multipleOf(value, message) {
|
||
return this._addCheck({
|
||
kind: "multipleOf",
|
||
value,
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
get minValue() {
|
||
let min = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "min") {
|
||
if (min === null || ch.value > min)
|
||
min = ch.value;
|
||
}
|
||
}
|
||
return min;
|
||
}
|
||
get maxValue() {
|
||
let max = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "max") {
|
||
if (max === null || ch.value < max)
|
||
max = ch.value;
|
||
}
|
||
}
|
||
return max;
|
||
}
|
||
}
|
||
ZodBigInt.create = (params) => {
|
||
var _a;
|
||
return new ZodBigInt({
|
||
checks: [],
|
||
typeName: ZodFirstPartyTypeKind.ZodBigInt,
|
||
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodBoolean extends ZodType {
|
||
_parse(input) {
|
||
if (this._def.coerce) {
|
||
input.data = Boolean(input.data);
|
||
}
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.boolean) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.boolean,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodBoolean.create = (params) => {
|
||
return new ZodBoolean({
|
||
typeName: ZodFirstPartyTypeKind.ZodBoolean,
|
||
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodDate extends ZodType {
|
||
_parse(input) {
|
||
if (this._def.coerce) {
|
||
input.data = new Date(input.data);
|
||
}
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.date) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.date,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (isNaN(input.data.getTime())) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_date,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const status = new ParseStatus();
|
||
let ctx = undefined;
|
||
for (const check of this._def.checks) {
|
||
if (check.kind === "min") {
|
||
if (input.data.getTime() < check.value) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
message: check.message,
|
||
inclusive: true,
|
||
exact: false,
|
||
minimum: check.value,
|
||
type: "date",
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (check.kind === "max") {
|
||
if (input.data.getTime() > check.value) {
|
||
ctx = this._getOrReturnCtx(input, ctx);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
message: check.message,
|
||
inclusive: true,
|
||
exact: false,
|
||
maximum: check.value,
|
||
type: "date",
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else {
|
||
util.assertNever(check);
|
||
}
|
||
}
|
||
return {
|
||
status: status.value,
|
||
value: new Date(input.data.getTime()),
|
||
};
|
||
}
|
||
_addCheck(check) {
|
||
return new ZodDate({
|
||
...this._def,
|
||
checks: [...this._def.checks, check],
|
||
});
|
||
}
|
||
min(minDate, message) {
|
||
return this._addCheck({
|
||
kind: "min",
|
||
value: minDate.getTime(),
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
max(maxDate, message) {
|
||
return this._addCheck({
|
||
kind: "max",
|
||
value: maxDate.getTime(),
|
||
message: errorUtil.toString(message),
|
||
});
|
||
}
|
||
get minDate() {
|
||
let min = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "min") {
|
||
if (min === null || ch.value > min)
|
||
min = ch.value;
|
||
}
|
||
}
|
||
return min != null ? new Date(min) : null;
|
||
}
|
||
get maxDate() {
|
||
let max = null;
|
||
for (const ch of this._def.checks) {
|
||
if (ch.kind === "max") {
|
||
if (max === null || ch.value < max)
|
||
max = ch.value;
|
||
}
|
||
}
|
||
return max != null ? new Date(max) : null;
|
||
}
|
||
}
|
||
ZodDate.create = (params) => {
|
||
return new ZodDate({
|
||
checks: [],
|
||
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
|
||
typeName: ZodFirstPartyTypeKind.ZodDate,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodSymbol extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.symbol) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.symbol,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodSymbol.create = (params) => {
|
||
return new ZodSymbol({
|
||
typeName: ZodFirstPartyTypeKind.ZodSymbol,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodUndefined extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.undefined) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.undefined,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodUndefined.create = (params) => {
|
||
return new ZodUndefined({
|
||
typeName: ZodFirstPartyTypeKind.ZodUndefined,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodNull extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.null) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.null,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodNull.create = (params) => {
|
||
return new ZodNull({
|
||
typeName: ZodFirstPartyTypeKind.ZodNull,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodAny extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
// to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
|
||
this._any = true;
|
||
}
|
||
_parse(input) {
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodAny.create = (params) => {
|
||
return new ZodAny({
|
||
typeName: ZodFirstPartyTypeKind.ZodAny,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodUnknown extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
// required
|
||
this._unknown = true;
|
||
}
|
||
_parse(input) {
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodUnknown.create = (params) => {
|
||
return new ZodUnknown({
|
||
typeName: ZodFirstPartyTypeKind.ZodUnknown,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodNever extends ZodType {
|
||
_parse(input) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.never,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
}
|
||
ZodNever.create = (params) => {
|
||
return new ZodNever({
|
||
typeName: ZodFirstPartyTypeKind.ZodNever,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodVoid extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.undefined) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.void,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
}
|
||
ZodVoid.create = (params) => {
|
||
return new ZodVoid({
|
||
typeName: ZodFirstPartyTypeKind.ZodVoid,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodArray extends ZodType {
|
||
_parse(input) {
|
||
const { ctx, status } = this._processInputParams(input);
|
||
const def = this._def;
|
||
if (ctx.parsedType !== ZodParsedType.array) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.array,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (def.exactLength !== null) {
|
||
const tooBig = ctx.data.length > def.exactLength.value;
|
||
const tooSmall = ctx.data.length < def.exactLength.value;
|
||
if (tooBig || tooSmall) {
|
||
addIssueToContext(ctx, {
|
||
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
|
||
minimum: (tooSmall ? def.exactLength.value : undefined),
|
||
maximum: (tooBig ? def.exactLength.value : undefined),
|
||
type: "array",
|
||
inclusive: true,
|
||
exact: true,
|
||
message: def.exactLength.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
if (def.minLength !== null) {
|
||
if (ctx.data.length < def.minLength.value) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: def.minLength.value,
|
||
type: "array",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: def.minLength.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
if (def.maxLength !== null) {
|
||
if (ctx.data.length > def.maxLength.value) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: def.maxLength.value,
|
||
type: "array",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: def.maxLength.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
if (ctx.common.async) {
|
||
return Promise.all([...ctx.data].map((item, i) => {
|
||
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
||
})).then((result) => {
|
||
return ParseStatus.mergeArray(status, result);
|
||
});
|
||
}
|
||
const result = [...ctx.data].map((item, i) => {
|
||
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
||
});
|
||
return ParseStatus.mergeArray(status, result);
|
||
}
|
||
get element() {
|
||
return this._def.type;
|
||
}
|
||
min(minLength, message) {
|
||
return new ZodArray({
|
||
...this._def,
|
||
minLength: { value: minLength, message: errorUtil.toString(message) },
|
||
});
|
||
}
|
||
max(maxLength, message) {
|
||
return new ZodArray({
|
||
...this._def,
|
||
maxLength: { value: maxLength, message: errorUtil.toString(message) },
|
||
});
|
||
}
|
||
length(len, message) {
|
||
return new ZodArray({
|
||
...this._def,
|
||
exactLength: { value: len, message: errorUtil.toString(message) },
|
||
});
|
||
}
|
||
nonempty(message) {
|
||
return this.min(1, message);
|
||
}
|
||
}
|
||
ZodArray.create = (schema, params) => {
|
||
return new ZodArray({
|
||
type: schema,
|
||
minLength: null,
|
||
maxLength: null,
|
||
exactLength: null,
|
||
typeName: ZodFirstPartyTypeKind.ZodArray,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
function deepPartialify(schema) {
|
||
if (schema instanceof ZodObject) {
|
||
const newShape = {};
|
||
for (const key in schema.shape) {
|
||
const fieldSchema = schema.shape[key];
|
||
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
|
||
}
|
||
return new ZodObject({
|
||
...schema._def,
|
||
shape: () => newShape,
|
||
});
|
||
}
|
||
else if (schema instanceof ZodArray) {
|
||
return new ZodArray({
|
||
...schema._def,
|
||
type: deepPartialify(schema.element),
|
||
});
|
||
}
|
||
else if (schema instanceof ZodOptional) {
|
||
return ZodOptional.create(deepPartialify(schema.unwrap()));
|
||
}
|
||
else if (schema instanceof ZodNullable) {
|
||
return ZodNullable.create(deepPartialify(schema.unwrap()));
|
||
}
|
||
else if (schema instanceof ZodTuple) {
|
||
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
|
||
}
|
||
else {
|
||
return schema;
|
||
}
|
||
}
|
||
class ZodObject extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
this._cached = null;
|
||
/**
|
||
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
|
||
* If you want to pass through unknown properties, use `.passthrough()` instead.
|
||
*/
|
||
this.nonstrict = this.passthrough;
|
||
// extend<
|
||
// Augmentation extends ZodRawShape,
|
||
// NewOutput extends util.flatten<{
|
||
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
|
||
// ? Augmentation[k]["_output"]
|
||
// : k extends keyof Output
|
||
// ? Output[k]
|
||
// : never;
|
||
// }>,
|
||
// NewInput extends util.flatten<{
|
||
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
|
||
// ? Augmentation[k]["_input"]
|
||
// : k extends keyof Input
|
||
// ? Input[k]
|
||
// : never;
|
||
// }>
|
||
// >(
|
||
// augmentation: Augmentation
|
||
// ): ZodObject<
|
||
// extendShape<T, Augmentation>,
|
||
// UnknownKeys,
|
||
// Catchall,
|
||
// NewOutput,
|
||
// NewInput
|
||
// > {
|
||
// return new ZodObject({
|
||
// ...this._def,
|
||
// shape: () => ({
|
||
// ...this._def.shape(),
|
||
// ...augmentation,
|
||
// }),
|
||
// }) as any;
|
||
// }
|
||
/**
|
||
* @deprecated Use `.extend` instead
|
||
* */
|
||
this.augment = this.extend;
|
||
}
|
||
_getCached() {
|
||
if (this._cached !== null)
|
||
return this._cached;
|
||
const shape = this._def.shape();
|
||
const keys = util.objectKeys(shape);
|
||
return (this._cached = { shape, keys });
|
||
}
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.object) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.object,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const { status, ctx } = this._processInputParams(input);
|
||
const { shape, keys: shapeKeys } = this._getCached();
|
||
const extraKeys = [];
|
||
if (!(this._def.catchall instanceof ZodNever &&
|
||
this._def.unknownKeys === "strip")) {
|
||
for (const key in ctx.data) {
|
||
if (!shapeKeys.includes(key)) {
|
||
extraKeys.push(key);
|
||
}
|
||
}
|
||
}
|
||
const pairs = [];
|
||
for (const key of shapeKeys) {
|
||
const keyValidator = shape[key];
|
||
const value = ctx.data[key];
|
||
pairs.push({
|
||
key: { status: "valid", value: key },
|
||
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
|
||
alwaysSet: key in ctx.data,
|
||
});
|
||
}
|
||
if (this._def.catchall instanceof ZodNever) {
|
||
const unknownKeys = this._def.unknownKeys;
|
||
if (unknownKeys === "passthrough") {
|
||
for (const key of extraKeys) {
|
||
pairs.push({
|
||
key: { status: "valid", value: key },
|
||
value: { status: "valid", value: ctx.data[key] },
|
||
});
|
||
}
|
||
}
|
||
else if (unknownKeys === "strict") {
|
||
if (extraKeys.length > 0) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.unrecognized_keys,
|
||
keys: extraKeys,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
else if (unknownKeys === "strip") ;
|
||
else {
|
||
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
|
||
}
|
||
}
|
||
else {
|
||
// run catchall validation
|
||
const catchall = this._def.catchall;
|
||
for (const key of extraKeys) {
|
||
const value = ctx.data[key];
|
||
pairs.push({
|
||
key: { status: "valid", value: key },
|
||
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
|
||
),
|
||
alwaysSet: key in ctx.data,
|
||
});
|
||
}
|
||
}
|
||
if (ctx.common.async) {
|
||
return Promise.resolve()
|
||
.then(async () => {
|
||
const syncPairs = [];
|
||
for (const pair of pairs) {
|
||
const key = await pair.key;
|
||
const value = await pair.value;
|
||
syncPairs.push({
|
||
key,
|
||
value,
|
||
alwaysSet: pair.alwaysSet,
|
||
});
|
||
}
|
||
return syncPairs;
|
||
})
|
||
.then((syncPairs) => {
|
||
return ParseStatus.mergeObjectSync(status, syncPairs);
|
||
});
|
||
}
|
||
else {
|
||
return ParseStatus.mergeObjectSync(status, pairs);
|
||
}
|
||
}
|
||
get shape() {
|
||
return this._def.shape();
|
||
}
|
||
strict(message) {
|
||
errorUtil.errToObj;
|
||
return new ZodObject({
|
||
...this._def,
|
||
unknownKeys: "strict",
|
||
...(message !== undefined
|
||
? {
|
||
errorMap: (issue, ctx) => {
|
||
var _a, _b, _c, _d;
|
||
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
|
||
if (issue.code === "unrecognized_keys")
|
||
return {
|
||
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
|
||
};
|
||
return {
|
||
message: defaultError,
|
||
};
|
||
},
|
||
}
|
||
: {}),
|
||
});
|
||
}
|
||
strip() {
|
||
return new ZodObject({
|
||
...this._def,
|
||
unknownKeys: "strip",
|
||
});
|
||
}
|
||
passthrough() {
|
||
return new ZodObject({
|
||
...this._def,
|
||
unknownKeys: "passthrough",
|
||
});
|
||
}
|
||
// const AugmentFactory =
|
||
// <Def extends ZodObjectDef>(def: Def) =>
|
||
// <Augmentation extends ZodRawShape>(
|
||
// augmentation: Augmentation
|
||
// ): ZodObject<
|
||
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
|
||
// Def["unknownKeys"],
|
||
// Def["catchall"]
|
||
// > => {
|
||
// return new ZodObject({
|
||
// ...def,
|
||
// shape: () => ({
|
||
// ...def.shape(),
|
||
// ...augmentation,
|
||
// }),
|
||
// }) as any;
|
||
// };
|
||
extend(augmentation) {
|
||
return new ZodObject({
|
||
...this._def,
|
||
shape: () => ({
|
||
...this._def.shape(),
|
||
...augmentation,
|
||
}),
|
||
});
|
||
}
|
||
/**
|
||
* Prior to zod@1.0.12 there was a bug in the
|
||
* inferred type of merged objects. Please
|
||
* upgrade if you are experiencing issues.
|
||
*/
|
||
merge(merging) {
|
||
const merged = new ZodObject({
|
||
unknownKeys: merging._def.unknownKeys,
|
||
catchall: merging._def.catchall,
|
||
shape: () => ({
|
||
...this._def.shape(),
|
||
...merging._def.shape(),
|
||
}),
|
||
typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
});
|
||
return merged;
|
||
}
|
||
// merge<
|
||
// Incoming extends AnyZodObject,
|
||
// Augmentation extends Incoming["shape"],
|
||
// NewOutput extends {
|
||
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
|
||
// ? Augmentation[k]["_output"]
|
||
// : k extends keyof Output
|
||
// ? Output[k]
|
||
// : never;
|
||
// },
|
||
// NewInput extends {
|
||
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
|
||
// ? Augmentation[k]["_input"]
|
||
// : k extends keyof Input
|
||
// ? Input[k]
|
||
// : never;
|
||
// }
|
||
// >(
|
||
// merging: Incoming
|
||
// ): ZodObject<
|
||
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
|
||
// Incoming["_def"]["unknownKeys"],
|
||
// Incoming["_def"]["catchall"],
|
||
// NewOutput,
|
||
// NewInput
|
||
// > {
|
||
// const merged: any = new ZodObject({
|
||
// unknownKeys: merging._def.unknownKeys,
|
||
// catchall: merging._def.catchall,
|
||
// shape: () =>
|
||
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
|
||
// typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
// }) as any;
|
||
// return merged;
|
||
// }
|
||
setKey(key, schema) {
|
||
return this.augment({ [key]: schema });
|
||
}
|
||
// merge<Incoming extends AnyZodObject>(
|
||
// merging: Incoming
|
||
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
|
||
// ZodObject<
|
||
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
|
||
// Incoming["_def"]["unknownKeys"],
|
||
// Incoming["_def"]["catchall"]
|
||
// > {
|
||
// // const mergedShape = objectUtil.mergeShapes(
|
||
// // this._def.shape(),
|
||
// // merging._def.shape()
|
||
// // );
|
||
// const merged: any = new ZodObject({
|
||
// unknownKeys: merging._def.unknownKeys,
|
||
// catchall: merging._def.catchall,
|
||
// shape: () =>
|
||
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
|
||
// typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
// }) as any;
|
||
// return merged;
|
||
// }
|
||
catchall(index) {
|
||
return new ZodObject({
|
||
...this._def,
|
||
catchall: index,
|
||
});
|
||
}
|
||
pick(mask) {
|
||
const shape = {};
|
||
util.objectKeys(mask).forEach((key) => {
|
||
if (mask[key] && this.shape[key]) {
|
||
shape[key] = this.shape[key];
|
||
}
|
||
});
|
||
return new ZodObject({
|
||
...this._def,
|
||
shape: () => shape,
|
||
});
|
||
}
|
||
omit(mask) {
|
||
const shape = {};
|
||
util.objectKeys(this.shape).forEach((key) => {
|
||
if (!mask[key]) {
|
||
shape[key] = this.shape[key];
|
||
}
|
||
});
|
||
return new ZodObject({
|
||
...this._def,
|
||
shape: () => shape,
|
||
});
|
||
}
|
||
/**
|
||
* @deprecated
|
||
*/
|
||
deepPartial() {
|
||
return deepPartialify(this);
|
||
}
|
||
partial(mask) {
|
||
const newShape = {};
|
||
util.objectKeys(this.shape).forEach((key) => {
|
||
const fieldSchema = this.shape[key];
|
||
if (mask && !mask[key]) {
|
||
newShape[key] = fieldSchema;
|
||
}
|
||
else {
|
||
newShape[key] = fieldSchema.optional();
|
||
}
|
||
});
|
||
return new ZodObject({
|
||
...this._def,
|
||
shape: () => newShape,
|
||
});
|
||
}
|
||
required(mask) {
|
||
const newShape = {};
|
||
util.objectKeys(this.shape).forEach((key) => {
|
||
if (mask && !mask[key]) {
|
||
newShape[key] = this.shape[key];
|
||
}
|
||
else {
|
||
const fieldSchema = this.shape[key];
|
||
let newField = fieldSchema;
|
||
while (newField instanceof ZodOptional) {
|
||
newField = newField._def.innerType;
|
||
}
|
||
newShape[key] = newField;
|
||
}
|
||
});
|
||
return new ZodObject({
|
||
...this._def,
|
||
shape: () => newShape,
|
||
});
|
||
}
|
||
keyof() {
|
||
return createZodEnum(util.objectKeys(this.shape));
|
||
}
|
||
}
|
||
ZodObject.create = (shape, params) => {
|
||
return new ZodObject({
|
||
shape: () => shape,
|
||
unknownKeys: "strip",
|
||
catchall: ZodNever.create(),
|
||
typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
ZodObject.strictCreate = (shape, params) => {
|
||
return new ZodObject({
|
||
shape: () => shape,
|
||
unknownKeys: "strict",
|
||
catchall: ZodNever.create(),
|
||
typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
ZodObject.lazycreate = (shape, params) => {
|
||
return new ZodObject({
|
||
shape,
|
||
unknownKeys: "strip",
|
||
catchall: ZodNever.create(),
|
||
typeName: ZodFirstPartyTypeKind.ZodObject,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodUnion extends ZodType {
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
const options = this._def.options;
|
||
function handleResults(results) {
|
||
// return first issue-free validation if it exists
|
||
for (const result of results) {
|
||
if (result.result.status === "valid") {
|
||
return result.result;
|
||
}
|
||
}
|
||
for (const result of results) {
|
||
if (result.result.status === "dirty") {
|
||
// add issues from dirty option
|
||
ctx.common.issues.push(...result.ctx.common.issues);
|
||
return result.result;
|
||
}
|
||
}
|
||
// return invalid
|
||
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_union,
|
||
unionErrors,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (ctx.common.async) {
|
||
return Promise.all(options.map(async (option) => {
|
||
const childCtx = {
|
||
...ctx,
|
||
common: {
|
||
...ctx.common,
|
||
issues: [],
|
||
},
|
||
parent: null,
|
||
};
|
||
return {
|
||
result: await option._parseAsync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: childCtx,
|
||
}),
|
||
ctx: childCtx,
|
||
};
|
||
})).then(handleResults);
|
||
}
|
||
else {
|
||
let dirty = undefined;
|
||
const issues = [];
|
||
for (const option of options) {
|
||
const childCtx = {
|
||
...ctx,
|
||
common: {
|
||
...ctx.common,
|
||
issues: [],
|
||
},
|
||
parent: null,
|
||
};
|
||
const result = option._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: childCtx,
|
||
});
|
||
if (result.status === "valid") {
|
||
return result;
|
||
}
|
||
else if (result.status === "dirty" && !dirty) {
|
||
dirty = { result, ctx: childCtx };
|
||
}
|
||
if (childCtx.common.issues.length) {
|
||
issues.push(childCtx.common.issues);
|
||
}
|
||
}
|
||
if (dirty) {
|
||
ctx.common.issues.push(...dirty.ctx.common.issues);
|
||
return dirty.result;
|
||
}
|
||
const unionErrors = issues.map((issues) => new ZodError(issues));
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_union,
|
||
unionErrors,
|
||
});
|
||
return INVALID;
|
||
}
|
||
}
|
||
get options() {
|
||
return this._def.options;
|
||
}
|
||
}
|
||
ZodUnion.create = (types, params) => {
|
||
return new ZodUnion({
|
||
options: types,
|
||
typeName: ZodFirstPartyTypeKind.ZodUnion,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
/////////////////////////////////////////////////////
|
||
/////////////////////////////////////////////////////
|
||
////////// //////////
|
||
////////// ZodDiscriminatedUnion //////////
|
||
////////// //////////
|
||
/////////////////////////////////////////////////////
|
||
/////////////////////////////////////////////////////
|
||
const getDiscriminator = (type) => {
|
||
if (type instanceof ZodLazy) {
|
||
return getDiscriminator(type.schema);
|
||
}
|
||
else if (type instanceof ZodEffects) {
|
||
return getDiscriminator(type.innerType());
|
||
}
|
||
else if (type instanceof ZodLiteral) {
|
||
return [type.value];
|
||
}
|
||
else if (type instanceof ZodEnum) {
|
||
return type.options;
|
||
}
|
||
else if (type instanceof ZodNativeEnum) {
|
||
// eslint-disable-next-line ban/ban
|
||
return util.objectValues(type.enum);
|
||
}
|
||
else if (type instanceof ZodDefault) {
|
||
return getDiscriminator(type._def.innerType);
|
||
}
|
||
else if (type instanceof ZodUndefined) {
|
||
return [undefined];
|
||
}
|
||
else if (type instanceof ZodNull) {
|
||
return [null];
|
||
}
|
||
else if (type instanceof ZodOptional) {
|
||
return [undefined, ...getDiscriminator(type.unwrap())];
|
||
}
|
||
else if (type instanceof ZodNullable) {
|
||
return [null, ...getDiscriminator(type.unwrap())];
|
||
}
|
||
else if (type instanceof ZodBranded) {
|
||
return getDiscriminator(type.unwrap());
|
||
}
|
||
else if (type instanceof ZodReadonly) {
|
||
return getDiscriminator(type.unwrap());
|
||
}
|
||
else if (type instanceof ZodCatch) {
|
||
return getDiscriminator(type._def.innerType);
|
||
}
|
||
else {
|
||
return [];
|
||
}
|
||
};
|
||
class ZodDiscriminatedUnion extends ZodType {
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.object) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.object,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const discriminator = this.discriminator;
|
||
const discriminatorValue = ctx.data[discriminator];
|
||
const option = this.optionsMap.get(discriminatorValue);
|
||
if (!option) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_union_discriminator,
|
||
options: Array.from(this.optionsMap.keys()),
|
||
path: [discriminator],
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (ctx.common.async) {
|
||
return option._parseAsync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
else {
|
||
return option._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
}
|
||
get discriminator() {
|
||
return this._def.discriminator;
|
||
}
|
||
get options() {
|
||
return this._def.options;
|
||
}
|
||
get optionsMap() {
|
||
return this._def.optionsMap;
|
||
}
|
||
/**
|
||
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
|
||
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
|
||
* have a different value for each object in the union.
|
||
* @param discriminator the name of the discriminator property
|
||
* @param types an array of object schemas
|
||
* @param params
|
||
*/
|
||
static create(discriminator, options, params) {
|
||
// Get all the valid discriminator values
|
||
const optionsMap = new Map();
|
||
// try {
|
||
for (const type of options) {
|
||
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
|
||
if (!discriminatorValues.length) {
|
||
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
|
||
}
|
||
for (const value of discriminatorValues) {
|
||
if (optionsMap.has(value)) {
|
||
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
|
||
}
|
||
optionsMap.set(value, type);
|
||
}
|
||
}
|
||
return new ZodDiscriminatedUnion({
|
||
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
|
||
discriminator,
|
||
options,
|
||
optionsMap,
|
||
...processCreateParams(params),
|
||
});
|
||
}
|
||
}
|
||
function mergeValues(a, b) {
|
||
const aType = getParsedType(a);
|
||
const bType = getParsedType(b);
|
||
if (a === b) {
|
||
return { valid: true, data: a };
|
||
}
|
||
else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
|
||
const bKeys = util.objectKeys(b);
|
||
const sharedKeys = util
|
||
.objectKeys(a)
|
||
.filter((key) => bKeys.indexOf(key) !== -1);
|
||
const newObj = { ...a, ...b };
|
||
for (const key of sharedKeys) {
|
||
const sharedValue = mergeValues(a[key], b[key]);
|
||
if (!sharedValue.valid) {
|
||
return { valid: false };
|
||
}
|
||
newObj[key] = sharedValue.data;
|
||
}
|
||
return { valid: true, data: newObj };
|
||
}
|
||
else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
|
||
if (a.length !== b.length) {
|
||
return { valid: false };
|
||
}
|
||
const newArray = [];
|
||
for (let index = 0; index < a.length; index++) {
|
||
const itemA = a[index];
|
||
const itemB = b[index];
|
||
const sharedValue = mergeValues(itemA, itemB);
|
||
if (!sharedValue.valid) {
|
||
return { valid: false };
|
||
}
|
||
newArray.push(sharedValue.data);
|
||
}
|
||
return { valid: true, data: newArray };
|
||
}
|
||
else if (aType === ZodParsedType.date &&
|
||
bType === ZodParsedType.date &&
|
||
+a === +b) {
|
||
return { valid: true, data: a };
|
||
}
|
||
else {
|
||
return { valid: false };
|
||
}
|
||
}
|
||
class ZodIntersection extends ZodType {
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
const handleParsed = (parsedLeft, parsedRight) => {
|
||
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
|
||
return INVALID;
|
||
}
|
||
const merged = mergeValues(parsedLeft.value, parsedRight.value);
|
||
if (!merged.valid) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_intersection_types,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
|
||
status.dirty();
|
||
}
|
||
return { status: status.value, value: merged.data };
|
||
};
|
||
if (ctx.common.async) {
|
||
return Promise.all([
|
||
this._def.left._parseAsync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
}),
|
||
this._def.right._parseAsync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
}),
|
||
]).then(([left, right]) => handleParsed(left, right));
|
||
}
|
||
else {
|
||
return handleParsed(this._def.left._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
}), this._def.right._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
}));
|
||
}
|
||
}
|
||
}
|
||
ZodIntersection.create = (left, right, params) => {
|
||
return new ZodIntersection({
|
||
left: left,
|
||
right: right,
|
||
typeName: ZodFirstPartyTypeKind.ZodIntersection,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodTuple extends ZodType {
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.array) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.array,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (ctx.data.length < this._def.items.length) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: this._def.items.length,
|
||
inclusive: true,
|
||
exact: false,
|
||
type: "array",
|
||
});
|
||
return INVALID;
|
||
}
|
||
const rest = this._def.rest;
|
||
if (!rest && ctx.data.length > this._def.items.length) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: this._def.items.length,
|
||
inclusive: true,
|
||
exact: false,
|
||
type: "array",
|
||
});
|
||
status.dirty();
|
||
}
|
||
const items = [...ctx.data]
|
||
.map((item, itemIndex) => {
|
||
const schema = this._def.items[itemIndex] || this._def.rest;
|
||
if (!schema)
|
||
return null;
|
||
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
|
||
})
|
||
.filter((x) => !!x); // filter nulls
|
||
if (ctx.common.async) {
|
||
return Promise.all(items).then((results) => {
|
||
return ParseStatus.mergeArray(status, results);
|
||
});
|
||
}
|
||
else {
|
||
return ParseStatus.mergeArray(status, items);
|
||
}
|
||
}
|
||
get items() {
|
||
return this._def.items;
|
||
}
|
||
rest(rest) {
|
||
return new ZodTuple({
|
||
...this._def,
|
||
rest,
|
||
});
|
||
}
|
||
}
|
||
ZodTuple.create = (schemas, params) => {
|
||
if (!Array.isArray(schemas)) {
|
||
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
|
||
}
|
||
return new ZodTuple({
|
||
items: schemas,
|
||
typeName: ZodFirstPartyTypeKind.ZodTuple,
|
||
rest: null,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodRecord extends ZodType {
|
||
get keySchema() {
|
||
return this._def.keyType;
|
||
}
|
||
get valueSchema() {
|
||
return this._def.valueType;
|
||
}
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.object) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.object,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const pairs = [];
|
||
const keyType = this._def.keyType;
|
||
const valueType = this._def.valueType;
|
||
for (const key in ctx.data) {
|
||
pairs.push({
|
||
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
|
||
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
|
||
alwaysSet: key in ctx.data,
|
||
});
|
||
}
|
||
if (ctx.common.async) {
|
||
return ParseStatus.mergeObjectAsync(status, pairs);
|
||
}
|
||
else {
|
||
return ParseStatus.mergeObjectSync(status, pairs);
|
||
}
|
||
}
|
||
get element() {
|
||
return this._def.valueType;
|
||
}
|
||
static create(first, second, third) {
|
||
if (second instanceof ZodType) {
|
||
return new ZodRecord({
|
||
keyType: first,
|
||
valueType: second,
|
||
typeName: ZodFirstPartyTypeKind.ZodRecord,
|
||
...processCreateParams(third),
|
||
});
|
||
}
|
||
return new ZodRecord({
|
||
keyType: ZodString.create(),
|
||
valueType: first,
|
||
typeName: ZodFirstPartyTypeKind.ZodRecord,
|
||
...processCreateParams(second),
|
||
});
|
||
}
|
||
}
|
||
class ZodMap extends ZodType {
|
||
get keySchema() {
|
||
return this._def.keyType;
|
||
}
|
||
get valueSchema() {
|
||
return this._def.valueType;
|
||
}
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.map) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.map,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const keyType = this._def.keyType;
|
||
const valueType = this._def.valueType;
|
||
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
|
||
return {
|
||
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
|
||
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
|
||
};
|
||
});
|
||
if (ctx.common.async) {
|
||
const finalMap = new Map();
|
||
return Promise.resolve().then(async () => {
|
||
for (const pair of pairs) {
|
||
const key = await pair.key;
|
||
const value = await pair.value;
|
||
if (key.status === "aborted" || value.status === "aborted") {
|
||
return INVALID;
|
||
}
|
||
if (key.status === "dirty" || value.status === "dirty") {
|
||
status.dirty();
|
||
}
|
||
finalMap.set(key.value, value.value);
|
||
}
|
||
return { status: status.value, value: finalMap };
|
||
});
|
||
}
|
||
else {
|
||
const finalMap = new Map();
|
||
for (const pair of pairs) {
|
||
const key = pair.key;
|
||
const value = pair.value;
|
||
if (key.status === "aborted" || value.status === "aborted") {
|
||
return INVALID;
|
||
}
|
||
if (key.status === "dirty" || value.status === "dirty") {
|
||
status.dirty();
|
||
}
|
||
finalMap.set(key.value, value.value);
|
||
}
|
||
return { status: status.value, value: finalMap };
|
||
}
|
||
}
|
||
}
|
||
ZodMap.create = (keyType, valueType, params) => {
|
||
return new ZodMap({
|
||
valueType,
|
||
keyType,
|
||
typeName: ZodFirstPartyTypeKind.ZodMap,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodSet extends ZodType {
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.set) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.set,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const def = this._def;
|
||
if (def.minSize !== null) {
|
||
if (ctx.data.size < def.minSize.value) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_small,
|
||
minimum: def.minSize.value,
|
||
type: "set",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: def.minSize.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
if (def.maxSize !== null) {
|
||
if (ctx.data.size > def.maxSize.value) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.too_big,
|
||
maximum: def.maxSize.value,
|
||
type: "set",
|
||
inclusive: true,
|
||
exact: false,
|
||
message: def.maxSize.message,
|
||
});
|
||
status.dirty();
|
||
}
|
||
}
|
||
const valueType = this._def.valueType;
|
||
function finalizeSet(elements) {
|
||
const parsedSet = new Set();
|
||
for (const element of elements) {
|
||
if (element.status === "aborted")
|
||
return INVALID;
|
||
if (element.status === "dirty")
|
||
status.dirty();
|
||
parsedSet.add(element.value);
|
||
}
|
||
return { status: status.value, value: parsedSet };
|
||
}
|
||
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
|
||
if (ctx.common.async) {
|
||
return Promise.all(elements).then((elements) => finalizeSet(elements));
|
||
}
|
||
else {
|
||
return finalizeSet(elements);
|
||
}
|
||
}
|
||
min(minSize, message) {
|
||
return new ZodSet({
|
||
...this._def,
|
||
minSize: { value: minSize, message: errorUtil.toString(message) },
|
||
});
|
||
}
|
||
max(maxSize, message) {
|
||
return new ZodSet({
|
||
...this._def,
|
||
maxSize: { value: maxSize, message: errorUtil.toString(message) },
|
||
});
|
||
}
|
||
size(size, message) {
|
||
return this.min(size, message).max(size, message);
|
||
}
|
||
nonempty(message) {
|
||
return this.min(1, message);
|
||
}
|
||
}
|
||
ZodSet.create = (valueType, params) => {
|
||
return new ZodSet({
|
||
valueType,
|
||
minSize: null,
|
||
maxSize: null,
|
||
typeName: ZodFirstPartyTypeKind.ZodSet,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodFunction extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
this.validate = this.implement;
|
||
}
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.function) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.function,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
function makeArgsIssue(args, error) {
|
||
return makeIssue({
|
||
data: args,
|
||
path: ctx.path,
|
||
errorMaps: [
|
||
ctx.common.contextualErrorMap,
|
||
ctx.schemaErrorMap,
|
||
getErrorMap(),
|
||
errorMap,
|
||
].filter((x) => !!x),
|
||
issueData: {
|
||
code: ZodIssueCode.invalid_arguments,
|
||
argumentsError: error,
|
||
},
|
||
});
|
||
}
|
||
function makeReturnsIssue(returns, error) {
|
||
return makeIssue({
|
||
data: returns,
|
||
path: ctx.path,
|
||
errorMaps: [
|
||
ctx.common.contextualErrorMap,
|
||
ctx.schemaErrorMap,
|
||
getErrorMap(),
|
||
errorMap,
|
||
].filter((x) => !!x),
|
||
issueData: {
|
||
code: ZodIssueCode.invalid_return_type,
|
||
returnTypeError: error,
|
||
},
|
||
});
|
||
}
|
||
const params = { errorMap: ctx.common.contextualErrorMap };
|
||
const fn = ctx.data;
|
||
if (this._def.returns instanceof ZodPromise) {
|
||
// Would love a way to avoid disabling this rule, but we need
|
||
// an alias (using an arrow function was what caused 2651).
|
||
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
||
const me = this;
|
||
return OK(async function (...args) {
|
||
const error = new ZodError([]);
|
||
const parsedArgs = await me._def.args
|
||
.parseAsync(args, params)
|
||
.catch((e) => {
|
||
error.addIssue(makeArgsIssue(args, e));
|
||
throw error;
|
||
});
|
||
const result = await Reflect.apply(fn, this, parsedArgs);
|
||
const parsedReturns = await me._def.returns._def.type
|
||
.parseAsync(result, params)
|
||
.catch((e) => {
|
||
error.addIssue(makeReturnsIssue(result, e));
|
||
throw error;
|
||
});
|
||
return parsedReturns;
|
||
});
|
||
}
|
||
else {
|
||
// Would love a way to avoid disabling this rule, but we need
|
||
// an alias (using an arrow function was what caused 2651).
|
||
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
||
const me = this;
|
||
return OK(function (...args) {
|
||
const parsedArgs = me._def.args.safeParse(args, params);
|
||
if (!parsedArgs.success) {
|
||
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
|
||
}
|
||
const result = Reflect.apply(fn, this, parsedArgs.data);
|
||
const parsedReturns = me._def.returns.safeParse(result, params);
|
||
if (!parsedReturns.success) {
|
||
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
|
||
}
|
||
return parsedReturns.data;
|
||
});
|
||
}
|
||
}
|
||
parameters() {
|
||
return this._def.args;
|
||
}
|
||
returnType() {
|
||
return this._def.returns;
|
||
}
|
||
args(...items) {
|
||
return new ZodFunction({
|
||
...this._def,
|
||
args: ZodTuple.create(items).rest(ZodUnknown.create()),
|
||
});
|
||
}
|
||
returns(returnType) {
|
||
return new ZodFunction({
|
||
...this._def,
|
||
returns: returnType,
|
||
});
|
||
}
|
||
implement(func) {
|
||
const validatedFunc = this.parse(func);
|
||
return validatedFunc;
|
||
}
|
||
strictImplement(func) {
|
||
const validatedFunc = this.parse(func);
|
||
return validatedFunc;
|
||
}
|
||
static create(args, returns, params) {
|
||
return new ZodFunction({
|
||
args: (args
|
||
? args
|
||
: ZodTuple.create([]).rest(ZodUnknown.create())),
|
||
returns: returns || ZodUnknown.create(),
|
||
typeName: ZodFirstPartyTypeKind.ZodFunction,
|
||
...processCreateParams(params),
|
||
});
|
||
}
|
||
}
|
||
class ZodLazy extends ZodType {
|
||
get schema() {
|
||
return this._def.getter();
|
||
}
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
const lazySchema = this._def.getter();
|
||
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
|
||
}
|
||
}
|
||
ZodLazy.create = (getter, params) => {
|
||
return new ZodLazy({
|
||
getter: getter,
|
||
typeName: ZodFirstPartyTypeKind.ZodLazy,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodLiteral extends ZodType {
|
||
_parse(input) {
|
||
if (input.data !== this._def.value) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
received: ctx.data,
|
||
code: ZodIssueCode.invalid_literal,
|
||
expected: this._def.value,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return { status: "valid", value: input.data };
|
||
}
|
||
get value() {
|
||
return this._def.value;
|
||
}
|
||
}
|
||
ZodLiteral.create = (value, params) => {
|
||
return new ZodLiteral({
|
||
value: value,
|
||
typeName: ZodFirstPartyTypeKind.ZodLiteral,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
function createZodEnum(values, params) {
|
||
return new ZodEnum({
|
||
values,
|
||
typeName: ZodFirstPartyTypeKind.ZodEnum,
|
||
...processCreateParams(params),
|
||
});
|
||
}
|
||
class ZodEnum extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
_ZodEnum_cache.set(this, void 0);
|
||
}
|
||
_parse(input) {
|
||
if (typeof input.data !== "string") {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
const expectedValues = this._def.values;
|
||
addIssueToContext(ctx, {
|
||
expected: util.joinValues(expectedValues),
|
||
received: ctx.parsedType,
|
||
code: ZodIssueCode.invalid_type,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
|
||
lib_classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
|
||
}
|
||
if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
const expectedValues = this._def.values;
|
||
addIssueToContext(ctx, {
|
||
received: ctx.data,
|
||
code: ZodIssueCode.invalid_enum_value,
|
||
options: expectedValues,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
get options() {
|
||
return this._def.values;
|
||
}
|
||
get enum() {
|
||
const enumValues = {};
|
||
for (const val of this._def.values) {
|
||
enumValues[val] = val;
|
||
}
|
||
return enumValues;
|
||
}
|
||
get Values() {
|
||
const enumValues = {};
|
||
for (const val of this._def.values) {
|
||
enumValues[val] = val;
|
||
}
|
||
return enumValues;
|
||
}
|
||
get Enum() {
|
||
const enumValues = {};
|
||
for (const val of this._def.values) {
|
||
enumValues[val] = val;
|
||
}
|
||
return enumValues;
|
||
}
|
||
extract(values, newDef = this._def) {
|
||
return ZodEnum.create(values, {
|
||
...this._def,
|
||
...newDef,
|
||
});
|
||
}
|
||
exclude(values, newDef = this._def) {
|
||
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
|
||
...this._def,
|
||
...newDef,
|
||
});
|
||
}
|
||
}
|
||
_ZodEnum_cache = new WeakMap();
|
||
ZodEnum.create = createZodEnum;
|
||
class ZodNativeEnum extends ZodType {
|
||
constructor() {
|
||
super(...arguments);
|
||
_ZodNativeEnum_cache.set(this, void 0);
|
||
}
|
||
_parse(input) {
|
||
const nativeEnumValues = util.getValidEnumValues(this._def.values);
|
||
const ctx = this._getOrReturnCtx(input);
|
||
if (ctx.parsedType !== ZodParsedType.string &&
|
||
ctx.parsedType !== ZodParsedType.number) {
|
||
const expectedValues = util.objectValues(nativeEnumValues);
|
||
addIssueToContext(ctx, {
|
||
expected: util.joinValues(expectedValues),
|
||
received: ctx.parsedType,
|
||
code: ZodIssueCode.invalid_type,
|
||
});
|
||
return INVALID;
|
||
}
|
||
if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
|
||
lib_classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
|
||
}
|
||
if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
|
||
const expectedValues = util.objectValues(nativeEnumValues);
|
||
addIssueToContext(ctx, {
|
||
received: ctx.data,
|
||
code: ZodIssueCode.invalid_enum_value,
|
||
options: expectedValues,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return OK(input.data);
|
||
}
|
||
get enum() {
|
||
return this._def.values;
|
||
}
|
||
}
|
||
_ZodNativeEnum_cache = new WeakMap();
|
||
ZodNativeEnum.create = (values, params) => {
|
||
return new ZodNativeEnum({
|
||
values: values,
|
||
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodPromise extends ZodType {
|
||
unwrap() {
|
||
return this._def.type;
|
||
}
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
if (ctx.parsedType !== ZodParsedType.promise &&
|
||
ctx.common.async === false) {
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.promise,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
const promisified = ctx.parsedType === ZodParsedType.promise
|
||
? ctx.data
|
||
: Promise.resolve(ctx.data);
|
||
return OK(promisified.then((data) => {
|
||
return this._def.type.parseAsync(data, {
|
||
path: ctx.path,
|
||
errorMap: ctx.common.contextualErrorMap,
|
||
});
|
||
}));
|
||
}
|
||
}
|
||
ZodPromise.create = (schema, params) => {
|
||
return new ZodPromise({
|
||
type: schema,
|
||
typeName: ZodFirstPartyTypeKind.ZodPromise,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodEffects extends ZodType {
|
||
innerType() {
|
||
return this._def.schema;
|
||
}
|
||
sourceType() {
|
||
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
|
||
? this._def.schema.sourceType()
|
||
: this._def.schema;
|
||
}
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
const effect = this._def.effect || null;
|
||
const checkCtx = {
|
||
addIssue: (arg) => {
|
||
addIssueToContext(ctx, arg);
|
||
if (arg.fatal) {
|
||
status.abort();
|
||
}
|
||
else {
|
||
status.dirty();
|
||
}
|
||
},
|
||
get path() {
|
||
return ctx.path;
|
||
},
|
||
};
|
||
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
|
||
if (effect.type === "preprocess") {
|
||
const processed = effect.transform(ctx.data, checkCtx);
|
||
if (ctx.common.async) {
|
||
return Promise.resolve(processed).then(async (processed) => {
|
||
if (status.value === "aborted")
|
||
return INVALID;
|
||
const result = await this._def.schema._parseAsync({
|
||
data: processed,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (result.status === "aborted")
|
||
return INVALID;
|
||
if (result.status === "dirty")
|
||
return DIRTY(result.value);
|
||
if (status.value === "dirty")
|
||
return DIRTY(result.value);
|
||
return result;
|
||
});
|
||
}
|
||
else {
|
||
if (status.value === "aborted")
|
||
return INVALID;
|
||
const result = this._def.schema._parseSync({
|
||
data: processed,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (result.status === "aborted")
|
||
return INVALID;
|
||
if (result.status === "dirty")
|
||
return DIRTY(result.value);
|
||
if (status.value === "dirty")
|
||
return DIRTY(result.value);
|
||
return result;
|
||
}
|
||
}
|
||
if (effect.type === "refinement") {
|
||
const executeRefinement = (acc) => {
|
||
const result = effect.refinement(acc, checkCtx);
|
||
if (ctx.common.async) {
|
||
return Promise.resolve(result);
|
||
}
|
||
if (result instanceof Promise) {
|
||
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
|
||
}
|
||
return acc;
|
||
};
|
||
if (ctx.common.async === false) {
|
||
const inner = this._def.schema._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (inner.status === "aborted")
|
||
return INVALID;
|
||
if (inner.status === "dirty")
|
||
status.dirty();
|
||
// return value is ignored
|
||
executeRefinement(inner.value);
|
||
return { status: status.value, value: inner.value };
|
||
}
|
||
else {
|
||
return this._def.schema
|
||
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
|
||
.then((inner) => {
|
||
if (inner.status === "aborted")
|
||
return INVALID;
|
||
if (inner.status === "dirty")
|
||
status.dirty();
|
||
return executeRefinement(inner.value).then(() => {
|
||
return { status: status.value, value: inner.value };
|
||
});
|
||
});
|
||
}
|
||
}
|
||
if (effect.type === "transform") {
|
||
if (ctx.common.async === false) {
|
||
const base = this._def.schema._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (!isValid(base))
|
||
return base;
|
||
const result = effect.transform(base.value, checkCtx);
|
||
if (result instanceof Promise) {
|
||
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
|
||
}
|
||
return { status: status.value, value: result };
|
||
}
|
||
else {
|
||
return this._def.schema
|
||
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
|
||
.then((base) => {
|
||
if (!isValid(base))
|
||
return base;
|
||
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
|
||
});
|
||
}
|
||
}
|
||
util.assertNever(effect);
|
||
}
|
||
}
|
||
ZodEffects.create = (schema, effect, params) => {
|
||
return new ZodEffects({
|
||
schema,
|
||
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
||
effect,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
|
||
return new ZodEffects({
|
||
schema,
|
||
effect: { type: "preprocess", transform: preprocess },
|
||
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodOptional extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType === ZodParsedType.undefined) {
|
||
return OK(undefined);
|
||
}
|
||
return this._def.innerType._parse(input);
|
||
}
|
||
unwrap() {
|
||
return this._def.innerType;
|
||
}
|
||
}
|
||
ZodOptional.create = (type, params) => {
|
||
return new ZodOptional({
|
||
innerType: type,
|
||
typeName: ZodFirstPartyTypeKind.ZodOptional,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodNullable extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType === ZodParsedType.null) {
|
||
return OK(null);
|
||
}
|
||
return this._def.innerType._parse(input);
|
||
}
|
||
unwrap() {
|
||
return this._def.innerType;
|
||
}
|
||
}
|
||
ZodNullable.create = (type, params) => {
|
||
return new ZodNullable({
|
||
innerType: type,
|
||
typeName: ZodFirstPartyTypeKind.ZodNullable,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodDefault extends ZodType {
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
let data = ctx.data;
|
||
if (ctx.parsedType === ZodParsedType.undefined) {
|
||
data = this._def.defaultValue();
|
||
}
|
||
return this._def.innerType._parse({
|
||
data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
removeDefault() {
|
||
return this._def.innerType;
|
||
}
|
||
}
|
||
ZodDefault.create = (type, params) => {
|
||
return new ZodDefault({
|
||
innerType: type,
|
||
typeName: ZodFirstPartyTypeKind.ZodDefault,
|
||
defaultValue: typeof params.default === "function"
|
||
? params.default
|
||
: () => params.default,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodCatch extends ZodType {
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
// newCtx is used to not collect issues from inner types in ctx
|
||
const newCtx = {
|
||
...ctx,
|
||
common: {
|
||
...ctx.common,
|
||
issues: [],
|
||
},
|
||
};
|
||
const result = this._def.innerType._parse({
|
||
data: newCtx.data,
|
||
path: newCtx.path,
|
||
parent: {
|
||
...newCtx,
|
||
},
|
||
});
|
||
if (isAsync(result)) {
|
||
return result.then((result) => {
|
||
return {
|
||
status: "valid",
|
||
value: result.status === "valid"
|
||
? result.value
|
||
: this._def.catchValue({
|
||
get error() {
|
||
return new ZodError(newCtx.common.issues);
|
||
},
|
||
input: newCtx.data,
|
||
}),
|
||
};
|
||
});
|
||
}
|
||
else {
|
||
return {
|
||
status: "valid",
|
||
value: result.status === "valid"
|
||
? result.value
|
||
: this._def.catchValue({
|
||
get error() {
|
||
return new ZodError(newCtx.common.issues);
|
||
},
|
||
input: newCtx.data,
|
||
}),
|
||
};
|
||
}
|
||
}
|
||
removeCatch() {
|
||
return this._def.innerType;
|
||
}
|
||
}
|
||
ZodCatch.create = (type, params) => {
|
||
return new ZodCatch({
|
||
innerType: type,
|
||
typeName: ZodFirstPartyTypeKind.ZodCatch,
|
||
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
class ZodNaN extends ZodType {
|
||
_parse(input) {
|
||
const parsedType = this._getType(input);
|
||
if (parsedType !== ZodParsedType.nan) {
|
||
const ctx = this._getOrReturnCtx(input);
|
||
addIssueToContext(ctx, {
|
||
code: ZodIssueCode.invalid_type,
|
||
expected: ZodParsedType.nan,
|
||
received: ctx.parsedType,
|
||
});
|
||
return INVALID;
|
||
}
|
||
return { status: "valid", value: input.data };
|
||
}
|
||
}
|
||
ZodNaN.create = (params) => {
|
||
return new ZodNaN({
|
||
typeName: ZodFirstPartyTypeKind.ZodNaN,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
const BRAND = Symbol("zod_brand");
|
||
class ZodBranded extends ZodType {
|
||
_parse(input) {
|
||
const { ctx } = this._processInputParams(input);
|
||
const data = ctx.data;
|
||
return this._def.type._parse({
|
||
data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
unwrap() {
|
||
return this._def.type;
|
||
}
|
||
}
|
||
class ZodPipeline extends ZodType {
|
||
_parse(input) {
|
||
const { status, ctx } = this._processInputParams(input);
|
||
if (ctx.common.async) {
|
||
const handleAsync = async () => {
|
||
const inResult = await this._def.in._parseAsync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (inResult.status === "aborted")
|
||
return INVALID;
|
||
if (inResult.status === "dirty") {
|
||
status.dirty();
|
||
return DIRTY(inResult.value);
|
||
}
|
||
else {
|
||
return this._def.out._parseAsync({
|
||
data: inResult.value,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
};
|
||
return handleAsync();
|
||
}
|
||
else {
|
||
const inResult = this._def.in._parseSync({
|
||
data: ctx.data,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
if (inResult.status === "aborted")
|
||
return INVALID;
|
||
if (inResult.status === "dirty") {
|
||
status.dirty();
|
||
return {
|
||
status: "dirty",
|
||
value: inResult.value,
|
||
};
|
||
}
|
||
else {
|
||
return this._def.out._parseSync({
|
||
data: inResult.value,
|
||
path: ctx.path,
|
||
parent: ctx,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
static create(a, b) {
|
||
return new ZodPipeline({
|
||
in: a,
|
||
out: b,
|
||
typeName: ZodFirstPartyTypeKind.ZodPipeline,
|
||
});
|
||
}
|
||
}
|
||
class ZodReadonly extends ZodType {
|
||
_parse(input) {
|
||
const result = this._def.innerType._parse(input);
|
||
const freeze = (data) => {
|
||
if (isValid(data)) {
|
||
data.value = Object.freeze(data.value);
|
||
}
|
||
return data;
|
||
};
|
||
return isAsync(result)
|
||
? result.then((data) => freeze(data))
|
||
: freeze(result);
|
||
}
|
||
unwrap() {
|
||
return this._def.innerType;
|
||
}
|
||
}
|
||
ZodReadonly.create = (type, params) => {
|
||
return new ZodReadonly({
|
||
innerType: type,
|
||
typeName: ZodFirstPartyTypeKind.ZodReadonly,
|
||
...processCreateParams(params),
|
||
});
|
||
};
|
||
////////////////////////////////////////
|
||
////////////////////////////////////////
|
||
////////// //////////
|
||
////////// z.custom //////////
|
||
////////// //////////
|
||
////////////////////////////////////////
|
||
////////////////////////////////////////
|
||
function cleanParams(params, data) {
|
||
const p = typeof params === "function"
|
||
? params(data)
|
||
: typeof params === "string"
|
||
? { message: params }
|
||
: params;
|
||
const p2 = typeof p === "string" ? { message: p } : p;
|
||
return p2;
|
||
}
|
||
function custom(check, _params = {},
|
||
/**
|
||
* @deprecated
|
||
*
|
||
* Pass `fatal` into the params object instead:
|
||
*
|
||
* ```ts
|
||
* z.string().custom((val) => val.length > 5, { fatal: false })
|
||
* ```
|
||
*
|
||
*/
|
||
fatal) {
|
||
if (check)
|
||
return ZodAny.create().superRefine((data, ctx) => {
|
||
var _a, _b;
|
||
const r = check(data);
|
||
if (r instanceof Promise) {
|
||
return r.then((r) => {
|
||
var _a, _b;
|
||
if (!r) {
|
||
const params = cleanParams(_params, data);
|
||
const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
|
||
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
|
||
}
|
||
});
|
||
}
|
||
if (!r) {
|
||
const params = cleanParams(_params, data);
|
||
const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
|
||
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
|
||
}
|
||
return;
|
||
});
|
||
return ZodAny.create();
|
||
}
|
||
const late = {
|
||
object: ZodObject.lazycreate,
|
||
};
|
||
var ZodFirstPartyTypeKind;
|
||
(function (ZodFirstPartyTypeKind) {
|
||
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
|
||
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
|
||
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
|
||
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
|
||
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
|
||
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
|
||
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
|
||
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
|
||
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
|
||
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
|
||
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
|
||
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
|
||
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
|
||
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
|
||
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
|
||
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
|
||
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
|
||
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
|
||
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
|
||
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
|
||
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
|
||
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
|
||
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
|
||
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
|
||
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
|
||
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
|
||
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
|
||
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
|
||
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
|
||
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
|
||
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
|
||
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
|
||
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
|
||
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
|
||
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
|
||
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
|
||
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
||
const instanceOfType = (
|
||
// const instanceOfType = <T extends new (...args: any[]) => any>(
|
||
cls, params = {
|
||
message: `Input not instance of ${cls.name}`,
|
||
}) => custom((data) => data instanceof cls, params);
|
||
const stringType = ZodString.create;
|
||
const numberType = ZodNumber.create;
|
||
const nanType = ZodNaN.create;
|
||
const bigIntType = ZodBigInt.create;
|
||
const booleanType = ZodBoolean.create;
|
||
const dateType = ZodDate.create;
|
||
const symbolType = ZodSymbol.create;
|
||
const undefinedType = ZodUndefined.create;
|
||
const nullType = ZodNull.create;
|
||
const anyType = ZodAny.create;
|
||
const unknownType = ZodUnknown.create;
|
||
const neverType = ZodNever.create;
|
||
const voidType = ZodVoid.create;
|
||
const arrayType = ZodArray.create;
|
||
const objectType = ZodObject.create;
|
||
const strictObjectType = ZodObject.strictCreate;
|
||
const unionType = ZodUnion.create;
|
||
const discriminatedUnionType = ZodDiscriminatedUnion.create;
|
||
const intersectionType = ZodIntersection.create;
|
||
const tupleType = ZodTuple.create;
|
||
const recordType = ZodRecord.create;
|
||
const mapType = ZodMap.create;
|
||
const setType = ZodSet.create;
|
||
const functionType = ZodFunction.create;
|
||
const lazyType = ZodLazy.create;
|
||
const literalType = ZodLiteral.create;
|
||
const enumType = ZodEnum.create;
|
||
const nativeEnumType = ZodNativeEnum.create;
|
||
const promiseType = ZodPromise.create;
|
||
const effectsType = ZodEffects.create;
|
||
const optionalType = ZodOptional.create;
|
||
const nullableType = ZodNullable.create;
|
||
const preprocessType = ZodEffects.createWithPreprocess;
|
||
const pipelineType = ZodPipeline.create;
|
||
const ostring = () => stringType().optional();
|
||
const onumber = () => numberType().optional();
|
||
const oboolean = () => booleanType().optional();
|
||
const coerce = {
|
||
string: ((arg) => ZodString.create({ ...arg, coerce: true })),
|
||
number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
|
||
boolean: ((arg) => ZodBoolean.create({
|
||
...arg,
|
||
coerce: true,
|
||
})),
|
||
bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
|
||
date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
|
||
};
|
||
const NEVER = INVALID;
|
||
|
||
var z = /*#__PURE__*/Object.freeze({
|
||
__proto__: null,
|
||
defaultErrorMap: errorMap,
|
||
setErrorMap: setErrorMap,
|
||
getErrorMap: getErrorMap,
|
||
makeIssue: makeIssue,
|
||
EMPTY_PATH: EMPTY_PATH,
|
||
addIssueToContext: addIssueToContext,
|
||
ParseStatus: ParseStatus,
|
||
INVALID: INVALID,
|
||
DIRTY: DIRTY,
|
||
OK: OK,
|
||
isAborted: isAborted,
|
||
isDirty: isDirty,
|
||
isValid: isValid,
|
||
isAsync: isAsync,
|
||
get util () { return util; },
|
||
get objectUtil () { return objectUtil; },
|
||
ZodParsedType: ZodParsedType,
|
||
getParsedType: getParsedType,
|
||
ZodType: ZodType,
|
||
datetimeRegex: datetimeRegex,
|
||
ZodString: ZodString,
|
||
ZodNumber: ZodNumber,
|
||
ZodBigInt: ZodBigInt,
|
||
ZodBoolean: ZodBoolean,
|
||
ZodDate: ZodDate,
|
||
ZodSymbol: ZodSymbol,
|
||
ZodUndefined: ZodUndefined,
|
||
ZodNull: ZodNull,
|
||
ZodAny: ZodAny,
|
||
ZodUnknown: ZodUnknown,
|
||
ZodNever: ZodNever,
|
||
ZodVoid: ZodVoid,
|
||
ZodArray: ZodArray,
|
||
ZodObject: ZodObject,
|
||
ZodUnion: ZodUnion,
|
||
ZodDiscriminatedUnion: ZodDiscriminatedUnion,
|
||
ZodIntersection: ZodIntersection,
|
||
ZodTuple: ZodTuple,
|
||
ZodRecord: ZodRecord,
|
||
ZodMap: ZodMap,
|
||
ZodSet: ZodSet,
|
||
ZodFunction: ZodFunction,
|
||
ZodLazy: ZodLazy,
|
||
ZodLiteral: ZodLiteral,
|
||
ZodEnum: ZodEnum,
|
||
ZodNativeEnum: ZodNativeEnum,
|
||
ZodPromise: ZodPromise,
|
||
ZodEffects: ZodEffects,
|
||
ZodTransformer: ZodEffects,
|
||
ZodOptional: ZodOptional,
|
||
ZodNullable: ZodNullable,
|
||
ZodDefault: ZodDefault,
|
||
ZodCatch: ZodCatch,
|
||
ZodNaN: ZodNaN,
|
||
BRAND: BRAND,
|
||
ZodBranded: ZodBranded,
|
||
ZodPipeline: ZodPipeline,
|
||
ZodReadonly: ZodReadonly,
|
||
custom: custom,
|
||
Schema: ZodType,
|
||
ZodSchema: ZodType,
|
||
late: late,
|
||
get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
|
||
coerce: coerce,
|
||
any: anyType,
|
||
array: arrayType,
|
||
bigint: bigIntType,
|
||
boolean: booleanType,
|
||
date: dateType,
|
||
discriminatedUnion: discriminatedUnionType,
|
||
effect: effectsType,
|
||
'enum': enumType,
|
||
'function': functionType,
|
||
'instanceof': instanceOfType,
|
||
intersection: intersectionType,
|
||
lazy: lazyType,
|
||
literal: literalType,
|
||
map: mapType,
|
||
nan: nanType,
|
||
nativeEnum: nativeEnumType,
|
||
never: neverType,
|
||
'null': nullType,
|
||
nullable: nullableType,
|
||
number: numberType,
|
||
object: objectType,
|
||
oboolean: oboolean,
|
||
onumber: onumber,
|
||
optional: optionalType,
|
||
ostring: ostring,
|
||
pipeline: pipelineType,
|
||
preprocess: preprocessType,
|
||
promise: promiseType,
|
||
record: recordType,
|
||
set: setType,
|
||
strictObject: strictObjectType,
|
||
string: stringType,
|
||
symbol: symbolType,
|
||
transformer: effectsType,
|
||
tuple: tupleType,
|
||
'undefined': undefinedType,
|
||
union: unionType,
|
||
unknown: unknownType,
|
||
'void': voidType,
|
||
NEVER: NEVER,
|
||
ZodIssueCode: ZodIssueCode,
|
||
quotelessJson: quotelessJson,
|
||
ZodError: ZodError
|
||
});
|
||
|
||
|
||
|
||
;// ./src/types.ts
|
||
|
||
// Basic YouTube DLP options schema
|
||
const YtDlpOptionsSchema = z.object({
|
||
// Path to the yt-dlp executable
|
||
executablePath: z.string().optional(),
|
||
// Output options
|
||
output: z.string().optional(),
|
||
format: z.string().optional(),
|
||
formatSort: z.string().optional(),
|
||
mergeOutputFormat: z.enum(['mp4', 'flv', 'webm', 'mkv', 'avi']).optional(),
|
||
// Download options
|
||
limit: z.number().int().positive().optional(),
|
||
maxFilesize: z.string().optional(),
|
||
minFilesize: z.string().optional(),
|
||
// Filesystem options
|
||
noOverwrites: z.boolean().optional(),
|
||
continue: z.boolean().optional(),
|
||
noPart: z.boolean().optional(),
|
||
// Thumbnail options
|
||
writeThumbnail: z.boolean().optional(),
|
||
writeAllThumbnails: z.boolean().optional(),
|
||
// Subtitles options
|
||
writeSubtitles: z.boolean().optional(),
|
||
writeAutoSubtitles: z.boolean().optional(),
|
||
subLang: z.string().optional(),
|
||
// Authentication options
|
||
username: z.string().optional(),
|
||
password: z.string().optional(),
|
||
// Video selection options
|
||
playlistStart: z.number().int().positive().optional(),
|
||
playlistEnd: z.number().int().positive().optional(),
|
||
playlistItems: z.string().optional(),
|
||
// Post-processing options
|
||
extractAudio: z.boolean().optional(),
|
||
audioFormat: z.enum(['best', 'aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']).optional(),
|
||
audioQuality: z.string().optional(),
|
||
remuxVideo: z.enum(['mp4', 'mkv', 'flv', 'webm', 'mov', 'avi']).optional(),
|
||
recodeVideo: z.enum(['mp4', 'flv', 'webm', 'mkv', 'avi']).optional(),
|
||
// Verbosity and simulation options
|
||
quiet: z.boolean().optional(),
|
||
verbose: z.boolean().optional(),
|
||
noWarnings: z.boolean().optional(),
|
||
simulate: z.boolean().optional(),
|
||
// Workarounds
|
||
noCheckCertificates: z.boolean().optional(),
|
||
preferInsecure: z.boolean().optional(),
|
||
userAgent: z.string().optional(),
|
||
// Extra arguments as string array
|
||
extraArgs: z.array(z.string()).optional(),
|
||
});
|
||
// Video information schema
|
||
const VideoInfoSchema = z.object({
|
||
id: z.string(),
|
||
title: z.string(),
|
||
formats: z.array(z.object({
|
||
format_id: z.string(),
|
||
format: z.string(),
|
||
ext: z.string(),
|
||
resolution: z.string().optional(),
|
||
fps: z.number().optional(),
|
||
filesize: z.number().optional(),
|
||
tbr: z.number().optional(),
|
||
protocol: z.string(),
|
||
vcodec: z.string(),
|
||
acodec: z.string(),
|
||
})),
|
||
thumbnails: z.array(z.object({
|
||
url: z.string(),
|
||
height: z.number().optional(),
|
||
width: z.number().optional(),
|
||
})).optional(),
|
||
description: z.string().optional(),
|
||
upload_date: z.string().optional(),
|
||
uploader: z.string().optional(),
|
||
uploader_id: z.string().optional(),
|
||
uploader_url: z.string().optional(),
|
||
channel_id: z.string().optional(),
|
||
channel_url: z.string().optional(),
|
||
duration: z.number().optional(),
|
||
view_count: z.number().optional(),
|
||
like_count: z.number().optional(),
|
||
dislike_count: z.number().optional(),
|
||
average_rating: z.number().optional(),
|
||
age_limit: z.number().optional(),
|
||
webpage_url: z.string(),
|
||
categories: z.array(z.string()).optional(),
|
||
tags: z.array(z.string()).optional(),
|
||
is_live: z.boolean().optional(),
|
||
was_live: z.boolean().optional(),
|
||
playable_in_embed: z.boolean().optional(),
|
||
availability: z.string().optional(),
|
||
});
|
||
// Download result schema
|
||
const DownloadResultSchema = z.object({
|
||
videoInfo: VideoInfoSchema,
|
||
filePath: z.string(),
|
||
downloadedBytes: z.number().optional(),
|
||
elapsedTime: z.number().optional(),
|
||
averageSpeed: z.number().optional(), // in bytes/s
|
||
success: z.boolean(),
|
||
error: z.string().optional(),
|
||
});
|
||
// Command execution result schema
|
||
const CommandResultSchema = z.object({
|
||
command: z.string(),
|
||
stdout: z.string(),
|
||
stderr: z.string(),
|
||
success: z.boolean(),
|
||
exitCode: z.number(),
|
||
});
|
||
// Progress update schema for download progress events
|
||
const ProgressUpdateSchema = z.object({
|
||
videoId: z.string(),
|
||
percent: z.number().min(0).max(100),
|
||
totalSize: z.number().optional(),
|
||
downloadedBytes: z.number(),
|
||
speed: z.number(), // in bytes/s
|
||
eta: z.number().optional(), // in seconds
|
||
status: z.enum(['downloading', 'finished', 'error']),
|
||
message: z.string().optional(),
|
||
});
|
||
// Error types
|
||
var YtDlpErrorType;
|
||
(function (YtDlpErrorType) {
|
||
YtDlpErrorType["PROCESS_ERROR"] = "PROCESS_ERROR";
|
||
YtDlpErrorType["VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
||
YtDlpErrorType["DOWNLOAD_ERROR"] = "DOWNLOAD_ERROR";
|
||
YtDlpErrorType["UNSUPPORTED_URL"] = "UNSUPPORTED_URL";
|
||
YtDlpErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
|
||
})(YtDlpErrorType || (YtDlpErrorType = {}));
|
||
// Custom error schema
|
||
const YtDlpErrorSchema = z.object({
|
||
type: z.nativeEnum(YtDlpErrorType),
|
||
message: z.string(),
|
||
details: z.record(z.any()).optional(),
|
||
command: z.string().optional(),
|
||
});
|
||
// Download options schema
|
||
const DownloadOptionsSchema = z.object({
|
||
outputDir: z.string().optional(),
|
||
format: z.string().optional(),
|
||
outputTemplate: z.string().optional(),
|
||
audioOnly: z.boolean().optional(),
|
||
audioFormat: z.string().optional(),
|
||
subtitles: z.union([z.boolean(), z.array(z.string())]).optional(),
|
||
maxFileSize: z.number().optional(),
|
||
rateLimit: z.string().optional(),
|
||
additionalArgs: z.array(z.string()).optional(),
|
||
});
|
||
// Format options schema for listing video formats
|
||
const FormatOptionsSchema = z.object({
|
||
all: z.boolean().optional().default(false),
|
||
});
|
||
// Video info options schema
|
||
const VideoInfoOptionsSchema = z.object({
|
||
dumpJson: z.boolean().optional().default(false),
|
||
flatPlaylist: z.boolean().optional().default(false),
|
||
});
|
||
// Video format schema representing a single format option returned by yt-dlp
|
||
// Video format schema representing a single format option returned by yt-dlp
|
||
const VideoFormatSchema = z.object({
|
||
format_id: z.string(),
|
||
format: z.string(),
|
||
ext: z.string(),
|
||
resolution: z.string().optional(),
|
||
fps: z.number().optional(),
|
||
filesize: z.number().optional(),
|
||
tbr: z.number().optional(),
|
||
protocol: z.string(),
|
||
vcodec: z.string(),
|
||
acodec: z.string(),
|
||
width: z.number().optional(),
|
||
height: z.number().optional(),
|
||
url: z.string().optional(),
|
||
format_note: z.string().optional(),
|
||
container: z.string().optional(),
|
||
quality: z.number().optional(),
|
||
preference: z.number().optional(),
|
||
});
|
||
|
||
;// ./src/cli.ts
|
||
//#!/usr/bin/env node
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
const cli_execAsync = (0,external_node_util_namespaceObject.promisify)(external_node_child_process_namespaceObject.exec);
|
||
const cli_ytdlp = new YtDlp();
|
||
// Function to generate user-friendly help message
|
||
function printHelp() {
|
||
console.log("\n======= yt-dlp TypeScript Wrapper =======");
|
||
console.log("A TypeScript wrapper for the yt-dlp video downloader\n");
|
||
console.log("USAGE:");
|
||
console.log(" ytdlp-ts <command> [options] <url>\n");
|
||
console.log("COMMANDS:");
|
||
console.log(" download [url] Download a video from the specified URL");
|
||
console.log(" info [url] Get information about a video");
|
||
console.log(" formats [url] List available formats for a video\n");
|
||
console.log("DOWNLOAD OPTIONS:");
|
||
console.log(" --format, -f Specify video format code");
|
||
console.log(" --output, -o Specify output filename template");
|
||
console.log(" --quiet, -q Activate quiet mode");
|
||
console.log(" --verbose, -v Print various debugging information");
|
||
console.log(" --mp3 Download only the audio in MP3 format\n");
|
||
console.log("INFO OPTIONS:");
|
||
console.log(" --dump-json Output JSON information");
|
||
console.log(" --flat-playlist Flat playlist output\n");
|
||
console.log("FORMATS OPTIONS:");
|
||
console.log(" --all Show all available formats\n");
|
||
console.log("EXAMPLES:");
|
||
console.log(" ytdlp-ts download https://www.tiktok.com/@woman.power.quote/video/7476910372121970");
|
||
console.log(" ytdlp-ts download https://www.youtube.com/watch?v=_oVI0GW-Xd4 -f \"bestvideo[height<=1080]+bestaudio/best[height<=1080]\"");
|
||
console.log(" ytdlp-ts download https://www.youtube.com/watch?v=_oVI0GW-Xd4 --mp3");
|
||
console.log(" ytdlp-ts info https://www.tiktok.com/@woman.power.quote/video/7476910372121970 --dump-json");
|
||
console.log(" ytdlp-ts formats https://www.youtube.com/watch?v=_oVI0GW-Xd4 --all\n");
|
||
console.log("For more information, visit https://github.com/yt-dlp/yt-dlp");
|
||
}
|
||
/**
|
||
* Checks if ffmpeg is installed on the system
|
||
* @returns {Promise<boolean>} True if ffmpeg is installed, false otherwise
|
||
*/
|
||
async function isFFmpegInstalled() {
|
||
try {
|
||
// Try to execute ffmpeg -version command
|
||
await cli_execAsync('ffmpeg -version');
|
||
return true;
|
||
}
|
||
catch (error) {
|
||
return false;
|
||
}
|
||
}
|
||
// Check for help flags directly in process.argv
|
||
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
||
printHelp();
|
||
process.exit(0);
|
||
}
|
||
// Create a simple yargs CLI with clear command structure
|
||
yargs(hideBin(process.argv))
|
||
.scriptName('yt-dlp-wrapper')
|
||
.usage('$0 <cmd> [args]')
|
||
.command('download [url]', 'Download a video', (yargs) => {
|
||
return yargs
|
||
.positional('url', {
|
||
type: 'string',
|
||
describe: 'URL of the video to download',
|
||
demandOption: true,
|
||
})
|
||
.option('format', {
|
||
type: 'string',
|
||
describe: 'Video format code',
|
||
alias: 'f',
|
||
})
|
||
.option('output', {
|
||
type: 'string',
|
||
describe: 'Output filename template',
|
||
alias: 'o',
|
||
})
|
||
.option('quiet', {
|
||
type: 'boolean',
|
||
describe: 'Activate quiet mode',
|
||
alias: 'q',
|
||
default: false,
|
||
})
|
||
.option('verbose', {
|
||
type: 'boolean',
|
||
describe: 'Print various debugging information',
|
||
alias: 'v',
|
||
default: false,
|
||
})
|
||
.option('mp3', {
|
||
type: 'boolean',
|
||
describe: 'Download only the audio in MP3 format',
|
||
default: false,
|
||
});
|
||
}, async (argv) => {
|
||
try {
|
||
logger.info(`Starting download process for: ${argv.url}`);
|
||
logger.debug(`Download options: mp3=${argv.mp3}, format=${argv.format}, output=${argv.output}`);
|
||
// Check if ffmpeg is installed when MP3 option is specified
|
||
if (argv.mp3) {
|
||
logger.info('MP3 option detected. Checking for ffmpeg installation...');
|
||
const ffmpegInstalled = await isFFmpegInstalled();
|
||
if (!ffmpegInstalled) {
|
||
logger.error('\x1b[31mError: ffmpeg is not installed or not found in PATH\x1b[0m');
|
||
logger.error('\nTo download videos as MP3, ffmpeg is required. Please install ffmpeg:');
|
||
logger.error('\n • Windows: https://ffmpeg.org/download.html or install via Chocolatey/Scoop');
|
||
logger.error(' • macOS: brew install ffmpeg');
|
||
logger.error(' • Linux: apt install ffmpeg / yum install ffmpeg / etc. (depending on your distribution)');
|
||
logger.error('\nAfter installing, make sure ffmpeg is in your PATH and try again.');
|
||
process.exit(1);
|
||
}
|
||
logger.info('ffmpeg is installed. Proceeding with MP3 download...');
|
||
}
|
||
// Parse and validate options using Zod
|
||
const options = DownloadOptionsSchema.parse({
|
||
format: argv.format,
|
||
output: argv.output,
|
||
quiet: argv.quiet,
|
||
verbose: argv.verbose,
|
||
audioOnly: argv.mp3 ? true : undefined,
|
||
audioFormat: argv.mp3 ? 'mp3' : undefined,
|
||
});
|
||
logger.debug(`Parsed download options: ${JSON.stringify(options)}`);
|
||
logger.info(`Starting download with options: ${JSON.stringify({
|
||
url: argv.url,
|
||
mp3: argv.mp3,
|
||
format: argv.format,
|
||
output: argv.output
|
||
})}`);
|
||
const downloadedFile = await cli_ytdlp.downloadVideo(argv.url, options);
|
||
logger.info(`Download completed successfully: ${downloadedFile}`);
|
||
}
|
||
catch (error) {
|
||
if (error instanceof z.ZodError) {
|
||
logger.error('Invalid options:', error.errors);
|
||
}
|
||
else {
|
||
logger.error('Failed to download video:', error);
|
||
}
|
||
process.exit(1);
|
||
}
|
||
})
|
||
.command('info [url]', 'Get video information', (yargs) => {
|
||
return yargs
|
||
.positional('url', {
|
||
type: 'string',
|
||
describe: 'URL of the video',
|
||
demandOption: true,
|
||
})
|
||
.option('dump-json', {
|
||
type: 'boolean',
|
||
describe: 'Output JSON information',
|
||
default: false,
|
||
})
|
||
.option('flat-playlist', {
|
||
type: 'boolean',
|
||
describe: 'Flat playlist output',
|
||
default: false,
|
||
});
|
||
}, async (argv) => {
|
||
try {
|
||
logger.info(`Starting info retrieval for: ${argv.url}`);
|
||
// Parse and validate options using Zod
|
||
const options = VideoInfoOptionsSchema.parse({
|
||
dumpJson: argv.dumpJson,
|
||
flatPlaylist: argv.flatPlaylist,
|
||
});
|
||
const info = await cli_ytdlp.getVideoInfo(argv.url, options);
|
||
logger.info(`Info retrieval completed successfully`);
|
||
console.log(JSON.stringify(info, null, 2));
|
||
}
|
||
catch (error) {
|
||
if (error instanceof z.ZodError) {
|
||
logger.error('Invalid options:', error.errors);
|
||
}
|
||
else {
|
||
logger.error('Failed to get video info:', error);
|
||
}
|
||
process.exit(1);
|
||
}
|
||
})
|
||
.command('formats [url]', 'List available formats of a video', (yargs) => {
|
||
return yargs
|
||
.positional('url', {
|
||
type: 'string',
|
||
describe: 'URL of the video',
|
||
demandOption: true,
|
||
})
|
||
.option('all', {
|
||
type: 'boolean',
|
||
describe: 'Show all available formats',
|
||
default: false,
|
||
});
|
||
}, async (argv) => {
|
||
try {
|
||
logger.info(`Getting available formats for video: ${argv.url}`);
|
||
// Parse and validate options using Zod
|
||
const options = FormatOptionsSchema.parse({
|
||
all: argv.all,
|
||
});
|
||
const formats = await cli_ytdlp.listFormats(argv.url, options);
|
||
logger.info(`Format listing completed successfully`);
|
||
console.log(formats);
|
||
}
|
||
catch (error) {
|
||
if (error instanceof z.ZodError) {
|
||
logger.error('Invalid options:', error.errors);
|
||
}
|
||
else {
|
||
logger.error('Failed to list formats:', error);
|
||
}
|
||
process.exit(1);
|
||
}
|
||
})
|
||
.example('$0 download https://www.tiktok.com/@woman.power.quote/video/7476910372121971970', 'Download a TikTok video with default settings')
|
||
.example('$0 download https://www.youtube.com/watch?v=_oVI0GW-Xd4 -f "bestvideo[height<=1080]+bestaudio/best[height<=1080]"', 'Download a YouTube video in 1080p or lower quality')
|
||
.example('$0 download https://www.youtube.com/watch?v=_oVI0GW-Xd4 --mp3', 'Extract and download only the audio in MP3 format')
|
||
.example('$0 info https://www.tiktok.com/@woman.power.quote/video/7476910372121971970 --dump-json', 'Retrieve and display detailed video metadata in JSON format')
|
||
.example('$0 formats https://www.youtube.com/watch?v=_oVI0GW-Xd4 --all', 'List all available video and audio formats for a YouTube video')
|
||
.demandCommand(1, 'You need to specify a command')
|
||
.strict()
|
||
.help()
|
||
.alias('h', 'help')
|
||
.version()
|
||
.alias('V', 'version')
|
||
.wrap(800) // Fixed width value instead of yargs.terminalWidth() which isn't compatible with ESM
|
||
.showHelpOnFail(true)
|
||
.parse();
|
||
|