smashspace 0.1.0

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