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