@frontstackdev/cli 0.0.0-canary-20240830084126

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