@mutmutco/cli 2.19.0 → 2.20.0

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