@blyp/core 0.1.21 → 0.1.23
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 +54 -522
- 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/better-agent/index.d.ts +3 -0
- package/dist/ai/better-agent/normalize.d.ts +18 -0
- package/dist/ai/better-agent/plugin.d.ts +3 -0
- package/dist/ai/better-agent/tracker.d.ts +35 -0
- package/dist/ai/better-agent.js +701 -0
- package/dist/ai/better-agent.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 +119 -0
- package/dist/ai/shared/types.d.ts +171 -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 +259 -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
package/dist/client.mjs
CHANGED
|
@@ -1,1132 +1 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
|
-
|
|
7
|
-
// src/shared/log-value.ts
|
|
8
|
-
function normalizeError(error) {
|
|
9
|
-
const normalized = {
|
|
10
|
-
name: error.name,
|
|
11
|
-
message: error.message
|
|
12
|
-
};
|
|
13
|
-
if (error.stack) {
|
|
14
|
-
normalized.stack = error.stack;
|
|
15
|
-
}
|
|
16
|
-
const errorWithCause = error;
|
|
17
|
-
if (errorWithCause.cause !== void 0) {
|
|
18
|
-
normalized.cause = normalizeLogValue(errorWithCause.cause);
|
|
19
|
-
}
|
|
20
|
-
return normalized;
|
|
21
|
-
}
|
|
22
|
-
function normalizeLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
23
|
-
if (value instanceof Error) {
|
|
24
|
-
return normalizeError(value);
|
|
25
|
-
}
|
|
26
|
-
if (typeof value === "function") {
|
|
27
|
-
return `[Function: ${value.name || "anonymous"}]`;
|
|
28
|
-
}
|
|
29
|
-
if (typeof value === "symbol") {
|
|
30
|
-
return value.toString();
|
|
31
|
-
}
|
|
32
|
-
if (value === void 0 || value === null) {
|
|
33
|
-
return value;
|
|
34
|
-
}
|
|
35
|
-
if (Array.isArray(value)) {
|
|
36
|
-
return value.map((entry) => normalizeLogValue(entry, seen));
|
|
37
|
-
}
|
|
38
|
-
if (typeof value === "object") {
|
|
39
|
-
if (seen.has(value)) {
|
|
40
|
-
return "[Circular]";
|
|
41
|
-
}
|
|
42
|
-
seen.add(value);
|
|
43
|
-
const normalized = {};
|
|
44
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
45
|
-
normalized[key] = normalizeLogValue(entry, seen);
|
|
46
|
-
}
|
|
47
|
-
seen.delete(value);
|
|
48
|
-
return normalized;
|
|
49
|
-
}
|
|
50
|
-
return value;
|
|
51
|
-
}
|
|
52
|
-
function serializeLogMessage(message) {
|
|
53
|
-
if (typeof message === "string") {
|
|
54
|
-
return message;
|
|
55
|
-
}
|
|
56
|
-
if (message instanceof Error) {
|
|
57
|
-
return message.message || message.name;
|
|
58
|
-
}
|
|
59
|
-
const normalized = normalizeLogValue(message);
|
|
60
|
-
if (typeof normalized === "string") {
|
|
61
|
-
return normalized;
|
|
62
|
-
}
|
|
63
|
-
try {
|
|
64
|
-
const serialized = JSON.stringify(normalized, null, 2);
|
|
65
|
-
return serialized ?? String(normalized);
|
|
66
|
-
} catch {
|
|
67
|
-
return String(normalized);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
z.string().url().refine((value) => {
|
|
71
|
-
try {
|
|
72
|
-
const url = new URL(value);
|
|
73
|
-
return url.protocol === "http:" || url.protocol === "https:";
|
|
74
|
-
} catch {
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
}, {
|
|
78
|
-
message: "Expected an absolute http(s) URL"
|
|
79
|
-
});
|
|
80
|
-
var plainObjectSchema = z.custom(
|
|
81
|
-
(value) => {
|
|
82
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
83
|
-
},
|
|
84
|
-
{
|
|
85
|
-
message: "Expected a plain object"
|
|
86
|
-
}
|
|
87
|
-
);
|
|
88
|
-
var nonEmptyStringSchema = z.string().trim().min(1);
|
|
89
|
-
function isPlainObject(value) {
|
|
90
|
-
return plainObjectSchema.safeParse(value).success;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// src/shared/client-log.ts
|
|
94
|
-
var DEFAULT_CLIENT_LOG_ENDPOINT = "/inngest";
|
|
95
|
-
var SESSION_STORAGE_KEY = "blyp:session-id";
|
|
96
|
-
z.union([
|
|
97
|
-
z.literal("betterstack"),
|
|
98
|
-
z.literal("databuddy"),
|
|
99
|
-
z.literal("posthog"),
|
|
100
|
-
z.literal("sentry"),
|
|
101
|
-
z.undefined(),
|
|
102
|
-
z.object({
|
|
103
|
-
type: z.literal("otlp"),
|
|
104
|
-
name: nonEmptyStringSchema
|
|
105
|
-
})
|
|
106
|
-
]);
|
|
107
|
-
function safeGet(getter) {
|
|
108
|
-
try {
|
|
109
|
-
return getter();
|
|
110
|
-
} catch {
|
|
111
|
-
return void 0;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function randomSegment() {
|
|
115
|
-
return Math.random().toString(36).slice(2, 10);
|
|
116
|
-
}
|
|
117
|
-
function createRandomId() {
|
|
118
|
-
const maybeCrypto = safeGet(() => globalThis.crypto);
|
|
119
|
-
const randomUUID = maybeCrypto && typeof maybeCrypto.randomUUID === "function" ? maybeCrypto.randomUUID.bind(maybeCrypto) : void 0;
|
|
120
|
-
if (randomUUID) {
|
|
121
|
-
return randomUUID();
|
|
122
|
-
}
|
|
123
|
-
return `${Date.now().toString(36)}-${randomSegment()}`;
|
|
124
|
-
}
|
|
125
|
-
function normalizeClientLogLevel(level) {
|
|
126
|
-
return level === "warn" ? "warning" : level;
|
|
127
|
-
}
|
|
128
|
-
function normalizeClientPayloadData(message, args) {
|
|
129
|
-
const normalizedArgs = args.map((entry) => normalizeLogValue(entry));
|
|
130
|
-
const messageData = message instanceof Error ? normalizeError(message) : void 0;
|
|
131
|
-
if (messageData !== void 0 && normalizedArgs.length === 0) {
|
|
132
|
-
return messageData;
|
|
133
|
-
}
|
|
134
|
-
const combined = messageData === void 0 ? normalizedArgs : [messageData, ...normalizedArgs];
|
|
135
|
-
if (combined.length === 0) {
|
|
136
|
-
return void 0;
|
|
137
|
-
}
|
|
138
|
-
if (combined.length === 1) {
|
|
139
|
-
return combined[0];
|
|
140
|
-
}
|
|
141
|
-
return combined;
|
|
142
|
-
}
|
|
143
|
-
function getBrowserPageContext() {
|
|
144
|
-
const location2 = safeGet(() => globalThis.location);
|
|
145
|
-
const document = safeGet(() => globalThis.document);
|
|
146
|
-
return {
|
|
147
|
-
url: location2?.href,
|
|
148
|
-
pathname: location2?.pathname,
|
|
149
|
-
search: location2?.search,
|
|
150
|
-
hash: location2?.hash,
|
|
151
|
-
title: document?.title,
|
|
152
|
-
referrer: document?.referrer
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
function getBrowserContext() {
|
|
156
|
-
const navigator2 = safeGet(() => globalThis.navigator);
|
|
157
|
-
return {
|
|
158
|
-
userAgent: navigator2?.userAgent,
|
|
159
|
-
language: navigator2?.language,
|
|
160
|
-
platform: navigator2?.platform
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
function getClientSessionId() {
|
|
164
|
-
const storage = safeGet(() => globalThis.sessionStorage);
|
|
165
|
-
const existing = safeGet(() => storage?.getItem(SESSION_STORAGE_KEY));
|
|
166
|
-
if (existing) {
|
|
167
|
-
return existing;
|
|
168
|
-
}
|
|
169
|
-
const sessionId = createRandomId();
|
|
170
|
-
safeGet(() => storage?.setItem(SESSION_STORAGE_KEY, sessionId));
|
|
171
|
-
return sessionId;
|
|
172
|
-
}
|
|
173
|
-
function normalizeMetadata(metadata) {
|
|
174
|
-
if (metadata === void 0) {
|
|
175
|
-
return void 0;
|
|
176
|
-
}
|
|
177
|
-
const resolved = typeof metadata === "function" ? safeGet(metadata) : metadata;
|
|
178
|
-
if (!isPlainObject(resolved)) {
|
|
179
|
-
return void 0;
|
|
180
|
-
}
|
|
181
|
-
return normalizeLogValue(resolved);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// src/shared/remote-delivery.ts
|
|
185
|
-
var DEFAULT_MAX_RETRIES = 3;
|
|
186
|
-
var DEFAULT_RETRY_DELAY_MS = 5e3;
|
|
187
|
-
var DEFAULT_MAX_QUEUE_SIZE = 100;
|
|
188
|
-
function clampInteger(value, fallback, minimum) {
|
|
189
|
-
if (!Number.isFinite(value)) {
|
|
190
|
-
return fallback;
|
|
191
|
-
}
|
|
192
|
-
return Math.max(minimum, Math.floor(value));
|
|
193
|
-
}
|
|
194
|
-
function safeCall(callback, value) {
|
|
195
|
-
if (!callback) {
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
try {
|
|
199
|
-
callback(value);
|
|
200
|
-
} catch {
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
function warn(message) {
|
|
204
|
-
if (typeof console === "undefined" || typeof console.warn !== "function") {
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
console.warn(message);
|
|
208
|
-
}
|
|
209
|
-
function formatWarningValue(value) {
|
|
210
|
-
return value === void 0 ? "unknown" : String(value);
|
|
211
|
-
}
|
|
212
|
-
function createRemoteDeliveryManager(options) {
|
|
213
|
-
const deliveryConfig = {
|
|
214
|
-
maxRetries: clampInteger(options.delivery?.maxRetries, DEFAULT_MAX_RETRIES, 0),
|
|
215
|
-
retryDelayMs: clampInteger(options.delivery?.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 0),
|
|
216
|
-
maxQueueSize: clampInteger(options.delivery?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE, 1),
|
|
217
|
-
warnOnFailure: options.delivery?.warnOnFailure ?? true,
|
|
218
|
-
onSuccess: options.delivery?.onSuccess,
|
|
219
|
-
onRetry: options.delivery?.onRetry,
|
|
220
|
-
onFailure: options.delivery?.onFailure,
|
|
221
|
-
onDrop: options.delivery?.onDrop
|
|
222
|
-
};
|
|
223
|
-
const queue = [];
|
|
224
|
-
let inFlight;
|
|
225
|
-
let flushTimer;
|
|
226
|
-
let isProcessing = false;
|
|
227
|
-
let unsubscribeFromResume;
|
|
228
|
-
const runtimeLabel = options.runtime === "browser" ? "client" : options.runtime;
|
|
229
|
-
const clearFlushTimer = () => {
|
|
230
|
-
if (!flushTimer) {
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
clearTimeout(flushTimer);
|
|
234
|
-
flushTimer = void 0;
|
|
235
|
-
};
|
|
236
|
-
const hasUnsentEvents = () => queue.length > 0 || inFlight !== void 0;
|
|
237
|
-
const refreshResumeSubscription = (flush2) => {
|
|
238
|
-
if (!options.subscribeToResume) {
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
if (hasUnsentEvents()) {
|
|
242
|
-
if (!unsubscribeFromResume) {
|
|
243
|
-
unsubscribeFromResume = options.subscribeToResume(() => {
|
|
244
|
-
const now = Date.now();
|
|
245
|
-
for (const item of queue) {
|
|
246
|
-
item.nextAttemptAt = now;
|
|
247
|
-
}
|
|
248
|
-
clearFlushTimer();
|
|
249
|
-
flush2();
|
|
250
|
-
}) ?? void 0;
|
|
251
|
-
}
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (unsubscribeFromResume) {
|
|
255
|
-
unsubscribeFromResume();
|
|
256
|
-
unsubscribeFromResume = void 0;
|
|
257
|
-
}
|
|
258
|
-
};
|
|
259
|
-
const warnDrop = (ctx) => {
|
|
260
|
-
if (!deliveryConfig.warnOnFailure) {
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
warn(
|
|
264
|
-
`[blyp/${runtimeLabel}] Dropped queued log "${ctx.droppedEvent.message}" (id: ${ctx.droppedEvent.id}) because the delivery queue reached ${ctx.maxQueueSize}. Keeping "${ctx.replacementEvent.message}" (id: ${ctx.replacementEvent.id}) instead.`
|
|
265
|
-
);
|
|
266
|
-
};
|
|
267
|
-
const warnFailure = (ctx, suppressWarning) => {
|
|
268
|
-
if (!deliveryConfig.warnOnFailure || suppressWarning) {
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
const details = [
|
|
272
|
-
`reason=${ctx.reason}`,
|
|
273
|
-
`attempt=${formatWarningValue(ctx.attempt)}`,
|
|
274
|
-
`status=${formatWarningValue(ctx.status)}`
|
|
275
|
-
];
|
|
276
|
-
if (ctx.error) {
|
|
277
|
-
details.push(`error=${ctx.error}`);
|
|
278
|
-
}
|
|
279
|
-
warn(
|
|
280
|
-
`[blyp/${runtimeLabel}] Failed to deliver log "${ctx.event.message}" (id: ${ctx.event.id}, ${details.join(", ")})`
|
|
281
|
-
);
|
|
282
|
-
};
|
|
283
|
-
const totalUnsentEvents = () => queue.length + (inFlight ? 1 : 0);
|
|
284
|
-
const scheduleFlush = (flush2) => {
|
|
285
|
-
clearFlushTimer();
|
|
286
|
-
if (queue.length === 0) {
|
|
287
|
-
refreshResumeSubscription(flush2);
|
|
288
|
-
return;
|
|
289
|
-
}
|
|
290
|
-
const nextAttemptAt = queue.reduce((lowest, item) => {
|
|
291
|
-
return Math.min(lowest, item.nextAttemptAt);
|
|
292
|
-
}, Number.POSITIVE_INFINITY);
|
|
293
|
-
const delay = Math.max(nextAttemptAt - Date.now(), 0);
|
|
294
|
-
flushTimer = setTimeout(() => {
|
|
295
|
-
flushTimer = void 0;
|
|
296
|
-
flush2();
|
|
297
|
-
}, delay);
|
|
298
|
-
refreshResumeSubscription(flush2);
|
|
299
|
-
};
|
|
300
|
-
const emitDrop = (droppedEvent, replacementEvent) => {
|
|
301
|
-
const context = {
|
|
302
|
-
runtime: options.runtime,
|
|
303
|
-
droppedEvent,
|
|
304
|
-
replacementEvent,
|
|
305
|
-
maxQueueSize: deliveryConfig.maxQueueSize,
|
|
306
|
-
reason: "queue_overflow"
|
|
307
|
-
};
|
|
308
|
-
safeCall(deliveryConfig.onDrop, context);
|
|
309
|
-
warnDrop(context);
|
|
310
|
-
};
|
|
311
|
-
const enforceQueueCapacity = () => {
|
|
312
|
-
while (totalUnsentEvents() > deliveryConfig.maxQueueSize && queue.length > 0) {
|
|
313
|
-
const droppedItem = queue.shift();
|
|
314
|
-
const replacementEvent = queue[queue.length - 1]?.event ?? inFlight?.event;
|
|
315
|
-
if (!droppedItem || !replacementEvent) {
|
|
316
|
-
break;
|
|
317
|
-
}
|
|
318
|
-
emitDrop(droppedItem.event, replacementEvent);
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
const getNextReadyIndex = () => {
|
|
322
|
-
const now = Date.now();
|
|
323
|
-
for (let index = 0; index < queue.length; index += 1) {
|
|
324
|
-
if (queue[index].nextAttemptAt <= now) {
|
|
325
|
-
return index;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
return -1;
|
|
329
|
-
};
|
|
330
|
-
const flush = async () => {
|
|
331
|
-
if (isProcessing) {
|
|
332
|
-
return;
|
|
333
|
-
}
|
|
334
|
-
isProcessing = true;
|
|
335
|
-
try {
|
|
336
|
-
while (true) {
|
|
337
|
-
const nextIndex = getNextReadyIndex();
|
|
338
|
-
if (nextIndex === -1) {
|
|
339
|
-
break;
|
|
340
|
-
}
|
|
341
|
-
const item = queue.splice(nextIndex, 1)[0];
|
|
342
|
-
if (!item) {
|
|
343
|
-
continue;
|
|
344
|
-
}
|
|
345
|
-
inFlight = item;
|
|
346
|
-
refreshResumeSubscription(() => {
|
|
347
|
-
void flush();
|
|
348
|
-
});
|
|
349
|
-
item.attempt += 1;
|
|
350
|
-
const result = await options.send(item.event);
|
|
351
|
-
inFlight = void 0;
|
|
352
|
-
if (result.outcome === "success") {
|
|
353
|
-
const context = {
|
|
354
|
-
runtime: options.runtime,
|
|
355
|
-
event: item.event,
|
|
356
|
-
attempt: item.attempt,
|
|
357
|
-
status: result.status,
|
|
358
|
-
transport: result.transport
|
|
359
|
-
};
|
|
360
|
-
safeCall(deliveryConfig.onSuccess, context);
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
if (result.outcome === "retry" && item.attempt <= deliveryConfig.maxRetries) {
|
|
364
|
-
item.nextAttemptAt = Date.now() + deliveryConfig.retryDelayMs;
|
|
365
|
-
queue.push(item);
|
|
366
|
-
const context = {
|
|
367
|
-
runtime: options.runtime,
|
|
368
|
-
event: item.event,
|
|
369
|
-
attempt: item.attempt,
|
|
370
|
-
retriesRemaining: deliveryConfig.maxRetries - (item.attempt - 1),
|
|
371
|
-
nextRetryAt: new Date(item.nextAttemptAt).toISOString(),
|
|
372
|
-
reason: result.reason,
|
|
373
|
-
status: result.status,
|
|
374
|
-
error: result.error
|
|
375
|
-
};
|
|
376
|
-
safeCall(deliveryConfig.onRetry, context);
|
|
377
|
-
continue;
|
|
378
|
-
}
|
|
379
|
-
const failureContext = {
|
|
380
|
-
runtime: options.runtime,
|
|
381
|
-
event: item.event,
|
|
382
|
-
attempt: item.attempt,
|
|
383
|
-
reason: result.reason,
|
|
384
|
-
status: result.status,
|
|
385
|
-
error: result.error
|
|
386
|
-
};
|
|
387
|
-
safeCall(deliveryConfig.onFailure, failureContext);
|
|
388
|
-
warnFailure(
|
|
389
|
-
failureContext,
|
|
390
|
-
result.outcome === "failure" ? result.suppressWarning : void 0
|
|
391
|
-
);
|
|
392
|
-
}
|
|
393
|
-
} finally {
|
|
394
|
-
isProcessing = false;
|
|
395
|
-
scheduleFlush(() => {
|
|
396
|
-
void flush();
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
};
|
|
400
|
-
return {
|
|
401
|
-
enqueue(event) {
|
|
402
|
-
queue.push({
|
|
403
|
-
event,
|
|
404
|
-
attempt: 0,
|
|
405
|
-
nextAttemptAt: Date.now()
|
|
406
|
-
});
|
|
407
|
-
enforceQueueCapacity();
|
|
408
|
-
scheduleFlush(() => {
|
|
409
|
-
void flush();
|
|
410
|
-
});
|
|
411
|
-
void flush();
|
|
412
|
-
}
|
|
413
|
-
};
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
// src/shared/once.ts
|
|
417
|
-
function createConsoleOnceLogger(method, warnedKeys = /* @__PURE__ */ new Set()) {
|
|
418
|
-
return (key, message, error) => {
|
|
419
|
-
if (warnedKeys.has(key) || typeof console === "undefined") {
|
|
420
|
-
return;
|
|
421
|
-
}
|
|
422
|
-
const writer = console[method];
|
|
423
|
-
if (typeof writer !== "function") {
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
warnedKeys.add(key);
|
|
427
|
-
if (error === void 0) {
|
|
428
|
-
writer.call(console, message);
|
|
429
|
-
return;
|
|
430
|
-
}
|
|
431
|
-
writer.call(console, message, error);
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
function createErrorOnceLogger(warnedKeys) {
|
|
435
|
-
return createConsoleOnceLogger("error", warnedKeys);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
// src/frameworks/client/logger.ts
|
|
439
|
-
var warnedMessages = /* @__PURE__ */ new Set();
|
|
440
|
-
var errorOnce = createErrorOnceLogger(warnedMessages);
|
|
441
|
-
function resolveHeaders(headers) {
|
|
442
|
-
return {
|
|
443
|
-
"content-type": "application/json",
|
|
444
|
-
...headers ?? {}
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
function shouldUseBeaconFallback(headers) {
|
|
448
|
-
return Object.keys(headers ?? {}).length === 0;
|
|
449
|
-
}
|
|
450
|
-
function isRetryableStatus(status) {
|
|
451
|
-
return status === 429 || status >= 500;
|
|
452
|
-
}
|
|
453
|
-
function isBrowserRuntime() {
|
|
454
|
-
return typeof navigator !== "undefined" && typeof location !== "undefined";
|
|
455
|
-
}
|
|
456
|
-
async function sendRemoteLog(config, payload) {
|
|
457
|
-
if (typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
458
|
-
return {
|
|
459
|
-
outcome: "retry",
|
|
460
|
-
reason: "offline"
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
if (typeof fetch !== "function") {
|
|
464
|
-
return {
|
|
465
|
-
outcome: "failure",
|
|
466
|
-
reason: "missing_transport",
|
|
467
|
-
suppressWarning: true
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
const body = JSON.stringify(payload);
|
|
471
|
-
const headers = resolveHeaders(config.headers);
|
|
472
|
-
const canUseBeacon = shouldUseBeaconFallback(config.headers) && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function" && typeof Blob !== "undefined";
|
|
473
|
-
try {
|
|
474
|
-
const response = await fetch(config.endpoint, {
|
|
475
|
-
method: "POST",
|
|
476
|
-
keepalive: true,
|
|
477
|
-
credentials: config.credentials,
|
|
478
|
-
headers,
|
|
479
|
-
body
|
|
480
|
-
});
|
|
481
|
-
if (response.ok) {
|
|
482
|
-
if (config.connector === "betterstack" && response.headers.get("x-blyp-betterstack-status") === "missing") {
|
|
483
|
-
errorOnce(
|
|
484
|
-
"betterstack-missing",
|
|
485
|
-
"[blyp/client] Better Stack connector requested but not configured on the server. Continuing without Better Stack forwarding."
|
|
486
|
-
);
|
|
487
|
-
}
|
|
488
|
-
if (config.connector === "databuddy" && response.headers.get("x-blyp-databuddy-status") === "missing") {
|
|
489
|
-
errorOnce(
|
|
490
|
-
"databuddy-missing",
|
|
491
|
-
"[blyp/client] Databuddy connector requested but not configured on the server. Continuing without Databuddy forwarding."
|
|
492
|
-
);
|
|
493
|
-
}
|
|
494
|
-
if (config.connector === "posthog" && response.headers.get("x-blyp-posthog-status") === "missing") {
|
|
495
|
-
errorOnce(
|
|
496
|
-
"posthog-missing",
|
|
497
|
-
"[blyp/client] PostHog connector requested but not configured on the server. Continuing without PostHog forwarding."
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
if (config.connector === "sentry" && response.headers.get("x-blyp-sentry-status") === "missing") {
|
|
501
|
-
errorOnce(
|
|
502
|
-
"sentry-missing",
|
|
503
|
-
"[blyp/client] Sentry not setup. Continuing without Sentry forwarding."
|
|
504
|
-
);
|
|
505
|
-
}
|
|
506
|
-
if (config.connector && typeof config.connector === "object" && config.connector.type === "otlp" && response.headers.get("x-blyp-otlp-status") === "missing") {
|
|
507
|
-
errorOnce(
|
|
508
|
-
`otlp-missing:${config.connector.name}`,
|
|
509
|
-
`[blyp/client] OTLP target "${config.connector.name}" was requested but not configured on the server. Continuing without OTLP forwarding.`
|
|
510
|
-
);
|
|
511
|
-
}
|
|
512
|
-
return {
|
|
513
|
-
outcome: "success",
|
|
514
|
-
transport: "fetch",
|
|
515
|
-
status: response.status
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
if (isRetryableStatus(response.status)) {
|
|
519
|
-
return {
|
|
520
|
-
outcome: "retry",
|
|
521
|
-
reason: "response_status",
|
|
522
|
-
status: response.status
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
return {
|
|
526
|
-
outcome: "failure",
|
|
527
|
-
reason: "response_status",
|
|
528
|
-
status: response.status
|
|
529
|
-
};
|
|
530
|
-
} catch (error) {
|
|
531
|
-
if (canUseBeacon) {
|
|
532
|
-
try {
|
|
533
|
-
if (navigator.sendBeacon(
|
|
534
|
-
config.endpoint,
|
|
535
|
-
new Blob([body], { type: "application/json" })
|
|
536
|
-
)) {
|
|
537
|
-
return {
|
|
538
|
-
outcome: "success",
|
|
539
|
-
transport: "beacon"
|
|
540
|
-
};
|
|
541
|
-
}
|
|
542
|
-
} catch {
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
return {
|
|
546
|
-
outcome: "retry",
|
|
547
|
-
reason: "network_error",
|
|
548
|
-
error: error instanceof Error ? error.message : String(error)
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
function emitLocalConsole(level, message, args) {
|
|
553
|
-
if (typeof console === "undefined") {
|
|
554
|
-
return;
|
|
555
|
-
}
|
|
556
|
-
const normalizedArgs = args.map((entry) => normalizeLogValue(entry));
|
|
557
|
-
const text = serializeLogMessage(message);
|
|
558
|
-
switch (level) {
|
|
559
|
-
case "table":
|
|
560
|
-
console.log(text);
|
|
561
|
-
if (normalizedArgs.length > 0 && typeof console.table === "function") {
|
|
562
|
-
console.table(normalizedArgs[0]);
|
|
563
|
-
}
|
|
564
|
-
return;
|
|
565
|
-
case "warning":
|
|
566
|
-
case "warn":
|
|
567
|
-
console.warn(text, ...normalizedArgs);
|
|
568
|
-
return;
|
|
569
|
-
case "error":
|
|
570
|
-
case "critical":
|
|
571
|
-
console.error(text, ...normalizedArgs);
|
|
572
|
-
return;
|
|
573
|
-
case "debug":
|
|
574
|
-
console.debug(text, ...normalizedArgs);
|
|
575
|
-
return;
|
|
576
|
-
case "success":
|
|
577
|
-
console.log(text, ...normalizedArgs);
|
|
578
|
-
return;
|
|
579
|
-
case "info":
|
|
580
|
-
default:
|
|
581
|
-
console.info(text, ...normalizedArgs);
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
function buildClientLogger(config, state) {
|
|
585
|
-
const resolvedConfig = {
|
|
586
|
-
endpoint: config.endpoint ?? DEFAULT_CLIENT_LOG_ENDPOINT,
|
|
587
|
-
headers: config.headers,
|
|
588
|
-
credentials: config.credentials ?? "same-origin",
|
|
589
|
-
localConsole: config.localConsole ?? true,
|
|
590
|
-
remoteSync: config.remoteSync ?? true,
|
|
591
|
-
connector: config.connector,
|
|
592
|
-
metadata: config.metadata
|
|
593
|
-
};
|
|
594
|
-
const delivery = state.delivery ?? (resolvedConfig.remoteSync && isBrowserRuntime() && typeof fetch === "function" ? createRemoteDeliveryManager({
|
|
595
|
-
runtime: "browser",
|
|
596
|
-
delivery: config.delivery,
|
|
597
|
-
send: (event) => sendRemoteLog(resolvedConfig, event),
|
|
598
|
-
subscribeToResume: (resume) => {
|
|
599
|
-
if (typeof globalThis.addEventListener !== "function") {
|
|
600
|
-
return;
|
|
601
|
-
}
|
|
602
|
-
const listener = () => {
|
|
603
|
-
resume();
|
|
604
|
-
};
|
|
605
|
-
globalThis.addEventListener("online", listener);
|
|
606
|
-
return () => {
|
|
607
|
-
if (typeof globalThis.removeEventListener === "function") {
|
|
608
|
-
globalThis.removeEventListener("online", listener);
|
|
609
|
-
}
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
}) : void 0);
|
|
613
|
-
const writeLog = (level, message, args) => {
|
|
614
|
-
if (resolvedConfig.localConsole) {
|
|
615
|
-
emitLocalConsole(level, message, args);
|
|
616
|
-
}
|
|
617
|
-
if (!resolvedConfig.remoteSync) {
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
const normalizedLevel = normalizeClientLogLevel(level);
|
|
621
|
-
const normalizedMessage = serializeLogMessage(message);
|
|
622
|
-
const normalizedData = normalizeClientPayloadData(message, args);
|
|
623
|
-
const metadata = normalizeMetadata(resolvedConfig.metadata);
|
|
624
|
-
const payload = {
|
|
625
|
-
type: "client_log",
|
|
626
|
-
source: "client",
|
|
627
|
-
id: createRandomId(),
|
|
628
|
-
level: normalizedLevel,
|
|
629
|
-
message: normalizedMessage,
|
|
630
|
-
connector: resolvedConfig.connector,
|
|
631
|
-
data: normalizedData,
|
|
632
|
-
bindings: Object.keys(state.bindings).length > 0 ? normalizeLogValue(state.bindings) : void 0,
|
|
633
|
-
clientTimestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
634
|
-
page: getBrowserPageContext(),
|
|
635
|
-
browser: getBrowserContext(),
|
|
636
|
-
session: {
|
|
637
|
-
pageId: state.pageId,
|
|
638
|
-
sessionId: state.sessionId
|
|
639
|
-
},
|
|
640
|
-
metadata
|
|
641
|
-
};
|
|
642
|
-
delivery?.enqueue(payload);
|
|
643
|
-
};
|
|
644
|
-
return {
|
|
645
|
-
debug: (message, ...args) => {
|
|
646
|
-
writeLog("debug", message, args);
|
|
647
|
-
},
|
|
648
|
-
info: (message, ...args) => {
|
|
649
|
-
writeLog("info", message, args);
|
|
650
|
-
},
|
|
651
|
-
error: (message, ...args) => {
|
|
652
|
-
writeLog("error", message, args);
|
|
653
|
-
},
|
|
654
|
-
warn: (message, ...args) => {
|
|
655
|
-
writeLog("warn", message, args);
|
|
656
|
-
},
|
|
657
|
-
warning: (message, ...args) => {
|
|
658
|
-
writeLog("warning", message, args);
|
|
659
|
-
},
|
|
660
|
-
success: (message, ...args) => {
|
|
661
|
-
writeLog("success", message, args);
|
|
662
|
-
},
|
|
663
|
-
critical: (message, ...args) => {
|
|
664
|
-
writeLog("critical", message, args);
|
|
665
|
-
},
|
|
666
|
-
table: (message, data) => {
|
|
667
|
-
writeLog("table", message, data === void 0 ? [] : [data]);
|
|
668
|
-
},
|
|
669
|
-
child: (bindings) => {
|
|
670
|
-
return buildClientLogger(config, {
|
|
671
|
-
...state,
|
|
672
|
-
bindings: {
|
|
673
|
-
...state.bindings,
|
|
674
|
-
...bindings
|
|
675
|
-
},
|
|
676
|
-
delivery
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
function createClientLogger(config = {}) {
|
|
682
|
-
return buildClientLogger(config, {
|
|
683
|
-
pageId: createRandomId(),
|
|
684
|
-
sessionId: getClientSessionId(),
|
|
685
|
-
bindings: {}
|
|
686
|
-
});
|
|
687
|
-
}
|
|
688
|
-
var logger = createClientLogger();
|
|
689
|
-
|
|
690
|
-
// src/shared/errors.ts
|
|
691
|
-
var HTTP_STATUS_DEFINITIONS = {
|
|
692
|
-
CONTINUE: { status: 100, message: "Continue" },
|
|
693
|
-
SWITCHING_PROTOCOLS: { status: 101, message: "Switching Protocols" },
|
|
694
|
-
PROCESSING: { status: 102, message: "Processing" },
|
|
695
|
-
EARLY_HINTS: { status: 103, message: "Early Hints" },
|
|
696
|
-
OK: { status: 200, message: "OK" },
|
|
697
|
-
CREATED: { status: 201, message: "Created" },
|
|
698
|
-
ACCEPTED: { status: 202, message: "Accepted" },
|
|
699
|
-
NON_AUTHORITATIVE_INFORMATION: { status: 203, message: "Non-Authoritative Information" },
|
|
700
|
-
NO_CONTENT: { status: 204, message: "No Content" },
|
|
701
|
-
RESET_CONTENT: { status: 205, message: "Reset Content" },
|
|
702
|
-
PARTIAL_CONTENT: { status: 206, message: "Partial Content" },
|
|
703
|
-
MULTI_STATUS: { status: 207, message: "Multi-Status" },
|
|
704
|
-
ALREADY_REPORTED: { status: 208, message: "Already Reported" },
|
|
705
|
-
IM_USED: { status: 226, message: "IM Used" },
|
|
706
|
-
MULTIPLE_CHOICES: { status: 300, message: "Multiple Choices" },
|
|
707
|
-
MOVED_PERMANENTLY: { status: 301, message: "Moved Permanently" },
|
|
708
|
-
FOUND: { status: 302, message: "Found" },
|
|
709
|
-
SEE_OTHER: { status: 303, message: "See Other" },
|
|
710
|
-
NOT_MODIFIED: { status: 304, message: "Not Modified" },
|
|
711
|
-
USE_PROXY: { status: 305, message: "Use Proxy" },
|
|
712
|
-
TEMPORARY_REDIRECT: { status: 307, message: "Temporary Redirect" },
|
|
713
|
-
PERMANENT_REDIRECT: { status: 308, message: "Permanent Redirect" },
|
|
714
|
-
BAD_REQUEST: { status: 400, message: "Bad Request" },
|
|
715
|
-
UNAUTHORIZED: { status: 401, message: "Unauthorized" },
|
|
716
|
-
PAYMENT_REQUIRED: { status: 402, message: "Payment Required" },
|
|
717
|
-
FORBIDDEN: { status: 403, message: "Forbidden" },
|
|
718
|
-
NOT_FOUND: { status: 404, message: "Not Found" },
|
|
719
|
-
METHOD_NOT_ALLOWED: { status: 405, message: "Method Not Allowed" },
|
|
720
|
-
NOT_ACCEPTABLE: { status: 406, message: "Not Acceptable" },
|
|
721
|
-
PROXY_AUTHENTICATION_REQUIRED: { status: 407, message: "Proxy Authentication Required" },
|
|
722
|
-
REQUEST_TIMEOUT: { status: 408, message: "Request Timeout" },
|
|
723
|
-
CONFLICT: { status: 409, message: "Conflict" },
|
|
724
|
-
GONE: { status: 410, message: "Gone" },
|
|
725
|
-
LENGTH_REQUIRED: { status: 411, message: "Length Required" },
|
|
726
|
-
PRECONDITION_FAILED: { status: 412, message: "Precondition Failed" },
|
|
727
|
-
PAYLOAD_TOO_LARGE: { status: 413, message: "Payload Too Large" },
|
|
728
|
-
URI_TOO_LONG: { status: 414, message: "URI Too Long" },
|
|
729
|
-
UNSUPPORTED_MEDIA_TYPE: { status: 415, message: "Unsupported Media Type" },
|
|
730
|
-
RANGE_NOT_SATISFIABLE: { status: 416, message: "Range Not Satisfiable" },
|
|
731
|
-
EXPECTATION_FAILED: { status: 417, message: "Expectation Failed" },
|
|
732
|
-
IM_A_TEAPOT: { status: 418, message: "I'm a Teapot" },
|
|
733
|
-
MISDIRECTED_REQUEST: { status: 421, message: "Misdirected Request" },
|
|
734
|
-
UNPROCESSABLE_ENTITY: { status: 422, message: "Unprocessable Entity" },
|
|
735
|
-
LOCKED: { status: 423, message: "Locked" },
|
|
736
|
-
FAILED_DEPENDENCY: { status: 424, message: "Failed Dependency" },
|
|
737
|
-
TOO_EARLY: { status: 425, message: "Too Early" },
|
|
738
|
-
UPGRADE_REQUIRED: { status: 426, message: "Upgrade Required" },
|
|
739
|
-
PRECONDITION_REQUIRED: { status: 428, message: "Precondition Required" },
|
|
740
|
-
TOO_MANY_REQUESTS: { status: 429, message: "Too Many Requests" },
|
|
741
|
-
REQUEST_HEADER_FIELDS_TOO_LARGE: { status: 431, message: "Request Header Fields Too Large" },
|
|
742
|
-
UNAVAILABLE_FOR_LEGAL_REASONS: { status: 451, message: "Unavailable For Legal Reasons" },
|
|
743
|
-
INTERNAL_SERVER_ERROR: { status: 500, message: "Internal Server Error" },
|
|
744
|
-
NOT_IMPLEMENTED: { status: 501, message: "Not Implemented" },
|
|
745
|
-
BAD_GATEWAY: { status: 502, message: "Bad Gateway" },
|
|
746
|
-
SERVICE_UNAVAILABLE: { status: 503, message: "Service Unavailable" },
|
|
747
|
-
GATEWAY_TIMEOUT: { status: 504, message: "Gateway Timeout" },
|
|
748
|
-
HTTP_VERSION_NOT_SUPPORTED: { status: 505, message: "HTTP Version Not Supported" },
|
|
749
|
-
VARIANT_ALSO_NEGOTIATES: { status: 506, message: "Variant Also Negotiates" },
|
|
750
|
-
INSUFFICIENT_STORAGE: { status: 507, message: "Insufficient Storage" },
|
|
751
|
-
LOOP_DETECTED: { status: 508, message: "Loop Detected" },
|
|
752
|
-
BANDWIDTH_LIMIT_EXCEEDED: { status: 509, message: "Bandwidth Limit Exceeded" },
|
|
753
|
-
NOT_EXTENDED: { status: 510, message: "Not Extended" },
|
|
754
|
-
NETWORK_AUTHENTICATION_REQUIRED: { status: 511, message: "Network Authentication Required" }
|
|
755
|
-
};
|
|
756
|
-
var ERROR_KEYS = [
|
|
757
|
-
"status",
|
|
758
|
-
"statusCode",
|
|
759
|
-
"code",
|
|
760
|
-
"message",
|
|
761
|
-
"stack",
|
|
762
|
-
"why",
|
|
763
|
-
"fix",
|
|
764
|
-
"link",
|
|
765
|
-
"details",
|
|
766
|
-
"cause",
|
|
767
|
-
"title",
|
|
768
|
-
"detail",
|
|
769
|
-
"logLevel",
|
|
770
|
-
"error",
|
|
771
|
-
"data"
|
|
772
|
-
];
|
|
773
|
-
function isErrorLogLevel(value) {
|
|
774
|
-
return value === "debug" || value === "info" || value === "warning" || value === "error" || value === "critical";
|
|
775
|
-
}
|
|
776
|
-
function parseStatus(value) {
|
|
777
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
778
|
-
return value;
|
|
779
|
-
}
|
|
780
|
-
if (typeof value === "string" && /^\d+$/.test(value.trim())) {
|
|
781
|
-
return Number.parseInt(value, 10);
|
|
782
|
-
}
|
|
783
|
-
return void 0;
|
|
784
|
-
}
|
|
785
|
-
function normalizeDetails(value) {
|
|
786
|
-
return isPlainObject(value) ? value : void 0;
|
|
787
|
-
}
|
|
788
|
-
function hasMeaningfulErrorData(candidate) {
|
|
789
|
-
return candidate.status !== void 0 || candidate.statusCode !== void 0 || candidate.code !== void 0 || candidate.message !== void 0 || candidate.stack !== void 0 || candidate.why !== void 0 || candidate.fix !== void 0 || candidate.link !== void 0 || candidate.details !== void 0 || candidate.cause !== void 0 || candidate.logLevel !== void 0;
|
|
790
|
-
}
|
|
791
|
-
function normalizeRecordCandidate(record) {
|
|
792
|
-
const title = typeof record.title === "string" ? record.title : void 0;
|
|
793
|
-
const detail = typeof record.detail === "string" ? record.detail : void 0;
|
|
794
|
-
return {
|
|
795
|
-
status: parseStatus(record.status),
|
|
796
|
-
statusCode: parseStatus(record.statusCode),
|
|
797
|
-
code: typeof record.code === "string" || typeof record.code === "number" ? record.code : void 0,
|
|
798
|
-
message: typeof record.message === "string" ? record.message : title ?? detail,
|
|
799
|
-
stack: typeof record.stack === "string" ? record.stack : void 0,
|
|
800
|
-
why: typeof record.why === "string" ? record.why : void 0,
|
|
801
|
-
fix: typeof record.fix === "string" ? record.fix : void 0,
|
|
802
|
-
link: typeof record.link === "string" ? record.link : void 0,
|
|
803
|
-
details: normalizeDetails(record.details),
|
|
804
|
-
cause: record.cause,
|
|
805
|
-
logLevel: isErrorLogLevel(record.logLevel) ? record.logLevel : void 0
|
|
806
|
-
};
|
|
807
|
-
}
|
|
808
|
-
function mergeCandidates(container, nested) {
|
|
809
|
-
const own = normalizeRecordCandidate(container);
|
|
810
|
-
if (nested === void 0) {
|
|
811
|
-
return hasMeaningfulErrorData(own) ? own : void 0;
|
|
812
|
-
}
|
|
813
|
-
if (typeof nested === "string") {
|
|
814
|
-
if (hasMeaningfulErrorData(own)) {
|
|
815
|
-
return {
|
|
816
|
-
...own,
|
|
817
|
-
message: own.message ?? nested
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
return nested;
|
|
821
|
-
}
|
|
822
|
-
return {
|
|
823
|
-
status: own.status ?? nested.status,
|
|
824
|
-
statusCode: own.statusCode ?? nested.statusCode,
|
|
825
|
-
code: own.code ?? nested.code,
|
|
826
|
-
message: own.message ?? nested.message,
|
|
827
|
-
stack: own.stack ?? nested.stack,
|
|
828
|
-
why: own.why ?? nested.why,
|
|
829
|
-
fix: own.fix ?? nested.fix,
|
|
830
|
-
link: own.link ?? nested.link,
|
|
831
|
-
details: own.details ?? nested.details,
|
|
832
|
-
cause: own.cause ?? nested.cause,
|
|
833
|
-
logLevel: own.logLevel ?? nested.logLevel
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
function hasErrorShape(record) {
|
|
837
|
-
return ERROR_KEYS.some((key) => record[key] !== void 0);
|
|
838
|
-
}
|
|
839
|
-
function isResponseLike(input) {
|
|
840
|
-
if (typeof Response !== "undefined" && input instanceof Response) {
|
|
841
|
-
return true;
|
|
842
|
-
}
|
|
843
|
-
return isPlainObject(input) && typeof input.status === "number" && typeof input.statusText === "string" && typeof input.clone === "function" && typeof input.text === "function";
|
|
844
|
-
}
|
|
845
|
-
var BlypError = class _BlypError extends Error {
|
|
846
|
-
constructor(config) {
|
|
847
|
-
super(config.message);
|
|
848
|
-
__publicField(this, "name", "BlypError");
|
|
849
|
-
__publicField(this, "status");
|
|
850
|
-
__publicField(this, "statusCode");
|
|
851
|
-
__publicField(this, "code");
|
|
852
|
-
__publicField(this, "why");
|
|
853
|
-
__publicField(this, "fix");
|
|
854
|
-
__publicField(this, "link");
|
|
855
|
-
__publicField(this, "details");
|
|
856
|
-
__publicField(this, "cause");
|
|
857
|
-
__publicField(this, "logLevel");
|
|
858
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
859
|
-
this.status = config.status;
|
|
860
|
-
this.statusCode = config.statusCode;
|
|
861
|
-
this.code = config.code;
|
|
862
|
-
this.why = config.why;
|
|
863
|
-
this.fix = config.fix;
|
|
864
|
-
this.link = config.link;
|
|
865
|
-
this.details = config.details;
|
|
866
|
-
this.cause = config.cause;
|
|
867
|
-
this.logLevel = config.logLevel;
|
|
868
|
-
if (config.stack) {
|
|
869
|
-
this.stack = config.stack;
|
|
870
|
-
} else if (typeof Error.captureStackTrace === "function") {
|
|
871
|
-
Error.captureStackTrace(this, _BlypError);
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
toJSON() {
|
|
875
|
-
return {
|
|
876
|
-
name: "BlypError",
|
|
877
|
-
message: this.message,
|
|
878
|
-
status: this.status,
|
|
879
|
-
statusCode: this.statusCode,
|
|
880
|
-
...this.code !== void 0 ? { code: this.code } : {},
|
|
881
|
-
...this.why !== void 0 ? { why: this.why } : {},
|
|
882
|
-
...this.fix !== void 0 ? { fix: this.fix } : {},
|
|
883
|
-
...this.link !== void 0 ? { link: this.link } : {},
|
|
884
|
-
...this.details !== void 0 ? { details: this.details } : {}
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
};
|
|
888
|
-
function resolveErrorLogLevel(status, explicit) {
|
|
889
|
-
if (explicit) {
|
|
890
|
-
return explicit;
|
|
891
|
-
}
|
|
892
|
-
if (status >= 500) {
|
|
893
|
-
return "critical";
|
|
894
|
-
}
|
|
895
|
-
if (status >= 400) {
|
|
896
|
-
return "error";
|
|
897
|
-
}
|
|
898
|
-
return "warning";
|
|
899
|
-
}
|
|
900
|
-
function normalizeCauseForLog(cause) {
|
|
901
|
-
if (cause instanceof Error) {
|
|
902
|
-
return {
|
|
903
|
-
name: cause.name,
|
|
904
|
-
message: cause.message,
|
|
905
|
-
...cause.stack ? { stack: cause.stack } : {}
|
|
906
|
-
};
|
|
907
|
-
}
|
|
908
|
-
return cause;
|
|
909
|
-
}
|
|
910
|
-
function emitErrorLog(logger2, error, levelOverride) {
|
|
911
|
-
const level = resolveErrorLogLevel(error.status, levelOverride ?? error.logLevel);
|
|
912
|
-
const logMethod = (() => {
|
|
913
|
-
switch (level) {
|
|
914
|
-
case "debug":
|
|
915
|
-
return logger2.debug;
|
|
916
|
-
case "info":
|
|
917
|
-
return logger2.info;
|
|
918
|
-
case "warning":
|
|
919
|
-
return logger2.warning;
|
|
920
|
-
case "critical":
|
|
921
|
-
return logger2.critical;
|
|
922
|
-
case "error":
|
|
923
|
-
default:
|
|
924
|
-
return logger2.error;
|
|
925
|
-
}
|
|
926
|
-
})();
|
|
927
|
-
logMethod(error.message, {
|
|
928
|
-
type: "application_error",
|
|
929
|
-
status: error.status,
|
|
930
|
-
statusCode: error.statusCode,
|
|
931
|
-
code: error.code,
|
|
932
|
-
why: error.why,
|
|
933
|
-
fix: error.fix,
|
|
934
|
-
link: error.link,
|
|
935
|
-
details: error.details,
|
|
936
|
-
cause: normalizeCauseForLog(error.cause)
|
|
937
|
-
});
|
|
938
|
-
}
|
|
939
|
-
function resolveErrorConfig(input, defaults = {}) {
|
|
940
|
-
const candidateStatus = input.status ?? input.statusCode;
|
|
941
|
-
const status = candidateStatus ?? defaults.status ?? defaults.statusCode ?? 500;
|
|
942
|
-
const preset = getHttpCode(status);
|
|
943
|
-
const message = input.message ?? defaults.message ?? preset?.message ?? `HTTP ${status}`;
|
|
944
|
-
return {
|
|
945
|
-
status,
|
|
946
|
-
statusCode: status,
|
|
947
|
-
message,
|
|
948
|
-
code: input.code ?? defaults.code ?? preset?.code,
|
|
949
|
-
why: input.why ?? defaults.why ?? preset?.why,
|
|
950
|
-
fix: input.fix ?? defaults.fix ?? preset?.fix,
|
|
951
|
-
link: input.link ?? defaults.link ?? preset?.link,
|
|
952
|
-
details: input.details ?? defaults.details ?? preset?.details,
|
|
953
|
-
cause: input.cause ?? defaults.cause,
|
|
954
|
-
stack: input.stack ?? defaults.stack,
|
|
955
|
-
logLevel: resolveErrorLogLevel(
|
|
956
|
-
status,
|
|
957
|
-
input.logLevel ?? defaults.logLevel ?? preset?.logLevel
|
|
958
|
-
)
|
|
959
|
-
};
|
|
960
|
-
}
|
|
961
|
-
function createBlypError(input, defaults = {}) {
|
|
962
|
-
const error = new BlypError(resolveErrorConfig(input, defaults));
|
|
963
|
-
if (input.skipLogging !== true && input.logger) {
|
|
964
|
-
emitErrorLog(input.logger, error, input.logLevel);
|
|
965
|
-
}
|
|
966
|
-
return error;
|
|
967
|
-
}
|
|
968
|
-
function createErrorCode(definition, createErrorFromCode) {
|
|
969
|
-
const errorCode = {
|
|
970
|
-
...definition,
|
|
971
|
-
statusCode: definition.status,
|
|
972
|
-
create(overrides = {}) {
|
|
973
|
-
return createBlypError({
|
|
974
|
-
status: definition.status,
|
|
975
|
-
message: definition.message,
|
|
976
|
-
code: overrides.code ?? definition.code,
|
|
977
|
-
why: overrides.why ?? definition.why,
|
|
978
|
-
fix: overrides.fix ?? definition.fix,
|
|
979
|
-
link: overrides.link ?? definition.link,
|
|
980
|
-
details: overrides.details ?? definition.details,
|
|
981
|
-
cause: overrides.cause,
|
|
982
|
-
stack: overrides.stack,
|
|
983
|
-
logLevel: overrides.logLevel ?? definition.logLevel,
|
|
984
|
-
logger: overrides.logger,
|
|
985
|
-
skipLogging: overrides.skipLogging
|
|
986
|
-
});
|
|
987
|
-
},
|
|
988
|
-
extend(extension) {
|
|
989
|
-
return createErrorCode(
|
|
990
|
-
{
|
|
991
|
-
key: extension.code,
|
|
992
|
-
status: definition.status,
|
|
993
|
-
message: extension.message ?? definition.message,
|
|
994
|
-
code: extension.code,
|
|
995
|
-
why: extension.why ?? definition.why,
|
|
996
|
-
fix: extension.fix ?? definition.fix,
|
|
997
|
-
link: extension.link ?? definition.link,
|
|
998
|
-
details: extension.details ?? definition.details,
|
|
999
|
-
logLevel: extension.logLevel ?? definition.logLevel
|
|
1000
|
-
});
|
|
1001
|
-
}
|
|
1002
|
-
};
|
|
1003
|
-
return Object.freeze(errorCode);
|
|
1004
|
-
}
|
|
1005
|
-
function buildHttpCodeRegistry(createErrorFromCode) {
|
|
1006
|
-
const entries = Object.entries(HTTP_STATUS_DEFINITIONS).map(([key, value]) => {
|
|
1007
|
-
return [key, createErrorCode({ key, ...value })];
|
|
1008
|
-
});
|
|
1009
|
-
return Object.freeze(
|
|
1010
|
-
Object.fromEntries(entries)
|
|
1011
|
-
);
|
|
1012
|
-
}
|
|
1013
|
-
var HTTP_CODES = buildHttpCodeRegistry();
|
|
1014
|
-
var httpCodeByStatus = new Map(
|
|
1015
|
-
Object.values(HTTP_CODES).map((value) => [value.status, value])
|
|
1016
|
-
);
|
|
1017
|
-
function getHttpCode(status) {
|
|
1018
|
-
return httpCodeByStatus.get(status);
|
|
1019
|
-
}
|
|
1020
|
-
function extractErrorCandidate(payload) {
|
|
1021
|
-
if (typeof payload === "string") {
|
|
1022
|
-
return payload;
|
|
1023
|
-
}
|
|
1024
|
-
if (!isPlainObject(payload)) {
|
|
1025
|
-
return void 0;
|
|
1026
|
-
}
|
|
1027
|
-
if (payload.error !== void 0) {
|
|
1028
|
-
const nested = payload.error;
|
|
1029
|
-
if (typeof nested === "string") {
|
|
1030
|
-
return mergeCandidates(payload, nested);
|
|
1031
|
-
}
|
|
1032
|
-
if (isPlainObject(nested)) {
|
|
1033
|
-
return mergeCandidates(payload, extractErrorCandidate(nested));
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
if (isPlainObject(payload.data)) {
|
|
1037
|
-
const nested = payload.data;
|
|
1038
|
-
if (nested.error !== void 0 || hasErrorShape(nested)) {
|
|
1039
|
-
return mergeCandidates(payload, extractErrorCandidate(nested));
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
if (hasErrorShape(payload)) {
|
|
1043
|
-
return normalizeRecordCandidate(payload);
|
|
1044
|
-
}
|
|
1045
|
-
return void 0;
|
|
1046
|
-
}
|
|
1047
|
-
function coercePayloadToError(payload, options = {}, responseContext = {}) {
|
|
1048
|
-
if (payload instanceof BlypError) {
|
|
1049
|
-
return payload;
|
|
1050
|
-
}
|
|
1051
|
-
const candidate = (() => {
|
|
1052
|
-
if (payload instanceof Error) {
|
|
1053
|
-
const errorWithMetadata = payload;
|
|
1054
|
-
return {
|
|
1055
|
-
status: errorWithMetadata.status,
|
|
1056
|
-
statusCode: errorWithMetadata.statusCode,
|
|
1057
|
-
code: errorWithMetadata.code,
|
|
1058
|
-
message: payload.message,
|
|
1059
|
-
stack: payload.stack,
|
|
1060
|
-
why: errorWithMetadata.why,
|
|
1061
|
-
fix: errorWithMetadata.fix,
|
|
1062
|
-
link: errorWithMetadata.link,
|
|
1063
|
-
details: errorWithMetadata.details,
|
|
1064
|
-
cause: errorWithMetadata.cause,
|
|
1065
|
-
logLevel: errorWithMetadata.logLevel
|
|
1066
|
-
};
|
|
1067
|
-
}
|
|
1068
|
-
return extractErrorCandidate(payload);
|
|
1069
|
-
})();
|
|
1070
|
-
const responseStatus = responseContext.status && responseContext.status > 0 ? responseContext.status : void 0;
|
|
1071
|
-
const candidateStatus = typeof candidate === "string" ? void 0 : candidate?.status ?? candidate?.statusCode;
|
|
1072
|
-
const status = responseStatus ?? candidateStatus ?? options.fallbackStatus ?? 500;
|
|
1073
|
-
const textBody = typeof candidate === "string" ? candidate.trim() || void 0 : void 0;
|
|
1074
|
-
const statusText = responseContext.statusText?.trim() || void 0;
|
|
1075
|
-
return createBlypError(
|
|
1076
|
-
typeof candidate === "string" ? { message: textBody, ...responseStatus !== void 0 ? { status: responseStatus } : {} } : {
|
|
1077
|
-
...candidate ?? {},
|
|
1078
|
-
...responseStatus !== void 0 ? {
|
|
1079
|
-
status: responseStatus,
|
|
1080
|
-
statusCode: responseStatus
|
|
1081
|
-
} : {}
|
|
1082
|
-
},
|
|
1083
|
-
{
|
|
1084
|
-
status,
|
|
1085
|
-
message: (typeof candidate === "string" ? textBody : candidate?.message) ?? statusText ?? getHttpCode(status)?.message ?? `HTTP ${status}`
|
|
1086
|
-
}
|
|
1087
|
-
);
|
|
1088
|
-
}
|
|
1089
|
-
async function readResponseErrorPayload(response) {
|
|
1090
|
-
const contentType = response.headers.get("content-type")?.toLowerCase();
|
|
1091
|
-
const isJsonResponse = contentType?.includes("application/json") || contentType?.includes("+json");
|
|
1092
|
-
if (isJsonResponse) {
|
|
1093
|
-
try {
|
|
1094
|
-
return await response.clone().json();
|
|
1095
|
-
} catch {
|
|
1096
|
-
try {
|
|
1097
|
-
return await response.clone().text();
|
|
1098
|
-
} catch {
|
|
1099
|
-
return void 0;
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
try {
|
|
1104
|
-
return await response.clone().text();
|
|
1105
|
-
} catch {
|
|
1106
|
-
return void 0;
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
function parseError(input, options = {}) {
|
|
1110
|
-
if (isResponseLike(input)) {
|
|
1111
|
-
return (async () => {
|
|
1112
|
-
const payload = await readResponseErrorPayload(input).catch(() => void 0);
|
|
1113
|
-
const error2 = coercePayloadToError(payload, options, {
|
|
1114
|
-
status: input.status,
|
|
1115
|
-
statusText: input.statusText
|
|
1116
|
-
});
|
|
1117
|
-
if (options.logger) {
|
|
1118
|
-
emitErrorLog(options.logger, error2, options.logLevel);
|
|
1119
|
-
}
|
|
1120
|
-
return error2;
|
|
1121
|
-
})();
|
|
1122
|
-
}
|
|
1123
|
-
const error = coercePayloadToError(input, options);
|
|
1124
|
-
if (options.logger) {
|
|
1125
|
-
emitErrorLog(options.logger, error, options.logLevel);
|
|
1126
|
-
}
|
|
1127
|
-
return error;
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
export { BlypError, HTTP_CODES, createClientLogger, getHttpCode, logger, parseError };
|
|
1131
|
-
//# sourceMappingURL=client.mjs.map
|
|
1132
|
-
//# sourceMappingURL=client.mjs.map
|
|
1
|
+
import {z as z$1}from'zod';var Le=Object.defineProperty;var he=(e,t,n)=>t in e?Le(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var d=(e,t,n)=>he(e,typeof t!="symbol"?t+"":t,n);function _(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=f(n.cause)),t}function f(e,t=new WeakSet){if(e instanceof Error)return _(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=>f(n,t));if(typeof e=="object"){if(t.has(e))return "[Circular]";t.add(e);let n={};for(let[r,s]of Object.entries(e))n[r]=f(s,t);return t.delete(e),n}return e}function L(e){if(typeof e=="string")return e;if(e instanceof Error)return e.message||e.name;let t=f(e);if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)??String(t)}catch{return String(t)}}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"});var q=z$1.custom(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),{message:"Expected a plain object"}),j=z$1.string().trim().min(1);function m(e){return q.safeParse(e).success}var Q="/inngest",$="blyp:session-id";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:j})]);function y(e){try{return e()}catch{return}}function we(){return Math.random().toString(36).slice(2,10)}function D(){let e=y(()=>globalThis.crypto),t=e&&typeof e.randomUUID=="function"?e.randomUUID.bind(e):void 0;return t?t():`${Date.now().toString(36)}-${we()}`}function G(e){return e==="warn"?"warning":e}function Y(e,t){let n=t.map(o=>f(o)),r=e instanceof Error?_(e):void 0;if(r!==void 0&&n.length===0)return r;let s=r===void 0?n:[r,...n];if(s.length!==0)return s.length===1?s[0]:s}function V(){let e=y(()=>globalThis.location),t=y(()=>globalThis.document);return {url:e?.href,pathname:e?.pathname,search:e?.search,hash:e?.hash,title:t?.title,referrer:t?.referrer}}function W(){let e=y(()=>globalThis.navigator);return {userAgent:e?.userAgent,language:e?.language,platform:e?.platform}}function Z(){let e=y(()=>globalThis.sessionStorage),t=y(()=>e?.getItem($));if(t)return t;let n=D();return y(()=>e?.setItem($,n)),n}function X(e){if(e===void 0)return;let t=typeof e=="function"?y(e):e;if(m(t))return f(t)}function I(e,t,n){return Number.isFinite(e)?Math.max(n,Math.floor(e)):t}function S(e,t){if(e)try{e(t);}catch{}}function K(e){typeof console>"u"||typeof console.warn!="function"||console.warn(e);}function J(e){return e===void 0?"unknown":String(e)}function ee(e){let t={maxRetries:I(e.delivery?.maxRetries,3,0),retryDelayMs:I(e.delivery?.retryDelayMs,5e3,0),maxQueueSize:I(e.delivery?.maxQueueSize,100,1),warnOnFailure:e.delivery?.warnOnFailure??true,onSuccess:e.delivery?.onSuccess,onRetry:e.delivery?.onRetry,onFailure:e.delivery?.onFailure,onDrop:e.delivery?.onDrop},n=[],r,s,o=false,i,g=e.runtime==="browser"?"client":e.runtime,C=()=>{s&&(clearTimeout(s),s=void 0);},c=()=>n.length>0||r!==void 0,h=a=>{if(e.subscribeToResume){if(c()){i||(i=e.subscribeToResume(()=>{let u=Date.now();for(let l of n)l.nextAttemptAt=u;C(),a();})??void 0);return}i&&(i(),i=void 0);}},A=a=>{t.warnOnFailure&&K(`[blyp/${g}] Dropped queued log "${a.droppedEvent.message}" (id: ${a.droppedEvent.id}) because the delivery queue reached ${a.maxQueueSize}. Keeping "${a.replacementEvent.message}" (id: ${a.replacementEvent.id}) instead.`);},O=(a,u)=>{if(!t.warnOnFailure||u)return;let l=[`reason=${a.reason}`,`attempt=${J(a.attempt)}`,`status=${J(a.status)}`];a.error&&l.push(`error=${a.error}`),K(`[blyp/${g}] Failed to deliver log "${a.event.message}" (id: ${a.event.id}, ${l.join(", ")})`);},ye=()=>n.length+(r?1:0),H=a=>{if(C(),n.length===0){h(a);return}let u=n.reduce((v,w)=>Math.min(v,w.nextAttemptAt),Number.POSITIVE_INFINITY),l=Math.max(u-Date.now(),0);s=setTimeout(()=>{s=void 0,a();},l),h(a);},Ee=(a,u)=>{let l={runtime:e.runtime,droppedEvent:a,replacementEvent:u,maxQueueSize:t.maxQueueSize,reason:"queue_overflow"};S(t.onDrop,l),A(l);},Re=()=>{for(;ye()>t.maxQueueSize&&n.length>0;){let a=n.shift(),u=n[n.length-1]?.event??r?.event;if(!a||!u)break;Ee(a.event,u);}},Ce=()=>{let a=Date.now();for(let u=0;u<n.length;u+=1)if(n[u].nextAttemptAt<=a)return u;return -1},b=async()=>{if(!o){o=true;try{for(;;){let a=Ce();if(a===-1)break;let u=n.splice(a,1)[0];if(!u)continue;r=u,h(()=>{b();}),u.attempt+=1;let l=await e.send(u.event);if(r=void 0,l.outcome==="success"){let w={runtime:e.runtime,event:u.event,attempt:u.attempt,status:l.status,transport:l.transport};S(t.onSuccess,w);continue}if(l.outcome==="retry"&&u.attempt<=t.maxRetries){u.nextAttemptAt=Date.now()+t.retryDelayMs,n.push(u);let w={runtime:e.runtime,event:u.event,attempt:u.attempt,retriesRemaining:t.maxRetries-(u.attempt-1),nextRetryAt:new Date(u.nextAttemptAt).toISOString(),reason:l.reason,status:l.status,error:l.error};S(t.onRetry,w);continue}let v={runtime:e.runtime,event:u.event,attempt:u.attempt,reason:l.reason,status:l.status,error:l.error};S(t.onFailure,v),O(v,l.outcome==="failure"?l.suppressWarning:void 0);}}finally{o=false,H(()=>{b();});}}};return {enqueue(a){n.push({event:a,attempt:0,nextAttemptAt:Date.now()}),Re(),H(()=>{b();}),b();}}}var ke="[REDACTED]",Te=["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 be=[{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}],ve=/\b(?:\d[ -]*?){16}\b/g;function te(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 De(e){let t=e.flags.includes("g")?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function Se(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xe(e){return new Set(e.keys.map(t=>t.toLowerCase()))}function Ae(e){return e.split(".").filter(Boolean)}function N(e,t,n=0,r=0){if(n===e.length)return r===t.length;let s=e[n];if(s==="**"){if(n===e.length-1)return true;for(let o=r;o<=t.length;o+=1)if(N(e,t,n+1,o))return true;return false}return r>=t.length||s!=="*"&&s!==t[r]?false:N(e,t,n+1,r+1)}function Oe(e,t){return e.length===0||t.paths.length===0?false:t.paths.some(n=>N(Ae(n),e))}function _e(e){let t=e.replace(/\D/g,"");if(t.length!==16)return false;let n=0,r=false;for(let s=t.length-1;s>=0;s-=1){let o=Number(t[s]);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r;}return n%10===0}function ne(e,t,n){if(n||t.disablePatternScanning)return e;let r=e;for(let{type:s,pattern:o}of be)r=r.replace(o,`[REDACTED:${s}]`);r=r.replace(ve,s=>_e(s)?"[REDACTED:card]":s);for(let s of t.patterns)r=r.replace(De(s),"[REDACTED:pattern]");return r}function x(e,t,n,r){if(typeof e=="string")return ne(e,t,!!r.skipPatternScanning);if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map((o,i)=>x(o,t,n,{path:[...r.path,String(i)],skipPatternScanning:r.skipPatternScanning}));if(!Se(e))return e;let s={};for(let[o,i]of Object.entries(e)){let g=[...r.path,o];if(n.has(o.toLowerCase())||Oe(g,t)){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"){s[o]=ke;continue}s[o]=x(i,t,n,{path:g,skipPatternScanning:r.skipPatternScanning});continue}s[o]=x(i,t,n,{path:g,skipPatternScanning:r.skipPatternScanning});}return s}function re(e,t){return {keys:te([...Te,...[],...[]]),paths:te([...[],...[]]),patterns:[...[],...[]].filter(n=>n instanceof RegExp),disablePatternScanning:false}}function E(e,t,n={path:[]}){let r=f(e);return x(r,t,xe(t),n)}function U(e,t){return typeof e=="string"?ne(e,t,false):L(E(e,t))}function Pe(e,t=new Set){return (n,r,s)=>{if(t.has(n)||typeof console>"u")return;let o=console[e];if(typeof o=="function"){if(t.add(n),s===void 0){o.call(console,r);return}o.call(console,r,s);}}}function oe(e){return Pe("error",e)}var Ie=new Set,k=oe(Ie),R=re();function Ne(e){return {"content-type":"application/json",...e??{}}}function Ue(e){return Object.keys(e??{}).length===0}function Be(e){return e===429||e>=500}function ze(){return typeof navigator<"u"&&typeof location<"u"}async function Fe(e,t){if(typeof navigator<"u"&&navigator.onLine===false)return {outcome:"retry",reason:"offline"};if(typeof fetch!="function")return {outcome:"failure",reason:"missing_transport",suppressWarning:true};let n=JSON.stringify(t),r=Ne(e.headers),s=Ue(e.headers)&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&typeof Blob<"u";try{let o=await fetch(e.endpoint,{method:"POST",keepalive:!0,credentials:e.credentials,headers:r,body:n});return o.ok?(e.connector==="betterstack"&&o.headers.get("x-blyp-betterstack-status")==="missing"&&k("betterstack-missing","[blyp/client] Better Stack connector requested but not configured on the server. Continuing without Better Stack forwarding."),e.connector==="databuddy"&&o.headers.get("x-blyp-databuddy-status")==="missing"&&k("databuddy-missing","[blyp/client] Databuddy connector requested but not configured on the server. Continuing without Databuddy forwarding."),e.connector==="posthog"&&o.headers.get("x-blyp-posthog-status")==="missing"&&k("posthog-missing","[blyp/client] PostHog connector requested but not configured on the server. Continuing without PostHog forwarding."),e.connector==="sentry"&&o.headers.get("x-blyp-sentry-status")==="missing"&&k("sentry-missing","[blyp/client] Sentry not setup. Continuing without Sentry forwarding."),e.connector&&typeof e.connector=="object"&&e.connector.type==="otlp"&&o.headers.get("x-blyp-otlp-status")==="missing"&&k(`otlp-missing:${e.connector.name}`,`[blyp/client] OTLP target "${e.connector.name}" was requested but not configured on the server. Continuing without OTLP forwarding.`),{outcome:"success",transport:"fetch",status:o.status}):Be(o.status)?{outcome:"retry",reason:"response_status",status:o.status}:{outcome:"failure",reason:"response_status",status:o.status}}catch(o){if(s)try{if(navigator.sendBeacon(e.endpoint,new Blob([n],{type:"application/json"})))return {outcome:"success",transport:"beacon"}}catch{}return {outcome:"retry",reason:"network_error",error:o instanceof Error?o.message:String(o)}}}function Me(e,t,n){if(typeof console>"u")return;let r=n.map(i=>f(i)),s=r.map(i=>E(i,R)),o=U(L(t),R);switch(e){case "table":console.log(o),r.length>0&&typeof console.table=="function"&&console.table(s[0]);return;case "warning":case "warn":console.warn(o,...s);return;case "error":case "critical":console.error(o,...s);return;case "debug":console.debug(o,...s);return;case "success":console.log(o,...s);return;default:console.info(o,...s);}}function se(e,t){let n={endpoint:e.endpoint??Q,headers:e.headers,credentials:e.credentials??"same-origin",localConsole:e.localConsole??true,remoteSync:e.remoteSync??true,connector:e.connector,metadata:e.metadata},r=t.delivery??(n.remoteSync&&ze()&&typeof fetch=="function"?ee({runtime:"browser",delivery:e.delivery,send:o=>Fe(n,o),subscribeToResume:o=>{if(typeof globalThis.addEventListener!="function")return;let i=()=>{o();};return globalThis.addEventListener("online",i),()=>{typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("online",i);}}}):void 0),s=(o,i,g)=>{if(n.localConsole&&Me(o,i,g),!n.remoteSync)return;let C=G(o),c=U(L(i),R),h=E(Y(i,g),R),A=E(X(n.metadata),R),O={type:"client_log",source:"client",id:D(),traceId:t.traceId,level:C,message:c,connector:n.connector,data:h,bindings:Object.keys(t.bindings).length>0?E(t.bindings,R):void 0,clientTimestamp:new Date().toISOString(),page:V(),browser:W(),session:{pageId:t.pageId,sessionId:t.sessionId},metadata:A};r?.enqueue(E(O,R));};return {debug:(o,...i)=>{s("debug",o,i);},info:(o,...i)=>{s("info",o,i);},error:(o,...i)=>{s("error",o,i);},warn:(o,...i)=>{s("warn",o,i);},warning:(o,...i)=>{s("warning",o,i);},success:(o,...i)=>{s("success",o,i);},critical:(o,...i)=>{s("critical",o,i);},table:(o,i)=>{s("table",o,i===void 0?[]:[i]);},child:o=>se(e,{...t,bindings:{...t.bindings,...o},traceId:t.traceId,delivery:r})}}function ie(e={}){return se(e,{pageId:D(),sessionId:Z(),bindings:{},traceId:e.traceId})}var He=ie();var qe={CONTINUE:{status:100,message:"Continue"},SWITCHING_PROTOCOLS:{status:101,message:"Switching Protocols"},PROCESSING:{status:102,message:"Processing"},EARLY_HINTS:{status:103,message:"Early Hints"},OK:{status:200,message:"OK"},CREATED:{status:201,message:"Created"},ACCEPTED:{status:202,message:"Accepted"},NON_AUTHORITATIVE_INFORMATION:{status:203,message:"Non-Authoritative Information"},NO_CONTENT:{status:204,message:"No Content"},RESET_CONTENT:{status:205,message:"Reset Content"},PARTIAL_CONTENT:{status:206,message:"Partial Content"},MULTI_STATUS:{status:207,message:"Multi-Status"},ALREADY_REPORTED:{status:208,message:"Already Reported"},IM_USED:{status:226,message:"IM Used"},MULTIPLE_CHOICES:{status:300,message:"Multiple Choices"},MOVED_PERMANENTLY:{status:301,message:"Moved Permanently"},FOUND:{status:302,message:"Found"},SEE_OTHER:{status:303,message:"See Other"},NOT_MODIFIED:{status:304,message:"Not Modified"},USE_PROXY:{status:305,message:"Use Proxy"},TEMPORARY_REDIRECT:{status:307,message:"Temporary Redirect"},PERMANENT_REDIRECT:{status:308,message:"Permanent Redirect"},BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},PAYMENT_REQUIRED:{status:402,message:"Payment Required"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_ALLOWED:{status:405,message:"Method Not Allowed"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},PROXY_AUTHENTICATION_REQUIRED:{status:407,message:"Proxy Authentication Required"},REQUEST_TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},GONE:{status:410,message:"Gone"},LENGTH_REQUIRED:{status:411,message:"Length Required"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},URI_TOO_LONG:{status:414,message:"URI Too Long"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},RANGE_NOT_SATISFIABLE:{status:416,message:"Range Not Satisfiable"},EXPECTATION_FAILED:{status:417,message:"Expectation Failed"},IM_A_TEAPOT:{status:418,message:"I'm a Teapot"},MISDIRECTED_REQUEST:{status:421,message:"Misdirected Request"},UNPROCESSABLE_ENTITY:{status:422,message:"Unprocessable Entity"},LOCKED:{status:423,message:"Locked"},FAILED_DEPENDENCY:{status:424,message:"Failed Dependency"},TOO_EARLY:{status:425,message:"Too Early"},UPGRADE_REQUIRED:{status:426,message:"Upgrade Required"},PRECONDITION_REQUIRED:{status:428,message:"Precondition Required"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},REQUEST_HEADER_FIELDS_TOO_LARGE:{status:431,message:"Request Header Fields Too Large"},UNAVAILABLE_FOR_LEGAL_REASONS:{status:451,message:"Unavailable For Legal Reasons"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"},HTTP_VERSION_NOT_SUPPORTED:{status:505,message:"HTTP Version Not Supported"},VARIANT_ALSO_NEGOTIATES:{status:506,message:"Variant Also Negotiates"},INSUFFICIENT_STORAGE:{status:507,message:"Insufficient Storage"},LOOP_DETECTED:{status:508,message:"Loop Detected"},BANDWIDTH_LIMIT_EXCEEDED:{status:509,message:"Bandwidth Limit Exceeded"},NOT_EXTENDED:{status:510,message:"Not Extended"},NETWORK_AUTHENTICATION_REQUIRED:{status:511,message:"Network Authentication Required"}},je=["status","statusCode","code","message","stack","why","fix","link","details","cause","title","detail","logLevel","error","data"];function $e(e){return e==="debug"||e==="info"||e==="warning"||e==="error"||e==="critical"}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&/^\d+$/.test(e.trim()))return Number.parseInt(e,10)}function Qe(e){return m(e)?e:void 0}function ue(e){return e.status!==void 0||e.statusCode!==void 0||e.code!==void 0||e.message!==void 0||e.stack!==void 0||e.why!==void 0||e.fix!==void 0||e.link!==void 0||e.details!==void 0||e.cause!==void 0||e.logLevel!==void 0}function ge(e){let t=typeof e.title=="string"?e.title:void 0,n=typeof e.detail=="string"?e.detail:void 0;return {status:ae(e.status),statusCode:ae(e.statusCode),code:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,message:typeof e.message=="string"?e.message:t??n,stack:typeof e.stack=="string"?e.stack:void 0,why:typeof e.why=="string"?e.why:void 0,fix:typeof e.fix=="string"?e.fix:void 0,link:typeof e.link=="string"?e.link:void 0,details:Qe(e.details),cause:e.cause,logLevel:$e(e.logLevel)?e.logLevel:void 0}}function B(e,t){let n=ge(e);return t===void 0?ue(n)?n:void 0:typeof t=="string"?ue(n)?{...n,message:n.message??t}:t:{status:n.status??t.status,statusCode:n.statusCode??t.statusCode,code:n.code??t.code,message:n.message??t.message,stack:n.stack??t.stack,why:n.why??t.why,fix:n.fix??t.fix,link:n.link??t.link,details:n.details??t.details,cause:n.cause??t.cause,logLevel:n.logLevel??t.logLevel}}function le(e){return je.some(t=>e[t]!==void 0)}function Ge(e){return typeof Response<"u"&&e instanceof Response?true:m(e)&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.clone=="function"&&typeof e.text=="function"}var T=class e extends Error{constructor(n){super(n.message);d(this,"name","BlypError");d(this,"status");d(this,"statusCode");d(this,"code");d(this,"why");d(this,"fix");d(this,"link");d(this,"details");d(this,"cause");d(this,"logLevel");Object.setPrototypeOf(this,new.target.prototype),this.status=n.status,this.statusCode=n.statusCode,this.code=n.code,this.why=n.why,this.fix=n.fix,this.link=n.link,this.details=n.details,this.cause=n.cause,this.logLevel=n.logLevel,n.stack?this.stack=n.stack:typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,e);}toJSON(){return {name:"BlypError",message:this.message,status:this.status,statusCode:this.statusCode,...this.code!==void 0?{code:this.code}:{},...this.why!==void 0?{why:this.why}:{},...this.fix!==void 0?{fix:this.fix}:{},...this.link!==void 0?{link:this.link}:{},...this.details!==void 0?{details:this.details}:{}}}};function de(e,t){return t||(e>=500?"critical":e>=400?"error":"warning")}function Ye(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}}:e}function z(e,t,n){let r=de(t.status,n??t.logLevel);(()=>{switch(r){case "debug":return e.debug;case "info":return e.info;case "warning":return e.warning;case "critical":return e.critical;default:return e.error}})()(t.message,{type:"application_error",status:t.status,statusCode:t.statusCode,code:t.code,why:t.why,fix:t.fix,link:t.link,details:t.details,cause:Ye(t.cause)});}function Ve(e,t={}){let r=e.status??e.statusCode??t.status??t.statusCode??500,s=M(r),o=e.message??t.message??s?.message??`HTTP ${r}`;return {status:r,statusCode:r,message:o,code:e.code??t.code??s?.code,why:e.why??t.why??s?.why,fix:e.fix??t.fix??s?.fix,link:e.link??t.link??s?.link,details:e.details??t.details??s?.details,cause:e.cause??t.cause,stack:e.stack??t.stack,logLevel:de(r,e.logLevel??t.logLevel??s?.logLevel)}}function fe(e,t={}){let n=new T(Ve(e,t));return e.skipLogging!==true&&e.logger&&z(e.logger,n,e.logLevel),n}function me(e,t){let n={...e,statusCode:e.status,create(r={}){return fe({status:e.status,message:e.message,code:r.code??e.code,why:r.why??e.why,fix:r.fix??e.fix,link:r.link??e.link,details:r.details??e.details,cause:r.cause,stack:r.stack,logLevel:r.logLevel??e.logLevel,logger:r.logger,skipLogging:r.skipLogging})},extend(r){return me({key:r.code,status:e.status,message:r.message??e.message,code:r.code,why:r.why??e.why,fix:r.fix??e.fix,link:r.link??e.link,details:r.details??e.details,logLevel:r.logLevel??e.logLevel})}};return Object.freeze(n)}function We(e){let t=Object.entries(qe).map(([n,r])=>[n,me({key:n,...r})]);return Object.freeze(Object.fromEntries(t))}var pe=We(),Ze=new Map(Object.values(pe).map(e=>[e.status,e]));function M(e){return Ze.get(e)}function F(e){if(typeof e=="string")return e;if(m(e)){if(e.error!==void 0){let t=e.error;if(typeof t=="string")return B(e,t);if(m(t))return B(e,F(t))}if(m(e.data)){let t=e.data;if(t.error!==void 0||le(t))return B(e,F(t))}if(le(e))return ge(e)}}function ce(e,t={},n={}){if(e instanceof T)return e;let r=(()=>{if(e instanceof Error){let c=e;return {status:c.status,statusCode:c.statusCode,code:c.code,message:e.message,stack:e.stack,why:c.why,fix:c.fix,link:c.link,details:c.details,cause:c.cause,logLevel:c.logLevel}}return F(e)})(),s=n.status&&n.status>0?n.status:void 0,o=typeof r=="string"?void 0:r?.status??r?.statusCode,i=s??o??t.fallbackStatus??500,g=typeof r=="string"&&r.trim()||void 0,C=n.statusText?.trim()||void 0;return fe(typeof r=="string"?{message:g,...s!==void 0?{status:s}:{}}:{...r??{},...s!==void 0?{status:s,statusCode:s}:{}},{status:i,message:(typeof r=="string"?g:r?.message)??C??M(i)?.message??`HTTP ${i}`})}async function Xe(e){let t=e.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")||t?.includes("+json"))try{return await e.clone().json()}catch{try{return await e.clone().text()}catch{return}}try{return await e.clone().text()}catch{return}}function Ke(e,t={}){if(Ge(e))return (async()=>{let r=await Xe(e).catch(()=>{}),s=ce(r,t,{status:e.status,statusText:e.statusText});return t.logger&&z(t.logger,s,t.logLevel),s})();let n=ce(e,t);return t.logger&&z(t.logger,n,t.logLevel),n}export{T as BlypError,pe as HTTP_CODES,ie as createClientLogger,M as getHttpCode,He as logger,Ke as parseError};
|