@mistweaverco/kulala-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs ADDED
@@ -0,0 +1,4095 @@
1
+ #!/usr/bin/env node
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ //#endregion
25
+ let node_events = require("node:events");
26
+ let node_child_process = require("node:child_process");
27
+ node_child_process = __toESM(node_child_process, 1);
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path, 1);
30
+ let node_fs = require("node:fs");
31
+ node_fs = __toESM(node_fs, 1);
32
+ let node_process = require("node:process");
33
+ node_process = __toESM(node_process, 1);
34
+ let node_util = require("node:util");
35
+ let node_os = require("node:os");
36
+ node_os = __toESM(node_os, 1);
37
+ let node_tty = require("node:tty");
38
+ node_tty = __toESM(node_tty, 1);
39
+ let fs = require("fs");
40
+ fs = __toESM(fs, 1);
41
+ let path = require("path");
42
+ path = __toESM(path, 1);
43
+ let stream_promises = require("stream/promises");
44
+ var package_default = {
45
+ name: "@mistweaverco/kulala-cli",
46
+ version: "0.1.0",
47
+ repository: {
48
+ "type": "git",
49
+ "url": "https://github.com/mistweaverco/kulala-cli"
50
+ },
51
+ bin: { "kulala": "dist/cli.cjs" },
52
+ files: ["dist/cli.cjs", "dist/install-backend.cjs"],
53
+ type: "module",
54
+ publishConfig: { "access": "public" },
55
+ scripts: {
56
+ "build": "tsx ./scripts/build.ts",
57
+ "lint": "vp lint",
58
+ "prepare": "vp config && tsx ./scripts/build.ts || true",
59
+ "postinstall": "node dist/install-backend.cjs || true"
60
+ },
61
+ devDependencies: {
62
+ "@types/node": "25.9.1",
63
+ "chalk": "5.6.2",
64
+ "commander": "15.0.0",
65
+ "eslint-plugin-prettier": "5.5.6",
66
+ "globals": "17.6.0",
67
+ "picocolors": "1.1.1",
68
+ "prettier": "3.8.4",
69
+ "tsx": "4.22.4",
70
+ "typescript": "5.9.3",
71
+ "vite-plus": "catalog:"
72
+ },
73
+ packageManager: "pnpm@11.5.2"
74
+ };
75
+ //#endregion
76
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
77
+ /**
78
+ * CommanderError class
79
+ */
80
+ var CommanderError = class extends Error {
81
+ /**
82
+ * Constructs the CommanderError class
83
+ * @param {number} exitCode suggested exit code which could be used with process.exit
84
+ * @param {string} code an id string representing the error
85
+ * @param {string} message human-readable description of the error
86
+ */
87
+ constructor(exitCode, code, message) {
88
+ super(message);
89
+ Error.captureStackTrace(this, this.constructor);
90
+ this.name = this.constructor.name;
91
+ this.code = code;
92
+ this.exitCode = exitCode;
93
+ this.nestedError = void 0;
94
+ }
95
+ };
96
+ /**
97
+ * InvalidArgumentError class
98
+ */
99
+ var InvalidArgumentError = class extends CommanderError {
100
+ /**
101
+ * Constructs the InvalidArgumentError class
102
+ * @param {string} [message] explanation of why argument is invalid
103
+ */
104
+ constructor(message) {
105
+ super(1, "commander.invalidArgument", message);
106
+ Error.captureStackTrace(this, this.constructor);
107
+ this.name = this.constructor.name;
108
+ }
109
+ };
110
+ //#endregion
111
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
112
+ var Argument = class {
113
+ /**
114
+ * Initialize a new command argument with the given name and description.
115
+ * The default is that the argument is required, and you can explicitly
116
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
117
+ *
118
+ * @param {string} name
119
+ * @param {string} [description]
120
+ */
121
+ constructor(name, description) {
122
+ this.description = description || "";
123
+ this.variadic = false;
124
+ this.parseArg = void 0;
125
+ this.defaultValue = void 0;
126
+ this.defaultValueDescription = void 0;
127
+ this.argChoices = void 0;
128
+ switch (name[0]) {
129
+ case "<":
130
+ this.required = true;
131
+ this._name = name.slice(1, -1);
132
+ break;
133
+ case "[":
134
+ this.required = false;
135
+ this._name = name.slice(1, -1);
136
+ break;
137
+ default:
138
+ this.required = true;
139
+ this._name = name;
140
+ break;
141
+ }
142
+ if (this._name.endsWith("...")) {
143
+ this.variadic = true;
144
+ this._name = this._name.slice(0, -3);
145
+ }
146
+ }
147
+ /**
148
+ * Return argument name.
149
+ *
150
+ * @return {string}
151
+ */
152
+ name() {
153
+ return this._name;
154
+ }
155
+ /**
156
+ * @package
157
+ */
158
+ _collectValue(value, previous) {
159
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
160
+ previous.push(value);
161
+ return previous;
162
+ }
163
+ /**
164
+ * Set the default value, and optionally supply the description to be displayed in the help.
165
+ *
166
+ * @param {*} value
167
+ * @param {string} [description]
168
+ * @return {Argument}
169
+ */
170
+ default(value, description) {
171
+ this.defaultValue = value;
172
+ this.defaultValueDescription = description;
173
+ return this;
174
+ }
175
+ /**
176
+ * Set the custom handler for processing CLI command arguments into argument values.
177
+ *
178
+ * @param {Function} [fn]
179
+ * @return {Argument}
180
+ */
181
+ argParser(fn) {
182
+ this.parseArg = fn;
183
+ return this;
184
+ }
185
+ /**
186
+ * Only allow argument value to be one of choices.
187
+ *
188
+ * @param {string[]} values
189
+ * @return {Argument}
190
+ */
191
+ choices(values) {
192
+ this.argChoices = values.slice();
193
+ this.parseArg = (arg, previous) => {
194
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
195
+ if (this.variadic) return this._collectValue(arg, previous);
196
+ return arg;
197
+ };
198
+ return this;
199
+ }
200
+ /**
201
+ * Make argument required.
202
+ *
203
+ * @returns {Argument}
204
+ */
205
+ argRequired() {
206
+ this.required = true;
207
+ return this;
208
+ }
209
+ /**
210
+ * Make argument optional.
211
+ *
212
+ * @returns {Argument}
213
+ */
214
+ argOptional() {
215
+ this.required = false;
216
+ return this;
217
+ }
218
+ };
219
+ /**
220
+ * Takes an argument and returns its human readable equivalent for help usage.
221
+ *
222
+ * @param {Argument} arg
223
+ * @return {string}
224
+ * @private
225
+ */
226
+ function humanReadableArgName(arg) {
227
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
228
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
229
+ }
230
+ //#endregion
231
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
232
+ /**
233
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
234
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
235
+ * @typedef { import("./argument.js").Argument } Argument
236
+ * @typedef { import("./command.js").Command } Command
237
+ * @typedef { import("./option.js").Option } Option
238
+ */
239
+ var Help = class {
240
+ constructor() {
241
+ this.helpWidth = void 0;
242
+ this.minWidthToWrap = 40;
243
+ this.sortSubcommands = false;
244
+ this.sortOptions = false;
245
+ this.showGlobalOptions = false;
246
+ }
247
+ /**
248
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
249
+ * and just before calling `formatHelp()`.
250
+ *
251
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
252
+ *
253
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
254
+ */
255
+ prepareContext(contextOptions) {
256
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
257
+ }
258
+ /**
259
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
260
+ *
261
+ * @param {Command} cmd
262
+ * @returns {Command[]}
263
+ */
264
+ visibleCommands(cmd) {
265
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
266
+ const helpCommand = cmd._getHelpCommand();
267
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
268
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
269
+ return a.name().localeCompare(b.name());
270
+ });
271
+ return visibleCommands;
272
+ }
273
+ /**
274
+ * Compare options for sort.
275
+ *
276
+ * @param {Option} a
277
+ * @param {Option} b
278
+ * @returns {number}
279
+ */
280
+ compareOptions(a, b) {
281
+ const getSortKey = (option) => {
282
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
283
+ };
284
+ return getSortKey(a).localeCompare(getSortKey(b));
285
+ }
286
+ /**
287
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
288
+ *
289
+ * @param {Command} cmd
290
+ * @returns {Option[]}
291
+ */
292
+ visibleOptions(cmd) {
293
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
294
+ const helpOption = cmd._getHelpOption();
295
+ if (helpOption && !helpOption.hidden) {
296
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
297
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
298
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
299
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
300
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
301
+ }
302
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
303
+ return visibleOptions;
304
+ }
305
+ /**
306
+ * Get an array of the visible global options. (Not including help.)
307
+ *
308
+ * @param {Command} cmd
309
+ * @returns {Option[]}
310
+ */
311
+ visibleGlobalOptions(cmd) {
312
+ if (!this.showGlobalOptions) return [];
313
+ const globalOptions = [];
314
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
315
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
316
+ globalOptions.push(...visibleOptions);
317
+ }
318
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
319
+ return globalOptions;
320
+ }
321
+ /**
322
+ * Get an array of the arguments if any have a description.
323
+ *
324
+ * @param {Command} cmd
325
+ * @returns {Argument[]}
326
+ */
327
+ visibleArguments(cmd) {
328
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
329
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
330
+ });
331
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
332
+ return [];
333
+ }
334
+ /**
335
+ * Get the command term to show in the list of subcommands.
336
+ *
337
+ * @param {Command} cmd
338
+ * @returns {string}
339
+ */
340
+ subcommandTerm(cmd) {
341
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
342
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
343
+ }
344
+ /**
345
+ * Get the option term to show in the list of options.
346
+ *
347
+ * @param {Option} option
348
+ * @returns {string}
349
+ */
350
+ optionTerm(option) {
351
+ return option.flags;
352
+ }
353
+ /**
354
+ * Get the argument term to show in the list of arguments.
355
+ *
356
+ * @param {Argument} argument
357
+ * @returns {string}
358
+ */
359
+ argumentTerm(argument) {
360
+ return argument.name();
361
+ }
362
+ /**
363
+ * Get the longest command term length.
364
+ *
365
+ * @param {Command} cmd
366
+ * @param {Help} helper
367
+ * @returns {number}
368
+ */
369
+ longestSubcommandTermLength(cmd, helper) {
370
+ return helper.visibleCommands(cmd).reduce((max, command) => {
371
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
372
+ }, 0);
373
+ }
374
+ /**
375
+ * Get the longest option term length.
376
+ *
377
+ * @param {Command} cmd
378
+ * @param {Help} helper
379
+ * @returns {number}
380
+ */
381
+ longestOptionTermLength(cmd, helper) {
382
+ return helper.visibleOptions(cmd).reduce((max, option) => {
383
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
384
+ }, 0);
385
+ }
386
+ /**
387
+ * Get the longest global option term length.
388
+ *
389
+ * @param {Command} cmd
390
+ * @param {Help} helper
391
+ * @returns {number}
392
+ */
393
+ longestGlobalOptionTermLength(cmd, helper) {
394
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
395
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
396
+ }, 0);
397
+ }
398
+ /**
399
+ * Get the longest argument term length.
400
+ *
401
+ * @param {Command} cmd
402
+ * @param {Help} helper
403
+ * @returns {number}
404
+ */
405
+ longestArgumentTermLength(cmd, helper) {
406
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
407
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
408
+ }, 0);
409
+ }
410
+ /**
411
+ * Get the command usage to be displayed at the top of the built-in help.
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ commandUsage(cmd) {
417
+ let cmdName = cmd._name;
418
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
419
+ let ancestorCmdNames = "";
420
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
421
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
422
+ }
423
+ /**
424
+ * Get the description for the command.
425
+ *
426
+ * @param {Command} cmd
427
+ * @returns {string}
428
+ */
429
+ commandDescription(cmd) {
430
+ return cmd.description();
431
+ }
432
+ /**
433
+ * Get the subcommand summary to show in the list of subcommands.
434
+ * (Fallback to description for backwards compatibility.)
435
+ *
436
+ * @param {Command} cmd
437
+ * @returns {string}
438
+ */
439
+ subcommandDescription(cmd) {
440
+ return cmd.summary() || cmd.description();
441
+ }
442
+ /**
443
+ * Get the option description to show in the list of options.
444
+ *
445
+ * @param {Option} option
446
+ * @return {string}
447
+ */
448
+ optionDescription(option) {
449
+ const extraInfo = [];
450
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
451
+ if (option.defaultValue !== void 0) {
452
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
453
+ }
454
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
455
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
456
+ if (extraInfo.length > 0) {
457
+ const extraDescription = `(${extraInfo.join(", ")})`;
458
+ if (option.description) return `${option.description} ${extraDescription}`;
459
+ return extraDescription;
460
+ }
461
+ return option.description;
462
+ }
463
+ /**
464
+ * Get the argument description to show in the list of arguments.
465
+ *
466
+ * @param {Argument} argument
467
+ * @return {string}
468
+ */
469
+ argumentDescription(argument) {
470
+ const extraInfo = [];
471
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
472
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
473
+ if (extraInfo.length > 0) {
474
+ const extraDescription = `(${extraInfo.join(", ")})`;
475
+ if (argument.description) return `${argument.description} ${extraDescription}`;
476
+ return extraDescription;
477
+ }
478
+ return argument.description;
479
+ }
480
+ /**
481
+ * Format a list of items, given a heading and an array of formatted items.
482
+ *
483
+ * @param {string} heading
484
+ * @param {string[]} items
485
+ * @param {Help} helper
486
+ * @returns string[]
487
+ */
488
+ formatItemList(heading, items, helper) {
489
+ if (items.length === 0) return [];
490
+ return [
491
+ helper.styleTitle(heading),
492
+ ...items,
493
+ ""
494
+ ];
495
+ }
496
+ /**
497
+ * Group items by their help group heading.
498
+ *
499
+ * @param {Command[] | Option[]} unsortedItems
500
+ * @param {Command[] | Option[]} visibleItems
501
+ * @param {Function} getGroup
502
+ * @returns {Map<string, Command[] | Option[]>}
503
+ */
504
+ groupItems(unsortedItems, visibleItems, getGroup) {
505
+ const result = /* @__PURE__ */ new Map();
506
+ unsortedItems.forEach((item) => {
507
+ const group = getGroup(item);
508
+ if (!result.has(group)) result.set(group, []);
509
+ });
510
+ visibleItems.forEach((item) => {
511
+ const group = getGroup(item);
512
+ if (!result.has(group)) result.set(group, []);
513
+ result.get(group).push(item);
514
+ });
515
+ return result;
516
+ }
517
+ /**
518
+ * Generate the built-in help text.
519
+ *
520
+ * @param {Command} cmd
521
+ * @param {Help} helper
522
+ * @returns {string}
523
+ */
524
+ formatHelp(cmd, helper) {
525
+ const termWidth = helper.padWidth(cmd, helper);
526
+ const helpWidth = helper.helpWidth ?? 80;
527
+ function callFormatItem(term, description) {
528
+ return helper.formatItem(term, termWidth, description, helper);
529
+ }
530
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
531
+ const commandDescription = helper.commandDescription(cmd);
532
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
533
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
534
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
535
+ });
536
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
537
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
538
+ const optionList = options.map((option) => {
539
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
540
+ });
541
+ output = output.concat(this.formatItemList(group, optionList, helper));
542
+ });
543
+ if (helper.showGlobalOptions) {
544
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
545
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
546
+ });
547
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
548
+ }
549
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
550
+ const commandList = commands.map((sub) => {
551
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
552
+ });
553
+ output = output.concat(this.formatItemList(group, commandList, helper));
554
+ });
555
+ return output.join("\n");
556
+ }
557
+ /**
558
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
559
+ *
560
+ * @param {string} str
561
+ * @returns {number}
562
+ */
563
+ displayWidth(str) {
564
+ return (0, node_util.stripVTControlCharacters)(str).length;
565
+ }
566
+ /**
567
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
568
+ *
569
+ * @param {string} str
570
+ * @returns {string}
571
+ */
572
+ styleTitle(str) {
573
+ return str;
574
+ }
575
+ styleUsage(str) {
576
+ return str.split(" ").map((word) => {
577
+ if (word === "[options]") return this.styleOptionText(word);
578
+ if (word === "[command]") return this.styleSubcommandText(word);
579
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
580
+ return this.styleCommandText(word);
581
+ }).join(" ");
582
+ }
583
+ styleCommandDescription(str) {
584
+ return this.styleDescriptionText(str);
585
+ }
586
+ styleOptionDescription(str) {
587
+ return this.styleDescriptionText(str);
588
+ }
589
+ styleSubcommandDescription(str) {
590
+ return this.styleDescriptionText(str);
591
+ }
592
+ styleArgumentDescription(str) {
593
+ return this.styleDescriptionText(str);
594
+ }
595
+ styleDescriptionText(str) {
596
+ return str;
597
+ }
598
+ styleOptionTerm(str) {
599
+ return this.styleOptionText(str);
600
+ }
601
+ styleSubcommandTerm(str) {
602
+ return str.split(" ").map((word) => {
603
+ if (word === "[options]") return this.styleOptionText(word);
604
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
605
+ return this.styleSubcommandText(word);
606
+ }).join(" ");
607
+ }
608
+ styleArgumentTerm(str) {
609
+ return this.styleArgumentText(str);
610
+ }
611
+ styleOptionText(str) {
612
+ return str;
613
+ }
614
+ styleArgumentText(str) {
615
+ return str;
616
+ }
617
+ styleSubcommandText(str) {
618
+ return str;
619
+ }
620
+ styleCommandText(str) {
621
+ return str;
622
+ }
623
+ /**
624
+ * Calculate the pad width from the maximum term length.
625
+ *
626
+ * @param {Command} cmd
627
+ * @param {Help} helper
628
+ * @returns {number}
629
+ */
630
+ padWidth(cmd, helper) {
631
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
632
+ }
633
+ /**
634
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
635
+ *
636
+ * @param {string} str
637
+ * @returns {boolean}
638
+ */
639
+ preformatted(str) {
640
+ return /\n[^\S\r\n]/.test(str);
641
+ }
642
+ /**
643
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
644
+ *
645
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
646
+ * TTT DDD DDDD
647
+ * DD DDD
648
+ *
649
+ * @param {string} term
650
+ * @param {number} termWidth
651
+ * @param {string} description
652
+ * @param {Help} helper
653
+ * @returns {string}
654
+ */
655
+ formatItem(term, termWidth, description, helper) {
656
+ const itemIndent = 2;
657
+ const itemIndentStr = " ".repeat(itemIndent);
658
+ if (!description) return itemIndentStr + term;
659
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
660
+ const spacerWidth = 2;
661
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
662
+ let formattedDescription;
663
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
664
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
665
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
666
+ }
667
+ /**
668
+ * Wrap a string at whitespace, preserving existing line breaks.
669
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
670
+ *
671
+ * @param {string} str
672
+ * @param {number} width
673
+ * @returns {string}
674
+ */
675
+ boxWrap(str, width) {
676
+ if (width < this.minWidthToWrap) return str;
677
+ const rawLines = str.split(/\r\n|\n/);
678
+ const chunkPattern = /[\s]*[^\s]+/g;
679
+ const wrappedLines = [];
680
+ rawLines.forEach((line) => {
681
+ const chunks = line.match(chunkPattern);
682
+ if (chunks === null) {
683
+ wrappedLines.push("");
684
+ return;
685
+ }
686
+ let sumChunks = [chunks.shift()];
687
+ let sumWidth = this.displayWidth(sumChunks[0]);
688
+ chunks.forEach((chunk) => {
689
+ const visibleWidth = this.displayWidth(chunk);
690
+ if (sumWidth + visibleWidth <= width) {
691
+ sumChunks.push(chunk);
692
+ sumWidth += visibleWidth;
693
+ return;
694
+ }
695
+ wrappedLines.push(sumChunks.join(""));
696
+ const nextChunk = chunk.trimStart();
697
+ sumChunks = [nextChunk];
698
+ sumWidth = this.displayWidth(nextChunk);
699
+ });
700
+ wrappedLines.push(sumChunks.join(""));
701
+ });
702
+ return wrappedLines.join("\n");
703
+ }
704
+ };
705
+ //#endregion
706
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
707
+ var Option = class {
708
+ /**
709
+ * Initialize a new `Option` with the given `flags` and `description`.
710
+ *
711
+ * @param {string} flags
712
+ * @param {string} [description]
713
+ */
714
+ constructor(flags, description) {
715
+ this.flags = flags;
716
+ this.description = description || "";
717
+ this.required = flags.includes("<");
718
+ this.optional = flags.includes("[");
719
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
720
+ this.mandatory = false;
721
+ const optionFlags = splitOptionFlags(flags);
722
+ this.short = optionFlags.shortFlag;
723
+ this.long = optionFlags.longFlag;
724
+ this.negate = false;
725
+ if (this.long) this.negate = this.long.startsWith("--no-");
726
+ this.defaultValue = void 0;
727
+ this.defaultValueDescription = void 0;
728
+ this.presetArg = void 0;
729
+ this.envVar = void 0;
730
+ this.parseArg = void 0;
731
+ this.hidden = false;
732
+ this.argChoices = void 0;
733
+ this.conflictsWith = [];
734
+ this.implied = void 0;
735
+ this.helpGroupHeading = void 0;
736
+ }
737
+ /**
738
+ * Set the default value, and optionally supply the description to be displayed in the help.
739
+ *
740
+ * @param {*} value
741
+ * @param {string} [description]
742
+ * @return {Option}
743
+ */
744
+ default(value, description) {
745
+ this.defaultValue = value;
746
+ this.defaultValueDescription = description;
747
+ return this;
748
+ }
749
+ /**
750
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
751
+ * The custom processing (parseArg) is called.
752
+ *
753
+ * @example
754
+ * new Option('--color').default('GREYSCALE').preset('RGB');
755
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
756
+ *
757
+ * @param {*} arg
758
+ * @return {Option}
759
+ */
760
+ preset(arg) {
761
+ this.presetArg = arg;
762
+ return this;
763
+ }
764
+ /**
765
+ * Add option name(s) that conflict with this option.
766
+ * An error will be displayed if conflicting options are found during parsing.
767
+ *
768
+ * @example
769
+ * new Option('--rgb').conflicts('cmyk');
770
+ * new Option('--js').conflicts(['ts', 'jsx']);
771
+ *
772
+ * @param {(string | string[])} names
773
+ * @return {Option}
774
+ */
775
+ conflicts(names) {
776
+ this.conflictsWith = this.conflictsWith.concat(names);
777
+ return this;
778
+ }
779
+ /**
780
+ * Specify implied option values for when this option is set and the implied options are not.
781
+ *
782
+ * The custom processing (parseArg) is not called on the implied values.
783
+ *
784
+ * @example
785
+ * program
786
+ * .addOption(new Option('--log', 'write logging information to file'))
787
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
788
+ *
789
+ * @param {object} impliedOptionValues
790
+ * @return {Option}
791
+ */
792
+ implies(impliedOptionValues) {
793
+ let newImplied = impliedOptionValues;
794
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
795
+ this.implied = Object.assign(this.implied || {}, newImplied);
796
+ return this;
797
+ }
798
+ /**
799
+ * Set environment variable to check for option value.
800
+ *
801
+ * An environment variable is only used if when processed the current option value is
802
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
803
+ *
804
+ * @param {string} name
805
+ * @return {Option}
806
+ */
807
+ env(name) {
808
+ this.envVar = name;
809
+ return this;
810
+ }
811
+ /**
812
+ * Set the custom handler for processing CLI option arguments into option values.
813
+ *
814
+ * @param {Function} [fn]
815
+ * @return {Option}
816
+ */
817
+ argParser(fn) {
818
+ this.parseArg = fn;
819
+ return this;
820
+ }
821
+ /**
822
+ * Whether the option is mandatory and must have a value after parsing.
823
+ *
824
+ * @param {boolean} [mandatory=true]
825
+ * @return {Option}
826
+ */
827
+ makeOptionMandatory(mandatory = true) {
828
+ this.mandatory = !!mandatory;
829
+ return this;
830
+ }
831
+ /**
832
+ * Hide option in help.
833
+ *
834
+ * @param {boolean} [hide=true]
835
+ * @return {Option}
836
+ */
837
+ hideHelp(hide = true) {
838
+ this.hidden = !!hide;
839
+ return this;
840
+ }
841
+ /**
842
+ * @package
843
+ */
844
+ _collectValue(value, previous) {
845
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
846
+ previous.push(value);
847
+ return previous;
848
+ }
849
+ /**
850
+ * Only allow option value to be one of choices.
851
+ *
852
+ * @param {string[]} values
853
+ * @return {Option}
854
+ */
855
+ choices(values) {
856
+ this.argChoices = values.slice();
857
+ this.parseArg = (arg, previous) => {
858
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
859
+ if (this.variadic) return this._collectValue(arg, previous);
860
+ return arg;
861
+ };
862
+ return this;
863
+ }
864
+ /**
865
+ * Return option name.
866
+ *
867
+ * @return {string}
868
+ */
869
+ name() {
870
+ if (this.long) return this.long.replace(/^--/, "");
871
+ return this.short.replace(/^-/, "");
872
+ }
873
+ /**
874
+ * Return option name, in a camelcase format that can be used
875
+ * as an object attribute key.
876
+ *
877
+ * @return {string}
878
+ */
879
+ attributeName() {
880
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
881
+ return camelcase(this.name());
882
+ }
883
+ /**
884
+ * Set the help group heading.
885
+ *
886
+ * @param {string} heading
887
+ * @return {Option}
888
+ */
889
+ helpGroup(heading) {
890
+ this.helpGroupHeading = heading;
891
+ return this;
892
+ }
893
+ /**
894
+ * Check if `arg` matches the short or long flag.
895
+ *
896
+ * @param {string} arg
897
+ * @return {boolean}
898
+ * @package
899
+ */
900
+ is(arg) {
901
+ return this.short === arg || this.long === arg;
902
+ }
903
+ /**
904
+ * Return whether a boolean option.
905
+ *
906
+ * Options are one of boolean, negated, required argument, or optional argument.
907
+ *
908
+ * @return {boolean}
909
+ * @package
910
+ */
911
+ isBoolean() {
912
+ return !this.required && !this.optional && !this.negate;
913
+ }
914
+ };
915
+ /**
916
+ * This class is to make it easier to work with dual options, without changing the existing
917
+ * implementation. We support separate dual options for separate positive and negative options,
918
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
919
+ * use cases, but is tricky for others where we want separate behaviours despite
920
+ * the single shared option value.
921
+ */
922
+ var DualOptions = class {
923
+ /**
924
+ * @param {Option[]} options
925
+ */
926
+ constructor(options) {
927
+ this.positiveOptions = /* @__PURE__ */ new Map();
928
+ this.negativeOptions = /* @__PURE__ */ new Map();
929
+ this.dualOptions = /* @__PURE__ */ new Set();
930
+ options.forEach((option) => {
931
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
932
+ else this.positiveOptions.set(option.attributeName(), option);
933
+ });
934
+ this.negativeOptions.forEach((value, key) => {
935
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
936
+ });
937
+ }
938
+ /**
939
+ * Did the value come from the option, and not from possible matching dual option?
940
+ *
941
+ * @param {*} value
942
+ * @param {Option} option
943
+ * @returns {boolean}
944
+ */
945
+ valueFromOption(value, option) {
946
+ const optionKey = option.attributeName();
947
+ if (!this.dualOptions.has(optionKey)) return true;
948
+ const preset = this.negativeOptions.get(optionKey).presetArg;
949
+ const negativeValue = preset !== void 0 ? preset : false;
950
+ return option.negate === (negativeValue === value);
951
+ }
952
+ };
953
+ /**
954
+ * Convert string from kebab-case to camelCase.
955
+ *
956
+ * @param {string} str
957
+ * @return {string}
958
+ * @private
959
+ */
960
+ function camelcase(str) {
961
+ return str.split("-").reduce((str, word) => {
962
+ return str + word[0].toUpperCase() + word.slice(1);
963
+ });
964
+ }
965
+ /**
966
+ * Split the short and long flag out of something like '-m,--mixed <value>'
967
+ *
968
+ * @private
969
+ */
970
+ function splitOptionFlags(flags) {
971
+ let shortFlag;
972
+ let longFlag;
973
+ const shortFlagExp = /^-[^-]$/;
974
+ const longFlagExp = /^--[^-]/;
975
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
976
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
977
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
978
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
979
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
980
+ shortFlag = longFlag;
981
+ longFlag = flagParts.shift();
982
+ }
983
+ if (flagParts[0].startsWith("-")) {
984
+ const unsupportedFlag = flagParts[0];
985
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
986
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
987
+ - a short flag is a single dash and a single character
988
+ - either use a single dash and a single character (for a short flag)
989
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
990
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
991
+ - too many short flags`);
992
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
993
+ - too many long flags`);
994
+ throw new Error(`${baseError}
995
+ - unrecognised flag format`);
996
+ }
997
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
998
+ return {
999
+ shortFlag,
1000
+ longFlag
1001
+ };
1002
+ }
1003
+ //#endregion
1004
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
1005
+ var maxDistance = 3;
1006
+ function editDistance(a, b) {
1007
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1008
+ const d = [];
1009
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1010
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1011
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1012
+ let cost;
1013
+ if (a[i - 1] === b[j - 1]) cost = 0;
1014
+ else cost = 1;
1015
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1016
+ 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);
1017
+ }
1018
+ return d[a.length][b.length];
1019
+ }
1020
+ /**
1021
+ * Find close matches, restricted to same number of edits.
1022
+ *
1023
+ * @param {string} word
1024
+ * @param {string[]} candidates
1025
+ * @returns {string}
1026
+ */
1027
+ function suggestSimilar(word, candidates) {
1028
+ if (!candidates || candidates.length === 0) return "";
1029
+ candidates = Array.from(new Set(candidates));
1030
+ const searchingOptions = word.startsWith("--");
1031
+ if (searchingOptions) {
1032
+ word = word.slice(2);
1033
+ candidates = candidates.map((candidate) => candidate.slice(2));
1034
+ }
1035
+ let similar = [];
1036
+ let bestDistance = maxDistance;
1037
+ const minSimilarity = .4;
1038
+ candidates.forEach((candidate) => {
1039
+ if (candidate.length <= 1) return;
1040
+ const distance = editDistance(word, candidate);
1041
+ const length = Math.max(word.length, candidate.length);
1042
+ if ((length - distance) / length > minSimilarity) {
1043
+ if (distance < bestDistance) {
1044
+ bestDistance = distance;
1045
+ similar = [candidate];
1046
+ } else if (distance === bestDistance) similar.push(candidate);
1047
+ }
1048
+ });
1049
+ similar.sort((a, b) => a.localeCompare(b));
1050
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1051
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1052
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1053
+ return "";
1054
+ }
1055
+ //#endregion
1056
+ //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
1057
+ var Command = class Command extends node_events.EventEmitter {
1058
+ /**
1059
+ * Initialize a new `Command`.
1060
+ *
1061
+ * @param {string} [name]
1062
+ */
1063
+ constructor(name) {
1064
+ super();
1065
+ /** @type {Command[]} */
1066
+ this.commands = [];
1067
+ /** @type {Option[]} */
1068
+ this.options = [];
1069
+ this.parent = null;
1070
+ this._allowUnknownOption = false;
1071
+ this._allowExcessArguments = false;
1072
+ /** @type {Argument[]} */
1073
+ this.registeredArguments = [];
1074
+ this._args = this.registeredArguments;
1075
+ /** @type {string[]} */
1076
+ this.args = [];
1077
+ this.rawArgs = [];
1078
+ this.processedArgs = [];
1079
+ this._scriptPath = null;
1080
+ this._name = name || "";
1081
+ this._optionValues = {};
1082
+ this._optionValueSources = {};
1083
+ this._storeOptionsAsProperties = false;
1084
+ this._actionHandler = null;
1085
+ this._executableHandler = false;
1086
+ this._executableFile = null;
1087
+ this._executableDir = null;
1088
+ this._defaultCommandName = null;
1089
+ this._exitCallback = null;
1090
+ this._aliases = [];
1091
+ this._combineFlagAndOptionalValue = true;
1092
+ this._description = "";
1093
+ this._summary = "";
1094
+ this._argsDescription = void 0;
1095
+ this._enablePositionalOptions = false;
1096
+ this._passThroughOptions = false;
1097
+ this._lifeCycleHooks = {};
1098
+ /** @type {(boolean | string)} */
1099
+ this._showHelpAfterError = false;
1100
+ this._showSuggestionAfterError = true;
1101
+ this._savedState = null;
1102
+ this._outputConfiguration = {
1103
+ writeOut: (str) => node_process.default.stdout.write(str),
1104
+ writeErr: (str) => node_process.default.stderr.write(str),
1105
+ outputError: (str, write) => write(str),
1106
+ getOutHelpWidth: () => node_process.default.stdout.isTTY ? node_process.default.stdout.columns : void 0,
1107
+ getErrHelpWidth: () => node_process.default.stderr.isTTY ? node_process.default.stderr.columns : void 0,
1108
+ getOutHasColors: () => useColor() ?? (node_process.default.stdout.isTTY && node_process.default.stdout.hasColors?.()),
1109
+ getErrHasColors: () => useColor() ?? (node_process.default.stderr.isTTY && node_process.default.stderr.hasColors?.()),
1110
+ stripColor: (str) => (0, node_util.stripVTControlCharacters)(str)
1111
+ };
1112
+ this._hidden = false;
1113
+ /** @type {(Option | null | undefined)} */
1114
+ this._helpOption = void 0;
1115
+ this._addImplicitHelpCommand = void 0;
1116
+ /** @type {Command} */
1117
+ this._helpCommand = void 0;
1118
+ this._helpConfiguration = {};
1119
+ /** @type {string | undefined} */
1120
+ this._helpGroupHeading = void 0;
1121
+ /** @type {string | undefined} */
1122
+ this._defaultCommandGroup = void 0;
1123
+ /** @type {string | undefined} */
1124
+ this._defaultOptionGroup = void 0;
1125
+ }
1126
+ /**
1127
+ * Copy settings that are useful to have in common across root command and subcommands.
1128
+ *
1129
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1130
+ *
1131
+ * @param {Command} sourceCommand
1132
+ * @return {Command} `this` command for chaining
1133
+ */
1134
+ copyInheritedSettings(sourceCommand) {
1135
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1136
+ this._helpOption = sourceCommand._helpOption;
1137
+ this._helpCommand = sourceCommand._helpCommand;
1138
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1139
+ this._exitCallback = sourceCommand._exitCallback;
1140
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1141
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1142
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1143
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1144
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1145
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ * @returns {Command[]}
1150
+ * @private
1151
+ */
1152
+ _getCommandAndAncestors() {
1153
+ const result = [];
1154
+ for (let command = this; command; command = command.parent) result.push(command);
1155
+ return result;
1156
+ }
1157
+ /**
1158
+ * Define a command.
1159
+ *
1160
+ * There are two styles of command: pay attention to where to put the description.
1161
+ *
1162
+ * @example
1163
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1164
+ * program
1165
+ * .command('clone <source> [destination]')
1166
+ * .description('clone a repository into a newly created directory')
1167
+ * .action((source, destination) => {
1168
+ * console.log('clone command called');
1169
+ * });
1170
+ *
1171
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1172
+ * program
1173
+ * .command('start <service>', 'start named service')
1174
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1175
+ *
1176
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1177
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1178
+ * @param {object} [execOpts] - configuration options (for executable)
1179
+ * @return {Command} returns new command for action handler, or `this` for executable command
1180
+ */
1181
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1182
+ let desc = actionOptsOrExecDesc;
1183
+ let opts = execOpts;
1184
+ if (typeof desc === "object" && desc !== null) {
1185
+ opts = desc;
1186
+ desc = null;
1187
+ }
1188
+ opts = opts || {};
1189
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1190
+ const cmd = this.createCommand(name);
1191
+ if (desc) {
1192
+ cmd.description(desc);
1193
+ cmd._executableHandler = true;
1194
+ }
1195
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1196
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1197
+ cmd._executableFile = opts.executableFile || null;
1198
+ if (args) cmd.arguments(args);
1199
+ this._registerCommand(cmd);
1200
+ cmd.parent = this;
1201
+ cmd.copyInheritedSettings(this);
1202
+ if (desc) return this;
1203
+ return cmd;
1204
+ }
1205
+ /**
1206
+ * Factory routine to create a new unattached command.
1207
+ *
1208
+ * See .command() for creating an attached subcommand, which uses this routine to
1209
+ * create the command. You can override createCommand to customise subcommands.
1210
+ *
1211
+ * @param {string} [name]
1212
+ * @return {Command} new command
1213
+ */
1214
+ createCommand(name) {
1215
+ return new Command(name);
1216
+ }
1217
+ /**
1218
+ * You can customise the help with a subclass of Help by overriding createHelp,
1219
+ * or by overriding Help properties using configureHelp().
1220
+ *
1221
+ * @return {Help}
1222
+ */
1223
+ createHelp() {
1224
+ return Object.assign(new Help(), this.configureHelp());
1225
+ }
1226
+ /**
1227
+ * You can customise the help by overriding Help properties using configureHelp(),
1228
+ * or with a subclass of Help by overriding createHelp().
1229
+ *
1230
+ * @param {object} [configuration] - configuration options
1231
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1232
+ */
1233
+ configureHelp(configuration) {
1234
+ if (configuration === void 0) return this._helpConfiguration;
1235
+ this._helpConfiguration = configuration;
1236
+ return this;
1237
+ }
1238
+ /**
1239
+ * The default output goes to stdout and stderr. You can customise this for special
1240
+ * applications. You can also customise the display of errors by overriding outputError.
1241
+ *
1242
+ * The configuration properties are all functions:
1243
+ *
1244
+ * // change how output being written, defaults to stdout and stderr
1245
+ * writeOut(str)
1246
+ * writeErr(str)
1247
+ * // change how output being written for errors, defaults to writeErr
1248
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1249
+ * // specify width for wrapping help
1250
+ * getOutHelpWidth()
1251
+ * getErrHelpWidth()
1252
+ * // color support, currently only used with Help
1253
+ * getOutHasColors()
1254
+ * getErrHasColors()
1255
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1256
+ *
1257
+ * @param {object} [configuration] - configuration options
1258
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1259
+ */
1260
+ configureOutput(configuration) {
1261
+ if (configuration === void 0) return this._outputConfiguration;
1262
+ this._outputConfiguration = {
1263
+ ...this._outputConfiguration,
1264
+ ...configuration
1265
+ };
1266
+ return this;
1267
+ }
1268
+ /**
1269
+ * Display the help or a custom message after an error occurs.
1270
+ *
1271
+ * @param {(boolean|string)} [displayHelp]
1272
+ * @return {Command} `this` command for chaining
1273
+ */
1274
+ showHelpAfterError(displayHelp = true) {
1275
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1276
+ this._showHelpAfterError = displayHelp;
1277
+ return this;
1278
+ }
1279
+ /**
1280
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1281
+ *
1282
+ * @param {boolean} [displaySuggestion]
1283
+ * @return {Command} `this` command for chaining
1284
+ */
1285
+ showSuggestionAfterError(displaySuggestion = true) {
1286
+ this._showSuggestionAfterError = !!displaySuggestion;
1287
+ return this;
1288
+ }
1289
+ /**
1290
+ * Add a prepared subcommand.
1291
+ *
1292
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1293
+ *
1294
+ * @param {Command} cmd - new subcommand
1295
+ * @param {object} [opts] - configuration options
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ addCommand(cmd, opts) {
1299
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1300
+ - specify the name in Command constructor or using .name()`);
1301
+ opts = opts || {};
1302
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1303
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1304
+ this._registerCommand(cmd);
1305
+ cmd.parent = this;
1306
+ cmd._checkForBrokenPassThrough();
1307
+ return this;
1308
+ }
1309
+ /**
1310
+ * Factory routine to create a new unattached argument.
1311
+ *
1312
+ * See .argument() for creating an attached argument, which uses this routine to
1313
+ * create the argument. You can override createArgument to return a custom argument.
1314
+ *
1315
+ * @param {string} name
1316
+ * @param {string} [description]
1317
+ * @return {Argument} new argument
1318
+ */
1319
+ createArgument(name, description) {
1320
+ return new Argument(name, description);
1321
+ }
1322
+ /**
1323
+ * Define argument syntax for command.
1324
+ *
1325
+ * The default is that the argument is required, and you can explicitly
1326
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1327
+ *
1328
+ * @example
1329
+ * program.argument('<input-file>');
1330
+ * program.argument('[output-file]');
1331
+ *
1332
+ * @param {string} name
1333
+ * @param {string} [description]
1334
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1335
+ * @param {*} [defaultValue]
1336
+ * @return {Command} `this` command for chaining
1337
+ */
1338
+ argument(name, description, parseArg, defaultValue) {
1339
+ const argument = this.createArgument(name, description);
1340
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1341
+ else argument.default(parseArg);
1342
+ this.addArgument(argument);
1343
+ return this;
1344
+ }
1345
+ /**
1346
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1347
+ *
1348
+ * See also .argument().
1349
+ *
1350
+ * @example
1351
+ * program.arguments('<cmd> [env]');
1352
+ *
1353
+ * @param {string} names
1354
+ * @return {Command} `this` command for chaining
1355
+ */
1356
+ arguments(names) {
1357
+ names.trim().split(/ +/).forEach((detail) => {
1358
+ this.argument(detail);
1359
+ });
1360
+ return this;
1361
+ }
1362
+ /**
1363
+ * Define argument syntax for command, adding a prepared argument.
1364
+ *
1365
+ * @param {Argument} argument
1366
+ * @return {Command} `this` command for chaining
1367
+ */
1368
+ addArgument(argument) {
1369
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1370
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1371
+ 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()}'`);
1372
+ this.registeredArguments.push(argument);
1373
+ return this;
1374
+ }
1375
+ /**
1376
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1377
+ *
1378
+ * @example
1379
+ * program.helpCommand('help [cmd]');
1380
+ * program.helpCommand('help [cmd]', 'show help');
1381
+ * program.helpCommand(false); // suppress default help command
1382
+ * program.helpCommand(true); // add help command even if no subcommands
1383
+ *
1384
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1385
+ * @param {string} [description] - custom description
1386
+ * @return {Command} `this` command for chaining
1387
+ */
1388
+ helpCommand(enableOrNameAndArgs, description) {
1389
+ if (typeof enableOrNameAndArgs === "boolean") {
1390
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1391
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1392
+ return this;
1393
+ }
1394
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1395
+ const helpDescription = description ?? "display help for command";
1396
+ const helpCommand = this.createCommand(helpName);
1397
+ helpCommand.helpOption(false);
1398
+ if (helpArgs) helpCommand.arguments(helpArgs);
1399
+ if (helpDescription) helpCommand.description(helpDescription);
1400
+ this._addImplicitHelpCommand = true;
1401
+ this._helpCommand = helpCommand;
1402
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1403
+ return this;
1404
+ }
1405
+ /**
1406
+ * Add prepared custom help command.
1407
+ *
1408
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1409
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1410
+ * @return {Command} `this` command for chaining
1411
+ */
1412
+ addHelpCommand(helpCommand, deprecatedDescription) {
1413
+ if (typeof helpCommand !== "object") {
1414
+ this.helpCommand(helpCommand, deprecatedDescription);
1415
+ return this;
1416
+ }
1417
+ this._addImplicitHelpCommand = true;
1418
+ this._helpCommand = helpCommand;
1419
+ this._initCommandGroup(helpCommand);
1420
+ return this;
1421
+ }
1422
+ /**
1423
+ * Lazy create help command.
1424
+ *
1425
+ * @return {(Command|null)}
1426
+ * @package
1427
+ */
1428
+ _getHelpCommand() {
1429
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1430
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1431
+ return this._helpCommand;
1432
+ }
1433
+ return null;
1434
+ }
1435
+ /**
1436
+ * Add hook for life cycle event.
1437
+ *
1438
+ * @param {string} event
1439
+ * @param {Function} listener
1440
+ * @return {Command} `this` command for chaining
1441
+ */
1442
+ hook(event, listener) {
1443
+ const allowedValues = [
1444
+ "preSubcommand",
1445
+ "preAction",
1446
+ "postAction"
1447
+ ];
1448
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1449
+ Expecting one of '${allowedValues.join("', '")}'`);
1450
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1451
+ else this._lifeCycleHooks[event] = [listener];
1452
+ return this;
1453
+ }
1454
+ /**
1455
+ * Register callback to use as replacement for calling process.exit.
1456
+ *
1457
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1458
+ * @return {Command} `this` command for chaining
1459
+ */
1460
+ exitOverride(fn) {
1461
+ if (fn) this._exitCallback = fn;
1462
+ else this._exitCallback = (err) => {
1463
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1464
+ };
1465
+ return this;
1466
+ }
1467
+ /**
1468
+ * Call process.exit, and _exitCallback if defined.
1469
+ *
1470
+ * @param {number} exitCode exit code for using with process.exit
1471
+ * @param {string} code an id string representing the error
1472
+ * @param {string} message human-readable description of the error
1473
+ * @return never
1474
+ * @private
1475
+ */
1476
+ _exit(exitCode, code, message) {
1477
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1478
+ node_process.default.exit(exitCode);
1479
+ }
1480
+ /**
1481
+ * Register callback `fn` for the command.
1482
+ *
1483
+ * @example
1484
+ * program
1485
+ * .command('serve')
1486
+ * .description('start service')
1487
+ * .action(function() {
1488
+ * // do work here
1489
+ * });
1490
+ *
1491
+ * @param {Function} fn
1492
+ * @return {Command} `this` command for chaining
1493
+ */
1494
+ action(fn) {
1495
+ const listener = (args) => {
1496
+ const expectedArgsCount = this.registeredArguments.length;
1497
+ const actionArgs = args.slice(0, expectedArgsCount);
1498
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1499
+ else actionArgs[expectedArgsCount] = this.opts();
1500
+ actionArgs.push(this);
1501
+ return fn.apply(this, actionArgs);
1502
+ };
1503
+ this._actionHandler = listener;
1504
+ return this;
1505
+ }
1506
+ /**
1507
+ * Factory routine to create a new unattached option.
1508
+ *
1509
+ * See .option() for creating an attached option, which uses this routine to
1510
+ * create the option. You can override createOption to return a custom option.
1511
+ *
1512
+ * @param {string} flags
1513
+ * @param {string} [description]
1514
+ * @return {Option} new option
1515
+ */
1516
+ createOption(flags, description) {
1517
+ return new Option(flags, description);
1518
+ }
1519
+ /**
1520
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1521
+ *
1522
+ * @param {(Option | Argument)} target
1523
+ * @param {string} value
1524
+ * @param {*} previous
1525
+ * @param {string} invalidArgumentMessage
1526
+ * @private
1527
+ */
1528
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1529
+ try {
1530
+ return target.parseArg(value, previous);
1531
+ } catch (err) {
1532
+ if (err.code === "commander.invalidArgument") {
1533
+ const message = `${invalidArgumentMessage} ${err.message}`;
1534
+ this.error(message, {
1535
+ exitCode: err.exitCode,
1536
+ code: err.code
1537
+ });
1538
+ }
1539
+ throw err;
1540
+ }
1541
+ }
1542
+ /**
1543
+ * Check for option flag conflicts.
1544
+ * Register option if no conflicts found, or throw on conflict.
1545
+ *
1546
+ * @param {Option} option
1547
+ * @private
1548
+ */
1549
+ _registerOption(option) {
1550
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1551
+ if (matchingOption) {
1552
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1553
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1554
+ - already used by option '${matchingOption.flags}'`);
1555
+ }
1556
+ this._initOptionGroup(option);
1557
+ this.options.push(option);
1558
+ }
1559
+ /**
1560
+ * Check for command name and alias conflicts with existing commands.
1561
+ * Register command if no conflicts found, or throw on conflict.
1562
+ *
1563
+ * @param {Command} command
1564
+ * @private
1565
+ */
1566
+ _registerCommand(command) {
1567
+ const knownBy = (cmd) => {
1568
+ return [cmd.name()].concat(cmd.aliases());
1569
+ };
1570
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1571
+ if (alreadyUsed) {
1572
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1573
+ const newCmd = knownBy(command).join("|");
1574
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1575
+ }
1576
+ this._initCommandGroup(command);
1577
+ this.commands.push(command);
1578
+ }
1579
+ /**
1580
+ * Add an option.
1581
+ *
1582
+ * @param {Option} option
1583
+ * @return {Command} `this` command for chaining
1584
+ */
1585
+ addOption(option) {
1586
+ this._registerOption(option);
1587
+ const oname = option.name();
1588
+ const name = option.attributeName();
1589
+ if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1590
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1591
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1592
+ const oldValue = this.getOptionValue(name);
1593
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1594
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1595
+ if (val == null) if (option.negate) val = false;
1596
+ else if (option.isBoolean() || option.optional) val = true;
1597
+ else val = "";
1598
+ this.setOptionValueWithSource(name, val, valueSource);
1599
+ };
1600
+ this.on("option:" + oname, (val) => {
1601
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1602
+ });
1603
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1604
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1605
+ });
1606
+ return this;
1607
+ }
1608
+ /**
1609
+ * Internal implementation shared by .option() and .requiredOption()
1610
+ *
1611
+ * @return {Command} `this` command for chaining
1612
+ * @private
1613
+ */
1614
+ _optionEx(config, flags, description, fn, defaultValue) {
1615
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1616
+ const option = this.createOption(flags, description);
1617
+ option.makeOptionMandatory(!!config.mandatory);
1618
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1619
+ else if (fn instanceof RegExp) {
1620
+ const regex = fn;
1621
+ fn = (val, def) => {
1622
+ const m = regex.exec(val);
1623
+ return m ? m[0] : def;
1624
+ };
1625
+ option.default(defaultValue).argParser(fn);
1626
+ } else option.default(fn);
1627
+ return this.addOption(option);
1628
+ }
1629
+ /**
1630
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1631
+ *
1632
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1633
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1634
+ *
1635
+ * See the README for more details, and see also addOption() and requiredOption().
1636
+ *
1637
+ * @example
1638
+ * program
1639
+ * .option('-p, --pepper', 'add pepper')
1640
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1641
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1642
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1643
+ *
1644
+ * @param {string} flags
1645
+ * @param {string} [description]
1646
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1647
+ * @param {*} [defaultValue]
1648
+ * @return {Command} `this` command for chaining
1649
+ */
1650
+ option(flags, description, parseArg, defaultValue) {
1651
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1652
+ }
1653
+ /**
1654
+ * Add a required option which must have a value after parsing. This usually means
1655
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1656
+ *
1657
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1658
+ *
1659
+ * @param {string} flags
1660
+ * @param {string} [description]
1661
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1662
+ * @param {*} [defaultValue]
1663
+ * @return {Command} `this` command for chaining
1664
+ */
1665
+ requiredOption(flags, description, parseArg, defaultValue) {
1666
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1667
+ }
1668
+ /**
1669
+ * Alter parsing of short flags with optional values.
1670
+ *
1671
+ * @example
1672
+ * // for `.option('-f,--flag [value]'):
1673
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1674
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1675
+ *
1676
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1677
+ * @return {Command} `this` command for chaining
1678
+ */
1679
+ combineFlagAndOptionalValue(combine = true) {
1680
+ this._combineFlagAndOptionalValue = !!combine;
1681
+ return this;
1682
+ }
1683
+ /**
1684
+ * Allow unknown options on the command line.
1685
+ *
1686
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1687
+ * @return {Command} `this` command for chaining
1688
+ */
1689
+ allowUnknownOption(allowUnknown = true) {
1690
+ this._allowUnknownOption = !!allowUnknown;
1691
+ return this;
1692
+ }
1693
+ /**
1694
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1695
+ *
1696
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1697
+ * @return {Command} `this` command for chaining
1698
+ */
1699
+ allowExcessArguments(allowExcess = true) {
1700
+ this._allowExcessArguments = !!allowExcess;
1701
+ return this;
1702
+ }
1703
+ /**
1704
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1705
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1706
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1707
+ *
1708
+ * @param {boolean} [positional]
1709
+ * @return {Command} `this` command for chaining
1710
+ */
1711
+ enablePositionalOptions(positional = true) {
1712
+ this._enablePositionalOptions = !!positional;
1713
+ return this;
1714
+ }
1715
+ /**
1716
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1717
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1718
+ * positional options to have been enabled on the program (parent commands).
1719
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1720
+ *
1721
+ * @param {boolean} [passThrough] for unknown options.
1722
+ * @return {Command} `this` command for chaining
1723
+ */
1724
+ passThroughOptions(passThrough = true) {
1725
+ this._passThroughOptions = !!passThrough;
1726
+ this._checkForBrokenPassThrough();
1727
+ return this;
1728
+ }
1729
+ /**
1730
+ * @private
1731
+ */
1732
+ _checkForBrokenPassThrough() {
1733
+ 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)`);
1734
+ }
1735
+ /**
1736
+ * Whether to store option values as properties on command object,
1737
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1738
+ *
1739
+ * @param {boolean} [storeAsProperties=true]
1740
+ * @return {Command} `this` command for chaining
1741
+ */
1742
+ storeOptionsAsProperties(storeAsProperties = true) {
1743
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1744
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1745
+ this._storeOptionsAsProperties = !!storeAsProperties;
1746
+ return this;
1747
+ }
1748
+ /**
1749
+ * Retrieve option value.
1750
+ *
1751
+ * @param {string} key
1752
+ * @return {object} value
1753
+ */
1754
+ getOptionValue(key) {
1755
+ if (this._storeOptionsAsProperties) return this[key];
1756
+ return this._optionValues[key];
1757
+ }
1758
+ /**
1759
+ * Store option value.
1760
+ *
1761
+ * @param {string} key
1762
+ * @param {object} value
1763
+ * @return {Command} `this` command for chaining
1764
+ */
1765
+ setOptionValue(key, value) {
1766
+ return this.setOptionValueWithSource(key, value, void 0);
1767
+ }
1768
+ /**
1769
+ * Store option value and where the value came from.
1770
+ *
1771
+ * @param {string} key
1772
+ * @param {object} value
1773
+ * @param {string} source - expected values are default/config/env/cli/implied
1774
+ * @return {Command} `this` command for chaining
1775
+ */
1776
+ setOptionValueWithSource(key, value, source) {
1777
+ if (this._storeOptionsAsProperties) this[key] = value;
1778
+ else this._optionValues[key] = value;
1779
+ this._optionValueSources[key] = source;
1780
+ return this;
1781
+ }
1782
+ /**
1783
+ * Get source of option value.
1784
+ * Expected values are default | config | env | cli | implied
1785
+ *
1786
+ * @param {string} key
1787
+ * @return {string}
1788
+ */
1789
+ getOptionValueSource(key) {
1790
+ return this._optionValueSources[key];
1791
+ }
1792
+ /**
1793
+ * Get source of option value. See also .optsWithGlobals().
1794
+ * Expected values are default | config | env | cli | implied
1795
+ *
1796
+ * @param {string} key
1797
+ * @return {string}
1798
+ */
1799
+ getOptionValueSourceWithGlobals(key) {
1800
+ let source;
1801
+ this._getCommandAndAncestors().forEach((cmd) => {
1802
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1803
+ });
1804
+ return source;
1805
+ }
1806
+ /**
1807
+ * Get user arguments from implied or explicit arguments.
1808
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1809
+ *
1810
+ * @private
1811
+ */
1812
+ _prepareUserArgs(argv, parseOptions) {
1813
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1814
+ parseOptions = parseOptions || {};
1815
+ if (argv === void 0 && parseOptions.from === void 0) {
1816
+ if (node_process.default.versions?.electron) parseOptions.from = "electron";
1817
+ const execArgv = node_process.default.execArgv ?? [];
1818
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1819
+ }
1820
+ if (argv === void 0) argv = node_process.default.argv;
1821
+ this.rawArgs = argv.slice();
1822
+ let userArgs;
1823
+ switch (parseOptions.from) {
1824
+ case void 0:
1825
+ case "node":
1826
+ this._scriptPath = argv[1];
1827
+ userArgs = argv.slice(2);
1828
+ break;
1829
+ case "electron":
1830
+ if (node_process.default.defaultApp) {
1831
+ this._scriptPath = argv[1];
1832
+ userArgs = argv.slice(2);
1833
+ } else userArgs = argv.slice(1);
1834
+ break;
1835
+ case "user":
1836
+ userArgs = argv.slice(0);
1837
+ break;
1838
+ case "eval":
1839
+ userArgs = argv.slice(1);
1840
+ break;
1841
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1842
+ }
1843
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1844
+ this._name = this._name || "program";
1845
+ return userArgs;
1846
+ }
1847
+ /**
1848
+ * Parse `argv`, setting options and invoking commands when defined.
1849
+ *
1850
+ * Use parseAsync instead of parse if any of your action handlers are async.
1851
+ *
1852
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1853
+ *
1854
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1855
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1856
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1857
+ * - `'user'`: just user arguments
1858
+ *
1859
+ * @example
1860
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1861
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1862
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1863
+ *
1864
+ * @param {string[]} [argv] - optional, defaults to process.argv
1865
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1866
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1867
+ * @return {Command} `this` command for chaining
1868
+ */
1869
+ parse(argv, parseOptions) {
1870
+ this._prepareForParse();
1871
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1872
+ this._parseCommand([], userArgs);
1873
+ return this;
1874
+ }
1875
+ /**
1876
+ * Parse `argv`, setting options and invoking commands when defined.
1877
+ *
1878
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1879
+ *
1880
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1881
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1882
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1883
+ * - `'user'`: just user arguments
1884
+ *
1885
+ * @example
1886
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1887
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1888
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1889
+ *
1890
+ * @param {string[]} [argv]
1891
+ * @param {object} [parseOptions]
1892
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1893
+ * @return {Promise}
1894
+ */
1895
+ async parseAsync(argv, parseOptions) {
1896
+ this._prepareForParse();
1897
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1898
+ await this._parseCommand([], userArgs);
1899
+ return this;
1900
+ }
1901
+ _prepareForParse() {
1902
+ if (this._savedState === null) {
1903
+ this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
1904
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1905
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
1906
+ });
1907
+ this.saveStateBeforeParse();
1908
+ } else this.restoreStateBeforeParse();
1909
+ }
1910
+ /**
1911
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1912
+ * Not usually called directly, but available for subclasses to save their custom state.
1913
+ *
1914
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1915
+ */
1916
+ saveStateBeforeParse() {
1917
+ this._savedState = {
1918
+ _name: this._name,
1919
+ _optionValues: { ...this._optionValues },
1920
+ _optionValueSources: { ...this._optionValueSources }
1921
+ };
1922
+ }
1923
+ /**
1924
+ * Restore state before parse for calls after the first.
1925
+ * Not usually called directly, but available for subclasses to save their custom state.
1926
+ *
1927
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1928
+ */
1929
+ restoreStateBeforeParse() {
1930
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1931
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1932
+ this._name = this._savedState._name;
1933
+ this._scriptPath = null;
1934
+ this.rawArgs = [];
1935
+ this._optionValues = { ...this._savedState._optionValues };
1936
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1937
+ this.args = [];
1938
+ this.processedArgs = [];
1939
+ }
1940
+ /**
1941
+ * Throw if expected executable is missing. Add lots of help for author.
1942
+ *
1943
+ * @param {string} executableFile
1944
+ * @param {string} executableDir
1945
+ * @param {string} subcommandName
1946
+ */
1947
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1948
+ if (node_fs.default.existsSync(executableFile)) return;
1949
+ const executableMissing = `'${executableFile}' does not exist
1950
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1951
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1952
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1953
+ throw new Error(executableMissing);
1954
+ }
1955
+ /**
1956
+ * Execute a sub-command executable.
1957
+ *
1958
+ * @private
1959
+ */
1960
+ _executeSubCommand(subcommand, args) {
1961
+ args = args.slice();
1962
+ const sourceExt = [
1963
+ ".js",
1964
+ ".ts",
1965
+ ".tsx",
1966
+ ".mjs",
1967
+ ".cjs"
1968
+ ];
1969
+ function findFile(baseDir, baseName) {
1970
+ const localBin = node_path.default.resolve(baseDir, baseName);
1971
+ if (node_fs.default.existsSync(localBin)) return localBin;
1972
+ if (sourceExt.includes(node_path.default.extname(baseName))) return void 0;
1973
+ const foundExt = sourceExt.find((ext) => node_fs.default.existsSync(`${localBin}${ext}`));
1974
+ if (foundExt) return `${localBin}${foundExt}`;
1975
+ }
1976
+ this._checkForMissingMandatoryOptions();
1977
+ this._checkForConflictingOptions();
1978
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1979
+ let executableDir = this._executableDir || "";
1980
+ if (this._scriptPath) {
1981
+ let resolvedScriptPath;
1982
+ try {
1983
+ resolvedScriptPath = node_fs.default.realpathSync(this._scriptPath);
1984
+ } catch {
1985
+ resolvedScriptPath = this._scriptPath;
1986
+ }
1987
+ executableDir = node_path.default.resolve(node_path.default.dirname(resolvedScriptPath), executableDir);
1988
+ }
1989
+ if (executableDir) {
1990
+ let localFile = findFile(executableDir, executableFile);
1991
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1992
+ const legacyName = node_path.default.basename(this._scriptPath, node_path.default.extname(this._scriptPath));
1993
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1994
+ }
1995
+ executableFile = localFile || executableFile;
1996
+ }
1997
+ const launchWithNode = sourceExt.includes(node_path.default.extname(executableFile));
1998
+ let proc;
1999
+ if (node_process.default.platform !== "win32") if (launchWithNode) {
2000
+ args.unshift(executableFile);
2001
+ args = incrementNodeInspectorPort(node_process.default.execArgv).concat(args);
2002
+ proc = node_child_process.default.spawn(node_process.default.argv[0], args, { stdio: "inherit" });
2003
+ } else proc = node_child_process.default.spawn(executableFile, args, { stdio: "inherit" });
2004
+ else {
2005
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2006
+ args.unshift(executableFile);
2007
+ args = incrementNodeInspectorPort(node_process.default.execArgv).concat(args);
2008
+ proc = node_child_process.default.spawn(node_process.default.execPath, args, { stdio: "inherit" });
2009
+ }
2010
+ if (!proc.killed) [
2011
+ "SIGUSR1",
2012
+ "SIGUSR2",
2013
+ "SIGTERM",
2014
+ "SIGINT",
2015
+ "SIGHUP"
2016
+ ].forEach((signal) => {
2017
+ node_process.default.on(signal, () => {
2018
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2019
+ });
2020
+ });
2021
+ const exitCallback = this._exitCallback;
2022
+ proc.on("close", (code) => {
2023
+ code = code ?? 1;
2024
+ if (!exitCallback) node_process.default.exit(code);
2025
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2026
+ });
2027
+ proc.on("error", (err) => {
2028
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2029
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2030
+ if (!exitCallback) node_process.default.exit(1);
2031
+ else {
2032
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2033
+ wrappedError.nestedError = err;
2034
+ exitCallback(wrappedError);
2035
+ }
2036
+ });
2037
+ this.runningCommand = proc;
2038
+ }
2039
+ /**
2040
+ * @private
2041
+ */
2042
+ _dispatchSubcommand(commandName, operands, unknown) {
2043
+ const subCommand = this._findCommand(commandName);
2044
+ if (!subCommand) this.help({ error: true });
2045
+ subCommand._prepareForParse();
2046
+ let promiseChain;
2047
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2048
+ promiseChain = this._chainOrCall(promiseChain, () => {
2049
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2050
+ else return subCommand._parseCommand(operands, unknown);
2051
+ });
2052
+ return promiseChain;
2053
+ }
2054
+ /**
2055
+ * Invoke help directly if possible, or dispatch if necessary.
2056
+ * e.g. help foo
2057
+ *
2058
+ * @private
2059
+ */
2060
+ _dispatchHelpCommand(subcommandName) {
2061
+ if (!subcommandName) this.help();
2062
+ const subCommand = this._findCommand(subcommandName);
2063
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2064
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2065
+ }
2066
+ /**
2067
+ * Check this.args against expected this.registeredArguments.
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _checkNumberOfArguments() {
2072
+ this.registeredArguments.forEach((arg, i) => {
2073
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2074
+ });
2075
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2076
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2077
+ }
2078
+ /**
2079
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2080
+ *
2081
+ * @private
2082
+ */
2083
+ _processArguments() {
2084
+ const myParseArg = (argument, value, previous) => {
2085
+ let parsedValue = value;
2086
+ if (value !== null && argument.parseArg) {
2087
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2088
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2089
+ }
2090
+ return parsedValue;
2091
+ };
2092
+ this._checkNumberOfArguments();
2093
+ const processedArgs = [];
2094
+ this.registeredArguments.forEach((declaredArg, index) => {
2095
+ let value = declaredArg.defaultValue;
2096
+ if (declaredArg.variadic) {
2097
+ if (index < this.args.length) {
2098
+ value = this.args.slice(index);
2099
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2100
+ return myParseArg(declaredArg, v, processed);
2101
+ }, declaredArg.defaultValue);
2102
+ } else if (value === void 0) value = [];
2103
+ } else if (index < this.args.length) {
2104
+ value = this.args[index];
2105
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2106
+ }
2107
+ processedArgs[index] = value;
2108
+ });
2109
+ this.processedArgs = processedArgs;
2110
+ }
2111
+ /**
2112
+ * Once we have a promise we chain, but call synchronously until then.
2113
+ *
2114
+ * @param {(Promise|undefined)} promise
2115
+ * @param {Function} fn
2116
+ * @return {(Promise|undefined)}
2117
+ * @private
2118
+ */
2119
+ _chainOrCall(promise, fn) {
2120
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2121
+ return fn();
2122
+ }
2123
+ /**
2124
+ *
2125
+ * @param {(Promise|undefined)} promise
2126
+ * @param {string} event
2127
+ * @return {(Promise|undefined)}
2128
+ * @private
2129
+ */
2130
+ _chainOrCallHooks(promise, event) {
2131
+ let result = promise;
2132
+ const hooks = [];
2133
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2134
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2135
+ hooks.push({
2136
+ hookedCommand,
2137
+ callback
2138
+ });
2139
+ });
2140
+ });
2141
+ if (event === "postAction") hooks.reverse();
2142
+ hooks.forEach((hookDetail) => {
2143
+ result = this._chainOrCall(result, () => {
2144
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2145
+ });
2146
+ });
2147
+ return result;
2148
+ }
2149
+ /**
2150
+ *
2151
+ * @param {(Promise|undefined)} promise
2152
+ * @param {Command} subCommand
2153
+ * @param {string} event
2154
+ * @return {(Promise|undefined)}
2155
+ * @private
2156
+ */
2157
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2158
+ let result = promise;
2159
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2160
+ result = this._chainOrCall(result, () => {
2161
+ return hook(this, subCommand);
2162
+ });
2163
+ });
2164
+ return result;
2165
+ }
2166
+ /**
2167
+ * Process arguments in context of this command.
2168
+ * Returns action result, in case it is a promise.
2169
+ *
2170
+ * @private
2171
+ */
2172
+ _parseCommand(operands, unknown) {
2173
+ const parsed = this.parseOptions(unknown);
2174
+ this._parseOptionsEnv();
2175
+ this._parseOptionsImplied();
2176
+ operands = operands.concat(parsed.operands);
2177
+ unknown = parsed.unknown;
2178
+ this.args = operands.concat(unknown);
2179
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2180
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2181
+ if (this._defaultCommandName) {
2182
+ this._outputHelpIfRequested(unknown);
2183
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2184
+ }
2185
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2186
+ this._outputHelpIfRequested(parsed.unknown);
2187
+ this._checkForMissingMandatoryOptions();
2188
+ this._checkForConflictingOptions();
2189
+ const checkForUnknownOptions = () => {
2190
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2191
+ };
2192
+ const commandEvent = `command:${this.name()}`;
2193
+ if (this._actionHandler) {
2194
+ checkForUnknownOptions();
2195
+ this._processArguments();
2196
+ let promiseChain;
2197
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2198
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2199
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2200
+ this.parent.emit(commandEvent, operands, unknown);
2201
+ });
2202
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2203
+ return promiseChain;
2204
+ }
2205
+ if (this.parent?.listenerCount(commandEvent)) {
2206
+ checkForUnknownOptions();
2207
+ this._processArguments();
2208
+ this.parent.emit(commandEvent, operands, unknown);
2209
+ } else if (operands.length) {
2210
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2211
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2212
+ else if (this.commands.length) this.unknownCommand();
2213
+ else {
2214
+ checkForUnknownOptions();
2215
+ this._processArguments();
2216
+ }
2217
+ } else if (this.commands.length) {
2218
+ checkForUnknownOptions();
2219
+ this.help({ error: true });
2220
+ } else {
2221
+ checkForUnknownOptions();
2222
+ this._processArguments();
2223
+ }
2224
+ }
2225
+ /**
2226
+ * Find matching command.
2227
+ *
2228
+ * @private
2229
+ * @return {Command | undefined}
2230
+ */
2231
+ _findCommand(name) {
2232
+ if (!name) return void 0;
2233
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2234
+ }
2235
+ /**
2236
+ * Return an option matching `arg` if any.
2237
+ *
2238
+ * @param {string} arg
2239
+ * @return {Option}
2240
+ * @package
2241
+ */
2242
+ _findOption(arg) {
2243
+ return this.options.find((option) => option.is(arg));
2244
+ }
2245
+ /**
2246
+ * Display an error message if a mandatory option does not have a value.
2247
+ * Called after checking for help flags in leaf subcommand.
2248
+ *
2249
+ * @private
2250
+ */
2251
+ _checkForMissingMandatoryOptions() {
2252
+ this._getCommandAndAncestors().forEach((cmd) => {
2253
+ cmd.options.forEach((anOption) => {
2254
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2255
+ });
2256
+ });
2257
+ }
2258
+ /**
2259
+ * Display an error message if conflicting options are used together in this.
2260
+ *
2261
+ * @private
2262
+ */
2263
+ _checkForConflictingLocalOptions() {
2264
+ const definedNonDefaultOptions = this.options.filter((option) => {
2265
+ const optionKey = option.attributeName();
2266
+ if (this.getOptionValue(optionKey) === void 0) return false;
2267
+ return this.getOptionValueSource(optionKey) !== "default";
2268
+ });
2269
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2270
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2271
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2272
+ });
2273
+ }
2274
+ /**
2275
+ * Display an error message if conflicting options are used together.
2276
+ * Called after checking for help flags in leaf subcommand.
2277
+ *
2278
+ * @private
2279
+ */
2280
+ _checkForConflictingOptions() {
2281
+ this._getCommandAndAncestors().forEach((cmd) => {
2282
+ cmd._checkForConflictingLocalOptions();
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Parse options from `argv` removing known options,
2287
+ * and return argv split into operands and unknown arguments.
2288
+ *
2289
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2290
+ *
2291
+ * Examples:
2292
+ *
2293
+ * argv => operands, unknown
2294
+ * --known kkk op => [op], []
2295
+ * op --known kkk => [op], []
2296
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2297
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2298
+ *
2299
+ * @param {string[]} args
2300
+ * @return {{operands: string[], unknown: string[]}}
2301
+ */
2302
+ parseOptions(args) {
2303
+ const operands = [];
2304
+ const unknown = [];
2305
+ let dest = operands;
2306
+ function maybeOption(arg) {
2307
+ return arg.length > 1 && arg[0] === "-";
2308
+ }
2309
+ const negativeNumberArg = (arg) => {
2310
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2311
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2312
+ };
2313
+ let activeVariadicOption = null;
2314
+ let activeGroup = null;
2315
+ let i = 0;
2316
+ while (i < args.length || activeGroup) {
2317
+ const arg = activeGroup ?? args[i++];
2318
+ activeGroup = null;
2319
+ if (arg === "--") {
2320
+ if (dest === unknown) dest.push(arg);
2321
+ dest.push(...args.slice(i));
2322
+ break;
2323
+ }
2324
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2325
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2326
+ continue;
2327
+ }
2328
+ activeVariadicOption = null;
2329
+ if (maybeOption(arg)) {
2330
+ const option = this._findOption(arg);
2331
+ if (option) {
2332
+ if (option.required) {
2333
+ const value = args[i++];
2334
+ if (value === void 0) this.optionMissingArgument(option);
2335
+ this.emit(`option:${option.name()}`, value);
2336
+ } else if (option.optional) {
2337
+ let value = null;
2338
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2339
+ this.emit(`option:${option.name()}`, value);
2340
+ } else this.emit(`option:${option.name()}`);
2341
+ activeVariadicOption = option.variadic ? option : null;
2342
+ continue;
2343
+ }
2344
+ }
2345
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2346
+ const option = this._findOption(`-${arg[1]}`);
2347
+ if (option) {
2348
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2349
+ else {
2350
+ this.emit(`option:${option.name()}`);
2351
+ activeGroup = `-${arg.slice(2)}`;
2352
+ }
2353
+ continue;
2354
+ }
2355
+ }
2356
+ if (/^--[^=]+=/.test(arg)) {
2357
+ const index = arg.indexOf("=");
2358
+ const option = this._findOption(arg.slice(0, index));
2359
+ if (option && (option.required || option.optional)) {
2360
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2361
+ continue;
2362
+ }
2363
+ }
2364
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2365
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2366
+ if (this._findCommand(arg)) {
2367
+ operands.push(arg);
2368
+ unknown.push(...args.slice(i));
2369
+ break;
2370
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2371
+ operands.push(arg, ...args.slice(i));
2372
+ break;
2373
+ } else if (this._defaultCommandName) {
2374
+ unknown.push(arg, ...args.slice(i));
2375
+ break;
2376
+ }
2377
+ }
2378
+ if (this._passThroughOptions) {
2379
+ dest.push(arg, ...args.slice(i));
2380
+ break;
2381
+ }
2382
+ dest.push(arg);
2383
+ }
2384
+ return {
2385
+ operands,
2386
+ unknown
2387
+ };
2388
+ }
2389
+ /**
2390
+ * Return an object containing local option values as key-value pairs.
2391
+ *
2392
+ * @return {object}
2393
+ */
2394
+ opts() {
2395
+ if (this._storeOptionsAsProperties) {
2396
+ const result = {};
2397
+ const len = this.options.length;
2398
+ for (let i = 0; i < len; i++) {
2399
+ const key = this.options[i].attributeName();
2400
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2401
+ }
2402
+ return result;
2403
+ }
2404
+ return this._optionValues;
2405
+ }
2406
+ /**
2407
+ * Return an object containing merged local and global option values as key-value pairs.
2408
+ *
2409
+ * @return {object}
2410
+ */
2411
+ optsWithGlobals() {
2412
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2413
+ }
2414
+ /**
2415
+ * Display error message and exit (or call exitOverride).
2416
+ *
2417
+ * @param {string} message
2418
+ * @param {object} [errorOptions]
2419
+ * @param {string} [errorOptions.code] - an id string representing the error
2420
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2421
+ */
2422
+ error(message, errorOptions) {
2423
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2424
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2425
+ else if (this._showHelpAfterError) {
2426
+ this._outputConfiguration.writeErr("\n");
2427
+ this.outputHelp({ error: true });
2428
+ }
2429
+ const config = errorOptions || {};
2430
+ const exitCode = config.exitCode || 1;
2431
+ const code = config.code || "commander.error";
2432
+ this._exit(exitCode, code, message);
2433
+ }
2434
+ /**
2435
+ * Apply any option related environment variables, if option does
2436
+ * not have a value from cli or client code.
2437
+ *
2438
+ * @private
2439
+ */
2440
+ _parseOptionsEnv() {
2441
+ this.options.forEach((option) => {
2442
+ if (option.envVar && option.envVar in node_process.default.env) {
2443
+ const optionKey = option.attributeName();
2444
+ if (this.getOptionValue(optionKey) === void 0 || [
2445
+ "default",
2446
+ "config",
2447
+ "env"
2448
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, node_process.default.env[option.envVar]);
2449
+ else this.emit(`optionEnv:${option.name()}`);
2450
+ }
2451
+ });
2452
+ }
2453
+ /**
2454
+ * Apply any implied option values, if option is undefined or default value.
2455
+ *
2456
+ * @private
2457
+ */
2458
+ _parseOptionsImplied() {
2459
+ const dualHelper = new DualOptions(this.options);
2460
+ const hasCustomOptionValue = (optionKey) => {
2461
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2462
+ };
2463
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2464
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2465
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2466
+ });
2467
+ });
2468
+ }
2469
+ /**
2470
+ * Argument `name` is missing.
2471
+ *
2472
+ * @param {string} name
2473
+ * @private
2474
+ */
2475
+ missingArgument(name) {
2476
+ const message = `error: missing required argument '${name}'`;
2477
+ this.error(message, { code: "commander.missingArgument" });
2478
+ }
2479
+ /**
2480
+ * `Option` is missing an argument.
2481
+ *
2482
+ * @param {Option} option
2483
+ * @private
2484
+ */
2485
+ optionMissingArgument(option) {
2486
+ const message = `error: option '${option.flags}' argument missing`;
2487
+ this.error(message, { code: "commander.optionMissingArgument" });
2488
+ }
2489
+ /**
2490
+ * `Option` does not have a value, and is a mandatory option.
2491
+ *
2492
+ * @param {Option} option
2493
+ * @private
2494
+ */
2495
+ missingMandatoryOptionValue(option) {
2496
+ const message = `error: required option '${option.flags}' not specified`;
2497
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2498
+ }
2499
+ /**
2500
+ * `Option` conflicts with another option.
2501
+ *
2502
+ * @param {Option} option
2503
+ * @param {Option} conflictingOption
2504
+ * @private
2505
+ */
2506
+ _conflictingOption(option, conflictingOption) {
2507
+ const findBestOptionFromValue = (option) => {
2508
+ const optionKey = option.attributeName();
2509
+ const optionValue = this.getOptionValue(optionKey);
2510
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2511
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2512
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2513
+ return positiveOption || option;
2514
+ };
2515
+ const getErrorMessage = (option) => {
2516
+ const bestOption = findBestOptionFromValue(option);
2517
+ const optionKey = bestOption.attributeName();
2518
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2519
+ return `option '${bestOption.flags}'`;
2520
+ };
2521
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2522
+ this.error(message, { code: "commander.conflictingOption" });
2523
+ }
2524
+ /**
2525
+ * Unknown option `flag`.
2526
+ *
2527
+ * @param {string} flag
2528
+ * @private
2529
+ */
2530
+ unknownOption(flag) {
2531
+ if (this._allowUnknownOption) return;
2532
+ let suggestion = "";
2533
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2534
+ let candidateFlags = [];
2535
+ let command = this;
2536
+ do {
2537
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2538
+ candidateFlags = candidateFlags.concat(moreFlags);
2539
+ command = command.parent;
2540
+ } while (command && !command._enablePositionalOptions);
2541
+ suggestion = suggestSimilar(flag, candidateFlags);
2542
+ }
2543
+ const message = `error: unknown option '${flag}'${suggestion}`;
2544
+ this.error(message, { code: "commander.unknownOption" });
2545
+ }
2546
+ /**
2547
+ * Excess arguments, more than expected.
2548
+ *
2549
+ * @param {string[]} receivedArgs
2550
+ * @private
2551
+ */
2552
+ _excessArguments(receivedArgs) {
2553
+ if (this._allowExcessArguments) return;
2554
+ const expected = this.registeredArguments.length;
2555
+ const s = expected === 1 ? "" : "s";
2556
+ const received = receivedArgs.length;
2557
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
2558
+ this.error(message, { code: "commander.excessArguments" });
2559
+ }
2560
+ /**
2561
+ * Unknown command.
2562
+ *
2563
+ * @private
2564
+ */
2565
+ unknownCommand() {
2566
+ const unknownName = this.args[0];
2567
+ let suggestion = "";
2568
+ if (this._showSuggestionAfterError) {
2569
+ const candidateNames = [];
2570
+ this.createHelp().visibleCommands(this).forEach((command) => {
2571
+ candidateNames.push(command.name());
2572
+ if (command.alias()) candidateNames.push(command.alias());
2573
+ });
2574
+ suggestion = suggestSimilar(unknownName, candidateNames);
2575
+ }
2576
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2577
+ this.error(message, { code: "commander.unknownCommand" });
2578
+ }
2579
+ /**
2580
+ * Get or set the program version.
2581
+ *
2582
+ * This method auto-registers the "-V, --version" option which will print the version number.
2583
+ *
2584
+ * You can optionally supply the flags and description to override the defaults.
2585
+ *
2586
+ * @param {string} [str]
2587
+ * @param {string} [flags]
2588
+ * @param {string} [description]
2589
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2590
+ */
2591
+ version(str, flags, description) {
2592
+ if (str === void 0) return this._version;
2593
+ this._version = str;
2594
+ flags = flags || "-V, --version";
2595
+ description = description || "output the version number";
2596
+ const versionOption = this.createOption(flags, description);
2597
+ this._versionOptionName = versionOption.attributeName();
2598
+ this._registerOption(versionOption);
2599
+ this.on("option:" + versionOption.name(), () => {
2600
+ this._outputConfiguration.writeOut(`${str}\n`);
2601
+ this._exit(0, "commander.version", str);
2602
+ });
2603
+ return this;
2604
+ }
2605
+ /**
2606
+ * Set the description.
2607
+ *
2608
+ * @param {string} [str]
2609
+ * @param {object} [argsDescription]
2610
+ * @return {(string|Command)}
2611
+ */
2612
+ description(str, argsDescription) {
2613
+ if (str === void 0 && argsDescription === void 0) return this._description;
2614
+ this._description = str;
2615
+ if (argsDescription) this._argsDescription = argsDescription;
2616
+ return this;
2617
+ }
2618
+ /**
2619
+ * Set the summary. Used when listed as subcommand of parent.
2620
+ *
2621
+ * @param {string} [str]
2622
+ * @return {(string|Command)}
2623
+ */
2624
+ summary(str) {
2625
+ if (str === void 0) return this._summary;
2626
+ this._summary = str;
2627
+ return this;
2628
+ }
2629
+ /**
2630
+ * Set an alias for the command.
2631
+ *
2632
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2633
+ *
2634
+ * @param {string} [alias]
2635
+ * @return {(string|Command)}
2636
+ */
2637
+ alias(alias) {
2638
+ if (alias === void 0) return this._aliases[0];
2639
+ /** @type {Command} */
2640
+ let command = this;
2641
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2642
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2643
+ const matchingCommand = this.parent?._findCommand(alias);
2644
+ if (matchingCommand) {
2645
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2646
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2647
+ }
2648
+ command._aliases.push(alias);
2649
+ return this;
2650
+ }
2651
+ /**
2652
+ * Set aliases for the command.
2653
+ *
2654
+ * Only the first alias is shown in the auto-generated help.
2655
+ *
2656
+ * @param {string[]} [aliases]
2657
+ * @return {(string[]|Command)}
2658
+ */
2659
+ aliases(aliases) {
2660
+ if (aliases === void 0) return this._aliases;
2661
+ aliases.forEach((alias) => this.alias(alias));
2662
+ return this;
2663
+ }
2664
+ /**
2665
+ * Set / get the command usage `str`.
2666
+ *
2667
+ * @param {string} [str]
2668
+ * @return {(string|Command)}
2669
+ */
2670
+ usage(str) {
2671
+ if (str === void 0) {
2672
+ if (this._usage) return this._usage;
2673
+ const args = this.registeredArguments.map((arg) => {
2674
+ return humanReadableArgName(arg);
2675
+ });
2676
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2677
+ }
2678
+ this._usage = str;
2679
+ return this;
2680
+ }
2681
+ /**
2682
+ * Get or set the name of the command.
2683
+ *
2684
+ * @param {string} [str]
2685
+ * @return {(string|Command)}
2686
+ */
2687
+ name(str) {
2688
+ if (str === void 0) return this._name;
2689
+ this._name = str;
2690
+ return this;
2691
+ }
2692
+ /**
2693
+ * Set/get the help group heading for this subcommand in parent command's help.
2694
+ *
2695
+ * @param {string} [heading]
2696
+ * @return {Command | string}
2697
+ */
2698
+ helpGroup(heading) {
2699
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2700
+ this._helpGroupHeading = heading;
2701
+ return this;
2702
+ }
2703
+ /**
2704
+ * Set/get the default help group heading for subcommands added to this command.
2705
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2706
+ *
2707
+ * @example
2708
+ * program.commandsGroup('Development Commands:);
2709
+ * program.command('watch')...
2710
+ * program.command('lint')...
2711
+ * ...
2712
+ *
2713
+ * @param {string} [heading]
2714
+ * @returns {Command | string}
2715
+ */
2716
+ commandsGroup(heading) {
2717
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2718
+ this._defaultCommandGroup = heading;
2719
+ return this;
2720
+ }
2721
+ /**
2722
+ * Set/get the default help group heading for options added to this command.
2723
+ * (This does not override a group set directly on the option using .helpGroup().)
2724
+ *
2725
+ * @example
2726
+ * program
2727
+ * .optionsGroup('Development Options:')
2728
+ * .option('-d, --debug', 'output extra debugging')
2729
+ * .option('-p, --profile', 'output profiling information')
2730
+ *
2731
+ * @param {string} [heading]
2732
+ * @returns {Command | string}
2733
+ */
2734
+ optionsGroup(heading) {
2735
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2736
+ this._defaultOptionGroup = heading;
2737
+ return this;
2738
+ }
2739
+ /**
2740
+ * @param {Option} option
2741
+ * @private
2742
+ */
2743
+ _initOptionGroup(option) {
2744
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2745
+ }
2746
+ /**
2747
+ * @param {Command} cmd
2748
+ * @private
2749
+ */
2750
+ _initCommandGroup(cmd) {
2751
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2752
+ }
2753
+ /**
2754
+ * Set the name of the command from script filename, such as process.argv[1],
2755
+ * or import.meta.filename.
2756
+ *
2757
+ * (Used internally and public although not documented in README.)
2758
+ *
2759
+ * @example
2760
+ * program.nameFromFilename(import.meta.filename);
2761
+ *
2762
+ * @param {string} filename
2763
+ * @return {Command}
2764
+ */
2765
+ nameFromFilename(filename) {
2766
+ this._name = node_path.default.basename(filename, node_path.default.extname(filename));
2767
+ return this;
2768
+ }
2769
+ /**
2770
+ * Get or set the directory for searching for executable subcommands of this command.
2771
+ *
2772
+ * @example
2773
+ * program.executableDir(import.meta.dirname);
2774
+ * // or
2775
+ * program.executableDir('subcommands');
2776
+ *
2777
+ * @param {string} [path]
2778
+ * @return {(string|null|Command)}
2779
+ */
2780
+ executableDir(path) {
2781
+ if (path === void 0) return this._executableDir;
2782
+ this._executableDir = path;
2783
+ return this;
2784
+ }
2785
+ /**
2786
+ * Return program help documentation.
2787
+ *
2788
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2789
+ * @return {string}
2790
+ */
2791
+ helpInformation(contextOptions) {
2792
+ const helper = this.createHelp();
2793
+ const context = this._getOutputContext(contextOptions);
2794
+ helper.prepareContext({
2795
+ error: context.error,
2796
+ helpWidth: context.helpWidth,
2797
+ outputHasColors: context.hasColors
2798
+ });
2799
+ const text = helper.formatHelp(this, helper);
2800
+ if (context.hasColors) return text;
2801
+ return this._outputConfiguration.stripColor(text);
2802
+ }
2803
+ /**
2804
+ * @typedef HelpContext
2805
+ * @type {object}
2806
+ * @property {boolean} error
2807
+ * @property {number} helpWidth
2808
+ * @property {boolean} hasColors
2809
+ * @property {function} write - includes stripColor if needed
2810
+ *
2811
+ * @returns {HelpContext}
2812
+ * @private
2813
+ */
2814
+ _getOutputContext(contextOptions) {
2815
+ contextOptions = contextOptions || {};
2816
+ const error = !!contextOptions.error;
2817
+ let baseWrite;
2818
+ let hasColors;
2819
+ let helpWidth;
2820
+ if (error) {
2821
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2822
+ hasColors = this._outputConfiguration.getErrHasColors();
2823
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2824
+ } else {
2825
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2826
+ hasColors = this._outputConfiguration.getOutHasColors();
2827
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2828
+ }
2829
+ const write = (str) => {
2830
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2831
+ return baseWrite(str);
2832
+ };
2833
+ return {
2834
+ error,
2835
+ write,
2836
+ hasColors,
2837
+ helpWidth
2838
+ };
2839
+ }
2840
+ /**
2841
+ * Output help information for this command.
2842
+ *
2843
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2844
+ *
2845
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2846
+ */
2847
+ outputHelp(contextOptions) {
2848
+ let deprecatedCallback;
2849
+ if (typeof contextOptions === "function") {
2850
+ deprecatedCallback = contextOptions;
2851
+ contextOptions = void 0;
2852
+ }
2853
+ const outputContext = this._getOutputContext(contextOptions);
2854
+ /** @type {HelpTextEventContext} */
2855
+ const eventContext = {
2856
+ error: outputContext.error,
2857
+ write: outputContext.write,
2858
+ command: this
2859
+ };
2860
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2861
+ this.emit("beforeHelp", eventContext);
2862
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2863
+ if (deprecatedCallback) {
2864
+ helpInformation = deprecatedCallback(helpInformation);
2865
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2866
+ }
2867
+ outputContext.write(helpInformation);
2868
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2869
+ this.emit("afterHelp", eventContext);
2870
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2871
+ }
2872
+ /**
2873
+ * You can pass in flags and a description to customise the built-in help option.
2874
+ * Pass in false to disable the built-in help option.
2875
+ *
2876
+ * @example
2877
+ * program.helpOption('-?, --help' 'show help'); // customise
2878
+ * program.helpOption(false); // disable
2879
+ *
2880
+ * @param {(string | boolean)} flags
2881
+ * @param {string} [description]
2882
+ * @return {Command} `this` command for chaining
2883
+ */
2884
+ helpOption(flags, description) {
2885
+ if (typeof flags === "boolean") {
2886
+ if (flags) {
2887
+ if (this._helpOption === null) this._helpOption = void 0;
2888
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2889
+ } else this._helpOption = null;
2890
+ return this;
2891
+ }
2892
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2893
+ if (flags || description) this._initOptionGroup(this._helpOption);
2894
+ return this;
2895
+ }
2896
+ /**
2897
+ * Lazy create help option.
2898
+ * Returns null if has been disabled with .helpOption(false).
2899
+ *
2900
+ * @returns {(Option | null)} the help option
2901
+ * @package
2902
+ */
2903
+ _getHelpOption() {
2904
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2905
+ return this._helpOption;
2906
+ }
2907
+ /**
2908
+ * Supply your own option to use for the built-in help option.
2909
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2910
+ *
2911
+ * @param {Option} option
2912
+ * @return {Command} `this` command for chaining
2913
+ */
2914
+ addHelpOption(option) {
2915
+ this._helpOption = option;
2916
+ this._initOptionGroup(option);
2917
+ return this;
2918
+ }
2919
+ /**
2920
+ * Output help information and exit.
2921
+ *
2922
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2923
+ *
2924
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2925
+ */
2926
+ help(contextOptions) {
2927
+ this.outputHelp(contextOptions);
2928
+ let exitCode = Number(node_process.default.exitCode ?? 0);
2929
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2930
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2931
+ }
2932
+ /**
2933
+ * // Do a little typing to coordinate emit and listener for the help text events.
2934
+ * @typedef HelpTextEventContext
2935
+ * @type {object}
2936
+ * @property {boolean} error
2937
+ * @property {Command} command
2938
+ * @property {function} write
2939
+ */
2940
+ /**
2941
+ * Add additional text to be displayed with the built-in help.
2942
+ *
2943
+ * Position is 'before' or 'after' to affect just this command,
2944
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2945
+ *
2946
+ * @param {string} position - before or after built-in help
2947
+ * @param {(string | Function)} text - string to add, or a function returning a string
2948
+ * @return {Command} `this` command for chaining
2949
+ */
2950
+ addHelpText(position, text) {
2951
+ const allowedValues = [
2952
+ "beforeAll",
2953
+ "before",
2954
+ "after",
2955
+ "afterAll"
2956
+ ];
2957
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2958
+ Expecting one of '${allowedValues.join("', '")}'`);
2959
+ const helpEvent = `${position}Help`;
2960
+ this.on(helpEvent, (context) => {
2961
+ let helpStr;
2962
+ if (typeof text === "function") helpStr = text({
2963
+ error: context.error,
2964
+ command: context.command
2965
+ });
2966
+ else helpStr = text;
2967
+ if (helpStr) context.write(`${helpStr}\n`);
2968
+ });
2969
+ return this;
2970
+ }
2971
+ /**
2972
+ * Output help information if help flags specified
2973
+ *
2974
+ * @param {Array} args - array of options to search for help flags
2975
+ * @private
2976
+ */
2977
+ _outputHelpIfRequested(args) {
2978
+ const helpOption = this._getHelpOption();
2979
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2980
+ this.outputHelp();
2981
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2982
+ }
2983
+ }
2984
+ };
2985
+ /**
2986
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2987
+ *
2988
+ * @param {string[]} args - array of arguments from node.execArgv
2989
+ * @returns {string[]}
2990
+ * @private
2991
+ */
2992
+ function incrementNodeInspectorPort(args) {
2993
+ return args.map((arg) => {
2994
+ if (!arg.startsWith("--inspect")) return arg;
2995
+ let debugOption;
2996
+ let debugHost = "127.0.0.1";
2997
+ let debugPort = "9229";
2998
+ let match;
2999
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3000
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3001
+ debugOption = match[1];
3002
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3003
+ else debugHost = match[3];
3004
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3005
+ debugOption = match[1];
3006
+ debugHost = match[3];
3007
+ debugPort = match[4];
3008
+ }
3009
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3010
+ return arg;
3011
+ });
3012
+ }
3013
+ /**
3014
+ * Exported for using from tests, not otherwise used outside this file.
3015
+ *
3016
+ * @returns {boolean | undefined}
3017
+ * @package
3018
+ */
3019
+ function useColor() {
3020
+ if (node_process.default.env.NO_COLOR || node_process.default.env.FORCE_COLOR === "0" || node_process.default.env.FORCE_COLOR === "false") return false;
3021
+ if (node_process.default.env.FORCE_COLOR || node_process.default.env.CLICOLOR_FORCE !== void 0) return true;
3022
+ }
3023
+ new Command();
3024
+ //#endregion
3025
+ //#region node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
3026
+ var ANSI_BACKGROUND_OFFSET = 10;
3027
+ var wrapAnsi16 = (offset = 0) => (code) => `\u001B[${code + offset}m`;
3028
+ var wrapAnsi256 = (offset = 0) => (code) => `\u001B[${38 + offset};5;${code}m`;
3029
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
3030
+ var styles$1 = {
3031
+ modifier: {
3032
+ reset: [0, 0],
3033
+ bold: [1, 22],
3034
+ dim: [2, 22],
3035
+ italic: [3, 23],
3036
+ underline: [4, 24],
3037
+ overline: [53, 55],
3038
+ inverse: [7, 27],
3039
+ hidden: [8, 28],
3040
+ strikethrough: [9, 29]
3041
+ },
3042
+ color: {
3043
+ black: [30, 39],
3044
+ red: [31, 39],
3045
+ green: [32, 39],
3046
+ yellow: [33, 39],
3047
+ blue: [34, 39],
3048
+ magenta: [35, 39],
3049
+ cyan: [36, 39],
3050
+ white: [37, 39],
3051
+ blackBright: [90, 39],
3052
+ gray: [90, 39],
3053
+ grey: [90, 39],
3054
+ redBright: [91, 39],
3055
+ greenBright: [92, 39],
3056
+ yellowBright: [93, 39],
3057
+ blueBright: [94, 39],
3058
+ magentaBright: [95, 39],
3059
+ cyanBright: [96, 39],
3060
+ whiteBright: [97, 39]
3061
+ },
3062
+ bgColor: {
3063
+ bgBlack: [40, 49],
3064
+ bgRed: [41, 49],
3065
+ bgGreen: [42, 49],
3066
+ bgYellow: [43, 49],
3067
+ bgBlue: [44, 49],
3068
+ bgMagenta: [45, 49],
3069
+ bgCyan: [46, 49],
3070
+ bgWhite: [47, 49],
3071
+ bgBlackBright: [100, 49],
3072
+ bgGray: [100, 49],
3073
+ bgGrey: [100, 49],
3074
+ bgRedBright: [101, 49],
3075
+ bgGreenBright: [102, 49],
3076
+ bgYellowBright: [103, 49],
3077
+ bgBlueBright: [104, 49],
3078
+ bgMagentaBright: [105, 49],
3079
+ bgCyanBright: [106, 49],
3080
+ bgWhiteBright: [107, 49]
3081
+ }
3082
+ };
3083
+ Object.keys(styles$1.modifier);
3084
+ var foregroundColorNames = Object.keys(styles$1.color);
3085
+ var backgroundColorNames = Object.keys(styles$1.bgColor);
3086
+ [...foregroundColorNames, ...backgroundColorNames];
3087
+ function assembleStyles() {
3088
+ const codes = /* @__PURE__ */ new Map();
3089
+ for (const [groupName, group] of Object.entries(styles$1)) {
3090
+ for (const [styleName, style] of Object.entries(group)) {
3091
+ styles$1[styleName] = {
3092
+ open: `\u001B[${style[0]}m`,
3093
+ close: `\u001B[${style[1]}m`
3094
+ };
3095
+ group[styleName] = styles$1[styleName];
3096
+ codes.set(style[0], style[1]);
3097
+ }
3098
+ Object.defineProperty(styles$1, groupName, {
3099
+ value: group,
3100
+ enumerable: false
3101
+ });
3102
+ }
3103
+ Object.defineProperty(styles$1, "codes", {
3104
+ value: codes,
3105
+ enumerable: false
3106
+ });
3107
+ styles$1.color.close = "\x1B[39m";
3108
+ styles$1.bgColor.close = "\x1B[49m";
3109
+ styles$1.color.ansi = wrapAnsi16();
3110
+ styles$1.color.ansi256 = wrapAnsi256();
3111
+ styles$1.color.ansi16m = wrapAnsi16m();
3112
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3113
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3114
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3115
+ Object.defineProperties(styles$1, {
3116
+ rgbToAnsi256: {
3117
+ value(red, green, blue) {
3118
+ if (red === green && green === blue) {
3119
+ if (red < 8) return 16;
3120
+ if (red > 248) return 231;
3121
+ return Math.round((red - 8) / 247 * 24) + 232;
3122
+ }
3123
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3124
+ },
3125
+ enumerable: false
3126
+ },
3127
+ hexToRgb: {
3128
+ value(hex) {
3129
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3130
+ if (!matches) return [
3131
+ 0,
3132
+ 0,
3133
+ 0
3134
+ ];
3135
+ let [colorString] = matches;
3136
+ if (colorString.length === 3) colorString = [...colorString].map((character) => character + character).join("");
3137
+ const integer = Number.parseInt(colorString, 16);
3138
+ return [
3139
+ integer >> 16 & 255,
3140
+ integer >> 8 & 255,
3141
+ integer & 255
3142
+ ];
3143
+ },
3144
+ enumerable: false
3145
+ },
3146
+ hexToAnsi256: {
3147
+ value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
3148
+ enumerable: false
3149
+ },
3150
+ ansi256ToAnsi: {
3151
+ value(code) {
3152
+ if (code < 8) return 30 + code;
3153
+ if (code < 16) return 90 + (code - 8);
3154
+ let red;
3155
+ let green;
3156
+ let blue;
3157
+ if (code >= 232) {
3158
+ red = ((code - 232) * 10 + 8) / 255;
3159
+ green = red;
3160
+ blue = red;
3161
+ } else {
3162
+ code -= 16;
3163
+ const remainder = code % 36;
3164
+ red = Math.floor(code / 36) / 5;
3165
+ green = Math.floor(remainder / 6) / 5;
3166
+ blue = remainder % 6 / 5;
3167
+ }
3168
+ const value = Math.max(red, green, blue) * 2;
3169
+ if (value === 0) return 30;
3170
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3171
+ if (value === 2) result += 60;
3172
+ return result;
3173
+ },
3174
+ enumerable: false
3175
+ },
3176
+ rgbToAnsi: {
3177
+ value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
3178
+ enumerable: false
3179
+ },
3180
+ hexToAnsi: {
3181
+ value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
3182
+ enumerable: false
3183
+ }
3184
+ });
3185
+ return styles$1;
3186
+ }
3187
+ var ansiStyles = assembleStyles();
3188
+ //#endregion
3189
+ //#region node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
3190
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : node_process.default.argv) {
3191
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3192
+ const position = argv.indexOf(prefix + flag);
3193
+ const terminatorPosition = argv.indexOf("--");
3194
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3195
+ }
3196
+ var { env } = node_process.default;
3197
+ var flagForceColor;
3198
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
3199
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
3200
+ function envForceColor() {
3201
+ if ("FORCE_COLOR" in env) {
3202
+ if (env.FORCE_COLOR === "true") return 1;
3203
+ if (env.FORCE_COLOR === "false") return 0;
3204
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3205
+ }
3206
+ }
3207
+ function translateLevel(level) {
3208
+ if (level === 0) return false;
3209
+ return {
3210
+ level,
3211
+ hasBasic: true,
3212
+ has256: level >= 2,
3213
+ has16m: level >= 3
3214
+ };
3215
+ }
3216
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3217
+ const noFlagForceColor = envForceColor();
3218
+ if (noFlagForceColor !== void 0) flagForceColor = noFlagForceColor;
3219
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3220
+ if (forceColor === 0) return 0;
3221
+ if (sniffFlags) {
3222
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
3223
+ if (hasFlag("color=256")) return 2;
3224
+ }
3225
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) return 1;
3226
+ if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
3227
+ const min = forceColor || 0;
3228
+ if (env.TERM === "dumb") return min;
3229
+ if (node_process.default.platform === "win32") {
3230
+ const osRelease = node_os.default.release().split(".");
3231
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
3232
+ return 1;
3233
+ }
3234
+ if ("CI" in env) {
3235
+ if ([
3236
+ "GITHUB_ACTIONS",
3237
+ "GITEA_ACTIONS",
3238
+ "CIRCLECI"
3239
+ ].some((key) => key in env)) return 3;
3240
+ if ([
3241
+ "TRAVIS",
3242
+ "APPVEYOR",
3243
+ "GITLAB_CI",
3244
+ "BUILDKITE",
3245
+ "DRONE"
3246
+ ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
3247
+ return min;
3248
+ }
3249
+ if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3250
+ if (env.COLORTERM === "truecolor") return 3;
3251
+ if (env.TERM === "xterm-kitty") return 3;
3252
+ if (env.TERM === "xterm-ghostty") return 3;
3253
+ if (env.TERM === "wezterm") return 3;
3254
+ if ("TERM_PROGRAM" in env) {
3255
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3256
+ switch (env.TERM_PROGRAM) {
3257
+ case "iTerm.app": return version >= 3 ? 3 : 2;
3258
+ case "Apple_Terminal": return 2;
3259
+ }
3260
+ }
3261
+ if (/-256(color)?$/i.test(env.TERM)) return 2;
3262
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
3263
+ if ("COLORTERM" in env) return 1;
3264
+ return min;
3265
+ }
3266
+ function createSupportsColor(stream, options = {}) {
3267
+ return translateLevel(_supportsColor(stream, {
3268
+ streamIsTTY: stream && stream.isTTY,
3269
+ ...options
3270
+ }));
3271
+ }
3272
+ var supportsColor = {
3273
+ stdout: createSupportsColor({ isTTY: node_tty.default.isatty(1) }),
3274
+ stderr: createSupportsColor({ isTTY: node_tty.default.isatty(2) })
3275
+ };
3276
+ //#endregion
3277
+ //#region node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
3278
+ function stringReplaceAll(string, substring, replacer) {
3279
+ let index = string.indexOf(substring);
3280
+ if (index === -1) return string;
3281
+ const substringLength = substring.length;
3282
+ let endIndex = 0;
3283
+ let returnValue = "";
3284
+ do {
3285
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3286
+ endIndex = index + substringLength;
3287
+ index = string.indexOf(substring, endIndex);
3288
+ } while (index !== -1);
3289
+ returnValue += string.slice(endIndex);
3290
+ return returnValue;
3291
+ }
3292
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3293
+ let endIndex = 0;
3294
+ let returnValue = "";
3295
+ do {
3296
+ const gotCR = string[index - 1] === "\r";
3297
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3298
+ endIndex = index + 1;
3299
+ index = string.indexOf("\n", endIndex);
3300
+ } while (index !== -1);
3301
+ returnValue += string.slice(endIndex);
3302
+ return returnValue;
3303
+ }
3304
+ //#endregion
3305
+ //#region node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
3306
+ var { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
3307
+ var GENERATOR = Symbol("GENERATOR");
3308
+ var STYLER = Symbol("STYLER");
3309
+ var IS_EMPTY = Symbol("IS_EMPTY");
3310
+ var levelMapping = [
3311
+ "ansi",
3312
+ "ansi",
3313
+ "ansi256",
3314
+ "ansi16m"
3315
+ ];
3316
+ var styles = Object.create(null);
3317
+ var applyOptions = (object, options = {}) => {
3318
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) throw new Error("The `level` option should be an integer from 0 to 3");
3319
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3320
+ object.level = options.level === void 0 ? colorLevel : options.level;
3321
+ };
3322
+ var chalkFactory = (options) => {
3323
+ const chalk = (...strings) => strings.join(" ");
3324
+ applyOptions(chalk, options);
3325
+ Object.setPrototypeOf(chalk, createChalk.prototype);
3326
+ return chalk;
3327
+ };
3328
+ function createChalk(options) {
3329
+ return chalkFactory(options);
3330
+ }
3331
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3332
+ for (const [styleName, style] of Object.entries(ansiStyles)) styles[styleName] = { get() {
3333
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3334
+ Object.defineProperty(this, styleName, { value: builder });
3335
+ return builder;
3336
+ } };
3337
+ styles.visible = { get() {
3338
+ const builder = createBuilder(this, this[STYLER], true);
3339
+ Object.defineProperty(this, "visible", { value: builder });
3340
+ return builder;
3341
+ } };
3342
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3343
+ if (model === "rgb") {
3344
+ if (level === "ansi16m") return ansiStyles[type].ansi16m(...arguments_);
3345
+ if (level === "ansi256") return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
3346
+ return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
3347
+ }
3348
+ if (model === "hex") return getModelAnsi("rgb", level, type, ...ansiStyles.hexToRgb(...arguments_));
3349
+ return ansiStyles[type][model](...arguments_);
3350
+ };
3351
+ for (const model of [
3352
+ "rgb",
3353
+ "hex",
3354
+ "ansi256"
3355
+ ]) {
3356
+ styles[model] = { get() {
3357
+ const { level } = this;
3358
+ return function(...arguments_) {
3359
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansiStyles.color.close, this[STYLER]);
3360
+ return createBuilder(this, styler, this[IS_EMPTY]);
3361
+ };
3362
+ } };
3363
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3364
+ styles[bgModel] = { get() {
3365
+ const { level } = this;
3366
+ return function(...arguments_) {
3367
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
3368
+ return createBuilder(this, styler, this[IS_EMPTY]);
3369
+ };
3370
+ } };
3371
+ }
3372
+ var proto = Object.defineProperties(() => {}, {
3373
+ ...styles,
3374
+ level: {
3375
+ enumerable: true,
3376
+ get() {
3377
+ return this[GENERATOR].level;
3378
+ },
3379
+ set(level) {
3380
+ this[GENERATOR].level = level;
3381
+ }
3382
+ }
3383
+ });
3384
+ var createStyler = (open, close, parent) => {
3385
+ let openAll;
3386
+ let closeAll;
3387
+ if (parent === void 0) {
3388
+ openAll = open;
3389
+ closeAll = close;
3390
+ } else {
3391
+ openAll = parent.openAll + open;
3392
+ closeAll = close + parent.closeAll;
3393
+ }
3394
+ return {
3395
+ open,
3396
+ close,
3397
+ openAll,
3398
+ closeAll,
3399
+ parent
3400
+ };
3401
+ };
3402
+ var createBuilder = (self, _styler, _isEmpty) => {
3403
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3404
+ Object.setPrototypeOf(builder, proto);
3405
+ builder[GENERATOR] = self;
3406
+ builder[STYLER] = _styler;
3407
+ builder[IS_EMPTY] = _isEmpty;
3408
+ return builder;
3409
+ };
3410
+ var applyStyle = (self, string) => {
3411
+ if (self.level <= 0 || !string) return self[IS_EMPTY] ? "" : string;
3412
+ let styler = self[STYLER];
3413
+ if (styler === void 0) return string;
3414
+ const { openAll, closeAll } = styler;
3415
+ if (string.includes("\x1B")) while (styler !== void 0) {
3416
+ string = stringReplaceAll(string, styler.close, styler.open);
3417
+ styler = styler.parent;
3418
+ }
3419
+ const lfIndex = string.indexOf("\n");
3420
+ if (lfIndex !== -1) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3421
+ return openAll + string + closeAll;
3422
+ };
3423
+ Object.defineProperties(createChalk.prototype, styles);
3424
+ var chalk = createChalk();
3425
+ createChalk({ level: stderrColor ? stderrColor.level : 0 });
3426
+ //#endregion
3427
+ //#region src/lib/filewalker/index.ts
3428
+ /**
3429
+ * Walks a directory recursively (or processes a single file) and returns an array of file paths
3430
+ * matching the given extensions.
3431
+ */
3432
+ function fileWalker(inputPath, extensions) {
3433
+ const filePaths = [];
3434
+ const absolutePath = path.default.resolve(inputPath);
3435
+ let stats;
3436
+ try {
3437
+ stats = fs.default.lstatSync(absolutePath);
3438
+ } catch (err) {
3439
+ const error = err;
3440
+ console.error(chalk.red(`Error: ${error.message}`));
3441
+ return filePaths;
3442
+ }
3443
+ const rootDir = process.cwd();
3444
+ if (stats.isFile()) {
3445
+ const ext = path.default.extname(absolutePath).toLowerCase();
3446
+ if (extensions.includes(ext)) filePaths.push(path.default.relative(rootDir, absolutePath));
3447
+ return filePaths;
3448
+ } else if (stats.isDirectory()) {} else return filePaths;
3449
+ function walk(currentPath) {
3450
+ const files = fs.default.readdirSync(currentPath);
3451
+ for (const file of files) {
3452
+ const filePath = path.default.join(currentPath, file);
3453
+ const fileStats = fs.default.lstatSync(filePath);
3454
+ if (fileStats.isSymbolicLink()) continue;
3455
+ if (fileStats.isDirectory()) walk(filePath);
3456
+ else if (fileStats.isFile()) {
3457
+ const ext = path.default.extname(filePath).toLowerCase();
3458
+ if (extensions.includes(ext)) filePaths.push(path.default.relative(rootDir, filePath));
3459
+ }
3460
+ }
3461
+ }
3462
+ walk(absolutePath);
3463
+ return filePaths;
3464
+ }
3465
+ //#endregion
3466
+ //#region src/versions/backend.ts
3467
+ var KULALA_CORE_VERSION = "0.17.0";
3468
+ //#endregion
3469
+ //#region src/lib/downloader/index.ts
3470
+ var BINARY_NAME = "kulala-core";
3471
+ var DOWNLOAD_URL = "https://github.com/mistweaverco/kulala-core/releases/download/v%s/%s";
3472
+ function platform() {
3473
+ const os = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux";
3474
+ const arch = process.arch;
3475
+ let archName = arch;
3476
+ if (arch === "x64") archName = "x86_64";
3477
+ else if (arch === "arm64") archName = os === "darwin" ? "arm64" : "aarch64";
3478
+ return `${os}-${archName}`;
3479
+ }
3480
+ function getBinDir() {
3481
+ return path.default.join(__dirname, "bin");
3482
+ }
3483
+ function getReleaseBinName() {
3484
+ const name = `${BINARY_NAME}-${platform()}`;
3485
+ return process.platform === "win32" ? `${name}.exe` : name;
3486
+ }
3487
+ function getBinName() {
3488
+ return process.platform === "win32" ? `${BINARY_NAME}.exe` : BINARY_NAME;
3489
+ }
3490
+ function getBinPath() {
3491
+ return path.default.join(getBinDir(), getBinName());
3492
+ }
3493
+ function getVersionPath() {
3494
+ return path.default.join(getBinDir(), "version.txt");
3495
+ }
3496
+ function binaryExists() {
3497
+ return fs.default.existsSync(getBinPath());
3498
+ }
3499
+ function getInstalledVersion() {
3500
+ const versionPath = getVersionPath();
3501
+ if (!fs.default.existsSync(versionPath)) return null;
3502
+ return fs.default.readFileSync(versionPath, "utf-8").trim();
3503
+ }
3504
+ function versionMatches() {
3505
+ return getInstalledVersion() === KULALA_CORE_VERSION;
3506
+ }
3507
+ function makeExecutable(filePath) {
3508
+ if (process.platform !== "win32") (0, fs.chmodSync)(filePath, 493);
3509
+ }
3510
+ var SPINNER_FRAMES = [
3511
+ "⠋",
3512
+ "⠙",
3513
+ "⠹",
3514
+ "⠸",
3515
+ "⠼",
3516
+ "⠴",
3517
+ "⠦",
3518
+ "⠧",
3519
+ "⠇",
3520
+ "⠏"
3521
+ ];
3522
+ function isInteractiveTerminal() {
3523
+ return process.stderr.isTTY === true;
3524
+ }
3525
+ function createDownloadProgress() {
3526
+ let timer;
3527
+ let frame = 0;
3528
+ let message = "";
3529
+ const clearLine = () => {
3530
+ if (timer) {
3531
+ clearInterval(timer);
3532
+ timer = void 0;
3533
+ }
3534
+ if (isInteractiveTerminal()) process.stderr.write("\r\x1B[K");
3535
+ };
3536
+ return {
3537
+ start(msg) {
3538
+ message = msg;
3539
+ if (!isInteractiveTerminal()) {
3540
+ console.error(message);
3541
+ return;
3542
+ }
3543
+ const render = () => {
3544
+ process.stderr.write(`\r${SPINNER_FRAMES[frame]} ${message}`);
3545
+ frame = (frame + 1) % SPINNER_FRAMES.length;
3546
+ };
3547
+ render();
3548
+ timer = setInterval(render, 80);
3549
+ },
3550
+ succeed(msg) {
3551
+ clearLine();
3552
+ console.error(msg);
3553
+ },
3554
+ fail() {
3555
+ clearLine();
3556
+ }
3557
+ };
3558
+ }
3559
+ async function downloadFile(url, outputPath) {
3560
+ const response = await fetch(url);
3561
+ if (!response.ok || !response.body) throw new Error(`Failed to download kulala-core from ${url}: ${response.status} ${response.statusText}`);
3562
+ await (0, stream_promises.pipeline)(response.body, (0, fs.createWriteStream)(outputPath));
3563
+ }
3564
+ function removeStaleBinary() {
3565
+ if (!binaryExists()) return;
3566
+ fs.default.unlinkSync(getBinPath());
3567
+ const versionPath = getVersionPath();
3568
+ if (fs.default.existsSync(versionPath)) fs.default.unlinkSync(versionPath);
3569
+ }
3570
+ async function installBackend() {
3571
+ const binDir = getBinDir();
3572
+ fs.default.mkdirSync(binDir, { recursive: true });
3573
+ const releaseName = getReleaseBinName();
3574
+ const url = DOWNLOAD_URL.replace("%s", KULALA_CORE_VERSION).replace("%s", releaseName);
3575
+ const downloadPath = path.default.join(binDir, `${releaseName}.download`);
3576
+ const binPath = getBinPath();
3577
+ const progress = createDownloadProgress();
3578
+ progress.start(`Downloading kulala-core v${KULALA_CORE_VERSION}...`);
3579
+ try {
3580
+ await downloadFile(url, downloadPath);
3581
+ makeExecutable(downloadPath);
3582
+ fs.default.renameSync(downloadPath, binPath);
3583
+ fs.default.writeFileSync(getVersionPath(), KULALA_CORE_VERSION, "utf-8");
3584
+ progress.succeed(`Installed kulala-core to ${binPath}`);
3585
+ } catch (error) {
3586
+ progress.fail();
3587
+ throw error;
3588
+ }
3589
+ }
3590
+ /**
3591
+ * Best-effort install for lifecycle scripts (postinstall/prepare).
3592
+ * Never throws; logs a warning when download fails so first-use fallback can run.
3593
+ */
3594
+ async function tryInstallBackend() {
3595
+ const fromEnv = process.env.KULALA_CORE_PATH;
3596
+ if (fromEnv && fromEnv.length > 0) return;
3597
+ if (binaryExists() && versionMatches()) return;
3598
+ if (binaryExists()) removeStaleBinary();
3599
+ try {
3600
+ await installBackend();
3601
+ } catch (error) {
3602
+ const message = error instanceof Error ? error.message : String(error);
3603
+ console.error(`Warning: failed to download kulala-core during install: ${message}`);
3604
+ console.error("kulala-cli will attempt to download it on first use instead.");
3605
+ }
3606
+ }
3607
+ async function ensureInstalled() {
3608
+ const fromEnv = process.env.KULALA_CORE_PATH;
3609
+ if (fromEnv && fromEnv.length > 0) {
3610
+ if (!fs.default.existsSync(fromEnv)) throw new Error(`KULALA_CORE_PATH does not exist: ${fromEnv}`);
3611
+ return fromEnv;
3612
+ }
3613
+ if (binaryExists() && versionMatches()) return getBinPath();
3614
+ if (binaryExists()) removeStaleBinary();
3615
+ await installBackend();
3616
+ return getBinPath();
3617
+ }
3618
+ var downloader = {
3619
+ ensureInstalled,
3620
+ getBinPath,
3621
+ installBackend,
3622
+ tryInstallBackend
3623
+ };
3624
+ //#endregion
3625
+ //#region src/lib/kulala-core/index.ts
3626
+ var cachedExecutable = null;
3627
+ async function executablePath() {
3628
+ if (!cachedExecutable) cachedExecutable = await downloader.ensureInstalled();
3629
+ return cachedExecutable;
3630
+ }
3631
+ function invoke(payload, options = {}) {
3632
+ const exe = cachedExecutable;
3633
+ if (!exe) throw new Error("kulala-core executable not resolved");
3634
+ const result = (0, node_child_process.spawnSync)(exe, [], {
3635
+ input: `${JSON.stringify(payload)}\n`,
3636
+ encoding: "utf-8",
3637
+ maxBuffer: 50 * 1024 * 1024,
3638
+ cwd: options.cwd,
3639
+ env: process.env
3640
+ });
3641
+ if (result.error) throw result.error;
3642
+ if (result.status !== 0) throw new Error(result.stderr?.trim() || `kulala-core exited with code ${result.status ?? "unknown"}`);
3643
+ const stdout = result.stdout?.trim();
3644
+ if (!stdout) throw new Error("kulala-core returned empty output");
3645
+ return JSON.parse(stdout);
3646
+ }
3647
+ async function runHttp(options, invokeOptions = {}) {
3648
+ await executablePath();
3649
+ return invoke({
3650
+ action: "run",
3651
+ content: options.content,
3652
+ filepath: options.filepath,
3653
+ env: options.env,
3654
+ limit: options.limit,
3655
+ haltOnError: options.haltOnError
3656
+ }, invokeOptions);
3657
+ }
3658
+ var kulalaCore = { runHttp };
3659
+ //#endregion
3660
+ //#region src/lib/output/human.ts
3661
+ var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3662
+ var p = process || {}, argv = p.argv || [], env = p.env || {};
3663
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
3664
+ var formatter = (open, close, replace = open) => (input) => {
3665
+ let string = "" + input, index = string.indexOf(close, open.length);
3666
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
3667
+ };
3668
+ var replaceClose = (string, close, replace, index) => {
3669
+ let result = "", cursor = 0;
3670
+ do {
3671
+ result += string.substring(cursor, index) + replace;
3672
+ cursor = index + close.length;
3673
+ index = string.indexOf(close, cursor);
3674
+ } while (~index);
3675
+ return result + string.substring(cursor);
3676
+ };
3677
+ var createColors = (enabled = isColorSupported) => {
3678
+ let f = enabled ? formatter : () => String;
3679
+ return {
3680
+ isColorSupported: enabled,
3681
+ reset: f("\x1B[0m", "\x1B[0m"),
3682
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
3683
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
3684
+ italic: f("\x1B[3m", "\x1B[23m"),
3685
+ underline: f("\x1B[4m", "\x1B[24m"),
3686
+ inverse: f("\x1B[7m", "\x1B[27m"),
3687
+ hidden: f("\x1B[8m", "\x1B[28m"),
3688
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
3689
+ black: f("\x1B[30m", "\x1B[39m"),
3690
+ red: f("\x1B[31m", "\x1B[39m"),
3691
+ green: f("\x1B[32m", "\x1B[39m"),
3692
+ yellow: f("\x1B[33m", "\x1B[39m"),
3693
+ blue: f("\x1B[34m", "\x1B[39m"),
3694
+ magenta: f("\x1B[35m", "\x1B[39m"),
3695
+ cyan: f("\x1B[36m", "\x1B[39m"),
3696
+ white: f("\x1B[37m", "\x1B[39m"),
3697
+ gray: f("\x1B[90m", "\x1B[39m"),
3698
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
3699
+ bgRed: f("\x1B[41m", "\x1B[49m"),
3700
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
3701
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
3702
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
3703
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
3704
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
3705
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
3706
+ blackBright: f("\x1B[90m", "\x1B[39m"),
3707
+ redBright: f("\x1B[91m", "\x1B[39m"),
3708
+ greenBright: f("\x1B[92m", "\x1B[39m"),
3709
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
3710
+ blueBright: f("\x1B[94m", "\x1B[39m"),
3711
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
3712
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
3713
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
3714
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
3715
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
3716
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
3717
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
3718
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
3719
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
3720
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
3721
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3722
+ };
3723
+ };
3724
+ module.exports = createColors();
3725
+ module.exports.createColors = createColors;
3726
+ })))(), 1);
3727
+ function isPromptResponse$1(item) {
3728
+ return "prompt" in item && item.prompt === true;
3729
+ }
3730
+ function isSkippedResponse$1(item) {
3731
+ return "skipped" in item && item.skipped === true;
3732
+ }
3733
+ function isWebSocketResponse$1(item) {
3734
+ return "protocol" in item && item.protocol === "websocket";
3735
+ }
3736
+ function isErrorResponse$1(item) {
3737
+ return item.success === false && !isPromptResponse$1(item);
3738
+ }
3739
+ function isSuccessResponse$1(item) {
3740
+ return item.success === true && !isSkippedResponse$1(item) && !isWebSocketResponse$1(item);
3741
+ }
3742
+ function responseBodyText(body) {
3743
+ if (!body) return "";
3744
+ if (body.type === "json") return body.formatted ?? JSON.stringify(body.content, null, 2);
3745
+ return body.content;
3746
+ }
3747
+ function statusColor(status) {
3748
+ if (status >= 200 && status < 300) return import_picocolors.default.green;
3749
+ if (status >= 300 && status < 400) return import_picocolors.default.yellow;
3750
+ return import_picocolors.default.red;
3751
+ }
3752
+ function formatHeaders(headers) {
3753
+ return Object.entries(headers).map(([name, value]) => `${name}: ${value}`).join("\n");
3754
+ }
3755
+ function formatScriptConsole(lines) {
3756
+ if (!lines?.length) return "";
3757
+ return lines.map((line) => {
3758
+ return `${line.level === "error" ? import_picocolors.default.red("[error]") : line.level === "warn" ? import_picocolors.default.yellow("[warn]") : import_picocolors.default.dim(`[${line.level}]`)} ${line.message}`;
3759
+ }).join("\n");
3760
+ }
3761
+ function formatMs(ms) {
3762
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
3763
+ return `${(ms / 1e3).toFixed(2)}s`;
3764
+ }
3765
+ function formatItem(item) {
3766
+ if (isPromptResponse$1(item)) {
3767
+ const parts = [import_picocolors.default.yellow(`Prompt (${item.promptType}): ${item.message}`)];
3768
+ for (const input of item.inputs) parts.push(` - ${input.label} (${input.type}${input.required ? ", required" : ""})`);
3769
+ return parts.join("\n");
3770
+ }
3771
+ if (isSkippedResponse$1(item)) {
3772
+ const parts = [import_picocolors.default.dim(`Skipped${item.blockName ? ` [${item.blockName}]` : ""}`)];
3773
+ if (item.scriptConsole?.length) parts.push(formatScriptConsole(item.scriptConsole));
3774
+ return parts.join("\n");
3775
+ }
3776
+ if (isWebSocketResponse$1(item)) {
3777
+ const parts = [import_picocolors.default.cyan(`WebSocket: ${item.url}`)];
3778
+ if (item.initialMessage) parts.push(import_picocolors.default.dim(`Initial message: ${item.initialMessage}`));
3779
+ return parts.join("\n");
3780
+ }
3781
+ if (isErrorResponse$1(item)) {
3782
+ const parts = [import_picocolors.default.red(`Error${item.blockName ? ` [${item.blockName}]` : ""}: ${item.error}`)];
3783
+ if (item.url) parts.push(import_picocolors.default.dim(`${item.request?.method ?? "GET"} ${item.url}`));
3784
+ if (item.status !== void 0) parts.push(statusColor(item.status)(`HTTP ${item.status}`));
3785
+ if (item.body) {
3786
+ parts.push("");
3787
+ parts.push(responseBodyText(item.body));
3788
+ }
3789
+ if (item.scriptConsole?.length) {
3790
+ parts.push("");
3791
+ parts.push(formatScriptConsole(item.scriptConsole));
3792
+ }
3793
+ return parts.join("\n");
3794
+ }
3795
+ if (isSuccessResponse$1(item)) {
3796
+ const method = item.request?.method ?? "GET";
3797
+ const statusLabel = item.status >= 200 && item.status < 300 ? statusColor(item.status)(`HTTP ${item.status}`) : import_picocolors.default.green(`HTTP ${item.status}`);
3798
+ const parts = [`${import_picocolors.default.bold(method)} ${item.url}${item.blockName ? import_picocolors.default.dim(` [${item.blockName}]`) : ""}`, statusLabel];
3799
+ if (item.timings?.total !== void 0) parts.push(import_picocolors.default.dim(`Duration: ${formatMs(item.timings.total)}`));
3800
+ if (Object.keys(item.headers).length > 0) {
3801
+ parts.push("");
3802
+ parts.push(import_picocolors.default.dim(formatHeaders(item.headers)));
3803
+ }
3804
+ const bodyText = responseBodyText(item.filteredBody ?? item.body);
3805
+ if (bodyText) {
3806
+ parts.push("");
3807
+ parts.push(bodyText);
3808
+ }
3809
+ if (item.scriptConsole?.length) {
3810
+ parts.push("");
3811
+ parts.push(formatScriptConsole(item.scriptConsole));
3812
+ }
3813
+ return parts.join("\n");
3814
+ }
3815
+ return import_picocolors.default.dim("Unknown response type");
3816
+ }
3817
+ function formatWrapper(wrapper) {
3818
+ return (wrapper.type === "error" ? wrapper.data : wrapper.data).map((entry) => formatItem(entry)).join("\n\n");
3819
+ }
3820
+ function printHumanReadable(results) {
3821
+ const blocks = results.map((result) => {
3822
+ return `${results.length > 1 ? import_picocolors.default.bold(`# ${result.filepath}\n`) : ""}${formatWrapper(result.response)}`;
3823
+ });
3824
+ console.log(blocks.join("\n\n"));
3825
+ }
3826
+ function printJson(results) {
3827
+ const payload = results.length === 1 ? results[0].response : results;
3828
+ console.log(JSON.stringify(payload, null, 2));
3829
+ }
3830
+ function isResponseSuccessful(item) {
3831
+ if (isPromptResponse$1(item)) return false;
3832
+ return item.success === true;
3833
+ }
3834
+ function filterFailedWrapper(wrapper) {
3835
+ const failed = (wrapper.type === "error" ? wrapper.data : wrapper.data).filter((item) => !isResponseSuccessful(item));
3836
+ if (failed.length === 0) return null;
3837
+ return {
3838
+ type: "responses",
3839
+ data: failed
3840
+ };
3841
+ }
3842
+ function filterFailedResults(results) {
3843
+ return results.flatMap((result) => {
3844
+ const filtered = filterFailedWrapper(result.response);
3845
+ if (!filtered) return [];
3846
+ return [{
3847
+ filepath: result.filepath,
3848
+ response: filtered
3849
+ }];
3850
+ });
3851
+ }
3852
+ function countResults(wrapper) {
3853
+ const items = wrapper.type === "error" ? wrapper.data : wrapper.data;
3854
+ let success = 0;
3855
+ let failed = 0;
3856
+ for (const item of items) if (isResponseSuccessful(item)) success += 1;
3857
+ else failed += 1;
3858
+ return {
3859
+ total: items.length,
3860
+ success,
3861
+ failed
3862
+ };
3863
+ }
3864
+ //#endregion
3865
+ //#region src/lib/output/report.ts
3866
+ function isPromptResponse(item) {
3867
+ return "prompt" in item && item.prompt === true;
3868
+ }
3869
+ function isSkippedResponse(item) {
3870
+ return "skipped" in item && item.skipped === true;
3871
+ }
3872
+ function isWebSocketResponse(item) {
3873
+ return "protocol" in item && item.protocol === "websocket";
3874
+ }
3875
+ function isErrorResponse(item) {
3876
+ return item.success === false && !isPromptResponse(item);
3877
+ }
3878
+ function isSuccessResponse(item) {
3879
+ return item.success === true && !isSkippedResponse(item) && !isWebSocketResponse(item);
3880
+ }
3881
+ function escapeCell(value) {
3882
+ return value.replace(/\|/g, "\\|").replace(/\n/g, " ");
3883
+ }
3884
+ function mdTable(rows) {
3885
+ if (rows.length === 0) return "";
3886
+ const header = rows[0];
3887
+ const separator = header.map(() => "---");
3888
+ const body = rows.slice(1);
3889
+ const formatRow = (row) => `| ${row.join(" | ")} |`;
3890
+ return [
3891
+ formatRow(header),
3892
+ formatRow(separator),
3893
+ ...body.map(formatRow)
3894
+ ].join("\n");
3895
+ }
3896
+ function itemTitle(item) {
3897
+ if (isPromptResponse(item)) return `Prompt: ${item.promptType}`;
3898
+ if (isSkippedResponse(item)) return item.blockName ? `Skipped — ${item.blockName}` : "Skipped";
3899
+ if (isWebSocketResponse(item)) return `WebSocket — ${item.url}`;
3900
+ if (isErrorResponse(item)) return `${item.request?.method ?? "REQUEST"} ${item.url ?? item.blockName ?? "unknown"}`;
3901
+ if (isSuccessResponse(item)) return `${item.request?.method ?? "GET"} ${item.url}`;
3902
+ return "Unknown request";
3903
+ }
3904
+ function formatScriptSection(item) {
3905
+ if (!("scriptConsole" in item) || !item.scriptConsole?.length) return "";
3906
+ return `#### Script output\n\n${item.scriptConsole.map((line) => `- **${line.level.toUpperCase()}** ${escapeCell(line.message)}`).join("\n")}\n`;
3907
+ }
3908
+ function formatItemSection(item) {
3909
+ const parts = [`## ${escapeCell(itemTitle(item))}\n`];
3910
+ const rows = [["Field", "Value"]];
3911
+ if ("blockName" in item && item.blockName) rows.push(["Block", escapeCell(item.blockName)]);
3912
+ if (isErrorResponse(item)) {
3913
+ rows.push(["Error", escapeCell(item.error)]);
3914
+ if (item.url) rows.push(["URL", escapeCell(item.url)]);
3915
+ if (item.status !== void 0) rows.push(["Status", String(item.status)]);
3916
+ } else if (isPromptResponse(item)) rows.push(["Message", escapeCell(item.message)]);
3917
+ else if (isWebSocketResponse(item)) rows.push(["URL", escapeCell(item.url)]);
3918
+ else if (isSkippedResponse(item)) rows.push(["Status", "skipped"]);
3919
+ else if (isSuccessResponse(item)) {
3920
+ rows.push(["URL", escapeCell(item.url)]);
3921
+ rows.push(["Status", String(item.status)]);
3922
+ if (item.timings?.total !== void 0) rows.push(["Duration", formatMs(item.timings.total)]);
3923
+ }
3924
+ parts.push(mdTable(rows));
3925
+ parts.push("");
3926
+ if ("body" in item && item.body) {
3927
+ const text = responseBodyText("filteredBody" in item && item.filteredBody ? item.filteredBody : item.body);
3928
+ if (text) {
3929
+ parts.push("#### Response body\n");
3930
+ parts.push("```");
3931
+ parts.push(text);
3932
+ parts.push("```");
3933
+ parts.push("");
3934
+ }
3935
+ }
3936
+ const script = formatScriptSection(item);
3937
+ if (script) parts.push(script);
3938
+ return parts.join("\n");
3939
+ }
3940
+ function formatSummary(stats) {
3941
+ return `## Summary\n\n${mdTable([[
3942
+ "",
3943
+ "Total",
3944
+ "Successful",
3945
+ "Failed"
3946
+ ], [
3947
+ "Requests",
3948
+ String(stats.total),
3949
+ String(stats.success),
3950
+ String(stats.failed)
3951
+ ]])}\n`;
3952
+ }
3953
+ function printReport(results) {
3954
+ const parts = ["# Requests report\n"];
3955
+ const stats = {
3956
+ total: 0,
3957
+ success: 0,
3958
+ failed: 0
3959
+ };
3960
+ for (const result of results) {
3961
+ if (results.length > 1) parts.push(`### File: ${result.filepath}\n`);
3962
+ const items = result.response.type === "error" ? result.response.data : result.response.data;
3963
+ for (const item of items) {
3964
+ parts.push(formatItemSection(item));
3965
+ stats.total += 1;
3966
+ if (isResponseSuccessful(item)) stats.success += 1;
3967
+ else stats.failed += 1;
3968
+ }
3969
+ }
3970
+ parts.push(formatSummary(stats));
3971
+ console.log(parts.join("\n"));
3972
+ }
3973
+ //#endregion
3974
+ //#region src/lib/runner/limit.ts
3975
+ function buildRunLimit(options) {
3976
+ const hasName = options.name !== void 0 && options.name.length > 0;
3977
+ const hasLine = options.line !== void 0;
3978
+ const hasColumn = options.column !== void 0;
3979
+ if (hasName && (hasLine || hasColumn)) {
3980
+ console.error(chalk.red("Cannot use --name together with --line/--column"));
3981
+ process.exit(1);
3982
+ }
3983
+ if (hasColumn && !hasLine) {
3984
+ console.error(chalk.red("--column requires --line"));
3985
+ process.exit(1);
3986
+ }
3987
+ if (hasName) return [{
3988
+ filter: "name",
3989
+ name: options.name
3990
+ }];
3991
+ if (hasLine) {
3992
+ const line = options.line;
3993
+ if (!Number.isInteger(line) || line < 1) {
3994
+ console.error(chalk.red("--line must be a positive integer"));
3995
+ process.exit(1);
3996
+ }
3997
+ const column = options.column ?? 1;
3998
+ if (!Number.isInteger(column) || column < 1) {
3999
+ console.error(chalk.red("--column must be a positive integer"));
4000
+ process.exit(1);
4001
+ }
4002
+ return [{
4003
+ filter: "cursorPosition",
4004
+ line,
4005
+ column
4006
+ }];
4007
+ }
4008
+ }
4009
+ function resolveSingleHttpFile(inputPath) {
4010
+ const absolutePath = node_path.default.resolve(process.cwd(), inputPath);
4011
+ let stats;
4012
+ try {
4013
+ stats = node_fs.default.lstatSync(absolutePath);
4014
+ } catch (err) {
4015
+ const error = err;
4016
+ console.error(chalk.red(`Error: ${error.message}`));
4017
+ process.exit(1);
4018
+ }
4019
+ if (!stats.isFile()) {
4020
+ console.error(chalk.red("--name and --line require a single .http or .rest file path"));
4021
+ process.exit(1);
4022
+ }
4023
+ const ext = node_path.default.extname(absolutePath).toLowerCase();
4024
+ if (![".http", ".rest"].includes(ext)) {
4025
+ console.error(chalk.red("Expected a .http or .rest file"));
4026
+ process.exit(1);
4027
+ }
4028
+ return node_path.default.relative(process.cwd(), absolutePath);
4029
+ }
4030
+ //#endregion
4031
+ //#region src/lib/runner/index.ts
4032
+ var HTTP_EXTENSIONS = [".http", ".rest"];
4033
+ function shuffleFiles(items) {
4034
+ const copy = [...items];
4035
+ for (let i = copy.length - 1; i > 0; i -= 1) {
4036
+ const j = Math.floor(Math.random() * (i + 1));
4037
+ [copy[i], copy[j]] = [copy[j], copy[i]];
4038
+ }
4039
+ return copy;
4040
+ }
4041
+ function resolveFiles(inputPath, shuffle) {
4042
+ let files = fileWalker(inputPath, HTTP_EXTENSIONS);
4043
+ if (files.length === 0) {
4044
+ console.error(chalk.red(`No .http or .rest files found at: ${inputPath}`));
4045
+ process.exit(1);
4046
+ }
4047
+ files.sort();
4048
+ if (shuffle) files = shuffleFiles(files);
4049
+ return files;
4050
+ }
4051
+ function responseHasFailure(result) {
4052
+ return countResults(result.response).failed > 0;
4053
+ }
4054
+ async function runFile(relativePath, env, limit) {
4055
+ const absolutePath = node_path.default.resolve(process.cwd(), relativePath);
4056
+ const content = node_fs.default.readFileSync(absolutePath, "utf-8");
4057
+ const cwd = node_path.default.dirname(absolutePath);
4058
+ return {
4059
+ filepath: relativePath,
4060
+ response: await kulalaCore.runHttp({
4061
+ content,
4062
+ filepath: absolutePath,
4063
+ env,
4064
+ limit,
4065
+ haltOnError: true
4066
+ }, { cwd })
4067
+ };
4068
+ }
4069
+ function hasFailures(results) {
4070
+ return results.some((result) => responseHasFailure(result));
4071
+ }
4072
+ async function run(inputPath, options) {
4073
+ const limit = buildRunLimit(options);
4074
+ const files = limit ? [resolveSingleHttpFile(inputPath)] : resolveFiles(inputPath, options.shuffle ?? false);
4075
+ const results = [];
4076
+ for (const file of files) {
4077
+ const result = await runFile(file, options.env, limit);
4078
+ results.push(result);
4079
+ if (responseHasFailure(result)) break;
4080
+ }
4081
+ const outputResults = options.quiet ? filterFailedResults(results) : results;
4082
+ if (!options.quiet || outputResults.length > 0) if (options.json) printJson(outputResults);
4083
+ else if (options.report) printReport(outputResults);
4084
+ else printHumanReadable(outputResults);
4085
+ if (hasFailures(results)) process.exit(1);
4086
+ }
4087
+ //#endregion
4088
+ //#region src/cli.ts
4089
+ var program = new Command();
4090
+ program.name("kulala").description("A fully-featured HTTP/GraphQL/gRPC/WebSocket client for your command-line.").version(package_default.version);
4091
+ program.command("run").description("Run .http or .rest files").argument("<path>", "file or directory to run").option("--json", "print raw kulala-core JSON output").option("--report", "print a summary report").option("-q, --quiet", "only print output when errors occur").option("--shuffle", "shuffle files when running a directory").option("--env <name>", "environment name for variable resolution").option("--name <name>", "run a single request by block name").option("--line <line>", "run request at 1-based line number", (value) => Number.parseInt(value, 10)).option("--column <column>", "1-based column for --line (default: 1)", (value) => Number.parseInt(value, 10)).action(async (inputPath, options) => {
4092
+ await run(inputPath, options);
4093
+ });
4094
+ program.parse();
4095
+ //#endregion