@koed-labs/server 0.0.0-bootstrap.0 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +65 -0
  3. package/bin/koed.js +7 -0
  4. package/package.json +22 -4
  5. package/third-party-notices.json +92 -0
  6. package/vendor/chunk-2BWTLF7A.js +13883 -0
  7. package/vendor/chunk-2DA7EFZV.js +924 -0
  8. package/vendor/chunk-2S3OGPUC.js +58 -0
  9. package/vendor/chunk-473OA62O.js +26827 -0
  10. package/vendor/chunk-6JRWGOQG.js +236 -0
  11. package/vendor/chunk-7NOQSX4T.js +14 -0
  12. package/vendor/chunk-7NXKPDF3.js +1586 -0
  13. package/vendor/chunk-A4NKL2PK.js +153 -0
  14. package/vendor/chunk-A6WMU2GG.js +48 -0
  15. package/vendor/chunk-AFLKCQHF.js +73 -0
  16. package/vendor/chunk-BTS4ZTF3.js +43 -0
  17. package/vendor/chunk-C3N4N5HR.js +108 -0
  18. package/vendor/chunk-DXTAWHY3.js +25 -0
  19. package/vendor/chunk-G4IIVVJO.js +56 -0
  20. package/vendor/chunk-GELDEJJ2.js +4337 -0
  21. package/vendor/chunk-HFM6ROJL.js +188 -0
  22. package/vendor/chunk-HK2H3MVE.js +328 -0
  23. package/vendor/chunk-HZJK5RWC.js +5088 -0
  24. package/vendor/chunk-J2L726BC.js +2497 -0
  25. package/vendor/chunk-JBGD4JLR.js +3779 -0
  26. package/vendor/chunk-JJNLH5GA.js +2470 -0
  27. package/vendor/chunk-JKOG52PE.js +128 -0
  28. package/vendor/chunk-K2EIFEQF.js +89 -0
  29. package/vendor/chunk-KUIWH33N.js +16 -0
  30. package/vendor/chunk-NEWIOOM6.js +34 -0
  31. package/vendor/chunk-NM5NXCVM.js +2404 -0
  32. package/vendor/chunk-PT3AUPGE.js +459 -0
  33. package/vendor/chunk-PY5LYLV7.js +143 -0
  34. package/vendor/chunk-QIIKMG3M.js +103 -0
  35. package/vendor/chunk-QT24SAW6.js +110 -0
  36. package/vendor/chunk-RVYJKKWA.js +22 -0
  37. package/vendor/chunk-SKVYP7NY.js +1647 -0
  38. package/vendor/chunk-TSRPHKAC.js +780 -0
  39. package/vendor/chunk-UI5RLBKQ.js +30 -0
  40. package/vendor/chunk-VPC5NLZG.js +259 -0
  41. package/vendor/chunk-W2HNI6AA.js +75 -0
  42. package/vendor/chunk-X6M525ZJ.js +20 -0
  43. package/vendor/chunk-XIZVLPHZ.js +18 -0
  44. package/vendor/chunk-XNFVSVBS.js +242 -0
  45. package/vendor/chunk-YCDEMYY6.js +2076 -0
  46. package/vendor/chunk-YJ6XUZT6.js +292 -0
  47. package/vendor/chunk-YJWREXN6.js +26020 -0
  48. package/vendor/chunk-YK4F4VY2.js +173 -0
  49. package/vendor/chunk-YOFI4PCH.js +36 -0
  50. package/vendor/chunk-ZUGNCQZE.js +247 -0
  51. package/vendor/chunk-ZXX4ZNJY.js +21 -0
  52. package/vendor/cli.js +7 -0
  53. package/vendor/component-manifest-catalog.js +8 -0
  54. package/vendor/control-plane.js +23 -0
  55. package/vendor/package.json +1 -0
  56. package/vendor/privacy-service-bootstrap.js +6 -0
