UNPKG

@arcgis/create

Version:

ArcGIS command line tool to create new web GIS projects and applications

1,413 lines • 298 kB
import mi from "node:events"; import gi from "node:child_process"; import Ci from "node:path"; import Ei from "node:fs"; import J, { stdin as Br, stdout as Pr } from "node:process"; import De from "fs/promises"; import Me from "path"; import Ve from "process"; import Fi from "child_process"; import bi, { promisify as Ai } from "util"; import Rr from "url"; import vi from "node:module"; import * as Se from "node:readline"; import Bt from "node:readline"; import Pt, { WriteStream as yi } from "node:tty"; import wi from "node:os"; function Ue(s) { return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s; } var Oe = { exports: {} }, ee = {}, _e = {}, xe = {}, Rt; function je() { if (Rt) return xe; Rt = 1; class s 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(h, n, r) { super(r), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name, this.code = n, this.exitCode = h, this.nestedError = void 0; } } class i extends s { /** * Constructs the InvalidArgumentError class * @param {string} [message] explanation of why argument is invalid */ constructor(h) { super(1, "commander.invalidArgument", h), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name; } } return xe.CommanderError = s, xe.InvalidArgumentError = i, xe; } var It; function yt() { if (It) return _e; It = 1; const { InvalidArgumentError: s } = je(); class i { /** * 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(n, r) { switch (this.description = r || "", this.variadic = !1, this.parseArg = void 0, this.defaultValue = void 0, this.defaultValueDescription = void 0, this.argChoices = void 0, n[0]) { case "<": this.required = !0, this._name = n.slice(1, -1); break; case "[": this.required = !1, this._name = n.slice(1, -1); break; default: this.required = !0, this._name = n; break; } this._name.length > 3 && this._name.slice(-3) === "..." && (this.variadic = !0, this._name = this._name.slice(0, -3)); } /** * Return argument name. * * @return {string} */ name() { return this._name; } /** * @package */ _concatValue(n, r) { return r === this.defaultValue || !Array.isArray(r) ? [n] : r.concat(n); } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Argument} */ default(n, r) { return this.defaultValue = n, this.defaultValueDescription = r, this; } /** * Set the custom handler for processing CLI command arguments into argument values. * * @param {Function} [fn] * @return {Argument} */ argParser(n) { return this.parseArg = n, this; } /** * Only allow argument value to be one of choices. * * @param {string[]} values * @return {Argument} */ choices(n) { return this.argChoices = n.slice(), this.parseArg = (r, e) => { if (!this.argChoices.includes(r)) throw new s( `Allowed choices are ${this.argChoices.join(", ")}.` ); return this.variadic ? this._concatValue(r, e) : r; }, this; } /** * Make argument required. * * @returns {Argument} */ argRequired() { return this.required = !0, this; } /** * Make argument optional. * * @returns {Argument} */ argOptional() { return this.required = !1, this; } } function o(h) { const n = h.name() + (h.variadic === !0 ? "..." : ""); return h.required ? "<" + n + ">" : "[" + n + "]"; } return _e.Argument = i, _e.humanReadableArgName = o, _e; } var $e = {}, Be = {}, Nt; function Ir() { if (Nt) return Be; Nt = 1; const { humanReadableArgName: s } = yt(); class i { 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(n) { this.helpWidth = this.helpWidth ?? n.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(n) { const r = n.commands.filter((a) => !a._hidden), e = n._getHelpCommand(); return e && !e._hidden && r.push(e), this.sortSubcommands && r.sort((a, l) => a.name().localeCompare(l.name())), r; } /** * Compare options for sort. * * @param {Option} a * @param {Option} b * @returns {number} */ compareOptions(n, r) { const e = (a) => a.short ? a.short.replace(/^-/, "") : a.long.replace(/^--/, ""); return e(n).localeCompare(e(r)); } /** * 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(n) { const r = n.options.filter((a) => !a.hidden), e = n._getHelpOption(); if (e && !e.hidden) { const a = e.short && n._findOption(e.short), l = e.long && n._findOption(e.long); !a && !l ? r.push(e) : e.long && !l ? r.push( n.createOption(e.long, e.description) ) : e.short && !a && r.push( n.createOption(e.short, e.description) ); } return this.sortOptions && r.sort(this.compareOptions), r; } /** * Get an array of the visible global options. (Not including help.) * * @param {Command} cmd * @returns {Option[]} */ visibleGlobalOptions(n) { if (!this.showGlobalOptions) return []; const r = []; for (let e = n.parent; e; e = e.parent) { const a = e.options.filter( (l) => !l.hidden ); r.push(...a); } return this.sortOptions && r.sort(this.compareOptions), r; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(n) { return n._argsDescription && n.registeredArguments.forEach((r) => { r.description = r.description || n._argsDescription[r.name()] || ""; }), n.registeredArguments.find((r) => r.description) ? n.registeredArguments : []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(n) { const r = n.registeredArguments.map((e) => s(e)).join(" "); return n._name + (n._aliases[0] ? "|" + n._aliases[0] : "") + (n.options.length ? " [options]" : "") + // simplistic check for non-help option (r ? " " + r : ""); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(n) { return n.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(n) { return n.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(n, r) { return r.visibleCommands(n).reduce((e, a) => Math.max( e, this.displayWidth( r.styleSubcommandTerm(r.subcommandTerm(a)) ) ), 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(n, r) { return r.visibleOptions(n).reduce((e, a) => Math.max( e, this.displayWidth(r.styleOptionTerm(r.optionTerm(a))) ), 0); } /** * Get the longest global option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestGlobalOptionTermLength(n, r) { return r.visibleGlobalOptions(n).reduce((e, a) => Math.max( e, this.displayWidth(r.styleOptionTerm(r.optionTerm(a))) ), 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(n, r) { return r.visibleArguments(n).reduce((e, a) => Math.max( e, this.displayWidth( r.styleArgumentTerm(r.argumentTerm(a)) ) ), 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(n) { let r = n._name; n._aliases[0] && (r = r + "|" + n._aliases[0]); let e = ""; for (let a = n.parent; a; a = a.parent) e = a.name() + " " + e; return e + r + " " + n.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(n) { return n.description(); } /** * Get the subcommand summary to show in the list of subcommands. * (Fallback to description for backwards compatibility.) * * @param {Command} cmd * @returns {string} */ subcommandDescription(n) { return n.summary() || n.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(n) { const r = []; if (n.argChoices && r.push( // use stringify to match the display of the default value `choices: ${n.argChoices.map((e) => JSON.stringify(e)).join(", ")}` ), n.defaultValue !== void 0 && (n.required || n.optional || n.isBoolean() && typeof n.defaultValue == "boolean") && r.push( `default: ${n.defaultValueDescription || JSON.stringify(n.defaultValue)}` ), n.presetArg !== void 0 && n.optional && r.push(`preset: ${JSON.stringify(n.presetArg)}`), n.envVar !== void 0 && r.push(`env: ${n.envVar}`), r.length > 0) { const e = `(${r.join(", ")})`; return n.description ? `${n.description} ${e}` : e; } return n.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(n) { const r = []; if (n.argChoices && r.push( // use stringify to match the display of the default value `choices: ${n.argChoices.map((e) => JSON.stringify(e)).join(", ")}` ), n.defaultValue !== void 0 && r.push( `default: ${n.defaultValueDescription || JSON.stringify(n.defaultValue)}` ), r.length > 0) { const e = `(${r.join(", ")})`; return n.description ? `${n.description} ${e}` : e; } return n.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(n, r, e) { return r.length === 0 ? [] : [e.styleTitle(n), ...r, ""]; } /** * Group items by their help group heading. * * @param {Command[] | Option[]} unsortedItems * @param {Command[] | Option[]} visibleItems * @param {Function} getGroup * @returns {Map<string, Command[] | Option[]>} */ groupItems(n, r, e) { const a = /* @__PURE__ */ new Map(); return n.forEach((l) => { const C = e(l); a.has(C) || a.set(C, []); }), r.forEach((l) => { const C = e(l); a.has(C) || a.set(C, []), a.get(C).push(l); }), a; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(n, r) { const e = r.padWidth(n, r), a = r.helpWidth ?? 80; function l(d, f) { return r.formatItem(d, e, f, r); } let C = [ `${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(n))}`, "" ]; const m = r.commandDescription(n); m.length > 0 && (C = C.concat([ r.boxWrap( r.styleCommandDescription(m), a ), "" ])); const v = r.visibleArguments(n).map((d) => l( r.styleArgumentTerm(r.argumentTerm(d)), r.styleArgumentDescription(r.argumentDescription(d)) )); if (C = C.concat( this.formatItemList("Arguments:", v, r) ), this.groupItems( n.options, r.visibleOptions(n), (d) => d.helpGroupHeading ?? "Options:" ).forEach((d, f) => { const A = d.map((t) => l( r.styleOptionTerm(r.optionTerm(t)), r.styleOptionDescription(r.optionDescription(t)) )); C = C.concat(this.formatItemList(f, A, r)); }), r.showGlobalOptions) { const d = r.visibleGlobalOptions(n).map((f) => l( r.styleOptionTerm(r.optionTerm(f)), r.styleOptionDescription(r.optionDescription(f)) )); C = C.concat( this.formatItemList("Global Options:", d, r) ); } return this.groupItems( n.commands, r.visibleCommands(n), (d) => d.helpGroup() || "Commands:" ).forEach((d, f) => { const A = d.map((t) => l( r.styleSubcommandTerm(r.subcommandTerm(t)), r.styleSubcommandDescription(r.subcommandDescription(t)) )); C = C.concat(this.formatItemList(f, A, r)); }), C.join(` `); } /** * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. * * @param {string} str * @returns {number} */ displayWidth(n) { return o(n).length; } /** * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. * * @param {string} str * @returns {string} */ styleTitle(n) { return n; } styleUsage(n) { return n.split(" ").map((r) => r === "[options]" ? this.styleOptionText(r) : r === "[command]" ? this.styleSubcommandText(r) : r[0] === "[" || r[0] === "<" ? this.styleArgumentText(r) : this.styleCommandText(r)).join(" "); } styleCommandDescription(n) { return this.styleDescriptionText(n); } styleOptionDescription(n) { return this.styleDescriptionText(n); } styleSubcommandDescription(n) { return this.styleDescriptionText(n); } styleArgumentDescription(n) { return this.styleDescriptionText(n); } styleDescriptionText(n) { return n; } styleOptionTerm(n) { return this.styleOptionText(n); } styleSubcommandTerm(n) { return n.split(" ").map((r) => r === "[options]" ? this.styleOptionText(r) : r[0] === "[" || r[0] === "<" ? this.styleArgumentText(r) : this.styleSubcommandText(r)).join(" "); } styleArgumentTerm(n) { return this.styleArgumentText(n); } styleOptionText(n) { return n; } styleArgumentText(n) { return n; } styleSubcommandText(n) { return n; } styleCommandText(n) { return n; } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(n, r) { return Math.max( r.longestOptionTermLength(n, r), r.longestGlobalOptionTermLength(n, r), r.longestSubcommandTermLength(n, r), r.longestArgumentTermLength(n, r) ); } /** * Detect manually wrapped and indented strings by checking for line break followed by whitespace. * * @param {string} str * @returns {boolean} */ preformatted(n) { return /\n[^\S\r\n]/.test(n); } /** * 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(n, r, e, a) { const C = " ".repeat(2); if (!e) return C + n; const m = n.padEnd( r + n.length - a.displayWidth(n) ), v = 2, D = (this.helpWidth ?? 80) - r - v - 2; let d; return D < this.minWidthToWrap || a.preformatted(e) ? d = e : d = a.boxWrap(e, D).replace( /\n/g, ` ` + " ".repeat(r + v) ), C + m + " ".repeat(v) + d.replace(/\n/g, ` ${C}`); } /** * 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(n, r) { if (r < this.minWidthToWrap) return n; const e = n.split(/\r\n|\n/), a = /[\s]*[^\s]+/g, l = []; return e.forEach((C) => { const m = C.match(a); if (m === null) { l.push(""); return; } let v = [m.shift()], w = this.displayWidth(v[0]); m.forEach((D) => { const d = this.displayWidth(D); if (w + d <= r) { v.push(D), w += d; return; } l.push(v.join("")); const f = D.trimStart(); v = [f], w = this.displayWidth(f); }), l.push(v.join("")); }), l.join(` `); } } function o(h) { const n = /\x1b\[\d*(;\d*)*m/g; return h.replace(n, ""); } return Be.Help = i, Be.stripColor = o, Be; } var Pe = {}, Tt; function Nr() { if (Tt) return Pe; Tt = 1; const { InvalidArgumentError: s } = je(); class i { /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {string} flags * @param {string} [description] */ constructor(e, a) { this.flags = e, this.description = a || "", this.required = e.includes("<"), this.optional = e.includes("["), this.variadic = /\w\.\.\.[>\]]$/.test(e), this.mandatory = !1; const l = n(e); this.short = l.shortFlag, this.long = l.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(e, a) { return this.defaultValue = e, 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(e) { return this.presetArg = e, 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(e) { return this.conflictsWith = this.conflictsWith.concat(e), 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(e) { let a = e; return typeof e == "string" && (a = { [e]: !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(e) { return this.envVar = e, this; } /** * Set the custom handler for processing CLI option arguments into option values. * * @param {Function} [fn] * @return {Option} */ argParser(e) { return this.parseArg = e, this; } /** * Whether the option is mandatory and must have a value after parsing. * * @param {boolean} [mandatory=true] * @return {Option} */ makeOptionMandatory(e = !0) { return this.mandatory = !!e, this; } /** * Hide option in help. * * @param {boolean} [hide=true] * @return {Option} */ hideHelp(e = !0) { return this.hidden = !!e, this; } /** * @package */ _concatValue(e, a) { return a === this.defaultValue || !Array.isArray(a) ? [e] : a.concat(e); } /** * Only allow option value to be one of choices. * * @param {string[]} values * @return {Option} */ choices(e) { return this.argChoices = e.slice(), this.parseArg = (a, l) => { if (!this.argChoices.includes(a)) throw new s( `Allowed choices are ${this.argChoices.join(", ")}.` ); return this.variadic ? this._concatValue(a, l) : 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 ? h(this.name().replace(/^no-/, "")) : h(this.name()); } /** * Set the help group heading. * * @param {string} heading * @return {Option} */ helpGroup(e) { return this.helpGroupHeading = e, this; } /** * Check if `arg` matches the short or long flag. * * @param {string} arg * @return {boolean} * @package */ is(e) { return this.short === e || this.long === e; } /** * 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 o { /** * @param {Option[]} options */ constructor(e) { this.positiveOptions = /* @__PURE__ */ new Map(), this.negativeOptions = /* @__PURE__ */ new Map(), this.dualOptions = /* @__PURE__ */ new Set(), e.forEach((a) => { a.negate ? this.negativeOptions.set(a.attributeName(), a) : this.positiveOptions.set(a.attributeName(), a); }), this.negativeOptions.forEach((a, l) => { this.positiveOptions.has(l) && this.dualOptions.add(l); }); } /** * Did the value come from the option, and not from possible matching dual option? * * @param {*} value * @param {Option} option * @returns {boolean} */ valueFromOption(e, a) { const l = a.attributeName(); if (!this.dualOptions.has(l)) return !0; const C = this.negativeOptions.get(l).presetArg, m = C !== void 0 ? C : !1; return a.negate === (m === e); } } function h(r) { return r.split("-").reduce((e, a) => e + a[0].toUpperCase() + a.slice(1)); } function n(r) { let e, a; const l = /^-[^-]$/, C = /^--[^-]/, m = r.split(/[ |,]+/).concat("guard"); if (l.test(m[0]) && (e = m.shift()), C.test(m[0]) && (a = m.shift()), !e && l.test(m[0]) && (e = m.shift()), !e && C.test(m[0]) && (e = a, a = m.shift()), m[0].startsWith("-")) { const v = m[0], w = `option creation failed due to '${v}' in option flags '${r}'`; throw /^-[^-][^-]/.test(v) ? new Error( `${w} - 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')` ) : l.test(v) ? new Error(`${w} - too many short flags`) : C.test(v) ? new Error(`${w} - too many long flags`) : new Error(`${w} - unrecognised flag format`); } if (e === void 0 && a === void 0) throw new Error( `option creation failed due to no flags found in '${r}'.` ); return { shortFlag: e, longFlag: a }; } return Pe.Option = i, Pe.DualOptions = o, Pe; } var qe = {}, Mt; function Li() { if (Mt) return qe; Mt = 1; const s = 3; function i(h, n) { if (Math.abs(h.length - n.length) > s) return Math.max(h.length, n.length); const r = []; for (let e = 0; e <= h.length; e++) r[e] = [e]; for (let e = 0; e <= n.length; e++) r[0][e] = e; for (let e = 1; e <= n.length; e++) for (let a = 1; a <= h.length; a++) { let l = 1; h[a - 1] === n[e - 1] ? l = 0 : l = 1, r[a][e] = Math.min( r[a - 1][e] + 1, // deletion r[a][e - 1] + 1, // insertion r[a - 1][e - 1] + l // substitution ), a > 1 && e > 1 && h[a - 1] === n[e - 2] && h[a - 2] === n[e - 1] && (r[a][e] = Math.min(r[a][e], r[a - 2][e - 2] + 1)); } return r[h.length][n.length]; } function o(h, n) { if (!n || n.length === 0) return ""; n = Array.from(new Set(n)); const r = h.startsWith("--"); r && (h = h.slice(2), n = n.map((C) => C.slice(2))); let e = [], a = s; const l = 0.4; return n.forEach((C) => { if (C.length <= 1) return; const m = i(h, C), v = Math.max(h.length, C.length); (v - m) / v > l && (m < a ? (a = m, e = [C]) : m === a && e.push(C)); }), e.sort((C, m) => C.localeCompare(m)), r && (e = e.map((C) => `--${C}`)), e.length > 1 ? ` (Did you mean one of ${e.join(", ")}?)` : e.length === 1 ? ` (Did you mean ${e[0]}?)` : ""; } return qe.suggestSimilar = o, qe; } var Gt; function Si() { if (Gt) return $e; Gt = 1; const s = mi.EventEmitter, i = gi, o = Ci, h = Ei, n = J, { Argument: r, humanReadableArgName: e } = yt(), { CommanderError: a } = je(), { Help: l, stripColor: C } = Ir(), { Option: m, DualOptions: v } = Nr(), { suggestSimilar: w } = Li(); class D extends s { /** * Initialize a new `Command`. * * @param {string} [name] */ constructor(t) { 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 = t || "", 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: (c) => n.stdout.write(c), writeErr: (c) => n.stderr.write(c), outputError: (c, g) => g(c), getOutHelpWidth: () => n.stdout.isTTY ? n.stdout.columns : void 0, getErrHelpWidth: () => n.stderr.isTTY ? n.stderr.columns : void 0, getOutHasColors: () => f() ?? (n.stdout.isTTY && n.stdout.hasColors?.()), getErrHasColors: () => f() ?? (n.stderr.isTTY && n.stderr.hasColors?.()), stripColor: (c) => C(c) }, 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(t) { return this._outputConfiguration = t._outputConfiguration, this._helpOption = t._helpOption, this._helpCommand = t._helpCommand, this._helpConfiguration = t._helpConfiguration, this._exitCallback = t._exitCallback, this._storeOptionsAsProperties = t._storeOptionsAsProperties, this._combineFlagAndOptionalValue = t._combineFlagAndOptionalValue, this._allowExcessArguments = t._allowExcessArguments, this._enablePositionalOptions = t._enablePositionalOptions, this._showHelpAfterError = t._showHelpAfterError, this._showSuggestionAfterError = t._showSuggestionAfterError, this; } /** * @returns {Command[]} * @private */ _getCommandAndAncestors() { const t = []; for (let c = this; c; c = c.parent) t.push(c); return t; } /** * 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(t, c, g) { let u = c, p = g; typeof u == "object" && u !== null && (p = u, u = null), p = p || {}; const [, y, L] = t.match(/([^ ]+) *(.*)/), O = this.createCommand(y); return u && (O.description(u), O._executableHandler = !0), p.isDefault && (this._defaultCommandName = O._name), O._hidden = !!(p.noHelp || p.hidden), O._executableFile = p.executableFile || null, L && O.arguments(L), this._registerCommand(O), O.parent = this, O.copyInheritedSettings(this), u ? this : O; } /** * 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(t) { return new D(t); } /** * 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 l(), 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(t) { return t === void 0 ? this._helpConfiguration : (this._helpConfiguration = t, 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(t) { return t === void 0 ? this._outputConfiguration : (this._outputConfiguration = Object.assign( {}, this._outputConfiguration, t ), this); } /** * Display the help or a custom message after an error occurs. * * @param {(boolean|string)} [displayHelp] * @return {Command} `this` command for chaining */ showHelpAfterError(t = !0) { return typeof t != "string" && (t = !!t), this._showHelpAfterError = t, this; } /** * Display suggestion of similar commands for unknown commands, or options for unknown options. * * @param {boolean} [displaySuggestion] * @return {Command} `this` command for chaining */ showSuggestionAfterError(t = !0) { return this._showSuggestionAfterError = !!t, 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(t, c) { if (!t._name) throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); return c = c || {}, c.isDefault && (this._defaultCommandName = t._name), (c.noHelp || c.hidden) && (t._hidden = !0), this._registerCommand(t), t.parent = this, t._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(t, c) { return new r(t, c); } /** * 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(t, c, g, u) { const p = this.createArgument(t, c); return typeof g == "function" ? p.default(u).argParser(g) : p.default(g), this.addArgument(p), 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(t) { return t.trim().split(/ +/).forEach((c) => { this.argument(c); }), this; } /** * Define argument syntax for command, adding a prepared argument. * * @param {Argument} argument * @return {Command} `this` command for chaining */ addArgument(t) { const c = this.registeredArguments.slice(-1)[0]; if (c && c.variadic) throw new Error( `only the last argument can be variadic '${c.name()}'` ); if (t.required && t.defaultValue !== void 0 && t.parseArg === void 0) throw new Error( `a default value for a required argument is never used: '${t.name()}'` ); return this.registeredArguments.push(t), 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(t, c) { if (typeof t == "boolean") return this._addImplicitHelpCommand = t, t && this._defaultCommandGroup && this._initCommandGroup(this._getHelpCommand()), this; const g = t ?? "help [command]", [, u, p] = g.match(/([^ ]+) *(.*)/), y = c ?? "display help for command", L = this.createCommand(u); return L.helpOption(!1), p && L.arguments(p), y && L.description(y), this._addImplicitHelpCommand = !0, this._helpCommand = L, (t || c) && this._initCommandGroup(L), 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(t, c) { return typeof t != "object" ? (this.helpCommand(t, c), this) : (this._addImplicitHelpCommand = !0, this._helpCommand = t, this._initCommandGroup(t), 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(t, c) { const g = ["preSubcommand", "preAction", "postAction"]; if (!g.includes(t)) throw new Error(`Unexpected value for event passed to hook : '${t}'. Expecting one of '${g.join("', '")}'`); return this._lifeCycleHooks[t] ? this._lifeCycleHooks[t].push(c) : this._lifeCycleHooks[t] = [c], 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(t) { return t ? this._exitCallback = t : this._exitCallback = (c) => { if (c.code !== "commander.executeSubCommandAsync") throw c; }, 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(t, c, g) { this._exitCallback && this._exitCallback(new a(t, c, g)), n.exit(t); } /** * 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(t) { const c = (g) => { const u = this.registeredArguments.length, p = g.slice(0, u); return this._storeOptionsAsProperties ? p[u] = this : p[u] = this.opts(), p.push(this), t.apply(this, p); }; return this._actionHandler = c, 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(t, c) { return new m(t, c); } /** * Wrap parseArgs to catch 'commander.invalidArgument'. * * @param {(Option | Argument)} target * @param {string} value * @param {*} previous * @param {string} invalidArgumentMessage * @private */ _callParseArg(t, c, g, u) { try { return t.parseArg(c, g); } catch (p) { if (p.code === "commander.invalidArgument") { const y = `${u} ${p.message}`; this.error(y, { exitCode: p.exitCode, code: p.code }); } throw p; } } /** * Check for option flag conflicts. * Register option if no conflicts found, or throw on conflict. * * @param {Option} option * @private */ _registerOption(t) { const c = t.short && this._findOption(t.short) || t.long && this._findOption(t.long); if (c) { const g = t.long && this._findOption(t.long) ? t.long : t.short; throw new Error(`Cannot add option '${t.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${g}' - already used by option '${c.flags}'`); } this._initOptionGroup(t), this.options.push(t); } /** * 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(t) { const c = (u) => [u.name()].concat(u.aliases()), g = c(t).find( (u) => this._findCommand(u) ); if (g) { const u = c(this._findCommand(g)).join("|"), p = c(t).join("|"); throw new Error( `cannot add command '${p}' as already have command '${u}'` ); } this._initCommandGroup(t), this.commands.push(t); } /** * Add an option. * * @param {Option} option * @return {Command} `this` command for chaining */ addOption(t) { this._registerOption(t); const c = t.name(), g = t.attributeName(); if (t.negate) { const p = t.long.replace(/^--no-/, "--"); this._findOption(p) || this.setOptionValueWithSource( g, t.defaultValue === void 0 ? !0 : t.defaultValue, "default" ); } else t.defaultValue !== void 0 && this.setOptionValueWithSource(g, t.defaultValue, "default"); const u = (p, y, L) => { p == null && t.presetArg !== void 0 && (p = t.presetArg); const O = this.getOptionValue(g); p !== null && t.parseArg ? p = this._callParseArg(t, p, O, y) : p !== null && t.variadic && (p = t._concatValue(p, O)), p == null && (t.negate ? p = !1 : t.isBoolean() || t.optional ? p = !0 : p = ""), this.setOptionValueWithSource(g, p, L); }; return this.on("option:" + c, (p) => { const y = `error: option '${t.flags}' argument '${p}' is invalid.`; u(p, y, "cli"); }), t.envVar && this.on("optionEnv:" + c, (p) => { const y = `error: option '${t.flags}' value '${p}' from env '${t.envVar}' is invalid.`; u(p, y, "env"); }), this; } /** * Internal implementation shared by .option() and .requiredOption() * * @return {Command} `this` command for chaining * @private */ _optionEx(t, c, g, u, p) { if (typeof c == "object" && c instanceof m) throw new Error( "To add an Option object use addOption() instead of option() or requiredOption()" ); const y = this.createOption(c, g); if (y.makeOptionMandatory(!!t.mandatory), typeof u == "function") y.default(p).argParser(u); else if (u instanceof RegExp) { const L = u; u = (O, $) => { const P = L.exec(O); return P ? P[0] : $; }, y.default(p).argParser(u); } else y.default(u); return this.addOption(y); } /** * 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(t, c, g, u) { return this._optionEx({}, t, c, g, u); } /** * 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(t, c, g, u) { return this._optionEx( { mandatory: !0 }, t, c, g, u ); } /** * 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(t = !0) { return this._combineFlagAndOptionalValue = !!t, this; } /** * Allow unknown options on