bun-workspaces 1.5.0 → 1.5.2

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