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