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