@huitl/sdk 0.1.0

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