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