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