luckerr 0.41.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 (156) hide show
  1. package/README.md +267 -0
  2. package/README.zh-CN.md +237 -0
  3. package/dashboard/app.css +3022 -0
  4. package/dashboard/dist/app.js +30137 -0
  5. package/dashboard/dist/app.js.map +1 -0
  6. package/dashboard/dist/vendor-hljs.css +10 -0
  7. package/dashboard/dist/vendor-uplot.css +1 -0
  8. package/dashboard/index.html +19 -0
  9. package/data/deepseek-tokenizer.json.gz +0 -0
  10. package/dist/cli/acp-EOOAI4F5.js +712 -0
  11. package/dist/cli/acp-EOOAI4F5.js.map +1 -0
  12. package/dist/cli/chat-7J6GJXL2.js +51 -0
  13. package/dist/cli/chat-7J6GJXL2.js.map +1 -0
  14. package/dist/cli/chunk-2425HK6U.js +54 -0
  15. package/dist/cli/chunk-2425HK6U.js.map +1 -0
  16. package/dist/cli/chunk-25T6CVUP.js +172 -0
  17. package/dist/cli/chunk-25T6CVUP.js.map +1 -0
  18. package/dist/cli/chunk-2UQP6H6T.js +31 -0
  19. package/dist/cli/chunk-2UQP6H6T.js.map +1 -0
  20. package/dist/cli/chunk-56OAJILV.js +47 -0
  21. package/dist/cli/chunk-56OAJILV.js.map +1 -0
  22. package/dist/cli/chunk-5FTI4KXH.js +150 -0
  23. package/dist/cli/chunk-5FTI4KXH.js.map +1 -0
  24. package/dist/cli/chunk-5TWQD73O.js +2846 -0
  25. package/dist/cli/chunk-5TWQD73O.js.map +1 -0
  26. package/dist/cli/chunk-653BOCMK.js +40 -0
  27. package/dist/cli/chunk-653BOCMK.js.map +1 -0
  28. package/dist/cli/chunk-6ALJTWWQ.js +2663 -0
  29. package/dist/cli/chunk-6ALJTWWQ.js.map +1 -0
  30. package/dist/cli/chunk-6DRKA2IL.js +341 -0
  31. package/dist/cli/chunk-6DRKA2IL.js.map +1 -0
  32. package/dist/cli/chunk-6LV63NJV.js +634 -0
  33. package/dist/cli/chunk-6LV63NJV.js.map +1 -0
  34. package/dist/cli/chunk-74EX7SUH.js +25293 -0
  35. package/dist/cli/chunk-74EX7SUH.js.map +1 -0
  36. package/dist/cli/chunk-74U5RKTX.js +60611 -0
  37. package/dist/cli/chunk-74U5RKTX.js.map +1 -0
  38. package/dist/cli/chunk-ANJSUESV.js +143 -0
  39. package/dist/cli/chunk-ANJSUESV.js.map +1 -0
  40. package/dist/cli/chunk-DB2Z3DKZ.js +54 -0
  41. package/dist/cli/chunk-DB2Z3DKZ.js.map +1 -0
  42. package/dist/cli/chunk-DDIH3ZAA.js +400 -0
  43. package/dist/cli/chunk-DDIH3ZAA.js.map +1 -0
  44. package/dist/cli/chunk-ELN3Z3B2.js +621 -0
  45. package/dist/cli/chunk-ELN3Z3B2.js.map +1 -0
  46. package/dist/cli/chunk-F6BSQJGV.js +200 -0
  47. package/dist/cli/chunk-F6BSQJGV.js.map +1 -0
  48. package/dist/cli/chunk-FET2UAG5.js +246 -0
  49. package/dist/cli/chunk-FET2UAG5.js.map +1 -0
  50. package/dist/cli/chunk-FFJ342IJ.js +190 -0
  51. package/dist/cli/chunk-FFJ342IJ.js.map +1 -0
  52. package/dist/cli/chunk-GB3247B6.js +130 -0
  53. package/dist/cli/chunk-GB3247B6.js.map +1 -0
  54. package/dist/cli/chunk-HC2J4U3G.js +373 -0
  55. package/dist/cli/chunk-HC2J4U3G.js.map +1 -0
  56. package/dist/cli/chunk-HRUZAIHQ.js +42 -0
  57. package/dist/cli/chunk-HRUZAIHQ.js.map +1 -0
  58. package/dist/cli/chunk-J3ZJFUDL.js +308 -0
  59. package/dist/cli/chunk-J3ZJFUDL.js.map +1 -0
  60. package/dist/cli/chunk-J5XJHLWM.js +55 -0
  61. package/dist/cli/chunk-J5XJHLWM.js.map +1 -0
  62. package/dist/cli/chunk-JFGLMRZ6.js +160 -0
  63. package/dist/cli/chunk-JFGLMRZ6.js.map +1 -0
  64. package/dist/cli/chunk-JMBMLOBP.js +26 -0
  65. package/dist/cli/chunk-JMBMLOBP.js.map +1 -0
  66. package/dist/cli/chunk-JMWHXZEL.js +551 -0
  67. package/dist/cli/chunk-JMWHXZEL.js.map +1 -0
  68. package/dist/cli/chunk-KEQGPJBO.js +209 -0
  69. package/dist/cli/chunk-KEQGPJBO.js.map +1 -0
  70. package/dist/cli/chunk-M4K6U37F.js +232 -0
  71. package/dist/cli/chunk-M4K6U37F.js.map +1 -0
  72. package/dist/cli/chunk-MIJI2WMN.js +95 -0
  73. package/dist/cli/chunk-MIJI2WMN.js.map +1 -0
  74. package/dist/cli/chunk-MPAO3JNR.js +128 -0
  75. package/dist/cli/chunk-MPAO3JNR.js.map +1 -0
  76. package/dist/cli/chunk-PZOFBEDC.js +873 -0
  77. package/dist/cli/chunk-PZOFBEDC.js.map +1 -0
  78. package/dist/cli/chunk-RAILYQLN.js +46 -0
  79. package/dist/cli/chunk-RAILYQLN.js.map +1 -0
  80. package/dist/cli/chunk-RR35VQVT.js +90 -0
  81. package/dist/cli/chunk-RR35VQVT.js.map +1 -0
  82. package/dist/cli/chunk-RRA7VPW4.js +417 -0
  83. package/dist/cli/chunk-RRA7VPW4.js.map +1 -0
  84. package/dist/cli/chunk-RU36QVN3.js +452 -0
  85. package/dist/cli/chunk-RU36QVN3.js.map +1 -0
  86. package/dist/cli/chunk-RUBIINXR.js +1819 -0
  87. package/dist/cli/chunk-RUBIINXR.js.map +1 -0
  88. package/dist/cli/chunk-S4XVGLRW.js +499 -0
  89. package/dist/cli/chunk-S4XVGLRW.js.map +1 -0
  90. package/dist/cli/chunk-TUK7OWJA.js +51 -0
  91. package/dist/cli/chunk-TUK7OWJA.js.map +1 -0
  92. package/dist/cli/chunk-VALDDV76.js +580 -0
  93. package/dist/cli/chunk-VALDDV76.js.map +1 -0
  94. package/dist/cli/chunk-WQOGPYGN.js +11390 -0
  95. package/dist/cli/chunk-WQOGPYGN.js.map +1 -0
  96. package/dist/cli/chunk-WREKDFXT.js +34320 -0
  97. package/dist/cli/chunk-WREKDFXT.js.map +1 -0
  98. package/dist/cli/chunk-Y7XQU2EL.js +270 -0
  99. package/dist/cli/chunk-Y7XQU2EL.js.map +1 -0
  100. package/dist/cli/chunk-YBVCZJU4.js +54 -0
  101. package/dist/cli/chunk-YBVCZJU4.js.map +1 -0
  102. package/dist/cli/chunk-YLIHDXUQ.js +749 -0
  103. package/dist/cli/chunk-YLIHDXUQ.js.map +1 -0
  104. package/dist/cli/chunk-YV5XXFD7.js +767 -0
  105. package/dist/cli/chunk-YV5XXFD7.js.map +1 -0
  106. package/dist/cli/chunk-ZRCNIYRQ.js +101 -0
  107. package/dist/cli/chunk-ZRCNIYRQ.js.map +1 -0
  108. package/dist/cli/code-CRKVCMFZ.js +155 -0
  109. package/dist/cli/code-CRKVCMFZ.js.map +1 -0
  110. package/dist/cli/commands-QLMD3T7B.js +356 -0
  111. package/dist/cli/commands-QLMD3T7B.js.map +1 -0
  112. package/dist/cli/commit-53PP32NC.js +293 -0
  113. package/dist/cli/commit-53PP32NC.js.map +1 -0
  114. package/dist/cli/desktop-R6W5CLJ5.js +1046 -0
  115. package/dist/cli/desktop-R6W5CLJ5.js.map +1 -0
  116. package/dist/cli/devtools-YECO25QO.js +3719 -0
  117. package/dist/cli/devtools-YECO25QO.js.map +1 -0
  118. package/dist/cli/diff-LYNRCJZE.js +166 -0
  119. package/dist/cli/diff-LYNRCJZE.js.map +1 -0
  120. package/dist/cli/doctor-5IBP4R5J.js +28 -0
  121. package/dist/cli/doctor-5IBP4R5J.js.map +1 -0
  122. package/dist/cli/events-QN6KLN2V.js +340 -0
  123. package/dist/cli/events-QN6KLN2V.js.map +1 -0
  124. package/dist/cli/index.js +3500 -0
  125. package/dist/cli/index.js.map +1 -0
  126. package/dist/cli/mcp-FGKEH7RG.js +277 -0
  127. package/dist/cli/mcp-FGKEH7RG.js.map +1 -0
  128. package/dist/cli/mcp-browse-YCND4NWT.js +178 -0
  129. package/dist/cli/mcp-browse-YCND4NWT.js.map +1 -0
  130. package/dist/cli/mcp-inspect-V34J3VX5.js +143 -0
  131. package/dist/cli/mcp-inspect-V34J3VX5.js.map +1 -0
  132. package/dist/cli/package.json +3 -0
  133. package/dist/cli/prompt-I775PNKT.js +16 -0
  134. package/dist/cli/prompt-I775PNKT.js.map +1 -0
  135. package/dist/cli/prune-sessions-KGIIYD3P.js +44 -0
  136. package/dist/cli/prune-sessions-KGIIYD3P.js.map +1 -0
  137. package/dist/cli/replay-RDXLUAOE.js +292 -0
  138. package/dist/cli/replay-RDXLUAOE.js.map +1 -0
  139. package/dist/cli/run-RCAC2RYW.js +223 -0
  140. package/dist/cli/run-RCAC2RYW.js.map +1 -0
  141. package/dist/cli/server-FFU6TLYJ.js +3658 -0
  142. package/dist/cli/server-FFU6TLYJ.js.map +1 -0
  143. package/dist/cli/sessions-QT26MQAE.js +107 -0
  144. package/dist/cli/sessions-QT26MQAE.js.map +1 -0
  145. package/dist/cli/setup-VV4WKXHV.js +767 -0
  146. package/dist/cli/setup-VV4WKXHV.js.map +1 -0
  147. package/dist/cli/stats-JVZPQWAN.js +15 -0
  148. package/dist/cli/stats-JVZPQWAN.js.map +1 -0
  149. package/dist/cli/update-KYI3OVJP.js +15 -0
  150. package/dist/cli/update-KYI3OVJP.js.map +1 -0
  151. package/dist/cli/version-ANYORXTI.js +34 -0
  152. package/dist/cli/version-ANYORXTI.js.map +1 -0
  153. package/dist/index.d.ts +2557 -0
  154. package/dist/index.js +15000 -0
  155. package/dist/index.js.map +1 -0
  156. package/package.json +106 -0
