@mx-space/cli 0.2.3 → 0.3.1

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