@@ -0,0 +1,4337 @@
1
+ import { createRequire as createKoedRequire } from "node:module"; const require = createKoedRequire(import.meta.url);
2
+ import {
3
+ resolveKoedControlPlaneVersion
4
+ } from "./chunk-A4NKL2PK.js";
5
+ import {
6
+ resolveKoedServerPaths
7
+ } from "./chunk-K2EIFEQF.js";
8
+
9
+ // packages/koed-server/dist/cli.js
10
+ import { realpathSync } from "node:fs";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
12
+
13
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
14
+ var CommanderError = class extends Error {
15
+ /**
16
+ * Constructs the CommanderError class
17
+ * @param {number} exitCode suggested exit code which could be used with process.exit
18
+ * @param {string} code an id string representing the error
19
+ * @param {string} message human-readable description of the error
20
+ */
21
+ constructor(exitCode, code, message) {
22
+ super(message);
23
+ Error.captureStackTrace(this, this.constructor);
24
+ this.name = this.constructor.name;
25
+ this.code = code;
26
+ this.exitCode = exitCode;
27
+ this.nestedError = void 0;
28
+ }
29
+ };
30
+ var InvalidArgumentError = class extends CommanderError {
31
+ /**
32
+ * Constructs the InvalidArgumentError class
33
+ * @param {string} [message] explanation of why argument is invalid
34
+ */
35
+ constructor(message) {
36
+ super(1, "commander.invalidArgument", message);
37
+ Error.captureStackTrace(this, this.constructor);
38
+ this.name = this.constructor.name;
39
+ }
40
+ };
41
+
42
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
43
+ var Argument = class {
44
+ /**
45
+ * Initialize a new command argument with the given name and description.
46
+ * The default is that the argument is required, and you can explicitly
47
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
48
+ *
49
+ * @param {string} name
50
+ * @param {string} [description]
51
+ */
52
+ constructor(name, description) {
53
+ this.description = description || "";
54
+ this.variadic = false;
55
+ this.parseArg = void 0;
56
+ this.defaultValue = void 0;
57
+ this.defaultValueDescription = void 0;
58
+ this.argChoices = void 0;
59
+ switch (name[0]) {
60
+ case "<":
61
+ this.required = true;
62
+ this._name = name.slice(1, -1);
63
+ break;
64
+ case "[":
65
+ this.required = false;
66
+ this._name = name.slice(1, -1);
67
+ break;
68
+ default:
69
+ this.required = true;
70
+ this._name = name;
71
+ break;
72
+ }
73
+ if (this._name.endsWith("...")) {
74
+ this.variadic = true;
75
+ this._name = this._name.slice(0, -3);
76
+ }
77
+ }
78
+ /**
79
+ * Return argument name.
80
+ *
81
+ * @return {string}
82
+ */
83
+ name() {
84
+ return this._name;
85
+ }
86
+ /**
87
+ * @package
88
+ */
89
+ _collectValue(value, previous) {
90
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
91
+ return [value];
92
+ }
93
+ previous.push(value);
94
+ return previous;
95
+ }
96
+ /**
97
+ * Set the default value, and optionally supply the description to be displayed in the help.
98
+ *
99
+ * @param {*} value
100
+ * @param {string} [description]
101
+ * @return {Argument}
102
+ */
103
+ default(value, description) {
104
+ this.defaultValue = value;
105
+ this.defaultValueDescription = description;
106
+ return this;
107
+ }
108
+ /**
109
+ * Set the custom handler for processing CLI command arguments into argument values.
110
+ *
111
+ * @param {Function} [fn]
112
+ * @return {Argument}
113
+ */
114
+ argParser(fn) {
115
+ this.parseArg = fn;
116
+ return this;
117
+ }
118
+ /**
119
+ * Only allow argument value to be one of choices.
120
+ *
121
+ * @param {string[]} values
122
+ * @return {Argument}
123
+ */
124
+ choices(values) {
125
+ this.argChoices = values.slice();
126
+ this.parseArg = (arg, previous) => {
127
+ if (!this.argChoices.includes(arg)) {
128
+ throw new InvalidArgumentError(
129
+ `Allowed choices are ${this.argChoices.join(", ")}.`
130
+ );
131
+ }
132
+ if (this.variadic) {
133
+ return this._collectValue(arg, previous);
134
+ }
135
+ return arg;
136
+ };
137
+ return this;
138
+ }
139
+ /**
140
+ * Make argument required.
141
+ *
142
+ * @returns {Argument}
143
+ */
144
+ argRequired() {
145
+ this.required = true;
146
+ return this;
147
+ }
148
+ /**
149
+ * Make argument optional.
150
+ *
151
+ * @returns {Argument}
152
+ */
153
+ argOptional() {
154
+ this.required = false;
155
+ return this;
156
+ }
157
+ };
158
+ function humanReadableArgName(arg) {
159
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
160
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
161
+ }
162
+
163
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
164
+ import { EventEmitter } from "node:events";
165
+ import childProcess from "node:child_process";
166
+ import path from "node:path";
167
+ import fs from "node:fs";
168
+ import process2 from "node:process";
169
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
170
+
171
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
172
+ import { stripVTControlCharacters } from "node:util";
173
+ var Help = class {
174
+ constructor() {
175
+ this.helpWidth = void 0;
176
+ this.minWidthToWrap = 40;
177
+ this.sortSubcommands = false;
178
+ this.sortOptions = false;
179
+ this.showGlobalOptions = false;
180
+ }
181
+ /**
182
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
183
+ * and just before calling `formatHelp()`.
184
+ *
185
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
186
+ *
187
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
188
+ */
189
+ prepareContext(contextOptions) {
190
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
191
+ }
192
+ /**
193
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
194
+ *
195
+ * @param {Command} cmd
196
+ * @returns {Command[]}
197
+ */
198
+ visibleCommands(cmd) {
199
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
200
+ const helpCommand = cmd._getHelpCommand();
201
+ if (helpCommand && !helpCommand._hidden) {
202
+ visibleCommands.push(helpCommand);
203
+ }
204
+ if (this.sortSubcommands) {
205
+ visibleCommands.sort((a, b) => {
206
+ return a.name().localeCompare(b.name());
207
+ });
208
+ }
209
+ return visibleCommands;
210
+ }
211
+ /**
212
+ * Compare options for sort.
213
+ *
214
+ * @param {Option} a
215
+ * @param {Option} b
216
+ * @returns {number}
217
+ */
218
+ compareOptions(a, b) {
219
+ const getSortKey = (option) => {
220
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
221
+ };
222
+ return getSortKey(a).localeCompare(getSortKey(b));
223
+ }
224
+ /**
225
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
226
+ *
227
+ * @param {Command} cmd
228
+ * @returns {Option[]}
229
+ */
230
+ visibleOptions(cmd) {
231
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
232
+ const helpOption = cmd._getHelpOption();
233
+ if (helpOption && !helpOption.hidden) {
234
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
235
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
236
+ if (!removeShort && !removeLong) {
237
+ visibleOptions.push(helpOption);
238
+ } else if (helpOption.long && !removeLong) {
239
+ visibleOptions.push(
240
+ cmd.createOption(helpOption.long, helpOption.description)
241
+ );
242
+ } else if (helpOption.short && !removeShort) {
243
+ visibleOptions.push(
244
+ cmd.createOption(helpOption.short, helpOption.description)
245
+ );
246
+ }
247
+ }
248
+ if (this.sortOptions) {
249
+ visibleOptions.sort(this.compareOptions);
250
+ }
251
+ return visibleOptions;
252
+ }
253
+ /**
254
+ * Get an array of the visible global options. (Not including help.)
255
+ *
256
+ * @param {Command} cmd
257
+ * @returns {Option[]}
258
+ */
259
+ visibleGlobalOptions(cmd) {
260
+ if (!this.showGlobalOptions) return [];
261
+ const globalOptions = [];
262
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
263
+ const visibleOptions = ancestorCmd.options.filter(
264
+ (option) => !option.hidden
265
+ );
266
+ globalOptions.push(...visibleOptions);
267
+ }
268
+ if (this.sortOptions) {
269
+ globalOptions.sort(this.compareOptions);
270
+ }
271
+ return globalOptions;
272
+ }
273
+ /**
274
+ * Get an array of the arguments if any have a description.
275
+ *
276
+ * @param {Command} cmd
277
+ * @returns {Argument[]}
278
+ */
279
+ visibleArguments(cmd) {
280
+ if (cmd._argsDescription) {
281
+ cmd.registeredArguments.forEach((argument) => {
282
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
283
+ });
284
+ }
285
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
286
+ return cmd.registeredArguments;
287
+ }
288
+ return [];
289
+ }
290
+ /**
291
+ * Get the command term to show in the list of subcommands.
292
+ *
293
+ * @param {Command} cmd
294
+ * @returns {string}
295
+ */
296
+ subcommandTerm(cmd) {
297
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
298
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
299
+ (args ? " " + args : "");
300
+ }
301
+ /**
302
+ * Get the option term to show in the list of options.
303
+ *
304
+ * @param {Option} option
305
+ * @returns {string}
306
+ */
307
+ optionTerm(option) {
308
+ return option.flags;
309
+ }
310
+ /**
311
+ * Get the argument term to show in the list of arguments.
312
+ *
313
+ * @param {Argument} argument
314
+ * @returns {string}
315
+ */
316
+ argumentTerm(argument) {
317
+ return argument.name();
318
+ }
319
+ /**
320
+ * Get the longest command term length.
321
+ *
322
+ * @param {Command} cmd
323
+ * @param {Help} helper
324
+ * @returns {number}
325
+ */
326
+ longestSubcommandTermLength(cmd, helper) {
327
+ return helper.visibleCommands(cmd).reduce((max, command) => {
328
+ return Math.max(
329
+ max,
330
+ this.displayWidth(
331
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
332
+ )
333
+ );
334
+ }, 0);
335
+ }
336
+ /**
337
+ * Get the longest option term length.
338
+ *
339
+ * @param {Command} cmd
340
+ * @param {Help} helper
341
+ * @returns {number}
342
+ */
343
+ longestOptionTermLength(cmd, helper) {
344
+ return helper.visibleOptions(cmd).reduce((max, option) => {
345
+ return Math.max(
346
+ max,
347
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
348
+ );
349
+ }, 0);
350
+ }
351
+ /**
352
+ * Get the longest global option term length.
353
+ *
354
+ * @param {Command} cmd
355
+ * @param {Help} helper
356
+ * @returns {number}
357
+ */
358
+ longestGlobalOptionTermLength(cmd, helper) {
359
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
360
+ return Math.max(
361
+ max,
362
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
363
+ );
364
+ }, 0);
365
+ }
366
+ /**
367
+ * Get the longest argument term length.
368
+ *
369
+ * @param {Command} cmd
370
+ * @param {Help} helper
371
+ * @returns {number}
372
+ */
373
+ longestArgumentTermLength(cmd, helper) {
374
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
375
+ return Math.max(
376
+ max,
377
+ this.displayWidth(
378
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
379
+ )
380
+ );
381
+ }, 0);
382
+ }
383
+ /**
384
+ * Get the command usage to be displayed at the top of the built-in help.
385
+ *
386
+ * @param {Command} cmd
387
+ * @returns {string}
388
+ */
389
+ commandUsage(cmd) {
390
+ let cmdName = cmd._name;
391
+ if (cmd._aliases[0]) {
392
+ cmdName = cmdName + "|" + cmd._aliases[0];
393
+ }
394
+ let ancestorCmdNames = "";
395
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
396
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
397
+ }
398
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
399
+ }
400
+ /**
401
+ * Get the description for the command.
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ commandDescription(cmd) {
407
+ return cmd.description();
408
+ }
409
+ /**
410
+ * Get the subcommand summary to show in the list of subcommands.
411
+ * (Fallback to description for backwards compatibility.)
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ subcommandDescription(cmd) {
417
+ return cmd.summary() || cmd.description();
418
+ }
419
+ /**
420
+ * Get the option description to show in the list of options.
421
+ *
422
+ * @param {Option} option
423
+ * @return {string}
424
+ */
425
+ optionDescription(option) {
426
+ const extraInfo = [];
427
+ if (option.argChoices) {
428
+ extraInfo.push(
429
+ // use stringify to match the display of the default value
430
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
431
+ );
432
+ }
433
+ if (option.defaultValue !== void 0) {
434
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
435
+ if (showDefault) {
436
+ extraInfo.push(
437
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
438
+ );
439
+ }
440
+ }
441
+ if (option.presetArg !== void 0 && option.optional) {
442
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
+ }
444
+ if (option.envVar !== void 0) {
445
+ extraInfo.push(`env: ${option.envVar}`);
446
+ }
447
+ if (extraInfo.length > 0) {
448
+ const extraDescription = `(${extraInfo.join(", ")})`;
449
+ if (option.description) {
450
+ return `${option.description} ${extraDescription}`;
451
+ }
452
+ return extraDescription;
453
+ }
454
+ return option.description;
455
+ }
456
+ /**
457
+ * Get the argument description to show in the list of arguments.
458
+ *
459
+ * @param {Argument} argument
460
+ * @return {string}
461
+ */
462
+ argumentDescription(argument) {
463
+ const extraInfo = [];
464
+ if (argument.argChoices) {
465
+ extraInfo.push(
466
+ // use stringify to match the display of the default value
467
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
468
+ );
469
+ }
470
+ if (argument.defaultValue !== void 0) {
471
+ extraInfo.push(
472
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
473
+ );
474
+ }
475
+ if (extraInfo.length > 0) {
476
+ const extraDescription = `(${extraInfo.join(", ")})`;
477
+ if (argument.description) {
478
+ return `${argument.description} ${extraDescription}`;
479
+ }
480
+ return extraDescription;
481
+ }
482
+ return argument.description;
483
+ }
484
+ /**
485
+ * Format a list of items, given a heading and an array of formatted items.
486
+ *
487
+ * @param {string} heading
488
+ * @param {string[]} items
489
+ * @param {Help} helper
490
+ * @returns string[]
491
+ */
492
+ formatItemList(heading, items, helper) {
493
+ if (items.length === 0) return [];
494
+ return [helper.styleTitle(heading), ...items, ""];
495
+ }
496
+ /**
497
+ * Group items by their help group heading.
498
+ *
499
+ * @param {Command[] | Option[]} unsortedItems
500
+ * @param {Command[] | Option[]} visibleItems
501
+ * @param {Function} getGroup
502
+ * @returns {Map<string, Command[] | Option[]>}
503
+ */
504
+ groupItems(unsortedItems, visibleItems, getGroup) {
505
+ const result = /* @__PURE__ */ new Map();
506
+ unsortedItems.forEach((item) => {
507
+ const group = getGroup(item);
508
+ if (!result.has(group)) result.set(group, []);
509
+ });
510
+ visibleItems.forEach((item) => {
511
+ const group = getGroup(item);
512
+ if (!result.has(group)) {
513
+ result.set(group, []);
514
+ }
515
+ result.get(group).push(item);
516
+ });
517
+ return result;
518
+ }
519
+ /**
520
+ * Generate the built-in help text.
521
+ *
522
+ * @param {Command} cmd
523
+ * @param {Help} helper
524
+ * @returns {string}
525
+ */
526
+ formatHelp(cmd, helper) {
527
+ const termWidth = helper.padWidth(cmd, helper);
528
+ const helpWidth = helper.helpWidth ?? 80;
529
+ function callFormatItem(term, description) {
530
+ return helper.formatItem(term, termWidth, description, helper);
531
+ }
532
+ let output = [
533
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
534
+ ""
535
+ ];
536
+ const commandDescription = helper.commandDescription(cmd);
537
+ if (commandDescription.length > 0) {
538
+ output = output.concat([
539
+ helper.boxWrap(
540
+ helper.styleCommandDescription(commandDescription),
541
+ helpWidth
542
+ ),
543
+ ""
544
+ ]);
545
+ }
546
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
547
+ return callFormatItem(
548
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
549
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
550
+ );
551
+ });
552
+ output = output.concat(
553
+ this.formatItemList("Arguments:", argumentList, helper)
554
+ );
555
+ const optionGroups = this.groupItems(
556
+ cmd.options,
557
+ helper.visibleOptions(cmd),
558
+ (option) => option.helpGroupHeading ?? "Options:"
559
+ );
560
+ optionGroups.forEach((options, group) => {
561
+ const optionList = options.map((option) => {
562
+ return callFormatItem(
563
+ helper.styleOptionTerm(helper.optionTerm(option)),
564
+ helper.styleOptionDescription(helper.optionDescription(option))
565
+ );
566
+ });
567
+ output = output.concat(this.formatItemList(group, optionList, helper));
568
+ });
569
+ if (helper.showGlobalOptions) {
570
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
571
+ return callFormatItem(
572
+ helper.styleOptionTerm(helper.optionTerm(option)),
573
+ helper.styleOptionDescription(helper.optionDescription(option))
574
+ );
575
+ });
576
+ output = output.concat(
577
+ this.formatItemList("Global Options:", globalOptionList, helper)
578
+ );
579
+ }
580
+ const commandGroups = this.groupItems(
581
+ cmd.commands,
582
+ helper.visibleCommands(cmd),
583
+ (sub) => sub.helpGroup() || "Commands:"
584
+ );
585
+ commandGroups.forEach((commands, group) => {
586
+ const commandList = commands.map((sub) => {
587
+ return callFormatItem(
588
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
589
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
590
+ );
591
+ });
592
+ output = output.concat(this.formatItemList(group, commandList, helper));
593
+ });
594
+ return output.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 stripVTControlCharacters(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
+
763
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
764
+ var Option = class {
765
+ /**
766
+ * Initialize a new `Option` with the given `flags` and `description`.
767
+ *
768
+ * @param {string} flags
769
+ * @param {string} [description]
770
+ */
771
+ constructor(flags, description) {
772
+ this.flags = flags;
773
+ this.description = description || "";
774
+ this.required = flags.includes("<");
775
+ this.optional = flags.includes("[");
776
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
777
+ this.mandatory = false;
778
+ const optionFlags = splitOptionFlags(flags);
779
+ this.short = optionFlags.shortFlag;
780
+ this.long = optionFlags.longFlag;
781
+ this.negate = false;
782
+ if (this.long) {
783
+ this.negate = this.long.startsWith("--no-");
784
+ }
785
+ this.defaultValue = void 0;
786
+ this.defaultValueDescription = void 0;
787
+ this.presetArg = void 0;
788
+ this.envVar = void 0;
789
+ this.parseArg = void 0;
790
+ this.hidden = false;
791
+ this.argChoices = void 0;
792
+ this.conflictsWith = [];
793
+ this.implied = void 0;
794
+ this.helpGroupHeading = void 0;
795
+ }
796
+ /**
797
+ * Set the default value, and optionally supply the description to be displayed in the help.
798
+ *
799
+ * @param {*} value
800
+ * @param {string} [description]
801
+ * @return {Option}
802
+ */
803
+ default(value, description) {
804
+ this.defaultValue = value;
805
+ this.defaultValueDescription = description;
806
+ return this;
807
+ }
808
+ /**
809
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
810
+ * The custom processing (parseArg) is called.
811
+ *
812
+ * @example
813
+ * new Option('--color').default('GREYSCALE').preset('RGB');
814
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
815
+ *
816
+ * @param {*} arg
817
+ * @return {Option}
818
+ */
819
+ preset(arg) {
820
+ this.presetArg = arg;
821
+ return this;
822
+ }
823
+ /**
824
+ * Add option name(s) that conflict with this option.
825
+ * An error will be displayed if conflicting options are found during parsing.
826
+ *
827
+ * @example
828
+ * new Option('--rgb').conflicts('cmyk');
829
+ * new Option('--js').conflicts(['ts', 'jsx']);
830
+ *
831
+ * @param {(string | string[])} names
832
+ * @return {Option}
833
+ */
834
+ conflicts(names) {
835
+ this.conflictsWith = this.conflictsWith.concat(names);
836
+ return this;
837
+ }
838
+ /**
839
+ * Specify implied option values for when this option is set and the implied options are not.
840
+ *
841
+ * The custom processing (parseArg) is not called on the implied values.
842
+ *
843
+ * @example
844
+ * program
845
+ * .addOption(new Option('--log', 'write logging information to file'))
846
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
847
+ *
848
+ * @param {object} impliedOptionValues
849
+ * @return {Option}
850
+ */
851
+ implies(impliedOptionValues) {
852
+ let newImplied = impliedOptionValues;
853
+ if (typeof impliedOptionValues === "string") {
854
+ newImplied = { [impliedOptionValues]: true };
855
+ }
856
+ this.implied = Object.assign(this.implied || {}, newImplied);
857
+ return this;
858
+ }
859
+ /**
860
+ * Set environment variable to check for option value.
861
+ *
862
+ * An environment variable is only used if when processed the current option value is
863
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
864
+ *
865
+ * @param {string} name
866
+ * @return {Option}
867
+ */
868
+ env(name) {
869
+ this.envVar = name;
870
+ return this;
871
+ }
872
+ /**
873
+ * Set the custom handler for processing CLI option arguments into option values.
874
+ *
875
+ * @param {Function} [fn]
876
+ * @return {Option}
877
+ */
878
+ argParser(fn) {
879
+ this.parseArg = fn;
880
+ return this;
881
+ }
882
+ /**
883
+ * Whether the option is mandatory and must have a value after parsing.
884
+ *
885
+ * @param {boolean} [mandatory=true]
886
+ * @return {Option}
887
+ */
888
+ makeOptionMandatory(mandatory = true) {
889
+ this.mandatory = !!mandatory;
890
+ return this;
891
+ }
892
+ /**
893
+ * Hide option in help.
894
+ *
895
+ * @param {boolean} [hide=true]
896
+ * @return {Option}
897
+ */
898
+ hideHelp(hide = true) {
899
+ this.hidden = !!hide;
900
+ return this;
901
+ }
902
+ /**
903
+ * @package
904
+ */
905
+ _collectValue(value, previous) {
906
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
907
+ return [value];
908
+ }
909
+ previous.push(value);
910
+ return previous;
911
+ }
912
+ /**
913
+ * Only allow option value to be one of choices.
914
+ *
915
+ * @param {string[]} values
916
+ * @return {Option}
917
+ */
918
+ choices(values) {
919
+ this.argChoices = values.slice();
920
+ this.parseArg = (arg, previous) => {
921
+ if (!this.argChoices.includes(arg)) {
922
+ throw new InvalidArgumentError(
923
+ `Allowed choices are ${this.argChoices.join(", ")}.`
924
+ );
925
+ }
926
+ if (this.variadic) {
927
+ return this._collectValue(arg, previous);
928
+ }
929
+ return arg;
930
+ };
931
+ return this;
932
+ }
933
+ /**
934
+ * Return option name.
935
+ *
936
+ * @return {string}
937
+ */
938
+ name() {
939
+ if (this.long) {
940
+ return this.long.replace(/^--/, "");
941
+ }
942
+ return this.short.replace(/^-/, "");
943
+ }
944
+ /**
945
+ * Return option name, in a camelcase format that can be used
946
+ * as an object attribute key.
947
+ *
948
+ * @return {string}
949
+ */
950
+ attributeName() {
951
+ if (this.negate) {
952
+ return camelcase(this.name().replace(/^no-/, ""));
953
+ }
954
+ return camelcase(this.name());
955
+ }
956
+ /**
957
+ * Set the help group heading.
958
+ *
959
+ * @param {string} heading
960
+ * @return {Option}
961
+ */
962
+ helpGroup(heading) {
963
+ this.helpGroupHeading = heading;
964
+ return this;
965
+ }
966
+ /**
967
+ * Check if `arg` matches the short or long flag.
968
+ *
969
+ * @param {string} arg
970
+ * @return {boolean}
971
+ * @package
972
+ */
973
+ is(arg) {
974
+ return this.short === arg || this.long === arg;
975
+ }
976
+ /**
977
+ * Return whether a boolean option.
978
+ *
979
+ * Options are one of boolean, negated, required argument, or optional argument.
980
+ *
981
+ * @return {boolean}
982
+ * @package
983
+ */
984
+ isBoolean() {
985
+ return !this.required && !this.optional && !this.negate;
986
+ }
987
+ };
988
+ var DualOptions = class {
989
+ /**
990
+ * @param {Option[]} options
991
+ */
992
+ constructor(options) {
993
+ this.positiveOptions = /* @__PURE__ */ new Map();
994
+ this.negativeOptions = /* @__PURE__ */ new Map();
995
+ this.dualOptions = /* @__PURE__ */ new Set();
996
+ options.forEach((option) => {
997
+ if (option.negate) {
998
+ this.negativeOptions.set(option.attributeName(), option);
999
+ } else {
1000
+ this.positiveOptions.set(option.attributeName(), option);
1001
+ }
1002
+ });
1003
+ this.negativeOptions.forEach((value, key) => {
1004
+ if (this.positiveOptions.has(key)) {
1005
+ this.dualOptions.add(key);
1006
+ }
1007
+ });
1008
+ }
1009
+ /**
1010
+ * Did the value come from the option, and not from possible matching dual option?
1011
+ *
1012
+ * @param {*} value
1013
+ * @param {Option} option
1014
+ * @returns {boolean}
1015
+ */
1016
+ valueFromOption(value, option) {
1017
+ const optionKey = option.attributeName();
1018
+ if (!this.dualOptions.has(optionKey)) return true;
1019
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1020
+ const negativeValue = preset !== void 0 ? preset : false;
1021
+ return option.negate === (negativeValue === value);
1022
+ }
1023
+ };
1024
+ function camelcase(str) {
1025
+ return str.split("-").reduce((str2, word) => {
1026
+ return str2 + word[0].toUpperCase() + word.slice(1);
1027
+ });
1028
+ }
1029
+ function splitOptionFlags(flags) {
1030
+ let shortFlag;
1031
+ let longFlag;
1032
+ const shortFlagExp = /^-[^-]$/;
1033
+ const longFlagExp = /^--[^-]/;
1034
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1035
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1036
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1037
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1038
+ shortFlag = flagParts.shift();
1039
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1040
+ shortFlag = longFlag;
1041
+ longFlag = flagParts.shift();
1042
+ }
1043
+ if (flagParts[0].startsWith("-")) {
1044
+ const unsupportedFlag = flagParts[0];
1045
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1046
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1047
+ throw new Error(
1048
+ `${baseError}
1049
+ - a short flag is a single dash and a single character
1050
+ - either use a single dash and a single character (for a short flag)
1051
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1052
+ );
1053
+ if (shortFlagExp.test(unsupportedFlag))
1054
+ throw new Error(`${baseError}
1055
+ - too many short flags`);
1056
+ if (longFlagExp.test(unsupportedFlag))
1057
+ throw new Error(`${baseError}
1058
+ - too many long flags`);
1059
+ throw new Error(`${baseError}
1060
+ - unrecognised flag format`);
1061
+ }
1062
+ if (shortFlag === void 0 && longFlag === void 0)
1063
+ throw new Error(
1064
+ `option creation failed due to no flags found in '${flags}'.`
1065
+ );
1066
+ return { shortFlag, longFlag };
1067
+ }
1068
+
1069
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
1070
+ var maxDistance = 3;
1071
+ function editDistance(a, b) {
1072
+ if (Math.abs(a.length - b.length) > maxDistance)
1073
+ return Math.max(a.length, b.length);
1074
+ const d = [];
1075
+ for (let i = 0; i <= a.length; i++) {
1076
+ d[i] = [i];
1077
+ }
1078
+ for (let j = 0; j <= b.length; j++) {
1079
+ d[0][j] = j;
1080
+ }
1081
+ for (let j = 1; j <= b.length; j++) {
1082
+ for (let i = 1; i <= a.length; i++) {
1083
+ let cost;
1084
+ if (a[i - 1] === b[j - 1]) {
1085
+ cost = 0;
1086
+ } else {
1087
+ cost = 1;
1088
+ }
1089
+ d[i][j] = Math.min(
1090
+ d[i - 1][j] + 1,
1091
+ // deletion
1092
+ d[i][j - 1] + 1,
1093
+ // insertion
1094
+ d[i - 1][j - 1] + cost
1095
+ // substitution
1096
+ );
1097
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1098
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1099
+ }
1100
+ }
1101
+ }
1102
+ return d[a.length][b.length];
1103
+ }
1104
+ function suggestSimilar(word, candidates) {
1105
+ if (!candidates || candidates.length === 0) return "";
1106
+ candidates = Array.from(new Set(candidates));
1107
+ const searchingOptions = word.startsWith("--");
1108
+ if (searchingOptions) {
1109
+ word = word.slice(2);
1110
+ candidates = candidates.map((candidate) => candidate.slice(2));
1111
+ }
1112
+ let similar = [];
1113
+ let bestDistance = maxDistance;
1114
+ const minSimilarity = 0.4;
1115
+ candidates.forEach((candidate) => {
1116
+ if (candidate.length <= 1) return;
1117
+ const distance = editDistance(word, candidate);
1118
+ const length = Math.max(word.length, candidate.length);
1119
+ const similarity = (length - distance) / length;
1120
+ if (similarity > minSimilarity) {
1121
+ if (distance < bestDistance) {
1122
+ bestDistance = distance;
1123
+ similar = [candidate];
1124
+ } else if (distance === bestDistance) {
1125
+ similar.push(candidate);
1126
+ }
1127
+ }
1128
+ });
1129
+ similar.sort((a, b) => a.localeCompare(b));
1130
+ if (searchingOptions) {
1131
+ similar = similar.map((candidate) => `--${candidate}`);
1132
+ }
1133
+ if (similar.length > 1) {
1134
+ return `
1135
+ (Did you mean one of ${similar.join(", ")}?)`;
1136
+ }
1137
+ if (similar.length === 1) {
1138
+ return `
1139
+ (Did you mean ${similar[0]}?)`;
1140
+ }
1141
+ return "";
1142
+ }
1143
+
1144
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
1145
+ var Command = class _Command extends EventEmitter {
1146
+ /**
1147
+ * Initialize a new `Command`.
1148
+ *
1149
+ * @param {string} [name]
1150
+ */
1151
+ constructor(name) {
1152
+ super();
1153
+ this.commands = [];
1154
+ this.options = [];
1155
+ this.parent = null;
1156
+ this._allowUnknownOption = false;
1157
+ this._allowExcessArguments = false;
1158
+ this.registeredArguments = [];
1159
+ this._args = this.registeredArguments;
1160
+ this.args = [];
1161
+ this.rawArgs = [];
1162
+ this.processedArgs = [];
1163
+ this._scriptPath = null;
1164
+ this._name = name || "";
1165
+ this._optionValues = {};
1166
+ this._optionValueSources = {};
1167
+ this._storeOptionsAsProperties = false;
1168
+ this._actionHandler = null;
1169
+ this._executableHandler = false;
1170
+ this._executableFile = null;
1171
+ this._executableDir = null;
1172
+ this._defaultCommandName = null;
1173
+ this._exitCallback = null;
1174
+ this._aliases = [];
1175
+ this._combineFlagAndOptionalValue = true;
1176
+ this._description = "";
1177
+ this._summary = "";
1178
+ this._argsDescription = void 0;
1179
+ this._enablePositionalOptions = false;
1180
+ this._passThroughOptions = false;
1181
+ this._lifeCycleHooks = {};
1182
+ this._showHelpAfterError = false;
1183
+ this._showSuggestionAfterError = true;
1184
+ this._savedState = null;
1185
+ this._outputConfiguration = {
1186
+ writeOut: (str) => process2.stdout.write(str),
1187
+ writeErr: (str) => process2.stderr.write(str),
1188
+ outputError: (str, write) => write(str),
1189
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1190
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1191
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1192
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1193
+ stripColor: (str) => stripVTControlCharacters2(str)
1194
+ };
1195
+ this._hidden = false;
1196
+ this._helpOption = void 0;
1197
+ this._addImplicitHelpCommand = void 0;
1198
+ this._helpCommand = void 0;
1199
+ this._helpConfiguration = {};
1200
+ this._helpGroupHeading = void 0;
1201
+ this._defaultCommandGroup = void 0;
1202
+ this._defaultOptionGroup = void 0;
1203
+ }
1204
+ /**
1205
+ * Copy settings that are useful to have in common across root command and subcommands.
1206
+ *
1207
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1208
+ *
1209
+ * @param {Command} sourceCommand
1210
+ * @return {Command} `this` command for chaining
1211
+ */
1212
+ copyInheritedSettings(sourceCommand) {
1213
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1214
+ this._helpOption = sourceCommand._helpOption;
1215
+ this._helpCommand = sourceCommand._helpCommand;
1216
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1217
+ this._exitCallback = sourceCommand._exitCallback;
1218
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1219
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1220
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1221
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1222
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1223
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1224
+ return this;
1225
+ }
1226
+ /**
1227
+ * @returns {Command[]}
1228
+ * @private
1229
+ */
1230
+ _getCommandAndAncestors() {
1231
+ const result = [];
1232
+ for (let command = this; command; command = command.parent) {
1233
+ result.push(command);
1234
+ }
1235
+ return result;
1236
+ }
1237
+ /**
1238
+ * Define a command.
1239
+ *
1240
+ * There are two styles of command: pay attention to where to put the description.
1241
+ *
1242
+ * @example
1243
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1244
+ * program
1245
+ * .command('clone <source> [destination]')
1246
+ * .description('clone a repository into a newly created directory')
1247
+ * .action((source, destination) => {
1248
+ * console.log('clone command called');
1249
+ * });
1250
+ *
1251
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1252
+ * program
1253
+ * .command('start <service>', 'start named service')
1254
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1255
+ *
1256
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1257
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1258
+ * @param {object} [execOpts] - configuration options (for executable)
1259
+ * @return {Command} returns new command for action handler, or `this` for executable command
1260
+ */
1261
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1262
+ let desc = actionOptsOrExecDesc;
1263
+ let opts = execOpts;
1264
+ if (typeof desc === "object" && desc !== null) {
1265
+ opts = desc;
1266
+ desc = null;
1267
+ }
1268
+ opts = opts || {};
1269
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1270
+ const cmd = this.createCommand(name);
1271
+ if (desc) {
1272
+ cmd.description(desc);
1273
+ cmd._executableHandler = true;
1274
+ }
1275
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1276
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1277
+ cmd._executableFile = opts.executableFile || null;
1278
+ if (args) cmd.arguments(args);
1279
+ this._registerCommand(cmd);
1280
+ cmd.parent = this;
1281
+ cmd.copyInheritedSettings(this);
1282
+ if (desc) return this;
1283
+ return cmd;
1284
+ }
1285
+ /**
1286
+ * Factory routine to create a new unattached command.
1287
+ *
1288
+ * See .command() for creating an attached subcommand, which uses this routine to
1289
+ * create the command. You can override createCommand to customise subcommands.
1290
+ *
1291
+ * @param {string} [name]
1292
+ * @return {Command} new command
1293
+ */
1294
+ createCommand(name) {
1295
+ return new _Command(name);
1296
+ }
1297
+ /**
1298
+ * You can customise the help with a subclass of Help by overriding createHelp,
1299
+ * or by overriding Help properties using configureHelp().
1300
+ *
1301
+ * @return {Help}
1302
+ */
1303
+ createHelp() {
1304
+ return Object.assign(new Help(), this.configureHelp());
1305
+ }
1306
+ /**
1307
+ * You can customise the help by overriding Help properties using configureHelp(),
1308
+ * or with a subclass of Help by overriding createHelp().
1309
+ *
1310
+ * @param {object} [configuration] - configuration options
1311
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1312
+ */
1313
+ configureHelp(configuration) {
1314
+ if (configuration === void 0) return this._helpConfiguration;
1315
+ this._helpConfiguration = configuration;
1316
+ return this;
1317
+ }
1318
+ /**
1319
+ * The default output goes to stdout and stderr. You can customise this for special
1320
+ * applications. You can also customise the display of errors by overriding outputError.
1321
+ *
1322
+ * The configuration properties are all functions:
1323
+ *
1324
+ * // change how output being written, defaults to stdout and stderr
1325
+ * writeOut(str)
1326
+ * writeErr(str)
1327
+ * // change how output being written for errors, defaults to writeErr
1328
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1329
+ * // specify width for wrapping help
1330
+ * getOutHelpWidth()
1331
+ * getErrHelpWidth()
1332
+ * // color support, currently only used with Help
1333
+ * getOutHasColors()
1334
+ * getErrHasColors()
1335
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1336
+ *
1337
+ * @param {object} [configuration] - configuration options
1338
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1339
+ */
1340
+ configureOutput(configuration) {
1341
+ if (configuration === void 0) return this._outputConfiguration;
1342
+ this._outputConfiguration = {
1343
+ ...this._outputConfiguration,
1344
+ ...configuration
1345
+ };
1346
+ return this;
1347
+ }
1348
+ /**
1349
+ * Display the help or a custom message after an error occurs.
1350
+ *
1351
+ * @param {(boolean|string)} [displayHelp]
1352
+ * @return {Command} `this` command for chaining
1353
+ */
1354
+ showHelpAfterError(displayHelp = true) {
1355
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1356
+ this._showHelpAfterError = displayHelp;
1357
+ return this;
1358
+ }
1359
+ /**
1360
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1361
+ *
1362
+ * @param {boolean} [displaySuggestion]
1363
+ * @return {Command} `this` command for chaining
1364
+ */
1365
+ showSuggestionAfterError(displaySuggestion = true) {
1366
+ this._showSuggestionAfterError = !!displaySuggestion;
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Add a prepared subcommand.
1371
+ *
1372
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1373
+ *
1374
+ * @param {Command} cmd - new subcommand
1375
+ * @param {object} [opts] - configuration options
1376
+ * @return {Command} `this` command for chaining
1377
+ */
1378
+ addCommand(cmd, opts) {
1379
+ if (!cmd._name) {
1380
+ throw new Error(`Command passed to .addCommand() must have a name
1381
+ - specify the name in Command constructor or using .name()`);
1382
+ }
1383
+ opts = opts || {};
1384
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1385
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1386
+ this._registerCommand(cmd);
1387
+ cmd.parent = this;
1388
+ cmd._checkForBrokenPassThrough();
1389
+ return this;
1390
+ }
1391
+ /**
1392
+ * Factory routine to create a new unattached argument.
1393
+ *
1394
+ * See .argument() for creating an attached argument, which uses this routine to
1395
+ * create the argument. You can override createArgument to return a custom argument.
1396
+ *
1397
+ * @param {string} name
1398
+ * @param {string} [description]
1399
+ * @return {Argument} new argument
1400
+ */
1401
+ createArgument(name, description) {
1402
+ return new Argument(name, description);
1403
+ }
1404
+ /**
1405
+ * Define argument syntax for command.
1406
+ *
1407
+ * The default is that the argument is required, and you can explicitly
1408
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1409
+ *
1410
+ * @example
1411
+ * program.argument('<input-file>');
1412
+ * program.argument('[output-file]');
1413
+ *
1414
+ * @param {string} name
1415
+ * @param {string} [description]
1416
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1417
+ * @param {*} [defaultValue]
1418
+ * @return {Command} `this` command for chaining
1419
+ */
1420
+ argument(name, description, parseArg, defaultValue) {
1421
+ const argument = this.createArgument(name, description);
1422
+ if (typeof parseArg === "function") {
1423
+ argument.default(defaultValue).argParser(parseArg);
1424
+ } else {
1425
+ argument.default(parseArg);
1426
+ }
1427
+ this.addArgument(argument);
1428
+ return this;
1429
+ }
1430
+ /**
1431
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1432
+ *
1433
+ * See also .argument().
1434
+ *
1435
+ * @example
1436
+ * program.arguments('<cmd> [env]');
1437
+ *
1438
+ * @param {string} names
1439
+ * @return {Command} `this` command for chaining
1440
+ */
1441
+ arguments(names) {
1442
+ names.trim().split(/ +/).forEach((detail) => {
1443
+ this.argument(detail);
1444
+ });
1445
+ return this;
1446
+ }
1447
+ /**
1448
+ * Define argument syntax for command, adding a prepared argument.
1449
+ *
1450
+ * @param {Argument} argument
1451
+ * @return {Command} `this` command for chaining
1452
+ */
1453
+ addArgument(argument) {
1454
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1455
+ if (previousArgument?.variadic) {
1456
+ throw new Error(
1457
+ `only the last argument can be variadic '${previousArgument.name()}'`
1458
+ );
1459
+ }
1460
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1461
+ throw new Error(
1462
+ `a default value for a required argument is never used: '${argument.name()}'`
1463
+ );
1464
+ }
1465
+ this.registeredArguments.push(argument);
1466
+ return this;
1467
+ }
1468
+ /**
1469
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1470
+ *
1471
+ * @example
1472
+ * program.helpCommand('help [cmd]');
1473
+ * program.helpCommand('help [cmd]', 'show help');
1474
+ * program.helpCommand(false); // suppress default help command
1475
+ * program.helpCommand(true); // add help command even if no subcommands
1476
+ *
1477
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1478
+ * @param {string} [description] - custom description
1479
+ * @return {Command} `this` command for chaining
1480
+ */
1481
+ helpCommand(enableOrNameAndArgs, description) {
1482
+ if (typeof enableOrNameAndArgs === "boolean") {
1483
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1484
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1485
+ this._initCommandGroup(this._getHelpCommand());
1486
+ }
1487
+ return this;
1488
+ }
1489
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1490
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1491
+ const helpDescription = description ?? "display help for command";
1492
+ const helpCommand = this.createCommand(helpName);
1493
+ helpCommand.helpOption(false);
1494
+ if (helpArgs) helpCommand.arguments(helpArgs);
1495
+ if (helpDescription) helpCommand.description(helpDescription);
1496
+ this._addImplicitHelpCommand = true;
1497
+ this._helpCommand = helpCommand;
1498
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1499
+ return this;
1500
+ }
1501
+ /**
1502
+ * Add prepared custom help command.
1503
+ *
1504
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1505
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1506
+ * @return {Command} `this` command for chaining
1507
+ */
1508
+ addHelpCommand(helpCommand, deprecatedDescription) {
1509
+ if (typeof helpCommand !== "object") {
1510
+ this.helpCommand(helpCommand, deprecatedDescription);
1511
+ return this;
1512
+ }
1513
+ this._addImplicitHelpCommand = true;
1514
+ this._helpCommand = helpCommand;
1515
+ this._initCommandGroup(helpCommand);
1516
+ return this;
1517
+ }
1518
+ /**
1519
+ * Lazy create help command.
1520
+ *
1521
+ * @return {(Command|null)}
1522
+ * @package
1523
+ */
1524
+ _getHelpCommand() {
1525
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1526
+ if (hasImplicitHelpCommand) {
1527
+ if (this._helpCommand === void 0) {
1528
+ this.helpCommand(void 0, void 0);
1529
+ }
1530
+ return this._helpCommand;
1531
+ }
1532
+ return null;
1533
+ }
1534
+ /**
1535
+ * Add hook for life cycle event.
1536
+ *
1537
+ * @param {string} event
1538
+ * @param {Function} listener
1539
+ * @return {Command} `this` command for chaining
1540
+ */
1541
+ hook(event, listener) {
1542
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1543
+ if (!allowedValues.includes(event)) {
1544
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1545
+ Expecting one of '${allowedValues.join("', '")}'`);
1546
+ }
1547
+ if (this._lifeCycleHooks[event]) {
1548
+ this._lifeCycleHooks[event].push(listener);
1549
+ } else {
1550
+ this._lifeCycleHooks[event] = [listener];
1551
+ }
1552
+ return this;
1553
+ }
1554
+ /**
1555
+ * Register callback to use as replacement for calling process.exit.
1556
+ *
1557
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1558
+ * @return {Command} `this` command for chaining
1559
+ */
1560
+ exitOverride(fn) {
1561
+ if (fn) {
1562
+ this._exitCallback = fn;
1563
+ } else {
1564
+ this._exitCallback = (err) => {
1565
+ if (err.code !== "commander.executeSubCommandAsync") {
1566
+ throw err;
1567
+ } else {
1568
+ }
1569
+ };
1570
+ }
1571
+ return this;
1572
+ }
1573
+ /**
1574
+ * Call process.exit, and _exitCallback if defined.
1575
+ *
1576
+ * @param {number} exitCode exit code for using with process.exit
1577
+ * @param {string} code an id string representing the error
1578
+ * @param {string} message human-readable description of the error
1579
+ * @return never
1580
+ * @private
1581
+ */
1582
+ _exit(exitCode, code, message) {
1583
+ if (this._exitCallback) {
1584
+ this._exitCallback(new CommanderError(exitCode, code, message));
1585
+ }
1586
+ process2.exit(exitCode);
1587
+ }
1588
+ /**
1589
+ * Register callback `fn` for the command.
1590
+ *
1591
+ * @example
1592
+ * program
1593
+ * .command('serve')
1594
+ * .description('start service')
1595
+ * .action(function() {
1596
+ * // do work here
1597
+ * });
1598
+ *
1599
+ * @param {Function} fn
1600
+ * @return {Command} `this` command for chaining
1601
+ */
1602
+ action(fn) {
1603
+ const listener = (args) => {
1604
+ const expectedArgsCount = this.registeredArguments.length;
1605
+ const actionArgs = args.slice(0, expectedArgsCount);
1606
+ if (this._storeOptionsAsProperties) {
1607
+ actionArgs[expectedArgsCount] = this;
1608
+ } else {
1609
+ actionArgs[expectedArgsCount] = this.opts();
1610
+ }
1611
+ actionArgs.push(this);
1612
+ return fn.apply(this, actionArgs);
1613
+ };
1614
+ this._actionHandler = listener;
1615
+ return this;
1616
+ }
1617
+ /**
1618
+ * Factory routine to create a new unattached option.
1619
+ *
1620
+ * See .option() for creating an attached option, which uses this routine to
1621
+ * create the option. You can override createOption to return a custom option.
1622
+ *
1623
+ * @param {string} flags
1624
+ * @param {string} [description]
1625
+ * @return {Option} new option
1626
+ */
1627
+ createOption(flags, description) {
1628
+ return new Option(flags, description);
1629
+ }
1630
+ /**
1631
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1632
+ *
1633
+ * @param {(Option | Argument)} target
1634
+ * @param {string} value
1635
+ * @param {*} previous
1636
+ * @param {string} invalidArgumentMessage
1637
+ * @private
1638
+ */
1639
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1640
+ try {
1641
+ return target.parseArg(value, previous);
1642
+ } catch (err) {
1643
+ if (err.code === "commander.invalidArgument") {
1644
+ const message = `${invalidArgumentMessage} ${err.message}`;
1645
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1646
+ }
1647
+ throw err;
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Check for option flag conflicts.
1652
+ * Register option if no conflicts found, or throw on conflict.
1653
+ *
1654
+ * @param {Option} option
1655
+ * @private
1656
+ */
1657
+ _registerOption(option) {
1658
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1659
+ if (matchingOption) {
1660
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1661
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1662
+ - already used by option '${matchingOption.flags}'`);
1663
+ }
1664
+ this._initOptionGroup(option);
1665
+ this.options.push(option);
1666
+ }
1667
+ /**
1668
+ * Check for command name and alias conflicts with existing commands.
1669
+ * Register command if no conflicts found, or throw on conflict.
1670
+ *
1671
+ * @param {Command} command
1672
+ * @private
1673
+ */
1674
+ _registerCommand(command) {
1675
+ const knownBy = (cmd) => {
1676
+ return [cmd.name()].concat(cmd.aliases());
1677
+ };
1678
+ const alreadyUsed = knownBy(command).find(
1679
+ (name) => this._findCommand(name)
1680
+ );
1681
+ if (alreadyUsed) {
1682
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1683
+ const newCmd = knownBy(command).join("|");
1684
+ throw new Error(
1685
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1686
+ );
1687
+ }
1688
+ this._initCommandGroup(command);
1689
+ this.commands.push(command);
1690
+ }
1691
+ /**
1692
+ * Add an option.
1693
+ *
1694
+ * @param {Option} option
1695
+ * @return {Command} `this` command for chaining
1696
+ */
1697
+ addOption(option) {
1698
+ this._registerOption(option);
1699
+ const oname = option.name();
1700
+ const name = option.attributeName();
1701
+ if (option.defaultValue !== void 0) {
1702
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1703
+ }
1704
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1705
+ if (val == null && option.presetArg !== void 0) {
1706
+ val = option.presetArg;
1707
+ }
1708
+ const oldValue = this.getOptionValue(name);
1709
+ if (val !== null && option.parseArg) {
1710
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1711
+ } else if (val !== null && option.variadic) {
1712
+ val = option._collectValue(val, oldValue);
1713
+ }
1714
+ if (val == null) {
1715
+ if (option.negate) {
1716
+ val = false;
1717
+ } else if (option.isBoolean() || option.optional) {
1718
+ val = true;
1719
+ } else {
1720
+ val = "";
1721
+ }
1722
+ }
1723
+ this.setOptionValueWithSource(name, val, valueSource);
1724
+ };
1725
+ this.on("option:" + oname, (val) => {
1726
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1727
+ handleOptionValue(val, invalidValueMessage, "cli");
1728
+ });
1729
+ if (option.envVar) {
1730
+ this.on("optionEnv:" + oname, (val) => {
1731
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1732
+ handleOptionValue(val, invalidValueMessage, "env");
1733
+ });
1734
+ }
1735
+ return this;
1736
+ }
1737
+ /**
1738
+ * Internal implementation shared by .option() and .requiredOption()
1739
+ *
1740
+ * @return {Command} `this` command for chaining
1741
+ * @private
1742
+ */
1743
+ _optionEx(config, flags, description, fn, defaultValue) {
1744
+ if (typeof flags === "object" && flags instanceof Option) {
1745
+ throw new Error(
1746
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1747
+ );
1748
+ }
1749
+ const option = this.createOption(flags, description);
1750
+ option.makeOptionMandatory(!!config.mandatory);
1751
+ if (typeof fn === "function") {
1752
+ option.default(defaultValue).argParser(fn);
1753
+ } else if (fn instanceof RegExp) {
1754
+ const regex = fn;
1755
+ fn = (val, def) => {
1756
+ const m = regex.exec(val);
1757
+ return m ? m[0] : def;
1758
+ };
1759
+ option.default(defaultValue).argParser(fn);
1760
+ } else {
1761
+ option.default(fn);
1762
+ }
1763
+ return this.addOption(option);
1764
+ }
1765
+ /**
1766
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1767
+ *
1768
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1769
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1770
+ *
1771
+ * See the README for more details, and see also addOption() and requiredOption().
1772
+ *
1773
+ * @example
1774
+ * program
1775
+ * .option('-p, --pepper', 'add pepper')
1776
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1777
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1778
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1779
+ *
1780
+ * @param {string} flags
1781
+ * @param {string} [description]
1782
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1783
+ * @param {*} [defaultValue]
1784
+ * @return {Command} `this` command for chaining
1785
+ */
1786
+ option(flags, description, parseArg, defaultValue) {
1787
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1788
+ }
1789
+ /**
1790
+ * Add a required option which must have a value after parsing. This usually means
1791
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1792
+ *
1793
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1794
+ *
1795
+ * @param {string} flags
1796
+ * @param {string} [description]
1797
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1798
+ * @param {*} [defaultValue]
1799
+ * @return {Command} `this` command for chaining
1800
+ */
1801
+ requiredOption(flags, description, parseArg, defaultValue) {
1802
+ return this._optionEx(
1803
+ { mandatory: true },
1804
+ flags,
1805
+ description,
1806
+ parseArg,
1807
+ defaultValue
1808
+ );
1809
+ }
1810
+ /**
1811
+ * Alter parsing of short flags with optional values.
1812
+ *
1813
+ * @example
1814
+ * // for `.option('-f,--flag [value]'):
1815
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1816
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1817
+ *
1818
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1819
+ * @return {Command} `this` command for chaining
1820
+ */
1821
+ combineFlagAndOptionalValue(combine = true) {
1822
+ this._combineFlagAndOptionalValue = !!combine;
1823
+ return this;
1824
+ }
1825
+ /**
1826
+ * Allow unknown options on the command line.
1827
+ *
1828
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1829
+ * @return {Command} `this` command for chaining
1830
+ */
1831
+ allowUnknownOption(allowUnknown = true) {
1832
+ this._allowUnknownOption = !!allowUnknown;
1833
+ return this;
1834
+ }
1835
+ /**
1836
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1837
+ *
1838
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1839
+ * @return {Command} `this` command for chaining
1840
+ */
1841
+ allowExcessArguments(allowExcess = true) {
1842
+ this._allowExcessArguments = !!allowExcess;
1843
+ return this;
1844
+ }
1845
+ /**
1846
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1847
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1848
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1849
+ *
1850
+ * @param {boolean} [positional]
1851
+ * @return {Command} `this` command for chaining
1852
+ */
1853
+ enablePositionalOptions(positional = true) {
1854
+ this._enablePositionalOptions = !!positional;
1855
+ return this;
1856
+ }
1857
+ /**
1858
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1859
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1860
+ * positional options to have been enabled on the program (parent commands).
1861
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1862
+ *
1863
+ * @param {boolean} [passThrough] for unknown options.
1864
+ * @return {Command} `this` command for chaining
1865
+ */
1866
+ passThroughOptions(passThrough = true) {
1867
+ this._passThroughOptions = !!passThrough;
1868
+ this._checkForBrokenPassThrough();
1869
+ return this;
1870
+ }
1871
+ /**
1872
+ * @private
1873
+ */
1874
+ _checkForBrokenPassThrough() {
1875
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1876
+ throw new Error(
1877
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1878
+ );
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Whether to store option values as properties on command object,
1883
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1884
+ *
1885
+ * @param {boolean} [storeAsProperties=true]
1886
+ * @return {Command} `this` command for chaining
1887
+ */
1888
+ storeOptionsAsProperties(storeAsProperties = true) {
1889
+ if (this.options.length) {
1890
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1891
+ }
1892
+ if (Object.keys(this._optionValues).length) {
1893
+ throw new Error(
1894
+ "call .storeOptionsAsProperties() before setting option values"
1895
+ );
1896
+ }
1897
+ this._storeOptionsAsProperties = !!storeAsProperties;
1898
+ return this;
1899
+ }
1900
+ /**
1901
+ * Retrieve option value.
1902
+ *
1903
+ * @param {string} key
1904
+ * @return {object} value
1905
+ */
1906
+ getOptionValue(key) {
1907
+ if (this._storeOptionsAsProperties) {
1908
+ return this[key];
1909
+ }
1910
+ return this._optionValues[key];
1911
+ }
1912
+ /**
1913
+ * Store option value.
1914
+ *
1915
+ * @param {string} key
1916
+ * @param {object} value
1917
+ * @return {Command} `this` command for chaining
1918
+ */
1919
+ setOptionValue(key, value) {
1920
+ return this.setOptionValueWithSource(key, value, void 0);
1921
+ }
1922
+ /**
1923
+ * Store option value and where the value came from.
1924
+ *
1925
+ * @param {string} key
1926
+ * @param {object} value
1927
+ * @param {string} source - expected values are default/config/env/cli/implied
1928
+ * @return {Command} `this` command for chaining
1929
+ */
1930
+ setOptionValueWithSource(key, value, source) {
1931
+ if (this._storeOptionsAsProperties) {
1932
+ this[key] = value;
1933
+ } else {
1934
+ this._optionValues[key] = value;
1935
+ }
1936
+ this._optionValueSources[key] = source;
1937
+ return this;
1938
+ }
1939
+ /**
1940
+ * Get source of option value.
1941
+ * Expected values are default | config | env | cli | implied
1942
+ *
1943
+ * @param {string} key
1944
+ * @return {string}
1945
+ */
1946
+ getOptionValueSource(key) {
1947
+ return this._optionValueSources[key];
1948
+ }
1949
+ /**
1950
+ * Get source of option value. See also .optsWithGlobals().
1951
+ * Expected values are default | config | env | cli | implied
1952
+ *
1953
+ * @param {string} key
1954
+ * @return {string}
1955
+ */
1956
+ getOptionValueSourceWithGlobals(key) {
1957
+ let source;
1958
+ this._getCommandAndAncestors().forEach((cmd) => {
1959
+ if (cmd.getOptionValueSource(key) !== void 0) {
1960
+ source = cmd.getOptionValueSource(key);
1961
+ }
1962
+ });
1963
+ return source;
1964
+ }
1965
+ /**
1966
+ * Get user arguments from implied or explicit arguments.
1967
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1968
+ *
1969
+ * @private
1970
+ */
1971
+ _prepareUserArgs(argv, parseOptions) {
1972
+ if (argv !== void 0 && !Array.isArray(argv)) {
1973
+ throw new Error("first parameter to parse must be array or undefined");
1974
+ }
1975
+ parseOptions = parseOptions || {};
1976
+ if (argv === void 0 && parseOptions.from === void 0) {
1977
+ if (process2.versions?.electron) {
1978
+ parseOptions.from = "electron";
1979
+ }
1980
+ const execArgv = process2.execArgv ?? [];
1981
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1982
+ parseOptions.from = "eval";
1983
+ }
1984
+ }
1985
+ if (argv === void 0) {
1986
+ argv = process2.argv;
1987
+ }
1988
+ this.rawArgs = argv.slice();
1989
+ let userArgs;
1990
+ switch (parseOptions.from) {
1991
+ case void 0:
1992
+ case "node":
1993
+ this._scriptPath = argv[1];
1994
+ userArgs = argv.slice(2);
1995
+ break;
1996
+ case "electron":
1997
+ if (process2.defaultApp) {
1998
+ this._scriptPath = argv[1];
1999
+ userArgs = argv.slice(2);
2000
+ } else {
2001
+ userArgs = argv.slice(1);
2002
+ }
2003
+ break;
2004
+ case "user":
2005
+ userArgs = argv.slice(0);
2006
+ break;
2007
+ case "eval":
2008
+ userArgs = argv.slice(1);
2009
+ break;
2010
+ default:
2011
+ throw new Error(
2012
+ `unexpected parse option { from: '${parseOptions.from}' }`
2013
+ );
2014
+ }
2015
+ if (!this._name && this._scriptPath)
2016
+ this.nameFromFilename(this._scriptPath);
2017
+ this._name = this._name || "program";
2018
+ return userArgs;
2019
+ }
2020
+ /**
2021
+ * Parse `argv`, setting options and invoking commands when defined.
2022
+ *
2023
+ * Use parseAsync instead of parse if any of your action handlers are async.
2024
+ *
2025
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2026
+ *
2027
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2028
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2029
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2030
+ * - `'user'`: just user arguments
2031
+ *
2032
+ * @example
2033
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2034
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2035
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2036
+ *
2037
+ * @param {string[]} [argv] - optional, defaults to process.argv
2038
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2039
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2040
+ * @return {Command} `this` command for chaining
2041
+ */
2042
+ parse(argv, parseOptions) {
2043
+ this._prepareForParse();
2044
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2045
+ this._parseCommand([], userArgs);
2046
+ return this;
2047
+ }
2048
+ /**
2049
+ * Parse `argv`, setting options and invoking commands when defined.
2050
+ *
2051
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2052
+ *
2053
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2054
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2055
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2056
+ * - `'user'`: just user arguments
2057
+ *
2058
+ * @example
2059
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2060
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2061
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2062
+ *
2063
+ * @param {string[]} [argv]
2064
+ * @param {object} [parseOptions]
2065
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2066
+ * @return {Promise}
2067
+ */
2068
+ async parseAsync(argv, parseOptions) {
2069
+ this._prepareForParse();
2070
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2071
+ await this._parseCommand([], userArgs);
2072
+ return this;
2073
+ }
2074
+ _prepareForParse() {
2075
+ if (this._savedState === null) {
2076
+ this.options.filter(
2077
+ (option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
2078
+ ).forEach((option) => {
2079
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
2080
+ if (!this._findOption(positiveLongFlag)) {
2081
+ this.setOptionValueWithSource(
2082
+ option.attributeName(),
2083
+ true,
2084
+ "default"
2085
+ );
2086
+ }
2087
+ });
2088
+ this.saveStateBeforeParse();
2089
+ } else {
2090
+ this.restoreStateBeforeParse();
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2095
+ * Not usually called directly, but available for subclasses to save their custom state.
2096
+ *
2097
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2098
+ */
2099
+ saveStateBeforeParse() {
2100
+ this._savedState = {
2101
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2102
+ _name: this._name,
2103
+ // option values before parse have default values (including false for negated options)
2104
+ // shallow clones
2105
+ _optionValues: { ...this._optionValues },
2106
+ _optionValueSources: { ...this._optionValueSources }
2107
+ };
2108
+ }
2109
+ /**
2110
+ * Restore state before parse for calls after the first.
2111
+ * Not usually called directly, but available for subclasses to save their custom state.
2112
+ *
2113
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2114
+ */
2115
+ restoreStateBeforeParse() {
2116
+ if (this._storeOptionsAsProperties)
2117
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2118
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2119
+ this._name = this._savedState._name;
2120
+ this._scriptPath = null;
2121
+ this.rawArgs = [];
2122
+ this._optionValues = { ...this._savedState._optionValues };
2123
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2124
+ this.args = [];
2125
+ this.processedArgs = [];
2126
+ }
2127
+ /**
2128
+ * Throw if expected executable is missing. Add lots of help for author.
2129
+ *
2130
+ * @param {string} executableFile
2131
+ * @param {string} executableDir
2132
+ * @param {string} subcommandName
2133
+ */
2134
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2135
+ if (fs.existsSync(executableFile)) return;
2136
+ 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";
2137
+ const executableMissing = `'${executableFile}' does not exist
2138
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2139
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2140
+ - ${executableDirMessage}`;
2141
+ throw new Error(executableMissing);
2142
+ }
2143
+ /**
2144
+ * Execute a sub-command executable.
2145
+ *
2146
+ * @private
2147
+ */
2148
+ _executeSubCommand(subcommand, args) {
2149
+ args = args.slice();
2150
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2151
+ function findFile(baseDir, baseName) {
2152
+ const localBin = path.resolve(baseDir, baseName);
2153
+ if (fs.existsSync(localBin)) return localBin;
2154
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2155
+ const foundExt = sourceExt.find(
2156
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2157
+ );
2158
+ if (foundExt) return `${localBin}${foundExt}`;
2159
+ return void 0;
2160
+ }
2161
+ this._checkForMissingMandatoryOptions();
2162
+ this._checkForConflictingOptions();
2163
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2164
+ let executableDir = this._executableDir || "";
2165
+ if (this._scriptPath) {
2166
+ let resolvedScriptPath;
2167
+ try {
2168
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2169
+ } catch {
2170
+ resolvedScriptPath = this._scriptPath;
2171
+ }
2172
+ executableDir = path.resolve(
2173
+ path.dirname(resolvedScriptPath),
2174
+ executableDir
2175
+ );
2176
+ }
2177
+ if (executableDir) {
2178
+ let localFile = findFile(executableDir, executableFile);
2179
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2180
+ const legacyName = path.basename(
2181
+ this._scriptPath,
2182
+ path.extname(this._scriptPath)
2183
+ );
2184
+ if (legacyName !== this._name) {
2185
+ localFile = findFile(
2186
+ executableDir,
2187
+ `${legacyName}-${subcommand._name}`
2188
+ );
2189
+ }
2190
+ }
2191
+ executableFile = localFile || executableFile;
2192
+ }
2193
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
2194
+ let proc;
2195
+ if (process2.platform !== "win32") {
2196
+ if (launchWithNode) {
2197
+ args.unshift(executableFile);
2198
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2199
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2200
+ } else {
2201
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2202
+ }
2203
+ } else {
2204
+ this._checkForMissingExecutable(
2205
+ executableFile,
2206
+ executableDir,
2207
+ subcommand._name
2208
+ );
2209
+ args.unshift(executableFile);
2210
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2211
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2212
+ }
2213
+ if (!proc.killed) {
2214
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2215
+ signals.forEach((signal) => {
2216
+ process2.on(signal, () => {
2217
+ if (proc.killed === false && proc.exitCode === null) {
2218
+ proc.kill(signal);
2219
+ }
2220
+ });
2221
+ });
2222
+ }
2223
+ const exitCallback = this._exitCallback;
2224
+ proc.on("close", (code) => {
2225
+ code = code ?? 1;
2226
+ if (!exitCallback) {
2227
+ process2.exit(code);
2228
+ } else {
2229
+ exitCallback(
2230
+ new CommanderError(
2231
+ code,
2232
+ "commander.executeSubCommandAsync",
2233
+ "(close)"
2234
+ )
2235
+ );
2236
+ }
2237
+ });
2238
+ proc.on("error", (err) => {
2239
+ if (err.code === "ENOENT") {
2240
+ this._checkForMissingExecutable(
2241
+ executableFile,
2242
+ executableDir,
2243
+ subcommand._name
2244
+ );
2245
+ } else if (err.code === "EACCES") {
2246
+ throw new Error(`'${executableFile}' not executable`);
2247
+ }
2248
+ if (!exitCallback) {
2249
+ process2.exit(1);
2250
+ } else {
2251
+ const wrappedError = new CommanderError(
2252
+ 1,
2253
+ "commander.executeSubCommandAsync",
2254
+ "(error)"
2255
+ );
2256
+ wrappedError.nestedError = err;
2257
+ exitCallback(wrappedError);
2258
+ }
2259
+ });
2260
+ this.runningCommand = proc;
2261
+ }
2262
+ /**
2263
+ * @private
2264
+ */
2265
+ _dispatchSubcommand(commandName, operands, unknown) {
2266
+ const subCommand = this._findCommand(commandName);
2267
+ if (!subCommand) this.help({ error: true });
2268
+ subCommand._prepareForParse();
2269
+ let promiseChain;
2270
+ promiseChain = this._chainOrCallSubCommandHook(
2271
+ promiseChain,
2272
+ subCommand,
2273
+ "preSubcommand"
2274
+ );
2275
+ promiseChain = this._chainOrCall(promiseChain, () => {
2276
+ if (subCommand._executableHandler) {
2277
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2278
+ } else {
2279
+ return subCommand._parseCommand(operands, unknown);
2280
+ }
2281
+ });
2282
+ return promiseChain;
2283
+ }
2284
+ /**
2285
+ * Invoke help directly if possible, or dispatch if necessary.
2286
+ * e.g. help foo
2287
+ *
2288
+ * @private
2289
+ */
2290
+ _dispatchHelpCommand(subcommandName) {
2291
+ if (!subcommandName) {
2292
+ this.help();
2293
+ }
2294
+ const subCommand = this._findCommand(subcommandName);
2295
+ if (subCommand && !subCommand._executableHandler) {
2296
+ subCommand.help();
2297
+ }
2298
+ return this._dispatchSubcommand(
2299
+ subcommandName,
2300
+ [],
2301
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2302
+ );
2303
+ }
2304
+ /**
2305
+ * Check this.args against expected this.registeredArguments.
2306
+ *
2307
+ * @private
2308
+ */
2309
+ _checkNumberOfArguments() {
2310
+ this.registeredArguments.forEach((arg, i) => {
2311
+ if (arg.required && this.args[i] == null) {
2312
+ this.missingArgument(arg.name());
2313
+ }
2314
+ });
2315
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2316
+ return;
2317
+ }
2318
+ if (this.args.length > this.registeredArguments.length) {
2319
+ this._excessArguments(this.args);
2320
+ }
2321
+ }
2322
+ /**
2323
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2324
+ *
2325
+ * @private
2326
+ */
2327
+ _processArguments() {
2328
+ const myParseArg = (argument, value, previous) => {
2329
+ let parsedValue = value;
2330
+ if (value !== null && argument.parseArg) {
2331
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2332
+ parsedValue = this._callParseArg(
2333
+ argument,
2334
+ value,
2335
+ previous,
2336
+ invalidValueMessage
2337
+ );
2338
+ }
2339
+ return parsedValue;
2340
+ };
2341
+ this._checkNumberOfArguments();
2342
+ const processedArgs = [];
2343
+ this.registeredArguments.forEach((declaredArg, index) => {
2344
+ let value = declaredArg.defaultValue;
2345
+ if (declaredArg.variadic) {
2346
+ if (index < this.args.length) {
2347
+ value = this.args.slice(index);
2348
+ if (declaredArg.parseArg) {
2349
+ value = value.reduce((processed, v) => {
2350
+ return myParseArg(declaredArg, v, processed);
2351
+ }, declaredArg.defaultValue);
2352
+ }
2353
+ } else if (value === void 0) {
2354
+ value = [];
2355
+ }
2356
+ } else if (index < this.args.length) {
2357
+ value = this.args[index];
2358
+ if (declaredArg.parseArg) {
2359
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2360
+ }
2361
+ }
2362
+ processedArgs[index] = value;
2363
+ });
2364
+ this.processedArgs = processedArgs;
2365
+ }
2366
+ /**
2367
+ * Once we have a promise we chain, but call synchronously until then.
2368
+ *
2369
+ * @param {(Promise|undefined)} promise
2370
+ * @param {Function} fn
2371
+ * @return {(Promise|undefined)}
2372
+ * @private
2373
+ */
2374
+ _chainOrCall(promise, fn) {
2375
+ if (promise?.then && typeof promise.then === "function") {
2376
+ return promise.then(() => fn());
2377
+ }
2378
+ return fn();
2379
+ }
2380
+ /**
2381
+ *
2382
+ * @param {(Promise|undefined)} promise
2383
+ * @param {string} event
2384
+ * @return {(Promise|undefined)}
2385
+ * @private
2386
+ */
2387
+ _chainOrCallHooks(promise, event) {
2388
+ let result = promise;
2389
+ const hooks = [];
2390
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2391
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2392
+ hooks.push({ hookedCommand, callback });
2393
+ });
2394
+ });
2395
+ if (event === "postAction") {
2396
+ hooks.reverse();
2397
+ }
2398
+ hooks.forEach((hookDetail) => {
2399
+ result = this._chainOrCall(result, () => {
2400
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2401
+ });
2402
+ });
2403
+ return result;
2404
+ }
2405
+ /**
2406
+ *
2407
+ * @param {(Promise|undefined)} promise
2408
+ * @param {Command} subCommand
2409
+ * @param {string} event
2410
+ * @return {(Promise|undefined)}
2411
+ * @private
2412
+ */
2413
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2414
+ let result = promise;
2415
+ if (this._lifeCycleHooks[event] !== void 0) {
2416
+ this._lifeCycleHooks[event].forEach((hook) => {
2417
+ result = this._chainOrCall(result, () => {
2418
+ return hook(this, subCommand);
2419
+ });
2420
+ });
2421
+ }
2422
+ return result;
2423
+ }
2424
+ /**
2425
+ * Process arguments in context of this command.
2426
+ * Returns action result, in case it is a promise.
2427
+ *
2428
+ * @private
2429
+ */
2430
+ _parseCommand(operands, unknown) {
2431
+ const parsed = this.parseOptions(unknown);
2432
+ this._parseOptionsEnv();
2433
+ this._parseOptionsImplied();
2434
+ operands = operands.concat(parsed.operands);
2435
+ unknown = parsed.unknown;
2436
+ this.args = operands.concat(unknown);
2437
+ if (operands && this._findCommand(operands[0])) {
2438
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2439
+ }
2440
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2441
+ return this._dispatchHelpCommand(operands[1]);
2442
+ }
2443
+ if (this._defaultCommandName) {
2444
+ this._outputHelpIfRequested(unknown);
2445
+ return this._dispatchSubcommand(
2446
+ this._defaultCommandName,
2447
+ operands,
2448
+ unknown
2449
+ );
2450
+ }
2451
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2452
+ this.help({ error: true });
2453
+ }
2454
+ this._outputHelpIfRequested(parsed.unknown);
2455
+ this._checkForMissingMandatoryOptions();
2456
+ this._checkForConflictingOptions();
2457
+ const checkForUnknownOptions = () => {
2458
+ if (parsed.unknown.length > 0) {
2459
+ this.unknownOption(parsed.unknown[0]);
2460
+ }
2461
+ };
2462
+ const commandEvent = `command:${this.name()}`;
2463
+ if (this._actionHandler) {
2464
+ checkForUnknownOptions();
2465
+ this._processArguments();
2466
+ let promiseChain;
2467
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2468
+ promiseChain = this._chainOrCall(
2469
+ promiseChain,
2470
+ () => this._actionHandler(this.processedArgs)
2471
+ );
2472
+ if (this.parent) {
2473
+ promiseChain = this._chainOrCall(promiseChain, () => {
2474
+ this.parent.emit(commandEvent, operands, unknown);
2475
+ });
2476
+ }
2477
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2478
+ return promiseChain;
2479
+ }
2480
+ if (this.parent?.listenerCount(commandEvent)) {
2481
+ checkForUnknownOptions();
2482
+ this._processArguments();
2483
+ this.parent.emit(commandEvent, operands, unknown);
2484
+ } else if (operands.length) {
2485
+ if (this._findCommand("*")) {
2486
+ return this._dispatchSubcommand("*", operands, unknown);
2487
+ }
2488
+ if (this.listenerCount("command:*")) {
2489
+ this.emit("command:*", operands, unknown);
2490
+ } else if (this.commands.length) {
2491
+ this.unknownCommand();
2492
+ } else {
2493
+ checkForUnknownOptions();
2494
+ this._processArguments();
2495
+ }
2496
+ } else if (this.commands.length) {
2497
+ checkForUnknownOptions();
2498
+ this.help({ error: true });
2499
+ } else {
2500
+ checkForUnknownOptions();
2501
+ this._processArguments();
2502
+ }
2503
+ }
2504
+ /**
2505
+ * Find matching command.
2506
+ *
2507
+ * @private
2508
+ * @return {Command | undefined}
2509
+ */
2510
+ _findCommand(name) {
2511
+ if (!name) return void 0;
2512
+ return this.commands.find(
2513
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2514
+ );
2515
+ }
2516
+ /**
2517
+ * Return an option matching `arg` if any.
2518
+ *
2519
+ * @param {string} arg
2520
+ * @return {Option}
2521
+ * @package
2522
+ */
2523
+ _findOption(arg) {
2524
+ return this.options.find((option) => option.is(arg));
2525
+ }
2526
+ /**
2527
+ * Display an error message if a mandatory option does not have a value.
2528
+ * Called after checking for help flags in leaf subcommand.
2529
+ *
2530
+ * @private
2531
+ */
2532
+ _checkForMissingMandatoryOptions() {
2533
+ this._getCommandAndAncestors().forEach((cmd) => {
2534
+ cmd.options.forEach((anOption) => {
2535
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2536
+ cmd.missingMandatoryOptionValue(anOption);
2537
+ }
2538
+ });
2539
+ });
2540
+ }
2541
+ /**
2542
+ * Display an error message if conflicting options are used together in this.
2543
+ *
2544
+ * @private
2545
+ */
2546
+ _checkForConflictingLocalOptions() {
2547
+ const definedNonDefaultOptions = this.options.filter((option) => {
2548
+ const optionKey = option.attributeName();
2549
+ if (this.getOptionValue(optionKey) === void 0) {
2550
+ return false;
2551
+ }
2552
+ return this.getOptionValueSource(optionKey) !== "default";
2553
+ });
2554
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2555
+ (option) => option.conflictsWith.length > 0
2556
+ );
2557
+ optionsWithConflicting.forEach((option) => {
2558
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2559
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2560
+ );
2561
+ if (conflictingAndDefined) {
2562
+ this._conflictingOption(option, conflictingAndDefined);
2563
+ }
2564
+ });
2565
+ }
2566
+ /**
2567
+ * Display an error message if conflicting options are used together.
2568
+ * Called after checking for help flags in leaf subcommand.
2569
+ *
2570
+ * @private
2571
+ */
2572
+ _checkForConflictingOptions() {
2573
+ this._getCommandAndAncestors().forEach((cmd) => {
2574
+ cmd._checkForConflictingLocalOptions();
2575
+ });
2576
+ }
2577
+ /**
2578
+ * Parse options from `argv` removing known options,
2579
+ * and return argv split into operands and unknown arguments.
2580
+ *
2581
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2582
+ *
2583
+ * Examples:
2584
+ *
2585
+ * argv => operands, unknown
2586
+ * --known kkk op => [op], []
2587
+ * op --known kkk => [op], []
2588
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2589
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2590
+ *
2591
+ * @param {string[]} args
2592
+ * @return {{operands: string[], unknown: string[]}}
2593
+ */
2594
+ parseOptions(args) {
2595
+ const operands = [];
2596
+ const unknown = [];
2597
+ let dest = operands;
2598
+ function maybeOption(arg) {
2599
+ return arg.length > 1 && arg[0] === "-";
2600
+ }
2601
+ const negativeNumberArg = (arg) => {
2602
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2603
+ return !this._getCommandAndAncestors().some(
2604
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2605
+ );
2606
+ };
2607
+ let activeVariadicOption = null;
2608
+ let activeGroup = null;
2609
+ let i = 0;
2610
+ while (i < args.length || activeGroup) {
2611
+ const arg = activeGroup ?? args[i++];
2612
+ activeGroup = null;
2613
+ if (arg === "--") {
2614
+ if (dest === unknown) dest.push(arg);
2615
+ dest.push(...args.slice(i));
2616
+ break;
2617
+ }
2618
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2619
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2620
+ continue;
2621
+ }
2622
+ activeVariadicOption = null;
2623
+ if (maybeOption(arg)) {
2624
+ const option = this._findOption(arg);
2625
+ if (option) {
2626
+ if (option.required) {
2627
+ const value = args[i++];
2628
+ if (value === void 0) this.optionMissingArgument(option);
2629
+ this.emit(`option:${option.name()}`, value);
2630
+ } else if (option.optional) {
2631
+ let value = null;
2632
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2633
+ value = args[i++];
2634
+ }
2635
+ this.emit(`option:${option.name()}`, value);
2636
+ } else {
2637
+ this.emit(`option:${option.name()}`);
2638
+ }
2639
+ activeVariadicOption = option.variadic ? option : null;
2640
+ continue;
2641
+ }
2642
+ }
2643
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2644
+ const option = this._findOption(`-${arg[1]}`);
2645
+ if (option) {
2646
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2647
+ this.emit(`option:${option.name()}`, arg.slice(2));
2648
+ } else {
2649
+ this.emit(`option:${option.name()}`);
2650
+ activeGroup = `-${arg.slice(2)}`;
2651
+ }
2652
+ continue;
2653
+ }
2654
+ }
2655
+ if (/^--[^=]+=/.test(arg)) {
2656
+ const index = arg.indexOf("=");
2657
+ const option = this._findOption(arg.slice(0, index));
2658
+ if (option && (option.required || option.optional)) {
2659
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2660
+ continue;
2661
+ }
2662
+ }
2663
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2664
+ dest = unknown;
2665
+ }
2666
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2667
+ if (this._findCommand(arg)) {
2668
+ operands.push(arg);
2669
+ unknown.push(...args.slice(i));
2670
+ break;
2671
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2672
+ operands.push(arg, ...args.slice(i));
2673
+ break;
2674
+ } else if (this._defaultCommandName) {
2675
+ unknown.push(arg, ...args.slice(i));
2676
+ break;
2677
+ }
2678
+ }
2679
+ if (this._passThroughOptions) {
2680
+ dest.push(arg, ...args.slice(i));
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 received = receivedArgs.length;
2885
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2886
+ const details = receivedArgs.join(", ");
2887
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
2888
+ this.error(message, { code: "commander.excessArguments" });
2889
+ }
2890
+ /**
2891
+ * Unknown command.
2892
+ *
2893
+ * @private
2894
+ */
2895
+ unknownCommand() {
2896
+ const unknownName = this.args[0];
2897
+ let suggestion = "";
2898
+ if (this._showSuggestionAfterError) {
2899
+ const candidateNames = [];
2900
+ this.createHelp().visibleCommands(this).forEach((command) => {
2901
+ candidateNames.push(command.name());
2902
+ if (command.alias()) candidateNames.push(command.alias());
2903
+ });
2904
+ suggestion = suggestSimilar(unknownName, candidateNames);
2905
+ }
2906
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2907
+ this.error(message, { code: "commander.unknownCommand" });
2908
+ }
2909
+ /**
2910
+ * Get or set the program version.
2911
+ *
2912
+ * This method auto-registers the "-V, --version" option which will print the version number.
2913
+ *
2914
+ * You can optionally supply the flags and description to override the defaults.
2915
+ *
2916
+ * @param {string} [str]
2917
+ * @param {string} [flags]
2918
+ * @param {string} [description]
2919
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2920
+ */
2921
+ version(str, flags, description) {
2922
+ if (str === void 0) return this._version;
2923
+ this._version = str;
2924
+ flags = flags || "-V, --version";
2925
+ description = description || "output the version number";
2926
+ const versionOption = this.createOption(flags, description);
2927
+ this._versionOptionName = versionOption.attributeName();
2928
+ this._registerOption(versionOption);
2929
+ this.on("option:" + versionOption.name(), () => {
2930
+ this._outputConfiguration.writeOut(`${str}
2931
+ `);
2932
+ this._exit(0, "commander.version", str);
2933
+ });
2934
+ return this;
2935
+ }
2936
+ /**
2937
+ * Set the description.
2938
+ *
2939
+ * @param {string} [str]
2940
+ * @param {object} [argsDescription]
2941
+ * @return {(string|Command)}
2942
+ */
2943
+ description(str, argsDescription) {
2944
+ if (str === void 0 && argsDescription === void 0)
2945
+ return this._description;
2946
+ this._description = str;
2947
+ if (argsDescription) {
2948
+ this._argsDescription = argsDescription;
2949
+ }
2950
+ return this;
2951
+ }
2952
+ /**
2953
+ * Set the summary. Used when listed as subcommand of parent.
2954
+ *
2955
+ * @param {string} [str]
2956
+ * @return {(string|Command)}
2957
+ */
2958
+ summary(str) {
2959
+ if (str === void 0) return this._summary;
2960
+ this._summary = str;
2961
+ return this;
2962
+ }
2963
+ /**
2964
+ * Set an alias for the command.
2965
+ *
2966
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2967
+ *
2968
+ * @param {string} [alias]
2969
+ * @return {(string|Command)}
2970
+ */
2971
+ alias(alias) {
2972
+ if (alias === void 0) return this._aliases[0];
2973
+ let command = this;
2974
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2975
+ command = this.commands[this.commands.length - 1];
2976
+ }
2977
+ if (alias === command._name)
2978
+ throw new Error("Command alias can't be the same as its name");
2979
+ const matchingCommand = this.parent?._findCommand(alias);
2980
+ if (matchingCommand) {
2981
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2982
+ throw new Error(
2983
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2984
+ );
2985
+ }
2986
+ command._aliases.push(alias);
2987
+ return this;
2988
+ }
2989
+ /**
2990
+ * Set aliases for the command.
2991
+ *
2992
+ * Only the first alias is shown in the auto-generated help.
2993
+ *
2994
+ * @param {string[]} [aliases]
2995
+ * @return {(string[]|Command)}
2996
+ */
2997
+ aliases(aliases) {
2998
+ if (aliases === void 0) return this._aliases;
2999
+ aliases.forEach((alias) => this.alias(alias));
3000
+ return this;
3001
+ }
3002
+ /**
3003
+ * Set / get the command usage `str`.
3004
+ *
3005
+ * @param {string} [str]
3006
+ * @return {(string|Command)}
3007
+ */
3008
+ usage(str) {
3009
+ if (str === void 0) {
3010
+ if (this._usage) return this._usage;
3011
+ const args = this.registeredArguments.map((arg) => {
3012
+ return humanReadableArgName(arg);
3013
+ });
3014
+ return [].concat(
3015
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3016
+ this.commands.length ? "[command]" : [],
3017
+ this.registeredArguments.length ? args : []
3018
+ ).join(" ");
3019
+ }
3020
+ this._usage = str;
3021
+ return this;
3022
+ }
3023
+ /**
3024
+ * Get or set the name of the command.
3025
+ *
3026
+ * @param {string} [str]
3027
+ * @return {(string|Command)}
3028
+ */
3029
+ name(str) {
3030
+ if (str === void 0) return this._name;
3031
+ this._name = str;
3032
+ return this;
3033
+ }
3034
+ /**
3035
+ * Set/get the help group heading for this subcommand in parent command's help.
3036
+ *
3037
+ * @param {string} [heading]
3038
+ * @return {Command | string}
3039
+ */
3040
+ helpGroup(heading) {
3041
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3042
+ this._helpGroupHeading = heading;
3043
+ return this;
3044
+ }
3045
+ /**
3046
+ * Set/get the default help group heading for subcommands added to this command.
3047
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3048
+ *
3049
+ * @example
3050
+ * program.commandsGroup('Development Commands:);
3051
+ * program.command('watch')...
3052
+ * program.command('lint')...
3053
+ * ...
3054
+ *
3055
+ * @param {string} [heading]
3056
+ * @returns {Command | string}
3057
+ */
3058
+ commandsGroup(heading) {
3059
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3060
+ this._defaultCommandGroup = heading;
3061
+ return this;
3062
+ }
3063
+ /**
3064
+ * Set/get the default help group heading for options added to this command.
3065
+ * (This does not override a group set directly on the option using .helpGroup().)
3066
+ *
3067
+ * @example
3068
+ * program
3069
+ * .optionsGroup('Development Options:')
3070
+ * .option('-d, --debug', 'output extra debugging')
3071
+ * .option('-p, --profile', 'output profiling information')
3072
+ *
3073
+ * @param {string} [heading]
3074
+ * @returns {Command | string}
3075
+ */
3076
+ optionsGroup(heading) {
3077
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3078
+ this._defaultOptionGroup = heading;
3079
+ return this;
3080
+ }
3081
+ /**
3082
+ * @param {Option} option
3083
+ * @private
3084
+ */
3085
+ _initOptionGroup(option) {
3086
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3087
+ option.helpGroup(this._defaultOptionGroup);
3088
+ }
3089
+ /**
3090
+ * @param {Command} cmd
3091
+ * @private
3092
+ */
3093
+ _initCommandGroup(cmd) {
3094
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3095
+ cmd.helpGroup(this._defaultCommandGroup);
3096
+ }
3097
+ /**
3098
+ * Set the name of the command from script filename, such as process.argv[1],
3099
+ * or import.meta.filename.
3100
+ *
3101
+ * (Used internally and public although not documented in README.)
3102
+ *
3103
+ * @example
3104
+ * program.nameFromFilename(import.meta.filename);
3105
+ *
3106
+ * @param {string} filename
3107
+ * @return {Command}
3108
+ */
3109
+ nameFromFilename(filename) {
3110
+ this._name = path.basename(filename, path.extname(filename));
3111
+ return this;
3112
+ }
3113
+ /**
3114
+ * Get or set the directory for searching for executable subcommands of this command.
3115
+ *
3116
+ * @example
3117
+ * program.executableDir(import.meta.dirname);
3118
+ * // or
3119
+ * program.executableDir('subcommands');
3120
+ *
3121
+ * @param {string} [path]
3122
+ * @return {(string|null|Command)}
3123
+ */
3124
+ executableDir(path2) {
3125
+ if (path2 === void 0) return this._executableDir;
3126
+ this._executableDir = path2;
3127
+ return this;
3128
+ }
3129
+ /**
3130
+ * Return program help documentation.
3131
+ *
3132
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3133
+ * @return {string}
3134
+ */
3135
+ helpInformation(contextOptions) {
3136
+ const helper = this.createHelp();
3137
+ const context = this._getOutputContext(contextOptions);
3138
+ helper.prepareContext({
3139
+ error: context.error,
3140
+ helpWidth: context.helpWidth,
3141
+ outputHasColors: context.hasColors
3142
+ });
3143
+ const text = helper.formatHelp(this, helper);
3144
+ if (context.hasColors) return text;
3145
+ return this._outputConfiguration.stripColor(text);
3146
+ }
3147
+ /**
3148
+ * @typedef HelpContext
3149
+ * @type {object}
3150
+ * @property {boolean} error
3151
+ * @property {number} helpWidth
3152
+ * @property {boolean} hasColors
3153
+ * @property {function} write - includes stripColor if needed
3154
+ *
3155
+ * @returns {HelpContext}
3156
+ * @private
3157
+ */
3158
+ _getOutputContext(contextOptions) {
3159
+ contextOptions = contextOptions || {};
3160
+ const error = !!contextOptions.error;
3161
+ let baseWrite;
3162
+ let hasColors;
3163
+ let helpWidth;
3164
+ if (error) {
3165
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3166
+ hasColors = this._outputConfiguration.getErrHasColors();
3167
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3168
+ } else {
3169
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3170
+ hasColors = this._outputConfiguration.getOutHasColors();
3171
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3172
+ }
3173
+ const write = (str) => {
3174
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3175
+ return baseWrite(str);
3176
+ };
3177
+ return { error, write, hasColors, helpWidth };
3178
+ }
3179
+ /**
3180
+ * Output help information for this command.
3181
+ *
3182
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3183
+ *
3184
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3185
+ */
3186
+ outputHelp(contextOptions) {
3187
+ let deprecatedCallback;
3188
+ if (typeof contextOptions === "function") {
3189
+ deprecatedCallback = contextOptions;
3190
+ contextOptions = void 0;
3191
+ }
3192
+ const outputContext = this._getOutputContext(contextOptions);
3193
+ const eventContext = {
3194
+ error: outputContext.error,
3195
+ write: outputContext.write,
3196
+ command: this
3197
+ };
3198
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3199
+ this.emit("beforeHelp", eventContext);
3200
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3201
+ if (deprecatedCallback) {
3202
+ helpInformation = deprecatedCallback(helpInformation);
3203
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3204
+ throw new Error("outputHelp callback must return a string or a Buffer");
3205
+ }
3206
+ }
3207
+ outputContext.write(helpInformation);
3208
+ if (this._getHelpOption()?.long) {
3209
+ this.emit(this._getHelpOption().long);
3210
+ }
3211
+ this.emit("afterHelp", eventContext);
3212
+ this._getCommandAndAncestors().forEach(
3213
+ (command) => command.emit("afterAllHelp", eventContext)
3214
+ );
3215
+ }
3216
+ /**
3217
+ * You can pass in flags and a description to customise the built-in help option.
3218
+ * Pass in false to disable the built-in help option.
3219
+ *
3220
+ * @example
3221
+ * program.helpOption('-?, --help' 'show help'); // customise
3222
+ * program.helpOption(false); // disable
3223
+ *
3224
+ * @param {(string | boolean)} flags
3225
+ * @param {string} [description]
3226
+ * @return {Command} `this` command for chaining
3227
+ */
3228
+ helpOption(flags, description) {
3229
+ if (typeof flags === "boolean") {
3230
+ if (flags) {
3231
+ if (this._helpOption === null) this._helpOption = void 0;
3232
+ if (this._defaultOptionGroup) {
3233
+ this._initOptionGroup(this._getHelpOption());
3234
+ }
3235
+ } else {
3236
+ this._helpOption = null;
3237
+ }
3238
+ return this;
3239
+ }
3240
+ this._helpOption = this.createOption(
3241
+ flags ?? "-h, --help",
3242
+ description ?? "display help for command"
3243
+ );
3244
+ if (flags || description) this._initOptionGroup(this._helpOption);
3245
+ return this;
3246
+ }
3247
+ /**
3248
+ * Lazy create help option.
3249
+ * Returns null if has been disabled with .helpOption(false).
3250
+ *
3251
+ * @returns {(Option | null)} the help option
3252
+ * @package
3253
+ */
3254
+ _getHelpOption() {
3255
+ if (this._helpOption === void 0) {
3256
+ this.helpOption(void 0, void 0);
3257
+ }
3258
+ return this._helpOption;
3259
+ }
3260
+ /**
3261
+ * Supply your own option to use for the built-in help option.
3262
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3263
+ *
3264
+ * @param {Option} option
3265
+ * @return {Command} `this` command for chaining
3266
+ */
3267
+ addHelpOption(option) {
3268
+ this._helpOption = option;
3269
+ this._initOptionGroup(option);
3270
+ return this;
3271
+ }
3272
+ /**
3273
+ * Output help information and exit.
3274
+ *
3275
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3276
+ *
3277
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3278
+ */
3279
+ help(contextOptions) {
3280
+ this.outputHelp(contextOptions);
3281
+ let exitCode = Number(process2.exitCode ?? 0);
3282
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3283
+ exitCode = 1;
3284
+ }
3285
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3286
+ }
3287
+ /**
3288
+ * // Do a little typing to coordinate emit and listener for the help text events.
3289
+ * @typedef HelpTextEventContext
3290
+ * @type {object}
3291
+ * @property {boolean} error
3292
+ * @property {Command} command
3293
+ * @property {function} write
3294
+ */
3295
+ /**
3296
+ * Add additional text to be displayed with the built-in help.
3297
+ *
3298
+ * Position is 'before' or 'after' to affect just this command,
3299
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3300
+ *
3301
+ * @param {string} position - before or after built-in help
3302
+ * @param {(string | Function)} text - string to add, or a function returning a string
3303
+ * @return {Command} `this` command for chaining
3304
+ */
3305
+ addHelpText(position, text) {
3306
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3307
+ if (!allowedValues.includes(position)) {
3308
+ throw new Error(`Unexpected value for position to addHelpText.
3309
+ Expecting one of '${allowedValues.join("', '")}'`);
3310
+ }
3311
+ const helpEvent = `${position}Help`;
3312
+ this.on(helpEvent, (context) => {
3313
+ let helpStr;
3314
+ if (typeof text === "function") {
3315
+ helpStr = text({ error: context.error, command: context.command });
3316
+ } else {
3317
+ helpStr = text;
3318
+ }
3319
+ if (helpStr) {
3320
+ context.write(`${helpStr}
3321
+ `);
3322
+ }
3323
+ });
3324
+ return this;
3325
+ }
3326
+ /**
3327
+ * Output help information if help flags specified
3328
+ *
3329
+ * @param {Array} args - array of options to search for help flags
3330
+ * @private
3331
+ */
3332
+ _outputHelpIfRequested(args) {
3333
+ const helpOption = this._getHelpOption();
3334
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3335
+ if (helpRequested) {
3336
+ this.outputHelp();
3337
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3338
+ }
3339
+ }
3340
+ };
3341
+ function incrementNodeInspectorPort(args) {
3342
+ return args.map((arg) => {
3343
+ if (!arg.startsWith("--inspect")) {
3344
+ return arg;
3345
+ }
3346
+ let debugOption;
3347
+ let debugHost = "127.0.0.1";
3348
+ let debugPort = "9229";
3349
+ let match;
3350
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3351
+ debugOption = match[1];
3352
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3353
+ debugOption = match[1];
3354
+ if (/^\d+$/.test(match[3])) {
3355
+ debugPort = match[3];
3356
+ } else {
3357
+ debugHost = match[3];
3358
+ }
3359
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3360
+ debugOption = match[1];
3361
+ debugHost = match[3];
3362
+ debugPort = match[4];
3363
+ }
3364
+ if (debugOption && debugPort !== "0") {
3365
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3366
+ }
3367
+ return arg;
3368
+ });
3369
+ }
3370
+ function useColor() {
3371
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3372
+ return false;
3373
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3374
+ return true;
3375
+ return void 0;
3376
+ }
3377
+
3378
+ // node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js
3379
+ var program = new Command();
3380
+
3381
+ // packages/koed-server/dist/cli-service-loader.js
3382
+ var reportMissingCliService = (dependencies, json) => {
3383
+ const error = "Koed service runtime is not provisioned. Install the manifest-pinned base component from a trusted offline archive pair, then run `koed doctor`.";
3384
+ if (json)
3385
+ (dependencies.stdout ?? process.stdout).write(`${JSON.stringify({ ok: false, error, action: "components install --component base" }, null, 2)}
3386
+ `);
3387
+ else
3388
+ (dependencies.stderr ?? process.stderr).write(`${error}
3389
+ `);
3390
+ return 1;
3391
+ };
3392
+ var withCliService = async (load, run, dependencies, json) => {
3393
+ let service;
3394
+ try {
3395
+ service = await load();
3396
+ } catch {
3397
+ return reportMissingCliService(dependencies, json);
3398
+ }
3399
+ return run(service);
3400
+ };
3401
+
3402
+ // packages/koed-server/dist/cli-personal-sync.js
3403
+ var recoveryOptions = {
3404
+ group: ["--group-id <id>", "Personal Sync group identifier"],
3405
+ device: ["--device-id <id>", "Retained Desktop compatibility metadata"],
3406
+ challenge: ["--challenge-id <id>", "Pending enrollment challenge identifier"],
3407
+ user: ["--user-id <id>", "Local User identifier"],
3408
+ invitation: [
3409
+ "--invitation-fd <fd>",
3410
+ "Protected invitation JSON file descriptor"
3411
+ ],
3412
+ request: [
3413
+ "--request-fd <fd>",
3414
+ "Protected pairing request JSON file descriptor"
3415
+ ],
3416
+ statement: [
3417
+ "--statement-fd <fd>",
3418
+ "Protected signed transition JSON file descriptor"
3419
+ ],
3420
+ bundle: ["--key-bundle-fd <fd>", "Protected key bundle JSON file descriptor"],
3421
+ proof: ["--proof-fd <fd>", "Protected transition proof JSON file descriptor"],
3422
+ kit: ["--recovery-kit <path>", "Protected recovery kit file"],
3423
+ runtime: [
3424
+ "--runtime-secret-ref <reference>",
3425
+ "Runtime secret reference for bootstrap"
3426
+ ],
3427
+ passwordFd: [
3428
+ "--password-fd <fd>",
3429
+ "Read the recovery password from a protected file descriptor"
3430
+ ],
3431
+ passwordStdin: ["--password-stdin", "Read the recovery password from stdin"],
3432
+ linkFd: [
3433
+ "--link-fd <fd>",
3434
+ "Read the pairing link from a protected file descriptor"
3435
+ ],
3436
+ linkStdin: ["--link-stdin", "Read the pairing link from stdin"],
3437
+ label: ["--device-label <name>", "Device display name"],
3438
+ output: ["--output <path>", "Protected recovery kit output file"],
3439
+ payload: [
3440
+ "--payload-fd <fd>",
3441
+ "Protected recovery payload JSON file descriptor"
3442
+ ]
3443
+ };
3444
+ var recoveryCommands = [
3445
+ {
3446
+ path: "group bootstrap",
3447
+ description: "Create the initial Personal Sync group",
3448
+ options: ["kit", "runtime", "passwordFd", "passwordStdin"]
3449
+ },
3450
+ {
3451
+ path: "invite create",
3452
+ description: "Create a pairing invitation",
3453
+ options: ["group"]
3454
+ },
3455
+ {
3456
+ path: "join request",
3457
+ description: "Request enrollment for this device",
3458
+ options: ["group", "invitation"]
3459
+ },
3460
+ {
3461
+ path: "join redeem",
3462
+ description: "Redeem a pairing link through protected input",
3463
+ options: ["linkFd", "linkStdin", "label"]
3464
+ },
3465
+ {
3466
+ path: "join complete",
3467
+ description: "Complete approved device enrollment",
3468
+ options: ["group", "challenge"]
3469
+ },
3470
+ {
3471
+ path: "join bind-local-user",
3472
+ description: "Bind the enrolled runtime to a local User",
3473
+ options: ["group", "user", "challenge"]
3474
+ },
3475
+ {
3476
+ path: "join challenge",
3477
+ description: "Show redacted pending pairing request identifiers",
3478
+ options: []
3479
+ },
3480
+ {
3481
+ path: "active-device approve",
3482
+ description: "Approve a signed device request",
3483
+ options: ["request"]
3484
+ },
3485
+ {
3486
+ path: "active-device refresh",
3487
+ description: "Refresh this device to the current group epoch",
3488
+ options: []
3489
+ },
3490
+ {
3491
+ path: "device list",
3492
+ description: "List group devices",
3493
+ options: ["group"]
3494
+ },
3495
+ {
3496
+ path: "device revoke",
3497
+ description: "Submit a signed device revocation",
3498
+ options: ["group", "device", "statement", "bundle", "proof"]
3499
+ },
3500
+ {
3501
+ path: "policy enable",
3502
+ description: "Enable Personal Sync policy",
3503
+ options: ["group"]
3504
+ },
3505
+ {
3506
+ path: "policy pause",
3507
+ description: "Pause Personal Sync policy",
3508
+ options: ["group"]
3509
+ },
3510
+ {
3511
+ path: "policy resume",
3512
+ description: "Resume Personal Sync policy",
3513
+ options: ["group"]
3514
+ },
3515
+ {
3516
+ path: "replica status",
3517
+ description: "Inspect local replica status",
3518
+ options: ["group"]
3519
+ },
3520
+ {
3521
+ path: "retry",
3522
+ description: "Retry pending Personal Sync work",
3523
+ options: ["group"]
3524
+ },
3525
+ {
3526
+ path: "recovery approve",
3527
+ description: "Submit a signed recovery transition",
3528
+ options: ["group", "statement", "bundle", "proof"]
3529
+ },
3530
+ {
3531
+ path: "recovery guidance",
3532
+ description: "Show protected recovery guidance",
3533
+ options: []
3534
+ },
3535
+ {
3536
+ path: "recovery-kit create",
3537
+ description: "Encrypt a protected recovery kit",
3538
+ options: ["output", "payload", "passwordFd", "passwordStdin"]
3539
+ },
3540
+ {
3541
+ path: "recovery-kit verify",
3542
+ description: "Verify a protected recovery kit",
3543
+ options: ["kit", "passwordFd", "passwordStdin"]
3544
+ }
3545
+ ];
3546
+ var registerPersonalSyncCommands = (program2, dependencies, complete, advanced) => {
3547
+ const pair = program2.command("pair").description("Connect this device through Koed Desktop").option("--device-label <name>", "Device display name").option("--detach", "Return after creating the request").option("--json", "Emit JSON progress records");
3548
+ const pairAction = async (operation, options) => {
3549
+ const input = { ...pair.opts(), ...options };
3550
+ complete(await withCliService(() => import("./chunk-C3N4N5HR.js"), (service) => service.runPairCommand(operation, input, dependencies), dependencies, input.json));
3551
+ };
3552
+ pair.action(async (options) => pairAction(void 0, options));
3553
+ for (const operation of ["status", "cancel"])
3554
+ pair.command(operation).description(`${operation} the pending pairing request`).option("--json", "Emit JSON output").action(async (options) => pairAction(operation, options));
3555
+ const sync = program2.command("personal-sync").description("Inspect Personal Sync and recovery guidance").option("--advanced", "Show advanced compatibility and recovery commands");
3556
+ sync.action(() => sync.outputHelp());
3557
+ sync.addHelpText("after", "\nConnect this device with koed pair. Create your first group and manage devices in Electron \u2192 Devices.\n\nExamples:\n koed personal-sync status --json\n koed personal-sync --help --advanced");
3558
+ const execute = (command, path2, flags) => {
3559
+ command.option("--json", "Emit JSON output").action(async (options) => {
3560
+ const args = [...path2];
3561
+ for (const flag of flags) {
3562
+ const key = flag.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
3563
+ const value = options[key];
3564
+ if (value === true)
3565
+ args.push(flag);
3566
+ else if (typeof value === "string")
3567
+ args.push(flag, value);
3568
+ }
3569
+ const stdout = dependencies.stdout ?? process.stdout;
3570
+ const stderr = dependencies.stderr ?? process.stderr;
3571
+ try {
3572
+ const operation = dependencies.runPersonalSync ?? (await import("./chunk-DXTAWHY3.js")).runPersonalSyncCommand;
3573
+ const result = await operation(args, (dependencies.resolvePaths ?? resolveKoedServerPaths)(), process.env);
3574
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
3575
+ ` : `${result.message}
3576
+ `);
3577
+ complete(result.ok ? 0 : 1);
3578
+ } catch (error) {
3579
+ const message = error instanceof Error ? error.message : String(error);
3580
+ if (options.json)
3581
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
3582
+ `);
3583
+ else
3584
+ stderr.write(`${message}
3585
+ `);
3586
+ complete(1);
3587
+ }
3588
+ });
3589
+ };
3590
+ execute(sync.command("status").description("Show redacted status for this local Personal installation"), ["status"], []);
3591
+ const groups = /* @__PURE__ */ new Map();
3592
+ for (const entry of recoveryCommands) {
3593
+ const path2 = entry.path.split(" ");
3594
+ let parent = sync;
3595
+ if (path2.length === 2) {
3596
+ const name = path2[0];
3597
+ let group = groups.get(name);
3598
+ if (!group) {
3599
+ group = sync.command(name, { hidden: !advanced }).description(`Advanced ${name} operations`);
3600
+ group.action(() => group.outputHelp());
3601
+ groups.set(name, group);
3602
+ }
3603
+ parent = group;
3604
+ }
3605
+ const command = parent.command(path2.at(-1), { hidden: path2.length === 1 && !advanced }).description(entry.description);
3606
+ const flags = [];
3607
+ for (const key of entry.options) {
3608
+ const [syntax, description] = recoveryOptions[key];
3609
+ if (key === "device") {
3610
+ command.addOption(new Option(syntax, description).hideHelp());
3611
+ } else
3612
+ command.option(syntax, description);
3613
+ flags.push(syntax.split(" ")[0]);
3614
+ }
3615
+ execute(command, path2, flags);
3616
+ }
3617
+ };
3618
+
3619
+ // packages/koed-server/dist/cli-remote.js
3620
+ var callbackArguments = (operation, options) => {
3621
+ const args = [operation];
3622
+ if (options.client)
3623
+ args.push(options.client);
3624
+ for (const [key, flag] of [
3625
+ ["backend", "--backend"],
3626
+ ["koedHome", "--koed-home"]
3627
+ ])
3628
+ if (options[key] !== void 0)
3629
+ args.push(flag, options[key]);
3630
+ for (const [key, flag] of [
3631
+ ["consent", "--consent"],
3632
+ ["localRuntime", "--local-runtime"],
3633
+ ["teamRead", "--team-read"],
3634
+ ["json", "--json"]
3635
+ ])
3636
+ if (options[key])
3637
+ args.push(flag);
3638
+ return args;
3639
+ };
3640
+ var registerRemoteCommands = (program2, dependencies, complete) => {
3641
+ const remote = program2.command("remote").description("Manage remote authorization and AI Client integrations");
3642
+ remote.action(() => remote.outputHelp());
3643
+ const bind = (command, operation, client) => {
3644
+ command.option("--koed-home <path>", "Dedicated local instance directory").option("--json", "Emit pretty JSON output").action(async (options) => {
3645
+ const input = { ...options, client };
3646
+ if (dependencies.runRemoteMcp) {
3647
+ complete(await dependencies.runRemoteMcp(callbackArguments(operation, input), {
3648
+ stdout: dependencies.stdout ?? process.stdout,
3649
+ stderr: dependencies.stderr ?? process.stderr
3650
+ }));
3651
+ return;
3652
+ }
3653
+ complete(await withCliService(() => import("./chunk-2BWTLF7A.js"), (service) => service.runRemoteMcpOperation(operation, input, {
3654
+ environment: dependencies.remoteEnvironment,
3655
+ stdout: dependencies.stdout ?? process.stdout,
3656
+ stderr: dependencies.stderr ?? process.stderr
3657
+ }), dependencies, options.json));
3658
+ });
3659
+ };
3660
+ bind(remote.command("login").description("Authorize remote recall and optional local execution").option("--backend <url>", "HTTPS backend URL").option("--consent", "Explicitly authorize the requested scopes").option("--local-runtime", "Also authorize capture and local execution").option("--team-read", "Request authorized Team recall"), "login");
3661
+ bind(remote.command("logout").description("Revoke remote authorization and clear local tokens").option("--consent", "Explicitly authorize logout"), "logout");
3662
+ bind(remote.command("start").description("Run the shared remote Local AI Runtime in the foreground"), "start");
3663
+ for (const operation of ["setup", "check", "remove"]) {
3664
+ const group = remote.command(operation).description(`${operation} a remote AI Client integration`);
3665
+ group.action(() => group.outputHelp());
3666
+ for (const client of ["codex", "claude", "pi"]) {
3667
+ const command = group.command(client).description(`${operation} the ${client} remote integration`);
3668
+ command.option("--consent", "Explicitly authorize integration changes");
3669
+ bind(command, operation, client);
3670
+ }
3671
+ }
3672
+ };
3673
+
3674
+ // packages/koed-server/dist/cli-internal.js
3675
+ var secretProviderUsage = "Usage: koed secret-provider <get|put|delete> <reference>\n";
3676
+ var registerInternalCommands = (program2, dependencies, complete) => {
3677
+ const secret = program2.command("secret-provider", { hidden: true }).description("Internal credential adapter");
3678
+ secret.action(() => {
3679
+ (dependencies.stdout ?? process.stdout).write(secretProviderUsage);
3680
+ complete(1);
3681
+ });
3682
+ for (const operation of ["get", "put", "delete"])
3683
+ secret.command(operation).argument("<reference>").action(async (reference) => {
3684
+ if (!reference) {
3685
+ (dependencies.stdout ?? process.stdout).write(secretProviderUsage);
3686
+ complete(1);
3687
+ return;
3688
+ }
3689
+ complete(await withCliService(() => import("./chunk-A6WMU2GG.js"), (service) => service.runSecretProviderCommand(operation, reference, dependencies), dependencies, false));
3690
+ });
3691
+ const desktop = program2.command("desktop", { hidden: true }).description("Internal Desktop commands");
3692
+ desktop.action(() => desktop.outputHelp());
3693
+ desktop.command("collaboration-broker").action(async () => {
3694
+ complete(await withCliService(() => import("./chunk-JJNLH5GA.js"), async (service) => {
3695
+ try {
3696
+ await service.runDesktopCollaborationBrokerProcess();
3697
+ return 0;
3698
+ } catch (error) {
3699
+ (dependencies.stderr ?? process.stderr).write(`${error instanceof Error ? error.message : String(error)}
3700
+ `);
3701
+ return 1;
3702
+ }
3703
+ }, dependencies, false));
3704
+ });
3705
+ };
3706
+
3707
+ // packages/koed-server/dist/cli-components.js
3708
+ var componentSyntaxError = (error) => {
3709
+ const flag = error.message.match(/'(--[a-z][a-z-]*)(?:[^']*)'/)?.[1];
3710
+ if (flag && error.code === "commander.unknownOption")
3711
+ return `Unsupported components option: ${flag}`;
3712
+ if (flag && error.code === "commander.optionMissingArgument")
3713
+ return `${flag} requires a value.`;
3714
+ return "Invalid components command. Run koed components --help.";
3715
+ };
3716
+ var registerComponentCommands = (program2, dependencies, complete) => {
3717
+ const components = program2.command("components").description("Manage manifest-pinned components");
3718
+ components.action(() => components.outputHelp());
3719
+ const descriptions = {
3720
+ status: "Inspect required, installed, staged, and active components",
3721
+ install: "Stage a manifest-pinned exact-version component",
3722
+ activate: "Activate a complete staged generation",
3723
+ cleanup: "Remove inactive unreferenced generations"
3724
+ };
3725
+ for (const operation of Object.keys(descriptions)) {
3726
+ const command = components.command(operation).description(descriptions[operation]).option("--json", "Emit JSON output");
3727
+ if (operation === "install")
3728
+ command.option("--component <id>", "Component identifier: base or privacy").option("--variant <variant>", "Linux x64 Privacy bundle: cpu or cuda").option("--version <version>", "Exact component version").option("--archive <path>", "Offline component archive").option("--manifest <path>", "Offline component manifest").option("--archive-url <url>", "Exact-version component archive URL").option("--manifest-url <url>", "Exact-version component manifest URL").option("--stage-only", "Stage the component without activation");
3729
+ if (operation === "activate")
3730
+ command.option("--version <version>", "Complete staged generation version");
3731
+ const seen = /* @__PURE__ */ new Set();
3732
+ for (const option of command.options)
3733
+ command.on(`option:${option.name()}`, () => {
3734
+ if (seen.has(option.long))
3735
+ throw new CommanderError(1, "koed.componentInput", `Duplicate components option: ${option.long}`);
3736
+ seen.add(option.long);
3737
+ });
3738
+ command.exitOverride((error) => {
3739
+ if (error.exitCode === 0)
3740
+ throw error;
3741
+ throw new CommanderError(1, "koed.componentInput", componentSyntaxError(error));
3742
+ });
3743
+ command.action(async (options) => {
3744
+ let service;
3745
+ try {
3746
+ service = await import("./chunk-YJ6XUZT6.js");
3747
+ } catch {
3748
+ complete(reportMissingCliService(dependencies, options.json));
3749
+ return;
3750
+ }
3751
+ complete(await service.runComponentCommand(operation, options, dependencies));
3752
+ });
3753
+ }
3754
+ };
3755
+
3756
+ // packages/koed-server/dist/cli-integrations.js
3757
+ var registerIntegrationCommands = (program2, dependencies, complete) => {
3758
+ const descriptions = {
3759
+ setup: "Configure core services and AI Client integrations",
3760
+ check: "Inspect an AI Client integration without mutation",
3761
+ repair: "Repair an AI Client integration",
3762
+ remove: "Remove Koed-owned AI Client integration state"
3763
+ };
3764
+ for (const operation of Object.keys(descriptions)) {
3765
+ const group = program2.command(operation).description(descriptions[operation]);
3766
+ group.action(() => group.outputHelp());
3767
+ const clients = operation === "setup" ? ["core", "codex", "claude", "pi"] : ["codex", "claude", "pi"];
3768
+ for (const client of clients) {
3769
+ const command = group.command(client).description(client === "core" ? "Prepare core services and the local API Token" : `${descriptions[operation]} for ${client}`).option("--json", "Emit JSON output");
3770
+ if (operation === "setup" && client === "codex")
3771
+ command.option("--with-memory-guidance", "Install the recommended global guidance (default)").option("--without-memory-guidance", "Disable recommended global guidance installation").option("--deferred-recall", "Legacy recall flag; delivery is selected per tool call").option("--blocking-recall", "Legacy recall flag; delivery is selected per tool call");
3772
+ if (operation === "setup" && client === "claude")
3773
+ command.option("--background-recall", "Opt in to 500 ms background recall for main-Conversation MCP calls");
3774
+ if (operation === "check")
3775
+ command.option("--capabilities-refreshed-since <value>", "Minimum capability refresh timestamp").option("--include-status", "Include complete service status in the result");
3776
+ command.action(async (options) => {
3777
+ complete(await withCliService(() => import("./chunk-YK4F4VY2.js"), (service) => service.runIntegrationCommand(operation, { ...options, client }, dependencies), dependencies, options.json));
3778
+ });
3779
+ }
3780
+ }
3781
+ };
3782
+
3783
+ // packages/koed-server/dist/cli-lifecycle.js
3784
+ var registerLifecycleCommands = (program2, dependencies, complete) => {
3785
+ const descriptions = {
3786
+ start: "Start and supervise local Koed services",
3787
+ stop: "Stop supervised local Koed services",
3788
+ restart: "Restart supervised local Koed services",
3789
+ status: "Show local service state",
3790
+ doctor: "Inspect setup and dependencies"
3791
+ };
3792
+ const bind = (command, operation, identityAction) => {
3793
+ command.option("--json", "Emit JSON output").action(async (options) => {
3794
+ complete(await withCliService(() => import("./chunk-PY5LYLV7.js"), (service) => service.runLifecycleCommand(operation, { ...options, identityAction }, dependencies), dependencies, options.json));
3795
+ });
3796
+ };
3797
+ for (const operation of Object.keys(descriptions)) {
3798
+ const command = program2.command(operation).description(descriptions[operation]);
3799
+ if (operation === "start")
3800
+ command.option("--daemon", "Start the supervisor detached");
3801
+ if (operation === "status")
3802
+ command.option("--startup", "Show lightweight supervisor startup state");
3803
+ bind(command, operation);
3804
+ }
3805
+ const identity = program2.command("identity").description("Manage deployment and device identity");
3806
+ identity.action(() => identity.outputHelp());
3807
+ bind(identity.command("status").description("Show redacted deployment and device identity"), "identity", "status");
3808
+ bind(identity.command("rotate").description("Create a fresh device identity and invalidate enrollment references"), "identity", "rotate");
3809
+ };
3810
+
3811
+ // packages/koed-server/dist/cli-upstream.js
3812
+ var policyOptions = [
3813
+ ["personal-memory-read", "personalMemoryRead"],
3814
+ ["personal-collaboration", "personalCollaboration"],
3815
+ ["team-workspace-read", "teamWorkspaceRead"],
3816
+ ["share-grant-management", "shareGrantManagement"],
3817
+ ["capture-writes", "captureWrites"],
3818
+ ["sync", "sync"],
3819
+ ["managed-execution", "managedExecution"],
3820
+ ["admin", "admin"]
3821
+ ];
3822
+ var required = (value, flag) => {
3823
+ if (!value)
3824
+ throw new Error(`${flag} is required.`);
3825
+ return value;
3826
+ };
3827
+ var registerUpstreamCommands = (program2, dependencies, complete) => {
3828
+ const upstream = program2.command("upstream").description("Manage upstream backends and enrollment");
3829
+ upstream.action(() => upstream.outputHelp());
3830
+ const list = upstream.command("list").description("List registered upstream backends");
3831
+ const register = upstream.command("register").description("Register or update an upstream backend").option("--url <url>", "Backend URL").option("--id <id>", "Backend identifier").option("--name <name>", "Display name").option("--profile <profile>", "Deployment profile");
3832
+ const refresh = upstream.command("refresh").description("Refresh cached upstream capabilities");
3833
+ const policy = upstream.command("policy").description("Update explicit upstream route policies");
3834
+ for (const [flag] of policyOptions)
3835
+ policy.option(`--${flag} <state>`, "enabled or disabled");
3836
+ const activate = upstream.command("activate").description("Select the active upstream backend");
3837
+ const remove = upstream.command("remove").description("Remove an upstream backend");
3838
+ const disconnect = upstream.command("disconnect").description("Disable upstream routes and enrollment");
3839
+ const enroll = upstream.command("enroll").description("Manage upstream enrollment approval");
3840
+ enroll.action(() => enroll.outputHelp());
3841
+ const start = enroll.command("start").description("Start enrollment through explicit browser approval").option("--source-owner-principal-id <id>", "Source owner principal identifier").option("--memory-answers", "Request Memory Answer execution").option("--enable-memory-answers", "Compatibility alias for --memory-answers");
3842
+ const status = enroll.command("status").description("Show upstream enrollment state");
3843
+ const cancel = enroll.command("cancel").description("Cancel enrollment orchestration");
3844
+ for (const command of [
3845
+ refresh,
3846
+ policy,
3847
+ activate,
3848
+ remove,
3849
+ disconnect,
3850
+ start,
3851
+ status,
3852
+ cancel
3853
+ ])
3854
+ command.option("--id <id>", "Registered backend identifier");
3855
+ for (const command of [
3856
+ list,
3857
+ register,
3858
+ refresh,
3859
+ policy,
3860
+ activate,
3861
+ remove,
3862
+ disconnect,
3863
+ start,
3864
+ status,
3865
+ cancel
3866
+ ])
3867
+ command.option("--json", "Emit JSON output").action(async (options) => {
3868
+ const stdout = dependencies.stdout ?? process.stdout;
3869
+ const stderr = dependencies.stderr ?? process.stderr;
3870
+ try {
3871
+ const paths = (dependencies.resolvePaths ?? resolveKoedServerPaths)();
3872
+ let result;
3873
+ if (command === list) {
3874
+ const execute = dependencies.listUpstreams ?? (await import("./chunk-NEWIOOM6.js")).listUpstreamBackends;
3875
+ result = execute(paths);
3876
+ } else if (command === register) {
3877
+ const execute = dependencies.registerUpstream ?? (await import("./chunk-NEWIOOM6.js")).registerUpstreamBackend;
3878
+ result = execute(paths, {
3879
+ url: required(options.url, "--url"),
3880
+ id: options.id,
3881
+ displayName: options.name,
3882
+ profile: options.profile
3883
+ });
3884
+ } else {
3885
+ const id = required(options.id, "--id");
3886
+ if (command === refresh) {
3887
+ const execute = dependencies.refreshUpstream ?? (await import("./chunk-NEWIOOM6.js")).refreshUpstreamBackendCapabilities;
3888
+ result = await execute(paths, id);
3889
+ } else if (command === policy) {
3890
+ const update = {};
3891
+ for (const [flag, key] of policyOptions) {
3892
+ const value = options[key];
3893
+ if (!value)
3894
+ continue;
3895
+ if (value !== "enabled" && value !== "disabled")
3896
+ throw new Error(`--${flag} must be enabled or disabled.`);
3897
+ update[key] = value;
3898
+ }
3899
+ const execute = dependencies.updateUpstreamPolicy ?? (await import("./chunk-NEWIOOM6.js")).updateUpstreamBackendRoutePolicy;
3900
+ result = execute(paths, id, update);
3901
+ } else if (command === activate) {
3902
+ const execute = dependencies.activateUpstream ?? (await import("./chunk-NEWIOOM6.js")).setActiveUpstreamBackend;
3903
+ result = execute(paths, id);
3904
+ } else if (command === remove) {
3905
+ const execute = dependencies.removeUpstream ?? (await import("./chunk-NEWIOOM6.js")).removeUpstreamBackend;
3906
+ result = execute(paths, id);
3907
+ } else if (command === disconnect) {
3908
+ const execute = dependencies.disconnectUpstream ?? (await import("./chunk-RVYJKKWA.js")).disconnectUpstreamBackendEnrollment;
3909
+ result = await execute(paths, id);
3910
+ } else if (command === start) {
3911
+ const execute = dependencies.startUpstreamEnroll ?? (await import("./chunk-RVYJKKWA.js")).startUpstreamEnrollment;
3912
+ result = await execute(paths, id, {
3913
+ memoryAnswers: Boolean(options.memoryAnswers || options.enableMemoryAnswers),
3914
+ sourceOwnerPrincipalId: required(options.sourceOwnerPrincipalId, "--source-owner-principal-id")
3915
+ });
3916
+ } else if (command === status) {
3917
+ const execute = dependencies.getUpstreamEnrollStatus ?? (await import("./chunk-RVYJKKWA.js")).getUpstreamEnrollmentStatus;
3918
+ result = await execute(paths, id);
3919
+ } else {
3920
+ const execute = dependencies.cancelUpstreamEnroll ?? (await import("./chunk-RVYJKKWA.js")).cancelUpstreamEnrollment;
3921
+ result = await execute(paths, id);
3922
+ }
3923
+ }
3924
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
3925
+ ` : `${result.message}
3926
+ `);
3927
+ complete(result.ok ? 0 : 1);
3928
+ } catch (error) {
3929
+ const message = error instanceof Error ? error.message : String(error);
3930
+ if (options.json)
3931
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
3932
+ `);
3933
+ else
3934
+ stderr.write(`${message}
3935
+ `);
3936
+ complete(1);
3937
+ }
3938
+ });
3939
+ };
3940
+
3941
+ // packages/koed-server/dist/cli-projects.js
3942
+ var required2 = (value, flag) => {
3943
+ if (!value)
3944
+ throw new Error(`${flag} is required.`);
3945
+ return value;
3946
+ };
3947
+ var registerProjectCommands = (program2, dependencies, complete) => {
3948
+ const project = program2.command("project").description("Manage local Project metadata");
3949
+ project.action(() => project.outputHelp());
3950
+ const discover = project.command("discover").description("Discover and store local Project metadata").option("--cwd <path>", "Folder to inspect; defaults to the current directory").option("--codex", "Record Codex as the AI Client source");
3951
+ const list = project.command("list").description("List discovered local Projects");
3952
+ const show = project.command("show").description("Show Project metadata for a Folder").option("--cwd <path>", "Folder to inspect; defaults to the current directory");
3953
+ const forget = project.command("forget").description("Forget discovered local Project metadata").option("--local-project-id <id>", "Local Project identifier");
3954
+ const anchor = project.command("anchor").description("Select or reset a Project Git Anchor").option("--local-project-id <id>", "Local Project identifier").option("--checkout-id <id>", "Expected checkout identifier").option("--remote <name>", "Git remote to select").option("--reset", "Reset the selected remote");
3955
+ const team = program2.command("team").description("Manage local Team Workspace links");
3956
+ team.action(() => team.outputHelp());
3957
+ const workspace = team.command("workspace").description("Manage Project links to Team Workspaces");
3958
+ workspace.action(() => workspace.outputHelp());
3959
+ const link = workspace.command("link").description("Link a Project root to a Team Workspace").option("--project-root <path>", "Local Project root").option("--team-workspace-id <id>", "Team Workspace identifier").option("--backend-id <id>", "Registered backend identifier").option("--upstream-backend-id <id>", "Compatibility alias for backend selection").option("--local-project-id <id>", "Local Project identifier").option("--project-display-name <name>", "Local Project display name");
3960
+ const links = workspace.command("list").description("List local Project links to Team Workspaces");
3961
+ const linked = workspace.command("show").description("Show the Workspace link for a Project root").option("--project-root <path>", "Local Project root");
3962
+ const unlink = workspace.command("remove").description("Remove a local Project link to a Team Workspace").option("--project-root <path>", "Local Project root");
3963
+ for (const command of [
3964
+ discover,
3965
+ list,
3966
+ show,
3967
+ forget,
3968
+ anchor,
3969
+ link,
3970
+ links,
3971
+ linked,
3972
+ unlink
3973
+ ])
3974
+ command.option("--json", "Emit JSON output").action(async (options) => {
3975
+ const stdout = dependencies.stdout ?? process.stdout;
3976
+ const stderr = dependencies.stderr ?? process.stderr;
3977
+ try {
3978
+ const paths = (dependencies.resolvePaths ?? resolveKoedServerPaths)();
3979
+ let result;
3980
+ if (command === discover) {
3981
+ const execute = dependencies.discoverProjectMetadata ?? (await import("./chunk-TSRPHKAC.js")).discoverProjectMetadata;
3982
+ result = await execute(paths, {
3983
+ cwd: options.cwd ?? process.cwd(),
3984
+ aiClientSource: options.codex ? "codex" : void 0
3985
+ });
3986
+ } else if (command === list) {
3987
+ const execute = dependencies.listProjectMetadata ?? (await import("./chunk-TSRPHKAC.js")).listProjectMetadata;
3988
+ result = execute(paths);
3989
+ } else if (command === show) {
3990
+ const execute = dependencies.getProjectMetadataForCwd ?? (await import("./chunk-TSRPHKAC.js")).getProjectMetadataForCwd;
3991
+ result = execute(paths, options.cwd ?? process.cwd());
3992
+ } else if (command === forget) {
3993
+ const execute = dependencies.forgetProjectMetadata ?? (await import("./chunk-TSRPHKAC.js")).forgetProjectMetadata;
3994
+ result = execute(paths, required2(options.localProjectId, "--local-project-id"));
3995
+ } else if (command === anchor) {
3996
+ const { setProjectRepositoryAnchor } = await import("./chunk-TSRPHKAC.js");
3997
+ result = await setProjectRepositoryAnchor(paths, {
3998
+ localProjectId: required2(options.localProjectId, "--local-project-id"),
3999
+ expectedCheckoutId: required2(options.checkoutId, "--checkout-id"),
4000
+ remoteName: options.reset ? null : required2(options.remote, "--remote")
4001
+ });
4002
+ } else if (command === link) {
4003
+ const execute = dependencies.linkProjectTeamWorkspace ?? (await import("./chunk-XIZVLPHZ.js")).linkProjectTeamWorkspace;
4004
+ result = execute(paths, {
4005
+ projectRoot: required2(options.projectRoot, "--project-root"),
4006
+ teamWorkspaceId: required2(options.teamWorkspaceId, "--team-workspace-id"),
4007
+ backendId: options.backendId ?? options.upstreamBackendId,
4008
+ localProjectId: options.localProjectId,
4009
+ projectDisplayName: options.projectDisplayName
4010
+ });
4011
+ } else if (command === links) {
4012
+ const execute = dependencies.listProjectTeamWorkspaceLinks ?? (await import("./chunk-XIZVLPHZ.js")).listProjectTeamWorkspaceLinks;
4013
+ result = execute(paths);
4014
+ } else if (command === linked) {
4015
+ const execute = dependencies.getProjectTeamWorkspaceLink ?? (await import("./chunk-XIZVLPHZ.js")).getProjectTeamWorkspaceLink;
4016
+ result = execute(paths, required2(options.projectRoot, "--project-root"));
4017
+ } else {
4018
+ const execute = dependencies.removeProjectTeamWorkspaceLink ?? (await import("./chunk-XIZVLPHZ.js")).removeProjectTeamWorkspaceLink;
4019
+ result = execute(paths, required2(options.projectRoot, "--project-root"));
4020
+ }
4021
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
4022
+ ` : `${result.message}
4023
+ `);
4024
+ complete(result.ok ? 0 : 1);
4025
+ } catch (error) {
4026
+ const message = error instanceof Error ? error.message : String(error);
4027
+ if (options.json)
4028
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
4029
+ `);
4030
+ else
4031
+ stderr.write(`${message}
4032
+ `);
4033
+ complete(1);
4034
+ }
4035
+ });
4036
+ };
4037
+
4038
+ // packages/koed-server/dist/cli-package.js
4039
+ var required3 = (value, flag) => {
4040
+ if (!value)
4041
+ throw new Error(`${flag} is required.`);
4042
+ return value;
4043
+ };
4044
+ var registerPackageCommands = (program2, dependencies, complete) => {
4045
+ const packages = program2.command("package").description("Manage standalone Server packages");
4046
+ packages.action(() => packages.outputHelp());
4047
+ const status = packages.command("status").description("Show installed package status");
4048
+ const install = packages.command("install").description("Verify and install a standalone Server package").option("--source <source>", "Package archive source").option("--sha256 <digest>", "Expected archive SHA-256 digest").option("--sha256-file <path>", "Archive checksum file").option("--activate", "Activate the installed package").option("--provenance-file <path>", "Package provenance file").option("--signature-file <path>", "Package provenance signature").option("--trusted-public-key <key>", "Trusted package provenance public key").option("--trusted-public-key-file <path>", "Trusted package provenance public key file").option("--trust-policy <policy>", "sha256-only, require-provenance, or require-signature").option("--allow-downgrade", "Allow a downgrade subject to existing package policy");
4049
+ const activate = packages.command("activate").description("Activate an installed package version").option("--version <version>", "Installed package version").option("--allow-downgrade", "Allow a downgrade subject to existing package policy");
4050
+ const cleanup = packages.command("cleanup").description("Remove inactive versions and stale archives").option("--keep <count>", "Number of inactive versions to retain", "1");
4051
+ for (const command of [status, install, activate, cleanup])
4052
+ command.option("--json", "Emit JSON output").action(async (options) => {
4053
+ const stdout = dependencies.stdout ?? process.stdout;
4054
+ const stderr = dependencies.stderr ?? process.stderr;
4055
+ try {
4056
+ const paths = (dependencies.resolvePaths ?? resolveKoedServerPaths)();
4057
+ let result;
4058
+ switch (command.name()) {
4059
+ case "status": {
4060
+ const execute = dependencies.collectPackageStatus ?? (await import("./chunk-YOFI4PCH.js")).collectServerPackageStatus;
4061
+ result = execute(paths);
4062
+ break;
4063
+ }
4064
+ case "install": {
4065
+ const source = required3(options.source, "--source");
4066
+ const policy = options.trustPolicy;
4067
+ if (policy !== void 0 && policy !== "sha256-only" && policy !== "require-provenance" && policy !== "require-signature")
4068
+ throw new Error("--trust-policy must be sha256-only, require-provenance, or require-signature.");
4069
+ const input = {
4070
+ source,
4071
+ activate: Boolean(options.activate)
4072
+ };
4073
+ for (const key of [
4074
+ "sha256",
4075
+ "sha256File",
4076
+ "provenanceFile",
4077
+ "signatureFile",
4078
+ "trustedPublicKey",
4079
+ "trustedPublicKeyFile"
4080
+ ])
4081
+ if (options[key] !== void 0)
4082
+ input[key] = options[key];
4083
+ if (policy !== void 0)
4084
+ input.trustPolicy = policy;
4085
+ if (options.allowDowngrade)
4086
+ input.allowDowngrade = true;
4087
+ const execute = dependencies.installPackage ?? (await import("./chunk-YOFI4PCH.js")).installServerPackage;
4088
+ result = await execute(paths, input);
4089
+ break;
4090
+ }
4091
+ case "activate": {
4092
+ const version = required3(options.version, "--version");
4093
+ const execute = dependencies.activatePackage ?? (await import("./chunk-YOFI4PCH.js")).activateServerPackage;
4094
+ result = execute(paths, version, {
4095
+ allowDowngrade: Boolean(options.allowDowngrade)
4096
+ });
4097
+ break;
4098
+ }
4099
+ default: {
4100
+ const execute = dependencies.cleanupPackages ?? (await import("./chunk-YOFI4PCH.js")).cleanupServerPackages;
4101
+ result = execute(paths, Number.parseInt(options.keep ?? "1", 10));
4102
+ }
4103
+ }
4104
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
4105
+ ` : `${result.message}
4106
+ `);
4107
+ complete(result.ok ? 0 : 1);
4108
+ } catch (error) {
4109
+ const message = error instanceof Error ? error.message : String(error);
4110
+ if (options.json)
4111
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
4112
+ `);
4113
+ else
4114
+ stderr.write(`${message}
4115
+ `);
4116
+ complete(1);
4117
+ }
4118
+ });
4119
+ };
4120
+
4121
+ // packages/koed-server/dist/cli-models.js
4122
+ var runModelCommand = async (operation, options, dependencies) => {
4123
+ const stdout = dependencies.stdout ?? process.stdout;
4124
+ const stderr = dependencies.stderr ?? process.stderr;
4125
+ try {
4126
+ if (options.kind !== "embedding" && options.kind !== "privacy")
4127
+ throw new Error("--kind must be embedding or privacy.");
4128
+ const paths = (dependencies.resolvePaths ?? resolveKoedServerPaths)();
4129
+ const loadEnvironment = dependencies.loadEnvironment ?? (await import("./chunk-7NOQSX4T.js")).loadRepoEnv;
4130
+ const environment = {
4131
+ ...loadEnvironment(paths.repoRoot),
4132
+ ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value?.trim()))
4133
+ };
4134
+ let result;
4135
+ if (options.kind === "privacy") {
4136
+ if (operation === "status") {
4137
+ const execute = dependencies.collectPrivacyModelStatus ?? (await import("./chunk-ZXX4ZNJY.js")).collectPrivacyModelStatus;
4138
+ result = await execute(paths);
4139
+ } else {
4140
+ const execute = dependencies.installPrivacyModel ?? (await import("./chunk-ZXX4ZNJY.js")).installPrivacyModel;
4141
+ result = await execute(paths, environment);
4142
+ }
4143
+ } else {
4144
+ const execute = operation === "status" ? dependencies.collectModelStatus ?? (await import("./chunk-KUIWH33N.js")).collectLocalModelStatus : dependencies.installModel ?? (await import("./chunk-KUIWH33N.js")).installLocalModel;
4145
+ result = await execute(paths, options.kind, environment);
4146
+ }
4147
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
4148
+ ` : `${result.message}
4149
+ `);
4150
+ return operation === "status" ? result.state === "checksum_mismatch" ? 1 : 0 : result.ok ? 0 : 1;
4151
+ } catch (error) {
4152
+ const message = error instanceof Error ? error.message : String(error);
4153
+ if (options.json)
4154
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
4155
+ `);
4156
+ else
4157
+ stderr.write(`${message}
4158
+ `);
4159
+ return 1;
4160
+ }
4161
+ };
4162
+ var registerModelCommands = (program2, dependencies, complete) => {
4163
+ const models = program2.command("models").description("Manage embedding and privacy models");
4164
+ models.action(() => models.outputHelp());
4165
+ for (const operation of ["status", "install"])
4166
+ models.command(operation).description(operation === "status" ? "Show model installation status" : "Download and verify a local model").option("--kind <kind>", "Model kind: embedding or privacy", "embedding").option("--json", "Emit JSON output").action(async (options) => {
4167
+ complete(await runModelCommand(operation, options, dependencies));
4168
+ });
4169
+ };
4170
+
4171
+ // packages/koed-server/dist/cli-runtime.js
4172
+ var runRuntimeCommand = async (operation, options, dependencies) => {
4173
+ const stdout = dependencies.stdout ?? process.stdout;
4174
+ const stderr = dependencies.stderr ?? process.stderr;
4175
+ try {
4176
+ if (options.provider !== "homebrew" && options.provider !== "packaged")
4177
+ throw new Error("--provider must be homebrew or packaged.");
4178
+ if (operation === "install" && options.dependencyMode !== "bundled-local")
4179
+ throw new Error("runtime install requires --dependency-mode bundled-local.");
4180
+ const paths = (dependencies.resolvePaths ?? resolveKoedServerPaths)();
4181
+ const loadEnvironment = dependencies.loadEnvironment ?? (await import("./chunk-7NOQSX4T.js")).loadRepoEnv;
4182
+ const environment = {
4183
+ ...loadEnvironment(paths.repoRoot),
4184
+ ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value?.trim()))
4185
+ };
4186
+ let result;
4187
+ if (options.provider === "packaged") {
4188
+ const execute = operation === "status" ? dependencies.collectPackagedRuntimeStatus ?? (await import("./chunk-PT3AUPGE.js")).collectPackagedRuntimeStatus : dependencies.installPackagedRuntime ?? (await import("./chunk-PT3AUPGE.js")).installPackagedRuntime;
4189
+ result = execute(paths, environment);
4190
+ } else {
4191
+ const execute = operation === "status" ? dependencies.collectRuntimeStatus ?? (await import("./chunk-HK2H3MVE.js")).collectHomebrewRuntimeStatus : dependencies.installRuntime ?? (await import("./chunk-HK2H3MVE.js")).installHomebrewRuntime;
4192
+ result = execute(paths, environment);
4193
+ }
4194
+ stdout.write(options.json ? `${JSON.stringify(result, null, 2)}
4195
+ ` : `${result.message}
4196
+ `);
4197
+ return result.ok ? 0 : 1;
4198
+ } catch (error) {
4199
+ const message = error instanceof Error ? error.message : String(error);
4200
+ if (options.json)
4201
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
4202
+ `);
4203
+ else
4204
+ stderr.write(`${message}
4205
+ `);
4206
+ return 1;
4207
+ }
4208
+ };
4209
+ var registerRuntimeCommands = (program2, dependencies, complete) => {
4210
+ const runtime = program2.command("runtime").description("Manage local runtime dependencies");
4211
+ runtime.action(() => runtime.outputHelp());
4212
+ for (const operation of ["status", "install"]) {
4213
+ const command = runtime.command(operation).description(operation === "status" ? "Show runtime installation status" : "Install local runtime dependencies explicitly").option("--provider <provider>", "Runtime provider: homebrew or packaged", "homebrew").option("--dependency-mode <mode>", "Dependency mode; installation requires bundled-local").option("--json", "Emit JSON output").action(async (options) => {
4214
+ complete(await runRuntimeCommand(operation, options, dependencies));
4215
+ });
4216
+ if (operation === "install")
4217
+ command.addHelpText("after", "\nExample:\n koed runtime install --provider homebrew --dependency-mode bundled-local --json");
4218
+ }
4219
+ };
4220
+
4221
+ // packages/koed-server/dist/cli-command-tree.js
4222
+ var runCommandTree = async (args, dependencies = {}) => {
4223
+ const stdout = dependencies.stdout ?? process.stdout;
4224
+ const stderr = dependencies.stderr ?? process.stderr;
4225
+ let exitCode = 0;
4226
+ const program2 = new Command().name("koed").enablePositionalOptions().description("Manage Koed services and AI Client integrations").version(resolveKoedControlPlaneVersion(), "-V, --version", "Print the Koed version").exitOverride().showSuggestionAfterError(false).configureOutput({
4227
+ writeOut: (text) => {
4228
+ stdout.write(text);
4229
+ },
4230
+ writeErr: () => {
4231
+ },
4232
+ outputError: () => {
4233
+ }
4234
+ });
4235
+ program2.action(() => program2.outputHelp());
4236
+ registerRuntimeCommands(program2, dependencies, (code) => {
4237
+ exitCode = code;
4238
+ });
4239
+ registerModelCommands(program2, dependencies, (code) => {
4240
+ exitCode = code;
4241
+ });
4242
+ registerPackageCommands(program2, dependencies, (code) => {
4243
+ exitCode = code;
4244
+ });
4245
+ registerProjectCommands(program2, dependencies, (code) => {
4246
+ exitCode = code;
4247
+ });
4248
+ registerUpstreamCommands(program2, dependencies, (code) => {
4249
+ exitCode = code;
4250
+ });
4251
+ registerLifecycleCommands(program2, dependencies, (code) => {
4252
+ exitCode = code;
4253
+ });
4254
+ registerIntegrationCommands(program2, dependencies, (code) => {
4255
+ exitCode = code;
4256
+ });
4257
+ registerComponentCommands(program2, dependencies, (code) => {
4258
+ exitCode = code;
4259
+ });
4260
+ registerInternalCommands(program2, dependencies, (code) => {
4261
+ exitCode = code;
4262
+ });
4263
+ registerRemoteCommands(program2, dependencies, (code) => {
4264
+ exitCode = code;
4265
+ });
4266
+ registerPersonalSyncCommands(program2, dependencies, (code) => {
4267
+ exitCode = code;
4268
+ }, args.includes("--advanced"));
4269
+ program2.addHelpText("after", "\nEnvironment:\n KOED_HOME Local configuration, logs, and runtime state\n KOED_REPO_ROOT Checkout path for development builds\n\nRun koed <command> --help for command help.");
4270
+ const configureCommand = (command) => {
4271
+ if (command.commands.length)
4272
+ command.helpCommand(true);
4273
+ for (const option of command.options) {
4274
+ if (option.required && !option.parseArg) {
4275
+ option.argParser((value, previous) => command.getOptionValueSource(option.attributeName()) === "cli" ? previous : value);
4276
+ }
4277
+ }
4278
+ for (const child of command.commands)
4279
+ configureCommand(child);
4280
+ };
4281
+ configureCommand(program2);
4282
+ const publicFamilies = program2.commands.map((command) => command.name()).filter((name) => name !== "secret-provider" && name !== "desktop" && name !== "help");
4283
+ try {
4284
+ await program2.parseAsync(args, { from: "user" });
4285
+ return exitCode;
4286
+ } catch (error) {
4287
+ if (!(error instanceof CommanderError))
4288
+ throw error;
4289
+ if (error.exitCode === 0)
4290
+ return 0;
4291
+ if (args[0] === "secret-provider") {
4292
+ stdout.write(secretProviderUsage);
4293
+ return 1;
4294
+ }
4295
+ const scope = publicFamilies.includes(args[0] ?? "") ? `koed ${args[0]}` : "koed";
4296
+ const isComponentInput = args[0] === "components";
4297
+ const message = isComponentInput ? error.code === "koed.componentInput" ? error.message : componentSyntaxError(error) : `${error.code === "commander.unknownCommand" || error.code === "commander.excessArguments" ? "Unknown command" : "Invalid command syntax"}. Run ${scope} --help.`;
4298
+ if (publicFamilies.includes(args[0] ?? "") && args.includes("--json"))
4299
+ stdout.write(`${JSON.stringify({ ok: false, error: message }, null, 2)}
4300
+ `);
4301
+ else
4302
+ stderr.write(`${message}
4303
+ `);
4304
+ return isComponentInput ? 1 : 2;
4305
+ }
4306
+ };
4307
+
4308
+ // packages/koed-server/dist/cli.js
4309
+ var runKoedServerCli = async (args, dependencies) => runCommandTree(args, dependencies);
4310
+ var isKoedServerCliEntrypoint = (moduleUrl, argvPath) => {
4311
+ if (!moduleUrl || !argvPath)
4312
+ return false;
4313
+ try {
4314
+ return realpathSync(argvPath) === realpathSync(fileURLToPath(moduleUrl));
4315
+ } catch {
4316
+ try {
4317
+ return pathToFileURL(argvPath).href === moduleUrl;
4318
+ } catch {
4319
+ return false;
4320
+ }
4321
+ }
4322
+ };
4323
+ var shouldExitPackagedSupervisor = (args, environment = process.env) => environment.KOED_PACKAGED_DESKTOP === "1" && args[0] === "start" && !args.includes("--daemon");
4324
+ if (isKoedServerCliEntrypoint(import.meta.url, process.argv[1])) {
4325
+ const entrypointArgs = process.argv.slice(2);
4326
+ void runKoedServerCli(entrypointArgs).then((exitCode) => {
4327
+ if (shouldExitPackagedSupervisor(entrypointArgs))
4328
+ process.exit(exitCode);
4329
+ process.exitCode = exitCode;
4330
+ });
4331
+ }
4332
+
4333
+ export {
4334
+ runKoedServerCli,
4335
+ isKoedServerCliEntrypoint,
4336
+ shouldExitPackagedSupervisor
4337
+ };