@chrom-ar/collector 0.0.0-stage → 0.3.0
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/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/dist/index.cjs +1094 -0
- package/dist/index.d.cts +150 -0
- package/dist/index.d.ts +150 -0
- package/dist/index.js +1083 -0
- package/package.json +61 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
1
|
+
// src/dsn.ts
|
|
2
|
+
function parseDsn(dsn) {
|
|
3
|
+
let parsed;
|
|
4
|
+
try {
|
|
5
|
+
parsed = new URL(dsn);
|
|
6
|
+
} catch {
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
|
|
10
|
+
const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
|
|
11
|
+
const key = parsed.username;
|
|
12
|
+
return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/util.ts
|
|
16
|
+
function uuid4() {
|
|
17
|
+
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
18
|
+
const b = crypto.getRandomValues(new Uint8Array(16));
|
|
19
|
+
b[6] = (b[6] ?? 0) & 15 | 64;
|
|
20
|
+
b[8] = (b[8] ?? 0) & 63 | 128;
|
|
21
|
+
const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
22
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
23
|
+
}
|
|
24
|
+
function truncate(s, max) {
|
|
25
|
+
if (s.length <= max) return s;
|
|
26
|
+
const last = s.charCodeAt(max - 1);
|
|
27
|
+
return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
|
|
28
|
+
}
|
|
29
|
+
function safeStringify(value, max = 8192) {
|
|
30
|
+
return truncate(stringify(value), max);
|
|
31
|
+
}
|
|
32
|
+
function stringify(value) {
|
|
33
|
+
if (typeof value === "string") return value;
|
|
34
|
+
if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
|
|
35
|
+
return String(value);
|
|
36
|
+
}
|
|
37
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
38
|
+
try {
|
|
39
|
+
return JSON.stringify(value, (_key, v) => {
|
|
40
|
+
if (typeof v === "bigint") return v.toString();
|
|
41
|
+
if (typeof v === "object" && v !== null) {
|
|
42
|
+
if (seen.has(v)) return "[Circular]";
|
|
43
|
+
seen.add(v);
|
|
44
|
+
}
|
|
45
|
+
return v;
|
|
46
|
+
});
|
|
47
|
+
} catch {
|
|
48
|
+
try {
|
|
49
|
+
return String(value);
|
|
50
|
+
} catch {
|
|
51
|
+
return "[unserializable]";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function stripUrl(url) {
|
|
56
|
+
const i = url.search(/[?#]/);
|
|
57
|
+
return i === -1 ? url : url.slice(0, i);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/stacktrace.ts
|
|
61
|
+
var MAX_FRAMES = 250;
|
|
62
|
+
var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
63
|
+
var GECKO = /^(.*?)@(.*):(\d+):(\d+)$/;
|
|
64
|
+
var V8_EVAL = /\((\S+?):(\d+):(\d+)\)/;
|
|
65
|
+
var GECKO_EVAL = /^(.*?) line (\d+) > (?:eval|Function)/;
|
|
66
|
+
var NOT_FUNCTIONS = /* @__PURE__ */ new Set(["global code", "module code", "eval code"]);
|
|
67
|
+
function parseStack(stack) {
|
|
68
|
+
const frames = [];
|
|
69
|
+
for (const text of stack.split("\n")) {
|
|
70
|
+
const frame = parseV8(text) ?? parseGecko(text);
|
|
71
|
+
if (frame) frames.push(frame);
|
|
72
|
+
}
|
|
73
|
+
return frames;
|
|
74
|
+
}
|
|
75
|
+
function parseV8(text) {
|
|
76
|
+
const m = V8.exec(text);
|
|
77
|
+
if (m?.[2] === void 0) return void 0;
|
|
78
|
+
let url = m[2];
|
|
79
|
+
let line = Number(m[3]);
|
|
80
|
+
let column = Number(m[4]);
|
|
81
|
+
if (url.startsWith("eval at ")) {
|
|
82
|
+
const inner = V8_EVAL.exec(url);
|
|
83
|
+
if (inner?.[1] === void 0) return void 0;
|
|
84
|
+
url = inner[1];
|
|
85
|
+
line = Number(inner[2]);
|
|
86
|
+
column = Number(inner[3]);
|
|
87
|
+
}
|
|
88
|
+
return { function: cleanName(m[1]), url, line, column };
|
|
89
|
+
}
|
|
90
|
+
function parseGecko(text) {
|
|
91
|
+
const m = GECKO.exec(text);
|
|
92
|
+
if (m?.[2] === void 0 || m[2] === "") return void 0;
|
|
93
|
+
let name = m[1];
|
|
94
|
+
const marker = /^([^*]*)\*(.*)$/.exec(name ?? "");
|
|
95
|
+
if (marker) {
|
|
96
|
+
if (marker[1] !== "async") return void 0;
|
|
97
|
+
name = marker[2];
|
|
98
|
+
}
|
|
99
|
+
const evalMatch = GECKO_EVAL.exec(m[2]);
|
|
100
|
+
if (evalMatch?.[1] !== void 0 && evalMatch[1] !== "") return { function: cleanName(name), url: evalMatch[1], line: Number(evalMatch[2]), column: void 0 };
|
|
101
|
+
return { function: cleanName(name), url: m[2], line: Number(m[3]), column: Number(m[4]) };
|
|
102
|
+
}
|
|
103
|
+
function cleanName(name) {
|
|
104
|
+
if (name === void 0 || name === "") return void 0;
|
|
105
|
+
if (NOT_FUNCTIONS.has(name)) return void 0;
|
|
106
|
+
const cleaned = name.replace(/^async\*/, "").replace(/^(?:async|new) /, "").replace(/ \[as [^\]]*\]$/, "").replace(/[/<]+$/, "");
|
|
107
|
+
const bare = cleaned.slice(Math.max(cleaned.lastIndexOf("."), cleaned.lastIndexOf("/")) + 1);
|
|
108
|
+
return bare !== "" && bare !== "<anonymous>" ? bare : void 0;
|
|
109
|
+
}
|
|
110
|
+
function isExtensionUrl(url) {
|
|
111
|
+
return /^(?:chrome|moz|safari|safari-web)-extension:\/\//.test(url);
|
|
112
|
+
}
|
|
113
|
+
var VENDOR_PATTERNS = [
|
|
114
|
+
/\/node_modules\//,
|
|
115
|
+
/\/\.vite\/deps\//,
|
|
116
|
+
// A vendor/ directory, or a bundle named vendor(s)…; not /vendor-portal/App.js.
|
|
117
|
+
/\/vendors?(?:\/|[-.~][^/]*$)/,
|
|
118
|
+
/chunk-vendors/,
|
|
119
|
+
/vendors~/,
|
|
120
|
+
/\/@vite\//,
|
|
121
|
+
/\/@react-refresh/,
|
|
122
|
+
/\/_next\/static\/chunks\/(?:framework|main|webpack)[-.]/
|
|
123
|
+
];
|
|
124
|
+
var HASH_SEGMENT = /[-.~]([A-Za-z0-9_]{8,}|[A-Za-z0-9_-]{8})(?=\.)/g;
|
|
125
|
+
function isHash(token) {
|
|
126
|
+
if (/\d/.test(token)) return true;
|
|
127
|
+
if (token.length !== 8) return false;
|
|
128
|
+
return /[_-]/.test(token) || /[A-Z]/.test(token) && /[a-z]/.test(token) && !/[a-z]{3}/.test(token);
|
|
129
|
+
}
|
|
130
|
+
function normalizeModule(path) {
|
|
131
|
+
const clean = stripUrl(path);
|
|
132
|
+
const slash = clean.lastIndexOf("/") + 1;
|
|
133
|
+
const name = clean.slice(slash).replace(HASH_SEGMENT, (segment, token) => isHash(token) ? "" : segment);
|
|
134
|
+
return clean.slice(0, slash) + name;
|
|
135
|
+
}
|
|
136
|
+
function toFrames(raw, opts) {
|
|
137
|
+
const frames = [];
|
|
138
|
+
for (const r of raw) {
|
|
139
|
+
if (r.function?.startsWith("__collector") === true) continue;
|
|
140
|
+
if (frames.length === MAX_FRAMES) break;
|
|
141
|
+
frames.push(toFrame(r, opts));
|
|
142
|
+
}
|
|
143
|
+
return frames;
|
|
144
|
+
}
|
|
145
|
+
function toFrame(raw, { origin, inAppUrls }) {
|
|
146
|
+
let url;
|
|
147
|
+
try {
|
|
148
|
+
url = new URL(raw.url, origin);
|
|
149
|
+
} catch {
|
|
150
|
+
url = void 0;
|
|
151
|
+
}
|
|
152
|
+
const webpackInternal = raw.url.startsWith("webpack-internal://");
|
|
153
|
+
const sameOrigin = url?.origin === origin || webpackInternal;
|
|
154
|
+
let file = stripUrl(raw.url);
|
|
155
|
+
if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
|
|
156
|
+
const inApp = inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file));
|
|
157
|
+
const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
|
|
158
|
+
if (raw.line !== void 0) frame.line = raw.line;
|
|
159
|
+
if (raw.column !== void 0) frame.column = raw.column;
|
|
160
|
+
return frame;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/event.ts
|
|
164
|
+
var MAX_MESSAGE = 8192;
|
|
165
|
+
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
166
|
+
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
167
|
+
function toLevel(level) {
|
|
168
|
+
if (typeof level !== "string") return "error";
|
|
169
|
+
return LEVELS.has(level) ? level : LEVEL_ALIASES[level] ?? "error";
|
|
170
|
+
}
|
|
171
|
+
var SDK_NAME = "@chrom-ar/collector";
|
|
172
|
+
function isErrorLike(value) {
|
|
173
|
+
if (value instanceof Error) return true;
|
|
174
|
+
if (typeof value !== "object" || value === null) return false;
|
|
175
|
+
const v = value;
|
|
176
|
+
return typeof v.message === "string" && (typeof v.name === "string" || typeof v.stack === "string");
|
|
177
|
+
}
|
|
178
|
+
function errorType(error) {
|
|
179
|
+
if (typeof error.name === "string" && error.name !== "") return error.name;
|
|
180
|
+
const ctor = error.constructor?.name;
|
|
181
|
+
return typeof ctor === "string" && ctor !== "" && ctor !== "Object" ? ctor : "Error";
|
|
182
|
+
}
|
|
183
|
+
function eventFromException(error, env, ctx, mechanism = "manual") {
|
|
184
|
+
const event = baseEvent(env, ctx);
|
|
185
|
+
if (isErrorLike(error)) {
|
|
186
|
+
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
|
|
187
|
+
event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
|
|
188
|
+
if (frames.length > 0) event.exception.frames = frames;
|
|
189
|
+
} else {
|
|
190
|
+
event.exception = {
|
|
191
|
+
type: mechanism === "onunhandledrejection" ? "UnhandledRejection" : "NonError",
|
|
192
|
+
message: safeStringify(error, MAX_MESSAGE)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
return event;
|
|
196
|
+
}
|
|
197
|
+
function eventFromMessage(message, env, ctx) {
|
|
198
|
+
const event = baseEvent(env, ctx);
|
|
199
|
+
event.message = safeStringify(message, MAX_MESSAGE);
|
|
200
|
+
return event;
|
|
201
|
+
}
|
|
202
|
+
function injectedRelease() {
|
|
203
|
+
return typeof __COLLECTOR_RELEASE__ === "string" ? __COLLECTOR_RELEASE__ : void 0;
|
|
204
|
+
}
|
|
205
|
+
function releaseOf(options) {
|
|
206
|
+
const release = options.release ?? injectedRelease();
|
|
207
|
+
return release === "" ? void 0 : release;
|
|
208
|
+
}
|
|
209
|
+
function environmentOf(options) {
|
|
210
|
+
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
211
|
+
}
|
|
212
|
+
function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
|
|
213
|
+
const event = {
|
|
214
|
+
v: 1,
|
|
215
|
+
uuid: uuid4(),
|
|
216
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
217
|
+
platform: "javascript",
|
|
218
|
+
level: toLevel(ctx.level),
|
|
219
|
+
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
220
|
+
sdk: { name: SDK_NAME, version: "0.3.0" }
|
|
221
|
+
};
|
|
222
|
+
const environment = environmentOf(options);
|
|
223
|
+
if (environment !== void 0) event.environment = environment;
|
|
224
|
+
const release = releaseOf(options);
|
|
225
|
+
if (release !== void 0) event.release = release;
|
|
226
|
+
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
227
|
+
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
228
|
+
if (user) event.user = user;
|
|
229
|
+
const tags = { ...scope2.tags, ...ctx.tags };
|
|
230
|
+
if (Object.keys(tags).length > 0) event.tags = tags;
|
|
231
|
+
const breadcrumbs = scope2.getBreadcrumbs();
|
|
232
|
+
if (breadcrumbs.length > 0) event.breadcrumbs = breadcrumbs;
|
|
233
|
+
return event;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// src/filters.ts
|
|
237
|
+
var DEFAULT_IGNORE = [
|
|
238
|
+
"ResizeObserver loop limit exceeded",
|
|
239
|
+
"ResizeObserver loop completed with undelivered notifications",
|
|
240
|
+
// Cross-origin scripts without CORS: the browser hides everything.
|
|
241
|
+
/^(?:Error: )?Script error\.?$/
|
|
242
|
+
];
|
|
243
|
+
function summary(event) {
|
|
244
|
+
const { exception } = event;
|
|
245
|
+
if (!exception) return event.message ?? "";
|
|
246
|
+
return exception.message !== void 0 && exception.message !== "" ? `${exception.type}: ${exception.message}` : exception.type;
|
|
247
|
+
}
|
|
248
|
+
function shouldIgnore(event, patterns) {
|
|
249
|
+
const frames = event.exception?.frames;
|
|
250
|
+
if (frames !== void 0 && frames.length > 0 && frames.every((f) => isExtensionUrl(f.file))) return true;
|
|
251
|
+
const text = summary(event);
|
|
252
|
+
return patterns.some((p) => typeof p === "string" ? text.includes(p) : p.test(text));
|
|
253
|
+
}
|
|
254
|
+
var Deduper = class {
|
|
255
|
+
constructor(windowMs = 1e3) {
|
|
256
|
+
this.windowMs = windowMs;
|
|
257
|
+
this.lastAt = 0;
|
|
258
|
+
}
|
|
259
|
+
isDuplicate(event, now) {
|
|
260
|
+
const frames = (event.exception?.frames ?? []).slice(0, 5).map((f) => `${f.file}:${String(f.line)}:${String(f.column)}`);
|
|
261
|
+
const key = `${summary(event)}
|
|
262
|
+
${frames.join("\n")}`;
|
|
263
|
+
const duplicate = key === this.last && now - this.lastAt <= this.windowMs;
|
|
264
|
+
this.last = key;
|
|
265
|
+
this.lastAt = now;
|
|
266
|
+
return duplicate;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
var RateGuard = class {
|
|
270
|
+
constructor(max = 30, windowMs = 1e4) {
|
|
271
|
+
this.max = max;
|
|
272
|
+
this.windowMs = windowMs;
|
|
273
|
+
this.times = [];
|
|
274
|
+
}
|
|
275
|
+
take(now) {
|
|
276
|
+
this.times = this.times.filter((t) => now - t < this.windowMs);
|
|
277
|
+
if (this.times.length >= this.max) return false;
|
|
278
|
+
this.times.push(now);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// src/handlers.ts
|
|
284
|
+
function installGlobalHandlers(win, onError, opts) {
|
|
285
|
+
const onErrorEvent = (event) => {
|
|
286
|
+
try {
|
|
287
|
+
if (typeof event.target?.nodeType === "number") return;
|
|
288
|
+
const e = event;
|
|
289
|
+
onError(e.error ?? errorFromLocation(e), "onerror");
|
|
290
|
+
} catch {
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const onRejection = (event) => {
|
|
294
|
+
try {
|
|
295
|
+
onError(event.reason, "onunhandledrejection");
|
|
296
|
+
} catch {
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
if (opts.onerror) win.addEventListener("error", onErrorEvent);
|
|
300
|
+
if (opts.onunhandledrejection) win.addEventListener("unhandledrejection", onRejection);
|
|
301
|
+
return () => {
|
|
302
|
+
win.removeEventListener("error", onErrorEvent);
|
|
303
|
+
win.removeEventListener("unhandledrejection", onRejection);
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
var THROWN_NOTHING = /^(?:Uncaught |uncaught exception: )?(null|undefined)$/;
|
|
307
|
+
function errorFromLocation(e) {
|
|
308
|
+
const nothing = THROWN_NOTHING.exec(e.message);
|
|
309
|
+
const error = new Error(nothing?.[1] ?? (e.message !== "" ? e.message : "Unknown error"));
|
|
310
|
+
if (nothing) error.name = "NonError";
|
|
311
|
+
error.stack = typeof e.filename === "string" && e.filename !== "" ? `${error.name}: ${error.message}
|
|
312
|
+
at ? (${e.filename}:${String(e.lineno)}:${String(e.colno)})` : "";
|
|
313
|
+
return error;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// src/heartbeat.ts
|
|
317
|
+
var HEARTBEAT_DELAY_MS = 5e3;
|
|
318
|
+
var STORAGE_PREFIX = "collector:heartbeat:";
|
|
319
|
+
var sentThisPage = /* @__PURE__ */ new Set();
|
|
320
|
+
function scheduleHeartbeat(deps) {
|
|
321
|
+
let idle;
|
|
322
|
+
const run = () => {
|
|
323
|
+
void beat(deps);
|
|
324
|
+
};
|
|
325
|
+
const timer = setTimeout(() => {
|
|
326
|
+
if ("requestIdleCallback" in globalThis) idle = requestIdleCallback(run, { timeout: HEARTBEAT_DELAY_MS });
|
|
327
|
+
else run();
|
|
328
|
+
}, HEARTBEAT_DELAY_MS);
|
|
329
|
+
return () => {
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
if (idle !== void 0) cancelIdleCallback(idle);
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function storedMark(storageKey) {
|
|
335
|
+
try {
|
|
336
|
+
return localStorage.getItem(storageKey);
|
|
337
|
+
} catch {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async function beat({ url, key, fetch, options, logger }) {
|
|
342
|
+
const release = releaseOf(options);
|
|
343
|
+
const environment = environmentOf(options);
|
|
344
|
+
const storageKey = STORAGE_PREFIX + key;
|
|
345
|
+
const mark = JSON.stringify([(/* @__PURE__ */ new Date()).toISOString().slice(0, 10), release ?? "", environment ?? ""]);
|
|
346
|
+
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
347
|
+
let status;
|
|
348
|
+
try {
|
|
349
|
+
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.0" }, environment, release });
|
|
350
|
+
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
351
|
+
({ status } = response);
|
|
352
|
+
} catch (error) {
|
|
353
|
+
logger.debug("heartbeat not sent", error);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (status === 429 || status >= 500) return;
|
|
357
|
+
try {
|
|
358
|
+
localStorage.setItem(storageKey, mark);
|
|
359
|
+
} catch {
|
|
360
|
+
sentThisPage.add(storageKey + mark);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/instrument/common.ts
|
|
365
|
+
var ORIGINAL = "__collector_original__";
|
|
366
|
+
function wrap(obj, name, make) {
|
|
367
|
+
const current = obj[name];
|
|
368
|
+
if (typeof current !== "function" || current[ORIGINAL] !== void 0) return () => true;
|
|
369
|
+
const wrapper = make(current);
|
|
370
|
+
Object.defineProperty(wrapper, ORIGINAL, { value: current });
|
|
371
|
+
obj[name] = wrapper;
|
|
372
|
+
return () => {
|
|
373
|
+
if (obj[name] !== wrapper) return false;
|
|
374
|
+
obj[name] = current;
|
|
375
|
+
return true;
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function safeRecord(fn) {
|
|
379
|
+
try {
|
|
380
|
+
fn();
|
|
381
|
+
} catch {
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function displayUrl(win, url, stripQuery) {
|
|
385
|
+
let shown = url;
|
|
386
|
+
try {
|
|
387
|
+
const parsed = new URL(url, win.location.href);
|
|
388
|
+
parsed.username = "";
|
|
389
|
+
parsed.password = "";
|
|
390
|
+
shown = parsed.origin === win.location.origin ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
|
|
391
|
+
} catch {
|
|
392
|
+
}
|
|
393
|
+
return stripQuery ? stripUrl(shown) : shown;
|
|
394
|
+
}
|
|
395
|
+
function absoluteUrl(win, url) {
|
|
396
|
+
try {
|
|
397
|
+
return new URL(url, win.location.href).href;
|
|
398
|
+
} catch {
|
|
399
|
+
return url;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function levelForStatus(status) {
|
|
403
|
+
if (status === void 0 || status >= 500) return "error";
|
|
404
|
+
return status >= 400 ? "warning" : "info";
|
|
405
|
+
}
|
|
406
|
+
function requestMessage(method, url, status) {
|
|
407
|
+
return `${method.toUpperCase()} ${url} \u2192 ${status === void 0 ? "failed" : String(status)}`;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// src/instrument/console.ts
|
|
411
|
+
var LEVELS2 = { error: "error", warn: "warning", log: "info", info: "info" };
|
|
412
|
+
var MAX_KEYS = 10;
|
|
413
|
+
var MAX_STRING = 100;
|
|
414
|
+
function describeValue(value, nested = false) {
|
|
415
|
+
if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
|
|
416
|
+
if (value === null || typeof value !== "object") {
|
|
417
|
+
return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
|
|
418
|
+
}
|
|
419
|
+
const v = value;
|
|
420
|
+
if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
|
|
421
|
+
return `${String(v.name)}: ${String(v.message)}`;
|
|
422
|
+
}
|
|
423
|
+
if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
|
|
424
|
+
if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
|
|
425
|
+
if (Array.isArray(value)) {
|
|
426
|
+
const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
|
|
427
|
+
return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
|
|
428
|
+
}
|
|
429
|
+
try {
|
|
430
|
+
const keys = Object.keys(value);
|
|
431
|
+
const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
|
|
432
|
+
return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
|
|
433
|
+
} catch {
|
|
434
|
+
return "{\u2026}";
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function instrumentConsole(win, record, _opts) {
|
|
438
|
+
const target = win.console;
|
|
439
|
+
const restores = Object.keys(LEVELS2).map(
|
|
440
|
+
(method) => wrap(
|
|
441
|
+
target,
|
|
442
|
+
method,
|
|
443
|
+
(original) => function __collectorWrapped(...args) {
|
|
444
|
+
safeRecord(() => {
|
|
445
|
+
record({ category: "console", level: LEVELS2[method], message: truncate(args.map((a) => describeValue(a)).join(" "), 500) });
|
|
446
|
+
});
|
|
447
|
+
original.apply(this, args);
|
|
448
|
+
}
|
|
449
|
+
)
|
|
450
|
+
);
|
|
451
|
+
return () => restores.map((restore) => restore()).every(Boolean);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/instrument/dom.ts
|
|
455
|
+
var MAX_DEPTH = 3;
|
|
456
|
+
function describe(element) {
|
|
457
|
+
const parts = [];
|
|
458
|
+
let el = element;
|
|
459
|
+
while (el && parts.length < MAX_DEPTH && el.tagName !== "BODY" && el.tagName !== "HTML") {
|
|
460
|
+
let part = el.tagName.toLowerCase();
|
|
461
|
+
if (el.id !== "") part += `#${el.id}`;
|
|
462
|
+
for (const cls of Array.from(el.classList)) part += `.${cls}`;
|
|
463
|
+
parts.unshift(part);
|
|
464
|
+
el = el.parentElement;
|
|
465
|
+
}
|
|
466
|
+
return parts.join(" > ");
|
|
467
|
+
}
|
|
468
|
+
function instrumentDom(win, record, _opts) {
|
|
469
|
+
const onClick = (event) => {
|
|
470
|
+
safeRecord(() => {
|
|
471
|
+
const target = event.target;
|
|
472
|
+
if (target?.nodeType !== 1) return;
|
|
473
|
+
const message = describe(target);
|
|
474
|
+
if (message !== "") record({ category: "ui.click", level: "info", message });
|
|
475
|
+
});
|
|
476
|
+
};
|
|
477
|
+
win.document.addEventListener("click", onClick, true);
|
|
478
|
+
return () => {
|
|
479
|
+
win.document.removeEventListener("click", onClick, true);
|
|
480
|
+
return true;
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/instrument/fetch.ts
|
|
485
|
+
function describe2(input, init2) {
|
|
486
|
+
const isRequest = typeof Request !== "undefined" && input instanceof Request;
|
|
487
|
+
let url;
|
|
488
|
+
if (isRequest) url = input.url;
|
|
489
|
+
else if (input instanceof URL) url = input.href;
|
|
490
|
+
else url = String(input);
|
|
491
|
+
const method = init2?.method ?? (isRequest ? input.method : "GET");
|
|
492
|
+
return { method, url };
|
|
493
|
+
}
|
|
494
|
+
function instrumentFetch(win, record, opts) {
|
|
495
|
+
return wrap(
|
|
496
|
+
win,
|
|
497
|
+
"fetch",
|
|
498
|
+
(original) => async function __collectorWrapped(input, init2) {
|
|
499
|
+
const promise = original.apply(this, arguments);
|
|
500
|
+
let done = (_status) => void 0;
|
|
501
|
+
safeRecord(() => {
|
|
502
|
+
const { method, url } = describe2(input, init2);
|
|
503
|
+
if (opts.skipUrl(absoluteUrl(win, url))) return;
|
|
504
|
+
const shown = displayUrl(win, url, opts.stripQuery);
|
|
505
|
+
done = (status) => {
|
|
506
|
+
safeRecord(() => {
|
|
507
|
+
record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
|
|
508
|
+
});
|
|
509
|
+
};
|
|
510
|
+
});
|
|
511
|
+
return promise.then(
|
|
512
|
+
(response) => {
|
|
513
|
+
done(response.status);
|
|
514
|
+
return response;
|
|
515
|
+
},
|
|
516
|
+
(error) => {
|
|
517
|
+
done(void 0);
|
|
518
|
+
throw error;
|
|
519
|
+
}
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/instrument/history.ts
|
|
526
|
+
function instrumentHistory(win, record, opts) {
|
|
527
|
+
const here = () => {
|
|
528
|
+
const shown = displayUrl(win, win.location.href, opts.stripQuery);
|
|
529
|
+
const { hash } = win.location;
|
|
530
|
+
if (!opts.stripQuery || !/^#!?\//.test(hash)) return shown;
|
|
531
|
+
return `${shown}#${stripUrl(hash.slice(1))}`;
|
|
532
|
+
};
|
|
533
|
+
let last = here();
|
|
534
|
+
const moved = () => {
|
|
535
|
+
safeRecord(() => {
|
|
536
|
+
const to = here();
|
|
537
|
+
if (to === last) return;
|
|
538
|
+
record({ category: "navigation", level: "info", message: `${last} \u2192 ${to}` });
|
|
539
|
+
last = to;
|
|
540
|
+
});
|
|
541
|
+
};
|
|
542
|
+
const wrapState = (name) => wrap(
|
|
543
|
+
win.history,
|
|
544
|
+
name,
|
|
545
|
+
(original) => function __collectorWrapped(...args) {
|
|
546
|
+
original.apply(this, args);
|
|
547
|
+
moved();
|
|
548
|
+
}
|
|
549
|
+
);
|
|
550
|
+
const restores = [wrapState("pushState"), wrapState("replaceState")];
|
|
551
|
+
win.addEventListener("popstate", moved);
|
|
552
|
+
win.addEventListener("hashchange", moved);
|
|
553
|
+
return () => {
|
|
554
|
+
if (!restores.map((restore) => restore()).every(Boolean)) return false;
|
|
555
|
+
win.removeEventListener("popstate", moved);
|
|
556
|
+
win.removeEventListener("hashchange", moved);
|
|
557
|
+
return true;
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/instrument/xhr.ts
|
|
562
|
+
function instrumentXhr(win, record, opts) {
|
|
563
|
+
const Xhr = win.XMLHttpRequest;
|
|
564
|
+
if (!Xhr) return () => true;
|
|
565
|
+
const proto = Xhr.prototype;
|
|
566
|
+
const requests = /* @__PURE__ */ new WeakMap();
|
|
567
|
+
const restoreOpen = wrap(
|
|
568
|
+
proto,
|
|
569
|
+
"open",
|
|
570
|
+
(original) => function __collectorWrapped(...args) {
|
|
571
|
+
safeRecord(() => {
|
|
572
|
+
const [method, url] = args;
|
|
573
|
+
requests.set(this, { method: String(method), url: url instanceof URL ? url.href : String(url) });
|
|
574
|
+
});
|
|
575
|
+
original.apply(this, args);
|
|
576
|
+
}
|
|
577
|
+
);
|
|
578
|
+
const restoreSend = wrap(
|
|
579
|
+
proto,
|
|
580
|
+
"send",
|
|
581
|
+
(original) => function __collectorWrapped(body) {
|
|
582
|
+
safeRecord(() => {
|
|
583
|
+
const request = requests.get(this);
|
|
584
|
+
if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
|
|
585
|
+
const shown = displayUrl(win, request.url, opts.stripQuery);
|
|
586
|
+
this.addEventListener("loadend", () => {
|
|
587
|
+
safeRecord(() => {
|
|
588
|
+
const status = this.status !== 0 ? this.status : void 0;
|
|
589
|
+
record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
|
|
590
|
+
});
|
|
591
|
+
}, { once: true });
|
|
592
|
+
});
|
|
593
|
+
original.call(this, body);
|
|
594
|
+
}
|
|
595
|
+
);
|
|
596
|
+
return () => [restoreOpen(), restoreSend()].every(Boolean);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/logger.ts
|
|
600
|
+
function createLogger(isDebug) {
|
|
601
|
+
const warned = /* @__PURE__ */ new Set();
|
|
602
|
+
const { debug, warn } = console;
|
|
603
|
+
return {
|
|
604
|
+
debug(...args) {
|
|
605
|
+
if (isDebug()) debug.call(console, "[collector]", ...args);
|
|
606
|
+
},
|
|
607
|
+
warnOnce(message) {
|
|
608
|
+
if (warned.has(message)) return;
|
|
609
|
+
warned.add(message);
|
|
610
|
+
warn.call(console, `[collector] ${message}`);
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/scope.ts
|
|
616
|
+
var BREADCRUMB_MESSAGE_LENGTH = 500;
|
|
617
|
+
var Scope = class {
|
|
618
|
+
constructor() {
|
|
619
|
+
this.tags = {};
|
|
620
|
+
this.breadcrumbs = [];
|
|
621
|
+
}
|
|
622
|
+
setUser(user) {
|
|
623
|
+
this.user = user ? { id: String(user.id) } : void 0;
|
|
624
|
+
}
|
|
625
|
+
setTag(key, value) {
|
|
626
|
+
this.tags[key] = String(value);
|
|
627
|
+
}
|
|
628
|
+
setTags(tags) {
|
|
629
|
+
for (const [key, value] of Object.entries(tags)) this.setTag(key, value);
|
|
630
|
+
}
|
|
631
|
+
addBreadcrumb(crumb, max) {
|
|
632
|
+
this.breadcrumbs.push({
|
|
633
|
+
...crumb,
|
|
634
|
+
timestamp: crumb.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
635
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-conversion -- plain-JS callers
|
|
636
|
+
message: truncate(String(crumb.message), BREADCRUMB_MESSAGE_LENGTH)
|
|
637
|
+
});
|
|
638
|
+
if (this.breadcrumbs.length > max) this.breadcrumbs.splice(0, this.breadcrumbs.length - max);
|
|
639
|
+
}
|
|
640
|
+
/** Oldest first. */
|
|
641
|
+
getBreadcrumbs() {
|
|
642
|
+
return this.breadcrumbs.map((c) => ({ ...c }));
|
|
643
|
+
}
|
|
644
|
+
clear() {
|
|
645
|
+
this.user = void 0;
|
|
646
|
+
this.tags = {};
|
|
647
|
+
this.breadcrumbs = [];
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
// src/transport.ts
|
|
652
|
+
var FIRST_BACKOFF = 1e3;
|
|
653
|
+
var MAX_BACKOFF = 6e4;
|
|
654
|
+
var MAX_ATTEMPTS = 8;
|
|
655
|
+
var DEFAULT_PAUSE = 60;
|
|
656
|
+
var KEEPALIVE_LIMIT = 6e4;
|
|
657
|
+
var MAX_BODY = 1e6;
|
|
658
|
+
var FRAMES_WHEN_TOO_BIG = 50;
|
|
659
|
+
var encoder = new TextEncoder();
|
|
660
|
+
var byteLength = (s) => encoder.encode(s).length;
|
|
661
|
+
var Transport = class {
|
|
662
|
+
constructor(deps) {
|
|
663
|
+
this.deps = deps;
|
|
664
|
+
this.disabled = false;
|
|
665
|
+
this.queue = [];
|
|
666
|
+
this.inFlight = false;
|
|
667
|
+
this.paused = false;
|
|
668
|
+
this.backoff = FIRST_BACKOFF;
|
|
669
|
+
this.inFlightKeepaliveBytes = 0;
|
|
670
|
+
this.idleWaiters = [];
|
|
671
|
+
this.maxQueue = deps.maxQueue ?? 30;
|
|
672
|
+
}
|
|
673
|
+
/** Queues the event. Never blocks, never throws. */
|
|
674
|
+
send(event) {
|
|
675
|
+
if (this.disabled) return;
|
|
676
|
+
if (this.queue.length >= this.maxQueue) {
|
|
677
|
+
this.queue.shift();
|
|
678
|
+
this.deps.logger.debug("queue full, dropped the oldest event");
|
|
679
|
+
}
|
|
680
|
+
this.queue.push({ event, attempts: 0 });
|
|
681
|
+
this.dispatch();
|
|
682
|
+
}
|
|
683
|
+
/** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
|
|
684
|
+
async flush(timeoutMs = 2e3) {
|
|
685
|
+
if (this.isIdle()) return Promise.resolve(true);
|
|
686
|
+
return new Promise((resolve) => {
|
|
687
|
+
const timer = setTimeout(() => {
|
|
688
|
+
this.idleWaiters = this.idleWaiters.filter((w) => w !== done);
|
|
689
|
+
resolve(false);
|
|
690
|
+
}, timeoutMs);
|
|
691
|
+
const done = () => {
|
|
692
|
+
clearTimeout(timer);
|
|
693
|
+
resolve(true);
|
|
694
|
+
};
|
|
695
|
+
this.idleWaiters.push(done);
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* The page is going away: send everything queued at once, with keepalive
|
|
700
|
+
* while the browser's 64 KB budget lasts. Answers are ignored.
|
|
701
|
+
*/
|
|
702
|
+
sendQueuedNow() {
|
|
703
|
+
if (this.disabled || this.paused) return;
|
|
704
|
+
let budget = KEEPALIVE_LIMIT - this.inFlightKeepaliveBytes;
|
|
705
|
+
for (const { event } of this.queue.splice(0)) {
|
|
706
|
+
const body = encode(event);
|
|
707
|
+
if (body === void 0) continue;
|
|
708
|
+
const size = byteLength(body);
|
|
709
|
+
const keepalive = size <= budget;
|
|
710
|
+
if (keepalive) budget -= size;
|
|
711
|
+
try {
|
|
712
|
+
this.deps.fetch(this.deps.url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive, credentials: "omit" }).catch(() => void 0);
|
|
713
|
+
} catch {
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
this.notifyIfIdle();
|
|
717
|
+
}
|
|
718
|
+
isIdle() {
|
|
719
|
+
return !this.inFlight && (this.queue.length === 0 || this.disabled);
|
|
720
|
+
}
|
|
721
|
+
dispatch() {
|
|
722
|
+
const pending = this.inFlight || this.paused || this.disabled ? void 0 : this.queue.shift();
|
|
723
|
+
if (!pending) {
|
|
724
|
+
this.notifyIfIdle();
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const body = encode(pending.event);
|
|
728
|
+
if (body === void 0) {
|
|
729
|
+
this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
|
|
730
|
+
this.dispatch();
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
this.inFlight = true;
|
|
734
|
+
const size = byteLength(body);
|
|
735
|
+
const keepalive = size <= KEEPALIVE_LIMIT;
|
|
736
|
+
this.inFlightKeepaliveBytes = keepalive ? size : 0;
|
|
737
|
+
let request;
|
|
738
|
+
try {
|
|
739
|
+
request = this.deps.fetch(this.deps.url, {
|
|
740
|
+
method: "POST",
|
|
741
|
+
body,
|
|
742
|
+
headers: { "Content-Type": "text/plain;charset=UTF-8" },
|
|
743
|
+
keepalive,
|
|
744
|
+
credentials: "omit"
|
|
745
|
+
});
|
|
746
|
+
} catch (error) {
|
|
747
|
+
request = Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
748
|
+
}
|
|
749
|
+
request.then(
|
|
750
|
+
(response) => {
|
|
751
|
+
this.handle(pending, response);
|
|
752
|
+
},
|
|
753
|
+
(error) => {
|
|
754
|
+
this.retry(pending, error);
|
|
755
|
+
}
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
handle(pending, response) {
|
|
759
|
+
this.inFlight = false;
|
|
760
|
+
this.inFlightKeepaliveBytes = 0;
|
|
761
|
+
const { status } = response;
|
|
762
|
+
if (status >= 200 && status < 300) {
|
|
763
|
+
this.backoff = FIRST_BACKOFF;
|
|
764
|
+
} else if (status === 429) {
|
|
765
|
+
this.backoff = FIRST_BACKOFF;
|
|
766
|
+
this.pause(retryAfter(response.headers.get("Retry-After")) * 1e3);
|
|
767
|
+
} else if (status === 401 || status === 403) {
|
|
768
|
+
this.disable(status);
|
|
769
|
+
} else if (status >= 500) {
|
|
770
|
+
this.retry(pending, `HTTP ${String(status)}`);
|
|
771
|
+
return;
|
|
772
|
+
} else {
|
|
773
|
+
const { logger } = this.deps;
|
|
774
|
+
response.text().then(
|
|
775
|
+
(body) => {
|
|
776
|
+
logger.debug(`Collector rejected an event (HTTP ${String(status)})`, pending.event.uuid, body);
|
|
777
|
+
},
|
|
778
|
+
() => {
|
|
779
|
+
logger.debug(`Collector rejected an event (HTTP ${String(status)})`, pending.event.uuid);
|
|
780
|
+
}
|
|
781
|
+
);
|
|
782
|
+
}
|
|
783
|
+
this.dispatch();
|
|
784
|
+
}
|
|
785
|
+
retry(pending, error) {
|
|
786
|
+
this.inFlight = false;
|
|
787
|
+
this.inFlightKeepaliveBytes = 0;
|
|
788
|
+
pending.attempts += 1;
|
|
789
|
+
if (pending.attempts >= MAX_ATTEMPTS) {
|
|
790
|
+
this.deps.logger.debug(`gave up on an event after ${String(pending.attempts)} tries`, error);
|
|
791
|
+
} else {
|
|
792
|
+
this.deps.logger.debug("sending failed, will retry", error);
|
|
793
|
+
this.queue.unshift(pending);
|
|
794
|
+
}
|
|
795
|
+
const wait = this.backoff;
|
|
796
|
+
this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF);
|
|
797
|
+
this.pause(wait);
|
|
798
|
+
}
|
|
799
|
+
pause(ms) {
|
|
800
|
+
this.paused = true;
|
|
801
|
+
setTimeout(() => {
|
|
802
|
+
this.paused = false;
|
|
803
|
+
this.dispatch();
|
|
804
|
+
}, ms);
|
|
805
|
+
}
|
|
806
|
+
disable(status) {
|
|
807
|
+
this.disabled = true;
|
|
808
|
+
this.queue = [];
|
|
809
|
+
this.deps.onDisable?.();
|
|
810
|
+
const where = this.deps.origin ?? "unknown origin";
|
|
811
|
+
this.deps.logger.warnOnce(
|
|
812
|
+
status === 401 ? "Collector rejected the key (HTTP 401): check the DSN on your project's setup page. Nothing more will be sent from this page." : `This site's domain (${where}) is blocked for this project in Collector (HTTP 403). Events won't be sent from this page. A project admin can unblock it in the project's settings.`
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
notifyIfIdle() {
|
|
816
|
+
if (!this.isIdle()) return;
|
|
817
|
+
const waiters = this.idleWaiters;
|
|
818
|
+
this.idleWaiters = [];
|
|
819
|
+
for (const w of waiters) w();
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
function retryAfter(header) {
|
|
823
|
+
const seconds = Number.parseInt(header ?? "", 10);
|
|
824
|
+
return seconds >= 0 ? seconds : DEFAULT_PAUSE;
|
|
825
|
+
}
|
|
826
|
+
function encode(event) {
|
|
827
|
+
try {
|
|
828
|
+
return encodeWithin(event);
|
|
829
|
+
} catch {
|
|
830
|
+
return void 0;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
function encodeWithin(event) {
|
|
834
|
+
let body = JSON.stringify(event);
|
|
835
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
836
|
+
const trimmed = { ...event };
|
|
837
|
+
delete trimmed.breadcrumbs;
|
|
838
|
+
body = JSON.stringify(trimmed);
|
|
839
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
840
|
+
if (trimmed.exception?.frames) {
|
|
841
|
+
trimmed.exception = { ...trimmed.exception, frames: trimmed.exception.frames.slice(0, FRAMES_WHEN_TOO_BIG) };
|
|
842
|
+
body = JSON.stringify(trimmed);
|
|
843
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
844
|
+
}
|
|
845
|
+
return void 0;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/client.ts
|
|
849
|
+
var INSTRUMENTS = {
|
|
850
|
+
console: instrumentConsole,
|
|
851
|
+
dom: instrumentDom,
|
|
852
|
+
fetch: instrumentFetch,
|
|
853
|
+
xhr: instrumentXhr,
|
|
854
|
+
history: instrumentHistory
|
|
855
|
+
};
|
|
856
|
+
var DEFAULT_MAX_BREADCRUMBS = 50;
|
|
857
|
+
var active;
|
|
858
|
+
var installed = /* @__PURE__ */ new Map();
|
|
859
|
+
var sharedOptions = {
|
|
860
|
+
skipUrl: (url) => active?.isOwnUrl(url) ?? false,
|
|
861
|
+
get stripQuery() {
|
|
862
|
+
return active?.options.stripQuery !== false;
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
var rejected = /* @__PURE__ */ new Set();
|
|
866
|
+
var recorderFor = (kind) => (crumb) => {
|
|
867
|
+
if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
|
|
868
|
+
};
|
|
869
|
+
function unwrapped(fn) {
|
|
870
|
+
return fn.__collector_original__ ?? fn;
|
|
871
|
+
}
|
|
872
|
+
var Client = class {
|
|
873
|
+
constructor(options, win, scope2 = new Scope()) {
|
|
874
|
+
this.options = options;
|
|
875
|
+
this.win = win;
|
|
876
|
+
this.scope = scope2;
|
|
877
|
+
this.cleanups = [];
|
|
878
|
+
this.deduper = new Deduper();
|
|
879
|
+
this.rateGuard = new RateGuard();
|
|
880
|
+
this.closed = false;
|
|
881
|
+
this.logger = createLogger(() => options.debug === true);
|
|
882
|
+
this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
|
|
883
|
+
if (options.enabled === false) {
|
|
884
|
+
this.logger.debug("disabled (enabled: false): nothing will be sent");
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
if (typeof options.dsn !== "string" || options.dsn === "") {
|
|
888
|
+
this.logger.debug("no DSN given: nothing will be sent");
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
const endpoint = parseDsn(options.dsn);
|
|
892
|
+
if (!endpoint) {
|
|
893
|
+
this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
this.endpointBase = endpoint.base;
|
|
897
|
+
const fetchFn = unwrapped(win.fetch).bind(win);
|
|
898
|
+
const { url } = endpoint;
|
|
899
|
+
this.transport = new Transport({ url, fetch: fetchFn, logger: this.logger, origin: win.location.origin, onDisable: () => rejected.add(url) });
|
|
900
|
+
if (rejected.has(url)) {
|
|
901
|
+
this.transport.disabled = true;
|
|
902
|
+
this.logger.debug("Collector already rejected this DSN on this page: nothing will be sent");
|
|
903
|
+
} else if (options.heartbeat !== false) {
|
|
904
|
+
this.cleanups.push(scheduleHeartbeat({ url: endpoint.heartbeatUrl, key: endpoint.key, fetch: fetchFn, options, logger: this.logger }));
|
|
905
|
+
}
|
|
906
|
+
const auto = options.autoCapture;
|
|
907
|
+
if (auto !== false) {
|
|
908
|
+
this.cleanups.push(
|
|
909
|
+
installGlobalHandlers(
|
|
910
|
+
win,
|
|
911
|
+
(error, mechanism) => this.captureException(error, void 0, mechanism),
|
|
912
|
+
{ onerror: auto?.onerror !== false, onunhandledrejection: auto?.onunhandledrejection !== false }
|
|
913
|
+
)
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
active = this;
|
|
917
|
+
for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
|
|
918
|
+
if (options.breadcrumbs?.[kind] === false || installed.has(kind)) continue;
|
|
919
|
+
try {
|
|
920
|
+
installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
|
|
921
|
+
} catch (error) {
|
|
922
|
+
this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
const onPageHide = () => {
|
|
926
|
+
this.transport?.sendQueuedNow();
|
|
927
|
+
};
|
|
928
|
+
win.addEventListener("pagehide", onPageHide);
|
|
929
|
+
this.cleanups.push(() => {
|
|
930
|
+
win.removeEventListener("pagehide", onPageHide);
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
captureException(error, ctx, mechanism = "manual") {
|
|
934
|
+
return this.capture(() => eventFromException(error, this.env(), ctx, mechanism));
|
|
935
|
+
}
|
|
936
|
+
captureMessage(message, ctx) {
|
|
937
|
+
const context = typeof ctx === "string" ? { level: ctx } : ctx;
|
|
938
|
+
return this.capture(() => eventFromMessage(message, this.env(), context));
|
|
939
|
+
}
|
|
940
|
+
addBreadcrumb(crumb) {
|
|
941
|
+
this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
|
|
942
|
+
}
|
|
943
|
+
async flush(timeoutMs) {
|
|
944
|
+
return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
|
|
945
|
+
}
|
|
946
|
+
/** True for requests to Collector itself. */
|
|
947
|
+
isOwnUrl(url) {
|
|
948
|
+
return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
|
|
949
|
+
}
|
|
950
|
+
/** Removes every listener and wrapper it can. Events already queued still go out. */
|
|
951
|
+
close() {
|
|
952
|
+
this.closed = true;
|
|
953
|
+
if (active === this) {
|
|
954
|
+
active = void 0;
|
|
955
|
+
for (const [kind, restore] of installed) {
|
|
956
|
+
try {
|
|
957
|
+
if (restore()) installed.delete(kind);
|
|
958
|
+
} catch {
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
for (const cleanup of this.cleanups.splice(0).reverse()) {
|
|
963
|
+
try {
|
|
964
|
+
cleanup();
|
|
965
|
+
} catch (error) {
|
|
966
|
+
this.logger.debug("cleanup failed", error);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
env() {
|
|
971
|
+
const { win } = this;
|
|
972
|
+
return {
|
|
973
|
+
options: this.options,
|
|
974
|
+
scope: this.scope,
|
|
975
|
+
origin: win.location.origin,
|
|
976
|
+
href: win.location.href,
|
|
977
|
+
userAgent: win.navigator.userAgent
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
capture(build) {
|
|
981
|
+
const transport = this.transport;
|
|
982
|
+
if (!transport || this.closed || transport.disabled) return void 0;
|
|
983
|
+
const event = build();
|
|
984
|
+
if (shouldIgnore(event, this.ignore)) {
|
|
985
|
+
this.logger.debug("ignored", event.exception?.type ?? event.message);
|
|
986
|
+
return void 0;
|
|
987
|
+
}
|
|
988
|
+
const now = Date.now();
|
|
989
|
+
if (this.deduper.isDuplicate(event, now)) return void 0;
|
|
990
|
+
const final = this.beforeSend(event);
|
|
991
|
+
if (!final) return void 0;
|
|
992
|
+
if (!this.rateGuard.take(now)) {
|
|
993
|
+
this.logger.debug("too many events, dropped one");
|
|
994
|
+
return void 0;
|
|
995
|
+
}
|
|
996
|
+
transport.send(final);
|
|
997
|
+
return final.uuid;
|
|
998
|
+
}
|
|
999
|
+
beforeSend(event) {
|
|
1000
|
+
const hook = this.options.beforeSend;
|
|
1001
|
+
if (!hook) return event;
|
|
1002
|
+
let result;
|
|
1003
|
+
try {
|
|
1004
|
+
result = hook(event);
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
this.logger.debug("beforeSend threw; sending the event unchanged", error);
|
|
1007
|
+
return event;
|
|
1008
|
+
}
|
|
1009
|
+
if (result === null) return void 0;
|
|
1010
|
+
if ((typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
|
|
1011
|
+
this.logger.warnOnce("beforeSend returned a Promise, so the event was dropped. It must return the event (or null) right away, not async.");
|
|
1012
|
+
return void 0;
|
|
1013
|
+
}
|
|
1014
|
+
if (typeof result !== "object" || Array.isArray(result) || !("uuid" in result) || typeof result.uuid !== "string") {
|
|
1015
|
+
this.logger.debug("beforeSend returned neither an event nor null; dropped", result);
|
|
1016
|
+
return void 0;
|
|
1017
|
+
}
|
|
1018
|
+
return result;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
// src/index.ts
|
|
1023
|
+
var SDK_VERSION = "0.3.0";
|
|
1024
|
+
var client;
|
|
1025
|
+
var pendingScope = new Scope();
|
|
1026
|
+
function scope() {
|
|
1027
|
+
return client?.scope ?? pendingScope;
|
|
1028
|
+
}
|
|
1029
|
+
function safely(fn, fallback) {
|
|
1030
|
+
try {
|
|
1031
|
+
return fn();
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
client?.logger.debug("internal error", error);
|
|
1034
|
+
return fallback;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
function init(options) {
|
|
1038
|
+
safely(() => {
|
|
1039
|
+
if (typeof window === "undefined") return;
|
|
1040
|
+
const kept = scope();
|
|
1041
|
+
client?.close();
|
|
1042
|
+
client = new Client(options, window, kept);
|
|
1043
|
+
}, void 0);
|
|
1044
|
+
}
|
|
1045
|
+
function captureException(error, context) {
|
|
1046
|
+
return safely(() => client?.captureException(error, context), void 0);
|
|
1047
|
+
}
|
|
1048
|
+
function captureMessage(message, context) {
|
|
1049
|
+
return safely(() => client?.captureMessage(message, context), void 0);
|
|
1050
|
+
}
|
|
1051
|
+
function setUser(user) {
|
|
1052
|
+
safely(() => {
|
|
1053
|
+
scope().setUser(user);
|
|
1054
|
+
}, void 0);
|
|
1055
|
+
}
|
|
1056
|
+
function setTag(key, value) {
|
|
1057
|
+
safely(() => {
|
|
1058
|
+
scope().setTag(key, value);
|
|
1059
|
+
}, void 0);
|
|
1060
|
+
}
|
|
1061
|
+
function setTags(tags) {
|
|
1062
|
+
safely(() => {
|
|
1063
|
+
scope().setTags(tags);
|
|
1064
|
+
}, void 0);
|
|
1065
|
+
}
|
|
1066
|
+
function addBreadcrumb(crumb) {
|
|
1067
|
+
safely(() => {
|
|
1068
|
+
if (client) client.addBreadcrumb(crumb);
|
|
1069
|
+
else pendingScope.addBreadcrumb(crumb, 50);
|
|
1070
|
+
}, void 0);
|
|
1071
|
+
}
|
|
1072
|
+
async function flush(timeoutMs) {
|
|
1073
|
+
return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
|
|
1074
|
+
}
|
|
1075
|
+
function close() {
|
|
1076
|
+
safely(() => {
|
|
1077
|
+
client?.close();
|
|
1078
|
+
client = void 0;
|
|
1079
|
+
pendingScope = new Scope();
|
|
1080
|
+
}, void 0);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser };
|