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