@sandeepk1729/porter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/dist/index.js +4617 -0
  4. package/package.json +52 -0
package/dist/index.js ADDED
@@ -0,0 +1,4617 @@
1
+ #! /usr/bin/env node
2
+ /******/ (() => { // webpackBootstrap
3
+ /******/ var __webpack_modules__ = ({
4
+
5
+ /***/ 585:
6
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
7
+
8
+ "use strict";
9
+
10
+ var __importDefault = (this && this.__importDefault) || function (mod) {
11
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12
+ };
13
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
14
+ const commander_1 = __nccwpck_require__(909);
15
+ const package_json_1 = __importDefault(__nccwpck_require__(330));
16
+ const agent_1 = __nccwpck_require__(257);
17
+ const config_1 = __nccwpck_require__(750);
18
+ const porter = new commander_1.Command();
19
+ porter.name("porter").description(package_json_1.default.description).version(package_json_1.default.version); // <-- Dynamically injected
20
+ // 1. add alias
21
+ porter
22
+ .command("http")
23
+ .arguments("<local-port>")
24
+ .description("Add http port forwarding")
25
+ .action(async (localPort) => {
26
+ console.log(`Connecting to porter server and forwarding to local port ${localPort}`);
27
+ config_1.caller.request(config_1.REQ_BODY)
28
+ .on("response", (res) => {
29
+ console.log("Unexpected response from server:", res.statusCode);
30
+ res.on("data", (chunk) => {
31
+ console.log("Response body:", chunk.toString());
32
+ });
33
+ })
34
+ .on("upgrade", (0, agent_1.upgradeHandler)(localPort))
35
+ .end();
36
+ });
37
+ exports["default"] = porter;
38
+
39
+
40
+ /***/ }),
41
+
42
+ /***/ 750:
43
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
44
+
45
+ "use strict";
46
+
47
+ var __importDefault = (this && this.__importDefault) || function (mod) {
48
+ return (mod && mod.__esModule) ? mod : { "default": mod };
49
+ };
50
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
51
+ exports.publicUrl = exports.caller = exports.REQ_BODY = void 0;
52
+ const node_http_1 = __importDefault(__nccwpck_require__(67));
53
+ const node_https_1 = __importDefault(__nccwpck_require__(327));
54
+ const { PORTER_SERVER_HOST = "porter-sandeep.fly.dev" } = process.env;
55
+ const isLocalHost = PORTER_SERVER_HOST === "localhost";
56
+ const caller = isLocalHost ? node_http_1.default : node_https_1.default;
57
+ exports.caller = caller;
58
+ const localConfig = {
59
+ host: 'localhost',
60
+ port: 9000,
61
+ };
62
+ const serverConfig = {
63
+ host: PORTER_SERVER_HOST,
64
+ };
65
+ const hostConfig = isLocalHost ? localConfig : serverConfig;
66
+ const REQ_BODY = {
67
+ ...hostConfig,
68
+ path: '/agent',
69
+ method: "GET",
70
+ headers: {
71
+ Connection: "Upgrade",
72
+ Upgrade: "tunnel",
73
+ },
74
+ };
75
+ exports.REQ_BODY = REQ_BODY;
76
+ const publicUrl = `http${isLocalHost ? '' : 's'}://${PORTER_SERVER_HOST}/{tunnelId}`;
77
+ exports.publicUrl = publicUrl;
78
+
79
+
80
+ /***/ }),
81
+
82
+ /***/ 407:
83
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
84
+
85
+ "use strict";
86
+
87
+ var __importDefault = (this && this.__importDefault) || function (mod) {
88
+ return (mod && mod.__esModule) ? mod : { "default": mod };
89
+ };
90
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
91
+ const command_1 = __importDefault(__nccwpck_require__(585));
92
+ // If no args are provided, show help
93
+ if (!process.argv.slice(2).length) {
94
+ command_1.default.outputHelp();
95
+ process.exit(0);
96
+ }
97
+ // Execute the CLI
98
+ command_1.default.parse(process.argv);
99
+
100
+
101
+ /***/ }),
102
+
103
+ /***/ 257:
104
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
105
+
106
+ "use strict";
107
+
108
+ var __importDefault = (this && this.__importDefault) || function (mod) {
109
+ return (mod && mod.__esModule) ? mod : { "default": mod };
110
+ };
111
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
112
+ exports.upgradeHandler = void 0;
113
+ const node_http_1 = __importDefault(__nccwpck_require__(67));
114
+ const buffer_1 = __nccwpck_require__(88);
115
+ const config_1 = __nccwpck_require__(750);
116
+ const upgradeHandler = (localPort) => (res, socket) => {
117
+ let tunnelId = null;
118
+ let buffer = Buffer.alloc(0);
119
+ console.log("🚀 Agent connected");
120
+ socket.on("data", (chunk) => {
121
+ if (!tunnelId) {
122
+ tunnelId = (0, buffer_1.decodeTunnelId)(Buffer.concat([buffer, chunk]));
123
+ console.log(`⬇️ Forwarding ${config_1.publicUrl.replace("{tunnelId}", tunnelId)} -> http://localhost:${localPort}`);
124
+ buffer = Buffer.alloc(0);
125
+ return;
126
+ }
127
+ const { frames, remaining } = (0, buffer_1.decodeFrames)(Buffer.concat([buffer, chunk]));
128
+ buffer = remaining;
129
+ frames.forEach((frame) => {
130
+ if (frame.type !== buffer_1.FrameType.REQUEST)
131
+ return;
132
+ const options = {
133
+ host: "localhost",
134
+ port: parseInt(localPort, 10),
135
+ method: frame.payload.method,
136
+ path: frame.payload.path,
137
+ headers: frame.payload.headers,
138
+ };
139
+ console.log(`➡️ Incoming request for tunnel ${tunnelId}: `, options);
140
+ // Using ANSI escape codes
141
+ console.log(`- \x1b[32m${options.method}\x1b[0m \x1b[34m${options.path}\x1b[0m`);
142
+ const proxy = node_http_1.default.request(options, (res) => {
143
+ let body = "";
144
+ res.on("data", (c) => (body += c));
145
+ res.on("end", () => socket.write((0, buffer_1.encodeFrame)({
146
+ type: buffer_1.FrameType.RESPONSE,
147
+ requestId: frame.requestId,
148
+ payload: {
149
+ status: res.statusCode,
150
+ headers: res.headers,
151
+ body,
152
+ },
153
+ })));
154
+ });
155
+ proxy.on("error", (err) => socket.write((0, buffer_1.encodeFrame)({
156
+ type: buffer_1.FrameType.RESPONSE,
157
+ requestId: frame.requestId,
158
+ payload: {
159
+ status: 502,
160
+ headers: {},
161
+ body: "Bad Gateway: " + err.message
162
+ },
163
+ })));
164
+ proxy.end();
165
+ });
166
+ });
167
+ socket.on("error", (err) => {
168
+ console.error("Socket error:", err);
169
+ });
170
+ socket.on("close", () => {
171
+ console.log("Agent disconnected");
172
+ });
173
+ };
174
+ exports.upgradeHandler = upgradeHandler;
175
+
176
+
177
+ /***/ }),
178
+
179
+ /***/ 88:
180
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
181
+
182
+ "use strict";
183
+
184
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
185
+ exports.decodeTunnelId = exports.decodeFrames = exports.encodeFrame = exports.FrameType = void 0;
186
+ const node_buffer_1 = __nccwpck_require__(573);
187
+ const LENGTH = {
188
+ LENGTH_FIELD: 4,
189
+ };
190
+ var FrameType;
191
+ (function (FrameType) {
192
+ FrameType[FrameType["REQUEST"] = 1] = "REQUEST";
193
+ FrameType[FrameType["RESPONSE"] = 2] = "RESPONSE";
194
+ FrameType[FrameType["REGISTERED"] = 3] = "REGISTERED";
195
+ })(FrameType || (exports.FrameType = FrameType = {}));
196
+ const encodeFrame = (frame) => {
197
+ const data = JSON.stringify(frame);
198
+ const buf = node_buffer_1.Buffer.allocUnsafe(LENGTH.LENGTH_FIELD + node_buffer_1.Buffer.byteLength(data));
199
+ buf.writeInt32BE(node_buffer_1.Buffer.byteLength(data), 0);
200
+ node_buffer_1.Buffer.from(data).copy(buf, LENGTH.LENGTH_FIELD);
201
+ console.log(`Encoded frame ${JSON.stringify(frame)} to buffer of length ${buf.length}`);
202
+ return buf;
203
+ };
204
+ exports.encodeFrame = encodeFrame;
205
+ const decodeFrames = (buffer) => {
206
+ let offset = 0;
207
+ let len = buffer.readInt32BE(0);
208
+ const frames = [];
209
+ while (buffer.length - offset <= LENGTH.LENGTH_FIELD + len) {
210
+ const body = buffer.slice(offset + LENGTH.LENGTH_FIELD, offset + LENGTH.LENGTH_FIELD + len);
211
+ frames.push(JSON.parse(body.toString()));
212
+ offset += LENGTH.LENGTH_FIELD + len;
213
+ if (buffer.length - offset < LENGTH.LENGTH_FIELD)
214
+ break;
215
+ len = buffer.readInt32BE(offset);
216
+ }
217
+ return { frames, remaining: buffer.slice(offset) };
218
+ };
219
+ exports.decodeFrames = decodeFrames;
220
+ const decodeTunnelId = (buffer) => {
221
+ const data = decodeFrames(buffer).frames[0];
222
+ if (data?.type !== FrameType.REGISTERED) {
223
+ throw new Error("Invalid frame type for tunnel ID");
224
+ }
225
+ return data.tunnelId;
226
+ };
227
+ exports.decodeTunnelId = decodeTunnelId;
228
+
229
+
230
+ /***/ }),
231
+
232
+ /***/ 573:
233
+ /***/ ((module) => {
234
+
235
+ "use strict";
236
+ module.exports = require("node:buffer");
237
+
238
+ /***/ }),
239
+
240
+ /***/ 421:
241
+ /***/ ((module) => {
242
+
243
+ "use strict";
244
+ module.exports = require("node:child_process");
245
+
246
+ /***/ }),
247
+
248
+ /***/ 474:
249
+ /***/ ((module) => {
250
+
251
+ "use strict";
252
+ module.exports = require("node:events");
253
+
254
+ /***/ }),
255
+
256
+ /***/ 24:
257
+ /***/ ((module) => {
258
+
259
+ "use strict";
260
+ module.exports = require("node:fs");
261
+
262
+ /***/ }),
263
+
264
+ /***/ 67:
265
+ /***/ ((module) => {
266
+
267
+ "use strict";
268
+ module.exports = require("node:http");
269
+
270
+ /***/ }),
271
+
272
+ /***/ 327:
273
+ /***/ ((module) => {
274
+
275
+ "use strict";
276
+ module.exports = require("node:https");
277
+
278
+ /***/ }),
279
+
280
+ /***/ 760:
281
+ /***/ ((module) => {
282
+
283
+ "use strict";
284
+ module.exports = require("node:path");
285
+
286
+ /***/ }),
287
+
288
+ /***/ 708:
289
+ /***/ ((module) => {
290
+
291
+ "use strict";
292
+ module.exports = require("node:process");
293
+
294
+ /***/ }),
295
+
296
+ /***/ 909:
297
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
298
+
299
+ const { Argument } = __nccwpck_require__(154);
300
+ const { Command } = __nccwpck_require__(348);
301
+ const { CommanderError, InvalidArgumentError } = __nccwpck_require__(135);
302
+ const { Help } = __nccwpck_require__(754);
303
+ const { Option } = __nccwpck_require__(240);
304
+
305
+ exports.program = new Command();
306
+
307
+ exports.createCommand = (name) => new Command(name);
308
+ exports.createOption = (flags, description) => new Option(flags, description);
309
+ exports.createArgument = (name, description) => new Argument(name, description);
310
+
311
+ /**
312
+ * Expose classes
313
+ */
314
+
315
+ exports.Command = Command;
316
+ exports.Option = Option;
317
+ exports.Argument = Argument;
318
+ exports.Help = Help;
319
+
320
+ exports.CommanderError = CommanderError;
321
+ exports.InvalidArgumentError = InvalidArgumentError;
322
+ exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
323
+
324
+
325
+ /***/ }),
326
+
327
+ /***/ 154:
328
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
329
+
330
+ const { InvalidArgumentError } = __nccwpck_require__(135);
331
+
332
+ class Argument {
333
+ /**
334
+ * Initialize a new command argument with the given name and description.
335
+ * The default is that the argument is required, and you can explicitly
336
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
337
+ *
338
+ * @param {string} name
339
+ * @param {string} [description]
340
+ */
341
+
342
+ constructor(name, description) {
343
+ this.description = description || '';
344
+ this.variadic = false;
345
+ this.parseArg = undefined;
346
+ this.defaultValue = undefined;
347
+ this.defaultValueDescription = undefined;
348
+ this.argChoices = undefined;
349
+
350
+ switch (name[0]) {
351
+ case '<': // e.g. <required>
352
+ this.required = true;
353
+ this._name = name.slice(1, -1);
354
+ break;
355
+ case '[': // e.g. [optional]
356
+ this.required = false;
357
+ this._name = name.slice(1, -1);
358
+ break;
359
+ default:
360
+ this.required = true;
361
+ this._name = name;
362
+ break;
363
+ }
364
+
365
+ if (this._name.endsWith('...')) {
366
+ this.variadic = true;
367
+ this._name = this._name.slice(0, -3);
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Return argument name.
373
+ *
374
+ * @return {string}
375
+ */
376
+
377
+ name() {
378
+ return this._name;
379
+ }
380
+
381
+ /**
382
+ * @package
383
+ */
384
+
385
+ _collectValue(value, previous) {
386
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
387
+ return [value];
388
+ }
389
+
390
+ previous.push(value);
391
+ return previous;
392
+ }
393
+
394
+ /**
395
+ * Set the default value, and optionally supply the description to be displayed in the help.
396
+ *
397
+ * @param {*} value
398
+ * @param {string} [description]
399
+ * @return {Argument}
400
+ */
401
+
402
+ default(value, description) {
403
+ this.defaultValue = value;
404
+ this.defaultValueDescription = description;
405
+ return this;
406
+ }
407
+
408
+ /**
409
+ * Set the custom handler for processing CLI command arguments into argument values.
410
+ *
411
+ * @param {Function} [fn]
412
+ * @return {Argument}
413
+ */
414
+
415
+ argParser(fn) {
416
+ this.parseArg = fn;
417
+ return this;
418
+ }
419
+
420
+ /**
421
+ * Only allow argument value to be one of choices.
422
+ *
423
+ * @param {string[]} values
424
+ * @return {Argument}
425
+ */
426
+
427
+ choices(values) {
428
+ this.argChoices = values.slice();
429
+ this.parseArg = (arg, previous) => {
430
+ if (!this.argChoices.includes(arg)) {
431
+ throw new InvalidArgumentError(
432
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
433
+ );
434
+ }
435
+ if (this.variadic) {
436
+ return this._collectValue(arg, previous);
437
+ }
438
+ return arg;
439
+ };
440
+ return this;
441
+ }
442
+
443
+ /**
444
+ * Make argument required.
445
+ *
446
+ * @returns {Argument}
447
+ */
448
+ argRequired() {
449
+ this.required = true;
450
+ return this;
451
+ }
452
+
453
+ /**
454
+ * Make argument optional.
455
+ *
456
+ * @returns {Argument}
457
+ */
458
+ argOptional() {
459
+ this.required = false;
460
+ return this;
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Takes an argument and returns its human readable equivalent for help usage.
466
+ *
467
+ * @param {Argument} arg
468
+ * @return {string}
469
+ * @private
470
+ */
471
+
472
+ function humanReadableArgName(arg) {
473
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
474
+
475
+ return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
476
+ }
477
+
478
+ exports.Argument = Argument;
479
+ exports.humanReadableArgName = humanReadableArgName;
480
+
481
+
482
+ /***/ }),
483
+
484
+ /***/ 348:
485
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
486
+
487
+ const EventEmitter = (__nccwpck_require__(474).EventEmitter);
488
+ const childProcess = __nccwpck_require__(421);
489
+ const path = __nccwpck_require__(760);
490
+ const fs = __nccwpck_require__(24);
491
+ const process = __nccwpck_require__(708);
492
+
493
+ const { Argument, humanReadableArgName } = __nccwpck_require__(154);
494
+ const { CommanderError } = __nccwpck_require__(135);
495
+ const { Help, stripColor } = __nccwpck_require__(754);
496
+ const { Option, DualOptions } = __nccwpck_require__(240);
497
+ const { suggestSimilar } = __nccwpck_require__(30);
498
+
499
+ class Command extends EventEmitter {
500
+ /**
501
+ * Initialize a new `Command`.
502
+ *
503
+ * @param {string} [name]
504
+ */
505
+
506
+ constructor(name) {
507
+ super();
508
+ /** @type {Command[]} */
509
+ this.commands = [];
510
+ /** @type {Option[]} */
511
+ this.options = [];
512
+ this.parent = null;
513
+ this._allowUnknownOption = false;
514
+ this._allowExcessArguments = false;
515
+ /** @type {Argument[]} */
516
+ this.registeredArguments = [];
517
+ this._args = this.registeredArguments; // deprecated old name
518
+ /** @type {string[]} */
519
+ this.args = []; // cli args with options removed
520
+ this.rawArgs = [];
521
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
522
+ this._scriptPath = null;
523
+ this._name = name || '';
524
+ this._optionValues = {};
525
+ this._optionValueSources = {}; // default, env, cli etc
526
+ this._storeOptionsAsProperties = false;
527
+ this._actionHandler = null;
528
+ this._executableHandler = false;
529
+ this._executableFile = null; // custom name for executable
530
+ this._executableDir = null; // custom search directory for subcommands
531
+ this._defaultCommandName = null;
532
+ this._exitCallback = null;
533
+ this._aliases = [];
534
+ this._combineFlagAndOptionalValue = true;
535
+ this._description = '';
536
+ this._summary = '';
537
+ this._argsDescription = undefined; // legacy
538
+ this._enablePositionalOptions = false;
539
+ this._passThroughOptions = false;
540
+ this._lifeCycleHooks = {}; // a hash of arrays
541
+ /** @type {(boolean | string)} */
542
+ this._showHelpAfterError = false;
543
+ this._showSuggestionAfterError = true;
544
+ this._savedState = null; // used in save/restoreStateBeforeParse
545
+
546
+ // see configureOutput() for docs
547
+ this._outputConfiguration = {
548
+ writeOut: (str) => process.stdout.write(str),
549
+ writeErr: (str) => process.stderr.write(str),
550
+ outputError: (str, write) => write(str),
551
+ getOutHelpWidth: () =>
552
+ process.stdout.isTTY ? process.stdout.columns : undefined,
553
+ getErrHelpWidth: () =>
554
+ process.stderr.isTTY ? process.stderr.columns : undefined,
555
+ getOutHasColors: () =>
556
+ useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
557
+ getErrHasColors: () =>
558
+ useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
559
+ stripColor: (str) => stripColor(str),
560
+ };
561
+
562
+ this._hidden = false;
563
+ /** @type {(Option | null | undefined)} */
564
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
565
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
566
+ /** @type {Command} */
567
+ this._helpCommand = undefined; // lazy initialised, inherited
568
+ this._helpConfiguration = {};
569
+ /** @type {string | undefined} */
570
+ this._helpGroupHeading = undefined; // soft initialised when added to parent
571
+ /** @type {string | undefined} */
572
+ this._defaultCommandGroup = undefined;
573
+ /** @type {string | undefined} */
574
+ this._defaultOptionGroup = undefined;
575
+ }
576
+
577
+ /**
578
+ * Copy settings that are useful to have in common across root command and subcommands.
579
+ *
580
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
581
+ *
582
+ * @param {Command} sourceCommand
583
+ * @return {Command} `this` command for chaining
584
+ */
585
+ copyInheritedSettings(sourceCommand) {
586
+ this._outputConfiguration = sourceCommand._outputConfiguration;
587
+ this._helpOption = sourceCommand._helpOption;
588
+ this._helpCommand = sourceCommand._helpCommand;
589
+ this._helpConfiguration = sourceCommand._helpConfiguration;
590
+ this._exitCallback = sourceCommand._exitCallback;
591
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
592
+ this._combineFlagAndOptionalValue =
593
+ sourceCommand._combineFlagAndOptionalValue;
594
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
595
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
596
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
597
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
598
+
599
+ return this;
600
+ }
601
+
602
+ /**
603
+ * @returns {Command[]}
604
+ * @private
605
+ */
606
+
607
+ _getCommandAndAncestors() {
608
+ const result = [];
609
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
610
+ for (let command = this; command; command = command.parent) {
611
+ result.push(command);
612
+ }
613
+ return result;
614
+ }
615
+
616
+ /**
617
+ * Define a command.
618
+ *
619
+ * There are two styles of command: pay attention to where to put the description.
620
+ *
621
+ * @example
622
+ * // Command implemented using action handler (description is supplied separately to `.command`)
623
+ * program
624
+ * .command('clone <source> [destination]')
625
+ * .description('clone a repository into a newly created directory')
626
+ * .action((source, destination) => {
627
+ * console.log('clone command called');
628
+ * });
629
+ *
630
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
631
+ * program
632
+ * .command('start <service>', 'start named service')
633
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
634
+ *
635
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
636
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
637
+ * @param {object} [execOpts] - configuration options (for executable)
638
+ * @return {Command} returns new command for action handler, or `this` for executable command
639
+ */
640
+
641
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
642
+ let desc = actionOptsOrExecDesc;
643
+ let opts = execOpts;
644
+ if (typeof desc === 'object' && desc !== null) {
645
+ opts = desc;
646
+ desc = null;
647
+ }
648
+ opts = opts || {};
649
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
650
+
651
+ const cmd = this.createCommand(name);
652
+ if (desc) {
653
+ cmd.description(desc);
654
+ cmd._executableHandler = true;
655
+ }
656
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
657
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
658
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
659
+ if (args) cmd.arguments(args);
660
+ this._registerCommand(cmd);
661
+ cmd.parent = this;
662
+ cmd.copyInheritedSettings(this);
663
+
664
+ if (desc) return this;
665
+ return cmd;
666
+ }
667
+
668
+ /**
669
+ * Factory routine to create a new unattached command.
670
+ *
671
+ * See .command() for creating an attached subcommand, which uses this routine to
672
+ * create the command. You can override createCommand to customise subcommands.
673
+ *
674
+ * @param {string} [name]
675
+ * @return {Command} new command
676
+ */
677
+
678
+ createCommand(name) {
679
+ return new Command(name);
680
+ }
681
+
682
+ /**
683
+ * You can customise the help with a subclass of Help by overriding createHelp,
684
+ * or by overriding Help properties using configureHelp().
685
+ *
686
+ * @return {Help}
687
+ */
688
+
689
+ createHelp() {
690
+ return Object.assign(new Help(), this.configureHelp());
691
+ }
692
+
693
+ /**
694
+ * You can customise the help by overriding Help properties using configureHelp(),
695
+ * or with a subclass of Help by overriding createHelp().
696
+ *
697
+ * @param {object} [configuration] - configuration options
698
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
699
+ */
700
+
701
+ configureHelp(configuration) {
702
+ if (configuration === undefined) return this._helpConfiguration;
703
+
704
+ this._helpConfiguration = configuration;
705
+ return this;
706
+ }
707
+
708
+ /**
709
+ * The default output goes to stdout and stderr. You can customise this for special
710
+ * applications. You can also customise the display of errors by overriding outputError.
711
+ *
712
+ * The configuration properties are all functions:
713
+ *
714
+ * // change how output being written, defaults to stdout and stderr
715
+ * writeOut(str)
716
+ * writeErr(str)
717
+ * // change how output being written for errors, defaults to writeErr
718
+ * outputError(str, write) // used for displaying errors and not used for displaying help
719
+ * // specify width for wrapping help
720
+ * getOutHelpWidth()
721
+ * getErrHelpWidth()
722
+ * // color support, currently only used with Help
723
+ * getOutHasColors()
724
+ * getErrHasColors()
725
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
726
+ *
727
+ * @param {object} [configuration] - configuration options
728
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
729
+ */
730
+
731
+ configureOutput(configuration) {
732
+ if (configuration === undefined) return this._outputConfiguration;
733
+
734
+ this._outputConfiguration = {
735
+ ...this._outputConfiguration,
736
+ ...configuration,
737
+ };
738
+ return this;
739
+ }
740
+
741
+ /**
742
+ * Display the help or a custom message after an error occurs.
743
+ *
744
+ * @param {(boolean|string)} [displayHelp]
745
+ * @return {Command} `this` command for chaining
746
+ */
747
+ showHelpAfterError(displayHelp = true) {
748
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
749
+ this._showHelpAfterError = displayHelp;
750
+ return this;
751
+ }
752
+
753
+ /**
754
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
755
+ *
756
+ * @param {boolean} [displaySuggestion]
757
+ * @return {Command} `this` command for chaining
758
+ */
759
+ showSuggestionAfterError(displaySuggestion = true) {
760
+ this._showSuggestionAfterError = !!displaySuggestion;
761
+ return this;
762
+ }
763
+
764
+ /**
765
+ * Add a prepared subcommand.
766
+ *
767
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
768
+ *
769
+ * @param {Command} cmd - new subcommand
770
+ * @param {object} [opts] - configuration options
771
+ * @return {Command} `this` command for chaining
772
+ */
773
+
774
+ addCommand(cmd, opts) {
775
+ if (!cmd._name) {
776
+ throw new Error(`Command passed to .addCommand() must have a name
777
+ - specify the name in Command constructor or using .name()`);
778
+ }
779
+
780
+ opts = opts || {};
781
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
782
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
783
+
784
+ this._registerCommand(cmd);
785
+ cmd.parent = this;
786
+ cmd._checkForBrokenPassThrough();
787
+
788
+ return this;
789
+ }
790
+
791
+ /**
792
+ * Factory routine to create a new unattached argument.
793
+ *
794
+ * See .argument() for creating an attached argument, which uses this routine to
795
+ * create the argument. You can override createArgument to return a custom argument.
796
+ *
797
+ * @param {string} name
798
+ * @param {string} [description]
799
+ * @return {Argument} new argument
800
+ */
801
+
802
+ createArgument(name, description) {
803
+ return new Argument(name, description);
804
+ }
805
+
806
+ /**
807
+ * Define argument syntax for command.
808
+ *
809
+ * The default is that the argument is required, and you can explicitly
810
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
811
+ *
812
+ * @example
813
+ * program.argument('<input-file>');
814
+ * program.argument('[output-file]');
815
+ *
816
+ * @param {string} name
817
+ * @param {string} [description]
818
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
819
+ * @param {*} [defaultValue]
820
+ * @return {Command} `this` command for chaining
821
+ */
822
+ argument(name, description, parseArg, defaultValue) {
823
+ const argument = this.createArgument(name, description);
824
+ if (typeof parseArg === 'function') {
825
+ argument.default(defaultValue).argParser(parseArg);
826
+ } else {
827
+ argument.default(parseArg);
828
+ }
829
+ this.addArgument(argument);
830
+ return this;
831
+ }
832
+
833
+ /**
834
+ * Define argument syntax for command, adding multiple at once (without descriptions).
835
+ *
836
+ * See also .argument().
837
+ *
838
+ * @example
839
+ * program.arguments('<cmd> [env]');
840
+ *
841
+ * @param {string} names
842
+ * @return {Command} `this` command for chaining
843
+ */
844
+
845
+ arguments(names) {
846
+ names
847
+ .trim()
848
+ .split(/ +/)
849
+ .forEach((detail) => {
850
+ this.argument(detail);
851
+ });
852
+ return this;
853
+ }
854
+
855
+ /**
856
+ * Define argument syntax for command, adding a prepared argument.
857
+ *
858
+ * @param {Argument} argument
859
+ * @return {Command} `this` command for chaining
860
+ */
861
+ addArgument(argument) {
862
+ const previousArgument = this.registeredArguments.slice(-1)[0];
863
+ if (previousArgument?.variadic) {
864
+ throw new Error(
865
+ `only the last argument can be variadic '${previousArgument.name()}'`,
866
+ );
867
+ }
868
+ if (
869
+ argument.required &&
870
+ argument.defaultValue !== undefined &&
871
+ argument.parseArg === undefined
872
+ ) {
873
+ throw new Error(
874
+ `a default value for a required argument is never used: '${argument.name()}'`,
875
+ );
876
+ }
877
+ this.registeredArguments.push(argument);
878
+ return this;
879
+ }
880
+
881
+ /**
882
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
883
+ *
884
+ * @example
885
+ * program.helpCommand('help [cmd]');
886
+ * program.helpCommand('help [cmd]', 'show help');
887
+ * program.helpCommand(false); // suppress default help command
888
+ * program.helpCommand(true); // add help command even if no subcommands
889
+ *
890
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
891
+ * @param {string} [description] - custom description
892
+ * @return {Command} `this` command for chaining
893
+ */
894
+
895
+ helpCommand(enableOrNameAndArgs, description) {
896
+ if (typeof enableOrNameAndArgs === 'boolean') {
897
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
898
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
899
+ // make the command to store the group
900
+ this._initCommandGroup(this._getHelpCommand());
901
+ }
902
+ return this;
903
+ }
904
+
905
+ const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';
906
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
907
+ const helpDescription = description ?? 'display help for command';
908
+
909
+ const helpCommand = this.createCommand(helpName);
910
+ helpCommand.helpOption(false);
911
+ if (helpArgs) helpCommand.arguments(helpArgs);
912
+ if (helpDescription) helpCommand.description(helpDescription);
913
+
914
+ this._addImplicitHelpCommand = true;
915
+ this._helpCommand = helpCommand;
916
+ // init group unless lazy create
917
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
918
+
919
+ return this;
920
+ }
921
+
922
+ /**
923
+ * Add prepared custom help command.
924
+ *
925
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
926
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
927
+ * @return {Command} `this` command for chaining
928
+ */
929
+ addHelpCommand(helpCommand, deprecatedDescription) {
930
+ // If not passed an object, call through to helpCommand for backwards compatibility,
931
+ // as addHelpCommand was originally used like helpCommand is now.
932
+ if (typeof helpCommand !== 'object') {
933
+ this.helpCommand(helpCommand, deprecatedDescription);
934
+ return this;
935
+ }
936
+
937
+ this._addImplicitHelpCommand = true;
938
+ this._helpCommand = helpCommand;
939
+ this._initCommandGroup(helpCommand);
940
+ return this;
941
+ }
942
+
943
+ /**
944
+ * Lazy create help command.
945
+ *
946
+ * @return {(Command|null)}
947
+ * @package
948
+ */
949
+ _getHelpCommand() {
950
+ const hasImplicitHelpCommand =
951
+ this._addImplicitHelpCommand ??
952
+ (this.commands.length &&
953
+ !this._actionHandler &&
954
+ !this._findCommand('help'));
955
+
956
+ if (hasImplicitHelpCommand) {
957
+ if (this._helpCommand === undefined) {
958
+ this.helpCommand(undefined, undefined); // use default name and description
959
+ }
960
+ return this._helpCommand;
961
+ }
962
+ return null;
963
+ }
964
+
965
+ /**
966
+ * Add hook for life cycle event.
967
+ *
968
+ * @param {string} event
969
+ * @param {Function} listener
970
+ * @return {Command} `this` command for chaining
971
+ */
972
+
973
+ hook(event, listener) {
974
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
975
+ if (!allowedValues.includes(event)) {
976
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
977
+ Expecting one of '${allowedValues.join("', '")}'`);
978
+ }
979
+ if (this._lifeCycleHooks[event]) {
980
+ this._lifeCycleHooks[event].push(listener);
981
+ } else {
982
+ this._lifeCycleHooks[event] = [listener];
983
+ }
984
+ return this;
985
+ }
986
+
987
+ /**
988
+ * Register callback to use as replacement for calling process.exit.
989
+ *
990
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
991
+ * @return {Command} `this` command for chaining
992
+ */
993
+
994
+ exitOverride(fn) {
995
+ if (fn) {
996
+ this._exitCallback = fn;
997
+ } else {
998
+ this._exitCallback = (err) => {
999
+ if (err.code !== 'commander.executeSubCommandAsync') {
1000
+ throw err;
1001
+ } else {
1002
+ // Async callback from spawn events, not useful to throw.
1003
+ }
1004
+ };
1005
+ }
1006
+ return this;
1007
+ }
1008
+
1009
+ /**
1010
+ * Call process.exit, and _exitCallback if defined.
1011
+ *
1012
+ * @param {number} exitCode exit code for using with process.exit
1013
+ * @param {string} code an id string representing the error
1014
+ * @param {string} message human-readable description of the error
1015
+ * @return never
1016
+ * @private
1017
+ */
1018
+
1019
+ _exit(exitCode, code, message) {
1020
+ if (this._exitCallback) {
1021
+ this._exitCallback(new CommanderError(exitCode, code, message));
1022
+ // Expecting this line is not reached.
1023
+ }
1024
+ process.exit(exitCode);
1025
+ }
1026
+
1027
+ /**
1028
+ * Register callback `fn` for the command.
1029
+ *
1030
+ * @example
1031
+ * program
1032
+ * .command('serve')
1033
+ * .description('start service')
1034
+ * .action(function() {
1035
+ * // do work here
1036
+ * });
1037
+ *
1038
+ * @param {Function} fn
1039
+ * @return {Command} `this` command for chaining
1040
+ */
1041
+
1042
+ action(fn) {
1043
+ const listener = (args) => {
1044
+ // The .action callback takes an extra parameter which is the command or options.
1045
+ const expectedArgsCount = this.registeredArguments.length;
1046
+ const actionArgs = args.slice(0, expectedArgsCount);
1047
+ if (this._storeOptionsAsProperties) {
1048
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
1049
+ } else {
1050
+ actionArgs[expectedArgsCount] = this.opts();
1051
+ }
1052
+ actionArgs.push(this);
1053
+
1054
+ return fn.apply(this, actionArgs);
1055
+ };
1056
+ this._actionHandler = listener;
1057
+ return this;
1058
+ }
1059
+
1060
+ /**
1061
+ * Factory routine to create a new unattached option.
1062
+ *
1063
+ * See .option() for creating an attached option, which uses this routine to
1064
+ * create the option. You can override createOption to return a custom option.
1065
+ *
1066
+ * @param {string} flags
1067
+ * @param {string} [description]
1068
+ * @return {Option} new option
1069
+ */
1070
+
1071
+ createOption(flags, description) {
1072
+ return new Option(flags, description);
1073
+ }
1074
+
1075
+ /**
1076
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1077
+ *
1078
+ * @param {(Option | Argument)} target
1079
+ * @param {string} value
1080
+ * @param {*} previous
1081
+ * @param {string} invalidArgumentMessage
1082
+ * @private
1083
+ */
1084
+
1085
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1086
+ try {
1087
+ return target.parseArg(value, previous);
1088
+ } catch (err) {
1089
+ if (err.code === 'commander.invalidArgument') {
1090
+ const message = `${invalidArgumentMessage} ${err.message}`;
1091
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1092
+ }
1093
+ throw err;
1094
+ }
1095
+ }
1096
+
1097
+ /**
1098
+ * Check for option flag conflicts.
1099
+ * Register option if no conflicts found, or throw on conflict.
1100
+ *
1101
+ * @param {Option} option
1102
+ * @private
1103
+ */
1104
+
1105
+ _registerOption(option) {
1106
+ const matchingOption =
1107
+ (option.short && this._findOption(option.short)) ||
1108
+ (option.long && this._findOption(option.long));
1109
+ if (matchingOption) {
1110
+ const matchingFlag =
1111
+ option.long && this._findOption(option.long)
1112
+ ? option.long
1113
+ : option.short;
1114
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1115
+ - already used by option '${matchingOption.flags}'`);
1116
+ }
1117
+
1118
+ this._initOptionGroup(option);
1119
+ this.options.push(option);
1120
+ }
1121
+
1122
+ /**
1123
+ * Check for command name and alias conflicts with existing commands.
1124
+ * Register command if no conflicts found, or throw on conflict.
1125
+ *
1126
+ * @param {Command} command
1127
+ * @private
1128
+ */
1129
+
1130
+ _registerCommand(command) {
1131
+ const knownBy = (cmd) => {
1132
+ return [cmd.name()].concat(cmd.aliases());
1133
+ };
1134
+
1135
+ const alreadyUsed = knownBy(command).find((name) =>
1136
+ this._findCommand(name),
1137
+ );
1138
+ if (alreadyUsed) {
1139
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
1140
+ const newCmd = knownBy(command).join('|');
1141
+ throw new Error(
1142
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`,
1143
+ );
1144
+ }
1145
+
1146
+ this._initCommandGroup(command);
1147
+ this.commands.push(command);
1148
+ }
1149
+
1150
+ /**
1151
+ * Add an option.
1152
+ *
1153
+ * @param {Option} option
1154
+ * @return {Command} `this` command for chaining
1155
+ */
1156
+ addOption(option) {
1157
+ this._registerOption(option);
1158
+
1159
+ const oname = option.name();
1160
+ const name = option.attributeName();
1161
+
1162
+ // store default value
1163
+ if (option.negate) {
1164
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
1165
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
1166
+ if (!this._findOption(positiveLongFlag)) {
1167
+ this.setOptionValueWithSource(
1168
+ name,
1169
+ option.defaultValue === undefined ? true : option.defaultValue,
1170
+ 'default',
1171
+ );
1172
+ }
1173
+ } else if (option.defaultValue !== undefined) {
1174
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
1175
+ }
1176
+
1177
+ // handler for cli and env supplied values
1178
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1179
+ // val is null for optional option used without an optional-argument.
1180
+ // val is undefined for boolean and negated option.
1181
+ if (val == null && option.presetArg !== undefined) {
1182
+ val = option.presetArg;
1183
+ }
1184
+
1185
+ // custom processing
1186
+ const oldValue = this.getOptionValue(name);
1187
+ if (val !== null && option.parseArg) {
1188
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1189
+ } else if (val !== null && option.variadic) {
1190
+ val = option._collectValue(val, oldValue);
1191
+ }
1192
+
1193
+ // Fill-in appropriate missing values. Long winded but easy to follow.
1194
+ if (val == null) {
1195
+ if (option.negate) {
1196
+ val = false;
1197
+ } else if (option.isBoolean() || option.optional) {
1198
+ val = true;
1199
+ } else {
1200
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
1201
+ }
1202
+ }
1203
+ this.setOptionValueWithSource(name, val, valueSource);
1204
+ };
1205
+
1206
+ this.on('option:' + oname, (val) => {
1207
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1208
+ handleOptionValue(val, invalidValueMessage, 'cli');
1209
+ });
1210
+
1211
+ if (option.envVar) {
1212
+ this.on('optionEnv:' + oname, (val) => {
1213
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1214
+ handleOptionValue(val, invalidValueMessage, 'env');
1215
+ });
1216
+ }
1217
+
1218
+ return this;
1219
+ }
1220
+
1221
+ /**
1222
+ * Internal implementation shared by .option() and .requiredOption()
1223
+ *
1224
+ * @return {Command} `this` command for chaining
1225
+ * @private
1226
+ */
1227
+ _optionEx(config, flags, description, fn, defaultValue) {
1228
+ if (typeof flags === 'object' && flags instanceof Option) {
1229
+ throw new Error(
1230
+ 'To add an Option object use addOption() instead of option() or requiredOption()',
1231
+ );
1232
+ }
1233
+ const option = this.createOption(flags, description);
1234
+ option.makeOptionMandatory(!!config.mandatory);
1235
+ if (typeof fn === 'function') {
1236
+ option.default(defaultValue).argParser(fn);
1237
+ } else if (fn instanceof RegExp) {
1238
+ // deprecated
1239
+ const regex = fn;
1240
+ fn = (val, def) => {
1241
+ const m = regex.exec(val);
1242
+ return m ? m[0] : def;
1243
+ };
1244
+ option.default(defaultValue).argParser(fn);
1245
+ } else {
1246
+ option.default(fn);
1247
+ }
1248
+
1249
+ return this.addOption(option);
1250
+ }
1251
+
1252
+ /**
1253
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1254
+ *
1255
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1256
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1257
+ *
1258
+ * See the README for more details, and see also addOption() and requiredOption().
1259
+ *
1260
+ * @example
1261
+ * program
1262
+ * .option('-p, --pepper', 'add pepper')
1263
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1264
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1265
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1266
+ *
1267
+ * @param {string} flags
1268
+ * @param {string} [description]
1269
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1270
+ * @param {*} [defaultValue]
1271
+ * @return {Command} `this` command for chaining
1272
+ */
1273
+
1274
+ option(flags, description, parseArg, defaultValue) {
1275
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1276
+ }
1277
+
1278
+ /**
1279
+ * Add a required option which must have a value after parsing. This usually means
1280
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1281
+ *
1282
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1283
+ *
1284
+ * @param {string} flags
1285
+ * @param {string} [description]
1286
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1287
+ * @param {*} [defaultValue]
1288
+ * @return {Command} `this` command for chaining
1289
+ */
1290
+
1291
+ requiredOption(flags, description, parseArg, defaultValue) {
1292
+ return this._optionEx(
1293
+ { mandatory: true },
1294
+ flags,
1295
+ description,
1296
+ parseArg,
1297
+ defaultValue,
1298
+ );
1299
+ }
1300
+
1301
+ /**
1302
+ * Alter parsing of short flags with optional values.
1303
+ *
1304
+ * @example
1305
+ * // for `.option('-f,--flag [value]'):
1306
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1307
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1308
+ *
1309
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1310
+ * @return {Command} `this` command for chaining
1311
+ */
1312
+ combineFlagAndOptionalValue(combine = true) {
1313
+ this._combineFlagAndOptionalValue = !!combine;
1314
+ return this;
1315
+ }
1316
+
1317
+ /**
1318
+ * Allow unknown options on the command line.
1319
+ *
1320
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1321
+ * @return {Command} `this` command for chaining
1322
+ */
1323
+ allowUnknownOption(allowUnknown = true) {
1324
+ this._allowUnknownOption = !!allowUnknown;
1325
+ return this;
1326
+ }
1327
+
1328
+ /**
1329
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1330
+ *
1331
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1332
+ * @return {Command} `this` command for chaining
1333
+ */
1334
+ allowExcessArguments(allowExcess = true) {
1335
+ this._allowExcessArguments = !!allowExcess;
1336
+ return this;
1337
+ }
1338
+
1339
+ /**
1340
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1341
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1342
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1343
+ *
1344
+ * @param {boolean} [positional]
1345
+ * @return {Command} `this` command for chaining
1346
+ */
1347
+ enablePositionalOptions(positional = true) {
1348
+ this._enablePositionalOptions = !!positional;
1349
+ return this;
1350
+ }
1351
+
1352
+ /**
1353
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1354
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1355
+ * positional options to have been enabled on the program (parent commands).
1356
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1357
+ *
1358
+ * @param {boolean} [passThrough] for unknown options.
1359
+ * @return {Command} `this` command for chaining
1360
+ */
1361
+ passThroughOptions(passThrough = true) {
1362
+ this._passThroughOptions = !!passThrough;
1363
+ this._checkForBrokenPassThrough();
1364
+ return this;
1365
+ }
1366
+
1367
+ /**
1368
+ * @private
1369
+ */
1370
+
1371
+ _checkForBrokenPassThrough() {
1372
+ if (
1373
+ this.parent &&
1374
+ this._passThroughOptions &&
1375
+ !this.parent._enablePositionalOptions
1376
+ ) {
1377
+ throw new Error(
1378
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,
1379
+ );
1380
+ }
1381
+ }
1382
+
1383
+ /**
1384
+ * Whether to store option values as properties on command object,
1385
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1386
+ *
1387
+ * @param {boolean} [storeAsProperties=true]
1388
+ * @return {Command} `this` command for chaining
1389
+ */
1390
+
1391
+ storeOptionsAsProperties(storeAsProperties = true) {
1392
+ if (this.options.length) {
1393
+ throw new Error('call .storeOptionsAsProperties() before adding options');
1394
+ }
1395
+ if (Object.keys(this._optionValues).length) {
1396
+ throw new Error(
1397
+ 'call .storeOptionsAsProperties() before setting option values',
1398
+ );
1399
+ }
1400
+ this._storeOptionsAsProperties = !!storeAsProperties;
1401
+ return this;
1402
+ }
1403
+
1404
+ /**
1405
+ * Retrieve option value.
1406
+ *
1407
+ * @param {string} key
1408
+ * @return {object} value
1409
+ */
1410
+
1411
+ getOptionValue(key) {
1412
+ if (this._storeOptionsAsProperties) {
1413
+ return this[key];
1414
+ }
1415
+ return this._optionValues[key];
1416
+ }
1417
+
1418
+ /**
1419
+ * Store option value.
1420
+ *
1421
+ * @param {string} key
1422
+ * @param {object} value
1423
+ * @return {Command} `this` command for chaining
1424
+ */
1425
+
1426
+ setOptionValue(key, value) {
1427
+ return this.setOptionValueWithSource(key, value, undefined);
1428
+ }
1429
+
1430
+ /**
1431
+ * Store option value and where the value came from.
1432
+ *
1433
+ * @param {string} key
1434
+ * @param {object} value
1435
+ * @param {string} source - expected values are default/config/env/cli/implied
1436
+ * @return {Command} `this` command for chaining
1437
+ */
1438
+
1439
+ setOptionValueWithSource(key, value, source) {
1440
+ if (this._storeOptionsAsProperties) {
1441
+ this[key] = value;
1442
+ } else {
1443
+ this._optionValues[key] = value;
1444
+ }
1445
+ this._optionValueSources[key] = source;
1446
+ return this;
1447
+ }
1448
+
1449
+ /**
1450
+ * Get source of option value.
1451
+ * Expected values are default | config | env | cli | implied
1452
+ *
1453
+ * @param {string} key
1454
+ * @return {string}
1455
+ */
1456
+
1457
+ getOptionValueSource(key) {
1458
+ return this._optionValueSources[key];
1459
+ }
1460
+
1461
+ /**
1462
+ * Get source of option value. See also .optsWithGlobals().
1463
+ * Expected values are default | config | env | cli | implied
1464
+ *
1465
+ * @param {string} key
1466
+ * @return {string}
1467
+ */
1468
+
1469
+ getOptionValueSourceWithGlobals(key) {
1470
+ // global overwrites local, like optsWithGlobals
1471
+ let source;
1472
+ this._getCommandAndAncestors().forEach((cmd) => {
1473
+ if (cmd.getOptionValueSource(key) !== undefined) {
1474
+ source = cmd.getOptionValueSource(key);
1475
+ }
1476
+ });
1477
+ return source;
1478
+ }
1479
+
1480
+ /**
1481
+ * Get user arguments from implied or explicit arguments.
1482
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1483
+ *
1484
+ * @private
1485
+ */
1486
+
1487
+ _prepareUserArgs(argv, parseOptions) {
1488
+ if (argv !== undefined && !Array.isArray(argv)) {
1489
+ throw new Error('first parameter to parse must be array or undefined');
1490
+ }
1491
+ parseOptions = parseOptions || {};
1492
+
1493
+ // auto-detect argument conventions if nothing supplied
1494
+ if (argv === undefined && parseOptions.from === undefined) {
1495
+ if (process.versions?.electron) {
1496
+ parseOptions.from = 'electron';
1497
+ }
1498
+ // check node specific options for scenarios where user CLI args follow executable without scriptname
1499
+ const execArgv = process.execArgv ?? [];
1500
+ if (
1501
+ execArgv.includes('-e') ||
1502
+ execArgv.includes('--eval') ||
1503
+ execArgv.includes('-p') ||
1504
+ execArgv.includes('--print')
1505
+ ) {
1506
+ parseOptions.from = 'eval'; // internal usage, not documented
1507
+ }
1508
+ }
1509
+
1510
+ // default to using process.argv
1511
+ if (argv === undefined) {
1512
+ argv = process.argv;
1513
+ }
1514
+ this.rawArgs = argv.slice();
1515
+
1516
+ // extract the user args and scriptPath
1517
+ let userArgs;
1518
+ switch (parseOptions.from) {
1519
+ case undefined:
1520
+ case 'node':
1521
+ this._scriptPath = argv[1];
1522
+ userArgs = argv.slice(2);
1523
+ break;
1524
+ case 'electron':
1525
+ // @ts-ignore: because defaultApp is an unknown property
1526
+ if (process.defaultApp) {
1527
+ this._scriptPath = argv[1];
1528
+ userArgs = argv.slice(2);
1529
+ } else {
1530
+ userArgs = argv.slice(1);
1531
+ }
1532
+ break;
1533
+ case 'user':
1534
+ userArgs = argv.slice(0);
1535
+ break;
1536
+ case 'eval':
1537
+ userArgs = argv.slice(1);
1538
+ break;
1539
+ default:
1540
+ throw new Error(
1541
+ `unexpected parse option { from: '${parseOptions.from}' }`,
1542
+ );
1543
+ }
1544
+
1545
+ // Find default name for program from arguments.
1546
+ if (!this._name && this._scriptPath)
1547
+ this.nameFromFilename(this._scriptPath);
1548
+ this._name = this._name || 'program';
1549
+
1550
+ return userArgs;
1551
+ }
1552
+
1553
+ /**
1554
+ * Parse `argv`, setting options and invoking commands when defined.
1555
+ *
1556
+ * Use parseAsync instead of parse if any of your action handlers are async.
1557
+ *
1558
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1559
+ *
1560
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1561
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1562
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1563
+ * - `'user'`: just user arguments
1564
+ *
1565
+ * @example
1566
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1567
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1568
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1569
+ *
1570
+ * @param {string[]} [argv] - optional, defaults to process.argv
1571
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1572
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1573
+ * @return {Command} `this` command for chaining
1574
+ */
1575
+
1576
+ parse(argv, parseOptions) {
1577
+ this._prepareForParse();
1578
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1579
+ this._parseCommand([], userArgs);
1580
+
1581
+ return this;
1582
+ }
1583
+
1584
+ /**
1585
+ * Parse `argv`, setting options and invoking commands when defined.
1586
+ *
1587
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1588
+ *
1589
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1590
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1591
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1592
+ * - `'user'`: just user arguments
1593
+ *
1594
+ * @example
1595
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1596
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1597
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1598
+ *
1599
+ * @param {string[]} [argv]
1600
+ * @param {object} [parseOptions]
1601
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1602
+ * @return {Promise}
1603
+ */
1604
+
1605
+ async parseAsync(argv, parseOptions) {
1606
+ this._prepareForParse();
1607
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1608
+ await this._parseCommand([], userArgs);
1609
+
1610
+ return this;
1611
+ }
1612
+
1613
+ _prepareForParse() {
1614
+ if (this._savedState === null) {
1615
+ this.saveStateBeforeParse();
1616
+ } else {
1617
+ this.restoreStateBeforeParse();
1618
+ }
1619
+ }
1620
+
1621
+ /**
1622
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1623
+ * Not usually called directly, but available for subclasses to save their custom state.
1624
+ *
1625
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1626
+ */
1627
+ saveStateBeforeParse() {
1628
+ this._savedState = {
1629
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
1630
+ _name: this._name,
1631
+ // option values before parse have default values (including false for negated options)
1632
+ // shallow clones
1633
+ _optionValues: { ...this._optionValues },
1634
+ _optionValueSources: { ...this._optionValueSources },
1635
+ };
1636
+ }
1637
+
1638
+ /**
1639
+ * Restore state before parse for calls after the first.
1640
+ * Not usually called directly, but available for subclasses to save their custom state.
1641
+ *
1642
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1643
+ */
1644
+ restoreStateBeforeParse() {
1645
+ if (this._storeOptionsAsProperties)
1646
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1647
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1648
+
1649
+ // clear state from _prepareUserArgs
1650
+ this._name = this._savedState._name;
1651
+ this._scriptPath = null;
1652
+ this.rawArgs = [];
1653
+ // clear state from setOptionValueWithSource
1654
+ this._optionValues = { ...this._savedState._optionValues };
1655
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1656
+ // clear state from _parseCommand
1657
+ this.args = [];
1658
+ // clear state from _processArguments
1659
+ this.processedArgs = [];
1660
+ }
1661
+
1662
+ /**
1663
+ * Throw if expected executable is missing. Add lots of help for author.
1664
+ *
1665
+ * @param {string} executableFile
1666
+ * @param {string} executableDir
1667
+ * @param {string} subcommandName
1668
+ */
1669
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1670
+ if (fs.existsSync(executableFile)) return;
1671
+
1672
+ const executableDirMessage = executableDir
1673
+ ? `searched for local subcommand relative to directory '${executableDir}'`
1674
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1675
+ const executableMissing = `'${executableFile}' does not exist
1676
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1677
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1678
+ - ${executableDirMessage}`;
1679
+ throw new Error(executableMissing);
1680
+ }
1681
+
1682
+ /**
1683
+ * Execute a sub-command executable.
1684
+ *
1685
+ * @private
1686
+ */
1687
+
1688
+ _executeSubCommand(subcommand, args) {
1689
+ args = args.slice();
1690
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
1691
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
1692
+
1693
+ function findFile(baseDir, baseName) {
1694
+ // Look for specified file
1695
+ const localBin = path.resolve(baseDir, baseName);
1696
+ if (fs.existsSync(localBin)) return localBin;
1697
+
1698
+ // Stop looking if candidate already has an expected extension.
1699
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
1700
+
1701
+ // Try all the extensions.
1702
+ const foundExt = sourceExt.find((ext) =>
1703
+ fs.existsSync(`${localBin}${ext}`),
1704
+ );
1705
+ if (foundExt) return `${localBin}${foundExt}`;
1706
+
1707
+ return undefined;
1708
+ }
1709
+
1710
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
1711
+ this._checkForMissingMandatoryOptions();
1712
+ this._checkForConflictingOptions();
1713
+
1714
+ // executableFile and executableDir might be full path, or just a name
1715
+ let executableFile =
1716
+ subcommand._executableFile || `${this._name}-${subcommand._name}`;
1717
+ let executableDir = this._executableDir || '';
1718
+ if (this._scriptPath) {
1719
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
1720
+ try {
1721
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1722
+ } catch {
1723
+ resolvedScriptPath = this._scriptPath;
1724
+ }
1725
+ executableDir = path.resolve(
1726
+ path.dirname(resolvedScriptPath),
1727
+ executableDir,
1728
+ );
1729
+ }
1730
+
1731
+ // Look for a local file in preference to a command in PATH.
1732
+ if (executableDir) {
1733
+ let localFile = findFile(executableDir, executableFile);
1734
+
1735
+ // Legacy search using prefix of script name instead of command name
1736
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1737
+ const legacyName = path.basename(
1738
+ this._scriptPath,
1739
+ path.extname(this._scriptPath),
1740
+ );
1741
+ if (legacyName !== this._name) {
1742
+ localFile = findFile(
1743
+ executableDir,
1744
+ `${legacyName}-${subcommand._name}`,
1745
+ );
1746
+ }
1747
+ }
1748
+ executableFile = localFile || executableFile;
1749
+ }
1750
+
1751
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1752
+
1753
+ let proc;
1754
+ if (process.platform !== 'win32') {
1755
+ if (launchWithNode) {
1756
+ args.unshift(executableFile);
1757
+ // add executable arguments to spawn
1758
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1759
+
1760
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
1761
+ } else {
1762
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
1763
+ }
1764
+ } else {
1765
+ this._checkForMissingExecutable(
1766
+ executableFile,
1767
+ executableDir,
1768
+ subcommand._name,
1769
+ );
1770
+ args.unshift(executableFile);
1771
+ // add executable arguments to spawn
1772
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1773
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
1774
+ }
1775
+
1776
+ if (!proc.killed) {
1777
+ // testing mainly to avoid leak warnings during unit tests with mocked spawn
1778
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1779
+ signals.forEach((signal) => {
1780
+ process.on(signal, () => {
1781
+ if (proc.killed === false && proc.exitCode === null) {
1782
+ // @ts-ignore because signals not typed to known strings
1783
+ proc.kill(signal);
1784
+ }
1785
+ });
1786
+ });
1787
+ }
1788
+
1789
+ // By default terminate process when spawned process terminates.
1790
+ const exitCallback = this._exitCallback;
1791
+ proc.on('close', (code) => {
1792
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
1793
+ if (!exitCallback) {
1794
+ process.exit(code);
1795
+ } else {
1796
+ exitCallback(
1797
+ new CommanderError(
1798
+ code,
1799
+ 'commander.executeSubCommandAsync',
1800
+ '(close)',
1801
+ ),
1802
+ );
1803
+ }
1804
+ });
1805
+ proc.on('error', (err) => {
1806
+ // @ts-ignore: because err.code is an unknown property
1807
+ if (err.code === 'ENOENT') {
1808
+ this._checkForMissingExecutable(
1809
+ executableFile,
1810
+ executableDir,
1811
+ subcommand._name,
1812
+ );
1813
+ // @ts-ignore: because err.code is an unknown property
1814
+ } else if (err.code === 'EACCES') {
1815
+ throw new Error(`'${executableFile}' not executable`);
1816
+ }
1817
+ if (!exitCallback) {
1818
+ process.exit(1);
1819
+ } else {
1820
+ const wrappedError = new CommanderError(
1821
+ 1,
1822
+ 'commander.executeSubCommandAsync',
1823
+ '(error)',
1824
+ );
1825
+ wrappedError.nestedError = err;
1826
+ exitCallback(wrappedError);
1827
+ }
1828
+ });
1829
+
1830
+ // Store the reference to the child process
1831
+ this.runningCommand = proc;
1832
+ }
1833
+
1834
+ /**
1835
+ * @private
1836
+ */
1837
+
1838
+ _dispatchSubcommand(commandName, operands, unknown) {
1839
+ const subCommand = this._findCommand(commandName);
1840
+ if (!subCommand) this.help({ error: true });
1841
+
1842
+ subCommand._prepareForParse();
1843
+ let promiseChain;
1844
+ promiseChain = this._chainOrCallSubCommandHook(
1845
+ promiseChain,
1846
+ subCommand,
1847
+ 'preSubcommand',
1848
+ );
1849
+ promiseChain = this._chainOrCall(promiseChain, () => {
1850
+ if (subCommand._executableHandler) {
1851
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1852
+ } else {
1853
+ return subCommand._parseCommand(operands, unknown);
1854
+ }
1855
+ });
1856
+ return promiseChain;
1857
+ }
1858
+
1859
+ /**
1860
+ * Invoke help directly if possible, or dispatch if necessary.
1861
+ * e.g. help foo
1862
+ *
1863
+ * @private
1864
+ */
1865
+
1866
+ _dispatchHelpCommand(subcommandName) {
1867
+ if (!subcommandName) {
1868
+ this.help();
1869
+ }
1870
+ const subCommand = this._findCommand(subcommandName);
1871
+ if (subCommand && !subCommand._executableHandler) {
1872
+ subCommand.help();
1873
+ }
1874
+
1875
+ // Fallback to parsing the help flag to invoke the help.
1876
+ return this._dispatchSubcommand(
1877
+ subcommandName,
1878
+ [],
1879
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],
1880
+ );
1881
+ }
1882
+
1883
+ /**
1884
+ * Check this.args against expected this.registeredArguments.
1885
+ *
1886
+ * @private
1887
+ */
1888
+
1889
+ _checkNumberOfArguments() {
1890
+ // too few
1891
+ this.registeredArguments.forEach((arg, i) => {
1892
+ if (arg.required && this.args[i] == null) {
1893
+ this.missingArgument(arg.name());
1894
+ }
1895
+ });
1896
+ // too many
1897
+ if (
1898
+ this.registeredArguments.length > 0 &&
1899
+ this.registeredArguments[this.registeredArguments.length - 1].variadic
1900
+ ) {
1901
+ return;
1902
+ }
1903
+ if (this.args.length > this.registeredArguments.length) {
1904
+ this._excessArguments(this.args);
1905
+ }
1906
+ }
1907
+
1908
+ /**
1909
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1910
+ *
1911
+ * @private
1912
+ */
1913
+
1914
+ _processArguments() {
1915
+ const myParseArg = (argument, value, previous) => {
1916
+ // Extra processing for nice error message on parsing failure.
1917
+ let parsedValue = value;
1918
+ if (value !== null && argument.parseArg) {
1919
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1920
+ parsedValue = this._callParseArg(
1921
+ argument,
1922
+ value,
1923
+ previous,
1924
+ invalidValueMessage,
1925
+ );
1926
+ }
1927
+ return parsedValue;
1928
+ };
1929
+
1930
+ this._checkNumberOfArguments();
1931
+
1932
+ const processedArgs = [];
1933
+ this.registeredArguments.forEach((declaredArg, index) => {
1934
+ let value = declaredArg.defaultValue;
1935
+ if (declaredArg.variadic) {
1936
+ // Collect together remaining arguments for passing together as an array.
1937
+ if (index < this.args.length) {
1938
+ value = this.args.slice(index);
1939
+ if (declaredArg.parseArg) {
1940
+ value = value.reduce((processed, v) => {
1941
+ return myParseArg(declaredArg, v, processed);
1942
+ }, declaredArg.defaultValue);
1943
+ }
1944
+ } else if (value === undefined) {
1945
+ value = [];
1946
+ }
1947
+ } else if (index < this.args.length) {
1948
+ value = this.args[index];
1949
+ if (declaredArg.parseArg) {
1950
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1951
+ }
1952
+ }
1953
+ processedArgs[index] = value;
1954
+ });
1955
+ this.processedArgs = processedArgs;
1956
+ }
1957
+
1958
+ /**
1959
+ * Once we have a promise we chain, but call synchronously until then.
1960
+ *
1961
+ * @param {(Promise|undefined)} promise
1962
+ * @param {Function} fn
1963
+ * @return {(Promise|undefined)}
1964
+ * @private
1965
+ */
1966
+
1967
+ _chainOrCall(promise, fn) {
1968
+ // thenable
1969
+ if (promise?.then && typeof promise.then === 'function') {
1970
+ // already have a promise, chain callback
1971
+ return promise.then(() => fn());
1972
+ }
1973
+ // callback might return a promise
1974
+ return fn();
1975
+ }
1976
+
1977
+ /**
1978
+ *
1979
+ * @param {(Promise|undefined)} promise
1980
+ * @param {string} event
1981
+ * @return {(Promise|undefined)}
1982
+ * @private
1983
+ */
1984
+
1985
+ _chainOrCallHooks(promise, event) {
1986
+ let result = promise;
1987
+ const hooks = [];
1988
+ this._getCommandAndAncestors()
1989
+ .reverse()
1990
+ .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)
1991
+ .forEach((hookedCommand) => {
1992
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1993
+ hooks.push({ hookedCommand, callback });
1994
+ });
1995
+ });
1996
+ if (event === 'postAction') {
1997
+ hooks.reverse();
1998
+ }
1999
+
2000
+ hooks.forEach((hookDetail) => {
2001
+ result = this._chainOrCall(result, () => {
2002
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2003
+ });
2004
+ });
2005
+ return result;
2006
+ }
2007
+
2008
+ /**
2009
+ *
2010
+ * @param {(Promise|undefined)} promise
2011
+ * @param {Command} subCommand
2012
+ * @param {string} event
2013
+ * @return {(Promise|undefined)}
2014
+ * @private
2015
+ */
2016
+
2017
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2018
+ let result = promise;
2019
+ if (this._lifeCycleHooks[event] !== undefined) {
2020
+ this._lifeCycleHooks[event].forEach((hook) => {
2021
+ result = this._chainOrCall(result, () => {
2022
+ return hook(this, subCommand);
2023
+ });
2024
+ });
2025
+ }
2026
+ return result;
2027
+ }
2028
+
2029
+ /**
2030
+ * Process arguments in context of this command.
2031
+ * Returns action result, in case it is a promise.
2032
+ *
2033
+ * @private
2034
+ */
2035
+
2036
+ _parseCommand(operands, unknown) {
2037
+ const parsed = this.parseOptions(unknown);
2038
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
2039
+ this._parseOptionsImplied();
2040
+ operands = operands.concat(parsed.operands);
2041
+ unknown = parsed.unknown;
2042
+ this.args = operands.concat(unknown);
2043
+
2044
+ if (operands && this._findCommand(operands[0])) {
2045
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2046
+ }
2047
+ if (
2048
+ this._getHelpCommand() &&
2049
+ operands[0] === this._getHelpCommand().name()
2050
+ ) {
2051
+ return this._dispatchHelpCommand(operands[1]);
2052
+ }
2053
+ if (this._defaultCommandName) {
2054
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
2055
+ return this._dispatchSubcommand(
2056
+ this._defaultCommandName,
2057
+ operands,
2058
+ unknown,
2059
+ );
2060
+ }
2061
+ if (
2062
+ this.commands.length &&
2063
+ this.args.length === 0 &&
2064
+ !this._actionHandler &&
2065
+ !this._defaultCommandName
2066
+ ) {
2067
+ // probably missing subcommand and no handler, user needs help (and exit)
2068
+ this.help({ error: true });
2069
+ }
2070
+
2071
+ this._outputHelpIfRequested(parsed.unknown);
2072
+ this._checkForMissingMandatoryOptions();
2073
+ this._checkForConflictingOptions();
2074
+
2075
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
2076
+ const checkForUnknownOptions = () => {
2077
+ if (parsed.unknown.length > 0) {
2078
+ this.unknownOption(parsed.unknown[0]);
2079
+ }
2080
+ };
2081
+
2082
+ const commandEvent = `command:${this.name()}`;
2083
+ if (this._actionHandler) {
2084
+ checkForUnknownOptions();
2085
+ this._processArguments();
2086
+
2087
+ let promiseChain;
2088
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
2089
+ promiseChain = this._chainOrCall(promiseChain, () =>
2090
+ this._actionHandler(this.processedArgs),
2091
+ );
2092
+ if (this.parent) {
2093
+ promiseChain = this._chainOrCall(promiseChain, () => {
2094
+ this.parent.emit(commandEvent, operands, unknown); // legacy
2095
+ });
2096
+ }
2097
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
2098
+ return promiseChain;
2099
+ }
2100
+ if (this.parent?.listenerCount(commandEvent)) {
2101
+ checkForUnknownOptions();
2102
+ this._processArguments();
2103
+ this.parent.emit(commandEvent, operands, unknown); // legacy
2104
+ } else if (operands.length) {
2105
+ if (this._findCommand('*')) {
2106
+ // legacy default command
2107
+ return this._dispatchSubcommand('*', operands, unknown);
2108
+ }
2109
+ if (this.listenerCount('command:*')) {
2110
+ // skip option check, emit event for possible misspelling suggestion
2111
+ this.emit('command:*', operands, unknown);
2112
+ } else if (this.commands.length) {
2113
+ this.unknownCommand();
2114
+ } else {
2115
+ checkForUnknownOptions();
2116
+ this._processArguments();
2117
+ }
2118
+ } else if (this.commands.length) {
2119
+ checkForUnknownOptions();
2120
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
2121
+ this.help({ error: true });
2122
+ } else {
2123
+ checkForUnknownOptions();
2124
+ this._processArguments();
2125
+ // fall through for caller to handle after calling .parse()
2126
+ }
2127
+ }
2128
+
2129
+ /**
2130
+ * Find matching command.
2131
+ *
2132
+ * @private
2133
+ * @return {Command | undefined}
2134
+ */
2135
+ _findCommand(name) {
2136
+ if (!name) return undefined;
2137
+ return this.commands.find(
2138
+ (cmd) => cmd._name === name || cmd._aliases.includes(name),
2139
+ );
2140
+ }
2141
+
2142
+ /**
2143
+ * Return an option matching `arg` if any.
2144
+ *
2145
+ * @param {string} arg
2146
+ * @return {Option}
2147
+ * @package
2148
+ */
2149
+
2150
+ _findOption(arg) {
2151
+ return this.options.find((option) => option.is(arg));
2152
+ }
2153
+
2154
+ /**
2155
+ * Display an error message if a mandatory option does not have a value.
2156
+ * Called after checking for help flags in leaf subcommand.
2157
+ *
2158
+ * @private
2159
+ */
2160
+
2161
+ _checkForMissingMandatoryOptions() {
2162
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
2163
+ this._getCommandAndAncestors().forEach((cmd) => {
2164
+ cmd.options.forEach((anOption) => {
2165
+ if (
2166
+ anOption.mandatory &&
2167
+ cmd.getOptionValue(anOption.attributeName()) === undefined
2168
+ ) {
2169
+ cmd.missingMandatoryOptionValue(anOption);
2170
+ }
2171
+ });
2172
+ });
2173
+ }
2174
+
2175
+ /**
2176
+ * Display an error message if conflicting options are used together in this.
2177
+ *
2178
+ * @private
2179
+ */
2180
+ _checkForConflictingLocalOptions() {
2181
+ const definedNonDefaultOptions = this.options.filter((option) => {
2182
+ const optionKey = option.attributeName();
2183
+ if (this.getOptionValue(optionKey) === undefined) {
2184
+ return false;
2185
+ }
2186
+ return this.getOptionValueSource(optionKey) !== 'default';
2187
+ });
2188
+
2189
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2190
+ (option) => option.conflictsWith.length > 0,
2191
+ );
2192
+
2193
+ optionsWithConflicting.forEach((option) => {
2194
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
2195
+ option.conflictsWith.includes(defined.attributeName()),
2196
+ );
2197
+ if (conflictingAndDefined) {
2198
+ this._conflictingOption(option, conflictingAndDefined);
2199
+ }
2200
+ });
2201
+ }
2202
+
2203
+ /**
2204
+ * Display an error message if conflicting options are used together.
2205
+ * Called after checking for help flags in leaf subcommand.
2206
+ *
2207
+ * @private
2208
+ */
2209
+ _checkForConflictingOptions() {
2210
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
2211
+ this._getCommandAndAncestors().forEach((cmd) => {
2212
+ cmd._checkForConflictingLocalOptions();
2213
+ });
2214
+ }
2215
+
2216
+ /**
2217
+ * Parse options from `argv` removing known options,
2218
+ * and return argv split into operands and unknown arguments.
2219
+ *
2220
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2221
+ *
2222
+ * Examples:
2223
+ *
2224
+ * argv => operands, unknown
2225
+ * --known kkk op => [op], []
2226
+ * op --known kkk => [op], []
2227
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2228
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2229
+ *
2230
+ * @param {string[]} args
2231
+ * @return {{operands: string[], unknown: string[]}}
2232
+ */
2233
+
2234
+ parseOptions(args) {
2235
+ const operands = []; // operands, not options or values
2236
+ const unknown = []; // first unknown option and remaining unknown args
2237
+ let dest = operands;
2238
+
2239
+ function maybeOption(arg) {
2240
+ return arg.length > 1 && arg[0] === '-';
2241
+ }
2242
+
2243
+ const negativeNumberArg = (arg) => {
2244
+ // return false if not a negative number
2245
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2246
+ // negative number is ok unless digit used as an option in command hierarchy
2247
+ return !this._getCommandAndAncestors().some((cmd) =>
2248
+ cmd.options
2249
+ .map((opt) => opt.short)
2250
+ .some((short) => /^-\d$/.test(short)),
2251
+ );
2252
+ };
2253
+
2254
+ // parse options
2255
+ let activeVariadicOption = null;
2256
+ let activeGroup = null; // working through group of short options, like -abc
2257
+ let i = 0;
2258
+ while (i < args.length || activeGroup) {
2259
+ const arg = activeGroup ?? args[i++];
2260
+ activeGroup = null;
2261
+
2262
+ // literal
2263
+ if (arg === '--') {
2264
+ if (dest === unknown) dest.push(arg);
2265
+ dest.push(...args.slice(i));
2266
+ break;
2267
+ }
2268
+
2269
+ if (
2270
+ activeVariadicOption &&
2271
+ (!maybeOption(arg) || negativeNumberArg(arg))
2272
+ ) {
2273
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2274
+ continue;
2275
+ }
2276
+ activeVariadicOption = null;
2277
+
2278
+ if (maybeOption(arg)) {
2279
+ const option = this._findOption(arg);
2280
+ // recognised option, call listener to assign value with possible custom processing
2281
+ if (option) {
2282
+ if (option.required) {
2283
+ const value = args[i++];
2284
+ if (value === undefined) this.optionMissingArgument(option);
2285
+ this.emit(`option:${option.name()}`, value);
2286
+ } else if (option.optional) {
2287
+ let value = null;
2288
+ // historical behaviour is optional value is following arg unless an option
2289
+ if (
2290
+ i < args.length &&
2291
+ (!maybeOption(args[i]) || negativeNumberArg(args[i]))
2292
+ ) {
2293
+ value = args[i++];
2294
+ }
2295
+ this.emit(`option:${option.name()}`, value);
2296
+ } else {
2297
+ // boolean flag
2298
+ this.emit(`option:${option.name()}`);
2299
+ }
2300
+ activeVariadicOption = option.variadic ? option : null;
2301
+ continue;
2302
+ }
2303
+ }
2304
+
2305
+ // Look for combo options following single dash, eat first one if known.
2306
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
2307
+ const option = this._findOption(`-${arg[1]}`);
2308
+ if (option) {
2309
+ if (
2310
+ option.required ||
2311
+ (option.optional && this._combineFlagAndOptionalValue)
2312
+ ) {
2313
+ // option with value following in same argument
2314
+ this.emit(`option:${option.name()}`, arg.slice(2));
2315
+ } else {
2316
+ // boolean option
2317
+ this.emit(`option:${option.name()}`);
2318
+ // remove the processed option and keep processing group
2319
+ activeGroup = `-${arg.slice(2)}`;
2320
+ }
2321
+ continue;
2322
+ }
2323
+ }
2324
+
2325
+ // Look for known long flag with value, like --foo=bar
2326
+ if (/^--[^=]+=/.test(arg)) {
2327
+ const index = arg.indexOf('=');
2328
+ const option = this._findOption(arg.slice(0, index));
2329
+ if (option && (option.required || option.optional)) {
2330
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2331
+ continue;
2332
+ }
2333
+ }
2334
+
2335
+ // Not a recognised option by this command.
2336
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
2337
+
2338
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
2339
+ // A negative number in a leaf command is not an unknown option.
2340
+ if (
2341
+ dest === operands &&
2342
+ maybeOption(arg) &&
2343
+ !(this.commands.length === 0 && negativeNumberArg(arg))
2344
+ ) {
2345
+ dest = unknown;
2346
+ }
2347
+
2348
+ // If using positionalOptions, stop processing our options at subcommand.
2349
+ if (
2350
+ (this._enablePositionalOptions || this._passThroughOptions) &&
2351
+ operands.length === 0 &&
2352
+ unknown.length === 0
2353
+ ) {
2354
+ if (this._findCommand(arg)) {
2355
+ operands.push(arg);
2356
+ unknown.push(...args.slice(i));
2357
+ break;
2358
+ } else if (
2359
+ this._getHelpCommand() &&
2360
+ arg === this._getHelpCommand().name()
2361
+ ) {
2362
+ operands.push(arg, ...args.slice(i));
2363
+ break;
2364
+ } else if (this._defaultCommandName) {
2365
+ unknown.push(arg, ...args.slice(i));
2366
+ break;
2367
+ }
2368
+ }
2369
+
2370
+ // If using passThroughOptions, stop processing options at first command-argument.
2371
+ if (this._passThroughOptions) {
2372
+ dest.push(arg, ...args.slice(i));
2373
+ break;
2374
+ }
2375
+
2376
+ // add arg
2377
+ dest.push(arg);
2378
+ }
2379
+
2380
+ return { operands, unknown };
2381
+ }
2382
+
2383
+ /**
2384
+ * Return an object containing local option values as key-value pairs.
2385
+ *
2386
+ * @return {object}
2387
+ */
2388
+ opts() {
2389
+ if (this._storeOptionsAsProperties) {
2390
+ // Preserve original behaviour so backwards compatible when still using properties
2391
+ const result = {};
2392
+ const len = this.options.length;
2393
+
2394
+ for (let i = 0; i < len; i++) {
2395
+ const key = this.options[i].attributeName();
2396
+ result[key] =
2397
+ key === this._versionOptionName ? this._version : this[key];
2398
+ }
2399
+ return result;
2400
+ }
2401
+
2402
+ return this._optionValues;
2403
+ }
2404
+
2405
+ /**
2406
+ * Return an object containing merged local and global option values as key-value pairs.
2407
+ *
2408
+ * @return {object}
2409
+ */
2410
+ optsWithGlobals() {
2411
+ // globals overwrite locals
2412
+ return this._getCommandAndAncestors().reduce(
2413
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2414
+ {},
2415
+ );
2416
+ }
2417
+
2418
+ /**
2419
+ * Display error message and exit (or call exitOverride).
2420
+ *
2421
+ * @param {string} message
2422
+ * @param {object} [errorOptions]
2423
+ * @param {string} [errorOptions.code] - an id string representing the error
2424
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2425
+ */
2426
+ error(message, errorOptions) {
2427
+ // output handling
2428
+ this._outputConfiguration.outputError(
2429
+ `${message}\n`,
2430
+ this._outputConfiguration.writeErr,
2431
+ );
2432
+ if (typeof this._showHelpAfterError === 'string') {
2433
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2434
+ } else if (this._showHelpAfterError) {
2435
+ this._outputConfiguration.writeErr('\n');
2436
+ this.outputHelp({ error: true });
2437
+ }
2438
+
2439
+ // exit handling
2440
+ const config = errorOptions || {};
2441
+ const exitCode = config.exitCode || 1;
2442
+ const code = config.code || 'commander.error';
2443
+ this._exit(exitCode, code, message);
2444
+ }
2445
+
2446
+ /**
2447
+ * Apply any option related environment variables, if option does
2448
+ * not have a value from cli or client code.
2449
+ *
2450
+ * @private
2451
+ */
2452
+ _parseOptionsEnv() {
2453
+ this.options.forEach((option) => {
2454
+ if (option.envVar && option.envVar in process.env) {
2455
+ const optionKey = option.attributeName();
2456
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
2457
+ if (
2458
+ this.getOptionValue(optionKey) === undefined ||
2459
+ ['default', 'config', 'env'].includes(
2460
+ this.getOptionValueSource(optionKey),
2461
+ )
2462
+ ) {
2463
+ if (option.required || option.optional) {
2464
+ // option can take a value
2465
+ // keep very simple, optional always takes value
2466
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
2467
+ } else {
2468
+ // boolean
2469
+ // keep very simple, only care that envVar defined and not the value
2470
+ this.emit(`optionEnv:${option.name()}`);
2471
+ }
2472
+ }
2473
+ }
2474
+ });
2475
+ }
2476
+
2477
+ /**
2478
+ * Apply any implied option values, if option is undefined or default value.
2479
+ *
2480
+ * @private
2481
+ */
2482
+ _parseOptionsImplied() {
2483
+ const dualHelper = new DualOptions(this.options);
2484
+ const hasCustomOptionValue = (optionKey) => {
2485
+ return (
2486
+ this.getOptionValue(optionKey) !== undefined &&
2487
+ !['default', 'implied'].includes(this.getOptionValueSource(optionKey))
2488
+ );
2489
+ };
2490
+ this.options
2491
+ .filter(
2492
+ (option) =>
2493
+ option.implied !== undefined &&
2494
+ hasCustomOptionValue(option.attributeName()) &&
2495
+ dualHelper.valueFromOption(
2496
+ this.getOptionValue(option.attributeName()),
2497
+ option,
2498
+ ),
2499
+ )
2500
+ .forEach((option) => {
2501
+ Object.keys(option.implied)
2502
+ .filter((impliedKey) => !hasCustomOptionValue(impliedKey))
2503
+ .forEach((impliedKey) => {
2504
+ this.setOptionValueWithSource(
2505
+ impliedKey,
2506
+ option.implied[impliedKey],
2507
+ 'implied',
2508
+ );
2509
+ });
2510
+ });
2511
+ }
2512
+
2513
+ /**
2514
+ * Argument `name` is missing.
2515
+ *
2516
+ * @param {string} name
2517
+ * @private
2518
+ */
2519
+
2520
+ missingArgument(name) {
2521
+ const message = `error: missing required argument '${name}'`;
2522
+ this.error(message, { code: 'commander.missingArgument' });
2523
+ }
2524
+
2525
+ /**
2526
+ * `Option` is missing an argument.
2527
+ *
2528
+ * @param {Option} option
2529
+ * @private
2530
+ */
2531
+
2532
+ optionMissingArgument(option) {
2533
+ const message = `error: option '${option.flags}' argument missing`;
2534
+ this.error(message, { code: 'commander.optionMissingArgument' });
2535
+ }
2536
+
2537
+ /**
2538
+ * `Option` does not have a value, and is a mandatory option.
2539
+ *
2540
+ * @param {Option} option
2541
+ * @private
2542
+ */
2543
+
2544
+ missingMandatoryOptionValue(option) {
2545
+ const message = `error: required option '${option.flags}' not specified`;
2546
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
2547
+ }
2548
+
2549
+ /**
2550
+ * `Option` conflicts with another option.
2551
+ *
2552
+ * @param {Option} option
2553
+ * @param {Option} conflictingOption
2554
+ * @private
2555
+ */
2556
+ _conflictingOption(option, conflictingOption) {
2557
+ // The calling code does not know whether a negated option is the source of the
2558
+ // value, so do some work to take an educated guess.
2559
+ const findBestOptionFromValue = (option) => {
2560
+ const optionKey = option.attributeName();
2561
+ const optionValue = this.getOptionValue(optionKey);
2562
+ const negativeOption = this.options.find(
2563
+ (target) => target.negate && optionKey === target.attributeName(),
2564
+ );
2565
+ const positiveOption = this.options.find(
2566
+ (target) => !target.negate && optionKey === target.attributeName(),
2567
+ );
2568
+ if (
2569
+ negativeOption &&
2570
+ ((negativeOption.presetArg === undefined && optionValue === false) ||
2571
+ (negativeOption.presetArg !== undefined &&
2572
+ optionValue === negativeOption.presetArg))
2573
+ ) {
2574
+ return negativeOption;
2575
+ }
2576
+ return positiveOption || option;
2577
+ };
2578
+
2579
+ const getErrorMessage = (option) => {
2580
+ const bestOption = findBestOptionFromValue(option);
2581
+ const optionKey = bestOption.attributeName();
2582
+ const source = this.getOptionValueSource(optionKey);
2583
+ if (source === 'env') {
2584
+ return `environment variable '${bestOption.envVar}'`;
2585
+ }
2586
+ return `option '${bestOption.flags}'`;
2587
+ };
2588
+
2589
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2590
+ this.error(message, { code: 'commander.conflictingOption' });
2591
+ }
2592
+
2593
+ /**
2594
+ * Unknown option `flag`.
2595
+ *
2596
+ * @param {string} flag
2597
+ * @private
2598
+ */
2599
+
2600
+ unknownOption(flag) {
2601
+ if (this._allowUnknownOption) return;
2602
+ let suggestion = '';
2603
+
2604
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2605
+ // Looping to pick up the global options too
2606
+ let candidateFlags = [];
2607
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2608
+ let command = this;
2609
+ do {
2610
+ const moreFlags = command
2611
+ .createHelp()
2612
+ .visibleOptions(command)
2613
+ .filter((option) => option.long)
2614
+ .map((option) => option.long);
2615
+ candidateFlags = candidateFlags.concat(moreFlags);
2616
+ command = command.parent;
2617
+ } while (command && !command._enablePositionalOptions);
2618
+ suggestion = suggestSimilar(flag, candidateFlags);
2619
+ }
2620
+
2621
+ const message = `error: unknown option '${flag}'${suggestion}`;
2622
+ this.error(message, { code: 'commander.unknownOption' });
2623
+ }
2624
+
2625
+ /**
2626
+ * Excess arguments, more than expected.
2627
+ *
2628
+ * @param {string[]} receivedArgs
2629
+ * @private
2630
+ */
2631
+
2632
+ _excessArguments(receivedArgs) {
2633
+ if (this._allowExcessArguments) return;
2634
+
2635
+ const expected = this.registeredArguments.length;
2636
+ const s = expected === 1 ? '' : 's';
2637
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2638
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2639
+ this.error(message, { code: 'commander.excessArguments' });
2640
+ }
2641
+
2642
+ /**
2643
+ * Unknown command.
2644
+ *
2645
+ * @private
2646
+ */
2647
+
2648
+ unknownCommand() {
2649
+ const unknownName = this.args[0];
2650
+ let suggestion = '';
2651
+
2652
+ if (this._showSuggestionAfterError) {
2653
+ const candidateNames = [];
2654
+ this.createHelp()
2655
+ .visibleCommands(this)
2656
+ .forEach((command) => {
2657
+ candidateNames.push(command.name());
2658
+ // just visible alias
2659
+ if (command.alias()) candidateNames.push(command.alias());
2660
+ });
2661
+ suggestion = suggestSimilar(unknownName, candidateNames);
2662
+ }
2663
+
2664
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2665
+ this.error(message, { code: 'commander.unknownCommand' });
2666
+ }
2667
+
2668
+ /**
2669
+ * Get or set the program version.
2670
+ *
2671
+ * This method auto-registers the "-V, --version" option which will print the version number.
2672
+ *
2673
+ * You can optionally supply the flags and description to override the defaults.
2674
+ *
2675
+ * @param {string} [str]
2676
+ * @param {string} [flags]
2677
+ * @param {string} [description]
2678
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2679
+ */
2680
+
2681
+ version(str, flags, description) {
2682
+ if (str === undefined) return this._version;
2683
+ this._version = str;
2684
+ flags = flags || '-V, --version';
2685
+ description = description || 'output the version number';
2686
+ const versionOption = this.createOption(flags, description);
2687
+ this._versionOptionName = versionOption.attributeName();
2688
+ this._registerOption(versionOption);
2689
+
2690
+ this.on('option:' + versionOption.name(), () => {
2691
+ this._outputConfiguration.writeOut(`${str}\n`);
2692
+ this._exit(0, 'commander.version', str);
2693
+ });
2694
+ return this;
2695
+ }
2696
+
2697
+ /**
2698
+ * Set the description.
2699
+ *
2700
+ * @param {string} [str]
2701
+ * @param {object} [argsDescription]
2702
+ * @return {(string|Command)}
2703
+ */
2704
+ description(str, argsDescription) {
2705
+ if (str === undefined && argsDescription === undefined)
2706
+ return this._description;
2707
+ this._description = str;
2708
+ if (argsDescription) {
2709
+ this._argsDescription = argsDescription;
2710
+ }
2711
+ return this;
2712
+ }
2713
+
2714
+ /**
2715
+ * Set the summary. Used when listed as subcommand of parent.
2716
+ *
2717
+ * @param {string} [str]
2718
+ * @return {(string|Command)}
2719
+ */
2720
+ summary(str) {
2721
+ if (str === undefined) return this._summary;
2722
+ this._summary = str;
2723
+ return this;
2724
+ }
2725
+
2726
+ /**
2727
+ * Set an alias for the command.
2728
+ *
2729
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2730
+ *
2731
+ * @param {string} [alias]
2732
+ * @return {(string|Command)}
2733
+ */
2734
+
2735
+ alias(alias) {
2736
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2737
+
2738
+ /** @type {Command} */
2739
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2740
+ let command = this;
2741
+ if (
2742
+ this.commands.length !== 0 &&
2743
+ this.commands[this.commands.length - 1]._executableHandler
2744
+ ) {
2745
+ // assume adding alias for last added executable subcommand, rather than this
2746
+ command = this.commands[this.commands.length - 1];
2747
+ }
2748
+
2749
+ if (alias === command._name)
2750
+ throw new Error("Command alias can't be the same as its name");
2751
+ const matchingCommand = this.parent?._findCommand(alias);
2752
+ if (matchingCommand) {
2753
+ // c.f. _registerCommand
2754
+ const existingCmd = [matchingCommand.name()]
2755
+ .concat(matchingCommand.aliases())
2756
+ .join('|');
2757
+ throw new Error(
2758
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,
2759
+ );
2760
+ }
2761
+
2762
+ command._aliases.push(alias);
2763
+ return this;
2764
+ }
2765
+
2766
+ /**
2767
+ * Set aliases for the command.
2768
+ *
2769
+ * Only the first alias is shown in the auto-generated help.
2770
+ *
2771
+ * @param {string[]} [aliases]
2772
+ * @return {(string[]|Command)}
2773
+ */
2774
+
2775
+ aliases(aliases) {
2776
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2777
+ if (aliases === undefined) return this._aliases;
2778
+
2779
+ aliases.forEach((alias) => this.alias(alias));
2780
+ return this;
2781
+ }
2782
+
2783
+ /**
2784
+ * Set / get the command usage `str`.
2785
+ *
2786
+ * @param {string} [str]
2787
+ * @return {(string|Command)}
2788
+ */
2789
+
2790
+ usage(str) {
2791
+ if (str === undefined) {
2792
+ if (this._usage) return this._usage;
2793
+
2794
+ const args = this.registeredArguments.map((arg) => {
2795
+ return humanReadableArgName(arg);
2796
+ });
2797
+ return []
2798
+ .concat(
2799
+ this.options.length || this._helpOption !== null ? '[options]' : [],
2800
+ this.commands.length ? '[command]' : [],
2801
+ this.registeredArguments.length ? args : [],
2802
+ )
2803
+ .join(' ');
2804
+ }
2805
+
2806
+ this._usage = str;
2807
+ return this;
2808
+ }
2809
+
2810
+ /**
2811
+ * Get or set the name of the command.
2812
+ *
2813
+ * @param {string} [str]
2814
+ * @return {(string|Command)}
2815
+ */
2816
+
2817
+ name(str) {
2818
+ if (str === undefined) return this._name;
2819
+ this._name = str;
2820
+ return this;
2821
+ }
2822
+
2823
+ /**
2824
+ * Set/get the help group heading for this subcommand in parent command's help.
2825
+ *
2826
+ * @param {string} [heading]
2827
+ * @return {Command | string}
2828
+ */
2829
+
2830
+ helpGroup(heading) {
2831
+ if (heading === undefined) return this._helpGroupHeading ?? '';
2832
+ this._helpGroupHeading = heading;
2833
+ return this;
2834
+ }
2835
+
2836
+ /**
2837
+ * Set/get the default help group heading for subcommands added to this command.
2838
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2839
+ *
2840
+ * @example
2841
+ * program.commandsGroup('Development Commands:);
2842
+ * program.command('watch')...
2843
+ * program.command('lint')...
2844
+ * ...
2845
+ *
2846
+ * @param {string} [heading]
2847
+ * @returns {Command | string}
2848
+ */
2849
+ commandsGroup(heading) {
2850
+ if (heading === undefined) return this._defaultCommandGroup ?? '';
2851
+ this._defaultCommandGroup = heading;
2852
+ return this;
2853
+ }
2854
+
2855
+ /**
2856
+ * Set/get the default help group heading for options added to this command.
2857
+ * (This does not override a group set directly on the option using .helpGroup().)
2858
+ *
2859
+ * @example
2860
+ * program
2861
+ * .optionsGroup('Development Options:')
2862
+ * .option('-d, --debug', 'output extra debugging')
2863
+ * .option('-p, --profile', 'output profiling information')
2864
+ *
2865
+ * @param {string} [heading]
2866
+ * @returns {Command | string}
2867
+ */
2868
+ optionsGroup(heading) {
2869
+ if (heading === undefined) return this._defaultOptionGroup ?? '';
2870
+ this._defaultOptionGroup = heading;
2871
+ return this;
2872
+ }
2873
+
2874
+ /**
2875
+ * @param {Option} option
2876
+ * @private
2877
+ */
2878
+ _initOptionGroup(option) {
2879
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
2880
+ option.helpGroup(this._defaultOptionGroup);
2881
+ }
2882
+
2883
+ /**
2884
+ * @param {Command} cmd
2885
+ * @private
2886
+ */
2887
+ _initCommandGroup(cmd) {
2888
+ if (this._defaultCommandGroup && !cmd.helpGroup())
2889
+ cmd.helpGroup(this._defaultCommandGroup);
2890
+ }
2891
+
2892
+ /**
2893
+ * Set the name of the command from script filename, such as process.argv[1],
2894
+ * or require.main.filename, or __filename.
2895
+ *
2896
+ * (Used internally and public although not documented in README.)
2897
+ *
2898
+ * @example
2899
+ * program.nameFromFilename(require.main.filename);
2900
+ *
2901
+ * @param {string} filename
2902
+ * @return {Command}
2903
+ */
2904
+
2905
+ nameFromFilename(filename) {
2906
+ this._name = path.basename(filename, path.extname(filename));
2907
+
2908
+ return this;
2909
+ }
2910
+
2911
+ /**
2912
+ * Get or set the directory for searching for executable subcommands of this command.
2913
+ *
2914
+ * @example
2915
+ * program.executableDir(__dirname);
2916
+ * // or
2917
+ * program.executableDir('subcommands');
2918
+ *
2919
+ * @param {string} [path]
2920
+ * @return {(string|null|Command)}
2921
+ */
2922
+
2923
+ executableDir(path) {
2924
+ if (path === undefined) return this._executableDir;
2925
+ this._executableDir = path;
2926
+ return this;
2927
+ }
2928
+
2929
+ /**
2930
+ * Return program help documentation.
2931
+ *
2932
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2933
+ * @return {string}
2934
+ */
2935
+
2936
+ helpInformation(contextOptions) {
2937
+ const helper = this.createHelp();
2938
+ const context = this._getOutputContext(contextOptions);
2939
+ helper.prepareContext({
2940
+ error: context.error,
2941
+ helpWidth: context.helpWidth,
2942
+ outputHasColors: context.hasColors,
2943
+ });
2944
+ const text = helper.formatHelp(this, helper);
2945
+ if (context.hasColors) return text;
2946
+ return this._outputConfiguration.stripColor(text);
2947
+ }
2948
+
2949
+ /**
2950
+ * @typedef HelpContext
2951
+ * @type {object}
2952
+ * @property {boolean} error
2953
+ * @property {number} helpWidth
2954
+ * @property {boolean} hasColors
2955
+ * @property {function} write - includes stripColor if needed
2956
+ *
2957
+ * @returns {HelpContext}
2958
+ * @private
2959
+ */
2960
+
2961
+ _getOutputContext(contextOptions) {
2962
+ contextOptions = contextOptions || {};
2963
+ const error = !!contextOptions.error;
2964
+ let baseWrite;
2965
+ let hasColors;
2966
+ let helpWidth;
2967
+ if (error) {
2968
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2969
+ hasColors = this._outputConfiguration.getErrHasColors();
2970
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2971
+ } else {
2972
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2973
+ hasColors = this._outputConfiguration.getOutHasColors();
2974
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2975
+ }
2976
+ const write = (str) => {
2977
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2978
+ return baseWrite(str);
2979
+ };
2980
+ return { error, write, hasColors, helpWidth };
2981
+ }
2982
+
2983
+ /**
2984
+ * Output help information for this command.
2985
+ *
2986
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2987
+ *
2988
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2989
+ */
2990
+
2991
+ outputHelp(contextOptions) {
2992
+ let deprecatedCallback;
2993
+ if (typeof contextOptions === 'function') {
2994
+ deprecatedCallback = contextOptions;
2995
+ contextOptions = undefined;
2996
+ }
2997
+
2998
+ const outputContext = this._getOutputContext(contextOptions);
2999
+ /** @type {HelpTextEventContext} */
3000
+ const eventContext = {
3001
+ error: outputContext.error,
3002
+ write: outputContext.write,
3003
+ command: this,
3004
+ };
3005
+
3006
+ this._getCommandAndAncestors()
3007
+ .reverse()
3008
+ .forEach((command) => command.emit('beforeAllHelp', eventContext));
3009
+ this.emit('beforeHelp', eventContext);
3010
+
3011
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3012
+ if (deprecatedCallback) {
3013
+ helpInformation = deprecatedCallback(helpInformation);
3014
+ if (
3015
+ typeof helpInformation !== 'string' &&
3016
+ !Buffer.isBuffer(helpInformation)
3017
+ ) {
3018
+ throw new Error('outputHelp callback must return a string or a Buffer');
3019
+ }
3020
+ }
3021
+ outputContext.write(helpInformation);
3022
+
3023
+ if (this._getHelpOption()?.long) {
3024
+ this.emit(this._getHelpOption().long); // deprecated
3025
+ }
3026
+ this.emit('afterHelp', eventContext);
3027
+ this._getCommandAndAncestors().forEach((command) =>
3028
+ command.emit('afterAllHelp', eventContext),
3029
+ );
3030
+ }
3031
+
3032
+ /**
3033
+ * You can pass in flags and a description to customise the built-in help option.
3034
+ * Pass in false to disable the built-in help option.
3035
+ *
3036
+ * @example
3037
+ * program.helpOption('-?, --help' 'show help'); // customise
3038
+ * program.helpOption(false); // disable
3039
+ *
3040
+ * @param {(string | boolean)} flags
3041
+ * @param {string} [description]
3042
+ * @return {Command} `this` command for chaining
3043
+ */
3044
+
3045
+ helpOption(flags, description) {
3046
+ // Support enabling/disabling built-in help option.
3047
+ if (typeof flags === 'boolean') {
3048
+ if (flags) {
3049
+ if (this._helpOption === null) this._helpOption = undefined; // reenable
3050
+ if (this._defaultOptionGroup) {
3051
+ // make the option to store the group
3052
+ this._initOptionGroup(this._getHelpOption());
3053
+ }
3054
+ } else {
3055
+ this._helpOption = null; // disable
3056
+ }
3057
+ return this;
3058
+ }
3059
+
3060
+ // Customise flags and description.
3061
+ this._helpOption = this.createOption(
3062
+ flags ?? '-h, --help',
3063
+ description ?? 'display help for command',
3064
+ );
3065
+ // init group unless lazy create
3066
+ if (flags || description) this._initOptionGroup(this._helpOption);
3067
+
3068
+ return this;
3069
+ }
3070
+
3071
+ /**
3072
+ * Lazy create help option.
3073
+ * Returns null if has been disabled with .helpOption(false).
3074
+ *
3075
+ * @returns {(Option | null)} the help option
3076
+ * @package
3077
+ */
3078
+ _getHelpOption() {
3079
+ // Lazy create help option on demand.
3080
+ if (this._helpOption === undefined) {
3081
+ this.helpOption(undefined, undefined);
3082
+ }
3083
+ return this._helpOption;
3084
+ }
3085
+
3086
+ /**
3087
+ * Supply your own option to use for the built-in help option.
3088
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3089
+ *
3090
+ * @param {Option} option
3091
+ * @return {Command} `this` command for chaining
3092
+ */
3093
+ addHelpOption(option) {
3094
+ this._helpOption = option;
3095
+ this._initOptionGroup(option);
3096
+ return this;
3097
+ }
3098
+
3099
+ /**
3100
+ * Output help information and exit.
3101
+ *
3102
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3103
+ *
3104
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3105
+ */
3106
+
3107
+ help(contextOptions) {
3108
+ this.outputHelp(contextOptions);
3109
+ let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number
3110
+ if (
3111
+ exitCode === 0 &&
3112
+ contextOptions &&
3113
+ typeof contextOptions !== 'function' &&
3114
+ contextOptions.error
3115
+ ) {
3116
+ exitCode = 1;
3117
+ }
3118
+ // message: do not have all displayed text available so only passing placeholder.
3119
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
3120
+ }
3121
+
3122
+ /**
3123
+ * // Do a little typing to coordinate emit and listener for the help text events.
3124
+ * @typedef HelpTextEventContext
3125
+ * @type {object}
3126
+ * @property {boolean} error
3127
+ * @property {Command} command
3128
+ * @property {function} write
3129
+ */
3130
+
3131
+ /**
3132
+ * Add additional text to be displayed with the built-in help.
3133
+ *
3134
+ * Position is 'before' or 'after' to affect just this command,
3135
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3136
+ *
3137
+ * @param {string} position - before or after built-in help
3138
+ * @param {(string | Function)} text - string to add, or a function returning a string
3139
+ * @return {Command} `this` command for chaining
3140
+ */
3141
+
3142
+ addHelpText(position, text) {
3143
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
3144
+ if (!allowedValues.includes(position)) {
3145
+ throw new Error(`Unexpected value for position to addHelpText.
3146
+ Expecting one of '${allowedValues.join("', '")}'`);
3147
+ }
3148
+
3149
+ const helpEvent = `${position}Help`;
3150
+ this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {
3151
+ let helpStr;
3152
+ if (typeof text === 'function') {
3153
+ helpStr = text({ error: context.error, command: context.command });
3154
+ } else {
3155
+ helpStr = text;
3156
+ }
3157
+ // Ignore falsy value when nothing to output.
3158
+ if (helpStr) {
3159
+ context.write(`${helpStr}\n`);
3160
+ }
3161
+ });
3162
+ return this;
3163
+ }
3164
+
3165
+ /**
3166
+ * Output help information if help flags specified
3167
+ *
3168
+ * @param {Array} args - array of options to search for help flags
3169
+ * @private
3170
+ */
3171
+
3172
+ _outputHelpIfRequested(args) {
3173
+ const helpOption = this._getHelpOption();
3174
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3175
+ if (helpRequested) {
3176
+ this.outputHelp();
3177
+ // (Do not have all displayed text available so only passing placeholder.)
3178
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
3179
+ }
3180
+ }
3181
+ }
3182
+
3183
+ /**
3184
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3185
+ *
3186
+ * @param {string[]} args - array of arguments from node.execArgv
3187
+ * @returns {string[]}
3188
+ * @private
3189
+ */
3190
+
3191
+ function incrementNodeInspectorPort(args) {
3192
+ // Testing for these options:
3193
+ // --inspect[=[host:]port]
3194
+ // --inspect-brk[=[host:]port]
3195
+ // --inspect-port=[host:]port
3196
+ return args.map((arg) => {
3197
+ if (!arg.startsWith('--inspect')) {
3198
+ return arg;
3199
+ }
3200
+ let debugOption;
3201
+ let debugHost = '127.0.0.1';
3202
+ let debugPort = '9229';
3203
+ let match;
3204
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3205
+ // e.g. --inspect
3206
+ debugOption = match[1];
3207
+ } else if (
3208
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null
3209
+ ) {
3210
+ debugOption = match[1];
3211
+ if (/^\d+$/.test(match[3])) {
3212
+ // e.g. --inspect=1234
3213
+ debugPort = match[3];
3214
+ } else {
3215
+ // e.g. --inspect=localhost
3216
+ debugHost = match[3];
3217
+ }
3218
+ } else if (
3219
+ (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null
3220
+ ) {
3221
+ // e.g. --inspect=localhost:1234
3222
+ debugOption = match[1];
3223
+ debugHost = match[3];
3224
+ debugPort = match[4];
3225
+ }
3226
+
3227
+ if (debugOption && debugPort !== '0') {
3228
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3229
+ }
3230
+ return arg;
3231
+ });
3232
+ }
3233
+
3234
+ /**
3235
+ * @returns {boolean | undefined}
3236
+ * @package
3237
+ */
3238
+ function useColor() {
3239
+ // Test for common conventions.
3240
+ // NB: the observed behaviour is in combination with how author adds color! For example:
3241
+ // - we do not test NODE_DISABLE_COLORS, but util:styletext does
3242
+ // - we do test NO_COLOR, but Chalk does not
3243
+ //
3244
+ // References:
3245
+ // https://no-color.org
3246
+ // https://bixense.com/clicolors/
3247
+ // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109
3248
+ // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33
3249
+ // (https://force-color.org recent web page from 2023, does not match major javascript implementations)
3250
+
3251
+ if (
3252
+ process.env.NO_COLOR ||
3253
+ process.env.FORCE_COLOR === '0' ||
3254
+ process.env.FORCE_COLOR === 'false'
3255
+ )
3256
+ return false;
3257
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
3258
+ return true;
3259
+ return undefined;
3260
+ }
3261
+
3262
+ exports.Command = Command;
3263
+ exports.useColor = useColor; // exporting for tests
3264
+
3265
+
3266
+ /***/ }),
3267
+
3268
+ /***/ 135:
3269
+ /***/ ((__unused_webpack_module, exports) => {
3270
+
3271
+ /**
3272
+ * CommanderError class
3273
+ */
3274
+ class CommanderError extends Error {
3275
+ /**
3276
+ * Constructs the CommanderError class
3277
+ * @param {number} exitCode suggested exit code which could be used with process.exit
3278
+ * @param {string} code an id string representing the error
3279
+ * @param {string} message human-readable description of the error
3280
+ */
3281
+ constructor(exitCode, code, message) {
3282
+ super(message);
3283
+ // properly capture stack trace in Node.js
3284
+ Error.captureStackTrace(this, this.constructor);
3285
+ this.name = this.constructor.name;
3286
+ this.code = code;
3287
+ this.exitCode = exitCode;
3288
+ this.nestedError = undefined;
3289
+ }
3290
+ }
3291
+
3292
+ /**
3293
+ * InvalidArgumentError class
3294
+ */
3295
+ class InvalidArgumentError extends CommanderError {
3296
+ /**
3297
+ * Constructs the InvalidArgumentError class
3298
+ * @param {string} [message] explanation of why argument is invalid
3299
+ */
3300
+ constructor(message) {
3301
+ super(1, 'commander.invalidArgument', message);
3302
+ // properly capture stack trace in Node.js
3303
+ Error.captureStackTrace(this, this.constructor);
3304
+ this.name = this.constructor.name;
3305
+ }
3306
+ }
3307
+
3308
+ exports.CommanderError = CommanderError;
3309
+ exports.InvalidArgumentError = InvalidArgumentError;
3310
+
3311
+
3312
+ /***/ }),
3313
+
3314
+ /***/ 754:
3315
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
3316
+
3317
+ const { humanReadableArgName } = __nccwpck_require__(154);
3318
+
3319
+ /**
3320
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
3321
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
3322
+ * @typedef { import("./argument.js").Argument } Argument
3323
+ * @typedef { import("./command.js").Command } Command
3324
+ * @typedef { import("./option.js").Option } Option
3325
+ */
3326
+
3327
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
3328
+ class Help {
3329
+ constructor() {
3330
+ this.helpWidth = undefined;
3331
+ this.minWidthToWrap = 40;
3332
+ this.sortSubcommands = false;
3333
+ this.sortOptions = false;
3334
+ this.showGlobalOptions = false;
3335
+ }
3336
+
3337
+ /**
3338
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
3339
+ * and just before calling `formatHelp()`.
3340
+ *
3341
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
3342
+ *
3343
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
3344
+ */
3345
+ prepareContext(contextOptions) {
3346
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
3347
+ }
3348
+
3349
+ /**
3350
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
3351
+ *
3352
+ * @param {Command} cmd
3353
+ * @returns {Command[]}
3354
+ */
3355
+
3356
+ visibleCommands(cmd) {
3357
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
3358
+ const helpCommand = cmd._getHelpCommand();
3359
+ if (helpCommand && !helpCommand._hidden) {
3360
+ visibleCommands.push(helpCommand);
3361
+ }
3362
+ if (this.sortSubcommands) {
3363
+ visibleCommands.sort((a, b) => {
3364
+ // @ts-ignore: because overloaded return type
3365
+ return a.name().localeCompare(b.name());
3366
+ });
3367
+ }
3368
+ return visibleCommands;
3369
+ }
3370
+
3371
+ /**
3372
+ * Compare options for sort.
3373
+ *
3374
+ * @param {Option} a
3375
+ * @param {Option} b
3376
+ * @returns {number}
3377
+ */
3378
+ compareOptions(a, b) {
3379
+ const getSortKey = (option) => {
3380
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
3381
+ return option.short
3382
+ ? option.short.replace(/^-/, '')
3383
+ : option.long.replace(/^--/, '');
3384
+ };
3385
+ return getSortKey(a).localeCompare(getSortKey(b));
3386
+ }
3387
+
3388
+ /**
3389
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
3390
+ *
3391
+ * @param {Command} cmd
3392
+ * @returns {Option[]}
3393
+ */
3394
+
3395
+ visibleOptions(cmd) {
3396
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
3397
+ // Built-in help option.
3398
+ const helpOption = cmd._getHelpOption();
3399
+ if (helpOption && !helpOption.hidden) {
3400
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
3401
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
3402
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
3403
+ if (!removeShort && !removeLong) {
3404
+ visibleOptions.push(helpOption); // no changes needed
3405
+ } else if (helpOption.long && !removeLong) {
3406
+ visibleOptions.push(
3407
+ cmd.createOption(helpOption.long, helpOption.description),
3408
+ );
3409
+ } else if (helpOption.short && !removeShort) {
3410
+ visibleOptions.push(
3411
+ cmd.createOption(helpOption.short, helpOption.description),
3412
+ );
3413
+ }
3414
+ }
3415
+ if (this.sortOptions) {
3416
+ visibleOptions.sort(this.compareOptions);
3417
+ }
3418
+ return visibleOptions;
3419
+ }
3420
+
3421
+ /**
3422
+ * Get an array of the visible global options. (Not including help.)
3423
+ *
3424
+ * @param {Command} cmd
3425
+ * @returns {Option[]}
3426
+ */
3427
+
3428
+ visibleGlobalOptions(cmd) {
3429
+ if (!this.showGlobalOptions) return [];
3430
+
3431
+ const globalOptions = [];
3432
+ for (
3433
+ let ancestorCmd = cmd.parent;
3434
+ ancestorCmd;
3435
+ ancestorCmd = ancestorCmd.parent
3436
+ ) {
3437
+ const visibleOptions = ancestorCmd.options.filter(
3438
+ (option) => !option.hidden,
3439
+ );
3440
+ globalOptions.push(...visibleOptions);
3441
+ }
3442
+ if (this.sortOptions) {
3443
+ globalOptions.sort(this.compareOptions);
3444
+ }
3445
+ return globalOptions;
3446
+ }
3447
+
3448
+ /**
3449
+ * Get an array of the arguments if any have a description.
3450
+ *
3451
+ * @param {Command} cmd
3452
+ * @returns {Argument[]}
3453
+ */
3454
+
3455
+ visibleArguments(cmd) {
3456
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
3457
+ if (cmd._argsDescription) {
3458
+ cmd.registeredArguments.forEach((argument) => {
3459
+ argument.description =
3460
+ argument.description || cmd._argsDescription[argument.name()] || '';
3461
+ });
3462
+ }
3463
+
3464
+ // If there are any arguments with a description then return all the arguments.
3465
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
3466
+ return cmd.registeredArguments;
3467
+ }
3468
+ return [];
3469
+ }
3470
+
3471
+ /**
3472
+ * Get the command term to show in the list of subcommands.
3473
+ *
3474
+ * @param {Command} cmd
3475
+ * @returns {string}
3476
+ */
3477
+
3478
+ subcommandTerm(cmd) {
3479
+ // Legacy. Ignores custom usage string, and nested commands.
3480
+ const args = cmd.registeredArguments
3481
+ .map((arg) => humanReadableArgName(arg))
3482
+ .join(' ');
3483
+ return (
3484
+ cmd._name +
3485
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
3486
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
3487
+ (args ? ' ' + args : '')
3488
+ );
3489
+ }
3490
+
3491
+ /**
3492
+ * Get the option term to show in the list of options.
3493
+ *
3494
+ * @param {Option} option
3495
+ * @returns {string}
3496
+ */
3497
+
3498
+ optionTerm(option) {
3499
+ return option.flags;
3500
+ }
3501
+
3502
+ /**
3503
+ * Get the argument term to show in the list of arguments.
3504
+ *
3505
+ * @param {Argument} argument
3506
+ * @returns {string}
3507
+ */
3508
+
3509
+ argumentTerm(argument) {
3510
+ return argument.name();
3511
+ }
3512
+
3513
+ /**
3514
+ * Get the longest command term length.
3515
+ *
3516
+ * @param {Command} cmd
3517
+ * @param {Help} helper
3518
+ * @returns {number}
3519
+ */
3520
+
3521
+ longestSubcommandTermLength(cmd, helper) {
3522
+ return helper.visibleCommands(cmd).reduce((max, command) => {
3523
+ return Math.max(
3524
+ max,
3525
+ this.displayWidth(
3526
+ helper.styleSubcommandTerm(helper.subcommandTerm(command)),
3527
+ ),
3528
+ );
3529
+ }, 0);
3530
+ }
3531
+
3532
+ /**
3533
+ * Get the longest option term length.
3534
+ *
3535
+ * @param {Command} cmd
3536
+ * @param {Help} helper
3537
+ * @returns {number}
3538
+ */
3539
+
3540
+ longestOptionTermLength(cmd, helper) {
3541
+ return helper.visibleOptions(cmd).reduce((max, option) => {
3542
+ return Math.max(
3543
+ max,
3544
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
3545
+ );
3546
+ }, 0);
3547
+ }
3548
+
3549
+ /**
3550
+ * Get the longest global option term length.
3551
+ *
3552
+ * @param {Command} cmd
3553
+ * @param {Help} helper
3554
+ * @returns {number}
3555
+ */
3556
+
3557
+ longestGlobalOptionTermLength(cmd, helper) {
3558
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
3559
+ return Math.max(
3560
+ max,
3561
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
3562
+ );
3563
+ }, 0);
3564
+ }
3565
+
3566
+ /**
3567
+ * Get the longest argument term length.
3568
+ *
3569
+ * @param {Command} cmd
3570
+ * @param {Help} helper
3571
+ * @returns {number}
3572
+ */
3573
+
3574
+ longestArgumentTermLength(cmd, helper) {
3575
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
3576
+ return Math.max(
3577
+ max,
3578
+ this.displayWidth(
3579
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
3580
+ ),
3581
+ );
3582
+ }, 0);
3583
+ }
3584
+
3585
+ /**
3586
+ * Get the command usage to be displayed at the top of the built-in help.
3587
+ *
3588
+ * @param {Command} cmd
3589
+ * @returns {string}
3590
+ */
3591
+
3592
+ commandUsage(cmd) {
3593
+ // Usage
3594
+ let cmdName = cmd._name;
3595
+ if (cmd._aliases[0]) {
3596
+ cmdName = cmdName + '|' + cmd._aliases[0];
3597
+ }
3598
+ let ancestorCmdNames = '';
3599
+ for (
3600
+ let ancestorCmd = cmd.parent;
3601
+ ancestorCmd;
3602
+ ancestorCmd = ancestorCmd.parent
3603
+ ) {
3604
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
3605
+ }
3606
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
3607
+ }
3608
+
3609
+ /**
3610
+ * Get the description for the command.
3611
+ *
3612
+ * @param {Command} cmd
3613
+ * @returns {string}
3614
+ */
3615
+
3616
+ commandDescription(cmd) {
3617
+ // @ts-ignore: because overloaded return type
3618
+ return cmd.description();
3619
+ }
3620
+
3621
+ /**
3622
+ * Get the subcommand summary to show in the list of subcommands.
3623
+ * (Fallback to description for backwards compatibility.)
3624
+ *
3625
+ * @param {Command} cmd
3626
+ * @returns {string}
3627
+ */
3628
+
3629
+ subcommandDescription(cmd) {
3630
+ // @ts-ignore: because overloaded return type
3631
+ return cmd.summary() || cmd.description();
3632
+ }
3633
+
3634
+ /**
3635
+ * Get the option description to show in the list of options.
3636
+ *
3637
+ * @param {Option} option
3638
+ * @return {string}
3639
+ */
3640
+
3641
+ optionDescription(option) {
3642
+ const extraInfo = [];
3643
+
3644
+ if (option.argChoices) {
3645
+ extraInfo.push(
3646
+ // use stringify to match the display of the default value
3647
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
3648
+ );
3649
+ }
3650
+ if (option.defaultValue !== undefined) {
3651
+ // default for boolean and negated more for programmer than end user,
3652
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
3653
+ const showDefault =
3654
+ option.required ||
3655
+ option.optional ||
3656
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
3657
+ if (showDefault) {
3658
+ extraInfo.push(
3659
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
3660
+ );
3661
+ }
3662
+ }
3663
+ // preset for boolean and negated are more for programmer than end user
3664
+ if (option.presetArg !== undefined && option.optional) {
3665
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
3666
+ }
3667
+ if (option.envVar !== undefined) {
3668
+ extraInfo.push(`env: ${option.envVar}`);
3669
+ }
3670
+ if (extraInfo.length > 0) {
3671
+ const extraDescription = `(${extraInfo.join(', ')})`;
3672
+ if (option.description) {
3673
+ return `${option.description} ${extraDescription}`;
3674
+ }
3675
+ return extraDescription;
3676
+ }
3677
+
3678
+ return option.description;
3679
+ }
3680
+
3681
+ /**
3682
+ * Get the argument description to show in the list of arguments.
3683
+ *
3684
+ * @param {Argument} argument
3685
+ * @return {string}
3686
+ */
3687
+
3688
+ argumentDescription(argument) {
3689
+ const extraInfo = [];
3690
+ if (argument.argChoices) {
3691
+ extraInfo.push(
3692
+ // use stringify to match the display of the default value
3693
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
3694
+ );
3695
+ }
3696
+ if (argument.defaultValue !== undefined) {
3697
+ extraInfo.push(
3698
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
3699
+ );
3700
+ }
3701
+ if (extraInfo.length > 0) {
3702
+ const extraDescription = `(${extraInfo.join(', ')})`;
3703
+ if (argument.description) {
3704
+ return `${argument.description} ${extraDescription}`;
3705
+ }
3706
+ return extraDescription;
3707
+ }
3708
+ return argument.description;
3709
+ }
3710
+
3711
+ /**
3712
+ * Format a list of items, given a heading and an array of formatted items.
3713
+ *
3714
+ * @param {string} heading
3715
+ * @param {string[]} items
3716
+ * @param {Help} helper
3717
+ * @returns string[]
3718
+ */
3719
+ formatItemList(heading, items, helper) {
3720
+ if (items.length === 0) return [];
3721
+
3722
+ return [helper.styleTitle(heading), ...items, ''];
3723
+ }
3724
+
3725
+ /**
3726
+ * Group items by their help group heading.
3727
+ *
3728
+ * @param {Command[] | Option[]} unsortedItems
3729
+ * @param {Command[] | Option[]} visibleItems
3730
+ * @param {Function} getGroup
3731
+ * @returns {Map<string, Command[] | Option[]>}
3732
+ */
3733
+ groupItems(unsortedItems, visibleItems, getGroup) {
3734
+ const result = new Map();
3735
+ // Add groups in order of appearance in unsortedItems.
3736
+ unsortedItems.forEach((item) => {
3737
+ const group = getGroup(item);
3738
+ if (!result.has(group)) result.set(group, []);
3739
+ });
3740
+ // Add items in order of appearance in visibleItems.
3741
+ visibleItems.forEach((item) => {
3742
+ const group = getGroup(item);
3743
+ if (!result.has(group)) {
3744
+ result.set(group, []);
3745
+ }
3746
+ result.get(group).push(item);
3747
+ });
3748
+ return result;
3749
+ }
3750
+
3751
+ /**
3752
+ * Generate the built-in help text.
3753
+ *
3754
+ * @param {Command} cmd
3755
+ * @param {Help} helper
3756
+ * @returns {string}
3757
+ */
3758
+
3759
+ formatHelp(cmd, helper) {
3760
+ const termWidth = helper.padWidth(cmd, helper);
3761
+ const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
3762
+
3763
+ function callFormatItem(term, description) {
3764
+ return helper.formatItem(term, termWidth, description, helper);
3765
+ }
3766
+
3767
+ // Usage
3768
+ let output = [
3769
+ `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
3770
+ '',
3771
+ ];
3772
+
3773
+ // Description
3774
+ const commandDescription = helper.commandDescription(cmd);
3775
+ if (commandDescription.length > 0) {
3776
+ output = output.concat([
3777
+ helper.boxWrap(
3778
+ helper.styleCommandDescription(commandDescription),
3779
+ helpWidth,
3780
+ ),
3781
+ '',
3782
+ ]);
3783
+ }
3784
+
3785
+ // Arguments
3786
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
3787
+ return callFormatItem(
3788
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
3789
+ helper.styleArgumentDescription(helper.argumentDescription(argument)),
3790
+ );
3791
+ });
3792
+ output = output.concat(
3793
+ this.formatItemList('Arguments:', argumentList, helper),
3794
+ );
3795
+
3796
+ // Options
3797
+ const optionGroups = this.groupItems(
3798
+ cmd.options,
3799
+ helper.visibleOptions(cmd),
3800
+ (option) => option.helpGroupHeading ?? 'Options:',
3801
+ );
3802
+ optionGroups.forEach((options, group) => {
3803
+ const optionList = options.map((option) => {
3804
+ return callFormatItem(
3805
+ helper.styleOptionTerm(helper.optionTerm(option)),
3806
+ helper.styleOptionDescription(helper.optionDescription(option)),
3807
+ );
3808
+ });
3809
+ output = output.concat(this.formatItemList(group, optionList, helper));
3810
+ });
3811
+
3812
+ if (helper.showGlobalOptions) {
3813
+ const globalOptionList = helper
3814
+ .visibleGlobalOptions(cmd)
3815
+ .map((option) => {
3816
+ return callFormatItem(
3817
+ helper.styleOptionTerm(helper.optionTerm(option)),
3818
+ helper.styleOptionDescription(helper.optionDescription(option)),
3819
+ );
3820
+ });
3821
+ output = output.concat(
3822
+ this.formatItemList('Global Options:', globalOptionList, helper),
3823
+ );
3824
+ }
3825
+
3826
+ // Commands
3827
+ const commandGroups = this.groupItems(
3828
+ cmd.commands,
3829
+ helper.visibleCommands(cmd),
3830
+ (sub) => sub.helpGroup() || 'Commands:',
3831
+ );
3832
+ commandGroups.forEach((commands, group) => {
3833
+ const commandList = commands.map((sub) => {
3834
+ return callFormatItem(
3835
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
3836
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub)),
3837
+ );
3838
+ });
3839
+ output = output.concat(this.formatItemList(group, commandList, helper));
3840
+ });
3841
+
3842
+ return output.join('\n');
3843
+ }
3844
+
3845
+ /**
3846
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
3847
+ *
3848
+ * @param {string} str
3849
+ * @returns {number}
3850
+ */
3851
+ displayWidth(str) {
3852
+ return stripColor(str).length;
3853
+ }
3854
+
3855
+ /**
3856
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
3857
+ *
3858
+ * @param {string} str
3859
+ * @returns {string}
3860
+ */
3861
+ styleTitle(str) {
3862
+ return str;
3863
+ }
3864
+
3865
+ styleUsage(str) {
3866
+ // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
3867
+ // command subcommand [options] [command] <foo> [bar]
3868
+ return str
3869
+ .split(' ')
3870
+ .map((word) => {
3871
+ if (word === '[options]') return this.styleOptionText(word);
3872
+ if (word === '[command]') return this.styleSubcommandText(word);
3873
+ if (word[0] === '[' || word[0] === '<')
3874
+ return this.styleArgumentText(word);
3875
+ return this.styleCommandText(word); // Restrict to initial words?
3876
+ })
3877
+ .join(' ');
3878
+ }
3879
+ styleCommandDescription(str) {
3880
+ return this.styleDescriptionText(str);
3881
+ }
3882
+ styleOptionDescription(str) {
3883
+ return this.styleDescriptionText(str);
3884
+ }
3885
+ styleSubcommandDescription(str) {
3886
+ return this.styleDescriptionText(str);
3887
+ }
3888
+ styleArgumentDescription(str) {
3889
+ return this.styleDescriptionText(str);
3890
+ }
3891
+ styleDescriptionText(str) {
3892
+ return str;
3893
+ }
3894
+ styleOptionTerm(str) {
3895
+ return this.styleOptionText(str);
3896
+ }
3897
+ styleSubcommandTerm(str) {
3898
+ // This is very like usage with lots of parts! Assume default string which is formed like:
3899
+ // subcommand [options] <foo> [bar]
3900
+ return str
3901
+ .split(' ')
3902
+ .map((word) => {
3903
+ if (word === '[options]') return this.styleOptionText(word);
3904
+ if (word[0] === '[' || word[0] === '<')
3905
+ return this.styleArgumentText(word);
3906
+ return this.styleSubcommandText(word); // Restrict to initial words?
3907
+ })
3908
+ .join(' ');
3909
+ }
3910
+ styleArgumentTerm(str) {
3911
+ return this.styleArgumentText(str);
3912
+ }
3913
+ styleOptionText(str) {
3914
+ return str;
3915
+ }
3916
+ styleArgumentText(str) {
3917
+ return str;
3918
+ }
3919
+ styleSubcommandText(str) {
3920
+ return str;
3921
+ }
3922
+ styleCommandText(str) {
3923
+ return str;
3924
+ }
3925
+
3926
+ /**
3927
+ * Calculate the pad width from the maximum term length.
3928
+ *
3929
+ * @param {Command} cmd
3930
+ * @param {Help} helper
3931
+ * @returns {number}
3932
+ */
3933
+
3934
+ padWidth(cmd, helper) {
3935
+ return Math.max(
3936
+ helper.longestOptionTermLength(cmd, helper),
3937
+ helper.longestGlobalOptionTermLength(cmd, helper),
3938
+ helper.longestSubcommandTermLength(cmd, helper),
3939
+ helper.longestArgumentTermLength(cmd, helper),
3940
+ );
3941
+ }
3942
+
3943
+ /**
3944
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
3945
+ *
3946
+ * @param {string} str
3947
+ * @returns {boolean}
3948
+ */
3949
+ preformatted(str) {
3950
+ return /\n[^\S\r\n]/.test(str);
3951
+ }
3952
+
3953
+ /**
3954
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
3955
+ *
3956
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
3957
+ * TTT DDD DDDD
3958
+ * DD DDD
3959
+ *
3960
+ * @param {string} term
3961
+ * @param {number} termWidth
3962
+ * @param {string} description
3963
+ * @param {Help} helper
3964
+ * @returns {string}
3965
+ */
3966
+ formatItem(term, termWidth, description, helper) {
3967
+ const itemIndent = 2;
3968
+ const itemIndentStr = ' '.repeat(itemIndent);
3969
+ if (!description) return itemIndentStr + term;
3970
+
3971
+ // Pad the term out to a consistent width, so descriptions are aligned.
3972
+ const paddedTerm = term.padEnd(
3973
+ termWidth + term.length - helper.displayWidth(term),
3974
+ );
3975
+
3976
+ // Format the description.
3977
+ const spacerWidth = 2; // between term and description
3978
+ const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
3979
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
3980
+ let formattedDescription;
3981
+ if (
3982
+ remainingWidth < this.minWidthToWrap ||
3983
+ helper.preformatted(description)
3984
+ ) {
3985
+ formattedDescription = description;
3986
+ } else {
3987
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
3988
+ formattedDescription = wrappedDescription.replace(
3989
+ /\n/g,
3990
+ '\n' + ' '.repeat(termWidth + spacerWidth),
3991
+ );
3992
+ }
3993
+
3994
+ // Construct and overall indent.
3995
+ return (
3996
+ itemIndentStr +
3997
+ paddedTerm +
3998
+ ' '.repeat(spacerWidth) +
3999
+ formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
4000
+ );
4001
+ }
4002
+
4003
+ /**
4004
+ * Wrap a string at whitespace, preserving existing line breaks.
4005
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
4006
+ *
4007
+ * @param {string} str
4008
+ * @param {number} width
4009
+ * @returns {string}
4010
+ */
4011
+ boxWrap(str, width) {
4012
+ if (width < this.minWidthToWrap) return str;
4013
+
4014
+ const rawLines = str.split(/\r\n|\n/);
4015
+ // split up text by whitespace
4016
+ const chunkPattern = /[\s]*[^\s]+/g;
4017
+ const wrappedLines = [];
4018
+ rawLines.forEach((line) => {
4019
+ const chunks = line.match(chunkPattern);
4020
+ if (chunks === null) {
4021
+ wrappedLines.push('');
4022
+ return;
4023
+ }
4024
+
4025
+ let sumChunks = [chunks.shift()];
4026
+ let sumWidth = this.displayWidth(sumChunks[0]);
4027
+ chunks.forEach((chunk) => {
4028
+ const visibleWidth = this.displayWidth(chunk);
4029
+ // Accumulate chunks while they fit into width.
4030
+ if (sumWidth + visibleWidth <= width) {
4031
+ sumChunks.push(chunk);
4032
+ sumWidth += visibleWidth;
4033
+ return;
4034
+ }
4035
+ wrappedLines.push(sumChunks.join(''));
4036
+
4037
+ const nextChunk = chunk.trimStart(); // trim space at line break
4038
+ sumChunks = [nextChunk];
4039
+ sumWidth = this.displayWidth(nextChunk);
4040
+ });
4041
+ wrappedLines.push(sumChunks.join(''));
4042
+ });
4043
+
4044
+ return wrappedLines.join('\n');
4045
+ }
4046
+ }
4047
+
4048
+ /**
4049
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
4050
+ *
4051
+ * @param {string} str
4052
+ * @returns {string}
4053
+ * @package
4054
+ */
4055
+
4056
+ function stripColor(str) {
4057
+ // eslint-disable-next-line no-control-regex
4058
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
4059
+ return str.replace(sgrPattern, '');
4060
+ }
4061
+
4062
+ exports.Help = Help;
4063
+ exports.stripColor = stripColor;
4064
+
4065
+
4066
+ /***/ }),
4067
+
4068
+ /***/ 240:
4069
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
4070
+
4071
+ const { InvalidArgumentError } = __nccwpck_require__(135);
4072
+
4073
+ class Option {
4074
+ /**
4075
+ * Initialize a new `Option` with the given `flags` and `description`.
4076
+ *
4077
+ * @param {string} flags
4078
+ * @param {string} [description]
4079
+ */
4080
+
4081
+ constructor(flags, description) {
4082
+ this.flags = flags;
4083
+ this.description = description || '';
4084
+
4085
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
4086
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
4087
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
4088
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
4089
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
4090
+ const optionFlags = splitOptionFlags(flags);
4091
+ this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
4092
+ this.long = optionFlags.longFlag;
4093
+ this.negate = false;
4094
+ if (this.long) {
4095
+ this.negate = this.long.startsWith('--no-');
4096
+ }
4097
+ this.defaultValue = undefined;
4098
+ this.defaultValueDescription = undefined;
4099
+ this.presetArg = undefined;
4100
+ this.envVar = undefined;
4101
+ this.parseArg = undefined;
4102
+ this.hidden = false;
4103
+ this.argChoices = undefined;
4104
+ this.conflictsWith = [];
4105
+ this.implied = undefined;
4106
+ this.helpGroupHeading = undefined; // soft initialised when option added to command
4107
+ }
4108
+
4109
+ /**
4110
+ * Set the default value, and optionally supply the description to be displayed in the help.
4111
+ *
4112
+ * @param {*} value
4113
+ * @param {string} [description]
4114
+ * @return {Option}
4115
+ */
4116
+
4117
+ default(value, description) {
4118
+ this.defaultValue = value;
4119
+ this.defaultValueDescription = description;
4120
+ return this;
4121
+ }
4122
+
4123
+ /**
4124
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
4125
+ * The custom processing (parseArg) is called.
4126
+ *
4127
+ * @example
4128
+ * new Option('--color').default('GREYSCALE').preset('RGB');
4129
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
4130
+ *
4131
+ * @param {*} arg
4132
+ * @return {Option}
4133
+ */
4134
+
4135
+ preset(arg) {
4136
+ this.presetArg = arg;
4137
+ return this;
4138
+ }
4139
+
4140
+ /**
4141
+ * Add option name(s) that conflict with this option.
4142
+ * An error will be displayed if conflicting options are found during parsing.
4143
+ *
4144
+ * @example
4145
+ * new Option('--rgb').conflicts('cmyk');
4146
+ * new Option('--js').conflicts(['ts', 'jsx']);
4147
+ *
4148
+ * @param {(string | string[])} names
4149
+ * @return {Option}
4150
+ */
4151
+
4152
+ conflicts(names) {
4153
+ this.conflictsWith = this.conflictsWith.concat(names);
4154
+ return this;
4155
+ }
4156
+
4157
+ /**
4158
+ * Specify implied option values for when this option is set and the implied options are not.
4159
+ *
4160
+ * The custom processing (parseArg) is not called on the implied values.
4161
+ *
4162
+ * @example
4163
+ * program
4164
+ * .addOption(new Option('--log', 'write logging information to file'))
4165
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
4166
+ *
4167
+ * @param {object} impliedOptionValues
4168
+ * @return {Option}
4169
+ */
4170
+ implies(impliedOptionValues) {
4171
+ let newImplied = impliedOptionValues;
4172
+ if (typeof impliedOptionValues === 'string') {
4173
+ // string is not documented, but easy mistake and we can do what user probably intended.
4174
+ newImplied = { [impliedOptionValues]: true };
4175
+ }
4176
+ this.implied = Object.assign(this.implied || {}, newImplied);
4177
+ return this;
4178
+ }
4179
+
4180
+ /**
4181
+ * Set environment variable to check for option value.
4182
+ *
4183
+ * An environment variable is only used if when processed the current option value is
4184
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
4185
+ *
4186
+ * @param {string} name
4187
+ * @return {Option}
4188
+ */
4189
+
4190
+ env(name) {
4191
+ this.envVar = name;
4192
+ return this;
4193
+ }
4194
+
4195
+ /**
4196
+ * Set the custom handler for processing CLI option arguments into option values.
4197
+ *
4198
+ * @param {Function} [fn]
4199
+ * @return {Option}
4200
+ */
4201
+
4202
+ argParser(fn) {
4203
+ this.parseArg = fn;
4204
+ return this;
4205
+ }
4206
+
4207
+ /**
4208
+ * Whether the option is mandatory and must have a value after parsing.
4209
+ *
4210
+ * @param {boolean} [mandatory=true]
4211
+ * @return {Option}
4212
+ */
4213
+
4214
+ makeOptionMandatory(mandatory = true) {
4215
+ this.mandatory = !!mandatory;
4216
+ return this;
4217
+ }
4218
+
4219
+ /**
4220
+ * Hide option in help.
4221
+ *
4222
+ * @param {boolean} [hide=true]
4223
+ * @return {Option}
4224
+ */
4225
+
4226
+ hideHelp(hide = true) {
4227
+ this.hidden = !!hide;
4228
+ return this;
4229
+ }
4230
+
4231
+ /**
4232
+ * @package
4233
+ */
4234
+
4235
+ _collectValue(value, previous) {
4236
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
4237
+ return [value];
4238
+ }
4239
+
4240
+ previous.push(value);
4241
+ return previous;
4242
+ }
4243
+
4244
+ /**
4245
+ * Only allow option value to be one of choices.
4246
+ *
4247
+ * @param {string[]} values
4248
+ * @return {Option}
4249
+ */
4250
+
4251
+ choices(values) {
4252
+ this.argChoices = values.slice();
4253
+ this.parseArg = (arg, previous) => {
4254
+ if (!this.argChoices.includes(arg)) {
4255
+ throw new InvalidArgumentError(
4256
+ `Allowed choices are ${this.argChoices.join(', ')}.`,
4257
+ );
4258
+ }
4259
+ if (this.variadic) {
4260
+ return this._collectValue(arg, previous);
4261
+ }
4262
+ return arg;
4263
+ };
4264
+ return this;
4265
+ }
4266
+
4267
+ /**
4268
+ * Return option name.
4269
+ *
4270
+ * @return {string}
4271
+ */
4272
+
4273
+ name() {
4274
+ if (this.long) {
4275
+ return this.long.replace(/^--/, '');
4276
+ }
4277
+ return this.short.replace(/^-/, '');
4278
+ }
4279
+
4280
+ /**
4281
+ * Return option name, in a camelcase format that can be used
4282
+ * as an object attribute key.
4283
+ *
4284
+ * @return {string}
4285
+ */
4286
+
4287
+ attributeName() {
4288
+ if (this.negate) {
4289
+ return camelcase(this.name().replace(/^no-/, ''));
4290
+ }
4291
+ return camelcase(this.name());
4292
+ }
4293
+
4294
+ /**
4295
+ * Set the help group heading.
4296
+ *
4297
+ * @param {string} heading
4298
+ * @return {Option}
4299
+ */
4300
+ helpGroup(heading) {
4301
+ this.helpGroupHeading = heading;
4302
+ return this;
4303
+ }
4304
+
4305
+ /**
4306
+ * Check if `arg` matches the short or long flag.
4307
+ *
4308
+ * @param {string} arg
4309
+ * @return {boolean}
4310
+ * @package
4311
+ */
4312
+
4313
+ is(arg) {
4314
+ return this.short === arg || this.long === arg;
4315
+ }
4316
+
4317
+ /**
4318
+ * Return whether a boolean option.
4319
+ *
4320
+ * Options are one of boolean, negated, required argument, or optional argument.
4321
+ *
4322
+ * @return {boolean}
4323
+ * @package
4324
+ */
4325
+
4326
+ isBoolean() {
4327
+ return !this.required && !this.optional && !this.negate;
4328
+ }
4329
+ }
4330
+
4331
+ /**
4332
+ * This class is to make it easier to work with dual options, without changing the existing
4333
+ * implementation. We support separate dual options for separate positive and negative options,
4334
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
4335
+ * use cases, but is tricky for others where we want separate behaviours despite
4336
+ * the single shared option value.
4337
+ */
4338
+ class DualOptions {
4339
+ /**
4340
+ * @param {Option[]} options
4341
+ */
4342
+ constructor(options) {
4343
+ this.positiveOptions = new Map();
4344
+ this.negativeOptions = new Map();
4345
+ this.dualOptions = new Set();
4346
+ options.forEach((option) => {
4347
+ if (option.negate) {
4348
+ this.negativeOptions.set(option.attributeName(), option);
4349
+ } else {
4350
+ this.positiveOptions.set(option.attributeName(), option);
4351
+ }
4352
+ });
4353
+ this.negativeOptions.forEach((value, key) => {
4354
+ if (this.positiveOptions.has(key)) {
4355
+ this.dualOptions.add(key);
4356
+ }
4357
+ });
4358
+ }
4359
+
4360
+ /**
4361
+ * Did the value come from the option, and not from possible matching dual option?
4362
+ *
4363
+ * @param {*} value
4364
+ * @param {Option} option
4365
+ * @returns {boolean}
4366
+ */
4367
+ valueFromOption(value, option) {
4368
+ const optionKey = option.attributeName();
4369
+ if (!this.dualOptions.has(optionKey)) return true;
4370
+
4371
+ // Use the value to deduce if (probably) came from the option.
4372
+ const preset = this.negativeOptions.get(optionKey).presetArg;
4373
+ const negativeValue = preset !== undefined ? preset : false;
4374
+ return option.negate === (negativeValue === value);
4375
+ }
4376
+ }
4377
+
4378
+ /**
4379
+ * Convert string from kebab-case to camelCase.
4380
+ *
4381
+ * @param {string} str
4382
+ * @return {string}
4383
+ * @private
4384
+ */
4385
+
4386
+ function camelcase(str) {
4387
+ return str.split('-').reduce((str, word) => {
4388
+ return str + word[0].toUpperCase() + word.slice(1);
4389
+ });
4390
+ }
4391
+
4392
+ /**
4393
+ * Split the short and long flag out of something like '-m,--mixed <value>'
4394
+ *
4395
+ * @private
4396
+ */
4397
+
4398
+ function splitOptionFlags(flags) {
4399
+ let shortFlag;
4400
+ let longFlag;
4401
+ // short flag, single dash and single character
4402
+ const shortFlagExp = /^-[^-]$/;
4403
+ // long flag, double dash and at least one character
4404
+ const longFlagExp = /^--[^-]/;
4405
+
4406
+ const flagParts = flags.split(/[ |,]+/).concat('guard');
4407
+ // Normal is short and/or long.
4408
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
4409
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
4410
+ // Long then short. Rarely used but fine.
4411
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
4412
+ shortFlag = flagParts.shift();
4413
+ // Allow two long flags, like '--ws, --workspace'
4414
+ // This is the supported way to have a shortish option flag.
4415
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
4416
+ shortFlag = longFlag;
4417
+ longFlag = flagParts.shift();
4418
+ }
4419
+
4420
+ // Check for unprocessed flag. Fail noisily rather than silently ignore.
4421
+ if (flagParts[0].startsWith('-')) {
4422
+ const unsupportedFlag = flagParts[0];
4423
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
4424
+ if (/^-[^-][^-]/.test(unsupportedFlag))
4425
+ throw new Error(
4426
+ `${baseError}
4427
+ - a short flag is a single dash and a single character
4428
+ - either use a single dash and a single character (for a short flag)
4429
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
4430
+ );
4431
+ if (shortFlagExp.test(unsupportedFlag))
4432
+ throw new Error(`${baseError}
4433
+ - too many short flags`);
4434
+ if (longFlagExp.test(unsupportedFlag))
4435
+ throw new Error(`${baseError}
4436
+ - too many long flags`);
4437
+
4438
+ throw new Error(`${baseError}
4439
+ - unrecognised flag format`);
4440
+ }
4441
+ if (shortFlag === undefined && longFlag === undefined)
4442
+ throw new Error(
4443
+ `option creation failed due to no flags found in '${flags}'.`,
4444
+ );
4445
+
4446
+ return { shortFlag, longFlag };
4447
+ }
4448
+
4449
+ exports.Option = Option;
4450
+ exports.DualOptions = DualOptions;
4451
+
4452
+
4453
+ /***/ }),
4454
+
4455
+ /***/ 30:
4456
+ /***/ ((__unused_webpack_module, exports) => {
4457
+
4458
+ const maxDistance = 3;
4459
+
4460
+ function editDistance(a, b) {
4461
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
4462
+ // Calculating optimal string alignment distance, no substring is edited more than once.
4463
+ // (Simple implementation.)
4464
+
4465
+ // Quick early exit, return worst case.
4466
+ if (Math.abs(a.length - b.length) > maxDistance)
4467
+ return Math.max(a.length, b.length);
4468
+
4469
+ // distance between prefix substrings of a and b
4470
+ const d = [];
4471
+
4472
+ // pure deletions turn a into empty string
4473
+ for (let i = 0; i <= a.length; i++) {
4474
+ d[i] = [i];
4475
+ }
4476
+ // pure insertions turn empty string into b
4477
+ for (let j = 0; j <= b.length; j++) {
4478
+ d[0][j] = j;
4479
+ }
4480
+
4481
+ // fill matrix
4482
+ for (let j = 1; j <= b.length; j++) {
4483
+ for (let i = 1; i <= a.length; i++) {
4484
+ let cost = 1;
4485
+ if (a[i - 1] === b[j - 1]) {
4486
+ cost = 0;
4487
+ } else {
4488
+ cost = 1;
4489
+ }
4490
+ d[i][j] = Math.min(
4491
+ d[i - 1][j] + 1, // deletion
4492
+ d[i][j - 1] + 1, // insertion
4493
+ d[i - 1][j - 1] + cost, // substitution
4494
+ );
4495
+ // transposition
4496
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
4497
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
4498
+ }
4499
+ }
4500
+ }
4501
+
4502
+ return d[a.length][b.length];
4503
+ }
4504
+
4505
+ /**
4506
+ * Find close matches, restricted to same number of edits.
4507
+ *
4508
+ * @param {string} word
4509
+ * @param {string[]} candidates
4510
+ * @returns {string}
4511
+ */
4512
+
4513
+ function suggestSimilar(word, candidates) {
4514
+ if (!candidates || candidates.length === 0) return '';
4515
+ // remove possible duplicates
4516
+ candidates = Array.from(new Set(candidates));
4517
+
4518
+ const searchingOptions = word.startsWith('--');
4519
+ if (searchingOptions) {
4520
+ word = word.slice(2);
4521
+ candidates = candidates.map((candidate) => candidate.slice(2));
4522
+ }
4523
+
4524
+ let similar = [];
4525
+ let bestDistance = maxDistance;
4526
+ const minSimilarity = 0.4;
4527
+ candidates.forEach((candidate) => {
4528
+ if (candidate.length <= 1) return; // no one character guesses
4529
+
4530
+ const distance = editDistance(word, candidate);
4531
+ const length = Math.max(word.length, candidate.length);
4532
+ const similarity = (length - distance) / length;
4533
+ if (similarity > minSimilarity) {
4534
+ if (distance < bestDistance) {
4535
+ // better edit distance, throw away previous worse matches
4536
+ bestDistance = distance;
4537
+ similar = [candidate];
4538
+ } else if (distance === bestDistance) {
4539
+ similar.push(candidate);
4540
+ }
4541
+ }
4542
+ });
4543
+
4544
+ similar.sort((a, b) => a.localeCompare(b));
4545
+ if (searchingOptions) {
4546
+ similar = similar.map((candidate) => `--${candidate}`);
4547
+ }
4548
+
4549
+ if (similar.length > 1) {
4550
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
4551
+ }
4552
+ if (similar.length === 1) {
4553
+ return `\n(Did you mean ${similar[0]}?)`;
4554
+ }
4555
+ return '';
4556
+ }
4557
+
4558
+ exports.suggestSimilar = suggestSimilar;
4559
+
4560
+
4561
+ /***/ }),
4562
+
4563
+ /***/ 330:
4564
+ /***/ ((module) => {
4565
+
4566
+ "use strict";
4567
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@sandeepk1729/porter","version":"1.0.0","description":"a port forwarding agent","main":"./dist/index.js","bin":{"porter":"dist/index.js"},"scripts":{"dev":"tsc -w & ncc build src/index.ts --out dist --watch","unlink":"npm unlink @sandeepk1729/jarvis -g","build":"tsc && ncc build src/index.ts --out dist","prepublishOnly":"npm run build","lint":"eslint \'src/**/*.ts\'"},"keywords":["port","agent","node","cli"],"homepage":"https://github.com/SandeepK1729/porter-agent#readme","bugs":{"url":"https://github.com/SandeepK1729/porter-agent/issues"},"repository":{"type":"git","url":"git+https://github.com/SandeepK1729/porter-agent.git"},"author":"SandeepK1729 <SandeepK1729+user@users.noreply.github.com>","license":"MIT","devDependencies":{"@types/node":"^24.3.0","@vercel/ncc":"^0.38.3","eslint":"^9.35.0","prettier":"^3.6.2","typescript":"^5.9.2"},"publishConfig":{"access":"public","directory":"dist","registry":"https://registry.npmjs.org"},"files":["dist/","README.md","package.json"],"dependencies":{"commander":"^14.0.0"}}');
4568
+
4569
+ /***/ })
4570
+
4571
+ /******/ });
4572
+ /************************************************************************/
4573
+ /******/ // The module cache
4574
+ /******/ var __webpack_module_cache__ = {};
4575
+ /******/
4576
+ /******/ // The require function
4577
+ /******/ function __nccwpck_require__(moduleId) {
4578
+ /******/ // Check if module is in cache
4579
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
4580
+ /******/ if (cachedModule !== undefined) {
4581
+ /******/ return cachedModule.exports;
4582
+ /******/ }
4583
+ /******/ // Create a new module (and put it into the cache)
4584
+ /******/ var module = __webpack_module_cache__[moduleId] = {
4585
+ /******/ // no module.id needed
4586
+ /******/ // no module.loaded needed
4587
+ /******/ exports: {}
4588
+ /******/ };
4589
+ /******/
4590
+ /******/ // Execute the module function
4591
+ /******/ var threw = true;
4592
+ /******/ try {
4593
+ /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
4594
+ /******/ threw = false;
4595
+ /******/ } finally {
4596
+ /******/ if(threw) delete __webpack_module_cache__[moduleId];
4597
+ /******/ }
4598
+ /******/
4599
+ /******/ // Return the exports of the module
4600
+ /******/ return module.exports;
4601
+ /******/ }
4602
+ /******/
4603
+ /************************************************************************/
4604
+ /******/ /* webpack/runtime/compat */
4605
+ /******/
4606
+ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
4607
+ /******/
4608
+ /************************************************************************/
4609
+ /******/
4610
+ /******/ // startup
4611
+ /******/ // Load entry module and return exports
4612
+ /******/ // This entry module is referenced by other modules so it can't be inlined
4613
+ /******/ var __webpack_exports__ = __nccwpck_require__(407);
4614
+ /******/ module.exports = __webpack_exports__;
4615
+ /******/
4616
+ /******/ })()
4617
+ ;