vslides 1.0.0

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