qcobjects-cli 2.4.65 → 2.5.103-beta

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