qcobjects-cli 2.5.103-beta → 2.5.104-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 (80) hide show
  1. package/VERSION +1 -1
  2. package/build-esbuild.js +4 -3
  3. package/package.json +55 -21
  4. package/public/browser/com.qcobjects.cli.commands.jira.client_services.js +66 -55
  5. package/public/browser/com.qcobjects.cli.commands.jira.client_services.js.map +2 -2
  6. package/public/browser/com.qcobjects.cli.commands.jira.js +138 -93
  7. package/public/browser/com.qcobjects.cli.commands.jira.js.map +4 -4
  8. package/public/browser/com.qcobjects.cli.commands.js +371 -14
  9. package/public/browser/com.qcobjects.cli.commands.js.map +4 -4
  10. package/public/browser/com.qcobjects.cli.commands.version.js +220 -214
  11. package/public/browser/com.qcobjects.cli.commands.version.js.map +2 -2
  12. package/public/browser/index.js +4042 -13
  13. package/public/browser/index.js.map +4 -4
  14. package/public/browser/org.qcobjects.common.pipelog.js +37 -24
  15. package/public/browser/org.qcobjects.common.pipelog.js.map +2 -2
  16. package/public/browser/org.qcobjects.enterprise.commands.js +108 -117
  17. package/public/browser/org.qcobjects.enterprise.commands.js.map +3 -3
  18. package/public/browser/org.quickcorp.qcobjects.api.client_services.js +64 -55
  19. package/public/browser/org.quickcorp.qcobjects.api.client_services.js.map +2 -2
  20. package/public/browser/org.quickcorp.qcobjects.cli.js +1280 -379
  21. package/public/browser/org.quickcorp.qcobjects.cli.js.map +4 -4
  22. package/public/browser/org.quickcorp.qcobjects.defaultsettings.js +373 -359
  23. package/public/browser/org.quickcorp.qcobjects.defaultsettings.js.map +2 -2
  24. package/public/browser/qcobjects-cli.js +4042 -13
  25. package/public/browser/qcobjects-cli.js.map +4 -4
  26. package/public/cjs/com.qcobjects.cli.commands.cjs +377 -6
  27. package/public/cjs/com.qcobjects.cli.commands.cjs.map +4 -4
  28. package/public/cjs/com.qcobjects.cli.commands.jira.cjs +82 -24
  29. package/public/cjs/com.qcobjects.cli.commands.jira.cjs.map +4 -4
  30. package/public/cjs/com.qcobjects.cli.commands.jira.client_services.cjs +25 -1
  31. package/public/cjs/com.qcobjects.cli.commands.jira.client_services.cjs.map +2 -2
  32. package/public/cjs/com.qcobjects.cli.commands.version.cjs +25 -6
  33. package/public/cjs/com.qcobjects.cli.commands.version.cjs.map +2 -2
  34. package/public/cjs/index.cjs +4042 -13
  35. package/public/cjs/index.cjs.map +4 -4
  36. package/public/cjs/org.qcobjects.common.pipelog.cjs +40 -14
  37. package/public/cjs/org.qcobjects.common.pipelog.cjs.map +2 -2
  38. package/public/cjs/org.qcobjects.enterprise.commands.cjs +38 -34
  39. package/public/cjs/org.qcobjects.enterprise.commands.cjs.map +3 -3
  40. package/public/cjs/org.quickcorp.qcobjects.api.client_services.cjs +24 -2
  41. package/public/cjs/org.quickcorp.qcobjects.api.client_services.cjs.map +2 -2
  42. package/public/cjs/org.quickcorp.qcobjects.cli.cjs +1032 -118
  43. package/public/cjs/org.quickcorp.qcobjects.cli.cjs.map +4 -4
  44. package/public/cjs/org.quickcorp.qcobjects.defaultsettings.cjs +362 -334
  45. package/public/cjs/org.quickcorp.qcobjects.defaultsettings.cjs.map +2 -2
  46. package/public/cjs/qcobjects-cli.cjs +4047 -13
  47. package/public/cjs/qcobjects-cli.cjs.map +4 -4
  48. package/public/esm/com.qcobjects.cli.commands.jira.client_services.mjs +50 -57
  49. package/public/esm/com.qcobjects.cli.commands.jira.client_services.mjs.map +2 -2
  50. package/public/esm/com.qcobjects.cli.commands.jira.mjs +119 -94
  51. package/public/esm/com.qcobjects.cli.commands.jira.mjs.map +4 -4
  52. package/public/esm/com.qcobjects.cli.commands.mjs +357 -16
  53. package/public/esm/com.qcobjects.cli.commands.mjs.map +4 -4
  54. package/public/esm/com.qcobjects.cli.commands.version.mjs +204 -216
  55. package/public/esm/com.qcobjects.cli.commands.version.mjs.map +2 -2
  56. package/public/esm/index.mjs +4043 -13
  57. package/public/esm/index.mjs.map +4 -4
  58. package/public/esm/org.qcobjects.common.pipelog.mjs +21 -26
  59. package/public/esm/org.qcobjects.common.pipelog.mjs.map +2 -2
  60. package/public/esm/org.qcobjects.enterprise.commands.mjs +92 -119
  61. package/public/esm/org.qcobjects.enterprise.commands.mjs.map +3 -3
  62. package/public/esm/org.quickcorp.qcobjects.api.client_services.mjs +48 -57
  63. package/public/esm/org.quickcorp.qcobjects.api.client_services.mjs.map +2 -2
  64. package/public/esm/org.quickcorp.qcobjects.cli.mjs +1266 -380
  65. package/public/esm/org.quickcorp.qcobjects.cli.mjs.map +4 -4
  66. package/public/esm/org.quickcorp.qcobjects.defaultsettings.mjs +357 -361
  67. package/public/esm/org.quickcorp.qcobjects.defaultsettings.mjs.map +2 -2
  68. package/public/esm/qcobjects-cli.mjs +4046 -14
  69. package/public/esm/qcobjects-cli.mjs.map +4 -4
  70. package/public/index.d.ts +140 -10
  71. package/src/com.qcobjects.cli.commands.jira.client_services.ts +19 -21
  72. package/src/com.qcobjects.cli.commands.jira.ts +11 -34
  73. package/src/com.qcobjects.cli.commands.ts +3 -9
  74. package/src/com.qcobjects.cli.commands.version.ts +1 -9
  75. package/src/org.qcobjects.common.pipelog.ts +18 -15
  76. package/src/org.qcobjects.enterprise.commands.ts +29 -50
  77. package/src/org.quickcorp.qcobjects.api.client_services.ts +1 -4
  78. package/src/org.quickcorp.qcobjects.cli.ts +28 -57
  79. package/src/org.quickcorp.qcobjects.defaultsettings.ts +359 -355
  80. package/src/qcobjects-cli.ts +4 -5
@@ -1,4 +1,5 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -6,22 +7,4053 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
7
  if (typeof require !== "undefined") return require.apply(this, arguments);
7
8
  throw Error('Dynamic require of "' + x + '" is not supported');
8
9
  });
10
+ var __commonJS = (cb, mod) => function __require2() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
9
13
  var __export = (target, all) => {
10
14
  for (var name in all)
11
15
  __defProp(target, name, { get: all[name], enumerable: true });
12
16
  };
13
17
 
