@v1nvn/md 0.43.0 → 0.45.0

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