@xaendar/cli 0.4.4 → 0.4.6

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 (2) hide show
  1. package/dist/cli.js +51 -3636
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,3503 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
-
5
- // ../node_modules/commander/lib/error.js
6
- var CommanderError = class extends Error {
7
- /**
8
- * Constructs the CommanderError class
9
- * @param {number} exitCode suggested exit code which could be used with process.exit
10
- * @param {string} code an id string representing the error
11
- * @param {string} message human-readable description of the error
12
- */
13
- constructor(exitCode, code, message) {
14
- super(message);
15
- Error.captureStackTrace(this, this.constructor);
16
- this.name = this.constructor.name;
17
- this.code = code;
18
- this.exitCode = exitCode;
19
- this.nestedError = void 0;
20
- }
21
- };
22
- var InvalidArgumentError = class extends CommanderError {
23
- /**
24
- * Constructs the InvalidArgumentError class
25
- * @param {string} [message] explanation of why argument is invalid
26
- */
27
- constructor(message) {
28
- super(1, "commander.invalidArgument", message);
29
- Error.captureStackTrace(this, this.constructor);
30
- this.name = this.constructor.name;
31
- }
32
- };
33
-
34
- // ../node_modules/commander/lib/argument.js
35
- var Argument = class {
36
- /**
37
- * Initialize a new command argument with the given name and description.
38
- * The default is that the argument is required, and you can explicitly
39
- * indicate this with <> around the name. Put [] around the name for an optional argument.
40
- *
41
- * @param {string} name
42
- * @param {string} [description]
43
- */
44
- constructor(name, description) {
45
- this.description = description || "";
46
- this.variadic = false;
47
- this.parseArg = void 0;
48
- this.defaultValue = void 0;
49
- this.defaultValueDescription = void 0;
50
- this.argChoices = void 0;
51
- switch (name[0]) {
52
- case "<":
53
- this.required = true;
54
- this._name = name.slice(1, -1);
55
- break;
56
- case "[":
57
- this.required = false;
58
- this._name = name.slice(1, -1);
59
- break;
60
- default:
61
- this.required = true;
62
- this._name = name;
63
- break;
64
- }
65
- if (this._name.endsWith("...")) {
66
- this.variadic = true;
67
- this._name = this._name.slice(0, -3);
68
- }
69
- }
70
- /**
71
- * Return argument name.
72
- *
73
- * @return {string}
74
- */
75
- name() {
76
- return this._name;
77
- }
78
- /**
79
- * @package
80
- */
81
- _collectValue(value, previous) {
82
- if (previous === this.defaultValue || !Array.isArray(previous)) {
83
- return [value];
84
- }
85
- previous.push(value);
86
- return previous;
87
- }
88
- /**
89
- * Set the default value, and optionally supply the description to be displayed in the help.
90
- *
91
- * @param {*} value
92
- * @param {string} [description]
93
- * @return {Argument}
94
- */
95
- default(value, description) {
96
- this.defaultValue = value;
97
- this.defaultValueDescription = description;
98
- return this;
99
- }
100
- /**
101
- * Set the custom handler for processing CLI command arguments into argument values.
102
- *
103
- * @param {Function} [fn]
104
- * @return {Argument}
105
- */
106
- argParser(fn) {
107
- this.parseArg = fn;
108
- return this;
109
- }
110
- /**
111
- * Only allow argument value to be one of choices.
112
- *
113
- * @param {string[]} values
114
- * @return {Argument}
115
- */
116
- choices(values) {
117
- this.argChoices = values.slice();
118
- this.parseArg = (arg, previous) => {
119
- if (!this.argChoices.includes(arg)) {
120
- throw new InvalidArgumentError(
121
- `Allowed choices are ${this.argChoices.join(", ")}.`
122
- );
123
- }
124
- if (this.variadic) {
125
- return this._collectValue(arg, previous);
126
- }
127
- return arg;
128
- };
129
- return this;
130
- }
131
- /**
132
- * Make argument required.
133
- *
134
- * @returns {Argument}
135
- */
136
- argRequired() {
137
- this.required = true;
138
- return this;
139
- }
140
- /**
141
- * Make argument optional.
142
- *
143
- * @returns {Argument}
144
- */
145
- argOptional() {
146
- this.required = false;
147
- return this;
148
- }
149
- };
150
- function humanReadableArgName(arg) {
151
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
152
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
153
- }
154
-
155
- // ../node_modules/commander/lib/command.js
156
- import { EventEmitter } from "events";
157
- import childProcess from "child_process";
158
- import path from "path";
159
- import fs from "fs";
160
- import process2 from "process";
161
- import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
162
-
163
- // ../node_modules/commander/lib/help.js
164
- import { stripVTControlCharacters } from "util";
165
- var Help = class {
166
- constructor() {
167
- this.helpWidth = void 0;
168
- this.minWidthToWrap = 40;
169
- this.sortSubcommands = false;
170
- this.sortOptions = false;
171
- this.showGlobalOptions = false;
172
- }
173
- /**
174
- * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
175
- * and just before calling `formatHelp()`.
176
- *
177
- * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
178
- *
179
- * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
180
- */
181
- prepareContext(contextOptions) {
182
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
183
- }
184
- /**
185
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
186
- *
187
- * @param {Command} cmd
188
- * @returns {Command[]}
189
- */
190
- visibleCommands(cmd) {
191
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
192
- const helpCommand = cmd._getHelpCommand();
193
- if (helpCommand && !helpCommand._hidden) {
194
- visibleCommands.push(helpCommand);
195
- }
196
- if (this.sortSubcommands) {
197
- visibleCommands.sort((a, b) => {
198
- return a.name().localeCompare(b.name());
199
- });
200
- }
201
- return visibleCommands;
202
- }
203
- /**
204
- * Compare options for sort.
205
- *
206
- * @param {Option} a
207
- * @param {Option} b
208
- * @returns {number}
209
- */
210
- compareOptions(a, b) {
211
- const getSortKey = (option) => {
212
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
213
- };
214
- return getSortKey(a).localeCompare(getSortKey(b));
215
- }
216
- /**
217
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
218
- *
219
- * @param {Command} cmd
220
- * @returns {Option[]}
221
- */
222
- visibleOptions(cmd) {
223
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
224
- const helpOption = cmd._getHelpOption();
225
- if (helpOption && !helpOption.hidden) {
226
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
227
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
228
- if (!removeShort && !removeLong) {
229
- visibleOptions.push(helpOption);
230
- } else if (helpOption.long && !removeLong) {
231
- visibleOptions.push(
232
- cmd.createOption(helpOption.long, helpOption.description)
233
- );
234
- } else if (helpOption.short && !removeShort) {
235
- visibleOptions.push(
236
- cmd.createOption(helpOption.short, helpOption.description)
237
- );
238
- }
239
- }
240
- if (this.sortOptions) {
241
- visibleOptions.sort(this.compareOptions);
242
- }
243
- return visibleOptions;
244
- }
245
- /**
246
- * Get an array of the visible global options. (Not including help.)
247
- *
248
- * @param {Command} cmd
249
- * @returns {Option[]}
250
- */
251
- visibleGlobalOptions(cmd) {
252
- if (!this.showGlobalOptions) return [];
253
- const globalOptions = [];
254
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
255
- const visibleOptions = ancestorCmd.options.filter(
256
- (option) => !option.hidden
257
- );
258
- globalOptions.push(...visibleOptions);
259
- }
260
- if (this.sortOptions) {
261
- globalOptions.sort(this.compareOptions);
262
- }
263
- return globalOptions;
264
- }
265
- /**
266
- * Get an array of the arguments if any have a description.
267
- *
268
- * @param {Command} cmd
269
- * @returns {Argument[]}
270
- */
271
- visibleArguments(cmd) {
272
- if (cmd._argsDescription) {
273
- cmd.registeredArguments.forEach((argument) => {
274
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
275
- });
276
- }
277
- if (cmd.registeredArguments.find((argument) => argument.description)) {
278
- return cmd.registeredArguments;
279
- }
280
- return [];
281
- }
282
- /**
283
- * Get the command term to show in the list of subcommands.
284
- *
285
- * @param {Command} cmd
286
- * @returns {string}
287
- */
288
- subcommandTerm(cmd) {
289
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
290
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
291
- (args ? " " + args : "");
292
- }
293
- /**
294
- * Get the option term to show in the list of options.
295
- *
296
- * @param {Option} option
297
- * @returns {string}
298
- */
299
- optionTerm(option) {
300
- return option.flags;
301
- }
302
- /**
303
- * Get the argument term to show in the list of arguments.
304
- *
305
- * @param {Argument} argument
306
- * @returns {string}
307
- */
308
- argumentTerm(argument) {
309
- return argument.name();
310
- }
311
- /**
312
- * Get the longest command term length.
313
- *
314
- * @param {Command} cmd
315
- * @param {Help} helper
316
- * @returns {number}
317
- */
318
- longestSubcommandTermLength(cmd, helper) {
319
- return helper.visibleCommands(cmd).reduce((max, command) => {
320
- return Math.max(
321
- max,
322
- this.displayWidth(
323
- helper.styleSubcommandTerm(helper.subcommandTerm(command))
324
- )
325
- );
326
- }, 0);
327
- }
328
- /**
329
- * Get the longest option term length.
330
- *
331
- * @param {Command} cmd
332
- * @param {Help} helper
333
- * @returns {number}
334
- */
335
- longestOptionTermLength(cmd, helper) {
336
- return helper.visibleOptions(cmd).reduce((max, option) => {
337
- return Math.max(
338
- max,
339
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
340
- );
341
- }, 0);
342
- }
343
- /**
344
- * Get the longest global option term length.
345
- *
346
- * @param {Command} cmd
347
- * @param {Help} helper
348
- * @returns {number}
349
- */
350
- longestGlobalOptionTermLength(cmd, helper) {
351
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
352
- return Math.max(
353
- max,
354
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
355
- );
356
- }, 0);
357
- }
358
- /**
359
- * Get the longest argument term length.
360
- *
361
- * @param {Command} cmd
362
- * @param {Help} helper
363
- * @returns {number}
364
- */
365
- longestArgumentTermLength(cmd, helper) {
366
- return helper.visibleArguments(cmd).reduce((max, argument) => {
367
- return Math.max(
368
- max,
369
- this.displayWidth(
370
- helper.styleArgumentTerm(helper.argumentTerm(argument))
371
- )
372
- );
373
- }, 0);
374
- }
375
- /**
376
- * Get the command usage to be displayed at the top of the built-in help.
377
- *
378
- * @param {Command} cmd
379
- * @returns {string}
380
- */
381
- commandUsage(cmd) {
382
- let cmdName = cmd._name;
383
- if (cmd._aliases[0]) {
384
- cmdName = cmdName + "|" + cmd._aliases[0];
385
- }
386
- let ancestorCmdNames = "";
387
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
388
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
389
- }
390
- return ancestorCmdNames + cmdName + " " + cmd.usage();
391
- }
392
- /**
393
- * Get the description for the command.
394
- *
395
- * @param {Command} cmd
396
- * @returns {string}
397
- */
398
- commandDescription(cmd) {
399
- return cmd.description();
400
- }
401
- /**
402
- * Get the subcommand summary to show in the list of subcommands.
403
- * (Fallback to description for backwards compatibility.)
404
- *
405
- * @param {Command} cmd
406
- * @returns {string}
407
- */
408
- subcommandDescription(cmd) {
409
- return cmd.summary() || cmd.description();
410
- }
411
- /**
412
- * Get the option description to show in the list of options.
413
- *
414
- * @param {Option} option
415
- * @return {string}
416
- */
417
- optionDescription(option) {
418
- const extraInfo = [];
419
- if (option.argChoices) {
420
- extraInfo.push(
421
- // use stringify to match the display of the default value
422
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
423
- );
424
- }
425
- if (option.defaultValue !== void 0) {
426
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
427
- if (showDefault) {
428
- extraInfo.push(
429
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
430
- );
431
- }
432
- }
433
- if (option.presetArg !== void 0 && option.optional) {
434
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
435
- }
436
- if (option.envVar !== void 0) {
437
- extraInfo.push(`env: ${option.envVar}`);
438
- }
439
- if (extraInfo.length > 0) {
440
- const extraDescription = `(${extraInfo.join(", ")})`;
441
- if (option.description) {
442
- return `${option.description} ${extraDescription}`;
443
- }
444
- return extraDescription;
445
- }
446
- return option.description;
447
- }
448
- /**
449
- * Get the argument description to show in the list of arguments.
450
- *
451
- * @param {Argument} argument
452
- * @return {string}
453
- */
454
- argumentDescription(argument) {
455
- const extraInfo = [];
456
- if (argument.argChoices) {
457
- extraInfo.push(
458
- // use stringify to match the display of the default value
459
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
460
- );
461
- }
462
- if (argument.defaultValue !== void 0) {
463
- extraInfo.push(
464
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
465
- );
466
- }
467
- if (extraInfo.length > 0) {
468
- const extraDescription = `(${extraInfo.join(", ")})`;
469
- if (argument.description) {
470
- return `${argument.description} ${extraDescription}`;
471
- }
472
- return extraDescription;
473
- }
474
- return argument.description;
475
- }
476
- /**
477
- * Format a list of items, given a heading and an array of formatted items.
478
- *
479
- * @param {string} heading
480
- * @param {string[]} items
481
- * @param {Help} helper
482
- * @returns string[]
483
- */
484
- formatItemList(heading, items, helper) {
485
- if (items.length === 0) return [];
486
- return [helper.styleTitle(heading), ...items, ""];
487
- }
488
- /**
489
- * Group items by their help group heading.
490
- *
491
- * @param {Command[] | Option[]} unsortedItems
492
- * @param {Command[] | Option[]} visibleItems
493
- * @param {Function} getGroup
494
- * @returns {Map<string, Command[] | Option[]>}
495
- */
496
- groupItems(unsortedItems, visibleItems, getGroup) {
497
- const result = /* @__PURE__ */ new Map();
498
- unsortedItems.forEach((item) => {
499
- const group = getGroup(item);
500
- if (!result.has(group)) result.set(group, []);
501
- });
502
- visibleItems.forEach((item) => {
503
- const group = getGroup(item);
504
- if (!result.has(group)) {
505
- result.set(group, []);
506
- }
507
- result.get(group).push(item);
508
- });
509
- return result;
510
- }
511
- /**
512
- * Generate the built-in help text.
513
- *
514
- * @param {Command} cmd
515
- * @param {Help} helper
516
- * @returns {string}
517
- */
518
- formatHelp(cmd, helper) {
519
- const termWidth = helper.padWidth(cmd, helper);
520
- const helpWidth = helper.helpWidth ?? 80;
521
- function callFormatItem(term, description) {
522
- return helper.formatItem(term, termWidth, description, helper);
523
- }
524
- let output = [
525
- `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
526
- ""
527
- ];
528
- const commandDescription = helper.commandDescription(cmd);
529
- if (commandDescription.length > 0) {
530
- output = output.concat([
531
- helper.boxWrap(
532
- helper.styleCommandDescription(commandDescription),
533
- helpWidth
534
- ),
535
- ""
536
- ]);
537
- }
538
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
539
- return callFormatItem(
540
- helper.styleArgumentTerm(helper.argumentTerm(argument)),
541
- helper.styleArgumentDescription(helper.argumentDescription(argument))
542
- );
543
- });
544
- output = output.concat(
545
- this.formatItemList("Arguments:", argumentList, helper)
546
- );
547
- const optionGroups = this.groupItems(
548
- cmd.options,
549
- helper.visibleOptions(cmd),
550
- (option) => option.helpGroupHeading ?? "Options:"
551
- );
552
- optionGroups.forEach((options, group) => {
553
- const optionList = options.map((option) => {
554
- return callFormatItem(
555
- helper.styleOptionTerm(helper.optionTerm(option)),
556
- helper.styleOptionDescription(helper.optionDescription(option))
557
- );
558
- });
559
- output = output.concat(this.formatItemList(group, optionList, helper));
560
- });
561
- if (helper.showGlobalOptions) {
562
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
563
- return callFormatItem(
564
- helper.styleOptionTerm(helper.optionTerm(option)),
565
- helper.styleOptionDescription(helper.optionDescription(option))
566
- );
567
- });
568
- output = output.concat(
569
- this.formatItemList("Global Options:", globalOptionList, helper)
570
- );
571
- }
572
- const commandGroups = this.groupItems(
573
- cmd.commands,
574
- helper.visibleCommands(cmd),
575
- (sub) => sub.helpGroup() || "Commands:"
576
- );
577
- commandGroups.forEach((commands, group) => {
578
- const commandList = commands.map((sub) => {
579
- return callFormatItem(
580
- helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
581
- helper.styleSubcommandDescription(helper.subcommandDescription(sub))
582
- );
583
- });
584
- output = output.concat(this.formatItemList(group, commandList, helper));
585
- });
586
- return output.join("\n");
587
- }
588
- /**
589
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
590
- *
591
- * @param {string} str
592
- * @returns {number}
593
- */
594
- displayWidth(str) {
595
- return stripVTControlCharacters(str).length;
596
- }
597
- /**
598
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
599
- *
600
- * @param {string} str
601
- * @returns {string}
602
- */
603
- styleTitle(str) {
604
- return str;
605
- }
606
- styleUsage(str) {
607
- return str.split(" ").map((word) => {
608
- if (word === "[options]") return this.styleOptionText(word);
609
- if (word === "[command]") return this.styleSubcommandText(word);
610
- if (word[0] === "[" || word[0] === "<")
611
- return this.styleArgumentText(word);
612
- return this.styleCommandText(word);
613
- }).join(" ");
614
- }
615
- styleCommandDescription(str) {
616
- return this.styleDescriptionText(str);
617
- }
618
- styleOptionDescription(str) {
619
- return this.styleDescriptionText(str);
620
- }
621
- styleSubcommandDescription(str) {
622
- return this.styleDescriptionText(str);
623
- }
624
- styleArgumentDescription(str) {
625
- return this.styleDescriptionText(str);
626
- }
627
- styleDescriptionText(str) {
628
- return str;
629
- }
630
- styleOptionTerm(str) {
631
- return this.styleOptionText(str);
632
- }
633
- styleSubcommandTerm(str) {
634
- return str.split(" ").map((word) => {
635
- if (word === "[options]") return this.styleOptionText(word);
636
- if (word[0] === "[" || word[0] === "<")
637
- return this.styleArgumentText(word);
638
- return this.styleSubcommandText(word);
639
- }).join(" ");
640
- }
641
- styleArgumentTerm(str) {
642
- return this.styleArgumentText(str);
643
- }
644
- styleOptionText(str) {
645
- return str;
646
- }
647
- styleArgumentText(str) {
648
- return str;
649
- }
650
- styleSubcommandText(str) {
651
- return str;
652
- }
653
- styleCommandText(str) {
654
- return str;
655
- }
656
- /**
657
- * Calculate the pad width from the maximum term length.
658
- *
659
- * @param {Command} cmd
660
- * @param {Help} helper
661
- * @returns {number}
662
- */
663
- padWidth(cmd, helper) {
664
- return Math.max(
665
- helper.longestOptionTermLength(cmd, helper),
666
- helper.longestGlobalOptionTermLength(cmd, helper),
667
- helper.longestSubcommandTermLength(cmd, helper),
668
- helper.longestArgumentTermLength(cmd, helper)
669
- );
670
- }
671
- /**
672
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
673
- *
674
- * @param {string} str
675
- * @returns {boolean}
676
- */
677
- preformatted(str) {
678
- return /\n[^\S\r\n]/.test(str);
679
- }
680
- /**
681
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
682
- *
683
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
684
- * TTT DDD DDDD
685
- * DD DDD
686
- *
687
- * @param {string} term
688
- * @param {number} termWidth
689
- * @param {string} description
690
- * @param {Help} helper
691
- * @returns {string}
692
- */
693
- formatItem(term, termWidth, description, helper) {
694
- const itemIndent = 2;
695
- const itemIndentStr = " ".repeat(itemIndent);
696
- if (!description) return itemIndentStr + term;
697
- const paddedTerm = term.padEnd(
698
- termWidth + term.length - helper.displayWidth(term)
699
- );
700
- const spacerWidth = 2;
701
- const helpWidth = this.helpWidth ?? 80;
702
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
703
- let formattedDescription;
704
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
705
- formattedDescription = description;
706
- } else {
707
- const wrappedDescription = helper.boxWrap(description, remainingWidth);
708
- formattedDescription = wrappedDescription.replace(
709
- /\n/g,
710
- "\n" + " ".repeat(termWidth + spacerWidth)
711
- );
712
- }
713
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
714
- ${itemIndentStr}`);
715
- }
716
- /**
717
- * Wrap a string at whitespace, preserving existing line breaks.
718
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
719
- *
720
- * @param {string} str
721
- * @param {number} width
722
- * @returns {string}
723
- */
724
- boxWrap(str, width) {
725
- if (width < this.minWidthToWrap) return str;
726
- const rawLines = str.split(/\r\n|\n/);
727
- const chunkPattern = /[\s]*[^\s]+/g;
728
- const wrappedLines = [];
729
- rawLines.forEach((line) => {
730
- const chunks = line.match(chunkPattern);
731
- if (chunks === null) {
732
- wrappedLines.push("");
733
- return;
734
- }
735
- let sumChunks = [chunks.shift()];
736
- let sumWidth = this.displayWidth(sumChunks[0]);
737
- chunks.forEach((chunk) => {
738
- const visibleWidth = this.displayWidth(chunk);
739
- if (sumWidth + visibleWidth <= width) {
740
- sumChunks.push(chunk);
741
- sumWidth += visibleWidth;
742
- return;
743
- }
744
- wrappedLines.push(sumChunks.join(""));
745
- const nextChunk = chunk.trimStart();
746
- sumChunks = [nextChunk];
747
- sumWidth = this.displayWidth(nextChunk);
748
- });
749
- wrappedLines.push(sumChunks.join(""));
750
- });
751
- return wrappedLines.join("\n");
752
- }
753
- };
754
-
755
- // ../node_modules/commander/lib/option.js
756
- var Option = class {
757
- /**
758
- * Initialize a new `Option` with the given `flags` and `description`.
759
- *
760
- * @param {string} flags
761
- * @param {string} [description]
762
- */
763
- constructor(flags, description) {
764
- this.flags = flags;
765
- this.description = description || "";
766
- this.required = flags.includes("<");
767
- this.optional = flags.includes("[");
768
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
769
- this.mandatory = false;
770
- const optionFlags = splitOptionFlags(flags);
771
- this.short = optionFlags.shortFlag;
772
- this.long = optionFlags.longFlag;
773
- this.negate = false;
774
- if (this.long) {
775
- this.negate = this.long.startsWith("--no-");
776
- }
777
- this.defaultValue = void 0;
778
- this.defaultValueDescription = void 0;
779
- this.presetArg = void 0;
780
- this.envVar = void 0;
781
- this.parseArg = void 0;
782
- this.hidden = false;
783
- this.argChoices = void 0;
784
- this.conflictsWith = [];
785
- this.implied = void 0;
786
- this.helpGroupHeading = void 0;
787
- }
788
- /**
789
- * Set the default value, and optionally supply the description to be displayed in the help.
790
- *
791
- * @param {*} value
792
- * @param {string} [description]
793
- * @return {Option}
794
- */
795
- default(value, description) {
796
- this.defaultValue = value;
797
- this.defaultValueDescription = description;
798
- return this;
799
- }
800
- /**
801
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
802
- * The custom processing (parseArg) is called.
803
- *
804
- * @example
805
- * new Option('--color').default('GREYSCALE').preset('RGB');
806
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
807
- *
808
- * @param {*} arg
809
- * @return {Option}
810
- */
811
- preset(arg) {
812
- this.presetArg = arg;
813
- return this;
814
- }
815
- /**
816
- * Add option name(s) that conflict with this option.
817
- * An error will be displayed if conflicting options are found during parsing.
818
- *
819
- * @example
820
- * new Option('--rgb').conflicts('cmyk');
821
- * new Option('--js').conflicts(['ts', 'jsx']);
822
- *
823
- * @param {(string | string[])} names
824
- * @return {Option}
825
- */
826
- conflicts(names) {
827
- this.conflictsWith = this.conflictsWith.concat(names);
828
- return this;
829
- }
830
- /**
831
- * Specify implied option values for when this option is set and the implied options are not.
832
- *
833
- * The custom processing (parseArg) is not called on the implied values.
834
- *
835
- * @example
836
- * program
837
- * .addOption(new Option('--log', 'write logging information to file'))
838
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
839
- *
840
- * @param {object} impliedOptionValues
841
- * @return {Option}
842
- */
843
- implies(impliedOptionValues) {
844
- let newImplied = impliedOptionValues;
845
- if (typeof impliedOptionValues === "string") {
846
- newImplied = { [impliedOptionValues]: true };
847
- }
848
- this.implied = Object.assign(this.implied || {}, newImplied);
849
- return this;
850
- }
851
- /**
852
- * Set environment variable to check for option value.
853
- *
854
- * An environment variable is only used if when processed the current option value is
855
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
856
- *
857
- * @param {string} name
858
- * @return {Option}
859
- */
860
- env(name) {
861
- this.envVar = name;
862
- return this;
863
- }
864
- /**
865
- * Set the custom handler for processing CLI option arguments into option values.
866
- *
867
- * @param {Function} [fn]
868
- * @return {Option}
869
- */
870
- argParser(fn) {
871
- this.parseArg = fn;
872
- return this;
873
- }
874
- /**
875
- * Whether the option is mandatory and must have a value after parsing.
876
- *
877
- * @param {boolean} [mandatory=true]
878
- * @return {Option}
879
- */
880
- makeOptionMandatory(mandatory = true) {
881
- this.mandatory = !!mandatory;
882
- return this;
883
- }
884
- /**
885
- * Hide option in help.
886
- *
887
- * @param {boolean} [hide=true]
888
- * @return {Option}
889
- */
890
- hideHelp(hide = true) {
891
- this.hidden = !!hide;
892
- return this;
893
- }
894
- /**
895
- * @package
896
- */
897
- _collectValue(value, previous) {
898
- if (previous === this.defaultValue || !Array.isArray(previous)) {
899
- return [value];
900
- }
901
- previous.push(value);
902
- return previous;
903
- }
904
- /**
905
- * Only allow option value to be one of choices.
906
- *
907
- * @param {string[]} values
908
- * @return {Option}
909
- */
910
- choices(values) {
911
- this.argChoices = values.slice();
912
- this.parseArg = (arg, previous) => {
913
- if (!this.argChoices.includes(arg)) {
914
- throw new InvalidArgumentError(
915
- `Allowed choices are ${this.argChoices.join(", ")}.`
916
- );
917
- }
918
- if (this.variadic) {
919
- return this._collectValue(arg, previous);
920
- }
921
- return arg;
922
- };
923
- return this;
924
- }
925
- /**
926
- * Return option name.
927
- *
928
- * @return {string}
929
- */
930
- name() {
931
- if (this.long) {
932
- return this.long.replace(/^--/, "");
933
- }
934
- return this.short.replace(/^-/, "");
935
- }
936
- /**
937
- * Return option name, in a camelcase format that can be used
938
- * as an object attribute key.
939
- *
940
- * @return {string}
941
- */
942
- attributeName() {
943
- if (this.negate) {
944
- return camelcase(this.name().replace(/^no-/, ""));
945
- }
946
- return camelcase(this.name());
947
- }
948
- /**
949
- * Set the help group heading.
950
- *
951
- * @param {string} heading
952
- * @return {Option}
953
- */
954
- helpGroup(heading) {
955
- this.helpGroupHeading = heading;
956
- return this;
957
- }
958
- /**
959
- * Check if `arg` matches the short or long flag.
960
- *
961
- * @param {string} arg
962
- * @return {boolean}
963
- * @package
964
- */
965
- is(arg) {
966
- return this.short === arg || this.long === arg;
967
- }
968
- /**
969
- * Return whether a boolean option.
970
- *
971
- * Options are one of boolean, negated, required argument, or optional argument.
972
- *
973
- * @return {boolean}
974
- * @package
975
- */
976
- isBoolean() {
977
- return !this.required && !this.optional && !this.negate;
978
- }
979
- };
980
- var DualOptions = class {
981
- /**
982
- * @param {Option[]} options
983
- */
984
- constructor(options) {
985
- this.positiveOptions = /* @__PURE__ */ new Map();
986
- this.negativeOptions = /* @__PURE__ */ new Map();
987
- this.dualOptions = /* @__PURE__ */ new Set();
988
- options.forEach((option) => {
989
- if (option.negate) {
990
- this.negativeOptions.set(option.attributeName(), option);
991
- } else {
992
- this.positiveOptions.set(option.attributeName(), option);
993
- }
994
- });
995
- this.negativeOptions.forEach((value, key) => {
996
- if (this.positiveOptions.has(key)) {
997
- this.dualOptions.add(key);
998
- }
999
- });
1000
- }
1001
- /**
1002
- * Did the value come from the option, and not from possible matching dual option?
1003
- *
1004
- * @param {*} value
1005
- * @param {Option} option
1006
- * @returns {boolean}
1007
- */
1008
- valueFromOption(value, option) {
1009
- const optionKey = option.attributeName();
1010
- if (!this.dualOptions.has(optionKey)) return true;
1011
- const preset = this.negativeOptions.get(optionKey).presetArg;
1012
- const negativeValue = preset !== void 0 ? preset : false;
1013
- return option.negate === (negativeValue === value);
1014
- }
1015
- };
1016
- function camelcase(str) {
1017
- return str.split("-").reduce((str2, word) => {
1018
- return str2 + word[0].toUpperCase() + word.slice(1);
1019
- });
1020
- }
1021
- function splitOptionFlags(flags) {
1022
- let shortFlag;
1023
- let longFlag;
1024
- const shortFlagExp = /^-[^-]$/;
1025
- const longFlagExp = /^--[^-]/;
1026
- const flagParts = flags.split(/[ |,]+/).concat("guard");
1027
- if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1028
- if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1029
- if (!shortFlag && shortFlagExp.test(flagParts[0]))
1030
- shortFlag = flagParts.shift();
1031
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
1032
- shortFlag = longFlag;
1033
- longFlag = flagParts.shift();
1034
- }
1035
- if (flagParts[0].startsWith("-")) {
1036
- const unsupportedFlag = flagParts[0];
1037
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1038
- if (/^-[^-][^-]/.test(unsupportedFlag))
1039
- throw new Error(
1040
- `${baseError}
4
+ var f=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},C=class extends f{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var x=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new C(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function $(o){let t=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+t+">":"["+t+"]"}import{EventEmitter as Z}from"events";import k from"child_process";import d from"path";import v from"fs";import m from"process";import{stripVTControlCharacters as Q}from"util";import{stripVTControlCharacters as X}from"util";var y=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>$(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[])}),e.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[]),n.get(r).push(s)}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(u,p){return e.formatItem(u,i,p,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(u=>s(e.styleArgumentTerm(e.argumentTerm(u)),e.styleArgumentDescription(e.argumentDescription(u))));if(r=r.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),u=>u.helpGroupHeading??"Options:").forEach((u,p)=>{let O=u.map(_=>s(e.styleOptionTerm(e.optionTerm(_)),e.styleOptionDescription(e.optionDescription(_))));r=r.concat(this.formatItemList(p,O,e))}),e.showGlobalOptions){let u=e.visibleGlobalOptions(t).map(p=>s(e.styleOptionTerm(e.optionTerm(p)),e.styleOptionDescription(e.optionDescription(p))));r=r.concat(this.formatItemList("Global Options:",u,e))}return this.groupItems(t.commands,e.visibleCommands(t),u=>u.helpGroup()||"Commands:").forEach((u,p)=>{let O=u.map(_=>s(e.styleSubcommandTerm(e.subcommandTerm(_)),e.styleSubcommandDescription(e.subcommandDescription(_))));r=r.concat(this.formatItemList(p,O,e))}),r.join(`
5
+ `)}displayWidth(t){return X(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let r=" ".repeat(2);if(!i)return r+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,u;return l<this.minWidthToWrap||n.preformatted(i)?u=i:u=n.boxWrap(i,l).replace(/\n/g,`
6
+ `+" ".repeat(e+h)),r+a+" ".repeat(h)+u.replace(/\n/g,`
7
+ ${r}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(r=>{let a=r.match(n);if(a===null){s.push("");return}let h=[a.shift()],c=this.displayWidth(h[0]);a.forEach(l=>{let u=this.displayWidth(l);if(c+u<=e){h.push(l),c+=u;return}s.push(h.join(""));let p=l.trimStart();h=[p],c=this.displayWidth(p)}),s.push(h.join(""))}),s.join(`
8
+ `)}};var b=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=Y(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new C(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?T(this.name().replace(/^no-/,"")):T(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},E=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return e.negate===(s===t)}};function T(o){return o.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function Y(o){let t,e,i=/^-[^-]$/,n=/^--[^-]/,s=o.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(t=s.shift()),n.test(s[0])&&(e=s.shift()),!t&&i.test(s[0])&&(t=s.shift()),!t&&n.test(s[0])&&(t=e,e=s.shift()),s[0].startsWith("-")){let r=s[0],a=`option creation failed due to '${r}' in option flags '${o}'`;throw/^-[^-][^-]/.test(r)?new Error(`${a}
1041
9
  - a short flag is a single dash and a single character
1042
10
  - either use a single dash and a single character (for a short flag)
1043
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1044
- );
1045
- if (shortFlagExp.test(unsupportedFlag))
1046
- throw new Error(`${baseError}
1047
- - too many short flags`);
1048
- if (longFlagExp.test(unsupportedFlag))
1049
- throw new Error(`${baseError}
1050
- - too many long flags`);
1051
- throw new Error(`${baseError}
1052
- - unrecognised flag format`);
1053
- }
1054
- if (shortFlag === void 0 && longFlag === void 0)
1055
- throw new Error(
1056
- `option creation failed due to no flags found in '${flags}'.`
1057
- );
1058
- return { shortFlag, longFlag };
1059
- }
1060
-
1061
- // ../node_modules/commander/lib/suggestSimilar.js
1062
- var maxDistance = 3;
1063
- function editDistance(a, b) {
1064
- if (Math.abs(a.length - b.length) > maxDistance)
1065
- return Math.max(a.length, b.length);
1066
- const d = [];
1067
- for (let i = 0; i <= a.length; i++) {
1068
- d[i] = [i];
1069
- }
1070
- for (let j = 0; j <= b.length; j++) {
1071
- d[0][j] = j;
1072
- }
1073
- for (let j = 1; j <= b.length; j++) {
1074
- for (let i = 1; i <= a.length; i++) {
1075
- let cost;
1076
- if (a[i - 1] === b[j - 1]) {
1077
- cost = 0;
1078
- } else {
1079
- cost = 1;
1080
- }
1081
- d[i][j] = Math.min(
1082
- d[i - 1][j] + 1,
1083
- // deletion
1084
- d[i][j - 1] + 1,
1085
- // insertion
1086
- d[i - 1][j - 1] + cost
1087
- // substitution
1088
- );
1089
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1090
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1091
- }
1092
- }
1093
- }
1094
- return d[a.length][b.length];
1095
- }
1096
- function suggestSimilar(word, candidates) {
1097
- if (!candidates || candidates.length === 0) return "";
1098
- candidates = Array.from(new Set(candidates));
1099
- const searchingOptions = word.startsWith("--");
1100
- if (searchingOptions) {
1101
- word = word.slice(2);
1102
- candidates = candidates.map((candidate) => candidate.slice(2));
1103
- }
1104
- let similar = [];
1105
- let bestDistance = maxDistance;
1106
- const minSimilarity = 0.4;
1107
- candidates.forEach((candidate) => {
1108
- if (candidate.length <= 1) return;
1109
- const distance = editDistance(word, candidate);
1110
- const length = Math.max(word.length, candidate.length);
1111
- const similarity = (length - distance) / length;
1112
- if (similarity > minSimilarity) {
1113
- if (distance < bestDistance) {
1114
- bestDistance = distance;
1115
- similar = [candidate];
1116
- } else if (distance === bestDistance) {
1117
- similar.push(candidate);
1118
- }
1119
- }
1120
- });
1121
- similar.sort((a, b) => a.localeCompare(b));
1122
- if (searchingOptions) {
1123
- similar = similar.map((candidate) => `--${candidate}`);
1124
- }
1125
- if (similar.length > 1) {
1126
- return `
1127
- (Did you mean one of ${similar.join(", ")}?)`;
1128
- }
1129
- if (similar.length === 1) {
1130
- return `
1131
- (Did you mean ${similar[0]}?)`;
1132
- }
1133
- return "";
1134
- }
1135
-
1136
- // ../node_modules/commander/lib/command.js
1137
- var Command = class _Command extends EventEmitter {
1138
- /**
1139
- * Initialize a new `Command`.
1140
- *
1141
- * @param {string} [name]
1142
- */
1143
- constructor(name) {
1144
- super();
1145
- this.commands = [];
1146
- this.options = [];
1147
- this.parent = null;
1148
- this._allowUnknownOption = false;
1149
- this._allowExcessArguments = false;
1150
- this.registeredArguments = [];
1151
- this._args = this.registeredArguments;
1152
- this.args = [];
1153
- this.rawArgs = [];
1154
- this.processedArgs = [];
1155
- this._scriptPath = null;
1156
- this._name = name || "";
1157
- this._optionValues = {};
1158
- this._optionValueSources = {};
1159
- this._storeOptionsAsProperties = false;
1160
- this._actionHandler = null;
1161
- this._executableHandler = false;
1162
- this._executableFile = null;
1163
- this._executableDir = null;
1164
- this._defaultCommandName = null;
1165
- this._exitCallback = null;
1166
- this._aliases = [];
1167
- this._combineFlagAndOptionalValue = true;
1168
- this._description = "";
1169
- this._summary = "";
1170
- this._argsDescription = void 0;
1171
- this._enablePositionalOptions = false;
1172
- this._passThroughOptions = false;
1173
- this._lifeCycleHooks = {};
1174
- this._showHelpAfterError = false;
1175
- this._showSuggestionAfterError = true;
1176
- this._savedState = null;
1177
- this._outputConfiguration = {
1178
- writeOut: (str) => process2.stdout.write(str),
1179
- writeErr: (str) => process2.stderr.write(str),
1180
- outputError: (str, write) => write(str),
1181
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1182
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1183
- getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1184
- getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1185
- stripColor: (str) => stripVTControlCharacters2(str)
1186
- };
1187
- this._hidden = false;
1188
- this._helpOption = void 0;
1189
- this._addImplicitHelpCommand = void 0;
1190
- this._helpCommand = void 0;
1191
- this._helpConfiguration = {};
1192
- this._helpGroupHeading = void 0;
1193
- this._defaultCommandGroup = void 0;
1194
- this._defaultOptionGroup = void 0;
1195
- }
1196
- /**
1197
- * Copy settings that are useful to have in common across root command and subcommands.
1198
- *
1199
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1200
- *
1201
- * @param {Command} sourceCommand
1202
- * @return {Command} `this` command for chaining
1203
- */
1204
- copyInheritedSettings(sourceCommand) {
1205
- this._outputConfiguration = sourceCommand._outputConfiguration;
1206
- this._helpOption = sourceCommand._helpOption;
1207
- this._helpCommand = sourceCommand._helpCommand;
1208
- this._helpConfiguration = sourceCommand._helpConfiguration;
1209
- this._exitCallback = sourceCommand._exitCallback;
1210
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1211
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1212
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1213
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1214
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1215
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1216
- return this;
1217
- }
1218
- /**
1219
- * @returns {Command[]}
1220
- * @private
1221
- */
1222
- _getCommandAndAncestors() {
1223
- const result = [];
1224
- for (let command = this; command; command = command.parent) {
1225
- result.push(command);
1226
- }
1227
- return result;
1228
- }
1229
- /**
1230
- * Define a command.
1231
- *
1232
- * There are two styles of command: pay attention to where to put the description.
1233
- *
1234
- * @example
1235
- * // Command implemented using action handler (description is supplied separately to `.command`)
1236
- * program
1237
- * .command('clone <source> [destination]')
1238
- * .description('clone a repository into a newly created directory')
1239
- * .action((source, destination) => {
1240
- * console.log('clone command called');
1241
- * });
1242
- *
1243
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1244
- * program
1245
- * .command('start <service>', 'start named service')
1246
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1247
- *
1248
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1249
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1250
- * @param {object} [execOpts] - configuration options (for executable)
1251
- * @return {Command} returns new command for action handler, or `this` for executable command
1252
- */
1253
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1254
- let desc = actionOptsOrExecDesc;
1255
- let opts = execOpts;
1256
- if (typeof desc === "object" && desc !== null) {
1257
- opts = desc;
1258
- desc = null;
1259
- }
1260
- opts = opts || {};
1261
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1262
- const cmd = this.createCommand(name);
1263
- if (desc) {
1264
- cmd.description(desc);
1265
- cmd._executableHandler = true;
1266
- }
1267
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1268
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1269
- cmd._executableFile = opts.executableFile || null;
1270
- if (args) cmd.arguments(args);
1271
- this._registerCommand(cmd);
1272
- cmd.parent = this;
1273
- cmd.copyInheritedSettings(this);
1274
- if (desc) return this;
1275
- return cmd;
1276
- }
1277
- /**
1278
- * Factory routine to create a new unattached command.
1279
- *
1280
- * See .command() for creating an attached subcommand, which uses this routine to
1281
- * create the command. You can override createCommand to customise subcommands.
1282
- *
1283
- * @param {string} [name]
1284
- * @return {Command} new command
1285
- */
1286
- createCommand(name) {
1287
- return new _Command(name);
1288
- }
1289
- /**
1290
- * You can customise the help with a subclass of Help by overriding createHelp,
1291
- * or by overriding Help properties using configureHelp().
1292
- *
1293
- * @return {Help}
1294
- */
1295
- createHelp() {
1296
- return Object.assign(new Help(), this.configureHelp());
1297
- }
1298
- /**
1299
- * You can customise the help by overriding Help properties using configureHelp(),
1300
- * or with a subclass of Help by overriding createHelp().
1301
- *
1302
- * @param {object} [configuration] - configuration options
1303
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1304
- */
1305
- configureHelp(configuration) {
1306
- if (configuration === void 0) return this._helpConfiguration;
1307
- this._helpConfiguration = configuration;
1308
- return this;
1309
- }
1310
- /**
1311
- * The default output goes to stdout and stderr. You can customise this for special
1312
- * applications. You can also customise the display of errors by overriding outputError.
1313
- *
1314
- * The configuration properties are all functions:
1315
- *
1316
- * // change how output being written, defaults to stdout and stderr
1317
- * writeOut(str)
1318
- * writeErr(str)
1319
- * // change how output being written for errors, defaults to writeErr
1320
- * outputError(str, write) // used for displaying errors and not used for displaying help
1321
- * // specify width for wrapping help
1322
- * getOutHelpWidth()
1323
- * getErrHelpWidth()
1324
- * // color support, currently only used with Help
1325
- * getOutHasColors()
1326
- * getErrHasColors()
1327
- * stripColor() // used to remove ANSI escape codes if output does not have colors
1328
- *
1329
- * @param {object} [configuration] - configuration options
1330
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1331
- */
1332
- configureOutput(configuration) {
1333
- if (configuration === void 0) return this._outputConfiguration;
1334
- this._outputConfiguration = {
1335
- ...this._outputConfiguration,
1336
- ...configuration
1337
- };
1338
- return this;
1339
- }
1340
- /**
1341
- * Display the help or a custom message after an error occurs.
1342
- *
1343
- * @param {(boolean|string)} [displayHelp]
1344
- * @return {Command} `this` command for chaining
1345
- */
1346
- showHelpAfterError(displayHelp = true) {
1347
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1348
- this._showHelpAfterError = displayHelp;
1349
- return this;
1350
- }
1351
- /**
1352
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1353
- *
1354
- * @param {boolean} [displaySuggestion]
1355
- * @return {Command} `this` command for chaining
1356
- */
1357
- showSuggestionAfterError(displaySuggestion = true) {
1358
- this._showSuggestionAfterError = !!displaySuggestion;
1359
- return this;
1360
- }
1361
- /**
1362
- * Add a prepared subcommand.
1363
- *
1364
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1365
- *
1366
- * @param {Command} cmd - new subcommand
1367
- * @param {object} [opts] - configuration options
1368
- * @return {Command} `this` command for chaining
1369
- */
1370
- addCommand(cmd, opts) {
1371
- if (!cmd._name) {
1372
- throw new Error(`Command passed to .addCommand() must have a name
1373
- - specify the name in Command constructor or using .name()`);
1374
- }
1375
- opts = opts || {};
1376
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1377
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1378
- this._registerCommand(cmd);
1379
- cmd.parent = this;
1380
- cmd._checkForBrokenPassThrough();
1381
- return this;
1382
- }
1383
- /**
1384
- * Factory routine to create a new unattached argument.
1385
- *
1386
- * See .argument() for creating an attached argument, which uses this routine to
1387
- * create the argument. You can override createArgument to return a custom argument.
1388
- *
1389
- * @param {string} name
1390
- * @param {string} [description]
1391
- * @return {Argument} new argument
1392
- */
1393
- createArgument(name, description) {
1394
- return new Argument(name, description);
1395
- }
1396
- /**
1397
- * Define argument syntax for command.
1398
- *
1399
- * The default is that the argument is required, and you can explicitly
1400
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1401
- *
1402
- * @example
1403
- * program.argument('<input-file>');
1404
- * program.argument('[output-file]');
1405
- *
1406
- * @param {string} name
1407
- * @param {string} [description]
1408
- * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1409
- * @param {*} [defaultValue]
1410
- * @return {Command} `this` command for chaining
1411
- */
1412
- argument(name, description, parseArg, defaultValue) {
1413
- const argument = this.createArgument(name, description);
1414
- if (typeof parseArg === "function") {
1415
- argument.default(defaultValue).argParser(parseArg);
1416
- } else {
1417
- argument.default(parseArg);
1418
- }
1419
- this.addArgument(argument);
1420
- return this;
1421
- }
1422
- /**
1423
- * Define argument syntax for command, adding multiple at once (without descriptions).
1424
- *
1425
- * See also .argument().
1426
- *
1427
- * @example
1428
- * program.arguments('<cmd> [env]');
1429
- *
1430
- * @param {string} names
1431
- * @return {Command} `this` command for chaining
1432
- */
1433
- arguments(names) {
1434
- names.trim().split(/ +/).forEach((detail) => {
1435
- this.argument(detail);
1436
- });
1437
- return this;
1438
- }
1439
- /**
1440
- * Define argument syntax for command, adding a prepared argument.
1441
- *
1442
- * @param {Argument} argument
1443
- * @return {Command} `this` command for chaining
1444
- */
1445
- addArgument(argument) {
1446
- const previousArgument = this.registeredArguments.slice(-1)[0];
1447
- if (previousArgument?.variadic) {
1448
- throw new Error(
1449
- `only the last argument can be variadic '${previousArgument.name()}'`
1450
- );
1451
- }
1452
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1453
- throw new Error(
1454
- `a default value for a required argument is never used: '${argument.name()}'`
1455
- );
1456
- }
1457
- this.registeredArguments.push(argument);
1458
- return this;
1459
- }
1460
- /**
1461
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1462
- *
1463
- * @example
1464
- * program.helpCommand('help [cmd]');
1465
- * program.helpCommand('help [cmd]', 'show help');
1466
- * program.helpCommand(false); // suppress default help command
1467
- * program.helpCommand(true); // add help command even if no subcommands
1468
- *
1469
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1470
- * @param {string} [description] - custom description
1471
- * @return {Command} `this` command for chaining
1472
- */
1473
- helpCommand(enableOrNameAndArgs, description) {
1474
- if (typeof enableOrNameAndArgs === "boolean") {
1475
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1476
- if (enableOrNameAndArgs && this._defaultCommandGroup) {
1477
- this._initCommandGroup(this._getHelpCommand());
1478
- }
1479
- return this;
1480
- }
1481
- const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1482
- const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1483
- const helpDescription = description ?? "display help for command";
1484
- const helpCommand = this.createCommand(helpName);
1485
- helpCommand.helpOption(false);
1486
- if (helpArgs) helpCommand.arguments(helpArgs);
1487
- if (helpDescription) helpCommand.description(helpDescription);
1488
- this._addImplicitHelpCommand = true;
1489
- this._helpCommand = helpCommand;
1490
- if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1491
- return this;
1492
- }
1493
- /**
1494
- * Add prepared custom help command.
1495
- *
1496
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1497
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1498
- * @return {Command} `this` command for chaining
1499
- */
1500
- addHelpCommand(helpCommand, deprecatedDescription) {
1501
- if (typeof helpCommand !== "object") {
1502
- this.helpCommand(helpCommand, deprecatedDescription);
1503
- return this;
1504
- }
1505
- this._addImplicitHelpCommand = true;
1506
- this._helpCommand = helpCommand;
1507
- this._initCommandGroup(helpCommand);
1508
- return this;
1509
- }
1510
- /**
1511
- * Lazy create help command.
1512
- *
1513
- * @return {(Command|null)}
1514
- * @package
1515
- */
1516
- _getHelpCommand() {
1517
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1518
- if (hasImplicitHelpCommand) {
1519
- if (this._helpCommand === void 0) {
1520
- this.helpCommand(void 0, void 0);
1521
- }
1522
- return this._helpCommand;
1523
- }
1524
- return null;
1525
- }
1526
- /**
1527
- * Add hook for life cycle event.
1528
- *
1529
- * @param {string} event
1530
- * @param {Function} listener
1531
- * @return {Command} `this` command for chaining
1532
- */
1533
- hook(event, listener) {
1534
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1535
- if (!allowedValues.includes(event)) {
1536
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1537
- Expecting one of '${allowedValues.join("', '")}'`);
1538
- }
1539
- if (this._lifeCycleHooks[event]) {
1540
- this._lifeCycleHooks[event].push(listener);
1541
- } else {
1542
- this._lifeCycleHooks[event] = [listener];
1543
- }
1544
- return this;
1545
- }
1546
- /**
1547
- * Register callback to use as replacement for calling process.exit.
1548
- *
1549
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1550
- * @return {Command} `this` command for chaining
1551
- */
1552
- exitOverride(fn) {
1553
- if (fn) {
1554
- this._exitCallback = fn;
1555
- } else {
1556
- this._exitCallback = (err) => {
1557
- if (err.code !== "commander.executeSubCommandAsync") {
1558
- throw err;
1559
- } else {
1560
- }
1561
- };
1562
- }
1563
- return this;
1564
- }
1565
- /**
1566
- * Call process.exit, and _exitCallback if defined.
1567
- *
1568
- * @param {number} exitCode exit code for using with process.exit
1569
- * @param {string} code an id string representing the error
1570
- * @param {string} message human-readable description of the error
1571
- * @return never
1572
- * @private
1573
- */
1574
- _exit(exitCode, code, message) {
1575
- if (this._exitCallback) {
1576
- this._exitCallback(new CommanderError(exitCode, code, message));
1577
- }
1578
- process2.exit(exitCode);
1579
- }
1580
- /**
1581
- * Register callback `fn` for the command.
1582
- *
1583
- * @example
1584
- * program
1585
- * .command('serve')
1586
- * .description('start service')
1587
- * .action(function() {
1588
- * // do work here
1589
- * });
1590
- *
1591
- * @param {Function} fn
1592
- * @return {Command} `this` command for chaining
1593
- */
1594
- action(fn) {
1595
- const listener = (args) => {
1596
- const expectedArgsCount = this.registeredArguments.length;
1597
- const actionArgs = args.slice(0, expectedArgsCount);
1598
- if (this._storeOptionsAsProperties) {
1599
- actionArgs[expectedArgsCount] = this;
1600
- } else {
1601
- actionArgs[expectedArgsCount] = this.opts();
1602
- }
1603
- actionArgs.push(this);
1604
- return fn.apply(this, actionArgs);
1605
- };
1606
- this._actionHandler = listener;
1607
- return this;
1608
- }
1609
- /**
1610
- * Factory routine to create a new unattached option.
1611
- *
1612
- * See .option() for creating an attached option, which uses this routine to
1613
- * create the option. You can override createOption to return a custom option.
1614
- *
1615
- * @param {string} flags
1616
- * @param {string} [description]
1617
- * @return {Option} new option
1618
- */
1619
- createOption(flags, description) {
1620
- return new Option(flags, description);
1621
- }
1622
- /**
1623
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1624
- *
1625
- * @param {(Option | Argument)} target
1626
- * @param {string} value
1627
- * @param {*} previous
1628
- * @param {string} invalidArgumentMessage
1629
- * @private
1630
- */
1631
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1632
- try {
1633
- return target.parseArg(value, previous);
1634
- } catch (err) {
1635
- if (err.code === "commander.invalidArgument") {
1636
- const message = `${invalidArgumentMessage} ${err.message}`;
1637
- this.error(message, { exitCode: err.exitCode, code: err.code });
1638
- }
1639
- throw err;
1640
- }
1641
- }
1642
- /**
1643
- * Check for option flag conflicts.
1644
- * Register option if no conflicts found, or throw on conflict.
1645
- *
1646
- * @param {Option} option
1647
- * @private
1648
- */
1649
- _registerOption(option) {
1650
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1651
- if (matchingOption) {
1652
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1653
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1654
- - already used by option '${matchingOption.flags}'`);
1655
- }
1656
- this._initOptionGroup(option);
1657
- this.options.push(option);
1658
- }
1659
- /**
1660
- * Check for command name and alias conflicts with existing commands.
1661
- * Register command if no conflicts found, or throw on conflict.
1662
- *
1663
- * @param {Command} command
1664
- * @private
1665
- */
1666
- _registerCommand(command) {
1667
- const knownBy = (cmd) => {
1668
- return [cmd.name()].concat(cmd.aliases());
1669
- };
1670
- const alreadyUsed = knownBy(command).find(
1671
- (name) => this._findCommand(name)
1672
- );
1673
- if (alreadyUsed) {
1674
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1675
- const newCmd = knownBy(command).join("|");
1676
- throw new Error(
1677
- `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1678
- );
1679
- }
1680
- this._initCommandGroup(command);
1681
- this.commands.push(command);
1682
- }
1683
- /**
1684
- * Add an option.
1685
- *
1686
- * @param {Option} option
1687
- * @return {Command} `this` command for chaining
1688
- */
1689
- addOption(option) {
1690
- this._registerOption(option);
1691
- const oname = option.name();
1692
- const name = option.attributeName();
1693
- if (option.defaultValue !== void 0) {
1694
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1695
- }
1696
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1697
- if (val == null && option.presetArg !== void 0) {
1698
- val = option.presetArg;
1699
- }
1700
- const oldValue = this.getOptionValue(name);
1701
- if (val !== null && option.parseArg) {
1702
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1703
- } else if (val !== null && option.variadic) {
1704
- val = option._collectValue(val, oldValue);
1705
- }
1706
- if (val == null) {
1707
- if (option.negate) {
1708
- val = false;
1709
- } else if (option.isBoolean() || option.optional) {
1710
- val = true;
1711
- } else {
1712
- val = "";
1713
- }
1714
- }
1715
- this.setOptionValueWithSource(name, val, valueSource);
1716
- };
1717
- this.on("option:" + oname, (val) => {
1718
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1719
- handleOptionValue(val, invalidValueMessage, "cli");
1720
- });
1721
- if (option.envVar) {
1722
- this.on("optionEnv:" + oname, (val) => {
1723
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1724
- handleOptionValue(val, invalidValueMessage, "env");
1725
- });
1726
- }
1727
- return this;
1728
- }
1729
- /**
1730
- * Internal implementation shared by .option() and .requiredOption()
1731
- *
1732
- * @return {Command} `this` command for chaining
1733
- * @private
1734
- */
1735
- _optionEx(config, flags, description, fn, defaultValue) {
1736
- if (typeof flags === "object" && flags instanceof Option) {
1737
- throw new Error(
1738
- "To add an Option object use addOption() instead of option() or requiredOption()"
1739
- );
1740
- }
1741
- const option = this.createOption(flags, description);
1742
- option.makeOptionMandatory(!!config.mandatory);
1743
- if (typeof fn === "function") {
1744
- option.default(defaultValue).argParser(fn);
1745
- } else if (fn instanceof RegExp) {
1746
- const regex = fn;
1747
- fn = (val, def) => {
1748
- const m = regex.exec(val);
1749
- return m ? m[0] : def;
1750
- };
1751
- option.default(defaultValue).argParser(fn);
1752
- } else {
1753
- option.default(fn);
1754
- }
1755
- return this.addOption(option);
1756
- }
1757
- /**
1758
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1759
- *
1760
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1761
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1762
- *
1763
- * See the README for more details, and see also addOption() and requiredOption().
1764
- *
1765
- * @example
1766
- * program
1767
- * .option('-p, --pepper', 'add pepper')
1768
- * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1769
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1770
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1771
- *
1772
- * @param {string} flags
1773
- * @param {string} [description]
1774
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1775
- * @param {*} [defaultValue]
1776
- * @return {Command} `this` command for chaining
1777
- */
1778
- option(flags, description, parseArg, defaultValue) {
1779
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1780
- }
1781
- /**
1782
- * Add a required option which must have a value after parsing. This usually means
1783
- * the option must be specified on the command line. (Otherwise the same as .option().)
1784
- *
1785
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1786
- *
1787
- * @param {string} flags
1788
- * @param {string} [description]
1789
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1790
- * @param {*} [defaultValue]
1791
- * @return {Command} `this` command for chaining
1792
- */
1793
- requiredOption(flags, description, parseArg, defaultValue) {
1794
- return this._optionEx(
1795
- { mandatory: true },
1796
- flags,
1797
- description,
1798
- parseArg,
1799
- defaultValue
1800
- );
1801
- }
1802
- /**
1803
- * Alter parsing of short flags with optional values.
1804
- *
1805
- * @example
1806
- * // for `.option('-f,--flag [value]'):
1807
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1808
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1809
- *
1810
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1811
- * @return {Command} `this` command for chaining
1812
- */
1813
- combineFlagAndOptionalValue(combine = true) {
1814
- this._combineFlagAndOptionalValue = !!combine;
1815
- return this;
1816
- }
1817
- /**
1818
- * Allow unknown options on the command line.
1819
- *
1820
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1821
- * @return {Command} `this` command for chaining
1822
- */
1823
- allowUnknownOption(allowUnknown = true) {
1824
- this._allowUnknownOption = !!allowUnknown;
1825
- return this;
1826
- }
1827
- /**
1828
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1829
- *
1830
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1831
- * @return {Command} `this` command for chaining
1832
- */
1833
- allowExcessArguments(allowExcess = true) {
1834
- this._allowExcessArguments = !!allowExcess;
1835
- return this;
1836
- }
1837
- /**
1838
- * Enable positional options. Positional means global options are specified before subcommands which lets
1839
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1840
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1841
- *
1842
- * @param {boolean} [positional]
1843
- * @return {Command} `this` command for chaining
1844
- */
1845
- enablePositionalOptions(positional = true) {
1846
- this._enablePositionalOptions = !!positional;
1847
- return this;
1848
- }
1849
- /**
1850
- * Pass through options that come after command-arguments rather than treat them as command-options,
1851
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1852
- * positional options to have been enabled on the program (parent commands).
1853
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1854
- *
1855
- * @param {boolean} [passThrough] for unknown options.
1856
- * @return {Command} `this` command for chaining
1857
- */
1858
- passThroughOptions(passThrough = true) {
1859
- this._passThroughOptions = !!passThrough;
1860
- this._checkForBrokenPassThrough();
1861
- return this;
1862
- }
1863
- /**
1864
- * @private
1865
- */
1866
- _checkForBrokenPassThrough() {
1867
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1868
- throw new Error(
1869
- `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1870
- );
1871
- }
1872
- }
1873
- /**
1874
- * Whether to store option values as properties on command object,
1875
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1876
- *
1877
- * @param {boolean} [storeAsProperties=true]
1878
- * @return {Command} `this` command for chaining
1879
- */
1880
- storeOptionsAsProperties(storeAsProperties = true) {
1881
- if (this.options.length) {
1882
- throw new Error("call .storeOptionsAsProperties() before adding options");
1883
- }
1884
- if (Object.keys(this._optionValues).length) {
1885
- throw new Error(
1886
- "call .storeOptionsAsProperties() before setting option values"
1887
- );
1888
- }
1889
- this._storeOptionsAsProperties = !!storeAsProperties;
1890
- return this;
1891
- }
1892
- /**
1893
- * Retrieve option value.
1894
- *
1895
- * @param {string} key
1896
- * @return {object} value
1897
- */
1898
- getOptionValue(key) {
1899
- if (this._storeOptionsAsProperties) {
1900
- return this[key];
1901
- }
1902
- return this._optionValues[key];
1903
- }
1904
- /**
1905
- * Store option value.
1906
- *
1907
- * @param {string} key
1908
- * @param {object} value
1909
- * @return {Command} `this` command for chaining
1910
- */
1911
- setOptionValue(key, value) {
1912
- return this.setOptionValueWithSource(key, value, void 0);
1913
- }
1914
- /**
1915
- * Store option value and where the value came from.
1916
- *
1917
- * @param {string} key
1918
- * @param {object} value
1919
- * @param {string} source - expected values are default/config/env/cli/implied
1920
- * @return {Command} `this` command for chaining
1921
- */
1922
- setOptionValueWithSource(key, value, source) {
1923
- if (this._storeOptionsAsProperties) {
1924
- this[key] = value;
1925
- } else {
1926
- this._optionValues[key] = value;
1927
- }
1928
- this._optionValueSources[key] = source;
1929
- return this;
1930
- }
1931
- /**
1932
- * Get source of option value.
1933
- * Expected values are default | config | env | cli | implied
1934
- *
1935
- * @param {string} key
1936
- * @return {string}
1937
- */
1938
- getOptionValueSource(key) {
1939
- return this._optionValueSources[key];
1940
- }
1941
- /**
1942
- * Get source of option value. See also .optsWithGlobals().
1943
- * Expected values are default | config | env | cli | implied
1944
- *
1945
- * @param {string} key
1946
- * @return {string}
1947
- */
1948
- getOptionValueSourceWithGlobals(key) {
1949
- let source;
1950
- this._getCommandAndAncestors().forEach((cmd) => {
1951
- if (cmd.getOptionValueSource(key) !== void 0) {
1952
- source = cmd.getOptionValueSource(key);
1953
- }
1954
- });
1955
- return source;
1956
- }
1957
- /**
1958
- * Get user arguments from implied or explicit arguments.
1959
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1960
- *
1961
- * @private
1962
- */
1963
- _prepareUserArgs(argv, parseOptions) {
1964
- if (argv !== void 0 && !Array.isArray(argv)) {
1965
- throw new Error("first parameter to parse must be array or undefined");
1966
- }
1967
- parseOptions = parseOptions || {};
1968
- if (argv === void 0 && parseOptions.from === void 0) {
1969
- if (process2.versions?.electron) {
1970
- parseOptions.from = "electron";
1971
- }
1972
- const execArgv = process2.execArgv ?? [];
1973
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1974
- parseOptions.from = "eval";
1975
- }
1976
- }
1977
- if (argv === void 0) {
1978
- argv = process2.argv;
1979
- }
1980
- this.rawArgs = argv.slice();
1981
- let userArgs;
1982
- switch (parseOptions.from) {
1983
- case void 0:
1984
- case "node":
1985
- this._scriptPath = argv[1];
1986
- userArgs = argv.slice(2);
1987
- break;
1988
- case "electron":
1989
- if (process2.defaultApp) {
1990
- this._scriptPath = argv[1];
1991
- userArgs = argv.slice(2);
1992
- } else {
1993
- userArgs = argv.slice(1);
1994
- }
1995
- break;
1996
- case "user":
1997
- userArgs = argv.slice(0);
1998
- break;
1999
- case "eval":
2000
- userArgs = argv.slice(1);
2001
- break;
2002
- default:
2003
- throw new Error(
2004
- `unexpected parse option { from: '${parseOptions.from}' }`
2005
- );
2006
- }
2007
- if (!this._name && this._scriptPath)
2008
- this.nameFromFilename(this._scriptPath);
2009
- this._name = this._name || "program";
2010
- return userArgs;
2011
- }
2012
- /**
2013
- * Parse `argv`, setting options and invoking commands when defined.
2014
- *
2015
- * Use parseAsync instead of parse if any of your action handlers are async.
2016
- *
2017
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2018
- *
2019
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2020
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2021
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2022
- * - `'user'`: just user arguments
2023
- *
2024
- * @example
2025
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
2026
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2027
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2028
- *
2029
- * @param {string[]} [argv] - optional, defaults to process.argv
2030
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2031
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2032
- * @return {Command} `this` command for chaining
2033
- */
2034
- parse(argv, parseOptions) {
2035
- this._prepareForParse();
2036
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2037
- this._parseCommand([], userArgs);
2038
- return this;
2039
- }
2040
- /**
2041
- * Parse `argv`, setting options and invoking commands when defined.
2042
- *
2043
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2044
- *
2045
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2046
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2047
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2048
- * - `'user'`: just user arguments
2049
- *
2050
- * @example
2051
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2052
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2053
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2054
- *
2055
- * @param {string[]} [argv]
2056
- * @param {object} [parseOptions]
2057
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2058
- * @return {Promise}
2059
- */
2060
- async parseAsync(argv, parseOptions) {
2061
- this._prepareForParse();
2062
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2063
- await this._parseCommand([], userArgs);
2064
- return this;
2065
- }
2066
- _prepareForParse() {
2067
- if (this._savedState === null) {
2068
- this.options.filter(
2069
- (option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
2070
- ).forEach((option) => {
2071
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
2072
- if (!this._findOption(positiveLongFlag)) {
2073
- this.setOptionValueWithSource(
2074
- option.attributeName(),
2075
- true,
2076
- "default"
2077
- );
2078
- }
2079
- });
2080
- this.saveStateBeforeParse();
2081
- } else {
2082
- this.restoreStateBeforeParse();
2083
- }
2084
- }
2085
- /**
2086
- * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2087
- * Not usually called directly, but available for subclasses to save their custom state.
2088
- *
2089
- * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2090
- */
2091
- saveStateBeforeParse() {
2092
- this._savedState = {
2093
- // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2094
- _name: this._name,
2095
- // option values before parse have default values (including false for negated options)
2096
- // shallow clones
2097
- _optionValues: { ...this._optionValues },
2098
- _optionValueSources: { ...this._optionValueSources }
2099
- };
2100
- }
2101
- /**
2102
- * Restore state before parse for calls after the first.
2103
- * Not usually called directly, but available for subclasses to save their custom state.
2104
- *
2105
- * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2106
- */
2107
- restoreStateBeforeParse() {
2108
- if (this._storeOptionsAsProperties)
2109
- throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2110
- - either make a new Command for each call to parse, or stop storing options as properties`);
2111
- this._name = this._savedState._name;
2112
- this._scriptPath = null;
2113
- this.rawArgs = [];
2114
- this._optionValues = { ...this._savedState._optionValues };
2115
- this._optionValueSources = { ...this._savedState._optionValueSources };
2116
- this.args = [];
2117
- this.processedArgs = [];
2118
- }
2119
- /**
2120
- * Throw if expected executable is missing. Add lots of help for author.
2121
- *
2122
- * @param {string} executableFile
2123
- * @param {string} executableDir
2124
- * @param {string} subcommandName
2125
- */
2126
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2127
- if (fs.existsSync(executableFile)) return;
2128
- 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";
2129
- const executableMissing = `'${executableFile}' does not exist
2130
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(r)?new Error(`${a}
12
+ - too many short flags`):n.test(r)?new Error(`${a}
13
+ - too many long flags`):new Error(`${a}
14
+ - unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:t,longFlag:e}}function z(o,t){if(Math.abs(o.length-t.length)>3)return Math.max(o.length,t.length);let e=[];for(let i=0;i<=o.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=o.length;n++){let s;o[n-1]===t[i-1]?s=0:s=1,e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s),n>1&&i>1&&o[n-1]===t[i-2]&&o[n-2]===t[i-1]&&(e[n][i]=Math.min(e[n][i],e[n-2][i-2]+1))}return e[o.length][t.length]}function H(o,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=o.startsWith("--");e&&(o=o.slice(2),t=t.map(r=>r.slice(2)));let i=[],n=3,s=.4;return t.forEach(r=>{if(r.length<=1)return;let a=z(o,r),h=Math.max(o.length,r.length);(h-a)/h>s&&(a<n?(n=a,i=[r]):a===n&&i.push(r))}),i.sort((r,a)=>r.localeCompare(a)),e&&(i=i.map(r=>`--${r}`)),i.length>1?`
15
+ (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
16
+ (Did you mean ${i[0]}?)`:""}var g=class o extends Z{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>m.stdout.write(e),writeErr:e=>m.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>D()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>D()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:e=>Q(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,r,a]=t.match(/([^ ]+) *(.*)/),h=this.createCommand(r);return n&&(h.description(n),h._executableHandler=!0),s.isDefault&&(this._defaultCommandName=h._name),h._hidden=!!(s.noHelp||s.hidden),h._executableFile=s.executableFile||null,a&&h.arguments(a),this._registerCommand(h),h.parent=this,h.copyInheritedSettings(this),n?this:h}createCommand(t){return new o(t)}createHelp(){return Object.assign(new y,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
17
+ - specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new x(t,e)}argument(t,e,i,n){let s=this.createArgument(t,e);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,n,s]=i.match(/([^ ]+) *(.*)/),r=e??"display help for command",a=this.createCommand(n);return a.helpOption(!1),s&&a.arguments(s),r&&a.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
18
+ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new f(t,e,i)),m.exit(t)}action(t){let e=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=e,this}createOption(t,e){return new b(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
19
+ - already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(s,r,a)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let h=this.getOptionValue(i);s!==null&&t.parseArg?s=this._callParseArg(t,s,h,r):s!==null&&t.variadic&&(s=t._collectValue(s,h)),s==null&&(t.negate?s=!1:t.isBoolean()||t.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+e,s=>{let r=`error: option '${t.flags}' argument '${s}' is invalid.`;n(s,r,"cli")}),t.envVar&&this.on("optionEnv:"+e,s=>{let r=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;n(s,r,"env")}),this}_optionEx(t,e,i,n,s){if(typeof e=="object"&&e instanceof b)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),typeof n=="function")r.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(h,c)=>{let l=a.exec(h);return l?l[0]:c},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){m.versions?.electron&&(e.from="electron");let n=m.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(e.from="eval")}t===void 0&&(t=m.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?(this.options.filter(t=>t.negate&&t.defaultValue===void 0&&this.getOptionValue(t.attributeName())===void 0).forEach(t=>{let e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(t.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(v.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${t}' does not exist
21
+ - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2131
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2132
- - ${executableDirMessage}`;
2133
- throw new Error(executableMissing);
2134
- }
2135
- /**
2136
- * Execute a sub-command executable.
2137
- *
2138
- * @private
2139
- */
2140
- _executeSubCommand(subcommand, args) {
2141
- args = args.slice();
2142
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2143
- function findFile(baseDir, baseName) {
2144
- const localBin = path.resolve(baseDir, baseName);
2145
- if (fs.existsSync(localBin)) return localBin;
2146
- if (sourceExt.includes(path.extname(baseName))) return void 0;
2147
- const foundExt = sourceExt.find(
2148
- (ext) => fs.existsSync(`${localBin}${ext}`)
2149
- );
2150
- if (foundExt) return `${localBin}${foundExt}`;
2151
- return void 0;
2152
- }
2153
- this._checkForMissingMandatoryOptions();
2154
- this._checkForConflictingOptions();
2155
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2156
- let executableDir = this._executableDir || "";
2157
- if (this._scriptPath) {
2158
- let resolvedScriptPath;
2159
- try {
2160
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
2161
- } catch {
2162
- resolvedScriptPath = this._scriptPath;
2163
- }
2164
- executableDir = path.resolve(
2165
- path.dirname(resolvedScriptPath),
2166
- executableDir
2167
- );
2168
- }
2169
- if (executableDir) {
2170
- let localFile = findFile(executableDir, executableFile);
2171
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
2172
- const legacyName = path.basename(
2173
- this._scriptPath,
2174
- path.extname(this._scriptPath)
2175
- );
2176
- if (legacyName !== this._name) {
2177
- localFile = findFile(
2178
- executableDir,
2179
- `${legacyName}-${subcommand._name}`
2180
- );
2181
- }
2182
- }
2183
- executableFile = localFile || executableFile;
2184
- }
2185
- const launchWithNode = sourceExt.includes(path.extname(executableFile));
2186
- let proc;
2187
- if (process2.platform !== "win32") {
2188
- if (launchWithNode) {
2189
- args.unshift(executableFile);
2190
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2191
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2192
- } else {
2193
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2194
- }
2195
- } else {
2196
- this._checkForMissingExecutable(
2197
- executableFile,
2198
- executableDir,
2199
- subcommand._name
2200
- );
2201
- args.unshift(executableFile);
2202
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2203
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2204
- }
2205
- if (!proc.killed) {
2206
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2207
- signals.forEach((signal) => {
2208
- process2.on(signal, () => {
2209
- if (proc.killed === false && proc.exitCode === null) {
2210
- proc.kill(signal);
2211
- }
2212
- });
2213
- });
2214
- }
2215
- const exitCallback = this._exitCallback;
2216
- proc.on("close", (code) => {
2217
- code = code ?? 1;
2218
- if (!exitCallback) {
2219
- process2.exit(code);
2220
- } else {
2221
- exitCallback(
2222
- new CommanderError(
2223
- code,
2224
- "commander.executeSubCommandAsync",
2225
- "(close)"
2226
- )
2227
- );
2228
- }
2229
- });
2230
- proc.on("error", (err) => {
2231
- if (err.code === "ENOENT") {
2232
- this._checkForMissingExecutable(
2233
- executableFile,
2234
- executableDir,
2235
- subcommand._name
2236
- );
2237
- } else if (err.code === "EACCES") {
2238
- throw new Error(`'${executableFile}' not executable`);
2239
- }
2240
- if (!exitCallback) {
2241
- process2.exit(1);
2242
- } else {
2243
- const wrappedError = new CommanderError(
2244
- 1,
2245
- "commander.executeSubCommandAsync",
2246
- "(error)"
2247
- );
2248
- wrappedError.nestedError = err;
2249
- exitCallback(wrappedError);
2250
- }
2251
- });
2252
- this.runningCommand = proc;
2253
- }
2254
- /**
2255
- * @private
2256
- */
2257
- _dispatchSubcommand(commandName, operands, unknown) {
2258
- const subCommand = this._findCommand(commandName);
2259
- if (!subCommand) this.help({ error: true });
2260
- subCommand._prepareForParse();
2261
- let promiseChain;
2262
- promiseChain = this._chainOrCallSubCommandHook(
2263
- promiseChain,
2264
- subCommand,
2265
- "preSubcommand"
2266
- );
2267
- promiseChain = this._chainOrCall(promiseChain, () => {
2268
- if (subCommand._executableHandler) {
2269
- this._executeSubCommand(subCommand, operands.concat(unknown));
2270
- } else {
2271
- return subCommand._parseCommand(operands, unknown);
2272
- }
2273
- });
2274
- return promiseChain;
2275
- }
2276
- /**
2277
- * Invoke help directly if possible, or dispatch if necessary.
2278
- * e.g. help foo
2279
- *
2280
- * @private
2281
- */
2282
- _dispatchHelpCommand(subcommandName) {
2283
- if (!subcommandName) {
2284
- this.help();
2285
- }
2286
- const subCommand = this._findCommand(subcommandName);
2287
- if (subCommand && !subCommand._executableHandler) {
2288
- subCommand.help();
2289
- }
2290
- return this._dispatchSubcommand(
2291
- subcommandName,
2292
- [],
2293
- [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2294
- );
2295
- }
2296
- /**
2297
- * Check this.args against expected this.registeredArguments.
2298
- *
2299
- * @private
2300
- */
2301
- _checkNumberOfArguments() {
2302
- this.registeredArguments.forEach((arg, i) => {
2303
- if (arg.required && this.args[i] == null) {
2304
- this.missingArgument(arg.name());
2305
- }
2306
- });
2307
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2308
- return;
2309
- }
2310
- if (this.args.length > this.registeredArguments.length) {
2311
- this._excessArguments(this.args);
2312
- }
2313
- }
2314
- /**
2315
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2316
- *
2317
- * @private
2318
- */
2319
- _processArguments() {
2320
- const myParseArg = (argument, value, previous) => {
2321
- let parsedValue = value;
2322
- if (value !== null && argument.parseArg) {
2323
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2324
- parsedValue = this._callParseArg(
2325
- argument,
2326
- value,
2327
- previous,
2328
- invalidValueMessage
2329
- );
2330
- }
2331
- return parsedValue;
2332
- };
2333
- this._checkNumberOfArguments();
2334
- const processedArgs = [];
2335
- this.registeredArguments.forEach((declaredArg, index) => {
2336
- let value = declaredArg.defaultValue;
2337
- if (declaredArg.variadic) {
2338
- if (index < this.args.length) {
2339
- value = this.args.slice(index);
2340
- if (declaredArg.parseArg) {
2341
- value = value.reduce((processed, v) => {
2342
- return myParseArg(declaredArg, v, processed);
2343
- }, declaredArg.defaultValue);
2344
- }
2345
- } else if (value === void 0) {
2346
- value = [];
2347
- }
2348
- } else if (index < this.args.length) {
2349
- value = this.args[index];
2350
- if (declaredArg.parseArg) {
2351
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2352
- }
2353
- }
2354
- processedArgs[index] = value;
2355
- });
2356
- this.processedArgs = processedArgs;
2357
- }
2358
- /**
2359
- * Once we have a promise we chain, but call synchronously until then.
2360
- *
2361
- * @param {(Promise|undefined)} promise
2362
- * @param {Function} fn
2363
- * @return {(Promise|undefined)}
2364
- * @private
2365
- */
2366
- _chainOrCall(promise, fn) {
2367
- if (promise?.then && typeof promise.then === "function") {
2368
- return promise.then(() => fn());
2369
- }
2370
- return fn();
2371
- }
2372
- /**
2373
- *
2374
- * @param {(Promise|undefined)} promise
2375
- * @param {string} event
2376
- * @return {(Promise|undefined)}
2377
- * @private
2378
- */
2379
- _chainOrCallHooks(promise, event) {
2380
- let result = promise;
2381
- const hooks = [];
2382
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2383
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2384
- hooks.push({ hookedCommand, callback });
2385
- });
2386
- });
2387
- if (event === "postAction") {
2388
- hooks.reverse();
2389
- }
2390
- hooks.forEach((hookDetail) => {
2391
- result = this._chainOrCall(result, () => {
2392
- return hookDetail.callback(hookDetail.hookedCommand, this);
2393
- });
2394
- });
2395
- return result;
2396
- }
2397
- /**
2398
- *
2399
- * @param {(Promise|undefined)} promise
2400
- * @param {Command} subCommand
2401
- * @param {string} event
2402
- * @return {(Promise|undefined)}
2403
- * @private
2404
- */
2405
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2406
- let result = promise;
2407
- if (this._lifeCycleHooks[event] !== void 0) {
2408
- this._lifeCycleHooks[event].forEach((hook) => {
2409
- result = this._chainOrCall(result, () => {
2410
- return hook(this, subCommand);
2411
- });
2412
- });
2413
- }
2414
- return result;
2415
- }
2416
- /**
2417
- * Process arguments in context of this command.
2418
- * Returns action result, in case it is a promise.
2419
- *
2420
- * @private
2421
- */
2422
- _parseCommand(operands, unknown) {
2423
- const parsed = this.parseOptions(unknown);
2424
- this._parseOptionsEnv();
2425
- this._parseOptionsImplied();
2426
- operands = operands.concat(parsed.operands);
2427
- unknown = parsed.unknown;
2428
- this.args = operands.concat(unknown);
2429
- if (operands && this._findCommand(operands[0])) {
2430
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2431
- }
2432
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2433
- return this._dispatchHelpCommand(operands[1]);
2434
- }
2435
- if (this._defaultCommandName) {
2436
- this._outputHelpIfRequested(unknown);
2437
- return this._dispatchSubcommand(
2438
- this._defaultCommandName,
2439
- operands,
2440
- unknown
2441
- );
2442
- }
2443
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2444
- this.help({ error: true });
2445
- }
2446
- this._outputHelpIfRequested(parsed.unknown);
2447
- this._checkForMissingMandatoryOptions();
2448
- this._checkForConflictingOptions();
2449
- const checkForUnknownOptions = () => {
2450
- if (parsed.unknown.length > 0) {
2451
- this.unknownOption(parsed.unknown[0]);
2452
- }
2453
- };
2454
- const commandEvent = `command:${this.name()}`;
2455
- if (this._actionHandler) {
2456
- checkForUnknownOptions();
2457
- this._processArguments();
2458
- let promiseChain;
2459
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2460
- promiseChain = this._chainOrCall(
2461
- promiseChain,
2462
- () => this._actionHandler(this.processedArgs)
2463
- );
2464
- if (this.parent) {
2465
- promiseChain = this._chainOrCall(promiseChain, () => {
2466
- this.parent.emit(commandEvent, operands, unknown);
2467
- });
2468
- }
2469
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2470
- return promiseChain;
2471
- }
2472
- if (this.parent?.listenerCount(commandEvent)) {
2473
- checkForUnknownOptions();
2474
- this._processArguments();
2475
- this.parent.emit(commandEvent, operands, unknown);
2476
- } else if (operands.length) {
2477
- if (this._findCommand("*")) {
2478
- return this._dispatchSubcommand("*", operands, unknown);
2479
- }
2480
- if (this.listenerCount("command:*")) {
2481
- this.emit("command:*", operands, unknown);
2482
- } else if (this.commands.length) {
2483
- this.unknownCommand();
2484
- } else {
2485
- checkForUnknownOptions();
2486
- this._processArguments();
2487
- }
2488
- } else if (this.commands.length) {
2489
- checkForUnknownOptions();
2490
- this.help({ error: true });
2491
- } else {
2492
- checkForUnknownOptions();
2493
- this._processArguments();
2494
- }
2495
- }
2496
- /**
2497
- * Find matching command.
2498
- *
2499
- * @private
2500
- * @return {Command | undefined}
2501
- */
2502
- _findCommand(name) {
2503
- if (!name) return void 0;
2504
- return this.commands.find(
2505
- (cmd) => cmd._name === name || cmd._aliases.includes(name)
2506
- );
2507
- }
2508
- /**
2509
- * Return an option matching `arg` if any.
2510
- *
2511
- * @param {string} arg
2512
- * @return {Option}
2513
- * @package
2514
- */
2515
- _findOption(arg) {
2516
- return this.options.find((option) => option.is(arg));
2517
- }
2518
- /**
2519
- * Display an error message if a mandatory option does not have a value.
2520
- * Called after checking for help flags in leaf subcommand.
2521
- *
2522
- * @private
2523
- */
2524
- _checkForMissingMandatoryOptions() {
2525
- this._getCommandAndAncestors().forEach((cmd) => {
2526
- cmd.options.forEach((anOption) => {
2527
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2528
- cmd.missingMandatoryOptionValue(anOption);
2529
- }
2530
- });
2531
- });
2532
- }
2533
- /**
2534
- * Display an error message if conflicting options are used together in this.
2535
- *
2536
- * @private
2537
- */
2538
- _checkForConflictingLocalOptions() {
2539
- const definedNonDefaultOptions = this.options.filter((option) => {
2540
- const optionKey = option.attributeName();
2541
- if (this.getOptionValue(optionKey) === void 0) {
2542
- return false;
2543
- }
2544
- return this.getOptionValueSource(optionKey) !== "default";
2545
- });
2546
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2547
- (option) => option.conflictsWith.length > 0
2548
- );
2549
- optionsWithConflicting.forEach((option) => {
2550
- const conflictingAndDefined = definedNonDefaultOptions.find(
2551
- (defined) => option.conflictsWith.includes(defined.attributeName())
2552
- );
2553
- if (conflictingAndDefined) {
2554
- this._conflictingOption(option, conflictingAndDefined);
2555
- }
2556
- });
2557
- }
2558
- /**
2559
- * Display an error message if conflicting options are used together.
2560
- * Called after checking for help flags in leaf subcommand.
2561
- *
2562
- * @private
2563
- */
2564
- _checkForConflictingOptions() {
2565
- this._getCommandAndAncestors().forEach((cmd) => {
2566
- cmd._checkForConflictingLocalOptions();
2567
- });
2568
- }
2569
- /**
2570
- * Parse options from `argv` removing known options,
2571
- * and return argv split into operands and unknown arguments.
2572
- *
2573
- * Side effects: modifies command by storing options. Does not reset state if called again.
2574
- *
2575
- * Examples:
2576
- *
2577
- * argv => operands, unknown
2578
- * --known kkk op => [op], []
2579
- * op --known kkk => [op], []
2580
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2581
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2582
- *
2583
- * @param {string[]} args
2584
- * @return {{operands: string[], unknown: string[]}}
2585
- */
2586
- parseOptions(args) {
2587
- const operands = [];
2588
- const unknown = [];
2589
- let dest = operands;
2590
- function maybeOption(arg) {
2591
- return arg.length > 1 && arg[0] === "-";
2592
- }
2593
- const negativeNumberArg = (arg) => {
2594
- if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2595
- return !this._getCommandAndAncestors().some(
2596
- (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2597
- );
2598
- };
2599
- let activeVariadicOption = null;
2600
- let activeGroup = null;
2601
- let i = 0;
2602
- while (i < args.length || activeGroup) {
2603
- const arg = activeGroup ?? args[i++];
2604
- activeGroup = null;
2605
- if (arg === "--") {
2606
- if (dest === unknown) dest.push(arg);
2607
- dest.push(...args.slice(i));
2608
- break;
2609
- }
2610
- if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2611
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2612
- continue;
2613
- }
2614
- activeVariadicOption = null;
2615
- if (maybeOption(arg)) {
2616
- const option = this._findOption(arg);
2617
- if (option) {
2618
- if (option.required) {
2619
- const value = args[i++];
2620
- if (value === void 0) this.optionMissingArgument(option);
2621
- this.emit(`option:${option.name()}`, value);
2622
- } else if (option.optional) {
2623
- let value = null;
2624
- if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2625
- value = args[i++];
2626
- }
2627
- this.emit(`option:${option.name()}`, value);
2628
- } else {
2629
- this.emit(`option:${option.name()}`);
2630
- }
2631
- activeVariadicOption = option.variadic ? option : null;
2632
- continue;
2633
- }
2634
- }
2635
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2636
- const option = this._findOption(`-${arg[1]}`);
2637
- if (option) {
2638
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2639
- this.emit(`option:${option.name()}`, arg.slice(2));
2640
- } else {
2641
- this.emit(`option:${option.name()}`);
2642
- activeGroup = `-${arg.slice(2)}`;
2643
- }
2644
- continue;
2645
- }
2646
- }
2647
- if (/^--[^=]+=/.test(arg)) {
2648
- const index = arg.indexOf("=");
2649
- const option = this._findOption(arg.slice(0, index));
2650
- if (option && (option.required || option.optional)) {
2651
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2652
- continue;
2653
- }
2654
- }
2655
- if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2656
- dest = unknown;
2657
- }
2658
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2659
- if (this._findCommand(arg)) {
2660
- operands.push(arg);
2661
- unknown.push(...args.slice(i));
2662
- break;
2663
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2664
- operands.push(arg, ...args.slice(i));
2665
- break;
2666
- } else if (this._defaultCommandName) {
2667
- unknown.push(arg, ...args.slice(i));
2668
- break;
2669
- }
2670
- }
2671
- if (this._passThroughOptions) {
2672
- dest.push(arg, ...args.slice(i));
2673
- break;
2674
- }
2675
- dest.push(arg);
2676
- }
2677
- return { operands, unknown };
2678
- }
2679
- /**
2680
- * Return an object containing local option values as key-value pairs.
2681
- *
2682
- * @return {object}
2683
- */
2684
- opts() {
2685
- if (this._storeOptionsAsProperties) {
2686
- const result = {};
2687
- const len = this.options.length;
2688
- for (let i = 0; i < len; i++) {
2689
- const key = this.options[i].attributeName();
2690
- result[key] = key === this._versionOptionName ? this._version : this[key];
2691
- }
2692
- return result;
2693
- }
2694
- return this._optionValues;
2695
- }
2696
- /**
2697
- * Return an object containing merged local and global option values as key-value pairs.
2698
- *
2699
- * @return {object}
2700
- */
2701
- optsWithGlobals() {
2702
- return this._getCommandAndAncestors().reduce(
2703
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2704
- {}
2705
- );
2706
- }
2707
- /**
2708
- * Display error message and exit (or call exitOverride).
2709
- *
2710
- * @param {string} message
2711
- * @param {object} [errorOptions]
2712
- * @param {string} [errorOptions.code] - an id string representing the error
2713
- * @param {number} [errorOptions.exitCode] - used with process.exit
2714
- */
2715
- error(message, errorOptions) {
2716
- this._outputConfiguration.outputError(
2717
- `${message}
2718
- `,
2719
- this._outputConfiguration.writeErr
2720
- );
2721
- if (typeof this._showHelpAfterError === "string") {
2722
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2723
- `);
2724
- } else if (this._showHelpAfterError) {
2725
- this._outputConfiguration.writeErr("\n");
2726
- this.outputHelp({ error: true });
2727
- }
2728
- const config = errorOptions || {};
2729
- const exitCode = config.exitCode || 1;
2730
- const code = config.code || "commander.error";
2731
- this._exit(exitCode, code, message);
2732
- }
2733
- /**
2734
- * Apply any option related environment variables, if option does
2735
- * not have a value from cli or client code.
2736
- *
2737
- * @private
2738
- */
2739
- _parseOptionsEnv() {
2740
- this.options.forEach((option) => {
2741
- if (option.envVar && option.envVar in process2.env) {
2742
- const optionKey = option.attributeName();
2743
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2744
- this.getOptionValueSource(optionKey)
2745
- )) {
2746
- if (option.required || option.optional) {
2747
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2748
- } else {
2749
- this.emit(`optionEnv:${option.name()}`);
2750
- }
2751
- }
2752
- }
2753
- });
2754
- }
2755
- /**
2756
- * Apply any implied option values, if option is undefined or default value.
2757
- *
2758
- * @private
2759
- */
2760
- _parseOptionsImplied() {
2761
- const dualHelper = new DualOptions(this.options);
2762
- const hasCustomOptionValue = (optionKey) => {
2763
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2764
- };
2765
- this.options.filter(
2766
- (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2767
- this.getOptionValue(option.attributeName()),
2768
- option
2769
- )
2770
- ).forEach((option) => {
2771
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2772
- this.setOptionValueWithSource(
2773
- impliedKey,
2774
- option.implied[impliedKey],
2775
- "implied"
2776
- );
2777
- });
2778
- });
2779
- }
2780
- /**
2781
- * Argument `name` is missing.
2782
- *
2783
- * @param {string} name
2784
- * @private
2785
- */
2786
- missingArgument(name) {
2787
- const message = `error: missing required argument '${name}'`;
2788
- this.error(message, { code: "commander.missingArgument" });
2789
- }
2790
- /**
2791
- * `Option` is missing an argument.
2792
- *
2793
- * @param {Option} option
2794
- * @private
2795
- */
2796
- optionMissingArgument(option) {
2797
- const message = `error: option '${option.flags}' argument missing`;
2798
- this.error(message, { code: "commander.optionMissingArgument" });
2799
- }
2800
- /**
2801
- * `Option` does not have a value, and is a mandatory option.
2802
- *
2803
- * @param {Option} option
2804
- * @private
2805
- */
2806
- missingMandatoryOptionValue(option) {
2807
- const message = `error: required option '${option.flags}' not specified`;
2808
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2809
- }
2810
- /**
2811
- * `Option` conflicts with another option.
2812
- *
2813
- * @param {Option} option
2814
- * @param {Option} conflictingOption
2815
- * @private
2816
- */
2817
- _conflictingOption(option, conflictingOption) {
2818
- const findBestOptionFromValue = (option2) => {
2819
- const optionKey = option2.attributeName();
2820
- const optionValue = this.getOptionValue(optionKey);
2821
- const negativeOption = this.options.find(
2822
- (target) => target.negate && optionKey === target.attributeName()
2823
- );
2824
- const positiveOption = this.options.find(
2825
- (target) => !target.negate && optionKey === target.attributeName()
2826
- );
2827
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2828
- return negativeOption;
2829
- }
2830
- return positiveOption || option2;
2831
- };
2832
- const getErrorMessage = (option2) => {
2833
- const bestOption = findBestOptionFromValue(option2);
2834
- const optionKey = bestOption.attributeName();
2835
- const source = this.getOptionValueSource(optionKey);
2836
- if (source === "env") {
2837
- return `environment variable '${bestOption.envVar}'`;
2838
- }
2839
- return `option '${bestOption.flags}'`;
2840
- };
2841
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2842
- this.error(message, { code: "commander.conflictingOption" });
2843
- }
2844
- /**
2845
- * Unknown option `flag`.
2846
- *
2847
- * @param {string} flag
2848
- * @private
2849
- */
2850
- unknownOption(flag) {
2851
- if (this._allowUnknownOption) return;
2852
- let suggestion = "";
2853
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2854
- let candidateFlags = [];
2855
- let command = this;
2856
- do {
2857
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2858
- candidateFlags = candidateFlags.concat(moreFlags);
2859
- command = command.parent;
2860
- } while (command && !command._enablePositionalOptions);
2861
- suggestion = suggestSimilar(flag, candidateFlags);
2862
- }
2863
- const message = `error: unknown option '${flag}'${suggestion}`;
2864
- this.error(message, { code: "commander.unknownOption" });
2865
- }
2866
- /**
2867
- * Excess arguments, more than expected.
2868
- *
2869
- * @param {string[]} receivedArgs
2870
- * @private
2871
- */
2872
- _excessArguments(receivedArgs) {
2873
- if (this._allowExcessArguments) return;
2874
- const expected = this.registeredArguments.length;
2875
- const s = expected === 1 ? "" : "s";
2876
- const received = receivedArgs.length;
2877
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2878
- const details = receivedArgs.join(", ");
2879
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
2880
- this.error(message, { code: "commander.excessArguments" });
2881
- }
2882
- /**
2883
- * Unknown command.
2884
- *
2885
- * @private
2886
- */
2887
- unknownCommand() {
2888
- const unknownName = this.args[0];
2889
- let suggestion = "";
2890
- if (this._showSuggestionAfterError) {
2891
- const candidateNames = [];
2892
- this.createHelp().visibleCommands(this).forEach((command) => {
2893
- candidateNames.push(command.name());
2894
- if (command.alias()) candidateNames.push(command.alias());
2895
- });
2896
- suggestion = suggestSimilar(unknownName, candidateNames);
2897
- }
2898
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2899
- this.error(message, { code: "commander.unknownCommand" });
2900
- }
2901
- /**
2902
- * Get or set the program version.
2903
- *
2904
- * This method auto-registers the "-V, --version" option which will print the version number.
2905
- *
2906
- * You can optionally supply the flags and description to override the defaults.
2907
- *
2908
- * @param {string} [str]
2909
- * @param {string} [flags]
2910
- * @param {string} [description]
2911
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2912
- */
2913
- version(str, flags, description) {
2914
- if (str === void 0) return this._version;
2915
- this._version = str;
2916
- flags = flags || "-V, --version";
2917
- description = description || "output the version number";
2918
- const versionOption = this.createOption(flags, description);
2919
- this._versionOptionName = versionOption.attributeName();
2920
- this._registerOption(versionOption);
2921
- this.on("option:" + versionOption.name(), () => {
2922
- this._outputConfiguration.writeOut(`${str}
2923
- `);
2924
- this._exit(0, "commander.version", str);
2925
- });
2926
- return this;
2927
- }
2928
- /**
2929
- * Set the description.
2930
- *
2931
- * @param {string} [str]
2932
- * @param {object} [argsDescription]
2933
- * @return {(string|Command)}
2934
- */
2935
- description(str, argsDescription) {
2936
- if (str === void 0 && argsDescription === void 0)
2937
- return this._description;
2938
- this._description = str;
2939
- if (argsDescription) {
2940
- this._argsDescription = argsDescription;
2941
- }
2942
- return this;
2943
- }
2944
- /**
2945
- * Set the summary. Used when listed as subcommand of parent.
2946
- *
2947
- * @param {string} [str]
2948
- * @return {(string|Command)}
2949
- */
2950
- summary(str) {
2951
- if (str === void 0) return this._summary;
2952
- this._summary = str;
2953
- return this;
2954
- }
2955
- /**
2956
- * Set an alias for the command.
2957
- *
2958
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2959
- *
2960
- * @param {string} [alias]
2961
- * @return {(string|Command)}
2962
- */
2963
- alias(alias) {
2964
- if (alias === void 0) return this._aliases[0];
2965
- let command = this;
2966
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2967
- command = this.commands[this.commands.length - 1];
2968
- }
2969
- if (alias === command._name)
2970
- throw new Error("Command alias can't be the same as its name");
2971
- const matchingCommand = this.parent?._findCommand(alias);
2972
- if (matchingCommand) {
2973
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2974
- throw new Error(
2975
- `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2976
- );
2977
- }
2978
- command._aliases.push(alias);
2979
- return this;
2980
- }
2981
- /**
2982
- * Set aliases for the command.
2983
- *
2984
- * Only the first alias is shown in the auto-generated help.
2985
- *
2986
- * @param {string[]} [aliases]
2987
- * @return {(string[]|Command)}
2988
- */
2989
- aliases(aliases) {
2990
- if (aliases === void 0) return this._aliases;
2991
- aliases.forEach((alias) => this.alias(alias));
2992
- return this;
2993
- }
2994
- /**
2995
- * Set / get the command usage `str`.
2996
- *
2997
- * @param {string} [str]
2998
- * @return {(string|Command)}
2999
- */
3000
- usage(str) {
3001
- if (str === void 0) {
3002
- if (this._usage) return this._usage;
3003
- const args = this.registeredArguments.map((arg) => {
3004
- return humanReadableArgName(arg);
3005
- });
3006
- return [].concat(
3007
- this.options.length || this._helpOption !== null ? "[options]" : [],
3008
- this.commands.length ? "[command]" : [],
3009
- this.registeredArguments.length ? args : []
3010
- ).join(" ");
3011
- }
3012
- this._usage = str;
3013
- return this;
3014
- }
3015
- /**
3016
- * Get or set the name of the command.
3017
- *
3018
- * @param {string} [str]
3019
- * @return {(string|Command)}
3020
- */
3021
- name(str) {
3022
- if (str === void 0) return this._name;
3023
- this._name = str;
3024
- return this;
3025
- }
3026
- /**
3027
- * Set/get the help group heading for this subcommand in parent command's help.
3028
- *
3029
- * @param {string} [heading]
3030
- * @return {Command | string}
3031
- */
3032
- helpGroup(heading) {
3033
- if (heading === void 0) return this._helpGroupHeading ?? "";
3034
- this._helpGroupHeading = heading;
3035
- return this;
3036
- }
3037
- /**
3038
- * Set/get the default help group heading for subcommands added to this command.
3039
- * (This does not override a group set directly on the subcommand using .helpGroup().)
3040
- *
3041
- * @example
3042
- * program.commandsGroup('Development Commands:);
3043
- * program.command('watch')...
3044
- * program.command('lint')...
3045
- * ...
3046
- *
3047
- * @param {string} [heading]
3048
- * @returns {Command | string}
3049
- */
3050
- commandsGroup(heading) {
3051
- if (heading === void 0) return this._defaultCommandGroup ?? "";
3052
- this._defaultCommandGroup = heading;
3053
- return this;
3054
- }
3055
- /**
3056
- * Set/get the default help group heading for options added to this command.
3057
- * (This does not override a group set directly on the option using .helpGroup().)
3058
- *
3059
- * @example
3060
- * program
3061
- * .optionsGroup('Development Options:')
3062
- * .option('-d, --debug', 'output extra debugging')
3063
- * .option('-p, --profile', 'output profiling information')
3064
- *
3065
- * @param {string} [heading]
3066
- * @returns {Command | string}
3067
- */
3068
- optionsGroup(heading) {
3069
- if (heading === void 0) return this._defaultOptionGroup ?? "";
3070
- this._defaultOptionGroup = heading;
3071
- return this;
3072
- }
3073
- /**
3074
- * @param {Option} option
3075
- * @private
3076
- */
3077
- _initOptionGroup(option) {
3078
- if (this._defaultOptionGroup && !option.helpGroupHeading)
3079
- option.helpGroup(this._defaultOptionGroup);
3080
- }
3081
- /**
3082
- * @param {Command} cmd
3083
- * @private
3084
- */
3085
- _initCommandGroup(cmd) {
3086
- if (this._defaultCommandGroup && !cmd.helpGroup())
3087
- cmd.helpGroup(this._defaultCommandGroup);
3088
- }
3089
- /**
3090
- * Set the name of the command from script filename, such as process.argv[1],
3091
- * or import.meta.filename.
3092
- *
3093
- * (Used internally and public although not documented in README.)
3094
- *
3095
- * @example
3096
- * program.nameFromFilename(import.meta.filename);
3097
- *
3098
- * @param {string} filename
3099
- * @return {Command}
3100
- */
3101
- nameFromFilename(filename) {
3102
- this._name = path.basename(filename, path.extname(filename));
3103
- return this;
3104
- }
3105
- /**
3106
- * Get or set the directory for searching for executable subcommands of this command.
3107
- *
3108
- * @example
3109
- * program.executableDir(import.meta.dirname);
3110
- * // or
3111
- * program.executableDir('subcommands');
3112
- *
3113
- * @param {string} [path]
3114
- * @return {(string|null|Command)}
3115
- */
3116
- executableDir(path2) {
3117
- if (path2 === void 0) return this._executableDir;
3118
- this._executableDir = path2;
3119
- return this;
3120
- }
3121
- /**
3122
- * Return program help documentation.
3123
- *
3124
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3125
- * @return {string}
3126
- */
3127
- helpInformation(contextOptions) {
3128
- const helper = this.createHelp();
3129
- const context = this._getOutputContext(contextOptions);
3130
- helper.prepareContext({
3131
- error: context.error,
3132
- helpWidth: context.helpWidth,
3133
- outputHasColors: context.hasColors
3134
- });
3135
- const text = helper.formatHelp(this, helper);
3136
- if (context.hasColors) return text;
3137
- return this._outputConfiguration.stripColor(text);
3138
- }
3139
- /**
3140
- * @typedef HelpContext
3141
- * @type {object}
3142
- * @property {boolean} error
3143
- * @property {number} helpWidth
3144
- * @property {boolean} hasColors
3145
- * @property {function} write - includes stripColor if needed
3146
- *
3147
- * @returns {HelpContext}
3148
- * @private
3149
- */
3150
- _getOutputContext(contextOptions) {
3151
- contextOptions = contextOptions || {};
3152
- const error = !!contextOptions.error;
3153
- let baseWrite;
3154
- let hasColors;
3155
- let helpWidth;
3156
- if (error) {
3157
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
3158
- hasColors = this._outputConfiguration.getErrHasColors();
3159
- helpWidth = this._outputConfiguration.getErrHelpWidth();
3160
- } else {
3161
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3162
- hasColors = this._outputConfiguration.getOutHasColors();
3163
- helpWidth = this._outputConfiguration.getOutHelpWidth();
3164
- }
3165
- const write = (str) => {
3166
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3167
- return baseWrite(str);
3168
- };
3169
- return { error, write, hasColors, helpWidth };
3170
- }
3171
- /**
3172
- * Output help information for this command.
3173
- *
3174
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3175
- *
3176
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3177
- */
3178
- outputHelp(contextOptions) {
3179
- let deprecatedCallback;
3180
- if (typeof contextOptions === "function") {
3181
- deprecatedCallback = contextOptions;
3182
- contextOptions = void 0;
3183
- }
3184
- const outputContext = this._getOutputContext(contextOptions);
3185
- const eventContext = {
3186
- error: outputContext.error,
3187
- write: outputContext.write,
3188
- command: this
3189
- };
3190
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3191
- this.emit("beforeHelp", eventContext);
3192
- let helpInformation = this.helpInformation({ error: outputContext.error });
3193
- if (deprecatedCallback) {
3194
- helpInformation = deprecatedCallback(helpInformation);
3195
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3196
- throw new Error("outputHelp callback must return a string or a Buffer");
3197
- }
3198
- }
3199
- outputContext.write(helpInformation);
3200
- if (this._getHelpOption()?.long) {
3201
- this.emit(this._getHelpOption().long);
3202
- }
3203
- this.emit("afterHelp", eventContext);
3204
- this._getCommandAndAncestors().forEach(
3205
- (command) => command.emit("afterAllHelp", eventContext)
3206
- );
3207
- }
3208
- /**
3209
- * You can pass in flags and a description to customise the built-in help option.
3210
- * Pass in false to disable the built-in help option.
3211
- *
3212
- * @example
3213
- * program.helpOption('-?, --help' 'show help'); // customise
3214
- * program.helpOption(false); // disable
3215
- *
3216
- * @param {(string | boolean)} flags
3217
- * @param {string} [description]
3218
- * @return {Command} `this` command for chaining
3219
- */
3220
- helpOption(flags, description) {
3221
- if (typeof flags === "boolean") {
3222
- if (flags) {
3223
- if (this._helpOption === null) this._helpOption = void 0;
3224
- if (this._defaultOptionGroup) {
3225
- this._initOptionGroup(this._getHelpOption());
3226
- }
3227
- } else {
3228
- this._helpOption = null;
3229
- }
3230
- return this;
3231
- }
3232
- this._helpOption = this.createOption(
3233
- flags ?? "-h, --help",
3234
- description ?? "display help for command"
3235
- );
3236
- if (flags || description) this._initOptionGroup(this._helpOption);
3237
- return this;
3238
- }
3239
- /**
3240
- * Lazy create help option.
3241
- * Returns null if has been disabled with .helpOption(false).
3242
- *
3243
- * @returns {(Option | null)} the help option
3244
- * @package
3245
- */
3246
- _getHelpOption() {
3247
- if (this._helpOption === void 0) {
3248
- this.helpOption(void 0, void 0);
3249
- }
3250
- return this._helpOption;
3251
- }
3252
- /**
3253
- * Supply your own option to use for the built-in help option.
3254
- * This is an alternative to using helpOption() to customise the flags and description etc.
3255
- *
3256
- * @param {Option} option
3257
- * @return {Command} `this` command for chaining
3258
- */
3259
- addHelpOption(option) {
3260
- this._helpOption = option;
3261
- this._initOptionGroup(option);
3262
- return this;
3263
- }
3264
- /**
3265
- * Output help information and exit.
3266
- *
3267
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3268
- *
3269
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3270
- */
3271
- help(contextOptions) {
3272
- this.outputHelp(contextOptions);
3273
- let exitCode = Number(process2.exitCode ?? 0);
3274
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3275
- exitCode = 1;
3276
- }
3277
- this._exit(exitCode, "commander.help", "(outputHelp)");
3278
- }
3279
- /**
3280
- * // Do a little typing to coordinate emit and listener for the help text events.
3281
- * @typedef HelpTextEventContext
3282
- * @type {object}
3283
- * @property {boolean} error
3284
- * @property {Command} command
3285
- * @property {function} write
3286
- */
3287
- /**
3288
- * Add additional text to be displayed with the built-in help.
3289
- *
3290
- * Position is 'before' or 'after' to affect just this command,
3291
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3292
- *
3293
- * @param {string} position - before or after built-in help
3294
- * @param {(string | Function)} text - string to add, or a function returning a string
3295
- * @return {Command} `this` command for chaining
3296
- */
3297
- addHelpText(position, text) {
3298
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3299
- if (!allowedValues.includes(position)) {
3300
- throw new Error(`Unexpected value for position to addHelpText.
3301
- Expecting one of '${allowedValues.join("', '")}'`);
3302
- }
3303
- const helpEvent = `${position}Help`;
3304
- this.on(helpEvent, (context) => {
3305
- let helpStr;
3306
- if (typeof text === "function") {
3307
- helpStr = text({ error: context.error, command: context.command });
3308
- } else {
3309
- helpStr = text;
3310
- }
3311
- if (helpStr) {
3312
- context.write(`${helpStr}
3313
- `);
3314
- }
3315
- });
3316
- return this;
3317
- }
3318
- /**
3319
- * Output help information if help flags specified
3320
- *
3321
- * @param {Array} args - array of options to search for help flags
3322
- * @private
3323
- */
3324
- _outputHelpIfRequested(args) {
3325
- const helpOption = this._getHelpOption();
3326
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3327
- if (helpRequested) {
3328
- this.outputHelp();
3329
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3330
- }
3331
- }
3332
- };
3333
- function incrementNodeInspectorPort(args) {
3334
- return args.map((arg) => {
3335
- if (!arg.startsWith("--inspect")) {
3336
- return arg;
3337
- }
3338
- let debugOption;
3339
- let debugHost = "127.0.0.1";
3340
- let debugPort = "9229";
3341
- let match;
3342
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3343
- debugOption = match[1];
3344
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3345
- debugOption = match[1];
3346
- if (/^\d+$/.test(match[3])) {
3347
- debugPort = match[3];
3348
- } else {
3349
- debugHost = match[3];
3350
- }
3351
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3352
- debugOption = match[1];
3353
- debugHost = match[3];
3354
- debugPort = match[4];
3355
- }
3356
- if (debugOption && debugPort !== "0") {
3357
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3358
- }
3359
- return arg;
3360
- });
3361
- }
3362
- function useColor() {
3363
- if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3364
- return false;
3365
- if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3366
- return true;
3367
- return void 0;
3368
- }
3369
-
3370
- // ../node_modules/commander/index.js
3371
- var program = new Command();
3372
-
3373
- // ../packages/cli/src/index.ts
3374
- import { readFileSync as readFileSync2 } from "fs";
3375
- import { resolve as resolve3 } from "path";
3376
-
3377
- // ../packages/cli/src/commands/generate/component/component.command.ts
3378
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
3379
- import { join } from "path";
3380
-
3381
- // ../packages/cli/src/utils/case.utils.ts
3382
- function toPascalCase(str) {
3383
- return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^(.)/, (_, c) => c.toUpperCase());
3384
- }
3385
- function toKebabCase(str) {
3386
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
3387
- }
3388
-
3389
- // ../packages/cli/src/commands/generate/component/component.command.ts
3390
- function generateComponent(name, path2, force, style) {
3391
- const dir = join(path2, name);
3392
- style ??= "css";
3393
- if (existsSync(dir)) {
3394
- if (force) {
3395
- console.log(`Deleting "${name}"...`);
3396
- rmSync(dir, { recursive: true, force: true });
3397
- console.log("\u2714 Component Deleted.");
3398
- } else {
3399
- console.error(`\u2716 Directory "${name}" already exists.`);
3400
- process.exit(1);
3401
- }
3402
- }
3403
- mkdirSync(dir, { recursive: true });
3404
- const files = [
3405
- [`${name}.xd.component.ts`, tsTemplate(name, style)],
3406
- [`${name}.xd.component.html`, htmlTemplate(name)],
3407
- [`${name}.xd.component.${style}`, cssTemplate(name)],
3408
- [`${name}.xd.component.spec.ts`, specTemplate(name)]
3409
- ];
3410
- for (const [filename, content] of files) {
3411
- writeFileSync(join(dir, filename), content, "utf8");
3412
- }
3413
- console.log();
3414
- console.log(`\u2714 Component "${name}" generated:`);
3415
- for (const [filename] of files) {
3416
- console.log(`${name}/${filename}`);
3417
- }
3418
- }
3419
- function tsTemplate(name, style) {
3420
- const className = toPascalCase(name);
3421
- return `import { BaseWebComponent, WebComponent } from '@xaendar/core';
23
+ - ${n}`;throw new Error(s)}_executeSubCommand(t,e){e=e.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,u){let p=d.resolve(l,u);if(v.existsSync(p))return p;if(i.includes(d.extname(u)))return;let O=i.find(_=>v.existsSync(`${p}${_}`));if(O)return`${p}${O}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,r=this._executableDir||"";if(this._scriptPath){let l;try{l=v.realpathSync(this._scriptPath)}catch{l=this._scriptPath}r=d.resolve(d.dirname(l),r)}if(r){let l=n(r,s);if(!l&&!t._executableFile&&this._scriptPath){let u=d.basename(this._scriptPath,d.extname(this._scriptPath));u!==this._name&&(l=n(r,`${u}-${t._name}`))}s=l||s}let a=i.includes(d.extname(s)),h;m.platform!=="win32"?a?(e.unshift(s),e=P(m.execArgv).concat(e),h=k.spawn(m.argv[0],e,{stdio:"inherit"})):h=k.spawn(s,e,{stdio:"inherit"}):(this._checkForMissingExecutable(s,r,t._name),e.unshift(s),e=P(m.execArgv).concat(e),h=k.spawn(m.execPath,e,{stdio:"inherit"})),h.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{m.on(u,()=>{h.killed===!1&&h.exitCode===null&&h.kill(u)})});let c=this._exitCallback;h.on("close",l=>{l=l??1,c?c(new f(l,"commander.executeSubCommandAsync","(close)")):m.exit(l)}),h.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(s,r,t._name);else if(l.code==="EACCES")throw new Error(`'${s}' not executable`);if(!c)m.exit(1);else{let u=new f(1,"commander.executeSubCommandAsync","(error)");u.nestedError=l,c(u)}}),this.runningCommand=h}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,e.concat(i));else return n._parseCommand(e,i)}),s}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,a)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((r,a)=>t(i,a,r),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=t(i,s,i.defaultValue))),e[n]=s}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[e]!==void 0).forEach(s=>{s._lifeCycleHooks[e].forEach(r=>{n.push({hookedCommand:s,callback:r})})}),e==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,e))}),n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(s,t,e)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=t.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],n=e;function s(l){return l.length>1&&l[0]==="-"}let r=l=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l)?!this._getCommandAndAncestors().some(u=>u.options.map(p=>p.short).some(p=>/^-\d$/.test(p))):!1,a=null,h=null,c=0;for(;c<t.length||h;){let l=h??t[c++];if(h=null,l==="--"){n===i&&n.push(l),n.push(...t.slice(c));break}if(a&&(!s(l)||r(l))){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let p=t[c++];p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;c<t.length&&(!s(t[c])||r(t[c]))&&(p=t[c++]),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),h=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),p=this._findOption(l.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,l.slice(u+1));continue}}if(n===e&&s(l)&&!(this.commands.length===0&&r(l))&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(l)){e.push(l),i.push(...t.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){e.push(l,...t.slice(c));break}else if(this._defaultCommandName){i.push(l,...t.slice(c));break}}if(this._passThroughOptions){n.push(l,...t.slice(c));break}n.push(l)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
24
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
+ `),this.outputHelp({error:!0}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new E(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=r=>{let a=r.attributeName(),h=this.getOptionValue(a),c=this.options.find(u=>u.negate&&a===u.attributeName()),l=this.options.find(u=>!u.negate&&a===u.attributeName());return c&&(c.presetArg===void 0&&h===!1||c.presetArg!==void 0&&h===c.presetArg)?c:l||r},n=r=>{let a=i(r),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(r),s=s.parent}while(s&&!s._enablePositionalOptions);e=H(t,n)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",n=t.length,s=this.parent?` for '${this.name()}'`:"",r=t.join(", "),a=`error: too many arguments${s}. Expected ${e} argument${i} but got ${n}: ${r}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),e=H(t,n)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
27
+ `),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>$(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=d.basename(t,d.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",n))}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
28
+ Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let r;typeof e=="function"?r=e({error:s.error,command:s.command}):r=e,r&&s.write(`${r}
29
+ `)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function P(o){return o.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return(s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function D(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}var A=new g;import{readFileSync as _t}from"fs";import{resolve as Ct}from"path";import{existsSync as tt,mkdirSync as et,rmSync as it,writeFileSync as nt}from"fs";import{join as F}from"path";function w(o){return o.replace(/[-_](.)/g,(t,e)=>e.toUpperCase()).replace(/^(.)/,(t,e)=>e.toUpperCase())}function W(o){return o.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function S(o,t,e,i){let n=F(t,o);i??="css",tt(n)&&(e?(console.log(`Deleting "${o}"...`),it(n,{recursive:!0,force:!0}),console.log("\u2714 Component Deleted.")):(console.error(`\u2716 Directory "${o}" already exists.`),process.exit(1))),et(n,{recursive:!0});let s=[[`${o}.xd.component.ts`,st(o,i)],[`${o}.xd.component.html`,rt(o)],[`${o}.xd.component.${i}`,ot(o)],[`${o}.xd.component.spec.ts`,at(o)]];for(let[r,a]of s)nt(F(n,r),a,"utf8");console.log(),console.log(`\u2714 Component "${o}" generated:`);for(let[r]of s)console.log(`${o}/${r}`)}function st(o,t){let e=w(o);return`import { BaseWebComponent, WebComponent } from '@xaendar/core';
3422
30
 
