@fml-inc/fml 0.0.25 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,9 +1,15 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ config,
4
+ loadUnifiedConfig,
5
+ saveUnifiedConfig
6
+ } from "./chunk-NLFKYSN7.js";
2
7
  import {
3
8
  createApiClient,
4
9
  ensureNativeModules,
5
10
  getAuthenticatedClient
6
- } from "./chunk-WXDGVKXK.js";
11
+ } from "./chunk-ND2YSPQ6.js";
12
+ import "./chunk-UALBZA5X.js";
7
13
  import {
8
14
  AUTH_STORE_PATH,
9
15
  CONVEX_URL,
@@ -24,13 +30,16 @@ import {
24
30
  import {
25
31
  handleStart,
26
32
  handleStop,
27
- panopticonExec,
28
33
  parsePanopticonRunning
29
- } from "./chunk-EL2WSQBR.js";
34
+ } from "./chunk-YIWT7BWN.js";
35
+ import {
36
+ panopticonExec
37
+ } from "./chunk-ZA4RG25C.js";
30
38
  import {
31
39
  FML_DATA_DIR,
32
40
  FML_LOG_DIR
33
41
  } from "./chunk-4YEAQJPF.js";
42
+ import "./chunk-2CRFCFE4.js";
34
43
  import "./chunk-PZ5AY32C.js";
35
44
 
36
45
  // src/cli.ts
@@ -39,8 +48,1737 @@ import { Command } from "commander";
39
48
  // src/commands/doctor.ts
40
49
  import ora from "ora";
41
50
  import pc from "picocolors";
42
- import { loadSyncConfig } from "@fml-inc/panopticon/sync";
43
- import { syncPending } from "@fml-inc/panopticon/api";
51
+
52
+ // node_modules/.pnpm/@fml-inc+panopticon@0.2.2/node_modules/@fml-inc/panopticon/dist/chunk-6NMLAGHC.js
53
+ import os from "os";
54
+ import path from "path";
55
+ function urlToObject(url) {
56
+ return {
57
+ href: url.href,
58
+ protocol: url.protocol,
59
+ username: url.username,
60
+ password: url.password,
61
+ host: url.host,
62
+ hostname: url.hostname,
63
+ port: url.port,
64
+ pathname: url.pathname,
65
+ search: url.search,
66
+ searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
67
+ hash: url.hash,
68
+ origin: url.origin
69
+ };
70
+ }
71
+ var prettyLogStyles = {
72
+ reset: [0, 0],
73
+ bold: [1, 22],
74
+ dim: [2, 22],
75
+ italic: [3, 23],
76
+ underline: [4, 24],
77
+ overline: [53, 55],
78
+ inverse: [7, 27],
79
+ hidden: [8, 28],
80
+ strikethrough: [9, 29],
81
+ black: [30, 39],
82
+ red: [31, 39],
83
+ green: [32, 39],
84
+ yellow: [33, 39],
85
+ blue: [34, 39],
86
+ magenta: [35, 39],
87
+ cyan: [36, 39],
88
+ white: [37, 39],
89
+ blackBright: [90, 39],
90
+ redBright: [91, 39],
91
+ greenBright: [92, 39],
92
+ yellowBright: [93, 39],
93
+ blueBright: [94, 39],
94
+ magentaBright: [95, 39],
95
+ cyanBright: [96, 39],
96
+ whiteBright: [97, 39],
97
+ bgBlack: [40, 49],
98
+ bgRed: [41, 49],
99
+ bgGreen: [42, 49],
100
+ bgYellow: [43, 49],
101
+ bgBlue: [44, 49],
102
+ bgMagenta: [45, 49],
103
+ bgCyan: [46, 49],
104
+ bgWhite: [47, 49],
105
+ bgBlackBright: [100, 49],
106
+ bgRedBright: [101, 49],
107
+ bgGreenBright: [102, 49],
108
+ bgYellowBright: [103, 49],
109
+ bgBlueBright: [104, 49],
110
+ bgMagentaBright: [105, 49],
111
+ bgCyanBright: [106, 49],
112
+ bgWhiteBright: [107, 49]
113
+ };
114
+ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
115
+ const templateString = String(template);
116
+ const ansiColorWrap = (placeholderValue, code) => `\x1B[${code[0]}m${placeholderValue}\x1B[${code[1]}m`;
117
+ const styleWrap = (value, style) => {
118
+ if (style != null && typeof style === "string") {
119
+ return ansiColorWrap(value, prettyLogStyles[style]);
120
+ } else if (style != null && Array.isArray(style)) {
121
+ return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
122
+ } else {
123
+ if (style != null && style[value.trim()] != null) {
124
+ return styleWrap(value, style[value.trim()]);
125
+ } else if (style != null && style["*"] != null) {
126
+ return styleWrap(value, style["*"]);
127
+ } else {
128
+ return value;
129
+ }
130
+ }
131
+ };
132
+ const defaultStyle = null;
133
+ return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
134
+ const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
135
+ return settings.stylePrettyLogs ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset) : value;
136
+ });
137
+ }
138
+ function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
139
+ if (value != null && isNaN(value)) {
140
+ return "";
141
+ }
142
+ value = value != null ? value + addNumber : value;
143
+ return digits === 2 ? value == null ? "--" : value < 10 ? "0" + value : value.toString() : value == null ? "---" : value < 10 ? "00" + value : value < 100 ? "0" + value : value.toString();
144
+ }
145
+ function buildPrettyMeta(settings, meta) {
146
+ if (meta == null) {
147
+ return {
148
+ text: "",
149
+ template: settings.prettyLogTemplate,
150
+ placeholders: {}
151
+ };
152
+ }
153
+ let template = settings.prettyLogTemplate;
154
+ const placeholderValues = {};
155
+ if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
156
+ template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
157
+ } else {
158
+ if (settings.prettyLogTimeZone === "UTC") {
159
+ placeholderValues["yyyy"] = meta.date?.getUTCFullYear() ?? "----";
160
+ placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getUTCMonth(), 2, 1);
161
+ placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getUTCDate(), 2);
162
+ placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getUTCHours(), 2);
163
+ placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getUTCMinutes(), 2);
164
+ placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getUTCSeconds(), 2);
165
+ placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getUTCMilliseconds(), 3);
166
+ } else {
167
+ placeholderValues["yyyy"] = meta.date?.getFullYear() ?? "----";
168
+ placeholderValues["mm"] = formatNumberAddZeros(meta.date?.getMonth(), 2, 1);
169
+ placeholderValues["dd"] = formatNumberAddZeros(meta.date?.getDate(), 2);
170
+ placeholderValues["hh"] = formatNumberAddZeros(meta.date?.getHours(), 2);
171
+ placeholderValues["MM"] = formatNumberAddZeros(meta.date?.getMinutes(), 2);
172
+ placeholderValues["ss"] = formatNumberAddZeros(meta.date?.getSeconds(), 2);
173
+ placeholderValues["ms"] = formatNumberAddZeros(meta.date?.getMilliseconds(), 3);
174
+ }
175
+ }
176
+ const dateInSettingsTimeZone = settings.prettyLogTimeZone === "UTC" ? meta.date : meta.date != null ? new Date(meta.date.getTime() - meta.date.getTimezoneOffset() * 6e4) : void 0;
177
+ placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString() ?? "";
178
+ placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "") ?? "";
179
+ placeholderValues["logLevelName"] = meta.logLevelName;
180
+ placeholderValues["fileNameWithLine"] = meta.path?.fileNameWithLine ?? "";
181
+ placeholderValues["filePathWithLine"] = meta.path?.filePathWithLine ?? "";
182
+ placeholderValues["fullFilePath"] = meta.path?.fullFilePath ?? "";
183
+ let parentNamesString = settings.parentNames?.join(settings.prettyErrorParentNamesSeparator);
184
+ parentNamesString = parentNamesString != null && meta.name != null ? parentNamesString + settings.prettyErrorParentNamesSeparator : void 0;
185
+ const combinedName = meta.name != null || parentNamesString != null ? `${parentNamesString ?? ""}${meta.name ?? ""}` : "";
186
+ placeholderValues["name"] = combinedName;
187
+ placeholderValues["nameWithDelimiterPrefix"] = combinedName.length > 0 ? settings.prettyErrorLoggerNameDelimiter + combinedName : "";
188
+ placeholderValues["nameWithDelimiterSuffix"] = combinedName.length > 0 ? combinedName + settings.prettyErrorLoggerNameDelimiter : "";
189
+ if (settings.overwrite?.addPlaceholders != null) {
190
+ settings.overwrite.addPlaceholders(meta, placeholderValues);
191
+ }
192
+ return {
193
+ text: formatTemplate(settings, template, placeholderValues),
194
+ template,
195
+ placeholders: placeholderValues
196
+ };
197
+ }
198
+ var DEFAULT_IGNORE_PATTERNS = [
199
+ /(?:^|[\\/])node_modules[\\/].*tslog/i,
200
+ /(?:^|[\\/])deps[\\/].*tslog/i,
201
+ /tslog[\\/]+src[\\/]+internal[\\/]/i,
202
+ /tslog[\\/]+src[\\/]BaseLogger/i,
203
+ /tslog[\\/]+src[\\/]index/i
204
+ ];
205
+ function splitStackLines(error) {
206
+ const stack = typeof error?.stack === "string" ? error.stack : void 0;
207
+ if (stack == null || stack.length === 0) {
208
+ return [];
209
+ }
210
+ return stack.split("\n").map((line) => line.trimEnd());
211
+ }
212
+ function sanitizeStackLines(lines) {
213
+ return lines.filter((line) => line.length > 0 && !/^\s*Error\b/.test(line));
214
+ }
215
+ function toStackFrames(lines, parseLine) {
216
+ const frames = [];
217
+ for (const line of lines) {
218
+ const frame = parseLine(line);
219
+ if (frame != null) {
220
+ frames.push(frame);
221
+ }
222
+ }
223
+ return frames;
224
+ }
225
+ function findFirstExternalFrameIndex(frames, ignorePatterns = DEFAULT_IGNORE_PATTERNS) {
226
+ for (let index = 0; index < frames.length; index += 1) {
227
+ const frame = frames[index];
228
+ const filePathCandidate = frame.filePath ?? "";
229
+ const fullPathCandidate = frame.fullFilePath ?? "";
230
+ if (!ignorePatterns.some((pattern) => pattern.test(filePathCandidate) || pattern.test(fullPathCandidate))) {
231
+ return index;
232
+ }
233
+ }
234
+ return 0;
235
+ }
236
+ function getCleanStackLines(error) {
237
+ return sanitizeStackLines(splitStackLines(error));
238
+ }
239
+ function buildStackTrace(error, parseLine) {
240
+ return toStackFrames(getCleanStackLines(error), parseLine);
241
+ }
242
+ function clampIndex(index, maxExclusive) {
243
+ if (index < 0) {
244
+ return 0;
245
+ }
246
+ if (index >= maxExclusive) {
247
+ return Math.max(0, maxExclusive - 1);
248
+ }
249
+ return index;
250
+ }
251
+ function getDefaultIgnorePatterns() {
252
+ return [...DEFAULT_IGNORE_PATTERNS];
253
+ }
254
+ var DEFAULT_CAUSE_DEPTH = 5;
255
+ function collectErrorCauses(error, options = {}) {
256
+ const maxDepth = options.maxDepth ?? DEFAULT_CAUSE_DEPTH;
257
+ const causes = [];
258
+ const visited = /* @__PURE__ */ new Set();
259
+ let current = error;
260
+ let depth = 0;
261
+ while (current != null && depth < maxDepth) {
262
+ const cause = current?.cause;
263
+ if (cause == null || visited.has(cause)) {
264
+ break;
265
+ }
266
+ visited.add(cause);
267
+ causes.push(toError(cause));
268
+ current = cause;
269
+ depth += 1;
270
+ }
271
+ return causes;
272
+ }
273
+ function toError(value) {
274
+ if (value instanceof Error) {
275
+ return value;
276
+ }
277
+ const error = new Error(typeof value === "string" ? value : JSON.stringify(value));
278
+ if (typeof value === "object" && value != null) {
279
+ Object.assign(error, value);
280
+ }
281
+ return error;
282
+ }
283
+ function jsonStringifyRecursive(obj) {
284
+ const cache = /* @__PURE__ */ new Set();
285
+ return JSON.stringify(obj, (key, value) => {
286
+ if (typeof value === "object" && value !== null) {
287
+ if (cache.has(value)) {
288
+ return "[Circular]";
289
+ }
290
+ cache.add(value);
291
+ }
292
+ if (typeof value === "bigint") {
293
+ return `${value}`;
294
+ }
295
+ if (typeof value === "undefined") {
296
+ return "[undefined]";
297
+ }
298
+ return value;
299
+ });
300
+ }
301
+ function inspect(obj, opts) {
302
+ const ctx = {
303
+ seen: [],
304
+ stylize: stylizeNoColor
305
+ };
306
+ if (opts != null) {
307
+ _extend(ctx, opts);
308
+ }
309
+ if (isUndefined(ctx.showHidden))
310
+ ctx.showHidden = false;
311
+ if (isUndefined(ctx.depth))
312
+ ctx.depth = 2;
313
+ if (isUndefined(ctx.colors))
314
+ ctx.colors = true;
315
+ if (isUndefined(ctx.customInspect))
316
+ ctx.customInspect = true;
317
+ if (ctx.colors)
318
+ ctx.stylize = stylizeWithColor;
319
+ return formatValue(ctx, obj, ctx.depth);
320
+ }
321
+ inspect.colors = prettyLogStyles;
322
+ inspect.styles = {
323
+ special: "cyan",
324
+ number: "yellow",
325
+ boolean: "yellow",
326
+ undefined: "grey",
327
+ null: "bold",
328
+ string: "green",
329
+ date: "magenta",
330
+ regexp: "red"
331
+ };
332
+ function isBoolean(arg) {
333
+ return typeof arg === "boolean";
334
+ }
335
+ function isUndefined(arg) {
336
+ return arg === void 0;
337
+ }
338
+ function stylizeNoColor(str) {
339
+ return str;
340
+ }
341
+ function stylizeWithColor(str, styleType) {
342
+ const style = inspect.styles[styleType];
343
+ if (style != null && inspect?.colors?.[style]?.[0] != null && inspect?.colors?.[style]?.[1] != null) {
344
+ return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m";
345
+ } else {
346
+ return str;
347
+ }
348
+ }
349
+ function isFunction(arg) {
350
+ return typeof arg === "function";
351
+ }
352
+ function isString(arg) {
353
+ return typeof arg === "string";
354
+ }
355
+ function isNumber(arg) {
356
+ return typeof arg === "number";
357
+ }
358
+ function isNull(arg) {
359
+ return arg === null;
360
+ }
361
+ function hasOwn(obj, prop) {
362
+ return Object.prototype.hasOwnProperty.call(obj, prop);
363
+ }
364
+ function isRegExp(re) {
365
+ return isObject(re) && objectToString(re) === "[object RegExp]";
366
+ }
367
+ function isObject(arg) {
368
+ return typeof arg === "object" && arg !== null;
369
+ }
370
+ function isError(e) {
371
+ return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
372
+ }
373
+ function isDate(d) {
374
+ return isObject(d) && objectToString(d) === "[object Date]";
375
+ }
376
+ function objectToString(o) {
377
+ return Object.prototype.toString.call(o);
378
+ }
379
+ function arrayToHash(array) {
380
+ const hash = {};
381
+ array.forEach((val) => {
382
+ hash[val] = true;
383
+ });
384
+ return hash;
385
+ }
386
+ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
387
+ const output = [];
388
+ for (let i = 0, l = value.length; i < l; ++i) {
389
+ if (hasOwn(value, String(i))) {
390
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
391
+ } else {
392
+ output.push("");
393
+ }
394
+ }
395
+ keys.forEach((key) => {
396
+ if (!key.match(/^\d+$/)) {
397
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
398
+ }
399
+ });
400
+ return output;
401
+ }
402
+ function formatError(value) {
403
+ return "[" + Error.prototype.toString.call(value) + "]";
404
+ }
405
+ function formatValue(ctx, value, recurseTimes = 0) {
406
+ if (ctx.customInspect && value != null && isFunction(value) && value?.inspect !== inspect && !(value?.constructor && value?.constructor.prototype === value)) {
407
+ if (typeof value.inspect !== "function" && value.toString != null) {
408
+ return value.toString();
409
+ }
410
+ let ret = value?.inspect(recurseTimes, ctx);
411
+ if (!isString(ret)) {
412
+ ret = formatValue(ctx, ret, recurseTimes);
413
+ }
414
+ return ret;
415
+ }
416
+ const primitive = formatPrimitive(ctx, value);
417
+ if (primitive) {
418
+ return primitive;
419
+ }
420
+ let keys = Object.keys(value);
421
+ const visibleKeys = arrayToHash(keys);
422
+ try {
423
+ if (ctx.showHidden && Object.getOwnPropertyNames) {
424
+ keys = Object.getOwnPropertyNames(value);
425
+ }
426
+ } catch {
427
+ }
428
+ if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
429
+ return formatError(value);
430
+ }
431
+ if (keys.length === 0) {
432
+ if (isFunction(ctx.stylize)) {
433
+ if (isFunction(value)) {
434
+ const name = value.name ? ": " + value.name : "";
435
+ return ctx.stylize("[Function" + name + "]", "special");
436
+ }
437
+ if (isRegExp(value)) {
438
+ return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
439
+ }
440
+ if (isDate(value)) {
441
+ return ctx.stylize(Date.prototype.toISOString.call(value), "date");
442
+ }
443
+ if (isError(value)) {
444
+ return formatError(value);
445
+ }
446
+ } else {
447
+ return value;
448
+ }
449
+ }
450
+ let base = "";
451
+ let array = false;
452
+ let braces = ["{\n", "\n}"];
453
+ if (Array.isArray(value)) {
454
+ array = true;
455
+ braces = ["[\n", "\n]"];
456
+ }
457
+ if (isFunction(value)) {
458
+ const n = value.name ? ": " + value.name : "";
459
+ base = " [Function" + n + "]";
460
+ }
461
+ if (isRegExp(value)) {
462
+ base = " " + RegExp.prototype.toString.call(value);
463
+ }
464
+ if (isDate(value)) {
465
+ base = " " + Date.prototype.toUTCString.call(value);
466
+ }
467
+ if (isError(value)) {
468
+ base = " " + formatError(value);
469
+ }
470
+ if (keys.length === 0 && (!array || value.length == 0)) {
471
+ return braces[0] + base + braces[1];
472
+ }
473
+ if (recurseTimes < 0) {
474
+ if (isRegExp(value)) {
475
+ return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
476
+ } else {
477
+ return ctx.stylize("[Object]", "special");
478
+ }
479
+ }
480
+ ctx.seen.push(value);
481
+ let output;
482
+ if (array) {
483
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
484
+ } else {
485
+ output = keys.map((key) => {
486
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
487
+ });
488
+ }
489
+ ctx.seen.pop();
490
+ return reduceToSingleString(output, base, braces);
491
+ }
492
+ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
493
+ let name, str;
494
+ let desc = { value: void 0 };
495
+ try {
496
+ desc.value = value[key];
497
+ } catch {
498
+ }
499
+ try {
500
+ if (Object.getOwnPropertyDescriptor) {
501
+ desc = Object.getOwnPropertyDescriptor(value, key) || desc;
502
+ }
503
+ } catch {
504
+ }
505
+ if (desc.get) {
506
+ if (desc.set) {
507
+ str = ctx.stylize("[Getter/Setter]", "special");
508
+ } else {
509
+ str = ctx.stylize("[Getter]", "special");
510
+ }
511
+ } else {
512
+ if (desc.set) {
513
+ str = ctx.stylize("[Setter]", "special");
514
+ }
515
+ }
516
+ if (!hasOwn(visibleKeys, key)) {
517
+ name = "[" + key + "]";
518
+ }
519
+ if (!str) {
520
+ if (ctx.seen.indexOf(desc.value) < 0) {
521
+ if (isNull(recurseTimes)) {
522
+ str = formatValue(ctx, desc.value, void 0);
523
+ } else {
524
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
525
+ }
526
+ if (str.indexOf("\n") > -1) {
527
+ if (array) {
528
+ str = str.split("\n").map((line) => {
529
+ return " " + line;
530
+ }).join("\n").substr(2);
531
+ } else {
532
+ str = "\n" + str.split("\n").map((line) => {
533
+ return " " + line;
534
+ }).join("\n");
535
+ }
536
+ }
537
+ } else {
538
+ str = ctx.stylize("[Circular]", "special");
539
+ }
540
+ }
541
+ if (isUndefined(name)) {
542
+ if (array && key.match(/^\d+$/)) {
543
+ return str;
544
+ }
545
+ name = JSON.stringify("" + key);
546
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
547
+ name = name.substr(1, name.length - 2);
548
+ name = ctx.stylize(name, "name");
549
+ } else {
550
+ name = name.replace(/'/g, "\\'").replace(/\\"/g, "\\'").replace(/(^"|"$)/g, "'");
551
+ name = ctx.stylize(name, "string");
552
+ }
553
+ }
554
+ return name + ": " + str;
555
+ }
556
+ function formatPrimitive(ctx, value) {
557
+ if (isUndefined(value))
558
+ return ctx.stylize("undefined", "undefined");
559
+ if (isString(value)) {
560
+ const simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, "\\'") + "'";
561
+ return ctx.stylize(simple, "string");
562
+ }
563
+ if (isNumber(value))
564
+ return ctx.stylize("" + value, "number");
565
+ if (isBoolean(value))
566
+ return ctx.stylize("" + value, "boolean");
567
+ if (isNull(value))
568
+ return ctx.stylize("null", "null");
569
+ }
570
+ function reduceToSingleString(output, base, braces) {
571
+ return braces[0] + (base === "" ? "" : base + "\n") + " " + output.join(",\n ") + " " + braces[1];
572
+ }
573
+ function _extend(origin, add) {
574
+ const typedOrigin = { ...origin };
575
+ if (!add || !isObject(add))
576
+ return origin;
577
+ const clonedAdd = { ...add };
578
+ const keys = Object.keys(add);
579
+ let i = keys.length;
580
+ while (i--) {
581
+ typedOrigin[keys[i]] = clonedAdd[keys[i]];
582
+ }
583
+ return typedOrigin;
584
+ }
585
+ function formatWithOptions(inspectOptions, ...args) {
586
+ const ctx = {
587
+ seen: [],
588
+ stylize: stylizeNoColor
589
+ };
590
+ if (inspectOptions != null) {
591
+ _extend(ctx, inspectOptions);
592
+ }
593
+ const first = args[0];
594
+ let a = 0;
595
+ let str = "";
596
+ let join = "";
597
+ if (typeof first === "string") {
598
+ if (args.length === 1) {
599
+ return first;
600
+ }
601
+ let tempStr;
602
+ let lastPos = 0;
603
+ for (let i = 0; i < first.length - 1; i++) {
604
+ if (first.charCodeAt(i) === 37) {
605
+ const nextChar = first.charCodeAt(++i);
606
+ if (a + 1 !== args.length) {
607
+ switch (nextChar) {
608
+ case 115: {
609
+ const tempArg = args[++a];
610
+ if (typeof tempArg === "number") {
611
+ tempStr = formatPrimitive(ctx, tempArg);
612
+ } else if (typeof tempArg === "bigint") {
613
+ tempStr = formatPrimitive(ctx, tempArg);
614
+ } else if (typeof tempArg !== "object" || tempArg === null) {
615
+ tempStr = String(tempArg);
616
+ } else {
617
+ tempStr = inspect(tempArg, {
618
+ ...inspectOptions,
619
+ compact: 3,
620
+ colors: false,
621
+ depth: 0
622
+ });
623
+ }
624
+ break;
625
+ }
626
+ case 106:
627
+ tempStr = jsonStringifyRecursive(args[++a]);
628
+ break;
629
+ case 100: {
630
+ const tempNum = args[++a];
631
+ if (typeof tempNum === "bigint") {
632
+ tempStr = formatPrimitive(ctx, tempNum);
633
+ } else if (typeof tempNum === "symbol") {
634
+ tempStr = "NaN";
635
+ } else {
636
+ tempStr = formatPrimitive(ctx, tempNum);
637
+ }
638
+ break;
639
+ }
640
+ case 79:
641
+ tempStr = inspect(args[++a], inspectOptions);
642
+ break;
643
+ case 111:
644
+ tempStr = inspect(args[++a], {
645
+ ...inspectOptions,
646
+ showHidden: true,
647
+ showProxy: true,
648
+ depth: 4
649
+ });
650
+ break;
651
+ case 105: {
652
+ const tempInteger = args[++a];
653
+ if (typeof tempInteger === "bigint") {
654
+ tempStr = formatPrimitive(ctx, tempInteger);
655
+ } else if (typeof tempInteger === "symbol") {
656
+ tempStr = "NaN";
657
+ } else {
658
+ tempStr = formatPrimitive(ctx, parseInt(tempStr));
659
+ }
660
+ break;
661
+ }
662
+ case 102: {
663
+ const tempFloat = args[++a];
664
+ if (typeof tempFloat === "symbol") {
665
+ tempStr = "NaN";
666
+ } else {
667
+ tempStr = formatPrimitive(ctx, parseInt(tempFloat));
668
+ }
669
+ break;
670
+ }
671
+ case 99:
672
+ a += 1;
673
+ tempStr = "";
674
+ break;
675
+ case 37:
676
+ str += first.slice(lastPos, i);
677
+ lastPos = i + 1;
678
+ continue;
679
+ default:
680
+ continue;
681
+ }
682
+ if (lastPos !== i - 1) {
683
+ str += first.slice(lastPos, i - 1);
684
+ }
685
+ str += tempStr;
686
+ lastPos = i + 1;
687
+ } else if (nextChar === 37) {
688
+ str += first.slice(lastPos, i);
689
+ lastPos = i + 1;
690
+ }
691
+ }
692
+ }
693
+ if (lastPos !== 0) {
694
+ a++;
695
+ join = " ";
696
+ if (lastPos < first.length) {
697
+ str += first.slice(lastPos);
698
+ }
699
+ }
700
+ }
701
+ while (a < args.length) {
702
+ const value = args[a];
703
+ str += join;
704
+ str += typeof value !== "string" ? inspect(value, inspectOptions) : value;
705
+ join = " ";
706
+ a++;
707
+ }
708
+ return str;
709
+ }
710
+ function safeGetCwd() {
711
+ try {
712
+ const nodeProcess = globalThis?.process;
713
+ if (typeof nodeProcess?.cwd === "function") {
714
+ return nodeProcess.cwd();
715
+ }
716
+ } catch {
717
+ }
718
+ try {
719
+ const deno = globalThis?.["Deno"];
720
+ if (typeof deno?.cwd === "function") {
721
+ return deno.cwd();
722
+ }
723
+ } catch {
724
+ }
725
+ return void 0;
726
+ }
727
+ function isBrowserEnvironment() {
728
+ return typeof window !== "undefined" && typeof document !== "undefined";
729
+ }
730
+ function consoleSupportsCssStyling() {
731
+ if (!isBrowserEnvironment()) {
732
+ return false;
733
+ }
734
+ const navigatorObj = globalThis?.navigator;
735
+ const userAgent = navigatorObj?.userAgent ?? "";
736
+ if (/firefox/i.test(userAgent)) {
737
+ return true;
738
+ }
739
+ const windowObj = globalThis;
740
+ if (windowObj?.CSS?.supports?.("color", "#000")) {
741
+ return true;
742
+ }
743
+ return /safari/i.test(userAgent) && !/chrome/i.test(userAgent);
744
+ }
745
+ function createLoggerEnvironment() {
746
+ const runtimeInfo = detectRuntimeInfo();
747
+ const meta = createRuntimeMeta(runtimeInfo);
748
+ const usesBrowserStack = runtimeInfo.name === "browser" || runtimeInfo.name === "worker";
749
+ const callerIgnorePatterns = usesBrowserStack ? [...getDefaultIgnorePatterns(), /node_modules[\\/].*tslog/i] : [...getDefaultIgnorePatterns(), /node:(?:internal|vm)/i, /\binternal[\\/]/i];
750
+ let cachedCwd;
751
+ const environment = {
752
+ getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
753
+ return Object.assign({}, meta, {
754
+ name,
755
+ parentNames,
756
+ date: /* @__PURE__ */ new Date(),
757
+ logLevelId,
758
+ logLevelName,
759
+ path: !hideLogPositionForPerformance ? environment.getCallerStackFrame(stackDepthLevel) : void 0
760
+ });
761
+ },
762
+ getCallerStackFrame(stackDepthLevel, error = new Error()) {
763
+ const frames = buildStackTrace(error, (line) => parseStackLine(line));
764
+ if (frames.length === 0) {
765
+ return {};
766
+ }
767
+ const autoIndex = findFirstExternalFrameIndex(frames, callerIgnorePatterns);
768
+ const useManualIndex = Number.isFinite(stackDepthLevel) && stackDepthLevel >= 0;
769
+ const resolvedIndex = useManualIndex ? clampIndex(stackDepthLevel, frames.length) : clampIndex(autoIndex, frames.length);
770
+ return frames[resolvedIndex] ?? {};
771
+ },
772
+ getErrorTrace(error) {
773
+ return buildStackTrace(error, (line) => parseStackLine(line));
774
+ },
775
+ isError(value) {
776
+ return isNativeError(value);
777
+ },
778
+ isBuffer(value) {
779
+ return typeof Buffer !== "undefined" && typeof Buffer.isBuffer === "function" ? Buffer.isBuffer(value) : false;
780
+ },
781
+ prettyFormatLogObj(maskedArgs, settings) {
782
+ return maskedArgs.reduce((result, arg) => {
783
+ if (environment.isError(arg)) {
784
+ result.errors.push(environment.prettyFormatErrorObj(arg, settings));
785
+ } else {
786
+ result.args.push(arg);
787
+ }
788
+ return result;
789
+ }, { args: [], errors: [] });
790
+ },
791
+ prettyFormatErrorObj(error, settings) {
792
+ const stackLines = formatStackFrames(environment.getErrorTrace(error), settings);
793
+ const causeSections = collectErrorCauses(error).map((cause, index) => {
794
+ const header = `Caused by (${index + 1}): ${cause.name ?? "Error"}${cause.message ? `: ${cause.message}` : ""}`;
795
+ const frames = formatStackFrames(buildStackTrace(cause, (line) => parseStackLine(line)), settings);
796
+ return [header, ...frames].join("\n");
797
+ });
798
+ const placeholderValuesError = {
799
+ errorName: ` ${error.name} `,
800
+ errorMessage: formatErrorMessage(error),
801
+ errorStack: [...stackLines, ...causeSections].join("\n")
802
+ };
803
+ return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
804
+ },
805
+ transportFormatted(logMetaMarkup, logArgs, logErrors, logMeta, settings) {
806
+ const prettyLogs = settings.stylePrettyLogs !== false;
807
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
808
+ const sanitizedMetaMarkup = stripAnsi(logMetaMarkup);
809
+ const metaMarkupForText = prettyLogs ? logMetaMarkup : sanitizedMetaMarkup;
810
+ if (shouldUseCss(prettyLogs)) {
811
+ settings.prettyInspectOptions.colors = false;
812
+ const formattedArgs2 = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
813
+ const cssMeta = logMeta != null ? buildCssMetaOutput(settings, logMeta) : { text: sanitizedMetaMarkup, styles: [] };
814
+ const hasCssMeta = cssMeta.text.length > 0 && cssMeta.styles.length > 0;
815
+ const metaOutput = hasCssMeta ? cssMeta.text : sanitizedMetaMarkup;
816
+ const output = metaOutput + formattedArgs2 + logErrorsStr;
817
+ if (hasCssMeta) {
818
+ console.log(output, ...cssMeta.styles);
819
+ } else {
820
+ console.log(output);
821
+ }
822
+ return;
823
+ }
824
+ settings.prettyInspectOptions.colors = prettyLogs;
825
+ const formattedArgs = formatWithOptionsSafe(settings.prettyInspectOptions, logArgs);
826
+ console.log(metaMarkupForText + formattedArgs + logErrorsStr);
827
+ },
828
+ transportJSON(json) {
829
+ console.log(jsonStringifyRecursive(json));
830
+ }
831
+ };
832
+ if (getNodeEnv() === "test") {
833
+ environment.__resetWorkingDirectoryCacheForTests = () => {
834
+ cachedCwd = void 0;
835
+ };
836
+ }
837
+ return environment;
838
+ function parseStackLine(line) {
839
+ return usesBrowserStack ? parseBrowserStackLine(line) : parseServerStackLine(line);
840
+ }
841
+ function parseServerStackLine(rawLine) {
842
+ if (typeof rawLine !== "string" || rawLine.length === 0) {
843
+ return void 0;
844
+ }
845
+ const trimmedLine = rawLine.trim();
846
+ if (!trimmedLine.includes(" at ") && !trimmedLine.startsWith("at ")) {
847
+ return void 0;
848
+ }
849
+ const line = trimmedLine.replace(/^at\s+/, "");
850
+ let method;
851
+ let location = line;
852
+ const methodMatch = line.match(/^(.*?)\s+\((.*)\)$/);
853
+ if (methodMatch) {
854
+ method = methodMatch[1];
855
+ location = methodMatch[2];
856
+ }
857
+ const sanitizedLocation = location.replace(/^\(/, "").replace(/\)$/, "");
858
+ const withoutQuery = sanitizedLocation.replace(/\?.*$/, "");
859
+ let fileLine;
860
+ let fileColumn;
861
+ let filePathCandidate = withoutQuery;
862
+ const segments = withoutQuery.split(":");
863
+ if (segments.length >= 3 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
864
+ fileColumn = segments.pop();
865
+ fileLine = segments.pop();
866
+ filePathCandidate = segments.join(":");
867
+ } else if (segments.length >= 2 && /^\d+$/.test(segments[segments.length - 1] ?? "")) {
868
+ fileLine = segments.pop();
869
+ filePathCandidate = segments.join(":");
870
+ }
871
+ let normalizedPath = filePathCandidate.replace(/^file:\/\//, "");
872
+ const cwd = getWorkingDirectory();
873
+ if (cwd != null && normalizedPath.startsWith(cwd)) {
874
+ normalizedPath = normalizedPath.slice(cwd.length);
875
+ normalizedPath = normalizedPath.replace(/^[\\/]/, "");
876
+ }
877
+ if (normalizedPath.length === 0) {
878
+ normalizedPath = filePathCandidate;
879
+ }
880
+ const normalizedPathWithoutLine = normalizeFilePath(normalizedPath);
881
+ const effectivePath = normalizedPathWithoutLine.length > 0 ? normalizedPathWithoutLine : normalizedPath;
882
+ const pathSegments = effectivePath.split(/\\|\//);
883
+ const fileName = pathSegments[pathSegments.length - 1];
884
+ const fileNameWithLine = fileName && fileLine ? `${fileName}:${fileLine}` : void 0;
885
+ const filePathWithLine = effectivePath && fileLine ? `${effectivePath}:${fileLine}` : void 0;
886
+ return {
887
+ fullFilePath: sanitizedLocation,
888
+ fileName,
889
+ fileNameWithLine,
890
+ fileColumn,
891
+ fileLine,
892
+ filePath: effectivePath,
893
+ filePathWithLine,
894
+ method
895
+ };
896
+ }
897
+ function parseBrowserStackLine(line) {
898
+ const href = globalThis.location?.origin;
899
+ if (line == null) {
900
+ return void 0;
901
+ }
902
+ const match = line.match(BROWSER_PATH_REGEX);
903
+ if (!match) {
904
+ return void 0;
905
+ }
906
+ const filePath = match[1]?.replace(/\?.*$/, "");
907
+ if (filePath == null) {
908
+ return void 0;
909
+ }
910
+ const pathParts = filePath.split("/");
911
+ const fileLine = match[2];
912
+ const fileColumn = match[3];
913
+ const fileName = pathParts[pathParts.length - 1];
914
+ return {
915
+ fullFilePath: href ? `${href}${filePath}` : filePath,
916
+ fileName,
917
+ fileNameWithLine: fileName && fileLine ? `${fileName}:${fileLine}` : void 0,
918
+ fileColumn,
919
+ fileLine,
920
+ filePath,
921
+ filePathWithLine: fileLine ? `${filePath}:${fileLine}` : void 0,
922
+ method: void 0
923
+ };
924
+ }
925
+ function formatStackFrames(frames, settings) {
926
+ return frames.map((stackFrame) => formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true));
927
+ }
928
+ function formatErrorMessage(error) {
929
+ return Object.getOwnPropertyNames(error).filter((key) => key !== "stack" && key !== "cause").reduce((result, key) => {
930
+ const value = error[key];
931
+ if (typeof value === "function") {
932
+ return result;
933
+ }
934
+ result.push(String(value));
935
+ return result;
936
+ }, []).join(", ");
937
+ }
938
+ function shouldUseCss(prettyLogs) {
939
+ return prettyLogs && (runtimeInfo.name === "browser" || runtimeInfo.name === "worker") && consoleSupportsCssStyling();
940
+ }
941
+ function stripAnsi(value) {
942
+ return value.replace(ANSI_REGEX, "");
943
+ }
944
+ function buildCssMetaOutput(settings, metaValue) {
945
+ if (metaValue == null) {
946
+ return { text: "", styles: [] };
947
+ }
948
+ const { template, placeholders } = buildPrettyMeta(settings, metaValue);
949
+ const parts = [];
950
+ const styles = [];
951
+ let lastIndex = 0;
952
+ const placeholderRegex = /{{(.+?)}}/g;
953
+ let match;
954
+ while ((match = placeholderRegex.exec(template)) != null) {
955
+ if (match.index > lastIndex) {
956
+ parts.push(template.slice(lastIndex, match.index));
957
+ }
958
+ const key = match[1];
959
+ const rawValue = placeholders[key] != null ? String(placeholders[key]) : "";
960
+ const tokens = collectStyleTokens(settings.prettyLogStyles?.[key], rawValue);
961
+ const css = tokensToCss(tokens);
962
+ if (css.length > 0) {
963
+ parts.push(`%c${rawValue}%c`);
964
+ styles.push(css, "");
965
+ } else {
966
+ parts.push(rawValue);
967
+ }
968
+ lastIndex = placeholderRegex.lastIndex;
969
+ }
970
+ if (lastIndex < template.length) {
971
+ parts.push(template.slice(lastIndex));
972
+ }
973
+ return {
974
+ text: parts.join(""),
975
+ styles
976
+ };
977
+ }
978
+ function collectStyleTokens(style, value) {
979
+ if (style == null) {
980
+ return [];
981
+ }
982
+ if (typeof style === "string") {
983
+ return [style];
984
+ }
985
+ if (Array.isArray(style)) {
986
+ return style.flatMap((token) => collectStyleTokens(token, value));
987
+ }
988
+ if (typeof style === "object") {
989
+ const normalizedValue = value.trim();
990
+ const nextStyle = style[normalizedValue] ?? style["*"];
991
+ if (nextStyle == null) {
992
+ return [];
993
+ }
994
+ return collectStyleTokens(nextStyle, value);
995
+ }
996
+ return [];
997
+ }
998
+ function tokensToCss(tokens) {
999
+ const seen = /* @__PURE__ */ new Set();
1000
+ const cssParts = [];
1001
+ for (const token of tokens) {
1002
+ const css = styleTokenToCss(token);
1003
+ if (css != null && css.length > 0 && !seen.has(css)) {
1004
+ seen.add(css);
1005
+ cssParts.push(css);
1006
+ }
1007
+ }
1008
+ return cssParts.join("; ");
1009
+ }
1010
+ function styleTokenToCss(token) {
1011
+ const color = COLOR_TOKENS[token];
1012
+ if (color != null) {
1013
+ return `color: ${color}`;
1014
+ }
1015
+ const background = BACKGROUND_TOKENS[token];
1016
+ if (background != null) {
1017
+ return `background-color: ${background}`;
1018
+ }
1019
+ switch (token) {
1020
+ case "bold":
1021
+ return "font-weight: bold";
1022
+ case "dim":
1023
+ return "opacity: 0.75";
1024
+ case "italic":
1025
+ return "font-style: italic";
1026
+ case "underline":
1027
+ return "text-decoration: underline";
1028
+ case "overline":
1029
+ return "text-decoration: overline";
1030
+ case "inverse":
1031
+ return "filter: invert(1)";
1032
+ case "hidden":
1033
+ return "visibility: hidden";
1034
+ case "strikethrough":
1035
+ return "text-decoration: line-through";
1036
+ default:
1037
+ return void 0;
1038
+ }
1039
+ }
1040
+ function getWorkingDirectory() {
1041
+ if (cachedCwd === void 0) {
1042
+ cachedCwd = safeGetCwd() ?? null;
1043
+ }
1044
+ return cachedCwd ?? void 0;
1045
+ }
1046
+ function shouldCaptureHostname() {
1047
+ return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1048
+ }
1049
+ function shouldCaptureRuntimeVersion() {
1050
+ return runtimeInfo.name === "node" || runtimeInfo.name === "deno" || runtimeInfo.name === "bun";
1051
+ }
1052
+ function createRuntimeMeta(info) {
1053
+ if (info.name === "browser" || info.name === "worker") {
1054
+ return {
1055
+ runtime: info.name,
1056
+ browser: info.userAgent
1057
+ };
1058
+ }
1059
+ const metaStatic = {
1060
+ runtime: info.name
1061
+ };
1062
+ if (shouldCaptureRuntimeVersion()) {
1063
+ metaStatic.runtimeVersion = info.version ?? "unknown";
1064
+ }
1065
+ if (shouldCaptureHostname()) {
1066
+ metaStatic.hostname = info.hostname ?? "unknown";
1067
+ }
1068
+ return metaStatic;
1069
+ }
1070
+ function formatWithOptionsSafe(options, args) {
1071
+ try {
1072
+ return formatWithOptions(options, ...args);
1073
+ } catch {
1074
+ return args.map(stringifyFallback).join(" ");
1075
+ }
1076
+ }
1077
+ function stringifyFallback(value) {
1078
+ if (typeof value === "string") {
1079
+ return value;
1080
+ }
1081
+ try {
1082
+ return JSON.stringify(value);
1083
+ } catch {
1084
+ return String(value);
1085
+ }
1086
+ }
1087
+ function normalizeFilePath(value) {
1088
+ if (typeof value !== "string" || value.length === 0) {
1089
+ return value;
1090
+ }
1091
+ const replaced = value.replace(/\\+/g, "\\").replace(/\\/g, "/");
1092
+ const hasRootDoubleSlash = replaced.startsWith("//");
1093
+ const hasLeadingSlash = replaced.startsWith("/") && !hasRootDoubleSlash;
1094
+ const driveMatch = replaced.match(/^[A-Za-z]:/);
1095
+ const drivePrefix = driveMatch ? driveMatch[0] : "";
1096
+ const withoutDrive = drivePrefix ? replaced.slice(drivePrefix.length) : replaced;
1097
+ const segments = withoutDrive.split("/");
1098
+ const normalizedSegments = [];
1099
+ for (const segment of segments) {
1100
+ if (segment === "" || segment === ".") {
1101
+ continue;
1102
+ }
1103
+ if (segment === "..") {
1104
+ if (normalizedSegments.length > 0) {
1105
+ normalizedSegments.pop();
1106
+ }
1107
+ continue;
1108
+ }
1109
+ normalizedSegments.push(segment);
1110
+ }
1111
+ let normalized = normalizedSegments.join("/");
1112
+ if (hasRootDoubleSlash) {
1113
+ normalized = `//${normalized}`;
1114
+ } else if (hasLeadingSlash) {
1115
+ normalized = `/${normalized}`;
1116
+ } else if (drivePrefix !== "") {
1117
+ normalized = `${drivePrefix}${normalized.length > 0 ? `/${normalized}` : ""}`;
1118
+ }
1119
+ if (normalized.length === 0) {
1120
+ return value;
1121
+ }
1122
+ return normalized;
1123
+ }
1124
+ function detectRuntimeInfo() {
1125
+ if (isBrowserEnvironment()) {
1126
+ const navigatorObj = globalThis.navigator;
1127
+ return {
1128
+ name: "browser",
1129
+ userAgent: navigatorObj?.userAgent
1130
+ };
1131
+ }
1132
+ const globalScope = globalThis;
1133
+ if (typeof globalScope.importScripts === "function") {
1134
+ return {
1135
+ name: "worker",
1136
+ userAgent: globalScope.navigator?.userAgent
1137
+ };
1138
+ }
1139
+ const globalAny = globalThis;
1140
+ if (globalAny.Bun != null) {
1141
+ const bunVersion = globalAny.Bun.version;
1142
+ return {
1143
+ name: "bun",
1144
+ version: bunVersion != null ? `bun/${bunVersion}` : void 0,
1145
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
1146
+ };
1147
+ }
1148
+ if (globalAny.Deno != null) {
1149
+ const denoHostname = resolveDenoHostname(globalAny.Deno);
1150
+ const denoVersion = globalAny.Deno?.version?.deno;
1151
+ return {
1152
+ name: "deno",
1153
+ version: denoVersion != null ? `deno/${denoVersion}` : void 0,
1154
+ hostname: denoHostname ?? getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
1155
+ };
1156
+ }
1157
+ if (globalAny.process?.versions?.node != null || globalAny.process?.version != null) {
1158
+ return {
1159
+ name: "node",
1160
+ version: globalAny.process?.versions?.node ?? globalAny.process?.version,
1161
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
1162
+ };
1163
+ }
1164
+ if (globalAny.process != null) {
1165
+ return {
1166
+ name: "node",
1167
+ version: "unknown",
1168
+ hostname: getEnvironmentHostname(globalAny.process, globalAny.Deno, globalAny.Bun, globalAny.location)
1169
+ };
1170
+ }
1171
+ return {
1172
+ name: "unknown"
1173
+ };
1174
+ }
1175
+ function getEnvironmentHostname(nodeProcess, deno, bun, location) {
1176
+ const processHostname = nodeProcess?.env?.HOSTNAME ?? nodeProcess?.env?.HOST ?? nodeProcess?.env?.COMPUTERNAME;
1177
+ if (processHostname != null && processHostname.length > 0) {
1178
+ return processHostname;
1179
+ }
1180
+ const bunHostname = bun?.env?.HOSTNAME ?? bun?.env?.HOST ?? bun?.env?.COMPUTERNAME;
1181
+ if (bunHostname != null && bunHostname.length > 0) {
1182
+ return bunHostname;
1183
+ }
1184
+ try {
1185
+ const denoEnvGet = deno?.env?.get;
1186
+ if (typeof denoEnvGet === "function") {
1187
+ const value = denoEnvGet("HOSTNAME");
1188
+ if (value != null && value.length > 0) {
1189
+ return value;
1190
+ }
1191
+ }
1192
+ } catch {
1193
+ }
1194
+ if (location?.hostname != null && location.hostname.length > 0) {
1195
+ return location.hostname;
1196
+ }
1197
+ return void 0;
1198
+ }
1199
+ function resolveDenoHostname(deno) {
1200
+ try {
1201
+ if (typeof deno?.hostname === "function") {
1202
+ const value = deno.hostname();
1203
+ if (value != null && value.length > 0) {
1204
+ return value;
1205
+ }
1206
+ }
1207
+ } catch {
1208
+ }
1209
+ const locationHostname = globalThis.location?.hostname;
1210
+ if (locationHostname != null && locationHostname.length > 0) {
1211
+ return locationHostname;
1212
+ }
1213
+ return void 0;
1214
+ }
1215
+ function getNodeEnv() {
1216
+ const globalProcess = globalThis?.process;
1217
+ return globalProcess?.env?.NODE_ENV;
1218
+ }
1219
+ function isNativeError(value) {
1220
+ if (value instanceof Error) {
1221
+ return true;
1222
+ }
1223
+ if (value != null && typeof value === "object") {
1224
+ const objectTag = Object.prototype.toString.call(value);
1225
+ if (/\[object .*Error\]/.test(objectTag)) {
1226
+ return true;
1227
+ }
1228
+ const name = value.name;
1229
+ if (typeof name === "string" && name.endsWith("Error")) {
1230
+ return true;
1231
+ }
1232
+ }
1233
+ return false;
1234
+ }
1235
+ }
1236
+ var ANSI_REGEX = /\u001b\[[0-9;]*m/g;
1237
+ var COLOR_TOKENS = {
1238
+ black: "#000000",
1239
+ red: "#ef5350",
1240
+ green: "#66bb6a",
1241
+ yellow: "#fdd835",
1242
+ blue: "#42a5f5",
1243
+ magenta: "#ab47bc",
1244
+ cyan: "#26c6da",
1245
+ white: "#fafafa",
1246
+ blackBright: "#424242",
1247
+ redBright: "#ff7043",
1248
+ greenBright: "#81c784",
1249
+ yellowBright: "#ffe082",
1250
+ blueBright: "#64b5f6",
1251
+ magentaBright: "#ce93d8",
1252
+ cyanBright: "#4dd0e1",
1253
+ whiteBright: "#ffffff"
1254
+ };
1255
+ var BACKGROUND_TOKENS = {
1256
+ bgBlack: "#000000",
1257
+ bgRed: "#ef5350",
1258
+ bgGreen: "#66bb6a",
1259
+ bgYellow: "#fdd835",
1260
+ bgBlue: "#42a5f5",
1261
+ bgMagenta: "#ab47bc",
1262
+ bgCyan: "#26c6da",
1263
+ bgWhite: "#fafafa",
1264
+ bgBlackBright: "#424242",
1265
+ bgRedBright: "#ff7043",
1266
+ bgGreenBright: "#81c784",
1267
+ bgYellowBright: "#ffe082",
1268
+ bgBlueBright: "#64b5f6",
1269
+ bgMagentaBright: "#ce93d8",
1270
+ bgCyanBright: "#4dd0e1",
1271
+ bgWhiteBright: "#ffffff"
1272
+ };
1273
+ var BROWSER_PATH_REGEX = /(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?((?:\/[^:/]+){2,})(?::(\d+))?(?::(\d+))?/;
1274
+ var runtime = createLoggerEnvironment();
1275
+ var BaseLogger = class {
1276
+ constructor(settings, logObj, stackDepthLevel = Number.NaN) {
1277
+ this.logObj = logObj;
1278
+ this.stackDepthLevel = stackDepthLevel;
1279
+ this.runtime = runtime;
1280
+ this.maxErrorCauseDepth = 5;
1281
+ this.settings = {
1282
+ type: settings?.type ?? "pretty",
1283
+ name: settings?.name,
1284
+ parentNames: settings?.parentNames,
1285
+ minLevel: settings?.minLevel ?? 0,
1286
+ argumentsArrayName: settings?.argumentsArrayName,
1287
+ hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
1288
+ prettyLogTemplate: settings?.prettyLogTemplate ?? "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}} {{logLevelName}} {{filePathWithLine}}{{nameWithDelimiterPrefix}} ",
1289
+ prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
1290
+ prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? " \u2022 {{fileName}} {{method}}\n {{filePathWithLine}}",
1291
+ prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
1292
+ prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? " ",
1293
+ stylePrettyLogs: settings?.stylePrettyLogs ?? true,
1294
+ prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
1295
+ prettyLogStyles: settings?.prettyLogStyles ?? {
1296
+ logLevelName: {
1297
+ "*": ["bold", "black", "bgWhiteBright", "dim"],
1298
+ SILLY: ["bold", "white"],
1299
+ TRACE: ["bold", "whiteBright"],
1300
+ DEBUG: ["bold", "green"],
1301
+ INFO: ["bold", "blue"],
1302
+ WARN: ["bold", "yellow"],
1303
+ ERROR: ["bold", "red"],
1304
+ FATAL: ["bold", "redBright"]
1305
+ },
1306
+ dateIsoStr: "white",
1307
+ filePathWithLine: "white",
1308
+ name: ["white", "bold"],
1309
+ nameWithDelimiterPrefix: ["white", "bold"],
1310
+ nameWithDelimiterSuffix: ["white", "bold"],
1311
+ errorName: ["bold", "bgRedBright", "whiteBright"],
1312
+ fileName: ["yellow"],
1313
+ fileNameWithLine: "white"
1314
+ },
1315
+ prettyInspectOptions: settings?.prettyInspectOptions ?? {
1316
+ colors: true,
1317
+ compact: false,
1318
+ depth: Infinity
1319
+ },
1320
+ metaProperty: settings?.metaProperty ?? "_meta",
1321
+ maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
1322
+ maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
1323
+ maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
1324
+ maskValuesRegEx: settings?.maskValuesRegEx,
1325
+ prefix: [...settings?.prefix ?? []],
1326
+ attachedTransports: [...settings?.attachedTransports ?? []],
1327
+ overwrite: {
1328
+ mask: settings?.overwrite?.mask,
1329
+ toLogObj: settings?.overwrite?.toLogObj,
1330
+ addMeta: settings?.overwrite?.addMeta,
1331
+ addPlaceholders: settings?.overwrite?.addPlaceholders,
1332
+ formatMeta: settings?.overwrite?.formatMeta,
1333
+ formatLogObj: settings?.overwrite?.formatLogObj,
1334
+ transportFormatted: settings?.overwrite?.transportFormatted,
1335
+ transportJSON: settings?.overwrite?.transportJSON
1336
+ }
1337
+ };
1338
+ this.captureStackForMeta = this._shouldCaptureStack();
1339
+ }
1340
+ log(logLevelId, logLevelName, ...args) {
1341
+ if (logLevelId < this.settings.minLevel) {
1342
+ return;
1343
+ }
1344
+ const resolvedArgs = this._resolveLogArguments(args);
1345
+ const logArgs = [...this.settings.prefix, ...resolvedArgs];
1346
+ const maskedArgs = this.settings.overwrite?.mask != null ? this.settings.overwrite?.mask(logArgs) : this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0 ? this._mask(logArgs) : logArgs;
1347
+ const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : void 0;
1348
+ const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
1349
+ const logObjWithMeta = this.settings.overwrite?.addMeta != null ? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName) : this._addMetaToLogObj(logObj, logLevelId, logLevelName);
1350
+ const logMeta = logObjWithMeta?.[this.settings.metaProperty];
1351
+ let logMetaMarkup;
1352
+ let logArgsAndErrorsMarkup = void 0;
1353
+ if (this.settings.overwrite?.formatMeta != null) {
1354
+ logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
1355
+ }
1356
+ if (this.settings.overwrite?.formatLogObj != null) {
1357
+ logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
1358
+ }
1359
+ if (this.settings.type === "pretty") {
1360
+ logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
1361
+ logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? runtime.prettyFormatLogObj(maskedArgs, this.settings);
1362
+ }
1363
+ if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
1364
+ if (this.settings.overwrite?.transportFormatted != null) {
1365
+ const transport = this.settings.overwrite.transportFormatted;
1366
+ const declaredParams = transport.length;
1367
+ if (declaredParams < 4) {
1368
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors);
1369
+ } else if (declaredParams === 4) {
1370
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta);
1371
+ } else {
1372
+ transport(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
1373
+ }
1374
+ } else {
1375
+ runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, logMeta, this.settings);
1376
+ }
1377
+ } else {
1378
+ if (this.settings.overwrite?.transportJSON != null) {
1379
+ this.settings.overwrite.transportJSON(logObjWithMeta);
1380
+ } else if (this.settings.type !== "hidden") {
1381
+ runtime.transportJSON(logObjWithMeta);
1382
+ }
1383
+ }
1384
+ if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
1385
+ this.settings.attachedTransports.forEach((transportLogger) => {
1386
+ transportLogger(logObjWithMeta);
1387
+ });
1388
+ }
1389
+ return logObjWithMeta;
1390
+ }
1391
+ attachTransport(transportLogger) {
1392
+ this.settings.attachedTransports.push(transportLogger);
1393
+ }
1394
+ getSubLogger(settings, logObj) {
1395
+ const subLoggerSettings = {
1396
+ ...this.settings,
1397
+ ...settings,
1398
+ parentNames: this.settings?.parentNames != null && this.settings?.name != null ? [...this.settings.parentNames, this.settings.name] : this.settings?.name != null ? [this.settings.name] : void 0,
1399
+ prefix: [...this.settings.prefix, ...settings?.prefix ?? []]
1400
+ };
1401
+ const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
1402
+ return subLogger;
1403
+ }
1404
+ _mask(args) {
1405
+ const maskKeys = this._getMaskKeys();
1406
+ return args?.map((arg) => {
1407
+ return this._recursiveCloneAndMaskValuesOfKeys(arg, maskKeys);
1408
+ });
1409
+ }
1410
+ _getMaskKeys() {
1411
+ const maskKeys = this.settings.maskValuesOfKeys ?? [];
1412
+ const signature = maskKeys.map(String).join("|");
1413
+ if (this.settings.maskValuesOfKeysCaseInsensitive === true) {
1414
+ if (this.maskKeysCache?.source === maskKeys && this.maskKeysCache.caseInsensitive === true && this.maskKeysCache.signature === signature) {
1415
+ return this.maskKeysCache.normalized;
1416
+ }
1417
+ const normalized = maskKeys.map((key) => typeof key === "string" ? key.toLowerCase() : String(key).toLowerCase());
1418
+ this.maskKeysCache = {
1419
+ source: maskKeys,
1420
+ caseInsensitive: true,
1421
+ normalized,
1422
+ signature
1423
+ };
1424
+ return normalized;
1425
+ }
1426
+ this.maskKeysCache = {
1427
+ source: maskKeys,
1428
+ caseInsensitive: false,
1429
+ normalized: maskKeys,
1430
+ signature
1431
+ };
1432
+ return maskKeys;
1433
+ }
1434
+ _resolveLogArguments(args) {
1435
+ if (args.length === 1 && typeof args[0] === "function") {
1436
+ const candidate = args[0];
1437
+ if (candidate.length === 0) {
1438
+ const result = candidate();
1439
+ return Array.isArray(result) ? result : [result];
1440
+ }
1441
+ }
1442
+ return args;
1443
+ }
1444
+ _recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
1445
+ if (seen.includes(source)) {
1446
+ return { ...source };
1447
+ }
1448
+ if (typeof source === "object" && source !== null) {
1449
+ seen.push(source);
1450
+ }
1451
+ if (runtime.isError(source) || runtime.isBuffer(source)) {
1452
+ return source;
1453
+ } else if (source instanceof Map) {
1454
+ return new Map(source);
1455
+ } else if (source instanceof Set) {
1456
+ return new Set(source);
1457
+ } else if (Array.isArray(source)) {
1458
+ return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
1459
+ } else if (source instanceof Date) {
1460
+ return new Date(source.getTime());
1461
+ } else if (source instanceof URL) {
1462
+ return urlToObject(source);
1463
+ } else if (source !== null && typeof source === "object") {
1464
+ const baseObject = runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
1465
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
1466
+ const lookupKey = this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : typeof prop === "string" ? prop.toLowerCase() : String(prop).toLowerCase();
1467
+ o[prop] = keys.includes(lookupKey) ? this.settings.maskPlaceholder : (() => {
1468
+ try {
1469
+ return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
1470
+ } catch {
1471
+ return null;
1472
+ }
1473
+ })();
1474
+ return o;
1475
+ }, baseObject);
1476
+ } else {
1477
+ if (typeof source === "string") {
1478
+ let modifiedSource = source;
1479
+ for (const regEx of this.settings?.maskValuesRegEx || []) {
1480
+ modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
1481
+ }
1482
+ return modifiedSource;
1483
+ }
1484
+ return source;
1485
+ }
1486
+ }
1487
+ _recursiveCloneAndExecuteFunctions(source, seen = []) {
1488
+ if (this.isObjectOrArray(source) && seen.includes(source)) {
1489
+ return this.shallowCopy(source);
1490
+ }
1491
+ if (this.isObjectOrArray(source)) {
1492
+ seen.push(source);
1493
+ }
1494
+ if (Array.isArray(source)) {
1495
+ return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
1496
+ } else if (source instanceof Date) {
1497
+ return new Date(source.getTime());
1498
+ } else if (this.isObject(source)) {
1499
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
1500
+ const descriptor = Object.getOwnPropertyDescriptor(source, prop);
1501
+ if (descriptor) {
1502
+ Object.defineProperty(o, prop, descriptor);
1503
+ const value = source[prop];
1504
+ o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
1505
+ }
1506
+ return o;
1507
+ }, Object.create(Object.getPrototypeOf(source)));
1508
+ } else {
1509
+ return source;
1510
+ }
1511
+ }
1512
+ isObjectOrArray(value) {
1513
+ return typeof value === "object" && value !== null;
1514
+ }
1515
+ isObject(value) {
1516
+ return typeof value === "object" && !Array.isArray(value) && value !== null;
1517
+ }
1518
+ shallowCopy(source) {
1519
+ if (Array.isArray(source)) {
1520
+ return [...source];
1521
+ } else {
1522
+ return { ...source };
1523
+ }
1524
+ }
1525
+ _toLogObj(args, clonedLogObj = {}) {
1526
+ args = args?.map((arg) => runtime.isError(arg) ? this._toErrorObject(arg) : arg);
1527
+ if (this.settings.argumentsArrayName == null) {
1528
+ if (args.length === 1 && !Array.isArray(args[0]) && runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
1529
+ clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
1530
+ } else {
1531
+ clonedLogObj = { ...clonedLogObj, ...args };
1532
+ }
1533
+ } else {
1534
+ clonedLogObj = {
1535
+ ...clonedLogObj,
1536
+ [this.settings.argumentsArrayName]: args
1537
+ };
1538
+ }
1539
+ return clonedLogObj;
1540
+ }
1541
+ _cloneError(error) {
1542
+ const cloned = new error.constructor();
1543
+ Object.getOwnPropertyNames(error).forEach((key) => {
1544
+ cloned[key] = error[key];
1545
+ });
1546
+ return cloned;
1547
+ }
1548
+ _toErrorObject(error, depth = 0, seen = /* @__PURE__ */ new Set()) {
1549
+ if (!seen.has(error)) {
1550
+ seen.add(error);
1551
+ }
1552
+ const errorObject = {
1553
+ nativeError: error,
1554
+ name: error.name ?? "Error",
1555
+ message: error.message,
1556
+ stack: runtime.getErrorTrace(error)
1557
+ };
1558
+ if (depth >= this.maxErrorCauseDepth) {
1559
+ return errorObject;
1560
+ }
1561
+ const causeValue = error.cause;
1562
+ if (causeValue != null) {
1563
+ const normalizedCause = toError(causeValue);
1564
+ if (!seen.has(normalizedCause)) {
1565
+ errorObject.cause = this._toErrorObject(normalizedCause, depth + 1, seen);
1566
+ }
1567
+ }
1568
+ return errorObject;
1569
+ }
1570
+ _addMetaToLogObj(logObj, logLevelId, logLevelName) {
1571
+ return {
1572
+ ...logObj,
1573
+ [this.settings.metaProperty]: runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, !this.captureStackForMeta, this.settings.name, this.settings.parentNames)
1574
+ };
1575
+ }
1576
+ _shouldCaptureStack() {
1577
+ if (this.settings.hideLogPositionForProduction) {
1578
+ return false;
1579
+ }
1580
+ if (this.settings.type === "json") {
1581
+ return true;
1582
+ }
1583
+ const template = this.settings.prettyLogTemplate ?? "";
1584
+ const stackPlaceholders = /{{\s*(file(Name|Path|Line|PathWithLine|NameWithLine)|fullFilePath)\s*}}/;
1585
+ if (stackPlaceholders.test(template)) {
1586
+ return true;
1587
+ }
1588
+ return false;
1589
+ }
1590
+ _prettyFormatLogObjMeta(logObjMeta) {
1591
+ return buildPrettyMeta(this.settings, logObjMeta).text;
1592
+ }
1593
+ };
1594
+ var Logger = class extends BaseLogger {
1595
+ constructor(settings, logObj) {
1596
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
1597
+ const normalizedSettings = { ...settings ?? {} };
1598
+ if (isBrowser) {
1599
+ normalizedSettings.stylePrettyLogs = settings?.stylePrettyLogs ?? true;
1600
+ }
1601
+ super(normalizedSettings, logObj, Number.NaN);
1602
+ }
1603
+ log(logLevelId, logLevelName, ...args) {
1604
+ return super.log(logLevelId, logLevelName, ...args);
1605
+ }
1606
+ silly(...args) {
1607
+ return super.log(0, "SILLY", ...args);
1608
+ }
1609
+ trace(...args) {
1610
+ return super.log(1, "TRACE", ...args);
1611
+ }
1612
+ debug(...args) {
1613
+ return super.log(2, "DEBUG", ...args);
1614
+ }
1615
+ info(...args) {
1616
+ return super.log(3, "INFO", ...args);
1617
+ }
1618
+ warn(...args) {
1619
+ return super.log(4, "WARN", ...args);
1620
+ }
1621
+ error(...args) {
1622
+ return super.log(5, "ERROR", ...args);
1623
+ }
1624
+ fatal(...args) {
1625
+ return super.log(6, "FATAL", ...args);
1626
+ }
1627
+ getSubLogger(settings, logObj) {
1628
+ return super.getSubLogger(settings, logObj);
1629
+ }
1630
+ };
1631
+ function getLogDir() {
1632
+ switch (process.platform) {
1633
+ case "darwin":
1634
+ return path.join(os.homedir(), "Library", "Logs", "panopticon");
1635
+ case "win32":
1636
+ return path.join(
1637
+ process.env.LOCALAPPDATA ?? path.join(os.homedir(), "AppData", "Local"),
1638
+ "panopticon",
1639
+ "logs"
1640
+ );
1641
+ default:
1642
+ return path.join(
1643
+ process.env.XDG_STATE_HOME ?? path.join(os.homedir(), ".local", "state"),
1644
+ "panopticon",
1645
+ "logs"
1646
+ );
1647
+ }
1648
+ }
1649
+ var LOG_DIR = getLogDir();
1650
+ var logPaths = {
1651
+ server: path.join(LOG_DIR, "server.log"),
1652
+ otlp: path.join(LOG_DIR, "otlp-receiver.log"),
1653
+ mcp: path.join(LOG_DIR, "mcp-server.log"),
1654
+ proxy: path.join(LOG_DIR, "proxy.log"),
1655
+ hook: path.join(LOG_DIR, "hook-handler.log")
1656
+ };
1657
+ var DAEMON_NAMES = Object.keys(logPaths);
1658
+ var root = new Logger({
1659
+ name: "panopticon",
1660
+ type: "pretty",
1661
+ prettyLogTimeZone: "UTC",
1662
+ stylePrettyLogs: false,
1663
+ prettyLogTemplate: "{{dateIsoStr}} [{{name}}] {{logLevelName}} "
1664
+ });
1665
+ var log = {
1666
+ server: root.getSubLogger({ name: "server" }),
1667
+ scanner: root.getSubLogger({ name: "scanner" }),
1668
+ sync: root.getSubLogger({ name: "sync" }),
1669
+ proxy: root.getSubLogger({ name: "proxy" }),
1670
+ llm: root.getSubLogger({ name: "llm" }),
1671
+ mcp: root.getSubLogger({ name: "mcp" }),
1672
+ otlp: root.getSubLogger({ name: "otlp" }),
1673
+ hooks: root.getSubLogger({ name: "hooks" })
1674
+ };
1675
+
1676
+ // node_modules/.pnpm/@fml-inc+panopticon@0.2.2/node_modules/@fml-inc/panopticon/dist/chunk-WNBA7CY3.js
1677
+ function loadSyncConfig() {
1678
+ const cfg = loadUnifiedConfig();
1679
+ return { targets: cfg.sync.targets, filter: cfg.sync.filter };
1680
+ }
1681
+ function saveSyncConfig(syncCfg) {
1682
+ const cfg = loadUnifiedConfig();
1683
+ cfg.sync.targets = syncCfg.targets;
1684
+ cfg.sync.filter = syncCfg.filter;
1685
+ saveUnifiedConfig(cfg);
1686
+ }
1687
+ function addTarget(target) {
1688
+ const cfg = loadUnifiedConfig();
1689
+ const existing = cfg.sync.targets.findIndex((t) => t.name === target.name);
1690
+ if (existing >= 0) {
1691
+ cfg.sync.targets[existing] = target;
1692
+ } else {
1693
+ cfg.sync.targets.push(target);
1694
+ }
1695
+ saveUnifiedConfig(cfg);
1696
+ }
1697
+ function removeTarget(name) {
1698
+ const cfg = loadUnifiedConfig();
1699
+ const before = cfg.sync.targets.length;
1700
+ cfg.sync.targets = cfg.sync.targets.filter((t) => t.name !== name);
1701
+ if (cfg.sync.targets.length === before) return false;
1702
+ saveUnifiedConfig(cfg);
1703
+ return true;
1704
+ }
1705
+ function listTargets() {
1706
+ return loadUnifiedConfig().sync.targets;
1707
+ }
1708
+ var TOKEN_CACHE_TTL_MS = 5 * 60 * 1e3;
1709
+
1710
+ // node_modules/.pnpm/@fml-inc+panopticon@0.2.2/node_modules/@fml-inc/panopticon/dist/chunk-CL3PWTMD.js
1711
+ import http from "http";
1712
+ function post(path4, body, timeoutMs) {
1713
+ return new Promise((resolve, reject) => {
1714
+ const json = JSON.stringify(body);
1715
+ const req = http.request(
1716
+ {
1717
+ hostname: config.host,
1718
+ port: config.port,
1719
+ path: path4,
1720
+ method: "POST",
1721
+ headers: {
1722
+ "Content-Type": "application/json",
1723
+ "Content-Length": Buffer.byteLength(json)
1724
+ },
1725
+ timeout: timeoutMs
1726
+ },
1727
+ (res) => {
1728
+ const chunks = [];
1729
+ res.on("data", (chunk) => chunks.push(chunk));
1730
+ res.on("end", () => {
1731
+ const text = Buffer.concat(chunks).toString("utf-8");
1732
+ let parsed;
1733
+ try {
1734
+ parsed = JSON.parse(text);
1735
+ } catch {
1736
+ reject(
1737
+ new Error(
1738
+ `Invalid JSON response from server: ${text.slice(0, 200)}`
1739
+ )
1740
+ );
1741
+ return;
1742
+ }
1743
+ if (res.statusCode && res.statusCode >= 400 && typeof parsed === "object" && parsed !== null && "error" in parsed) {
1744
+ reject(new Error(parsed.error));
1745
+ return;
1746
+ }
1747
+ resolve(parsed);
1748
+ });
1749
+ }
1750
+ );
1751
+ req.on("error", (err) => {
1752
+ if (err.code === "ECONNREFUSED") {
1753
+ reject(
1754
+ new Error(
1755
+ "Panopticon server is not running. Start with: panopticon start"
1756
+ )
1757
+ );
1758
+ return;
1759
+ }
1760
+ reject(err);
1761
+ });
1762
+ req.on("timeout", () => {
1763
+ req.destroy();
1764
+ reject(new Error("Request to panopticon server timed out"));
1765
+ });
1766
+ req.write(json);
1767
+ req.end();
1768
+ });
1769
+ }
1770
+ var EXEC_TIMEOUT = 6e4;
1771
+ function callExec(command, params) {
1772
+ return post("/api/exec", { command, params }, EXEC_TIMEOUT);
1773
+ }
1774
+ function syncReset(target) {
1775
+ return callExec("sync-reset", target ? { target } : {});
1776
+ }
1777
+ function syncPending(target) {
1778
+ return callExec("sync-pending", { target });
1779
+ }
1780
+
1781
+ // src/commands/doctor.ts
44
1782
  function reportResult(result, spinner) {
45
1783
  const text = `${result.label} \u2014 ${result.detail}`;
46
1784
  if (spinner) {
@@ -98,7 +1836,7 @@ async function handleDoctor(opts) {
98
1836
  {
99
1837
  const spinner = startSpinner("panopticon");
100
1838
  try {
101
- const { doctor } = await import("@fml-inc/panopticon/doctor");
1839
+ const { doctor } = await import("./doctor-YV6KQEGW.js");
102
1840
  const result = await doctor();
103
1841
  if (spinner) spinner.stop();
104
1842
  for (const check of result.checks) {
@@ -269,11 +2007,11 @@ async function handleDoctor(opts) {
269
2007
  }
270
2008
 
271
2009
  // src/commands/install.ts
2010
+ import { execFileSync } from "child_process";
272
2011
  import fs from "fs";
273
- import os from "os";
274
- import path from "path";
2012
+ import os2 from "os";
2013
+ import path2 from "path";
275
2014
  import { fileURLToPath } from "url";
276
- import { addTarget, listTargets } from "@fml-inc/panopticon/sync";
277
2015
 
278
2016
  // src/banner.ts
279
2017
  import pc2 from "picocolors";
@@ -327,17 +2065,17 @@ function resolveGitHubToken() {
327
2065
  }
328
2066
 
329
2067
  // src/commands/install.ts
330
- var CLAUDE_DIR = path.join(os.homedir(), ".claude");
331
- var CLAUDE_SETTINGS_PATH = path.join(CLAUDE_DIR, "settings.json");
332
- var MARKETPLACE_DIR = path.join(
333
- os.homedir(),
2068
+ var CLAUDE_DIR = path2.join(os2.homedir(), ".claude");
2069
+ var CLAUDE_SETTINGS_PATH = path2.join(CLAUDE_DIR, "settings.json");
2070
+ var MARKETPLACE_DIR = path2.join(
2071
+ os2.homedir(),
334
2072
  ".local",
335
2073
  "share",
336
2074
  "claude-plugins"
337
2075
  );
338
2076
  function getPluginRoot() {
339
- let dir = path.dirname(fileURLToPath(import.meta.url));
340
- dir = path.resolve(dir, "..");
2077
+ let dir = path2.dirname(fileURLToPath(import.meta.url));
2078
+ dir = path2.resolve(dir, "..");
341
2079
  return dir;
342
2080
  }
343
2081
  function readJsonFile(filePath) {
@@ -348,45 +2086,96 @@ function readJsonFile(filePath) {
348
2086
  }
349
2087
  }
350
2088
  function writeJsonFile(filePath, data) {
351
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
2089
+ fs.mkdirSync(path2.dirname(filePath), { recursive: true });
352
2090
  fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}
353
2091
  `);
354
2092
  }
355
2093
  async function handleInstall() {
356
2094
  const pluginRoot = getPluginRoot();
357
2095
  console.log("Installing fml...\n");
358
- console.log("[1/4] Running panopticon install...");
359
- const result = panopticonExec("install", { timeout: 6e4 });
360
- if (result.ok) {
361
- for (const line of result.stdout.trim().split("\n")) {
362
- console.log(` ${line}`);
2096
+ console.log("[1/5] Setting up panopticon...");
2097
+ const { resolvePanopticonBin } = await import("./daemon-utils-LIG6K2MK.js");
2098
+ let freshInstall = false;
2099
+ const bin = resolvePanopticonBin();
2100
+ let needsInstall = !bin;
2101
+ if (bin) {
2102
+ const MIN_PANOPTICON = "0.2.2";
2103
+ const vResult = panopticonExec("--version", { timeout: 5e3 });
2104
+ const installed = vResult.ok ? vResult.stdout.trim().split("+")[0] : "0.0.0";
2105
+ if (installed < MIN_PANOPTICON) {
2106
+ console.log(` Found panopticon ${installed}, need >=${MIN_PANOPTICON}`);
2107
+ needsInstall = true;
363
2108
  }
364
- } else {
365
- console.error(" panopticon install failed:");
366
- for (const line of result.stdout.trim().split("\n")) {
367
- console.error(` ${line}`);
2109
+ }
2110
+ if (needsInstall) {
2111
+ console.log(
2112
+ bin ? " Upgrading @fml-inc/panopticon..." : " Installing @fml-inc/panopticon globally..."
2113
+ );
2114
+ try {
2115
+ execFileSync("npm", ["install", "-g", "@fml-inc/panopticon@latest"], {
2116
+ encoding: "utf-8",
2117
+ timeout: 12e4,
2118
+ stdio: "pipe"
2119
+ });
2120
+ freshInstall = true;
2121
+ console.log(" Installed @fml-inc/panopticon");
2122
+ } catch (err) {
2123
+ const msg = err instanceof Error ? err.message : String(err);
2124
+ console.error(` Failed to install panopticon: ${msg}`);
2125
+ console.error(" Install manually: npm install -g @fml-inc/panopticon@latest");
2126
+ }
2127
+ }
2128
+ if (!freshInstall) {
2129
+ const result = panopticonExec("install", { timeout: 6e4 });
2130
+ if (result.ok) {
2131
+ for (const line of result.stdout.trim().split("\n")) {
2132
+ console.log(` ${line}`);
2133
+ }
2134
+ } else {
2135
+ console.error(" panopticon install failed:");
2136
+ for (const line of result.stdout.trim().split("\n")) {
2137
+ console.error(` ${line}`);
2138
+ }
368
2139
  }
369
2140
  }
370
2141
  console.log();
371
- console.log("[2/4] Creating fml directories...");
2142
+ console.log("[2/5] Creating fml directories...");
372
2143
  for (const dir of [FML_DATA_DIR, FML_LOG_DIR]) {
373
2144
  fs.mkdirSync(dir, { recursive: true });
374
2145
  }
375
2146
  console.log(` ${FML_DATA_DIR}`);
376
2147
  console.log(` ${FML_LOG_DIR}
377
2148
  `);
378
- console.log("[3/4] Setting up fml plugin...");
379
- fs.mkdirSync(path.join(MARKETPLACE_DIR, ".claude-plugin"), {
2149
+ console.log("[3/5] Writing plugin manifest...");
2150
+ const pkgJson = readJsonFile(path2.join(pluginRoot, "package.json"));
2151
+ const version = pkgJson?.version ?? "0.0.0-dev";
2152
+ const pluginManifestDir = path2.join(pluginRoot, ".claude-plugin");
2153
+ fs.mkdirSync(pluginManifestDir, { recursive: true });
2154
+ writeJsonFile(path2.join(pluginManifestDir, "plugin.json"), {
2155
+ name: "fml",
2156
+ version,
2157
+ description: "FML agent tools for Claude Code",
2158
+ mcpServers: {
2159
+ fml: {
2160
+ command: "node",
2161
+ args: ["${CLAUDE_PLUGIN_ROOT}/bin/mcp-server"]
2162
+ }
2163
+ }
2164
+ });
2165
+ console.log(` Version: ${version}
2166
+ `);
2167
+ console.log("[4/5] Setting up fml plugin...");
2168
+ fs.mkdirSync(path2.join(MARKETPLACE_DIR, ".claude-plugin"), {
380
2169
  recursive: true
381
2170
  });
382
- const manifestPath = path.join(
2171
+ const manifestPath = path2.join(
383
2172
  MARKETPLACE_DIR,
384
2173
  ".claude-plugin",
385
2174
  "marketplace.json"
386
2175
  );
387
2176
  const manifest = readJsonFile(manifestPath) ?? {
388
2177
  name: "local-plugins",
389
- owner: { name: os.userInfo().username },
2178
+ owner: { name: os2.userInfo().username },
390
2179
  plugins: []
391
2180
  };
392
2181
  const plugins = manifest.plugins ?? [];
@@ -399,7 +2188,7 @@ async function handleInstall() {
399
2188
  manifest.plugins = plugins;
400
2189
  }
401
2190
  writeJsonFile(manifestPath, manifest);
402
- const marketplaceLink = path.join(MARKETPLACE_DIR, "fml");
2191
+ const marketplaceLink = path2.join(MARKETPLACE_DIR, "fml");
403
2192
  try {
404
2193
  fs.unlinkSync(marketplaceLink);
405
2194
  } catch {
@@ -416,9 +2205,25 @@ async function handleInstall() {
416
2205
  settings.enabledPlugins = settings.enabledPlugins ?? {};
417
2206
  settings.enabledPlugins["fml@local-plugins"] = true;
418
2207
  writeJsonFile(CLAUDE_SETTINGS_PATH, settings);
419
- console.log(` Claude settings: ${CLAUDE_SETTINGS_PATH}
420
- `);
421
- console.log("[4/4] Configuring sync target...");
2208
+ console.log(` Claude settings: ${CLAUDE_SETTINGS_PATH}`);
2209
+ try {
2210
+ try {
2211
+ execFileSync("claude", ["plugin", "install", "fml@local-plugins"], {
2212
+ stdio: "pipe",
2213
+ timeout: 15e3
2214
+ });
2215
+ } catch {
2216
+ execFileSync("claude", ["plugin", "update", "fml@local-plugins"], {
2217
+ stdio: "pipe",
2218
+ timeout: 15e3
2219
+ });
2220
+ }
2221
+ console.log(" Plugin registered via Claude Code CLI");
2222
+ } catch {
2223
+ console.log(" warn: claude CLI not found, run 'claude plugin install fml@local-plugins' manually");
2224
+ }
2225
+ console.log();
2226
+ console.log("[5/5] Configuring sync target...");
422
2227
  const prodSyncUrl = DEFAULT_PROD_URL.replace(".cloud", ".site");
423
2228
  const existingTargets = listTargets();
424
2229
  const existingProd = existingTargets.find((t) => t.url === prodSyncUrl);
@@ -452,17 +2257,25 @@ async function handleInstall() {
452
2257
  }
453
2258
 
454
2259
  // src/commands/uninstall.ts
2260
+ import { execFileSync as execFileSync2 } from "child_process";
455
2261
  import fs2 from "fs";
456
- import os2 from "os";
457
- import path2 from "path";
458
- var CLAUDE_DIR2 = path2.join(os2.homedir(), ".claude");
459
- var CLAUDE_SETTINGS_PATH2 = path2.join(CLAUDE_DIR2, "settings.json");
460
- var MARKETPLACE_DIR2 = path2.join(
461
- os2.homedir(),
2262
+ import os3 from "os";
2263
+ import path3 from "path";
2264
+ var CLAUDE_DIR2 = path3.join(os3.homedir(), ".claude");
2265
+ var CLAUDE_SETTINGS_PATH2 = path3.join(CLAUDE_DIR2, "settings.json");
2266
+ var MARKETPLACE_DIR2 = path3.join(
2267
+ os3.homedir(),
462
2268
  ".local",
463
2269
  "share",
464
2270
  "claude-plugins"
465
2271
  );
2272
+ var PLUGIN_CACHE_DIR = path3.join(
2273
+ CLAUDE_DIR2,
2274
+ "plugins",
2275
+ "cache",
2276
+ "local-plugins",
2277
+ "fml"
2278
+ );
466
2279
  function readJsonFile2(filePath) {
467
2280
  try {
468
2281
  return JSON.parse(fs2.readFileSync(filePath, "utf-8"));
@@ -478,9 +2291,48 @@ function handleUninstall(opts) {
478
2291
  const targetSpecific = opts.target && opts.target !== "all";
479
2292
  console.log("Uninstalling fml...\n");
480
2293
  if (targetSpecific) {
481
- console.log("[1/4] Skipping plugin settings (target-specific uninstall)");
2294
+ console.log("[1/5] Skipping plugin uninstall (target-specific uninstall)");
2295
+ } else {
2296
+ console.log("[1/5] Uninstalling MCP plugin...");
2297
+ try {
2298
+ execFileSync2(
2299
+ "claude",
2300
+ ["plugin", "uninstall", "fml@local-plugins", "--scope", "user"],
2301
+ { stdio: "pipe", timeout: 1e4 }
2302
+ );
2303
+ console.log(" Uninstalled (user scope)");
2304
+ } catch {
2305
+ }
2306
+ const installedPluginsPath = path3.join(
2307
+ CLAUDE_DIR2,
2308
+ "plugins",
2309
+ "installed_plugins.json"
2310
+ );
2311
+ const installedPlugins = readJsonFile2(installedPluginsPath);
2312
+ const plugins = installedPlugins?.plugins;
2313
+ const fmlEntries = plugins?.["fml@local-plugins"];
2314
+ if (plugins && fmlEntries) {
2315
+ for (const entry of fmlEntries) {
2316
+ const e = entry;
2317
+ if (e.scope === "project" && e.projectPath) {
2318
+ const projSettings = path3.join(e.projectPath, ".claude", "settings.json");
2319
+ const proj = readJsonFile2(projSettings);
2320
+ if (proj?.enabledPlugins?.["fml@local-plugins"] != null) {
2321
+ delete proj.enabledPlugins["fml@local-plugins"];
2322
+ writeJsonFile2(projSettings, proj);
2323
+ console.log(` Cleaned ${projSettings}`);
2324
+ }
2325
+ }
2326
+ }
2327
+ delete plugins["fml@local-plugins"];
2328
+ writeJsonFile2(installedPluginsPath, installedPlugins);
2329
+ console.log(" Cleaned installed_plugins.json");
2330
+ }
2331
+ }
2332
+ if (targetSpecific) {
2333
+ console.log("[2/5] Skipping plugin settings (target-specific uninstall)");
482
2334
  } else {
483
- console.log("[1/4] Removing plugin from Claude Code settings...");
2335
+ console.log("[2/5] Removing plugin from Claude Code settings...");
484
2336
  const settings = readJsonFile2(CLAUDE_SETTINGS_PATH2);
485
2337
  if (settings) {
486
2338
  if (settings.enabledPlugins) {
@@ -496,17 +2348,17 @@ function handleUninstall(opts) {
496
2348
  }
497
2349
  }
498
2350
  if (targetSpecific) {
499
- console.log("[2/4] Skipping marketplace (target-specific uninstall)");
2351
+ console.log("[3/5] Skipping marketplace (target-specific uninstall)");
500
2352
  } else {
501
- console.log("[2/4] Removing marketplace registration...");
502
- const marketplaceLink = path2.join(MARKETPLACE_DIR2, "fml");
2353
+ console.log("[3/5] Removing marketplace registration...");
2354
+ const marketplaceLink = path3.join(MARKETPLACE_DIR2, "fml");
503
2355
  try {
504
2356
  fs2.rmSync(marketplaceLink, { recursive: true, force: true });
505
2357
  console.log(` Removed ${marketplaceLink}`);
506
2358
  } catch {
507
2359
  console.log(" No marketplace link found, skipping");
508
2360
  }
509
- const manifestPath = path2.join(
2361
+ const manifestPath = path3.join(
510
2362
  MARKETPLACE_DIR2,
511
2363
  ".claude-plugin",
512
2364
  "marketplace.json"
@@ -518,7 +2370,7 @@ function handleUninstall(opts) {
518
2370
  console.log(` Updated ${manifestPath}`);
519
2371
  }
520
2372
  }
521
- console.log("[3/4] Running panopticon uninstall...");
2373
+ console.log("[4/5] Running panopticon uninstall...");
522
2374
  const panoArgs = ["uninstall"];
523
2375
  if (opts.target) panoArgs.push("--target", opts.target);
524
2376
  if (opts.purge) panoArgs.push("--purge");
@@ -534,9 +2386,18 @@ function handleUninstall(opts) {
534
2386
  }
535
2387
  }
536
2388
  if (targetSpecific) {
537
- console.log("[4/4] Skipping data removal (target-specific uninstall)");
538
- } else if (opts.purge) {
539
- console.log("[4/4] Removing fml data and logs...");
2389
+ console.log("[5/5] Skipping data removal (target-specific uninstall)");
2390
+ } else {
2391
+ console.log("[5/5] Removing plugin cache...");
2392
+ try {
2393
+ fs2.rmSync(PLUGIN_CACHE_DIR, { recursive: true, force: true });
2394
+ console.log(` Removed ${PLUGIN_CACHE_DIR}`);
2395
+ } catch {
2396
+ console.log(" No plugin cache found");
2397
+ }
2398
+ }
2399
+ if (opts.purge) {
2400
+ console.log("Removing fml data and logs...");
540
2401
  for (const dir of [FML_DATA_DIR, FML_LOG_DIR]) {
541
2402
  try {
542
2403
  fs2.rmSync(dir, { recursive: true, force: true });
@@ -546,7 +2407,7 @@ function handleUninstall(opts) {
546
2407
  }
547
2408
  }
548
2409
  } else {
549
- console.log("[4/4] Keeping fml data (use --purge to remove)");
2410
+ console.log("Keeping fml data (use --purge to remove)");
550
2411
  }
551
2412
  console.log("\nDone! FML has been uninstalled.");
552
2413
  }
@@ -554,7 +2415,7 @@ function handleUninstall(opts) {
554
2415
  // src/commands/update.ts
555
2416
  import { execSync as execSync2 } from "child_process";
556
2417
  async function handleUpdate() {
557
- const currentVersion = true ? "0.0.25+ec510b5" : "unknown";
2418
+ const currentVersion = true ? "0.0.27+924614a" : "unknown";
558
2419
  console.log(`Current: ${currentVersion}`);
559
2420
  console.log("Updating via npm...\n");
560
2421
  try {
@@ -576,7 +2437,7 @@ async function handleUpdate() {
576
2437
 
577
2438
  // src/auth/oauth.ts
578
2439
  import crypto from "crypto";
579
- import http from "http";
2440
+ import http2 from "http";
580
2441
  async function fetchWorkosClientId() {
581
2442
  const { ConvexHttpClient } = await import("convex/browser");
582
2443
  const client = new ConvexHttpClient(CONVEX_URL);
@@ -647,7 +2508,7 @@ function startCallbackServer(expectedState) {
647
2508
  resolveCode = res;
648
2509
  rejectCode = rej;
649
2510
  });
650
- const server = http.createServer((req, res) => {
2511
+ const server = http2.createServer((req, res) => {
651
2512
  const url = new URL(req.url ?? "/", `http://localhost`);
652
2513
  if (url.pathname === "/callback") {
653
2514
  const code = url.searchParams.get("code");
@@ -899,14 +2760,6 @@ async function handleStatus() {
899
2760
  }
900
2761
 
901
2762
  // src/commands/sync.ts
902
- import {
903
- addTarget as addTarget2,
904
- removeTarget,
905
- listTargets as listTargets2,
906
- loadSyncConfig as loadSyncConfig2,
907
- saveSyncConfig
908
- } from "@fml-inc/panopticon/sync";
909
- import { syncPending as syncPending2, syncReset } from "@fml-inc/panopticon/api";
910
2763
  var FML_SYNC_URL = CONVEX_URL.replace(".cloud", ".site");
911
2764
  async function handleSyncSetup() {
912
2765
  console.log("FML Sync Setup\n");
@@ -918,7 +2771,7 @@ async function handleSyncSetup() {
918
2771
  process.exit(1);
919
2772
  }
920
2773
  console.log("GitHub token: found");
921
- addTarget2({
2774
+ addTarget({
922
2775
  name: DEFAULT_TARGET_NAME,
923
2776
  url: FML_SYNC_URL,
924
2777
  tokenCommand: "gh auth token"
@@ -931,7 +2784,7 @@ Sync target "${DEFAULT_TARGET_NAME}" configured:`);
931
2784
  Restart panopticon to activate: fml stop && fml start`);
932
2785
  }
933
2786
  async function handleSyncList() {
934
- const targets = listTargets2();
2787
+ const targets = listTargets();
935
2788
  if (targets.length === 0) {
936
2789
  console.log(
937
2790
  "No sync targets configured. Run `fml sync setup` or `fml sync add`."
@@ -947,14 +2800,14 @@ async function handleSyncList() {
947
2800
  }
948
2801
  }
949
2802
  async function handleSyncAdd(name, url, opts) {
950
- const existing = listTargets2();
2803
+ const existing = listTargets();
951
2804
  if (existing.some((t) => t.name === name)) {
952
2805
  console.error(
953
2806
  `Target "${name}" already exists. Use \`fml sync edit\` to modify it.`
954
2807
  );
955
2808
  process.exit(1);
956
2809
  }
957
- addTarget2({
2810
+ addTarget({
958
2811
  name,
959
2812
  url,
960
2813
  tokenCommand: opts.tokenCmd,
@@ -978,8 +2831,8 @@ async function handleSyncRemove(name) {
978
2831
  }
979
2832
  }
980
2833
  async function handleSyncEdit(name, opts) {
981
- const config2 = loadSyncConfig2();
982
- const target = config2.targets.find((t) => t.name === name);
2834
+ const config3 = loadSyncConfig();
2835
+ const target = config3.targets.find((t) => t.name === name);
983
2836
  if (!target) {
984
2837
  console.error(`Target "${name}" not found.`);
985
2838
  process.exit(1);
@@ -993,7 +2846,7 @@ async function handleSyncEdit(name, opts) {
993
2846
  target.token = opts.token;
994
2847
  delete target.tokenCommand;
995
2848
  }
996
- saveSyncConfig(config2);
2849
+ saveSyncConfig(config3);
997
2850
  console.log(`Sync target "${name}" updated:`);
998
2851
  console.log(` URL: ${target.url}`);
999
2852
  const auth = target.token ? "static token" : target.tokenCommand ? `command: ${target.tokenCommand}` : "none";
@@ -1001,7 +2854,7 @@ async function handleSyncEdit(name, opts) {
1001
2854
  console.log("\nRestart panopticon to apply: fml stop && fml start");
1002
2855
  }
1003
2856
  async function handleSyncStatus() {
1004
- const targets = listTargets2();
2857
+ const targets = listTargets();
1005
2858
  if (targets.length === 0) {
1006
2859
  console.log("No sync targets configured. Run `fml sync setup` first.");
1007
2860
  return;
@@ -1012,7 +2865,7 @@ async function handleSyncStatus() {
1012
2865
  console.log(` URL: ${target.url}`);
1013
2866
  console.log(` Auth: ${auth}`);
1014
2867
  try {
1015
- const result = await syncPending2(target.name);
2868
+ const result = await syncPending(target.name);
1016
2869
  if (result.totalPending === 0) {
1017
2870
  console.log(" Status: up to date");
1018
2871
  } else {
@@ -1038,14 +2891,13 @@ async function handleSyncReset(targetName) {
1038
2891
  }
1039
2892
 
1040
2893
  // src/commands/env.ts
1041
- import { listTargets as listTargets3 } from "@fml-inc/panopticon/sync";
1042
2894
  function handleEnvShow() {
1043
2895
  const { name, convexUrl } = getActiveEnv();
1044
2896
  console.log(`Environment: ${name}`);
1045
2897
  console.log(` Convex URL: ${convexUrl}`);
1046
2898
  }
1047
2899
  async function handleEnvSwitch(target) {
1048
- const targets = listTargets3();
2900
+ const targets = listTargets();
1049
2901
  const match = targets.find((t) => t.name === target);
1050
2902
  if (!match) {
1051
2903
  console.error(`Sync target "${target}" not found. Available targets:`);
@@ -1615,7 +3467,7 @@ if (process.argv.length <= 2 || process.argv.includes("--help") || process.argv.
1615
3467
  printBanner();
1616
3468
  }
1617
3469
  var program = new Command().name("fml").description("FML agent tools for Claude Code").version(
1618
- true ? "0.0.25+ec510b5" : "dev"
3470
+ true ? "0.0.27+924614a" : "dev"
1619
3471
  );
1620
3472
  program.command("tools", { hidden: true }).description("List all available CLI commands (including hidden agent tools)").action(() => {
1621
3473
  function formatCmd(cmd, prefix = "") {
@@ -1709,9 +3561,9 @@ messages.command("context").description("Get messages around a specific message"
1709
3561
  var skills = program.command("skills", { hidden: true }).description("Browse and load skills");
1710
3562
  skills.command("list").description("List available skills").action(() => handleSkillsList());
1711
3563
  skills.command("load").description("Load a skill by ID").argument("<skill-id>", "Skill ID").action((skillId) => handleSkillsLoad(skillId));
1712
- var config = program.command("config", { hidden: true }).description("View team config snapshots");
1713
- config.command("list").description("List config snapshots for an org").requiredOption("--org <slug>", "Organization slug").option("--repo <full-name>", "Filter by repo (owner/name)").action((opts) => handleConfigList(opts));
1714
- config.command("detail").description("Get config snapshot detail").requiredOption("--org <slug>", "Organization slug").option("--user <username>", "GitHub username").option("--repo <full-name>", "Repository (owner/name)").action((opts) => handleConfigDetail(opts));
3564
+ var config2 = program.command("config", { hidden: true }).description("View team config snapshots");
3565
+ config2.command("list").description("List config snapshots for an org").requiredOption("--org <slug>", "Organization slug").option("--repo <full-name>", "Filter by repo (owner/name)").action((opts) => handleConfigList(opts));
3566
+ config2.command("detail").description("Get config snapshot detail").requiredOption("--org <slug>", "Organization slug").option("--user <username>", "GitHub username").option("--repo <full-name>", "Repository (owner/name)").action((opts) => handleConfigDetail(opts));
1715
3567
  program.parseAsync(process.argv).catch((err) => {
1716
3568
  Sentry.captureException(err);
1717
3569
  console.error(err);