@v1nvn/md 0.35.1 → 0.36.1

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