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