@libtmux/workspace-cli 0.1.0-alpha.11

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.
@@ -0,0 +1,3106 @@
1
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/error.js
2
+ class CommanderError extends Error {
3
+ constructor(exitCode, code, message) {
4
+ super(message);
5
+ Error.captureStackTrace(this, this.constructor);
6
+ this.name = this.constructor.name;
7
+ this.code = code;
8
+ this.exitCode = exitCode;
9
+ this.nestedError = undefined;
10
+ }
11
+ }
12
+
13
+ class InvalidArgumentError extends CommanderError {
14
+ constructor(message) {
15
+ super(1, "commander.invalidArgument", message);
16
+ Error.captureStackTrace(this, this.constructor);
17
+ this.name = this.constructor.name;
18
+ }
19
+ }
20
+
21
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/argument.js
22
+ class Argument {
23
+ constructor(name, description) {
24
+ this.description = description || "";
25
+ this.variadic = false;
26
+ this.parseArg = undefined;
27
+ this.defaultValue = undefined;
28
+ this.defaultValueDescription = undefined;
29
+ this.argChoices = undefined;
30
+ switch (name[0]) {
31
+ case "<":
32
+ this.required = true;
33
+ this._name = name.slice(1, -1);
34
+ break;
35
+ case "[":
36
+ this.required = false;
37
+ this._name = name.slice(1, -1);
38
+ break;
39
+ default:
40
+ this.required = true;
41
+ this._name = name;
42
+ break;
43
+ }
44
+ if (this._name.endsWith("...")) {
45
+ this.variadic = true;
46
+ this._name = this._name.slice(0, -3);
47
+ }
48
+ }
49
+ name() {
50
+ return this._name;
51
+ }
52
+ _collectValue(value, previous) {
53
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
54
+ return [value];
55
+ }
56
+ previous.push(value);
57
+ return previous;
58
+ }
59
+ default(value, description) {
60
+ this.defaultValue = value;
61
+ this.defaultValueDescription = description;
62
+ return this;
63
+ }
64
+ argParser(fn) {
65
+ this.parseArg = fn;
66
+ return this;
67
+ }
68
+ choices(values) {
69
+ this.argChoices = values.slice();
70
+ this.parseArg = (arg, previous) => {
71
+ if (!this.argChoices.includes(arg)) {
72
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
73
+ }
74
+ if (this.variadic) {
75
+ return this._collectValue(arg, previous);
76
+ }
77
+ return arg;
78
+ };
79
+ return this;
80
+ }
81
+ argRequired() {
82
+ this.required = true;
83
+ return this;
84
+ }
85
+ argOptional() {
86
+ this.required = false;
87
+ return this;
88
+ }
89
+ }
90
+ function humanReadableArgName(arg) {
91
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
92
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
93
+ }
94
+
95
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/command.js
96
+ import { EventEmitter } from "node:events";
97
+ import childProcess from "node:child_process";
98
+ import path from "node:path";
99
+ import fs from "node:fs";
100
+ import process from "node:process";
101
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
102
+
103
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/help.js
104
+ import { stripVTControlCharacters } from "node:util";
105
+
106
+ class Help {
107
+ constructor() {
108
+ this.helpWidth = undefined;
109
+ this.minWidthToWrap = 40;
110
+ this.sortSubcommands = false;
111
+ this.sortOptions = false;
112
+ this.showGlobalOptions = false;
113
+ }
114
+ prepareContext(contextOptions) {
115
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
116
+ }
117
+ visibleCommands(cmd) {
118
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
119
+ const helpCommand = cmd._getHelpCommand();
120
+ if (helpCommand && !helpCommand._hidden) {
121
+ visibleCommands.push(helpCommand);
122
+ }
123
+ if (this.sortSubcommands) {
124
+ visibleCommands.sort((a, b) => {
125
+ return a.name().localeCompare(b.name());
126
+ });
127
+ }
128
+ return visibleCommands;
129
+ }
130
+ compareOptions(a, b) {
131
+ const getSortKey = (option) => {
132
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
133
+ };
134
+ return getSortKey(a).localeCompare(getSortKey(b));
135
+ }
136
+ visibleOptions(cmd) {
137
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
138
+ const helpOption = cmd._getHelpOption();
139
+ if (helpOption && !helpOption.hidden) {
140
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
141
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
142
+ if (!removeShort && !removeLong) {
143
+ visibleOptions.push(helpOption);
144
+ } else if (helpOption.long && !removeLong) {
145
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
146
+ } else if (helpOption.short && !removeShort) {
147
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
148
+ }
149
+ }
150
+ if (this.sortOptions) {
151
+ visibleOptions.sort(this.compareOptions);
152
+ }
153
+ return visibleOptions;
154
+ }
155
+ visibleGlobalOptions(cmd) {
156
+ if (!this.showGlobalOptions)
157
+ return [];
158
+ const globalOptions = [];
159
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
160
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
161
+ globalOptions.push(...visibleOptions);
162
+ }
163
+ if (this.sortOptions) {
164
+ globalOptions.sort(this.compareOptions);
165
+ }
166
+ return globalOptions;
167
+ }
168
+ visibleArguments(cmd) {
169
+ if (cmd._argsDescription) {
170
+ cmd.registeredArguments.forEach((argument) => {
171
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
172
+ });
173
+ }
174
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
175
+ return cmd.registeredArguments;
176
+ }
177
+ return [];
178
+ }
179
+ subcommandTerm(cmd) {
180
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
181
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
182
+ }
183
+ optionTerm(option) {
184
+ return option.flags;
185
+ }
186
+ argumentTerm(argument) {
187
+ return argument.name();
188
+ }
189
+ longestSubcommandTermLength(cmd, helper) {
190
+ return helper.visibleCommands(cmd).reduce((max, command) => {
191
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
192
+ }, 0);
193
+ }
194
+ longestOptionTermLength(cmd, helper) {
195
+ return helper.visibleOptions(cmd).reduce((max, option) => {
196
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
197
+ }, 0);
198
+ }
199
+ longestGlobalOptionTermLength(cmd, helper) {
200
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
201
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
202
+ }, 0);
203
+ }
204
+ longestArgumentTermLength(cmd, helper) {
205
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
206
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
207
+ }, 0);
208
+ }
209
+ commandUsage(cmd) {
210
+ let cmdName = cmd._name;
211
+ if (cmd._aliases[0]) {
212
+ cmdName = cmdName + "|" + cmd._aliases[0];
213
+ }
214
+ let ancestorCmdNames = "";
215
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
216
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
217
+ }
218
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
219
+ }
220
+ commandDescription(cmd) {
221
+ return cmd.description();
222
+ }
223
+ subcommandDescription(cmd) {
224
+ return cmd.summary() || cmd.description();
225
+ }
226
+ optionDescription(option) {
227
+ const extraInfo = [];
228
+ if (option.argChoices) {
229
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
230
+ }
231
+ if (option.defaultValue !== undefined) {
232
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
233
+ if (showDefault) {
234
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
235
+ }
236
+ }
237
+ if (option.presetArg !== undefined && option.optional) {
238
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
239
+ }
240
+ if (option.envVar !== undefined) {
241
+ extraInfo.push(`env: ${option.envVar}`);
242
+ }
243
+ if (extraInfo.length > 0) {
244
+ const extraDescription = `(${extraInfo.join(", ")})`;
245
+ if (option.description) {
246
+ return `${option.description} ${extraDescription}`;
247
+ }
248
+ return extraDescription;
249
+ }
250
+ return option.description;
251
+ }
252
+ argumentDescription(argument) {
253
+ const extraInfo = [];
254
+ if (argument.argChoices) {
255
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
256
+ }
257
+ if (argument.defaultValue !== undefined) {
258
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
259
+ }
260
+ if (extraInfo.length > 0) {
261
+ const extraDescription = `(${extraInfo.join(", ")})`;
262
+ if (argument.description) {
263
+ return `${argument.description} ${extraDescription}`;
264
+ }
265
+ return extraDescription;
266
+ }
267
+ return argument.description;
268
+ }
269
+ formatItemList(heading, items, helper) {
270
+ if (items.length === 0)
271
+ return [];
272
+ return [helper.styleTitle(heading), ...items, ""];
273
+ }
274
+ groupItems(unsortedItems, visibleItems, getGroup) {
275
+ const result = new Map;
276
+ unsortedItems.forEach((item) => {
277
+ const group = getGroup(item);
278
+ if (!result.has(group))
279
+ result.set(group, []);
280
+ });
281
+ visibleItems.forEach((item) => {
282
+ const group = getGroup(item);
283
+ if (!result.has(group)) {
284
+ result.set(group, []);
285
+ }
286
+ result.get(group).push(item);
287
+ });
288
+ return result;
289
+ }
290
+ formatHelp(cmd, helper) {
291
+ const termWidth = helper.padWidth(cmd, helper);
292
+ const helpWidth = helper.helpWidth ?? 80;
293
+ function callFormatItem(term, description) {
294
+ return helper.formatItem(term, termWidth, description, helper);
295
+ }
296
+ let output = [
297
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
298
+ ""
299
+ ];
300
+ const commandDescription = helper.commandDescription(cmd);
301
+ if (commandDescription.length > 0) {
302
+ output = output.concat([
303
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
304
+ ""
305
+ ]);
306
+ }
307
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
308
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
309
+ });
310
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
311
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
312
+ optionGroups.forEach((options, group) => {
313
+ const optionList = options.map((option) => {
314
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
315
+ });
316
+ output = output.concat(this.formatItemList(group, optionList, helper));
317
+ });
318
+ if (helper.showGlobalOptions) {
319
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
320
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
321
+ });
322
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
323
+ }
324
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
325
+ commandGroups.forEach((commands, group) => {
326
+ const commandList = commands.map((sub) => {
327
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
328
+ });
329
+ output = output.concat(this.formatItemList(group, commandList, helper));
330
+ });
331
+ return output.join(`
332
+ `);
333
+ }
334
+ displayWidth(str) {
335
+ return stripVTControlCharacters(str).length;
336
+ }
337
+ styleTitle(str) {
338
+ return str;
339
+ }
340
+ styleUsage(str) {
341
+ return str.split(" ").map((word) => {
342
+ if (word === "[options]")
343
+ return this.styleOptionText(word);
344
+ if (word === "[command]")
345
+ return this.styleSubcommandText(word);
346
+ if (word[0] === "[" || word[0] === "<")
347
+ return this.styleArgumentText(word);
348
+ return this.styleCommandText(word);
349
+ }).join(" ");
350
+ }
351
+ styleCommandDescription(str) {
352
+ return this.styleDescriptionText(str);
353
+ }
354
+ styleOptionDescription(str) {
355
+ return this.styleDescriptionText(str);
356
+ }
357
+ styleSubcommandDescription(str) {
358
+ return this.styleDescriptionText(str);
359
+ }
360
+ styleArgumentDescription(str) {
361
+ return this.styleDescriptionText(str);
362
+ }
363
+ styleDescriptionText(str) {
364
+ return str;
365
+ }
366
+ styleOptionTerm(str) {
367
+ return this.styleOptionText(str);
368
+ }
369
+ styleSubcommandTerm(str) {
370
+ return str.split(" ").map((word) => {
371
+ if (word === "[options]")
372
+ return this.styleOptionText(word);
373
+ if (word[0] === "[" || word[0] === "<")
374
+ return this.styleArgumentText(word);
375
+ return this.styleSubcommandText(word);
376
+ }).join(" ");
377
+ }
378
+ styleArgumentTerm(str) {
379
+ return this.styleArgumentText(str);
380
+ }
381
+ styleOptionText(str) {
382
+ return str;
383
+ }
384
+ styleArgumentText(str) {
385
+ return str;
386
+ }
387
+ styleSubcommandText(str) {
388
+ return str;
389
+ }
390
+ styleCommandText(str) {
391
+ return str;
392
+ }
393
+ padWidth(cmd, helper) {
394
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
395
+ }
396
+ preformatted(str) {
397
+ return /\n[^\S\r\n]/.test(str);
398
+ }
399
+ formatItem(term, termWidth, description, helper) {
400
+ const itemIndent = 2;
401
+ const itemIndentStr = " ".repeat(itemIndent);
402
+ if (!description)
403
+ return itemIndentStr + term;
404
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
405
+ const spacerWidth = 2;
406
+ const helpWidth = this.helpWidth ?? 80;
407
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
408
+ let formattedDescription;
409
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
410
+ formattedDescription = description;
411
+ } else {
412
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
413
+ formattedDescription = wrappedDescription.replace(/\n/g, `
414
+ ` + " ".repeat(termWidth + spacerWidth));
415
+ }
416
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
417
+ ${itemIndentStr}`);
418
+ }
419
+ boxWrap(str, width) {
420
+ if (width < this.minWidthToWrap)
421
+ return str;
422
+ const rawLines = str.split(/\r\n|\n/);
423
+ const chunkPattern = /[\s]*[^\s]+/g;
424
+ const wrappedLines = [];
425
+ rawLines.forEach((line) => {
426
+ const chunks = line.match(chunkPattern);
427
+ if (chunks === null) {
428
+ wrappedLines.push("");
429
+ return;
430
+ }
431
+ let sumChunks = [chunks.shift()];
432
+ let sumWidth = this.displayWidth(sumChunks[0]);
433
+ chunks.forEach((chunk) => {
434
+ const visibleWidth = this.displayWidth(chunk);
435
+ if (sumWidth + visibleWidth <= width) {
436
+ sumChunks.push(chunk);
437
+ sumWidth += visibleWidth;
438
+ return;
439
+ }
440
+ wrappedLines.push(sumChunks.join(""));
441
+ const nextChunk = chunk.trimStart();
442
+ sumChunks = [nextChunk];
443
+ sumWidth = this.displayWidth(nextChunk);
444
+ });
445
+ wrappedLines.push(sumChunks.join(""));
446
+ });
447
+ return wrappedLines.join(`
448
+ `);
449
+ }
450
+ }
451
+
452
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/option.js
453
+ class Option {
454
+ constructor(flags, description) {
455
+ this.flags = flags;
456
+ this.description = description || "";
457
+ this.required = flags.includes("<");
458
+ this.optional = flags.includes("[");
459
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
460
+ this.mandatory = false;
461
+ const optionFlags = splitOptionFlags(flags);
462
+ this.short = optionFlags.shortFlag;
463
+ this.long = optionFlags.longFlag;
464
+ this.negate = false;
465
+ if (this.long) {
466
+ this.negate = this.long.startsWith("--no-");
467
+ }
468
+ this.defaultValue = undefined;
469
+ this.defaultValueDescription = undefined;
470
+ this.presetArg = undefined;
471
+ this.envVar = undefined;
472
+ this.parseArg = undefined;
473
+ this.hidden = false;
474
+ this.argChoices = undefined;
475
+ this.conflictsWith = [];
476
+ this.implied = undefined;
477
+ this.helpGroupHeading = undefined;
478
+ }
479
+ default(value, description) {
480
+ this.defaultValue = value;
481
+ this.defaultValueDescription = description;
482
+ return this;
483
+ }
484
+ preset(arg) {
485
+ this.presetArg = arg;
486
+ return this;
487
+ }
488
+ conflicts(names) {
489
+ this.conflictsWith = this.conflictsWith.concat(names);
490
+ return this;
491
+ }
492
+ implies(impliedOptionValues) {
493
+ let newImplied = impliedOptionValues;
494
+ if (typeof impliedOptionValues === "string") {
495
+ newImplied = { [impliedOptionValues]: true };
496
+ }
497
+ this.implied = Object.assign(this.implied || {}, newImplied);
498
+ return this;
499
+ }
500
+ env(name) {
501
+ this.envVar = name;
502
+ return this;
503
+ }
504
+ argParser(fn) {
505
+ this.parseArg = fn;
506
+ return this;
507
+ }
508
+ makeOptionMandatory(mandatory = true) {
509
+ this.mandatory = !!mandatory;
510
+ return this;
511
+ }
512
+ hideHelp(hide = true) {
513
+ this.hidden = !!hide;
514
+ return this;
515
+ }
516
+ _collectValue(value, previous) {
517
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
518
+ return [value];
519
+ }
520
+ previous.push(value);
521
+ return previous;
522
+ }
523
+ choices(values) {
524
+ this.argChoices = values.slice();
525
+ this.parseArg = (arg, previous) => {
526
+ if (!this.argChoices.includes(arg)) {
527
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
528
+ }
529
+ if (this.variadic) {
530
+ return this._collectValue(arg, previous);
531
+ }
532
+ return arg;
533
+ };
534
+ return this;
535
+ }
536
+ name() {
537
+ if (this.long) {
538
+ return this.long.replace(/^--/, "");
539
+ }
540
+ return this.short.replace(/^-/, "");
541
+ }
542
+ attributeName() {
543
+ if (this.negate) {
544
+ return camelcase(this.name().replace(/^no-/, ""));
545
+ }
546
+ return camelcase(this.name());
547
+ }
548
+ helpGroup(heading) {
549
+ this.helpGroupHeading = heading;
550
+ return this;
551
+ }
552
+ is(arg) {
553
+ return this.short === arg || this.long === arg;
554
+ }
555
+ isBoolean() {
556
+ return !this.required && !this.optional && !this.negate;
557
+ }
558
+ }
559
+
560
+ class DualOptions {
561
+ constructor(options) {
562
+ this.positiveOptions = new Map;
563
+ this.negativeOptions = new Map;
564
+ this.dualOptions = new Set;
565
+ options.forEach((option) => {
566
+ if (option.negate) {
567
+ this.negativeOptions.set(option.attributeName(), option);
568
+ } else {
569
+ this.positiveOptions.set(option.attributeName(), option);
570
+ }
571
+ });
572
+ this.negativeOptions.forEach((value, key) => {
573
+ if (this.positiveOptions.has(key)) {
574
+ this.dualOptions.add(key);
575
+ }
576
+ });
577
+ }
578
+ valueFromOption(value, option) {
579
+ const optionKey = option.attributeName();
580
+ if (!this.dualOptions.has(optionKey))
581
+ return true;
582
+ const preset = this.negativeOptions.get(optionKey).presetArg;
583
+ const negativeValue = preset !== undefined ? preset : false;
584
+ return option.negate === (negativeValue === value);
585
+ }
586
+ }
587
+ function camelcase(str) {
588
+ return str.split("-").reduce((str2, word) => {
589
+ return str2 + word[0].toUpperCase() + word.slice(1);
590
+ });
591
+ }
592
+ function splitOptionFlags(flags) {
593
+ let shortFlag;
594
+ let longFlag;
595
+ const shortFlagExp = /^-[^-]$/;
596
+ const longFlagExp = /^--[^-]/;
597
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
598
+ if (shortFlagExp.test(flagParts[0]))
599
+ shortFlag = flagParts.shift();
600
+ if (longFlagExp.test(flagParts[0]))
601
+ longFlag = flagParts.shift();
602
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
603
+ shortFlag = flagParts.shift();
604
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
605
+ shortFlag = longFlag;
606
+ longFlag = flagParts.shift();
607
+ }
608
+ if (flagParts[0].startsWith("-")) {
609
+ const unsupportedFlag = flagParts[0];
610
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
611
+ if (/^-[^-][^-]/.test(unsupportedFlag))
612
+ throw new Error(`${baseError}
613
+ - a short flag is a single dash and a single character
614
+ - either use a single dash and a single character (for a short flag)
615
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
616
+ if (shortFlagExp.test(unsupportedFlag))
617
+ throw new Error(`${baseError}
618
+ - too many short flags`);
619
+ if (longFlagExp.test(unsupportedFlag))
620
+ throw new Error(`${baseError}
621
+ - too many long flags`);
622
+ throw new Error(`${baseError}
623
+ - unrecognised flag format`);
624
+ }
625
+ if (shortFlag === undefined && longFlag === undefined)
626
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
627
+ return { shortFlag, longFlag };
628
+ }
629
+
630
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
631
+ var maxDistance = 3;
632
+ function editDistance(a, b) {
633
+ if (Math.abs(a.length - b.length) > maxDistance)
634
+ return Math.max(a.length, b.length);
635
+ const d = [];
636
+ for (let i = 0;i <= a.length; i++) {
637
+ d[i] = [i];
638
+ }
639
+ for (let j = 0;j <= b.length; j++) {
640
+ d[0][j] = j;
641
+ }
642
+ for (let j = 1;j <= b.length; j++) {
643
+ for (let i = 1;i <= a.length; i++) {
644
+ let cost;
645
+ if (a[i - 1] === b[j - 1]) {
646
+ cost = 0;
647
+ } else {
648
+ cost = 1;
649
+ }
650
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
651
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
652
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
653
+ }
654
+ }
655
+ }
656
+ return d[a.length][b.length];
657
+ }
658
+ function suggestSimilar(word, candidates) {
659
+ if (!candidates || candidates.length === 0)
660
+ return "";
661
+ candidates = Array.from(new Set(candidates));
662
+ const searchingOptions = word.startsWith("--");
663
+ if (searchingOptions) {
664
+ word = word.slice(2);
665
+ candidates = candidates.map((candidate) => candidate.slice(2));
666
+ }
667
+ let similar = [];
668
+ let bestDistance = maxDistance;
669
+ const minSimilarity = 0.4;
670
+ candidates.forEach((candidate) => {
671
+ if (candidate.length <= 1)
672
+ return;
673
+ const distance = editDistance(word, candidate);
674
+ const length = Math.max(word.length, candidate.length);
675
+ const similarity = (length - distance) / length;
676
+ if (similarity > minSimilarity) {
677
+ if (distance < bestDistance) {
678
+ bestDistance = distance;
679
+ similar = [candidate];
680
+ } else if (distance === bestDistance) {
681
+ similar.push(candidate);
682
+ }
683
+ }
684
+ });
685
+ similar.sort((a, b) => a.localeCompare(b));
686
+ if (searchingOptions) {
687
+ similar = similar.map((candidate) => `--${candidate}`);
688
+ }
689
+ if (similar.length > 1) {
690
+ return `
691
+ (Did you mean one of ${similar.join(", ")}?)`;
692
+ }
693
+ if (similar.length === 1) {
694
+ return `
695
+ (Did you mean ${similar[0]}?)`;
696
+ }
697
+ return "";
698
+ }
699
+
700
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/command.js
701
+ class Command extends EventEmitter {
702
+ constructor(name) {
703
+ super();
704
+ this.commands = [];
705
+ this.options = [];
706
+ this.parent = null;
707
+ this._allowUnknownOption = false;
708
+ this._allowExcessArguments = false;
709
+ this.registeredArguments = [];
710
+ this._args = this.registeredArguments;
711
+ this.args = [];
712
+ this.rawArgs = [];
713
+ this.processedArgs = [];
714
+ this._scriptPath = null;
715
+ this._name = name || "";
716
+ this._optionValues = {};
717
+ this._optionValueSources = {};
718
+ this._storeOptionsAsProperties = false;
719
+ this._actionHandler = null;
720
+ this._executableHandler = false;
721
+ this._executableFile = null;
722
+ this._executableDir = null;
723
+ this._defaultCommandName = null;
724
+ this._exitCallback = null;
725
+ this._aliases = [];
726
+ this._combineFlagAndOptionalValue = true;
727
+ this._description = "";
728
+ this._summary = "";
729
+ this._argsDescription = undefined;
730
+ this._enablePositionalOptions = false;
731
+ this._passThroughOptions = false;
732
+ this._lifeCycleHooks = {};
733
+ this._showHelpAfterError = false;
734
+ this._showSuggestionAfterError = true;
735
+ this._savedState = null;
736
+ this._outputConfiguration = {
737
+ writeOut: (str) => process.stdout.write(str),
738
+ writeErr: (str) => process.stderr.write(str),
739
+ outputError: (str, write) => write(str),
740
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
741
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
742
+ getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
743
+ getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
744
+ stripColor: (str) => stripVTControlCharacters2(str)
745
+ };
746
+ this._hidden = false;
747
+ this._helpOption = undefined;
748
+ this._addImplicitHelpCommand = undefined;
749
+ this._helpCommand = undefined;
750
+ this._helpConfiguration = {};
751
+ this._helpGroupHeading = undefined;
752
+ this._defaultCommandGroup = undefined;
753
+ this._defaultOptionGroup = undefined;
754
+ }
755
+ copyInheritedSettings(sourceCommand) {
756
+ this._outputConfiguration = sourceCommand._outputConfiguration;
757
+ this._helpOption = sourceCommand._helpOption;
758
+ this._helpCommand = sourceCommand._helpCommand;
759
+ this._helpConfiguration = sourceCommand._helpConfiguration;
760
+ this._exitCallback = sourceCommand._exitCallback;
761
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
762
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
763
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
764
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
765
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
766
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
767
+ return this;
768
+ }
769
+ _getCommandAndAncestors() {
770
+ const result = [];
771
+ for (let command = this;command; command = command.parent) {
772
+ result.push(command);
773
+ }
774
+ return result;
775
+ }
776
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
777
+ let desc = actionOptsOrExecDesc;
778
+ let opts = execOpts;
779
+ if (typeof desc === "object" && desc !== null) {
780
+ opts = desc;
781
+ desc = null;
782
+ }
783
+ opts = opts || {};
784
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
785
+ const cmd = this.createCommand(name);
786
+ if (desc) {
787
+ cmd.description(desc);
788
+ cmd._executableHandler = true;
789
+ }
790
+ if (opts.isDefault)
791
+ this._defaultCommandName = cmd._name;
792
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
793
+ cmd._executableFile = opts.executableFile || null;
794
+ if (args)
795
+ cmd.arguments(args);
796
+ this._registerCommand(cmd);
797
+ cmd.parent = this;
798
+ cmd.copyInheritedSettings(this);
799
+ if (desc)
800
+ return this;
801
+ return cmd;
802
+ }
803
+ createCommand(name) {
804
+ return new Command(name);
805
+ }
806
+ createHelp() {
807
+ return Object.assign(new Help, this.configureHelp());
808
+ }
809
+ configureHelp(configuration) {
810
+ if (configuration === undefined)
811
+ return this._helpConfiguration;
812
+ this._helpConfiguration = configuration;
813
+ return this;
814
+ }
815
+ configureOutput(configuration) {
816
+ if (configuration === undefined)
817
+ return this._outputConfiguration;
818
+ this._outputConfiguration = {
819
+ ...this._outputConfiguration,
820
+ ...configuration
821
+ };
822
+ return this;
823
+ }
824
+ showHelpAfterError(displayHelp = true) {
825
+ if (typeof displayHelp !== "string")
826
+ displayHelp = !!displayHelp;
827
+ this._showHelpAfterError = displayHelp;
828
+ return this;
829
+ }
830
+ showSuggestionAfterError(displaySuggestion = true) {
831
+ this._showSuggestionAfterError = !!displaySuggestion;
832
+ return this;
833
+ }
834
+ addCommand(cmd, opts) {
835
+ if (!cmd._name) {
836
+ throw new Error(`Command passed to .addCommand() must have a name
837
+ - specify the name in Command constructor or using .name()`);
838
+ }
839
+ opts = opts || {};
840
+ if (opts.isDefault)
841
+ this._defaultCommandName = cmd._name;
842
+ if (opts.noHelp || opts.hidden)
843
+ cmd._hidden = true;
844
+ this._registerCommand(cmd);
845
+ cmd.parent = this;
846
+ cmd._checkForBrokenPassThrough();
847
+ return this;
848
+ }
849
+ createArgument(name, description) {
850
+ return new Argument(name, description);
851
+ }
852
+ argument(name, description, parseArg, defaultValue) {
853
+ const argument = this.createArgument(name, description);
854
+ if (typeof parseArg === "function") {
855
+ argument.default(defaultValue).argParser(parseArg);
856
+ } else {
857
+ argument.default(parseArg);
858
+ }
859
+ this.addArgument(argument);
860
+ return this;
861
+ }
862
+ arguments(names) {
863
+ names.trim().split(/ +/).forEach((detail) => {
864
+ this.argument(detail);
865
+ });
866
+ return this;
867
+ }
868
+ addArgument(argument) {
869
+ const previousArgument = this.registeredArguments.slice(-1)[0];
870
+ if (previousArgument?.variadic) {
871
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
872
+ }
873
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
874
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
875
+ }
876
+ this.registeredArguments.push(argument);
877
+ return this;
878
+ }
879
+ helpCommand(enableOrNameAndArgs, description) {
880
+ if (typeof enableOrNameAndArgs === "boolean") {
881
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
882
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
883
+ this._initCommandGroup(this._getHelpCommand());
884
+ }
885
+ return this;
886
+ }
887
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
888
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
889
+ const helpDescription = description ?? "display help for command";
890
+ const helpCommand = this.createCommand(helpName);
891
+ helpCommand.helpOption(false);
892
+ if (helpArgs)
893
+ helpCommand.arguments(helpArgs);
894
+ if (helpDescription)
895
+ helpCommand.description(helpDescription);
896
+ this._addImplicitHelpCommand = true;
897
+ this._helpCommand = helpCommand;
898
+ if (enableOrNameAndArgs || description)
899
+ this._initCommandGroup(helpCommand);
900
+ return this;
901
+ }
902
+ addHelpCommand(helpCommand, deprecatedDescription) {
903
+ if (typeof helpCommand !== "object") {
904
+ this.helpCommand(helpCommand, deprecatedDescription);
905
+ return this;
906
+ }
907
+ this._addImplicitHelpCommand = true;
908
+ this._helpCommand = helpCommand;
909
+ this._initCommandGroup(helpCommand);
910
+ return this;
911
+ }
912
+ _getHelpCommand() {
913
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
914
+ if (hasImplicitHelpCommand) {
915
+ if (this._helpCommand === undefined) {
916
+ this.helpCommand(undefined, undefined);
917
+ }
918
+ return this._helpCommand;
919
+ }
920
+ return null;
921
+ }
922
+ hook(event, listener) {
923
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
924
+ if (!allowedValues.includes(event)) {
925
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
926
+ Expecting one of '${allowedValues.join("', '")}'`);
927
+ }
928
+ if (this._lifeCycleHooks[event]) {
929
+ this._lifeCycleHooks[event].push(listener);
930
+ } else {
931
+ this._lifeCycleHooks[event] = [listener];
932
+ }
933
+ return this;
934
+ }
935
+ exitOverride(fn) {
936
+ if (fn) {
937
+ this._exitCallback = fn;
938
+ } else {
939
+ this._exitCallback = (err) => {
940
+ if (err.code !== "commander.executeSubCommandAsync") {
941
+ throw err;
942
+ }
943
+ };
944
+ }
945
+ return this;
946
+ }
947
+ _exit(exitCode, code, message) {
948
+ if (this._exitCallback) {
949
+ this._exitCallback(new CommanderError(exitCode, code, message));
950
+ }
951
+ process.exit(exitCode);
952
+ }
953
+ action(fn) {
954
+ const listener = (args) => {
955
+ const expectedArgsCount = this.registeredArguments.length;
956
+ const actionArgs = args.slice(0, expectedArgsCount);
957
+ if (this._storeOptionsAsProperties) {
958
+ actionArgs[expectedArgsCount] = this;
959
+ } else {
960
+ actionArgs[expectedArgsCount] = this.opts();
961
+ }
962
+ actionArgs.push(this);
963
+ return fn.apply(this, actionArgs);
964
+ };
965
+ this._actionHandler = listener;
966
+ return this;
967
+ }
968
+ createOption(flags, description) {
969
+ return new Option(flags, description);
970
+ }
971
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
972
+ try {
973
+ return target.parseArg(value, previous);
974
+ } catch (err) {
975
+ if (err.code === "commander.invalidArgument") {
976
+ const message = `${invalidArgumentMessage} ${err.message}`;
977
+ this.error(message, { exitCode: err.exitCode, code: err.code });
978
+ }
979
+ throw err;
980
+ }
981
+ }
982
+ _registerOption(option) {
983
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
984
+ if (matchingOption) {
985
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
986
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
987
+ - already used by option '${matchingOption.flags}'`);
988
+ }
989
+ this._initOptionGroup(option);
990
+ this.options.push(option);
991
+ }
992
+ _registerCommand(command) {
993
+ const knownBy = (cmd) => {
994
+ return [cmd.name()].concat(cmd.aliases());
995
+ };
996
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
997
+ if (alreadyUsed) {
998
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
999
+ const newCmd = knownBy(command).join("|");
1000
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1001
+ }
1002
+ this._initCommandGroup(command);
1003
+ this.commands.push(command);
1004
+ }
1005
+ addOption(option) {
1006
+ this._registerOption(option);
1007
+ const oname = option.name();
1008
+ const name = option.attributeName();
1009
+ if (option.defaultValue !== undefined) {
1010
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1011
+ }
1012
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1013
+ if (val == null && option.presetArg !== undefined) {
1014
+ val = option.presetArg;
1015
+ }
1016
+ const oldValue = this.getOptionValue(name);
1017
+ if (val !== null && option.parseArg) {
1018
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1019
+ } else if (val !== null && option.variadic) {
1020
+ val = option._collectValue(val, oldValue);
1021
+ }
1022
+ if (val == null) {
1023
+ if (option.negate) {
1024
+ val = false;
1025
+ } else if (option.isBoolean() || option.optional) {
1026
+ val = true;
1027
+ } else {
1028
+ val = "";
1029
+ }
1030
+ }
1031
+ this.setOptionValueWithSource(name, val, valueSource);
1032
+ };
1033
+ this.on("option:" + oname, (val) => {
1034
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1035
+ handleOptionValue(val, invalidValueMessage, "cli");
1036
+ });
1037
+ if (option.envVar) {
1038
+ this.on("optionEnv:" + oname, (val) => {
1039
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1040
+ handleOptionValue(val, invalidValueMessage, "env");
1041
+ });
1042
+ }
1043
+ return this;
1044
+ }
1045
+ _optionEx(config, flags, description, fn, defaultValue) {
1046
+ if (typeof flags === "object" && flags instanceof Option) {
1047
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1048
+ }
1049
+ const option = this.createOption(flags, description);
1050
+ option.makeOptionMandatory(!!config.mandatory);
1051
+ if (typeof fn === "function") {
1052
+ option.default(defaultValue).argParser(fn);
1053
+ } else if (fn instanceof RegExp) {
1054
+ const regex = fn;
1055
+ fn = (val, def) => {
1056
+ const m = regex.exec(val);
1057
+ return m ? m[0] : def;
1058
+ };
1059
+ option.default(defaultValue).argParser(fn);
1060
+ } else {
1061
+ option.default(fn);
1062
+ }
1063
+ return this.addOption(option);
1064
+ }
1065
+ option(flags, description, parseArg, defaultValue) {
1066
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1067
+ }
1068
+ requiredOption(flags, description, parseArg, defaultValue) {
1069
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1070
+ }
1071
+ combineFlagAndOptionalValue(combine = true) {
1072
+ this._combineFlagAndOptionalValue = !!combine;
1073
+ return this;
1074
+ }
1075
+ allowUnknownOption(allowUnknown = true) {
1076
+ this._allowUnknownOption = !!allowUnknown;
1077
+ return this;
1078
+ }
1079
+ allowExcessArguments(allowExcess = true) {
1080
+ this._allowExcessArguments = !!allowExcess;
1081
+ return this;
1082
+ }
1083
+ enablePositionalOptions(positional = true) {
1084
+ this._enablePositionalOptions = !!positional;
1085
+ return this;
1086
+ }
1087
+ passThroughOptions(passThrough = true) {
1088
+ this._passThroughOptions = !!passThrough;
1089
+ this._checkForBrokenPassThrough();
1090
+ return this;
1091
+ }
1092
+ _checkForBrokenPassThrough() {
1093
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1094
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1095
+ }
1096
+ }
1097
+ storeOptionsAsProperties(storeAsProperties = true) {
1098
+ if (this.options.length) {
1099
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1100
+ }
1101
+ if (Object.keys(this._optionValues).length) {
1102
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1103
+ }
1104
+ this._storeOptionsAsProperties = !!storeAsProperties;
1105
+ return this;
1106
+ }
1107
+ getOptionValue(key) {
1108
+ if (this._storeOptionsAsProperties) {
1109
+ return this[key];
1110
+ }
1111
+ return this._optionValues[key];
1112
+ }
1113
+ setOptionValue(key, value) {
1114
+ return this.setOptionValueWithSource(key, value, undefined);
1115
+ }
1116
+ setOptionValueWithSource(key, value, source) {
1117
+ if (this._storeOptionsAsProperties) {
1118
+ this[key] = value;
1119
+ } else {
1120
+ this._optionValues[key] = value;
1121
+ }
1122
+ this._optionValueSources[key] = source;
1123
+ return this;
1124
+ }
1125
+ getOptionValueSource(key) {
1126
+ return this._optionValueSources[key];
1127
+ }
1128
+ getOptionValueSourceWithGlobals(key) {
1129
+ let source;
1130
+ this._getCommandAndAncestors().forEach((cmd) => {
1131
+ if (cmd.getOptionValueSource(key) !== undefined) {
1132
+ source = cmd.getOptionValueSource(key);
1133
+ }
1134
+ });
1135
+ return source;
1136
+ }
1137
+ _prepareUserArgs(argv, parseOptions) {
1138
+ if (argv !== undefined && !Array.isArray(argv)) {
1139
+ throw new Error("first parameter to parse must be array or undefined");
1140
+ }
1141
+ parseOptions = parseOptions || {};
1142
+ if (argv === undefined && parseOptions.from === undefined) {
1143
+ if (process.versions?.electron) {
1144
+ parseOptions.from = "electron";
1145
+ }
1146
+ const execArgv = process.execArgv ?? [];
1147
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1148
+ parseOptions.from = "eval";
1149
+ }
1150
+ }
1151
+ if (argv === undefined) {
1152
+ argv = process.argv;
1153
+ }
1154
+ this.rawArgs = argv.slice();
1155
+ let userArgs;
1156
+ switch (parseOptions.from) {
1157
+ case undefined:
1158
+ case "node":
1159
+ this._scriptPath = argv[1];
1160
+ userArgs = argv.slice(2);
1161
+ break;
1162
+ case "electron":
1163
+ if (process.defaultApp) {
1164
+ this._scriptPath = argv[1];
1165
+ userArgs = argv.slice(2);
1166
+ } else {
1167
+ userArgs = argv.slice(1);
1168
+ }
1169
+ break;
1170
+ case "user":
1171
+ userArgs = argv.slice(0);
1172
+ break;
1173
+ case "eval":
1174
+ userArgs = argv.slice(1);
1175
+ break;
1176
+ default:
1177
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1178
+ }
1179
+ if (!this._name && this._scriptPath)
1180
+ this.nameFromFilename(this._scriptPath);
1181
+ this._name = this._name || "program";
1182
+ return userArgs;
1183
+ }
1184
+ parse(argv, parseOptions) {
1185
+ this._prepareForParse();
1186
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1187
+ this._parseCommand([], userArgs);
1188
+ return this;
1189
+ }
1190
+ async parseAsync(argv, parseOptions) {
1191
+ this._prepareForParse();
1192
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1193
+ await this._parseCommand([], userArgs);
1194
+ return this;
1195
+ }
1196
+ _prepareForParse() {
1197
+ if (this._savedState === null) {
1198
+ this.options.filter((option) => option.negate && option.defaultValue === undefined && this.getOptionValue(option.attributeName()) === undefined).forEach((option) => {
1199
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1200
+ if (!this._findOption(positiveLongFlag)) {
1201
+ this.setOptionValueWithSource(option.attributeName(), true, "default");
1202
+ }
1203
+ });
1204
+ this.saveStateBeforeParse();
1205
+ } else {
1206
+ this.restoreStateBeforeParse();
1207
+ }
1208
+ }
1209
+ saveStateBeforeParse() {
1210
+ this._savedState = {
1211
+ _name: this._name,
1212
+ _optionValues: { ...this._optionValues },
1213
+ _optionValueSources: { ...this._optionValueSources }
1214
+ };
1215
+ }
1216
+ restoreStateBeforeParse() {
1217
+ if (this._storeOptionsAsProperties)
1218
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1219
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1220
+ this._name = this._savedState._name;
1221
+ this._scriptPath = null;
1222
+ this.rawArgs = [];
1223
+ this._optionValues = { ...this._savedState._optionValues };
1224
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1225
+ this.args = [];
1226
+ this.processedArgs = [];
1227
+ }
1228
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1229
+ if (fs.existsSync(executableFile))
1230
+ return;
1231
+ 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";
1232
+ const executableMissing = `'${executableFile}' does not exist
1233
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1234
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1235
+ - ${executableDirMessage}`;
1236
+ throw new Error(executableMissing);
1237
+ }
1238
+ _executeSubCommand(subcommand, args) {
1239
+ args = args.slice();
1240
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1241
+ function findFile(baseDir, baseName) {
1242
+ const localBin = path.resolve(baseDir, baseName);
1243
+ if (fs.existsSync(localBin))
1244
+ return localBin;
1245
+ if (sourceExt.includes(path.extname(baseName)))
1246
+ return;
1247
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1248
+ if (foundExt)
1249
+ return `${localBin}${foundExt}`;
1250
+ return;
1251
+ }
1252
+ this._checkForMissingMandatoryOptions();
1253
+ this._checkForConflictingOptions();
1254
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1255
+ let executableDir = this._executableDir || "";
1256
+ if (this._scriptPath) {
1257
+ let resolvedScriptPath;
1258
+ try {
1259
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1260
+ } catch {
1261
+ resolvedScriptPath = this._scriptPath;
1262
+ }
1263
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1264
+ }
1265
+ if (executableDir) {
1266
+ let localFile = findFile(executableDir, executableFile);
1267
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1268
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1269
+ if (legacyName !== this._name) {
1270
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1271
+ }
1272
+ }
1273
+ executableFile = localFile || executableFile;
1274
+ }
1275
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1276
+ let proc;
1277
+ if (process.platform !== "win32") {
1278
+ if (launchWithNode) {
1279
+ args.unshift(executableFile);
1280
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1281
+ proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
1282
+ } else {
1283
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1284
+ }
1285
+ } else {
1286
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1287
+ args.unshift(executableFile);
1288
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1289
+ proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
1290
+ }
1291
+ if (!proc.killed) {
1292
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1293
+ signals.forEach((signal) => {
1294
+ process.on(signal, () => {
1295
+ if (proc.killed === false && proc.exitCode === null) {
1296
+ proc.kill(signal);
1297
+ }
1298
+ });
1299
+ });
1300
+ }
1301
+ const exitCallback = this._exitCallback;
1302
+ proc.on("close", (code) => {
1303
+ code = code ?? 1;
1304
+ if (!exitCallback) {
1305
+ process.exit(code);
1306
+ } else {
1307
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1308
+ }
1309
+ });
1310
+ proc.on("error", (err) => {
1311
+ if (err.code === "ENOENT") {
1312
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1313
+ } else if (err.code === "EACCES") {
1314
+ throw new Error(`'${executableFile}' not executable`);
1315
+ }
1316
+ if (!exitCallback) {
1317
+ process.exit(1);
1318
+ } else {
1319
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1320
+ wrappedError.nestedError = err;
1321
+ exitCallback(wrappedError);
1322
+ }
1323
+ });
1324
+ this.runningCommand = proc;
1325
+ }
1326
+ _dispatchSubcommand(commandName, operands, unknown) {
1327
+ const subCommand = this._findCommand(commandName);
1328
+ if (!subCommand)
1329
+ this.help({ error: true });
1330
+ subCommand._prepareForParse();
1331
+ let promiseChain;
1332
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1333
+ promiseChain = this._chainOrCall(promiseChain, () => {
1334
+ if (subCommand._executableHandler) {
1335
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1336
+ } else {
1337
+ return subCommand._parseCommand(operands, unknown);
1338
+ }
1339
+ });
1340
+ return promiseChain;
1341
+ }
1342
+ _dispatchHelpCommand(subcommandName) {
1343
+ if (!subcommandName) {
1344
+ this.help();
1345
+ }
1346
+ const subCommand = this._findCommand(subcommandName);
1347
+ if (subCommand && !subCommand._executableHandler) {
1348
+ subCommand.help();
1349
+ }
1350
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1351
+ }
1352
+ _checkNumberOfArguments() {
1353
+ this.registeredArguments.forEach((arg, i) => {
1354
+ if (arg.required && this.args[i] == null) {
1355
+ this.missingArgument(arg.name());
1356
+ }
1357
+ });
1358
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1359
+ return;
1360
+ }
1361
+ if (this.args.length > this.registeredArguments.length) {
1362
+ this._excessArguments(this.args);
1363
+ }
1364
+ }
1365
+ _processArguments() {
1366
+ const myParseArg = (argument, value, previous) => {
1367
+ let parsedValue = value;
1368
+ if (value !== null && argument.parseArg) {
1369
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1370
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1371
+ }
1372
+ return parsedValue;
1373
+ };
1374
+ this._checkNumberOfArguments();
1375
+ const processedArgs = [];
1376
+ this.registeredArguments.forEach((declaredArg, index) => {
1377
+ let value = declaredArg.defaultValue;
1378
+ if (declaredArg.variadic) {
1379
+ if (index < this.args.length) {
1380
+ value = this.args.slice(index);
1381
+ if (declaredArg.parseArg) {
1382
+ value = value.reduce((processed, v) => {
1383
+ return myParseArg(declaredArg, v, processed);
1384
+ }, declaredArg.defaultValue);
1385
+ }
1386
+ } else if (value === undefined) {
1387
+ value = [];
1388
+ }
1389
+ } else if (index < this.args.length) {
1390
+ value = this.args[index];
1391
+ if (declaredArg.parseArg) {
1392
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1393
+ }
1394
+ }
1395
+ processedArgs[index] = value;
1396
+ });
1397
+ this.processedArgs = processedArgs;
1398
+ }
1399
+ _chainOrCall(promise, fn) {
1400
+ if (promise?.then && typeof promise.then === "function") {
1401
+ return promise.then(() => fn());
1402
+ }
1403
+ return fn();
1404
+ }
1405
+ _chainOrCallHooks(promise, event) {
1406
+ let result = promise;
1407
+ const hooks = [];
1408
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1409
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1410
+ hooks.push({ hookedCommand, callback });
1411
+ });
1412
+ });
1413
+ if (event === "postAction") {
1414
+ hooks.reverse();
1415
+ }
1416
+ hooks.forEach((hookDetail) => {
1417
+ result = this._chainOrCall(result, () => {
1418
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1419
+ });
1420
+ });
1421
+ return result;
1422
+ }
1423
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1424
+ let result = promise;
1425
+ if (this._lifeCycleHooks[event] !== undefined) {
1426
+ this._lifeCycleHooks[event].forEach((hook) => {
1427
+ result = this._chainOrCall(result, () => {
1428
+ return hook(this, subCommand);
1429
+ });
1430
+ });
1431
+ }
1432
+ return result;
1433
+ }
1434
+ _parseCommand(operands, unknown) {
1435
+ const parsed = this.parseOptions(unknown);
1436
+ this._parseOptionsEnv();
1437
+ this._parseOptionsImplied();
1438
+ operands = operands.concat(parsed.operands);
1439
+ unknown = parsed.unknown;
1440
+ this.args = operands.concat(unknown);
1441
+ if (operands && this._findCommand(operands[0])) {
1442
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1443
+ }
1444
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1445
+ return this._dispatchHelpCommand(operands[1]);
1446
+ }
1447
+ if (this._defaultCommandName) {
1448
+ this._outputHelpIfRequested(unknown);
1449
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1450
+ }
1451
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1452
+ this.help({ error: true });
1453
+ }
1454
+ this._outputHelpIfRequested(parsed.unknown);
1455
+ this._checkForMissingMandatoryOptions();
1456
+ this._checkForConflictingOptions();
1457
+ const checkForUnknownOptions = () => {
1458
+ if (parsed.unknown.length > 0) {
1459
+ this.unknownOption(parsed.unknown[0]);
1460
+ }
1461
+ };
1462
+ const commandEvent = `command:${this.name()}`;
1463
+ if (this._actionHandler) {
1464
+ checkForUnknownOptions();
1465
+ this._processArguments();
1466
+ let promiseChain;
1467
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1468
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1469
+ if (this.parent) {
1470
+ promiseChain = this._chainOrCall(promiseChain, () => {
1471
+ this.parent.emit(commandEvent, operands, unknown);
1472
+ });
1473
+ }
1474
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1475
+ return promiseChain;
1476
+ }
1477
+ if (this.parent?.listenerCount(commandEvent)) {
1478
+ checkForUnknownOptions();
1479
+ this._processArguments();
1480
+ this.parent.emit(commandEvent, operands, unknown);
1481
+ } else if (operands.length) {
1482
+ if (this._findCommand("*")) {
1483
+ return this._dispatchSubcommand("*", operands, unknown);
1484
+ }
1485
+ if (this.listenerCount("command:*")) {
1486
+ this.emit("command:*", operands, unknown);
1487
+ } else if (this.commands.length) {
1488
+ this.unknownCommand();
1489
+ } else {
1490
+ checkForUnknownOptions();
1491
+ this._processArguments();
1492
+ }
1493
+ } else if (this.commands.length) {
1494
+ checkForUnknownOptions();
1495
+ this.help({ error: true });
1496
+ } else {
1497
+ checkForUnknownOptions();
1498
+ this._processArguments();
1499
+ }
1500
+ }
1501
+ _findCommand(name) {
1502
+ if (!name)
1503
+ return;
1504
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1505
+ }
1506
+ _findOption(arg) {
1507
+ return this.options.find((option) => option.is(arg));
1508
+ }
1509
+ _checkForMissingMandatoryOptions() {
1510
+ this._getCommandAndAncestors().forEach((cmd) => {
1511
+ cmd.options.forEach((anOption) => {
1512
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1513
+ cmd.missingMandatoryOptionValue(anOption);
1514
+ }
1515
+ });
1516
+ });
1517
+ }
1518
+ _checkForConflictingLocalOptions() {
1519
+ const definedNonDefaultOptions = this.options.filter((option) => {
1520
+ const optionKey = option.attributeName();
1521
+ if (this.getOptionValue(optionKey) === undefined) {
1522
+ return false;
1523
+ }
1524
+ return this.getOptionValueSource(optionKey) !== "default";
1525
+ });
1526
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1527
+ optionsWithConflicting.forEach((option) => {
1528
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1529
+ if (conflictingAndDefined) {
1530
+ this._conflictingOption(option, conflictingAndDefined);
1531
+ }
1532
+ });
1533
+ }
1534
+ _checkForConflictingOptions() {
1535
+ this._getCommandAndAncestors().forEach((cmd) => {
1536
+ cmd._checkForConflictingLocalOptions();
1537
+ });
1538
+ }
1539
+ parseOptions(args) {
1540
+ const operands = [];
1541
+ const unknown = [];
1542
+ let dest = operands;
1543
+ function maybeOption(arg) {
1544
+ return arg.length > 1 && arg[0] === "-";
1545
+ }
1546
+ const negativeNumberArg = (arg) => {
1547
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1548
+ return false;
1549
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1550
+ };
1551
+ let activeVariadicOption = null;
1552
+ let activeGroup = null;
1553
+ let i = 0;
1554
+ while (i < args.length || activeGroup) {
1555
+ const arg = activeGroup ?? args[i++];
1556
+ activeGroup = null;
1557
+ if (arg === "--") {
1558
+ if (dest === unknown)
1559
+ dest.push(arg);
1560
+ dest.push(...args.slice(i));
1561
+ break;
1562
+ }
1563
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1564
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1565
+ continue;
1566
+ }
1567
+ activeVariadicOption = null;
1568
+ if (maybeOption(arg)) {
1569
+ const option = this._findOption(arg);
1570
+ if (option) {
1571
+ if (option.required) {
1572
+ const value = args[i++];
1573
+ if (value === undefined)
1574
+ this.optionMissingArgument(option);
1575
+ this.emit(`option:${option.name()}`, value);
1576
+ } else if (option.optional) {
1577
+ let value = null;
1578
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1579
+ value = args[i++];
1580
+ }
1581
+ this.emit(`option:${option.name()}`, value);
1582
+ } else {
1583
+ this.emit(`option:${option.name()}`);
1584
+ }
1585
+ activeVariadicOption = option.variadic ? option : null;
1586
+ continue;
1587
+ }
1588
+ }
1589
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1590
+ const option = this._findOption(`-${arg[1]}`);
1591
+ if (option) {
1592
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1593
+ this.emit(`option:${option.name()}`, arg.slice(2));
1594
+ } else {
1595
+ this.emit(`option:${option.name()}`);
1596
+ activeGroup = `-${arg.slice(2)}`;
1597
+ }
1598
+ continue;
1599
+ }
1600
+ }
1601
+ if (/^--[^=]+=/.test(arg)) {
1602
+ const index = arg.indexOf("=");
1603
+ const option = this._findOption(arg.slice(0, index));
1604
+ if (option && (option.required || option.optional)) {
1605
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1606
+ continue;
1607
+ }
1608
+ }
1609
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1610
+ dest = unknown;
1611
+ }
1612
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1613
+ if (this._findCommand(arg)) {
1614
+ operands.push(arg);
1615
+ unknown.push(...args.slice(i));
1616
+ break;
1617
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1618
+ operands.push(arg, ...args.slice(i));
1619
+ break;
1620
+ } else if (this._defaultCommandName) {
1621
+ unknown.push(arg, ...args.slice(i));
1622
+ break;
1623
+ }
1624
+ }
1625
+ if (this._passThroughOptions) {
1626
+ dest.push(arg, ...args.slice(i));
1627
+ break;
1628
+ }
1629
+ dest.push(arg);
1630
+ }
1631
+ return { operands, unknown };
1632
+ }
1633
+ opts() {
1634
+ if (this._storeOptionsAsProperties) {
1635
+ const result = {};
1636
+ const len = this.options.length;
1637
+ for (let i = 0;i < len; i++) {
1638
+ const key = this.options[i].attributeName();
1639
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1640
+ }
1641
+ return result;
1642
+ }
1643
+ return this._optionValues;
1644
+ }
1645
+ optsWithGlobals() {
1646
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1647
+ }
1648
+ error(message, errorOptions) {
1649
+ this._outputConfiguration.outputError(`${message}
1650
+ `, this._outputConfiguration.writeErr);
1651
+ if (typeof this._showHelpAfterError === "string") {
1652
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1653
+ `);
1654
+ } else if (this._showHelpAfterError) {
1655
+ this._outputConfiguration.writeErr(`
1656
+ `);
1657
+ this.outputHelp({ error: true });
1658
+ }
1659
+ const config = errorOptions || {};
1660
+ const exitCode = config.exitCode || 1;
1661
+ const code = config.code || "commander.error";
1662
+ this._exit(exitCode, code, message);
1663
+ }
1664
+ _parseOptionsEnv() {
1665
+ this.options.forEach((option) => {
1666
+ if (option.envVar && option.envVar in process.env) {
1667
+ const optionKey = option.attributeName();
1668
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1669
+ if (option.required || option.optional) {
1670
+ this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
1671
+ } else {
1672
+ this.emit(`optionEnv:${option.name()}`);
1673
+ }
1674
+ }
1675
+ }
1676
+ });
1677
+ }
1678
+ _parseOptionsImplied() {
1679
+ const dualHelper = new DualOptions(this.options);
1680
+ const hasCustomOptionValue = (optionKey) => {
1681
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1682
+ };
1683
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1684
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1685
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1686
+ });
1687
+ });
1688
+ }
1689
+ missingArgument(name) {
1690
+ const message = `error: missing required argument '${name}'`;
1691
+ this.error(message, { code: "commander.missingArgument" });
1692
+ }
1693
+ optionMissingArgument(option) {
1694
+ const message = `error: option '${option.flags}' argument missing`;
1695
+ this.error(message, { code: "commander.optionMissingArgument" });
1696
+ }
1697
+ missingMandatoryOptionValue(option) {
1698
+ const message = `error: required option '${option.flags}' not specified`;
1699
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1700
+ }
1701
+ _conflictingOption(option, conflictingOption) {
1702
+ const findBestOptionFromValue = (option2) => {
1703
+ const optionKey = option2.attributeName();
1704
+ const optionValue = this.getOptionValue(optionKey);
1705
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1706
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1707
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1708
+ return negativeOption;
1709
+ }
1710
+ return positiveOption || option2;
1711
+ };
1712
+ const getErrorMessage = (option2) => {
1713
+ const bestOption = findBestOptionFromValue(option2);
1714
+ const optionKey = bestOption.attributeName();
1715
+ const source = this.getOptionValueSource(optionKey);
1716
+ if (source === "env") {
1717
+ return `environment variable '${bestOption.envVar}'`;
1718
+ }
1719
+ return `option '${bestOption.flags}'`;
1720
+ };
1721
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1722
+ this.error(message, { code: "commander.conflictingOption" });
1723
+ }
1724
+ unknownOption(flag) {
1725
+ if (this._allowUnknownOption)
1726
+ return;
1727
+ let suggestion = "";
1728
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1729
+ let candidateFlags = [];
1730
+ let command = this;
1731
+ do {
1732
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1733
+ candidateFlags = candidateFlags.concat(moreFlags);
1734
+ command = command.parent;
1735
+ } while (command && !command._enablePositionalOptions);
1736
+ suggestion = suggestSimilar(flag, candidateFlags);
1737
+ }
1738
+ const message = `error: unknown option '${flag}'${suggestion}`;
1739
+ this.error(message, { code: "commander.unknownOption" });
1740
+ }
1741
+ _excessArguments(receivedArgs) {
1742
+ if (this._allowExcessArguments)
1743
+ return;
1744
+ const expected = this.registeredArguments.length;
1745
+ const s = expected === 1 ? "" : "s";
1746
+ const received = receivedArgs.length;
1747
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1748
+ const details = receivedArgs.join(", ");
1749
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
1750
+ this.error(message, { code: "commander.excessArguments" });
1751
+ }
1752
+ unknownCommand() {
1753
+ const unknownName = this.args[0];
1754
+ let suggestion = "";
1755
+ if (this._showSuggestionAfterError) {
1756
+ const candidateNames = [];
1757
+ this.createHelp().visibleCommands(this).forEach((command) => {
1758
+ candidateNames.push(command.name());
1759
+ if (command.alias())
1760
+ candidateNames.push(command.alias());
1761
+ });
1762
+ suggestion = suggestSimilar(unknownName, candidateNames);
1763
+ }
1764
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1765
+ this.error(message, { code: "commander.unknownCommand" });
1766
+ }
1767
+ version(str, flags, description) {
1768
+ if (str === undefined)
1769
+ return this._version;
1770
+ this._version = str;
1771
+ flags = flags || "-V, --version";
1772
+ description = description || "output the version number";
1773
+ const versionOption = this.createOption(flags, description);
1774
+ this._versionOptionName = versionOption.attributeName();
1775
+ this._registerOption(versionOption);
1776
+ this.on("option:" + versionOption.name(), () => {
1777
+ this._outputConfiguration.writeOut(`${str}
1778
+ `);
1779
+ this._exit(0, "commander.version", str);
1780
+ });
1781
+ return this;
1782
+ }
1783
+ description(str, argsDescription) {
1784
+ if (str === undefined && argsDescription === undefined)
1785
+ return this._description;
1786
+ this._description = str;
1787
+ if (argsDescription) {
1788
+ this._argsDescription = argsDescription;
1789
+ }
1790
+ return this;
1791
+ }
1792
+ summary(str) {
1793
+ if (str === undefined)
1794
+ return this._summary;
1795
+ this._summary = str;
1796
+ return this;
1797
+ }
1798
+ alias(alias) {
1799
+ if (alias === undefined)
1800
+ return this._aliases[0];
1801
+ let command = this;
1802
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1803
+ command = this.commands[this.commands.length - 1];
1804
+ }
1805
+ if (alias === command._name)
1806
+ throw new Error("Command alias can't be the same as its name");
1807
+ const matchingCommand = this.parent?._findCommand(alias);
1808
+ if (matchingCommand) {
1809
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1810
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1811
+ }
1812
+ command._aliases.push(alias);
1813
+ return this;
1814
+ }
1815
+ aliases(aliases) {
1816
+ if (aliases === undefined)
1817
+ return this._aliases;
1818
+ aliases.forEach((alias) => this.alias(alias));
1819
+ return this;
1820
+ }
1821
+ usage(str) {
1822
+ if (str === undefined) {
1823
+ if (this._usage)
1824
+ return this._usage;
1825
+ const args = this.registeredArguments.map((arg) => {
1826
+ return humanReadableArgName(arg);
1827
+ });
1828
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1829
+ }
1830
+ this._usage = str;
1831
+ return this;
1832
+ }
1833
+ name(str) {
1834
+ if (str === undefined)
1835
+ return this._name;
1836
+ this._name = str;
1837
+ return this;
1838
+ }
1839
+ helpGroup(heading) {
1840
+ if (heading === undefined)
1841
+ return this._helpGroupHeading ?? "";
1842
+ this._helpGroupHeading = heading;
1843
+ return this;
1844
+ }
1845
+ commandsGroup(heading) {
1846
+ if (heading === undefined)
1847
+ return this._defaultCommandGroup ?? "";
1848
+ this._defaultCommandGroup = heading;
1849
+ return this;
1850
+ }
1851
+ optionsGroup(heading) {
1852
+ if (heading === undefined)
1853
+ return this._defaultOptionGroup ?? "";
1854
+ this._defaultOptionGroup = heading;
1855
+ return this;
1856
+ }
1857
+ _initOptionGroup(option) {
1858
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1859
+ option.helpGroup(this._defaultOptionGroup);
1860
+ }
1861
+ _initCommandGroup(cmd) {
1862
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1863
+ cmd.helpGroup(this._defaultCommandGroup);
1864
+ }
1865
+ nameFromFilename(filename) {
1866
+ this._name = path.basename(filename, path.extname(filename));
1867
+ return this;
1868
+ }
1869
+ executableDir(path2) {
1870
+ if (path2 === undefined)
1871
+ return this._executableDir;
1872
+ this._executableDir = path2;
1873
+ return this;
1874
+ }
1875
+ helpInformation(contextOptions) {
1876
+ const helper = this.createHelp();
1877
+ const context = this._getOutputContext(contextOptions);
1878
+ helper.prepareContext({
1879
+ error: context.error,
1880
+ helpWidth: context.helpWidth,
1881
+ outputHasColors: context.hasColors
1882
+ });
1883
+ const text = helper.formatHelp(this, helper);
1884
+ if (context.hasColors)
1885
+ return text;
1886
+ return this._outputConfiguration.stripColor(text);
1887
+ }
1888
+ _getOutputContext(contextOptions) {
1889
+ contextOptions = contextOptions || {};
1890
+ const error = !!contextOptions.error;
1891
+ let baseWrite;
1892
+ let hasColors;
1893
+ let helpWidth;
1894
+ if (error) {
1895
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1896
+ hasColors = this._outputConfiguration.getErrHasColors();
1897
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1898
+ } else {
1899
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1900
+ hasColors = this._outputConfiguration.getOutHasColors();
1901
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1902
+ }
1903
+ const write = (str) => {
1904
+ if (!hasColors)
1905
+ str = this._outputConfiguration.stripColor(str);
1906
+ return baseWrite(str);
1907
+ };
1908
+ return { error, write, hasColors, helpWidth };
1909
+ }
1910
+ outputHelp(contextOptions) {
1911
+ let deprecatedCallback;
1912
+ if (typeof contextOptions === "function") {
1913
+ deprecatedCallback = contextOptions;
1914
+ contextOptions = undefined;
1915
+ }
1916
+ const outputContext = this._getOutputContext(contextOptions);
1917
+ const eventContext = {
1918
+ error: outputContext.error,
1919
+ write: outputContext.write,
1920
+ command: this
1921
+ };
1922
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1923
+ this.emit("beforeHelp", eventContext);
1924
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1925
+ if (deprecatedCallback) {
1926
+ helpInformation = deprecatedCallback(helpInformation);
1927
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1928
+ throw new Error("outputHelp callback must return a string or a Buffer");
1929
+ }
1930
+ }
1931
+ outputContext.write(helpInformation);
1932
+ if (this._getHelpOption()?.long) {
1933
+ this.emit(this._getHelpOption().long);
1934
+ }
1935
+ this.emit("afterHelp", eventContext);
1936
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1937
+ }
1938
+ helpOption(flags, description) {
1939
+ if (typeof flags === "boolean") {
1940
+ if (flags) {
1941
+ if (this._helpOption === null)
1942
+ this._helpOption = undefined;
1943
+ if (this._defaultOptionGroup) {
1944
+ this._initOptionGroup(this._getHelpOption());
1945
+ }
1946
+ } else {
1947
+ this._helpOption = null;
1948
+ }
1949
+ return this;
1950
+ }
1951
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
1952
+ if (flags || description)
1953
+ this._initOptionGroup(this._helpOption);
1954
+ return this;
1955
+ }
1956
+ _getHelpOption() {
1957
+ if (this._helpOption === undefined) {
1958
+ this.helpOption(undefined, undefined);
1959
+ }
1960
+ return this._helpOption;
1961
+ }
1962
+ addHelpOption(option) {
1963
+ this._helpOption = option;
1964
+ this._initOptionGroup(option);
1965
+ return this;
1966
+ }
1967
+ help(contextOptions) {
1968
+ this.outputHelp(contextOptions);
1969
+ let exitCode = Number(process.exitCode ?? 0);
1970
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1971
+ exitCode = 1;
1972
+ }
1973
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1974
+ }
1975
+ addHelpText(position, text) {
1976
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1977
+ if (!allowedValues.includes(position)) {
1978
+ throw new Error(`Unexpected value for position to addHelpText.
1979
+ Expecting one of '${allowedValues.join("', '")}'`);
1980
+ }
1981
+ const helpEvent = `${position}Help`;
1982
+ this.on(helpEvent, (context) => {
1983
+ let helpStr;
1984
+ if (typeof text === "function") {
1985
+ helpStr = text({ error: context.error, command: context.command });
1986
+ } else {
1987
+ helpStr = text;
1988
+ }
1989
+ if (helpStr) {
1990
+ context.write(`${helpStr}
1991
+ `);
1992
+ }
1993
+ });
1994
+ return this;
1995
+ }
1996
+ _outputHelpIfRequested(args) {
1997
+ const helpOption = this._getHelpOption();
1998
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1999
+ if (helpRequested) {
2000
+ this.outputHelp();
2001
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2002
+ }
2003
+ }
2004
+ }
2005
+ function incrementNodeInspectorPort(args) {
2006
+ return args.map((arg) => {
2007
+ if (!arg.startsWith("--inspect")) {
2008
+ return arg;
2009
+ }
2010
+ let debugOption;
2011
+ let debugHost = "127.0.0.1";
2012
+ let debugPort = "9229";
2013
+ let match;
2014
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2015
+ debugOption = match[1];
2016
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2017
+ debugOption = match[1];
2018
+ if (/^\d+$/.test(match[3])) {
2019
+ debugPort = match[3];
2020
+ } else {
2021
+ debugHost = match[3];
2022
+ }
2023
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2024
+ debugOption = match[1];
2025
+ debugHost = match[3];
2026
+ debugPort = match[4];
2027
+ }
2028
+ if (debugOption && debugPort !== "0") {
2029
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2030
+ }
2031
+ return arg;
2032
+ });
2033
+ }
2034
+ function useColor() {
2035
+ if (process.env.NO_COLOR || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false")
2036
+ return false;
2037
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)
2038
+ return true;
2039
+ return;
2040
+ }
2041
+
2042
+ // ../../node_modules/.bun/commander@15.0.0/node_modules/commander/index.js
2043
+ var program = new Command;
2044
+ // package.json
2045
+ var package_default = {
2046
+ name: "@libtmux/workspace-cli",
2047
+ version: "0.1.0-alpha.11",
2048
+ description: "A tmuxp-compatible workspace manager for Node and Bun.",
2049
+ license: "MIT",
2050
+ repository: {
2051
+ type: "git",
2052
+ url: "git+https://github.com/libtmux/libtmux-ts.git",
2053
+ directory: "packages/workspace-cli"
2054
+ },
2055
+ bin: {
2056
+ "tmux-workspace": "./dist/main.js"
2057
+ },
2058
+ files: [
2059
+ "dist",
2060
+ "docs",
2061
+ "THIRD-PARTY-NOTICES.md"
2062
+ ],
2063
+ type: "module",
2064
+ publishConfig: {
2065
+ access: "public"
2066
+ },
2067
+ scripts: {
2068
+ build: "bun run docs:check && bun run notices:check && rm -rf dist && bun build src/main.ts --target node --outdir dist --splitting --external libtmux",
2069
+ "docs:generate": "bun scripts/generate-reference.ts",
2070
+ "docs:check": "bun scripts/generate-reference.ts --check",
2071
+ notices: "bun scripts/third_party_notices.ts",
2072
+ "notices:check": "bun scripts/third_party_notices.ts --check",
2073
+ typecheck: "tsc -p tsconfig.json --noEmit",
2074
+ test: "bun test tests",
2075
+ "test:package": "bun run build && bun scripts/check-install.ts --package-only",
2076
+ "test:install": "bun run build && bun scripts/check-install.ts"
2077
+ },
2078
+ devDependencies: {
2079
+ "cli-truncate": "6.1.1",
2080
+ commander: "15.0.0",
2081
+ libtmux: "0.1.0-alpha.11",
2082
+ oxfmt: "0.68.0",
2083
+ "string-width": "8.2.2",
2084
+ yaml: "2.9.0"
2085
+ },
2086
+ peerDependencies: {
2087
+ libtmux: "0.1.0-alpha.11"
2088
+ },
2089
+ engines: {
2090
+ bun: ">=1.3.14",
2091
+ node: ">=22.12.0"
2092
+ }
2093
+ };
2094
+
2095
+ // src/grammar.json
2096
+ var grammar_default = [
2097
+ {
2098
+ command: "tmuxp load",
2099
+ actions: [
2100
+ {
2101
+ dest: "help",
2102
+ default: "==SUPPRESS==",
2103
+ required: false,
2104
+ nargs: 0,
2105
+ choices: null,
2106
+ const: null,
2107
+ help: "show this help message and exit",
2108
+ flags: ["-h", "--help"]
2109
+ },
2110
+ {
2111
+ dest: "workspace_files",
2112
+ default: null,
2113
+ required: true,
2114
+ nargs: "+",
2115
+ choices: null,
2116
+ const: null,
2117
+ help: "filepath to session or filename of session in tmuxp workspace directory",
2118
+ flags: []
2119
+ },
2120
+ {
2121
+ dest: "socket_name",
2122
+ default: null,
2123
+ required: false,
2124
+ nargs: null,
2125
+ choices: null,
2126
+ const: null,
2127
+ help: "passthru to tmux(1) -L",
2128
+ flags: ["-L"]
2129
+ },
2130
+ {
2131
+ dest: "socket_path",
2132
+ default: null,
2133
+ required: false,
2134
+ nargs: null,
2135
+ choices: null,
2136
+ const: null,
2137
+ help: "passthru to tmux(1) -S",
2138
+ flags: ["-S"]
2139
+ },
2140
+ {
2141
+ dest: "tmux_config_file",
2142
+ default: null,
2143
+ required: false,
2144
+ nargs: null,
2145
+ choices: null,
2146
+ const: null,
2147
+ help: "passthru to tmux(1) -f",
2148
+ flags: ["-f"]
2149
+ },
2150
+ {
2151
+ dest: "new_session_name",
2152
+ default: null,
2153
+ required: false,
2154
+ nargs: null,
2155
+ choices: null,
2156
+ const: null,
2157
+ help: "start new session with new session name",
2158
+ flags: ["-s"]
2159
+ },
2160
+ {
2161
+ dest: "answer_yes",
2162
+ default: false,
2163
+ required: false,
2164
+ nargs: 0,
2165
+ choices: null,
2166
+ const: true,
2167
+ help: "always answer yes",
2168
+ flags: ["--yes", "-y"]
2169
+ },
2170
+ {
2171
+ dest: "detached",
2172
+ default: false,
2173
+ required: false,
2174
+ nargs: 0,
2175
+ choices: null,
2176
+ const: true,
2177
+ help: "load the session without attaching it",
2178
+ flags: ["-d"]
2179
+ },
2180
+ {
2181
+ dest: "append",
2182
+ default: false,
2183
+ required: false,
2184
+ nargs: 0,
2185
+ choices: null,
2186
+ const: true,
2187
+ help: "load workspace, appending windows to the current session",
2188
+ flags: ["-a", "--append"]
2189
+ },
2190
+ {
2191
+ dest: "colors",
2192
+ default: null,
2193
+ required: false,
2194
+ nargs: 0,
2195
+ choices: null,
2196
+ const: 256,
2197
+ help: "force tmux to assume the terminal supports 256 colours.",
2198
+ flags: ["-2"]
2199
+ },
2200
+ {
2201
+ dest: "colors",
2202
+ default: null,
2203
+ required: false,
2204
+ nargs: 0,
2205
+ choices: null,
2206
+ const: 88,
2207
+ help: "legacy 88-color mode; rejected because tmux 3.2a+ does not implement it.",
2208
+ flags: ["-8"]
2209
+ },
2210
+ {
2211
+ dest: "log_file",
2212
+ default: null,
2213
+ required: false,
2214
+ nargs: null,
2215
+ choices: null,
2216
+ const: null,
2217
+ help: "file to log errors/output to",
2218
+ flags: ["--log-file"]
2219
+ },
2220
+ {
2221
+ dest: "progress_format",
2222
+ default: null,
2223
+ required: false,
2224
+ nargs: null,
2225
+ choices: null,
2226
+ const: null,
2227
+ help: "Progress line format: preset name (default, minimal, window, pane, verbose) or a format string with tokens {session}, {window}, {progress}, {window_progress}, {pane_progress}, etc. Env: TMUXP_PROGRESS_FORMAT",
2228
+ flags: ["--progress-format"]
2229
+ },
2230
+ {
2231
+ dest: "panel_lines",
2232
+ default: null,
2233
+ required: false,
2234
+ nargs: null,
2235
+ choices: null,
2236
+ const: null,
2237
+ help: "Recent script-output lines in the terminal panel (default: 3). 0 forwards each stream directly; -1 uses terminal height. Retention is bounded. Env: TMUXP_PROGRESS_LINES",
2238
+ flags: ["--progress-lines"]
2239
+ },
2240
+ {
2241
+ dest: "no_progress",
2242
+ default: false,
2243
+ required: false,
2244
+ nargs: 0,
2245
+ choices: null,
2246
+ const: true,
2247
+ help: "Disable terminal progress. Env: TMUXP_PROGRESS=0",
2248
+ flags: ["--no-progress"]
2249
+ }
2250
+ ],
2251
+ exclusive_groups: [["colors", "colors"]],
2252
+ required_groups: []
2253
+ },
2254
+ {
2255
+ command: "tmuxp shell",
2256
+ actions: [
2257
+ {
2258
+ dest: "help",
2259
+ default: "==SUPPRESS==",
2260
+ required: false,
2261
+ nargs: 0,
2262
+ choices: null,
2263
+ const: null,
2264
+ help: "show this help message and exit",
2265
+ flags: ["-h", "--help"]
2266
+ },
2267
+ {
2268
+ dest: "session_name",
2269
+ default: null,
2270
+ required: false,
2271
+ nargs: "?",
2272
+ choices: null,
2273
+ const: null,
2274
+ help: null,
2275
+ flags: []
2276
+ },
2277
+ {
2278
+ dest: "window_name",
2279
+ default: null,
2280
+ required: false,
2281
+ nargs: "?",
2282
+ choices: null,
2283
+ const: null,
2284
+ help: null,
2285
+ flags: []
2286
+ },
2287
+ {
2288
+ dest: "socket_path",
2289
+ default: null,
2290
+ required: false,
2291
+ nargs: null,
2292
+ choices: null,
2293
+ const: null,
2294
+ help: "pass-through for tmux -S",
2295
+ flags: ["-S"]
2296
+ },
2297
+ {
2298
+ dest: "socket_name",
2299
+ default: null,
2300
+ required: false,
2301
+ nargs: null,
2302
+ choices: null,
2303
+ const: null,
2304
+ help: "pass-through for tmux -L",
2305
+ flags: ["-L"]
2306
+ },
2307
+ {
2308
+ dest: "command",
2309
+ default: null,
2310
+ required: false,
2311
+ nargs: null,
2312
+ choices: null,
2313
+ const: null,
2314
+ help: "instead of opening shell, execute python code in libtmux and exit",
2315
+ flags: ["-c"]
2316
+ },
2317
+ {
2318
+ dest: "shell",
2319
+ default: "best",
2320
+ required: false,
2321
+ nargs: 0,
2322
+ choices: null,
2323
+ const: "best",
2324
+ help: "use best shell available in site packages",
2325
+ flags: ["--best"]
2326
+ },
2327
+ {
2328
+ dest: "shell",
2329
+ default: null,
2330
+ required: false,
2331
+ nargs: 0,
2332
+ choices: null,
2333
+ const: "pdb",
2334
+ help: "use plain pdb",
2335
+ flags: ["--pdb"]
2336
+ },
2337
+ {
2338
+ dest: "shell",
2339
+ default: null,
2340
+ required: false,
2341
+ nargs: 0,
2342
+ choices: null,
2343
+ const: "code",
2344
+ help: "use stdlib's code.interact()",
2345
+ flags: ["--code"]
2346
+ },
2347
+ {
2348
+ dest: "shell",
2349
+ default: null,
2350
+ required: false,
2351
+ nargs: 0,
2352
+ choices: null,
2353
+ const: "ptipython",
2354
+ help: "use ptpython + ipython",
2355
+ flags: ["--ptipython"]
2356
+ },
2357
+ {
2358
+ dest: "shell",
2359
+ default: null,
2360
+ required: false,
2361
+ nargs: 0,
2362
+ choices: null,
2363
+ const: "ptpython",
2364
+ help: "use ptpython",
2365
+ flags: ["--ptpython"]
2366
+ },
2367
+ {
2368
+ dest: "shell",
2369
+ default: null,
2370
+ required: false,
2371
+ nargs: 0,
2372
+ choices: null,
2373
+ const: "ipython",
2374
+ help: "use ipython",
2375
+ flags: ["--ipython"]
2376
+ },
2377
+ {
2378
+ dest: "shell",
2379
+ default: null,
2380
+ required: false,
2381
+ nargs: 0,
2382
+ choices: null,
2383
+ const: "bpython",
2384
+ help: "use bpython",
2385
+ flags: ["--bpython"]
2386
+ },
2387
+ {
2388
+ dest: "use_pythonrc",
2389
+ default: false,
2390
+ required: false,
2391
+ nargs: 0,
2392
+ choices: null,
2393
+ const: true,
2394
+ help: "load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code",
2395
+ flags: ["--use-pythonrc"]
2396
+ },
2397
+ {
2398
+ dest: "use_pythonrc",
2399
+ default: false,
2400
+ required: false,
2401
+ nargs: 0,
2402
+ choices: null,
2403
+ const: false,
2404
+ help: "load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code",
2405
+ flags: ["--no-startup"]
2406
+ },
2407
+ {
2408
+ dest: "use_vi_mode",
2409
+ default: false,
2410
+ required: false,
2411
+ nargs: 0,
2412
+ choices: null,
2413
+ const: true,
2414
+ help: "use vi-mode in ptpython/ptipython",
2415
+ flags: ["--use-vi-mode"]
2416
+ },
2417
+ {
2418
+ dest: "use_vi_mode",
2419
+ default: false,
2420
+ required: false,
2421
+ nargs: 0,
2422
+ choices: null,
2423
+ const: false,
2424
+ help: "use vi-mode in ptpython/ptipython",
2425
+ flags: ["--no-vi-mode"]
2426
+ }
2427
+ ],
2428
+ exclusive_groups: [["shell", "shell", "shell", "shell", "shell", "shell", "shell"]],
2429
+ required_groups: []
2430
+ },
2431
+ {
2432
+ command: "tmuxp import teamocil",
2433
+ actions: [
2434
+ {
2435
+ dest: "help",
2436
+ default: "==SUPPRESS==",
2437
+ required: false,
2438
+ nargs: 0,
2439
+ choices: null,
2440
+ const: null,
2441
+ help: "show this help message and exit",
2442
+ flags: ["-h", "--help"]
2443
+ },
2444
+ {
2445
+ dest: "workspace_file",
2446
+ default: null,
2447
+ required: false,
2448
+ nargs: "?",
2449
+ choices: null,
2450
+ const: null,
2451
+ help: "checks current ~/.teamocil and current directory for yaml files",
2452
+ flags: []
2453
+ }
2454
+ ],
2455
+ exclusive_groups: [["workspace_file"]],
2456
+ required_groups: [["workspace_file"]]
2457
+ },
2458
+ {
2459
+ command: "tmuxp import tmuxinator",
2460
+ actions: [
2461
+ {
2462
+ dest: "help",
2463
+ default: "==SUPPRESS==",
2464
+ required: false,
2465
+ nargs: 0,
2466
+ choices: null,
2467
+ const: null,
2468
+ help: "show this help message and exit",
2469
+ flags: ["-h", "--help"]
2470
+ },
2471
+ {
2472
+ dest: "workspace_file",
2473
+ default: null,
2474
+ required: false,
2475
+ nargs: "?",
2476
+ choices: null,
2477
+ const: null,
2478
+ help: "checks current ~/.tmuxinator and current directory for yaml files",
2479
+ flags: []
2480
+ }
2481
+ ],
2482
+ exclusive_groups: [["workspace_file"]],
2483
+ required_groups: [["workspace_file"]]
2484
+ },
2485
+ {
2486
+ command: "tmuxp import",
2487
+ actions: [
2488
+ {
2489
+ dest: "help",
2490
+ default: "==SUPPRESS==",
2491
+ required: false,
2492
+ nargs: 0,
2493
+ choices: null,
2494
+ const: null,
2495
+ help: "show this help message and exit",
2496
+ flags: ["-h", "--help"]
2497
+ }
2498
+ ],
2499
+ exclusive_groups: [],
2500
+ required_groups: []
2501
+ },
2502
+ {
2503
+ command: "tmuxp convert",
2504
+ actions: [
2505
+ {
2506
+ dest: "help",
2507
+ default: "==SUPPRESS==",
2508
+ required: false,
2509
+ nargs: 0,
2510
+ choices: null,
2511
+ const: null,
2512
+ help: "show this help message and exit",
2513
+ flags: ["-h", "--help"]
2514
+ },
2515
+ {
2516
+ dest: "workspace_file",
2517
+ default: null,
2518
+ required: true,
2519
+ nargs: null,
2520
+ choices: null,
2521
+ const: null,
2522
+ help: "checks tmuxp and current directory for workspace files.",
2523
+ flags: []
2524
+ },
2525
+ {
2526
+ dest: "answer_yes",
2527
+ default: false,
2528
+ required: false,
2529
+ nargs: 0,
2530
+ choices: null,
2531
+ const: true,
2532
+ help: "always answer yes",
2533
+ flags: ["--yes", "-y"]
2534
+ }
2535
+ ],
2536
+ exclusive_groups: [],
2537
+ required_groups: []
2538
+ },
2539
+ {
2540
+ command: "tmuxp debug-info",
2541
+ actions: [
2542
+ {
2543
+ dest: "help",
2544
+ default: "==SUPPRESS==",
2545
+ required: false,
2546
+ nargs: 0,
2547
+ choices: null,
2548
+ const: null,
2549
+ help: "show this help message and exit",
2550
+ flags: ["-h", "--help"]
2551
+ },
2552
+ {
2553
+ dest: "output_json",
2554
+ default: false,
2555
+ required: false,
2556
+ nargs: 0,
2557
+ choices: null,
2558
+ const: true,
2559
+ help: "output as JSON",
2560
+ flags: ["--json"]
2561
+ }
2562
+ ],
2563
+ exclusive_groups: [],
2564
+ required_groups: []
2565
+ },
2566
+ {
2567
+ command: "tmuxp ls",
2568
+ actions: [
2569
+ {
2570
+ dest: "help",
2571
+ default: "==SUPPRESS==",
2572
+ required: false,
2573
+ nargs: 0,
2574
+ choices: null,
2575
+ const: null,
2576
+ help: "show this help message and exit",
2577
+ flags: ["-h", "--help"]
2578
+ },
2579
+ {
2580
+ dest: "tree",
2581
+ default: false,
2582
+ required: false,
2583
+ nargs: 0,
2584
+ choices: null,
2585
+ const: true,
2586
+ help: "display workspaces grouped by directory",
2587
+ flags: ["--tree"]
2588
+ },
2589
+ {
2590
+ dest: "output_json",
2591
+ default: false,
2592
+ required: false,
2593
+ nargs: 0,
2594
+ choices: null,
2595
+ const: true,
2596
+ help: "output as JSON",
2597
+ flags: ["--json"]
2598
+ },
2599
+ {
2600
+ dest: "output_ndjson",
2601
+ default: false,
2602
+ required: false,
2603
+ nargs: 0,
2604
+ choices: null,
2605
+ const: true,
2606
+ help: "output as NDJSON (one JSON per line)",
2607
+ flags: ["--ndjson"]
2608
+ },
2609
+ {
2610
+ dest: "full",
2611
+ default: false,
2612
+ required: false,
2613
+ nargs: 0,
2614
+ choices: null,
2615
+ const: true,
2616
+ help: "include full config content in output",
2617
+ flags: ["--full"]
2618
+ }
2619
+ ],
2620
+ exclusive_groups: [],
2621
+ required_groups: []
2622
+ },
2623
+ {
2624
+ command: "tmuxp search",
2625
+ actions: [
2626
+ {
2627
+ dest: "help",
2628
+ default: "==SUPPRESS==",
2629
+ required: false,
2630
+ nargs: 0,
2631
+ choices: null,
2632
+ const: null,
2633
+ help: "show this help message and exit",
2634
+ flags: ["-h", "--help"]
2635
+ },
2636
+ {
2637
+ dest: "query_terms",
2638
+ default: null,
2639
+ required: false,
2640
+ nargs: "*",
2641
+ choices: null,
2642
+ const: null,
2643
+ help: "search patterns (prefix with field: for field-scoped search)",
2644
+ flags: []
2645
+ },
2646
+ {
2647
+ dest: "field",
2648
+ default: null,
2649
+ required: false,
2650
+ nargs: null,
2651
+ choices: null,
2652
+ const: null,
2653
+ help: "restrict search to field(s): name, session/s, path/p, window/w, pane",
2654
+ flags: ["-f", "--field"]
2655
+ },
2656
+ {
2657
+ dest: "ignore_case",
2658
+ default: false,
2659
+ required: false,
2660
+ nargs: 0,
2661
+ choices: null,
2662
+ const: true,
2663
+ help: "case-insensitive matching",
2664
+ flags: ["-i", "--ignore-case"]
2665
+ },
2666
+ {
2667
+ dest: "smart_case",
2668
+ default: false,
2669
+ required: false,
2670
+ nargs: 0,
2671
+ choices: null,
2672
+ const: true,
2673
+ help: "case-insensitive unless pattern has uppercase",
2674
+ flags: ["-S", "--smart-case"]
2675
+ },
2676
+ {
2677
+ dest: "fixed_strings",
2678
+ default: false,
2679
+ required: false,
2680
+ nargs: 0,
2681
+ choices: null,
2682
+ const: true,
2683
+ help: "treat patterns as literal strings, not regex",
2684
+ flags: ["-F", "--fixed-strings"]
2685
+ },
2686
+ {
2687
+ dest: "word_regexp",
2688
+ default: false,
2689
+ required: false,
2690
+ nargs: 0,
2691
+ choices: null,
2692
+ const: true,
2693
+ help: "match whole words only",
2694
+ flags: ["-w", "--word-regexp"]
2695
+ },
2696
+ {
2697
+ dest: "invert_match",
2698
+ default: false,
2699
+ required: false,
2700
+ nargs: 0,
2701
+ choices: null,
2702
+ const: true,
2703
+ help: "show workspaces that do NOT match",
2704
+ flags: ["-v", "--invert-match"]
2705
+ },
2706
+ {
2707
+ dest: "match_any",
2708
+ default: false,
2709
+ required: false,
2710
+ nargs: 0,
2711
+ choices: null,
2712
+ const: true,
2713
+ help: "match ANY pattern (OR logic); default is ALL (AND logic)",
2714
+ flags: ["--any"]
2715
+ },
2716
+ {
2717
+ dest: "output_json",
2718
+ default: false,
2719
+ required: false,
2720
+ nargs: 0,
2721
+ choices: null,
2722
+ const: true,
2723
+ help: "output as JSON",
2724
+ flags: ["--json"]
2725
+ },
2726
+ {
2727
+ dest: "output_ndjson",
2728
+ default: false,
2729
+ required: false,
2730
+ nargs: 0,
2731
+ choices: null,
2732
+ const: true,
2733
+ help: "output as NDJSON (one JSON per line)",
2734
+ flags: ["--ndjson"]
2735
+ }
2736
+ ],
2737
+ exclusive_groups: [],
2738
+ required_groups: []
2739
+ },
2740
+ {
2741
+ command: "tmuxp edit",
2742
+ actions: [
2743
+ {
2744
+ dest: "help",
2745
+ default: "==SUPPRESS==",
2746
+ required: false,
2747
+ nargs: 0,
2748
+ choices: null,
2749
+ const: null,
2750
+ help: "show this help message and exit",
2751
+ flags: ["-h", "--help"]
2752
+ },
2753
+ {
2754
+ dest: "workspace_file",
2755
+ default: null,
2756
+ required: true,
2757
+ nargs: null,
2758
+ choices: null,
2759
+ const: null,
2760
+ help: "checks current tmuxp and current directory for workspace files.",
2761
+ flags: []
2762
+ }
2763
+ ],
2764
+ exclusive_groups: [],
2765
+ required_groups: []
2766
+ },
2767
+ {
2768
+ command: "tmuxp freeze",
2769
+ actions: [
2770
+ {
2771
+ dest: "help",
2772
+ default: "==SUPPRESS==",
2773
+ required: false,
2774
+ nargs: 0,
2775
+ choices: null,
2776
+ const: null,
2777
+ help: "show this help message and exit",
2778
+ flags: ["-h", "--help"]
2779
+ },
2780
+ {
2781
+ dest: "session_name",
2782
+ default: null,
2783
+ required: false,
2784
+ nargs: "?",
2785
+ choices: null,
2786
+ const: null,
2787
+ help: null,
2788
+ flags: []
2789
+ },
2790
+ {
2791
+ dest: "socket_path",
2792
+ default: null,
2793
+ required: false,
2794
+ nargs: null,
2795
+ choices: null,
2796
+ const: null,
2797
+ help: "pass-through for tmux -S",
2798
+ flags: ["-S"]
2799
+ },
2800
+ {
2801
+ dest: "socket_name",
2802
+ default: null,
2803
+ required: false,
2804
+ nargs: null,
2805
+ choices: null,
2806
+ const: null,
2807
+ help: "pass-through for tmux -L",
2808
+ flags: ["-L"]
2809
+ },
2810
+ {
2811
+ dest: "workspace_format",
2812
+ default: null,
2813
+ required: false,
2814
+ nargs: null,
2815
+ choices: ["yaml", "json"],
2816
+ const: null,
2817
+ help: "format to save in",
2818
+ flags: ["-f", "--workspace-format"]
2819
+ },
2820
+ {
2821
+ dest: "save_to",
2822
+ default: null,
2823
+ required: false,
2824
+ nargs: null,
2825
+ choices: null,
2826
+ const: null,
2827
+ help: "file to save to",
2828
+ flags: ["-o", "--save-to"]
2829
+ },
2830
+ {
2831
+ dest: "answer_yes",
2832
+ default: false,
2833
+ required: false,
2834
+ nargs: 0,
2835
+ choices: null,
2836
+ const: true,
2837
+ help: "always answer yes",
2838
+ flags: ["--yes", "-y"]
2839
+ },
2840
+ {
2841
+ dest: "quiet",
2842
+ default: false,
2843
+ required: false,
2844
+ nargs: 0,
2845
+ choices: null,
2846
+ const: true,
2847
+ help: "don't prompt for confirmation",
2848
+ flags: ["--quiet", "-q"]
2849
+ },
2850
+ {
2851
+ dest: "force",
2852
+ default: false,
2853
+ required: false,
2854
+ nargs: 0,
2855
+ choices: null,
2856
+ const: true,
2857
+ help: "overwrite the workspace file",
2858
+ flags: ["--force"]
2859
+ }
2860
+ ],
2861
+ exclusive_groups: [],
2862
+ required_groups: []
2863
+ },
2864
+ {
2865
+ command: "tmuxp",
2866
+ actions: [
2867
+ {
2868
+ dest: "help",
2869
+ default: "==SUPPRESS==",
2870
+ required: false,
2871
+ nargs: 0,
2872
+ choices: null,
2873
+ const: null,
2874
+ help: "show this help message and exit",
2875
+ flags: ["-h", "--help"]
2876
+ },
2877
+ {
2878
+ dest: "version",
2879
+ default: "==SUPPRESS==",
2880
+ required: false,
2881
+ nargs: 0,
2882
+ choices: null,
2883
+ const: null,
2884
+ help: "show program's version number and exit",
2885
+ flags: ["--version", "-V"]
2886
+ },
2887
+ {
2888
+ dest: "log_level",
2889
+ default: "warning",
2890
+ required: false,
2891
+ nargs: null,
2892
+ choices: ["debug", "info", "warning", "error", "critical"],
2893
+ const: null,
2894
+ help: 'log level (debug, info, warning, error, critical) (default "warning")',
2895
+ flags: ["--log-level"]
2896
+ },
2897
+ {
2898
+ dest: "color",
2899
+ default: "auto",
2900
+ required: false,
2901
+ nargs: null,
2902
+ choices: ["auto", "always", "never"],
2903
+ const: null,
2904
+ help: "when to use colors: auto (default), always, or never",
2905
+ flags: ["--color"]
2906
+ }
2907
+ ],
2908
+ exclusive_groups: [],
2909
+ required_groups: []
2910
+ }
2911
+ ];
2912
+
2913
+ // src/parser.ts
2914
+ var completionShells = ["bash", "zsh", "fish"];
2915
+ var inventory = grammar_default.map((definition) => ({
2916
+ ...definition,
2917
+ command: definition.command.replace(/^tmuxp ?/, "")
2918
+ }));
2919
+ inventory.push({
2920
+ command: "completion",
2921
+ exclusive_groups: [],
2922
+ actions: [
2923
+ {
2924
+ dest: "shell",
2925
+ default: null,
2926
+ required: true,
2927
+ nargs: null,
2928
+ choices: [...completionShells],
2929
+ const: null,
2930
+ help: "Shell to complete in.",
2931
+ flags: []
2932
+ }
2933
+ ]
2934
+ });
2935
+ var fileValues = new Set([
2936
+ "workspace_file",
2937
+ "workspace_files",
2938
+ "socket_path",
2939
+ "tmux_config_file",
2940
+ "log_file",
2941
+ "save_to"
2942
+ ]);
2943
+ var descriptions = {
2944
+ "": "Manage tmux workspaces from YAML and JSON configuration.",
2945
+ load: "Load workspace files, attach to existing sessions, or append windows.",
2946
+ freeze: "Capture a live tmux session as a workspace document.",
2947
+ convert: "Convert a workspace between YAML and JSON.",
2948
+ edit: "Open a discovered workspace in your editor.",
2949
+ "debug-info": "Show runtime, configuration, and tmux diagnostics.",
2950
+ ls: "List project and saved workspace files.",
2951
+ search: "Search workspace names, sessions, windows, and pane commands.",
2952
+ shell: "Open the Python tmuxp shell with the selected tmux context.",
2953
+ import: "Import a teamocil or tmuxinator workspace.",
2954
+ "import teamocil": "Convert a teamocil workspace to tmuxp configuration.",
2955
+ "import tmuxinator": "Convert a tmuxinator workspace to tmuxp configuration.",
2956
+ completion: "Print a shell completion script."
2957
+ };
2958
+ function optionFor(item) {
2959
+ const flags = [...item.flags].sort((a, b) => a.length - b.length).join(", ");
2960
+ const option = new Option(flags + (item.nargs === 0 ? "" : ` <${item.dest}>`), item.help ?? "");
2961
+ if (item.choices)
2962
+ option.choices(item.choices);
2963
+ if (item.default !== null && item.default !== "==SUPPRESS==")
2964
+ option.default(item.default);
2965
+ if (item.dest === "field")
2966
+ option.argParser((value, previous) => [...previous ?? [], value]);
2967
+ if (item.dest === "panel_lines")
2968
+ option.argParser((value) => {
2969
+ if (!/^-?\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < -1) {
2970
+ throw new InvalidArgumentError("expected an integer at least -1");
2971
+ }
2972
+ return Number(value);
2973
+ });
2974
+ if (item.flags.includes("--no-startup"))
2975
+ option.description = "Do not load Python startup files.";
2976
+ if (item.flags.includes("--no-vi-mode"))
2977
+ option.description = "Disable vi editing mode.";
2978
+ if (item.dest === "quiet")
2979
+ option.description = "Suppress human status messages.";
2980
+ if (item.flags.includes("-8"))
2981
+ option.description = "Reject unsupported legacy 88-color mode before loading.";
2982
+ return option;
2983
+ }
2984
+ function createParser(io) {
2985
+ const root = new Command("tmux-workspace").enablePositionalOptions();
2986
+ const commands = new Map([["", root]]);
2987
+ const completionHints = new Map;
2988
+ const events = [];
2989
+ let request;
2990
+ const definitions = [...inventory].sort((a, b) => a.command.split(" ").filter(Boolean).length - b.command.split(" ").filter(Boolean).length);
2991
+ for (const spec of definitions) {
2992
+ const name = spec.command;
2993
+ const words = name.split(" ");
2994
+ let command = commands.get(name);
2995
+ if (!command) {
2996
+ const parent = commands.get(words.slice(0, -1).join(" "));
2997
+ command = parent.command(words.at(-1));
2998
+ commands.set(name, command);
2999
+ }
3000
+ const current = command;
3001
+ current.description(descriptions[name] ?? name).exitOverride().configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
3002
+ const options = [];
3003
+ for (const item of spec.actions) {
3004
+ if (item.dest === "help")
3005
+ continue;
3006
+ if (item.dest === "version") {
3007
+ current.version(`${current.name()} ${package_default.version}`, "-V, --version");
3008
+ continue;
3009
+ }
3010
+ if (!item.flags.length) {
3011
+ const required = item.required || spec.required_groups?.some((group) => group.includes(item.dest));
3012
+ const argument = item.nargs === "+" ? `<${item.dest}...>` : item.nargs === "*" ? `[${item.dest}...]` : item.nargs === "?" && !required ? `[${item.dest}]` : `<${item.dest}>`;
3013
+ const operand = new Argument(argument, item.help ?? "");
3014
+ if (item.choices)
3015
+ operand.choices(item.choices);
3016
+ current.addArgument(operand);
3017
+ if (fileValues.has(item.dest))
3018
+ completionHints.set(operand, "file");
3019
+ continue;
3020
+ }
3021
+ const option = optionFor(item);
3022
+ current.addOption(option);
3023
+ if (fileValues.has(item.dest))
3024
+ completionHints.set(option, "file");
3025
+ current.on(`option:${option.name()}`, () => events.push({
3026
+ scope: name,
3027
+ dest: item.dest,
3028
+ value: item.nargs === 0 ? item.const : current.getOptionValue(option.attributeName())
3029
+ }));
3030
+ options.push({ item, option });
3031
+ }
3032
+ for (const group of spec.exclusive_groups) {
3033
+ const members = options.filter(({ item }) => group.includes(item.dest)).map(({ option }) => option);
3034
+ for (const option of members)
3035
+ option.conflicts(members.filter((other) => other !== option).map((other) => other.attributeName()));
3036
+ }
3037
+ for (const [flag, dest, description] of [
3038
+ ["--json", "output_json", "Write JSON; machine operations never prompt."],
3039
+ ["--ndjson", "output_ndjson", "Stream NDJSON; takes precedence over --json."],
3040
+ [
3041
+ "--color <mode>",
3042
+ "color",
3043
+ "Human color: auto, always, or never. Machine output disables color."
3044
+ ]
3045
+ ]) {
3046
+ if (current.options.some((option2) => option2.long === flag.split(" ")[0]))
3047
+ continue;
3048
+ const option = new Option(flag, description);
3049
+ if (dest === "color")
3050
+ option.choices(["auto", "always", "never"]);
3051
+ current.addOption(option);
3052
+ current.on(`option:${option.name()}`, () => events.push({ scope: name, dest, value: current.getOptionValue(option.attributeName()) }));
3053
+ }
3054
+ if (["convert", "import teamocil", "import tmuxinator"].includes(name)) {
3055
+ for (const [flag, dest, description] of [
3056
+ ["--save-to <path>", "save_to", "Write to this destination instead of machine stdout."],
3057
+ ["--workspace-format <format>", "workspace_format", "Document format: yaml or json."],
3058
+ ["--force", "force", "Allow replacing an existing destination."]
3059
+ ]) {
3060
+ const option = new Option(flag, description);
3061
+ if (dest === "workspace_format")
3062
+ option.choices(["yaml", "json"]);
3063
+ current.addOption(option);
3064
+ if (dest === "save_to")
3065
+ completionHints.set(option, "file");
3066
+ current.on(`option:${option.name()}`, () => events.push({ scope: name, dest, value: current.getOptionValue(option.attributeName()) }));
3067
+ }
3068
+ }
3069
+ current.action(() => {
3070
+ const values = {};
3071
+ for (const definition of definitions.filter((item) => item.command === "" || item === spec)) {
3072
+ const node = commands.get(definition.command);
3073
+ let position = 0;
3074
+ for (const item of definition.actions) {
3075
+ if (["help", "version"].includes(item.dest))
3076
+ continue;
3077
+ if (!Object.hasOwn(values, item.dest))
3078
+ values[item.dest] = item.default;
3079
+ if (!item.flags.length)
3080
+ values[item.dest] = node.processedArgs[position++] ?? (item.nargs === "*" ? [] : null);
3081
+ }
3082
+ }
3083
+ for (const event of events) {
3084
+ if (!event.scope || event.scope === name || name.startsWith(event.scope + " "))
3085
+ values[event.dest] = event.value;
3086
+ }
3087
+ request = {
3088
+ command: name,
3089
+ values,
3090
+ mode: values.output_ndjson ? "ndjson" : values.output_json ? "json" : "human"
3091
+ };
3092
+ });
3093
+ }
3094
+ return {
3095
+ command: root,
3096
+ commands,
3097
+ completionHints,
3098
+ request: () => {
3099
+ if (!request)
3100
+ throw new Error("No command was parsed");
3101
+ return request;
3102
+ }
3103
+ };
3104
+ }
3105
+
3106
+ export { CommanderError, package_default, createParser };