@v1nvn/zai 0.35.1 → 0.36.1

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