@blyp/core 0.1.2

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