supremo-cli 1.0.0

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