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