@nomai/nomai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,3367 @@
1
+ #!/usr/bin/env node
2
+ import { r as __toESM } from "./rolldown-runtime-C7HZzL1F.mjs";
3
+ import { a as getHarness, i as detectHarnesses, o as listHarnesses, r as resolvePayloadSource } from "./payload-DdBYzrl3.mjs";
4
+ import fs, { readFileSync, realpathSync } from "node:fs";
5
+ import { pathToFileURL } from "node:url";
6
+ import { EventEmitter } from "node:events";
7
+ import childProcess from "node:child_process";
8
+ import path from "node:path";
9
+ import process$1 from "node:process";
10
+ import { stripVTControlCharacters } from "node:util";
11
+ import os from "node:os";
12
+ //#region node_modules/commander/lib/error.js
13
+ /**
14
+ * CommanderError class
15
+ */
16
+ var CommanderError = class extends Error {
17
+ /**
18
+ * Constructs the CommanderError class
19
+ * @param {number} exitCode suggested exit code which could be used with process.exit
20
+ * @param {string} code an id string representing the error
21
+ * @param {string} message human-readable description of the error
22
+ */
23
+ constructor(exitCode, code, message) {
24
+ super(message);
25
+ Error.captureStackTrace(this, this.constructor);
26
+ this.name = this.constructor.name;
27
+ this.code = code;
28
+ this.exitCode = exitCode;
29
+ this.nestedError = void 0;
30
+ }
31
+ };
32
+ /**
33
+ * InvalidArgumentError class
34
+ */
35
+ var InvalidArgumentError = class extends CommanderError {
36
+ /**
37
+ * Constructs the InvalidArgumentError class
38
+ * @param {string} [message] explanation of why argument is invalid
39
+ */
40
+ constructor(message) {
41
+ super(1, "commander.invalidArgument", message);
42
+ Error.captureStackTrace(this, this.constructor);
43
+ this.name = this.constructor.name;
44
+ }
45
+ };
46
+ //#endregion
47
+ //#region node_modules/commander/lib/argument.js
48
+ var Argument = class {
49
+ /**
50
+ * Initialize a new command argument with the given name and description.
51
+ * The default is that the argument is required, and you can explicitly
52
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
53
+ *
54
+ * @param {string} name
55
+ * @param {string} [description]
56
+ */
57
+ constructor(name, description) {
58
+ this.description = description || "";
59
+ this.variadic = false;
60
+ this.parseArg = void 0;
61
+ this.defaultValue = void 0;
62
+ this.defaultValueDescription = void 0;
63
+ this.argChoices = void 0;
64
+ switch (name[0]) {
65
+ case "<":
66
+ this.required = true;
67
+ this._name = name.slice(1, -1);
68
+ break;
69
+ case "[":
70
+ this.required = false;
71
+ this._name = name.slice(1, -1);
72
+ break;
73
+ default:
74
+ this.required = true;
75
+ this._name = name;
76
+ break;
77
+ }
78
+ if (this._name.endsWith("...")) {
79
+ this.variadic = true;
80
+ this._name = this._name.slice(0, -3);
81
+ }
82
+ }
83
+ /**
84
+ * Return argument name.
85
+ *
86
+ * @return {string}
87
+ */
88
+ name() {
89
+ return this._name;
90
+ }
91
+ /**
92
+ * @package
93
+ */
94
+ _collectValue(value, previous) {
95
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
96
+ previous.push(value);
97
+ return previous;
98
+ }
99
+ /**
100
+ * Set the default value, and optionally supply the description to be displayed in the help.
101
+ *
102
+ * @param {*} value
103
+ * @param {string} [description]
104
+ * @return {Argument}
105
+ */
106
+ default(value, description) {
107
+ this.defaultValue = value;
108
+ this.defaultValueDescription = description;
109
+ return this;
110
+ }
111
+ /**
112
+ * Set the custom handler for processing CLI command arguments into argument values.
113
+ *
114
+ * @param {Function} [fn]
115
+ * @return {Argument}
116
+ */
117
+ argParser(fn) {
118
+ this.parseArg = fn;
119
+ return this;
120
+ }
121
+ /**
122
+ * Only allow argument value to be one of choices.
123
+ *
124
+ * @param {string[]} values
125
+ * @return {Argument}
126
+ */
127
+ choices(values) {
128
+ this.argChoices = values.slice();
129
+ this.parseArg = (arg, previous) => {
130
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
131
+ if (this.variadic) return this._collectValue(arg, previous);
132
+ return arg;
133
+ };
134
+ return this;
135
+ }
136
+ /**
137
+ * Make argument required.
138
+ *
139
+ * @returns {Argument}
140
+ */
141
+ argRequired() {
142
+ this.required = true;
143
+ return this;
144
+ }
145
+ /**
146
+ * Make argument optional.
147
+ *
148
+ * @returns {Argument}
149
+ */
150
+ argOptional() {
151
+ this.required = false;
152
+ return this;
153
+ }
154
+ };
155
+ /**
156
+ * Takes an argument and returns its human readable equivalent for help usage.
157
+ *
158
+ * @param {Argument} arg
159
+ * @return {string}
160
+ * @private
161
+ */
162
+ function humanReadableArgName(arg) {
163
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
164
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
165
+ }
166
+ //#endregion
167
+ //#region node_modules/commander/lib/help.js
168
+ /**
169
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
170
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
171
+ * @typedef { import("./argument.js").Argument } Argument
172
+ * @typedef { import("./command.js").Command } Command
173
+ * @typedef { import("./option.js").Option } Option
174
+ */
175
+ var Help = class {
176
+ constructor() {
177
+ this.helpWidth = void 0;
178
+ this.minWidthToWrap = 40;
179
+ this.sortSubcommands = false;
180
+ this.sortOptions = false;
181
+ this.showGlobalOptions = false;
182
+ }
183
+ /**
184
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
185
+ * and just before calling `formatHelp()`.
186
+ *
187
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
188
+ *
189
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
190
+ */
191
+ prepareContext(contextOptions) {
192
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
193
+ }
194
+ /**
195
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
196
+ *
197
+ * @param {Command} cmd
198
+ * @returns {Command[]}
199
+ */
200
+ visibleCommands(cmd) {
201
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
202
+ const helpCommand = cmd._getHelpCommand();
203
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
204
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
205
+ return a.name().localeCompare(b.name());
206
+ });
207
+ return visibleCommands;
208
+ }
209
+ /**
210
+ * Compare options for sort.
211
+ *
212
+ * @param {Option} a
213
+ * @param {Option} b
214
+ * @returns {number}
215
+ */
216
+ compareOptions(a, b) {
217
+ const getSortKey = (option) => {
218
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
219
+ };
220
+ return getSortKey(a).localeCompare(getSortKey(b));
221
+ }
222
+ /**
223
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
224
+ *
225
+ * @param {Command} cmd
226
+ * @returns {Option[]}
227
+ */
228
+ visibleOptions(cmd) {
229
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
230
+ const helpOption = cmd._getHelpOption();
231
+ if (helpOption && !helpOption.hidden) {
232
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
233
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
234
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
235
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
236
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
237
+ }
238
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
239
+ return visibleOptions;
240
+ }
241
+ /**
242
+ * Get an array of the visible global options. (Not including help.)
243
+ *
244
+ * @param {Command} cmd
245
+ * @returns {Option[]}
246
+ */
247
+ visibleGlobalOptions(cmd) {
248
+ if (!this.showGlobalOptions) return [];
249
+ const globalOptions = [];
250
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
251
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
252
+ globalOptions.push(...visibleOptions);
253
+ }
254
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
255
+ return globalOptions;
256
+ }
257
+ /**
258
+ * Get an array of the arguments if any have a description.
259
+ *
260
+ * @param {Command} cmd
261
+ * @returns {Argument[]}
262
+ */
263
+ visibleArguments(cmd) {
264
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
265
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
266
+ });
267
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
268
+ return [];
269
+ }
270
+ /**
271
+ * Get the command term to show in the list of subcommands.
272
+ *
273
+ * @param {Command} cmd
274
+ * @returns {string}
275
+ */
276
+ subcommandTerm(cmd) {
277
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
278
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
279
+ }
280
+ /**
281
+ * Get the option term to show in the list of options.
282
+ *
283
+ * @param {Option} option
284
+ * @returns {string}
285
+ */
286
+ optionTerm(option) {
287
+ return option.flags;
288
+ }
289
+ /**
290
+ * Get the argument term to show in the list of arguments.
291
+ *
292
+ * @param {Argument} argument
293
+ * @returns {string}
294
+ */
295
+ argumentTerm(argument) {
296
+ return argument.name();
297
+ }
298
+ /**
299
+ * Get the longest command term length.
300
+ *
301
+ * @param {Command} cmd
302
+ * @param {Help} helper
303
+ * @returns {number}
304
+ */
305
+ longestSubcommandTermLength(cmd, helper) {
306
+ return helper.visibleCommands(cmd).reduce((max, command) => {
307
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
308
+ }, 0);
309
+ }
310
+ /**
311
+ * Get the longest option term length.
312
+ *
313
+ * @param {Command} cmd
314
+ * @param {Help} helper
315
+ * @returns {number}
316
+ */
317
+ longestOptionTermLength(cmd, helper) {
318
+ return helper.visibleOptions(cmd).reduce((max, option) => {
319
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
320
+ }, 0);
321
+ }
322
+ /**
323
+ * Get the longest global option term length.
324
+ *
325
+ * @param {Command} cmd
326
+ * @param {Help} helper
327
+ * @returns {number}
328
+ */
329
+ longestGlobalOptionTermLength(cmd, helper) {
330
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
331
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
332
+ }, 0);
333
+ }
334
+ /**
335
+ * Get the longest argument term length.
336
+ *
337
+ * @param {Command} cmd
338
+ * @param {Help} helper
339
+ * @returns {number}
340
+ */
341
+ longestArgumentTermLength(cmd, helper) {
342
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
343
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
344
+ }, 0);
345
+ }
346
+ /**
347
+ * Get the command usage to be displayed at the top of the built-in help.
348
+ *
349
+ * @param {Command} cmd
350
+ * @returns {string}
351
+ */
352
+ commandUsage(cmd) {
353
+ let cmdName = cmd._name;
354
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
355
+ let ancestorCmdNames = "";
356
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
357
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
358
+ }
359
+ /**
360
+ * Get the description for the command.
361
+ *
362
+ * @param {Command} cmd
363
+ * @returns {string}
364
+ */
365
+ commandDescription(cmd) {
366
+ return cmd.description();
367
+ }
368
+ /**
369
+ * Get the subcommand summary to show in the list of subcommands.
370
+ * (Fallback to description for backwards compatibility.)
371
+ *
372
+ * @param {Command} cmd
373
+ * @returns {string}
374
+ */
375
+ subcommandDescription(cmd) {
376
+ return cmd.summary() || cmd.description();
377
+ }
378
+ /**
379
+ * Get the option description to show in the list of options.
380
+ *
381
+ * @param {Option} option
382
+ * @return {string}
383
+ */
384
+ optionDescription(option) {
385
+ const extraInfo = [];
386
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
387
+ if (option.defaultValue !== void 0) {
388
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
389
+ }
390
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
391
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
392
+ if (extraInfo.length > 0) {
393
+ const extraDescription = `(${extraInfo.join(", ")})`;
394
+ if (option.description) return `${option.description} ${extraDescription}`;
395
+ return extraDescription;
396
+ }
397
+ return option.description;
398
+ }
399
+ /**
400
+ * Get the argument description to show in the list of arguments.
401
+ *
402
+ * @param {Argument} argument
403
+ * @return {string}
404
+ */
405
+ argumentDescription(argument) {
406
+ const extraInfo = [];
407
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
408
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
409
+ if (extraInfo.length > 0) {
410
+ const extraDescription = `(${extraInfo.join(", ")})`;
411
+ if (argument.description) return `${argument.description} ${extraDescription}`;
412
+ return extraDescription;
413
+ }
414
+ return argument.description;
415
+ }
416
+ /**
417
+ * Format a list of items, given a heading and an array of formatted items.
418
+ *
419
+ * @param {string} heading
420
+ * @param {string[]} items
421
+ * @param {Help} helper
422
+ * @returns string[]
423
+ */
424
+ formatItemList(heading, items, helper) {
425
+ if (items.length === 0) return [];
426
+ return [
427
+ helper.styleTitle(heading),
428
+ ...items,
429
+ ""
430
+ ];
431
+ }
432
+ /**
433
+ * Group items by their help group heading.
434
+ *
435
+ * @param {Command[] | Option[]} unsortedItems
436
+ * @param {Command[] | Option[]} visibleItems
437
+ * @param {Function} getGroup
438
+ * @returns {Map<string, Command[] | Option[]>}
439
+ */
440
+ groupItems(unsortedItems, visibleItems, getGroup) {
441
+ const result = /* @__PURE__ */ new Map();
442
+ unsortedItems.forEach((item) => {
443
+ const group = getGroup(item);
444
+ if (!result.has(group)) result.set(group, []);
445
+ });
446
+ visibleItems.forEach((item) => {
447
+ const group = getGroup(item);
448
+ if (!result.has(group)) result.set(group, []);
449
+ result.get(group).push(item);
450
+ });
451
+ return result;
452
+ }
453
+ /**
454
+ * Generate the built-in help text.
455
+ *
456
+ * @param {Command} cmd
457
+ * @param {Help} helper
458
+ * @returns {string}
459
+ */
460
+ formatHelp(cmd, helper) {
461
+ const termWidth = helper.padWidth(cmd, helper);
462
+ const helpWidth = helper.helpWidth ?? 80;
463
+ function callFormatItem(term, description) {
464
+ return helper.formatItem(term, termWidth, description, helper);
465
+ }
466
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
467
+ const commandDescription = helper.commandDescription(cmd);
468
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
469
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
470
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
471
+ });
472
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
473
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
474
+ const optionList = options.map((option) => {
475
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
476
+ });
477
+ output = output.concat(this.formatItemList(group, optionList, helper));
478
+ });
479
+ if (helper.showGlobalOptions) {
480
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
481
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
482
+ });
483
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
484
+ }
485
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
486
+ const commandList = commands.map((sub) => {
487
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
488
+ });
489
+ output = output.concat(this.formatItemList(group, commandList, helper));
490
+ });
491
+ return output.join("\n");
492
+ }
493
+ /**
494
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
495
+ *
496
+ * @param {string} str
497
+ * @returns {number}
498
+ */
499
+ displayWidth(str) {
500
+ return stripVTControlCharacters(str).length;
501
+ }
502
+ /**
503
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
504
+ *
505
+ * @param {string} str
506
+ * @returns {string}
507
+ */
508
+ styleTitle(str) {
509
+ return str;
510
+ }
511
+ styleUsage(str) {
512
+ return str.split(" ").map((word) => {
513
+ if (word === "[options]") return this.styleOptionText(word);
514
+ if (word === "[command]") return this.styleSubcommandText(word);
515
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
516
+ return this.styleCommandText(word);
517
+ }).join(" ");
518
+ }
519
+ styleCommandDescription(str) {
520
+ return this.styleDescriptionText(str);
521
+ }
522
+ styleOptionDescription(str) {
523
+ return this.styleDescriptionText(str);
524
+ }
525
+ styleSubcommandDescription(str) {
526
+ return this.styleDescriptionText(str);
527
+ }
528
+ styleArgumentDescription(str) {
529
+ return this.styleDescriptionText(str);
530
+ }
531
+ styleDescriptionText(str) {
532
+ return str;
533
+ }
534
+ styleOptionTerm(str) {
535
+ return this.styleOptionText(str);
536
+ }
537
+ styleSubcommandTerm(str) {
538
+ return str.split(" ").map((word) => {
539
+ if (word === "[options]") return this.styleOptionText(word);
540
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
541
+ return this.styleSubcommandText(word);
542
+ }).join(" ");
543
+ }
544
+ styleArgumentTerm(str) {
545
+ return this.styleArgumentText(str);
546
+ }
547
+ styleOptionText(str) {
548
+ return str;
549
+ }
550
+ styleArgumentText(str) {
551
+ return str;
552
+ }
553
+ styleSubcommandText(str) {
554
+ return str;
555
+ }
556
+ styleCommandText(str) {
557
+ return str;
558
+ }
559
+ /**
560
+ * Calculate the pad width from the maximum term length.
561
+ *
562
+ * @param {Command} cmd
563
+ * @param {Help} helper
564
+ * @returns {number}
565
+ */
566
+ padWidth(cmd, helper) {
567
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
568
+ }
569
+ /**
570
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
571
+ *
572
+ * @param {string} str
573
+ * @returns {boolean}
574
+ */
575
+ preformatted(str) {
576
+ return /\n[^\S\r\n]/.test(str);
577
+ }
578
+ /**
579
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
580
+ *
581
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
582
+ * TTT DDD DDDD
583
+ * DD DDD
584
+ *
585
+ * @param {string} term
586
+ * @param {number} termWidth
587
+ * @param {string} description
588
+ * @param {Help} helper
589
+ * @returns {string}
590
+ */
591
+ formatItem(term, termWidth, description, helper) {
592
+ const itemIndent = 2;
593
+ const itemIndentStr = " ".repeat(itemIndent);
594
+ if (!description) return itemIndentStr + term;
595
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
596
+ const spacerWidth = 2;
597
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
598
+ let formattedDescription;
599
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
600
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
601
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
602
+ }
603
+ /**
604
+ * Wrap a string at whitespace, preserving existing line breaks.
605
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
606
+ *
607
+ * @param {string} str
608
+ * @param {number} width
609
+ * @returns {string}
610
+ */
611
+ boxWrap(str, width) {
612
+ if (width < this.minWidthToWrap) return str;
613
+ const rawLines = str.split(/\r\n|\n/);
614
+ const chunkPattern = /[\s]*[^\s]+/g;
615
+ const wrappedLines = [];
616
+ rawLines.forEach((line) => {
617
+ const chunks = line.match(chunkPattern);
618
+ if (chunks === null) {
619
+ wrappedLines.push("");
620
+ return;
621
+ }
622
+ let sumChunks = [chunks.shift()];
623
+ let sumWidth = this.displayWidth(sumChunks[0]);
624
+ chunks.forEach((chunk) => {
625
+ const visibleWidth = this.displayWidth(chunk);
626
+ if (sumWidth + visibleWidth <= width) {
627
+ sumChunks.push(chunk);
628
+ sumWidth += visibleWidth;
629
+ return;
630
+ }
631
+ wrappedLines.push(sumChunks.join(""));
632
+ const nextChunk = chunk.trimStart();
633
+ sumChunks = [nextChunk];
634
+ sumWidth = this.displayWidth(nextChunk);
635
+ });
636
+ wrappedLines.push(sumChunks.join(""));
637
+ });
638
+ return wrappedLines.join("\n");
639
+ }
640
+ };
641
+ //#endregion
642
+ //#region node_modules/commander/lib/option.js
643
+ var Option = class {
644
+ /**
645
+ * Initialize a new `Option` with the given `flags` and `description`.
646
+ *
647
+ * @param {string} flags
648
+ * @param {string} [description]
649
+ */
650
+ constructor(flags, description) {
651
+ this.flags = flags;
652
+ this.description = description || "";
653
+ this.required = flags.includes("<");
654
+ this.optional = flags.includes("[");
655
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
656
+ this.mandatory = false;
657
+ const optionFlags = splitOptionFlags(flags);
658
+ this.short = optionFlags.shortFlag;
659
+ this.long = optionFlags.longFlag;
660
+ this.negate = false;
661
+ if (this.long) this.negate = this.long.startsWith("--no-");
662
+ this.defaultValue = void 0;
663
+ this.defaultValueDescription = void 0;
664
+ this.presetArg = void 0;
665
+ this.envVar = void 0;
666
+ this.parseArg = void 0;
667
+ this.hidden = false;
668
+ this.argChoices = void 0;
669
+ this.conflictsWith = [];
670
+ this.implied = void 0;
671
+ this.helpGroupHeading = void 0;
672
+ }
673
+ /**
674
+ * Set the default value, and optionally supply the description to be displayed in the help.
675
+ *
676
+ * @param {*} value
677
+ * @param {string} [description]
678
+ * @return {Option}
679
+ */
680
+ default(value, description) {
681
+ this.defaultValue = value;
682
+ this.defaultValueDescription = description;
683
+ return this;
684
+ }
685
+ /**
686
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
687
+ * The custom processing (parseArg) is called.
688
+ *
689
+ * @example
690
+ * new Option('--color').default('GREYSCALE').preset('RGB');
691
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
692
+ *
693
+ * @param {*} arg
694
+ * @return {Option}
695
+ */
696
+ preset(arg) {
697
+ this.presetArg = arg;
698
+ return this;
699
+ }
700
+ /**
701
+ * Add option name(s) that conflict with this option.
702
+ * An error will be displayed if conflicting options are found during parsing.
703
+ *
704
+ * @example
705
+ * new Option('--rgb').conflicts('cmyk');
706
+ * new Option('--js').conflicts(['ts', 'jsx']);
707
+ *
708
+ * @param {(string | string[])} names
709
+ * @return {Option}
710
+ */
711
+ conflicts(names) {
712
+ this.conflictsWith = this.conflictsWith.concat(names);
713
+ return this;
714
+ }
715
+ /**
716
+ * Specify implied option values for when this option is set and the implied options are not.
717
+ *
718
+ * The custom processing (parseArg) is not called on the implied values.
719
+ *
720
+ * @example
721
+ * program
722
+ * .addOption(new Option('--log', 'write logging information to file'))
723
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
724
+ *
725
+ * @param {object} impliedOptionValues
726
+ * @return {Option}
727
+ */
728
+ implies(impliedOptionValues) {
729
+ let newImplied = impliedOptionValues;
730
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
731
+ this.implied = Object.assign(this.implied || {}, newImplied);
732
+ return this;
733
+ }
734
+ /**
735
+ * Set environment variable to check for option value.
736
+ *
737
+ * An environment variable is only used if when processed the current option value is
738
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
739
+ *
740
+ * @param {string} name
741
+ * @return {Option}
742
+ */
743
+ env(name) {
744
+ this.envVar = name;
745
+ return this;
746
+ }
747
+ /**
748
+ * Set the custom handler for processing CLI option arguments into option values.
749
+ *
750
+ * @param {Function} [fn]
751
+ * @return {Option}
752
+ */
753
+ argParser(fn) {
754
+ this.parseArg = fn;
755
+ return this;
756
+ }
757
+ /**
758
+ * Whether the option is mandatory and must have a value after parsing.
759
+ *
760
+ * @param {boolean} [mandatory=true]
761
+ * @return {Option}
762
+ */
763
+ makeOptionMandatory(mandatory = true) {
764
+ this.mandatory = !!mandatory;
765
+ return this;
766
+ }
767
+ /**
768
+ * Hide option in help.
769
+ *
770
+ * @param {boolean} [hide=true]
771
+ * @return {Option}
772
+ */
773
+ hideHelp(hide = true) {
774
+ this.hidden = !!hide;
775
+ return this;
776
+ }
777
+ /**
778
+ * @package
779
+ */
780
+ _collectValue(value, previous) {
781
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
782
+ previous.push(value);
783
+ return previous;
784
+ }
785
+ /**
786
+ * Only allow option value to be one of choices.
787
+ *
788
+ * @param {string[]} values
789
+ * @return {Option}
790
+ */
791
+ choices(values) {
792
+ this.argChoices = values.slice();
793
+ this.parseArg = (arg, previous) => {
794
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
795
+ if (this.variadic) return this._collectValue(arg, previous);
796
+ return arg;
797
+ };
798
+ return this;
799
+ }
800
+ /**
801
+ * Return option name.
802
+ *
803
+ * @return {string}
804
+ */
805
+ name() {
806
+ if (this.long) return this.long.replace(/^--/, "");
807
+ return this.short.replace(/^-/, "");
808
+ }
809
+ /**
810
+ * Return option name, in a camelcase format that can be used
811
+ * as an object attribute key.
812
+ *
813
+ * @return {string}
814
+ */
815
+ attributeName() {
816
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
817
+ return camelcase(this.name());
818
+ }
819
+ /**
820
+ * Set the help group heading.
821
+ *
822
+ * @param {string} heading
823
+ * @return {Option}
824
+ */
825
+ helpGroup(heading) {
826
+ this.helpGroupHeading = heading;
827
+ return this;
828
+ }
829
+ /**
830
+ * Check if `arg` matches the short or long flag.
831
+ *
832
+ * @param {string} arg
833
+ * @return {boolean}
834
+ * @package
835
+ */
836
+ is(arg) {
837
+ return this.short === arg || this.long === arg;
838
+ }
839
+ /**
840
+ * Return whether a boolean option.
841
+ *
842
+ * Options are one of boolean, negated, required argument, or optional argument.
843
+ *
844
+ * @return {boolean}
845
+ * @package
846
+ */
847
+ isBoolean() {
848
+ return !this.required && !this.optional && !this.negate;
849
+ }
850
+ };
851
+ /**
852
+ * This class is to make it easier to work with dual options, without changing the existing
853
+ * implementation. We support separate dual options for separate positive and negative options,
854
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
855
+ * use cases, but is tricky for others where we want separate behaviours despite
856
+ * the single shared option value.
857
+ */
858
+ var DualOptions = class {
859
+ /**
860
+ * @param {Option[]} options
861
+ */
862
+ constructor(options) {
863
+ this.positiveOptions = /* @__PURE__ */ new Map();
864
+ this.negativeOptions = /* @__PURE__ */ new Map();
865
+ this.dualOptions = /* @__PURE__ */ new Set();
866
+ options.forEach((option) => {
867
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
868
+ else this.positiveOptions.set(option.attributeName(), option);
869
+ });
870
+ this.negativeOptions.forEach((value, key) => {
871
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
872
+ });
873
+ }
874
+ /**
875
+ * Did the value come from the option, and not from possible matching dual option?
876
+ *
877
+ * @param {*} value
878
+ * @param {Option} option
879
+ * @returns {boolean}
880
+ */
881
+ valueFromOption(value, option) {
882
+ const optionKey = option.attributeName();
883
+ if (!this.dualOptions.has(optionKey)) return true;
884
+ const preset = this.negativeOptions.get(optionKey).presetArg;
885
+ const negativeValue = preset !== void 0 ? preset : false;
886
+ return option.negate === (negativeValue === value);
887
+ }
888
+ };
889
+ /**
890
+ * Convert string from kebab-case to camelCase.
891
+ *
892
+ * @param {string} str
893
+ * @return {string}
894
+ * @private
895
+ */
896
+ function camelcase(str) {
897
+ return str.split("-").reduce((str, word) => {
898
+ return str + word[0].toUpperCase() + word.slice(1);
899
+ });
900
+ }
901
+ /**
902
+ * Split the short and long flag out of something like '-m,--mixed <value>'
903
+ *
904
+ * @private
905
+ */
906
+ function splitOptionFlags(flags) {
907
+ let shortFlag;
908
+ let longFlag;
909
+ const shortFlagExp = /^-[^-]$/;
910
+ const longFlagExp = /^--[^-]/;
911
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
912
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
913
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
914
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
915
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
916
+ shortFlag = longFlag;
917
+ longFlag = flagParts.shift();
918
+ }
919
+ if (flagParts[0].startsWith("-")) {
920
+ const unsupportedFlag = flagParts[0];
921
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
922
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
923
+ - a short flag is a single dash and a single character
924
+ - either use a single dash and a single character (for a short flag)
925
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
926
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
927
+ - too many short flags`);
928
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
929
+ - too many long flags`);
930
+ throw new Error(`${baseError}
931
+ - unrecognised flag format`);
932
+ }
933
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
934
+ return {
935
+ shortFlag,
936
+ longFlag
937
+ };
938
+ }
939
+ //#endregion
940
+ //#region node_modules/commander/lib/suggestSimilar.js
941
+ const maxDistance = 3;
942
+ function editDistance(a, b) {
943
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
944
+ const d = [];
945
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
946
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
947
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
948
+ let cost;
949
+ if (a[i - 1] === b[j - 1]) cost = 0;
950
+ else cost = 1;
951
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
952
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
953
+ }
954
+ return d[a.length][b.length];
955
+ }
956
+ /**
957
+ * Find close matches, restricted to same number of edits.
958
+ *
959
+ * @param {string} word
960
+ * @param {string[]} candidates
961
+ * @returns {string}
962
+ */
963
+ function suggestSimilar(word, candidates) {
964
+ if (!candidates || candidates.length === 0) return "";
965
+ candidates = Array.from(new Set(candidates));
966
+ const searchingOptions = word.startsWith("--");
967
+ if (searchingOptions) {
968
+ word = word.slice(2);
969
+ candidates = candidates.map((candidate) => candidate.slice(2));
970
+ }
971
+ let similar = [];
972
+ let bestDistance = maxDistance;
973
+ const minSimilarity = .4;
974
+ candidates.forEach((candidate) => {
975
+ if (candidate.length <= 1) return;
976
+ const distance = editDistance(word, candidate);
977
+ const length = Math.max(word.length, candidate.length);
978
+ if ((length - distance) / length > minSimilarity) {
979
+ if (distance < bestDistance) {
980
+ bestDistance = distance;
981
+ similar = [candidate];
982
+ } else if (distance === bestDistance) similar.push(candidate);
983
+ }
984
+ });
985
+ similar.sort((a, b) => a.localeCompare(b));
986
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
987
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
988
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
989
+ return "";
990
+ }
991
+ //#endregion
992
+ //#region node_modules/commander/lib/command.js
993
+ var Command = class Command extends EventEmitter {
994
+ /**
995
+ * Initialize a new `Command`.
996
+ *
997
+ * @param {string} [name]
998
+ */
999
+ constructor(name) {
1000
+ super();
1001
+ /** @type {Command[]} */
1002
+ this.commands = [];
1003
+ /** @type {Option[]} */
1004
+ this.options = [];
1005
+ this.parent = null;
1006
+ this._allowUnknownOption = false;
1007
+ this._allowExcessArguments = false;
1008
+ /** @type {Argument[]} */
1009
+ this.registeredArguments = [];
1010
+ this._args = this.registeredArguments;
1011
+ /** @type {string[]} */
1012
+ this.args = [];
1013
+ this.rawArgs = [];
1014
+ this.processedArgs = [];
1015
+ this._scriptPath = null;
1016
+ this._name = name || "";
1017
+ this._optionValues = {};
1018
+ this._optionValueSources = {};
1019
+ this._storeOptionsAsProperties = false;
1020
+ this._actionHandler = null;
1021
+ this._executableHandler = false;
1022
+ this._executableFile = null;
1023
+ this._executableDir = null;
1024
+ this._defaultCommandName = null;
1025
+ this._exitCallback = null;
1026
+ this._aliases = [];
1027
+ this._combineFlagAndOptionalValue = true;
1028
+ this._description = "";
1029
+ this._summary = "";
1030
+ this._argsDescription = void 0;
1031
+ this._enablePositionalOptions = false;
1032
+ this._passThroughOptions = false;
1033
+ this._lifeCycleHooks = {};
1034
+ /** @type {(boolean | string)} */
1035
+ this._showHelpAfterError = false;
1036
+ this._showSuggestionAfterError = true;
1037
+ this._savedState = null;
1038
+ this._outputConfiguration = {
1039
+ writeOut: (str) => process$1.stdout.write(str),
1040
+ writeErr: (str) => process$1.stderr.write(str),
1041
+ outputError: (str, write) => write(str),
1042
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1043
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1044
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1045
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1046
+ stripColor: (str) => stripVTControlCharacters(str)
1047
+ };
1048
+ this._hidden = false;
1049
+ /** @type {(Option | null | undefined)} */
1050
+ this._helpOption = void 0;
1051
+ this._addImplicitHelpCommand = void 0;
1052
+ /** @type {Command} */
1053
+ this._helpCommand = void 0;
1054
+ this._helpConfiguration = {};
1055
+ /** @type {string | undefined} */
1056
+ this._helpGroupHeading = void 0;
1057
+ /** @type {string | undefined} */
1058
+ this._defaultCommandGroup = void 0;
1059
+ /** @type {string | undefined} */
1060
+ this._defaultOptionGroup = void 0;
1061
+ }
1062
+ /**
1063
+ * Copy settings that are useful to have in common across root command and subcommands.
1064
+ *
1065
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1066
+ *
1067
+ * @param {Command} sourceCommand
1068
+ * @return {Command} `this` command for chaining
1069
+ */
1070
+ copyInheritedSettings(sourceCommand) {
1071
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1072
+ this._helpOption = sourceCommand._helpOption;
1073
+ this._helpCommand = sourceCommand._helpCommand;
1074
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1075
+ this._exitCallback = sourceCommand._exitCallback;
1076
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1077
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1078
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1079
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1080
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1081
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1082
+ return this;
1083
+ }
1084
+ /**
1085
+ * @returns {Command[]}
1086
+ * @private
1087
+ */
1088
+ _getCommandAndAncestors() {
1089
+ const result = [];
1090
+ for (let command = this; command; command = command.parent) result.push(command);
1091
+ return result;
1092
+ }
1093
+ /**
1094
+ * Define a command.
1095
+ *
1096
+ * There are two styles of command: pay attention to where to put the description.
1097
+ *
1098
+ * @example
1099
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1100
+ * program
1101
+ * .command('clone <source> [destination]')
1102
+ * .description('clone a repository into a newly created directory')
1103
+ * .action((source, destination) => {
1104
+ * console.log('clone command called');
1105
+ * });
1106
+ *
1107
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1108
+ * program
1109
+ * .command('start <service>', 'start named service')
1110
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1111
+ *
1112
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1113
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1114
+ * @param {object} [execOpts] - configuration options (for executable)
1115
+ * @return {Command} returns new command for action handler, or `this` for executable command
1116
+ */
1117
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1118
+ let desc = actionOptsOrExecDesc;
1119
+ let opts = execOpts;
1120
+ if (typeof desc === "object" && desc !== null) {
1121
+ opts = desc;
1122
+ desc = null;
1123
+ }
1124
+ opts = opts || {};
1125
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1126
+ const cmd = this.createCommand(name);
1127
+ if (desc) {
1128
+ cmd.description(desc);
1129
+ cmd._executableHandler = true;
1130
+ }
1131
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1132
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1133
+ cmd._executableFile = opts.executableFile || null;
1134
+ if (args) cmd.arguments(args);
1135
+ this._registerCommand(cmd);
1136
+ cmd.parent = this;
1137
+ cmd.copyInheritedSettings(this);
1138
+ if (desc) return this;
1139
+ return cmd;
1140
+ }
1141
+ /**
1142
+ * Factory routine to create a new unattached command.
1143
+ *
1144
+ * See .command() for creating an attached subcommand, which uses this routine to
1145
+ * create the command. You can override createCommand to customise subcommands.
1146
+ *
1147
+ * @param {string} [name]
1148
+ * @return {Command} new command
1149
+ */
1150
+ createCommand(name) {
1151
+ return new Command(name);
1152
+ }
1153
+ /**
1154
+ * You can customise the help with a subclass of Help by overriding createHelp,
1155
+ * or by overriding Help properties using configureHelp().
1156
+ *
1157
+ * @return {Help}
1158
+ */
1159
+ createHelp() {
1160
+ return Object.assign(new Help(), this.configureHelp());
1161
+ }
1162
+ /**
1163
+ * You can customise the help by overriding Help properties using configureHelp(),
1164
+ * or with a subclass of Help by overriding createHelp().
1165
+ *
1166
+ * @param {object} [configuration] - configuration options
1167
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1168
+ */
1169
+ configureHelp(configuration) {
1170
+ if (configuration === void 0) return this._helpConfiguration;
1171
+ this._helpConfiguration = configuration;
1172
+ return this;
1173
+ }
1174
+ /**
1175
+ * The default output goes to stdout and stderr. You can customise this for special
1176
+ * applications. You can also customise the display of errors by overriding outputError.
1177
+ *
1178
+ * The configuration properties are all functions:
1179
+ *
1180
+ * // change how output being written, defaults to stdout and stderr
1181
+ * writeOut(str)
1182
+ * writeErr(str)
1183
+ * // change how output being written for errors, defaults to writeErr
1184
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1185
+ * // specify width for wrapping help
1186
+ * getOutHelpWidth()
1187
+ * getErrHelpWidth()
1188
+ * // color support, currently only used with Help
1189
+ * getOutHasColors()
1190
+ * getErrHasColors()
1191
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1192
+ *
1193
+ * @param {object} [configuration] - configuration options
1194
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1195
+ */
1196
+ configureOutput(configuration) {
1197
+ if (configuration === void 0) return this._outputConfiguration;
1198
+ this._outputConfiguration = {
1199
+ ...this._outputConfiguration,
1200
+ ...configuration
1201
+ };
1202
+ return this;
1203
+ }
1204
+ /**
1205
+ * Display the help or a custom message after an error occurs.
1206
+ *
1207
+ * @param {(boolean|string)} [displayHelp]
1208
+ * @return {Command} `this` command for chaining
1209
+ */
1210
+ showHelpAfterError(displayHelp = true) {
1211
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1212
+ this._showHelpAfterError = displayHelp;
1213
+ return this;
1214
+ }
1215
+ /**
1216
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1217
+ *
1218
+ * @param {boolean} [displaySuggestion]
1219
+ * @return {Command} `this` command for chaining
1220
+ */
1221
+ showSuggestionAfterError(displaySuggestion = true) {
1222
+ this._showSuggestionAfterError = !!displaySuggestion;
1223
+ return this;
1224
+ }
1225
+ /**
1226
+ * Add a prepared subcommand.
1227
+ *
1228
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1229
+ *
1230
+ * @param {Command} cmd - new subcommand
1231
+ * @param {object} [opts] - configuration options
1232
+ * @return {Command} `this` command for chaining
1233
+ */
1234
+ addCommand(cmd, opts) {
1235
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1236
+ - specify the name in Command constructor or using .name()`);
1237
+ opts = opts || {};
1238
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1239
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1240
+ this._registerCommand(cmd);
1241
+ cmd.parent = this;
1242
+ cmd._checkForBrokenPassThrough();
1243
+ return this;
1244
+ }
1245
+ /**
1246
+ * Factory routine to create a new unattached argument.
1247
+ *
1248
+ * See .argument() for creating an attached argument, which uses this routine to
1249
+ * create the argument. You can override createArgument to return a custom argument.
1250
+ *
1251
+ * @param {string} name
1252
+ * @param {string} [description]
1253
+ * @return {Argument} new argument
1254
+ */
1255
+ createArgument(name, description) {
1256
+ return new Argument(name, description);
1257
+ }
1258
+ /**
1259
+ * Define argument syntax for command.
1260
+ *
1261
+ * The default is that the argument is required, and you can explicitly
1262
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1263
+ *
1264
+ * @example
1265
+ * program.argument('<input-file>');
1266
+ * program.argument('[output-file]');
1267
+ *
1268
+ * @param {string} name
1269
+ * @param {string} [description]
1270
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1271
+ * @param {*} [defaultValue]
1272
+ * @return {Command} `this` command for chaining
1273
+ */
1274
+ argument(name, description, parseArg, defaultValue) {
1275
+ const argument = this.createArgument(name, description);
1276
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1277
+ else argument.default(parseArg);
1278
+ this.addArgument(argument);
1279
+ return this;
1280
+ }
1281
+ /**
1282
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1283
+ *
1284
+ * See also .argument().
1285
+ *
1286
+ * @example
1287
+ * program.arguments('<cmd> [env]');
1288
+ *
1289
+ * @param {string} names
1290
+ * @return {Command} `this` command for chaining
1291
+ */
1292
+ arguments(names) {
1293
+ names.trim().split(/ +/).forEach((detail) => {
1294
+ this.argument(detail);
1295
+ });
1296
+ return this;
1297
+ }
1298
+ /**
1299
+ * Define argument syntax for command, adding a prepared argument.
1300
+ *
1301
+ * @param {Argument} argument
1302
+ * @return {Command} `this` command for chaining
1303
+ */
1304
+ addArgument(argument) {
1305
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1306
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1307
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1308
+ this.registeredArguments.push(argument);
1309
+ return this;
1310
+ }
1311
+ /**
1312
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1313
+ *
1314
+ * @example
1315
+ * program.helpCommand('help [cmd]');
1316
+ * program.helpCommand('help [cmd]', 'show help');
1317
+ * program.helpCommand(false); // suppress default help command
1318
+ * program.helpCommand(true); // add help command even if no subcommands
1319
+ *
1320
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1321
+ * @param {string} [description] - custom description
1322
+ * @return {Command} `this` command for chaining
1323
+ */
1324
+ helpCommand(enableOrNameAndArgs, description) {
1325
+ if (typeof enableOrNameAndArgs === "boolean") {
1326
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1327
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1328
+ return this;
1329
+ }
1330
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1331
+ const helpDescription = description ?? "display help for command";
1332
+ const helpCommand = this.createCommand(helpName);
1333
+ helpCommand.helpOption(false);
1334
+ if (helpArgs) helpCommand.arguments(helpArgs);
1335
+ if (helpDescription) helpCommand.description(helpDescription);
1336
+ this._addImplicitHelpCommand = true;
1337
+ this._helpCommand = helpCommand;
1338
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1339
+ return this;
1340
+ }
1341
+ /**
1342
+ * Add prepared custom help command.
1343
+ *
1344
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1345
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1346
+ * @return {Command} `this` command for chaining
1347
+ */
1348
+ addHelpCommand(helpCommand, deprecatedDescription) {
1349
+ if (typeof helpCommand !== "object") {
1350
+ this.helpCommand(helpCommand, deprecatedDescription);
1351
+ return this;
1352
+ }
1353
+ this._addImplicitHelpCommand = true;
1354
+ this._helpCommand = helpCommand;
1355
+ this._initCommandGroup(helpCommand);
1356
+ return this;
1357
+ }
1358
+ /**
1359
+ * Lazy create help command.
1360
+ *
1361
+ * @return {(Command|null)}
1362
+ * @package
1363
+ */
1364
+ _getHelpCommand() {
1365
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1366
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1367
+ return this._helpCommand;
1368
+ }
1369
+ return null;
1370
+ }
1371
+ /**
1372
+ * Add hook for life cycle event.
1373
+ *
1374
+ * @param {string} event
1375
+ * @param {Function} listener
1376
+ * @return {Command} `this` command for chaining
1377
+ */
1378
+ hook(event, listener) {
1379
+ const allowedValues = [
1380
+ "preSubcommand",
1381
+ "preAction",
1382
+ "postAction"
1383
+ ];
1384
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1385
+ Expecting one of '${allowedValues.join("', '")}'`);
1386
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1387
+ else this._lifeCycleHooks[event] = [listener];
1388
+ return this;
1389
+ }
1390
+ /**
1391
+ * Register callback to use as replacement for calling process.exit.
1392
+ *
1393
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1394
+ * @return {Command} `this` command for chaining
1395
+ */
1396
+ exitOverride(fn) {
1397
+ if (fn) this._exitCallback = fn;
1398
+ else this._exitCallback = (err) => {
1399
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1400
+ };
1401
+ return this;
1402
+ }
1403
+ /**
1404
+ * Call process.exit, and _exitCallback if defined.
1405
+ *
1406
+ * @param {number} exitCode exit code for using with process.exit
1407
+ * @param {string} code an id string representing the error
1408
+ * @param {string} message human-readable description of the error
1409
+ * @return never
1410
+ * @private
1411
+ */
1412
+ _exit(exitCode, code, message) {
1413
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1414
+ process$1.exit(exitCode);
1415
+ }
1416
+ /**
1417
+ * Register callback `fn` for the command.
1418
+ *
1419
+ * @example
1420
+ * program
1421
+ * .command('serve')
1422
+ * .description('start service')
1423
+ * .action(function() {
1424
+ * // do work here
1425
+ * });
1426
+ *
1427
+ * @param {Function} fn
1428
+ * @return {Command} `this` command for chaining
1429
+ */
1430
+ action(fn) {
1431
+ const listener = (args) => {
1432
+ const expectedArgsCount = this.registeredArguments.length;
1433
+ const actionArgs = args.slice(0, expectedArgsCount);
1434
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1435
+ else actionArgs[expectedArgsCount] = this.opts();
1436
+ actionArgs.push(this);
1437
+ return fn.apply(this, actionArgs);
1438
+ };
1439
+ this._actionHandler = listener;
1440
+ return this;
1441
+ }
1442
+ /**
1443
+ * Factory routine to create a new unattached option.
1444
+ *
1445
+ * See .option() for creating an attached option, which uses this routine to
1446
+ * create the option. You can override createOption to return a custom option.
1447
+ *
1448
+ * @param {string} flags
1449
+ * @param {string} [description]
1450
+ * @return {Option} new option
1451
+ */
1452
+ createOption(flags, description) {
1453
+ return new Option(flags, description);
1454
+ }
1455
+ /**
1456
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1457
+ *
1458
+ * @param {(Option | Argument)} target
1459
+ * @param {string} value
1460
+ * @param {*} previous
1461
+ * @param {string} invalidArgumentMessage
1462
+ * @private
1463
+ */
1464
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1465
+ try {
1466
+ return target.parseArg(value, previous);
1467
+ } catch (err) {
1468
+ if (err.code === "commander.invalidArgument") {
1469
+ const message = `${invalidArgumentMessage} ${err.message}`;
1470
+ this.error(message, {
1471
+ exitCode: err.exitCode,
1472
+ code: err.code
1473
+ });
1474
+ }
1475
+ throw err;
1476
+ }
1477
+ }
1478
+ /**
1479
+ * Check for option flag conflicts.
1480
+ * Register option if no conflicts found, or throw on conflict.
1481
+ *
1482
+ * @param {Option} option
1483
+ * @private
1484
+ */
1485
+ _registerOption(option) {
1486
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1487
+ if (matchingOption) {
1488
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1489
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1490
+ - already used by option '${matchingOption.flags}'`);
1491
+ }
1492
+ this._initOptionGroup(option);
1493
+ this.options.push(option);
1494
+ }
1495
+ /**
1496
+ * Check for command name and alias conflicts with existing commands.
1497
+ * Register command if no conflicts found, or throw on conflict.
1498
+ *
1499
+ * @param {Command} command
1500
+ * @private
1501
+ */
1502
+ _registerCommand(command) {
1503
+ const knownBy = (cmd) => {
1504
+ return [cmd.name()].concat(cmd.aliases());
1505
+ };
1506
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1507
+ if (alreadyUsed) {
1508
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1509
+ const newCmd = knownBy(command).join("|");
1510
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1511
+ }
1512
+ this._initCommandGroup(command);
1513
+ this.commands.push(command);
1514
+ }
1515
+ /**
1516
+ * Add an option.
1517
+ *
1518
+ * @param {Option} option
1519
+ * @return {Command} `this` command for chaining
1520
+ */
1521
+ addOption(option) {
1522
+ this._registerOption(option);
1523
+ const oname = option.name();
1524
+ const name = option.attributeName();
1525
+ if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1526
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1527
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1528
+ const oldValue = this.getOptionValue(name);
1529
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1530
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1531
+ if (val == null) if (option.negate) val = false;
1532
+ else if (option.isBoolean() || option.optional) val = true;
1533
+ else val = "";
1534
+ this.setOptionValueWithSource(name, val, valueSource);
1535
+ };
1536
+ this.on("option:" + oname, (val) => {
1537
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1538
+ handleOptionValue(val, invalidValueMessage, "cli");
1539
+ });
1540
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1541
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1542
+ handleOptionValue(val, invalidValueMessage, "env");
1543
+ });
1544
+ return this;
1545
+ }
1546
+ /**
1547
+ * Internal implementation shared by .option() and .requiredOption()
1548
+ *
1549
+ * @return {Command} `this` command for chaining
1550
+ * @private
1551
+ */
1552
+ _optionEx(config, flags, description, fn, defaultValue) {
1553
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1554
+ const option = this.createOption(flags, description);
1555
+ option.makeOptionMandatory(!!config.mandatory);
1556
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1557
+ else if (fn instanceof RegExp) {
1558
+ const regex = fn;
1559
+ fn = (val, def) => {
1560
+ const m = regex.exec(val);
1561
+ return m ? m[0] : def;
1562
+ };
1563
+ option.default(defaultValue).argParser(fn);
1564
+ } else option.default(fn);
1565
+ return this.addOption(option);
1566
+ }
1567
+ /**
1568
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1569
+ *
1570
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1571
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1572
+ *
1573
+ * See the README for more details, and see also addOption() and requiredOption().
1574
+ *
1575
+ * @example
1576
+ * program
1577
+ * .option('-p, --pepper', 'add pepper')
1578
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1579
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1580
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1581
+ *
1582
+ * @param {string} flags
1583
+ * @param {string} [description]
1584
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1585
+ * @param {*} [defaultValue]
1586
+ * @return {Command} `this` command for chaining
1587
+ */
1588
+ option(flags, description, parseArg, defaultValue) {
1589
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1590
+ }
1591
+ /**
1592
+ * Add a required option which must have a value after parsing. This usually means
1593
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1594
+ *
1595
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1596
+ *
1597
+ * @param {string} flags
1598
+ * @param {string} [description]
1599
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1600
+ * @param {*} [defaultValue]
1601
+ * @return {Command} `this` command for chaining
1602
+ */
1603
+ requiredOption(flags, description, parseArg, defaultValue) {
1604
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1605
+ }
1606
+ /**
1607
+ * Alter parsing of short flags with optional values.
1608
+ *
1609
+ * @example
1610
+ * // for `.option('-f,--flag [value]'):
1611
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1612
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1613
+ *
1614
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1615
+ * @return {Command} `this` command for chaining
1616
+ */
1617
+ combineFlagAndOptionalValue(combine = true) {
1618
+ this._combineFlagAndOptionalValue = !!combine;
1619
+ return this;
1620
+ }
1621
+ /**
1622
+ * Allow unknown options on the command line.
1623
+ *
1624
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1625
+ * @return {Command} `this` command for chaining
1626
+ */
1627
+ allowUnknownOption(allowUnknown = true) {
1628
+ this._allowUnknownOption = !!allowUnknown;
1629
+ return this;
1630
+ }
1631
+ /**
1632
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1633
+ *
1634
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1635
+ * @return {Command} `this` command for chaining
1636
+ */
1637
+ allowExcessArguments(allowExcess = true) {
1638
+ this._allowExcessArguments = !!allowExcess;
1639
+ return this;
1640
+ }
1641
+ /**
1642
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1643
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1644
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1645
+ *
1646
+ * @param {boolean} [positional]
1647
+ * @return {Command} `this` command for chaining
1648
+ */
1649
+ enablePositionalOptions(positional = true) {
1650
+ this._enablePositionalOptions = !!positional;
1651
+ return this;
1652
+ }
1653
+ /**
1654
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1655
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1656
+ * positional options to have been enabled on the program (parent commands).
1657
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1658
+ *
1659
+ * @param {boolean} [passThrough] for unknown options.
1660
+ * @return {Command} `this` command for chaining
1661
+ */
1662
+ passThroughOptions(passThrough = true) {
1663
+ this._passThroughOptions = !!passThrough;
1664
+ this._checkForBrokenPassThrough();
1665
+ return this;
1666
+ }
1667
+ /**
1668
+ * @private
1669
+ */
1670
+ _checkForBrokenPassThrough() {
1671
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1672
+ }
1673
+ /**
1674
+ * Whether to store option values as properties on command object,
1675
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1676
+ *
1677
+ * @param {boolean} [storeAsProperties=true]
1678
+ * @return {Command} `this` command for chaining
1679
+ */
1680
+ storeOptionsAsProperties(storeAsProperties = true) {
1681
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1682
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1683
+ this._storeOptionsAsProperties = !!storeAsProperties;
1684
+ return this;
1685
+ }
1686
+ /**
1687
+ * Retrieve option value.
1688
+ *
1689
+ * @param {string} key
1690
+ * @return {object} value
1691
+ */
1692
+ getOptionValue(key) {
1693
+ if (this._storeOptionsAsProperties) return this[key];
1694
+ return this._optionValues[key];
1695
+ }
1696
+ /**
1697
+ * Store option value.
1698
+ *
1699
+ * @param {string} key
1700
+ * @param {object} value
1701
+ * @return {Command} `this` command for chaining
1702
+ */
1703
+ setOptionValue(key, value) {
1704
+ return this.setOptionValueWithSource(key, value, void 0);
1705
+ }
1706
+ /**
1707
+ * Store option value and where the value came from.
1708
+ *
1709
+ * @param {string} key
1710
+ * @param {object} value
1711
+ * @param {string} source - expected values are default/config/env/cli/implied
1712
+ * @return {Command} `this` command for chaining
1713
+ */
1714
+ setOptionValueWithSource(key, value, source) {
1715
+ if (this._storeOptionsAsProperties) this[key] = value;
1716
+ else this._optionValues[key] = value;
1717
+ this._optionValueSources[key] = source;
1718
+ return this;
1719
+ }
1720
+ /**
1721
+ * Get source of option value.
1722
+ * Expected values are default | config | env | cli | implied
1723
+ *
1724
+ * @param {string} key
1725
+ * @return {string}
1726
+ */
1727
+ getOptionValueSource(key) {
1728
+ return this._optionValueSources[key];
1729
+ }
1730
+ /**
1731
+ * Get source of option value. See also .optsWithGlobals().
1732
+ * Expected values are default | config | env | cli | implied
1733
+ *
1734
+ * @param {string} key
1735
+ * @return {string}
1736
+ */
1737
+ getOptionValueSourceWithGlobals(key) {
1738
+ let source;
1739
+ this._getCommandAndAncestors().forEach((cmd) => {
1740
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1741
+ });
1742
+ return source;
1743
+ }
1744
+ /**
1745
+ * Get user arguments from implied or explicit arguments.
1746
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1747
+ *
1748
+ * @private
1749
+ */
1750
+ _prepareUserArgs(argv, parseOptions) {
1751
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1752
+ parseOptions = parseOptions || {};
1753
+ if (argv === void 0 && parseOptions.from === void 0) {
1754
+ if (process$1.versions?.electron) parseOptions.from = "electron";
1755
+ const execArgv = process$1.execArgv ?? [];
1756
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1757
+ }
1758
+ if (argv === void 0) argv = process$1.argv;
1759
+ this.rawArgs = argv.slice();
1760
+ let userArgs;
1761
+ switch (parseOptions.from) {
1762
+ case void 0:
1763
+ case "node":
1764
+ this._scriptPath = argv[1];
1765
+ userArgs = argv.slice(2);
1766
+ break;
1767
+ case "electron":
1768
+ if (process$1.defaultApp) {
1769
+ this._scriptPath = argv[1];
1770
+ userArgs = argv.slice(2);
1771
+ } else userArgs = argv.slice(1);
1772
+ break;
1773
+ case "user":
1774
+ userArgs = argv.slice(0);
1775
+ break;
1776
+ case "eval":
1777
+ userArgs = argv.slice(1);
1778
+ break;
1779
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1780
+ }
1781
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1782
+ this._name = this._name || "program";
1783
+ return userArgs;
1784
+ }
1785
+ /**
1786
+ * Parse `argv`, setting options and invoking commands when defined.
1787
+ *
1788
+ * Use parseAsync instead of parse if any of your action handlers are async.
1789
+ *
1790
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1791
+ *
1792
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1793
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1794
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1795
+ * - `'user'`: just user arguments
1796
+ *
1797
+ * @example
1798
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1799
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1800
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1801
+ *
1802
+ * @param {string[]} [argv] - optional, defaults to process.argv
1803
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1804
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1805
+ * @return {Command} `this` command for chaining
1806
+ */
1807
+ parse(argv, parseOptions) {
1808
+ this._prepareForParse();
1809
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1810
+ this._parseCommand([], userArgs);
1811
+ return this;
1812
+ }
1813
+ /**
1814
+ * Parse `argv`, setting options and invoking commands when defined.
1815
+ *
1816
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1817
+ *
1818
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1819
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1820
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1821
+ * - `'user'`: just user arguments
1822
+ *
1823
+ * @example
1824
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1825
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1826
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1827
+ *
1828
+ * @param {string[]} [argv]
1829
+ * @param {object} [parseOptions]
1830
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1831
+ * @return {Promise}
1832
+ */
1833
+ async parseAsync(argv, parseOptions) {
1834
+ this._prepareForParse();
1835
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1836
+ await this._parseCommand([], userArgs);
1837
+ return this;
1838
+ }
1839
+ _prepareForParse() {
1840
+ if (this._savedState === null) {
1841
+ this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
1842
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1843
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
1844
+ });
1845
+ this.saveStateBeforeParse();
1846
+ } else this.restoreStateBeforeParse();
1847
+ }
1848
+ /**
1849
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1850
+ * Not usually called directly, but available for subclasses to save their custom state.
1851
+ *
1852
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1853
+ */
1854
+ saveStateBeforeParse() {
1855
+ this._savedState = {
1856
+ _name: this._name,
1857
+ _optionValues: { ...this._optionValues },
1858
+ _optionValueSources: { ...this._optionValueSources }
1859
+ };
1860
+ }
1861
+ /**
1862
+ * Restore state before parse for calls after the first.
1863
+ * Not usually called directly, but available for subclasses to save their custom state.
1864
+ *
1865
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1866
+ */
1867
+ restoreStateBeforeParse() {
1868
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1869
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1870
+ this._name = this._savedState._name;
1871
+ this._scriptPath = null;
1872
+ this.rawArgs = [];
1873
+ this._optionValues = { ...this._savedState._optionValues };
1874
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1875
+ this.args = [];
1876
+ this.processedArgs = [];
1877
+ }
1878
+ /**
1879
+ * Throw if expected executable is missing. Add lots of help for author.
1880
+ *
1881
+ * @param {string} executableFile
1882
+ * @param {string} executableDir
1883
+ * @param {string} subcommandName
1884
+ */
1885
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1886
+ if (fs.existsSync(executableFile)) return;
1887
+ const executableMissing = `'${executableFile}' does not exist
1888
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1889
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1890
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1891
+ throw new Error(executableMissing);
1892
+ }
1893
+ /**
1894
+ * Execute a sub-command executable.
1895
+ *
1896
+ * @private
1897
+ */
1898
+ _executeSubCommand(subcommand, args) {
1899
+ args = args.slice();
1900
+ const sourceExt = [
1901
+ ".js",
1902
+ ".ts",
1903
+ ".tsx",
1904
+ ".mjs",
1905
+ ".cjs"
1906
+ ];
1907
+ function findFile(baseDir, baseName) {
1908
+ const localBin = path.resolve(baseDir, baseName);
1909
+ if (fs.existsSync(localBin)) return localBin;
1910
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1911
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1912
+ if (foundExt) return `${localBin}${foundExt}`;
1913
+ }
1914
+ this._checkForMissingMandatoryOptions();
1915
+ this._checkForConflictingOptions();
1916
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1917
+ let executableDir = this._executableDir || "";
1918
+ if (this._scriptPath) {
1919
+ let resolvedScriptPath;
1920
+ try {
1921
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1922
+ } catch {
1923
+ resolvedScriptPath = this._scriptPath;
1924
+ }
1925
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1926
+ }
1927
+ if (executableDir) {
1928
+ let localFile = findFile(executableDir, executableFile);
1929
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1930
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1931
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1932
+ }
1933
+ executableFile = localFile || executableFile;
1934
+ }
1935
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1936
+ let proc;
1937
+ if (process$1.platform !== "win32") if (launchWithNode) {
1938
+ args.unshift(executableFile);
1939
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1940
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1941
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1942
+ else {
1943
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1944
+ args.unshift(executableFile);
1945
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1946
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
1947
+ }
1948
+ if (!proc.killed) [
1949
+ "SIGUSR1",
1950
+ "SIGUSR2",
1951
+ "SIGTERM",
1952
+ "SIGINT",
1953
+ "SIGHUP"
1954
+ ].forEach((signal) => {
1955
+ process$1.on(signal, () => {
1956
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
1957
+ });
1958
+ });
1959
+ const exitCallback = this._exitCallback;
1960
+ proc.on("close", (code) => {
1961
+ code = code ?? 1;
1962
+ if (!exitCallback) process$1.exit(code);
1963
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1964
+ });
1965
+ proc.on("error", (err) => {
1966
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1967
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
1968
+ if (!exitCallback) process$1.exit(1);
1969
+ else {
1970
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1971
+ wrappedError.nestedError = err;
1972
+ exitCallback(wrappedError);
1973
+ }
1974
+ });
1975
+ this.runningCommand = proc;
1976
+ }
1977
+ /**
1978
+ * @private
1979
+ */
1980
+ _dispatchSubcommand(commandName, operands, unknown) {
1981
+ const subCommand = this._findCommand(commandName);
1982
+ if (!subCommand) this.help({ error: true });
1983
+ subCommand._prepareForParse();
1984
+ let promiseChain;
1985
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1986
+ promiseChain = this._chainOrCall(promiseChain, () => {
1987
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
1988
+ else return subCommand._parseCommand(operands, unknown);
1989
+ });
1990
+ return promiseChain;
1991
+ }
1992
+ /**
1993
+ * Invoke help directly if possible, or dispatch if necessary.
1994
+ * e.g. help foo
1995
+ *
1996
+ * @private
1997
+ */
1998
+ _dispatchHelpCommand(subcommandName) {
1999
+ if (!subcommandName) this.help();
2000
+ const subCommand = this._findCommand(subcommandName);
2001
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2002
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2003
+ }
2004
+ /**
2005
+ * Check this.args against expected this.registeredArguments.
2006
+ *
2007
+ * @private
2008
+ */
2009
+ _checkNumberOfArguments() {
2010
+ this.registeredArguments.forEach((arg, i) => {
2011
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2012
+ });
2013
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2014
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2015
+ }
2016
+ /**
2017
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2018
+ *
2019
+ * @private
2020
+ */
2021
+ _processArguments() {
2022
+ const myParseArg = (argument, value, previous) => {
2023
+ let parsedValue = value;
2024
+ if (value !== null && argument.parseArg) {
2025
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2026
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2027
+ }
2028
+ return parsedValue;
2029
+ };
2030
+ this._checkNumberOfArguments();
2031
+ const processedArgs = [];
2032
+ this.registeredArguments.forEach((declaredArg, index) => {
2033
+ let value = declaredArg.defaultValue;
2034
+ if (declaredArg.variadic) {
2035
+ if (index < this.args.length) {
2036
+ value = this.args.slice(index);
2037
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2038
+ return myParseArg(declaredArg, v, processed);
2039
+ }, declaredArg.defaultValue);
2040
+ } else if (value === void 0) value = [];
2041
+ } else if (index < this.args.length) {
2042
+ value = this.args[index];
2043
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2044
+ }
2045
+ processedArgs[index] = value;
2046
+ });
2047
+ this.processedArgs = processedArgs;
2048
+ }
2049
+ /**
2050
+ * Once we have a promise we chain, but call synchronously until then.
2051
+ *
2052
+ * @param {(Promise|undefined)} promise
2053
+ * @param {Function} fn
2054
+ * @return {(Promise|undefined)}
2055
+ * @private
2056
+ */
2057
+ _chainOrCall(promise, fn) {
2058
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2059
+ return fn();
2060
+ }
2061
+ /**
2062
+ *
2063
+ * @param {(Promise|undefined)} promise
2064
+ * @param {string} event
2065
+ * @return {(Promise|undefined)}
2066
+ * @private
2067
+ */
2068
+ _chainOrCallHooks(promise, event) {
2069
+ let result = promise;
2070
+ const hooks = [];
2071
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2072
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2073
+ hooks.push({
2074
+ hookedCommand,
2075
+ callback
2076
+ });
2077
+ });
2078
+ });
2079
+ if (event === "postAction") hooks.reverse();
2080
+ hooks.forEach((hookDetail) => {
2081
+ result = this._chainOrCall(result, () => {
2082
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2083
+ });
2084
+ });
2085
+ return result;
2086
+ }
2087
+ /**
2088
+ *
2089
+ * @param {(Promise|undefined)} promise
2090
+ * @param {Command} subCommand
2091
+ * @param {string} event
2092
+ * @return {(Promise|undefined)}
2093
+ * @private
2094
+ */
2095
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2096
+ let result = promise;
2097
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2098
+ result = this._chainOrCall(result, () => {
2099
+ return hook(this, subCommand);
2100
+ });
2101
+ });
2102
+ return result;
2103
+ }
2104
+ /**
2105
+ * Process arguments in context of this command.
2106
+ * Returns action result, in case it is a promise.
2107
+ *
2108
+ * @private
2109
+ */
2110
+ _parseCommand(operands, unknown) {
2111
+ const parsed = this.parseOptions(unknown);
2112
+ this._parseOptionsEnv();
2113
+ this._parseOptionsImplied();
2114
+ operands = operands.concat(parsed.operands);
2115
+ unknown = parsed.unknown;
2116
+ this.args = operands.concat(unknown);
2117
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2118
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2119
+ if (this._defaultCommandName) {
2120
+ this._outputHelpIfRequested(unknown);
2121
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2122
+ }
2123
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2124
+ this._outputHelpIfRequested(parsed.unknown);
2125
+ this._checkForMissingMandatoryOptions();
2126
+ this._checkForConflictingOptions();
2127
+ const checkForUnknownOptions = () => {
2128
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2129
+ };
2130
+ const commandEvent = `command:${this.name()}`;
2131
+ if (this._actionHandler) {
2132
+ checkForUnknownOptions();
2133
+ this._processArguments();
2134
+ let promiseChain;
2135
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2136
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2137
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2138
+ this.parent.emit(commandEvent, operands, unknown);
2139
+ });
2140
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2141
+ return promiseChain;
2142
+ }
2143
+ if (this.parent?.listenerCount(commandEvent)) {
2144
+ checkForUnknownOptions();
2145
+ this._processArguments();
2146
+ this.parent.emit(commandEvent, operands, unknown);
2147
+ } else if (operands.length) {
2148
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2149
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2150
+ else if (this.commands.length) this.unknownCommand();
2151
+ else {
2152
+ checkForUnknownOptions();
2153
+ this._processArguments();
2154
+ }
2155
+ } else if (this.commands.length) {
2156
+ checkForUnknownOptions();
2157
+ this.help({ error: true });
2158
+ } else {
2159
+ checkForUnknownOptions();
2160
+ this._processArguments();
2161
+ }
2162
+ }
2163
+ /**
2164
+ * Find matching command.
2165
+ *
2166
+ * @private
2167
+ * @return {Command | undefined}
2168
+ */
2169
+ _findCommand(name) {
2170
+ if (!name) return void 0;
2171
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2172
+ }
2173
+ /**
2174
+ * Return an option matching `arg` if any.
2175
+ *
2176
+ * @param {string} arg
2177
+ * @return {Option}
2178
+ * @package
2179
+ */
2180
+ _findOption(arg) {
2181
+ return this.options.find((option) => option.is(arg));
2182
+ }
2183
+ /**
2184
+ * Display an error message if a mandatory option does not have a value.
2185
+ * Called after checking for help flags in leaf subcommand.
2186
+ *
2187
+ * @private
2188
+ */
2189
+ _checkForMissingMandatoryOptions() {
2190
+ this._getCommandAndAncestors().forEach((cmd) => {
2191
+ cmd.options.forEach((anOption) => {
2192
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2193
+ });
2194
+ });
2195
+ }
2196
+ /**
2197
+ * Display an error message if conflicting options are used together in this.
2198
+ *
2199
+ * @private
2200
+ */
2201
+ _checkForConflictingLocalOptions() {
2202
+ const definedNonDefaultOptions = this.options.filter((option) => {
2203
+ const optionKey = option.attributeName();
2204
+ if (this.getOptionValue(optionKey) === void 0) return false;
2205
+ return this.getOptionValueSource(optionKey) !== "default";
2206
+ });
2207
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2208
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2209
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2210
+ });
2211
+ }
2212
+ /**
2213
+ * Display an error message if conflicting options are used together.
2214
+ * Called after checking for help flags in leaf subcommand.
2215
+ *
2216
+ * @private
2217
+ */
2218
+ _checkForConflictingOptions() {
2219
+ this._getCommandAndAncestors().forEach((cmd) => {
2220
+ cmd._checkForConflictingLocalOptions();
2221
+ });
2222
+ }
2223
+ /**
2224
+ * Parse options from `argv` removing known options,
2225
+ * and return argv split into operands and unknown arguments.
2226
+ *
2227
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2228
+ *
2229
+ * Examples:
2230
+ *
2231
+ * argv => operands, unknown
2232
+ * --known kkk op => [op], []
2233
+ * op --known kkk => [op], []
2234
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2235
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2236
+ *
2237
+ * @param {string[]} args
2238
+ * @return {{operands: string[], unknown: string[]}}
2239
+ */
2240
+ parseOptions(args) {
2241
+ const operands = [];
2242
+ const unknown = [];
2243
+ let dest = operands;
2244
+ function maybeOption(arg) {
2245
+ return arg.length > 1 && arg[0] === "-";
2246
+ }
2247
+ const negativeNumberArg = (arg) => {
2248
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2249
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2250
+ };
2251
+ let activeVariadicOption = null;
2252
+ let activeGroup = null;
2253
+ let i = 0;
2254
+ while (i < args.length || activeGroup) {
2255
+ const arg = activeGroup ?? args[i++];
2256
+ activeGroup = null;
2257
+ if (arg === "--") {
2258
+ if (dest === unknown) dest.push(arg);
2259
+ dest.push(...args.slice(i));
2260
+ break;
2261
+ }
2262
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2263
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2264
+ continue;
2265
+ }
2266
+ activeVariadicOption = null;
2267
+ if (maybeOption(arg)) {
2268
+ const option = this._findOption(arg);
2269
+ if (option) {
2270
+ if (option.required) {
2271
+ const value = args[i++];
2272
+ if (value === void 0) this.optionMissingArgument(option);
2273
+ this.emit(`option:${option.name()}`, value);
2274
+ } else if (option.optional) {
2275
+ let value = null;
2276
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2277
+ this.emit(`option:${option.name()}`, value);
2278
+ } else this.emit(`option:${option.name()}`);
2279
+ activeVariadicOption = option.variadic ? option : null;
2280
+ continue;
2281
+ }
2282
+ }
2283
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2284
+ const option = this._findOption(`-${arg[1]}`);
2285
+ if (option) {
2286
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2287
+ else {
2288
+ this.emit(`option:${option.name()}`);
2289
+ activeGroup = `-${arg.slice(2)}`;
2290
+ }
2291
+ continue;
2292
+ }
2293
+ }
2294
+ if (/^--[^=]+=/.test(arg)) {
2295
+ const index = arg.indexOf("=");
2296
+ const option = this._findOption(arg.slice(0, index));
2297
+ if (option && (option.required || option.optional)) {
2298
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2299
+ continue;
2300
+ }
2301
+ }
2302
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2303
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2304
+ if (this._findCommand(arg)) {
2305
+ operands.push(arg);
2306
+ unknown.push(...args.slice(i));
2307
+ break;
2308
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2309
+ operands.push(arg, ...args.slice(i));
2310
+ break;
2311
+ } else if (this._defaultCommandName) {
2312
+ unknown.push(arg, ...args.slice(i));
2313
+ break;
2314
+ }
2315
+ }
2316
+ if (this._passThroughOptions) {
2317
+ dest.push(arg, ...args.slice(i));
2318
+ break;
2319
+ }
2320
+ dest.push(arg);
2321
+ }
2322
+ return {
2323
+ operands,
2324
+ unknown
2325
+ };
2326
+ }
2327
+ /**
2328
+ * Return an object containing local option values as key-value pairs.
2329
+ *
2330
+ * @return {object}
2331
+ */
2332
+ opts() {
2333
+ if (this._storeOptionsAsProperties) {
2334
+ const result = {};
2335
+ const len = this.options.length;
2336
+ for (let i = 0; i < len; i++) {
2337
+ const key = this.options[i].attributeName();
2338
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2339
+ }
2340
+ return result;
2341
+ }
2342
+ return this._optionValues;
2343
+ }
2344
+ /**
2345
+ * Return an object containing merged local and global option values as key-value pairs.
2346
+ *
2347
+ * @return {object}
2348
+ */
2349
+ optsWithGlobals() {
2350
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2351
+ }
2352
+ /**
2353
+ * Display error message and exit (or call exitOverride).
2354
+ *
2355
+ * @param {string} message
2356
+ * @param {object} [errorOptions]
2357
+ * @param {string} [errorOptions.code] - an id string representing the error
2358
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2359
+ */
2360
+ error(message, errorOptions) {
2361
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2362
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2363
+ else if (this._showHelpAfterError) {
2364
+ this._outputConfiguration.writeErr("\n");
2365
+ this.outputHelp({ error: true });
2366
+ }
2367
+ const config = errorOptions || {};
2368
+ const exitCode = config.exitCode || 1;
2369
+ const code = config.code || "commander.error";
2370
+ this._exit(exitCode, code, message);
2371
+ }
2372
+ /**
2373
+ * Apply any option related environment variables, if option does
2374
+ * not have a value from cli or client code.
2375
+ *
2376
+ * @private
2377
+ */
2378
+ _parseOptionsEnv() {
2379
+ this.options.forEach((option) => {
2380
+ if (option.envVar && option.envVar in process$1.env) {
2381
+ const optionKey = option.attributeName();
2382
+ if (this.getOptionValue(optionKey) === void 0 || [
2383
+ "default",
2384
+ "config",
2385
+ "env"
2386
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2387
+ else this.emit(`optionEnv:${option.name()}`);
2388
+ }
2389
+ });
2390
+ }
2391
+ /**
2392
+ * Apply any implied option values, if option is undefined or default value.
2393
+ *
2394
+ * @private
2395
+ */
2396
+ _parseOptionsImplied() {
2397
+ const dualHelper = new DualOptions(this.options);
2398
+ const hasCustomOptionValue = (optionKey) => {
2399
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2400
+ };
2401
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2402
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2403
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2404
+ });
2405
+ });
2406
+ }
2407
+ /**
2408
+ * Argument `name` is missing.
2409
+ *
2410
+ * @param {string} name
2411
+ * @private
2412
+ */
2413
+ missingArgument(name) {
2414
+ const message = `error: missing required argument '${name}'`;
2415
+ this.error(message, { code: "commander.missingArgument" });
2416
+ }
2417
+ /**
2418
+ * `Option` is missing an argument.
2419
+ *
2420
+ * @param {Option} option
2421
+ * @private
2422
+ */
2423
+ optionMissingArgument(option) {
2424
+ const message = `error: option '${option.flags}' argument missing`;
2425
+ this.error(message, { code: "commander.optionMissingArgument" });
2426
+ }
2427
+ /**
2428
+ * `Option` does not have a value, and is a mandatory option.
2429
+ *
2430
+ * @param {Option} option
2431
+ * @private
2432
+ */
2433
+ missingMandatoryOptionValue(option) {
2434
+ const message = `error: required option '${option.flags}' not specified`;
2435
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2436
+ }
2437
+ /**
2438
+ * `Option` conflicts with another option.
2439
+ *
2440
+ * @param {Option} option
2441
+ * @param {Option} conflictingOption
2442
+ * @private
2443
+ */
2444
+ _conflictingOption(option, conflictingOption) {
2445
+ const findBestOptionFromValue = (option) => {
2446
+ const optionKey = option.attributeName();
2447
+ const optionValue = this.getOptionValue(optionKey);
2448
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2449
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2450
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2451
+ return positiveOption || option;
2452
+ };
2453
+ const getErrorMessage = (option) => {
2454
+ const bestOption = findBestOptionFromValue(option);
2455
+ const optionKey = bestOption.attributeName();
2456
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2457
+ return `option '${bestOption.flags}'`;
2458
+ };
2459
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2460
+ this.error(message, { code: "commander.conflictingOption" });
2461
+ }
2462
+ /**
2463
+ * Unknown option `flag`.
2464
+ *
2465
+ * @param {string} flag
2466
+ * @private
2467
+ */
2468
+ unknownOption(flag) {
2469
+ if (this._allowUnknownOption) return;
2470
+ let suggestion = "";
2471
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2472
+ let candidateFlags = [];
2473
+ let command = this;
2474
+ do {
2475
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2476
+ candidateFlags = candidateFlags.concat(moreFlags);
2477
+ command = command.parent;
2478
+ } while (command && !command._enablePositionalOptions);
2479
+ suggestion = suggestSimilar(flag, candidateFlags);
2480
+ }
2481
+ const message = `error: unknown option '${flag}'${suggestion}`;
2482
+ this.error(message, { code: "commander.unknownOption" });
2483
+ }
2484
+ /**
2485
+ * Excess arguments, more than expected.
2486
+ *
2487
+ * @param {string[]} receivedArgs
2488
+ * @private
2489
+ */
2490
+ _excessArguments(receivedArgs) {
2491
+ if (this._allowExcessArguments) return;
2492
+ const expected = this.registeredArguments.length;
2493
+ const s = expected === 1 ? "" : "s";
2494
+ const received = receivedArgs.length;
2495
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
2496
+ this.error(message, { code: "commander.excessArguments" });
2497
+ }
2498
+ /**
2499
+ * Unknown command.
2500
+ *
2501
+ * @private
2502
+ */
2503
+ unknownCommand() {
2504
+ const unknownName = this.args[0];
2505
+ let suggestion = "";
2506
+ if (this._showSuggestionAfterError) {
2507
+ const candidateNames = [];
2508
+ this.createHelp().visibleCommands(this).forEach((command) => {
2509
+ candidateNames.push(command.name());
2510
+ if (command.alias()) candidateNames.push(command.alias());
2511
+ });
2512
+ suggestion = suggestSimilar(unknownName, candidateNames);
2513
+ }
2514
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2515
+ this.error(message, { code: "commander.unknownCommand" });
2516
+ }
2517
+ /**
2518
+ * Get or set the program version.
2519
+ *
2520
+ * This method auto-registers the "-V, --version" option which will print the version number.
2521
+ *
2522
+ * You can optionally supply the flags and description to override the defaults.
2523
+ *
2524
+ * @param {string} [str]
2525
+ * @param {string} [flags]
2526
+ * @param {string} [description]
2527
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2528
+ */
2529
+ version(str, flags, description) {
2530
+ if (str === void 0) return this._version;
2531
+ this._version = str;
2532
+ flags = flags || "-V, --version";
2533
+ description = description || "output the version number";
2534
+ const versionOption = this.createOption(flags, description);
2535
+ this._versionOptionName = versionOption.attributeName();
2536
+ this._registerOption(versionOption);
2537
+ this.on("option:" + versionOption.name(), () => {
2538
+ this._outputConfiguration.writeOut(`${str}\n`);
2539
+ this._exit(0, "commander.version", str);
2540
+ });
2541
+ return this;
2542
+ }
2543
+ /**
2544
+ * Set the description.
2545
+ *
2546
+ * @param {string} [str]
2547
+ * @param {object} [argsDescription]
2548
+ * @return {(string|Command)}
2549
+ */
2550
+ description(str, argsDescription) {
2551
+ if (str === void 0 && argsDescription === void 0) return this._description;
2552
+ this._description = str;
2553
+ if (argsDescription) this._argsDescription = argsDescription;
2554
+ return this;
2555
+ }
2556
+ /**
2557
+ * Set the summary. Used when listed as subcommand of parent.
2558
+ *
2559
+ * @param {string} [str]
2560
+ * @return {(string|Command)}
2561
+ */
2562
+ summary(str) {
2563
+ if (str === void 0) return this._summary;
2564
+ this._summary = str;
2565
+ return this;
2566
+ }
2567
+ /**
2568
+ * Set an alias for the command.
2569
+ *
2570
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2571
+ *
2572
+ * @param {string} [alias]
2573
+ * @return {(string|Command)}
2574
+ */
2575
+ alias(alias) {
2576
+ if (alias === void 0) return this._aliases[0];
2577
+ /** @type {Command} */
2578
+ let command = this;
2579
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2580
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2581
+ const matchingCommand = this.parent?._findCommand(alias);
2582
+ if (matchingCommand) {
2583
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2584
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2585
+ }
2586
+ command._aliases.push(alias);
2587
+ return this;
2588
+ }
2589
+ /**
2590
+ * Set aliases for the command.
2591
+ *
2592
+ * Only the first alias is shown in the auto-generated help.
2593
+ *
2594
+ * @param {string[]} [aliases]
2595
+ * @return {(string[]|Command)}
2596
+ */
2597
+ aliases(aliases) {
2598
+ if (aliases === void 0) return this._aliases;
2599
+ aliases.forEach((alias) => this.alias(alias));
2600
+ return this;
2601
+ }
2602
+ /**
2603
+ * Set / get the command usage `str`.
2604
+ *
2605
+ * @param {string} [str]
2606
+ * @return {(string|Command)}
2607
+ */
2608
+ usage(str) {
2609
+ if (str === void 0) {
2610
+ if (this._usage) return this._usage;
2611
+ const args = this.registeredArguments.map((arg) => {
2612
+ return humanReadableArgName(arg);
2613
+ });
2614
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2615
+ }
2616
+ this._usage = str;
2617
+ return this;
2618
+ }
2619
+ /**
2620
+ * Get or set the name of the command.
2621
+ *
2622
+ * @param {string} [str]
2623
+ * @return {(string|Command)}
2624
+ */
2625
+ name(str) {
2626
+ if (str === void 0) return this._name;
2627
+ this._name = str;
2628
+ return this;
2629
+ }
2630
+ /**
2631
+ * Set/get the help group heading for this subcommand in parent command's help.
2632
+ *
2633
+ * @param {string} [heading]
2634
+ * @return {Command | string}
2635
+ */
2636
+ helpGroup(heading) {
2637
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2638
+ this._helpGroupHeading = heading;
2639
+ return this;
2640
+ }
2641
+ /**
2642
+ * Set/get the default help group heading for subcommands added to this command.
2643
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2644
+ *
2645
+ * @example
2646
+ * program.commandsGroup('Development Commands:);
2647
+ * program.command('watch')...
2648
+ * program.command('lint')...
2649
+ * ...
2650
+ *
2651
+ * @param {string} [heading]
2652
+ * @returns {Command | string}
2653
+ */
2654
+ commandsGroup(heading) {
2655
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2656
+ this._defaultCommandGroup = heading;
2657
+ return this;
2658
+ }
2659
+ /**
2660
+ * Set/get the default help group heading for options added to this command.
2661
+ * (This does not override a group set directly on the option using .helpGroup().)
2662
+ *
2663
+ * @example
2664
+ * program
2665
+ * .optionsGroup('Development Options:')
2666
+ * .option('-d, --debug', 'output extra debugging')
2667
+ * .option('-p, --profile', 'output profiling information')
2668
+ *
2669
+ * @param {string} [heading]
2670
+ * @returns {Command | string}
2671
+ */
2672
+ optionsGroup(heading) {
2673
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2674
+ this._defaultOptionGroup = heading;
2675
+ return this;
2676
+ }
2677
+ /**
2678
+ * @param {Option} option
2679
+ * @private
2680
+ */
2681
+ _initOptionGroup(option) {
2682
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2683
+ }
2684
+ /**
2685
+ * @param {Command} cmd
2686
+ * @private
2687
+ */
2688
+ _initCommandGroup(cmd) {
2689
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2690
+ }
2691
+ /**
2692
+ * Set the name of the command from script filename, such as process.argv[1],
2693
+ * or import.meta.filename.
2694
+ *
2695
+ * (Used internally and public although not documented in README.)
2696
+ *
2697
+ * @example
2698
+ * program.nameFromFilename(import.meta.filename);
2699
+ *
2700
+ * @param {string} filename
2701
+ * @return {Command}
2702
+ */
2703
+ nameFromFilename(filename) {
2704
+ this._name = path.basename(filename, path.extname(filename));
2705
+ return this;
2706
+ }
2707
+ /**
2708
+ * Get or set the directory for searching for executable subcommands of this command.
2709
+ *
2710
+ * @example
2711
+ * program.executableDir(import.meta.dirname);
2712
+ * // or
2713
+ * program.executableDir('subcommands');
2714
+ *
2715
+ * @param {string} [path]
2716
+ * @return {(string|null|Command)}
2717
+ */
2718
+ executableDir(path) {
2719
+ if (path === void 0) return this._executableDir;
2720
+ this._executableDir = path;
2721
+ return this;
2722
+ }
2723
+ /**
2724
+ * Return program help documentation.
2725
+ *
2726
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2727
+ * @return {string}
2728
+ */
2729
+ helpInformation(contextOptions) {
2730
+ const helper = this.createHelp();
2731
+ const context = this._getOutputContext(contextOptions);
2732
+ helper.prepareContext({
2733
+ error: context.error,
2734
+ helpWidth: context.helpWidth,
2735
+ outputHasColors: context.hasColors
2736
+ });
2737
+ const text = helper.formatHelp(this, helper);
2738
+ if (context.hasColors) return text;
2739
+ return this._outputConfiguration.stripColor(text);
2740
+ }
2741
+ /**
2742
+ * @typedef HelpContext
2743
+ * @type {object}
2744
+ * @property {boolean} error
2745
+ * @property {number} helpWidth
2746
+ * @property {boolean} hasColors
2747
+ * @property {function} write - includes stripColor if needed
2748
+ *
2749
+ * @returns {HelpContext}
2750
+ * @private
2751
+ */
2752
+ _getOutputContext(contextOptions) {
2753
+ contextOptions = contextOptions || {};
2754
+ const error = !!contextOptions.error;
2755
+ let baseWrite;
2756
+ let hasColors;
2757
+ let helpWidth;
2758
+ if (error) {
2759
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2760
+ hasColors = this._outputConfiguration.getErrHasColors();
2761
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2762
+ } else {
2763
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2764
+ hasColors = this._outputConfiguration.getOutHasColors();
2765
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2766
+ }
2767
+ const write = (str) => {
2768
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2769
+ return baseWrite(str);
2770
+ };
2771
+ return {
2772
+ error,
2773
+ write,
2774
+ hasColors,
2775
+ helpWidth
2776
+ };
2777
+ }
2778
+ /**
2779
+ * Output help information for this command.
2780
+ *
2781
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2782
+ *
2783
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2784
+ */
2785
+ outputHelp(contextOptions) {
2786
+ let deprecatedCallback;
2787
+ if (typeof contextOptions === "function") {
2788
+ deprecatedCallback = contextOptions;
2789
+ contextOptions = void 0;
2790
+ }
2791
+ const outputContext = this._getOutputContext(contextOptions);
2792
+ /** @type {HelpTextEventContext} */
2793
+ const eventContext = {
2794
+ error: outputContext.error,
2795
+ write: outputContext.write,
2796
+ command: this
2797
+ };
2798
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2799
+ this.emit("beforeHelp", eventContext);
2800
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2801
+ if (deprecatedCallback) {
2802
+ helpInformation = deprecatedCallback(helpInformation);
2803
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2804
+ }
2805
+ outputContext.write(helpInformation);
2806
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2807
+ this.emit("afterHelp", eventContext);
2808
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2809
+ }
2810
+ /**
2811
+ * You can pass in flags and a description to customise the built-in help option.
2812
+ * Pass in false to disable the built-in help option.
2813
+ *
2814
+ * @example
2815
+ * program.helpOption('-?, --help' 'show help'); // customise
2816
+ * program.helpOption(false); // disable
2817
+ *
2818
+ * @param {(string | boolean)} flags
2819
+ * @param {string} [description]
2820
+ * @return {Command} `this` command for chaining
2821
+ */
2822
+ helpOption(flags, description) {
2823
+ if (typeof flags === "boolean") {
2824
+ if (flags) {
2825
+ if (this._helpOption === null) this._helpOption = void 0;
2826
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2827
+ } else this._helpOption = null;
2828
+ return this;
2829
+ }
2830
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2831
+ if (flags || description) this._initOptionGroup(this._helpOption);
2832
+ return this;
2833
+ }
2834
+ /**
2835
+ * Lazy create help option.
2836
+ * Returns null if has been disabled with .helpOption(false).
2837
+ *
2838
+ * @returns {(Option | null)} the help option
2839
+ * @package
2840
+ */
2841
+ _getHelpOption() {
2842
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2843
+ return this._helpOption;
2844
+ }
2845
+ /**
2846
+ * Supply your own option to use for the built-in help option.
2847
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2848
+ *
2849
+ * @param {Option} option
2850
+ * @return {Command} `this` command for chaining
2851
+ */
2852
+ addHelpOption(option) {
2853
+ this._helpOption = option;
2854
+ this._initOptionGroup(option);
2855
+ return this;
2856
+ }
2857
+ /**
2858
+ * Output help information and exit.
2859
+ *
2860
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2861
+ *
2862
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2863
+ */
2864
+ help(contextOptions) {
2865
+ this.outputHelp(contextOptions);
2866
+ let exitCode = Number(process$1.exitCode ?? 0);
2867
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2868
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2869
+ }
2870
+ /**
2871
+ * // Do a little typing to coordinate emit and listener for the help text events.
2872
+ * @typedef HelpTextEventContext
2873
+ * @type {object}
2874
+ * @property {boolean} error
2875
+ * @property {Command} command
2876
+ * @property {function} write
2877
+ */
2878
+ /**
2879
+ * Add additional text to be displayed with the built-in help.
2880
+ *
2881
+ * Position is 'before' or 'after' to affect just this command,
2882
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2883
+ *
2884
+ * @param {string} position - before or after built-in help
2885
+ * @param {(string | Function)} text - string to add, or a function returning a string
2886
+ * @return {Command} `this` command for chaining
2887
+ */
2888
+ addHelpText(position, text) {
2889
+ const allowedValues = [
2890
+ "beforeAll",
2891
+ "before",
2892
+ "after",
2893
+ "afterAll"
2894
+ ];
2895
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2896
+ Expecting one of '${allowedValues.join("', '")}'`);
2897
+ const helpEvent = `${position}Help`;
2898
+ this.on(helpEvent, (context) => {
2899
+ let helpStr;
2900
+ if (typeof text === "function") helpStr = text({
2901
+ error: context.error,
2902
+ command: context.command
2903
+ });
2904
+ else helpStr = text;
2905
+ if (helpStr) context.write(`${helpStr}\n`);
2906
+ });
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Output help information if help flags specified
2911
+ *
2912
+ * @param {Array} args - array of options to search for help flags
2913
+ * @private
2914
+ */
2915
+ _outputHelpIfRequested(args) {
2916
+ const helpOption = this._getHelpOption();
2917
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2918
+ this.outputHelp();
2919
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2920
+ }
2921
+ }
2922
+ };
2923
+ /**
2924
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2925
+ *
2926
+ * @param {string[]} args - array of arguments from node.execArgv
2927
+ * @returns {string[]}
2928
+ * @private
2929
+ */
2930
+ function incrementNodeInspectorPort(args) {
2931
+ return args.map((arg) => {
2932
+ if (!arg.startsWith("--inspect")) return arg;
2933
+ let debugOption;
2934
+ let debugHost = "127.0.0.1";
2935
+ let debugPort = "9229";
2936
+ let match;
2937
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
2938
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2939
+ debugOption = match[1];
2940
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
2941
+ else debugHost = match[3];
2942
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2943
+ debugOption = match[1];
2944
+ debugHost = match[3];
2945
+ debugPort = match[4];
2946
+ }
2947
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2948
+ return arg;
2949
+ });
2950
+ }
2951
+ /**
2952
+ * Exported for using from tests, not otherwise used outside this file.
2953
+ *
2954
+ * @returns {boolean | undefined}
2955
+ * @package
2956
+ */
2957
+ function useColor() {
2958
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
2959
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
2960
+ }
2961
+ new Command();
2962
+ //#endregion
2963
+ //#region src/core/version.ts
2964
+ let cached;
2965
+ /**
2966
+ * Locate our own package.json. Probes two depths because the file layout
2967
+ * differs between dev (src/core/*.ts via tsx/vitest) and the published
2968
+ * bundle (dist/*.mjs next to package.json). The first parseable hit wins —
2969
+ * at both locations the only package.json present is our own, and not
2970
+ * pinning the name keeps package renames from silently breaking this.
2971
+ */
2972
+ function readOwnPackage() {
2973
+ if (cached) return cached;
2974
+ for (const relative of ["../package.json", "../../package.json"]) try {
2975
+ const pkg = JSON.parse(readFileSync(new URL(relative, import.meta.url), "utf8"));
2976
+ if (typeof pkg.name === "string" && typeof pkg.version === "string") {
2977
+ cached = {
2978
+ name: pkg.name,
2979
+ version: pkg.version
2980
+ };
2981
+ return cached;
2982
+ }
2983
+ } catch {}
2984
+ cached = {
2985
+ name: "nomai",
2986
+ version: "0.0.0"
2987
+ };
2988
+ return cached;
2989
+ }
2990
+ function getNomaiVersion() {
2991
+ return readOwnPackage().version;
2992
+ }
2993
+ /** The published npm package name — used to render `npx <name> …` hints. */
2994
+ function getNomaiPackageName() {
2995
+ return readOwnPackage().name;
2996
+ }
2997
+ //#endregion
2998
+ //#region src/core/errors.ts
2999
+ /**
3000
+ * Raised when prompts are needed but the session is non-interactive
3001
+ * (piped stdin/stdout or an AI agent driving the CLI). Mapped to exit
3002
+ * code 2 so scripts can distinguish "needs flags" from real failures.
3003
+ */
3004
+ var NonInteractiveError = class extends Error {
3005
+ exitCode = 2;
3006
+ };
3007
+ //#endregion
3008
+ //#region src/wizard/install-wizard.ts
3009
+ /**
3010
+ * Resolve the install plan: which harnesses, which scope.
3011
+ *
3012
+ * Each question is asked only if flags don't already answer it. With --yes,
3013
+ * missing answers fall back to detection-based defaults. Non-interactive
3014
+ * sessions (CI, piped output, AI agents) must pass --yes — we never guess
3015
+ * silently and never hang on a prompt.
3016
+ */
3017
+ async function runInstallWizard(options) {
3018
+ const { ctx, report, flags, interactive } = options;
3019
+ for (const id of flags.harness) getHarness(id);
3020
+ const defaultHarnessIds = report.detectedIds.length > 0 ? report.detectedIds : listHarnesses().map((h) => h.id);
3021
+ const defaultScope = report.projectDetectedIds.length > 0 ? "project" : "global";
3022
+ if (!interactive || flags.yes) {
3023
+ if (!interactive && !flags.yes) throw new NonInteractiveError("Interactive prompts are unavailable (non-TTY or AI-agent session). Re-run with --yes, optionally with --harness <id> and --scope project|global.");
3024
+ return {
3025
+ harnessIds: flags.harness.length > 0 ? flags.harness : defaultHarnessIds,
3026
+ scope: flags.scope ?? defaultScope
3027
+ };
3028
+ }
3029
+ const p = await import("./dist-DQ6U1xGI.mjs");
3030
+ let harnessIds = flags.harness;
3031
+ if (harnessIds.length === 0) {
3032
+ const detected = new Set(report.detectedIds);
3033
+ const picked = await p.multiselect({
3034
+ message: "Which harnesses should Nomai be installed into?",
3035
+ options: listHarnesses().map((harness) => ({
3036
+ value: harness.id,
3037
+ label: harness.displayName,
3038
+ hint: detected.has(harness.id) ? "detected" : void 0
3039
+ })),
3040
+ initialValues: defaultHarnessIds,
3041
+ required: true
3042
+ });
3043
+ if (p.isCancel(picked)) return cancelInstall(p);
3044
+ harnessIds = picked;
3045
+ }
3046
+ let scope = flags.scope;
3047
+ if (!scope) {
3048
+ const picked = await p.select({
3049
+ message: "Install where?",
3050
+ options: [{
3051
+ value: "project",
3052
+ label: "This project",
3053
+ hint: ctx.projectDir
3054
+ }, {
3055
+ value: "global",
3056
+ label: "Your machine (global)",
3057
+ hint: ctx.homeDir
3058
+ }],
3059
+ initialValue: defaultScope
3060
+ });
3061
+ if (p.isCancel(picked)) return cancelInstall(p);
3062
+ scope = picked;
3063
+ }
3064
+ const targets = harnessIds.map((id) => getHarness(id)).map((harness) => `${harness.displayName} → ${harness.resolveInstallDir(scope, ctx)}`);
3065
+ p.note(targets.join("\n"), "Install plan");
3066
+ const confirmed = await p.confirm({ message: "Install Nomai?" });
3067
+ if (p.isCancel(confirmed) || !confirmed) return cancelInstall(p);
3068
+ return {
3069
+ harnessIds,
3070
+ scope
3071
+ };
3072
+ }
3073
+ function cancelInstall(p) {
3074
+ p.cancel("Install cancelled.");
3075
+ process.exit(0);
3076
+ }
3077
+ //#endregion
3078
+ //#region src/commands/shared.ts
3079
+ function makeResolveContext(dir) {
3080
+ return {
3081
+ projectDir: path.resolve(dir ?? process.cwd()),
3082
+ homeDir: os.homedir()
3083
+ };
3084
+ }
3085
+ /** Commander repeatable-option accumulator. */
3086
+ function collect(value, previous) {
3087
+ return [...previous, value];
3088
+ }
3089
+ function parseScope(value) {
3090
+ if (value === void 0) return void 0;
3091
+ if (value === "project" || value === "global") return value;
3092
+ throw new Error(`Invalid --scope "${value}". Use "project" or "global".`);
3093
+ }
3094
+ /**
3095
+ * Prompts are only shown on a real TTY that is not driven by an AI agent
3096
+ * (Claude Code, Cursor, Codex, ... — detected via @vercel/detect-agent).
3097
+ */
3098
+ async function isInteractive() {
3099
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
3100
+ try {
3101
+ const { determineAgent } = await import("./dist-DSXfsMP5.mjs").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
3102
+ return !(await determineAgent()).isAgent;
3103
+ } catch {
3104
+ return true;
3105
+ }
3106
+ }
3107
+ function addTargetOptions(command) {
3108
+ return command.option("-H, --harness <id>", "target harness id (repeatable)", collect, []).option("-s, --scope <scope>", "target scope: \"project\" or \"global\"").option("-C, --dir <path>", "project directory (default: current directory)");
3109
+ }
3110
+ /** Every harness × scope carrying a Nomai manifest, optionally narrowed by flags. */
3111
+ async function findInstalledTargets(ctx, nomaiVersion, filter) {
3112
+ const adapters = filter.harness.length > 0 ? listHarnesses().filter((adapter) => filter.harness.includes(adapter.id)) : listHarnesses();
3113
+ const scopes = filter.scope ? [filter.scope] : ["project", "global"];
3114
+ const targets = [];
3115
+ for (const adapter of adapters) for (const scope of scopes) {
3116
+ const status = await adapter.status({
3117
+ ...ctx,
3118
+ scope,
3119
+ nomaiVersion,
3120
+ dryRun: false,
3121
+ force: false
3122
+ });
3123
+ if (status.installed) targets.push({
3124
+ adapter,
3125
+ scope,
3126
+ status
3127
+ });
3128
+ }
3129
+ return targets;
3130
+ }
3131
+ //#endregion
3132
+ //#region src/commands/install.ts
3133
+ function registerInstall(program) {
3134
+ addTargetOptions(program.command("install")).description("Install Nomai into your AI coding harnesses (interactive wizard)").option("-y, --yes", "accept defaults and skip prompts", false).option("--source <src>", "payload source: local path or GitHub owner/repo[#ref]").option("--dry-run", "print planned changes without writing anything", false).option("--force", "reinstall even if current; overwrite/remove user-modified files", false).action(async (options) => {
3135
+ await runInstall(options);
3136
+ });
3137
+ }
3138
+ async function runInstall(options) {
3139
+ const ctx = makeResolveContext(options.dir);
3140
+ const scope = parseScope(options.scope);
3141
+ const nomaiVersion = getNomaiVersion();
3142
+ const interactive = await isInteractive();
3143
+ const p = interactive ? await import("./dist-DQ6U1xGI.mjs") : void 0;
3144
+ p?.intro(`nomai v${nomaiVersion}`);
3145
+ const plan = await runInstallWizard({
3146
+ ctx,
3147
+ report: await detectHarnesses(ctx),
3148
+ flags: {
3149
+ harness: options.harness,
3150
+ scope,
3151
+ yes: options.yes
3152
+ },
3153
+ interactive
3154
+ });
3155
+ const downloadSpinner = p?.spinner();
3156
+ downloadSpinner?.start("Fetching Nomai payload…");
3157
+ let payload;
3158
+ try {
3159
+ payload = await resolvePayloadSource(options.source);
3160
+ downloadSpinner?.stop(`Payload ready (${payload.description})`);
3161
+ } catch (error) {
3162
+ downloadSpinner?.stop("Could not fetch the Nomai payload.");
3163
+ throw error;
3164
+ }
3165
+ try {
3166
+ for (const harnessId of plan.harnessIds) {
3167
+ const adapter = getHarness(harnessId);
3168
+ const spinner = p?.spinner();
3169
+ spinner?.start(`Installing for ${adapter.displayName}…`);
3170
+ const result = await adapter.install({
3171
+ ...ctx,
3172
+ scope: plan.scope,
3173
+ payload,
3174
+ nomaiVersion,
3175
+ dryRun: options.dryRun,
3176
+ force: options.force
3177
+ });
3178
+ const verb = options.dryRun ? "would write" : "wrote";
3179
+ const summary = result.skipped ? `${adapter.displayName}: already up to date (${result.installDir})` : `${adapter.displayName}: ${verb} ${result.filesWritten.length} file(s) → ${result.installDir}`;
3180
+ spinner?.stop(summary);
3181
+ if (!p) console.log(summary);
3182
+ if (result.filesRemoved.length > 0) {
3183
+ const orphanLine = ` ${options.dryRun ? "would remove" : "removed"} ${result.filesRemoved.length} orphaned file(s)`;
3184
+ if (p) p.log.info(orphanLine.trim());
3185
+ else console.log(orphanLine);
3186
+ }
3187
+ }
3188
+ const done = options.dryRun ? "Dry run complete — nothing was written." : `Nomai installed. Run \`npx ${getNomaiPackageName()} status\` anytime.`;
3189
+ if (p) p.outro(done);
3190
+ else console.log(done);
3191
+ } finally {
3192
+ await payload.dispose();
3193
+ }
3194
+ }
3195
+ //#endregion
3196
+ //#region src/commands/status.ts
3197
+ function registerStatus(program) {
3198
+ addTargetOptions(program.command("status")).description("Show Nomai install state per harness and scope (never prompts)").option("--json", "machine-readable output", false).action(async (options) => {
3199
+ await runStatus(options);
3200
+ });
3201
+ }
3202
+ async function runStatus(options) {
3203
+ const ctx = makeResolveContext(options.dir);
3204
+ const scopeFilter = parseScope(options.scope);
3205
+ const nomaiVersion = getNomaiVersion();
3206
+ const adapters = options.harness.length > 0 ? listHarnesses().filter((adapter) => options.harness.includes(adapter.id)) : listHarnesses();
3207
+ const scopes = scopeFilter ? [scopeFilter] : ["project", "global"];
3208
+ const rows = [];
3209
+ for (const adapter of adapters) for (const scope of scopes) rows.push(await adapter.status({
3210
+ ...ctx,
3211
+ scope,
3212
+ nomaiVersion,
3213
+ dryRun: false,
3214
+ force: false
3215
+ }));
3216
+ if (options.json) {
3217
+ console.log(JSON.stringify({
3218
+ nomaiVersion,
3219
+ statuses: rows
3220
+ }, null, 2));
3221
+ return;
3222
+ }
3223
+ for (const adapter of adapters) {
3224
+ console.log(`${adapter.displayName} (${adapter.id})`);
3225
+ for (const row of rows.filter((r) => r.harnessId === adapter.id)) console.log(` ${row.scope.padEnd(7)} ${describe(row)} ${row.installDir}`);
3226
+ }
3227
+ }
3228
+ function describe(row) {
3229
+ const harness = row.detected ? "harness detected" : "harness not detected";
3230
+ if (!row.installed) return `${harness}, nomai not installed`.padEnd(48);
3231
+ const drift = row.modifiedFiles.length > 0 || row.missingFiles.length > 0 ? ` (${[row.modifiedFiles.length > 0 ? `${row.modifiedFiles.length} modified` : "", row.missingFiles.length > 0 ? `${row.missingFiles.length} missing` : ""].filter(Boolean).join(", ")})` : "";
3232
+ return `${harness}, nomai v${row.installedVersion}${drift}`.padEnd(48);
3233
+ }
3234
+ //#endregion
3235
+ //#region src/commands/uninstall.ts
3236
+ function registerUninstall(program) {
3237
+ addTargetOptions(program.command("uninstall")).description("Remove Nomai from your harnesses (only files Nomai installed)").option("-y, --yes", "skip the confirmation prompt", false).option("--dry-run", "print what would be removed without removing anything", false).option("--force", "also remove files you modified after install", false).action(async (options) => {
3238
+ await runUninstall(options);
3239
+ });
3240
+ }
3241
+ async function runUninstall(options) {
3242
+ const ctx = makeResolveContext(options.dir);
3243
+ const scope = parseScope(options.scope);
3244
+ const nomaiVersion = getNomaiVersion();
3245
+ const interactive = await isInteractive();
3246
+ const targets = await findInstalledTargets(ctx, nomaiVersion, {
3247
+ harness: options.harness,
3248
+ scope
3249
+ });
3250
+ if (targets.length === 0) {
3251
+ console.log("Nomai is not installed at any matching target — nothing to do.");
3252
+ return;
3253
+ }
3254
+ const p = interactive ? await import("./dist-DQ6U1xGI.mjs") : void 0;
3255
+ if (!options.yes && !options.dryRun) {
3256
+ if (!p) throw new NonInteractiveError("Confirmation prompt unavailable (non-TTY or AI-agent session). Re-run with --yes.");
3257
+ p.intro(`nomai v${nomaiVersion}`);
3258
+ p.note(targets.map((target) => `${target.adapter.displayName} (${target.scope}) → ${target.status.installDir} [${target.status.modifiedFiles.length > 0 ? `${target.status.modifiedFiles.length} modified, ` : ""}${target.status.installedVersion ?? "?"}]`).join("\n"), "Will uninstall");
3259
+ const confirmed = await p.confirm({ message: "Remove Nomai from these targets?" });
3260
+ if (p.isCancel(confirmed) || !confirmed) {
3261
+ p.cancel("Uninstall cancelled.");
3262
+ process.exit(0);
3263
+ }
3264
+ }
3265
+ for (const target of targets) {
3266
+ const result = await target.adapter.uninstall({
3267
+ ...ctx,
3268
+ scope: target.scope,
3269
+ nomaiVersion,
3270
+ dryRun: options.dryRun,
3271
+ force: options.force
3272
+ });
3273
+ const verb = options.dryRun ? "would remove" : "removed";
3274
+ const line = `${target.adapter.displayName} (${target.scope}): ${verb} ${result.filesRemoved.length} file(s) from ${result.installDir}`;
3275
+ if (p) p.log.success(line);
3276
+ else console.log(line);
3277
+ if (result.filesKept.length > 0) {
3278
+ const keptLine = `kept ${result.filesKept.length} user-modified file(s): ${result.filesKept.join(", ")} (use --force to remove)`;
3279
+ if (p) p.log.warn(keptLine);
3280
+ else console.log(` ${keptLine}`);
3281
+ }
3282
+ }
3283
+ const done = options.dryRun ? "Dry run complete — nothing was removed." : "Nomai uninstalled.";
3284
+ if (p) p.outro(done);
3285
+ else console.log(done);
3286
+ }
3287
+ //#endregion
3288
+ //#region src/commands/update.ts
3289
+ function registerUpdate(program) {
3290
+ addTargetOptions(program.command("update")).description("Update existing Nomai installs to the latest payload").option("--source <src>", "payload source: local path or GitHub owner/repo[#ref]").option("--dry-run", "print planned changes without writing anything", false).option("--force", "rewrite even if current; overwrite/remove user-modified files", false).action(async (options) => {
3291
+ await runUpdate(options);
3292
+ });
3293
+ }
3294
+ async function runUpdate(options) {
3295
+ const ctx = makeResolveContext(options.dir);
3296
+ const scope = parseScope(options.scope);
3297
+ const nomaiVersion = getNomaiVersion();
3298
+ const p = await isInteractive() ? await import("./dist-DQ6U1xGI.mjs") : void 0;
3299
+ const targets = await findInstalledTargets(ctx, nomaiVersion, {
3300
+ harness: options.harness,
3301
+ scope
3302
+ });
3303
+ if (targets.length === 0) {
3304
+ console.log(`Nomai is not installed at any matching target. Run \`npx ${getNomaiPackageName()} install\` first.`);
3305
+ return;
3306
+ }
3307
+ p?.intro(`nomai v${nomaiVersion}`);
3308
+ const downloadSpinner = p?.spinner();
3309
+ downloadSpinner?.start("Fetching Nomai payload…");
3310
+ let payload;
3311
+ try {
3312
+ payload = await resolvePayloadSource(options.source);
3313
+ downloadSpinner?.stop(`Payload ready (${payload.description})`);
3314
+ } catch (error) {
3315
+ downloadSpinner?.stop("Could not fetch the Nomai payload.");
3316
+ throw error;
3317
+ }
3318
+ try {
3319
+ for (const target of targets) {
3320
+ const result = await target.adapter.install({
3321
+ ...ctx,
3322
+ scope: target.scope,
3323
+ payload,
3324
+ nomaiVersion,
3325
+ dryRun: options.dryRun,
3326
+ force: options.force
3327
+ });
3328
+ const line = result.skipped ? `${target.adapter.displayName} (${target.scope}): already up to date` : `${target.adapter.displayName} (${target.scope}): ${options.dryRun ? "would update" : "updated"} ${result.filesWritten.length} file(s)` + (result.filesRemoved.length > 0 ? `, ${options.dryRun ? "would remove" : "removed"} ${result.filesRemoved.length} orphaned` : "");
3329
+ if (p) p.log.success(line);
3330
+ else console.log(line);
3331
+ }
3332
+ const done = options.dryRun ? "Dry run complete — nothing was written." : "Update complete.";
3333
+ if (p) p.outro(done);
3334
+ else console.log(done);
3335
+ } finally {
3336
+ await payload.dispose();
3337
+ }
3338
+ }
3339
+ //#endregion
3340
+ //#region src/cli.ts
3341
+ function buildProgram() {
3342
+ const program = new Command();
3343
+ program.name("nomai").description("Install Nomai skills, hooks, and commands into AI coding harnesses").version(getNomaiVersion(), "-v, --version");
3344
+ registerInstall(program);
3345
+ registerUpdate(program);
3346
+ registerStatus(program);
3347
+ registerUninstall(program);
3348
+ return program;
3349
+ }
3350
+ async function main() {
3351
+ try {
3352
+ await buildProgram().parseAsync(process.argv);
3353
+ } catch (error) {
3354
+ console.error(error instanceof Error ? error.message : String(error));
3355
+ process.exit(error instanceof NonInteractiveError ? error.exitCode : 1);
3356
+ }
3357
+ }
3358
+ if ((() => {
3359
+ if (!process.argv[1]) return void 0;
3360
+ try {
3361
+ return pathToFileURL(realpathSync(process.argv[1])).href;
3362
+ } catch {
3363
+ return;
3364
+ }
3365
+ })() === import.meta.url) await main();
3366
+ //#endregion
3367
+ export { buildProgram };