@blyp/core 0.1.2 → 0.1.21

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 (124) hide show
  1. package/README.md +56 -3
  2. package/dist/astro.js +4602 -0
  3. package/dist/astro.js.map +1 -0
  4. package/dist/astro.mjs +4574 -0
  5. package/dist/astro.mjs.map +1 -0
  6. package/dist/client.js +7 -0
  7. package/dist/client.js.map +1 -1
  8. package/dist/client.mjs +7 -0
  9. package/dist/client.mjs.map +1 -1
  10. package/dist/connectors/betterstack.js +24 -0
  11. package/dist/connectors/betterstack.js.map +1 -1
  12. package/dist/connectors/betterstack.mjs +24 -0
  13. package/dist/connectors/betterstack.mjs.map +1 -1
  14. package/dist/connectors/databuddy/index.d.ts +7 -0
  15. package/dist/connectors/databuddy/sender.d.ts +5 -0
  16. package/dist/connectors/databuddy.js +1456 -0
  17. package/dist/connectors/databuddy.js.map +1 -0
  18. package/dist/connectors/databuddy.mjs +1451 -0
  19. package/dist/connectors/databuddy.mjs.map +1 -0
  20. package/dist/connectors/otlp.js +24 -0
  21. package/dist/connectors/otlp.js.map +1 -1
  22. package/dist/connectors/otlp.mjs +24 -0
  23. package/dist/connectors/otlp.mjs.map +1 -1
  24. package/dist/connectors/posthog.js +24 -0
  25. package/dist/connectors/posthog.js.map +1 -1
  26. package/dist/connectors/posthog.mjs +24 -0
  27. package/dist/connectors/posthog.mjs.map +1 -1
  28. package/dist/connectors/sentry.js +24 -0
  29. package/dist/connectors/sentry.js.map +1 -1
  30. package/dist/connectors/sentry.mjs +24 -0
  31. package/dist/connectors/sentry.mjs.map +1 -1
  32. package/dist/core/config.d.ts +1 -1
  33. package/dist/core/logger.d.ts +3 -0
  34. package/dist/elysia.js +455 -30
  35. package/dist/elysia.js.map +1 -1
  36. package/dist/elysia.mjs +455 -30
  37. package/dist/elysia.mjs.map +1 -1
  38. package/dist/expo.js +7 -0
  39. package/dist/expo.js.map +1 -1
  40. package/dist/expo.mjs +7 -0
  41. package/dist/expo.mjs.map +1 -1
  42. package/dist/express.js +455 -30
  43. package/dist/express.js.map +1 -1
  44. package/dist/express.mjs +455 -30
  45. package/dist/express.mjs.map +1 -1
  46. package/dist/fastify.js +455 -30
  47. package/dist/fastify.js.map +1 -1
  48. package/dist/fastify.mjs +455 -30
  49. package/dist/fastify.mjs.map +1 -1
  50. package/dist/frameworks/astro/index.d.ts +2 -0
  51. package/dist/frameworks/astro/logger.d.ts +3 -0
  52. package/dist/frameworks/nitro/index.d.ts +2 -0
  53. package/dist/frameworks/nitro/logger.d.ts +6 -0
  54. package/dist/frameworks/nuxt/index.d.ts +2 -0
  55. package/dist/frameworks/nuxt/logger.d.ts +3 -0
  56. package/dist/frameworks/react-router/index.d.ts +2 -0
  57. package/dist/frameworks/react-router/logger.d.ts +3 -0
  58. package/dist/frameworks/shared/h3.d.ts +19 -0
  59. package/dist/hono.js +455 -30
  60. package/dist/hono.js.map +1 -1
  61. package/dist/hono.mjs +455 -30
  62. package/dist/hono.mjs.map +1 -1
  63. package/dist/index.d.ts +11 -1
  64. package/dist/index.js +1142 -78
  65. package/dist/index.js.map +1 -1
  66. package/dist/index.mjs +1135 -79
  67. package/dist/index.mjs.map +1 -1
  68. package/dist/nestjs.js +455 -30
  69. package/dist/nestjs.js.map +1 -1
  70. package/dist/nestjs.mjs +455 -30
  71. package/dist/nestjs.mjs.map +1 -1
  72. package/dist/nextjs.js +455 -30
  73. package/dist/nextjs.js.map +1 -1
  74. package/dist/nextjs.mjs +455 -30
  75. package/dist/nextjs.mjs.map +1 -1
  76. package/dist/nitro.js +4726 -0
  77. package/dist/nitro.js.map +1 -0
  78. package/dist/nitro.mjs +4698 -0
  79. package/dist/nitro.mjs.map +1 -0
  80. package/dist/nuxt.js +4733 -0
  81. package/dist/nuxt.js.map +1 -0
  82. package/dist/nuxt.mjs +4705 -0
  83. package/dist/nuxt.mjs.map +1 -0
  84. package/dist/react-router.js +4644 -0
  85. package/dist/react-router.js.map +1 -0
  86. package/dist/react-router.mjs +4616 -0
  87. package/dist/react-router.mjs.map +1 -0
  88. package/dist/standalone.js +423 -53
  89. package/dist/standalone.js.map +1 -1
  90. package/dist/standalone.mjs +423 -53
  91. package/dist/standalone.mjs.map +1 -1
  92. package/dist/sveltekit.js +455 -30
  93. package/dist/sveltekit.js.map +1 -1
  94. package/dist/sveltekit.mjs +455 -30
  95. package/dist/sveltekit.mjs.map +1 -1
  96. package/dist/tanstack-start.js +455 -30
  97. package/dist/tanstack-start.js.map +1 -1
  98. package/dist/tanstack-start.mjs +455 -30
  99. package/dist/tanstack-start.mjs.map +1 -1
  100. package/dist/types/connectors/databuddy.d.ts +52 -0
  101. package/dist/types/core/config.d.ts +32 -0
  102. package/dist/types/core/logger.d.ts +2 -0
  103. package/dist/types/frameworks/astro.d.ts +32 -0
  104. package/dist/types/frameworks/nitro.d.ts +62 -0
  105. package/dist/types/frameworks/nuxt.d.ts +12 -0
  106. package/dist/types/frameworks/react-router.d.ts +33 -0
  107. package/dist/types/frameworks/shared.d.ts +24 -0
  108. package/dist/types/shared/client-log.d.ts +1 -1
  109. package/exports/connectors/databuddy.js +1 -0
  110. package/exports/connectors/databuddy.mjs +1 -0
  111. package/exports/frameworks/astro.js +1 -0
  112. package/exports/frameworks/astro.mjs +1 -0
  113. package/exports/frameworks/nitro.js +1 -0
  114. package/exports/frameworks/nitro.mjs +1 -0
  115. package/exports/frameworks/nuxt.js +1 -0
  116. package/exports/frameworks/nuxt.mjs +1 -0
  117. package/exports/frameworks/react-router.js +1 -0
  118. package/exports/frameworks/react-router.mjs +1 -0
  119. package/package.json +59 -2
  120. package/types/connectors/databuddy.d.ts +1 -0
  121. package/types/frameworks/astro.d.ts +1 -0
  122. package/types/frameworks/nitro.d.ts +1 -0
  123. package/types/frameworks/nuxt.d.ts +1 -0
  124. package/types/frameworks/react-router.d.ts +1 -0
