@grantjs/cli 1.0.0

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