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