3423
31
  @WebComponent({
3424
- selector: '${toKebabCase(name)}',
3425
- styleUrl: './${name}.xd.component.${style}',
3426
- templateUrl: './${name}.xd.component.html'
32
+ selector: '${W(o)}',
33
+ styleUrl: './${o}.xd.component.${t}',
34
+ templateUrl: './${o}.xd.component.html'
3427
35
  })
3428
- export class ${className}Component extends BaseWebComponent {
36
+ export class ${e}Component extends BaseWebComponent {
3429
37
 
3430
- }`;
3431
- }
3432
- function htmlTemplate(name) {
3433
- return `<p>${name} works!</p>
3434
- `;
3435
- }
3436
- function cssTemplate(_name) {
3437
- return `/* component styles */
3438
- `;
3439
- }
3440
- function specTemplate(name) {
3441
- const className = toPascalCase(name);
3442
- return `import { describe, expect, it } from "vitest";
3443
- import { ${className}Component } from './${name}.xd.component';
38
+ }`}function rt(o){return`<p>${o} works!</p>
39
+ `}function ot(o){return`/* component styles */
40
+ `}function at(o){let t=w(o);return`import { describe, expect, it } from "vitest";
41
+ import { ${t}Component } from './${o}.xd.component';
3444
42
 
