lifeos-cli 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.
Files changed (2) hide show
  1. package/dist/lifeos.mjs +3972 -0
  2. package/package.json +37 -0
@@ -0,0 +1,3972 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js
23
+ var require_error = __commonJS((exports) => {
24
+ class CommanderError extends Error {
25
+ constructor(exitCode, code, message) {
26
+ super(message);
27
+ Error.captureStackTrace(this, this.constructor);
28
+ this.name = this.constructor.name;
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.nestedError = undefined;
32
+ }
33
+ }
34
+
35
+ class InvalidArgumentError extends CommanderError {
36
+ constructor(message) {
37
+ super(1, "commander.invalidArgument", message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
40
+ }
41
+ }
42
+ exports.CommanderError = CommanderError;
43
+ exports.InvalidArgumentError = InvalidArgumentError;
44
+ });
45
+
46
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js
47
+ var require_argument = __commonJS((exports) => {
48
+ var { InvalidArgumentError } = require_error();
49
+
50
+ class Argument {
51
+ constructor(name, description) {
52
+ this.description = description || "";
53
+ this.variadic = false;
54
+ this.parseArg = undefined;
55
+ this.defaultValue = undefined;
56
+ this.defaultValueDescription = undefined;
57
+ this.argChoices = undefined;
58
+ switch (name[0]) {
59
+ case "<":
60
+ this.required = true;
61
+ this._name = name.slice(1, -1);
62
+ break;
63
+ case "[":
64
+ this.required = false;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ default:
68
+ this.required = true;
69
+ this._name = name;
70
+ break;
71
+ }
72
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
76
+ }
77
+ name() {
78
+ return this._name;
79
+ }
80
+ _concatValue(value, previous) {
81
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
82
+ return [value];
83
+ }
84
+ return previous.concat(value);
85
+ }
86
+ default(value, description) {
87
+ this.defaultValue = value;
88
+ this.defaultValueDescription = description;
89
+ return this;
90
+ }
91
+ argParser(fn) {
92
+ this.parseArg = fn;
93
+ return this;
94
+ }
95
+ choices(values) {
96
+ this.argChoices = values.slice();
97
+ this.parseArg = (arg, previous) => {
98
+ if (!this.argChoices.includes(arg)) {
99
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
100
+ }
101
+ if (this.variadic) {
102
+ return this._concatValue(arg, previous);
103
+ }
104
+ return arg;
105
+ };
106
+ return this;
107
+ }
108
+ argRequired() {
109
+ this.required = true;
110
+ return this;
111
+ }
112
+ argOptional() {
113
+ this.required = false;
114
+ return this;
115
+ }
116
+ }
117
+ function humanReadableArgName(arg) {
118
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
119
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
120
+ }
121
+ exports.Argument = Argument;
122
+ exports.humanReadableArgName = humanReadableArgName;
123
+ });
124
+
125
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js
126
+ var require_help = __commonJS((exports) => {
127
+ var { humanReadableArgName } = require_argument();
128
+
129
+ class Help {
130
+ constructor() {
131
+ this.helpWidth = undefined;
132
+ this.minWidthToWrap = 40;
133
+ this.sortSubcommands = false;
134
+ this.sortOptions = false;
135
+ this.showGlobalOptions = false;
136
+ }
137
+ prepareContext(contextOptions) {
138
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
139
+ }
140
+ visibleCommands(cmd) {
141
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
142
+ const helpCommand = cmd._getHelpCommand();
143
+ if (helpCommand && !helpCommand._hidden) {
144
+ visibleCommands.push(helpCommand);
145
+ }
146
+ if (this.sortSubcommands) {
147
+ visibleCommands.sort((a, b) => {
148
+ return a.name().localeCompare(b.name());
149
+ });
150
+ }
151
+ return visibleCommands;
152
+ }
153
+ compareOptions(a, b) {
154
+ const getSortKey = (option) => {
155
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
156
+ };
157
+ return getSortKey(a).localeCompare(getSortKey(b));
158
+ }
159
+ visibleOptions(cmd) {
160
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
161
+ const helpOption = cmd._getHelpOption();
162
+ if (helpOption && !helpOption.hidden) {
163
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
164
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
165
+ if (!removeShort && !removeLong) {
166
+ visibleOptions.push(helpOption);
167
+ } else if (helpOption.long && !removeLong) {
168
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
169
+ } else if (helpOption.short && !removeShort) {
170
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
171
+ }
172
+ }
173
+ if (this.sortOptions) {
174
+ visibleOptions.sort(this.compareOptions);
175
+ }
176
+ return visibleOptions;
177
+ }
178
+ visibleGlobalOptions(cmd) {
179
+ if (!this.showGlobalOptions)
180
+ return [];
181
+ const globalOptions = [];
182
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
183
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
184
+ globalOptions.push(...visibleOptions);
185
+ }
186
+ if (this.sortOptions) {
187
+ globalOptions.sort(this.compareOptions);
188
+ }
189
+ return globalOptions;
190
+ }
191
+ visibleArguments(cmd) {
192
+ if (cmd._argsDescription) {
193
+ cmd.registeredArguments.forEach((argument) => {
194
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
195
+ });
196
+ }
197
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
198
+ return cmd.registeredArguments;
199
+ }
200
+ return [];
201
+ }
202
+ subcommandTerm(cmd) {
203
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
204
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
205
+ }
206
+ optionTerm(option) {
207
+ return option.flags;
208
+ }
209
+ argumentTerm(argument) {
210
+ return argument.name();
211
+ }
212
+ longestSubcommandTermLength(cmd, helper) {
213
+ return helper.visibleCommands(cmd).reduce((max, command) => {
214
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
215
+ }, 0);
216
+ }
217
+ longestOptionTermLength(cmd, helper) {
218
+ return helper.visibleOptions(cmd).reduce((max, option) => {
219
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
220
+ }, 0);
221
+ }
222
+ longestGlobalOptionTermLength(cmd, helper) {
223
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
224
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
225
+ }, 0);
226
+ }
227
+ longestArgumentTermLength(cmd, helper) {
228
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
229
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
230
+ }, 0);
231
+ }
232
+ commandUsage(cmd) {
233
+ let cmdName = cmd._name;
234
+ if (cmd._aliases[0]) {
235
+ cmdName = cmdName + "|" + cmd._aliases[0];
236
+ }
237
+ let ancestorCmdNames = "";
238
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
239
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
240
+ }
241
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
242
+ }
243
+ commandDescription(cmd) {
244
+ return cmd.description();
245
+ }
246
+ subcommandDescription(cmd) {
247
+ return cmd.summary() || cmd.description();
248
+ }
249
+ optionDescription(option) {
250
+ const extraInfo = [];
251
+ if (option.argChoices) {
252
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
253
+ }
254
+ if (option.defaultValue !== undefined) {
255
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
256
+ if (showDefault) {
257
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
258
+ }
259
+ }
260
+ if (option.presetArg !== undefined && option.optional) {
261
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
262
+ }
263
+ if (option.envVar !== undefined) {
264
+ extraInfo.push(`env: ${option.envVar}`);
265
+ }
266
+ if (extraInfo.length > 0) {
267
+ return `${option.description} (${extraInfo.join(", ")})`;
268
+ }
269
+ return option.description;
270
+ }
271
+ argumentDescription(argument) {
272
+ const extraInfo = [];
273
+ if (argument.argChoices) {
274
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
275
+ }
276
+ if (argument.defaultValue !== undefined) {
277
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
278
+ }
279
+ if (extraInfo.length > 0) {
280
+ const extraDescription = `(${extraInfo.join(", ")})`;
281
+ if (argument.description) {
282
+ return `${argument.description} ${extraDescription}`;
283
+ }
284
+ return extraDescription;
285
+ }
286
+ return argument.description;
287
+ }
288
+ formatHelp(cmd, helper) {
289
+ const termWidth = helper.padWidth(cmd, helper);
290
+ const helpWidth = helper.helpWidth ?? 80;
291
+ function callFormatItem(term, description) {
292
+ return helper.formatItem(term, termWidth, description, helper);
293
+ }
294
+ let output = [
295
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
296
+ ""
297
+ ];
298
+ const commandDescription = helper.commandDescription(cmd);
299
+ if (commandDescription.length > 0) {
300
+ output = output.concat([
301
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
302
+ ""
303
+ ]);
304
+ }
305
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
306
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
307
+ });
308
+ if (argumentList.length > 0) {
309
+ output = output.concat([
310
+ helper.styleTitle("Arguments:"),
311
+ ...argumentList,
312
+ ""
313
+ ]);
314
+ }
315
+ const optionList = helper.visibleOptions(cmd).map((option) => {
316
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
317
+ });
318
+ if (optionList.length > 0) {
319
+ output = output.concat([
320
+ helper.styleTitle("Options:"),
321
+ ...optionList,
322
+ ""
323
+ ]);
324
+ }
325
+ if (helper.showGlobalOptions) {
326
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
327
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
328
+ });
329
+ if (globalOptionList.length > 0) {
330
+ output = output.concat([
331
+ helper.styleTitle("Global Options:"),
332
+ ...globalOptionList,
333
+ ""
334
+ ]);
335
+ }
336
+ }
337
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
338
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)), helper.styleSubcommandDescription(helper.subcommandDescription(cmd2)));
339
+ });
340
+ if (commandList.length > 0) {
341
+ output = output.concat([
342
+ helper.styleTitle("Commands:"),
343
+ ...commandList,
344
+ ""
345
+ ]);
346
+ }
347
+ return output.join(`
348
+ `);
349
+ }
350
+ displayWidth(str) {
351
+ return stripColor(str).length;
352
+ }
353
+ styleTitle(str) {
354
+ return str;
355
+ }
356
+ styleUsage(str) {
357
+ return str.split(" ").map((word) => {
358
+ if (word === "[options]")
359
+ return this.styleOptionText(word);
360
+ if (word === "[command]")
361
+ return this.styleSubcommandText(word);
362
+ if (word[0] === "[" || word[0] === "<")
363
+ return this.styleArgumentText(word);
364
+ return this.styleCommandText(word);
365
+ }).join(" ");
366
+ }
367
+ styleCommandDescription(str) {
368
+ return this.styleDescriptionText(str);
369
+ }
370
+ styleOptionDescription(str) {
371
+ return this.styleDescriptionText(str);
372
+ }
373
+ styleSubcommandDescription(str) {
374
+ return this.styleDescriptionText(str);
375
+ }
376
+ styleArgumentDescription(str) {
377
+ return this.styleDescriptionText(str);
378
+ }
379
+ styleDescriptionText(str) {
380
+ return str;
381
+ }
382
+ styleOptionTerm(str) {
383
+ return this.styleOptionText(str);
384
+ }
385
+ styleSubcommandTerm(str) {
386
+ return str.split(" ").map((word) => {
387
+ if (word === "[options]")
388
+ return this.styleOptionText(word);
389
+ if (word[0] === "[" || word[0] === "<")
390
+ return this.styleArgumentText(word);
391
+ return this.styleSubcommandText(word);
392
+ }).join(" ");
393
+ }
394
+ styleArgumentTerm(str) {
395
+ return this.styleArgumentText(str);
396
+ }
397
+ styleOptionText(str) {
398
+ return str;
399
+ }
400
+ styleArgumentText(str) {
401
+ return str;
402
+ }
403
+ styleSubcommandText(str) {
404
+ return str;
405
+ }
406
+ styleCommandText(str) {
407
+ return str;
408
+ }
409
+ padWidth(cmd, helper) {
410
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
411
+ }
412
+ preformatted(str) {
413
+ return /\n[^\S\r\n]/.test(str);
414
+ }
415
+ formatItem(term, termWidth, description, helper) {
416
+ const itemIndent = 2;
417
+ const itemIndentStr = " ".repeat(itemIndent);
418
+ if (!description)
419
+ return itemIndentStr + term;
420
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
421
+ const spacerWidth = 2;
422
+ const helpWidth = this.helpWidth ?? 80;
423
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
424
+ let formattedDescription;
425
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
426
+ formattedDescription = description;
427
+ } else {
428
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
429
+ formattedDescription = wrappedDescription.replace(/\n/g, `
430
+ ` + " ".repeat(termWidth + spacerWidth));
431
+ }
432
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
433
+ ${itemIndentStr}`);
434
+ }
435
+ boxWrap(str, width) {
436
+ if (width < this.minWidthToWrap)
437
+ return str;
438
+ const rawLines = str.split(/\r\n|\n/);
439
+ const chunkPattern = /[\s]*[^\s]+/g;
440
+ const wrappedLines = [];
441
+ rawLines.forEach((line) => {
442
+ const chunks = line.match(chunkPattern);
443
+ if (chunks === null) {
444
+ wrappedLines.push("");
445
+ return;
446
+ }
447
+ let sumChunks = [chunks.shift()];
448
+ let sumWidth = this.displayWidth(sumChunks[0]);
449
+ chunks.forEach((chunk) => {
450
+ const visibleWidth = this.displayWidth(chunk);
451
+ if (sumWidth + visibleWidth <= width) {
452
+ sumChunks.push(chunk);
453
+ sumWidth += visibleWidth;
454
+ return;
455
+ }
456
+ wrappedLines.push(sumChunks.join(""));
457
+ const nextChunk = chunk.trimStart();
458
+ sumChunks = [nextChunk];
459
+ sumWidth = this.displayWidth(nextChunk);
460
+ });
461
+ wrappedLines.push(sumChunks.join(""));
462
+ });
463
+ return wrappedLines.join(`
464
+ `);
465
+ }
466
+ }
467
+ function stripColor(str) {
468
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
469
+ return str.replace(sgrPattern, "");
470
+ }
471
+ exports.Help = Help;
472
+ exports.stripColor = stripColor;
473
+ });
474
+
475
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js
476
+ var require_option = __commonJS((exports) => {
477
+ var { InvalidArgumentError } = require_error();
478
+
479
+ class Option {
480
+ constructor(flags, description) {
481
+ this.flags = flags;
482
+ this.description = description || "";
483
+ this.required = flags.includes("<");
484
+ this.optional = flags.includes("[");
485
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
486
+ this.mandatory = false;
487
+ const optionFlags = splitOptionFlags(flags);
488
+ this.short = optionFlags.shortFlag;
489
+ this.long = optionFlags.longFlag;
490
+ this.negate = false;
491
+ if (this.long) {
492
+ this.negate = this.long.startsWith("--no-");
493
+ }
494
+ this.defaultValue = undefined;
495
+ this.defaultValueDescription = undefined;
496
+ this.presetArg = undefined;
497
+ this.envVar = undefined;
498
+ this.parseArg = undefined;
499
+ this.hidden = false;
500
+ this.argChoices = undefined;
501
+ this.conflictsWith = [];
502
+ this.implied = undefined;
503
+ }
504
+ default(value, description) {
505
+ this.defaultValue = value;
506
+ this.defaultValueDescription = description;
507
+ return this;
508
+ }
509
+ preset(arg) {
510
+ this.presetArg = arg;
511
+ return this;
512
+ }
513
+ conflicts(names) {
514
+ this.conflictsWith = this.conflictsWith.concat(names);
515
+ return this;
516
+ }
517
+ implies(impliedOptionValues) {
518
+ let newImplied = impliedOptionValues;
519
+ if (typeof impliedOptionValues === "string") {
520
+ newImplied = { [impliedOptionValues]: true };
521
+ }
522
+ this.implied = Object.assign(this.implied || {}, newImplied);
523
+ return this;
524
+ }
525
+ env(name) {
526
+ this.envVar = name;
527
+ return this;
528
+ }
529
+ argParser(fn) {
530
+ this.parseArg = fn;
531
+ return this;
532
+ }
533
+ makeOptionMandatory(mandatory = true) {
534
+ this.mandatory = !!mandatory;
535
+ return this;
536
+ }
537
+ hideHelp(hide = true) {
538
+ this.hidden = !!hide;
539
+ return this;
540
+ }
541
+ _concatValue(value, previous) {
542
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
543
+ return [value];
544
+ }
545
+ return previous.concat(value);
546
+ }
547
+ choices(values) {
548
+ this.argChoices = values.slice();
549
+ this.parseArg = (arg, previous) => {
550
+ if (!this.argChoices.includes(arg)) {
551
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
552
+ }
553
+ if (this.variadic) {
554
+ return this._concatValue(arg, previous);
555
+ }
556
+ return arg;
557
+ };
558
+ return this;
559
+ }
560
+ name() {
561
+ if (this.long) {
562
+ return this.long.replace(/^--/, "");
563
+ }
564
+ return this.short.replace(/^-/, "");
565
+ }
566
+ attributeName() {
567
+ if (this.negate) {
568
+ return camelcase(this.name().replace(/^no-/, ""));
569
+ }
570
+ return camelcase(this.name());
571
+ }
572
+ is(arg) {
573
+ return this.short === arg || this.long === arg;
574
+ }
575
+ isBoolean() {
576
+ return !this.required && !this.optional && !this.negate;
577
+ }
578
+ }
579
+
580
+ class DualOptions {
581
+ constructor(options) {
582
+ this.positiveOptions = new Map;
583
+ this.negativeOptions = new Map;
584
+ this.dualOptions = new Set;
585
+ options.forEach((option) => {
586
+ if (option.negate) {
587
+ this.negativeOptions.set(option.attributeName(), option);
588
+ } else {
589
+ this.positiveOptions.set(option.attributeName(), option);
590
+ }
591
+ });
592
+ this.negativeOptions.forEach((value, key) => {
593
+ if (this.positiveOptions.has(key)) {
594
+ this.dualOptions.add(key);
595
+ }
596
+ });
597
+ }
598
+ valueFromOption(value, option) {
599
+ const optionKey = option.attributeName();
600
+ if (!this.dualOptions.has(optionKey))
601
+ return true;
602
+ const preset = this.negativeOptions.get(optionKey).presetArg;
603
+ const negativeValue = preset !== undefined ? preset : false;
604
+ return option.negate === (negativeValue === value);
605
+ }
606
+ }
607
+ function camelcase(str) {
608
+ return str.split("-").reduce((str2, word) => {
609
+ return str2 + word[0].toUpperCase() + word.slice(1);
610
+ });
611
+ }
612
+ function splitOptionFlags(flags) {
613
+ let shortFlag;
614
+ let longFlag;
615
+ const shortFlagExp = /^-[^-]$/;
616
+ const longFlagExp = /^--[^-]/;
617
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
618
+ if (shortFlagExp.test(flagParts[0]))
619
+ shortFlag = flagParts.shift();
620
+ if (longFlagExp.test(flagParts[0]))
621
+ longFlag = flagParts.shift();
622
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
623
+ shortFlag = flagParts.shift();
624
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
625
+ shortFlag = longFlag;
626
+ longFlag = flagParts.shift();
627
+ }
628
+ if (flagParts[0].startsWith("-")) {
629
+ const unsupportedFlag = flagParts[0];
630
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
631
+ if (/^-[^-][^-]/.test(unsupportedFlag))
632
+ throw new Error(`${baseError}
633
+ - a short flag is a single dash and a single character
634
+ - either use a single dash and a single character (for a short flag)
635
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
636
+ if (shortFlagExp.test(unsupportedFlag))
637
+ throw new Error(`${baseError}
638
+ - too many short flags`);
639
+ if (longFlagExp.test(unsupportedFlag))
640
+ throw new Error(`${baseError}
641
+ - too many long flags`);
642
+ throw new Error(`${baseError}
643
+ - unrecognised flag format`);
644
+ }
645
+ if (shortFlag === undefined && longFlag === undefined)
646
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
647
+ return { shortFlag, longFlag };
648
+ }
649
+ exports.Option = Option;
650
+ exports.DualOptions = DualOptions;
651
+ });
652
+
653
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js
654
+ var require_suggestSimilar = __commonJS((exports) => {
655
+ var maxDistance = 3;
656
+ function editDistance(a, b) {
657
+ if (Math.abs(a.length - b.length) > maxDistance)
658
+ return Math.max(a.length, b.length);
659
+ const d = [];
660
+ for (let i = 0;i <= a.length; i++) {
661
+ d[i] = [i];
662
+ }
663
+ for (let j = 0;j <= b.length; j++) {
664
+ d[0][j] = j;
665
+ }
666
+ for (let j = 1;j <= b.length; j++) {
667
+ for (let i = 1;i <= a.length; i++) {
668
+ let cost = 1;
669
+ if (a[i - 1] === b[j - 1]) {
670
+ cost = 0;
671
+ } else {
672
+ cost = 1;
673
+ }
674
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
675
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
676
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
677
+ }
678
+ }
679
+ }
680
+ return d[a.length][b.length];
681
+ }
682
+ function suggestSimilar(word, candidates) {
683
+ if (!candidates || candidates.length === 0)
684
+ return "";
685
+ candidates = Array.from(new Set(candidates));
686
+ const searchingOptions = word.startsWith("--");
687
+ if (searchingOptions) {
688
+ word = word.slice(2);
689
+ candidates = candidates.map((candidate) => candidate.slice(2));
690
+ }
691
+ let similar = [];
692
+ let bestDistance = maxDistance;
693
+ const minSimilarity = 0.4;
694
+ candidates.forEach((candidate) => {
695
+ if (candidate.length <= 1)
696
+ return;
697
+ const distance = editDistance(word, candidate);
698
+ const length = Math.max(word.length, candidate.length);
699
+ const similarity = (length - distance) / length;
700
+ if (similarity > minSimilarity) {
701
+ if (distance < bestDistance) {
702
+ bestDistance = distance;
703
+ similar = [candidate];
704
+ } else if (distance === bestDistance) {
705
+ similar.push(candidate);
706
+ }
707
+ }
708
+ });
709
+ similar.sort((a, b) => a.localeCompare(b));
710
+ if (searchingOptions) {
711
+ similar = similar.map((candidate) => `--${candidate}`);
712
+ }
713
+ if (similar.length > 1) {
714
+ return `
715
+ (Did you mean one of ${similar.join(", ")}?)`;
716
+ }
717
+ if (similar.length === 1) {
718
+ return `
719
+ (Did you mean ${similar[0]}?)`;
720
+ }
721
+ return "";
722
+ }
723
+ exports.suggestSimilar = suggestSimilar;
724
+ });
725
+
726
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js
727
+ var require_command = __commonJS((exports) => {
728
+ var EventEmitter = __require("node:events").EventEmitter;
729
+ var childProcess = __require("node:child_process");
730
+ var path = __require("node:path");
731
+ var fs = __require("node:fs");
732
+ var process2 = __require("node:process");
733
+ var { Argument, humanReadableArgName } = require_argument();
734
+ var { CommanderError } = require_error();
735
+ var { Help, stripColor } = require_help();
736
+ var { Option, DualOptions } = require_option();
737
+ var { suggestSimilar } = require_suggestSimilar();
738
+
739
+ class Command extends EventEmitter {
740
+ constructor(name) {
741
+ super();
742
+ this.commands = [];
743
+ this.options = [];
744
+ this.parent = null;
745
+ this._allowUnknownOption = false;
746
+ this._allowExcessArguments = false;
747
+ this.registeredArguments = [];
748
+ this._args = this.registeredArguments;
749
+ this.args = [];
750
+ this.rawArgs = [];
751
+ this.processedArgs = [];
752
+ this._scriptPath = null;
753
+ this._name = name || "";
754
+ this._optionValues = {};
755
+ this._optionValueSources = {};
756
+ this._storeOptionsAsProperties = false;
757
+ this._actionHandler = null;
758
+ this._executableHandler = false;
759
+ this._executableFile = null;
760
+ this._executableDir = null;
761
+ this._defaultCommandName = null;
762
+ this._exitCallback = null;
763
+ this._aliases = [];
764
+ this._combineFlagAndOptionalValue = true;
765
+ this._description = "";
766
+ this._summary = "";
767
+ this._argsDescription = undefined;
768
+ this._enablePositionalOptions = false;
769
+ this._passThroughOptions = false;
770
+ this._lifeCycleHooks = {};
771
+ this._showHelpAfterError = false;
772
+ this._showSuggestionAfterError = true;
773
+ this._savedState = null;
774
+ this._outputConfiguration = {
775
+ writeOut: (str) => process2.stdout.write(str),
776
+ writeErr: (str) => process2.stderr.write(str),
777
+ outputError: (str, write) => write(str),
778
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
779
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
780
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
781
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
782
+ stripColor: (str) => stripColor(str)
783
+ };
784
+ this._hidden = false;
785
+ this._helpOption = undefined;
786
+ this._addImplicitHelpCommand = undefined;
787
+ this._helpCommand = undefined;
788
+ this._helpConfiguration = {};
789
+ }
790
+ copyInheritedSettings(sourceCommand) {
791
+ this._outputConfiguration = sourceCommand._outputConfiguration;
792
+ this._helpOption = sourceCommand._helpOption;
793
+ this._helpCommand = sourceCommand._helpCommand;
794
+ this._helpConfiguration = sourceCommand._helpConfiguration;
795
+ this._exitCallback = sourceCommand._exitCallback;
796
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
797
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
798
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
799
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
800
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
801
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
802
+ return this;
803
+ }
804
+ _getCommandAndAncestors() {
805
+ const result = [];
806
+ for (let command = this;command; command = command.parent) {
807
+ result.push(command);
808
+ }
809
+ return result;
810
+ }
811
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
812
+ let desc = actionOptsOrExecDesc;
813
+ let opts = execOpts;
814
+ if (typeof desc === "object" && desc !== null) {
815
+ opts = desc;
816
+ desc = null;
817
+ }
818
+ opts = opts || {};
819
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
820
+ const cmd = this.createCommand(name);
821
+ if (desc) {
822
+ cmd.description(desc);
823
+ cmd._executableHandler = true;
824
+ }
825
+ if (opts.isDefault)
826
+ this._defaultCommandName = cmd._name;
827
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
828
+ cmd._executableFile = opts.executableFile || null;
829
+ if (args)
830
+ cmd.arguments(args);
831
+ this._registerCommand(cmd);
832
+ cmd.parent = this;
833
+ cmd.copyInheritedSettings(this);
834
+ if (desc)
835
+ return this;
836
+ return cmd;
837
+ }
838
+ createCommand(name) {
839
+ return new Command(name);
840
+ }
841
+ createHelp() {
842
+ return Object.assign(new Help, this.configureHelp());
843
+ }
844
+ configureHelp(configuration) {
845
+ if (configuration === undefined)
846
+ return this._helpConfiguration;
847
+ this._helpConfiguration = configuration;
848
+ return this;
849
+ }
850
+ configureOutput(configuration) {
851
+ if (configuration === undefined)
852
+ return this._outputConfiguration;
853
+ Object.assign(this._outputConfiguration, configuration);
854
+ return this;
855
+ }
856
+ showHelpAfterError(displayHelp = true) {
857
+ if (typeof displayHelp !== "string")
858
+ displayHelp = !!displayHelp;
859
+ this._showHelpAfterError = displayHelp;
860
+ return this;
861
+ }
862
+ showSuggestionAfterError(displaySuggestion = true) {
863
+ this._showSuggestionAfterError = !!displaySuggestion;
864
+ return this;
865
+ }
866
+ addCommand(cmd, opts) {
867
+ if (!cmd._name) {
868
+ throw new Error(`Command passed to .addCommand() must have a name
869
+ - specify the name in Command constructor or using .name()`);
870
+ }
871
+ opts = opts || {};
872
+ if (opts.isDefault)
873
+ this._defaultCommandName = cmd._name;
874
+ if (opts.noHelp || opts.hidden)
875
+ cmd._hidden = true;
876
+ this._registerCommand(cmd);
877
+ cmd.parent = this;
878
+ cmd._checkForBrokenPassThrough();
879
+ return this;
880
+ }
881
+ createArgument(name, description) {
882
+ return new Argument(name, description);
883
+ }
884
+ argument(name, description, fn, defaultValue) {
885
+ const argument = this.createArgument(name, description);
886
+ if (typeof fn === "function") {
887
+ argument.default(defaultValue).argParser(fn);
888
+ } else {
889
+ argument.default(fn);
890
+ }
891
+ this.addArgument(argument);
892
+ return this;
893
+ }
894
+ arguments(names) {
895
+ names.trim().split(/ +/).forEach((detail) => {
896
+ this.argument(detail);
897
+ });
898
+ return this;
899
+ }
900
+ addArgument(argument) {
901
+ const previousArgument = this.registeredArguments.slice(-1)[0];
902
+ if (previousArgument && previousArgument.variadic) {
903
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
904
+ }
905
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
906
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
907
+ }
908
+ this.registeredArguments.push(argument);
909
+ return this;
910
+ }
911
+ helpCommand(enableOrNameAndArgs, description) {
912
+ if (typeof enableOrNameAndArgs === "boolean") {
913
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
914
+ return this;
915
+ }
916
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
917
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
918
+ const helpDescription = description ?? "display help for command";
919
+ const helpCommand = this.createCommand(helpName);
920
+ helpCommand.helpOption(false);
921
+ if (helpArgs)
922
+ helpCommand.arguments(helpArgs);
923
+ if (helpDescription)
924
+ helpCommand.description(helpDescription);
925
+ this._addImplicitHelpCommand = true;
926
+ this._helpCommand = helpCommand;
927
+ return this;
928
+ }
929
+ addHelpCommand(helpCommand, deprecatedDescription) {
930
+ if (typeof helpCommand !== "object") {
931
+ this.helpCommand(helpCommand, deprecatedDescription);
932
+ return this;
933
+ }
934
+ this._addImplicitHelpCommand = true;
935
+ this._helpCommand = helpCommand;
936
+ return this;
937
+ }
938
+ _getHelpCommand() {
939
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
940
+ if (hasImplicitHelpCommand) {
941
+ if (this._helpCommand === undefined) {
942
+ this.helpCommand(undefined, undefined);
943
+ }
944
+ return this._helpCommand;
945
+ }
946
+ return null;
947
+ }
948
+ hook(event, listener) {
949
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
950
+ if (!allowedValues.includes(event)) {
951
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
952
+ Expecting one of '${allowedValues.join("', '")}'`);
953
+ }
954
+ if (this._lifeCycleHooks[event]) {
955
+ this._lifeCycleHooks[event].push(listener);
956
+ } else {
957
+ this._lifeCycleHooks[event] = [listener];
958
+ }
959
+ return this;
960
+ }
961
+ exitOverride(fn) {
962
+ if (fn) {
963
+ this._exitCallback = fn;
964
+ } else {
965
+ this._exitCallback = (err) => {
966
+ if (err.code !== "commander.executeSubCommandAsync") {
967
+ throw err;
968
+ } else {}
969
+ };
970
+ }
971
+ return this;
972
+ }
973
+ _exit(exitCode, code, message) {
974
+ if (this._exitCallback) {
975
+ this._exitCallback(new CommanderError(exitCode, code, message));
976
+ }
977
+ process2.exit(exitCode);
978
+ }
979
+ action(fn) {
980
+ const listener = (args) => {
981
+ const expectedArgsCount = this.registeredArguments.length;
982
+ const actionArgs = args.slice(0, expectedArgsCount);
983
+ if (this._storeOptionsAsProperties) {
984
+ actionArgs[expectedArgsCount] = this;
985
+ } else {
986
+ actionArgs[expectedArgsCount] = this.opts();
987
+ }
988
+ actionArgs.push(this);
989
+ return fn.apply(this, actionArgs);
990
+ };
991
+ this._actionHandler = listener;
992
+ return this;
993
+ }
994
+ createOption(flags, description) {
995
+ return new Option(flags, description);
996
+ }
997
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
998
+ try {
999
+ return target.parseArg(value, previous);
1000
+ } catch (err) {
1001
+ if (err.code === "commander.invalidArgument") {
1002
+ const message = `${invalidArgumentMessage} ${err.message}`;
1003
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1004
+ }
1005
+ throw err;
1006
+ }
1007
+ }
1008
+ _registerOption(option) {
1009
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1010
+ if (matchingOption) {
1011
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1012
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1013
+ - already used by option '${matchingOption.flags}'`);
1014
+ }
1015
+ this.options.push(option);
1016
+ }
1017
+ _registerCommand(command) {
1018
+ const knownBy = (cmd) => {
1019
+ return [cmd.name()].concat(cmd.aliases());
1020
+ };
1021
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1022
+ if (alreadyUsed) {
1023
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1024
+ const newCmd = knownBy(command).join("|");
1025
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1026
+ }
1027
+ this.commands.push(command);
1028
+ }
1029
+ addOption(option) {
1030
+ this._registerOption(option);
1031
+ const oname = option.name();
1032
+ const name = option.attributeName();
1033
+ if (option.negate) {
1034
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1035
+ if (!this._findOption(positiveLongFlag)) {
1036
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1037
+ }
1038
+ } else if (option.defaultValue !== undefined) {
1039
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1040
+ }
1041
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1042
+ if (val == null && option.presetArg !== undefined) {
1043
+ val = option.presetArg;
1044
+ }
1045
+ const oldValue = this.getOptionValue(name);
1046
+ if (val !== null && option.parseArg) {
1047
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1048
+ } else if (val !== null && option.variadic) {
1049
+ val = option._concatValue(val, oldValue);
1050
+ }
1051
+ if (val == null) {
1052
+ if (option.negate) {
1053
+ val = false;
1054
+ } else if (option.isBoolean() || option.optional) {
1055
+ val = true;
1056
+ } else {
1057
+ val = "";
1058
+ }
1059
+ }
1060
+ this.setOptionValueWithSource(name, val, valueSource);
1061
+ };
1062
+ this.on("option:" + oname, (val) => {
1063
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1064
+ handleOptionValue(val, invalidValueMessage, "cli");
1065
+ });
1066
+ if (option.envVar) {
1067
+ this.on("optionEnv:" + oname, (val) => {
1068
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1069
+ handleOptionValue(val, invalidValueMessage, "env");
1070
+ });
1071
+ }
1072
+ return this;
1073
+ }
1074
+ _optionEx(config, flags, description, fn, defaultValue) {
1075
+ if (typeof flags === "object" && flags instanceof Option) {
1076
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1077
+ }
1078
+ const option = this.createOption(flags, description);
1079
+ option.makeOptionMandatory(!!config.mandatory);
1080
+ if (typeof fn === "function") {
1081
+ option.default(defaultValue).argParser(fn);
1082
+ } else if (fn instanceof RegExp) {
1083
+ const regex = fn;
1084
+ fn = (val, def) => {
1085
+ const m = regex.exec(val);
1086
+ return m ? m[0] : def;
1087
+ };
1088
+ option.default(defaultValue).argParser(fn);
1089
+ } else {
1090
+ option.default(fn);
1091
+ }
1092
+ return this.addOption(option);
1093
+ }
1094
+ option(flags, description, parseArg, defaultValue) {
1095
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1096
+ }
1097
+ requiredOption(flags, description, parseArg, defaultValue) {
1098
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1099
+ }
1100
+ combineFlagAndOptionalValue(combine = true) {
1101
+ this._combineFlagAndOptionalValue = !!combine;
1102
+ return this;
1103
+ }
1104
+ allowUnknownOption(allowUnknown = true) {
1105
+ this._allowUnknownOption = !!allowUnknown;
1106
+ return this;
1107
+ }
1108
+ allowExcessArguments(allowExcess = true) {
1109
+ this._allowExcessArguments = !!allowExcess;
1110
+ return this;
1111
+ }
1112
+ enablePositionalOptions(positional = true) {
1113
+ this._enablePositionalOptions = !!positional;
1114
+ return this;
1115
+ }
1116
+ passThroughOptions(passThrough = true) {
1117
+ this._passThroughOptions = !!passThrough;
1118
+ this._checkForBrokenPassThrough();
1119
+ return this;
1120
+ }
1121
+ _checkForBrokenPassThrough() {
1122
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1123
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1124
+ }
1125
+ }
1126
+ storeOptionsAsProperties(storeAsProperties = true) {
1127
+ if (this.options.length) {
1128
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1129
+ }
1130
+ if (Object.keys(this._optionValues).length) {
1131
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1132
+ }
1133
+ this._storeOptionsAsProperties = !!storeAsProperties;
1134
+ return this;
1135
+ }
1136
+ getOptionValue(key) {
1137
+ if (this._storeOptionsAsProperties) {
1138
+ return this[key];
1139
+ }
1140
+ return this._optionValues[key];
1141
+ }
1142
+ setOptionValue(key, value) {
1143
+ return this.setOptionValueWithSource(key, value, undefined);
1144
+ }
1145
+ setOptionValueWithSource(key, value, source) {
1146
+ if (this._storeOptionsAsProperties) {
1147
+ this[key] = value;
1148
+ } else {
1149
+ this._optionValues[key] = value;
1150
+ }
1151
+ this._optionValueSources[key] = source;
1152
+ return this;
1153
+ }
1154
+ getOptionValueSource(key) {
1155
+ return this._optionValueSources[key];
1156
+ }
1157
+ getOptionValueSourceWithGlobals(key) {
1158
+ let source;
1159
+ this._getCommandAndAncestors().forEach((cmd) => {
1160
+ if (cmd.getOptionValueSource(key) !== undefined) {
1161
+ source = cmd.getOptionValueSource(key);
1162
+ }
1163
+ });
1164
+ return source;
1165
+ }
1166
+ _prepareUserArgs(argv, parseOptions) {
1167
+ if (argv !== undefined && !Array.isArray(argv)) {
1168
+ throw new Error("first parameter to parse must be array or undefined");
1169
+ }
1170
+ parseOptions = parseOptions || {};
1171
+ if (argv === undefined && parseOptions.from === undefined) {
1172
+ if (process2.versions?.electron) {
1173
+ parseOptions.from = "electron";
1174
+ }
1175
+ const execArgv = process2.execArgv ?? [];
1176
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1177
+ parseOptions.from = "eval";
1178
+ }
1179
+ }
1180
+ if (argv === undefined) {
1181
+ argv = process2.argv;
1182
+ }
1183
+ this.rawArgs = argv.slice();
1184
+ let userArgs;
1185
+ switch (parseOptions.from) {
1186
+ case undefined:
1187
+ case "node":
1188
+ this._scriptPath = argv[1];
1189
+ userArgs = argv.slice(2);
1190
+ break;
1191
+ case "electron":
1192
+ if (process2.defaultApp) {
1193
+ this._scriptPath = argv[1];
1194
+ userArgs = argv.slice(2);
1195
+ } else {
1196
+ userArgs = argv.slice(1);
1197
+ }
1198
+ break;
1199
+ case "user":
1200
+ userArgs = argv.slice(0);
1201
+ break;
1202
+ case "eval":
1203
+ userArgs = argv.slice(1);
1204
+ break;
1205
+ default:
1206
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1207
+ }
1208
+ if (!this._name && this._scriptPath)
1209
+ this.nameFromFilename(this._scriptPath);
1210
+ this._name = this._name || "program";
1211
+ return userArgs;
1212
+ }
1213
+ parse(argv, parseOptions) {
1214
+ this._prepareForParse();
1215
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1216
+ this._parseCommand([], userArgs);
1217
+ return this;
1218
+ }
1219
+ async parseAsync(argv, parseOptions) {
1220
+ this._prepareForParse();
1221
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1222
+ await this._parseCommand([], userArgs);
1223
+ return this;
1224
+ }
1225
+ _prepareForParse() {
1226
+ if (this._savedState === null) {
1227
+ this.saveStateBeforeParse();
1228
+ } else {
1229
+ this.restoreStateBeforeParse();
1230
+ }
1231
+ }
1232
+ saveStateBeforeParse() {
1233
+ this._savedState = {
1234
+ _name: this._name,
1235
+ _optionValues: { ...this._optionValues },
1236
+ _optionValueSources: { ...this._optionValueSources }
1237
+ };
1238
+ }
1239
+ restoreStateBeforeParse() {
1240
+ if (this._storeOptionsAsProperties)
1241
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1242
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1243
+ this._name = this._savedState._name;
1244
+ this._scriptPath = null;
1245
+ this.rawArgs = [];
1246
+ this._optionValues = { ...this._savedState._optionValues };
1247
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1248
+ this.args = [];
1249
+ this.processedArgs = [];
1250
+ }
1251
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1252
+ if (fs.existsSync(executableFile))
1253
+ return;
1254
+ 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";
1255
+ const executableMissing = `'${executableFile}' does not exist
1256
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1257
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1258
+ - ${executableDirMessage}`;
1259
+ throw new Error(executableMissing);
1260
+ }
1261
+ _executeSubCommand(subcommand, args) {
1262
+ args = args.slice();
1263
+ let launchWithNode = false;
1264
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1265
+ function findFile(baseDir, baseName) {
1266
+ const localBin = path.resolve(baseDir, baseName);
1267
+ if (fs.existsSync(localBin))
1268
+ return localBin;
1269
+ if (sourceExt.includes(path.extname(baseName)))
1270
+ return;
1271
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1272
+ if (foundExt)
1273
+ return `${localBin}${foundExt}`;
1274
+ return;
1275
+ }
1276
+ this._checkForMissingMandatoryOptions();
1277
+ this._checkForConflictingOptions();
1278
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1279
+ let executableDir = this._executableDir || "";
1280
+ if (this._scriptPath) {
1281
+ let resolvedScriptPath;
1282
+ try {
1283
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1284
+ } catch {
1285
+ resolvedScriptPath = this._scriptPath;
1286
+ }
1287
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1288
+ }
1289
+ if (executableDir) {
1290
+ let localFile = findFile(executableDir, executableFile);
1291
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1292
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1293
+ if (legacyName !== this._name) {
1294
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1295
+ }
1296
+ }
1297
+ executableFile = localFile || executableFile;
1298
+ }
1299
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1300
+ let proc;
1301
+ if (process2.platform !== "win32") {
1302
+ if (launchWithNode) {
1303
+ args.unshift(executableFile);
1304
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1305
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1306
+ } else {
1307
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1308
+ }
1309
+ } else {
1310
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1311
+ args.unshift(executableFile);
1312
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1313
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1314
+ }
1315
+ if (!proc.killed) {
1316
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1317
+ signals.forEach((signal) => {
1318
+ process2.on(signal, () => {
1319
+ if (proc.killed === false && proc.exitCode === null) {
1320
+ proc.kill(signal);
1321
+ }
1322
+ });
1323
+ });
1324
+ }
1325
+ const exitCallback = this._exitCallback;
1326
+ proc.on("close", (code) => {
1327
+ code = code ?? 1;
1328
+ if (!exitCallback) {
1329
+ process2.exit(code);
1330
+ } else {
1331
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1332
+ }
1333
+ });
1334
+ proc.on("error", (err) => {
1335
+ if (err.code === "ENOENT") {
1336
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1337
+ } else if (err.code === "EACCES") {
1338
+ throw new Error(`'${executableFile}' not executable`);
1339
+ }
1340
+ if (!exitCallback) {
1341
+ process2.exit(1);
1342
+ } else {
1343
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1344
+ wrappedError.nestedError = err;
1345
+ exitCallback(wrappedError);
1346
+ }
1347
+ });
1348
+ this.runningCommand = proc;
1349
+ }
1350
+ _dispatchSubcommand(commandName, operands, unknown) {
1351
+ const subCommand = this._findCommand(commandName);
1352
+ if (!subCommand)
1353
+ this.help({ error: true });
1354
+ subCommand._prepareForParse();
1355
+ let promiseChain;
1356
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1357
+ promiseChain = this._chainOrCall(promiseChain, () => {
1358
+ if (subCommand._executableHandler) {
1359
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1360
+ } else {
1361
+ return subCommand._parseCommand(operands, unknown);
1362
+ }
1363
+ });
1364
+ return promiseChain;
1365
+ }
1366
+ _dispatchHelpCommand(subcommandName) {
1367
+ if (!subcommandName) {
1368
+ this.help();
1369
+ }
1370
+ const subCommand = this._findCommand(subcommandName);
1371
+ if (subCommand && !subCommand._executableHandler) {
1372
+ subCommand.help();
1373
+ }
1374
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1375
+ }
1376
+ _checkNumberOfArguments() {
1377
+ this.registeredArguments.forEach((arg, i) => {
1378
+ if (arg.required && this.args[i] == null) {
1379
+ this.missingArgument(arg.name());
1380
+ }
1381
+ });
1382
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1383
+ return;
1384
+ }
1385
+ if (this.args.length > this.registeredArguments.length) {
1386
+ this._excessArguments(this.args);
1387
+ }
1388
+ }
1389
+ _processArguments() {
1390
+ const myParseArg = (argument, value, previous) => {
1391
+ let parsedValue = value;
1392
+ if (value !== null && argument.parseArg) {
1393
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1394
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1395
+ }
1396
+ return parsedValue;
1397
+ };
1398
+ this._checkNumberOfArguments();
1399
+ const processedArgs = [];
1400
+ this.registeredArguments.forEach((declaredArg, index) => {
1401
+ let value = declaredArg.defaultValue;
1402
+ if (declaredArg.variadic) {
1403
+ if (index < this.args.length) {
1404
+ value = this.args.slice(index);
1405
+ if (declaredArg.parseArg) {
1406
+ value = value.reduce((processed, v) => {
1407
+ return myParseArg(declaredArg, v, processed);
1408
+ }, declaredArg.defaultValue);
1409
+ }
1410
+ } else if (value === undefined) {
1411
+ value = [];
1412
+ }
1413
+ } else if (index < this.args.length) {
1414
+ value = this.args[index];
1415
+ if (declaredArg.parseArg) {
1416
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1417
+ }
1418
+ }
1419
+ processedArgs[index] = value;
1420
+ });
1421
+ this.processedArgs = processedArgs;
1422
+ }
1423
+ _chainOrCall(promise, fn) {
1424
+ if (promise && promise.then && typeof promise.then === "function") {
1425
+ return promise.then(() => fn());
1426
+ }
1427
+ return fn();
1428
+ }
1429
+ _chainOrCallHooks(promise, event) {
1430
+ let result = promise;
1431
+ const hooks = [];
1432
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1433
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1434
+ hooks.push({ hookedCommand, callback });
1435
+ });
1436
+ });
1437
+ if (event === "postAction") {
1438
+ hooks.reverse();
1439
+ }
1440
+ hooks.forEach((hookDetail) => {
1441
+ result = this._chainOrCall(result, () => {
1442
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1443
+ });
1444
+ });
1445
+ return result;
1446
+ }
1447
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1448
+ let result = promise;
1449
+ if (this._lifeCycleHooks[event] !== undefined) {
1450
+ this._lifeCycleHooks[event].forEach((hook) => {
1451
+ result = this._chainOrCall(result, () => {
1452
+ return hook(this, subCommand);
1453
+ });
1454
+ });
1455
+ }
1456
+ return result;
1457
+ }
1458
+ _parseCommand(operands, unknown) {
1459
+ const parsed = this.parseOptions(unknown);
1460
+ this._parseOptionsEnv();
1461
+ this._parseOptionsImplied();
1462
+ operands = operands.concat(parsed.operands);
1463
+ unknown = parsed.unknown;
1464
+ this.args = operands.concat(unknown);
1465
+ if (operands && this._findCommand(operands[0])) {
1466
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1467
+ }
1468
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1469
+ return this._dispatchHelpCommand(operands[1]);
1470
+ }
1471
+ if (this._defaultCommandName) {
1472
+ this._outputHelpIfRequested(unknown);
1473
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1474
+ }
1475
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1476
+ this.help({ error: true });
1477
+ }
1478
+ this._outputHelpIfRequested(parsed.unknown);
1479
+ this._checkForMissingMandatoryOptions();
1480
+ this._checkForConflictingOptions();
1481
+ const checkForUnknownOptions = () => {
1482
+ if (parsed.unknown.length > 0) {
1483
+ this.unknownOption(parsed.unknown[0]);
1484
+ }
1485
+ };
1486
+ const commandEvent = `command:${this.name()}`;
1487
+ if (this._actionHandler) {
1488
+ checkForUnknownOptions();
1489
+ this._processArguments();
1490
+ let promiseChain;
1491
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1492
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1493
+ if (this.parent) {
1494
+ promiseChain = this._chainOrCall(promiseChain, () => {
1495
+ this.parent.emit(commandEvent, operands, unknown);
1496
+ });
1497
+ }
1498
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1499
+ return promiseChain;
1500
+ }
1501
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1502
+ checkForUnknownOptions();
1503
+ this._processArguments();
1504
+ this.parent.emit(commandEvent, operands, unknown);
1505
+ } else if (operands.length) {
1506
+ if (this._findCommand("*")) {
1507
+ return this._dispatchSubcommand("*", operands, unknown);
1508
+ }
1509
+ if (this.listenerCount("command:*")) {
1510
+ this.emit("command:*", operands, unknown);
1511
+ } else if (this.commands.length) {
1512
+ this.unknownCommand();
1513
+ } else {
1514
+ checkForUnknownOptions();
1515
+ this._processArguments();
1516
+ }
1517
+ } else if (this.commands.length) {
1518
+ checkForUnknownOptions();
1519
+ this.help({ error: true });
1520
+ } else {
1521
+ checkForUnknownOptions();
1522
+ this._processArguments();
1523
+ }
1524
+ }
1525
+ _findCommand(name) {
1526
+ if (!name)
1527
+ return;
1528
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1529
+ }
1530
+ _findOption(arg) {
1531
+ return this.options.find((option) => option.is(arg));
1532
+ }
1533
+ _checkForMissingMandatoryOptions() {
1534
+ this._getCommandAndAncestors().forEach((cmd) => {
1535
+ cmd.options.forEach((anOption) => {
1536
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1537
+ cmd.missingMandatoryOptionValue(anOption);
1538
+ }
1539
+ });
1540
+ });
1541
+ }
1542
+ _checkForConflictingLocalOptions() {
1543
+ const definedNonDefaultOptions = this.options.filter((option) => {
1544
+ const optionKey = option.attributeName();
1545
+ if (this.getOptionValue(optionKey) === undefined) {
1546
+ return false;
1547
+ }
1548
+ return this.getOptionValueSource(optionKey) !== "default";
1549
+ });
1550
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1551
+ optionsWithConflicting.forEach((option) => {
1552
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1553
+ if (conflictingAndDefined) {
1554
+ this._conflictingOption(option, conflictingAndDefined);
1555
+ }
1556
+ });
1557
+ }
1558
+ _checkForConflictingOptions() {
1559
+ this._getCommandAndAncestors().forEach((cmd) => {
1560
+ cmd._checkForConflictingLocalOptions();
1561
+ });
1562
+ }
1563
+ parseOptions(argv) {
1564
+ const operands = [];
1565
+ const unknown = [];
1566
+ let dest = operands;
1567
+ const args = argv.slice();
1568
+ function maybeOption(arg) {
1569
+ return arg.length > 1 && arg[0] === "-";
1570
+ }
1571
+ let activeVariadicOption = null;
1572
+ while (args.length) {
1573
+ const arg = args.shift();
1574
+ if (arg === "--") {
1575
+ if (dest === unknown)
1576
+ dest.push(arg);
1577
+ dest.push(...args);
1578
+ break;
1579
+ }
1580
+ if (activeVariadicOption && !maybeOption(arg)) {
1581
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1582
+ continue;
1583
+ }
1584
+ activeVariadicOption = null;
1585
+ if (maybeOption(arg)) {
1586
+ const option = this._findOption(arg);
1587
+ if (option) {
1588
+ if (option.required) {
1589
+ const value = args.shift();
1590
+ if (value === undefined)
1591
+ this.optionMissingArgument(option);
1592
+ this.emit(`option:${option.name()}`, value);
1593
+ } else if (option.optional) {
1594
+ let value = null;
1595
+ if (args.length > 0 && !maybeOption(args[0])) {
1596
+ value = args.shift();
1597
+ }
1598
+ this.emit(`option:${option.name()}`, value);
1599
+ } else {
1600
+ this.emit(`option:${option.name()}`);
1601
+ }
1602
+ activeVariadicOption = option.variadic ? option : null;
1603
+ continue;
1604
+ }
1605
+ }
1606
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1607
+ const option = this._findOption(`-${arg[1]}`);
1608
+ if (option) {
1609
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1610
+ this.emit(`option:${option.name()}`, arg.slice(2));
1611
+ } else {
1612
+ this.emit(`option:${option.name()}`);
1613
+ args.unshift(`-${arg.slice(2)}`);
1614
+ }
1615
+ continue;
1616
+ }
1617
+ }
1618
+ if (/^--[^=]+=/.test(arg)) {
1619
+ const index = arg.indexOf("=");
1620
+ const option = this._findOption(arg.slice(0, index));
1621
+ if (option && (option.required || option.optional)) {
1622
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1623
+ continue;
1624
+ }
1625
+ }
1626
+ if (maybeOption(arg)) {
1627
+ dest = unknown;
1628
+ }
1629
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1630
+ if (this._findCommand(arg)) {
1631
+ operands.push(arg);
1632
+ if (args.length > 0)
1633
+ unknown.push(...args);
1634
+ break;
1635
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1636
+ operands.push(arg);
1637
+ if (args.length > 0)
1638
+ operands.push(...args);
1639
+ break;
1640
+ } else if (this._defaultCommandName) {
1641
+ unknown.push(arg);
1642
+ if (args.length > 0)
1643
+ unknown.push(...args);
1644
+ break;
1645
+ }
1646
+ }
1647
+ if (this._passThroughOptions) {
1648
+ dest.push(arg);
1649
+ if (args.length > 0)
1650
+ dest.push(...args);
1651
+ break;
1652
+ }
1653
+ dest.push(arg);
1654
+ }
1655
+ return { operands, unknown };
1656
+ }
1657
+ opts() {
1658
+ if (this._storeOptionsAsProperties) {
1659
+ const result = {};
1660
+ const len = this.options.length;
1661
+ for (let i = 0;i < len; i++) {
1662
+ const key = this.options[i].attributeName();
1663
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1664
+ }
1665
+ return result;
1666
+ }
1667
+ return this._optionValues;
1668
+ }
1669
+ optsWithGlobals() {
1670
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1671
+ }
1672
+ error(message, errorOptions) {
1673
+ this._outputConfiguration.outputError(`${message}
1674
+ `, this._outputConfiguration.writeErr);
1675
+ if (typeof this._showHelpAfterError === "string") {
1676
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1677
+ `);
1678
+ } else if (this._showHelpAfterError) {
1679
+ this._outputConfiguration.writeErr(`
1680
+ `);
1681
+ this.outputHelp({ error: true });
1682
+ }
1683
+ const config = errorOptions || {};
1684
+ const exitCode = config.exitCode || 1;
1685
+ const code = config.code || "commander.error";
1686
+ this._exit(exitCode, code, message);
1687
+ }
1688
+ _parseOptionsEnv() {
1689
+ this.options.forEach((option) => {
1690
+ if (option.envVar && option.envVar in process2.env) {
1691
+ const optionKey = option.attributeName();
1692
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1693
+ if (option.required || option.optional) {
1694
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1695
+ } else {
1696
+ this.emit(`optionEnv:${option.name()}`);
1697
+ }
1698
+ }
1699
+ }
1700
+ });
1701
+ }
1702
+ _parseOptionsImplied() {
1703
+ const dualHelper = new DualOptions(this.options);
1704
+ const hasCustomOptionValue = (optionKey) => {
1705
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1706
+ };
1707
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1708
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1709
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1710
+ });
1711
+ });
1712
+ }
1713
+ missingArgument(name) {
1714
+ const message = `error: missing required argument '${name}'`;
1715
+ this.error(message, { code: "commander.missingArgument" });
1716
+ }
1717
+ optionMissingArgument(option) {
1718
+ const message = `error: option '${option.flags}' argument missing`;
1719
+ this.error(message, { code: "commander.optionMissingArgument" });
1720
+ }
1721
+ missingMandatoryOptionValue(option) {
1722
+ const message = `error: required option '${option.flags}' not specified`;
1723
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1724
+ }
1725
+ _conflictingOption(option, conflictingOption) {
1726
+ const findBestOptionFromValue = (option2) => {
1727
+ const optionKey = option2.attributeName();
1728
+ const optionValue = this.getOptionValue(optionKey);
1729
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1730
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1731
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1732
+ return negativeOption;
1733
+ }
1734
+ return positiveOption || option2;
1735
+ };
1736
+ const getErrorMessage = (option2) => {
1737
+ const bestOption = findBestOptionFromValue(option2);
1738
+ const optionKey = bestOption.attributeName();
1739
+ const source = this.getOptionValueSource(optionKey);
1740
+ if (source === "env") {
1741
+ return `environment variable '${bestOption.envVar}'`;
1742
+ }
1743
+ return `option '${bestOption.flags}'`;
1744
+ };
1745
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1746
+ this.error(message, { code: "commander.conflictingOption" });
1747
+ }
1748
+ unknownOption(flag) {
1749
+ if (this._allowUnknownOption)
1750
+ return;
1751
+ let suggestion = "";
1752
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1753
+ let candidateFlags = [];
1754
+ let command = this;
1755
+ do {
1756
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1757
+ candidateFlags = candidateFlags.concat(moreFlags);
1758
+ command = command.parent;
1759
+ } while (command && !command._enablePositionalOptions);
1760
+ suggestion = suggestSimilar(flag, candidateFlags);
1761
+ }
1762
+ const message = `error: unknown option '${flag}'${suggestion}`;
1763
+ this.error(message, { code: "commander.unknownOption" });
1764
+ }
1765
+ _excessArguments(receivedArgs) {
1766
+ if (this._allowExcessArguments)
1767
+ return;
1768
+ const expected = this.registeredArguments.length;
1769
+ const s = expected === 1 ? "" : "s";
1770
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1771
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1772
+ this.error(message, { code: "commander.excessArguments" });
1773
+ }
1774
+ unknownCommand() {
1775
+ const unknownName = this.args[0];
1776
+ let suggestion = "";
1777
+ if (this._showSuggestionAfterError) {
1778
+ const candidateNames = [];
1779
+ this.createHelp().visibleCommands(this).forEach((command) => {
1780
+ candidateNames.push(command.name());
1781
+ if (command.alias())
1782
+ candidateNames.push(command.alias());
1783
+ });
1784
+ suggestion = suggestSimilar(unknownName, candidateNames);
1785
+ }
1786
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1787
+ this.error(message, { code: "commander.unknownCommand" });
1788
+ }
1789
+ version(str, flags, description) {
1790
+ if (str === undefined)
1791
+ return this._version;
1792
+ this._version = str;
1793
+ flags = flags || "-V, --version";
1794
+ description = description || "output the version number";
1795
+ const versionOption = this.createOption(flags, description);
1796
+ this._versionOptionName = versionOption.attributeName();
1797
+ this._registerOption(versionOption);
1798
+ this.on("option:" + versionOption.name(), () => {
1799
+ this._outputConfiguration.writeOut(`${str}
1800
+ `);
1801
+ this._exit(0, "commander.version", str);
1802
+ });
1803
+ return this;
1804
+ }
1805
+ description(str, argsDescription) {
1806
+ if (str === undefined && argsDescription === undefined)
1807
+ return this._description;
1808
+ this._description = str;
1809
+ if (argsDescription) {
1810
+ this._argsDescription = argsDescription;
1811
+ }
1812
+ return this;
1813
+ }
1814
+ summary(str) {
1815
+ if (str === undefined)
1816
+ return this._summary;
1817
+ this._summary = str;
1818
+ return this;
1819
+ }
1820
+ alias(alias) {
1821
+ if (alias === undefined)
1822
+ return this._aliases[0];
1823
+ let command = this;
1824
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1825
+ command = this.commands[this.commands.length - 1];
1826
+ }
1827
+ if (alias === command._name)
1828
+ throw new Error("Command alias can't be the same as its name");
1829
+ const matchingCommand = this.parent?._findCommand(alias);
1830
+ if (matchingCommand) {
1831
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1832
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1833
+ }
1834
+ command._aliases.push(alias);
1835
+ return this;
1836
+ }
1837
+ aliases(aliases) {
1838
+ if (aliases === undefined)
1839
+ return this._aliases;
1840
+ aliases.forEach((alias) => this.alias(alias));
1841
+ return this;
1842
+ }
1843
+ usage(str) {
1844
+ if (str === undefined) {
1845
+ if (this._usage)
1846
+ return this._usage;
1847
+ const args = this.registeredArguments.map((arg) => {
1848
+ return humanReadableArgName(arg);
1849
+ });
1850
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1851
+ }
1852
+ this._usage = str;
1853
+ return this;
1854
+ }
1855
+ name(str) {
1856
+ if (str === undefined)
1857
+ return this._name;
1858
+ this._name = str;
1859
+ return this;
1860
+ }
1861
+ nameFromFilename(filename) {
1862
+ this._name = path.basename(filename, path.extname(filename));
1863
+ return this;
1864
+ }
1865
+ executableDir(path2) {
1866
+ if (path2 === undefined)
1867
+ return this._executableDir;
1868
+ this._executableDir = path2;
1869
+ return this;
1870
+ }
1871
+ helpInformation(contextOptions) {
1872
+ const helper = this.createHelp();
1873
+ const context = this._getOutputContext(contextOptions);
1874
+ helper.prepareContext({
1875
+ error: context.error,
1876
+ helpWidth: context.helpWidth,
1877
+ outputHasColors: context.hasColors
1878
+ });
1879
+ const text = helper.formatHelp(this, helper);
1880
+ if (context.hasColors)
1881
+ return text;
1882
+ return this._outputConfiguration.stripColor(text);
1883
+ }
1884
+ _getOutputContext(contextOptions) {
1885
+ contextOptions = contextOptions || {};
1886
+ const error = !!contextOptions.error;
1887
+ let baseWrite;
1888
+ let hasColors;
1889
+ let helpWidth;
1890
+ if (error) {
1891
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1892
+ hasColors = this._outputConfiguration.getErrHasColors();
1893
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1894
+ } else {
1895
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1896
+ hasColors = this._outputConfiguration.getOutHasColors();
1897
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1898
+ }
1899
+ const write = (str) => {
1900
+ if (!hasColors)
1901
+ str = this._outputConfiguration.stripColor(str);
1902
+ return baseWrite(str);
1903
+ };
1904
+ return { error, write, hasColors, helpWidth };
1905
+ }
1906
+ outputHelp(contextOptions) {
1907
+ let deprecatedCallback;
1908
+ if (typeof contextOptions === "function") {
1909
+ deprecatedCallback = contextOptions;
1910
+ contextOptions = undefined;
1911
+ }
1912
+ const outputContext = this._getOutputContext(contextOptions);
1913
+ const eventContext = {
1914
+ error: outputContext.error,
1915
+ write: outputContext.write,
1916
+ command: this
1917
+ };
1918
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1919
+ this.emit("beforeHelp", eventContext);
1920
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1921
+ if (deprecatedCallback) {
1922
+ helpInformation = deprecatedCallback(helpInformation);
1923
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1924
+ throw new Error("outputHelp callback must return a string or a Buffer");
1925
+ }
1926
+ }
1927
+ outputContext.write(helpInformation);
1928
+ if (this._getHelpOption()?.long) {
1929
+ this.emit(this._getHelpOption().long);
1930
+ }
1931
+ this.emit("afterHelp", eventContext);
1932
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1933
+ }
1934
+ helpOption(flags, description) {
1935
+ if (typeof flags === "boolean") {
1936
+ if (flags) {
1937
+ this._helpOption = this._helpOption ?? undefined;
1938
+ } else {
1939
+ this._helpOption = null;
1940
+ }
1941
+ return this;
1942
+ }
1943
+ flags = flags ?? "-h, --help";
1944
+ description = description ?? "display help for command";
1945
+ this._helpOption = this.createOption(flags, description);
1946
+ return this;
1947
+ }
1948
+ _getHelpOption() {
1949
+ if (this._helpOption === undefined) {
1950
+ this.helpOption(undefined, undefined);
1951
+ }
1952
+ return this._helpOption;
1953
+ }
1954
+ addHelpOption(option) {
1955
+ this._helpOption = option;
1956
+ return this;
1957
+ }
1958
+ help(contextOptions) {
1959
+ this.outputHelp(contextOptions);
1960
+ let exitCode = Number(process2.exitCode ?? 0);
1961
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1962
+ exitCode = 1;
1963
+ }
1964
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1965
+ }
1966
+ addHelpText(position, text) {
1967
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1968
+ if (!allowedValues.includes(position)) {
1969
+ throw new Error(`Unexpected value for position to addHelpText.
1970
+ Expecting one of '${allowedValues.join("', '")}'`);
1971
+ }
1972
+ const helpEvent = `${position}Help`;
1973
+ this.on(helpEvent, (context) => {
1974
+ let helpStr;
1975
+ if (typeof text === "function") {
1976
+ helpStr = text({ error: context.error, command: context.command });
1977
+ } else {
1978
+ helpStr = text;
1979
+ }
1980
+ if (helpStr) {
1981
+ context.write(`${helpStr}
1982
+ `);
1983
+ }
1984
+ });
1985
+ return this;
1986
+ }
1987
+ _outputHelpIfRequested(args) {
1988
+ const helpOption = this._getHelpOption();
1989
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1990
+ if (helpRequested) {
1991
+ this.outputHelp();
1992
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1993
+ }
1994
+ }
1995
+ }
1996
+ function incrementNodeInspectorPort(args) {
1997
+ return args.map((arg) => {
1998
+ if (!arg.startsWith("--inspect")) {
1999
+ return arg;
2000
+ }
2001
+ let debugOption;
2002
+ let debugHost = "127.0.0.1";
2003
+ let debugPort = "9229";
2004
+ let match;
2005
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2006
+ debugOption = match[1];
2007
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2008
+ debugOption = match[1];
2009
+ if (/^\d+$/.test(match[3])) {
2010
+ debugPort = match[3];
2011
+ } else {
2012
+ debugHost = match[3];
2013
+ }
2014
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2015
+ debugOption = match[1];
2016
+ debugHost = match[3];
2017
+ debugPort = match[4];
2018
+ }
2019
+ if (debugOption && debugPort !== "0") {
2020
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2021
+ }
2022
+ return arg;
2023
+ });
2024
+ }
2025
+ function useColor() {
2026
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2027
+ return false;
2028
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2029
+ return true;
2030
+ return;
2031
+ }
2032
+ exports.Command = Command;
2033
+ exports.useColor = useColor;
2034
+ });
2035
+
2036
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js
2037
+ var require_commander = __commonJS((exports) => {
2038
+ var { Argument } = require_argument();
2039
+ var { Command } = require_command();
2040
+ var { CommanderError, InvalidArgumentError } = require_error();
2041
+ var { Help } = require_help();
2042
+ var { Option } = require_option();
2043
+ exports.program = new Command;
2044
+ exports.createCommand = (name) => new Command(name);
2045
+ exports.createOption = (flags, description) => new Option(flags, description);
2046
+ exports.createArgument = (name, description) => new Argument(name, description);
2047
+ exports.Command = Command;
2048
+ exports.Option = Option;
2049
+ exports.Argument = Argument;
2050
+ exports.Help = Help;
2051
+ exports.CommanderError = CommanderError;
2052
+ exports.InvalidArgumentError = InvalidArgumentError;
2053
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2054
+ });
2055
+
2056
+ // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/esm.mjs
2057
+ var import__ = __toESM(require_commander(), 1);
2058
+ var {
2059
+ program,
2060
+ createCommand,
2061
+ createArgument,
2062
+ createOption,
2063
+ CommanderError,
2064
+ InvalidArgumentError,
2065
+ InvalidOptionArgumentError,
2066
+ Command,
2067
+ Argument,
2068
+ Option,
2069
+ Help
2070
+ } = import__.default;
2071
+
2072
+ // src/config.ts
2073
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2074
+ import { homedir } from "node:os";
2075
+ import { join } from "node:path";
2076
+ var CONFIG_DIR_NAME = ".lifeos";
2077
+ var CONFIG_FILE_NAME = "config.json";
2078
+ function getConfigDir() {
2079
+ const dir = join(homedir(), CONFIG_DIR_NAME);
2080
+ if (!existsSync(dir)) {
2081
+ mkdirSync(dir, { recursive: true });
2082
+ }
2083
+ return dir;
2084
+ }
2085
+ function getConfig() {
2086
+ const configPath = join(getConfigDir(), CONFIG_FILE_NAME);
2087
+ if (!existsSync(configPath)) {
2088
+ return { api_url: "", api_key: "" };
2089
+ }
2090
+ try {
2091
+ const raw = readFileSync(configPath, "utf-8");
2092
+ const parsed = JSON.parse(raw);
2093
+ return {
2094
+ api_url: parsed.api_url ?? "",
2095
+ api_key: parsed.api_key ?? ""
2096
+ };
2097
+ } catch {
2098
+ return { api_url: "", api_key: "" };
2099
+ }
2100
+ }
2101
+ function saveConfig(config) {
2102
+ const configPath = join(getConfigDir(), CONFIG_FILE_NAME);
2103
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + `
2104
+ `, "utf-8");
2105
+ }
2106
+ function getApiUrl() {
2107
+ const { api_url } = getConfig();
2108
+ if (!api_url) {
2109
+ throw new Error("API URL not configured. Run 'lifeos config set-url <url>' first.");
2110
+ }
2111
+ return api_url;
2112
+ }
2113
+ function getApiKey() {
2114
+ const { api_key } = getConfig();
2115
+ if (!api_key) {
2116
+ throw new Error("API key not configured. Run 'lifeos config set-key <key>' first.");
2117
+ }
2118
+ return api_key;
2119
+ }
2120
+
2121
+ // src/api-client.ts
2122
+ class ApiClient {
2123
+ baseUrl;
2124
+ apiKey;
2125
+ constructor(baseUrl, apiKey) {
2126
+ this.baseUrl = baseUrl;
2127
+ this.apiKey = apiKey;
2128
+ }
2129
+ headers() {
2130
+ return {
2131
+ Authorization: `Bearer ${this.apiKey}`,
2132
+ "Content-Type": "application/json"
2133
+ };
2134
+ }
2135
+ buildUrl(path, params) {
2136
+ const url = new URL(path, this.baseUrl);
2137
+ if (params) {
2138
+ for (const [key, value] of Object.entries(params)) {
2139
+ if (value !== undefined && value !== "") {
2140
+ url.searchParams.set(key, value);
2141
+ }
2142
+ }
2143
+ }
2144
+ return url.toString();
2145
+ }
2146
+ async request(method, path, opts) {
2147
+ const url = this.buildUrl(path, opts?.params);
2148
+ const res = await fetch(url, {
2149
+ method,
2150
+ headers: this.headers(),
2151
+ body: opts?.body !== undefined ? JSON.stringify(opts.body) : undefined
2152
+ });
2153
+ if (!res.ok) {
2154
+ let message = `HTTP ${res.status} ${res.statusText}`;
2155
+ try {
2156
+ const errBody = await res.json();
2157
+ if (errBody.error) {
2158
+ message = errBody.error;
2159
+ }
2160
+ } catch {}
2161
+ throw new Error(message);
2162
+ }
2163
+ if (res.status === 204) {
2164
+ return;
2165
+ }
2166
+ return await res.json();
2167
+ }
2168
+ async get(path, params) {
2169
+ return this.request("GET", path, { params });
2170
+ }
2171
+ async post(path, body) {
2172
+ return this.request("POST", path, { body });
2173
+ }
2174
+ async put(path, body) {
2175
+ return this.request("PUT", path, { body });
2176
+ }
2177
+ async patch(path, body) {
2178
+ return this.request("PATCH", path, { body });
2179
+ }
2180
+ async del(path) {
2181
+ return this.request("DELETE", path);
2182
+ }
2183
+ }
2184
+ function createClient() {
2185
+ const baseUrl = getApiUrl();
2186
+ const apiKey = getApiKey();
2187
+ return new ApiClient(baseUrl, apiKey);
2188
+ }
2189
+
2190
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
2191
+ var ANSI_BACKGROUND_OFFSET = 10;
2192
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
2193
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
2194
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
2195
+ var styles = {
2196
+ modifier: {
2197
+ reset: [0, 0],
2198
+ bold: [1, 22],
2199
+ dim: [2, 22],
2200
+ italic: [3, 23],
2201
+ underline: [4, 24],
2202
+ overline: [53, 55],
2203
+ inverse: [7, 27],
2204
+ hidden: [8, 28],
2205
+ strikethrough: [9, 29]
2206
+ },
2207
+ color: {
2208
+ black: [30, 39],
2209
+ red: [31, 39],
2210
+ green: [32, 39],
2211
+ yellow: [33, 39],
2212
+ blue: [34, 39],
2213
+ magenta: [35, 39],
2214
+ cyan: [36, 39],
2215
+ white: [37, 39],
2216
+ blackBright: [90, 39],
2217
+ gray: [90, 39],
2218
+ grey: [90, 39],
2219
+ redBright: [91, 39],
2220
+ greenBright: [92, 39],
2221
+ yellowBright: [93, 39],
2222
+ blueBright: [94, 39],
2223
+ magentaBright: [95, 39],
2224
+ cyanBright: [96, 39],
2225
+ whiteBright: [97, 39]
2226
+ },
2227
+ bgColor: {
2228
+ bgBlack: [40, 49],
2229
+ bgRed: [41, 49],
2230
+ bgGreen: [42, 49],
2231
+ bgYellow: [43, 49],
2232
+ bgBlue: [44, 49],
2233
+ bgMagenta: [45, 49],
2234
+ bgCyan: [46, 49],
2235
+ bgWhite: [47, 49],
2236
+ bgBlackBright: [100, 49],
2237
+ bgGray: [100, 49],
2238
+ bgGrey: [100, 49],
2239
+ bgRedBright: [101, 49],
2240
+ bgGreenBright: [102, 49],
2241
+ bgYellowBright: [103, 49],
2242
+ bgBlueBright: [104, 49],
2243
+ bgMagentaBright: [105, 49],
2244
+ bgCyanBright: [106, 49],
2245
+ bgWhiteBright: [107, 49]
2246
+ }
2247
+ };
2248
+ var modifierNames = Object.keys(styles.modifier);
2249
+ var foregroundColorNames = Object.keys(styles.color);
2250
+ var backgroundColorNames = Object.keys(styles.bgColor);
2251
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
2252
+ function assembleStyles() {
2253
+ const codes = new Map;
2254
+ for (const [groupName, group] of Object.entries(styles)) {
2255
+ for (const [styleName, style] of Object.entries(group)) {
2256
+ styles[styleName] = {
2257
+ open: `\x1B[${style[0]}m`,
2258
+ close: `\x1B[${style[1]}m`
2259
+ };
2260
+ group[styleName] = styles[styleName];
2261
+ codes.set(style[0], style[1]);
2262
+ }
2263
+ Object.defineProperty(styles, groupName, {
2264
+ value: group,
2265
+ enumerable: false
2266
+ });
2267
+ }
2268
+ Object.defineProperty(styles, "codes", {
2269
+ value: codes,
2270
+ enumerable: false
2271
+ });
2272
+ styles.color.close = "\x1B[39m";
2273
+ styles.bgColor.close = "\x1B[49m";
2274
+ styles.color.ansi = wrapAnsi16();
2275
+ styles.color.ansi256 = wrapAnsi256();
2276
+ styles.color.ansi16m = wrapAnsi16m();
2277
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
2278
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
2279
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
2280
+ Object.defineProperties(styles, {
2281
+ rgbToAnsi256: {
2282
+ value(red, green, blue) {
2283
+ if (red === green && green === blue) {
2284
+ if (red < 8) {
2285
+ return 16;
2286
+ }
2287
+ if (red > 248) {
2288
+ return 231;
2289
+ }
2290
+ return Math.round((red - 8) / 247 * 24) + 232;
2291
+ }
2292
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
2293
+ },
2294
+ enumerable: false
2295
+ },
2296
+ hexToRgb: {
2297
+ value(hex) {
2298
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
2299
+ if (!matches) {
2300
+ return [0, 0, 0];
2301
+ }
2302
+ let [colorString] = matches;
2303
+ if (colorString.length === 3) {
2304
+ colorString = [...colorString].map((character) => character + character).join("");
2305
+ }
2306
+ const integer = Number.parseInt(colorString, 16);
2307
+ return [
2308
+ integer >> 16 & 255,
2309
+ integer >> 8 & 255,
2310
+ integer & 255
2311
+ ];
2312
+ },
2313
+ enumerable: false
2314
+ },
2315
+ hexToAnsi256: {
2316
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
2317
+ enumerable: false
2318
+ },
2319
+ ansi256ToAnsi: {
2320
+ value(code) {
2321
+ if (code < 8) {
2322
+ return 30 + code;
2323
+ }
2324
+ if (code < 16) {
2325
+ return 90 + (code - 8);
2326
+ }
2327
+ let red;
2328
+ let green;
2329
+ let blue;
2330
+ if (code >= 232) {
2331
+ red = ((code - 232) * 10 + 8) / 255;
2332
+ green = red;
2333
+ blue = red;
2334
+ } else {
2335
+ code -= 16;
2336
+ const remainder = code % 36;
2337
+ red = Math.floor(code / 36) / 5;
2338
+ green = Math.floor(remainder / 6) / 5;
2339
+ blue = remainder % 6 / 5;
2340
+ }
2341
+ const value = Math.max(red, green, blue) * 2;
2342
+ if (value === 0) {
2343
+ return 30;
2344
+ }
2345
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
2346
+ if (value === 2) {
2347
+ result += 60;
2348
+ }
2349
+ return result;
2350
+ },
2351
+ enumerable: false
2352
+ },
2353
+ rgbToAnsi: {
2354
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
2355
+ enumerable: false
2356
+ },
2357
+ hexToAnsi: {
2358
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
2359
+ enumerable: false
2360
+ }
2361
+ });
2362
+ return styles;
2363
+ }
2364
+ var ansiStyles = assembleStyles();
2365
+ var ansi_styles_default = ansiStyles;
2366
+
2367
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
2368
+ import process2 from "node:process";
2369
+ import os from "node:os";
2370
+ import tty from "node:tty";
2371
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2372
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2373
+ const position = argv.indexOf(prefix + flag);
2374
+ const terminatorPosition = argv.indexOf("--");
2375
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2376
+ }
2377
+ var { env } = process2;
2378
+ var flagForceColor;
2379
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2380
+ flagForceColor = 0;
2381
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2382
+ flagForceColor = 1;
2383
+ }
2384
+ function envForceColor() {
2385
+ if ("FORCE_COLOR" in env) {
2386
+ if (env.FORCE_COLOR === "true") {
2387
+ return 1;
2388
+ }
2389
+ if (env.FORCE_COLOR === "false") {
2390
+ return 0;
2391
+ }
2392
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2393
+ }
2394
+ }
2395
+ function translateLevel(level) {
2396
+ if (level === 0) {
2397
+ return false;
2398
+ }
2399
+ return {
2400
+ level,
2401
+ hasBasic: true,
2402
+ has256: level >= 2,
2403
+ has16m: level >= 3
2404
+ };
2405
+ }
2406
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2407
+ const noFlagForceColor = envForceColor();
2408
+ if (noFlagForceColor !== undefined) {
2409
+ flagForceColor = noFlagForceColor;
2410
+ }
2411
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2412
+ if (forceColor === 0) {
2413
+ return 0;
2414
+ }
2415
+ if (sniffFlags) {
2416
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2417
+ return 3;
2418
+ }
2419
+ if (hasFlag("color=256")) {
2420
+ return 2;
2421
+ }
2422
+ }
2423
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2424
+ return 1;
2425
+ }
2426
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
2427
+ return 0;
2428
+ }
2429
+ const min = forceColor || 0;
2430
+ if (env.TERM === "dumb") {
2431
+ return min;
2432
+ }
2433
+ if (process2.platform === "win32") {
2434
+ const osRelease = os.release().split(".");
2435
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2436
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2437
+ }
2438
+ return 1;
2439
+ }
2440
+ if ("CI" in env) {
2441
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
2442
+ return 3;
2443
+ }
2444
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
2445
+ return 1;
2446
+ }
2447
+ return min;
2448
+ }
2449
+ if ("TEAMCITY_VERSION" in env) {
2450
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2451
+ }
2452
+ if (env.COLORTERM === "truecolor") {
2453
+ return 3;
2454
+ }
2455
+ if (env.TERM === "xterm-kitty") {
2456
+ return 3;
2457
+ }
2458
+ if (env.TERM === "xterm-ghostty") {
2459
+ return 3;
2460
+ }
2461
+ if (env.TERM === "wezterm") {
2462
+ return 3;
2463
+ }
2464
+ if ("TERM_PROGRAM" in env) {
2465
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2466
+ switch (env.TERM_PROGRAM) {
2467
+ case "iTerm.app": {
2468
+ return version >= 3 ? 3 : 2;
2469
+ }
2470
+ case "Apple_Terminal": {
2471
+ return 2;
2472
+ }
2473
+ }
2474
+ }
2475
+ if (/-256(color)?$/i.test(env.TERM)) {
2476
+ return 2;
2477
+ }
2478
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2479
+ return 1;
2480
+ }
2481
+ if ("COLORTERM" in env) {
2482
+ return 1;
2483
+ }
2484
+ return min;
2485
+ }
2486
+ function createSupportsColor(stream, options = {}) {
2487
+ const level = _supportsColor(stream, {
2488
+ streamIsTTY: stream && stream.isTTY,
2489
+ ...options
2490
+ });
2491
+ return translateLevel(level);
2492
+ }
2493
+ var supportsColor = {
2494
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2495
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2496
+ };
2497
+ var supports_color_default = supportsColor;
2498
+
2499
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
2500
+ function stringReplaceAll(string, substring, replacer) {
2501
+ let index = string.indexOf(substring);
2502
+ if (index === -1) {
2503
+ return string;
2504
+ }
2505
+ const substringLength = substring.length;
2506
+ let endIndex = 0;
2507
+ let returnValue = "";
2508
+ do {
2509
+ returnValue += string.slice(endIndex, index) + substring + replacer;
2510
+ endIndex = index + substringLength;
2511
+ index = string.indexOf(substring, endIndex);
2512
+ } while (index !== -1);
2513
+ returnValue += string.slice(endIndex);
2514
+ return returnValue;
2515
+ }
2516
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2517
+ let endIndex = 0;
2518
+ let returnValue = "";
2519
+ do {
2520
+ const gotCR = string[index - 1] === "\r";
2521
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
2522
+ ` : `
2523
+ `) + postfix;
2524
+ endIndex = index + 1;
2525
+ index = string.indexOf(`
2526
+ `, endIndex);
2527
+ } while (index !== -1);
2528
+ returnValue += string.slice(endIndex);
2529
+ return returnValue;
2530
+ }
2531
+
2532
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
2533
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
2534
+ var GENERATOR = Symbol("GENERATOR");
2535
+ var STYLER = Symbol("STYLER");
2536
+ var IS_EMPTY = Symbol("IS_EMPTY");
2537
+ var levelMapping = [
2538
+ "ansi",
2539
+ "ansi",
2540
+ "ansi256",
2541
+ "ansi16m"
2542
+ ];
2543
+ var styles2 = Object.create(null);
2544
+ var applyOptions = (object, options = {}) => {
2545
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2546
+ throw new Error("The `level` option should be an integer from 0 to 3");
2547
+ }
2548
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2549
+ object.level = options.level === undefined ? colorLevel : options.level;
2550
+ };
2551
+ var chalkFactory = (options) => {
2552
+ const chalk = (...strings) => strings.join(" ");
2553
+ applyOptions(chalk, options);
2554
+ Object.setPrototypeOf(chalk, createChalk.prototype);
2555
+ return chalk;
2556
+ };
2557
+ function createChalk(options) {
2558
+ return chalkFactory(options);
2559
+ }
2560
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
2561
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
2562
+ styles2[styleName] = {
2563
+ get() {
2564
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
2565
+ Object.defineProperty(this, styleName, { value: builder });
2566
+ return builder;
2567
+ }
2568
+ };
2569
+ }
2570
+ styles2.visible = {
2571
+ get() {
2572
+ const builder = createBuilder(this, this[STYLER], true);
2573
+ Object.defineProperty(this, "visible", { value: builder });
2574
+ return builder;
2575
+ }
2576
+ };
2577
+ var getModelAnsi = (model, level, type, ...arguments_) => {
2578
+ if (model === "rgb") {
2579
+ if (level === "ansi16m") {
2580
+ return ansi_styles_default[type].ansi16m(...arguments_);
2581
+ }
2582
+ if (level === "ansi256") {
2583
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
2584
+ }
2585
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
2586
+ }
2587
+ if (model === "hex") {
2588
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
2589
+ }
2590
+ return ansi_styles_default[type][model](...arguments_);
2591
+ };
2592
+ var usedModels = ["rgb", "hex", "ansi256"];
2593
+ for (const model of usedModels) {
2594
+ styles2[model] = {
2595
+ get() {
2596
+ const { level } = this;
2597
+ return function(...arguments_) {
2598
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
2599
+ return createBuilder(this, styler, this[IS_EMPTY]);
2600
+ };
2601
+ }
2602
+ };
2603
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2604
+ styles2[bgModel] = {
2605
+ get() {
2606
+ const { level } = this;
2607
+ return function(...arguments_) {
2608
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
2609
+ return createBuilder(this, styler, this[IS_EMPTY]);
2610
+ };
2611
+ }
2612
+ };
2613
+ }
2614
+ var proto = Object.defineProperties(() => {}, {
2615
+ ...styles2,
2616
+ level: {
2617
+ enumerable: true,
2618
+ get() {
2619
+ return this[GENERATOR].level;
2620
+ },
2621
+ set(level) {
2622
+ this[GENERATOR].level = level;
2623
+ }
2624
+ }
2625
+ });
2626
+ var createStyler = (open, close, parent) => {
2627
+ let openAll;
2628
+ let closeAll;
2629
+ if (parent === undefined) {
2630
+ openAll = open;
2631
+ closeAll = close;
2632
+ } else {
2633
+ openAll = parent.openAll + open;
2634
+ closeAll = close + parent.closeAll;
2635
+ }
2636
+ return {
2637
+ open,
2638
+ close,
2639
+ openAll,
2640
+ closeAll,
2641
+ parent
2642
+ };
2643
+ };
2644
+ var createBuilder = (self, _styler, _isEmpty) => {
2645
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2646
+ Object.setPrototypeOf(builder, proto);
2647
+ builder[GENERATOR] = self;
2648
+ builder[STYLER] = _styler;
2649
+ builder[IS_EMPTY] = _isEmpty;
2650
+ return builder;
2651
+ };
2652
+ var applyStyle = (self, string) => {
2653
+ if (self.level <= 0 || !string) {
2654
+ return self[IS_EMPTY] ? "" : string;
2655
+ }
2656
+ let styler = self[STYLER];
2657
+ if (styler === undefined) {
2658
+ return string;
2659
+ }
2660
+ const { openAll, closeAll } = styler;
2661
+ if (string.includes("\x1B")) {
2662
+ while (styler !== undefined) {
2663
+ string = stringReplaceAll(string, styler.close, styler.open);
2664
+ styler = styler.parent;
2665
+ }
2666
+ }
2667
+ const lfIndex = string.indexOf(`
2668
+ `);
2669
+ if (lfIndex !== -1) {
2670
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2671
+ }
2672
+ return openAll + string + closeAll;
2673
+ };
2674
+ Object.defineProperties(createChalk.prototype, styles2);
2675
+ var chalk = createChalk();
2676
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2677
+ var source_default = chalk;
2678
+
2679
+ // src/output.ts
2680
+ function isJsonMode() {
2681
+ return process.argv.includes("--json");
2682
+ }
2683
+ function printTable(headers, rows) {
2684
+ if (isJsonMode())
2685
+ return;
2686
+ const colWidths = headers.map((h, i) => {
2687
+ const maxRow = rows.reduce((max, row) => Math.max(max, (row[i] ?? "").length), 0);
2688
+ return Math.max(h.length, maxRow);
2689
+ });
2690
+ const headerLine = headers.map((h, i) => source_default.bold(h.padEnd(colWidths[i]))).join(" ");
2691
+ console.log(headerLine);
2692
+ const separator = colWidths.map((w) => "-".repeat(w)).join(" ");
2693
+ console.log(source_default.dim(separator));
2694
+ for (const row of rows) {
2695
+ const line = row.map((cell, i) => (cell ?? "").padEnd(colWidths[i])).join(" ");
2696
+ console.log(line);
2697
+ }
2698
+ }
2699
+ function printJson(data) {
2700
+ console.log(JSON.stringify(data, null, 2));
2701
+ }
2702
+ function printSuccess(msg) {
2703
+ console.log(source_default.green("✓") + " " + msg);
2704
+ }
2705
+ function printError(msg) {
2706
+ console.error(source_default.red("✗") + " " + msg);
2707
+ }
2708
+ function getId(obj) {
2709
+ return String(obj._id ?? obj.id ?? "");
2710
+ }
2711
+ function shortId(obj) {
2712
+ return getId(obj).slice(0, 8);
2713
+ }
2714
+ function formatDate(dateStr) {
2715
+ if (!dateStr)
2716
+ return "-";
2717
+ try {
2718
+ const d = new Date(dateStr);
2719
+ return d.toLocaleDateString("en-US", {
2720
+ year: "numeric",
2721
+ month: "short",
2722
+ day: "numeric"
2723
+ });
2724
+ } catch {
2725
+ return dateStr;
2726
+ }
2727
+ }
2728
+
2729
+ // src/commands/config.ts
2730
+ var configCommand = new Command("config").description("Manage CLI configuration");
2731
+ configCommand.command("set-url <url>").description("Set the API server URL").action((url) => {
2732
+ try {
2733
+ const config = getConfig();
2734
+ config.api_url = url;
2735
+ saveConfig(config);
2736
+ printSuccess(`API URL set to ${url}`);
2737
+ } catch (err) {
2738
+ printError(err instanceof Error ? err.message : String(err));
2739
+ process.exitCode = 1;
2740
+ }
2741
+ });
2742
+ configCommand.command("set-key <key>").description("Set the API key").action((key) => {
2743
+ try {
2744
+ const config = getConfig();
2745
+ config.api_key = key;
2746
+ saveConfig(config);
2747
+ printSuccess("API key saved.");
2748
+ } catch (err) {
2749
+ printError(err instanceof Error ? err.message : String(err));
2750
+ process.exitCode = 1;
2751
+ }
2752
+ });
2753
+ configCommand.command("show").description("Display current configuration").action(() => {
2754
+ try {
2755
+ const config = getConfig();
2756
+ const masked = {
2757
+ api_url: config.api_url || "(not set)",
2758
+ api_key: config.api_key ? config.api_key.slice(0, 14) + "..." : "(not set)"
2759
+ };
2760
+ if (isJsonMode()) {
2761
+ printJson(masked);
2762
+ } else {
2763
+ console.log(`API URL: ${masked.api_url}`);
2764
+ console.log(`API Key: ${masked.api_key}`);
2765
+ }
2766
+ } catch (err) {
2767
+ printError(err instanceof Error ? err.message : String(err));
2768
+ process.exitCode = 1;
2769
+ }
2770
+ });
2771
+
2772
+ // src/commands/task.ts
2773
+ var taskCommand = new Command("task").description("Manage tasks");
2774
+ taskCommand.command("list").description("List tasks").option("-s, --status <status>", "Filter by status (todo, done, dropped)").option("-d, --due <due>", "Filter by due date (today, tomorrow, week, overdue, all)").action(async (opts) => {
2775
+ try {
2776
+ const client = createClient();
2777
+ const params = {};
2778
+ if (opts.status)
2779
+ params.status = opts.status;
2780
+ if (opts.due)
2781
+ params.due = opts.due;
2782
+ const res = await client.get("/api/v1/tasks", params);
2783
+ if (isJsonMode()) {
2784
+ printJson(res);
2785
+ return;
2786
+ }
2787
+ if (res.data.length === 0) {
2788
+ console.log("No tasks found.");
2789
+ return;
2790
+ }
2791
+ const rows = res.data.map((t) => [
2792
+ shortId(t),
2793
+ t.title,
2794
+ t.status,
2795
+ formatDate(t.dueDate ?? t.due_date ?? null),
2796
+ (t.goalId ?? t.goal_id)?.slice(0, 8) ?? "-"
2797
+ ]);
2798
+ printTable(["ID", "Title", "Status", "Due", "Goal"], rows);
2799
+ } catch (err) {
2800
+ printError(err instanceof Error ? err.message : String(err));
2801
+ process.exitCode = 1;
2802
+ }
2803
+ });
2804
+ taskCommand.command("create <title>").description("Create a new task").option("-d, --due <date>", "Due date (YYYY-MM-DD)").option("-p, --project <id>", "Project ID").option("-g, --goal <id>", "Goal ID").option("-n, --notes <notes>", "Notes").action(async (title, opts) => {
2805
+ try {
2806
+ const client = createClient();
2807
+ const body = { title };
2808
+ if (opts.due)
2809
+ body.dueDate = opts.due;
2810
+ if (opts.project)
2811
+ body.projectId = opts.project;
2812
+ if (opts.goal)
2813
+ body.goalId = opts.goal;
2814
+ if (opts.notes)
2815
+ body.notes = opts.notes;
2816
+ const res = await client.post("/api/v1/tasks", body);
2817
+ if (isJsonMode()) {
2818
+ printJson(res);
2819
+ return;
2820
+ }
2821
+ printSuccess(`Task created: ${res.data.title} (${shortId(res.data)})`);
2822
+ } catch (err) {
2823
+ printError(err instanceof Error ? err.message : String(err));
2824
+ process.exitCode = 1;
2825
+ }
2826
+ });
2827
+ taskCommand.command("show <id>").description("Show task details").action(async (id) => {
2828
+ try {
2829
+ const client = createClient();
2830
+ const res = await client.get(`/api/v1/tasks/${id}`);
2831
+ if (isJsonMode()) {
2832
+ printJson(res);
2833
+ return;
2834
+ }
2835
+ const t = res.data;
2836
+ console.log(`ID: ${getId(t)}`);
2837
+ console.log(`Title: ${t.title}`);
2838
+ console.log(`Status: ${t.status}`);
2839
+ console.log(`Due: ${formatDate(t.dueDate ?? t.due_date ?? null)}`);
2840
+ console.log(`Notes: ${t.notes ?? "-"}`);
2841
+ console.log(`Project ID: ${t.projectId ?? t.project_id ?? "-"}`);
2842
+ console.log(`Goal ID: ${t.goalId ?? t.goal_id ?? "-"}`);
2843
+ console.log(`Created: ${formatDate(t.createdAt ?? t.created_at ?? null)}`);
2844
+ const completedAt = t.completedAt ?? t.completed_at;
2845
+ if (completedAt) {
2846
+ console.log(`Completed: ${formatDate(completedAt)}`);
2847
+ }
2848
+ } catch (err) {
2849
+ printError(err instanceof Error ? err.message : String(err));
2850
+ process.exitCode = 1;
2851
+ }
2852
+ });
2853
+ taskCommand.command("complete <id>").description("Mark a task as done").action(async (id) => {
2854
+ try {
2855
+ const client = createClient();
2856
+ const res = await client.patch(`/api/v1/tasks/${id}`, { status: "done" });
2857
+ if (isJsonMode()) {
2858
+ printJson(res);
2859
+ return;
2860
+ }
2861
+ printSuccess(`Task completed: ${res.data.title}`);
2862
+ } catch (err) {
2863
+ printError(err instanceof Error ? err.message : String(err));
2864
+ process.exitCode = 1;
2865
+ }
2866
+ });
2867
+ taskCommand.command("update <id>").description("Update a task").option("-t, --title <title>", "New title").option("-d, --due <date>", "Due date (YYYY-MM-DD)").option("-n, --notes <notes>", "Notes").option("-g, --goal <id>", "Goal ID").action(async (id, opts) => {
2868
+ try {
2869
+ const client = createClient();
2870
+ const body = {};
2871
+ if (opts.title)
2872
+ body.title = opts.title;
2873
+ if (opts.due)
2874
+ body.dueDate = opts.due;
2875
+ if (opts.notes)
2876
+ body.notes = opts.notes;
2877
+ if (opts.goal)
2878
+ body.goalId = opts.goal;
2879
+ const res = await client.patch(`/api/v1/tasks/${id}`, body);
2880
+ if (isJsonMode()) {
2881
+ printJson(res);
2882
+ return;
2883
+ }
2884
+ printSuccess(`Task updated: ${res.data.title}`);
2885
+ } catch (err) {
2886
+ printError(err instanceof Error ? err.message : String(err));
2887
+ process.exitCode = 1;
2888
+ }
2889
+ });
2890
+ taskCommand.command("delete <id>").description("Delete a task").action(async (id) => {
2891
+ try {
2892
+ const client = createClient();
2893
+ await client.del(`/api/v1/tasks/${id}`);
2894
+ printSuccess(`Task ${id.slice(0, 8)} deleted.`);
2895
+ } catch (err) {
2896
+ printError(err instanceof Error ? err.message : String(err));
2897
+ process.exitCode = 1;
2898
+ }
2899
+ });
2900
+ taskCommand.command("bulk-complete <ids...>").description("Mark multiple tasks as done").action(async (ids) => {
2901
+ try {
2902
+ const client = createClient();
2903
+ const res = await client.post("/api/v1/tasks/bulk-complete", { ids });
2904
+ if (isJsonMode()) {
2905
+ printJson(res);
2906
+ return;
2907
+ }
2908
+ printSuccess(`${res.data.completed} task(s) completed.`);
2909
+ } catch (err) {
2910
+ printError(err instanceof Error ? err.message : String(err));
2911
+ process.exitCode = 1;
2912
+ }
2913
+ });
2914
+
2915
+ // src/commands/project.ts
2916
+ var projectCommand = new Command("project").description("Manage projects");
2917
+ projectCommand.command("list").description("List projects").option("-s, --status <status>", "Filter by status (active, completed, archived)").action(async (opts) => {
2918
+ try {
2919
+ const client = createClient();
2920
+ const params = {};
2921
+ if (opts.status)
2922
+ params.status = opts.status;
2923
+ const res = await client.get("/api/v1/projects", params);
2924
+ if (isJsonMode()) {
2925
+ printJson(res);
2926
+ return;
2927
+ }
2928
+ if (res.data.length === 0) {
2929
+ console.log("No projects found.");
2930
+ return;
2931
+ }
2932
+ const rows = res.data.map((p) => [
2933
+ shortId(p),
2934
+ p.title,
2935
+ p.status,
2936
+ formatDate(p.createdAt ?? p.created_at ?? null)
2937
+ ]);
2938
+ printTable(["ID", "Title", "Status", "Created"], rows);
2939
+ } catch (err) {
2940
+ printError(err instanceof Error ? err.message : String(err));
2941
+ process.exitCode = 1;
2942
+ }
2943
+ });
2944
+ projectCommand.command("create <title>").description("Create a new project").option("-d, --description <desc>", "Project description").action(async (title, opts) => {
2945
+ try {
2946
+ const client = createClient();
2947
+ const body = { title };
2948
+ if (opts.description)
2949
+ body.description = opts.description;
2950
+ const res = await client.post("/api/v1/projects", body);
2951
+ if (isJsonMode()) {
2952
+ printJson(res);
2953
+ return;
2954
+ }
2955
+ printSuccess(`Project created: ${res.data.title} (${shortId(res.data)})`);
2956
+ } catch (err) {
2957
+ printError(err instanceof Error ? err.message : String(err));
2958
+ process.exitCode = 1;
2959
+ }
2960
+ });
2961
+ projectCommand.command("show <id>").description("Show project details").action(async (id) => {
2962
+ try {
2963
+ const client = createClient();
2964
+ const res = await client.get(`/api/v1/projects/${id}`);
2965
+ if (isJsonMode()) {
2966
+ printJson(res);
2967
+ return;
2968
+ }
2969
+ const p = res.data;
2970
+ console.log(`ID: ${getId(p)}`);
2971
+ console.log(`Title: ${p.title}`);
2972
+ console.log(`Description: ${p.description ?? "-"}`);
2973
+ console.log(`Status: ${p.status}`);
2974
+ console.log(`Created: ${formatDate(p.createdAt ?? p.created_at ?? null)}`);
2975
+ } catch (err) {
2976
+ printError(err instanceof Error ? err.message : String(err));
2977
+ process.exitCode = 1;
2978
+ }
2979
+ });
2980
+
2981
+ // src/commands/goal.ts
2982
+ var goalCommand = new Command("goal").description("Manage goals");
2983
+ goalCommand.command("list").description("List goals").option("-q, --quarter <quarter>", "Filter by quarter (e.g. 2026-Q1)").option("-s, --status <status>", "Filter by status (active, completed, dropped)").action(async (opts) => {
2984
+ try {
2985
+ const client = createClient();
2986
+ const params = {};
2987
+ if (opts.quarter)
2988
+ params.quarter = opts.quarter;
2989
+ if (opts.status)
2990
+ params.status = opts.status;
2991
+ const res = await client.get("/api/v1/goals", params);
2992
+ if (isJsonMode()) {
2993
+ printJson(res);
2994
+ return;
2995
+ }
2996
+ if (res.data.length === 0) {
2997
+ console.log("No goals found.");
2998
+ return;
2999
+ }
3000
+ const rows = res.data.map((g) => [
3001
+ shortId(g),
3002
+ g.title,
3003
+ g.status,
3004
+ g.quarter ?? "-",
3005
+ formatDate(g.targetDate ?? g.target_date ?? null)
3006
+ ]);
3007
+ printTable(["ID", "Title", "Status", "Quarter", "Target"], rows);
3008
+ } catch (err) {
3009
+ printError(err instanceof Error ? err.message : String(err));
3010
+ process.exitCode = 1;
3011
+ }
3012
+ });
3013
+ goalCommand.command("create <title>").description("Create a new goal").option("-t, --target-date <date>", "Target date (YYYY-MM-DD)").option("-q, --quarter <quarter>", "Quarter (e.g. 2026-Q1)").option("-d, --description <desc>", "Goal description").action(async (title, opts) => {
3014
+ try {
3015
+ const client = createClient();
3016
+ const body = { title };
3017
+ if (opts.targetDate)
3018
+ body.targetDate = opts.targetDate;
3019
+ if (opts.quarter)
3020
+ body.quarter = opts.quarter;
3021
+ if (opts.description)
3022
+ body.description = opts.description;
3023
+ const res = await client.post("/api/v1/goals", body);
3024
+ if (isJsonMode()) {
3025
+ printJson(res);
3026
+ return;
3027
+ }
3028
+ printSuccess(`Goal created: ${res.data.title} (${shortId(res.data)})`);
3029
+ } catch (err) {
3030
+ printError(err instanceof Error ? err.message : String(err));
3031
+ process.exitCode = 1;
3032
+ }
3033
+ });
3034
+ goalCommand.command("show <id>").description("Show goal details").action(async (id) => {
3035
+ try {
3036
+ const client = createClient();
3037
+ const res = await client.get(`/api/v1/goals/${id}`);
3038
+ if (isJsonMode()) {
3039
+ printJson(res);
3040
+ return;
3041
+ }
3042
+ const g = res.data;
3043
+ console.log(`ID: ${getId(g)}`);
3044
+ console.log(`Title: ${g.title}`);
3045
+ console.log(`Description: ${g.description ?? "-"}`);
3046
+ console.log(`Status: ${g.status}`);
3047
+ console.log(`Quarter: ${g.quarter ?? "-"}`);
3048
+ console.log(`Target Date: ${formatDate(g.targetDate ?? g.target_date ?? null)}`);
3049
+ console.log(`Created: ${formatDate(g.createdAt ?? g.created_at ?? null)}`);
3050
+ const completedAt = g.completedAt ?? g.completed_at;
3051
+ if (completedAt) {
3052
+ console.log(`Completed: ${formatDate(completedAt)}`);
3053
+ }
3054
+ } catch (err) {
3055
+ printError(err instanceof Error ? err.message : String(err));
3056
+ process.exitCode = 1;
3057
+ }
3058
+ });
3059
+ function colorHealth(status) {
3060
+ switch (status) {
3061
+ case "on_track":
3062
+ return source_default.green(status);
3063
+ case "at_risk":
3064
+ return source_default.yellow(status);
3065
+ case "off_track":
3066
+ return source_default.red(status);
3067
+ default:
3068
+ return source_default.dim(status);
3069
+ }
3070
+ }
3071
+ goalCommand.command("health [id]").description("Show health for one or all goals").action(async (id) => {
3072
+ try {
3073
+ const client = createClient();
3074
+ if (id) {
3075
+ const res = await client.get(`/api/v1/goals/${id}/health`);
3076
+ if (isJsonMode()) {
3077
+ printJson(res);
3078
+ return;
3079
+ }
3080
+ const h = res.data;
3081
+ const tasksDone = h.tasksDone ?? h.tasks_done ?? 0;
3082
+ const tasksTotal = h.tasksTotal ?? h.tasks_total ?? 0;
3083
+ console.log(`Status: ${colorHealth(h.status)}`);
3084
+ console.log(`Score: ${h.score}`);
3085
+ console.log(`Tasks: ${tasksDone}/${tasksTotal}`);
3086
+ console.log(`Velocity: ${h.velocity}`);
3087
+ } else {
3088
+ const goalsRes = await client.get("/api/v1/goals", { status: "active" });
3089
+ if (isJsonMode()) {
3090
+ const healthData = [];
3091
+ for (const goal of goalsRes.data) {
3092
+ const hRes = await client.get(`/api/v1/goals/${getId(goal)}/health`);
3093
+ healthData.push({ goal, health: hRes.data });
3094
+ }
3095
+ printJson(healthData);
3096
+ return;
3097
+ }
3098
+ if (goalsRes.data.length === 0) {
3099
+ console.log("No active goals.");
3100
+ return;
3101
+ }
3102
+ const rows = [];
3103
+ for (const goal of goalsRes.data) {
3104
+ const hRes = await client.get(`/api/v1/goals/${getId(goal)}/health`);
3105
+ const h = hRes.data;
3106
+ const tasksDone = h.tasksDone ?? h.tasks_done ?? 0;
3107
+ const tasksTotal = h.tasksTotal ?? h.tasks_total ?? 0;
3108
+ rows.push([
3109
+ shortId(goal),
3110
+ goal.title,
3111
+ colorHealth(h.status),
3112
+ String(h.score),
3113
+ `${tasksDone}/${tasksTotal}`
3114
+ ]);
3115
+ }
3116
+ printTable(["ID", "Goal", "Health", "Score", "Tasks"], rows);
3117
+ }
3118
+ } catch (err) {
3119
+ printError(err instanceof Error ? err.message : String(err));
3120
+ process.exitCode = 1;
3121
+ }
3122
+ });
3123
+
3124
+ // src/commands/journal.ts
3125
+ function todayStr() {
3126
+ return new Date().toISOString().slice(0, 10);
3127
+ }
3128
+ var journalCommand = new Command("journal").description("Journal entries").argument("[date]", "Entry date (YYYY-MM-DD, default today)").action(async (date) => {
3129
+ try {
3130
+ const client = createClient();
3131
+ const d = date ?? todayStr();
3132
+ const res = await client.get(`/api/v1/journal/${d}`);
3133
+ if (isJsonMode()) {
3134
+ printJson(res);
3135
+ return;
3136
+ }
3137
+ const j = res.data;
3138
+ console.log(`Date: ${j.entryDate ?? j.entry_date ?? "-"}`);
3139
+ console.log(`MIT: ${j.mit ?? "-"}`);
3140
+ console.log(`P1: ${j.p1 ?? "-"}`);
3141
+ console.log(`P2: ${j.p2 ?? "-"}`);
3142
+ console.log(`Notes: ${j.notes ?? "-"}`);
3143
+ if (j.wins.length > 0) {
3144
+ console.log(`Wins:`);
3145
+ for (const w of j.wins) {
3146
+ console.log(` - ${w}`);
3147
+ }
3148
+ }
3149
+ } catch (err) {
3150
+ printError(err instanceof Error ? err.message : String(err));
3151
+ process.exitCode = 1;
3152
+ }
3153
+ });
3154
+ journalCommand.command("write").description("Write or update today's journal entry").option("--mit <text>", "Most Important Task").option("--p1 <text>", "Priority 1").option("--p2 <text>", "Priority 2").option("--notes <text>", "Notes").action(async (opts) => {
3155
+ try {
3156
+ const client = createClient();
3157
+ const body = {};
3158
+ if (opts.mit)
3159
+ body.mit = opts.mit;
3160
+ if (opts.p1)
3161
+ body.p1 = opts.p1;
3162
+ if (opts.p2)
3163
+ body.p2 = opts.p2;
3164
+ if (opts.notes)
3165
+ body.notes = opts.notes;
3166
+ const d = todayStr();
3167
+ const res = await client.put(`/api/v1/journal/${d}`, body);
3168
+ if (isJsonMode()) {
3169
+ printJson(res);
3170
+ return;
3171
+ }
3172
+ printSuccess(`Journal entry saved for ${res.data.entryDate ?? res.data.entry_date ?? d}.`);
3173
+ } catch (err) {
3174
+ printError(err instanceof Error ? err.message : String(err));
3175
+ process.exitCode = 1;
3176
+ }
3177
+ });
3178
+ journalCommand.command("wins [date]").description("List wins for a date").action(async (date) => {
3179
+ try {
3180
+ const client = createClient();
3181
+ const d = date ?? todayStr();
3182
+ const res = await client.get(`/api/v1/wins`, { entryDate: d });
3183
+ if (isJsonMode()) {
3184
+ printJson(res);
3185
+ return;
3186
+ }
3187
+ if (res.data.length === 0) {
3188
+ console.log(`No wins recorded for ${d}.`);
3189
+ return;
3190
+ }
3191
+ console.log(`Wins for ${d}:`);
3192
+ for (const w of res.data) {
3193
+ console.log(` - ${w.content} (${formatDate(w.createdAt ?? w.created_at ?? null)})`);
3194
+ }
3195
+ } catch (err) {
3196
+ printError(err instanceof Error ? err.message : String(err));
3197
+ process.exitCode = 1;
3198
+ }
3199
+ });
3200
+
3201
+ // src/commands/plan.ts
3202
+ function todayStr2() {
3203
+ return new Date().toISOString().slice(0, 10);
3204
+ }
3205
+ function tomorrowStr() {
3206
+ const d = new Date;
3207
+ d.setDate(d.getDate() + 1);
3208
+ return d.toISOString().slice(0, 10);
3209
+ }
3210
+ function printPlan(plan) {
3211
+ console.log(`Date: ${plan.planDate ?? plan.plan_date ?? "-"}`);
3212
+ console.log(`Wake Time: ${plan.wakeTime ?? plan.wake_time ?? "-"}`);
3213
+ const mitDone = plan.mitDone ?? plan.mit_done ?? false;
3214
+ const p1Done = plan.p1Done ?? plan.p1_done ?? false;
3215
+ const p2Done = plan.p2Done ?? plan.p2_done ?? false;
3216
+ const mitStatus = mitDone ? source_default.green("done") : source_default.yellow("pending");
3217
+ const p1Status = p1Done ? source_default.green("done") : source_default.yellow("pending");
3218
+ const p2Status = p2Done ? source_default.green("done") : source_default.yellow("pending");
3219
+ const mitTaskId = plan.mitTaskId ?? plan.mit_task_id;
3220
+ const p1TaskId = plan.p1TaskId ?? plan.p1_task_id;
3221
+ const p2TaskId = plan.p2TaskId ?? plan.p2_task_id;
3222
+ console.log(`MIT: ${mitTaskId?.slice(0, 8) ?? "-"} [${mitStatus}]`);
3223
+ console.log(`P1: ${p1TaskId?.slice(0, 8) ?? "-"} [${p1Status}]`);
3224
+ console.log(`P2: ${p2TaskId?.slice(0, 8) ?? "-"} [${p2Status}]`);
3225
+ if (plan.schedule.length > 0) {
3226
+ console.log("Schedule:");
3227
+ for (const block of plan.schedule) {
3228
+ console.log(` ${block.start}-${block.end} ${block.label} (${block.type})`);
3229
+ }
3230
+ }
3231
+ if (plan.overflow.length > 0) {
3232
+ console.log(`Overflow: ${plan.overflow.join(", ")}`);
3233
+ }
3234
+ }
3235
+ var planCommand = new Command("plan").description("Manage day plans");
3236
+ planCommand.command("today").description("Show today's plan").action(async () => {
3237
+ try {
3238
+ const client = createClient();
3239
+ const res = await client.get(`/api/v1/plans/${todayStr2()}`);
3240
+ if (isJsonMode()) {
3241
+ printJson(res);
3242
+ return;
3243
+ }
3244
+ printPlan(res.data);
3245
+ } catch (err) {
3246
+ printError(err instanceof Error ? err.message : String(err));
3247
+ process.exitCode = 1;
3248
+ }
3249
+ });
3250
+ planCommand.command("tomorrow").description("Show tomorrow's plan").action(async () => {
3251
+ try {
3252
+ const client = createClient();
3253
+ const res = await client.get(`/api/v1/plans/${tomorrowStr()}`);
3254
+ if (isJsonMode()) {
3255
+ printJson(res);
3256
+ return;
3257
+ }
3258
+ printPlan(res.data);
3259
+ } catch (err) {
3260
+ printError(err instanceof Error ? err.message : String(err));
3261
+ process.exitCode = 1;
3262
+ }
3263
+ });
3264
+ planCommand.command("set <date>").description("Create or update a day plan").option("-w, --wake <time>", "Wake time (HH:MM)").option("--mit <taskId>", "MIT task ID").option("--p1 <taskId>", "P1 task ID").option("--p2 <taskId>", "P2 task ID").action(async (date, opts) => {
3265
+ try {
3266
+ const client = createClient();
3267
+ const body = {};
3268
+ if (opts.wake)
3269
+ body.wakeTime = opts.wake;
3270
+ if (opts.mit)
3271
+ body.mitTaskId = opts.mit;
3272
+ if (opts.p1)
3273
+ body.p1TaskId = opts.p1;
3274
+ if (opts.p2)
3275
+ body.p2TaskId = opts.p2;
3276
+ const res = await client.put(`/api/v1/plans/${date}`, body);
3277
+ if (isJsonMode()) {
3278
+ printJson(res);
3279
+ return;
3280
+ }
3281
+ printSuccess(`Day plan saved for ${date}.`);
3282
+ } catch (err) {
3283
+ printError(err instanceof Error ? err.message : String(err));
3284
+ process.exitCode = 1;
3285
+ }
3286
+ });
3287
+ planCommand.command("complete-mit").description("Mark MIT as done for today").action(async () => {
3288
+ try {
3289
+ const client = createClient();
3290
+ const res = await client.patch(`/api/v1/plans/${todayStr2()}`, { mitDone: true });
3291
+ if (isJsonMode()) {
3292
+ printJson(res);
3293
+ return;
3294
+ }
3295
+ printSuccess("MIT marked as done.");
3296
+ } catch (err) {
3297
+ printError(err instanceof Error ? err.message : String(err));
3298
+ process.exitCode = 1;
3299
+ }
3300
+ });
3301
+ planCommand.command("complete-p1").description("Mark P1 as done for today").action(async () => {
3302
+ try {
3303
+ const client = createClient();
3304
+ const res = await client.patch(`/api/v1/plans/${todayStr2()}`, { p1Done: true });
3305
+ if (isJsonMode()) {
3306
+ printJson(res);
3307
+ return;
3308
+ }
3309
+ printSuccess("P1 marked as done.");
3310
+ } catch (err) {
3311
+ printError(err instanceof Error ? err.message : String(err));
3312
+ process.exitCode = 1;
3313
+ }
3314
+ });
3315
+ planCommand.command("complete-p2").description("Mark P2 as done for today").action(async () => {
3316
+ try {
3317
+ const client = createClient();
3318
+ const res = await client.patch(`/api/v1/plans/${todayStr2()}`, { p2Done: true });
3319
+ if (isJsonMode()) {
3320
+ printJson(res);
3321
+ return;
3322
+ }
3323
+ printSuccess("P2 marked as done.");
3324
+ } catch (err) {
3325
+ printError(err instanceof Error ? err.message : String(err));
3326
+ process.exitCode = 1;
3327
+ }
3328
+ });
3329
+
3330
+ // src/commands/week.ts
3331
+ function currentWeekStart() {
3332
+ const now = new Date;
3333
+ const day = now.getDay();
3334
+ const diff = now.getDate() - day + (day === 0 ? -6 : 1);
3335
+ const monday = new Date(now);
3336
+ monday.setDate(diff);
3337
+ return monday.toISOString().slice(0, 10);
3338
+ }
3339
+ function printWeeklyPlan(plan) {
3340
+ console.log(`Week: ${plan.weekStart ?? plan.week_start ?? "-"}`);
3341
+ console.log(`Theme: ${plan.theme ?? "-"}`);
3342
+ console.log(`Review Score: ${plan.reviewScore ?? plan.review_score ?? "-"}`);
3343
+ if (plan.goals.length > 0) {
3344
+ console.log("Goals:");
3345
+ for (const g of plan.goals) {
3346
+ const status = g.status ? ` [${g.status}]` : "";
3347
+ console.log(` - ${g.title}${status}`);
3348
+ }
3349
+ }
3350
+ }
3351
+ var weekCommand = new Command("week").description("Manage weekly plans").argument("[week-start]", "Week start date (YYYY-MM-DD, default current Monday)").action(async (weekStart) => {
3352
+ try {
3353
+ const client = createClient();
3354
+ const ws = weekStart ?? currentWeekStart();
3355
+ const res = await client.get(`/api/v1/weekly-plans/${ws}`);
3356
+ if (isJsonMode()) {
3357
+ printJson(res);
3358
+ return;
3359
+ }
3360
+ printWeeklyPlan(res.data);
3361
+ } catch (err) {
3362
+ printError(err instanceof Error ? err.message : String(err));
3363
+ process.exitCode = 1;
3364
+ }
3365
+ });
3366
+ weekCommand.command("create").description("Create a weekly plan for this week").option("-t, --theme <theme>", "Week theme").action(async (opts) => {
3367
+ try {
3368
+ const client = createClient();
3369
+ const body = {};
3370
+ if (opts.theme)
3371
+ body.theme = opts.theme;
3372
+ const ws = currentWeekStart();
3373
+ const res = await client.put(`/api/v1/weekly-plans/${ws}`, body);
3374
+ if (isJsonMode()) {
3375
+ printJson(res);
3376
+ return;
3377
+ }
3378
+ printSuccess(`Weekly plan created for ${ws}.`);
3379
+ } catch (err) {
3380
+ printError(err instanceof Error ? err.message : String(err));
3381
+ process.exitCode = 1;
3382
+ }
3383
+ });
3384
+ weekCommand.command("score <score>").description("Set the review score for this week (1-10)").action(async (score) => {
3385
+ try {
3386
+ const client = createClient();
3387
+ const ws = currentWeekStart();
3388
+ const res = await client.patch(`/api/v1/weekly-plans/${ws}`, {
3389
+ reviewScore: parseInt(score, 10)
3390
+ });
3391
+ if (isJsonMode()) {
3392
+ printJson(res);
3393
+ return;
3394
+ }
3395
+ printSuccess(`Week score set to ${score}.`);
3396
+ } catch (err) {
3397
+ printError(err instanceof Error ? err.message : String(err));
3398
+ process.exitCode = 1;
3399
+ }
3400
+ });
3401
+
3402
+ // src/commands/capture.ts
3403
+ var ideaCommand = new Command("idea").description("Capture an idea").argument("<content>", "Idea content").option("-a, --actionability <level>", "Actionability level (high, medium, low)").action(async (content, opts) => {
3404
+ try {
3405
+ const client = createClient();
3406
+ const body = { content };
3407
+ if (opts.actionability)
3408
+ body.actionability = opts.actionability;
3409
+ const res = await client.post("/api/v1/ideas", body);
3410
+ if (isJsonMode()) {
3411
+ printJson(res);
3412
+ return;
3413
+ }
3414
+ printSuccess(`Idea captured (${shortId(res.data)}).`);
3415
+ } catch (err) {
3416
+ printError(err instanceof Error ? err.message : String(err));
3417
+ process.exitCode = 1;
3418
+ }
3419
+ });
3420
+ var thoughtCommand = new Command("thought").description("Capture a thought").argument("<content>", "Thought content").option("-t, --title <title>", "Optional title").action(async (content, opts) => {
3421
+ try {
3422
+ const client = createClient();
3423
+ const body = { content };
3424
+ if (opts.title)
3425
+ body.title = opts.title;
3426
+ const res = await client.post("/api/v1/thoughts", body);
3427
+ if (isJsonMode()) {
3428
+ printJson(res);
3429
+ return;
3430
+ }
3431
+ printSuccess(`Thought captured (${shortId(res.data)}).`);
3432
+ } catch (err) {
3433
+ printError(err instanceof Error ? err.message : String(err));
3434
+ process.exitCode = 1;
3435
+ }
3436
+ });
3437
+ var winCommand = new Command("win").description("Record a win").argument("<content>", "Win description").action(async (content) => {
3438
+ try {
3439
+ const client = createClient();
3440
+ const res = await client.post("/api/v1/wins", { content });
3441
+ if (isJsonMode()) {
3442
+ printJson(res);
3443
+ return;
3444
+ }
3445
+ printSuccess(`Win recorded (${shortId(res.data)}).`);
3446
+ } catch (err) {
3447
+ printError(err instanceof Error ? err.message : String(err));
3448
+ process.exitCode = 1;
3449
+ }
3450
+ });
3451
+ var resourceCommand = new Command("resource").description("Save a resource").argument("<title>", "Resource title").option("-u, --url <url>", "URL").option("-t, --type <type>", "Type (article, tool, book, video, other)").action(async (title, opts) => {
3452
+ try {
3453
+ const client = createClient();
3454
+ const body = { title };
3455
+ if (opts.url)
3456
+ body.url = opts.url;
3457
+ if (opts.type)
3458
+ body.type = opts.type;
3459
+ const res = await client.post("/api/v1/resources", body);
3460
+ if (isJsonMode()) {
3461
+ printJson(res);
3462
+ return;
3463
+ }
3464
+ printSuccess(`Resource saved: ${res.data.title} (${shortId(res.data)}).`);
3465
+ } catch (err) {
3466
+ printError(err instanceof Error ? err.message : String(err));
3467
+ process.exitCode = 1;
3468
+ }
3469
+ });
3470
+
3471
+ // src/commands/review.ts
3472
+ var reviewCommand = new Command("review").description("Manage reviews");
3473
+ reviewCommand.command("list").description("List reviews").option("-t, --type <type>", "Filter by type (daily, weekly, monthly, quarterly)").action(async (opts) => {
3474
+ try {
3475
+ const client = createClient();
3476
+ const params = {};
3477
+ if (opts.type)
3478
+ params.reviewType = opts.type;
3479
+ const res = await client.get("/api/v1/reviews", params);
3480
+ if (isJsonMode()) {
3481
+ printJson(res);
3482
+ return;
3483
+ }
3484
+ if (res.data.length === 0) {
3485
+ console.log("No reviews found.");
3486
+ return;
3487
+ }
3488
+ const rows = res.data.map((r) => [
3489
+ shortId(r),
3490
+ r.reviewType ?? r.review_type ?? "-",
3491
+ `${r.periodStart ?? r.period_start ?? "-"} - ${r.periodEnd ?? r.period_end ?? "-"}`,
3492
+ r.score !== null ? String(r.score) : "-",
3493
+ formatDate(r.createdAt ?? r.created_at ?? null)
3494
+ ]);
3495
+ printTable(["ID", "Type", "Period", "Score", "Created"], rows);
3496
+ } catch (err) {
3497
+ printError(err instanceof Error ? err.message : String(err));
3498
+ process.exitCode = 1;
3499
+ }
3500
+ });
3501
+ reviewCommand.command("daily").description("Trigger a daily review and show results").action(async () => {
3502
+ try {
3503
+ const client = createClient();
3504
+ const res = await client.post("/api/v1/triggers/daily-review");
3505
+ if (isJsonMode()) {
3506
+ printJson(res);
3507
+ return;
3508
+ }
3509
+ const d = res.data;
3510
+ console.log(`=== Daily Review ===
3511
+ `);
3512
+ if (d.tasks_completed_today.length > 0) {
3513
+ console.log("Tasks completed today:");
3514
+ for (const t of d.tasks_completed_today) {
3515
+ console.log(` - ${t.title}`);
3516
+ }
3517
+ console.log();
3518
+ }
3519
+ if (d.wins_today.length > 0) {
3520
+ console.log("Wins today:");
3521
+ for (const w of d.wins_today) {
3522
+ console.log(` - ${w.content}`);
3523
+ }
3524
+ console.log();
3525
+ }
3526
+ if (d.journal) {
3527
+ console.log(`Journal MIT: ${d.journal.mit ?? "-"}`);
3528
+ console.log(`Journal P1: ${d.journal.p1 ?? "-"}`);
3529
+ console.log(`Journal P2: ${d.journal.p2 ?? "-"}`);
3530
+ }
3531
+ } catch (err) {
3532
+ printError(err instanceof Error ? err.message : String(err));
3533
+ process.exitCode = 1;
3534
+ }
3535
+ });
3536
+ reviewCommand.command("weekly").description("Trigger a weekly review and show results").action(async () => {
3537
+ try {
3538
+ const client = createClient();
3539
+ const res = await client.post("/api/v1/triggers/weekly-review");
3540
+ if (isJsonMode()) {
3541
+ printJson(res);
3542
+ return;
3543
+ }
3544
+ const d = res.data;
3545
+ console.log(`=== Weekly Review ===
3546
+ `);
3547
+ if (d.weekly_plan) {
3548
+ console.log(`Theme: ${d.weekly_plan.theme ?? "-"}`);
3549
+ console.log(`Score: ${d.weekly_plan.reviewScore ?? d.weekly_plan.review_score ?? "-"}`);
3550
+ console.log();
3551
+ }
3552
+ console.log(`Tasks completed: ${d.tasks_completed.length}`);
3553
+ console.log(`Journal entries: ${d.journals.length}`);
3554
+ console.log(`Wins: ${d.wins.length}`);
3555
+ console.log(`Goals tracked: ${d.goals.length}`);
3556
+ } catch (err) {
3557
+ printError(err instanceof Error ? err.message : String(err));
3558
+ process.exitCode = 1;
3559
+ }
3560
+ });
3561
+ reviewCommand.command("show <id>").description("Show review details").action(async (id) => {
3562
+ try {
3563
+ const client = createClient();
3564
+ const res = await client.get(`/api/v1/reviews/${id}`);
3565
+ if (isJsonMode()) {
3566
+ printJson(res);
3567
+ return;
3568
+ }
3569
+ const r = res.data;
3570
+ console.log(`ID: ${getId(r)}`);
3571
+ console.log(`Type: ${r.reviewType ?? r.review_type ?? "-"}`);
3572
+ console.log(`Period: ${r.periodStart ?? r.period_start ?? "-"} - ${r.periodEnd ?? r.period_end ?? "-"}`);
3573
+ console.log(`Score: ${r.score ?? "-"}`);
3574
+ console.log(`Created: ${formatDate(r.createdAt ?? r.created_at ?? null)}`);
3575
+ console.log("Content:");
3576
+ console.log(JSON.stringify(r.content, null, 2));
3577
+ } catch (err) {
3578
+ printError(err instanceof Error ? err.message : String(err));
3579
+ process.exitCode = 1;
3580
+ }
3581
+ });
3582
+
3583
+ // src/commands/reminder.ts
3584
+ var reminderCommand = new Command("reminder").description("Manage reminders");
3585
+ reminderCommand.command("list").description("List reminders").option("-s, --status <status>", "Filter by status (pending, delivered, snoozed, done)").action(async (opts) => {
3586
+ try {
3587
+ const client = createClient();
3588
+ const params = {};
3589
+ if (opts.status)
3590
+ params.status = opts.status;
3591
+ const res = await client.get("/api/v1/reminders", params);
3592
+ if (isJsonMode()) {
3593
+ printJson(res);
3594
+ return;
3595
+ }
3596
+ if (res.data.length === 0) {
3597
+ console.log("No reminders found.");
3598
+ return;
3599
+ }
3600
+ const rows = res.data.map((r) => [
3601
+ shortId(r),
3602
+ r.title,
3603
+ r.status,
3604
+ formatDate(r.scheduledAt ?? r.scheduled_at ?? null),
3605
+ String(r.snoozeCount ?? r.snooze_count ?? 0)
3606
+ ]);
3607
+ printTable(["ID", "Title", "Status", "Scheduled", "Snoozed"], rows);
3608
+ } catch (err) {
3609
+ printError(err instanceof Error ? err.message : String(err));
3610
+ process.exitCode = 1;
3611
+ }
3612
+ });
3613
+ reminderCommand.command("create <title>").description("Create a reminder").option("-a, --at <datetime>", "Scheduled time (ISO datetime)").option("-b, --body <body>", "Reminder body").action(async (title, opts) => {
3614
+ try {
3615
+ const client = createClient();
3616
+ const body = { title };
3617
+ if (opts.at)
3618
+ body.scheduledAt = opts.at;
3619
+ if (opts.body)
3620
+ body.body = opts.body;
3621
+ const res = await client.post("/api/v1/reminders", body);
3622
+ if (isJsonMode()) {
3623
+ printJson(res);
3624
+ return;
3625
+ }
3626
+ printSuccess(`Reminder created: ${res.data.title} (${shortId(res.data)})`);
3627
+ } catch (err) {
3628
+ printError(err instanceof Error ? err.message : String(err));
3629
+ process.exitCode = 1;
3630
+ }
3631
+ });
3632
+ reminderCommand.command("snooze <id>").description("Snooze a reminder").option("-m, --minutes <min>", "Snooze duration in minutes (default 60)", "60").action(async (id, opts) => {
3633
+ try {
3634
+ const client = createClient();
3635
+ const res = await client.post(`/api/v1/reminders/${id}/snooze`, {
3636
+ minutes: parseInt(opts.minutes, 10)
3637
+ });
3638
+ if (isJsonMode()) {
3639
+ printJson(res);
3640
+ return;
3641
+ }
3642
+ printSuccess(`Reminder snoozed for ${opts.minutes} minutes.`);
3643
+ } catch (err) {
3644
+ printError(err instanceof Error ? err.message : String(err));
3645
+ process.exitCode = 1;
3646
+ }
3647
+ });
3648
+ reminderCommand.command("done <id>").description("Mark a reminder as done").action(async (id) => {
3649
+ try {
3650
+ const client = createClient();
3651
+ const res = await client.patch(`/api/v1/reminders/${id}`, { status: "done" });
3652
+ if (isJsonMode()) {
3653
+ printJson(res);
3654
+ return;
3655
+ }
3656
+ printSuccess(`Reminder marked as done: ${res.data.title}`);
3657
+ } catch (err) {
3658
+ printError(err instanceof Error ? err.message : String(err));
3659
+ process.exitCode = 1;
3660
+ }
3661
+ });
3662
+
3663
+ // src/commands/search.ts
3664
+ var searchCommand = new Command("search").description("Search across all entities").argument("<query>", "Search query").option("-t, --type <type>", "Filter by type (tasks,goals,ideas,journal,resources)").action(async (query, opts) => {
3665
+ try {
3666
+ const client = createClient();
3667
+ const params = { q: query };
3668
+ if (opts.type)
3669
+ params.type = opts.type;
3670
+ const res = await client.get("/api/v1/search", params);
3671
+ if (isJsonMode()) {
3672
+ printJson(res);
3673
+ return;
3674
+ }
3675
+ const d = res.data;
3676
+ let found = false;
3677
+ if (d.tasks.length > 0) {
3678
+ found = true;
3679
+ console.log(`
3680
+ Tasks:`);
3681
+ printTable(["ID", "Title", "Status", "Due"], d.tasks.map((t) => [shortId(t), t.title, t.status, formatDate(t.dueDate ?? t.due_date ?? null)]));
3682
+ }
3683
+ if (d.goals.length > 0) {
3684
+ found = true;
3685
+ console.log(`
3686
+ Goals:`);
3687
+ printTable(["ID", "Title", "Status", "Quarter"], d.goals.map((g) => [shortId(g), g.title, g.status, g.quarter ?? "-"]));
3688
+ }
3689
+ if (d.ideas.length > 0) {
3690
+ found = true;
3691
+ console.log(`
3692
+ Ideas:`);
3693
+ printTable(["ID", "Content"], d.ideas.map((i) => [shortId(i), i.content.slice(0, 80)]));
3694
+ }
3695
+ if (d.journal.length > 0) {
3696
+ found = true;
3697
+ console.log(`
3698
+ Journal:`);
3699
+ printTable(["ID", "Date", "Notes"], d.journal.map((j) => [shortId(j), j.entryDate ?? j.entry_date ?? "-", (j.notes ?? "").slice(0, 60)]));
3700
+ }
3701
+ if (d.resources.length > 0) {
3702
+ found = true;
3703
+ console.log(`
3704
+ Resources:`);
3705
+ printTable(["ID", "Title", "Type"], d.resources.map((r) => [shortId(r), r.title, r.type ?? "-"]));
3706
+ }
3707
+ if (!found) {
3708
+ console.log("No results found.");
3709
+ }
3710
+ } catch (err) {
3711
+ printError(err instanceof Error ? err.message : String(err));
3712
+ process.exitCode = 1;
3713
+ }
3714
+ });
3715
+
3716
+ // src/commands/undo.ts
3717
+ var undoCommand = new Command("undo").description("Undo the last mutation").action(async () => {
3718
+ try {
3719
+ const client = createClient();
3720
+ const res = await client.post("/api/v1/mutations/undo");
3721
+ if (isJsonMode()) {
3722
+ printJson(res);
3723
+ return;
3724
+ }
3725
+ const entry = res.data;
3726
+ const table = entry.tableName ?? entry.table ?? "unknown";
3727
+ const recordId = entry.recordId ?? entry.record_id ?? "";
3728
+ printSuccess(`Undid ${entry.undone} on ${table} (record ${recordId.slice(0, 8)}).`);
3729
+ } catch (err) {
3730
+ printError(err instanceof Error ? err.message : String(err));
3731
+ process.exitCode = 1;
3732
+ }
3733
+ });
3734
+
3735
+ // src/commands/trigger.ts
3736
+ var VALID_TRIGGERS = [
3737
+ "morning-briefing",
3738
+ "daily-review",
3739
+ "weekly-review",
3740
+ "overdue-triage",
3741
+ "reminder-check",
3742
+ "goal-health"
3743
+ ];
3744
+ var triggerCommand = new Command("trigger").description("Fire a named trigger").argument("<name>", `Trigger name (${VALID_TRIGGERS.join(", ")})`).action(async (name) => {
3745
+ try {
3746
+ if (!VALID_TRIGGERS.includes(name)) {
3747
+ printError(`Unknown trigger: ${name}. Valid triggers: ${VALID_TRIGGERS.join(", ")}`);
3748
+ process.exitCode = 1;
3749
+ return;
3750
+ }
3751
+ const client = createClient();
3752
+ const res = await client.post(`/api/v1/triggers/${name}`);
3753
+ if (isJsonMode()) {
3754
+ printJson(res);
3755
+ return;
3756
+ }
3757
+ printSuccess(`Trigger '${name}' executed.`);
3758
+ if (res.data) {
3759
+ console.log(JSON.stringify(res.data, null, 2));
3760
+ }
3761
+ } catch (err) {
3762
+ printError(err instanceof Error ? err.message : String(err));
3763
+ process.exitCode = 1;
3764
+ }
3765
+ });
3766
+
3767
+ // src/commands/dashboard.ts
3768
+ var ALL_PRESETS = ["default", "solopreneur", "content-creator", "developer", "executive", "minimalist", "journaler"];
3769
+ var PAGE_PRESETS = {
3770
+ today: ALL_PRESETS,
3771
+ tasks: ALL_PRESETS,
3772
+ projects: ALL_PRESETS,
3773
+ goals: ALL_PRESETS,
3774
+ journal: ALL_PRESETS,
3775
+ ideas: ALL_PRESETS,
3776
+ plan: ALL_PRESETS,
3777
+ reviews: ALL_PRESETS
3778
+ };
3779
+ var dashboardCommand = new Command("dashboard").description("Configure dashboard layout and presets");
3780
+ dashboardCommand.command("config").description("Show current dashboard configuration").action(async () => {
3781
+ try {
3782
+ const client = createClient();
3783
+ const res = await client.get("/api/v1/dashboard/config");
3784
+ if (isJsonMode()) {
3785
+ printJson(res);
3786
+ return;
3787
+ }
3788
+ const config = res.data;
3789
+ console.log(`Nav Mode: ${config.navMode}`);
3790
+ console.log(`Nav Order: ${config.navOrder.join(", ")}`);
3791
+ console.log(`Hidden Pages: ${config.navHidden.length > 0 ? config.navHidden.join(", ") : "(none)"}`);
3792
+ const presetEntries = Object.entries(config.pagePresets);
3793
+ if (presetEntries.length > 0) {
3794
+ console.log(`Page Presets:`);
3795
+ for (const [page, preset] of presetEntries) {
3796
+ console.log(` ${page}: ${preset}`);
3797
+ }
3798
+ } else {
3799
+ console.log(`Page Presets: (none)`);
3800
+ }
3801
+ console.log(`Custom Theme: ${config.customTheme ? "yes" : "(none)"}`);
3802
+ console.log(`Persisted: ${config._id ? "yes" : "no (using defaults)"}`);
3803
+ } catch (err) {
3804
+ printError(err instanceof Error ? err.message : String(err));
3805
+ process.exitCode = 1;
3806
+ }
3807
+ });
3808
+ dashboardCommand.command("nav-mode <mode>").description("Set navigation mode (sidebar or header)").action(async (mode) => {
3809
+ try {
3810
+ if (mode !== "sidebar" && mode !== "header") {
3811
+ printError('Mode must be "sidebar" or "header"');
3812
+ process.exitCode = 1;
3813
+ return;
3814
+ }
3815
+ const client = createClient();
3816
+ const res = await client.post("/api/v1/dashboard/nav-mode", { mode });
3817
+ if (isJsonMode()) {
3818
+ printJson(res);
3819
+ return;
3820
+ }
3821
+ printSuccess(`Navigation mode set to "${mode}"`);
3822
+ } catch (err) {
3823
+ printError(err instanceof Error ? err.message : String(err));
3824
+ process.exitCode = 1;
3825
+ }
3826
+ });
3827
+ dashboardCommand.command("nav-order <pages...>").description("Set sidebar page order").action(async (pages) => {
3828
+ try {
3829
+ const client = createClient();
3830
+ const res = await client.post("/api/v1/dashboard/nav-order", { order: pages });
3831
+ if (isJsonMode()) {
3832
+ printJson(res);
3833
+ return;
3834
+ }
3835
+ printSuccess(`Navigation order set to: ${pages.join(", ")}`);
3836
+ } catch (err) {
3837
+ printError(err instanceof Error ? err.message : String(err));
3838
+ process.exitCode = 1;
3839
+ }
3840
+ });
3841
+ dashboardCommand.command("hide <page>").description("Hide a page from navigation").action(async (page) => {
3842
+ try {
3843
+ const client = createClient();
3844
+ const res = await client.post("/api/v1/dashboard/visibility", {
3845
+ page,
3846
+ visible: false
3847
+ });
3848
+ if (isJsonMode()) {
3849
+ printJson(res);
3850
+ return;
3851
+ }
3852
+ printSuccess(`Page "${page}" is now hidden`);
3853
+ } catch (err) {
3854
+ printError(err instanceof Error ? err.message : String(err));
3855
+ process.exitCode = 1;
3856
+ }
3857
+ });
3858
+ dashboardCommand.command("show <page>").description("Show a hidden page in navigation").action(async (page) => {
3859
+ try {
3860
+ const client = createClient();
3861
+ const res = await client.post("/api/v1/dashboard/visibility", {
3862
+ page,
3863
+ visible: true
3864
+ });
3865
+ if (isJsonMode()) {
3866
+ printJson(res);
3867
+ return;
3868
+ }
3869
+ printSuccess(`Page "${page}" is now visible`);
3870
+ } catch (err) {
3871
+ printError(err instanceof Error ? err.message : String(err));
3872
+ process.exitCode = 1;
3873
+ }
3874
+ });
3875
+ dashboardCommand.command("preset <page> <preset>").description("Set page preset (e.g., today solopreneur)").action(async (page, preset) => {
3876
+ try {
3877
+ const known = PAGE_PRESETS[page];
3878
+ if (known && !known.includes(preset)) {
3879
+ printError(`Unknown preset "${preset}" for page "${page}". Known presets: ${known.join(", ")}`);
3880
+ process.exitCode = 1;
3881
+ return;
3882
+ }
3883
+ const client = createClient();
3884
+ const res = await client.post("/api/v1/dashboard/preset", { page, preset });
3885
+ if (isJsonMode()) {
3886
+ printJson(res);
3887
+ return;
3888
+ }
3889
+ printSuccess(`Preset for "${page}" set to "${preset}"`);
3890
+ } catch (err) {
3891
+ printError(err instanceof Error ? err.message : String(err));
3892
+ process.exitCode = 1;
3893
+ }
3894
+ });
3895
+ dashboardCommand.command("presets <page>").description("List available presets for a page").action(async (page) => {
3896
+ try {
3897
+ const presets = PAGE_PRESETS[page];
3898
+ if (isJsonMode()) {
3899
+ printJson({ page, presets: presets ?? [] });
3900
+ return;
3901
+ }
3902
+ if (!presets || presets.length === 0) {
3903
+ console.log(`No known presets for page "${page}".`);
3904
+ return;
3905
+ }
3906
+ const client = createClient();
3907
+ const res = await client.get("/api/v1/dashboard/config");
3908
+ const activePreset = res.data.pagePresets[page];
3909
+ const rows = presets.map((p) => [
3910
+ p,
3911
+ p === activePreset ? "active" : ""
3912
+ ]);
3913
+ printTable(["Preset", "Status"], rows);
3914
+ } catch (err) {
3915
+ printError(err instanceof Error ? err.message : String(err));
3916
+ process.exitCode = 1;
3917
+ }
3918
+ });
3919
+ dashboardCommand.command("reset").description("Reset dashboard to defaults").action(async () => {
3920
+ try {
3921
+ const client = createClient();
3922
+ const res = await client.post("/api/v1/dashboard/reset");
3923
+ if (isJsonMode()) {
3924
+ printJson(res);
3925
+ return;
3926
+ }
3927
+ printSuccess("Dashboard configuration reset to defaults");
3928
+ } catch (err) {
3929
+ printError(err instanceof Error ? err.message : String(err));
3930
+ process.exitCode = 1;
3931
+ }
3932
+ });
3933
+
3934
+ // src/index.ts
3935
+ var program2 = new Command;
3936
+ program2.name("lifeos").description("Personal Life Operating System").version("0.1.0").option("--json", "Output results as JSON");
3937
+ program2.command("whoami").description("Show current authenticated user").action(async () => {
3938
+ try {
3939
+ const client = createClient();
3940
+ const res = await client.get("/api/v1/auth/me");
3941
+ if (isJsonMode()) {
3942
+ printJson(res);
3943
+ return;
3944
+ }
3945
+ const u = res.data;
3946
+ console.log(`ID: ${u.id}`);
3947
+ console.log(`Email: ${u.email}`);
3948
+ console.log(`Name: ${u.name ?? "-"}`);
3949
+ console.log(`Timezone: ${u.timezone}`);
3950
+ } catch (err) {
3951
+ printError(err instanceof Error ? err.message : String(err));
3952
+ process.exitCode = 1;
3953
+ }
3954
+ });
3955
+ program2.addCommand(configCommand);
3956
+ program2.addCommand(taskCommand);
3957
+ program2.addCommand(projectCommand);
3958
+ program2.addCommand(goalCommand);
3959
+ program2.addCommand(journalCommand);
3960
+ program2.addCommand(planCommand);
3961
+ program2.addCommand(weekCommand);
3962
+ program2.addCommand(ideaCommand);
3963
+ program2.addCommand(thoughtCommand);
3964
+ program2.addCommand(winCommand);
3965
+ program2.addCommand(resourceCommand);
3966
+ program2.addCommand(reviewCommand);
3967
+ program2.addCommand(reminderCommand);
3968
+ program2.addCommand(searchCommand);
3969
+ program2.addCommand(undoCommand);
3970
+ program2.addCommand(triggerCommand);
3971
+ program2.addCommand(dashboardCommand);
3972
+ program2.parseAsync(process.argv);