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