@xaendar/cli 0.2.0

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 (3) hide show
  1. package/index.js +4842 -0
  2. package/index.js.map +1 -0
  3. package/package.json +14 -0
package/index.js ADDED
@@ -0,0 +1,4842 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a2, b) => (typeof require !== "undefined" ? require : a2)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // ../node_modules/commander/lib/error.js
35
+ var require_error = __commonJS({
36
+ "../node_modules/commander/lib/error.js"(exports) {
37
+ var CommanderError2 = class extends Error {
38
+ /**
39
+ * Constructs the CommanderError class
40
+ * @param {number} exitCode suggested exit code which could be used with process.exit
41
+ * @param {string} code an id string representing the error
42
+ * @param {string} message human-readable description of the error
43
+ */
44
+ constructor(exitCode, code, message) {
45
+ super(message);
46
+ Error.captureStackTrace(this, this.constructor);
47
+ this.name = this.constructor.name;
48
+ this.code = code;
49
+ this.exitCode = exitCode;
50
+ this.nestedError = void 0;
51
+ }
52
+ };
53
+ var InvalidArgumentError2 = class extends CommanderError2 {
54
+ /**
55
+ * Constructs the InvalidArgumentError class
56
+ * @param {string} [message] explanation of why argument is invalid
57
+ */
58
+ constructor(message) {
59
+ super(1, "commander.invalidArgument", message);
60
+ Error.captureStackTrace(this, this.constructor);
61
+ this.name = this.constructor.name;
62
+ }
63
+ };
64
+ exports.CommanderError = CommanderError2;
65
+ exports.InvalidArgumentError = InvalidArgumentError2;
66
+ }
67
+ });
68
+
69
+ // ../node_modules/commander/lib/argument.js
70
+ var require_argument = __commonJS({
71
+ "../node_modules/commander/lib/argument.js"(exports) {
72
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
73
+ var Argument2 = class {
74
+ /**
75
+ * Initialize a new command argument with the given name and description.
76
+ * The default is that the argument is required, and you can explicitly
77
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
78
+ *
79
+ * @param {string} name
80
+ * @param {string} [description]
81
+ */
82
+ constructor(name, description) {
83
+ this.description = description || "";
84
+ this.variadic = false;
85
+ this.parseArg = void 0;
86
+ this.defaultValue = void 0;
87
+ this.defaultValueDescription = void 0;
88
+ this.argChoices = void 0;
89
+ switch (name[0]) {
90
+ case "<":
91
+ this.required = true;
92
+ this._name = name.slice(1, -1);
93
+ break;
94
+ case "[":
95
+ this.required = false;
96
+ this._name = name.slice(1, -1);
97
+ break;
98
+ default:
99
+ this.required = true;
100
+ this._name = name;
101
+ break;
102
+ }
103
+ if (this._name.endsWith("...")) {
104
+ this.variadic = true;
105
+ this._name = this._name.slice(0, -3);
106
+ }
107
+ }
108
+ /**
109
+ * Return argument name.
110
+ *
111
+ * @return {string}
112
+ */
113
+ name() {
114
+ return this._name;
115
+ }
116
+ /**
117
+ * @package
118
+ */
119
+ _collectValue(value, previous) {
120
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
121
+ return [value];
122
+ }
123
+ previous.push(value);
124
+ return previous;
125
+ }
126
+ /**
127
+ * Set the default value, and optionally supply the description to be displayed in the help.
128
+ *
129
+ * @param {*} value
130
+ * @param {string} [description]
131
+ * @return {Argument}
132
+ */
133
+ default(value, description) {
134
+ this.defaultValue = value;
135
+ this.defaultValueDescription = description;
136
+ return this;
137
+ }
138
+ /**
139
+ * Set the custom handler for processing CLI command arguments into argument values.
140
+ *
141
+ * @param {Function} [fn]
142
+ * @return {Argument}
143
+ */
144
+ argParser(fn) {
145
+ this.parseArg = fn;
146
+ return this;
147
+ }
148
+ /**
149
+ * Only allow argument value to be one of choices.
150
+ *
151
+ * @param {string[]} values
152
+ * @return {Argument}
153
+ */
154
+ choices(values) {
155
+ this.argChoices = values.slice();
156
+ this.parseArg = (arg, previous) => {
157
+ if (!this.argChoices.includes(arg)) {
158
+ throw new InvalidArgumentError2(
159
+ `Allowed choices are ${this.argChoices.join(", ")}.`
160
+ );
161
+ }
162
+ if (this.variadic) {
163
+ return this._collectValue(arg, previous);
164
+ }
165
+ return arg;
166
+ };
167
+ return this;
168
+ }
169
+ /**
170
+ * Make argument required.
171
+ *
172
+ * @returns {Argument}
173
+ */
174
+ argRequired() {
175
+ this.required = true;
176
+ return this;
177
+ }
178
+ /**
179
+ * Make argument optional.
180
+ *
181
+ * @returns {Argument}
182
+ */
183
+ argOptional() {
184
+ this.required = false;
185
+ return this;
186
+ }
187
+ };
188
+ function humanReadableArgName(arg) {
189
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
190
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
191
+ }
192
+ exports.Argument = Argument2;
193
+ exports.humanReadableArgName = humanReadableArgName;
194
+ }
195
+ });
196
+
197
+ // ../node_modules/commander/lib/help.js
198
+ var require_help = __commonJS({
199
+ "../node_modules/commander/lib/help.js"(exports) {
200
+ var { humanReadableArgName } = require_argument();
201
+ var Help2 = class {
202
+ constructor() {
203
+ this.helpWidth = void 0;
204
+ this.minWidthToWrap = 40;
205
+ this.sortSubcommands = false;
206
+ this.sortOptions = false;
207
+ this.showGlobalOptions = false;
208
+ }
209
+ /**
210
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
211
+ * and just before calling `formatHelp()`.
212
+ *
213
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
214
+ *
215
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
216
+ */
217
+ prepareContext(contextOptions) {
218
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
219
+ }
220
+ /**
221
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
222
+ *
223
+ * @param {Command} cmd
224
+ * @returns {Command[]}
225
+ */
226
+ visibleCommands(cmd) {
227
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
228
+ const helpCommand = cmd._getHelpCommand();
229
+ if (helpCommand && !helpCommand._hidden) {
230
+ visibleCommands.push(helpCommand);
231
+ }
232
+ if (this.sortSubcommands) {
233
+ visibleCommands.sort((a2, b) => {
234
+ return a2.name().localeCompare(b.name());
235
+ });
236
+ }
237
+ return visibleCommands;
238
+ }
239
+ /**
240
+ * Compare options for sort.
241
+ *
242
+ * @param {Option} a
243
+ * @param {Option} b
244
+ * @returns {number}
245
+ */
246
+ compareOptions(a2, b) {
247
+ const getSortKey = (option) => {
248
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
249
+ };
250
+ return getSortKey(a2).localeCompare(getSortKey(b));
251
+ }
252
+ /**
253
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
254
+ *
255
+ * @param {Command} cmd
256
+ * @returns {Option[]}
257
+ */
258
+ visibleOptions(cmd) {
259
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
260
+ const helpOption = cmd._getHelpOption();
261
+ if (helpOption && !helpOption.hidden) {
262
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
263
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
264
+ if (!removeShort && !removeLong) {
265
+ visibleOptions.push(helpOption);
266
+ } else if (helpOption.long && !removeLong) {
267
+ visibleOptions.push(
268
+ cmd.createOption(helpOption.long, helpOption.description)
269
+ );
270
+ } else if (helpOption.short && !removeShort) {
271
+ visibleOptions.push(
272
+ cmd.createOption(helpOption.short, helpOption.description)
273
+ );
274
+ }
275
+ }
276
+ if (this.sortOptions) {
277
+ visibleOptions.sort(this.compareOptions);
278
+ }
279
+ return visibleOptions;
280
+ }
281
+ /**
282
+ * Get an array of the visible global options. (Not including help.)
283
+ *
284
+ * @param {Command} cmd
285
+ * @returns {Option[]}
286
+ */
287
+ visibleGlobalOptions(cmd) {
288
+ if (!this.showGlobalOptions) return [];
289
+ const globalOptions = [];
290
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
291
+ const visibleOptions = ancestorCmd.options.filter(
292
+ (option) => !option.hidden
293
+ );
294
+ globalOptions.push(...visibleOptions);
295
+ }
296
+ if (this.sortOptions) {
297
+ globalOptions.sort(this.compareOptions);
298
+ }
299
+ return globalOptions;
300
+ }
301
+ /**
302
+ * Get an array of the arguments if any have a description.
303
+ *
304
+ * @param {Command} cmd
305
+ * @returns {Argument[]}
306
+ */
307
+ visibleArguments(cmd) {
308
+ if (cmd._argsDescription) {
309
+ cmd.registeredArguments.forEach((argument) => {
310
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
311
+ });
312
+ }
313
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
314
+ return cmd.registeredArguments;
315
+ }
316
+ return [];
317
+ }
318
+ /**
319
+ * Get the command term to show in the list of subcommands.
320
+ *
321
+ * @param {Command} cmd
322
+ * @returns {string}
323
+ */
324
+ subcommandTerm(cmd) {
325
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
326
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
327
+ (args ? " " + args : "");
328
+ }
329
+ /**
330
+ * Get the option term to show in the list of options.
331
+ *
332
+ * @param {Option} option
333
+ * @returns {string}
334
+ */
335
+ optionTerm(option) {
336
+ return option.flags;
337
+ }
338
+ /**
339
+ * Get the argument term to show in the list of arguments.
340
+ *
341
+ * @param {Argument} argument
342
+ * @returns {string}
343
+ */
344
+ argumentTerm(argument) {
345
+ return argument.name();
346
+ }
347
+ /**
348
+ * Get the longest command term length.
349
+ *
350
+ * @param {Command} cmd
351
+ * @param {Help} helper
352
+ * @returns {number}
353
+ */
354
+ longestSubcommandTermLength(cmd, helper) {
355
+ return helper.visibleCommands(cmd).reduce((max, command) => {
356
+ return Math.max(
357
+ max,
358
+ this.displayWidth(
359
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
360
+ )
361
+ );
362
+ }, 0);
363
+ }
364
+ /**
365
+ * Get the longest option term length.
366
+ *
367
+ * @param {Command} cmd
368
+ * @param {Help} helper
369
+ * @returns {number}
370
+ */
371
+ longestOptionTermLength(cmd, helper) {
372
+ return helper.visibleOptions(cmd).reduce((max, option) => {
373
+ return Math.max(
374
+ max,
375
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
376
+ );
377
+ }, 0);
378
+ }
379
+ /**
380
+ * Get the longest global option term length.
381
+ *
382
+ * @param {Command} cmd
383
+ * @param {Help} helper
384
+ * @returns {number}
385
+ */
386
+ longestGlobalOptionTermLength(cmd, helper) {
387
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
388
+ return Math.max(
389
+ max,
390
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
391
+ );
392
+ }, 0);
393
+ }
394
+ /**
395
+ * Get the longest argument term length.
396
+ *
397
+ * @param {Command} cmd
398
+ * @param {Help} helper
399
+ * @returns {number}
400
+ */
401
+ longestArgumentTermLength(cmd, helper) {
402
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
403
+ return Math.max(
404
+ max,
405
+ this.displayWidth(
406
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
407
+ )
408
+ );
409
+ }, 0);
410
+ }
411
+ /**
412
+ * Get the command usage to be displayed at the top of the built-in help.
413
+ *
414
+ * @param {Command} cmd
415
+ * @returns {string}
416
+ */
417
+ commandUsage(cmd) {
418
+ let cmdName = cmd._name;
419
+ if (cmd._aliases[0]) {
420
+ cmdName = cmdName + "|" + cmd._aliases[0];
421
+ }
422
+ let ancestorCmdNames = "";
423
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
424
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
425
+ }
426
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
427
+ }
428
+ /**
429
+ * Get the description for the command.
430
+ *
431
+ * @param {Command} cmd
432
+ * @returns {string}
433
+ */
434
+ commandDescription(cmd) {
435
+ return cmd.description();
436
+ }
437
+ /**
438
+ * Get the subcommand summary to show in the list of subcommands.
439
+ * (Fallback to description for backwards compatibility.)
440
+ *
441
+ * @param {Command} cmd
442
+ * @returns {string}
443
+ */
444
+ subcommandDescription(cmd) {
445
+ return cmd.summary() || cmd.description();
446
+ }
447
+ /**
448
+ * Get the option description to show in the list of options.
449
+ *
450
+ * @param {Option} option
451
+ * @return {string}
452
+ */
453
+ optionDescription(option) {
454
+ const extraInfo = [];
455
+ if (option.argChoices) {
456
+ extraInfo.push(
457
+ // use stringify to match the display of the default value
458
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
459
+ );
460
+ }
461
+ if (option.defaultValue !== void 0) {
462
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
463
+ if (showDefault) {
464
+ extraInfo.push(
465
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
466
+ );
467
+ }
468
+ }
469
+ if (option.presetArg !== void 0 && option.optional) {
470
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
471
+ }
472
+ if (option.envVar !== void 0) {
473
+ extraInfo.push(`env: ${option.envVar}`);
474
+ }
475
+ if (extraInfo.length > 0) {
476
+ const extraDescription = `(${extraInfo.join(", ")})`;
477
+ if (option.description) {
478
+ return `${option.description} ${extraDescription}`;
479
+ }
480
+ return extraDescription;
481
+ }
482
+ return option.description;
483
+ }
484
+ /**
485
+ * Get the argument description to show in the list of arguments.
486
+ *
487
+ * @param {Argument} argument
488
+ * @return {string}
489
+ */
490
+ argumentDescription(argument) {
491
+ const extraInfo = [];
492
+ if (argument.argChoices) {
493
+ extraInfo.push(
494
+ // use stringify to match the display of the default value
495
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
496
+ );
497
+ }
498
+ if (argument.defaultValue !== void 0) {
499
+ extraInfo.push(
500
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
501
+ );
502
+ }
503
+ if (extraInfo.length > 0) {
504
+ const extraDescription = `(${extraInfo.join(", ")})`;
505
+ if (argument.description) {
506
+ return `${argument.description} ${extraDescription}`;
507
+ }
508
+ return extraDescription;
509
+ }
510
+ return argument.description;
511
+ }
512
+ /**
513
+ * Format a list of items, given a heading and an array of formatted items.
514
+ *
515
+ * @param {string} heading
516
+ * @param {string[]} items
517
+ * @param {Help} helper
518
+ * @returns string[]
519
+ */
520
+ formatItemList(heading, items, helper) {
521
+ if (items.length === 0) return [];
522
+ return [helper.styleTitle(heading), ...items, ""];
523
+ }
524
+ /**
525
+ * Group items by their help group heading.
526
+ *
527
+ * @param {Command[] | Option[]} unsortedItems
528
+ * @param {Command[] | Option[]} visibleItems
529
+ * @param {Function} getGroup
530
+ * @returns {Map<string, Command[] | Option[]>}
531
+ */
532
+ groupItems(unsortedItems, visibleItems, getGroup) {
533
+ const result = /* @__PURE__ */ new Map();
534
+ unsortedItems.forEach((item) => {
535
+ const group = getGroup(item);
536
+ if (!result.has(group)) result.set(group, []);
537
+ });
538
+ visibleItems.forEach((item) => {
539
+ const group = getGroup(item);
540
+ if (!result.has(group)) {
541
+ result.set(group, []);
542
+ }
543
+ result.get(group).push(item);
544
+ });
545
+ return result;
546
+ }
547
+ /**
548
+ * Generate the built-in help text.
549
+ *
550
+ * @param {Command} cmd
551
+ * @param {Help} helper
552
+ * @returns {string}
553
+ */
554
+ formatHelp(cmd, helper) {
555
+ const termWidth = helper.padWidth(cmd, helper);
556
+ const helpWidth = helper.helpWidth ?? 80;
557
+ function callFormatItem(term, description) {
558
+ return helper.formatItem(term, termWidth, description, helper);
559
+ }
560
+ let output = [
561
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
562
+ ""
563
+ ];
564
+ const commandDescription = helper.commandDescription(cmd);
565
+ if (commandDescription.length > 0) {
566
+ output = output.concat([
567
+ helper.boxWrap(
568
+ helper.styleCommandDescription(commandDescription),
569
+ helpWidth
570
+ ),
571
+ ""
572
+ ]);
573
+ }
574
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
575
+ return callFormatItem(
576
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
577
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
578
+ );
579
+ });
580
+ output = output.concat(
581
+ this.formatItemList("Arguments:", argumentList, helper)
582
+ );
583
+ const optionGroups = this.groupItems(
584
+ cmd.options,
585
+ helper.visibleOptions(cmd),
586
+ (option) => option.helpGroupHeading ?? "Options:"
587
+ );
588
+ optionGroups.forEach((options, group) => {
589
+ const optionList = options.map((option) => {
590
+ return callFormatItem(
591
+ helper.styleOptionTerm(helper.optionTerm(option)),
592
+ helper.styleOptionDescription(helper.optionDescription(option))
593
+ );
594
+ });
595
+ output = output.concat(this.formatItemList(group, optionList, helper));
596
+ });
597
+ if (helper.showGlobalOptions) {
598
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
599
+ return callFormatItem(
600
+ helper.styleOptionTerm(helper.optionTerm(option)),
601
+ helper.styleOptionDescription(helper.optionDescription(option))
602
+ );
603
+ });
604
+ output = output.concat(
605
+ this.formatItemList("Global Options:", globalOptionList, helper)
606
+ );
607
+ }
608
+ const commandGroups = this.groupItems(
609
+ cmd.commands,
610
+ helper.visibleCommands(cmd),
611
+ (sub) => sub.helpGroup() || "Commands:"
612
+ );
613
+ commandGroups.forEach((commands, group) => {
614
+ const commandList = commands.map((sub) => {
615
+ return callFormatItem(
616
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
617
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
618
+ );
619
+ });
620
+ output = output.concat(this.formatItemList(group, commandList, helper));
621
+ });
622
+ return output.join("\n");
623
+ }
624
+ /**
625
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
626
+ *
627
+ * @param {string} str
628
+ * @returns {number}
629
+ */
630
+ displayWidth(str) {
631
+ return stripColor(str).length;
632
+ }
633
+ /**
634
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
635
+ *
636
+ * @param {string} str
637
+ * @returns {string}
638
+ */
639
+ styleTitle(str) {
640
+ return str;
641
+ }
642
+ styleUsage(str) {
643
+ return str.split(" ").map((word) => {
644
+ if (word === "[options]") return this.styleOptionText(word);
645
+ if (word === "[command]") return this.styleSubcommandText(word);
646
+ if (word[0] === "[" || word[0] === "<")
647
+ return this.styleArgumentText(word);
648
+ return this.styleCommandText(word);
649
+ }).join(" ");
650
+ }
651
+ styleCommandDescription(str) {
652
+ return this.styleDescriptionText(str);
653
+ }
654
+ styleOptionDescription(str) {
655
+ return this.styleDescriptionText(str);
656
+ }
657
+ styleSubcommandDescription(str) {
658
+ return this.styleDescriptionText(str);
659
+ }
660
+ styleArgumentDescription(str) {
661
+ return this.styleDescriptionText(str);
662
+ }
663
+ styleDescriptionText(str) {
664
+ return str;
665
+ }
666
+ styleOptionTerm(str) {
667
+ return this.styleOptionText(str);
668
+ }
669
+ styleSubcommandTerm(str) {
670
+ return str.split(" ").map((word) => {
671
+ if (word === "[options]") return this.styleOptionText(word);
672
+ if (word[0] === "[" || word[0] === "<")
673
+ return this.styleArgumentText(word);
674
+ return this.styleSubcommandText(word);
675
+ }).join(" ");
676
+ }
677
+ styleArgumentTerm(str) {
678
+ return this.styleArgumentText(str);
679
+ }
680
+ styleOptionText(str) {
681
+ return str;
682
+ }
683
+ styleArgumentText(str) {
684
+ return str;
685
+ }
686
+ styleSubcommandText(str) {
687
+ return str;
688
+ }
689
+ styleCommandText(str) {
690
+ return str;
691
+ }
692
+ /**
693
+ * Calculate the pad width from the maximum term length.
694
+ *
695
+ * @param {Command} cmd
696
+ * @param {Help} helper
697
+ * @returns {number}
698
+ */
699
+ padWidth(cmd, helper) {
700
+ return Math.max(
701
+ helper.longestOptionTermLength(cmd, helper),
702
+ helper.longestGlobalOptionTermLength(cmd, helper),
703
+ helper.longestSubcommandTermLength(cmd, helper),
704
+ helper.longestArgumentTermLength(cmd, helper)
705
+ );
706
+ }
707
+ /**
708
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
709
+ *
710
+ * @param {string} str
711
+ * @returns {boolean}
712
+ */
713
+ preformatted(str) {
714
+ return /\n[^\S\r\n]/.test(str);
715
+ }
716
+ /**
717
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
718
+ *
719
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
720
+ * TTT DDD DDDD
721
+ * DD DDD
722
+ *
723
+ * @param {string} term
724
+ * @param {number} termWidth
725
+ * @param {string} description
726
+ * @param {Help} helper
727
+ * @returns {string}
728
+ */
729
+ formatItem(term, termWidth, description, helper) {
730
+ const itemIndent = 2;
731
+ const itemIndentStr = " ".repeat(itemIndent);
732
+ if (!description) return itemIndentStr + term;
733
+ const paddedTerm = term.padEnd(
734
+ termWidth + term.length - helper.displayWidth(term)
735
+ );
736
+ const spacerWidth = 2;
737
+ const helpWidth = this.helpWidth ?? 80;
738
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
739
+ let formattedDescription;
740
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
741
+ formattedDescription = description;
742
+ } else {
743
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
744
+ formattedDescription = wrappedDescription.replace(
745
+ /\n/g,
746
+ "\n" + " ".repeat(termWidth + spacerWidth)
747
+ );
748
+ }
749
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
750
+ ${itemIndentStr}`);
751
+ }
752
+ /**
753
+ * Wrap a string at whitespace, preserving existing line breaks.
754
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
755
+ *
756
+ * @param {string} str
757
+ * @param {number} width
758
+ * @returns {string}
759
+ */
760
+ boxWrap(str, width) {
761
+ if (width < this.minWidthToWrap) return str;
762
+ const rawLines = str.split(/\r\n|\n/);
763
+ const chunkPattern = /[\s]*[^\s]+/g;
764
+ const wrappedLines = [];
765
+ rawLines.forEach((line) => {
766
+ const chunks = line.match(chunkPattern);
767
+ if (chunks === null) {
768
+ wrappedLines.push("");
769
+ return;
770
+ }
771
+ let sumChunks = [chunks.shift()];
772
+ let sumWidth = this.displayWidth(sumChunks[0]);
773
+ chunks.forEach((chunk) => {
774
+ const visibleWidth = this.displayWidth(chunk);
775
+ if (sumWidth + visibleWidth <= width) {
776
+ sumChunks.push(chunk);
777
+ sumWidth += visibleWidth;
778
+ return;
779
+ }
780
+ wrappedLines.push(sumChunks.join(""));
781
+ const nextChunk = chunk.trimStart();
782
+ sumChunks = [nextChunk];
783
+ sumWidth = this.displayWidth(nextChunk);
784
+ });
785
+ wrappedLines.push(sumChunks.join(""));
786
+ });
787
+ return wrappedLines.join("\n");
788
+ }
789
+ };
790
+ function stripColor(str) {
791
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
792
+ return str.replace(sgrPattern, "");
793
+ }
794
+ exports.Help = Help2;
795
+ exports.stripColor = stripColor;
796
+ }
797
+ });
798
+
799
+ // ../node_modules/commander/lib/option.js
800
+ var require_option = __commonJS({
801
+ "../node_modules/commander/lib/option.js"(exports) {
802
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
803
+ var Option2 = class {
804
+ /**
805
+ * Initialize a new `Option` with the given `flags` and `description`.
806
+ *
807
+ * @param {string} flags
808
+ * @param {string} [description]
809
+ */
810
+ constructor(flags, description) {
811
+ this.flags = flags;
812
+ this.description = description || "";
813
+ this.required = flags.includes("<");
814
+ this.optional = flags.includes("[");
815
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
816
+ this.mandatory = false;
817
+ const optionFlags = splitOptionFlags(flags);
818
+ this.short = optionFlags.shortFlag;
819
+ this.long = optionFlags.longFlag;
820
+ this.negate = false;
821
+ if (this.long) {
822
+ this.negate = this.long.startsWith("--no-");
823
+ }
824
+ this.defaultValue = void 0;
825
+ this.defaultValueDescription = void 0;
826
+ this.presetArg = void 0;
827
+ this.envVar = void 0;
828
+ this.parseArg = void 0;
829
+ this.hidden = false;
830
+ this.argChoices = void 0;
831
+ this.conflictsWith = [];
832
+ this.implied = void 0;
833
+ this.helpGroupHeading = void 0;
834
+ }
835
+ /**
836
+ * Set the default value, and optionally supply the description to be displayed in the help.
837
+ *
838
+ * @param {*} value
839
+ * @param {string} [description]
840
+ * @return {Option}
841
+ */
842
+ default(value, description) {
843
+ this.defaultValue = value;
844
+ this.defaultValueDescription = description;
845
+ return this;
846
+ }
847
+ /**
848
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
849
+ * The custom processing (parseArg) is called.
850
+ *
851
+ * @example
852
+ * new Option('--color').default('GREYSCALE').preset('RGB');
853
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
854
+ *
855
+ * @param {*} arg
856
+ * @return {Option}
857
+ */
858
+ preset(arg) {
859
+ this.presetArg = arg;
860
+ return this;
861
+ }
862
+ /**
863
+ * Add option name(s) that conflict with this option.
864
+ * An error will be displayed if conflicting options are found during parsing.
865
+ *
866
+ * @example
867
+ * new Option('--rgb').conflicts('cmyk');
868
+ * new Option('--js').conflicts(['ts', 'jsx']);
869
+ *
870
+ * @param {(string | string[])} names
871
+ * @return {Option}
872
+ */
873
+ conflicts(names) {
874
+ this.conflictsWith = this.conflictsWith.concat(names);
875
+ return this;
876
+ }
877
+ /**
878
+ * Specify implied option values for when this option is set and the implied options are not.
879
+ *
880
+ * The custom processing (parseArg) is not called on the implied values.
881
+ *
882
+ * @example
883
+ * program
884
+ * .addOption(new Option('--log', 'write logging information to file'))
885
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
886
+ *
887
+ * @param {object} impliedOptionValues
888
+ * @return {Option}
889
+ */
890
+ implies(impliedOptionValues) {
891
+ let newImplied = impliedOptionValues;
892
+ if (typeof impliedOptionValues === "string") {
893
+ newImplied = { [impliedOptionValues]: true };
894
+ }
895
+ this.implied = Object.assign(this.implied || {}, newImplied);
896
+ return this;
897
+ }
898
+ /**
899
+ * Set environment variable to check for option value.
900
+ *
901
+ * An environment variable is only used if when processed the current option value is
902
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
903
+ *
904
+ * @param {string} name
905
+ * @return {Option}
906
+ */
907
+ env(name) {
908
+ this.envVar = name;
909
+ return this;
910
+ }
911
+ /**
912
+ * Set the custom handler for processing CLI option arguments into option values.
913
+ *
914
+ * @param {Function} [fn]
915
+ * @return {Option}
916
+ */
917
+ argParser(fn) {
918
+ this.parseArg = fn;
919
+ return this;
920
+ }
921
+ /**
922
+ * Whether the option is mandatory and must have a value after parsing.
923
+ *
924
+ * @param {boolean} [mandatory=true]
925
+ * @return {Option}
926
+ */
927
+ makeOptionMandatory(mandatory = true) {
928
+ this.mandatory = !!mandatory;
929
+ return this;
930
+ }
931
+ /**
932
+ * Hide option in help.
933
+ *
934
+ * @param {boolean} [hide=true]
935
+ * @return {Option}
936
+ */
937
+ hideHelp(hide = true) {
938
+ this.hidden = !!hide;
939
+ return this;
940
+ }
941
+ /**
942
+ * @package
943
+ */
944
+ _collectValue(value, previous) {
945
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
946
+ return [value];
947
+ }
948
+ previous.push(value);
949
+ return previous;
950
+ }
951
+ /**
952
+ * Only allow option value to be one of choices.
953
+ *
954
+ * @param {string[]} values
955
+ * @return {Option}
956
+ */
957
+ choices(values) {
958
+ this.argChoices = values.slice();
959
+ this.parseArg = (arg, previous) => {
960
+ if (!this.argChoices.includes(arg)) {
961
+ throw new InvalidArgumentError2(
962
+ `Allowed choices are ${this.argChoices.join(", ")}.`
963
+ );
964
+ }
965
+ if (this.variadic) {
966
+ return this._collectValue(arg, previous);
967
+ }
968
+ return arg;
969
+ };
970
+ return this;
971
+ }
972
+ /**
973
+ * Return option name.
974
+ *
975
+ * @return {string}
976
+ */
977
+ name() {
978
+ if (this.long) {
979
+ return this.long.replace(/^--/, "");
980
+ }
981
+ return this.short.replace(/^-/, "");
982
+ }
983
+ /**
984
+ * Return option name, in a camelcase format that can be used
985
+ * as an object attribute key.
986
+ *
987
+ * @return {string}
988
+ */
989
+ attributeName() {
990
+ if (this.negate) {
991
+ return camelcase(this.name().replace(/^no-/, ""));
992
+ }
993
+ return camelcase(this.name());
994
+ }
995
+ /**
996
+ * Set the help group heading.
997
+ *
998
+ * @param {string} heading
999
+ * @return {Option}
1000
+ */
1001
+ helpGroup(heading) {
1002
+ this.helpGroupHeading = heading;
1003
+ return this;
1004
+ }
1005
+ /**
1006
+ * Check if `arg` matches the short or long flag.
1007
+ *
1008
+ * @param {string} arg
1009
+ * @return {boolean}
1010
+ * @package
1011
+ */
1012
+ is(arg) {
1013
+ return this.short === arg || this.long === arg;
1014
+ }
1015
+ /**
1016
+ * Return whether a boolean option.
1017
+ *
1018
+ * Options are one of boolean, negated, required argument, or optional argument.
1019
+ *
1020
+ * @return {boolean}
1021
+ * @package
1022
+ */
1023
+ isBoolean() {
1024
+ return !this.required && !this.optional && !this.negate;
1025
+ }
1026
+ };
1027
+ var DualOptions = class {
1028
+ /**
1029
+ * @param {Option[]} options
1030
+ */
1031
+ constructor(options) {
1032
+ this.positiveOptions = /* @__PURE__ */ new Map();
1033
+ this.negativeOptions = /* @__PURE__ */ new Map();
1034
+ this.dualOptions = /* @__PURE__ */ new Set();
1035
+ options.forEach((option) => {
1036
+ if (option.negate) {
1037
+ this.negativeOptions.set(option.attributeName(), option);
1038
+ } else {
1039
+ this.positiveOptions.set(option.attributeName(), option);
1040
+ }
1041
+ });
1042
+ this.negativeOptions.forEach((value, key) => {
1043
+ if (this.positiveOptions.has(key)) {
1044
+ this.dualOptions.add(key);
1045
+ }
1046
+ });
1047
+ }
1048
+ /**
1049
+ * Did the value come from the option, and not from possible matching dual option?
1050
+ *
1051
+ * @param {*} value
1052
+ * @param {Option} option
1053
+ * @returns {boolean}
1054
+ */
1055
+ valueFromOption(value, option) {
1056
+ const optionKey = option.attributeName();
1057
+ if (!this.dualOptions.has(optionKey)) return true;
1058
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1059
+ const negativeValue = preset !== void 0 ? preset : false;
1060
+ return option.negate === (negativeValue === value);
1061
+ }
1062
+ };
1063
+ function camelcase(str) {
1064
+ return str.split("-").reduce((str2, word) => {
1065
+ return str2 + word[0].toUpperCase() + word.slice(1);
1066
+ });
1067
+ }
1068
+ function splitOptionFlags(flags) {
1069
+ let shortFlag;
1070
+ let longFlag;
1071
+ const shortFlagExp = /^-[^-]$/;
1072
+ const longFlagExp = /^--[^-]/;
1073
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1074
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1075
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1076
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1077
+ shortFlag = flagParts.shift();
1078
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1079
+ shortFlag = longFlag;
1080
+ longFlag = flagParts.shift();
1081
+ }
1082
+ if (flagParts[0].startsWith("-")) {
1083
+ const unsupportedFlag = flagParts[0];
1084
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1085
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1086
+ throw new Error(
1087
+ `${baseError}
1088
+ - a short flag is a single dash and a single character
1089
+ - either use a single dash and a single character (for a short flag)
1090
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1091
+ );
1092
+ if (shortFlagExp.test(unsupportedFlag))
1093
+ throw new Error(`${baseError}
1094
+ - too many short flags`);
1095
+ if (longFlagExp.test(unsupportedFlag))
1096
+ throw new Error(`${baseError}
1097
+ - too many long flags`);
1098
+ throw new Error(`${baseError}
1099
+ - unrecognised flag format`);
1100
+ }
1101
+ if (shortFlag === void 0 && longFlag === void 0)
1102
+ throw new Error(
1103
+ `option creation failed due to no flags found in '${flags}'.`
1104
+ );
1105
+ return { shortFlag, longFlag };
1106
+ }
1107
+ exports.Option = Option2;
1108
+ exports.DualOptions = DualOptions;
1109
+ }
1110
+ });
1111
+
1112
+ // ../node_modules/commander/lib/suggestSimilar.js
1113
+ var require_suggestSimilar = __commonJS({
1114
+ "../node_modules/commander/lib/suggestSimilar.js"(exports) {
1115
+ var maxDistance = 3;
1116
+ function editDistance(a2, b) {
1117
+ if (Math.abs(a2.length - b.length) > maxDistance)
1118
+ return Math.max(a2.length, b.length);
1119
+ const d = [];
1120
+ for (let i = 0; i <= a2.length; i++) {
1121
+ d[i] = [i];
1122
+ }
1123
+ for (let j = 0; j <= b.length; j++) {
1124
+ d[0][j] = j;
1125
+ }
1126
+ for (let j = 1; j <= b.length; j++) {
1127
+ for (let i = 1; i <= a2.length; i++) {
1128
+ let cost = 1;
1129
+ if (a2[i - 1] === b[j - 1]) {
1130
+ cost = 0;
1131
+ } else {
1132
+ cost = 1;
1133
+ }
1134
+ d[i][j] = Math.min(
1135
+ d[i - 1][j] + 1,
1136
+ // deletion
1137
+ d[i][j - 1] + 1,
1138
+ // insertion
1139
+ d[i - 1][j - 1] + cost
1140
+ // substitution
1141
+ );
1142
+ if (i > 1 && j > 1 && a2[i - 1] === b[j - 2] && a2[i - 2] === b[j - 1]) {
1143
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1144
+ }
1145
+ }
1146
+ }
1147
+ return d[a2.length][b.length];
1148
+ }
1149
+ function suggestSimilar(word, candidates) {
1150
+ if (!candidates || candidates.length === 0) return "";
1151
+ candidates = Array.from(new Set(candidates));
1152
+ const searchingOptions = word.startsWith("--");
1153
+ if (searchingOptions) {
1154
+ word = word.slice(2);
1155
+ candidates = candidates.map((candidate) => candidate.slice(2));
1156
+ }
1157
+ let similar = [];
1158
+ let bestDistance = maxDistance;
1159
+ const minSimilarity = 0.4;
1160
+ candidates.forEach((candidate) => {
1161
+ if (candidate.length <= 1) return;
1162
+ const distance = editDistance(word, candidate);
1163
+ const length = Math.max(word.length, candidate.length);
1164
+ const similarity = (length - distance) / length;
1165
+ if (similarity > minSimilarity) {
1166
+ if (distance < bestDistance) {
1167
+ bestDistance = distance;
1168
+ similar = [candidate];
1169
+ } else if (distance === bestDistance) {
1170
+ similar.push(candidate);
1171
+ }
1172
+ }
1173
+ });
1174
+ similar.sort((a2, b) => a2.localeCompare(b));
1175
+ if (searchingOptions) {
1176
+ similar = similar.map((candidate) => `--${candidate}`);
1177
+ }
1178
+ if (similar.length > 1) {
1179
+ return `
1180
+ (Did you mean one of ${similar.join(", ")}?)`;
1181
+ }
1182
+ if (similar.length === 1) {
1183
+ return `
1184
+ (Did you mean ${similar[0]}?)`;
1185
+ }
1186
+ return "";
1187
+ }
1188
+ exports.suggestSimilar = suggestSimilar;
1189
+ }
1190
+ });
1191
+
1192
+ // ../node_modules/commander/lib/command.js
1193
+ var require_command = __commonJS({
1194
+ "../node_modules/commander/lib/command.js"(exports) {
1195
+ var EventEmitter = __require("events").EventEmitter;
1196
+ var childProcess = __require("child_process");
1197
+ var path = __require("path");
1198
+ var fs = __require("fs");
1199
+ var process2 = __require("process");
1200
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1201
+ var { CommanderError: CommanderError2 } = require_error();
1202
+ var { Help: Help2, stripColor } = require_help();
1203
+ var { Option: Option2, DualOptions } = require_option();
1204
+ var { suggestSimilar } = require_suggestSimilar();
1205
+ var Command2 = class _Command extends EventEmitter {
1206
+ /**
1207
+ * Initialize a new `Command`.
1208
+ *
1209
+ * @param {string} [name]
1210
+ */
1211
+ constructor(name) {
1212
+ super();
1213
+ this.commands = [];
1214
+ this.options = [];
1215
+ this.parent = null;
1216
+ this._allowUnknownOption = false;
1217
+ this._allowExcessArguments = false;
1218
+ this.registeredArguments = [];
1219
+ this._args = this.registeredArguments;
1220
+ this.args = [];
1221
+ this.rawArgs = [];
1222
+ this.processedArgs = [];
1223
+ this._scriptPath = null;
1224
+ this._name = name || "";
1225
+ this._optionValues = {};
1226
+ this._optionValueSources = {};
1227
+ this._storeOptionsAsProperties = false;
1228
+ this._actionHandler = null;
1229
+ this._executableHandler = false;
1230
+ this._executableFile = null;
1231
+ this._executableDir = null;
1232
+ this._defaultCommandName = null;
1233
+ this._exitCallback = null;
1234
+ this._aliases = [];
1235
+ this._combineFlagAndOptionalValue = true;
1236
+ this._description = "";
1237
+ this._summary = "";
1238
+ this._argsDescription = void 0;
1239
+ this._enablePositionalOptions = false;
1240
+ this._passThroughOptions = false;
1241
+ this._lifeCycleHooks = {};
1242
+ this._showHelpAfterError = false;
1243
+ this._showSuggestionAfterError = true;
1244
+ this._savedState = null;
1245
+ this._outputConfiguration = {
1246
+ writeOut: (str) => process2.stdout.write(str),
1247
+ writeErr: (str) => process2.stderr.write(str),
1248
+ outputError: (str, write) => write(str),
1249
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1250
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1251
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1252
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1253
+ stripColor: (str) => stripColor(str)
1254
+ };
1255
+ this._hidden = false;
1256
+ this._helpOption = void 0;
1257
+ this._addImplicitHelpCommand = void 0;
1258
+ this._helpCommand = void 0;
1259
+ this._helpConfiguration = {};
1260
+ this._helpGroupHeading = void 0;
1261
+ this._defaultCommandGroup = void 0;
1262
+ this._defaultOptionGroup = void 0;
1263
+ }
1264
+ /**
1265
+ * Copy settings that are useful to have in common across root command and subcommands.
1266
+ *
1267
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1268
+ *
1269
+ * @param {Command} sourceCommand
1270
+ * @return {Command} `this` command for chaining
1271
+ */
1272
+ copyInheritedSettings(sourceCommand) {
1273
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1274
+ this._helpOption = sourceCommand._helpOption;
1275
+ this._helpCommand = sourceCommand._helpCommand;
1276
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1277
+ this._exitCallback = sourceCommand._exitCallback;
1278
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1279
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1280
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1281
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1282
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1283
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1284
+ return this;
1285
+ }
1286
+ /**
1287
+ * @returns {Command[]}
1288
+ * @private
1289
+ */
1290
+ _getCommandAndAncestors() {
1291
+ const result = [];
1292
+ for (let command = this; command; command = command.parent) {
1293
+ result.push(command);
1294
+ }
1295
+ return result;
1296
+ }
1297
+ /**
1298
+ * Define a command.
1299
+ *
1300
+ * There are two styles of command: pay attention to where to put the description.
1301
+ *
1302
+ * @example
1303
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1304
+ * program
1305
+ * .command('clone <source> [destination]')
1306
+ * .description('clone a repository into a newly created directory')
1307
+ * .action((source, destination) => {
1308
+ * console.log('clone command called');
1309
+ * });
1310
+ *
1311
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1312
+ * program
1313
+ * .command('start <service>', 'start named service')
1314
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1315
+ *
1316
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1317
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1318
+ * @param {object} [execOpts] - configuration options (for executable)
1319
+ * @return {Command} returns new command for action handler, or `this` for executable command
1320
+ */
1321
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1322
+ let desc = actionOptsOrExecDesc;
1323
+ let opts = execOpts;
1324
+ if (typeof desc === "object" && desc !== null) {
1325
+ opts = desc;
1326
+ desc = null;
1327
+ }
1328
+ opts = opts || {};
1329
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1330
+ const cmd = this.createCommand(name);
1331
+ if (desc) {
1332
+ cmd.description(desc);
1333
+ cmd._executableHandler = true;
1334
+ }
1335
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1336
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1337
+ cmd._executableFile = opts.executableFile || null;
1338
+ if (args) cmd.arguments(args);
1339
+ this._registerCommand(cmd);
1340
+ cmd.parent = this;
1341
+ cmd.copyInheritedSettings(this);
1342
+ if (desc) return this;
1343
+ return cmd;
1344
+ }
1345
+ /**
1346
+ * Factory routine to create a new unattached command.
1347
+ *
1348
+ * See .command() for creating an attached subcommand, which uses this routine to
1349
+ * create the command. You can override createCommand to customise subcommands.
1350
+ *
1351
+ * @param {string} [name]
1352
+ * @return {Command} new command
1353
+ */
1354
+ createCommand(name) {
1355
+ return new _Command(name);
1356
+ }
1357
+ /**
1358
+ * You can customise the help with a subclass of Help by overriding createHelp,
1359
+ * or by overriding Help properties using configureHelp().
1360
+ *
1361
+ * @return {Help}
1362
+ */
1363
+ createHelp() {
1364
+ return Object.assign(new Help2(), this.configureHelp());
1365
+ }
1366
+ /**
1367
+ * You can customise the help by overriding Help properties using configureHelp(),
1368
+ * or with a subclass of Help by overriding createHelp().
1369
+ *
1370
+ * @param {object} [configuration] - configuration options
1371
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1372
+ */
1373
+ configureHelp(configuration) {
1374
+ if (configuration === void 0) return this._helpConfiguration;
1375
+ this._helpConfiguration = configuration;
1376
+ return this;
1377
+ }
1378
+ /**
1379
+ * The default output goes to stdout and stderr. You can customise this for special
1380
+ * applications. You can also customise the display of errors by overriding outputError.
1381
+ *
1382
+ * The configuration properties are all functions:
1383
+ *
1384
+ * // change how output being written, defaults to stdout and stderr
1385
+ * writeOut(str)
1386
+ * writeErr(str)
1387
+ * // change how output being written for errors, defaults to writeErr
1388
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1389
+ * // specify width for wrapping help
1390
+ * getOutHelpWidth()
1391
+ * getErrHelpWidth()
1392
+ * // color support, currently only used with Help
1393
+ * getOutHasColors()
1394
+ * getErrHasColors()
1395
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1396
+ *
1397
+ * @param {object} [configuration] - configuration options
1398
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1399
+ */
1400
+ configureOutput(configuration) {
1401
+ if (configuration === void 0) return this._outputConfiguration;
1402
+ this._outputConfiguration = {
1403
+ ...this._outputConfiguration,
1404
+ ...configuration
1405
+ };
1406
+ return this;
1407
+ }
1408
+ /**
1409
+ * Display the help or a custom message after an error occurs.
1410
+ *
1411
+ * @param {(boolean|string)} [displayHelp]
1412
+ * @return {Command} `this` command for chaining
1413
+ */
1414
+ showHelpAfterError(displayHelp = true) {
1415
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1416
+ this._showHelpAfterError = displayHelp;
1417
+ return this;
1418
+ }
1419
+ /**
1420
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1421
+ *
1422
+ * @param {boolean} [displaySuggestion]
1423
+ * @return {Command} `this` command for chaining
1424
+ */
1425
+ showSuggestionAfterError(displaySuggestion = true) {
1426
+ this._showSuggestionAfterError = !!displaySuggestion;
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Add a prepared subcommand.
1431
+ *
1432
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1433
+ *
1434
+ * @param {Command} cmd - new subcommand
1435
+ * @param {object} [opts] - configuration options
1436
+ * @return {Command} `this` command for chaining
1437
+ */
1438
+ addCommand(cmd, opts) {
1439
+ if (!cmd._name) {
1440
+ throw new Error(`Command passed to .addCommand() must have a name
1441
+ - specify the name in Command constructor or using .name()`);
1442
+ }
1443
+ opts = opts || {};
1444
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1445
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1446
+ this._registerCommand(cmd);
1447
+ cmd.parent = this;
1448
+ cmd._checkForBrokenPassThrough();
1449
+ return this;
1450
+ }
1451
+ /**
1452
+ * Factory routine to create a new unattached argument.
1453
+ *
1454
+ * See .argument() for creating an attached argument, which uses this routine to
1455
+ * create the argument. You can override createArgument to return a custom argument.
1456
+ *
1457
+ * @param {string} name
1458
+ * @param {string} [description]
1459
+ * @return {Argument} new argument
1460
+ */
1461
+ createArgument(name, description) {
1462
+ return new Argument2(name, description);
1463
+ }
1464
+ /**
1465
+ * Define argument syntax for command.
1466
+ *
1467
+ * The default is that the argument is required, and you can explicitly
1468
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1469
+ *
1470
+ * @example
1471
+ * program.argument('<input-file>');
1472
+ * program.argument('[output-file]');
1473
+ *
1474
+ * @param {string} name
1475
+ * @param {string} [description]
1476
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1477
+ * @param {*} [defaultValue]
1478
+ * @return {Command} `this` command for chaining
1479
+ */
1480
+ argument(name, description, parseArg, defaultValue) {
1481
+ const argument = this.createArgument(name, description);
1482
+ if (typeof parseArg === "function") {
1483
+ argument.default(defaultValue).argParser(parseArg);
1484
+ } else {
1485
+ argument.default(parseArg);
1486
+ }
1487
+ this.addArgument(argument);
1488
+ return this;
1489
+ }
1490
+ /**
1491
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1492
+ *
1493
+ * See also .argument().
1494
+ *
1495
+ * @example
1496
+ * program.arguments('<cmd> [env]');
1497
+ *
1498
+ * @param {string} names
1499
+ * @return {Command} `this` command for chaining
1500
+ */
1501
+ arguments(names) {
1502
+ names.trim().split(/ +/).forEach((detail) => {
1503
+ this.argument(detail);
1504
+ });
1505
+ return this;
1506
+ }
1507
+ /**
1508
+ * Define argument syntax for command, adding a prepared argument.
1509
+ *
1510
+ * @param {Argument} argument
1511
+ * @return {Command} `this` command for chaining
1512
+ */
1513
+ addArgument(argument) {
1514
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1515
+ if (previousArgument?.variadic) {
1516
+ throw new Error(
1517
+ `only the last argument can be variadic '${previousArgument.name()}'`
1518
+ );
1519
+ }
1520
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1521
+ throw new Error(
1522
+ `a default value for a required argument is never used: '${argument.name()}'`
1523
+ );
1524
+ }
1525
+ this.registeredArguments.push(argument);
1526
+ return this;
1527
+ }
1528
+ /**
1529
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1530
+ *
1531
+ * @example
1532
+ * program.helpCommand('help [cmd]');
1533
+ * program.helpCommand('help [cmd]', 'show help');
1534
+ * program.helpCommand(false); // suppress default help command
1535
+ * program.helpCommand(true); // add help command even if no subcommands
1536
+ *
1537
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1538
+ * @param {string} [description] - custom description
1539
+ * @return {Command} `this` command for chaining
1540
+ */
1541
+ helpCommand(enableOrNameAndArgs, description) {
1542
+ if (typeof enableOrNameAndArgs === "boolean") {
1543
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1544
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1545
+ this._initCommandGroup(this._getHelpCommand());
1546
+ }
1547
+ return this;
1548
+ }
1549
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1550
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1551
+ const helpDescription = description ?? "display help for command";
1552
+ const helpCommand = this.createCommand(helpName);
1553
+ helpCommand.helpOption(false);
1554
+ if (helpArgs) helpCommand.arguments(helpArgs);
1555
+ if (helpDescription) helpCommand.description(helpDescription);
1556
+ this._addImplicitHelpCommand = true;
1557
+ this._helpCommand = helpCommand;
1558
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1559
+ return this;
1560
+ }
1561
+ /**
1562
+ * Add prepared custom help command.
1563
+ *
1564
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1565
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1566
+ * @return {Command} `this` command for chaining
1567
+ */
1568
+ addHelpCommand(helpCommand, deprecatedDescription) {
1569
+ if (typeof helpCommand !== "object") {
1570
+ this.helpCommand(helpCommand, deprecatedDescription);
1571
+ return this;
1572
+ }
1573
+ this._addImplicitHelpCommand = true;
1574
+ this._helpCommand = helpCommand;
1575
+ this._initCommandGroup(helpCommand);
1576
+ return this;
1577
+ }
1578
+ /**
1579
+ * Lazy create help command.
1580
+ *
1581
+ * @return {(Command|null)}
1582
+ * @package
1583
+ */
1584
+ _getHelpCommand() {
1585
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1586
+ if (hasImplicitHelpCommand) {
1587
+ if (this._helpCommand === void 0) {
1588
+ this.helpCommand(void 0, void 0);
1589
+ }
1590
+ return this._helpCommand;
1591
+ }
1592
+ return null;
1593
+ }
1594
+ /**
1595
+ * Add hook for life cycle event.
1596
+ *
1597
+ * @param {string} event
1598
+ * @param {Function} listener
1599
+ * @return {Command} `this` command for chaining
1600
+ */
1601
+ hook(event, listener) {
1602
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1603
+ if (!allowedValues.includes(event)) {
1604
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1605
+ Expecting one of '${allowedValues.join("', '")}'`);
1606
+ }
1607
+ if (this._lifeCycleHooks[event]) {
1608
+ this._lifeCycleHooks[event].push(listener);
1609
+ } else {
1610
+ this._lifeCycleHooks[event] = [listener];
1611
+ }
1612
+ return this;
1613
+ }
1614
+ /**
1615
+ * Register callback to use as replacement for calling process.exit.
1616
+ *
1617
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1618
+ * @return {Command} `this` command for chaining
1619
+ */
1620
+ exitOverride(fn) {
1621
+ if (fn) {
1622
+ this._exitCallback = fn;
1623
+ } else {
1624
+ this._exitCallback = (err) => {
1625
+ if (err.code !== "commander.executeSubCommandAsync") {
1626
+ throw err;
1627
+ } else {
1628
+ }
1629
+ };
1630
+ }
1631
+ return this;
1632
+ }
1633
+ /**
1634
+ * Call process.exit, and _exitCallback if defined.
1635
+ *
1636
+ * @param {number} exitCode exit code for using with process.exit
1637
+ * @param {string} code an id string representing the error
1638
+ * @param {string} message human-readable description of the error
1639
+ * @return never
1640
+ * @private
1641
+ */
1642
+ _exit(exitCode, code, message) {
1643
+ if (this._exitCallback) {
1644
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1645
+ }
1646
+ process2.exit(exitCode);
1647
+ }
1648
+ /**
1649
+ * Register callback `fn` for the command.
1650
+ *
1651
+ * @example
1652
+ * program
1653
+ * .command('serve')
1654
+ * .description('start service')
1655
+ * .action(function() {
1656
+ * // do work here
1657
+ * });
1658
+ *
1659
+ * @param {Function} fn
1660
+ * @return {Command} `this` command for chaining
1661
+ */
1662
+ action(fn) {
1663
+ const listener = (args) => {
1664
+ const expectedArgsCount = this.registeredArguments.length;
1665
+ const actionArgs = args.slice(0, expectedArgsCount);
1666
+ if (this._storeOptionsAsProperties) {
1667
+ actionArgs[expectedArgsCount] = this;
1668
+ } else {
1669
+ actionArgs[expectedArgsCount] = this.opts();
1670
+ }
1671
+ actionArgs.push(this);
1672
+ return fn.apply(this, actionArgs);
1673
+ };
1674
+ this._actionHandler = listener;
1675
+ return this;
1676
+ }
1677
+ /**
1678
+ * Factory routine to create a new unattached option.
1679
+ *
1680
+ * See .option() for creating an attached option, which uses this routine to
1681
+ * create the option. You can override createOption to return a custom option.
1682
+ *
1683
+ * @param {string} flags
1684
+ * @param {string} [description]
1685
+ * @return {Option} new option
1686
+ */
1687
+ createOption(flags, description) {
1688
+ return new Option2(flags, description);
1689
+ }
1690
+ /**
1691
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1692
+ *
1693
+ * @param {(Option | Argument)} target
1694
+ * @param {string} value
1695
+ * @param {*} previous
1696
+ * @param {string} invalidArgumentMessage
1697
+ * @private
1698
+ */
1699
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1700
+ try {
1701
+ return target.parseArg(value, previous);
1702
+ } catch (err) {
1703
+ if (err.code === "commander.invalidArgument") {
1704
+ const message = `${invalidArgumentMessage} ${err.message}`;
1705
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1706
+ }
1707
+ throw err;
1708
+ }
1709
+ }
1710
+ /**
1711
+ * Check for option flag conflicts.
1712
+ * Register option if no conflicts found, or throw on conflict.
1713
+ *
1714
+ * @param {Option} option
1715
+ * @private
1716
+ */
1717
+ _registerOption(option) {
1718
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1719
+ if (matchingOption) {
1720
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1721
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1722
+ - already used by option '${matchingOption.flags}'`);
1723
+ }
1724
+ this._initOptionGroup(option);
1725
+ this.options.push(option);
1726
+ }
1727
+ /**
1728
+ * Check for command name and alias conflicts with existing commands.
1729
+ * Register command if no conflicts found, or throw on conflict.
1730
+ *
1731
+ * @param {Command} command
1732
+ * @private
1733
+ */
1734
+ _registerCommand(command) {
1735
+ const knownBy = (cmd) => {
1736
+ return [cmd.name()].concat(cmd.aliases());
1737
+ };
1738
+ const alreadyUsed = knownBy(command).find(
1739
+ (name) => this._findCommand(name)
1740
+ );
1741
+ if (alreadyUsed) {
1742
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1743
+ const newCmd = knownBy(command).join("|");
1744
+ throw new Error(
1745
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1746
+ );
1747
+ }
1748
+ this._initCommandGroup(command);
1749
+ this.commands.push(command);
1750
+ }
1751
+ /**
1752
+ * Add an option.
1753
+ *
1754
+ * @param {Option} option
1755
+ * @return {Command} `this` command for chaining
1756
+ */
1757
+ addOption(option) {
1758
+ this._registerOption(option);
1759
+ const oname = option.name();
1760
+ const name = option.attributeName();
1761
+ if (option.negate) {
1762
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1763
+ if (!this._findOption(positiveLongFlag)) {
1764
+ this.setOptionValueWithSource(
1765
+ name,
1766
+ option.defaultValue === void 0 ? true : option.defaultValue,
1767
+ "default"
1768
+ );
1769
+ }
1770
+ } else if (option.defaultValue !== void 0) {
1771
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1772
+ }
1773
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1774
+ if (val == null && option.presetArg !== void 0) {
1775
+ val = option.presetArg;
1776
+ }
1777
+ const oldValue = this.getOptionValue(name);
1778
+ if (val !== null && option.parseArg) {
1779
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1780
+ } else if (val !== null && option.variadic) {
1781
+ val = option._collectValue(val, oldValue);
1782
+ }
1783
+ if (val == null) {
1784
+ if (option.negate) {
1785
+ val = false;
1786
+ } else if (option.isBoolean() || option.optional) {
1787
+ val = true;
1788
+ } else {
1789
+ val = "";
1790
+ }
1791
+ }
1792
+ this.setOptionValueWithSource(name, val, valueSource);
1793
+ };
1794
+ this.on("option:" + oname, (val) => {
1795
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1796
+ handleOptionValue(val, invalidValueMessage, "cli");
1797
+ });
1798
+ if (option.envVar) {
1799
+ this.on("optionEnv:" + oname, (val) => {
1800
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1801
+ handleOptionValue(val, invalidValueMessage, "env");
1802
+ });
1803
+ }
1804
+ return this;
1805
+ }
1806
+ /**
1807
+ * Internal implementation shared by .option() and .requiredOption()
1808
+ *
1809
+ * @return {Command} `this` command for chaining
1810
+ * @private
1811
+ */
1812
+ _optionEx(config, flags, description, fn, defaultValue) {
1813
+ if (typeof flags === "object" && flags instanceof Option2) {
1814
+ throw new Error(
1815
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1816
+ );
1817
+ }
1818
+ const option = this.createOption(flags, description);
1819
+ option.makeOptionMandatory(!!config.mandatory);
1820
+ if (typeof fn === "function") {
1821
+ option.default(defaultValue).argParser(fn);
1822
+ } else if (fn instanceof RegExp) {
1823
+ const regex = fn;
1824
+ fn = (val, def) => {
1825
+ const m = regex.exec(val);
1826
+ return m ? m[0] : def;
1827
+ };
1828
+ option.default(defaultValue).argParser(fn);
1829
+ } else {
1830
+ option.default(fn);
1831
+ }
1832
+ return this.addOption(option);
1833
+ }
1834
+ /**
1835
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1836
+ *
1837
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1838
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1839
+ *
1840
+ * See the README for more details, and see also addOption() and requiredOption().
1841
+ *
1842
+ * @example
1843
+ * program
1844
+ * .option('-p, --pepper', 'add pepper')
1845
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1846
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1847
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1848
+ *
1849
+ * @param {string} flags
1850
+ * @param {string} [description]
1851
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1852
+ * @param {*} [defaultValue]
1853
+ * @return {Command} `this` command for chaining
1854
+ */
1855
+ option(flags, description, parseArg, defaultValue) {
1856
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1857
+ }
1858
+ /**
1859
+ * Add a required option which must have a value after parsing. This usually means
1860
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1861
+ *
1862
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1863
+ *
1864
+ * @param {string} flags
1865
+ * @param {string} [description]
1866
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1867
+ * @param {*} [defaultValue]
1868
+ * @return {Command} `this` command for chaining
1869
+ */
1870
+ requiredOption(flags, description, parseArg, defaultValue) {
1871
+ return this._optionEx(
1872
+ { mandatory: true },
1873
+ flags,
1874
+ description,
1875
+ parseArg,
1876
+ defaultValue
1877
+ );
1878
+ }
1879
+ /**
1880
+ * Alter parsing of short flags with optional values.
1881
+ *
1882
+ * @example
1883
+ * // for `.option('-f,--flag [value]'):
1884
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1885
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1886
+ *
1887
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1888
+ * @return {Command} `this` command for chaining
1889
+ */
1890
+ combineFlagAndOptionalValue(combine = true) {
1891
+ this._combineFlagAndOptionalValue = !!combine;
1892
+ return this;
1893
+ }
1894
+ /**
1895
+ * Allow unknown options on the command line.
1896
+ *
1897
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1898
+ * @return {Command} `this` command for chaining
1899
+ */
1900
+ allowUnknownOption(allowUnknown = true) {
1901
+ this._allowUnknownOption = !!allowUnknown;
1902
+ return this;
1903
+ }
1904
+ /**
1905
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1906
+ *
1907
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1908
+ * @return {Command} `this` command for chaining
1909
+ */
1910
+ allowExcessArguments(allowExcess = true) {
1911
+ this._allowExcessArguments = !!allowExcess;
1912
+ return this;
1913
+ }
1914
+ /**
1915
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1916
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1917
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1918
+ *
1919
+ * @param {boolean} [positional]
1920
+ * @return {Command} `this` command for chaining
1921
+ */
1922
+ enablePositionalOptions(positional = true) {
1923
+ this._enablePositionalOptions = !!positional;
1924
+ return this;
1925
+ }
1926
+ /**
1927
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1928
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1929
+ * positional options to have been enabled on the program (parent commands).
1930
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1931
+ *
1932
+ * @param {boolean} [passThrough] for unknown options.
1933
+ * @return {Command} `this` command for chaining
1934
+ */
1935
+ passThroughOptions(passThrough = true) {
1936
+ this._passThroughOptions = !!passThrough;
1937
+ this._checkForBrokenPassThrough();
1938
+ return this;
1939
+ }
1940
+ /**
1941
+ * @private
1942
+ */
1943
+ _checkForBrokenPassThrough() {
1944
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1945
+ throw new Error(
1946
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1947
+ );
1948
+ }
1949
+ }
1950
+ /**
1951
+ * Whether to store option values as properties on command object,
1952
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1953
+ *
1954
+ * @param {boolean} [storeAsProperties=true]
1955
+ * @return {Command} `this` command for chaining
1956
+ */
1957
+ storeOptionsAsProperties(storeAsProperties = true) {
1958
+ if (this.options.length) {
1959
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1960
+ }
1961
+ if (Object.keys(this._optionValues).length) {
1962
+ throw new Error(
1963
+ "call .storeOptionsAsProperties() before setting option values"
1964
+ );
1965
+ }
1966
+ this._storeOptionsAsProperties = !!storeAsProperties;
1967
+ return this;
1968
+ }
1969
+ /**
1970
+ * Retrieve option value.
1971
+ *
1972
+ * @param {string} key
1973
+ * @return {object} value
1974
+ */
1975
+ getOptionValue(key) {
1976
+ if (this._storeOptionsAsProperties) {
1977
+ return this[key];
1978
+ }
1979
+ return this._optionValues[key];
1980
+ }
1981
+ /**
1982
+ * Store option value.
1983
+ *
1984
+ * @param {string} key
1985
+ * @param {object} value
1986
+ * @return {Command} `this` command for chaining
1987
+ */
1988
+ setOptionValue(key, value) {
1989
+ return this.setOptionValueWithSource(key, value, void 0);
1990
+ }
1991
+ /**
1992
+ * Store option value and where the value came from.
1993
+ *
1994
+ * @param {string} key
1995
+ * @param {object} value
1996
+ * @param {string} source - expected values are default/config/env/cli/implied
1997
+ * @return {Command} `this` command for chaining
1998
+ */
1999
+ setOptionValueWithSource(key, value, source) {
2000
+ if (this._storeOptionsAsProperties) {
2001
+ this[key] = value;
2002
+ } else {
2003
+ this._optionValues[key] = value;
2004
+ }
2005
+ this._optionValueSources[key] = source;
2006
+ return this;
2007
+ }
2008
+ /**
2009
+ * Get source of option value.
2010
+ * Expected values are default | config | env | cli | implied
2011
+ *
2012
+ * @param {string} key
2013
+ * @return {string}
2014
+ */
2015
+ getOptionValueSource(key) {
2016
+ return this._optionValueSources[key];
2017
+ }
2018
+ /**
2019
+ * Get source of option value. See also .optsWithGlobals().
2020
+ * Expected values are default | config | env | cli | implied
2021
+ *
2022
+ * @param {string} key
2023
+ * @return {string}
2024
+ */
2025
+ getOptionValueSourceWithGlobals(key) {
2026
+ let source;
2027
+ this._getCommandAndAncestors().forEach((cmd) => {
2028
+ if (cmd.getOptionValueSource(key) !== void 0) {
2029
+ source = cmd.getOptionValueSource(key);
2030
+ }
2031
+ });
2032
+ return source;
2033
+ }
2034
+ /**
2035
+ * Get user arguments from implied or explicit arguments.
2036
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2037
+ *
2038
+ * @private
2039
+ */
2040
+ _prepareUserArgs(argv, parseOptions) {
2041
+ if (argv !== void 0 && !Array.isArray(argv)) {
2042
+ throw new Error("first parameter to parse must be array or undefined");
2043
+ }
2044
+ parseOptions = parseOptions || {};
2045
+ if (argv === void 0 && parseOptions.from === void 0) {
2046
+ if (process2.versions?.electron) {
2047
+ parseOptions.from = "electron";
2048
+ }
2049
+ const execArgv = process2.execArgv ?? [];
2050
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2051
+ parseOptions.from = "eval";
2052
+ }
2053
+ }
2054
+ if (argv === void 0) {
2055
+ argv = process2.argv;
2056
+ }
2057
+ this.rawArgs = argv.slice();
2058
+ let userArgs;
2059
+ switch (parseOptions.from) {
2060
+ case void 0:
2061
+ case "node":
2062
+ this._scriptPath = argv[1];
2063
+ userArgs = argv.slice(2);
2064
+ break;
2065
+ case "electron":
2066
+ if (process2.defaultApp) {
2067
+ this._scriptPath = argv[1];
2068
+ userArgs = argv.slice(2);
2069
+ } else {
2070
+ userArgs = argv.slice(1);
2071
+ }
2072
+ break;
2073
+ case "user":
2074
+ userArgs = argv.slice(0);
2075
+ break;
2076
+ case "eval":
2077
+ userArgs = argv.slice(1);
2078
+ break;
2079
+ default:
2080
+ throw new Error(
2081
+ `unexpected parse option { from: '${parseOptions.from}' }`
2082
+ );
2083
+ }
2084
+ if (!this._name && this._scriptPath)
2085
+ this.nameFromFilename(this._scriptPath);
2086
+ this._name = this._name || "program";
2087
+ return userArgs;
2088
+ }
2089
+ /**
2090
+ * Parse `argv`, setting options and invoking commands when defined.
2091
+ *
2092
+ * Use parseAsync instead of parse if any of your action handlers are async.
2093
+ *
2094
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2095
+ *
2096
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2097
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2098
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2099
+ * - `'user'`: just user arguments
2100
+ *
2101
+ * @example
2102
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2103
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2104
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2105
+ *
2106
+ * @param {string[]} [argv] - optional, defaults to process.argv
2107
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2108
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2109
+ * @return {Command} `this` command for chaining
2110
+ */
2111
+ parse(argv, parseOptions) {
2112
+ this._prepareForParse();
2113
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2114
+ this._parseCommand([], userArgs);
2115
+ return this;
2116
+ }
2117
+ /**
2118
+ * Parse `argv`, setting options and invoking commands when defined.
2119
+ *
2120
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2121
+ *
2122
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2123
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2124
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2125
+ * - `'user'`: just user arguments
2126
+ *
2127
+ * @example
2128
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2129
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2130
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2131
+ *
2132
+ * @param {string[]} [argv]
2133
+ * @param {object} [parseOptions]
2134
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2135
+ * @return {Promise}
2136
+ */
2137
+ async parseAsync(argv, parseOptions) {
2138
+ this._prepareForParse();
2139
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2140
+ await this._parseCommand([], userArgs);
2141
+ return this;
2142
+ }
2143
+ _prepareForParse() {
2144
+ if (this._savedState === null) {
2145
+ this.saveStateBeforeParse();
2146
+ } else {
2147
+ this.restoreStateBeforeParse();
2148
+ }
2149
+ }
2150
+ /**
2151
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2152
+ * Not usually called directly, but available for subclasses to save their custom state.
2153
+ *
2154
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2155
+ */
2156
+ saveStateBeforeParse() {
2157
+ this._savedState = {
2158
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2159
+ _name: this._name,
2160
+ // option values before parse have default values (including false for negated options)
2161
+ // shallow clones
2162
+ _optionValues: { ...this._optionValues },
2163
+ _optionValueSources: { ...this._optionValueSources }
2164
+ };
2165
+ }
2166
+ /**
2167
+ * Restore state before parse for calls after the first.
2168
+ * Not usually called directly, but available for subclasses to save their custom state.
2169
+ *
2170
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2171
+ */
2172
+ restoreStateBeforeParse() {
2173
+ if (this._storeOptionsAsProperties)
2174
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2175
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2176
+ this._name = this._savedState._name;
2177
+ this._scriptPath = null;
2178
+ this.rawArgs = [];
2179
+ this._optionValues = { ...this._savedState._optionValues };
2180
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2181
+ this.args = [];
2182
+ this.processedArgs = [];
2183
+ }
2184
+ /**
2185
+ * Throw if expected executable is missing. Add lots of help for author.
2186
+ *
2187
+ * @param {string} executableFile
2188
+ * @param {string} executableDir
2189
+ * @param {string} subcommandName
2190
+ */
2191
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2192
+ if (fs.existsSync(executableFile)) return;
2193
+ 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";
2194
+ const executableMissing = `'${executableFile}' does not exist
2195
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2196
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2197
+ - ${executableDirMessage}`;
2198
+ throw new Error(executableMissing);
2199
+ }
2200
+ /**
2201
+ * Execute a sub-command executable.
2202
+ *
2203
+ * @private
2204
+ */
2205
+ _executeSubCommand(subcommand, args) {
2206
+ args = args.slice();
2207
+ let launchWithNode = false;
2208
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2209
+ function findFile(baseDir, baseName) {
2210
+ const localBin = path.resolve(baseDir, baseName);
2211
+ if (fs.existsSync(localBin)) return localBin;
2212
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2213
+ const foundExt = sourceExt.find(
2214
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2215
+ );
2216
+ if (foundExt) return `${localBin}${foundExt}`;
2217
+ return void 0;
2218
+ }
2219
+ this._checkForMissingMandatoryOptions();
2220
+ this._checkForConflictingOptions();
2221
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2222
+ let executableDir = this._executableDir || "";
2223
+ if (this._scriptPath) {
2224
+ let resolvedScriptPath;
2225
+ try {
2226
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2227
+ } catch {
2228
+ resolvedScriptPath = this._scriptPath;
2229
+ }
2230
+ executableDir = path.resolve(
2231
+ path.dirname(resolvedScriptPath),
2232
+ executableDir
2233
+ );
2234
+ }
2235
+ if (executableDir) {
2236
+ let localFile = findFile(executableDir, executableFile);
2237
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2238
+ const legacyName = path.basename(
2239
+ this._scriptPath,
2240
+ path.extname(this._scriptPath)
2241
+ );
2242
+ if (legacyName !== this._name) {
2243
+ localFile = findFile(
2244
+ executableDir,
2245
+ `${legacyName}-${subcommand._name}`
2246
+ );
2247
+ }
2248
+ }
2249
+ executableFile = localFile || executableFile;
2250
+ }
2251
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2252
+ let proc;
2253
+ if (process2.platform !== "win32") {
2254
+ if (launchWithNode) {
2255
+ args.unshift(executableFile);
2256
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2257
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2258
+ } else {
2259
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2260
+ }
2261
+ } else {
2262
+ this._checkForMissingExecutable(
2263
+ executableFile,
2264
+ executableDir,
2265
+ subcommand._name
2266
+ );
2267
+ args.unshift(executableFile);
2268
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2269
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2270
+ }
2271
+ if (!proc.killed) {
2272
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2273
+ signals.forEach((signal) => {
2274
+ process2.on(signal, () => {
2275
+ if (proc.killed === false && proc.exitCode === null) {
2276
+ proc.kill(signal);
2277
+ }
2278
+ });
2279
+ });
2280
+ }
2281
+ const exitCallback = this._exitCallback;
2282
+ proc.on("close", (code) => {
2283
+ code = code ?? 1;
2284
+ if (!exitCallback) {
2285
+ process2.exit(code);
2286
+ } else {
2287
+ exitCallback(
2288
+ new CommanderError2(
2289
+ code,
2290
+ "commander.executeSubCommandAsync",
2291
+ "(close)"
2292
+ )
2293
+ );
2294
+ }
2295
+ });
2296
+ proc.on("error", (err) => {
2297
+ if (err.code === "ENOENT") {
2298
+ this._checkForMissingExecutable(
2299
+ executableFile,
2300
+ executableDir,
2301
+ subcommand._name
2302
+ );
2303
+ } else if (err.code === "EACCES") {
2304
+ throw new Error(`'${executableFile}' not executable`);
2305
+ }
2306
+ if (!exitCallback) {
2307
+ process2.exit(1);
2308
+ } else {
2309
+ const wrappedError = new CommanderError2(
2310
+ 1,
2311
+ "commander.executeSubCommandAsync",
2312
+ "(error)"
2313
+ );
2314
+ wrappedError.nestedError = err;
2315
+ exitCallback(wrappedError);
2316
+ }
2317
+ });
2318
+ this.runningCommand = proc;
2319
+ }
2320
+ /**
2321
+ * @private
2322
+ */
2323
+ _dispatchSubcommand(commandName, operands, unknown) {
2324
+ const subCommand = this._findCommand(commandName);
2325
+ if (!subCommand) this.help({ error: true });
2326
+ subCommand._prepareForParse();
2327
+ let promiseChain;
2328
+ promiseChain = this._chainOrCallSubCommandHook(
2329
+ promiseChain,
2330
+ subCommand,
2331
+ "preSubcommand"
2332
+ );
2333
+ promiseChain = this._chainOrCall(promiseChain, () => {
2334
+ if (subCommand._executableHandler) {
2335
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2336
+ } else {
2337
+ return subCommand._parseCommand(operands, unknown);
2338
+ }
2339
+ });
2340
+ return promiseChain;
2341
+ }
2342
+ /**
2343
+ * Invoke help directly if possible, or dispatch if necessary.
2344
+ * e.g. help foo
2345
+ *
2346
+ * @private
2347
+ */
2348
+ _dispatchHelpCommand(subcommandName) {
2349
+ if (!subcommandName) {
2350
+ this.help();
2351
+ }
2352
+ const subCommand = this._findCommand(subcommandName);
2353
+ if (subCommand && !subCommand._executableHandler) {
2354
+ subCommand.help();
2355
+ }
2356
+ return this._dispatchSubcommand(
2357
+ subcommandName,
2358
+ [],
2359
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2360
+ );
2361
+ }
2362
+ /**
2363
+ * Check this.args against expected this.registeredArguments.
2364
+ *
2365
+ * @private
2366
+ */
2367
+ _checkNumberOfArguments() {
2368
+ this.registeredArguments.forEach((arg, i) => {
2369
+ if (arg.required && this.args[i] == null) {
2370
+ this.missingArgument(arg.name());
2371
+ }
2372
+ });
2373
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2374
+ return;
2375
+ }
2376
+ if (this.args.length > this.registeredArguments.length) {
2377
+ this._excessArguments(this.args);
2378
+ }
2379
+ }
2380
+ /**
2381
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2382
+ *
2383
+ * @private
2384
+ */
2385
+ _processArguments() {
2386
+ const myParseArg = (argument, value, previous) => {
2387
+ let parsedValue = value;
2388
+ if (value !== null && argument.parseArg) {
2389
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2390
+ parsedValue = this._callParseArg(
2391
+ argument,
2392
+ value,
2393
+ previous,
2394
+ invalidValueMessage
2395
+ );
2396
+ }
2397
+ return parsedValue;
2398
+ };
2399
+ this._checkNumberOfArguments();
2400
+ const processedArgs = [];
2401
+ this.registeredArguments.forEach((declaredArg, index) => {
2402
+ let value = declaredArg.defaultValue;
2403
+ if (declaredArg.variadic) {
2404
+ if (index < this.args.length) {
2405
+ value = this.args.slice(index);
2406
+ if (declaredArg.parseArg) {
2407
+ value = value.reduce((processed, v) => {
2408
+ return myParseArg(declaredArg, v, processed);
2409
+ }, declaredArg.defaultValue);
2410
+ }
2411
+ } else if (value === void 0) {
2412
+ value = [];
2413
+ }
2414
+ } else if (index < this.args.length) {
2415
+ value = this.args[index];
2416
+ if (declaredArg.parseArg) {
2417
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2418
+ }
2419
+ }
2420
+ processedArgs[index] = value;
2421
+ });
2422
+ this.processedArgs = processedArgs;
2423
+ }
2424
+ /**
2425
+ * Once we have a promise we chain, but call synchronously until then.
2426
+ *
2427
+ * @param {(Promise|undefined)} promise
2428
+ * @param {Function} fn
2429
+ * @return {(Promise|undefined)}
2430
+ * @private
2431
+ */
2432
+ _chainOrCall(promise, fn) {
2433
+ if (promise?.then && typeof promise.then === "function") {
2434
+ return promise.then(() => fn());
2435
+ }
2436
+ return fn();
2437
+ }
2438
+ /**
2439
+ *
2440
+ * @param {(Promise|undefined)} promise
2441
+ * @param {string} event
2442
+ * @return {(Promise|undefined)}
2443
+ * @private
2444
+ */
2445
+ _chainOrCallHooks(promise, event) {
2446
+ let result = promise;
2447
+ const hooks = [];
2448
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2449
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2450
+ hooks.push({ hookedCommand, callback });
2451
+ });
2452
+ });
2453
+ if (event === "postAction") {
2454
+ hooks.reverse();
2455
+ }
2456
+ hooks.forEach((hookDetail) => {
2457
+ result = this._chainOrCall(result, () => {
2458
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2459
+ });
2460
+ });
2461
+ return result;
2462
+ }
2463
+ /**
2464
+ *
2465
+ * @param {(Promise|undefined)} promise
2466
+ * @param {Command} subCommand
2467
+ * @param {string} event
2468
+ * @return {(Promise|undefined)}
2469
+ * @private
2470
+ */
2471
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2472
+ let result = promise;
2473
+ if (this._lifeCycleHooks[event] !== void 0) {
2474
+ this._lifeCycleHooks[event].forEach((hook) => {
2475
+ result = this._chainOrCall(result, () => {
2476
+ return hook(this, subCommand);
2477
+ });
2478
+ });
2479
+ }
2480
+ return result;
2481
+ }
2482
+ /**
2483
+ * Process arguments in context of this command.
2484
+ * Returns action result, in case it is a promise.
2485
+ *
2486
+ * @private
2487
+ */
2488
+ _parseCommand(operands, unknown) {
2489
+ const parsed = this.parseOptions(unknown);
2490
+ this._parseOptionsEnv();
2491
+ this._parseOptionsImplied();
2492
+ operands = operands.concat(parsed.operands);
2493
+ unknown = parsed.unknown;
2494
+ this.args = operands.concat(unknown);
2495
+ if (operands && this._findCommand(operands[0])) {
2496
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2497
+ }
2498
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2499
+ return this._dispatchHelpCommand(operands[1]);
2500
+ }
2501
+ if (this._defaultCommandName) {
2502
+ this._outputHelpIfRequested(unknown);
2503
+ return this._dispatchSubcommand(
2504
+ this._defaultCommandName,
2505
+ operands,
2506
+ unknown
2507
+ );
2508
+ }
2509
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2510
+ this.help({ error: true });
2511
+ }
2512
+ this._outputHelpIfRequested(parsed.unknown);
2513
+ this._checkForMissingMandatoryOptions();
2514
+ this._checkForConflictingOptions();
2515
+ const checkForUnknownOptions = () => {
2516
+ if (parsed.unknown.length > 0) {
2517
+ this.unknownOption(parsed.unknown[0]);
2518
+ }
2519
+ };
2520
+ const commandEvent = `command:${this.name()}`;
2521
+ if (this._actionHandler) {
2522
+ checkForUnknownOptions();
2523
+ this._processArguments();
2524
+ let promiseChain;
2525
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2526
+ promiseChain = this._chainOrCall(
2527
+ promiseChain,
2528
+ () => this._actionHandler(this.processedArgs)
2529
+ );
2530
+ if (this.parent) {
2531
+ promiseChain = this._chainOrCall(promiseChain, () => {
2532
+ this.parent.emit(commandEvent, operands, unknown);
2533
+ });
2534
+ }
2535
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2536
+ return promiseChain;
2537
+ }
2538
+ if (this.parent?.listenerCount(commandEvent)) {
2539
+ checkForUnknownOptions();
2540
+ this._processArguments();
2541
+ this.parent.emit(commandEvent, operands, unknown);
2542
+ } else if (operands.length) {
2543
+ if (this._findCommand("*")) {
2544
+ return this._dispatchSubcommand("*", operands, unknown);
2545
+ }
2546
+ if (this.listenerCount("command:*")) {
2547
+ this.emit("command:*", operands, unknown);
2548
+ } else if (this.commands.length) {
2549
+ this.unknownCommand();
2550
+ } else {
2551
+ checkForUnknownOptions();
2552
+ this._processArguments();
2553
+ }
2554
+ } else if (this.commands.length) {
2555
+ checkForUnknownOptions();
2556
+ this.help({ error: true });
2557
+ } else {
2558
+ checkForUnknownOptions();
2559
+ this._processArguments();
2560
+ }
2561
+ }
2562
+ /**
2563
+ * Find matching command.
2564
+ *
2565
+ * @private
2566
+ * @return {Command | undefined}
2567
+ */
2568
+ _findCommand(name) {
2569
+ if (!name) return void 0;
2570
+ return this.commands.find(
2571
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2572
+ );
2573
+ }
2574
+ /**
2575
+ * Return an option matching `arg` if any.
2576
+ *
2577
+ * @param {string} arg
2578
+ * @return {Option}
2579
+ * @package
2580
+ */
2581
+ _findOption(arg) {
2582
+ return this.options.find((option) => option.is(arg));
2583
+ }
2584
+ /**
2585
+ * Display an error message if a mandatory option does not have a value.
2586
+ * Called after checking for help flags in leaf subcommand.
2587
+ *
2588
+ * @private
2589
+ */
2590
+ _checkForMissingMandatoryOptions() {
2591
+ this._getCommandAndAncestors().forEach((cmd) => {
2592
+ cmd.options.forEach((anOption) => {
2593
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2594
+ cmd.missingMandatoryOptionValue(anOption);
2595
+ }
2596
+ });
2597
+ });
2598
+ }
2599
+ /**
2600
+ * Display an error message if conflicting options are used together in this.
2601
+ *
2602
+ * @private
2603
+ */
2604
+ _checkForConflictingLocalOptions() {
2605
+ const definedNonDefaultOptions = this.options.filter((option) => {
2606
+ const optionKey = option.attributeName();
2607
+ if (this.getOptionValue(optionKey) === void 0) {
2608
+ return false;
2609
+ }
2610
+ return this.getOptionValueSource(optionKey) !== "default";
2611
+ });
2612
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2613
+ (option) => option.conflictsWith.length > 0
2614
+ );
2615
+ optionsWithConflicting.forEach((option) => {
2616
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2617
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2618
+ );
2619
+ if (conflictingAndDefined) {
2620
+ this._conflictingOption(option, conflictingAndDefined);
2621
+ }
2622
+ });
2623
+ }
2624
+ /**
2625
+ * Display an error message if conflicting options are used together.
2626
+ * Called after checking for help flags in leaf subcommand.
2627
+ *
2628
+ * @private
2629
+ */
2630
+ _checkForConflictingOptions() {
2631
+ this._getCommandAndAncestors().forEach((cmd) => {
2632
+ cmd._checkForConflictingLocalOptions();
2633
+ });
2634
+ }
2635
+ /**
2636
+ * Parse options from `argv` removing known options,
2637
+ * and return argv split into operands and unknown arguments.
2638
+ *
2639
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2640
+ *
2641
+ * Examples:
2642
+ *
2643
+ * argv => operands, unknown
2644
+ * --known kkk op => [op], []
2645
+ * op --known kkk => [op], []
2646
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2647
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2648
+ *
2649
+ * @param {string[]} args
2650
+ * @return {{operands: string[], unknown: string[]}}
2651
+ */
2652
+ parseOptions(args) {
2653
+ const operands = [];
2654
+ const unknown = [];
2655
+ let dest = operands;
2656
+ function maybeOption(arg) {
2657
+ return arg.length > 1 && arg[0] === "-";
2658
+ }
2659
+ const negativeNumberArg = (arg) => {
2660
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2661
+ return !this._getCommandAndAncestors().some(
2662
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2663
+ );
2664
+ };
2665
+ let activeVariadicOption = null;
2666
+ let activeGroup = null;
2667
+ let i = 0;
2668
+ while (i < args.length || activeGroup) {
2669
+ const arg = activeGroup ?? args[i++];
2670
+ activeGroup = null;
2671
+ if (arg === "--") {
2672
+ if (dest === unknown) dest.push(arg);
2673
+ dest.push(...args.slice(i));
2674
+ break;
2675
+ }
2676
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2677
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2678
+ continue;
2679
+ }
2680
+ activeVariadicOption = null;
2681
+ if (maybeOption(arg)) {
2682
+ const option = this._findOption(arg);
2683
+ if (option) {
2684
+ if (option.required) {
2685
+ const value = args[i++];
2686
+ if (value === void 0) this.optionMissingArgument(option);
2687
+ this.emit(`option:${option.name()}`, value);
2688
+ } else if (option.optional) {
2689
+ let value = null;
2690
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2691
+ value = args[i++];
2692
+ }
2693
+ this.emit(`option:${option.name()}`, value);
2694
+ } else {
2695
+ this.emit(`option:${option.name()}`);
2696
+ }
2697
+ activeVariadicOption = option.variadic ? option : null;
2698
+ continue;
2699
+ }
2700
+ }
2701
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2702
+ const option = this._findOption(`-${arg[1]}`);
2703
+ if (option) {
2704
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2705
+ this.emit(`option:${option.name()}`, arg.slice(2));
2706
+ } else {
2707
+ this.emit(`option:${option.name()}`);
2708
+ activeGroup = `-${arg.slice(2)}`;
2709
+ }
2710
+ continue;
2711
+ }
2712
+ }
2713
+ if (/^--[^=]+=/.test(arg)) {
2714
+ const index = arg.indexOf("=");
2715
+ const option = this._findOption(arg.slice(0, index));
2716
+ if (option && (option.required || option.optional)) {
2717
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2718
+ continue;
2719
+ }
2720
+ }
2721
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2722
+ dest = unknown;
2723
+ }
2724
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2725
+ if (this._findCommand(arg)) {
2726
+ operands.push(arg);
2727
+ unknown.push(...args.slice(i));
2728
+ break;
2729
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2730
+ operands.push(arg, ...args.slice(i));
2731
+ break;
2732
+ } else if (this._defaultCommandName) {
2733
+ unknown.push(arg, ...args.slice(i));
2734
+ break;
2735
+ }
2736
+ }
2737
+ if (this._passThroughOptions) {
2738
+ dest.push(arg, ...args.slice(i));
2739
+ break;
2740
+ }
2741
+ dest.push(arg);
2742
+ }
2743
+ return { operands, unknown };
2744
+ }
2745
+ /**
2746
+ * Return an object containing local option values as key-value pairs.
2747
+ *
2748
+ * @return {object}
2749
+ */
2750
+ opts() {
2751
+ if (this._storeOptionsAsProperties) {
2752
+ const result = {};
2753
+ const len = this.options.length;
2754
+ for (let i = 0; i < len; i++) {
2755
+ const key = this.options[i].attributeName();
2756
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2757
+ }
2758
+ return result;
2759
+ }
2760
+ return this._optionValues;
2761
+ }
2762
+ /**
2763
+ * Return an object containing merged local and global option values as key-value pairs.
2764
+ *
2765
+ * @return {object}
2766
+ */
2767
+ optsWithGlobals() {
2768
+ return this._getCommandAndAncestors().reduce(
2769
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2770
+ {}
2771
+ );
2772
+ }
2773
+ /**
2774
+ * Display error message and exit (or call exitOverride).
2775
+ *
2776
+ * @param {string} message
2777
+ * @param {object} [errorOptions]
2778
+ * @param {string} [errorOptions.code] - an id string representing the error
2779
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2780
+ */
2781
+ error(message, errorOptions) {
2782
+ this._outputConfiguration.outputError(
2783
+ `${message}
2784
+ `,
2785
+ this._outputConfiguration.writeErr
2786
+ );
2787
+ if (typeof this._showHelpAfterError === "string") {
2788
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2789
+ `);
2790
+ } else if (this._showHelpAfterError) {
2791
+ this._outputConfiguration.writeErr("\n");
2792
+ this.outputHelp({ error: true });
2793
+ }
2794
+ const config = errorOptions || {};
2795
+ const exitCode = config.exitCode || 1;
2796
+ const code = config.code || "commander.error";
2797
+ this._exit(exitCode, code, message);
2798
+ }
2799
+ /**
2800
+ * Apply any option related environment variables, if option does
2801
+ * not have a value from cli or client code.
2802
+ *
2803
+ * @private
2804
+ */
2805
+ _parseOptionsEnv() {
2806
+ this.options.forEach((option) => {
2807
+ if (option.envVar && option.envVar in process2.env) {
2808
+ const optionKey = option.attributeName();
2809
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2810
+ this.getOptionValueSource(optionKey)
2811
+ )) {
2812
+ if (option.required || option.optional) {
2813
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2814
+ } else {
2815
+ this.emit(`optionEnv:${option.name()}`);
2816
+ }
2817
+ }
2818
+ }
2819
+ });
2820
+ }
2821
+ /**
2822
+ * Apply any implied option values, if option is undefined or default value.
2823
+ *
2824
+ * @private
2825
+ */
2826
+ _parseOptionsImplied() {
2827
+ const dualHelper = new DualOptions(this.options);
2828
+ const hasCustomOptionValue = (optionKey) => {
2829
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2830
+ };
2831
+ this.options.filter(
2832
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2833
+ this.getOptionValue(option.attributeName()),
2834
+ option
2835
+ )
2836
+ ).forEach((option) => {
2837
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2838
+ this.setOptionValueWithSource(
2839
+ impliedKey,
2840
+ option.implied[impliedKey],
2841
+ "implied"
2842
+ );
2843
+ });
2844
+ });
2845
+ }
2846
+ /**
2847
+ * Argument `name` is missing.
2848
+ *
2849
+ * @param {string} name
2850
+ * @private
2851
+ */
2852
+ missingArgument(name) {
2853
+ const message = `error: missing required argument '${name}'`;
2854
+ this.error(message, { code: "commander.missingArgument" });
2855
+ }
2856
+ /**
2857
+ * `Option` is missing an argument.
2858
+ *
2859
+ * @param {Option} option
2860
+ * @private
2861
+ */
2862
+ optionMissingArgument(option) {
2863
+ const message = `error: option '${option.flags}' argument missing`;
2864
+ this.error(message, { code: "commander.optionMissingArgument" });
2865
+ }
2866
+ /**
2867
+ * `Option` does not have a value, and is a mandatory option.
2868
+ *
2869
+ * @param {Option} option
2870
+ * @private
2871
+ */
2872
+ missingMandatoryOptionValue(option) {
2873
+ const message = `error: required option '${option.flags}' not specified`;
2874
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2875
+ }
2876
+ /**
2877
+ * `Option` conflicts with another option.
2878
+ *
2879
+ * @param {Option} option
2880
+ * @param {Option} conflictingOption
2881
+ * @private
2882
+ */
2883
+ _conflictingOption(option, conflictingOption) {
2884
+ const findBestOptionFromValue = (option2) => {
2885
+ const optionKey = option2.attributeName();
2886
+ const optionValue = this.getOptionValue(optionKey);
2887
+ const negativeOption = this.options.find(
2888
+ (target) => target.negate && optionKey === target.attributeName()
2889
+ );
2890
+ const positiveOption = this.options.find(
2891
+ (target) => !target.negate && optionKey === target.attributeName()
2892
+ );
2893
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2894
+ return negativeOption;
2895
+ }
2896
+ return positiveOption || option2;
2897
+ };
2898
+ const getErrorMessage = (option2) => {
2899
+ const bestOption = findBestOptionFromValue(option2);
2900
+ const optionKey = bestOption.attributeName();
2901
+ const source = this.getOptionValueSource(optionKey);
2902
+ if (source === "env") {
2903
+ return `environment variable '${bestOption.envVar}'`;
2904
+ }
2905
+ return `option '${bestOption.flags}'`;
2906
+ };
2907
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2908
+ this.error(message, { code: "commander.conflictingOption" });
2909
+ }
2910
+ /**
2911
+ * Unknown option `flag`.
2912
+ *
2913
+ * @param {string} flag
2914
+ * @private
2915
+ */
2916
+ unknownOption(flag) {
2917
+ if (this._allowUnknownOption) return;
2918
+ let suggestion = "";
2919
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2920
+ let candidateFlags = [];
2921
+ let command = this;
2922
+ do {
2923
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2924
+ candidateFlags = candidateFlags.concat(moreFlags);
2925
+ command = command.parent;
2926
+ } while (command && !command._enablePositionalOptions);
2927
+ suggestion = suggestSimilar(flag, candidateFlags);
2928
+ }
2929
+ const message = `error: unknown option '${flag}'${suggestion}`;
2930
+ this.error(message, { code: "commander.unknownOption" });
2931
+ }
2932
+ /**
2933
+ * Excess arguments, more than expected.
2934
+ *
2935
+ * @param {string[]} receivedArgs
2936
+ * @private
2937
+ */
2938
+ _excessArguments(receivedArgs) {
2939
+ if (this._allowExcessArguments) return;
2940
+ const expected = this.registeredArguments.length;
2941
+ const s = expected === 1 ? "" : "s";
2942
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2943
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2944
+ this.error(message, { code: "commander.excessArguments" });
2945
+ }
2946
+ /**
2947
+ * Unknown command.
2948
+ *
2949
+ * @private
2950
+ */
2951
+ unknownCommand() {
2952
+ const unknownName = this.args[0];
2953
+ let suggestion = "";
2954
+ if (this._showSuggestionAfterError) {
2955
+ const candidateNames = [];
2956
+ this.createHelp().visibleCommands(this).forEach((command) => {
2957
+ candidateNames.push(command.name());
2958
+ if (command.alias()) candidateNames.push(command.alias());
2959
+ });
2960
+ suggestion = suggestSimilar(unknownName, candidateNames);
2961
+ }
2962
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2963
+ this.error(message, { code: "commander.unknownCommand" });
2964
+ }
2965
+ /**
2966
+ * Get or set the program version.
2967
+ *
2968
+ * This method auto-registers the "-V, --version" option which will print the version number.
2969
+ *
2970
+ * You can optionally supply the flags and description to override the defaults.
2971
+ *
2972
+ * @param {string} [str]
2973
+ * @param {string} [flags]
2974
+ * @param {string} [description]
2975
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2976
+ */
2977
+ version(str, flags, description) {
2978
+ if (str === void 0) return this._version;
2979
+ this._version = str;
2980
+ flags = flags || "-V, --version";
2981
+ description = description || "output the version number";
2982
+ const versionOption = this.createOption(flags, description);
2983
+ this._versionOptionName = versionOption.attributeName();
2984
+ this._registerOption(versionOption);
2985
+ this.on("option:" + versionOption.name(), () => {
2986
+ this._outputConfiguration.writeOut(`${str}
2987
+ `);
2988
+ this._exit(0, "commander.version", str);
2989
+ });
2990
+ return this;
2991
+ }
2992
+ /**
2993
+ * Set the description.
2994
+ *
2995
+ * @param {string} [str]
2996
+ * @param {object} [argsDescription]
2997
+ * @return {(string|Command)}
2998
+ */
2999
+ description(str, argsDescription) {
3000
+ if (str === void 0 && argsDescription === void 0)
3001
+ return this._description;
3002
+ this._description = str;
3003
+ if (argsDescription) {
3004
+ this._argsDescription = argsDescription;
3005
+ }
3006
+ return this;
3007
+ }
3008
+ /**
3009
+ * Set the summary. Used when listed as subcommand of parent.
3010
+ *
3011
+ * @param {string} [str]
3012
+ * @return {(string|Command)}
3013
+ */
3014
+ summary(str) {
3015
+ if (str === void 0) return this._summary;
3016
+ this._summary = str;
3017
+ return this;
3018
+ }
3019
+ /**
3020
+ * Set an alias for the command.
3021
+ *
3022
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3023
+ *
3024
+ * @param {string} [alias]
3025
+ * @return {(string|Command)}
3026
+ */
3027
+ alias(alias) {
3028
+ if (alias === void 0) return this._aliases[0];
3029
+ let command = this;
3030
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3031
+ command = this.commands[this.commands.length - 1];
3032
+ }
3033
+ if (alias === command._name)
3034
+ throw new Error("Command alias can't be the same as its name");
3035
+ const matchingCommand = this.parent?._findCommand(alias);
3036
+ if (matchingCommand) {
3037
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3038
+ throw new Error(
3039
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3040
+ );
3041
+ }
3042
+ command._aliases.push(alias);
3043
+ return this;
3044
+ }
3045
+ /**
3046
+ * Set aliases for the command.
3047
+ *
3048
+ * Only the first alias is shown in the auto-generated help.
3049
+ *
3050
+ * @param {string[]} [aliases]
3051
+ * @return {(string[]|Command)}
3052
+ */
3053
+ aliases(aliases) {
3054
+ if (aliases === void 0) return this._aliases;
3055
+ aliases.forEach((alias) => this.alias(alias));
3056
+ return this;
3057
+ }
3058
+ /**
3059
+ * Set / get the command usage `str`.
3060
+ *
3061
+ * @param {string} [str]
3062
+ * @return {(string|Command)}
3063
+ */
3064
+ usage(str) {
3065
+ if (str === void 0) {
3066
+ if (this._usage) return this._usage;
3067
+ const args = this.registeredArguments.map((arg) => {
3068
+ return humanReadableArgName(arg);
3069
+ });
3070
+ return [].concat(
3071
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3072
+ this.commands.length ? "[command]" : [],
3073
+ this.registeredArguments.length ? args : []
3074
+ ).join(" ");
3075
+ }
3076
+ this._usage = str;
3077
+ return this;
3078
+ }
3079
+ /**
3080
+ * Get or set the name of the command.
3081
+ *
3082
+ * @param {string} [str]
3083
+ * @return {(string|Command)}
3084
+ */
3085
+ name(str) {
3086
+ if (str === void 0) return this._name;
3087
+ this._name = str;
3088
+ return this;
3089
+ }
3090
+ /**
3091
+ * Set/get the help group heading for this subcommand in parent command's help.
3092
+ *
3093
+ * @param {string} [heading]
3094
+ * @return {Command | string}
3095
+ */
3096
+ helpGroup(heading) {
3097
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3098
+ this._helpGroupHeading = heading;
3099
+ return this;
3100
+ }
3101
+ /**
3102
+ * Set/get the default help group heading for subcommands added to this command.
3103
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3104
+ *
3105
+ * @example
3106
+ * program.commandsGroup('Development Commands:);
3107
+ * program.command('watch')...
3108
+ * program.command('lint')...
3109
+ * ...
3110
+ *
3111
+ * @param {string} [heading]
3112
+ * @returns {Command | string}
3113
+ */
3114
+ commandsGroup(heading) {
3115
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3116
+ this._defaultCommandGroup = heading;
3117
+ return this;
3118
+ }
3119
+ /**
3120
+ * Set/get the default help group heading for options added to this command.
3121
+ * (This does not override a group set directly on the option using .helpGroup().)
3122
+ *
3123
+ * @example
3124
+ * program
3125
+ * .optionsGroup('Development Options:')
3126
+ * .option('-d, --debug', 'output extra debugging')
3127
+ * .option('-p, --profile', 'output profiling information')
3128
+ *
3129
+ * @param {string} [heading]
3130
+ * @returns {Command | string}
3131
+ */
3132
+ optionsGroup(heading) {
3133
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3134
+ this._defaultOptionGroup = heading;
3135
+ return this;
3136
+ }
3137
+ /**
3138
+ * @param {Option} option
3139
+ * @private
3140
+ */
3141
+ _initOptionGroup(option) {
3142
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3143
+ option.helpGroup(this._defaultOptionGroup);
3144
+ }
3145
+ /**
3146
+ * @param {Command} cmd
3147
+ * @private
3148
+ */
3149
+ _initCommandGroup(cmd) {
3150
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3151
+ cmd.helpGroup(this._defaultCommandGroup);
3152
+ }
3153
+ /**
3154
+ * Set the name of the command from script filename, such as process.argv[1],
3155
+ * or require.main.filename, or __filename.
3156
+ *
3157
+ * (Used internally and public although not documented in README.)
3158
+ *
3159
+ * @example
3160
+ * program.nameFromFilename(require.main.filename);
3161
+ *
3162
+ * @param {string} filename
3163
+ * @return {Command}
3164
+ */
3165
+ nameFromFilename(filename) {
3166
+ this._name = path.basename(filename, path.extname(filename));
3167
+ return this;
3168
+ }
3169
+ /**
3170
+ * Get or set the directory for searching for executable subcommands of this command.
3171
+ *
3172
+ * @example
3173
+ * program.executableDir(__dirname);
3174
+ * // or
3175
+ * program.executableDir('subcommands');
3176
+ *
3177
+ * @param {string} [path]
3178
+ * @return {(string|null|Command)}
3179
+ */
3180
+ executableDir(path2) {
3181
+ if (path2 === void 0) return this._executableDir;
3182
+ this._executableDir = path2;
3183
+ return this;
3184
+ }
3185
+ /**
3186
+ * Return program help documentation.
3187
+ *
3188
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3189
+ * @return {string}
3190
+ */
3191
+ helpInformation(contextOptions) {
3192
+ const helper = this.createHelp();
3193
+ const context = this._getOutputContext(contextOptions);
3194
+ helper.prepareContext({
3195
+ error: context.error,
3196
+ helpWidth: context.helpWidth,
3197
+ outputHasColors: context.hasColors
3198
+ });
3199
+ const text = helper.formatHelp(this, helper);
3200
+ if (context.hasColors) return text;
3201
+ return this._outputConfiguration.stripColor(text);
3202
+ }
3203
+ /**
3204
+ * @typedef HelpContext
3205
+ * @type {object}
3206
+ * @property {boolean} error
3207
+ * @property {number} helpWidth
3208
+ * @property {boolean} hasColors
3209
+ * @property {function} write - includes stripColor if needed
3210
+ *
3211
+ * @returns {HelpContext}
3212
+ * @private
3213
+ */
3214
+ _getOutputContext(contextOptions) {
3215
+ contextOptions = contextOptions || {};
3216
+ const error = !!contextOptions.error;
3217
+ let baseWrite;
3218
+ let hasColors;
3219
+ let helpWidth;
3220
+ if (error) {
3221
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3222
+ hasColors = this._outputConfiguration.getErrHasColors();
3223
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3224
+ } else {
3225
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3226
+ hasColors = this._outputConfiguration.getOutHasColors();
3227
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3228
+ }
3229
+ const write = (str) => {
3230
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3231
+ return baseWrite(str);
3232
+ };
3233
+ return { error, write, hasColors, helpWidth };
3234
+ }
3235
+ /**
3236
+ * Output help information for this command.
3237
+ *
3238
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3239
+ *
3240
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3241
+ */
3242
+ outputHelp(contextOptions) {
3243
+ let deprecatedCallback;
3244
+ if (typeof contextOptions === "function") {
3245
+ deprecatedCallback = contextOptions;
3246
+ contextOptions = void 0;
3247
+ }
3248
+ const outputContext = this._getOutputContext(contextOptions);
3249
+ const eventContext = {
3250
+ error: outputContext.error,
3251
+ write: outputContext.write,
3252
+ command: this
3253
+ };
3254
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3255
+ this.emit("beforeHelp", eventContext);
3256
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3257
+ if (deprecatedCallback) {
3258
+ helpInformation = deprecatedCallback(helpInformation);
3259
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3260
+ throw new Error("outputHelp callback must return a string or a Buffer");
3261
+ }
3262
+ }
3263
+ outputContext.write(helpInformation);
3264
+ if (this._getHelpOption()?.long) {
3265
+ this.emit(this._getHelpOption().long);
3266
+ }
3267
+ this.emit("afterHelp", eventContext);
3268
+ this._getCommandAndAncestors().forEach(
3269
+ (command) => command.emit("afterAllHelp", eventContext)
3270
+ );
3271
+ }
3272
+ /**
3273
+ * You can pass in flags and a description to customise the built-in help option.
3274
+ * Pass in false to disable the built-in help option.
3275
+ *
3276
+ * @example
3277
+ * program.helpOption('-?, --help' 'show help'); // customise
3278
+ * program.helpOption(false); // disable
3279
+ *
3280
+ * @param {(string | boolean)} flags
3281
+ * @param {string} [description]
3282
+ * @return {Command} `this` command for chaining
3283
+ */
3284
+ helpOption(flags, description) {
3285
+ if (typeof flags === "boolean") {
3286
+ if (flags) {
3287
+ if (this._helpOption === null) this._helpOption = void 0;
3288
+ if (this._defaultOptionGroup) {
3289
+ this._initOptionGroup(this._getHelpOption());
3290
+ }
3291
+ } else {
3292
+ this._helpOption = null;
3293
+ }
3294
+ return this;
3295
+ }
3296
+ this._helpOption = this.createOption(
3297
+ flags ?? "-h, --help",
3298
+ description ?? "display help for command"
3299
+ );
3300
+ if (flags || description) this._initOptionGroup(this._helpOption);
3301
+ return this;
3302
+ }
3303
+ /**
3304
+ * Lazy create help option.
3305
+ * Returns null if has been disabled with .helpOption(false).
3306
+ *
3307
+ * @returns {(Option | null)} the help option
3308
+ * @package
3309
+ */
3310
+ _getHelpOption() {
3311
+ if (this._helpOption === void 0) {
3312
+ this.helpOption(void 0, void 0);
3313
+ }
3314
+ return this._helpOption;
3315
+ }
3316
+ /**
3317
+ * Supply your own option to use for the built-in help option.
3318
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3319
+ *
3320
+ * @param {Option} option
3321
+ * @return {Command} `this` command for chaining
3322
+ */
3323
+ addHelpOption(option) {
3324
+ this._helpOption = option;
3325
+ this._initOptionGroup(option);
3326
+ return this;
3327
+ }
3328
+ /**
3329
+ * Output help information and exit.
3330
+ *
3331
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3332
+ *
3333
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3334
+ */
3335
+ help(contextOptions) {
3336
+ this.outputHelp(contextOptions);
3337
+ let exitCode = Number(process2.exitCode ?? 0);
3338
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3339
+ exitCode = 1;
3340
+ }
3341
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3342
+ }
3343
+ /**
3344
+ * // Do a little typing to coordinate emit and listener for the help text events.
3345
+ * @typedef HelpTextEventContext
3346
+ * @type {object}
3347
+ * @property {boolean} error
3348
+ * @property {Command} command
3349
+ * @property {function} write
3350
+ */
3351
+ /**
3352
+ * Add additional text to be displayed with the built-in help.
3353
+ *
3354
+ * Position is 'before' or 'after' to affect just this command,
3355
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3356
+ *
3357
+ * @param {string} position - before or after built-in help
3358
+ * @param {(string | Function)} text - string to add, or a function returning a string
3359
+ * @return {Command} `this` command for chaining
3360
+ */
3361
+ addHelpText(position, text) {
3362
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3363
+ if (!allowedValues.includes(position)) {
3364
+ throw new Error(`Unexpected value for position to addHelpText.
3365
+ Expecting one of '${allowedValues.join("', '")}'`);
3366
+ }
3367
+ const helpEvent = `${position}Help`;
3368
+ this.on(helpEvent, (context) => {
3369
+ let helpStr;
3370
+ if (typeof text === "function") {
3371
+ helpStr = text({ error: context.error, command: context.command });
3372
+ } else {
3373
+ helpStr = text;
3374
+ }
3375
+ if (helpStr) {
3376
+ context.write(`${helpStr}
3377
+ `);
3378
+ }
3379
+ });
3380
+ return this;
3381
+ }
3382
+ /**
3383
+ * Output help information if help flags specified
3384
+ *
3385
+ * @param {Array} args - array of options to search for help flags
3386
+ * @private
3387
+ */
3388
+ _outputHelpIfRequested(args) {
3389
+ const helpOption = this._getHelpOption();
3390
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3391
+ if (helpRequested) {
3392
+ this.outputHelp();
3393
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3394
+ }
3395
+ }
3396
+ };
3397
+ function incrementNodeInspectorPort(args) {
3398
+ return args.map((arg) => {
3399
+ if (!arg.startsWith("--inspect")) {
3400
+ return arg;
3401
+ }
3402
+ let debugOption;
3403
+ let debugHost = "127.0.0.1";
3404
+ let debugPort = "9229";
3405
+ let match;
3406
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3407
+ debugOption = match[1];
3408
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3409
+ debugOption = match[1];
3410
+ if (/^\d+$/.test(match[3])) {
3411
+ debugPort = match[3];
3412
+ } else {
3413
+ debugHost = match[3];
3414
+ }
3415
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3416
+ debugOption = match[1];
3417
+ debugHost = match[3];
3418
+ debugPort = match[4];
3419
+ }
3420
+ if (debugOption && debugPort !== "0") {
3421
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3422
+ }
3423
+ return arg;
3424
+ });
3425
+ }
3426
+ function useColor() {
3427
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3428
+ return false;
3429
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3430
+ return true;
3431
+ return void 0;
3432
+ }
3433
+ exports.Command = Command2;
3434
+ exports.useColor = useColor;
3435
+ }
3436
+ });
3437
+
3438
+ // ../node_modules/commander/index.js
3439
+ var require_commander = __commonJS({
3440
+ "../node_modules/commander/index.js"(exports) {
3441
+ var { Argument: Argument2 } = require_argument();
3442
+ var { Command: Command2 } = require_command();
3443
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3444
+ var { Help: Help2 } = require_help();
3445
+ var { Option: Option2 } = require_option();
3446
+ exports.program = new Command2();
3447
+ exports.createCommand = (name) => new Command2(name);
3448
+ exports.createOption = (flags, description) => new Option2(flags, description);
3449
+ exports.createArgument = (name, description) => new Argument2(name, description);
3450
+ exports.Command = Command2;
3451
+ exports.Option = Option2;
3452
+ exports.Argument = Argument2;
3453
+ exports.Help = Help2;
3454
+ exports.CommanderError = CommanderError2;
3455
+ exports.InvalidArgumentError = InvalidArgumentError2;
3456
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3457
+ }
3458
+ });
3459
+
3460
+ // ../node_modules/commander/esm.mjs
3461
+ var import_index = __toESM(require_commander(), 1);
3462
+ var {
3463
+ program,
3464
+ createCommand,
3465
+ createArgument,
3466
+ createOption,
3467
+ CommanderError,
3468
+ InvalidArgumentError,
3469
+ InvalidOptionArgumentError,
3470
+ // deprecated old name
3471
+ Command,
3472
+ Argument,
3473
+ Option,
3474
+ Help
3475
+ } = import_index.default;
3476
+
3477
+ // ../packages/cli/src/commands/generate/component/component.command.ts
3478
+ import { mkdirSync, writeFileSync, existsSync, rmSync } from "fs";
3479
+ import { join } from "path";
3480
+ function generateComponent(name, path, force) {
3481
+ const dir = join(path, name);
3482
+ if (existsSync(dir)) {
3483
+ if (force) {
3484
+ console.log(`Deleting "${name}"...`);
3485
+ rmSync(dir, { recursive: true, force: true });
3486
+ console.log("\u2714 Component Deleted.");
3487
+ } else {
3488
+ console.error(`\u2716 Directory "${name}" already exists.`);
3489
+ process.exit(1);
3490
+ }
3491
+ }
3492
+ mkdirSync(dir, { recursive: true });
3493
+ const files = [
3494
+ [`${name}.xd.component.ts`, tsTemplate(name)],
3495
+ [`${name}.xd.component.html`, htmlTemplate(name)],
3496
+ [`${name}.xd.component.css`, cssTemplate(name)],
3497
+ [`${name}.xd.component.spec.ts`, specTemplate(name)]
3498
+ ];
3499
+ for (const [filename, content] of files) {
3500
+ writeFileSync(join(dir, filename), content, "utf8");
3501
+ }
3502
+ console.log();
3503
+ console.log(`\u2714 Component "${name}" generated:`);
3504
+ for (const [filename] of files) {
3505
+ console.log(`${name}/${filename}`);
3506
+ }
3507
+ }
3508
+ function tsTemplate(name) {
3509
+ const className = toPascalCase(name);
3510
+ return `import { BaseWebComponent, WebComponent } from '@xaendar/core';
3511
+
3512
+ @WebComponent({
3513
+ selector: '${toKebabCase(name)}',
3514
+ styleUrl: './${name}.xd.component.css',
3515
+ templateUrl: './${name}.xd.component.html'
3516
+ })
3517
+ export class ${className}Component extends BaseWebComponent {
3518
+
3519
+ }`;
3520
+ }
3521
+ function htmlTemplate(name) {
3522
+ return `<p>${name} works!</p>
3523
+ `;
3524
+ }
3525
+ function cssTemplate(_name) {
3526
+ return `/* component styles */
3527
+ `;
3528
+ }
3529
+ function specTemplate(name) {
3530
+ const className = toPascalCase(name);
3531
+ return `
3532
+ import { describe, expect, it } from "vitest";
3533
+ import { ${className}Component } from './${name}.xd.component';
3534
+
3535
+ describe('${className}Component', () => {
3536
+ it('should create', () => {
3537
+ const component = new ${className}Component();
3538
+ expect(component).toBeTruthy();
3539
+ });
3540
+ });
3541
+ `;
3542
+ }
3543
+ function toPascalCase(str) {
3544
+ return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^(.)/, (_, c) => c.toUpperCase());
3545
+ }
3546
+ function toKebabCase(str) {
3547
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
3548
+ }
3549
+
3550
+ // ../packages/cli/src/commands/generate/generate.command.ts
3551
+ function makeGenerateCommand() {
3552
+ const generate = new Command("generate").alias("g").description("Generate Xendar building blocks");
3553
+ generate.command("component <name>").alias("c").option("-p, --path <path>", "Custom path for the generated component (default: current directory)").option("-f, --force", "Force generation deleting current component if already exists").description("Generate a new component (creates <name>/ folder with .ts, .html, .css, .spec.ts)").action((name, options) => {
3554
+ const path = options.path || process.cwd();
3555
+ generateComponent(name, path, !!options.force);
3556
+ });
3557
+ return generate;
3558
+ }
3559
+
3560
+ // ../packages/common/src/models/stack/stack.model.ts
3561
+ var Stack = class {
3562
+ /**
3563
+ * Internal array holding the stack elements, ordered from bottom to top.
3564
+ */
3565
+ _elements = new Array();
3566
+ constructor() {
3567
+ return new Proxy(this, {
3568
+ get(target, prop) {
3569
+ return isNaN(Number(prop)) ? target[prop] : target._elements[Number(prop)];
3570
+ }
3571
+ });
3572
+ }
3573
+ /**
3574
+ * The number of elements currently in the stack.
3575
+ */
3576
+ get length() {
3577
+ return this._elements.length;
3578
+ }
3579
+ /**
3580
+ * A shallow copy of the elements in the stack, ordered from bottom to top.
3581
+ */
3582
+ get values() {
3583
+ return [...this._elements];
3584
+ }
3585
+ /**
3586
+ * Removes and returns the top element of the stack.
3587
+ *
3588
+ * @returns The top element, or `undefined` if the stack is empty.
3589
+ */
3590
+ pop() {
3591
+ return this._elements.pop();
3592
+ }
3593
+ /**
3594
+ * Pushes an element onto the top of the stack.
3595
+ *
3596
+ * @param element - The element to push.
3597
+ * @returns The new length of the stack.
3598
+ */
3599
+ push(element) {
3600
+ return this._elements.push(element);
3601
+ }
3602
+ };
3603
+
3604
+ // ../packages/compiler/src/costants/chars.constants.ts
3605
+ var EOF = 0;
3606
+ var LF = 10;
3607
+ var CR = 13;
3608
+ var SPACE = 32;
3609
+ var LPAREN = 40;
3610
+ var RPAREN = 41;
3611
+ var SLASH = 47;
3612
+ var LESS_THAN = 60;
3613
+ var GREATER_THEN = 62;
3614
+ var AT_SIGN = 64;
3615
+ var GRAVE_ACCENT = 96;
3616
+ var LEFT_BRACE = 123;
3617
+ var RIGHT_BRACE = 125;
3618
+
3619
+ // ../packages/compiler/src/lexer/models/lexer-cursor.model.ts
3620
+ var LexerCursor = class {
3621
+ /**
3622
+ * Creates a new cursor for the given input source.
3623
+ *
3624
+ * @param input Full source string to be tokenized.
3625
+ */
3626
+ constructor(input) {
3627
+ this.input = input;
3628
+ }
3629
+ input;
3630
+ /**
3631
+ * Representation of the current character.
3632
+ *
3633
+ * - `index`: absolute index within the input string
3634
+ * - `code`: Unicode code point of the character
3635
+ * - `value`: actual character value
3636
+ *
3637
+ * An index of `-1` indicates that the cursor has not yet consumed
3638
+ * any character or has reached EOF.
3639
+ */
3640
+ _currentChar = {
3641
+ code: 0,
3642
+ index: -1,
3643
+ value: ""
3644
+ };
3645
+ /**
3646
+ * Returns a read-only snapshot of the current character.
3647
+ */
3648
+ get currentChar() {
3649
+ return this._currentChar;
3650
+ }
3651
+ /**
3652
+ * Cache used by peek operations to avoid re-reading
3653
+ * the same character positions multiple times.
3654
+ *
3655
+ * Key: absolute character index
3656
+ * Value: Unicode code point
3657
+ */
3658
+ _peekCache = /* @__PURE__ */ new Map();
3659
+ /**
3660
+ * Logical position of the cursor in the input.
3661
+ *
3662
+ * - `row`: zero-based line number
3663
+ * - `column`: zero-based column number
3664
+ */
3665
+ _position = {
3666
+ row: 0,
3667
+ column: 0
3668
+ };
3669
+ /**
3670
+ * Returns a read-only snapshot of the current cursor position.
3671
+ */
3672
+ get position() {
3673
+ return this._position;
3674
+ }
3675
+ /**
3676
+ * Advances the cursor by the specified number of characters.
3677
+ *
3678
+ * This method:
3679
+ * - Updates the current character
3680
+ * - Updates row/column position
3681
+ * - Detects line breaks (LF / CR)
3682
+ * - Throws an EOF error when the end of the input is reached
3683
+ *
3684
+ * @param chars Number of characters to consume (must be >= 1)
3685
+ *
3686
+ * @throws Error with cause `EOF` when advancing past input length
3687
+ */
3688
+ advance(chars = 1) {
3689
+ if (chars < 1) {
3690
+ throw new Error(`${chars} is not a valid value. Please enter a number equal or greater than 1`);
3691
+ }
3692
+ const newIndex = this._currentChar.index + chars;
3693
+ if (newIndex >= this.input.length) {
3694
+ this._currentChar.code = EOF;
3695
+ this._currentChar.index = -1;
3696
+ this._currentChar.value = "";
3697
+ this.throwEOFError();
3698
+ } else {
3699
+ if ([LF, CR].includes(this._currentChar.code)) {
3700
+ this._position.row++;
3701
+ this._position.column = 0;
3702
+ } else {
3703
+ this._position.column++;
3704
+ }
3705
+ this._currentChar.index = newIndex;
3706
+ this._currentChar.value = this.input[newIndex];
3707
+ this._currentChar.code = this.input.charCodeAt(newIndex);
3708
+ }
3709
+ }
3710
+ peekMatch(pattern, length) {
3711
+ if (typeof pattern === "string") {
3712
+ const peekedChars = this.peek(pattern.length);
3713
+ for (let i = 0; i < pattern.length; i++) {
3714
+ if (peekedChars[i] !== pattern.charCodeAt(i)) {
3715
+ return false;
3716
+ }
3717
+ }
3718
+ return true;
3719
+ }
3720
+ const start = this._currentChar.index + 1;
3721
+ const slice = this.input.slice(start, start + length);
3722
+ return pattern.test(slice);
3723
+ }
3724
+ peek(charsOrOptions, options) {
3725
+ const cache = this._peekCache;
3726
+ const chars = typeof charsOrOptions === "number" ? charsOrOptions : 1;
3727
+ const offset = (typeof charsOrOptions === "object" ? charsOrOptions : options)?.offset ?? 0;
3728
+ return chars === 1 ? this.peekOneChar(this._currentChar.index + offset + 1, cache) : this.peekMany(chars + offset, cache);
3729
+ }
3730
+ /**
3731
+ * Skips all consecutive space characters from the current position.
3732
+ */
3733
+ skipSpaces() {
3734
+ while (this.peek() === SPACE) {
3735
+ this.advance();
3736
+ }
3737
+ }
3738
+ /**
3739
+ * Peeks multiple characters ahead.
3740
+ */
3741
+ peekMany(chars, cache) {
3742
+ const peekedChars = new Array();
3743
+ const nextCharIndex = this._currentChar.index + 1;
3744
+ for (let i = nextCharIndex; i < nextCharIndex + chars; i++) {
3745
+ peekedChars.push(this.peekOneChar(i, cache));
3746
+ }
3747
+ return peekedChars;
3748
+ }
3749
+ /**
3750
+ * Peeks a single character at the given absolute index.
3751
+ */
3752
+ peekOneChar(index, cache) {
3753
+ if (cache.has(index)) {
3754
+ return cache.get(index);
3755
+ }
3756
+ if (index >= this.input.length) {
3757
+ this.throwEOFError();
3758
+ }
3759
+ const charCode = this.input.charCodeAt(index);
3760
+ cache.set(index, charCode);
3761
+ return charCode;
3762
+ }
3763
+ /**
3764
+ * Throws a standardized EOF error used by the lexer engine
3765
+ * to terminate tokenization.
3766
+ */
3767
+ throwEOFError() {
3768
+ throw new Error("", { cause: EOF });
3769
+ }
3770
+ };
3771
+
3772
+ // ../packages/compiler/src/lexer/models/token-type.enum.ts
3773
+ var TokenType = /* @__PURE__ */ ((TokenType2) => {
3774
+ TokenType2[TokenType2["TEXT"] = 0] = "TEXT";
3775
+ TokenType2[TokenType2["TAG_OPEN_NAME"] = 1] = "TAG_OPEN_NAME";
3776
+ TokenType2[TokenType2["TAG_SELF_CLOSE"] = 2] = "TAG_SELF_CLOSE";
3777
+ TokenType2[TokenType2["TAG_OPEN_END"] = 3] = "TAG_OPEN_END";
3778
+ TokenType2[TokenType2["TAG_CLOSE_NAME"] = 4] = "TAG_CLOSE_NAME";
3779
+ TokenType2[TokenType2["ATTRIBUTE"] = 5] = "ATTRIBUTE";
3780
+ TokenType2[TokenType2["EVENT"] = 6] = "EVENT";
3781
+ TokenType2[TokenType2["INTERPOLATION_LITERAL"] = 7] = "INTERPOLATION_LITERAL";
3782
+ TokenType2[TokenType2["INTERPOLATION_EXPRESSION"] = 8] = "INTERPOLATION_EXPRESSION";
3783
+ TokenType2[TokenType2["IF"] = 9] = "IF";
3784
+ TokenType2[TokenType2["FOR"] = 10] = "FOR";
3785
+ TokenType2[TokenType2["ELSE"] = 11] = "ELSE";
3786
+ TokenType2[TokenType2["SWITCH"] = 12] = "SWITCH";
3787
+ TokenType2[TokenType2["CASE"] = 13] = "CASE";
3788
+ TokenType2[TokenType2["DEFAULT"] = 14] = "DEFAULT";
3789
+ TokenType2[TokenType2["CONDITION"] = 15] = "CONDITION";
3790
+ TokenType2[TokenType2["BLOCK_OPEN"] = 16] = "BLOCK_OPEN";
3791
+ TokenType2[TokenType2["BLOCK_CLOSE"] = 17] = "BLOCK_CLOSE";
3792
+ TokenType2[TokenType2["EOF"] = 18] = "EOF";
3793
+ return TokenType2;
3794
+ })(TokenType || {});
3795
+
3796
+ // ../packages/compiler/src/lexer/states/attribute.state.ts
3797
+ function consumeAttribute(cursor, _context) {
3798
+ let read = true;
3799
+ let attribute = "";
3800
+ let retVal;
3801
+ while (read) {
3802
+ switch (cursor.peek()) {
3803
+ case SPACE:
3804
+ case SLASH:
3805
+ case GREATER_THEN:
3806
+ retVal = {
3807
+ state: "tag-body" /* TAG_BODY */,
3808
+ tokens: [{
3809
+ type: 5 /* ATTRIBUTE */,
3810
+ parts: [attribute]
3811
+ }]
3812
+ };
3813
+ read = false;
3814
+ break;
3815
+ case LEFT_BRACE:
3816
+ retVal = {
3817
+ state: "interpolation" /* INTERPOLATION */,
3818
+ tokens: [{
3819
+ type: 5 /* ATTRIBUTE */,
3820
+ parts: [attribute]
3821
+ }],
3822
+ pushState: true
3823
+ };
3824
+ read = false;
3825
+ break;
3826
+ default:
3827
+ cursor.advance();
3828
+ attribute = `${attribute}${cursor.currentChar.value}`;
3829
+ }
3830
+ }
3831
+ return retVal;
3832
+ }
3833
+
3834
+ // ../packages/compiler/src/lexer/states/event.state.ts
3835
+ function consumeEvent(cursor, _context) {
3836
+ let read = true;
3837
+ let event = "";
3838
+ let retVal;
3839
+ cursor.advance();
3840
+ while (read) {
3841
+ switch (cursor.peek()) {
3842
+ case SPACE:
3843
+ case SLASH:
3844
+ case GREATER_THEN:
3845
+ retVal = {
3846
+ state: "tag-body" /* TAG_BODY */,
3847
+ tokens: [{
3848
+ type: 6 /* EVENT */,
3849
+ parts: [event]
3850
+ }]
3851
+ };
3852
+ read = false;
3853
+ break;
3854
+ default:
3855
+ cursor.advance();
3856
+ event = `${event}${cursor.currentChar.value}`;
3857
+ }
3858
+ }
3859
+ return retVal;
3860
+ }
3861
+
3862
+ // ../packages/compiler/src/lexer/states/flow-control.ts
3863
+ function consumeFlowControl(cursor, _context) {
3864
+ let retVal;
3865
+ cursor.advance();
3866
+ if (cursor.peekMatch("for ")) {
3867
+ cursor.advance(4);
3868
+ retVal = {
3869
+ state: "flow-control-condition" /* FLOW_CONTROL_CONDITION */,
3870
+ tokens: [{
3871
+ type: 10 /* FOR */
3872
+ }],
3873
+ pushState: true
3874
+ };
3875
+ } else if (cursor.peekMatch("if ")) {
3876
+ cursor.advance(2);
3877
+ retVal = {
3878
+ state: "flow-control-condition" /* FLOW_CONTROL_CONDITION */,
3879
+ tokens: [{
3880
+ type: 9 /* IF */
3881
+ }],
3882
+ pushState: true
3883
+ };
3884
+ } else if (cursor.peekMatch("else ")) {
3885
+ cursor.advance(5);
3886
+ retVal = {
3887
+ state: "flow-control-block" /* FLOW_CONTROL_BLOCK */,
3888
+ tokens: [{
3889
+ type: 11 /* ELSE */
3890
+ }],
3891
+ pushState: true
3892
+ };
3893
+ } else if (cursor.peekMatch("switch ")) {
3894
+ cursor.advance(7);
3895
+ retVal = {
3896
+ state: "flow-control-condition" /* FLOW_CONTROL_CONDITION */,
3897
+ tokens: [{
3898
+ type: 12 /* SWITCH */
3899
+ }],
3900
+ pushState: true
3901
+ };
3902
+ } else if (cursor.peekMatch("case ")) {
3903
+ cursor.advance(5);
3904
+ retVal = {
3905
+ state: "flow-control-condition" /* FLOW_CONTROL_CONDITION */,
3906
+ tokens: [{
3907
+ type: 13 /* CASE */
3908
+ }],
3909
+ pushState: true
3910
+ };
3911
+ } else if (cursor.peekMatch("default ")) {
3912
+ cursor.advance(8);
3913
+ retVal = {
3914
+ state: "flow-control-block" /* FLOW_CONTROL_BLOCK */,
3915
+ tokens: [{
3916
+ type: 14 /* DEFAULT */
3917
+ }],
3918
+ pushState: true
3919
+ };
3920
+ }
3921
+ return retVal;
3922
+ }
3923
+
3924
+ // ../packages/compiler/src/lexer/states/flow-control-block.state.ts
3925
+ function consumeFlowControlBlock(cursor, _context) {
3926
+ cursor.skipSpaces();
3927
+ if (cursor.peek() !== LEFT_BRACE) {
3928
+ throw new Error(`Expected '{' but got '${String.fromCharCode(cursor.peek())}' at row ${cursor.position.row}, col ${cursor.position.column}`);
3929
+ }
3930
+ cursor.advance();
3931
+ return {
3932
+ state: "text" /* TEXT */,
3933
+ tokens: [{ type: 16 /* BLOCK_OPEN */ }],
3934
+ pushState: true
3935
+ };
3936
+ }
3937
+
3938
+ // ../packages/compiler/src/lexer/states/flow-control-condition.state.ts
3939
+ function consumeFlowControlCondition(cursor, _context) {
3940
+ cursor.skipSpaces();
3941
+ if (cursor.peek() !== LPAREN) {
3942
+ throw new Error(`Expected '(' but got '${String.fromCharCode(cursor.peek())}' at row ${cursor.position.row}, col ${cursor.position.column}`);
3943
+ }
3944
+ cursor.advance();
3945
+ let expression = "";
3946
+ let depth = 1;
3947
+ while (depth > 0) {
3948
+ const code = cursor.peek();
3949
+ switch (code) {
3950
+ case LPAREN:
3951
+ depth++;
3952
+ cursor.advance();
3953
+ break;
3954
+ case RPAREN:
3955
+ depth--;
3956
+ if (!depth) {
3957
+ cursor.advance();
3958
+ break;
3959
+ }
3960
+ cursor.advance();
3961
+ break;
3962
+ default:
3963
+ cursor.advance();
3964
+ expression = `${expression}${cursor.currentChar.value}`;
3965
+ }
3966
+ }
3967
+ return {
3968
+ state: "flow-control-block" /* FLOW_CONTROL_BLOCK */,
3969
+ tokens: [{
3970
+ type: 15 /* CONDITION */,
3971
+ parts: [expression]
3972
+ }],
3973
+ popState: true
3974
+ };
3975
+ }
3976
+
3977
+ // ../packages/compiler/src/lexer/states/interpolation-expression.state.ts
3978
+ function consumeInterpolationExpression(cursor, context) {
3979
+ let read = true;
3980
+ let interpolation = "";
3981
+ let deep = 1;
3982
+ let retVal;
3983
+ while (read) {
3984
+ switch (cursor.peek()) {
3985
+ case LEFT_BRACE:
3986
+ deep++;
3987
+ interpolation = addCharacter(cursor, interpolation);
3988
+ break;
3989
+ case RIGHT_BRACE:
3990
+ deep--;
3991
+ if (deep === 0) {
3992
+ cursor.advance();
3993
+ const previousState = context.history.pop();
3994
+ let state;
3995
+ switch (previousState) {
3996
+ case "attribute" /* ATTRIBUTE */:
3997
+ state = "tag-body" /* TAG_BODY */;
3998
+ break;
3999
+ case "text" /* TEXT */:
4000
+ state = "text" /* TEXT */;
4001
+ }
4002
+ ;
4003
+ retVal = {
4004
+ state,
4005
+ tokens: [{
4006
+ type: 8 /* INTERPOLATION_EXPRESSION */,
4007
+ parts: [interpolation]
4008
+ }],
4009
+ popState: true
4010
+ };
4011
+ read = false;
4012
+ } else {
4013
+ interpolation = addCharacter(cursor, interpolation);
4014
+ }
4015
+ break;
4016
+ default:
4017
+ interpolation = addCharacter(cursor, interpolation);
4018
+ }
4019
+ }
4020
+ return retVal;
4021
+ }
4022
+ function addCharacter(cursor, interpolation) {
4023
+ cursor.advance(1);
4024
+ return `${interpolation}${cursor.currentChar.value}`;
4025
+ }
4026
+
4027
+ // ../packages/compiler/src/lexer/states/interpolation-literal.state.ts
4028
+ function consumeInterpolationliteral(cursor, context) {
4029
+ let read = true;
4030
+ let interpolation = "";
4031
+ let retVal;
4032
+ cursor.advance();
4033
+ while (read) {
4034
+ switch (cursor.peek()) {
4035
+ case GRAVE_ACCENT:
4036
+ cursor.advance();
4037
+ if (cursor.peek() === RIGHT_BRACE) {
4038
+ cursor.advance();
4039
+ const previousState = context.history.pop();
4040
+ let state;
4041
+ switch (previousState) {
4042
+ case "attribute" /* ATTRIBUTE */:
4043
+ state = "tag-body" /* TAG_BODY */;
4044
+ break;
4045
+ case "text" /* TEXT */:
4046
+ state = "text" /* TEXT */;
4047
+ }
4048
+ ;
4049
+ retVal = {
4050
+ state,
4051
+ tokens: [{
4052
+ type: 7 /* INTERPOLATION_LITERAL */,
4053
+ parts: [interpolation]
4054
+ }],
4055
+ popState: true
4056
+ };
4057
+ read = false;
4058
+ } else {
4059
+ interpolation = `${interpolation}${cursor.currentChar.value}`;
4060
+ }
4061
+ break;
4062
+ default:
4063
+ interpolation = addCharacter2(cursor, interpolation);
4064
+ }
4065
+ }
4066
+ return retVal;
4067
+ }
4068
+ function addCharacter2(cursor, interpolation) {
4069
+ cursor.advance(1);
4070
+ return `${interpolation}${cursor.currentChar.value}`;
4071
+ }
4072
+
4073
+ // ../packages/compiler/src/utils/chars.utils.ts
4074
+ function isNotBlank(str) {
4075
+ return /\S/.test(str);
4076
+ }
4077
+ function isJSIdentifierStart(code) {
4078
+ return code >= 65 && code <= 90 || // A-Z
4079
+ code >= 97 && code <= 122 || // a-z
4080
+ code === 36 || // $
4081
+ code === 95;
4082
+ }
4083
+
4084
+ // ../packages/compiler/src/lexer/states/interpolation.state.ts
4085
+ function consumeInterpolation(cursor, _context) {
4086
+ let retVal;
4087
+ cursor.advance();
4088
+ cursor.skipSpaces();
4089
+ const nextChar = cursor.peek();
4090
+ if (nextChar === GRAVE_ACCENT) {
4091
+ retVal = { state: "interpolation-literal" /* INTERPOLATION_LITERAL */ };
4092
+ } else if (isJSIdentifierStart(nextChar)) {
4093
+ retVal = { state: "interpolation-expression" /* INTERPOLATION_EXPRESSION */ };
4094
+ } else {
4095
+ throw new Error(`Unrecognized First Character ${String.fromCharCode(nextChar)} in interpolation`);
4096
+ }
4097
+ return retVal;
4098
+ }
4099
+
4100
+ // ../packages/compiler/src/lexer/states/tag-body.state.ts
4101
+ function consumeTagBody(cursor, _context) {
4102
+ let read = true;
4103
+ let retVal;
4104
+ while (read) {
4105
+ const nextChar = cursor.peek();
4106
+ switch (nextChar) {
4107
+ case AT_SIGN:
4108
+ retVal = {
4109
+ state: "event" /* EVENT */
4110
+ };
4111
+ read = false;
4112
+ break;
4113
+ case SPACE:
4114
+ cursor.advance();
4115
+ break;
4116
+ case GREATER_THEN:
4117
+ case SLASH:
4118
+ retVal = {
4119
+ state: "tag-open-end" /* TAG_OPEN_END */
4120
+ };
4121
+ read = false;
4122
+ break;
4123
+ default:
4124
+ retVal = {
4125
+ state: "attribute" /* ATTRIBUTE */
4126
+ };
4127
+ read = false;
4128
+ }
4129
+ }
4130
+ return retVal;
4131
+ }
4132
+
4133
+ // ../packages/compiler/src/lexer/states/tag-close.state.ts
4134
+ function consumeTagClose(cursor, _context) {
4135
+ let read = true;
4136
+ let tagName = "";
4137
+ let retVal;
4138
+ cursor.advance(2);
4139
+ cursor.skipSpaces();
4140
+ while (read) {
4141
+ switch (cursor.peek()) {
4142
+ case GREATER_THEN:
4143
+ cursor.advance();
4144
+ retVal = {
4145
+ state: "text" /* TEXT */,
4146
+ tokens: [{
4147
+ type: 4 /* TAG_CLOSE_NAME */,
4148
+ parts: [tagName]
4149
+ }]
4150
+ };
4151
+ read = false;
4152
+ break;
4153
+ case SPACE:
4154
+ throw new Error("Tag Close Name cannot contains spaces");
4155
+ default:
4156
+ cursor.advance();
4157
+ tagName = `${tagName}${cursor.currentChar.value}`;
4158
+ }
4159
+ }
4160
+ return retVal;
4161
+ }
4162
+
4163
+ // ../packages/compiler/src/lexer/states/tag-open-end.state.ts
4164
+ function consumeTagOpenEnd(cursor, _context) {
4165
+ let retVal;
4166
+ if (cursor.peek() === GREATER_THEN) {
4167
+ cursor.advance();
4168
+ retVal = {
4169
+ state: "text" /* TEXT */,
4170
+ tokens: [{
4171
+ type: 3 /* TAG_OPEN_END */,
4172
+ parts: []
4173
+ }]
4174
+ };
4175
+ } else {
4176
+ cursor.advance();
4177
+ const nextChar = cursor.peek();
4178
+ if (nextChar === GREATER_THEN) {
4179
+ cursor.advance();
4180
+ retVal = {
4181
+ state: "text" /* TEXT */,
4182
+ tokens: [{
4183
+ type: 2 /* TAG_SELF_CLOSE */,
4184
+ parts: []
4185
+ }]
4186
+ };
4187
+ } else {
4188
+ throw new Error(`Unexpected character ${nextChar} for closing tag.
4189
+ Expected />
4190
+ Read of /${String.fromCharCode(nextChar)}
4191
+ At line ${cursor.position.row + 1} col ${cursor.position.column + 1}`);
4192
+ }
4193
+ }
4194
+ return retVal;
4195
+ }
4196
+
4197
+ // ../packages/compiler/src/lexer/states/tag-open-name.state.ts
4198
+ function consumeTagOpenName(cursor, _context) {
4199
+ let read = true;
4200
+ let tagName = "";
4201
+ let retVal;
4202
+ cursor.advance();
4203
+ cursor.skipSpaces();
4204
+ while (read) {
4205
+ switch (cursor.peek()) {
4206
+ case SPACE:
4207
+ case SLASH:
4208
+ case GREATER_THEN:
4209
+ retVal = {
4210
+ state: "tag-body" /* TAG_BODY */,
4211
+ tokens: [{
4212
+ type: 1 /* TAG_OPEN_NAME */,
4213
+ parts: [tagName]
4214
+ }]
4215
+ };
4216
+ read = false;
4217
+ break;
4218
+ default:
4219
+ cursor.advance();
4220
+ tagName = `${tagName}${cursor.currentChar.value}`;
4221
+ }
4222
+ }
4223
+ return retVal;
4224
+ }
4225
+
4226
+ // ../packages/compiler/src/lexer/states/text.state.ts
4227
+ function consumeText(cursor, context) {
4228
+ let read = true;
4229
+ let text = "";
4230
+ let retVal;
4231
+ while (read) {
4232
+ switch (cursor.peek()) {
4233
+ case LESS_THAN:
4234
+ const nextState = cursor.peek(1, { offset: 1 }) === SLASH ? "tag-close" /* TAG_CLOSE */ : "tag-open-name" /* TAG_OPEN_NAME */;
4235
+ retVal = { state: nextState };
4236
+ read = false;
4237
+ break;
4238
+ case LEFT_BRACE:
4239
+ retVal = {
4240
+ state: "interpolation" /* INTERPOLATION */,
4241
+ pushState: true
4242
+ };
4243
+ read = false;
4244
+ break;
4245
+ case AT_SIGN:
4246
+ retVal = {
4247
+ state: "flow-control" /* FLOW_CONTROL */
4248
+ };
4249
+ read = false;
4250
+ break;
4251
+ case RIGHT_BRACE:
4252
+ if (context.history[context.history.length - 1] === "flow-control-block" /* FLOW_CONTROL_BLOCK */) {
4253
+ cursor.advance();
4254
+ retVal = {
4255
+ state: "text" /* TEXT */,
4256
+ tokens: [{ type: 17 /* BLOCK_CLOSE */ }],
4257
+ popState: true
4258
+ };
4259
+ read = false;
4260
+ } else {
4261
+ cursor.advance();
4262
+ text = `${text}${cursor.currentChar.value}`;
4263
+ }
4264
+ break;
4265
+ case LF:
4266
+ case CR:
4267
+ cursor.advance();
4268
+ break;
4269
+ default:
4270
+ cursor.advance();
4271
+ text = `${text}${cursor.currentChar.value}`;
4272
+ }
4273
+ }
4274
+ retVal.tokens ??= isNotBlank(text) ? [{ type: 0 /* TEXT */, parts: [text] }] : void 0;
4275
+ return retVal;
4276
+ }
4277
+
4278
+ // ../packages/compiler/src/lexer/lexer.ts
4279
+ var Lexer = class {
4280
+ /**
4281
+ * Creates a new Cursor instance for the given template content.
4282
+ *
4283
+ * @param input The full template text that the cursor will navigate.
4284
+ */
4285
+ constructor(input) {
4286
+ this.input = input;
4287
+ this._cursor = new LexerCursor(this.input);
4288
+ }
4289
+ input;
4290
+ _cursor;
4291
+ _state = "start" /* START */;
4292
+ _stack = new Stack();
4293
+ _tokens = new Array();
4294
+ _states = {
4295
+ ["start" /* START */]: consumeText,
4296
+ ["text" /* TEXT */]: consumeText,
4297
+ ["tag-open-name" /* TAG_OPEN_NAME */]: consumeTagOpenName,
4298
+ ["tag-body" /* TAG_BODY */]: consumeTagBody,
4299
+ ["tag-open-end" /* TAG_OPEN_END */]: consumeTagOpenEnd,
4300
+ ["tag-close" /* TAG_CLOSE */]: consumeTagClose,
4301
+ ["attribute" /* ATTRIBUTE */]: consumeAttribute,
4302
+ ["flow-control" /* FLOW_CONTROL */]: consumeFlowControl,
4303
+ ["flow-control-condition" /* FLOW_CONTROL_CONDITION */]: consumeFlowControlCondition,
4304
+ ["flow-control-block" /* FLOW_CONTROL_BLOCK */]: consumeFlowControlBlock,
4305
+ ["event" /* EVENT */]: consumeEvent,
4306
+ ["interpolation" /* INTERPOLATION */]: consumeInterpolation,
4307
+ ["interpolation-expression" /* INTERPOLATION_EXPRESSION */]: consumeInterpolationExpression,
4308
+ ["interpolation-literal" /* INTERPOLATION_LITERAL */]: consumeInterpolationliteral
4309
+ };
4310
+ tokenize() {
4311
+ let eof = false;
4312
+ while (!eof) {
4313
+ try {
4314
+ const transitionFunction = this._states[this._state];
4315
+ const { state, tokens, popState, pushState } = transitionFunction(this._cursor, { history: this._stack.values });
4316
+ if (tokens?.length) {
4317
+ this._tokens.push(...tokens);
4318
+ }
4319
+ if (pushState) {
4320
+ this._stack.push(this._state);
4321
+ }
4322
+ if (popState) {
4323
+ this._stack.pop();
4324
+ }
4325
+ this._state = state;
4326
+ } catch (err) {
4327
+ const error = err;
4328
+ if (error.cause === EOF) {
4329
+ eof = true;
4330
+ } else {
4331
+ throw err;
4332
+ }
4333
+ }
4334
+ }
4335
+ return this._tokens;
4336
+ }
4337
+ };
4338
+
4339
+ // ../packages/compiler/src/parser/models/parser-cursor.model.ts
4340
+ var ParserCursor = class {
4341
+ /**
4342
+ * Creates a new ParserCursor for the given token array.
4343
+ *
4344
+ * @param _tokens Array of tokens to navigate.
4345
+ */
4346
+ constructor(_tokens) {
4347
+ this._tokens = _tokens;
4348
+ }
4349
+ _tokens;
4350
+ /**
4351
+ * Representation of the current token.
4352
+ *
4353
+ * - `index`: absolute index within the token array
4354
+ * - `value`: current token object (or EOF token)
4355
+ *
4356
+ * An index of `-1` indicates that the cursor has not
4357
+ * yet consumed any token or has reached EOF.
4358
+ */
4359
+ _currentToken = {
4360
+ value: { type: 18 /* EOF */ },
4361
+ index: -1
4362
+ };
4363
+ /**
4364
+ * Returns a read-only snapshot of the current token.
4365
+ */
4366
+ get currentToken() {
4367
+ return this._currentToken;
4368
+ }
4369
+ /**
4370
+ * Advances the cursor by the specified number of tokens.
4371
+ *
4372
+ * Updates the current token and index.
4373
+ *
4374
+ * @param chars Number of tokens to advance (must be >= 1)
4375
+ *
4376
+ * @throws Error with cause `EOF` when advancing past the end
4377
+ */
4378
+ advance(chars = 1) {
4379
+ if (chars < 1) {
4380
+ throw new Error(`${chars} is not a valid value. Please enter a number equal or greater than 1`);
4381
+ }
4382
+ const newIndex = this._currentToken.index + chars;
4383
+ if (newIndex >= this._tokens.length) {
4384
+ this._currentToken.value = { type: 18 /* EOF */ };
4385
+ this._currentToken.index = -1;
4386
+ this.throwEOFError();
4387
+ } else {
4388
+ this._currentToken.index = newIndex;
4389
+ this._currentToken.value = this._tokens[newIndex];
4390
+ }
4391
+ }
4392
+ peek(charsOrOptions, options) {
4393
+ const tokens = typeof charsOrOptions === "number" ? charsOrOptions : 1;
4394
+ const offset = (typeof charsOrOptions === "object" ? charsOrOptions : options)?.offset ?? 0;
4395
+ return tokens === 1 ? this.peekOneToken(this._currentToken.index + offset + 1) : this.peekMany(tokens + offset);
4396
+ }
4397
+ /**
4398
+ * Peeks multiple tokens ahead.
4399
+ */
4400
+ peekMany(chars) {
4401
+ const peekedTokens = [];
4402
+ const nextTokenIndex = this._currentToken.index + 1;
4403
+ for (let i = nextTokenIndex; i < nextTokenIndex + chars; i++) {
4404
+ peekedTokens.push(this.peekOneToken(i));
4405
+ }
4406
+ return peekedTokens;
4407
+ }
4408
+ /**
4409
+ * Peeks a single token at the given absolute index.
4410
+ */
4411
+ peekOneToken(index) {
4412
+ if (index >= this._tokens.length) {
4413
+ this.throwEOFError();
4414
+ }
4415
+ return this._tokens[index];
4416
+ }
4417
+ /**
4418
+ * Throws a standardized EOF error used by the parser
4419
+ * to terminate token consumption.
4420
+ */
4421
+ throwEOFError() {
4422
+ throw new Error("", { cause: EOF });
4423
+ }
4424
+ };
4425
+
4426
+ // ../packages/compiler/src/parser/parser.ts
4427
+ var Parser = class {
4428
+ /**
4429
+ * Creates a new Parser instance.
4430
+ *
4431
+ * @param tokens Array of tokens produced by the Lexer
4432
+ */
4433
+ constructor(tokens) {
4434
+ this.tokens = tokens;
4435
+ this._cursor = new ParserCursor(this.tokens);
4436
+ }
4437
+ tokens;
4438
+ /** Internal cursor for navigating tokens */
4439
+ _cursor;
4440
+ /**
4441
+ * Entry point for parsing the token stream into AST nodes.
4442
+ *
4443
+ * @returns Array of top-level AST nodes
4444
+ */
4445
+ parse() {
4446
+ let eof = false;
4447
+ const nodes = [];
4448
+ while (!eof) {
4449
+ try {
4450
+ nodes.push(this.parseNode());
4451
+ } catch (err) {
4452
+ const error = err;
4453
+ if (error.cause === EOF) {
4454
+ eof = true;
4455
+ } else {
4456
+ throw err;
4457
+ }
4458
+ }
4459
+ }
4460
+ return nodes;
4461
+ }
4462
+ /**
4463
+ * Parses the next AST node based on the current token.
4464
+ *
4465
+ * @returns Parsed AST node
4466
+ * @throws Error if an unexpected token is encountered
4467
+ */
4468
+ parseNode() {
4469
+ const token = this._cursor.peek();
4470
+ switch (token.type) {
4471
+ case 0 /* TEXT */:
4472
+ return this.parseText(token);
4473
+ case 8 /* INTERPOLATION_EXPRESSION */:
4474
+ case 7 /* INTERPOLATION_LITERAL */:
4475
+ return this.parseInterpolation(token);
4476
+ case 1 /* TAG_OPEN_NAME */:
4477
+ return this.parseElement(token);
4478
+ case 9 /* IF */:
4479
+ return this.parseIfControlFlow(token);
4480
+ case 10 /* FOR */:
4481
+ return this.parseForControlFlow(token);
4482
+ case 12 /* SWITCH */:
4483
+ return this.parseSwitchControlFlow(token);
4484
+ default:
4485
+ throw this.error(`Unexpected token ${TokenType[token.type]}`);
4486
+ }
4487
+ }
4488
+ /**
4489
+ * Parses an @if block, including an optional @else branch.
4490
+ *
4491
+ * Expected token sequence:
4492
+ * IF → CONDITION → BLOCK_OPEN → ...children... → BLOCK_CLOSE
4493
+ * (optionally followed by: ELSE → BLOCK_OPEN → ...children... → BLOCK_CLOSE)
4494
+ */
4495
+ parseIfControlFlow(_token) {
4496
+ this._cursor.advance();
4497
+ const conditionToken = this._cursor.peek();
4498
+ if (conditionToken.type !== 15 /* CONDITION */) {
4499
+ throw this.error(`Expected CONDITION after IF, got ${TokenType[conditionToken.type]}`);
4500
+ }
4501
+ const condition = conditionToken.parts[0];
4502
+ this._cursor.advance();
4503
+ this._cursor.advance();
4504
+ const consequent = this.parseBlockChildren();
4505
+ let alternate = null;
4506
+ const next = this._cursor.peek();
4507
+ if (next.type === 11 /* ELSE */) {
4508
+ this._cursor.advance();
4509
+ this._cursor.advance();
4510
+ const elseChildren = this.parseBlockChildren();
4511
+ alternate = { type: 4 /* Else */, children: elseChildren };
4512
+ }
4513
+ return { type: 3 /* If */, condition, consequent, alternate };
4514
+ }
4515
+ /**
4516
+ * Parses a @for block.
4517
+ *
4518
+ * Expected token sequence:
4519
+ * FOR → CONDITION → BLOCK_OPEN → ...children... → BLOCK_CLOSE
4520
+ */
4521
+ parseForControlFlow(_token) {
4522
+ this._cursor.advance();
4523
+ const conditionToken = this._cursor.peek();
4524
+ if (conditionToken.type !== 15 /* CONDITION */) {
4525
+ throw this.error(`Expected CONDITION after FOR, got ${TokenType[conditionToken.type]}`);
4526
+ }
4527
+ const expression = conditionToken.parts[0];
4528
+ this._cursor.advance();
4529
+ this._cursor.advance();
4530
+ const children = this.parseBlockChildren();
4531
+ return { type: 5 /* For */, expression, children };
4532
+ }
4533
+ /**
4534
+ * Parses a @switch block containing @case and @default branches.
4535
+ *
4536
+ * Expected token sequence:
4537
+ * SWITCH → CONDITION → BLOCK_OPEN
4538
+ * (CASE → CONDITION → BLOCK_OPEN → ...children... → BLOCK_CLOSE)*
4539
+ * (DEFAULT → BLOCK_OPEN → ...children... → BLOCK_CLOSE)?
4540
+ * BLOCK_CLOSE
4541
+ */
4542
+ parseSwitchControlFlow(_token) {
4543
+ this._cursor.advance();
4544
+ const conditionToken = this._cursor.peek();
4545
+ if (conditionToken.type !== 15 /* CONDITION */) {
4546
+ throw this.error(`Expected CONDITION after SWITCH, got ${TokenType[conditionToken.type]}`);
4547
+ }
4548
+ const expression = conditionToken.parts[0];
4549
+ this._cursor.advance();
4550
+ this._cursor.advance();
4551
+ const cases = [];
4552
+ while (this._cursor.peek().type !== 17 /* BLOCK_CLOSE */) {
4553
+ const t = this._cursor.peek();
4554
+ if (t.type === 13 /* CASE */) {
4555
+ this._cursor.advance();
4556
+ const caseCondition = this._cursor.peek();
4557
+ if (caseCondition.type !== 15 /* CONDITION */) {
4558
+ throw this.error(`Expected CONDITION after CASE`);
4559
+ }
4560
+ const caseExpr = caseCondition.parts[0];
4561
+ this._cursor.advance();
4562
+ this._cursor.advance();
4563
+ cases.push({ type: 7 /* Case */, condition: caseExpr, children: this.parseBlockChildren() });
4564
+ } else if (t.type === 14 /* DEFAULT */) {
4565
+ this._cursor.advance();
4566
+ this._cursor.advance();
4567
+ cases.push({ type: 7 /* Case */, condition: null, children: this.parseBlockChildren() });
4568
+ } else {
4569
+ break;
4570
+ }
4571
+ }
4572
+ this._cursor.advance();
4573
+ return { type: 6 /* Switch */, expression, cases };
4574
+ }
4575
+ /**
4576
+ * Parses child nodes until a BLOCK_CLOSE token is encountered.
4577
+ * Consumes the BLOCK_CLOSE before returning.
4578
+ */
4579
+ parseBlockChildren() {
4580
+ const children = [];
4581
+ while (this._cursor.peek().type !== 17 /* BLOCK_CLOSE */) {
4582
+ children.push(this.parseNode());
4583
+ }
4584
+ this._cursor.advance();
4585
+ return children;
4586
+ }
4587
+ /**
4588
+ * Parses a text token into a TextNode.
4589
+ */
4590
+ parseText(token) {
4591
+ this._cursor.advance();
4592
+ return {
4593
+ type: 1 /* Text */,
4594
+ value: token.parts[0]
4595
+ };
4596
+ }
4597
+ /**
4598
+ * Parses an interpolation token into an InterpolationNode.
4599
+ */
4600
+ parseInterpolation(token) {
4601
+ this._cursor.advance();
4602
+ return {
4603
+ type: 2 /* Interpolation */,
4604
+ expression: token.parts[0]
4605
+ };
4606
+ }
4607
+ /**
4608
+ * Parses an element starting from a TAG_OPEN_NAME token.
4609
+ * Handles attributes, events, children, and tag closure.
4610
+ */
4611
+ parseElement(token) {
4612
+ this._cursor.advance();
4613
+ const tagName = token.parts[0];
4614
+ const attributes = new Array();
4615
+ const events = new Array();
4616
+ let read = true;
4617
+ while (read) {
4618
+ const token2 = this._cursor.peek();
4619
+ switch (token2.type) {
4620
+ case 5 /* ATTRIBUTE */:
4621
+ attributes.push(this.parseAttribute(token2));
4622
+ break;
4623
+ case 6 /* EVENT */:
4624
+ events.push(this.parseEvent(token2));
4625
+ break;
4626
+ default:
4627
+ read = false;
4628
+ }
4629
+ }
4630
+ if (this._cursor.peek().type === 3 /* TAG_OPEN_END */) {
4631
+ this._cursor.advance();
4632
+ }
4633
+ if (this._cursor.peek().type === 2 /* TAG_SELF_CLOSE */) {
4634
+ this._cursor.advance();
4635
+ return {
4636
+ type: 0 /* Element */,
4637
+ tagName,
4638
+ attributes,
4639
+ events,
4640
+ children: []
4641
+ };
4642
+ }
4643
+ const children = [];
4644
+ while (!this.isTagClose(tagName)) {
4645
+ children.push(this.parseNode());
4646
+ }
4647
+ this._cursor.advance();
4648
+ return {
4649
+ type: 0 /* Element */,
4650
+ tagName,
4651
+ attributes,
4652
+ events,
4653
+ children
4654
+ };
4655
+ }
4656
+ /**
4657
+ * Parses an attribute token into an AttributeNode.
4658
+ * Supports literal values and interpolations as attribute values.
4659
+ */
4660
+ parseAttribute(token) {
4661
+ this._cursor.advance();
4662
+ const raw = token.parts[0];
4663
+ if (!raw.includes("=")) {
4664
+ return { name: raw, value: "true" };
4665
+ }
4666
+ const [name, value] = raw.split("=");
4667
+ if (!name || !value) {
4668
+ throw this.error(`Invalid attribute format: ${raw}`);
4669
+ }
4670
+ const nextToken = this._cursor.peek();
4671
+ if (nextToken.type === 8 /* INTERPOLATION_EXPRESSION */ || nextToken.type === 7 /* INTERPOLATION_LITERAL */) {
4672
+ return {
4673
+ name,
4674
+ value: this.parseInterpolation(nextToken)
4675
+ };
4676
+ }
4677
+ return {
4678
+ name,
4679
+ value: value.replace(/^['']|['']$/g, "")
4680
+ };
4681
+ }
4682
+ /**
4683
+ * Parses an event token into an EventNode.
4684
+ */
4685
+ parseEvent(token) {
4686
+ this._cursor.advance();
4687
+ const raw = token.parts[0];
4688
+ const [name, value] = raw.split("=");
4689
+ if (!name || !value) {
4690
+ throw this.error(`Invalid event format: ${raw}`);
4691
+ }
4692
+ return {
4693
+ name,
4694
+ handler: value.replace(/^[""]|[""]$/g, "")
4695
+ };
4696
+ }
4697
+ /**
4698
+ * Checks whether the next token is a closing tag matching the given name.
4699
+ */
4700
+ isTagClose(tagName) {
4701
+ const nextToken = this._cursor.peek();
4702
+ return nextToken.type === 4 /* TAG_CLOSE_NAME */ && nextToken.parts[0] === tagName;
4703
+ }
4704
+ /**
4705
+ * Creates a parser error with a consistent prefix.
4706
+ */
4707
+ error(message) {
4708
+ return new Error(`[Parser] ${message}`);
4709
+ }
4710
+ };
4711
+
4712
+ // ../packages/compiler/src/render-generator/render-generator.model.ts
4713
+ function generateRenderFunction(ast, componentVar = "this") {
4714
+ return [
4715
+ `
4716
+ const shadow = ${componentVar}.shadowRoot!;
4717
+ `,
4718
+ ...ast.map((node, i) => processNode(node, `node${i}`, componentVar, "shadow")).flat()
4719
+ ].join("\n");
4720
+ }
4721
+ function processNode(node, varName, componentVar, parentVar) {
4722
+ switch (node.type) {
4723
+ case 1 /* Text */:
4724
+ case 2 /* Interpolation */:
4725
+ return processTextAndInterpolation(node, varName, componentVar, parentVar);
4726
+ case 0 /* Element */:
4727
+ return processElement(node, varName, componentVar, parentVar);
4728
+ case 3 /* If */:
4729
+ return processIf(node, varName, componentVar, parentVar);
4730
+ case 5 /* For */:
4731
+ return processFor(node, varName, componentVar, parentVar);
4732
+ case 6 /* Switch */:
4733
+ return processSwitch(node, varName, componentVar, parentVar);
4734
+ default:
4735
+ return [];
4736
+ }
4737
+ }
4738
+ function processTextAndInterpolation(node, varName, componentVar, parentVar) {
4739
+ const textValue = node.type === 1 /* Text */ ? JSON.stringify(node.value) : resolveExpression(node.expression, componentVar);
4740
+ return [
4741
+ `const ${varName} = document.createTextNode(${textValue});`,
4742
+ `${parentVar}.appendChild(${varName});`
4743
+ ];
4744
+ }
4745
+ function processElement(node, varName, componentVar, parentVar) {
4746
+ return [
4747
+ `const ${varName} = document.createElement("${node.tagName}");`,
4748
+ ...node.attributes?.map((attr) => `${varName}.setAttribute('${attr.name}', ${typeof attr.value === "string" ? attr.value : `${componentVar}.${attr.value.expression}`});`) || [],
4749
+ ...node.events?.map((event) => `${varName}.addEventListener("${event.name}", ${componentVar}.${event.handler}.bind(${componentVar}));`) || [],
4750
+ `${parentVar}.appendChild(${varName});`,
4751
+ ...node.children.map((child, i) => processNode(child, `${varName}_c${i}`, componentVar, varName)).flat()
4752
+ ];
4753
+ }
4754
+ function processIf(node, varName, componentVar, parentVar) {
4755
+ const code = [
4756
+ `if (${resolveExpression(node.condition, componentVar)}) {`,
4757
+ ...node.consequent.map((child, idx) => indent(...processNode(child, `${varName}_t${idx}`, componentVar, parentVar))).flat(),
4758
+ "}"
4759
+ ];
4760
+ const alt = node.alternate;
4761
+ if (alt) {
4762
+ code[code.length - 1] += " else {";
4763
+ code.push(
4764
+ ...alt.children.map((child, idx) => indent(...processNode(child, `${varName}_e${idx}`, componentVar, parentVar))).flat(),
4765
+ "}"
4766
+ );
4767
+ }
4768
+ return code;
4769
+ }
4770
+ function processFor(node, varName, componentVar, parentVar) {
4771
+ const iterExpr = resolveForExpression(node.expression, componentVar);
4772
+ return [
4773
+ `for (${iterExpr}) {`,
4774
+ ...node.children.map((child, idx) => indent(...processNode(child, `${varName}_f${idx}`, componentVar, parentVar))).flat(),
4775
+ "}"
4776
+ ];
4777
+ }
4778
+ function processSwitch(node, varName, componentVar, parentVar) {
4779
+ return [
4780
+ `switch (${resolveExpression(node.expression, componentVar)}) {`,
4781
+ ...node.cases.map((caseNode) => [
4782
+ ...indent(
4783
+ `${!caseNode.condition ? "default" : `case ${caseNode.condition}`}: {`,
4784
+ ...caseNode.children.map((child, i) => indent(...processNode(child, `${varName}_s${i}_${i}`, componentVar, parentVar))).flat(),
4785
+ `${indent("break;")}`,
4786
+ `}`
4787
+ )
4788
+ ]).flat(),
4789
+ "}"
4790
+ ];
4791
+ }
4792
+ function resolveForExpression(expression, componentVar) {
4793
+ const match = expression.match(/^let\s+(\w+)\s+of\s+(\w+)$/);
4794
+ if (!match) {
4795
+ throw new Error(`String "${expression}" does not match the structure "let X of Y"`);
4796
+ }
4797
+ const [, X, Y] = match;
4798
+ return `const ${X} of this.${Y}`;
4799
+ }
4800
+ function resolveExpression(expression, componentVar) {
4801
+ return expression.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g, (match) => match === componentVar ? match : `${componentVar}.${match}`);
4802
+ }
4803
+ function indent(...lines) {
4804
+ return lines.map((line) => ` ${line}`);
4805
+ }
4806
+
4807
+ // ../packages/cli/src/commands/compile/compile.command.ts
4808
+ import { readFileSync, writeFileSync as writeFileSync2 } from "fs";
4809
+ import { basename, dirname, extname, resolve } from "path";
4810
+ function compileFile(inputPath, outputPath) {
4811
+ const absInput = resolve(process.cwd(), inputPath);
4812
+ const absOutput = outputPath ? resolve(process.cwd(), outputPath) : resolve(dirname(absInput), `${basename(absInput, extname(absInput))}.render.js`);
4813
+ let source;
4814
+ try {
4815
+ source = readFileSync(absInput, "utf8");
4816
+ } catch {
4817
+ console.error(`\u2716 Cannot read file: ${absInput}`);
4818
+ process.exit(1);
4819
+ }
4820
+ const result = compile(source);
4821
+ writeFileSync2(absOutput, result, "utf8");
4822
+ console.log(`\u2714 Compiled: ${inputPath} \u2192 ${absOutput}`);
4823
+ }
4824
+ function compile(source) {
4825
+ const tokens = new Lexer(source).tokenize();
4826
+ const ast = new Parser(tokens).parse();
4827
+ return generateRenderFunction(ast);
4828
+ }
4829
+
4830
+ // ../packages/cli/src/commands/compile/compile.ts
4831
+ function makeCompileCommand() {
4832
+ return new Command("compile").alias("co").description("Compile a Xendar HTML template into a render function").argument("<input>", "Path to the .xd.component.html template file").option("-o, --output <path>", "Path for the emitted output file (default: <input>.render.js)").action((input, options) => {
4833
+ compileFile(input, options.output);
4834
+ });
4835
+ }
4836
+
4837
+ // ../packages/cli/src/index.ts
4838
+ program.name("xd").description("Xendar CLI").version("0.2.0");
4839
+ program.addCommand(makeGenerateCommand());
4840
+ program.addCommand(makeCompileCommand());
4841
+ program.parse();
4842
+ //# sourceMappingURL=index.js.map