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