package/dist/nuxt.mjs ADDED
@@ -0,0 +1,4705 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { z } from 'zod';
3
+ import fs, { existsSync, readFileSync, writeFileSync, appendFileSync } from 'fs';
4
+ import { createJiti } from 'jiti';
5
+ import path, { resolve, dirname } from 'path';
6
+ import { SeverityNumber } from '@opentelemetry/api-logs';
7
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
8
+ import { resourceFromAttributes } from '@opentelemetry/resources';
9
+ import { LoggerProvider, BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';
10
+ import { PostHog } from 'posthog-node';
11
+ import { gzipSync } from 'fflate';
12
+ import pino from 'pino';
13
+ import { randomUUID } from 'crypto';
14
+ import * as Sentry from '@sentry/node';
15
+ import { Logtail } from '@logtail/node';
16
+ import { Databuddy } from '@databuddy/sdk/node';
17
+
18
+ var __defProp = Object.defineProperty;
19
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
20
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
21
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
22
+ }) : x)(function(x) {
23
+ if (typeof require !== "undefined") return require.apply(this, arguments);
24
+ throw Error('Dynamic require of "' + x + '" is not supported');
25
+ });
26
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
27
+ var requestContextStorage = new AsyncLocalStorage();
28
+ function createStore() {
29
+ return {
30
+ requestScopedLoggerActive: true,
31
+ structuredCollectorActive: false,
32
+ structuredLogEmitted: false,
33
+ mixedLoggerWarningShown: false
34
+ };
35
+ }
36
+ function enterRequestContext() {
37
+ const store = createStore();
38
+ requestContextStorage.enterWith(store);
39
+ return store;
40
+ }
41
+ function getRequestContextStore() {
42
+ return requestContextStorage.getStore();
43
+ }
44
+ function setActiveRequestLogger(logger2) {
45
+ const store = getRequestContextStore();
46
+ if (store) {
47
+ store.activeLogger = logger2;
48
+ }
49
+ }
50
+ function markStructuredCollectorActive() {
51
+ const store = getRequestContextStore();
52
+ if (store) {
53
+ store.structuredCollectorActive = true;
54
+ }
55
+ }
56
+ function markStructuredLogEmitted() {
57
+ const store = getRequestContextStore();
58
+ if (store) {
59
+ store.structuredLogEmitted = true;
60
+ }
61
+ }
62
+ function shouldDropRootLogWrite() {
63
+ const store = getRequestContextStore();
64
+ if (!store || !store.requestScopedLoggerActive || !store.structuredCollectorActive) {
65
+ return false;
66
+ }
67
+ if (!store.mixedLoggerWarningShown) {
68
+ store.mixedLoggerWarningShown = true;
69
+ console.warn(
70
+ "[Blyp] Warning: Mixed logger usage detected for this request. The root logger call was ignored because a request-scoped structured logger is active."
71
+ );
72
+ }
73
+ return true;
74
+ }
75
+
76
+ // src/core/colors.ts
77
+ function getMethodColor(method) {
78
+ const colors = {
79
+ GET: "\x1B[32m",
80
+ POST: "\x1B[36m",
81
+ PUT: "\x1B[33m",
82
+ PATCH: "\x1B[34m",
83
+ DELETE: "\x1B[31m"
84
+ };
85
+ const reset = "\x1B[0m";
86
+ return `${colors[method.toUpperCase()] || ""}${method}${reset}`;
87
+ }
88
+ function getStatusColor(statusCode) {
89
+ const reset = "\x1B[0m";
90
+ if (statusCode >= 500) return `\x1B[31m${statusCode}${reset}`;
91
+ if (statusCode >= 400) return `\x1B[33m${statusCode}${reset}`;
92
+ if (statusCode >= 300) return `\x1B[36m${statusCode}${reset}`;
93
+ if (statusCode >= 200) return `\x1B[32m${statusCode}${reset}`;
94
+ return `\x1B[37m${statusCode}${reset}`;
95
+ }
96
+ function getArrowForMethod(method) {
97
+ const arrows = {
98
+ GET: "\u2192",
99
+ POST: "\u2191",
100
+ PUT: "\u21D1",
101
+ PATCH: "\u2197",
102
+ DELETE: "\u2715"
103
+ };
104
+ return arrows[method.toUpperCase()] || "\u2022";
105
+ }
106
+ function getResponseTimeColor(ms) {
107
+ const reset = "\x1B[0m";
108
+ if (ms < 100) return `\x1B[32m${ms}ms${reset}`;
109
+ if (ms < 300) return `\x1B[33m${ms}ms${reset}`;
110
+ if (ms < 1e3) return `\x1B[31m${ms}ms${reset}`;
111
+ return `\x1B[41m\x1B[37m${ms}ms${reset}`;
112
+ }
113
+
114
+ // src/frameworks/shared/http.ts
115
+ function getHeaderValue(headers, name) {
116
+ if (!headers) {
117
+ return void 0;
118
+ }
119
+ if (headers instanceof Headers) {
120
+ return headers.get(name) ?? headers.get(name.toLowerCase()) ?? void 0;
121
+ }
122
+ if (typeof headers.get === "function") {
123
+ const direct2 = headers.get(name);
124
+ return direct2 ?? headers.get(name.toLowerCase()) ?? void 0;
125
+ }
126
+ const record = headers;
127
+ const direct = record[name] ?? record[name.toLowerCase()];
128
+ if (Array.isArray(direct)) {
129
+ return direct[0];
130
+ }
131
+ return direct;
132
+ }
133
+ function parseForwardedHeader(value) {
134
+ if (!value) {
135
+ return [];
136
+ }
137
+ return value.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
138
+ const match = entry.match(/for="?(\[[^\]]+\]|[^;,\s"]+)/i);
139
+ return match?.[1]?.replace(/^"|"$/g, "") ?? "";
140
+ }).map((entry) => entry.replace(/^\[|\]$/g, "")).filter(Boolean);
141
+ }
142
+ function parseForwardedFor(value) {
143
+ if (!value) {
144
+ return [];
145
+ }
146
+ return value.split(",").map((entry) => entry.trim()).filter(Boolean);
147
+ }
148
+ function stripPort(host) {
149
+ if (host.startsWith("[")) {
150
+ const endIndex = host.indexOf("]");
151
+ return endIndex >= 0 ? host.slice(1, endIndex) : host;
152
+ }
153
+ return host.replace(/:\d+$/, "");
154
+ }
155
+ function detectBrowser(userAgent) {
156
+ if (/edg\//i.test(userAgent)) return "Edge";
157
+ if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) return "Opera";
158
+ if (/chrome\//i.test(userAgent) && !/edg\//i.test(userAgent)) return "Chrome";
159
+ if (/firefox\//i.test(userAgent)) return "Firefox";
160
+ if (/safari\//i.test(userAgent) && !/chrome\//i.test(userAgent)) return "Safari";
161
+ if (/curl\//i.test(userAgent)) return "curl";
162
+ if (/postmanruntime/i.test(userAgent)) return "Postman";
163
+ return "Unknown";
164
+ }
165
+ function detectOperatingSystem(userAgent) {
166
+ if (/windows/i.test(userAgent)) return "Windows";
167
+ if (/android/i.test(userAgent)) return "Android";
168
+ if (/iphone|ipad|ipod/i.test(userAgent)) return "iOS";
169
+ if (/mac os x|macintosh/i.test(userAgent)) return "macOS";
170
+ if (/linux/i.test(userAgent)) return "Linux";
171
+ return "Unknown";
172
+ }
173
+ function detectDeviceType(userAgent) {
174
+ if (!userAgent) return "unknown";
175
+ if (/bot|crawler|spider|curl|wget|postmanruntime/i.test(userAgent)) return "bot";
176
+ if (/ipad|tablet/i.test(userAgent)) return "tablet";
177
+ if (/mobi|iphone|android/i.test(userAgent)) return "mobile";
178
+ return "desktop";
179
+ }
180
+ function extractPathname(requestUrl, fallbackPath = "/") {
181
+ if (!requestUrl) {
182
+ return fallbackPath;
183
+ }
184
+ if (requestUrl.startsWith("http://") || requestUrl.startsWith("https://")) {
185
+ try {
186
+ return new URL(requestUrl).pathname || fallbackPath;
187
+ } catch {
188
+ return fallbackPath;
189
+ }
190
+ }
191
+ if (requestUrl.startsWith("/")) {
192
+ const queryIndex = requestUrl.indexOf("?");
193
+ return queryIndex >= 0 ? requestUrl.slice(0, queryIndex) : requestUrl;
194
+ }
195
+ try {
196
+ return new URL(requestUrl, "http://localhost").pathname || fallbackPath;
197
+ } catch {
198
+ return fallbackPath;
199
+ }
200
+ }
201
+ function createRequestLike(method, url, headers) {
202
+ return { method, url, headers };
203
+ }
204
+ function buildClientDetails(request, fallbackPath) {
205
+ const pathname = fallbackPath ?? extractPathname(request.url);
206
+ const urlObject = (() => {
207
+ try {
208
+ return new URL(request.url);
209
+ } catch {
210
+ try {
211
+ return new URL(pathname, "http://localhost");
212
+ } catch {
213
+ return null;
214
+ }
215
+ }
216
+ })();
217
+ const hostHeader = getHeaderValue(request.headers, "x-forwarded-host") ?? getHeaderValue(request.headers, "host") ?? urlObject?.host ?? void 0;
218
+ const hostname = hostHeader ? stripPort(hostHeader) : urlObject?.hostname;
219
+ const port = hostHeader?.match(/:(\d+)$/)?.[1] ?? (urlObject?.port || void 0);
220
+ const xForwardedFor = parseForwardedFor(getHeaderValue(request.headers, "x-forwarded-for"));
221
+ const forwardedFor = parseForwardedHeader(getHeaderValue(request.headers, "forwarded"));
222
+ const ipCandidates = [
223
+ getHeaderValue(request.headers, "cf-connecting-ip"),
224
+ getHeaderValue(request.headers, "true-client-ip"),
225
+ getHeaderValue(request.headers, "fly-client-ip"),
226
+ getHeaderValue(request.headers, "x-real-ip"),
227
+ getHeaderValue(request.headers, "x-client-ip"),
228
+ xForwardedFor[0],
229
+ forwardedFor[0]
230
+ ].filter((value) => Boolean(value));
231
+ const userAgent = getHeaderValue(request.headers, "user-agent");
232
+ const platform = getHeaderValue(request.headers, "sec-ch-ua-platform")?.replace(/^"|"$/g, "") ?? void 0;
233
+ const deviceType = detectDeviceType(userAgent ?? "");
234
+ return {
235
+ hostname,
236
+ ip: ipCandidates[0],
237
+ forwardedFor: [...xForwardedFor, ...forwardedFor].filter((value, index, values) => {
238
+ return values.indexOf(value) === index;
239
+ }),
240
+ protocol: getHeaderValue(request.headers, "x-forwarded-proto") ?? (urlObject?.protocol ? urlObject.protocol.replace(/:$/, "") : void 0),
241
+ port,
242
+ userAgent,
243
+ origin: getHeaderValue(request.headers, "origin"),
244
+ referer: getHeaderValue(request.headers, "referer"),
245
+ acceptLanguage: getHeaderValue(request.headers, "accept-language"),
246
+ client: {
247
+ ip: ipCandidates[0],
248
+ hostname,
249
+ browser: userAgent ? detectBrowser(userAgent) : void 0,
250
+ os: userAgent ? detectOperatingSystem(userAgent) : void 0,
251
+ deviceType,
252
+ platform,
253
+ isMobile: deviceType === "mobile"
254
+ }
255
+ };
256
+ }
257
+ function buildRequestLogData(request, type, path3, statusCode, responseTime, extra = {}) {
258
+ return {
259
+ type,
260
+ method: request.method,
261
+ url: path3,
262
+ statusCode,
263
+ responseTime,
264
+ ...buildClientDetails(request, path3),
265
+ ...extra
266
+ };
267
+ }
268
+ function buildInfoLogMessage(method, statusCode, url, responseTime) {
269
+ const methodColor = getMethodColor(method);
270
+ const statusColor = getStatusColor(statusCode);
271
+ const timeColor = getResponseTimeColor(responseTime);
272
+ const arrow = getArrowForMethod(method);
273
+ return `${methodColor} ${arrow} ${statusColor} ${url} ${timeColor}`;
274
+ }
275
+ function toErrorLike(error, fallbackStatusCode) {
276
+ if (error === void 0 || error === null) {
277
+ return fallbackStatusCode === void 0 ? void 0 : { statusCode: fallbackStatusCode, message: `HTTP ${fallbackStatusCode}` };
278
+ }
279
+ if (error instanceof Error) {
280
+ const errorWithStatus = error;
281
+ return {
282
+ status: errorWithStatus.status,
283
+ statusCode: errorWithStatus.statusCode ?? fallbackStatusCode,
284
+ code: errorWithStatus.code,
285
+ message: error.message,
286
+ stack: error.stack,
287
+ why: errorWithStatus.why,
288
+ fix: errorWithStatus.fix,
289
+ link: errorWithStatus.link,
290
+ details: errorWithStatus.details,
291
+ cause: errorWithStatus.cause
292
+ };
293
+ }
294
+ if (typeof error === "object") {
295
+ const record = error;
296
+ return {
297
+ status: typeof record.status === "number" ? record.status : void 0,
298
+ statusCode: typeof record.statusCode === "number" ? record.statusCode : fallbackStatusCode,
299
+ code: typeof record.code === "string" || typeof record.code === "number" ? record.code : void 0,
300
+ message: typeof record.message === "string" ? record.message : `HTTP ${fallbackStatusCode ?? 500}`,
301
+ stack: typeof record.stack === "string" ? record.stack : void 0,
302
+ why: typeof record.why === "string" ? record.why : void 0,
303
+ fix: typeof record.fix === "string" ? record.fix : void 0,
304
+ link: typeof record.link === "string" ? record.link : void 0,
305
+ details: record.details !== null && typeof record.details === "object" && !Array.isArray(record.details) ? record.details : void 0,
306
+ cause: record.cause
307
+ };
308
+ }
309
+ return {
310
+ statusCode: fallbackStatusCode,
311
+ message: typeof error === "string" ? error : `HTTP ${fallbackStatusCode ?? 500}`
312
+ };
313
+ }
314
+ function isErrorStatus(statusCode) {
315
+ return statusCode >= 400;
316
+ }
317
+
318
+ // src/shared/log-value.ts
319
+ function normalizeError(error) {
320
+ const normalized = {
321
+ name: error.name,
322
+ message: error.message
323
+ };
324
+ if (error.stack) {
325
+ normalized.stack = error.stack;
326
+ }
327
+ const errorWithCause = error;
328
+ if (errorWithCause.cause !== void 0) {
329
+ normalized.cause = normalizeLogValue(errorWithCause.cause);
330
+ }
331
+ return normalized;
332
+ }
333
+ function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
334
+ if (value instanceof Error) {
335
+ return normalizeError(value);
336
+ }
337
+ if (typeof value === "function") {
338
+ return `[Function: ${value.name || "anonymous"}]`;
339
+ }
340
+ if (typeof value === "symbol") {
341
+ return value.toString();
342
+ }
343
+ if (value === void 0 || value === null) {
344
+ return value;
345
+ }
346
+ if (Array.isArray(value)) {
347
+ return value.map((entry) => normalizeLogValue(entry, seen));
348
+ }
349
+ if (typeof value === "object") {
350
+ if (seen.has(value)) {
351
+ return "[Circular]";
352
+ }
353
+ seen.add(value);
354
+ const normalized = {};
355
+ for (const [key, entry] of Object.entries(value)) {
356
+ normalized[key] = normalizeLogValue(entry, seen);
357
+ }
358
+ seen.delete(value);
359
+ return normalized;
360
+ }
361
+ return value;
362
+ }
363
+ function serializeLogMessage(message) {
364
+ if (typeof message === "string") {
365
+ return message;
366
+ }
367
+ if (message instanceof Error) {
368
+ return message.message || message.name;
369
+ }
370
+ const normalized = normalizeLogValue(message);
371
+ if (typeof normalized === "string") {
372
+ return normalized;
373
+ }
374
+ try {
375
+ const serialized = JSON.stringify(normalized, null, 2);
376
+ return serialized ?? String(normalized);
377
+ } catch {
378
+ return String(normalized);
379
+ }
380
+ }
381
+ var absoluteHttpUrlSchema = z.string().url().refine((value) => {
382
+ try {
383
+ const url = new URL(value);
384
+ return url.protocol === "http:" || url.protocol === "https:";
385
+ } catch {
386
+ return false;
387
+ }
388
+ }, {
389
+ message: "Expected an absolute http(s) URL"
390
+ });
391
+ var plainObjectSchema = z.custom(
392
+ (value) => {
393
+ return value !== null && typeof value === "object" && !Array.isArray(value);
394
+ },
395
+ {
396
+ message: "Expected a plain object"
397
+ }
398
+ );
399
+ var nonEmptyStringSchema = z.string().trim().min(1);
400
+ function isAbsoluteHttpUrl(value) {
401
+ return absoluteHttpUrlSchema.safeParse(value).success;
402
+ }
403
+ function isPlainObject(value) {
404
+ return plainObjectSchema.safeParse(value).success;
405
+ }
406
+ function hasNonEmptyString(value) {
407
+ return nonEmptyStringSchema.safeParse(value).success;
408
+ }
409
+
410
+ // src/shared/client-log.ts
411
+ var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
412
+ var CLIENT_LOG_LEVELS = [
413
+ "debug",
414
+ "info",
415
+ "warning",
416
+ "error",
417
+ "critical",
418
+ "success",
419
+ "table"
420
+ ];
421
+ var clientConnectorRequestSchema = z.union([
422
+ z.literal("betterstack"),
423
+ z.literal("databuddy"),
424
+ z.literal("posthog"),
425
+ z.literal("sentry"),
426
+ z.undefined(),
427
+ z.object({
428
+ type: z.literal("otlp"),
429
+ name: nonEmptyStringSchema
430
+ })
431
+ ]);
432
+ function isClientLogLevel(value) {
433
+ return typeof value === "string" && CLIENT_LOG_LEVELS.includes(value);
434
+ }
435
+ function isClientConnectorRequest(value) {
436
+ return clientConnectorRequestSchema.safeParse(value).success;
437
+ }
438
+ function isClientLogEvent(payload) {
439
+ if (!isPlainObject(payload)) {
440
+ return false;
441
+ }
442
+ if (payload.type !== "client_log" || payload.source !== "client" || !isClientLogLevel(payload.level) || typeof payload.id !== "string" || typeof payload.message !== "string" || typeof payload.clientTimestamp !== "string") {
443
+ return false;
444
+ }
445
+ const pageResult = plainObjectSchema.safeParse(payload.page);
446
+ const browserResult = plainObjectSchema.safeParse(payload.browser);
447
+ const sessionResult = plainObjectSchema.safeParse(payload.session);
448
+ if (!pageResult.success || !browserResult.success || !sessionResult.success) {
449
+ return false;
450
+ }
451
+ if (!isClientConnectorRequest(payload.connector)) {
452
+ return false;
453
+ }
454
+ return typeof sessionResult.data.pageId === "string" && typeof sessionResult.data.sessionId === "string";
455
+ }
456
+ function normalizeEndpointPath(path3) {
457
+ if (!path3) {
458
+ return DEFAULT_CLIENT_LOG_ENDPOINT;
459
+ }
460
+ return path3.startsWith("/") ? path3 : `/${path3}`;
461
+ }
462
+
463
+ // src/shared/once.ts
464
+ function createConsoleOnceLogger(method, warnedKeys7 = /* @__PURE__ */ new Set()) {
465
+ return (key, message, error) => {
466
+ if (warnedKeys7.has(key) || typeof console === "undefined") {
467
+ return;
468
+ }
469
+ const writer = console[method];
470
+ if (typeof writer !== "function") {
471
+ return;
472
+ }
473
+ warnedKeys7.add(key);
474
+ if (error === void 0) {
475
+ writer.call(console, message);
476
+ return;
477
+ }
478
+ writer.call(console, message, error);
479
+ };
480
+ }
481
+ function createWarnOnceLogger(warnedKeys7) {
482
+ return createConsoleOnceLogger("warn", warnedKeys7);
483
+ }
484
+ function createErrorOnceLogger(warnedKeys7) {
485
+ return createConsoleOnceLogger("error", warnedKeys7);
486
+ }
487
+
488
+ // src/core/config.ts
489
+ var PACKAGE_NAME = "@blyp/core";
490
+ var GITIGNORE_FILE_NAME = ".gitignore";
491
+ var CONFIG_FILE_NAMES = [
492
+ "blyp.config.ts",
493
+ "blyp.config.mts",
494
+ "blyp.config.cts",
495
+ "blyp.config.js",
496
+ "blyp.config.mjs",
497
+ "blyp.config.cjs",
498
+ "blyp.config.json"
499
+ ];
500
+ var CONFIG_FILE_NAME = "blyp.config.json";
501
+ var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
502
+ var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
503
+ var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
504
+ var warnedKeys = /* @__PURE__ */ new Set();
505
+ var warnOnce = createWarnOnceLogger(warnedKeys);
506
+ var DEFAULT_ROTATION_CONFIG = {
507
+ enabled: true,
508
+ maxSizeBytes: 10 * 1024 * 1024,
509
+ maxArchives: 5,
510
+ compress: true
511
+ };
512
+ var DEFAULT_FILE_CONFIG = {
513
+ enabled: true,
514
+ dir: "",
515
+ archiveDir: "",
516
+ format: "ndjson",
517
+ rotation: DEFAULT_ROTATION_CONFIG
518
+ };
519
+ var DEFAULT_CLIENT_LOGGING_CONFIG = {
520
+ enabled: true,
521
+ path: DEFAULT_CLIENT_LOG_ENDPOINT
522
+ };
523
+ var DEFAULT_DATABASE_RETRY_CONFIG = {
524
+ maxRetries: 1,
525
+ backoffMs: 100
526
+ };
527
+ var DEFAULT_DATABASE_DELIVERY_CONFIG = {
528
+ strategy: "immediate",
529
+ batchSize: 1,
530
+ flushIntervalMs: 250,
531
+ maxQueueSize: 1e3,
532
+ overflowStrategy: "drop-oldest",
533
+ flushTimeoutMs: 5e3,
534
+ retry: DEFAULT_DATABASE_RETRY_CONFIG
535
+ };
536
+ var DEFAULT_CONFIG = {
537
+ pretty: true,
538
+ level: "info",
539
+ destination: "file",
540
+ file: DEFAULT_FILE_CONFIG,
541
+ clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
542
+ connectors: {}
543
+ };
544
+ var cachedConfig = null;
545
+ function findNearestPackageName(startDir) {
546
+ let currentDir = startDir;
547
+ while (true) {
548
+ const packageJsonPath = resolve(currentDir, "package.json");
549
+ if (existsSync(packageJsonPath)) {
550
+ try {
551
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
552
+ if (hasNonEmptyString(packageJson.name)) {
553
+ return packageJson.name;
554
+ }
555
+ } catch {
556
+ }
557
+ }
558
+ const parentDir = dirname(currentDir);
559
+ if (parentDir === currentDir) {
560
+ return void 0;
561
+ }
562
+ currentDir = parentDir;
563
+ }
564
+ }
565
+ function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
566
+ return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
567
+ }
568
+ function getBootstrapConfig() {
569
+ return {
570
+ pretty: true,
571
+ level: "info",
572
+ destination: "file",
573
+ file: {
574
+ enabled: true,
575
+ format: "ndjson",
576
+ rotation: {
577
+ enabled: true,
578
+ maxSizeBytes: 10 * 1024 * 1024,
579
+ maxArchives: 5,
580
+ compress: true
581
+ }
582
+ },
583
+ clientLogging: {
584
+ enabled: true,
585
+ path: DEFAULT_CLIENT_LOG_ENDPOINT
586
+ },
587
+ connectors: {}
588
+ };
589
+ }
590
+ function shouldBootstrapProjectFiles(cwd) {
591
+ const packageJsonPath = resolve(cwd, "package.json");
592
+ if (!existsSync(packageJsonPath)) {
593
+ return true;
594
+ }
595
+ try {
596
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
597
+ return packageJson.name !== PACKAGE_NAME;
598
+ } catch {
599
+ return true;
600
+ }
601
+ }
602
+ function ensureConfigFile(cwd) {
603
+ if (CONFIG_FILE_NAMES.some((fileName) => existsSync(resolve(cwd, fileName)))) {
604
+ return;
605
+ }
606
+ const configPath = resolve(cwd, CONFIG_FILE_NAME);
607
+ if (existsSync(configPath)) {
608
+ return;
609
+ }
610
+ try {
611
+ writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
612
+ `);
613
+ } catch (error) {
614
+ console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
615
+ }
616
+ }
617
+ function ensureLogsIgnored(cwd) {
618
+ const gitignorePath = resolve(cwd, GITIGNORE_FILE_NAME);
619
+ if (!existsSync(gitignorePath)) {
620
+ try {
621
+ writeFileSync(gitignorePath, "logs\n");
622
+ } catch (error) {
623
+ console.error("[Blyp] Warning: Failed to create .gitignore:", error);
624
+ }
625
+ return;
626
+ }
627
+ try {
628
+ const currentContent = readFileSync(gitignorePath, "utf-8");
629
+ if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
630
+ return;
631
+ }
632
+ const separator = currentContent.endsWith("\n") ? "" : "\n";
633
+ appendFileSync(gitignorePath, `${separator}logs
634
+ `);
635
+ } catch (error) {
636
+ console.error("[Blyp] Warning: Failed to update .gitignore:", error);
637
+ }
638
+ }
639
+ function bootstrapProjectFiles() {
640
+ const cwd = process.cwd();
641
+ if (!shouldBootstrapProjectFiles(cwd)) {
642
+ return;
643
+ }
644
+ ensureConfigFile(cwd);
645
+ ensureLogsIgnored(cwd);
646
+ }
647
+ function findConfigFile() {
648
+ const cwd = process.cwd();
649
+ const matches = CONFIG_FILE_NAMES.map((fileName) => resolve(cwd, fileName)).filter((filePath) => existsSync(filePath));
650
+ if (matches.length === 0) {
651
+ return null;
652
+ }
653
+ if (matches.length > 1) {
654
+ const preferred = matches[0];
655
+ warnOnce(
656
+ `config-multiple:${preferred}`,
657
+ `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
658
+ );
659
+ }
660
+ const selectedPath = matches[0];
661
+ return {
662
+ path: selectedPath,
663
+ type: selectedPath.endsWith(".json") ? "json" : "jiti"
664
+ };
665
+ }
666
+ function normalizeLoadedConfig(value, configPath) {
667
+ const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
668
+ if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
669
+ warnOnce(
670
+ `config-invalid:${configPath}`,
671
+ `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
672
+ );
673
+ return {};
674
+ }
675
+ return normalized;
676
+ }
677
+ function parseJsonConfigFile(configPath) {
678
+ try {
679
+ const content = readFileSync(configPath, "utf-8");
680
+ return normalizeLoadedConfig(JSON.parse(content), configPath);
681
+ } catch (error) {
682
+ console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
683
+ return {};
684
+ }
685
+ }
686
+ function parseExecutableConfigFile(configPath) {
687
+ try {
688
+ const jiti = createJiti(process.cwd(), {
689
+ interopDefault: true,
690
+ moduleCache: false,
691
+ fsCache: false
692
+ });
693
+ return normalizeLoadedConfig(jiti(configPath), configPath);
694
+ } catch (error) {
695
+ console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
696
+ return {};
697
+ }
698
+ }
699
+ function parseConfigFile(config) {
700
+ return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
701
+ }
702
+ function isPrismaAdapter(value) {
703
+ return !!value && typeof value === "object" && value.type === "prisma";
704
+ }
705
+ function isDrizzleAdapter(value) {
706
+ return !!value && typeof value === "object" && value.type === "drizzle";
707
+ }
708
+ function mergeDatabaseRetryConfig(base, override) {
709
+ return {
710
+ ...DEFAULT_DATABASE_RETRY_CONFIG,
711
+ ...base,
712
+ ...override
713
+ };
714
+ }
715
+ function mergeDatabaseDeliveryConfig(base, override) {
716
+ return {
717
+ ...DEFAULT_DATABASE_DELIVERY_CONFIG,
718
+ ...base,
719
+ ...override,
720
+ retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
721
+ };
722
+ }
723
+ function hasPrismaDelegate(adapter) {
724
+ const model = adapter.model ?? "blypLog";
725
+ const client = adapter.client;
726
+ const delegate = client?.[model];
727
+ return !!delegate && typeof delegate.create === "function";
728
+ }
729
+ function hasDrizzleAdapterShape(adapter) {
730
+ const db = adapter.db;
731
+ return !!db && typeof db.insert === "function" && adapter.table !== void 0;
732
+ }
733
+ function resolveDatabaseLoggerConfig(config, sourceType) {
734
+ if (!config) {
735
+ return void 0;
736
+ }
737
+ const adapter = config.adapter;
738
+ let ready = false;
739
+ if (sourceType === "json") {
740
+ warnOnce(
741
+ "database-json-config",
742
+ "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
743
+ );
744
+ } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
745
+ warnOnce(
746
+ `database-dialect:${String(config.dialect)}`,
747
+ `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
748
+ );
749
+ } else if (!adapter) {
750
+ warnOnce(
751
+ "database-adapter-missing",
752
+ "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
753
+ );
754
+ } else if (isPrismaAdapter(adapter)) {
755
+ ready = hasPrismaDelegate({
756
+ ...adapter,
757
+ model: adapter.model ?? "blypLog"
758
+ });
759
+ if (!ready) {
760
+ warnOnce(
761
+ "database-prisma-missing",
762
+ `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
763
+ );
764
+ }
765
+ } else if (isDrizzleAdapter(adapter)) {
766
+ ready = hasDrizzleAdapterShape(adapter);
767
+ if (!ready) {
768
+ warnOnce(
769
+ "database-drizzle-missing",
770
+ "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
771
+ );
772
+ }
773
+ }
774
+ const normalizedAdapter = isPrismaAdapter(adapter) ? {
775
+ ...adapter,
776
+ model: adapter.model ?? "blypLog"
777
+ } : adapter;
778
+ return {
779
+ dialect: config.dialect,
780
+ adapter: normalizedAdapter,
781
+ delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
782
+ ready,
783
+ status: ready ? "enabled" : "missing"
784
+ };
785
+ }
786
+ function mergeRotationConfig(base, override) {
787
+ return {
788
+ ...DEFAULT_ROTATION_CONFIG,
789
+ ...base,
790
+ ...override
791
+ };
792
+ }
793
+ function mergeFileConfig(base, override) {
794
+ return {
795
+ ...DEFAULT_FILE_CONFIG,
796
+ ...base,
797
+ ...override,
798
+ rotation: mergeRotationConfig(base?.rotation, override?.rotation)
799
+ };
800
+ }
801
+ function mergeClientLoggingConfig(base, override) {
802
+ return {
803
+ ...DEFAULT_CLIENT_LOGGING_CONFIG,
804
+ ...base,
805
+ ...override,
806
+ path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
807
+ };
808
+ }
809
+ function mergeDatabaseLoggerConfig(base, override, sourceType) {
810
+ if (!base && !override) {
811
+ return void 0;
812
+ }
813
+ return resolveDatabaseLoggerConfig(
814
+ {
815
+ dialect: override?.dialect ?? base?.dialect,
816
+ adapter: override?.adapter ?? base?.adapter,
817
+ delivery: {
818
+ ...base?.delivery ?? {},
819
+ ...override?.delivery ?? {},
820
+ retry: {
821
+ ...base?.delivery?.retry ?? {},
822
+ ...override?.delivery?.retry ?? {}
823
+ }
824
+ }
825
+ },
826
+ sourceType
827
+ );
828
+ }
829
+ function mergePostHogConnectorConfig(base, override) {
830
+ const enabled = override?.enabled ?? base?.enabled ?? false;
831
+ const projectKey = override?.projectKey ?? base?.projectKey;
832
+ const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
833
+ const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
834
+ const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
835
+ const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
836
+ return {
837
+ enabled,
838
+ mode: override?.mode ?? base?.mode ?? "auto",
839
+ projectKey,
840
+ host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
841
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
842
+ errorTracking: {
843
+ enabled: errorTrackingEnabled,
844
+ mode: errorTrackingMode,
845
+ enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
846
+ ready: errorTrackingReady,
847
+ status: errorTrackingReady ? "enabled" : "missing"
848
+ }
849
+ };
850
+ }
851
+ function mergeDatabuddyConnectorConfig(base, override) {
852
+ const enabled = override?.enabled ?? base?.enabled ?? false;
853
+ const apiKey = override?.apiKey ?? base?.apiKey;
854
+ const websiteId = override?.websiteId ?? base?.websiteId;
855
+ const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
856
+ return {
857
+ enabled,
858
+ mode: override?.mode ?? base?.mode ?? "auto",
859
+ apiKey,
860
+ websiteId,
861
+ namespace: override?.namespace ?? base?.namespace,
862
+ source: override?.source ?? base?.source,
863
+ apiUrl: override?.apiUrl ?? base?.apiUrl,
864
+ debug: override?.debug ?? base?.debug ?? false,
865
+ enableBatching: override?.enableBatching ?? base?.enableBatching ?? true,
866
+ batchSize: override?.batchSize ?? base?.batchSize,
867
+ batchTimeout: override?.batchTimeout ?? base?.batchTimeout,
868
+ maxQueueSize: override?.maxQueueSize ?? base?.maxQueueSize,
869
+ ready,
870
+ status: ready ? "enabled" : "missing"
871
+ };
872
+ }
873
+ function mergeBetterStackConnectorConfig(base, override) {
874
+ const sourceToken = override?.sourceToken ?? base?.sourceToken;
875
+ const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
876
+ const enabled = override?.enabled ?? base?.enabled ?? false;
877
+ const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
878
+ const errorTracking = mergeBetterStackErrorTrackingConfig(
879
+ enabled,
880
+ baseErrorTracking,
881
+ override?.errorTracking
882
+ );
883
+ const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
884
+ return {
885
+ enabled,
886
+ mode: override?.mode ?? base?.mode ?? "auto",
887
+ sourceToken,
888
+ ingestingHost,
889
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
890
+ errorTracking,
891
+ ready,
892
+ status: ready ? "enabled" : "missing"
893
+ };
894
+ }
895
+ function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
896
+ const dsn = override?.dsn ?? base?.dsn;
897
+ const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
898
+ const ready = enabled && hasNonEmptyString(dsn);
899
+ return {
900
+ enabled,
901
+ dsn,
902
+ tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
903
+ environment: override?.environment ?? base?.environment,
904
+ release: override?.release ?? base?.release,
905
+ ready,
906
+ status: ready ? "enabled" : "missing"
907
+ };
908
+ }
909
+ function mergeSentryConnectorConfig(base, override) {
910
+ const dsn = override?.dsn ?? base?.dsn;
911
+ const enabled = override?.enabled ?? base?.enabled ?? false;
912
+ const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
913
+ return {
914
+ enabled,
915
+ mode: override?.mode ?? base?.mode ?? "auto",
916
+ dsn,
917
+ environment: override?.environment ?? base?.environment,
918
+ release: override?.release ?? base?.release,
919
+ ready,
920
+ status: ready ? "enabled" : "missing"
921
+ };
922
+ }
923
+ function mergeOTLPConnectorConfig(base, override) {
924
+ const endpoint = override?.endpoint ?? base?.endpoint;
925
+ const enabled = override?.enabled ?? base?.enabled ?? false;
926
+ const resolvedHeaders = {
927
+ ...{},
928
+ ...override?.headers ?? {}
929
+ };
930
+ const ready = enabled && isAbsoluteHttpUrl(endpoint);
931
+ return {
932
+ name: override?.name ?? base?.name ?? "",
933
+ enabled,
934
+ mode: override?.mode ?? base?.mode ?? "auto",
935
+ endpoint,
936
+ headers: resolvedHeaders,
937
+ auth: override?.auth ?? base?.auth,
938
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
939
+ ready,
940
+ status: ready ? "enabled" : "missing"
941
+ };
942
+ }
943
+ function mergeOTLPConnectorsConfig(base, override) {
944
+ const source = override ?? base ?? [];
945
+ const deduped = /* @__PURE__ */ new Map();
946
+ for (const connector of source) {
947
+ if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
948
+ continue;
949
+ }
950
+ if (deduped.has(connector.name)) {
951
+ warnOnce(
952
+ `otlp-duplicate:${connector.name}`,
953
+ `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
954
+ );
955
+ }
956
+ deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
957
+ }
958
+ return Array.from(deduped.values());
959
+ }
960
+ function mergeConnectorsConfig(base, override) {
961
+ return {
962
+ betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
963
+ databuddy: mergeDatabuddyConnectorConfig(base?.databuddy, override?.databuddy),
964
+ posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
965
+ sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
966
+ otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
967
+ };
968
+ }
969
+ function mergeBlypConfig(base, override = {}, options = {}) {
970
+ return {
971
+ ...base,
972
+ ...override,
973
+ destination: override.destination ?? base.destination ?? "file",
974
+ file: mergeFileConfig(base.file, override.file),
975
+ database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
976
+ clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
977
+ connectors: mergeConnectorsConfig(base.connectors, override.connectors)
978
+ };
979
+ }
980
+ function loadConfig() {
981
+ if (cachedConfig !== null) {
982
+ return cachedConfig;
983
+ }
984
+ bootstrapProjectFiles();
985
+ const configFile = findConfigFile();
986
+ if (configFile) {
987
+ const userConfig = parseConfigFile(configFile);
988
+ cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
989
+ configFileType: configFile.type
990
+ });
991
+ } else {
992
+ cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
993
+ }
994
+ return cachedConfig;
995
+ }
996
+ function resolveConfig(overrides = {}) {
997
+ return mergeBlypConfig(loadConfig(), overrides);
998
+ }
999
+
1000
+ // src/core/helpers.ts
1001
+ function normalizePath(path3) {
1002
+ const queryIndex = path3.indexOf("?");
1003
+ let withoutQuery = queryIndex >= 0 ? path3.substring(0, queryIndex) : path3;
1004
+ if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
1005
+ withoutQuery = withoutQuery.slice(0, -1);
1006
+ }
1007
+ if (!withoutQuery.startsWith("/")) {
1008
+ withoutQuery = "/" + withoutQuery;
1009
+ }
1010
+ return withoutQuery;
1011
+ }
1012
+ function normalizePattern(pattern) {
1013
+ const queryIndex = pattern.indexOf("?");
1014
+ let withoutQuery = queryIndex >= 0 ? pattern.substring(0, queryIndex) : pattern;
1015
+ if (withoutQuery.endsWith("/") && withoutQuery.length > 1) {
1016
+ withoutQuery = withoutQuery.slice(0, -1);
1017
+ }
1018
+ if (!withoutQuery.startsWith("/")) {
1019
+ withoutQuery = "/" + withoutQuery;
1020
+ }
1021
+ return withoutQuery;
1022
+ }
1023
+ function shouldIgnorePath(path3, ignorePaths) {
1024
+ if (!ignorePaths || ignorePaths.length === 0) {
1025
+ return false;
1026
+ }
1027
+ const normalizedPath = normalizePath(path3);
1028
+ return ignorePaths.some((ignoredPattern) => {
1029
+ const normalizedPattern = normalizePattern(ignoredPattern);
1030
+ if (normalizedPattern === normalizedPath) {
1031
+ return true;
1032
+ }
1033
+ if (normalizedPattern === "/**" || normalizedPattern === "**") {
1034
+ return true;
1035
+ }
1036
+ if (normalizedPattern === "/*") {
1037
+ const segments = normalizedPath.split("/").filter((s) => s.length > 0);
1038
+ return segments.length === 1;
1039
+ }
1040
+ if (normalizedPattern.endsWith("/*") && !normalizedPattern.includes("**")) {
1041
+ const prefix = normalizedPattern.slice(0, -1);
1042
+ if (normalizedPath.startsWith(prefix)) {
1043
+ const rest = normalizedPath.slice(prefix.length);
1044
+ const restSegments = rest.split("/").filter((s) => s.length > 0);
1045
+ return restSegments.length === 1;
1046
+ }
1047
+ return false;
1048
+ }
1049
+ if (normalizedPattern.includes("**")) {
1050
+ if (normalizedPattern === "/**") {
1051
+ return true;
1052
+ }
1053
+ if (normalizedPattern.startsWith("/") && normalizedPattern.endsWith("**")) {
1054
+ let prefix2 = normalizedPattern.slice(0, -2);
1055
+ if (prefix2.endsWith("/") && prefix2.length > 1) {
1056
+ prefix2 = prefix2.slice(0, -1);
1057
+ }
1058
+ if (prefix2 === normalizedPath) {
1059
+ return true;
1060
+ }
1061
+ return normalizedPath.startsWith(prefix2 + "/");
1062
+ }
1063
+ const starIndex = normalizedPattern.indexOf("**");
1064
+ let prefix = normalizedPattern.substring(0, starIndex);
1065
+ const suffix = normalizedPattern.substring(starIndex + 2);
1066
+ if (prefix.endsWith("/") && prefix.length > 1) {
1067
+ prefix = prefix.slice(0, -1);
1068
+ }
1069
+ if (prefix === "" && suffix === "") {
1070
+ return true;
1071
+ }
1072
+ if (prefix !== "" && suffix === "") {
1073
+ return normalizedPath.startsWith(prefix + "/");
1074
+ }
1075
+ if (prefix === "" && suffix !== "") {
1076
+ return normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/");
1077
+ }
1078
+ if (prefix !== "" && suffix !== "") {
1079
+ return normalizedPath.startsWith(prefix) && (normalizedPath.endsWith(suffix) || normalizedPath.includes(suffix + "/"));
1080
+ }
1081
+ return false;
1082
+ }
1083
+ if (normalizedPattern.includes("*")) {
1084
+ const lastDotIndex = normalizedPattern.lastIndexOf(".");
1085
+ const lastStarIndex = normalizedPattern.lastIndexOf("*");
1086
+ if (lastDotIndex > lastStarIndex && lastStarIndex > 0) {
1087
+ const charBeforeStar = normalizedPattern[lastStarIndex - 1];
1088
+ if (charBeforeStar === "/") {
1089
+ const extPattern = normalizedPattern.slice(lastStarIndex);
1090
+ const filePart = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1);
1091
+ const extIndex = filePart.lastIndexOf(".");
1092
+ if (extIndex > 0) {
1093
+ const actualExt = filePart.slice(extIndex);
1094
+ return actualExt === extPattern;
1095
+ }
1096
+ }
1097
+ }
1098
+ const regexPattern = normalizedPattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
1099
+ const regex = new RegExp("^" + regexPattern + "$");
1100
+ return regex.test(normalizedPath);
1101
+ }
1102
+ return false;
1103
+ });
1104
+ }
1105
+ function gzipBuffer(buf) {
1106
+ return Buffer.from(gzipSync(buf));
1107
+ }
1108
+ function warnWithConsole(message, error) {
1109
+ console.warn(`[Blyp] Warning: ${message}`, error);
1110
+ }
1111
+ function ensureDirectory(dirPath) {
1112
+ fs.mkdirSync(dirPath, { recursive: true });
1113
+ }
1114
+ function getFileSize(filePath) {
1115
+ try {
1116
+ return fs.statSync(filePath).size;
1117
+ } catch {
1118
+ return 0;
1119
+ }
1120
+ }
1121
+ function formatArchiveTimestamp(timestamp) {
1122
+ const year = timestamp.getUTCFullYear();
1123
+ const month = String(timestamp.getUTCMonth() + 1).padStart(2, "0");
1124
+ const day = String(timestamp.getUTCDate()).padStart(2, "0");
1125
+ const hours = String(timestamp.getUTCHours()).padStart(2, "0");
1126
+ const minutes = String(timestamp.getUTCMinutes()).padStart(2, "0");
1127
+ const seconds = String(timestamp.getUTCSeconds()).padStart(2, "0");
1128
+ return `${year}${month}${day}T${hours}${minutes}${seconds}Z`;
1129
+ }
1130
+ function getUniqueArchivePath(basePath, extension) {
1131
+ let candidate = `${basePath}${extension}`;
1132
+ let suffix = 1;
1133
+ while (fs.existsSync(candidate)) {
1134
+ candidate = `${basePath}-${suffix}${extension}`;
1135
+ suffix += 1;
1136
+ }
1137
+ return candidate;
1138
+ }
1139
+ function pruneArchives(archiveDir, archivePrefix, maxArchives, warn) {
1140
+ const prefix = `${archivePrefix}.`;
1141
+ try {
1142
+ const archivePaths = fs.readdirSync(archiveDir).filter(
1143
+ (name) => name.startsWith(prefix) && (name.endsWith(".ndjson") || name.endsWith(".ndjson.gz"))
1144
+ ).map((name) => path.join(archiveDir, name)).sort((left, right) => {
1145
+ return fs.statSync(left).mtimeMs - fs.statSync(right).mtimeMs;
1146
+ });
1147
+ const deleteCount = Math.max(archivePaths.length - maxArchives, 0);
1148
+ for (let index = 0; index < deleteCount; index += 1) {
1149
+ fs.rmSync(archivePaths[index]);
1150
+ }
1151
+ } catch (error) {
1152
+ warn(`Failed to prune archives for ${archivePrefix}`, error);
1153
+ }
1154
+ }
1155
+ function createSafeReplacer() {
1156
+ const seen = /* @__PURE__ */ new WeakSet();
1157
+ return (_key, value) => {
1158
+ if (typeof value === "function") {
1159
+ return `[Function: ${value.name || "anonymous"}]`;
1160
+ }
1161
+ if (value === void 0) {
1162
+ return "[undefined]";
1163
+ }
1164
+ if (typeof value === "symbol") {
1165
+ return value.toString();
1166
+ }
1167
+ if (value !== null && typeof value === "object") {
1168
+ if (seen.has(value)) {
1169
+ return "[Circular]";
1170
+ }
1171
+ seen.add(value);
1172
+ }
1173
+ return value;
1174
+ };
1175
+ }
1176
+ function serializeLogRecord(record) {
1177
+ return JSON.stringify(record, createSafeReplacer());
1178
+ }
1179
+ function resolveFileLoggerConfig(config) {
1180
+ const fileConfig = config.file;
1181
+ const dir = fileConfig?.dir || config.logDir || path.join(process.cwd(), "logs");
1182
+ const archiveDir = fileConfig?.archiveDir || path.join(dir, "archive");
1183
+ const rotation = fileConfig?.rotation;
1184
+ return {
1185
+ enabled: fileConfig?.enabled ?? true,
1186
+ dir,
1187
+ archiveDir,
1188
+ rotationEnabled: rotation?.enabled ?? true,
1189
+ maxSizeBytes: rotation?.maxSizeBytes ?? 10 * 1024 * 1024,
1190
+ maxArchives: rotation?.maxArchives ?? 5,
1191
+ compress: rotation?.compress ?? true
1192
+ };
1193
+ }
1194
+ var RotatingFileLogger = class {
1195
+ constructor(config, dependencies = {}) {
1196
+ __publicField(this, "config");
1197
+ __publicField(this, "gzip");
1198
+ __publicField(this, "warn");
1199
+ __publicField(this, "combined");
1200
+ __publicField(this, "error");
1201
+ this.config = resolveFileLoggerConfig(config);
1202
+ this.gzip = dependencies.gzip ?? gzipBuffer;
1203
+ this.warn = dependencies.warn ?? warnWithConsole;
1204
+ this.combined = {
1205
+ activePath: path.join(this.config.dir, "log.ndjson"),
1206
+ archivePrefix: "log",
1207
+ bytes: 0,
1208
+ queue: [],
1209
+ processing: false
1210
+ };
1211
+ this.error = {
1212
+ activePath: path.join(this.config.dir, "log.error.ndjson"),
1213
+ archivePrefix: "log.error",
1214
+ bytes: 0,
1215
+ queue: [],
1216
+ processing: false
1217
+ };
1218
+ if (!this.config.enabled) {
1219
+ return;
1220
+ }
1221
+ ensureDirectory(this.config.dir);
1222
+ ensureDirectory(this.config.archiveDir);
1223
+ this.seedStream(this.combined);
1224
+ this.seedStream(this.error);
1225
+ }
1226
+ write(record) {
1227
+ if (!this.config.enabled) {
1228
+ return;
1229
+ }
1230
+ const line = `${serializeLogRecord(record)}
1231
+ `;
1232
+ this.enqueue(this.combined, line);
1233
+ if (record.level === "error" || record.level === "critical") {
1234
+ this.enqueue(this.error, line);
1235
+ }
1236
+ }
1237
+ enqueue(stream, line) {
1238
+ stream.queue.push(line);
1239
+ this.processQueue(stream);
1240
+ }
1241
+ processQueue(stream) {
1242
+ if (stream.processing) {
1243
+ return;
1244
+ }
1245
+ stream.processing = true;
1246
+ try {
1247
+ while (stream.queue.length > 0) {
1248
+ const queuedLine = stream.queue.shift();
1249
+ if (queuedLine === void 0) {
1250
+ continue;
1251
+ }
1252
+ try {
1253
+ this.append(stream, queuedLine);
1254
+ } catch (error) {
1255
+ this.warn(`Failed writing log line for ${stream.archivePrefix}`, error);
1256
+ }
1257
+ }
1258
+ } finally {
1259
+ stream.processing = false;
1260
+ }
1261
+ }
1262
+ seedStream(stream) {
1263
+ stream.bytes = getFileSize(stream.activePath);
1264
+ if (this.config.rotationEnabled && stream.bytes > this.config.maxSizeBytes && stream.bytes > 0) {
1265
+ this.rotate(stream);
1266
+ fs.closeSync(fs.openSync(stream.activePath, "a"));
1267
+ stream.bytes = 0;
1268
+ }
1269
+ }
1270
+ append(stream, line) {
1271
+ ensureDirectory(this.config.dir);
1272
+ const lineBytes = Buffer.byteLength(line, "utf8");
1273
+ if (this.config.rotationEnabled && stream.bytes > 0 && stream.bytes + lineBytes > this.config.maxSizeBytes) {
1274
+ this.rotate(stream);
1275
+ }
1276
+ fs.appendFileSync(stream.activePath, line, "utf8");
1277
+ stream.bytes += lineBytes;
1278
+ }
1279
+ rotate(stream) {
1280
+ ensureDirectory(this.config.archiveDir);
1281
+ if (!fs.existsSync(stream.activePath) || stream.bytes === 0) {
1282
+ stream.bytes = 0;
1283
+ return;
1284
+ }
1285
+ const archiveTimestamp = formatArchiveTimestamp(/* @__PURE__ */ new Date());
1286
+ const archiveBasePath = path.join(
1287
+ this.config.archiveDir,
1288
+ `${stream.archivePrefix}.${archiveTimestamp}`
1289
+ );
1290
+ const archivePath = getUniqueArchivePath(archiveBasePath, ".ndjson");
1291
+ fs.renameSync(stream.activePath, archivePath);
1292
+ if (this.config.compress) {
1293
+ try {
1294
+ const compressedPath = `${archivePath}.gz`;
1295
+ const gzipped = this.gzip(fs.readFileSync(archivePath));
1296
+ fs.writeFileSync(compressedPath, gzipped);
1297
+ fs.rmSync(archivePath);
1298
+ } catch (error) {
1299
+ this.warn(`Failed to gzip archive ${archivePath}`, error);
1300
+ }
1301
+ }
1302
+ stream.bytes = 0;
1303
+ pruneArchives(this.config.archiveDir, stream.archivePrefix, this.config.maxArchives, this.warn);
1304
+ }
1305
+ };
1306
+ function createFileLogger(config) {
1307
+ return new RotatingFileLogger(config);
1308
+ }
1309
+
1310
+ // src/connectors/shared.ts
1311
+ function isBlypConfig(config) {
1312
+ return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
1313
+ }
1314
+ function getPrimaryPayload(record) {
1315
+ return isPlainObject(record.data) ? record.data : record;
1316
+ }
1317
+ function getField(record, key) {
1318
+ if (key in record) {
1319
+ const direct = record[key];
1320
+ if (typeof direct === "string" || typeof direct === "number") {
1321
+ return direct;
1322
+ }
1323
+ }
1324
+ const payload = getPrimaryPayload(record);
1325
+ const nested = payload[key];
1326
+ if (typeof nested === "string" || typeof nested === "number") {
1327
+ return nested;
1328
+ }
1329
+ return void 0;
1330
+ }
1331
+ function getClientPageField(record, key) {
1332
+ const payload = getPrimaryPayload(record);
1333
+ const page = isPlainObject(payload.page) ? payload.page : void 0;
1334
+ const value = page?.[key];
1335
+ return typeof value === "string" ? value : void 0;
1336
+ }
1337
+ function getClientSessionField(record, key) {
1338
+ const payload = getPrimaryPayload(record);
1339
+ const session = isPlainObject(payload.session) ? payload.session : void 0;
1340
+ const value = session?.[key];
1341
+ return typeof value === "string" ? value : void 0;
1342
+ }
1343
+ function getRecordType(record) {
1344
+ return getField(record, "type");
1345
+ }
1346
+
1347
+ // src/connectors/posthog/sender.ts
1348
+ var PREVIOUSLY_CAPTURED_ERROR_KEY = "__posthog_previously_captured_error";
1349
+ var warnedKeys2 = /* @__PURE__ */ new Set();
1350
+ var testHooks = {};
1351
+ var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1352
+ function normalizeHost(host) {
1353
+ const trimmed = (host || "https://us.i.posthog.com").trim();
1354
+ return trimmed.replace(/\/+$/, "");
1355
+ }
1356
+ function buildRecordAttributes(record, source) {
1357
+ const recordType = getRecordType(record);
1358
+ const caller = typeof record.caller === "string" ? record.caller : void 0;
1359
+ const groupId = getField(record, "groupId");
1360
+ const method = getField(record, "method");
1361
+ const path3 = getField(record, "path");
1362
+ const status = getField(record, "status");
1363
+ const duration = getField(record, "duration");
1364
+ const pagePath = getClientPageField(record, "pathname");
1365
+ const pageUrl = getClientPageField(record, "url");
1366
+ const sessionId = getClientSessionField(record, "sessionId");
1367
+ const pageId = getClientSessionField(record, "pageId");
1368
+ const attributes = {
1369
+ "blyp.level": record.level,
1370
+ "blyp.source": source,
1371
+ "blyp.payload": serializeLogRecord(record)
1372
+ };
1373
+ const ifTruthy = [
1374
+ ["blyp.type", recordType],
1375
+ ["blyp.caller", caller],
1376
+ ["blyp.group_id", groupId],
1377
+ ["http.method", method],
1378
+ ["url.path", path3],
1379
+ ["client.page_path", pagePath],
1380
+ ["client.page_url", pageUrl],
1381
+ ["client.session_id", sessionId],
1382
+ ["client.page_id", pageId]
1383
+ ];
1384
+ const ifDefined = [
1385
+ ["http.status_code", status],
1386
+ ["blyp.duration_ms", duration]
1387
+ ];
1388
+ for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
1389
+ for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
1390
+ return attributes;
1391
+ }
1392
+ function normalizeExceptionProperties(value) {
1393
+ if (!isPlainObject(value)) {
1394
+ return {};
1395
+ }
1396
+ return normalizeLogValue(value);
1397
+ }
1398
+ function assignExceptionField(target, key, value) {
1399
+ if (value === void 0) {
1400
+ return;
1401
+ }
1402
+ try {
1403
+ target[key] = value;
1404
+ } catch {
1405
+ }
1406
+ }
1407
+ function createSyntheticError(message, source) {
1408
+ const error = new Error(message);
1409
+ const name = hasNonEmptyString(source.name) ? source.name : "Error";
1410
+ error.name = name;
1411
+ if (hasNonEmptyString(source.stack)) {
1412
+ error.stack = source.stack;
1413
+ }
1414
+ assignExceptionField(error, "cause", source.cause);
1415
+ assignExceptionField(error, "status", source.status);
1416
+ assignExceptionField(error, "statusCode", source.statusCode);
1417
+ assignExceptionField(error, "code", source.code);
1418
+ assignExceptionField(error, "why", source.why);
1419
+ assignExceptionField(error, "fix", source.fix);
1420
+ assignExceptionField(error, "link", source.link);
1421
+ assignExceptionField(error, "details", source.details);
1422
+ return error;
1423
+ }
1424
+ function normalizeExceptionInput(input, fallbackMessage = "Unknown error") {
1425
+ if (input instanceof Error) {
1426
+ return {
1427
+ error: input,
1428
+ properties: normalizeExceptionProperties(input)
1429
+ };
1430
+ }
1431
+ if (isPlainObject(input)) {
1432
+ const message = hasNonEmptyString(input.message) ? input.message : hasNonEmptyString(input.error) ? input.error : fallbackMessage;
1433
+ return {
1434
+ error: createSyntheticError(message, input),
1435
+ properties: normalizeExceptionProperties(input)
1436
+ };
1437
+ }
1438
+ if (typeof input === "string") {
1439
+ return {
1440
+ error: new Error(input),
1441
+ properties: {
1442
+ message: input
1443
+ }
1444
+ };
1445
+ }
1446
+ return {
1447
+ error: new Error(fallbackMessage),
1448
+ properties: {
1449
+ value: normalizeLogValue(input)
1450
+ }
1451
+ };
1452
+ }
1453
+ function createExceptionPropertiesFromRecord(record, source) {
1454
+ return buildRecordAttributes(record, source);
1455
+ }
1456
+ function isPreviouslyCapturedPostHogError(value) {
1457
+ return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY] === true;
1458
+ }
1459
+ function markPostHogCapturedError(value) {
1460
+ if (!isPlainObject(value) || isPreviouslyCapturedPostHogError(value)) {
1461
+ return;
1462
+ }
1463
+ try {
1464
+ Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY, {
1465
+ value: true,
1466
+ enumerable: false,
1467
+ configurable: true,
1468
+ writable: true
1469
+ });
1470
+ } catch {
1471
+ try {
1472
+ value[PREVIOUSLY_CAPTURED_ERROR_KEY] = true;
1473
+ } catch {
1474
+ }
1475
+ }
1476
+ }
1477
+ function isClientLogRecord(record) {
1478
+ return getRecordType(record) === "client_log";
1479
+ }
1480
+ function normalizePostHogRecord(record, connector, source = "server") {
1481
+ const severity = resolveSeverity(record.level);
1482
+ const body = typeof record.message === "string" ? record.message : String(record.message);
1483
+ return {
1484
+ body,
1485
+ severityText: severity.text,
1486
+ severityNumber: severity.number,
1487
+ attributes: buildRecordAttributes(record, source),
1488
+ resourceAttributes: {
1489
+ "service.name": connector.serviceName
1490
+ }
1491
+ };
1492
+ }
1493
+ function resolveSeverity(level) {
1494
+ switch (level) {
1495
+ case "debug":
1496
+ return { text: "debug", number: SeverityNumber.DEBUG };
1497
+ case "warning":
1498
+ case "warn":
1499
+ return { text: "warn", number: SeverityNumber.WARN };
1500
+ case "error":
1501
+ return { text: "error", number: SeverityNumber.ERROR };
1502
+ case "critical":
1503
+ return { text: "fatal", number: SeverityNumber.FATAL };
1504
+ case "success":
1505
+ case "table":
1506
+ case "info":
1507
+ default:
1508
+ return { text: "info", number: SeverityNumber.INFO };
1509
+ }
1510
+ }
1511
+ function registerShutdownHooks(key, shutdown) {
1512
+ const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1513
+ for (const event of handlers) {
1514
+ process.once(event, () => {
1515
+ void shutdown().catch((error) => {
1516
+ warnOnce2(
1517
+ `${key}:shutdown`,
1518
+ "[Blyp] Failed to flush PostHog telemetry during shutdown.",
1519
+ error
1520
+ );
1521
+ });
1522
+ });
1523
+ }
1524
+ }
1525
+ function createDefaultTransport(connector) {
1526
+ const exporter = new OTLPLogExporter({
1527
+ url: `${normalizeHost(connector.host)}/i/v1/logs`,
1528
+ headers: {
1529
+ Authorization: `Bearer ${connector.projectKey}`
1530
+ }
1531
+ });
1532
+ const provider = new LoggerProvider({
1533
+ resource: resourceFromAttributes({
1534
+ "service.name": connector.serviceName
1535
+ }),
1536
+ processors: [new BatchLogRecordProcessor(exporter)]
1537
+ });
1538
+ const logger2 = provider.getLogger("blyp-posthog");
1539
+ return {
1540
+ emit(payload) {
1541
+ logger2.emit({
1542
+ body: payload.body,
1543
+ severityText: payload.severityText,
1544
+ severityNumber: payload.severityNumber,
1545
+ attributes: payload.attributes
1546
+ });
1547
+ },
1548
+ flush() {
1549
+ return provider.forceFlush();
1550
+ },
1551
+ shutdown() {
1552
+ return provider.shutdown();
1553
+ }
1554
+ };
1555
+ }
1556
+ function createDefaultExceptionClient(connector) {
1557
+ const client = new PostHog(connector.projectKey ?? "", {
1558
+ host: connector.host,
1559
+ enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1560
+ });
1561
+ return {
1562
+ captureException(error, distinctId, additionalProperties) {
1563
+ return client.captureExceptionImmediate(error, distinctId, additionalProperties);
1564
+ },
1565
+ shutdown() {
1566
+ return client._shutdown();
1567
+ }
1568
+ };
1569
+ }
1570
+ function resolveConnectorConfig(config) {
1571
+ const connector = isBlypConfig(config) ? config.connectors?.posthog : config;
1572
+ const enabled = connector?.enabled ?? false;
1573
+ const projectKey = connector?.projectKey;
1574
+ const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
1575
+ const errorTrackingMode = connector?.errorTracking?.mode ?? "auto";
1576
+ const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(projectKey);
1577
+ return {
1578
+ enabled,
1579
+ mode: connector?.mode ?? "auto",
1580
+ projectKey,
1581
+ host: normalizeHost(connector?.host),
1582
+ serviceName: connector?.serviceName ?? "blyp-app",
1583
+ errorTracking: {
1584
+ enabled: errorTrackingEnabled,
1585
+ mode: errorTrackingMode,
1586
+ enableExceptionAutocapture: connector?.errorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
1587
+ ready: errorTrackingReady,
1588
+ status: errorTrackingReady ? "enabled" : "missing"
1589
+ }
1590
+ };
1591
+ }
1592
+ function createPostHogSender(config) {
1593
+ const connector = resolveConnectorConfig(config);
1594
+ const key = `${connector.serviceName}:${connector.host}:${connector.mode}`;
1595
+ const ready = connector.enabled === true && hasNonEmptyString(connector.projectKey);
1596
+ const transport = ready ? testHooks.createTransport?.(connector) ?? createDefaultTransport(connector) : void 0;
1597
+ const exceptionClient = connector.errorTracking.ready ? testHooks.createExceptionClient?.(connector) ?? createDefaultExceptionClient(connector) : void 0;
1598
+ const shutdown = async () => {
1599
+ if (transport?.shutdown) {
1600
+ await transport.shutdown();
1601
+ } else if (transport?.flush) {
1602
+ await transport.flush();
1603
+ }
1604
+ if (exceptionClient?.shutdown) {
1605
+ await exceptionClient.shutdown();
1606
+ }
1607
+ };
1608
+ if (transport || exceptionClient) {
1609
+ registerShutdownHooks(key, shutdown);
1610
+ }
1611
+ const emitUnavailableWarning = () => {
1612
+ warnOnce2(
1613
+ `posthog-unavailable:${key}`,
1614
+ "[Blyp] PostHog connector is not configured. Skipping PostHog delivery."
1615
+ );
1616
+ };
1617
+ const emitExceptionUnavailableWarning = () => {
1618
+ warnOnce2(
1619
+ `posthog-exception-unavailable:${key}`,
1620
+ "[Blyp] PostHog error tracking is not configured. Skipping PostHog exception capture."
1621
+ );
1622
+ };
1623
+ return {
1624
+ enabled: connector.enabled,
1625
+ ready,
1626
+ mode: connector.mode,
1627
+ serviceName: connector.serviceName,
1628
+ host: connector.host,
1629
+ status: ready ? "enabled" : "missing",
1630
+ errorTracking: {
1631
+ enabled: connector.errorTracking.enabled,
1632
+ ready: connector.errorTracking.ready,
1633
+ mode: connector.errorTracking.mode,
1634
+ status: connector.errorTracking.status,
1635
+ enableExceptionAutocapture: connector.errorTracking.enableExceptionAutocapture
1636
+ },
1637
+ shouldAutoForwardServerLogs() {
1638
+ return ready && connector.mode === "auto";
1639
+ },
1640
+ shouldAutoCaptureExceptions() {
1641
+ return connector.errorTracking.ready && connector.errorTracking.mode === "auto";
1642
+ },
1643
+ send(record, options = {}) {
1644
+ const source = options.source ?? "server";
1645
+ if (!ready || !transport) {
1646
+ if (options.warnIfUnavailable) {
1647
+ emitUnavailableWarning();
1648
+ }
1649
+ return;
1650
+ }
1651
+ const normalized = normalizePostHogRecord(record, connector, source);
1652
+ try {
1653
+ const result = transport.emit(normalized);
1654
+ if (result && typeof result.catch === "function") {
1655
+ void result.catch((error) => {
1656
+ warnOnce2(
1657
+ `posthog-emit:${key}`,
1658
+ "[Blyp] Failed to deliver log to PostHog.",
1659
+ error
1660
+ );
1661
+ });
1662
+ }
1663
+ } catch (error) {
1664
+ warnOnce2(
1665
+ `posthog-emit:${key}`,
1666
+ "[Blyp] Failed to deliver log to PostHog.",
1667
+ error
1668
+ );
1669
+ }
1670
+ },
1671
+ captureException(error, options = {}) {
1672
+ if (!connector.errorTracking.ready || !exceptionClient) {
1673
+ if (options.warnIfUnavailable) {
1674
+ emitExceptionUnavailableWarning();
1675
+ }
1676
+ return;
1677
+ }
1678
+ if (isPreviouslyCapturedPostHogError(error)) {
1679
+ return;
1680
+ }
1681
+ const normalized = normalizeExceptionInput(
1682
+ error,
1683
+ options.source === "client" ? "Client error" : "Server error"
1684
+ );
1685
+ const properties = {
1686
+ ...normalized.properties,
1687
+ ...options.properties ?? {},
1688
+ "blyp.source": options.source ?? "server"
1689
+ };
1690
+ try {
1691
+ const result = exceptionClient.captureException(
1692
+ normalized.error,
1693
+ options.distinctId,
1694
+ properties
1695
+ );
1696
+ markPostHogCapturedError(error);
1697
+ markPostHogCapturedError(normalized.error);
1698
+ if (result && typeof result.catch === "function") {
1699
+ void result.catch((captureError) => {
1700
+ warnOnce2(
1701
+ `posthog-capture:${key}`,
1702
+ "[Blyp] Failed to capture exception in PostHog.",
1703
+ captureError
1704
+ );
1705
+ });
1706
+ }
1707
+ } catch (captureError) {
1708
+ warnOnce2(
1709
+ `posthog-capture:${key}`,
1710
+ "[Blyp] Failed to capture exception in PostHog.",
1711
+ captureError
1712
+ );
1713
+ }
1714
+ },
1715
+ async flush() {
1716
+ try {
1717
+ if (transport?.flush) {
1718
+ await transport.flush();
1719
+ }
1720
+ } catch (error) {
1721
+ warnOnce2(
1722
+ `posthog-flush:${key}`,
1723
+ "[Blyp] Failed to flush PostHog telemetry.",
1724
+ error
1725
+ );
1726
+ }
1727
+ }
1728
+ };
1729
+ }
1730
+ function buildPostHogExceptionProperties(record, source, properties = {}) {
1731
+ return {
1732
+ ...createExceptionPropertiesFromRecord(record, source),
1733
+ ...properties
1734
+ };
1735
+ }
1736
+
1737
+ // src/core/log-record.ts
1738
+ var RECORD_LEVELS = {
1739
+ success: "success",
1740
+ critical: "critical",
1741
+ warning: "warning",
1742
+ info: "info",
1743
+ debug: "debug",
1744
+ error: "error",
1745
+ warn: "warning",
1746
+ table: "table"
1747
+ };
1748
+ function normalizePath2(filePath) {
1749
+ return filePath.replace(/\\/g, "/");
1750
+ }
1751
+ function isInternalLoggerFrame(filePath) {
1752
+ const normalizedPath = normalizePath2(filePath);
1753
+ return normalizedPath.startsWith("node:") || normalizedPath.includes("/node_modules/pino") || normalizedPath.includes("/node_modules/pino-pretty") || normalizedPath.includes("/node_modules/@blyp/core/") || normalizedPath.includes("/blyp/src/core/") || normalizedPath.includes("/blyp/src/frameworks/") || normalizedPath.includes("/blyp/src/posthog/") || normalizedPath.includes("/blyp/dist/");
1754
+ }
1755
+ function formatCallerPath(filePath) {
1756
+ const normalizedPath = normalizePath2(filePath);
1757
+ const normalizedCwd = normalizePath2(process.cwd());
1758
+ return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
1759
+ }
1760
+ function getCallerLocation() {
1761
+ try {
1762
+ const stack = new Error().stack;
1763
+ if (!stack) {
1764
+ return { file: null, line: null };
1765
+ }
1766
+ const lines = stack.split("\n");
1767
+ let fallback = null;
1768
+ for (let index = 2; index < lines.length; index += 1) {
1769
+ const line = lines[index];
1770
+ if (!line) {
1771
+ continue;
1772
+ }
1773
+ const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
1774
+ if (!match) {
1775
+ continue;
1776
+ }
1777
+ const fileName = match[1] || "";
1778
+ const lineNumber = parseInt(match[2] || "0", 10) || null;
1779
+ if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
1780
+ const formattedPath = formatCallerPath(fileName);
1781
+ const normalizedFormattedPath = normalizePath2(formattedPath);
1782
+ if (!normalizedFormattedPath.startsWith("dist/")) {
1783
+ return { file: formattedPath, line: lineNumber };
1784
+ }
1785
+ fallback ?? (fallback = { file: formattedPath, line: lineNumber });
1786
+ }
1787
+ }
1788
+ if (fallback) {
1789
+ return fallback;
1790
+ }
1791
+ } catch {
1792
+ return { file: null, line: null };
1793
+ }
1794
+ return { file: null, line: null };
1795
+ }
1796
+ var serializeMessage = serializeLogMessage;
1797
+ function stripAnsi(value) {
1798
+ return value.replace(/\u001b\[[0-9;]*m/g, "");
1799
+ }
1800
+ function buildRecord(level, message, args, bindings) {
1801
+ const { file, line } = getCallerLocation();
1802
+ const serializedMessage = serializeMessage(message);
1803
+ const record = {
1804
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1805
+ level: RECORD_LEVELS[level],
1806
+ message: stripAnsi(serializedMessage)
1807
+ };
1808
+ if (message instanceof Error) {
1809
+ record.error = normalizeError(message);
1810
+ }
1811
+ if (file) {
1812
+ record.caller = line !== null ? `${file}:${line}` : file;
1813
+ }
1814
+ if (args.length === 1) {
1815
+ record.data = normalizeLogValue(args[0]);
1816
+ } else if (args.length > 1) {
1817
+ record.data = normalizeLogValue(args);
1818
+ }
1819
+ if (Object.keys(bindings).length > 0) {
1820
+ record.bindings = normalizeLogValue(bindings);
1821
+ }
1822
+ return record;
1823
+ }
1824
+ function buildStructuredRecord(level, message, payload, bindings) {
1825
+ const { file, line } = getCallerLocation();
1826
+ const normalizedPayload = normalizeLogValue(payload);
1827
+ const record = {
1828
+ message: stripAnsi(message),
1829
+ ...normalizedPayload
1830
+ };
1831
+ if (file) {
1832
+ record.caller = line !== null ? `${file}:${line}` : file;
1833
+ }
1834
+ if (Object.keys(bindings).length > 0) {
1835
+ record.bindings = normalizeLogValue(bindings);
1836
+ }
1837
+ record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
1838
+ record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
1839
+ return record;
1840
+ }
1841
+ function resolveStructuredWriteLevel(level) {
1842
+ switch (level) {
1843
+ case "debug":
1844
+ return "debug";
1845
+ case "warning":
1846
+ return "warning";
1847
+ case "warn":
1848
+ return "warn";
1849
+ case "error":
1850
+ return "error";
1851
+ case "success":
1852
+ return "success";
1853
+ case "critical":
1854
+ return "critical";
1855
+ case "table":
1856
+ return "table";
1857
+ case "info":
1858
+ default:
1859
+ return "info";
1860
+ }
1861
+ }
1862
+
1863
+ // src/core/sinks/file-primary-sink.ts
1864
+ var FilePrimarySink = class {
1865
+ constructor(logger2) {
1866
+ this.logger = logger2;
1867
+ __publicField(this, "isAsync", false);
1868
+ __publicField(this, "isReady", true);
1869
+ }
1870
+ write(record) {
1871
+ this.logger.write(record);
1872
+ }
1873
+ async flush() {
1874
+ }
1875
+ async shutdown() {
1876
+ }
1877
+ };
1878
+ function createFilePrimarySink(config) {
1879
+ return new FilePrimarySink(createFileLogger(config));
1880
+ }
1881
+
1882
+ // src/database/adapters/drizzle.ts
1883
+ function createDrizzleRowWriter(adapter) {
1884
+ const db = adapter.db;
1885
+ if (typeof db?.insert !== "function" || adapter.table === void 0) {
1886
+ throw new Error(
1887
+ "[Blyp] Drizzle database adapter is missing a db.insert function or table reference."
1888
+ );
1889
+ }
1890
+ return {
1891
+ async insert(rows) {
1892
+ if (rows.length === 0) {
1893
+ return;
1894
+ }
1895
+ await db.insert(adapter.table).values(rows);
1896
+ }
1897
+ };
1898
+ }
1899
+
1900
+ // src/database/adapters/prisma.ts
1901
+ function shouldFallbackFromCreateMany(error) {
1902
+ const message = String(error ?? "");
1903
+ return message.includes("createMany") || message.includes("Unknown argument") || message.includes("not supported") || message.includes("is not a function");
1904
+ }
1905
+ function createPrismaRowWriter(adapter) {
1906
+ const client = adapter.client;
1907
+ const model = adapter.model ?? "blypLog";
1908
+ const delegateCandidate = client[model];
1909
+ if (!delegateCandidate || typeof delegateCandidate.create !== "function") {
1910
+ throw new Error(
1911
+ `[Blyp] Prisma database adapter is missing the "${model}" delegate or its create method.`
1912
+ );
1913
+ }
1914
+ const delegate = delegateCandidate;
1915
+ let useCreateMany = typeof delegate.createMany === "function";
1916
+ async function fallbackInsert(rows) {
1917
+ if (typeof client.$transaction === "function") {
1918
+ await client.$transaction(
1919
+ rows.map((row) => delegate.create({ data: row }))
1920
+ );
1921
+ return;
1922
+ }
1923
+ for (const row of rows) {
1924
+ await delegate.create({ data: row });
1925
+ }
1926
+ }
1927
+ return {
1928
+ async insert(rows) {
1929
+ if (rows.length === 0) {
1930
+ return;
1931
+ }
1932
+ if (rows.length === 1) {
1933
+ await delegate.create({ data: rows[0] });
1934
+ return;
1935
+ }
1936
+ if (!useCreateMany || typeof delegate.createMany !== "function") {
1937
+ await fallbackInsert(rows);
1938
+ return;
1939
+ }
1940
+ try {
1941
+ await delegate.createMany({ data: rows });
1942
+ } catch (error) {
1943
+ if (!shouldFallbackFromCreateMany(error)) {
1944
+ throw error;
1945
+ }
1946
+ useCreateMany = false;
1947
+ await fallbackInsert(rows);
1948
+ }
1949
+ }
1950
+ };
1951
+ }
1952
+
1953
+ // src/database/helpers.ts
1954
+ function normalizeNullableNumber(value) {
1955
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1956
+ }
1957
+ function normalizeNullableString(value) {
1958
+ return typeof value === "string" && value.length > 0 ? value : null;
1959
+ }
1960
+ function parseTimestamp(value) {
1961
+ if (typeof value === "string") {
1962
+ const timestamp = new Date(value);
1963
+ if (!Number.isNaN(timestamp.getTime())) {
1964
+ return timestamp;
1965
+ }
1966
+ }
1967
+ return /* @__PURE__ */ new Date();
1968
+ }
1969
+ function toDatabaseLogRow(record) {
1970
+ const normalizedRecord = normalizeLogValue(record);
1971
+ return {
1972
+ id: randomUUID(),
1973
+ timestamp: parseTimestamp(record.timestamp),
1974
+ level: record.level,
1975
+ message: record.message,
1976
+ caller: normalizeNullableString(record.caller),
1977
+ type: normalizeNullableString(record.type),
1978
+ groupId: normalizeNullableString(record.groupId),
1979
+ method: normalizeNullableString(record.method),
1980
+ path: normalizeNullableString(record.path),
1981
+ status: normalizeNullableNumber(record.status),
1982
+ duration: normalizeNullableNumber(record.duration),
1983
+ hasError: normalizedRecord.error != null,
1984
+ data: normalizedRecord.data ?? null,
1985
+ bindings: normalizedRecord.bindings ?? null,
1986
+ error: normalizedRecord.error ?? null,
1987
+ events: normalizedRecord.events ?? null,
1988
+ record: normalizedRecord,
1989
+ createdAt: /* @__PURE__ */ new Date()
1990
+ };
1991
+ }
1992
+ function isPrismaAdapter2(adapter) {
1993
+ return !!adapter && adapter.type === "prisma";
1994
+ }
1995
+ function isDrizzleAdapter2(adapter) {
1996
+ return !!adapter && adapter.type === "drizzle";
1997
+ }
1998
+ function createDatabaseRowWriter(config) {
1999
+ if (isPrismaAdapter2(config.adapter)) {
2000
+ return createPrismaRowWriter(config.adapter);
2001
+ }
2002
+ if (isDrizzleAdapter2(config.adapter)) {
2003
+ return createDrizzleRowWriter(config.adapter);
2004
+ }
2005
+ throw new Error("[Blyp] Unsupported database adapter configuration.");
2006
+ }
2007
+
2008
+ // src/core/sinks/database-primary-sink.ts
2009
+ function delay(ms) {
2010
+ return new Promise((resolve2) => {
2011
+ setTimeout(resolve2, ms);
2012
+ });
2013
+ }
2014
+ var DatabasePrimarySink = class {
2015
+ constructor(config) {
2016
+ this.config = config;
2017
+ __publicField(this, "isAsync", true);
2018
+ __publicField(this, "isReady", true);
2019
+ __publicField(this, "warnOnce", createWarnOnceLogger(/* @__PURE__ */ new Set()));
2020
+ __publicField(this, "queue", []);
2021
+ __publicField(this, "writer");
2022
+ __publicField(this, "timer", null);
2023
+ __publicField(this, "processing", false);
2024
+ __publicField(this, "closed", false);
2025
+ __publicField(this, "terminalError", null);
2026
+ __publicField(this, "activeDispatch", null);
2027
+ this.writer = createDatabaseRowWriter(config);
2028
+ }
2029
+ write(record) {
2030
+ if (this.closed) {
2031
+ return;
2032
+ }
2033
+ this.enqueue(toDatabaseLogRow(record));
2034
+ this.scheduleDispatch();
2035
+ }
2036
+ async flush() {
2037
+ if (this.timer) {
2038
+ clearTimeout(this.timer);
2039
+ this.timer = null;
2040
+ }
2041
+ const flushPromise = (async () => {
2042
+ await this.drain();
2043
+ if (this.terminalError) {
2044
+ throw this.terminalError;
2045
+ }
2046
+ })();
2047
+ let timeoutHandle = null;
2048
+ try {
2049
+ await Promise.race([
2050
+ flushPromise,
2051
+ new Promise((_, reject) => {
2052
+ timeoutHandle = setTimeout(() => {
2053
+ this.warnOnce(
2054
+ "database-flush-timeout",
2055
+ `[Blyp] Warning: Timed out flushing database logs after ${this.config.delivery.flushTimeoutMs}ms.`
2056
+ );
2057
+ reject(new Error("[Blyp] Timed out flushing database logs."));
2058
+ }, this.config.delivery.flushTimeoutMs);
2059
+ })
2060
+ ]);
2061
+ } finally {
2062
+ if (timeoutHandle) {
2063
+ clearTimeout(timeoutHandle);
2064
+ }
2065
+ }
2066
+ }
2067
+ async shutdown() {
2068
+ this.closed = true;
2069
+ await this.flush();
2070
+ }
2071
+ enqueue(row) {
2072
+ this.queue.push(row);
2073
+ const overflow = this.queue.length - this.config.delivery.maxQueueSize;
2074
+ if (overflow <= 0) {
2075
+ return;
2076
+ }
2077
+ this.warnOnce(
2078
+ "database-overflow",
2079
+ `[Blyp] Warning: Database log queue exceeded ${this.config.delivery.maxQueueSize} entries. Applying ${this.config.delivery.overflowStrategy} overflow handling.`
2080
+ );
2081
+ if (this.config.delivery.overflowStrategy === "drop-new") {
2082
+ this.queue.splice(this.config.delivery.maxQueueSize);
2083
+ return;
2084
+ }
2085
+ this.queue.splice(0, overflow);
2086
+ }
2087
+ scheduleDispatch() {
2088
+ if (this.processing) {
2089
+ return;
2090
+ }
2091
+ if (this.config.delivery.strategy === "immediate") {
2092
+ void this.drain();
2093
+ return;
2094
+ }
2095
+ if (this.queue.length >= this.config.delivery.batchSize) {
2096
+ void this.drain();
2097
+ return;
2098
+ }
2099
+ if (this.timer) {
2100
+ return;
2101
+ }
2102
+ this.timer = setTimeout(() => {
2103
+ this.timer = null;
2104
+ void this.drain();
2105
+ }, this.config.delivery.flushIntervalMs);
2106
+ }
2107
+ async drain() {
2108
+ if (this.processing) {
2109
+ if (this.activeDispatch) {
2110
+ await this.activeDispatch;
2111
+ }
2112
+ return;
2113
+ }
2114
+ this.processing = true;
2115
+ this.activeDispatch = this.processQueue();
2116
+ try {
2117
+ await this.activeDispatch;
2118
+ } finally {
2119
+ this.processing = false;
2120
+ this.activeDispatch = null;
2121
+ }
2122
+ }
2123
+ async processQueue() {
2124
+ while (this.queue.length > 0) {
2125
+ const batchSize = this.config.delivery.strategy === "batch" ? Math.max(1, this.config.delivery.batchSize) : 1;
2126
+ const batch = this.queue.splice(0, batchSize);
2127
+ try {
2128
+ await this.insertWithRetry(batch);
2129
+ } catch (error) {
2130
+ const failure = error instanceof Error ? error : new Error(String(error ?? "Unknown database logging failure"));
2131
+ this.terminalError = failure;
2132
+ this.warnOnce(
2133
+ "database-insert-failure",
2134
+ `[Blyp] Warning: Failed to persist logs to the ${this.config.dialect ?? "database"} database.`,
2135
+ failure
2136
+ );
2137
+ throw failure;
2138
+ }
2139
+ }
2140
+ }
2141
+ async insertWithRetry(batch) {
2142
+ const maxAttempts = Math.max(1, this.config.delivery.retry.maxRetries + 1);
2143
+ let attempt = 0;
2144
+ while (attempt < maxAttempts) {
2145
+ attempt += 1;
2146
+ try {
2147
+ await this.writer.insert(batch);
2148
+ return;
2149
+ } catch (error) {
2150
+ if (attempt >= maxAttempts) {
2151
+ throw error;
2152
+ }
2153
+ await delay(this.config.delivery.retry.backoffMs);
2154
+ }
2155
+ }
2156
+ }
2157
+ };
2158
+
2159
+ // src/core/primary-sink.ts
2160
+ var NoopPrimarySink = class {
2161
+ constructor() {
2162
+ __publicField(this, "isAsync", false);
2163
+ __publicField(this, "isReady", false);
2164
+ }
2165
+ write(_record) {
2166
+ }
2167
+ async flush() {
2168
+ }
2169
+ async shutdown() {
2170
+ }
2171
+ };
2172
+ var warnOnce3 = createWarnOnceLogger(/* @__PURE__ */ new Set());
2173
+ function createPrimarySink(config) {
2174
+ if (config.destination !== "database") {
2175
+ return createFilePrimarySink(config);
2176
+ }
2177
+ const databaseConfig = config.database;
2178
+ if (!databaseConfig?.ready) {
2179
+ warnOnce3(
2180
+ "database-sink-disabled",
2181
+ "[Blyp] Warning: Database destination is configured but not ready. Falling back to a no-op primary sink."
2182
+ );
2183
+ return new NoopPrimarySink();
2184
+ }
2185
+ return new DatabasePrimarySink(databaseConfig);
2186
+ }
2187
+ var PREVIOUSLY_CAPTURED_ERROR_KEY2 = "__betterstack_previously_captured_error";
2188
+ var warnedKeys3 = /* @__PURE__ */ new Set();
2189
+ var testHooks2 = {};
2190
+ var warnOnce4 = createErrorOnceLogger(warnedKeys3);
2191
+ function getSentryModule() {
2192
+ return testHooks2.module ?? Sentry;
2193
+ }
2194
+ function resolveConnectorConfig2(config) {
2195
+ const connector = isBlypConfig(config) ? config.connectors?.betterstack : config;
2196
+ const enabled = connector?.enabled ?? false;
2197
+ const sourceToken = connector?.sourceToken;
2198
+ const ingestingHost = connector?.ingestingHost;
2199
+ const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
2200
+ const errorTrackingDsn = connector?.errorTracking?.dsn;
2201
+ const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(errorTrackingDsn);
2202
+ const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
2203
+ return {
2204
+ enabled,
2205
+ mode: connector?.mode ?? "auto",
2206
+ sourceToken,
2207
+ ingestingHost,
2208
+ serviceName: connector?.serviceName ?? "blyp-app",
2209
+ errorTracking: {
2210
+ enabled: errorTrackingEnabled,
2211
+ dsn: errorTrackingDsn,
2212
+ tracesSampleRate: connector?.errorTracking?.tracesSampleRate ?? 1,
2213
+ environment: connector?.errorTracking?.environment,
2214
+ release: connector?.errorTracking?.release,
2215
+ ready: errorTrackingReady,
2216
+ status: errorTrackingReady ? "enabled" : "missing"
2217
+ },
2218
+ ready,
2219
+ status: ready ? "enabled" : "missing"
2220
+ };
2221
+ }
2222
+ function resolveBetterStackLevel(level) {
2223
+ switch (level) {
2224
+ case "debug":
2225
+ return "debug";
2226
+ case "warning":
2227
+ case "warn":
2228
+ return "warn";
2229
+ case "error":
2230
+ return "error";
2231
+ case "critical":
2232
+ return "fatal";
2233
+ case "success":
2234
+ case "table":
2235
+ case "info":
2236
+ default:
2237
+ return "info";
2238
+ }
2239
+ }
2240
+ function parseCaller(caller) {
2241
+ if (typeof caller !== "string" || caller.trim().length === 0) {
2242
+ return {};
2243
+ }
2244
+ const match = caller.match(/^(.*):(\d+)$/);
2245
+ if (!match) {
2246
+ return {};
2247
+ }
2248
+ const file = match[1]?.trim();
2249
+ const line = Number.parseInt(match[2] ?? "", 10);
2250
+ return {
2251
+ ...file ? { file } : {},
2252
+ ...Number.isFinite(line) ? { line } : {}
2253
+ };
2254
+ }
2255
+ function buildContext(record, connector, source) {
2256
+ const recordType = getRecordType(record);
2257
+ const groupId = getField(record, "groupId");
2258
+ const method = getField(record, "method");
2259
+ const path3 = getField(record, "path");
2260
+ const status = getField(record, "status");
2261
+ const duration = getField(record, "duration");
2262
+ const pagePath = getClientPageField(record, "pathname");
2263
+ const pageUrl = getClientPageField(record, "url");
2264
+ const sessionId = getClientSessionField(record, "sessionId");
2265
+ const pageId = getClientSessionField(record, "pageId");
2266
+ const runtime2 = parseCaller(record.caller);
2267
+ return {
2268
+ service: connector.serviceName,
2269
+ context: {
2270
+ blyp: {
2271
+ level: record.level,
2272
+ source,
2273
+ ...recordType ? { type: recordType } : {},
2274
+ ...groupId ? { group_id: groupId } : {},
2275
+ ...record.caller ? { caller: record.caller } : {},
2276
+ ...duration !== void 0 ? { duration_ms: duration } : {},
2277
+ ...record.bindings ? { bindings: record.bindings } : {},
2278
+ payload: serializeLogRecord(record)
2279
+ },
2280
+ ...method || path3 || status !== void 0 ? {
2281
+ http: {
2282
+ ...method ? { method } : {},
2283
+ ...path3 ? { path: path3 } : {},
2284
+ ...status !== void 0 ? { status_code: status } : {}
2285
+ }
2286
+ } : {},
2287
+ ...pagePath || pageUrl || sessionId || pageId ? {
2288
+ client: {
2289
+ ...pagePath ? { page_path: pagePath } : {},
2290
+ ...pageUrl ? { page_url: pageUrl } : {},
2291
+ ...sessionId ? { session_id: sessionId } : {},
2292
+ ...pageId ? { page_id: pageId } : {}
2293
+ }
2294
+ } : {},
2295
+ ...Object.keys(runtime2).length > 0 ? { runtime: runtime2 } : {},
2296
+ ...record.data !== void 0 ? { data: record.data } : {},
2297
+ ...record.error !== void 0 ? { error: record.error } : {}
2298
+ }
2299
+ };
2300
+ }
2301
+ function toExceptionCandidate(value) {
2302
+ if (!isPlainObject(value)) {
2303
+ return void 0;
2304
+ }
2305
+ const message = typeof value.message === "string" ? value.message : void 0;
2306
+ const name = typeof value.name === "string" ? value.name : void 0;
2307
+ const stack = typeof value.stack === "string" ? value.stack : void 0;
2308
+ if (!message && !name && !stack) {
2309
+ return void 0;
2310
+ }
2311
+ const error = new Error(message ?? name ?? "Unknown error");
2312
+ error.name = name ?? "Error";
2313
+ if (stack) {
2314
+ error.stack = stack;
2315
+ }
2316
+ for (const [key, entry] of Object.entries(value)) {
2317
+ if (key === "message" || key === "name" || key === "stack") {
2318
+ continue;
2319
+ }
2320
+ error[key] = entry;
2321
+ }
2322
+ return error;
2323
+ }
2324
+ function normalizeScopeLevel(level) {
2325
+ switch (level) {
2326
+ case "debug":
2327
+ return "debug";
2328
+ case "warning":
2329
+ case "warn":
2330
+ return "warning";
2331
+ case "critical":
2332
+ return "fatal";
2333
+ case "error":
2334
+ return "error";
2335
+ case "success":
2336
+ case "table":
2337
+ case "info":
2338
+ default:
2339
+ return "info";
2340
+ }
2341
+ }
2342
+ function normalizeExceptionInput2(input) {
2343
+ if (input instanceof Error) {
2344
+ return input;
2345
+ }
2346
+ const direct = toExceptionCandidate(input);
2347
+ if (direct) {
2348
+ return direct;
2349
+ }
2350
+ if (typeof input === "string") {
2351
+ return new Error(input);
2352
+ }
2353
+ return new Error("Unknown Better Stack exception");
2354
+ }
2355
+ function isPreviouslyCapturedError(value) {
2356
+ return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY2] === true;
2357
+ }
2358
+ function markCapturedError(value) {
2359
+ if (!isPlainObject(value) || isPreviouslyCapturedError(value)) {
2360
+ return;
2361
+ }
2362
+ try {
2363
+ Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY2, {
2364
+ value: true,
2365
+ enumerable: false,
2366
+ configurable: true,
2367
+ writable: true
2368
+ });
2369
+ } catch {
2370
+ try {
2371
+ value[PREVIOUSLY_CAPTURED_ERROR_KEY2] = true;
2372
+ } catch {
2373
+ }
2374
+ }
2375
+ }
2376
+ function createDefaultClient(connector) {
2377
+ return new Logtail(connector.sourceToken ?? "", {
2378
+ endpoint: connector.ingestingHost,
2379
+ captureStackContext: false
2380
+ });
2381
+ }
2382
+ function getClientOptions(client) {
2383
+ return client?.getOptions?.() ?? {};
2384
+ }
2385
+ function registerShutdownHooks2(key, flush) {
2386
+ const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2387
+ for (const event of handlers) {
2388
+ process.once(event, () => {
2389
+ void flush().catch((error) => {
2390
+ warnOnce4(
2391
+ `${key}:shutdown`,
2392
+ "[Blyp] Failed to flush Better Stack logs during shutdown.",
2393
+ error
2394
+ );
2395
+ });
2396
+ });
2397
+ }
2398
+ }
2399
+ function createBetterStackSender(config) {
2400
+ const connector = resolveConnectorConfig2(config);
2401
+ const key = `${connector.serviceName}:${connector.ingestingHost ?? "missing"}:${connector.mode}`;
2402
+ const sentryModule = getSentryModule();
2403
+ const client = connector.ready ? testHooks2.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
2404
+ let sentryClient = connector.errorTracking.enabled ? sentryModule?.getClient?.() : void 0;
2405
+ if (sentryClient) {
2406
+ const options = getClientOptions(sentryClient);
2407
+ if (hasNonEmptyString(connector.errorTracking.dsn) && connector.errorTracking.dsn !== options.dsn || hasNonEmptyString(connector.errorTracking.environment) && connector.errorTracking.environment !== options.environment || hasNonEmptyString(connector.errorTracking.release) && connector.errorTracking.release !== options.release) {
2408
+ warnOnce4(
2409
+ `betterstack-error-mismatch:${key}`,
2410
+ "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking."
2411
+ );
2412
+ }
2413
+ }
2414
+ if (!sentryClient && connector.errorTracking.enabled && hasNonEmptyString(connector.errorTracking.dsn) && sentryModule) {
2415
+ try {
2416
+ sentryModule.init({
2417
+ dsn: connector.errorTracking.dsn,
2418
+ tracesSampleRate: connector.errorTracking.tracesSampleRate,
2419
+ environment: connector.errorTracking.environment,
2420
+ release: connector.errorTracking.release
2421
+ });
2422
+ sentryClient = sentryModule.getClient();
2423
+ } catch (error) {
2424
+ warnOnce4(
2425
+ `betterstack-error-init:${key}`,
2426
+ "[Blyp] Failed to initialize Better Stack error tracking.",
2427
+ error
2428
+ );
2429
+ }
2430
+ }
2431
+ const errorTrackingReady = connector.errorTracking.enabled && sentryClient !== void 0;
2432
+ if (client || errorTrackingReady) {
2433
+ registerShutdownHooks2(key, async () => {
2434
+ if (client) {
2435
+ await client.flush();
2436
+ }
2437
+ if (errorTrackingReady) {
2438
+ await sentryModule.flush(2e3);
2439
+ }
2440
+ });
2441
+ }
2442
+ const emitUnavailableWarning = () => {
2443
+ warnOnce4(
2444
+ `betterstack-unavailable:${key}`,
2445
+ "[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery."
2446
+ );
2447
+ };
2448
+ const emitExceptionUnavailableWarning = () => {
2449
+ warnOnce4(
2450
+ `betterstack-exception-unavailable:${key}`,
2451
+ "[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture."
2452
+ );
2453
+ };
2454
+ return {
2455
+ enabled: connector.enabled,
2456
+ ready: connector.ready,
2457
+ mode: connector.mode,
2458
+ serviceName: connector.serviceName,
2459
+ ingestingHost: connector.ingestingHost,
2460
+ status: connector.status,
2461
+ errorTracking: {
2462
+ enabled: connector.errorTracking.enabled,
2463
+ ready: errorTrackingReady,
2464
+ status: errorTrackingReady ? "enabled" : "missing",
2465
+ dsn: connector.errorTracking.dsn,
2466
+ tracesSampleRate: connector.errorTracking.tracesSampleRate,
2467
+ environment: connector.errorTracking.environment,
2468
+ release: connector.errorTracking.release
2469
+ },
2470
+ shouldAutoForwardServerLogs() {
2471
+ return connector.ready && connector.mode === "auto";
2472
+ },
2473
+ shouldAutoCaptureExceptions() {
2474
+ return errorTrackingReady;
2475
+ },
2476
+ send(record, options = {}) {
2477
+ if (!connector.ready || !client) {
2478
+ if (options.warnIfUnavailable) {
2479
+ emitUnavailableWarning();
2480
+ }
2481
+ return;
2482
+ }
2483
+ const source = options.source ?? "server";
2484
+ void client.log(
2485
+ record.message,
2486
+ resolveBetterStackLevel(record.level),
2487
+ buildContext(record, connector, source)
2488
+ ).catch((error) => {
2489
+ warnOnce4(
2490
+ `betterstack-send:${key}`,
2491
+ "[Blyp] Failed to deliver log to Better Stack.",
2492
+ error
2493
+ );
2494
+ });
2495
+ },
2496
+ captureException(error, options = {}) {
2497
+ if (!errorTrackingReady || !sentryModule) {
2498
+ if (options.warnIfUnavailable) {
2499
+ emitExceptionUnavailableWarning();
2500
+ }
2501
+ return;
2502
+ }
2503
+ if (isPreviouslyCapturedError(error)) {
2504
+ return;
2505
+ }
2506
+ try {
2507
+ const exception = normalizeExceptionInput2(error);
2508
+ sentryModule.withScope((scope) => {
2509
+ scope.setLevel(
2510
+ normalizeScopeLevel(
2511
+ options.source === "client" ? "error" : "error"
2512
+ )
2513
+ );
2514
+ scope.setContext("blyp", {
2515
+ source: options.source ?? "server",
2516
+ ...options.context ? { context: options.context } : {}
2517
+ });
2518
+ sentryModule.captureException(exception);
2519
+ });
2520
+ markCapturedError(error);
2521
+ markCapturedError(exception);
2522
+ } catch (captureError) {
2523
+ warnOnce4(
2524
+ `betterstack-manual-capture:${key}`,
2525
+ "[Blyp] Failed to capture exception in Better Stack error tracking.",
2526
+ captureError
2527
+ );
2528
+ }
2529
+ },
2530
+ async flush() {
2531
+ if (!client) {
2532
+ if (!errorTrackingReady || !sentryModule) {
2533
+ return;
2534
+ }
2535
+ }
2536
+ try {
2537
+ if (client) {
2538
+ await client.flush();
2539
+ }
2540
+ if (errorTrackingReady && sentryModule) {
2541
+ await sentryModule.flush(2e3);
2542
+ }
2543
+ } catch (error) {
2544
+ warnOnce4(
2545
+ `betterstack-flush:${key}`,
2546
+ "[Blyp] Failed to flush Better Stack logs.",
2547
+ error
2548
+ );
2549
+ }
2550
+ }
2551
+ };
2552
+ }
2553
+ var warnedKeys4 = /* @__PURE__ */ new Set();
2554
+ var senderCache = /* @__PURE__ */ new Map();
2555
+ var testHooks3 = {};
2556
+ var warnOnce5 = createErrorOnceLogger(warnedKeys4);
2557
+ function registerShutdownHooks3(key, shutdown) {
2558
+ const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
2559
+ for (const event of handlers) {
2560
+ process.once(event, () => {
2561
+ void shutdown().catch((error) => {
2562
+ warnOnce5(
2563
+ `${key}:shutdown`,
2564
+ "[Blyp] Failed to flush Databuddy telemetry during shutdown.",
2565
+ error
2566
+ );
2567
+ });
2568
+ });
2569
+ }
2570
+ }
2571
+ function resolveConnectorConfig3(config) {
2572
+ const connector = isBlypConfig(config) ? config.connectors?.databuddy : config;
2573
+ const enabled = connector?.enabled ?? false;
2574
+ const apiKey = connector?.apiKey;
2575
+ const websiteId = connector?.websiteId;
2576
+ const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
2577
+ return {
2578
+ enabled,
2579
+ mode: connector?.mode ?? "auto",
2580
+ apiKey,
2581
+ websiteId,
2582
+ namespace: connector?.namespace,
2583
+ source: connector?.source,
2584
+ apiUrl: connector?.apiUrl,
2585
+ debug: connector?.debug ?? false,
2586
+ enableBatching: connector?.enableBatching ?? true,
2587
+ batchSize: connector?.batchSize,
2588
+ batchTimeout: connector?.batchTimeout,
2589
+ maxQueueSize: connector?.maxQueueSize,
2590
+ ready,
2591
+ status: ready ? "enabled" : "missing"
2592
+ };
2593
+ }
2594
+ function createDefaultClient2(connector) {
2595
+ return new Databuddy({
2596
+ apiKey: connector.apiKey ?? "",
2597
+ ...connector.websiteId ? { websiteId: connector.websiteId } : {},
2598
+ ...connector.namespace ? { namespace: connector.namespace } : {},
2599
+ ...connector.source ? { source: connector.source } : {},
2600
+ ...connector.apiUrl ? { apiUrl: connector.apiUrl } : {},
2601
+ debug: connector.debug,
2602
+ enableBatching: connector.enableBatching,
2603
+ ...connector.batchSize !== void 0 ? { batchSize: connector.batchSize } : {},
2604
+ ...connector.batchTimeout !== void 0 ? { batchTimeout: connector.batchTimeout } : {},
2605
+ ...connector.maxQueueSize !== void 0 ? { maxQueueSize: connector.maxQueueSize } : {}
2606
+ });
2607
+ }
2608
+ function getDatabuddySenderKey(connector) {
2609
+ return JSON.stringify({
2610
+ enabled: connector.enabled,
2611
+ mode: connector.mode,
2612
+ apiKey: connector.apiKey ?? null,
2613
+ websiteId: connector.websiteId ?? null,
2614
+ namespace: connector.namespace ?? null,
2615
+ source: connector.source ?? null,
2616
+ apiUrl: connector.apiUrl ?? null,
2617
+ debug: connector.debug,
2618
+ enableBatching: connector.enableBatching,
2619
+ batchSize: connector.batchSize ?? null,
2620
+ batchTimeout: connector.batchTimeout ?? null,
2621
+ maxQueueSize: connector.maxQueueSize ?? null
2622
+ });
2623
+ }
2624
+ function getSessionId(record) {
2625
+ const direct = getField(record, "sessionId");
2626
+ if (hasNonEmptyString(direct)) {
2627
+ return direct;
2628
+ }
2629
+ return getClientSessionField(record, "sessionId");
2630
+ }
2631
+ function getAnonymousId(record) {
2632
+ const direct = getField(record, "anonymousId");
2633
+ if (hasNonEmptyString(direct)) {
2634
+ return direct;
2635
+ }
2636
+ const payload = getPrimaryPayload(record);
2637
+ if (isPlainObject(payload.metadata) && hasNonEmptyString(payload.metadata.databuddyAnonymousId)) {
2638
+ return payload.metadata.databuddyAnonymousId;
2639
+ }
2640
+ return void 0;
2641
+ }
2642
+ function getDatabuddyEventName(record) {
2643
+ const recordType = getRecordType(record);
2644
+ if (hasNonEmptyString(recordType)) {
2645
+ return recordType;
2646
+ }
2647
+ return "log";
2648
+ }
2649
+ function buildRecordProperties(record, source) {
2650
+ const properties = {
2651
+ blyp_level: record.level,
2652
+ blyp_source: source,
2653
+ blyp_payload: serializeLogRecord(record),
2654
+ message: typeof record.message === "string" ? record.message : String(record.message)
2655
+ };
2656
+ const caller = typeof record.caller === "string" ? record.caller : void 0;
2657
+ const groupId = getField(record, "groupId");
2658
+ const method = getField(record, "method");
2659
+ const path3 = getField(record, "path");
2660
+ const status = getField(record, "status");
2661
+ const duration = getField(record, "duration");
2662
+ const pagePath = getClientPageField(record, "pathname");
2663
+ const pageUrl = getClientPageField(record, "url");
2664
+ const sessionId = getClientSessionField(record, "sessionId");
2665
+ const pageId = getClientSessionField(record, "pageId");
2666
+ const ifTruthy = [
2667
+ ["blyp_type", getRecordType(record)],
2668
+ ["caller", caller],
2669
+ ["group_id", groupId],
2670
+ ["method", method],
2671
+ ["path", path3],
2672
+ ["page_path", pagePath],
2673
+ ["page_url", pageUrl],
2674
+ ["session_id", sessionId],
2675
+ ["page_id", pageId]
2676
+ ];
2677
+ const ifDefined = [
2678
+ ["status_code", status],
2679
+ ["duration_ms", duration]
2680
+ ];
2681
+ for (const [key, value] of ifTruthy) {
2682
+ if (value) {
2683
+ properties[key] = value;
2684
+ }
2685
+ }
2686
+ for (const [key, value] of ifDefined) {
2687
+ if (value !== void 0) {
2688
+ properties[key] = value;
2689
+ }
2690
+ }
2691
+ return properties;
2692
+ }
2693
+ function createTrackEvent(record, source) {
2694
+ return {
2695
+ name: getDatabuddyEventName(record),
2696
+ anonymousId: getAnonymousId(record),
2697
+ sessionId: getSessionId(record),
2698
+ properties: buildRecordProperties(record, source)
2699
+ };
2700
+ }
2701
+ function normalizeExceptionProperties2(value) {
2702
+ if (!isPlainObject(value)) {
2703
+ return {};
2704
+ }
2705
+ return normalizeLogValue(value);
2706
+ }
2707
+ function normalizeExceptionInput3(value, fallbackMessage) {
2708
+ if (value instanceof Error) {
2709
+ return {
2710
+ message: value.message || fallbackMessage,
2711
+ properties: {
2712
+ error_type: value.name,
2713
+ ...value.stack ? { stack: value.stack } : {},
2714
+ ...normalizeExceptionProperties2(value)
2715
+ }
2716
+ };
2717
+ }
2718
+ if (isPlainObject(value)) {
2719
+ const message = hasNonEmptyString(value.message) ? value.message : hasNonEmptyString(value.error) ? value.error : fallbackMessage;
2720
+ return {
2721
+ message,
2722
+ properties: normalizeExceptionProperties2(value)
2723
+ };
2724
+ }
2725
+ if (typeof value === "string") {
2726
+ return {
2727
+ message: value,
2728
+ properties: {
2729
+ message: value
2730
+ }
2731
+ };
2732
+ }
2733
+ return {
2734
+ message: fallbackMessage,
2735
+ properties: {
2736
+ value: normalizeLogValue(value)
2737
+ }
2738
+ };
2739
+ }
2740
+ function createDatabuddySender(config) {
2741
+ const connector = resolveConnectorConfig3(config);
2742
+ const senderKey = getDatabuddySenderKey(connector);
2743
+ const cached = senderCache.get(senderKey);
2744
+ if (cached) {
2745
+ return cached;
2746
+ }
2747
+ const key = `${connector.apiUrl ?? "default"}:${connector.mode}:${connector.apiKey ?? "missing"}`;
2748
+ const client = connector.ready ? testHooks3.createClient?.(connector) ?? createDefaultClient2(connector) : void 0;
2749
+ if (client) {
2750
+ registerShutdownHooks3(key, async () => {
2751
+ await client.flush();
2752
+ });
2753
+ }
2754
+ const emitUnavailableWarning = () => {
2755
+ warnOnce5(
2756
+ `databuddy-unavailable:${key}`,
2757
+ "[Blyp] Databuddy connector is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy delivery."
2758
+ );
2759
+ };
2760
+ const emitExceptionUnavailableWarning = () => {
2761
+ warnOnce5(
2762
+ `databuddy-exception-unavailable:${key}`,
2763
+ "[Blyp] Databuddy error tracking is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy exception capture."
2764
+ );
2765
+ };
2766
+ const sender = {
2767
+ enabled: connector.enabled,
2768
+ ready: connector.ready,
2769
+ mode: connector.mode,
2770
+ status: connector.status,
2771
+ shouldAutoForwardServerLogs() {
2772
+ return connector.ready && connector.mode === "auto";
2773
+ },
2774
+ shouldAutoCaptureExceptions() {
2775
+ return connector.ready && connector.mode === "auto";
2776
+ },
2777
+ send(record, options = {}) {
2778
+ if (!connector.ready || !client) {
2779
+ if (options.warnIfUnavailable) {
2780
+ emitUnavailableWarning();
2781
+ }
2782
+ return;
2783
+ }
2784
+ try {
2785
+ const result = client.track(createTrackEvent(record, options.source ?? "server"));
2786
+ if (result && typeof result.catch === "function") {
2787
+ void result.catch((error) => {
2788
+ warnOnce5(
2789
+ `databuddy-send:${key}`,
2790
+ "[Blyp] Failed to deliver log to Databuddy.",
2791
+ error
2792
+ );
2793
+ });
2794
+ }
2795
+ } catch (error) {
2796
+ warnOnce5(
2797
+ `databuddy-send:${key}`,
2798
+ "[Blyp] Failed to deliver log to Databuddy.",
2799
+ error
2800
+ );
2801
+ }
2802
+ },
2803
+ captureException(error, options = {}) {
2804
+ if (!connector.ready || !client) {
2805
+ if (options.warnIfUnavailable) {
2806
+ emitExceptionUnavailableWarning();
2807
+ }
2808
+ return;
2809
+ }
2810
+ const normalized = normalizeExceptionInput3(
2811
+ error,
2812
+ options.source === "client" ? "Client error" : "Server error"
2813
+ );
2814
+ try {
2815
+ const result = client.track({
2816
+ name: "error",
2817
+ anonymousId: options.anonymousId,
2818
+ sessionId: options.sessionId,
2819
+ properties: {
2820
+ message: normalized.message,
2821
+ blyp_source: options.source ?? "server",
2822
+ blyp_level: "error",
2823
+ ...normalized.properties,
2824
+ ...options.properties ?? {}
2825
+ }
2826
+ });
2827
+ if (result && typeof result.catch === "function") {
2828
+ void result.catch((captureError) => {
2829
+ warnOnce5(
2830
+ `databuddy-capture:${key}`,
2831
+ "[Blyp] Failed to capture exception in Databuddy.",
2832
+ captureError
2833
+ );
2834
+ });
2835
+ }
2836
+ } catch (captureError) {
2837
+ warnOnce5(
2838
+ `databuddy-capture:${key}`,
2839
+ "[Blyp] Failed to capture exception in Databuddy.",
2840
+ captureError
2841
+ );
2842
+ }
2843
+ },
2844
+ async flush() {
2845
+ try {
2846
+ if (client) {
2847
+ await client.flush();
2848
+ }
2849
+ } catch (error) {
2850
+ warnOnce5(
2851
+ `databuddy-flush:${key}`,
2852
+ "[Blyp] Failed to flush Databuddy telemetry.",
2853
+ error
2854
+ );
2855
+ }
2856
+ }
2857
+ };
2858
+ senderCache.set(senderKey, sender);
2859
+ return sender;
2860
+ }
2861
+ var warnedKeys5 = /* @__PURE__ */ new Set();
2862
+ var testHooks4 = {};
2863
+ var warnOnce6 = createErrorOnceLogger(warnedKeys5);
2864
+ function getSentryModule2() {
2865
+ return testHooks4.module ?? Sentry;
2866
+ }
2867
+ function resolveConnectorConfig4(config) {
2868
+ const connector = isBlypConfig(config) ? config.connectors?.sentry : config;
2869
+ const enabled = connector?.enabled ?? false;
2870
+ const dsn = connector?.dsn;
2871
+ const ready = enabled && hasNonEmptyString(dsn);
2872
+ return {
2873
+ enabled,
2874
+ mode: connector?.mode ?? "auto",
2875
+ dsn,
2876
+ environment: connector?.environment,
2877
+ release: connector?.release,
2878
+ ready,
2879
+ status: ready ? "enabled" : "missing"
2880
+ };
2881
+ }
2882
+ function normalizeAttributes(record, source) {
2883
+ const attributes = {
2884
+ "blyp.level": record.level,
2885
+ "blyp.source": source,
2886
+ "blyp.payload": serializeLogRecord(record)
2887
+ };
2888
+ const recordType = getRecordType(record);
2889
+ const caller = typeof record.caller === "string" ? record.caller : void 0;
2890
+ const groupId = getField(record, "groupId");
2891
+ const method = getField(record, "method");
2892
+ const path3 = getField(record, "path");
2893
+ const status = getField(record, "status");
2894
+ const duration = getField(record, "duration");
2895
+ const pagePath = getClientPageField(record, "pathname");
2896
+ const pageUrl = getClientPageField(record, "url");
2897
+ const sessionId = getClientSessionField(record, "sessionId");
2898
+ const pageId = getClientSessionField(record, "pageId");
2899
+ const ifTruthy = [
2900
+ ["blyp.type", recordType],
2901
+ ["blyp.caller", caller],
2902
+ ["blyp.group_id", groupId],
2903
+ ["http.method", method],
2904
+ ["url.path", path3],
2905
+ ["client.page_path", pagePath],
2906
+ ["client.page_url", pageUrl],
2907
+ ["client.session_id", sessionId],
2908
+ ["client.page_id", pageId]
2909
+ ];
2910
+ const ifDefined = [
2911
+ ["http.status_code", status],
2912
+ ["blyp.duration_ms", duration]
2913
+ ];
2914
+ for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
2915
+ for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
2916
+ return attributes;
2917
+ }
2918
+ function resolveLogMethod(module, level) {
2919
+ switch (level) {
2920
+ case "debug":
2921
+ return module.logger.debug;
2922
+ case "warning":
2923
+ case "warn":
2924
+ return module.logger.warn;
2925
+ case "error":
2926
+ return module.logger.error;
2927
+ case "critical":
2928
+ return module.logger.fatal;
2929
+ case "success":
2930
+ case "table":
2931
+ case "info":
2932
+ default:
2933
+ return module.logger.info;
2934
+ }
2935
+ }
2936
+ function normalizeScopeLevel2(level) {
2937
+ switch (level) {
2938
+ case "debug":
2939
+ return "debug";
2940
+ case "warning":
2941
+ case "warn":
2942
+ return "warning";
2943
+ case "critical":
2944
+ return "fatal";
2945
+ case "error":
2946
+ return "error";
2947
+ case "success":
2948
+ case "table":
2949
+ case "info":
2950
+ default:
2951
+ return "info";
2952
+ }
2953
+ }
2954
+ function toExceptionCandidate2(value) {
2955
+ if (!isPlainObject(value)) {
2956
+ return void 0;
2957
+ }
2958
+ const message = typeof value.message === "string" ? value.message : void 0;
2959
+ const name = typeof value.name === "string" ? value.name : void 0;
2960
+ const stack = typeof value.stack === "string" ? value.stack : void 0;
2961
+ if (!message && !name && !stack) {
2962
+ return void 0;
2963
+ }
2964
+ const error = new Error(message ?? name ?? "Unknown error");
2965
+ error.name = name ?? "Error";
2966
+ if (stack) {
2967
+ error.stack = stack;
2968
+ }
2969
+ for (const [key, entry] of Object.entries(value)) {
2970
+ if (key === "message" || key === "name" || key === "stack") {
2971
+ continue;
2972
+ }
2973
+ error[key] = entry;
2974
+ }
2975
+ return error;
2976
+ }
2977
+ function extractExceptionCandidate(record) {
2978
+ if (record.level !== "error" && record.level !== "critical") {
2979
+ return void 0;
2980
+ }
2981
+ const direct = toExceptionCandidate2(record.error);
2982
+ if (direct) {
2983
+ return direct;
2984
+ }
2985
+ if (isPlainObject(record.data)) {
2986
+ const directData = toExceptionCandidate2(record.data);
2987
+ if (directData) {
2988
+ return directData;
2989
+ }
2990
+ const nested = toExceptionCandidate2(record.data.error);
2991
+ if (nested) {
2992
+ return nested;
2993
+ }
2994
+ }
2995
+ const payload = getPrimaryPayload(record);
2996
+ if (isPlainObject(payload)) {
2997
+ const nested = toExceptionCandidate2(payload.error);
2998
+ if (nested) {
2999
+ return nested;
3000
+ }
3001
+ }
3002
+ return void 0;
3003
+ }
3004
+ function getClientOptions2(client) {
3005
+ return client?.getOptions?.() ?? {};
3006
+ }
3007
+ function hasConfigMismatch(connector, client) {
3008
+ const options = getClientOptions2(client);
3009
+ return hasNonEmptyString(connector.dsn) && connector.dsn !== options.dsn || hasNonEmptyString(connector.environment) && connector.environment !== options.environment || hasNonEmptyString(connector.release) && connector.release !== options.release;
3010
+ }
3011
+ function createSentrySender(config) {
3012
+ const connector = resolveConnectorConfig4(config);
3013
+ const key = `${connector.mode}:${connector.dsn ?? "missing"}`;
3014
+ const module = getSentryModule2();
3015
+ let client = connector.enabled ? module.getClient() : void 0;
3016
+ if (!client && connector.enabled && hasNonEmptyString(connector.dsn)) {
3017
+ try {
3018
+ module.init({
3019
+ dsn: connector.dsn,
3020
+ environment: connector.environment,
3021
+ release: connector.release,
3022
+ enableLogs: true
3023
+ });
3024
+ client = module.getClient();
3025
+ } catch (error) {
3026
+ warnOnce6(
3027
+ `sentry-init:${key}`,
3028
+ "[Blyp] Failed to initialize Sentry. Skipping Sentry delivery.",
3029
+ error
3030
+ );
3031
+ }
3032
+ }
3033
+ if (client && hasConfigMismatch(connector, client)) {
3034
+ warnOnce6(
3035
+ `sentry-mismatch:${key}`,
3036
+ "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client."
3037
+ );
3038
+ }
3039
+ const ready = connector.enabled && client !== void 0;
3040
+ const emitUnavailableWarning = () => {
3041
+ warnOnce6(
3042
+ `sentry-unavailable:${key}`,
3043
+ "[Blyp] Sentry connector is not configured. Skipping Sentry delivery."
3044
+ );
3045
+ };
3046
+ return {
3047
+ enabled: connector.enabled,
3048
+ ready,
3049
+ mode: connector.mode,
3050
+ status: ready ? "enabled" : "missing",
3051
+ shouldAutoForwardServerLogs() {
3052
+ return ready && connector.mode === "auto";
3053
+ },
3054
+ send(record, options = {}) {
3055
+ if (!ready) {
3056
+ if (options.warnIfUnavailable) {
3057
+ emitUnavailableWarning();
3058
+ }
3059
+ return;
3060
+ }
3061
+ const source = options.source ?? "server";
3062
+ const attributes = normalizeAttributes(record, source);
3063
+ const logMethod = resolveLogMethod(module, record.level);
3064
+ try {
3065
+ logMethod(record.message, attributes);
3066
+ } catch (error) {
3067
+ warnOnce6(
3068
+ `sentry-log:${key}`,
3069
+ "[Blyp] Failed to deliver log to Sentry.",
3070
+ error
3071
+ );
3072
+ }
3073
+ const exception = extractExceptionCandidate(record);
3074
+ if (!exception) {
3075
+ return;
3076
+ }
3077
+ try {
3078
+ module.withScope((scope) => {
3079
+ scope.setLevel(normalizeScopeLevel2(record.level));
3080
+ scope.setContext("blyp", attributes);
3081
+ scope.setExtra("blyp.payload", serializeLogRecord(record));
3082
+ module.captureException(exception);
3083
+ });
3084
+ } catch (error) {
3085
+ warnOnce6(
3086
+ `sentry-exception:${key}`,
3087
+ "[Blyp] Failed to capture exception in Sentry.",
3088
+ error
3089
+ );
3090
+ }
3091
+ },
3092
+ async flush() {
3093
+ try {
3094
+ await module.flush(2e3);
3095
+ } catch (error) {
3096
+ warnOnce6(
3097
+ `sentry-flush:${key}`,
3098
+ "[Blyp] Failed to flush Sentry logs.",
3099
+ error
3100
+ );
3101
+ }
3102
+ }
3103
+ };
3104
+ }
3105
+ var warnedKeys6 = /* @__PURE__ */ new Set();
3106
+ var testHooks5 = {};
3107
+ var warnOnce7 = createErrorOnceLogger(warnedKeys6);
3108
+ function normalizeOTLPRecord(record, connector, source = "server") {
3109
+ const severity = resolveSeverity2(record.level);
3110
+ const body = typeof record.message === "string" ? record.message : String(record.message);
3111
+ const recordType = getRecordType(record);
3112
+ const caller = typeof record.caller === "string" ? record.caller : void 0;
3113
+ const groupId = getField(record, "groupId");
3114
+ const method = getField(record, "method");
3115
+ const path3 = getField(record, "path");
3116
+ const status = getField(record, "status");
3117
+ const duration = getField(record, "duration");
3118
+ const pagePath = getClientPageField(record, "pathname");
3119
+ const pageUrl = getClientPageField(record, "url");
3120
+ const sessionId = getClientSessionField(record, "sessionId");
3121
+ const pageId = getClientSessionField(record, "pageId");
3122
+ const attributes = {
3123
+ "blyp.level": record.level,
3124
+ "blyp.source": source,
3125
+ "blyp.payload": serializeLogRecord(record)
3126
+ };
3127
+ const ifTruthy = [
3128
+ ["blyp.type", recordType],
3129
+ ["blyp.caller", caller],
3130
+ ["blyp.group_id", groupId],
3131
+ ["http.method", method],
3132
+ ["url.path", path3],
3133
+ ["client.page_path", pagePath],
3134
+ ["client.page_url", pageUrl],
3135
+ ["client.session_id", sessionId],
3136
+ ["client.page_id", pageId]
3137
+ ];
3138
+ const ifDefined = [
3139
+ ["http.status_code", status],
3140
+ ["blyp.duration_ms", duration]
3141
+ ];
3142
+ for (const [k, v] of ifTruthy) if (v) attributes[k] = v;
3143
+ for (const [k, v] of ifDefined) if (v !== void 0) attributes[k] = v;
3144
+ return {
3145
+ body,
3146
+ severityText: severity.text,
3147
+ severityNumber: severity.number,
3148
+ attributes,
3149
+ resourceAttributes: {
3150
+ "service.name": connector.serviceName
3151
+ }
3152
+ };
3153
+ }
3154
+ function resolveSeverity2(level) {
3155
+ switch (level) {
3156
+ case "debug":
3157
+ return { text: "debug", number: SeverityNumber.DEBUG };
3158
+ case "warning":
3159
+ case "warn":
3160
+ return { text: "warn", number: SeverityNumber.WARN };
3161
+ case "error":
3162
+ return { text: "error", number: SeverityNumber.ERROR };
3163
+ case "critical":
3164
+ return { text: "fatal", number: SeverityNumber.FATAL };
3165
+ case "success":
3166
+ case "table":
3167
+ case "info":
3168
+ default:
3169
+ return { text: "info", number: SeverityNumber.INFO };
3170
+ }
3171
+ }
3172
+ function registerShutdownHooks4(key, shutdown) {
3173
+ const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
3174
+ for (const event of handlers) {
3175
+ process.once(event, async () => {
3176
+ try {
3177
+ await shutdown();
3178
+ } catch (error) {
3179
+ warnOnce7(
3180
+ `${key}:shutdown`,
3181
+ "[Blyp] Failed to flush OTLP logs during shutdown.",
3182
+ error
3183
+ );
3184
+ }
3185
+ if (event !== "beforeExit") {
3186
+ process.exit(0);
3187
+ }
3188
+ });
3189
+ }
3190
+ }
3191
+ function resolveTransportHeaders(connector) {
3192
+ const headers = {
3193
+ ...connector.headers ?? {}
3194
+ };
3195
+ if (headers.Authorization === void 0 && connector.auth) {
3196
+ headers.Authorization = connector.auth;
3197
+ }
3198
+ return headers;
3199
+ }
3200
+ function createDefaultTransport2(connector) {
3201
+ const exporter = new OTLPLogExporter({
3202
+ url: connector.endpoint,
3203
+ headers: resolveTransportHeaders(connector)
3204
+ });
3205
+ const provider = new LoggerProvider({
3206
+ resource: resourceFromAttributes({
3207
+ "service.name": connector.serviceName
3208
+ }),
3209
+ processors: [new BatchLogRecordProcessor(exporter)]
3210
+ });
3211
+ const logger2 = provider.getLogger(`blyp-otlp:${connector.name}`);
3212
+ return {
3213
+ emit(payload) {
3214
+ logger2.emit({
3215
+ body: payload.body,
3216
+ severityText: payload.severityText,
3217
+ severityNumber: payload.severityNumber,
3218
+ attributes: payload.attributes
3219
+ });
3220
+ },
3221
+ flush() {
3222
+ return provider.forceFlush();
3223
+ },
3224
+ shutdown() {
3225
+ return provider.shutdown();
3226
+ }
3227
+ };
3228
+ }
3229
+ function resolveConnectors(config) {
3230
+ const connectors = isBlypConfig(config) ? config.connectors?.otlp ?? [] : config;
3231
+ return connectors.map((connector) => {
3232
+ const headers = {
3233
+ ...connector.headers ?? {}
3234
+ };
3235
+ const enabled = connector.enabled ?? false;
3236
+ const endpoint = connector.endpoint;
3237
+ const explicitReady = "ready" in connector && typeof connector.ready === "boolean" ? connector.ready : void 0;
3238
+ const ready = (explicitReady ?? (enabled && isAbsoluteHttpUrl(endpoint))) && isAbsoluteHttpUrl(endpoint);
3239
+ return {
3240
+ name: connector.name,
3241
+ enabled,
3242
+ mode: connector.mode ?? "auto",
3243
+ endpoint,
3244
+ headers,
3245
+ auth: connector.auth,
3246
+ serviceName: connector.serviceName ?? "blyp-app",
3247
+ ready,
3248
+ status: ready ? "enabled" : "missing"
3249
+ };
3250
+ });
3251
+ }
3252
+ function createUnavailableSender(name, connector) {
3253
+ const senderName = name || connector?.name || "otlp";
3254
+ const key = `${senderName}:${connector?.serviceName ?? "blyp-app"}:${connector?.endpoint ?? "missing"}`;
3255
+ const emitUnavailableWarning = () => {
3256
+ warnOnce7(
3257
+ `otlp-unavailable:${key}`,
3258
+ `[Blyp] OTLP target "${senderName}" is not configured or not ready. Skipping OTLP delivery.`
3259
+ );
3260
+ };
3261
+ return {
3262
+ name: senderName,
3263
+ enabled: connector?.enabled ?? false,
3264
+ ready: false,
3265
+ mode: connector?.mode ?? "auto",
3266
+ serviceName: connector?.serviceName ?? "blyp-app",
3267
+ endpoint: connector?.endpoint,
3268
+ status: "missing",
3269
+ send(_record, options = {}) {
3270
+ if (options.warnIfUnavailable) {
3271
+ emitUnavailableWarning();
3272
+ }
3273
+ },
3274
+ async flush() {
3275
+ }
3276
+ };
3277
+ }
3278
+ function createSender(connector) {
3279
+ if (!connector.ready || !connector.endpoint) {
3280
+ return createUnavailableSender(connector.name, connector);
3281
+ }
3282
+ const key = `${connector.name}:${connector.serviceName}:${connector.endpoint}:${connector.mode}`;
3283
+ const transportConnector = {
3284
+ ...connector,
3285
+ headers: resolveTransportHeaders(connector)
3286
+ };
3287
+ const transport = testHooks5.createTransport?.(transportConnector) ?? createDefaultTransport2(transportConnector);
3288
+ return {
3289
+ name: connector.name,
3290
+ enabled: connector.enabled,
3291
+ ready: connector.ready,
3292
+ mode: connector.mode,
3293
+ serviceName: connector.serviceName,
3294
+ endpoint: connector.endpoint,
3295
+ status: connector.status,
3296
+ send(record, options = {}) {
3297
+ const source = options.source ?? "server";
3298
+ const normalized = normalizeOTLPRecord(record, connector, source);
3299
+ try {
3300
+ const result = transport.emit(normalized);
3301
+ if (result && typeof result.catch === "function") {
3302
+ void result.catch((error) => {
3303
+ warnOnce7(
3304
+ `otlp-emit:${key}`,
3305
+ `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
3306
+ error
3307
+ );
3308
+ });
3309
+ }
3310
+ } catch (error) {
3311
+ warnOnce7(
3312
+ `otlp-emit:${key}`,
3313
+ `[Blyp] Failed to deliver log to OTLP target "${connector.name}".`,
3314
+ error
3315
+ );
3316
+ }
3317
+ },
3318
+ async flush() {
3319
+ try {
3320
+ if (transport.flush) {
3321
+ await transport.flush();
3322
+ }
3323
+ } catch (error) {
3324
+ warnOnce7(
3325
+ `otlp-flush:${key}`,
3326
+ `[Blyp] Failed to flush OTLP logs for target "${connector.name}".`,
3327
+ error
3328
+ );
3329
+ }
3330
+ }
3331
+ };
3332
+ }
3333
+ function createOTLPRegistry(config) {
3334
+ const senders = /* @__PURE__ */ new Map();
3335
+ for (const connector of resolveConnectors(config)) {
3336
+ senders.set(connector.name, createSender(connector));
3337
+ }
3338
+ const registry = {
3339
+ get(name) {
3340
+ return senders.get(name) ?? createUnavailableSender(name);
3341
+ },
3342
+ getAutoForwardTargets() {
3343
+ return Array.from(senders.values()).filter((sender) => sender.ready && sender.mode === "auto");
3344
+ },
3345
+ send(name, record, options = {}) {
3346
+ const sender = senders.get(name) ?? createUnavailableSender(name);
3347
+ sender.send(record, options);
3348
+ },
3349
+ async flush() {
3350
+ await Promise.all(Array.from(senders.values()).map((sender) => sender.flush()));
3351
+ }
3352
+ };
3353
+ registerShutdownHooks4("otlp-registry", () => registry.flush());
3354
+ return registry;
3355
+ }
3356
+ var _RuntimeDetector = class _RuntimeDetector {
3357
+ constructor() {
3358
+ __publicField(this, "_type", null);
3359
+ }
3360
+ static getInstance() {
3361
+ if (!_RuntimeDetector.instance) {
3362
+ _RuntimeDetector.instance = new _RuntimeDetector();
3363
+ }
3364
+ return _RuntimeDetector.instance;
3365
+ }
3366
+ get type() {
3367
+ if (this._type === null) {
3368
+ this._type = this.detectRuntime();
3369
+ }
3370
+ return this._type;
3371
+ }
3372
+ get isBun() {
3373
+ return this.type === "bun";
3374
+ }
3375
+ get isNode() {
3376
+ return this.type === "node";
3377
+ }
3378
+ detectRuntime() {
3379
+ if (typeof Bun !== "undefined" && typeof Bun.file === "function") {
3380
+ return "bun";
3381
+ }
3382
+ return "node";
3383
+ }
3384
+ };
3385
+ __publicField(_RuntimeDetector, "instance");
3386
+ var RuntimeDetector = _RuntimeDetector;
3387
+ var BunAdapter = class {
3388
+ constructor() {
3389
+ __publicField(this, "type", "bun");
3390
+ __publicField(this, "isBun", true);
3391
+ __publicField(this, "isNode", false);
3392
+ __publicField(this, "file", {
3393
+ existsSync: (filePath) => {
3394
+ try {
3395
+ const file = Bun.file(filePath);
3396
+ return file.size > 0 || file.name !== "";
3397
+ } catch {
3398
+ return false;
3399
+ }
3400
+ },
3401
+ mkdirSync: (filePath, options) => {
3402
+ try {
3403
+ fs.mkdirSync(filePath, options);
3404
+ } catch {
3405
+ }
3406
+ },
3407
+ writeFileSync: (filePath, data) => {
3408
+ Bun.write(filePath, data);
3409
+ }
3410
+ });
3411
+ __publicField(this, "path", {
3412
+ join: (...paths) => {
3413
+ return path.join(...paths);
3414
+ }
3415
+ });
3416
+ __publicField(this, "env", {
3417
+ get: (key) => Bun.env[key]
3418
+ });
3419
+ __publicField(this, "cwd", () => {
3420
+ return process.cwd();
3421
+ });
3422
+ }
3423
+ };
3424
+ var NodeAdapter = class {
3425
+ constructor() {
3426
+ __publicField(this, "type", "node");
3427
+ __publicField(this, "isBun", false);
3428
+ __publicField(this, "isNode", true);
3429
+ __publicField(this, "file", {
3430
+ existsSync: (filePath) => fs.existsSync(filePath),
3431
+ mkdirSync: (filePath, options) => {
3432
+ fs.mkdirSync(filePath, options);
3433
+ },
3434
+ writeFileSync: (filePath, data) => {
3435
+ fs.writeFileSync(filePath, data);
3436
+ }
3437
+ });
3438
+ __publicField(this, "path", {
3439
+ join: (...paths) => path.join(...paths)
3440
+ });
3441
+ __publicField(this, "env", {
3442
+ get: (key) => process.env[key]
3443
+ });
3444
+ __publicField(this, "cwd", () => process.cwd());
3445
+ }
3446
+ };
3447
+ function createRuntimeAdapter() {
3448
+ const detector = RuntimeDetector.getInstance();
3449
+ if (detector.isBun) {
3450
+ return new BunAdapter();
3451
+ }
3452
+ return new NodeAdapter();
3453
+ }
3454
+ var runtime = createRuntimeAdapter();
3455
+
3456
+ // src/core/structured-log.ts
3457
+ function serializeMessage2(message) {
3458
+ if (typeof message === "string") {
3459
+ return message;
3460
+ }
3461
+ if (message !== null && typeof message === "object") {
3462
+ try {
3463
+ return JSON.stringify(
3464
+ message,
3465
+ (_key, value) => {
3466
+ if (typeof value === "function") {
3467
+ return `[Function: ${value.name || "anonymous"}]`;
3468
+ }
3469
+ if (value === void 0) {
3470
+ return "[undefined]";
3471
+ }
3472
+ if (typeof value === "symbol") {
3473
+ return value.toString();
3474
+ }
3475
+ return value;
3476
+ },
3477
+ 2
3478
+ );
3479
+ } catch {
3480
+ return "[Object]";
3481
+ }
3482
+ }
3483
+ return String(message);
3484
+ }
3485
+ function normalizeEventData(message, args) {
3486
+ if (typeof message === "string") {
3487
+ if (args.length === 0) {
3488
+ return void 0;
3489
+ }
3490
+ return args.length === 1 ? args[0] : args;
3491
+ }
3492
+ const values = [message, ...args];
3493
+ return values.length === 1 ? values[0] : values;
3494
+ }
3495
+ function normalizeDetails(value) {
3496
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
3497
+ return void 0;
3498
+ }
3499
+ return value;
3500
+ }
3501
+ function normalizeError2(error, fallbackStatus) {
3502
+ if (error === void 0 || error === null) {
3503
+ return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
3504
+ message: `HTTP ${fallbackStatus}`,
3505
+ code: fallbackStatus,
3506
+ type: "HttpError"
3507
+ };
3508
+ }
3509
+ if (error instanceof Error) {
3510
+ const errorLike = error;
3511
+ return {
3512
+ message: error.message,
3513
+ code: errorLike.code,
3514
+ type: errorLike.type ?? error.name ?? error.constructor?.name,
3515
+ stack: error.stack,
3516
+ why: errorLike.why,
3517
+ fix: errorLike.fix,
3518
+ link: errorLike.link,
3519
+ details: normalizeDetails(errorLike.details),
3520
+ cause: errorLike.cause
3521
+ };
3522
+ }
3523
+ if (typeof error === "object") {
3524
+ const record = error;
3525
+ const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
3526
+ return {
3527
+ message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
3528
+ code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
3529
+ type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
3530
+ stack: typeof record.stack === "string" ? record.stack : void 0,
3531
+ why: typeof record.why === "string" ? record.why : void 0,
3532
+ fix: typeof record.fix === "string" ? record.fix : void 0,
3533
+ link: typeof record.link === "string" ? record.link : void 0,
3534
+ details: normalizeDetails(record.details),
3535
+ cause: record.cause
3536
+ };
3537
+ }
3538
+ return {
3539
+ message: String(error),
3540
+ code: fallbackStatus,
3541
+ type: typeof error
3542
+ };
3543
+ }
3544
+ function resolveEmitStatus(options) {
3545
+ if (options.response && typeof options.response.status === "number") {
3546
+ return options.response.status;
3547
+ }
3548
+ if (typeof options.status === "number") {
3549
+ return options.status;
3550
+ }
3551
+ if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
3552
+ return options.error.statusCode;
3553
+ }
3554
+ if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
3555
+ return options.error.status;
3556
+ }
3557
+ return options.error ? 500 : void 0;
3558
+ }
3559
+ function createStructuredLog(groupId, options) {
3560
+ const startedAt = performance.now();
3561
+ const fields = { ...options.initialFields ?? {} };
3562
+ const events = [];
3563
+ let emittedPayload;
3564
+ options.onCreate?.();
3565
+ const appendEvent = (level, message, args) => {
3566
+ events.push({
3567
+ level,
3568
+ message: serializeMessage2(message),
3569
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3570
+ ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
3571
+ });
3572
+ return structuredLog;
3573
+ };
3574
+ const structuredLog = {
3575
+ set(extraFields) {
3576
+ Object.assign(fields, extraFields);
3577
+ return structuredLog;
3578
+ },
3579
+ debug(message, ...args) {
3580
+ return appendEvent("debug", message, args);
3581
+ },
3582
+ info(message, ...args) {
3583
+ return appendEvent("info", message, args);
3584
+ },
3585
+ warn(message, ...args) {
3586
+ return appendEvent("warn", message, args);
3587
+ },
3588
+ warning(message, ...args) {
3589
+ return appendEvent("warning", message, args);
3590
+ },
3591
+ error(message, ...args) {
3592
+ return appendEvent("error", message, args);
3593
+ },
3594
+ success(message, ...args) {
3595
+ return appendEvent("success", message, args);
3596
+ },
3597
+ critical(message, ...args) {
3598
+ return appendEvent("critical", message, args);
3599
+ },
3600
+ table(message, data) {
3601
+ return appendEvent("table", message, data === void 0 ? [] : [data]);
3602
+ },
3603
+ emit(emitOptions = {}) {
3604
+ if (emittedPayload) {
3605
+ return emittedPayload;
3606
+ }
3607
+ const defaultFields = options.resolveDefaultFields?.() ?? {};
3608
+ const status = resolveEmitStatus(emitOptions);
3609
+ const error = normalizeError2(emitOptions.error, status);
3610
+ const level = emitOptions.level ?? (error ? "error" : "info");
3611
+ const payload = {
3612
+ ...defaultFields,
3613
+ ...fields,
3614
+ groupId,
3615
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3616
+ level,
3617
+ duration: Math.round(performance.now() - startedAt),
3618
+ ...typeof status === "number" ? { status } : {},
3619
+ ...events.length > 0 ? { events: [...events] } : {},
3620
+ ...error ? { error } : {}
3621
+ };
3622
+ options.write(payload, emitOptions.message ?? "structured_log");
3623
+ emittedPayload = payload;
3624
+ options.onEmit?.(payload);
3625
+ return payload;
3626
+ }
3627
+ };
3628
+ return structuredLog;
3629
+ }
3630
+
3631
+ // src/core/logger.ts
3632
+ var LOGGER_FACTORY = /* @__PURE__ */ Symbol("blyp.logger.factory");
3633
+ var CUSTOM_LEVELS = {
3634
+ success: 25,
3635
+ info: 30,
3636
+ debug: 35,
3637
+ table: 37,
3638
+ warning: 40,
3639
+ error: 50,
3640
+ critical: 60
3641
+ };
3642
+ var CONSOLE_LEVELS = {
3643
+ success: "success",
3644
+ critical: "critical",
3645
+ warning: "warning",
3646
+ info: "info",
3647
+ debug: "debug",
3648
+ error: "error",
3649
+ warn: "warn",
3650
+ table: "debug"
3651
+ };
3652
+ var MAGENTA = "\x1B[35m";
3653
+ var RESET = "\x1B[0m";
3654
+ function summarizeClientConsoleData(data) {
3655
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
3656
+ return null;
3657
+ }
3658
+ const record = data;
3659
+ const summary = {};
3660
+ if (record.data !== void 0) {
3661
+ summary.data = record.data;
3662
+ }
3663
+ const pathname = typeof record.page?.pathname === "string" ? record.page.pathname : void 0;
3664
+ const url = typeof record.page?.url === "string" ? record.page.url : void 0;
3665
+ if (pathname || url) {
3666
+ summary.page = pathname ?? url;
3667
+ }
3668
+ if (record.metadata !== void 0) {
3669
+ summary.metadata = record.metadata;
3670
+ }
3671
+ return Object.keys(summary).length > 0 ? summary : null;
3672
+ }
3673
+ function getConsoleDataPayload(data) {
3674
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
3675
+ return { hidden: false, value: data };
3676
+ }
3677
+ const record = data;
3678
+ if (record.type === "http_request" || record.type === "http_error") {
3679
+ return { hidden: true };
3680
+ }
3681
+ if (record.type === "client_log") {
3682
+ const summary = summarizeClientConsoleData(data);
3683
+ if (!summary) {
3684
+ return { hidden: true };
3685
+ }
3686
+ return {
3687
+ hidden: false,
3688
+ value: summary
3689
+ };
3690
+ }
3691
+ return { hidden: false, value: data };
3692
+ }
3693
+ function createPinoLogger(config) {
3694
+ if (config.pretty) {
3695
+ const pinoPretty = __require("pino-pretty");
3696
+ const pretty = pinoPretty.default({
3697
+ colorize: true,
3698
+ translateTime: "SYS:HH:MM:ss",
3699
+ ignore: "pid,hostname,caller",
3700
+ customColors: {
3701
+ success: "green",
3702
+ critical: "red bold",
3703
+ info: "blue",
3704
+ warning: "yellow",
3705
+ error: "red",
3706
+ debug: "cyan",
3707
+ table: "cyan"
3708
+ },
3709
+ messageFormat: (log, messageKey) => {
3710
+ const message = String(log[messageKey] ?? "");
3711
+ const caller = typeof log.caller === "string" ? log.caller.trim() : "";
3712
+ if (!caller) {
3713
+ return message;
3714
+ }
3715
+ return `${message} ${MAGENTA}${caller}${RESET}`;
3716
+ }
3717
+ });
3718
+ return pino(
3719
+ {
3720
+ level: config.level,
3721
+ customLevels: CUSTOM_LEVELS
3722
+ },
3723
+ pretty
3724
+ );
3725
+ }
3726
+ return pino({
3727
+ level: config.level,
3728
+ customLevels: CUSTOM_LEVELS
3729
+ });
3730
+ }
3731
+ function getLoggerFactory(logger2) {
3732
+ const factory = logger2[LOGGER_FACTORY];
3733
+ if (!factory) {
3734
+ throw new Error("Unsupported Blyp logger instance");
3735
+ }
3736
+ return factory;
3737
+ }
3738
+ function getPostHogSender(logger2) {
3739
+ return getLoggerFactory(logger2).posthog;
3740
+ }
3741
+ function getBetterStackSender(logger2) {
3742
+ return getLoggerFactory(logger2).betterstack;
3743
+ }
3744
+ function getDatabuddySender(logger2) {
3745
+ return getLoggerFactory(logger2).databuddy;
3746
+ }
3747
+ function tryGetPostHogSender(logger2) {
3748
+ try {
3749
+ return getPostHogSender(logger2);
3750
+ } catch {
3751
+ return null;
3752
+ }
3753
+ }
3754
+ function tryGetBetterStackSender(logger2) {
3755
+ try {
3756
+ return getBetterStackSender(logger2);
3757
+ } catch {
3758
+ return null;
3759
+ }
3760
+ }
3761
+ function tryGetDatabuddySender(logger2) {
3762
+ try {
3763
+ return getDatabuddySender(logger2);
3764
+ } catch {
3765
+ return null;
3766
+ }
3767
+ }
3768
+ function getSentrySender(logger2) {
3769
+ return getLoggerFactory(logger2).sentry;
3770
+ }
3771
+ function getOtlpRegistry(logger2) {
3772
+ return getLoggerFactory(logger2).otlp;
3773
+ }
3774
+ function attachLoggerInternals(target, source) {
3775
+ const factory = getLoggerFactory(source);
3776
+ Object.defineProperty(target, LOGGER_FACTORY, {
3777
+ value: factory,
3778
+ enumerable: false,
3779
+ configurable: false,
3780
+ writable: false
3781
+ });
3782
+ return target;
3783
+ }
3784
+ function createLoggerWithSource(logger2, source) {
3785
+ const factory = getLoggerFactory(logger2);
3786
+ return factory.create(source, factory.bindings);
3787
+ }
3788
+ function createStructuredLogForLogger(logger2, groupId, options = {}) {
3789
+ const factory = getLoggerFactory(logger2);
3790
+ return createStructuredLog(groupId, {
3791
+ initialFields: options.initialFields,
3792
+ resolveDefaultFields: () => ({
3793
+ ...factory.bindings,
3794
+ ...options.resolveDefaultFields?.() ?? {}
3795
+ }),
3796
+ write: (payload, message) => {
3797
+ factory.writeStructured(payload, message, "structured-flush");
3798
+ },
3799
+ onCreate: options.onCreate,
3800
+ onEmit: options.onEmit
3801
+ });
3802
+ }
3803
+ function maybeSendToPostHog(posthog, record) {
3804
+ if (isClientLogRecord(record)) {
3805
+ return;
3806
+ }
3807
+ if (!posthog.shouldAutoForwardServerLogs()) {
3808
+ if (posthog.enabled && !posthog.ready) {
3809
+ posthog.send(record, { source: "server", warnIfUnavailable: true });
3810
+ }
3811
+ return;
3812
+ }
3813
+ posthog.send(record, { source: "server", warnIfUnavailable: true });
3814
+ }
3815
+ function maybeSendToBetterStack(betterstack, record) {
3816
+ if (isClientLogRecord(record)) {
3817
+ return;
3818
+ }
3819
+ if (!betterstack.shouldAutoForwardServerLogs()) {
3820
+ if (betterstack.enabled && !betterstack.ready) {
3821
+ betterstack.send(record, { source: "server", warnIfUnavailable: true });
3822
+ }
3823
+ return;
3824
+ }
3825
+ betterstack.send(record, { source: "server", warnIfUnavailable: true });
3826
+ }
3827
+ function maybeSendToDatabuddy(databuddy, record) {
3828
+ if (isClientLogRecord(record)) {
3829
+ return;
3830
+ }
3831
+ if (!databuddy.shouldAutoForwardServerLogs()) {
3832
+ if (databuddy.enabled && !databuddy.ready) {
3833
+ databuddy.send(record, { source: "server", warnIfUnavailable: true });
3834
+ }
3835
+ return;
3836
+ }
3837
+ databuddy.send(record, { source: "server", warnIfUnavailable: true });
3838
+ }
3839
+ function maybeSendToSentry(sentry, record) {
3840
+ if (isClientLogRecord(record)) {
3841
+ return;
3842
+ }
3843
+ if (!sentry.shouldAutoForwardServerLogs()) {
3844
+ if (sentry.enabled && !sentry.ready) {
3845
+ sentry.send(record, { source: "server", warnIfUnavailable: true });
3846
+ }
3847
+ return;
3848
+ }
3849
+ sentry.send(record, { source: "server", warnIfUnavailable: true });
3850
+ }
3851
+ function maybeSendToOTLP(otlp, record) {
3852
+ if (isClientLogRecord(record)) {
3853
+ return;
3854
+ }
3855
+ for (const sender of otlp.getAutoForwardTargets()) {
3856
+ sender.send(record, { source: "server", warnIfUnavailable: true });
3857
+ }
3858
+ }
3859
+ function createLoggerInstance(rootRawLogger, sink, betterstack, databuddy, posthog, sentry, otlp, bindings = {}, source = "root") {
3860
+ const rawLogger = Object.keys(bindings).length > 0 ? rootRawLogger.child(bindings) : rootRawLogger;
3861
+ const writeRecord = (level, message, args, writeSource = source) => {
3862
+ if (writeSource === "root" && shouldDropRootLogWrite()) {
3863
+ return;
3864
+ }
3865
+ const record = buildRecord(level, message, args, bindings);
3866
+ const consoleMessage = serializeMessage(message);
3867
+ const payload = {
3868
+ caller: record.caller
3869
+ };
3870
+ const consoleData = getConsoleDataPayload(record.data);
3871
+ if (!consoleData.hidden && consoleData.value !== void 0) {
3872
+ payload.data = consoleData.value;
3873
+ }
3874
+ const consoleMethod = CONSOLE_LEVELS[level];
3875
+ const boundLogger = rawLogger;
3876
+ const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3877
+ });
3878
+ logMethod.call(
3879
+ rawLogger,
3880
+ payload,
3881
+ consoleMessage
3882
+ );
3883
+ sink.write(record);
3884
+ maybeSendToBetterStack(betterstack, record);
3885
+ maybeSendToDatabuddy(databuddy, record);
3886
+ maybeSendToPostHog(posthog, record);
3887
+ maybeSendToSentry(sentry, record);
3888
+ maybeSendToOTLP(otlp, record);
3889
+ };
3890
+ const writeStructuredRecord = (payload, message, writeSource = "structured-flush") => {
3891
+ const level = resolveStructuredWriteLevel(payload.level);
3892
+ const record = buildStructuredRecord(level, message, payload, bindings);
3893
+ const consoleMethod = CONSOLE_LEVELS[level];
3894
+ const boundLogger = rawLogger;
3895
+ const logMethod = boundLogger[consoleMethod] ?? boundLogger.info ?? ((_payload, _message) => {
3896
+ });
3897
+ logMethod.call(
3898
+ rawLogger,
3899
+ {
3900
+ caller: record.caller,
3901
+ ...payload
3902
+ },
3903
+ message
3904
+ );
3905
+ if (writeSource !== "root" || !shouldDropRootLogWrite()) {
3906
+ sink.write(record);
3907
+ }
3908
+ maybeSendToBetterStack(betterstack, record);
3909
+ maybeSendToDatabuddy(databuddy, record);
3910
+ maybeSendToPostHog(posthog, record);
3911
+ maybeSendToSentry(sentry, record);
3912
+ maybeSendToOTLP(otlp, record);
3913
+ };
3914
+ const logger2 = {
3915
+ success: (message, ...args) => {
3916
+ writeRecord("success", message, args);
3917
+ },
3918
+ critical: (message, ...args) => {
3919
+ writeRecord("critical", message, args);
3920
+ },
3921
+ warning: (message, ...args) => {
3922
+ writeRecord("warning", message, args);
3923
+ },
3924
+ info: (message, ...args) => {
3925
+ writeRecord("info", message, args);
3926
+ },
3927
+ debug: (message, ...args) => {
3928
+ writeRecord("debug", message, args);
3929
+ },
3930
+ error: (message, ...args) => {
3931
+ writeRecord("error", message, args);
3932
+ },
3933
+ warn: (message, ...args) => {
3934
+ writeRecord("warn", message, args);
3935
+ },
3936
+ table: (message, data) => {
3937
+ if (data && typeof data === "object" && runtime.env.get("NODE_ENV") !== "production") {
3938
+ console.log("TABLE:", message);
3939
+ console.table(data);
3940
+ }
3941
+ writeRecord("table", message, data === void 0 ? [] : [data]);
3942
+ },
3943
+ flush: async () => {
3944
+ await sink.flush();
3945
+ await Promise.allSettled([
3946
+ betterstack.flush(),
3947
+ databuddy.flush(),
3948
+ posthog.flush(),
3949
+ sentry.flush(),
3950
+ otlp.flush()
3951
+ ]);
3952
+ },
3953
+ shutdown: async () => {
3954
+ await sink.shutdown();
3955
+ await Promise.allSettled([
3956
+ betterstack.flush(),
3957
+ databuddy.flush(),
3958
+ posthog.flush(),
3959
+ sentry.flush(),
3960
+ otlp.flush()
3961
+ ]);
3962
+ },
3963
+ createStructuredLog: (groupId, initial) => {
3964
+ return createStructuredLogForLogger(logger2, groupId, {
3965
+ initialFields: initial
3966
+ });
3967
+ },
3968
+ child: (childBindings) => {
3969
+ const mergedBindings = { ...bindings, ...childBindings };
3970
+ return createLoggerInstance(
3971
+ rootRawLogger,
3972
+ sink,
3973
+ betterstack,
3974
+ databuddy,
3975
+ posthog,
3976
+ sentry,
3977
+ otlp,
3978
+ mergedBindings,
3979
+ source
3980
+ );
3981
+ },
3982
+ [LOGGER_FACTORY]: {
3983
+ bindings,
3984
+ betterstack,
3985
+ databuddy,
3986
+ posthog,
3987
+ sentry,
3988
+ otlp,
3989
+ sink,
3990
+ create: (nextSource, nextBindings = bindings) => {
3991
+ return createLoggerInstance(
3992
+ rootRawLogger,
3993
+ sink,
3994
+ betterstack,
3995
+ databuddy,
3996
+ posthog,
3997
+ sentry,
3998
+ otlp,
3999
+ nextBindings,
4000
+ nextSource
4001
+ );
4002
+ },
4003
+ writeStructured: (payload, message, nextSource = "structured-flush") => {
4004
+ writeStructuredRecord(payload, message, nextSource);
4005
+ }
4006
+ }
4007
+ };
4008
+ return logger2;
4009
+ }
4010
+ var loggerInstance = null;
4011
+ function createBaseLogger(config) {
4012
+ if (config === void 0 && loggerInstance) {
4013
+ return loggerInstance;
4014
+ }
4015
+ const resolvedConfig = resolveConfig(config);
4016
+ const rawLogger = createPinoLogger(resolvedConfig);
4017
+ const sink = createPrimarySink(resolvedConfig);
4018
+ const betterstack = createBetterStackSender(resolvedConfig);
4019
+ const databuddy = createDatabuddySender(resolvedConfig);
4020
+ const posthog = createPostHogSender(resolvedConfig);
4021
+ const sentry = createSentrySender(resolvedConfig);
4022
+ const otlp = createOTLPRegistry(resolvedConfig);
4023
+ const instance = createLoggerInstance(
4024
+ rawLogger,
4025
+ sink,
4026
+ betterstack,
4027
+ databuddy,
4028
+ posthog,
4029
+ sentry,
4030
+ otlp
4031
+ );
4032
+ if (config === void 0) {
4033
+ loggerInstance = instance;
4034
+ }
4035
+ return instance;
4036
+ }
4037
+ createBaseLogger();
4038
+
4039
+ // src/frameworks/shared/logger.ts
4040
+ function buildVerboseLogMessage(method, statusCode, url, responseTime) {
4041
+ const methodColor = getMethodColor(method);
4042
+ const statusColor = getStatusColor(statusCode);
4043
+ const timeColor = getResponseTimeColor(responseTime);
4044
+ return `${methodColor} ${url} ${statusColor} ${timeColor}`;
4045
+ }
4046
+ function resolveClientLoggingConfig(clientLogging, defaultClientLogging) {
4047
+ const defaultPath = normalizeEndpointPath(
4048
+ defaultClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT
4049
+ );
4050
+ const defaultConfig = defaultClientLogging?.enabled === false ? null : { path: defaultPath };
4051
+ if (clientLogging === false) {
4052
+ return null;
4053
+ }
4054
+ if (clientLogging === void 0) {
4055
+ return defaultConfig;
4056
+ }
4057
+ if (clientLogging === true) {
4058
+ return {
4059
+ path: defaultPath
4060
+ };
4061
+ }
4062
+ return {
4063
+ ...defaultConfig,
4064
+ ...clientLogging,
4065
+ path: normalizeEndpointPath(clientLogging.path ?? defaultPath)
4066
+ };
4067
+ }
4068
+ function resolveServerLogger(config = {}, loggerOverride) {
4069
+ const resolvedConfig = resolveConfig({
4070
+ ...config.level !== void 0 ? { level: config.level } : {},
4071
+ ...config.pretty !== void 0 ? { pretty: config.pretty } : {},
4072
+ ...config.destination !== void 0 ? { destination: config.destination } : {},
4073
+ ...config.logDir !== void 0 ? { logDir: config.logDir } : {},
4074
+ ...config.file !== void 0 ? { file: config.file } : {},
4075
+ ...config.database !== void 0 ? { database: config.database } : {},
4076
+ ...config.connectors !== void 0 ? { connectors: config.connectors } : {}
4077
+ });
4078
+ const {
4079
+ level = resolvedConfig.level,
4080
+ pretty = resolvedConfig.pretty,
4081
+ destination = resolvedConfig.destination,
4082
+ logDir = resolvedConfig.logDir,
4083
+ file = resolvedConfig.file,
4084
+ database = resolvedConfig.database,
4085
+ autoLogging = true,
4086
+ customProps,
4087
+ logErrors = true,
4088
+ ignorePaths,
4089
+ clientLogging,
4090
+ connectors
4091
+ } = config;
4092
+ const logger2 = loggerOverride ?? createBaseLogger({
4093
+ level,
4094
+ pretty,
4095
+ destination,
4096
+ logDir,
4097
+ file,
4098
+ database,
4099
+ connectors
4100
+ });
4101
+ const resolvedClientLogging = resolveClientLoggingConfig(
4102
+ clientLogging,
4103
+ resolvedConfig.clientLogging
4104
+ );
4105
+ const ingestionPath = resolvedClientLogging?.path ?? DEFAULT_CLIENT_LOG_ENDPOINT;
4106
+ const resolvedIgnorePaths = resolvedClientLogging ? Array.from(/* @__PURE__ */ new Set([...ignorePaths ?? [], ingestionPath])) : ignorePaths;
4107
+ return {
4108
+ logger: logger2,
4109
+ betterstack: getBetterStackSender(logger2),
4110
+ databuddy: getDatabuddySender(logger2),
4111
+ posthog: getPostHogSender(logger2),
4112
+ sentry: getSentrySender(logger2),
4113
+ otlp: getOtlpRegistry(logger2),
4114
+ resolvedConfig,
4115
+ level,
4116
+ pretty,
4117
+ logDir,
4118
+ file,
4119
+ autoLogging,
4120
+ customProps,
4121
+ logErrors,
4122
+ resolvedIgnorePaths,
4123
+ resolvedClientLogging,
4124
+ ingestionPath
4125
+ };
4126
+ }
4127
+ function shouldSkipAutoLogging(config, ctx, path3) {
4128
+ if (config.autoLogging === false) {
4129
+ return true;
4130
+ }
4131
+ if (typeof config.autoLogging === "object" && config.autoLogging.ignore?.(ctx)) {
4132
+ return true;
4133
+ }
4134
+ return shouldIgnorePath(path3, config.resolvedIgnorePaths);
4135
+ }
4136
+ function shouldSkipErrorLogging(config, path3) {
4137
+ if (!config.logErrors) {
4138
+ return true;
4139
+ }
4140
+ return shouldIgnorePath(path3, config.resolvedIgnorePaths);
4141
+ }
4142
+ function resolveAdditionalProps(config, ctx) {
4143
+ return config.customProps ? config.customProps(ctx) : {};
4144
+ }
4145
+ function emitHttpRequestLog(logger2, level, request, path3, statusCode, responseTime, additionalProps = {}) {
4146
+ const requestLogData = buildRequestLogData(
4147
+ request,
4148
+ "http_request",
4149
+ path3,
4150
+ statusCode,
4151
+ responseTime,
4152
+ additionalProps
4153
+ );
4154
+ if (level === "info") {
4155
+ logger2.info(
4156
+ buildInfoLogMessage(request.method, statusCode, path3, responseTime),
4157
+ requestLogData
4158
+ );
4159
+ } else {
4160
+ logger2.info(
4161
+ buildVerboseLogMessage(request.method, statusCode, path3, responseTime),
4162
+ requestLogData
4163
+ );
4164
+ if (Object.keys(additionalProps).length > 0) {
4165
+ logger2.debug("Request context", additionalProps);
4166
+ }
4167
+ }
4168
+ return requestLogData;
4169
+ }
4170
+ function emitHttpErrorLog(logger2, level, request, path3, statusCode, responseTime, error, additionalProps = {}, captureContext = {}) {
4171
+ const errorLogData = buildRequestLogData(
4172
+ request,
4173
+ "http_error",
4174
+ path3,
4175
+ statusCode,
4176
+ responseTime,
4177
+ {
4178
+ error: error?.message ?? `HTTP ${statusCode}`,
4179
+ stack: error?.stack,
4180
+ code: error?.code,
4181
+ why: error?.why,
4182
+ fix: error?.fix,
4183
+ link: error?.link,
4184
+ details: error?.details,
4185
+ ...additionalProps
4186
+ }
4187
+ );
4188
+ const message = level === "info" ? buildInfoLogMessage(request.method, statusCode, path3, responseTime) : buildVerboseLogMessage(request.method, statusCode, path3, responseTime);
4189
+ logger2.error(message, errorLogData);
4190
+ const posthog = tryGetPostHogSender(logger2);
4191
+ if (posthog?.shouldAutoCaptureExceptions()) {
4192
+ posthog.captureException(captureContext.error ?? error ?? message, {
4193
+ source: "server",
4194
+ warnIfUnavailable: true,
4195
+ distinctId: captureContext.distinctId ?? getHeaderValue(request.headers, "x-posthog-distinct-id"),
4196
+ properties: buildPostHogExceptionProperties(
4197
+ {
4198
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4199
+ level: "error",
4200
+ message,
4201
+ data: errorLogData
4202
+ },
4203
+ "server",
4204
+ {
4205
+ $request_method: request.method,
4206
+ $request_path: path3,
4207
+ $current_url: request.url,
4208
+ $response_status_code: statusCode,
4209
+ ...getHeaderValue(request.headers, "user-agent") ? { $user_agent: getHeaderValue(request.headers, "user-agent") } : {},
4210
+ ...errorLogData.ip ? { $ip: errorLogData.ip } : {}
4211
+ }
4212
+ )
4213
+ });
4214
+ }
4215
+ const betterstack = tryGetBetterStackSender(logger2);
4216
+ if (betterstack?.shouldAutoCaptureExceptions()) {
4217
+ betterstack.captureException(captureContext.error ?? error ?? message, {
4218
+ source: "server",
4219
+ warnIfUnavailable: true,
4220
+ context: {
4221
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4222
+ level: "error",
4223
+ message,
4224
+ status: statusCode,
4225
+ path: path3,
4226
+ data: errorLogData
4227
+ }
4228
+ });
4229
+ }
4230
+ const databuddy = tryGetDatabuddySender(logger2);
4231
+ if (databuddy?.shouldAutoCaptureExceptions()) {
4232
+ databuddy.captureException(captureContext.error ?? error ?? message, {
4233
+ source: "server",
4234
+ warnIfUnavailable: true,
4235
+ properties: {
4236
+ method: request.method,
4237
+ path: path3,
4238
+ status_code: statusCode,
4239
+ ...request.url ? { current_url: request.url } : {},
4240
+ ...getHeaderValue(request.headers, "user-agent") ? { user_agent: getHeaderValue(request.headers, "user-agent") } : {},
4241
+ ...errorLogData.ip ? { ip: errorLogData.ip } : {},
4242
+ payload: errorLogData
4243
+ }
4244
+ });
4245
+ }
4246
+ return errorLogData;
4247
+ }
4248
+ async function parseClientLogPayload(request, body) {
4249
+ if (body !== void 0) {
4250
+ if (typeof body === "string") {
4251
+ return JSON.parse(body);
4252
+ }
4253
+ return body;
4254
+ }
4255
+ if (typeof request.json === "function") {
4256
+ return await request.json();
4257
+ }
4258
+ throw new Error("Unable to parse client log payload");
4259
+ }
4260
+ function getClientLogMethod(logger2, level) {
4261
+ switch (level) {
4262
+ case "debug":
4263
+ return logger2.debug;
4264
+ case "info":
4265
+ return logger2.info;
4266
+ case "warning":
4267
+ return logger2.warning;
4268
+ case "error":
4269
+ return logger2.error;
4270
+ case "critical":
4271
+ return logger2.critical;
4272
+ case "success":
4273
+ return logger2.success;
4274
+ }
4275
+ }
4276
+ async function handleClientLogIngestion(options) {
4277
+ const { config, ctx, request, body, deliveryPath } = options;
4278
+ if (!config.resolvedClientLogging) {
4279
+ return { status: 404 };
4280
+ }
4281
+ let payload;
4282
+ try {
4283
+ payload = await parseClientLogPayload(request, body);
4284
+ } catch {
4285
+ return { status: 400 };
4286
+ }
4287
+ if (!isClientLogEvent(payload)) {
4288
+ return { status: 400 };
4289
+ }
4290
+ const isAllowed = config.resolvedClientLogging.validate ? await config.resolvedClientLogging.validate(ctx, payload) : true;
4291
+ if (!isAllowed) {
4292
+ return { status: 403 };
4293
+ }
4294
+ const serverContext = config.resolvedClientLogging.enrich ? await config.resolvedClientLogging.enrich(ctx, payload) : void 0;
4295
+ const structuredPayload = {
4296
+ ...payload,
4297
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
4298
+ delivery: buildClientDetails(request, deliveryPath ?? extractPathname(request.url))
4299
+ };
4300
+ if (serverContext !== void 0) {
4301
+ structuredPayload.serverContext = serverContext;
4302
+ }
4303
+ if (payload.level === "table") {
4304
+ config.logger.table(`[client] ${payload.message}`, structuredPayload);
4305
+ } else {
4306
+ const logMethod = getClientLogMethod(config.logger, payload.level);
4307
+ logMethod(`[client] ${payload.message}`, structuredPayload);
4308
+ }
4309
+ const headers = {};
4310
+ if (payload.connector === "betterstack") {
4311
+ headers["x-blyp-betterstack-status"] = config.betterstack.ready ? "enabled" : "missing";
4312
+ if (config.betterstack.ready) {
4313
+ const forwardedRecord = {
4314
+ timestamp: structuredPayload.receivedAt,
4315
+ level: payload.level,
4316
+ message: `[client] ${payload.message}`,
4317
+ data: structuredPayload
4318
+ };
4319
+ config.betterstack.send(forwardedRecord, {
4320
+ source: "client"
4321
+ });
4322
+ if ((payload.level === "error" || payload.level === "critical") && config.betterstack.shouldAutoCaptureExceptions()) {
4323
+ const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
4324
+ config.betterstack.captureException(clientErrorCandidate, {
4325
+ source: "client",
4326
+ warnIfUnavailable: true,
4327
+ context: {
4328
+ sessionId: payload.session.sessionId,
4329
+ pageUrl: payload.page.url,
4330
+ pagePath: payload.page.pathname,
4331
+ metadata: payload.metadata,
4332
+ payload: structuredPayload
4333
+ }
4334
+ });
4335
+ }
4336
+ }
4337
+ } else if (payload.connector === "databuddy") {
4338
+ headers["x-blyp-databuddy-status"] = config.databuddy.ready ? "enabled" : "missing";
4339
+ if (config.databuddy.ready) {
4340
+ const forwardedRecord = {
4341
+ timestamp: structuredPayload.receivedAt,
4342
+ level: payload.level,
4343
+ message: `[client] ${payload.message}`,
4344
+ data: structuredPayload
4345
+ };
4346
+ config.databuddy.send(forwardedRecord, {
4347
+ source: "client"
4348
+ });
4349
+ if ((payload.level === "error" || payload.level === "critical") && config.databuddy.shouldAutoCaptureExceptions()) {
4350
+ const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
4351
+ config.databuddy.captureException(clientErrorCandidate, {
4352
+ source: "client",
4353
+ warnIfUnavailable: true,
4354
+ sessionId: payload.session.sessionId,
4355
+ properties: {
4356
+ page_url: payload.page.url,
4357
+ page_path: payload.page.pathname,
4358
+ client_runtime: payload.device?.runtime,
4359
+ metadata: payload.metadata,
4360
+ payload: structuredPayload
4361
+ }
4362
+ });
4363
+ }
4364
+ }
4365
+ } else if (payload.connector === "posthog") {
4366
+ headers["x-blyp-posthog-status"] = config.posthog.ready ? "enabled" : "missing";
4367
+ if (config.posthog.ready) {
4368
+ const forwardedRecord = {
4369
+ timestamp: structuredPayload.receivedAt,
4370
+ level: payload.level,
4371
+ message: `[client] ${payload.message}`,
4372
+ data: structuredPayload
4373
+ };
4374
+ config.posthog.send(forwardedRecord, {
4375
+ source: "client"
4376
+ });
4377
+ if ((payload.level === "error" || payload.level === "critical") && config.posthog.shouldAutoCaptureExceptions()) {
4378
+ const metadata = structuredPayload.metadata;
4379
+ const posthogDistinctId = metadata && typeof metadata === "object" && !Array.isArray(metadata) && typeof metadata.posthogDistinctId === "string" && metadata.posthogDistinctId ? String(metadata.posthogDistinctId) : void 0;
4380
+ const clientErrorCandidate = payload.data && typeof payload.data === "object" && !Array.isArray(payload.data) && typeof payload.data.message === "string" ? payload.data : payload.message;
4381
+ config.posthog.captureException(clientErrorCandidate, {
4382
+ source: "client",
4383
+ warnIfUnavailable: true,
4384
+ distinctId: posthogDistinctId,
4385
+ properties: buildPostHogExceptionProperties(forwardedRecord, "client", {
4386
+ $session_id: payload.session.sessionId,
4387
+ $current_url: payload.page.url,
4388
+ $request_path: payload.page.pathname,
4389
+ "client.runtime": payload.device?.runtime,
4390
+ "client.metadata": payload.metadata
4391
+ })
4392
+ });
4393
+ }
4394
+ }
4395
+ } else if (payload.connector === "sentry") {
4396
+ headers["x-blyp-sentry-status"] = config.sentry.ready ? "enabled" : "missing";
4397
+ if (config.sentry.ready) {
4398
+ config.sentry.send({
4399
+ timestamp: structuredPayload.receivedAt,
4400
+ level: payload.level,
4401
+ message: `[client] ${payload.message}`,
4402
+ data: structuredPayload
4403
+ }, {
4404
+ source: "client"
4405
+ });
4406
+ }
4407
+ } else if (payload.connector?.type === "otlp") {
4408
+ const sender = config.otlp.get(payload.connector.name);
4409
+ headers["x-blyp-otlp-status"] = sender.ready ? "enabled" : "missing";
4410
+ if (sender.ready) {
4411
+ sender.send({
4412
+ timestamp: structuredPayload.receivedAt,
4413
+ level: payload.level,
4414
+ message: `[client] ${payload.message}`,
4415
+ data: structuredPayload
4416
+ }, {
4417
+ source: "client"
4418
+ });
4419
+ }
4420
+ }
4421
+ return Object.keys(headers).length > 0 ? { status: 204, headers } : { status: 204 };
4422
+ }
4423
+ async function readNodeRequestBody(stream) {
4424
+ const chunks = [];
4425
+ for await (const chunk of stream) {
4426
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
4427
+ }
4428
+ return Buffer.concat(chunks).toString("utf8");
4429
+ }
4430
+ function buildAbsoluteUrl(path3, headers) {
4431
+ if (path3.startsWith("http://") || path3.startsWith("https://")) {
4432
+ return path3;
4433
+ }
4434
+ const protocol = getHeaderValue(headers, "x-forwarded-proto") ?? "http";
4435
+ const host = getHeaderValue(headers, "host") ?? "localhost";
4436
+ return `${protocol}://${host}${path3.startsWith("/") ? path3 : `/${path3}`}`;
4437
+ }
4438
+ function shouldAutoFlushServerLogger(config) {
4439
+ return config.resolvedConfig.destination === "database";
4440
+ }
4441
+ async function flushServerLoggerSafely(config) {
4442
+ if (!shouldAutoFlushServerLogger(config)) {
4443
+ return;
4444
+ }
4445
+ try {
4446
+ await config.logger.flush();
4447
+ } catch (error) {
4448
+ console.warn("[Blyp] Warning: Failed to flush database logs.", error);
4449
+ }
4450
+ }
4451
+
4452
+ // src/frameworks/shared/request-logger.ts
4453
+ function createRequestScopedLogger(logger2, options = {}) {
4454
+ const scopedLogger = createLoggerWithSource(logger2, "request-scoped");
4455
+ const requestScopedLogger = attachLoggerInternals({
4456
+ ...scopedLogger,
4457
+ createStructuredLog: (groupId, initial) => {
4458
+ return createStructuredLogForLogger(requestScopedLogger, groupId, {
4459
+ initialFields: initial,
4460
+ resolveDefaultFields: options.resolveStructuredFields,
4461
+ onCreate: () => {
4462
+ markStructuredCollectorActive();
4463
+ },
4464
+ onEmit: () => {
4465
+ markStructuredLogEmitted();
4466
+ options.onStructuredEmit?.();
4467
+ }
4468
+ });
4469
+ },
4470
+ child(bindings) {
4471
+ return createRequestScopedLogger(scopedLogger.child(bindings), options);
4472
+ }
4473
+ }, scopedLogger);
4474
+ setActiveRequestLogger(requestScopedLogger);
4475
+ return requestScopedLogger;
4476
+ }
4477
+
4478
+ // src/frameworks/shared/h3.ts
4479
+ var BLYP_NITRO_STATE_KEY = /* @__PURE__ */ Symbol.for("blyp.nitro.state");
4480
+ function getNitroState(event) {
4481
+ return event.context[BLYP_NITRO_STATE_KEY];
4482
+ }
4483
+ function setNitroState(event, state) {
4484
+ event.context[BLYP_NITRO_STATE_KEY] = state;
4485
+ return state;
4486
+ }
4487
+ function getNitroMethod(event) {
4488
+ return event.method ?? event.node?.req?.method ?? event.request?.method ?? "GET";
4489
+ }
4490
+ function getNitroHeaders(event) {
4491
+ return event.headers ?? event.node?.req?.headers ?? event.request?.headers;
4492
+ }
4493
+ function getNitroUrl(event) {
4494
+ if (event.request?.url) {
4495
+ return event.request.url;
4496
+ }
4497
+ const path3 = event.url ?? event.path ?? event.node?.req?.url ?? "/";
4498
+ return buildAbsoluteUrl(path3, getNitroHeaders(event));
4499
+ }
4500
+ function getNitroPath(event) {
4501
+ if (typeof event.path === "string" && event.path.length > 0) {
4502
+ return event.path;
4503
+ }
4504
+ if (event.request?.url) {
4505
+ return new URL(event.request.url).pathname;
4506
+ }
4507
+ const requestUrl = event.url ?? event.node?.req?.url ?? "/";
4508
+ if (requestUrl.startsWith("http://") || requestUrl.startsWith("https://")) {
4509
+ return new URL(requestUrl).pathname;
4510
+ }
4511
+ const queryIndex = requestUrl.indexOf("?");
4512
+ return queryIndex >= 0 ? requestUrl.slice(0, queryIndex) : requestUrl;
4513
+ }
4514
+ function createNitroRequestLike(event) {
4515
+ return createRequestLike(getNitroMethod(event), getNitroUrl(event), getNitroHeaders(event));
4516
+ }
4517
+ function getNitroStatus(event, response, fallbackStatus = 200) {
4518
+ if (response instanceof Response) {
4519
+ return response.status;
4520
+ }
4521
+ if (typeof response?.status === "number") {
4522
+ return response.status;
4523
+ }
4524
+ if (typeof response?.statusCode === "number") {
4525
+ return response.statusCode;
4526
+ }
4527
+ if (typeof event.node?.res?.statusCode === "number" && event.node.res.statusCode > 0) {
4528
+ return event.node.res.statusCode;
4529
+ }
4530
+ return fallbackStatus;
4531
+ }
4532
+ async function readNitroBody(event) {
4533
+ if (event.body !== void 0) {
4534
+ return event.body;
4535
+ }
4536
+ if (event.request) {
4537
+ const contentType = event.request.headers.get("content-type") ?? "";
4538
+ if (contentType.includes("application/json")) {
4539
+ const fallbackRequest = event.request.clone();
4540
+ try {
4541
+ return await event.request.json();
4542
+ } catch {
4543
+ return await fallbackRequest.text();
4544
+ }
4545
+ }
4546
+ return await event.request.text();
4547
+ }
4548
+ if (event.node?.req) {
4549
+ return await readNodeRequestBody(event.node.req);
4550
+ }
4551
+ throw new Error("Unable to parse Nitro request body");
4552
+ }
4553
+
4554
+ // src/frameworks/nitro/logger.ts
4555
+ function createContext(event, response, error) {
4556
+ return { event, response, error };
4557
+ }
4558
+ function buildFactory(shared) {
4559
+ const getLogger = (event) => event.context.blypLog ?? shared.logger;
4560
+ const logSuccess = async (event, response) => {
4561
+ const state = getNitroState(event);
4562
+ if (!state || state.structuredLogEmitted || state.errorLogged) {
4563
+ return;
4564
+ }
4565
+ const requestLike = createNitroRequestLike(event);
4566
+ const statusCode = getNitroStatus(event, response);
4567
+ const responseTime = Math.round(performance.now() - state.startTime);
4568
+ const loggerContext = createContext(event, response);
4569
+ if (isErrorStatus(statusCode)) {
4570
+ if (!shouldSkipErrorLogging(shared, state.path)) {
4571
+ emitHttpErrorLog(
4572
+ shared.logger,
4573
+ shared.level,
4574
+ requestLike,
4575
+ state.path,
4576
+ statusCode,
4577
+ responseTime,
4578
+ toErrorLike(void 0, statusCode),
4579
+ resolveAdditionalProps(shared, loggerContext)
4580
+ );
4581
+ }
4582
+ } else if (!shouldSkipAutoLogging(shared, loggerContext, state.path)) {
4583
+ emitHttpRequestLog(
4584
+ shared.logger,
4585
+ shared.level,
4586
+ requestLike,
4587
+ state.path,
4588
+ statusCode,
4589
+ responseTime,
4590
+ resolveAdditionalProps(shared, loggerContext)
4591
+ );
4592
+ }
4593
+ };
4594
+ const logError = async (event, error, response) => {
4595
+ const state = getNitroState(event);
4596
+ if (!state || state.structuredLogEmitted || state.errorLogged || shouldSkipErrorLogging(shared, state.path)) {
4597
+ return;
4598
+ }
4599
+ state.errorLogged = true;
4600
+ emitHttpErrorLog(
4601
+ shared.logger,
4602
+ shared.level,
4603
+ createNitroRequestLike(event),
4604
+ state.path,
4605
+ getNitroStatus(event, response, 500),
4606
+ Math.round(performance.now() - state.startTime),
4607
+ toErrorLike(error, 500),
4608
+ resolveAdditionalProps(shared, createContext(event, response, error)),
4609
+ { error }
4610
+ );
4611
+ };
4612
+ return {
4613
+ logger: shared.logger,
4614
+ getLogger,
4615
+ plugin: async (nitroApp) => {
4616
+ await nitroApp.hooks.hook("request", async (eventArg) => {
4617
+ const event = eventArg;
4618
+ enterRequestContext();
4619
+ const path3 = getNitroPath(event);
4620
+ let state = setNitroState(event, {
4621
+ startTime: performance.now(),
4622
+ path: path3,
4623
+ structuredLogEmitted: false
4624
+ });
4625
+ const scopedLogger = createRequestScopedLogger(shared.logger, {
4626
+ resolveStructuredFields: () => ({
4627
+ method: getNitroMethod(event),
4628
+ path: path3,
4629
+ ...resolveAdditionalProps(shared, createContext(event))
4630
+ }),
4631
+ onStructuredEmit: () => {
4632
+ const currentState = getNitroState(event);
4633
+ if (currentState) {
4634
+ currentState.structuredLogEmitted = true;
4635
+ }
4636
+ }
4637
+ });
4638
+ event.context.blypLog = scopedLogger;
4639
+ state.scopedLogger = scopedLogger;
4640
+ });
4641
+ await nitroApp.hooks.hook("beforeResponse", async (eventArg, payload) => {
4642
+ await logSuccess(eventArg, payload);
4643
+ });
4644
+ await nitroApp.hooks.hook("afterResponse", async (eventArg) => {
4645
+ await flushServerLoggerSafely(shared);
4646
+ const state = getNitroState(eventArg);
4647
+ if (state) {
4648
+ state.errorLogged = true;
4649
+ }
4650
+ });
4651
+ await nitroApp.hooks.hook("error", async (errorArg, eventArg) => {
4652
+ if (eventArg && typeof eventArg === "object") {
4653
+ await logError(eventArg, errorArg);
4654
+ await flushServerLoggerSafely(shared);
4655
+ }
4656
+ });
4657
+ },
4658
+ clientLogHandler: async (event) => {
4659
+ const path3 = getNitroPath(event);
4660
+ if (path3 !== shared.ingestionPath) {
4661
+ return new Response(
4662
+ JSON.stringify({
4663
+ error: `Mounted route path ${path3} does not match configured client logging path ${shared.ingestionPath}`
4664
+ }),
4665
+ {
4666
+ status: 500,
4667
+ headers: { "content-type": "application/json" }
4668
+ }
4669
+ );
4670
+ }
4671
+ const body = await readNitroBody(event);
4672
+ const result = await handleClientLogIngestion({
4673
+ config: shared,
4674
+ ctx: createContext(event),
4675
+ request: {
4676
+ ...createNitroRequestLike(event),
4677
+ json: async () => body
4678
+ },
4679
+ body,
4680
+ deliveryPath: path3
4681
+ });
4682
+ await flushServerLoggerSafely(shared);
4683
+ return new Response(null, {
4684
+ status: result.status,
4685
+ headers: result.headers
4686
+ });
4687
+ }
4688
+ };
4689
+ }
4690
+
4691
+ // src/frameworks/nuxt/logger.ts
4692
+ function createNuxtLogger(config = {}) {
4693
+ const nitro = buildFactory(resolveServerLogger(config));
4694
+ return {
4695
+ logger: nitro.logger,
4696
+ serverPlugin: nitro.plugin,
4697
+ clientLogHandler: nitro.clientLogHandler,
4698
+ getLogger: (event) => nitro.getLogger(event)
4699
+ };
4700
+ }
4701
+ var createLogger = createNuxtLogger;
4702
+
4703
+ export { createLogger, createNuxtLogger };
4704
+ //# sourceMappingURL=nuxt.mjs.map
4705
+ //# sourceMappingURL=nuxt.mjs.map