reasonix 0.41.0 → 0.43.0

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