UNPKG

@arcgis/create

Version:

The ArcGIS Maps SDK for JavaScript provides this CLI tool to streamline the process of creating a new web mapping application.

1,414 lines • 484 kB
import Ea from "node:events"; import Ca from "node:child_process"; import Aa from "node:path"; import La from "node:fs"; import le, { stdin as yo, stdout as Nn } from "node:process"; import * as st from "node:readline"; import Oa from "node:readline"; import Zn, { ReadStream as es } from "node:tty"; import $a from "node:os"; import ne from "fs/promises"; import Je from "path"; import Ae from "process"; import _a from "child_process"; import Na, { promisify as Pa } from "util"; import Ia from "node:url"; import Ta from "url"; import ka from "node:module"; import xa from "buffer"; function Mt(e) { return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e; } var rt = { exports: {} }, pe = {}, ot = {}, at = {}, ts; function Dt() { if (ts) return at; ts = 1; class e extends Error { /** * Constructs the CommanderError class * @param {number} exitCode suggested exit code which could be used with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error */ constructor(g, f, i) { super(i), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name, this.code = f, this.exitCode = g, this.nestedError = void 0; } } class h extends e { /** * Constructs the InvalidArgumentError class * @param {string} [message] explanation of why argument is invalid */ constructor(g) { super(1, "commander.invalidArgument", g), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name; } } return at.CommanderError = e, at.InvalidArgumentError = h, at; } var is; function Pn() { if (is) return ot; is = 1; const { InvalidArgumentError: e } = Dt(); class h { /** * Initialize a new command argument with the given name and description. * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @param {string} name * @param {string} [description] */ constructor(f, i) { switch (this.description = i || "", this.variadic = !1, this.parseArg = void 0, this.defaultValue = void 0, this.defaultValueDescription = void 0, this.argChoices = void 0, f[0]) { case "<": this.required = !0, this._name = f.slice(1, -1); break; case "[": this.required = !1, this._name = f.slice(1, -1); break; default: this.required = !0, this._name = f; break; } this._name.endsWith("...") && (this.variadic = !0, this._name = this._name.slice(0, -3)); } /** * Return argument name. * * @return {string} */ name() { return this._name; } /** * @package */ _collectValue(f, i) { return i === this.defaultValue || !Array.isArray(i) ? [f] : (i.push(f), i); } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Argument} */ default(f, i) { return this.defaultValue = f, this.defaultValueDescription = i, this; } /** * Set the custom handler for processing CLI command arguments into argument values. * * @param {Function} [fn] * @return {Argument} */ argParser(f) { return this.parseArg = f, this; } /** * Only allow argument value to be one of choices. * * @param {string[]} values * @return {Argument} */ choices(f) { return this.argChoices = f.slice(), this.parseArg = (i, s) => { if (!this.argChoices.includes(i)) throw new e( `Allowed choices are ${this.argChoices.join(", ")}.` ); return this.variadic ? this._collectValue(i, s) : i; }, this; } /** * Make argument required. * * @returns {Argument} */ argRequired() { return this.required = !0, this; } /** * Make argument optional. * * @returns {Argument} */ argOptional() { return this.required = !1, this; } } function m(g) { const f = g.name() + (g.variadic === !0 ? "..." : ""); return g.required ? "<" + f + ">" : "[" + f + "]"; } return ot.Argument = h, ot.humanReadableArgName = m, ot; } var lt = {}, ct = {}, ns; function bo() { if (ns) return ct; ns = 1; const { humanReadableArgName: e } = Pn(); class h { constructor() { this.helpWidth = void 0, this.minWidthToWrap = 40, this.sortSubcommands = !1, this.sortOptions = !1, this.showGlobalOptions = !1; } /** * prepareContext is called by Commander after applying overrides from `Command.configureHelp()` * and just before calling `formatHelp()`. * * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses. * * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions */ prepareContext(f) { this.helpWidth = this.helpWidth ?? f.helpWidth ?? 80; } /** * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. * * @param {Command} cmd * @returns {Command[]} */ visibleCommands(f) { const i = f.commands.filter((a) => !a._hidden), s = f._getHelpCommand(); return s && !s._hidden && i.push(s), this.sortSubcommands && i.sort((a, o) => a.name().localeCompare(o.name())), i; } /** * Compare options for sort. * * @param {Option} a * @param {Option} b * @returns {number} */ compareOptions(f, i) { const s = (a) => a.short ? a.short.replace(/^-/, "") : a.long.replace(/^--/, ""); return s(f).localeCompare(s(i)); } /** * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. * * @param {Command} cmd * @returns {Option[]} */ visibleOptions(f) { const i = f.options.filter((a) => !a.hidden), s = f._getHelpOption(); if (s && !s.hidden) { const a = s.short && f._findOption(s.short), o = s.long && f._findOption(s.long); !a && !o ? i.push(s) : s.long && !o ? i.push( f.createOption(s.long, s.description) ) : s.short && !a && i.push( f.createOption(s.short, s.description) ); } return this.sortOptions && i.sort(this.compareOptions), i; } /** * Get an array of the visible global options. (Not including help.) * * @param {Command} cmd * @returns {Option[]} */ visibleGlobalOptions(f) { if (!this.showGlobalOptions) return []; const i = []; for (let s = f.parent; s; s = s.parent) { const a = s.options.filter( (o) => !o.hidden ); i.push(...a); } return this.sortOptions && i.sort(this.compareOptions), i; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(f) { return f._argsDescription && f.registeredArguments.forEach((i) => { i.description = i.description || f._argsDescription[i.name()] || ""; }), f.registeredArguments.find((i) => i.description) ? f.registeredArguments : []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(f) { const i = f.registeredArguments.map((s) => e(s)).join(" "); return f._name + (f._aliases[0] ? "|" + f._aliases[0] : "") + (f.options.length ? " [options]" : "") + // simplistic check for non-help option (i ? " " + i : ""); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(f) { return f.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(f) { return f.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(f, i) { return i.visibleCommands(f).reduce((s, a) => Math.max( s, this.displayWidth( i.styleSubcommandTerm(i.subcommandTerm(a)) ) ), 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(f, i) { return i.visibleOptions(f).reduce((s, a) => Math.max( s, this.displayWidth(i.styleOptionTerm(i.optionTerm(a))) ), 0); } /** * Get the longest global option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestGlobalOptionTermLength(f, i) { return i.visibleGlobalOptions(f).reduce((s, a) => Math.max( s, this.displayWidth(i.styleOptionTerm(i.optionTerm(a))) ), 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(f, i) { return i.visibleArguments(f).reduce((s, a) => Math.max( s, this.displayWidth( i.styleArgumentTerm(i.argumentTerm(a)) ) ), 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(f) { let i = f._name; f._aliases[0] && (i = i + "|" + f._aliases[0]); let s = ""; for (let a = f.parent; a; a = a.parent) s = a.name() + " " + s; return s + i + " " + f.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(f) { return f.description(); } /** * Get the subcommand summary to show in the list of subcommands. * (Fallback to description for backwards compatibility.) * * @param {Command} cmd * @returns {string} */ subcommandDescription(f) { return f.summary() || f.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(f) { const i = []; if (f.argChoices && i.push( // use stringify to match the display of the default value `choices: ${f.argChoices.map((s) => JSON.stringify(s)).join(", ")}` ), f.defaultValue !== void 0 && (f.required || f.optional || f.isBoolean() && typeof f.defaultValue == "boolean") && i.push( `default: ${f.defaultValueDescription || JSON.stringify(f.defaultValue)}` ), f.presetArg !== void 0 && f.optional && i.push(`preset: ${JSON.stringify(f.presetArg)}`), f.envVar !== void 0 && i.push(`env: ${f.envVar}`), i.length > 0) { const s = `(${i.join(", ")})`; return f.description ? `${f.description} ${s}` : s; } return f.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(f) { const i = []; if (f.argChoices && i.push( // use stringify to match the display of the default value `choices: ${f.argChoices.map((s) => JSON.stringify(s)).join(", ")}` ), f.defaultValue !== void 0 && i.push( `default: ${f.defaultValueDescription || JSON.stringify(f.defaultValue)}` ), i.length > 0) { const s = `(${i.join(", ")})`; return f.description ? `${f.description} ${s}` : s; } return f.description; } /** * Format a list of items, given a heading and an array of formatted items. * * @param {string} heading * @param {string[]} items * @param {Help} helper * @returns string[] */ formatItemList(f, i, s) { return i.length === 0 ? [] : [s.styleTitle(f), ...i, ""]; } /** * Group items by their help group heading. * * @param {Command[] | Option[]} unsortedItems * @param {Command[] | Option[]} visibleItems * @param {Function} getGroup * @returns {Map<string, Command[] | Option[]>} */ groupItems(f, i, s) { const a = /* @__PURE__ */ new Map(); return f.forEach((o) => { const p = s(o); a.has(p) || a.set(p, []); }), i.forEach((o) => { const p = s(o); a.has(p) || a.set(p, []), a.get(p).push(o); }), a; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(f, i) { const s = i.padWidth(f, i), a = i.helpWidth ?? 80; function o(u, d) { return i.formatItem(u, s, d, i); } let p = [ `${i.styleTitle("Usage:")} ${i.styleUsage(i.commandUsage(f))}`, "" ]; const n = i.commandDescription(f); n.length > 0 && (p = p.concat([ i.boxWrap( i.styleCommandDescription(n), a ), "" ])); const t = i.visibleArguments(f).map((u) => o( i.styleArgumentTerm(i.argumentTerm(u)), i.styleArgumentDescription(i.argumentDescription(u)) )); if (p = p.concat( this.formatItemList("Arguments:", t, i) ), this.groupItems( f.options, i.visibleOptions(f), (u) => u.helpGroupHeading ?? "Options:" ).forEach((u, d) => { const v = u.map((r) => o( i.styleOptionTerm(i.optionTerm(r)), i.styleOptionDescription(i.optionDescription(r)) )); p = p.concat(this.formatItemList(d, v, i)); }), i.showGlobalOptions) { const u = i.visibleGlobalOptions(f).map((d) => o( i.styleOptionTerm(i.optionTerm(d)), i.styleOptionDescription(i.optionDescription(d)) )); p = p.concat( this.formatItemList("Global Options:", u, i) ); } return this.groupItems( f.commands, i.visibleCommands(f), (u) => u.helpGroup() || "Commands:" ).forEach((u, d) => { const v = u.map((r) => o( i.styleSubcommandTerm(i.subcommandTerm(r)), i.styleSubcommandDescription(i.subcommandDescription(r)) )); p = p.concat(this.formatItemList(d, v, i)); }), p.join(` `); } /** * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. * * @param {string} str * @returns {number} */ displayWidth(f) { return m(f).length; } /** * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. * * @param {string} str * @returns {string} */ styleTitle(f) { return f; } styleUsage(f) { return f.split(" ").map((i) => i === "[options]" ? this.styleOptionText(i) : i === "[command]" ? this.styleSubcommandText(i) : i[0] === "[" || i[0] === "<" ? this.styleArgumentText(i) : this.styleCommandText(i)).join(" "); } styleCommandDescription(f) { return this.styleDescriptionText(f); } styleOptionDescription(f) { return this.styleDescriptionText(f); } styleSubcommandDescription(f) { return this.styleDescriptionText(f); } styleArgumentDescription(f) { return this.styleDescriptionText(f); } styleDescriptionText(f) { return f; } styleOptionTerm(f) { return this.styleOptionText(f); } styleSubcommandTerm(f) { return f.split(" ").map((i) => i === "[options]" ? this.styleOptionText(i) : i[0] === "[" || i[0] === "<" ? this.styleArgumentText(i) : this.styleSubcommandText(i)).join(" "); } styleArgumentTerm(f) { return this.styleArgumentText(f); } styleOptionText(f) { return f; } styleArgumentText(f) { return f; } styleSubcommandText(f) { return f; } styleCommandText(f) { return f; } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(f, i) { return Math.max( i.longestOptionTermLength(f, i), i.longestGlobalOptionTermLength(f, i), i.longestSubcommandTermLength(f, i), i.longestArgumentTermLength(f, i) ); } /** * Detect manually wrapped and indented strings by checking for line break followed by whitespace. * * @param {string} str * @returns {boolean} */ preformatted(f) { return /\n[^\S\r\n]/.test(f); } /** * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines. * * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so: * TTT DDD DDDD * DD DDD * * @param {string} term * @param {number} termWidth * @param {string} description * @param {Help} helper * @returns {string} */ formatItem(f, i, s, a) { const p = " ".repeat(2); if (!s) return p + f; const n = f.padEnd( i + f.length - a.displayWidth(f) ), t = 2, c = (this.helpWidth ?? 80) - i - t - 2; let u; return c < this.minWidthToWrap || a.preformatted(s) ? u = s : u = a.boxWrap(s, c).replace( /\n/g, ` ` + " ".repeat(i + t) ), p + n + " ".repeat(t) + u.replace(/\n/g, ` ${p}`); } /** * Wrap a string at whitespace, preserving existing line breaks. * Wrapping is skipped if the width is less than `minWidthToWrap`. * * @param {string} str * @param {number} width * @returns {string} */ boxWrap(f, i) { if (i < this.minWidthToWrap) return f; const s = f.split(/\r\n|\n/), a = /[\s]*[^\s]+/g, o = []; return s.forEach((p) => { const n = p.match(a); if (n === null) { o.push(""); return; } let t = [n.shift()], l = this.displayWidth(t[0]); n.forEach((c) => { const u = this.displayWidth(c); if (l + u <= i) { t.push(c), l += u; return; } o.push(t.join("")); const d = c.trimStart(); t = [d], l = this.displayWidth(d); }), o.push(t.join("")); }), o.join(` `); } } function m(g) { const f = /\x1b\[\d*(;\d*)*m/g; return g.replace(f, ""); } return ct.Help = h, ct.stripColor = m, ct; } var ut = {}, ss; function vo() { if (ss) return ut; ss = 1; const { InvalidArgumentError: e } = Dt(); class h { /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {string} flags * @param {string} [description] */ constructor(s, a) { this.flags = s, this.description = a || "", this.required = s.includes("<"), this.optional = s.includes("["), this.variadic = /\w\.\.\.[>\]]$/.test(s), this.mandatory = !1; const o = f(s); this.short = o.shortFlag, this.long = o.longFlag, this.negate = !1, this.long && (this.negate = this.long.startsWith("--no-")), this.defaultValue = void 0, this.defaultValueDescription = void 0, this.presetArg = void 0, this.envVar = void 0, this.parseArg = void 0, this.hidden = !1, this.argChoices = void 0, this.conflictsWith = [], this.implied = void 0, this.helpGroupHeading = void 0; } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Option} */ default(s, a) { return this.defaultValue = s, this.defaultValueDescription = a, this; } /** * Preset to use when option used without option-argument, especially optional but also boolean and negated. * The custom processing (parseArg) is called. * * @example * new Option('--color').default('GREYSCALE').preset('RGB'); * new Option('--donate [amount]').preset('20').argParser(parseFloat); * * @param {*} arg * @return {Option} */ preset(s) { return this.presetArg = s, this; } /** * Add option name(s) that conflict with this option. * An error will be displayed if conflicting options are found during parsing. * * @example * new Option('--rgb').conflicts('cmyk'); * new Option('--js').conflicts(['ts', 'jsx']); * * @param {(string | string[])} names * @return {Option} */ conflicts(s) { return this.conflictsWith = this.conflictsWith.concat(s), this; } /** * Specify implied option values for when this option is set and the implied options are not. * * The custom processing (parseArg) is not called on the implied values. * * @example * program * .addOption(new Option('--log', 'write logging information to file')) * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); * * @param {object} impliedOptionValues * @return {Option} */ implies(s) { let a = s; return typeof s == "string" && (a = { [s]: !0 }), this.implied = Object.assign(this.implied || {}, a), this; } /** * Set environment variable to check for option value. * * An environment variable is only used if when processed the current option value is * undefined, or the source of the current value is 'default' or 'config' or 'env'. * * @param {string} name * @return {Option} */ env(s) { return this.envVar = s, this; } /** * Set the custom handler for processing CLI option arguments into option values. * * @param {Function} [fn] * @return {Option} */ argParser(s) { return this.parseArg = s, this; } /** * Whether the option is mandatory and must have a value after parsing. * * @param {boolean} [mandatory=true] * @return {Option} */ makeOptionMandatory(s = !0) { return this.mandatory = !!s, this; } /** * Hide option in help. * * @param {boolean} [hide=true] * @return {Option} */ hideHelp(s = !0) { return this.hidden = !!s, this; } /** * @package */ _collectValue(s, a) { return a === this.defaultValue || !Array.isArray(a) ? [s] : (a.push(s), a); } /** * Only allow option value to be one of choices. * * @param {string[]} values * @return {Option} */ choices(s) { return this.argChoices = s.slice(), this.parseArg = (a, o) => { if (!this.argChoices.includes(a)) throw new e( `Allowed choices are ${this.argChoices.join(", ")}.` ); return this.variadic ? this._collectValue(a, o) : a; }, this; } /** * Return option name. * * @return {string} */ name() { return this.long ? this.long.replace(/^--/, "") : this.short.replace(/^-/, ""); } /** * Return option name, in a camelcase format that can be used * as an object attribute key. * * @return {string} */ attributeName() { return this.negate ? g(this.name().replace(/^no-/, "")) : g(this.name()); } /** * Set the help group heading. * * @param {string} heading * @return {Option} */ helpGroup(s) { return this.helpGroupHeading = s, this; } /** * Check if `arg` matches the short or long flag. * * @param {string} arg * @return {boolean} * @package */ is(s) { return this.short === s || this.long === s; } /** * Return whether a boolean option. * * Options are one of boolean, negated, required argument, or optional argument. * * @return {boolean} * @package */ isBoolean() { return !this.required && !this.optional && !this.negate; } } class m { /** * @param {Option[]} options */ constructor(s) { this.positiveOptions = /* @__PURE__ */ new Map(), this.negativeOptions = /* @__PURE__ */ new Map(), this.dualOptions = /* @__PURE__ */ new Set(), s.forEach((a) => { a.negate ? this.negativeOptions.set(a.attributeName(), a) : this.positiveOptions.set(a.attributeName(), a); }), this.negativeOptions.forEach((a, o) => { this.positiveOptions.has(o) && this.dualOptions.add(o); }); } /** * Did the value come from the option, and not from possible matching dual option? * * @param {*} value * @param {Option} option * @returns {boolean} */ valueFromOption(s, a) { const o = a.attributeName(); if (!this.dualOptions.has(o)) return !0; const p = this.negativeOptions.get(o).presetArg, n = p !== void 0 ? p : !1; return a.negate === (n === s); } } function g(i) { return i.split("-").reduce((s, a) => s + a[0].toUpperCase() + a.slice(1)); } function f(i) { let s, a; const o = /^-[^-]$/, p = /^--[^-]/, n = i.split(/[ |,]+/).concat("guard"); if (o.test(n[0]) && (s = n.shift()), p.test(n[0]) && (a = n.shift()), !s && o.test(n[0]) && (s = n.shift()), !s && p.test(n[0]) && (s = a, a = n.shift()), n[0].startsWith("-")) { const t = n[0], l = `option creation failed due to '${t}' in option flags '${i}'`; throw /^-[^-][^-]/.test(t) ? new Error( `${l} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - or use a double dash for a long option (and can have two, like '--ws, --workspace')` ) : o.test(t) ? new Error(`${l} - too many short flags`) : p.test(t) ? new Error(`${l} - too many long flags`) : new Error(`${l} - unrecognised flag format`); } if (s === void 0 && a === void 0) throw new Error( `option creation failed due to no flags found in '${i}'.` ); return { shortFlag: s, longFlag: a }; } return ut.Option = h, ut.DualOptions = m, ut; } var Xt = {}, rs; function Ra() { if (rs) return Xt; rs = 1; const e = 3; function h(g, f) { if (Math.abs(g.length - f.length) > e) return Math.max(g.length, f.length); const i = []; for (let s = 0; s <= g.length; s++) i[s] = [s]; for (let s = 0; s <= f.length; s++) i[0][s] = s; for (let s = 1; s <= f.length; s++) for (let a = 1; a <= g.length; a++) { let o = 1; g[a - 1] === f[s - 1] ? o = 0 : o = 1, i[a][s] = Math.min( i[a - 1][s] + 1, // deletion i[a][s - 1] + 1, // insertion i[a - 1][s - 1] + o // substitution ), a > 1 && s > 1 && g[a - 1] === f[s - 2] && g[a - 2] === f[s - 1] && (i[a][s] = Math.min(i[a][s], i[a - 2][s - 2] + 1)); } return i[g.length][f.length]; } function m(g, f) { if (!f || f.length === 0) return ""; f = Array.from(new Set(f)); const i = g.startsWith("--"); i && (g = g.slice(2), f = f.map((p) => p.slice(2))); let s = [], a = e; const o = 0.4; return f.forEach((p) => { if (p.length <= 1) return; const n = h(g, p), t = Math.max(g.length, p.length); (t - n) / t > o && (n < a ? (a = n, s = [p]) : n === a && s.push(p)); }), s.sort((p, n) => p.localeCompare(n)), i && (s = s.map((p) => `--${p}`)), s.length > 1 ? ` (Did you mean one of ${s.join(", ")}?)` : s.length === 1 ? ` (Did you mean ${s[0]}?)` : ""; } return Xt.suggestSimilar = m, Xt; } var os; function Ma() { if (os) return lt; os = 1; const e = Ea.EventEmitter, h = Ca, m = Aa, g = La, f = le, { Argument: i, humanReadableArgName: s } = Pn(), { CommanderError: a } = Dt(), { Help: o, stripColor: p } = bo(), { Option: n, DualOptions: t } = vo(), { suggestSimilar: l } = Ra(); class c extends e { /** * Initialize a new `Command`. * * @param {string} [name] */ constructor(r) { super(), this.commands = [], this.options = [], this.parent = null, this._allowUnknownOption = !1, this._allowExcessArguments = !1, this.registeredArguments = [], this._args = this.registeredArguments, this.args = [], this.rawArgs = [], this.processedArgs = [], this._scriptPath = null, this._name = r || "", this._optionValues = {}, this._optionValueSources = {}, this._storeOptionsAsProperties = !1, this._actionHandler = null, this._executableHandler = !1, this._executableFile = null, this._executableDir = null, this._defaultCommandName = null, this._exitCallback = null, this._aliases = [], this._combineFlagAndOptionalValue = !0, this._description = "", this._summary = "", this._argsDescription = void 0, this._enablePositionalOptions = !1, this._passThroughOptions = !1, this._lifeCycleHooks = {}, this._showHelpAfterError = !1, this._showSuggestionAfterError = !0, this._savedState = null, this._outputConfiguration = { writeOut: (b) => f.stdout.write(b), writeErr: (b) => f.stderr.write(b), outputError: (b, w) => w(b), getOutHelpWidth: () => f.stdout.isTTY ? f.stdout.columns : void 0, getErrHelpWidth: () => f.stderr.isTTY ? f.stderr.columns : void 0, getOutHasColors: () => d() ?? (f.stdout.isTTY && f.stdout.hasColors?.()), getErrHasColors: () => d() ?? (f.stderr.isTTY && f.stderr.hasColors?.()), stripColor: (b) => p(b) }, this._hidden = !1, this._helpOption = void 0, this._addImplicitHelpCommand = void 0, this._helpCommand = void 0, this._helpConfiguration = {}, this._helpGroupHeading = void 0, this._defaultCommandGroup = void 0, this._defaultOptionGroup = void 0; } /** * Copy settings that are useful to have in common across root command and subcommands. * * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) * * @param {Command} sourceCommand * @return {Command} `this` command for chaining */ copyInheritedSettings(r) { return this._outputConfiguration = r._outputConfiguration, this._helpOption = r._helpOption, this._helpCommand = r._helpCommand, this._helpConfiguration = r._helpConfiguration, this._exitCallback = r._exitCallback, this._storeOptionsAsProperties = r._storeOptionsAsProperties, this._combineFlagAndOptionalValue = r._combineFlagAndOptionalValue, this._allowExcessArguments = r._allowExcessArguments, this._enablePositionalOptions = r._enablePositionalOptions, this._showHelpAfterError = r._showHelpAfterError, this._showSuggestionAfterError = r._showSuggestionAfterError, this; } /** * @returns {Command[]} * @private */ _getCommandAndAncestors() { const r = []; for (let b = this; b; b = b.parent) r.push(b); return r; } /** * Define a command. * * There are two styles of command: pay attention to where to put the description. * * @example * // Command implemented using action handler (description is supplied separately to `.command`) * program * .command('clone <source> [destination]') * .description('clone a repository into a newly created directory') * .action((source, destination) => { * console.log('clone command called'); * }); * * // Command implemented using separate executable file (description is second parameter to `.command`) * program * .command('start <service>', 'start named service') * .command('stop [service]', 'stop named service, or all if no name supplied'); * * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) * @param {object} [execOpts] - configuration options (for executable) * @return {Command} returns new command for action handler, or `this` for executable command */ command(r, b, w) { let y = b, S = w; typeof y == "object" && y !== null && (S = y, y = null), S = S || {}; const [, E, C] = r.match(/([^ ]+) *(.*)/), $ = this.createCommand(E); return y && ($.description(y), $._executableHandler = !0), S.isDefault && (this._defaultCommandName = $._name), $._hidden = !!(S.noHelp || S.hidden), $._executableFile = S.executableFile || null, C && $.arguments(C), this._registerCommand($), $.parent = this, $.copyInheritedSettings(this), y ? this : $; } /** * Factory routine to create a new unattached command. * * See .command() for creating an attached subcommand, which uses this routine to * create the command. You can override createCommand to customise subcommands. * * @param {string} [name] * @return {Command} new command */ createCommand(r) { return new c(r); } /** * You can customise the help with a subclass of Help by overriding createHelp, * or by overriding Help properties using configureHelp(). * * @return {Help} */ createHelp() { return Object.assign(new o(), this.configureHelp()); } /** * You can customise the help by overriding Help properties using configureHelp(), * or with a subclass of Help by overriding createHelp(). * * @param {object} [configuration] - configuration options * @return {(Command | object)} `this` command for chaining, or stored configuration */ configureHelp(r) { return r === void 0 ? this._helpConfiguration : (this._helpConfiguration = r, this); } /** * The default output goes to stdout and stderr. You can customise this for special * applications. You can also customise the display of errors by overriding outputError. * * The configuration properties are all functions: * * // change how output being written, defaults to stdout and stderr * writeOut(str) * writeErr(str) * // change how output being written for errors, defaults to writeErr * outputError(str, write) // used for displaying errors and not used for displaying help * // specify width for wrapping help * getOutHelpWidth() * getErrHelpWidth() * // color support, currently only used with Help * getOutHasColors() * getErrHasColors() * stripColor() // used to remove ANSI escape codes if output does not have colors * * @param {object} [configuration] - configuration options * @return {(Command | object)} `this` command for chaining, or stored configuration */ configureOutput(r) { return r === void 0 ? this._outputConfiguration : (this._outputConfiguration = { ...this._outputConfiguration, ...r }, this); } /** * Display the help or a custom message after an error occurs. * * @param {(boolean|string)} [displayHelp] * @return {Command} `this` command for chaining */ showHelpAfterError(r = !0) { return typeof r != "string" && (r = !!r), this._showHelpAfterError = r, this; } /** * Display suggestion of similar commands for unknown commands, or options for unknown options. * * @param {boolean} [displaySuggestion] * @return {Command} `this` command for chaining */ showSuggestionAfterError(r = !0) { return this._showSuggestionAfterError = !!r, this; } /** * Add a prepared subcommand. * * See .command() for creating an attached subcommand which inherits settings from its parent. * * @param {Command} cmd - new subcommand * @param {object} [opts] - configuration options * @return {Command} `this` command for chaining */ addCommand(r, b) { if (!r._name) throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); return b = b || {}, b.isDefault && (this._defaultCommandName = r._name), (b.noHelp || b.hidden) && (r._hidden = !0), this._registerCommand(r), r.parent = this, r._checkForBrokenPassThrough(), this; } /** * Factory routine to create a new unattached argument. * * See .argument() for creating an attached argument, which uses this routine to * create the argument. You can override createArgument to return a custom argument. * * @param {string} name * @param {string} [description] * @return {Argument} new argument */ createArgument(r, b) { return new i(r, b); } /** * Define argument syntax for command. * * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @example * program.argument('<input-file>'); * program.argument('[output-file]'); * * @param {string} name * @param {string} [description] * @param {(Function|*)} [parseArg] - custom argument processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ argument(r, b, w, y) { const S = this.createArgument(r, b); return typeof w == "function" ? S.default(y).argParser(w) : S.default(w), this.addArgument(S), this; } /** * Define argument syntax for command, adding multiple at once (without descriptions). * * See also .argument(). * * @example * program.arguments('<cmd> [env]'); * * @param {string} names * @return {Command} `this` command for chaining */ arguments(r) { return r.trim().split(/ +/).forEach((b) => { this.argument(b); }), this; } /** * Define argument syntax for command, adding a prepared argument. * * @param {Argument} argument * @return {Command} `this` command for chaining */ addArgument(r) { const b = this.registeredArguments.slice(-1)[0]; if (b?.variadic) throw new Error( `only the last argument can be variadic '${b.name()}'` ); if (r.required && r.defaultValue !== void 0 && r.parseArg === void 0) throw new Error( `a default value for a required argument is never used: '${r.name()}'` ); return this.registeredArguments.push(r), this; } /** * Customise or override default help command. By default a help command is automatically added if your command has subcommands. * * @example * program.helpCommand('help [cmd]'); * program.helpCommand('help [cmd]', 'show help'); * program.helpCommand(false); // suppress default help command * program.helpCommand(true); // add help command even if no subcommands * * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added * @param {string} [description] - custom description * @return {Command} `this` command for chaining */ helpCommand(r, b) { if (typeof r == "boolean") return this._addImplicitHelpCommand = r, r && this._defaultCommandGroup && this._initCommandGroup(this._getHelpCommand()), this; const w = r ?? "help [command]", [, y, S] = w.match(/([^ ]+) *(.*)/), E = b ?? "display help for command", C = this.createCommand(y); return C.helpOption(!1), S && C.arguments(S), E && C.description(E), this._addImplicitHelpCommand = !0, this._helpCommand = C, (r || b) && this._initCommandGroup(C), this; } /** * Add prepared custom help command. * * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only * @return {Command} `this` command for chaining */ addHelpCommand(r, b) { return typeof r != "object" ? (this.helpCommand(r, b), this) : (this._addImplicitHelpCommand = !0, this._helpCommand = r, this._initCommandGroup(r), this); } /** * Lazy create help command. * * @return {(Command|null)} * @package */ _getHelpCommand() { return this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help")) ? (this._helpCommand === void 0 && this.helpCommand(void 0, void 0), this._helpCommand) : null; } /** * Add hook for life cycle event. * * @param {string} event * @param {Function} listener * @return {Command} `this` command for chaining */ hook(r, b) { const w = ["preSubcommand", "preAction", "postAction"]; if (!w.includes(r)) throw new Error(`Unexpected value for event passed to hook : '${r}'. Expecting one of '${w.join("', '")}'`); return this._lifeCycleHooks[r] ? this._lifeCycleHooks[r].push(b) : this._lifeCycleHooks[r] = [b], this; } /** * Register callback to use as replacement for calling process.exit. * * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing * @return {Command} `this` command for chaining */ exitOverride(r) { return r ? this._exitCallback = r : this._exitCallback = (b) => { if (b.code !== "commander.executeSubCommandAsync") throw b; }, this; } /** * Call process.exit, and _exitCallback if defined. * * @param {number} exitCode exit code for using with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error * @return never * @private */ _exit(r, b, w) { this._exitCallback && this._exitCallback(new a(r, b, w)), f.exit(r); } /** * Register callback `fn` for the command. * * @example * program * .command('serve') * .description('start service') * .action(function() { * // do work here * }); * * @param {Function} fn * @return {Command} `this` command for chaining */ action(r) { const b = (w) => { const y = this.registeredArguments.length, S = w.slice(0, y); return this._storeOptionsAsProperties ? S[y] = this : S[y] = this.opts(), S.push(this), r.apply(this, S); }; return this._actionHandler = b, this; } /** * Factory routine to create a new unattached option. * * See .option() for creating an attached option, which uses this routine to * create the option. You can override createOption to return a custom option. * * @param {string} flags * @param {string} [description] * @return {Option} new option */ createOption(r, b) { return new n(r, b); } /** * Wrap parseArgs to catch 'commander.invalidArgument'. * * @param {(Option | Argument)} target * @param {string} value * @param {*} previous * @param {string} invalidArgumentMessage * @private */ _callParseArg(r, b, w, y) { try { return r.parseArg(b, w); } catch (S) { if (S.code === "commander.invalidArgument") { const E = `${y} ${S.message}`; this.error(E, { exitCode: S.exitCode, code: S.code }); } throw S; } } /** * Check for option flag conflicts. * Register option if no conflicts found, or throw on conflict. * * @param {Option} option * @private */ _registerOption(r) { const b = r.short && this._findOption(r.short) || r.long && this._findOption(r.long); if (b) { const w = r.long && this._findOption(r.long) ? r.long : r.short; throw new Error(`Cannot add option '${r.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${w}' - already used by option '${b.flags}'`); } this._initOptionGroup(r), this.options.push(r); } /** * Check for command name and alias conflicts with existing commands. * Register command if no conflicts found, or throw on conflict. * * @param {Command} command * @private */ _registerCommand(r) { const b = (y) => [y.name()].concat(y.aliases()), w = b(r).find( (y) => this._findCommand(y) ); if (w) { const y = b(this._findCommand(w)).join("|"), S = b(r).join("|"); throw new Error( `cannot add command '${S}' as already have command '${y}'` ); } this._initCommandGroup(r), this.commands.push(r); } /** * Add an option. * * @param {Option} option * @return {Command} `this` command for chaining */ addOption(r) { this._registerOption(r); const b = r.name(), w = r.attributeName(); if (r.negate) { const S = r.long.replace(/^--no-/, "--"); this._findOption(S) || this.setOptionValueWithSource( w, r.defaultValue === void 0 ? !0 : r.defaultValue, "default" ); } else r.defaultValue !== void 0 && this.setOptionValueWithSource(w, r.defaultValue, "default"); const y = (S, E, C) => { S == null && r.presetArg !== void 0 && (S = r.presetArg); const $ = this.getOptionValue(w); S !== null && r.parseArg ? S = this._callParseArg(r, S, $, E) : S !== null && r.variadic && (S = r._collectValue(S, $)), S == null && (r.negate ? S = !1 : r.isBoolean() || r.optional ? S = !0 : S = ""), this.setOptionValueWithSource(w, S, C); }; return this.on("option:" + b, (S) => { const E = `error: option '${r.flags}' argument '${S}' is invalid.`; y(S, E, "cli"); }), r.envVar && this.on("optionEnv:" + b, (S) => { const E = `error: option '${r.flags}' value '${S}' from env '${r.envVar}' is invalid.`; y(S, E, "env"); }), this; } /** * Internal implementation shared by .option() and .requiredOption() * * @return {Command} `this` command for chaining * @private */ _optionEx(r, b, w, y, S) { if (typeof b == "object" && b instanceof n) throw new Error( "To add an Option object use addOption() instead of option() or requiredOption()" ); const E = this.createOption(b, w); if (E.makeOptionMandatory(!!r.mandatory), typeof y == "function") E.default(S).argParser(y); else if (y instanceof RegExp) { const C = y; y = ($, _) => { const N = C.exec($); return N ? N[0] : _; }, E.default(S).argParser(y); } else E.default(y); return this.addOption(E); } /** * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required * option-argument is indicated by `<>` and an optional option-argument by `[]`. * * See the README for more details, and see also addOption() and requiredOption(). * * @example * program * .option('-p, --pepper', 'add pepper') * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function * * @param {string} flags * @param {string} [description] * @param {(Function|*)} [parseArg] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ option(r, b, w, y) { return this._optionEx({}, r, b, w, y); } /** * Add a required option which must have a value after parsing. This usually means * the option must be specified on the command line. (Otherwise the same as .option().) * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. * * @param {string} flags * @param {string} [description] * @param {(Function|*)} [parseArg] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ requiredOption(r, b, w, y) { return this._optionEx( { mandatory: !0 }, r, b, w, y ); } /** * Alter parsing of short flags with optional values. * * @example * // for `.option('-f,--flag [value]'): * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` * * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag. * @return {Command} `this` command for chaining */ combineFlagAndOptionalValue(r = !0) { return this._combineFlagAndOptionalValue = !!r, this; } /** * Allow unknown