@xaendar/cli 0.4.0 → 0.4.2

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.
package/index.js DELETED
@@ -1,3854 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
4
- var __create = Object.create;
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getProtoOf = Object.getPrototypeOf;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
- }) : x)(function(x) {
13
- if (typeof require !== "undefined") return require.apply(this, arguments);
14
- throw Error('Dynamic require of "' + x + '" is not supported');
15
- });
16
- var __commonJS = (cb, mod) => function __require2() {
17
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
- };
19
- var __copyProps = (to, from, except, desc) => {
20
- if (from && typeof from === "object" || typeof from === "function") {
21
- for (let key of __getOwnPropNames(from))
22
- if (!__hasOwnProp.call(to, key) && key !== except)
23
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
- }
25
- return to;
26
- };
27
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
- // If the importer is in node compatibility mode or this is not an ESM
29
- // file that has been converted to a CommonJS file using a Babel-
30
- // compatible transform (i.e. "__esModule" has not been set), then set
31
- // "default" to the CommonJS "module.exports" for node compatibility.
32
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
- mod
34
- ));
35
-
36
- // ../node_modules/commander/lib/error.js
37
- var require_error = __commonJS({
38
- "../node_modules/commander/lib/error.js"(exports) {
39
- var CommanderError2 = class extends Error {
40
- /**
41
- * Constructs the CommanderError class
42
- * @param {number} exitCode suggested exit code which could be used with process.exit
43
- * @param {string} code an id string representing the error
44
- * @param {string} message human-readable description of the error
45
- */
46
- constructor(exitCode, code, message) {
47
- super(message);
48
- Error.captureStackTrace(this, this.constructor);
49
- this.name = this.constructor.name;
50
- this.code = code;
51
- this.exitCode = exitCode;
52
- this.nestedError = void 0;
53
- }
54
- };
55
- var InvalidArgumentError2 = class extends CommanderError2 {
56
- /**
57
- * Constructs the InvalidArgumentError class
58
- * @param {string} [message] explanation of why argument is invalid
59
- */
60
- constructor(message) {
61
- super(1, "commander.invalidArgument", message);
62
- Error.captureStackTrace(this, this.constructor);
63
- this.name = this.constructor.name;
64
- }
65
- };
66
- exports.CommanderError = CommanderError2;
67
- exports.InvalidArgumentError = InvalidArgumentError2;
68
- }
69
- });
70
-
71
- // ../node_modules/commander/lib/argument.js
72
- var require_argument = __commonJS({
73
- "../node_modules/commander/lib/argument.js"(exports) {
74
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
75
- var Argument2 = class {
76
- /**
77
- * Initialize a new command argument with the given name and description.
78
- * The default is that the argument is required, and you can explicitly
79
- * indicate this with <> around the name. Put [] around the name for an optional argument.
80
- *
81
- * @param {string} name
82
- * @param {string} [description]
83
- */
84
- constructor(name, description) {
85
- this.description = description || "";
86
- this.variadic = false;
87
- this.parseArg = void 0;
88
- this.defaultValue = void 0;
89
- this.defaultValueDescription = void 0;
90
- this.argChoices = void 0;
91
- switch (name[0]) {
92
- case "<":
93
- this.required = true;
94
- this._name = name.slice(1, -1);
95
- break;
96
- case "[":
97
- this.required = false;
98
- this._name = name.slice(1, -1);
99
- break;
100
- default:
101
- this.required = true;
102
- this._name = name;
103
- break;
104
- }
105
- if (this._name.endsWith("...")) {
106
- this.variadic = true;
107
- this._name = this._name.slice(0, -3);
108
- }
109
- }
110
- /**
111
- * Return argument name.
112
- *
113
- * @return {string}
114
- */
115
- name() {
116
- return this._name;
117
- }
118
- /**
119
- * @package
120
- */
121
- _collectValue(value, previous) {
122
- if (previous === this.defaultValue || !Array.isArray(previous)) {
123
- return [value];
124
- }
125
- previous.push(value);
126
- return previous;
127
- }
128
- /**
129
- * Set the default value, and optionally supply the description to be displayed in the help.
130
- *
131
- * @param {*} value
132
- * @param {string} [description]
133
- * @return {Argument}
134
- */
135
- default(value, description) {
136
- this.defaultValue = value;
137
- this.defaultValueDescription = description;
138
- return this;
139
- }
140
- /**
141
- * Set the custom handler for processing CLI command arguments into argument values.
142
- *
143
- * @param {Function} [fn]
144
- * @return {Argument}
145
- */
146
- argParser(fn) {
147
- this.parseArg = fn;
148
- return this;
149
- }
150
- /**
151
- * Only allow argument value to be one of choices.
152
- *
153
- * @param {string[]} values
154
- * @return {Argument}
155
- */
156
- choices(values) {
157
- this.argChoices = values.slice();
158
- this.parseArg = (arg, previous) => {
159
- if (!this.argChoices.includes(arg)) {
160
- throw new InvalidArgumentError2(
161
- `Allowed choices are ${this.argChoices.join(", ")}.`
162
- );
163
- }
164
- if (this.variadic) {
165
- return this._collectValue(arg, previous);
166
- }
167
- return arg;
168
- };
169
- return this;
170
- }
171
- /**
172
- * Make argument required.
173
- *
174
- * @returns {Argument}
175
- */
176
- argRequired() {
177
- this.required = true;
178
- return this;
179
- }
180
- /**
181
- * Make argument optional.
182
- *
183
- * @returns {Argument}
184
- */
185
- argOptional() {
186
- this.required = false;
187
- return this;
188
- }
189
- };
190
- function humanReadableArgName(arg) {
191
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
192
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
193
- }
194
- exports.Argument = Argument2;
195
- exports.humanReadableArgName = humanReadableArgName;
196
- }
197
- });
198
-
199
- // ../node_modules/commander/lib/help.js
200
- var require_help = __commonJS({
201
- "../node_modules/commander/lib/help.js"(exports) {
202
- var { humanReadableArgName } = require_argument();
203
- var Help2 = class {
204
- constructor() {
205
- this.helpWidth = void 0;
206
- this.minWidthToWrap = 40;
207
- this.sortSubcommands = false;
208
- this.sortOptions = false;
209
- this.showGlobalOptions = false;
210
- }
211
- /**
212
- * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
213
- * and just before calling `formatHelp()`.
214
- *
215
- * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
216
- *
217
- * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
218
- */
219
- prepareContext(contextOptions) {
220
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
221
- }
222
- /**
223
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
224
- *
225
- * @param {Command} cmd
226
- * @returns {Command[]}
227
- */
228
- visibleCommands(cmd) {
229
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
230
- const helpCommand = cmd._getHelpCommand();
231
- if (helpCommand && !helpCommand._hidden) {
232
- visibleCommands.push(helpCommand);
233
- }
234
- if (this.sortSubcommands) {
235
- visibleCommands.sort((a, b) => {
236
- return a.name().localeCompare(b.name());
237
- });
238
- }
239
- return visibleCommands;
240
- }
241
- /**
242
- * Compare options for sort.
243
- *
244
- * @param {Option} a
245
- * @param {Option} b
246
- * @returns {number}
247
- */
248
- compareOptions(a, b) {
249
- const getSortKey = (option) => {
250
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
251
- };
252
- return getSortKey(a).localeCompare(getSortKey(b));
253
- }
254
- /**
255
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
256
- *
257
- * @param {Command} cmd
258
- * @returns {Option[]}
259
- */
260
- visibleOptions(cmd) {
261
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
262
- const helpOption = cmd._getHelpOption();
263
- if (helpOption && !helpOption.hidden) {
264
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
265
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
266
- if (!removeShort && !removeLong) {
267
- visibleOptions.push(helpOption);
268
- } else if (helpOption.long && !removeLong) {
269
- visibleOptions.push(
270
- cmd.createOption(helpOption.long, helpOption.description)
271
- );
272
- } else if (helpOption.short && !removeShort) {
273
- visibleOptions.push(
274
- cmd.createOption(helpOption.short, helpOption.description)
275
- );
276
- }
277
- }
278
- if (this.sortOptions) {
279
- visibleOptions.sort(this.compareOptions);
280
- }
281
- return visibleOptions;
282
- }
283
- /**
284
- * Get an array of the visible global options. (Not including help.)
285
- *
286
- * @param {Command} cmd
287
- * @returns {Option[]}
288
- */
289
- visibleGlobalOptions(cmd) {
290
- if (!this.showGlobalOptions) return [];
291
- const globalOptions = [];
292
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
293
- const visibleOptions = ancestorCmd.options.filter(
294
- (option) => !option.hidden
295
- );
296
- globalOptions.push(...visibleOptions);
297
- }
298
- if (this.sortOptions) {
299
- globalOptions.sort(this.compareOptions);
300
- }
301
- return globalOptions;
302
- }
303
- /**
304
- * Get an array of the arguments if any have a description.
305
- *
306
- * @param {Command} cmd
307
- * @returns {Argument[]}
308
- */
309
- visibleArguments(cmd) {
310
- if (cmd._argsDescription) {
311
- cmd.registeredArguments.forEach((argument) => {
312
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
313
- });
314
- }
315
- if (cmd.registeredArguments.find((argument) => argument.description)) {
316
- return cmd.registeredArguments;
317
- }
318
- return [];
319
- }
320
- /**
321
- * Get the command term to show in the list of subcommands.
322
- *
323
- * @param {Command} cmd
324
- * @returns {string}
325
- */
326
- subcommandTerm(cmd) {
327
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
328
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
329
- (args ? " " + args : "");
330
- }
331
- /**
332
- * Get the option term to show in the list of options.
333
- *
334
- * @param {Option} option
335
- * @returns {string}
336
- */
337
- optionTerm(option) {
338
- return option.flags;
339
- }
340
- /**
341
- * Get the argument term to show in the list of arguments.
342
- *
343
- * @param {Argument} argument
344
- * @returns {string}
345
- */
346
- argumentTerm(argument) {
347
- return argument.name();
348
- }
349
- /**
350
- * Get the longest command term length.
351
- *
352
- * @param {Command} cmd
353
- * @param {Help} helper
354
- * @returns {number}
355
- */
356
- longestSubcommandTermLength(cmd, helper) {
357
- return helper.visibleCommands(cmd).reduce((max, command) => {
358
- return Math.max(
359
- max,
360
- this.displayWidth(
361
- helper.styleSubcommandTerm(helper.subcommandTerm(command))
362
- )
363
- );
364
- }, 0);
365
- }
366
- /**
367
- * Get the longest option term length.
368
- *
369
- * @param {Command} cmd
370
- * @param {Help} helper
371
- * @returns {number}
372
- */
373
- longestOptionTermLength(cmd, helper) {
374
- return helper.visibleOptions(cmd).reduce((max, option) => {
375
- return Math.max(
376
- max,
377
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
378
- );
379
- }, 0);
380
- }
381
- /**
382
- * Get the longest global option term length.
383
- *
384
- * @param {Command} cmd
385
- * @param {Help} helper
386
- * @returns {number}
387
- */
388
- longestGlobalOptionTermLength(cmd, helper) {
389
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
390
- return Math.max(
391
- max,
392
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
393
- );
394
- }, 0);
395
- }
396
- /**
397
- * Get the longest argument term length.
398
- *
399
- * @param {Command} cmd
400
- * @param {Help} helper
401
- * @returns {number}
402
- */
403
- longestArgumentTermLength(cmd, helper) {
404
- return helper.visibleArguments(cmd).reduce((max, argument) => {
405
- return Math.max(
406
- max,
407
- this.displayWidth(
408
- helper.styleArgumentTerm(helper.argumentTerm(argument))
409
- )
410
- );
411
- }, 0);
412
- }
413
- /**
414
- * Get the command usage to be displayed at the top of the built-in help.
415
- *
416
- * @param {Command} cmd
417
- * @returns {string}
418
- */
419
- commandUsage(cmd) {
420
- let cmdName = cmd._name;
421
- if (cmd._aliases[0]) {
422
- cmdName = cmdName + "|" + cmd._aliases[0];
423
- }
424
- let ancestorCmdNames = "";
425
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
426
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
427
- }
428
- return ancestorCmdNames + cmdName + " " + cmd.usage();
429
- }
430
- /**
431
- * Get the description for the command.
432
- *
433
- * @param {Command} cmd
434
- * @returns {string}
435
- */
436
- commandDescription(cmd) {
437
- return cmd.description();
438
- }
439
- /**
440
- * Get the subcommand summary to show in the list of subcommands.
441
- * (Fallback to description for backwards compatibility.)
442
- *
443
- * @param {Command} cmd
444
- * @returns {string}
445
- */
446
- subcommandDescription(cmd) {
447
- return cmd.summary() || cmd.description();
448
- }
449
- /**
450
- * Get the option description to show in the list of options.
451
- *
452
- * @param {Option} option
453
- * @return {string}
454
- */
455
- optionDescription(option) {
456
- const extraInfo = [];
457
- if (option.argChoices) {
458
- extraInfo.push(
459
- // use stringify to match the display of the default value
460
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
461
- );
462
- }
463
- if (option.defaultValue !== void 0) {
464
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
465
- if (showDefault) {
466
- extraInfo.push(
467
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
468
- );
469
- }
470
- }
471
- if (option.presetArg !== void 0 && option.optional) {
472
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
473
- }
474
- if (option.envVar !== void 0) {
475
- extraInfo.push(`env: ${option.envVar}`);
476
- }
477
- if (extraInfo.length > 0) {
478
- const extraDescription = `(${extraInfo.join(", ")})`;
479
- if (option.description) {
480
- return `${option.description} ${extraDescription}`;
481
- }
482
- return extraDescription;
483
- }
484
- return option.description;
485
- }
486
- /**
487
- * Get the argument description to show in the list of arguments.
488
- *
489
- * @param {Argument} argument
490
- * @return {string}
491
- */
492
- argumentDescription(argument) {
493
- const extraInfo = [];
494
- if (argument.argChoices) {
495
- extraInfo.push(
496
- // use stringify to match the display of the default value
497
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
498
- );
499
- }
500
- if (argument.defaultValue !== void 0) {
501
- extraInfo.push(
502
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
503
- );
504
- }
505
- if (extraInfo.length > 0) {
506
- const extraDescription = `(${extraInfo.join(", ")})`;
507
- if (argument.description) {
508
- return `${argument.description} ${extraDescription}`;
509
- }
510
- return extraDescription;
511
- }
512
- return argument.description;
513
- }
514
- /**
515
- * Format a list of items, given a heading and an array of formatted items.
516
- *
517
- * @param {string} heading
518
- * @param {string[]} items
519
- * @param {Help} helper
520
- * @returns string[]
521
- */
522
- formatItemList(heading, items, helper) {
523
- if (items.length === 0) return [];
524
- return [helper.styleTitle(heading), ...items, ""];
525
- }
526
- /**
527
- * Group items by their help group heading.
528
- *
529
- * @param {Command[] | Option[]} unsortedItems
530
- * @param {Command[] | Option[]} visibleItems
531
- * @param {Function} getGroup
532
- * @returns {Map<string, Command[] | Option[]>}
533
- */
534
- groupItems(unsortedItems, visibleItems, getGroup) {
535
- const result = /* @__PURE__ */ new Map();
536
- unsortedItems.forEach((item) => {
537
- const group = getGroup(item);
538
- if (!result.has(group)) result.set(group, []);
539
- });
540
- visibleItems.forEach((item) => {
541
- const group = getGroup(item);
542
- if (!result.has(group)) {
543
- result.set(group, []);
544
- }
545
- result.get(group).push(item);
546
- });
547
- return result;
548
- }
549
- /**
550
- * Generate the built-in help text.
551
- *
552
- * @param {Command} cmd
553
- * @param {Help} helper
554
- * @returns {string}
555
- */
556
- formatHelp(cmd, helper) {
557
- const termWidth = helper.padWidth(cmd, helper);
558
- const helpWidth = helper.helpWidth ?? 80;
559
- function callFormatItem(term, description) {
560
- return helper.formatItem(term, termWidth, description, helper);
561
- }
562
- let output = [
563
- `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
564
- ""
565
- ];
566
- const commandDescription = helper.commandDescription(cmd);
567
- if (commandDescription.length > 0) {
568
- output = output.concat([
569
- helper.boxWrap(
570
- helper.styleCommandDescription(commandDescription),
571
- helpWidth
572
- ),
573
- ""
574
- ]);
575
- }
576
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
577
- return callFormatItem(
578
- helper.styleArgumentTerm(helper.argumentTerm(argument)),
579
- helper.styleArgumentDescription(helper.argumentDescription(argument))
580
- );
581
- });
582
- output = output.concat(
583
- this.formatItemList("Arguments:", argumentList, helper)
584
- );
585
- const optionGroups = this.groupItems(
586
- cmd.options,
587
- helper.visibleOptions(cmd),
588
- (option) => option.helpGroupHeading ?? "Options:"
589
- );
590
- optionGroups.forEach((options, group) => {
591
- const optionList = options.map((option) => {
592
- return callFormatItem(
593
- helper.styleOptionTerm(helper.optionTerm(option)),
594
- helper.styleOptionDescription(helper.optionDescription(option))
595
- );
596
- });
597
- output = output.concat(this.formatItemList(group, optionList, helper));
598
- });
599
- if (helper.showGlobalOptions) {
600
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
601
- return callFormatItem(
602
- helper.styleOptionTerm(helper.optionTerm(option)),
603
- helper.styleOptionDescription(helper.optionDescription(option))
604
- );
605
- });
606
- output = output.concat(
607
- this.formatItemList("Global Options:", globalOptionList, helper)
608
- );
609
- }
610
- const commandGroups = this.groupItems(
611
- cmd.commands,
612
- helper.visibleCommands(cmd),
613
- (sub) => sub.helpGroup() || "Commands:"
614
- );
615
- commandGroups.forEach((commands, group) => {
616
- const commandList = commands.map((sub) => {
617
- return callFormatItem(
618
- helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
619
- helper.styleSubcommandDescription(helper.subcommandDescription(sub))
620
- );
621
- });
622
- output = output.concat(this.formatItemList(group, commandList, helper));
623
- });
624
- return output.join("\n");
625
- }
626
- /**
627
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
628
- *
629
- * @param {string} str
630
- * @returns {number}
631
- */
632
- displayWidth(str) {
633
- return stripColor(str).length;
634
- }
635
- /**
636
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
637
- *
638
- * @param {string} str
639
- * @returns {string}
640
- */
641
- styleTitle(str) {
642
- return str;
643
- }
644
- styleUsage(str) {
645
- return str.split(" ").map((word) => {
646
- if (word === "[options]") return this.styleOptionText(word);
647
- if (word === "[command]") return this.styleSubcommandText(word);
648
- if (word[0] === "[" || word[0] === "<")
649
- return this.styleArgumentText(word);
650
- return this.styleCommandText(word);
651
- }).join(" ");
652
- }
653
- styleCommandDescription(str) {
654
- return this.styleDescriptionText(str);
655
- }
656
- styleOptionDescription(str) {
657
- return this.styleDescriptionText(str);
658
- }
659
- styleSubcommandDescription(str) {
660
- return this.styleDescriptionText(str);
661
- }
662
- styleArgumentDescription(str) {
663
- return this.styleDescriptionText(str);
664
- }
665
- styleDescriptionText(str) {
666
- return str;
667
- }
668
- styleOptionTerm(str) {
669
- return this.styleOptionText(str);
670
- }
671
- styleSubcommandTerm(str) {
672
- return str.split(" ").map((word) => {
673
- if (word === "[options]") return this.styleOptionText(word);
674
- if (word[0] === "[" || word[0] === "<")
675
- return this.styleArgumentText(word);
676
- return this.styleSubcommandText(word);
677
- }).join(" ");
678
- }
679
- styleArgumentTerm(str) {
680
- return this.styleArgumentText(str);
681
- }
682
- styleOptionText(str) {
683
- return str;
684
- }
685
- styleArgumentText(str) {
686
- return str;
687
- }
688
- styleSubcommandText(str) {
689
- return str;
690
- }
691
- styleCommandText(str) {
692
- return str;
693
- }
694
- /**
695
- * Calculate the pad width from the maximum term length.
696
- *
697
- * @param {Command} cmd
698
- * @param {Help} helper
699
- * @returns {number}
700
- */
701
- padWidth(cmd, helper) {
702
- return Math.max(
703
- helper.longestOptionTermLength(cmd, helper),
704
- helper.longestGlobalOptionTermLength(cmd, helper),
705
- helper.longestSubcommandTermLength(cmd, helper),
706
- helper.longestArgumentTermLength(cmd, helper)
707
- );
708
- }
709
- /**
710
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
711
- *
712
- * @param {string} str
713
- * @returns {boolean}
714
- */
715
- preformatted(str) {
716
- return /\n[^\S\r\n]/.test(str);
717
- }
718
- /**
719
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
720
- *
721
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
722
- * TTT DDD DDDD
723
- * DD DDD
724
- *
725
- * @param {string} term
726
- * @param {number} termWidth
727
- * @param {string} description
728
- * @param {Help} helper
729
- * @returns {string}
730
- */
731
- formatItem(term, termWidth, description, helper) {
732
- const itemIndent = 2;
733
- const itemIndentStr = " ".repeat(itemIndent);
734
- if (!description) return itemIndentStr + term;
735
- const paddedTerm = term.padEnd(
736
- termWidth + term.length - helper.displayWidth(term)
737
- );
738
- const spacerWidth = 2;
739
- const helpWidth = this.helpWidth ?? 80;
740
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
741
- let formattedDescription;
742
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
743
- formattedDescription = description;
744
- } else {
745
- const wrappedDescription = helper.boxWrap(description, remainingWidth);
746
- formattedDescription = wrappedDescription.replace(
747
- /\n/g,
748
- "\n" + " ".repeat(termWidth + spacerWidth)
749
- );
750
- }
751
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
752
- ${itemIndentStr}`);
753
- }
754
- /**
755
- * Wrap a string at whitespace, preserving existing line breaks.
756
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
757
- *
758
- * @param {string} str
759
- * @param {number} width
760
- * @returns {string}
761
- */
762
- boxWrap(str, width) {
763
- if (width < this.minWidthToWrap) return str;
764
- const rawLines = str.split(/\r\n|\n/);
765
- const chunkPattern = /[\s]*[^\s]+/g;
766
- const wrappedLines = [];
767
- rawLines.forEach((line) => {
768
- const chunks = line.match(chunkPattern);
769
- if (chunks === null) {
770
- wrappedLines.push("");
771
- return;
772
- }
773
- let sumChunks = [chunks.shift()];
774
- let sumWidth = this.displayWidth(sumChunks[0]);
775
- chunks.forEach((chunk) => {
776
- const visibleWidth = this.displayWidth(chunk);
777
- if (sumWidth + visibleWidth <= width) {
778
- sumChunks.push(chunk);
779
- sumWidth += visibleWidth;
780
- return;
781
- }
782
- wrappedLines.push(sumChunks.join(""));
783
- const nextChunk = chunk.trimStart();
784
- sumChunks = [nextChunk];
785
- sumWidth = this.displayWidth(nextChunk);
786
- });
787
- wrappedLines.push(sumChunks.join(""));
788
- });
789
- return wrappedLines.join("\n");
790
- }
791
- };
792
- function stripColor(str) {
793
- const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
794
- return str.replace(sgrPattern, "");
795
- }
796
- exports.Help = Help2;
797
- exports.stripColor = stripColor;
798
- }
799
- });
800
-
801
- // ../node_modules/commander/lib/option.js
802
- var require_option = __commonJS({
803
- "../node_modules/commander/lib/option.js"(exports) {
804
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
805
- var Option2 = class {
806
- /**
807
- * Initialize a new `Option` with the given `flags` and `description`.
808
- *
809
- * @param {string} flags
810
- * @param {string} [description]
811
- */
812
- constructor(flags, description) {
813
- this.flags = flags;
814
- this.description = description || "";
815
- this.required = flags.includes("<");
816
- this.optional = flags.includes("[");
817
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
818
- this.mandatory = false;
819
- const optionFlags = splitOptionFlags(flags);
820
- this.short = optionFlags.shortFlag;
821
- this.long = optionFlags.longFlag;
822
- this.negate = false;
823
- if (this.long) {
824
- this.negate = this.long.startsWith("--no-");
825
- }
826
- this.defaultValue = void 0;
827
- this.defaultValueDescription = void 0;
828
- this.presetArg = void 0;
829
- this.envVar = void 0;
830
- this.parseArg = void 0;
831
- this.hidden = false;
832
- this.argChoices = void 0;
833
- this.conflictsWith = [];
834
- this.implied = void 0;
835
- this.helpGroupHeading = void 0;
836
- }
837
- /**
838
- * Set the default value, and optionally supply the description to be displayed in the help.
839
- *
840
- * @param {*} value
841
- * @param {string} [description]
842
- * @return {Option}
843
- */
844
- default(value, description) {
845
- this.defaultValue = value;
846
- this.defaultValueDescription = description;
847
- return this;
848
- }
849
- /**
850
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
851
- * The custom processing (parseArg) is called.
852
- *
853
- * @example
854
- * new Option('--color').default('GREYSCALE').preset('RGB');
855
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
856
- *
857
- * @param {*} arg
858
- * @return {Option}
859
- */
860
- preset(arg) {
861
- this.presetArg = arg;
862
- return this;
863
- }
864
- /**
865
- * Add option name(s) that conflict with this option.
866
- * An error will be displayed if conflicting options are found during parsing.
867
- *
868
- * @example
869
- * new Option('--rgb').conflicts('cmyk');
870
- * new Option('--js').conflicts(['ts', 'jsx']);
871
- *
872
- * @param {(string | string[])} names
873
- * @return {Option}
874
- */
875
- conflicts(names) {
876
- this.conflictsWith = this.conflictsWith.concat(names);
877
- return this;
878
- }
879
- /**
880
- * Specify implied option values for when this option is set and the implied options are not.
881
- *
882
- * The custom processing (parseArg) is not called on the implied values.
883
- *
884
- * @example
885
- * program
886
- * .addOption(new Option('--log', 'write logging information to file'))
887
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
888
- *
889
- * @param {object} impliedOptionValues
890
- * @return {Option}
891
- */
892
- implies(impliedOptionValues) {
893
- let newImplied = impliedOptionValues;
894
- if (typeof impliedOptionValues === "string") {
895
- newImplied = { [impliedOptionValues]: true };
896
- }
897
- this.implied = Object.assign(this.implied || {}, newImplied);
898
- return this;
899
- }
900
- /**
901
- * Set environment variable to check for option value.
902
- *
903
- * An environment variable is only used if when processed the current option value is
904
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
905
- *
906
- * @param {string} name
907
- * @return {Option}
908
- */
909
- env(name) {
910
- this.envVar = name;
911
- return this;
912
- }
913
- /**
914
- * Set the custom handler for processing CLI option arguments into option values.
915
- *
916
- * @param {Function} [fn]
917
- * @return {Option}
918
- */
919
- argParser(fn) {
920
- this.parseArg = fn;
921
- return this;
922
- }
923
- /**
924
- * Whether the option is mandatory and must have a value after parsing.
925
- *
926
- * @param {boolean} [mandatory=true]
927
- * @return {Option}
928
- */
929
- makeOptionMandatory(mandatory = true) {
930
- this.mandatory = !!mandatory;
931
- return this;
932
- }
933
- /**
934
- * Hide option in help.
935
- *
936
- * @param {boolean} [hide=true]
937
- * @return {Option}
938
- */
939
- hideHelp(hide = true) {
940
- this.hidden = !!hide;
941
- return this;
942
- }
943
- /**
944
- * @package
945
- */
946
- _collectValue(value, previous) {
947
- if (previous === this.defaultValue || !Array.isArray(previous)) {
948
- return [value];
949
- }
950
- previous.push(value);
951
- return previous;
952
- }
953
- /**
954
- * Only allow option value to be one of choices.
955
- *
956
- * @param {string[]} values
957
- * @return {Option}
958
- */
959
- choices(values) {
960
- this.argChoices = values.slice();
961
- this.parseArg = (arg, previous) => {
962
- if (!this.argChoices.includes(arg)) {
963
- throw new InvalidArgumentError2(
964
- `Allowed choices are ${this.argChoices.join(", ")}.`
965
- );
966
- }
967
- if (this.variadic) {
968
- return this._collectValue(arg, previous);
969
- }
970
- return arg;
971
- };
972
- return this;
973
- }
974
- /**
975
- * Return option name.
976
- *
977
- * @return {string}
978
- */
979
- name() {
980
- if (this.long) {
981
- return this.long.replace(/^--/, "");
982
- }
983
- return this.short.replace(/^-/, "");
984
- }
985
- /**
986
- * Return option name, in a camelcase format that can be used
987
- * as an object attribute key.
988
- *
989
- * @return {string}
990
- */
991
- attributeName() {
992
- if (this.negate) {
993
- return camelcase(this.name().replace(/^no-/, ""));
994
- }
995
- return camelcase(this.name());
996
- }
997
- /**
998
- * Set the help group heading.
999
- *
1000
- * @param {string} heading
1001
- * @return {Option}
1002
- */
1003
- helpGroup(heading) {
1004
- this.helpGroupHeading = heading;
1005
- return this;
1006
- }
1007
- /**
1008
- * Check if `arg` matches the short or long flag.
1009
- *
1010
- * @param {string} arg
1011
- * @return {boolean}
1012
- * @package
1013
- */
1014
- is(arg) {
1015
- return this.short === arg || this.long === arg;
1016
- }
1017
- /**
1018
- * Return whether a boolean option.
1019
- *
1020
- * Options are one of boolean, negated, required argument, or optional argument.
1021
- *
1022
- * @return {boolean}
1023
- * @package
1024
- */
1025
- isBoolean() {
1026
- return !this.required && !this.optional && !this.negate;
1027
- }
1028
- };
1029
- var DualOptions = class {
1030
- /**
1031
- * @param {Option[]} options
1032
- */
1033
- constructor(options) {
1034
- this.positiveOptions = /* @__PURE__ */ new Map();
1035
- this.negativeOptions = /* @__PURE__ */ new Map();
1036
- this.dualOptions = /* @__PURE__ */ new Set();
1037
- options.forEach((option) => {
1038
- if (option.negate) {
1039
- this.negativeOptions.set(option.attributeName(), option);
1040
- } else {
1041
- this.positiveOptions.set(option.attributeName(), option);
1042
- }
1043
- });
1044
- this.negativeOptions.forEach((value, key) => {
1045
- if (this.positiveOptions.has(key)) {
1046
- this.dualOptions.add(key);
1047
- }
1048
- });
1049
- }
1050
- /**
1051
- * Did the value come from the option, and not from possible matching dual option?
1052
- *
1053
- * @param {*} value
1054
- * @param {Option} option
1055
- * @returns {boolean}
1056
- */
1057
- valueFromOption(value, option) {
1058
- const optionKey = option.attributeName();
1059
- if (!this.dualOptions.has(optionKey)) return true;
1060
- const preset = this.negativeOptions.get(optionKey).presetArg;
1061
- const negativeValue = preset !== void 0 ? preset : false;
1062
- return option.negate === (negativeValue === value);
1063
- }
1064
- };
1065
- function camelcase(str) {
1066
- return str.split("-").reduce((str2, word) => {
1067
- return str2 + word[0].toUpperCase() + word.slice(1);
1068
- });
1069
- }
1070
- function splitOptionFlags(flags) {
1071
- let shortFlag;
1072
- let longFlag;
1073
- const shortFlagExp = /^-[^-]$/;
1074
- const longFlagExp = /^--[^-]/;
1075
- const flagParts = flags.split(/[ |,]+/).concat("guard");
1076
- if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1077
- if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1078
- if (!shortFlag && shortFlagExp.test(flagParts[0]))
1079
- shortFlag = flagParts.shift();
1080
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
1081
- shortFlag = longFlag;
1082
- longFlag = flagParts.shift();
1083
- }
1084
- if (flagParts[0].startsWith("-")) {
1085
- const unsupportedFlag = flagParts[0];
1086
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1087
- if (/^-[^-][^-]/.test(unsupportedFlag))
1088
- throw new Error(
1089
- `${baseError}
1090
- - a short flag is a single dash and a single character
1091
- - either use a single dash and a single character (for a short flag)
1092
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1093
- );
1094
- if (shortFlagExp.test(unsupportedFlag))
1095
- throw new Error(`${baseError}
1096
- - too many short flags`);
1097
- if (longFlagExp.test(unsupportedFlag))
1098
- throw new Error(`${baseError}
1099
- - too many long flags`);
1100
- throw new Error(`${baseError}
1101
- - unrecognised flag format`);
1102
- }
1103
- if (shortFlag === void 0 && longFlag === void 0)
1104
- throw new Error(
1105
- `option creation failed due to no flags found in '${flags}'.`
1106
- );
1107
- return { shortFlag, longFlag };
1108
- }
1109
- exports.Option = Option2;
1110
- exports.DualOptions = DualOptions;
1111
- }
1112
- });
1113
-
1114
- // ../node_modules/commander/lib/suggestSimilar.js
1115
- var require_suggestSimilar = __commonJS({
1116
- "../node_modules/commander/lib/suggestSimilar.js"(exports) {
1117
- var maxDistance = 3;
1118
- function editDistance(a, b) {
1119
- if (Math.abs(a.length - b.length) > maxDistance)
1120
- return Math.max(a.length, b.length);
1121
- const d = [];
1122
- for (let i = 0; i <= a.length; i++) {
1123
- d[i] = [i];
1124
- }
1125
- for (let j = 0; j <= b.length; j++) {
1126
- d[0][j] = j;
1127
- }
1128
- for (let j = 1; j <= b.length; j++) {
1129
- for (let i = 1; i <= a.length; i++) {
1130
- let cost = 1;
1131
- if (a[i - 1] === b[j - 1]) {
1132
- cost = 0;
1133
- } else {
1134
- cost = 1;
1135
- }
1136
- d[i][j] = Math.min(
1137
- d[i - 1][j] + 1,
1138
- // deletion
1139
- d[i][j - 1] + 1,
1140
- // insertion
1141
- d[i - 1][j - 1] + cost
1142
- // substitution
1143
- );
1144
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1145
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1146
- }
1147
- }
1148
- }
1149
- return d[a.length][b.length];
1150
- }
1151
- function suggestSimilar(word, candidates) {
1152
- if (!candidates || candidates.length === 0) return "";
1153
- candidates = Array.from(new Set(candidates));
1154
- const searchingOptions = word.startsWith("--");
1155
- if (searchingOptions) {
1156
- word = word.slice(2);
1157
- candidates = candidates.map((candidate) => candidate.slice(2));
1158
- }
1159
- let similar = [];
1160
- let bestDistance = maxDistance;
1161
- const minSimilarity = 0.4;
1162
- candidates.forEach((candidate) => {
1163
- if (candidate.length <= 1) return;
1164
- const distance = editDistance(word, candidate);
1165
- const length = Math.max(word.length, candidate.length);
1166
- const similarity = (length - distance) / length;
1167
- if (similarity > minSimilarity) {
1168
- if (distance < bestDistance) {
1169
- bestDistance = distance;
1170
- similar = [candidate];
1171
- } else if (distance === bestDistance) {
1172
- similar.push(candidate);
1173
- }
1174
- }
1175
- });
1176
- similar.sort((a, b) => a.localeCompare(b));
1177
- if (searchingOptions) {
1178
- similar = similar.map((candidate) => `--${candidate}`);
1179
- }
1180
- if (similar.length > 1) {
1181
- return `
1182
- (Did you mean one of ${similar.join(", ")}?)`;
1183
- }
1184
- if (similar.length === 1) {
1185
- return `
1186
- (Did you mean ${similar[0]}?)`;
1187
- }
1188
- return "";
1189
- }
1190
- exports.suggestSimilar = suggestSimilar;
1191
- }
1192
- });
1193
-
1194
- // ../node_modules/commander/lib/command.js
1195
- var require_command = __commonJS({
1196
- "../node_modules/commander/lib/command.js"(exports) {
1197
- var EventEmitter = __require("events").EventEmitter;
1198
- var childProcess = __require("child_process");
1199
- var path = __require("path");
1200
- var fs = __require("fs");
1201
- var process2 = __require("process");
1202
- var { Argument: Argument2, humanReadableArgName } = require_argument();
1203
- var { CommanderError: CommanderError2 } = require_error();
1204
- var { Help: Help2, stripColor } = require_help();
1205
- var { Option: Option2, DualOptions } = require_option();
1206
- var { suggestSimilar } = require_suggestSimilar();
1207
- var Command2 = class _Command extends EventEmitter {
1208
- /**
1209
- * Initialize a new `Command`.
1210
- *
1211
- * @param {string} [name]
1212
- */
1213
- constructor(name) {
1214
- super();
1215
- this.commands = [];
1216
- this.options = [];
1217
- this.parent = null;
1218
- this._allowUnknownOption = false;
1219
- this._allowExcessArguments = false;
1220
- this.registeredArguments = [];
1221
- this._args = this.registeredArguments;
1222
- this.args = [];
1223
- this.rawArgs = [];
1224
- this.processedArgs = [];
1225
- this._scriptPath = null;
1226
- this._name = name || "";
1227
- this._optionValues = {};
1228
- this._optionValueSources = {};
1229
- this._storeOptionsAsProperties = false;
1230
- this._actionHandler = null;
1231
- this._executableHandler = false;
1232
- this._executableFile = null;
1233
- this._executableDir = null;
1234
- this._defaultCommandName = null;
1235
- this._exitCallback = null;
1236
- this._aliases = [];
1237
- this._combineFlagAndOptionalValue = true;
1238
- this._description = "";
1239
- this._summary = "";
1240
- this._argsDescription = void 0;
1241
- this._enablePositionalOptions = false;
1242
- this._passThroughOptions = false;
1243
- this._lifeCycleHooks = {};
1244
- this._showHelpAfterError = false;
1245
- this._showSuggestionAfterError = true;
1246
- this._savedState = null;
1247
- this._outputConfiguration = {
1248
- writeOut: (str) => process2.stdout.write(str),
1249
- writeErr: (str) => process2.stderr.write(str),
1250
- outputError: (str, write) => write(str),
1251
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1252
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1253
- getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1254
- getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1255
- stripColor: (str) => stripColor(str)
1256
- };
1257
- this._hidden = false;
1258
- this._helpOption = void 0;
1259
- this._addImplicitHelpCommand = void 0;
1260
- this._helpCommand = void 0;
1261
- this._helpConfiguration = {};
1262
- this._helpGroupHeading = void 0;
1263
- this._defaultCommandGroup = void 0;
1264
- this._defaultOptionGroup = void 0;
1265
- }
1266
- /**
1267
- * Copy settings that are useful to have in common across root command and subcommands.
1268
- *
1269
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1270
- *
1271
- * @param {Command} sourceCommand
1272
- * @return {Command} `this` command for chaining
1273
- */
1274
- copyInheritedSettings(sourceCommand) {
1275
- this._outputConfiguration = sourceCommand._outputConfiguration;
1276
- this._helpOption = sourceCommand._helpOption;
1277
- this._helpCommand = sourceCommand._helpCommand;
1278
- this._helpConfiguration = sourceCommand._helpConfiguration;
1279
- this._exitCallback = sourceCommand._exitCallback;
1280
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1281
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1282
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1283
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1284
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1285
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1286
- return this;
1287
- }
1288
- /**
1289
- * @returns {Command[]}
1290
- * @private
1291
- */
1292
- _getCommandAndAncestors() {
1293
- const result = [];
1294
- for (let command = this; command; command = command.parent) {
1295
- result.push(command);
1296
- }
1297
- return result;
1298
- }
1299
- /**
1300
- * Define a command.
1301
- *
1302
- * There are two styles of command: pay attention to where to put the description.
1303
- *
1304
- * @example
1305
- * // Command implemented using action handler (description is supplied separately to `.command`)
1306
- * program
1307
- * .command('clone <source> [destination]')
1308
- * .description('clone a repository into a newly created directory')
1309
- * .action((source, destination) => {
1310
- * console.log('clone command called');
1311
- * });
1312
- *
1313
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1314
- * program
1315
- * .command('start <service>', 'start named service')
1316
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1317
- *
1318
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1319
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1320
- * @param {object} [execOpts] - configuration options (for executable)
1321
- * @return {Command} returns new command for action handler, or `this` for executable command
1322
- */
1323
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1324
- let desc = actionOptsOrExecDesc;
1325
- let opts = execOpts;
1326
- if (typeof desc === "object" && desc !== null) {
1327
- opts = desc;
1328
- desc = null;
1329
- }
1330
- opts = opts || {};
1331
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1332
- const cmd = this.createCommand(name);
1333
- if (desc) {
1334
- cmd.description(desc);
1335
- cmd._executableHandler = true;
1336
- }
1337
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1338
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1339
- cmd._executableFile = opts.executableFile || null;
1340
- if (args) cmd.arguments(args);
1341
- this._registerCommand(cmd);
1342
- cmd.parent = this;
1343
- cmd.copyInheritedSettings(this);
1344
- if (desc) return this;
1345
- return cmd;
1346
- }
1347
- /**
1348
- * Factory routine to create a new unattached command.
1349
- *
1350
- * See .command() for creating an attached subcommand, which uses this routine to
1351
- * create the command. You can override createCommand to customise subcommands.
1352
- *
1353
- * @param {string} [name]
1354
- * @return {Command} new command
1355
- */
1356
- createCommand(name) {
1357
- return new _Command(name);
1358
- }
1359
- /**
1360
- * You can customise the help with a subclass of Help by overriding createHelp,
1361
- * or by overriding Help properties using configureHelp().
1362
- *
1363
- * @return {Help}
1364
- */
1365
- createHelp() {
1366
- return Object.assign(new Help2(), this.configureHelp());
1367
- }
1368
- /**
1369
- * You can customise the help by overriding Help properties using configureHelp(),
1370
- * or with a subclass of Help by overriding createHelp().
1371
- *
1372
- * @param {object} [configuration] - configuration options
1373
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1374
- */
1375
- configureHelp(configuration) {
1376
- if (configuration === void 0) return this._helpConfiguration;
1377
- this._helpConfiguration = configuration;
1378
- return this;
1379
- }
1380
- /**
1381
- * The default output goes to stdout and stderr. You can customise this for special
1382
- * applications. You can also customise the display of errors by overriding outputError.
1383
- *
1384
- * The configuration properties are all functions:
1385
- *
1386
- * // change how output being written, defaults to stdout and stderr
1387
- * writeOut(str)
1388
- * writeErr(str)
1389
- * // change how output being written for errors, defaults to writeErr
1390
- * outputError(str, write) // used for displaying errors and not used for displaying help
1391
- * // specify width for wrapping help
1392
- * getOutHelpWidth()
1393
- * getErrHelpWidth()
1394
- * // color support, currently only used with Help
1395
- * getOutHasColors()
1396
- * getErrHasColors()
1397
- * stripColor() // used to remove ANSI escape codes if output does not have colors
1398
- *
1399
- * @param {object} [configuration] - configuration options
1400
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1401
- */
1402
- configureOutput(configuration) {
1403
- if (configuration === void 0) return this._outputConfiguration;
1404
- this._outputConfiguration = {
1405
- ...this._outputConfiguration,
1406
- ...configuration
1407
- };
1408
- return this;
1409
- }
1410
- /**
1411
- * Display the help or a custom message after an error occurs.
1412
- *
1413
- * @param {(boolean|string)} [displayHelp]
1414
- * @return {Command} `this` command for chaining
1415
- */
1416
- showHelpAfterError(displayHelp = true) {
1417
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1418
- this._showHelpAfterError = displayHelp;
1419
- return this;
1420
- }
1421
- /**
1422
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1423
- *
1424
- * @param {boolean} [displaySuggestion]
1425
- * @return {Command} `this` command for chaining
1426
- */
1427
- showSuggestionAfterError(displaySuggestion = true) {
1428
- this._showSuggestionAfterError = !!displaySuggestion;
1429
- return this;
1430
- }
1431
- /**
1432
- * Add a prepared subcommand.
1433
- *
1434
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1435
- *
1436
- * @param {Command} cmd - new subcommand
1437
- * @param {object} [opts] - configuration options
1438
- * @return {Command} `this` command for chaining
1439
- */
1440
- addCommand(cmd, opts) {
1441
- if (!cmd._name) {
1442
- throw new Error(`Command passed to .addCommand() must have a name
1443
- - specify the name in Command constructor or using .name()`);
1444
- }
1445
- opts = opts || {};
1446
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1447
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1448
- this._registerCommand(cmd);
1449
- cmd.parent = this;
1450
- cmd._checkForBrokenPassThrough();
1451
- return this;
1452
- }
1453
- /**
1454
- * Factory routine to create a new unattached argument.
1455
- *
1456
- * See .argument() for creating an attached argument, which uses this routine to
1457
- * create the argument. You can override createArgument to return a custom argument.
1458
- *
1459
- * @param {string} name
1460
- * @param {string} [description]
1461
- * @return {Argument} new argument
1462
- */
1463
- createArgument(name, description) {
1464
- return new Argument2(name, description);
1465
- }
1466
- /**
1467
- * Define argument syntax for command.
1468
- *
1469
- * The default is that the argument is required, and you can explicitly
1470
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1471
- *
1472
- * @example
1473
- * program.argument('<input-file>');
1474
- * program.argument('[output-file]');
1475
- *
1476
- * @param {string} name
1477
- * @param {string} [description]
1478
- * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1479
- * @param {*} [defaultValue]
1480
- * @return {Command} `this` command for chaining
1481
- */
1482
- argument(name, description, parseArg, defaultValue) {
1483
- const argument = this.createArgument(name, description);
1484
- if (typeof parseArg === "function") {
1485
- argument.default(defaultValue).argParser(parseArg);
1486
- } else {
1487
- argument.default(parseArg);
1488
- }
1489
- this.addArgument(argument);
1490
- return this;
1491
- }
1492
- /**
1493
- * Define argument syntax for command, adding multiple at once (without descriptions).
1494
- *
1495
- * See also .argument().
1496
- *
1497
- * @example
1498
- * program.arguments('<cmd> [env]');
1499
- *
1500
- * @param {string} names
1501
- * @return {Command} `this` command for chaining
1502
- */
1503
- arguments(names) {
1504
- names.trim().split(/ +/).forEach((detail) => {
1505
- this.argument(detail);
1506
- });
1507
- return this;
1508
- }
1509
- /**
1510
- * Define argument syntax for command, adding a prepared argument.
1511
- *
1512
- * @param {Argument} argument
1513
- * @return {Command} `this` command for chaining
1514
- */
1515
- addArgument(argument) {
1516
- const previousArgument = this.registeredArguments.slice(-1)[0];
1517
- if (previousArgument?.variadic) {
1518
- throw new Error(
1519
- `only the last argument can be variadic '${previousArgument.name()}'`
1520
- );
1521
- }
1522
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1523
- throw new Error(
1524
- `a default value for a required argument is never used: '${argument.name()}'`
1525
- );
1526
- }
1527
- this.registeredArguments.push(argument);
1528
- return this;
1529
- }
1530
- /**
1531
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1532
- *
1533
- * @example
1534
- * program.helpCommand('help [cmd]');
1535
- * program.helpCommand('help [cmd]', 'show help');
1536
- * program.helpCommand(false); // suppress default help command
1537
- * program.helpCommand(true); // add help command even if no subcommands
1538
- *
1539
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1540
- * @param {string} [description] - custom description
1541
- * @return {Command} `this` command for chaining
1542
- */
1543
- helpCommand(enableOrNameAndArgs, description) {
1544
- if (typeof enableOrNameAndArgs === "boolean") {
1545
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1546
- if (enableOrNameAndArgs && this._defaultCommandGroup) {
1547
- this._initCommandGroup(this._getHelpCommand());
1548
- }
1549
- return this;
1550
- }
1551
- const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1552
- const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1553
- const helpDescription = description ?? "display help for command";
1554
- const helpCommand = this.createCommand(helpName);
1555
- helpCommand.helpOption(false);
1556
- if (helpArgs) helpCommand.arguments(helpArgs);
1557
- if (helpDescription) helpCommand.description(helpDescription);
1558
- this._addImplicitHelpCommand = true;
1559
- this._helpCommand = helpCommand;
1560
- if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1561
- return this;
1562
- }
1563
- /**
1564
- * Add prepared custom help command.
1565
- *
1566
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1567
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1568
- * @return {Command} `this` command for chaining
1569
- */
1570
- addHelpCommand(helpCommand, deprecatedDescription) {
1571
- if (typeof helpCommand !== "object") {
1572
- this.helpCommand(helpCommand, deprecatedDescription);
1573
- return this;
1574
- }
1575
- this._addImplicitHelpCommand = true;
1576
- this._helpCommand = helpCommand;
1577
- this._initCommandGroup(helpCommand);
1578
- return this;
1579
- }
1580
- /**
1581
- * Lazy create help command.
1582
- *
1583
- * @return {(Command|null)}
1584
- * @package
1585
- */
1586
- _getHelpCommand() {
1587
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1588
- if (hasImplicitHelpCommand) {
1589
- if (this._helpCommand === void 0) {
1590
- this.helpCommand(void 0, void 0);
1591
- }
1592
- return this._helpCommand;
1593
- }
1594
- return null;
1595
- }
1596
- /**
1597
- * Add hook for life cycle event.
1598
- *
1599
- * @param {string} event
1600
- * @param {Function} listener
1601
- * @return {Command} `this` command for chaining
1602
- */
1603
- hook(event, listener) {
1604
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1605
- if (!allowedValues.includes(event)) {
1606
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1607
- Expecting one of '${allowedValues.join("', '")}'`);
1608
- }
1609
- if (this._lifeCycleHooks[event]) {
1610
- this._lifeCycleHooks[event].push(listener);
1611
- } else {
1612
- this._lifeCycleHooks[event] = [listener];
1613
- }
1614
- return this;
1615
- }
1616
- /**
1617
- * Register callback to use as replacement for calling process.exit.
1618
- *
1619
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1620
- * @return {Command} `this` command for chaining
1621
- */
1622
- exitOverride(fn) {
1623
- if (fn) {
1624
- this._exitCallback = fn;
1625
- } else {
1626
- this._exitCallback = (err) => {
1627
- if (err.code !== "commander.executeSubCommandAsync") {
1628
- throw err;
1629
- } else {
1630
- }
1631
- };
1632
- }
1633
- return this;
1634
- }
1635
- /**
1636
- * Call process.exit, and _exitCallback if defined.
1637
- *
1638
- * @param {number} exitCode exit code for using with process.exit
1639
- * @param {string} code an id string representing the error
1640
- * @param {string} message human-readable description of the error
1641
- * @return never
1642
- * @private
1643
- */
1644
- _exit(exitCode, code, message) {
1645
- if (this._exitCallback) {
1646
- this._exitCallback(new CommanderError2(exitCode, code, message));
1647
- }
1648
- process2.exit(exitCode);
1649
- }
1650
- /**
1651
- * Register callback `fn` for the command.
1652
- *
1653
- * @example
1654
- * program
1655
- * .command('serve')
1656
- * .description('start service')
1657
- * .action(function() {
1658
- * // do work here
1659
- * });
1660
- *
1661
- * @param {Function} fn
1662
- * @return {Command} `this` command for chaining
1663
- */
1664
- action(fn) {
1665
- const listener = (args) => {
1666
- const expectedArgsCount = this.registeredArguments.length;
1667
- const actionArgs = args.slice(0, expectedArgsCount);
1668
- if (this._storeOptionsAsProperties) {
1669
- actionArgs[expectedArgsCount] = this;
1670
- } else {
1671
- actionArgs[expectedArgsCount] = this.opts();
1672
- }
1673
- actionArgs.push(this);
1674
- return fn.apply(this, actionArgs);
1675
- };
1676
- this._actionHandler = listener;
1677
- return this;
1678
- }
1679
- /**
1680
- * Factory routine to create a new unattached option.
1681
- *
1682
- * See .option() for creating an attached option, which uses this routine to
1683
- * create the option. You can override createOption to return a custom option.
1684
- *
1685
- * @param {string} flags
1686
- * @param {string} [description]
1687
- * @return {Option} new option
1688
- */
1689
- createOption(flags, description) {
1690
- return new Option2(flags, description);
1691
- }
1692
- /**
1693
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1694
- *
1695
- * @param {(Option | Argument)} target
1696
- * @param {string} value
1697
- * @param {*} previous
1698
- * @param {string} invalidArgumentMessage
1699
- * @private
1700
- */
1701
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1702
- try {
1703
- return target.parseArg(value, previous);
1704
- } catch (err) {
1705
- if (err.code === "commander.invalidArgument") {
1706
- const message = `${invalidArgumentMessage} ${err.message}`;
1707
- this.error(message, { exitCode: err.exitCode, code: err.code });
1708
- }
1709
- throw err;
1710
- }
1711
- }
1712
- /**
1713
- * Check for option flag conflicts.
1714
- * Register option if no conflicts found, or throw on conflict.
1715
- *
1716
- * @param {Option} option
1717
- * @private
1718
- */
1719
- _registerOption(option) {
1720
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1721
- if (matchingOption) {
1722
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1723
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1724
- - already used by option '${matchingOption.flags}'`);
1725
- }
1726
- this._initOptionGroup(option);
1727
- this.options.push(option);
1728
- }
1729
- /**
1730
- * Check for command name and alias conflicts with existing commands.
1731
- * Register command if no conflicts found, or throw on conflict.
1732
- *
1733
- * @param {Command} command
1734
- * @private
1735
- */
1736
- _registerCommand(command) {
1737
- const knownBy = (cmd) => {
1738
- return [cmd.name()].concat(cmd.aliases());
1739
- };
1740
- const alreadyUsed = knownBy(command).find(
1741
- (name) => this._findCommand(name)
1742
- );
1743
- if (alreadyUsed) {
1744
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1745
- const newCmd = knownBy(command).join("|");
1746
- throw new Error(
1747
- `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1748
- );
1749
- }
1750
- this._initCommandGroup(command);
1751
- this.commands.push(command);
1752
- }
1753
- /**
1754
- * Add an option.
1755
- *
1756
- * @param {Option} option
1757
- * @return {Command} `this` command for chaining
1758
- */
1759
- addOption(option) {
1760
- this._registerOption(option);
1761
- const oname = option.name();
1762
- const name = option.attributeName();
1763
- if (option.negate) {
1764
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1765
- if (!this._findOption(positiveLongFlag)) {
1766
- this.setOptionValueWithSource(
1767
- name,
1768
- option.defaultValue === void 0 ? true : option.defaultValue,
1769
- "default"
1770
- );
1771
- }
1772
- } else if (option.defaultValue !== void 0) {
1773
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1774
- }
1775
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1776
- if (val == null && option.presetArg !== void 0) {
1777
- val = option.presetArg;
1778
- }
1779
- const oldValue = this.getOptionValue(name);
1780
- if (val !== null && option.parseArg) {
1781
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1782
- } else if (val !== null && option.variadic) {
1783
- val = option._collectValue(val, oldValue);
1784
- }
1785
- if (val == null) {
1786
- if (option.negate) {
1787
- val = false;
1788
- } else if (option.isBoolean() || option.optional) {
1789
- val = true;
1790
- } else {
1791
- val = "";
1792
- }
1793
- }
1794
- this.setOptionValueWithSource(name, val, valueSource);
1795
- };
1796
- this.on("option:" + oname, (val) => {
1797
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1798
- handleOptionValue(val, invalidValueMessage, "cli");
1799
- });
1800
- if (option.envVar) {
1801
- this.on("optionEnv:" + oname, (val) => {
1802
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1803
- handleOptionValue(val, invalidValueMessage, "env");
1804
- });
1805
- }
1806
- return this;
1807
- }
1808
- /**
1809
- * Internal implementation shared by .option() and .requiredOption()
1810
- *
1811
- * @return {Command} `this` command for chaining
1812
- * @private
1813
- */
1814
- _optionEx(config, flags, description, fn, defaultValue) {
1815
- if (typeof flags === "object" && flags instanceof Option2) {
1816
- throw new Error(
1817
- "To add an Option object use addOption() instead of option() or requiredOption()"
1818
- );
1819
- }
1820
- const option = this.createOption(flags, description);
1821
- option.makeOptionMandatory(!!config.mandatory);
1822
- if (typeof fn === "function") {
1823
- option.default(defaultValue).argParser(fn);
1824
- } else if (fn instanceof RegExp) {
1825
- const regex = fn;
1826
- fn = (val, def) => {
1827
- const m = regex.exec(val);
1828
- return m ? m[0] : def;
1829
- };
1830
- option.default(defaultValue).argParser(fn);
1831
- } else {
1832
- option.default(fn);
1833
- }
1834
- return this.addOption(option);
1835
- }
1836
- /**
1837
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1838
- *
1839
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1840
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1841
- *
1842
- * See the README for more details, and see also addOption() and requiredOption().
1843
- *
1844
- * @example
1845
- * program
1846
- * .option('-p, --pepper', 'add pepper')
1847
- * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1848
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1849
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1850
- *
1851
- * @param {string} flags
1852
- * @param {string} [description]
1853
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1854
- * @param {*} [defaultValue]
1855
- * @return {Command} `this` command for chaining
1856
- */
1857
- option(flags, description, parseArg, defaultValue) {
1858
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1859
- }
1860
- /**
1861
- * Add a required option which must have a value after parsing. This usually means
1862
- * the option must be specified on the command line. (Otherwise the same as .option().)
1863
- *
1864
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1865
- *
1866
- * @param {string} flags
1867
- * @param {string} [description]
1868
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1869
- * @param {*} [defaultValue]
1870
- * @return {Command} `this` command for chaining
1871
- */
1872
- requiredOption(flags, description, parseArg, defaultValue) {
1873
- return this._optionEx(
1874
- { mandatory: true },
1875
- flags,
1876
- description,
1877
- parseArg,
1878
- defaultValue
1879
- );
1880
- }
1881
- /**
1882
- * Alter parsing of short flags with optional values.
1883
- *
1884
- * @example
1885
- * // for `.option('-f,--flag [value]'):
1886
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1887
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1888
- *
1889
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1890
- * @return {Command} `this` command for chaining
1891
- */
1892
- combineFlagAndOptionalValue(combine = true) {
1893
- this._combineFlagAndOptionalValue = !!combine;
1894
- return this;
1895
- }
1896
- /**
1897
- * Allow unknown options on the command line.
1898
- *
1899
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1900
- * @return {Command} `this` command for chaining
1901
- */
1902
- allowUnknownOption(allowUnknown = true) {
1903
- this._allowUnknownOption = !!allowUnknown;
1904
- return this;
1905
- }
1906
- /**
1907
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1908
- *
1909
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1910
- * @return {Command} `this` command for chaining
1911
- */
1912
- allowExcessArguments(allowExcess = true) {
1913
- this._allowExcessArguments = !!allowExcess;
1914
- return this;
1915
- }
1916
- /**
1917
- * Enable positional options. Positional means global options are specified before subcommands which lets
1918
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1919
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1920
- *
1921
- * @param {boolean} [positional]
1922
- * @return {Command} `this` command for chaining
1923
- */
1924
- enablePositionalOptions(positional = true) {
1925
- this._enablePositionalOptions = !!positional;
1926
- return this;
1927
- }
1928
- /**
1929
- * Pass through options that come after command-arguments rather than treat them as command-options,
1930
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1931
- * positional options to have been enabled on the program (parent commands).
1932
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1933
- *
1934
- * @param {boolean} [passThrough] for unknown options.
1935
- * @return {Command} `this` command for chaining
1936
- */
1937
- passThroughOptions(passThrough = true) {
1938
- this._passThroughOptions = !!passThrough;
1939
- this._checkForBrokenPassThrough();
1940
- return this;
1941
- }
1942
- /**
1943
- * @private
1944
- */
1945
- _checkForBrokenPassThrough() {
1946
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1947
- throw new Error(
1948
- `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1949
- );
1950
- }
1951
- }
1952
- /**
1953
- * Whether to store option values as properties on command object,
1954
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1955
- *
1956
- * @param {boolean} [storeAsProperties=true]
1957
- * @return {Command} `this` command for chaining
1958
- */
1959
- storeOptionsAsProperties(storeAsProperties = true) {
1960
- if (this.options.length) {
1961
- throw new Error("call .storeOptionsAsProperties() before adding options");
1962
- }
1963
- if (Object.keys(this._optionValues).length) {
1964
- throw new Error(
1965
- "call .storeOptionsAsProperties() before setting option values"
1966
- );
1967
- }
1968
- this._storeOptionsAsProperties = !!storeAsProperties;
1969
- return this;
1970
- }
1971
- /**
1972
- * Retrieve option value.
1973
- *
1974
- * @param {string} key
1975
- * @return {object} value
1976
- */
1977
- getOptionValue(key) {
1978
- if (this._storeOptionsAsProperties) {
1979
- return this[key];
1980
- }
1981
- return this._optionValues[key];
1982
- }
1983
- /**
1984
- * Store option value.
1985
- *
1986
- * @param {string} key
1987
- * @param {object} value
1988
- * @return {Command} `this` command for chaining
1989
- */
1990
- setOptionValue(key, value) {
1991
- return this.setOptionValueWithSource(key, value, void 0);
1992
- }
1993
- /**
1994
- * Store option value and where the value came from.
1995
- *
1996
- * @param {string} key
1997
- * @param {object} value
1998
- * @param {string} source - expected values are default/config/env/cli/implied
1999
- * @return {Command} `this` command for chaining
2000
- */
2001
- setOptionValueWithSource(key, value, source) {
2002
- if (this._storeOptionsAsProperties) {
2003
- this[key] = value;
2004
- } else {
2005
- this._optionValues[key] = value;
2006
- }
2007
- this._optionValueSources[key] = source;
2008
- return this;
2009
- }
2010
- /**
2011
- * Get source of option value.
2012
- * Expected values are default | config | env | cli | implied
2013
- *
2014
- * @param {string} key
2015
- * @return {string}
2016
- */
2017
- getOptionValueSource(key) {
2018
- return this._optionValueSources[key];
2019
- }
2020
- /**
2021
- * Get source of option value. See also .optsWithGlobals().
2022
- * Expected values are default | config | env | cli | implied
2023
- *
2024
- * @param {string} key
2025
- * @return {string}
2026
- */
2027
- getOptionValueSourceWithGlobals(key) {
2028
- let source;
2029
- this._getCommandAndAncestors().forEach((cmd) => {
2030
- if (cmd.getOptionValueSource(key) !== void 0) {
2031
- source = cmd.getOptionValueSource(key);
2032
- }
2033
- });
2034
- return source;
2035
- }
2036
- /**
2037
- * Get user arguments from implied or explicit arguments.
2038
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2039
- *
2040
- * @private
2041
- */
2042
- _prepareUserArgs(argv, parseOptions) {
2043
- if (argv !== void 0 && !Array.isArray(argv)) {
2044
- throw new Error("first parameter to parse must be array or undefined");
2045
- }
2046
- parseOptions = parseOptions || {};
2047
- if (argv === void 0 && parseOptions.from === void 0) {
2048
- if (process2.versions?.electron) {
2049
- parseOptions.from = "electron";
2050
- }
2051
- const execArgv = process2.execArgv ?? [];
2052
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2053
- parseOptions.from = "eval";
2054
- }
2055
- }
2056
- if (argv === void 0) {
2057
- argv = process2.argv;
2058
- }
2059
- this.rawArgs = argv.slice();
2060
- let userArgs;
2061
- switch (parseOptions.from) {
2062
- case void 0:
2063
- case "node":
2064
- this._scriptPath = argv[1];
2065
- userArgs = argv.slice(2);
2066
- break;
2067
- case "electron":
2068
- if (process2.defaultApp) {
2069
- this._scriptPath = argv[1];
2070
- userArgs = argv.slice(2);
2071
- } else {
2072
- userArgs = argv.slice(1);
2073
- }
2074
- break;
2075
- case "user":
2076
- userArgs = argv.slice(0);
2077
- break;
2078
- case "eval":
2079
- userArgs = argv.slice(1);
2080
- break;
2081
- default:
2082
- throw new Error(
2083
- `unexpected parse option { from: '${parseOptions.from}' }`
2084
- );
2085
- }
2086
- if (!this._name && this._scriptPath)
2087
- this.nameFromFilename(this._scriptPath);
2088
- this._name = this._name || "program";
2089
- return userArgs;
2090
- }
2091
- /**
2092
- * Parse `argv`, setting options and invoking commands when defined.
2093
- *
2094
- * Use parseAsync instead of parse if any of your action handlers are async.
2095
- *
2096
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2097
- *
2098
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2099
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2100
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2101
- * - `'user'`: just user arguments
2102
- *
2103
- * @example
2104
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
2105
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2106
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2107
- *
2108
- * @param {string[]} [argv] - optional, defaults to process.argv
2109
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2110
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2111
- * @return {Command} `this` command for chaining
2112
- */
2113
- parse(argv, parseOptions) {
2114
- this._prepareForParse();
2115
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2116
- this._parseCommand([], userArgs);
2117
- return this;
2118
- }
2119
- /**
2120
- * Parse `argv`, setting options and invoking commands when defined.
2121
- *
2122
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2123
- *
2124
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2125
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2126
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2127
- * - `'user'`: just user arguments
2128
- *
2129
- * @example
2130
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2131
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2132
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2133
- *
2134
- * @param {string[]} [argv]
2135
- * @param {object} [parseOptions]
2136
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2137
- * @return {Promise}
2138
- */
2139
- async parseAsync(argv, parseOptions) {
2140
- this._prepareForParse();
2141
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2142
- await this._parseCommand([], userArgs);
2143
- return this;
2144
- }
2145
- _prepareForParse() {
2146
- if (this._savedState === null) {
2147
- this.saveStateBeforeParse();
2148
- } else {
2149
- this.restoreStateBeforeParse();
2150
- }
2151
- }
2152
- /**
2153
- * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2154
- * Not usually called directly, but available for subclasses to save their custom state.
2155
- *
2156
- * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2157
- */
2158
- saveStateBeforeParse() {
2159
- this._savedState = {
2160
- // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2161
- _name: this._name,
2162
- // option values before parse have default values (including false for negated options)
2163
- // shallow clones
2164
- _optionValues: { ...this._optionValues },
2165
- _optionValueSources: { ...this._optionValueSources }
2166
- };
2167
- }
2168
- /**
2169
- * Restore state before parse for calls after the first.
2170
- * Not usually called directly, but available for subclasses to save their custom state.
2171
- *
2172
- * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2173
- */
2174
- restoreStateBeforeParse() {
2175
- if (this._storeOptionsAsProperties)
2176
- throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2177
- - either make a new Command for each call to parse, or stop storing options as properties`);
2178
- this._name = this._savedState._name;
2179
- this._scriptPath = null;
2180
- this.rawArgs = [];
2181
- this._optionValues = { ...this._savedState._optionValues };
2182
- this._optionValueSources = { ...this._savedState._optionValueSources };
2183
- this.args = [];
2184
- this.processedArgs = [];
2185
- }
2186
- /**
2187
- * Throw if expected executable is missing. Add lots of help for author.
2188
- *
2189
- * @param {string} executableFile
2190
- * @param {string} executableDir
2191
- * @param {string} subcommandName
2192
- */
2193
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2194
- if (fs.existsSync(executableFile)) return;
2195
- const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2196
- const executableMissing = `'${executableFile}' does not exist
2197
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2198
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2199
- - ${executableDirMessage}`;
2200
- throw new Error(executableMissing);
2201
- }
2202
- /**
2203
- * Execute a sub-command executable.
2204
- *
2205
- * @private
2206
- */
2207
- _executeSubCommand(subcommand, args) {
2208
- args = args.slice();
2209
- let launchWithNode = false;
2210
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2211
- function findFile(baseDir, baseName) {
2212
- const localBin = path.resolve(baseDir, baseName);
2213
- if (fs.existsSync(localBin)) return localBin;
2214
- if (sourceExt.includes(path.extname(baseName))) return void 0;
2215
- const foundExt = sourceExt.find(
2216
- (ext) => fs.existsSync(`${localBin}${ext}`)
2217
- );
2218
- if (foundExt) return `${localBin}${foundExt}`;
2219
- return void 0;
2220
- }
2221
- this._checkForMissingMandatoryOptions();
2222
- this._checkForConflictingOptions();
2223
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2224
- let executableDir = this._executableDir || "";
2225
- if (this._scriptPath) {
2226
- let resolvedScriptPath;
2227
- try {
2228
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
2229
- } catch {
2230
- resolvedScriptPath = this._scriptPath;
2231
- }
2232
- executableDir = path.resolve(
2233
- path.dirname(resolvedScriptPath),
2234
- executableDir
2235
- );
2236
- }
2237
- if (executableDir) {
2238
- let localFile = findFile(executableDir, executableFile);
2239
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
2240
- const legacyName = path.basename(
2241
- this._scriptPath,
2242
- path.extname(this._scriptPath)
2243
- );
2244
- if (legacyName !== this._name) {
2245
- localFile = findFile(
2246
- executableDir,
2247
- `${legacyName}-${subcommand._name}`
2248
- );
2249
- }
2250
- }
2251
- executableFile = localFile || executableFile;
2252
- }
2253
- launchWithNode = sourceExt.includes(path.extname(executableFile));
2254
- let proc;
2255
- if (process2.platform !== "win32") {
2256
- if (launchWithNode) {
2257
- args.unshift(executableFile);
2258
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2259
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2260
- } else {
2261
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2262
- }
2263
- } else {
2264
- this._checkForMissingExecutable(
2265
- executableFile,
2266
- executableDir,
2267
- subcommand._name
2268
- );
2269
- args.unshift(executableFile);
2270
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2271
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2272
- }
2273
- if (!proc.killed) {
2274
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2275
- signals.forEach((signal) => {
2276
- process2.on(signal, () => {
2277
- if (proc.killed === false && proc.exitCode === null) {
2278
- proc.kill(signal);
2279
- }
2280
- });
2281
- });
2282
- }
2283
- const exitCallback = this._exitCallback;
2284
- proc.on("close", (code) => {
2285
- code = code ?? 1;
2286
- if (!exitCallback) {
2287
- process2.exit(code);
2288
- } else {
2289
- exitCallback(
2290
- new CommanderError2(
2291
- code,
2292
- "commander.executeSubCommandAsync",
2293
- "(close)"
2294
- )
2295
- );
2296
- }
2297
- });
2298
- proc.on("error", (err) => {
2299
- if (err.code === "ENOENT") {
2300
- this._checkForMissingExecutable(
2301
- executableFile,
2302
- executableDir,
2303
- subcommand._name
2304
- );
2305
- } else if (err.code === "EACCES") {
2306
- throw new Error(`'${executableFile}' not executable`);
2307
- }
2308
- if (!exitCallback) {
2309
- process2.exit(1);
2310
- } else {
2311
- const wrappedError = new CommanderError2(
2312
- 1,
2313
- "commander.executeSubCommandAsync",
2314
- "(error)"
2315
- );
2316
- wrappedError.nestedError = err;
2317
- exitCallback(wrappedError);
2318
- }
2319
- });
2320
- this.runningCommand = proc;
2321
- }
2322
- /**
2323
- * @private
2324
- */
2325
- _dispatchSubcommand(commandName, operands, unknown) {
2326
- const subCommand = this._findCommand(commandName);
2327
- if (!subCommand) this.help({ error: true });
2328
- subCommand._prepareForParse();
2329
- let promiseChain;
2330
- promiseChain = this._chainOrCallSubCommandHook(
2331
- promiseChain,
2332
- subCommand,
2333
- "preSubcommand"
2334
- );
2335
- promiseChain = this._chainOrCall(promiseChain, () => {
2336
- if (subCommand._executableHandler) {
2337
- this._executeSubCommand(subCommand, operands.concat(unknown));
2338
- } else {
2339
- return subCommand._parseCommand(operands, unknown);
2340
- }
2341
- });
2342
- return promiseChain;
2343
- }
2344
- /**
2345
- * Invoke help directly if possible, or dispatch if necessary.
2346
- * e.g. help foo
2347
- *
2348
- * @private
2349
- */
2350
- _dispatchHelpCommand(subcommandName) {
2351
- if (!subcommandName) {
2352
- this.help();
2353
- }
2354
- const subCommand = this._findCommand(subcommandName);
2355
- if (subCommand && !subCommand._executableHandler) {
2356
- subCommand.help();
2357
- }
2358
- return this._dispatchSubcommand(
2359
- subcommandName,
2360
- [],
2361
- [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2362
- );
2363
- }
2364
- /**
2365
- * Check this.args against expected this.registeredArguments.
2366
- *
2367
- * @private
2368
- */
2369
- _checkNumberOfArguments() {
2370
- this.registeredArguments.forEach((arg, i) => {
2371
- if (arg.required && this.args[i] == null) {
2372
- this.missingArgument(arg.name());
2373
- }
2374
- });
2375
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2376
- return;
2377
- }
2378
- if (this.args.length > this.registeredArguments.length) {
2379
- this._excessArguments(this.args);
2380
- }
2381
- }
2382
- /**
2383
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2384
- *
2385
- * @private
2386
- */
2387
- _processArguments() {
2388
- const myParseArg = (argument, value, previous) => {
2389
- let parsedValue = value;
2390
- if (value !== null && argument.parseArg) {
2391
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2392
- parsedValue = this._callParseArg(
2393
- argument,
2394
- value,
2395
- previous,
2396
- invalidValueMessage
2397
- );
2398
- }
2399
- return parsedValue;
2400
- };
2401
- this._checkNumberOfArguments();
2402
- const processedArgs = [];
2403
- this.registeredArguments.forEach((declaredArg, index) => {
2404
- let value = declaredArg.defaultValue;
2405
- if (declaredArg.variadic) {
2406
- if (index < this.args.length) {
2407
- value = this.args.slice(index);
2408
- if (declaredArg.parseArg) {
2409
- value = value.reduce((processed, v) => {
2410
- return myParseArg(declaredArg, v, processed);
2411
- }, declaredArg.defaultValue);
2412
- }
2413
- } else if (value === void 0) {
2414
- value = [];
2415
- }
2416
- } else if (index < this.args.length) {
2417
- value = this.args[index];
2418
- if (declaredArg.parseArg) {
2419
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2420
- }
2421
- }
2422
- processedArgs[index] = value;
2423
- });
2424
- this.processedArgs = processedArgs;
2425
- }
2426
- /**
2427
- * Once we have a promise we chain, but call synchronously until then.
2428
- *
2429
- * @param {(Promise|undefined)} promise
2430
- * @param {Function} fn
2431
- * @return {(Promise|undefined)}
2432
- * @private
2433
- */
2434
- _chainOrCall(promise, fn) {
2435
- if (promise?.then && typeof promise.then === "function") {
2436
- return promise.then(() => fn());
2437
- }
2438
- return fn();
2439
- }
2440
- /**
2441
- *
2442
- * @param {(Promise|undefined)} promise
2443
- * @param {string} event
2444
- * @return {(Promise|undefined)}
2445
- * @private
2446
- */
2447
- _chainOrCallHooks(promise, event) {
2448
- let result = promise;
2449
- const hooks = [];
2450
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2451
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2452
- hooks.push({ hookedCommand, callback });
2453
- });
2454
- });
2455
- if (event === "postAction") {
2456
- hooks.reverse();
2457
- }
2458
- hooks.forEach((hookDetail) => {
2459
- result = this._chainOrCall(result, () => {
2460
- return hookDetail.callback(hookDetail.hookedCommand, this);
2461
- });
2462
- });
2463
- return result;
2464
- }
2465
- /**
2466
- *
2467
- * @param {(Promise|undefined)} promise
2468
- * @param {Command} subCommand
2469
- * @param {string} event
2470
- * @return {(Promise|undefined)}
2471
- * @private
2472
- */
2473
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2474
- let result = promise;
2475
- if (this._lifeCycleHooks[event] !== void 0) {
2476
- this._lifeCycleHooks[event].forEach((hook) => {
2477
- result = this._chainOrCall(result, () => {
2478
- return hook(this, subCommand);
2479
- });
2480
- });
2481
- }
2482
- return result;
2483
- }
2484
- /**
2485
- * Process arguments in context of this command.
2486
- * Returns action result, in case it is a promise.
2487
- *
2488
- * @private
2489
- */
2490
- _parseCommand(operands, unknown) {
2491
- const parsed = this.parseOptions(unknown);
2492
- this._parseOptionsEnv();
2493
- this._parseOptionsImplied();
2494
- operands = operands.concat(parsed.operands);
2495
- unknown = parsed.unknown;
2496
- this.args = operands.concat(unknown);
2497
- if (operands && this._findCommand(operands[0])) {
2498
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2499
- }
2500
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2501
- return this._dispatchHelpCommand(operands[1]);
2502
- }
2503
- if (this._defaultCommandName) {
2504
- this._outputHelpIfRequested(unknown);
2505
- return this._dispatchSubcommand(
2506
- this._defaultCommandName,
2507
- operands,
2508
- unknown
2509
- );
2510
- }
2511
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2512
- this.help({ error: true });
2513
- }
2514
- this._outputHelpIfRequested(parsed.unknown);
2515
- this._checkForMissingMandatoryOptions();
2516
- this._checkForConflictingOptions();
2517
- const checkForUnknownOptions = () => {
2518
- if (parsed.unknown.length > 0) {
2519
- this.unknownOption(parsed.unknown[0]);
2520
- }
2521
- };
2522
- const commandEvent = `command:${this.name()}`;
2523
- if (this._actionHandler) {
2524
- checkForUnknownOptions();
2525
- this._processArguments();
2526
- let promiseChain;
2527
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2528
- promiseChain = this._chainOrCall(
2529
- promiseChain,
2530
- () => this._actionHandler(this.processedArgs)
2531
- );
2532
- if (this.parent) {
2533
- promiseChain = this._chainOrCall(promiseChain, () => {
2534
- this.parent.emit(commandEvent, operands, unknown);
2535
- });
2536
- }
2537
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2538
- return promiseChain;
2539
- }
2540
- if (this.parent?.listenerCount(commandEvent)) {
2541
- checkForUnknownOptions();
2542
- this._processArguments();
2543
- this.parent.emit(commandEvent, operands, unknown);
2544
- } else if (operands.length) {
2545
- if (this._findCommand("*")) {
2546
- return this._dispatchSubcommand("*", operands, unknown);
2547
- }
2548
- if (this.listenerCount("command:*")) {
2549
- this.emit("command:*", operands, unknown);
2550
- } else if (this.commands.length) {
2551
- this.unknownCommand();
2552
- } else {
2553
- checkForUnknownOptions();
2554
- this._processArguments();
2555
- }
2556
- } else if (this.commands.length) {
2557
- checkForUnknownOptions();
2558
- this.help({ error: true });
2559
- } else {
2560
- checkForUnknownOptions();
2561
- this._processArguments();
2562
- }
2563
- }
2564
- /**
2565
- * Find matching command.
2566
- *
2567
- * @private
2568
- * @return {Command | undefined}
2569
- */
2570
- _findCommand(name) {
2571
- if (!name) return void 0;
2572
- return this.commands.find(
2573
- (cmd) => cmd._name === name || cmd._aliases.includes(name)
2574
- );
2575
- }
2576
- /**
2577
- * Return an option matching `arg` if any.
2578
- *
2579
- * @param {string} arg
2580
- * @return {Option}
2581
- * @package
2582
- */
2583
- _findOption(arg) {
2584
- return this.options.find((option) => option.is(arg));
2585
- }
2586
- /**
2587
- * Display an error message if a mandatory option does not have a value.
2588
- * Called after checking for help flags in leaf subcommand.
2589
- *
2590
- * @private
2591
- */
2592
- _checkForMissingMandatoryOptions() {
2593
- this._getCommandAndAncestors().forEach((cmd) => {
2594
- cmd.options.forEach((anOption) => {
2595
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2596
- cmd.missingMandatoryOptionValue(anOption);
2597
- }
2598
- });
2599
- });
2600
- }
2601
- /**
2602
- * Display an error message if conflicting options are used together in this.
2603
- *
2604
- * @private
2605
- */
2606
- _checkForConflictingLocalOptions() {
2607
- const definedNonDefaultOptions = this.options.filter((option) => {
2608
- const optionKey = option.attributeName();
2609
- if (this.getOptionValue(optionKey) === void 0) {
2610
- return false;
2611
- }
2612
- return this.getOptionValueSource(optionKey) !== "default";
2613
- });
2614
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2615
- (option) => option.conflictsWith.length > 0
2616
- );
2617
- optionsWithConflicting.forEach((option) => {
2618
- const conflictingAndDefined = definedNonDefaultOptions.find(
2619
- (defined) => option.conflictsWith.includes(defined.attributeName())
2620
- );
2621
- if (conflictingAndDefined) {
2622
- this._conflictingOption(option, conflictingAndDefined);
2623
- }
2624
- });
2625
- }
2626
- /**
2627
- * Display an error message if conflicting options are used together.
2628
- * Called after checking for help flags in leaf subcommand.
2629
- *
2630
- * @private
2631
- */
2632
- _checkForConflictingOptions() {
2633
- this._getCommandAndAncestors().forEach((cmd) => {
2634
- cmd._checkForConflictingLocalOptions();
2635
- });
2636
- }
2637
- /**
2638
- * Parse options from `argv` removing known options,
2639
- * and return argv split into operands and unknown arguments.
2640
- *
2641
- * Side effects: modifies command by storing options. Does not reset state if called again.
2642
- *
2643
- * Examples:
2644
- *
2645
- * argv => operands, unknown
2646
- * --known kkk op => [op], []
2647
- * op --known kkk => [op], []
2648
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2649
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2650
- *
2651
- * @param {string[]} args
2652
- * @return {{operands: string[], unknown: string[]}}
2653
- */
2654
- parseOptions(args) {
2655
- const operands = [];
2656
- const unknown = [];
2657
- let dest = operands;
2658
- function maybeOption(arg) {
2659
- return arg.length > 1 && arg[0] === "-";
2660
- }
2661
- const negativeNumberArg = (arg) => {
2662
- if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2663
- return !this._getCommandAndAncestors().some(
2664
- (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2665
- );
2666
- };
2667
- let activeVariadicOption = null;
2668
- let activeGroup = null;
2669
- let i = 0;
2670
- while (i < args.length || activeGroup) {
2671
- const arg = activeGroup ?? args[i++];
2672
- activeGroup = null;
2673
- if (arg === "--") {
2674
- if (dest === unknown) dest.push(arg);
2675
- dest.push(...args.slice(i));
2676
- break;
2677
- }
2678
- if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2679
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2680
- continue;
2681
- }
2682
- activeVariadicOption = null;
2683
- if (maybeOption(arg)) {
2684
- const option = this._findOption(arg);
2685
- if (option) {
2686
- if (option.required) {
2687
- const value = args[i++];
2688
- if (value === void 0) this.optionMissingArgument(option);
2689
- this.emit(`option:${option.name()}`, value);
2690
- } else if (option.optional) {
2691
- let value = null;
2692
- if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2693
- value = args[i++];
2694
- }
2695
- this.emit(`option:${option.name()}`, value);
2696
- } else {
2697
- this.emit(`option:${option.name()}`);
2698
- }
2699
- activeVariadicOption = option.variadic ? option : null;
2700
- continue;
2701
- }
2702
- }
2703
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2704
- const option = this._findOption(`-${arg[1]}`);
2705
- if (option) {
2706
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2707
- this.emit(`option:${option.name()}`, arg.slice(2));
2708
- } else {
2709
- this.emit(`option:${option.name()}`);
2710
- activeGroup = `-${arg.slice(2)}`;
2711
- }
2712
- continue;
2713
- }
2714
- }
2715
- if (/^--[^=]+=/.test(arg)) {
2716
- const index = arg.indexOf("=");
2717
- const option = this._findOption(arg.slice(0, index));
2718
- if (option && (option.required || option.optional)) {
2719
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2720
- continue;
2721
- }
2722
- }
2723
- if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2724
- dest = unknown;
2725
- }
2726
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2727
- if (this._findCommand(arg)) {
2728
- operands.push(arg);
2729
- unknown.push(...args.slice(i));
2730
- break;
2731
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2732
- operands.push(arg, ...args.slice(i));
2733
- break;
2734
- } else if (this._defaultCommandName) {
2735
- unknown.push(arg, ...args.slice(i));
2736
- break;
2737
- }
2738
- }
2739
- if (this._passThroughOptions) {
2740
- dest.push(arg, ...args.slice(i));
2741
- break;
2742
- }
2743
- dest.push(arg);
2744
- }
2745
- return { operands, unknown };
2746
- }
2747
- /**
2748
- * Return an object containing local option values as key-value pairs.
2749
- *
2750
- * @return {object}
2751
- */
2752
- opts() {
2753
- if (this._storeOptionsAsProperties) {
2754
- const result = {};
2755
- const len = this.options.length;
2756
- for (let i = 0; i < len; i++) {
2757
- const key = this.options[i].attributeName();
2758
- result[key] = key === this._versionOptionName ? this._version : this[key];
2759
- }
2760
- return result;
2761
- }
2762
- return this._optionValues;
2763
- }
2764
- /**
2765
- * Return an object containing merged local and global option values as key-value pairs.
2766
- *
2767
- * @return {object}
2768
- */
2769
- optsWithGlobals() {
2770
- return this._getCommandAndAncestors().reduce(
2771
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2772
- {}
2773
- );
2774
- }
2775
- /**
2776
- * Display error message and exit (or call exitOverride).
2777
- *
2778
- * @param {string} message
2779
- * @param {object} [errorOptions]
2780
- * @param {string} [errorOptions.code] - an id string representing the error
2781
- * @param {number} [errorOptions.exitCode] - used with process.exit
2782
- */
2783
- error(message, errorOptions) {
2784
- this._outputConfiguration.outputError(
2785
- `${message}
2786
- `,
2787
- this._outputConfiguration.writeErr
2788
- );
2789
- if (typeof this._showHelpAfterError === "string") {
2790
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2791
- `);
2792
- } else if (this._showHelpAfterError) {
2793
- this._outputConfiguration.writeErr("\n");
2794
- this.outputHelp({ error: true });
2795
- }
2796
- const config = errorOptions || {};
2797
- const exitCode = config.exitCode || 1;
2798
- const code = config.code || "commander.error";
2799
- this._exit(exitCode, code, message);
2800
- }
2801
- /**
2802
- * Apply any option related environment variables, if option does
2803
- * not have a value from cli or client code.
2804
- *
2805
- * @private
2806
- */
2807
- _parseOptionsEnv() {
2808
- this.options.forEach((option) => {
2809
- if (option.envVar && option.envVar in process2.env) {
2810
- const optionKey = option.attributeName();
2811
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2812
- this.getOptionValueSource(optionKey)
2813
- )) {
2814
- if (option.required || option.optional) {
2815
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2816
- } else {
2817
- this.emit(`optionEnv:${option.name()}`);
2818
- }
2819
- }
2820
- }
2821
- });
2822
- }
2823
- /**
2824
- * Apply any implied option values, if option is undefined or default value.
2825
- *
2826
- * @private
2827
- */
2828
- _parseOptionsImplied() {
2829
- const dualHelper = new DualOptions(this.options);
2830
- const hasCustomOptionValue = (optionKey) => {
2831
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2832
- };
2833
- this.options.filter(
2834
- (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2835
- this.getOptionValue(option.attributeName()),
2836
- option
2837
- )
2838
- ).forEach((option) => {
2839
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2840
- this.setOptionValueWithSource(
2841
- impliedKey,
2842
- option.implied[impliedKey],
2843
- "implied"
2844
- );
2845
- });
2846
- });
2847
- }
2848
- /**
2849
- * Argument `name` is missing.
2850
- *
2851
- * @param {string} name
2852
- * @private
2853
- */
2854
- missingArgument(name) {
2855
- const message = `error: missing required argument '${name}'`;
2856
- this.error(message, { code: "commander.missingArgument" });
2857
- }
2858
- /**
2859
- * `Option` is missing an argument.
2860
- *
2861
- * @param {Option} option
2862
- * @private
2863
- */
2864
- optionMissingArgument(option) {
2865
- const message = `error: option '${option.flags}' argument missing`;
2866
- this.error(message, { code: "commander.optionMissingArgument" });
2867
- }
2868
- /**
2869
- * `Option` does not have a value, and is a mandatory option.
2870
- *
2871
- * @param {Option} option
2872
- * @private
2873
- */
2874
- missingMandatoryOptionValue(option) {
2875
- const message = `error: required option '${option.flags}' not specified`;
2876
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2877
- }
2878
- /**
2879
- * `Option` conflicts with another option.
2880
- *
2881
- * @param {Option} option
2882
- * @param {Option} conflictingOption
2883
- * @private
2884
- */
2885
- _conflictingOption(option, conflictingOption) {
2886
- const findBestOptionFromValue = (option2) => {
2887
- const optionKey = option2.attributeName();
2888
- const optionValue = this.getOptionValue(optionKey);
2889
- const negativeOption = this.options.find(
2890
- (target) => target.negate && optionKey === target.attributeName()
2891
- );
2892
- const positiveOption = this.options.find(
2893
- (target) => !target.negate && optionKey === target.attributeName()
2894
- );
2895
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2896
- return negativeOption;
2897
- }
2898
- return positiveOption || option2;
2899
- };
2900
- const getErrorMessage = (option2) => {
2901
- const bestOption = findBestOptionFromValue(option2);
2902
- const optionKey = bestOption.attributeName();
2903
- const source = this.getOptionValueSource(optionKey);
2904
- if (source === "env") {
2905
- return `environment variable '${bestOption.envVar}'`;
2906
- }
2907
- return `option '${bestOption.flags}'`;
2908
- };
2909
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2910
- this.error(message, { code: "commander.conflictingOption" });
2911
- }
2912
- /**
2913
- * Unknown option `flag`.
2914
- *
2915
- * @param {string} flag
2916
- * @private
2917
- */
2918
- unknownOption(flag) {
2919
- if (this._allowUnknownOption) return;
2920
- let suggestion = "";
2921
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2922
- let candidateFlags = [];
2923
- let command = this;
2924
- do {
2925
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2926
- candidateFlags = candidateFlags.concat(moreFlags);
2927
- command = command.parent;
2928
- } while (command && !command._enablePositionalOptions);
2929
- suggestion = suggestSimilar(flag, candidateFlags);
2930
- }
2931
- const message = `error: unknown option '${flag}'${suggestion}`;
2932
- this.error(message, { code: "commander.unknownOption" });
2933
- }
2934
- /**
2935
- * Excess arguments, more than expected.
2936
- *
2937
- * @param {string[]} receivedArgs
2938
- * @private
2939
- */
2940
- _excessArguments(receivedArgs) {
2941
- if (this._allowExcessArguments) return;
2942
- const expected = this.registeredArguments.length;
2943
- const s = expected === 1 ? "" : "s";
2944
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2945
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2946
- this.error(message, { code: "commander.excessArguments" });
2947
- }
2948
- /**
2949
- * Unknown command.
2950
- *
2951
- * @private
2952
- */
2953
- unknownCommand() {
2954
- const unknownName = this.args[0];
2955
- let suggestion = "";
2956
- if (this._showSuggestionAfterError) {
2957
- const candidateNames = [];
2958
- this.createHelp().visibleCommands(this).forEach((command) => {
2959
- candidateNames.push(command.name());
2960
- if (command.alias()) candidateNames.push(command.alias());
2961
- });
2962
- suggestion = suggestSimilar(unknownName, candidateNames);
2963
- }
2964
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2965
- this.error(message, { code: "commander.unknownCommand" });
2966
- }
2967
- /**
2968
- * Get or set the program version.
2969
- *
2970
- * This method auto-registers the "-V, --version" option which will print the version number.
2971
- *
2972
- * You can optionally supply the flags and description to override the defaults.
2973
- *
2974
- * @param {string} [str]
2975
- * @param {string} [flags]
2976
- * @param {string} [description]
2977
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2978
- */
2979
- version(str, flags, description) {
2980
- if (str === void 0) return this._version;
2981
- this._version = str;
2982
- flags = flags || "-V, --version";
2983
- description = description || "output the version number";
2984
- const versionOption = this.createOption(flags, description);
2985
- this._versionOptionName = versionOption.attributeName();
2986
- this._registerOption(versionOption);
2987
- this.on("option:" + versionOption.name(), () => {
2988
- this._outputConfiguration.writeOut(`${str}
2989
- `);
2990
- this._exit(0, "commander.version", str);
2991
- });
2992
- return this;
2993
- }
2994
- /**
2995
- * Set the description.
2996
- *
2997
- * @param {string} [str]
2998
- * @param {object} [argsDescription]
2999
- * @return {(string|Command)}
3000
- */
3001
- description(str, argsDescription) {
3002
- if (str === void 0 && argsDescription === void 0)
3003
- return this._description;
3004
- this._description = str;
3005
- if (argsDescription) {
3006
- this._argsDescription = argsDescription;
3007
- }
3008
- return this;
3009
- }
3010
- /**
3011
- * Set the summary. Used when listed as subcommand of parent.
3012
- *
3013
- * @param {string} [str]
3014
- * @return {(string|Command)}
3015
- */
3016
- summary(str) {
3017
- if (str === void 0) return this._summary;
3018
- this._summary = str;
3019
- return this;
3020
- }
3021
- /**
3022
- * Set an alias for the command.
3023
- *
3024
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3025
- *
3026
- * @param {string} [alias]
3027
- * @return {(string|Command)}
3028
- */
3029
- alias(alias) {
3030
- if (alias === void 0) return this._aliases[0];
3031
- let command = this;
3032
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3033
- command = this.commands[this.commands.length - 1];
3034
- }
3035
- if (alias === command._name)
3036
- throw new Error("Command alias can't be the same as its name");
3037
- const matchingCommand = this.parent?._findCommand(alias);
3038
- if (matchingCommand) {
3039
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3040
- throw new Error(
3041
- `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3042
- );
3043
- }
3044
- command._aliases.push(alias);
3045
- return this;
3046
- }
3047
- /**
3048
- * Set aliases for the command.
3049
- *
3050
- * Only the first alias is shown in the auto-generated help.
3051
- *
3052
- * @param {string[]} [aliases]
3053
- * @return {(string[]|Command)}
3054
- */
3055
- aliases(aliases) {
3056
- if (aliases === void 0) return this._aliases;
3057
- aliases.forEach((alias) => this.alias(alias));
3058
- return this;
3059
- }
3060
- /**
3061
- * Set / get the command usage `str`.
3062
- *
3063
- * @param {string} [str]
3064
- * @return {(string|Command)}
3065
- */
3066
- usage(str) {
3067
- if (str === void 0) {
3068
- if (this._usage) return this._usage;
3069
- const args = this.registeredArguments.map((arg) => {
3070
- return humanReadableArgName(arg);
3071
- });
3072
- return [].concat(
3073
- this.options.length || this._helpOption !== null ? "[options]" : [],
3074
- this.commands.length ? "[command]" : [],
3075
- this.registeredArguments.length ? args : []
3076
- ).join(" ");
3077
- }
3078
- this._usage = str;
3079
- return this;
3080
- }
3081
- /**
3082
- * Get or set the name of the command.
3083
- *
3084
- * @param {string} [str]
3085
- * @return {(string|Command)}
3086
- */
3087
- name(str) {
3088
- if (str === void 0) return this._name;
3089
- this._name = str;
3090
- return this;
3091
- }
3092
- /**
3093
- * Set/get the help group heading for this subcommand in parent command's help.
3094
- *
3095
- * @param {string} [heading]
3096
- * @return {Command | string}
3097
- */
3098
- helpGroup(heading) {
3099
- if (heading === void 0) return this._helpGroupHeading ?? "";
3100
- this._helpGroupHeading = heading;
3101
- return this;
3102
- }
3103
- /**
3104
- * Set/get the default help group heading for subcommands added to this command.
3105
- * (This does not override a group set directly on the subcommand using .helpGroup().)
3106
- *
3107
- * @example
3108
- * program.commandsGroup('Development Commands:);
3109
- * program.command('watch')...
3110
- * program.command('lint')...
3111
- * ...
3112
- *
3113
- * @param {string} [heading]
3114
- * @returns {Command | string}
3115
- */
3116
- commandsGroup(heading) {
3117
- if (heading === void 0) return this._defaultCommandGroup ?? "";
3118
- this._defaultCommandGroup = heading;
3119
- return this;
3120
- }
3121
- /**
3122
- * Set/get the default help group heading for options added to this command.
3123
- * (This does not override a group set directly on the option using .helpGroup().)
3124
- *
3125
- * @example
3126
- * program
3127
- * .optionsGroup('Development Options:')
3128
- * .option('-d, --debug', 'output extra debugging')
3129
- * .option('-p, --profile', 'output profiling information')
3130
- *
3131
- * @param {string} [heading]
3132
- * @returns {Command | string}
3133
- */
3134
- optionsGroup(heading) {
3135
- if (heading === void 0) return this._defaultOptionGroup ?? "";
3136
- this._defaultOptionGroup = heading;
3137
- return this;
3138
- }
3139
- /**
3140
- * @param {Option} option
3141
- * @private
3142
- */
3143
- _initOptionGroup(option) {
3144
- if (this._defaultOptionGroup && !option.helpGroupHeading)
3145
- option.helpGroup(this._defaultOptionGroup);
3146
- }
3147
- /**
3148
- * @param {Command} cmd
3149
- * @private
3150
- */
3151
- _initCommandGroup(cmd) {
3152
- if (this._defaultCommandGroup && !cmd.helpGroup())
3153
- cmd.helpGroup(this._defaultCommandGroup);
3154
- }
3155
- /**
3156
- * Set the name of the command from script filename, such as process.argv[1],
3157
- * or require.main.filename, or __filename.
3158
- *
3159
- * (Used internally and public although not documented in README.)
3160
- *
3161
- * @example
3162
- * program.nameFromFilename(require.main.filename);
3163
- *
3164
- * @param {string} filename
3165
- * @return {Command}
3166
- */
3167
- nameFromFilename(filename) {
3168
- this._name = path.basename(filename, path.extname(filename));
3169
- return this;
3170
- }
3171
- /**
3172
- * Get or set the directory for searching for executable subcommands of this command.
3173
- *
3174
- * @example
3175
- * program.executableDir(__dirname);
3176
- * // or
3177
- * program.executableDir('subcommands');
3178
- *
3179
- * @param {string} [path]
3180
- * @return {(string|null|Command)}
3181
- */
3182
- executableDir(path2) {
3183
- if (path2 === void 0) return this._executableDir;
3184
- this._executableDir = path2;
3185
- return this;
3186
- }
3187
- /**
3188
- * Return program help documentation.
3189
- *
3190
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3191
- * @return {string}
3192
- */
3193
- helpInformation(contextOptions) {
3194
- const helper = this.createHelp();
3195
- const context = this._getOutputContext(contextOptions);
3196
- helper.prepareContext({
3197
- error: context.error,
3198
- helpWidth: context.helpWidth,
3199
- outputHasColors: context.hasColors
3200
- });
3201
- const text = helper.formatHelp(this, helper);
3202
- if (context.hasColors) return text;
3203
- return this._outputConfiguration.stripColor(text);
3204
- }
3205
- /**
3206
- * @typedef HelpContext
3207
- * @type {object}
3208
- * @property {boolean} error
3209
- * @property {number} helpWidth
3210
- * @property {boolean} hasColors
3211
- * @property {function} write - includes stripColor if needed
3212
- *
3213
- * @returns {HelpContext}
3214
- * @private
3215
- */
3216
- _getOutputContext(contextOptions) {
3217
- contextOptions = contextOptions || {};
3218
- const error = !!contextOptions.error;
3219
- let baseWrite;
3220
- let hasColors;
3221
- let helpWidth;
3222
- if (error) {
3223
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
3224
- hasColors = this._outputConfiguration.getErrHasColors();
3225
- helpWidth = this._outputConfiguration.getErrHelpWidth();
3226
- } else {
3227
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3228
- hasColors = this._outputConfiguration.getOutHasColors();
3229
- helpWidth = this._outputConfiguration.getOutHelpWidth();
3230
- }
3231
- const write = (str) => {
3232
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3233
- return baseWrite(str);
3234
- };
3235
- return { error, write, hasColors, helpWidth };
3236
- }
3237
- /**
3238
- * Output help information for this command.
3239
- *
3240
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3241
- *
3242
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3243
- */
3244
- outputHelp(contextOptions) {
3245
- let deprecatedCallback;
3246
- if (typeof contextOptions === "function") {
3247
- deprecatedCallback = contextOptions;
3248
- contextOptions = void 0;
3249
- }
3250
- const outputContext = this._getOutputContext(contextOptions);
3251
- const eventContext = {
3252
- error: outputContext.error,
3253
- write: outputContext.write,
3254
- command: this
3255
- };
3256
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3257
- this.emit("beforeHelp", eventContext);
3258
- let helpInformation = this.helpInformation({ error: outputContext.error });
3259
- if (deprecatedCallback) {
3260
- helpInformation = deprecatedCallback(helpInformation);
3261
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3262
- throw new Error("outputHelp callback must return a string or a Buffer");
3263
- }
3264
- }
3265
- outputContext.write(helpInformation);
3266
- if (this._getHelpOption()?.long) {
3267
- this.emit(this._getHelpOption().long);
3268
- }
3269
- this.emit("afterHelp", eventContext);
3270
- this._getCommandAndAncestors().forEach(
3271
- (command) => command.emit("afterAllHelp", eventContext)
3272
- );
3273
- }
3274
- /**
3275
- * You can pass in flags and a description to customise the built-in help option.
3276
- * Pass in false to disable the built-in help option.
3277
- *
3278
- * @example
3279
- * program.helpOption('-?, --help' 'show help'); // customise
3280
- * program.helpOption(false); // disable
3281
- *
3282
- * @param {(string | boolean)} flags
3283
- * @param {string} [description]
3284
- * @return {Command} `this` command for chaining
3285
- */
3286
- helpOption(flags, description) {
3287
- if (typeof flags === "boolean") {
3288
- if (flags) {
3289
- if (this._helpOption === null) this._helpOption = void 0;
3290
- if (this._defaultOptionGroup) {
3291
- this._initOptionGroup(this._getHelpOption());
3292
- }
3293
- } else {
3294
- this._helpOption = null;
3295
- }
3296
- return this;
3297
- }
3298
- this._helpOption = this.createOption(
3299
- flags ?? "-h, --help",
3300
- description ?? "display help for command"
3301
- );
3302
- if (flags || description) this._initOptionGroup(this._helpOption);
3303
- return this;
3304
- }
3305
- /**
3306
- * Lazy create help option.
3307
- * Returns null if has been disabled with .helpOption(false).
3308
- *
3309
- * @returns {(Option | null)} the help option
3310
- * @package
3311
- */
3312
- _getHelpOption() {
3313
- if (this._helpOption === void 0) {
3314
- this.helpOption(void 0, void 0);
3315
- }
3316
- return this._helpOption;
3317
- }
3318
- /**
3319
- * Supply your own option to use for the built-in help option.
3320
- * This is an alternative to using helpOption() to customise the flags and description etc.
3321
- *
3322
- * @param {Option} option
3323
- * @return {Command} `this` command for chaining
3324
- */
3325
- addHelpOption(option) {
3326
- this._helpOption = option;
3327
- this._initOptionGroup(option);
3328
- return this;
3329
- }
3330
- /**
3331
- * Output help information and exit.
3332
- *
3333
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3334
- *
3335
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3336
- */
3337
- help(contextOptions) {
3338
- this.outputHelp(contextOptions);
3339
- let exitCode = Number(process2.exitCode ?? 0);
3340
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3341
- exitCode = 1;
3342
- }
3343
- this._exit(exitCode, "commander.help", "(outputHelp)");
3344
- }
3345
- /**
3346
- * // Do a little typing to coordinate emit and listener for the help text events.
3347
- * @typedef HelpTextEventContext
3348
- * @type {object}
3349
- * @property {boolean} error
3350
- * @property {Command} command
3351
- * @property {function} write
3352
- */
3353
- /**
3354
- * Add additional text to be displayed with the built-in help.
3355
- *
3356
- * Position is 'before' or 'after' to affect just this command,
3357
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3358
- *
3359
- * @param {string} position - before or after built-in help
3360
- * @param {(string | Function)} text - string to add, or a function returning a string
3361
- * @return {Command} `this` command for chaining
3362
- */
3363
- addHelpText(position, text) {
3364
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3365
- if (!allowedValues.includes(position)) {
3366
- throw new Error(`Unexpected value for position to addHelpText.
3367
- Expecting one of '${allowedValues.join("', '")}'`);
3368
- }
3369
- const helpEvent = `${position}Help`;
3370
- this.on(helpEvent, (context) => {
3371
- let helpStr;
3372
- if (typeof text === "function") {
3373
- helpStr = text({ error: context.error, command: context.command });
3374
- } else {
3375
- helpStr = text;
3376
- }
3377
- if (helpStr) {
3378
- context.write(`${helpStr}
3379
- `);
3380
- }
3381
- });
3382
- return this;
3383
- }
3384
- /**
3385
- * Output help information if help flags specified
3386
- *
3387
- * @param {Array} args - array of options to search for help flags
3388
- * @private
3389
- */
3390
- _outputHelpIfRequested(args) {
3391
- const helpOption = this._getHelpOption();
3392
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3393
- if (helpRequested) {
3394
- this.outputHelp();
3395
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3396
- }
3397
- }
3398
- };
3399
- function incrementNodeInspectorPort(args) {
3400
- return args.map((arg) => {
3401
- if (!arg.startsWith("--inspect")) {
3402
- return arg;
3403
- }
3404
- let debugOption;
3405
- let debugHost = "127.0.0.1";
3406
- let debugPort = "9229";
3407
- let match;
3408
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3409
- debugOption = match[1];
3410
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3411
- debugOption = match[1];
3412
- if (/^\d+$/.test(match[3])) {
3413
- debugPort = match[3];
3414
- } else {
3415
- debugHost = match[3];
3416
- }
3417
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3418
- debugOption = match[1];
3419
- debugHost = match[3];
3420
- debugPort = match[4];
3421
- }
3422
- if (debugOption && debugPort !== "0") {
3423
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3424
- }
3425
- return arg;
3426
- });
3427
- }
3428
- function useColor() {
3429
- if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3430
- return false;
3431
- if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3432
- return true;
3433
- return void 0;
3434
- }
3435
- exports.Command = Command2;
3436
- exports.useColor = useColor;
3437
- }
3438
- });
3439
-
3440
- // ../node_modules/commander/index.js
3441
- var require_commander = __commonJS({
3442
- "../node_modules/commander/index.js"(exports) {
3443
- var { Argument: Argument2 } = require_argument();
3444
- var { Command: Command2 } = require_command();
3445
- var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3446
- var { Help: Help2 } = require_help();
3447
- var { Option: Option2 } = require_option();
3448
- exports.program = new Command2();
3449
- exports.createCommand = (name) => new Command2(name);
3450
- exports.createOption = (flags, description) => new Option2(flags, description);
3451
- exports.createArgument = (name, description) => new Argument2(name, description);
3452
- exports.Command = Command2;
3453
- exports.Option = Option2;
3454
- exports.Argument = Argument2;
3455
- exports.Help = Help2;
3456
- exports.CommanderError = CommanderError2;
3457
- exports.InvalidArgumentError = InvalidArgumentError2;
3458
- exports.InvalidOptionArgumentError = InvalidArgumentError2;
3459
- }
3460
- });
3461
-
3462
- // ../node_modules/commander/esm.mjs
3463
- var import_index = __toESM(require_commander(), 1);
3464
- var {
3465
- program,
3466
- createCommand,
3467
- createArgument,
3468
- createOption,
3469
- CommanderError,
3470
- InvalidArgumentError,
3471
- InvalidOptionArgumentError,
3472
- // deprecated old name
3473
- Command,
3474
- Argument,
3475
- Option,
3476
- Help
3477
- } = import_index.default;
3478
-
3479
- // ../packages/cli/src/index.ts
3480
- import { readFileSync as readFileSync2 } from "fs";
3481
- import { resolve as resolve3 } from "path";
3482
-
3483
- // ../packages/cli/src/commands/generate/component/component.command.ts
3484
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
3485
- import { join } from "path";
3486
-
3487
- // ../packages/cli/src/utils/case.utils.ts
3488
- function toPascalCase(str) {
3489
- return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^(.)/, (_, c) => c.toUpperCase());
3490
- }
3491
- function toKebabCase(str) {
3492
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
3493
- }
3494
-
3495
- // ../packages/cli/src/commands/generate/component/component.command.ts
3496
- function generateComponent(name, path, force, style) {
3497
- const dir = join(path, name);
3498
- style ??= "css";
3499
- if (existsSync(dir)) {
3500
- if (force) {
3501
- console.log(`Deleting "${name}"...`);
3502
- rmSync(dir, { recursive: true, force: true });
3503
- console.log("\u2714 Component Deleted.");
3504
- } else {
3505
- console.error(`\u2716 Directory "${name}" already exists.`);
3506
- process.exit(1);
3507
- }
3508
- }
3509
- mkdirSync(dir, { recursive: true });
3510
- const files = [
3511
- [`${name}.xd.component.ts`, tsTemplate(name, style)],
3512
- [`${name}.xd.component.html`, htmlTemplate(name)],
3513
- [`${name}.xd.component.${style}`, cssTemplate(name)],
3514
- [`${name}.xd.component.spec.ts`, specTemplate(name)]
3515
- ];
3516
- for (const [filename, content] of files) {
3517
- writeFileSync(join(dir, filename), content, "utf8");
3518
- }
3519
- console.log();
3520
- console.log(`\u2714 Component "${name}" generated:`);
3521
- for (const [filename] of files) {
3522
- console.log(`${name}/${filename}`);
3523
- }
3524
- }
3525
- function tsTemplate(name, style) {
3526
- const className = toPascalCase(name);
3527
- return `import { BaseWebComponent, WebComponent } from '@xaendar/core';
3528
-
3529
- @WebComponent({
3530
- selector: '${toKebabCase(name)}',
3531
- styleUrl: './${name}.xd.component.${style}',
3532
- templateUrl: './${name}.xd.component.html'
3533
- })
3534
- export class ${className}Component extends BaseWebComponent {
3535
-
3536
- }`;
3537
- }
3538
- function htmlTemplate(name) {
3539
- return `<p>${name} works!</p>
3540
- `;
3541
- }
3542
- function cssTemplate(_name) {
3543
- return `/* component styles */
3544
- `;
3545
- }
3546
- function specTemplate(name) {
3547
- const className = toPascalCase(name);
3548
- return `import { describe, expect, it } from "vitest";
3549
- import { ${className}Component } from './${name}.xd.component';
3550
-
3551
- describe('${className}Component', () => {
3552
- it('should create', () => {
3553
- const component = new ${className}Component();
3554
- expect(component).toBeTruthy();
3555
- });
3556
- });
3557
- `;
3558
- }
3559
-
3560
- // ../packages/cli/src/commands/generate/generate.command.ts
3561
- function generateCommand() {
3562
- const generate = new Command("generate").alias("g").description("Generate Xaendar building blocks");
3563
- generate.command("component <name>").alias("c").option("-p, --path <path>", "Custom path for the generated component (default: current directory)").option("-f, --force", "Force generation deleting current component if already exists").description("Generate a new component (creates <name>/ folder with .ts, .html, .css, .spec.ts)").action((name, options) => {
3564
- const path = options.path || process.cwd();
3565
- generateComponent(name, path, !!options.force);
3566
- });
3567
- return generate;
3568
- }
3569
-
3570
- // ../packages/cli/src/commands/new/new.command.ts
3571
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, writeFileSync as writeFileSync2 } from "fs";
3572
- import { resolve as resolve2 } from "path/win32";
3573
-
3574
- // ../packages/cli/src/commands/new/structure.ts
3575
- import { readFileSync } from "fs";
3576
- import { resolve } from "path";
3577
-
3578
- // ../packages/cli/src/commands/new/templates/index-html.ts
3579
- function indexHtml(name) {
3580
- return `<!DOCTYPE html>
3581
- <html lang="en">
3582
- <head>
3583
- <meta charset="UTF-8" />
3584
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
3585
- <title>${name}</title>
3586
- <script type="module" src="./signals.ts"></script>
3587
- <script type="module" src="./main.ts"></script>
3588
- </head>
3589
- <body>
3590
- <${name}></${name}>
3591
- </body>
3592
- </html>`;
3593
- }
3594
-
3595
- // ../packages/cli/src/commands/new/templates/main-ts.ts
3596
- function mainTs(componentName) {
3597
- const componentClassName = `${toPascalCase(componentName)}Component`;
3598
- return `import { ${componentClassName} } from './${componentName}/${componentName}.xd.component';
3599
-
3600
- console.log(${componentClassName});`;
3601
- }
3602
-
3603
- // ../packages/cli/src/commands/new/templates/package-json.ts
3604
- function packageJson(name, version2) {
3605
- return `{
3606
- "name": "${name}",
3607
- "version": "0.0.1",
3608
- "private": true,
3609
- "scripts": {
3610
- "build": "vite build",
3611
- "start": "vite",
3612
- "test": "vitest",
3613
- "xd": "xd"
3614
- },
3615
- "dependencies": {
3616
- "@xaendar/core": "^${version2}",
3617
- "@xaendar/signals": "^${version2}",
3618
- "@xaendar/types": "^${version2}"
3619
- },
3620
- "devDependencies": {
3621
- "@babel/plugin-proposal-decorators": "^7.29.0",
3622
- "@rolldown/plugin-babel": "^0.2.3",
3623
- "@vitest/coverage-v8": "^4.1.7",
3624
- "@xaendar/build-tools": "^${version2}",
3625
- "@xaendar/cli": "^${version2}",
3626
- "typescript": "^6.0.3",
3627
- "vite": "^8.0.14",
3628
- "vitest": "^4.1.7"
3629
- }
3630
- }
3631
- `;
3632
- }
3633
-
3634
- // ../packages/cli/src/commands/new/templates/signal-ts.ts
3635
- function signalTs() {
3636
- return `import { loadSignals } from "@xaendar/signals";
3637
-
3638
- loadSignals();`;
3639
- }
3640
-
3641
- // ../packages/cli/src/commands/new/templates/tsconfig-json.ts
3642
- function tsconfigJson() {
3643
- return `{
3644
- "compilerOptions": {
3645
- "target": "ESNext",
3646
- "module": "ESNext",
3647
- "moduleResolution": "bundler",
3648
- "lib": [
3649
- "ESNext",
3650
- "DOM"
3651
- ],
3652
- "outDir": "./dist",
3653
- "rootDir": "./src",
3654
- "declaration": true,
3655
- "declarationMap": true,
3656
- "sourceMap": true,
3657
- "isolatedModules": true,
3658
- "moduleDetection": "force",
3659
- "noUncheckedIndexedAccess": true,
3660
- "noEmit": true,
3661
- "skipLibCheck": true,
3662
- "paths": {
3663
- "@/*": ["./src/*"]
3664
- }
3665
- },
3666
- "include": ["src/**/*.ts"],
3667
- "exclude": [
3668
- "dist",
3669
- "node_modules",
3670
- "**/*.spec.ts"
3671
- ]
3672
- }`;
3673
- }
3674
-
3675
- // ../packages/cli/src/commands/new/templates/vite-config-ts.ts
3676
- function viteConfigTs() {
3677
- return `import babel from "@rolldown/plugin-babel";
3678
- import { xaendarPlugin } from "@xaendar/build-tools";
3679
- import { defineConfig } from 'vite';
3680
-
3681
- export default defineConfig({
3682
- root: 'src',
3683
- server: {
3684
- open: true,
3685
- port: 4200
3686
- },
3687
- plugins: [
3688
- babel({
3689
- presets: [
3690
- {
3691
- preset: () => ({
3692
- plugins: [
3693
- [
3694
- "@babel/plugin-proposal-decorators",
3695
- { version: "2023-11" }
3696
- ]
3697
- ]
3698
- }),
3699
- rolldown: {
3700
- filter: {
3701
- code: "@"
3702
- }
3703
- }
3704
- }
3705
- ]
3706
- }),
3707
- xaendarPlugin()
3708
- ]
3709
- });`;
3710
- }
3711
-
3712
- // ../packages/cli/src/commands/new/templates/xaendar-json.ts
3713
- function xaendarJson(name, style) {
3714
- return `{
3715
- "name": "${name}",
3716
- "entry": "src/main.ts",
3717
- "outDir": "dist",
3718
- "assetsDir": "assets",
3719
- "generate": {
3720
- "components": {
3721
- "style": "${style}"
3722
- }
3723
- }
3724
- }`;
3725
- }
3726
-
3727
- // ../packages/cli/src/commands/new/structure.ts
3728
- function readCliVersion() {
3729
- try {
3730
- const cliPackageJson = JSON.parse(readFileSync(resolve(import.meta.filename, "..", "./package.json"), "utf8"));
3731
- if (!cliPackageJson.version) {
3732
- throw new Error("Unable to determine Xaendar CLI version.");
3733
- }
3734
- return cliPackageJson.version;
3735
- } catch (error) {
3736
- console.error("Error reading Xaendar CLI version:", error);
3737
- process.exit(1);
3738
- }
3739
- }
3740
- function buildStructure(context) {
3741
- const version2 = readCliVersion();
3742
- const name = context.name;
3743
- const componentName = `${name}-root`;
3744
- return [
3745
- {
3746
- type: "file",
3747
- name: "package.json",
3748
- content: packageJson(name, version2)
3749
- },
3750
- {
3751
- type: "file",
3752
- name: "xaendar.json",
3753
- content: xaendarJson(name, context.style)
3754
- },
3755
- {
3756
- type: "file",
3757
- name: "vite.config.ts",
3758
- content: viteConfigTs()
3759
- },
3760
- {
3761
- type: "file",
3762
- name: "tsconfig.json",
3763
- content: tsconfigJson()
3764
- },
3765
- {
3766
- type: "directory",
3767
- name: "src",
3768
- children: [
3769
- {
3770
- type: "file",
3771
- name: "index.html",
3772
- content: indexHtml(componentName)
3773
- },
3774
- {
3775
- type: "file",
3776
- name: "signals.ts",
3777
- content: signalTs()
3778
- },
3779
- {
3780
- type: "file",
3781
- name: "main.ts",
3782
- content: mainTs(componentName)
3783
- },
3784
- {
3785
- type: "generateComponent",
3786
- name: componentName
3787
- }
3788
- ]
3789
- }
3790
- ];
3791
- }
3792
-
3793
- // ../packages/cli/src/commands/new/new.command.ts
3794
- import { execSync } from "child_process";
3795
- function newCommand() {
3796
- return new Command("new").description("Scaffold a new Xaendar project").argument("<name>", "Name of the project to create").option("-p, --path <path>", "Custom path for the generated project (default: current directory)").option("-s, --style <style>", "CSS preprocessor to use (css, scss, less, styl)", "css").action((name, options) => {
3797
- const style = resolveStyleOptions(options.style);
3798
- const workingDirectory = options.path || process.cwd();
3799
- const projectDirectory = resolve2(workingDirectory, name);
3800
- checkAndCreateProjectDirectory(projectDirectory);
3801
- createFiles(buildStructure({ name, style }), projectDirectory, style);
3802
- execSync("npm i", { stdio: "inherit", cwd: projectDirectory });
3803
- });
3804
- }
3805
- function resolveStyleOptions(style) {
3806
- const validStyles = ["css", "scss", "less", "styl"];
3807
- if (!style) {
3808
- return "css";
3809
- }
3810
- if (!validStyles.includes(style)) {
3811
- console.error(`\u2716 Invalid style option: ${style}`);
3812
- process.exit(1);
3813
- }
3814
- return style;
3815
- }
3816
- function checkAndCreateProjectDirectory(path) {
3817
- const exists = existsSync2(path);
3818
- if (exists && readdirSync(path).length) {
3819
- console.error(`\u2716 Cannot create project: target directory is not empty: ${path}`);
3820
- process.exit(1);
3821
- }
3822
- if (!exists) {
3823
- mkdirSync2(path);
3824
- }
3825
- }
3826
- function createFiles(entries, basePath, style) {
3827
- entries.forEach((entry) => {
3828
- switch (entry.type) {
3829
- case "file":
3830
- case void 0:
3831
- const content = entry.content;
3832
- writeFileSync2(resolve2(basePath, entry.name), content, "utf8");
3833
- break;
3834
- case "directory":
3835
- const dirPath = resolve2(basePath, entry.name);
3836
- mkdirSync2(dirPath);
3837
- if (entry.children) {
3838
- createFiles(entry.children, dirPath, style);
3839
- }
3840
- break;
3841
- case "generateComponent":
3842
- generateComponent(entry.name, basePath, false, style);
3843
- break;
3844
- }
3845
- });
3846
- }
3847
-
3848
- // ../packages/cli/src/index.ts
3849
- var version = JSON.parse(readFileSync2(resolve3(import.meta.filename, "..", "package.json"), "utf-8")).version;
3850
- program.name("xd").description("Xaendar CLI").version(version);
3851
- program.addCommand(generateCommand());
3852
- program.addCommand(newCommand());
3853
- program.parse();
3854
- //# sourceMappingURL=index.js.map