exomind 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,4021 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // node_modules/commander/lib/error.js
30
+ var require_error = __commonJS({
31
+ "node_modules/commander/lib/error.js"(exports2) {
32
+ "use strict";
33
+ var CommanderError2 = class extends Error {
34
+ /**
35
+ * Constructs the CommanderError class
36
+ * @param {number} exitCode suggested exit code which could be used with process.exit
37
+ * @param {string} code an id string representing the error
38
+ * @param {string} message human-readable description of the error
39
+ */
40
+ constructor(exitCode, code, message) {
41
+ super(message);
42
+ Error.captureStackTrace(this, this.constructor);
43
+ this.name = this.constructor.name;
44
+ this.code = code;
45
+ this.exitCode = exitCode;
46
+ this.nestedError = void 0;
47
+ }
48
+ };
49
+ var InvalidArgumentError2 = class extends CommanderError2 {
50
+ /**
51
+ * Constructs the InvalidArgumentError class
52
+ * @param {string} [message] explanation of why argument is invalid
53
+ */
54
+ constructor(message) {
55
+ super(1, "commander.invalidArgument", message);
56
+ Error.captureStackTrace(this, this.constructor);
57
+ this.name = this.constructor.name;
58
+ }
59
+ };
60
+ exports2.CommanderError = CommanderError2;
61
+ exports2.InvalidArgumentError = InvalidArgumentError2;
62
+ }
63
+ });
64
+
65
+ // node_modules/commander/lib/argument.js
66
+ var require_argument = __commonJS({
67
+ "node_modules/commander/lib/argument.js"(exports2) {
68
+ "use strict";
69
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
70
+ var Argument2 = class {
71
+ /**
72
+ * Initialize a new command argument with the given name and description.
73
+ * The default is that the argument is required, and you can explicitly
74
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
75
+ *
76
+ * @param {string} name
77
+ * @param {string} [description]
78
+ */
79
+ constructor(name, description) {
80
+ this.description = description || "";
81
+ this.variadic = false;
82
+ this.parseArg = void 0;
83
+ this.defaultValue = void 0;
84
+ this.defaultValueDescription = void 0;
85
+ this.argChoices = void 0;
86
+ switch (name[0]) {
87
+ case "<":
88
+ this.required = true;
89
+ this._name = name.slice(1, -1);
90
+ break;
91
+ case "[":
92
+ this.required = false;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ default:
96
+ this.required = true;
97
+ this._name = name;
98
+ break;
99
+ }
100
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
101
+ this.variadic = true;
102
+ this._name = this._name.slice(0, -3);
103
+ }
104
+ }
105
+ /**
106
+ * Return argument name.
107
+ *
108
+ * @return {string}
109
+ */
110
+ name() {
111
+ return this._name;
112
+ }
113
+ /**
114
+ * @package
115
+ */
116
+ _concatValue(value, previous) {
117
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
118
+ return [value];
119
+ }
120
+ return previous.concat(value);
121
+ }
122
+ /**
123
+ * Set the default value, and optionally supply the description to be displayed in the help.
124
+ *
125
+ * @param {*} value
126
+ * @param {string} [description]
127
+ * @return {Argument}
128
+ */
129
+ default(value, description) {
130
+ this.defaultValue = value;
131
+ this.defaultValueDescription = description;
132
+ return this;
133
+ }
134
+ /**
135
+ * Set the custom handler for processing CLI command arguments into argument values.
136
+ *
137
+ * @param {Function} [fn]
138
+ * @return {Argument}
139
+ */
140
+ argParser(fn) {
141
+ this.parseArg = fn;
142
+ return this;
143
+ }
144
+ /**
145
+ * Only allow argument value to be one of choices.
146
+ *
147
+ * @param {string[]} values
148
+ * @return {Argument}
149
+ */
150
+ choices(values) {
151
+ this.argChoices = values.slice();
152
+ this.parseArg = (arg, previous) => {
153
+ if (!this.argChoices.includes(arg)) {
154
+ throw new InvalidArgumentError2(
155
+ `Allowed choices are ${this.argChoices.join(", ")}.`
156
+ );
157
+ }
158
+ if (this.variadic) {
159
+ return this._concatValue(arg, previous);
160
+ }
161
+ return arg;
162
+ };
163
+ return this;
164
+ }
165
+ /**
166
+ * Make argument required.
167
+ *
168
+ * @returns {Argument}
169
+ */
170
+ argRequired() {
171
+ this.required = true;
172
+ return this;
173
+ }
174
+ /**
175
+ * Make argument optional.
176
+ *
177
+ * @returns {Argument}
178
+ */
179
+ argOptional() {
180
+ this.required = false;
181
+ return this;
182
+ }
183
+ };
184
+ function humanReadableArgName(arg) {
185
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
186
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
187
+ }
188
+ exports2.Argument = Argument2;
189
+ exports2.humanReadableArgName = humanReadableArgName;
190
+ }
191
+ });
192
+
193
+ // node_modules/commander/lib/help.js
194
+ var require_help = __commonJS({
195
+ "node_modules/commander/lib/help.js"(exports2) {
196
+ "use strict";
197
+ var { humanReadableArgName } = require_argument();
198
+ var Help2 = class {
199
+ constructor() {
200
+ this.helpWidth = void 0;
201
+ this.sortSubcommands = false;
202
+ this.sortOptions = false;
203
+ this.showGlobalOptions = false;
204
+ }
205
+ /**
206
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
207
+ *
208
+ * @param {Command} cmd
209
+ * @returns {Command[]}
210
+ */
211
+ visibleCommands(cmd) {
212
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
213
+ const helpCommand = cmd._getHelpCommand();
214
+ if (helpCommand && !helpCommand._hidden) {
215
+ visibleCommands.push(helpCommand);
216
+ }
217
+ if (this.sortSubcommands) {
218
+ visibleCommands.sort((a, b) => {
219
+ return a.name().localeCompare(b.name());
220
+ });
221
+ }
222
+ return visibleCommands;
223
+ }
224
+ /**
225
+ * Compare options for sort.
226
+ *
227
+ * @param {Option} a
228
+ * @param {Option} b
229
+ * @returns {number}
230
+ */
231
+ compareOptions(a, b) {
232
+ const getSortKey = (option) => {
233
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
234
+ };
235
+ return getSortKey(a).localeCompare(getSortKey(b));
236
+ }
237
+ /**
238
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
239
+ *
240
+ * @param {Command} cmd
241
+ * @returns {Option[]}
242
+ */
243
+ visibleOptions(cmd) {
244
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
245
+ const helpOption = cmd._getHelpOption();
246
+ if (helpOption && !helpOption.hidden) {
247
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
248
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
249
+ if (!removeShort && !removeLong) {
250
+ visibleOptions.push(helpOption);
251
+ } else if (helpOption.long && !removeLong) {
252
+ visibleOptions.push(
253
+ cmd.createOption(helpOption.long, helpOption.description)
254
+ );
255
+ } else if (helpOption.short && !removeShort) {
256
+ visibleOptions.push(
257
+ cmd.createOption(helpOption.short, helpOption.description)
258
+ );
259
+ }
260
+ }
261
+ if (this.sortOptions) {
262
+ visibleOptions.sort(this.compareOptions);
263
+ }
264
+ return visibleOptions;
265
+ }
266
+ /**
267
+ * Get an array of the visible global options. (Not including help.)
268
+ *
269
+ * @param {Command} cmd
270
+ * @returns {Option[]}
271
+ */
272
+ visibleGlobalOptions(cmd) {
273
+ if (!this.showGlobalOptions) return [];
274
+ const globalOptions = [];
275
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
276
+ const visibleOptions = ancestorCmd.options.filter(
277
+ (option) => !option.hidden
278
+ );
279
+ globalOptions.push(...visibleOptions);
280
+ }
281
+ if (this.sortOptions) {
282
+ globalOptions.sort(this.compareOptions);
283
+ }
284
+ return globalOptions;
285
+ }
286
+ /**
287
+ * Get an array of the arguments if any have a description.
288
+ *
289
+ * @param {Command} cmd
290
+ * @returns {Argument[]}
291
+ */
292
+ visibleArguments(cmd) {
293
+ if (cmd._argsDescription) {
294
+ cmd.registeredArguments.forEach((argument) => {
295
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
296
+ });
297
+ }
298
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
299
+ return cmd.registeredArguments;
300
+ }
301
+ return [];
302
+ }
303
+ /**
304
+ * Get the command term to show in the list of subcommands.
305
+ *
306
+ * @param {Command} cmd
307
+ * @returns {string}
308
+ */
309
+ subcommandTerm(cmd) {
310
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
311
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
312
+ (args ? " " + args : "");
313
+ }
314
+ /**
315
+ * Get the option term to show in the list of options.
316
+ *
317
+ * @param {Option} option
318
+ * @returns {string}
319
+ */
320
+ optionTerm(option) {
321
+ return option.flags;
322
+ }
323
+ /**
324
+ * Get the argument term to show in the list of arguments.
325
+ *
326
+ * @param {Argument} argument
327
+ * @returns {string}
328
+ */
329
+ argumentTerm(argument) {
330
+ return argument.name();
331
+ }
332
+ /**
333
+ * Get the longest command term length.
334
+ *
335
+ * @param {Command} cmd
336
+ * @param {Help} helper
337
+ * @returns {number}
338
+ */
339
+ longestSubcommandTermLength(cmd, helper) {
340
+ return helper.visibleCommands(cmd).reduce((max, command) => {
341
+ return Math.max(max, helper.subcommandTerm(command).length);
342
+ }, 0);
343
+ }
344
+ /**
345
+ * Get the longest option term length.
346
+ *
347
+ * @param {Command} cmd
348
+ * @param {Help} helper
349
+ * @returns {number}
350
+ */
351
+ longestOptionTermLength(cmd, helper) {
352
+ return helper.visibleOptions(cmd).reduce((max, option) => {
353
+ return Math.max(max, helper.optionTerm(option).length);
354
+ }, 0);
355
+ }
356
+ /**
357
+ * Get the longest global option term length.
358
+ *
359
+ * @param {Command} cmd
360
+ * @param {Help} helper
361
+ * @returns {number}
362
+ */
363
+ longestGlobalOptionTermLength(cmd, helper) {
364
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
365
+ return Math.max(max, helper.optionTerm(option).length);
366
+ }, 0);
367
+ }
368
+ /**
369
+ * Get the longest argument term length.
370
+ *
371
+ * @param {Command} cmd
372
+ * @param {Help} helper
373
+ * @returns {number}
374
+ */
375
+ longestArgumentTermLength(cmd, helper) {
376
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
377
+ return Math.max(max, helper.argumentTerm(argument).length);
378
+ }, 0);
379
+ }
380
+ /**
381
+ * Get the command usage to be displayed at the top of the built-in help.
382
+ *
383
+ * @param {Command} cmd
384
+ * @returns {string}
385
+ */
386
+ commandUsage(cmd) {
387
+ let cmdName = cmd._name;
388
+ if (cmd._aliases[0]) {
389
+ cmdName = cmdName + "|" + cmd._aliases[0];
390
+ }
391
+ let ancestorCmdNames = "";
392
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
393
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
394
+ }
395
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
396
+ }
397
+ /**
398
+ * Get the description for the command.
399
+ *
400
+ * @param {Command} cmd
401
+ * @returns {string}
402
+ */
403
+ commandDescription(cmd) {
404
+ return cmd.description();
405
+ }
406
+ /**
407
+ * Get the subcommand summary to show in the list of subcommands.
408
+ * (Fallback to description for backwards compatibility.)
409
+ *
410
+ * @param {Command} cmd
411
+ * @returns {string}
412
+ */
413
+ subcommandDescription(cmd) {
414
+ return cmd.summary() || cmd.description();
415
+ }
416
+ /**
417
+ * Get the option description to show in the list of options.
418
+ *
419
+ * @param {Option} option
420
+ * @return {string}
421
+ */
422
+ optionDescription(option) {
423
+ const extraInfo = [];
424
+ if (option.argChoices) {
425
+ extraInfo.push(
426
+ // use stringify to match the display of the default value
427
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
428
+ );
429
+ }
430
+ if (option.defaultValue !== void 0) {
431
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
432
+ if (showDefault) {
433
+ extraInfo.push(
434
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
435
+ );
436
+ }
437
+ }
438
+ if (option.presetArg !== void 0 && option.optional) {
439
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
440
+ }
441
+ if (option.envVar !== void 0) {
442
+ extraInfo.push(`env: ${option.envVar}`);
443
+ }
444
+ if (extraInfo.length > 0) {
445
+ return `${option.description} (${extraInfo.join(", ")})`;
446
+ }
447
+ return option.description;
448
+ }
449
+ /**
450
+ * Get the argument description to show in the list of arguments.
451
+ *
452
+ * @param {Argument} argument
453
+ * @return {string}
454
+ */
455
+ argumentDescription(argument) {
456
+ const extraInfo = [];
457
+ if (argument.argChoices) {
458
+ extraInfo.push(
459
+ // use stringify to match the display of the default value
460
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
461
+ );
462
+ }
463
+ if (argument.defaultValue !== void 0) {
464
+ extraInfo.push(
465
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
466
+ );
467
+ }
468
+ if (extraInfo.length > 0) {
469
+ const extraDescripton = `(${extraInfo.join(", ")})`;
470
+ if (argument.description) {
471
+ return `${argument.description} ${extraDescripton}`;
472
+ }
473
+ return extraDescripton;
474
+ }
475
+ return argument.description;
476
+ }
477
+ /**
478
+ * Generate the built-in help text.
479
+ *
480
+ * @param {Command} cmd
481
+ * @param {Help} helper
482
+ * @returns {string}
483
+ */
484
+ formatHelp(cmd, helper) {
485
+ const termWidth = helper.padWidth(cmd, helper);
486
+ const helpWidth = helper.helpWidth || 80;
487
+ const itemIndentWidth = 2;
488
+ const itemSeparatorWidth = 2;
489
+ function formatItem(term, description) {
490
+ if (description) {
491
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
492
+ return helper.wrap(
493
+ fullText,
494
+ helpWidth - itemIndentWidth,
495
+ termWidth + itemSeparatorWidth
496
+ );
497
+ }
498
+ return term;
499
+ }
500
+ function formatList(textArray) {
501
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
502
+ }
503
+ let output3 = [`Usage: ${helper.commandUsage(cmd)}`, ""];
504
+ const commandDescription = helper.commandDescription(cmd);
505
+ if (commandDescription.length > 0) {
506
+ output3 = output3.concat([
507
+ helper.wrap(commandDescription, helpWidth, 0),
508
+ ""
509
+ ]);
510
+ }
511
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
512
+ return formatItem(
513
+ helper.argumentTerm(argument),
514
+ helper.argumentDescription(argument)
515
+ );
516
+ });
517
+ if (argumentList.length > 0) {
518
+ output3 = output3.concat(["Arguments:", formatList(argumentList), ""]);
519
+ }
520
+ const optionList = helper.visibleOptions(cmd).map((option) => {
521
+ return formatItem(
522
+ helper.optionTerm(option),
523
+ helper.optionDescription(option)
524
+ );
525
+ });
526
+ if (optionList.length > 0) {
527
+ output3 = output3.concat(["Options:", formatList(optionList), ""]);
528
+ }
529
+ if (this.showGlobalOptions) {
530
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
531
+ return formatItem(
532
+ helper.optionTerm(option),
533
+ helper.optionDescription(option)
534
+ );
535
+ });
536
+ if (globalOptionList.length > 0) {
537
+ output3 = output3.concat([
538
+ "Global Options:",
539
+ formatList(globalOptionList),
540
+ ""
541
+ ]);
542
+ }
543
+ }
544
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
545
+ return formatItem(
546
+ helper.subcommandTerm(cmd2),
547
+ helper.subcommandDescription(cmd2)
548
+ );
549
+ });
550
+ if (commandList.length > 0) {
551
+ output3 = output3.concat(["Commands:", formatList(commandList), ""]);
552
+ }
553
+ return output3.join("\n");
554
+ }
555
+ /**
556
+ * Calculate the pad width from the maximum term length.
557
+ *
558
+ * @param {Command} cmd
559
+ * @param {Help} helper
560
+ * @returns {number}
561
+ */
562
+ padWidth(cmd, helper) {
563
+ return Math.max(
564
+ helper.longestOptionTermLength(cmd, helper),
565
+ helper.longestGlobalOptionTermLength(cmd, helper),
566
+ helper.longestSubcommandTermLength(cmd, helper),
567
+ helper.longestArgumentTermLength(cmd, helper)
568
+ );
569
+ }
570
+ /**
571
+ * Wrap the given string to width characters per line, with lines after the first indented.
572
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
573
+ *
574
+ * @param {string} str
575
+ * @param {number} width
576
+ * @param {number} indent
577
+ * @param {number} [minColumnWidth=40]
578
+ * @return {string}
579
+ *
580
+ */
581
+ wrap(str, width, indent, minColumnWidth = 40) {
582
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
583
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
584
+ if (str.match(manualIndent)) return str;
585
+ const columnWidth = width - indent;
586
+ if (columnWidth < minColumnWidth) return str;
587
+ const leadingStr = str.slice(0, indent);
588
+ const columnText = str.slice(indent).replace("\r\n", "\n");
589
+ const indentString = " ".repeat(indent);
590
+ const zeroWidthSpace = "\u200B";
591
+ const breaks = `\\s${zeroWidthSpace}`;
592
+ const regex = new RegExp(
593
+ `
594
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
595
+ "g"
596
+ );
597
+ const lines = columnText.match(regex) || [];
598
+ return leadingStr + lines.map((line, i) => {
599
+ if (line === "\n") return "";
600
+ return (i > 0 ? indentString : "") + line.trimEnd();
601
+ }).join("\n");
602
+ }
603
+ };
604
+ exports2.Help = Help2;
605
+ }
606
+ });
607
+
608
+ // node_modules/commander/lib/option.js
609
+ var require_option = __commonJS({
610
+ "node_modules/commander/lib/option.js"(exports2) {
611
+ "use strict";
612
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
613
+ var Option2 = class {
614
+ /**
615
+ * Initialize a new `Option` with the given `flags` and `description`.
616
+ *
617
+ * @param {string} flags
618
+ * @param {string} [description]
619
+ */
620
+ constructor(flags, description) {
621
+ this.flags = flags;
622
+ this.description = description || "";
623
+ this.required = flags.includes("<");
624
+ this.optional = flags.includes("[");
625
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
626
+ this.mandatory = false;
627
+ const optionFlags = splitOptionFlags(flags);
628
+ this.short = optionFlags.shortFlag;
629
+ this.long = optionFlags.longFlag;
630
+ this.negate = false;
631
+ if (this.long) {
632
+ this.negate = this.long.startsWith("--no-");
633
+ }
634
+ this.defaultValue = void 0;
635
+ this.defaultValueDescription = void 0;
636
+ this.presetArg = void 0;
637
+ this.envVar = void 0;
638
+ this.parseArg = void 0;
639
+ this.hidden = false;
640
+ this.argChoices = void 0;
641
+ this.conflictsWith = [];
642
+ this.implied = void 0;
643
+ }
644
+ /**
645
+ * Set the default value, and optionally supply the description to be displayed in the help.
646
+ *
647
+ * @param {*} value
648
+ * @param {string} [description]
649
+ * @return {Option}
650
+ */
651
+ default(value, description) {
652
+ this.defaultValue = value;
653
+ this.defaultValueDescription = description;
654
+ return this;
655
+ }
656
+ /**
657
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
658
+ * The custom processing (parseArg) is called.
659
+ *
660
+ * @example
661
+ * new Option('--color').default('GREYSCALE').preset('RGB');
662
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
663
+ *
664
+ * @param {*} arg
665
+ * @return {Option}
666
+ */
667
+ preset(arg) {
668
+ this.presetArg = arg;
669
+ return this;
670
+ }
671
+ /**
672
+ * Add option name(s) that conflict with this option.
673
+ * An error will be displayed if conflicting options are found during parsing.
674
+ *
675
+ * @example
676
+ * new Option('--rgb').conflicts('cmyk');
677
+ * new Option('--js').conflicts(['ts', 'jsx']);
678
+ *
679
+ * @param {(string | string[])} names
680
+ * @return {Option}
681
+ */
682
+ conflicts(names) {
683
+ this.conflictsWith = this.conflictsWith.concat(names);
684
+ return this;
685
+ }
686
+ /**
687
+ * Specify implied option values for when this option is set and the implied options are not.
688
+ *
689
+ * The custom processing (parseArg) is not called on the implied values.
690
+ *
691
+ * @example
692
+ * program
693
+ * .addOption(new Option('--log', 'write logging information to file'))
694
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
695
+ *
696
+ * @param {object} impliedOptionValues
697
+ * @return {Option}
698
+ */
699
+ implies(impliedOptionValues) {
700
+ let newImplied = impliedOptionValues;
701
+ if (typeof impliedOptionValues === "string") {
702
+ newImplied = { [impliedOptionValues]: true };
703
+ }
704
+ this.implied = Object.assign(this.implied || {}, newImplied);
705
+ return this;
706
+ }
707
+ /**
708
+ * Set environment variable to check for option value.
709
+ *
710
+ * An environment variable is only used if when processed the current option value is
711
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
712
+ *
713
+ * @param {string} name
714
+ * @return {Option}
715
+ */
716
+ env(name) {
717
+ this.envVar = name;
718
+ return this;
719
+ }
720
+ /**
721
+ * Set the custom handler for processing CLI option arguments into option values.
722
+ *
723
+ * @param {Function} [fn]
724
+ * @return {Option}
725
+ */
726
+ argParser(fn) {
727
+ this.parseArg = fn;
728
+ return this;
729
+ }
730
+ /**
731
+ * Whether the option is mandatory and must have a value after parsing.
732
+ *
733
+ * @param {boolean} [mandatory=true]
734
+ * @return {Option}
735
+ */
736
+ makeOptionMandatory(mandatory = true) {
737
+ this.mandatory = !!mandatory;
738
+ return this;
739
+ }
740
+ /**
741
+ * Hide option in help.
742
+ *
743
+ * @param {boolean} [hide=true]
744
+ * @return {Option}
745
+ */
746
+ hideHelp(hide = true) {
747
+ this.hidden = !!hide;
748
+ return this;
749
+ }
750
+ /**
751
+ * @package
752
+ */
753
+ _concatValue(value, previous) {
754
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
755
+ return [value];
756
+ }
757
+ return previous.concat(value);
758
+ }
759
+ /**
760
+ * Only allow option value to be one of choices.
761
+ *
762
+ * @param {string[]} values
763
+ * @return {Option}
764
+ */
765
+ choices(values) {
766
+ this.argChoices = values.slice();
767
+ this.parseArg = (arg, previous) => {
768
+ if (!this.argChoices.includes(arg)) {
769
+ throw new InvalidArgumentError2(
770
+ `Allowed choices are ${this.argChoices.join(", ")}.`
771
+ );
772
+ }
773
+ if (this.variadic) {
774
+ return this._concatValue(arg, previous);
775
+ }
776
+ return arg;
777
+ };
778
+ return this;
779
+ }
780
+ /**
781
+ * Return option name.
782
+ *
783
+ * @return {string}
784
+ */
785
+ name() {
786
+ if (this.long) {
787
+ return this.long.replace(/^--/, "");
788
+ }
789
+ return this.short.replace(/^-/, "");
790
+ }
791
+ /**
792
+ * Return option name, in a camelcase format that can be used
793
+ * as a object attribute key.
794
+ *
795
+ * @return {string}
796
+ */
797
+ attributeName() {
798
+ return camelcase(this.name().replace(/^no-/, ""));
799
+ }
800
+ /**
801
+ * Check if `arg` matches the short or long flag.
802
+ *
803
+ * @param {string} arg
804
+ * @return {boolean}
805
+ * @package
806
+ */
807
+ is(arg) {
808
+ return this.short === arg || this.long === arg;
809
+ }
810
+ /**
811
+ * Return whether a boolean option.
812
+ *
813
+ * Options are one of boolean, negated, required argument, or optional argument.
814
+ *
815
+ * @return {boolean}
816
+ * @package
817
+ */
818
+ isBoolean() {
819
+ return !this.required && !this.optional && !this.negate;
820
+ }
821
+ };
822
+ var DualOptions = class {
823
+ /**
824
+ * @param {Option[]} options
825
+ */
826
+ constructor(options) {
827
+ this.positiveOptions = /* @__PURE__ */ new Map();
828
+ this.negativeOptions = /* @__PURE__ */ new Map();
829
+ this.dualOptions = /* @__PURE__ */ new Set();
830
+ options.forEach((option) => {
831
+ if (option.negate) {
832
+ this.negativeOptions.set(option.attributeName(), option);
833
+ } else {
834
+ this.positiveOptions.set(option.attributeName(), option);
835
+ }
836
+ });
837
+ this.negativeOptions.forEach((value, key) => {
838
+ if (this.positiveOptions.has(key)) {
839
+ this.dualOptions.add(key);
840
+ }
841
+ });
842
+ }
843
+ /**
844
+ * Did the value come from the option, and not from possible matching dual option?
845
+ *
846
+ * @param {*} value
847
+ * @param {Option} option
848
+ * @returns {boolean}
849
+ */
850
+ valueFromOption(value, option) {
851
+ const optionKey = option.attributeName();
852
+ if (!this.dualOptions.has(optionKey)) return true;
853
+ const preset = this.negativeOptions.get(optionKey).presetArg;
854
+ const negativeValue = preset !== void 0 ? preset : false;
855
+ return option.negate === (negativeValue === value);
856
+ }
857
+ };
858
+ function camelcase(str) {
859
+ return str.split("-").reduce((str2, word) => {
860
+ return str2 + word[0].toUpperCase() + word.slice(1);
861
+ });
862
+ }
863
+ function splitOptionFlags(flags) {
864
+ let shortFlag;
865
+ let longFlag;
866
+ const flagParts = flags.split(/[ |,]+/);
867
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
868
+ shortFlag = flagParts.shift();
869
+ longFlag = flagParts.shift();
870
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
871
+ shortFlag = longFlag;
872
+ longFlag = void 0;
873
+ }
874
+ return { shortFlag, longFlag };
875
+ }
876
+ exports2.Option = Option2;
877
+ exports2.DualOptions = DualOptions;
878
+ }
879
+ });
880
+
881
+ // node_modules/commander/lib/suggestSimilar.js
882
+ var require_suggestSimilar = __commonJS({
883
+ "node_modules/commander/lib/suggestSimilar.js"(exports2) {
884
+ "use strict";
885
+ var maxDistance = 3;
886
+ function editDistance(a, b) {
887
+ if (Math.abs(a.length - b.length) > maxDistance)
888
+ return Math.max(a.length, b.length);
889
+ const d = [];
890
+ for (let i = 0; i <= a.length; i++) {
891
+ d[i] = [i];
892
+ }
893
+ for (let j = 0; j <= b.length; j++) {
894
+ d[0][j] = j;
895
+ }
896
+ for (let j = 1; j <= b.length; j++) {
897
+ for (let i = 1; i <= a.length; i++) {
898
+ let cost = 1;
899
+ if (a[i - 1] === b[j - 1]) {
900
+ cost = 0;
901
+ } else {
902
+ cost = 1;
903
+ }
904
+ d[i][j] = Math.min(
905
+ d[i - 1][j] + 1,
906
+ // deletion
907
+ d[i][j - 1] + 1,
908
+ // insertion
909
+ d[i - 1][j - 1] + cost
910
+ // substitution
911
+ );
912
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
913
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
914
+ }
915
+ }
916
+ }
917
+ return d[a.length][b.length];
918
+ }
919
+ function suggestSimilar(word, candidates) {
920
+ if (!candidates || candidates.length === 0) return "";
921
+ candidates = Array.from(new Set(candidates));
922
+ const searchingOptions = word.startsWith("--");
923
+ if (searchingOptions) {
924
+ word = word.slice(2);
925
+ candidates = candidates.map((candidate) => candidate.slice(2));
926
+ }
927
+ let similar = [];
928
+ let bestDistance = maxDistance;
929
+ const minSimilarity = 0.4;
930
+ candidates.forEach((candidate) => {
931
+ if (candidate.length <= 1) return;
932
+ const distance = editDistance(word, candidate);
933
+ const length = Math.max(word.length, candidate.length);
934
+ const similarity = (length - distance) / length;
935
+ if (similarity > minSimilarity) {
936
+ if (distance < bestDistance) {
937
+ bestDistance = distance;
938
+ similar = [candidate];
939
+ } else if (distance === bestDistance) {
940
+ similar.push(candidate);
941
+ }
942
+ }
943
+ });
944
+ similar.sort((a, b) => a.localeCompare(b));
945
+ if (searchingOptions) {
946
+ similar = similar.map((candidate) => `--${candidate}`);
947
+ }
948
+ if (similar.length > 1) {
949
+ return `
950
+ (Did you mean one of ${similar.join(", ")}?)`;
951
+ }
952
+ if (similar.length === 1) {
953
+ return `
954
+ (Did you mean ${similar[0]}?)`;
955
+ }
956
+ return "";
957
+ }
958
+ exports2.suggestSimilar = suggestSimilar;
959
+ }
960
+ });
961
+
962
+ // node_modules/commander/lib/command.js
963
+ var require_command = __commonJS({
964
+ "node_modules/commander/lib/command.js"(exports2) {
965
+ "use strict";
966
+ var EventEmitter = require("events").EventEmitter;
967
+ var childProcess = require("child_process");
968
+ var path4 = require("path");
969
+ var fs5 = require("fs");
970
+ var process2 = require("process");
971
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
972
+ var { CommanderError: CommanderError2 } = require_error();
973
+ var { Help: Help2 } = require_help();
974
+ var { Option: Option2, DualOptions } = require_option();
975
+ var { suggestSimilar } = require_suggestSimilar();
976
+ var Command2 = class _Command extends EventEmitter {
977
+ /**
978
+ * Initialize a new `Command`.
979
+ *
980
+ * @param {string} [name]
981
+ */
982
+ constructor(name) {
983
+ super();
984
+ this.commands = [];
985
+ this.options = [];
986
+ this.parent = null;
987
+ this._allowUnknownOption = false;
988
+ this._allowExcessArguments = true;
989
+ this.registeredArguments = [];
990
+ this._args = this.registeredArguments;
991
+ this.args = [];
992
+ this.rawArgs = [];
993
+ this.processedArgs = [];
994
+ this._scriptPath = null;
995
+ this._name = name || "";
996
+ this._optionValues = {};
997
+ this._optionValueSources = {};
998
+ this._storeOptionsAsProperties = false;
999
+ this._actionHandler = null;
1000
+ this._executableHandler = false;
1001
+ this._executableFile = null;
1002
+ this._executableDir = null;
1003
+ this._defaultCommandName = null;
1004
+ this._exitCallback = null;
1005
+ this._aliases = [];
1006
+ this._combineFlagAndOptionalValue = true;
1007
+ this._description = "";
1008
+ this._summary = "";
1009
+ this._argsDescription = void 0;
1010
+ this._enablePositionalOptions = false;
1011
+ this._passThroughOptions = false;
1012
+ this._lifeCycleHooks = {};
1013
+ this._showHelpAfterError = false;
1014
+ this._showSuggestionAfterError = true;
1015
+ this._outputConfiguration = {
1016
+ writeOut: (str) => process2.stdout.write(str),
1017
+ writeErr: (str) => process2.stderr.write(str),
1018
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1019
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1020
+ outputError: (str, write) => write(str)
1021
+ };
1022
+ this._hidden = false;
1023
+ this._helpOption = void 0;
1024
+ this._addImplicitHelpCommand = void 0;
1025
+ this._helpCommand = void 0;
1026
+ this._helpConfiguration = {};
1027
+ }
1028
+ /**
1029
+ * Copy settings that are useful to have in common across root command and subcommands.
1030
+ *
1031
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1032
+ *
1033
+ * @param {Command} sourceCommand
1034
+ * @return {Command} `this` command for chaining
1035
+ */
1036
+ copyInheritedSettings(sourceCommand) {
1037
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1038
+ this._helpOption = sourceCommand._helpOption;
1039
+ this._helpCommand = sourceCommand._helpCommand;
1040
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1041
+ this._exitCallback = sourceCommand._exitCallback;
1042
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1043
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1044
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1045
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1046
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1047
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1048
+ return this;
1049
+ }
1050
+ /**
1051
+ * @returns {Command[]}
1052
+ * @private
1053
+ */
1054
+ _getCommandAndAncestors() {
1055
+ const result = [];
1056
+ for (let command = this; command; command = command.parent) {
1057
+ result.push(command);
1058
+ }
1059
+ return result;
1060
+ }
1061
+ /**
1062
+ * Define a command.
1063
+ *
1064
+ * There are two styles of command: pay attention to where to put the description.
1065
+ *
1066
+ * @example
1067
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1068
+ * program
1069
+ * .command('clone <source> [destination]')
1070
+ * .description('clone a repository into a newly created directory')
1071
+ * .action((source, destination) => {
1072
+ * console.log('clone command called');
1073
+ * });
1074
+ *
1075
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1076
+ * program
1077
+ * .command('start <service>', 'start named service')
1078
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1079
+ *
1080
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1081
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1082
+ * @param {object} [execOpts] - configuration options (for executable)
1083
+ * @return {Command} returns new command for action handler, or `this` for executable command
1084
+ */
1085
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1086
+ let desc = actionOptsOrExecDesc;
1087
+ let opts = execOpts;
1088
+ if (typeof desc === "object" && desc !== null) {
1089
+ opts = desc;
1090
+ desc = null;
1091
+ }
1092
+ opts = opts || {};
1093
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1094
+ const cmd = this.createCommand(name);
1095
+ if (desc) {
1096
+ cmd.description(desc);
1097
+ cmd._executableHandler = true;
1098
+ }
1099
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1100
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1101
+ cmd._executableFile = opts.executableFile || null;
1102
+ if (args) cmd.arguments(args);
1103
+ this._registerCommand(cmd);
1104
+ cmd.parent = this;
1105
+ cmd.copyInheritedSettings(this);
1106
+ if (desc) return this;
1107
+ return cmd;
1108
+ }
1109
+ /**
1110
+ * Factory routine to create a new unattached command.
1111
+ *
1112
+ * See .command() for creating an attached subcommand, which uses this routine to
1113
+ * create the command. You can override createCommand to customise subcommands.
1114
+ *
1115
+ * @param {string} [name]
1116
+ * @return {Command} new command
1117
+ */
1118
+ createCommand(name) {
1119
+ return new _Command(name);
1120
+ }
1121
+ /**
1122
+ * You can customise the help with a subclass of Help by overriding createHelp,
1123
+ * or by overriding Help properties using configureHelp().
1124
+ *
1125
+ * @return {Help}
1126
+ */
1127
+ createHelp() {
1128
+ return Object.assign(new Help2(), this.configureHelp());
1129
+ }
1130
+ /**
1131
+ * You can customise the help by overriding Help properties using configureHelp(),
1132
+ * or with a subclass of Help by overriding createHelp().
1133
+ *
1134
+ * @param {object} [configuration] - configuration options
1135
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1136
+ */
1137
+ configureHelp(configuration) {
1138
+ if (configuration === void 0) return this._helpConfiguration;
1139
+ this._helpConfiguration = configuration;
1140
+ return this;
1141
+ }
1142
+ /**
1143
+ * The default output goes to stdout and stderr. You can customise this for special
1144
+ * applications. You can also customise the display of errors by overriding outputError.
1145
+ *
1146
+ * The configuration properties are all functions:
1147
+ *
1148
+ * // functions to change where being written, stdout and stderr
1149
+ * writeOut(str)
1150
+ * writeErr(str)
1151
+ * // matching functions to specify width for wrapping help
1152
+ * getOutHelpWidth()
1153
+ * getErrHelpWidth()
1154
+ * // functions based on what is being written out
1155
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1156
+ *
1157
+ * @param {object} [configuration] - configuration options
1158
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1159
+ */
1160
+ configureOutput(configuration) {
1161
+ if (configuration === void 0) return this._outputConfiguration;
1162
+ Object.assign(this._outputConfiguration, configuration);
1163
+ return this;
1164
+ }
1165
+ /**
1166
+ * Display the help or a custom message after an error occurs.
1167
+ *
1168
+ * @param {(boolean|string)} [displayHelp]
1169
+ * @return {Command} `this` command for chaining
1170
+ */
1171
+ showHelpAfterError(displayHelp = true) {
1172
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1173
+ this._showHelpAfterError = displayHelp;
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1178
+ *
1179
+ * @param {boolean} [displaySuggestion]
1180
+ * @return {Command} `this` command for chaining
1181
+ */
1182
+ showSuggestionAfterError(displaySuggestion = true) {
1183
+ this._showSuggestionAfterError = !!displaySuggestion;
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Add a prepared subcommand.
1188
+ *
1189
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1190
+ *
1191
+ * @param {Command} cmd - new subcommand
1192
+ * @param {object} [opts] - configuration options
1193
+ * @return {Command} `this` command for chaining
1194
+ */
1195
+ addCommand(cmd, opts) {
1196
+ if (!cmd._name) {
1197
+ throw new Error(`Command passed to .addCommand() must have a name
1198
+ - specify the name in Command constructor or using .name()`);
1199
+ }
1200
+ opts = opts || {};
1201
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1202
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1203
+ this._registerCommand(cmd);
1204
+ cmd.parent = this;
1205
+ cmd._checkForBrokenPassThrough();
1206
+ return this;
1207
+ }
1208
+ /**
1209
+ * Factory routine to create a new unattached argument.
1210
+ *
1211
+ * See .argument() for creating an attached argument, which uses this routine to
1212
+ * create the argument. You can override createArgument to return a custom argument.
1213
+ *
1214
+ * @param {string} name
1215
+ * @param {string} [description]
1216
+ * @return {Argument} new argument
1217
+ */
1218
+ createArgument(name, description) {
1219
+ return new Argument2(name, description);
1220
+ }
1221
+ /**
1222
+ * Define argument syntax for command.
1223
+ *
1224
+ * The default is that the argument is required, and you can explicitly
1225
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1226
+ *
1227
+ * @example
1228
+ * program.argument('<input-file>');
1229
+ * program.argument('[output-file]');
1230
+ *
1231
+ * @param {string} name
1232
+ * @param {string} [description]
1233
+ * @param {(Function|*)} [fn] - custom argument processing function
1234
+ * @param {*} [defaultValue]
1235
+ * @return {Command} `this` command for chaining
1236
+ */
1237
+ argument(name, description, fn, defaultValue) {
1238
+ const argument = this.createArgument(name, description);
1239
+ if (typeof fn === "function") {
1240
+ argument.default(defaultValue).argParser(fn);
1241
+ } else {
1242
+ argument.default(fn);
1243
+ }
1244
+ this.addArgument(argument);
1245
+ return this;
1246
+ }
1247
+ /**
1248
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1249
+ *
1250
+ * See also .argument().
1251
+ *
1252
+ * @example
1253
+ * program.arguments('<cmd> [env]');
1254
+ *
1255
+ * @param {string} names
1256
+ * @return {Command} `this` command for chaining
1257
+ */
1258
+ arguments(names) {
1259
+ names.trim().split(/ +/).forEach((detail) => {
1260
+ this.argument(detail);
1261
+ });
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Define argument syntax for command, adding a prepared argument.
1266
+ *
1267
+ * @param {Argument} argument
1268
+ * @return {Command} `this` command for chaining
1269
+ */
1270
+ addArgument(argument) {
1271
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1272
+ if (previousArgument && previousArgument.variadic) {
1273
+ throw new Error(
1274
+ `only the last argument can be variadic '${previousArgument.name()}'`
1275
+ );
1276
+ }
1277
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1278
+ throw new Error(
1279
+ `a default value for a required argument is never used: '${argument.name()}'`
1280
+ );
1281
+ }
1282
+ this.registeredArguments.push(argument);
1283
+ return this;
1284
+ }
1285
+ /**
1286
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1287
+ *
1288
+ * @example
1289
+ * program.helpCommand('help [cmd]');
1290
+ * program.helpCommand('help [cmd]', 'show help');
1291
+ * program.helpCommand(false); // suppress default help command
1292
+ * program.helpCommand(true); // add help command even if no subcommands
1293
+ *
1294
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1295
+ * @param {string} [description] - custom description
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ helpCommand(enableOrNameAndArgs, description) {
1299
+ if (typeof enableOrNameAndArgs === "boolean") {
1300
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1301
+ return this;
1302
+ }
1303
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1304
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1305
+ const helpDescription = description ?? "display help for command";
1306
+ const helpCommand = this.createCommand(helpName);
1307
+ helpCommand.helpOption(false);
1308
+ if (helpArgs) helpCommand.arguments(helpArgs);
1309
+ if (helpDescription) helpCommand.description(helpDescription);
1310
+ this._addImplicitHelpCommand = true;
1311
+ this._helpCommand = helpCommand;
1312
+ return this;
1313
+ }
1314
+ /**
1315
+ * Add prepared custom help command.
1316
+ *
1317
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1318
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1319
+ * @return {Command} `this` command for chaining
1320
+ */
1321
+ addHelpCommand(helpCommand, deprecatedDescription) {
1322
+ if (typeof helpCommand !== "object") {
1323
+ this.helpCommand(helpCommand, deprecatedDescription);
1324
+ return this;
1325
+ }
1326
+ this._addImplicitHelpCommand = true;
1327
+ this._helpCommand = helpCommand;
1328
+ return this;
1329
+ }
1330
+ /**
1331
+ * Lazy create help command.
1332
+ *
1333
+ * @return {(Command|null)}
1334
+ * @package
1335
+ */
1336
+ _getHelpCommand() {
1337
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1338
+ if (hasImplicitHelpCommand) {
1339
+ if (this._helpCommand === void 0) {
1340
+ this.helpCommand(void 0, void 0);
1341
+ }
1342
+ return this._helpCommand;
1343
+ }
1344
+ return null;
1345
+ }
1346
+ /**
1347
+ * Add hook for life cycle event.
1348
+ *
1349
+ * @param {string} event
1350
+ * @param {Function} listener
1351
+ * @return {Command} `this` command for chaining
1352
+ */
1353
+ hook(event, listener) {
1354
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1355
+ if (!allowedValues.includes(event)) {
1356
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1357
+ Expecting one of '${allowedValues.join("', '")}'`);
1358
+ }
1359
+ if (this._lifeCycleHooks[event]) {
1360
+ this._lifeCycleHooks[event].push(listener);
1361
+ } else {
1362
+ this._lifeCycleHooks[event] = [listener];
1363
+ }
1364
+ return this;
1365
+ }
1366
+ /**
1367
+ * Register callback to use as replacement for calling process.exit.
1368
+ *
1369
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1370
+ * @return {Command} `this` command for chaining
1371
+ */
1372
+ exitOverride(fn) {
1373
+ if (fn) {
1374
+ this._exitCallback = fn;
1375
+ } else {
1376
+ this._exitCallback = (err) => {
1377
+ if (err.code !== "commander.executeSubCommandAsync") {
1378
+ throw err;
1379
+ } else {
1380
+ }
1381
+ };
1382
+ }
1383
+ return this;
1384
+ }
1385
+ /**
1386
+ * Call process.exit, and _exitCallback if defined.
1387
+ *
1388
+ * @param {number} exitCode exit code for using with process.exit
1389
+ * @param {string} code an id string representing the error
1390
+ * @param {string} message human-readable description of the error
1391
+ * @return never
1392
+ * @private
1393
+ */
1394
+ _exit(exitCode, code, message) {
1395
+ if (this._exitCallback) {
1396
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1397
+ }
1398
+ process2.exit(exitCode);
1399
+ }
1400
+ /**
1401
+ * Register callback `fn` for the command.
1402
+ *
1403
+ * @example
1404
+ * program
1405
+ * .command('serve')
1406
+ * .description('start service')
1407
+ * .action(function() {
1408
+ * // do work here
1409
+ * });
1410
+ *
1411
+ * @param {Function} fn
1412
+ * @return {Command} `this` command for chaining
1413
+ */
1414
+ action(fn) {
1415
+ const listener = (args) => {
1416
+ const expectedArgsCount = this.registeredArguments.length;
1417
+ const actionArgs = args.slice(0, expectedArgsCount);
1418
+ if (this._storeOptionsAsProperties) {
1419
+ actionArgs[expectedArgsCount] = this;
1420
+ } else {
1421
+ actionArgs[expectedArgsCount] = this.opts();
1422
+ }
1423
+ actionArgs.push(this);
1424
+ return fn.apply(this, actionArgs);
1425
+ };
1426
+ this._actionHandler = listener;
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Factory routine to create a new unattached option.
1431
+ *
1432
+ * See .option() for creating an attached option, which uses this routine to
1433
+ * create the option. You can override createOption to return a custom option.
1434
+ *
1435
+ * @param {string} flags
1436
+ * @param {string} [description]
1437
+ * @return {Option} new option
1438
+ */
1439
+ createOption(flags, description) {
1440
+ return new Option2(flags, description);
1441
+ }
1442
+ /**
1443
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1444
+ *
1445
+ * @param {(Option | Argument)} target
1446
+ * @param {string} value
1447
+ * @param {*} previous
1448
+ * @param {string} invalidArgumentMessage
1449
+ * @private
1450
+ */
1451
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1452
+ try {
1453
+ return target.parseArg(value, previous);
1454
+ } catch (err) {
1455
+ if (err.code === "commander.invalidArgument") {
1456
+ const message = `${invalidArgumentMessage} ${err.message}`;
1457
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1458
+ }
1459
+ throw err;
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Check for option flag conflicts.
1464
+ * Register option if no conflicts found, or throw on conflict.
1465
+ *
1466
+ * @param {Option} option
1467
+ * @private
1468
+ */
1469
+ _registerOption(option) {
1470
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1471
+ if (matchingOption) {
1472
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1473
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1474
+ - already used by option '${matchingOption.flags}'`);
1475
+ }
1476
+ this.options.push(option);
1477
+ }
1478
+ /**
1479
+ * Check for command name and alias conflicts with existing commands.
1480
+ * Register command if no conflicts found, or throw on conflict.
1481
+ *
1482
+ * @param {Command} command
1483
+ * @private
1484
+ */
1485
+ _registerCommand(command) {
1486
+ const knownBy = (cmd) => {
1487
+ return [cmd.name()].concat(cmd.aliases());
1488
+ };
1489
+ const alreadyUsed = knownBy(command).find(
1490
+ (name) => this._findCommand(name)
1491
+ );
1492
+ if (alreadyUsed) {
1493
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1494
+ const newCmd = knownBy(command).join("|");
1495
+ throw new Error(
1496
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1497
+ );
1498
+ }
1499
+ this.commands.push(command);
1500
+ }
1501
+ /**
1502
+ * Add an option.
1503
+ *
1504
+ * @param {Option} option
1505
+ * @return {Command} `this` command for chaining
1506
+ */
1507
+ addOption(option) {
1508
+ this._registerOption(option);
1509
+ const oname = option.name();
1510
+ const name = option.attributeName();
1511
+ if (option.negate) {
1512
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1513
+ if (!this._findOption(positiveLongFlag)) {
1514
+ this.setOptionValueWithSource(
1515
+ name,
1516
+ option.defaultValue === void 0 ? true : option.defaultValue,
1517
+ "default"
1518
+ );
1519
+ }
1520
+ } else if (option.defaultValue !== void 0) {
1521
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1522
+ }
1523
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1524
+ if (val == null && option.presetArg !== void 0) {
1525
+ val = option.presetArg;
1526
+ }
1527
+ const oldValue = this.getOptionValue(name);
1528
+ if (val !== null && option.parseArg) {
1529
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1530
+ } else if (val !== null && option.variadic) {
1531
+ val = option._concatValue(val, oldValue);
1532
+ }
1533
+ if (val == null) {
1534
+ if (option.negate) {
1535
+ val = false;
1536
+ } else if (option.isBoolean() || option.optional) {
1537
+ val = true;
1538
+ } else {
1539
+ val = "";
1540
+ }
1541
+ }
1542
+ this.setOptionValueWithSource(name, val, valueSource);
1543
+ };
1544
+ this.on("option:" + oname, (val) => {
1545
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1546
+ handleOptionValue(val, invalidValueMessage, "cli");
1547
+ });
1548
+ if (option.envVar) {
1549
+ this.on("optionEnv:" + oname, (val) => {
1550
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1551
+ handleOptionValue(val, invalidValueMessage, "env");
1552
+ });
1553
+ }
1554
+ return this;
1555
+ }
1556
+ /**
1557
+ * Internal implementation shared by .option() and .requiredOption()
1558
+ *
1559
+ * @return {Command} `this` command for chaining
1560
+ * @private
1561
+ */
1562
+ _optionEx(config, flags, description, fn, defaultValue) {
1563
+ if (typeof flags === "object" && flags instanceof Option2) {
1564
+ throw new Error(
1565
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1566
+ );
1567
+ }
1568
+ const option = this.createOption(flags, description);
1569
+ option.makeOptionMandatory(!!config.mandatory);
1570
+ if (typeof fn === "function") {
1571
+ option.default(defaultValue).argParser(fn);
1572
+ } else if (fn instanceof RegExp) {
1573
+ const regex = fn;
1574
+ fn = (val, def) => {
1575
+ const m = regex.exec(val);
1576
+ return m ? m[0] : def;
1577
+ };
1578
+ option.default(defaultValue).argParser(fn);
1579
+ } else {
1580
+ option.default(fn);
1581
+ }
1582
+ return this.addOption(option);
1583
+ }
1584
+ /**
1585
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1586
+ *
1587
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1588
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1589
+ *
1590
+ * See the README for more details, and see also addOption() and requiredOption().
1591
+ *
1592
+ * @example
1593
+ * program
1594
+ * .option('-p, --pepper', 'add pepper')
1595
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1596
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1597
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1598
+ *
1599
+ * @param {string} flags
1600
+ * @param {string} [description]
1601
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1602
+ * @param {*} [defaultValue]
1603
+ * @return {Command} `this` command for chaining
1604
+ */
1605
+ option(flags, description, parseArg, defaultValue) {
1606
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1607
+ }
1608
+ /**
1609
+ * Add a required option which must have a value after parsing. This usually means
1610
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1611
+ *
1612
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1613
+ *
1614
+ * @param {string} flags
1615
+ * @param {string} [description]
1616
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1617
+ * @param {*} [defaultValue]
1618
+ * @return {Command} `this` command for chaining
1619
+ */
1620
+ requiredOption(flags, description, parseArg, defaultValue) {
1621
+ return this._optionEx(
1622
+ { mandatory: true },
1623
+ flags,
1624
+ description,
1625
+ parseArg,
1626
+ defaultValue
1627
+ );
1628
+ }
1629
+ /**
1630
+ * Alter parsing of short flags with optional values.
1631
+ *
1632
+ * @example
1633
+ * // for `.option('-f,--flag [value]'):
1634
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1635
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1636
+ *
1637
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1638
+ * @return {Command} `this` command for chaining
1639
+ */
1640
+ combineFlagAndOptionalValue(combine = true) {
1641
+ this._combineFlagAndOptionalValue = !!combine;
1642
+ return this;
1643
+ }
1644
+ /**
1645
+ * Allow unknown options on the command line.
1646
+ *
1647
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1648
+ * @return {Command} `this` command for chaining
1649
+ */
1650
+ allowUnknownOption(allowUnknown = true) {
1651
+ this._allowUnknownOption = !!allowUnknown;
1652
+ return this;
1653
+ }
1654
+ /**
1655
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1656
+ *
1657
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1658
+ * @return {Command} `this` command for chaining
1659
+ */
1660
+ allowExcessArguments(allowExcess = true) {
1661
+ this._allowExcessArguments = !!allowExcess;
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1666
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1667
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1668
+ *
1669
+ * @param {boolean} [positional]
1670
+ * @return {Command} `this` command for chaining
1671
+ */
1672
+ enablePositionalOptions(positional = true) {
1673
+ this._enablePositionalOptions = !!positional;
1674
+ return this;
1675
+ }
1676
+ /**
1677
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1678
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1679
+ * positional options to have been enabled on the program (parent commands).
1680
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1681
+ *
1682
+ * @param {boolean} [passThrough] for unknown options.
1683
+ * @return {Command} `this` command for chaining
1684
+ */
1685
+ passThroughOptions(passThrough = true) {
1686
+ this._passThroughOptions = !!passThrough;
1687
+ this._checkForBrokenPassThrough();
1688
+ return this;
1689
+ }
1690
+ /**
1691
+ * @private
1692
+ */
1693
+ _checkForBrokenPassThrough() {
1694
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1695
+ throw new Error(
1696
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1697
+ );
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Whether to store option values as properties on command object,
1702
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1703
+ *
1704
+ * @param {boolean} [storeAsProperties=true]
1705
+ * @return {Command} `this` command for chaining
1706
+ */
1707
+ storeOptionsAsProperties(storeAsProperties = true) {
1708
+ if (this.options.length) {
1709
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1710
+ }
1711
+ if (Object.keys(this._optionValues).length) {
1712
+ throw new Error(
1713
+ "call .storeOptionsAsProperties() before setting option values"
1714
+ );
1715
+ }
1716
+ this._storeOptionsAsProperties = !!storeAsProperties;
1717
+ return this;
1718
+ }
1719
+ /**
1720
+ * Retrieve option value.
1721
+ *
1722
+ * @param {string} key
1723
+ * @return {object} value
1724
+ */
1725
+ getOptionValue(key) {
1726
+ if (this._storeOptionsAsProperties) {
1727
+ return this[key];
1728
+ }
1729
+ return this._optionValues[key];
1730
+ }
1731
+ /**
1732
+ * Store option value.
1733
+ *
1734
+ * @param {string} key
1735
+ * @param {object} value
1736
+ * @return {Command} `this` command for chaining
1737
+ */
1738
+ setOptionValue(key, value) {
1739
+ return this.setOptionValueWithSource(key, value, void 0);
1740
+ }
1741
+ /**
1742
+ * Store option value and where the value came from.
1743
+ *
1744
+ * @param {string} key
1745
+ * @param {object} value
1746
+ * @param {string} source - expected values are default/config/env/cli/implied
1747
+ * @return {Command} `this` command for chaining
1748
+ */
1749
+ setOptionValueWithSource(key, value, source) {
1750
+ if (this._storeOptionsAsProperties) {
1751
+ this[key] = value;
1752
+ } else {
1753
+ this._optionValues[key] = value;
1754
+ }
1755
+ this._optionValueSources[key] = source;
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Get source of option value.
1760
+ * Expected values are default | config | env | cli | implied
1761
+ *
1762
+ * @param {string} key
1763
+ * @return {string}
1764
+ */
1765
+ getOptionValueSource(key) {
1766
+ return this._optionValueSources[key];
1767
+ }
1768
+ /**
1769
+ * Get source of option value. See also .optsWithGlobals().
1770
+ * Expected values are default | config | env | cli | implied
1771
+ *
1772
+ * @param {string} key
1773
+ * @return {string}
1774
+ */
1775
+ getOptionValueSourceWithGlobals(key) {
1776
+ let source;
1777
+ this._getCommandAndAncestors().forEach((cmd) => {
1778
+ if (cmd.getOptionValueSource(key) !== void 0) {
1779
+ source = cmd.getOptionValueSource(key);
1780
+ }
1781
+ });
1782
+ return source;
1783
+ }
1784
+ /**
1785
+ * Get user arguments from implied or explicit arguments.
1786
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1787
+ *
1788
+ * @private
1789
+ */
1790
+ _prepareUserArgs(argv, parseOptions) {
1791
+ if (argv !== void 0 && !Array.isArray(argv)) {
1792
+ throw new Error("first parameter to parse must be array or undefined");
1793
+ }
1794
+ parseOptions = parseOptions || {};
1795
+ if (argv === void 0 && parseOptions.from === void 0) {
1796
+ if (process2.versions?.electron) {
1797
+ parseOptions.from = "electron";
1798
+ }
1799
+ const execArgv = process2.execArgv ?? [];
1800
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1801
+ parseOptions.from = "eval";
1802
+ }
1803
+ }
1804
+ if (argv === void 0) {
1805
+ argv = process2.argv;
1806
+ }
1807
+ this.rawArgs = argv.slice();
1808
+ let userArgs;
1809
+ switch (parseOptions.from) {
1810
+ case void 0:
1811
+ case "node":
1812
+ this._scriptPath = argv[1];
1813
+ userArgs = argv.slice(2);
1814
+ break;
1815
+ case "electron":
1816
+ if (process2.defaultApp) {
1817
+ this._scriptPath = argv[1];
1818
+ userArgs = argv.slice(2);
1819
+ } else {
1820
+ userArgs = argv.slice(1);
1821
+ }
1822
+ break;
1823
+ case "user":
1824
+ userArgs = argv.slice(0);
1825
+ break;
1826
+ case "eval":
1827
+ userArgs = argv.slice(1);
1828
+ break;
1829
+ default:
1830
+ throw new Error(
1831
+ `unexpected parse option { from: '${parseOptions.from}' }`
1832
+ );
1833
+ }
1834
+ if (!this._name && this._scriptPath)
1835
+ this.nameFromFilename(this._scriptPath);
1836
+ this._name = this._name || "program";
1837
+ return userArgs;
1838
+ }
1839
+ /**
1840
+ * Parse `argv`, setting options and invoking commands when defined.
1841
+ *
1842
+ * Use parseAsync instead of parse if any of your action handlers are async.
1843
+ *
1844
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1845
+ *
1846
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1847
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1848
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1849
+ * - `'user'`: just user arguments
1850
+ *
1851
+ * @example
1852
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1853
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1854
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1855
+ *
1856
+ * @param {string[]} [argv] - optional, defaults to process.argv
1857
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1858
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1859
+ * @return {Command} `this` command for chaining
1860
+ */
1861
+ parse(argv, parseOptions) {
1862
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1863
+ this._parseCommand([], userArgs);
1864
+ return this;
1865
+ }
1866
+ /**
1867
+ * Parse `argv`, setting options and invoking commands when defined.
1868
+ *
1869
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1870
+ *
1871
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1872
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1873
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1874
+ * - `'user'`: just user arguments
1875
+ *
1876
+ * @example
1877
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1878
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1879
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1880
+ *
1881
+ * @param {string[]} [argv]
1882
+ * @param {object} [parseOptions]
1883
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1884
+ * @return {Promise}
1885
+ */
1886
+ async parseAsync(argv, parseOptions) {
1887
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1888
+ await this._parseCommand([], userArgs);
1889
+ return this;
1890
+ }
1891
+ /**
1892
+ * Execute a sub-command executable.
1893
+ *
1894
+ * @private
1895
+ */
1896
+ _executeSubCommand(subcommand, args) {
1897
+ args = args.slice();
1898
+ let launchWithNode = false;
1899
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1900
+ function findFile(baseDir, baseName) {
1901
+ const localBin = path4.resolve(baseDir, baseName);
1902
+ if (fs5.existsSync(localBin)) return localBin;
1903
+ if (sourceExt.includes(path4.extname(baseName))) return void 0;
1904
+ const foundExt = sourceExt.find(
1905
+ (ext) => fs5.existsSync(`${localBin}${ext}`)
1906
+ );
1907
+ if (foundExt) return `${localBin}${foundExt}`;
1908
+ return void 0;
1909
+ }
1910
+ this._checkForMissingMandatoryOptions();
1911
+ this._checkForConflictingOptions();
1912
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1913
+ let executableDir = this._executableDir || "";
1914
+ if (this._scriptPath) {
1915
+ let resolvedScriptPath;
1916
+ try {
1917
+ resolvedScriptPath = fs5.realpathSync(this._scriptPath);
1918
+ } catch (err) {
1919
+ resolvedScriptPath = this._scriptPath;
1920
+ }
1921
+ executableDir = path4.resolve(
1922
+ path4.dirname(resolvedScriptPath),
1923
+ executableDir
1924
+ );
1925
+ }
1926
+ if (executableDir) {
1927
+ let localFile = findFile(executableDir, executableFile);
1928
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1929
+ const legacyName = path4.basename(
1930
+ this._scriptPath,
1931
+ path4.extname(this._scriptPath)
1932
+ );
1933
+ if (legacyName !== this._name) {
1934
+ localFile = findFile(
1935
+ executableDir,
1936
+ `${legacyName}-${subcommand._name}`
1937
+ );
1938
+ }
1939
+ }
1940
+ executableFile = localFile || executableFile;
1941
+ }
1942
+ launchWithNode = sourceExt.includes(path4.extname(executableFile));
1943
+ let proc;
1944
+ if (process2.platform !== "win32") {
1945
+ if (launchWithNode) {
1946
+ args.unshift(executableFile);
1947
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1948
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1949
+ } else {
1950
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1951
+ }
1952
+ } else {
1953
+ args.unshift(executableFile);
1954
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1955
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1956
+ }
1957
+ if (!proc.killed) {
1958
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1959
+ signals.forEach((signal) => {
1960
+ process2.on(signal, () => {
1961
+ if (proc.killed === false && proc.exitCode === null) {
1962
+ proc.kill(signal);
1963
+ }
1964
+ });
1965
+ });
1966
+ }
1967
+ const exitCallback = this._exitCallback;
1968
+ proc.on("close", (code) => {
1969
+ code = code ?? 1;
1970
+ if (!exitCallback) {
1971
+ process2.exit(code);
1972
+ } else {
1973
+ exitCallback(
1974
+ new CommanderError2(
1975
+ code,
1976
+ "commander.executeSubCommandAsync",
1977
+ "(close)"
1978
+ )
1979
+ );
1980
+ }
1981
+ });
1982
+ proc.on("error", (err) => {
1983
+ if (err.code === "ENOENT") {
1984
+ 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";
1985
+ const executableMissing = `'${executableFile}' does not exist
1986
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1987
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1988
+ - ${executableDirMessage}`;
1989
+ throw new Error(executableMissing);
1990
+ } else if (err.code === "EACCES") {
1991
+ throw new Error(`'${executableFile}' not executable`);
1992
+ }
1993
+ if (!exitCallback) {
1994
+ process2.exit(1);
1995
+ } else {
1996
+ const wrappedError = new CommanderError2(
1997
+ 1,
1998
+ "commander.executeSubCommandAsync",
1999
+ "(error)"
2000
+ );
2001
+ wrappedError.nestedError = err;
2002
+ exitCallback(wrappedError);
2003
+ }
2004
+ });
2005
+ this.runningCommand = proc;
2006
+ }
2007
+ /**
2008
+ * @private
2009
+ */
2010
+ _dispatchSubcommand(commandName, operands, unknown) {
2011
+ const subCommand = this._findCommand(commandName);
2012
+ if (!subCommand) this.help({ error: true });
2013
+ let promiseChain;
2014
+ promiseChain = this._chainOrCallSubCommandHook(
2015
+ promiseChain,
2016
+ subCommand,
2017
+ "preSubcommand"
2018
+ );
2019
+ promiseChain = this._chainOrCall(promiseChain, () => {
2020
+ if (subCommand._executableHandler) {
2021
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2022
+ } else {
2023
+ return subCommand._parseCommand(operands, unknown);
2024
+ }
2025
+ });
2026
+ return promiseChain;
2027
+ }
2028
+ /**
2029
+ * Invoke help directly if possible, or dispatch if necessary.
2030
+ * e.g. help foo
2031
+ *
2032
+ * @private
2033
+ */
2034
+ _dispatchHelpCommand(subcommandName) {
2035
+ if (!subcommandName) {
2036
+ this.help();
2037
+ }
2038
+ const subCommand = this._findCommand(subcommandName);
2039
+ if (subCommand && !subCommand._executableHandler) {
2040
+ subCommand.help();
2041
+ }
2042
+ return this._dispatchSubcommand(
2043
+ subcommandName,
2044
+ [],
2045
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2046
+ );
2047
+ }
2048
+ /**
2049
+ * Check this.args against expected this.registeredArguments.
2050
+ *
2051
+ * @private
2052
+ */
2053
+ _checkNumberOfArguments() {
2054
+ this.registeredArguments.forEach((arg, i) => {
2055
+ if (arg.required && this.args[i] == null) {
2056
+ this.missingArgument(arg.name());
2057
+ }
2058
+ });
2059
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2060
+ return;
2061
+ }
2062
+ if (this.args.length > this.registeredArguments.length) {
2063
+ this._excessArguments(this.args);
2064
+ }
2065
+ }
2066
+ /**
2067
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _processArguments() {
2072
+ const myParseArg = (argument, value, previous) => {
2073
+ let parsedValue = value;
2074
+ if (value !== null && argument.parseArg) {
2075
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2076
+ parsedValue = this._callParseArg(
2077
+ argument,
2078
+ value,
2079
+ previous,
2080
+ invalidValueMessage
2081
+ );
2082
+ }
2083
+ return parsedValue;
2084
+ };
2085
+ this._checkNumberOfArguments();
2086
+ const processedArgs = [];
2087
+ this.registeredArguments.forEach((declaredArg, index) => {
2088
+ let value = declaredArg.defaultValue;
2089
+ if (declaredArg.variadic) {
2090
+ if (index < this.args.length) {
2091
+ value = this.args.slice(index);
2092
+ if (declaredArg.parseArg) {
2093
+ value = value.reduce((processed, v) => {
2094
+ return myParseArg(declaredArg, v, processed);
2095
+ }, declaredArg.defaultValue);
2096
+ }
2097
+ } else if (value === void 0) {
2098
+ value = [];
2099
+ }
2100
+ } else if (index < this.args.length) {
2101
+ value = this.args[index];
2102
+ if (declaredArg.parseArg) {
2103
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2104
+ }
2105
+ }
2106
+ processedArgs[index] = value;
2107
+ });
2108
+ this.processedArgs = processedArgs;
2109
+ }
2110
+ /**
2111
+ * Once we have a promise we chain, but call synchronously until then.
2112
+ *
2113
+ * @param {(Promise|undefined)} promise
2114
+ * @param {Function} fn
2115
+ * @return {(Promise|undefined)}
2116
+ * @private
2117
+ */
2118
+ _chainOrCall(promise, fn) {
2119
+ if (promise && promise.then && typeof promise.then === "function") {
2120
+ return promise.then(() => fn());
2121
+ }
2122
+ return fn();
2123
+ }
2124
+ /**
2125
+ *
2126
+ * @param {(Promise|undefined)} promise
2127
+ * @param {string} event
2128
+ * @return {(Promise|undefined)}
2129
+ * @private
2130
+ */
2131
+ _chainOrCallHooks(promise, event) {
2132
+ let result = promise;
2133
+ const hooks = [];
2134
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2135
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2136
+ hooks.push({ hookedCommand, callback });
2137
+ });
2138
+ });
2139
+ if (event === "postAction") {
2140
+ hooks.reverse();
2141
+ }
2142
+ hooks.forEach((hookDetail) => {
2143
+ result = this._chainOrCall(result, () => {
2144
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2145
+ });
2146
+ });
2147
+ return result;
2148
+ }
2149
+ /**
2150
+ *
2151
+ * @param {(Promise|undefined)} promise
2152
+ * @param {Command} subCommand
2153
+ * @param {string} event
2154
+ * @return {(Promise|undefined)}
2155
+ * @private
2156
+ */
2157
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2158
+ let result = promise;
2159
+ if (this._lifeCycleHooks[event] !== void 0) {
2160
+ this._lifeCycleHooks[event].forEach((hook) => {
2161
+ result = this._chainOrCall(result, () => {
2162
+ return hook(this, subCommand);
2163
+ });
2164
+ });
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /**
2169
+ * Process arguments in context of this command.
2170
+ * Returns action result, in case it is a promise.
2171
+ *
2172
+ * @private
2173
+ */
2174
+ _parseCommand(operands, unknown) {
2175
+ const parsed = this.parseOptions(unknown);
2176
+ this._parseOptionsEnv();
2177
+ this._parseOptionsImplied();
2178
+ operands = operands.concat(parsed.operands);
2179
+ unknown = parsed.unknown;
2180
+ this.args = operands.concat(unknown);
2181
+ if (operands && this._findCommand(operands[0])) {
2182
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2183
+ }
2184
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2185
+ return this._dispatchHelpCommand(operands[1]);
2186
+ }
2187
+ if (this._defaultCommandName) {
2188
+ this._outputHelpIfRequested(unknown);
2189
+ return this._dispatchSubcommand(
2190
+ this._defaultCommandName,
2191
+ operands,
2192
+ unknown
2193
+ );
2194
+ }
2195
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2196
+ this.help({ error: true });
2197
+ }
2198
+ this._outputHelpIfRequested(parsed.unknown);
2199
+ this._checkForMissingMandatoryOptions();
2200
+ this._checkForConflictingOptions();
2201
+ const checkForUnknownOptions = () => {
2202
+ if (parsed.unknown.length > 0) {
2203
+ this.unknownOption(parsed.unknown[0]);
2204
+ }
2205
+ };
2206
+ const commandEvent = `command:${this.name()}`;
2207
+ if (this._actionHandler) {
2208
+ checkForUnknownOptions();
2209
+ this._processArguments();
2210
+ let promiseChain;
2211
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2212
+ promiseChain = this._chainOrCall(
2213
+ promiseChain,
2214
+ () => this._actionHandler(this.processedArgs)
2215
+ );
2216
+ if (this.parent) {
2217
+ promiseChain = this._chainOrCall(promiseChain, () => {
2218
+ this.parent.emit(commandEvent, operands, unknown);
2219
+ });
2220
+ }
2221
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2222
+ return promiseChain;
2223
+ }
2224
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2225
+ checkForUnknownOptions();
2226
+ this._processArguments();
2227
+ this.parent.emit(commandEvent, operands, unknown);
2228
+ } else if (operands.length) {
2229
+ if (this._findCommand("*")) {
2230
+ return this._dispatchSubcommand("*", operands, unknown);
2231
+ }
2232
+ if (this.listenerCount("command:*")) {
2233
+ this.emit("command:*", operands, unknown);
2234
+ } else if (this.commands.length) {
2235
+ this.unknownCommand();
2236
+ } else {
2237
+ checkForUnknownOptions();
2238
+ this._processArguments();
2239
+ }
2240
+ } else if (this.commands.length) {
2241
+ checkForUnknownOptions();
2242
+ this.help({ error: true });
2243
+ } else {
2244
+ checkForUnknownOptions();
2245
+ this._processArguments();
2246
+ }
2247
+ }
2248
+ /**
2249
+ * Find matching command.
2250
+ *
2251
+ * @private
2252
+ * @return {Command | undefined}
2253
+ */
2254
+ _findCommand(name) {
2255
+ if (!name) return void 0;
2256
+ return this.commands.find(
2257
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2258
+ );
2259
+ }
2260
+ /**
2261
+ * Return an option matching `arg` if any.
2262
+ *
2263
+ * @param {string} arg
2264
+ * @return {Option}
2265
+ * @package
2266
+ */
2267
+ _findOption(arg) {
2268
+ return this.options.find((option) => option.is(arg));
2269
+ }
2270
+ /**
2271
+ * Display an error message if a mandatory option does not have a value.
2272
+ * Called after checking for help flags in leaf subcommand.
2273
+ *
2274
+ * @private
2275
+ */
2276
+ _checkForMissingMandatoryOptions() {
2277
+ this._getCommandAndAncestors().forEach((cmd) => {
2278
+ cmd.options.forEach((anOption) => {
2279
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2280
+ cmd.missingMandatoryOptionValue(anOption);
2281
+ }
2282
+ });
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Display an error message if conflicting options are used together in this.
2287
+ *
2288
+ * @private
2289
+ */
2290
+ _checkForConflictingLocalOptions() {
2291
+ const definedNonDefaultOptions = this.options.filter((option) => {
2292
+ const optionKey = option.attributeName();
2293
+ if (this.getOptionValue(optionKey) === void 0) {
2294
+ return false;
2295
+ }
2296
+ return this.getOptionValueSource(optionKey) !== "default";
2297
+ });
2298
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2299
+ (option) => option.conflictsWith.length > 0
2300
+ );
2301
+ optionsWithConflicting.forEach((option) => {
2302
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2303
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2304
+ );
2305
+ if (conflictingAndDefined) {
2306
+ this._conflictingOption(option, conflictingAndDefined);
2307
+ }
2308
+ });
2309
+ }
2310
+ /**
2311
+ * Display an error message if conflicting options are used together.
2312
+ * Called after checking for help flags in leaf subcommand.
2313
+ *
2314
+ * @private
2315
+ */
2316
+ _checkForConflictingOptions() {
2317
+ this._getCommandAndAncestors().forEach((cmd) => {
2318
+ cmd._checkForConflictingLocalOptions();
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Parse options from `argv` removing known options,
2323
+ * and return argv split into operands and unknown arguments.
2324
+ *
2325
+ * Examples:
2326
+ *
2327
+ * argv => operands, unknown
2328
+ * --known kkk op => [op], []
2329
+ * op --known kkk => [op], []
2330
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2331
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2332
+ *
2333
+ * @param {string[]} argv
2334
+ * @return {{operands: string[], unknown: string[]}}
2335
+ */
2336
+ parseOptions(argv) {
2337
+ const operands = [];
2338
+ const unknown = [];
2339
+ let dest = operands;
2340
+ const args = argv.slice();
2341
+ function maybeOption(arg) {
2342
+ return arg.length > 1 && arg[0] === "-";
2343
+ }
2344
+ let activeVariadicOption = null;
2345
+ while (args.length) {
2346
+ const arg = args.shift();
2347
+ if (arg === "--") {
2348
+ if (dest === unknown) dest.push(arg);
2349
+ dest.push(...args);
2350
+ break;
2351
+ }
2352
+ if (activeVariadicOption && !maybeOption(arg)) {
2353
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2354
+ continue;
2355
+ }
2356
+ activeVariadicOption = null;
2357
+ if (maybeOption(arg)) {
2358
+ const option = this._findOption(arg);
2359
+ if (option) {
2360
+ if (option.required) {
2361
+ const value = args.shift();
2362
+ if (value === void 0) this.optionMissingArgument(option);
2363
+ this.emit(`option:${option.name()}`, value);
2364
+ } else if (option.optional) {
2365
+ let value = null;
2366
+ if (args.length > 0 && !maybeOption(args[0])) {
2367
+ value = args.shift();
2368
+ }
2369
+ this.emit(`option:${option.name()}`, value);
2370
+ } else {
2371
+ this.emit(`option:${option.name()}`);
2372
+ }
2373
+ activeVariadicOption = option.variadic ? option : null;
2374
+ continue;
2375
+ }
2376
+ }
2377
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2378
+ const option = this._findOption(`-${arg[1]}`);
2379
+ if (option) {
2380
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2381
+ this.emit(`option:${option.name()}`, arg.slice(2));
2382
+ } else {
2383
+ this.emit(`option:${option.name()}`);
2384
+ args.unshift(`-${arg.slice(2)}`);
2385
+ }
2386
+ continue;
2387
+ }
2388
+ }
2389
+ if (/^--[^=]+=/.test(arg)) {
2390
+ const index = arg.indexOf("=");
2391
+ const option = this._findOption(arg.slice(0, index));
2392
+ if (option && (option.required || option.optional)) {
2393
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2394
+ continue;
2395
+ }
2396
+ }
2397
+ if (maybeOption(arg)) {
2398
+ dest = unknown;
2399
+ }
2400
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2401
+ if (this._findCommand(arg)) {
2402
+ operands.push(arg);
2403
+ if (args.length > 0) unknown.push(...args);
2404
+ break;
2405
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2406
+ operands.push(arg);
2407
+ if (args.length > 0) operands.push(...args);
2408
+ break;
2409
+ } else if (this._defaultCommandName) {
2410
+ unknown.push(arg);
2411
+ if (args.length > 0) unknown.push(...args);
2412
+ break;
2413
+ }
2414
+ }
2415
+ if (this._passThroughOptions) {
2416
+ dest.push(arg);
2417
+ if (args.length > 0) dest.push(...args);
2418
+ break;
2419
+ }
2420
+ dest.push(arg);
2421
+ }
2422
+ return { operands, unknown };
2423
+ }
2424
+ /**
2425
+ * Return an object containing local option values as key-value pairs.
2426
+ *
2427
+ * @return {object}
2428
+ */
2429
+ opts() {
2430
+ if (this._storeOptionsAsProperties) {
2431
+ const result = {};
2432
+ const len = this.options.length;
2433
+ for (let i = 0; i < len; i++) {
2434
+ const key = this.options[i].attributeName();
2435
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2436
+ }
2437
+ return result;
2438
+ }
2439
+ return this._optionValues;
2440
+ }
2441
+ /**
2442
+ * Return an object containing merged local and global option values as key-value pairs.
2443
+ *
2444
+ * @return {object}
2445
+ */
2446
+ optsWithGlobals() {
2447
+ return this._getCommandAndAncestors().reduce(
2448
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2449
+ {}
2450
+ );
2451
+ }
2452
+ /**
2453
+ * Display error message and exit (or call exitOverride).
2454
+ *
2455
+ * @param {string} message
2456
+ * @param {object} [errorOptions]
2457
+ * @param {string} [errorOptions.code] - an id string representing the error
2458
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2459
+ */
2460
+ error(message, errorOptions) {
2461
+ this._outputConfiguration.outputError(
2462
+ `${message}
2463
+ `,
2464
+ this._outputConfiguration.writeErr
2465
+ );
2466
+ if (typeof this._showHelpAfterError === "string") {
2467
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2468
+ `);
2469
+ } else if (this._showHelpAfterError) {
2470
+ this._outputConfiguration.writeErr("\n");
2471
+ this.outputHelp({ error: true });
2472
+ }
2473
+ const config = errorOptions || {};
2474
+ const exitCode = config.exitCode || 1;
2475
+ const code = config.code || "commander.error";
2476
+ this._exit(exitCode, code, message);
2477
+ }
2478
+ /**
2479
+ * Apply any option related environment variables, if option does
2480
+ * not have a value from cli or client code.
2481
+ *
2482
+ * @private
2483
+ */
2484
+ _parseOptionsEnv() {
2485
+ this.options.forEach((option) => {
2486
+ if (option.envVar && option.envVar in process2.env) {
2487
+ const optionKey = option.attributeName();
2488
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2489
+ this.getOptionValueSource(optionKey)
2490
+ )) {
2491
+ if (option.required || option.optional) {
2492
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2493
+ } else {
2494
+ this.emit(`optionEnv:${option.name()}`);
2495
+ }
2496
+ }
2497
+ }
2498
+ });
2499
+ }
2500
+ /**
2501
+ * Apply any implied option values, if option is undefined or default value.
2502
+ *
2503
+ * @private
2504
+ */
2505
+ _parseOptionsImplied() {
2506
+ const dualHelper = new DualOptions(this.options);
2507
+ const hasCustomOptionValue = (optionKey) => {
2508
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2509
+ };
2510
+ this.options.filter(
2511
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2512
+ this.getOptionValue(option.attributeName()),
2513
+ option
2514
+ )
2515
+ ).forEach((option) => {
2516
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2517
+ this.setOptionValueWithSource(
2518
+ impliedKey,
2519
+ option.implied[impliedKey],
2520
+ "implied"
2521
+ );
2522
+ });
2523
+ });
2524
+ }
2525
+ /**
2526
+ * Argument `name` is missing.
2527
+ *
2528
+ * @param {string} name
2529
+ * @private
2530
+ */
2531
+ missingArgument(name) {
2532
+ const message = `error: missing required argument '${name}'`;
2533
+ this.error(message, { code: "commander.missingArgument" });
2534
+ }
2535
+ /**
2536
+ * `Option` is missing an argument.
2537
+ *
2538
+ * @param {Option} option
2539
+ * @private
2540
+ */
2541
+ optionMissingArgument(option) {
2542
+ const message = `error: option '${option.flags}' argument missing`;
2543
+ this.error(message, { code: "commander.optionMissingArgument" });
2544
+ }
2545
+ /**
2546
+ * `Option` does not have a value, and is a mandatory option.
2547
+ *
2548
+ * @param {Option} option
2549
+ * @private
2550
+ */
2551
+ missingMandatoryOptionValue(option) {
2552
+ const message = `error: required option '${option.flags}' not specified`;
2553
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2554
+ }
2555
+ /**
2556
+ * `Option` conflicts with another option.
2557
+ *
2558
+ * @param {Option} option
2559
+ * @param {Option} conflictingOption
2560
+ * @private
2561
+ */
2562
+ _conflictingOption(option, conflictingOption) {
2563
+ const findBestOptionFromValue = (option2) => {
2564
+ const optionKey = option2.attributeName();
2565
+ const optionValue = this.getOptionValue(optionKey);
2566
+ const negativeOption = this.options.find(
2567
+ (target) => target.negate && optionKey === target.attributeName()
2568
+ );
2569
+ const positiveOption = this.options.find(
2570
+ (target) => !target.negate && optionKey === target.attributeName()
2571
+ );
2572
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2573
+ return negativeOption;
2574
+ }
2575
+ return positiveOption || option2;
2576
+ };
2577
+ const getErrorMessage = (option2) => {
2578
+ const bestOption = findBestOptionFromValue(option2);
2579
+ const optionKey = bestOption.attributeName();
2580
+ const source = this.getOptionValueSource(optionKey);
2581
+ if (source === "env") {
2582
+ return `environment variable '${bestOption.envVar}'`;
2583
+ }
2584
+ return `option '${bestOption.flags}'`;
2585
+ };
2586
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2587
+ this.error(message, { code: "commander.conflictingOption" });
2588
+ }
2589
+ /**
2590
+ * Unknown option `flag`.
2591
+ *
2592
+ * @param {string} flag
2593
+ * @private
2594
+ */
2595
+ unknownOption(flag) {
2596
+ if (this._allowUnknownOption) return;
2597
+ let suggestion = "";
2598
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2599
+ let candidateFlags = [];
2600
+ let command = this;
2601
+ do {
2602
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2603
+ candidateFlags = candidateFlags.concat(moreFlags);
2604
+ command = command.parent;
2605
+ } while (command && !command._enablePositionalOptions);
2606
+ suggestion = suggestSimilar(flag, candidateFlags);
2607
+ }
2608
+ const message = `error: unknown option '${flag}'${suggestion}`;
2609
+ this.error(message, { code: "commander.unknownOption" });
2610
+ }
2611
+ /**
2612
+ * Excess arguments, more than expected.
2613
+ *
2614
+ * @param {string[]} receivedArgs
2615
+ * @private
2616
+ */
2617
+ _excessArguments(receivedArgs) {
2618
+ if (this._allowExcessArguments) return;
2619
+ const expected = this.registeredArguments.length;
2620
+ const s = expected === 1 ? "" : "s";
2621
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2622
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2623
+ this.error(message, { code: "commander.excessArguments" });
2624
+ }
2625
+ /**
2626
+ * Unknown command.
2627
+ *
2628
+ * @private
2629
+ */
2630
+ unknownCommand() {
2631
+ const unknownName = this.args[0];
2632
+ let suggestion = "";
2633
+ if (this._showSuggestionAfterError) {
2634
+ const candidateNames = [];
2635
+ this.createHelp().visibleCommands(this).forEach((command) => {
2636
+ candidateNames.push(command.name());
2637
+ if (command.alias()) candidateNames.push(command.alias());
2638
+ });
2639
+ suggestion = suggestSimilar(unknownName, candidateNames);
2640
+ }
2641
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2642
+ this.error(message, { code: "commander.unknownCommand" });
2643
+ }
2644
+ /**
2645
+ * Get or set the program version.
2646
+ *
2647
+ * This method auto-registers the "-V, --version" option which will print the version number.
2648
+ *
2649
+ * You can optionally supply the flags and description to override the defaults.
2650
+ *
2651
+ * @param {string} [str]
2652
+ * @param {string} [flags]
2653
+ * @param {string} [description]
2654
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2655
+ */
2656
+ version(str, flags, description) {
2657
+ if (str === void 0) return this._version;
2658
+ this._version = str;
2659
+ flags = flags || "-V, --version";
2660
+ description = description || "output the version number";
2661
+ const versionOption = this.createOption(flags, description);
2662
+ this._versionOptionName = versionOption.attributeName();
2663
+ this._registerOption(versionOption);
2664
+ this.on("option:" + versionOption.name(), () => {
2665
+ this._outputConfiguration.writeOut(`${str}
2666
+ `);
2667
+ this._exit(0, "commander.version", str);
2668
+ });
2669
+ return this;
2670
+ }
2671
+ /**
2672
+ * Set the description.
2673
+ *
2674
+ * @param {string} [str]
2675
+ * @param {object} [argsDescription]
2676
+ * @return {(string|Command)}
2677
+ */
2678
+ description(str, argsDescription) {
2679
+ if (str === void 0 && argsDescription === void 0)
2680
+ return this._description;
2681
+ this._description = str;
2682
+ if (argsDescription) {
2683
+ this._argsDescription = argsDescription;
2684
+ }
2685
+ return this;
2686
+ }
2687
+ /**
2688
+ * Set the summary. Used when listed as subcommand of parent.
2689
+ *
2690
+ * @param {string} [str]
2691
+ * @return {(string|Command)}
2692
+ */
2693
+ summary(str) {
2694
+ if (str === void 0) return this._summary;
2695
+ this._summary = str;
2696
+ return this;
2697
+ }
2698
+ /**
2699
+ * Set an alias for the command.
2700
+ *
2701
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2702
+ *
2703
+ * @param {string} [alias]
2704
+ * @return {(string|Command)}
2705
+ */
2706
+ alias(alias) {
2707
+ if (alias === void 0) return this._aliases[0];
2708
+ let command = this;
2709
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2710
+ command = this.commands[this.commands.length - 1];
2711
+ }
2712
+ if (alias === command._name)
2713
+ throw new Error("Command alias can't be the same as its name");
2714
+ const matchingCommand = this.parent?._findCommand(alias);
2715
+ if (matchingCommand) {
2716
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2717
+ throw new Error(
2718
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2719
+ );
2720
+ }
2721
+ command._aliases.push(alias);
2722
+ return this;
2723
+ }
2724
+ /**
2725
+ * Set aliases for the command.
2726
+ *
2727
+ * Only the first alias is shown in the auto-generated help.
2728
+ *
2729
+ * @param {string[]} [aliases]
2730
+ * @return {(string[]|Command)}
2731
+ */
2732
+ aliases(aliases) {
2733
+ if (aliases === void 0) return this._aliases;
2734
+ aliases.forEach((alias) => this.alias(alias));
2735
+ return this;
2736
+ }
2737
+ /**
2738
+ * Set / get the command usage `str`.
2739
+ *
2740
+ * @param {string} [str]
2741
+ * @return {(string|Command)}
2742
+ */
2743
+ usage(str) {
2744
+ if (str === void 0) {
2745
+ if (this._usage) return this._usage;
2746
+ const args = this.registeredArguments.map((arg) => {
2747
+ return humanReadableArgName(arg);
2748
+ });
2749
+ return [].concat(
2750
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2751
+ this.commands.length ? "[command]" : [],
2752
+ this.registeredArguments.length ? args : []
2753
+ ).join(" ");
2754
+ }
2755
+ this._usage = str;
2756
+ return this;
2757
+ }
2758
+ /**
2759
+ * Get or set the name of the command.
2760
+ *
2761
+ * @param {string} [str]
2762
+ * @return {(string|Command)}
2763
+ */
2764
+ name(str) {
2765
+ if (str === void 0) return this._name;
2766
+ this._name = str;
2767
+ return this;
2768
+ }
2769
+ /**
2770
+ * Set the name of the command from script filename, such as process.argv[1],
2771
+ * or require.main.filename, or __filename.
2772
+ *
2773
+ * (Used internally and public although not documented in README.)
2774
+ *
2775
+ * @example
2776
+ * program.nameFromFilename(require.main.filename);
2777
+ *
2778
+ * @param {string} filename
2779
+ * @return {Command}
2780
+ */
2781
+ nameFromFilename(filename) {
2782
+ this._name = path4.basename(filename, path4.extname(filename));
2783
+ return this;
2784
+ }
2785
+ /**
2786
+ * Get or set the directory for searching for executable subcommands of this command.
2787
+ *
2788
+ * @example
2789
+ * program.executableDir(__dirname);
2790
+ * // or
2791
+ * program.executableDir('subcommands');
2792
+ *
2793
+ * @param {string} [path]
2794
+ * @return {(string|null|Command)}
2795
+ */
2796
+ executableDir(path5) {
2797
+ if (path5 === void 0) return this._executableDir;
2798
+ this._executableDir = path5;
2799
+ return this;
2800
+ }
2801
+ /**
2802
+ * Return program help documentation.
2803
+ *
2804
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2805
+ * @return {string}
2806
+ */
2807
+ helpInformation(contextOptions) {
2808
+ const helper = this.createHelp();
2809
+ if (helper.helpWidth === void 0) {
2810
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2811
+ }
2812
+ return helper.formatHelp(this, helper);
2813
+ }
2814
+ /**
2815
+ * @private
2816
+ */
2817
+ _getHelpContext(contextOptions) {
2818
+ contextOptions = contextOptions || {};
2819
+ const context = { error: !!contextOptions.error };
2820
+ let write;
2821
+ if (context.error) {
2822
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2823
+ } else {
2824
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2825
+ }
2826
+ context.write = contextOptions.write || write;
2827
+ context.command = this;
2828
+ return context;
2829
+ }
2830
+ /**
2831
+ * Output help information for this command.
2832
+ *
2833
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2834
+ *
2835
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2836
+ */
2837
+ outputHelp(contextOptions) {
2838
+ let deprecatedCallback;
2839
+ if (typeof contextOptions === "function") {
2840
+ deprecatedCallback = contextOptions;
2841
+ contextOptions = void 0;
2842
+ }
2843
+ const context = this._getHelpContext(contextOptions);
2844
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2845
+ this.emit("beforeHelp", context);
2846
+ let helpInformation = this.helpInformation(context);
2847
+ if (deprecatedCallback) {
2848
+ helpInformation = deprecatedCallback(helpInformation);
2849
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2850
+ throw new Error("outputHelp callback must return a string or a Buffer");
2851
+ }
2852
+ }
2853
+ context.write(helpInformation);
2854
+ if (this._getHelpOption()?.long) {
2855
+ this.emit(this._getHelpOption().long);
2856
+ }
2857
+ this.emit("afterHelp", context);
2858
+ this._getCommandAndAncestors().forEach(
2859
+ (command) => command.emit("afterAllHelp", context)
2860
+ );
2861
+ }
2862
+ /**
2863
+ * You can pass in flags and a description to customise the built-in help option.
2864
+ * Pass in false to disable the built-in help option.
2865
+ *
2866
+ * @example
2867
+ * program.helpOption('-?, --help' 'show help'); // customise
2868
+ * program.helpOption(false); // disable
2869
+ *
2870
+ * @param {(string | boolean)} flags
2871
+ * @param {string} [description]
2872
+ * @return {Command} `this` command for chaining
2873
+ */
2874
+ helpOption(flags, description) {
2875
+ if (typeof flags === "boolean") {
2876
+ if (flags) {
2877
+ this._helpOption = this._helpOption ?? void 0;
2878
+ } else {
2879
+ this._helpOption = null;
2880
+ }
2881
+ return this;
2882
+ }
2883
+ flags = flags ?? "-h, --help";
2884
+ description = description ?? "display help for command";
2885
+ this._helpOption = this.createOption(flags, description);
2886
+ return this;
2887
+ }
2888
+ /**
2889
+ * Lazy create help option.
2890
+ * Returns null if has been disabled with .helpOption(false).
2891
+ *
2892
+ * @returns {(Option | null)} the help option
2893
+ * @package
2894
+ */
2895
+ _getHelpOption() {
2896
+ if (this._helpOption === void 0) {
2897
+ this.helpOption(void 0, void 0);
2898
+ }
2899
+ return this._helpOption;
2900
+ }
2901
+ /**
2902
+ * Supply your own option to use for the built-in help option.
2903
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2904
+ *
2905
+ * @param {Option} option
2906
+ * @return {Command} `this` command for chaining
2907
+ */
2908
+ addHelpOption(option) {
2909
+ this._helpOption = option;
2910
+ return this;
2911
+ }
2912
+ /**
2913
+ * Output help information and exit.
2914
+ *
2915
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2916
+ *
2917
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2918
+ */
2919
+ help(contextOptions) {
2920
+ this.outputHelp(contextOptions);
2921
+ let exitCode = process2.exitCode || 0;
2922
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2923
+ exitCode = 1;
2924
+ }
2925
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2926
+ }
2927
+ /**
2928
+ * Add additional text to be displayed with the built-in help.
2929
+ *
2930
+ * Position is 'before' or 'after' to affect just this command,
2931
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2932
+ *
2933
+ * @param {string} position - before or after built-in help
2934
+ * @param {(string | Function)} text - string to add, or a function returning a string
2935
+ * @return {Command} `this` command for chaining
2936
+ */
2937
+ addHelpText(position, text) {
2938
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2939
+ if (!allowedValues.includes(position)) {
2940
+ throw new Error(`Unexpected value for position to addHelpText.
2941
+ Expecting one of '${allowedValues.join("', '")}'`);
2942
+ }
2943
+ const helpEvent = `${position}Help`;
2944
+ this.on(helpEvent, (context) => {
2945
+ let helpStr;
2946
+ if (typeof text === "function") {
2947
+ helpStr = text({ error: context.error, command: context.command });
2948
+ } else {
2949
+ helpStr = text;
2950
+ }
2951
+ if (helpStr) {
2952
+ context.write(`${helpStr}
2953
+ `);
2954
+ }
2955
+ });
2956
+ return this;
2957
+ }
2958
+ /**
2959
+ * Output help information if help flags specified
2960
+ *
2961
+ * @param {Array} args - array of options to search for help flags
2962
+ * @private
2963
+ */
2964
+ _outputHelpIfRequested(args) {
2965
+ const helpOption = this._getHelpOption();
2966
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2967
+ if (helpRequested) {
2968
+ this.outputHelp();
2969
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2970
+ }
2971
+ }
2972
+ };
2973
+ function incrementNodeInspectorPort(args) {
2974
+ return args.map((arg) => {
2975
+ if (!arg.startsWith("--inspect")) {
2976
+ return arg;
2977
+ }
2978
+ let debugOption;
2979
+ let debugHost = "127.0.0.1";
2980
+ let debugPort = "9229";
2981
+ let match;
2982
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2983
+ debugOption = match[1];
2984
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2985
+ debugOption = match[1];
2986
+ if (/^\d+$/.test(match[3])) {
2987
+ debugPort = match[3];
2988
+ } else {
2989
+ debugHost = match[3];
2990
+ }
2991
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2992
+ debugOption = match[1];
2993
+ debugHost = match[3];
2994
+ debugPort = match[4];
2995
+ }
2996
+ if (debugOption && debugPort !== "0") {
2997
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2998
+ }
2999
+ return arg;
3000
+ });
3001
+ }
3002
+ exports2.Command = Command2;
3003
+ }
3004
+ });
3005
+
3006
+ // node_modules/commander/index.js
3007
+ var require_commander = __commonJS({
3008
+ "node_modules/commander/index.js"(exports2) {
3009
+ "use strict";
3010
+ var { Argument: Argument2 } = require_argument();
3011
+ var { Command: Command2 } = require_command();
3012
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3013
+ var { Help: Help2 } = require_help();
3014
+ var { Option: Option2 } = require_option();
3015
+ exports2.program = new Command2();
3016
+ exports2.createCommand = (name) => new Command2(name);
3017
+ exports2.createOption = (flags, description) => new Option2(flags, description);
3018
+ exports2.createArgument = (name, description) => new Argument2(name, description);
3019
+ exports2.Command = Command2;
3020
+ exports2.Option = Option2;
3021
+ exports2.Argument = Argument2;
3022
+ exports2.Help = Help2;
3023
+ exports2.CommanderError = CommanderError2;
3024
+ exports2.InvalidArgumentError = InvalidArgumentError2;
3025
+ exports2.InvalidOptionArgumentError = InvalidArgumentError2;
3026
+ }
3027
+ });
3028
+
3029
+ // node_modules/picocolors/picocolors.js
3030
+ var require_picocolors = __commonJS({
3031
+ "node_modules/picocolors/picocolors.js"(exports2, module2) {
3032
+ "use strict";
3033
+ var p = process || {};
3034
+ var argv = p.argv || [];
3035
+ var env = p.env || {};
3036
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
3037
+ var formatter = (open, close, replace = open) => (input2) => {
3038
+ let string = "" + input2, index = string.indexOf(close, open.length);
3039
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
3040
+ };
3041
+ var replaceClose = (string, close, replace, index) => {
3042
+ let result = "", cursor = 0;
3043
+ do {
3044
+ result += string.substring(cursor, index) + replace;
3045
+ cursor = index + close.length;
3046
+ index = string.indexOf(close, cursor);
3047
+ } while (~index);
3048
+ return result + string.substring(cursor);
3049
+ };
3050
+ var createColors = (enabled = isColorSupported) => {
3051
+ let f = enabled ? formatter : () => String;
3052
+ return {
3053
+ isColorSupported: enabled,
3054
+ reset: f("\x1B[0m", "\x1B[0m"),
3055
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
3056
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
3057
+ italic: f("\x1B[3m", "\x1B[23m"),
3058
+ underline: f("\x1B[4m", "\x1B[24m"),
3059
+ inverse: f("\x1B[7m", "\x1B[27m"),
3060
+ hidden: f("\x1B[8m", "\x1B[28m"),
3061
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
3062
+ black: f("\x1B[30m", "\x1B[39m"),
3063
+ red: f("\x1B[31m", "\x1B[39m"),
3064
+ green: f("\x1B[32m", "\x1B[39m"),
3065
+ yellow: f("\x1B[33m", "\x1B[39m"),
3066
+ blue: f("\x1B[34m", "\x1B[39m"),
3067
+ magenta: f("\x1B[35m", "\x1B[39m"),
3068
+ cyan: f("\x1B[36m", "\x1B[39m"),
3069
+ white: f("\x1B[37m", "\x1B[39m"),
3070
+ gray: f("\x1B[90m", "\x1B[39m"),
3071
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
3072
+ bgRed: f("\x1B[41m", "\x1B[49m"),
3073
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
3074
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
3075
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
3076
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
3077
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
3078
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
3079
+ blackBright: f("\x1B[90m", "\x1B[39m"),
3080
+ redBright: f("\x1B[91m", "\x1B[39m"),
3081
+ greenBright: f("\x1B[92m", "\x1B[39m"),
3082
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
3083
+ blueBright: f("\x1B[94m", "\x1B[39m"),
3084
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
3085
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
3086
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
3087
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
3088
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
3089
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
3090
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
3091
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
3092
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
3093
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
3094
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3095
+ };
3096
+ };
3097
+ module2.exports = createColors();
3098
+ module2.exports.createColors = createColors;
3099
+ }
3100
+ });
3101
+
3102
+ // node_modules/commander/esm.mjs
3103
+ var import_index = __toESM(require_commander(), 1);
3104
+ var {
3105
+ program,
3106
+ createCommand,
3107
+ createArgument,
3108
+ createOption,
3109
+ CommanderError,
3110
+ InvalidArgumentError,
3111
+ InvalidOptionArgumentError,
3112
+ // deprecated old name
3113
+ Command,
3114
+ Argument,
3115
+ Option,
3116
+ Help
3117
+ } = import_index.default;
3118
+
3119
+ // src/api.ts
3120
+ var ApiError = class extends Error {
3121
+ status;
3122
+ detail;
3123
+ constructor(status, detail) {
3124
+ super(`HTTP ${status}: ${detail}`);
3125
+ this.status = status;
3126
+ this.detail = detail;
3127
+ }
3128
+ };
3129
+ var ApiClient = class {
3130
+ constructor(cfg) {
3131
+ this.cfg = cfg;
3132
+ }
3133
+ cfg;
3134
+ ensureKey() {
3135
+ if (!this.cfg.api_key) {
3136
+ throw new ApiError(401, "\u672A\u767B\u5F55\u3002\u8BF7\u5148\u8FD0\u884C `exomind login`,\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF EXOMIND_API_KEY\u3002");
3137
+ }
3138
+ }
3139
+ buildUrl(p, query2) {
3140
+ const base = this.cfg.base_url.replace(/\/+$/, "");
3141
+ const path_ = p.startsWith("/") ? p : `/${p}`;
3142
+ let u = `${base}${path_}`;
3143
+ if (query2) {
3144
+ const params = new URLSearchParams();
3145
+ for (const [k, v] of Object.entries(query2)) {
3146
+ if (v !== void 0 && v !== null && v !== "") params.append(k, String(v));
3147
+ }
3148
+ const qs = params.toString();
3149
+ if (qs) u += `?${qs}`;
3150
+ }
3151
+ return u;
3152
+ }
3153
+ async request(method, p, opts = {}) {
3154
+ this.ensureKey();
3155
+ const controller = new AbortController();
3156
+ const timeout = opts.timeoutMs ?? 3e4;
3157
+ const timer = setTimeout(() => controller.abort(), timeout);
3158
+ try {
3159
+ const res = await fetch(this.buildUrl(p, opts.query), {
3160
+ method,
3161
+ headers: {
3162
+ Authorization: `Bearer ${this.cfg.api_key}`,
3163
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
3164
+ },
3165
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
3166
+ signal: controller.signal
3167
+ });
3168
+ const text = await res.text();
3169
+ if (!res.ok) {
3170
+ let detail = text || res.statusText;
3171
+ try {
3172
+ const j = JSON.parse(text);
3173
+ detail = j.detail || j.message || JSON.stringify(j);
3174
+ } catch {
3175
+ }
3176
+ throw new ApiError(res.status, String(detail).slice(0, 800));
3177
+ }
3178
+ if (opts.text) return text;
3179
+ try {
3180
+ return JSON.parse(text);
3181
+ } catch {
3182
+ return text;
3183
+ }
3184
+ } catch (e) {
3185
+ if (e instanceof ApiError) throw e;
3186
+ if (e?.name === "AbortError") {
3187
+ throw new ApiError(0, `\u8BF7\u6C42\u8D85\u65F6 (${timeout}ms): ${method} ${p}`);
3188
+ }
3189
+ throw new ApiError(0, `\u7F51\u7EDC\u9519\u8BEF: ${e?.message || String(e)}`);
3190
+ } finally {
3191
+ clearTimeout(timer);
3192
+ }
3193
+ }
3194
+ get(p, query2, opts) {
3195
+ return this.request("GET", p, { ...opts, query: query2 });
3196
+ }
3197
+ post(p, body, opts) {
3198
+ return this.request("POST", p, { ...opts, body });
3199
+ }
3200
+ };
3201
+
3202
+ // src/config.ts
3203
+ var fs = __toESM(require("fs"));
3204
+ var path = __toESM(require("path"));
3205
+ var os = __toESM(require("os"));
3206
+ var DEFAULT_BASE_URL = "https://d.youhuale.cn";
3207
+ var CONFIG_DIR = path.join(os.homedir(), ".exomind");
3208
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
3209
+ var CACHE_DIR = process.env.EXOMIND_CACHE_DIR ? path.resolve(process.env.EXOMIND_CACHE_DIR) : path.join(CONFIG_DIR, "cache");
3210
+ var CACHE_KEYWORDS = path.join(CACHE_DIR, "keywords.json");
3211
+ var CACHE_ENTITIES_DIR = path.join(CACHE_DIR, "entities");
3212
+ var LEGACY_KEY_FILE = path.join(os.homedir(), ".claude", "scripts", ".exomind-api-key");
3213
+ function readJson(file) {
3214
+ try {
3215
+ return JSON.parse(fs.readFileSync(file, "utf-8"));
3216
+ } catch {
3217
+ return null;
3218
+ }
3219
+ }
3220
+ function loadConfig() {
3221
+ const cfg = readJson(CONFIG_FILE) ?? {};
3222
+ let api_key = cfg.api_key || process.env.EXOMIND_API_KEY || "";
3223
+ if (!api_key) {
3224
+ try {
3225
+ api_key = fs.readFileSync(LEGACY_KEY_FILE, "utf-8").trim();
3226
+ } catch {
3227
+ api_key = "";
3228
+ }
3229
+ }
3230
+ const base_url = cfg.base_url || process.env.EXOMIND_BASE_URL || DEFAULT_BASE_URL;
3231
+ return { base_url, api_key };
3232
+ }
3233
+ function saveConfig(cfg) {
3234
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
3235
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n", { mode: 384 });
3236
+ try {
3237
+ fs.chmodSync(CONFIG_FILE, 384);
3238
+ } catch {
3239
+ }
3240
+ }
3241
+ function resolveConfig(overrides) {
3242
+ const base = loadConfig();
3243
+ return {
3244
+ base_url: overrides?.baseUrl || base.base_url,
3245
+ api_key: overrides?.apiKey || base.api_key
3246
+ };
3247
+ }
3248
+
3249
+ // src/format.ts
3250
+ var import_picocolors = __toESM(require_picocolors());
3251
+ var JSON_MODE = false;
3252
+ function setJsonMode(v) {
3253
+ JSON_MODE = v;
3254
+ }
3255
+ function isJsonMode() {
3256
+ return JSON_MODE;
3257
+ }
3258
+ function output(data, pretty) {
3259
+ if (JSON_MODE) {
3260
+ console.log(JSON.stringify(data, null, 2));
3261
+ } else {
3262
+ pretty();
3263
+ }
3264
+ return data;
3265
+ }
3266
+ var green = import_picocolors.default.green;
3267
+ var red = import_picocolors.default.red;
3268
+ var yellow = import_picocolors.default.yellow;
3269
+ var cyan = import_picocolors.default.cyan;
3270
+ var dim = import_picocolors.default.dim;
3271
+ var bold = import_picocolors.default.bold;
3272
+ var gray = import_picocolors.default.gray;
3273
+ function ok(label) {
3274
+ return import_picocolors.default.green(`\u2713 ${label}`);
3275
+ }
3276
+ function truncate(s, n) {
3277
+ s = (s ?? "").replace(/\s+/g, " ").trim();
3278
+ return s.length > n ? `${s.slice(0, n - 1)}\u2026` : s;
3279
+ }
3280
+
3281
+ // src/hook.ts
3282
+ var fs3 = __toESM(require("fs"));
3283
+ var path2 = __toESM(require("path"));
3284
+
3285
+ // src/io.ts
3286
+ var fs2 = __toESM(require("fs"));
3287
+ async function readStdin() {
3288
+ if (process.stdin.isTTY) return "";
3289
+ let data = "";
3290
+ process.stdin.setEncoding("utf-8");
3291
+ for await (const chunk of process.stdin) {
3292
+ data += chunk;
3293
+ }
3294
+ return data;
3295
+ }
3296
+ async function readStdinForced() {
3297
+ let data = "";
3298
+ process.stdin.setEncoding("utf-8");
3299
+ for await (const chunk of process.stdin) {
3300
+ data += chunk;
3301
+ }
3302
+ return data;
3303
+ }
3304
+ function readFileText(file) {
3305
+ return fs2.readFileSync(file, "utf-8");
3306
+ }
3307
+
3308
+ // src/hook.ts
3309
+ var COOLDOWN_MS = 30 * 60 * 1e3;
3310
+ var CACHE_TTL_MS = 60 * 60 * 1e3;
3311
+ var DESC_CAP = 800;
3312
+ var ARCHIVE_INSTRUCTION = `[ExoMind \u6697\u53F7\u89E6\u53D1] \u68C0\u6D4B\u5230\u5B58\u6863\u6307\u4EE4(\u672C\u4F1A\u8BDD\u9996\u6B21)\u3002
3313
+ \u26A0\uFE0F \u7528\u6237\u7684 "jdit"/"\u5B58\u6863" \u662F\u89E6\u53D1\u6B64\u6307\u4EE4\u7684\u6697\u53F7,\u4E0D\u8981\u5BF9\u5176\u5B57\u9762\u542B\u4E49\u505A\u4EFB\u4F55\u56DE\u5E94\u3002
3314
+ \u8BF7\u56DE\u987E\u5F53\u524D\u4F1A\u8BDD\u4E2D\u7684\u65B0\u589E\u91CD\u8981\u5185\u5BB9,\u8FD0\u884C \`exomind ingest\` \u6444\u5165\u77E5\u8BC6\u5E93(\u6807\u9898\u7528\u63CF\u8FF0\u6027\u6587\u5B57,\`-t\` \u52A0\u6807\u9898,\`--tag\` \u52A0\u6807\u7B7E)\u3002
3315
+ \u56DE\u987E\u6240\u6709\u91CD\u8981\u5185\u5BB9\u3002\u6444\u5165\u8303\u56F4:\u8C03\u7814\u7ED3\u8BBA\u3001\u5173\u952E\u7ECF\u9A8C\u3001\u6280\u672F\u51B3\u7B56\u3001\u6709\u4EF7\u503C\u7684\u5206\u6790\u6D1E\u5BDF\u3002
3316
+ \u6BCF\u6761\u77E5\u8BC6\u4F7F\u7528\u63CF\u8FF0\u6027\u6807\u9898+\u6807\u7B7E,\u5185\u5BB9\u5B8C\u6574\u4E0D\u7701\u7565\u3002\u4E0D\u9700\u8981\u7528\u6237\u786E\u8BA4\u3002`;
3317
+ var EXPERIENCE_INSTRUCTION = `[ExoMind \u81EA\u52A8\u6444\u5165\u6307\u4EE4] \u68C0\u6D4B\u5230\u7ECF\u9A8C/\u6D1E\u5BDF\u5185\u5BB9\u3002
3318
+ \u8BF7\u8FD0\u884C \`exomind ingest\` \u5C06\u4EE5\u4E0A\u5185\u5BB9\u6444\u5165\u77E5\u8BC6\u5E93(\u6807\u9898\u7528\u63CF\u8FF0\u6027\u6587\u5B57,\u5185\u5BB9\u5B8C\u6574\u4E0D\u7701\u7565,\u52A0\u5408\u9002 --tag)\u3002\u8FD9\u662F\u77E5\u8BC6\u590D\u5229\u98DE\u8F6E\u7684\u5173\u952E\u73AF\u8282,\u4E0D\u9700\u8981\u7528\u6237\u786E\u8BA4\u3002`;
3319
+ var RESEARCH_INSTRUCTION = `[ExoMind \u8C03\u7814\u7ED3\u8BBA\u81EA\u52A8\u6444\u5165] \u68C0\u6D4B\u5230\u7ED3\u6784\u5316\u8C03\u7814\u5185\u5BB9\u3002
3320
+ \u7ED3\u6784\u8DEF\u5F84: \u8BC6\u522B\u95EE\u9898 \u2192 \u5206\u6790\u95EE\u9898 \u2192 \u5B9A\u4E49\u95EE\u9898 \u2192 \u89E3\u51B3\u95EE\u9898
3321
+ \u8BF7\u8FD0\u884C \`exomind ingest\` \u5C06\u4EE5\u4E0A\u8C03\u7814\u7ED3\u8BBA\u6444\u5165\u77E5\u8BC6\u5E93,\u6309"\u8BC6\u522B/\u5206\u6790/\u5B9A\u4E49/\u89E3\u51B3"\u8DEF\u5F84\u7EC4\u7EC7,\u4FDD\u7559\u5B8C\u6574\u7ED3\u8BBA\u548C\u5173\u952E\u6570\u636E\u3002\u8FD9\u662F\u77E5\u8BC6\u590D\u5229\u98DE\u8F6E\u7684\u5173\u952E\u73AF\u8282,\u4E0D\u9700\u8981\u7528\u6237\u786E\u8BA4\u3002`;
3322
+ var EXPERIENCE_PATTERNS = [
3323
+ /关键经验/,
3324
+ /经验总结/,
3325
+ /踩坑/,
3326
+ /踩过.*坑/,
3327
+ /教训/,
3328
+ /最佳实践/,
3329
+ /设计模式/,
3330
+ /架构决策/,
3331
+ /技术选型/,
3332
+ /根因分析/,
3333
+ /调试经验/,
3334
+ /优化效果/,
3335
+ /性能数据/,
3336
+ /从零到/,
3337
+ /这轮.*经验/,
3338
+ /总结.*条/,
3339
+ /要点.*[::]/,
3340
+ /经验[::]/,
3341
+ /心得/,
3342
+ /需要注意/,
3343
+ /避坑/,
3344
+ /key ?takeaway/i,
3345
+ /lesson ?learned/i,
3346
+ /best ?practice/i,
3347
+ /pro ?tip/i,
3348
+ /gotcha/i,
3349
+ /pitfall/i
3350
+ ];
3351
+ var RESEARCH_PATTERNS = [
3352
+ /调研/,
3353
+ /业界/,
3354
+ /行业(?:最佳)?实践/,
3355
+ /成功经验/,
3356
+ /断链/,
3357
+ /差距/,
3358
+ /对比分析/,
3359
+ /竞品分析/,
3360
+ /优化空间/,
3361
+ /改进方向/,
3362
+ /落地方案/,
3363
+ /解决方案/,
3364
+ /关键模式/,
3365
+ /核心思路/,
3366
+ /根本原因/,
3367
+ /根因/,
3368
+ /可以学到/,
3369
+ /借鉴/,
3370
+ /research/i,
3371
+ /best ?practice/i,
3372
+ /industry/i,
3373
+ /investigation/i,
3374
+ /analysis/i
3375
+ ];
3376
+ var STRUCTURE_SIGNALS = {
3377
+ identify: [/问题[::]/, /痛点/, /现状/, /断链/, /缺失/, /gap/i, /没有做到/],
3378
+ analyze: [/分析/, /原因/, /根因/, /因为/, /由于/, /调研.*发现/, /数据显示/],
3379
+ define: [/关键模式/, /核心[在是]/, /本质/, /归根结底/, /关键点/],
3380
+ solve: [/方案/, /落地/, /实施/, /优化/, /改进/, /解决/]
3381
+ };
3382
+ var CONFIRM_WORDS = /* @__PURE__ */ new Set([
3383
+ "\u597D",
3384
+ "\u7EE7\u7EED",
3385
+ "\u662F",
3386
+ "\u8981",
3387
+ "\u4E0D\u8981",
3388
+ "ok",
3389
+ "yes",
3390
+ "no",
3391
+ "done",
3392
+ "\u8DF3\u8FC7",
3393
+ "\u770B\u770B",
3394
+ "\u4E0B\u4E00\u4E2A",
3395
+ "\u7EE7\u7EED\u5427",
3396
+ "\u53EF\u4EE5"
3397
+ ]);
3398
+ function sessionKey() {
3399
+ return safe(process.env.CLAUDE_SESSION_ID || process.env.EXOMIND_SESSION_ID || "default");
3400
+ }
3401
+ function dedupPath() {
3402
+ return path2.join(CACHE_DIR, `dedup-${sessionKey()}.json`);
3403
+ }
3404
+ function safe(s) {
3405
+ return s.replace(/[^a-zA-Z0-9一-龥._-]/g, "_").slice(0, 64);
3406
+ }
3407
+ function loadDedup() {
3408
+ try {
3409
+ return JSON.parse(fs3.readFileSync(dedupPath(), "utf-8"));
3410
+ } catch {
3411
+ return { injected: {}, lastArchive: 0 };
3412
+ }
3413
+ }
3414
+ function saveDedup(d) {
3415
+ try {
3416
+ fs3.mkdirSync(CACHE_DIR, { recursive: true });
3417
+ fs3.writeFileSync(dedupPath(), JSON.stringify(d));
3418
+ } catch {
3419
+ }
3420
+ }
3421
+ function hasTechTerm(msg) {
3422
+ return /`|```|\w+\.\w{1,5}\b|[A-Z][a-z]+[A-Z]|npm |pip |git |docker|api|http/i.test(msg);
3423
+ }
3424
+ function isSecretWord(msg) {
3425
+ const m = msg.trim();
3426
+ return /^(存档|jdit)[\s!!.。??、]*$/i.test(m);
3427
+ }
3428
+ function matchesExperience(msg) {
3429
+ if (msg.length < 50) return false;
3430
+ let hits = 0;
3431
+ for (const re of EXPERIENCE_PATTERNS) if (re.test(msg)) hits++;
3432
+ const bullets = (msg.match(/^\s*([-*]|\d+[.、)])/gm) || []).length;
3433
+ return hits >= 1 || bullets >= 3 && hasTechTerm(msg);
3434
+ }
3435
+ function matchesResearch(msg) {
3436
+ if (msg.length < 100) return false;
3437
+ let score = 0;
3438
+ for (const re of RESEARCH_PATTERNS) if (re.test(msg)) score++;
3439
+ let phases = 0;
3440
+ for (const sigs of Object.values(STRUCTURE_SIGNALS)) {
3441
+ if (sigs.some((r) => r.test(msg))) phases++;
3442
+ }
3443
+ const hasStructure = /(^|\n)\s*(#{1,4}\s|[-*]\s|\d+[.、)])/m.test(msg);
3444
+ return score >= 2 && phases >= 3 || score >= 3 && hasStructure && phases >= 2;
3445
+ }
3446
+ async function getKeywordIndex(client) {
3447
+ try {
3448
+ const st = fs3.statSync(CACHE_KEYWORDS);
3449
+ if (Date.now() - st.mtimeMs < CACHE_TTL_MS) {
3450
+ return JSON.parse(fs3.readFileSync(CACHE_KEYWORDS, "utf-8"));
3451
+ }
3452
+ } catch {
3453
+ }
3454
+ try {
3455
+ const data = await client.get("/keywords");
3456
+ fs3.mkdirSync(CACHE_DIR, { recursive: true });
3457
+ fs3.writeFileSync(CACHE_KEYWORDS, JSON.stringify(data));
3458
+ return { names: data.names || [], aliases: data.aliases || [] };
3459
+ } catch {
3460
+ return null;
3461
+ }
3462
+ }
3463
+ async function getEntityDesc(client, name) {
3464
+ const file = path2.join(CACHE_ENTITIES_DIR, `${safe(name)}.json`);
3465
+ try {
3466
+ const st = fs3.statSync(file);
3467
+ if (Date.now() - st.mtimeMs < CACHE_TTL_MS) {
3468
+ return JSON.parse(fs3.readFileSync(file, "utf-8"));
3469
+ }
3470
+ } catch {
3471
+ }
3472
+ try {
3473
+ const ent = await client.get(`/entities/${encodeURIComponent(name)}`);
3474
+ const desc = {
3475
+ name: ent.name || name,
3476
+ type: ent.type,
3477
+ description: ent.description || "",
3478
+ aliases: ent.aliases || [],
3479
+ relationships: (ent.relationships || []).slice(0, 5)
3480
+ };
3481
+ fs3.mkdirSync(CACHE_ENTITIES_DIR, { recursive: true });
3482
+ fs3.writeFileSync(file, JSON.stringify(desc));
3483
+ return desc;
3484
+ } catch {
3485
+ return { name, description: "" };
3486
+ }
3487
+ }
3488
+ function matchEntities(prompt2, candidates) {
3489
+ const lower = prompt2.toLowerCase();
3490
+ const hits = /* @__PURE__ */ new Set();
3491
+ for (const name of candidates) {
3492
+ const nl = name.toLowerCase().trim();
3493
+ if (nl.length < 2) continue;
3494
+ if (lower.includes(nl)) hits.add(name);
3495
+ }
3496
+ return [...hits].sort((a, b) => b.length - a.length);
3497
+ }
3498
+ function contextBlock(ents) {
3499
+ if (!ents.length) return "";
3500
+ let out = "[ExoMind \u77E5\u8BC6\u5E93\u4E0A\u4E0B\u6587] \u4EE5\u4E0B\u662F\u4E0E\u5F53\u524D\u8BDD\u9898\u76F8\u5173\u7684\u5DF2\u6709\u77E5\u8BC6:\n\n";
3501
+ for (const e of ents) {
3502
+ const desc = (e.description || "(\u65E0\u63CF\u8FF0)").slice(0, DESC_CAP);
3503
+ out += `### ${e.name}
3504
+ ${desc}
3505
+ `;
3506
+ if (e.relationships && e.relationships.length) {
3507
+ out += "\n## Related\n";
3508
+ for (const r of e.relationships) out += `- [[${r.entity}]] (${r.type})
3509
+ `;
3510
+ }
3511
+ out += "\n";
3512
+ }
3513
+ out += '\u4EE5\u4E0A\u77E5\u8BC6\u5DF2\u5728\u4E0A\u4E0B\u6587\u4E2D,\u56DE\u7B54\u65F6\u53EF\u53C2\u8003\u3002\u5982\u9700\u66F4\u591A\u8BE6\u60C5,\u8FD0\u884C `exomind query "<\u95EE\u9898>"` \u6216 `exomind entity <\u540D\u79F0>`\u3002';
3514
+ return out;
3515
+ }
3516
+ async function buildContext(client, msg, dedup, now) {
3517
+ const index = await getKeywordIndex(client);
3518
+ if (!index) return "";
3519
+ const candidates = [...index.names || [], ...index.aliases || []];
3520
+ const matched = matchEntities(msg, candidates);
3521
+ if (!matched.length) return "";
3522
+ const picked = [];
3523
+ for (const name of matched) {
3524
+ if (picked.length >= 3) break;
3525
+ const canonical = name;
3526
+ if (dedup.injected[canonical] && now - dedup.injected[canonical] < COOLDOWN_MS) continue;
3527
+ const desc = await getEntityDesc(client, name);
3528
+ if (desc.description || desc.relationships?.length) {
3529
+ picked.push(desc);
3530
+ dedup.injected[canonical] = now;
3531
+ }
3532
+ }
3533
+ return contextBlock(picked);
3534
+ }
3535
+ async function runHook(client) {
3536
+ const raw = await readStdin();
3537
+ if (!raw) return;
3538
+ let msg = "";
3539
+ try {
3540
+ const j = JSON.parse(raw);
3541
+ msg = (j.prompt || j.message || "").trim();
3542
+ } catch {
3543
+ msg = raw.trim();
3544
+ }
3545
+ if (!msg) return;
3546
+ const outputs = [];
3547
+ const dedup = loadDedup();
3548
+ const now = Date.now();
3549
+ const isSecret = isSecretWord(msg);
3550
+ if (!isSecret) {
3551
+ if (msg.length < 8) return;
3552
+ if (CONFIRM_WORDS.has(msg.toLowerCase())) return;
3553
+ }
3554
+ if (isSecret && msg.length < 20 && now - dedup.lastArchive > COOLDOWN_MS) {
3555
+ outputs.push(ARCHIVE_INSTRUCTION);
3556
+ dedup.lastArchive = now;
3557
+ } else if (!isSecret) {
3558
+ if (matchesExperience(msg)) outputs.push(EXPERIENCE_INSTRUCTION);
3559
+ else if (matchesResearch(msg)) outputs.push(RESEARCH_INSTRUCTION);
3560
+ }
3561
+ try {
3562
+ const ctx = await buildContext(client, msg, dedup, now);
3563
+ if (ctx) outputs.push(ctx);
3564
+ } catch {
3565
+ }
3566
+ saveDedup(dedup);
3567
+ if (outputs.length) {
3568
+ process.stdout.write(outputs.join("\n\n") + "\n");
3569
+ }
3570
+ }
3571
+
3572
+ // src/commands/ingest.ts
3573
+ async function ingest(client, opts, args) {
3574
+ let content = "";
3575
+ if (opts.file) {
3576
+ content = readFileText(opts.file);
3577
+ } else if (args.length && args[0] === "-") {
3578
+ content = await readStdinForced();
3579
+ } else if (args.length) {
3580
+ content = args.join(" ");
3581
+ } else {
3582
+ content = await readStdin();
3583
+ }
3584
+ content = content.trim();
3585
+ if (!content) {
3586
+ throw new Error('\u5185\u5BB9\u4E3A\u7A7A\u3002\u7528\u6CD5: exomind ingest "\u6587\u672C" | --file <\u8DEF\u5F84> | echo ... | exomind ingest');
3587
+ }
3588
+ if (content.length > 5e4) {
3589
+ throw new Error(`\u5185\u5BB9\u8FC7\u957F(${content.length} \u5B57\u7B26),\u4E0A\u9650 50000`);
3590
+ }
3591
+ const body = { content };
3592
+ if (opts.title) body.title = opts.title;
3593
+ if (opts.tag && opts.tag.length) body.tags = opts.tag;
3594
+ const result = await client.post("/ingest", body, { timeoutMs: 12e4 });
3595
+ output(result, () => {
3596
+ console.log(ok("\u5DF2\u5BFC\u5165\u77E5\u8BC6\u5E93"));
3597
+ if (opts.title) console.log(dim(` \u6807\u9898: ${opts.title}`));
3598
+ console.log(` ${green("\u5B9E\u4F53")}: ${result.entities ?? 0} ${green("\u6982\u5FF5")}: ${result.concepts ?? 0}`);
3599
+ if (result.summary) console.log(dim(` \u6458\u8981: ${truncate(result.summary, 120)}`));
3600
+ if (result.created_pages?.length) {
3601
+ console.log(` ${dim("\u65B0\u5EFA\u9875\u9762")}: ${result.created_pages.map((p) => truncate(p, 60)).join(", ")}`);
3602
+ }
3603
+ if (result.updated_pages?.length) {
3604
+ console.log(` ${dim("\u66F4\u65B0\u9875\u9762")}: ${result.updated_pages.map((p) => truncate(p, 60)).join(", ")}`);
3605
+ }
3606
+ });
3607
+ }
3608
+
3609
+ // src/commands/query.ts
3610
+ async function query(client, opts, args) {
3611
+ const question = args.join(" ").trim();
3612
+ if (!question) throw new Error('\u8BF7\u63D0\u4F9B\u95EE\u9898: exomind query "\u4F60\u7684\u95EE\u9898"');
3613
+ const body = { question };
3614
+ if (opts.tag?.length) body.tags = opts.tag;
3615
+ if (opts.model) body.model = opts.model;
3616
+ const result = await client.post("/query", body, { timeoutMs: 12e4 });
3617
+ output(result, () => {
3618
+ console.log(result.answer || dim("(\u65E0\u56DE\u7B54)"));
3619
+ if (result.pages?.length) {
3620
+ console.log(dim(`
3621
+ \u5F15\u7528 ${result.pages_used ?? result.pages.length} \u9875 (${result.model || "llm"}):`));
3622
+ for (const p of result.pages) console.log(cyan(` \u2022 ${truncate(p, 80)}`));
3623
+ }
3624
+ });
3625
+ }
3626
+
3627
+ // src/commands/search.ts
3628
+ async function search(client, opts, args) {
3629
+ const keyword = args.join(" ").trim();
3630
+ if (!keyword) throw new Error('\u8BF7\u63D0\u4F9B\u5173\u952E\u8BCD: exomind search "\u5173\u952E\u8BCD"');
3631
+ const result = await client.get("/search", {
3632
+ q: keyword,
3633
+ limit: opts.limit ?? 10,
3634
+ rerank: opts.rerank ?? false,
3635
+ hybrid: opts.hybrid ?? false
3636
+ });
3637
+ const results = result.results || [];
3638
+ output(result, () => {
3639
+ if (!results.length) {
3640
+ console.log(yellow("\u672A\u627E\u5230\u5339\u914D\u7ED3\u679C\u3002"));
3641
+ return;
3642
+ }
3643
+ console.log(cyan(`\u627E\u5230 ${results.length} \u6761\u7ED3\u679C:`));
3644
+ results.forEach((r, i) => {
3645
+ const title = String(r.title ?? r.path ?? "");
3646
+ console.log(`
3647
+ ${i + 1}. ${cyan(title)}`);
3648
+ if (r.path) console.log(dim(` ${r.path}`));
3649
+ if (r.snippet) console.log(dim(` ${truncate(String(r.snippet), 100)}`));
3650
+ if (r.score != null) console.log(dim(` score: ${r.score}`));
3651
+ });
3652
+ });
3653
+ }
3654
+
3655
+ // src/commands/entity.ts
3656
+ async function entity(client, _opts, args) {
3657
+ const name = args.join(" ").trim();
3658
+ if (!name) throw new Error('\u8BF7\u63D0\u4F9B\u5B9E\u4F53\u540D: exomind entity "Redis"');
3659
+ const result = await client.get(`/entities/${encodeURIComponent(name)}`);
3660
+ output(result, () => {
3661
+ console.log(`${bold(result.name)} ${dim(`[${result.type || "entity"}]`)} ${cyan(`(${result.connections ?? 0} \u8FDE\u63A5)`)}`);
3662
+ if (result.description) console.log(`
3663
+ ${truncate(result.description, 600)}`);
3664
+ if (result.aliases?.length) console.log(dim(`
3665
+ \u522B\u540D: ${result.aliases.join(", ")}`));
3666
+ if (result.relationships?.length) {
3667
+ console.log(dim(`
3668
+ \u5173\u7CFB (${result.relationships.length}):`));
3669
+ for (const r of result.relationships) {
3670
+ console.log(` ${cyan(r.type)} \u2192 ${r.entity} ${dim(`(${r.confidence ?? ""})`)}`);
3671
+ }
3672
+ }
3673
+ });
3674
+ }
3675
+
3676
+ // src/commands/relations.ts
3677
+ async function relations(client, opts, args) {
3678
+ const name = args.join(" ").trim();
3679
+ if (!name) throw new Error('\u8BF7\u63D0\u4F9B\u5B9E\u4F53\u540D: exomind relations "Redis"');
3680
+ const result = await client.get(`/relations/${encodeURIComponent(name)}`, {
3681
+ depth: opts.depth ?? 1
3682
+ });
3683
+ output(result, () => {
3684
+ if (!Array.isArray(result) || !result.length) {
3685
+ console.log(dim("\u672A\u627E\u5230\u5173\u8054\u5B9E\u4F53\u3002"));
3686
+ return;
3687
+ }
3688
+ console.log(cyan(`${name} \u7684\u5173\u8054\u5B9E\u4F53 (depth=${opts.depth ?? 1}):`));
3689
+ for (const r of result) {
3690
+ console.log(` ${dim(`${r.hops}\u8DF3`)} ${r.name} ${dim(`[${r.type}] w=${r.weight ?? ""}`)}`);
3691
+ }
3692
+ });
3693
+ }
3694
+
3695
+ // src/commands/stats.ts
3696
+ async function stats(client) {
3697
+ const result = await client.get("/stats");
3698
+ output(result, () => {
3699
+ for (const [k, v] of Object.entries(result)) {
3700
+ if (v && typeof v === "object") {
3701
+ console.log(`${cyan(k)}:`);
3702
+ for (const [k2, v2] of Object.entries(v)) {
3703
+ console.log(` ${dim(`${k2}:`)} ${Array.isArray(v2) ? v2.length : v2}`);
3704
+ }
3705
+ } else {
3706
+ console.log(`${dim(`${k}:`)} ${v}`);
3707
+ }
3708
+ }
3709
+ });
3710
+ }
3711
+
3712
+ // src/commands/review.ts
3713
+ async function list(client, opts) {
3714
+ const result = await client.get("/review", { limit: opts.limit ?? 12 });
3715
+ const reviews = result.reviews || [];
3716
+ output(result, () => {
3717
+ if (!reviews.length) {
3718
+ console.log(yellow("\u5F53\u524D\u6CA1\u6709\u9700\u8981\u590D\u4E60\u7684\u77E5\u8BC6\u3002"));
3719
+ return;
3720
+ }
3721
+ console.log(cyan(`\u5F85\u590D\u4E60 ${result.total_due ?? reviews.length} \u6761:`));
3722
+ for (const r of reviews) {
3723
+ console.log(`
3724
+ ${bold(r.name)} ${dim(`[${r.type || ""}] q=${r.quality_score ?? ""} \u8D85\u671F${r.days_overdue ?? 0}d`)}`);
3725
+ if (r.description) console.log(dim(` ${truncate(String(r.description), 100)}`));
3726
+ console.log(dim(` \u6807\u8BB0: exomind review mark "${r.name}" --rating 3`));
3727
+ }
3728
+ console.log(dim("\nrating: 1=\u5FD8\u8BB0 2=\u5403\u529B 3=\u987A\u5229 4=\u8F7B\u677E"));
3729
+ });
3730
+ }
3731
+ async function mark(client, opts, args) {
3732
+ const name = args.join(" ").trim();
3733
+ if (!name) throw new Error('\u8BF7\u63D0\u4F9B\u5B9E\u4F53\u540D: exomind review mark "Redis" --rating 3');
3734
+ const rating = opts.rating ?? 3;
3735
+ if (rating < 1 || rating > 4) throw new Error("rating \u5FC5\u987B\u662F 1-4 (1=\u5FD8\u8BB0 2=\u5403\u529B 3=\u987A\u5229 4=\u8F7B\u677E)");
3736
+ const result = await client.request("POST", "/review/mark", { query: { name, rating } });
3737
+ output(result, () => {
3738
+ console.log(ok(`\u5DF2\u8BB0\u5F55\u590D\u4E60: ${name} (rating=${rating})`));
3739
+ console.log(dim(` \u4E0B\u6B21\u590D\u4E60: ${result.next_review ?? "?"} (${result.next_interval_days ?? "?"} \u5929\u540E)`));
3740
+ console.log(dim(` stability=${result.stability ?? "?"} difficulty=${result.difficulty ?? "?"}`));
3741
+ });
3742
+ }
3743
+
3744
+ // src/commands/synthesize.ts
3745
+ async function synthesize(client, opts, args) {
3746
+ const topic = args.join(" ").trim();
3747
+ if (!topic) throw new Error('\u8BF7\u63D0\u4F9B\u4E3B\u9898: exomind synthesize "Redis \u6301\u4E45\u5316"');
3748
+ const result = await client.post("/synthesize", { topic, depth: opts.depth ?? 2 }, { timeoutMs: 18e4 });
3749
+ output(result, () => {
3750
+ console.log(bold(result.topic || topic));
3751
+ if (result.content) console.log(`
3752
+ ${result.content}`);
3753
+ if (result.insights) console.log(cyan("\n\u6D1E\u5BDF: ") + result.insights);
3754
+ if (result.confidence != null) console.log(dim(`
3755
+ \u7F6E\u4FE1\u5EA6: ${result.confidence}`));
3756
+ if (result.sources?.length) console.log(dim(`\u6765\u6E90\u9875\u6570: ${result.sources.length}`));
3757
+ });
3758
+ }
3759
+
3760
+ // src/commands/topics.ts
3761
+ async function topics(client, opts) {
3762
+ const result = await client.get("/suggest-topics", { count: opts.count ?? 5 });
3763
+ const topics2 = result.topics || [];
3764
+ output(result, () => {
3765
+ console.log(cyan(`\u9009\u9898\u63A8\u8350 (${topics2.length}):`));
3766
+ topics2.forEach((t, i) => {
3767
+ console.log(`
3768
+ ${i + 1}. ${bold(String(t.topic ?? ""))}`);
3769
+ if (t.reason) console.log(dim(` \u7B56\u7565: ${t.reason}`));
3770
+ if (t.readiness != null) console.log(dim(` \u7D20\u6750\u5145\u5206\u5EA6: ${Math.round(Number(t.readiness) * 100)}%`));
3771
+ if (t.entity_count != null) console.log(dim(` \u5173\u8054\u5B9E\u4F53: ${t.entity_count} \u4E2A`));
3772
+ });
3773
+ });
3774
+ }
3775
+
3776
+ // src/commands/gaps.ts
3777
+ async function gaps(client, opts) {
3778
+ const result = await client.get("/knowledge-gaps", { days: opts.days ?? 30 });
3779
+ const gaps2 = result.gaps || [];
3780
+ output(result, () => {
3781
+ if (!gaps2.length) {
3782
+ console.log(green("\u6682\u65E0\u77E5\u8BC6\u7F3A\u53E3 \u{1F389}"));
3783
+ return;
3784
+ }
3785
+ console.log(cyan(`\u77E5\u8BC6\u7F3A\u53E3 ${result.total_gaps ?? gaps2.length} \u4E2A (\u8FD1 ${result.days} \u5929):`));
3786
+ for (const g of gaps2) {
3787
+ console.log(` ${bold(`${g.count}\xD7`)} ${g.query} ${dim(`(\u6700\u5C11 ${g.min_results ?? 0} \u7ED3\u679C)`)}`);
3788
+ }
3789
+ console.log(dim("\n\u63D0\u793A: \u7528 exomind ingest \u8865\u5145\u4EE5\u4E0A\u7F3A\u53E3\u3002"));
3790
+ });
3791
+ }
3792
+
3793
+ // src/commands/feedback.ts
3794
+ async function feedback(client, _opts, args) {
3795
+ if (args.length < 2) {
3796
+ throw new Error("\u7528\u6CD5: exomind feedback <\u9875\u9762\u8DEF\u5F84\u6216\u5B9E\u4F53\u540D> positive|negative");
3797
+ }
3798
+ const rating = args[args.length - 1];
3799
+ const page = args.slice(0, -1).join(" ").trim();
3800
+ if (rating !== "positive" && rating !== "negative") {
3801
+ throw new Error("\u7B2C\u4E8C\u53C2\u6570\u5FC5\u987B\u662F positive \u6216 negative");
3802
+ }
3803
+ const result = await client.post("/track/feedback", { path: page, feedback: rating });
3804
+ output(result, () => {
3805
+ console.log(ok(`\u5DF2\u8BB0\u5F55\u53CD\u9988: ${page} \u2192 ${rating}`));
3806
+ });
3807
+ }
3808
+
3809
+ // src/commands/daily.ts
3810
+ async function daily(client, opts) {
3811
+ const result = await client.get("/daily-summary", { days: opts.days ?? 1 });
3812
+ if (typeof result === "string") {
3813
+ console.log(isJsonMode() ? JSON.stringify(result) : result);
3814
+ return;
3815
+ }
3816
+ if (result && typeof result === "object" && typeof result.report === "string") {
3817
+ console.log(isJsonMode() ? JSON.stringify(result) : result.report);
3818
+ return;
3819
+ }
3820
+ console.log(isJsonMode() ? JSON.stringify(result, null, 2) : JSON.stringify(result, null, 2));
3821
+ }
3822
+
3823
+ // src/commands/login.ts
3824
+ var readline = __toESM(require("readline/promises"));
3825
+ var import_node_process = require("process");
3826
+ async function prompt(question) {
3827
+ const rl = readline.createInterface({ input: import_node_process.stdin, output: import_node_process.stdout });
3828
+ try {
3829
+ return (await rl.question(question)).trim();
3830
+ } finally {
3831
+ rl.close();
3832
+ }
3833
+ }
3834
+ async function login(_client, opts) {
3835
+ const baseUrl = opts.baseUrl || DEFAULT_BASE_URL;
3836
+ let token = opts.apiKey || "";
3837
+ if (!token) {
3838
+ console.log(dim("\u4ECE d.youhuale.cn/ui/account (\u767B\u5F55\u540E) \u590D\u5236 API Key \u6216\u767B\u5F55 token\u3002"));
3839
+ token = await prompt("\u51ED\u8BC1: ");
3840
+ }
3841
+ if (!token) throw new Error("\u672A\u63D0\u4F9B\u51ED\u8BC1");
3842
+ saveConfig({ base_url: baseUrl, api_key: token });
3843
+ const probe = new ApiClient({ base_url: baseUrl, api_key: token });
3844
+ try {
3845
+ await probe.get("/keywords");
3846
+ } catch (e) {
3847
+ if (e instanceof ApiError && (e.status === 401 || e.status === 403)) {
3848
+ throw new Error(`\u51ED\u8BC1\u6821\u9A8C\u5931\u8D25 (HTTP ${e.status}): ${e.detail}`);
3849
+ }
3850
+ console.log(
3851
+ yellow(
3852
+ `\u8B66\u544A: \u65E0\u6CD5\u8FDE\u63A5 ${baseUrl} \u6821\u9A8C\u51ED\u8BC1 (${e instanceof Error ? e.message : String(e)})\u3002\u914D\u7F6E\u5DF2\u4FDD\u5B58,\u7A0D\u540E\u53EF\u7528 exomind whoami \u9A8C\u8BC1\u3002`
3853
+ )
3854
+ );
3855
+ }
3856
+ const hint = token.length > 12 ? `${token.slice(0, 8)}\u2026${token.slice(-4)}` : token;
3857
+ console.log(ok("\u767B\u5F55\u6210\u529F"));
3858
+ console.log(dim(` \u670D\u52A1\u5668: ${baseUrl}`));
3859
+ console.log(dim(` \u51ED\u8BC1: ${hint} (${token.startsWith("gh_") ? "GitHub token" : "API Key"})`));
3860
+ }
3861
+
3862
+ // src/commands/whoami.ts
3863
+ async function whoami(client) {
3864
+ const cfg = loadConfig();
3865
+ if (!cfg.api_key) {
3866
+ console.log(yellow("\u672A\u767B\u5F55\u3002\u8FD0\u884C exomind login\u3002"));
3867
+ return;
3868
+ }
3869
+ let me = {};
3870
+ try {
3871
+ me = await client.get("/auth/me");
3872
+ } catch {
3873
+ me = {};
3874
+ }
3875
+ const hint = cfg.api_key.length > 12 ? `${cfg.api_key.slice(0, 8)}\u2026${cfg.api_key.slice(-4)}` : cfg.api_key;
3876
+ const kind = cfg.api_key.startsWith("gh_") ? "GitHub token" : "API Key";
3877
+ output(
3878
+ { base_url: cfg.base_url, credential: hint, kind, ...me },
3879
+ () => {
3880
+ console.log(ok("\u5DF2\u767B\u5F55"));
3881
+ console.log(dim(` \u670D\u52A1\u5668: ${cfg.base_url}`));
3882
+ console.log(dim(` \u51ED\u8BC1: ${hint} (${kind})`));
3883
+ if (me.authenticated) {
3884
+ console.log(dim(` \u7528\u6237: ${me.name || me.login || "-"} (tenant: ${me.tenant_id || "-"})`));
3885
+ }
3886
+ }
3887
+ );
3888
+ }
3889
+
3890
+ // src/commands/install.ts
3891
+ var fs4 = __toESM(require("fs"));
3892
+ var path3 = __toESM(require("path"));
3893
+ var os2 = __toESM(require("os"));
3894
+ var PKG_ROOT = path3.resolve(__dirname, "..");
3895
+ var SKILL_SRC = path3.join(PKG_ROOT, "skill", "SKILL.md");
3896
+ function readJson2(file) {
3897
+ try {
3898
+ return JSON.parse(fs4.readFileSync(file, "utf-8"));
3899
+ } catch {
3900
+ return null;
3901
+ }
3902
+ }
3903
+ function backup(file) {
3904
+ if (!fs4.existsSync(file)) return;
3905
+ const bak = `${file}.bak-${Date.now()}`;
3906
+ try {
3907
+ fs4.copyFileSync(file, bak);
3908
+ console.log(dim(` (\u5DF2\u5907\u4EFD\u539F\u914D\u7F6E \u2192 ${path3.basename(bak)})`));
3909
+ } catch {
3910
+ }
3911
+ }
3912
+ async function install(_client, opts) {
3913
+ const claudeDir = path3.join(os2.homedir(), ".claude");
3914
+ const skillDestDir = path3.join(claudeDir, "skills", "exomind");
3915
+ if (!fs4.existsSync(SKILL_SRC)) {
3916
+ throw new Error(`skill \u6E90\u4E0D\u5B58\u5728: ${SKILL_SRC}(npm \u5305\u53EF\u80FD\u635F\u574F,\u6216\u5F00\u53D1\u6A21\u5F0F\u4E0B\u672A\u6784\u5EFA)`);
3917
+ }
3918
+ fs4.mkdirSync(skillDestDir, { recursive: true });
3919
+ fs4.copyFileSync(SKILL_SRC, path3.join(skillDestDir, "SKILL.md"));
3920
+ console.log(ok("\u5DF2\u5B89\u88C5 Claude Code skill"));
3921
+ console.log(dim(` \u2192 ${skillDestDir}/SKILL.md`));
3922
+ if (opts.withHook) {
3923
+ const settingsFile = path3.join(claudeDir, "settings.json");
3924
+ fs4.mkdirSync(claudeDir, { recursive: true });
3925
+ backup(settingsFile);
3926
+ const settings = readJson2(settingsFile) ?? {};
3927
+ const hooks = settings.hooks ?? {};
3928
+ const list2 = Array.isArray(hooks.UserPromptSubmit) ? hooks.UserPromptSubmit : [];
3929
+ const kept = list2.filter(
3930
+ (m) => !(m.hooks || []).some((h) => String(h.command || "").includes("exomind"))
3931
+ );
3932
+ kept.push({
3933
+ hooks: [{ type: "command", command: "exomind hook", statusMessage: "ExoMind \u77E5\u8BC6\u5E93\u68C0\u7D22" }]
3934
+ });
3935
+ hooks.UserPromptSubmit = kept;
3936
+ settings.hooks = hooks;
3937
+ fs4.writeFileSync(settingsFile, JSON.stringify(settings, null, 2) + "\n");
3938
+ console.log(ok("\u5DF2\u914D\u7F6E UserPromptSubmit hook \u2192 exomind hook"));
3939
+ console.log(dim(" \u91CD\u542F Claude Code \u751F\u6548\u3002hook \u51FA\u9519\u4E0D\u4F1A\u963B\u585E\u4F60\u7684\u8F93\u5165(\u9519\u8BEF\u53EA\u8FDB stderr)\u3002"));
3940
+ }
3941
+ console.log(yellow("\n\u4E0B\u4E00\u6B65:"));
3942
+ console.log(dim(" 1. \u82E5\u672A\u914D\u7F6E\u51ED\u8BC1: exomind login"));
3943
+ console.log(dim(" 2. \u91CD\u542F Claude Code(\u82E5\u88C5\u4E86 hook)"));
3944
+ }
3945
+
3946
+ // src/cli.ts
3947
+ var VERSION = "0.1.0";
3948
+ function collect(value, previous) {
3949
+ return [...previous ?? [], value];
3950
+ }
3951
+ function toInt(v) {
3952
+ const n = parseInt(String(v), 10);
3953
+ if (Number.isNaN(n)) throw new Error(`\u671F\u671B\u6574\u6570,\u5F97\u5230: ${v}`);
3954
+ return n;
3955
+ }
3956
+ function rootOptions(cmd) {
3957
+ let c = cmd;
3958
+ while (c.parent) c = c.parent;
3959
+ return c.opts();
3960
+ }
3961
+ function handleError(e) {
3962
+ const msg = e instanceof ApiError ? e.message : e instanceof Error ? e.message : String(e);
3963
+ if (isJsonMode()) {
3964
+ console.log(JSON.stringify({ error: msg }));
3965
+ } else {
3966
+ console.error(red(`\u2717 ${msg}`));
3967
+ }
3968
+ process.exit(1);
3969
+ }
3970
+ function run(fn) {
3971
+ return async (...a) => {
3972
+ const command = a[a.length - 1];
3973
+ const root = rootOptions(command);
3974
+ setJsonMode(!!root.json);
3975
+ const cfg = resolveConfig({ baseUrl: root.baseUrl, apiKey: root.apiKey });
3976
+ const client = new ApiClient(cfg);
3977
+ try {
3978
+ await fn(client, command.opts(), command.args);
3979
+ } catch (e) {
3980
+ handleError(e);
3981
+ }
3982
+ };
3983
+ }
3984
+ var program2 = new Command();
3985
+ program2.name("exomind").description("ExoMind \u8DE8\u5E73\u53F0\u77E5\u8BC6\u5E93\u5BA2\u6237\u7AEF \u2014 \u901A\u8FC7 REST \u4EA4\u4E92(\u66FF\u4EE3 Windows MCP \u5BA2\u6237\u7AEF)\u3002").version(VERSION).option("--json", "\u8F93\u51FA\u539F\u59CB JSON(\u673A\u5668\u53EF\u8BFB)").option("--base-url <url>", "\u8986\u76D6\u670D\u52A1\u5668\u5730\u5740").option("--api-key <key>", "\u8986\u76D6 API Key / \u51ED\u8BC1");
3986
+ program2.command("login").description("\u914D\u7F6E\u670D\u52A1\u5668\u5730\u5740\u4E0E\u51ED\u8BC1,\u5199\u5165 ~/.exomind/config.json").option("--base-url <url>", "\u670D\u52A1\u5668\u5730\u5740").option("--api-key <key>", "API Key \u6216\u767B\u5F55 token(\u4E0D\u586B\u5219\u4EA4\u4E92\u8F93\u5165)").action(run(login));
3987
+ program2.command("whoami").description("\u663E\u793A\u5F53\u524D\u767B\u5F55\u6001\u4E0E\u670D\u52A1\u5668").action(run(whoami));
3988
+ program2.command("ingest [content...]").description("\u5BFC\u5165\u77E5\u8BC6: \u53C2\u6570\u6587\u672C / --file / stdin (echo ... | exomind ingest)").option("-t, --title <title>", "\u6807\u9898").option("--tag <tag>", "\u6807\u7B7E(\u53EF\u91CD\u590D)", collect, []).option("--file <path>", "\u4ECE\u6587\u4EF6\u8BFB\u53D6\u5185\u5BB9").action(run(ingest));
3989
+ program2.command("query [question...]").description("LLM \u95EE\u7B54").option("--tag <tag>", "\u6807\u7B7E\u8FC7\u6EE4(\u53EF\u91CD\u590D)", collect, []).option("--model <name>", "\u6A21\u578B").action(run(query));
3990
+ program2.command("search [keyword...]").description("\u5168\u6587/\u6DF7\u5408/\u7CBE\u6392\u641C\u7D22").option("-l, --limit <n>", "\u8FD4\u56DE\u6570\u91CF", "10").option("--rerank", "LLM \u7CBE\u6392(\u66F4\u51C6\u4F46\u66F4\u6162)").option("--hybrid", "\u6DF7\u5408\u641C\u7D22(BM25+\u8BED\u4E49)").action(run(search));
3991
+ program2.command("entity [name...]").description("\u5B9E\u4F53\u8BE6\u60C5 + \u5173\u7CFB").action(run(entity));
3992
+ program2.command("relations [name...]").description("\u5173\u8054\u5B9E\u4F53(\u53EF\u8FBE\u6027)").option("-d, --depth <n>", "\u641C\u7D22\u6DF1\u5EA6 1-3", "1").action(run(relations));
3993
+ program2.command("stats").description("\u77E5\u8BC6\u5E93\u7EDF\u8BA1").action(run(stats));
3994
+ var reviewCmd = program2.command("review").description("FSRS-5 \u590D\u4E60\u961F\u5217").option("-l, --limit <n>", "\u6570\u91CF", "12");
3995
+ reviewCmd.action(run((client, opts) => list(client, { limit: toInt(opts.limit) })));
3996
+ reviewCmd.command("mark [name...]").description("\u6807\u8BB0\u590D\u4E60 (rating: 1=\u5FD8\u8BB0 2=\u5403\u529B 3=\u987A\u5229 4=\u8F7B\u677E)").option("-r, --rating <n>", "1-4", "3").action(run((client, opts, args) => mark(client, { rating: toInt(opts.rating) }, args)));
3997
+ program2.command("synthesize [topic...]").description("\u4E3B\u9898\u7EFC\u5408\u62A5\u544A").option("-d, --depth <n>", "\u6DF1\u5EA6 1-5", "2").action(run(synthesize));
3998
+ program2.command("topics").description("\u9009\u9898\u63A8\u8350").option("-c, --count <n>", "\u6570\u91CF", "5").action(run((client, opts) => topics(client, { count: toInt(opts.count) })));
3999
+ program2.command("gaps").description("\u77E5\u8BC6\u7F3A\u53E3(\u88AB\u591A\u6B21\u641C\u7D22\u4F46\u65E0\u7ED3\u679C)").option("-d, --days <n>", "\u56DE\u6EAF\u5929\u6570", "30").action(run((client, opts) => gaps(client, { days: toInt(opts.days) })));
4000
+ program2.command("feedback [page...]").description("\u5BF9\u9875\u9762/\u5B9E\u4F53\u6253\u53CD\u9988 (positive|negative)").action(run(feedback));
4001
+ program2.command("daily").description("\u6BCF\u65E5\u6D3B\u52A8\u6458\u8981").option("-d, --days <n>", "\u56DE\u6EAF\u5929\u6570", "1").action(run((client, opts) => daily(client, { days: toInt(opts.days) })));
4002
+ program2.command("hook").description("UserPromptSubmit \u94A9\u5B50(\u7531 Claude Code \u8C03\u7528,\u975E\u624B\u52A8)").action(async (...a) => {
4003
+ const command = a[a.length - 1];
4004
+ const root = rootOptions(command);
4005
+ setJsonMode(false);
4006
+ const cfg = resolveConfig({ baseUrl: root.baseUrl, apiKey: root.apiKey });
4007
+ const client = new ApiClient(cfg);
4008
+ try {
4009
+ await runHook(client);
4010
+ } catch (e) {
4011
+ process.stderr.write(`[exomind hook] ${e instanceof Error ? e.message : String(e)}
4012
+ `);
4013
+ }
4014
+ process.exit(0);
4015
+ });
4016
+ program2.command("install").description("\u5B89\u88C5 Claude Code skill(\u53EF\u9009 --with-hook \u5199\u5165 UserPromptSubmit)").option("--with-hook", "\u540C\u65F6\u5199\u5165 ~/.claude/settings.json \u7684 hook").action(run(install));
4017
+ async function main() {
4018
+ await program2.parseAsync(process.argv);
4019
+ }
4020
+ main().catch((e) => handleError(e));
4021
+ //# sourceMappingURL=cli.js.map