@blyp/core 0.1.2 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +56 -3
  2. package/dist/astro.js +4602 -0
  3. package/dist/astro.js.map +1 -0
  4. package/dist/astro.mjs +4574 -0
  5. package/dist/astro.mjs.map +1 -0
  6. package/dist/client.js +7 -0
  7. package/dist/client.js.map +1 -1
  8. package/dist/client.mjs +7 -0
  9. package/dist/client.mjs.map +1 -1
  10. package/dist/connectors/betterstack.js +24 -0
  11. package/dist/connectors/betterstack.js.map +1 -1
  12. package/dist/connectors/betterstack.mjs +24 -0
  13. package/dist/connectors/betterstack.mjs.map +1 -1
  14. package/dist/connectors/databuddy/index.d.ts +7 -0
  15. package/dist/connectors/databuddy/sender.d.ts +5 -0
  16. package/dist/connectors/databuddy.js +1456 -0
  17. package/dist/connectors/databuddy.js.map +1 -0
  18. package/dist/connectors/databuddy.mjs +1451 -0
  19. package/dist/connectors/databuddy.mjs.map +1 -0
  20. package/dist/connectors/otlp.js +24 -0
  21. package/dist/connectors/otlp.js.map +1 -1
  22. package/dist/connectors/otlp.mjs +24 -0
  23. package/dist/connectors/otlp.mjs.map +1 -1
  24. package/dist/connectors/posthog.js +24 -0
  25. package/dist/connectors/posthog.js.map +1 -1
  26. package/dist/connectors/posthog.mjs +24 -0
  27. package/dist/connectors/posthog.mjs.map +1 -1
  28. package/dist/connectors/sentry.js +24 -0
  29. package/dist/connectors/sentry.js.map +1 -1
  30. package/dist/connectors/sentry.mjs +24 -0
  31. package/dist/connectors/sentry.mjs.map +1 -1
  32. package/dist/core/config.d.ts +1 -1
  33. package/dist/core/logger.d.ts +3 -0
  34. package/dist/elysia.js +455 -30
  35. package/dist/elysia.js.map +1 -1
  36. package/dist/elysia.mjs +455 -30
  37. package/dist/elysia.mjs.map +1 -1
  38. package/dist/expo.js +7 -0
  39. package/dist/expo.js.map +1 -1
  40. package/dist/expo.mjs +7 -0
  41. package/dist/expo.mjs.map +1 -1
  42. package/dist/express.js +455 -30
  43. package/dist/express.js.map +1 -1
  44. package/dist/express.mjs +455 -30
  45. package/dist/express.mjs.map +1 -1
  46. package/dist/fastify.js +455 -30
  47. package/dist/fastify.js.map +1 -1
  48. package/dist/fastify.mjs +455 -30
  49. package/dist/fastify.mjs.map +1 -1
  50. package/dist/frameworks/astro/index.d.ts +2 -0
  51. package/dist/frameworks/astro/logger.d.ts +3 -0
  52. package/dist/frameworks/nitro/index.d.ts +2 -0
  53. package/dist/frameworks/nitro/logger.d.ts +6 -0
  54. package/dist/frameworks/nuxt/index.d.ts +2 -0
  55. package/dist/frameworks/nuxt/logger.d.ts +3 -0
  56. package/dist/frameworks/react-router/index.d.ts +2 -0
  57. package/dist/frameworks/react-router/logger.d.ts +3 -0
  58. package/dist/frameworks/shared/h3.d.ts +19 -0
  59. package/dist/hono.js +455 -30
  60. package/dist/hono.js.map +1 -1
  61. package/dist/hono.mjs +455 -30
  62. package/dist/hono.mjs.map +1 -1
  63. package/dist/index.d.ts +11 -1
  64. package/dist/index.js +1142 -78
  65. package/dist/index.js.map +1 -1
  66. package/dist/index.mjs +1135 -79
  67. package/dist/index.mjs.map +1 -1
  68. package/dist/nestjs.js +455 -30
  69. package/dist/nestjs.js.map +1 -1
  70. package/dist/nestjs.mjs +455 -30
  71. package/dist/nestjs.mjs.map +1 -1
  72. package/dist/nextjs.js +455 -30
  73. package/dist/nextjs.js.map +1 -1
  74. package/dist/nextjs.mjs +455 -30
  75. package/dist/nextjs.mjs.map +1 -1
  76. package/dist/nitro.js +4726 -0
  77. package/dist/nitro.js.map +1 -0
  78. package/dist/nitro.mjs +4698 -0
  79. package/dist/nitro.mjs.map +1 -0
  80. package/dist/nuxt.js +4733 -0
  81. package/dist/nuxt.js.map +1 -0
  82. package/dist/nuxt.mjs +4705 -0
  83. package/dist/nuxt.mjs.map +1 -0
  84. package/dist/react-router.js +4644 -0
  85. package/dist/react-router.js.map +1 -0
  86. package/dist/react-router.mjs +4616 -0
  87. package/dist/react-router.mjs.map +1 -0
  88. package/dist/standalone.js +423 -53
  89. package/dist/standalone.js.map +1 -1
  90. package/dist/standalone.mjs +423 -53
  91. package/dist/standalone.mjs.map +1 -1
  92. package/dist/sveltekit.js +455 -30
  93. package/dist/sveltekit.js.map +1 -1
  94. package/dist/sveltekit.mjs +455 -30
  95. package/dist/sveltekit.mjs.map +1 -1
  96. package/dist/tanstack-start.js +455 -30
  97. package/dist/tanstack-start.js.map +1 -1
  98. package/dist/tanstack-start.mjs +455 -30
  99. package/dist/tanstack-start.mjs.map +1 -1
  100. package/dist/types/connectors/databuddy.d.ts +52 -0
  101. package/dist/types/core/config.d.ts +32 -0
  102. package/dist/types/core/logger.d.ts +2 -0
  103. package/dist/types/frameworks/astro.d.ts +32 -0
  104. package/dist/types/frameworks/nitro.d.ts +62 -0
  105. package/dist/types/frameworks/nuxt.d.ts +12 -0
  106. package/dist/types/frameworks/react-router.d.ts +33 -0
  107. package/dist/types/frameworks/shared.d.ts +24 -0
  108. package/dist/types/shared/client-log.d.ts +1 -1
  109. package/exports/connectors/databuddy.js +1 -0
  110. package/exports/connectors/databuddy.mjs +1 -0
  111. package/exports/frameworks/astro.js +1 -0
  112. package/exports/frameworks/astro.mjs +1 -0
  113. package/exports/frameworks/nitro.js +1 -0
  114. package/exports/frameworks/nitro.mjs +1 -0
  115. package/exports/frameworks/nuxt.js +1 -0
  116. package/exports/frameworks/nuxt.mjs +1 -0
  117. package/exports/frameworks/react-router.js +1 -0
  118. package/exports/frameworks/react-router.mjs +1 -0
  119. package/package.json +59 -2
  120. package/types/connectors/databuddy.d.ts +1 -0
  121. package/types/frameworks/astro.d.ts +1 -0
  122. package/types/frameworks/nitro.d.ts +1 -0
  123. package/types/frameworks/nuxt.d.ts +1 -0
  124. package/types/frameworks/react-router.d.ts +1 -0