18
+ // node_modules/commander/lib/error.js
19
+ var require_error = __commonJS({
20
+ "node_modules/commander/lib/error.js"(exports) {
21
+ "use strict";
22
+ var CommanderError = class extends Error {
23
+ static {
24
+ __name(this, "CommanderError");
25
+ }
26
+ /**
27
+ * Constructs the CommanderError class
28
+ * @param {number} exitCode suggested exit code which could be used with process.exit
29
+ * @param {string} code an id string representing the error
30
+ * @param {string} message human-readable description of the error
31
+ * @constructor
32
+ */
33
+ constructor(exitCode, code, message) {
34
+ super(message);
35
+ Error.captureStackTrace(this, this.constructor);
36
+ this.name = this.constructor.name;
37
+ this.code = code;
38
+ this.exitCode = exitCode;
39
+ this.nestedError = void 0;
40
+ }
41
+ };
42
+ var InvalidArgumentError = class extends CommanderError {
43
+ static {
44
+ __name(this, "InvalidArgumentError");
45
+ }
46
+ /**
47
+ * Constructs the InvalidArgumentError class
48
+ * @param {string} [message] explanation of why argument is invalid
49
+ * @constructor
50
+ */
51
+ constructor(message) {
52
+ super(1, "commander.invalidArgument", message);
53
+ Error.captureStackTrace(this, this.constructor);
54
+ this.name = this.constructor.name;
55
+ }
56
+ };
57
+ exports.CommanderError = CommanderError;
58
+ exports.InvalidArgumentError = InvalidArgumentError;
59
+ }
60
+ });
61
+
62
+ // node_modules/commander/lib/argument.js
63
+ var require_argument = __commonJS({
64
+ "node_modules/commander/lib/argument.js"(exports) {
65
+ "use strict";
66
+ var { InvalidArgumentError } = require_error();
67
+ var Argument = class {
68
+ static {
69
+ __name(this, "Argument");
70
+ }
71
+ /**
72
+ * Initialize a new command argument with the given name and description.
73
+ * The default is that the argument is required, and you can explicitly
74
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
75
+ *
76
+ * @param {string} name
77
+ * @param {string} [description]
78
+ */
79
+ constructor(name, description) {
80
+ this.description = description || "";
81
+ this.variadic = false;
82
+ this.parseArg = void 0;
83
+ this.defaultValue = void 0;
84
+ this.defaultValueDescription = void 0;
85
+ this.argChoices = void 0;
86
+ switch (name[0]) {
87
+ case "<":
88
+ this.required = true;
89
+ this._name = name.slice(1, -1);
90
+ break;
91
+ case "[":
92
+ this.required = false;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ default:
96
+ this.required = true;
97
+ this._name = name;
98
+ break;
99
+ }
100
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
101
+ this.variadic = true;
102
+ this._name = this._name.slice(0, -3);
103
+ }
104
+ }
105
+ /**
106
+ * Return argument name.
107
+ *
108
+ * @return {string}
109
+ */
110
+ name() {
111
+ return this._name;
112
+ }
113
+ /**
114
+ * @api private
115
+ */
116
+ _concatValue(value, previous) {
117
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
118
+ return [value];
119
+ }
120
+ return previous.concat(value);
121
+ }
122
+ /**
123
+ * Set the default value, and optionally supply the description to be displayed in the help.
124
+ *
125
+ * @param {any} value
126
+ * @param {string} [description]
127
+ * @return {Argument}
128
+ */
129
+ default(value, description) {
130
+ this.defaultValue = value;
131
+ this.defaultValueDescription = description;
132
+ return this;
133
+ }
134
+ /**
135
+ * Set the custom handler for processing CLI command arguments into argument values.
136
+ *
137
+ * @param {Function} [fn]
138
+ * @return {Argument}
139
+ */
140
+ argParser(fn) {
141
+ this.parseArg = fn;
142
+ return this;
143
+ }
144
+ /**
145
+ * Only allow argument value to be one of choices.
146
+ *
147
+ * @param {string[]} values
148
+ * @return {Argument}
149
+ */
150
+ choices(values) {
151
+ this.argChoices = values.slice();
152
+ this.parseArg = (arg, previous) => {
153
+ if (!this.argChoices.includes(arg)) {
154
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
155
+ }
156
+ if (this.variadic) {
157
+ return this._concatValue(arg, previous);
158
+ }
159
+ return arg;
160
+ };
161
+ return this;
162
+ }
163
+ /**
164
+ * Make argument required.
165
+ */
166
+ argRequired() {
167
+ this.required = true;
168
+ return this;
169
+ }
170
+ /**
171
+ * Make argument optional.
172
+ */
173
+ argOptional() {
174
+ this.required = false;
175
+ return this;
176
+ }
177
+ };
178
+ function humanReadableArgName(arg) {
179
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
180
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
181
+ }
182
+ __name(humanReadableArgName, "humanReadableArgName");
183
+ exports.Argument = Argument;
184
+ exports.humanReadableArgName = humanReadableArgName;
185
+ }
186
+ });
187
+
188
+ // node_modules/commander/lib/help.js
189
+ var require_help = __commonJS({
190
+ "node_modules/commander/lib/help.js"(exports) {
191
+ "use strict";
192
+ var { humanReadableArgName } = require_argument();
193
+ var Help = class {
194
+ static {
195
+ __name(this, "Help");
196
+ }
197
+ constructor() {
198
+ this.helpWidth = void 0;
199
+ this.sortSubcommands = false;
200
+ this.sortOptions = false;
201
+ this.showGlobalOptions = false;
202
+ }
203
+ /**
204
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
205
+ *
206
+ * @param {Command} cmd
207
+ * @returns {Command[]}
208
+ */
209
+ visibleCommands(cmd) {
210
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
211
+ if (cmd._hasImplicitHelpCommand()) {
212
+ const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
213
+ const helpCommand = cmd.createCommand(helpName).helpOption(false);
214
+ helpCommand.description(cmd._helpCommandDescription);
215
+ if (helpArgs) helpCommand.arguments(helpArgs);
216
+ visibleCommands.push(helpCommand);
217
+ }
218
+ if (this.sortSubcommands) {
219
+ visibleCommands.sort((a, b) => {
220
+ return a.name().localeCompare(b.name());
221
+ });
222
+ }
223
+ return visibleCommands;
224
+ }
225
+ /**
226
+ * Compare options for sort.
227
+ *
228
+ * @param {Option} a
229
+ * @param {Option} b
230
+ * @returns number
231
+ */
232
+ compareOptions(a, b) {
233
+ const getSortKey = /* @__PURE__ */ __name((option) => {
234
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
235
+ }, "getSortKey");
236
+ return getSortKey(a).localeCompare(getSortKey(b));
237
+ }
238
+ /**
239
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
240
+ *
241
+ * @param {Command} cmd
242
+ * @returns {Option[]}
243
+ */
244
+ visibleOptions(cmd) {
245
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
246
+ const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
247
+ const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
248
+ if (showShortHelpFlag || showLongHelpFlag) {
249
+ let helpOption;
250
+ if (!showShortHelpFlag) {
251
+ helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
252
+ } else if (!showLongHelpFlag) {
253
+ helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
254
+ } else {
255
+ helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
256
+ }
257
+ visibleOptions.push(helpOption);
258
+ }
259
+ if (this.sortOptions) {
260
+ visibleOptions.sort(this.compareOptions);
261
+ }
262
+ return visibleOptions;
263
+ }
264
+ /**
265
+ * Get an array of the visible global options. (Not including help.)
266
+ *
267
+ * @param {Command} cmd
268
+ * @returns {Option[]}
269
+ */
270
+ visibleGlobalOptions(cmd) {
271
+ if (!this.showGlobalOptions) return [];
272
+ const globalOptions = [];
273
+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
274
+ const visibleOptions = parentCmd.options.filter((option) => !option.hidden);
275
+ globalOptions.push(...visibleOptions);
276
+ }
277
+ if (this.sortOptions) {
278
+ globalOptions.sort(this.compareOptions);
279
+ }
280
+ return globalOptions;
281
+ }
282
+ /**
283
+ * Get an array of the arguments if any have a description.
284
+ *
285
+ * @param {Command} cmd
286
+ * @returns {Argument[]}
287
+ */
288
+ visibleArguments(cmd) {
289
+ if (cmd._argsDescription) {
290
+ cmd._args.forEach((argument) => {
291
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
292
+ });
293
+ }
294
+ if (cmd._args.find((argument) => argument.description)) {
295
+ return cmd._args;
296
+ }
297
+ return [];
298
+ }
299
+ /**
300
+ * Get the command term to show in the list of subcommands.
301
+ *
302
+ * @param {Command} cmd
303
+ * @returns {string}
304
+ */
305
+ subcommandTerm(cmd) {
306
+ const args = cmd._args.map((arg) => humanReadableArgName(arg)).join(" ");
307
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
308
+ (args ? " " + args : "");
309
+ }
310
+ /**
311
+ * Get the option term to show in the list of options.
312
+ *
313
+ * @param {Option} option
314
+ * @returns {string}
315
+ */
316
+ optionTerm(option) {
317
+ return option.flags;
318
+ }
319
+ /**
320
+ * Get the argument term to show in the list of arguments.
321
+ *
322
+ * @param {Argument} argument
323
+ * @returns {string}
324
+ */
325
+ argumentTerm(argument) {
326
+ return argument.name();
327
+ }
328
+ /**
329
+ * Get the longest command term length.
330
+ *
331
+ * @param {Command} cmd
332
+ * @param {Help} helper
333
+ * @returns {number}
334
+ */
335
+ longestSubcommandTermLength(cmd, helper) {
336
+ return helper.visibleCommands(cmd).reduce((max, command) => {
337
+ return Math.max(max, helper.subcommandTerm(command).length);
338
+ }, 0);
339
+ }
340
+ /**
341
+ * Get the longest option term length.
342
+ *
343
+ * @param {Command} cmd
344
+ * @param {Help} helper
345
+ * @returns {number}
346
+ */
347
+ longestOptionTermLength(cmd, helper) {
348
+ return helper.visibleOptions(cmd).reduce((max, option) => {
349
+ return Math.max(max, helper.optionTerm(option).length);
350
+ }, 0);
351
+ }
352
+ /**
353
+ * Get the longest global option term length.
354
+ *
355
+ * @param {Command} cmd
356
+ * @param {Help} helper
357
+ * @returns {number}
358
+ */
359
+ longestGlobalOptionTermLength(cmd, helper) {
360
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
361
+ return Math.max(max, helper.optionTerm(option).length);
362
+ }, 0);
363
+ }
364
+ /**
365
+ * Get the longest argument term length.
366
+ *
367
+ * @param {Command} cmd
368
+ * @param {Help} helper
369
+ * @returns {number}
370
+ */
371
+ longestArgumentTermLength(cmd, helper) {
372
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
373
+ return Math.max(max, helper.argumentTerm(argument).length);
374
+ }, 0);
375
+ }
376
+ /**
377
+ * Get the command usage to be displayed at the top of the built-in help.
378
+ *
379
+ * @param {Command} cmd
380
+ * @returns {string}
381
+ */
382
+ commandUsage(cmd) {
383
+ let cmdName = cmd._name;
384
+ if (cmd._aliases[0]) {
385
+ cmdName = cmdName + "|" + cmd._aliases[0];
386
+ }
387
+ let parentCmdNames = "";
388
+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
389
+ parentCmdNames = parentCmd.name() + " " + parentCmdNames;
390
+ }
391
+ return parentCmdNames + cmdName + " " + cmd.usage();
392
+ }
393
+ /**
394
+ * Get the description for the command.
395
+ *
396
+ * @param {Command} cmd
397
+ * @returns {string}
398
+ */
399
+ commandDescription(cmd) {
400
+ return cmd.description();
401
+ }
402
+ /**
403
+ * Get the subcommand summary to show in the list of subcommands.
404
+ * (Fallback to description for backwards compatibility.)
405
+ *
406
+ * @param {Command} cmd
407
+ * @returns {string}
408
+ */
409
+ subcommandDescription(cmd) {
410
+ return cmd.summary() || cmd.description();
411
+ }
412
+ /**
413
+ * Get the option description to show in the list of options.
414
+ *
415
+ * @param {Option} option
416
+ * @return {string}
417
+ */
418
+ optionDescription(option) {
419
+ const extraInfo = [];
420
+ if (option.argChoices) {
421
+ extraInfo.push(
422
+ // use stringify to match the display of the default value
423
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
424
+ );
425
+ }
426
+ if (option.defaultValue !== void 0) {
427
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
428
+ if (showDefault) {
429
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
430
+ }
431
+ }
432
+ if (option.presetArg !== void 0 && option.optional) {
433
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
434
+ }
435
+ if (option.envVar !== void 0) {
436
+ extraInfo.push(`env: ${option.envVar}`);
437
+ }
438
+ if (extraInfo.length > 0) {
439
+ return `${option.description} (${extraInfo.join(", ")})`;
440
+ }
441
+ return option.description;
442
+ }
443
+ /**
444
+ * Get the argument description to show in the list of arguments.
445
+ *
446
+ * @param {Argument} argument
447
+ * @return {string}
448
+ */
449
+ argumentDescription(argument) {
450
+ const extraInfo = [];
451
+ if (argument.argChoices) {
452
+ extraInfo.push(
453
+ // use stringify to match the display of the default value
454
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
455
+ );
456
+ }
457
+ if (argument.defaultValue !== void 0) {
458
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
459
+ }
460
+ if (extraInfo.length > 0) {
461
+ const extraDescripton = `(${extraInfo.join(", ")})`;
462
+ if (argument.description) {
463
+ return `${argument.description} ${extraDescripton}`;
464
+ }
465
+ return extraDescripton;
466
+ }
467
+ return argument.description;
468
+ }
469
+ /**
470
+ * Generate the built-in help text.
471
+ *
472
+ * @param {Command} cmd
473
+ * @param {Help} helper
474
+ * @returns {string}
475
+ */
476
+ formatHelp(cmd, helper) {
477
+ const termWidth = helper.padWidth(cmd, helper);
478
+ const helpWidth = helper.helpWidth || 80;
479
+ const itemIndentWidth = 2;
480
+ const itemSeparatorWidth = 2;
481
+ function formatItem(term, description) {
482
+ if (description) {
483
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
484
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
485
+ }
486
+ return term;
487
+ }
488
+ __name(formatItem, "formatItem");
489
+ function formatList(textArray) {
490
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
491
+ }
492
+ __name(formatList, "formatList");
493
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
494
+ const commandDescription = helper.commandDescription(cmd);
495
+ if (commandDescription.length > 0) {
496
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
497
+ }
498
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
499
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
500
+ });
501
+ if (argumentList.length > 0) {
502
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
503
+ }
504
+ const optionList = helper.visibleOptions(cmd).map((option) => {
505
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
506
+ });
507
+ if (optionList.length > 0) {
508
+ output = output.concat(["Options:", formatList(optionList), ""]);
509
+ }
510
+ if (this.showGlobalOptions) {
511
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
512
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
513
+ });
514
+ if (globalOptionList.length > 0) {
515
+ output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
516
+ }
517
+ }
518
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
519
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
520
+ });
521
+ if (commandList.length > 0) {
522
+ output = output.concat(["Commands:", formatList(commandList), ""]);
523
+ }
524
+ return output.join("\n");
525
+ }
526
+ /**
527
+ * Calculate the pad width from the maximum term length.
528
+ *
529
+ * @param {Command} cmd
530
+ * @param {Help} helper
531
+ * @returns {number}
532
+ */
533
+ padWidth(cmd, helper) {
534
+ return Math.max(
535
+ helper.longestOptionTermLength(cmd, helper),
536
+ helper.longestGlobalOptionTermLength(cmd, helper),
537
+ helper.longestSubcommandTermLength(cmd, helper),
538
+ helper.longestArgumentTermLength(cmd, helper)
539
+ );
540
+ }
541
+ /**
542
+ * Wrap the given string to width characters per line, with lines after the first indented.
543
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
544
+ *
545
+ * @param {string} str
546
+ * @param {number} width
547
+ * @param {number} indent
548
+ * @param {number} [minColumnWidth=40]
549
+ * @return {string}
550
+ *
551
+ */
552
+ wrap(str, width, indent, minColumnWidth = 40) {
553
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
554
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
555
+ if (str.match(manualIndent)) return str;
556
+ const columnWidth = width - indent;
557
+ if (columnWidth < minColumnWidth) return str;
558
+ const leadingStr = str.slice(0, indent);
559
+ const columnText = str.slice(indent).replace("\r\n", "\n");
560
+ const indentString = " ".repeat(indent);
561
+ const zeroWidthSpace = "\u200B";
562
+ const breaks = `\\s${zeroWidthSpace}`;
563
+ const regex = new RegExp(`
564
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
565
+ const lines = columnText.match(regex) || [];
566
+ return leadingStr + lines.map((line, i) => {
567
+ if (line === "\n") return "";
568
+ return (i > 0 ? indentString : "") + line.trimEnd();
569
+ }).join("\n");
570
+ }
571
+ };
572
+ exports.Help = Help;
573
+ }
574
+ });
575
+
576
+ // node_modules/commander/lib/option.js
577
+ var require_option = __commonJS({
578
+ "node_modules/commander/lib/option.js"(exports) {
579
+ "use strict";
580
+ var { InvalidArgumentError } = require_error();
581
+ var Option = class {
582
+ static {
583
+ __name(this, "Option");
584
+ }
585
+ /**
586
+ * Initialize a new `Option` with the given `flags` and `description`.
587
+ *
588
+ * @param {string} flags
589
+ * @param {string} [description]
590
+ */
591
+ constructor(flags, description) {
592
+ this.flags = flags;
593
+ this.description = description || "";
594
+ this.required = flags.includes("<");
595
+ this.optional = flags.includes("[");
596
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
597
+ this.mandatory = false;
598
+ const optionFlags = splitOptionFlags(flags);
599
+ this.short = optionFlags.shortFlag;
600
+ this.long = optionFlags.longFlag;
601
+ this.negate = false;
602
+ if (this.long) {
603
+ this.negate = this.long.startsWith("--no-");
604
+ }
605
+ this.defaultValue = void 0;
606
+ this.defaultValueDescription = void 0;
607
+ this.presetArg = void 0;
608
+ this.envVar = void 0;
609
+ this.parseArg = void 0;
610
+ this.hidden = false;
611
+ this.argChoices = void 0;
612
+ this.conflictsWith = [];
613
+ this.implied = void 0;
614
+ }
615
+ /**
616
+ * Set the default value, and optionally supply the description to be displayed in the help.
617
+ *
618
+ * @param {any} value
619
+ * @param {string} [description]
620
+ * @return {Option}
621
+ */
622
+ default(value, description) {
623
+ this.defaultValue = value;
624
+ this.defaultValueDescription = description;
625
+ return this;
626
+ }
627
+ /**
628
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
629
+ * The custom processing (parseArg) is called.
630
+ *
631
+ * @example
632
+ * new Option('--color').default('GREYSCALE').preset('RGB');
633
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
634
+ *
635
+ * @param {any} arg
636
+ * @return {Option}
637
+ */
638
+ preset(arg) {
639
+ this.presetArg = arg;
640
+ return this;
641
+ }
642
+ /**
643
+ * Add option name(s) that conflict with this option.
644
+ * An error will be displayed if conflicting options are found during parsing.
645
+ *
646
+ * @example
647
+ * new Option('--rgb').conflicts('cmyk');
648
+ * new Option('--js').conflicts(['ts', 'jsx']);
649
+ *
650
+ * @param {string | string[]} names
651
+ * @return {Option}
652
+ */
653
+ conflicts(names) {
654
+ this.conflictsWith = this.conflictsWith.concat(names);
655
+ return this;
656
+ }
657
+ /**
658
+ * Specify implied option values for when this option is set and the implied options are not.
659
+ *
660
+ * The custom processing (parseArg) is not called on the implied values.
661
+ *
662
+ * @example
663
+ * program
664
+ * .addOption(new Option('--log', 'write logging information to file'))
665
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
666
+ *
667
+ * @param {Object} impliedOptionValues
668
+ * @return {Option}
669
+ */
670
+ implies(impliedOptionValues) {
671
+ let newImplied = impliedOptionValues;
672
+ if (typeof impliedOptionValues === "string") {
673
+ newImplied = { [impliedOptionValues]: true };
674
+ }
675
+ this.implied = Object.assign(this.implied || {}, newImplied);
676
+ return this;
677
+ }
678
+ /**
679
+ * Set environment variable to check for option value.
680
+ *
681
+ * An environment variable is only used if when processed the current option value is
682
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
683
+ *
684
+ * @param {string} name
685
+ * @return {Option}
686
+ */
687
+ env(name) {
688
+ this.envVar = name;
689
+ return this;
690
+ }
691
+ /**
692
+ * Set the custom handler for processing CLI option arguments into option values.
693
+ *
694
+ * @param {Function} [fn]
695
+ * @return {Option}
696
+ */
697
+ argParser(fn) {
698
+ this.parseArg = fn;
699
+ return this;
700
+ }
701
+ /**
702
+ * Whether the option is mandatory and must have a value after parsing.
703
+ *
704
+ * @param {boolean} [mandatory=true]
705
+ * @return {Option}
706
+ */
707
+ makeOptionMandatory(mandatory = true) {
708
+ this.mandatory = !!mandatory;
709
+ return this;
710
+ }
711
+ /**
712
+ * Hide option in help.
713
+ *
714
+ * @param {boolean} [hide=true]
715
+ * @return {Option}
716
+ */
717
+ hideHelp(hide = true) {
718
+ this.hidden = !!hide;
719
+ return this;
720
+ }
721
+ /**
722
+ * @api private
723
+ */
724
+ _concatValue(value, previous) {
725
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
726
+ return [value];
727
+ }
728
+ return previous.concat(value);
729
+ }
730
+ /**
731
+ * Only allow option value to be one of choices.
732
+ *
733
+ * @param {string[]} values
734
+ * @return {Option}
735
+ */
736
+ choices(values) {
737
+ this.argChoices = values.slice();
738
+ this.parseArg = (arg, previous) => {
739
+ if (!this.argChoices.includes(arg)) {
740
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
741
+ }
742
+ if (this.variadic) {
743
+ return this._concatValue(arg, previous);
744
+ }
745
+ return arg;
746
+ };
747
+ return this;
748
+ }
749
+ /**
750
+ * Return option name.
751
+ *
752
+ * @return {string}
753
+ */
754
+ name() {
755
+ if (this.long) {
756
+ return this.long.replace(/^--/, "");
757
+ }
758
+ return this.short.replace(/^-/, "");
759
+ }
760
+ /**
761
+ * Return option name, in a camelcase format that can be used
762
+ * as a object attribute key.
763
+ *
764
+ * @return {string}
765
+ * @api private
766
+ */
767
+ attributeName() {
768
+ return camelcase(this.name().replace(/^no-/, ""));
769
+ }
770
+ /**
771
+ * Check if `arg` matches the short or long flag.
772
+ *
773
+ * @param {string} arg
774
+ * @return {boolean}
775
+ * @api private
776
+ */
777
+ is(arg) {
778
+ return this.short === arg || this.long === arg;
779
+ }
780
+ /**
781
+ * Return whether a boolean option.
782
+ *
783
+ * Options are one of boolean, negated, required argument, or optional argument.
784
+ *
785
+ * @return {boolean}
786
+ * @api private
787
+ */
788
+ isBoolean() {
789
+ return !this.required && !this.optional && !this.negate;
790
+ }
791
+ };
792
+ var DualOptions = class {
793
+ static {
794
+ __name(this, "DualOptions");
795
+ }
796
+ /**
797
+ * @param {Option[]} options
798
+ */
799
+ constructor(options) {
800
+ this.positiveOptions = /* @__PURE__ */ new Map();
801
+ this.negativeOptions = /* @__PURE__ */ new Map();
802
+ this.dualOptions = /* @__PURE__ */ new Set();
803
+ options.forEach((option) => {
804
+ if (option.negate) {
805
+ this.negativeOptions.set(option.attributeName(), option);
806
+ } else {
807
+ this.positiveOptions.set(option.attributeName(), option);
808
+ }
809
+ });
810
+ this.negativeOptions.forEach((value, key) => {
811
+ if (this.positiveOptions.has(key)) {
812
+ this.dualOptions.add(key);
813
+ }
814
+ });
815
+ }
816
+ /**
817
+ * Did the value come from the option, and not from possible matching dual option?
818
+ *
819
+ * @param {any} value
820
+ * @param {Option} option
821
+ * @returns {boolean}
822
+ */
823
+ valueFromOption(value, option) {
824
+ const optionKey = option.attributeName();
825
+ if (!this.dualOptions.has(optionKey)) return true;
826
+ const preset = this.negativeOptions.get(optionKey).presetArg;
827
+ const negativeValue = preset !== void 0 ? preset : false;
828
+ return option.negate === (negativeValue === value);
829
+ }
830
+ };
831
+ function camelcase(str) {
832
+ return str.split("-").reduce((str2, word) => {
833
+ return str2 + word[0].toUpperCase() + word.slice(1);
834
+ });
835
+ }
836
+ __name(camelcase, "camelcase");
837
+ function splitOptionFlags(flags) {
838
+ let shortFlag;
839
+ let longFlag;
840
+ const flagParts = flags.split(/[ |,]+/);
841
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
842
+ longFlag = flagParts.shift();
843
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
844
+ shortFlag = longFlag;
845
+ longFlag = void 0;
846
+ }
847
+ return { shortFlag, longFlag };
848
+ }
849
+ __name(splitOptionFlags, "splitOptionFlags");
850
+ exports.Option = Option;
851
+ exports.splitOptionFlags = splitOptionFlags;
852
+ exports.DualOptions = DualOptions;
853
+ }
854
+ });
855
+
856
+ // node_modules/commander/lib/suggestSimilar.js
857
+ var require_suggestSimilar = __commonJS({
858
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
859
+ "use strict";
860
+ var maxDistance = 3;
861
+ function editDistance(a, b) {
862
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
863
+ const d = [];
864
+ for (let i = 0; i <= a.length; i++) {
865
+ d[i] = [i];
866
+ }
867
+ for (let j = 0; j <= b.length; j++) {
868
+ d[0][j] = j;
869
+ }
870
+ for (let j = 1; j <= b.length; j++) {
871
+ for (let i = 1; i <= a.length; i++) {
872
+ let cost = 1;
873
+ if (a[i - 1] === b[j - 1]) {
874
+ cost = 0;
875
+ } else {
876
+ cost = 1;
877
+ }
878
+ d[i][j] = Math.min(
879
+ d[i - 1][j] + 1,
880
+ // deletion
881
+ d[i][j - 1] + 1,
882
+ // insertion
883
+ d[i - 1][j - 1] + cost
884
+ // substitution
885
+ );
886
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
887
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
888
+ }
889
+ }
890
+ }
891
+ return d[a.length][b.length];
892
+ }
893
+ __name(editDistance, "editDistance");
894
+ function suggestSimilar(word, candidates) {
895
+ if (!candidates || candidates.length === 0) return "";
896
+ candidates = Array.from(new Set(candidates));
897
+ const searchingOptions = word.startsWith("--");
898
+ if (searchingOptions) {
899
+ word = word.slice(2);
900
+ candidates = candidates.map((candidate) => candidate.slice(2));
901
+ }
902
+ let similar = [];
903
+ let bestDistance = maxDistance;
904
+ const minSimilarity = 0.4;
905
+ candidates.forEach((candidate) => {
906
+ if (candidate.length <= 1) return;
907
+ const distance = editDistance(word, candidate);
908
+ const length = Math.max(word.length, candidate.length);
909
+ const similarity = (length - distance) / length;
910
+ if (similarity > minSimilarity) {
911
+ if (distance < bestDistance) {
912
+ bestDistance = distance;
913
+ similar = [candidate];
914
+ } else if (distance === bestDistance) {
915
+ similar.push(candidate);
916
+ }
917
+ }
918
+ });
919
+ similar.sort((a, b) => a.localeCompare(b));
920
+ if (searchingOptions) {
921
+ similar = similar.map((candidate) => `--${candidate}`);
922
+ }
923
+ if (similar.length > 1) {
924
+ return `
925
+ (Did you mean one of ${similar.join(", ")}?)`;
926
+ }
927
+ if (similar.length === 1) {
928
+ return `
929
+ (Did you mean ${similar[0]}?)`;
930
+ }
931
+ return "";
932
+ }
933
+ __name(suggestSimilar, "suggestSimilar");
934
+ exports.suggestSimilar = suggestSimilar;
935
+ }
936
+ });
937
+
938
+ // node_modules/commander/lib/command.js
939
+ var require_command = __commonJS({
940
+ "node_modules/commander/lib/command.js"(exports) {
941
+ "use strict";
942
+ var EventEmitter = __require("events").EventEmitter;
943
+ var childProcess = __require("child_process");
944
+ var path5 = __require("path");
945
+ var fs3 = __require("fs");
946
+ var process2 = __require("process");
947
+ var { Argument, humanReadableArgName } = require_argument();
948
+ var { CommanderError } = require_error();
949
+ var { Help } = require_help();
950
+ var { Option, splitOptionFlags, DualOptions } = require_option();
951
+ var { suggestSimilar } = require_suggestSimilar();
952
+ var Command = class _Command extends EventEmitter {
953
+ static {
954
+ __name(this, "Command");
955
+ }
956
+ /**
957
+ * Initialize a new `Command`.
958
+ *
959
+ * @param {string} [name]
960
+ */
961
+ constructor(name) {
962
+ super();
963
+ this.commands = [];
964
+ this.options = [];
965
+ this.parent = null;
966
+ this._allowUnknownOption = false;
967
+ this._allowExcessArguments = true;
968
+ this._args = [];
969
+ this.args = [];
970
+ this.rawArgs = [];
971
+ this.processedArgs = [];
972
+ this._scriptPath = null;
973
+ this._name = name || "";
974
+ this._optionValues = {};
975
+ this._optionValueSources = {};
976
+ this._storeOptionsAsProperties = false;
977
+ this._actionHandler = null;
978
+ this._executableHandler = false;
979
+ this._executableFile = null;
980
+ this._executableDir = null;
981
+ this._defaultCommandName = null;
982
+ this._exitCallback = null;
983
+ this._aliases = [];
984
+ this._combineFlagAndOptionalValue = true;
985
+ this._description = "";
986
+ this._summary = "";
987
+ this._argsDescription = void 0;
988
+ this._enablePositionalOptions = false;
989
+ this._passThroughOptions = false;
990
+ this._lifeCycleHooks = {};
991
+ this._showHelpAfterError = false;
992
+ this._showSuggestionAfterError = true;
993
+ this._outputConfiguration = {
994
+ writeOut: /* @__PURE__ */ __name((str) => process2.stdout.write(str), "writeOut"),
995
+ writeErr: /* @__PURE__ */ __name((str) => process2.stderr.write(str), "writeErr"),
996
+ getOutHelpWidth: /* @__PURE__ */ __name(() => process2.stdout.isTTY ? process2.stdout.columns : void 0, "getOutHelpWidth"),
997
+ getErrHelpWidth: /* @__PURE__ */ __name(() => process2.stderr.isTTY ? process2.stderr.columns : void 0, "getErrHelpWidth"),
998
+ outputError: /* @__PURE__ */ __name((str, write) => write(str), "outputError")
999
+ };
1000
+ this._hidden = false;
1001
+ this._hasHelpOption = true;
1002
+ this._helpFlags = "-h, --help";
1003
+ this._helpDescription = "display help for command";
1004
+ this._helpShortFlag = "-h";
1005
+ this._helpLongFlag = "--help";
1006
+ this._addImplicitHelpCommand = void 0;
1007
+ this._helpCommandName = "help";
1008
+ this._helpCommandnameAndArgs = "help [command]";
1009
+ this._helpCommandDescription = "display help for command";
1010
+ this._helpConfiguration = {};
1011
+ }
1012
+ /**
1013
+ * Copy settings that are useful to have in common across root command and subcommands.
1014
+ *
1015
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1016
+ *
1017
+ * @param {Command} sourceCommand
1018
+ * @return {Command} `this` command for chaining
1019
+ */
1020
+ copyInheritedSettings(sourceCommand) {
1021
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1022
+ this._hasHelpOption = sourceCommand._hasHelpOption;
1023
+ this._helpFlags = sourceCommand._helpFlags;
1024
+ this._helpDescription = sourceCommand._helpDescription;
1025
+ this._helpShortFlag = sourceCommand._helpShortFlag;
1026
+ this._helpLongFlag = sourceCommand._helpLongFlag;
1027
+ this._helpCommandName = sourceCommand._helpCommandName;
1028
+ this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1029
+ this._helpCommandDescription = sourceCommand._helpCommandDescription;
1030
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1031
+ this._exitCallback = sourceCommand._exitCallback;
1032
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1033
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1034
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1035
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1036
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1037
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1038
+ return this;
1039
+ }
1040
+ /**
1041
+ * Define a command.
1042
+ *
1043
+ * There are two styles of command: pay attention to where to put the description.
1044
+ *
1045
+ * @example
1046
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1047
+ * program
1048
+ * .command('clone <source> [destination]')
1049
+ * .description('clone a repository into a newly created directory')
1050
+ * .action((source, destination) => {
1051
+ * console.log('clone command called');
1052
+ * });
1053
+ *
1054
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1055
+ * program
1056
+ * .command('start <service>', 'start named service')
1057
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1058
+ *
1059
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1060
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1061
+ * @param {Object} [execOpts] - configuration options (for executable)
1062
+ * @return {Command} returns new command for action handler, or `this` for executable command
1063
+ */
1064
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1065
+ let desc = actionOptsOrExecDesc;
1066
+ let opts = execOpts;
1067
+ if (typeof desc === "object" && desc !== null) {
1068
+ opts = desc;
1069
+ desc = null;
1070
+ }
1071
+ opts = opts || {};
1072
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1073
+ const cmd = this.createCommand(name);
1074
+ if (desc) {
1075
+ cmd.description(desc);
1076
+ cmd._executableHandler = true;
1077
+ }
1078
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1079
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1080
+ cmd._executableFile = opts.executableFile || null;
1081
+ if (args) cmd.arguments(args);
1082
+ this.commands.push(cmd);
1083
+ cmd.parent = this;
1084
+ cmd.copyInheritedSettings(this);
1085
+ if (desc) return this;
1086
+ return cmd;
1087
+ }
1088
+ /**
1089
+ * Factory routine to create a new unattached command.
1090
+ *
1091
+ * See .command() for creating an attached subcommand, which uses this routine to
1092
+ * create the command. You can override createCommand to customise subcommands.
1093
+ *
1094
+ * @param {string} [name]
1095
+ * @return {Command} new command
1096
+ */
1097
+ createCommand(name) {
1098
+ return new _Command(name);
1099
+ }
1100
+ /**
1101
+ * You can customise the help with a subclass of Help by overriding createHelp,
1102
+ * or by overriding Help properties using configureHelp().
1103
+ *
1104
+ * @return {Help}
1105
+ */
1106
+ createHelp() {
1107
+ return Object.assign(new Help(), this.configureHelp());
1108
+ }
1109
+ /**
1110
+ * You can customise the help by overriding Help properties using configureHelp(),
1111
+ * or with a subclass of Help by overriding createHelp().
1112
+ *
1113
+ * @param {Object} [configuration] - configuration options
1114
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1115
+ */
1116
+ configureHelp(configuration) {
1117
+ if (configuration === void 0) return this._helpConfiguration;
1118
+ this._helpConfiguration = configuration;
1119
+ return this;
1120
+ }
1121
+ /**
1122
+ * The default output goes to stdout and stderr. You can customise this for special
1123
+ * applications. You can also customise the display of errors by overriding outputError.
1124
+ *
1125
+ * The configuration properties are all functions:
1126
+ *
1127
+ * // functions to change where being written, stdout and stderr
1128
+ * writeOut(str)
1129
+ * writeErr(str)
1130
+ * // matching functions to specify width for wrapping help
1131
+ * getOutHelpWidth()
1132
+ * getErrHelpWidth()
1133
+ * // functions based on what is being written out
1134
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1135
+ *
1136
+ * @param {Object} [configuration] - configuration options
1137
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1138
+ */
1139
+ configureOutput(configuration) {
1140
+ if (configuration === void 0) return this._outputConfiguration;
1141
+ Object.assign(this._outputConfiguration, configuration);
1142
+ return this;
1143
+ }
1144
+ /**
1145
+ * Display the help or a custom message after an error occurs.
1146
+ *
1147
+ * @param {boolean|string} [displayHelp]
1148
+ * @return {Command} `this` command for chaining
1149
+ */
1150
+ showHelpAfterError(displayHelp = true) {
1151
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1152
+ this._showHelpAfterError = displayHelp;
1153
+ return this;
1154
+ }
1155
+ /**
1156
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1157
+ *
1158
+ * @param {boolean} [displaySuggestion]
1159
+ * @return {Command} `this` command for chaining
1160
+ */
1161
+ showSuggestionAfterError(displaySuggestion = true) {
1162
+ this._showSuggestionAfterError = !!displaySuggestion;
1163
+ return this;
1164
+ }
1165
+ /**
1166
+ * Add a prepared subcommand.
1167
+ *
1168
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1169
+ *
1170
+ * @param {Command} cmd - new subcommand
1171
+ * @param {Object} [opts] - configuration options
1172
+ * @return {Command} `this` command for chaining
1173
+ */
1174
+ addCommand(cmd, opts) {
1175
+ if (!cmd._name) {
1176
+ throw new Error(`Command passed to .addCommand() must have a name
1177
+ - specify the name in Command constructor or using .name()`);
1178
+ }
1179
+ opts = opts || {};
1180
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1181
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1182
+ this.commands.push(cmd);
1183
+ cmd.parent = this;
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Factory routine to create a new unattached argument.
1188
+ *
1189
+ * See .argument() for creating an attached argument, which uses this routine to
1190
+ * create the argument. You can override createArgument to return a custom argument.
1191
+ *
1192
+ * @param {string} name
1193
+ * @param {string} [description]
1194
+ * @return {Argument} new argument
1195
+ */
1196
+ createArgument(name, description) {
1197
+ return new Argument(name, description);
1198
+ }
1199
+ /**
1200
+ * Define argument syntax for command.
1201
+ *
1202
+ * The default is that the argument is required, and you can explicitly
1203
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1204
+ *
1205
+ * @example
1206
+ * program.argument('<input-file>');
1207
+ * program.argument('[output-file]');
1208
+ *
1209
+ * @param {string} name
1210
+ * @param {string} [description]
1211
+ * @param {Function|*} [fn] - custom argument processing function
1212
+ * @param {*} [defaultValue]
1213
+ * @return {Command} `this` command for chaining
1214
+ */
1215
+ argument(name, description, fn, defaultValue) {
1216
+ const argument = this.createArgument(name, description);
1217
+ if (typeof fn === "function") {
1218
+ argument.default(defaultValue).argParser(fn);
1219
+ } else {
1220
+ argument.default(fn);
1221
+ }
1222
+ this.addArgument(argument);
1223
+ return this;
1224
+ }
1225
+ /**
1226
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1227
+ *
1228
+ * See also .argument().
1229
+ *
1230
+ * @example
1231
+ * program.arguments('<cmd> [env]');
1232
+ *
1233
+ * @param {string} names
1234
+ * @return {Command} `this` command for chaining
1235
+ */
1236
+ arguments(names) {
1237
+ names.split(/ +/).forEach((detail) => {
1238
+ this.argument(detail);
1239
+ });
1240
+ return this;
1241
+ }
1242
+ /**
1243
+ * Define argument syntax for command, adding a prepared argument.
1244
+ *
1245
+ * @param {Argument} argument
1246
+ * @return {Command} `this` command for chaining
1247
+ */
1248
+ addArgument(argument) {
1249
+ const previousArgument = this._args.slice(-1)[0];
1250
+ if (previousArgument && previousArgument.variadic) {
1251
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1252
+ }
1253
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1254
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1255
+ }
1256
+ this._args.push(argument);
1257
+ return this;
1258
+ }
1259
+ /**
1260
+ * Override default decision whether to add implicit help command.
1261
+ *
1262
+ * addHelpCommand() // force on
1263
+ * addHelpCommand(false); // force off
1264
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1265
+ *
1266
+ * @return {Command} `this` command for chaining
1267
+ */
1268
+ addHelpCommand(enableOrNameAndArgs, description) {
1269
+ if (enableOrNameAndArgs === false) {
1270
+ this._addImplicitHelpCommand = false;
1271
+ } else {
1272
+ this._addImplicitHelpCommand = true;
1273
+ if (typeof enableOrNameAndArgs === "string") {
1274
+ this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1275
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
1276
+ }
1277
+ this._helpCommandDescription = description || this._helpCommandDescription;
1278
+ }
1279
+ return this;
1280
+ }
1281
+ /**
1282
+ * @return {boolean}
1283
+ * @api private
1284
+ */
1285
+ _hasImplicitHelpCommand() {
1286
+ if (this._addImplicitHelpCommand === void 0) {
1287
+ return this.commands.length && !this._actionHandler && !this._findCommand("help");
1288
+ }
1289
+ return this._addImplicitHelpCommand;
1290
+ }
1291
+ /**
1292
+ * Add hook for life cycle event.
1293
+ *
1294
+ * @param {string} event
1295
+ * @param {Function} listener
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ hook(event, listener) {
1299
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1300
+ if (!allowedValues.includes(event)) {
1301
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1302
+ Expecting one of '${allowedValues.join("', '")}'`);
1303
+ }
1304
+ if (this._lifeCycleHooks[event]) {
1305
+ this._lifeCycleHooks[event].push(listener);
1306
+ } else {
1307
+ this._lifeCycleHooks[event] = [listener];
1308
+ }
1309
+ return this;
1310
+ }
1311
+ /**
1312
+ * Register callback to use as replacement for calling process.exit.
1313
+ *
1314
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1315
+ * @return {Command} `this` command for chaining
1316
+ */
1317
+ exitOverride(fn) {
1318
+ if (fn) {
1319
+ this._exitCallback = fn;
1320
+ } else {
1321
+ this._exitCallback = (err) => {
1322
+ if (err.code !== "commander.executeSubCommandAsync") {
1323
+ throw err;
1324
+ } else {
1325
+ }
1326
+ };
1327
+ }
1328
+ return this;
1329
+ }
1330
+ /**
1331
+ * Call process.exit, and _exitCallback if defined.
1332
+ *
1333
+ * @param {number} exitCode exit code for using with process.exit
1334
+ * @param {string} code an id string representing the error
1335
+ * @param {string} message human-readable description of the error
1336
+ * @return never
1337
+ * @api private
1338
+ */
1339
+ _exit(exitCode, code, message) {
1340
+ if (this._exitCallback) {
1341
+ this._exitCallback(new CommanderError(exitCode, code, message));
1342
+ }
1343
+ process2.exit(exitCode);
1344
+ }
1345
+ /**
1346
+ * Register callback `fn` for the command.
1347
+ *
1348
+ * @example
1349
+ * program
1350
+ * .command('serve')
1351
+ * .description('start service')
1352
+ * .action(function() {
1353
+ * // do work here
1354
+ * });
1355
+ *
1356
+ * @param {Function} fn
1357
+ * @return {Command} `this` command for chaining
1358
+ */
1359
+ action(fn) {
1360
+ const listener = /* @__PURE__ */ __name((args) => {
1361
+ const expectedArgsCount = this._args.length;
1362
+ const actionArgs = args.slice(0, expectedArgsCount);
1363
+ if (this._storeOptionsAsProperties) {
1364
+ actionArgs[expectedArgsCount] = this;
1365
+ } else {
1366
+ actionArgs[expectedArgsCount] = this.opts();
1367
+ }
1368
+ actionArgs.push(this);
1369
+ return fn.apply(this, actionArgs);
1370
+ }, "listener");
1371
+ this._actionHandler = listener;
1372
+ return this;
1373
+ }
1374
+ /**
1375
+ * Factory routine to create a new unattached option.
1376
+ *
1377
+ * See .option() for creating an attached option, which uses this routine to
1378
+ * create the option. You can override createOption to return a custom option.
1379
+ *
1380
+ * @param {string} flags
1381
+ * @param {string} [description]
1382
+ * @return {Option} new option
1383
+ */
1384
+ createOption(flags, description) {
1385
+ return new Option(flags, description);
1386
+ }
1387
+ /**
1388
+ * Add an option.
1389
+ *
1390
+ * @param {Option} option
1391
+ * @return {Command} `this` command for chaining
1392
+ */
1393
+ addOption(option) {
1394
+ const oname = option.name();
1395
+ const name = option.attributeName();
1396
+ if (option.negate) {
1397
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1398
+ if (!this._findOption(positiveLongFlag)) {
1399
+ this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1400
+ }
1401
+ } else if (option.defaultValue !== void 0) {
1402
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1403
+ }
1404
+ this.options.push(option);
1405
+ const handleOptionValue = /* @__PURE__ */ __name((val, invalidValueMessage, valueSource) => {
1406
+ if (val == null && option.presetArg !== void 0) {
1407
+ val = option.presetArg;
1408
+ }
1409
+ const oldValue = this.getOptionValue(name);
1410
+ if (val !== null && option.parseArg) {
1411
+ try {
1412
+ val = option.parseArg(val, oldValue);
1413
+ } catch (err) {
1414
+ if (err.code === "commander.invalidArgument") {
1415
+ const message = `${invalidValueMessage} ${err.message}`;
1416
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1417
+ }
1418
+ throw err;
1419
+ }
1420
+ } else if (val !== null && option.variadic) {
1421
+ val = option._concatValue(val, oldValue);
1422
+ }
1423
+ if (val == null) {
1424
+ if (option.negate) {
1425
+ val = false;
1426
+ } else if (option.isBoolean() || option.optional) {
1427
+ val = true;
1428
+ } else {
1429
+ val = "";
1430
+ }
1431
+ }
1432
+ this.setOptionValueWithSource(name, val, valueSource);
1433
+ }, "handleOptionValue");
1434
+ this.on("option:" + oname, (val) => {
1435
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1436
+ handleOptionValue(val, invalidValueMessage, "cli");
1437
+ });
1438
+ if (option.envVar) {
1439
+ this.on("optionEnv:" + oname, (val) => {
1440
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1441
+ handleOptionValue(val, invalidValueMessage, "env");
1442
+ });
1443
+ }
1444
+ return this;
1445
+ }
1446
+ /**
1447
+ * Internal implementation shared by .option() and .requiredOption()
1448
+ *
1449
+ * @api private
1450
+ */
1451
+ _optionEx(config, flags, description, fn, defaultValue) {
1452
+ if (typeof flags === "object" && flags instanceof Option) {
1453
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1454
+ }
1455
+ const option = this.createOption(flags, description);
1456
+ option.makeOptionMandatory(!!config.mandatory);
1457
+ if (typeof fn === "function") {
1458
+ option.default(defaultValue).argParser(fn);
1459
+ } else if (fn instanceof RegExp) {
1460
+ const regex = fn;
1461
+ fn = /* @__PURE__ */ __name((val, def) => {
1462
+ const m = regex.exec(val);
1463
+ return m ? m[0] : def;
1464
+ }, "fn");
1465
+ option.default(defaultValue).argParser(fn);
1466
+ } else {
1467
+ option.default(fn);
1468
+ }
1469
+ return this.addOption(option);
1470
+ }
1471
+ /**
1472
+ * Define option with `flags`, `description` and optional
1473
+ * coercion `fn`.
1474
+ *
1475
+ * The `flags` string contains the short and/or long flags,
1476
+ * separated by comma, a pipe or space. The following are all valid
1477
+ * all will output this way when `--help` is used.
1478
+ *
1479
+ * "-p, --pepper"
1480
+ * "-p|--pepper"
1481
+ * "-p --pepper"
1482
+ *
1483
+ * @example
1484
+ * // simple boolean defaulting to undefined
1485
+ * program.option('-p, --pepper', 'add pepper');
1486
+ *
1487
+ * program.pepper
1488
+ * // => undefined
1489
+ *
1490
+ * --pepper
1491
+ * program.pepper
1492
+ * // => true
1493
+ *
1494
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
1495
+ * program.option('-C, --no-cheese', 'remove cheese');
1496
+ *
1497
+ * program.cheese
1498
+ * // => true
1499
+ *
1500
+ * --no-cheese
1501
+ * program.cheese
1502
+ * // => false
1503
+ *
1504
+ * // required argument
1505
+ * program.option('-C, --chdir <path>', 'change the working directory');
1506
+ *
1507
+ * --chdir /tmp
1508
+ * program.chdir
1509
+ * // => "/tmp"
1510
+ *
1511
+ * // optional argument
1512
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
1513
+ *
1514
+ * @param {string} flags
1515
+ * @param {string} [description]
1516
+ * @param {Function|*} [fn] - custom option processing function or default value
1517
+ * @param {*} [defaultValue]
1518
+ * @return {Command} `this` command for chaining
1519
+ */
1520
+ option(flags, description, fn, defaultValue) {
1521
+ return this._optionEx({}, flags, description, fn, defaultValue);
1522
+ }
1523
+ /**
1524
+ * Add a required option which must have a value after parsing. This usually means
1525
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1526
+ *
1527
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1528
+ *
1529
+ * @param {string} flags
1530
+ * @param {string} [description]
1531
+ * @param {Function|*} [fn] - custom option processing function or default value
1532
+ * @param {*} [defaultValue]
1533
+ * @return {Command} `this` command for chaining
1534
+ */
1535
+ requiredOption(flags, description, fn, defaultValue) {
1536
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
1537
+ }
1538
+ /**
1539
+ * Alter parsing of short flags with optional values.
1540
+ *
1541
+ * @example
1542
+ * // for `.option('-f,--flag [value]'):
1543
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1544
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1545
+ *
1546
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1547
+ */
1548
+ combineFlagAndOptionalValue(combine = true) {
1549
+ this._combineFlagAndOptionalValue = !!combine;
1550
+ return this;
1551
+ }
1552
+ /**
1553
+ * Allow unknown options on the command line.
1554
+ *
1555
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1556
+ * for unknown options.
1557
+ */
1558
+ allowUnknownOption(allowUnknown = true) {
1559
+ this._allowUnknownOption = !!allowUnknown;
1560
+ return this;
1561
+ }
1562
+ /**
1563
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1564
+ *
1565
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1566
+ * for excess arguments.
1567
+ */
1568
+ allowExcessArguments(allowExcess = true) {
1569
+ this._allowExcessArguments = !!allowExcess;
1570
+ return this;
1571
+ }
1572
+ /**
1573
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1574
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1575
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1576
+ *
1577
+ * @param {Boolean} [positional=true]
1578
+ */
1579
+ enablePositionalOptions(positional = true) {
1580
+ this._enablePositionalOptions = !!positional;
1581
+ return this;
1582
+ }
1583
+ /**
1584
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1585
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1586
+ * positional options to have been enabled on the program (parent commands).
1587
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1588
+ *
1589
+ * @param {Boolean} [passThrough=true]
1590
+ * for unknown options.
1591
+ */
1592
+ passThroughOptions(passThrough = true) {
1593
+ this._passThroughOptions = !!passThrough;
1594
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1595
+ throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1596
+ }
1597
+ return this;
1598
+ }
1599
+ /**
1600
+ * Whether to store option values as properties on command object,
1601
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1602
+ *
1603
+ * @param {boolean} [storeAsProperties=true]
1604
+ * @return {Command} `this` command for chaining
1605
+ */
1606
+ storeOptionsAsProperties(storeAsProperties = true) {
1607
+ this._storeOptionsAsProperties = !!storeAsProperties;
1608
+ if (this.options.length) {
1609
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1610
+ }
1611
+ return this;
1612
+ }
1613
+ /**
1614
+ * Retrieve option value.
1615
+ *
1616
+ * @param {string} key
1617
+ * @return {Object} value
1618
+ */
1619
+ getOptionValue(key) {
1620
+ if (this._storeOptionsAsProperties) {
1621
+ return this[key];
1622
+ }
1623
+ return this._optionValues[key];
1624
+ }
1625
+ /**
1626
+ * Store option value.
1627
+ *
1628
+ * @param {string} key
1629
+ * @param {Object} value
1630
+ * @return {Command} `this` command for chaining
1631
+ */
1632
+ setOptionValue(key, value) {
1633
+ return this.setOptionValueWithSource(key, value, void 0);
1634
+ }
1635
+ /**
1636
+ * Store option value and where the value came from.
1637
+ *
1638
+ * @param {string} key
1639
+ * @param {Object} value
1640
+ * @param {string} source - expected values are default/config/env/cli/implied
1641
+ * @return {Command} `this` command for chaining
1642
+ */
1643
+ setOptionValueWithSource(key, value, source) {
1644
+ if (this._storeOptionsAsProperties) {
1645
+ this[key] = value;
1646
+ } else {
1647
+ this._optionValues[key] = value;
1648
+ }
1649
+ this._optionValueSources[key] = source;
1650
+ return this;
1651
+ }
1652
+ /**
1653
+ * Get source of option value.
1654
+ * Expected values are default | config | env | cli | implied
1655
+ *
1656
+ * @param {string} key
1657
+ * @return {string}
1658
+ */
1659
+ getOptionValueSource(key) {
1660
+ return this._optionValueSources[key];
1661
+ }
1662
+ /**
1663
+ * Get source of option value. See also .optsWithGlobals().
1664
+ * Expected values are default | config | env | cli | implied
1665
+ *
1666
+ * @param {string} key
1667
+ * @return {string}
1668
+ */
1669
+ getOptionValueSourceWithGlobals(key) {
1670
+ let source;
1671
+ getCommandAndParents(this).forEach((cmd) => {
1672
+ if (cmd.getOptionValueSource(key) !== void 0) {
1673
+ source = cmd.getOptionValueSource(key);
1674
+ }
1675
+ });
1676
+ return source;
1677
+ }
1678
+ /**
1679
+ * Get user arguments from implied or explicit arguments.
1680
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1681
+ *
1682
+ * @api private
1683
+ */
1684
+ _prepareUserArgs(argv, parseOptions) {
1685
+ if (argv !== void 0 && !Array.isArray(argv)) {
1686
+ throw new Error("first parameter to parse must be array or undefined");
1687
+ }
1688
+ parseOptions = parseOptions || {};
1689
+ if (argv === void 0) {
1690
+ argv = process2.argv;
1691
+ if (process2.versions && process2.versions.electron) {
1692
+ parseOptions.from = "electron";
1693
+ }
1694
+ }
1695
+ this.rawArgs = argv.slice();
1696
+ let userArgs;
1697
+ switch (parseOptions.from) {
1698
+ case void 0:
1699
+ case "node":
1700
+ this._scriptPath = argv[1];
1701
+ userArgs = argv.slice(2);
1702
+ break;
1703
+ case "electron":
1704
+ if (process2.defaultApp) {
1705
+ this._scriptPath = argv[1];
1706
+ userArgs = argv.slice(2);
1707
+ } else {
1708
+ userArgs = argv.slice(1);
1709
+ }
1710
+ break;
1711
+ case "user":
1712
+ userArgs = argv.slice(0);
1713
+ break;
1714
+ default:
1715
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1716
+ }
1717
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1718
+ this._name = this._name || "program";
1719
+ return userArgs;
1720
+ }
1721
+ /**
1722
+ * Parse `argv`, setting options and invoking commands when defined.
1723
+ *
1724
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1725
+ * and the script being run in argv[1], with user parameters after that.
1726
+ *
1727
+ * @example
1728
+ * program.parse(process.argv);
1729
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1730
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1731
+ *
1732
+ * @param {string[]} [argv] - optional, defaults to process.argv
1733
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1734
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1735
+ * @return {Command} `this` command for chaining
1736
+ */
1737
+ parse(argv, parseOptions) {
1738
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1739
+ this._parseCommand([], userArgs);
1740
+ return this;
1741
+ }
1742
+ /**
1743
+ * Parse `argv`, setting options and invoking commands when defined.
1744
+ *
1745
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1746
+ *
1747
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1748
+ * and the script being run in argv[1], with user parameters after that.
1749
+ *
1750
+ * @example
1751
+ * await program.parseAsync(process.argv);
1752
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1753
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1754
+ *
1755
+ * @param {string[]} [argv]
1756
+ * @param {Object} [parseOptions]
1757
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1758
+ * @return {Promise}
1759
+ */
1760
+ async parseAsync(argv, parseOptions) {
1761
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1762
+ await this._parseCommand([], userArgs);
1763
+ return this;
1764
+ }
1765
+ /**
1766
+ * Execute a sub-command executable.
1767
+ *
1768
+ * @api private
1769
+ */
1770
+ _executeSubCommand(subcommand, args) {
1771
+ args = args.slice();
1772
+ let launchWithNode = false;
1773
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1774
+ function findFile(baseDir, baseName) {
1775
+ const localBin = path5.resolve(baseDir, baseName);
1776
+ if (fs3.existsSync(localBin)) return localBin;
1777
+ if (sourceExt.includes(path5.extname(baseName))) return void 0;
1778
+ const foundExt = sourceExt.find((ext) => fs3.existsSync(`${localBin}${ext}`));
1779
+ if (foundExt) return `${localBin}${foundExt}`;
1780
+ return void 0;
1781
+ }
1782
+ __name(findFile, "findFile");
1783
+ this._checkForMissingMandatoryOptions();
1784
+ this._checkForConflictingOptions();
1785
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1786
+ let executableDir = this._executableDir || "";
1787
+ if (this._scriptPath) {
1788
+ let resolvedScriptPath;
1789
+ try {
1790
+ resolvedScriptPath = fs3.realpathSync(this._scriptPath);
1791
+ } catch (err) {
1792
+ resolvedScriptPath = this._scriptPath;
1793
+ }
1794
+ executableDir = path5.resolve(path5.dirname(resolvedScriptPath), executableDir);
1795
+ }
1796
+ if (executableDir) {
1797
+ let localFile = findFile(executableDir, executableFile);
1798
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1799
+ const legacyName = path5.basename(this._scriptPath, path5.extname(this._scriptPath));
1800
+ if (legacyName !== this._name) {
1801
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1802
+ }
1803
+ }
1804
+ executableFile = localFile || executableFile;
1805
+ }
1806
+ launchWithNode = sourceExt.includes(path5.extname(executableFile));
1807
+ let proc;
1808
+ if (process2.platform !== "win32") {
1809
+ if (launchWithNode) {
1810
+ args.unshift(executableFile);
1811
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1812
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1813
+ } else {
1814
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1815
+ }
1816
+ } else {
1817
+ args.unshift(executableFile);
1818
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1819
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1820
+ }
1821
+ if (!proc.killed) {
1822
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1823
+ signals.forEach((signal) => {
1824
+ process2.on(signal, () => {
1825
+ if (proc.killed === false && proc.exitCode === null) {
1826
+ proc.kill(signal);
1827
+ }
1828
+ });
1829
+ });
1830
+ }
1831
+ const exitCallback = this._exitCallback;
1832
+ if (!exitCallback) {
1833
+ proc.on("close", process2.exit.bind(process2));
1834
+ } else {
1835
+ proc.on("close", () => {
1836
+ exitCallback(new CommanderError(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1837
+ });
1838
+ }
1839
+ proc.on("error", (err) => {
1840
+ if (err.code === "ENOENT") {
1841
+ 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";
1842
+ const executableMissing = `'${executableFile}' does not exist
1843
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1844
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1845
+ - ${executableDirMessage}`;
1846
+ throw new Error(executableMissing);
1847
+ } else if (err.code === "EACCES") {
1848
+ throw new Error(`'${executableFile}' not executable`);
1849
+ }
1850
+ if (!exitCallback) {
1851
+ process2.exit(1);
1852
+ } else {
1853
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1854
+ wrappedError.nestedError = err;
1855
+ exitCallback(wrappedError);
1856
+ }
1857
+ });
1858
+ this.runningCommand = proc;
1859
+ }
1860
+ /**
1861
+ * @api private
1862
+ */
1863
+ _dispatchSubcommand(commandName, operands, unknown) {
1864
+ const subCommand = this._findCommand(commandName);
1865
+ if (!subCommand) this.help({ error: true });
1866
+ let hookResult;
1867
+ hookResult = this._chainOrCallSubCommandHook(hookResult, subCommand, "preSubcommand");
1868
+ hookResult = this._chainOrCall(hookResult, () => {
1869
+ if (subCommand._executableHandler) {
1870
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1871
+ } else {
1872
+ return subCommand._parseCommand(operands, unknown);
1873
+ }
1874
+ });
1875
+ return hookResult;
1876
+ }
1877
+ /**
1878
+ * Check this.args against expected this._args.
1879
+ *
1880
+ * @api private
1881
+ */
1882
+ _checkNumberOfArguments() {
1883
+ this._args.forEach((arg, i) => {
1884
+ if (arg.required && this.args[i] == null) {
1885
+ this.missingArgument(arg.name());
1886
+ }
1887
+ });
1888
+ if (this._args.length > 0 && this._args[this._args.length - 1].variadic) {
1889
+ return;
1890
+ }
1891
+ if (this.args.length > this._args.length) {
1892
+ this._excessArguments(this.args);
1893
+ }
1894
+ }
1895
+ /**
1896
+ * Process this.args using this._args and save as this.processedArgs!
1897
+ *
1898
+ * @api private
1899
+ */
1900
+ _processArguments() {
1901
+ const myParseArg = /* @__PURE__ */ __name((argument, value, previous) => {
1902
+ let parsedValue = value;
1903
+ if (value !== null && argument.parseArg) {
1904
+ try {
1905
+ parsedValue = argument.parseArg(value, previous);
1906
+ } catch (err) {
1907
+ if (err.code === "commander.invalidArgument") {
1908
+ const message = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'. ${err.message}`;
1909
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1910
+ }
1911
+ throw err;
1912
+ }
1913
+ }
1914
+ return parsedValue;
1915
+ }, "myParseArg");
1916
+ this._checkNumberOfArguments();
1917
+ const processedArgs = [];
1918
+ this._args.forEach((declaredArg, index) => {
1919
+ let value = declaredArg.defaultValue;
1920
+ if (declaredArg.variadic) {
1921
+ if (index < this.args.length) {
1922
+ value = this.args.slice(index);
1923
+ if (declaredArg.parseArg) {
1924
+ value = value.reduce((processed, v) => {
1925
+ return myParseArg(declaredArg, v, processed);
1926
+ }, declaredArg.defaultValue);
1927
+ }
1928
+ } else if (value === void 0) {
1929
+ value = [];
1930
+ }
1931
+ } else if (index < this.args.length) {
1932
+ value = this.args[index];
1933
+ if (declaredArg.parseArg) {
1934
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1935
+ }
1936
+ }
1937
+ processedArgs[index] = value;
1938
+ });
1939
+ this.processedArgs = processedArgs;
1940
+ }
1941
+ /**
1942
+ * Once we have a promise we chain, but call synchronously until then.
1943
+ *
1944
+ * @param {Promise|undefined} promise
1945
+ * @param {Function} fn
1946
+ * @return {Promise|undefined}
1947
+ * @api private
1948
+ */
1949
+ _chainOrCall(promise, fn) {
1950
+ if (promise && promise.then && typeof promise.then === "function") {
1951
+ return promise.then(() => fn());
1952
+ }
1953
+ return fn();
1954
+ }
1955
+ /**
1956
+ *
1957
+ * @param {Promise|undefined} promise
1958
+ * @param {string} event
1959
+ * @return {Promise|undefined}
1960
+ * @api private
1961
+ */
1962
+ _chainOrCallHooks(promise, event) {
1963
+ let result = promise;
1964
+ const hooks = [];
1965
+ getCommandAndParents(this).reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1966
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1967
+ hooks.push({ hookedCommand, callback });
1968
+ });
1969
+ });
1970
+ if (event === "postAction") {
1971
+ hooks.reverse();
1972
+ }
1973
+ hooks.forEach((hookDetail) => {
1974
+ result = this._chainOrCall(result, () => {
1975
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1976
+ });
1977
+ });
1978
+ return result;
1979
+ }
1980
+ /**
1981
+ *
1982
+ * @param {Promise|undefined} promise
1983
+ * @param {Command} subCommand
1984
+ * @param {string} event
1985
+ * @return {Promise|undefined}
1986
+ * @api private
1987
+ */
1988
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1989
+ let result = promise;
1990
+ if (this._lifeCycleHooks[event] !== void 0) {
1991
+ this._lifeCycleHooks[event].forEach((hook) => {
1992
+ result = this._chainOrCall(result, () => {
1993
+ return hook(this, subCommand);
1994
+ });
1995
+ });
1996
+ }
1997
+ return result;
1998
+ }
1999
+ /**
2000
+ * Process arguments in context of this command.
2001
+ * Returns action result, in case it is a promise.
2002
+ *
2003
+ * @api private
2004
+ */
2005
+ _parseCommand(operands, unknown) {
2006
+ const parsed = this.parseOptions(unknown);
2007
+ this._parseOptionsEnv();
2008
+ this._parseOptionsImplied();
2009
+ operands = operands.concat(parsed.operands);
2010
+ unknown = parsed.unknown;
2011
+ this.args = operands.concat(unknown);
2012
+ if (operands && this._findCommand(operands[0])) {
2013
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2014
+ }
2015
+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2016
+ if (operands.length === 1) {
2017
+ this.help();
2018
+ }
2019
+ return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
2020
+ }
2021
+ if (this._defaultCommandName) {
2022
+ outputHelpIfRequested(this, unknown);
2023
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2024
+ }
2025
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2026
+ this.help({ error: true });
2027
+ }
2028
+ outputHelpIfRequested(this, parsed.unknown);
2029
+ this._checkForMissingMandatoryOptions();
2030
+ this._checkForConflictingOptions();
2031
+ const checkForUnknownOptions = /* @__PURE__ */ __name(() => {
2032
+ if (parsed.unknown.length > 0) {
2033
+ this.unknownOption(parsed.unknown[0]);
2034
+ }
2035
+ }, "checkForUnknownOptions");
2036
+ const commandEvent = `command:${this.name()}`;
2037
+ if (this._actionHandler) {
2038
+ checkForUnknownOptions();
2039
+ this._processArguments();
2040
+ let actionResult;
2041
+ actionResult = this._chainOrCallHooks(actionResult, "preAction");
2042
+ actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs));
2043
+ if (this.parent) {
2044
+ actionResult = this._chainOrCall(actionResult, () => {
2045
+ this.parent.emit(commandEvent, operands, unknown);
2046
+ });
2047
+ }
2048
+ actionResult = this._chainOrCallHooks(actionResult, "postAction");
2049
+ return actionResult;
2050
+ }
2051
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2052
+ checkForUnknownOptions();
2053
+ this._processArguments();
2054
+ this.parent.emit(commandEvent, operands, unknown);
2055
+ } else if (operands.length) {
2056
+ if (this._findCommand("*")) {
2057
+ return this._dispatchSubcommand("*", operands, unknown);
2058
+ }
2059
+ if (this.listenerCount("command:*")) {
2060
+ this.emit("command:*", operands, unknown);
2061
+ } else if (this.commands.length) {
2062
+ this.unknownCommand();
2063
+ } else {
2064
+ checkForUnknownOptions();
2065
+ this._processArguments();
2066
+ }
2067
+ } else if (this.commands.length) {
2068
+ checkForUnknownOptions();
2069
+ this.help({ error: true });
2070
+ } else {
2071
+ checkForUnknownOptions();
2072
+ this._processArguments();
2073
+ }
2074
+ }
2075
+ /**
2076
+ * Find matching command.
2077
+ *
2078
+ * @api private
2079
+ */
2080
+ _findCommand(name) {
2081
+ if (!name) return void 0;
2082
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2083
+ }
2084
+ /**
2085
+ * Return an option matching `arg` if any.
2086
+ *
2087
+ * @param {string} arg
2088
+ * @return {Option}
2089
+ * @api private
2090
+ */
2091
+ _findOption(arg) {
2092
+ return this.options.find((option) => option.is(arg));
2093
+ }
2094
+ /**
2095
+ * Display an error message if a mandatory option does not have a value.
2096
+ * Called after checking for help flags in leaf subcommand.
2097
+ *
2098
+ * @api private
2099
+ */
2100
+ _checkForMissingMandatoryOptions() {
2101
+ for (let cmd = this; cmd; cmd = cmd.parent) {
2102
+ cmd.options.forEach((anOption) => {
2103
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2104
+ cmd.missingMandatoryOptionValue(anOption);
2105
+ }
2106
+ });
2107
+ }
2108
+ }
2109
+ /**
2110
+ * Display an error message if conflicting options are used together in this.
2111
+ *
2112
+ * @api private
2113
+ */
2114
+ _checkForConflictingLocalOptions() {
2115
+ const definedNonDefaultOptions = this.options.filter(
2116
+ (option) => {
2117
+ const optionKey = option.attributeName();
2118
+ if (this.getOptionValue(optionKey) === void 0) {
2119
+ return false;
2120
+ }
2121
+ return this.getOptionValueSource(optionKey) !== "default";
2122
+ }
2123
+ );
2124
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2125
+ (option) => option.conflictsWith.length > 0
2126
+ );
2127
+ optionsWithConflicting.forEach((option) => {
2128
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2129
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2130
+ );
2131
+ if (conflictingAndDefined) {
2132
+ this._conflictingOption(option, conflictingAndDefined);
2133
+ }
2134
+ });
2135
+ }
2136
+ /**
2137
+ * Display an error message if conflicting options are used together.
2138
+ * Called after checking for help flags in leaf subcommand.
2139
+ *
2140
+ * @api private
2141
+ */
2142
+ _checkForConflictingOptions() {
2143
+ for (let cmd = this; cmd; cmd = cmd.parent) {
2144
+ cmd._checkForConflictingLocalOptions();
2145
+ }
2146
+ }
2147
+ /**
2148
+ * Parse options from `argv` removing known options,
2149
+ * and return argv split into operands and unknown arguments.
2150
+ *
2151
+ * Examples:
2152
+ *
2153
+ * argv => operands, unknown
2154
+ * --known kkk op => [op], []
2155
+ * op --known kkk => [op], []
2156
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2157
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2158
+ *
2159
+ * @param {String[]} argv
2160
+ * @return {{operands: String[], unknown: String[]}}
2161
+ */
2162
+ parseOptions(argv) {
2163
+ const operands = [];
2164
+ const unknown = [];
2165
+ let dest = operands;
2166
+ const args = argv.slice();
2167
+ function maybeOption(arg) {
2168
+ return arg.length > 1 && arg[0] === "-";
2169
+ }
2170
+ __name(maybeOption, "maybeOption");
2171
+ let activeVariadicOption = null;
2172
+ while (args.length) {
2173
+ const arg = args.shift();
2174
+ if (arg === "--") {
2175
+ if (dest === unknown) dest.push(arg);
2176
+ dest.push(...args);
2177
+ break;
2178
+ }
2179
+ if (activeVariadicOption && !maybeOption(arg)) {
2180
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2181
+ continue;
2182
+ }
2183
+ activeVariadicOption = null;
2184
+ if (maybeOption(arg)) {
2185
+ const option = this._findOption(arg);
2186
+ if (option) {
2187
+ if (option.required) {
2188
+ const value = args.shift();
2189
+ if (value === void 0) this.optionMissingArgument(option);
2190
+ this.emit(`option:${option.name()}`, value);
2191
+ } else if (option.optional) {
2192
+ let value = null;
2193
+ if (args.length > 0 && !maybeOption(args[0])) {
2194
+ value = args.shift();
2195
+ }
2196
+ this.emit(`option:${option.name()}`, value);
2197
+ } else {
2198
+ this.emit(`option:${option.name()}`);
2199
+ }
2200
+ activeVariadicOption = option.variadic ? option : null;
2201
+ continue;
2202
+ }
2203
+ }
2204
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2205
+ const option = this._findOption(`-${arg[1]}`);
2206
+ if (option) {
2207
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2208
+ this.emit(`option:${option.name()}`, arg.slice(2));
2209
+ } else {
2210
+ this.emit(`option:${option.name()}`);
2211
+ args.unshift(`-${arg.slice(2)}`);
2212
+ }
2213
+ continue;
2214
+ }
2215
+ }
2216
+ if (/^--[^=]+=/.test(arg)) {
2217
+ const index = arg.indexOf("=");
2218
+ const option = this._findOption(arg.slice(0, index));
2219
+ if (option && (option.required || option.optional)) {
2220
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2221
+ continue;
2222
+ }
2223
+ }
2224
+ if (maybeOption(arg)) {
2225
+ dest = unknown;
2226
+ }
2227
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2228
+ if (this._findCommand(arg)) {
2229
+ operands.push(arg);
2230
+ if (args.length > 0) unknown.push(...args);
2231
+ break;
2232
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2233
+ operands.push(arg);
2234
+ if (args.length > 0) operands.push(...args);
2235
+ break;
2236
+ } else if (this._defaultCommandName) {
2237
+ unknown.push(arg);
2238
+ if (args.length > 0) unknown.push(...args);
2239
+ break;
2240
+ }
2241
+ }
2242
+ if (this._passThroughOptions) {
2243
+ dest.push(arg);
2244
+ if (args.length > 0) dest.push(...args);
2245
+ break;
2246
+ }
2247
+ dest.push(arg);
2248
+ }
2249
+ return { operands, unknown };
2250
+ }
2251
+ /**
2252
+ * Return an object containing local option values as key-value pairs.
2253
+ *
2254
+ * @return {Object}
2255
+ */
2256
+ opts() {
2257
+ if (this._storeOptionsAsProperties) {
2258
+ const result = {};
2259
+ const len = this.options.length;
2260
+ for (let i = 0; i < len; i++) {
2261
+ const key = this.options[i].attributeName();
2262
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2263
+ }
2264
+ return result;
2265
+ }
2266
+ return this._optionValues;
2267
+ }
2268
+ /**
2269
+ * Return an object containing merged local and global option values as key-value pairs.
2270
+ *
2271
+ * @return {Object}
2272
+ */
2273
+ optsWithGlobals() {
2274
+ return getCommandAndParents(this).reduce(
2275
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2276
+ {}
2277
+ );
2278
+ }
2279
+ /**
2280
+ * Display error message and exit (or call exitOverride).
2281
+ *
2282
+ * @param {string} message
2283
+ * @param {Object} [errorOptions]
2284
+ * @param {string} [errorOptions.code] - an id string representing the error
2285
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2286
+ */
2287
+ error(message, errorOptions) {
2288
+ this._outputConfiguration.outputError(`${message}
2289
+ `, this._outputConfiguration.writeErr);
2290
+ if (typeof this._showHelpAfterError === "string") {
2291
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2292
+ `);
2293
+ } else if (this._showHelpAfterError) {
2294
+ this._outputConfiguration.writeErr("\n");
2295
+ this.outputHelp({ error: true });
2296
+ }
2297
+ const config = errorOptions || {};
2298
+ const exitCode = config.exitCode || 1;
2299
+ const code = config.code || "commander.error";
2300
+ this._exit(exitCode, code, message);
2301
+ }
2302
+ /**
2303
+ * Apply any option related environment variables, if option does
2304
+ * not have a value from cli or client code.
2305
+ *
2306
+ * @api private
2307
+ */
2308
+ _parseOptionsEnv() {
2309
+ this.options.forEach((option) => {
2310
+ if (option.envVar && option.envVar in process2.env) {
2311
+ const optionKey = option.attributeName();
2312
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2313
+ if (option.required || option.optional) {
2314
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2315
+ } else {
2316
+ this.emit(`optionEnv:${option.name()}`);
2317
+ }
2318
+ }
2319
+ }
2320
+ });
2321
+ }
2322
+ /**
2323
+ * Apply any implied option values, if option is undefined or default value.
2324
+ *
2325
+ * @api private
2326
+ */
2327
+ _parseOptionsImplied() {
2328
+ const dualHelper = new DualOptions(this.options);
2329
+ const hasCustomOptionValue = /* @__PURE__ */ __name((optionKey) => {
2330
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2331
+ }, "hasCustomOptionValue");
2332
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2333
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2334
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2335
+ });
2336
+ });
2337
+ }
2338
+ /**
2339
+ * Argument `name` is missing.
2340
+ *
2341
+ * @param {string} name
2342
+ * @api private
2343
+ */
2344
+ missingArgument(name) {
2345
+ const message = `error: missing required argument '${name}'`;
2346
+ this.error(message, { code: "commander.missingArgument" });
2347
+ }
2348
+ /**
2349
+ * `Option` is missing an argument.
2350
+ *
2351
+ * @param {Option} option
2352
+ * @api private
2353
+ */
2354
+ optionMissingArgument(option) {
2355
+ const message = `error: option '${option.flags}' argument missing`;
2356
+ this.error(message, { code: "commander.optionMissingArgument" });
2357
+ }
2358
+ /**
2359
+ * `Option` does not have a value, and is a mandatory option.
2360
+ *
2361
+ * @param {Option} option
2362
+ * @api private
2363
+ */
2364
+ missingMandatoryOptionValue(option) {
2365
+ const message = `error: required option '${option.flags}' not specified`;
2366
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2367
+ }
2368
+ /**
2369
+ * `Option` conflicts with another option.
2370
+ *
2371
+ * @param {Option} option
2372
+ * @param {Option} conflictingOption
2373
+ * @api private
2374
+ */
2375
+ _conflictingOption(option, conflictingOption) {
2376
+ const findBestOptionFromValue = /* @__PURE__ */ __name((option2) => {
2377
+ const optionKey = option2.attributeName();
2378
+ const optionValue = this.getOptionValue(optionKey);
2379
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2380
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2381
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2382
+ return negativeOption;
2383
+ }
2384
+ return positiveOption || option2;
2385
+ }, "findBestOptionFromValue");
2386
+ const getErrorMessage = /* @__PURE__ */ __name((option2) => {
2387
+ const bestOption = findBestOptionFromValue(option2);
2388
+ const optionKey = bestOption.attributeName();
2389
+ const source = this.getOptionValueSource(optionKey);
2390
+ if (source === "env") {
2391
+ return `environment variable '${bestOption.envVar}'`;
2392
+ }
2393
+ return `option '${bestOption.flags}'`;
2394
+ }, "getErrorMessage");
2395
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2396
+ this.error(message, { code: "commander.conflictingOption" });
2397
+ }
2398
+ /**
2399
+ * Unknown option `flag`.
2400
+ *
2401
+ * @param {string} flag
2402
+ * @api private
2403
+ */
2404
+ unknownOption(flag) {
2405
+ if (this._allowUnknownOption) return;
2406
+ let suggestion = "";
2407
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2408
+ let candidateFlags = [];
2409
+ let command = this;
2410
+ do {
2411
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2412
+ candidateFlags = candidateFlags.concat(moreFlags);
2413
+ command = command.parent;
2414
+ } while (command && !command._enablePositionalOptions);
2415
+ suggestion = suggestSimilar(flag, candidateFlags);
2416
+ }
2417
+ const message = `error: unknown option '${flag}'${suggestion}`;
2418
+ this.error(message, { code: "commander.unknownOption" });
2419
+ }
2420
+ /**
2421
+ * Excess arguments, more than expected.
2422
+ *
2423
+ * @param {string[]} receivedArgs
2424
+ * @api private
2425
+ */
2426
+ _excessArguments(receivedArgs) {
2427
+ if (this._allowExcessArguments) return;
2428
+ const expected = this._args.length;
2429
+ const s = expected === 1 ? "" : "s";
2430
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2431
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2432
+ this.error(message, { code: "commander.excessArguments" });
2433
+ }
2434
+ /**
2435
+ * Unknown command.
2436
+ *
2437
+ * @api private
2438
+ */
2439
+ unknownCommand() {
2440
+ const unknownName = this.args[0];
2441
+ let suggestion = "";
2442
+ if (this._showSuggestionAfterError) {
2443
+ const candidateNames = [];
2444
+ this.createHelp().visibleCommands(this).forEach((command) => {
2445
+ candidateNames.push(command.name());
2446
+ if (command.alias()) candidateNames.push(command.alias());
2447
+ });
2448
+ suggestion = suggestSimilar(unknownName, candidateNames);
2449
+ }
2450
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2451
+ this.error(message, { code: "commander.unknownCommand" });
2452
+ }
2453
+ /**
2454
+ * Set the program version to `str`.
2455
+ *
2456
+ * This method auto-registers the "-V, --version" flag
2457
+ * which will print the version number when passed.
2458
+ *
2459
+ * You can optionally supply the flags and description to override the defaults.
2460
+ *
2461
+ * @param {string} str
2462
+ * @param {string} [flags]
2463
+ * @param {string} [description]
2464
+ * @return {this | string} `this` command for chaining, or version string if no arguments
2465
+ */
2466
+ version(str, flags, description) {
2467
+ if (str === void 0) return this._version;
2468
+ this._version = str;
2469
+ flags = flags || "-V, --version";
2470
+ description = description || "output the version number";
2471
+ const versionOption = this.createOption(flags, description);
2472
+ this._versionOptionName = versionOption.attributeName();
2473
+ this.options.push(versionOption);
2474
+ this.on("option:" + versionOption.name(), () => {
2475
+ this._outputConfiguration.writeOut(`${str}
2476
+ `);
2477
+ this._exit(0, "commander.version", str);
2478
+ });
2479
+ return this;
2480
+ }
2481
+ /**
2482
+ * Set the description.
2483
+ *
2484
+ * @param {string} [str]
2485
+ * @param {Object} [argsDescription]
2486
+ * @return {string|Command}
2487
+ */
2488
+ description(str, argsDescription) {
2489
+ if (str === void 0 && argsDescription === void 0) return this._description;
2490
+ this._description = str;
2491
+ if (argsDescription) {
2492
+ this._argsDescription = argsDescription;
2493
+ }
2494
+ return this;
2495
+ }
2496
+ /**
2497
+ * Set the summary. Used when listed as subcommand of parent.
2498
+ *
2499
+ * @param {string} [str]
2500
+ * @return {string|Command}
2501
+ */
2502
+ summary(str) {
2503
+ if (str === void 0) return this._summary;
2504
+ this._summary = str;
2505
+ return this;
2506
+ }
2507
+ /**
2508
+ * Set an alias for the command.
2509
+ *
2510
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2511
+ *
2512
+ * @param {string} [alias]
2513
+ * @return {string|Command}
2514
+ */
2515
+ alias(alias) {
2516
+ if (alias === void 0) return this._aliases[0];
2517
+ let command = this;
2518
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2519
+ command = this.commands[this.commands.length - 1];
2520
+ }
2521
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2522
+ command._aliases.push(alias);
2523
+ return this;
2524
+ }
2525
+ /**
2526
+ * Set aliases for the command.
2527
+ *
2528
+ * Only the first alias is shown in the auto-generated help.
2529
+ *
2530
+ * @param {string[]} [aliases]
2531
+ * @return {string[]|Command}
2532
+ */
2533
+ aliases(aliases) {
2534
+ if (aliases === void 0) return this._aliases;
2535
+ aliases.forEach((alias) => this.alias(alias));
2536
+ return this;
2537
+ }
2538
+ /**
2539
+ * Set / get the command usage `str`.
2540
+ *
2541
+ * @param {string} [str]
2542
+ * @return {String|Command}
2543
+ */
2544
+ usage(str) {
2545
+ if (str === void 0) {
2546
+ if (this._usage) return this._usage;
2547
+ const args = this._args.map((arg) => {
2548
+ return humanReadableArgName(arg);
2549
+ });
2550
+ return [].concat(
2551
+ this.options.length || this._hasHelpOption ? "[options]" : [],
2552
+ this.commands.length ? "[command]" : [],
2553
+ this._args.length ? args : []
2554
+ ).join(" ");
2555
+ }
2556
+ this._usage = str;
2557
+ return this;
2558
+ }
2559
+ /**
2560
+ * Get or set the name of the command.
2561
+ *
2562
+ * @param {string} [str]
2563
+ * @return {string|Command}
2564
+ */
2565
+ name(str) {
2566
+ if (str === void 0) return this._name;
2567
+ this._name = str;
2568
+ return this;
2569
+ }
2570
+ /**
2571
+ * Set the name of the command from script filename, such as process.argv[1],
2572
+ * or require.main.filename, or __filename.
2573
+ *
2574
+ * (Used internally and public although not documented in README.)
2575
+ *
2576
+ * @example
2577
+ * program.nameFromFilename(require.main.filename);
2578
+ *
2579
+ * @param {string} filename
2580
+ * @return {Command}
2581
+ */
2582
+ nameFromFilename(filename) {
2583
+ this._name = path5.basename(filename, path5.extname(filename));
2584
+ return this;
2585
+ }
2586
+ /**
2587
+ * Get or set the directory for searching for executable subcommands of this command.
2588
+ *
2589
+ * @example
2590
+ * program.executableDir(__dirname);
2591
+ * // or
2592
+ * program.executableDir('subcommands');
2593
+ *
2594
+ * @param {string} [path]
2595
+ * @return {string|Command}
2596
+ */
2597
+ executableDir(path6) {
2598
+ if (path6 === void 0) return this._executableDir;
2599
+ this._executableDir = path6;
2600
+ return this;
2601
+ }
2602
+ /**
2603
+ * Return program help documentation.
2604
+ *
2605
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2606
+ * @return {string}
2607
+ */
2608
+ helpInformation(contextOptions) {
2609
+ const helper = this.createHelp();
2610
+ if (helper.helpWidth === void 0) {
2611
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2612
+ }
2613
+ return helper.formatHelp(this, helper);
2614
+ }
2615
+ /**
2616
+ * @api private
2617
+ */
2618
+ _getHelpContext(contextOptions) {
2619
+ contextOptions = contextOptions || {};
2620
+ const context = { error: !!contextOptions.error };
2621
+ let write;
2622
+ if (context.error) {
2623
+ write = /* @__PURE__ */ __name((arg) => this._outputConfiguration.writeErr(arg), "write");
2624
+ } else {
2625
+ write = /* @__PURE__ */ __name((arg) => this._outputConfiguration.writeOut(arg), "write");
2626
+ }
2627
+ context.write = contextOptions.write || write;
2628
+ context.command = this;
2629
+ return context;
2630
+ }
2631
+ /**
2632
+ * Output help information for this command.
2633
+ *
2634
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2635
+ *
2636
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2637
+ */
2638
+ outputHelp(contextOptions) {
2639
+ let deprecatedCallback;
2640
+ if (typeof contextOptions === "function") {
2641
+ deprecatedCallback = contextOptions;
2642
+ contextOptions = void 0;
2643
+ }
2644
+ const context = this._getHelpContext(contextOptions);
2645
+ getCommandAndParents(this).reverse().forEach((command) => command.emit("beforeAllHelp", context));
2646
+ this.emit("beforeHelp", context);
2647
+ let helpInformation = this.helpInformation(context);
2648
+ if (deprecatedCallback) {
2649
+ helpInformation = deprecatedCallback(helpInformation);
2650
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2651
+ throw new Error("outputHelp callback must return a string or a Buffer");
2652
+ }
2653
+ }
2654
+ context.write(helpInformation);
2655
+ this.emit(this._helpLongFlag);
2656
+ this.emit("afterHelp", context);
2657
+ getCommandAndParents(this).forEach((command) => command.emit("afterAllHelp", context));
2658
+ }
2659
+ /**
2660
+ * You can pass in flags and a description to override the help
2661
+ * flags and help description for your command. Pass in false to
2662
+ * disable the built-in help option.
2663
+ *
2664
+ * @param {string | boolean} [flags]
2665
+ * @param {string} [description]
2666
+ * @return {Command} `this` command for chaining
2667
+ */
2668
+ helpOption(flags, description) {
2669
+ if (typeof flags === "boolean") {
2670
+ this._hasHelpOption = flags;
2671
+ return this;
2672
+ }
2673
+ this._helpFlags = flags || this._helpFlags;
2674
+ this._helpDescription = description || this._helpDescription;
2675
+ const helpFlags = splitOptionFlags(this._helpFlags);
2676
+ this._helpShortFlag = helpFlags.shortFlag;
2677
+ this._helpLongFlag = helpFlags.longFlag;
2678
+ return this;
2679
+ }
2680
+ /**
2681
+ * Output help information and exit.
2682
+ *
2683
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2684
+ *
2685
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2686
+ */
2687
+ help(contextOptions) {
2688
+ this.outputHelp(contextOptions);
2689
+ let exitCode = process2.exitCode || 0;
2690
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2691
+ exitCode = 1;
2692
+ }
2693
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2694
+ }
2695
+ /**
2696
+ * Add additional text to be displayed with the built-in help.
2697
+ *
2698
+ * Position is 'before' or 'after' to affect just this command,
2699
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2700
+ *
2701
+ * @param {string} position - before or after built-in help
2702
+ * @param {string | Function} text - string to add, or a function returning a string
2703
+ * @return {Command} `this` command for chaining
2704
+ */
2705
+ addHelpText(position, text) {
2706
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2707
+ if (!allowedValues.includes(position)) {
2708
+ throw new Error(`Unexpected value for position to addHelpText.
2709
+ Expecting one of '${allowedValues.join("', '")}'`);
2710
+ }
2711
+ const helpEvent = `${position}Help`;
2712
+ this.on(helpEvent, (context) => {
2713
+ let helpStr;
2714
+ if (typeof text === "function") {
2715
+ helpStr = text({ error: context.error, command: context.command });
2716
+ } else {
2717
+ helpStr = text;
2718
+ }
2719
+ if (helpStr) {
2720
+ context.write(`${helpStr}
2721
+ `);
2722
+ }
2723
+ });
2724
+ return this;
2725
+ }
2726
+ };
2727
+ function outputHelpIfRequested(cmd, args) {
2728
+ const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2729
+ if (helpOption) {
2730
+ cmd.outputHelp();
2731
+ cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2732
+ }
2733
+ }
2734
+ __name(outputHelpIfRequested, "outputHelpIfRequested");
2735
+ function incrementNodeInspectorPort(args) {
2736
+ return args.map((arg) => {
2737
+ if (!arg.startsWith("--inspect")) {
2738
+ return arg;
2739
+ }
2740
+ let debugOption;
2741
+ let debugHost = "127.0.0.1";
2742
+ let debugPort = "9229";
2743
+ let match;
2744
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2745
+ debugOption = match[1];
2746
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2747
+ debugOption = match[1];
2748
+ if (/^\d+$/.test(match[3])) {
2749
+ debugPort = match[3];
2750
+ } else {
2751
+ debugHost = match[3];
2752
+ }
2753
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2754
+ debugOption = match[1];
2755
+ debugHost = match[3];
2756
+ debugPort = match[4];
2757
+ }
2758
+ if (debugOption && debugPort !== "0") {
2759
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2760
+ }
2761
+ return arg;
2762
+ });
2763
+ }
2764
+ __name(incrementNodeInspectorPort, "incrementNodeInspectorPort");
2765
+ function getCommandAndParents(startCommand) {
2766
+ const result = [];
2767
+ for (let command = startCommand; command; command = command.parent) {
2768
+ result.push(command);
2769
+ }
2770
+ return result;
2771
+ }
2772
+ __name(getCommandAndParents, "getCommandAndParents");
2773
+ exports.Command = Command;
2774
+ }
2775
+ });
2776
+
2777
+ // node_modules/commander/index.js
2778
+ var require_commander = __commonJS({
2779
+ "node_modules/commander/index.js"(exports, module) {
2780
+ "use strict";
2781
+ var { Argument } = require_argument();
2782
+ var { Command } = require_command();
2783
+ var { CommanderError, InvalidArgumentError } = require_error();
2784
+ var { Help } = require_help();
2785
+ var { Option } = require_option();
2786
+ exports = module.exports = new Command();
2787
+ exports.program = exports;
2788
+ exports.Argument = Argument;
2789
+ exports.Command = Command;
2790
+ exports.CommanderError = CommanderError;
2791
+ exports.Help = Help;
2792
+ exports.InvalidArgumentError = InvalidArgumentError;
2793
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2794
+ exports.Option = Option;
2795
+ }
2796
+ });
2797
+
14
2798
  // src/qcobjects-cli.ts
15
2799
  var qcobjects_cli_exports = {};
16
2800
  __export(qcobjects_cli_exports, {
17
- default: () => qcobjects_cli_default
2801
+ Main: () => Main,
2802
+ default: () => qcobjects_cli_default,
2803
+ defaultSettings: () => org_quickcorp_qcobjects_defaultsettings_exports
18
2804
  });
2805
+
2806
+ // src/org.quickcorp.qcobjects.defaultsettings.ts
2807
+ var org_quickcorp_qcobjects_defaultsettings_exports = {};
2808
+ __export(org_quickcorp_qcobjects_defaultsettings_exports, {
2809
+ __get_version__: () => __get_version__,
2810
+ __get_version_string__: () => __get_version_string__
2811
+ });
2812
+ __require("qcobjects");
2813
+ var { CONFIG, global, logger, _Crypt, findPackageNodePath, Export } = __require("qcobjects");
2814
+ var __get_version__ = /* @__PURE__ */ __name(() => {
2815
+ const path5 = __require("path");
2816
+ const absolutePath3 = path5.resolve(__dirname, "./");
2817
+ const package_config2 = __require(path5.resolve(process.cwd(), "package.json"));
2818
+ const qcobjects_pkg_config = __require("qcobjects/package.json");
2819
+ const qcobjects_sdk_pkg_config = __require("qcobjects-sdk/package.json");
2820
+ return {
2821
+ "qcobjects": qcobjects_pkg_config.version,
2822
+ "sdk": qcobjects_sdk_pkg_config.version,
2823
+ "cli": package_config2.version
2824
+ };
2825
+ }, "__get_version__");
2826
+ var __get_version_string__ = /* @__PURE__ */ __name(() => {
2827
+ const version = __get_version__();
2828
+ return "QCObjects: v" + version.qcobjects + ", SDK: v" + version.sdk + ", CLI: v" + version.cli;
2829
+ }, "__get_version_string__");
2830
+ Export(__get_version__);
2831
+ Export(__get_version_string__);
2832
+ var __load_default_settings__ = /* @__PURE__ */ __name(() => {
2833
+ CONFIG.set("documentRootFileIndex", "index.html");
2834
+ CONFIG.set("projectPath", `${process.cwd()}/`);
2835
+ CONFIG.set("useConfigService", false);
2836
+ CONFIG.set("documentRoot", "./");
2837
+ CONFIG.set("serverPortHTTP", 80);
2838
+ CONFIG.set("serverPortHTTPS", 443);
2839
+ CONFIG.set("private-key-pem", "localhost-privkey.pem");
2840
+ CONFIG.set("private-cert-pem", "localhost-cert.pem");
2841
+ CONFIG.set("allowHTTP1", true);
2842
+ CONFIG.set("useTemplate", false);
2843
+ CONFIG.set("domain", "localhost");
2844
+ const setDevMode = /* @__PURE__ */ __name((devmode) => {
2845
+ if (typeof devmode !== "undefined") {
2846
+ switch (true) {
2847
+ case devmode == "debug":
2848
+ logger.debugEnabled = true;
2849
+ logger.warnEnabled = true;
2850
+ logger.infoEnabled = true;
2851
+ break;
2852
+ case devmode == "warn":
2853
+ logger.debugEnabled = false;
2854
+ logger.warnEnabled = true;
2855
+ logger.infoEnabled = true;
2856
+ break;
2857
+ case devmode == "info":
2858
+ logger.debugEnabled = false;
2859
+ logger.warnEnabled = false;
2860
+ logger.infoEnabled = true;
2861
+ break;
2862
+ default:
2863
+ logger.debugEnabled = false;
2864
+ logger.warnEnabled = false;
2865
+ logger.infoEnabled = false;
2866
+ break;
2867
+ }
2868
+ } else {
2869
+ logger.debugEnabled = false;
2870
+ logger.warnEnabled = false;
2871
+ logger.infoEnabled = false;
2872
+ }
2873
+ }, "setDevMode");
2874
+ try {
2875
+ var _config = __require(CONFIG.get("projectPath") + "config.json");
2876
+ logger.debug("Loading settings from your config.json");
2877
+ const _secretKey = Object.hasOwn(_config, "domain") ? _config["domain"] : "_secret_";
2878
+ if (Object.hasOwn(_config, "__encoded__")) {
2879
+ _config = JSON.parse(_Crypt.decrypt(_config.__encoded__, _secretKey));
2880
+ }
2881
+ for (var k in _config) {
2882
+ CONFIG.set(k, _config[k]);
2883
+ }
2884
+ setDevMode(CONFIG.get("devmode", ""));
2885
+ if (typeof CONFIG.get("backend") !== "undefined") {
2886
+ global.set("backendAvailable", true);
2887
+ if (typeof CONFIG.get("basePath") !== "undefined") {
2888
+ logger.debug(`Changing the current directory: ${process.cwd()}`);
2889
+ try {
2890
+ process.chdir(CONFIG.get("basePath"));
2891
+ logger.debug(`New directory: ${process.cwd()}`);
2892
+ } catch (err) {
2893
+ logger.warn(`It was impossible to change the current chdir: ${err}`);
2894
+ }
2895
+ }
2896
+ }
2897
+ } catch (e) {
2898
+ logger.debug(e);
2899
+ logger.debug("Something went wrong trying to load config.json file in your project");
2900
+ }
2901
+ (async function() {
2902
+ const path5 = __require("path");
2903
+ const projectPath = CONFIG.get("projectPath", `${process.cwd()}/`);
2904
+ const loadDefaultRoutes = /* @__PURE__ */ __name(async () => {
2905
+ return await new Promise((resolve, reject) => {
2906
+ const sdkPath = path5.resolve(findPackageNodePath("qcobjects-sdk"), "qcobjects-sdk");
2907
+ const qcobjectsPath = path5.resolve(findPackageNodePath("qcobjects"), "qcobjects");
2908
+ let backend = CONFIG.get("backend");
2909
+ if (typeof backend === "undefined") {
2910
+ backend = {};
2911
+ }
2912
+ if (typeof backend.routes === "undefined") {
2913
+ backend.routes = [];
2914
+ }
2915
+ backend.routes = backend.routes.concat([
2916
+ {
2917
+ "name": "QCObjects.js",
2918
+ "description": "Redirection of QCObjects.js",
2919
+ "path": "^/QCObjects.js$",
2920
+ "microservice": "com.qcobjects.backend.microservice.static",
2921
+ "redirect_to": path5.resolve(qcobjectsPath, "src", "QCObjects.js"),
2922
+ "responseHeaders": {},
2923
+ "cors": {
2924
+ "allow_origins": "*"
2925
+ }
2926
+ },
2927
+ {
2928
+ "name": "QCObjects-SDK.js",
2929
+ "description": "Redirection of QCObjects SDK",
2930
+ "path": "^/js/packages/QCObjects-SDK.js$",
2931
+ "microservice": "com.qcobjects.backend.microservice.static",
2932
+ "redirect_to": path5.resolve(sdkPath, "src/QCObjects-SDK.js"),
2933
+ "responseHeaders": {},
2934
+ "cors": {
2935
+ "allow_origins": "*"
2936
+ }
2937
+ },
2938
+ {
2939
+ "name": "QCObjects-SDK Components",
2940
+ "description": "Redirection of QCObjects SDK",
2941
+ "path": "^/qcobjects-sdk/(.*)$",
2942
+ "microservice": "com.qcobjects.backend.microservice.static",
2943
+ "redirect_to": path5.resolve(sdkPath, "$1"),
2944
+ "responseHeaders": {},
2945
+ "cors": {
2946
+ "allow_origins": "*"
2947
+ }
2948
+ }
2949
+ ]);
2950
+ CONFIG.set("backend", backend);
2951
+ resolve();
2952
+ });
2953
+ }, "loadDefaultRoutes");
2954
+ await loadDefaultRoutes();
2955
+ })().then(() => logger.info("Default routes loaded")).catch((e) => {
2956
+ logger.warn(`An error ocurred loading default settings: ${e}`);
2957
+ });
2958
+ (function() {
2959
+ const path5 = __require("path");
2960
+ const fs3 = __require("fs");
2961
+ const projectPath = CONFIG.get("projectPath", `${process.cwd()}/`);
2962
+ logger.debug(`CONFIG.projectPath is set to ${projectPath}`);
2963
+ const findPath = /* @__PURE__ */ __name((p) => {
2964
+ const packagePath = path5.resolve(findPackageNodePath(p), p);
2965
+ return packagePath;
2966
+ }, "findPath");
2967
+ const getPackageJSON = /* @__PURE__ */ __name((p) => {
2968
+ let _json;
2969
+ try {
2970
+ const packagePath = findPath(p);
2971
+ if (typeof packagePath !== "undefined") {
2972
+ _json = JSON.parse(fs3.readFileSync(path5.resolve(`${packagePath}`, "./package.json")).toString());
2973
+ } else {
2974
+ _json = {};
2975
+ }
2976
+ } catch (e) {
2977
+ logger.debug(`It was impossible to get the package.json from ${p}: ${e}`);
2978
+ _json = {};
2979
+ }
2980
+ return _json;
2981
+ }, "getPackageJSON");
2982
+ const hasKeyword = /* @__PURE__ */ (() => {
2983
+ let keywords = {};
2984
+ return (p, keyword) => {
2985
+ if (typeof keywords === "undefined") {
2986
+ keywords = {};
2987
+ }
2988
+ try {
2989
+ if (typeof keywords[p] === "undefined") {
2990
+ keywords[p] = getPackageJSON(p).keywords;
2991
+ }
2992
+ } catch (e) {
2993
+ throw Error(`Something went wrong when trying to get the keywords of ${p}`);
2994
+ }
2995
+ return typeof keywords[p] !== "undefined" && keywords[p].includes(keyword);
2996
+ };
2997
+ })();
2998
+ const setBackendValue = /* @__PURE__ */ __name((name, value) => {
2999
+ const backend = CONFIG.get("backend", {});
3000
+ if (typeof value !== "undefined") {
3001
+ backend[name] = value;
3002
+ }
3003
+ CONFIG.set("backend", backend);
3004
+ }, "setBackendValue");
3005
+ const dependencies = /* @__PURE__ */ (() => {
3006
+ let deps = [];
3007
+ return () => {
3008
+ if (typeof deps === "undefined") {
3009
+ deps = Object.keys(JSON.parse(fs3.readFileSync(path5.resolve(`${projectPath}`, "./package.json")).toString()).dependencies);
3010
+ setBackendValue("dependencies", deps);
3011
+ }
3012
+ return deps;
3013
+ };
3014
+ })();
3015
+ const devDependencies = /* @__PURE__ */ (() => {
3016
+ let deps = [];
3017
+ return () => {
3018
+ if (typeof deps === "undefined") {
3019
+ deps = Object.keys(JSON.parse(fs3.readFileSync(path5.resolve(`${projectPath}`, "./package.json")).toString()).devDependencies);
3020
+ setBackendValue("devDependencies", deps);
3021
+ }
3022
+ return deps;
3023
+ };
3024
+ })();
3025
+ const loadLibs = /* @__PURE__ */ __name(() => {
3026
+ let _ret_;
3027
+ if (CONFIG.get("autodiscover", false) || CONFIG.get("autodiscover_libs", false)) {
3028
+ const libs = dependencies().filter((p) => hasKeyword(p, "qcobjects-lib"));
3029
+ setBackendValue("libs", libs);
3030
+ if (libs.length > 0) {
3031
+ logger.debug(`Plugin Libs found: ${libs.join(",")}`);
3032
+ _ret_ = Promise.all(libs.map((p) => {
3033
+ return __require(findPath(p));
3034
+ })).then(() => logger.info("Libs loaded"));
3035
+ } else {
3036
+ logger.debug("No Plugin Libs found.");
3037
+ _ret_ = Promise.resolve();
3038
+ }
3039
+ } else {
3040
+ logger.debug("To load libs, set autodiscover_libs to true in your config.json");
3041
+ _ret_ = Promise.resolve();
3042
+ }
3043
+ return _ret_;
3044
+ }, "loadLibs");
3045
+ const loadHandlers = /* @__PURE__ */ __name(() => {
3046
+ let _ret_;
3047
+ if (CONFIG.get("autodiscover", false) || CONFIG.get("autodiscover_handlers", false)) {
3048
+ const handlers = dependencies().filter((p) => hasKeyword(p, "qcobjects-handler"));
3049
+ setBackendValue("handlers", handlers);
3050
+ if (handlers.length > 0) {
3051
+ logger.debug(`Plugin Handlers found: ${handlers.join(",")}`);
3052
+ _ret_ = Promise.all(handlers.map((p) => {
3053
+ return __require(findPath(p));
3054
+ })).then(() => logger.info("Handlers loaded"));
3055
+ } else {
3056
+ logger.debug("No Plugin Handlers found.");
3057
+ _ret_ = Promise.resolve();
3058
+ }
3059
+ } else {
3060
+ logger.debug("To load handlers, set autodiscover_handlers to true in your config.json");
3061
+ _ret_ = Promise.resolve();
3062
+ }
3063
+ return _ret_;
3064
+ }, "loadHandlers");
3065
+ const loadCommands = /* @__PURE__ */ __name(() => {
3066
+ let _ret_;
3067
+ logger.debug(`Looking for custom commands as dependencies in: ${projectPath}/package.json`);
3068
+ if (CONFIG.get("autodiscover", false) || CONFIG.get("autodiscover_commands", false)) {
3069
+ const commands = dependencies().filter((p) => hasKeyword(p, "qcobjects-command"));
3070
+ setBackendValue("commands", commands);
3071
+ if (commands.length > 0) {
3072
+ logger.debug(`Plugin Commands found: ${commands.join(",")}`);
3073
+ _ret_ = Promise.all(commands.map((p) => {
3074
+ return __require(findPath(p));
3075
+ })).then(() => logger.info("Commands loaded"));
3076
+ } else {
3077
+ logger.debug("No Plugin Commands found.");
3078
+ _ret_ = Promise.resolve();
3079
+ }
3080
+ } else {
3081
+ logger.debug("To load commands, set autodiscover_commands to true in your config.json");
3082
+ _ret_ = Promise.resolve();
3083
+ }
3084
+ return _ret_;
3085
+ }, "loadCommands");
3086
+ const loadDevCommands = /* @__PURE__ */ __name(() => {
3087
+ let _ret_;
3088
+ logger.debug(`Looking for custom commands as dev dependencies in: ${projectPath}/package.json`);
3089
+ if (CONFIG.get("autodiscover", false) || CONFIG.get("autodiscover_commands", false)) {
3090
+ const commands = devDependencies().filter((p) => hasKeyword(p, "qcobjects-command"));
3091
+ setBackendValue("devCommands", commands);
3092
+ if (commands.length > 0) {
3093
+ logger.debug(`Dev Plugin Commands found: ${commands.join(",")}`);
3094
+ _ret_ = Promise.all(commands.map((p) => {
3095
+ return __require(findPath(p));
3096
+ })).then(() => logger.info("Commands loaded"));
3097
+ } else {
3098
+ logger.debug("No Plugin Commands found in dev dependencies.");
3099
+ _ret_ = Promise.resolve();
3100
+ }
3101
+ } else {
3102
+ logger.debug("To load commands, set autodiscover_commands to true in your config.json");
3103
+ _ret_ = Promise.resolve();
3104
+ }
3105
+ return _ret_;
3106
+ }, "loadDevCommands");
3107
+ if (CONFIG.get("autodiscover", false) || CONFIG.get("autodiscover_libs", false) || CONFIG.get("autodiscover_handlers", false) || CONFIG.get("autodiscover_commands", false)) {
3108
+ logger.info("Auto discover is enabled");
3109
+ } else if (!CONFIG.get("autodiscover", false)) {
3110
+ logger.info("Auto discover is disabled");
3111
+ logger.debug("To load all dependencies, set autodiscover to true in your config.json");
3112
+ } else {
3113
+ logger.info("Auto discover is disabled");
3114
+ }
3115
+ try {
3116
+ logger.debug("Loading Libs...");
3117
+ loadLibs().catch((e) => {
3118
+ logger.warn(`An error ocurred loading libs: ${e}`);
3119
+ });
3120
+ } catch (e) {
3121
+ throw Error(`Something went wrong trying to load libs: ${e.message}`);
3122
+ }
3123
+ try {
3124
+ logger.debug("Loading Handlers...");
3125
+ loadHandlers().catch((e) => {
3126
+ logger.warn(`An error ocurred loading handlers: ${e}`);
3127
+ });
3128
+ } catch (e) {
3129
+ throw Error(`Something went wrong trying to load handler: ${e.message}`);
3130
+ }
3131
+ try {
3132
+ logger.debug("Loading Commands...");
3133
+ loadCommands().catch((e) => {
3134
+ logger.warn(`An error ocurred loading commands: ${e}`);
3135
+ });
3136
+ } catch (e) {
3137
+ throw Error(`Something went wrong trying to load commands: ${e.message}`);
3138
+ }
3139
+ try {
3140
+ logger.debug("Loading Dev Commands...");
3141
+ loadDevCommands().catch((e) => {
3142
+ logger.warn(`An error ocurred loading dev commands: ${e}`);
3143
+ });
3144
+ } catch (e) {
3145
+ throw Error(`Something went wrong trying to load Dev commands: ${e.message}`);
3146
+ }
3147
+ try {
3148
+ const commands = CONFIG.get("backend", { commands: [] }).commands || [];
3149
+ const devCommands = CONFIG.get("backend", { devCommands: [] }).devCommands || [];
3150
+ setBackendValue("plugins", commands.concat(devCommands));
3151
+ } catch (e) {
3152
+ throw Error(`Something went wrong trying to load plugins list: ${e.message}`);
3153
+ }
3154
+ logger.info("Dependencies loaded");
3155
+ process.once("SIGTERM", () => {
3156
+ console.log("\x1B[33m%s\x1B[0m", "Bye bye!");
3157
+ process.exit();
3158
+ });
3159
+ })();
3160
+ }, "__load_default_settings__");
3161
+ global.__load_default_settings__ = __load_default_settings__;
3162
+ global.__load_default_settings__();
3163
+ var cleanCache = /* @__PURE__ */ __name(() => {
3164
+ Object.keys(__require.cache).forEach((key) => {
3165
+ delete __require.cache[key];
3166
+ });
3167
+ }, "cleanCache");
3168
+ var __reset_settings__ = /* @__PURE__ */ __name(() => {
3169
+ cleanCache();
3170
+ global.__load_default_settings__();
3171
+ }, "__reset_settings__");
3172
+ global.__reset_settings__ = __reset_settings__;
3173
+
3174
+ // src/org.qcobjects.enterprise.commands.ts
3175
+ import { execSync } from "node:child_process";
3176
+ var { Package, InheritClass, CONFIG: CONFIG2, logger: logger2 } = __require("qcobjects");
3177
+ var license = CONFIG2.get("enterprise-license", "1234");
3178
+ var email = CONFIG2.get("enterprise-email", "a@b.com");
3179
+ var QCObjectsEnterprise = class extends InheritClass {
3180
+ static {
3181
+ __name(this, "QCObjectsEnterprise");
3182
+ }
3183
+ install() {
3184
+ const instance = this;
3185
+ return instance.installEnterprise(license, email);
3186
+ }
3187
+ upgrade(switchCommander) {
3188
+ const instance = this;
3189
+ const readline = __require("readline");
3190
+ const rl = readline.createInterface({
3191
+ input: process.stdin,
3192
+ output: process.stdout
3193
+ });
3194
+ var emailQuestion = /* @__PURE__ */ __name(function() {
3195
+ rl.question(`
3196
+ [NOTE: No information will be sent to a server until I got your consent]
3197
+
3198
+ Please tell me your e-Mail (\u{1F48C}):
3199
+ `, (email2) => {
3200
+ if (email2 !== "") {
3201
+ var phoneNumberQuestion = /* @__PURE__ */ __name(function() {
3202
+ rl.question("Please tell me your phone number (\u{1F919}): \n", (phonenumber) => {
3203
+ if (phonenumber !== "") {
3204
+ rl.question(`
3205
+ Please select one of the following options (type a number):
3206
+
3207
+ 1.- \u{1F640} This is your first interaction \u{1F60D} with QCObjects Enterprise Edition \u{1F3E2},
3208
+ you want to send your email and phone number to one of our executives to process your
3209
+ inquiry, pay the license (when aplies) and receive a new fresh license number
3210
+ that will free up to you the most advanced features for large companies
3211
+
3212
+ 2.- \u2714 Your assigned executive \u{1F9D1} has given to you a new fresh QCObjects Enterprise Edition License Number
3213
+ and you want to enter it to follow up with the next steps.
3214
+
3215
+ 3.- \u{1F3C3} You want to quit this form, as you got here accidentally
3216
+ (You should think about it. It's not a coincidence, It's destiny \u{1F600}).
3217
+
3218
+ Please enter the number of the option and press [enter]: `, (interaction_option) => {
3219
+ logger2.infoEnabled = true;
3220
+ switch (interaction_option) {
3221
+ case "1":
3222
+ switchCommander.register(email2, phonenumber).then(function() {
3223
+ logger2.info(`\u{1F44F} Congrats! You have been successfully registered to the cloud! \u{1F44F}
3224
+ One of our executives will be in touch with you as soon as possible to give you the next steps
3225
+ to get a new License Number and start using QCObjects Entrprise Edition!
3226
+
3227
+ (In the meantime, you can continue using all the features of the QCObjects Community Edition)
3228
+ `);
3229
+ rl.close();
3230
+ }).catch(() => {
3231
+ rl.close();
3232
+ });
3233
+ break;
3234
+ case "2":
3235
+ rl.stdoutMuted = true;
3236
+ rl._writeToOutput = /* @__PURE__ */ __name(function _writeToOutput(stringToWrite) {
3237
+ if (rl.stdoutMuted)
3238
+ rl.output.write("*");
3239
+ else
3240
+ rl.output.write(stringToWrite);
3241
+ }, "_writeToOutput");
3242
+ rl.question("Please tell me the number of license that your executive has given to you: \n", (license2) => {
3243
+ rl.stdoutMuted = false;
3244
+ instance.installEnterprise(license2, email2);
3245
+ rl.close();
3246
+ });
3247
+ break;
3248
+ default:
3249
+ logger2.info("\u{1F937} You can continue to use QCObjects Community Edition, see you! \u{1F64B} ");
3250
+ rl.close();
3251
+ break;
3252
+ }
3253
+ });
3254
+ } else {
3255
+ console.log(`You need to enter a Phone Number if you want to be contacted.
3256
+ If you want to quit, press Ctrl-C.
3257
+ `);
3258
+ phoneNumberQuestion();
3259
+ }
3260
+ });
3261
+ }, "phoneNumberQuestion");
3262
+ phoneNumberQuestion();
3263
+ } else {
3264
+ console.log(`You need to enter a real e-Mail adress if you want to be contacted.
3265
+ If you want to quit, press Ctrl-C.
3266
+ `);
3267
+ emailQuestion();
3268
+ }
3269
+ });
3270
+ }, "emailQuestion");
3271
+ emailQuestion();
3272
+ }
3273
+ installEnterprise(license2, email2) {
3274
+ const asterisk = "*";
3275
+ logger2.info(`Your entered license number is ${asterisk.repeat(license2.length)} and the email that you have entered is ${email2}`);
3276
+ logger2.info("Now, I'm installing QCObjects Enterprise Edition in your computer...");
3277
+ const cmdDownloadGit = `npm i --force -g git+https://license:${license2}@software.qcobjects.io/qcobjects-enterprise/qcobjects-enterprise.git`;
3278
+ execSync(cmdDownloadGit);
3279
+ const stdout = execSync("qcobjects --version");
3280
+ if (stdout.lastIndexOf("Enterprise Edition") !== -1) {
3281
+ logger2.info("\u{1F44F} Congrats! Now you have installed QCObjects Entrprise Edition! \u{1F44F}");
3282
+ logger2.info(`You can test it using:
3283
+ > qcobjects --version
3284
+
3285
+ To find more help, type the command:
3286
+
3287
+ > qcobjects --help
3288
+
3289
+ Enjoy!
3290
+ `);
3291
+ } else {
3292
+ console.log("\u{1F926} Something went wrong \u{1F926} when trying to update your license to QCObjects Enterprise Edition");
3293
+ console.log("Ask your executive to help");
3294
+ }
3295
+ }
3296
+ };
3297
+ Package("org.qcobjects.enterprise.commands", [
3298
+ QCObjectsEnterprise
3299
+ ]);
3300
+
3301
+ // src/org.quickcorp.qcobjects.api.client_services.ts
3302
+ var { Package: Package2, Service, logger: logger3 } = __require("qcobjects");
3303
+ var QuickCorpCloud = class extends Service {
3304
+ static {
3305
+ __name(this, "QuickCorpCloud");
3306
+ }
3307
+ constructor({
3308
+ name = "quickcorp_cloud",
3309
+ external = true,
3310
+ useHTTP2 = true,
3311
+ cached = false,
3312
+ method = "post",
3313
+ headers = {
3314
+ "origin": "localhost",
3315
+ "content-type": "application/json"
3316
+ },
3317
+ basePath = "https://cloud.quickcorp.org/",
3318
+ url = "",
3319
+ withCredentials = false
3320
+ }) {
3321
+ super({
3322
+ name,
3323
+ external,
3324
+ useHTTP2,
3325
+ cached,
3326
+ method,
3327
+ headers,
3328
+ basePath,
3329
+ url,
3330
+ withCredentials
3331
+ });
3332
+ }
3333
+ _new_(o) {
3334
+ this.headers["authorization"] = "Basic token";
3335
+ this.url = this.basePath + o.apiMethod;
3336
+ this.data = o.data;
3337
+ }
3338
+ done(service, standardResponse) {
3339
+ logger3.debug(standardResponse);
3340
+ }
3341
+ fail(e) {
3342
+ logger3.debug(e);
3343
+ }
3344
+ };
3345
+ Package2("org.quickcorp.qcobjects.api.client_services", [
3346
+ QuickCorpCloud
3347
+ ]);
3348
+
3349
+ // src/com.qcobjects.cli.commands.version.ts
3350
+ var fs = __require("fs");
19
3351
  var path = __require("path");
