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