decision-memory 0.1.3 → 0.1.4

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.js DELETED
@@ -1,3159 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- __commonJS,
4
- __require,
5
- __toESM,
6
- appendDecision,
7
- formatContextSummaryAsToon,
8
- initDecisionFile,
9
- parseDecisionFile,
10
- resolveDecisionFilePath,
11
- searchDecisions,
12
- serializeDecisionRow
13
- } from "./chunk-5VFZ3YOK.js";
14
-
15
- // node_modules/commander/lib/error.js
16
- var require_error = __commonJS({
17
- "node_modules/commander/lib/error.js"(exports) {
18
- var CommanderError2 = class extends Error {
19
- /**
20
- * Constructs the CommanderError class
21
- * @param {number} exitCode suggested exit code which could be used with process.exit
22
- * @param {string} code an id string representing the error
23
- * @param {string} message human-readable description of the error
24
- */
25
- constructor(exitCode, code, message) {
26
- super(message);
27
- Error.captureStackTrace(this, this.constructor);
28
- this.name = this.constructor.name;
29
- this.code = code;
30
- this.exitCode = exitCode;
31
- this.nestedError = void 0;
32
- }
33
- };
34
- var InvalidArgumentError2 = class extends CommanderError2 {
35
- /**
36
- * Constructs the InvalidArgumentError class
37
- * @param {string} [message] explanation of why argument is invalid
38
- */
39
- constructor(message) {
40
- super(1, "commander.invalidArgument", message);
41
- Error.captureStackTrace(this, this.constructor);
42
- this.name = this.constructor.name;
43
- }
44
- };
45
- exports.CommanderError = CommanderError2;
46
- exports.InvalidArgumentError = InvalidArgumentError2;
47
- }
48
- });
49
-
50
- // node_modules/commander/lib/argument.js
51
- var require_argument = __commonJS({
52
- "node_modules/commander/lib/argument.js"(exports) {
53
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
54
- var Argument2 = class {
55
- /**
56
- * Initialize a new command argument with the given name and description.
57
- * The default is that the argument is required, and you can explicitly
58
- * indicate this with <> around the name. Put [] around the name for an optional argument.
59
- *
60
- * @param {string} name
61
- * @param {string} [description]
62
- */
63
- constructor(name, description) {
64
- this.description = description || "";
65
- this.variadic = false;
66
- this.parseArg = void 0;
67
- this.defaultValue = void 0;
68
- this.defaultValueDescription = void 0;
69
- this.argChoices = void 0;
70
- switch (name[0]) {
71
- case "<":
72
- this.required = true;
73
- this._name = name.slice(1, -1);
74
- break;
75
- case "[":
76
- this.required = false;
77
- this._name = name.slice(1, -1);
78
- break;
79
- default:
80
- this.required = true;
81
- this._name = name;
82
- break;
83
- }
84
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
85
- this.variadic = true;
86
- this._name = this._name.slice(0, -3);
87
- }
88
- }
89
- /**
90
- * Return argument name.
91
- *
92
- * @return {string}
93
- */
94
- name() {
95
- return this._name;
96
- }
97
- /**
98
- * @package
99
- */
100
- _concatValue(value, previous) {
101
- if (previous === this.defaultValue || !Array.isArray(previous)) {
102
- return [value];
103
- }
104
- return previous.concat(value);
105
- }
106
- /**
107
- * Set the default value, and optionally supply the description to be displayed in the help.
108
- *
109
- * @param {*} value
110
- * @param {string} [description]
111
- * @return {Argument}
112
- */
113
- default(value, description) {
114
- this.defaultValue = value;
115
- this.defaultValueDescription = description;
116
- return this;
117
- }
118
- /**
119
- * Set the custom handler for processing CLI command arguments into argument values.
120
- *
121
- * @param {Function} [fn]
122
- * @return {Argument}
123
- */
124
- argParser(fn) {
125
- this.parseArg = fn;
126
- return this;
127
- }
128
- /**
129
- * Only allow argument value to be one of choices.
130
- *
131
- * @param {string[]} values
132
- * @return {Argument}
133
- */
134
- choices(values) {
135
- this.argChoices = values.slice();
136
- this.parseArg = (arg, previous) => {
137
- if (!this.argChoices.includes(arg)) {
138
- throw new InvalidArgumentError2(
139
- `Allowed choices are ${this.argChoices.join(", ")}.`
140
- );
141
- }
142
- if (this.variadic) {
143
- return this._concatValue(arg, previous);
144
- }
145
- return arg;
146
- };
147
- return this;
148
- }
149
- /**
150
- * Make argument required.
151
- *
152
- * @returns {Argument}
153
- */
154
- argRequired() {
155
- this.required = true;
156
- return this;
157
- }
158
- /**
159
- * Make argument optional.
160
- *
161
- * @returns {Argument}
162
- */
163
- argOptional() {
164
- this.required = false;
165
- return this;
166
- }
167
- };
168
- function humanReadableArgName(arg) {
169
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
170
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
171
- }
172
- exports.Argument = Argument2;
173
- exports.humanReadableArgName = humanReadableArgName;
174
- }
175
- });
176
-
177
- // node_modules/commander/lib/help.js
178
- var require_help = __commonJS({
179
- "node_modules/commander/lib/help.js"(exports) {
180
- var { humanReadableArgName } = require_argument();
181
- var Help2 = class {
182
- constructor() {
183
- this.helpWidth = void 0;
184
- this.sortSubcommands = false;
185
- this.sortOptions = false;
186
- this.showGlobalOptions = false;
187
- }
188
- /**
189
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
190
- *
191
- * @param {Command} cmd
192
- * @returns {Command[]}
193
- */
194
- visibleCommands(cmd) {
195
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
196
- const helpCommand = cmd._getHelpCommand();
197
- if (helpCommand && !helpCommand._hidden) {
198
- visibleCommands.push(helpCommand);
199
- }
200
- if (this.sortSubcommands) {
201
- visibleCommands.sort((a, b) => {
202
- return a.name().localeCompare(b.name());
203
- });
204
- }
205
- return visibleCommands;
206
- }
207
- /**
208
- * Compare options for sort.
209
- *
210
- * @param {Option} a
211
- * @param {Option} b
212
- * @returns {number}
213
- */
214
- compareOptions(a, b) {
215
- const getSortKey = (option) => {
216
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
217
- };
218
- return getSortKey(a).localeCompare(getSortKey(b));
219
- }
220
- /**
221
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
222
- *
223
- * @param {Command} cmd
224
- * @returns {Option[]}
225
- */
226
- visibleOptions(cmd) {
227
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
228
- const helpOption = cmd._getHelpOption();
229
- if (helpOption && !helpOption.hidden) {
230
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
231
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
232
- if (!removeShort && !removeLong) {
233
- visibleOptions.push(helpOption);
234
- } else if (helpOption.long && !removeLong) {
235
- visibleOptions.push(
236
- cmd.createOption(helpOption.long, helpOption.description)
237
- );
238
- } else if (helpOption.short && !removeShort) {
239
- visibleOptions.push(
240
- cmd.createOption(helpOption.short, helpOption.description)
241
- );
242
- }
243
- }
244
- if (this.sortOptions) {
245
- visibleOptions.sort(this.compareOptions);
246
- }
247
- return visibleOptions;
248
- }
249
- /**
250
- * Get an array of the visible global options. (Not including help.)
251
- *
252
- * @param {Command} cmd
253
- * @returns {Option[]}
254
- */
255
- visibleGlobalOptions(cmd) {
256
- if (!this.showGlobalOptions) return [];
257
- const globalOptions = [];
258
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
259
- const visibleOptions = ancestorCmd.options.filter(
260
- (option) => !option.hidden
261
- );
262
- globalOptions.push(...visibleOptions);
263
- }
264
- if (this.sortOptions) {
265
- globalOptions.sort(this.compareOptions);
266
- }
267
- return globalOptions;
268
- }
269
- /**
270
- * Get an array of the arguments if any have a description.
271
- *
272
- * @param {Command} cmd
273
- * @returns {Argument[]}
274
- */
275
- visibleArguments(cmd) {
276
- if (cmd._argsDescription) {
277
- cmd.registeredArguments.forEach((argument) => {
278
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
279
- });
280
- }
281
- if (cmd.registeredArguments.find((argument) => argument.description)) {
282
- return cmd.registeredArguments;
283
- }
284
- return [];
285
- }
286
- /**
287
- * Get the command term to show in the list of subcommands.
288
- *
289
- * @param {Command} cmd
290
- * @returns {string}
291
- */
292
- subcommandTerm(cmd) {
293
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
294
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
295
- (args ? " " + args : "");
296
- }
297
- /**
298
- * Get the option term to show in the list of options.
299
- *
300
- * @param {Option} option
301
- * @returns {string}
302
- */
303
- optionTerm(option) {
304
- return option.flags;
305
- }
306
- /**
307
- * Get the argument term to show in the list of arguments.
308
- *
309
- * @param {Argument} argument
310
- * @returns {string}
311
- */
312
- argumentTerm(argument) {
313
- return argument.name();
314
- }
315
- /**
316
- * Get the longest command term length.
317
- *
318
- * @param {Command} cmd
319
- * @param {Help} helper
320
- * @returns {number}
321
- */
322
- longestSubcommandTermLength(cmd, helper) {
323
- return helper.visibleCommands(cmd).reduce((max, command) => {
324
- return Math.max(max, helper.subcommandTerm(command).length);
325
- }, 0);
326
- }
327
- /**
328
- * Get the longest option term length.
329
- *
330
- * @param {Command} cmd
331
- * @param {Help} helper
332
- * @returns {number}
333
- */
334
- longestOptionTermLength(cmd, helper) {
335
- return helper.visibleOptions(cmd).reduce((max, option) => {
336
- return Math.max(max, helper.optionTerm(option).length);
337
- }, 0);
338
- }
339
- /**
340
- * Get the longest global option term length.
341
- *
342
- * @param {Command} cmd
343
- * @param {Help} helper
344
- * @returns {number}
345
- */
346
- longestGlobalOptionTermLength(cmd, helper) {
347
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
348
- return Math.max(max, helper.optionTerm(option).length);
349
- }, 0);
350
- }
351
- /**
352
- * Get the longest argument term length.
353
- *
354
- * @param {Command} cmd
355
- * @param {Help} helper
356
- * @returns {number}
357
- */
358
- longestArgumentTermLength(cmd, helper) {
359
- return helper.visibleArguments(cmd).reduce((max, argument) => {
360
- return Math.max(max, helper.argumentTerm(argument).length);
361
- }, 0);
362
- }
363
- /**
364
- * Get the command usage to be displayed at the top of the built-in help.
365
- *
366
- * @param {Command} cmd
367
- * @returns {string}
368
- */
369
- commandUsage(cmd) {
370
- let cmdName = cmd._name;
371
- if (cmd._aliases[0]) {
372
- cmdName = cmdName + "|" + cmd._aliases[0];
373
- }
374
- let ancestorCmdNames = "";
375
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
376
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
377
- }
378
- return ancestorCmdNames + cmdName + " " + cmd.usage();
379
- }
380
- /**
381
- * Get the description for the command.
382
- *
383
- * @param {Command} cmd
384
- * @returns {string}
385
- */
386
- commandDescription(cmd) {
387
- return cmd.description();
388
- }
389
- /**
390
- * Get the subcommand summary to show in the list of subcommands.
391
- * (Fallback to description for backwards compatibility.)
392
- *
393
- * @param {Command} cmd
394
- * @returns {string}
395
- */
396
- subcommandDescription(cmd) {
397
- return cmd.summary() || cmd.description();
398
- }
399
- /**
400
- * Get the option description to show in the list of options.
401
- *
402
- * @param {Option} option
403
- * @return {string}
404
- */
405
- optionDescription(option) {
406
- const extraInfo = [];
407
- if (option.argChoices) {
408
- extraInfo.push(
409
- // use stringify to match the display of the default value
410
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
411
- );
412
- }
413
- if (option.defaultValue !== void 0) {
414
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
415
- if (showDefault) {
416
- extraInfo.push(
417
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
418
- );
419
- }
420
- }
421
- if (option.presetArg !== void 0 && option.optional) {
422
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
423
- }
424
- if (option.envVar !== void 0) {
425
- extraInfo.push(`env: ${option.envVar}`);
426
- }
427
- if (extraInfo.length > 0) {
428
- return `${option.description} (${extraInfo.join(", ")})`;
429
- }
430
- return option.description;
431
- }
432
- /**
433
- * Get the argument description to show in the list of arguments.
434
- *
435
- * @param {Argument} argument
436
- * @return {string}
437
- */
438
- argumentDescription(argument) {
439
- const extraInfo = [];
440
- if (argument.argChoices) {
441
- extraInfo.push(
442
- // use stringify to match the display of the default value
443
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
444
- );
445
- }
446
- if (argument.defaultValue !== void 0) {
447
- extraInfo.push(
448
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
449
- );
450
- }
451
- if (extraInfo.length > 0) {
452
- const extraDescripton = `(${extraInfo.join(", ")})`;
453
- if (argument.description) {
454
- return `${argument.description} ${extraDescripton}`;
455
- }
456
- return extraDescripton;
457
- }
458
- return argument.description;
459
- }
460
- /**
461
- * Generate the built-in help text.
462
- *
463
- * @param {Command} cmd
464
- * @param {Help} helper
465
- * @returns {string}
466
- */
467
- formatHelp(cmd, helper) {
468
- const termWidth = helper.padWidth(cmd, helper);
469
- const helpWidth = helper.helpWidth || 80;
470
- const itemIndentWidth = 2;
471
- const itemSeparatorWidth = 2;
472
- function formatItem(term, description) {
473
- if (description) {
474
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
475
- return helper.wrap(
476
- fullText,
477
- helpWidth - itemIndentWidth,
478
- termWidth + itemSeparatorWidth
479
- );
480
- }
481
- return term;
482
- }
483
- function formatList(textArray) {
484
- return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
485
- }
486
- let output2 = [`Usage: ${helper.commandUsage(cmd)}`, ""];
487
- const commandDescription = helper.commandDescription(cmd);
488
- if (commandDescription.length > 0) {
489
- output2 = output2.concat([
490
- helper.wrap(commandDescription, helpWidth, 0),
491
- ""
492
- ]);
493
- }
494
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
495
- return formatItem(
496
- helper.argumentTerm(argument),
497
- helper.argumentDescription(argument)
498
- );
499
- });
500
- if (argumentList.length > 0) {
501
- output2 = output2.concat(["Arguments:", formatList(argumentList), ""]);
502
- }
503
- const optionList = helper.visibleOptions(cmd).map((option) => {
504
- return formatItem(
505
- helper.optionTerm(option),
506
- helper.optionDescription(option)
507
- );
508
- });
509
- if (optionList.length > 0) {
510
- output2 = output2.concat(["Options:", formatList(optionList), ""]);
511
- }
512
- if (this.showGlobalOptions) {
513
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
514
- return formatItem(
515
- helper.optionTerm(option),
516
- helper.optionDescription(option)
517
- );
518
- });
519
- if (globalOptionList.length > 0) {
520
- output2 = output2.concat([
521
- "Global Options:",
522
- formatList(globalOptionList),
523
- ""
524
- ]);
525
- }
526
- }
527
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
528
- return formatItem(
529
- helper.subcommandTerm(cmd2),
530
- helper.subcommandDescription(cmd2)
531
- );
532
- });
533
- if (commandList.length > 0) {
534
- output2 = output2.concat(["Commands:", formatList(commandList), ""]);
535
- }
536
- return output2.join("\n");
537
- }
538
- /**
539
- * Calculate the pad width from the maximum term length.
540
- *
541
- * @param {Command} cmd
542
- * @param {Help} helper
543
- * @returns {number}
544
- */
545
- padWidth(cmd, helper) {
546
- return Math.max(
547
- helper.longestOptionTermLength(cmd, helper),
548
- helper.longestGlobalOptionTermLength(cmd, helper),
549
- helper.longestSubcommandTermLength(cmd, helper),
550
- helper.longestArgumentTermLength(cmd, helper)
551
- );
552
- }
553
- /**
554
- * Wrap the given string to width characters per line, with lines after the first indented.
555
- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
556
- *
557
- * @param {string} str
558
- * @param {number} width
559
- * @param {number} indent
560
- * @param {number} [minColumnWidth=40]
561
- * @return {string}
562
- *
563
- */
564
- wrap(str, width, indent, minColumnWidth = 40) {
565
- const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
566
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
567
- if (str.match(manualIndent)) return str;
568
- const columnWidth = width - indent;
569
- if (columnWidth < minColumnWidth) return str;
570
- const leadingStr = str.slice(0, indent);
571
- const columnText = str.slice(indent).replace("\r\n", "\n");
572
- const indentString = " ".repeat(indent);
573
- const zeroWidthSpace = "\u200B";
574
- const breaks = `\\s${zeroWidthSpace}`;
575
- const regex = new RegExp(
576
- `
577
- |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
578
- "g"
579
- );
580
- const lines = columnText.match(regex) || [];
581
- return leadingStr + lines.map((line, i) => {
582
- if (line === "\n") return "";
583
- return (i > 0 ? indentString : "") + line.trimEnd();
584
- }).join("\n");
585
- }
586
- };
587
- exports.Help = Help2;
588
- }
589
- });
590
-
591
- // node_modules/commander/lib/option.js
592
- var require_option = __commonJS({
593
- "node_modules/commander/lib/option.js"(exports) {
594
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
595
- var Option2 = class {
596
- /**
597
- * Initialize a new `Option` with the given `flags` and `description`.
598
- *
599
- * @param {string} flags
600
- * @param {string} [description]
601
- */
602
- constructor(flags, description) {
603
- this.flags = flags;
604
- this.description = description || "";
605
- this.required = flags.includes("<");
606
- this.optional = flags.includes("[");
607
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
608
- this.mandatory = false;
609
- const optionFlags = splitOptionFlags(flags);
610
- this.short = optionFlags.shortFlag;
611
- this.long = optionFlags.longFlag;
612
- this.negate = false;
613
- if (this.long) {
614
- this.negate = this.long.startsWith("--no-");
615
- }
616
- this.defaultValue = void 0;
617
- this.defaultValueDescription = void 0;
618
- this.presetArg = void 0;
619
- this.envVar = void 0;
620
- this.parseArg = void 0;
621
- this.hidden = false;
622
- this.argChoices = void 0;
623
- this.conflictsWith = [];
624
- this.implied = void 0;
625
- }
626
- /**
627
- * Set the default value, and optionally supply the description to be displayed in the help.
628
- *
629
- * @param {*} value
630
- * @param {string} [description]
631
- * @return {Option}
632
- */
633
- default(value, description) {
634
- this.defaultValue = value;
635
- this.defaultValueDescription = description;
636
- return this;
637
- }
638
- /**
639
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
640
- * The custom processing (parseArg) is called.
641
- *
642
- * @example
643
- * new Option('--color').default('GREYSCALE').preset('RGB');
644
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
645
- *
646
- * @param {*} arg
647
- * @return {Option}
648
- */
649
- preset(arg) {
650
- this.presetArg = arg;
651
- return this;
652
- }
653
- /**
654
- * Add option name(s) that conflict with this option.
655
- * An error will be displayed if conflicting options are found during parsing.
656
- *
657
- * @example
658
- * new Option('--rgb').conflicts('cmyk');
659
- * new Option('--js').conflicts(['ts', 'jsx']);
660
- *
661
- * @param {(string | string[])} names
662
- * @return {Option}
663
- */
664
- conflicts(names) {
665
- this.conflictsWith = this.conflictsWith.concat(names);
666
- return this;
667
- }
668
- /**
669
- * Specify implied option values for when this option is set and the implied options are not.
670
- *
671
- * The custom processing (parseArg) is not called on the implied values.
672
- *
673
- * @example
674
- * program
675
- * .addOption(new Option('--log', 'write logging information to file'))
676
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
677
- *
678
- * @param {object} impliedOptionValues
679
- * @return {Option}
680
- */
681
- implies(impliedOptionValues) {
682
- let newImplied = impliedOptionValues;
683
- if (typeof impliedOptionValues === "string") {
684
- newImplied = { [impliedOptionValues]: true };
685
- }
686
- this.implied = Object.assign(this.implied || {}, newImplied);
687
- return this;
688
- }
689
- /**
690
- * Set environment variable to check for option value.
691
- *
692
- * An environment variable is only used if when processed the current option value is
693
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
694
- *
695
- * @param {string} name
696
- * @return {Option}
697
- */
698
- env(name) {
699
- this.envVar = name;
700
- return this;
701
- }
702
- /**
703
- * Set the custom handler for processing CLI option arguments into option values.
704
- *
705
- * @param {Function} [fn]
706
- * @return {Option}
707
- */
708
- argParser(fn) {
709
- this.parseArg = fn;
710
- return this;
711
- }
712
- /**
713
- * Whether the option is mandatory and must have a value after parsing.
714
- *
715
- * @param {boolean} [mandatory=true]
716
- * @return {Option}
717
- */
718
- makeOptionMandatory(mandatory = true) {
719
- this.mandatory = !!mandatory;
720
- return this;
721
- }
722
- /**
723
- * Hide option in help.
724
- *
725
- * @param {boolean} [hide=true]
726
- * @return {Option}
727
- */
728
- hideHelp(hide = true) {
729
- this.hidden = !!hide;
730
- return this;
731
- }
732
- /**
733
- * @package
734
- */
735
- _concatValue(value, previous) {
736
- if (previous === this.defaultValue || !Array.isArray(previous)) {
737
- return [value];
738
- }
739
- return previous.concat(value);
740
- }
741
- /**
742
- * Only allow option value to be one of choices.
743
- *
744
- * @param {string[]} values
745
- * @return {Option}
746
- */
747
- choices(values) {
748
- this.argChoices = values.slice();
749
- this.parseArg = (arg, previous) => {
750
- if (!this.argChoices.includes(arg)) {
751
- throw new InvalidArgumentError2(
752
- `Allowed choices are ${this.argChoices.join(", ")}.`
753
- );
754
- }
755
- if (this.variadic) {
756
- return this._concatValue(arg, previous);
757
- }
758
- return arg;
759
- };
760
- return this;
761
- }
762
- /**
763
- * Return option name.
764
- *
765
- * @return {string}
766
- */
767
- name() {
768
- if (this.long) {
769
- return this.long.replace(/^--/, "");
770
- }
771
- return this.short.replace(/^-/, "");
772
- }
773
- /**
774
- * Return option name, in a camelcase format that can be used
775
- * as a object attribute key.
776
- *
777
- * @return {string}
778
- */
779
- attributeName() {
780
- return camelcase(this.name().replace(/^no-/, ""));
781
- }
782
- /**
783
- * Check if `arg` matches the short or long flag.
784
- *
785
- * @param {string} arg
786
- * @return {boolean}
787
- * @package
788
- */
789
- is(arg) {
790
- return this.short === arg || this.long === arg;
791
- }
792
- /**
793
- * Return whether a boolean option.
794
- *
795
- * Options are one of boolean, negated, required argument, or optional argument.
796
- *
797
- * @return {boolean}
798
- * @package
799
- */
800
- isBoolean() {
801
- return !this.required && !this.optional && !this.negate;
802
- }
803
- };
804
- var DualOptions = class {
805
- /**
806
- * @param {Option[]} options
807
- */
808
- constructor(options) {
809
- this.positiveOptions = /* @__PURE__ */ new Map();
810
- this.negativeOptions = /* @__PURE__ */ new Map();
811
- this.dualOptions = /* @__PURE__ */ new Set();
812
- options.forEach((option) => {
813
- if (option.negate) {
814
- this.negativeOptions.set(option.attributeName(), option);
815
- } else {
816
- this.positiveOptions.set(option.attributeName(), option);
817
- }
818
- });
819
- this.negativeOptions.forEach((value, key) => {
820
- if (this.positiveOptions.has(key)) {
821
- this.dualOptions.add(key);
822
- }
823
- });
824
- }
825
- /**
826
- * Did the value come from the option, and not from possible matching dual option?
827
- *
828
- * @param {*} value
829
- * @param {Option} option
830
- * @returns {boolean}
831
- */
832
- valueFromOption(value, option) {
833
- const optionKey = option.attributeName();
834
- if (!this.dualOptions.has(optionKey)) return true;
835
- const preset = this.negativeOptions.get(optionKey).presetArg;
836
- const negativeValue = preset !== void 0 ? preset : false;
837
- return option.negate === (negativeValue === value);
838
- }
839
- };
840
- function camelcase(str) {
841
- return str.split("-").reduce((str2, word) => {
842
- return str2 + word[0].toUpperCase() + word.slice(1);
843
- });
844
- }
845
- function splitOptionFlags(flags) {
846
- let shortFlag;
847
- let longFlag;
848
- const flagParts = flags.split(/[ |,]+/);
849
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
850
- shortFlag = flagParts.shift();
851
- longFlag = flagParts.shift();
852
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
853
- shortFlag = longFlag;
854
- longFlag = void 0;
855
- }
856
- return { shortFlag, longFlag };
857
- }
858
- exports.Option = Option2;
859
- exports.DualOptions = DualOptions;
860
- }
861
- });
862
-
863
- // node_modules/commander/lib/suggestSimilar.js
864
- var require_suggestSimilar = __commonJS({
865
- "node_modules/commander/lib/suggestSimilar.js"(exports) {
866
- var maxDistance = 3;
867
- function editDistance(a, b) {
868
- if (Math.abs(a.length - b.length) > maxDistance)
869
- return Math.max(a.length, b.length);
870
- const d = [];
871
- for (let i = 0; i <= a.length; i++) {
872
- d[i] = [i];
873
- }
874
- for (let j = 0; j <= b.length; j++) {
875
- d[0][j] = j;
876
- }
877
- for (let j = 1; j <= b.length; j++) {
878
- for (let i = 1; i <= a.length; i++) {
879
- let cost = 1;
880
- if (a[i - 1] === b[j - 1]) {
881
- cost = 0;
882
- } else {
883
- cost = 1;
884
- }
885
- d[i][j] = Math.min(
886
- d[i - 1][j] + 1,
887
- // deletion
888
- d[i][j - 1] + 1,
889
- // insertion
890
- d[i - 1][j - 1] + cost
891
- // substitution
892
- );
893
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
894
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
895
- }
896
- }
897
- }
898
- return d[a.length][b.length];
899
- }
900
- function suggestSimilar(word, candidates) {
901
- if (!candidates || candidates.length === 0) return "";
902
- candidates = Array.from(new Set(candidates));
903
- const searchingOptions = word.startsWith("--");
904
- if (searchingOptions) {
905
- word = word.slice(2);
906
- candidates = candidates.map((candidate) => candidate.slice(2));
907
- }
908
- let similar = [];
909
- let bestDistance = maxDistance;
910
- const minSimilarity = 0.4;
911
- candidates.forEach((candidate) => {
912
- if (candidate.length <= 1) return;
913
- const distance = editDistance(word, candidate);
914
- const length = Math.max(word.length, candidate.length);
915
- const similarity = (length - distance) / length;
916
- if (similarity > minSimilarity) {
917
- if (distance < bestDistance) {
918
- bestDistance = distance;
919
- similar = [candidate];
920
- } else if (distance === bestDistance) {
921
- similar.push(candidate);
922
- }
923
- }
924
- });
925
- similar.sort((a, b) => a.localeCompare(b));
926
- if (searchingOptions) {
927
- similar = similar.map((candidate) => `--${candidate}`);
928
- }
929
- if (similar.length > 1) {
930
- return `
931
- (Did you mean one of ${similar.join(", ")}?)`;
932
- }
933
- if (similar.length === 1) {
934
- return `
935
- (Did you mean ${similar[0]}?)`;
936
- }
937
- return "";
938
- }
939
- exports.suggestSimilar = suggestSimilar;
940
- }
941
- });
942
-
943
- // node_modules/commander/lib/command.js
944
- var require_command = __commonJS({
945
- "node_modules/commander/lib/command.js"(exports) {
946
- var EventEmitter = __require("events").EventEmitter;
947
- var childProcess = __require("child_process");
948
- var path2 = __require("path");
949
- var fs4 = __require("fs");
950
- var process2 = __require("process");
951
- var { Argument: Argument2, humanReadableArgName } = require_argument();
952
- var { CommanderError: CommanderError2 } = require_error();
953
- var { Help: Help2 } = require_help();
954
- var { Option: Option2, DualOptions } = require_option();
955
- var { suggestSimilar } = require_suggestSimilar();
956
- var Command2 = class _Command extends EventEmitter {
957
- /**
958
- * Initialize a new `Command`.
959
- *
960
- * @param {string} [name]
961
- */
962
- constructor(name) {
963
- super();
964
- this.commands = [];
965
- this.options = [];
966
- this.parent = null;
967
- this._allowUnknownOption = false;
968
- this._allowExcessArguments = true;
969
- this.registeredArguments = [];
970
- this._args = this.registeredArguments;
971
- this.args = [];
972
- this.rawArgs = [];
973
- this.processedArgs = [];
974
- this._scriptPath = null;
975
- this._name = name || "";
976
- this._optionValues = {};
977
- this._optionValueSources = {};
978
- this._storeOptionsAsProperties = false;
979
- this._actionHandler = null;
980
- this._executableHandler = false;
981
- this._executableFile = null;
982
- this._executableDir = null;
983
- this._defaultCommandName = null;
984
- this._exitCallback = null;
985
- this._aliases = [];
986
- this._combineFlagAndOptionalValue = true;
987
- this._description = "";
988
- this._summary = "";
989
- this._argsDescription = void 0;
990
- this._enablePositionalOptions = false;
991
- this._passThroughOptions = false;
992
- this._lifeCycleHooks = {};
993
- this._showHelpAfterError = false;
994
- this._showSuggestionAfterError = true;
995
- this._outputConfiguration = {
996
- writeOut: (str) => process2.stdout.write(str),
997
- writeErr: (str) => process2.stderr.write(str),
998
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
999
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1000
- outputError: (str, write) => write(str)
1001
- };
1002
- this._hidden = false;
1003
- this._helpOption = void 0;
1004
- this._addImplicitHelpCommand = void 0;
1005
- this._helpCommand = void 0;
1006
- this._helpConfiguration = {};
1007
- }
1008
- /**
1009
- * Copy settings that are useful to have in common across root command and subcommands.
1010
- *
1011
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1012
- *
1013
- * @param {Command} sourceCommand
1014
- * @return {Command} `this` command for chaining
1015
- */
1016
- copyInheritedSettings(sourceCommand) {
1017
- this._outputConfiguration = sourceCommand._outputConfiguration;
1018
- this._helpOption = sourceCommand._helpOption;
1019
- this._helpCommand = sourceCommand._helpCommand;
1020
- this._helpConfiguration = sourceCommand._helpConfiguration;
1021
- this._exitCallback = sourceCommand._exitCallback;
1022
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1023
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1024
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1025
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1026
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1027
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1028
- return this;
1029
- }
1030
- /**
1031
- * @returns {Command[]}
1032
- * @private
1033
- */
1034
- _getCommandAndAncestors() {
1035
- const result = [];
1036
- for (let command = this; command; command = command.parent) {
1037
- result.push(command);
1038
- }
1039
- return result;
1040
- }
1041
- /**
1042
- * Define a command.
1043
- *
1044
- * There are two styles of command: pay attention to where to put the description.
1045
- *
1046
- * @example
1047
- * // Command implemented using action handler (description is supplied separately to `.command`)
1048
- * program
1049
- * .command('clone <source> [destination]')
1050
- * .description('clone a repository into a newly created directory')
1051
- * .action((source, destination) => {
1052
- * console.log('clone command called');
1053
- * });
1054
- *
1055
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1056
- * program
1057
- * .command('start <service>', 'start named service')
1058
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1059
- *
1060
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1061
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1062
- * @param {object} [execOpts] - configuration options (for executable)
1063
- * @return {Command} returns new command for action handler, or `this` for executable command
1064
- */
1065
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1066
- let desc = actionOptsOrExecDesc;
1067
- let opts = execOpts;
1068
- if (typeof desc === "object" && desc !== null) {
1069
- opts = desc;
1070
- desc = null;
1071
- }
1072
- opts = opts || {};
1073
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1074
- const cmd = this.createCommand(name);
1075
- if (desc) {
1076
- cmd.description(desc);
1077
- cmd._executableHandler = true;
1078
- }
1079
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1080
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1081
- cmd._executableFile = opts.executableFile || null;
1082
- if (args) cmd.arguments(args);
1083
- this._registerCommand(cmd);
1084
- cmd.parent = this;
1085
- cmd.copyInheritedSettings(this);
1086
- if (desc) return this;
1087
- return cmd;
1088
- }
1089
- /**
1090
- * Factory routine to create a new unattached command.
1091
- *
1092
- * See .command() for creating an attached subcommand, which uses this routine to
1093
- * create the command. You can override createCommand to customise subcommands.
1094
- *
1095
- * @param {string} [name]
1096
- * @return {Command} new command
1097
- */
1098
- createCommand(name) {
1099
- return new _Command(name);
1100
- }
1101
- /**
1102
- * You can customise the help with a subclass of Help by overriding createHelp,
1103
- * or by overriding Help properties using configureHelp().
1104
- *
1105
- * @return {Help}
1106
- */
1107
- createHelp() {
1108
- return Object.assign(new Help2(), this.configureHelp());
1109
- }
1110
- /**
1111
- * You can customise the help by overriding Help properties using configureHelp(),
1112
- * or with a subclass of Help by overriding createHelp().
1113
- *
1114
- * @param {object} [configuration] - configuration options
1115
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1116
- */
1117
- configureHelp(configuration) {
1118
- if (configuration === void 0) return this._helpConfiguration;
1119
- this._helpConfiguration = configuration;
1120
- return this;
1121
- }
1122
- /**
1123
- * The default output goes to stdout and stderr. You can customise this for special
1124
- * applications. You can also customise the display of errors by overriding outputError.
1125
- *
1126
- * The configuration properties are all functions:
1127
- *
1128
- * // functions to change where being written, stdout and stderr
1129
- * writeOut(str)
1130
- * writeErr(str)
1131
- * // matching functions to specify width for wrapping help
1132
- * getOutHelpWidth()
1133
- * getErrHelpWidth()
1134
- * // functions based on what is being written out
1135
- * outputError(str, write) // used for displaying errors, and not used for displaying help
1136
- *
1137
- * @param {object} [configuration] - configuration options
1138
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1139
- */
1140
- configureOutput(configuration) {
1141
- if (configuration === void 0) return this._outputConfiguration;
1142
- Object.assign(this._outputConfiguration, configuration);
1143
- return this;
1144
- }
1145
- /**
1146
- * Display the help or a custom message after an error occurs.
1147
- *
1148
- * @param {(boolean|string)} [displayHelp]
1149
- * @return {Command} `this` command for chaining
1150
- */
1151
- showHelpAfterError(displayHelp = true) {
1152
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1153
- this._showHelpAfterError = displayHelp;
1154
- return this;
1155
- }
1156
- /**
1157
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1158
- *
1159
- * @param {boolean} [displaySuggestion]
1160
- * @return {Command} `this` command for chaining
1161
- */
1162
- showSuggestionAfterError(displaySuggestion = true) {
1163
- this._showSuggestionAfterError = !!displaySuggestion;
1164
- return this;
1165
- }
1166
- /**
1167
- * Add a prepared subcommand.
1168
- *
1169
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1170
- *
1171
- * @param {Command} cmd - new subcommand
1172
- * @param {object} [opts] - configuration options
1173
- * @return {Command} `this` command for chaining
1174
- */
1175
- addCommand(cmd, opts) {
1176
- if (!cmd._name) {
1177
- throw new Error(`Command passed to .addCommand() must have a name
1178
- - specify the name in Command constructor or using .name()`);
1179
- }
1180
- opts = opts || {};
1181
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1182
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1183
- this._registerCommand(cmd);
1184
- cmd.parent = this;
1185
- cmd._checkForBrokenPassThrough();
1186
- return this;
1187
- }
1188
- /**
1189
- * Factory routine to create a new unattached argument.
1190
- *
1191
- * See .argument() for creating an attached argument, which uses this routine to
1192
- * create the argument. You can override createArgument to return a custom argument.
1193
- *
1194
- * @param {string} name
1195
- * @param {string} [description]
1196
- * @return {Argument} new argument
1197
- */
1198
- createArgument(name, description) {
1199
- return new Argument2(name, description);
1200
- }
1201
- /**
1202
- * Define argument syntax for command.
1203
- *
1204
- * The default is that the argument is required, and you can explicitly
1205
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1206
- *
1207
- * @example
1208
- * program.argument('<input-file>');
1209
- * program.argument('[output-file]');
1210
- *
1211
- * @param {string} name
1212
- * @param {string} [description]
1213
- * @param {(Function|*)} [fn] - custom argument processing function
1214
- * @param {*} [defaultValue]
1215
- * @return {Command} `this` command for chaining
1216
- */
1217
- argument(name, description, fn, defaultValue) {
1218
- const argument = this.createArgument(name, description);
1219
- if (typeof fn === "function") {
1220
- argument.default(defaultValue).argParser(fn);
1221
- } else {
1222
- argument.default(fn);
1223
- }
1224
- this.addArgument(argument);
1225
- return this;
1226
- }
1227
- /**
1228
- * Define argument syntax for command, adding multiple at once (without descriptions).
1229
- *
1230
- * See also .argument().
1231
- *
1232
- * @example
1233
- * program.arguments('<cmd> [env]');
1234
- *
1235
- * @param {string} names
1236
- * @return {Command} `this` command for chaining
1237
- */
1238
- arguments(names) {
1239
- names.trim().split(/ +/).forEach((detail) => {
1240
- this.argument(detail);
1241
- });
1242
- return this;
1243
- }
1244
- /**
1245
- * Define argument syntax for command, adding a prepared argument.
1246
- *
1247
- * @param {Argument} argument
1248
- * @return {Command} `this` command for chaining
1249
- */
1250
- addArgument(argument) {
1251
- const previousArgument = this.registeredArguments.slice(-1)[0];
1252
- if (previousArgument && previousArgument.variadic) {
1253
- throw new Error(
1254
- `only the last argument can be variadic '${previousArgument.name()}'`
1255
- );
1256
- }
1257
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1258
- throw new Error(
1259
- `a default value for a required argument is never used: '${argument.name()}'`
1260
- );
1261
- }
1262
- this.registeredArguments.push(argument);
1263
- return this;
1264
- }
1265
- /**
1266
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1267
- *
1268
- * @example
1269
- * program.helpCommand('help [cmd]');
1270
- * program.helpCommand('help [cmd]', 'show help');
1271
- * program.helpCommand(false); // suppress default help command
1272
- * program.helpCommand(true); // add help command even if no subcommands
1273
- *
1274
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1275
- * @param {string} [description] - custom description
1276
- * @return {Command} `this` command for chaining
1277
- */
1278
- helpCommand(enableOrNameAndArgs, description) {
1279
- if (typeof enableOrNameAndArgs === "boolean") {
1280
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1281
- return this;
1282
- }
1283
- enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1284
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1285
- const helpDescription = description ?? "display help for command";
1286
- const helpCommand = this.createCommand(helpName);
1287
- helpCommand.helpOption(false);
1288
- if (helpArgs) helpCommand.arguments(helpArgs);
1289
- if (helpDescription) helpCommand.description(helpDescription);
1290
- this._addImplicitHelpCommand = true;
1291
- this._helpCommand = helpCommand;
1292
- return this;
1293
- }
1294
- /**
1295
- * Add prepared custom help command.
1296
- *
1297
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1298
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1299
- * @return {Command} `this` command for chaining
1300
- */
1301
- addHelpCommand(helpCommand, deprecatedDescription) {
1302
- if (typeof helpCommand !== "object") {
1303
- this.helpCommand(helpCommand, deprecatedDescription);
1304
- return this;
1305
- }
1306
- this._addImplicitHelpCommand = true;
1307
- this._helpCommand = helpCommand;
1308
- return this;
1309
- }
1310
- /**
1311
- * Lazy create help command.
1312
- *
1313
- * @return {(Command|null)}
1314
- * @package
1315
- */
1316
- _getHelpCommand() {
1317
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1318
- if (hasImplicitHelpCommand) {
1319
- if (this._helpCommand === void 0) {
1320
- this.helpCommand(void 0, void 0);
1321
- }
1322
- return this._helpCommand;
1323
- }
1324
- return null;
1325
- }
1326
- /**
1327
- * Add hook for life cycle event.
1328
- *
1329
- * @param {string} event
1330
- * @param {Function} listener
1331
- * @return {Command} `this` command for chaining
1332
- */
1333
- hook(event, listener) {
1334
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1335
- if (!allowedValues.includes(event)) {
1336
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1337
- Expecting one of '${allowedValues.join("', '")}'`);
1338
- }
1339
- if (this._lifeCycleHooks[event]) {
1340
- this._lifeCycleHooks[event].push(listener);
1341
- } else {
1342
- this._lifeCycleHooks[event] = [listener];
1343
- }
1344
- return this;
1345
- }
1346
- /**
1347
- * Register callback to use as replacement for calling process.exit.
1348
- *
1349
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1350
- * @return {Command} `this` command for chaining
1351
- */
1352
- exitOverride(fn) {
1353
- if (fn) {
1354
- this._exitCallback = fn;
1355
- } else {
1356
- this._exitCallback = (err) => {
1357
- if (err.code !== "commander.executeSubCommandAsync") {
1358
- throw err;
1359
- } else {
1360
- }
1361
- };
1362
- }
1363
- return this;
1364
- }
1365
- /**
1366
- * Call process.exit, and _exitCallback if defined.
1367
- *
1368
- * @param {number} exitCode exit code for using with process.exit
1369
- * @param {string} code an id string representing the error
1370
- * @param {string} message human-readable description of the error
1371
- * @return never
1372
- * @private
1373
- */
1374
- _exit(exitCode, code, message) {
1375
- if (this._exitCallback) {
1376
- this._exitCallback(new CommanderError2(exitCode, code, message));
1377
- }
1378
- process2.exit(exitCode);
1379
- }
1380
- /**
1381
- * Register callback `fn` for the command.
1382
- *
1383
- * @example
1384
- * program
1385
- * .command('serve')
1386
- * .description('start service')
1387
- * .action(function() {
1388
- * // do work here
1389
- * });
1390
- *
1391
- * @param {Function} fn
1392
- * @return {Command} `this` command for chaining
1393
- */
1394
- action(fn) {
1395
- const listener = (args) => {
1396
- const expectedArgsCount = this.registeredArguments.length;
1397
- const actionArgs = args.slice(0, expectedArgsCount);
1398
- if (this._storeOptionsAsProperties) {
1399
- actionArgs[expectedArgsCount] = this;
1400
- } else {
1401
- actionArgs[expectedArgsCount] = this.opts();
1402
- }
1403
- actionArgs.push(this);
1404
- return fn.apply(this, actionArgs);
1405
- };
1406
- this._actionHandler = listener;
1407
- return this;
1408
- }
1409
- /**
1410
- * Factory routine to create a new unattached option.
1411
- *
1412
- * See .option() for creating an attached option, which uses this routine to
1413
- * create the option. You can override createOption to return a custom option.
1414
- *
1415
- * @param {string} flags
1416
- * @param {string} [description]
1417
- * @return {Option} new option
1418
- */
1419
- createOption(flags, description) {
1420
- return new Option2(flags, description);
1421
- }
1422
- /**
1423
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1424
- *
1425
- * @param {(Option | Argument)} target
1426
- * @param {string} value
1427
- * @param {*} previous
1428
- * @param {string} invalidArgumentMessage
1429
- * @private
1430
- */
1431
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1432
- try {
1433
- return target.parseArg(value, previous);
1434
- } catch (err) {
1435
- if (err.code === "commander.invalidArgument") {
1436
- const message = `${invalidArgumentMessage} ${err.message}`;
1437
- this.error(message, { exitCode: err.exitCode, code: err.code });
1438
- }
1439
- throw err;
1440
- }
1441
- }
1442
- /**
1443
- * Check for option flag conflicts.
1444
- * Register option if no conflicts found, or throw on conflict.
1445
- *
1446
- * @param {Option} option
1447
- * @private
1448
- */
1449
- _registerOption(option) {
1450
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1451
- if (matchingOption) {
1452
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1453
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1454
- - already used by option '${matchingOption.flags}'`);
1455
- }
1456
- this.options.push(option);
1457
- }
1458
- /**
1459
- * Check for command name and alias conflicts with existing commands.
1460
- * Register command if no conflicts found, or throw on conflict.
1461
- *
1462
- * @param {Command} command
1463
- * @private
1464
- */
1465
- _registerCommand(command) {
1466
- const knownBy = (cmd) => {
1467
- return [cmd.name()].concat(cmd.aliases());
1468
- };
1469
- const alreadyUsed = knownBy(command).find(
1470
- (name) => this._findCommand(name)
1471
- );
1472
- if (alreadyUsed) {
1473
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1474
- const newCmd = knownBy(command).join("|");
1475
- throw new Error(
1476
- `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1477
- );
1478
- }
1479
- this.commands.push(command);
1480
- }
1481
- /**
1482
- * Add an option.
1483
- *
1484
- * @param {Option} option
1485
- * @return {Command} `this` command for chaining
1486
- */
1487
- addOption(option) {
1488
- this._registerOption(option);
1489
- const oname = option.name();
1490
- const name = option.attributeName();
1491
- if (option.negate) {
1492
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1493
- if (!this._findOption(positiveLongFlag)) {
1494
- this.setOptionValueWithSource(
1495
- name,
1496
- option.defaultValue === void 0 ? true : option.defaultValue,
1497
- "default"
1498
- );
1499
- }
1500
- } else if (option.defaultValue !== void 0) {
1501
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1502
- }
1503
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1504
- if (val == null && option.presetArg !== void 0) {
1505
- val = option.presetArg;
1506
- }
1507
- const oldValue = this.getOptionValue(name);
1508
- if (val !== null && option.parseArg) {
1509
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1510
- } else if (val !== null && option.variadic) {
1511
- val = option._concatValue(val, oldValue);
1512
- }
1513
- if (val == null) {
1514
- if (option.negate) {
1515
- val = false;
1516
- } else if (option.isBoolean() || option.optional) {
1517
- val = true;
1518
- } else {
1519
- val = "";
1520
- }
1521
- }
1522
- this.setOptionValueWithSource(name, val, valueSource);
1523
- };
1524
- this.on("option:" + oname, (val) => {
1525
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1526
- handleOptionValue(val, invalidValueMessage, "cli");
1527
- });
1528
- if (option.envVar) {
1529
- this.on("optionEnv:" + oname, (val) => {
1530
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1531
- handleOptionValue(val, invalidValueMessage, "env");
1532
- });
1533
- }
1534
- return this;
1535
- }
1536
- /**
1537
- * Internal implementation shared by .option() and .requiredOption()
1538
- *
1539
- * @return {Command} `this` command for chaining
1540
- * @private
1541
- */
1542
- _optionEx(config, flags, description, fn, defaultValue) {
1543
- if (typeof flags === "object" && flags instanceof Option2) {
1544
- throw new Error(
1545
- "To add an Option object use addOption() instead of option() or requiredOption()"
1546
- );
1547
- }
1548
- const option = this.createOption(flags, description);
1549
- option.makeOptionMandatory(!!config.mandatory);
1550
- if (typeof fn === "function") {
1551
- option.default(defaultValue).argParser(fn);
1552
- } else if (fn instanceof RegExp) {
1553
- const regex = fn;
1554
- fn = (val, def) => {
1555
- const m = regex.exec(val);
1556
- return m ? m[0] : def;
1557
- };
1558
- option.default(defaultValue).argParser(fn);
1559
- } else {
1560
- option.default(fn);
1561
- }
1562
- return this.addOption(option);
1563
- }
1564
- /**
1565
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1566
- *
1567
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1568
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1569
- *
1570
- * See the README for more details, and see also addOption() and requiredOption().
1571
- *
1572
- * @example
1573
- * program
1574
- * .option('-p, --pepper', 'add pepper')
1575
- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1576
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1577
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1578
- *
1579
- * @param {string} flags
1580
- * @param {string} [description]
1581
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1582
- * @param {*} [defaultValue]
1583
- * @return {Command} `this` command for chaining
1584
- */
1585
- option(flags, description, parseArg, defaultValue) {
1586
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1587
- }
1588
- /**
1589
- * Add a required option which must have a value after parsing. This usually means
1590
- * the option must be specified on the command line. (Otherwise the same as .option().)
1591
- *
1592
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1593
- *
1594
- * @param {string} flags
1595
- * @param {string} [description]
1596
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1597
- * @param {*} [defaultValue]
1598
- * @return {Command} `this` command for chaining
1599
- */
1600
- requiredOption(flags, description, parseArg, defaultValue) {
1601
- return this._optionEx(
1602
- { mandatory: true },
1603
- flags,
1604
- description,
1605
- parseArg,
1606
- defaultValue
1607
- );
1608
- }
1609
- /**
1610
- * Alter parsing of short flags with optional values.
1611
- *
1612
- * @example
1613
- * // for `.option('-f,--flag [value]'):
1614
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1615
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1616
- *
1617
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1618
- * @return {Command} `this` command for chaining
1619
- */
1620
- combineFlagAndOptionalValue(combine = true) {
1621
- this._combineFlagAndOptionalValue = !!combine;
1622
- return this;
1623
- }
1624
- /**
1625
- * Allow unknown options on the command line.
1626
- *
1627
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1628
- * @return {Command} `this` command for chaining
1629
- */
1630
- allowUnknownOption(allowUnknown = true) {
1631
- this._allowUnknownOption = !!allowUnknown;
1632
- return this;
1633
- }
1634
- /**
1635
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1636
- *
1637
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1638
- * @return {Command} `this` command for chaining
1639
- */
1640
- allowExcessArguments(allowExcess = true) {
1641
- this._allowExcessArguments = !!allowExcess;
1642
- return this;
1643
- }
1644
- /**
1645
- * Enable positional options. Positional means global options are specified before subcommands which lets
1646
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1647
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1648
- *
1649
- * @param {boolean} [positional]
1650
- * @return {Command} `this` command for chaining
1651
- */
1652
- enablePositionalOptions(positional = true) {
1653
- this._enablePositionalOptions = !!positional;
1654
- return this;
1655
- }
1656
- /**
1657
- * Pass through options that come after command-arguments rather than treat them as command-options,
1658
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1659
- * positional options to have been enabled on the program (parent commands).
1660
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1661
- *
1662
- * @param {boolean} [passThrough] for unknown options.
1663
- * @return {Command} `this` command for chaining
1664
- */
1665
- passThroughOptions(passThrough = true) {
1666
- this._passThroughOptions = !!passThrough;
1667
- this._checkForBrokenPassThrough();
1668
- return this;
1669
- }
1670
- /**
1671
- * @private
1672
- */
1673
- _checkForBrokenPassThrough() {
1674
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1675
- throw new Error(
1676
- `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1677
- );
1678
- }
1679
- }
1680
- /**
1681
- * Whether to store option values as properties on command object,
1682
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1683
- *
1684
- * @param {boolean} [storeAsProperties=true]
1685
- * @return {Command} `this` command for chaining
1686
- */
1687
- storeOptionsAsProperties(storeAsProperties = true) {
1688
- if (this.options.length) {
1689
- throw new Error("call .storeOptionsAsProperties() before adding options");
1690
- }
1691
- if (Object.keys(this._optionValues).length) {
1692
- throw new Error(
1693
- "call .storeOptionsAsProperties() before setting option values"
1694
- );
1695
- }
1696
- this._storeOptionsAsProperties = !!storeAsProperties;
1697
- return this;
1698
- }
1699
- /**
1700
- * Retrieve option value.
1701
- *
1702
- * @param {string} key
1703
- * @return {object} value
1704
- */
1705
- getOptionValue(key) {
1706
- if (this._storeOptionsAsProperties) {
1707
- return this[key];
1708
- }
1709
- return this._optionValues[key];
1710
- }
1711
- /**
1712
- * Store option value.
1713
- *
1714
- * @param {string} key
1715
- * @param {object} value
1716
- * @return {Command} `this` command for chaining
1717
- */
1718
- setOptionValue(key, value) {
1719
- return this.setOptionValueWithSource(key, value, void 0);
1720
- }
1721
- /**
1722
- * Store option value and where the value came from.
1723
- *
1724
- * @param {string} key
1725
- * @param {object} value
1726
- * @param {string} source - expected values are default/config/env/cli/implied
1727
- * @return {Command} `this` command for chaining
1728
- */
1729
- setOptionValueWithSource(key, value, source) {
1730
- if (this._storeOptionsAsProperties) {
1731
- this[key] = value;
1732
- } else {
1733
- this._optionValues[key] = value;
1734
- }
1735
- this._optionValueSources[key] = source;
1736
- return this;
1737
- }
1738
- /**
1739
- * Get source of option value.
1740
- * Expected values are default | config | env | cli | implied
1741
- *
1742
- * @param {string} key
1743
- * @return {string}
1744
- */
1745
- getOptionValueSource(key) {
1746
- return this._optionValueSources[key];
1747
- }
1748
- /**
1749
- * Get source of option value. See also .optsWithGlobals().
1750
- * Expected values are default | config | env | cli | implied
1751
- *
1752
- * @param {string} key
1753
- * @return {string}
1754
- */
1755
- getOptionValueSourceWithGlobals(key) {
1756
- let source;
1757
- this._getCommandAndAncestors().forEach((cmd) => {
1758
- if (cmd.getOptionValueSource(key) !== void 0) {
1759
- source = cmd.getOptionValueSource(key);
1760
- }
1761
- });
1762
- return source;
1763
- }
1764
- /**
1765
- * Get user arguments from implied or explicit arguments.
1766
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1767
- *
1768
- * @private
1769
- */
1770
- _prepareUserArgs(argv, parseOptions) {
1771
- var _a;
1772
- if (argv !== void 0 && !Array.isArray(argv)) {
1773
- throw new Error("first parameter to parse must be array or undefined");
1774
- }
1775
- parseOptions = parseOptions || {};
1776
- if (argv === void 0 && parseOptions.from === void 0) {
1777
- if ((_a = process2.versions) == null ? void 0 : _a.electron) {
1778
- parseOptions.from = "electron";
1779
- }
1780
- const execArgv = process2.execArgv ?? [];
1781
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1782
- parseOptions.from = "eval";
1783
- }
1784
- }
1785
- if (argv === void 0) {
1786
- argv = process2.argv;
1787
- }
1788
- this.rawArgs = argv.slice();
1789
- let userArgs;
1790
- switch (parseOptions.from) {
1791
- case void 0:
1792
- case "node":
1793
- this._scriptPath = argv[1];
1794
- userArgs = argv.slice(2);
1795
- break;
1796
- case "electron":
1797
- if (process2.defaultApp) {
1798
- this._scriptPath = argv[1];
1799
- userArgs = argv.slice(2);
1800
- } else {
1801
- userArgs = argv.slice(1);
1802
- }
1803
- break;
1804
- case "user":
1805
- userArgs = argv.slice(0);
1806
- break;
1807
- case "eval":
1808
- userArgs = argv.slice(1);
1809
- break;
1810
- default:
1811
- throw new Error(
1812
- `unexpected parse option { from: '${parseOptions.from}' }`
1813
- );
1814
- }
1815
- if (!this._name && this._scriptPath)
1816
- this.nameFromFilename(this._scriptPath);
1817
- this._name = this._name || "program";
1818
- return userArgs;
1819
- }
1820
- /**
1821
- * Parse `argv`, setting options and invoking commands when defined.
1822
- *
1823
- * Use parseAsync instead of parse if any of your action handlers are async.
1824
- *
1825
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1826
- *
1827
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1828
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1829
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1830
- * - `'user'`: just user arguments
1831
- *
1832
- * @example
1833
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
1834
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1835
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1836
- *
1837
- * @param {string[]} [argv] - optional, defaults to process.argv
1838
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1839
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1840
- * @return {Command} `this` command for chaining
1841
- */
1842
- parse(argv, parseOptions) {
1843
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1844
- this._parseCommand([], userArgs);
1845
- return this;
1846
- }
1847
- /**
1848
- * Parse `argv`, setting options and invoking commands when defined.
1849
- *
1850
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1851
- *
1852
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1853
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1854
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1855
- * - `'user'`: just user arguments
1856
- *
1857
- * @example
1858
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1859
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1860
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1861
- *
1862
- * @param {string[]} [argv]
1863
- * @param {object} [parseOptions]
1864
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1865
- * @return {Promise}
1866
- */
1867
- async parseAsync(argv, parseOptions) {
1868
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1869
- await this._parseCommand([], userArgs);
1870
- return this;
1871
- }
1872
- /**
1873
- * Execute a sub-command executable.
1874
- *
1875
- * @private
1876
- */
1877
- _executeSubCommand(subcommand, args) {
1878
- args = args.slice();
1879
- let launchWithNode = false;
1880
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1881
- function findFile(baseDir, baseName) {
1882
- const localBin = path2.resolve(baseDir, baseName);
1883
- if (fs4.existsSync(localBin)) return localBin;
1884
- if (sourceExt.includes(path2.extname(baseName))) return void 0;
1885
- const foundExt = sourceExt.find(
1886
- (ext) => fs4.existsSync(`${localBin}${ext}`)
1887
- );
1888
- if (foundExt) return `${localBin}${foundExt}`;
1889
- return void 0;
1890
- }
1891
- this._checkForMissingMandatoryOptions();
1892
- this._checkForConflictingOptions();
1893
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1894
- let executableDir = this._executableDir || "";
1895
- if (this._scriptPath) {
1896
- let resolvedScriptPath;
1897
- try {
1898
- resolvedScriptPath = fs4.realpathSync(this._scriptPath);
1899
- } catch (err) {
1900
- resolvedScriptPath = this._scriptPath;
1901
- }
1902
- executableDir = path2.resolve(
1903
- path2.dirname(resolvedScriptPath),
1904
- executableDir
1905
- );
1906
- }
1907
- if (executableDir) {
1908
- let localFile = findFile(executableDir, executableFile);
1909
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1910
- const legacyName = path2.basename(
1911
- this._scriptPath,
1912
- path2.extname(this._scriptPath)
1913
- );
1914
- if (legacyName !== this._name) {
1915
- localFile = findFile(
1916
- executableDir,
1917
- `${legacyName}-${subcommand._name}`
1918
- );
1919
- }
1920
- }
1921
- executableFile = localFile || executableFile;
1922
- }
1923
- launchWithNode = sourceExt.includes(path2.extname(executableFile));
1924
- let proc;
1925
- if (process2.platform !== "win32") {
1926
- if (launchWithNode) {
1927
- args.unshift(executableFile);
1928
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1929
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1930
- } else {
1931
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1932
- }
1933
- } else {
1934
- args.unshift(executableFile);
1935
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1936
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1937
- }
1938
- if (!proc.killed) {
1939
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1940
- signals.forEach((signal) => {
1941
- process2.on(signal, () => {
1942
- if (proc.killed === false && proc.exitCode === null) {
1943
- proc.kill(signal);
1944
- }
1945
- });
1946
- });
1947
- }
1948
- const exitCallback = this._exitCallback;
1949
- proc.on("close", (code) => {
1950
- code = code ?? 1;
1951
- if (!exitCallback) {
1952
- process2.exit(code);
1953
- } else {
1954
- exitCallback(
1955
- new CommanderError2(
1956
- code,
1957
- "commander.executeSubCommandAsync",
1958
- "(close)"
1959
- )
1960
- );
1961
- }
1962
- });
1963
- proc.on("error", (err) => {
1964
- if (err.code === "ENOENT") {
1965
- 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";
1966
- const executableMissing = `'${executableFile}' does not exist
1967
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1968
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1969
- - ${executableDirMessage}`;
1970
- throw new Error(executableMissing);
1971
- } else if (err.code === "EACCES") {
1972
- throw new Error(`'${executableFile}' not executable`);
1973
- }
1974
- if (!exitCallback) {
1975
- process2.exit(1);
1976
- } else {
1977
- const wrappedError = new CommanderError2(
1978
- 1,
1979
- "commander.executeSubCommandAsync",
1980
- "(error)"
1981
- );
1982
- wrappedError.nestedError = err;
1983
- exitCallback(wrappedError);
1984
- }
1985
- });
1986
- this.runningCommand = proc;
1987
- }
1988
- /**
1989
- * @private
1990
- */
1991
- _dispatchSubcommand(commandName, operands, unknown) {
1992
- const subCommand = this._findCommand(commandName);
1993
- if (!subCommand) this.help({ error: true });
1994
- let promiseChain;
1995
- promiseChain = this._chainOrCallSubCommandHook(
1996
- promiseChain,
1997
- subCommand,
1998
- "preSubcommand"
1999
- );
2000
- promiseChain = this._chainOrCall(promiseChain, () => {
2001
- if (subCommand._executableHandler) {
2002
- this._executeSubCommand(subCommand, operands.concat(unknown));
2003
- } else {
2004
- return subCommand._parseCommand(operands, unknown);
2005
- }
2006
- });
2007
- return promiseChain;
2008
- }
2009
- /**
2010
- * Invoke help directly if possible, or dispatch if necessary.
2011
- * e.g. help foo
2012
- *
2013
- * @private
2014
- */
2015
- _dispatchHelpCommand(subcommandName) {
2016
- var _a, _b;
2017
- if (!subcommandName) {
2018
- this.help();
2019
- }
2020
- const subCommand = this._findCommand(subcommandName);
2021
- if (subCommand && !subCommand._executableHandler) {
2022
- subCommand.help();
2023
- }
2024
- return this._dispatchSubcommand(
2025
- subcommandName,
2026
- [],
2027
- [((_a = this._getHelpOption()) == null ? void 0 : _a.long) ?? ((_b = this._getHelpOption()) == null ? void 0 : _b.short) ?? "--help"]
2028
- );
2029
- }
2030
- /**
2031
- * Check this.args against expected this.registeredArguments.
2032
- *
2033
- * @private
2034
- */
2035
- _checkNumberOfArguments() {
2036
- this.registeredArguments.forEach((arg, i) => {
2037
- if (arg.required && this.args[i] == null) {
2038
- this.missingArgument(arg.name());
2039
- }
2040
- });
2041
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2042
- return;
2043
- }
2044
- if (this.args.length > this.registeredArguments.length) {
2045
- this._excessArguments(this.args);
2046
- }
2047
- }
2048
- /**
2049
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2050
- *
2051
- * @private
2052
- */
2053
- _processArguments() {
2054
- const myParseArg = (argument, value, previous) => {
2055
- let parsedValue = value;
2056
- if (value !== null && argument.parseArg) {
2057
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2058
- parsedValue = this._callParseArg(
2059
- argument,
2060
- value,
2061
- previous,
2062
- invalidValueMessage
2063
- );
2064
- }
2065
- return parsedValue;
2066
- };
2067
- this._checkNumberOfArguments();
2068
- const processedArgs = [];
2069
- this.registeredArguments.forEach((declaredArg, index) => {
2070
- let value = declaredArg.defaultValue;
2071
- if (declaredArg.variadic) {
2072
- if (index < this.args.length) {
2073
- value = this.args.slice(index);
2074
- if (declaredArg.parseArg) {
2075
- value = value.reduce((processed, v) => {
2076
- return myParseArg(declaredArg, v, processed);
2077
- }, declaredArg.defaultValue);
2078
- }
2079
- } else if (value === void 0) {
2080
- value = [];
2081
- }
2082
- } else if (index < this.args.length) {
2083
- value = this.args[index];
2084
- if (declaredArg.parseArg) {
2085
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2086
- }
2087
- }
2088
- processedArgs[index] = value;
2089
- });
2090
- this.processedArgs = processedArgs;
2091
- }
2092
- /**
2093
- * Once we have a promise we chain, but call synchronously until then.
2094
- *
2095
- * @param {(Promise|undefined)} promise
2096
- * @param {Function} fn
2097
- * @return {(Promise|undefined)}
2098
- * @private
2099
- */
2100
- _chainOrCall(promise, fn) {
2101
- if (promise && promise.then && typeof promise.then === "function") {
2102
- return promise.then(() => fn());
2103
- }
2104
- return fn();
2105
- }
2106
- /**
2107
- *
2108
- * @param {(Promise|undefined)} promise
2109
- * @param {string} event
2110
- * @return {(Promise|undefined)}
2111
- * @private
2112
- */
2113
- _chainOrCallHooks(promise, event) {
2114
- let result = promise;
2115
- const hooks = [];
2116
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2117
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2118
- hooks.push({ hookedCommand, callback });
2119
- });
2120
- });
2121
- if (event === "postAction") {
2122
- hooks.reverse();
2123
- }
2124
- hooks.forEach((hookDetail) => {
2125
- result = this._chainOrCall(result, () => {
2126
- return hookDetail.callback(hookDetail.hookedCommand, this);
2127
- });
2128
- });
2129
- return result;
2130
- }
2131
- /**
2132
- *
2133
- * @param {(Promise|undefined)} promise
2134
- * @param {Command} subCommand
2135
- * @param {string} event
2136
- * @return {(Promise|undefined)}
2137
- * @private
2138
- */
2139
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2140
- let result = promise;
2141
- if (this._lifeCycleHooks[event] !== void 0) {
2142
- this._lifeCycleHooks[event].forEach((hook) => {
2143
- result = this._chainOrCall(result, () => {
2144
- return hook(this, subCommand);
2145
- });
2146
- });
2147
- }
2148
- return result;
2149
- }
2150
- /**
2151
- * Process arguments in context of this command.
2152
- * Returns action result, in case it is a promise.
2153
- *
2154
- * @private
2155
- */
2156
- _parseCommand(operands, unknown) {
2157
- const parsed = this.parseOptions(unknown);
2158
- this._parseOptionsEnv();
2159
- this._parseOptionsImplied();
2160
- operands = operands.concat(parsed.operands);
2161
- unknown = parsed.unknown;
2162
- this.args = operands.concat(unknown);
2163
- if (operands && this._findCommand(operands[0])) {
2164
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2165
- }
2166
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2167
- return this._dispatchHelpCommand(operands[1]);
2168
- }
2169
- if (this._defaultCommandName) {
2170
- this._outputHelpIfRequested(unknown);
2171
- return this._dispatchSubcommand(
2172
- this._defaultCommandName,
2173
- operands,
2174
- unknown
2175
- );
2176
- }
2177
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2178
- this.help({ error: true });
2179
- }
2180
- this._outputHelpIfRequested(parsed.unknown);
2181
- this._checkForMissingMandatoryOptions();
2182
- this._checkForConflictingOptions();
2183
- const checkForUnknownOptions = () => {
2184
- if (parsed.unknown.length > 0) {
2185
- this.unknownOption(parsed.unknown[0]);
2186
- }
2187
- };
2188
- const commandEvent = `command:${this.name()}`;
2189
- if (this._actionHandler) {
2190
- checkForUnknownOptions();
2191
- this._processArguments();
2192
- let promiseChain;
2193
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2194
- promiseChain = this._chainOrCall(
2195
- promiseChain,
2196
- () => this._actionHandler(this.processedArgs)
2197
- );
2198
- if (this.parent) {
2199
- promiseChain = this._chainOrCall(promiseChain, () => {
2200
- this.parent.emit(commandEvent, operands, unknown);
2201
- });
2202
- }
2203
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2204
- return promiseChain;
2205
- }
2206
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2207
- checkForUnknownOptions();
2208
- this._processArguments();
2209
- this.parent.emit(commandEvent, operands, unknown);
2210
- } else if (operands.length) {
2211
- if (this._findCommand("*")) {
2212
- return this._dispatchSubcommand("*", operands, unknown);
2213
- }
2214
- if (this.listenerCount("command:*")) {
2215
- this.emit("command:*", operands, unknown);
2216
- } else if (this.commands.length) {
2217
- this.unknownCommand();
2218
- } else {
2219
- checkForUnknownOptions();
2220
- this._processArguments();
2221
- }
2222
- } else if (this.commands.length) {
2223
- checkForUnknownOptions();
2224
- this.help({ error: true });
2225
- } else {
2226
- checkForUnknownOptions();
2227
- this._processArguments();
2228
- }
2229
- }
2230
- /**
2231
- * Find matching command.
2232
- *
2233
- * @private
2234
- * @return {Command | undefined}
2235
- */
2236
- _findCommand(name) {
2237
- if (!name) return void 0;
2238
- return this.commands.find(
2239
- (cmd) => cmd._name === name || cmd._aliases.includes(name)
2240
- );
2241
- }
2242
- /**
2243
- * Return an option matching `arg` if any.
2244
- *
2245
- * @param {string} arg
2246
- * @return {Option}
2247
- * @package
2248
- */
2249
- _findOption(arg) {
2250
- return this.options.find((option) => option.is(arg));
2251
- }
2252
- /**
2253
- * Display an error message if a mandatory option does not have a value.
2254
- * Called after checking for help flags in leaf subcommand.
2255
- *
2256
- * @private
2257
- */
2258
- _checkForMissingMandatoryOptions() {
2259
- this._getCommandAndAncestors().forEach((cmd) => {
2260
- cmd.options.forEach((anOption) => {
2261
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2262
- cmd.missingMandatoryOptionValue(anOption);
2263
- }
2264
- });
2265
- });
2266
- }
2267
- /**
2268
- * Display an error message if conflicting options are used together in this.
2269
- *
2270
- * @private
2271
- */
2272
- _checkForConflictingLocalOptions() {
2273
- const definedNonDefaultOptions = this.options.filter((option) => {
2274
- const optionKey = option.attributeName();
2275
- if (this.getOptionValue(optionKey) === void 0) {
2276
- return false;
2277
- }
2278
- return this.getOptionValueSource(optionKey) !== "default";
2279
- });
2280
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2281
- (option) => option.conflictsWith.length > 0
2282
- );
2283
- optionsWithConflicting.forEach((option) => {
2284
- const conflictingAndDefined = definedNonDefaultOptions.find(
2285
- (defined) => option.conflictsWith.includes(defined.attributeName())
2286
- );
2287
- if (conflictingAndDefined) {
2288
- this._conflictingOption(option, conflictingAndDefined);
2289
- }
2290
- });
2291
- }
2292
- /**
2293
- * Display an error message if conflicting options are used together.
2294
- * Called after checking for help flags in leaf subcommand.
2295
- *
2296
- * @private
2297
- */
2298
- _checkForConflictingOptions() {
2299
- this._getCommandAndAncestors().forEach((cmd) => {
2300
- cmd._checkForConflictingLocalOptions();
2301
- });
2302
- }
2303
- /**
2304
- * Parse options from `argv` removing known options,
2305
- * and return argv split into operands and unknown arguments.
2306
- *
2307
- * Examples:
2308
- *
2309
- * argv => operands, unknown
2310
- * --known kkk op => [op], []
2311
- * op --known kkk => [op], []
2312
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2313
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2314
- *
2315
- * @param {string[]} argv
2316
- * @return {{operands: string[], unknown: string[]}}
2317
- */
2318
- parseOptions(argv) {
2319
- const operands = [];
2320
- const unknown = [];
2321
- let dest = operands;
2322
- const args = argv.slice();
2323
- function maybeOption(arg) {
2324
- return arg.length > 1 && arg[0] === "-";
2325
- }
2326
- let activeVariadicOption = null;
2327
- while (args.length) {
2328
- const arg = args.shift();
2329
- if (arg === "--") {
2330
- if (dest === unknown) dest.push(arg);
2331
- dest.push(...args);
2332
- break;
2333
- }
2334
- if (activeVariadicOption && !maybeOption(arg)) {
2335
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2336
- continue;
2337
- }
2338
- activeVariadicOption = null;
2339
- if (maybeOption(arg)) {
2340
- const option = this._findOption(arg);
2341
- if (option) {
2342
- if (option.required) {
2343
- const value = args.shift();
2344
- if (value === void 0) this.optionMissingArgument(option);
2345
- this.emit(`option:${option.name()}`, value);
2346
- } else if (option.optional) {
2347
- let value = null;
2348
- if (args.length > 0 && !maybeOption(args[0])) {
2349
- value = args.shift();
2350
- }
2351
- this.emit(`option:${option.name()}`, value);
2352
- } else {
2353
- this.emit(`option:${option.name()}`);
2354
- }
2355
- activeVariadicOption = option.variadic ? option : null;
2356
- continue;
2357
- }
2358
- }
2359
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2360
- const option = this._findOption(`-${arg[1]}`);
2361
- if (option) {
2362
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2363
- this.emit(`option:${option.name()}`, arg.slice(2));
2364
- } else {
2365
- this.emit(`option:${option.name()}`);
2366
- args.unshift(`-${arg.slice(2)}`);
2367
- }
2368
- continue;
2369
- }
2370
- }
2371
- if (/^--[^=]+=/.test(arg)) {
2372
- const index = arg.indexOf("=");
2373
- const option = this._findOption(arg.slice(0, index));
2374
- if (option && (option.required || option.optional)) {
2375
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2376
- continue;
2377
- }
2378
- }
2379
- if (maybeOption(arg)) {
2380
- dest = unknown;
2381
- }
2382
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2383
- if (this._findCommand(arg)) {
2384
- operands.push(arg);
2385
- if (args.length > 0) unknown.push(...args);
2386
- break;
2387
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2388
- operands.push(arg);
2389
- if (args.length > 0) operands.push(...args);
2390
- break;
2391
- } else if (this._defaultCommandName) {
2392
- unknown.push(arg);
2393
- if (args.length > 0) unknown.push(...args);
2394
- break;
2395
- }
2396
- }
2397
- if (this._passThroughOptions) {
2398
- dest.push(arg);
2399
- if (args.length > 0) dest.push(...args);
2400
- break;
2401
- }
2402
- dest.push(arg);
2403
- }
2404
- return { operands, unknown };
2405
- }
2406
- /**
2407
- * Return an object containing local option values as key-value pairs.
2408
- *
2409
- * @return {object}
2410
- */
2411
- opts() {
2412
- if (this._storeOptionsAsProperties) {
2413
- const result = {};
2414
- const len = this.options.length;
2415
- for (let i = 0; i < len; i++) {
2416
- const key = this.options[i].attributeName();
2417
- result[key] = key === this._versionOptionName ? this._version : this[key];
2418
- }
2419
- return result;
2420
- }
2421
- return this._optionValues;
2422
- }
2423
- /**
2424
- * Return an object containing merged local and global option values as key-value pairs.
2425
- *
2426
- * @return {object}
2427
- */
2428
- optsWithGlobals() {
2429
- return this._getCommandAndAncestors().reduce(
2430
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2431
- {}
2432
- );
2433
- }
2434
- /**
2435
- * Display error message and exit (or call exitOverride).
2436
- *
2437
- * @param {string} message
2438
- * @param {object} [errorOptions]
2439
- * @param {string} [errorOptions.code] - an id string representing the error
2440
- * @param {number} [errorOptions.exitCode] - used with process.exit
2441
- */
2442
- error(message, errorOptions) {
2443
- this._outputConfiguration.outputError(
2444
- `${message}
2445
- `,
2446
- this._outputConfiguration.writeErr
2447
- );
2448
- if (typeof this._showHelpAfterError === "string") {
2449
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2450
- `);
2451
- } else if (this._showHelpAfterError) {
2452
- this._outputConfiguration.writeErr("\n");
2453
- this.outputHelp({ error: true });
2454
- }
2455
- const config = errorOptions || {};
2456
- const exitCode = config.exitCode || 1;
2457
- const code = config.code || "commander.error";
2458
- this._exit(exitCode, code, message);
2459
- }
2460
- /**
2461
- * Apply any option related environment variables, if option does
2462
- * not have a value from cli or client code.
2463
- *
2464
- * @private
2465
- */
2466
- _parseOptionsEnv() {
2467
- this.options.forEach((option) => {
2468
- if (option.envVar && option.envVar in process2.env) {
2469
- const optionKey = option.attributeName();
2470
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2471
- this.getOptionValueSource(optionKey)
2472
- )) {
2473
- if (option.required || option.optional) {
2474
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2475
- } else {
2476
- this.emit(`optionEnv:${option.name()}`);
2477
- }
2478
- }
2479
- }
2480
- });
2481
- }
2482
- /**
2483
- * Apply any implied option values, if option is undefined or default value.
2484
- *
2485
- * @private
2486
- */
2487
- _parseOptionsImplied() {
2488
- const dualHelper = new DualOptions(this.options);
2489
- const hasCustomOptionValue = (optionKey) => {
2490
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2491
- };
2492
- this.options.filter(
2493
- (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2494
- this.getOptionValue(option.attributeName()),
2495
- option
2496
- )
2497
- ).forEach((option) => {
2498
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2499
- this.setOptionValueWithSource(
2500
- impliedKey,
2501
- option.implied[impliedKey],
2502
- "implied"
2503
- );
2504
- });
2505
- });
2506
- }
2507
- /**
2508
- * Argument `name` is missing.
2509
- *
2510
- * @param {string} name
2511
- * @private
2512
- */
2513
- missingArgument(name) {
2514
- const message = `error: missing required argument '${name}'`;
2515
- this.error(message, { code: "commander.missingArgument" });
2516
- }
2517
- /**
2518
- * `Option` is missing an argument.
2519
- *
2520
- * @param {Option} option
2521
- * @private
2522
- */
2523
- optionMissingArgument(option) {
2524
- const message = `error: option '${option.flags}' argument missing`;
2525
- this.error(message, { code: "commander.optionMissingArgument" });
2526
- }
2527
- /**
2528
- * `Option` does not have a value, and is a mandatory option.
2529
- *
2530
- * @param {Option} option
2531
- * @private
2532
- */
2533
- missingMandatoryOptionValue(option) {
2534
- const message = `error: required option '${option.flags}' not specified`;
2535
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2536
- }
2537
- /**
2538
- * `Option` conflicts with another option.
2539
- *
2540
- * @param {Option} option
2541
- * @param {Option} conflictingOption
2542
- * @private
2543
- */
2544
- _conflictingOption(option, conflictingOption) {
2545
- const findBestOptionFromValue = (option2) => {
2546
- const optionKey = option2.attributeName();
2547
- const optionValue = this.getOptionValue(optionKey);
2548
- const negativeOption = this.options.find(
2549
- (target) => target.negate && optionKey === target.attributeName()
2550
- );
2551
- const positiveOption = this.options.find(
2552
- (target) => !target.negate && optionKey === target.attributeName()
2553
- );
2554
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2555
- return negativeOption;
2556
- }
2557
- return positiveOption || option2;
2558
- };
2559
- const getErrorMessage = (option2) => {
2560
- const bestOption = findBestOptionFromValue(option2);
2561
- const optionKey = bestOption.attributeName();
2562
- const source = this.getOptionValueSource(optionKey);
2563
- if (source === "env") {
2564
- return `environment variable '${bestOption.envVar}'`;
2565
- }
2566
- return `option '${bestOption.flags}'`;
2567
- };
2568
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2569
- this.error(message, { code: "commander.conflictingOption" });
2570
- }
2571
- /**
2572
- * Unknown option `flag`.
2573
- *
2574
- * @param {string} flag
2575
- * @private
2576
- */
2577
- unknownOption(flag) {
2578
- if (this._allowUnknownOption) return;
2579
- let suggestion = "";
2580
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2581
- let candidateFlags = [];
2582
- let command = this;
2583
- do {
2584
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2585
- candidateFlags = candidateFlags.concat(moreFlags);
2586
- command = command.parent;
2587
- } while (command && !command._enablePositionalOptions);
2588
- suggestion = suggestSimilar(flag, candidateFlags);
2589
- }
2590
- const message = `error: unknown option '${flag}'${suggestion}`;
2591
- this.error(message, { code: "commander.unknownOption" });
2592
- }
2593
- /**
2594
- * Excess arguments, more than expected.
2595
- *
2596
- * @param {string[]} receivedArgs
2597
- * @private
2598
- */
2599
- _excessArguments(receivedArgs) {
2600
- if (this._allowExcessArguments) return;
2601
- const expected = this.registeredArguments.length;
2602
- const s = expected === 1 ? "" : "s";
2603
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2604
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2605
- this.error(message, { code: "commander.excessArguments" });
2606
- }
2607
- /**
2608
- * Unknown command.
2609
- *
2610
- * @private
2611
- */
2612
- unknownCommand() {
2613
- const unknownName = this.args[0];
2614
- let suggestion = "";
2615
- if (this._showSuggestionAfterError) {
2616
- const candidateNames = [];
2617
- this.createHelp().visibleCommands(this).forEach((command) => {
2618
- candidateNames.push(command.name());
2619
- if (command.alias()) candidateNames.push(command.alias());
2620
- });
2621
- suggestion = suggestSimilar(unknownName, candidateNames);
2622
- }
2623
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2624
- this.error(message, { code: "commander.unknownCommand" });
2625
- }
2626
- /**
2627
- * Get or set the program version.
2628
- *
2629
- * This method auto-registers the "-V, --version" option which will print the version number.
2630
- *
2631
- * You can optionally supply the flags and description to override the defaults.
2632
- *
2633
- * @param {string} [str]
2634
- * @param {string} [flags]
2635
- * @param {string} [description]
2636
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2637
- */
2638
- version(str, flags, description) {
2639
- if (str === void 0) return this._version;
2640
- this._version = str;
2641
- flags = flags || "-V, --version";
2642
- description = description || "output the version number";
2643
- const versionOption = this.createOption(flags, description);
2644
- this._versionOptionName = versionOption.attributeName();
2645
- this._registerOption(versionOption);
2646
- this.on("option:" + versionOption.name(), () => {
2647
- this._outputConfiguration.writeOut(`${str}
2648
- `);
2649
- this._exit(0, "commander.version", str);
2650
- });
2651
- return this;
2652
- }
2653
- /**
2654
- * Set the description.
2655
- *
2656
- * @param {string} [str]
2657
- * @param {object} [argsDescription]
2658
- * @return {(string|Command)}
2659
- */
2660
- description(str, argsDescription) {
2661
- if (str === void 0 && argsDescription === void 0)
2662
- return this._description;
2663
- this._description = str;
2664
- if (argsDescription) {
2665
- this._argsDescription = argsDescription;
2666
- }
2667
- return this;
2668
- }
2669
- /**
2670
- * Set the summary. Used when listed as subcommand of parent.
2671
- *
2672
- * @param {string} [str]
2673
- * @return {(string|Command)}
2674
- */
2675
- summary(str) {
2676
- if (str === void 0) return this._summary;
2677
- this._summary = str;
2678
- return this;
2679
- }
2680
- /**
2681
- * Set an alias for the command.
2682
- *
2683
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2684
- *
2685
- * @param {string} [alias]
2686
- * @return {(string|Command)}
2687
- */
2688
- alias(alias) {
2689
- var _a;
2690
- if (alias === void 0) return this._aliases[0];
2691
- let command = this;
2692
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2693
- command = this.commands[this.commands.length - 1];
2694
- }
2695
- if (alias === command._name)
2696
- throw new Error("Command alias can't be the same as its name");
2697
- const matchingCommand = (_a = this.parent) == null ? void 0 : _a._findCommand(alias);
2698
- if (matchingCommand) {
2699
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2700
- throw new Error(
2701
- `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2702
- );
2703
- }
2704
- command._aliases.push(alias);
2705
- return this;
2706
- }
2707
- /**
2708
- * Set aliases for the command.
2709
- *
2710
- * Only the first alias is shown in the auto-generated help.
2711
- *
2712
- * @param {string[]} [aliases]
2713
- * @return {(string[]|Command)}
2714
- */
2715
- aliases(aliases) {
2716
- if (aliases === void 0) return this._aliases;
2717
- aliases.forEach((alias) => this.alias(alias));
2718
- return this;
2719
- }
2720
- /**
2721
- * Set / get the command usage `str`.
2722
- *
2723
- * @param {string} [str]
2724
- * @return {(string|Command)}
2725
- */
2726
- usage(str) {
2727
- if (str === void 0) {
2728
- if (this._usage) return this._usage;
2729
- const args = this.registeredArguments.map((arg) => {
2730
- return humanReadableArgName(arg);
2731
- });
2732
- return [].concat(
2733
- this.options.length || this._helpOption !== null ? "[options]" : [],
2734
- this.commands.length ? "[command]" : [],
2735
- this.registeredArguments.length ? args : []
2736
- ).join(" ");
2737
- }
2738
- this._usage = str;
2739
- return this;
2740
- }
2741
- /**
2742
- * Get or set the name of the command.
2743
- *
2744
- * @param {string} [str]
2745
- * @return {(string|Command)}
2746
- */
2747
- name(str) {
2748
- if (str === void 0) return this._name;
2749
- this._name = str;
2750
- return this;
2751
- }
2752
- /**
2753
- * Set the name of the command from script filename, such as process.argv[1],
2754
- * or require.main.filename, or __filename.
2755
- *
2756
- * (Used internally and public although not documented in README.)
2757
- *
2758
- * @example
2759
- * program.nameFromFilename(require.main.filename);
2760
- *
2761
- * @param {string} filename
2762
- * @return {Command}
2763
- */
2764
- nameFromFilename(filename) {
2765
- this._name = path2.basename(filename, path2.extname(filename));
2766
- return this;
2767
- }
2768
- /**
2769
- * Get or set the directory for searching for executable subcommands of this command.
2770
- *
2771
- * @example
2772
- * program.executableDir(__dirname);
2773
- * // or
2774
- * program.executableDir('subcommands');
2775
- *
2776
- * @param {string} [path]
2777
- * @return {(string|null|Command)}
2778
- */
2779
- executableDir(path3) {
2780
- if (path3 === void 0) return this._executableDir;
2781
- this._executableDir = path3;
2782
- return this;
2783
- }
2784
- /**
2785
- * Return program help documentation.
2786
- *
2787
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2788
- * @return {string}
2789
- */
2790
- helpInformation(contextOptions) {
2791
- const helper = this.createHelp();
2792
- if (helper.helpWidth === void 0) {
2793
- helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2794
- }
2795
- return helper.formatHelp(this, helper);
2796
- }
2797
- /**
2798
- * @private
2799
- */
2800
- _getHelpContext(contextOptions) {
2801
- contextOptions = contextOptions || {};
2802
- const context = { error: !!contextOptions.error };
2803
- let write;
2804
- if (context.error) {
2805
- write = (arg) => this._outputConfiguration.writeErr(arg);
2806
- } else {
2807
- write = (arg) => this._outputConfiguration.writeOut(arg);
2808
- }
2809
- context.write = contextOptions.write || write;
2810
- context.command = this;
2811
- return context;
2812
- }
2813
- /**
2814
- * Output help information for this command.
2815
- *
2816
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2817
- *
2818
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2819
- */
2820
- outputHelp(contextOptions) {
2821
- var _a;
2822
- let deprecatedCallback;
2823
- if (typeof contextOptions === "function") {
2824
- deprecatedCallback = contextOptions;
2825
- contextOptions = void 0;
2826
- }
2827
- const context = this._getHelpContext(contextOptions);
2828
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2829
- this.emit("beforeHelp", context);
2830
- let helpInformation = this.helpInformation(context);
2831
- if (deprecatedCallback) {
2832
- helpInformation = deprecatedCallback(helpInformation);
2833
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2834
- throw new Error("outputHelp callback must return a string or a Buffer");
2835
- }
2836
- }
2837
- context.write(helpInformation);
2838
- if ((_a = this._getHelpOption()) == null ? void 0 : _a.long) {
2839
- this.emit(this._getHelpOption().long);
2840
- }
2841
- this.emit("afterHelp", context);
2842
- this._getCommandAndAncestors().forEach(
2843
- (command) => command.emit("afterAllHelp", context)
2844
- );
2845
- }
2846
- /**
2847
- * You can pass in flags and a description to customise the built-in help option.
2848
- * Pass in false to disable the built-in help option.
2849
- *
2850
- * @example
2851
- * program.helpOption('-?, --help' 'show help'); // customise
2852
- * program.helpOption(false); // disable
2853
- *
2854
- * @param {(string | boolean)} flags
2855
- * @param {string} [description]
2856
- * @return {Command} `this` command for chaining
2857
- */
2858
- helpOption(flags, description) {
2859
- if (typeof flags === "boolean") {
2860
- if (flags) {
2861
- this._helpOption = this._helpOption ?? void 0;
2862
- } else {
2863
- this._helpOption = null;
2864
- }
2865
- return this;
2866
- }
2867
- flags = flags ?? "-h, --help";
2868
- description = description ?? "display help for command";
2869
- this._helpOption = this.createOption(flags, description);
2870
- return this;
2871
- }
2872
- /**
2873
- * Lazy create help option.
2874
- * Returns null if has been disabled with .helpOption(false).
2875
- *
2876
- * @returns {(Option | null)} the help option
2877
- * @package
2878
- */
2879
- _getHelpOption() {
2880
- if (this._helpOption === void 0) {
2881
- this.helpOption(void 0, void 0);
2882
- }
2883
- return this._helpOption;
2884
- }
2885
- /**
2886
- * Supply your own option to use for the built-in help option.
2887
- * This is an alternative to using helpOption() to customise the flags and description etc.
2888
- *
2889
- * @param {Option} option
2890
- * @return {Command} `this` command for chaining
2891
- */
2892
- addHelpOption(option) {
2893
- this._helpOption = option;
2894
- return this;
2895
- }
2896
- /**
2897
- * Output help information and exit.
2898
- *
2899
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2900
- *
2901
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2902
- */
2903
- help(contextOptions) {
2904
- this.outputHelp(contextOptions);
2905
- let exitCode = process2.exitCode || 0;
2906
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2907
- exitCode = 1;
2908
- }
2909
- this._exit(exitCode, "commander.help", "(outputHelp)");
2910
- }
2911
- /**
2912
- * Add additional text to be displayed with the built-in help.
2913
- *
2914
- * Position is 'before' or 'after' to affect just this command,
2915
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2916
- *
2917
- * @param {string} position - before or after built-in help
2918
- * @param {(string | Function)} text - string to add, or a function returning a string
2919
- * @return {Command} `this` command for chaining
2920
- */
2921
- addHelpText(position, text) {
2922
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2923
- if (!allowedValues.includes(position)) {
2924
- throw new Error(`Unexpected value for position to addHelpText.
2925
- Expecting one of '${allowedValues.join("', '")}'`);
2926
- }
2927
- const helpEvent = `${position}Help`;
2928
- this.on(helpEvent, (context) => {
2929
- let helpStr;
2930
- if (typeof text === "function") {
2931
- helpStr = text({ error: context.error, command: context.command });
2932
- } else {
2933
- helpStr = text;
2934
- }
2935
- if (helpStr) {
2936
- context.write(`${helpStr}
2937
- `);
2938
- }
2939
- });
2940
- return this;
2941
- }
2942
- /**
2943
- * Output help information if help flags specified
2944
- *
2945
- * @param {Array} args - array of options to search for help flags
2946
- * @private
2947
- */
2948
- _outputHelpIfRequested(args) {
2949
- const helpOption = this._getHelpOption();
2950
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2951
- if (helpRequested) {
2952
- this.outputHelp();
2953
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2954
- }
2955
- }
2956
- };
2957
- function incrementNodeInspectorPort(args) {
2958
- return args.map((arg) => {
2959
- if (!arg.startsWith("--inspect")) {
2960
- return arg;
2961
- }
2962
- let debugOption;
2963
- let debugHost = "127.0.0.1";
2964
- let debugPort = "9229";
2965
- let match;
2966
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2967
- debugOption = match[1];
2968
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2969
- debugOption = match[1];
2970
- if (/^\d+$/.test(match[3])) {
2971
- debugPort = match[3];
2972
- } else {
2973
- debugHost = match[3];
2974
- }
2975
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2976
- debugOption = match[1];
2977
- debugHost = match[3];
2978
- debugPort = match[4];
2979
- }
2980
- if (debugOption && debugPort !== "0") {
2981
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2982
- }
2983
- return arg;
2984
- });
2985
- }
2986
- exports.Command = Command2;
2987
- }
2988
- });
2989
-
2990
- // node_modules/commander/index.js
2991
- var require_commander = __commonJS({
2992
- "node_modules/commander/index.js"(exports) {
2993
- var { Argument: Argument2 } = require_argument();
2994
- var { Command: Command2 } = require_command();
2995
- var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2996
- var { Help: Help2 } = require_help();
2997
- var { Option: Option2 } = require_option();
2998
- exports.program = new Command2();
2999
- exports.createCommand = (name) => new Command2(name);
3000
- exports.createOption = (flags, description) => new Option2(flags, description);
3001
- exports.createArgument = (name, description) => new Argument2(name, description);
3002
- exports.Command = Command2;
3003
- exports.Option = Option2;
3004
- exports.Argument = Argument2;
3005
- exports.Help = Help2;
3006
- exports.CommanderError = CommanderError2;
3007
- exports.InvalidArgumentError = InvalidArgumentError2;
3008
- exports.InvalidOptionArgumentError = InvalidArgumentError2;
3009
- }
3010
- });
3011
-
3012
- // node_modules/commander/esm.mjs
3013
- var import_index = __toESM(require_commander(), 1);
3014
- var {
3015
- program,
3016
- createCommand,
3017
- createArgument,
3018
- createOption,
3019
- CommanderError,
3020
- InvalidArgumentError,
3021
- InvalidOptionArgumentError,
3022
- // deprecated old name
3023
- Command,
3024
- Argument,
3025
- Option,
3026
- Help
3027
- } = import_index.default;
3028
-
3029
- // packages/cli/src/commands/init.ts
3030
- import * as fs from "fs";
3031
- import * as path from "path";
3032
- function initCommand(options) {
3033
- const dir = options.dir ?? process.cwd();
3034
- const filePath = path.join(dir, "DECISIONS.toon");
3035
- if (fs.existsSync(filePath)) {
3036
- console.error(`Hata: ${filePath} zaten mevcut.`);
3037
- process.exit(1);
3038
- }
3039
- const projectName = options.project ?? path.basename(dir);
3040
- initDecisionFile(filePath, projectName);
3041
- const gitattributes = path.join(dir, ".gitattributes");
3042
- const entry = "DECISIONS.toon text eol=lf\n";
3043
- if (fs.existsSync(gitattributes)) {
3044
- const content = fs.readFileSync(gitattributes, "utf-8");
3045
- if (!content.includes("DECISIONS.toon")) {
3046
- fs.appendFileSync(gitattributes, entry);
3047
- }
3048
- } else {
3049
- fs.writeFileSync(gitattributes, entry);
3050
- }
3051
- console.log(`\u2713 ${filePath} olu\u015Fturuldu.`);
3052
- console.log(`\u2713 .gitattributes g\xFCncellendi.`);
3053
- console.log(`
3054
- Ba\u015Flamak i\xE7in:`);
3055
- console.log(` decision-memory log # yeni karar ekle`);
3056
- console.log(` decision-memory summary # \xF6zet g\xF6r\xFCnt\xFCle`);
3057
- }
3058
-
3059
- // packages/cli/src/commands/log.ts
3060
- import * as readline from "readline/promises";
3061
- import { stdin as input, stdout as output } from "process";
3062
- async function logCommand(options) {
3063
- if (options.topic && options.decision && options.rationale && options.impact) {
3064
- const inp = buildInput(options);
3065
- const filePath = options.file ?? resolveDecisionFilePath();
3066
- const entry = appendDecision(filePath, inp);
3067
- console.log(`\u2713 Karar kaydedildi: ${entry.id} \u2014 ${entry.decision}`);
3068
- return;
3069
- }
3070
- const rl = readline.createInterface({ input, output });
3071
- try {
3072
- const topic = options.topic ?? await rl.question("Konu (\xF6rn: auth, database): ");
3073
- const decision = options.decision ?? await rl.question("Al\u0131nan karar: ");
3074
- const rationale = options.rationale ?? await rl.question("Gerek\xE7e: ");
3075
- const impactRaw = options.impact ?? await rl.question("Etki (low/medium/high/critical) [medium]: ");
3076
- const tagsRaw = options.tags ?? await rl.question("Etiketler (virg\xFClle, \xF6rn: auth,jwt) []: ");
3077
- const filled = {
3078
- topic: topic.trim() || void 0,
3079
- decision: decision.trim() || void 0,
3080
- rationale: rationale.trim() || void 0,
3081
- impact: impactRaw.trim() || "medium",
3082
- tags: tagsRaw.trim()
3083
- };
3084
- if (!filled.topic || !filled.decision || !filled.rationale) {
3085
- console.error("Hata: Konu, karar ve gerek\xE7e zorunludur.");
3086
- process.exit(1);
3087
- }
3088
- const decisionInput = buildInput(filled);
3089
- const filePath = options.file ?? resolveDecisionFilePath();
3090
- const entry = appendDecision(filePath, decisionInput);
3091
- console.log(`
3092
- \u2713 Karar kaydedildi: ${entry.id} \u2014 ${entry.decision}`);
3093
- } finally {
3094
- rl.close();
3095
- }
3096
- }
3097
- function buildInput(options) {
3098
- const validImpacts = ["low", "medium", "high", "critical"];
3099
- const impact = validImpacts.includes(options.impact) ? options.impact : "medium";
3100
- const tags = options.tags ? options.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];
3101
- return {
3102
- topic: options.topic.trim(),
3103
- decision: options.decision.trim(),
3104
- rationale: options.rationale.trim(),
3105
- impact,
3106
- tags
3107
- };
3108
- }
3109
-
3110
- // packages/cli/src/commands/search.ts
3111
- import * as fs2 from "fs";
3112
- function searchCommand(options) {
3113
- const filePath = options.file ?? resolveDecisionFilePath();
3114
- if (!fs2.existsSync(filePath)) {
3115
- console.error(`Hata: ${filePath} bulunamad\u0131. \xD6nce 'decision-memory init' \xE7al\u0131\u015Ft\u0131r\u0131n.`);
3116
- process.exit(1);
3117
- }
3118
- const content = fs2.readFileSync(filePath, "utf-8");
3119
- const file = parseDecisionFile(content);
3120
- const keywords = options.keywords ? options.keywords.split(",").map((k) => k.trim()).filter(Boolean) : [];
3121
- const tags = options.tags ? options.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];
3122
- const validImpacts = ["low", "medium", "high", "critical"];
3123
- const impact = validImpacts.includes(options.impact) ? options.impact : void 0;
3124
- const limit = options.limit ? parseInt(options.limit, 10) : 5;
3125
- const results = searchDecisions(file, { keywords, tags, impact, limit });
3126
- if (results.length === 0) {
3127
- console.log("E\u015Fle\u015Fen karar bulunamad\u0131.");
3128
- return;
3129
- }
3130
- console.log(`decisions[${results.length}]{id,ts,topic,decision,rationale,impact,tags}:`);
3131
- for (const r of results) {
3132
- console.log(serializeDecisionRow(r.decision));
3133
- }
3134
- }
3135
-
3136
- // packages/cli/src/commands/summary.ts
3137
- import * as fs3 from "fs";
3138
- function summaryCommand(options) {
3139
- const filePath = options.file ?? resolveDecisionFilePath();
3140
- if (!fs3.existsSync(filePath)) {
3141
- console.error(`Hata: ${filePath} bulunamad\u0131. \xD6nce 'decision-memory init' \xE7al\u0131\u015Ft\u0131r\u0131n.`);
3142
- process.exit(1);
3143
- }
3144
- const content = fs3.readFileSync(filePath, "utf-8");
3145
- const file = parseDecisionFile(content);
3146
- const output2 = formatContextSummaryAsToon(file, !options.noRecent);
3147
- console.log(output2);
3148
- }
3149
-
3150
- // packages/cli/src/index.ts
3151
- var program2 = new Command();
3152
- program2.name("decision-memory").description("Claude Code i\xE7in karar haf\u0131zas\u0131 arac\u0131").version("0.1.0");
3153
- program2.command("init").description("Proje k\xF6k\xFCnde DECISIONS.toon dosyas\u0131 olu\u015Fturur").option("-p, --project <name>", "Proje ad\u0131").option("-d, --dir <path>", "Dizin (varsay\u0131lan: \xE7al\u0131\u015Fma dizini)").action((options) => initCommand(options));
3154
- program2.command("log").description("Yeni bir karar ekler (interaktif veya flag'lerle)").option("-t, --topic <topic>", "Konu (\xF6rn: auth, database)").option("-d, --decision <text>", "Al\u0131nan karar").option("-r, --rationale <text>", "Gerek\xE7e").option("-i, --impact <level>", "Etki: low|medium|high|critical").option("--tags <tags>", "Etiketler (virg\xFClle ayr\u0131lm\u0131\u015F)").option("-f, --file <path>", "DECISIONS.toon dosya yolu").action(async (options) => {
3155
- await logCommand(options);
3156
- });
3157
- program2.command("search").description("Ge\xE7mi\u015F kararlarda arama yapar").option("-k, --keywords <words>", "Anahtar kelimeler (virg\xFClle ayr\u0131lm\u0131\u015F)").option("--tags <tags>", "Etiketler (virg\xFClle ayr\u0131lm\u0131\u015F)").option("--impact <level>", "Etki filtresi: low|medium|high|critical").option("-n, --limit <n>", "Maksimum sonu\xE7 say\u0131s\u0131", "5").option("-f, --file <path>", "DECISIONS.toon dosya yolu").action((options) => searchCommand(options));
3158
- program2.command("summary").description("Kararlar\u0131n \xF6zetini g\xF6r\xFCnt\xFCler").option("--no-recent", "Son kararlar\u0131 dahil etme").option("-f, --file <path>", "DECISIONS.toon dosya yolu").action((options) => summaryCommand(options));
3159
- program2.parse();