@nseng-ai/ns 0.1.0 → 0.1.1

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