sslbear-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +120 -2
  2. package/dist/index.js +4362 -0
  3. package/package.json +38 -4
package/dist/index.js ADDED
@@ -0,0 +1,4362 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from "node:module";
3
+ const require = __createRequire(import.meta.url);
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __commonJS = (cb, mod) => function __require2() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+
40
+ // node_modules/commander/lib/error.js
41
+ var require_error = __commonJS({
42
+ "node_modules/commander/lib/error.js"(exports) {
43
+ "use strict";
44
+ var CommanderError2 = class extends Error {
45
+ /**
46
+ * Constructs the CommanderError class
47
+ * @param {number} exitCode suggested exit code which could be used with process.exit
48
+ * @param {string} code an id string representing the error
49
+ * @param {string} message human-readable description of the error
50
+ */
51
+ constructor(exitCode, code2, message) {
52
+ super(message);
53
+ Error.captureStackTrace(this, this.constructor);
54
+ this.name = this.constructor.name;
55
+ this.code = code2;
56
+ this.exitCode = exitCode;
57
+ this.nestedError = void 0;
58
+ }
59
+ };
60
+ var InvalidArgumentError2 = class extends CommanderError2 {
61
+ /**
62
+ * Constructs the InvalidArgumentError class
63
+ * @param {string} [message] explanation of why argument is invalid
64
+ */
65
+ constructor(message) {
66
+ super(1, "commander.invalidArgument", message);
67
+ Error.captureStackTrace(this, this.constructor);
68
+ this.name = this.constructor.name;
69
+ }
70
+ };
71
+ exports.CommanderError = CommanderError2;
72
+ exports.InvalidArgumentError = InvalidArgumentError2;
73
+ }
74
+ });
75
+
76
+ // node_modules/commander/lib/argument.js
77
+ var require_argument = __commonJS({
78
+ "node_modules/commander/lib/argument.js"(exports) {
79
+ "use strict";
80
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
81
+ var Argument2 = class {
82
+ /**
83
+ * Initialize a new command argument with the given name and description.
84
+ * The default is that the argument is required, and you can explicitly
85
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
86
+ *
87
+ * @param {string} name
88
+ * @param {string} [description]
89
+ */
90
+ constructor(name, description) {
91
+ this.description = description || "";
92
+ this.variadic = false;
93
+ this.parseArg = void 0;
94
+ this.defaultValue = void 0;
95
+ this.defaultValueDescription = void 0;
96
+ this.argChoices = void 0;
97
+ switch (name[0]) {
98
+ case "<":
99
+ this.required = true;
100
+ this._name = name.slice(1, -1);
101
+ break;
102
+ case "[":
103
+ this.required = false;
104
+ this._name = name.slice(1, -1);
105
+ break;
106
+ default:
107
+ this.required = true;
108
+ this._name = name;
109
+ break;
110
+ }
111
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
112
+ this.variadic = true;
113
+ this._name = this._name.slice(0, -3);
114
+ }
115
+ }
116
+ /**
117
+ * Return argument name.
118
+ *
119
+ * @return {string}
120
+ */
121
+ name() {
122
+ return this._name;
123
+ }
124
+ /**
125
+ * @package
126
+ */
127
+ _concatValue(value2, previous) {
128
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
129
+ return [value2];
130
+ }
131
+ return previous.concat(value2);
132
+ }
133
+ /**
134
+ * Set the default value, and optionally supply the description to be displayed in the help.
135
+ *
136
+ * @param {*} value
137
+ * @param {string} [description]
138
+ * @return {Argument}
139
+ */
140
+ default(value2, description) {
141
+ this.defaultValue = value2;
142
+ this.defaultValueDescription = description;
143
+ return this;
144
+ }
145
+ /**
146
+ * Set the custom handler for processing CLI command arguments into argument values.
147
+ *
148
+ * @param {Function} [fn]
149
+ * @return {Argument}
150
+ */
151
+ argParser(fn) {
152
+ this.parseArg = fn;
153
+ return this;
154
+ }
155
+ /**
156
+ * Only allow argument value to be one of choices.
157
+ *
158
+ * @param {string[]} values
159
+ * @return {Argument}
160
+ */
161
+ choices(values) {
162
+ this.argChoices = values.slice();
163
+ this.parseArg = (arg, previous) => {
164
+ if (!this.argChoices.includes(arg)) {
165
+ throw new InvalidArgumentError2(
166
+ `Allowed choices are ${this.argChoices.join(", ")}.`
167
+ );
168
+ }
169
+ if (this.variadic) {
170
+ return this._concatValue(arg, previous);
171
+ }
172
+ return arg;
173
+ };
174
+ return this;
175
+ }
176
+ /**
177
+ * Make argument required.
178
+ *
179
+ * @returns {Argument}
180
+ */
181
+ argRequired() {
182
+ this.required = true;
183
+ return this;
184
+ }
185
+ /**
186
+ * Make argument optional.
187
+ *
188
+ * @returns {Argument}
189
+ */
190
+ argOptional() {
191
+ this.required = false;
192
+ return this;
193
+ }
194
+ };
195
+ function humanReadableArgName(arg) {
196
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
197
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
198
+ }
199
+ exports.Argument = Argument2;
200
+ exports.humanReadableArgName = humanReadableArgName;
201
+ }
202
+ });
203
+
204
+ // node_modules/commander/lib/help.js
205
+ var require_help = __commonJS({
206
+ "node_modules/commander/lib/help.js"(exports) {
207
+ "use strict";
208
+ var { humanReadableArgName } = require_argument();
209
+ var Help2 = class {
210
+ constructor() {
211
+ this.helpWidth = void 0;
212
+ this.sortSubcommands = false;
213
+ this.sortOptions = false;
214
+ this.showGlobalOptions = false;
215
+ }
216
+ /**
217
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
218
+ *
219
+ * @param {Command} cmd
220
+ * @returns {Command[]}
221
+ */
222
+ visibleCommands(cmd) {
223
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
224
+ const helpCommand = cmd._getHelpCommand();
225
+ if (helpCommand && !helpCommand._hidden) {
226
+ visibleCommands.push(helpCommand);
227
+ }
228
+ if (this.sortSubcommands) {
229
+ visibleCommands.sort((a, b) => {
230
+ return a.name().localeCompare(b.name());
231
+ });
232
+ }
233
+ return visibleCommands;
234
+ }
235
+ /**
236
+ * Compare options for sort.
237
+ *
238
+ * @param {Option} a
239
+ * @param {Option} b
240
+ * @returns {number}
241
+ */
242
+ compareOptions(a, b) {
243
+ const getSortKey = (option) => {
244
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
245
+ };
246
+ return getSortKey(a).localeCompare(getSortKey(b));
247
+ }
248
+ /**
249
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
250
+ *
251
+ * @param {Command} cmd
252
+ * @returns {Option[]}
253
+ */
254
+ visibleOptions(cmd) {
255
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
256
+ const helpOption = cmd._getHelpOption();
257
+ if (helpOption && !helpOption.hidden) {
258
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
259
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
260
+ if (!removeShort && !removeLong) {
261
+ visibleOptions.push(helpOption);
262
+ } else if (helpOption.long && !removeLong) {
263
+ visibleOptions.push(
264
+ cmd.createOption(helpOption.long, helpOption.description)
265
+ );
266
+ } else if (helpOption.short && !removeShort) {
267
+ visibleOptions.push(
268
+ cmd.createOption(helpOption.short, helpOption.description)
269
+ );
270
+ }
271
+ }
272
+ if (this.sortOptions) {
273
+ visibleOptions.sort(this.compareOptions);
274
+ }
275
+ return visibleOptions;
276
+ }
277
+ /**
278
+ * Get an array of the visible global options. (Not including help.)
279
+ *
280
+ * @param {Command} cmd
281
+ * @returns {Option[]}
282
+ */
283
+ visibleGlobalOptions(cmd) {
284
+ if (!this.showGlobalOptions) return [];
285
+ const globalOptions = [];
286
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
287
+ const visibleOptions = ancestorCmd.options.filter(
288
+ (option) => !option.hidden
289
+ );
290
+ globalOptions.push(...visibleOptions);
291
+ }
292
+ if (this.sortOptions) {
293
+ globalOptions.sort(this.compareOptions);
294
+ }
295
+ return globalOptions;
296
+ }
297
+ /**
298
+ * Get an array of the arguments if any have a description.
299
+ *
300
+ * @param {Command} cmd
301
+ * @returns {Argument[]}
302
+ */
303
+ visibleArguments(cmd) {
304
+ if (cmd._argsDescription) {
305
+ cmd.registeredArguments.forEach((argument) => {
306
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
307
+ });
308
+ }
309
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
310
+ return cmd.registeredArguments;
311
+ }
312
+ return [];
313
+ }
314
+ /**
315
+ * Get the command term to show in the list of subcommands.
316
+ *
317
+ * @param {Command} cmd
318
+ * @returns {string}
319
+ */
320
+ subcommandTerm(cmd) {
321
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
322
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
323
+ (args ? " " + args : "");
324
+ }
325
+ /**
326
+ * Get the option term to show in the list of options.
327
+ *
328
+ * @param {Option} option
329
+ * @returns {string}
330
+ */
331
+ optionTerm(option) {
332
+ return option.flags;
333
+ }
334
+ /**
335
+ * Get the argument term to show in the list of arguments.
336
+ *
337
+ * @param {Argument} argument
338
+ * @returns {string}
339
+ */
340
+ argumentTerm(argument) {
341
+ return argument.name();
342
+ }
343
+ /**
344
+ * Get the longest command term length.
345
+ *
346
+ * @param {Command} cmd
347
+ * @param {Help} helper
348
+ * @returns {number}
349
+ */
350
+ longestSubcommandTermLength(cmd, helper) {
351
+ return helper.visibleCommands(cmd).reduce((max, command) => {
352
+ return Math.max(max, helper.subcommandTerm(command).length);
353
+ }, 0);
354
+ }
355
+ /**
356
+ * Get the longest option term length.
357
+ *
358
+ * @param {Command} cmd
359
+ * @param {Help} helper
360
+ * @returns {number}
361
+ */
362
+ longestOptionTermLength(cmd, helper) {
363
+ return helper.visibleOptions(cmd).reduce((max, option) => {
364
+ return Math.max(max, helper.optionTerm(option).length);
365
+ }, 0);
366
+ }
367
+ /**
368
+ * Get the longest global option term length.
369
+ *
370
+ * @param {Command} cmd
371
+ * @param {Help} helper
372
+ * @returns {number}
373
+ */
374
+ longestGlobalOptionTermLength(cmd, helper) {
375
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
376
+ return Math.max(max, helper.optionTerm(option).length);
377
+ }, 0);
378
+ }
379
+ /**
380
+ * Get the longest argument term length.
381
+ *
382
+ * @param {Command} cmd
383
+ * @param {Help} helper
384
+ * @returns {number}
385
+ */
386
+ longestArgumentTermLength(cmd, helper) {
387
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
388
+ return Math.max(max, helper.argumentTerm(argument).length);
389
+ }, 0);
390
+ }
391
+ /**
392
+ * Get the command usage to be displayed at the top of the built-in help.
393
+ *
394
+ * @param {Command} cmd
395
+ * @returns {string}
396
+ */
397
+ commandUsage(cmd) {
398
+ let cmdName = cmd._name;
399
+ if (cmd._aliases[0]) {
400
+ cmdName = cmdName + "|" + cmd._aliases[0];
401
+ }
402
+ let ancestorCmdNames = "";
403
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
404
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
405
+ }
406
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
407
+ }
408
+ /**
409
+ * Get the description for the command.
410
+ *
411
+ * @param {Command} cmd
412
+ * @returns {string}
413
+ */
414
+ commandDescription(cmd) {
415
+ return cmd.description();
416
+ }
417
+ /**
418
+ * Get the subcommand summary to show in the list of subcommands.
419
+ * (Fallback to description for backwards compatibility.)
420
+ *
421
+ * @param {Command} cmd
422
+ * @returns {string}
423
+ */
424
+ subcommandDescription(cmd) {
425
+ return cmd.summary() || cmd.description();
426
+ }
427
+ /**
428
+ * Get the option description to show in the list of options.
429
+ *
430
+ * @param {Option} option
431
+ * @return {string}
432
+ */
433
+ optionDescription(option) {
434
+ const extraInfo = [];
435
+ if (option.argChoices) {
436
+ extraInfo.push(
437
+ // use stringify to match the display of the default value
438
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
439
+ );
440
+ }
441
+ if (option.defaultValue !== void 0) {
442
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
443
+ if (showDefault) {
444
+ extraInfo.push(
445
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
446
+ );
447
+ }
448
+ }
449
+ if (option.presetArg !== void 0 && option.optional) {
450
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
451
+ }
452
+ if (option.envVar !== void 0) {
453
+ extraInfo.push(`env: ${option.envVar}`);
454
+ }
455
+ if (extraInfo.length > 0) {
456
+ return `${option.description} (${extraInfo.join(", ")})`;
457
+ }
458
+ return option.description;
459
+ }
460
+ /**
461
+ * Get the argument description to show in the list of arguments.
462
+ *
463
+ * @param {Argument} argument
464
+ * @return {string}
465
+ */
466
+ argumentDescription(argument) {
467
+ const extraInfo = [];
468
+ if (argument.argChoices) {
469
+ extraInfo.push(
470
+ // use stringify to match the display of the default value
471
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
472
+ );
473
+ }
474
+ if (argument.defaultValue !== void 0) {
475
+ extraInfo.push(
476
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
477
+ );
478
+ }
479
+ if (extraInfo.length > 0) {
480
+ const extraDescripton = `(${extraInfo.join(", ")})`;
481
+ if (argument.description) {
482
+ return `${argument.description} ${extraDescripton}`;
483
+ }
484
+ return extraDescripton;
485
+ }
486
+ return argument.description;
487
+ }
488
+ /**
489
+ * Generate the built-in help text.
490
+ *
491
+ * @param {Command} cmd
492
+ * @param {Help} helper
493
+ * @returns {string}
494
+ */
495
+ formatHelp(cmd, helper) {
496
+ const termWidth = helper.padWidth(cmd, helper);
497
+ const helpWidth = helper.helpWidth || 80;
498
+ const itemIndentWidth = 2;
499
+ const itemSeparatorWidth = 2;
500
+ function formatItem(term, description) {
501
+ if (description) {
502
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
503
+ return helper.wrap(
504
+ fullText,
505
+ helpWidth - itemIndentWidth,
506
+ termWidth + itemSeparatorWidth
507
+ );
508
+ }
509
+ return term;
510
+ }
511
+ function formatList(textArray) {
512
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
513
+ }
514
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
515
+ const commandDescription = helper.commandDescription(cmd);
516
+ if (commandDescription.length > 0) {
517
+ output = output.concat([
518
+ helper.wrap(commandDescription, helpWidth, 0),
519
+ ""
520
+ ]);
521
+ }
522
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
523
+ return formatItem(
524
+ helper.argumentTerm(argument),
525
+ helper.argumentDescription(argument)
526
+ );
527
+ });
528
+ if (argumentList.length > 0) {
529
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
530
+ }
531
+ const optionList = helper.visibleOptions(cmd).map((option) => {
532
+ return formatItem(
533
+ helper.optionTerm(option),
534
+ helper.optionDescription(option)
535
+ );
536
+ });
537
+ if (optionList.length > 0) {
538
+ output = output.concat(["Options:", formatList(optionList), ""]);
539
+ }
540
+ if (this.showGlobalOptions) {
541
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
542
+ return formatItem(
543
+ helper.optionTerm(option),
544
+ helper.optionDescription(option)
545
+ );
546
+ });
547
+ if (globalOptionList.length > 0) {
548
+ output = output.concat([
549
+ "Global Options:",
550
+ formatList(globalOptionList),
551
+ ""
552
+ ]);
553
+ }
554
+ }
555
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
556
+ return formatItem(
557
+ helper.subcommandTerm(cmd2),
558
+ helper.subcommandDescription(cmd2)
559
+ );
560
+ });
561
+ if (commandList.length > 0) {
562
+ output = output.concat(["Commands:", formatList(commandList), ""]);
563
+ }
564
+ return output.join("\n");
565
+ }
566
+ /**
567
+ * Calculate the pad width from the maximum term length.
568
+ *
569
+ * @param {Command} cmd
570
+ * @param {Help} helper
571
+ * @returns {number}
572
+ */
573
+ padWidth(cmd, helper) {
574
+ return Math.max(
575
+ helper.longestOptionTermLength(cmd, helper),
576
+ helper.longestGlobalOptionTermLength(cmd, helper),
577
+ helper.longestSubcommandTermLength(cmd, helper),
578
+ helper.longestArgumentTermLength(cmd, helper)
579
+ );
580
+ }
581
+ /**
582
+ * Wrap the given string to width characters per line, with lines after the first indented.
583
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
584
+ *
585
+ * @param {string} str
586
+ * @param {number} width
587
+ * @param {number} indent
588
+ * @param {number} [minColumnWidth=40]
589
+ * @return {string}
590
+ *
591
+ */
592
+ wrap(str, width, indent, minColumnWidth = 40) {
593
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
594
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
595
+ if (str.match(manualIndent)) return str;
596
+ const columnWidth = width - indent;
597
+ if (columnWidth < minColumnWidth) return str;
598
+ const leadingStr = str.slice(0, indent);
599
+ const columnText = str.slice(indent).replace("\r\n", "\n");
600
+ const indentString = " ".repeat(indent);
601
+ const zeroWidthSpace = "\u200B";
602
+ const breaks = `\\s${zeroWidthSpace}`;
603
+ const regex = new RegExp(
604
+ `
605
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
606
+ "g"
607
+ );
608
+ const lines = columnText.match(regex) || [];
609
+ return leadingStr + lines.map((line, i) => {
610
+ if (line === "\n") return "";
611
+ return (i > 0 ? indentString : "") + line.trimEnd();
612
+ }).join("\n");
613
+ }
614
+ };
615
+ exports.Help = Help2;
616
+ }
617
+ });
618
+
619
+ // node_modules/commander/lib/option.js
620
+ var require_option = __commonJS({
621
+ "node_modules/commander/lib/option.js"(exports) {
622
+ "use strict";
623
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
624
+ var Option2 = class {
625
+ /**
626
+ * Initialize a new `Option` with the given `flags` and `description`.
627
+ *
628
+ * @param {string} flags
629
+ * @param {string} [description]
630
+ */
631
+ constructor(flags, description) {
632
+ this.flags = flags;
633
+ this.description = description || "";
634
+ this.required = flags.includes("<");
635
+ this.optional = flags.includes("[");
636
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
637
+ this.mandatory = false;
638
+ const optionFlags = splitOptionFlags(flags);
639
+ this.short = optionFlags.shortFlag;
640
+ this.long = optionFlags.longFlag;
641
+ this.negate = false;
642
+ if (this.long) {
643
+ this.negate = this.long.startsWith("--no-");
644
+ }
645
+ this.defaultValue = void 0;
646
+ this.defaultValueDescription = void 0;
647
+ this.presetArg = void 0;
648
+ this.envVar = void 0;
649
+ this.parseArg = void 0;
650
+ this.hidden = false;
651
+ this.argChoices = void 0;
652
+ this.conflictsWith = [];
653
+ this.implied = void 0;
654
+ }
655
+ /**
656
+ * Set the default value, and optionally supply the description to be displayed in the help.
657
+ *
658
+ * @param {*} value
659
+ * @param {string} [description]
660
+ * @return {Option}
661
+ */
662
+ default(value2, description) {
663
+ this.defaultValue = value2;
664
+ this.defaultValueDescription = description;
665
+ return this;
666
+ }
667
+ /**
668
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
669
+ * The custom processing (parseArg) is called.
670
+ *
671
+ * @example
672
+ * new Option('--color').default('GREYSCALE').preset('RGB');
673
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
674
+ *
675
+ * @param {*} arg
676
+ * @return {Option}
677
+ */
678
+ preset(arg) {
679
+ this.presetArg = arg;
680
+ return this;
681
+ }
682
+ /**
683
+ * Add option name(s) that conflict with this option.
684
+ * An error will be displayed if conflicting options are found during parsing.
685
+ *
686
+ * @example
687
+ * new Option('--rgb').conflicts('cmyk');
688
+ * new Option('--js').conflicts(['ts', 'jsx']);
689
+ *
690
+ * @param {(string | string[])} names
691
+ * @return {Option}
692
+ */
693
+ conflicts(names) {
694
+ this.conflictsWith = this.conflictsWith.concat(names);
695
+ return this;
696
+ }
697
+ /**
698
+ * Specify implied option values for when this option is set and the implied options are not.
699
+ *
700
+ * The custom processing (parseArg) is not called on the implied values.
701
+ *
702
+ * @example
703
+ * program
704
+ * .addOption(new Option('--log', 'write logging information to file'))
705
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
706
+ *
707
+ * @param {object} impliedOptionValues
708
+ * @return {Option}
709
+ */
710
+ implies(impliedOptionValues) {
711
+ let newImplied = impliedOptionValues;
712
+ if (typeof impliedOptionValues === "string") {
713
+ newImplied = { [impliedOptionValues]: true };
714
+ }
715
+ this.implied = Object.assign(this.implied || {}, newImplied);
716
+ return this;
717
+ }
718
+ /**
719
+ * Set environment variable to check for option value.
720
+ *
721
+ * An environment variable is only used if when processed the current option value is
722
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
723
+ *
724
+ * @param {string} name
725
+ * @return {Option}
726
+ */
727
+ env(name) {
728
+ this.envVar = name;
729
+ return this;
730
+ }
731
+ /**
732
+ * Set the custom handler for processing CLI option arguments into option values.
733
+ *
734
+ * @param {Function} [fn]
735
+ * @return {Option}
736
+ */
737
+ argParser(fn) {
738
+ this.parseArg = fn;
739
+ return this;
740
+ }
741
+ /**
742
+ * Whether the option is mandatory and must have a value after parsing.
743
+ *
744
+ * @param {boolean} [mandatory=true]
745
+ * @return {Option}
746
+ */
747
+ makeOptionMandatory(mandatory = true) {
748
+ this.mandatory = !!mandatory;
749
+ return this;
750
+ }
751
+ /**
752
+ * Hide option in help.
753
+ *
754
+ * @param {boolean} [hide=true]
755
+ * @return {Option}
756
+ */
757
+ hideHelp(hide = true) {
758
+ this.hidden = !!hide;
759
+ return this;
760
+ }
761
+ /**
762
+ * @package
763
+ */
764
+ _concatValue(value2, previous) {
765
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
766
+ return [value2];
767
+ }
768
+ return previous.concat(value2);
769
+ }
770
+ /**
771
+ * Only allow option value to be one of choices.
772
+ *
773
+ * @param {string[]} values
774
+ * @return {Option}
775
+ */
776
+ choices(values) {
777
+ this.argChoices = values.slice();
778
+ this.parseArg = (arg, previous) => {
779
+ if (!this.argChoices.includes(arg)) {
780
+ throw new InvalidArgumentError2(
781
+ `Allowed choices are ${this.argChoices.join(", ")}.`
782
+ );
783
+ }
784
+ if (this.variadic) {
785
+ return this._concatValue(arg, previous);
786
+ }
787
+ return arg;
788
+ };
789
+ return this;
790
+ }
791
+ /**
792
+ * Return option name.
793
+ *
794
+ * @return {string}
795
+ */
796
+ name() {
797
+ if (this.long) {
798
+ return this.long.replace(/^--/, "");
799
+ }
800
+ return this.short.replace(/^-/, "");
801
+ }
802
+ /**
803
+ * Return option name, in a camelcase format that can be used
804
+ * as a object attribute key.
805
+ *
806
+ * @return {string}
807
+ */
808
+ attributeName() {
809
+ return camelcase(this.name().replace(/^no-/, ""));
810
+ }
811
+ /**
812
+ * Check if `arg` matches the short or long flag.
813
+ *
814
+ * @param {string} arg
815
+ * @return {boolean}
816
+ * @package
817
+ */
818
+ is(arg) {
819
+ return this.short === arg || this.long === arg;
820
+ }
821
+ /**
822
+ * Return whether a boolean option.
823
+ *
824
+ * Options are one of boolean, negated, required argument, or optional argument.
825
+ *
826
+ * @return {boolean}
827
+ * @package
828
+ */
829
+ isBoolean() {
830
+ return !this.required && !this.optional && !this.negate;
831
+ }
832
+ };
833
+ var DualOptions = class {
834
+ /**
835
+ * @param {Option[]} options
836
+ */
837
+ constructor(options) {
838
+ this.positiveOptions = /* @__PURE__ */ new Map();
839
+ this.negativeOptions = /* @__PURE__ */ new Map();
840
+ this.dualOptions = /* @__PURE__ */ new Set();
841
+ options.forEach((option) => {
842
+ if (option.negate) {
843
+ this.negativeOptions.set(option.attributeName(), option);
844
+ } else {
845
+ this.positiveOptions.set(option.attributeName(), option);
846
+ }
847
+ });
848
+ this.negativeOptions.forEach((value2, key) => {
849
+ if (this.positiveOptions.has(key)) {
850
+ this.dualOptions.add(key);
851
+ }
852
+ });
853
+ }
854
+ /**
855
+ * Did the value come from the option, and not from possible matching dual option?
856
+ *
857
+ * @param {*} value
858
+ * @param {Option} option
859
+ * @returns {boolean}
860
+ */
861
+ valueFromOption(value2, option) {
862
+ const optionKey = option.attributeName();
863
+ if (!this.dualOptions.has(optionKey)) return true;
864
+ const preset = this.negativeOptions.get(optionKey).presetArg;
865
+ const negativeValue = preset !== void 0 ? preset : false;
866
+ return option.negate === (negativeValue === value2);
867
+ }
868
+ };
869
+ function camelcase(str) {
870
+ return str.split("-").reduce((str2, word) => {
871
+ return str2 + word[0].toUpperCase() + word.slice(1);
872
+ });
873
+ }
874
+ function splitOptionFlags(flags) {
875
+ let shortFlag;
876
+ let longFlag;
877
+ const flagParts = flags.split(/[ |,]+/);
878
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
879
+ shortFlag = flagParts.shift();
880
+ longFlag = flagParts.shift();
881
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
882
+ shortFlag = longFlag;
883
+ longFlag = void 0;
884
+ }
885
+ return { shortFlag, longFlag };
886
+ }
887
+ exports.Option = Option2;
888
+ exports.DualOptions = DualOptions;
889
+ }
890
+ });
891
+
892
+ // node_modules/commander/lib/suggestSimilar.js
893
+ var require_suggestSimilar = __commonJS({
894
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
895
+ "use strict";
896
+ var maxDistance = 3;
897
+ function editDistance(a, b) {
898
+ if (Math.abs(a.length - b.length) > maxDistance)
899
+ return Math.max(a.length, b.length);
900
+ const d = [];
901
+ for (let i = 0; i <= a.length; i++) {
902
+ d[i] = [i];
903
+ }
904
+ for (let j = 0; j <= b.length; j++) {
905
+ d[0][j] = j;
906
+ }
907
+ for (let j = 1; j <= b.length; j++) {
908
+ for (let i = 1; i <= a.length; i++) {
909
+ let cost = 1;
910
+ if (a[i - 1] === b[j - 1]) {
911
+ cost = 0;
912
+ } else {
913
+ cost = 1;
914
+ }
915
+ d[i][j] = Math.min(
916
+ d[i - 1][j] + 1,
917
+ // deletion
918
+ d[i][j - 1] + 1,
919
+ // insertion
920
+ d[i - 1][j - 1] + cost
921
+ // substitution
922
+ );
923
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
924
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
925
+ }
926
+ }
927
+ }
928
+ return d[a.length][b.length];
929
+ }
930
+ function suggestSimilar(word, candidates) {
931
+ if (!candidates || candidates.length === 0) return "";
932
+ candidates = Array.from(new Set(candidates));
933
+ const searchingOptions = word.startsWith("--");
934
+ if (searchingOptions) {
935
+ word = word.slice(2);
936
+ candidates = candidates.map((candidate) => candidate.slice(2));
937
+ }
938
+ let similar = [];
939
+ let bestDistance = maxDistance;
940
+ const minSimilarity = 0.4;
941
+ candidates.forEach((candidate) => {
942
+ if (candidate.length <= 1) return;
943
+ const distance = editDistance(word, candidate);
944
+ const length = Math.max(word.length, candidate.length);
945
+ const similarity = (length - distance) / length;
946
+ if (similarity > minSimilarity) {
947
+ if (distance < bestDistance) {
948
+ bestDistance = distance;
949
+ similar = [candidate];
950
+ } else if (distance === bestDistance) {
951
+ similar.push(candidate);
952
+ }
953
+ }
954
+ });
955
+ similar.sort((a, b) => a.localeCompare(b));
956
+ if (searchingOptions) {
957
+ similar = similar.map((candidate) => `--${candidate}`);
958
+ }
959
+ if (similar.length > 1) {
960
+ return `
961
+ (Did you mean one of ${similar.join(", ")}?)`;
962
+ }
963
+ if (similar.length === 1) {
964
+ return `
965
+ (Did you mean ${similar[0]}?)`;
966
+ }
967
+ return "";
968
+ }
969
+ exports.suggestSimilar = suggestSimilar;
970
+ }
971
+ });
972
+
973
+ // node_modules/commander/lib/command.js
974
+ var require_command = __commonJS({
975
+ "node_modules/commander/lib/command.js"(exports) {
976
+ "use strict";
977
+ var EventEmitter = __require("events").EventEmitter;
978
+ var childProcess = __require("child_process");
979
+ var path = __require("path");
980
+ var fs = __require("fs");
981
+ var process2 = __require("process");
982
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
983
+ var { CommanderError: CommanderError2 } = require_error();
984
+ var { Help: Help2 } = require_help();
985
+ var { Option: Option2, DualOptions } = require_option();
986
+ var { suggestSimilar } = require_suggestSimilar();
987
+ var Command2 = class _Command extends EventEmitter {
988
+ /**
989
+ * Initialize a new `Command`.
990
+ *
991
+ * @param {string} [name]
992
+ */
993
+ constructor(name) {
994
+ super();
995
+ this.commands = [];
996
+ this.options = [];
997
+ this.parent = null;
998
+ this._allowUnknownOption = false;
999
+ this._allowExcessArguments = true;
1000
+ this.registeredArguments = [];
1001
+ this._args = this.registeredArguments;
1002
+ this.args = [];
1003
+ this.rawArgs = [];
1004
+ this.processedArgs = [];
1005
+ this._scriptPath = null;
1006
+ this._name = name || "";
1007
+ this._optionValues = {};
1008
+ this._optionValueSources = {};
1009
+ this._storeOptionsAsProperties = false;
1010
+ this._actionHandler = null;
1011
+ this._executableHandler = false;
1012
+ this._executableFile = null;
1013
+ this._executableDir = null;
1014
+ this._defaultCommandName = null;
1015
+ this._exitCallback = null;
1016
+ this._aliases = [];
1017
+ this._combineFlagAndOptionalValue = true;
1018
+ this._description = "";
1019
+ this._summary = "";
1020
+ this._argsDescription = void 0;
1021
+ this._enablePositionalOptions = false;
1022
+ this._passThroughOptions = false;
1023
+ this._lifeCycleHooks = {};
1024
+ this._showHelpAfterError = false;
1025
+ this._showSuggestionAfterError = true;
1026
+ this._outputConfiguration = {
1027
+ writeOut: (str) => process2.stdout.write(str),
1028
+ writeErr: (str) => process2.stderr.write(str),
1029
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1030
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1031
+ outputError: (str, write) => write(str)
1032
+ };
1033
+ this._hidden = false;
1034
+ this._helpOption = void 0;
1035
+ this._addImplicitHelpCommand = void 0;
1036
+ this._helpCommand = void 0;
1037
+ this._helpConfiguration = {};
1038
+ }
1039
+ /**
1040
+ * Copy settings that are useful to have in common across root command and subcommands.
1041
+ *
1042
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1043
+ *
1044
+ * @param {Command} sourceCommand
1045
+ * @return {Command} `this` command for chaining
1046
+ */
1047
+ copyInheritedSettings(sourceCommand) {
1048
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1049
+ this._helpOption = sourceCommand._helpOption;
1050
+ this._helpCommand = sourceCommand._helpCommand;
1051
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1052
+ this._exitCallback = sourceCommand._exitCallback;
1053
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1054
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1055
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1056
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1057
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1058
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1059
+ return this;
1060
+ }
1061
+ /**
1062
+ * @returns {Command[]}
1063
+ * @private
1064
+ */
1065
+ _getCommandAndAncestors() {
1066
+ const result = [];
1067
+ for (let command = this; command; command = command.parent) {
1068
+ result.push(command);
1069
+ }
1070
+ return result;
1071
+ }
1072
+ /**
1073
+ * Define a command.
1074
+ *
1075
+ * There are two styles of command: pay attention to where to put the description.
1076
+ *
1077
+ * @example
1078
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1079
+ * program
1080
+ * .command('clone <source> [destination]')
1081
+ * .description('clone a repository into a newly created directory')
1082
+ * .action((source, destination) => {
1083
+ * console.log('clone command called');
1084
+ * });
1085
+ *
1086
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1087
+ * program
1088
+ * .command('start <service>', 'start named service')
1089
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1090
+ *
1091
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1092
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1093
+ * @param {object} [execOpts] - configuration options (for executable)
1094
+ * @return {Command} returns new command for action handler, or `this` for executable command
1095
+ */
1096
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1097
+ let desc = actionOptsOrExecDesc;
1098
+ let opts = execOpts;
1099
+ if (typeof desc === "object" && desc !== null) {
1100
+ opts = desc;
1101
+ desc = null;
1102
+ }
1103
+ opts = opts || {};
1104
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1105
+ const cmd = this.createCommand(name);
1106
+ if (desc) {
1107
+ cmd.description(desc);
1108
+ cmd._executableHandler = true;
1109
+ }
1110
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1111
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1112
+ cmd._executableFile = opts.executableFile || null;
1113
+ if (args) cmd.arguments(args);
1114
+ this._registerCommand(cmd);
1115
+ cmd.parent = this;
1116
+ cmd.copyInheritedSettings(this);
1117
+ if (desc) return this;
1118
+ return cmd;
1119
+ }
1120
+ /**
1121
+ * Factory routine to create a new unattached command.
1122
+ *
1123
+ * See .command() for creating an attached subcommand, which uses this routine to
1124
+ * create the command. You can override createCommand to customise subcommands.
1125
+ *
1126
+ * @param {string} [name]
1127
+ * @return {Command} new command
1128
+ */
1129
+ createCommand(name) {
1130
+ return new _Command(name);
1131
+ }
1132
+ /**
1133
+ * You can customise the help with a subclass of Help by overriding createHelp,
1134
+ * or by overriding Help properties using configureHelp().
1135
+ *
1136
+ * @return {Help}
1137
+ */
1138
+ createHelp() {
1139
+ return Object.assign(new Help2(), this.configureHelp());
1140
+ }
1141
+ /**
1142
+ * You can customise the help by overriding Help properties using configureHelp(),
1143
+ * or with a subclass of Help by overriding createHelp().
1144
+ *
1145
+ * @param {object} [configuration] - configuration options
1146
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1147
+ */
1148
+ configureHelp(configuration) {
1149
+ if (configuration === void 0) return this._helpConfiguration;
1150
+ this._helpConfiguration = configuration;
1151
+ return this;
1152
+ }
1153
+ /**
1154
+ * The default output goes to stdout and stderr. You can customise this for special
1155
+ * applications. You can also customise the display of errors by overriding outputError.
1156
+ *
1157
+ * The configuration properties are all functions:
1158
+ *
1159
+ * // functions to change where being written, stdout and stderr
1160
+ * writeOut(str)
1161
+ * writeErr(str)
1162
+ * // matching functions to specify width for wrapping help
1163
+ * getOutHelpWidth()
1164
+ * getErrHelpWidth()
1165
+ * // functions based on what is being written out
1166
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1167
+ *
1168
+ * @param {object} [configuration] - configuration options
1169
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1170
+ */
1171
+ configureOutput(configuration) {
1172
+ if (configuration === void 0) return this._outputConfiguration;
1173
+ Object.assign(this._outputConfiguration, configuration);
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Display the help or a custom message after an error occurs.
1178
+ *
1179
+ * @param {(boolean|string)} [displayHelp]
1180
+ * @return {Command} `this` command for chaining
1181
+ */
1182
+ showHelpAfterError(displayHelp = true) {
1183
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1184
+ this._showHelpAfterError = displayHelp;
1185
+ return this;
1186
+ }
1187
+ /**
1188
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1189
+ *
1190
+ * @param {boolean} [displaySuggestion]
1191
+ * @return {Command} `this` command for chaining
1192
+ */
1193
+ showSuggestionAfterError(displaySuggestion = true) {
1194
+ this._showSuggestionAfterError = !!displaySuggestion;
1195
+ return this;
1196
+ }
1197
+ /**
1198
+ * Add a prepared subcommand.
1199
+ *
1200
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1201
+ *
1202
+ * @param {Command} cmd - new subcommand
1203
+ * @param {object} [opts] - configuration options
1204
+ * @return {Command} `this` command for chaining
1205
+ */
1206
+ addCommand(cmd, opts) {
1207
+ if (!cmd._name) {
1208
+ throw new Error(`Command passed to .addCommand() must have a name
1209
+ - specify the name in Command constructor or using .name()`);
1210
+ }
1211
+ opts = opts || {};
1212
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1213
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1214
+ this._registerCommand(cmd);
1215
+ cmd.parent = this;
1216
+ cmd._checkForBrokenPassThrough();
1217
+ return this;
1218
+ }
1219
+ /**
1220
+ * Factory routine to create a new unattached argument.
1221
+ *
1222
+ * See .argument() for creating an attached argument, which uses this routine to
1223
+ * create the argument. You can override createArgument to return a custom argument.
1224
+ *
1225
+ * @param {string} name
1226
+ * @param {string} [description]
1227
+ * @return {Argument} new argument
1228
+ */
1229
+ createArgument(name, description) {
1230
+ return new Argument2(name, description);
1231
+ }
1232
+ /**
1233
+ * Define argument syntax for command.
1234
+ *
1235
+ * The default is that the argument is required, and you can explicitly
1236
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1237
+ *
1238
+ * @example
1239
+ * program.argument('<input-file>');
1240
+ * program.argument('[output-file]');
1241
+ *
1242
+ * @param {string} name
1243
+ * @param {string} [description]
1244
+ * @param {(Function|*)} [fn] - custom argument processing function
1245
+ * @param {*} [defaultValue]
1246
+ * @return {Command} `this` command for chaining
1247
+ */
1248
+ argument(name, description, fn, defaultValue) {
1249
+ const argument = this.createArgument(name, description);
1250
+ if (typeof fn === "function") {
1251
+ argument.default(defaultValue).argParser(fn);
1252
+ } else {
1253
+ argument.default(fn);
1254
+ }
1255
+ this.addArgument(argument);
1256
+ return this;
1257
+ }
1258
+ /**
1259
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1260
+ *
1261
+ * See also .argument().
1262
+ *
1263
+ * @example
1264
+ * program.arguments('<cmd> [env]');
1265
+ *
1266
+ * @param {string} names
1267
+ * @return {Command} `this` command for chaining
1268
+ */
1269
+ arguments(names) {
1270
+ names.trim().split(/ +/).forEach((detail) => {
1271
+ this.argument(detail);
1272
+ });
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Define argument syntax for command, adding a prepared argument.
1277
+ *
1278
+ * @param {Argument} argument
1279
+ * @return {Command} `this` command for chaining
1280
+ */
1281
+ addArgument(argument) {
1282
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1283
+ if (previousArgument && previousArgument.variadic) {
1284
+ throw new Error(
1285
+ `only the last argument can be variadic '${previousArgument.name()}'`
1286
+ );
1287
+ }
1288
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1289
+ throw new Error(
1290
+ `a default value for a required argument is never used: '${argument.name()}'`
1291
+ );
1292
+ }
1293
+ this.registeredArguments.push(argument);
1294
+ return this;
1295
+ }
1296
+ /**
1297
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1298
+ *
1299
+ * @example
1300
+ * program.helpCommand('help [cmd]');
1301
+ * program.helpCommand('help [cmd]', 'show help');
1302
+ * program.helpCommand(false); // suppress default help command
1303
+ * program.helpCommand(true); // add help command even if no subcommands
1304
+ *
1305
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1306
+ * @param {string} [description] - custom description
1307
+ * @return {Command} `this` command for chaining
1308
+ */
1309
+ helpCommand(enableOrNameAndArgs, description) {
1310
+ if (typeof enableOrNameAndArgs === "boolean") {
1311
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1312
+ return this;
1313
+ }
1314
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1315
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1316
+ const helpDescription = description ?? "display help for command";
1317
+ const helpCommand = this.createCommand(helpName);
1318
+ helpCommand.helpOption(false);
1319
+ if (helpArgs) helpCommand.arguments(helpArgs);
1320
+ if (helpDescription) 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, code2, message) {
1406
+ if (this._exitCallback) {
1407
+ this._exitCallback(new CommanderError2(exitCode, code2, 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, value2, previous, invalidArgumentMessage) {
1463
+ try {
1464
+ return target.parseArg(value2, 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, value2) {
1750
+ return this.setOptionValueWithSource(key, value2, 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, value2, source) {
1761
+ if (this._storeOptionsAsProperties) {
1762
+ this[key] = value2;
1763
+ } else {
1764
+ this._optionValues[key] = value2;
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)) return localBin;
1914
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1915
+ const foundExt = sourceExt.find(
1916
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1917
+ );
1918
+ if (foundExt) return `${localBin}${foundExt}`;
1919
+ return void 0;
1920
+ }
1921
+ this._checkForMissingMandatoryOptions();
1922
+ this._checkForConflictingOptions();
1923
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1924
+ let executableDir = this._executableDir || "";
1925
+ if (this._scriptPath) {
1926
+ let resolvedScriptPath;
1927
+ try {
1928
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1929
+ } catch (err) {
1930
+ resolvedScriptPath = this._scriptPath;
1931
+ }
1932
+ executableDir = path.resolve(
1933
+ path.dirname(resolvedScriptPath),
1934
+ executableDir
1935
+ );
1936
+ }
1937
+ if (executableDir) {
1938
+ let localFile = findFile(executableDir, executableFile);
1939
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1940
+ const legacyName = path.basename(
1941
+ this._scriptPath,
1942
+ path.extname(this._scriptPath)
1943
+ );
1944
+ if (legacyName !== this._name) {
1945
+ localFile = findFile(
1946
+ executableDir,
1947
+ `${legacyName}-${subcommand._name}`
1948
+ );
1949
+ }
1950
+ }
1951
+ executableFile = localFile || executableFile;
1952
+ }
1953
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1954
+ let proc;
1955
+ if (process2.platform !== "win32") {
1956
+ if (launchWithNode) {
1957
+ args.unshift(executableFile);
1958
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1959
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1960
+ } else {
1961
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1962
+ }
1963
+ } else {
1964
+ args.unshift(executableFile);
1965
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1966
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1967
+ }
1968
+ if (!proc.killed) {
1969
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1970
+ signals.forEach((signal) => {
1971
+ process2.on(signal, () => {
1972
+ if (proc.killed === false && proc.exitCode === null) {
1973
+ proc.kill(signal);
1974
+ }
1975
+ });
1976
+ });
1977
+ }
1978
+ const exitCallback = this._exitCallback;
1979
+ proc.on("close", (code2) => {
1980
+ code2 = code2 ?? 1;
1981
+ if (!exitCallback) {
1982
+ process2.exit(code2);
1983
+ } else {
1984
+ exitCallback(
1985
+ new CommanderError2(
1986
+ code2,
1987
+ "commander.executeSubCommandAsync",
1988
+ "(close)"
1989
+ )
1990
+ );
1991
+ }
1992
+ });
1993
+ proc.on("error", (err) => {
1994
+ if (err.code === "ENOENT") {
1995
+ 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";
1996
+ const executableMissing = `'${executableFile}' does not exist
1997
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1998
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1999
+ - ${executableDirMessage}`;
2000
+ throw new Error(executableMissing);
2001
+ } else if (err.code === "EACCES") {
2002
+ throw new Error(`'${executableFile}' not executable`);
2003
+ }
2004
+ if (!exitCallback) {
2005
+ process2.exit(1);
2006
+ } else {
2007
+ const wrappedError = new CommanderError2(
2008
+ 1,
2009
+ "commander.executeSubCommandAsync",
2010
+ "(error)"
2011
+ );
2012
+ wrappedError.nestedError = err;
2013
+ exitCallback(wrappedError);
2014
+ }
2015
+ });
2016
+ this.runningCommand = proc;
2017
+ }
2018
+ /**
2019
+ * @private
2020
+ */
2021
+ _dispatchSubcommand(commandName, operands, unknown) {
2022
+ const subCommand = this._findCommand(commandName);
2023
+ if (!subCommand) this.help({ error: true });
2024
+ let promiseChain;
2025
+ promiseChain = this._chainOrCallSubCommandHook(
2026
+ promiseChain,
2027
+ subCommand,
2028
+ "preSubcommand"
2029
+ );
2030
+ promiseChain = this._chainOrCall(promiseChain, () => {
2031
+ if (subCommand._executableHandler) {
2032
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2033
+ } else {
2034
+ return subCommand._parseCommand(operands, unknown);
2035
+ }
2036
+ });
2037
+ return promiseChain;
2038
+ }
2039
+ /**
2040
+ * Invoke help directly if possible, or dispatch if necessary.
2041
+ * e.g. help foo
2042
+ *
2043
+ * @private
2044
+ */
2045
+ _dispatchHelpCommand(subcommandName) {
2046
+ if (!subcommandName) {
2047
+ this.help();
2048
+ }
2049
+ const subCommand = this._findCommand(subcommandName);
2050
+ if (subCommand && !subCommand._executableHandler) {
2051
+ subCommand.help();
2052
+ }
2053
+ return this._dispatchSubcommand(
2054
+ subcommandName,
2055
+ [],
2056
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2057
+ );
2058
+ }
2059
+ /**
2060
+ * Check this.args against expected this.registeredArguments.
2061
+ *
2062
+ * @private
2063
+ */
2064
+ _checkNumberOfArguments() {
2065
+ this.registeredArguments.forEach((arg, i) => {
2066
+ if (arg.required && this.args[i] == null) {
2067
+ this.missingArgument(arg.name());
2068
+ }
2069
+ });
2070
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2071
+ return;
2072
+ }
2073
+ if (this.args.length > this.registeredArguments.length) {
2074
+ this._excessArguments(this.args);
2075
+ }
2076
+ }
2077
+ /**
2078
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2079
+ *
2080
+ * @private
2081
+ */
2082
+ _processArguments() {
2083
+ const myParseArg = (argument, value2, previous) => {
2084
+ let parsedValue = value2;
2085
+ if (value2 !== null && argument.parseArg) {
2086
+ const invalidValueMessage = `error: command-argument value '${value2}' is invalid for argument '${argument.name()}'.`;
2087
+ parsedValue = this._callParseArg(
2088
+ argument,
2089
+ value2,
2090
+ previous,
2091
+ invalidValueMessage
2092
+ );
2093
+ }
2094
+ return parsedValue;
2095
+ };
2096
+ this._checkNumberOfArguments();
2097
+ const processedArgs = [];
2098
+ this.registeredArguments.forEach((declaredArg, index) => {
2099
+ let value2 = declaredArg.defaultValue;
2100
+ if (declaredArg.variadic) {
2101
+ if (index < this.args.length) {
2102
+ value2 = this.args.slice(index);
2103
+ if (declaredArg.parseArg) {
2104
+ value2 = value2.reduce((processed, v) => {
2105
+ return myParseArg(declaredArg, v, processed);
2106
+ }, declaredArg.defaultValue);
2107
+ }
2108
+ } else if (value2 === void 0) {
2109
+ value2 = [];
2110
+ }
2111
+ } else if (index < this.args.length) {
2112
+ value2 = this.args[index];
2113
+ if (declaredArg.parseArg) {
2114
+ value2 = myParseArg(declaredArg, value2, declaredArg.defaultValue);
2115
+ }
2116
+ }
2117
+ processedArgs[index] = value2;
2118
+ });
2119
+ this.processedArgs = processedArgs;
2120
+ }
2121
+ /**
2122
+ * Once we have a promise we chain, but call synchronously until then.
2123
+ *
2124
+ * @param {(Promise|undefined)} promise
2125
+ * @param {Function} fn
2126
+ * @return {(Promise|undefined)}
2127
+ * @private
2128
+ */
2129
+ _chainOrCall(promise, fn) {
2130
+ if (promise && promise.then && typeof promise.then === "function") {
2131
+ return promise.then(() => fn());
2132
+ }
2133
+ return fn();
2134
+ }
2135
+ /**
2136
+ *
2137
+ * @param {(Promise|undefined)} promise
2138
+ * @param {string} event
2139
+ * @return {(Promise|undefined)}
2140
+ * @private
2141
+ */
2142
+ _chainOrCallHooks(promise, event) {
2143
+ let result = promise;
2144
+ const hooks = [];
2145
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2146
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2147
+ hooks.push({ hookedCommand, callback });
2148
+ });
2149
+ });
2150
+ if (event === "postAction") {
2151
+ hooks.reverse();
2152
+ }
2153
+ hooks.forEach((hookDetail) => {
2154
+ result = this._chainOrCall(result, () => {
2155
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2156
+ });
2157
+ });
2158
+ return result;
2159
+ }
2160
+ /**
2161
+ *
2162
+ * @param {(Promise|undefined)} promise
2163
+ * @param {Command} subCommand
2164
+ * @param {string} event
2165
+ * @return {(Promise|undefined)}
2166
+ * @private
2167
+ */
2168
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2169
+ let result = promise;
2170
+ if (this._lifeCycleHooks[event] !== void 0) {
2171
+ this._lifeCycleHooks[event].forEach((hook) => {
2172
+ result = this._chainOrCall(result, () => {
2173
+ return hook(this, subCommand);
2174
+ });
2175
+ });
2176
+ }
2177
+ return result;
2178
+ }
2179
+ /**
2180
+ * Process arguments in context of this command.
2181
+ * Returns action result, in case it is a promise.
2182
+ *
2183
+ * @private
2184
+ */
2185
+ _parseCommand(operands, unknown) {
2186
+ const parsed = this.parseOptions(unknown);
2187
+ this._parseOptionsEnv();
2188
+ this._parseOptionsImplied();
2189
+ operands = operands.concat(parsed.operands);
2190
+ unknown = parsed.unknown;
2191
+ this.args = operands.concat(unknown);
2192
+ if (operands && this._findCommand(operands[0])) {
2193
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2194
+ }
2195
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2196
+ return this._dispatchHelpCommand(operands[1]);
2197
+ }
2198
+ if (this._defaultCommandName) {
2199
+ this._outputHelpIfRequested(unknown);
2200
+ return this._dispatchSubcommand(
2201
+ this._defaultCommandName,
2202
+ operands,
2203
+ unknown
2204
+ );
2205
+ }
2206
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2207
+ this.help({ error: true });
2208
+ }
2209
+ this._outputHelpIfRequested(parsed.unknown);
2210
+ this._checkForMissingMandatoryOptions();
2211
+ this._checkForConflictingOptions();
2212
+ const checkForUnknownOptions = () => {
2213
+ if (parsed.unknown.length > 0) {
2214
+ this.unknownOption(parsed.unknown[0]);
2215
+ }
2216
+ };
2217
+ const commandEvent = `command:${this.name()}`;
2218
+ if (this._actionHandler) {
2219
+ checkForUnknownOptions();
2220
+ this._processArguments();
2221
+ let promiseChain;
2222
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2223
+ promiseChain = this._chainOrCall(
2224
+ promiseChain,
2225
+ () => this._actionHandler(this.processedArgs)
2226
+ );
2227
+ if (this.parent) {
2228
+ promiseChain = this._chainOrCall(promiseChain, () => {
2229
+ this.parent.emit(commandEvent, operands, unknown);
2230
+ });
2231
+ }
2232
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2233
+ return promiseChain;
2234
+ }
2235
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2236
+ checkForUnknownOptions();
2237
+ this._processArguments();
2238
+ this.parent.emit(commandEvent, operands, unknown);
2239
+ } else if (operands.length) {
2240
+ if (this._findCommand("*")) {
2241
+ return this._dispatchSubcommand("*", operands, unknown);
2242
+ }
2243
+ if (this.listenerCount("command:*")) {
2244
+ this.emit("command:*", operands, unknown);
2245
+ } else if (this.commands.length) {
2246
+ this.unknownCommand();
2247
+ } else {
2248
+ checkForUnknownOptions();
2249
+ this._processArguments();
2250
+ }
2251
+ } else if (this.commands.length) {
2252
+ checkForUnknownOptions();
2253
+ this.help({ error: true });
2254
+ } else {
2255
+ checkForUnknownOptions();
2256
+ this._processArguments();
2257
+ }
2258
+ }
2259
+ /**
2260
+ * Find matching command.
2261
+ *
2262
+ * @private
2263
+ * @return {Command | undefined}
2264
+ */
2265
+ _findCommand(name) {
2266
+ if (!name) return void 0;
2267
+ return this.commands.find(
2268
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2269
+ );
2270
+ }
2271
+ /**
2272
+ * Return an option matching `arg` if any.
2273
+ *
2274
+ * @param {string} arg
2275
+ * @return {Option}
2276
+ * @package
2277
+ */
2278
+ _findOption(arg) {
2279
+ return this.options.find((option) => option.is(arg));
2280
+ }
2281
+ /**
2282
+ * Display an error message if a mandatory option does not have a value.
2283
+ * Called after checking for help flags in leaf subcommand.
2284
+ *
2285
+ * @private
2286
+ */
2287
+ _checkForMissingMandatoryOptions() {
2288
+ this._getCommandAndAncestors().forEach((cmd) => {
2289
+ cmd.options.forEach((anOption) => {
2290
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2291
+ cmd.missingMandatoryOptionValue(anOption);
2292
+ }
2293
+ });
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Display an error message if conflicting options are used together in this.
2298
+ *
2299
+ * @private
2300
+ */
2301
+ _checkForConflictingLocalOptions() {
2302
+ const definedNonDefaultOptions = this.options.filter((option) => {
2303
+ const optionKey = option.attributeName();
2304
+ if (this.getOptionValue(optionKey) === void 0) {
2305
+ return false;
2306
+ }
2307
+ return this.getOptionValueSource(optionKey) !== "default";
2308
+ });
2309
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2310
+ (option) => option.conflictsWith.length > 0
2311
+ );
2312
+ optionsWithConflicting.forEach((option) => {
2313
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2314
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2315
+ );
2316
+ if (conflictingAndDefined) {
2317
+ this._conflictingOption(option, conflictingAndDefined);
2318
+ }
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Display an error message if conflicting options are used together.
2323
+ * Called after checking for help flags in leaf subcommand.
2324
+ *
2325
+ * @private
2326
+ */
2327
+ _checkForConflictingOptions() {
2328
+ this._getCommandAndAncestors().forEach((cmd) => {
2329
+ cmd._checkForConflictingLocalOptions();
2330
+ });
2331
+ }
2332
+ /**
2333
+ * Parse options from `argv` removing known options,
2334
+ * and return argv split into operands and unknown arguments.
2335
+ *
2336
+ * Examples:
2337
+ *
2338
+ * argv => operands, unknown
2339
+ * --known kkk op => [op], []
2340
+ * op --known kkk => [op], []
2341
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2342
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2343
+ *
2344
+ * @param {string[]} argv
2345
+ * @return {{operands: string[], unknown: string[]}}
2346
+ */
2347
+ parseOptions(argv) {
2348
+ const operands = [];
2349
+ const unknown = [];
2350
+ let dest = operands;
2351
+ const args = argv.slice();
2352
+ function maybeOption(arg) {
2353
+ return arg.length > 1 && arg[0] === "-";
2354
+ }
2355
+ let activeVariadicOption = null;
2356
+ while (args.length) {
2357
+ const arg = args.shift();
2358
+ if (arg === "--") {
2359
+ if (dest === unknown) dest.push(arg);
2360
+ dest.push(...args);
2361
+ break;
2362
+ }
2363
+ if (activeVariadicOption && !maybeOption(arg)) {
2364
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2365
+ continue;
2366
+ }
2367
+ activeVariadicOption = null;
2368
+ if (maybeOption(arg)) {
2369
+ const option = this._findOption(arg);
2370
+ if (option) {
2371
+ if (option.required) {
2372
+ const value2 = args.shift();
2373
+ if (value2 === void 0) this.optionMissingArgument(option);
2374
+ this.emit(`option:${option.name()}`, value2);
2375
+ } else if (option.optional) {
2376
+ let value2 = null;
2377
+ if (args.length > 0 && !maybeOption(args[0])) {
2378
+ value2 = args.shift();
2379
+ }
2380
+ this.emit(`option:${option.name()}`, value2);
2381
+ } else {
2382
+ this.emit(`option:${option.name()}`);
2383
+ }
2384
+ activeVariadicOption = option.variadic ? option : null;
2385
+ continue;
2386
+ }
2387
+ }
2388
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2389
+ const option = this._findOption(`-${arg[1]}`);
2390
+ if (option) {
2391
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2392
+ this.emit(`option:${option.name()}`, arg.slice(2));
2393
+ } else {
2394
+ this.emit(`option:${option.name()}`);
2395
+ args.unshift(`-${arg.slice(2)}`);
2396
+ }
2397
+ continue;
2398
+ }
2399
+ }
2400
+ if (/^--[^=]+=/.test(arg)) {
2401
+ const index = arg.indexOf("=");
2402
+ const option = this._findOption(arg.slice(0, index));
2403
+ if (option && (option.required || option.optional)) {
2404
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2405
+ continue;
2406
+ }
2407
+ }
2408
+ if (maybeOption(arg)) {
2409
+ dest = unknown;
2410
+ }
2411
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2412
+ if (this._findCommand(arg)) {
2413
+ operands.push(arg);
2414
+ if (args.length > 0) unknown.push(...args);
2415
+ break;
2416
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2417
+ operands.push(arg);
2418
+ if (args.length > 0) operands.push(...args);
2419
+ break;
2420
+ } else if (this._defaultCommandName) {
2421
+ unknown.push(arg);
2422
+ if (args.length > 0) unknown.push(...args);
2423
+ break;
2424
+ }
2425
+ }
2426
+ if (this._passThroughOptions) {
2427
+ dest.push(arg);
2428
+ if (args.length > 0) dest.push(...args);
2429
+ break;
2430
+ }
2431
+ dest.push(arg);
2432
+ }
2433
+ return { operands, unknown };
2434
+ }
2435
+ /**
2436
+ * Return an object containing local option values as key-value pairs.
2437
+ *
2438
+ * @return {object}
2439
+ */
2440
+ opts() {
2441
+ if (this._storeOptionsAsProperties) {
2442
+ const result = {};
2443
+ const len = this.options.length;
2444
+ for (let i = 0; i < len; i++) {
2445
+ const key = this.options[i].attributeName();
2446
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2447
+ }
2448
+ return result;
2449
+ }
2450
+ return this._optionValues;
2451
+ }
2452
+ /**
2453
+ * Return an object containing merged local and global option values as key-value pairs.
2454
+ *
2455
+ * @return {object}
2456
+ */
2457
+ optsWithGlobals() {
2458
+ return this._getCommandAndAncestors().reduce(
2459
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2460
+ {}
2461
+ );
2462
+ }
2463
+ /**
2464
+ * Display error message and exit (or call exitOverride).
2465
+ *
2466
+ * @param {string} message
2467
+ * @param {object} [errorOptions]
2468
+ * @param {string} [errorOptions.code] - an id string representing the error
2469
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2470
+ */
2471
+ error(message, errorOptions) {
2472
+ this._outputConfiguration.outputError(
2473
+ `${message}
2474
+ `,
2475
+ this._outputConfiguration.writeErr
2476
+ );
2477
+ if (typeof this._showHelpAfterError === "string") {
2478
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2479
+ `);
2480
+ } else if (this._showHelpAfterError) {
2481
+ this._outputConfiguration.writeErr("\n");
2482
+ this.outputHelp({ error: true });
2483
+ }
2484
+ const config = errorOptions || {};
2485
+ const exitCode = config.exitCode || 1;
2486
+ const code2 = config.code || "commander.error";
2487
+ this._exit(exitCode, code2, message);
2488
+ }
2489
+ /**
2490
+ * Apply any option related environment variables, if option does
2491
+ * not have a value from cli or client code.
2492
+ *
2493
+ * @private
2494
+ */
2495
+ _parseOptionsEnv() {
2496
+ this.options.forEach((option) => {
2497
+ if (option.envVar && option.envVar in process2.env) {
2498
+ const optionKey = option.attributeName();
2499
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2500
+ this.getOptionValueSource(optionKey)
2501
+ )) {
2502
+ if (option.required || option.optional) {
2503
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2504
+ } else {
2505
+ this.emit(`optionEnv:${option.name()}`);
2506
+ }
2507
+ }
2508
+ }
2509
+ });
2510
+ }
2511
+ /**
2512
+ * Apply any implied option values, if option is undefined or default value.
2513
+ *
2514
+ * @private
2515
+ */
2516
+ _parseOptionsImplied() {
2517
+ const dualHelper = new DualOptions(this.options);
2518
+ const hasCustomOptionValue = (optionKey) => {
2519
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2520
+ };
2521
+ this.options.filter(
2522
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2523
+ this.getOptionValue(option.attributeName()),
2524
+ option
2525
+ )
2526
+ ).forEach((option) => {
2527
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2528
+ this.setOptionValueWithSource(
2529
+ impliedKey,
2530
+ option.implied[impliedKey],
2531
+ "implied"
2532
+ );
2533
+ });
2534
+ });
2535
+ }
2536
+ /**
2537
+ * Argument `name` is missing.
2538
+ *
2539
+ * @param {string} name
2540
+ * @private
2541
+ */
2542
+ missingArgument(name) {
2543
+ const message = `error: missing required argument '${name}'`;
2544
+ this.error(message, { code: "commander.missingArgument" });
2545
+ }
2546
+ /**
2547
+ * `Option` is missing an argument.
2548
+ *
2549
+ * @param {Option} option
2550
+ * @private
2551
+ */
2552
+ optionMissingArgument(option) {
2553
+ const message = `error: option '${option.flags}' argument missing`;
2554
+ this.error(message, { code: "commander.optionMissingArgument" });
2555
+ }
2556
+ /**
2557
+ * `Option` does not have a value, and is a mandatory option.
2558
+ *
2559
+ * @param {Option} option
2560
+ * @private
2561
+ */
2562
+ missingMandatoryOptionValue(option) {
2563
+ const message = `error: required option '${option.flags}' not specified`;
2564
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2565
+ }
2566
+ /**
2567
+ * `Option` conflicts with another option.
2568
+ *
2569
+ * @param {Option} option
2570
+ * @param {Option} conflictingOption
2571
+ * @private
2572
+ */
2573
+ _conflictingOption(option, conflictingOption) {
2574
+ const findBestOptionFromValue = (option2) => {
2575
+ const optionKey = option2.attributeName();
2576
+ const optionValue = this.getOptionValue(optionKey);
2577
+ const negativeOption = this.options.find(
2578
+ (target) => target.negate && optionKey === target.attributeName()
2579
+ );
2580
+ const positiveOption = this.options.find(
2581
+ (target) => !target.negate && optionKey === target.attributeName()
2582
+ );
2583
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2584
+ return negativeOption;
2585
+ }
2586
+ return positiveOption || option2;
2587
+ };
2588
+ const getErrorMessage = (option2) => {
2589
+ const bestOption = findBestOptionFromValue(option2);
2590
+ const optionKey = bestOption.attributeName();
2591
+ const source = this.getOptionValueSource(optionKey);
2592
+ if (source === "env") {
2593
+ return `environment variable '${bestOption.envVar}'`;
2594
+ }
2595
+ return `option '${bestOption.flags}'`;
2596
+ };
2597
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2598
+ this.error(message, { code: "commander.conflictingOption" });
2599
+ }
2600
+ /**
2601
+ * Unknown option `flag`.
2602
+ *
2603
+ * @param {string} flag
2604
+ * @private
2605
+ */
2606
+ unknownOption(flag) {
2607
+ if (this._allowUnknownOption) return;
2608
+ let suggestion = "";
2609
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2610
+ let candidateFlags = [];
2611
+ let command = this;
2612
+ do {
2613
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2614
+ candidateFlags = candidateFlags.concat(moreFlags);
2615
+ command = command.parent;
2616
+ } while (command && !command._enablePositionalOptions);
2617
+ suggestion = suggestSimilar(flag, candidateFlags);
2618
+ }
2619
+ const message = `error: unknown option '${flag}'${suggestion}`;
2620
+ this.error(message, { code: "commander.unknownOption" });
2621
+ }
2622
+ /**
2623
+ * Excess arguments, more than expected.
2624
+ *
2625
+ * @param {string[]} receivedArgs
2626
+ * @private
2627
+ */
2628
+ _excessArguments(receivedArgs) {
2629
+ if (this._allowExcessArguments) return;
2630
+ const expected = this.registeredArguments.length;
2631
+ const s = expected === 1 ? "" : "s";
2632
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2633
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2634
+ this.error(message, { code: "commander.excessArguments" });
2635
+ }
2636
+ /**
2637
+ * Unknown command.
2638
+ *
2639
+ * @private
2640
+ */
2641
+ unknownCommand() {
2642
+ const unknownName = this.args[0];
2643
+ let suggestion = "";
2644
+ if (this._showSuggestionAfterError) {
2645
+ const candidateNames = [];
2646
+ this.createHelp().visibleCommands(this).forEach((command) => {
2647
+ candidateNames.push(command.name());
2648
+ if (command.alias()) candidateNames.push(command.alias());
2649
+ });
2650
+ suggestion = suggestSimilar(unknownName, candidateNames);
2651
+ }
2652
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2653
+ this.error(message, { code: "commander.unknownCommand" });
2654
+ }
2655
+ /**
2656
+ * Get or set the program version.
2657
+ *
2658
+ * This method auto-registers the "-V, --version" option which will print the version number.
2659
+ *
2660
+ * You can optionally supply the flags and description to override the defaults.
2661
+ *
2662
+ * @param {string} [str]
2663
+ * @param {string} [flags]
2664
+ * @param {string} [description]
2665
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2666
+ */
2667
+ version(str, flags, description) {
2668
+ if (str === void 0) return this._version;
2669
+ this._version = str;
2670
+ flags = flags || "-V, --version";
2671
+ description = description || "output the version number";
2672
+ const versionOption = this.createOption(flags, description);
2673
+ this._versionOptionName = versionOption.attributeName();
2674
+ this._registerOption(versionOption);
2675
+ this.on("option:" + versionOption.name(), () => {
2676
+ this._outputConfiguration.writeOut(`${str}
2677
+ `);
2678
+ this._exit(0, "commander.version", str);
2679
+ });
2680
+ return this;
2681
+ }
2682
+ /**
2683
+ * Set the description.
2684
+ *
2685
+ * @param {string} [str]
2686
+ * @param {object} [argsDescription]
2687
+ * @return {(string|Command)}
2688
+ */
2689
+ description(str, argsDescription) {
2690
+ if (str === void 0 && argsDescription === void 0)
2691
+ return this._description;
2692
+ this._description = str;
2693
+ if (argsDescription) {
2694
+ this._argsDescription = argsDescription;
2695
+ }
2696
+ return this;
2697
+ }
2698
+ /**
2699
+ * Set the summary. Used when listed as subcommand of parent.
2700
+ *
2701
+ * @param {string} [str]
2702
+ * @return {(string|Command)}
2703
+ */
2704
+ summary(str) {
2705
+ if (str === void 0) return this._summary;
2706
+ this._summary = str;
2707
+ return this;
2708
+ }
2709
+ /**
2710
+ * Set an alias for the command.
2711
+ *
2712
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2713
+ *
2714
+ * @param {string} [alias]
2715
+ * @return {(string|Command)}
2716
+ */
2717
+ alias(alias) {
2718
+ if (alias === void 0) return this._aliases[0];
2719
+ let command = this;
2720
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2721
+ command = this.commands[this.commands.length - 1];
2722
+ }
2723
+ if (alias === command._name)
2724
+ throw new Error("Command alias can't be the same as its name");
2725
+ const matchingCommand = this.parent?._findCommand(alias);
2726
+ if (matchingCommand) {
2727
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2728
+ throw new Error(
2729
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2730
+ );
2731
+ }
2732
+ command._aliases.push(alias);
2733
+ return this;
2734
+ }
2735
+ /**
2736
+ * Set aliases for the command.
2737
+ *
2738
+ * Only the first alias is shown in the auto-generated help.
2739
+ *
2740
+ * @param {string[]} [aliases]
2741
+ * @return {(string[]|Command)}
2742
+ */
2743
+ aliases(aliases) {
2744
+ if (aliases === void 0) return this._aliases;
2745
+ aliases.forEach((alias) => this.alias(alias));
2746
+ return this;
2747
+ }
2748
+ /**
2749
+ * Set / get the command usage `str`.
2750
+ *
2751
+ * @param {string} [str]
2752
+ * @return {(string|Command)}
2753
+ */
2754
+ usage(str) {
2755
+ if (str === void 0) {
2756
+ if (this._usage) return this._usage;
2757
+ const args = this.registeredArguments.map((arg) => {
2758
+ return humanReadableArgName(arg);
2759
+ });
2760
+ return [].concat(
2761
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2762
+ this.commands.length ? "[command]" : [],
2763
+ this.registeredArguments.length ? args : []
2764
+ ).join(" ");
2765
+ }
2766
+ this._usage = str;
2767
+ return this;
2768
+ }
2769
+ /**
2770
+ * Get or set the name of the command.
2771
+ *
2772
+ * @param {string} [str]
2773
+ * @return {(string|Command)}
2774
+ */
2775
+ name(str) {
2776
+ if (str === void 0) return this._name;
2777
+ this._name = str;
2778
+ return this;
2779
+ }
2780
+ /**
2781
+ * Set the name of the command from script filename, such as process.argv[1],
2782
+ * or require.main.filename, or __filename.
2783
+ *
2784
+ * (Used internally and public although not documented in README.)
2785
+ *
2786
+ * @example
2787
+ * program.nameFromFilename(require.main.filename);
2788
+ *
2789
+ * @param {string} filename
2790
+ * @return {Command}
2791
+ */
2792
+ nameFromFilename(filename) {
2793
+ this._name = path.basename(filename, path.extname(filename));
2794
+ return this;
2795
+ }
2796
+ /**
2797
+ * Get or set the directory for searching for executable subcommands of this command.
2798
+ *
2799
+ * @example
2800
+ * program.executableDir(__dirname);
2801
+ * // or
2802
+ * program.executableDir('subcommands');
2803
+ *
2804
+ * @param {string} [path]
2805
+ * @return {(string|null|Command)}
2806
+ */
2807
+ executableDir(path2) {
2808
+ if (path2 === void 0) return this._executableDir;
2809
+ this._executableDir = path2;
2810
+ return this;
2811
+ }
2812
+ /**
2813
+ * Return program help documentation.
2814
+ *
2815
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2816
+ * @return {string}
2817
+ */
2818
+ helpInformation(contextOptions) {
2819
+ const helper = this.createHelp();
2820
+ if (helper.helpWidth === void 0) {
2821
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2822
+ }
2823
+ return helper.formatHelp(this, helper);
2824
+ }
2825
+ /**
2826
+ * @private
2827
+ */
2828
+ _getHelpContext(contextOptions) {
2829
+ contextOptions = contextOptions || {};
2830
+ const context = { error: !!contextOptions.error };
2831
+ let write;
2832
+ if (context.error) {
2833
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2834
+ } else {
2835
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2836
+ }
2837
+ context.write = contextOptions.write || write;
2838
+ context.command = this;
2839
+ return context;
2840
+ }
2841
+ /**
2842
+ * Output help information for this command.
2843
+ *
2844
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2845
+ *
2846
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2847
+ */
2848
+ outputHelp(contextOptions) {
2849
+ let deprecatedCallback;
2850
+ if (typeof contextOptions === "function") {
2851
+ deprecatedCallback = contextOptions;
2852
+ contextOptions = void 0;
2853
+ }
2854
+ const context = this._getHelpContext(contextOptions);
2855
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2856
+ this.emit("beforeHelp", context);
2857
+ let helpInformation = this.helpInformation(context);
2858
+ if (deprecatedCallback) {
2859
+ helpInformation = deprecatedCallback(helpInformation);
2860
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2861
+ throw new Error("outputHelp callback must return a string or a Buffer");
2862
+ }
2863
+ }
2864
+ context.write(helpInformation);
2865
+ if (this._getHelpOption()?.long) {
2866
+ this.emit(this._getHelpOption().long);
2867
+ }
2868
+ this.emit("afterHelp", context);
2869
+ this._getCommandAndAncestors().forEach(
2870
+ (command) => command.emit("afterAllHelp", context)
2871
+ );
2872
+ }
2873
+ /**
2874
+ * You can pass in flags and a description to customise the built-in help option.
2875
+ * Pass in false to disable the built-in help option.
2876
+ *
2877
+ * @example
2878
+ * program.helpOption('-?, --help' 'show help'); // customise
2879
+ * program.helpOption(false); // disable
2880
+ *
2881
+ * @param {(string | boolean)} flags
2882
+ * @param {string} [description]
2883
+ * @return {Command} `this` command for chaining
2884
+ */
2885
+ helpOption(flags, description) {
2886
+ if (typeof flags === "boolean") {
2887
+ if (flags) {
2888
+ this._helpOption = this._helpOption ?? void 0;
2889
+ } else {
2890
+ this._helpOption = null;
2891
+ }
2892
+ return this;
2893
+ }
2894
+ flags = flags ?? "-h, --help";
2895
+ description = description ?? "display help for command";
2896
+ this._helpOption = this.createOption(flags, description);
2897
+ return this;
2898
+ }
2899
+ /**
2900
+ * Lazy create help option.
2901
+ * Returns null if has been disabled with .helpOption(false).
2902
+ *
2903
+ * @returns {(Option | null)} the help option
2904
+ * @package
2905
+ */
2906
+ _getHelpOption() {
2907
+ if (this._helpOption === void 0) {
2908
+ this.helpOption(void 0, void 0);
2909
+ }
2910
+ return this._helpOption;
2911
+ }
2912
+ /**
2913
+ * Supply your own option to use for the built-in help option.
2914
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2915
+ *
2916
+ * @param {Option} option
2917
+ * @return {Command} `this` command for chaining
2918
+ */
2919
+ addHelpOption(option) {
2920
+ this._helpOption = option;
2921
+ return this;
2922
+ }
2923
+ /**
2924
+ * Output help information and exit.
2925
+ *
2926
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2927
+ *
2928
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2929
+ */
2930
+ help(contextOptions) {
2931
+ this.outputHelp(contextOptions);
2932
+ let exitCode = process2.exitCode || 0;
2933
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2934
+ exitCode = 1;
2935
+ }
2936
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2937
+ }
2938
+ /**
2939
+ * Add additional text to be displayed with the built-in help.
2940
+ *
2941
+ * Position is 'before' or 'after' to affect just this command,
2942
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2943
+ *
2944
+ * @param {string} position - before or after built-in help
2945
+ * @param {(string | Function)} text - string to add, or a function returning a string
2946
+ * @return {Command} `this` command for chaining
2947
+ */
2948
+ addHelpText(position, text) {
2949
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2950
+ if (!allowedValues.includes(position)) {
2951
+ throw new Error(`Unexpected value for position to addHelpText.
2952
+ Expecting one of '${allowedValues.join("', '")}'`);
2953
+ }
2954
+ const helpEvent = `${position}Help`;
2955
+ this.on(helpEvent, (context) => {
2956
+ let helpStr;
2957
+ if (typeof text === "function") {
2958
+ helpStr = text({ error: context.error, command: context.command });
2959
+ } else {
2960
+ helpStr = text;
2961
+ }
2962
+ if (helpStr) {
2963
+ context.write(`${helpStr}
2964
+ `);
2965
+ }
2966
+ });
2967
+ return this;
2968
+ }
2969
+ /**
2970
+ * Output help information if help flags specified
2971
+ *
2972
+ * @param {Array} args - array of options to search for help flags
2973
+ * @private
2974
+ */
2975
+ _outputHelpIfRequested(args) {
2976
+ const helpOption = this._getHelpOption();
2977
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2978
+ if (helpRequested) {
2979
+ this.outputHelp();
2980
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2981
+ }
2982
+ }
2983
+ };
2984
+ function incrementNodeInspectorPort(args) {
2985
+ return args.map((arg) => {
2986
+ if (!arg.startsWith("--inspect")) {
2987
+ return arg;
2988
+ }
2989
+ let debugOption;
2990
+ let debugHost = "127.0.0.1";
2991
+ let debugPort = "9229";
2992
+ let match;
2993
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2994
+ debugOption = match[1];
2995
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2996
+ debugOption = match[1];
2997
+ if (/^\d+$/.test(match[3])) {
2998
+ debugPort = match[3];
2999
+ } else {
3000
+ debugHost = match[3];
3001
+ }
3002
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3003
+ debugOption = match[1];
3004
+ debugHost = match[3];
3005
+ debugPort = match[4];
3006
+ }
3007
+ if (debugOption && debugPort !== "0") {
3008
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3009
+ }
3010
+ return arg;
3011
+ });
3012
+ }
3013
+ exports.Command = Command2;
3014
+ }
3015
+ });
3016
+
3017
+ // node_modules/commander/index.js
3018
+ var require_commander = __commonJS({
3019
+ "node_modules/commander/index.js"(exports) {
3020
+ "use strict";
3021
+ var { Argument: Argument2 } = require_argument();
3022
+ var { Command: Command2 } = require_command();
3023
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3024
+ var { Help: Help2 } = require_help();
3025
+ var { Option: Option2 } = require_option();
3026
+ exports.program = new Command2();
3027
+ exports.createCommand = (name) => new Command2(name);
3028
+ exports.createOption = (flags, description) => new Option2(flags, description);
3029
+ exports.createArgument = (name, description) => new Argument2(name, description);
3030
+ exports.Command = Command2;
3031
+ exports.Option = Option2;
3032
+ exports.Argument = Argument2;
3033
+ exports.Help = Help2;
3034
+ exports.CommanderError = CommanderError2;
3035
+ exports.InvalidArgumentError = InvalidArgumentError2;
3036
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3037
+ }
3038
+ });
3039
+
3040
+ // src/cli.ts
3041
+ import { resolve } from "path";
3042
+
3043
+ // node_modules/commander/esm.mjs
3044
+ var import_index = __toESM(require_commander(), 1);
3045
+ var {
3046
+ program,
3047
+ createCommand,
3048
+ createArgument,
3049
+ createOption,
3050
+ CommanderError,
3051
+ InvalidArgumentError,
3052
+ InvalidOptionArgumentError,
3053
+ // deprecated old name
3054
+ Command,
3055
+ Argument,
3056
+ Option,
3057
+ Help
3058
+ } = import_index.default;
3059
+
3060
+ // src/lib/env.ts
3061
+ import { existsSync, readFileSync } from "fs";
3062
+ var QUOTED = /^(["'])((?:\\.|(?!\1).)*)\1\s*(?:#.*)?$/;
3063
+ function parseDotenv(content) {
3064
+ const result = {};
3065
+ for (const raw of content.split(/\r?\n/)) {
3066
+ const line = raw.trim();
3067
+ if (!line || line.startsWith("#")) continue;
3068
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
3069
+ if (!m) continue;
3070
+ const key = m[1];
3071
+ const rest = m[2];
3072
+ const q = QUOTED.exec(rest);
3073
+ if (q) {
3074
+ const body = q[2];
3075
+ result[key] = q[1] === '"' ? body.replace(/\\(.)/g, (_, c) => c === "n" ? "\n" : c) : body;
3076
+ } else {
3077
+ result[key] = rest.replace(/\s+#.*$/, "");
3078
+ }
3079
+ }
3080
+ return result;
3081
+ }
3082
+ function loadEnvFile(path, env, groups = []) {
3083
+ if (!existsSync(path)) return false;
3084
+ const fileVars = parseDotenv(readFileSync(path, "utf8"));
3085
+ const blocked = new Set(groups.filter((g) => g.some((name) => env[name]?.trim())).flat());
3086
+ for (const [k, v] of Object.entries(fileVars)) {
3087
+ if (env[k] === void 0 && !blocked.has(k)) env[k] = v;
3088
+ }
3089
+ return true;
3090
+ }
3091
+ var ENV_FAMILIES = {
3092
+ aliyun: [
3093
+ { id: "ALIBABA_CLOUD_ACCESS_KEY_ID", secret: "ALIBABA_CLOUD_ACCESS_KEY_SECRET", token: "ALIBABA_CLOUD_SECURITY_TOKEN" },
3094
+ { id: "ALIYUN_ACCESS_KEY_ID", secret: "ALIYUN_ACCESS_KEY_SECRET", token: "ALIYUN_SECURITY_TOKEN" }
3095
+ ],
3096
+ tencent: [{ id: "TENCENTCLOUD_SECRET_ID", secret: "TENCENTCLOUD_SECRET_KEY", token: "TENCENTCLOUD_SESSION_TOKEN" }]
3097
+ };
3098
+ function familyNames(families) {
3099
+ return families.flatMap((f) => [f.id, f.secret, f.token]);
3100
+ }
3101
+ var value = (env, name) => env[name]?.trim() || void 0;
3102
+ function resolveFamily(env, families) {
3103
+ const family = families.find((f) => value(env, f.id) || value(env, f.secret));
3104
+ if (!family) return { state: "missing" };
3105
+ const id = value(env, family.id);
3106
+ const secret = value(env, family.secret);
3107
+ if (!id || !secret) return { state: "incomplete", family, missing: [!id ? family.id : family.secret] };
3108
+ const token = value(env, family.token);
3109
+ return { state: "ok", family, id, secret, ...token && { token } };
3110
+ }
3111
+ function readAliyun(env) {
3112
+ const r = resolveFamily(env, ENV_FAMILIES.aliyun);
3113
+ if (r.state !== "ok") return r;
3114
+ return { state: "ok", credentials: { accessKeyId: r.id, accessKeySecret: r.secret, ...r.token && { securityToken: r.token } } };
3115
+ }
3116
+ function readTencent(env) {
3117
+ const r = resolveFamily(env, ENV_FAMILIES.tencent);
3118
+ if (r.state !== "ok") return r;
3119
+ return { state: "ok", credentials: { secretId: r.id, secretKey: r.secret, ...r.token && { sessionToken: r.token } } };
3120
+ }
3121
+ function mask(value2) {
3122
+ if (value2.length <= 8) return "*".repeat(value2.length);
3123
+ return `${value2.slice(0, 4)}${"*".repeat(Math.min(value2.length - 8, 8))}${value2.slice(-4)}`;
3124
+ }
3125
+
3126
+ // src/lib/table.ts
3127
+ function charWidth(cp) {
3128
+ if (cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510) {
3129
+ return 2;
3130
+ }
3131
+ return 1;
3132
+ }
3133
+ function displayWidth(s) {
3134
+ let w = 0;
3135
+ for (const ch of s) w += charWidth(ch.codePointAt(0));
3136
+ return w;
3137
+ }
3138
+ function renderTable(headers, rows) {
3139
+ const widths = headers.map((h, i) => Math.max(displayWidth(h), ...rows.map((r) => displayWidth(r[i] ?? ""))));
3140
+ const line = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c + " ".repeat(widths[i] - displayWidth(c))).join(" ").trimEnd();
3141
+ return [line(headers), ...rows.map(line)].join("\n");
3142
+ }
3143
+
3144
+ // src/lib/time.ts
3145
+ var DAY_MS = 864e5;
3146
+ var LOCAL_DATETIME = /^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/;
3147
+ function toIso(value2) {
3148
+ if (value2 === void 0 || value2 === null || value2 === "") return void 0;
3149
+ let ms;
3150
+ if (typeof value2 === "number") {
3151
+ ms = value2 < 1e12 ? value2 * 1e3 : value2;
3152
+ } else if (typeof value2 === "string") {
3153
+ const s = value2.trim();
3154
+ const m = LOCAL_DATETIME.exec(s);
3155
+ if (/^\d{10,13}$/.test(s)) {
3156
+ return toIso(Number(s));
3157
+ } else if (m) {
3158
+ const [y, mo, d, h, mi, sec] = m.slice(1).map((x) => (x ?? "0").padStart(2, "0"));
3159
+ ms = Date.parse(`${y}-${mo}-${d}T${h}:${mi}:${sec}+08:00`);
3160
+ } else {
3161
+ ms = Date.parse(s);
3162
+ }
3163
+ } else {
3164
+ return void 0;
3165
+ }
3166
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : void 0;
3167
+ }
3168
+ function daysUntil(iso, now) {
3169
+ if (!iso) return void 0;
3170
+ const ms = Date.parse(iso);
3171
+ return Number.isFinite(ms) ? Math.floor((ms - now.getTime()) / DAY_MS) : void 0;
3172
+ }
3173
+ function formatDate(iso) {
3174
+ if (!iso) return "-";
3175
+ const d = new Date(iso);
3176
+ const pad = (n) => String(n).padStart(2, "0");
3177
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
3178
+ }
3179
+
3180
+ // src/providers/registry.ts
3181
+ function defineProvider(def) {
3182
+ return def;
3183
+ }
3184
+ function requiredEnvNames(def) {
3185
+ const f = def.envFamilies[0];
3186
+ return [f.id, f.secret];
3187
+ }
3188
+ function envKeyStatus(def, env, mask2) {
3189
+ const r = resolveFamily(env, def.envFamilies);
3190
+ const f = r.state === "missing" ? def.envFamilies[0] : r.family;
3191
+ const get = (name) => env[name]?.trim() || void 0;
3192
+ const id = get(f.id);
3193
+ return [
3194
+ { name: f.id, required: true, set: !!id, ...id && { masked: mask2(id) } },
3195
+ { name: f.secret, required: true, set: !!get(f.secret) },
3196
+ { name: f.token, required: false, set: !!get(f.token) }
3197
+ ];
3198
+ }
3199
+
3200
+ // src/lib/http.ts
3201
+ var CloudApiError = class extends Error {
3202
+ constructor(provider, code2, message, requestId, httpStatus) {
3203
+ super(message);
3204
+ this.provider = provider;
3205
+ this.code = code2;
3206
+ this.requestId = requestId;
3207
+ this.httpStatus = httpStatus;
3208
+ this.name = "CloudApiError";
3209
+ }
3210
+ provider;
3211
+ code;
3212
+ requestId;
3213
+ httpStatus;
3214
+ };
3215
+ var RETRYABLE = /Throttl|RequestLimitExceeded|ServiceUnavailable|^Timeout$|^NetworkError$/;
3216
+ var MAX_ATTEMPTS = 3;
3217
+ async function withRetry(ctx, fn) {
3218
+ const sleep = ctx.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3219
+ for (let attempt = 1; ; attempt++) {
3220
+ try {
3221
+ return await fn();
3222
+ } catch (e) {
3223
+ if (!(e instanceof CloudApiError) || !RETRYABLE.test(e.code) || attempt >= MAX_ATTEMPTS) throw e;
3224
+ await sleep(500 * 2 ** (attempt - 1));
3225
+ }
3226
+ }
3227
+ }
3228
+ async function send(ctx, provider, url, init) {
3229
+ try {
3230
+ const res = await ctx.fetch(url, { ...init, signal: AbortSignal.timeout(ctx.timeoutMs) });
3231
+ return { status: res.status, text: await res.text() };
3232
+ } catch (e) {
3233
+ const err = e;
3234
+ if (err.name === "TimeoutError" || err.name === "AbortError") {
3235
+ throw new CloudApiError(provider, "Timeout", `\u8BF7\u6C42\u8D85\u65F6\uFF08${ctx.timeoutMs}ms\uFF09\uFF1A${new URL(url).host}`);
3236
+ }
3237
+ const cause = err.cause?.code;
3238
+ throw new CloudApiError(provider, "NetworkError", `\u7F51\u7EDC\u9519\u8BEF\uFF1A${new URL(url).host} ${cause ?? err.message}`);
3239
+ }
3240
+ }
3241
+ function parseJson(provider, raw) {
3242
+ try {
3243
+ return JSON.parse(raw.text);
3244
+ } catch {
3245
+ throw new CloudApiError(provider, "InvalidResponse", `\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08HTTP ${raw.status}\uFF09\uFF1A${raw.text.slice(0, 200)}`, void 0, raw.status);
3246
+ }
3247
+ }
3248
+
3249
+ // src/lib/compact.ts
3250
+ function compact(o) {
3251
+ const out = {};
3252
+ for (const [k, v] of Object.entries(o)) {
3253
+ if (v === void 0 || v === null || v === "") continue;
3254
+ if (typeof v === "object" && Object.keys(v).length === 0) continue;
3255
+ out[k] = v;
3256
+ }
3257
+ return out;
3258
+ }
3259
+
3260
+ // src/lib/paginate.ts
3261
+ var MAX_PAGES = 1e3;
3262
+ async function paginate(pageSize, fetchPage) {
3263
+ const all = [];
3264
+ for (let page = 1; page <= MAX_PAGES; page++) {
3265
+ const { items, total } = await fetchPage(page, all.length);
3266
+ all.push(...items);
3267
+ const done = total !== void 0 ? all.length >= total || items.length === 0 : items.length < pageSize;
3268
+ if (done) return all;
3269
+ }
3270
+ throw new Error(`\u5206\u9875\u8D85\u8FC7 ${MAX_PAGES} \u9875\u4ECD\u672A\u53D6\u5B8C\uFF0C\u5DF2\u4E2D\u6B62\uFF08\u63A5\u53E3\u8FD4\u56DE\u53EF\u80FD\u5F02\u5E38\uFF09`);
3271
+ }
3272
+ function memo() {
3273
+ const cache = /* @__PURE__ */ new WeakMap();
3274
+ return (owner, key, load) => {
3275
+ let m = cache.get(owner);
3276
+ if (!m) cache.set(owner, m = /* @__PURE__ */ new Map());
3277
+ let p = m.get(key);
3278
+ if (!p) m.set(key, p = load());
3279
+ return p;
3280
+ };
3281
+ }
3282
+
3283
+ // src/providers/aliyun/client.ts
3284
+ import { randomUUID } from "crypto";
3285
+
3286
+ // src/providers/aliyun/sign.ts
3287
+ import { createHash, createHmac } from "crypto";
3288
+ function percentEncode(s) {
3289
+ return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
3290
+ }
3291
+ function canonicalQuery(params) {
3292
+ return Object.keys(params).sort().map((k) => `${percentEncode(k)}=${percentEncode(params[k])}`).join("&");
3293
+ }
3294
+ function rpcSignature(params, accessKeySecret, method = "GET") {
3295
+ const stringToSign = `${method}&${percentEncode("/")}&${percentEncode(canonicalQuery(params))}`;
3296
+ return createHmac("sha1", `${accessKeySecret}&`).update(stringToSign).digest("base64");
3297
+ }
3298
+ var sha256Hex = (s) => createHash("sha256").update(s).digest("hex");
3299
+ var hmac256 = (key, s) => createHmac("sha256", key).update(s).digest();
3300
+ function ossDate(d) {
3301
+ return d.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
3302
+ }
3303
+ function ossV4Authorization(input) {
3304
+ const headers = Object.fromEntries(Object.entries(input.headers).map(([k, v]) => [k.toLowerCase(), v.trim()]));
3305
+ const datetime = headers["x-oss-date"];
3306
+ if (!datetime) throw new Error("x-oss-date header is required");
3307
+ const day = datetime.slice(0, 8);
3308
+ const canonicalUri = input.bucket ? `/${percentEncode(input.bucket)}/` : "/";
3309
+ const canonicalQs = Object.keys(input.query).sort().map((k) => input.query[k] ? `${percentEncode(k)}=${percentEncode(input.query[k])}` : percentEncode(k)).join("&");
3310
+ const canonicalHeaders = Object.keys(headers).filter((k) => k.startsWith("x-oss-") || k === "content-type" || k === "content-md5").sort().map((k) => `${k}:${headers[k]}
3311
+ `).join("");
3312
+ const canonicalRequest = [
3313
+ input.method,
3314
+ canonicalUri,
3315
+ canonicalQs,
3316
+ canonicalHeaders,
3317
+ "",
3318
+ headers["x-oss-content-sha256"] ?? "UNSIGNED-PAYLOAD"
3319
+ ].join("\n");
3320
+ const scope = `${day}/${input.region}/oss/aliyun_v4_request`;
3321
+ const stringToSign = ["OSS4-HMAC-SHA256", datetime, scope, sha256Hex(canonicalRequest)].join("\n");
3322
+ let key = hmac256(`aliyun_v4${input.accessKeySecret}`, day);
3323
+ key = hmac256(key, input.region);
3324
+ key = hmac256(key, "oss");
3325
+ key = hmac256(key, "aliyun_v4_request");
3326
+ const signature = createHmac("sha256", key).update(stringToSign).digest("hex");
3327
+ return `OSS4-HMAC-SHA256 Credential=${input.accessKeyId}/${scope},Signature=${signature}`;
3328
+ }
3329
+
3330
+ // src/providers/aliyun/client.ts
3331
+ async function callRpc(ctx, creds, req) {
3332
+ return withRetry(ctx, async () => {
3333
+ const params = {
3334
+ Format: "JSON",
3335
+ Version: req.version,
3336
+ Action: req.action,
3337
+ AccessKeyId: creds.accessKeyId,
3338
+ SignatureMethod: "HMAC-SHA1",
3339
+ SignatureVersion: "1.0",
3340
+ SignatureNonce: randomUUID(),
3341
+ Timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z")
3342
+ };
3343
+ if (creds.securityToken) params.SecurityToken = creds.securityToken;
3344
+ for (const [k, v] of Object.entries(req.params ?? {})) {
3345
+ if (v !== void 0 && v !== "") params[k] = String(v);
3346
+ }
3347
+ params.Signature = rpcSignature(params, creds.accessKeySecret);
3348
+ const raw = await send(ctx, "aliyun", `https://${req.endpoint}/?${canonicalQuery(params)}`, { method: "GET" });
3349
+ const body = parseJson("aliyun", raw);
3350
+ if (raw.status >= 400) {
3351
+ throw new CloudApiError(
3352
+ "aliyun",
3353
+ body.Code ?? `HTTP${raw.status}`,
3354
+ body.Message ?? `HTTP ${raw.status}`,
3355
+ body.RequestId,
3356
+ raw.status
3357
+ );
3358
+ }
3359
+ return body;
3360
+ });
3361
+ }
3362
+
3363
+ // src/providers/aliyun/cas.ts
3364
+ var PAGE = 50;
3365
+ var endOfDay = (date) => date && /^\d{4}-\d{2}-\d{2}$/.test(date) ? `${date} 23:59:59` : date;
3366
+ function listOrders(ctx, creds, status) {
3367
+ return paginate(PAGE, async (page) => {
3368
+ const res = await callRpc(ctx, creds, {
3369
+ endpoint: "cas.aliyuncs.com",
3370
+ version: "2020-04-07",
3371
+ action: "ListUserCertificateOrder",
3372
+ params: { OrderType: "CERT", Status: status, CurrentPage: page, ShowSize: PAGE }
3373
+ });
3374
+ return { items: res.CertificateOrderList ?? [], total: res.TotalCount };
3375
+ });
3376
+ }
3377
+ async function listCasCertificates(ctx, creds) {
3378
+ const [valid, expired] = await Promise.all([listOrders(ctx, creds), listOrders(ctx, creds, "EXPIRED")]);
3379
+ const seen = /* @__PURE__ */ new Set();
3380
+ const out = [];
3381
+ for (const c of [...valid, ...expired]) {
3382
+ const id = String(c.CertificateId);
3383
+ if (seen.has(id)) continue;
3384
+ seen.add(id);
3385
+ out.push(
3386
+ compact({
3387
+ provider: "aliyun",
3388
+ id,
3389
+ name: c.Name,
3390
+ commonName: c.CommonName,
3391
+ sans: c.Sans?.split(",").map((s) => s.trim()).filter(Boolean),
3392
+ issuer: c.Issuer,
3393
+ notBefore: toIso(c.StartDate),
3394
+ notAfter: toIso(endOfDay(c.EndDate)),
3395
+ status: c.Status ?? (c.Expired ? "EXPIRED" : "ISSUED"),
3396
+ source: c.Upload === void 0 ? void 0 : c.Upload ? "upload" : "issued"
3397
+ })
3398
+ );
3399
+ }
3400
+ return out;
3401
+ }
3402
+
3403
+ // src/providers/aliyun/cdn.ts
3404
+ function cdnLike(p) {
3405
+ return {
3406
+ key: p.service,
3407
+ label: p.label,
3408
+ async list(ctx, creds) {
3409
+ const call4 = (action, params) => callRpc(ctx, creds, { endpoint: p.endpoint, version: p.version, action, params });
3410
+ const [domains, certs] = await Promise.all([
3411
+ paginate(p.listPageSize, async (page) => {
3412
+ const res = await call4(p.listAction, {
3413
+ PageNumber: page,
3414
+ PageSize: p.listPageSize
3415
+ });
3416
+ return { items: res.Domains?.PageData ?? [], total: res.TotalCount };
3417
+ }),
3418
+ paginate(p.httpsPageSize, async (page) => {
3419
+ const res = await call4(p.httpsAction, {
3420
+ PageNumber: page,
3421
+ PageSize: p.httpsPageSize
3422
+ });
3423
+ return { items: res.CertInfos?.CertInfo ?? [], total: res.TotalCount };
3424
+ }).catch((e) => {
3425
+ if (e instanceof CloudApiError && e.code === "NoHttpsDomain") return [];
3426
+ throw e;
3427
+ })
3428
+ ]);
3429
+ const certByDomain = new Map(certs.map((c) => [c.DomainName, c]));
3430
+ return domains.map((d) => {
3431
+ const ssl = d.SslProtocol ?? d.SSLProtocol;
3432
+ const https = ssl === void 0 ? certByDomain.has(d.DomainName) : ssl === "on";
3433
+ const c = https ? certByDomain.get(d.DomainName) : void 0;
3434
+ return compact({
3435
+ provider: "aliyun",
3436
+ service: p.service,
3437
+ domain: d.DomainName,
3438
+ status: d.DomainStatus ?? d.LiveDomainStatus,
3439
+ https,
3440
+ cert: c ? compact({
3441
+ name: c.CertName,
3442
+ commonName: c.CertCommonName,
3443
+ notBefore: toIso(c.CertStartTime),
3444
+ notAfter: toIso(c.CertExpireTime),
3445
+ status: c.CertStatus
3446
+ }) : void 0,
3447
+ extra: c?.CertType ? { certType: c.CertType } : void 0
3448
+ });
3449
+ });
3450
+ }
3451
+ };
3452
+ }
3453
+ var cdn = cdnLike({
3454
+ service: "cdn",
3455
+ label: "CDN",
3456
+ endpoint: "cdn.aliyuncs.com",
3457
+ version: "2018-05-10",
3458
+ listAction: "DescribeUserDomains",
3459
+ listPageSize: 500,
3460
+ httpsAction: "DescribeCdnHttpsDomainList",
3461
+ httpsPageSize: 20
3462
+ });
3463
+ var dcdn = cdnLike({
3464
+ service: "dcdn",
3465
+ label: "\u5168\u7AD9\u52A0\u901F DCDN",
3466
+ endpoint: "dcdn.aliyuncs.com",
3467
+ version: "2018-01-15",
3468
+ listAction: "DescribeDcdnUserDomains",
3469
+ listPageSize: 500,
3470
+ httpsAction: "DescribeDcdnHttpsDomainList",
3471
+ httpsPageSize: 500
3472
+ });
3473
+ var live = cdnLike({
3474
+ service: "live",
3475
+ label: "\u89C6\u9891\u76F4\u64AD",
3476
+ endpoint: "live.aliyuncs.com",
3477
+ version: "2016-11-01",
3478
+ listAction: "DescribeLiveUserDomains",
3479
+ listPageSize: 50,
3480
+ httpsAction: "DescribeLiveHttpsDomainList",
3481
+ httpsPageSize: 20
3482
+ });
3483
+
3484
+ // src/lib/pool.ts
3485
+ async function mapLimit(items, limit, fn) {
3486
+ const results = new Array(items.length);
3487
+ let next = 0;
3488
+ const worker = async () => {
3489
+ while (next < items.length) {
3490
+ const i = next++;
3491
+ results[i] = await fn(items[i], i);
3492
+ }
3493
+ };
3494
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
3495
+ return results;
3496
+ }
3497
+
3498
+ // src/lib/xml.ts
3499
+ function xmlBlocks(xml, tag) {
3500
+ const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "g");
3501
+ return Array.from(xml.matchAll(re), (m) => m[1]);
3502
+ }
3503
+ function xmlText(xml, tag) {
3504
+ const block = xmlBlocks(xml, tag)[0];
3505
+ return block === void 0 ? void 0 : decodeEntities(block.trim());
3506
+ }
3507
+ function decodeEntities(s) {
3508
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&amp;/g, "&");
3509
+ }
3510
+
3511
+ // src/providers/aliyun/oss.ts
3512
+ var SERVICE_HOST = "oss-cn-hangzhou.aliyuncs.com";
3513
+ var SERVICE_REGION = "cn-hangzhou";
3514
+ async function ossGet(ctx, creds, req) {
3515
+ return withRetry(ctx, async () => {
3516
+ const headers = {
3517
+ "x-oss-date": ossDate(/* @__PURE__ */ new Date()),
3518
+ "x-oss-content-sha256": "UNSIGNED-PAYLOAD"
3519
+ };
3520
+ if (creds.securityToken) headers["x-oss-security-token"] = creds.securityToken;
3521
+ headers.Authorization = ossV4Authorization({
3522
+ accessKeyId: creds.accessKeyId,
3523
+ accessKeySecret: creds.accessKeySecret,
3524
+ region: req.region,
3525
+ method: "GET",
3526
+ ...req.bucket && { bucket: req.bucket },
3527
+ query: req.query,
3528
+ headers
3529
+ });
3530
+ const qs = Object.entries(req.query).map(([k, v]) => v ? `${percentEncode(k)}=${percentEncode(v)}` : percentEncode(k)).join("&");
3531
+ const raw = await send(ctx, "aliyun", `https://${req.host}/${qs ? `?${qs}` : ""}`, { method: "GET", headers });
3532
+ if (raw.status >= 400) {
3533
+ throw new CloudApiError(
3534
+ "aliyun",
3535
+ xmlText(raw.text, "Code") ?? `HTTP${raw.status}`,
3536
+ xmlText(raw.text, "Message") ?? `HTTP ${raw.status}`,
3537
+ xmlText(raw.text, "RequestId"),
3538
+ raw.status
3539
+ );
3540
+ }
3541
+ return raw.text;
3542
+ });
3543
+ }
3544
+ async function listBuckets(ctx, creds) {
3545
+ const buckets = [];
3546
+ let marker;
3547
+ for (let page = 0; page < 200; page++) {
3548
+ const xml = await ossGet(ctx, creds, {
3549
+ host: SERVICE_HOST,
3550
+ region: SERVICE_REGION,
3551
+ query: { "max-keys": "1000", ...marker && { marker } }
3552
+ });
3553
+ for (const b of xmlBlocks(xml, "Bucket")) {
3554
+ const name = xmlText(b, "Name");
3555
+ const location = xmlText(b, "Location");
3556
+ const region = xmlText(b, "Region") ?? location?.replace(/^oss-/, "");
3557
+ const endpoint = xmlText(b, "ExtranetEndpoint") ?? (location && `${location}.aliyuncs.com`);
3558
+ if (name && region && endpoint) buckets.push({ name, region, endpoint });
3559
+ }
3560
+ marker = xmlText(xml, "IsTruncated") === "true" ? xmlText(xml, "NextMarker") : void 0;
3561
+ if (!marker) break;
3562
+ }
3563
+ return buckets;
3564
+ }
3565
+ function parseCnames(xml, bucket) {
3566
+ return xmlBlocks(xml, "Cname").flatMap((block) => {
3567
+ const domain = xmlText(block, "Domain");
3568
+ if (!domain) return [];
3569
+ const certXml = xmlBlocks(block, "Certificate")[0];
3570
+ const certStatus = certXml && xmlText(certXml, "Status");
3571
+ const https = !!certXml && certStatus !== "Disabled";
3572
+ return [
3573
+ compact({
3574
+ provider: "aliyun",
3575
+ service: "oss",
3576
+ domain,
3577
+ status: xmlText(block, "Status"),
3578
+ https,
3579
+ cert: https ? compact({
3580
+ id: xmlText(certXml, "CertId"),
3581
+ notBefore: toIso(xmlText(certXml, "ValidStartDate")),
3582
+ notAfter: toIso(xmlText(certXml, "ValidEndDate")),
3583
+ status: certStatus
3584
+ }) : void 0,
3585
+ extra: compact({ bucket: bucket.name, region: bucket.region, certType: certXml && xmlText(certXml, "Type") })
3586
+ })
3587
+ ];
3588
+ });
3589
+ }
3590
+ var oss = {
3591
+ key: "oss",
3592
+ label: "\u5BF9\u8C61\u5B58\u50A8 OSS",
3593
+ async list(ctx, creds, warn) {
3594
+ const buckets = await listBuckets(ctx, creds);
3595
+ const perBucket = await mapLimit(buckets, 5, async (bucket) => {
3596
+ try {
3597
+ const xml = await ossGet(ctx, creds, {
3598
+ host: `${bucket.name}.${bucket.endpoint}`,
3599
+ region: bucket.region,
3600
+ bucket: bucket.name,
3601
+ query: { cname: "" }
3602
+ });
3603
+ return parseCnames(xml, bucket);
3604
+ } catch (e) {
3605
+ warn(e, `bucket ${bucket.name}`);
3606
+ return [];
3607
+ }
3608
+ });
3609
+ return perBucket.flat();
3610
+ }
3611
+ };
3612
+
3613
+ // src/providers/aliyun/vod.ts
3614
+ var ENDPOINT = "vod.cn-shanghai.aliyuncs.com";
3615
+ var VERSION = "2017-03-21";
3616
+ var PAGE2 = 50;
3617
+ var vod = {
3618
+ key: "vod",
3619
+ label: "\u89C6\u9891\u70B9\u64AD",
3620
+ async list(ctx, creds, warn) {
3621
+ const call4 = (action, params) => callRpc(ctx, creds, { endpoint: ENDPOINT, version: VERSION, action, params });
3622
+ const domains = await paginate(PAGE2, async (page) => {
3623
+ const res = await call4("DescribeVodUserDomains", {
3624
+ PageNumber: page,
3625
+ PageSize: PAGE2
3626
+ });
3627
+ return { items: res.Domains?.PageData ?? [], total: res.TotalCount };
3628
+ });
3629
+ return mapLimit(domains, 5, async (d) => {
3630
+ const https = d.SslProtocol === "on";
3631
+ let c;
3632
+ if (https) {
3633
+ try {
3634
+ const res = await call4("DescribeVodDomainCertificateInfo", {
3635
+ DomainName: d.DomainName
3636
+ });
3637
+ c = res.CertInfos?.CertInfo?.[0];
3638
+ } catch (e) {
3639
+ warn(e, d.DomainName);
3640
+ }
3641
+ }
3642
+ return compact({
3643
+ provider: "aliyun",
3644
+ service: "vod",
3645
+ domain: d.DomainName,
3646
+ status: d.DomainStatus,
3647
+ https,
3648
+ cert: c ? compact({
3649
+ id: c.CertId,
3650
+ name: c.CertName,
3651
+ commonName: c.CertDomainName,
3652
+ issuer: c.CertOrg,
3653
+ notBefore: toIso(c.CertStartTime),
3654
+ notAfter: toIso(c.CertExpireTime),
3655
+ status: c.Status
3656
+ }) : void 0,
3657
+ extra: c?.CertType ? { certType: c.CertType } : void 0
3658
+ });
3659
+ });
3660
+ }
3661
+ };
3662
+
3663
+ // src/providers/aliyun/index.ts
3664
+ var INACTIVE_CODES = /* @__PURE__ */ new Set(["CdnServiceNotFound", "DcdnServiceNotFound", "LiveServiceNotFound", "VodServiceNotFound"]);
3665
+ var aliyun = defineProvider({
3666
+ provider: "aliyun",
3667
+ envFamilies: ENV_FAMILIES.aliyun,
3668
+ readCredentials: readAliyun,
3669
+ services: [cdn, dcdn, oss, live, vod],
3670
+ listCertificates: listCasCertificates,
3671
+ isInactive: (code2, message) => INACTIVE_CODES.has(code2) || code2 === "UserNotFound" && /not opened/i.test(message) || code2 === "OperationDenied" && /not (open|enabled)/i.test(message)
3672
+ });
3673
+
3674
+ // src/providers/tencent/sign.ts
3675
+ import { createHash as createHash2, createHmac as createHmac2 } from "crypto";
3676
+ var sha256Hex2 = (s) => createHash2("sha256").update(s).digest("hex");
3677
+ var hmac = (key, s) => createHmac2("sha256", key).update(s).digest();
3678
+ function tc3Authorization(input) {
3679
+ const contentType = input.contentType ?? "application/json; charset=utf-8";
3680
+ const signedHeaders = "content-type;host";
3681
+ const canonicalRequest = [
3682
+ "POST",
3683
+ "/",
3684
+ "",
3685
+ `content-type:${contentType}
3686
+ host:${input.host}
3687
+ `,
3688
+ signedHeaders,
3689
+ sha256Hex2(input.payload)
3690
+ ].join("\n");
3691
+ const date = new Date(input.timestamp * 1e3).toISOString().slice(0, 10);
3692
+ const scope = `${date}/${input.service}/tc3_request`;
3693
+ const stringToSign = ["TC3-HMAC-SHA256", String(input.timestamp), scope, sha256Hex2(canonicalRequest)].join("\n");
3694
+ const kDate = hmac(`TC3${input.secretKey}`, date);
3695
+ const kService = hmac(kDate, input.service);
3696
+ const kSigning = hmac(kService, "tc3_request");
3697
+ const signature = createHmac2("sha256", kSigning).update(stringToSign).digest("hex");
3698
+ return `TC3-HMAC-SHA256 Credential=${input.secretId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
3699
+ }
3700
+
3701
+ // src/providers/tencent/client.ts
3702
+ async function callTencent(ctx, creds, req) {
3703
+ return withRetry(ctx, async () => {
3704
+ const host = `${req.service}.tencentcloudapi.com`;
3705
+ const payload = JSON.stringify(req.payload ?? {});
3706
+ const timestamp = Math.floor(Date.now() / 1e3);
3707
+ const headers = {
3708
+ Authorization: tc3Authorization({
3709
+ secretId: creds.secretId,
3710
+ secretKey: creds.secretKey,
3711
+ service: req.service,
3712
+ host,
3713
+ payload,
3714
+ timestamp
3715
+ }),
3716
+ "Content-Type": "application/json; charset=utf-8",
3717
+ "X-TC-Action": req.action,
3718
+ "X-TC-Version": req.version,
3719
+ "X-TC-Timestamp": String(timestamp),
3720
+ "X-TC-Language": "zh-CN"
3721
+ };
3722
+ if (req.region) headers["X-TC-Region"] = req.region;
3723
+ if (creds.sessionToken) headers["X-TC-Token"] = creds.sessionToken;
3724
+ const raw = await send(ctx, "tencent", `https://${host}/`, { method: "POST", headers, body: payload });
3725
+ const body = parseJson("tencent", raw);
3726
+ const res = body.Response;
3727
+ if (!res) {
3728
+ throw new CloudApiError("tencent", `HTTP${raw.status}`, `\u54CD\u5E94\u7F3A\u5C11 Response \u5B57\u6BB5\uFF1A${raw.text.slice(0, 200)}`, void 0, raw.status);
3729
+ }
3730
+ if (res.Error) {
3731
+ throw new CloudApiError("tencent", res.Error.Code ?? "Unknown", res.Error.Message ?? "\u672A\u77E5\u9519\u8BEF", res.RequestId, raw.status);
3732
+ }
3733
+ return res;
3734
+ });
3735
+ }
3736
+
3737
+ // src/providers/tencent/cdn.ts
3738
+ var PAGE3 = 100;
3739
+ var cdn2 = {
3740
+ key: "cdn",
3741
+ label: "CDN",
3742
+ async list(ctx, creds) {
3743
+ const domains = await paginate(PAGE3, async (_page, offset) => {
3744
+ const res = await callTencent(ctx, creds, {
3745
+ service: "cdn",
3746
+ version: "2018-06-06",
3747
+ action: "DescribeDomainsConfig",
3748
+ payload: { Offset: offset, Limit: PAGE3 }
3749
+ });
3750
+ return { items: res.Domains ?? [], total: res.TotalNumber };
3751
+ });
3752
+ return domains.map((d) => {
3753
+ const cert = d.Https?.CertInfo;
3754
+ const https = d.Https?.Switch === "on";
3755
+ return compact({
3756
+ provider: "tencent",
3757
+ service: "cdn",
3758
+ domain: d.Domain,
3759
+ status: d.Status,
3760
+ https,
3761
+ cert: https && cert ? compact({ id: cert.CertId, name: cert.CertName, notAfter: toIso(cert.ExpireTime) }) : void 0,
3762
+ extra: d.Area ? { area: d.Area } : void 0
3763
+ });
3764
+ });
3765
+ }
3766
+ };
3767
+
3768
+ // src/providers/tencent/ssl.ts
3769
+ var PAGE4 = 1e3;
3770
+ async function fetchAll(ctx, creds) {
3771
+ const list = await paginate(PAGE4, async (_page, offset) => {
3772
+ const res = await callTencent(ctx, creds, {
3773
+ service: "ssl",
3774
+ version: "2019-12-05",
3775
+ action: "DescribeCertificates",
3776
+ payload: { Offset: offset, Limit: PAGE4, CertificateType: "SVR" }
3777
+ });
3778
+ return { items: res.Certificates ?? [], total: res.TotalCount };
3779
+ });
3780
+ return list.map(
3781
+ (c) => compact({
3782
+ provider: "tencent",
3783
+ id: c.CertificateId,
3784
+ name: c.Alias,
3785
+ commonName: c.Domain,
3786
+ sans: c.SubjectAltName ?? void 0,
3787
+ issuer: c.ProductZhName,
3788
+ notBefore: toIso(c.CertBeginTime),
3789
+ notAfter: toIso(c.CertEndTime),
3790
+ status: c.StatusName ?? (c.Status === void 0 ? void 0 : String(c.Status)),
3791
+ source: c.From
3792
+ })
3793
+ );
3794
+ }
3795
+ var cached = memo();
3796
+ function listSslCertificates(ctx, creds) {
3797
+ return cached(ctx, `ssl:${creds.secretId}`, () => fetchAll(ctx, creds));
3798
+ }
3799
+ async function enrichFromSsl(ctx, creds, warn, records) {
3800
+ const pending = records.filter((r) => r.cert?.id && !r.cert.notAfter);
3801
+ if (pending.length === 0) return records;
3802
+ let certs;
3803
+ try {
3804
+ certs = await listSslCertificates(ctx, creds);
3805
+ } catch (e) {
3806
+ warn(e, "SSL \u8BC1\u4E66\u5217\u8868\uFF08\u7528\u4E8E\u8865\u5168\u5230\u671F\u65F6\u95F4\uFF09");
3807
+ return records;
3808
+ }
3809
+ const byId = new Map(certs.map((c) => [c.id, c]));
3810
+ for (const r of pending) {
3811
+ const c = byId.get(r.cert.id);
3812
+ if (!c) continue;
3813
+ r.cert = compact({ ...r.cert, name: r.cert.name ?? c.name, commonName: c.commonName, sans: c.sans, notBefore: c.notBefore, notAfter: c.notAfter, status: r.cert.status ?? c.status });
3814
+ }
3815
+ return records;
3816
+ }
3817
+
3818
+ // src/providers/tencent/live.ts
3819
+ var DOMAIN_PAGE = 100;
3820
+ var BINDING_PAGE = 50;
3821
+ var call = (ctx, creds, action, payload) => callTencent(ctx, creds, { service: "live", version: "2018-08-01", action, payload });
3822
+ var live2 = {
3823
+ key: "live",
3824
+ label: "\u4E91\u76F4\u64AD",
3825
+ async list(ctx, creds, warn) {
3826
+ const [domains, bindings] = await Promise.all([
3827
+ paginate(DOMAIN_PAGE, async (page) => {
3828
+ const res = await call(ctx, creds, "DescribeLiveDomains", {
3829
+ PageNum: page,
3830
+ PageSize: DOMAIN_PAGE
3831
+ });
3832
+ return { items: res.DomainList ?? [], total: res.AllCount };
3833
+ }),
3834
+ paginate(BINDING_PAGE, async (_page, offset) => {
3835
+ const res = await call(
3836
+ ctx,
3837
+ creds,
3838
+ "DescribeLiveDomainCertBindings",
3839
+ { Offset: offset, Length: BINDING_PAGE }
3840
+ );
3841
+ return { items: res.LiveDomainCertBindings ?? [], total: res.TotalNum };
3842
+ })
3843
+ ]);
3844
+ const bindingByDomain = new Map(bindings.map((b) => [b.DomainName, b]));
3845
+ const records = domains.map((d) => {
3846
+ const b = bindingByDomain.get(d.Name);
3847
+ const https = b?.Status === 1;
3848
+ return compact({
3849
+ provider: "tencent",
3850
+ service: "live",
3851
+ domain: d.Name,
3852
+ status: d.Status === void 0 ? void 0 : d.Status === 1 ? "online" : "offline",
3853
+ https,
3854
+ // 绑了证书但未开启 HTTPS 的域名不对外提供证书,不计入到期统计
3855
+ cert: https && b ? compact({ id: b.CloudCertId, name: b.CertificateAlias, notAfter: toIso(b.CertExpireTime) }) : void 0,
3856
+ extra: d.Type === void 0 ? void 0 : { type: d.Type === 1 ? "play" : "push" }
3857
+ });
3858
+ });
3859
+ return enrichFromSsl(ctx, creds, warn, records);
3860
+ }
3861
+ };
3862
+
3863
+ // src/providers/tencent/teo.ts
3864
+ var ZONE_PAGE = 100;
3865
+ var DOMAIN_PAGE2 = 200;
3866
+ var call2 = (ctx, creds, action, payload) => callTencent(ctx, creds, { service: "teo", version: "2022-09-01", action, payload });
3867
+ var teo = {
3868
+ key: "teo",
3869
+ label: "EdgeOne",
3870
+ async list(ctx, creds, warn) {
3871
+ const zones = await paginate(ZONE_PAGE, async (_page, offset) => {
3872
+ const res = await call2(ctx, creds, "DescribeZones", {
3873
+ Offset: offset,
3874
+ Limit: ZONE_PAGE
3875
+ });
3876
+ return { items: res.Zones ?? [], total: res.TotalCount };
3877
+ });
3878
+ const perZone = await mapLimit(zones, 5, async (zone) => {
3879
+ const domains = await paginate(DOMAIN_PAGE2, async (_page, offset) => {
3880
+ const res = await call2(
3881
+ ctx,
3882
+ creds,
3883
+ "DescribeAccelerationDomains",
3884
+ { ZoneId: zone.ZoneId, Offset: offset, Limit: DOMAIN_PAGE2 }
3885
+ );
3886
+ return { items: res.AccelerationDomains ?? [], total: res.TotalCount };
3887
+ }).catch((e) => {
3888
+ warn(e, `zone ${zone.ZoneName ?? zone.ZoneId}`);
3889
+ return [];
3890
+ });
3891
+ return domains.map((d) => {
3892
+ const mode = d.Certificate?.Mode;
3893
+ const certs = (d.Certificate?.List ?? []).map((c) => ({ c, notAfter: toIso(c.ExpireTime) })).sort((a, b) => (a.notAfter ?? "9999").localeCompare(b.notAfter ?? "9999"));
3894
+ const first = certs[0];
3895
+ const https = !!mode && mode !== "disable";
3896
+ return compact({
3897
+ provider: "tencent",
3898
+ service: "teo",
3899
+ domain: d.DomainName,
3900
+ status: d.DomainStatus,
3901
+ https,
3902
+ cert: https && first ? compact({ id: first.c.CertId, name: first.c.Alias, notAfter: first.notAfter, status: first.c.Status }) : void 0,
3903
+ extra: compact({ zoneId: zone.ZoneId, zone: zone.ZoneName, certMode: mode })
3904
+ });
3905
+ });
3906
+ });
3907
+ return perZone.flat();
3908
+ }
3909
+ };
3910
+
3911
+ // src/providers/tencent/vod.ts
3912
+ var SUBAPP_PAGE = 200;
3913
+ var DOMAIN_PAGE3 = 20;
3914
+ var call3 = (ctx, creds, action, payload) => callTencent(ctx, creds, { service: "vod", version: "2018-07-17", action, payload });
3915
+ var vod2 = {
3916
+ key: "vod",
3917
+ label: "\u4E91\u70B9\u64AD",
3918
+ async list(ctx, creds, warn) {
3919
+ const apps = await paginate(SUBAPP_PAGE, async (_page, offset) => {
3920
+ const res = await call3(ctx, creds, "DescribeSubAppIds", {
3921
+ Offset: offset,
3922
+ Limit: SUBAPP_PAGE
3923
+ });
3924
+ return { items: res.SubAppIdInfoSet ?? [], total: res.TotalCount };
3925
+ }).catch(() => []);
3926
+ const active = apps.filter((a) => a.Status !== "Destroyed" && a.Status !== "Destroying");
3927
+ const targets = active.length ? active : [void 0];
3928
+ const perApp = await mapLimit(targets, 5, async (app) => {
3929
+ try {
3930
+ const domains = await paginate(DOMAIN_PAGE3, async (_page, offset) => {
3931
+ const res = await call3(ctx, creds, "DescribeVodDomains", {
3932
+ Offset: offset,
3933
+ Limit: DOMAIN_PAGE3,
3934
+ ...app && { SubAppId: app.SubAppId }
3935
+ });
3936
+ return { items: res.DomainSet ?? [], total: res.TotalCount };
3937
+ });
3938
+ return domains.map((d) => [d, app]);
3939
+ } catch (e) {
3940
+ if (targets.length === 1) throw e;
3941
+ warn(e, `\u5E94\u7528 ${app?.SubAppIdName ?? app?.SubAppId}`);
3942
+ return [];
3943
+ }
3944
+ });
3945
+ const records = perApp.flat().map(([d, app]) => {
3946
+ const certId = d.HTTPSConfig?.CloudCertId;
3947
+ return compact({
3948
+ provider: "tencent",
3949
+ service: "vod",
3950
+ domain: d.Domain,
3951
+ status: d.DeployStatus,
3952
+ https: !!certId,
3953
+ cert: certId ? compact({ id: certId, notAfter: toIso(d.HTTPSConfig?.CertExpireTime) }) : void 0,
3954
+ extra: compact({ type: d.Type, subAppId: app ? String(app.SubAppId) : void 0, subApp: app?.SubAppIdName })
3955
+ });
3956
+ });
3957
+ return enrichFromSsl(ctx, creds, warn, records);
3958
+ }
3959
+ };
3960
+
3961
+ // src/providers/tencent/index.ts
3962
+ var INACTIVE_CODES2 = /* @__PURE__ */ new Set([
3963
+ "ResourceNotFound.CdnUserNotExists",
3964
+ "ResourceNotFound.InvalidUser",
3965
+ "ResourceNotFound.UserNotExist",
3966
+ "FailedOperation.InvalidVodUser",
3967
+ "ResourceNotFound.ServiceNotExist"
3968
+ ]);
3969
+ var tencent = defineProvider({
3970
+ provider: "tencent",
3971
+ envFamilies: ENV_FAMILIES.tencent,
3972
+ readCredentials: readTencent,
3973
+ services: [cdn2, teo, live2, vod2],
3974
+ listCertificates: listSslCertificates,
3975
+ isInactive: (code2) => INACTIVE_CODES2.has(code2)
3976
+ });
3977
+
3978
+ // src/query.ts
3979
+ var PROVIDER_DEFS = { aliyun, tencent };
3980
+ var UsageError = class extends Error {
3981
+ };
3982
+ function resolveTargets(env, providers) {
3983
+ const explicit = providers && providers.length > 0;
3984
+ const targets = [];
3985
+ for (const p of explicit ? providers : Object.keys(PROVIDER_DEFS)) {
3986
+ const def = PROVIDER_DEFS[p];
3987
+ const state = def.readCredentials(env);
3988
+ if (state.state === "incomplete") {
3989
+ throw new UsageError(`${p} \u51ED\u8BC1\u4E0D\u5B8C\u6574\uFF0C\u7F3A\u5C11\u73AF\u5883\u53D8\u91CF ${state.missing.join(", ")}`);
3990
+ }
3991
+ if (state.state === "missing") {
3992
+ if (explicit) throw new UsageError(`${p} \u672A\u914D\u7F6E\u51ED\u8BC1\uFF0C\u9700\u8981\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF\uFF1A${requiredEnvNames(def).join("\u3001")}`);
3993
+ continue;
3994
+ }
3995
+ targets.push({ def, creds: state.credentials });
3996
+ }
3997
+ if (targets.length === 0) {
3998
+ const hints = Object.values(PROVIDER_DEFS).map((d) => `${d.provider}: ${requiredEnvNames(d).join("\u3001")}`);
3999
+ throw new UsageError(`\u672A\u68C0\u6D4B\u5230\u4EFB\u4F55\u4E91\u5382\u5546\u51ED\u8BC1\uFF0C\u8BF7\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF\uFF08\u6216\u5199\u5165\u5F53\u524D\u76EE\u5F55 .env\uFF09\uFF1A
4000
+ ${hints.join("\n ")}`);
4001
+ }
4002
+ return targets;
4003
+ }
4004
+ function toIssue(def, service, e, target) {
4005
+ const where = { provider: def.provider, service, ...target && { target } };
4006
+ if (e instanceof CloudApiError) {
4007
+ return {
4008
+ ...where,
4009
+ kind: def.isInactive(e.code, e.message) ? "inactive" : "error",
4010
+ code: e.code,
4011
+ message: e.message,
4012
+ ...e.requestId && { requestId: e.requestId }
4013
+ };
4014
+ }
4015
+ return { ...where, kind: "error", code: "Unknown", message: String(e?.message ?? e) };
4016
+ }
4017
+ async function queryDomains(ctx, sel) {
4018
+ const targets = resolveTargets(ctx.env, sel.providers);
4019
+ const jobs = targets.flatMap(({ def, creds }) => {
4020
+ const services = sel.services?.length ? def.services.filter((s) => sel.services.includes(s.key)) : def.services;
4021
+ return services.map((svc) => ({ def, svc, creds }));
4022
+ });
4023
+ if (jobs.length === 0) {
4024
+ throw new UsageError(`\u6240\u9009\u4E91\u5382\u5546\u4E0D\u652F\u6301\u670D\u52A1\uFF1A${sel.services?.join(", ")}`);
4025
+ }
4026
+ const items = [];
4027
+ const issues = [];
4028
+ const settled = await Promise.allSettled(
4029
+ jobs.map((j) => j.svc.list(ctx, j.creds, (e, target) => issues.push(toIssue(j.def, j.svc.key, e, target))))
4030
+ );
4031
+ settled.forEach((r, i) => {
4032
+ const job = jobs[i];
4033
+ if (r.status === "fulfilled") items.push(...r.value);
4034
+ else issues.push(toIssue(job.def, job.svc.key, r.reason));
4035
+ });
4036
+ for (const item of items) {
4037
+ const days2 = daysUntil(item.cert?.notAfter, ctx.now);
4038
+ if (days2 !== void 0) item.daysLeft = days2;
4039
+ }
4040
+ return { items, issues, succeeded: settled.filter((r) => r.status === "fulfilled").length };
4041
+ }
4042
+ async function queryCertificates(ctx, sel) {
4043
+ const targets = resolveTargets(ctx.env, sel.providers);
4044
+ const settled = await Promise.allSettled(targets.map(({ def, creds }) => def.listCertificates(ctx, creds)));
4045
+ const items = [];
4046
+ const issues = [];
4047
+ settled.forEach((r, i) => {
4048
+ const { def } = targets[i];
4049
+ if (r.status === "fulfilled") items.push(...r.value);
4050
+ else issues.push(toIssue(def, "cert", r.reason));
4051
+ });
4052
+ for (const item of items) {
4053
+ const days2 = daysUntil(item.notAfter, ctx.now);
4054
+ if (days2 !== void 0) item.daysLeft = days2;
4055
+ }
4056
+ return { items, issues, succeeded: settled.filter((r) => r.status === "fulfilled").length };
4057
+ }
4058
+ function matchesKeyword(values, keyword) {
4059
+ const k = keyword.toLowerCase();
4060
+ return values.some((v) => v?.toLowerCase().includes(k));
4061
+ }
4062
+ function byExpiry(a, b) {
4063
+ return (a.daysLeft ?? Number.POSITIVE_INFINITY) - (b.daysLeft ?? Number.POSITIVE_INFINITY);
4064
+ }
4065
+ function filterDomains(items, f) {
4066
+ return items.filter((d) => !f.keyword || matchesKeyword([d.domain, d.cert?.commonName, ...d.cert?.sans ?? []], f.keyword)).filter((d) => f.expiringWithin === void 0 || d.daysLeft !== void 0 && d.daysLeft <= f.expiringWithin).sort((a, b) => byExpiry(a, b) || `${a.provider}/${a.service}/${a.domain}`.localeCompare(`${b.provider}/${b.service}/${b.domain}`));
4067
+ }
4068
+ function filterCertificates(items, f) {
4069
+ return items.filter((c) => !f.keyword || matchesKeyword([c.name, c.commonName, ...c.sans ?? []], f.keyword)).filter((c) => f.expiringWithin === void 0 || c.daysLeft !== void 0 && c.daysLeft <= f.expiringWithin).sort((a, b) => byExpiry(a, b) || `${a.provider}/${a.commonName ?? ""}`.localeCompare(`${b.provider}/${b.commonName ?? ""}`));
4070
+ }
4071
+
4072
+ // src/types.ts
4073
+ var PROVIDERS = ["aliyun", "tencent"];
4074
+ var PROVIDER_LABEL = {
4075
+ aliyun: "\u963F\u91CC\u4E91",
4076
+ tencent: "\u817E\u8BAF\u4E91"
4077
+ };
4078
+
4079
+ // src/render.ts
4080
+ function serviceLabel(provider, key) {
4081
+ return PROVIDER_DEFS[provider].services.find((s) => s.key === key)?.label ?? key;
4082
+ }
4083
+ function days(d) {
4084
+ if (d === void 0) return "-";
4085
+ return d < 0 ? `\u5DF2\u8FC7\u671F ${-d} \u5929` : String(d);
4086
+ }
4087
+ function renderDomains(items, expiringWithin) {
4088
+ if (items.length === 0) return expiringWithin === void 0 ? "\u6CA1\u6709\u67E5\u5230\u57DF\u540D\u3002" : `\u6CA1\u6709 ${expiringWithin} \u5929\u5185\u5230\u671F\u7684\u8BC1\u4E66\u3002`;
4089
+ const table = renderTable(
4090
+ ["\u4E91\u5382\u5546", "\u670D\u52A1", "\u57DF\u540D", "HTTPS", "\u8BC1\u4E66", "\u5230\u671F\u65F6\u95F4", "\u5269\u4F59\u5929\u6570"],
4091
+ items.map((d) => [
4092
+ PROVIDER_LABEL[d.provider],
4093
+ serviceLabel(d.provider, d.service),
4094
+ d.domain,
4095
+ d.https ? "\u5F00\u542F" : "\u5173\u95ED",
4096
+ d.cert?.name ?? d.cert?.commonName ?? d.cert?.id ?? "-",
4097
+ formatDate(d.cert?.notAfter),
4098
+ days(d.daysLeft)
4099
+ ])
4100
+ );
4101
+ const expired = items.filter((d) => d.daysLeft !== void 0 && d.daysLeft < 0).length;
4102
+ const soon = items.filter((d) => d.daysLeft !== void 0 && d.daysLeft >= 0 && d.daysLeft <= 30).length;
4103
+ const plain = items.filter((d) => !d.https).length;
4104
+ const parts = [`\u5171 ${items.length} \u4E2A\u57DF\u540D`];
4105
+ if (expired) parts.push(`${expired} \u4E2A\u8BC1\u4E66\u5DF2\u8FC7\u671F`);
4106
+ if (soon) parts.push(`${soon} \u4E2A 30 \u5929\u5185\u5230\u671F`);
4107
+ if (plain) parts.push(`${plain} \u4E2A\u672A\u5F00\u542F HTTPS`);
4108
+ return `${table}
4109
+
4110
+ ${parts.join("\uFF0C")}`;
4111
+ }
4112
+ function renderCerts(items, expiringWithin) {
4113
+ if (items.length === 0) return expiringWithin === void 0 ? "\u6CA1\u6709\u67E5\u5230\u8BC1\u4E66\u3002" : `\u6CA1\u6709 ${expiringWithin} \u5929\u5185\u5230\u671F\u7684\u8BC1\u4E66\u3002`;
4114
+ const table = renderTable(
4115
+ ["\u4E91\u5382\u5546", "\u8BC1\u4E66 ID", "\u540D\u79F0", "\u7ED1\u5B9A\u57DF\u540D", "\u5230\u671F\u65F6\u95F4", "\u5269\u4F59\u5929\u6570", "\u72B6\u6001"],
4116
+ items.map((c) => {
4117
+ const domains = c.sans?.length ? c.sans : c.commonName ? [c.commonName] : [];
4118
+ const shown = domains.length > 3 ? `${domains.slice(0, 3).join(", ")} \u7B49 ${domains.length} \u4E2A` : domains.join(", ");
4119
+ return [
4120
+ PROVIDER_LABEL[c.provider],
4121
+ c.id,
4122
+ c.name ?? "-",
4123
+ shown || "-",
4124
+ formatDate(c.notAfter),
4125
+ days(c.daysLeft),
4126
+ c.status ?? "-"
4127
+ ];
4128
+ })
4129
+ );
4130
+ return `${table}
4131
+
4132
+ \u5171 ${items.length} \u5F20\u8BC1\u4E66`;
4133
+ }
4134
+ function envStatus(env) {
4135
+ return Object.values(PROVIDER_DEFS).map((def) => {
4136
+ const state = def.readCredentials(env);
4137
+ return {
4138
+ provider: def.provider,
4139
+ state: state.state,
4140
+ keys: envKeyStatus(def, env, mask),
4141
+ services: def.services.map((s) => s.key)
4142
+ };
4143
+ });
4144
+ }
4145
+ var STATE_LABEL = { ok: "\u5DF2\u914D\u7F6E", missing: "\u672A\u914D\u7F6E", incomplete: "\u914D\u7F6E\u4E0D\u5B8C\u6574" };
4146
+ function renderEnv(env, envFile) {
4147
+ const lines = [`.env \u6587\u4EF6\uFF1A${envFile ?? "\u672A\u52A0\u8F7D\uFF08\u5F53\u524D\u76EE\u5F55\u4E0D\u5B58\u5728 .env\uFF09"}`, ""];
4148
+ for (const s of envStatus(env)) {
4149
+ lines.push(`${PROVIDER_LABEL[s.provider]}\uFF08${s.provider}\uFF09\uFF1A${STATE_LABEL[s.state]}`);
4150
+ for (const k of s.keys) {
4151
+ const value2 = k.set ? k.masked ? `= ${k.masked}` : "\u5DF2\u8BBE\u7F6E" : k.required ? "\u672A\u8BBE\u7F6E\uFF08\u5FC5\u586B\uFF09" : "\u672A\u8BBE\u7F6E\uFF08\u53EF\u9009\uFF09";
4152
+ lines.push(` ${k.name} ${value2}`);
4153
+ }
4154
+ lines.push(` \u53EF\u67E5\u8BE2\u670D\u52A1\uFF1A${s.services.join(", ")}`, "");
4155
+ }
4156
+ return lines.join("\n").trimEnd();
4157
+ }
4158
+
4159
+ // src/lib/output.ts
4160
+ var ExitError = class extends Error {
4161
+ constructor(exitCode, message) {
4162
+ super(message ?? `exit ${exitCode}`);
4163
+ this.exitCode = exitCode;
4164
+ }
4165
+ exitCode;
4166
+ };
4167
+ function outJson(data) {
4168
+ console.log(JSON.stringify({ ok: true, data }));
4169
+ }
4170
+ function fail(opts, status, message, exitCode = 1, extra) {
4171
+ if (opts.json) {
4172
+ console.error(JSON.stringify({ ok: false, status, message, ...extra }));
4173
+ } else {
4174
+ console.error(`\u9519\u8BEF\uFF1A${message}`);
4175
+ }
4176
+ throw new ExitError(exitCode, message);
4177
+ }
4178
+
4179
+ // package.json
4180
+ var package_default = {
4181
+ name: "sslbear-cli",
4182
+ version: "0.1.0",
4183
+ description: "\u8BC1\u4E66\u718A CLI\uFF1A\u67E5\u8BE2\u963F\u91CC\u4E91\u3001\u817E\u8BAF\u4E91\u4E91\u670D\u52A1\u4E0A\u7684\u57DF\u540D\u53CA\u5176 SSL \u8BC1\u4E66",
4184
+ type: "module",
4185
+ bin: {
4186
+ "sslbear-cli": "dist/index.js"
4187
+ },
4188
+ files: [
4189
+ "dist",
4190
+ "README.md"
4191
+ ],
4192
+ engines: {
4193
+ node: ">=18.17"
4194
+ },
4195
+ scripts: {
4196
+ build: "tsup",
4197
+ dev: "tsx src/index.ts",
4198
+ test: "vitest run",
4199
+ typecheck: "tsc --noEmit",
4200
+ prepublishOnly: "npm run typecheck && npm test && npm run build"
4201
+ },
4202
+ keywords: [
4203
+ "ssl",
4204
+ "certificate",
4205
+ "aliyun",
4206
+ "tencentcloud",
4207
+ "cdn",
4208
+ "sslbear"
4209
+ ],
4210
+ license: "MIT",
4211
+ devDependencies: {
4212
+ "@types/node": "^22.20.5",
4213
+ commander: "^12.1.0",
4214
+ tsup: "^9.0.0",
4215
+ tsx: "^4.23.15",
4216
+ typescript: "^7.0.2",
4217
+ vitest: "^5.0.5"
4218
+ }
4219
+ };
4220
+
4221
+ // src/version.ts
4222
+ var VERSION2 = package_default.version;
4223
+
4224
+ // src/cli.ts
4225
+ var ALL_SERVICE_KEYS = [...new Set(Object.values(PROVIDER_DEFS).flatMap((d) => d.services.map((s) => s.key)))];
4226
+ var csv = (value2, prev = []) => [
4227
+ ...prev,
4228
+ ...value2.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
4229
+ ];
4230
+ function intArg(name, min, max) {
4231
+ return (value2) => {
4232
+ const n = Number(value2);
4233
+ if (!/^\d+$/.test(value2) || n < min || n > max) throw new UsageError(`${name} \u9700\u4E3A ${min}~${max} \u7684\u6574\u6570\uFF0C\u6536\u5230 "${value2}"`);
4234
+ return n;
4235
+ };
4236
+ }
4237
+ function validateProviders(list) {
4238
+ for (const p of list ?? []) {
4239
+ if (!PROVIDERS.includes(p)) throw new UsageError(`\u4E0D\u652F\u6301\u7684\u4E91\u5382\u5546 "${p}"\uFF0C\u53EF\u9009\uFF1A${PROVIDERS.join(", ")}`);
4240
+ }
4241
+ return list && [...new Set(list)];
4242
+ }
4243
+ function validateServices(list) {
4244
+ for (const s of list ?? []) {
4245
+ if (!ALL_SERVICE_KEYS.includes(s)) {
4246
+ const hint = Object.values(PROVIDER_DEFS).map((d) => `${d.provider}: ${d.services.map((x) => x.key).join(", ")}`);
4247
+ throw new UsageError(`\u4E0D\u652F\u6301\u7684\u670D\u52A1 "${s}"\uFF0C\u53EF\u9009\uFF1A
4248
+ ${hint.join("\n ")}`);
4249
+ }
4250
+ }
4251
+ return list && [...new Set(list)];
4252
+ }
4253
+ var CREDENTIAL_GROUPS = Object.values(PROVIDER_DEFS).map((d) => familyNames(d.envFamilies));
4254
+ function loadEnv(deps, opts) {
4255
+ const env = { ...deps.env };
4256
+ if (opts.envFile) {
4257
+ const path2 = resolve(deps.cwd, opts.envFile);
4258
+ if (!loadEnvFile(path2, env, CREDENTIAL_GROUPS)) throw new UsageError(`--env-file \u6307\u5B9A\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${path2}`);
4259
+ return { env, envFile: path2 };
4260
+ }
4261
+ const path = resolve(deps.cwd, ".env");
4262
+ return loadEnvFile(path, env, CREDENTIAL_GROUPS) ? { env, envFile: path } : { env };
4263
+ }
4264
+ function createContext(deps, opts) {
4265
+ return {
4266
+ env: loadEnv(deps, opts).env,
4267
+ fetch: deps.fetch,
4268
+ now: deps.now(),
4269
+ timeoutMs: opts.timeout,
4270
+ ...deps.sleep && { sleep: deps.sleep }
4271
+ };
4272
+ }
4273
+ function withQuery(cmd, serviceHelp) {
4274
+ cmd.option("-p, --provider <list>", `\u53EA\u67E5\u6307\u5B9A\u4E91\u5382\u5546\uFF0C\u9017\u53F7\u5206\u9694\uFF08${PROVIDERS.join(", ")}\uFF09\uFF1B\u9ED8\u8BA4\u67E5\u6240\u6709\u5DF2\u914D\u7F6E\u51ED\u8BC1\u7684\u4E91\u5382\u5546`, csv);
4275
+ if (serviceHelp) cmd.option("-s, --service <list>", `\u53EA\u67E5\u6307\u5B9A\u670D\u52A1\uFF0C\u9017\u53F7\u5206\u9694\u3002${serviceHelp}`, csv);
4276
+ return cmd.option("-d, --domain <keyword>", "\u6309\u57DF\u540D\u5173\u952E\u5B57\u8FC7\u6EE4\uFF08\u540C\u65F6\u5339\u914D\u8BC1\u4E66\u7684\u901A\u7528\u540D\u548C SAN\uFF09").addOption(
4277
+ new Option("-e, --expiring-within <days>", "\u53EA\u770B N \u5929\u5185\u5230\u671F\uFF08\u542B\u5DF2\u8FC7\u671F\uFF09\u7684\u8BC1\u4E66").argParser(intArg("--expiring-within", 0, 36500))
4278
+ ).addOption(new Option("--timeout <ms>", "\u5355\u4E2A\u8BF7\u6C42\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").default(15e3).argParser(intArg("--timeout", 1, 6e5))).option("--json", "\u8F93\u51FA\u5355\u884C JSON\uFF1A\u6210\u529F {ok:true,data}\uFF0C\u5931\u8D25 {ok:false,status,message}").option("--env-file <path>", "\u4ECE\u6307\u5B9A\u6587\u4EF6\u52A0\u8F7D\u73AF\u5883\u53D8\u91CF\uFF08\u9ED8\u8BA4\u52A0\u8F7D\u5F53\u524D\u76EE\u5F55\u7684 .env\uFF0C\u82E5\u5B58\u5728\uFF09");
4279
+ }
4280
+ function printIssues(opts, issues) {
4281
+ if (opts.json) return;
4282
+ for (const i of issues) {
4283
+ const where = `${i.provider}/${i.service}${i.target ? ` ${i.target}` : ""}`;
4284
+ const rid = i.requestId ? `\uFF08RequestId: ${i.requestId}\uFF09` : "";
4285
+ console.error(i.kind === "inactive" ? `\u63D0\u793A\uFF1A${where} \u672A\u5F00\u901A\u6216\u65E0\u8D44\u6E90\uFF08${i.code}\uFF09` : `\u8B66\u544A\uFF1A${where} \u67E5\u8BE2\u5931\u8D25\uFF1A${i.code} ${i.message}${rid}`);
4286
+ }
4287
+ }
4288
+ function emit(opts, result, items, render) {
4289
+ const errors = result.issues.filter((i) => i.kind === "error");
4290
+ if (result.succeeded === 0 && errors.length > 0) {
4291
+ printIssues(opts, result.issues);
4292
+ const message = opts.json ? `\u6CA1\u6709\u4EFB\u4F55\u67E5\u8BE2\u6210\u529F\uFF1A${errors.map((e) => `${e.provider}/${e.service} ${e.code} ${e.message}`).join("\uFF1B")}` : `\u6CA1\u6709\u4EFB\u4F55\u67E5\u8BE2\u6210\u529F\uFF08${errors.length} \u9879\u5931\u8D25\uFF09\uFF0C\u8BF7\u68C0\u67E5\u51ED\u8BC1\u4E0E\u6743\u9650`;
4293
+ fail(opts, errors[0].code, message, 1, { issues: result.issues });
4294
+ }
4295
+ if (opts.json) outJson({ items, issues: result.issues });
4296
+ else console.log(render());
4297
+ printIssues(opts, result.issues);
4298
+ }
4299
+ function buildProgram(deps, output = { json: false }) {
4300
+ const program2 = new Command("sslbear-cli").description("\u8BC1\u4E66\u718A CLI\uFF1A\u67E5\u8BE2\u963F\u91CC\u4E91\u3001\u817E\u8BAF\u4E91\u4E91\u670D\u52A1\u4E0A\u7684\u57DF\u540D\u53CA\u5176 SSL \u8BC1\u4E66\uFF08\u51ED\u8BC1\u4ECE\u73AF\u5883\u53D8\u91CF\u8BFB\u53D6\uFF09").version(VERSION2).exitOverride();
4301
+ if (output.json) program2.configureOutput({ writeErr: () => {
4302
+ }, outputError: () => {
4303
+ } });
4304
+ else program2.showHelpAfterError();
4305
+ const serviceHelp = Object.values(PROVIDER_DEFS).map((d) => `${d.provider}: ${d.services.map((s) => `${s.key}(${s.label})`).join(", ")}`).join("\uFF1B");
4306
+ withQuery(
4307
+ program2.command("domains").description("\u5217\u51FA\u4E91\u670D\u52A1\u4E0A\u7684\u57DF\u540D\u53CA\u5176\u7ED1\u5B9A\u7684 SSL \u8BC1\u4E66\uFF0C\u6309\u5269\u4F59\u5929\u6570\u5347\u5E8F"),
4308
+ serviceHelp
4309
+ ).action(async (opts) => {
4310
+ const out = { json: !!opts.json };
4311
+ const ctx = createContext(deps, opts);
4312
+ const sel = { providers: validateProviders(opts.provider), services: validateServices(opts.service) };
4313
+ const result = await queryDomains(ctx, sel);
4314
+ const items = filterDomains(result.items, { keyword: opts.domain, expiringWithin: opts.expiringWithin });
4315
+ emit(out, result, items, () => renderDomains(items, opts.expiringWithin));
4316
+ });
4317
+ withQuery(
4318
+ program2.command("certs").description("\u5217\u51FA\u8BC1\u4E66\u670D\u52A1\u4E2D\u7684\u8BC1\u4E66\uFF08\u963F\u91CC\u4E91\u6570\u5B57\u8BC1\u4E66\u7BA1\u7406\u670D\u52A1 / \u817E\u8BAF\u4E91 SSL \u8BC1\u4E66\uFF09\uFF0C\u6309\u5269\u4F59\u5929\u6570\u5347\u5E8F")
4319
+ ).action(async (opts) => {
4320
+ const out = { json: !!opts.json };
4321
+ const ctx = createContext(deps, opts);
4322
+ const result = await queryCertificates(ctx, { providers: validateProviders(opts.provider) });
4323
+ const items = filterCertificates(result.items, { keyword: opts.domain, expiringWithin: opts.expiringWithin });
4324
+ emit(out, result, items, () => renderCerts(items, opts.expiringWithin));
4325
+ });
4326
+ program2.command("env").description("\u68C0\u67E5\u73AF\u5883\u53D8\u91CF\u91CC\u7684\u4E91\u5382\u5546\u51ED\u8BC1\u914D\u7F6E\uFF08\u8131\u654F\u663E\u793A\uFF09").option("--json", "\u8F93\u51FA\u5355\u884C JSON").option("--env-file <path>", "\u4ECE\u6307\u5B9A\u6587\u4EF6\u52A0\u8F7D\u73AF\u5883\u53D8\u91CF\uFF08\u9ED8\u8BA4\u52A0\u8F7D\u5F53\u524D\u76EE\u5F55\u7684 .env\uFF0C\u82E5\u5B58\u5728\uFF09").action((opts) => {
4327
+ const { env, envFile } = loadEnv(deps, opts);
4328
+ if (opts.json) outJson({ envFile: envFile ?? null, providers: envStatus(env) });
4329
+ else console.log(renderEnv(env, envFile));
4330
+ });
4331
+ return program2;
4332
+ }
4333
+ async function run(argv, deps) {
4334
+ const json = argv.includes("--json");
4335
+ try {
4336
+ await buildProgram(deps, { json }).parseAsync(argv, { from: "user" });
4337
+ return 0;
4338
+ } catch (e) {
4339
+ if (e instanceof ExitError) return e.exitCode;
4340
+ const code2 = e.code ?? "";
4341
+ try {
4342
+ if (code2.startsWith("commander.")) {
4343
+ if (e.exitCode === 0) return 0;
4344
+ if (json) fail({ json }, "UsageError", e.message.replace(/^error: /, ""), 2);
4345
+ return 2;
4346
+ }
4347
+ if (e instanceof UsageError) fail({ json }, "UsageError", e.message, 2);
4348
+ fail({ json }, "Unknown", String(e?.message ?? e), 1);
4349
+ } catch (exit) {
4350
+ return exit.exitCode;
4351
+ }
4352
+ }
4353
+ }
4354
+
4355
+ // src/index.ts
4356
+ var code = await run(process.argv.slice(2), {
4357
+ env: process.env,
4358
+ fetch: globalThis.fetch,
4359
+ now: () => /* @__PURE__ */ new Date(),
4360
+ cwd: process.cwd()
4361
+ });
4362
+ process.exitCode = code;