@hasna/calendar 0.1.0

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