@@ -0,0 +1,3500 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cr } from 'node:module'; if (typeof globalThis.require === 'undefined') { globalThis.require = __cr(import.meta.url); }
3
+ import {
4
+ markPhase
5
+ } from "./chunk-653BOCMK.js";
6
+ import "./chunk-WQOGPYGN.js";
7
+ import "./chunk-J3ZJFUDL.js";
8
+ import "./chunk-FFJ342IJ.js";
9
+ import "./chunk-YV5XXFD7.js";
10
+ import {
11
+ applyMemoryStack
12
+ } from "./chunk-6LV63NJV.js";
13
+ import {
14
+ resolvePreset
15
+ } from "./chunk-2425HK6U.js";
16
+ import {
17
+ installProxyIfConfigured
18
+ } from "./chunk-74EX7SUH.js";
19
+ import "./chunk-F6BSQJGV.js";
20
+ import "./chunk-2UQP6H6T.js";
21
+ import "./chunk-RUBIINXR.js";
22
+ import {
23
+ escalationContract
24
+ } from "./chunk-VALDDV76.js";
25
+ import "./chunk-KEQGPJBO.js";
26
+ import "./chunk-S4XVGLRW.js";
27
+ import "./chunk-DDIH3ZAA.js";
28
+ import "./chunk-25T6CVUP.js";
29
+ import {
30
+ listSessions
31
+ } from "./chunk-Y7XQU2EL.js";
32
+ import {
33
+ t
34
+ } from "./chunk-5TWQD73O.js";
35
+ import {
36
+ readConfig
37
+ } from "./chunk-6ALJTWWQ.js";
38
+ import "./chunk-M4K6U37F.js";
39
+ import "./chunk-ANJSUESV.js";
40
+ import "./chunk-JMWHXZEL.js";
41
+ import {
42
+ VERSION
43
+ } from "./chunk-MPAO3JNR.js";
44
+ import {
45
+ __commonJS,
46
+ __require,
47
+ __toESM
48
+ } from "./chunk-TUK7OWJA.js";
49
+
50
+ // node_modules/commander/lib/error.js
51
+ var require_error = __commonJS({
52
+ "node_modules/commander/lib/error.js"(exports) {
53
+ "use strict";
54
+ var CommanderError2 = class extends Error {
55
+ /**
56
+ * Constructs the CommanderError class
57
+ * @param {number} exitCode suggested exit code which could be used with process.exit
58
+ * @param {string} code an id string representing the error
59
+ * @param {string} message human-readable description of the error
60
+ */
61
+ constructor(exitCode, code, message) {
62
+ super(message);
63
+ Error.captureStackTrace(this, this.constructor);
64
+ this.name = this.constructor.name;
65
+ this.code = code;
66
+ this.exitCode = exitCode;
67
+ this.nestedError = void 0;
68
+ }
69
+ };
70
+ var InvalidArgumentError2 = class extends CommanderError2 {
71
+ /**
72
+ * Constructs the InvalidArgumentError class
73
+ * @param {string} [message] explanation of why argument is invalid
74
+ */
75
+ constructor(message) {
76
+ super(1, "commander.invalidArgument", message);
77
+ Error.captureStackTrace(this, this.constructor);
78
+ this.name = this.constructor.name;
79
+ }
80
+ };
81
+ exports.CommanderError = CommanderError2;
82
+ exports.InvalidArgumentError = InvalidArgumentError2;
83
+ }
84
+ });
85
+
86
+ // node_modules/commander/lib/argument.js
87
+ var require_argument = __commonJS({
88
+ "node_modules/commander/lib/argument.js"(exports) {
89
+ "use strict";
90
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
91
+ var Argument2 = class {
92
+ /**
93
+ * Initialize a new command argument with the given name and description.
94
+ * The default is that the argument is required, and you can explicitly
95
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
96
+ *
97
+ * @param {string} name
98
+ * @param {string} [description]
99
+ */
100
+ constructor(name, description) {
101
+ this.description = description || "";
102
+ this.variadic = false;
103
+ this.parseArg = void 0;
104
+ this.defaultValue = void 0;
105
+ this.defaultValueDescription = void 0;
106
+ this.argChoices = void 0;
107
+ switch (name[0]) {
108
+ case "<":
109
+ this.required = true;
110
+ this._name = name.slice(1, -1);
111
+ break;
112
+ case "[":
113
+ this.required = false;
114
+ this._name = name.slice(1, -1);
115
+ break;
116
+ default:
117
+ this.required = true;
118
+ this._name = name;
119
+ break;
120
+ }
121
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
122
+ this.variadic = true;
123
+ this._name = this._name.slice(0, -3);
124
+ }
125
+ }
126
+ /**
127
+ * Return argument name.
128
+ *
129
+ * @return {string}
130
+ */
131
+ name() {
132
+ return this._name;
133
+ }
134
+ /**
135
+ * @package
136
+ */
137
+ _concatValue(value, previous) {
138
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
139
+ return [value];
140
+ }
141
+ return previous.concat(value);
142
+ }
143
+ /**
144
+ * Set the default value, and optionally supply the description to be displayed in the help.
145
+ *
146
+ * @param {*} value
147
+ * @param {string} [description]
148
+ * @return {Argument}
149
+ */
150
+ default(value, description) {
151
+ this.defaultValue = value;
152
+ this.defaultValueDescription = description;
153
+ return this;
154
+ }
155
+ /**
156
+ * Set the custom handler for processing CLI command arguments into argument values.
157
+ *
158
+ * @param {Function} [fn]
159
+ * @return {Argument}
160
+ */
161
+ argParser(fn) {
162
+ this.parseArg = fn;
163
+ return this;
164
+ }
165
+ /**
166
+ * Only allow argument value to be one of choices.
167
+ *
168
+ * @param {string[]} values
169
+ * @return {Argument}
170
+ */
171
+ choices(values) {
172
+ this.argChoices = values.slice();
173
+ this.parseArg = (arg, previous) => {
174
+ if (!this.argChoices.includes(arg)) {
175
+ throw new InvalidArgumentError2(
176
+ `Allowed choices are ${this.argChoices.join(", ")}.`
177
+ );
178
+ }
179
+ if (this.variadic) {
180
+ return this._concatValue(arg, previous);
181
+ }
182
+ return arg;
183
+ };
184
+ return this;
185
+ }
186
+ /**
187
+ * Make argument required.
188
+ *
189
+ * @returns {Argument}
190
+ */
191
+ argRequired() {
192
+ this.required = true;
193
+ return this;
194
+ }
195
+ /**
196
+ * Make argument optional.
197
+ *
198
+ * @returns {Argument}
199
+ */
200
+ argOptional() {
201
+ this.required = false;
202
+ return this;
203
+ }
204
+ };
205
+ function humanReadableArgName(arg) {
206
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
207
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
208
+ }
209
+ exports.Argument = Argument2;
210
+ exports.humanReadableArgName = humanReadableArgName;
211
+ }
212
+ });
213
+
214
+ // node_modules/commander/lib/help.js
215
+ var require_help = __commonJS({
216
+ "node_modules/commander/lib/help.js"(exports) {
217
+ "use strict";
218
+ var { humanReadableArgName } = require_argument();
219
+ var Help2 = class {
220
+ constructor() {
221
+ this.helpWidth = void 0;
222
+ this.sortSubcommands = false;
223
+ this.sortOptions = false;
224
+ this.showGlobalOptions = false;
225
+ }
226
+ /**
227
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
228
+ *
229
+ * @param {Command} cmd
230
+ * @returns {Command[]}
231
+ */
232
+ visibleCommands(cmd) {
233
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
234
+ const helpCommand = cmd._getHelpCommand();
235
+ if (helpCommand && !helpCommand._hidden) {
236
+ visibleCommands.push(helpCommand);
237
+ }
238
+ if (this.sortSubcommands) {
239
+ visibleCommands.sort((a, b) => {
240
+ return a.name().localeCompare(b.name());
241
+ });
242
+ }
243
+ return visibleCommands;
244
+ }
245
+ /**
246
+ * Compare options for sort.
247
+ *
248
+ * @param {Option} a
249
+ * @param {Option} b
250
+ * @returns {number}
251
+ */
252
+ compareOptions(a, b) {
253
+ const getSortKey = (option) => {
254
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
255
+ };
256
+ return getSortKey(a).localeCompare(getSortKey(b));
257
+ }
258
+ /**
259
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
260
+ *
261
+ * @param {Command} cmd
262
+ * @returns {Option[]}
263
+ */
264
+ visibleOptions(cmd) {
265
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
266
+ const helpOption = cmd._getHelpOption();
267
+ if (helpOption && !helpOption.hidden) {
268
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
269
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
270
+ if (!removeShort && !removeLong) {
271
+ visibleOptions.push(helpOption);
272
+ } else if (helpOption.long && !removeLong) {
273
+ visibleOptions.push(
274
+ cmd.createOption(helpOption.long, helpOption.description)
275
+ );
276
+ } else if (helpOption.short && !removeShort) {
277
+ visibleOptions.push(
278
+ cmd.createOption(helpOption.short, helpOption.description)
279
+ );
280
+ }
281
+ }
282
+ if (this.sortOptions) {
283
+ visibleOptions.sort(this.compareOptions);
284
+ }
285
+ return visibleOptions;
286
+ }
287
+ /**
288
+ * Get an array of the visible global options. (Not including help.)
289
+ *
290
+ * @param {Command} cmd
291
+ * @returns {Option[]}
292
+ */
293
+ visibleGlobalOptions(cmd) {
294
+ if (!this.showGlobalOptions) return [];
295
+ const globalOptions = [];
296
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
297
+ const visibleOptions = ancestorCmd.options.filter(
298
+ (option) => !option.hidden
299
+ );
300
+ globalOptions.push(...visibleOptions);
301
+ }
302
+ if (this.sortOptions) {
303
+ globalOptions.sort(this.compareOptions);
304
+ }
305
+ return globalOptions;
306
+ }
307
+ /**
308
+ * Get an array of the arguments if any have a description.
309
+ *
310
+ * @param {Command} cmd
311
+ * @returns {Argument[]}
312
+ */
313
+ visibleArguments(cmd) {
314
+ if (cmd._argsDescription) {
315
+ cmd.registeredArguments.forEach((argument) => {
316
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
317
+ });
318
+ }
319
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
320
+ return cmd.registeredArguments;
321
+ }
322
+ return [];
323
+ }
324
+ /**
325
+ * Get the command term to show in the list of subcommands.
326
+ *
327
+ * @param {Command} cmd
328
+ * @returns {string}
329
+ */
330
+ subcommandTerm(cmd) {
331
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
332
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
333
+ (args ? " " + args : "");
334
+ }
335
+ /**
336
+ * Get the option term to show in the list of options.
337
+ *
338
+ * @param {Option} option
339
+ * @returns {string}
340
+ */
341
+ optionTerm(option) {
342
+ return option.flags;
343
+ }
344
+ /**
345
+ * Get the argument term to show in the list of arguments.
346
+ *
347
+ * @param {Argument} argument
348
+ * @returns {string}
349
+ */
350
+ argumentTerm(argument) {
351
+ return argument.name();
352
+ }
353
+ /**
354
+ * Get the longest command term length.
355
+ *
356
+ * @param {Command} cmd
357
+ * @param {Help} helper
358
+ * @returns {number}
359
+ */
360
+ longestSubcommandTermLength(cmd, helper) {
361
+ return helper.visibleCommands(cmd).reduce((max, command) => {
362
+ return Math.max(max, helper.subcommandTerm(command).length);
363
+ }, 0);
364
+ }
365
+ /**
366
+ * Get the longest option term length.
367
+ *
368
+ * @param {Command} cmd
369
+ * @param {Help} helper
370
+ * @returns {number}
371
+ */
372
+ longestOptionTermLength(cmd, helper) {
373
+ return helper.visibleOptions(cmd).reduce((max, option) => {
374
+ return Math.max(max, helper.optionTerm(option).length);
375
+ }, 0);
376
+ }
377
+ /**
378
+ * Get the longest global option term length.
379
+ *
380
+ * @param {Command} cmd
381
+ * @param {Help} helper
382
+ * @returns {number}
383
+ */
384
+ longestGlobalOptionTermLength(cmd, helper) {
385
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
386
+ return Math.max(max, helper.optionTerm(option).length);
387
+ }, 0);
388
+ }
389
+ /**
390
+ * Get the longest argument term length.
391
+ *
392
+ * @param {Command} cmd
393
+ * @param {Help} helper
394
+ * @returns {number}
395
+ */
396
+ longestArgumentTermLength(cmd, helper) {
397
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
398
+ return Math.max(max, helper.argumentTerm(argument).length);
399
+ }, 0);
400
+ }
401
+ /**
402
+ * Get the command usage to be displayed at the top of the built-in help.
403
+ *
404
+ * @param {Command} cmd
405
+ * @returns {string}
406
+ */
407
+ commandUsage(cmd) {
408
+ let cmdName = cmd._name;
409
+ if (cmd._aliases[0]) {
410
+ cmdName = cmdName + "|" + cmd._aliases[0];
411
+ }
412
+ let ancestorCmdNames = "";
413
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
414
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
415
+ }
416
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
417
+ }
418
+ /**
419
+ * Get the description for the command.
420
+ *
421
+ * @param {Command} cmd
422
+ * @returns {string}
423
+ */
424
+ commandDescription(cmd) {
425
+ return cmd.description();
426
+ }
427
+ /**
428
+ * Get the subcommand summary to show in the list of subcommands.
429
+ * (Fallback to description for backwards compatibility.)
430
+ *
431
+ * @param {Command} cmd
432
+ * @returns {string}
433
+ */
434
+ subcommandDescription(cmd) {
435
+ return cmd.summary() || cmd.description();
436
+ }
437
+ /**
438
+ * Get the option description to show in the list of options.
439
+ *
440
+ * @param {Option} option
441
+ * @return {string}
442
+ */
443
+ optionDescription(option) {
444
+ const extraInfo = [];
445
+ if (option.argChoices) {
446
+ extraInfo.push(
447
+ // use stringify to match the display of the default value
448
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
449
+ );
450
+ }
451
+ if (option.defaultValue !== void 0) {
452
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
453
+ if (showDefault) {
454
+ extraInfo.push(
455
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
456
+ );
457
+ }
458
+ }
459
+ if (option.presetArg !== void 0 && option.optional) {
460
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
461
+ }
462
+ if (option.envVar !== void 0) {
463
+ extraInfo.push(`env: ${option.envVar}`);
464
+ }
465
+ if (extraInfo.length > 0) {
466
+ return `${option.description} (${extraInfo.join(", ")})`;
467
+ }
468
+ return option.description;
469
+ }
470
+ /**
471
+ * Get the argument description to show in the list of arguments.
472
+ *
473
+ * @param {Argument} argument
474
+ * @return {string}
475
+ */
476
+ argumentDescription(argument) {
477
+ const extraInfo = [];
478
+ if (argument.argChoices) {
479
+ extraInfo.push(
480
+ // use stringify to match the display of the default value
481
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
482
+ );
483
+ }
484
+ if (argument.defaultValue !== void 0) {
485
+ extraInfo.push(
486
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
487
+ );
488
+ }
489
+ if (extraInfo.length > 0) {
490
+ const extraDescripton = `(${extraInfo.join(", ")})`;
491
+ if (argument.description) {
492
+ return `${argument.description} ${extraDescripton}`;
493
+ }
494
+ return extraDescripton;
495
+ }
496
+ return argument.description;
497
+ }
498
+ /**
499
+ * Generate the built-in help text.
500
+ *
501
+ * @param {Command} cmd
502
+ * @param {Help} helper
503
+ * @returns {string}
504
+ */
505
+ formatHelp(cmd, helper) {
506
+ const termWidth = helper.padWidth(cmd, helper);
507
+ const helpWidth = helper.helpWidth || 80;
508
+ const itemIndentWidth = 2;
509
+ const itemSeparatorWidth = 2;
510
+ function formatItem(term, description) {
511
+ if (description) {
512
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
513
+ return helper.wrap(
514
+ fullText,
515
+ helpWidth - itemIndentWidth,
516
+ termWidth + itemSeparatorWidth
517
+ );
518
+ }
519
+ return term;
520
+ }
521
+ function formatList(textArray) {
522
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
523
+ }
524
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
525
+ const commandDescription = helper.commandDescription(cmd);
526
+ if (commandDescription.length > 0) {
527
+ output = output.concat([
528
+ helper.wrap(commandDescription, helpWidth, 0),
529
+ ""
530
+ ]);
531
+ }
532
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
533
+ return formatItem(
534
+ helper.argumentTerm(argument),
535
+ helper.argumentDescription(argument)
536
+ );
537
+ });
538
+ if (argumentList.length > 0) {
539
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
540
+ }
541
+ const optionList = helper.visibleOptions(cmd).map((option) => {
542
+ return formatItem(
543
+ helper.optionTerm(option),
544
+ helper.optionDescription(option)
545
+ );
546
+ });
547
+ if (optionList.length > 0) {
548
+ output = output.concat(["Options:", formatList(optionList), ""]);
549
+ }
550
+ if (this.showGlobalOptions) {
551
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
552
+ return formatItem(
553
+ helper.optionTerm(option),
554
+ helper.optionDescription(option)
555
+ );
556
+ });
557
+ if (globalOptionList.length > 0) {
558
+ output = output.concat([
559
+ "Global Options:",
560
+ formatList(globalOptionList),
561
+ ""
562
+ ]);
563
+ }
564
+ }
565
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
566
+ return formatItem(
567
+ helper.subcommandTerm(cmd2),
568
+ helper.subcommandDescription(cmd2)
569
+ );
570
+ });
571
+ if (commandList.length > 0) {
572
+ output = output.concat(["Commands:", formatList(commandList), ""]);
573
+ }
574
+ return output.join("\n");
575
+ }
576
+ /**
577
+ * Calculate the pad width from the maximum term length.
578
+ *
579
+ * @param {Command} cmd
580
+ * @param {Help} helper
581
+ * @returns {number}
582
+ */
583
+ padWidth(cmd, helper) {
584
+ return Math.max(
585
+ helper.longestOptionTermLength(cmd, helper),
586
+ helper.longestGlobalOptionTermLength(cmd, helper),
587
+ helper.longestSubcommandTermLength(cmd, helper),
588
+ helper.longestArgumentTermLength(cmd, helper)
589
+ );
590
+ }
591
+ /**
592
+ * Wrap the given string to width characters per line, with lines after the first indented.
593
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
594
+ *
595
+ * @param {string} str
596
+ * @param {number} width
597
+ * @param {number} indent
598
+ * @param {number} [minColumnWidth=40]
599
+ * @return {string}
600
+ *
601
+ */
602
+ wrap(str, width, indent, minColumnWidth = 40) {
603
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
604
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
605
+ if (str.match(manualIndent)) return str;
606
+ const columnWidth = width - indent;
607
+ if (columnWidth < minColumnWidth) return str;
608
+ const leadingStr = str.slice(0, indent);
609
+ const columnText = str.slice(indent).replace("\r\n", "\n");
610
+ const indentString = " ".repeat(indent);
611
+ const zeroWidthSpace = "\u200B";
612
+ const breaks = `\\s${zeroWidthSpace}`;
613
+ const regex = new RegExp(
614
+ `
615
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
616
+ "g"
617
+ );
618
+ const lines = columnText.match(regex) || [];
619
+ return leadingStr + lines.map((line, i) => {
620
+ if (line === "\n") return "";
621
+ return (i > 0 ? indentString : "") + line.trimEnd();
622
+ }).join("\n");
623
+ }
624
+ };
625
+ exports.Help = Help2;
626
+ }
627
+ });
628
+
629
+ // node_modules/commander/lib/option.js
630
+ var require_option = __commonJS({
631
+ "node_modules/commander/lib/option.js"(exports) {
632
+ "use strict";
633
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
634
+ var Option2 = class {
635
+ /**
636
+ * Initialize a new `Option` with the given `flags` and `description`.
637
+ *
638
+ * @param {string} flags
639
+ * @param {string} [description]
640
+ */
641
+ constructor(flags, description) {
642
+ this.flags = flags;
643
+ this.description = description || "";
644
+ this.required = flags.includes("<");
645
+ this.optional = flags.includes("[");
646
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
647
+ this.mandatory = false;
648
+ const optionFlags = splitOptionFlags(flags);
649
+ this.short = optionFlags.shortFlag;
650
+ this.long = optionFlags.longFlag;
651
+ this.negate = false;
652
+ if (this.long) {
653
+ this.negate = this.long.startsWith("--no-");
654
+ }
655
+ this.defaultValue = void 0;
656
+ this.defaultValueDescription = void 0;
657
+ this.presetArg = void 0;
658
+ this.envVar = void 0;
659
+ this.parseArg = void 0;
660
+ this.hidden = false;
661
+ this.argChoices = void 0;
662
+ this.conflictsWith = [];
663
+ this.implied = void 0;
664
+ }
665
+ /**
666
+ * Set the default value, and optionally supply the description to be displayed in the help.
667
+ *
668
+ * @param {*} value
669
+ * @param {string} [description]
670
+ * @return {Option}
671
+ */
672
+ default(value, description) {
673
+ this.defaultValue = value;
674
+ this.defaultValueDescription = description;
675
+ return this;
676
+ }
677
+ /**
678
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
679
+ * The custom processing (parseArg) is called.
680
+ *
681
+ * @example
682
+ * new Option('--color').default('GREYSCALE').preset('RGB');
683
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
684
+ *
685
+ * @param {*} arg
686
+ * @return {Option}
687
+ */
688
+ preset(arg) {
689
+ this.presetArg = arg;
690
+ return this;
691
+ }
692
+ /**
693
+ * Add option name(s) that conflict with this option.
694
+ * An error will be displayed if conflicting options are found during parsing.
695
+ *
696
+ * @example
697
+ * new Option('--rgb').conflicts('cmyk');
698
+ * new Option('--js').conflicts(['ts', 'jsx']);
699
+ *
700
+ * @param {(string | string[])} names
701
+ * @return {Option}
702
+ */
703
+ conflicts(names) {
704
+ this.conflictsWith = this.conflictsWith.concat(names);
705
+ return this;
706
+ }
707
+ /**
708
+ * Specify implied option values for when this option is set and the implied options are not.
709
+ *
710
+ * The custom processing (parseArg) is not called on the implied values.
711
+ *
712
+ * @example
713
+ * program
714
+ * .addOption(new Option('--log', 'write logging information to file'))
715
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
716
+ *
717
+ * @param {object} impliedOptionValues
718
+ * @return {Option}
719
+ */
720
+ implies(impliedOptionValues) {
721
+ let newImplied = impliedOptionValues;
722
+ if (typeof impliedOptionValues === "string") {
723
+ newImplied = { [impliedOptionValues]: true };
724
+ }
725
+ this.implied = Object.assign(this.implied || {}, newImplied);
726
+ return this;
727
+ }
728
+ /**
729
+ * Set environment variable to check for option value.
730
+ *
731
+ * An environment variable is only used if when processed the current option value is
732
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
733
+ *
734
+ * @param {string} name
735
+ * @return {Option}
736
+ */
737
+ env(name) {
738
+ this.envVar = name;
739
+ return this;
740
+ }
741
+ /**
742
+ * Set the custom handler for processing CLI option arguments into option values.
743
+ *
744
+ * @param {Function} [fn]
745
+ * @return {Option}
746
+ */
747
+ argParser(fn) {
748
+ this.parseArg = fn;
749
+ return this;
750
+ }
751
+ /**
752
+ * Whether the option is mandatory and must have a value after parsing.
753
+ *
754
+ * @param {boolean} [mandatory=true]
755
+ * @return {Option}
756
+ */
757
+ makeOptionMandatory(mandatory = true) {
758
+ this.mandatory = !!mandatory;
759
+ return this;
760
+ }
761
+ /**
762
+ * Hide option in help.
763
+ *
764
+ * @param {boolean} [hide=true]
765
+ * @return {Option}
766
+ */
767
+ hideHelp(hide = true) {
768
+ this.hidden = !!hide;
769
+ return this;
770
+ }
771
+ /**
772
+ * @package
773
+ */
774
+ _concatValue(value, previous) {
775
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
776
+ return [value];
777
+ }
778
+ return previous.concat(value);
779
+ }
780
+ /**
781
+ * Only allow option value to be one of choices.
782
+ *
783
+ * @param {string[]} values
784
+ * @return {Option}
785
+ */
786
+ choices(values) {
787
+ this.argChoices = values.slice();
788
+ this.parseArg = (arg, previous) => {
789
+ if (!this.argChoices.includes(arg)) {
790
+ throw new InvalidArgumentError2(
791
+ `Allowed choices are ${this.argChoices.join(", ")}.`
792
+ );
793
+ }
794
+ if (this.variadic) {
795
+ return this._concatValue(arg, previous);
796
+ }
797
+ return arg;
798
+ };
799
+ return this;
800
+ }
801
+ /**
802
+ * Return option name.
803
+ *
804
+ * @return {string}
805
+ */
806
+ name() {
807
+ if (this.long) {
808
+ return this.long.replace(/^--/, "");
809
+ }
810
+ return this.short.replace(/^-/, "");
811
+ }
812
+ /**
813
+ * Return option name, in a camelcase format that can be used
814
+ * as a object attribute key.
815
+ *
816
+ * @return {string}
817
+ */
818
+ attributeName() {
819
+ return camelcase(this.name().replace(/^no-/, ""));
820
+ }
821
+ /**
822
+ * Check if `arg` matches the short or long flag.
823
+ *
824
+ * @param {string} arg
825
+ * @return {boolean}
826
+ * @package
827
+ */
828
+ is(arg) {
829
+ return this.short === arg || this.long === arg;
830
+ }
831
+ /**
832
+ * Return whether a boolean option.
833
+ *
834
+ * Options are one of boolean, negated, required argument, or optional argument.
835
+ *
836
+ * @return {boolean}
837
+ * @package
838
+ */
839
+ isBoolean() {
840
+ return !this.required && !this.optional && !this.negate;
841
+ }
842
+ };
843
+ var DualOptions = class {
844
+ /**
845
+ * @param {Option[]} options
846
+ */
847
+ constructor(options) {
848
+ this.positiveOptions = /* @__PURE__ */ new Map();
849
+ this.negativeOptions = /* @__PURE__ */ new Map();
850
+ this.dualOptions = /* @__PURE__ */ new Set();
851
+ options.forEach((option) => {
852
+ if (option.negate) {
853
+ this.negativeOptions.set(option.attributeName(), option);
854
+ } else {
855
+ this.positiveOptions.set(option.attributeName(), option);
856
+ }
857
+ });
858
+ this.negativeOptions.forEach((value, key) => {
859
+ if (this.positiveOptions.has(key)) {
860
+ this.dualOptions.add(key);
861
+ }
862
+ });
863
+ }
864
+ /**
865
+ * Did the value come from the option, and not from possible matching dual option?
866
+ *
867
+ * @param {*} value
868
+ * @param {Option} option
869
+ * @returns {boolean}
870
+ */
871
+ valueFromOption(value, option) {
872
+ const optionKey = option.attributeName();
873
+ if (!this.dualOptions.has(optionKey)) return true;
874
+ const preset = this.negativeOptions.get(optionKey).presetArg;
875
+ const negativeValue = preset !== void 0 ? preset : false;
876
+ return option.negate === (negativeValue === value);
877
+ }
878
+ };
879
+ function camelcase(str) {
880
+ return str.split("-").reduce((str2, word) => {
881
+ return str2 + word[0].toUpperCase() + word.slice(1);
882
+ });
883
+ }
884
+ function splitOptionFlags(flags) {
885
+ let shortFlag;
886
+ let longFlag;
887
+ const flagParts = flags.split(/[ |,]+/);
888
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
889
+ shortFlag = flagParts.shift();
890
+ longFlag = flagParts.shift();
891
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
892
+ shortFlag = longFlag;
893
+ longFlag = void 0;
894
+ }
895
+ return { shortFlag, longFlag };
896
+ }
897
+ exports.Option = Option2;
898
+ exports.DualOptions = DualOptions;
899
+ }
900
+ });
901
+
902
+ // node_modules/commander/lib/suggestSimilar.js
903
+ var require_suggestSimilar = __commonJS({
904
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
905
+ "use strict";
906
+ var maxDistance = 3;
907
+ function editDistance(a, b) {
908
+ if (Math.abs(a.length - b.length) > maxDistance)
909
+ return Math.max(a.length, b.length);
910
+ const d = [];
911
+ for (let i = 0; i <= a.length; i++) {
912
+ d[i] = [i];
913
+ }
914
+ for (let j = 0; j <= b.length; j++) {
915
+ d[0][j] = j;
916
+ }
917
+ for (let j = 1; j <= b.length; j++) {
918
+ for (let i = 1; i <= a.length; i++) {
919
+ let cost = 1;
920
+ if (a[i - 1] === b[j - 1]) {
921
+ cost = 0;
922
+ } else {
923
+ cost = 1;
924
+ }
925
+ d[i][j] = Math.min(
926
+ d[i - 1][j] + 1,
927
+ // deletion
928
+ d[i][j - 1] + 1,
929
+ // insertion
930
+ d[i - 1][j - 1] + cost
931
+ // substitution
932
+ );
933
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
934
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
935
+ }
936
+ }
937
+ }
938
+ return d[a.length][b.length];
939
+ }
940
+ function suggestSimilar(word, candidates) {
941
+ if (!candidates || candidates.length === 0) return "";
942
+ candidates = Array.from(new Set(candidates));
943
+ const searchingOptions = word.startsWith("--");
944
+ if (searchingOptions) {
945
+ word = word.slice(2);
946
+ candidates = candidates.map((candidate) => candidate.slice(2));
947
+ }
948
+ let similar = [];
949
+ let bestDistance = maxDistance;
950
+ const minSimilarity = 0.4;
951
+ candidates.forEach((candidate) => {
952
+ if (candidate.length <= 1) return;
953
+ const distance = editDistance(word, candidate);
954
+ const length = Math.max(word.length, candidate.length);
955
+ const similarity = (length - distance) / length;
956
+ if (similarity > minSimilarity) {
957
+ if (distance < bestDistance) {
958
+ bestDistance = distance;
959
+ similar = [candidate];
960
+ } else if (distance === bestDistance) {
961
+ similar.push(candidate);
962
+ }
963
+ }
964
+ });
965
+ similar.sort((a, b) => a.localeCompare(b));
966
+ if (searchingOptions) {
967
+ similar = similar.map((candidate) => `--${candidate}`);
968
+ }
969
+ if (similar.length > 1) {
970
+ return `
971
+ (Did you mean one of ${similar.join(", ")}?)`;
972
+ }
973
+ if (similar.length === 1) {
974
+ return `
975
+ (Did you mean ${similar[0]}?)`;
976
+ }
977
+ return "";
978
+ }
979
+ exports.suggestSimilar = suggestSimilar;
980
+ }
981
+ });
982
+
983
+ // node_modules/commander/lib/command.js
984
+ var require_command = __commonJS({
985
+ "node_modules/commander/lib/command.js"(exports) {
986
+ "use strict";
987
+ var EventEmitter = __require("events").EventEmitter;
988
+ var childProcess = __require("child_process");
989
+ var path = __require("path");
990
+ var fs = __require("fs");
991
+ var process2 = __require("process");
992
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
993
+ var { CommanderError: CommanderError2 } = require_error();
994
+ var { Help: Help2 } = require_help();
995
+ var { Option: Option2, DualOptions } = require_option();
996
+ var { suggestSimilar } = require_suggestSimilar();
997
+ var Command2 = class _Command extends EventEmitter {
998
+ /**
999
+ * Initialize a new `Command`.
1000
+ *
1001
+ * @param {string} [name]
1002
+ */
1003
+ constructor(name) {
1004
+ super();
1005
+ this.commands = [];
1006
+ this.options = [];
1007
+ this.parent = null;
1008
+ this._allowUnknownOption = false;
1009
+ this._allowExcessArguments = true;
1010
+ this.registeredArguments = [];
1011
+ this._args = this.registeredArguments;
1012
+ this.args = [];
1013
+ this.rawArgs = [];
1014
+ this.processedArgs = [];
1015
+ this._scriptPath = null;
1016
+ this._name = name || "";
1017
+ this._optionValues = {};
1018
+ this._optionValueSources = {};
1019
+ this._storeOptionsAsProperties = false;
1020
+ this._actionHandler = null;
1021
+ this._executableHandler = false;
1022
+ this._executableFile = null;
1023
+ this._executableDir = null;
1024
+ this._defaultCommandName = null;
1025
+ this._exitCallback = null;
1026
+ this._aliases = [];
1027
+ this._combineFlagAndOptionalValue = true;
1028
+ this._description = "";
1029
+ this._summary = "";
1030
+ this._argsDescription = void 0;
1031
+ this._enablePositionalOptions = false;
1032
+ this._passThroughOptions = false;
1033
+ this._lifeCycleHooks = {};
1034
+ this._showHelpAfterError = false;
1035
+ this._showSuggestionAfterError = true;
1036
+ this._outputConfiguration = {
1037
+ writeOut: (str) => process2.stdout.write(str),
1038
+ writeErr: (str) => process2.stderr.write(str),
1039
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1040
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1041
+ outputError: (str, write) => write(str)
1042
+ };
1043
+ this._hidden = false;
1044
+ this._helpOption = void 0;
1045
+ this._addImplicitHelpCommand = void 0;
1046
+ this._helpCommand = void 0;
1047
+ this._helpConfiguration = {};
1048
+ }
1049
+ /**
1050
+ * Copy settings that are useful to have in common across root command and subcommands.
1051
+ *
1052
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1053
+ *
1054
+ * @param {Command} sourceCommand
1055
+ * @return {Command} `this` command for chaining
1056
+ */
1057
+ copyInheritedSettings(sourceCommand) {
1058
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1059
+ this._helpOption = sourceCommand._helpOption;
1060
+ this._helpCommand = sourceCommand._helpCommand;
1061
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1062
+ this._exitCallback = sourceCommand._exitCallback;
1063
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1064
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1065
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1066
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1067
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1068
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1069
+ return this;
1070
+ }
1071
+ /**
1072
+ * @returns {Command[]}
1073
+ * @private
1074
+ */
1075
+ _getCommandAndAncestors() {
1076
+ const result = [];
1077
+ for (let command = this; command; command = command.parent) {
1078
+ result.push(command);
1079
+ }
1080
+ return result;
1081
+ }
1082
+ /**
1083
+ * Define a command.
1084
+ *
1085
+ * There are two styles of command: pay attention to where to put the description.
1086
+ *
1087
+ * @example
1088
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1089
+ * program
1090
+ * .command('clone <source> [destination]')
1091
+ * .description('clone a repository into a newly created directory')
1092
+ * .action((source, destination) => {
1093
+ * console.log('clone command called');
1094
+ * });
1095
+ *
1096
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1097
+ * program
1098
+ * .command('start <service>', 'start named service')
1099
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1100
+ *
1101
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1102
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1103
+ * @param {object} [execOpts] - configuration options (for executable)
1104
+ * @return {Command} returns new command for action handler, or `this` for executable command
1105
+ */
1106
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1107
+ let desc = actionOptsOrExecDesc;
1108
+ let opts = execOpts;
1109
+ if (typeof desc === "object" && desc !== null) {
1110
+ opts = desc;
1111
+ desc = null;
1112
+ }
1113
+ opts = opts || {};
1114
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1115
+ const cmd = this.createCommand(name);
1116
+ if (desc) {
1117
+ cmd.description(desc);
1118
+ cmd._executableHandler = true;
1119
+ }
1120
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1121
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1122
+ cmd._executableFile = opts.executableFile || null;
1123
+ if (args) cmd.arguments(args);
1124
+ this._registerCommand(cmd);
1125
+ cmd.parent = this;
1126
+ cmd.copyInheritedSettings(this);
1127
+ if (desc) return this;
1128
+ return cmd;
1129
+ }
1130
+ /**
1131
+ * Factory routine to create a new unattached command.
1132
+ *
1133
+ * See .command() for creating an attached subcommand, which uses this routine to
1134
+ * create the command. You can override createCommand to customise subcommands.
1135
+ *
1136
+ * @param {string} [name]
1137
+ * @return {Command} new command
1138
+ */
1139
+ createCommand(name) {
1140
+ return new _Command(name);
1141
+ }
1142
+ /**
1143
+ * You can customise the help with a subclass of Help by overriding createHelp,
1144
+ * or by overriding Help properties using configureHelp().
1145
+ *
1146
+ * @return {Help}
1147
+ */
1148
+ createHelp() {
1149
+ return Object.assign(new Help2(), this.configureHelp());
1150
+ }
1151
+ /**
1152
+ * You can customise the help by overriding Help properties using configureHelp(),
1153
+ * or with a subclass of Help by overriding createHelp().
1154
+ *
1155
+ * @param {object} [configuration] - configuration options
1156
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1157
+ */
1158
+ configureHelp(configuration) {
1159
+ if (configuration === void 0) return this._helpConfiguration;
1160
+ this._helpConfiguration = configuration;
1161
+ return this;
1162
+ }
1163
+ /**
1164
+ * The default output goes to stdout and stderr. You can customise this for special
1165
+ * applications. You can also customise the display of errors by overriding outputError.
1166
+ *
1167
+ * The configuration properties are all functions:
1168
+ *
1169
+ * // functions to change where being written, stdout and stderr
1170
+ * writeOut(str)
1171
+ * writeErr(str)
1172
+ * // matching functions to specify width for wrapping help
1173
+ * getOutHelpWidth()
1174
+ * getErrHelpWidth()
1175
+ * // functions based on what is being written out
1176
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1177
+ *
1178
+ * @param {object} [configuration] - configuration options
1179
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1180
+ */
1181
+ configureOutput(configuration) {
1182
+ if (configuration === void 0) return this._outputConfiguration;
1183
+ Object.assign(this._outputConfiguration, configuration);
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Display the help or a custom message after an error occurs.
1188
+ *
1189
+ * @param {(boolean|string)} [displayHelp]
1190
+ * @return {Command} `this` command for chaining
1191
+ */
1192
+ showHelpAfterError(displayHelp = true) {
1193
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1194
+ this._showHelpAfterError = displayHelp;
1195
+ return this;
1196
+ }
1197
+ /**
1198
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1199
+ *
1200
+ * @param {boolean} [displaySuggestion]
1201
+ * @return {Command} `this` command for chaining
1202
+ */
1203
+ showSuggestionAfterError(displaySuggestion = true) {
1204
+ this._showSuggestionAfterError = !!displaySuggestion;
1205
+ return this;
1206
+ }
1207
+ /**
1208
+ * Add a prepared subcommand.
1209
+ *
1210
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1211
+ *
1212
+ * @param {Command} cmd - new subcommand
1213
+ * @param {object} [opts] - configuration options
1214
+ * @return {Command} `this` command for chaining
1215
+ */
1216
+ addCommand(cmd, opts) {
1217
+ if (!cmd._name) {
1218
+ throw new Error(`Command passed to .addCommand() must have a name
1219
+ - specify the name in Command constructor or using .name()`);
1220
+ }
1221
+ opts = opts || {};
1222
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1223
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1224
+ this._registerCommand(cmd);
1225
+ cmd.parent = this;
1226
+ cmd._checkForBrokenPassThrough();
1227
+ return this;
1228
+ }
1229
+ /**
1230
+ * Factory routine to create a new unattached argument.
1231
+ *
1232
+ * See .argument() for creating an attached argument, which uses this routine to
1233
+ * create the argument. You can override createArgument to return a custom argument.
1234
+ *
1235
+ * @param {string} name
1236
+ * @param {string} [description]
1237
+ * @return {Argument} new argument
1238
+ */
1239
+ createArgument(name, description) {
1240
+ return new Argument2(name, description);
1241
+ }
1242
+ /**
1243
+ * Define argument syntax for command.
1244
+ *
1245
+ * The default is that the argument is required, and you can explicitly
1246
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1247
+ *
1248
+ * @example
1249
+ * program.argument('<input-file>');
1250
+ * program.argument('[output-file]');
1251
+ *
1252
+ * @param {string} name
1253
+ * @param {string} [description]
1254
+ * @param {(Function|*)} [fn] - custom argument processing function
1255
+ * @param {*} [defaultValue]
1256
+ * @return {Command} `this` command for chaining
1257
+ */
1258
+ argument(name, description, fn, defaultValue) {
1259
+ const argument = this.createArgument(name, description);
1260
+ if (typeof fn === "function") {
1261
+ argument.default(defaultValue).argParser(fn);
1262
+ } else {
1263
+ argument.default(fn);
1264
+ }
1265
+ this.addArgument(argument);
1266
+ return this;
1267
+ }
1268
+ /**
1269
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1270
+ *
1271
+ * See also .argument().
1272
+ *
1273
+ * @example
1274
+ * program.arguments('<cmd> [env]');
1275
+ *
1276
+ * @param {string} names
1277
+ * @return {Command} `this` command for chaining
1278
+ */
1279
+ arguments(names) {
1280
+ names.trim().split(/ +/).forEach((detail) => {
1281
+ this.argument(detail);
1282
+ });
1283
+ return this;
1284
+ }
1285
+ /**
1286
+ * Define argument syntax for command, adding a prepared argument.
1287
+ *
1288
+ * @param {Argument} argument
1289
+ * @return {Command} `this` command for chaining
1290
+ */
1291
+ addArgument(argument) {
1292
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1293
+ if (previousArgument && previousArgument.variadic) {
1294
+ throw new Error(
1295
+ `only the last argument can be variadic '${previousArgument.name()}'`
1296
+ );
1297
+ }
1298
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1299
+ throw new Error(
1300
+ `a default value for a required argument is never used: '${argument.name()}'`
1301
+ );
1302
+ }
1303
+ this.registeredArguments.push(argument);
1304
+ return this;
1305
+ }
1306
+ /**
1307
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1308
+ *
1309
+ * @example
1310
+ * program.helpCommand('help [cmd]');
1311
+ * program.helpCommand('help [cmd]', 'show help');
1312
+ * program.helpCommand(false); // suppress default help command
1313
+ * program.helpCommand(true); // add help command even if no subcommands
1314
+ *
1315
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1316
+ * @param {string} [description] - custom description
1317
+ * @return {Command} `this` command for chaining
1318
+ */
1319
+ helpCommand(enableOrNameAndArgs, description) {
1320
+ if (typeof enableOrNameAndArgs === "boolean") {
1321
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1322
+ return this;
1323
+ }
1324
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1325
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1326
+ const helpDescription = description ?? "display help for command";
1327
+ const helpCommand = this.createCommand(helpName);
1328
+ helpCommand.helpOption(false);
1329
+ if (helpArgs) helpCommand.arguments(helpArgs);
1330
+ if (helpDescription) helpCommand.description(helpDescription);
1331
+ this._addImplicitHelpCommand = true;
1332
+ this._helpCommand = helpCommand;
1333
+ return this;
1334
+ }
1335
+ /**
1336
+ * Add prepared custom help command.
1337
+ *
1338
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1339
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1340
+ * @return {Command} `this` command for chaining
1341
+ */
1342
+ addHelpCommand(helpCommand, deprecatedDescription) {
1343
+ if (typeof helpCommand !== "object") {
1344
+ this.helpCommand(helpCommand, deprecatedDescription);
1345
+ return this;
1346
+ }
1347
+ this._addImplicitHelpCommand = true;
1348
+ this._helpCommand = helpCommand;
1349
+ return this;
1350
+ }
1351
+ /**
1352
+ * Lazy create help command.
1353
+ *
1354
+ * @return {(Command|null)}
1355
+ * @package
1356
+ */
1357
+ _getHelpCommand() {
1358
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1359
+ if (hasImplicitHelpCommand) {
1360
+ if (this._helpCommand === void 0) {
1361
+ this.helpCommand(void 0, void 0);
1362
+ }
1363
+ return this._helpCommand;
1364
+ }
1365
+ return null;
1366
+ }
1367
+ /**
1368
+ * Add hook for life cycle event.
1369
+ *
1370
+ * @param {string} event
1371
+ * @param {Function} listener
1372
+ * @return {Command} `this` command for chaining
1373
+ */
1374
+ hook(event, listener) {
1375
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1376
+ if (!allowedValues.includes(event)) {
1377
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1378
+ Expecting one of '${allowedValues.join("', '")}'`);
1379
+ }
1380
+ if (this._lifeCycleHooks[event]) {
1381
+ this._lifeCycleHooks[event].push(listener);
1382
+ } else {
1383
+ this._lifeCycleHooks[event] = [listener];
1384
+ }
1385
+ return this;
1386
+ }
1387
+ /**
1388
+ * Register callback to use as replacement for calling process.exit.
1389
+ *
1390
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1391
+ * @return {Command} `this` command for chaining
1392
+ */
1393
+ exitOverride(fn) {
1394
+ if (fn) {
1395
+ this._exitCallback = fn;
1396
+ } else {
1397
+ this._exitCallback = (err) => {
1398
+ if (err.code !== "commander.executeSubCommandAsync") {
1399
+ throw err;
1400
+ } else {
1401
+ }
1402
+ };
1403
+ }
1404
+ return this;
1405
+ }
1406
+ /**
1407
+ * Call process.exit, and _exitCallback if defined.
1408
+ *
1409
+ * @param {number} exitCode exit code for using with process.exit
1410
+ * @param {string} code an id string representing the error
1411
+ * @param {string} message human-readable description of the error
1412
+ * @return never
1413
+ * @private
1414
+ */
1415
+ _exit(exitCode, code, message) {
1416
+ if (this._exitCallback) {
1417
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1418
+ }
1419
+ process2.exit(exitCode);
1420
+ }
1421
+ /**
1422
+ * Register callback `fn` for the command.
1423
+ *
1424
+ * @example
1425
+ * program
1426
+ * .command('serve')
1427
+ * .description('start service')
1428
+ * .action(function() {
1429
+ * // do work here
1430
+ * });
1431
+ *
1432
+ * @param {Function} fn
1433
+ * @return {Command} `this` command for chaining
1434
+ */
1435
+ action(fn) {
1436
+ const listener = (args) => {
1437
+ const expectedArgsCount = this.registeredArguments.length;
1438
+ const actionArgs = args.slice(0, expectedArgsCount);
1439
+ if (this._storeOptionsAsProperties) {
1440
+ actionArgs[expectedArgsCount] = this;
1441
+ } else {
1442
+ actionArgs[expectedArgsCount] = this.opts();
1443
+ }
1444
+ actionArgs.push(this);
1445
+ return fn.apply(this, actionArgs);
1446
+ };
1447
+ this._actionHandler = listener;
1448
+ return this;
1449
+ }
1450
+ /**
1451
+ * Factory routine to create a new unattached option.
1452
+ *
1453
+ * See .option() for creating an attached option, which uses this routine to
1454
+ * create the option. You can override createOption to return a custom option.
1455
+ *
1456
+ * @param {string} flags
1457
+ * @param {string} [description]
1458
+ * @return {Option} new option
1459
+ */
1460
+ createOption(flags, description) {
1461
+ return new Option2(flags, description);
1462
+ }
1463
+ /**
1464
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1465
+ *
1466
+ * @param {(Option | Argument)} target
1467
+ * @param {string} value
1468
+ * @param {*} previous
1469
+ * @param {string} invalidArgumentMessage
1470
+ * @private
1471
+ */
1472
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1473
+ try {
1474
+ return target.parseArg(value, previous);
1475
+ } catch (err) {
1476
+ if (err.code === "commander.invalidArgument") {
1477
+ const message = `${invalidArgumentMessage} ${err.message}`;
1478
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1479
+ }
1480
+ throw err;
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Check for option flag conflicts.
1485
+ * Register option if no conflicts found, or throw on conflict.
1486
+ *
1487
+ * @param {Option} option
1488
+ * @private
1489
+ */
1490
+ _registerOption(option) {
1491
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1492
+ if (matchingOption) {
1493
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1494
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1495
+ - already used by option '${matchingOption.flags}'`);
1496
+ }
1497
+ this.options.push(option);
1498
+ }
1499
+ /**
1500
+ * Check for command name and alias conflicts with existing commands.
1501
+ * Register command if no conflicts found, or throw on conflict.
1502
+ *
1503
+ * @param {Command} command
1504
+ * @private
1505
+ */
1506
+ _registerCommand(command) {
1507
+ const knownBy = (cmd) => {
1508
+ return [cmd.name()].concat(cmd.aliases());
1509
+ };
1510
+ const alreadyUsed = knownBy(command).find(
1511
+ (name) => this._findCommand(name)
1512
+ );
1513
+ if (alreadyUsed) {
1514
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1515
+ const newCmd = knownBy(command).join("|");
1516
+ throw new Error(
1517
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1518
+ );
1519
+ }
1520
+ this.commands.push(command);
1521
+ }
1522
+ /**
1523
+ * Add an option.
1524
+ *
1525
+ * @param {Option} option
1526
+ * @return {Command} `this` command for chaining
1527
+ */
1528
+ addOption(option) {
1529
+ this._registerOption(option);
1530
+ const oname = option.name();
1531
+ const name = option.attributeName();
1532
+ if (option.negate) {
1533
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1534
+ if (!this._findOption(positiveLongFlag)) {
1535
+ this.setOptionValueWithSource(
1536
+ name,
1537
+ option.defaultValue === void 0 ? true : option.defaultValue,
1538
+ "default"
1539
+ );
1540
+ }
1541
+ } else if (option.defaultValue !== void 0) {
1542
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1543
+ }
1544
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1545
+ if (val == null && option.presetArg !== void 0) {
1546
+ val = option.presetArg;
1547
+ }
1548
+ const oldValue = this.getOptionValue(name);
1549
+ if (val !== null && option.parseArg) {
1550
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1551
+ } else if (val !== null && option.variadic) {
1552
+ val = option._concatValue(val, oldValue);
1553
+ }
1554
+ if (val == null) {
1555
+ if (option.negate) {
1556
+ val = false;
1557
+ } else if (option.isBoolean() || option.optional) {
1558
+ val = true;
1559
+ } else {
1560
+ val = "";
1561
+ }
1562
+ }
1563
+ this.setOptionValueWithSource(name, val, valueSource);
1564
+ };
1565
+ this.on("option:" + oname, (val) => {
1566
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1567
+ handleOptionValue(val, invalidValueMessage, "cli");
1568
+ });
1569
+ if (option.envVar) {
1570
+ this.on("optionEnv:" + oname, (val) => {
1571
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1572
+ handleOptionValue(val, invalidValueMessage, "env");
1573
+ });
1574
+ }
1575
+ return this;
1576
+ }
1577
+ /**
1578
+ * Internal implementation shared by .option() and .requiredOption()
1579
+ *
1580
+ * @return {Command} `this` command for chaining
1581
+ * @private
1582
+ */
1583
+ _optionEx(config, flags, description, fn, defaultValue) {
1584
+ if (typeof flags === "object" && flags instanceof Option2) {
1585
+ throw new Error(
1586
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1587
+ );
1588
+ }
1589
+ const option = this.createOption(flags, description);
1590
+ option.makeOptionMandatory(!!config.mandatory);
1591
+ if (typeof fn === "function") {
1592
+ option.default(defaultValue).argParser(fn);
1593
+ } else if (fn instanceof RegExp) {
1594
+ const regex = fn;
1595
+ fn = (val, def) => {
1596
+ const m = regex.exec(val);
1597
+ return m ? m[0] : def;
1598
+ };
1599
+ option.default(defaultValue).argParser(fn);
1600
+ } else {
1601
+ option.default(fn);
1602
+ }
1603
+ return this.addOption(option);
1604
+ }
1605
+ /**
1606
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1607
+ *
1608
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1609
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1610
+ *
1611
+ * See the README for more details, and see also addOption() and requiredOption().
1612
+ *
1613
+ * @example
1614
+ * program
1615
+ * .option('-p, --pepper', 'add pepper')
1616
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1617
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1618
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1619
+ *
1620
+ * @param {string} flags
1621
+ * @param {string} [description]
1622
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1623
+ * @param {*} [defaultValue]
1624
+ * @return {Command} `this` command for chaining
1625
+ */
1626
+ option(flags, description, parseArg, defaultValue) {
1627
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1628
+ }
1629
+ /**
1630
+ * Add a required option which must have a value after parsing. This usually means
1631
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1632
+ *
1633
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1634
+ *
1635
+ * @param {string} flags
1636
+ * @param {string} [description]
1637
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1638
+ * @param {*} [defaultValue]
1639
+ * @return {Command} `this` command for chaining
1640
+ */
1641
+ requiredOption(flags, description, parseArg, defaultValue) {
1642
+ return this._optionEx(
1643
+ { mandatory: true },
1644
+ flags,
1645
+ description,
1646
+ parseArg,
1647
+ defaultValue
1648
+ );
1649
+ }
1650
+ /**
1651
+ * Alter parsing of short flags with optional values.
1652
+ *
1653
+ * @example
1654
+ * // for `.option('-f,--flag [value]'):
1655
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1656
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1657
+ *
1658
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1659
+ * @return {Command} `this` command for chaining
1660
+ */
1661
+ combineFlagAndOptionalValue(combine = true) {
1662
+ this._combineFlagAndOptionalValue = !!combine;
1663
+ return this;
1664
+ }
1665
+ /**
1666
+ * Allow unknown options on the command line.
1667
+ *
1668
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1669
+ * @return {Command} `this` command for chaining
1670
+ */
1671
+ allowUnknownOption(allowUnknown = true) {
1672
+ this._allowUnknownOption = !!allowUnknown;
1673
+ return this;
1674
+ }
1675
+ /**
1676
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1677
+ *
1678
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1679
+ * @return {Command} `this` command for chaining
1680
+ */
1681
+ allowExcessArguments(allowExcess = true) {
1682
+ this._allowExcessArguments = !!allowExcess;
1683
+ return this;
1684
+ }
1685
+ /**
1686
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1687
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1688
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1689
+ *
1690
+ * @param {boolean} [positional]
1691
+ * @return {Command} `this` command for chaining
1692
+ */
1693
+ enablePositionalOptions(positional = true) {
1694
+ this._enablePositionalOptions = !!positional;
1695
+ return this;
1696
+ }
1697
+ /**
1698
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1699
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1700
+ * positional options to have been enabled on the program (parent commands).
1701
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1702
+ *
1703
+ * @param {boolean} [passThrough] for unknown options.
1704
+ * @return {Command} `this` command for chaining
1705
+ */
1706
+ passThroughOptions(passThrough = true) {
1707
+ this._passThroughOptions = !!passThrough;
1708
+ this._checkForBrokenPassThrough();
1709
+ return this;
1710
+ }
1711
+ /**
1712
+ * @private
1713
+ */
1714
+ _checkForBrokenPassThrough() {
1715
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1716
+ throw new Error(
1717
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1718
+ );
1719
+ }
1720
+ }
1721
+ /**
1722
+ * Whether to store option values as properties on command object,
1723
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1724
+ *
1725
+ * @param {boolean} [storeAsProperties=true]
1726
+ * @return {Command} `this` command for chaining
1727
+ */
1728
+ storeOptionsAsProperties(storeAsProperties = true) {
1729
+ if (this.options.length) {
1730
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1731
+ }
1732
+ if (Object.keys(this._optionValues).length) {
1733
+ throw new Error(
1734
+ "call .storeOptionsAsProperties() before setting option values"
1735
+ );
1736
+ }
1737
+ this._storeOptionsAsProperties = !!storeAsProperties;
1738
+ return this;
1739
+ }
1740
+ /**
1741
+ * Retrieve option value.
1742
+ *
1743
+ * @param {string} key
1744
+ * @return {object} value
1745
+ */
1746
+ getOptionValue(key) {
1747
+ if (this._storeOptionsAsProperties) {
1748
+ return this[key];
1749
+ }
1750
+ return this._optionValues[key];
1751
+ }
1752
+ /**
1753
+ * Store option value.
1754
+ *
1755
+ * @param {string} key
1756
+ * @param {object} value
1757
+ * @return {Command} `this` command for chaining
1758
+ */
1759
+ setOptionValue(key, value) {
1760
+ return this.setOptionValueWithSource(key, value, void 0);
1761
+ }
1762
+ /**
1763
+ * Store option value and where the value came from.
1764
+ *
1765
+ * @param {string} key
1766
+ * @param {object} value
1767
+ * @param {string} source - expected values are default/config/env/cli/implied
1768
+ * @return {Command} `this` command for chaining
1769
+ */
1770
+ setOptionValueWithSource(key, value, source) {
1771
+ if (this._storeOptionsAsProperties) {
1772
+ this[key] = value;
1773
+ } else {
1774
+ this._optionValues[key] = value;
1775
+ }
1776
+ this._optionValueSources[key] = source;
1777
+ return this;
1778
+ }
1779
+ /**
1780
+ * Get source of option value.
1781
+ * Expected values are default | config | env | cli | implied
1782
+ *
1783
+ * @param {string} key
1784
+ * @return {string}
1785
+ */
1786
+ getOptionValueSource(key) {
1787
+ return this._optionValueSources[key];
1788
+ }
1789
+ /**
1790
+ * Get source of option value. See also .optsWithGlobals().
1791
+ * Expected values are default | config | env | cli | implied
1792
+ *
1793
+ * @param {string} key
1794
+ * @return {string}
1795
+ */
1796
+ getOptionValueSourceWithGlobals(key) {
1797
+ let source;
1798
+ this._getCommandAndAncestors().forEach((cmd) => {
1799
+ if (cmd.getOptionValueSource(key) !== void 0) {
1800
+ source = cmd.getOptionValueSource(key);
1801
+ }
1802
+ });
1803
+ return source;
1804
+ }
1805
+ /**
1806
+ * Get user arguments from implied or explicit arguments.
1807
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1808
+ *
1809
+ * @private
1810
+ */
1811
+ _prepareUserArgs(argv, parseOptions) {
1812
+ if (argv !== void 0 && !Array.isArray(argv)) {
1813
+ throw new Error("first parameter to parse must be array or undefined");
1814
+ }
1815
+ parseOptions = parseOptions || {};
1816
+ if (argv === void 0 && parseOptions.from === void 0) {
1817
+ if (process2.versions?.electron) {
1818
+ parseOptions.from = "electron";
1819
+ }
1820
+ const execArgv = process2.execArgv ?? [];
1821
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1822
+ parseOptions.from = "eval";
1823
+ }
1824
+ }
1825
+ if (argv === void 0) {
1826
+ argv = process2.argv;
1827
+ }
1828
+ this.rawArgs = argv.slice();
1829
+ let userArgs;
1830
+ switch (parseOptions.from) {
1831
+ case void 0:
1832
+ case "node":
1833
+ this._scriptPath = argv[1];
1834
+ userArgs = argv.slice(2);
1835
+ break;
1836
+ case "electron":
1837
+ if (process2.defaultApp) {
1838
+ this._scriptPath = argv[1];
1839
+ userArgs = argv.slice(2);
1840
+ } else {
1841
+ userArgs = argv.slice(1);
1842
+ }
1843
+ break;
1844
+ case "user":
1845
+ userArgs = argv.slice(0);
1846
+ break;
1847
+ case "eval":
1848
+ userArgs = argv.slice(1);
1849
+ break;
1850
+ default:
1851
+ throw new Error(
1852
+ `unexpected parse option { from: '${parseOptions.from}' }`
1853
+ );
1854
+ }
1855
+ if (!this._name && this._scriptPath)
1856
+ this.nameFromFilename(this._scriptPath);
1857
+ this._name = this._name || "program";
1858
+ return userArgs;
1859
+ }
1860
+ /**
1861
+ * Parse `argv`, setting options and invoking commands when defined.
1862
+ *
1863
+ * Use parseAsync instead of parse if any of your action handlers are async.
1864
+ *
1865
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1866
+ *
1867
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1868
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1869
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1870
+ * - `'user'`: just user arguments
1871
+ *
1872
+ * @example
1873
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1874
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1875
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1876
+ *
1877
+ * @param {string[]} [argv] - optional, defaults to process.argv
1878
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1879
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1880
+ * @return {Command} `this` command for chaining
1881
+ */
1882
+ parse(argv, parseOptions) {
1883
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1884
+ this._parseCommand([], userArgs);
1885
+ return this;
1886
+ }
1887
+ /**
1888
+ * Parse `argv`, setting options and invoking commands when defined.
1889
+ *
1890
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1891
+ *
1892
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1893
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1894
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1895
+ * - `'user'`: just user arguments
1896
+ *
1897
+ * @example
1898
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1899
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1900
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1901
+ *
1902
+ * @param {string[]} [argv]
1903
+ * @param {object} [parseOptions]
1904
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1905
+ * @return {Promise}
1906
+ */
1907
+ async parseAsync(argv, parseOptions) {
1908
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1909
+ await this._parseCommand([], userArgs);
1910
+ return this;
1911
+ }
1912
+ /**
1913
+ * Execute a sub-command executable.
1914
+ *
1915
+ * @private
1916
+ */
1917
+ _executeSubCommand(subcommand, args) {
1918
+ args = args.slice();
1919
+ let launchWithNode = false;
1920
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1921
+ function findFile(baseDir, baseName) {
1922
+ const localBin = path.resolve(baseDir, baseName);
1923
+ if (fs.existsSync(localBin)) return localBin;
1924
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1925
+ const foundExt = sourceExt.find(
1926
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1927
+ );
1928
+ if (foundExt) return `${localBin}${foundExt}`;
1929
+ return void 0;
1930
+ }
1931
+ this._checkForMissingMandatoryOptions();
1932
+ this._checkForConflictingOptions();
1933
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1934
+ let executableDir = this._executableDir || "";
1935
+ if (this._scriptPath) {
1936
+ let resolvedScriptPath;
1937
+ try {
1938
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1939
+ } catch (err) {
1940
+ resolvedScriptPath = this._scriptPath;
1941
+ }
1942
+ executableDir = path.resolve(
1943
+ path.dirname(resolvedScriptPath),
1944
+ executableDir
1945
+ );
1946
+ }
1947
+ if (executableDir) {
1948
+ let localFile = findFile(executableDir, executableFile);
1949
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1950
+ const legacyName = path.basename(
1951
+ this._scriptPath,
1952
+ path.extname(this._scriptPath)
1953
+ );
1954
+ if (legacyName !== this._name) {
1955
+ localFile = findFile(
1956
+ executableDir,
1957
+ `${legacyName}-${subcommand._name}`
1958
+ );
1959
+ }
1960
+ }
1961
+ executableFile = localFile || executableFile;
1962
+ }
1963
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1964
+ let proc;
1965
+ if (process2.platform !== "win32") {
1966
+ if (launchWithNode) {
1967
+ args.unshift(executableFile);
1968
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1969
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1970
+ } else {
1971
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1972
+ }
1973
+ } else {
1974
+ args.unshift(executableFile);
1975
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1976
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1977
+ }
1978
+ if (!proc.killed) {
1979
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1980
+ signals.forEach((signal) => {
1981
+ process2.on(signal, () => {
1982
+ if (proc.killed === false && proc.exitCode === null) {
1983
+ proc.kill(signal);
1984
+ }
1985
+ });
1986
+ });
1987
+ }
1988
+ const exitCallback = this._exitCallback;
1989
+ proc.on("close", (code) => {
1990
+ code = code ?? 1;
1991
+ if (!exitCallback) {
1992
+ process2.exit(code);
1993
+ } else {
1994
+ exitCallback(
1995
+ new CommanderError2(
1996
+ code,
1997
+ "commander.executeSubCommandAsync",
1998
+ "(close)"
1999
+ )
2000
+ );
2001
+ }
2002
+ });
2003
+ proc.on("error", (err) => {
2004
+ if (err.code === "ENOENT") {
2005
+ 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";
2006
+ const executableMissing = `'${executableFile}' does not exist
2007
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2008
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2009
+ - ${executableDirMessage}`;
2010
+ throw new Error(executableMissing);
2011
+ } else if (err.code === "EACCES") {
2012
+ throw new Error(`'${executableFile}' not executable`);
2013
+ }
2014
+ if (!exitCallback) {
2015
+ process2.exit(1);
2016
+ } else {
2017
+ const wrappedError = new CommanderError2(
2018
+ 1,
2019
+ "commander.executeSubCommandAsync",
2020
+ "(error)"
2021
+ );
2022
+ wrappedError.nestedError = err;
2023
+ exitCallback(wrappedError);
2024
+ }
2025
+ });
2026
+ this.runningCommand = proc;
2027
+ }
2028
+ /**
2029
+ * @private
2030
+ */
2031
+ _dispatchSubcommand(commandName, operands, unknown) {
2032
+ const subCommand = this._findCommand(commandName);
2033
+ if (!subCommand) this.help({ error: true });
2034
+ let promiseChain;
2035
+ promiseChain = this._chainOrCallSubCommandHook(
2036
+ promiseChain,
2037
+ subCommand,
2038
+ "preSubcommand"
2039
+ );
2040
+ promiseChain = this._chainOrCall(promiseChain, () => {
2041
+ if (subCommand._executableHandler) {
2042
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2043
+ } else {
2044
+ return subCommand._parseCommand(operands, unknown);
2045
+ }
2046
+ });
2047
+ return promiseChain;
2048
+ }
2049
+ /**
2050
+ * Invoke help directly if possible, or dispatch if necessary.
2051
+ * e.g. help foo
2052
+ *
2053
+ * @private
2054
+ */
2055
+ _dispatchHelpCommand(subcommandName) {
2056
+ if (!subcommandName) {
2057
+ this.help();
2058
+ }
2059
+ const subCommand = this._findCommand(subcommandName);
2060
+ if (subCommand && !subCommand._executableHandler) {
2061
+ subCommand.help();
2062
+ }
2063
+ return this._dispatchSubcommand(
2064
+ subcommandName,
2065
+ [],
2066
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2067
+ );
2068
+ }
2069
+ /**
2070
+ * Check this.args against expected this.registeredArguments.
2071
+ *
2072
+ * @private
2073
+ */
2074
+ _checkNumberOfArguments() {
2075
+ this.registeredArguments.forEach((arg, i) => {
2076
+ if (arg.required && this.args[i] == null) {
2077
+ this.missingArgument(arg.name());
2078
+ }
2079
+ });
2080
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2081
+ return;
2082
+ }
2083
+ if (this.args.length > this.registeredArguments.length) {
2084
+ this._excessArguments(this.args);
2085
+ }
2086
+ }
2087
+ /**
2088
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2089
+ *
2090
+ * @private
2091
+ */
2092
+ _processArguments() {
2093
+ const myParseArg = (argument, value, previous) => {
2094
+ let parsedValue = value;
2095
+ if (value !== null && argument.parseArg) {
2096
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2097
+ parsedValue = this._callParseArg(
2098
+ argument,
2099
+ value,
2100
+ previous,
2101
+ invalidValueMessage
2102
+ );
2103
+ }
2104
+ return parsedValue;
2105
+ };
2106
+ this._checkNumberOfArguments();
2107
+ const processedArgs = [];
2108
+ this.registeredArguments.forEach((declaredArg, index) => {
2109
+ let value = declaredArg.defaultValue;
2110
+ if (declaredArg.variadic) {
2111
+ if (index < this.args.length) {
2112
+ value = this.args.slice(index);
2113
+ if (declaredArg.parseArg) {
2114
+ value = value.reduce((processed, v) => {
2115
+ return myParseArg(declaredArg, v, processed);
2116
+ }, declaredArg.defaultValue);
2117
+ }
2118
+ } else if (value === void 0) {
2119
+ value = [];
2120
+ }
2121
+ } else if (index < this.args.length) {
2122
+ value = this.args[index];
2123
+ if (declaredArg.parseArg) {
2124
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2125
+ }
2126
+ }
2127
+ processedArgs[index] = value;
2128
+ });
2129
+ this.processedArgs = processedArgs;
2130
+ }
2131
+ /**
2132
+ * Once we have a promise we chain, but call synchronously until then.
2133
+ *
2134
+ * @param {(Promise|undefined)} promise
2135
+ * @param {Function} fn
2136
+ * @return {(Promise|undefined)}
2137
+ * @private
2138
+ */
2139
+ _chainOrCall(promise, fn) {
2140
+ if (promise && promise.then && typeof promise.then === "function") {
2141
+ return promise.then(() => fn());
2142
+ }
2143
+ return fn();
2144
+ }
2145
+ /**
2146
+ *
2147
+ * @param {(Promise|undefined)} promise
2148
+ * @param {string} event
2149
+ * @return {(Promise|undefined)}
2150
+ * @private
2151
+ */
2152
+ _chainOrCallHooks(promise, event) {
2153
+ let result = promise;
2154
+ const hooks = [];
2155
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2156
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2157
+ hooks.push({ hookedCommand, callback });
2158
+ });
2159
+ });
2160
+ if (event === "postAction") {
2161
+ hooks.reverse();
2162
+ }
2163
+ hooks.forEach((hookDetail) => {
2164
+ result = this._chainOrCall(result, () => {
2165
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2166
+ });
2167
+ });
2168
+ return result;
2169
+ }
2170
+ /**
2171
+ *
2172
+ * @param {(Promise|undefined)} promise
2173
+ * @param {Command} subCommand
2174
+ * @param {string} event
2175
+ * @return {(Promise|undefined)}
2176
+ * @private
2177
+ */
2178
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2179
+ let result = promise;
2180
+ if (this._lifeCycleHooks[event] !== void 0) {
2181
+ this._lifeCycleHooks[event].forEach((hook) => {
2182
+ result = this._chainOrCall(result, () => {
2183
+ return hook(this, subCommand);
2184
+ });
2185
+ });
2186
+ }
2187
+ return result;
2188
+ }
2189
+ /**
2190
+ * Process arguments in context of this command.
2191
+ * Returns action result, in case it is a promise.
2192
+ *
2193
+ * @private
2194
+ */
2195
+ _parseCommand(operands, unknown) {
2196
+ const parsed = this.parseOptions(unknown);
2197
+ this._parseOptionsEnv();
2198
+ this._parseOptionsImplied();
2199
+ operands = operands.concat(parsed.operands);
2200
+ unknown = parsed.unknown;
2201
+ this.args = operands.concat(unknown);
2202
+ if (operands && this._findCommand(operands[0])) {
2203
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2204
+ }
2205
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2206
+ return this._dispatchHelpCommand(operands[1]);
2207
+ }
2208
+ if (this._defaultCommandName) {
2209
+ this._outputHelpIfRequested(unknown);
2210
+ return this._dispatchSubcommand(
2211
+ this._defaultCommandName,
2212
+ operands,
2213
+ unknown
2214
+ );
2215
+ }
2216
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2217
+ this.help({ error: true });
2218
+ }
2219
+ this._outputHelpIfRequested(parsed.unknown);
2220
+ this._checkForMissingMandatoryOptions();
2221
+ this._checkForConflictingOptions();
2222
+ const checkForUnknownOptions = () => {
2223
+ if (parsed.unknown.length > 0) {
2224
+ this.unknownOption(parsed.unknown[0]);
2225
+ }
2226
+ };
2227
+ const commandEvent = `command:${this.name()}`;
2228
+ if (this._actionHandler) {
2229
+ checkForUnknownOptions();
2230
+ this._processArguments();
2231
+ let promiseChain;
2232
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2233
+ promiseChain = this._chainOrCall(
2234
+ promiseChain,
2235
+ () => this._actionHandler(this.processedArgs)
2236
+ );
2237
+ if (this.parent) {
2238
+ promiseChain = this._chainOrCall(promiseChain, () => {
2239
+ this.parent.emit(commandEvent, operands, unknown);
2240
+ });
2241
+ }
2242
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2243
+ return promiseChain;
2244
+ }
2245
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2246
+ checkForUnknownOptions();
2247
+ this._processArguments();
2248
+ this.parent.emit(commandEvent, operands, unknown);
2249
+ } else if (operands.length) {
2250
+ if (this._findCommand("*")) {
2251
+ return this._dispatchSubcommand("*", operands, unknown);
2252
+ }
2253
+ if (this.listenerCount("command:*")) {
2254
+ this.emit("command:*", operands, unknown);
2255
+ } else if (this.commands.length) {
2256
+ this.unknownCommand();
2257
+ } else {
2258
+ checkForUnknownOptions();
2259
+ this._processArguments();
2260
+ }
2261
+ } else if (this.commands.length) {
2262
+ checkForUnknownOptions();
2263
+ this.help({ error: true });
2264
+ } else {
2265
+ checkForUnknownOptions();
2266
+ this._processArguments();
2267
+ }
2268
+ }
2269
+ /**
2270
+ * Find matching command.
2271
+ *
2272
+ * @private
2273
+ * @return {Command | undefined}
2274
+ */
2275
+ _findCommand(name) {
2276
+ if (!name) return void 0;
2277
+ return this.commands.find(
2278
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2279
+ );
2280
+ }
2281
+ /**
2282
+ * Return an option matching `arg` if any.
2283
+ *
2284
+ * @param {string} arg
2285
+ * @return {Option}
2286
+ * @package
2287
+ */
2288
+ _findOption(arg) {
2289
+ return this.options.find((option) => option.is(arg));
2290
+ }
2291
+ /**
2292
+ * Display an error message if a mandatory option does not have a value.
2293
+ * Called after checking for help flags in leaf subcommand.
2294
+ *
2295
+ * @private
2296
+ */
2297
+ _checkForMissingMandatoryOptions() {
2298
+ this._getCommandAndAncestors().forEach((cmd) => {
2299
+ cmd.options.forEach((anOption) => {
2300
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2301
+ cmd.missingMandatoryOptionValue(anOption);
2302
+ }
2303
+ });
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Display an error message if conflicting options are used together in this.
2308
+ *
2309
+ * @private
2310
+ */
2311
+ _checkForConflictingLocalOptions() {
2312
+ const definedNonDefaultOptions = this.options.filter((option) => {
2313
+ const optionKey = option.attributeName();
2314
+ if (this.getOptionValue(optionKey) === void 0) {
2315
+ return false;
2316
+ }
2317
+ return this.getOptionValueSource(optionKey) !== "default";
2318
+ });
2319
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2320
+ (option) => option.conflictsWith.length > 0
2321
+ );
2322
+ optionsWithConflicting.forEach((option) => {
2323
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2324
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2325
+ );
2326
+ if (conflictingAndDefined) {
2327
+ this._conflictingOption(option, conflictingAndDefined);
2328
+ }
2329
+ });
2330
+ }
2331
+ /**
2332
+ * Display an error message if conflicting options are used together.
2333
+ * Called after checking for help flags in leaf subcommand.
2334
+ *
2335
+ * @private
2336
+ */
2337
+ _checkForConflictingOptions() {
2338
+ this._getCommandAndAncestors().forEach((cmd) => {
2339
+ cmd._checkForConflictingLocalOptions();
2340
+ });
2341
+ }
2342
+ /**
2343
+ * Parse options from `argv` removing known options,
2344
+ * and return argv split into operands and unknown arguments.
2345
+ *
2346
+ * Examples:
2347
+ *
2348
+ * argv => operands, unknown
2349
+ * --known kkk op => [op], []
2350
+ * op --known kkk => [op], []
2351
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2352
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2353
+ *
2354
+ * @param {string[]} argv
2355
+ * @return {{operands: string[], unknown: string[]}}
2356
+ */
2357
+ parseOptions(argv) {
2358
+ const operands = [];
2359
+ const unknown = [];
2360
+ let dest = operands;
2361
+ const args = argv.slice();
2362
+ function maybeOption(arg) {
2363
+ return arg.length > 1 && arg[0] === "-";
2364
+ }
2365
+ let activeVariadicOption = null;
2366
+ while (args.length) {
2367
+ const arg = args.shift();
2368
+ if (arg === "--") {
2369
+ if (dest === unknown) dest.push(arg);
2370
+ dest.push(...args);
2371
+ break;
2372
+ }
2373
+ if (activeVariadicOption && !maybeOption(arg)) {
2374
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2375
+ continue;
2376
+ }
2377
+ activeVariadicOption = null;
2378
+ if (maybeOption(arg)) {
2379
+ const option = this._findOption(arg);
2380
+ if (option) {
2381
+ if (option.required) {
2382
+ const value = args.shift();
2383
+ if (value === void 0) this.optionMissingArgument(option);
2384
+ this.emit(`option:${option.name()}`, value);
2385
+ } else if (option.optional) {
2386
+ let value = null;
2387
+ if (args.length > 0 && !maybeOption(args[0])) {
2388
+ value = args.shift();
2389
+ }
2390
+ this.emit(`option:${option.name()}`, value);
2391
+ } else {
2392
+ this.emit(`option:${option.name()}`);
2393
+ }
2394
+ activeVariadicOption = option.variadic ? option : null;
2395
+ continue;
2396
+ }
2397
+ }
2398
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2399
+ const option = this._findOption(`-${arg[1]}`);
2400
+ if (option) {
2401
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2402
+ this.emit(`option:${option.name()}`, arg.slice(2));
2403
+ } else {
2404
+ this.emit(`option:${option.name()}`);
2405
+ args.unshift(`-${arg.slice(2)}`);
2406
+ }
2407
+ continue;
2408
+ }
2409
+ }
2410
+ if (/^--[^=]+=/.test(arg)) {
2411
+ const index = arg.indexOf("=");
2412
+ const option = this._findOption(arg.slice(0, index));
2413
+ if (option && (option.required || option.optional)) {
2414
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2415
+ continue;
2416
+ }
2417
+ }
2418
+ if (maybeOption(arg)) {
2419
+ dest = unknown;
2420
+ }
2421
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2422
+ if (this._findCommand(arg)) {
2423
+ operands.push(arg);
2424
+ if (args.length > 0) unknown.push(...args);
2425
+ break;
2426
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2427
+ operands.push(arg);
2428
+ if (args.length > 0) operands.push(...args);
2429
+ break;
2430
+ } else if (this._defaultCommandName) {
2431
+ unknown.push(arg);
2432
+ if (args.length > 0) unknown.push(...args);
2433
+ break;
2434
+ }
2435
+ }
2436
+ if (this._passThroughOptions) {
2437
+ dest.push(arg);
2438
+ if (args.length > 0) dest.push(...args);
2439
+ break;
2440
+ }
2441
+ dest.push(arg);
2442
+ }
2443
+ return { operands, unknown };
2444
+ }
2445
+ /**
2446
+ * Return an object containing local option values as key-value pairs.
2447
+ *
2448
+ * @return {object}
2449
+ */
2450
+ opts() {
2451
+ if (this._storeOptionsAsProperties) {
2452
+ const result = {};
2453
+ const len = this.options.length;
2454
+ for (let i = 0; i < len; i++) {
2455
+ const key = this.options[i].attributeName();
2456
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2457
+ }
2458
+ return result;
2459
+ }
2460
+ return this._optionValues;
2461
+ }
2462
+ /**
2463
+ * Return an object containing merged local and global option values as key-value pairs.
2464
+ *
2465
+ * @return {object}
2466
+ */
2467
+ optsWithGlobals() {
2468
+ return this._getCommandAndAncestors().reduce(
2469
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2470
+ {}
2471
+ );
2472
+ }
2473
+ /**
2474
+ * Display error message and exit (or call exitOverride).
2475
+ *
2476
+ * @param {string} message
2477
+ * @param {object} [errorOptions]
2478
+ * @param {string} [errorOptions.code] - an id string representing the error
2479
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2480
+ */
2481
+ error(message, errorOptions) {
2482
+ this._outputConfiguration.outputError(
2483
+ `${message}
2484
+ `,
2485
+ this._outputConfiguration.writeErr
2486
+ );
2487
+ if (typeof this._showHelpAfterError === "string") {
2488
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2489
+ `);
2490
+ } else if (this._showHelpAfterError) {
2491
+ this._outputConfiguration.writeErr("\n");
2492
+ this.outputHelp({ error: true });
2493
+ }
2494
+ const config = errorOptions || {};
2495
+ const exitCode = config.exitCode || 1;
2496
+ const code = config.code || "commander.error";
2497
+ this._exit(exitCode, code, message);
2498
+ }
2499
+ /**
2500
+ * Apply any option related environment variables, if option does
2501
+ * not have a value from cli or client code.
2502
+ *
2503
+ * @private
2504
+ */
2505
+ _parseOptionsEnv() {
2506
+ this.options.forEach((option) => {
2507
+ if (option.envVar && option.envVar in process2.env) {
2508
+ const optionKey = option.attributeName();
2509
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2510
+ this.getOptionValueSource(optionKey)
2511
+ )) {
2512
+ if (option.required || option.optional) {
2513
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2514
+ } else {
2515
+ this.emit(`optionEnv:${option.name()}`);
2516
+ }
2517
+ }
2518
+ }
2519
+ });
2520
+ }
2521
+ /**
2522
+ * Apply any implied option values, if option is undefined or default value.
2523
+ *
2524
+ * @private
2525
+ */
2526
+ _parseOptionsImplied() {
2527
+ const dualHelper = new DualOptions(this.options);
2528
+ const hasCustomOptionValue = (optionKey) => {
2529
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2530
+ };
2531
+ this.options.filter(
2532
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2533
+ this.getOptionValue(option.attributeName()),
2534
+ option
2535
+ )
2536
+ ).forEach((option) => {
2537
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2538
+ this.setOptionValueWithSource(
2539
+ impliedKey,
2540
+ option.implied[impliedKey],
2541
+ "implied"
2542
+ );
2543
+ });
2544
+ });
2545
+ }
2546
+ /**
2547
+ * Argument `name` is missing.
2548
+ *
2549
+ * @param {string} name
2550
+ * @private
2551
+ */
2552
+ missingArgument(name) {
2553
+ const message = `error: missing required argument '${name}'`;
2554
+ this.error(message, { code: "commander.missingArgument" });
2555
+ }
2556
+ /**
2557
+ * `Option` is missing an argument.
2558
+ *
2559
+ * @param {Option} option
2560
+ * @private
2561
+ */
2562
+ optionMissingArgument(option) {
2563
+ const message = `error: option '${option.flags}' argument missing`;
2564
+ this.error(message, { code: "commander.optionMissingArgument" });
2565
+ }
2566
+ /**
2567
+ * `Option` does not have a value, and is a mandatory option.
2568
+ *
2569
+ * @param {Option} option
2570
+ * @private
2571
+ */
2572
+ missingMandatoryOptionValue(option) {
2573
+ const message = `error: required option '${option.flags}' not specified`;
2574
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2575
+ }
2576
+ /**
2577
+ * `Option` conflicts with another option.
2578
+ *
2579
+ * @param {Option} option
2580
+ * @param {Option} conflictingOption
2581
+ * @private
2582
+ */
2583
+ _conflictingOption(option, conflictingOption) {
2584
+ const findBestOptionFromValue = (option2) => {
2585
+ const optionKey = option2.attributeName();
2586
+ const optionValue = this.getOptionValue(optionKey);
2587
+ const negativeOption = this.options.find(
2588
+ (target) => target.negate && optionKey === target.attributeName()
2589
+ );
2590
+ const positiveOption = this.options.find(
2591
+ (target) => !target.negate && optionKey === target.attributeName()
2592
+ );
2593
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2594
+ return negativeOption;
2595
+ }
2596
+ return positiveOption || option2;
2597
+ };
2598
+ const getErrorMessage = (option2) => {
2599
+ const bestOption = findBestOptionFromValue(option2);
2600
+ const optionKey = bestOption.attributeName();
2601
+ const source = this.getOptionValueSource(optionKey);
2602
+ if (source === "env") {
2603
+ return `environment variable '${bestOption.envVar}'`;
2604
+ }
2605
+ return `option '${bestOption.flags}'`;
2606
+ };
2607
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2608
+ this.error(message, { code: "commander.conflictingOption" });
2609
+ }
2610
+ /**
2611
+ * Unknown option `flag`.
2612
+ *
2613
+ * @param {string} flag
2614
+ * @private
2615
+ */
2616
+ unknownOption(flag) {
2617
+ if (this._allowUnknownOption) return;
2618
+ let suggestion = "";
2619
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2620
+ let candidateFlags = [];
2621
+ let command = this;
2622
+ do {
2623
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2624
+ candidateFlags = candidateFlags.concat(moreFlags);
2625
+ command = command.parent;
2626
+ } while (command && !command._enablePositionalOptions);
2627
+ suggestion = suggestSimilar(flag, candidateFlags);
2628
+ }
2629
+ const message = `error: unknown option '${flag}'${suggestion}`;
2630
+ this.error(message, { code: "commander.unknownOption" });
2631
+ }
2632
+ /**
2633
+ * Excess arguments, more than expected.
2634
+ *
2635
+ * @param {string[]} receivedArgs
2636
+ * @private
2637
+ */
2638
+ _excessArguments(receivedArgs) {
2639
+ if (this._allowExcessArguments) return;
2640
+ const expected = this.registeredArguments.length;
2641
+ const s = expected === 1 ? "" : "s";
2642
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2643
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2644
+ this.error(message, { code: "commander.excessArguments" });
2645
+ }
2646
+ /**
2647
+ * Unknown command.
2648
+ *
2649
+ * @private
2650
+ */
2651
+ unknownCommand() {
2652
+ const unknownName = this.args[0];
2653
+ let suggestion = "";
2654
+ if (this._showSuggestionAfterError) {
2655
+ const candidateNames = [];
2656
+ this.createHelp().visibleCommands(this).forEach((command) => {
2657
+ candidateNames.push(command.name());
2658
+ if (command.alias()) candidateNames.push(command.alias());
2659
+ });
2660
+ suggestion = suggestSimilar(unknownName, candidateNames);
2661
+ }
2662
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2663
+ this.error(message, { code: "commander.unknownCommand" });
2664
+ }
2665
+ /**
2666
+ * Get or set the program version.
2667
+ *
2668
+ * This method auto-registers the "-V, --version" option which will print the version number.
2669
+ *
2670
+ * You can optionally supply the flags and description to override the defaults.
2671
+ *
2672
+ * @param {string} [str]
2673
+ * @param {string} [flags]
2674
+ * @param {string} [description]
2675
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2676
+ */
2677
+ version(str, flags, description) {
2678
+ if (str === void 0) return this._version;
2679
+ this._version = str;
2680
+ flags = flags || "-V, --version";
2681
+ description = description || "output the version number";
2682
+ const versionOption = this.createOption(flags, description);
2683
+ this._versionOptionName = versionOption.attributeName();
2684
+ this._registerOption(versionOption);
2685
+ this.on("option:" + versionOption.name(), () => {
2686
+ this._outputConfiguration.writeOut(`${str}
2687
+ `);
2688
+ this._exit(0, "commander.version", str);
2689
+ });
2690
+ return this;
2691
+ }
2692
+ /**
2693
+ * Set the description.
2694
+ *
2695
+ * @param {string} [str]
2696
+ * @param {object} [argsDescription]
2697
+ * @return {(string|Command)}
2698
+ */
2699
+ description(str, argsDescription) {
2700
+ if (str === void 0 && argsDescription === void 0)
2701
+ return this._description;
2702
+ this._description = str;
2703
+ if (argsDescription) {
2704
+ this._argsDescription = argsDescription;
2705
+ }
2706
+ return this;
2707
+ }
2708
+ /**
2709
+ * Set the summary. Used when listed as subcommand of parent.
2710
+ *
2711
+ * @param {string} [str]
2712
+ * @return {(string|Command)}
2713
+ */
2714
+ summary(str) {
2715
+ if (str === void 0) return this._summary;
2716
+ this._summary = str;
2717
+ return this;
2718
+ }
2719
+ /**
2720
+ * Set an alias for the command.
2721
+ *
2722
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2723
+ *
2724
+ * @param {string} [alias]
2725
+ * @return {(string|Command)}
2726
+ */
2727
+ alias(alias) {
2728
+ if (alias === void 0) return this._aliases[0];
2729
+ let command = this;
2730
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2731
+ command = this.commands[this.commands.length - 1];
2732
+ }
2733
+ if (alias === command._name)
2734
+ throw new Error("Command alias can't be the same as its name");
2735
+ const matchingCommand = this.parent?._findCommand(alias);
2736
+ if (matchingCommand) {
2737
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2738
+ throw new Error(
2739
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2740
+ );
2741
+ }
2742
+ command._aliases.push(alias);
2743
+ return this;
2744
+ }
2745
+ /**
2746
+ * Set aliases for the command.
2747
+ *
2748
+ * Only the first alias is shown in the auto-generated help.
2749
+ *
2750
+ * @param {string[]} [aliases]
2751
+ * @return {(string[]|Command)}
2752
+ */
2753
+ aliases(aliases) {
2754
+ if (aliases === void 0) return this._aliases;
2755
+ aliases.forEach((alias) => this.alias(alias));
2756
+ return this;
2757
+ }
2758
+ /**
2759
+ * Set / get the command usage `str`.
2760
+ *
2761
+ * @param {string} [str]
2762
+ * @return {(string|Command)}
2763
+ */
2764
+ usage(str) {
2765
+ if (str === void 0) {
2766
+ if (this._usage) return this._usage;
2767
+ const args = this.registeredArguments.map((arg) => {
2768
+ return humanReadableArgName(arg);
2769
+ });
2770
+ return [].concat(
2771
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2772
+ this.commands.length ? "[command]" : [],
2773
+ this.registeredArguments.length ? args : []
2774
+ ).join(" ");
2775
+ }
2776
+ this._usage = str;
2777
+ return this;
2778
+ }
2779
+ /**
2780
+ * Get or set the name of the command.
2781
+ *
2782
+ * @param {string} [str]
2783
+ * @return {(string|Command)}
2784
+ */
2785
+ name(str) {
2786
+ if (str === void 0) return this._name;
2787
+ this._name = str;
2788
+ return this;
2789
+ }
2790
+ /**
2791
+ * Set the name of the command from script filename, such as process.argv[1],
2792
+ * or require.main.filename, or __filename.
2793
+ *
2794
+ * (Used internally and public although not documented in README.)
2795
+ *
2796
+ * @example
2797
+ * program.nameFromFilename(require.main.filename);
2798
+ *
2799
+ * @param {string} filename
2800
+ * @return {Command}
2801
+ */
2802
+ nameFromFilename(filename) {
2803
+ this._name = path.basename(filename, path.extname(filename));
2804
+ return this;
2805
+ }
2806
+ /**
2807
+ * Get or set the directory for searching for executable subcommands of this command.
2808
+ *
2809
+ * @example
2810
+ * program.executableDir(__dirname);
2811
+ * // or
2812
+ * program.executableDir('subcommands');
2813
+ *
2814
+ * @param {string} [path]
2815
+ * @return {(string|null|Command)}
2816
+ */
2817
+ executableDir(path2) {
2818
+ if (path2 === void 0) return this._executableDir;
2819
+ this._executableDir = path2;
2820
+ return this;
2821
+ }
2822
+ /**
2823
+ * Return program help documentation.
2824
+ *
2825
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2826
+ * @return {string}
2827
+ */
2828
+ helpInformation(contextOptions) {
2829
+ const helper = this.createHelp();
2830
+ if (helper.helpWidth === void 0) {
2831
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2832
+ }
2833
+ return helper.formatHelp(this, helper);
2834
+ }
2835
+ /**
2836
+ * @private
2837
+ */
2838
+ _getHelpContext(contextOptions) {
2839
+ contextOptions = contextOptions || {};
2840
+ const context = { error: !!contextOptions.error };
2841
+ let write;
2842
+ if (context.error) {
2843
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2844
+ } else {
2845
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2846
+ }
2847
+ context.write = contextOptions.write || write;
2848
+ context.command = this;
2849
+ return context;
2850
+ }
2851
+ /**
2852
+ * Output help information for this command.
2853
+ *
2854
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2855
+ *
2856
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2857
+ */
2858
+ outputHelp(contextOptions) {
2859
+ let deprecatedCallback;
2860
+ if (typeof contextOptions === "function") {
2861
+ deprecatedCallback = contextOptions;
2862
+ contextOptions = void 0;
2863
+ }
2864
+ const context = this._getHelpContext(contextOptions);
2865
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2866
+ this.emit("beforeHelp", context);
2867
+ let helpInformation = this.helpInformation(context);
2868
+ if (deprecatedCallback) {
2869
+ helpInformation = deprecatedCallback(helpInformation);
2870
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2871
+ throw new Error("outputHelp callback must return a string or a Buffer");
2872
+ }
2873
+ }
2874
+ context.write(helpInformation);
2875
+ if (this._getHelpOption()?.long) {
2876
+ this.emit(this._getHelpOption().long);
2877
+ }
2878
+ this.emit("afterHelp", context);
2879
+ this._getCommandAndAncestors().forEach(
2880
+ (command) => command.emit("afterAllHelp", context)
2881
+ );
2882
+ }
2883
+ /**
2884
+ * You can pass in flags and a description to customise the built-in help option.
2885
+ * Pass in false to disable the built-in help option.
2886
+ *
2887
+ * @example
2888
+ * program.helpOption('-?, --help' 'show help'); // customise
2889
+ * program.helpOption(false); // disable
2890
+ *
2891
+ * @param {(string | boolean)} flags
2892
+ * @param {string} [description]
2893
+ * @return {Command} `this` command for chaining
2894
+ */
2895
+ helpOption(flags, description) {
2896
+ if (typeof flags === "boolean") {
2897
+ if (flags) {
2898
+ this._helpOption = this._helpOption ?? void 0;
2899
+ } else {
2900
+ this._helpOption = null;
2901
+ }
2902
+ return this;
2903
+ }
2904
+ flags = flags ?? "-h, --help";
2905
+ description = description ?? "display help for command";
2906
+ this._helpOption = this.createOption(flags, description);
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Lazy create help option.
2911
+ * Returns null if has been disabled with .helpOption(false).
2912
+ *
2913
+ * @returns {(Option | null)} the help option
2914
+ * @package
2915
+ */
2916
+ _getHelpOption() {
2917
+ if (this._helpOption === void 0) {
2918
+ this.helpOption(void 0, void 0);
2919
+ }
2920
+ return this._helpOption;
2921
+ }
2922
+ /**
2923
+ * Supply your own option to use for the built-in help option.
2924
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2925
+ *
2926
+ * @param {Option} option
2927
+ * @return {Command} `this` command for chaining
2928
+ */
2929
+ addHelpOption(option) {
2930
+ this._helpOption = option;
2931
+ return this;
2932
+ }
2933
+ /**
2934
+ * Output help information and exit.
2935
+ *
2936
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2937
+ *
2938
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2939
+ */
2940
+ help(contextOptions) {
2941
+ this.outputHelp(contextOptions);
2942
+ let exitCode = process2.exitCode || 0;
2943
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2944
+ exitCode = 1;
2945
+ }
2946
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2947
+ }
2948
+ /**
2949
+ * Add additional text to be displayed with the built-in help.
2950
+ *
2951
+ * Position is 'before' or 'after' to affect just this command,
2952
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2953
+ *
2954
+ * @param {string} position - before or after built-in help
2955
+ * @param {(string | Function)} text - string to add, or a function returning a string
2956
+ * @return {Command} `this` command for chaining
2957
+ */
2958
+ addHelpText(position, text) {
2959
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2960
+ if (!allowedValues.includes(position)) {
2961
+ throw new Error(`Unexpected value for position to addHelpText.
2962
+ Expecting one of '${allowedValues.join("', '")}'`);
2963
+ }
2964
+ const helpEvent = `${position}Help`;
2965
+ this.on(helpEvent, (context) => {
2966
+ let helpStr;
2967
+ if (typeof text === "function") {
2968
+ helpStr = text({ error: context.error, command: context.command });
2969
+ } else {
2970
+ helpStr = text;
2971
+ }
2972
+ if (helpStr) {
2973
+ context.write(`${helpStr}
2974
+ `);
2975
+ }
2976
+ });
2977
+ return this;
2978
+ }
2979
+ /**
2980
+ * Output help information if help flags specified
2981
+ *
2982
+ * @param {Array} args - array of options to search for help flags
2983
+ * @private
2984
+ */
2985
+ _outputHelpIfRequested(args) {
2986
+ const helpOption = this._getHelpOption();
2987
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2988
+ if (helpRequested) {
2989
+ this.outputHelp();
2990
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2991
+ }
2992
+ }
2993
+ };
2994
+ function incrementNodeInspectorPort(args) {
2995
+ return args.map((arg) => {
2996
+ if (!arg.startsWith("--inspect")) {
2997
+ return arg;
2998
+ }
2999
+ let debugOption;
3000
+ let debugHost = "127.0.0.1";
3001
+ let debugPort = "9229";
3002
+ let match;
3003
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3004
+ debugOption = match[1];
3005
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3006
+ debugOption = match[1];
3007
+ if (/^\d+$/.test(match[3])) {
3008
+ debugPort = match[3];
3009
+ } else {
3010
+ debugHost = match[3];
3011
+ }
3012
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3013
+ debugOption = match[1];
3014
+ debugHost = match[3];
3015
+ debugPort = match[4];
3016
+ }
3017
+ if (debugOption && debugPort !== "0") {
3018
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3019
+ }
3020
+ return arg;
3021
+ });
3022
+ }
3023
+ exports.Command = Command2;
3024
+ }
3025
+ });
3026
+
3027
+ // node_modules/commander/index.js
3028
+ var require_commander = __commonJS({
3029
+ "node_modules/commander/index.js"(exports) {
3030
+ "use strict";
3031
+ var { Argument: Argument2 } = require_argument();
3032
+ var { Command: Command2 } = require_command();
3033
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3034
+ var { Help: Help2 } = require_help();
3035
+ var { Option: Option2 } = require_option();
3036
+ exports.program = new Command2();
3037
+ exports.createCommand = (name) => new Command2(name);
3038
+ exports.createOption = (flags, description) => new Option2(flags, description);
3039
+ exports.createArgument = (name, description) => new Argument2(name, description);
3040
+ exports.Command = Command2;
3041
+ exports.Option = Option2;
3042
+ exports.Argument = Argument2;
3043
+ exports.Help = Help2;
3044
+ exports.CommanderError = CommanderError2;
3045
+ exports.InvalidArgumentError = InvalidArgumentError2;
3046
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3047
+ }
3048
+ });
3049
+
3050
+ // node_modules/commander/esm.mjs
3051
+ var import_index = __toESM(require_commander(), 1);
3052
+ var {
3053
+ program,
3054
+ createCommand,
3055
+ createArgument,
3056
+ createOption,
3057
+ CommanderError,
3058
+ InvalidArgumentError,
3059
+ InvalidOptionArgumentError,
3060
+ // deprecated old name
3061
+ Command,
3062
+ Argument,
3063
+ Option,
3064
+ Help
3065
+ } = import_index.default;
3066
+
3067
+ // src/cli/resolve.ts
3068
+ function resolveDefaults(flags) {
3069
+ const cfg = flags.noConfig ? {} : readConfig();
3070
+ const preset = pickPreset(flags.preset, cfg.preset);
3071
+ const presetSettings = resolvePreset(preset);
3072
+ const model = flags.model ?? presetSettings.model;
3073
+ const reasoningEffort = presetSettings.reasoningEffort;
3074
+ const mcp2 = flags.mcp && flags.mcp.length > 0 ? flags.mcp : cfg.mcp ?? [];
3075
+ const session = resolveSession(flags.session, cfg.session);
3076
+ return { model, reasoningEffort, mcp: mcp2, session };
3077
+ }
3078
+ function pickPreset(flagPreset, configPreset) {
3079
+ if (flagPreset && isPresetName(flagPreset)) return flagPreset;
3080
+ if (configPreset) return configPreset;
3081
+ return "auto";
3082
+ }
3083
+ function isPresetName(s) {
3084
+ return s === "auto" || s === "flash" || s === "pro" || // Legacy names — kept callable so old `--preset smart` invocations
3085
+ // and stale config.json entries don't error out.
3086
+ s === "fast" || s === "smart" || s === "max";
3087
+ }
3088
+ function resolveSession(flag, configSession) {
3089
+ if (flag === false) return void 0;
3090
+ if (typeof flag === "string" && flag.length > 0) return flag;
3091
+ if (configSession === null) return void 0;
3092
+ if (typeof configSession === "string" && configSession.length > 0) return configSession;
3093
+ return "default";
3094
+ }
3095
+ function resolveContinueFlag(flag, fallbackSession, getLatestSession, warn = () => {
3096
+ }) {
3097
+ if (!flag) return { session: fallbackSession, forceResume: false };
3098
+ const latest = getLatestSession();
3099
+ if (!latest) {
3100
+ warn("\u25B8 -c/--continue: no saved sessions yet \u2014 starting a fresh one.");
3101
+ return { session: fallbackSession, forceResume: false };
3102
+ }
3103
+ return { session: latest.name, forceResume: true };
3104
+ }
3105
+
3106
+ // src/cli/index.ts
3107
+ installProxyIfConfigured();
3108
+ markPhase("cli_module_loaded");
3109
+ function defaultSystemPrompt(modelId) {
3110
+ return `You are Luckerr, a helpful DeepSeek-powered assistant. Be concise and accurate. Use tools when available.
3111
+
3112
+ # Cite or shut up \u2014 non-negotiable
3113
+
3114
+ Every factual claim about a codebase must be backed by evidence. Luckerr VALIDATES your citations \u2014 broken paths render in **red strikethrough with \u274C** in front of the user.
3115
+
3116
+ **Positive claims** \u2014 append a markdown link:
3117
+ - \u2705 \`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\`
3118
+ - \u274C \`The MCP client supports listResources.\` \u2190 unverifiable, do not write.
3119
+
3120
+ **Negative claims** ("X is missing", "Y isn't implemented", "lacks Z") are the #1 hallucination shape. STOP before writing them. If you have a search tool, call it first; if the search returns nothing, cite the search itself as evidence (\`No matches for "foo" in src/\`). If you have no tool, qualify hard: "I haven't verified \u2014 this is a guess."
3121
+
3122
+ Asserting absence without checking is how evaluative answers go wrong. Treat the urge to write "missing" as a red flag in your own reasoning.
3123
+
3124
+ # Don't invent what changes \u2014 search instead
3125
+
3126
+ Your training data has a cutoff. When an answer's correctness depends on something that changes over time (the user is asking what's happening, not what's true) and a search tool is available, search first. Inventing currently-correct values from training memory is the most common way these answers go wrong, and the user usually can't tell until much later.
3127
+
3128
+ The signal isn't a topic list \u2014 it's: "if I'm wrong about this, is it because reality moved on?". If yes, ground the answer in fresh evidence; if no (definitions, mechanisms, well-established APIs), answer from memory.
3129
+
3130
+ ${escalationContract(modelId)}`;
3131
+ }
3132
+ function parseBudgetFlag(raw) {
3133
+ if (raw === void 0) return void 0;
3134
+ if (!Number.isFinite(raw) || raw <= 0) {
3135
+ process.stderr.write(
3136
+ `\u25B2 ignoring --budget=${raw} (must be a positive number) \u2014 running with no cap
3137
+ `
3138
+ );
3139
+ return void 0;
3140
+ }
3141
+ return raw;
3142
+ }
3143
+ function parseEscalateAfterFlag(raw) {
3144
+ if (raw === void 0) return void 0;
3145
+ if (!Number.isInteger(raw) || raw < 1 || raw > 20) {
3146
+ process.stderr.write(
3147
+ `\u25B2 ignoring --escalate-after=${raw} (must be an integer in [1,20]) \u2014 using default
3148
+ `
3149
+ );
3150
+ return void 0;
3151
+ }
3152
+ return raw;
3153
+ }
3154
+ function resolveFailureThreshold(flagValue, noConfig) {
3155
+ if (flagValue !== void 0) return flagValue;
3156
+ if (noConfig) return void 0;
3157
+ const fromCfg = readConfig().escalation?.failureThreshold;
3158
+ if (typeof fromCfg !== "number") return void 0;
3159
+ if (!Number.isInteger(fromCfg) || fromCfg < 1 || fromCfg > 20) {
3160
+ process.stderr.write(
3161
+ `\u25B2 ignoring escalation.failureThreshold=${fromCfg} from config (must be an integer in [1,20]) \u2014 using default
3162
+ `
3163
+ );
3164
+ return void 0;
3165
+ }
3166
+ return fromCfg;
3167
+ }
3168
+ function parseDashboardPortFlag(raw) {
3169
+ if (raw === void 0) return void 0;
3170
+ const n = Number.parseInt(raw, 10);
3171
+ if (!Number.isInteger(n) || n < 1 || n > 65535) {
3172
+ process.stderr.write(`${t("ui.dashboardPortInvalid", { value: raw })}
3173
+ `);
3174
+ return void 0;
3175
+ }
3176
+ return n;
3177
+ }
3178
+ function resolveDashboardPort(flagValue, noConfig) {
3179
+ if (flagValue !== void 0) return flagValue;
3180
+ if (noConfig) return void 0;
3181
+ const fromCfg = readConfig().dashboard?.port;
3182
+ return typeof fromCfg === "number" && Number.isInteger(fromCfg) && fromCfg >= 1 && fromCfg <= 65535 ? fromCfg : void 0;
3183
+ }
3184
+ var program2 = new Command();
3185
+ program2.name("luckerr").description(t("cli.description")).version(VERSION).option("-c, --continue", t("cli.continue"));
3186
+ program2.action(async (opts) => {
3187
+ const cfg = readConfig();
3188
+ if (!cfg.setupCompleted) {
3189
+ const { setupCommand } = await import("./setup-VV4WKXHV.js");
3190
+ await setupCommand({ forceKeyStep: true });
3191
+ return;
3192
+ }
3193
+ const defaults = resolveDefaults({});
3194
+ const continueOpts = resolveContinueFlag(
3195
+ opts.continue,
3196
+ defaults.session,
3197
+ () => listSessions()[0],
3198
+ (msg) => process.stderr.write(`${msg}
3199
+ `)
3200
+ );
3201
+ const { chatCommand } = await import("./chat-7J6GJXL2.js");
3202
+ const defaultBase = defaultSystemPrompt(defaults.model);
3203
+ const defaultCwd = process.cwd();
3204
+ const defaultRebuildSystem = () => applyMemoryStack(defaultBase, defaultCwd);
3205
+ await chatCommand({
3206
+ model: defaults.model,
3207
+ system: defaultRebuildSystem(),
3208
+ rebuildSystem: defaultRebuildSystem,
3209
+ session: continueOpts.session,
3210
+ mcp: defaults.mcp,
3211
+ forceResume: continueOpts.forceResume
3212
+ });
3213
+ });
3214
+ program2.command("setup").description(t("cli.setup")).action(async () => {
3215
+ const { setupCommand } = await import("./setup-VV4WKXHV.js");
3216
+ await setupCommand({ forceKeyStep: true });
3217
+ });
3218
+ program2.command("code [dir]").description(t("cli.code")).option("-m, --model <id>", t("ui.modelOverride")).option("--no-session", t("ui.noSession")).option("-r, --resume", t("ui.resumeHint")).option("-n, --new", t("ui.newHint")).option("--transcript <path>", t("ui.transcriptHint")).option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v)).option(
3219
+ "--escalate-after <n>",
3220
+ "repair-signal count before flash\u2192pro escalation (default 3)",
3221
+ (v) => Number.parseInt(v, 10)
3222
+ ).option("--no-dashboard", t("ui.noDashboard")).option("--dashboard-port <port>", t("ui.dashboardPortHint")).option("--no-alt-screen", "keep chat output in shell scrollback (legacy mode, ghost-prone)").option("--no-mouse", "disable SGR mouse tracking (keeps drag-select 100% native)").option("--system-append <prompt>", t("ui.systemAppendHint")).option("--system-append-file <path>", t("ui.systemAppendFileHint")).action(async (dir, opts) => {
3223
+ const { codeCommand } = await import("./code-CRKVCMFZ.js");
3224
+ await codeCommand({
3225
+ dir,
3226
+ model: opts.model,
3227
+ noSession: opts.session === false,
3228
+ transcript: opts.transcript,
3229
+ forceResume: !!opts.resume,
3230
+ forceNew: !!opts.new,
3231
+ budgetUsd: parseBudgetFlag(opts.budget),
3232
+ failureThreshold: resolveFailureThreshold(parseEscalateAfterFlag(opts.escalateAfter), false),
3233
+ noDashboard: opts.dashboard === false,
3234
+ dashboardPort: resolveDashboardPort(parseDashboardPortFlag(opts.dashboardPort), false),
3235
+ systemAppend: opts.systemAppend,
3236
+ systemAppendFile: opts.systemAppendFile,
3237
+ altScreen: opts.altScreen !== false,
3238
+ mouse: opts.mouse !== false
3239
+ });
3240
+ });
3241
+ program2.command("chat").description(t("cli.chat")).option("-m, --model <id>", t("ui.modelIdHint")).option("-s, --system <prompt>", t("ui.systemPromptHint")).option("--transcript <path>", t("ui.transcriptHint")).option("--preset <name>", t("ui.presetHint")).option("--budget <usd>", t("ui.budgetHint"), (v) => Number.parseFloat(v)).option(
3242
+ "--escalate-after <n>",
3243
+ "repair-signal count before flash\u2192pro escalation (default 3)",
3244
+ (v) => Number.parseInt(v, 10)
3245
+ ).option("--session <name>", t("ui.sessionNameHint")).option("--no-session", t("ui.ephemeralHint")).option("-r, --resume", t("ui.resumeHint")).option("-c, --continue", t("cli.continue")).option("-n, --new", t("ui.newHint")).option(
3246
+ "--mcp <spec>",
3247
+ t("ui.mcpSpecHint"),
3248
+ (value, previous = []) => [...previous, value],
3249
+ []
3250
+ ).option("--mcp-prefix <str>", t("ui.mcpPrefixHint")).option("--no-config", t("ui.noConfigHint")).option("--no-dashboard", t("ui.noDashboard")).option("--dashboard-port <port>", t("ui.dashboardPortHint")).option("--no-alt-screen", "keep chat output in shell scrollback (legacy mode, ghost-prone)").option("--no-mouse", "disable SGR mouse tracking (keeps drag-select 100% native)").action(async (opts) => {
3251
+ const defaults = resolveDefaults({
3252
+ model: opts.model,
3253
+ mcp: opts.mcp,
3254
+ session: opts.session,
3255
+ preset: opts.preset,
3256
+ noConfig: opts.config === false
3257
+ });
3258
+ const continueOpts = opts.resume ? { session: defaults.session, forceResume: true } : resolveContinueFlag(
3259
+ opts.continue,
3260
+ defaults.session,
3261
+ () => listSessions()[0],
3262
+ (msg) => process.stderr.write(`${msg}
3263
+ `)
3264
+ );
3265
+ const { chatCommand } = await import("./chat-7J6GJXL2.js");
3266
+ const chatBase = opts.system ?? defaultSystemPrompt(defaults.model);
3267
+ const chatCwd = process.cwd();
3268
+ const chatRebuildSystem = () => applyMemoryStack(chatBase, chatCwd);
3269
+ await chatCommand({
3270
+ model: defaults.model,
3271
+ system: chatRebuildSystem(),
3272
+ rebuildSystem: chatRebuildSystem,
3273
+ transcript: opts.transcript,
3274
+ budgetUsd: parseBudgetFlag(opts.budget),
3275
+ failureThreshold: resolveFailureThreshold(
3276
+ parseEscalateAfterFlag(opts.escalateAfter),
3277
+ opts.config === false
3278
+ ),
3279
+ session: continueOpts.session,
3280
+ mcp: defaults.mcp,
3281
+ mcpPrefix: opts.mcpPrefix,
3282
+ forceResume: continueOpts.forceResume,
3283
+ forceNew: !!opts.new,
3284
+ noDashboard: opts.dashboard === false,
3285
+ dashboardPort: resolveDashboardPort(
3286
+ parseDashboardPortFlag(opts.dashboardPort),
3287
+ opts.config === false
3288
+ ),
3289
+ altScreen: opts.altScreen !== false,
3290
+ mouse: opts.mouse !== false
3291
+ });
3292
+ });
3293
+ program2.command("run <task>").description(t("cli.run")).option("-m, --model <id>", t("ui.modelIdHint")).option("-s, --system <prompt>", t("ui.systemPromptHint")).option("--preset <name>", t("ui.presetHintShort")).option("--budget <usd>", t("ui.budgetHintShort"), (v) => Number.parseFloat(v)).option(
3294
+ "--escalate-after <n>",
3295
+ "repair-signal count before flash\u2192pro escalation (default 3)",
3296
+ (v) => Number.parseInt(v, 10)
3297
+ ).option("--transcript <path>", t("ui.transcriptHintShort")).option(
3298
+ "--mcp <spec>",
3299
+ t("ui.mcpSpecHintShort"),
3300
+ (value, previous = []) => [...previous, value],
3301
+ []
3302
+ ).option("--mcp-prefix <str>", t("ui.mcpPrefixHintShort")).option("--no-config", t("ui.noConfigHint")).action(async (task, opts) => {
3303
+ const defaults = resolveDefaults({
3304
+ model: opts.model,
3305
+ mcp: opts.mcp,
3306
+ preset: opts.preset,
3307
+ noConfig: opts.config === false
3308
+ });
3309
+ const { runCommand } = await import("./run-RCAC2RYW.js");
3310
+ await runCommand({
3311
+ task,
3312
+ model: defaults.model,
3313
+ system: applyMemoryStack(opts.system ?? defaultSystemPrompt(defaults.model), process.cwd()),
3314
+ budgetUsd: parseBudgetFlag(opts.budget),
3315
+ failureThreshold: resolveFailureThreshold(
3316
+ parseEscalateAfterFlag(opts.escalateAfter),
3317
+ opts.config === false
3318
+ ),
3319
+ transcript: opts.transcript,
3320
+ mcp: defaults.mcp,
3321
+ mcpPrefix: opts.mcpPrefix
3322
+ });
3323
+ });
3324
+ program2.command("acp").description("run luckerr as an Agent Client Protocol (ACP) agent on stdio NDJSON JSON-RPC").option("-m, --model <id>", t("ui.modelIdHint")).option("--dir <path>", "root directory for filesystem tools (default: cwd)").option("--preset <name>", t("ui.presetHintShort")).option("--budget <usd>", t("ui.budgetHintShort"), (v) => Number.parseFloat(v)).option("--transcript <path>", t("ui.transcriptHint")).option(
3325
+ "--yolo",
3326
+ "auto-approve plan checkpoints for this invocation (equivalent to editMode=yolo without mutating config)"
3327
+ ).option(
3328
+ "--mcp <spec>",
3329
+ t("ui.mcpSpecHintShort"),
3330
+ (value, previous = []) => [...previous, value],
3331
+ []
3332
+ ).option("--mcp-prefix <str>", t("ui.mcpPrefixHintShort")).action(async (opts) => {
3333
+ const defaults = resolveDefaults({
3334
+ model: opts.model,
3335
+ mcp: opts.mcp,
3336
+ preset: opts.preset,
3337
+ noConfig: false
3338
+ });
3339
+ const { acpCommand } = await import("./acp-EOOAI4F5.js");
3340
+ await acpCommand({
3341
+ model: defaults.model,
3342
+ budgetUsd: parseBudgetFlag(opts.budget),
3343
+ dir: opts.dir,
3344
+ transcript: opts.transcript,
3345
+ yolo: !!opts.yolo,
3346
+ mcpSpecs: defaults.mcp,
3347
+ mcpPrefix: opts.mcpPrefix
3348
+ });
3349
+ });
3350
+ program2.command("desktop").description("headless JSON-RPC chat for the desktop client (internal)").option("-m, --model <id>", t("ui.modelIdHint")).option("--dir <path>", "root directory for filesystem tools (default: cwd)").option("--preset <name>", t("ui.presetHintShort")).option("--budget <usd>", t("ui.budgetHintShort"), (v) => Number.parseFloat(v)).action(async (opts) => {
3351
+ const defaults = resolveDefaults({
3352
+ model: opts.model,
3353
+ mcp: [],
3354
+ preset: opts.preset,
3355
+ noConfig: false
3356
+ });
3357
+ const { desktopCommand } = await import("./desktop-R6W5CLJ5.js");
3358
+ await desktopCommand({
3359
+ model: defaults.model,
3360
+ budgetUsd: parseBudgetFlag(opts.budget),
3361
+ dir: opts.dir
3362
+ });
3363
+ });
3364
+ program2.command("stats [transcript]").description(t("cli.stats")).action(async (transcript) => {
3365
+ const { statsCommand } = await import("./stats-JVZPQWAN.js");
3366
+ statsCommand({ transcript });
3367
+ });
3368
+ program2.command("doctor").description(t("cli.doctor")).option("--json", t("ui.jsonHint")).action(async (opts) => {
3369
+ const { doctorCommand } = await import("./doctor-5IBP4R5J.js");
3370
+ await doctorCommand({ json: !!opts.json });
3371
+ });
3372
+ program2.command("commit").description(t("cli.commit")).option("-m, --model <id>", t("ui.modelOverrideFlash")).option("-y, --yes", t("ui.skipConfirmHint")).action(async (opts) => {
3373
+ const { commitCommand } = await import("./commit-53PP32NC.js");
3374
+ await commitCommand({ model: opts.model, yes: !!opts.yes });
3375
+ });
3376
+ program2.command("sessions [name]").description(t("cli.sessions")).option("-v, --verbose", t("ui.verboseHint")).action(async (name, opts) => {
3377
+ const { sessionsCommand } = await import("./sessions-QT26MQAE.js");
3378
+ sessionsCommand({ name, verbose: !!opts.verbose });
3379
+ });
3380
+ program2.command("prune-sessions").description(t("cli.pruneSessions")).option("--days <n>", t("ui.pruneDaysHint"), (v) => Number.parseInt(v, 10)).option("--dry-run", t("ui.pruneDryRunHint")).action(async (opts) => {
3381
+ const { pruneSessionsCommand } = await import("./prune-sessions-KGIIYD3P.js");
3382
+ pruneSessionsCommand({ days: opts.days, dryRun: !!opts.dryRun });
3383
+ });
3384
+ program2.command("events <name>").description(t("cli.events")).option("--type <type>", t("ui.eventTypeHint")).option("--since <id>", t("ui.eventSinceHint"), (v) => Number.parseInt(v, 10)).option("--tail <n>", t("ui.eventTailHint"), (v) => Number.parseInt(v, 10)).option("--json", t("ui.jsonHint")).option("--projection", t("ui.projectionHint")).action(async (name, opts) => {
3385
+ const { eventsCommand } = await import("./events-QN6KLN2V.js");
3386
+ eventsCommand({
3387
+ name,
3388
+ type: opts.type,
3389
+ since: Number.isFinite(opts.since) ? opts.since : void 0,
3390
+ tail: Number.isFinite(opts.tail) ? opts.tail : void 0,
3391
+ json: !!opts.json,
3392
+ projection: !!opts.projection
3393
+ });
3394
+ });
3395
+ program2.command("replay <transcript>").description(t("cli.replay")).option("--print", t("ui.printHint")).option("--head <n>", t("ui.headHint"), (v) => Number.parseInt(v, 10)).option("--tail <n>", t("ui.tailHint"), (v) => Number.parseInt(v, 10)).action(async (transcript, opts) => {
3396
+ const { replayCommand } = await import("./replay-RDXLUAOE.js");
3397
+ await replayCommand({
3398
+ path: transcript,
3399
+ print: !!opts.print,
3400
+ head: Number.isFinite(opts.head) ? opts.head : void 0,
3401
+ tail: Number.isFinite(opts.tail) ? opts.tail : void 0
3402
+ });
3403
+ });
3404
+ program2.command("diff <a> <b>").description(t("cli.diff")).option("--md <path>", t("ui.mdReportHint")).option("--print", t("ui.printHintTable")).option("--tui", t("ui.tuiHint")).option("--label-a <label>", t("ui.labelAHint")).option("--label-b <label>", t("ui.labelBHint")).action(async (a, b, opts) => {
3405
+ const { diffCommand } = await import("./diff-LYNRCJZE.js");
3406
+ await diffCommand({
3407
+ a,
3408
+ b,
3409
+ mdPath: opts.md,
3410
+ labelA: opts.labelA,
3411
+ labelB: opts.labelB,
3412
+ print: !!opts.print,
3413
+ tui: !!opts.tui
3414
+ });
3415
+ });
3416
+ var mcp = program2.command("mcp").description(t("cli.mcp"));
3417
+ mcp.command("list").description(t("ui.mcpListDescription")).option("--json", t("ui.jsonHintCatalog")).option("--local", t("ui.mcpLocalHint")).option("--refresh", t("ui.mcpRefreshHint")).option("--limit <n>", t("ui.mcpLimitHint"), (v) => Number.parseInt(v, 10)).option("--pages <n>", t("ui.mcpPagesHint"), (v) => Number.parseInt(v, 10)).option("--all", t("ui.mcpAllHint")).action(async (opts) => {
3418
+ try {
3419
+ const { mcpListCommand } = await import("./mcp-FGKEH7RG.js");
3420
+ await mcpListCommand({
3421
+ json: !!opts.json,
3422
+ local: !!opts.local,
3423
+ refresh: !!opts.refresh,
3424
+ limit: typeof opts.limit === "number" && opts.limit > 0 ? opts.limit : void 0,
3425
+ pages: typeof opts.pages === "number" && opts.pages > 0 ? opts.pages : void 0,
3426
+ all: !!opts.all
3427
+ });
3428
+ } catch (err) {
3429
+ process.stderr.write(`mcp list failed: ${err.message}
3430
+ `);
3431
+ process.exit(1);
3432
+ }
3433
+ });
3434
+ mcp.command("search <query>").description(t("ui.mcpSearchDescription")).option("--json", t("ui.jsonHintCatalog")).option("--refresh", t("ui.mcpRefreshHint")).option("--limit <n>", t("ui.mcpLimitHint"), (v) => Number.parseInt(v, 10)).option("--max-pages <n>", t("ui.mcpMaxPagesHint"), (v) => Number.parseInt(v, 10)).action(async (query, opts) => {
3435
+ try {
3436
+ const { mcpSearchCommand } = await import("./mcp-FGKEH7RG.js");
3437
+ await mcpSearchCommand(query, {
3438
+ json: !!opts.json,
3439
+ refresh: !!opts.refresh,
3440
+ limit: typeof opts.limit === "number" && opts.limit > 0 ? opts.limit : void 0,
3441
+ maxPages: typeof opts.maxPages === "number" && opts.maxPages > 0 ? opts.maxPages : void 0
3442
+ });
3443
+ } catch (err) {
3444
+ process.stderr.write(`mcp search failed: ${err.message}
3445
+ `);
3446
+ process.exit(1);
3447
+ }
3448
+ });
3449
+ mcp.command("install <name>").description(t("ui.mcpInstallDescription")).option("--refresh", t("ui.mcpRefreshHint")).option("--max-pages <n>", t("ui.mcpMaxPagesHint"), (v) => Number.parseInt(v, 10)).action(async (name, opts) => {
3450
+ try {
3451
+ const { mcpInstallCommand } = await import("./mcp-FGKEH7RG.js");
3452
+ await mcpInstallCommand(name, {
3453
+ refresh: !!opts.refresh,
3454
+ maxPages: typeof opts.maxPages === "number" && opts.maxPages > 0 ? opts.maxPages : void 0
3455
+ });
3456
+ } catch (err) {
3457
+ process.stderr.write(`mcp install failed: ${err.message}
3458
+ `);
3459
+ process.exit(1);
3460
+ }
3461
+ });
3462
+ mcp.command("browse").description(t("ui.mcpBrowseDescription")).action(async () => {
3463
+ try {
3464
+ const { mcpBrowseCommand } = await import("./mcp-browse-YCND4NWT.js");
3465
+ await mcpBrowseCommand();
3466
+ } catch (err) {
3467
+ process.stderr.write(`mcp browse failed: ${err.message}
3468
+ `);
3469
+ process.exit(1);
3470
+ }
3471
+ });
3472
+ mcp.command("inspect <spec>").description(t("ui.mcpInspectDescription")).option("--json", t("ui.jsonHintReport")).action(async (spec, opts) => {
3473
+ const { formatMcpInspectFailure, mcpInspectCommand } = await import("./mcp-inspect-V34J3VX5.js");
3474
+ try {
3475
+ await mcpInspectCommand({ spec, json: !!opts.json });
3476
+ } catch (err) {
3477
+ process.stderr.write(`mcp inspect failed: ${formatMcpInspectFailure(err)}
3478
+ `);
3479
+ process.exit(1);
3480
+ }
3481
+ });
3482
+ program2.command("version").description(t("cli.version")).action(async () => {
3483
+ const { versionCommand } = await import("./version-ANYORXTI.js");
3484
+ versionCommand();
3485
+ });
3486
+ program2.command("update").description(t("cli.update")).option("--dry-run", t("ui.dryRunHint")).action(async (opts) => {
3487
+ const { updateCommand } = await import("./update-KYI3OVJP.js");
3488
+ await updateCommand({ dryRun: !!opts.dryRun });
3489
+ });
3490
+ program2.command("index").description(t("cli.index")).option("--rebuild", t("ui.rebuildHint")).option("--model <name>", t("ui.embedModelHint")).option("--dir <path>", t("ui.projectDirHint")).option("--ollama-url <url>", t("ui.ollamaUrlHint")).option("-y, --yes", t("ui.skipPromptsHint")).action(
3491
+ async (opts) => {
3492
+ const { indexCommand } = await import("./commands-QLMD3T7B.js");
3493
+ await indexCommand(opts);
3494
+ }
3495
+ );
3496
+ program2.parseAsync(process.argv).catch((err) => {
3497
+ console.error(err);
3498
+ process.exit(1);
3499
+ });
3500
+ //# sourceMappingURL=index.js.map