@blyp/core 0.1.21 → 0.1.22

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 (242) hide show
  1. package/README.md +217 -11
  2. package/STABILITY.md +56 -0
  3. package/dist/ai/anthropic/index.d.ts +3 -0
  4. package/dist/ai/anthropic/normalize.d.ts +9 -0
  5. package/dist/ai/anthropic/stream.d.ts +3 -0
  6. package/dist/ai/anthropic/wrap.d.ts +13 -0
  7. package/dist/ai/anthropic.js +701 -0
  8. package/dist/ai/anthropic.mjs +701 -0
  9. package/dist/ai/fetch.js +701 -0
  10. package/dist/ai/fetch.mjs +701 -0
  11. package/dist/ai/openai/index.d.ts +3 -0
  12. package/dist/ai/openai/normalize.d.ts +10 -0
  13. package/dist/ai/openai/stream.d.ts +3 -0
  14. package/dist/ai/openai/wrap.d.ts +24 -0
  15. package/dist/ai/openai.js +701 -0
  16. package/dist/ai/openai.mjs +701 -0
  17. package/dist/ai/shared/fetch.d.ts +5 -0
  18. package/dist/ai/shared/index.d.ts +2 -0
  19. package/dist/ai/shared/normalize.d.ts +17 -0
  20. package/dist/ai/shared/redaction.d.ts +6 -0
  21. package/dist/ai/shared/stream.d.ts +7 -0
  22. package/dist/ai/shared/trace.d.ts +116 -0
  23. package/dist/ai/shared/types.d.ts +161 -0
  24. package/dist/ai/shared.js +701 -0
  25. package/dist/ai/shared.mjs +701 -0
  26. package/dist/ai/vercel/index.d.ts +3 -0
  27. package/dist/ai/vercel/middleware.d.ts +3 -0
  28. package/dist/ai/vercel/model.d.ts +3 -0
  29. package/dist/ai/vercel.js +701 -0
  30. package/dist/ai/vercel.mjs +701 -0
  31. package/dist/astro.js +618 -4519
  32. package/dist/astro.mjs +618 -4491
  33. package/dist/client.js +1 -1139
  34. package/dist/client.mjs +1 -1132
  35. package/dist/connectors/betterstack.js +9 -1532
  36. package/dist/connectors/betterstack.mjs +9 -1507
  37. package/dist/connectors/databuddy.js +9 -1456
  38. package/dist/connectors/databuddy.mjs +9 -1451
  39. package/dist/connectors/delivery/backoff.d.ts +2 -0
  40. package/dist/connectors/delivery/manager.d.ts +44 -0
  41. package/dist/connectors/delivery/queue-path.d.ts +1 -0
  42. package/dist/connectors/delivery/sqlite-adapter-bun.d.ts +1 -0
  43. package/dist/connectors/delivery/sqlite-adapter-node.d.ts +1 -0
  44. package/dist/connectors/delivery/sqlite-client.d.ts +37 -0
  45. package/dist/connectors/delivery/sqlite-worker.d.ts +1 -0
  46. package/dist/connectors/delivery/studio-queue.d.ts +12 -0
  47. package/dist/connectors/delivery/types.d.ts +98 -0
  48. package/dist/connectors/otlp/index.d.ts +1 -0
  49. package/dist/connectors/otlp.js +9 -1371
  50. package/dist/connectors/otlp.mjs +9 -1368
  51. package/dist/connectors/posthog/properties.d.ts +4 -0
  52. package/dist/connectors/posthog/sender.d.ts +0 -1
  53. package/dist/connectors/posthog.js +10 -1527
  54. package/dist/connectors/posthog.mjs +10 -1522
  55. package/dist/connectors/sentry.js +9 -1380
  56. package/dist/connectors/sentry.mjs +9 -1357
  57. package/dist/core/config.d.ts +7 -2
  58. package/dist/core/log-record.d.ts +5 -4
  59. package/dist/core/logger.d.ts +2 -0
  60. package/dist/core/optional-module.d.ts +1 -0
  61. package/dist/core/pino-pretty-loader.d.ts +4 -0
  62. package/dist/database.js +1 -24
  63. package/dist/database.mjs +1 -21
  64. package/dist/elysia.js +613 -4517
  65. package/dist/elysia.mjs +615 -4491
  66. package/dist/expo.js +1 -726
  67. package/dist/expo.mjs +1 -724
  68. package/dist/express.js +613 -4507
  69. package/dist/express.mjs +615 -4480
  70. package/dist/fastify.js +615 -4526
  71. package/dist/fastify.mjs +617 -4499
  72. package/dist/frameworks/elysia/index.d.ts +1 -1
  73. package/dist/frameworks/elysia/logger.d.ts +2 -35
  74. package/dist/frameworks/nestjs/helpers.d.ts +2 -0
  75. package/dist/frameworks/shared/http.d.ts +3 -2
  76. package/dist/frameworks/shared/index.d.ts +2 -1
  77. package/dist/frameworks/shared/logger.d.ts +2 -0
  78. package/dist/frameworks/shared/request-context.d.ts +2 -0
  79. package/dist/frameworks/shared/trace.d.ts +6 -0
  80. package/dist/hono.js +616 -4496
  81. package/dist/hono.mjs +618 -4470
  82. package/dist/index.d.ts +49 -19
  83. package/dist/index.js +615 -7557
  84. package/dist/index.mjs +618 -7465
  85. package/dist/nestjs.js +626 -4999
  86. package/dist/nestjs.mjs +621 -4966
  87. package/dist/nextjs.js +618 -4525
  88. package/dist/nextjs.mjs +620 -4499
  89. package/dist/nitro.js +617 -4642
  90. package/dist/nitro.mjs +619 -4616
  91. package/dist/nuxt.js +617 -4649
  92. package/dist/nuxt.mjs +619 -4623
  93. package/dist/react-router.js +616 -4559
  94. package/dist/react-router.mjs +618 -4533
  95. package/dist/shared/redaction.d.ts +17 -0
  96. package/dist/standalone.js +606 -3628
  97. package/dist/standalone.mjs +610 -3603
  98. package/dist/sveltekit.js +617 -4523
  99. package/dist/sveltekit.mjs +619 -4497
  100. package/dist/tanstack-start.js +616 -4522
  101. package/dist/tanstack-start.mjs +618 -4496
  102. package/dist/types/core/config.d.ts +57 -0
  103. package/dist/types/core/logger.d.ts +3 -0
  104. package/dist/types/core/structured-log.d.ts +2 -0
  105. package/dist/types/database.d.ts +1 -0
  106. package/dist/types/frameworks/astro.d.ts +1 -0
  107. package/dist/types/frameworks/client.d.ts +2 -0
  108. package/dist/types/frameworks/elysia.d.ts +2 -0
  109. package/dist/types/frameworks/express.d.ts +1 -0
  110. package/dist/types/frameworks/fastify.d.ts +1 -0
  111. package/dist/types/frameworks/hono.d.ts +1 -0
  112. package/dist/types/frameworks/http.d.ts +1 -0
  113. package/dist/types/frameworks/nestjs.d.ts +2 -0
  114. package/dist/types/frameworks/nextjs.d.ts +1 -0
  115. package/dist/types/frameworks/nitro.d.ts +1 -0
  116. package/dist/types/frameworks/react-router.d.ts +2 -0
  117. package/dist/types/frameworks/request-context.d.ts +1 -0
  118. package/dist/types/frameworks/shared.d.ts +4 -1
  119. package/dist/types/frameworks/standalone.d.ts +3 -2
  120. package/dist/types/frameworks/sveltekit.d.ts +1 -0
  121. package/dist/types/frameworks/tanstack-start.d.ts +9 -3
  122. package/dist/types/frameworks/workers.d.ts +3 -0
  123. package/dist/types/shared/client-log.d.ts +1 -0
  124. package/dist/workers.js +2 -626
  125. package/dist/workers.mjs +2 -623
  126. package/package.json +246 -173
  127. package/dist/astro.js.map +0 -1
  128. package/dist/astro.mjs.map +0 -1
  129. package/dist/client.js.map +0 -1
  130. package/dist/client.mjs.map +0 -1
  131. package/dist/connectors/betterstack.js.map +0 -1
  132. package/dist/connectors/betterstack.mjs.map +0 -1
  133. package/dist/connectors/databuddy.js.map +0 -1
  134. package/dist/connectors/databuddy.mjs.map +0 -1
  135. package/dist/connectors/otlp.js.map +0 -1
  136. package/dist/connectors/otlp.mjs.map +0 -1
  137. package/dist/connectors/posthog.js.map +0 -1
  138. package/dist/connectors/posthog.mjs.map +0 -1
  139. package/dist/connectors/sentry.js.map +0 -1
  140. package/dist/connectors/sentry.mjs.map +0 -1
  141. package/dist/database.js.map +0 -1
  142. package/dist/database.mjs.map +0 -1
  143. package/dist/elysia.js.map +0 -1
  144. package/dist/elysia.mjs.map +0 -1
  145. package/dist/expo.js.map +0 -1
  146. package/dist/expo.mjs.map +0 -1
  147. package/dist/express.js.map +0 -1
  148. package/dist/express.mjs.map +0 -1
  149. package/dist/fastify.js.map +0 -1
  150. package/dist/fastify.mjs.map +0 -1
  151. package/dist/hono.js.map +0 -1
  152. package/dist/hono.mjs.map +0 -1
  153. package/dist/index.js.map +0 -1
  154. package/dist/index.mjs.map +0 -1
  155. package/dist/nestjs.js.map +0 -1
  156. package/dist/nestjs.mjs.map +0 -1
  157. package/dist/nextjs.js.map +0 -1
  158. package/dist/nextjs.mjs.map +0 -1
  159. package/dist/nitro.js.map +0 -1
  160. package/dist/nitro.mjs.map +0 -1
  161. package/dist/nuxt.js.map +0 -1
  162. package/dist/nuxt.mjs.map +0 -1
  163. package/dist/react-router.js.map +0 -1
  164. package/dist/react-router.mjs.map +0 -1
  165. package/dist/standalone.js.map +0 -1
  166. package/dist/standalone.mjs.map +0 -1
  167. package/dist/sveltekit.js.map +0 -1
  168. package/dist/sveltekit.mjs.map +0 -1
  169. package/dist/tanstack-start.js.map +0 -1
  170. package/dist/tanstack-start.mjs.map +0 -1
  171. package/dist/workers.js.map +0 -1
  172. package/dist/workers.mjs.map +0 -1
  173. package/exports/client.js +0 -3
  174. package/exports/client.mjs +0 -3
  175. package/exports/connectors/betterstack.js +0 -1
  176. package/exports/connectors/betterstack.mjs +0 -1
  177. package/exports/connectors/databuddy.js +0 -1
  178. package/exports/connectors/databuddy.mjs +0 -1
  179. package/exports/connectors/otlp.js +0 -1
  180. package/exports/connectors/otlp.mjs +0 -1
  181. package/exports/connectors/posthog.js +0 -1
  182. package/exports/connectors/posthog.mjs +0 -1
  183. package/exports/connectors/sentry.js +0 -1
  184. package/exports/connectors/sentry.mjs +0 -1
  185. package/exports/database.js +0 -1
  186. package/exports/database.mjs +0 -1
  187. package/exports/expo.js +0 -1
  188. package/exports/expo.mjs +0 -1
  189. package/exports/frameworks/astro.js +0 -1
  190. package/exports/frameworks/astro.mjs +0 -1
  191. package/exports/frameworks/elysia.js +0 -1
  192. package/exports/frameworks/elysia.mjs +0 -1
  193. package/exports/frameworks/express.js +0 -1
  194. package/exports/frameworks/express.mjs +0 -1
  195. package/exports/frameworks/fastify.js +0 -1
  196. package/exports/frameworks/fastify.mjs +0 -1
  197. package/exports/frameworks/hono.js +0 -1
  198. package/exports/frameworks/hono.mjs +0 -1
  199. package/exports/frameworks/nestjs.js +0 -1
  200. package/exports/frameworks/nestjs.mjs +0 -1
  201. package/exports/frameworks/nextjs.js +0 -1
  202. package/exports/frameworks/nextjs.mjs +0 -1
  203. package/exports/frameworks/nitro.js +0 -1
  204. package/exports/frameworks/nitro.mjs +0 -1
  205. package/exports/frameworks/nuxt.js +0 -1
  206. package/exports/frameworks/nuxt.mjs +0 -1
  207. package/exports/frameworks/react-router.js +0 -1
  208. package/exports/frameworks/react-router.mjs +0 -1
  209. package/exports/frameworks/standalone.js +0 -1
  210. package/exports/frameworks/standalone.mjs +0 -1
  211. package/exports/frameworks/sveltekit.js +0 -1
  212. package/exports/frameworks/sveltekit.mjs +0 -1
  213. package/exports/frameworks/tanstack-start.js +0 -1
  214. package/exports/frameworks/tanstack-start.mjs +0 -1
  215. package/exports/workers.js +0 -1
  216. package/exports/workers.mjs +0 -1
  217. package/types/client.d.ts +0 -34
  218. package/types/connectors/betterstack.d.ts +0 -1
  219. package/types/connectors/databuddy.d.ts +0 -1
  220. package/types/connectors/otlp.d.ts +0 -1
  221. package/types/connectors/posthog.d.ts +0 -1
  222. package/types/connectors/sentry.d.ts +0 -1
  223. package/types/database.d.ts +0 -1
  224. package/types/expo.d.ts +0 -17
  225. package/types/frameworks/astro.d.ts +0 -1
  226. package/types/frameworks/client.d.ts +0 -160
  227. package/types/frameworks/elysia.d.ts +0 -1
  228. package/types/frameworks/expo.d.ts +0 -50
  229. package/types/frameworks/express.d.ts +0 -1
  230. package/types/frameworks/fastify.d.ts +0 -1
  231. package/types/frameworks/hono.d.ts +0 -1
  232. package/types/frameworks/nestjs.d.ts +0 -1
  233. package/types/frameworks/nextjs.d.ts +0 -1
  234. package/types/frameworks/nitro.d.ts +0 -1
  235. package/types/frameworks/nuxt.d.ts +0 -1
  236. package/types/frameworks/react-router.d.ts +0 -1
  237. package/types/frameworks/standalone.d.ts +0 -1
  238. package/types/frameworks/sveltekit.d.ts +0 -1
  239. package/types/frameworks/tanstack-start.d.ts +0 -1
  240. package/types/frameworks/workers.d.ts +0 -115
  241. package/types/index.d.ts +0 -1
  242. package/types/workers.d.ts +0 -13
