@inkronik/browser-sdk 2.0.0 → 2.1.1

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.
@@ -0,0 +1,881 @@
1
+ // src/constants.ts
2
+ var DEFAULT_BATCH_SIZE = 20;
3
+ var DEFAULT_MAX_QUEUE_SIZE = 200;
4
+ var DEFAULT_FLUSH_INTERVAL_MS = 5000;
5
+ var DEFAULT_MAX_RETRIES = 2;
6
+ var DEFAULT_RETRY_BASE_MS = 250;
7
+ var BROWSER_TELEMETRY_MAX_AGE_MS = 24 * 60 * 60 * 1000;
8
+ var DEFAULT_SAMPLE_RATE = 1;
9
+ var SDK_NAME = "@inkronik/browser-sdk";
10
+ var SDK_VERSION = "2.1.1";
11
+ var DEFAULT_SESSION_INACTIVITY_MS = 30 * 60 * 1000;
12
+ var DEFAULT_SESSION_MAX_DURATION_MS = 30 * 60 * 1000;
13
+ var BROWSER_SESSION_STORAGE_KEY = "inkronik.browser.session";
14
+ var REDACTED_VALUE = "[REDACTED]";
15
+ var MAX_ATTRIBUTES = 32;
16
+ var MAX_ATTRIBUTE_KEY_LENGTH = 64;
17
+ var MAX_ATTRIBUTE_VALUE_LENGTH = 512;
18
+ var MAX_EVENT_MESSAGE_LENGTH = 1024;
19
+ var MAX_ERROR_VALUE_LENGTH = 4096;
20
+ var INKRONIK_ORIGINAL_BROWSER_FETCH = Symbol.for("inkronik.browser.originalFetch");
21
+ var SENSITIVE_KEY_FRAGMENTS = [
22
+ "password",
23
+ "passwd",
24
+ "secret",
25
+ "token",
26
+ "authorization",
27
+ "cookie",
28
+ "api_key",
29
+ "apikey",
30
+ "credential",
31
+ "session",
32
+ "card",
33
+ "cvv",
34
+ "cvc",
35
+ "email",
36
+ "phone",
37
+ "ssn",
38
+ "input",
39
+ "value"
40
+ ];
41
+ var EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
42
+ var PHONE_PATTERN = /\b(?:\+?\d[\d .()-]{7,}\d)\b/g;
43
+ var CARD_PATTERN = /\b(?:\d[ -]*?){13,19}\b/g;
44
+ var TOKEN_PATTERN = /\b(?:Bearer\s+)?(?:ik_(?:live|pub)_[A-Za-z0-9_-]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b/g;
45
+ var ROUTE_UUID_SEGMENT_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
46
+ var ROUTE_ULID_SEGMENT_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/iu;
47
+ var ROUTE_OBJECT_ID_SEGMENT_PATTERN = /^[0-9a-f]{24}$/iu;
48
+ var ROUTE_NUMERIC_SEGMENT_PATTERN = /^\d+$/u;
49
+
50
+ // src/sanitizer.ts
51
+ var normalizeKey = (value) => value.toLowerCase().replaceAll(/[^a-z0-9]+/g, "_");
52
+ var freeformSecretPattern = /((?:password|passwd|passphrase|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|refresh[_-]?token|id[_-]?token|jwt|credential|signature|session|cookie|card[_-]?number|credit[_-]?card|cvv|cvc|ssn)\s*[:=]\s*)([^&\s,"'}]+)/gi;
53
+ var isSensitiveBrowserKey = (key) => {
54
+ const normalized = normalizeKey(key);
55
+ return SENSITIVE_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));
56
+ };
57
+ var redactBrowserValue = (value) => value.replaceAll(TOKEN_PATTERN, REDACTED_VALUE).replaceAll(EMAIL_PATTERN, REDACTED_VALUE).replaceAll(PHONE_PATTERN, REDACTED_VALUE).replaceAll(CARD_PATTERN, REDACTED_VALUE);
58
+ var redactBrowserErrorValue = (value) => redactBrowserValue(value).replaceAll(freeformSecretPattern, `$1${REDACTED_VALUE}`);
59
+ var sanitizeValue = ({ key, value }) => {
60
+ const isFreeformErrorValue = key === "message" || key === "stack" || key === "reason";
61
+ if (isSensitiveBrowserKey(key) || isFreeformErrorValue) {
62
+ return REDACTED_VALUE;
63
+ }
64
+ if (typeof value !== "string") {
65
+ return value;
66
+ }
67
+ const isUrlValue = key === "file" || key === "url" || key.endsWith("_url");
68
+ if (isUrlValue) {
69
+ try {
70
+ return sanitizeBrowserUrl2(value).slice(0, MAX_ATTRIBUTE_VALUE_LENGTH);
71
+ } catch {
72
+ return REDACTED_VALUE;
73
+ }
74
+ }
75
+ return redactBrowserValue(value.slice(0, MAX_ATTRIBUTE_VALUE_LENGTH));
76
+ };
77
+ var sanitizeBrowserAttributes2 = (attributes) => Object.fromEntries(Object.entries(attributes).slice(0, MAX_ATTRIBUTES).filter(([key]) => key.length <= MAX_ATTRIBUTE_KEY_LENGTH).map(([key, value]) => [key, sanitizeValue({ key, value })]));
78
+ var sanitizeBrowserUrl2 = (value) => {
79
+ const parsed = new URL(value);
80
+ const isSupportedProtocol = parsed.protocol === "http:" || parsed.protocol === "https:";
81
+ if (!isSupportedProtocol) {
82
+ return "";
83
+ }
84
+ return `${parsed.origin}${sanitizeBrowserRoute(parsed.pathname)}`;
85
+ };
86
+ var createPrivacyPreservingUrlSanitizer = (customSanitizer) => (url) => {
87
+ try {
88
+ const baselineUrl = sanitizeBrowserUrl2(url.toString());
89
+ if (customSanitizer === undefined) {
90
+ return baselineUrl;
91
+ }
92
+ return sanitizeBrowserUrl2(customSanitizer(new URL(baselineUrl)));
93
+ } catch {
94
+ return "";
95
+ }
96
+ };
97
+ var isIdentifierRouteSegment = (segment) => ROUTE_UUID_SEGMENT_PATTERN.test(segment) || ROUTE_ULID_SEGMENT_PATTERN.test(segment) || ROUTE_OBJECT_ID_SEGMENT_PATTERN.test(segment) || ROUTE_NUMERIC_SEGMENT_PATTERN.test(segment);
98
+ var sanitizeBrowserRoute = (value) => {
99
+ const path = value.split(/[?#]/u).at(0)?.slice(0, 500) ?? "";
100
+ return path.split("/").map((segment) => isIdentifierRouteSegment(segment) ? ":id" : segment).join("/");
101
+ };
102
+
103
+ // src/browser-instrumentation.ts
104
+ var safeUrl = (value) => {
105
+ try {
106
+ return sanitizeBrowserUrl2(value);
107
+ } catch {
108
+ return "";
109
+ }
110
+ };
111
+ var installNavigationInstrumentation = (input) => {
112
+ if (!input.enableNavigationTracking) {
113
+ return () => {
114
+ return;
115
+ };
116
+ }
117
+ const originalPushState = input.environment.history.pushState;
118
+ const originalReplaceState = input.environment.history.replaceState;
119
+ const captureNavigation = () => input.beginView("navigation");
120
+ const onPopState = () => captureNavigation();
121
+ input.environment.history.pushState = (...arguments_) => {
122
+ const previousUrl = input.environment.location.href;
123
+ originalPushState.apply(input.environment.history, arguments_);
124
+ if (input.environment.location.href !== previousUrl) {
125
+ captureNavigation();
126
+ }
127
+ };
128
+ input.environment.history.replaceState = (...arguments_) => {
129
+ const previousUrl = input.environment.location.href;
130
+ originalReplaceState.apply(input.environment.history, arguments_);
131
+ if (input.environment.location.href !== previousUrl) {
132
+ captureNavigation();
133
+ }
134
+ };
135
+ input.environment.window.addEventListener("popstate", onPopState);
136
+ return () => {
137
+ input.environment.history.pushState = originalPushState;
138
+ input.environment.history.replaceState = originalReplaceState;
139
+ input.environment.window.removeEventListener("popstate", onPopState);
140
+ };
141
+ };
142
+ var installFetchInstrumentation = (input) => {
143
+ if (!input.enableFetchTracing) {
144
+ return () => {
145
+ return;
146
+ };
147
+ }
148
+ const currentFetch = input.environment.window.fetch;
149
+ if (Reflect.get(currentFetch, INKRONIK_ORIGINAL_BROWSER_FETCH) !== undefined) {
150
+ return () => {
151
+ return;
152
+ };
153
+ }
154
+ Reflect.defineProperty(input.traceFetch, INKRONIK_ORIGINAL_BROWSER_FETCH, { value: currentFetch });
155
+ input.environment.window.fetch = input.traceFetch;
156
+ return () => {
157
+ if (input.environment.window.fetch === input.traceFetch) {
158
+ input.environment.window.fetch = currentFetch;
159
+ }
160
+ };
161
+ };
162
+ var installErrorInstrumentation = (input) => {
163
+ const onError = (event) => {
164
+ input.capture({
165
+ eventType: "javascript_error",
166
+ name: event.error instanceof Error ? event.error.name : "Error",
167
+ attributes: {
168
+ message: event.message,
169
+ stack: event.error instanceof Error ? event.error.stack ?? "" : "",
170
+ file: safeUrl(event.filename),
171
+ line: event.lineno,
172
+ column: event.colno
173
+ }
174
+ });
175
+ };
176
+ const onUnhandledRejection = (event) => {
177
+ const reason = event.reason;
178
+ const isError = reason instanceof Error;
179
+ input.capture({
180
+ eventType: "unhandled_rejection",
181
+ name: isError ? reason.name : "UnhandledRejection",
182
+ attributes: {
183
+ reason: isError ? reason.message : typeof reason === "string" ? reason : "[non-error rejection]",
184
+ stack: isError ? reason.stack ?? "" : ""
185
+ }
186
+ });
187
+ };
188
+ input.environment.window.addEventListener("error", onError);
189
+ input.environment.window.addEventListener("unhandledrejection", onUnhandledRejection);
190
+ return () => {
191
+ input.environment.window.removeEventListener("error", onError);
192
+ input.environment.window.removeEventListener("unhandledrejection", onUnhandledRejection);
193
+ };
194
+ };
195
+ var observe = ({
196
+ capture,
197
+ entryTypes
198
+ }) => {
199
+ if (typeof PerformanceObserver === "undefined") {
200
+ return () => {
201
+ return;
202
+ };
203
+ }
204
+ const observer = new PerformanceObserver((list) => list.getEntries().forEach(capture));
205
+ entryTypes.forEach((type) => {
206
+ try {
207
+ observer.observe({ type, buffered: true });
208
+ } catch {}
209
+ });
210
+ return () => observer.disconnect();
211
+ };
212
+ var installWebVitalsInstrumentation = (input) => {
213
+ const cleanupObservers = [
214
+ observe({
215
+ entryTypes: ["largest-contentful-paint"],
216
+ capture: (entry) => input.capture({ eventType: "web_vital", name: "LCP", measurements: { value: entry.startTime }, attributes: { unit: "ms" } })
217
+ }),
218
+ observe({
219
+ entryTypes: ["layout-shift"],
220
+ capture: (entry) => {
221
+ const layoutShift = entry;
222
+ if (!layoutShift.hadRecentInput) {
223
+ input.capture({ eventType: "web_vital", name: "CLS", measurements: { value: layoutShift.value }, attributes: { unit: "score" } });
224
+ }
225
+ }
226
+ }),
227
+ observe({
228
+ entryTypes: ["event"],
229
+ capture: (entry) => {
230
+ const interaction = entry;
231
+ if (interaction.interactionId > 0) {
232
+ input.capture({ eventType: "web_vital", name: "INP", measurements: { value: interaction.duration }, attributes: { unit: "ms" } });
233
+ }
234
+ }
235
+ }),
236
+ observe({
237
+ entryTypes: ["paint"],
238
+ capture: (entry) => {
239
+ if (entry.name === "first-contentful-paint") {
240
+ input.capture({ eventType: "web_vital", name: "FCP", measurements: { value: entry.startTime }, attributes: { unit: "ms" } });
241
+ }
242
+ }
243
+ })
244
+ ];
245
+ const navigation = input.environment.performance.getEntriesByType("navigation").at(0);
246
+ if (navigation !== undefined) {
247
+ input.capture({
248
+ eventType: "web_vital",
249
+ name: "TTFB",
250
+ measurements: { value: Math.max(0, navigation.responseStart - navigation.requestStart) },
251
+ attributes: { unit: "ms" }
252
+ });
253
+ }
254
+ return () => cleanupObservers.forEach((cleanup) => cleanup());
255
+ };
256
+ var installBrowserInstrumentation = (input) => {
257
+ const cleanups = [
258
+ installNavigationInstrumentation(input),
259
+ installFetchInstrumentation(input),
260
+ installErrorInstrumentation(input),
261
+ installWebVitalsInstrumentation(input)
262
+ ];
263
+ return () => cleanups.forEach((cleanup) => cleanup());
264
+ };
265
+
266
+ // src/utils.ts
267
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
268
+ var safeString = (value) => {
269
+ try {
270
+ return String(value);
271
+ } catch {
272
+ return "[unserializable thrown value]";
273
+ }
274
+ };
275
+ var errorProperty = ({ error, property }) => {
276
+ if (!isRecord(error)) {
277
+ return "";
278
+ }
279
+ const value = (() => {
280
+ try {
281
+ return Reflect.get(error, property);
282
+ } catch {
283
+ return;
284
+ }
285
+ })();
286
+ return typeof value === "string" || typeof value === "number" ? safeString(value) : "";
287
+ };
288
+ var normalizeCapturedBrowserError = (error) => {
289
+ const capturedType = errorProperty({ error, property: "name" });
290
+ const capturedMessage = errorProperty({ error, property: "message" });
291
+ const errorType = capturedType === "" ? error instanceof Error ? "Error" : "NonError" : capturedType;
292
+ const errorMessage = capturedMessage === "" ? safeString(error) : capturedMessage;
293
+ const errorStack = errorProperty({ error, property: "stack" });
294
+ return {
295
+ type: redactBrowserValue(errorType.slice(0, 255)),
296
+ message: redactBrowserErrorValue(errorMessage.slice(0, MAX_ERROR_VALUE_LENGTH)),
297
+ stack: redactBrowserErrorValue(errorStack.slice(0, MAX_ERROR_VALUE_LENGTH)),
298
+ code: redactBrowserValue(errorProperty({ error, property: "code" }).slice(0, 255)),
299
+ handled: true
300
+ };
301
+ };
302
+ var createUuid = () => crypto.randomUUID();
303
+ var getBrowserTelemetryCutoff = () => Date.now() - BROWSER_TELEMETRY_MAX_AGE_MS;
304
+ var trimTrailingSlashes = (value) => {
305
+ let endIndex = value.length;
306
+ while (endIndex > 0 && value.at(endIndex - 1) === "/") {
307
+ endIndex -= 1;
308
+ }
309
+ return value.slice(0, endIndex);
310
+ };
311
+ var normalizeCollectorUrl = trimTrailingSlashes;
312
+ var ENVIRONMENT_MAX_LENGTH = 63;
313
+ var ENVIRONMENT_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
314
+ var normalizeTelemetryEnvironment = (value) => {
315
+ const environment = value.trim().toLowerCase();
316
+ if (environment.length === 0 || environment.length > ENVIRONMENT_MAX_LENGTH || !ENVIRONMENT_PATTERN.test(environment)) {
317
+ throw new TypeError("Inkronik environment must be a canonical slug containing only lowercase letters, numbers, dots, underscores, or dashes");
318
+ }
319
+ return environment;
320
+ };
321
+ var resolveTracePropagationOrigins = ({ environment, configuredOrigins }) => new Set([...environment === null ? [] : [environment.location.origin], ...(configuredOrigins ?? []).map((origin) => new URL(origin).origin)]);
322
+ var shouldTraceBrowserRequest = ({ collectorUrl, requestUrl, tracePropagationOrigins }) => {
323
+ const collector = new URL(collectorUrl);
324
+ const collectorPath = trimTrailingSlashes(collector.pathname);
325
+ const isCollectorRequest = requestUrl.origin === collector.origin && requestUrl.pathname.startsWith(`${collectorPath}/v1/browser`);
326
+ return !isCollectorRequest && tracePropagationOrigins.has(requestUrl.origin);
327
+ };
328
+ var resolveBrowserEnvironment = () => {
329
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof navigator === "undefined") {
330
+ return null;
331
+ }
332
+ return { window, document, navigator, history: window.history, location: window.location, performance: window.performance };
333
+ };
334
+ var resolveBrowserFetch = ({ configuredFetch, environment }) => {
335
+ if (configuredFetch !== undefined) {
336
+ return configuredFetch.bind(environment?.window ?? globalThis);
337
+ }
338
+ if (environment !== null) {
339
+ return environment.window.fetch.bind(environment.window);
340
+ }
341
+ return globalThis.fetch.bind(globalThis);
342
+ };
343
+ var normalizeBrowserUserContext = (input) => ({
344
+ id: redactBrowserValue(input.id.slice(0, 255)),
345
+ attributes: sanitizeBrowserAttributes2(Object.fromEntries(Object.entries(input.attributes ?? {}).map(([key, value]) => [`user.${key}`, value])))
346
+ });
347
+ var deterministicSample = ({ sampleRate, sessionId }) => {
348
+ const normalizedRate = Math.min(1, Math.max(0, sampleRate));
349
+ const hash = Array.from(sessionId).reduce((value, character) => (value * 31 + character.charCodeAt(0)) % 4294967296, 2166136261);
350
+ return hash / 4294967295 <= normalizedRate;
351
+ };
352
+ var buildBrowserEvent = ({
353
+ attributes,
354
+ defaultAttributes,
355
+ eventType,
356
+ error,
357
+ level,
358
+ message,
359
+ measurements,
360
+ name,
361
+ pageUrl,
362
+ route,
363
+ sessionId,
364
+ userId,
365
+ viewId,
366
+ traceId,
367
+ spanId
368
+ }) => ({
369
+ event_id: createUuid(),
370
+ event_type: eventType,
371
+ name: name.slice(0, 100),
372
+ level: level ?? (eventType === "javascript_error" || eventType === "unhandled_rejection" ? "error" : "info"),
373
+ message: redactBrowserErrorValue((message ?? "").slice(0, MAX_EVENT_MESSAGE_LENGTH)),
374
+ timestamp: new Date().toISOString(),
375
+ session_id: sessionId,
376
+ view_id: viewId,
377
+ page_url: pageUrl,
378
+ route: sanitizeBrowserRoute(route),
379
+ user_id: redactBrowserValue(userId.slice(0, 255)),
380
+ trace_id: traceId,
381
+ span_id: spanId,
382
+ error_type: error?.type ?? "",
383
+ error_message: error?.message ?? "",
384
+ error_stack: error?.stack ?? "",
385
+ error_code: error?.code ?? "",
386
+ error_handled: error?.handled ?? false,
387
+ attributes: sanitizeBrowserAttributes2({ ...defaultAttributes, ...attributes }),
388
+ measurements: Object.fromEntries(Object.entries(measurements ?? {}).filter(([, value]) => Number.isFinite(value)).slice(0, 16))
389
+ });
390
+ var buildBrowserSpan = ({
391
+ attributes,
392
+ context,
393
+ durationUs,
394
+ endTime,
395
+ httpMethod,
396
+ httpStatusCode,
397
+ httpUrl,
398
+ name,
399
+ pageUrl,
400
+ route,
401
+ sessionId,
402
+ spanCategory,
403
+ spanKind,
404
+ statusCode,
405
+ statusMessage,
406
+ timestamp,
407
+ userId,
408
+ viewId
409
+ }) => ({
410
+ trace_id: context.traceId,
411
+ span_id: context.spanId,
412
+ parent_span_id: context.parentSpanId,
413
+ name: redactBrowserValue(name.slice(0, 100)),
414
+ timestamp,
415
+ end_time: endTime,
416
+ duration_us: Math.max(0, Math.round(durationUs)),
417
+ span_kind: spanKind,
418
+ span_category: spanCategory,
419
+ status_code: statusCode,
420
+ status_message: statusMessage === undefined ? "" : redactBrowserValue(statusMessage.slice(0, 512)),
421
+ session_id: sessionId,
422
+ view_id: viewId,
423
+ page_url: pageUrl,
424
+ route: sanitizeBrowserRoute(route),
425
+ user_id: redactBrowserValue(userId.slice(0, 255)),
426
+ http_method: httpMethod?.slice(0, 16) ?? "",
427
+ http_url: httpUrl === undefined ? "" : sanitizeBrowserUrl2(httpUrl),
428
+ http_status_code: httpStatusCode ?? 0,
429
+ attributes: sanitizeBrowserAttributes2(attributes ?? {})
430
+ });
431
+
432
+ // src/session.ts
433
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
434
+ var readSession = (storage) => {
435
+ if (storage === null) {
436
+ return null;
437
+ }
438
+ try {
439
+ const value = storage.getItem(BROWSER_SESSION_STORAGE_KEY);
440
+ if (value === null) {
441
+ return null;
442
+ }
443
+ const parsed = JSON.parse(value);
444
+ const isValid = typeof parsed.id === "string" && UUID_PATTERN.test(parsed.id) && typeof parsed.startedAt === "number" && Number.isFinite(parsed.startedAt) && typeof parsed.lastActivityAt === "number" && Number.isFinite(parsed.lastActivityAt);
445
+ return isValid ? parsed : null;
446
+ } catch {
447
+ return null;
448
+ }
449
+ };
450
+ var writeSession = ({ record, storage }) => {
451
+ if (storage === null) {
452
+ return;
453
+ }
454
+ try {
455
+ storage.setItem(BROWSER_SESSION_STORAGE_KEY, JSON.stringify(record));
456
+ } catch {}
457
+ };
458
+ var canReuseSession = ({ inactivityMs, maxDurationMs, now, record }) => now >= record.lastActivityAt && now - record.lastActivityAt <= inactivityMs && now - record.startedAt <= maxDurationMs;
459
+ var resolveBrowserStorage = (environmentWindow) => {
460
+ if (environmentWindow === null) {
461
+ return null;
462
+ }
463
+ try {
464
+ return environmentWindow.localStorage;
465
+ } catch {
466
+ return null;
467
+ }
468
+ };
469
+ var resolveBrowserSession = ({
470
+ storage,
471
+ now = Date.now(),
472
+ inactivityMs = DEFAULT_SESSION_INACTIVITY_MS,
473
+ maxDurationMs = DEFAULT_SESSION_MAX_DURATION_MS
474
+ }) => {
475
+ const existing = readSession(storage);
476
+ const initialRecord = existing !== null && canReuseSession({ record: existing, now, inactivityMs, maxDurationMs }) ? existing : { id: createUuid(), startedAt: now, lastActivityAt: now };
477
+ const state = { record: initialRecord };
478
+ const persistActivity = () => {
479
+ const activityAt = Date.now();
480
+ const nextRecord = canReuseSession({ record: state.record, now: activityAt, inactivityMs, maxDurationMs }) ? { ...state.record, lastActivityAt: activityAt } : { id: createUuid(), startedAt: activityAt, lastActivityAt: activityAt };
481
+ state.record = nextRecord;
482
+ writeSession({ record: nextRecord, storage });
483
+ return nextRecord.id;
484
+ };
485
+ writeSession({ record: initialRecord, storage });
486
+ return { currentId: () => state.record.id, touch: persistActivity };
487
+ };
488
+
489
+ // src/trace-context.ts
490
+ var createHexIdentifier = (byteLength) => {
491
+ const value = Array.from(crypto.getRandomValues(new Uint8Array(byteLength)), (byte) => byte.toString(16).padStart(2, "0")).join("");
492
+ return /^0+$/u.test(value) ? createHexIdentifier(byteLength) : value;
493
+ };
494
+ var createRootBrowserTraceContext = () => ({
495
+ traceId: createHexIdentifier(16),
496
+ spanId: createHexIdentifier(8),
497
+ parentSpanId: ""
498
+ });
499
+ var toBrowserTraceparent = (context) => `00-${context.traceId}-${context.spanId}-01`;
500
+
501
+ // src/transport.ts
502
+ class BrowserBatchRejectedError extends Error {
503
+ }
504
+ var delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
505
+ var postBatch = async (input) => {
506
+ const cutoff = getBrowserTelemetryCutoff();
507
+ const events = input.events.filter((event) => Date.parse(event.timestamp) >= cutoff);
508
+ const spans = input.spans.filter((span) => Date.parse(span.timestamp) >= cutoff);
509
+ if (events.length === 0 && spans.length === 0) {
510
+ return { delivered: false, rejected: true };
511
+ }
512
+ const body = JSON.stringify({ public_key: input.publicKey, environment: input.environment, events, spans });
513
+ if (input.useBeacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
514
+ const delivered = navigator.sendBeacon(`${input.collectorUrl}/v1/browser`, new Blob([body], { type: "text/plain;charset=UTF-8" }));
515
+ return { delivered };
516
+ }
517
+ const response = await input.fetchImpl(`${input.collectorUrl}/v1/browser`, {
518
+ method: "POST",
519
+ headers: { "Content-Type": "application/json" },
520
+ body,
521
+ keepalive: true,
522
+ credentials: "omit"
523
+ });
524
+ if (!response.ok) {
525
+ const message = `Inkronik browser ingest failed with status ${response.status}`;
526
+ throw response.status === 400 ? new BrowserBatchRejectedError(message) : new Error(message);
527
+ }
528
+ return { delivered: true };
529
+ };
530
+ var sendBrowserBatch = async (input) => {
531
+ const attempts = Array.from({ length: input.useBeacon ? 1 : input.maxRetries + 1 }, (_, index) => index);
532
+ return attempts.reduce(async (previous, attempt) => {
533
+ const previousResult = await previous;
534
+ if (previousResult.delivered || previousResult.rejected === true) {
535
+ return previousResult;
536
+ }
537
+ if (attempt > 0) {
538
+ const jitter = Math.floor(Math.random() * DEFAULT_RETRY_BASE_MS);
539
+ await delay(DEFAULT_RETRY_BASE_MS * 2 ** (attempt - 1) + jitter);
540
+ }
541
+ return postBatch(input).catch((error) => {
542
+ const rejected = error instanceof BrowserBatchRejectedError;
543
+ if (rejected || attempt === attempts.length - 1) {
544
+ input.onError(error instanceof Error ? error : new Error(String(error)));
545
+ }
546
+ return rejected ? { delivered: false, rejected: true } : { delivered: false };
547
+ });
548
+ }, Promise.resolve({ delivered: false }));
549
+ };
550
+
551
+ // src/client.ts
552
+ var getBrowserAttributes = (userAgent) => {
553
+ const browserMatch = userAgent.match(/(?:Edg|Chrome|Firefox|Version)\/([\d.]+)/u);
554
+ const browserName = userAgent.includes("Edg/") ? "Edge" : userAgent.includes("Chrome/") ? "Chrome" : userAgent.includes("Firefox/") ? "Firefox" : userAgent.includes("Safari/") ? "Safari" : "Other";
555
+ const osName = userAgent.includes("Windows") ? "Windows" : userAgent.includes("Android") ? "Android" : userAgent.includes("iPhone") || userAgent.includes("iPad") ? "iOS" : userAgent.includes("Mac OS") ? "macOS" : userAgent.includes("Linux") ? "Linux" : "Other";
556
+ return {
557
+ browser_name: browserName,
558
+ browser_version: browserMatch?.at(1) ?? "",
559
+ os_name: osName,
560
+ device_type: /Mobi|Android|iPhone|iPad/u.test(userAgent) ? "mobile" : "desktop",
561
+ sdk_name: SDK_NAME,
562
+ sdk_version: SDK_VERSION
563
+ };
564
+ };
565
+ var removeExpiredItems = (items) => {
566
+ const cutoff = getBrowserTelemetryCutoff();
567
+ return items.filter((item) => Date.parse(item.itemType === "event" ? item.event.timestamp : item.span.timestamp) >= cutoff);
568
+ };
569
+
570
+ class InkronikBrowserClient2 {
571
+ publicKey;
572
+ collectorUrl;
573
+ telemetryEnvironment;
574
+ sampleRate;
575
+ defaultAttributes;
576
+ maxBatchSize;
577
+ maxQueueSize;
578
+ maxRetries;
579
+ fetchImpl;
580
+ onError;
581
+ getRoute;
582
+ sanitizeUrl;
583
+ enableFetchTracing;
584
+ enableNavigationTracking;
585
+ tracePropagationOrigins;
586
+ environment = resolveBrowserEnvironment();
587
+ session = resolveBrowserSession({ storage: resolveBrowserStorage(this.environment?.window ?? null) });
588
+ flushTimer;
589
+ cleanupInstrumentation;
590
+ cleanupLifecycle;
591
+ sampled;
592
+ queue = [];
593
+ flushing = null;
594
+ viewContext;
595
+ userId = "";
596
+ userAttributes = {};
597
+ closed = false;
598
+ constructor(options) {
599
+ this.publicKey = options.publicKey;
600
+ this.collectorUrl = normalizeCollectorUrl(options.collectorUrl);
601
+ this.telemetryEnvironment = normalizeTelemetryEnvironment(options.environment);
602
+ this.sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
603
+ this.defaultAttributes = {
604
+ ...this.environment === null ? {} : getBrowserAttributes(this.environment.navigator.userAgent),
605
+ ...options.defaultAttributes
606
+ };
607
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? DEFAULT_BATCH_SIZE);
608
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE);
609
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
610
+ this.fetchImpl = resolveBrowserFetch({ configuredFetch: options.fetchImpl, environment: this.environment });
611
+ this.onError = options.onError ?? (() => {
612
+ return;
613
+ });
614
+ this.getRoute = options.getRoute ?? (() => this.environment?.location.pathname ?? "");
615
+ this.sanitizeUrl = createPrivacyPreservingUrlSanitizer(options.sanitizeUrl);
616
+ this.enableFetchTracing = options.enableFetchTracing ?? true;
617
+ this.enableNavigationTracking = options.enableNavigationTracking ?? true;
618
+ this.tracePropagationOrigins = resolveTracePropagationOrigins({
619
+ environment: this.environment,
620
+ configuredOrigins: options.tracePropagationOrigins
621
+ });
622
+ this.sampled = deterministicSample({ sampleRate: this.sampleRate, sessionId: this.session.currentId() });
623
+ this.viewContext = { ...createRootBrowserTraceContext(), viewId: createUuid() };
624
+ if (options.user !== undefined) {
625
+ this.setUser(options.user);
626
+ }
627
+ this.flushTimer = this.environment === null ? null : setInterval(() => void this.flush(), options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS);
628
+ this.cleanupInstrumentation = this.installInstrumentation();
629
+ this.cleanupLifecycle = this.installLifecycle();
630
+ this.startView({ eventType: "page_view", name: "page_view" });
631
+ }
632
+ capture(input) {
633
+ this.enqueue({
634
+ eventType: "custom",
635
+ name: input.name,
636
+ level: input.level,
637
+ message: input.message,
638
+ attributes: input.attributes,
639
+ measurements: input.measurements
640
+ });
641
+ }
642
+ captureError(error, options) {
643
+ this.enqueue({
644
+ eventType: "custom",
645
+ name: options.name,
646
+ level: "error",
647
+ message: options.message,
648
+ error: normalizeCapturedBrowserError(error),
649
+ attributes: options.attributes,
650
+ measurements: options.measurements
651
+ });
652
+ }
653
+ setUser(input) {
654
+ const context = normalizeBrowserUserContext(input);
655
+ this.userId = context.id;
656
+ this.userAttributes = context.attributes;
657
+ }
658
+ clearUser() {
659
+ this.userId = "";
660
+ this.userAttributes = {};
661
+ }
662
+ captureNavigation(input) {
663
+ this.startView({ eventType: "navigation", name: input.navigationType, url: input.url });
664
+ }
665
+ flush() {
666
+ return this.flushBatch(false);
667
+ }
668
+ async shutdown() {
669
+ if (this.closed) {
670
+ return;
671
+ }
672
+ this.closed = true;
673
+ if (this.flushTimer !== null) {
674
+ clearInterval(this.flushTimer);
675
+ }
676
+ this.cleanupInstrumentation();
677
+ this.cleanupLifecycle();
678
+ await this.flushBatch(true);
679
+ }
680
+ beginView(name) {
681
+ this.startView({ eventType: "navigation", name });
682
+ }
683
+ startView(input) {
684
+ this.viewContext = { ...createRootBrowserTraceContext(), viewId: createUuid() };
685
+ if (this.environment === null) {
686
+ return;
687
+ }
688
+ const timestamp = new Date().toISOString();
689
+ const sessionId = this.session.touch();
690
+ const viewUrl = new URL(input.url ?? this.environment.location.href, this.environment.location.href);
691
+ const pageUrl = this.sanitizeUrl(viewUrl);
692
+ const route = sanitizeBrowserRoute(input.url === undefined ? this.getRoute() : viewUrl.pathname);
693
+ const attributes = { ...this.defaultAttributes, ...this.userAttributes };
694
+ this.enqueueSpan(buildBrowserSpan({
695
+ context: this.viewContext,
696
+ name: `${input.eventType} ${route}`,
697
+ timestamp,
698
+ endTime: timestamp,
699
+ durationUs: 0,
700
+ spanKind: "internal",
701
+ spanCategory: "navigation",
702
+ statusCode: "ok",
703
+ sessionId,
704
+ viewId: this.viewContext.viewId,
705
+ pageUrl,
706
+ route,
707
+ userId: this.userId,
708
+ attributes
709
+ }));
710
+ this.enqueue({ eventType: input.eventType, name: input.name, context: { pageUrl, route } });
711
+ }
712
+ enqueue(input) {
713
+ if (!this.sampled || this.closed || this.environment === null) {
714
+ return;
715
+ }
716
+ const sessionId = this.session.touch();
717
+ const { context, ...eventInput } = input;
718
+ const pageUrl = context?.pageUrl ?? this.sanitizeUrl(new URL(this.environment.location.href));
719
+ const event = buildBrowserEvent({
720
+ ...eventInput,
721
+ defaultAttributes: { ...this.defaultAttributes, ...this.userAttributes },
722
+ pageUrl,
723
+ route: context?.route ?? this.getRoute(),
724
+ sessionId,
725
+ userId: this.userId,
726
+ viewId: this.viewContext.viewId,
727
+ traceId: this.viewContext.traceId,
728
+ spanId: this.viewContext.spanId
729
+ });
730
+ this.enqueueItem({ itemType: "event", event });
731
+ }
732
+ enqueueSpan(span) {
733
+ this.enqueueItem({ itemType: "span", span });
734
+ }
735
+ enqueueItem(item) {
736
+ if (!this.sampled || this.closed || this.environment === null) {
737
+ return;
738
+ }
739
+ this.queue = [...this.queue.slice(-(this.maxQueueSize - 1)), item];
740
+ if (this.queue.length >= this.maxBatchSize) {
741
+ this.flush();
742
+ }
743
+ }
744
+ flushBatch(useBeacon) {
745
+ if (this.flushing !== null) {
746
+ return this.flushing;
747
+ }
748
+ const queue = removeExpiredItems(this.queue);
749
+ const batch = queue.slice(0, this.maxBatchSize);
750
+ this.queue = queue.slice(batch.length);
751
+ if (batch.length === 0) {
752
+ return Promise.resolve();
753
+ }
754
+ const transportBatch = {
755
+ events: batch.flatMap((item) => item.itemType === "event" ? [item.event] : []),
756
+ spans: batch.flatMap((item) => item.itemType === "span" ? [item.span] : [])
757
+ };
758
+ const operation = sendBrowserBatch({
759
+ collectorUrl: this.collectorUrl,
760
+ publicKey: this.publicKey,
761
+ environment: this.telemetryEnvironment,
762
+ ...transportBatch,
763
+ useBeacon,
764
+ fetchImpl: this.fetchImpl,
765
+ maxRetries: this.maxRetries,
766
+ onError: this.onError
767
+ }).then((result) => {
768
+ if (!result.delivered && result.rejected !== true) {
769
+ this.queue = removeExpiredItems([...batch, ...this.queue]).slice(0, this.maxQueueSize);
770
+ }
771
+ }).finally(() => {
772
+ this.flushing = null;
773
+ });
774
+ this.flushing = operation;
775
+ return operation;
776
+ }
777
+ installInstrumentation() {
778
+ if (this.environment === null) {
779
+ return () => {
780
+ return;
781
+ };
782
+ }
783
+ return installBrowserInstrumentation({
784
+ environment: this.environment,
785
+ capture: (input) => this.enqueue(input),
786
+ beginView: (name) => this.beginView(name),
787
+ traceFetch: this.traceFetch,
788
+ enableFetchTracing: this.enableFetchTracing,
789
+ enableNavigationTracking: this.enableNavigationTracking
790
+ });
791
+ }
792
+ traceFetch = async (input, init) => {
793
+ if (this.environment === null || !this.sampled || this.closed) {
794
+ return this.fetchImpl(input, init);
795
+ }
796
+ const request = new Request(input, init);
797
+ const requestUrl = new URL(request.url, this.environment.location.href);
798
+ if (!shouldTraceBrowserRequest({
799
+ collectorUrl: this.collectorUrl,
800
+ requestUrl,
801
+ tracePropagationOrigins: this.tracePropagationOrigins
802
+ })) {
803
+ return this.fetchImpl(input, init);
804
+ }
805
+ const context = createRootBrowserTraceContext();
806
+ const sessionId = this.session.touch();
807
+ const headers = new Headers(request.headers);
808
+ headers.set("traceparent", toBrowserTraceparent(context));
809
+ const tracedRequest = new Request(request, { headers });
810
+ const completionInput = {
811
+ context,
812
+ viewContext: this.viewContext,
813
+ request: tracedRequest,
814
+ startedAt: this.environment.performance.now(),
815
+ timestamp: new Date().toISOString(),
816
+ pageUrl: this.sanitizeUrl(new URL(this.environment.location.href)),
817
+ route: this.getRoute(),
818
+ userId: this.userId,
819
+ sessionId,
820
+ attributes: { ...this.defaultAttributes, ...this.userAttributes }
821
+ };
822
+ return this.fetchImpl(tracedRequest).then((response) => {
823
+ this.completeFetchSpan({ ...completionInput, response });
824
+ return response;
825
+ }, (error) => {
826
+ this.completeFetchSpan({ ...completionInput, error });
827
+ throw error;
828
+ });
829
+ };
830
+ completeFetchSpan(input) {
831
+ const requestUrl = new URL(input.request.url);
832
+ const statusCode = input.response?.status ?? 0;
833
+ const hasError = input.error !== undefined || statusCode >= 500;
834
+ this.enqueueSpan(buildBrowserSpan({
835
+ context: input.context,
836
+ name: `${input.request.method} ${requestUrl.pathname}`,
837
+ timestamp: input.timestamp,
838
+ endTime: new Date().toISOString(),
839
+ durationUs: Math.max(0, (this.environment?.performance.now() ?? input.startedAt) - input.startedAt) * 1000,
840
+ spanKind: "client",
841
+ spanCategory: "http",
842
+ statusCode: hasError ? "error" : "ok",
843
+ statusMessage: input.error === undefined ? "" : "FetchError",
844
+ sessionId: input.sessionId,
845
+ viewId: input.viewContext.viewId,
846
+ pageUrl: input.pageUrl,
847
+ route: input.route,
848
+ userId: input.userId,
849
+ httpMethod: input.request.method,
850
+ httpUrl: requestUrl.toString(),
851
+ httpStatusCode: statusCode,
852
+ attributes: input.attributes
853
+ }));
854
+ }
855
+ installLifecycle() {
856
+ if (this.environment === null) {
857
+ return () => {
858
+ return;
859
+ };
860
+ }
861
+ const flushOnHide = () => void this.flushBatch(true);
862
+ const onVisibilityChange = () => {
863
+ if (this.environment?.document.visibilityState === "hidden") {
864
+ flushOnHide();
865
+ }
866
+ };
867
+ this.environment.window.addEventListener("pagehide", flushOnHide);
868
+ this.environment.document.addEventListener("visibilitychange", onVisibilityChange);
869
+ return () => {
870
+ this.environment?.window.removeEventListener("pagehide", flushOnHide);
871
+ this.environment?.document.removeEventListener("visibilitychange", onVisibilityChange);
872
+ };
873
+ }
874
+ }
875
+ // src/index.ts
876
+ var createInkronikBrowser2 = (options) => new InkronikBrowserClient2(options);
877
+
878
+ export { sanitizeBrowserAttributes2, sanitizeBrowserUrl2, InkronikBrowserClient2, createInkronikBrowser2 };
879
+
880
+ //# debugId=938A993CF6B9370F64756E2164756E21
881
+ //# sourceMappingURL=index-rsfpk3kf.js.map