3445
- describe('${className}Component', () => {
43
+ describe('${t}Component', () => {
3446
44
  it('should create', () => {
3447
- const component = new ${className}Component();
45
+ const component = new ${t}Component();
3448
46
  expect(component).toBeTruthy();
3449
47
  });
3450
48
  });
3451
- `;
3452
- }
3453
-
3454
- // ../packages/cli/src/commands/generate/generate.command.ts
3455
- function generateCommand() {
3456
- const generate = new Command("generate").alias("g").description("Generate Xaendar building blocks");
3457
- 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) => {
3458
- const path2 = options.path || process.cwd();
3459
- generateComponent(name, path2, !!options.force);
3460
- });
3461
- return generate;
3462
- }
3463
-
3464
- // ../packages/cli/src/commands/new/new.command.ts
3465
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, writeFileSync as writeFileSync2 } from "fs";
3466
- import { resolve as resolve2 } from "path/win32";
3467
-
3468
- // ../packages/cli/src/commands/new/structure.ts
3469
- import { readFileSync } from "fs";
3470
- import { resolve } from "path";
3471
-
3472
- // ../packages/cli/src/commands/new/templates/index-html.ts
3473
- function indexHtml(name) {
3474
- return `<!DOCTYPE html>
49
+ `}function G(){let o=new g("generate").alias("g").description("Generate Xaendar building blocks");return o.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((t,e)=>{let i=e.path||process.cwd();S(t,i,!!e.force)}),o}import{existsSync as ct,mkdirSync as B,readdirSync as pt,writeFileSync as mt}from"fs";import{resolve as V}from"path/win32";import{readFileSync as lt}from"fs";import{resolve as ut}from"path";function N(o){return`<!DOCTYPE html>
3475
50
  <html lang="en">
3476
51
  <head>
3477
52
  <meta charset="UTF-8" />
3478
53
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
3479
- <title>${name}</title>
54
+ <title>${o}</title>
3480
55
  <script type="module" src="./signals.ts"></script>
3481
56
  <script type="module" src="./main.ts"></script>
3482
57
  </head>
3483
58
  <body>
3484
- <${name}></${name}>
59
+ <${o}></${o}>
3485
60
  </body>
3486
- </html>`;
3487
- }
3488
-
3489
- // ../packages/cli/src/commands/new/templates/main-ts.ts
3490
- function mainTs(componentName) {
3491
- const componentClassName = `${toPascalCase(componentName)}Component`;
3492
- return `import { ${componentClassName} } from './${componentName}/${componentName}.xd.component';
3493
-
3494
- console.log(${componentClassName});`;
3495
- }
61
+ </html>`}function I(o){let t=`${w(o)}Component`;return`import { ${t} } from './${o}/${o}.xd.component';
3496
62
 
3497
- // ../packages/cli/src/commands/new/templates/package-json.ts
3498
- function packageJson(name, version2) {
3499
- return `{
3500
- "name": "${name}",
63
+ console.log(${t});`}function j(o,t){return`{
64
+ "name": "${o}",
3501
65
  "version": "0.0.1",
3502
66
  "private": true,
3503
67
  "scripts": {
@@ -3507,34 +71,24 @@ function packageJson(name, version2) {
3507
71
  "xd": "xd"
3508
72
  },
3509
73
  "dependencies": {
3510
- "@xaendar/core": "^${version2}",
3511
- "@xaendar/signals": "^${version2}",
3512
- "@xaendar/types": "^${version2}"
74
+ "@xaendar/core": "^${t}",
75
+ "@xaendar/signals": "^${t}",
76
+ "@xaendar/types": "^${t}"
3513
77
  },
3514
78
  "devDependencies": {
3515
79
  "@babel/plugin-proposal-decorators": "^7.29.0",
3516
80
  "@rolldown/plugin-babel": "^0.2.3",
3517
81
  "@vitest/coverage-v8": "^4.1.7",
3518
- "@xaendar/build-tools": "^${version2}",
3519
- "@xaendar/cli": "^${version2}",
82
+ "@xaendar/build-tools": "^${t}",
83
+ "@xaendar/cli": "^${t}",
3520
84
  "typescript": "^6.0.3",
3521
85
  "vite": "^8.0.14",
3522
86
  "vitest": "^4.1.7"
3523
87
  }
3524
88
  }
3525
- `;
3526
- }
3527
-
3528
- // ../packages/cli/src/commands/new/templates/signal-ts.ts
3529
- function signalTs() {
3530
- return `import { loadSignals } from "@xaendar/signals";
3531
-
3532
- loadSignals();`;
3533
- }
89
+ `}function M(){return`import { loadSignals } from "@xaendar/signals";
3534
90
 
3535
- // ../packages/cli/src/commands/new/templates/tsconfig-json.ts
3536
- function tsconfigJson() {
3537
- return `{
91
+ loadSignals();`}function L(){return`{
3538
92
  "compilerOptions": {
3539
93
  "target": "ESNext",
3540
94
  "module": "ESNext",
@@ -3563,12 +117,7 @@ function tsconfigJson() {
3563
117
  "node_modules",
3564
118
  "**/*.spec.ts"
3565
119
  ]
3566
- }`;
3567
- }
3568
-
3569
- // ../packages/cli/src/commands/new/templates/vite-config-ts.ts
3570
- function viteConfigTs() {
3571
- return `import babel from "@rolldown/plugin-babel";
120
+ }`}function U(){return`import babel from "@rolldown/plugin-babel";
3572
121
  import { xaendarPlugin } from "@xaendar/build-tools";
3573
122
  import { defineConfig } from 'vite';
3574
123
 
@@ -3600,148 +149,14 @@ export default defineConfig({
3600
149
  }),
3601
150
  xaendarPlugin()
3602
151
  ]
3603
- });`;
3604
- }
3605
-
3606
- // ../packages/cli/src/commands/new/templates/xaendar-json.ts
3607
- function xaendarJson(name, style) {
3608
- return `{
3609
- "name": "${name}",
152
+ });`}function q(o,t){return`{
153
+ "name": "${o}",
3610
154
  "entry": "src/main.ts",
3611
155
  "outDir": "dist",
3612
156
  "assetsDir": "assets",
3613
157
  "generate": {
3614
158
  "components": {
3615
- "style": "${style}"
3616
- }
3617
- }
3618
- }`;
3619
- }
3620
-
3621
- // ../packages/cli/src/commands/new/structure.ts
3622
- function readCliVersion() {
3623
- try {
3624
- const cliPackageJson = JSON.parse(readFileSync(resolve(import.meta.filename, "..", "./package.json"), "utf8"));
3625
- if (!cliPackageJson.version) {
3626
- throw new Error("Unable to determine Xaendar CLI version.");
159
+ "style": "${t}"
3627
160
  }
3628
- return cliPackageJson.version;
3629
- } catch (error) {
3630
- console.error("Error reading Xaendar CLI version:", error);
3631
- process.exit(1);
3632
161
  }
3633
- }
3634
- function buildStructure(context) {
3635
- const version2 = readCliVersion();
3636
- const name = context.name;
3637
- const componentName = `${name}-root`;
3638
- return [
3639
- {
3640
- type: "file",
3641
- name: "package.json",
3642
- content: packageJson(name, version2)
3643
- },
3644
- {
3645
- type: "file",
3646
- name: "xaendar.json",
3647
- content: xaendarJson(name, context.style)
3648
- },
3649
- {
3650
- type: "file",
3651
- name: "vite.config.ts",
3652
- content: viteConfigTs()
3653
- },
3654
- {
3655
- type: "file",
3656
- name: "tsconfig.json",
3657
- content: tsconfigJson()
3658
- },
3659
- {
3660
- type: "directory",
3661
- name: "src",
3662
- children: [
3663
- {
3664
- type: "file",
3665
- name: "index.html",
3666
- content: indexHtml(componentName)
3667
- },
3668
- {
3669
- type: "file",
3670
- name: "signals.ts",
3671
- content: signalTs()
3672
- },
3673
- {
3674
- type: "file",
3675
- name: "main.ts",
3676
- content: mainTs(componentName)
3677
- },
3678
- {
3679
- type: "generateComponent",
3680
- name: componentName
3681
- }
3682
- ]
3683
- }
3684
- ];
3685
- }
3686
-
3687
- // ../packages/cli/src/commands/new/new.command.ts
3688
- import { execSync } from "child_process";
3689
- function newCommand() {
3690
- return new Command("new").description("Scaffold a new Xaendar project").argument("<name>", "Name of the project to create").option("-p, --path <path>", "Custom path for the generated project (default: current directory)").option("-s, --style <style>", "CSS preprocessor to use (css, scss, less, styl)", "css").action((name, options) => {
3691
- const style = resolveStyleOptions(options.style);
3692
- const workingDirectory = options.path || process.cwd();
3693
- const projectDirectory = resolve2(workingDirectory, name);
3694
- checkAndCreateProjectDirectory(projectDirectory);
3695
- createFiles(buildStructure({ name, style }), projectDirectory, style);
3696
- execSync("npm i", { stdio: "inherit", cwd: projectDirectory });
3697
- });
3698
- }
3699
- function resolveStyleOptions(style) {
3700
- const validStyles = ["css", "scss", "less", "styl"];
3701
- if (!style) {
3702
- return "css";
3703
- }
3704
- if (!validStyles.includes(style)) {
3705
- console.error(`\u2716 Invalid style option: ${style}`);
3706
- process.exit(1);
3707
- }
3708
- return style;
3709
- }
3710
- function checkAndCreateProjectDirectory(path2) {
3711
- const exists = existsSync2(path2);
3712
- if (exists && readdirSync(path2).length) {
3713
- console.error(`\u2716 Cannot create project: target directory is not empty: ${path2}`);
3714
- process.exit(1);
3715
- }
3716
- if (!exists) {
3717
- mkdirSync2(path2);
3718
- }
3719
- }
3720
- function createFiles(entries, basePath, style) {
3721
- entries.forEach((entry) => {
3722
- switch (entry.type) {
3723
- case "file":
3724
- case void 0:
3725
- const content = entry.content;
3726
- writeFileSync2(resolve2(basePath, entry.name), content, "utf8");
3727
- break;
3728
- case "directory":
3729
- const dirPath = resolve2(basePath, entry.name);
3730
- mkdirSync2(dirPath);
3731
- if (entry.children) {
3732
- createFiles(entry.children, dirPath, style);
3733
- }
3734
- break;
3735
- case "generateComponent":
3736
- generateComponent(entry.name, basePath, false, style);
3737
- break;
3738
- }
3739
- });
3740
- }
3741
-
3742
- // ../packages/cli/src/index.ts
3743
- var version = JSON.parse(readFileSync2(resolve3(import.meta.filename, "..", "package.json"), "utf-8")).version;
3744
- program.name("xd").description("Xaendar CLI").version(version);
3745
- program.addCommand(generateCommand());
3746
- program.addCommand(newCommand());
3747
- program.parse();
162
+ }`}function ht(){try{let o=JSON.parse(lt(ut(import.meta.filename,"..","./package.json"),"utf8"));if(!o.version)throw new Error("Unable to determine Xaendar CLI version.");return o.version}catch(o){console.error("Error reading Xaendar CLI version:",o),process.exit(1)}}function R(o){let t=ht(),e=o.name,i=`${e}-root`;return[{type:"file",name:"package.json",content:j(e,t)},{type:"file",name:"xaendar.json",content:q(e,o.style)},{type:"file",name:"vite.config.ts",content:U()},{type:"file",name:"tsconfig.json",content:L()},{type:"directory",name:"src",children:[{type:"file",name:"index.html",content:N(i)},{type:"file",name:"signals.ts",content:M()},{type:"file",name:"main.ts",content:I(i)},{type:"generateComponent",name:i}]}]}import{execSync as dt}from"child_process";function J(){return new g("new").description("Scaffold a new Xaendar project").argument("<name>","Name of the project to create").option("-p, --path <path>","Custom path for the generated project (default: current directory)").option("-s, --style <style>","CSS preprocessor to use (css, scss, less, styl)","css").action((o,t)=>{let e=ft(t.style),i=t.path||process.cwd(),n=V(i,o);gt(n),K(R({name:o,style:e}),n,e),dt("npm i",{stdio:"inherit",cwd:n})})}function ft(o){let t=["css","scss","less","styl"];return o?(t.includes(o)||(console.error(`\u2716 Invalid style option: ${o}`),process.exit(1)),o):"css"}function gt(o){let t=ct(o);t&&pt(o).length&&(console.error(`\u2716 Cannot create project: target directory is not empty: ${o}`),process.exit(1)),t||B(o)}function K(o,t,e){o.forEach(i=>{switch(i.type){case"file":case void 0:let n=i.content;mt(V(t,i.name),n,"utf8");break;case"directory":let s=V(t,i.name);B(s),i.children&&K(i.children,s,e);break;case"generateComponent":S(i.name,t,!1,e);break}})}var Ot=JSON.parse(_t(Ct(import.meta.filename,"..","package.json"),"utf-8")).version;A.name("xd").description("Xaendar CLI").version(Ot);A.addCommand(G());A.addCommand(J());A.parse();