@mx-space/cli 0.1.0

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