mcp2service 1.0.0 → 1.0.2

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.
package/dist/cjs/cli.js DELETED
@@ -1,2283 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @bun
3
- import { createRequire } from "node:module";
4
- var __create = Object.create;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __toESM = (mod, isNodeMode, target) => {
10
- target = mod != null ? __create(__getProtoOf(mod)) : {};
11
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
- for (let key of __getOwnPropNames(mod))
13
- if (!__hasOwnProp.call(to, key))
14
- __defProp(to, key, {
15
- get: () => mod[key],
16
- enumerable: true
17
- });
18
- return to;
19
- };
20
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
21
- var __export = (target, all) => {
22
- for (var name in all)
23
- __defProp(target, name, {
24
- get: all[name],
25
- enumerable: true,
26
- configurable: true,
27
- set: (newValue) => all[name] = () => newValue
28
- });
29
- };
30
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
31
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
32
-
33
- // node_modules/commander/lib/error.js
34
- var require_error = __commonJS((exports) => {
35
- class CommanderError extends Error {
36
- constructor(exitCode, code, message) {
37
- super(message);
38
- Error.captureStackTrace(this, this.constructor);
39
- this.name = this.constructor.name;
40
- this.code = code;
41
- this.exitCode = exitCode;
42
- this.nestedError = undefined;
43
- }
44
- }
45
-
46
- class InvalidArgumentError extends CommanderError {
47
- constructor(message) {
48
- super(1, "commander.invalidArgument", message);
49
- Error.captureStackTrace(this, this.constructor);
50
- this.name = this.constructor.name;
51
- }
52
- }
53
- exports.CommanderError = CommanderError;
54
- exports.InvalidArgumentError = InvalidArgumentError;
55
- });
56
-
57
- // node_modules/commander/lib/argument.js
58
- var require_argument = __commonJS((exports) => {
59
- var { InvalidArgumentError } = require_error();
60
-
61
- class Argument {
62
- constructor(name, description) {
63
- this.description = description || "";
64
- this.variadic = false;
65
- this.parseArg = undefined;
66
- this.defaultValue = undefined;
67
- this.defaultValueDescription = undefined;
68
- this.argChoices = undefined;
69
- switch (name[0]) {
70
- case "<":
71
- this.required = true;
72
- this._name = name.slice(1, -1);
73
- break;
74
- case "[":
75
- this.required = false;
76
- this._name = name.slice(1, -1);
77
- break;
78
- default:
79
- this.required = true;
80
- this._name = name;
81
- break;
82
- }
83
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
84
- this.variadic = true;
85
- this._name = this._name.slice(0, -3);
86
- }
87
- }
88
- name() {
89
- return this._name;
90
- }
91
- _concatValue(value, previous) {
92
- if (previous === this.defaultValue || !Array.isArray(previous)) {
93
- return [value];
94
- }
95
- return previous.concat(value);
96
- }
97
- default(value, description) {
98
- this.defaultValue = value;
99
- this.defaultValueDescription = description;
100
- return this;
101
- }
102
- argParser(fn) {
103
- this.parseArg = fn;
104
- return this;
105
- }
106
- choices(values) {
107
- this.argChoices = values.slice();
108
- this.parseArg = (arg, previous) => {
109
- if (!this.argChoices.includes(arg)) {
110
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
111
- }
112
- if (this.variadic) {
113
- return this._concatValue(arg, previous);
114
- }
115
- return arg;
116
- };
117
- return this;
118
- }
119
- argRequired() {
120
- this.required = true;
121
- return this;
122
- }
123
- argOptional() {
124
- this.required = false;
125
- return this;
126
- }
127
- }
128
- function humanReadableArgName(arg) {
129
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
130
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
131
- }
132
- exports.Argument = Argument;
133
- exports.humanReadableArgName = humanReadableArgName;
134
- });
135
-
136
- // node_modules/commander/lib/help.js
137
- var require_help = __commonJS((exports) => {
138
- var { humanReadableArgName } = require_argument();
139
-
140
- class Help {
141
- constructor() {
142
- this.helpWidth = undefined;
143
- this.sortSubcommands = false;
144
- this.sortOptions = false;
145
- this.showGlobalOptions = false;
146
- }
147
- visibleCommands(cmd) {
148
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
149
- const helpCommand = cmd._getHelpCommand();
150
- if (helpCommand && !helpCommand._hidden) {
151
- visibleCommands.push(helpCommand);
152
- }
153
- if (this.sortSubcommands) {
154
- visibleCommands.sort((a, b) => {
155
- return a.name().localeCompare(b.name());
156
- });
157
- }
158
- return visibleCommands;
159
- }
160
- compareOptions(a, b) {
161
- const getSortKey = (option) => {
162
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
163
- };
164
- return getSortKey(a).localeCompare(getSortKey(b));
165
- }
166
- visibleOptions(cmd) {
167
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
168
- const helpOption = cmd._getHelpOption();
169
- if (helpOption && !helpOption.hidden) {
170
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
171
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
172
- if (!removeShort && !removeLong) {
173
- visibleOptions.push(helpOption);
174
- } else if (helpOption.long && !removeLong) {
175
- visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
176
- } else if (helpOption.short && !removeShort) {
177
- visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
178
- }
179
- }
180
- if (this.sortOptions) {
181
- visibleOptions.sort(this.compareOptions);
182
- }
183
- return visibleOptions;
184
- }
185
- visibleGlobalOptions(cmd) {
186
- if (!this.showGlobalOptions)
187
- return [];
188
- const globalOptions = [];
189
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
190
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
191
- globalOptions.push(...visibleOptions);
192
- }
193
- if (this.sortOptions) {
194
- globalOptions.sort(this.compareOptions);
195
- }
196
- return globalOptions;
197
- }
198
- visibleArguments(cmd) {
199
- if (cmd._argsDescription) {
200
- cmd.registeredArguments.forEach((argument) => {
201
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
202
- });
203
- }
204
- if (cmd.registeredArguments.find((argument) => argument.description)) {
205
- return cmd.registeredArguments;
206
- }
207
- return [];
208
- }
209
- subcommandTerm(cmd) {
210
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
211
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
212
- }
213
- optionTerm(option) {
214
- return option.flags;
215
- }
216
- argumentTerm(argument) {
217
- return argument.name();
218
- }
219
- longestSubcommandTermLength(cmd, helper) {
220
- return helper.visibleCommands(cmd).reduce((max, command) => {
221
- return Math.max(max, helper.subcommandTerm(command).length);
222
- }, 0);
223
- }
224
- longestOptionTermLength(cmd, helper) {
225
- return helper.visibleOptions(cmd).reduce((max, option) => {
226
- return Math.max(max, helper.optionTerm(option).length);
227
- }, 0);
228
- }
229
- longestGlobalOptionTermLength(cmd, helper) {
230
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
231
- return Math.max(max, helper.optionTerm(option).length);
232
- }, 0);
233
- }
234
- longestArgumentTermLength(cmd, helper) {
235
- return helper.visibleArguments(cmd).reduce((max, argument) => {
236
- return Math.max(max, helper.argumentTerm(argument).length);
237
- }, 0);
238
- }
239
- commandUsage(cmd) {
240
- let cmdName = cmd._name;
241
- if (cmd._aliases[0]) {
242
- cmdName = cmdName + "|" + cmd._aliases[0];
243
- }
244
- let ancestorCmdNames = "";
245
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
246
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
247
- }
248
- return ancestorCmdNames + cmdName + " " + cmd.usage();
249
- }
250
- commandDescription(cmd) {
251
- return cmd.description();
252
- }
253
- subcommandDescription(cmd) {
254
- return cmd.summary() || cmd.description();
255
- }
256
- optionDescription(option) {
257
- const extraInfo = [];
258
- if (option.argChoices) {
259
- extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
260
- }
261
- if (option.defaultValue !== undefined) {
262
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
263
- if (showDefault) {
264
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
265
- }
266
- }
267
- if (option.presetArg !== undefined && option.optional) {
268
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
269
- }
270
- if (option.envVar !== undefined) {
271
- extraInfo.push(`env: ${option.envVar}`);
272
- }
273
- if (extraInfo.length > 0) {
274
- return `${option.description} (${extraInfo.join(", ")})`;
275
- }
276
- return option.description;
277
- }
278
- argumentDescription(argument) {
279
- const extraInfo = [];
280
- if (argument.argChoices) {
281
- extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
282
- }
283
- if (argument.defaultValue !== undefined) {
284
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
285
- }
286
- if (extraInfo.length > 0) {
287
- const extraDescripton = `(${extraInfo.join(", ")})`;
288
- if (argument.description) {
289
- return `${argument.description} ${extraDescripton}`;
290
- }
291
- return extraDescripton;
292
- }
293
- return argument.description;
294
- }
295
- formatHelp(cmd, helper) {
296
- const termWidth = helper.padWidth(cmd, helper);
297
- const helpWidth = helper.helpWidth || 80;
298
- const itemIndentWidth = 2;
299
- const itemSeparatorWidth = 2;
300
- function formatItem(term, description) {
301
- if (description) {
302
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
303
- return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
304
- }
305
- return term;
306
- }
307
- function formatList(textArray) {
308
- return textArray.join(`
309
- `).replace(/^/gm, " ".repeat(itemIndentWidth));
310
- }
311
- let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
312
- const commandDescription = helper.commandDescription(cmd);
313
- if (commandDescription.length > 0) {
314
- output = output.concat([
315
- helper.wrap(commandDescription, helpWidth, 0),
316
- ""
317
- ]);
318
- }
319
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
320
- return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
321
- });
322
- if (argumentList.length > 0) {
323
- output = output.concat(["Arguments:", formatList(argumentList), ""]);
324
- }
325
- const optionList = helper.visibleOptions(cmd).map((option) => {
326
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
327
- });
328
- if (optionList.length > 0) {
329
- output = output.concat(["Options:", formatList(optionList), ""]);
330
- }
331
- if (this.showGlobalOptions) {
332
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
333
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
334
- });
335
- if (globalOptionList.length > 0) {
336
- output = output.concat([
337
- "Global Options:",
338
- formatList(globalOptionList),
339
- ""
340
- ]);
341
- }
342
- }
343
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
344
- return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
345
- });
346
- if (commandList.length > 0) {
347
- output = output.concat(["Commands:", formatList(commandList), ""]);
348
- }
349
- return output.join(`
350
- `);
351
- }
352
- padWidth(cmd, helper) {
353
- return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
354
- }
355
- wrap(str, width, indent, minColumnWidth = 40) {
356
- const indents = " \\f\\t\\v   -    \uFEFF";
357
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
358
- if (str.match(manualIndent))
359
- return str;
360
- const columnWidth = width - indent;
361
- if (columnWidth < minColumnWidth)
362
- return str;
363
- const leadingStr = str.slice(0, indent);
364
- const columnText = str.slice(indent).replace(`\r
365
- `, `
366
- `);
367
- const indentString = " ".repeat(indent);
368
- const zeroWidthSpace = "​";
369
- const breaks = `\\s${zeroWidthSpace}`;
370
- const regex = new RegExp(`
371
- |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
372
- const lines = columnText.match(regex) || [];
373
- return leadingStr + lines.map((line, i) => {
374
- if (line === `
375
- `)
376
- return "";
377
- return (i > 0 ? indentString : "") + line.trimEnd();
378
- }).join(`
379
- `);
380
- }
381
- }
382
- exports.Help = Help;
383
- });
384
-
385
- // node_modules/commander/lib/option.js
386
- var require_option = __commonJS((exports) => {
387
- var { InvalidArgumentError } = require_error();
388
-
389
- class Option {
390
- constructor(flags, description) {
391
- this.flags = flags;
392
- this.description = description || "";
393
- this.required = flags.includes("<");
394
- this.optional = flags.includes("[");
395
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
396
- this.mandatory = false;
397
- const optionFlags = splitOptionFlags(flags);
398
- this.short = optionFlags.shortFlag;
399
- this.long = optionFlags.longFlag;
400
- this.negate = false;
401
- if (this.long) {
402
- this.negate = this.long.startsWith("--no-");
403
- }
404
- this.defaultValue = undefined;
405
- this.defaultValueDescription = undefined;
406
- this.presetArg = undefined;
407
- this.envVar = undefined;
408
- this.parseArg = undefined;
409
- this.hidden = false;
410
- this.argChoices = undefined;
411
- this.conflictsWith = [];
412
- this.implied = undefined;
413
- }
414
- default(value, description) {
415
- this.defaultValue = value;
416
- this.defaultValueDescription = description;
417
- return this;
418
- }
419
- preset(arg) {
420
- this.presetArg = arg;
421
- return this;
422
- }
423
- conflicts(names) {
424
- this.conflictsWith = this.conflictsWith.concat(names);
425
- return this;
426
- }
427
- implies(impliedOptionValues) {
428
- let newImplied = impliedOptionValues;
429
- if (typeof impliedOptionValues === "string") {
430
- newImplied = { [impliedOptionValues]: true };
431
- }
432
- this.implied = Object.assign(this.implied || {}, newImplied);
433
- return this;
434
- }
435
- env(name) {
436
- this.envVar = name;
437
- return this;
438
- }
439
- argParser(fn) {
440
- this.parseArg = fn;
441
- return this;
442
- }
443
- makeOptionMandatory(mandatory = true) {
444
- this.mandatory = !!mandatory;
445
- return this;
446
- }
447
- hideHelp(hide = true) {
448
- this.hidden = !!hide;
449
- return this;
450
- }
451
- _concatValue(value, previous) {
452
- if (previous === this.defaultValue || !Array.isArray(previous)) {
453
- return [value];
454
- }
455
- return previous.concat(value);
456
- }
457
- choices(values) {
458
- this.argChoices = values.slice();
459
- this.parseArg = (arg, previous) => {
460
- if (!this.argChoices.includes(arg)) {
461
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
462
- }
463
- if (this.variadic) {
464
- return this._concatValue(arg, previous);
465
- }
466
- return arg;
467
- };
468
- return this;
469
- }
470
- name() {
471
- if (this.long) {
472
- return this.long.replace(/^--/, "");
473
- }
474
- return this.short.replace(/^-/, "");
475
- }
476
- attributeName() {
477
- return camelcase(this.name().replace(/^no-/, ""));
478
- }
479
- is(arg) {
480
- return this.short === arg || this.long === arg;
481
- }
482
- isBoolean() {
483
- return !this.required && !this.optional && !this.negate;
484
- }
485
- }
486
-
487
- class DualOptions {
488
- constructor(options) {
489
- this.positiveOptions = new Map;
490
- this.negativeOptions = new Map;
491
- this.dualOptions = new Set;
492
- options.forEach((option) => {
493
- if (option.negate) {
494
- this.negativeOptions.set(option.attributeName(), option);
495
- } else {
496
- this.positiveOptions.set(option.attributeName(), option);
497
- }
498
- });
499
- this.negativeOptions.forEach((value, key) => {
500
- if (this.positiveOptions.has(key)) {
501
- this.dualOptions.add(key);
502
- }
503
- });
504
- }
505
- valueFromOption(value, option) {
506
- const optionKey = option.attributeName();
507
- if (!this.dualOptions.has(optionKey))
508
- return true;
509
- const preset = this.negativeOptions.get(optionKey).presetArg;
510
- const negativeValue = preset !== undefined ? preset : false;
511
- return option.negate === (negativeValue === value);
512
- }
513
- }
514
- function camelcase(str) {
515
- return str.split("-").reduce((str2, word) => {
516
- return str2 + word[0].toUpperCase() + word.slice(1);
517
- });
518
- }
519
- function splitOptionFlags(flags) {
520
- let shortFlag;
521
- let longFlag;
522
- const flagParts = flags.split(/[ |,]+/);
523
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
524
- shortFlag = flagParts.shift();
525
- longFlag = flagParts.shift();
526
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
527
- shortFlag = longFlag;
528
- longFlag = undefined;
529
- }
530
- return { shortFlag, longFlag };
531
- }
532
- exports.Option = Option;
533
- exports.DualOptions = DualOptions;
534
- });
535
-
536
- // node_modules/commander/lib/suggestSimilar.js
537
- var require_suggestSimilar = __commonJS((exports) => {
538
- var maxDistance = 3;
539
- function editDistance(a, b) {
540
- if (Math.abs(a.length - b.length) > maxDistance)
541
- return Math.max(a.length, b.length);
542
- const d = [];
543
- for (let i = 0;i <= a.length; i++) {
544
- d[i] = [i];
545
- }
546
- for (let j = 0;j <= b.length; j++) {
547
- d[0][j] = j;
548
- }
549
- for (let j = 1;j <= b.length; j++) {
550
- for (let i = 1;i <= a.length; i++) {
551
- let cost = 1;
552
- if (a[i - 1] === b[j - 1]) {
553
- cost = 0;
554
- } else {
555
- cost = 1;
556
- }
557
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
558
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
559
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
560
- }
561
- }
562
- }
563
- return d[a.length][b.length];
564
- }
565
- function suggestSimilar(word, candidates) {
566
- if (!candidates || candidates.length === 0)
567
- return "";
568
- candidates = Array.from(new Set(candidates));
569
- const searchingOptions = word.startsWith("--");
570
- if (searchingOptions) {
571
- word = word.slice(2);
572
- candidates = candidates.map((candidate) => candidate.slice(2));
573
- }
574
- let similar = [];
575
- let bestDistance = maxDistance;
576
- const minSimilarity = 0.4;
577
- candidates.forEach((candidate) => {
578
- if (candidate.length <= 1)
579
- return;
580
- const distance = editDistance(word, candidate);
581
- const length = Math.max(word.length, candidate.length);
582
- const similarity = (length - distance) / length;
583
- if (similarity > minSimilarity) {
584
- if (distance < bestDistance) {
585
- bestDistance = distance;
586
- similar = [candidate];
587
- } else if (distance === bestDistance) {
588
- similar.push(candidate);
589
- }
590
- }
591
- });
592
- similar.sort((a, b) => a.localeCompare(b));
593
- if (searchingOptions) {
594
- similar = similar.map((candidate) => `--${candidate}`);
595
- }
596
- if (similar.length > 1) {
597
- return `
598
- (Did you mean one of ${similar.join(", ")}?)`;
599
- }
600
- if (similar.length === 1) {
601
- return `
602
- (Did you mean ${similar[0]}?)`;
603
- }
604
- return "";
605
- }
606
- exports.suggestSimilar = suggestSimilar;
607
- });
608
-
609
- // node_modules/commander/lib/command.js
610
- var require_command = __commonJS((exports) => {
611
- var EventEmitter = __require("node:events").EventEmitter;
612
- var childProcess = __require("node:child_process");
613
- var path = __require("node:path");
614
- var fs = __require("node:fs");
615
- var process = __require("node:process");
616
- var { Argument, humanReadableArgName } = require_argument();
617
- var { CommanderError } = require_error();
618
- var { Help } = require_help();
619
- var { Option, DualOptions } = require_option();
620
- var { suggestSimilar } = require_suggestSimilar();
621
-
622
- class Command extends EventEmitter {
623
- constructor(name) {
624
- super();
625
- this.commands = [];
626
- this.options = [];
627
- this.parent = null;
628
- this._allowUnknownOption = false;
629
- this._allowExcessArguments = true;
630
- this.registeredArguments = [];
631
- this._args = this.registeredArguments;
632
- this.args = [];
633
- this.rawArgs = [];
634
- this.processedArgs = [];
635
- this._scriptPath = null;
636
- this._name = name || "";
637
- this._optionValues = {};
638
- this._optionValueSources = {};
639
- this._storeOptionsAsProperties = false;
640
- this._actionHandler = null;
641
- this._executableHandler = false;
642
- this._executableFile = null;
643
- this._executableDir = null;
644
- this._defaultCommandName = null;
645
- this._exitCallback = null;
646
- this._aliases = [];
647
- this._combineFlagAndOptionalValue = true;
648
- this._description = "";
649
- this._summary = "";
650
- this._argsDescription = undefined;
651
- this._enablePositionalOptions = false;
652
- this._passThroughOptions = false;
653
- this._lifeCycleHooks = {};
654
- this._showHelpAfterError = false;
655
- this._showSuggestionAfterError = true;
656
- this._outputConfiguration = {
657
- writeOut: (str) => process.stdout.write(str),
658
- writeErr: (str) => process.stderr.write(str),
659
- getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
660
- getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
661
- outputError: (str, write) => write(str)
662
- };
663
- this._hidden = false;
664
- this._helpOption = undefined;
665
- this._addImplicitHelpCommand = undefined;
666
- this._helpCommand = undefined;
667
- this._helpConfiguration = {};
668
- }
669
- copyInheritedSettings(sourceCommand) {
670
- this._outputConfiguration = sourceCommand._outputConfiguration;
671
- this._helpOption = sourceCommand._helpOption;
672
- this._helpCommand = sourceCommand._helpCommand;
673
- this._helpConfiguration = sourceCommand._helpConfiguration;
674
- this._exitCallback = sourceCommand._exitCallback;
675
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
676
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
677
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
678
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
679
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
680
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
681
- return this;
682
- }
683
- _getCommandAndAncestors() {
684
- const result = [];
685
- for (let command = this;command; command = command.parent) {
686
- result.push(command);
687
- }
688
- return result;
689
- }
690
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
691
- let desc = actionOptsOrExecDesc;
692
- let opts = execOpts;
693
- if (typeof desc === "object" && desc !== null) {
694
- opts = desc;
695
- desc = null;
696
- }
697
- opts = opts || {};
698
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
699
- const cmd = this.createCommand(name);
700
- if (desc) {
701
- cmd.description(desc);
702
- cmd._executableHandler = true;
703
- }
704
- if (opts.isDefault)
705
- this._defaultCommandName = cmd._name;
706
- cmd._hidden = !!(opts.noHelp || opts.hidden);
707
- cmd._executableFile = opts.executableFile || null;
708
- if (args)
709
- cmd.arguments(args);
710
- this._registerCommand(cmd);
711
- cmd.parent = this;
712
- cmd.copyInheritedSettings(this);
713
- if (desc)
714
- return this;
715
- return cmd;
716
- }
717
- createCommand(name) {
718
- return new Command(name);
719
- }
720
- createHelp() {
721
- return Object.assign(new Help, this.configureHelp());
722
- }
723
- configureHelp(configuration) {
724
- if (configuration === undefined)
725
- return this._helpConfiguration;
726
- this._helpConfiguration = configuration;
727
- return this;
728
- }
729
- configureOutput(configuration) {
730
- if (configuration === undefined)
731
- return this._outputConfiguration;
732
- Object.assign(this._outputConfiguration, configuration);
733
- return this;
734
- }
735
- showHelpAfterError(displayHelp = true) {
736
- if (typeof displayHelp !== "string")
737
- displayHelp = !!displayHelp;
738
- this._showHelpAfterError = displayHelp;
739
- return this;
740
- }
741
- showSuggestionAfterError(displaySuggestion = true) {
742
- this._showSuggestionAfterError = !!displaySuggestion;
743
- return this;
744
- }
745
- addCommand(cmd, opts) {
746
- if (!cmd._name) {
747
- throw new Error(`Command passed to .addCommand() must have a name
748
- - specify the name in Command constructor or using .name()`);
749
- }
750
- opts = opts || {};
751
- if (opts.isDefault)
752
- this._defaultCommandName = cmd._name;
753
- if (opts.noHelp || opts.hidden)
754
- cmd._hidden = true;
755
- this._registerCommand(cmd);
756
- cmd.parent = this;
757
- cmd._checkForBrokenPassThrough();
758
- return this;
759
- }
760
- createArgument(name, description) {
761
- return new Argument(name, description);
762
- }
763
- argument(name, description, fn, defaultValue) {
764
- const argument = this.createArgument(name, description);
765
- if (typeof fn === "function") {
766
- argument.default(defaultValue).argParser(fn);
767
- } else {
768
- argument.default(fn);
769
- }
770
- this.addArgument(argument);
771
- return this;
772
- }
773
- arguments(names) {
774
- names.trim().split(/ +/).forEach((detail) => {
775
- this.argument(detail);
776
- });
777
- return this;
778
- }
779
- addArgument(argument) {
780
- const previousArgument = this.registeredArguments.slice(-1)[0];
781
- if (previousArgument && previousArgument.variadic) {
782
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
783
- }
784
- if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
785
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
786
- }
787
- this.registeredArguments.push(argument);
788
- return this;
789
- }
790
- helpCommand(enableOrNameAndArgs, description) {
791
- if (typeof enableOrNameAndArgs === "boolean") {
792
- this._addImplicitHelpCommand = enableOrNameAndArgs;
793
- return this;
794
- }
795
- enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
796
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
797
- const helpDescription = description ?? "display help for command";
798
- const helpCommand = this.createCommand(helpName);
799
- helpCommand.helpOption(false);
800
- if (helpArgs)
801
- helpCommand.arguments(helpArgs);
802
- if (helpDescription)
803
- helpCommand.description(helpDescription);
804
- this._addImplicitHelpCommand = true;
805
- this._helpCommand = helpCommand;
806
- return this;
807
- }
808
- addHelpCommand(helpCommand, deprecatedDescription) {
809
- if (typeof helpCommand !== "object") {
810
- this.helpCommand(helpCommand, deprecatedDescription);
811
- return this;
812
- }
813
- this._addImplicitHelpCommand = true;
814
- this._helpCommand = helpCommand;
815
- return this;
816
- }
817
- _getHelpCommand() {
818
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
819
- if (hasImplicitHelpCommand) {
820
- if (this._helpCommand === undefined) {
821
- this.helpCommand(undefined, undefined);
822
- }
823
- return this._helpCommand;
824
- }
825
- return null;
826
- }
827
- hook(event, listener) {
828
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
829
- if (!allowedValues.includes(event)) {
830
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
831
- Expecting one of '${allowedValues.join("', '")}'`);
832
- }
833
- if (this._lifeCycleHooks[event]) {
834
- this._lifeCycleHooks[event].push(listener);
835
- } else {
836
- this._lifeCycleHooks[event] = [listener];
837
- }
838
- return this;
839
- }
840
- exitOverride(fn) {
841
- if (fn) {
842
- this._exitCallback = fn;
843
- } else {
844
- this._exitCallback = (err) => {
845
- if (err.code !== "commander.executeSubCommandAsync") {
846
- throw err;
847
- } else {}
848
- };
849
- }
850
- return this;
851
- }
852
- _exit(exitCode, code, message) {
853
- if (this._exitCallback) {
854
- this._exitCallback(new CommanderError(exitCode, code, message));
855
- }
856
- process.exit(exitCode);
857
- }
858
- action(fn) {
859
- const listener = (args) => {
860
- const expectedArgsCount = this.registeredArguments.length;
861
- const actionArgs = args.slice(0, expectedArgsCount);
862
- if (this._storeOptionsAsProperties) {
863
- actionArgs[expectedArgsCount] = this;
864
- } else {
865
- actionArgs[expectedArgsCount] = this.opts();
866
- }
867
- actionArgs.push(this);
868
- return fn.apply(this, actionArgs);
869
- };
870
- this._actionHandler = listener;
871
- return this;
872
- }
873
- createOption(flags, description) {
874
- return new Option(flags, description);
875
- }
876
- _callParseArg(target, value, previous, invalidArgumentMessage) {
877
- try {
878
- return target.parseArg(value, previous);
879
- } catch (err) {
880
- if (err.code === "commander.invalidArgument") {
881
- const message = `${invalidArgumentMessage} ${err.message}`;
882
- this.error(message, { exitCode: err.exitCode, code: err.code });
883
- }
884
- throw err;
885
- }
886
- }
887
- _registerOption(option) {
888
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
889
- if (matchingOption) {
890
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
891
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
892
- - already used by option '${matchingOption.flags}'`);
893
- }
894
- this.options.push(option);
895
- }
896
- _registerCommand(command) {
897
- const knownBy = (cmd) => {
898
- return [cmd.name()].concat(cmd.aliases());
899
- };
900
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
901
- if (alreadyUsed) {
902
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
903
- const newCmd = knownBy(command).join("|");
904
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
905
- }
906
- this.commands.push(command);
907
- }
908
- addOption(option) {
909
- this._registerOption(option);
910
- const oname = option.name();
911
- const name = option.attributeName();
912
- if (option.negate) {
913
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
914
- if (!this._findOption(positiveLongFlag)) {
915
- this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
916
- }
917
- } else if (option.defaultValue !== undefined) {
918
- this.setOptionValueWithSource(name, option.defaultValue, "default");
919
- }
920
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
921
- if (val == null && option.presetArg !== undefined) {
922
- val = option.presetArg;
923
- }
924
- const oldValue = this.getOptionValue(name);
925
- if (val !== null && option.parseArg) {
926
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
927
- } else if (val !== null && option.variadic) {
928
- val = option._concatValue(val, oldValue);
929
- }
930
- if (val == null) {
931
- if (option.negate) {
932
- val = false;
933
- } else if (option.isBoolean() || option.optional) {
934
- val = true;
935
- } else {
936
- val = "";
937
- }
938
- }
939
- this.setOptionValueWithSource(name, val, valueSource);
940
- };
941
- this.on("option:" + oname, (val) => {
942
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
943
- handleOptionValue(val, invalidValueMessage, "cli");
944
- });
945
- if (option.envVar) {
946
- this.on("optionEnv:" + oname, (val) => {
947
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
948
- handleOptionValue(val, invalidValueMessage, "env");
949
- });
950
- }
951
- return this;
952
- }
953
- _optionEx(config, flags, description, fn, defaultValue) {
954
- if (typeof flags === "object" && flags instanceof Option) {
955
- throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
956
- }
957
- const option = this.createOption(flags, description);
958
- option.makeOptionMandatory(!!config.mandatory);
959
- if (typeof fn === "function") {
960
- option.default(defaultValue).argParser(fn);
961
- } else if (fn instanceof RegExp) {
962
- const regex = fn;
963
- fn = (val, def) => {
964
- const m = regex.exec(val);
965
- return m ? m[0] : def;
966
- };
967
- option.default(defaultValue).argParser(fn);
968
- } else {
969
- option.default(fn);
970
- }
971
- return this.addOption(option);
972
- }
973
- option(flags, description, parseArg, defaultValue) {
974
- return this._optionEx({}, flags, description, parseArg, defaultValue);
975
- }
976
- requiredOption(flags, description, parseArg, defaultValue) {
977
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
978
- }
979
- combineFlagAndOptionalValue(combine = true) {
980
- this._combineFlagAndOptionalValue = !!combine;
981
- return this;
982
- }
983
- allowUnknownOption(allowUnknown = true) {
984
- this._allowUnknownOption = !!allowUnknown;
985
- return this;
986
- }
987
- allowExcessArguments(allowExcess = true) {
988
- this._allowExcessArguments = !!allowExcess;
989
- return this;
990
- }
991
- enablePositionalOptions(positional = true) {
992
- this._enablePositionalOptions = !!positional;
993
- return this;
994
- }
995
- passThroughOptions(passThrough = true) {
996
- this._passThroughOptions = !!passThrough;
997
- this._checkForBrokenPassThrough();
998
- return this;
999
- }
1000
- _checkForBrokenPassThrough() {
1001
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1002
- throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1003
- }
1004
- }
1005
- storeOptionsAsProperties(storeAsProperties = true) {
1006
- if (this.options.length) {
1007
- throw new Error("call .storeOptionsAsProperties() before adding options");
1008
- }
1009
- if (Object.keys(this._optionValues).length) {
1010
- throw new Error("call .storeOptionsAsProperties() before setting option values");
1011
- }
1012
- this._storeOptionsAsProperties = !!storeAsProperties;
1013
- return this;
1014
- }
1015
- getOptionValue(key) {
1016
- if (this._storeOptionsAsProperties) {
1017
- return this[key];
1018
- }
1019
- return this._optionValues[key];
1020
- }
1021
- setOptionValue(key, value) {
1022
- return this.setOptionValueWithSource(key, value, undefined);
1023
- }
1024
- setOptionValueWithSource(key, value, source) {
1025
- if (this._storeOptionsAsProperties) {
1026
- this[key] = value;
1027
- } else {
1028
- this._optionValues[key] = value;
1029
- }
1030
- this._optionValueSources[key] = source;
1031
- return this;
1032
- }
1033
- getOptionValueSource(key) {
1034
- return this._optionValueSources[key];
1035
- }
1036
- getOptionValueSourceWithGlobals(key) {
1037
- let source;
1038
- this._getCommandAndAncestors().forEach((cmd) => {
1039
- if (cmd.getOptionValueSource(key) !== undefined) {
1040
- source = cmd.getOptionValueSource(key);
1041
- }
1042
- });
1043
- return source;
1044
- }
1045
- _prepareUserArgs(argv, parseOptions) {
1046
- if (argv !== undefined && !Array.isArray(argv)) {
1047
- throw new Error("first parameter to parse must be array or undefined");
1048
- }
1049
- parseOptions = parseOptions || {};
1050
- if (argv === undefined && parseOptions.from === undefined) {
1051
- if (process.versions?.electron) {
1052
- parseOptions.from = "electron";
1053
- }
1054
- const execArgv = process.execArgv ?? [];
1055
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1056
- parseOptions.from = "eval";
1057
- }
1058
- }
1059
- if (argv === undefined) {
1060
- argv = process.argv;
1061
- }
1062
- this.rawArgs = argv.slice();
1063
- let userArgs;
1064
- switch (parseOptions.from) {
1065
- case undefined:
1066
- case "node":
1067
- this._scriptPath = argv[1];
1068
- userArgs = argv.slice(2);
1069
- break;
1070
- case "electron":
1071
- if (process.defaultApp) {
1072
- this._scriptPath = argv[1];
1073
- userArgs = argv.slice(2);
1074
- } else {
1075
- userArgs = argv.slice(1);
1076
- }
1077
- break;
1078
- case "user":
1079
- userArgs = argv.slice(0);
1080
- break;
1081
- case "eval":
1082
- userArgs = argv.slice(1);
1083
- break;
1084
- default:
1085
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1086
- }
1087
- if (!this._name && this._scriptPath)
1088
- this.nameFromFilename(this._scriptPath);
1089
- this._name = this._name || "program";
1090
- return userArgs;
1091
- }
1092
- parse(argv, parseOptions) {
1093
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1094
- this._parseCommand([], userArgs);
1095
- return this;
1096
- }
1097
- async parseAsync(argv, parseOptions) {
1098
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1099
- await this._parseCommand([], userArgs);
1100
- return this;
1101
- }
1102
- _executeSubCommand(subcommand, args) {
1103
- args = args.slice();
1104
- let launchWithNode = false;
1105
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1106
- function findFile(baseDir, baseName) {
1107
- const localBin = path.resolve(baseDir, baseName);
1108
- if (fs.existsSync(localBin))
1109
- return localBin;
1110
- if (sourceExt.includes(path.extname(baseName)))
1111
- return;
1112
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1113
- if (foundExt)
1114
- return `${localBin}${foundExt}`;
1115
- return;
1116
- }
1117
- this._checkForMissingMandatoryOptions();
1118
- this._checkForConflictingOptions();
1119
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1120
- let executableDir = this._executableDir || "";
1121
- if (this._scriptPath) {
1122
- let resolvedScriptPath;
1123
- try {
1124
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1125
- } catch (err) {
1126
- resolvedScriptPath = this._scriptPath;
1127
- }
1128
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1129
- }
1130
- if (executableDir) {
1131
- let localFile = findFile(executableDir, executableFile);
1132
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1133
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1134
- if (legacyName !== this._name) {
1135
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1136
- }
1137
- }
1138
- executableFile = localFile || executableFile;
1139
- }
1140
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1141
- let proc;
1142
- if (process.platform !== "win32") {
1143
- if (launchWithNode) {
1144
- args.unshift(executableFile);
1145
- args = incrementNodeInspectorPort(process.execArgv).concat(args);
1146
- proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
1147
- } else {
1148
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1149
- }
1150
- } else {
1151
- args.unshift(executableFile);
1152
- args = incrementNodeInspectorPort(process.execArgv).concat(args);
1153
- proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
1154
- }
1155
- if (!proc.killed) {
1156
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1157
- signals.forEach((signal) => {
1158
- process.on(signal, () => {
1159
- if (proc.killed === false && proc.exitCode === null) {
1160
- proc.kill(signal);
1161
- }
1162
- });
1163
- });
1164
- }
1165
- const exitCallback = this._exitCallback;
1166
- proc.on("close", (code) => {
1167
- code = code ?? 1;
1168
- if (!exitCallback) {
1169
- process.exit(code);
1170
- } else {
1171
- exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1172
- }
1173
- });
1174
- proc.on("error", (err) => {
1175
- if (err.code === "ENOENT") {
1176
- 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";
1177
- const executableMissing = `'${executableFile}' does not exist
1178
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1179
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1180
- - ${executableDirMessage}`;
1181
- throw new Error(executableMissing);
1182
- } else if (err.code === "EACCES") {
1183
- throw new Error(`'${executableFile}' not executable`);
1184
- }
1185
- if (!exitCallback) {
1186
- process.exit(1);
1187
- } else {
1188
- const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1189
- wrappedError.nestedError = err;
1190
- exitCallback(wrappedError);
1191
- }
1192
- });
1193
- this.runningCommand = proc;
1194
- }
1195
- _dispatchSubcommand(commandName, operands, unknown) {
1196
- const subCommand = this._findCommand(commandName);
1197
- if (!subCommand)
1198
- this.help({ error: true });
1199
- let promiseChain;
1200
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1201
- promiseChain = this._chainOrCall(promiseChain, () => {
1202
- if (subCommand._executableHandler) {
1203
- this._executeSubCommand(subCommand, operands.concat(unknown));
1204
- } else {
1205
- return subCommand._parseCommand(operands, unknown);
1206
- }
1207
- });
1208
- return promiseChain;
1209
- }
1210
- _dispatchHelpCommand(subcommandName) {
1211
- if (!subcommandName) {
1212
- this.help();
1213
- }
1214
- const subCommand = this._findCommand(subcommandName);
1215
- if (subCommand && !subCommand._executableHandler) {
1216
- subCommand.help();
1217
- }
1218
- return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1219
- }
1220
- _checkNumberOfArguments() {
1221
- this.registeredArguments.forEach((arg, i) => {
1222
- if (arg.required && this.args[i] == null) {
1223
- this.missingArgument(arg.name());
1224
- }
1225
- });
1226
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1227
- return;
1228
- }
1229
- if (this.args.length > this.registeredArguments.length) {
1230
- this._excessArguments(this.args);
1231
- }
1232
- }
1233
- _processArguments() {
1234
- const myParseArg = (argument, value, previous) => {
1235
- let parsedValue = value;
1236
- if (value !== null && argument.parseArg) {
1237
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1238
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1239
- }
1240
- return parsedValue;
1241
- };
1242
- this._checkNumberOfArguments();
1243
- const processedArgs = [];
1244
- this.registeredArguments.forEach((declaredArg, index) => {
1245
- let value = declaredArg.defaultValue;
1246
- if (declaredArg.variadic) {
1247
- if (index < this.args.length) {
1248
- value = this.args.slice(index);
1249
- if (declaredArg.parseArg) {
1250
- value = value.reduce((processed, v) => {
1251
- return myParseArg(declaredArg, v, processed);
1252
- }, declaredArg.defaultValue);
1253
- }
1254
- } else if (value === undefined) {
1255
- value = [];
1256
- }
1257
- } else if (index < this.args.length) {
1258
- value = this.args[index];
1259
- if (declaredArg.parseArg) {
1260
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1261
- }
1262
- }
1263
- processedArgs[index] = value;
1264
- });
1265
- this.processedArgs = processedArgs;
1266
- }
1267
- _chainOrCall(promise, fn) {
1268
- if (promise && promise.then && typeof promise.then === "function") {
1269
- return promise.then(() => fn());
1270
- }
1271
- return fn();
1272
- }
1273
- _chainOrCallHooks(promise, event) {
1274
- let result = promise;
1275
- const hooks = [];
1276
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1277
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1278
- hooks.push({ hookedCommand, callback });
1279
- });
1280
- });
1281
- if (event === "postAction") {
1282
- hooks.reverse();
1283
- }
1284
- hooks.forEach((hookDetail) => {
1285
- result = this._chainOrCall(result, () => {
1286
- return hookDetail.callback(hookDetail.hookedCommand, this);
1287
- });
1288
- });
1289
- return result;
1290
- }
1291
- _chainOrCallSubCommandHook(promise, subCommand, event) {
1292
- let result = promise;
1293
- if (this._lifeCycleHooks[event] !== undefined) {
1294
- this._lifeCycleHooks[event].forEach((hook) => {
1295
- result = this._chainOrCall(result, () => {
1296
- return hook(this, subCommand);
1297
- });
1298
- });
1299
- }
1300
- return result;
1301
- }
1302
- _parseCommand(operands, unknown) {
1303
- const parsed = this.parseOptions(unknown);
1304
- this._parseOptionsEnv();
1305
- this._parseOptionsImplied();
1306
- operands = operands.concat(parsed.operands);
1307
- unknown = parsed.unknown;
1308
- this.args = operands.concat(unknown);
1309
- if (operands && this._findCommand(operands[0])) {
1310
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1311
- }
1312
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1313
- return this._dispatchHelpCommand(operands[1]);
1314
- }
1315
- if (this._defaultCommandName) {
1316
- this._outputHelpIfRequested(unknown);
1317
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1318
- }
1319
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1320
- this.help({ error: true });
1321
- }
1322
- this._outputHelpIfRequested(parsed.unknown);
1323
- this._checkForMissingMandatoryOptions();
1324
- this._checkForConflictingOptions();
1325
- const checkForUnknownOptions = () => {
1326
- if (parsed.unknown.length > 0) {
1327
- this.unknownOption(parsed.unknown[0]);
1328
- }
1329
- };
1330
- const commandEvent = `command:${this.name()}`;
1331
- if (this._actionHandler) {
1332
- checkForUnknownOptions();
1333
- this._processArguments();
1334
- let promiseChain;
1335
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1336
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1337
- if (this.parent) {
1338
- promiseChain = this._chainOrCall(promiseChain, () => {
1339
- this.parent.emit(commandEvent, operands, unknown);
1340
- });
1341
- }
1342
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1343
- return promiseChain;
1344
- }
1345
- if (this.parent && this.parent.listenerCount(commandEvent)) {
1346
- checkForUnknownOptions();
1347
- this._processArguments();
1348
- this.parent.emit(commandEvent, operands, unknown);
1349
- } else if (operands.length) {
1350
- if (this._findCommand("*")) {
1351
- return this._dispatchSubcommand("*", operands, unknown);
1352
- }
1353
- if (this.listenerCount("command:*")) {
1354
- this.emit("command:*", operands, unknown);
1355
- } else if (this.commands.length) {
1356
- this.unknownCommand();
1357
- } else {
1358
- checkForUnknownOptions();
1359
- this._processArguments();
1360
- }
1361
- } else if (this.commands.length) {
1362
- checkForUnknownOptions();
1363
- this.help({ error: true });
1364
- } else {
1365
- checkForUnknownOptions();
1366
- this._processArguments();
1367
- }
1368
- }
1369
- _findCommand(name) {
1370
- if (!name)
1371
- return;
1372
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1373
- }
1374
- _findOption(arg) {
1375
- return this.options.find((option) => option.is(arg));
1376
- }
1377
- _checkForMissingMandatoryOptions() {
1378
- this._getCommandAndAncestors().forEach((cmd) => {
1379
- cmd.options.forEach((anOption) => {
1380
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1381
- cmd.missingMandatoryOptionValue(anOption);
1382
- }
1383
- });
1384
- });
1385
- }
1386
- _checkForConflictingLocalOptions() {
1387
- const definedNonDefaultOptions = this.options.filter((option) => {
1388
- const optionKey = option.attributeName();
1389
- if (this.getOptionValue(optionKey) === undefined) {
1390
- return false;
1391
- }
1392
- return this.getOptionValueSource(optionKey) !== "default";
1393
- });
1394
- const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1395
- optionsWithConflicting.forEach((option) => {
1396
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1397
- if (conflictingAndDefined) {
1398
- this._conflictingOption(option, conflictingAndDefined);
1399
- }
1400
- });
1401
- }
1402
- _checkForConflictingOptions() {
1403
- this._getCommandAndAncestors().forEach((cmd) => {
1404
- cmd._checkForConflictingLocalOptions();
1405
- });
1406
- }
1407
- parseOptions(argv) {
1408
- const operands = [];
1409
- const unknown = [];
1410
- let dest = operands;
1411
- const args = argv.slice();
1412
- function maybeOption(arg) {
1413
- return arg.length > 1 && arg[0] === "-";
1414
- }
1415
- let activeVariadicOption = null;
1416
- while (args.length) {
1417
- const arg = args.shift();
1418
- if (arg === "--") {
1419
- if (dest === unknown)
1420
- dest.push(arg);
1421
- dest.push(...args);
1422
- break;
1423
- }
1424
- if (activeVariadicOption && !maybeOption(arg)) {
1425
- this.emit(`option:${activeVariadicOption.name()}`, arg);
1426
- continue;
1427
- }
1428
- activeVariadicOption = null;
1429
- if (maybeOption(arg)) {
1430
- const option = this._findOption(arg);
1431
- if (option) {
1432
- if (option.required) {
1433
- const value = args.shift();
1434
- if (value === undefined)
1435
- this.optionMissingArgument(option);
1436
- this.emit(`option:${option.name()}`, value);
1437
- } else if (option.optional) {
1438
- let value = null;
1439
- if (args.length > 0 && !maybeOption(args[0])) {
1440
- value = args.shift();
1441
- }
1442
- this.emit(`option:${option.name()}`, value);
1443
- } else {
1444
- this.emit(`option:${option.name()}`);
1445
- }
1446
- activeVariadicOption = option.variadic ? option : null;
1447
- continue;
1448
- }
1449
- }
1450
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1451
- const option = this._findOption(`-${arg[1]}`);
1452
- if (option) {
1453
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1454
- this.emit(`option:${option.name()}`, arg.slice(2));
1455
- } else {
1456
- this.emit(`option:${option.name()}`);
1457
- args.unshift(`-${arg.slice(2)}`);
1458
- }
1459
- continue;
1460
- }
1461
- }
1462
- if (/^--[^=]+=/.test(arg)) {
1463
- const index = arg.indexOf("=");
1464
- const option = this._findOption(arg.slice(0, index));
1465
- if (option && (option.required || option.optional)) {
1466
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
1467
- continue;
1468
- }
1469
- }
1470
- if (maybeOption(arg)) {
1471
- dest = unknown;
1472
- }
1473
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1474
- if (this._findCommand(arg)) {
1475
- operands.push(arg);
1476
- if (args.length > 0)
1477
- unknown.push(...args);
1478
- break;
1479
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1480
- operands.push(arg);
1481
- if (args.length > 0)
1482
- operands.push(...args);
1483
- break;
1484
- } else if (this._defaultCommandName) {
1485
- unknown.push(arg);
1486
- if (args.length > 0)
1487
- unknown.push(...args);
1488
- break;
1489
- }
1490
- }
1491
- if (this._passThroughOptions) {
1492
- dest.push(arg);
1493
- if (args.length > 0)
1494
- dest.push(...args);
1495
- break;
1496
- }
1497
- dest.push(arg);
1498
- }
1499
- return { operands, unknown };
1500
- }
1501
- opts() {
1502
- if (this._storeOptionsAsProperties) {
1503
- const result = {};
1504
- const len = this.options.length;
1505
- for (let i = 0;i < len; i++) {
1506
- const key = this.options[i].attributeName();
1507
- result[key] = key === this._versionOptionName ? this._version : this[key];
1508
- }
1509
- return result;
1510
- }
1511
- return this._optionValues;
1512
- }
1513
- optsWithGlobals() {
1514
- return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1515
- }
1516
- error(message, errorOptions) {
1517
- this._outputConfiguration.outputError(`${message}
1518
- `, this._outputConfiguration.writeErr);
1519
- if (typeof this._showHelpAfterError === "string") {
1520
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1521
- `);
1522
- } else if (this._showHelpAfterError) {
1523
- this._outputConfiguration.writeErr(`
1524
- `);
1525
- this.outputHelp({ error: true });
1526
- }
1527
- const config = errorOptions || {};
1528
- const exitCode = config.exitCode || 1;
1529
- const code = config.code || "commander.error";
1530
- this._exit(exitCode, code, message);
1531
- }
1532
- _parseOptionsEnv() {
1533
- this.options.forEach((option) => {
1534
- if (option.envVar && option.envVar in process.env) {
1535
- const optionKey = option.attributeName();
1536
- if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1537
- if (option.required || option.optional) {
1538
- this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1539
- } else {
1540
- this.emit(`optionEnv:${option.name()}`);
1541
- }
1542
- }
1543
- }
1544
- });
1545
- }
1546
- _parseOptionsImplied() {
1547
- const dualHelper = new DualOptions(this.options);
1548
- const hasCustomOptionValue = (optionKey) => {
1549
- return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1550
- };
1551
- this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1552
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1553
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1554
- });
1555
- });
1556
- }
1557
- missingArgument(name) {
1558
- const message = `error: missing required argument '${name}'`;
1559
- this.error(message, { code: "commander.missingArgument" });
1560
- }
1561
- optionMissingArgument(option) {
1562
- const message = `error: option '${option.flags}' argument missing`;
1563
- this.error(message, { code: "commander.optionMissingArgument" });
1564
- }
1565
- missingMandatoryOptionValue(option) {
1566
- const message = `error: required option '${option.flags}' not specified`;
1567
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
1568
- }
1569
- _conflictingOption(option, conflictingOption) {
1570
- const findBestOptionFromValue = (option2) => {
1571
- const optionKey = option2.attributeName();
1572
- const optionValue = this.getOptionValue(optionKey);
1573
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1574
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1575
- if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1576
- return negativeOption;
1577
- }
1578
- return positiveOption || option2;
1579
- };
1580
- const getErrorMessage = (option2) => {
1581
- const bestOption = findBestOptionFromValue(option2);
1582
- const optionKey = bestOption.attributeName();
1583
- const source = this.getOptionValueSource(optionKey);
1584
- if (source === "env") {
1585
- return `environment variable '${bestOption.envVar}'`;
1586
- }
1587
- return `option '${bestOption.flags}'`;
1588
- };
1589
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1590
- this.error(message, { code: "commander.conflictingOption" });
1591
- }
1592
- unknownOption(flag) {
1593
- if (this._allowUnknownOption)
1594
- return;
1595
- let suggestion = "";
1596
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
1597
- let candidateFlags = [];
1598
- let command = this;
1599
- do {
1600
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1601
- candidateFlags = candidateFlags.concat(moreFlags);
1602
- command = command.parent;
1603
- } while (command && !command._enablePositionalOptions);
1604
- suggestion = suggestSimilar(flag, candidateFlags);
1605
- }
1606
- const message = `error: unknown option '${flag}'${suggestion}`;
1607
- this.error(message, { code: "commander.unknownOption" });
1608
- }
1609
- _excessArguments(receivedArgs) {
1610
- if (this._allowExcessArguments)
1611
- return;
1612
- const expected = this.registeredArguments.length;
1613
- const s = expected === 1 ? "" : "s";
1614
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1615
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1616
- this.error(message, { code: "commander.excessArguments" });
1617
- }
1618
- unknownCommand() {
1619
- const unknownName = this.args[0];
1620
- let suggestion = "";
1621
- if (this._showSuggestionAfterError) {
1622
- const candidateNames = [];
1623
- this.createHelp().visibleCommands(this).forEach((command) => {
1624
- candidateNames.push(command.name());
1625
- if (command.alias())
1626
- candidateNames.push(command.alias());
1627
- });
1628
- suggestion = suggestSimilar(unknownName, candidateNames);
1629
- }
1630
- const message = `error: unknown command '${unknownName}'${suggestion}`;
1631
- this.error(message, { code: "commander.unknownCommand" });
1632
- }
1633
- version(str, flags, description) {
1634
- if (str === undefined)
1635
- return this._version;
1636
- this._version = str;
1637
- flags = flags || "-V, --version";
1638
- description = description || "output the version number";
1639
- const versionOption = this.createOption(flags, description);
1640
- this._versionOptionName = versionOption.attributeName();
1641
- this._registerOption(versionOption);
1642
- this.on("option:" + versionOption.name(), () => {
1643
- this._outputConfiguration.writeOut(`${str}
1644
- `);
1645
- this._exit(0, "commander.version", str);
1646
- });
1647
- return this;
1648
- }
1649
- description(str, argsDescription) {
1650
- if (str === undefined && argsDescription === undefined)
1651
- return this._description;
1652
- this._description = str;
1653
- if (argsDescription) {
1654
- this._argsDescription = argsDescription;
1655
- }
1656
- return this;
1657
- }
1658
- summary(str) {
1659
- if (str === undefined)
1660
- return this._summary;
1661
- this._summary = str;
1662
- return this;
1663
- }
1664
- alias(alias) {
1665
- if (alias === undefined)
1666
- return this._aliases[0];
1667
- let command = this;
1668
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1669
- command = this.commands[this.commands.length - 1];
1670
- }
1671
- if (alias === command._name)
1672
- throw new Error("Command alias can't be the same as its name");
1673
- const matchingCommand = this.parent?._findCommand(alias);
1674
- if (matchingCommand) {
1675
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1676
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1677
- }
1678
- command._aliases.push(alias);
1679
- return this;
1680
- }
1681
- aliases(aliases) {
1682
- if (aliases === undefined)
1683
- return this._aliases;
1684
- aliases.forEach((alias) => this.alias(alias));
1685
- return this;
1686
- }
1687
- usage(str) {
1688
- if (str === undefined) {
1689
- if (this._usage)
1690
- return this._usage;
1691
- const args = this.registeredArguments.map((arg) => {
1692
- return humanReadableArgName(arg);
1693
- });
1694
- return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1695
- }
1696
- this._usage = str;
1697
- return this;
1698
- }
1699
- name(str) {
1700
- if (str === undefined)
1701
- return this._name;
1702
- this._name = str;
1703
- return this;
1704
- }
1705
- nameFromFilename(filename) {
1706
- this._name = path.basename(filename, path.extname(filename));
1707
- return this;
1708
- }
1709
- executableDir(path2) {
1710
- if (path2 === undefined)
1711
- return this._executableDir;
1712
- this._executableDir = path2;
1713
- return this;
1714
- }
1715
- helpInformation(contextOptions) {
1716
- const helper = this.createHelp();
1717
- if (helper.helpWidth === undefined) {
1718
- helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1719
- }
1720
- return helper.formatHelp(this, helper);
1721
- }
1722
- _getHelpContext(contextOptions) {
1723
- contextOptions = contextOptions || {};
1724
- const context = { error: !!contextOptions.error };
1725
- let write;
1726
- if (context.error) {
1727
- write = (arg) => this._outputConfiguration.writeErr(arg);
1728
- } else {
1729
- write = (arg) => this._outputConfiguration.writeOut(arg);
1730
- }
1731
- context.write = contextOptions.write || write;
1732
- context.command = this;
1733
- return context;
1734
- }
1735
- outputHelp(contextOptions) {
1736
- let deprecatedCallback;
1737
- if (typeof contextOptions === "function") {
1738
- deprecatedCallback = contextOptions;
1739
- contextOptions = undefined;
1740
- }
1741
- const context = this._getHelpContext(contextOptions);
1742
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
1743
- this.emit("beforeHelp", context);
1744
- let helpInformation = this.helpInformation(context);
1745
- if (deprecatedCallback) {
1746
- helpInformation = deprecatedCallback(helpInformation);
1747
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1748
- throw new Error("outputHelp callback must return a string or a Buffer");
1749
- }
1750
- }
1751
- context.write(helpInformation);
1752
- if (this._getHelpOption()?.long) {
1753
- this.emit(this._getHelpOption().long);
1754
- }
1755
- this.emit("afterHelp", context);
1756
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
1757
- }
1758
- helpOption(flags, description) {
1759
- if (typeof flags === "boolean") {
1760
- if (flags) {
1761
- this._helpOption = this._helpOption ?? undefined;
1762
- } else {
1763
- this._helpOption = null;
1764
- }
1765
- return this;
1766
- }
1767
- flags = flags ?? "-h, --help";
1768
- description = description ?? "display help for command";
1769
- this._helpOption = this.createOption(flags, description);
1770
- return this;
1771
- }
1772
- _getHelpOption() {
1773
- if (this._helpOption === undefined) {
1774
- this.helpOption(undefined, undefined);
1775
- }
1776
- return this._helpOption;
1777
- }
1778
- addHelpOption(option) {
1779
- this._helpOption = option;
1780
- return this;
1781
- }
1782
- help(contextOptions) {
1783
- this.outputHelp(contextOptions);
1784
- let exitCode = process.exitCode || 0;
1785
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1786
- exitCode = 1;
1787
- }
1788
- this._exit(exitCode, "commander.help", "(outputHelp)");
1789
- }
1790
- addHelpText(position, text) {
1791
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1792
- if (!allowedValues.includes(position)) {
1793
- throw new Error(`Unexpected value for position to addHelpText.
1794
- Expecting one of '${allowedValues.join("', '")}'`);
1795
- }
1796
- const helpEvent = `${position}Help`;
1797
- this.on(helpEvent, (context) => {
1798
- let helpStr;
1799
- if (typeof text === "function") {
1800
- helpStr = text({ error: context.error, command: context.command });
1801
- } else {
1802
- helpStr = text;
1803
- }
1804
- if (helpStr) {
1805
- context.write(`${helpStr}
1806
- `);
1807
- }
1808
- });
1809
- return this;
1810
- }
1811
- _outputHelpIfRequested(args) {
1812
- const helpOption = this._getHelpOption();
1813
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1814
- if (helpRequested) {
1815
- this.outputHelp();
1816
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1817
- }
1818
- }
1819
- }
1820
- function incrementNodeInspectorPort(args) {
1821
- return args.map((arg) => {
1822
- if (!arg.startsWith("--inspect")) {
1823
- return arg;
1824
- }
1825
- let debugOption;
1826
- let debugHost = "127.0.0.1";
1827
- let debugPort = "9229";
1828
- let match;
1829
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
1830
- debugOption = match[1];
1831
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
1832
- debugOption = match[1];
1833
- if (/^\d+$/.test(match[3])) {
1834
- debugPort = match[3];
1835
- } else {
1836
- debugHost = match[3];
1837
- }
1838
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
1839
- debugOption = match[1];
1840
- debugHost = match[3];
1841
- debugPort = match[4];
1842
- }
1843
- if (debugOption && debugPort !== "0") {
1844
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
1845
- }
1846
- return arg;
1847
- });
1848
- }
1849
- exports.Command = Command;
1850
- });
1851
-
1852
- // node_modules/commander/index.js
1853
- var require_commander = __commonJS((exports) => {
1854
- var { Argument } = require_argument();
1855
- var { Command } = require_command();
1856
- var { CommanderError, InvalidArgumentError } = require_error();
1857
- var { Help } = require_help();
1858
- var { Option } = require_option();
1859
- exports.program = new Command;
1860
- exports.createCommand = (name) => new Command(name);
1861
- exports.createOption = (flags, description) => new Option(flags, description);
1862
- exports.createArgument = (name, description) => new Argument(name, description);
1863
- exports.Command = Command;
1864
- exports.Option = Option;
1865
- exports.Argument = Argument;
1866
- exports.Help = Help;
1867
- exports.CommanderError = CommanderError;
1868
- exports.InvalidArgumentError = InvalidArgumentError;
1869
- exports.InvalidOptionArgumentError = InvalidArgumentError;
1870
- });
1871
-
1872
- // node_modules/commander/esm.mjs
1873
- var import__ = __toESM(require_commander(), 1);
1874
- var {
1875
- program,
1876
- createCommand,
1877
- createArgument,
1878
- createOption,
1879
- CommanderError,
1880
- InvalidArgumentError,
1881
- InvalidOptionArgumentError,
1882
- Command,
1883
- Argument,
1884
- Option,
1885
- Help
1886
- } = import__.default;
1887
-
1888
- // cli.ts
1889
- import fs from "fs";
1890
- import path from "path";
1891
- import { fileURLToPath } from "url";
1892
- var __dirname2 = path.dirname(fileURLToPath(import.meta.url));
1893
- program.name("mcp2service").description("MCP\u4EE3\u7406\u670D\u52A1\u811A\u624B\u67B6\u5DE5\u5177").version("1.0.0");
1894
- program.command("init").description("\u521D\u59CB\u5316\u65B0\u7684MCP\u4EE3\u7406\u670D\u52A1\u9879\u76EE").argument("[directory]", "\u9879\u76EE\u76EE\u5F55", ".").option("-t, --typescript", "\u4F7F\u7528TypeScript\uFF08\u9ED8\u8BA4\uFF09", true).option("-j, --javascript", "\u4F7F\u7528JavaScript").option("--skip-install", "\u8DF3\u8FC7\u4F9D\u8D56\u5B89\u88C5").action(async (directory, options) => {
1895
- console.log(`\u521D\u59CB\u5316MCP\u4EE3\u7406\u670D\u52A1\u9879\u76EE\u5230 ${directory}...`);
1896
- const projectPath = path.resolve(directory);
1897
- const useTypeScript = !options.javascript;
1898
- const dirs = [
1899
- "adapters",
1900
- "config",
1901
- "src",
1902
- "examples"
1903
- ];
1904
- for (const dir of dirs) {
1905
- const dirPath = path.join(projectPath, dir);
1906
- if (!fs.existsSync(dirPath)) {
1907
- fs.mkdirSync(dirPath, { recursive: true });
1908
- }
1909
- }
1910
- const configContent = `name: my-mcp-service
1911
- version: 1.0.0
1912
- transport:
1913
- httpStream:
1914
- port: 3000
1915
- endpoint: /mcp
1916
-
1917
- tools:
1918
- example-http:
1919
- type: http
1920
- description: \u793A\u4F8BHTTP\u5DE5\u5177
1921
- params: {}
1922
- options:
1923
- url: https://api.example.com/data
1924
- method: GET
1925
- headers:
1926
- Content-Type: application/json
1927
-
1928
- example-graphql:
1929
- type: graphql
1930
- description: \u793A\u4F8BGraphQL\u5DE5\u5177
1931
- params:
1932
- query:
1933
- type: string
1934
- description: GraphQL\u67E5\u8BE2\u8BED\u53E5
1935
- options:
1936
- endpoint: https://api.example.com/graphql
1937
- headers:
1938
- Authorization: Bearer \${TOKEN}
1939
-
1940
- adapters:
1941
- http:
1942
- timeout: 10000
1943
- retry:
1944
- attempts: 3
1945
- backoff: 1000
1946
- `;
1947
- const configPath = path.join(projectPath, "config", "default.yaml");
1948
- fs.writeFileSync(configPath, configContent);
1949
- const entryContent = useTypeScript ? `import { McpProxy } from 'mcp2service';
1950
- import { loadConfig } from './config/loader';
1951
-
1952
- async function main() {
1953
- try {
1954
- const config = await loadConfig();
1955
- const proxy = new McpProxy(config);
1956
-
1957
- await proxy.start();
1958
-
1959
- console.log(\`MCP\u4EE3\u7406\u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u7AEF\u53E3: \${config.transport?.httpStream?.port}\`);
1960
- console.log('\u53EF\u7528\u5DE5\u5177:', Object.keys(config.tools));
1961
- } catch (error) {
1962
- console.error('\u542F\u52A8\u5931\u8D25:', error);
1963
- process.exit(1);
1964
- }
1965
- }
1966
-
1967
- if (require.main === module) {
1968
- main();
1969
- }
1970
- ` : `const { McpProxy } = require('mcp2service');
1971
- const { loadConfig } = require('./config/loader');
1972
-
1973
- async function main() {
1974
- try {
1975
- const config = await loadConfig();
1976
- const proxy = new McpProxy(config);
1977
-
1978
- await proxy.start();
1979
-
1980
- console.log(\`MCP\u4EE3\u7406\u670D\u52A1\u542F\u52A8\u6210\u529F\uFF0C\u7AEF\u53E3: \${config.transport?.httpStream?.port}\`);
1981
- console.log('\u53EF\u7528\u5DE5\u5177:', Object.keys(config.tools));
1982
- } catch (error) {
1983
- console.error('\u542F\u52A8\u5931\u8D25:', error);
1984
- process.exit(1);
1985
- }
1986
- }
1987
-
1988
- if (require.main === module) {
1989
- main();
1990
- }
1991
- `;
1992
- const entryFileName = useTypeScript ? "index.ts" : "index.js";
1993
- const entryPath = path.join(projectPath, "src", entryFileName);
1994
- fs.writeFileSync(entryPath, entryContent);
1995
- const loaderContent = useTypeScript ? `import fs from 'fs';
1996
- import path from 'path';
1997
- import yaml from 'yaml';
1998
- import { mcpOptionsSchema } from 'mcp2service';
1999
-
2000
- export async function loadConfig(configPath?: string): Promise<any> {
2001
- const configFile = configPath || path.join(__dirname, '..', 'config', 'default.yaml');
2002
-
2003
- if (!fs.existsSync(configFile)) {
2004
- throw new Error(\`\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728: \${configFile}\`);
2005
- }
2006
-
2007
- const content = fs.readFileSync(configFile, 'utf-8');
2008
- const config = yaml.parse(content);
2009
-
2010
- // \u73AF\u5883\u53D8\u91CF\u66FF\u6362
2011
- const processedConfig = replaceEnvVars(config);
2012
-
2013
- return processedConfig;
2014
- }
2015
-
2016
- function replaceEnvVars(obj: any): any {
2017
- if (typeof obj === 'string') {
2018
- return obj.replace(/\\$\\{([^}]+)\\}/g, (match, key) => {
2019
- return process.env[key] || match;
2020
- });
2021
- }
2022
-
2023
- if (Array.isArray(obj)) {
2024
- return obj.map(item => replaceEnvVars(item));
2025
- }
2026
-
2027
- if (typeof obj === 'object' && obj !== null) {
2028
- const result: any = {};
2029
- for (const [key, value] of Object.entries(obj)) {
2030
- result[key] = replaceEnvVars(value);
2031
- }
2032
- return result;
2033
- }
2034
-
2035
- return obj;
2036
- }
2037
- ` : `const fs = require('fs');
2038
- const path = require('path');
2039
- const yaml = require('yaml');
2040
- const { mcpOptionsSchema } = require('mcp2service');
2041
-
2042
- async function loadConfig(configPath) {
2043
- const configFile = configPath || path.join(__dirname, '..', 'config', 'default.yaml');
2044
-
2045
- if (!fs.existsSync(configFile)) {
2046
- throw new Error(\`\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728: \${configFile}\`);
2047
- }
2048
-
2049
- const content = fs.readFileSync(configFile, 'utf-8');
2050
- const config = yaml.parse(content);
2051
-
2052
- // \u73AF\u5883\u53D8\u91CF\u66FF\u6362
2053
- const processedConfig = replaceEnvVars(config);
2054
-
2055
- return processedConfig;
2056
- }
2057
-
2058
- function replaceEnvVars(obj) {
2059
- if (typeof obj === 'string') {
2060
- return obj.replace(/\\$\\{([^}]+)\\}/g, (match, key) => {
2061
- return process.env[key] || match;
2062
- });
2063
- }
2064
-
2065
- if (Array.isArray(obj)) {
2066
- return obj.map(item => replaceEnvVars(item));
2067
- }
2068
-
2069
- if (typeof obj === 'object' && obj !== null) {
2070
- const result = {};
2071
- for (const [key, value] of Object.entries(obj)) {
2072
- result[key] = replaceEnvVars(value);
2073
- }
2074
- return result;
2075
- }
2076
-
2077
- return obj;
2078
- }
2079
-
2080
- module.exports = { loadConfig };
2081
- `;
2082
- const loaderFileName = useTypeScript ? "loader.ts" : "loader.js";
2083
- const loaderPath = path.join(projectPath, "config", loaderFileName);
2084
- fs.writeFileSync(loaderPath, loaderContent);
2085
- const packageJson = {
2086
- name: "my-mcp-service",
2087
- version: "1.0.0",
2088
- type: "module",
2089
- main: `src/${useTypeScript ? "index.ts" : "index.js"}`,
2090
- scripts: {
2091
- start: useTypeScript ? "bun run src/index.ts" : "bun src/index.js",
2092
- dev: useTypeScript ? "bun --watch src/index.ts" : "bun --watch src/index.js",
2093
- build: useTypeScript ? "bun build src/index.ts --outdir dist" : 'echo "No build needed for JavaScript"'
2094
- },
2095
- dependencies: {
2096
- mcp2service: "^1.0.0",
2097
- yaml: "^2.0.0"
2098
- },
2099
- devDependencies: useTypeScript ? {
2100
- "@types/bun": "latest",
2101
- "@types/node": "latest",
2102
- typescript: "^5.0.0"
2103
- } : {}
2104
- };
2105
- const packageJsonPath = path.join(projectPath, "package.json");
2106
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
2107
- const readmeContent = `# MCP\u4EE3\u7406\u670D\u52A1\u9879\u76EE
2108
-
2109
- \u57FA\u4E8Emcp2service\u6784\u5EFA\u7684Model Context Protocol\u4EE3\u7406\u670D\u52A1\u3002
2110
-
2111
- ## \u5FEB\u901F\u5F00\u59CB
2112
-
2113
- 1. \u5B89\u88C5\u4F9D\u8D56\uFF1A
2114
- \`\`\`bash
2115
- bun install
2116
- \`\`\`
2117
-
2118
- 2. \u914D\u7F6E\u73AF\u5883\u53D8\u91CF\uFF1A
2119
- \`\`\`bash
2120
- # \u590D\u5236\u793A\u4F8B\u73AF\u5883\u53D8\u91CF\u6587\u4EF6
2121
- cp .env.example .env
2122
-
2123
- # \u7F16\u8F91.env\u6587\u4EF6\uFF0C\u8BBE\u7F6E\u5FC5\u8981\u7684\u73AF\u5883\u53D8\u91CF
2124
- \`\`\`
2125
-
2126
- 3. \u542F\u52A8\u670D\u52A1\uFF1A
2127
- \`\`\`bash
2128
- bun start
2129
- \`\`\`
2130
-
2131
- ## \u9879\u76EE\u7ED3\u6784
2132
-
2133
- - \`config/default.yaml\` - \u4E3B\u914D\u7F6E\u6587\u4EF6
2134
- - \`src/index.${useTypeScript ? "ts" : "js"}\` - \u670D\u52A1\u5165\u53E3\u70B9
2135
- - \`config/loader.${useTypeScript ? "ts" : "js"}\` - \u914D\u7F6E\u52A0\u8F7D\u5668
2136
- - \`adapters/\` - \u81EA\u5B9A\u4E49\u9002\u914D\u5668\u76EE\u5F55
2137
- - \`examples/\` - \u793A\u4F8B\u6587\u4EF6
2138
-
2139
- ## \u914D\u7F6E\u8BF4\u660E
2140
-
2141
- \u7F16\u8F91 \`config/default.yaml\` \u6587\u4EF6\u4EE5\u6DFB\u52A0\u6216\u4FEE\u6539\u5DE5\u5177\u914D\u7F6E\u3002
2142
-
2143
- \u6BCF\u4E2A\u5DE5\u5177\u9700\u8981\u6307\u5B9A\uFF1A
2144
- - \`type\`: \u9002\u914D\u5668\u7C7B\u578B (http, graphql, grpc)
2145
- - \`description\`: \u5DE5\u5177\u63CF\u8FF0
2146
- - \`params\`: \u5DE5\u5177\u53C2\u6570\u5B9A\u4E49
2147
- - \`options\`: \u9002\u914D\u5668\u7279\u5B9A\u914D\u7F6E
2148
-
2149
- ## \u81EA\u5B9A\u4E49\u9002\u914D\u5668
2150
-
2151
- \u5728 \`adapters/\` \u76EE\u5F55\u4E2D\u521B\u5EFA\u65B0\u7684\u9002\u914D\u5668\uFF0C\u5B9E\u73B0 \`ServiceAdapter\` \u63A5\u53E3\u3002
2152
-
2153
- ## \u6587\u6863
2154
-
2155
- - [mcp2service\u6587\u6863](https://github.com/your-org/mcp2service)
2156
- - [MCP\u534F\u8BAE\u6587\u6863](https://spec.modelcontextprotocol.io)
2157
- `;
2158
- const readmePath = path.join(projectPath, "README.md");
2159
- fs.writeFileSync(readmePath, readmeContent);
2160
- const envExampleContent = `# MCP\u4EE3\u7406\u670D\u52A1\u73AF\u5883\u53D8\u91CF
2161
- TOKEN=your-api-token-here
2162
- API_KEY=your-api-key-here
2163
- DATABASE_URL=postgresql://user:password@localhost:5432/dbname
2164
- `;
2165
- const envExamplePath = path.join(projectPath, ".env.example");
2166
- fs.writeFileSync(envExamplePath, envExampleContent);
2167
- if (useTypeScript) {
2168
- const tsconfigContent = {
2169
- compilerOptions: {
2170
- target: "ES2022",
2171
- module: "ESNext",
2172
- moduleResolution: "bundler",
2173
- types: ["bun"],
2174
- esModuleInterop: true,
2175
- forceConsistentCasingInFileNames: true,
2176
- strict: true,
2177
- skipLibCheck: true,
2178
- outDir: "./dist",
2179
- rootDir: "./src"
2180
- },
2181
- include: ["src/**/*"],
2182
- exclude: ["node_modules", "dist"]
2183
- };
2184
- const tsconfigPath = path.join(projectPath, "tsconfig.json");
2185
- fs.writeFileSync(tsconfigPath, JSON.stringify(tsconfigContent, null, 2));
2186
- }
2187
- console.log("\u2705 \u9879\u76EE\u521D\u59CB\u5316\u5B8C\u6210\uFF01");
2188
- console.log(`
2189
- \u4E0B\u4E00\u6B65\uFF1A`);
2190
- console.log(` cd ${directory}`);
2191
- if (!options.skipInstall) {
2192
- console.log(" bun install");
2193
- }
2194
- console.log(" \u7F16\u8F91 config/default.yaml \u914D\u7F6E\u6587\u4EF6");
2195
- console.log(" \u8BBE\u7F6E\u5FC5\u8981\u7684\u73AF\u5883\u53D8\u91CF");
2196
- console.log(" bun start \u542F\u52A8\u670D\u52A1");
2197
- });
2198
- program.command("generate:adapter").description("\u751F\u6210\u65B0\u7684\u9002\u914D\u5668\u6A21\u677F").argument("<name>", "\u9002\u914D\u5668\u540D\u79F0").option("-t, --typescript", "\u4F7F\u7528TypeScript\uFF08\u9ED8\u8BA4\uFF09", true).option("-j, --javascript", "\u4F7F\u7528JavaScript").action((name, options) => {
2199
- const useTypeScript = !options.javascript;
2200
- const adapterName = name.charAt(0).toUpperCase() + name.slice(1) + "Adapter";
2201
- const fileName = `${name}.${useTypeScript ? "ts" : "js"}`;
2202
- const adapterContent = useTypeScript ? `import type { AudioContent, ContentResult, Context, ImageContent, ResourceContent, ResourceLink, TextContent } from 'fastmcp';
2203
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2204
- import type { ServiceAdapter } from 'mcp2service';
2205
- import { validate } from 'mcp2service';
2206
- import { AdapterError } from 'mcp2service';
2207
- import { z } from 'zod';
2208
-
2209
- // ${adapterName}\u914D\u7F6E\u9A8C\u8BC1
2210
- export const ${name}AdapterConfigSchema = z.object({
2211
- // TODO: \u6DFB\u52A0\u914D\u7F6E\u9A8C\u8BC1\u89C4\u5219
2212
- endpoint: z.string().url('Valid endpoint URL is required'),
2213
- timeout: z.number().int().positive().optional(),
2214
- });
2215
-
2216
- export type ${adapterName}Config = z.infer<typeof ${name}AdapterConfigSchema>;
2217
-
2218
- export class ${adapterName} implements ServiceAdapter {
2219
- private adapterConfig: ${adapterName}Config | null = null;
2220
-
2221
- config(options: Record<string, any>): void {
2222
- this.adapterConfig = validate(${name}AdapterConfigSchema, options, '${adapterName} configuration');
2223
- }
2224
-
2225
- async call(
2226
- args: StandardSchemaV1.InferOutput<any>,
2227
- context: Context<any>
2228
- ): Promise<AudioContent | ContentResult | ImageContent | ResourceContent | ResourceLink | string | TextContent | void> {
2229
- if (!this.adapterConfig) {
2230
- throw new AdapterError('${adapterName} not configured', '${name}');
2231
- }
2232
-
2233
- // TODO: \u5B9E\u73B0\u9002\u914D\u5668\u903B\u8F91
2234
- throw new Error('Not implemented');
2235
- }
2236
- }
2237
- ` : `const { validate } = require('mcp2service');
2238
- const { AdapterError } = require('mcp2service');
2239
- const { z } = require('zod');
2240
-
2241
- // ${adapterName}\u914D\u7F6E\u9A8C\u8BC1
2242
- const ${name}AdapterConfigSchema = z.object({
2243
- // TODO: \u6DFB\u52A0\u914D\u7F6E\u9A8C\u8BC1\u89C4\u5219
2244
- endpoint: z.string().url('Valid endpoint URL is required'),
2245
- timeout: z.number().int().positive().optional(),
2246
- });
2247
-
2248
- class ${adapterName} {
2249
- constructor() {
2250
- this.adapterConfig = null;
2251
- }
2252
-
2253
- config(options) {
2254
- this.adapterConfig = validate(${name}AdapterConfigSchema, options, '${adapterName} configuration');
2255
- }
2256
-
2257
- async call(args, context) {
2258
- if (!this.adapterConfig) {
2259
- throw new AdapterError('${adapterName} not configured', '${name}');
2260
- }
2261
-
2262
- // TODO: \u5B9E\u73B0\u9002\u914D\u5668\u903B\u8F91
2263
- throw new Error('Not implemented');
2264
- }
2265
- }
2266
-
2267
- module.exports = { ${adapterName}, ${name}AdapterConfigSchema };
2268
- `;
2269
- const adapterDir = "adapters";
2270
- if (!fs.existsSync(adapterDir)) {
2271
- fs.mkdirSync(adapterDir, { recursive: true });
2272
- }
2273
- const adapterPath = path.join(adapterDir, fileName);
2274
- fs.writeFileSync(adapterPath, adapterContent);
2275
- console.log(`\u2705 \u9002\u914D\u5668\u6A21\u677F\u5DF2\u751F\u6210: ${adapterPath}`);
2276
- console.log(`\u9002\u914D\u5668\u7C7B\u540D: ${adapterName}`);
2277
- console.log("\u8BF7\u7F16\u8F91\u6587\u4EF6\u5B9E\u73B0\u9002\u914D\u5668\u903B\u8F91");
2278
- });
2279
- program.command("validate:config").description("\u9A8C\u8BC1\u914D\u7F6E\u6587\u4EF6").argument("<config-file>", "\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84").action((configFile) => {
2280
- console.log(`\u9A8C\u8BC1\u914D\u7F6E\u6587\u4EF6: ${configFile}`);
2281
- console.log("\u2705 \u914D\u7F6E\u6587\u4EF6\u683C\u5F0F\u6B63\u786E");
2282
- });
2283
- program.parse();