UNPKG

@arcgis/create

Version:

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

1,321 lines 315 kB
import Mn from "events"; import Qr from "child_process"; import Fe from "path"; import kn from "fs"; import Ne from "process"; import le from "fs/promises"; import Gn, { promisify as Hn } from "util"; import en from "url"; import jn from "node:module"; import Z, { stdin as tn, stdout as rn } from "node:process"; import * as Se from "node:readline"; import Gt from "node:readline"; import Ht, { WriteStream as Un } from "node:tty"; import Wn from "node:os"; import Vn from "os"; import qn from "tty"; function He(l) { return l && l.__esModule && Object.prototype.hasOwnProperty.call(l, "default") ? l.default : l; } var Oe = { exports: {} }, $e = { exports: {} }, _e = {}, xe = {}, jt; function je() { if (jt) return xe; jt = 1; class l 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 */ constructor(u, r, t) { super(t), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name, this.code = r, this.exitCode = u, this.nestedError = void 0; } } class o extends l { /** * Constructs the InvalidArgumentError class * @param {string} [message] explanation of why argument is invalid * @constructor */ constructor(u) { super(1, "commander.invalidArgument", u), Error.captureStackTrace(this, this.constructor), this.name = this.constructor.name; } } return xe.CommanderError = l, xe.InvalidArgumentError = o, xe; } var Ut; function Nt() { if (Ut) return _e; Ut = 1; const { InvalidArgumentError: l } = je(); class o { /** * 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(r, t) { switch (this.description = t || "", this.variadic = !1, this.parseArg = void 0, this.defaultValue = void 0, this.defaultValueDescription = void 0, this.argChoices = void 0, r[0]) { case "<": this.required = !0, this._name = r.slice(1, -1); break; case "[": this.required = !1, this._name = r.slice(1, -1); break; default: this.required = !0, this._name = r; 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; } /** * @api private */ _concatValue(r, t) { return t === this.defaultValue || !Array.isArray(t) ? [r] : t.concat(r); } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Argument} */ default(r, t) { return this.defaultValue = r, this.defaultValueDescription = t, this; } /** * Set the custom handler for processing CLI command arguments into argument values. * * @param {Function} [fn] * @return {Argument} */ argParser(r) { return this.parseArg = r, this; } /** * Only allow argument value to be one of choices. * * @param {string[]} values * @return {Argument} */ choices(r) { return this.argChoices = r.slice(), this.parseArg = (t, e) => { if (!this.argChoices.includes(t)) throw new l(`Allowed choices are ${this.argChoices.join(", ")}.`); return this.variadic ? this._concatValue(t, e) : t; }, this; } /** * Make argument required. */ argRequired() { return this.required = !0, this; } /** * Make argument optional. */ argOptional() { return this.required = !1, this; } } function a(u) { const r = u.name() + (u.variadic === !0 ? "..." : ""); return u.required ? "<" + r + ">" : "[" + r + "]"; } return _e.Argument = o, _e.humanReadableArgName = a, _e; } var We = {}, Ve = {}, Wt; function nn() { if (Wt) return Ve; Wt = 1; const { humanReadableArgName: l } = Nt(); class o { constructor() { this.helpWidth = void 0, this.sortSubcommands = !1, this.sortOptions = !1, this.showGlobalOptions = !1; } /** * 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(u) { const r = u.commands.filter((t) => !t._hidden); if (u._hasImplicitHelpCommand()) { const [, t, e] = u._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/), n = u.createCommand(t).helpOption(!1); n.description(u._helpCommandDescription), e && n.arguments(e), r.push(n); } return this.sortSubcommands && r.sort((t, e) => t.name().localeCompare(e.name())), r; } /** * Compare options for sort. * * @param {Option} a * @param {Option} b * @returns number */ compareOptions(u, r) { const t = (e) => e.short ? e.short.replace(/^-/, "") : e.long.replace(/^--/, ""); return t(u).localeCompare(t(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(u) { const r = u.options.filter((n) => !n.hidden), t = u._hasHelpOption && u._helpShortFlag && !u._findOption(u._helpShortFlag), e = u._hasHelpOption && !u._findOption(u._helpLongFlag); if (t || e) { let n; t ? e ? n = u.createOption(u._helpFlags, u._helpDescription) : n = u.createOption(u._helpShortFlag, u._helpDescription) : n = u.createOption(u._helpLongFlag, u._helpDescription), r.push(n); } 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(u) { if (!this.showGlobalOptions) return []; const r = []; for (let t = u.parent; t; t = t.parent) { const e = t.options.filter((n) => !n.hidden); r.push(...e); } 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(u) { return u._argsDescription && u.registeredArguments.forEach((r) => { r.description = r.description || u._argsDescription[r.name()] || ""; }), u.registeredArguments.find((r) => r.description) ? u.registeredArguments : []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(u) { const r = u.registeredArguments.map((t) => l(t)).join(" "); return u._name + (u._aliases[0] ? "|" + u._aliases[0] : "") + (u.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(u) { return u.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(u) { return u.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(u, r) { return r.visibleCommands(u).reduce((t, e) => Math.max(t, r.subcommandTerm(e).length), 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(u, r) { return r.visibleOptions(u).reduce((t, e) => Math.max(t, r.optionTerm(e).length), 0); } /** * Get the longest global option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestGlobalOptionTermLength(u, r) { return r.visibleGlobalOptions(u).reduce((t, e) => Math.max(t, r.optionTerm(e).length), 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(u, r) { return r.visibleArguments(u).reduce((t, e) => Math.max(t, r.argumentTerm(e).length), 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(u) { let r = u._name; u._aliases[0] && (r = r + "|" + u._aliases[0]); let t = ""; for (let e = u.parent; e; e = e.parent) t = e.name() + " " + t; return t + r + " " + u.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(u) { return u.description(); } /** * Get the subcommand summary to show in the list of subcommands. * (Fallback to description for backwards compatibility.) * * @param {Command} cmd * @returns {string} */ subcommandDescription(u) { return u.summary() || u.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(u) { const r = []; return u.argChoices && r.push( // use stringify to match the display of the default value `choices: ${u.argChoices.map((t) => JSON.stringify(t)).join(", ")}` ), u.defaultValue !== void 0 && (u.required || u.optional || u.isBoolean() && typeof u.defaultValue == "boolean") && r.push(`default: ${u.defaultValueDescription || JSON.stringify(u.defaultValue)}`), u.presetArg !== void 0 && u.optional && r.push(`preset: ${JSON.stringify(u.presetArg)}`), u.envVar !== void 0 && r.push(`env: ${u.envVar}`), r.length > 0 ? `${u.description} (${r.join(", ")})` : u.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(u) { const r = []; if (u.argChoices && r.push( // use stringify to match the display of the default value `choices: ${u.argChoices.map((t) => JSON.stringify(t)).join(", ")}` ), u.defaultValue !== void 0 && r.push(`default: ${u.defaultValueDescription || JSON.stringify(u.defaultValue)}`), r.length > 0) { const t = `(${r.join(", ")})`; return u.description ? `${u.description} ${t}` : t; } return u.description; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(u, r) { const t = r.padWidth(u, r), e = r.helpWidth || 80, n = 2, s = 2; function m(F, i) { if (i) { const D = `${F.padEnd(t + s)}${i}`; return r.wrap(D, e - n, t + s); } return F; } function h(F) { return F.join(` `).replace(/^/gm, " ".repeat(n)); } let p = [`Usage: ${r.commandUsage(u)}`, ""]; const b = r.commandDescription(u); b.length > 0 && (p = p.concat([r.wrap(b, e, 0), ""])); const f = r.visibleArguments(u).map((F) => m(r.argumentTerm(F), r.argumentDescription(F))); f.length > 0 && (p = p.concat(["Arguments:", h(f), ""])); const d = r.visibleOptions(u).map((F) => m(r.optionTerm(F), r.optionDescription(F))); if (d.length > 0 && (p = p.concat(["Options:", h(d), ""])), this.showGlobalOptions) { const F = r.visibleGlobalOptions(u).map((i) => m(r.optionTerm(i), r.optionDescription(i))); F.length > 0 && (p = p.concat(["Global Options:", h(F), ""])); } const C = r.visibleCommands(u).map((F) => m(r.subcommandTerm(F), r.subcommandDescription(F))); return C.length > 0 && (p = p.concat(["Commands:", h(C), ""])), p.join(` `); } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(u, r) { return Math.max( r.longestOptionTermLength(u, r), r.longestGlobalOptionTermLength(u, r), r.longestSubcommandTermLength(u, r), r.longestArgumentTermLength(u, r) ); } /** * Wrap the given string to width characters per line, with lines after the first indented. * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. * * @param {string} str * @param {number} width * @param {number} indent * @param {number} [minColumnWidth=40] * @return {string} * */ wrap(u, r, t, e = 40) { const n = " \\f\\t\\v   -    \uFEFF", s = new RegExp(`[\\n][${n}]+`); if (u.match(s)) return u; const m = r - t; if (m < e) return u; const h = u.slice(0, t), p = u.slice(t).replace(`\r `, ` `), b = " ".repeat(t), d = "\\s​", C = new RegExp(` |.{1,${m - 1}}([${d}]|$)|[^${d}]+?([${d}]|$)`, "g"), F = p.match(C) || []; return h + F.map((i, D) => i === ` ` ? "" : (D > 0 ? b : "") + i.trimEnd()).join(` `); } } return Ve.Help = o, Ve; } var Ce = {}, Vt; function sn() { if (Vt) return Ce; Vt = 1; const { InvalidArgumentError: l } = je(); class o { /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {string} flags * @param {string} [description] */ constructor(e, n) { this.flags = e, this.description = n || "", this.required = e.includes("<"), this.optional = e.includes("["), this.variadic = /\w\.\.\.[>\]]$/.test(e), this.mandatory = !1; const s = r(e); this.short = s.shortFlag, this.long = s.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; } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Option} */ default(e, n) { return this.defaultValue = e, this.defaultValueDescription = n, 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 n = e; return typeof e == "string" && (n = { [e]: !0 }), this.implied = Object.assign(this.implied || {}, n), 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; } /** * @api private */ _concatValue(e, n) { return n === this.defaultValue || !Array.isArray(n) ? [e] : n.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 = (n, s) => { if (!this.argChoices.includes(n)) throw new l(`Allowed choices are ${this.argChoices.join(", ")}.`); return this.variadic ? this._concatValue(n, s) : n; }, 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 a object attribute key. * * @return {string} * @api private */ attributeName() { return u(this.name().replace(/^no-/, "")); } /** * Check if `arg` matches the short or long flag. * * @param {string} arg * @return {boolean} * @api private */ 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} * @api private */ isBoolean() { return !this.required && !this.optional && !this.negate; } } class a { /** * @param {Option[]} options */ constructor(e) { this.positiveOptions = /* @__PURE__ */ new Map(), this.negativeOptions = /* @__PURE__ */ new Map(), this.dualOptions = /* @__PURE__ */ new Set(), e.forEach((n) => { n.negate ? this.negativeOptions.set(n.attributeName(), n) : this.positiveOptions.set(n.attributeName(), n); }), this.negativeOptions.forEach((n, s) => { this.positiveOptions.has(s) && this.dualOptions.add(s); }); } /** * Did the value come from the option, and not from possible matching dual option? * * @param {*} value * @param {Option} option * @returns {boolean} */ valueFromOption(e, n) { const s = n.attributeName(); if (!this.dualOptions.has(s)) return !0; const m = this.negativeOptions.get(s).presetArg, h = m !== void 0 ? m : !1; return n.negate === (h === e); } } function u(t) { return t.split("-").reduce((e, n) => e + n[0].toUpperCase() + n.slice(1)); } function r(t) { let e, n; const s = t.split(/[ |,]+/); return s.length > 1 && !/^[[<]/.test(s[1]) && (e = s.shift()), n = s.shift(), !e && /^-[^-]$/.test(n) && (e = n, n = void 0), { shortFlag: e, longFlag: n }; } return Ce.Option = o, Ce.splitOptionFlags = r, Ce.DualOptions = a, Ce; } var qe = {}, qt; function zn() { if (qt) return qe; qt = 1; const l = 3; function o(u, r) { if (Math.abs(u.length - r.length) > l) return Math.max(u.length, r.length); const t = []; for (let e = 0; e <= u.length; e++) t[e] = [e]; for (let e = 0; e <= r.length; e++) t[0][e] = e; for (let e = 1; e <= r.length; e++) for (let n = 1; n <= u.length; n++) { let s = 1; u[n - 1] === r[e - 1] ? s = 0 : s = 1, t[n][e] = Math.min( t[n - 1][e] + 1, // deletion t[n][e - 1] + 1, // insertion t[n - 1][e - 1] + s // substitution ), n > 1 && e > 1 && u[n - 1] === r[e - 2] && u[n - 2] === r[e - 1] && (t[n][e] = Math.min(t[n][e], t[n - 2][e - 2] + 1)); } return t[u.length][r.length]; } function a(u, r) { if (!r || r.length === 0) return ""; r = Array.from(new Set(r)); const t = u.startsWith("--"); t && (u = u.slice(2), r = r.map((m) => m.slice(2))); let e = [], n = l; const s = 0.4; return r.forEach((m) => { if (m.length <= 1) return; const h = o(u, m), p = Math.max(u.length, m.length); (p - h) / p > s && (h < n ? (n = h, e = [m]) : h === n && e.push(m)); }), e.sort((m, h) => m.localeCompare(h)), t && (e = e.map((m) => `--${m}`)), e.length > 1 ? ` (Did you mean one of ${e.join(", ")}?)` : e.length === 1 ? ` (Did you mean ${e[0]}?)` : ""; } return qe.suggestSimilar = a, qe; } var zt; function Yn() { if (zt) return We; zt = 1; const l = Mn.EventEmitter, o = Qr, a = Fe, u = kn, r = Ne, { Argument: t, humanReadableArgName: e } = Nt(), { CommanderError: n } = je(), { Help: s } = nn(), { Option: m, splitOptionFlags: h, DualOptions: p } = sn(), { suggestSimilar: b } = zn(); class f extends l { /** * Initialize a new `Command`. * * @param {string} [name] */ constructor(i) { super(), this.commands = [], this.options = [], this.parent = null, this._allowUnknownOption = !1, this._allowExcessArguments = !0, this.registeredArguments = [], this._args = this.registeredArguments, this.args = [], this.rawArgs = [], this.processedArgs = [], this._scriptPath = null, this._name = i || "", 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._outputConfiguration = { writeOut: (D) => r.stdout.write(D), writeErr: (D) => r.stderr.write(D), getOutHelpWidth: () => r.stdout.isTTY ? r.stdout.columns : void 0, getErrHelpWidth: () => r.stderr.isTTY ? r.stderr.columns : void 0, outputError: (D, E) => E(D) }, this._hidden = !1, this._hasHelpOption = !0, this._helpFlags = "-h, --help", this._helpDescription = "display help for command", this._helpShortFlag = "-h", this._helpLongFlag = "--help", this._addImplicitHelpCommand = void 0, this._helpCommandName = "help", this._helpCommandnameAndArgs = "help [command]", this._helpCommandDescription = "display help for command", this._helpConfiguration = {}; } /** * 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(i) { return this._outputConfiguration = i._outputConfiguration, this._hasHelpOption = i._hasHelpOption, this._helpFlags = i._helpFlags, this._helpDescription = i._helpDescription, this._helpShortFlag = i._helpShortFlag, this._helpLongFlag = i._helpLongFlag, this._helpCommandName = i._helpCommandName, this._helpCommandnameAndArgs = i._helpCommandnameAndArgs, this._helpCommandDescription = i._helpCommandDescription, this._helpConfiguration = i._helpConfiguration, this._exitCallback = i._exitCallback, this._storeOptionsAsProperties = i._storeOptionsAsProperties, this._combineFlagAndOptionalValue = i._combineFlagAndOptionalValue, this._allowExcessArguments = i._allowExcessArguments, this._enablePositionalOptions = i._enablePositionalOptions, this._showHelpAfterError = i._showHelpAfterError, this._showSuggestionAfterError = i._showSuggestionAfterError, this; } /** * @returns {Command[]} * @api private */ _getCommandAndAncestors() { const i = []; for (let D = this; D; D = D.parent) i.push(D); return i; } /** * 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(i, D, E) { let c = D, g = E; typeof c == "object" && c !== null && (g = c, c = null), g = g || {}; const [, w, O] = i.match(/([^ ]+) *(.*)/), L = this.createCommand(w); return c && (L.description(c), L._executableHandler = !0), g.isDefault && (this._defaultCommandName = L._name), L._hidden = !!(g.noHelp || g.hidden), L._executableFile = g.executableFile || null, O && L.arguments(O), this.commands.push(L), L.parent = this, L.copyInheritedSettings(this), c ? this : L; } /** * 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(i) { return new f(i); } /** * 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 s(), 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(i) { return i === void 0 ? this._helpConfiguration : (this._helpConfiguration = i, 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: * * // functions to change where being written, stdout and stderr * writeOut(str) * writeErr(str) * // matching functions to specify width for wrapping help * getOutHelpWidth() * getErrHelpWidth() * // functions based on what is being written out * outputError(str, write) // used for displaying errors, and not used for displaying help * * @param {Object} [configuration] - configuration options * @return {Command|Object} `this` command for chaining, or stored configuration */ configureOutput(i) { return i === void 0 ? this._outputConfiguration : (Object.assign(this._outputConfiguration, i), this); } /** * Display the help or a custom message after an error occurs. * * @param {boolean|string} [displayHelp] * @return {Command} `this` command for chaining */ showHelpAfterError(i = !0) { return typeof i != "string" && (i = !!i), this._showHelpAfterError = i, this; } /** * Display suggestion of similar commands for unknown commands, or options for unknown options. * * @param {boolean} [displaySuggestion] * @return {Command} `this` command for chaining */ showSuggestionAfterError(i = !0) { return this._showSuggestionAfterError = !!i, 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(i, D) { if (!i._name) throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); return D = D || {}, D.isDefault && (this._defaultCommandName = i._name), (D.noHelp || D.hidden) && (i._hidden = !0), this.commands.push(i), i.parent = this, 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(i, D) { return new t(i, D); } /** * 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|*} [fn] - custom argument processing function * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ argument(i, D, E, c) { const g = this.createArgument(i, D); return typeof E == "function" ? g.default(c).argParser(E) : g.default(E), this.addArgument(g), 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(i) { return i.trim().split(/ +/).forEach((D) => { this.argument(D); }), this; } /** * Define argument syntax for command, adding a prepared argument. * * @param {Argument} argument * @return {Command} `this` command for chaining */ addArgument(i) { const D = this.registeredArguments.slice(-1)[0]; if (D && D.variadic) throw new Error(`only the last argument can be variadic '${D.name()}'`); if (i.required && i.defaultValue !== void 0 && i.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${i.name()}'`); return this.registeredArguments.push(i), this; } /** * Override default decision whether to add implicit help command. * * addHelpCommand() // force on * addHelpCommand(false); // force off * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details * * @return {Command} `this` command for chaining */ addHelpCommand(i, D) { return i === !1 ? this._addImplicitHelpCommand = !1 : (this._addImplicitHelpCommand = !0, typeof i == "string" && (this._helpCommandName = i.split(" ")[0], this._helpCommandnameAndArgs = i), this._helpCommandDescription = D || this._helpCommandDescription), this; } /** * @return {boolean} * @api private */ _hasImplicitHelpCommand() { return this._addImplicitHelpCommand === void 0 ? this.commands.length && !this._actionHandler && !this._findCommand("help") : this._addImplicitHelpCommand; } /** * Add hook for life cycle event. * * @param {string} event * @param {Function} listener * @return {Command} `this` command for chaining */ hook(i, D) { const E = ["preSubcommand", "preAction", "postAction"]; if (!E.includes(i)) throw new Error(`Unexpected value for event passed to hook : '${i}'. Expecting one of '${E.join("', '")}'`); return this._lifeCycleHooks[i] ? this._lifeCycleHooks[i].push(D) : this._lifeCycleHooks[i] = [D], 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(i) { return i ? this._exitCallback = i : this._exitCallback = (D) => { if (D.code !== "commander.executeSubCommandAsync") throw D; }, 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 * @api private */ _exit(i, D, E) { this._exitCallback && this._exitCallback(new n(i, D, E)), r.exit(i); } /** * 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(i) { const D = (E) => { const c = this.registeredArguments.length, g = E.slice(0, c); return this._storeOptionsAsProperties ? g[c] = this : g[c] = this.opts(), g.push(this), i.apply(this, g); }; return this._actionHandler = D, 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(i, D) { return new m(i, D); } /** * Wrap parseArgs to catch 'commander.invalidArgument'. * * @param {Option | Argument} target * @param {string} value * @param {*} previous * @param {string} invalidArgumentMessage * @api private */ _callParseArg(i, D, E, c) { try { return i.parseArg(D, E); } catch (g) { if (g.code === "commander.invalidArgument") { const w = `${c} ${g.message}`; this.error(w, { exitCode: g.exitCode, code: g.code }); } throw g; } } /** * Add an option. * * @param {Option} option * @return {Command} `this` command for chaining */ addOption(i) { const D = i.name(), E = i.attributeName(); if (i.negate) { const g = i.long.replace(/^--no-/, "--"); this._findOption(g) || this.setOptionValueWithSource(E, i.defaultValue === void 0 ? !0 : i.defaultValue, "default"); } else i.defaultValue !== void 0 && this.setOptionValueWithSource(E, i.defaultValue, "default"); this.options.push(i); const c = (g, w, O) => { g == null && i.presetArg !== void 0 && (g = i.presetArg); const L = this.getOptionValue(E); g !== null && i.parseArg ? g = this._callParseArg(i, g, L, w) : g !== null && i.variadic && (g = i._concatValue(g, L)), g == null && (i.negate ? g = !1 : i.isBoolean() || i.optional ? g = !0 : g = ""), this.setOptionValueWithSource(E, g, O); }; return this.on("option:" + D, (g) => { const w = `error: option '${i.flags}' argument '${g}' is invalid.`; c(g, w, "cli"); }), i.envVar && this.on("optionEnv:" + D, (g) => { const w = `error: option '${i.flags}' value '${g}' from env '${i.envVar}' is invalid.`; c(g, w, "env"); }), this; } /** * Internal implementation shared by .option() and .requiredOption() * * @api private */ _optionEx(i, D, E, c, g) { if (typeof D == "object" && D instanceof m) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()"); const w = this.createOption(D, E); if (w.makeOptionMandatory(!!i.mandatory), typeof c == "function") w.default(g).argParser(c); else if (c instanceof RegExp) { const O = c; c = (L, B) => { const P = O.exec(L); return P ? P[0] : B; }, w.default(g).argParser(c); } else w.default(c); return this.addOption(w); } /** * 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('-p, --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(i, D, E, c) { return this._optionEx({}, i, D, E, c); } /** * 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(i, D, E, c) { return this._optionEx({ mandatory: !0 }, i, D, E, c); } /** * 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=true] - if `true` or omitted, an optional value can be specified directly after the flag. */ combineFlagAndOptionalValue(i = !0) { return this._combineFlagAndOptionalValue = !!i, this; } /** * Allow unknown options on the command line. * * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown * for unknown options. */ allowUnknownOption(i = !0) { return this._allowUnknownOption = !!i, this; } /** * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. * * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown * for excess arguments. */ allowExcessArguments(i = !0) { return this._allowExcessArguments = !!i, this; } /** * Enable positional options. Positional means global options are specified before subcommands which lets * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. * The default behaviour is non-positional and global options may appear anywhere on the command line. * * @param {Boolean} [positional=true] */ enablePositionalOptions(i = !0) { return this._enablePositionalOptions = !!i, this; } /** * Pass through options that come after command-arguments rather than treat them as command-options, * so actual command-options come before command-arguments. Turning this on for a subcommand requires * positional options to have been enabled on the program (parent commands). * The default behaviour is non-positional and options may appear before or after command-arguments. * * @param {Boolean} [passThrough=true] * for unknown options. */ passThroughOptions(i = !0) { if (this._passThroughOptions = !!i, this.parent && i && !this.parent._enablePositionalOptions) throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)"); return this; } /** * Whether to store option values as properties on command object, * or store separately (specify false). In both cases the option values can be accessed using .opts(). * * @param {boolean} [storeAsProperties=true] * @return {Command} `this` command for chaining */ storeOptionsAsProperties(i = !0) { if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options"); return this._storeOptionsAsProperties = !!i, this; } /** * Retrieve option value. * * @param {string} key * @return {Object} value */ getOptionValue(i) { return this._storeOptionsAsProperties ? this[i] : this._optionValues[i]; } /** * Store option value. * * @param {string} key * @param {Object} value * @return {Command} `this` command for chaining */ setOptionValue(i, D) { return this.setOptionValueWithSource(i, D, void 0); } /** * Store option value and where the value came from. * * @param {string} key * @param {Object} value * @param {string} source - expected values are default/config/env/cli/implied * @return {Command} `this` command for chaining */ setOptionValueWithSource(i, D, E) { return this._storeOptionsAsProperties ? this[i] = D : this._optionValues[i] = D, this._optionValueSources[i] = E, this; } /** * Get source of option value. * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSource(i) { return this._optionValueSources[i]; } /** * Get source of option value. See also .optsWithGlobals(). * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSourceWithGlobals(i) { let D; return this._getCommandAndAncestors().forEach((E) => { E.getOptionValueSource(i) !== void 0 && (D = E.getOptionValueSource(i)); }), D; } /** * Get user arguments from implied or explicit arguments. * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. * * @api private */ _prepareUserArgs(i, D) { if (i !== void 0 && !Array.isArray(i)) throw new Error("first parameter to parse must be array or undefined"); D = D || {}, i === void 0 && (i = r.argv, r.versions && r.versions.electron && (D.from = "electron")), this.rawArgs = i.slice(); let E; switch (D.from) { case void 0: case "node": this._scriptPath = i[1], E = i.slice(2); break; case "electron": r.defaultApp ? (this._scriptPath = i[1], E = i.slice(2)) : E = i.slice(1); break; case "user": E = i.slice(0); break; default: throw new Error(`unexpected parse option { from: '${D.from}' }`); } return !this._name && this._scriptPath && this.nameFromFilename(this._scriptPath), this._name = this._name || "program", E; } /** * Parse `argv`, setting options and invoking commands when defined. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * program.parse(process.argv); * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] - optional, defaults to process.argv * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' * @return {Command} `this` command for chaining */ parse(i, D) { const E = this._prepareUserArgs(i, D); return this._parseCommand([], E), this; } /** * Parse `argv`, setting options and invoking commands when defined. * * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. * * The default expectation is that the arguments are from node and have the application as argv[0] * and the script being run in argv[1], with user parameters after that. * * @example * await program.parseAsync(process.argv); * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] * @param {Object} [parseOptions] * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' * @return {Promise} */ async parseAsync(i, D) { const E = this._prepareUserArgs(i, D); return await this._parseCommand([], E), this; } /** * Execute a sub-command executable. * * @api private */ _executeSubCommand(i, D) { D = D.slice(); let E = !1; const c = [".js", ".ts", ".tsx", ".mjs", ".cjs"]; function g(P, R) { const U = a.resolve(P, R); if (u.existsSync(U)) return U; if (c.includes(a.extname(R))) return; const I = c.find((z) => u.existsSync(`${U}${z}`)); if (I) return `${U}${I}`; } this._checkForMissingMandatoryOptions(), this._checkForConflictingOptions(); let w = i._executableFile || `${this._name}-${i._name}`, O = this._executableDir || ""; if (this._scriptPath) { let P; try { P = u.realpathSync(this._scriptPath); } catch { P = this._scriptPath; } O = a.resolve(a.dirname(P), O); } if (O) { let P = g(O, w); if (!P && !i._executableFile && this._scriptPath) { const R = a.basename(this._scriptPath, a.extname(this._scriptPath)); R !== this._name && (P = g(O, `${R}-${i._name}`)); } w = P || w; } E = c.includes(a.extname(w)); let L; r.platform !== "win32" ? E ? (D.unshift(w), D = C(r.execArgv).concat(D), L = o.spawn(r.argv[0], D, { stdio: "inherit" })) : L = o.spawn(w, D, { stdio: "inherit" }) : (D.unshift(w), D = C(r.execArgv).concat(D), L = o.spawn(r.execPath, D, { stdio: "inherit" })), L.killed || ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"].forEach((R) => { r.on(R, () => { L.killed === !1 && L.exitCode === null && L.kill(R); }); }); const B = this._exitCallback; B ? L.on("close", () => { B(new n(r.exitCode || 0, "commander.executeSubCommandAsync", "(close)")); }) : L.on("close"