lens-engine 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js ADDED
@@ -0,0 +1,4411 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from "node:module";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ import { dirname as __dirname_ } from "node:path";
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_(__filename);
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
15
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
16
+ }) : x)(function(x) {
17
+ if (typeof require !== "undefined") return require.apply(this, arguments);
18
+ throw Error('Dynamic require of "' + x + '" is not supported');
19
+ });
20
+ var __commonJS = (cb, mod) => function __require2() {
21
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
22
+ };
23
+ var __copyProps = (to, from, except, desc) => {
24
+ if (from && typeof from === "object" || typeof from === "function") {
25
+ for (let key of __getOwnPropNames(from))
26
+ if (!__hasOwnProp.call(to, key) && key !== except)
27
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
+ }
29
+ return to;
30
+ };
31
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
+ // If the importer is in node compatibility mode or this is not an ESM
33
+ // file that has been converted to a CommonJS file using a Babel-
34
+ // compatible transform (i.e. "__esModule" has not been set), then set
35
+ // "default" to the CommonJS "module.exports" for node compatibility.
36
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
+ mod
38
+ ));
39
+
40
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js
41
+ var require_error = __commonJS({
42
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js"(exports) {
43
+ var CommanderError2 = class extends Error {
44
+ /**
45
+ * Constructs the CommanderError class
46
+ * @param {number} exitCode suggested exit code which could be used with process.exit
47
+ * @param {string} code an id string representing the error
48
+ * @param {string} message human-readable description of the error
49
+ */
50
+ constructor(exitCode, code, message) {
51
+ super(message);
52
+ Error.captureStackTrace(this, this.constructor);
53
+ this.name = this.constructor.name;
54
+ this.code = code;
55
+ this.exitCode = exitCode;
56
+ this.nestedError = void 0;
57
+ }
58
+ };
59
+ var InvalidArgumentError2 = class extends CommanderError2 {
60
+ /**
61
+ * Constructs the InvalidArgumentError class
62
+ * @param {string} [message] explanation of why argument is invalid
63
+ */
64
+ constructor(message) {
65
+ super(1, "commander.invalidArgument", message);
66
+ Error.captureStackTrace(this, this.constructor);
67
+ this.name = this.constructor.name;
68
+ }
69
+ };
70
+ exports.CommanderError = CommanderError2;
71
+ exports.InvalidArgumentError = InvalidArgumentError2;
72
+ }
73
+ });
74
+
75
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js
76
+ var require_argument = __commonJS({
77
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js"(exports) {
78
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
79
+ var Argument2 = class {
80
+ /**
81
+ * Initialize a new command argument with the given name and description.
82
+ * The default is that the argument is required, and you can explicitly
83
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
84
+ *
85
+ * @param {string} name
86
+ * @param {string} [description]
87
+ */
88
+ constructor(name, description) {
89
+ this.description = description || "";
90
+ this.variadic = false;
91
+ this.parseArg = void 0;
92
+ this.defaultValue = void 0;
93
+ this.defaultValueDescription = void 0;
94
+ this.argChoices = void 0;
95
+ switch (name[0]) {
96
+ case "<":
97
+ this.required = true;
98
+ this._name = name.slice(1, -1);
99
+ break;
100
+ case "[":
101
+ this.required = false;
102
+ this._name = name.slice(1, -1);
103
+ break;
104
+ default:
105
+ this.required = true;
106
+ this._name = name;
107
+ break;
108
+ }
109
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
110
+ this.variadic = true;
111
+ this._name = this._name.slice(0, -3);
112
+ }
113
+ }
114
+ /**
115
+ * Return argument name.
116
+ *
117
+ * @return {string}
118
+ */
119
+ name() {
120
+ return this._name;
121
+ }
122
+ /**
123
+ * @package
124
+ */
125
+ _concatValue(value, previous) {
126
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
127
+ return [value];
128
+ }
129
+ return previous.concat(value);
130
+ }
131
+ /**
132
+ * Set the default value, and optionally supply the description to be displayed in the help.
133
+ *
134
+ * @param {*} value
135
+ * @param {string} [description]
136
+ * @return {Argument}
137
+ */
138
+ default(value, description) {
139
+ this.defaultValue = value;
140
+ this.defaultValueDescription = description;
141
+ return this;
142
+ }
143
+ /**
144
+ * Set the custom handler for processing CLI command arguments into argument values.
145
+ *
146
+ * @param {Function} [fn]
147
+ * @return {Argument}
148
+ */
149
+ argParser(fn) {
150
+ this.parseArg = fn;
151
+ return this;
152
+ }
153
+ /**
154
+ * Only allow argument value to be one of choices.
155
+ *
156
+ * @param {string[]} values
157
+ * @return {Argument}
158
+ */
159
+ choices(values) {
160
+ this.argChoices = values.slice();
161
+ this.parseArg = (arg, previous) => {
162
+ if (!this.argChoices.includes(arg)) {
163
+ throw new InvalidArgumentError2(
164
+ `Allowed choices are ${this.argChoices.join(", ")}.`
165
+ );
166
+ }
167
+ if (this.variadic) {
168
+ return this._concatValue(arg, previous);
169
+ }
170
+ return arg;
171
+ };
172
+ return this;
173
+ }
174
+ /**
175
+ * Make argument required.
176
+ *
177
+ * @returns {Argument}
178
+ */
179
+ argRequired() {
180
+ this.required = true;
181
+ return this;
182
+ }
183
+ /**
184
+ * Make argument optional.
185
+ *
186
+ * @returns {Argument}
187
+ */
188
+ argOptional() {
189
+ this.required = false;
190
+ return this;
191
+ }
192
+ };
193
+ function humanReadableArgName(arg) {
194
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
195
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
196
+ }
197
+ exports.Argument = Argument2;
198
+ exports.humanReadableArgName = humanReadableArgName;
199
+ }
200
+ });
201
+
202
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js
203
+ var require_help = __commonJS({
204
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js"(exports) {
205
+ var { humanReadableArgName } = require_argument();
206
+ var Help2 = class {
207
+ constructor() {
208
+ this.helpWidth = void 0;
209
+ this.minWidthToWrap = 40;
210
+ this.sortSubcommands = false;
211
+ this.sortOptions = false;
212
+ this.showGlobalOptions = false;
213
+ }
214
+ /**
215
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
216
+ * and just before calling `formatHelp()`.
217
+ *
218
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
219
+ *
220
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
221
+ */
222
+ prepareContext(contextOptions) {
223
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
224
+ }
225
+ /**
226
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
227
+ *
228
+ * @param {Command} cmd
229
+ * @returns {Command[]}
230
+ */
231
+ visibleCommands(cmd) {
232
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
233
+ const helpCommand = cmd._getHelpCommand();
234
+ if (helpCommand && !helpCommand._hidden) {
235
+ visibleCommands.push(helpCommand);
236
+ }
237
+ if (this.sortSubcommands) {
238
+ visibleCommands.sort((a, b) => {
239
+ return a.name().localeCompare(b.name());
240
+ });
241
+ }
242
+ return visibleCommands;
243
+ }
244
+ /**
245
+ * Compare options for sort.
246
+ *
247
+ * @param {Option} a
248
+ * @param {Option} b
249
+ * @returns {number}
250
+ */
251
+ compareOptions(a, b) {
252
+ const getSortKey = (option) => {
253
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
254
+ };
255
+ return getSortKey(a).localeCompare(getSortKey(b));
256
+ }
257
+ /**
258
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
259
+ *
260
+ * @param {Command} cmd
261
+ * @returns {Option[]}
262
+ */
263
+ visibleOptions(cmd) {
264
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
265
+ const helpOption = cmd._getHelpOption();
266
+ if (helpOption && !helpOption.hidden) {
267
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
268
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
269
+ if (!removeShort && !removeLong) {
270
+ visibleOptions.push(helpOption);
271
+ } else if (helpOption.long && !removeLong) {
272
+ visibleOptions.push(
273
+ cmd.createOption(helpOption.long, helpOption.description)
274
+ );
275
+ } else if (helpOption.short && !removeShort) {
276
+ visibleOptions.push(
277
+ cmd.createOption(helpOption.short, helpOption.description)
278
+ );
279
+ }
280
+ }
281
+ if (this.sortOptions) {
282
+ visibleOptions.sort(this.compareOptions);
283
+ }
284
+ return visibleOptions;
285
+ }
286
+ /**
287
+ * Get an array of the visible global options. (Not including help.)
288
+ *
289
+ * @param {Command} cmd
290
+ * @returns {Option[]}
291
+ */
292
+ visibleGlobalOptions(cmd) {
293
+ if (!this.showGlobalOptions) return [];
294
+ const globalOptions = [];
295
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
296
+ const visibleOptions = ancestorCmd.options.filter(
297
+ (option) => !option.hidden
298
+ );
299
+ globalOptions.push(...visibleOptions);
300
+ }
301
+ if (this.sortOptions) {
302
+ globalOptions.sort(this.compareOptions);
303
+ }
304
+ return globalOptions;
305
+ }
306
+ /**
307
+ * Get an array of the arguments if any have a description.
308
+ *
309
+ * @param {Command} cmd
310
+ * @returns {Argument[]}
311
+ */
312
+ visibleArguments(cmd) {
313
+ if (cmd._argsDescription) {
314
+ cmd.registeredArguments.forEach((argument) => {
315
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
316
+ });
317
+ }
318
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
319
+ return cmd.registeredArguments;
320
+ }
321
+ return [];
322
+ }
323
+ /**
324
+ * Get the command term to show in the list of subcommands.
325
+ *
326
+ * @param {Command} cmd
327
+ * @returns {string}
328
+ */
329
+ subcommandTerm(cmd) {
330
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
331
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
332
+ (args ? " " + args : "");
333
+ }
334
+ /**
335
+ * Get the option term to show in the list of options.
336
+ *
337
+ * @param {Option} option
338
+ * @returns {string}
339
+ */
340
+ optionTerm(option) {
341
+ return option.flags;
342
+ }
343
+ /**
344
+ * Get the argument term to show in the list of arguments.
345
+ *
346
+ * @param {Argument} argument
347
+ * @returns {string}
348
+ */
349
+ argumentTerm(argument) {
350
+ return argument.name();
351
+ }
352
+ /**
353
+ * Get the longest command term length.
354
+ *
355
+ * @param {Command} cmd
356
+ * @param {Help} helper
357
+ * @returns {number}
358
+ */
359
+ longestSubcommandTermLength(cmd, helper) {
360
+ return helper.visibleCommands(cmd).reduce((max, command) => {
361
+ return Math.max(
362
+ max,
363
+ this.displayWidth(
364
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
365
+ )
366
+ );
367
+ }, 0);
368
+ }
369
+ /**
370
+ * Get the longest option term length.
371
+ *
372
+ * @param {Command} cmd
373
+ * @param {Help} helper
374
+ * @returns {number}
375
+ */
376
+ longestOptionTermLength(cmd, helper) {
377
+ return helper.visibleOptions(cmd).reduce((max, option) => {
378
+ return Math.max(
379
+ max,
380
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
381
+ );
382
+ }, 0);
383
+ }
384
+ /**
385
+ * Get the longest global option term length.
386
+ *
387
+ * @param {Command} cmd
388
+ * @param {Help} helper
389
+ * @returns {number}
390
+ */
391
+ longestGlobalOptionTermLength(cmd, helper) {
392
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
393
+ return Math.max(
394
+ max,
395
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
396
+ );
397
+ }, 0);
398
+ }
399
+ /**
400
+ * Get the longest argument term length.
401
+ *
402
+ * @param {Command} cmd
403
+ * @param {Help} helper
404
+ * @returns {number}
405
+ */
406
+ longestArgumentTermLength(cmd, helper) {
407
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
408
+ return Math.max(
409
+ max,
410
+ this.displayWidth(
411
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
412
+ )
413
+ );
414
+ }, 0);
415
+ }
416
+ /**
417
+ * Get the command usage to be displayed at the top of the built-in help.
418
+ *
419
+ * @param {Command} cmd
420
+ * @returns {string}
421
+ */
422
+ commandUsage(cmd) {
423
+ let cmdName = cmd._name;
424
+ if (cmd._aliases[0]) {
425
+ cmdName = cmdName + "|" + cmd._aliases[0];
426
+ }
427
+ let ancestorCmdNames = "";
428
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
429
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
430
+ }
431
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
432
+ }
433
+ /**
434
+ * Get the description for the command.
435
+ *
436
+ * @param {Command} cmd
437
+ * @returns {string}
438
+ */
439
+ commandDescription(cmd) {
440
+ return cmd.description();
441
+ }
442
+ /**
443
+ * Get the subcommand summary to show in the list of subcommands.
444
+ * (Fallback to description for backwards compatibility.)
445
+ *
446
+ * @param {Command} cmd
447
+ * @returns {string}
448
+ */
449
+ subcommandDescription(cmd) {
450
+ return cmd.summary() || cmd.description();
451
+ }
452
+ /**
453
+ * Get the option description to show in the list of options.
454
+ *
455
+ * @param {Option} option
456
+ * @return {string}
457
+ */
458
+ optionDescription(option) {
459
+ const extraInfo = [];
460
+ if (option.argChoices) {
461
+ extraInfo.push(
462
+ // use stringify to match the display of the default value
463
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
464
+ );
465
+ }
466
+ if (option.defaultValue !== void 0) {
467
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
468
+ if (showDefault) {
469
+ extraInfo.push(
470
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
471
+ );
472
+ }
473
+ }
474
+ if (option.presetArg !== void 0 && option.optional) {
475
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
476
+ }
477
+ if (option.envVar !== void 0) {
478
+ extraInfo.push(`env: ${option.envVar}`);
479
+ }
480
+ if (extraInfo.length > 0) {
481
+ return `${option.description} (${extraInfo.join(", ")})`;
482
+ }
483
+ return option.description;
484
+ }
485
+ /**
486
+ * Get the argument description to show in the list of arguments.
487
+ *
488
+ * @param {Argument} argument
489
+ * @return {string}
490
+ */
491
+ argumentDescription(argument) {
492
+ const extraInfo = [];
493
+ if (argument.argChoices) {
494
+ extraInfo.push(
495
+ // use stringify to match the display of the default value
496
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
497
+ );
498
+ }
499
+ if (argument.defaultValue !== void 0) {
500
+ extraInfo.push(
501
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
502
+ );
503
+ }
504
+ if (extraInfo.length > 0) {
505
+ const extraDescription = `(${extraInfo.join(", ")})`;
506
+ if (argument.description) {
507
+ return `${argument.description} ${extraDescription}`;
508
+ }
509
+ return extraDescription;
510
+ }
511
+ return argument.description;
512
+ }
513
+ /**
514
+ * Generate the built-in help text.
515
+ *
516
+ * @param {Command} cmd
517
+ * @param {Help} helper
518
+ * @returns {string}
519
+ */
520
+ formatHelp(cmd, helper) {
521
+ const termWidth = helper.padWidth(cmd, helper);
522
+ const helpWidth = helper.helpWidth ?? 80;
523
+ function callFormatItem(term, description) {
524
+ return helper.formatItem(term, termWidth, description, helper);
525
+ }
526
+ let output2 = [
527
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
528
+ ""
529
+ ];
530
+ const commandDescription = helper.commandDescription(cmd);
531
+ if (commandDescription.length > 0) {
532
+ output2 = output2.concat([
533
+ helper.boxWrap(
534
+ helper.styleCommandDescription(commandDescription),
535
+ helpWidth
536
+ ),
537
+ ""
538
+ ]);
539
+ }
540
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
541
+ return callFormatItem(
542
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
543
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
544
+ );
545
+ });
546
+ if (argumentList.length > 0) {
547
+ output2 = output2.concat([
548
+ helper.styleTitle("Arguments:"),
549
+ ...argumentList,
550
+ ""
551
+ ]);
552
+ }
553
+ const optionList = helper.visibleOptions(cmd).map((option) => {
554
+ return callFormatItem(
555
+ helper.styleOptionTerm(helper.optionTerm(option)),
556
+ helper.styleOptionDescription(helper.optionDescription(option))
557
+ );
558
+ });
559
+ if (optionList.length > 0) {
560
+ output2 = output2.concat([
561
+ helper.styleTitle("Options:"),
562
+ ...optionList,
563
+ ""
564
+ ]);
565
+ }
566
+ if (helper.showGlobalOptions) {
567
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
568
+ return callFormatItem(
569
+ helper.styleOptionTerm(helper.optionTerm(option)),
570
+ helper.styleOptionDescription(helper.optionDescription(option))
571
+ );
572
+ });
573
+ if (globalOptionList.length > 0) {
574
+ output2 = output2.concat([
575
+ helper.styleTitle("Global Options:"),
576
+ ...globalOptionList,
577
+ ""
578
+ ]);
579
+ }
580
+ }
581
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
582
+ return callFormatItem(
583
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
584
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
585
+ );
586
+ });
587
+ if (commandList.length > 0) {
588
+ output2 = output2.concat([
589
+ helper.styleTitle("Commands:"),
590
+ ...commandList,
591
+ ""
592
+ ]);
593
+ }
594
+ return output2.join("\n");
595
+ }
596
+ /**
597
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
598
+ *
599
+ * @param {string} str
600
+ * @returns {number}
601
+ */
602
+ displayWidth(str) {
603
+ return stripColor(str).length;
604
+ }
605
+ /**
606
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
607
+ *
608
+ * @param {string} str
609
+ * @returns {string}
610
+ */
611
+ styleTitle(str) {
612
+ return str;
613
+ }
614
+ styleUsage(str) {
615
+ return str.split(" ").map((word) => {
616
+ if (word === "[options]") return this.styleOptionText(word);
617
+ if (word === "[command]") return this.styleSubcommandText(word);
618
+ if (word[0] === "[" || word[0] === "<")
619
+ return this.styleArgumentText(word);
620
+ return this.styleCommandText(word);
621
+ }).join(" ");
622
+ }
623
+ styleCommandDescription(str) {
624
+ return this.styleDescriptionText(str);
625
+ }
626
+ styleOptionDescription(str) {
627
+ return this.styleDescriptionText(str);
628
+ }
629
+ styleSubcommandDescription(str) {
630
+ return this.styleDescriptionText(str);
631
+ }
632
+ styleArgumentDescription(str) {
633
+ return this.styleDescriptionText(str);
634
+ }
635
+ styleDescriptionText(str) {
636
+ return str;
637
+ }
638
+ styleOptionTerm(str) {
639
+ return this.styleOptionText(str);
640
+ }
641
+ styleSubcommandTerm(str) {
642
+ return str.split(" ").map((word) => {
643
+ if (word === "[options]") return this.styleOptionText(word);
644
+ if (word[0] === "[" || word[0] === "<")
645
+ return this.styleArgumentText(word);
646
+ return this.styleSubcommandText(word);
647
+ }).join(" ");
648
+ }
649
+ styleArgumentTerm(str) {
650
+ return this.styleArgumentText(str);
651
+ }
652
+ styleOptionText(str) {
653
+ return str;
654
+ }
655
+ styleArgumentText(str) {
656
+ return str;
657
+ }
658
+ styleSubcommandText(str) {
659
+ return str;
660
+ }
661
+ styleCommandText(str) {
662
+ return str;
663
+ }
664
+ /**
665
+ * Calculate the pad width from the maximum term length.
666
+ *
667
+ * @param {Command} cmd
668
+ * @param {Help} helper
669
+ * @returns {number}
670
+ */
671
+ padWidth(cmd, helper) {
672
+ return Math.max(
673
+ helper.longestOptionTermLength(cmd, helper),
674
+ helper.longestGlobalOptionTermLength(cmd, helper),
675
+ helper.longestSubcommandTermLength(cmd, helper),
676
+ helper.longestArgumentTermLength(cmd, helper)
677
+ );
678
+ }
679
+ /**
680
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
681
+ *
682
+ * @param {string} str
683
+ * @returns {boolean}
684
+ */
685
+ preformatted(str) {
686
+ return /\n[^\S\r\n]/.test(str);
687
+ }
688
+ /**
689
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
690
+ *
691
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
692
+ * TTT DDD DDDD
693
+ * DD DDD
694
+ *
695
+ * @param {string} term
696
+ * @param {number} termWidth
697
+ * @param {string} description
698
+ * @param {Help} helper
699
+ * @returns {string}
700
+ */
701
+ formatItem(term, termWidth, description, helper) {
702
+ const itemIndent = 2;
703
+ const itemIndentStr = " ".repeat(itemIndent);
704
+ if (!description) return itemIndentStr + term;
705
+ const paddedTerm = term.padEnd(
706
+ termWidth + term.length - helper.displayWidth(term)
707
+ );
708
+ const spacerWidth = 2;
709
+ const helpWidth = this.helpWidth ?? 80;
710
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
711
+ let formattedDescription;
712
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
713
+ formattedDescription = description;
714
+ } else {
715
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
716
+ formattedDescription = wrappedDescription.replace(
717
+ /\n/g,
718
+ "\n" + " ".repeat(termWidth + spacerWidth)
719
+ );
720
+ }
721
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
722
+ ${itemIndentStr}`);
723
+ }
724
+ /**
725
+ * Wrap a string at whitespace, preserving existing line breaks.
726
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
727
+ *
728
+ * @param {string} str
729
+ * @param {number} width
730
+ * @returns {string}
731
+ */
732
+ boxWrap(str, width) {
733
+ if (width < this.minWidthToWrap) return str;
734
+ const rawLines = str.split(/\r\n|\n/);
735
+ const chunkPattern = /[\s]*[^\s]+/g;
736
+ const wrappedLines = [];
737
+ rawLines.forEach((line) => {
738
+ const chunks = line.match(chunkPattern);
739
+ if (chunks === null) {
740
+ wrappedLines.push("");
741
+ return;
742
+ }
743
+ let sumChunks = [chunks.shift()];
744
+ let sumWidth = this.displayWidth(sumChunks[0]);
745
+ chunks.forEach((chunk) => {
746
+ const visibleWidth = this.displayWidth(chunk);
747
+ if (sumWidth + visibleWidth <= width) {
748
+ sumChunks.push(chunk);
749
+ sumWidth += visibleWidth;
750
+ return;
751
+ }
752
+ wrappedLines.push(sumChunks.join(""));
753
+ const nextChunk = chunk.trimStart();
754
+ sumChunks = [nextChunk];
755
+ sumWidth = this.displayWidth(nextChunk);
756
+ });
757
+ wrappedLines.push(sumChunks.join(""));
758
+ });
759
+ return wrappedLines.join("\n");
760
+ }
761
+ };
762
+ function stripColor(str) {
763
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
764
+ return str.replace(sgrPattern, "");
765
+ }
766
+ exports.Help = Help2;
767
+ exports.stripColor = stripColor;
768
+ }
769
+ });
770
+
771
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js
772
+ var require_option = __commonJS({
773
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js"(exports) {
774
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
775
+ var Option2 = class {
776
+ /**
777
+ * Initialize a new `Option` with the given `flags` and `description`.
778
+ *
779
+ * @param {string} flags
780
+ * @param {string} [description]
781
+ */
782
+ constructor(flags, description) {
783
+ this.flags = flags;
784
+ this.description = description || "";
785
+ this.required = flags.includes("<");
786
+ this.optional = flags.includes("[");
787
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
788
+ this.mandatory = false;
789
+ const optionFlags = splitOptionFlags(flags);
790
+ this.short = optionFlags.shortFlag;
791
+ this.long = optionFlags.longFlag;
792
+ this.negate = false;
793
+ if (this.long) {
794
+ this.negate = this.long.startsWith("--no-");
795
+ }
796
+ this.defaultValue = void 0;
797
+ this.defaultValueDescription = void 0;
798
+ this.presetArg = void 0;
799
+ this.envVar = void 0;
800
+ this.parseArg = void 0;
801
+ this.hidden = false;
802
+ this.argChoices = void 0;
803
+ this.conflictsWith = [];
804
+ this.implied = void 0;
805
+ }
806
+ /**
807
+ * Set the default value, and optionally supply the description to be displayed in the help.
808
+ *
809
+ * @param {*} value
810
+ * @param {string} [description]
811
+ * @return {Option}
812
+ */
813
+ default(value, description) {
814
+ this.defaultValue = value;
815
+ this.defaultValueDescription = description;
816
+ return this;
817
+ }
818
+ /**
819
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
820
+ * The custom processing (parseArg) is called.
821
+ *
822
+ * @example
823
+ * new Option('--color').default('GREYSCALE').preset('RGB');
824
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
825
+ *
826
+ * @param {*} arg
827
+ * @return {Option}
828
+ */
829
+ preset(arg) {
830
+ this.presetArg = arg;
831
+ return this;
832
+ }
833
+ /**
834
+ * Add option name(s) that conflict with this option.
835
+ * An error will be displayed if conflicting options are found during parsing.
836
+ *
837
+ * @example
838
+ * new Option('--rgb').conflicts('cmyk');
839
+ * new Option('--js').conflicts(['ts', 'jsx']);
840
+ *
841
+ * @param {(string | string[])} names
842
+ * @return {Option}
843
+ */
844
+ conflicts(names) {
845
+ this.conflictsWith = this.conflictsWith.concat(names);
846
+ return this;
847
+ }
848
+ /**
849
+ * Specify implied option values for when this option is set and the implied options are not.
850
+ *
851
+ * The custom processing (parseArg) is not called on the implied values.
852
+ *
853
+ * @example
854
+ * program
855
+ * .addOption(new Option('--log', 'write logging information to file'))
856
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
857
+ *
858
+ * @param {object} impliedOptionValues
859
+ * @return {Option}
860
+ */
861
+ implies(impliedOptionValues) {
862
+ let newImplied = impliedOptionValues;
863
+ if (typeof impliedOptionValues === "string") {
864
+ newImplied = { [impliedOptionValues]: true };
865
+ }
866
+ this.implied = Object.assign(this.implied || {}, newImplied);
867
+ return this;
868
+ }
869
+ /**
870
+ * Set environment variable to check for option value.
871
+ *
872
+ * An environment variable is only used if when processed the current option value is
873
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
874
+ *
875
+ * @param {string} name
876
+ * @return {Option}
877
+ */
878
+ env(name) {
879
+ this.envVar = name;
880
+ return this;
881
+ }
882
+ /**
883
+ * Set the custom handler for processing CLI option arguments into option values.
884
+ *
885
+ * @param {Function} [fn]
886
+ * @return {Option}
887
+ */
888
+ argParser(fn) {
889
+ this.parseArg = fn;
890
+ return this;
891
+ }
892
+ /**
893
+ * Whether the option is mandatory and must have a value after parsing.
894
+ *
895
+ * @param {boolean} [mandatory=true]
896
+ * @return {Option}
897
+ */
898
+ makeOptionMandatory(mandatory = true) {
899
+ this.mandatory = !!mandatory;
900
+ return this;
901
+ }
902
+ /**
903
+ * Hide option in help.
904
+ *
905
+ * @param {boolean} [hide=true]
906
+ * @return {Option}
907
+ */
908
+ hideHelp(hide = true) {
909
+ this.hidden = !!hide;
910
+ return this;
911
+ }
912
+ /**
913
+ * @package
914
+ */
915
+ _concatValue(value, previous) {
916
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
917
+ return [value];
918
+ }
919
+ return previous.concat(value);
920
+ }
921
+ /**
922
+ * Only allow option value to be one of choices.
923
+ *
924
+ * @param {string[]} values
925
+ * @return {Option}
926
+ */
927
+ choices(values) {
928
+ this.argChoices = values.slice();
929
+ this.parseArg = (arg, previous) => {
930
+ if (!this.argChoices.includes(arg)) {
931
+ throw new InvalidArgumentError2(
932
+ `Allowed choices are ${this.argChoices.join(", ")}.`
933
+ );
934
+ }
935
+ if (this.variadic) {
936
+ return this._concatValue(arg, previous);
937
+ }
938
+ return arg;
939
+ };
940
+ return this;
941
+ }
942
+ /**
943
+ * Return option name.
944
+ *
945
+ * @return {string}
946
+ */
947
+ name() {
948
+ if (this.long) {
949
+ return this.long.replace(/^--/, "");
950
+ }
951
+ return this.short.replace(/^-/, "");
952
+ }
953
+ /**
954
+ * Return option name, in a camelcase format that can be used
955
+ * as an object attribute key.
956
+ *
957
+ * @return {string}
958
+ */
959
+ attributeName() {
960
+ if (this.negate) {
961
+ return camelcase(this.name().replace(/^no-/, ""));
962
+ }
963
+ return camelcase(this.name());
964
+ }
965
+ /**
966
+ * Check if `arg` matches the short or long flag.
967
+ *
968
+ * @param {string} arg
969
+ * @return {boolean}
970
+ * @package
971
+ */
972
+ is(arg) {
973
+ return this.short === arg || this.long === arg;
974
+ }
975
+ /**
976
+ * Return whether a boolean option.
977
+ *
978
+ * Options are one of boolean, negated, required argument, or optional argument.
979
+ *
980
+ * @return {boolean}
981
+ * @package
982
+ */
983
+ isBoolean() {
984
+ return !this.required && !this.optional && !this.negate;
985
+ }
986
+ };
987
+ var DualOptions = class {
988
+ /**
989
+ * @param {Option[]} options
990
+ */
991
+ constructor(options) {
992
+ this.positiveOptions = /* @__PURE__ */ new Map();
993
+ this.negativeOptions = /* @__PURE__ */ new Map();
994
+ this.dualOptions = /* @__PURE__ */ new Set();
995
+ options.forEach((option) => {
996
+ if (option.negate) {
997
+ this.negativeOptions.set(option.attributeName(), option);
998
+ } else {
999
+ this.positiveOptions.set(option.attributeName(), option);
1000
+ }
1001
+ });
1002
+ this.negativeOptions.forEach((value, key) => {
1003
+ if (this.positiveOptions.has(key)) {
1004
+ this.dualOptions.add(key);
1005
+ }
1006
+ });
1007
+ }
1008
+ /**
1009
+ * Did the value come from the option, and not from possible matching dual option?
1010
+ *
1011
+ * @param {*} value
1012
+ * @param {Option} option
1013
+ * @returns {boolean}
1014
+ */
1015
+ valueFromOption(value, option) {
1016
+ const optionKey = option.attributeName();
1017
+ if (!this.dualOptions.has(optionKey)) return true;
1018
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1019
+ const negativeValue = preset !== void 0 ? preset : false;
1020
+ return option.negate === (negativeValue === value);
1021
+ }
1022
+ };
1023
+ function camelcase(str) {
1024
+ return str.split("-").reduce((str2, word) => {
1025
+ return str2 + word[0].toUpperCase() + word.slice(1);
1026
+ });
1027
+ }
1028
+ function splitOptionFlags(flags) {
1029
+ let shortFlag;
1030
+ let longFlag;
1031
+ const shortFlagExp = /^-[^-]$/;
1032
+ const longFlagExp = /^--[^-]/;
1033
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1034
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1035
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1036
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1037
+ shortFlag = flagParts.shift();
1038
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1039
+ shortFlag = longFlag;
1040
+ longFlag = flagParts.shift();
1041
+ }
1042
+ if (flagParts[0].startsWith("-")) {
1043
+ const unsupportedFlag = flagParts[0];
1044
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1045
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1046
+ throw new Error(
1047
+ `${baseError}
1048
+ - a short flag is a single dash and a single character
1049
+ - either use a single dash and a single character (for a short flag)
1050
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1051
+ );
1052
+ if (shortFlagExp.test(unsupportedFlag))
1053
+ throw new Error(`${baseError}
1054
+ - too many short flags`);
1055
+ if (longFlagExp.test(unsupportedFlag))
1056
+ throw new Error(`${baseError}
1057
+ - too many long flags`);
1058
+ throw new Error(`${baseError}
1059
+ - unrecognised flag format`);
1060
+ }
1061
+ if (shortFlag === void 0 && longFlag === void 0)
1062
+ throw new Error(
1063
+ `option creation failed due to no flags found in '${flags}'.`
1064
+ );
1065
+ return { shortFlag, longFlag };
1066
+ }
1067
+ exports.Option = Option2;
1068
+ exports.DualOptions = DualOptions;
1069
+ }
1070
+ });
1071
+
1072
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js
1073
+ var require_suggestSimilar = __commonJS({
1074
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
1075
+ var maxDistance = 3;
1076
+ function editDistance(a, b) {
1077
+ if (Math.abs(a.length - b.length) > maxDistance)
1078
+ return Math.max(a.length, b.length);
1079
+ const d = [];
1080
+ for (let i = 0; i <= a.length; i++) {
1081
+ d[i] = [i];
1082
+ }
1083
+ for (let j = 0; j <= b.length; j++) {
1084
+ d[0][j] = j;
1085
+ }
1086
+ for (let j = 1; j <= b.length; j++) {
1087
+ for (let i = 1; i <= a.length; i++) {
1088
+ let cost = 1;
1089
+ if (a[i - 1] === b[j - 1]) {
1090
+ cost = 0;
1091
+ } else {
1092
+ cost = 1;
1093
+ }
1094
+ d[i][j] = Math.min(
1095
+ d[i - 1][j] + 1,
1096
+ // deletion
1097
+ d[i][j - 1] + 1,
1098
+ // insertion
1099
+ d[i - 1][j - 1] + cost
1100
+ // substitution
1101
+ );
1102
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1103
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1104
+ }
1105
+ }
1106
+ }
1107
+ return d[a.length][b.length];
1108
+ }
1109
+ function suggestSimilar(word, candidates) {
1110
+ if (!candidates || candidates.length === 0) return "";
1111
+ candidates = Array.from(new Set(candidates));
1112
+ const searchingOptions = word.startsWith("--");
1113
+ if (searchingOptions) {
1114
+ word = word.slice(2);
1115
+ candidates = candidates.map((candidate) => candidate.slice(2));
1116
+ }
1117
+ let similar = [];
1118
+ let bestDistance = maxDistance;
1119
+ const minSimilarity = 0.4;
1120
+ candidates.forEach((candidate) => {
1121
+ if (candidate.length <= 1) return;
1122
+ const distance = editDistance(word, candidate);
1123
+ const length = Math.max(word.length, candidate.length);
1124
+ const similarity = (length - distance) / length;
1125
+ if (similarity > minSimilarity) {
1126
+ if (distance < bestDistance) {
1127
+ bestDistance = distance;
1128
+ similar = [candidate];
1129
+ } else if (distance === bestDistance) {
1130
+ similar.push(candidate);
1131
+ }
1132
+ }
1133
+ });
1134
+ similar.sort((a, b) => a.localeCompare(b));
1135
+ if (searchingOptions) {
1136
+ similar = similar.map((candidate) => `--${candidate}`);
1137
+ }
1138
+ if (similar.length > 1) {
1139
+ return `
1140
+ (Did you mean one of ${similar.join(", ")}?)`;
1141
+ }
1142
+ if (similar.length === 1) {
1143
+ return `
1144
+ (Did you mean ${similar[0]}?)`;
1145
+ }
1146
+ return "";
1147
+ }
1148
+ exports.suggestSimilar = suggestSimilar;
1149
+ }
1150
+ });
1151
+
1152
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js
1153
+ var require_command = __commonJS({
1154
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js"(exports) {
1155
+ var EventEmitter = __require("events").EventEmitter;
1156
+ var childProcess = __require("child_process");
1157
+ var path4 = __require("path");
1158
+ var fs4 = __require("fs");
1159
+ var process2 = __require("process");
1160
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1161
+ var { CommanderError: CommanderError2 } = require_error();
1162
+ var { Help: Help2, stripColor } = require_help();
1163
+ var { Option: Option2, DualOptions } = require_option();
1164
+ var { suggestSimilar } = require_suggestSimilar();
1165
+ var Command2 = class _Command extends EventEmitter {
1166
+ /**
1167
+ * Initialize a new `Command`.
1168
+ *
1169
+ * @param {string} [name]
1170
+ */
1171
+ constructor(name) {
1172
+ super();
1173
+ this.commands = [];
1174
+ this.options = [];
1175
+ this.parent = null;
1176
+ this._allowUnknownOption = false;
1177
+ this._allowExcessArguments = false;
1178
+ this.registeredArguments = [];
1179
+ this._args = this.registeredArguments;
1180
+ this.args = [];
1181
+ this.rawArgs = [];
1182
+ this.processedArgs = [];
1183
+ this._scriptPath = null;
1184
+ this._name = name || "";
1185
+ this._optionValues = {};
1186
+ this._optionValueSources = {};
1187
+ this._storeOptionsAsProperties = false;
1188
+ this._actionHandler = null;
1189
+ this._executableHandler = false;
1190
+ this._executableFile = null;
1191
+ this._executableDir = null;
1192
+ this._defaultCommandName = null;
1193
+ this._exitCallback = null;
1194
+ this._aliases = [];
1195
+ this._combineFlagAndOptionalValue = true;
1196
+ this._description = "";
1197
+ this._summary = "";
1198
+ this._argsDescription = void 0;
1199
+ this._enablePositionalOptions = false;
1200
+ this._passThroughOptions = false;
1201
+ this._lifeCycleHooks = {};
1202
+ this._showHelpAfterError = false;
1203
+ this._showSuggestionAfterError = true;
1204
+ this._savedState = null;
1205
+ this._outputConfiguration = {
1206
+ writeOut: (str) => process2.stdout.write(str),
1207
+ writeErr: (str) => process2.stderr.write(str),
1208
+ outputError: (str, write) => write(str),
1209
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1210
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1211
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1212
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1213
+ stripColor: (str) => stripColor(str)
1214
+ };
1215
+ this._hidden = false;
1216
+ this._helpOption = void 0;
1217
+ this._addImplicitHelpCommand = void 0;
1218
+ this._helpCommand = void 0;
1219
+ this._helpConfiguration = {};
1220
+ }
1221
+ /**
1222
+ * Copy settings that are useful to have in common across root command and subcommands.
1223
+ *
1224
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1225
+ *
1226
+ * @param {Command} sourceCommand
1227
+ * @return {Command} `this` command for chaining
1228
+ */
1229
+ copyInheritedSettings(sourceCommand) {
1230
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1231
+ this._helpOption = sourceCommand._helpOption;
1232
+ this._helpCommand = sourceCommand._helpCommand;
1233
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1234
+ this._exitCallback = sourceCommand._exitCallback;
1235
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1236
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1237
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1238
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1239
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1240
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1241
+ return this;
1242
+ }
1243
+ /**
1244
+ * @returns {Command[]}
1245
+ * @private
1246
+ */
1247
+ _getCommandAndAncestors() {
1248
+ const result = [];
1249
+ for (let command = this; command; command = command.parent) {
1250
+ result.push(command);
1251
+ }
1252
+ return result;
1253
+ }
1254
+ /**
1255
+ * Define a command.
1256
+ *
1257
+ * There are two styles of command: pay attention to where to put the description.
1258
+ *
1259
+ * @example
1260
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1261
+ * program
1262
+ * .command('clone <source> [destination]')
1263
+ * .description('clone a repository into a newly created directory')
1264
+ * .action((source, destination) => {
1265
+ * console.log('clone command called');
1266
+ * });
1267
+ *
1268
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1269
+ * program
1270
+ * .command('start <service>', 'start named service')
1271
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1272
+ *
1273
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1274
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1275
+ * @param {object} [execOpts] - configuration options (for executable)
1276
+ * @return {Command} returns new command for action handler, or `this` for executable command
1277
+ */
1278
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1279
+ let desc = actionOptsOrExecDesc;
1280
+ let opts = execOpts;
1281
+ if (typeof desc === "object" && desc !== null) {
1282
+ opts = desc;
1283
+ desc = null;
1284
+ }
1285
+ opts = opts || {};
1286
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1287
+ const cmd = this.createCommand(name);
1288
+ if (desc) {
1289
+ cmd.description(desc);
1290
+ cmd._executableHandler = true;
1291
+ }
1292
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1293
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1294
+ cmd._executableFile = opts.executableFile || null;
1295
+ if (args) cmd.arguments(args);
1296
+ this._registerCommand(cmd);
1297
+ cmd.parent = this;
1298
+ cmd.copyInheritedSettings(this);
1299
+ if (desc) return this;
1300
+ return cmd;
1301
+ }
1302
+ /**
1303
+ * Factory routine to create a new unattached command.
1304
+ *
1305
+ * See .command() for creating an attached subcommand, which uses this routine to
1306
+ * create the command. You can override createCommand to customise subcommands.
1307
+ *
1308
+ * @param {string} [name]
1309
+ * @return {Command} new command
1310
+ */
1311
+ createCommand(name) {
1312
+ return new _Command(name);
1313
+ }
1314
+ /**
1315
+ * You can customise the help with a subclass of Help by overriding createHelp,
1316
+ * or by overriding Help properties using configureHelp().
1317
+ *
1318
+ * @return {Help}
1319
+ */
1320
+ createHelp() {
1321
+ return Object.assign(new Help2(), this.configureHelp());
1322
+ }
1323
+ /**
1324
+ * You can customise the help by overriding Help properties using configureHelp(),
1325
+ * or with a subclass of Help by overriding createHelp().
1326
+ *
1327
+ * @param {object} [configuration] - configuration options
1328
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1329
+ */
1330
+ configureHelp(configuration) {
1331
+ if (configuration === void 0) return this._helpConfiguration;
1332
+ this._helpConfiguration = configuration;
1333
+ return this;
1334
+ }
1335
+ /**
1336
+ * The default output goes to stdout and stderr. You can customise this for special
1337
+ * applications. You can also customise the display of errors by overriding outputError.
1338
+ *
1339
+ * The configuration properties are all functions:
1340
+ *
1341
+ * // change how output being written, defaults to stdout and stderr
1342
+ * writeOut(str)
1343
+ * writeErr(str)
1344
+ * // change how output being written for errors, defaults to writeErr
1345
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1346
+ * // specify width for wrapping help
1347
+ * getOutHelpWidth()
1348
+ * getErrHelpWidth()
1349
+ * // color support, currently only used with Help
1350
+ * getOutHasColors()
1351
+ * getErrHasColors()
1352
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1353
+ *
1354
+ * @param {object} [configuration] - configuration options
1355
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1356
+ */
1357
+ configureOutput(configuration) {
1358
+ if (configuration === void 0) return this._outputConfiguration;
1359
+ Object.assign(this._outputConfiguration, configuration);
1360
+ return this;
1361
+ }
1362
+ /**
1363
+ * Display the help or a custom message after an error occurs.
1364
+ *
1365
+ * @param {(boolean|string)} [displayHelp]
1366
+ * @return {Command} `this` command for chaining
1367
+ */
1368
+ showHelpAfterError(displayHelp = true) {
1369
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1370
+ this._showHelpAfterError = displayHelp;
1371
+ return this;
1372
+ }
1373
+ /**
1374
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1375
+ *
1376
+ * @param {boolean} [displaySuggestion]
1377
+ * @return {Command} `this` command for chaining
1378
+ */
1379
+ showSuggestionAfterError(displaySuggestion = true) {
1380
+ this._showSuggestionAfterError = !!displaySuggestion;
1381
+ return this;
1382
+ }
1383
+ /**
1384
+ * Add a prepared subcommand.
1385
+ *
1386
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1387
+ *
1388
+ * @param {Command} cmd - new subcommand
1389
+ * @param {object} [opts] - configuration options
1390
+ * @return {Command} `this` command for chaining
1391
+ */
1392
+ addCommand(cmd, opts) {
1393
+ if (!cmd._name) {
1394
+ throw new Error(`Command passed to .addCommand() must have a name
1395
+ - specify the name in Command constructor or using .name()`);
1396
+ }
1397
+ opts = opts || {};
1398
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1399
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1400
+ this._registerCommand(cmd);
1401
+ cmd.parent = this;
1402
+ cmd._checkForBrokenPassThrough();
1403
+ return this;
1404
+ }
1405
+ /**
1406
+ * Factory routine to create a new unattached argument.
1407
+ *
1408
+ * See .argument() for creating an attached argument, which uses this routine to
1409
+ * create the argument. You can override createArgument to return a custom argument.
1410
+ *
1411
+ * @param {string} name
1412
+ * @param {string} [description]
1413
+ * @return {Argument} new argument
1414
+ */
1415
+ createArgument(name, description) {
1416
+ return new Argument2(name, description);
1417
+ }
1418
+ /**
1419
+ * Define argument syntax for command.
1420
+ *
1421
+ * The default is that the argument is required, and you can explicitly
1422
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1423
+ *
1424
+ * @example
1425
+ * program.argument('<input-file>');
1426
+ * program.argument('[output-file]');
1427
+ *
1428
+ * @param {string} name
1429
+ * @param {string} [description]
1430
+ * @param {(Function|*)} [fn] - custom argument processing function
1431
+ * @param {*} [defaultValue]
1432
+ * @return {Command} `this` command for chaining
1433
+ */
1434
+ argument(name, description, fn, defaultValue) {
1435
+ const argument = this.createArgument(name, description);
1436
+ if (typeof fn === "function") {
1437
+ argument.default(defaultValue).argParser(fn);
1438
+ } else {
1439
+ argument.default(fn);
1440
+ }
1441
+ this.addArgument(argument);
1442
+ return this;
1443
+ }
1444
+ /**
1445
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1446
+ *
1447
+ * See also .argument().
1448
+ *
1449
+ * @example
1450
+ * program.arguments('<cmd> [env]');
1451
+ *
1452
+ * @param {string} names
1453
+ * @return {Command} `this` command for chaining
1454
+ */
1455
+ arguments(names) {
1456
+ names.trim().split(/ +/).forEach((detail) => {
1457
+ this.argument(detail);
1458
+ });
1459
+ return this;
1460
+ }
1461
+ /**
1462
+ * Define argument syntax for command, adding a prepared argument.
1463
+ *
1464
+ * @param {Argument} argument
1465
+ * @return {Command} `this` command for chaining
1466
+ */
1467
+ addArgument(argument) {
1468
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1469
+ if (previousArgument && previousArgument.variadic) {
1470
+ throw new Error(
1471
+ `only the last argument can be variadic '${previousArgument.name()}'`
1472
+ );
1473
+ }
1474
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1475
+ throw new Error(
1476
+ `a default value for a required argument is never used: '${argument.name()}'`
1477
+ );
1478
+ }
1479
+ this.registeredArguments.push(argument);
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1484
+ *
1485
+ * @example
1486
+ * program.helpCommand('help [cmd]');
1487
+ * program.helpCommand('help [cmd]', 'show help');
1488
+ * program.helpCommand(false); // suppress default help command
1489
+ * program.helpCommand(true); // add help command even if no subcommands
1490
+ *
1491
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1492
+ * @param {string} [description] - custom description
1493
+ * @return {Command} `this` command for chaining
1494
+ */
1495
+ helpCommand(enableOrNameAndArgs, description) {
1496
+ if (typeof enableOrNameAndArgs === "boolean") {
1497
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1498
+ return this;
1499
+ }
1500
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1501
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1502
+ const helpDescription = description ?? "display help for command";
1503
+ const helpCommand = this.createCommand(helpName);
1504
+ helpCommand.helpOption(false);
1505
+ if (helpArgs) helpCommand.arguments(helpArgs);
1506
+ if (helpDescription) helpCommand.description(helpDescription);
1507
+ this._addImplicitHelpCommand = true;
1508
+ this._helpCommand = helpCommand;
1509
+ return this;
1510
+ }
1511
+ /**
1512
+ * Add prepared custom help command.
1513
+ *
1514
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1515
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1516
+ * @return {Command} `this` command for chaining
1517
+ */
1518
+ addHelpCommand(helpCommand, deprecatedDescription) {
1519
+ if (typeof helpCommand !== "object") {
1520
+ this.helpCommand(helpCommand, deprecatedDescription);
1521
+ return this;
1522
+ }
1523
+ this._addImplicitHelpCommand = true;
1524
+ this._helpCommand = helpCommand;
1525
+ return this;
1526
+ }
1527
+ /**
1528
+ * Lazy create help command.
1529
+ *
1530
+ * @return {(Command|null)}
1531
+ * @package
1532
+ */
1533
+ _getHelpCommand() {
1534
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1535
+ if (hasImplicitHelpCommand) {
1536
+ if (this._helpCommand === void 0) {
1537
+ this.helpCommand(void 0, void 0);
1538
+ }
1539
+ return this._helpCommand;
1540
+ }
1541
+ return null;
1542
+ }
1543
+ /**
1544
+ * Add hook for life cycle event.
1545
+ *
1546
+ * @param {string} event
1547
+ * @param {Function} listener
1548
+ * @return {Command} `this` command for chaining
1549
+ */
1550
+ hook(event, listener) {
1551
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1552
+ if (!allowedValues.includes(event)) {
1553
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1554
+ Expecting one of '${allowedValues.join("', '")}'`);
1555
+ }
1556
+ if (this._lifeCycleHooks[event]) {
1557
+ this._lifeCycleHooks[event].push(listener);
1558
+ } else {
1559
+ this._lifeCycleHooks[event] = [listener];
1560
+ }
1561
+ return this;
1562
+ }
1563
+ /**
1564
+ * Register callback to use as replacement for calling process.exit.
1565
+ *
1566
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1567
+ * @return {Command} `this` command for chaining
1568
+ */
1569
+ exitOverride(fn) {
1570
+ if (fn) {
1571
+ this._exitCallback = fn;
1572
+ } else {
1573
+ this._exitCallback = (err) => {
1574
+ if (err.code !== "commander.executeSubCommandAsync") {
1575
+ throw err;
1576
+ } else {
1577
+ }
1578
+ };
1579
+ }
1580
+ return this;
1581
+ }
1582
+ /**
1583
+ * Call process.exit, and _exitCallback if defined.
1584
+ *
1585
+ * @param {number} exitCode exit code for using with process.exit
1586
+ * @param {string} code an id string representing the error
1587
+ * @param {string} message human-readable description of the error
1588
+ * @return never
1589
+ * @private
1590
+ */
1591
+ _exit(exitCode, code, message) {
1592
+ if (this._exitCallback) {
1593
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1594
+ }
1595
+ process2.exit(exitCode);
1596
+ }
1597
+ /**
1598
+ * Register callback `fn` for the command.
1599
+ *
1600
+ * @example
1601
+ * program
1602
+ * .command('serve')
1603
+ * .description('start service')
1604
+ * .action(function() {
1605
+ * // do work here
1606
+ * });
1607
+ *
1608
+ * @param {Function} fn
1609
+ * @return {Command} `this` command for chaining
1610
+ */
1611
+ action(fn) {
1612
+ const listener = (args) => {
1613
+ const expectedArgsCount = this.registeredArguments.length;
1614
+ const actionArgs = args.slice(0, expectedArgsCount);
1615
+ if (this._storeOptionsAsProperties) {
1616
+ actionArgs[expectedArgsCount] = this;
1617
+ } else {
1618
+ actionArgs[expectedArgsCount] = this.opts();
1619
+ }
1620
+ actionArgs.push(this);
1621
+ return fn.apply(this, actionArgs);
1622
+ };
1623
+ this._actionHandler = listener;
1624
+ return this;
1625
+ }
1626
+ /**
1627
+ * Factory routine to create a new unattached option.
1628
+ *
1629
+ * See .option() for creating an attached option, which uses this routine to
1630
+ * create the option. You can override createOption to return a custom option.
1631
+ *
1632
+ * @param {string} flags
1633
+ * @param {string} [description]
1634
+ * @return {Option} new option
1635
+ */
1636
+ createOption(flags, description) {
1637
+ return new Option2(flags, description);
1638
+ }
1639
+ /**
1640
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1641
+ *
1642
+ * @param {(Option | Argument)} target
1643
+ * @param {string} value
1644
+ * @param {*} previous
1645
+ * @param {string} invalidArgumentMessage
1646
+ * @private
1647
+ */
1648
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1649
+ try {
1650
+ return target.parseArg(value, previous);
1651
+ } catch (err) {
1652
+ if (err.code === "commander.invalidArgument") {
1653
+ const message = `${invalidArgumentMessage} ${err.message}`;
1654
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1655
+ }
1656
+ throw err;
1657
+ }
1658
+ }
1659
+ /**
1660
+ * Check for option flag conflicts.
1661
+ * Register option if no conflicts found, or throw on conflict.
1662
+ *
1663
+ * @param {Option} option
1664
+ * @private
1665
+ */
1666
+ _registerOption(option) {
1667
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1668
+ if (matchingOption) {
1669
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1670
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1671
+ - already used by option '${matchingOption.flags}'`);
1672
+ }
1673
+ this.options.push(option);
1674
+ }
1675
+ /**
1676
+ * Check for command name and alias conflicts with existing commands.
1677
+ * Register command if no conflicts found, or throw on conflict.
1678
+ *
1679
+ * @param {Command} command
1680
+ * @private
1681
+ */
1682
+ _registerCommand(command) {
1683
+ const knownBy = (cmd) => {
1684
+ return [cmd.name()].concat(cmd.aliases());
1685
+ };
1686
+ const alreadyUsed = knownBy(command).find(
1687
+ (name) => this._findCommand(name)
1688
+ );
1689
+ if (alreadyUsed) {
1690
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1691
+ const newCmd = knownBy(command).join("|");
1692
+ throw new Error(
1693
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1694
+ );
1695
+ }
1696
+ this.commands.push(command);
1697
+ }
1698
+ /**
1699
+ * Add an option.
1700
+ *
1701
+ * @param {Option} option
1702
+ * @return {Command} `this` command for chaining
1703
+ */
1704
+ addOption(option) {
1705
+ this._registerOption(option);
1706
+ const oname = option.name();
1707
+ const name = option.attributeName();
1708
+ if (option.negate) {
1709
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1710
+ if (!this._findOption(positiveLongFlag)) {
1711
+ this.setOptionValueWithSource(
1712
+ name,
1713
+ option.defaultValue === void 0 ? true : option.defaultValue,
1714
+ "default"
1715
+ );
1716
+ }
1717
+ } else if (option.defaultValue !== void 0) {
1718
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1719
+ }
1720
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1721
+ if (val == null && option.presetArg !== void 0) {
1722
+ val = option.presetArg;
1723
+ }
1724
+ const oldValue = this.getOptionValue(name);
1725
+ if (val !== null && option.parseArg) {
1726
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1727
+ } else if (val !== null && option.variadic) {
1728
+ val = option._concatValue(val, oldValue);
1729
+ }
1730
+ if (val == null) {
1731
+ if (option.negate) {
1732
+ val = false;
1733
+ } else if (option.isBoolean() || option.optional) {
1734
+ val = true;
1735
+ } else {
1736
+ val = "";
1737
+ }
1738
+ }
1739
+ this.setOptionValueWithSource(name, val, valueSource);
1740
+ };
1741
+ this.on("option:" + oname, (val) => {
1742
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1743
+ handleOptionValue(val, invalidValueMessage, "cli");
1744
+ });
1745
+ if (option.envVar) {
1746
+ this.on("optionEnv:" + oname, (val) => {
1747
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1748
+ handleOptionValue(val, invalidValueMessage, "env");
1749
+ });
1750
+ }
1751
+ return this;
1752
+ }
1753
+ /**
1754
+ * Internal implementation shared by .option() and .requiredOption()
1755
+ *
1756
+ * @return {Command} `this` command for chaining
1757
+ * @private
1758
+ */
1759
+ _optionEx(config, flags, description, fn, defaultValue) {
1760
+ if (typeof flags === "object" && flags instanceof Option2) {
1761
+ throw new Error(
1762
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1763
+ );
1764
+ }
1765
+ const option = this.createOption(flags, description);
1766
+ option.makeOptionMandatory(!!config.mandatory);
1767
+ if (typeof fn === "function") {
1768
+ option.default(defaultValue).argParser(fn);
1769
+ } else if (fn instanceof RegExp) {
1770
+ const regex = fn;
1771
+ fn = (val, def) => {
1772
+ const m = regex.exec(val);
1773
+ return m ? m[0] : def;
1774
+ };
1775
+ option.default(defaultValue).argParser(fn);
1776
+ } else {
1777
+ option.default(fn);
1778
+ }
1779
+ return this.addOption(option);
1780
+ }
1781
+ /**
1782
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1783
+ *
1784
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1785
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1786
+ *
1787
+ * See the README for more details, and see also addOption() and requiredOption().
1788
+ *
1789
+ * @example
1790
+ * program
1791
+ * .option('-p, --pepper', 'add pepper')
1792
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1793
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1794
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1795
+ *
1796
+ * @param {string} flags
1797
+ * @param {string} [description]
1798
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1799
+ * @param {*} [defaultValue]
1800
+ * @return {Command} `this` command for chaining
1801
+ */
1802
+ option(flags, description, parseArg, defaultValue) {
1803
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1804
+ }
1805
+ /**
1806
+ * Add a required option which must have a value after parsing. This usually means
1807
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1808
+ *
1809
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1810
+ *
1811
+ * @param {string} flags
1812
+ * @param {string} [description]
1813
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1814
+ * @param {*} [defaultValue]
1815
+ * @return {Command} `this` command for chaining
1816
+ */
1817
+ requiredOption(flags, description, parseArg, defaultValue) {
1818
+ return this._optionEx(
1819
+ { mandatory: true },
1820
+ flags,
1821
+ description,
1822
+ parseArg,
1823
+ defaultValue
1824
+ );
1825
+ }
1826
+ /**
1827
+ * Alter parsing of short flags with optional values.
1828
+ *
1829
+ * @example
1830
+ * // for `.option('-f,--flag [value]'):
1831
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1832
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1833
+ *
1834
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1835
+ * @return {Command} `this` command for chaining
1836
+ */
1837
+ combineFlagAndOptionalValue(combine = true) {
1838
+ this._combineFlagAndOptionalValue = !!combine;
1839
+ return this;
1840
+ }
1841
+ /**
1842
+ * Allow unknown options on the command line.
1843
+ *
1844
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1845
+ * @return {Command} `this` command for chaining
1846
+ */
1847
+ allowUnknownOption(allowUnknown = true) {
1848
+ this._allowUnknownOption = !!allowUnknown;
1849
+ return this;
1850
+ }
1851
+ /**
1852
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1853
+ *
1854
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1855
+ * @return {Command} `this` command for chaining
1856
+ */
1857
+ allowExcessArguments(allowExcess = true) {
1858
+ this._allowExcessArguments = !!allowExcess;
1859
+ return this;
1860
+ }
1861
+ /**
1862
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1863
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1864
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1865
+ *
1866
+ * @param {boolean} [positional]
1867
+ * @return {Command} `this` command for chaining
1868
+ */
1869
+ enablePositionalOptions(positional = true) {
1870
+ this._enablePositionalOptions = !!positional;
1871
+ return this;
1872
+ }
1873
+ /**
1874
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1875
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1876
+ * positional options to have been enabled on the program (parent commands).
1877
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1878
+ *
1879
+ * @param {boolean} [passThrough] for unknown options.
1880
+ * @return {Command} `this` command for chaining
1881
+ */
1882
+ passThroughOptions(passThrough = true) {
1883
+ this._passThroughOptions = !!passThrough;
1884
+ this._checkForBrokenPassThrough();
1885
+ return this;
1886
+ }
1887
+ /**
1888
+ * @private
1889
+ */
1890
+ _checkForBrokenPassThrough() {
1891
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1892
+ throw new Error(
1893
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1894
+ );
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Whether to store option values as properties on command object,
1899
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1900
+ *
1901
+ * @param {boolean} [storeAsProperties=true]
1902
+ * @return {Command} `this` command for chaining
1903
+ */
1904
+ storeOptionsAsProperties(storeAsProperties = true) {
1905
+ if (this.options.length) {
1906
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1907
+ }
1908
+ if (Object.keys(this._optionValues).length) {
1909
+ throw new Error(
1910
+ "call .storeOptionsAsProperties() before setting option values"
1911
+ );
1912
+ }
1913
+ this._storeOptionsAsProperties = !!storeAsProperties;
1914
+ return this;
1915
+ }
1916
+ /**
1917
+ * Retrieve option value.
1918
+ *
1919
+ * @param {string} key
1920
+ * @return {object} value
1921
+ */
1922
+ getOptionValue(key) {
1923
+ if (this._storeOptionsAsProperties) {
1924
+ return this[key];
1925
+ }
1926
+ return this._optionValues[key];
1927
+ }
1928
+ /**
1929
+ * Store option value.
1930
+ *
1931
+ * @param {string} key
1932
+ * @param {object} value
1933
+ * @return {Command} `this` command for chaining
1934
+ */
1935
+ setOptionValue(key, value) {
1936
+ return this.setOptionValueWithSource(key, value, void 0);
1937
+ }
1938
+ /**
1939
+ * Store option value and where the value came from.
1940
+ *
1941
+ * @param {string} key
1942
+ * @param {object} value
1943
+ * @param {string} source - expected values are default/config/env/cli/implied
1944
+ * @return {Command} `this` command for chaining
1945
+ */
1946
+ setOptionValueWithSource(key, value, source) {
1947
+ if (this._storeOptionsAsProperties) {
1948
+ this[key] = value;
1949
+ } else {
1950
+ this._optionValues[key] = value;
1951
+ }
1952
+ this._optionValueSources[key] = source;
1953
+ return this;
1954
+ }
1955
+ /**
1956
+ * Get source of option value.
1957
+ * Expected values are default | config | env | cli | implied
1958
+ *
1959
+ * @param {string} key
1960
+ * @return {string}
1961
+ */
1962
+ getOptionValueSource(key) {
1963
+ return this._optionValueSources[key];
1964
+ }
1965
+ /**
1966
+ * Get source of option value. See also .optsWithGlobals().
1967
+ * Expected values are default | config | env | cli | implied
1968
+ *
1969
+ * @param {string} key
1970
+ * @return {string}
1971
+ */
1972
+ getOptionValueSourceWithGlobals(key) {
1973
+ let source;
1974
+ this._getCommandAndAncestors().forEach((cmd) => {
1975
+ if (cmd.getOptionValueSource(key) !== void 0) {
1976
+ source = cmd.getOptionValueSource(key);
1977
+ }
1978
+ });
1979
+ return source;
1980
+ }
1981
+ /**
1982
+ * Get user arguments from implied or explicit arguments.
1983
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1984
+ *
1985
+ * @private
1986
+ */
1987
+ _prepareUserArgs(argv, parseOptions) {
1988
+ if (argv !== void 0 && !Array.isArray(argv)) {
1989
+ throw new Error("first parameter to parse must be array or undefined");
1990
+ }
1991
+ parseOptions = parseOptions || {};
1992
+ if (argv === void 0 && parseOptions.from === void 0) {
1993
+ if (process2.versions?.electron) {
1994
+ parseOptions.from = "electron";
1995
+ }
1996
+ const execArgv = process2.execArgv ?? [];
1997
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1998
+ parseOptions.from = "eval";
1999
+ }
2000
+ }
2001
+ if (argv === void 0) {
2002
+ argv = process2.argv;
2003
+ }
2004
+ this.rawArgs = argv.slice();
2005
+ let userArgs;
2006
+ switch (parseOptions.from) {
2007
+ case void 0:
2008
+ case "node":
2009
+ this._scriptPath = argv[1];
2010
+ userArgs = argv.slice(2);
2011
+ break;
2012
+ case "electron":
2013
+ if (process2.defaultApp) {
2014
+ this._scriptPath = argv[1];
2015
+ userArgs = argv.slice(2);
2016
+ } else {
2017
+ userArgs = argv.slice(1);
2018
+ }
2019
+ break;
2020
+ case "user":
2021
+ userArgs = argv.slice(0);
2022
+ break;
2023
+ case "eval":
2024
+ userArgs = argv.slice(1);
2025
+ break;
2026
+ default:
2027
+ throw new Error(
2028
+ `unexpected parse option { from: '${parseOptions.from}' }`
2029
+ );
2030
+ }
2031
+ if (!this._name && this._scriptPath)
2032
+ this.nameFromFilename(this._scriptPath);
2033
+ this._name = this._name || "program";
2034
+ return userArgs;
2035
+ }
2036
+ /**
2037
+ * Parse `argv`, setting options and invoking commands when defined.
2038
+ *
2039
+ * Use parseAsync instead of parse if any of your action handlers are async.
2040
+ *
2041
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2042
+ *
2043
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2044
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2045
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2046
+ * - `'user'`: just user arguments
2047
+ *
2048
+ * @example
2049
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2050
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2051
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2052
+ *
2053
+ * @param {string[]} [argv] - optional, defaults to process.argv
2054
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2055
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2056
+ * @return {Command} `this` command for chaining
2057
+ */
2058
+ parse(argv, parseOptions) {
2059
+ this._prepareForParse();
2060
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2061
+ this._parseCommand([], userArgs);
2062
+ return this;
2063
+ }
2064
+ /**
2065
+ * Parse `argv`, setting options and invoking commands when defined.
2066
+ *
2067
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2068
+ *
2069
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2070
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2071
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2072
+ * - `'user'`: just user arguments
2073
+ *
2074
+ * @example
2075
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2076
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2077
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2078
+ *
2079
+ * @param {string[]} [argv]
2080
+ * @param {object} [parseOptions]
2081
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2082
+ * @return {Promise}
2083
+ */
2084
+ async parseAsync(argv, parseOptions) {
2085
+ this._prepareForParse();
2086
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2087
+ await this._parseCommand([], userArgs);
2088
+ return this;
2089
+ }
2090
+ _prepareForParse() {
2091
+ if (this._savedState === null) {
2092
+ this.saveStateBeforeParse();
2093
+ } else {
2094
+ this.restoreStateBeforeParse();
2095
+ }
2096
+ }
2097
+ /**
2098
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2099
+ * Not usually called directly, but available for subclasses to save their custom state.
2100
+ *
2101
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2102
+ */
2103
+ saveStateBeforeParse() {
2104
+ this._savedState = {
2105
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2106
+ _name: this._name,
2107
+ // option values before parse have default values (including false for negated options)
2108
+ // shallow clones
2109
+ _optionValues: { ...this._optionValues },
2110
+ _optionValueSources: { ...this._optionValueSources }
2111
+ };
2112
+ }
2113
+ /**
2114
+ * Restore state before parse for calls after the first.
2115
+ * Not usually called directly, but available for subclasses to save their custom state.
2116
+ *
2117
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2118
+ */
2119
+ restoreStateBeforeParse() {
2120
+ if (this._storeOptionsAsProperties)
2121
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2122
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2123
+ this._name = this._savedState._name;
2124
+ this._scriptPath = null;
2125
+ this.rawArgs = [];
2126
+ this._optionValues = { ...this._savedState._optionValues };
2127
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2128
+ this.args = [];
2129
+ this.processedArgs = [];
2130
+ }
2131
+ /**
2132
+ * Throw if expected executable is missing. Add lots of help for author.
2133
+ *
2134
+ * @param {string} executableFile
2135
+ * @param {string} executableDir
2136
+ * @param {string} subcommandName
2137
+ */
2138
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2139
+ if (fs4.existsSync(executableFile)) return;
2140
+ 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";
2141
+ const executableMissing = `'${executableFile}' does not exist
2142
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2143
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2144
+ - ${executableDirMessage}`;
2145
+ throw new Error(executableMissing);
2146
+ }
2147
+ /**
2148
+ * Execute a sub-command executable.
2149
+ *
2150
+ * @private
2151
+ */
2152
+ _executeSubCommand(subcommand, args) {
2153
+ args = args.slice();
2154
+ let launchWithNode = false;
2155
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2156
+ function findFile(baseDir, baseName) {
2157
+ const localBin = path4.resolve(baseDir, baseName);
2158
+ if (fs4.existsSync(localBin)) return localBin;
2159
+ if (sourceExt.includes(path4.extname(baseName))) return void 0;
2160
+ const foundExt = sourceExt.find(
2161
+ (ext) => fs4.existsSync(`${localBin}${ext}`)
2162
+ );
2163
+ if (foundExt) return `${localBin}${foundExt}`;
2164
+ return void 0;
2165
+ }
2166
+ this._checkForMissingMandatoryOptions();
2167
+ this._checkForConflictingOptions();
2168
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2169
+ let executableDir = this._executableDir || "";
2170
+ if (this._scriptPath) {
2171
+ let resolvedScriptPath;
2172
+ try {
2173
+ resolvedScriptPath = fs4.realpathSync(this._scriptPath);
2174
+ } catch {
2175
+ resolvedScriptPath = this._scriptPath;
2176
+ }
2177
+ executableDir = path4.resolve(
2178
+ path4.dirname(resolvedScriptPath),
2179
+ executableDir
2180
+ );
2181
+ }
2182
+ if (executableDir) {
2183
+ let localFile = findFile(executableDir, executableFile);
2184
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2185
+ const legacyName = path4.basename(
2186
+ this._scriptPath,
2187
+ path4.extname(this._scriptPath)
2188
+ );
2189
+ if (legacyName !== this._name) {
2190
+ localFile = findFile(
2191
+ executableDir,
2192
+ `${legacyName}-${subcommand._name}`
2193
+ );
2194
+ }
2195
+ }
2196
+ executableFile = localFile || executableFile;
2197
+ }
2198
+ launchWithNode = sourceExt.includes(path4.extname(executableFile));
2199
+ let proc;
2200
+ if (process2.platform !== "win32") {
2201
+ if (launchWithNode) {
2202
+ args.unshift(executableFile);
2203
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2204
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2205
+ } else {
2206
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2207
+ }
2208
+ } else {
2209
+ this._checkForMissingExecutable(
2210
+ executableFile,
2211
+ executableDir,
2212
+ subcommand._name
2213
+ );
2214
+ args.unshift(executableFile);
2215
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2216
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2217
+ }
2218
+ if (!proc.killed) {
2219
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2220
+ signals.forEach((signal) => {
2221
+ process2.on(signal, () => {
2222
+ if (proc.killed === false && proc.exitCode === null) {
2223
+ proc.kill(signal);
2224
+ }
2225
+ });
2226
+ });
2227
+ }
2228
+ const exitCallback = this._exitCallback;
2229
+ proc.on("close", (code) => {
2230
+ code = code ?? 1;
2231
+ if (!exitCallback) {
2232
+ process2.exit(code);
2233
+ } else {
2234
+ exitCallback(
2235
+ new CommanderError2(
2236
+ code,
2237
+ "commander.executeSubCommandAsync",
2238
+ "(close)"
2239
+ )
2240
+ );
2241
+ }
2242
+ });
2243
+ proc.on("error", (err) => {
2244
+ if (err.code === "ENOENT") {
2245
+ this._checkForMissingExecutable(
2246
+ executableFile,
2247
+ executableDir,
2248
+ subcommand._name
2249
+ );
2250
+ } else if (err.code === "EACCES") {
2251
+ throw new Error(`'${executableFile}' not executable`);
2252
+ }
2253
+ if (!exitCallback) {
2254
+ process2.exit(1);
2255
+ } else {
2256
+ const wrappedError = new CommanderError2(
2257
+ 1,
2258
+ "commander.executeSubCommandAsync",
2259
+ "(error)"
2260
+ );
2261
+ wrappedError.nestedError = err;
2262
+ exitCallback(wrappedError);
2263
+ }
2264
+ });
2265
+ this.runningCommand = proc;
2266
+ }
2267
+ /**
2268
+ * @private
2269
+ */
2270
+ _dispatchSubcommand(commandName, operands, unknown) {
2271
+ const subCommand = this._findCommand(commandName);
2272
+ if (!subCommand) this.help({ error: true });
2273
+ subCommand._prepareForParse();
2274
+ let promiseChain;
2275
+ promiseChain = this._chainOrCallSubCommandHook(
2276
+ promiseChain,
2277
+ subCommand,
2278
+ "preSubcommand"
2279
+ );
2280
+ promiseChain = this._chainOrCall(promiseChain, () => {
2281
+ if (subCommand._executableHandler) {
2282
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2283
+ } else {
2284
+ return subCommand._parseCommand(operands, unknown);
2285
+ }
2286
+ });
2287
+ return promiseChain;
2288
+ }
2289
+ /**
2290
+ * Invoke help directly if possible, or dispatch if necessary.
2291
+ * e.g. help foo
2292
+ *
2293
+ * @private
2294
+ */
2295
+ _dispatchHelpCommand(subcommandName) {
2296
+ if (!subcommandName) {
2297
+ this.help();
2298
+ }
2299
+ const subCommand = this._findCommand(subcommandName);
2300
+ if (subCommand && !subCommand._executableHandler) {
2301
+ subCommand.help();
2302
+ }
2303
+ return this._dispatchSubcommand(
2304
+ subcommandName,
2305
+ [],
2306
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2307
+ );
2308
+ }
2309
+ /**
2310
+ * Check this.args against expected this.registeredArguments.
2311
+ *
2312
+ * @private
2313
+ */
2314
+ _checkNumberOfArguments() {
2315
+ this.registeredArguments.forEach((arg, i) => {
2316
+ if (arg.required && this.args[i] == null) {
2317
+ this.missingArgument(arg.name());
2318
+ }
2319
+ });
2320
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2321
+ return;
2322
+ }
2323
+ if (this.args.length > this.registeredArguments.length) {
2324
+ this._excessArguments(this.args);
2325
+ }
2326
+ }
2327
+ /**
2328
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2329
+ *
2330
+ * @private
2331
+ */
2332
+ _processArguments() {
2333
+ const myParseArg = (argument, value, previous) => {
2334
+ let parsedValue = value;
2335
+ if (value !== null && argument.parseArg) {
2336
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2337
+ parsedValue = this._callParseArg(
2338
+ argument,
2339
+ value,
2340
+ previous,
2341
+ invalidValueMessage
2342
+ );
2343
+ }
2344
+ return parsedValue;
2345
+ };
2346
+ this._checkNumberOfArguments();
2347
+ const processedArgs = [];
2348
+ this.registeredArguments.forEach((declaredArg, index) => {
2349
+ let value = declaredArg.defaultValue;
2350
+ if (declaredArg.variadic) {
2351
+ if (index < this.args.length) {
2352
+ value = this.args.slice(index);
2353
+ if (declaredArg.parseArg) {
2354
+ value = value.reduce((processed, v) => {
2355
+ return myParseArg(declaredArg, v, processed);
2356
+ }, declaredArg.defaultValue);
2357
+ }
2358
+ } else if (value === void 0) {
2359
+ value = [];
2360
+ }
2361
+ } else if (index < this.args.length) {
2362
+ value = this.args[index];
2363
+ if (declaredArg.parseArg) {
2364
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2365
+ }
2366
+ }
2367
+ processedArgs[index] = value;
2368
+ });
2369
+ this.processedArgs = processedArgs;
2370
+ }
2371
+ /**
2372
+ * Once we have a promise we chain, but call synchronously until then.
2373
+ *
2374
+ * @param {(Promise|undefined)} promise
2375
+ * @param {Function} fn
2376
+ * @return {(Promise|undefined)}
2377
+ * @private
2378
+ */
2379
+ _chainOrCall(promise, fn) {
2380
+ if (promise && promise.then && typeof promise.then === "function") {
2381
+ return promise.then(() => fn());
2382
+ }
2383
+ return fn();
2384
+ }
2385
+ /**
2386
+ *
2387
+ * @param {(Promise|undefined)} promise
2388
+ * @param {string} event
2389
+ * @return {(Promise|undefined)}
2390
+ * @private
2391
+ */
2392
+ _chainOrCallHooks(promise, event) {
2393
+ let result = promise;
2394
+ const hooks = [];
2395
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2396
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2397
+ hooks.push({ hookedCommand, callback });
2398
+ });
2399
+ });
2400
+ if (event === "postAction") {
2401
+ hooks.reverse();
2402
+ }
2403
+ hooks.forEach((hookDetail) => {
2404
+ result = this._chainOrCall(result, () => {
2405
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2406
+ });
2407
+ });
2408
+ return result;
2409
+ }
2410
+ /**
2411
+ *
2412
+ * @param {(Promise|undefined)} promise
2413
+ * @param {Command} subCommand
2414
+ * @param {string} event
2415
+ * @return {(Promise|undefined)}
2416
+ * @private
2417
+ */
2418
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2419
+ let result = promise;
2420
+ if (this._lifeCycleHooks[event] !== void 0) {
2421
+ this._lifeCycleHooks[event].forEach((hook) => {
2422
+ result = this._chainOrCall(result, () => {
2423
+ return hook(this, subCommand);
2424
+ });
2425
+ });
2426
+ }
2427
+ return result;
2428
+ }
2429
+ /**
2430
+ * Process arguments in context of this command.
2431
+ * Returns action result, in case it is a promise.
2432
+ *
2433
+ * @private
2434
+ */
2435
+ _parseCommand(operands, unknown) {
2436
+ const parsed = this.parseOptions(unknown);
2437
+ this._parseOptionsEnv();
2438
+ this._parseOptionsImplied();
2439
+ operands = operands.concat(parsed.operands);
2440
+ unknown = parsed.unknown;
2441
+ this.args = operands.concat(unknown);
2442
+ if (operands && this._findCommand(operands[0])) {
2443
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2444
+ }
2445
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2446
+ return this._dispatchHelpCommand(operands[1]);
2447
+ }
2448
+ if (this._defaultCommandName) {
2449
+ this._outputHelpIfRequested(unknown);
2450
+ return this._dispatchSubcommand(
2451
+ this._defaultCommandName,
2452
+ operands,
2453
+ unknown
2454
+ );
2455
+ }
2456
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2457
+ this.help({ error: true });
2458
+ }
2459
+ this._outputHelpIfRequested(parsed.unknown);
2460
+ this._checkForMissingMandatoryOptions();
2461
+ this._checkForConflictingOptions();
2462
+ const checkForUnknownOptions = () => {
2463
+ if (parsed.unknown.length > 0) {
2464
+ this.unknownOption(parsed.unknown[0]);
2465
+ }
2466
+ };
2467
+ const commandEvent = `command:${this.name()}`;
2468
+ if (this._actionHandler) {
2469
+ checkForUnknownOptions();
2470
+ this._processArguments();
2471
+ let promiseChain;
2472
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2473
+ promiseChain = this._chainOrCall(
2474
+ promiseChain,
2475
+ () => this._actionHandler(this.processedArgs)
2476
+ );
2477
+ if (this.parent) {
2478
+ promiseChain = this._chainOrCall(promiseChain, () => {
2479
+ this.parent.emit(commandEvent, operands, unknown);
2480
+ });
2481
+ }
2482
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2483
+ return promiseChain;
2484
+ }
2485
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2486
+ checkForUnknownOptions();
2487
+ this._processArguments();
2488
+ this.parent.emit(commandEvent, operands, unknown);
2489
+ } else if (operands.length) {
2490
+ if (this._findCommand("*")) {
2491
+ return this._dispatchSubcommand("*", operands, unknown);
2492
+ }
2493
+ if (this.listenerCount("command:*")) {
2494
+ this.emit("command:*", operands, unknown);
2495
+ } else if (this.commands.length) {
2496
+ this.unknownCommand();
2497
+ } else {
2498
+ checkForUnknownOptions();
2499
+ this._processArguments();
2500
+ }
2501
+ } else if (this.commands.length) {
2502
+ checkForUnknownOptions();
2503
+ this.help({ error: true });
2504
+ } else {
2505
+ checkForUnknownOptions();
2506
+ this._processArguments();
2507
+ }
2508
+ }
2509
+ /**
2510
+ * Find matching command.
2511
+ *
2512
+ * @private
2513
+ * @return {Command | undefined}
2514
+ */
2515
+ _findCommand(name) {
2516
+ if (!name) return void 0;
2517
+ return this.commands.find(
2518
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2519
+ );
2520
+ }
2521
+ /**
2522
+ * Return an option matching `arg` if any.
2523
+ *
2524
+ * @param {string} arg
2525
+ * @return {Option}
2526
+ * @package
2527
+ */
2528
+ _findOption(arg) {
2529
+ return this.options.find((option) => option.is(arg));
2530
+ }
2531
+ /**
2532
+ * Display an error message if a mandatory option does not have a value.
2533
+ * Called after checking for help flags in leaf subcommand.
2534
+ *
2535
+ * @private
2536
+ */
2537
+ _checkForMissingMandatoryOptions() {
2538
+ this._getCommandAndAncestors().forEach((cmd) => {
2539
+ cmd.options.forEach((anOption) => {
2540
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2541
+ cmd.missingMandatoryOptionValue(anOption);
2542
+ }
2543
+ });
2544
+ });
2545
+ }
2546
+ /**
2547
+ * Display an error message if conflicting options are used together in this.
2548
+ *
2549
+ * @private
2550
+ */
2551
+ _checkForConflictingLocalOptions() {
2552
+ const definedNonDefaultOptions = this.options.filter((option) => {
2553
+ const optionKey = option.attributeName();
2554
+ if (this.getOptionValue(optionKey) === void 0) {
2555
+ return false;
2556
+ }
2557
+ return this.getOptionValueSource(optionKey) !== "default";
2558
+ });
2559
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2560
+ (option) => option.conflictsWith.length > 0
2561
+ );
2562
+ optionsWithConflicting.forEach((option) => {
2563
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2564
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2565
+ );
2566
+ if (conflictingAndDefined) {
2567
+ this._conflictingOption(option, conflictingAndDefined);
2568
+ }
2569
+ });
2570
+ }
2571
+ /**
2572
+ * Display an error message if conflicting options are used together.
2573
+ * Called after checking for help flags in leaf subcommand.
2574
+ *
2575
+ * @private
2576
+ */
2577
+ _checkForConflictingOptions() {
2578
+ this._getCommandAndAncestors().forEach((cmd) => {
2579
+ cmd._checkForConflictingLocalOptions();
2580
+ });
2581
+ }
2582
+ /**
2583
+ * Parse options from `argv` removing known options,
2584
+ * and return argv split into operands and unknown arguments.
2585
+ *
2586
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2587
+ *
2588
+ * Examples:
2589
+ *
2590
+ * argv => operands, unknown
2591
+ * --known kkk op => [op], []
2592
+ * op --known kkk => [op], []
2593
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2594
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2595
+ *
2596
+ * @param {string[]} argv
2597
+ * @return {{operands: string[], unknown: string[]}}
2598
+ */
2599
+ parseOptions(argv) {
2600
+ const operands = [];
2601
+ const unknown = [];
2602
+ let dest = operands;
2603
+ const args = argv.slice();
2604
+ function maybeOption(arg) {
2605
+ return arg.length > 1 && arg[0] === "-";
2606
+ }
2607
+ let activeVariadicOption = null;
2608
+ while (args.length) {
2609
+ const arg = args.shift();
2610
+ if (arg === "--") {
2611
+ if (dest === unknown) dest.push(arg);
2612
+ dest.push(...args);
2613
+ break;
2614
+ }
2615
+ if (activeVariadicOption && !maybeOption(arg)) {
2616
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2617
+ continue;
2618
+ }
2619
+ activeVariadicOption = null;
2620
+ if (maybeOption(arg)) {
2621
+ const option = this._findOption(arg);
2622
+ if (option) {
2623
+ if (option.required) {
2624
+ const value = args.shift();
2625
+ if (value === void 0) this.optionMissingArgument(option);
2626
+ this.emit(`option:${option.name()}`, value);
2627
+ } else if (option.optional) {
2628
+ let value = null;
2629
+ if (args.length > 0 && !maybeOption(args[0])) {
2630
+ value = args.shift();
2631
+ }
2632
+ this.emit(`option:${option.name()}`, value);
2633
+ } else {
2634
+ this.emit(`option:${option.name()}`);
2635
+ }
2636
+ activeVariadicOption = option.variadic ? option : null;
2637
+ continue;
2638
+ }
2639
+ }
2640
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2641
+ const option = this._findOption(`-${arg[1]}`);
2642
+ if (option) {
2643
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2644
+ this.emit(`option:${option.name()}`, arg.slice(2));
2645
+ } else {
2646
+ this.emit(`option:${option.name()}`);
2647
+ args.unshift(`-${arg.slice(2)}`);
2648
+ }
2649
+ continue;
2650
+ }
2651
+ }
2652
+ if (/^--[^=]+=/.test(arg)) {
2653
+ const index = arg.indexOf("=");
2654
+ const option = this._findOption(arg.slice(0, index));
2655
+ if (option && (option.required || option.optional)) {
2656
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2657
+ continue;
2658
+ }
2659
+ }
2660
+ if (maybeOption(arg)) {
2661
+ dest = unknown;
2662
+ }
2663
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2664
+ if (this._findCommand(arg)) {
2665
+ operands.push(arg);
2666
+ if (args.length > 0) unknown.push(...args);
2667
+ break;
2668
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2669
+ operands.push(arg);
2670
+ if (args.length > 0) operands.push(...args);
2671
+ break;
2672
+ } else if (this._defaultCommandName) {
2673
+ unknown.push(arg);
2674
+ if (args.length > 0) unknown.push(...args);
2675
+ break;
2676
+ }
2677
+ }
2678
+ if (this._passThroughOptions) {
2679
+ dest.push(arg);
2680
+ if (args.length > 0) dest.push(...args);
2681
+ break;
2682
+ }
2683
+ dest.push(arg);
2684
+ }
2685
+ return { operands, unknown };
2686
+ }
2687
+ /**
2688
+ * Return an object containing local option values as key-value pairs.
2689
+ *
2690
+ * @return {object}
2691
+ */
2692
+ opts() {
2693
+ if (this._storeOptionsAsProperties) {
2694
+ const result = {};
2695
+ const len = this.options.length;
2696
+ for (let i = 0; i < len; i++) {
2697
+ const key = this.options[i].attributeName();
2698
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2699
+ }
2700
+ return result;
2701
+ }
2702
+ return this._optionValues;
2703
+ }
2704
+ /**
2705
+ * Return an object containing merged local and global option values as key-value pairs.
2706
+ *
2707
+ * @return {object}
2708
+ */
2709
+ optsWithGlobals() {
2710
+ return this._getCommandAndAncestors().reduce(
2711
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2712
+ {}
2713
+ );
2714
+ }
2715
+ /**
2716
+ * Display error message and exit (or call exitOverride).
2717
+ *
2718
+ * @param {string} message
2719
+ * @param {object} [errorOptions]
2720
+ * @param {string} [errorOptions.code] - an id string representing the error
2721
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2722
+ */
2723
+ error(message, errorOptions) {
2724
+ this._outputConfiguration.outputError(
2725
+ `${message}
2726
+ `,
2727
+ this._outputConfiguration.writeErr
2728
+ );
2729
+ if (typeof this._showHelpAfterError === "string") {
2730
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2731
+ `);
2732
+ } else if (this._showHelpAfterError) {
2733
+ this._outputConfiguration.writeErr("\n");
2734
+ this.outputHelp({ error: true });
2735
+ }
2736
+ const config = errorOptions || {};
2737
+ const exitCode = config.exitCode || 1;
2738
+ const code = config.code || "commander.error";
2739
+ this._exit(exitCode, code, message);
2740
+ }
2741
+ /**
2742
+ * Apply any option related environment variables, if option does
2743
+ * not have a value from cli or client code.
2744
+ *
2745
+ * @private
2746
+ */
2747
+ _parseOptionsEnv() {
2748
+ this.options.forEach((option) => {
2749
+ if (option.envVar && option.envVar in process2.env) {
2750
+ const optionKey = option.attributeName();
2751
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2752
+ this.getOptionValueSource(optionKey)
2753
+ )) {
2754
+ if (option.required || option.optional) {
2755
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2756
+ } else {
2757
+ this.emit(`optionEnv:${option.name()}`);
2758
+ }
2759
+ }
2760
+ }
2761
+ });
2762
+ }
2763
+ /**
2764
+ * Apply any implied option values, if option is undefined or default value.
2765
+ *
2766
+ * @private
2767
+ */
2768
+ _parseOptionsImplied() {
2769
+ const dualHelper = new DualOptions(this.options);
2770
+ const hasCustomOptionValue = (optionKey) => {
2771
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2772
+ };
2773
+ this.options.filter(
2774
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2775
+ this.getOptionValue(option.attributeName()),
2776
+ option
2777
+ )
2778
+ ).forEach((option) => {
2779
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2780
+ this.setOptionValueWithSource(
2781
+ impliedKey,
2782
+ option.implied[impliedKey],
2783
+ "implied"
2784
+ );
2785
+ });
2786
+ });
2787
+ }
2788
+ /**
2789
+ * Argument `name` is missing.
2790
+ *
2791
+ * @param {string} name
2792
+ * @private
2793
+ */
2794
+ missingArgument(name) {
2795
+ const message = `error: missing required argument '${name}'`;
2796
+ this.error(message, { code: "commander.missingArgument" });
2797
+ }
2798
+ /**
2799
+ * `Option` is missing an argument.
2800
+ *
2801
+ * @param {Option} option
2802
+ * @private
2803
+ */
2804
+ optionMissingArgument(option) {
2805
+ const message = `error: option '${option.flags}' argument missing`;
2806
+ this.error(message, { code: "commander.optionMissingArgument" });
2807
+ }
2808
+ /**
2809
+ * `Option` does not have a value, and is a mandatory option.
2810
+ *
2811
+ * @param {Option} option
2812
+ * @private
2813
+ */
2814
+ missingMandatoryOptionValue(option) {
2815
+ const message = `error: required option '${option.flags}' not specified`;
2816
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2817
+ }
2818
+ /**
2819
+ * `Option` conflicts with another option.
2820
+ *
2821
+ * @param {Option} option
2822
+ * @param {Option} conflictingOption
2823
+ * @private
2824
+ */
2825
+ _conflictingOption(option, conflictingOption) {
2826
+ const findBestOptionFromValue = (option2) => {
2827
+ const optionKey = option2.attributeName();
2828
+ const optionValue = this.getOptionValue(optionKey);
2829
+ const negativeOption = this.options.find(
2830
+ (target) => target.negate && optionKey === target.attributeName()
2831
+ );
2832
+ const positiveOption = this.options.find(
2833
+ (target) => !target.negate && optionKey === target.attributeName()
2834
+ );
2835
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2836
+ return negativeOption;
2837
+ }
2838
+ return positiveOption || option2;
2839
+ };
2840
+ const getErrorMessage = (option2) => {
2841
+ const bestOption = findBestOptionFromValue(option2);
2842
+ const optionKey = bestOption.attributeName();
2843
+ const source = this.getOptionValueSource(optionKey);
2844
+ if (source === "env") {
2845
+ return `environment variable '${bestOption.envVar}'`;
2846
+ }
2847
+ return `option '${bestOption.flags}'`;
2848
+ };
2849
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2850
+ this.error(message, { code: "commander.conflictingOption" });
2851
+ }
2852
+ /**
2853
+ * Unknown option `flag`.
2854
+ *
2855
+ * @param {string} flag
2856
+ * @private
2857
+ */
2858
+ unknownOption(flag) {
2859
+ if (this._allowUnknownOption) return;
2860
+ let suggestion = "";
2861
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2862
+ let candidateFlags = [];
2863
+ let command = this;
2864
+ do {
2865
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2866
+ candidateFlags = candidateFlags.concat(moreFlags);
2867
+ command = command.parent;
2868
+ } while (command && !command._enablePositionalOptions);
2869
+ suggestion = suggestSimilar(flag, candidateFlags);
2870
+ }
2871
+ const message = `error: unknown option '${flag}'${suggestion}`;
2872
+ this.error(message, { code: "commander.unknownOption" });
2873
+ }
2874
+ /**
2875
+ * Excess arguments, more than expected.
2876
+ *
2877
+ * @param {string[]} receivedArgs
2878
+ * @private
2879
+ */
2880
+ _excessArguments(receivedArgs) {
2881
+ if (this._allowExcessArguments) return;
2882
+ const expected = this.registeredArguments.length;
2883
+ const s = expected === 1 ? "" : "s";
2884
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2885
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2886
+ this.error(message, { code: "commander.excessArguments" });
2887
+ }
2888
+ /**
2889
+ * Unknown command.
2890
+ *
2891
+ * @private
2892
+ */
2893
+ unknownCommand() {
2894
+ const unknownName = this.args[0];
2895
+ let suggestion = "";
2896
+ if (this._showSuggestionAfterError) {
2897
+ const candidateNames = [];
2898
+ this.createHelp().visibleCommands(this).forEach((command) => {
2899
+ candidateNames.push(command.name());
2900
+ if (command.alias()) candidateNames.push(command.alias());
2901
+ });
2902
+ suggestion = suggestSimilar(unknownName, candidateNames);
2903
+ }
2904
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2905
+ this.error(message, { code: "commander.unknownCommand" });
2906
+ }
2907
+ /**
2908
+ * Get or set the program version.
2909
+ *
2910
+ * This method auto-registers the "-V, --version" option which will print the version number.
2911
+ *
2912
+ * You can optionally supply the flags and description to override the defaults.
2913
+ *
2914
+ * @param {string} [str]
2915
+ * @param {string} [flags]
2916
+ * @param {string} [description]
2917
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2918
+ */
2919
+ version(str, flags, description) {
2920
+ if (str === void 0) return this._version;
2921
+ this._version = str;
2922
+ flags = flags || "-V, --version";
2923
+ description = description || "output the version number";
2924
+ const versionOption = this.createOption(flags, description);
2925
+ this._versionOptionName = versionOption.attributeName();
2926
+ this._registerOption(versionOption);
2927
+ this.on("option:" + versionOption.name(), () => {
2928
+ this._outputConfiguration.writeOut(`${str}
2929
+ `);
2930
+ this._exit(0, "commander.version", str);
2931
+ });
2932
+ return this;
2933
+ }
2934
+ /**
2935
+ * Set the description.
2936
+ *
2937
+ * @param {string} [str]
2938
+ * @param {object} [argsDescription]
2939
+ * @return {(string|Command)}
2940
+ */
2941
+ description(str, argsDescription) {
2942
+ if (str === void 0 && argsDescription === void 0)
2943
+ return this._description;
2944
+ this._description = str;
2945
+ if (argsDescription) {
2946
+ this._argsDescription = argsDescription;
2947
+ }
2948
+ return this;
2949
+ }
2950
+ /**
2951
+ * Set the summary. Used when listed as subcommand of parent.
2952
+ *
2953
+ * @param {string} [str]
2954
+ * @return {(string|Command)}
2955
+ */
2956
+ summary(str) {
2957
+ if (str === void 0) return this._summary;
2958
+ this._summary = str;
2959
+ return this;
2960
+ }
2961
+ /**
2962
+ * Set an alias for the command.
2963
+ *
2964
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2965
+ *
2966
+ * @param {string} [alias]
2967
+ * @return {(string|Command)}
2968
+ */
2969
+ alias(alias) {
2970
+ if (alias === void 0) return this._aliases[0];
2971
+ let command = this;
2972
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2973
+ command = this.commands[this.commands.length - 1];
2974
+ }
2975
+ if (alias === command._name)
2976
+ throw new Error("Command alias can't be the same as its name");
2977
+ const matchingCommand = this.parent?._findCommand(alias);
2978
+ if (matchingCommand) {
2979
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2980
+ throw new Error(
2981
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2982
+ );
2983
+ }
2984
+ command._aliases.push(alias);
2985
+ return this;
2986
+ }
2987
+ /**
2988
+ * Set aliases for the command.
2989
+ *
2990
+ * Only the first alias is shown in the auto-generated help.
2991
+ *
2992
+ * @param {string[]} [aliases]
2993
+ * @return {(string[]|Command)}
2994
+ */
2995
+ aliases(aliases) {
2996
+ if (aliases === void 0) return this._aliases;
2997
+ aliases.forEach((alias) => this.alias(alias));
2998
+ return this;
2999
+ }
3000
+ /**
3001
+ * Set / get the command usage `str`.
3002
+ *
3003
+ * @param {string} [str]
3004
+ * @return {(string|Command)}
3005
+ */
3006
+ usage(str) {
3007
+ if (str === void 0) {
3008
+ if (this._usage) return this._usage;
3009
+ const args = this.registeredArguments.map((arg) => {
3010
+ return humanReadableArgName(arg);
3011
+ });
3012
+ return [].concat(
3013
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3014
+ this.commands.length ? "[command]" : [],
3015
+ this.registeredArguments.length ? args : []
3016
+ ).join(" ");
3017
+ }
3018
+ this._usage = str;
3019
+ return this;
3020
+ }
3021
+ /**
3022
+ * Get or set the name of the command.
3023
+ *
3024
+ * @param {string} [str]
3025
+ * @return {(string|Command)}
3026
+ */
3027
+ name(str) {
3028
+ if (str === void 0) return this._name;
3029
+ this._name = str;
3030
+ return this;
3031
+ }
3032
+ /**
3033
+ * Set the name of the command from script filename, such as process.argv[1],
3034
+ * or require.main.filename, or __filename.
3035
+ *
3036
+ * (Used internally and public although not documented in README.)
3037
+ *
3038
+ * @example
3039
+ * program.nameFromFilename(require.main.filename);
3040
+ *
3041
+ * @param {string} filename
3042
+ * @return {Command}
3043
+ */
3044
+ nameFromFilename(filename) {
3045
+ this._name = path4.basename(filename, path4.extname(filename));
3046
+ return this;
3047
+ }
3048
+ /**
3049
+ * Get or set the directory for searching for executable subcommands of this command.
3050
+ *
3051
+ * @example
3052
+ * program.executableDir(__dirname);
3053
+ * // or
3054
+ * program.executableDir('subcommands');
3055
+ *
3056
+ * @param {string} [path]
3057
+ * @return {(string|null|Command)}
3058
+ */
3059
+ executableDir(path5) {
3060
+ if (path5 === void 0) return this._executableDir;
3061
+ this._executableDir = path5;
3062
+ return this;
3063
+ }
3064
+ /**
3065
+ * Return program help documentation.
3066
+ *
3067
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3068
+ * @return {string}
3069
+ */
3070
+ helpInformation(contextOptions) {
3071
+ const helper = this.createHelp();
3072
+ const context = this._getOutputContext(contextOptions);
3073
+ helper.prepareContext({
3074
+ error: context.error,
3075
+ helpWidth: context.helpWidth,
3076
+ outputHasColors: context.hasColors
3077
+ });
3078
+ const text = helper.formatHelp(this, helper);
3079
+ if (context.hasColors) return text;
3080
+ return this._outputConfiguration.stripColor(text);
3081
+ }
3082
+ /**
3083
+ * @typedef HelpContext
3084
+ * @type {object}
3085
+ * @property {boolean} error
3086
+ * @property {number} helpWidth
3087
+ * @property {boolean} hasColors
3088
+ * @property {function} write - includes stripColor if needed
3089
+ *
3090
+ * @returns {HelpContext}
3091
+ * @private
3092
+ */
3093
+ _getOutputContext(contextOptions) {
3094
+ contextOptions = contextOptions || {};
3095
+ const error2 = !!contextOptions.error;
3096
+ let baseWrite;
3097
+ let hasColors;
3098
+ let helpWidth;
3099
+ if (error2) {
3100
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3101
+ hasColors = this._outputConfiguration.getErrHasColors();
3102
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3103
+ } else {
3104
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3105
+ hasColors = this._outputConfiguration.getOutHasColors();
3106
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3107
+ }
3108
+ const write = (str) => {
3109
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3110
+ return baseWrite(str);
3111
+ };
3112
+ return { error: error2, write, hasColors, helpWidth };
3113
+ }
3114
+ /**
3115
+ * Output help information for this command.
3116
+ *
3117
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3118
+ *
3119
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3120
+ */
3121
+ outputHelp(contextOptions) {
3122
+ let deprecatedCallback;
3123
+ if (typeof contextOptions === "function") {
3124
+ deprecatedCallback = contextOptions;
3125
+ contextOptions = void 0;
3126
+ }
3127
+ const outputContext = this._getOutputContext(contextOptions);
3128
+ const eventContext = {
3129
+ error: outputContext.error,
3130
+ write: outputContext.write,
3131
+ command: this
3132
+ };
3133
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3134
+ this.emit("beforeHelp", eventContext);
3135
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3136
+ if (deprecatedCallback) {
3137
+ helpInformation = deprecatedCallback(helpInformation);
3138
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3139
+ throw new Error("outputHelp callback must return a string or a Buffer");
3140
+ }
3141
+ }
3142
+ outputContext.write(helpInformation);
3143
+ if (this._getHelpOption()?.long) {
3144
+ this.emit(this._getHelpOption().long);
3145
+ }
3146
+ this.emit("afterHelp", eventContext);
3147
+ this._getCommandAndAncestors().forEach(
3148
+ (command) => command.emit("afterAllHelp", eventContext)
3149
+ );
3150
+ }
3151
+ /**
3152
+ * You can pass in flags and a description to customise the built-in help option.
3153
+ * Pass in false to disable the built-in help option.
3154
+ *
3155
+ * @example
3156
+ * program.helpOption('-?, --help' 'show help'); // customise
3157
+ * program.helpOption(false); // disable
3158
+ *
3159
+ * @param {(string | boolean)} flags
3160
+ * @param {string} [description]
3161
+ * @return {Command} `this` command for chaining
3162
+ */
3163
+ helpOption(flags, description) {
3164
+ if (typeof flags === "boolean") {
3165
+ if (flags) {
3166
+ this._helpOption = this._helpOption ?? void 0;
3167
+ } else {
3168
+ this._helpOption = null;
3169
+ }
3170
+ return this;
3171
+ }
3172
+ flags = flags ?? "-h, --help";
3173
+ description = description ?? "display help for command";
3174
+ this._helpOption = this.createOption(flags, description);
3175
+ return this;
3176
+ }
3177
+ /**
3178
+ * Lazy create help option.
3179
+ * Returns null if has been disabled with .helpOption(false).
3180
+ *
3181
+ * @returns {(Option | null)} the help option
3182
+ * @package
3183
+ */
3184
+ _getHelpOption() {
3185
+ if (this._helpOption === void 0) {
3186
+ this.helpOption(void 0, void 0);
3187
+ }
3188
+ return this._helpOption;
3189
+ }
3190
+ /**
3191
+ * Supply your own option to use for the built-in help option.
3192
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3193
+ *
3194
+ * @param {Option} option
3195
+ * @return {Command} `this` command for chaining
3196
+ */
3197
+ addHelpOption(option) {
3198
+ this._helpOption = option;
3199
+ return this;
3200
+ }
3201
+ /**
3202
+ * Output help information and exit.
3203
+ *
3204
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3205
+ *
3206
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3207
+ */
3208
+ help(contextOptions) {
3209
+ this.outputHelp(contextOptions);
3210
+ let exitCode = Number(process2.exitCode ?? 0);
3211
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3212
+ exitCode = 1;
3213
+ }
3214
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3215
+ }
3216
+ /**
3217
+ * // Do a little typing to coordinate emit and listener for the help text events.
3218
+ * @typedef HelpTextEventContext
3219
+ * @type {object}
3220
+ * @property {boolean} error
3221
+ * @property {Command} command
3222
+ * @property {function} write
3223
+ */
3224
+ /**
3225
+ * Add additional text to be displayed with the built-in help.
3226
+ *
3227
+ * Position is 'before' or 'after' to affect just this command,
3228
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3229
+ *
3230
+ * @param {string} position - before or after built-in help
3231
+ * @param {(string | Function)} text - string to add, or a function returning a string
3232
+ * @return {Command} `this` command for chaining
3233
+ */
3234
+ addHelpText(position, text) {
3235
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3236
+ if (!allowedValues.includes(position)) {
3237
+ throw new Error(`Unexpected value for position to addHelpText.
3238
+ Expecting one of '${allowedValues.join("', '")}'`);
3239
+ }
3240
+ const helpEvent = `${position}Help`;
3241
+ this.on(helpEvent, (context) => {
3242
+ let helpStr;
3243
+ if (typeof text === "function") {
3244
+ helpStr = text({ error: context.error, command: context.command });
3245
+ } else {
3246
+ helpStr = text;
3247
+ }
3248
+ if (helpStr) {
3249
+ context.write(`${helpStr}
3250
+ `);
3251
+ }
3252
+ });
3253
+ return this;
3254
+ }
3255
+ /**
3256
+ * Output help information if help flags specified
3257
+ *
3258
+ * @param {Array} args - array of options to search for help flags
3259
+ * @private
3260
+ */
3261
+ _outputHelpIfRequested(args) {
3262
+ const helpOption = this._getHelpOption();
3263
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3264
+ if (helpRequested) {
3265
+ this.outputHelp();
3266
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3267
+ }
3268
+ }
3269
+ };
3270
+ function incrementNodeInspectorPort(args) {
3271
+ return args.map((arg) => {
3272
+ if (!arg.startsWith("--inspect")) {
3273
+ return arg;
3274
+ }
3275
+ let debugOption;
3276
+ let debugHost = "127.0.0.1";
3277
+ let debugPort = "9229";
3278
+ let match;
3279
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3280
+ debugOption = match[1];
3281
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3282
+ debugOption = match[1];
3283
+ if (/^\d+$/.test(match[3])) {
3284
+ debugPort = match[3];
3285
+ } else {
3286
+ debugHost = match[3];
3287
+ }
3288
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3289
+ debugOption = match[1];
3290
+ debugHost = match[3];
3291
+ debugPort = match[4];
3292
+ }
3293
+ if (debugOption && debugPort !== "0") {
3294
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3295
+ }
3296
+ return arg;
3297
+ });
3298
+ }
3299
+ function useColor() {
3300
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3301
+ return false;
3302
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3303
+ return true;
3304
+ return void 0;
3305
+ }
3306
+ exports.Command = Command2;
3307
+ exports.useColor = useColor;
3308
+ }
3309
+ });
3310
+
3311
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js
3312
+ var require_commander = __commonJS({
3313
+ "node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports) {
3314
+ var { Argument: Argument2 } = require_argument();
3315
+ var { Command: Command2 } = require_command();
3316
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3317
+ var { Help: Help2 } = require_help();
3318
+ var { Option: Option2 } = require_option();
3319
+ exports.program = new Command2();
3320
+ exports.createCommand = (name) => new Command2(name);
3321
+ exports.createOption = (flags, description) => new Option2(flags, description);
3322
+ exports.createArgument = (name, description) => new Argument2(name, description);
3323
+ exports.Command = Command2;
3324
+ exports.Option = Option2;
3325
+ exports.Argument = Argument2;
3326
+ exports.Help = Help2;
3327
+ exports.CommanderError = CommanderError2;
3328
+ exports.InvalidArgumentError = InvalidArgumentError2;
3329
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3330
+ }
3331
+ });
3332
+
3333
+ // node_modules/.pnpm/commander@13.1.0/node_modules/commander/esm.mjs
3334
+ var import_index = __toESM(require_commander(), 1);
3335
+ var {
3336
+ program,
3337
+ createCommand,
3338
+ createArgument,
3339
+ createOption,
3340
+ CommanderError,
3341
+ InvalidArgumentError,
3342
+ InvalidOptionArgumentError,
3343
+ // deprecated old name
3344
+ Command,
3345
+ Argument,
3346
+ Option,
3347
+ Help
3348
+ } = import_index.default;
3349
+
3350
+ // packages/cli/src/util/repo.ts
3351
+ import { readFile } from "fs/promises";
3352
+ import { existsSync } from "fs";
3353
+ import { resolve, dirname, basename } from "path";
3354
+ function findGitRoot(from) {
3355
+ let dir = resolve(from);
3356
+ while (true) {
3357
+ if (existsSync(resolve(dir, ".git"))) return dir;
3358
+ const parent = dirname(dir);
3359
+ if (parent === dir) return null;
3360
+ dir = parent;
3361
+ }
3362
+ }
3363
+ async function parseRemoteUrl(gitRoot) {
3364
+ try {
3365
+ const config = await readFile(resolve(gitRoot, ".git/config"), "utf-8");
3366
+ const match = config.match(/\[remote "origin"\][^[]*url\s*=\s*(.+)/m);
3367
+ return match?.[1]?.trim();
3368
+ } catch {
3369
+ return void 0;
3370
+ }
3371
+ }
3372
+ async function detectRepo(cwd = process.cwd()) {
3373
+ const root = findGitRoot(cwd);
3374
+ if (!root) {
3375
+ throw new Error("Not inside a git repository. Run from a git repo or use `git init`.");
3376
+ }
3377
+ const remote_url = await parseRemoteUrl(root);
3378
+ const name = basename(root);
3379
+ return { root_path: root, name, remote_url };
3380
+ }
3381
+
3382
+ // packages/cli/src/util/client.ts
3383
+ var BASE_URL = process.env.LENS_HOST ?? "http://127.0.0.1:4111";
3384
+ var VERBOSE = process.env.LENS_VERBOSE === "1" || process.argv.includes("--verbose") || process.argv.includes("-v");
3385
+ function sleep(ms) {
3386
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
3387
+ }
3388
+ var DaemonError = class extends Error {
3389
+ constructor(status, body) {
3390
+ super(`Daemon returned ${status}`);
3391
+ this.status = status;
3392
+ this.body = body;
3393
+ this.name = "DaemonError";
3394
+ }
3395
+ };
3396
+ async function request(method, path4, body, retries = 3) {
3397
+ const url = `${BASE_URL}${path4}`;
3398
+ if (VERBOSE) {
3399
+ process.stderr.write(`[LENS] ${method} ${url}
3400
+ `);
3401
+ }
3402
+ for (let i = 0; i < retries; i++) {
3403
+ let res;
3404
+ try {
3405
+ res = await fetch(url, {
3406
+ method,
3407
+ headers: body ? { "Content-Type": "application/json" } : void 0,
3408
+ body: body ? JSON.stringify(body) : void 0,
3409
+ signal: AbortSignal.timeout(6e4)
3410
+ // 60s timeout
3411
+ });
3412
+ } catch (err) {
3413
+ if (err.code === "ECONNREFUSED") {
3414
+ throw new Error("LENS daemon is not running. Start with: lens start");
3415
+ }
3416
+ if (i === retries - 1) throw err;
3417
+ await sleep(500);
3418
+ continue;
3419
+ }
3420
+ const data = await res.json();
3421
+ if (VERBOSE) {
3422
+ process.stderr.write(`[LENS] ${res.status} ${res.statusText}
3423
+ `);
3424
+ }
3425
+ if (!res.ok) {
3426
+ throw new DaemonError(res.status, data);
3427
+ }
3428
+ return data;
3429
+ }
3430
+ throw new Error("fetch failed");
3431
+ }
3432
+ var get = (path4) => request("GET", path4);
3433
+ var post = (path4, body) => request("POST", path4, body);
3434
+
3435
+ // packages/cli/src/util/format.ts
3436
+ function output(data, json) {
3437
+ if (json) {
3438
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
3439
+ } else if (typeof data === "string") {
3440
+ process.stdout.write(data + "\n");
3441
+ } else {
3442
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
3443
+ }
3444
+ }
3445
+ function error(msg) {
3446
+ process.stderr.write(`Error: ${msg}
3447
+ `);
3448
+ }
3449
+
3450
+ // packages/cli/src/util/inject-claude-md.ts
3451
+ import fs2 from "fs/promises";
3452
+ import path2 from "path";
3453
+
3454
+ // packages/cli/src/util/config.ts
3455
+ import fs from "fs/promises";
3456
+ import fsSync from "fs";
3457
+ import path from "path";
3458
+ import os from "os";
3459
+ import { randomUUID } from "crypto";
3460
+ var CONFIG_DIR = path.join(os.homedir(), ".lens");
3461
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
3462
+ var DEFAULTS = {
3463
+ inject_behavior: "always",
3464
+ show_progress: true
3465
+ };
3466
+ async function readConfig() {
3467
+ try {
3468
+ const raw = await fs.readFile(CONFIG_FILE, "utf-8");
3469
+ return { ...DEFAULTS, ...JSON.parse(raw) };
3470
+ } catch {
3471
+ return DEFAULTS;
3472
+ }
3473
+ }
3474
+ async function writeConfig(config) {
3475
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
3476
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
3477
+ }
3478
+ async function configGet(key) {
3479
+ const config = await readConfig();
3480
+ if (key in config) {
3481
+ return JSON.stringify(config[key], null, 2);
3482
+ }
3483
+ return "null";
3484
+ }
3485
+ async function configSet(key, value) {
3486
+ const config = await readConfig();
3487
+ if (key === "inject_behavior" && ["always", "skip", "once"].includes(value)) {
3488
+ config.inject_behavior = value;
3489
+ } else if (key === "show_progress") {
3490
+ config.show_progress = value === "true";
3491
+ } else if (key === "cloud_url") {
3492
+ config.cloud_url = value;
3493
+ } else if (key === "telemetry") {
3494
+ config.telemetry = value === "true";
3495
+ } else {
3496
+ throw new Error(`Invalid config: ${key}=${value}`);
3497
+ }
3498
+ await writeConfig(config);
3499
+ }
3500
+ function getCloudUrl() {
3501
+ if (process.env.LENS_CLOUD_URL) return process.env.LENS_CLOUD_URL;
3502
+ try {
3503
+ const cfg2 = JSON.parse(fsSync.readFileSync(CONFIG_FILE, "utf-8"));
3504
+ if (cfg2.cloud_url) return cfg2.cloud_url;
3505
+ } catch {
3506
+ }
3507
+ return "https://lens.dev";
3508
+ }
3509
+ function readConfigSync() {
3510
+ try {
3511
+ return { ...DEFAULTS, ...JSON.parse(fsSync.readFileSync(CONFIG_FILE, "utf-8")) };
3512
+ } catch {
3513
+ return DEFAULTS;
3514
+ }
3515
+ }
3516
+ function isTelemetryEnabled() {
3517
+ const config = readConfigSync();
3518
+ return config.telemetry !== false;
3519
+ }
3520
+
3521
+ // packages/cli/src/util/inject-claude-md.ts
3522
+ var RLM_MARKER = "lens context";
3523
+ var CANDIDATE_PATHS = ["CLAUDE.md", "agents.md", "AGENTS.md", ".CLAUDE.md", ".agents.md", ".AGENTS.md"];
3524
+ async function findTargetFile(repoRoot) {
3525
+ for (const relPath of CANDIDATE_PATHS) {
3526
+ const fullPath = path2.join(repoRoot, relPath);
3527
+ try {
3528
+ await fs2.access(fullPath);
3529
+ return fullPath;
3530
+ } catch {
3531
+ continue;
3532
+ }
3533
+ }
3534
+ return null;
3535
+ }
3536
+ async function injectClaudeMd(repoRoot) {
3537
+ const existingFile = await findTargetFile(repoRoot);
3538
+ const targetFile = existingFile ?? path2.join(repoRoot, "CLAUDE.md");
3539
+ let existingContent = "";
3540
+ try {
3541
+ existingContent = await fs2.readFile(targetFile, "utf-8");
3542
+ if (existingContent.toLowerCase().includes(RLM_MARKER)) {
3543
+ return;
3544
+ }
3545
+ } catch {
3546
+ }
3547
+ const config = await readConfig();
3548
+ if (existingFile && config.inject_behavior === "once") {
3549
+ return;
3550
+ }
3551
+ if (config.inject_behavior === "skip") {
3552
+ return;
3553
+ }
3554
+ const { content } = await get("/repo/template");
3555
+ if (existingContent) {
3556
+ await fs2.writeFile(targetFile, `${content}
3557
+
3558
+ ${existingContent}`);
3559
+ } else {
3560
+ await fs2.writeFile(targetFile, content);
3561
+ }
3562
+ }
3563
+
3564
+ // packages/cli/src/util/inject-mcp.ts
3565
+ import { existsSync as existsSync2, readFileSync, writeFileSync } from "fs";
3566
+ import { join } from "path";
3567
+ var MCP_ENTRY = {
3568
+ command: "npx",
3569
+ args: ["lens-daemon", "--stdio"]
3570
+ };
3571
+ function injectMcp(repoRoot) {
3572
+ const mcpPath = join(repoRoot, ".mcp.json");
3573
+ let existing = {};
3574
+ if (existsSync2(mcpPath)) {
3575
+ try {
3576
+ existing = JSON.parse(readFileSync(mcpPath, "utf-8"));
3577
+ } catch {
3578
+ }
3579
+ }
3580
+ if (!existing.mcpServers) existing.mcpServers = {};
3581
+ const servers = existing.mcpServers;
3582
+ if (servers.lens) return "exists";
3583
+ const isNew = !existsSync2(mcpPath);
3584
+ servers.lens = MCP_ENTRY;
3585
+ writeFileSync(mcpPath, `${JSON.stringify(existing, null, 2)}
3586
+ `);
3587
+ return isNew ? "created" : "updated";
3588
+ }
3589
+
3590
+ // packages/cli/src/util/progress.ts
3591
+ var dim = (s) => `\x1B[2m${s}\x1B[0m`;
3592
+ var green = (s) => `\x1B[32m${s}\x1B[0m`;
3593
+ var cyan = (s) => `\x1B[36m${s}\x1B[0m`;
3594
+ var red = (s) => `\x1B[31m${s}\x1B[0m`;
3595
+ var yellow = (s) => `\x1B[33m${s}\x1B[0m`;
3596
+ var bold = (s) => `\x1B[1m${s}\x1B[0m`;
3597
+ var MAX_CONN_FAILURES = 5;
3598
+ var TOTAL_LINES = 18;
3599
+ var POLL_INTERVAL = 5e3;
3600
+ var RENDER_INTERVAL = 33;
3601
+ async function showProgress(repoId, name, timeoutMs = 18e5) {
3602
+ const start = Date.now();
3603
+ const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
3604
+ let frame = 0;
3605
+ let connFailures = 0;
3606
+ let lastRendered = "";
3607
+ let data = null;
3608
+ let done = false;
3609
+ const poll = async () => {
3610
+ while (!done && Date.now() - start < timeoutMs) {
3611
+ try {
3612
+ data = await get(`/repo/${repoId}/status`);
3613
+ connFailures = 0;
3614
+ } catch {
3615
+ connFailures++;
3616
+ if (connFailures >= MAX_CONN_FAILURES) {
3617
+ process.stdout.write(
3618
+ `
3619
+ ${red("\u2717")} ${bold("Daemon unavailable")} \u2014 ${dim("connection lost after " + connFailures + " retries")}
3620
+ `
3621
+ );
3622
+ process.stdout.write(` ${dim("Restart with: lens start")}
3623
+
3624
+ `);
3625
+ process.exit(1);
3626
+ }
3627
+ }
3628
+ await sleep2(POLL_INTERVAL);
3629
+ }
3630
+ };
3631
+ poll();
3632
+ while (!data && Date.now() - start < timeoutMs) {
3633
+ await sleep2(100);
3634
+ }
3635
+ if (!data) return;
3636
+ while (Date.now() - start < timeoutMs) {
3637
+ const s = data;
3638
+ const f = frames[frame % frames.length];
3639
+ const indexing = s.index_status === "indexing";
3640
+ const hasCaps = s.has_capabilities !== false;
3641
+ const lines = [];
3642
+ lines.push(``);
3643
+ if (indexing) {
3644
+ const elapsed = Math.round((Date.now() - start) / 1e3);
3645
+ lines.push(` ${bold("\u26A1 Indexing")} ${dim(name)} ${dim(`${elapsed}s`)}`);
3646
+ } else {
3647
+ lines.push(` ${bold("\u26A1 Indexing")} ${dim(name)}`);
3648
+ }
3649
+ lines.push(dim(` ${"\u2500".repeat(40)}`));
3650
+ if (indexing) {
3651
+ lines.push(` ${cyan(f)} Chunks ${dim(s.chunk_count > 0 ? s.chunk_count.toLocaleString() : "...")}`);
3652
+ lines.push(` ${dim("\u25CB")} Metadata ${dim("...")}`);
3653
+ lines.push(` ${dim("\u25CB")} Git history ${dim("...")}`);
3654
+ lines.push(` ${dim("\u25CB")} Import graph ${dim("...")}`);
3655
+ lines.push(` ${dim("\u25CB")} Co-changes ${dim("...")}`);
3656
+ if (hasCaps) {
3657
+ lines.push(` ${dim("\u25CB")} Vocab clusters ${dim("...")}`);
3658
+ lines.push(` ${dim("\u25CB")} Embeddings ${dim("...")}`);
3659
+ lines.push(` ${dim("\u25CB")} Summaries ${dim("...")}`);
3660
+ } else {
3661
+ lines.push(``);
3662
+ lines.push(` ${yellow("\u26A1")} ${bold("Pro")}`);
3663
+ lines.push(` ${dim("\xB7 Vocab clusters")}`);
3664
+ lines.push(` ${dim("\xB7 Embeddings")}`);
3665
+ lines.push(` ${dim("\xB7 Summaries")}`);
3666
+ lines.push(` ${dim("lens login \u2192 upgrade to enable")}`);
3667
+ }
3668
+ } else {
3669
+ lines.push(
3670
+ ` ${s.chunk_count > 0 ? green("\u2713") : cyan(f)} Chunks ${dim(s.chunk_count > 0 ? s.chunk_count.toLocaleString() : "scanning...")}`
3671
+ );
3672
+ lines.push(
3673
+ ` ${s.metadata_count > 0 ? green("\u2713") : cyan(f)} Metadata ${dim(s.metadata_count > 0 ? `${s.metadata_count.toLocaleString()} files` : "extracting...")}`
3674
+ );
3675
+ lines.push(
3676
+ ` ${s.git_commits_analyzed > 0 ? green("\u2713") : cyan(f)} Git history ${dim(s.git_commits_analyzed > 0 ? `${s.git_commits_analyzed.toLocaleString()} files` : "analyzing...")}`
3677
+ );
3678
+ lines.push(
3679
+ ` ${s.import_edge_count > 0 ? green("\u2713") : cyan(f)} Import graph ${dim(s.import_edge_count > 0 ? `${s.import_edge_count.toLocaleString()} edges` : "building...")}`
3680
+ );
3681
+ lines.push(
3682
+ ` ${s.cochange_pairs > 0 ? green("\u2713") : dim("\u25CB")} Co-changes ${dim(s.cochange_pairs > 0 ? `${s.cochange_pairs.toLocaleString()} pairs` : "...")}`
3683
+ );
3684
+ if (hasCaps) {
3685
+ if (s.vocab_cluster_count > 0) {
3686
+ lines.push(` ${green("\u2713")} Vocab clusters ${dim(`${s.vocab_cluster_count} clusters`)}`);
3687
+ } else {
3688
+ lines.push(` ${cyan(f)} Vocab clusters ${dim("building...")}`);
3689
+ }
3690
+ const embDone = s.embedded_count >= s.embeddable_count && s.embeddable_count > 0;
3691
+ if (embDone) {
3692
+ lines.push(` ${green("\u2713")} Embeddings ${dim(`${s.embedded_count}/${s.embeddable_count} code chunks`)}`);
3693
+ } else if (s.embedding_quota_exceeded) {
3694
+ lines.push(` ${yellow("\u26A0")} Embeddings ${dim(`quota exceeded \u2014 ${s.embedded_count}/${s.embeddable_count}`)}`);
3695
+ } else if (s.embeddable_count === 0) {
3696
+ lines.push(` ${dim("\u25CB")} Embeddings ${dim("no code chunks")}`);
3697
+ } else {
3698
+ lines.push(
3699
+ ` ${cyan(f)} Embeddings ${createBar(s.embedded_pct, 20)} ${dim(`${s.embedded_count}/${s.embeddable_count}`)}`
3700
+ );
3701
+ }
3702
+ const sumDone = s.purpose_count >= s.purpose_total && s.purpose_total > 0;
3703
+ if (sumDone) {
3704
+ lines.push(` ${green("\u2713")} Summaries ${dim(`${s.purpose_count}/${s.purpose_total} files`)}`);
3705
+ } else if (s.purpose_quota_exceeded) {
3706
+ lines.push(` ${yellow("\u26A0")} Summaries ${dim(`quota exceeded \u2014 ${s.purpose_count}/${s.purpose_total}`)}`);
3707
+ } else if (s.purpose_total > 0) {
3708
+ lines.push(
3709
+ ` ${cyan(f)} Summaries ${createBar(Math.round(s.purpose_count / s.purpose_total * 100), 20)} ${dim(`${s.purpose_count}/${s.purpose_total}`)}`
3710
+ );
3711
+ } else {
3712
+ lines.push(` ${dim("\u25CB")} Summaries ${dim("...")}`);
3713
+ }
3714
+ } else {
3715
+ lines.push(``);
3716
+ lines.push(` ${yellow("\u26A1")} ${bold("Pro")}`);
3717
+ lines.push(` ${dim("\xB7 Vocab clusters")}`);
3718
+ lines.push(` ${dim("\xB7 Embeddings")}`);
3719
+ lines.push(` ${dim("\xB7 Summaries")}`);
3720
+ lines.push(` ${dim("lens login \u2192 upgrade to enable")}`);
3721
+ }
3722
+ }
3723
+ const structuralDone = !indexing && s.metadata_count > 0 && s.chunk_count > 0 && s.git_commits_analyzed > 0 && s.import_edge_count > 0;
3724
+ let allDone;
3725
+ if (hasCaps) {
3726
+ const embDone = s.embedded_count >= s.embeddable_count && s.embeddable_count > 0 || s.embeddable_count === 0 || !!s.embedding_quota_exceeded;
3727
+ const sumDone = s.purpose_count >= s.purpose_total && s.purpose_total > 0 || !!s.purpose_quota_exceeded;
3728
+ allDone = structuralDone && embDone && sumDone;
3729
+ } else {
3730
+ allDone = structuralDone;
3731
+ }
3732
+ lines.push(``);
3733
+ if (indexing) {
3734
+ lines.push(` ${dim("Runs in background \u2014 Ctrl+C to exit")}`);
3735
+ lines.push(` ${dim("Check progress:")} ${cyan("lens status")}`);
3736
+ } else if (allDone) {
3737
+ lines.push(` ${green("\u2713")} ${bold("Ready")} \u2014 ${cyan('lens context "<goal>"')}`);
3738
+ lines.push(``);
3739
+ } else if (structuralDone) {
3740
+ lines.push(` ${green("\u2713")} ${bold("Ready")} \u2014 ${cyan('lens context "<goal>"')}`);
3741
+ if (hasCaps) {
3742
+ lines.push(` ${dim("Background tasks continue \u2014 Ctrl+C to exit, check:")} ${cyan("lens status")}`);
3743
+ } else {
3744
+ lines.push(``);
3745
+ }
3746
+ } else {
3747
+ lines.push(` ${dim("Runs in background \u2014 Ctrl+C to exit")}`);
3748
+ lines.push(` ${dim("Check progress:")} ${cyan("lens status")}`);
3749
+ }
3750
+ while (lines.length < TOTAL_LINES) lines.push(``);
3751
+ const output2 = lines.join("\n");
3752
+ if (lastRendered) {
3753
+ process.stdout.write(`\x1B[${TOTAL_LINES}A\x1B[J`);
3754
+ }
3755
+ process.stdout.write(output2 + "\n");
3756
+ lastRendered = output2;
3757
+ if (allDone) {
3758
+ done = true;
3759
+ return;
3760
+ }
3761
+ frame++;
3762
+ await sleep2(RENDER_INTERVAL);
3763
+ }
3764
+ }
3765
+ function createBar(pct, width) {
3766
+ const clamped = Math.min(pct, 100);
3767
+ const filled = Math.round(clamped / 100 * width);
3768
+ const bar = "\u2588".repeat(filled) + "\u2591".repeat(width - filled);
3769
+ return `\x1B[32m${bar}\x1B[0m`;
3770
+ }
3771
+ function sleep2(ms) {
3772
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
3773
+ }
3774
+
3775
+ // packages/cli/src/commands/register.ts
3776
+ async function registerCommand(opts) {
3777
+ const info = await detectRepo();
3778
+ const res = await post("/repo/register", {
3779
+ root_path: info.root_path,
3780
+ name: info.name,
3781
+ remote_url: info.remote_url
3782
+ });
3783
+ if (opts.json) {
3784
+ output(res, true);
3785
+ return;
3786
+ }
3787
+ const mcpResult = injectMcp(info.root_path);
3788
+ if (res.created) {
3789
+ await injectClaudeMd(info.root_path);
3790
+ output(`Registered ${res.name} (repo_id: ${res.repo_id})`, false);
3791
+ if (mcpResult === "created" || mcpResult === "updated") {
3792
+ output(`Wrote .mcp.json \u2192 Claude Code will auto-discover LENS`, false);
3793
+ }
3794
+ const config = await readConfig();
3795
+ if (config.show_progress) {
3796
+ await showProgress(res.repo_id, res.name);
3797
+ } else {
3798
+ output(`Indexing started. Run \`lens status\` to check progress.`, false);
3799
+ }
3800
+ } else {
3801
+ output(`Already registered ${res.name} (repo_id: ${res.repo_id})`, false);
3802
+ if (mcpResult === "created" || mcpResult === "updated") {
3803
+ output(`Wrote .mcp.json \u2192 Claude Code will auto-discover LENS`, false);
3804
+ }
3805
+ if (opts.inject) {
3806
+ await injectClaudeMd(info.root_path);
3807
+ output(`Injected LENS instructions into CLAUDE.md`, false);
3808
+ }
3809
+ }
3810
+ }
3811
+
3812
+ // packages/cli/src/util/ensure-repo.ts
3813
+ async function ensureRepo() {
3814
+ const info = await detectRepo();
3815
+ const res = await post("/repo/register", {
3816
+ root_path: info.root_path,
3817
+ name: info.name,
3818
+ remote_url: info.remote_url
3819
+ });
3820
+ return { repo_id: res.repo_id, name: res.name, root_path: info.root_path };
3821
+ }
3822
+
3823
+ // packages/cli/src/commands/context.ts
3824
+ async function contextCommand(goal, opts) {
3825
+ const { repo_id } = await ensureRepo();
3826
+ const res = await post("/context", { repo_id, goal });
3827
+ if (opts.json) {
3828
+ output(res, true);
3829
+ } else {
3830
+ output(res.context_pack, false);
3831
+ }
3832
+ }
3833
+
3834
+ // packages/cli/src/commands/index.ts
3835
+ async function indexCommand(opts) {
3836
+ const { repo_id, name } = await ensureRepo();
3837
+ if (opts.status) {
3838
+ const s = await get(`/index/status/${repo_id}`);
3839
+ if (opts.json) {
3840
+ output(s, true);
3841
+ } else {
3842
+ const lines = [
3843
+ `## Index Status: ${name}`,
3844
+ `- **Status:** ${s.index_status}`,
3845
+ `- **Last commit:** ${s.last_indexed_commit ?? "never"}`,
3846
+ `- **Last indexed:** ${s.last_indexed_at ?? "never"}`,
3847
+ `- **Current HEAD:** ${s.current_head ?? "unknown"}`,
3848
+ `- **Stale:** ${s.is_stale}`,
3849
+ `- **Files:** ${s.files_indexed}`,
3850
+ `- **Chunks:** ${s.chunk_count}`,
3851
+ `- **Embeddings:** ${s.chunks_with_embeddings}`
3852
+ ];
3853
+ output(lines.join("\n"), false);
3854
+ }
3855
+ return;
3856
+ }
3857
+ if (opts.json) {
3858
+ const res = await post("/index/run", { repo_id, force: opts.force });
3859
+ output(res, true);
3860
+ return;
3861
+ }
3862
+ post("/index/run", { repo_id, force: opts.force }).catch(() => {
3863
+ });
3864
+ await showProgress(repo_id, name);
3865
+ }
3866
+
3867
+ // packages/cli/src/commands/status.ts
3868
+ var dim2 = (s) => `\x1B[2m${s}\x1B[0m`;
3869
+ var green2 = (s) => `\x1B[32m${s}\x1B[0m`;
3870
+ var yellow2 = (s) => `\x1B[33m${s}\x1B[0m`;
3871
+ var bold2 = (s) => `\x1B[1m${s}\x1B[0m`;
3872
+ async function statusCommand(opts) {
3873
+ const { repo_id, name } = await ensureRepo();
3874
+ const s = await get(`/repo/${repo_id}/status`);
3875
+ if (opts.json) {
3876
+ output(s, true);
3877
+ return;
3878
+ }
3879
+ const staleTag = s.is_stale ? yellow2(" STALE") : "";
3880
+ const check = green2("\u2713");
3881
+ const pending = dim2("\u25CB");
3882
+ const hasCaps = s.has_capabilities !== false;
3883
+ const lines = [
3884
+ ``,
3885
+ ` ${bold2(name)}${staleTag}`,
3886
+ dim2(` ${"\u2500".repeat(40)}`),
3887
+ ` ${s.chunk_count > 0 ? check : pending} Chunks ${dim2(s.chunk_count.toLocaleString())}`,
3888
+ ` ${s.metadata_count > 0 ? check : pending} Metadata ${dim2(`${s.metadata_count.toLocaleString()} files`)}`,
3889
+ ` ${s.git_commits_analyzed > 0 ? check : pending} Git history ${dim2(`${s.git_commits_analyzed.toLocaleString()} files`)}`,
3890
+ ` ${s.import_edge_count > 0 ? check : pending} Import graph ${dim2(`${s.import_edge_count.toLocaleString()} edges`)}`,
3891
+ ` ${s.cochange_pairs > 0 ? check : pending} Co-changes ${dim2(`${s.cochange_pairs.toLocaleString()} pairs`)}`
3892
+ ];
3893
+ if (hasCaps) {
3894
+ const warn = yellow2("\u26A0");
3895
+ const embDone = s.embedded_pct >= 100 || s.embedded_count >= s.embeddable_count && s.embeddable_count > 0;
3896
+ const embLabel = s.embedding_quota_exceeded ? `quota exceeded \u2014 ${s.embedded_count}/${s.embeddable_count}` : s.embeddable_count > 0 ? `${s.embedded_count}/${s.embeddable_count} code chunks (${s.embedded_pct}%)` : "no code chunks";
3897
+ const embIcon = s.embedding_quota_exceeded ? warn : embDone ? check : pending;
3898
+ const vocabLabel = s.vocab_cluster_count > 0 ? `${s.vocab_cluster_count} clusters` : "...";
3899
+ const vocabIcon = s.vocab_cluster_count > 0 ? check : pending;
3900
+ const purDone = s.purpose_count > 0 && s.purpose_count >= s.purpose_total;
3901
+ const purposeLabel = s.purpose_quota_exceeded ? `quota exceeded \u2014 ${s.purpose_count}/${s.purpose_total}` : s.purpose_total > 0 ? `${s.purpose_count}/${s.purpose_total} files` : "no files";
3902
+ const purposeIcon = s.purpose_quota_exceeded ? warn : purDone ? check : pending;
3903
+ lines.push(` ${vocabIcon} Vocab clust. ${dim2(vocabLabel)}`);
3904
+ lines.push(` ${embIcon} Embeddings ${dim2(embLabel)}`);
3905
+ lines.push(` ${purposeIcon} Summaries ${dim2(purposeLabel)}`);
3906
+ } else {
3907
+ lines.push(``);
3908
+ lines.push(` ${yellow2("\u26A1")} ${bold2("Pro")}`);
3909
+ lines.push(` ${dim2("\xB7 Vocab clusters")}`);
3910
+ lines.push(` ${dim2("\xB7 Embeddings")}`);
3911
+ lines.push(` ${dim2("\xB7 Summaries")}`);
3912
+ lines.push(` ${dim2("lens login \u2192 upgrade to enable")}`);
3913
+ }
3914
+ output(lines.join("\n"), false);
3915
+ }
3916
+
3917
+ // packages/cli/src/commands/list.ts
3918
+ async function listCommand(opts) {
3919
+ const res = await get("/repo/list/detailed");
3920
+ if (opts.json) {
3921
+ output(res, true);
3922
+ return;
3923
+ }
3924
+ if (res.repos.length === 0) {
3925
+ output("No repos registered. Run `lens repo register` to add one.", false);
3926
+ return;
3927
+ }
3928
+ const header = pad("ID", 10) + pad("Name", 20) + pad("Status", 10) + pad("Files", 8) + pad("Chunks", 10) + pad("Embed%", 8) + "Last Indexed";
3929
+ const sep = "-".repeat(header.length);
3930
+ const lines = [header, sep];
3931
+ for (const r of res.repos) {
3932
+ const id = r.id.slice(0, 8);
3933
+ const indexed = r.last_indexed_at ? timeAgo(r.last_indexed_at) : "never";
3934
+ lines.push(
3935
+ pad(id, 10) + pad(r.name, 20) + pad(r.index_status, 10) + pad(String(r.files_indexed), 8) + pad(r.chunk_count.toLocaleString(), 10) + pad(`${r.embedded_pct}%`, 8) + indexed
3936
+ );
3937
+ }
3938
+ output(lines.join("\n"), false);
3939
+ }
3940
+ function pad(s, width) {
3941
+ return s.length >= width ? s.slice(0, width - 1) + " " : s + " ".repeat(width - s.length);
3942
+ }
3943
+ function timeAgo(iso) {
3944
+ const diff = Date.now() - new Date(iso).getTime();
3945
+ const mins = Math.floor(diff / 6e4);
3946
+ if (mins < 1) return "just now";
3947
+ if (mins < 60) return `${mins}m ago`;
3948
+ const hours = Math.floor(mins / 60);
3949
+ if (hours < 24) return `${hours}h ago`;
3950
+ const days = Math.floor(hours / 24);
3951
+ return `${days}d ago`;
3952
+ }
3953
+
3954
+ // packages/cli/src/commands/remove.ts
3955
+ async function removeCommand(opts) {
3956
+ const { repo_id, name } = await ensureRepo();
3957
+ if (!opts.yes) {
3958
+ process.stderr.write(`Remove "${name}" (${repo_id})? All index data will be deleted.
3959
+ `);
3960
+ process.stderr.write(`Re-run with --yes to confirm.
3961
+ `);
3962
+ process.exit(1);
3963
+ }
3964
+ const spinner = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
3965
+ let i = 0;
3966
+ let phase = "Stopping watcher";
3967
+ const interval = setInterval(() => {
3968
+ const frame = spinner[i % spinner.length];
3969
+ process.stdout.write(`\r${frame} ${phase}...`);
3970
+ i++;
3971
+ }, 80);
3972
+ await new Promise((r) => setTimeout(r, 200));
3973
+ phase = `Removing ${name}`;
3974
+ const res = await request("DELETE", `/repo/${repo_id}`);
3975
+ clearInterval(interval);
3976
+ if (opts.json) {
3977
+ output(res, true);
3978
+ } else {
3979
+ process.stdout.write(`\r\u2713 Removed ${name}: ${res.chunks_removed} chunks deleted
3980
+ `);
3981
+ }
3982
+ }
3983
+
3984
+ // packages/cli/src/commands/daemon-stats.ts
3985
+ async function daemonStatsCommand(opts) {
3986
+ const s = await get("/daemon/stats");
3987
+ if (opts.json) {
3988
+ output(s, true);
3989
+ return;
3990
+ }
3991
+ const embedPct = s.total_chunks > 0 ? Math.round(s.total_embeddings / s.total_chunks * 100) : 0;
3992
+ const maintResult = s.last_maintenance_result ? `${s.last_maintenance_result.processed} processed, ${s.last_maintenance_result.errors} errors` : "\u2014";
3993
+ const lines = [
3994
+ "## LENS Daemon",
3995
+ "",
3996
+ ` Repos: ${s.repos_count}`,
3997
+ ` Chunks: ${s.total_chunks.toLocaleString()}`,
3998
+ ` Embeddings: ${s.total_embeddings.toLocaleString()} (${embedPct}%)`,
3999
+ ` DB Size: ${s.db_size_mb} MB`,
4000
+ "",
4001
+ " ## Maintenance Cron",
4002
+ ` Last maintenance: ${s.last_maintenance_at ?? "never"}`,
4003
+ ` Next maintenance: ${s.next_maintenance_at ?? "\u2014"}`,
4004
+ ` Last result: ${maintResult}`
4005
+ ];
4006
+ output(lines.join("\n"), false);
4007
+ }
4008
+
4009
+ // packages/cli/src/commands/watch.ts
4010
+ async function watchCommand(opts) {
4011
+ const { repo_id, name } = await ensureRepo();
4012
+ const res = await post("/index/watch", { repo_id });
4013
+ if (opts.json) {
4014
+ output(res, true);
4015
+ } else if (res.already_watching) {
4016
+ output(`${name} is already being watched`, false);
4017
+ } else {
4018
+ output(`File watcher started for ${name}`, false);
4019
+ }
4020
+ }
4021
+ async function unwatchCommand(opts) {
4022
+ const { repo_id, name } = await ensureRepo();
4023
+ const res = await post("/index/unwatch", { repo_id });
4024
+ if (opts.json) {
4025
+ output(res, true);
4026
+ } else if (res.stopped) {
4027
+ output(`File watcher stopped for ${name}`, false);
4028
+ } else {
4029
+ output(`${name} was not being watched`, false);
4030
+ }
4031
+ }
4032
+ async function watchStatusCommand(opts) {
4033
+ const { repo_id, name } = await ensureRepo();
4034
+ const res = await get(`/index/watch-status/${repo_id}`);
4035
+ if (opts.json) {
4036
+ output(res, true);
4037
+ } else if (res.watching) {
4038
+ output(
4039
+ `${name}: watching since ${res.started_at}
4040
+ Changed: ${res.changed_files} files | Deleted: ${res.deleted_files} files`,
4041
+ false
4042
+ );
4043
+ } else {
4044
+ output(`${name}: not watching. Run \`lens repo watch\` to start.`, false);
4045
+ }
4046
+ }
4047
+
4048
+ // packages/cli/src/commands/config.ts
4049
+ async function configGetCommand(key) {
4050
+ try {
4051
+ const value = await configGet(key);
4052
+ output(value, false);
4053
+ } catch (err) {
4054
+ output(err instanceof Error ? err.message : String(err), false);
4055
+ }
4056
+ }
4057
+ async function configSetCommand(key, value) {
4058
+ try {
4059
+ await configSet(key, value);
4060
+ output(`Config updated: ${key} = ${value}`, false);
4061
+ } catch (err) {
4062
+ output(err instanceof Error ? err.message : String(err), false);
4063
+ process.exit(1);
4064
+ }
4065
+ }
4066
+
4067
+ // packages/cli/src/commands/daemon-ctrl.ts
4068
+ import { existsSync as existsSync3, readFileSync as readFileSync2, unlinkSync, openSync } from "fs";
4069
+ import { join as join2, dirname as dirname2 } from "path";
4070
+ import { homedir } from "os";
4071
+ import { spawn } from "child_process";
4072
+ import { fileURLToPath } from "url";
4073
+ import { createRequire } from "module";
4074
+ var LENS_DIR = join2(homedir(), ".lens");
4075
+ var PID_FILE = join2(LENS_DIR, "daemon.pid");
4076
+ var LOG_FILE = join2(LENS_DIR, "daemon.log");
4077
+ function isDaemonRunning() {
4078
+ if (!existsSync3(PID_FILE)) return { running: false };
4079
+ const pid = Number(readFileSync2(PID_FILE, "utf-8").trim());
4080
+ try {
4081
+ process.kill(pid, 0);
4082
+ return { running: true, pid };
4083
+ } catch {
4084
+ unlinkSync(PID_FILE);
4085
+ return { running: false };
4086
+ }
4087
+ }
4088
+ async function startCommand() {
4089
+ const status = isDaemonRunning();
4090
+ if (status.running) {
4091
+ output(`LENS daemon already running (pid: ${status.pid})`, false);
4092
+ return;
4093
+ }
4094
+ const selfDir = dirname2(fileURLToPath(import.meta.url));
4095
+ const sibling = join2(selfDir, "daemon.js");
4096
+ let daemonScript;
4097
+ if (existsSync3(sibling)) {
4098
+ daemonScript = sibling;
4099
+ } else {
4100
+ try {
4101
+ const require2 = createRequire(import.meta.url);
4102
+ daemonScript = require2.resolve("@lens/daemon");
4103
+ } catch {
4104
+ error("Could not find @lens/daemon. Run `pnpm build` first.");
4105
+ return;
4106
+ }
4107
+ }
4108
+ const logFd = openSync(LOG_FILE, "a");
4109
+ const child = spawn(process.execPath, [daemonScript], {
4110
+ detached: true,
4111
+ stdio: ["ignore", logFd, logFd],
4112
+ env: { ...process.env, LENS_DAEMON: "1" }
4113
+ });
4114
+ child.unref();
4115
+ for (let i = 0; i < 20; i++) {
4116
+ await new Promise((r) => setTimeout(r, 250));
4117
+ if (isDaemonRunning().running) break;
4118
+ }
4119
+ const check = isDaemonRunning();
4120
+ if (check.running) {
4121
+ output(`LENS daemon started (pid: ${check.pid})`, false);
4122
+ } else {
4123
+ error(`LENS daemon failed to start. Check logs: ${LOG_FILE}`);
4124
+ }
4125
+ }
4126
+ async function stopCommand() {
4127
+ const status = isDaemonRunning();
4128
+ if (!status.running) {
4129
+ output("LENS daemon is not running", false);
4130
+ return;
4131
+ }
4132
+ process.kill(status.pid, "SIGTERM");
4133
+ for (let i = 0; i < 20; i++) {
4134
+ await new Promise((r) => setTimeout(r, 250));
4135
+ if (!isDaemonRunning().running) {
4136
+ output(`LENS daemon stopped (pid: ${status.pid})`, false);
4137
+ return;
4138
+ }
4139
+ }
4140
+ error("Daemon did not stop within 5s. Force kill with: kill -9 " + status.pid);
4141
+ }
4142
+
4143
+ // packages/cli/src/commands/dashboard.ts
4144
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
4145
+ import { join as join3 } from "path";
4146
+ import { homedir as homedir2 } from "os";
4147
+
4148
+ // packages/cli/src/util/browser.ts
4149
+ import { exec } from "child_process";
4150
+ function openBrowser(url) {
4151
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4152
+ exec(`${cmd} ${url}`);
4153
+ }
4154
+
4155
+ // packages/cli/src/commands/dashboard.ts
4156
+ var PID_FILE2 = join3(homedir2(), ".lens", "daemon.pid");
4157
+ function isDaemonRunning2() {
4158
+ if (!existsSync4(PID_FILE2)) return false;
4159
+ const pid = Number(readFileSync3(PID_FILE2, "utf-8").trim());
4160
+ try {
4161
+ process.kill(pid, 0);
4162
+ return true;
4163
+ } catch {
4164
+ return false;
4165
+ }
4166
+ }
4167
+ async function dashboardCommand() {
4168
+ if (!isDaemonRunning2()) {
4169
+ error("LENS daemon is not running. Start with: lens daemon start");
4170
+ return;
4171
+ }
4172
+ const port = process.env.LENS_PORT || "4111";
4173
+ const host = process.env.LENS_HOST || `http://127.0.0.1:${port}`;
4174
+ const url = `${host}/dashboard`;
4175
+ output(`Opening ${url}`, false);
4176
+ openBrowser(url);
4177
+ }
4178
+
4179
+ // packages/cli/src/commands/login.ts
4180
+ import http from "http";
4181
+
4182
+ // packages/cli/src/util/auth.ts
4183
+ import fs3 from "fs/promises";
4184
+ import path3 from "path";
4185
+ import os2 from "os";
4186
+ var CONFIG_DIR2 = path3.join(os2.homedir(), ".lens");
4187
+ var AUTH_FILE = path3.join(CONFIG_DIR2, "auth.json");
4188
+ async function writeAuth(tokens) {
4189
+ await fs3.mkdir(CONFIG_DIR2, { recursive: true });
4190
+ await fs3.writeFile(AUTH_FILE, JSON.stringify(tokens, null, 2), { mode: 384 });
4191
+ }
4192
+ async function clearAuth() {
4193
+ try {
4194
+ await fs3.unlink(AUTH_FILE);
4195
+ } catch {
4196
+ }
4197
+ }
4198
+
4199
+ // packages/cli/src/commands/login.ts
4200
+ var SUPABASE_URL = "https://kuvsaycpvbbmyyxiklap.supabase.co";
4201
+ var SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt1dnNheWNwdmJibXl5eGlrbGFwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzA2MzIxNzQsImV4cCI6MjA4NjIwODE3NH0.yllrNUWVHUyFBwegoIeBkiHiIiWcsspHL9126nT2o2Q";
4202
+ var CLOUD_API_URL = getCloudUrl();
4203
+ function chooserPage(port) {
4204
+ const redirect = `http://localhost:${port}/callback`;
4205
+ const ghUrl = `${SUPABASE_URL}/auth/v1/authorize?provider=github&redirect_to=${encodeURIComponent(redirect)}`;
4206
+ const goUrl = `${SUPABASE_URL}/auth/v1/authorize?provider=google&redirect_to=${encodeURIComponent(redirect)}`;
4207
+ return `<!DOCTYPE html>
4208
+ <html><head><meta charset="utf-8"><title>LENS Login</title>
4209
+ <style>
4210
+ body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa; }
4211
+ .card { text-align: center; padding: 3rem; border: 1px solid #333; border-radius: 12px; background: #111; }
4212
+ h1 { font-size: 1.5rem; margin-bottom: 0.5rem; }
4213
+ p { color: #888; margin-bottom: 2rem; }
4214
+ a { display: block; padding: 0.75rem 2rem; margin: 0.75rem 0; border-radius: 8px; text-decoration: none; font-weight: 500; transition: opacity 0.15s; }
4215
+ a:hover { opacity: 0.85; }
4216
+ .gh { background: #24292e; color: #fff; }
4217
+ .go { background: #fff; color: #333; }
4218
+ </style></head><body>
4219
+ <div class="card">
4220
+ <h1>Sign in to LENS</h1>
4221
+ <p>Choose a provider to authenticate your CLI</p>
4222
+ <a class="gh" href="${ghUrl}">Continue with GitHub</a>
4223
+ <a class="go" href="${goUrl}">Continue with Google</a>
4224
+ </div></body></html>`;
4225
+ }
4226
+ function callbackPage() {
4227
+ return `<!DOCTYPE html>
4228
+ <html><head><meta charset="utf-8"><title>LENS Login</title>
4229
+ <style>
4230
+ body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa; }
4231
+ .card { text-align: center; padding: 3rem; }
4232
+ h1 { font-size: 1.5rem; }
4233
+ p { color: #888; }
4234
+ </style></head><body>
4235
+ <div class="card">
4236
+ <h1>Authenticating...</h1>
4237
+ <p id="msg">Processing tokens...</p>
4238
+ </div>
4239
+ <script>
4240
+ (async () => {
4241
+ const msg = document.getElementById("msg");
4242
+ try {
4243
+ const hash = window.location.hash.substring(1);
4244
+ const params = new URLSearchParams(hash);
4245
+ const access_token = params.get("access_token");
4246
+ const refresh_token = params.get("refresh_token");
4247
+ const expires_in = params.get("expires_in");
4248
+
4249
+ if (!access_token) {
4250
+ msg.textContent = "No access token received. Please try again.";
4251
+ return;
4252
+ }
4253
+
4254
+ // Fetch user info from Supabase
4255
+ const res = await fetch("${SUPABASE_URL}/auth/v1/user", {
4256
+ headers: {
4257
+ "Authorization": "Bearer " + access_token,
4258
+ "apikey": "${SUPABASE_ANON_KEY}"
4259
+ }
4260
+ });
4261
+ const user = await res.json();
4262
+ const user_email = user.email || "unknown";
4263
+
4264
+ const r = await fetch("/token", {
4265
+ method: "POST",
4266
+ headers: { "Content-Type": "application/json" },
4267
+ body: JSON.stringify({ access_token, refresh_token, expires_in, user_email })
4268
+ });
4269
+
4270
+ if (r.ok) {
4271
+ window.location.href = "http://127.0.0.1:4111/dashboard/";
4272
+ return;
4273
+ } else {
4274
+ msg.textContent = "Failed to save tokens. Please try again.";
4275
+ }
4276
+ } catch (e) {
4277
+ msg.textContent = "Error: " + e.message;
4278
+ }
4279
+ })();
4280
+ </script></body></html>`;
4281
+ }
4282
+ async function loginCommand(opts) {
4283
+ return new Promise((resolve2, reject) => {
4284
+ const server = http.createServer(async (req, res) => {
4285
+ const url = new URL(req.url, `http://localhost`);
4286
+ if (req.method === "GET" && url.pathname === "/") {
4287
+ const addr = server.address();
4288
+ res.writeHead(200, { "Content-Type": "text/html" });
4289
+ res.end(chooserPage(addr.port));
4290
+ return;
4291
+ }
4292
+ if (req.method === "GET" && url.pathname === "/callback") {
4293
+ res.writeHead(200, { "Content-Type": "text/html" });
4294
+ res.end(callbackPage());
4295
+ return;
4296
+ }
4297
+ if (req.method === "POST" && url.pathname === "/token") {
4298
+ let body = "";
4299
+ req.on("data", (c) => body += c);
4300
+ req.on("end", async () => {
4301
+ try {
4302
+ const { access_token, refresh_token, expires_in, user_email } = JSON.parse(body);
4303
+ const expires_at = Math.floor(Date.now() / 1e3) + Number(expires_in || 3600);
4304
+ const tokens = { access_token, refresh_token, user_email, expires_at };
4305
+ try {
4306
+ const keyRes = await fetch(`${CLOUD_API_URL}/auth/key`, {
4307
+ headers: { Authorization: `Bearer ${access_token}` }
4308
+ });
4309
+ if (keyRes.ok) {
4310
+ const { api_key } = await keyRes.json();
4311
+ tokens.api_key = api_key;
4312
+ } else {
4313
+ error(`Cloud API key failed (${keyRes.status}). Cloud features unavailable until daemon restarts.`);
4314
+ }
4315
+ } catch (e) {
4316
+ error(`Cloud unreachable: ${e?.message ?? "unknown"}. Daemon will retry on next start.`);
4317
+ }
4318
+ await writeAuth(tokens);
4319
+ res.writeHead(200, { "Content-Type": "application/json" });
4320
+ res.end(JSON.stringify({ ok: true }));
4321
+ output(`Logged in as ${user_email}`, false);
4322
+ if (tokens.api_key) output("Cloud API key provisioned", false);
4323
+ cleanup();
4324
+ resolve2();
4325
+ setTimeout(() => process.exit(0), 100);
4326
+ } catch (err) {
4327
+ res.writeHead(400);
4328
+ res.end("Bad request");
4329
+ }
4330
+ });
4331
+ return;
4332
+ }
4333
+ res.writeHead(404);
4334
+ res.end("Not found");
4335
+ });
4336
+ const timeout = setTimeout(() => {
4337
+ error("Login timed out (120s). Please try again.");
4338
+ cleanup();
4339
+ reject(new Error("Login timed out"));
4340
+ }, 12e4);
4341
+ function cleanup() {
4342
+ clearTimeout(timeout);
4343
+ server.close();
4344
+ }
4345
+ server.listen(0, "127.0.0.1", () => {
4346
+ const addr = server.address();
4347
+ const port = addr.port;
4348
+ const redirect = encodeURIComponent(`http://localhost:${port}/callback`);
4349
+ let url;
4350
+ if (opts.github) {
4351
+ url = `${SUPABASE_URL}/auth/v1/authorize?provider=github&redirect_to=${redirect}`;
4352
+ } else if (opts.google) {
4353
+ url = `${SUPABASE_URL}/auth/v1/authorize?provider=google&redirect_to=${redirect}`;
4354
+ } else {
4355
+ url = `http://localhost:${port}/`;
4356
+ }
4357
+ output(`Opening browser for authentication...`, false);
4358
+ openBrowser(url);
4359
+ });
4360
+ });
4361
+ }
4362
+
4363
+ // packages/cli/src/commands/logout.ts
4364
+ async function logoutCommand() {
4365
+ await clearAuth();
4366
+ output("Logged out of LENS cloud.", false);
4367
+ }
4368
+
4369
+ // packages/cli/src/index.ts
4370
+ var program2 = new Command().name("lens").description("LENS \u2014 Local-first repo context engine").version("0.1.0");
4371
+ function trackCommand(name) {
4372
+ if (!isTelemetryEnabled()) return;
4373
+ const BASE_URL2 = process.env.LENS_HOST ?? "http://127.0.0.1:4111";
4374
+ fetch(`${BASE_URL2}/telemetry/track`, {
4375
+ method: "POST",
4376
+ headers: { "Content-Type": "application/json" },
4377
+ body: JSON.stringify({ event_type: "command", event_data: { command_name: name } }),
4378
+ signal: AbortSignal.timeout(2e3)
4379
+ }).catch(() => {
4380
+ });
4381
+ }
4382
+ var repo = program2.command("repo").description("Repo management");
4383
+ repo.command("register").description("Register current repo with the daemon").option("--json", "Output as JSON", false).option("--inject", "Inject LENS instructions into existing CLAUDE.md", false).action((opts) => run(() => registerCommand(opts), "repo register"));
4384
+ repo.command("list").description("List all registered repos").option("--json", "Output as JSON", false).action((opts) => run(() => listCommand(opts)));
4385
+ repo.command("remove").description("Remove current repo and all its data").option("--json", "Output as JSON", false).option("--yes", "Skip confirmation", false).action((opts) => run(() => removeCommand(opts)));
4386
+ repo.command("watch").description("Start file watcher for current repo").option("--json", "Output as JSON", false).action((opts) => run(() => watchCommand(opts)));
4387
+ repo.command("unwatch").description("Stop file watcher for current repo").option("--json", "Output as JSON", false).action((opts) => run(() => unwatchCommand(opts)));
4388
+ repo.command("watch-status").description("Show file watcher status for current repo").option("--json", "Output as JSON", false).action((opts) => run(() => watchStatusCommand(opts)));
4389
+ program2.command("context <goal>").description("Build an intelligent context pack for a goal").option("--json", "Output as JSON", false).action((goal, opts) => run(() => contextCommand(goal, opts), "context"));
4390
+ program2.command("index").description("Index the current repo").option("--json", "Output as JSON", false).option("--force", "Full re-scan (default: diff scan, changed files only)", false).option("--status", "Show index status", false).action((opts) => run(() => indexCommand(opts), "index"));
4391
+ program2.command("status").description("Show repo index/embedding status").option("--json", "Output as JSON", false).action((opts) => run(() => statusCommand(opts), "status"));
4392
+ var daemon = program2.command("daemon").description("Daemon management");
4393
+ daemon.command("stats").description("Show global daemon statistics").option("--json", "Output as JSON", false).action((opts) => run(() => daemonStatsCommand(opts)));
4394
+ daemon.command("start").description("Start the LENS daemon").action(() => run(() => startCommand()));
4395
+ daemon.command("stop").description("Stop the LENS daemon").action(() => run(() => stopCommand()));
4396
+ program2.command("dashboard").description("Open the LENS dashboard in browser").action(() => run(() => dashboardCommand()));
4397
+ program2.command("login").description("Authenticate with LENS cloud via browser OAuth").option("--github", "Sign in with GitHub directly").option("--google", "Sign in with Google directly").action((opts) => run(() => loginCommand(opts)));
4398
+ program2.command("logout").description("Clear LENS cloud authentication").action(() => run(() => logoutCommand()));
4399
+ var cfg = program2.command("config").description("Manage LENS CLI config");
4400
+ cfg.command("get <key>").description("Get config value (inject_behavior, show_progress)").action((key) => run(() => configGetCommand(key)));
4401
+ cfg.command("set <key> <value>").description("Set config value (e.g. show_progress true, inject_behavior once)").action((key, value) => run(() => configSetCommand(key, value)));
4402
+ program2.parse();
4403
+ async function run(fn, commandName) {
4404
+ if (commandName) trackCommand(commandName);
4405
+ try {
4406
+ await fn();
4407
+ } catch (err) {
4408
+ error(err instanceof Error ? err.message : String(err));
4409
+ process.exit(1);
4410
+ }
4411
+ }