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