@@ -0,0 +1,1451 @@
1
+ import { existsSync, readFileSync, writeFileSync, appendFileSync } from 'fs';
2
+ import { createJiti } from 'jiti';
3
+ import { resolve, dirname } from 'path';
4
+ import { z } from 'zod';
5
+ import { Databuddy } from '@databuddy/sdk/node';
6
+ import 'fflate';
7
+
8
+ // src/core/config.ts
9
+
10
+ // src/shared/log-value.ts
11
+ function normalizeError(error) {
12
+ const normalized = {
13
+ name: error.name,
14
+ message: error.message
15
+ };
16
+ if (error.stack) {
17
+ normalized.stack = error.stack;
18
+ }
19
+ const errorWithCause = error;
20
+ if (errorWithCause.cause !== void 0) {
21
+ normalized.cause = normalizeLogValue(errorWithCause.cause);
22
+ }
23
+ return normalized;
24
+ }
25
+ function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
26
+ if (value instanceof Error) {
27
+ return normalizeError(value);
28
+ }
29
+ if (typeof value === "function") {
30
+ return `[Function: ${value.name || "anonymous"}]`;
31
+ }
32
+ if (typeof value === "symbol") {
33
+ return value.toString();
34
+ }
35
+ if (value === void 0 || value === null) {
36
+ return value;
37
+ }
38
+ if (Array.isArray(value)) {
39
+ return value.map((entry) => normalizeLogValue(entry, seen));
40
+ }
41
+ if (typeof value === "object") {
42
+ if (seen.has(value)) {
43
+ return "[Circular]";
44
+ }
45
+ seen.add(value);
46
+ const normalized = {};
47
+ for (const [key, entry] of Object.entries(value)) {
48
+ normalized[key] = normalizeLogValue(entry, seen);
49
+ }
50
+ seen.delete(value);
51
+ return normalized;
52
+ }
53
+ return value;
54
+ }
55
+ function serializeLogMessage(message) {
56
+ if (typeof message === "string") {
57
+ return message;
58
+ }
59
+ if (message instanceof Error) {
60
+ return message.message || message.name;
61
+ }
62
+ const normalized = normalizeLogValue(message);
63
+ if (typeof normalized === "string") {
64
+ return normalized;
65
+ }
66
+ try {
67
+ const serialized = JSON.stringify(normalized, null, 2);
68
+ return serialized ?? String(normalized);
69
+ } catch {
70
+ return String(normalized);
71
+ }
72
+ }
73
+ var absoluteHttpUrlSchema = z.string().url().refine((value) => {
74
+ try {
75
+ const url = new URL(value);
76
+ return url.protocol === "http:" || url.protocol === "https:";
77
+ } catch {
78
+ return false;
79
+ }
80
+ }, {
81
+ message: "Expected an absolute http(s) URL"
82
+ });
83
+ var plainObjectSchema = z.custom(
84
+ (value) => {
85
+ return value !== null && typeof value === "object" && !Array.isArray(value);
86
+ },
87
+ {
88
+ message: "Expected a plain object"
89
+ }
90
+ );
91
+ var nonEmptyStringSchema = z.string().trim().min(1);
92
+ function isAbsoluteHttpUrl(value) {
93
+ return absoluteHttpUrlSchema.safeParse(value).success;
94
+ }
95
+ function isPlainObject(value) {
96
+ return plainObjectSchema.safeParse(value).success;
97
+ }
98
+ function hasNonEmptyString(value) {
99
+ return nonEmptyStringSchema.safeParse(value).success;
100
+ }
101
+
102
+ // src/shared/client-log.ts
103
+ var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
104
+ z.union([
105
+ z.literal("betterstack"),
106
+ z.literal("databuddy"),
107
+ z.literal("posthog"),
108
+ z.literal("sentry"),
109
+ z.undefined(),
110
+ z.object({
111
+ type: z.literal("otlp"),
112
+ name: nonEmptyStringSchema
113
+ })
114
+ ]);
115
+
116
+ // src/shared/once.ts
117
+ function createConsoleOnceLogger(method, warnedKeys3 = /* @__PURE__ */ new Set()) {
118
+ return (key, message, error) => {
119
+ if (warnedKeys3.has(key) || typeof console === "undefined") {
120
+ return;
121
+ }
122
+ const writer = console[method];
123
+ if (typeof writer !== "function") {
124
+ return;
125
+ }
126
+ warnedKeys3.add(key);
127
+ if (error === void 0) {
128
+ writer.call(console, message);
129
+ return;
130
+ }
131
+ writer.call(console, message, error);
132
+ };
133
+ }
134
+ function createWarnOnceLogger(warnedKeys3) {
135
+ return createConsoleOnceLogger("warn", warnedKeys3);
136
+ }
137
+ function createErrorOnceLogger(warnedKeys3) {
138
+ return createConsoleOnceLogger("error", warnedKeys3);
139
+ }
140
+
141
+ // src/core/config.ts
142
+ var PACKAGE_NAME = "@blyp/core";
143
+ var GITIGNORE_FILE_NAME = ".gitignore";
144
+ var CONFIG_FILE_NAMES = [
145
+ "blyp.config.ts",
146
+ "blyp.config.mts",
147
+ "blyp.config.cts",
148
+ "blyp.config.js",
149
+ "blyp.config.mjs",
150
+ "blyp.config.cjs",
151
+ "blyp.config.json"
152
+ ];
153
+ var CONFIG_FILE_NAME = "blyp.config.json";
154
+ var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
155
+ var DEFAULT_CONNECTOR_SERVICE_NAME = "blyp-app";
156
+ var DEFAULT_POSTHOG_SERVICE_NAME = DEFAULT_CONNECTOR_SERVICE_NAME;
157
+ var warnedKeys = /* @__PURE__ */ new Set();
158
+ var warnOnce = createWarnOnceLogger(warnedKeys);
159
+ var DEFAULT_ROTATION_CONFIG = {
160
+ enabled: true,
161
+ maxSizeBytes: 10 * 1024 * 1024,
162
+ maxArchives: 5,
163
+ compress: true
164
+ };
165
+ var DEFAULT_FILE_CONFIG = {
166
+ enabled: true,
167
+ dir: "",
168
+ archiveDir: "",
169
+ format: "ndjson",
170
+ rotation: DEFAULT_ROTATION_CONFIG
171
+ };
172
+ var DEFAULT_CLIENT_LOGGING_CONFIG = {
173
+ enabled: true,
174
+ path: DEFAULT_CLIENT_LOG_ENDPOINT
175
+ };
176
+ var DEFAULT_DATABASE_RETRY_CONFIG = {
177
+ maxRetries: 1,
178
+ backoffMs: 100
179
+ };
180
+ var DEFAULT_DATABASE_DELIVERY_CONFIG = {
181
+ strategy: "immediate",
182
+ batchSize: 1,
183
+ flushIntervalMs: 250,
184
+ maxQueueSize: 1e3,
185
+ overflowStrategy: "drop-oldest",
186
+ flushTimeoutMs: 5e3,
187
+ retry: DEFAULT_DATABASE_RETRY_CONFIG
188
+ };
189
+ var DEFAULT_CONFIG = {
190
+ pretty: true,
191
+ level: "info",
192
+ destination: "file",
193
+ file: DEFAULT_FILE_CONFIG,
194
+ clientLogging: DEFAULT_CLIENT_LOGGING_CONFIG,
195
+ connectors: {}
196
+ };
197
+ var cachedConfig = null;
198
+ function findNearestPackageName(startDir) {
199
+ let currentDir = startDir;
200
+ while (true) {
201
+ const packageJsonPath = resolve(currentDir, "package.json");
202
+ if (existsSync(packageJsonPath)) {
203
+ try {
204
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
205
+ if (hasNonEmptyString(packageJson.name)) {
206
+ return packageJson.name;
207
+ }
208
+ } catch {
209
+ }
210
+ }
211
+ const parentDir = dirname(currentDir);
212
+ if (parentDir === currentDir) {
213
+ return void 0;
214
+ }
215
+ currentDir = parentDir;
216
+ }
217
+ }
218
+ function resolveDefaultConnectorServiceName(cwd = process.cwd()) {
219
+ return findNearestPackageName(cwd) ?? DEFAULT_POSTHOG_SERVICE_NAME;
220
+ }
221
+ function getBootstrapConfig() {
222
+ return {
223
+ pretty: true,
224
+ level: "info",
225
+ destination: "file",
226
+ file: {
227
+ enabled: true,
228
+ format: "ndjson",
229
+ rotation: {
230
+ enabled: true,
231
+ maxSizeBytes: 10 * 1024 * 1024,
232
+ maxArchives: 5,
233
+ compress: true
234
+ }
235
+ },
236
+ clientLogging: {
237
+ enabled: true,
238
+ path: DEFAULT_CLIENT_LOG_ENDPOINT
239
+ },
240
+ connectors: {}
241
+ };
242
+ }
243
+ function shouldBootstrapProjectFiles(cwd) {
244
+ const packageJsonPath = resolve(cwd, "package.json");
245
+ if (!existsSync(packageJsonPath)) {
246
+ return true;
247
+ }
248
+ try {
249
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
250
+ return packageJson.name !== PACKAGE_NAME;
251
+ } catch {
252
+ return true;
253
+ }
254
+ }
255
+ function ensureConfigFile(cwd) {
256
+ if (CONFIG_FILE_NAMES.some((fileName) => existsSync(resolve(cwd, fileName)))) {
257
+ return;
258
+ }
259
+ const configPath = resolve(cwd, CONFIG_FILE_NAME);
260
+ if (existsSync(configPath)) {
261
+ return;
262
+ }
263
+ try {
264
+ writeFileSync(configPath, `${JSON.stringify(getBootstrapConfig(), null, 2)}
265
+ `);
266
+ } catch (error) {
267
+ console.error("[Blyp] Warning: Failed to create blyp.config.json:", error);
268
+ }
269
+ }
270
+ function ensureLogsIgnored(cwd) {
271
+ const gitignorePath = resolve(cwd, GITIGNORE_FILE_NAME);
272
+ if (!existsSync(gitignorePath)) {
273
+ try {
274
+ writeFileSync(gitignorePath, "logs\n");
275
+ } catch (error) {
276
+ console.error("[Blyp] Warning: Failed to create .gitignore:", error);
277
+ }
278
+ return;
279
+ }
280
+ try {
281
+ const currentContent = readFileSync(gitignorePath, "utf-8");
282
+ if (/^(?:\/?logs\/?)\s*$/m.test(currentContent)) {
283
+ return;
284
+ }
285
+ const separator = currentContent.endsWith("\n") ? "" : "\n";
286
+ appendFileSync(gitignorePath, `${separator}logs
287
+ `);
288
+ } catch (error) {
289
+ console.error("[Blyp] Warning: Failed to update .gitignore:", error);
290
+ }
291
+ }
292
+ function bootstrapProjectFiles() {
293
+ const cwd = process.cwd();
294
+ if (!shouldBootstrapProjectFiles(cwd)) {
295
+ return;
296
+ }
297
+ ensureConfigFile(cwd);
298
+ ensureLogsIgnored(cwd);
299
+ }
300
+ function findConfigFile() {
301
+ const cwd = process.cwd();
302
+ const matches = CONFIG_FILE_NAMES.map((fileName) => resolve(cwd, fileName)).filter((filePath) => existsSync(filePath));
303
+ if (matches.length === 0) {
304
+ return null;
305
+ }
306
+ if (matches.length > 1) {
307
+ const preferred = matches[0];
308
+ warnOnce(
309
+ `config-multiple:${preferred}`,
310
+ `[Blyp] Warning: Multiple config files found. Using ${preferred} and ignoring ${matches.slice(1).join(", ")}.`
311
+ );
312
+ }
313
+ const selectedPath = matches[0];
314
+ return {
315
+ path: selectedPath,
316
+ type: selectedPath.endsWith(".json") ? "json" : "jiti"
317
+ };
318
+ }
319
+ function normalizeLoadedConfig(value, configPath) {
320
+ const normalized = value && typeof value === "object" && "default" in value && value.default !== void 0 ? value.default : value;
321
+ if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
322
+ warnOnce(
323
+ `config-invalid:${configPath}`,
324
+ `[Blyp] Warning: Config file ${configPath} did not export an object. Falling back to defaults.`
325
+ );
326
+ return {};
327
+ }
328
+ return normalized;
329
+ }
330
+ function parseJsonConfigFile(configPath) {
331
+ try {
332
+ const content = readFileSync(configPath, "utf-8");
333
+ return normalizeLoadedConfig(JSON.parse(content), configPath);
334
+ } catch (error) {
335
+ console.error("[Blyp] Warning: Failed to parse blyp.config.json:", error);
336
+ return {};
337
+ }
338
+ }
339
+ function parseExecutableConfigFile(configPath) {
340
+ try {
341
+ const jiti = createJiti(process.cwd(), {
342
+ interopDefault: true,
343
+ moduleCache: false,
344
+ fsCache: false
345
+ });
346
+ return normalizeLoadedConfig(jiti(configPath), configPath);
347
+ } catch (error) {
348
+ console.error(`[Blyp] Warning: Failed to load ${configPath}:`, error);
349
+ return {};
350
+ }
351
+ }
352
+ function parseConfigFile(config) {
353
+ return config.type === "json" ? parseJsonConfigFile(config.path) : parseExecutableConfigFile(config.path);
354
+ }
355
+ function isPrismaAdapter(value) {
356
+ return !!value && typeof value === "object" && value.type === "prisma";
357
+ }
358
+ function isDrizzleAdapter(value) {
359
+ return !!value && typeof value === "object" && value.type === "drizzle";
360
+ }
361
+ function mergeDatabaseRetryConfig(base, override) {
362
+ return {
363
+ ...DEFAULT_DATABASE_RETRY_CONFIG,
364
+ ...base,
365
+ ...override
366
+ };
367
+ }
368
+ function mergeDatabaseDeliveryConfig(base, override) {
369
+ return {
370
+ ...DEFAULT_DATABASE_DELIVERY_CONFIG,
371
+ ...base,
372
+ ...override,
373
+ retry: mergeDatabaseRetryConfig(base?.retry, override?.retry)
374
+ };
375
+ }
376
+ function hasPrismaDelegate(adapter) {
377
+ const model = adapter.model ?? "blypLog";
378
+ const client = adapter.client;
379
+ const delegate = client?.[model];
380
+ return !!delegate && typeof delegate.create === "function";
381
+ }
382
+ function hasDrizzleAdapterShape(adapter) {
383
+ const db = adapter.db;
384
+ return !!db && typeof db.insert === "function" && adapter.table !== void 0;
385
+ }
386
+ function resolveDatabaseLoggerConfig(config, sourceType) {
387
+ if (!config) {
388
+ return void 0;
389
+ }
390
+ const adapter = config.adapter;
391
+ let ready = false;
392
+ if (sourceType === "json") {
393
+ warnOnce(
394
+ "database-json-config",
395
+ "[Blyp] Warning: Database logging requires an executable blyp config file. Database destination remains disabled until you move this config to blyp.config.ts/js."
396
+ );
397
+ } else if (config.dialect !== "postgres" && config.dialect !== "mysql") {
398
+ warnOnce(
399
+ `database-dialect:${String(config.dialect)}`,
400
+ `[Blyp] Warning: Unsupported database dialect "${String(config.dialect)}". Database logging is disabled.`
401
+ );
402
+ } else if (!adapter) {
403
+ warnOnce(
404
+ "database-adapter-missing",
405
+ "[Blyp] Warning: Database logging is enabled without an adapter. Database logging is disabled."
406
+ );
407
+ } else if (isPrismaAdapter(adapter)) {
408
+ ready = hasPrismaDelegate({
409
+ ...adapter,
410
+ model: adapter.model ?? "blypLog"
411
+ });
412
+ if (!ready) {
413
+ warnOnce(
414
+ "database-prisma-missing",
415
+ `[Blyp] Warning: Prisma database adapter is missing the "${adapter.model ?? "blypLog"}" delegate or its create method. Database logging is disabled.`
416
+ );
417
+ }
418
+ } else if (isDrizzleAdapter(adapter)) {
419
+ ready = hasDrizzleAdapterShape(adapter);
420
+ if (!ready) {
421
+ warnOnce(
422
+ "database-drizzle-missing",
423
+ "[Blyp] Warning: Drizzle database adapter is missing a db.insert function or table reference. Database logging is disabled."
424
+ );
425
+ }
426
+ }
427
+ const normalizedAdapter = isPrismaAdapter(adapter) ? {
428
+ ...adapter,
429
+ model: adapter.model ?? "blypLog"
430
+ } : adapter;
431
+ return {
432
+ dialect: config.dialect,
433
+ adapter: normalizedAdapter,
434
+ delivery: mergeDatabaseDeliveryConfig(void 0, config.delivery),
435
+ ready,
436
+ status: ready ? "enabled" : "missing"
437
+ };
438
+ }
439
+ function mergeRotationConfig(base, override) {
440
+ return {
441
+ ...DEFAULT_ROTATION_CONFIG,
442
+ ...base,
443
+ ...override
444
+ };
445
+ }
446
+ function mergeFileConfig(base, override) {
447
+ return {
448
+ ...DEFAULT_FILE_CONFIG,
449
+ ...base,
450
+ ...override,
451
+ rotation: mergeRotationConfig(base?.rotation, override?.rotation)
452
+ };
453
+ }
454
+ function mergeClientLoggingConfig(base, override) {
455
+ return {
456
+ ...DEFAULT_CLIENT_LOGGING_CONFIG,
457
+ ...base,
458
+ ...override,
459
+ path: override?.path ?? base?.path ?? DEFAULT_CLIENT_LOGGING_CONFIG.path
460
+ };
461
+ }
462
+ function mergeDatabaseLoggerConfig(base, override, sourceType) {
463
+ if (!base && !override) {
464
+ return void 0;
465
+ }
466
+ return resolveDatabaseLoggerConfig(
467
+ {
468
+ dialect: override?.dialect ?? base?.dialect,
469
+ adapter: override?.adapter ?? base?.adapter,
470
+ delivery: {
471
+ ...base?.delivery ?? {},
472
+ ...override?.delivery ?? {},
473
+ retry: {
474
+ ...base?.delivery?.retry ?? {},
475
+ ...override?.delivery?.retry ?? {}
476
+ }
477
+ }
478
+ },
479
+ sourceType
480
+ );
481
+ }
482
+ function mergePostHogConnectorConfig(base, override) {
483
+ const enabled = override?.enabled ?? base?.enabled ?? false;
484
+ const projectKey = override?.projectKey ?? base?.projectKey;
485
+ const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
486
+ const errorTrackingMode = override?.errorTracking?.mode ?? baseErrorTracking?.mode ?? "auto";
487
+ const errorTrackingEnabled = override?.errorTracking?.enabled ?? baseErrorTracking?.enabled ?? enabled;
488
+ const errorTrackingReady = enabled && errorTrackingEnabled && typeof projectKey === "string" && projectKey.trim().length > 0;
489
+ return {
490
+ enabled,
491
+ mode: override?.mode ?? base?.mode ?? "auto",
492
+ projectKey,
493
+ host: override?.host ?? base?.host ?? DEFAULT_POSTHOG_HOST,
494
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
495
+ errorTracking: {
496
+ enabled: errorTrackingEnabled,
497
+ mode: errorTrackingMode,
498
+ enableExceptionAutocapture: override?.errorTracking?.enableExceptionAutocapture ?? baseErrorTracking?.enableExceptionAutocapture ?? errorTrackingMode === "auto",
499
+ ready: errorTrackingReady,
500
+ status: errorTrackingReady ? "enabled" : "missing"
501
+ }
502
+ };
503
+ }
504
+ function mergeDatabuddyConnectorConfig(base, override) {
505
+ const enabled = override?.enabled ?? base?.enabled ?? false;
506
+ const apiKey = override?.apiKey ?? base?.apiKey;
507
+ const websiteId = override?.websiteId ?? base?.websiteId;
508
+ const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
509
+ return {
510
+ enabled,
511
+ mode: override?.mode ?? base?.mode ?? "auto",
512
+ apiKey,
513
+ websiteId,
514
+ namespace: override?.namespace ?? base?.namespace,
515
+ source: override?.source ?? base?.source,
516
+ apiUrl: override?.apiUrl ?? base?.apiUrl,
517
+ debug: override?.debug ?? base?.debug ?? false,
518
+ enableBatching: override?.enableBatching ?? base?.enableBatching ?? true,
519
+ batchSize: override?.batchSize ?? base?.batchSize,
520
+ batchTimeout: override?.batchTimeout ?? base?.batchTimeout,
521
+ maxQueueSize: override?.maxQueueSize ?? base?.maxQueueSize,
522
+ ready,
523
+ status: ready ? "enabled" : "missing"
524
+ };
525
+ }
526
+ function mergeBetterStackConnectorConfig(base, override) {
527
+ const sourceToken = override?.sourceToken ?? base?.sourceToken;
528
+ const ingestingHost = override?.ingestingHost ?? base?.ingestingHost;
529
+ const enabled = override?.enabled ?? base?.enabled ?? false;
530
+ const baseErrorTracking = base?.enabled === true ? base?.errorTracking : void 0;
531
+ const errorTracking = mergeBetterStackErrorTrackingConfig(
532
+ enabled,
533
+ baseErrorTracking,
534
+ override?.errorTracking
535
+ );
536
+ const ready = enabled && hasNonEmptyString(sourceToken) && isAbsoluteHttpUrl(ingestingHost);
537
+ return {
538
+ enabled,
539
+ mode: override?.mode ?? base?.mode ?? "auto",
540
+ sourceToken,
541
+ ingestingHost,
542
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
543
+ errorTracking,
544
+ ready,
545
+ status: ready ? "enabled" : "missing"
546
+ };
547
+ }
548
+ function mergeBetterStackErrorTrackingConfig(connectorEnabled, base, override) {
549
+ const dsn = override?.dsn ?? base?.dsn;
550
+ const enabled = override?.enabled ?? base?.enabled ?? connectorEnabled;
551
+ const ready = enabled && hasNonEmptyString(dsn);
552
+ return {
553
+ enabled,
554
+ dsn,
555
+ tracesSampleRate: override?.tracesSampleRate ?? base?.tracesSampleRate ?? 1,
556
+ environment: override?.environment ?? base?.environment,
557
+ release: override?.release ?? base?.release,
558
+ ready,
559
+ status: ready ? "enabled" : "missing"
560
+ };
561
+ }
562
+ function mergeSentryConnectorConfig(base, override) {
563
+ const dsn = override?.dsn ?? base?.dsn;
564
+ const enabled = override?.enabled ?? base?.enabled ?? false;
565
+ const ready = enabled && typeof dsn === "string" && dsn.trim().length > 0;
566
+ return {
567
+ enabled,
568
+ mode: override?.mode ?? base?.mode ?? "auto",
569
+ dsn,
570
+ environment: override?.environment ?? base?.environment,
571
+ release: override?.release ?? base?.release,
572
+ ready,
573
+ status: ready ? "enabled" : "missing"
574
+ };
575
+ }
576
+ function mergeOTLPConnectorConfig(base, override) {
577
+ const endpoint = override?.endpoint ?? base?.endpoint;
578
+ const enabled = override?.enabled ?? base?.enabled ?? false;
579
+ const resolvedHeaders = {
580
+ ...{},
581
+ ...override?.headers ?? {}
582
+ };
583
+ const ready = enabled && isAbsoluteHttpUrl(endpoint);
584
+ return {
585
+ name: override?.name ?? base?.name ?? "",
586
+ enabled,
587
+ mode: override?.mode ?? base?.mode ?? "auto",
588
+ endpoint,
589
+ headers: resolvedHeaders,
590
+ auth: override?.auth ?? base?.auth,
591
+ serviceName: override?.serviceName ?? base?.serviceName ?? resolveDefaultConnectorServiceName(),
592
+ ready,
593
+ status: ready ? "enabled" : "missing"
594
+ };
595
+ }
596
+ function mergeOTLPConnectorsConfig(base, override) {
597
+ const source = override ?? base ?? [];
598
+ const deduped = /* @__PURE__ */ new Map();
599
+ for (const connector of source) {
600
+ if (!connector || typeof connector.name !== "string" || connector.name.length === 0) {
601
+ continue;
602
+ }
603
+ if (deduped.has(connector.name)) {
604
+ warnOnce(
605
+ `otlp-duplicate:${connector.name}`,
606
+ `[Blyp] Warning: Duplicate OTLP connector name "${connector.name}" found. Using the last definition.`
607
+ );
608
+ }
609
+ deduped.set(connector.name, mergeOTLPConnectorConfig(void 0, connector));
610
+ }
611
+ return Array.from(deduped.values());
612
+ }
613
+ function mergeConnectorsConfig(base, override) {
614
+ return {
615
+ betterstack: mergeBetterStackConnectorConfig(base?.betterstack, override?.betterstack),
616
+ databuddy: mergeDatabuddyConnectorConfig(base?.databuddy, override?.databuddy),
617
+ posthog: mergePostHogConnectorConfig(base?.posthog, override?.posthog),
618
+ sentry: mergeSentryConnectorConfig(base?.sentry, override?.sentry),
619
+ otlp: mergeOTLPConnectorsConfig(base?.otlp, override?.otlp)
620
+ };
621
+ }
622
+ function mergeBlypConfig(base, override = {}, options = {}) {
623
+ return {
624
+ ...base,
625
+ ...override,
626
+ destination: override.destination ?? base.destination ?? "file",
627
+ file: mergeFileConfig(base.file, override.file),
628
+ database: mergeDatabaseLoggerConfig(base.database, override.database, options.configFileType),
629
+ clientLogging: mergeClientLoggingConfig(base.clientLogging, override.clientLogging),
630
+ connectors: mergeConnectorsConfig(base.connectors, override.connectors)
631
+ };
632
+ }
633
+ function loadConfig() {
634
+ if (cachedConfig !== null) {
635
+ return cachedConfig;
636
+ }
637
+ bootstrapProjectFiles();
638
+ const configFile = findConfigFile();
639
+ if (configFile) {
640
+ const userConfig = parseConfigFile(configFile);
641
+ cachedConfig = mergeBlypConfig(DEFAULT_CONFIG, userConfig, {
642
+ configFileType: configFile.type
643
+ });
644
+ } else {
645
+ cachedConfig = mergeBlypConfig(DEFAULT_CONFIG);
646
+ }
647
+ return cachedConfig;
648
+ }
649
+ function resolveConfig(overrides = {}) {
650
+ return mergeBlypConfig(loadConfig(), overrides);
651
+ }
652
+
653
+ // src/core/log-record.ts
654
+ var RECORD_LEVELS = {
655
+ success: "success",
656
+ critical: "critical",
657
+ warning: "warning",
658
+ info: "info",
659
+ debug: "debug",
660
+ error: "error",
661
+ warn: "warning",
662
+ table: "table"
663
+ };
664
+ function normalizePath(filePath) {
665
+ return filePath.replace(/\\/g, "/");
666
+ }
667
+ function isInternalLoggerFrame(filePath) {
668
+ const normalizedPath = normalizePath(filePath);
669
+ 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/");
670
+ }
671
+ function formatCallerPath(filePath) {
672
+ const normalizedPath = normalizePath(filePath);
673
+ const normalizedCwd = normalizePath(process.cwd());
674
+ return normalizedPath.startsWith(`${normalizedCwd}/`) ? normalizedPath.slice(normalizedCwd.length + 1) : normalizedPath;
675
+ }
676
+ function getCallerLocation() {
677
+ try {
678
+ const stack = new Error().stack;
679
+ if (!stack) {
680
+ return { file: null, line: null };
681
+ }
682
+ const lines = stack.split("\n");
683
+ let fallback = null;
684
+ for (let index = 2; index < lines.length; index += 1) {
685
+ const line = lines[index];
686
+ if (!line) {
687
+ continue;
688
+ }
689
+ const match = line.match(/\((.*):(\d+):\d+\)/) || line.match(/at\s+(.*):(\d+):(\d+)/);
690
+ if (!match) {
691
+ continue;
692
+ }
693
+ const fileName = match[1] || "";
694
+ const lineNumber = parseInt(match[2] || "0", 10) || null;
695
+ if (fileName && !fileName.includes("node_modules") && !isInternalLoggerFrame(fileName)) {
696
+ const formattedPath = formatCallerPath(fileName);
697
+ const normalizedFormattedPath = normalizePath(formattedPath);
698
+ if (!normalizedFormattedPath.startsWith("dist/")) {
699
+ return { file: formattedPath, line: lineNumber };
700
+ }
701
+ fallback ?? (fallback = { file: formattedPath, line: lineNumber });
702
+ }
703
+ }
704
+ if (fallback) {
705
+ return fallback;
706
+ }
707
+ } catch {
708
+ return { file: null, line: null };
709
+ }
710
+ return { file: null, line: null };
711
+ }
712
+ var serializeMessage = serializeLogMessage;
713
+ function stripAnsi(value) {
714
+ return value.replace(/\u001b\[[0-9;]*m/g, "");
715
+ }
716
+ function buildRecord(level, message, args, bindings) {
717
+ const { file, line } = getCallerLocation();
718
+ const serializedMessage = serializeMessage(message);
719
+ const record = {
720
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
721
+ level: RECORD_LEVELS[level],
722
+ message: stripAnsi(serializedMessage)
723
+ };
724
+ if (message instanceof Error) {
725
+ record.error = normalizeError(message);
726
+ }
727
+ if (file) {
728
+ record.caller = line !== null ? `${file}:${line}` : file;
729
+ }
730
+ if (args.length === 1) {
731
+ record.data = normalizeLogValue(args[0]);
732
+ } else if (args.length > 1) {
733
+ record.data = normalizeLogValue(args);
734
+ }
735
+ if (Object.keys(bindings).length > 0) {
736
+ record.bindings = normalizeLogValue(bindings);
737
+ }
738
+ return record;
739
+ }
740
+ function buildStructuredRecord(level, message, payload, bindings) {
741
+ const { file, line } = getCallerLocation();
742
+ const normalizedPayload = normalizeLogValue(payload);
743
+ const record = {
744
+ message: stripAnsi(message),
745
+ ...normalizedPayload
746
+ };
747
+ if (file) {
748
+ record.caller = line !== null ? `${file}:${line}` : file;
749
+ }
750
+ if (Object.keys(bindings).length > 0) {
751
+ record.bindings = normalizeLogValue(bindings);
752
+ }
753
+ record.level = typeof normalizedPayload.level === "string" && normalizedPayload.level.length > 0 ? normalizedPayload.level : RECORD_LEVELS[level];
754
+ record.timestamp = typeof normalizedPayload.timestamp === "string" && normalizedPayload.timestamp.length > 0 ? normalizedPayload.timestamp : (/* @__PURE__ */ new Date()).toISOString();
755
+ return record;
756
+ }
757
+ function resolveStructuredWriteLevel(level) {
758
+ switch (level) {
759
+ case "debug":
760
+ return "debug";
761
+ case "warning":
762
+ return "warning";
763
+ case "warn":
764
+ return "warn";
765
+ case "error":
766
+ return "error";
767
+ case "success":
768
+ return "success";
769
+ case "critical":
770
+ return "critical";
771
+ case "table":
772
+ return "table";
773
+ case "info":
774
+ default:
775
+ return "info";
776
+ }
777
+ }
778
+
779
+ // src/core/structured-log.ts
780
+ function serializeMessage2(message) {
781
+ if (typeof message === "string") {
782
+ return message;
783
+ }
784
+ if (message !== null && typeof message === "object") {
785
+ try {
786
+ return JSON.stringify(
787
+ message,
788
+ (_key, value) => {
789
+ if (typeof value === "function") {
790
+ return `[Function: ${value.name || "anonymous"}]`;
791
+ }
792
+ if (value === void 0) {
793
+ return "[undefined]";
794
+ }
795
+ if (typeof value === "symbol") {
796
+ return value.toString();
797
+ }
798
+ return value;
799
+ },
800
+ 2
801
+ );
802
+ } catch {
803
+ return "[Object]";
804
+ }
805
+ }
806
+ return String(message);
807
+ }
808
+ function normalizeEventData(message, args) {
809
+ if (typeof message === "string") {
810
+ if (args.length === 0) {
811
+ return void 0;
812
+ }
813
+ return args.length === 1 ? args[0] : args;
814
+ }
815
+ const values = [message, ...args];
816
+ return values.length === 1 ? values[0] : values;
817
+ }
818
+ function normalizeDetails(value) {
819
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
820
+ return void 0;
821
+ }
822
+ return value;
823
+ }
824
+ function normalizeError2(error, fallbackStatus) {
825
+ if (error === void 0 || error === null) {
826
+ return fallbackStatus === void 0 || fallbackStatus < 400 ? void 0 : {
827
+ message: `HTTP ${fallbackStatus}`,
828
+ code: fallbackStatus,
829
+ type: "HttpError"
830
+ };
831
+ }
832
+ if (error instanceof Error) {
833
+ const errorLike = error;
834
+ return {
835
+ message: error.message,
836
+ code: errorLike.code,
837
+ type: errorLike.type ?? error.name ?? error.constructor?.name,
838
+ stack: error.stack,
839
+ why: errorLike.why,
840
+ fix: errorLike.fix,
841
+ link: errorLike.link,
842
+ details: normalizeDetails(errorLike.details),
843
+ cause: errorLike.cause
844
+ };
845
+ }
846
+ if (typeof error === "object") {
847
+ const record = error;
848
+ const statusCode = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : fallbackStatus;
849
+ return {
850
+ message: typeof record.message === "string" ? record.message : `HTTP ${statusCode ?? 500}`,
851
+ code: typeof record.code === "string" || typeof record.code === "number" ? record.code : statusCode,
852
+ type: typeof record.type === "string" ? record.type : typeof record.name === "string" ? record.name : "Error",
853
+ stack: typeof record.stack === "string" ? record.stack : void 0,
854
+ why: typeof record.why === "string" ? record.why : void 0,
855
+ fix: typeof record.fix === "string" ? record.fix : void 0,
856
+ link: typeof record.link === "string" ? record.link : void 0,
857
+ details: normalizeDetails(record.details),
858
+ cause: record.cause
859
+ };
860
+ }
861
+ return {
862
+ message: String(error),
863
+ code: fallbackStatus,
864
+ type: typeof error
865
+ };
866
+ }
867
+ function resolveEmitStatus(options) {
868
+ if (options.response && typeof options.response.status === "number") {
869
+ return options.response.status;
870
+ }
871
+ if (typeof options.status === "number") {
872
+ return options.status;
873
+ }
874
+ if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.statusCode === "number") {
875
+ return options.error.statusCode;
876
+ }
877
+ if (options.error && typeof options.error === "object" && options.error !== null && typeof options.error.status === "number") {
878
+ return options.error.status;
879
+ }
880
+ return options.error ? 500 : void 0;
881
+ }
882
+ function createStructuredLog(groupId, options) {
883
+ const startedAt = performance.now();
884
+ const fields = { ...options.initialFields ?? {} };
885
+ const events = [];
886
+ let emittedPayload;
887
+ options.onCreate?.();
888
+ const appendEvent = (level, message, args) => {
889
+ events.push({
890
+ level,
891
+ message: serializeMessage2(message),
892
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
893
+ ...normalizeEventData(message, args) === void 0 ? {} : { data: normalizeEventData(message, args) }
894
+ });
895
+ return structuredLog;
896
+ };
897
+ const structuredLog = {
898
+ set(extraFields) {
899
+ Object.assign(fields, extraFields);
900
+ return structuredLog;
901
+ },
902
+ debug(message, ...args) {
903
+ return appendEvent("debug", message, args);
904
+ },
905
+ info(message, ...args) {
906
+ return appendEvent("info", message, args);
907
+ },
908
+ warn(message, ...args) {
909
+ return appendEvent("warn", message, args);
910
+ },
911
+ warning(message, ...args) {
912
+ return appendEvent("warning", message, args);
913
+ },
914
+ error(message, ...args) {
915
+ return appendEvent("error", message, args);
916
+ },
917
+ success(message, ...args) {
918
+ return appendEvent("success", message, args);
919
+ },
920
+ critical(message, ...args) {
921
+ return appendEvent("critical", message, args);
922
+ },
923
+ table(message, data) {
924
+ return appendEvent("table", message, data === void 0 ? [] : [data]);
925
+ },
926
+ emit(emitOptions = {}) {
927
+ if (emittedPayload) {
928
+ return emittedPayload;
929
+ }
930
+ const defaultFields = options.resolveDefaultFields?.() ?? {};
931
+ const status = resolveEmitStatus(emitOptions);
932
+ const error = normalizeError2(emitOptions.error, status);
933
+ const level = emitOptions.level ?? (error ? "error" : "info");
934
+ const payload = {
935
+ ...defaultFields,
936
+ ...fields,
937
+ groupId,
938
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
939
+ level,
940
+ duration: Math.round(performance.now() - startedAt),
941
+ ...typeof status === "number" ? { status } : {},
942
+ ...events.length > 0 ? { events: [...events] } : {},
943
+ ...error ? { error } : {}
944
+ };
945
+ options.write(payload, emitOptions.message ?? "structured_log");
946
+ emittedPayload = payload;
947
+ options.onEmit?.(payload);
948
+ return payload;
949
+ }
950
+ };
951
+ return structuredLog;
952
+ }
953
+ function createSafeReplacer() {
954
+ const seen = /* @__PURE__ */ new WeakSet();
955
+ return (_key, value) => {
956
+ if (typeof value === "function") {
957
+ return `[Function: ${value.name || "anonymous"}]`;
958
+ }
959
+ if (value === void 0) {
960
+ return "[undefined]";
961
+ }
962
+ if (typeof value === "symbol") {
963
+ return value.toString();
964
+ }
965
+ if (value !== null && typeof value === "object") {
966
+ if (seen.has(value)) {
967
+ return "[Circular]";
968
+ }
969
+ seen.add(value);
970
+ }
971
+ return value;
972
+ };
973
+ }
974
+ function serializeLogRecord(record) {
975
+ return JSON.stringify(record, createSafeReplacer());
976
+ }
977
+
978
+ // src/connectors/shared.ts
979
+ function isBlypConfig(config) {
980
+ return isPlainObject(config) && ("connectors" in config || "pretty" in config || "level" in config);
981
+ }
982
+ function getPrimaryPayload(record) {
983
+ return isPlainObject(record.data) ? record.data : record;
984
+ }
985
+ function getField(record, key) {
986
+ if (key in record) {
987
+ const direct = record[key];
988
+ if (typeof direct === "string" || typeof direct === "number") {
989
+ return direct;
990
+ }
991
+ }
992
+ const payload = getPrimaryPayload(record);
993
+ const nested = payload[key];
994
+ if (typeof nested === "string" || typeof nested === "number") {
995
+ return nested;
996
+ }
997
+ return void 0;
998
+ }
999
+ function getClientPageField(record, key) {
1000
+ const payload = getPrimaryPayload(record);
1001
+ const page = isPlainObject(payload.page) ? payload.page : void 0;
1002
+ const value = page?.[key];
1003
+ return typeof value === "string" ? value : void 0;
1004
+ }
1005
+ function getClientSessionField(record, key) {
1006
+ const payload = getPrimaryPayload(record);
1007
+ const session = isPlainObject(payload.session) ? payload.session : void 0;
1008
+ const value = session?.[key];
1009
+ return typeof value === "string" ? value : void 0;
1010
+ }
1011
+ function getRecordType(record) {
1012
+ return getField(record, "type");
1013
+ }
1014
+
1015
+ // src/connectors/databuddy/sender.ts
1016
+ var warnedKeys2 = /* @__PURE__ */ new Set();
1017
+ var senderCache = /* @__PURE__ */ new Map();
1018
+ var testHooks = {};
1019
+ var warnOnce2 = createErrorOnceLogger(warnedKeys2);
1020
+ function registerShutdownHooks(key, shutdown) {
1021
+ const handlers = ["beforeExit", "SIGINT", "SIGTERM"];
1022
+ for (const event of handlers) {
1023
+ process.once(event, () => {
1024
+ void shutdown().catch((error) => {
1025
+ warnOnce2(
1026
+ `${key}:shutdown`,
1027
+ "[Blyp] Failed to flush Databuddy telemetry during shutdown.",
1028
+ error
1029
+ );
1030
+ });
1031
+ });
1032
+ }
1033
+ }
1034
+ function resolveConnectorConfig(config) {
1035
+ const connector = isBlypConfig(config) ? config.connectors?.databuddy : config;
1036
+ const enabled = connector?.enabled ?? false;
1037
+ const apiKey = connector?.apiKey;
1038
+ const websiteId = connector?.websiteId;
1039
+ const ready = enabled && hasNonEmptyString(apiKey) && hasNonEmptyString(websiteId);
1040
+ return {
1041
+ enabled,
1042
+ mode: connector?.mode ?? "auto",
1043
+ apiKey,
1044
+ websiteId,
1045
+ namespace: connector?.namespace,
1046
+ source: connector?.source,
1047
+ apiUrl: connector?.apiUrl,
1048
+ debug: connector?.debug ?? false,
1049
+ enableBatching: connector?.enableBatching ?? true,
1050
+ batchSize: connector?.batchSize,
1051
+ batchTimeout: connector?.batchTimeout,
1052
+ maxQueueSize: connector?.maxQueueSize,
1053
+ ready,
1054
+ status: ready ? "enabled" : "missing"
1055
+ };
1056
+ }
1057
+ function createDefaultClient(connector) {
1058
+ return new Databuddy({
1059
+ apiKey: connector.apiKey ?? "",
1060
+ ...connector.websiteId ? { websiteId: connector.websiteId } : {},
1061
+ ...connector.namespace ? { namespace: connector.namespace } : {},
1062
+ ...connector.source ? { source: connector.source } : {},
1063
+ ...connector.apiUrl ? { apiUrl: connector.apiUrl } : {},
1064
+ debug: connector.debug,
1065
+ enableBatching: connector.enableBatching,
1066
+ ...connector.batchSize !== void 0 ? { batchSize: connector.batchSize } : {},
1067
+ ...connector.batchTimeout !== void 0 ? { batchTimeout: connector.batchTimeout } : {},
1068
+ ...connector.maxQueueSize !== void 0 ? { maxQueueSize: connector.maxQueueSize } : {}
1069
+ });
1070
+ }
1071
+ function getDatabuddySenderKey(connector) {
1072
+ return JSON.stringify({
1073
+ enabled: connector.enabled,
1074
+ mode: connector.mode,
1075
+ apiKey: connector.apiKey ?? null,
1076
+ websiteId: connector.websiteId ?? null,
1077
+ namespace: connector.namespace ?? null,
1078
+ source: connector.source ?? null,
1079
+ apiUrl: connector.apiUrl ?? null,
1080
+ debug: connector.debug,
1081
+ enableBatching: connector.enableBatching,
1082
+ batchSize: connector.batchSize ?? null,
1083
+ batchTimeout: connector.batchTimeout ?? null,
1084
+ maxQueueSize: connector.maxQueueSize ?? null
1085
+ });
1086
+ }
1087
+ function getSessionId(record) {
1088
+ const direct = getField(record, "sessionId");
1089
+ if (hasNonEmptyString(direct)) {
1090
+ return direct;
1091
+ }
1092
+ return getClientSessionField(record, "sessionId");
1093
+ }
1094
+ function getAnonymousId(record) {
1095
+ const direct = getField(record, "anonymousId");
1096
+ if (hasNonEmptyString(direct)) {
1097
+ return direct;
1098
+ }
1099
+ const payload = getPrimaryPayload(record);
1100
+ if (isPlainObject(payload.metadata) && hasNonEmptyString(payload.metadata.databuddyAnonymousId)) {
1101
+ return payload.metadata.databuddyAnonymousId;
1102
+ }
1103
+ return void 0;
1104
+ }
1105
+ function getDatabuddyEventName(record) {
1106
+ const recordType = getRecordType(record);
1107
+ if (hasNonEmptyString(recordType)) {
1108
+ return recordType;
1109
+ }
1110
+ return "log";
1111
+ }
1112
+ function buildRecordProperties(record, source) {
1113
+ const properties = {
1114
+ blyp_level: record.level,
1115
+ blyp_source: source,
1116
+ blyp_payload: serializeLogRecord(record),
1117
+ message: typeof record.message === "string" ? record.message : String(record.message)
1118
+ };
1119
+ const caller = typeof record.caller === "string" ? record.caller : void 0;
1120
+ const groupId = getField(record, "groupId");
1121
+ const method = getField(record, "method");
1122
+ const path = getField(record, "path");
1123
+ const status = getField(record, "status");
1124
+ const duration = getField(record, "duration");
1125
+ const pagePath = getClientPageField(record, "pathname");
1126
+ const pageUrl = getClientPageField(record, "url");
1127
+ const sessionId = getClientSessionField(record, "sessionId");
1128
+ const pageId = getClientSessionField(record, "pageId");
1129
+ const ifTruthy = [
1130
+ ["blyp_type", getRecordType(record)],
1131
+ ["caller", caller],
1132
+ ["group_id", groupId],
1133
+ ["method", method],
1134
+ ["path", path],
1135
+ ["page_path", pagePath],
1136
+ ["page_url", pageUrl],
1137
+ ["session_id", sessionId],
1138
+ ["page_id", pageId]
1139
+ ];
1140
+ const ifDefined = [
1141
+ ["status_code", status],
1142
+ ["duration_ms", duration]
1143
+ ];
1144
+ for (const [key, value] of ifTruthy) {
1145
+ if (value) {
1146
+ properties[key] = value;
1147
+ }
1148
+ }
1149
+ for (const [key, value] of ifDefined) {
1150
+ if (value !== void 0) {
1151
+ properties[key] = value;
1152
+ }
1153
+ }
1154
+ return properties;
1155
+ }
1156
+ function createTrackEvent(record, source) {
1157
+ return {
1158
+ name: getDatabuddyEventName(record),
1159
+ anonymousId: getAnonymousId(record),
1160
+ sessionId: getSessionId(record),
1161
+ properties: buildRecordProperties(record, source)
1162
+ };
1163
+ }
1164
+ function normalizeExceptionProperties(value) {
1165
+ if (!isPlainObject(value)) {
1166
+ return {};
1167
+ }
1168
+ return normalizeLogValue(value);
1169
+ }
1170
+ function normalizeExceptionInput(value, fallbackMessage) {
1171
+ if (value instanceof Error) {
1172
+ return {
1173
+ message: value.message || fallbackMessage,
1174
+ properties: {
1175
+ error_type: value.name,
1176
+ ...value.stack ? { stack: value.stack } : {},
1177
+ ...normalizeExceptionProperties(value)
1178
+ }
1179
+ };
1180
+ }
1181
+ if (isPlainObject(value)) {
1182
+ const message = hasNonEmptyString(value.message) ? value.message : hasNonEmptyString(value.error) ? value.error : fallbackMessage;
1183
+ return {
1184
+ message,
1185
+ properties: normalizeExceptionProperties(value)
1186
+ };
1187
+ }
1188
+ if (typeof value === "string") {
1189
+ return {
1190
+ message: value,
1191
+ properties: {
1192
+ message: value
1193
+ }
1194
+ };
1195
+ }
1196
+ return {
1197
+ message: fallbackMessage,
1198
+ properties: {
1199
+ value: normalizeLogValue(value)
1200
+ }
1201
+ };
1202
+ }
1203
+ function createDatabuddySender(config) {
1204
+ const connector = resolveConnectorConfig(config);
1205
+ const senderKey = getDatabuddySenderKey(connector);
1206
+ const cached = senderCache.get(senderKey);
1207
+ if (cached) {
1208
+ return cached;
1209
+ }
1210
+ const key = `${connector.apiUrl ?? "default"}:${connector.mode}:${connector.apiKey ?? "missing"}`;
1211
+ const client = connector.ready ? testHooks.createClient?.(connector) ?? createDefaultClient(connector) : void 0;
1212
+ if (client) {
1213
+ registerShutdownHooks(key, async () => {
1214
+ await client.flush();
1215
+ });
1216
+ }
1217
+ const emitUnavailableWarning = () => {
1218
+ warnOnce2(
1219
+ `databuddy-unavailable:${key}`,
1220
+ "[Blyp] Databuddy connector is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy delivery."
1221
+ );
1222
+ };
1223
+ const emitExceptionUnavailableWarning = () => {
1224
+ warnOnce2(
1225
+ `databuddy-exception-unavailable:${key}`,
1226
+ "[Blyp] Databuddy error tracking is not configured. Databuddy requires both apiKey and websiteId. Skipping Databuddy exception capture."
1227
+ );
1228
+ };
1229
+ const sender = {
1230
+ enabled: connector.enabled,
1231
+ ready: connector.ready,
1232
+ mode: connector.mode,
1233
+ status: connector.status,
1234
+ shouldAutoForwardServerLogs() {
1235
+ return connector.ready && connector.mode === "auto";
1236
+ },
1237
+ shouldAutoCaptureExceptions() {
1238
+ return connector.ready && connector.mode === "auto";
1239
+ },
1240
+ send(record, options = {}) {
1241
+ if (!connector.ready || !client) {
1242
+ if (options.warnIfUnavailable) {
1243
+ emitUnavailableWarning();
1244
+ }
1245
+ return;
1246
+ }
1247
+ try {
1248
+ const result = client.track(createTrackEvent(record, options.source ?? "server"));
1249
+ if (result && typeof result.catch === "function") {
1250
+ void result.catch((error) => {
1251
+ warnOnce2(
1252
+ `databuddy-send:${key}`,
1253
+ "[Blyp] Failed to deliver log to Databuddy.",
1254
+ error
1255
+ );
1256
+ });
1257
+ }
1258
+ } catch (error) {
1259
+ warnOnce2(
1260
+ `databuddy-send:${key}`,
1261
+ "[Blyp] Failed to deliver log to Databuddy.",
1262
+ error
1263
+ );
1264
+ }
1265
+ },
1266
+ captureException(error, options = {}) {
1267
+ if (!connector.ready || !client) {
1268
+ if (options.warnIfUnavailable) {
1269
+ emitExceptionUnavailableWarning();
1270
+ }
1271
+ return;
1272
+ }
1273
+ const normalized = normalizeExceptionInput(
1274
+ error,
1275
+ options.source === "client" ? "Client error" : "Server error"
1276
+ );
1277
+ try {
1278
+ const result = client.track({
1279
+ name: "error",
1280
+ anonymousId: options.anonymousId,
1281
+ sessionId: options.sessionId,
1282
+ properties: {
1283
+ message: normalized.message,
1284
+ blyp_source: options.source ?? "server",
1285
+ blyp_level: "error",
1286
+ ...normalized.properties,
1287
+ ...options.properties ?? {}
1288
+ }
1289
+ });
1290
+ if (result && typeof result.catch === "function") {
1291
+ void result.catch((captureError) => {
1292
+ warnOnce2(
1293
+ `databuddy-capture:${key}`,
1294
+ "[Blyp] Failed to capture exception in Databuddy.",
1295
+ captureError
1296
+ );
1297
+ });
1298
+ }
1299
+ } catch (captureError) {
1300
+ warnOnce2(
1301
+ `databuddy-capture:${key}`,
1302
+ "[Blyp] Failed to capture exception in Databuddy.",
1303
+ captureError
1304
+ );
1305
+ }
1306
+ },
1307
+ async flush() {
1308
+ try {
1309
+ if (client) {
1310
+ await client.flush();
1311
+ }
1312
+ } catch (error) {
1313
+ warnOnce2(
1314
+ `databuddy-flush:${key}`,
1315
+ "[Blyp] Failed to flush Databuddy telemetry.",
1316
+ error
1317
+ );
1318
+ }
1319
+ }
1320
+ };
1321
+ senderCache.set(senderKey, sender);
1322
+ return sender;
1323
+ }
1324
+
1325
+ // src/connectors/databuddy/index.ts
1326
+ function resolveSender(config = {}) {
1327
+ return createDatabuddySender(resolveConfig({
1328
+ ...config.connectors ? { connectors: config.connectors } : {}
1329
+ }));
1330
+ }
1331
+ function createDatabuddyLoggerInstance(sender, bindings = {}) {
1332
+ const writeRecord = (level, message, args) => {
1333
+ sender.send(buildRecord(level, message, args, bindings), {
1334
+ source: "server",
1335
+ warnIfUnavailable: true
1336
+ });
1337
+ };
1338
+ const writeStructured = (payload, message) => {
1339
+ sender.send(
1340
+ buildStructuredRecord(
1341
+ resolveStructuredWriteLevel(payload.level),
1342
+ message,
1343
+ payload,
1344
+ bindings
1345
+ ),
1346
+ {
1347
+ source: "server",
1348
+ warnIfUnavailable: true
1349
+ }
1350
+ );
1351
+ };
1352
+ return {
1353
+ debug: (message, ...args) => {
1354
+ writeRecord("debug", message, args);
1355
+ },
1356
+ info: (message, ...args) => {
1357
+ writeRecord("info", message, args);
1358
+ },
1359
+ error: (message, ...args) => {
1360
+ writeRecord("error", message, args);
1361
+ },
1362
+ warn: (message, ...args) => {
1363
+ writeRecord("warn", message, args);
1364
+ },
1365
+ warning: (message, ...args) => {
1366
+ writeRecord("warning", message, args);
1367
+ },
1368
+ success: (message, ...args) => {
1369
+ writeRecord("success", message, args);
1370
+ },
1371
+ critical: (message, ...args) => {
1372
+ writeRecord("critical", message, args);
1373
+ },
1374
+ table: (message, data) => {
1375
+ writeRecord("table", message, data === void 0 ? [] : [data]);
1376
+ },
1377
+ flush: async () => {
1378
+ await sender.flush();
1379
+ },
1380
+ shutdown: async () => {
1381
+ await sender.flush();
1382
+ },
1383
+ createStructuredLog: (groupId, initial) => {
1384
+ return createStructuredLog(groupId, {
1385
+ initialFields: initial,
1386
+ write: writeStructured
1387
+ });
1388
+ },
1389
+ child: (childBindings) => {
1390
+ return createDatabuddyLoggerInstance(sender, {
1391
+ ...bindings,
1392
+ ...childBindings
1393
+ });
1394
+ }
1395
+ };
1396
+ }
1397
+ function createDatabuddyErrorTrackerInstance(sender, bindings = {}) {
1398
+ return {
1399
+ capture: (error, options = {}) => {
1400
+ sender.captureException(error, {
1401
+ source: "server",
1402
+ warnIfUnavailable: true,
1403
+ properties: {
1404
+ ...bindings,
1405
+ ...options.properties ?? {},
1406
+ blyp_source: "server",
1407
+ blyp_manual: true
1408
+ }
1409
+ });
1410
+ },
1411
+ child: (childBindings) => {
1412
+ return createDatabuddyErrorTrackerInstance(sender, {
1413
+ ...bindings,
1414
+ ...childBindings
1415
+ });
1416
+ }
1417
+ };
1418
+ }
1419
+ function createDatabuddyLogger(config = {}) {
1420
+ return createDatabuddyLoggerInstance(resolveSender(config));
1421
+ }
1422
+ function createStructuredDatabuddyLogger(groupId, initial, config = {}) {
1423
+ const sender = resolveSender(config);
1424
+ return createStructuredLog(groupId, {
1425
+ initialFields: initial,
1426
+ write: (payload, message) => {
1427
+ sender.send(
1428
+ buildStructuredRecord(
1429
+ resolveStructuredWriteLevel(payload.level),
1430
+ message,
1431
+ payload,
1432
+ {}
1433
+ ),
1434
+ {
1435
+ source: "server",
1436
+ warnIfUnavailable: true
1437
+ }
1438
+ );
1439
+ }
1440
+ });
1441
+ }
1442
+ function createDatabuddyErrorTracker(config = {}) {
1443
+ return createDatabuddyErrorTrackerInstance(resolveSender(config));
1444
+ }
1445
+ function captureDatabuddyException(error, options = {}, config = {}) {
1446
+ createDatabuddyErrorTracker(config).capture(error, options);
1447
+ }
1448
+
1449
+ export { captureDatabuddyException, createDatabuddyErrorTracker, createDatabuddyLogger, createStructuredDatabuddyLogger };
1450
+ //# sourceMappingURL=databuddy.mjs.map
1451
+ //# sourceMappingURL=databuddy.mjs.map