@@ -1,1532 +1,9 @@
1
- 'use strict';
2
-
3
- var fs = require('fs');
4
- var jiti = require('jiti');
5
- var path = require('path');
6
- var zod = require('zod');
7
- var Sentry = require('@sentry/node');
8
- var node = require('@logtail/node');
9
- require('fflate');
10
-
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
21
- });
22
- }
23
- });
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- var Sentry__namespace = /*#__PURE__*/_interopNamespace(Sentry);
30
-
31
- // src/core/config.ts
32
-
33
- // src/shared/log-value.ts
34
- function normalizeError(error) {
35
- const normalized = {
36
- name: error.name,
37
- message: error.message
38
- };
39
- if (error.stack) {
40
- normalized.stack = error.stack;
41
- }
42
- const errorWithCause = error;
43
- if (errorWithCause.cause !== void 0) {
44
- normalized.cause = normalizeLogValue(errorWithCause.cause);
45
- }
46
- return normalized;
47
- }
48
- function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
49
- if (value instanceof Error) {
50
- return normalizeError(value);
51
- }
52
- if (typeof value === "function") {
53
- return `[Function: ${value.name || "anonymous"}]`;
54
- }
55
- if (typeof value === "symbol") {
56
- return value.toString();
57
- }
58
- if (value === void 0 || value === null) {
59
- return value;
60
- }
61
- if (Array.isArray(value)) {
62
- return value.map((entry) => normalizeLogValue(entry, seen));
63
- }
64
- if (typeof value === "object") {
65
- if (seen.has(value)) {
66
- return "[Circular]";
67
- }
68
- seen.add(value);
69
- const normalized = {};
70
- for (const [key, entry] of Object.entries(value)) {
71
- normalized[key] = normalizeLogValue(entry, seen);
72
- }
73
- seen.delete(value);
74
- return normalized;
75
- }
76
- return value;
77
- }
78
- function serializeLogMessage(message) {
79
- if (typeof message === "string") {
80
- return message;
81
- }
82
- if (message instanceof Error) {
83
- return message.message || message.name;
84
- }
85
- const normalized = normalizeLogValue(message);
86
- if (typeof normalized === "string") {
87
- return normalized;
88
- }
89
- try {
90
- const serialized = JSON.stringify(normalized, null, 2);
91
- return serialized ?? String(normalized);
92
- } catch {
93
- return String(normalized);
94
- }
95
- }
96
- var absoluteHttpUrlSchema = zod.z.string().url().refine((value) => {
97
- try {
98
- const url = new URL(value);
99
- return url.protocol === "http:" || url.protocol === "https:";
100
- } catch {
101
- return false;
102
- }
103
- }, {
104
- message: "Expected an absolute http(s) URL"
105
- });
106
- var plainObjectSchema = zod.z.custom(
107
- (value) => {
108
- return value !== null && typeof value === "object" && !Array.isArray(value);
109
- },
110
- {
111
- message: "Expected a plain object"
112
- }
113
- );
114
- var nonEmptyStringSchema = zod.z.string().trim().min(1);
115
- function isAbsoluteHttpUrl(value) {
116
- return absoluteHttpUrlSchema.safeParse(value).success;
117
- }
118
- function isPlainObject(value) {
119
- return plainObjectSchema.safeParse(value).success;
120
- }
121
- function hasNonEmptyString(value) {
122
- return nonEmptyStringSchema.safeParse(value).success;
123
- }
124
-
125
- // src/shared/client-log.ts
126
- var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
127
- zod.z.union([
128
- zod.z.literal("betterstack"),
129
- zod.z.literal("databuddy"),
130
- zod.z.literal("posthog"),
131
- zod.z.literal("sentry"),
132
- zod.z.undefined(),
133
- zod.z.object({
134
- type: zod.z.literal("otlp"),
135
- name: nonEmptyStringSchema
136
- })
137
- ]);
138
-
139
- // src/shared/once.ts
140
- function createConsoleOnceLogger(method, warnedKeys3 = /* @__PURE__ */ new Set()) {
141
- return (key, message, error) => {
142
- if (warnedKeys3.has(key) || typeof console === "undefined") {
143
- return;
144
- }
145
- const writer = console[method];
146
- if (typeof writer !== "function") {
147
- return;
148
- }
149
- warnedKeys3.add(key);
150
- if (error === void 0) {
151
- writer.call(console, message);
152
- return;
153
- }
154
- writer.call(console, message, error);
155
- };
156
- }
157
- function createWarnOnceLogger(warnedKeys3) {
158
- return createConsoleOnceLogger("warn", warnedKeys3);
159
- }
160
- function createErrorOnceLogger(warnedKeys3) {
161
- return createConsoleOnceLogger("error", warnedKeys3);
162
- }
163
-
164
- // src/core/config.ts
165
- var PACKAGE_NAME = "@blyp/core";
166
- var GITIGNORE_FILE_NAME = ".gitignore";
167
- var CONFIG_FILE_NAMES = [
168
- "blyp.config.ts",
169
- "blyp.config.mts",
170
- "blyp.config.cts",
171
- "blyp.config.js",
172
- "blyp.config.mjs",
173
- "blyp.config.cjs",
174
- "blyp.config.json"
175
- ];
176
- var CONFIG_FILE_NAME = "blyp.config.json";
177
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
178
- var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
179
- var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
180
- var warnedKeys = /* @__PURE__ */ new Set();
181
- var warnOnce = createWarnOnceLogger(warnedKeys);
182
- var DEFAULT_ROTATION_CONFIG = {
183
- enabled: true,
184
- maxSizeBytes: 10 * 1024 * 1024,
185
- maxArchives: 5,
186
- compress: true
187
- };
188
- var DEFAULT_FILE_CONFIG = {
189
- enabled: true,
190
- dir: "",
191
- archiveDir: "",
192
- format: "ndjson",
193
- rotation: DEFAULT_ROTATION_CONFIG
194
- };
195
- var DEFAULT_CLIENT_LOGGING_CONFIG = {
196
- enabled: true,
197
- path: DEFAULT_CLIENT_LOG_ENDPOINT
198
- };
199
- var DEFAULT_DATABASE_RETRY_CONFIG = {
200
- maxRetries: 1,
201
- backoffMs: 100
202
- };
203
- var DEFAULT_DATABASE_DELIVERY_CONFIG = {
204
- strategy: "immediate",
205
- batchSize: 1,
206
- flushIntervalMs: 250,
207
- maxQueueSize: 1e3,
208
- overflowStrategy: "drop-oldest",
209
- flushTimeoutMs: 5e3,
210
- retry: DEFAULT_DATABASE_RETRY_CONFIG
211
- };
212
- var DEFAULT_CONFIG = {
213
- pretty: true,
214
- level: "info",
215
- destination: "file",
216
- file: DEFAULT_FILE_CONFIG,
217
- clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
218
- connectors: {}
219
- };
220
- var cachedConfig = null;
221
- function findNearestPackageName(startDir) {
222
- let currentDir = startDir;
223
- while (true) {
224
- const packageJsonPath = path.resolve(currentDir, "package.json");
225
- if (fs.existsSync(packageJsonPath)) {
226
- try {
227
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
228
- if (hasNonEmptyString(packageJson.name)) {
229
- return packageJson.name;
230
- }
231
- } catch {
232
- }
233
- }
234
- const parentDir = path.dirname(currentDir);
235
- if (parentDir === currentDir) {
236
- return void 0;
237
- }
238
- currentDir = parentDir;
239
- }
240
- }
241
- function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
242
- return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
243
- }
244
- function getBootstrapConfig() {
245
- return {
246
- pretty: true,
247
- level: "info",
248
- destination: "file",
249
- file: {
250
- enabled: true,
251
- format: "ndjson",
252
- rotation: {
253
- enabled: true,
254
- maxSizeBytes: 10 * 1024 * 1024,
255
- maxArchives: 5,
256
- compress: true
257
- }
258
- },
259
- clientLogging: {
260
- enabled: true,
261
- path: DEFAULT_CLIENT_LOG_ENDPOINT
262
- },
263
- connectors: {}
264
- };
265
- }
266
- function shouldBootstrapProjectFiles(cwd) {
267
- const packageJsonPath = path.resolve(cwd, "package.json");
268
- if (!fs.existsSync(packageJsonPath)) {
269
- return true;
270
- }
271
- try {
272
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
273
- return packageJson.name !== PACKAGE_NAME;
274
- } catch {
275
- return true;
276
- }
277
- }
278
- function ensureConfigFile(cwd) {
279
- if (CONFIG_FILE_NAMES.some((fileName) => fs.existsSync(path.resolve(cwd, fileName)))) {
280
- return;
281
- }
282
- const configPath = path.resolve(cwd, CONFIG_FILE_NAME);
283
- if (fs.existsSync(configPath)) {
284
- return;
285
- }
286
- try {
287
- fs.writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
288
- `);
289
- } catch (error) {
290
- console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
291
- }
292
- }
293
- function ensureLogsIgnored(cwd) {
294
- const gitignorePath = path.resolve(cwd, GITIGNORE_FILE_NAME);
295
- if (!fs.existsSync(gitignorePath)) {
296
- try {
297
- fs.writeFileSync(gitignorePath, "logs\n");
298
- } catch (error) {
299
- console.error("[Blyp] Warning: Failed to create .gitignore:", error);
300
- }
301
- return;
302
- }
303
- try {
304
- const currentContent = fs.readFileSync(gitignorePath, "utf-8");
305
- if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
306
- return;
307
- }
308
- const separator = currentContent.endsWith("\n") ? "" : "\n";
309
- fs.appendFileSync(gitignorePath, `${separator}logs
310
- `);
311
- } catch (error) {
312
- console.error("[Blyp] Warning: Failed to update .gitignore:", error);
313
- }
314
- }
315
- function bootstrapProjectFiles() {
316
- const cwd = process.cwd();
317
- if (!shouldBootstrapProjectFiles(cwd)) {
318
- return;
319
- }
320
- ensureConfigFile(cwd);
321
- ensureLogsIgnored(cwd);
322
- }
323
- function findConfigFile() {
324
- const cwd = process.cwd();
325
- const matches = CONFIG_FILE_NAMES.map((fileName) => path.resolve(cwd, fileName)).filter((filePath) => fs.existsSync(filePath));
326
- if (matches.length === 0) {
327
- return null;
328
- }
329
- if (matches.length > 1) {
330
- const preferred = matches[0];
331
- warnOnce(
332
- `config-multiple:${preferred}`,
333
- `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
334
- );
335
- }
336
- const selectedPath = matches[0];
337
- return {
338
- path: selectedPath,
339
- type: selectedPath.endsWith(".json") ? "json" : "jiti"
340
- };
341
- }
342
- function normalizeLoadedConfig(value, configPath) {
343
- const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
344
- if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
345
- warnOnce(
346
- `config-invalid:${configPath}`,
347
- `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
348
- );
349
- return {};
350
- }
351
- return normalized;
352
- }
353
- function parseJsonConfigFile(configPath) {
354
- try {
355
- const content = fs.readFileSync(configPath, "utf-8");
356
- return normalizeLoadedConfig(JSON.parse(content), configPath);
357
- } catch (error) {
358
- console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
359
- return {};
360
- }
361
- }
362
- function parseExecutableConfigFile(configPath) {
363
- try {
364
- const jiti$1 = jiti.createJiti(process.cwd(), {
365
- interopDefault: true,
366
- moduleCache: false,
367
- fsCache: false
368
- });
369
- return normalizeLoadedConfig(jiti$1(configPath), configPath);
370
- } catch (error) {
371
- console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
372
- return {};
373
- }
374
- }
375
- function parseConfigFile(config) {
376
- return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
377
- }
378
- function isPrismaAdapter(value) {
379
- return !!value && typeof value === "object" && value.type === "prisma";
380
- }
381
- function isDrizzleAdapter(value) {
382
- return !!value && typeof value === "object" && value.type === "drizzle";
383
- }
384
- function mergeDatabaseRetryConfig(base, override) {
385
- return {
386
- ...DEFAULT_DATABASE_RETRY_CONFIG,
387
- ...base,
388
- ...override
389
- };
390
- }
391
- function mergeDatabaseDeliveryConfig(base, override) {
392
- return {
393
- ...DEFAULT_DATABASE_DELIVERY_CONFIG,
394
- ...base,
395
- ...override,
396
- retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
397
- };
398
- }
399
- function hasPrismaDelegate(adapter) {
400
- const model = adapter.model ?? "blypLog";
401
- const client = adapter.client;
402
- const delegate = client?.[model];
403
- return !!delegate && typeof delegate.create === "function";
404
- }
405
- function hasDrizzleAdapterShape(adapter) {
406
- const db = adapter.db;
407
- return !!db && typeof db.insert === "function" && adapter.table !== void 0;
408
- }
409
- function resolveDatabaseLoggerConfig(config, sourceType) {
410
- if (!config) {
411
- return void 0;
412
- }
413
- const adapter = config.adapter;
414
- let ready = false;
415
- if (sourceType === "json") {
416
- warnOnce(
417
- "database-json-config",
418
- "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
419
- );
420
- } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
421
- warnOnce(
422
- `database-dialect:${String(config.dialect)}`,
423
- `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
424
- );
425
- } else if (!adapter) {
426
- warnOnce(
427
- "database-adapter-missing",
428
- "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
429
- );
430
- } else if (isPrismaAdapter(adapter)) {
431
- ready = hasPrismaDelegate({
432
- ...adapter,
433
- model: adapter.model ?? "blypLog"
434
- });
435
- if (!ready) {
436
- warnOnce(
437
- "database-prisma-missing",
438
- `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
439
- );
440
- }
441
- } else if (isDrizzleAdapter(adapter)) {
442
- ready = hasDrizzleAdapterShape(adapter);
443
- if (!ready) {
444
- warnOnce(
445
- "database-drizzle-missing",
446
- "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
447
- );
448
- }
449
- }
450
- const normalizedAdapter = isPrismaAdapter(adapter) ? {
451
- ...adapter,
452
- model: adapter.model ?? "blypLog"
453
- } : adapter;
454
- return {
455
- dialect: config.dialect,
456
- adapter: normalizedAdapter,
457
- delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
458
- ready,
459
- status: ready ? "enabled" : "missing"
460
- };
461
- }
462
- function mergeRotationConfig(base, override) {
463
- return {
464
- ...DEFAULT_ROTATION_CONFIG,
465
- ...base,
466
- ...override
467
- };
468
- }
469
- function mergeFileConfig(base, override) {
470
- return {
471
- ...DEFAULT_FILE_CONFIG,
472
- ...base,
473
- ...override,
474
- rotation: mergeRotationConfig(base?.rotation, override?.rotation)
475
- };
476
- }
477
- function mergeClientLoggingConfig(base, override) {
478
- return {
479
- ...DEFAULT_CLIENT_LOGGING_CONFIG,
480
- ...base,
481
- ...override,
482
- path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
483
- };
484
- }
485
- function mergeDatabaseLoggerConfig(base, override, sourceType) {
486
- if (!base && !override) {
487
- return void 0;
488
- }
489
- return resolveDatabaseLoggerConfig(
490
- {
491
- dialect: override?.dialect ?? base?.dialect,
492
- adapter: override?.adapter ?? base?.adapter,
493
- delivery: {
494
- ...base?.delivery ?? {},
495
- ...override?.delivery ?? {},
496
- retry: {
497
- ...base?.delivery?.retry ?? {},
498
- ...override?.delivery?.retry ?? {}
499
- }
500
- }
501
- },
502
- sourceType
503
- );
504
- }
505
- function mergePostHogConnectorConfig(base, override) {
506
- const enabled = override?.enabled ?? base?.enabled ?? false;
507
- const projectKey = override?.projectKey ?? base?.projectKey;
508
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
509
- const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
510
- const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
511
- const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
512
- return {
513
- enabled,
514
- mode: override?.mode ?? base?.mode ?? "auto",
515
- projectKey,
516
- host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
517
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
518
- errorTracking: {
519
- enabled: errorTrackingEnabled,
520
- mode: errorTrackingMode,
521
- enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
522
- ready: errorTrackingReady,
523
- status: errorTrackingReady ? "enabled" : "missing"
524
- }
525
- };
526
- }
527
- function mergeDatabuddyConnectorConfig(base, override) {
528
- const enabled = override?.enabled ?? base?.enabled ?? false;
529
- const apiKey = override?.apiKey ?? base?.apiKey;
530
- const websiteId = override?.websiteId ?? base?.websiteId;
531
- const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
532
- return {
533
- enabled,
534
- mode: override?.mode ?? base?.mode ?? "auto",
535
- apiKey,
536
- websiteId,
537
- namespace: override?.namespace ?? base?.namespace,
538
- source: override?.source ?? base?.source,
539
- apiUrl: override?.apiUrl ?? base?.apiUrl,
540
- debug: override?.debug ?? base?.debug ?? false,
541
- enableBatching: override?.enableBatching ?? base?.enableBatching ?? true,
542
- batchSize: override?.batchSize ?? base?.batchSize,
543
- batchTimeout: override?.batchTimeout ?? base?.batchTimeout,
544
- maxQueueSize: override?.maxQueueSize ?? base?.maxQueueSize,
545
- ready,
546
- status: ready ? "enabled" : "missing"
547
- };
548
- }
549
- function mergeBetterStackConnectorConfig(base, override) {
550
- const sourceToken = override?.sourceToken ?? base?.sourceToken;
551
- const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
552
- const enabled = override?.enabled ?? base?.enabled ?? false;
553
- const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
554
- const errorTracking = mergeBetterStackErrorTrackingConfig(
555
- enabled,
556
- baseErrorTracking,
557
- override?.errorTracking
558
- );
559
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
560
- return {
561
- enabled,
562
- mode: override?.mode ?? base?.mode ?? "auto",
563
- sourceToken,
564
- ingestingHost,
565
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
566
- errorTracking,
567
- ready,
568
- status: ready ? "enabled" : "missing"
569
- };
570
- }
571
- function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
572
- const dsn = override?.dsn ?? base?.dsn;
573
- const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
574
- const ready = enabled && hasNonEmptyString(dsn);
575
- return {
576
- enabled,
577
- dsn,
578
- tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
579
- environment: override?.environment ?? base?.environment,
580
- release: override?.release ?? base?.release,
581
- ready,
582
- status: ready ? "enabled" : "missing"
583
- };
584
- }
585
- function mergeSentryConnectorConfig(base, override) {
586
- const dsn = override?.dsn ?? base?.dsn;
587
- const enabled = override?.enabled ?? base?.enabled ?? false;
588
- const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
589
- return {
590
- enabled,
591
- mode: override?.mode ?? base?.mode ?? "auto",
592
- dsn,
593
- environment: override?.environment ?? base?.environment,
594
- release: override?.release ?? base?.release,
595
- ready,
596
- status: ready ? "enabled" : "missing"
597
- };
598
- }
599
- function mergeOTLPConnectorConfig(base, override) {
600
- const endpoint = override?.endpoint ?? base?.endpoint;
601
- const enabled = override?.enabled ?? base?.enabled ?? false;
602
- const resolvedHeaders = {
603
- ...{},
604
- ...override?.headers ?? {}
605
- };
606
- const ready = enabled && isAbsoluteHttpUrl(endpoint);
607
- return {
608
- name: override?.name ?? base?.name ?? "",
609
- enabled,
610
- mode: override?.mode ?? base?.mode ?? "auto",
611
- endpoint,
612
- headers: resolvedHeaders,
613
- auth: override?.auth ?? base?.auth,
614
- serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
615
- ready,
616
- status: ready ? "enabled" : "missing"
617
- };
618
- }
619
- function mergeOTLPConnectorsConfig(base, override) {
620
- const source = override ?? base ?? [];
621
- const deduped = /* @__PURE__ */ new Map();
622
- for (const connector of source) {
623
- if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
624
- continue;
625
- }
626
- if (deduped.has(connector.name)) {
627
- warnOnce(
628
- `otlp-duplicate:${connector.name}`,
629
- `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
630
- );
631
- }
632
- deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
633
- }
634
- return Array.from(deduped.values());
635
- }
636
- function mergeConnectorsConfig(base, override) {
637
- return {
638
- betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
639
- databuddy: mergeDatabuddyConnectorConfig(base?.databuddy, override?.databuddy),
640
- posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
641
- sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
642
- otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
643
- };
644
- }
645
- function mergeBlypConfig(base, override = {}, options = {}) {
646
- return {
647
- ...base,
648
- ...override,
649
- destination: override.destination ?? base.destination ?? "file",
650
- file: mergeFileConfig(base.file, override.file),
651
- database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
652
- clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
653
- connectors: mergeConnectorsConfig(base.connectors, override.connectors)
654
- };
655
- }
656
- function loadConfig() {
657
- if (cachedConfig !== null) {
658
- return cachedConfig;
659
- }
660
- bootstrapProjectFiles();
661
- const configFile = findConfigFile();
662
- if (configFile) {
663
- const userConfig = parseConfigFile(configFile);
664
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
665
- configFileType: configFile.type
666
- });
667
- } else {
668
- cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
669
- }
670
- return cachedConfig;
671
- }
672
- function resolveConfig(overrides = {}) {
673
- return mergeBlypConfig(loadConfig(), overrides);
674
- }
675
-
676
- // src/core/log-record.ts
677
- var RECORD_LEVELS = {
678
- success: "success",
679
- critical: "critical",
680
- warning: "warning",
681
- info: "info",
682
- debug: "debug",
683
- error: "error",
684
- warn: "warning",
685
- table: "table"
686
- };
687
- function normalizePath(filePath) {
688
- return filePath.replace(/\\/g, "/");
689
- }
690
- function isInternalLoggerFrame(filePath) {
691
- const normalizedPath = normalizePath(filePath);
692
- 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/");
693
- }
694
- function formatCallerPath(filePath) {
695
- const normalizedPath = normalizePath(filePath);
696
- const normalizedCwd = normalizePath(process.cwd());
697
- return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
698
- }
699
- function getCallerLocation() {
700
- try {
701
- const stack = new Error().stack;
702
- if (!stack) {
703
- return { file: null, line: null };
704
- }
705
- const lines = stack.split("\n");
706
- let fallback = null;
707
- for (let index = 2; index < lines.length; index += 1) {
708
- const line = lines[index];
709
- if (!line) {
710
- continue;
711
- }
712
- const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
713
- if (!match) {
714
- continue;
715
- }
716
- const fileName = match[1] || "";
717
- const lineNumber = parseInt(match[2] || "0", 10) || null;
718
- if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
719
- const formattedPath = formatCallerPath(fileName);
720
- const normalizedFormattedPath = normalizePath(formattedPath);
721
- if (!normalizedFormattedPath.startsWith("dist/")) {
722
- return { file: formattedPath, line: lineNumber };
723
- }
724
- fallback ?? (fallback = { file: formattedPath, line: lineNumber });
725
- }
726
- }
727
- if (fallback) {
728
- return fallback;
729
- }
730
- } catch {
731
- return { file: null, line: null };
732
- }
733
- return { file: null, line: null };
734
- }
735
- var serializeMessage = serializeLogMessage;
736
- function stripAnsi(value) {
737
- return value.replace(/\u001b\[[0-9;]*m/g, "");
738
- }
739
- function buildRecord(level, message, args, bindings) {
740
- const { file, line } = getCallerLocation();
741
- const serializedMessage = serializeMessage(message);
742
- const record = {
743
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
744
- level: RECORD_LEVELS[level],
745
- message: stripAnsi(serializedMessage)
746
- };
747
- if (message instanceof Error) {
748
- record.error = normalizeError(message);
749
- }
750
- if (file) {
751
- record.caller = line !== null ? `${file}:${line}` : file;
752
- }
753
- if (args.length === 1) {
754
- record.data = normalizeLogValue(args[0]);
755
- } else if (args.length > 1) {
756
- record.data = normalizeLogValue(args);
757
- }
758
- if (Object.keys(bindings).length > 0) {
759
- record.bindings = normalizeLogValue(bindings);
760
- }
761
- return record;
762
- }
763
- function buildStructuredRecord(level, message, payload, bindings) {
764
- const { file, line } = getCallerLocation();
765
- const normalizedPayload = normalizeLogValue(payload);
766
- const record = {
767
- message: stripAnsi(message),
768
- ...normalizedPayload
769
- };
770
- if (file) {
771
- record.caller = line !== null ? `${file}:${line}` : file;
772
- }
773
- if (Object.keys(bindings).length > 0) {
774
- record.bindings = normalizeLogValue(bindings);
775
- }
776
- record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
777
- record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
778
- return record;
779
- }
780
- function resolveStructuredWriteLevel(level) {
781
- switch (level) {
782
- case "debug":
783
- return "debug";
784
- case "warning":
785
- return "warning";
786
- case "warn":
787
- return "warn";
788
- case "error":
789
- return "error";
790
- case "success":
791
- return "success";
792
- case "critical":
793
- return "critical";
794
- case "table":
795
- return "table";
796
- case "info":
797
- default:
798
- return "info";
799
- }
800
- }
801
-
802
- // src/core/structured-log.ts
803
- function serializeMessage2(message) {
804
- if (typeof message === "string") {
805
- return message;
806
- }
807
- if (message !== null && typeof message === "object") {
808
- try {
809
- return JSON.stringify(
810
- message,
811
- (_key, value) => {
812
- if (typeof value === "function") {
813
- return `[Function: ${value.name || "anonymous"}]`;
814
- }
815
- if (value === void 0) {
816
- return "[undefined]";
817
- }
818
- if (typeof value === "symbol") {
819
- return value.toString();
820
- }
821
- return value;
822
- },
823
- 2
824
- );
825
- } catch {
826
- return "[Object]";
827
- }
828
- }
829
- return String(message);
830
- }
831
- function normalizeEventData(message, args) {
832
- if (typeof message === "string") {
833
- if (args.length === 0) {
834
- return void 0;
835
- }
836
- return args.length === 1 ? args[0] : args;
837
- }
838
- const values = [message, ...args];
839
- return values.length === 1 ? values[0] : values;
840
- }
841
- function normalizeDetails(value) {
842
- if (!value || typeof value !== "object" || Array.isArray(value)) {
843
- return void 0;
844
- }
845
- return value;
846
- }
847
- function normalizeError2(error, fallbackStatus) {
848
- if (error === void 0 || error === null) {
849
- return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
850
- message: `HTTP ${fallbackStatus}`,
851
- code: fallbackStatus,
852
- type: "HttpError"
853
- };
854
- }
855
- if (error instanceof Error) {
856
- const errorLike = error;
857
- return {
858
- message: error.message,
859
- code: errorLike.code,
860
- type: errorLike.type ?? error.name ?? error.constructor?.name,
861
- stack: error.stack,
862
- why: errorLike.why,
863
- fix: errorLike.fix,
864
- link: errorLike.link,
865
- details: normalizeDetails(errorLike.details),
866
- cause: errorLike.cause
867
- };
868
- }
869
- if (typeof error === "object") {
870
- const record = error;
871
- const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
872
- return {
873
- message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
874
- code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
875
- type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
876
- stack: typeof record.stack === "string" ? record.stack : void 0,
877
- why: typeof record.why === "string" ? record.why : void 0,
878
- fix: typeof record.fix === "string" ? record.fix : void 0,
879
- link: typeof record.link === "string" ? record.link : void 0,
880
- details: normalizeDetails(record.details),
881
- cause: record.cause
882
- };
883
- }
884
- return {
885
- message: String(error),
886
- code: fallbackStatus,
887
- type: typeof error
888
- };
889
- }
890
- function resolveEmitStatus(options) {
891
- if (options.response && typeof options.response.status === "number") {
892
- return options.response.status;
893
- }
894
- if (typeof options.status === "number") {
895
- return options.status;
896
- }
897
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
898
- return options.error.statusCode;
899
- }
900
- if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
901
- return options.error.status;
902
- }
903
- return options.error ? 500 : void 0;
904
- }
905
- function createStructuredLog(groupId, options) {
906
- const startedAt = performance.now();
907
- const fields = { ...options.initialFields ?? {} };
908
- const events = [];
909
- let emittedPayload;
910
- options.onCreate?.();
911
- const appendEvent = (level, message, args) => {
912
- events.push({
913
- level,
914
- message: serializeMessage2(message),
915
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
916
- ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
917
- });
918
- return structuredLog;
919
- };
920
- const structuredLog = {
921
- set(extraFields) {
922
- Object.assign(fields, extraFields);
923
- return structuredLog;
924
- },
925
- debug(message, ...args) {
926
- return appendEvent("debug", message, args);
927
- },
928
- info(message, ...args) {
929
- return appendEvent("info", message, args);
930
- },
931
- warn(message, ...args) {
932
- return appendEvent("warn", message, args);
933
- },
934
- warning(message, ...args) {
935
- return appendEvent("warning", message, args);
936
- },
937
- error(message, ...args) {
938
- return appendEvent("error", message, args);
939
- },
940
- success(message, ...args) {
941
- return appendEvent("success", message, args);
942
- },
943
- critical(message, ...args) {
944
- return appendEvent("critical", message, args);
945
- },
946
- table(message, data) {
947
- return appendEvent("table", message, data === void 0 ? [] : [data]);
948
- },
949
- emit(emitOptions = {}) {
950
- if (emittedPayload) {
951
- return emittedPayload;
952
- }
953
- const defaultFields = options.resolveDefaultFields?.() ?? {};
954
- const status = resolveEmitStatus(emitOptions);
955
- const error = normalizeError2(emitOptions.error, status);
956
- const level = emitOptions.level ?? (error ? "error" : "info");
957
- const payload = {
958
- ...defaultFields,
959
- ...fields,
960
- groupId,
961
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
962
- level,
963
- duration: Math.round(performance.now() - startedAt),
964
- ...typeof status === "number" ? { status } : {},
965
- ...events.length > 0 ? { events: [...events] } : {},
966
- ...error ? { error } : {}
967
- };
968
- options.write(payload, emitOptions.message ?? "structured_log");
969
- emittedPayload = payload;
970
- options.onEmit?.(payload);
971
- return payload;
972
- }
973
- };
974
- return structuredLog;
975
- }
976
- function createSafeReplacer() {
977
- const seen = /* @__PURE__ */ new WeakSet();
978
- return (_key, value) => {
979
- if (typeof value === "function") {
980
- return `[Function: ${value.name || "anonymous"}]`;
981
- }
982
- if (value === void 0) {
983
- return "[undefined]";
984
- }
985
- if (typeof value === "symbol") {
986
- return value.toString();
987
- }
988
- if (value !== null && typeof value === "object") {
989
- if (seen.has(value)) {
990
- return "[Circular]";
991
- }
992
- seen.add(value);
993
- }
994
- return value;
995
- };
996
- }
997
- function serializeLogRecord(record) {
998
- return JSON.stringify(record, createSafeReplacer());
999
- }
1000
-
1001
- // src/connectors/shared.ts
1002
- function isBlypConfig(config) {
1003
- return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
1004
- }
1005
- function getPrimaryPayload(record) {
1006
- return isPlainObject(record.data) ? record.data : record;
1007
- }
1008
- function getField(record, key) {
1009
- if (key in record) {
1010
- const direct = record[key];
1011
- if (typeof direct === "string" || typeof direct === "number") {
1012
- return direct;
1013
- }
1014
- }
1015
- const payload = getPrimaryPayload(record);
1016
- const nested = payload[key];
1017
- if (typeof nested === "string" || typeof nested === "number") {
1018
- return nested;
1019
- }
1020
- return void 0;
1021
- }
1022
- function getClientPageField(record, key) {
1023
- const payload = getPrimaryPayload(record);
1024
- const page = isPlainObject(payload.page) ? payload.page : void 0;
1025
- const value = page?.[key];
1026
- return typeof value === "string" ? value : void 0;
1027
- }
1028
- function getClientSessionField(record, key) {
1029
- const payload = getPrimaryPayload(record);
1030
- const session = isPlainObject(payload.session) ? payload.session : void 0;
1031
- const value = session?.[key];
1032
- return typeof value === "string" ? value : void 0;
1033
- }
1034
- function getRecordType(record) {
1035
- return getField(record, "type");
1036
- }
1037
-
1038
- // src/connectors/betterstack/sender.ts
1039
- var PREVIOUSLY_CAPTURED_ERROR_KEY = "__betterstack_previously_captured_error";
1040
- var warnedKeys2 = /* @__PURE__ */ new Set();
1041
- var testHooks = {};
1042
- var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1043
- function getSentryModule() {
1044
- return testHooks.module ?? Sentry__namespace;
1045
- }
1046
- function resolveConnectorConfig(config) {
1047
- const connector = isBlypConfig(config) ? config.connectors?.betterstack : config;
1048
- const enabled = connector?.enabled ?? false;
1049
- const sourceToken = connector?.sourceToken;
1050
- const ingestingHost = connector?.ingestingHost;
1051
- const errorTrackingEnabled = connector?.errorTracking?.enabled ?? enabled;
1052
- const errorTrackingDsn = connector?.errorTracking?.dsn;
1053
- const errorTrackingReady = enabled && errorTrackingEnabled && hasNonEmptyString(errorTrackingDsn);
1054
- const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
1055
- return {
1056
- enabled,
1057
- mode: connector?.mode ?? "auto",
1058
- sourceToken,
1059
- ingestingHost,
1060
- serviceName: connector?.serviceName ?? "blyp-app",
1061
- errorTracking: {
1062
- enabled: errorTrackingEnabled,
1063
- dsn: errorTrackingDsn,
1064
- tracesSampleRate: connector?.errorTracking?.tracesSampleRate ?? 1,
1065
- environment: connector?.errorTracking?.environment,
1066
- release: connector?.errorTracking?.release,
1067
- ready: errorTrackingReady,
1068
- status: errorTrackingReady ? "enabled" : "missing"
1069
- },
1070
- ready,
1071
- status: ready ? "enabled" : "missing"
1072
- };
1073
- }
1074
- function resolveBetterStackLevel(level) {
1075
- switch (level) {
1076
- case "debug":
1077
- return "debug";
1078
- case "warning":
1079
- case "warn":
1080
- return "warn";
1081
- case "error":
1082
- return "error";
1083
- case "critical":
1084
- return "fatal";
1085
- case "success":
1086
- case "table":
1087
- case "info":
1088
- default:
1089
- return "info";
1090
- }
1091
- }
1092
- function parseCaller(caller) {
1093
- if (typeof caller !== "string" || caller.trim().length === 0) {
1094
- return {};
1095
- }
1096
- const match = caller.match(/^(.*):(\d+)$/);
1097
- if (!match) {
1098
- return {};
1099
- }
1100
- const file = match[1]?.trim();
1101
- const line = Number.parseInt(match[2] ?? "", 10);
1102
- return {
1103
- ...file ? { file } : {},
1104
- ...Number.isFinite(line) ? { line } : {}
1105
- };
1106
- }
1107
- function buildContext(record, connector, source) {
1108
- const recordType = getRecordType(record);
1109
- const groupId = getField(record, "groupId");
1110
- const method = getField(record, "method");
1111
- const path = getField(record, "path");
1112
- const status = getField(record, "status");
1113
- const duration = getField(record, "duration");
1114
- const pagePath = getClientPageField(record, "pathname");
1115
- const pageUrl = getClientPageField(record, "url");
1116
- const sessionId = getClientSessionField(record, "sessionId");
1117
- const pageId = getClientSessionField(record, "pageId");
1118
- const runtime = parseCaller(record.caller);
1119
- return {
1120
- service: connector.serviceName,
1121
- context: {
1122
- blyp: {
1123
- level: record.level,
1124
- source,
1125
- ...recordType ? { type: recordType } : {},
1126
- ...groupId ? { group_id: groupId } : {},
1127
- ...record.caller ? { caller: record.caller } : {},
1128
- ...duration !== void 0 ? { duration_ms: duration } : {},
1129
- ...record.bindings ? { bindings: record.bindings } : {},
1130
- payload: serializeLogRecord(record)
1131
- },
1132
- ...method || path || status !== void 0 ? {
1133
- http: {
1134
- ...method ? { method } : {},
1135
- ...path ? { path } : {},
1136
- ...status !== void 0 ? { status_code: status } : {}
1137
- }
1138
- } : {},
1139
- ...pagePath || pageUrl || sessionId || pageId ? {
1140
- client: {
1141
- ...pagePath ? { page_path: pagePath } : {},
1142
- ...pageUrl ? { page_url: pageUrl } : {},
1143
- ...sessionId ? { session_id: sessionId } : {},
1144
- ...pageId ? { page_id: pageId } : {}
1145
- }
1146
- } : {},
1147
- ...Object.keys(runtime).length > 0 ? { runtime } : {},
1148
- ...record.data !== void 0 ? { data: record.data } : {},
1149
- ...record.error !== void 0 ? { error: record.error } : {}
1150
- }
1151
- };
1152
- }
1153
- function toExceptionCandidate(value) {
1154
- if (!isPlainObject(value)) {
1155
- return void 0;
1156
- }
1157
- const message = typeof value.message === "string" ? value.message : void 0;
1158
- const name = typeof value.name === "string" ? value.name : void 0;
1159
- const stack = typeof value.stack === "string" ? value.stack : void 0;
1160
- if (!message && !name && !stack) {
1161
- return void 0;
1162
- }
1163
- const error = new Error(message ?? name ?? "Unknown error");
1164
- error.name = name ?? "Error";
1165
- if (stack) {
1166
- error.stack = stack;
1167
- }
1168
- for (const [key, entry] of Object.entries(value)) {
1169
- if (key === "message" || key === "name" || key === "stack") {
1170
- continue;
1171
- }
1172
- error[key] = entry;
1173
- }
1174
- return error;
1175
- }
1176
- function normalizeScopeLevel(level) {
1177
- switch (level) {
1178
- case "debug":
1179
- return "debug";
1180
- case "warning":
1181
- case "warn":
1182
- return "warning";
1183
- case "critical":
1184
- return "fatal";
1185
- case "error":
1186
- return "error";
1187
- case "success":
1188
- case "table":
1189
- case "info":
1190
- default:
1191
- return "info";
1192
- }
1193
- }
1194
- function normalizeExceptionInput(input) {
1195
- if (input instanceof Error) {
1196
- return input;
1197
- }
1198
- const direct = toExceptionCandidate(input);
1199
- if (direct) {
1200
- return direct;
1201
- }
1202
- if (typeof input === "string") {
1203
- return new Error(input);
1204
- }
1205
- return new Error("Unknown Better Stack exception");
1206
- }
1207
- function isPreviouslyCapturedError(value) {
1208
- return isPlainObject(value) && value[PREVIOUSLY_CAPTURED_ERROR_KEY] === true;
1209
- }
1210
- function markCapturedError(value) {
1211
- if (!isPlainObject(value) || isPreviouslyCapturedError(value)) {
1212
- return;
1213
- }
1214
- try {
1215
- Object.defineProperty(value, PREVIOUSLY_CAPTURED_ERROR_KEY, {
1216
- value: true,
1217
- enumerable: false,
1218
- configurable: true,
1219
- writable: true
1220
- });
1221
- } catch {
1222
- try {
1223
- value[PREVIOUSLY_CAPTURED_ERROR_KEY] = true;
1224
- } catch {
1225
- }
1226
- }
1227
- }
1228
- function createDefaultClient(connector) {
1229
- return new node.Logtail(connector.sourceToken ?? "", {
1230
- endpoint: connector.ingestingHost,
1231
- captureStackContext: false
1232
- });
1233
- }
1234
- function getClientOptions(client) {
1235
- return client?.getOptions?.() ?? {};
1236
- }
1237
- function registerShutdownHooks(key, flush) {
1238
- const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1239
- for (const event of handlers) {
1240
- process.once(event, () => {
1241
- void flush().catch((error) => {
1242
- warnOnce2(
1243
- `${key}:shutdown`,
1244
- "[Blyp] Failed to flush Better Stack logs during shutdown.",
1245
- error
1246
- );
1247
- });
1248
- });
1249
- }
1250
- }
1251
- function createBetterStackSender(config) {
1252
- const connector = resolveConnectorConfig(config);
1253
- const key = `${connector.serviceName}:${connector.ingestingHost ?? "missing"}:${connector.mode}`;
1254
- const sentryModule = getSentryModule();
1255
- const client = connector.ready ? testHooks.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
1256
- let sentryClient = connector.errorTracking.enabled ? sentryModule?.getClient?.() : void 0;
1257
- if (sentryClient) {
1258
- const options = getClientOptions(sentryClient);
1259
- 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) {
1260
- warnOnce2(
1261
- `betterstack-error-mismatch:${key}`,
1262
- "[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking."
1263
- );
1264
- }
1265
- }
1266
- if (!sentryClient && connector.errorTracking.enabled && hasNonEmptyString(connector.errorTracking.dsn) && sentryModule) {
1267
- try {
1268
- sentryModule.init({
1269
- dsn: connector.errorTracking.dsn,
1270
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
1271
- environment: connector.errorTracking.environment,
1272
- release: connector.errorTracking.release
1273
- });
1274
- sentryClient = sentryModule.getClient();
1275
- } catch (error) {
1276
- warnOnce2(
1277
- `betterstack-error-init:${key}`,
1278
- "[Blyp] Failed to initialize Better Stack error tracking.",
1279
- error
1280
- );
1281
- }
1282
- }
1283
- const errorTrackingReady = connector.errorTracking.enabled && sentryClient !== void 0;
1284
- if (client || errorTrackingReady) {
1285
- registerShutdownHooks(key, async () => {
1286
- if (client) {
1287
- await client.flush();
1288
- }
1289
- if (errorTrackingReady) {
1290
- await sentryModule.flush(2e3);
1291
- }
1292
- });
1293
- }
1294
- const emitUnavailableWarning = () => {
1295
- warnOnce2(
1296
- `betterstack-unavailable:${key}`,
1297
- "[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery."
1298
- );
1299
- };
1300
- const emitExceptionUnavailableWarning = () => {
1301
- warnOnce2(
1302
- `betterstack-exception-unavailable:${key}`,
1303
- "[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture."
1304
- );
1305
- };
1306
- return {
1307
- enabled: connector.enabled,
1308
- ready: connector.ready,
1309
- mode: connector.mode,
1310
- serviceName: connector.serviceName,
1311
- ingestingHost: connector.ingestingHost,
1312
- status: connector.status,
1313
- errorTracking: {
1314
- enabled: connector.errorTracking.enabled,
1315
- ready: errorTrackingReady,
1316
- status: errorTrackingReady ? "enabled" : "missing",
1317
- dsn: connector.errorTracking.dsn,
1318
- tracesSampleRate: connector.errorTracking.tracesSampleRate,
1319
- environment: connector.errorTracking.environment,
1320
- release: connector.errorTracking.release
1321
- },
1322
- shouldAutoForwardServerLogs() {
1323
- return connector.ready && connector.mode === "auto";
1324
- },
1325
- shouldAutoCaptureExceptions() {
1326
- return errorTrackingReady;
1327
- },
1328
- send(record, options = {}) {
1329
- if (!connector.ready || !client) {
1330
- if (options.warnIfUnavailable) {
1331
- emitUnavailableWarning();
1332
- }
1333
- return;
1334
- }
1335
- const source = options.source ?? "server";
1336
- void client.log(
1337
- record.message,
1338
- resolveBetterStackLevel(record.level),
1339
- buildContext(record, connector, source)
1340
- ).catch((error) => {
1341
- warnOnce2(
1342
- `betterstack-send:${key}`,
1343
- "[Blyp] Failed to deliver log to Better Stack.",
1344
- error
1345
- );
1346
- });
1347
- },
1348
- captureException(error, options = {}) {
1349
- if (!errorTrackingReady || !sentryModule) {
1350
- if (options.warnIfUnavailable) {
1351
- emitExceptionUnavailableWarning();
1352
- }
1353
- return;
1354
- }
1355
- if (isPreviouslyCapturedError(error)) {
1356
- return;
1357
- }
1358
- try {
1359
- const exception = normalizeExceptionInput(error);
1360
- sentryModule.withScope((scope) => {
1361
- scope.setLevel(
1362
- normalizeScopeLevel(
1363
- options.source === "client" ? "error" : "error"
1364
- )
1365
- );
1366
- scope.setContext("blyp", {
1367
- source: options.source ?? "server",
1368
- ...options.context ? { context: options.context } : {}
1369
- });
1370
- sentryModule.captureException(exception);
1371
- });
1372
- markCapturedError(error);
1373
- markCapturedError(exception);
1374
- } catch (captureError) {
1375
- warnOnce2(
1376
- `betterstack-manual-capture:${key}`,
1377
- "[Blyp] Failed to capture exception in Better Stack error tracking.",
1378
- captureError
1379
- );
1380
- }
1381
- },
1382
- async flush() {
1383
- if (!client) {
1384
- if (!errorTrackingReady || !sentryModule) {
1385
- return;
1386
- }
1387
- }
1388
- try {
1389
- if (client) {
1390
- await client.flush();
1391
- }
1392
- if (errorTrackingReady && sentryModule) {
1393
- await sentryModule.flush(2e3);
1394
- }
1395
- } catch (error) {
1396
- warnOnce2(
1397
- `betterstack-flush:${key}`,
1398
- "[Blyp] Failed to flush Better Stack logs.",
1399
- error
1400
- );
1401
- }
1402
- }
1403
- };
1404
- }
1405
-
1406
- // src/connectors/betterstack/index.ts
1407
- function resolveSender(config = {}) {
1408
- return createBetterStackSender(resolveConfig({
1409
- ...config.connectors ? { connectors: config.connectors } : {}
1410
- }));
1411
- }
1412
- function createBetterStackLoggerInstance(sender, bindings = {}) {
1413
- const writeRecord = (level, message, args) => {
1414
- sender.send(buildRecord(level, message, args, bindings), {
1415
- source: "server",
1416
- warnIfUnavailable: true
1417
- });
1418
- };
1419
- const writeStructured = (payload, message) => {
1420
- sender.send(
1421
- buildStructuredRecord(
1422
- resolveStructuredWriteLevel(payload.level),
1423
- message,
1424
- payload,
1425
- bindings
1426
- ),
1427
- {
1428
- source: "server",
1429
- warnIfUnavailable: true
1430
- }
1431
- );
1432
- };
1433
- return {
1434
- debug: (message, ...args) => {
1435
- writeRecord("debug", message, args);
1436
- },
1437
- info: (message, ...args) => {
1438
- writeRecord("info", message, args);
1439
- },
1440
- error: (message, ...args) => {
1441
- writeRecord("error", message, args);
1442
- },
1443
- warn: (message, ...args) => {
1444
- writeRecord("warn", message, args);
1445
- },
1446
- warning: (message, ...args) => {
1447
- writeRecord("warning", message, args);
1448
- },
1449
- success: (message, ...args) => {
1450
- writeRecord("success", message, args);
1451
- },
1452
- critical: (message, ...args) => {
1453
- writeRecord("critical", message, args);
1454
- },
1455
- table: (message, data) => {
1456
- writeRecord("table", message, data === void 0 ? [] : [data]);
1457
- },
1458
- flush: async () => {
1459
- },
1460
- shutdown: async () => {
1461
- },
1462
- createStructuredLog: (groupId, initial) => {
1463
- return createStructuredLog(groupId, {
1464
- initialFields: initial,
1465
- write: writeStructured
1466
- });
1467
- },
1468
- child: (childBindings) => {
1469
- return createBetterStackLoggerInstance(sender, {
1470
- ...bindings,
1471
- ...childBindings
1472
- });
1473
- }
1474
- };
1475
- }
1476
- function createBetterStackErrorTrackerInstance(sender, bindings = {}) {
1477
- return {
1478
- capture: (error, options = {}) => {
1479
- sender.captureException(error, {
1480
- source: options.source ?? "server",
1481
- warnIfUnavailable: options.warnIfUnavailable ?? true,
1482
- context: {
1483
- ...bindings,
1484
- ...options.context ?? {},
1485
- "blyp.manual": true
1486
- }
1487
- });
1488
- },
1489
- child: (childBindings) => {
1490
- return createBetterStackErrorTrackerInstance(sender, {
1491
- ...bindings,
1492
- ...childBindings
1493
- });
1494
- }
1495
- };
1496
- }
1497
- function createBetterStackLogger(config = {}) {
1498
- return createBetterStackLoggerInstance(resolveSender(config));
1499
- }
1500
- function createBetterStackErrorTracker(config = {}) {
1501
- return createBetterStackErrorTrackerInstance(resolveSender(config));
1502
- }
1503
- function captureBetterStackException(error, options = {}, config = {}) {
1504
- createBetterStackErrorTracker(config).capture(error, options);
1505
- }
1506
- function createStructuredBetterStackLogger(groupId, initial, config = {}) {
1507
- const sender = resolveSender(config);
1508
- return createStructuredLog(groupId, {
1509
- initialFields: initial,
1510
- write: (payload, message) => {
1511
- sender.send(
1512
- buildStructuredRecord(
1513
- resolveStructuredWriteLevel(payload.level),
1514
- message,
1515
- payload,
1516
- {}
1517
- ),
1518
- {
1519
- source: "server",
1520
- warnIfUnavailable: true
1521
- }
1522
- );
1523
- }
1524
- });
1525
- }
1526
-
1527
- exports.captureBetterStackException = captureBetterStackException;
1528
- exports.createBetterStackErrorTracker = createBetterStackErrorTracker;
1529
- exports.createBetterStackLogger = createBetterStackLogger;
1530
- exports.createStructuredBetterStackLogger = createStructuredBetterStackLogger;
1531
- //# sourceMappingURL=betterstack.js.map
1532
- //# sourceMappingURL=betterstack.js.map
1
+ 'use strict';var fs=require('fs'),jiti=require('jiti'),Ne=require('path'),_e=require('os'),zod=require('zod'),async_hooks=require('async_hooks'),Gt=require('@sentry/node'),node=require('@logtail/node');require('fflate');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ne__default=/*#__PURE__*/_interopDefault(Ne);var _e__default=/*#__PURE__*/_interopDefault(_e);var Gt__namespace=/*#__PURE__*/_interopNamespace(Gt);function ee(){return Ne__default.default.join(_e__default.default.homedir(),".blyp","queue.db")}function P(e){let t={name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let n=e;return n.cause!==void 0&&(t.cause=w(n.cause)),t}function w(e,t=new WeakSet){if(e instanceof Error)return P(e);if(typeof e=="function")return `[Function: ${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e==null)return e;if(Array.isArray(e))return e.map(n=>w(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,o]of Object.entries(e))n[r]=w(o,t);return t.delete(e),n}return e}function _(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=w(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}var Ie=zod.z.string().url().refine(e=>{try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}},{message:"Expected an absolute http(s) URL"}),te=zod.z.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),I=zod.z.string().trim().min(1);function T(e){return Ie.safeParse(e).success}function h(e){return te.safeParse(e).success}function y(e){return I.safeParse(e).success}var M="/inngest";zod.z.union([zod.z.literal("betterstack"),zod.z.literal("databuddy"),zod.z.literal("posthog"),zod.z.literal("sentry"),zod.z.undefined(),zod.z.object({type:zod.z.literal("otlp"),name:I})]);function ne(e,t=new Set){return (n,r,o)=>{if(t.has(n)||typeof console>"u")return;let i=console[e];if(typeof i=="function"){if(t.add(n),o===void 0){i.call(console,r);return}i.call(console,r,o);}}}function re(e){return ne("warn",e)}function oe(e){return ne("error",e)}var Me="[REDACTED]",je=["password","passwd","pwd","secret","token","api_key","apikey","api_secret","authorization","auth","x-api-key","private_key","privatekey","access_token","refresh_token","client_secret","session","cookie","set-cookie","ssn","credit_card","card_number","cvv","cvc","otp","pin"];var qe=[{type:"bearer",pattern:/\bBearer\s+(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Za-z0-9._~+/-]{20,})\b/g},{type:"jwt",pattern:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"api_key",pattern:/\b(?:sk-[A-Za-z0-9]{20,}|pk_(?:live|test)_[A-Za-z0-9]{16,})\b/g}],$e=/\b(?:\d[ -]*?){16}\b/g;function ie(e){let t=new Set,n=[];for(let r of e)typeof r!="string"||r.length===0||t.has(r)||(t.add(r),n.push(r));return n}function He(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Ue(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function We(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ge(e){return e.split(".").filter(Boolean)}function j(e,t,n=0,r=0){if(n===e.length)return r===t.length;let o=e[n];if(o==="**"){if(n===e.length-1)return true;for(let i=r;i<=t.length;i+=1)if(j(e,t,n+1,i))return true;return false}return r>=t.length||o!=="*"&&o!==t[r]?false:j(e,t,n+1,r+1)}function Qe(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>j(Ge(n),e))}function Je(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let o=t.length-1;o>=0;o-=1){let i=Number(t[o]);r&&(i*=2,i>9&&(i-=9)),n+=i,r=!r;}return n%10===0}function ae(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:o,pattern:i}of qe)r=r.replace(i,`[REDACTED:${o}]`);r=r.replace($e,o=>Je(o)?"[REDACTED:card]":o);for(let o of t.patterns)r=r.replace(He(o),"[REDACTED:pattern]");return r}function z(e,t,n,r){if(typeof e=="string")return ae(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((i,a)=>z(i,t,n,{path:[...r.path,String(a)],skipPatternScanning:r.skipPatternScanning}));if(!Ue(e))return e;let o={};for(let[i,a]of Object.entries(e)){let c=[...r.path,i];if(n.has(i.toLowerCase())||Qe(c,t)){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){o[i]=Me;continue}o[i]=z(a,t,n,{path:c,skipPatternScanning:r.skipPatternScanning});continue}o[i]=z(a,t,n,{path:c,skipPatternScanning:r.skipPatternScanning});}return o}function k(e,t){return {keys:ie([...je,...e?.keys??[],...t?.keys??[]]),paths:ie([...e?.paths??[],...t?.paths??[]]),patterns:[...e?.patterns??[],...t?.patterns??[]].filter(n=>n instanceof RegExp),disablePatternScanning:t?.disablePatternScanning??e?.disablePatternScanning??false}}function f(e,t,n={path:[]}){let r=w(e);return z(r,t,We(t),n)}function D(e,t){return typeof e=="string"?ae(e,t,false):_(f(e,t))}var Ze="@blyp/core",Xe=".gitignore",le=["blyp.config.ts","blyp.config.mts","blyp.config.cts","blyp.config.js","blyp.config.mjs","blyp.config.cjs","blyp.config.json"],et="blyp.config.json",tt="https://us.i.posthog.com",nt="blyp-app",rt=nt,ot=new Set,b=re(ot),ge={enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true},de={enabled:true,dir:"",archiveDir:"",format:"ndjson",rotation:ge},q={enabled:true,path:M},fe=k(),x={maxAttempts:8,initialBackoffMs:500,maxBackoffMs:3e4,multiplier:2,jitter:true},C={enabled:false,memoryBufferSize:500,durableQueuePath:ee(),durableSpillStrategy:"after-first-failure",memoryBatchSize:25,sqliteWriteBatchSize:100,sqliteReadBatchSize:50,dispatchConcurrency:4,pollIntervalMs:1e3,overflowStrategy:"drop-oldest",retry:x},pe={maxRetries:1,backoffMs:100},it={strategy:"immediate",batchSize:1,flushIntervalMs:250,maxQueueSize:1e3,overflowStrategy:"drop-oldest",flushTimeoutMs:5e3,retry:pe},se={pretty:true,level:"info",destination:"file",file:de,clientLogging:q,redact:fe,connectors:{delivery:C}},E=null;function at(e){let t=e;for(;;){let n=Ne.resolve(t,"package.json");if(fs.existsSync(n))try{let o=JSON.parse(fs.readFileSync(n,"utf-8"));if(y(o.name))return o.name}catch{}let r=Ne.dirname(t);if(r===t)return;t=r;}}function H(e=process.cwd()){return at(e)??rt}function st(){return {pretty:true,level:"info",destination:"file",file:{enabled:true,format:"ndjson",rotation:{enabled:true,maxSizeBytes:10*1024*1024,maxArchives:5,compress:true}},clientLogging:{enabled:true,path:M},redact:fe,connectors:{delivery:C}}}function ct(e){let t=Ne.resolve(e,"package.json");if(!fs.existsSync(t))return true;try{return JSON.parse(fs.readFileSync(t,"utf-8")).name!==Ze}catch{return true}}function ut(e){if(le.some(n=>fs.existsSync(Ne.resolve(e,n))))return;let t=Ne.resolve(e,et);if(!fs.existsSync(t))try{fs.writeFileSync(t,`${JSON.stringify(st(),null,2)}
2
+ `);}catch(n){console.error("[Blyp] Warning: Failed to create blyp.config.json:",n);}}function lt(e){let t=Ne.resolve(e,Xe);if(!fs.existsSync(t)){try{fs.writeFileSync(t,`logs
3
+ .blyp
4
+ `);}catch(n){console.error("[Blyp] Warning: Failed to create .gitignore:",n);}return}try{let n=fs.readFileSync(t,"utf-8"),r=["logs",".blyp"].filter(i=>{let a=i.replace(".","\\.");return !new RegExp(`^(?:/?${a}/?)\\s*$`,"m").test(n)});if(r.length===0)return;let o=n.endsWith(`
5
+ `)?"":`
6
+ `;fs.appendFileSync(t,`${o}${r.join(`
7
+ `)}
8
+ `);}catch(n){console.error("[Blyp] Warning: Failed to update .gitignore:",n);}}function gt(){let e=process.cwd();ct(e)&&(ut(e),lt(e));}function dt(){let e=process.cwd(),t=le.map(r=>Ne.resolve(e,r)).filter(r=>fs.existsSync(r));if(t.length===0)return null;if(t.length>1){let r=t[0];b(`config-multiple:${r}`,`[Blyp] Warning: Multiple config files found. Using ${r} and ignoring ${t.slice(1).join(", ")}.`);}let n=t[0];return {path:n,type:n.endsWith(".json")?"json":"jiti"}}function ye(e,t){let n=e&&typeof e=="object"&&"default"in e&&e.default!==void 0?e.default:e;return !n||typeof n!="object"||Array.isArray(n)?(b(`config-invalid:${t}`,`[Blyp] Warning: Config file ${t} did not export an object. Falling back to defaults.`),{}):n}function ft(e){try{let t=fs.readFileSync(e,"utf-8");return ye(JSON.parse(t),e)}catch(t){return console.error("[Blyp] Warning: Failed to parse blyp.config.json:",t),{}}}function pt(e){try{let t=jiti.createJiti(process.cwd(),{interopDefault:!0,moduleCache:!1,fsCache:!1});return ye(t(e),e)}catch(t){return console.error(`[Blyp] Warning: Failed to load ${e}:`,t),{}}}function yt(e){return e.type==="json"?ft(e.path):pt(e.path)}function ce(e){return !!e&&typeof e=="object"&&e.type==="prisma"}function mt(e){return !!e&&typeof e=="object"&&e.type==="drizzle"}function Ct(e,t){return {...pe,...e,...t}}function ht(e,t){return {...it,...e,...t,retry:Ct(e?.retry,t?.retry)}}function St(e){let t=e.model??"blypLog",r=e.client?.[t];return !!r&&typeof r.create=="function"}function kt(e){let t=e.db;return !!t&&typeof t.insert=="function"&&e.table!==void 0}function bt(e,t){if(!e)return;let n=e.adapter,r=false;t==="json"?b("database-json-config","[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."):e.dialect!=="postgres"&&e.dialect!=="mysql"?b(`database-dialect:${String(e.dialect)}`,`[Blyp] Warning: Unsupported database dialect "${String(e.dialect)}". Database logging is disabled.`):n?ce(n)?(r=St({...n,model:n.model??"blypLog"}),r||b("database-prisma-missing",`[Blyp] Warning: Prisma database adapter is missing the "${n.model??"blypLog"}" delegate or its create method. Database logging is disabled.`)):mt(n)&&(r=kt(n),r||b("database-drizzle-missing","[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled.")):b("database-adapter-missing","[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled.");let o=ce(n)?{...n,model:n.model??"blypLog"}:n;return {dialect:e.dialect,adapter:o,delivery:ht(void 0,e.delivery),ready:r,status:r?"enabled":"missing"}}function Rt(e,t){return {...ge,...e,...t}}function Lt(e,t){return {...de,...e,...t,rotation:Rt(e?.rotation,t?.rotation)}}function wt(e,t){return {...q,...e,...t,path:t?.path??e?.path??q.path}}function xt(e,t){return k(e,t)}function vt(e,t){return {maxAttempts:Math.max(1,Math.floor(t?.maxAttempts??e?.maxAttempts??x.maxAttempts)),initialBackoffMs:Math.max(0,Math.floor(t?.initialBackoffMs??e?.initialBackoffMs??x.initialBackoffMs)),maxBackoffMs:Math.max(0,Math.floor(t?.maxBackoffMs??e?.maxBackoffMs??x.maxBackoffMs)),multiplier:Math.max(1,t?.multiplier??e?.multiplier??x.multiplier),jitter:t?.jitter??e?.jitter??x.jitter}}function Bt(e,t){let n=t?.durableQueuePath??e?.durableQueuePath??C.durableQueuePath;return {enabled:t?.enabled??e?.enabled??C.enabled,memoryBufferSize:Math.max(1,Math.floor(t?.memoryBufferSize??e?.memoryBufferSize??C.memoryBufferSize)),durableQueuePath:y(n)?n:C.durableQueuePath,durableSpillStrategy:t?.durableSpillStrategy??e?.durableSpillStrategy??C.durableSpillStrategy,memoryBatchSize:Math.max(1,Math.floor(t?.memoryBatchSize??e?.memoryBatchSize??C.memoryBatchSize)),sqliteWriteBatchSize:Math.max(1,Math.floor(t?.sqliteWriteBatchSize??e?.sqliteWriteBatchSize??C.sqliteWriteBatchSize)),sqliteReadBatchSize:Math.max(1,Math.floor(t?.sqliteReadBatchSize??e?.sqliteReadBatchSize??C.sqliteReadBatchSize)),dispatchConcurrency:Math.max(1,Math.floor(t?.dispatchConcurrency??e?.dispatchConcurrency??C.dispatchConcurrency)),pollIntervalMs:Math.max(50,Math.floor(t?.pollIntervalMs??e?.pollIntervalMs??C.pollIntervalMs)),overflowStrategy:t?.overflowStrategy??e?.overflowStrategy??C.overflowStrategy,retry:vt(e?.retry,t?.retry),durableReady:false}}function Tt(e,t,n){if(!(!e&&!t))return bt({dialect:t?.dialect??e?.dialect,adapter:t?.adapter??e?.adapter,delivery:{...e?.delivery??{},...t?.delivery??{},retry:{...e?.delivery?.retry??{},...t?.delivery?.retry??{}}}},n)}function Dt(e,t){let n=t?.enabled??e?.enabled??false,r=t?.projectKey??e?.projectKey,o=e?.enabled===true?e?.errorTracking:void 0,i=t?.errorTracking?.mode??o?.mode??"auto",a=t?.errorTracking?.enabled??o?.enabled??n,c=n&&a&&typeof r=="string"&&r.trim().length>0;return {enabled:n,mode:t?.mode??e?.mode??"auto",projectKey:r,host:t?.host??e?.host??tt,serviceName:t?.serviceName??e?.serviceName??H(),errorTracking:{enabled:a,mode:i,enableExceptionAutocapture:t?.errorTracking?.enableExceptionAutocapture??o?.enableExceptionAutocapture??i==="auto",ready:c,status:c?"enabled":"missing"}}}function Et(e,t){let n=t?.enabled??e?.enabled??false,r=t?.apiKey??e?.apiKey,o=t?.websiteId??e?.websiteId,i=n&&y(r)&&y(o);return {enabled:n,mode:t?.mode??e?.mode??"auto",apiKey:r,websiteId:o,namespace:t?.namespace??e?.namespace,source:t?.source??e?.source,apiUrl:t?.apiUrl??e?.apiUrl,debug:t?.debug??e?.debug??false,enableBatching:t?.enableBatching??e?.enableBatching??true,batchSize:t?.batchSize??e?.batchSize,batchTimeout:t?.batchTimeout??e?.batchTimeout,maxQueueSize:t?.maxQueueSize??e?.maxQueueSize,ready:i,status:i?"enabled":"missing"}}function At(e,t){let n=t?.sourceToken??e?.sourceToken,r=t?.ingestingHost??e?.ingestingHost,o=t?.enabled??e?.enabled??false,i=e?.enabled===true?e?.errorTracking:void 0,a=Pt(o,i,t?.errorTracking),c=o&&y(n)&&T(r);return {enabled:o,mode:t?.mode??e?.mode??"auto",sourceToken:n,ingestingHost:r,serviceName:t?.serviceName??e?.serviceName??H(),errorTracking:a,ready:c,status:c?"enabled":"missing"}}function Pt(e,t,n){let r=n?.dsn??t?.dsn,o=n?.enabled??t?.enabled??e,i=o&&y(r);return {enabled:o,dsn:r,tracesSampleRate:n?.tracesSampleRate??t?.tracesSampleRate??1,environment:n?.environment??t?.environment,release:n?.release??t?.release,ready:i,status:i?"enabled":"missing"}}function zt(e,t){let n=t?.dsn??e?.dsn,r=t?.enabled??e?.enabled??false,o=r&&typeof n=="string"&&n.trim().length>0;return {enabled:r,mode:t?.mode??e?.mode??"auto",dsn:n,environment:t?.environment??e?.environment,release:t?.release??e?.release,ready:o,status:o?"enabled":"missing"}}function Ot(e,t){let n=t?.endpoint??e?.endpoint,r=t?.enabled??e?.enabled??false,o={...{},...t?.headers??{}},i=r&&T(n);return {name:t?.name??e?.name??"",enabled:r,mode:t?.mode??e?.mode??"auto",endpoint:n,headers:o,auth:t?.auth??e?.auth,serviceName:t?.serviceName??e?.serviceName??H(),ready:i,status:i?"enabled":"missing"}}function Ft(e,t){let n=t??e??[],r=new Map;for(let o of n)!o||typeof o.name!="string"||o.name.length===0||(r.has(o.name)&&b(`otlp-duplicate:${o.name}`,`[Blyp] Warning: Duplicate OTLP connector name "${o.name}" found. Using the last definition.`),r.set(o.name,Ot(void 0,o)));return Array.from(r.values())}function _t(e,t){return {betterstack:At(e?.betterstack,t?.betterstack),databuddy:Et(e?.databuddy,t?.databuddy),posthog:Dt(e?.posthog,t?.posthog),sentry:zt(e?.sentry,t?.sentry),otlp:Ft(e?.otlp,t?.otlp),delivery:Bt(e?.delivery,t?.delivery)}}function $(e,t={},n={}){return {...e,...t,destination:t.destination??e.destination??"file",file:Lt(e.file,t.file),database:Tt(e.database,t.database,n.configFileType),clientLogging:wt(e.clientLogging,t.clientLogging),redact:xt(e.redact,t.redact),connectors:_t(e.connectors,t.connectors)}}function Nt(){if(E!==null)return E;gt();let e=dt();if(e){let t=yt(e);E=$(se,t,{configFileType:e.type});}else E=$(se);return E}function me(e={}){return $(Nt(),e)}var Mt=new async_hooks.AsyncLocalStorage;function jt(){return Mt.getStore()}function U(){return jt()?.traceId}var Ce={success:"success",critical:"critical",warning:"warning",info:"info",debug:"debug",error:"error",warn:"warning",table:"table"};function F(e){return e.replace(/\\/g,"/")}function qt(e){let t=F(e);return t.startsWith("node:")||t.includes("/node_modules/pino")||t.includes("/node_modules/pino-pretty")||t.includes("/node_modules/@blyp/core/")||t.includes("/blyp/src/core/")||t.includes("/blyp/src/frameworks/")||t.includes("/blyp/src/posthog/")||t.includes("/blyp/dist/")}function $t(e){let t=F(e),n=F(process.cwd());return t.startsWith(`${n}/`)?t.slice(n.length+1):t}function he(){try{let e=new Error().stack;if(!e)return {file:null,line:null};let t=e.split(`
9
+ `),n=null;for(let r=2;r<t.length;r+=1){let o=t[r];if(!o)continue;let i=o.match(/\((.*):(\d+):\d+\)/)||o.match(/at\s+(.*):(\d+):(\d+)/);if(!i)continue;let a=i[1]||"",c=parseInt(i[2]||"0",10)||null;if(a&&!a.includes("node_modules")&&!qt(a)){let g=$t(a);if(!F(g).startsWith("dist/"))return {file:g,line:c};n??(n={file:g,line:c});}}if(n)return n}catch{return {file:null,line:null}}return {file:null,line:null}}var Se=D;function ke(e){return e.replace(/\u001b\[[0-9;]*m/g,"")}function be(e,t,n,r,o=k()){let{file:i,line:a}=he(),c=Se(t,o),g={timestamp:new Date().toISOString(),level:Ce[e],message:ke(c)},s=U();return t instanceof Error&&(g.error=f(P(t),o)),i&&(g.caller=a!==null?`${i}:${a}`:i),n.length===1?g.data=f(n[0],o):n.length>1&&(g.data=f(n,o)),Object.keys(r).length>0&&(g.bindings=f(r,o)),s&&(g.traceId=s),g}function W(e,t,n,r,o=k()){let{file:i,line:a}=he(),c=f(n,o),g=U(),s={message:ke(Se(t,o)),...c};return i&&(s.caller=a!==null?`${i}:${a}`:i),Object.keys(r).length>0&&(s.bindings=f(r,o)),g&&s.traceId===void 0&&(s.traceId=g),s.level=typeof c.level=="string"&&c.level.length>0?c.level:Ce[e],s.timestamp=typeof c.timestamp=="string"&&c.timestamp.length>0?c.timestamp:new Date().toISOString(),s}function G(e){switch(e){case "debug":return "debug";case "warning":return "warning";case "warn":return "warn";case "error":return "error";case "success":return "success";case "critical":return "critical";case "table":return "table";default:return "info"}}function Re(e,t){if(typeof e=="string")return t.length===0?void 0:t.length===1?t[0]:t;let n=[e,...t];return n.length===1?n[0]:n}function Le(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ht(e,t){if(e==null)return t===void 0||t<400?void 0:{message:`HTTP ${t}`,code:t,type:"HttpError"};if(e instanceof Error){let n=e;return {message:e.message,code:n.code,type:n.type??e.name??e.constructor?.name,stack:e.stack,why:n.why,fix:n.fix,link:n.link,details:Le(n.details),cause:n.cause}}if(typeof e=="object"){let n=e,r=typeof n.statusCode=="number"?n.statusCode:typeof n.status=="number"?n.status:t;return {message:typeof n.message=="string"?n.message:`HTTP ${r??500}`,code:typeof n.code=="string"||typeof n.code=="number"?n.code:r,type:typeof n.type=="string"?n.type:typeof n.name=="string"?n.name:"Error",stack:typeof n.stack=="string"?n.stack:void 0,why:typeof n.why=="string"?n.why:void 0,fix:typeof n.fix=="string"?n.fix:void 0,link:typeof n.link=="string"?n.link:void 0,details:Le(n.details),cause:n.cause}}return {message:String(e),code:t,type:typeof e}}function Ut(e){return e.response&&typeof e.response.status=="number"?e.response.status:typeof e.status=="number"?e.status:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.statusCode=="number"?e.error.statusCode:e.error&&typeof e.error=="object"&&e.error!==null&&typeof e.error.status=="number"?e.error.status:e.error?500:void 0}function Q(e,t){let n=t.redact??k(),r=performance.now(),o=f(t.initialFields??{},n),i=[],a;t.onCreate?.();let c=(s,l,m)=>(i.push({level:s,message:D(l,n),timestamp:new Date().toISOString(),...Re(l,m)===void 0?{}:{data:f(Re(l,m),n)}}),g),g={set(s){return Object.assign(o,f(s,n)),g},debug(s,...l){return c("debug",s,l)},info(s,...l){return c("info",s,l)},warn(s,...l){return c("warn",s,l)},warning(s,...l){return c("warning",s,l)},error(s,...l){return c("error",s,l)},success(s,...l){return c("success",s,l)},critical(s,...l){return c("critical",s,l)},table(s,l){return c("table",s,l===void 0?[]:[l])},emit(s={}){if(a)return a;let l=f(t.resolveDefaultFields?.()??{},n),m=Ut(s),u=f(Ht(s.error,m),n),d=s.level??(u?"error":"info"),p=f({...l,...o,groupId:e,timestamp:new Date().toISOString(),level:d,duration:Math.round(performance.now()-r),...typeof m=="number"?{status:m}:{},...i.length>0?{events:[...i]}:{},...u?{error:u}:{}},n);return t.write(p,D(s.message??"structured_log",n)),a=p,t.onEmit?.(p),p}};return g}function Wt(){let e=new WeakSet;return (t,n)=>{if(typeof n=="function")return `[Function: ${n.name||"anonymous"}]`;if(n===void 0)return "[undefined]";if(typeof n=="symbol")return n.toString();if(n!==null&&typeof n=="object"){if(e.has(n))return "[Circular]";e.add(n);}return n}}function we(e){return JSON.stringify(e,Wt())}var J=Symbol("blyp.connector.batch-dispatch"),xe=Symbol("blyp.connector.delivery-binder");function ve(e){return h(e)&&("connectors"in e||"pretty"in e||"level"in e)}function V(e){return h(e.data)?e.data:e}function R(e,t){if(t in e){let o=e[t];if(typeof o=="string"||typeof o=="number")return o}let r=V(e)[t];if(typeof r=="string"||typeof r=="number")return r}function K(e,t){let n=V(e),o=(h(n.page)?n.page:void 0)?.[t];return typeof o=="string"?o:void 0}function Y(e,t){let n=V(e),o=(h(n.session)?n.session:void 0)?.[t];return typeof o=="string"?o:void 0}function Be(e){return R(e,"type")}var Z="__betterstack_previously_captured_error",Jt=new Set,Ae={},L=oe(Jt);function Vt(){return Ae.module??Gt__namespace}function Kt(e){let t=ve(e)?e.connectors?.betterstack:e,n=t?.enabled??false,r=t?.sourceToken,o=t?.ingestingHost,i=t?.errorTracking?.enabled??n,a=t?.errorTracking?.dsn,c=n&&i&&y(a),g=n&&y(r)&&T(o);return {enabled:n,mode:t?.mode??"auto",sourceToken:r,ingestingHost:o,serviceName:t?.serviceName??"blyp-app",errorTracking:{enabled:i,dsn:a,tracesSampleRate:t?.errorTracking?.tracesSampleRate??1,environment:t?.errorTracking?.environment,release:t?.errorTracking?.release,ready:c,status:c?"enabled":"missing"},ready:g,status:g?"enabled":"missing"}}function Te(e){switch(e){case "debug":return "debug";case "warning":case "warn":return "warn";case "error":return "error";case "critical":return "fatal";default:return "info"}}function Yt(e){if(typeof e!="string"||e.trim().length===0)return {};let t=e.match(/^(.*):(\d+)$/);if(!t)return {};let n=t[1]?.trim(),r=Number.parseInt(t[2]??"",10);return {...n?{file:n}:{},...Number.isFinite(r)?{line:r}:{}}}function De(e,t,n){let r=Be(e),o=R(e,"groupId"),i=R(e,"traceId"),a=R(e,"method"),c=R(e,"path"),g=R(e,"status"),s=R(e,"duration"),l=K(e,"pathname"),m=K(e,"url"),u=Y(e,"sessionId"),d=Y(e,"pageId"),p=Yt(e.caller);return {service:t.serviceName,context:{blyp:{level:e.level,source:n,...r?{type:r}:{},...o?{group_id:o}:{},...i?{trace_id:i}:{},...e.caller?{caller:e.caller}:{},...s!==void 0?{duration_ms:s}:{},...e.bindings?{bindings:e.bindings}:{},payload:we(e)},...a||c||g!==void 0?{http:{...a?{method:a}:{},...c?{path:c}:{},...g!==void 0?{status_code:g}:{}}}:{},...l||m||u||d?{client:{...l?{page_path:l}:{},...m?{page_url:m}:{},...u?{session_id:u}:{},...d?{page_id:d}:{}}}:{},...Object.keys(p).length>0?{runtime:p}:{},...e.data!==void 0?{data:e.data}:{},...e.error!==void 0?{error:e.error}:{}}}}function Zt(e){if(!h(e))return;let t=typeof e.message=="string"?e.message:void 0,n=typeof e.name=="string"?e.name:void 0,r=typeof e.stack=="string"?e.stack:void 0;if(!t&&!n&&!r)return;let o=new Error(t??n??"Unknown error");o.name=n??"Error",r&&(o.stack=r);for(let[i,a]of Object.entries(e))i==="message"||i==="name"||i==="stack"||(o[i]=a);return o}function Xt(e){switch(e){case "debug":return "debug";case "warning":case "warn":return "warning";case "critical":return "fatal";case "error":return "error";default:return "info"}}function en(e){if(e instanceof Error)return e;let t=Zt(e);return t||(typeof e=="string"?new Error(e):new Error("Unknown Better Stack exception"))}function Pe(e){return h(e)&&e[Z]===true}function Ee(e){if(!(!h(e)||Pe(e)))try{Object.defineProperty(e,Z,{value:!0,enumerable:!1,configurable:!0,writable:!0});}catch{try{e[Z]=!0;}catch{}}}function tn(e){return new node.Logtail(e.sourceToken??"",{endpoint:e.ingestingHost,captureStackContext:false})}function nn(e){return e?.getOptions?.()??{}}function rn(e,t){let n=["beforeExit","SIGINT","SIGTERM"];for(let r of n)process.once(r,()=>{t().catch(o=>{L(`${e}:shutdown`,"[Blyp] Failed to flush Better Stack logs during shutdown.",o);});});}function ze(e){let t=Kt(e),n=`${t.serviceName}:${t.ingestingHost??"missing"}:${t.mode}`,r=Vt(),o=t.ready?Ae.createClient?.(t)??tn(t):void 0,i=t.errorTracking.enabled?r?.getClient?.():void 0;if(i){let u=nn(i);(y(t.errorTracking.dsn)&&t.errorTracking.dsn!==u.dsn||y(t.errorTracking.environment)&&t.errorTracking.environment!==u.environment||y(t.errorTracking.release)&&t.errorTracking.release!==u.release)&&L(`betterstack-error-mismatch:${n}`,"[Blyp] Sentry is already initialized with different options. Reusing the existing Sentry client for Better Stack error tracking.");}if(!i&&t.errorTracking.enabled&&y(t.errorTracking.dsn)&&r)try{r.init({dsn:t.errorTracking.dsn,tracesSampleRate:t.errorTracking.tracesSampleRate,environment:t.errorTracking.environment,release:t.errorTracking.release}),i=r.getClient();}catch(u){L(`betterstack-error-init:${n}`,"[Blyp] Failed to initialize Better Stack error tracking.",u);}let a=t.errorTracking.enabled&&i!==void 0;(o||a)&&rn(n,async()=>{o&&await o.flush(),a&&await r.flush(2e3);});let c=()=>{L(`betterstack-unavailable:${n}`,"[Blyp] Better Stack connector is not configured or not ready. Skipping Better Stack delivery.");},g=()=>{L(`betterstack-exception-unavailable:${n}`,"[Blyp] Better Stack error tracking is not configured. Skipping Better Stack exception capture.");},s=null,l=async u=>{if(!t.ready||!o)return {ok:false,retryable:false,error:"Better Stack connector is not configured."};try{return await Promise.all(u.map(d=>o.log(d.message,Te(d.level),De(d,t,"server")))),await o.flush(),{ok:!0}}catch(d){return {ok:false,retryable:true,error:d instanceof Error?d.message:String(d)}}},m={enabled:t.enabled,ready:t.ready,mode:t.mode,serviceName:t.serviceName,ingestingHost:t.ingestingHost,status:t.status,errorTracking:{enabled:t.errorTracking.enabled,ready:a,status:a?"enabled":"missing",dsn:t.errorTracking.dsn,tracesSampleRate:t.errorTracking.tracesSampleRate,environment:t.errorTracking.environment,release:t.errorTracking.release},shouldAutoForwardServerLogs(){return t.ready&&t.mode==="auto"},shouldAutoCaptureExceptions(){return a},send(u,d={}){if(d.source!=="client"&&s){s.enqueue("betterstack",u,m[J]);return}if(!t.ready||!o){d.warnIfUnavailable&&c();return}let p=d.source??"server";o.log(u.message,Te(u.level),De(u,t,p)).catch(A=>{L(`betterstack-send:${n}`,"[Blyp] Failed to deliver log to Better Stack.",A);});},captureException(u,d={}){if(!a||!r){d.warnIfUnavailable&&g();return}if(!Pe(u))try{let p=en(u);r.withScope(A=>{A.setLevel(Xt((d.source==="client","error"))),A.setContext("blyp",{source:d.source??"server",...d.context?{context:d.context}:{}}),r.captureException(p);}),Ee(u),Ee(p);}catch(p){L(`betterstack-manual-capture:${n}`,"[Blyp] Failed to capture exception in Better Stack error tracking.",p);}},async flush(){if(!(!o&&(!a||!r)))try{o&&await o.flush(),a&&r&&await r.flush(2e3);}catch(u){L(`betterstack-flush:${n}`,"[Blyp] Failed to flush Better Stack logs.",u);}},[J]:{dispatchKey:"betterstack",dispatch:u=>l(u)},[xe](u){s=u;}};return m}function X(e={}){return ze(me({...e.connectors?{connectors:e.connectors}:{}}))}function Oe(e,t={}){let n=(o,i,a)=>{e.send(be(o,i,a,t),{source:"server",warnIfUnavailable:true});},r=(o,i)=>{e.send(W(G(o.level),i,o,t),{source:"server",warnIfUnavailable:true});};return {debug:(o,...i)=>{n("debug",o,i);},info:(o,...i)=>{n("info",o,i);},error:(o,...i)=>{n("error",o,i);},warn:(o,...i)=>{n("warn",o,i);},warning:(o,...i)=>{n("warning",o,i);},success:(o,...i)=>{n("success",o,i);},critical:(o,...i)=>{n("critical",o,i);},table:(o,i)=>{n("table",o,i===void 0?[]:[i]);},flush:async()=>{},shutdown:async()=>{},createStructuredLog:(o,i)=>Q(o,{initialFields:i,write:r}),child:o=>Oe(e,{...t,...o})}}function Fe(e,t={}){return {capture:(n,r={})=>{e.captureException(n,{source:r.source??"server",warnIfUnavailable:r.warnIfUnavailable??true,context:{...t,...r.context??{},"blyp.manual":true}});},child:n=>Fe(e,{...t,...n})}}function or(e={}){return Oe(X(e))}function on(e={}){return Fe(X(e))}function ir(e,t={},n={}){on(n).capture(e,t);}function ar(e,t,n={}){let r=X(n);return Q(e,{initialFields:t,write:(o,i)=>{r.send(W(G(o.level),i,o,{}),{source:"server",warnIfUnavailable:true});}})}exports.captureBetterStackException=ir;exports.createBetterStackErrorTracker=on;exports.createBetterStackLogger=or;exports.createStructuredBetterStackLogger=ar;