20
- var absolutePath = path.resolve(__dirname, "./");
21
- var templatePath = path.resolve(__dirname, "./templates/apps/") + "/";
22
- var package_config = __require(absolutePath + "/../package.json");
23
- var { logger, InheritClass } = __require("qcobjects");
24
- logger.debugEnabled = false;
3352
+ var { exec, execSync: execSync2 } = __require("child_process");
3353
+ var { Package: Package3, InheritClass: InheritClass2, logger: logger4 } = __require("qcobjects");
3354
+ var CommandHandler = class extends InheritClass2 {
3355
+ static {
3356
+ __name(this, "CommandHandler");
3357
+ }
3358
+ constructor({ switchCommander }) {
3359
+ super({ switchCommander });
3360
+ const commandHandler = this;
3361
+ this.choiceOption = {
3362
+ v_major(filename, options) {
3363
+ filename = typeof filename === "undefined" ? "VERSION" : filename;
3364
+ const versionString = this.getVersionStringFromFile(filename);
3365
+ const versionSuffix = this.parseVersionSuffix(versionString);
3366
+ const versionObject = this.parseVersionString(versionString);
3367
+ const major = parseInt(versionObject.major);
3368
+ const minor = parseInt(versionObject.minor);
3369
+ const patch = parseInt(versionObject.patch);
3370
+ const newVersion = this.buildNewVersionString({ major: major + 1, minor, patch }, versionSuffix);
3371
+ this.saveNewVersionFile(filename, newVersion);
3372
+ if (options.syncGit) {
3373
+ var commitMsg = options.commitMsg || `New Version v${newVersion}`;
3374
+ this.syncGit(newVersion, commitMsg, options.syncNpm);
3375
+ }
3376
+ },
3377
+ v_minor(filename, options) {
3378
+ filename = typeof filename === "undefined" ? "VERSION" : filename;
3379
+ const versionString = this.getVersionStringFromFile(filename);
3380
+ const versionSuffix = this.parseVersionSuffix(versionString);
3381
+ const versionObject = this.parseVersionString(versionString);
3382
+ const major = parseInt(versionObject.major);
3383
+ const minor = parseInt(versionObject.minor);
3384
+ const patch = parseInt(versionObject.patch);
3385
+ const newVersion = this.buildNewVersionString({ major, minor: minor + 1, patch }, versionSuffix);
3386
+ this.saveNewVersionFile(filename, newVersion);
3387
+ if (options.syncGit) {
3388
+ var commitMsg = options.commitMsg || `New Version v${newVersion}`;
3389
+ this.syncGit(newVersion, commitMsg, options.syncNpm);
3390
+ }
3391
+ },
3392
+ v_patch(filename, options) {
3393
+ filename = typeof filename === "undefined" ? "VERSION" : filename;
3394
+ const versionString = this.getVersionStringFromFile(filename);
3395
+ const versionSuffix = this.parseVersionSuffix(versionString);
3396
+ const versionObject = this.parseVersionString(versionString);
3397
+ const major = parseInt(versionObject.major);
3398
+ const minor = parseInt(versionObject.minor);
3399
+ const patch = parseInt(versionObject.patch);
3400
+ const newVersion = this.buildNewVersionString({ major, minor, patch: patch + 1 }, versionSuffix);
3401
+ this.saveNewVersionFile(filename, newVersion);
3402
+ if (options.syncGit) {
3403
+ var commitMsg = options.commitMsg || `New Version v${newVersion}`;
3404
+ this.syncGit(newVersion, commitMsg, options.syncNpm);
3405
+ }
3406
+ },
3407
+ v_sync(filename, options) {
3408
+ filename = typeof filename === "undefined" ? "VERSION" : filename;
3409
+ var commandHandler2 = this;
3410
+ commandHandler2.switchCommander.shellCommands([
3411
+ "echo $(git describe)"
3412
+ ]).then(function(response) {
3413
+ const versionString = response[0].split("-")[0].slice(1).replace("\n", "");
3414
+ console.log(versionString);
3415
+ const versionSuffix = commandHandler2.parseVersionSuffix(versionString);
3416
+ const versionObject = commandHandler2.parseVersionString(versionString);
3417
+ const major = parseInt(versionObject.major);
3418
+ const minor = parseInt(versionObject.minor);
3419
+ const patch = parseInt(versionObject.patch);
3420
+ const newVersion = commandHandler2.buildNewVersionString({ major, minor, patch }, versionSuffix);
3421
+ commandHandler2.saveNewVersionFile(filename, newVersion);
3422
+ var commitMsg = options.commitMsg || `Synced Version v${newVersion}`;
3423
+ commandHandler2.switchCommander.shellCommands(
3424
+ [
3425
+ "git fetch --tags -f",
3426
+ `git add . && git commit -am "${commitMsg}"`,
3427
+ "git fetch origin --tags",
3428
+ "git tag -ln",
3429
+ `npm version "${newVersion}" --allow-same-version -m "${commitMsg}"`,
3430
+ "git push && git push --tags"
3431
+ ]
3432
+ ).then(function(response2) {
3433
+ console.log(response2);
3434
+ });
3435
+ });
3436
+ },
3437
+ v_changelog() {
3438
+ const commandHandler2 = this;
3439
+ commandHandler2.switchCommander.shellCommands(
3440
+ [
3441
+ "git tag -ln"
3442
+ ]
3443
+ ).then(function(response) {
3444
+ var versionTags = response[0].split("\n").map((tag) => tag.split(" ").unique()).unique().map(
3445
+ (tag) => {
3446
+ return {
3447
+ "version": tag[0],
3448
+ "major": tag[0].split(".")[0],
3449
+ "minor": tag[0].split(".")[0] + "." + tag[0].split(".")[1],
3450
+ "description": tag.slice(1).join(" ").trim()
3451
+ };
3452
+ }
3453
+ );
3454
+ var minorVersionTags = versionTags.filter((tag) => tag.version !== "").map((tag) => tag.version.split(".")[0] + "." + tag.version.split(".")[1]).unique();
3455
+ var history = minorVersionTags.map((minor) => {
3456
+ return {
3457
+ "major": minor.split(".")[0],
3458
+ "minor": minor,
3459
+ "history": "\n - " + versionTags.filter((tag) => tag.minor === minor).map(
3460
+ function(tag) {
3461
+ return tag.description;
3462
+ }
3463
+ ).filter((desc) => !desc.startsWith(minor.slice(1))).sort().unique().join("\n - ")
3464
+ };
3465
+ }).map((hist) => {
3466
+ return `## ${hist.major} -> ${hist.minor}
3467
+ ` + hist.history;
3468
+ }).join("\n");
3469
+ const subtitle = "This is an automatic Changelog history of versions generated using the command: **qcobjects v-changelog > CHANGELOG.md**";
3470
+ console.log("# Changelog \n\n" + subtitle + "\n\n" + history);
3471
+ });
3472
+ }
3473
+ };
3474
+ switchCommander.program.command("v-major [filename]").option("--git, --sync-git", "Sync with Git").option("--npm, --sync-npm", "Sync with NPM").option("-m, --commit-msg [message]", "Commit Message").description("Semantic Versioning: Upgrade to a new major version").action(function(args, options) {
3475
+ commandHandler.choiceOption.v_major.call(commandHandler, args, options);
3476
+ });
3477
+ switchCommander.program.command("v-minor [filename]").option("--git, --sync-git", "Sync with Git").option("--npm, --sync-npm", "Sync with NPM").option("-m, --commit-msg [message]", "Commit Message").description("Semantic Versioning: Upgrade to a new minor version").action(function(args, options) {
3478
+ commandHandler.choiceOption.v_minor.call(commandHandler, args, options);
3479
+ });
3480
+ switchCommander.program.command("v-patch [filename]").option("--git, --sync-git", "Sync with Git").option("--npm, --sync-npm", "Sync with NPM").option("-m, --commit-msg [message]", "Commit Message").description("Semantic Versioning: Upgrade to a new patch version").action(function(args, options) {
3481
+ commandHandler.choiceOption.v_patch.call(commandHandler, args, options);
3482
+ });
3483
+ switchCommander.program.command("v-sync [filename]").option("-m, --commit-msg [message]", "Commit Message").description("Semantic Versioning: Sync the version of NPM with version of GIT").action(function(args, options) {
3484
+ commandHandler.choiceOption.v_sync.call(commandHandler, args, options);
3485
+ });
3486
+ switchCommander.program.command("v-changelog").description("Semantic Versioning: Shows a changelog using Semantic Versioning").action(function(args, options) {
3487
+ commandHandler.choiceOption.v_changelog.call(commandHandler, args, options);
3488
+ });
3489
+ }
3490
+ syncGit(versionString, commitMsg, syncNpm = false) {
3491
+ let _commands_ = [];
3492
+ if (syncNpm) {
3493
+ _commands_ = _commands_.concat(
3494
+ [
3495
+ "git fetch --tags -f",
3496
+ `npm version "${versionString}" -m "${commitMsg}"`
3497
+ ]
3498
+ );
3499
+ }
3500
+ _commands_ = _commands_.concat(
3501
+ [
3502
+ `git add . && git commit -am "${commitMsg}"`,
3503
+ "git fetch origin --tags",
3504
+ "git tag -ln"
3505
+ ]
3506
+ );
3507
+ if (!syncNpm) {
3508
+ _commands_ = _commands_.concat(
3509
+ [
3510
+ `git tag -a "v${versionString}" -m "${commitMsg}"`
3511
+ ]
3512
+ );
3513
+ }
3514
+ _commands_ = _commands_.concat(
3515
+ [
3516
+ "git push && git push --tags"
3517
+ ]
3518
+ );
3519
+ this.switchCommander.shellCommands(_commands_).then(function(response) {
3520
+ logger4.info("Synced to Git");
3521
+ logger4.debug(response);
3522
+ }).catch(function(e) {
3523
+ logger4.info("Something went wrong trying to sync to git");
3524
+ logger4.debug(e);
3525
+ });
3526
+ }
3527
+ parseVersionString(versionString) {
3528
+ versionString = versionString.replace("\n", "");
3529
+ const regexpVer = /^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
3530
+ const versionObject = { ...versionString.match(regexpVer)?.groups };
3531
+ return versionObject;
3532
+ }
3533
+ getVersionStringFromFile(filename) {
3534
+ let versionString;
3535
+ try {
3536
+ versionString = fs.readFileSync(filename).toString().replace("\n", "");
3537
+ } catch (e) {
3538
+ versionString = "0.0.1";
3539
+ }
3540
+ return versionString;
3541
+ }
3542
+ buildNewSemVersionString({ major, minor, patch }) {
3543
+ return `${major}.${minor}.${patch}`;
3544
+ }
3545
+ parseVersionSuffix(versionString) {
3546
+ versionString = versionString.replace("\n", "");
3547
+ const versionObject = this.parseVersionString(versionString);
3548
+ const semVersionString = this.buildNewSemVersionString(versionObject);
3549
+ return versionString.replace(semVersionString, "");
3550
+ }
3551
+ buildNewVersionString({ major, minor, patch }, suffix) {
3552
+ const semVersionString = this.buildNewSemVersionString({ major, minor, patch });
3553
+ return `${semVersionString}${suffix}`;
3554
+ }
3555
+ saveNewVersionFile(filename, versionString) {
3556
+ fs.writeFileSync(filename, versionString);
3557
+ }
3558
+ };
3559
+ Package3("com.qcobjects.cli.commands.version", [
3560
+ CommandHandler
3561
+ ]);
3562
+
3563
+ // src/com.qcobjects.cli.commands.jira.client_services.ts
3564
+ var { Package: Package4, Service: Service2, logger: logger5 } = __require("qcobjects");
3565
+ var JiraCloud = class extends Service2 {
3566
+ static {
3567
+ __name(this, "JiraCloud");
3568
+ }
3569
+ constructor({
3570
+ name = "jira_cloud",
3571
+ external = true,
3572
+ useHTTP2 = true,
3573
+ cached = false,
3574
+ method = "POST",
3575
+ headers = {
3576
+ "accept": "application/json",
3577
+ "content-type": "application/json"
3578
+ },
3579
+ basePath = "",
3580
+ url = "",
3581
+ withCredentials = false
3582
+ }) {
3583
+ super({
3584
+ name,
3585
+ external,
3586
+ useHTTP2,
3587
+ cached,
3588
+ method,
3589
+ headers,
3590
+ basePath,
3591
+ url,
3592
+ withCredentials
3593
+ });
3594
+ var o = this;
3595
+ this.domain = `${o.domain}`;
3596
+ this.basePath = `https://${this.domain}/`;
3597
+ this.username_password = `${o.username}:${o.password}`;
3598
+ this.headers["authorization"] = `Basic ${Buffer.from(this.username_password).toString("base64")}`;
3599
+ this.url = this.basePath + o.apiMethod;
3600
+ this.data = o.data;
3601
+ }
3602
+ done(service, standardResponse) {
3603
+ logger5.debug(standardResponse);
3604
+ }
3605
+ fail(e) {
3606
+ logger5.debug(e);
3607
+ }
3608
+ };
3609
+ Package4("com.qcobjects.cli.commands.jira.client_services", [
3610
+ JiraCloud
3611
+ ]);
3612
+
3613
+ // src/com.qcobjects.cli.commands.jira.ts
3614
+ var path2 = __require("path");
3615
+ var absolutePath = path2.resolve(__dirname, "./");
3616
+ var {
3617
+ exec: exec2,
3618
+ execSync: execSync3
3619
+ } = __require("child_process");
3620
+ var { Package: Package5, InheritClass: InheritClass3, _DataStringify, New, CONFIG: CONFIG3, logger: logger6, serviceLoader } = __require("qcobjects");
3621
+ var CommandHandler2 = class extends InheritClass3 {
3622
+ static {
3623
+ __name(this, "CommandHandler");
3624
+ }
3625
+ constructor({
3626
+ switchCommander
3627
+ }) {
3628
+ super({ switchCommander });
3629
+ this.choiceOption = {
3630
+ issues: /* @__PURE__ */ __name(function() {
3631
+ this.getIssueList().then(function(response) {
3632
+ console.log(_DataStringify(response));
3633
+ }).catch((e) => {
3634
+ console.log(e);
3635
+ process.exit(1);
3636
+ });
3637
+ }, "issues")
3638
+ };
3639
+ const commandHandler = this;
3640
+ switchCommander.program.command("jira <subcommand>").option("-u, --from-user [username]", "User name").option("-fp,--from-project <projectName>", "Project name").option("-p, --pwd <password>", "Password").option("-f, --format <format>", "Format (json, table)").description(`Jira Integration:
3641
+ Sub-Commands can be:
3642
+ issues: To get the issues list from JIRA
3643
+ `).action(function(subcommand, options) {
3644
+ if (commandHandler.choiceOption.hasOwnProperty.call(commandHandler.choiceOption, subcommand)) {
3645
+ commandHandler.choiceOption[subcommand].call(commandHandler, subcommand, options);
3646
+ } else {
3647
+ console.error(`Sub-Command (jira ${subcommand}... ) is not available`);
3648
+ process.exit(1);
3649
+ }
3650
+ });
3651
+ }
3652
+ getIssueList() {
3653
+ return new Promise(function(resolve, reject) {
3654
+ logger6.info("I'm going to get the issue list from the jira cloud...");
3655
+ const jira_config = CONFIG3.get("jira", null);
3656
+ if (jira_config !== null) {
3657
+ const jira_username = jira_config.username;
3658
+ const jira_password = jira_config.auth_token;
3659
+ const jira_project = jira_config.project;
3660
+ const jira_domain = jira_config.domain;
3661
+ const jira_issue_fields = ["id", "key", "summary", "timetracking"];
3662
+ const cloudClient = New(JiraCloud, {
3663
+ domain: `${jira_domain}`,
3664
+ username: `${jira_username}`,
3665
+ password: `${jira_password}`,
3666
+ apiMethod: "rest/api/latest/search",
3667
+ data: {
3668
+ "jql": `project = ${jira_project}`,
3669
+ "startAt": 0,
3670
+ "maxResults": 5e3,
3671
+ "fields": jira_issue_fields
3672
+ }
3673
+ });
3674
+ try {
3675
+ } catch (e) {
3676
+ console.error("\u{1F926} Something went wrong \u{1F926} when trying to get jira issues from the cloud");
3677
+ reject(e);
3678
+ }
3679
+ } else {
3680
+ console.error("\u{1F926} Something went wrong \u{1F926} You need to set the jira config settings");
3681
+ reject(new Error("\u{1F926} Something went wrong \u{1F926} You need to set the jira config settings"));
3682
+ }
3683
+ });
3684
+ }
3685
+ };
3686
+ Package5("com.qcobjects.cli.commands.jira", [
3687
+ CommandHandler2
3688
+ ]);
3689
+
3690
+ // src/org.quickcorp.qcobjects.cli.ts
3691
+ var fs2 = __require("fs");
3692
+ var path3 = __require("path");
3693
+ var templatePwaPath = path3.resolve(__dirname, "./templates/pwa/") + "/";
3694
+ var { exec: exec3, execSync: execSync4 } = __require("child_process");
3695
+ __require("qcobjects");
3696
+ var { CONFIG: CONFIG4, findPackageNodePath: findPackageNodePath2, logger: logger7, Package: Package6, InheritClass: InheritClass4, New: New2, serviceLoader: serviceLoader2, global: global2, Service: Service3, Component } = __require("qcobjects");
3697
+ CONFIG4.set("node_modules_path", "./node_modules/");
3698
+ CONFIG4.set("qcobjectsnewapp_path", CONFIG4.get("node_modules_path") + "/qcobjectsnewapp");
3699
+ var getPluginCommandsList = /* @__PURE__ */ __name(() => {
3700
+ return global2.ClassesList.filter((c) => c.packageName.startsWith("com.qcobjects.cli.commands.")).filter((p) => p.classFactory.name.endsWith("CommandHandler"));
3701
+ }, "getPluginCommandsList");
3702
+ var SwitchCommander = class extends InheritClass4 {
3703
+ static {
3704
+ __name(this, "SwitchCommander");
3705
+ }
3706
+ choiceOption = {
3707
+ generateSw: /* @__PURE__ */ __name((_appName, options) => {
3708
+ const dirPrefix = options.dir;
3709
+ const switchCommander = this;
3710
+ const appName = typeof _appName === "undefined" || _appName === true ? "MyAppName" : _appName;
3711
+ switchCommander.generateServiceWorker(appName, dirPrefix).catch((e) => {
3712
+ logger7.warn(`An error ocurred while creating service worker: ${e}`);
3713
+ });
3714
+ }, "generateSw"),
3715
+ create: /* @__PURE__ */ __name((_appName, options) => {
3716
+ const version = __get_version__();
3717
+ const switchCommander = this;
3718
+ const appName = typeof _appName === "undefined" || _appName === true ? "MyAppName" : _appName;
3719
+ let appTemplateName;
3720
+ if (options.createAmp) {
3721
+ appTemplateName = "qcobjects-ecommerce-amp";
3722
+ } else if (options.createPwa) {
3723
+ appTemplateName = "qcobjectsnewapp";
3724
+ } else if (options.createPhp) {
3725
+ appTemplateName = "qcobjectsnewphp";
3726
+ } else if (options.createCustom) {
3727
+ appTemplateName = options.createCustom;
3728
+ } else {
3729
+ appTemplateName = "qcobjectsnewapp";
3730
+ }
3731
+ CONFIG4.set("qcobjectsnewapp_path", CONFIG4.get("node_modules_path") + "/" + appTemplateName);
3732
+ const _package_json_template_fname = path3.resolve(CONFIG4.get("qcobjectsnewapp_path", "qcobjectsnewapp"), "./package.json");
3733
+ const createAppCommand = "npm init -y";
3734
+ const _package_json_file = path3.resolve(CONFIG4.get("projectPath"), "./package.json");
3735
+ logger7.debug("_package_json_file: " + _package_json_file);
3736
+ logger7.debug(createAppCommand);
3737
+ exec3(createAppCommand, (err) => {
3738
+ if (err) {
3739
+ throw Error(err.message);
3740
+ process.exit(1);
3741
+ return;
3742
+ }
3743
+ exec3(`npm i --save-dev ${appTemplateName}`, () => {
3744
+ const _package_json_template_file = __require(_package_json_template_fname);
3745
+ _package_json_template_file.name = appName;
3746
+ _package_json_template_file.version = "1.0.0";
3747
+ _package_json_template_file.repository = {};
3748
+ fs2.writeFileSync(_package_json_file, JSON.stringify(_package_json_template_file, null, 4));
3749
+ logger7.info("Good! App Templates was installed!");
3750
+ console.log(`Starting to copy files from app template ${appTemplateName} to your project...`);
3751
+ switchCommander.copyTemplate(path3.resolve(findPackageNodePath2(appTemplateName), appTemplateName), path3.resolve(CONFIG4.get("projectPath"), "./")).then(() => {
3752
+ exec3("npm uninstall " + appTemplateName + " --save && npm cache verify", (err2) => {
3753
+ if (err2) {
3754
+ throw Error(err2.message);
3755
+ process.exit(1);
3756
+ return;
3757
+ }
3758
+ execSync4("npm install --save-dev qcobjects-cli ");
3759
+ });
3760
+ exec3("npm cache verify && npm i ", (err2) => {
3761
+ if (err2) {
3762
+ throw Error(err2.message);
3763
+ process.exit(1);
3764
+ return;
3765
+ }
3766
+ logger7.info("Good! Your application is done. You can play with QCObjects now!");
3767
+ logger7.info("I will create the SSL certificates now. It may take some time...");
3768
+ exec3("qcobjects-createcert", () => {
3769
+ logger7.info("Test certificates generated");
3770
+ const githubService = New2(Service3);
3771
+ githubService.url = "https://raw.githubusercontent.com/QuickCorp/QCObjects/main/.gitignore";
3772
+ githubService.headers = {
3773
+ Accept: "application/vnd.github+json",
3774
+ "X-GitHub-Api-Version": "2022-11-28",
3775
+ "User-Agent": "qcobjects-cli"
3776
+ };
3777
+ githubService.done = () => {
3778
+ };
3779
+ serviceLoader2(githubService).then(({ service }) => {
3780
+ fs2.writeFileSync(path3.resolve(CONFIG4.get("projectPath"), "./.gitignore"), service.template);
3781
+ try {
3782
+ execSync4("git init");
3783
+ logger7.debug("Git initialized.");
3784
+ } catch (e) {
3785
+ logger7.debug("Could not initialize git.");
3786
+ }
3787
+ });
3788
+ }).stdout.on("data", function(data) {
3789
+ console.log(data);
3790
+ });
3791
+ }).stdout.on("data", function(data) {
3792
+ console.log(data);
3793
+ });
3794
+ }).catch((e) => {
3795
+ console.log(e);
3796
+ });
3797
+ }).stdout.on("data", function(data) {
3798
+ console.log(data);
3799
+ });
3800
+ }).stdout.on("data", function() {
3801
+ console.log("App generation started...");
3802
+ });
3803
+ }, "create"),
3804
+ publish(_appName, _options) {
3805
+ logger7.debug("publish is not yet implemented");
3806
+ },
3807
+ upgradeToEnterprise(_appName, _options) {
3808
+ const switchCommander = this;
3809
+ QCObjectsEnterprise.upgrade(switchCommander);
3810
+ }
3811
+ };
3812
+ constructor() {
3813
+ super();
3814
+ this.program = require_commander();
3815
+ }
3816
+ shellCommands(_shell_commands) {
3817
+ return new Promise(function(resolve_all, reject_all) {
3818
+ var _promises_set = _shell_commands.map(
3819
+ function(shell_command) {
3820
+ return new Promise(
3821
+ function(resolve, reject) {
3822
+ logger7.debug(shell_command);
3823
+ exec3(shell_command, (err, stdout, stderr) => {
3824
+ if (!err) {
3825
+ resolve(stdout);
3826
+ } else {
3827
+ logger7.debug(`[FAILED]: ${shell_command}`);
3828
+ logger7.debug(`${stderr}`);
3829
+ reject(stderr);
3830
+ }
3831
+ }).stdout.on("data", function(data) {
3832
+ logger7.info(data);
3833
+ });
3834
+ }
3835
+ ).catch((e) => reject_all(e));
3836
+ }
3837
+ );
3838
+ }).catch((e) => console.log(e));
3839
+ }
3840
+ fileListRecursive(dir) {
3841
+ var instance = this;
3842
+ return fs2.statSync(dir).isDirectory() ? Array.prototype.concat(...fs2.readdirSync(dir).map((f) => instance.fileListRecursive(path3.join(dir, f)))).filter((f) => {
3843
+ return !f.startsWith(".git") && f.lastIndexOf(".DS_Store") == -1;
3844
+ }) : dir;
3845
+ }
3846
+ register(email2, phonenumber) {
3847
+ return new Promise(function(resolve, reject) {
3848
+ logger7.info("I'm going to register your profile on the cloud...");
3849
+ const cloudClient = New2(QuickCorpCloud, {
3850
+ apiMethod: "register",
3851
+ data: { email: email2, phonenumber }
3852
+ });
3853
+ try {
3854
+ } catch (e) {
3855
+ console.log("\u{1F926} Something went wrong \u{1F926} when trying to register you in the cloud");
3856
+ reject(e);
3857
+ }
3858
+ });
3859
+ }
3860
+ generateServiceWorker(appName, dirPrefix = "./") {
3861
+ const writeContent = /* @__PURE__ */ __name((component) => {
3862
+ const parsedText = component.parseTemplate(component.template);
3863
+ logger7.debug("Starting to write the sw file...");
3864
+ fs2.writeFile(`${dirPrefix}/sw.js`, parsedText, (err) => {
3865
+ if (err) {
3866
+ throw Error(err);
3867
+ }
3868
+ logger7.info("Service Worker Generated");
3869
+ console.log("");
3870
+ console.log("Now simply put:");
3871
+ console.log("CONFIG.set('serviceWorkerURI','/sw.js');");
3872
+ console.log(" In your init.js file ");
3873
+ console.log("");
3874
+ console.log("To start your app in a local server ");
3875
+ console.log("Execute the command: ");
3876
+ console.log("> qcobjects launch <appname>");
3877
+ console.log("");
3878
+ });
3879
+ }, "writeContent");
3880
+ class ServiceWorkerComponent extends Component {
3881
+ static {
3882
+ __name(this, "ServiceWorkerComponent");
3883
+ }
3884
+ cached = false;
3885
+ templateURI = "sw.js";
3886
+ basePath = templatePwaPath;
3887
+ name = "sw";
3888
+ tplsource = "default";
3889
+ template = "";
3890
+ constructor({ name, data }) {
3891
+ super({ name, data });
3892
+ }
3893
+ done({ request, component }) {
3894
+ super.done({ request, component });
3895
+ writeContent(component);
3896
+ }
3897
+ }
3898
+ return new Promise(() => {
3899
+ var filelist = ["/"].concat(this.fileListRecursive(`${dirPrefix}`));
3900
+ if (typeof dirPrefix !== "undefined" && dirPrefix !== "./" && dirPrefix !== ".") {
3901
+ filelist = filelist.map((f) => f.replace(new RegExp(`${dirPrefix}/`), ""));
3902
+ }
3903
+ filelist = filelist.filter(function(fl) {
3904
+ return fl !== "sw.js" && !fl.startsWith("node_modules/");
3905
+ });
3906
+ filelist = filelist.filter((fname) => !fname.endsWith(".pem"));
3907
+ filelist = filelist.filter((fname) => !fname.endsWith(".sh"));
3908
+ filelist = filelist.filter((fname) => !new RegExp("^package(.*).json$").test(fname));
3909
+ filelist = filelist.filter((fname) => !fname.startsWith("."));
3910
+ var fileListString = '\n "' + filelist.join('",\n "') + '"';
3911
+ const component = new ServiceWorkerComponent({
3912
+ name: "sw",
3913
+ data: {
3914
+ appName,
3915
+ appVersion: "1.0.0",
3916
+ filelist: fileListString
3917
+ }
3918
+ });
3919
+ setTimeout(() => {
3920
+ component.done({ request: null, component });
3921
+ }, 1e3);
3922
+ });
3923
+ }
3924
+ copyTemplate(source, dest) {
3925
+ return new Promise((resolve, reject) => {
3926
+ const copyDir = /* @__PURE__ */ __name((source2, dest2, exclude) => {
3927
+ source2 = path3.resolve(source2);
3928
+ dest2 = path3.resolve(dest2);
3929
+ const dname = path3.basename(source2);
3930
+ const dirExcluded = exclude.includes(dname);
3931
+ const isDir = /* @__PURE__ */ __name((d) => {
3932
+ return fs2.existsSync(d) && fs2.statSync(d).isDirectory() ? true : false;
3933
+ }, "isDir");
3934
+ const isFile = /* @__PURE__ */ __name((d) => {
3935
+ return fs2.existsSync(d) && fs2.statSync(d).isFile() ? true : false;
3936
+ }, "isFile");
3937
+ if (isDir(source2) && !dirExcluded) {
3938
+ fs2.mkdirSync(dest2, { recursive: true });
3939
+ const paths = fs2.readdirSync(source2, { withFileTypes: true });
3940
+ const dirs = paths.filter((d) => d.isDirectory());
3941
+ const files = paths.filter((f) => f.isFile());
3942
+ ((paths2, dirs2, files2, exclude2) => {
3943
+ files2.map((f) => {
3944
+ const sourceFile = path3.resolve(source2, f.name);
3945
+ const destFile = path3.resolve(dest2, f.name);
3946
+ const fileExcluded = exclude2.includes(f.name);
3947
+ if (isFile(sourceFile) && !fileExcluded) {
3948
+ logger7.debug(`[publish:static] Copying files from ${sourceFile} to ${destFile} excluding ${exclude2.join(",")}...`);
3949
+ fs2.copyFileSync(sourceFile, destFile);
3950
+ logger7.debug(`[publish:static] Copying files from ${sourceFile} to ${destFile} excluding ${exclude2.join(",")}...DONE!`);
3951
+ }
3952
+ });
3953
+ dirs2.map((d) => {
3954
+ const sourceDir = path3.resolve(source2, d.name);
3955
+ const destDir = path3.resolve(dest2, d.name);
3956
+ copyDir(sourceDir, destDir, exclude2);
3957
+ });
3958
+ })(paths, dirs, files, exclude);
3959
+ }
3960
+ }, "copyDir");
3961
+ try {
3962
+ const exclude = [
3963
+ "package.json",
3964
+ "node_modules",
3965
+ ".DS_Store"
3966
+ ];
3967
+ logger7.info(`[create] Copying files from ${source} to ${dest} excluding ${exclude.join(",")}...`);
3968
+ copyDir(source, dest, typeof exclude !== "undefined" ? exclude : []);
3969
+ resolve();
3970
+ } catch (e) {
3971
+ logger7.warn(`Something went wrong trying to publish static files: ${e.message}`);
3972
+ reject(e);
3973
+ }
3974
+ });
3975
+ }
3976
+ initCommand() {
3977
+ const switchCommander = this;
3978
+ if (process.argv.length > 1) {
3979
+ logger7.debug("Installing Commands...");
3980
+ switchCommander.program.version(__get_version_string__());
3981
+ 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) {
3982
+ switchCommander.choiceOption.create.call(switchCommander, args, options);
3983
+ });
3984
+ try {
3985
+ logger7.debug("Loading Plugin Commands...");
3986
+ const importPluginCommands = /* @__PURE__ */ __name(function(switchCommander2) {
3987
+ return getPluginCommandsList().map((pluginCommand) => {
3988
+ try {
3989
+ logger7.debug(`Loading plugin ${pluginCommand.packageName}`);
3990
+ const classFactory = pluginCommand.classFactory;
3991
+ pluginCommand.plugin = new classFactory({ switchCommander: switchCommander2 });
3992
+ } catch (e) {
3993
+ throw Error(`Something went wrong loading ${pluginCommand.packageName}`);
3994
+ }
3995
+ return pluginCommand;
3996
+ });
3997
+ }, "importPluginCommands");
3998
+ importPluginCommands(switchCommander);
3999
+ } catch (e) {
4000
+ throw Error(`Something went wrong loading plugins: ${e.message}`);
4001
+ }
4002
+ 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) => {
4003
+ switchCommander.choiceOption.publish.bind(switchCommander)(args, options);
4004
+ });
4005
+ switchCommander.program.command("upgrade-to-enterprise").description("Upgrades to QCObjects Enterprise Edition").action(function(args, options) {
4006
+ switchCommander.choiceOption.upgradeToEnterprise.call(switchCommander, args, options);
4007
+ });
4008
+ 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) {
4009
+ switchCommander.choiceOption.generateSw.call(switchCommander, args, options);
4010
+ });
4011
+ switchCommander.program.command("launch <appname>").description("Launches the application").action(function() {
4012
+ logger7.info("Launching...");
4013
+ setTimeout(() => {
4014
+ logger7.info("Go to the browser and open https://localhost ");
4015
+ logger7.info("Press Ctrl-C to stop serving ");
4016
+ exec3("qcobjects-server", () => {
4017
+ }).stdout.on("data", function(data) {
4018
+ console.log(data);
4019
+ });
4020
+ }, 5e3);
4021
+ });
4022
+ switchCommander.program.on("--help", function() {
4023
+ console.log("");
4024
+ console.log("Use:");
4025
+ console.log(" $ qcobjects-cli [command] --help");
4026
+ console.log(" For detailed information of a command ");
4027
+ console.log("");
4028
+ process.exit(0);
4029
+ });
4030
+ switchCommander.program.on("command:*", function() {
4031
+ console.error("Invalid command: %s\nSee --help for a list of available commands.", switchCommander.program.args.join(" "));
4032
+ process.exit(1);
4033
+ });
4034
+ switchCommander.program.parse(process.argv);
4035
+ } else {
4036
+ console.log("");
4037
+ console.log("Use:");
4038
+ console.log(" $ qcobjects-cli [command] --help");
4039
+ console.log(" For detailed information of a command ");
4040
+ console.log("");
4041
+ process.exit(0);
4042
+ }
4043
+ }
4044
+ };
4045
+ Package6("org.quickcorp.qcobjects.cli", [
4046
+ SwitchCommander
4047
+ ]);
4048
+ global2.SwitchCommander = SwitchCommander;
4049
+
4050
+ // src/qcobjects-cli.ts
4051
+ var path4 = __require("path");
4052
+ var absolutePath2 = path4.resolve(__dirname, "./");
4053
+ var templatePath = path4.resolve(__dirname, "./templates/apps/") + "/";
4054
+ var package_config = __require(path4.resolve(process.cwd(), "package.json"));
4055
+ var { logger: logger8, InheritClass: InheritClass5 } = __require("qcobjects");
4056
+ logger8.debugEnabled = false;
25
4057
  var welcometo = "Welcome to \n";
26
4058
  var instructions = `
27
4059
  Community Edition
@@ -50,12 +4082,10 @@ if (process.argv.length < 3 || process.argv[2] === "create") {
50
4082
  console.log(logo);
51
4083
  console.log(instructions);
52
4084
  }
53
- logger.debugEnabled = false;
54
- logger.warnEnabled = false;
55
- logger.infoEnabled = false;
56
- __require(absolutePath + "/org.quickcorp.qcobjects.defaultsettings.js");
57
- var { SwitchCommander } = __require(absolutePath + "/org.quickcorp.qcobjects.cli");
58
- var Main = class extends InheritClass {
4085
+ logger8.debugEnabled = false;
4086
+ logger8.warnEnabled = false;
4087
+ logger8.infoEnabled = false;
4088
+ var Main = class extends InheritClass5 {
59
4089
  static {
60
4090
  __name(this, "Main");
61
4091
  }
@@ -64,7 +4094,7 @@ var Main = class extends InheritClass {
64
4094
  const main = this;
65
4095
  const switchCommander = new SwitchCommander();
66
4096
  switchCommander.initCommand();
67
- logger.debug("initialized");
4097
+ logger8.debug("initialized");
68
4098
  }
69
4099
  };
70
4100
  var __main__ = new Main();