@plasius/analytics 1.1.0 → 1.1.2

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,9 +1,170 @@
1
1
  // src/core/client.ts
2
+ import { createSchema, field } from "@plasius/schema";
2
3
  var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
3
4
  var DEFAULT_BATCH_SIZE = 20;
4
5
  var DEFAULT_MAX_QUEUE_SIZE = 500;
5
6
  var DEFAULT_STORAGE_KEY_PREFIX = "plasius.analytics.local-space.queue";
7
+ var DEFAULT_ERROR_MESSAGE_LENGTH = 240;
8
+ var DEFAULT_ERROR_STACK_LENGTH = 1800;
9
+ var DEFAULT_ERROR_COMPONENT_STACK_LENGTH = 1800;
10
+ var DEFAULT_ERROR_CONTEXT_DEPTH = 4;
11
+ var DEFAULT_ERROR_CONTEXT_BREADTH = 20;
12
+ var DEFAULT_ERROR_TAG_COUNT = 10;
13
+ var DEFAULT_ERROR_THRESHOLD_COUNT = 5;
14
+ var DEFAULT_ERROR_THRESHOLD_WINDOW_MS = 5 * 60 * 1e3;
15
+ var DEFAULT_ERROR_REDACT_KEYS = [
16
+ "email",
17
+ "phone",
18
+ "name",
19
+ "address",
20
+ "token",
21
+ "password",
22
+ "secret",
23
+ "cookie",
24
+ "session",
25
+ "auth",
26
+ "ssn",
27
+ "dob",
28
+ "user"
29
+ ];
6
30
  var JSON_CONTENT_TYPE_HEADER = "application/json";
31
+ var LOCALHOST_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
32
+ var PlainLogValueSchema = createSchema(
33
+ {
34
+ value: field.generalText().PID({
35
+ classification: "none",
36
+ action: "none",
37
+ logHandling: "plain",
38
+ purpose: "analytics log-safe value"
39
+ })
40
+ },
41
+ "analytics-log-safe-value",
42
+ { version: "1.0.0", piiEnforcement: "none" }
43
+ );
44
+ var SensitiveLogValueSchema = createSchema(
45
+ {
46
+ value: field.generalText().PID({
47
+ classification: "high",
48
+ action: "none",
49
+ logHandling: "redact",
50
+ purpose: "analytics private value"
51
+ })
52
+ },
53
+ "analytics-private-log-value",
54
+ { version: "1.0.0", piiEnforcement: "none" }
55
+ );
56
+ function applySchemaLogHandling(value, sensitive) {
57
+ const schema = sensitive ? SensitiveLogValueSchema : PlainLogValueSchema;
58
+ const sanitized = schema.sanitizeForLog({ value }, (input) => `p(${String(input ?? "")})`);
59
+ return typeof sanitized.value === "string" ? sanitized.value : "";
60
+ }
61
+ var REDACTED_VALUE = applySchemaLogHandling("sensitive", true) || "[REDACTED]";
62
+ var CrashIdentitySchema = createSchema(
63
+ {
64
+ source: field.generalText().PID({
65
+ classification: "none",
66
+ action: "none",
67
+ logHandling: "plain",
68
+ purpose: "analytics source identifier"
69
+ }).optional(),
70
+ channel: field.generalText().PID({
71
+ classification: "none",
72
+ action: "none",
73
+ logHandling: "plain",
74
+ purpose: "analytics channel identifier"
75
+ }).optional(),
76
+ runtime: field.generalText().PID({
77
+ classification: "none",
78
+ action: "none",
79
+ logHandling: "plain",
80
+ purpose: "analytics runtime identifier"
81
+ }).optional(),
82
+ sessionId: field.generalText().PID({
83
+ classification: "high",
84
+ action: "hash",
85
+ logHandling: "redact",
86
+ purpose: "client session identifier"
87
+ }).optional(),
88
+ userAgent: field.generalText().PID({
89
+ classification: "low",
90
+ action: "hash",
91
+ logHandling: "pseudonym",
92
+ purpose: "browser user agent"
93
+ }).optional(),
94
+ platform: field.generalText().PID({
95
+ classification: "low",
96
+ action: "hash",
97
+ logHandling: "pseudonym",
98
+ purpose: "client platform"
99
+ }).optional(),
100
+ language: field.generalText().PID({
101
+ classification: "low",
102
+ action: "hash",
103
+ logHandling: "pseudonym",
104
+ purpose: "client language"
105
+ }).optional(),
106
+ timezone: field.generalText().PID({
107
+ classification: "low",
108
+ action: "hash",
109
+ logHandling: "pseudonym",
110
+ purpose: "client timezone"
111
+ }).optional(),
112
+ origin: field.generalText().PID({
113
+ classification: "low",
114
+ action: "hash",
115
+ logHandling: "pseudonym",
116
+ purpose: "client origin"
117
+ }).optional(),
118
+ pathname: field.generalText().PID({
119
+ classification: "low",
120
+ action: "hash",
121
+ logHandling: "pseudonym",
122
+ purpose: "client route path"
123
+ }).optional(),
124
+ screenWidth: field.number().PID({
125
+ classification: "none",
126
+ action: "none",
127
+ logHandling: "plain",
128
+ purpose: "viewport width"
129
+ }).optional(),
130
+ screenHeight: field.number().PID({
131
+ classification: "none",
132
+ action: "none",
133
+ logHandling: "plain",
134
+ purpose: "viewport height"
135
+ }).optional(),
136
+ colorDepth: field.number().PID({
137
+ classification: "none",
138
+ action: "none",
139
+ logHandling: "plain",
140
+ purpose: "screen color depth"
141
+ }).optional(),
142
+ hardwareConcurrency: field.number().PID({
143
+ classification: "none",
144
+ action: "none",
145
+ logHandling: "plain",
146
+ purpose: "cpu concurrency"
147
+ }).optional(),
148
+ identifiers: field.array(
149
+ field.object({
150
+ key: field.generalText().PID({
151
+ classification: "none",
152
+ action: "none",
153
+ logHandling: "plain",
154
+ purpose: "identifier field key"
155
+ }),
156
+ value: field.generalText().PID({
157
+ classification: "high",
158
+ action: "hash",
159
+ logHandling: "redact",
160
+ purpose: "identifier value"
161
+ })
162
+ })
163
+ ).optional()
164
+ },
165
+ "analytics-crash-identity",
166
+ { version: "1.0.0", piiEnforcement: "none" }
167
+ );
7
168
  function createId(prefix) {
8
169
  return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
9
170
  }
@@ -76,6 +237,9 @@ function toPositiveInteger(value, fallback) {
76
237
  const rounded = Math.floor(value);
77
238
  return rounded > 0 ? rounded : fallback;
78
239
  }
240
+ function toNumberWithMinimum(value, fallback, minimum) {
241
+ return Math.max(toPositiveInteger(value, fallback), minimum);
242
+ }
79
243
  function resolveSessionId(configSessionId, previousSessionId) {
80
244
  const explicitSessionId = configSessionId?.trim();
81
245
  if (explicitSessionId) {
@@ -86,6 +250,62 @@ function resolveSessionId(configSessionId, previousSessionId) {
86
250
  }
87
251
  return createId("session");
88
252
  }
253
+ function normalizeRedactKeys(keys, previousKeys) {
254
+ const values = keys ?? previousKeys ?? DEFAULT_ERROR_REDACT_KEYS;
255
+ const normalized = values.map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0);
256
+ if (normalized.length === 0) {
257
+ return [...DEFAULT_ERROR_REDACT_KEYS];
258
+ }
259
+ return Array.from(new Set(normalized));
260
+ }
261
+ function resolveErrorReportingConfig(config, previous) {
262
+ return {
263
+ enabled: config?.enabled ?? previous?.enabled ?? true,
264
+ secureEndpointOnly: config?.secureEndpointOnly ?? previous?.secureEndpointOnly ?? true,
265
+ maxMessageLength: toNumberWithMinimum(
266
+ config?.maxMessageLength ?? previous?.maxMessageLength,
267
+ DEFAULT_ERROR_MESSAGE_LENGTH,
268
+ 16
269
+ ),
270
+ maxStackLength: toNumberWithMinimum(
271
+ config?.maxStackLength ?? previous?.maxStackLength,
272
+ DEFAULT_ERROR_STACK_LENGTH,
273
+ 32
274
+ ),
275
+ maxComponentStackLength: toNumberWithMinimum(
276
+ config?.maxComponentStackLength ?? previous?.maxComponentStackLength,
277
+ DEFAULT_ERROR_COMPONENT_STACK_LENGTH,
278
+ 32
279
+ ),
280
+ maxContextDepth: toNumberWithMinimum(
281
+ config?.maxContextDepth ?? previous?.maxContextDepth,
282
+ DEFAULT_ERROR_CONTEXT_DEPTH,
283
+ 1
284
+ ),
285
+ maxContextBreadth: toNumberWithMinimum(
286
+ config?.maxContextBreadth ?? previous?.maxContextBreadth,
287
+ DEFAULT_ERROR_CONTEXT_BREADTH,
288
+ 1
289
+ ),
290
+ maxTagCount: toNumberWithMinimum(
291
+ config?.maxTagCount ?? previous?.maxTagCount,
292
+ DEFAULT_ERROR_TAG_COUNT,
293
+ 1
294
+ ),
295
+ thresholdCount: toNumberWithMinimum(
296
+ config?.thresholdCount ?? previous?.thresholdCount,
297
+ DEFAULT_ERROR_THRESHOLD_COUNT,
298
+ 1
299
+ ),
300
+ thresholdWindowMs: toNumberWithMinimum(
301
+ config?.thresholdWindowMs ?? previous?.thresholdWindowMs,
302
+ DEFAULT_ERROR_THRESHOLD_WINDOW_MS,
303
+ 1e3
304
+ ),
305
+ redactKeys: normalizeRedactKeys(config?.redactKeys, previous?.redactKeys),
306
+ onThresholdReached: config?.onThresholdReached ?? previous?.onThresholdReached
307
+ };
308
+ }
89
309
  function resolveConfig(config, previous) {
90
310
  const source = (config.source ?? previous?.source ?? "").trim();
91
311
  if (!source) {
@@ -116,12 +336,19 @@ function resolveConfig(config, previous) {
116
336
  config.flushIntervalMs ?? previous?.flushIntervalMs,
117
337
  DEFAULT_FLUSH_INTERVAL_MS
118
338
  ),
119
- batchSize: toPositiveInteger(config.batchSize ?? previous?.batchSize, DEFAULT_BATCH_SIZE),
339
+ batchSize: toPositiveInteger(
340
+ config.batchSize ?? previous?.batchSize,
341
+ DEFAULT_BATCH_SIZE
342
+ ),
120
343
  maxQueueSize: toPositiveInteger(
121
344
  config.maxQueueSize ?? previous?.maxQueueSize,
122
345
  DEFAULT_MAX_QUEUE_SIZE
123
346
  ),
124
347
  storageKey: resolveStorageKey(config.storageKey, source, channel, previous),
348
+ errorReporting: resolveErrorReportingConfig(
349
+ config.errorReporting,
350
+ previous?.errorReporting
351
+ ),
125
352
  transport: config.transport ?? previous?.transport ?? defaultTransport,
126
353
  onError: config.onError ?? previous?.onError
127
354
  };
@@ -133,15 +360,339 @@ function isStoredRecordCandidate(value) {
133
360
  const candidate = value;
134
361
  return typeof candidate.id === "string" && typeof candidate.component === "string" && typeof candidate.action === "string" && typeof candidate.source === "string" && typeof candidate.sessionId === "string" && typeof candidate.timestamp === "number";
135
362
  }
363
+ function isErrorDetailsCandidate(value) {
364
+ if (!value || typeof value !== "object") {
365
+ return false;
366
+ }
367
+ const candidate = value;
368
+ return typeof candidate.boundary === "string" && typeof candidate.name === "string" && typeof candidate.message === "string" && typeof candidate.fingerprint === "string";
369
+ }
370
+ function redactSensitiveText(value) {
371
+ return value.replace(
372
+ /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,
373
+ REDACTED_VALUE
374
+ ).replace(/\bBearer\s+[A-Za-z0-9._-]+\b/gi, `Bearer ${REDACTED_VALUE}`).replace(/\b[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, REDACTED_VALUE).replace(/\b\d{9,}\b/g, REDACTED_VALUE).replace(
375
+ /([?&](?:token|email|phone|name|user|auth|session|password)=)[^&#\s]*/gi,
376
+ `$1${REDACTED_VALUE}`
377
+ );
378
+ }
379
+ function sanitizeSingleLine(value, maxLength) {
380
+ const raw = typeof value === "string" ? value : String(value ?? "");
381
+ const flattened = raw.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim();
382
+ if (!flattened) {
383
+ return "";
384
+ }
385
+ const redacted = redactSensitiveText(flattened).slice(0, maxLength);
386
+ return applySchemaLogHandling(redacted, false).slice(0, maxLength);
387
+ }
388
+ function sanitizeMultiline(value, maxLength) {
389
+ const raw = typeof value === "string" ? value : String(value ?? "");
390
+ const normalized = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
391
+ const sanitized = redactSensitiveText(normalized).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).join("\n");
392
+ if (!sanitized) {
393
+ return "";
394
+ }
395
+ const schemaHandled = applySchemaLogHandling(sanitized, false);
396
+ return schemaHandled.slice(0, maxLength);
397
+ }
398
+ function isPlainObject(value) {
399
+ return value !== null && typeof value === "object" && !Array.isArray(value);
400
+ }
401
+ function shouldRedactContextKey(key, resolvedErrorReporting) {
402
+ const loweredKey = key.trim().toLowerCase();
403
+ if (!loweredKey) {
404
+ return false;
405
+ }
406
+ return resolvedErrorReporting.redactKeys.some(
407
+ (candidate) => loweredKey === candidate || loweredKey.includes(candidate)
408
+ );
409
+ }
410
+ function toIdentifierValue(value, maxLength) {
411
+ if (value === null || value === void 0) {
412
+ return "null";
413
+ }
414
+ if (typeof value === "string") {
415
+ return sanitizeSingleLine(value, maxLength) || "empty";
416
+ }
417
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
418
+ return sanitizeSingleLine(String(value), maxLength) || "empty";
419
+ }
420
+ if (value instanceof Date) {
421
+ return value.toISOString();
422
+ }
423
+ return sanitizeSingleLine(safeSerialize(value), maxLength) || "empty";
424
+ }
425
+ function pushIdentifier(identifiers, keyPath, value, maxLength) {
426
+ if (!keyPath.trim()) {
427
+ return;
428
+ }
429
+ identifiers.push({
430
+ key: sanitizeSingleLine(keyPath, 160),
431
+ value: toIdentifierValue(value, maxLength)
432
+ });
433
+ }
434
+ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identifiers, keyPath) {
435
+ if (value === null || value === void 0) {
436
+ return null;
437
+ }
438
+ if (typeof value === "string") {
439
+ return sanitizeSingleLine(value, resolvedErrorReporting.maxMessageLength);
440
+ }
441
+ if (typeof value === "number") {
442
+ return Number.isFinite(value) ? value : null;
443
+ }
444
+ if (typeof value === "boolean") {
445
+ return value;
446
+ }
447
+ if (typeof value === "bigint") {
448
+ return sanitizeSingleLine(value.toString(), resolvedErrorReporting.maxMessageLength);
449
+ }
450
+ if (value instanceof Date) {
451
+ return value.toISOString();
452
+ }
453
+ if (Array.isArray(value)) {
454
+ if (seen.has(value)) {
455
+ return "[circular]";
456
+ }
457
+ seen.add(value);
458
+ if (depth >= resolvedErrorReporting.maxContextDepth) {
459
+ return "[truncated]";
460
+ }
461
+ return value.slice(0, resolvedErrorReporting.maxContextBreadth).map(
462
+ (item) => sanitizeContextValue(
463
+ item,
464
+ resolvedErrorReporting,
465
+ depth + 1,
466
+ seen,
467
+ identifiers,
468
+ `${keyPath}[]`
469
+ )
470
+ );
471
+ }
472
+ if (isPlainObject(value)) {
473
+ if (seen.has(value)) {
474
+ return "[circular]";
475
+ }
476
+ seen.add(value);
477
+ if (depth >= resolvedErrorReporting.maxContextDepth) {
478
+ return "[truncated]";
479
+ }
480
+ const sanitized = {};
481
+ const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
482
+ for (const [key, nestedValue] of entries) {
483
+ const childPath = keyPath ? `${keyPath}.${key}` : key;
484
+ if (shouldRedactContextKey(key, resolvedErrorReporting)) {
485
+ sanitized[key] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
486
+ pushIdentifier(
487
+ identifiers,
488
+ childPath,
489
+ nestedValue,
490
+ resolvedErrorReporting.maxMessageLength
491
+ );
492
+ continue;
493
+ }
494
+ sanitized[key] = sanitizeContextValue(
495
+ nestedValue,
496
+ resolvedErrorReporting,
497
+ depth + 1,
498
+ seen,
499
+ identifiers,
500
+ childPath
501
+ );
502
+ }
503
+ return sanitized;
504
+ }
505
+ return sanitizeSingleLine(value, resolvedErrorReporting.maxMessageLength);
506
+ }
507
+ function sanitizeErrorContext(context, resolvedErrorReporting) {
508
+ if (!context || !isPlainObject(context)) {
509
+ return { context: {}, identifiers: [] };
510
+ }
511
+ const sanitized = {};
512
+ const identifiers = [];
513
+ const seen = /* @__PURE__ */ new WeakSet();
514
+ const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
515
+ for (const [key, value] of entries) {
516
+ if (shouldRedactContextKey(key, resolvedErrorReporting)) {
517
+ sanitized[key] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
518
+ pushIdentifier(identifiers, key, value, resolvedErrorReporting.maxMessageLength);
519
+ continue;
520
+ }
521
+ sanitized[key] = sanitizeContextValue(
522
+ value,
523
+ resolvedErrorReporting,
524
+ 1,
525
+ seen,
526
+ identifiers,
527
+ key
528
+ );
529
+ }
530
+ return {
531
+ context: sanitized,
532
+ identifiers
533
+ };
534
+ }
535
+ function hashString(input) {
536
+ let hash = 5381;
537
+ for (let index = 0; index < input.length; index += 1) {
538
+ hash = hash * 33 ^ input.charCodeAt(index);
539
+ }
540
+ return hash >>> 0;
541
+ }
542
+ function hashForStorage(value) {
543
+ const normalized = typeof value === "string" ? value : safeSerialize(value);
544
+ return `hash_${hashString(normalized).toString(16)}`;
545
+ }
546
+ function encryptForStorage(value) {
547
+ return `enc_${hashForStorage(value)}`;
548
+ }
549
+ function buildCrashIdentityPayload(config, identifiers) {
550
+ const payload = {
551
+ source: config.source,
552
+ channel: config.channel,
553
+ runtime: config.runtime,
554
+ sessionId: config.sessionId
555
+ };
556
+ if (isBrowserEnvironment()) {
557
+ if (typeof navigator !== "undefined") {
558
+ payload.userAgent = navigator.userAgent;
559
+ payload.platform = navigator.platform;
560
+ payload.language = navigator.language;
561
+ payload.hardwareConcurrency = navigator.hardwareConcurrency;
562
+ }
563
+ if (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function") {
564
+ payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
565
+ }
566
+ if (typeof window !== "undefined") {
567
+ payload.origin = window.location.origin;
568
+ payload.pathname = window.location.pathname;
569
+ }
570
+ if (typeof screen !== "undefined") {
571
+ payload.screenWidth = screen.width;
572
+ payload.screenHeight = screen.height;
573
+ payload.colorDepth = screen.colorDepth;
574
+ }
575
+ }
576
+ if (identifiers.length > 0) {
577
+ payload.identifiers = identifiers.slice(0, config.errorReporting.maxContextBreadth);
578
+ }
579
+ return payload;
580
+ }
581
+ function prepareCrashIdentityForStorage(payload) {
582
+ return CrashIdentitySchema.prepareForStorage(
583
+ payload,
584
+ encryptForStorage,
585
+ hashForStorage
586
+ );
587
+ }
588
+ function normalizeTags(tags, maxTagCount, maxTagLength) {
589
+ if (!Array.isArray(tags) || tags.length === 0) {
590
+ return void 0;
591
+ }
592
+ const normalized = tags.map((tag) => sanitizeSingleLine(tag, maxTagLength)).filter((tag) => tag.length > 0);
593
+ if (normalized.length === 0) {
594
+ return void 0;
595
+ }
596
+ return Array.from(new Set(normalized)).slice(0, maxTagCount);
597
+ }
598
+ function safeSerialize(value) {
599
+ try {
600
+ return JSON.stringify(value);
601
+ } catch {
602
+ return "[unserializable]";
603
+ }
604
+ }
605
+ function extractErrorDetails(error) {
606
+ if (error instanceof Error) {
607
+ return {
608
+ name: error.name || "Error",
609
+ message: error.message || "Unknown error",
610
+ stack: error.stack
611
+ };
612
+ }
613
+ if (typeof error === "string") {
614
+ return {
615
+ name: "Error",
616
+ message: error
617
+ };
618
+ }
619
+ if (isPlainObject(error)) {
620
+ const name = typeof error.name === "string" && error.name.trim() ? error.name : "Error";
621
+ const message = typeof error.message === "string" && error.message.trim() ? error.message : sanitizeSingleLine(safeSerialize(error), DEFAULT_ERROR_MESSAGE_LENGTH);
622
+ return {
623
+ name,
624
+ message,
625
+ stack: typeof error.stack === "string" ? error.stack : void 0
626
+ };
627
+ }
628
+ return {
629
+ name: "UnknownError",
630
+ message: sanitizeSingleLine(error, DEFAULT_ERROR_MESSAGE_LENGTH) || "Unknown error"
631
+ };
632
+ }
633
+ function normalizeErrorReport(report, resolvedErrorReporting, existingFingerprint) {
634
+ const extractedError = extractErrorDetails(report.error);
635
+ const boundary = sanitizeSingleLine(report.boundary, 100) || "UnknownErrorBoundary";
636
+ const name = sanitizeSingleLine(extractedError.name, 80) || "Error";
637
+ const message = sanitizeSingleLine(extractedError.message, resolvedErrorReporting.maxMessageLength) || "Unknown error";
638
+ const stack = extractedError.stack ? sanitizeMultiline(extractedError.stack, resolvedErrorReporting.maxStackLength) : void 0;
639
+ const componentStack = report.componentStack ? sanitizeMultiline(
640
+ report.componentStack,
641
+ resolvedErrorReporting.maxComponentStackLength
642
+ ) : void 0;
643
+ const severity = report.severity === "fatal" ? "fatal" : "error";
644
+ const handled = report.handled ?? true;
645
+ const tags = normalizeTags(
646
+ report.tags,
647
+ resolvedErrorReporting.maxTagCount,
648
+ resolvedErrorReporting.maxMessageLength
649
+ );
650
+ const fingerprintBase = `${boundary}|${name}|${message}|${stack?.split("\n")[0] ?? ""}|${severity}`;
651
+ const fallbackFingerprint = `err_${hashString(fingerprintBase).toString(16)}`;
652
+ const fingerprint = sanitizeSingleLine(existingFingerprint, 120) || fallbackFingerprint;
653
+ return {
654
+ boundary,
655
+ name,
656
+ message,
657
+ fingerprint,
658
+ handled,
659
+ severity,
660
+ stack,
661
+ componentStack,
662
+ tags
663
+ };
664
+ }
665
+ function normalizeStoredErrorDetails(value, resolvedErrorReporting) {
666
+ return normalizeErrorReport(
667
+ {
668
+ boundary: value.boundary,
669
+ error: {
670
+ name: value.name,
671
+ message: value.message,
672
+ stack: value.stack
673
+ },
674
+ componentStack: value.componentStack,
675
+ handled: value.handled,
676
+ severity: value.severity,
677
+ tags: value.tags
678
+ },
679
+ resolvedErrorReporting,
680
+ value.fingerprint
681
+ );
682
+ }
136
683
  function normalizeStoredRecord(value, fallbackConfig) {
137
684
  const context = value.context && typeof value.context === "object" && !Array.isArray(value.context) ? value.context : {};
138
685
  const channel = value.channel === "frontend" || value.channel === "backend" ? value.channel : fallbackConfig.channel;
139
686
  const runtime = value.runtime === "browser" || value.runtime === "server" ? value.runtime : fallbackConfig.runtime;
687
+ const kind = value.kind === "error" ? "error" : "interaction";
688
+ const errorDetails = kind === "error" && isErrorDetailsCandidate(value.error) ? normalizeStoredErrorDetails(value.error, fallbackConfig.errorReporting) : void 0;
140
689
  return {
141
690
  ...value,
691
+ kind,
142
692
  channel,
143
693
  runtime,
144
- context
694
+ context,
695
+ error: errorDetails
145
696
  };
146
697
  }
147
698
  function readQueue(storageKey, fallbackConfig) {
@@ -199,6 +750,25 @@ function createMergedContext(config, eventChannel, eventContext) {
199
750
  }
200
751
  return mergedContext;
201
752
  }
753
+ function isSecureEndpoint(endpoint) {
754
+ const trimmedEndpoint = endpoint.trim();
755
+ if (!trimmedEndpoint) {
756
+ return false;
757
+ }
758
+ if (trimmedEndpoint.startsWith("/")) {
759
+ return true;
760
+ }
761
+ try {
762
+ const baseUrl = isBrowserEnvironment() ? window.location.origin : "https://localhost";
763
+ const parsedUrl = new URL(trimmedEndpoint, baseUrl);
764
+ if (parsedUrl.protocol === "https:") {
765
+ return true;
766
+ }
767
+ return parsedUrl.protocol === "http:" && LOCALHOST_HOSTS.has(parsedUrl.hostname);
768
+ } catch {
769
+ return false;
770
+ }
771
+ }
202
772
  function createLocalSpaceAnalyticsClient(config) {
203
773
  let resolvedConfig = resolveConfig(config);
204
774
  let queue = readQueue(resolvedConfig.storageKey, resolvedConfig).slice(
@@ -208,6 +778,7 @@ function createLocalSpaceAnalyticsClient(config) {
208
778
  let isFlushing = false;
209
779
  let flushQueuedAfterCurrent = false;
210
780
  let isDestroyed = false;
781
+ const issueAggregates = /* @__PURE__ */ new Map();
211
782
  const persistQueue = () => writeQueue(resolvedConfig.storageKey, queue);
212
783
  const trimQueue = () => {
213
784
  if (queue.length <= resolvedConfig.maxQueueSize) {
@@ -215,6 +786,117 @@ function createLocalSpaceAnalyticsClient(config) {
215
786
  }
216
787
  queue = queue.slice(queue.length - resolvedConfig.maxQueueSize);
217
788
  };
789
+ const pruneIssueState = (state, now) => {
790
+ const windowStart = now - resolvedConfig.errorReporting.thresholdWindowMs;
791
+ state.timestamps = state.timestamps.filter((timestamp) => timestamp >= windowStart);
792
+ };
793
+ const buildIssueReport = (fingerprint, state) => {
794
+ if (state.timestamps.length === 0) {
795
+ return null;
796
+ }
797
+ const sortedTimestamps = [...state.timestamps].sort((a, b) => a - b);
798
+ return {
799
+ fingerprint,
800
+ boundary: state.sample.boundary,
801
+ count: sortedTimestamps.length,
802
+ firstSeen: sortedTimestamps[0] ?? Date.now(),
803
+ lastSeen: sortedTimestamps[sortedTimestamps.length - 1] ?? Date.now(),
804
+ severity: state.sample.severity,
805
+ sample: state.sample
806
+ };
807
+ };
808
+ const recordIssue = (details, timestamp, triggerThreshold) => {
809
+ const existingState = issueAggregates.get(details.fingerprint);
810
+ if (!existingState) {
811
+ issueAggregates.set(details.fingerprint, {
812
+ timestamps: [timestamp],
813
+ sample: details
814
+ });
815
+ } else {
816
+ existingState.timestamps.push(timestamp);
817
+ existingState.sample = details;
818
+ }
819
+ const state = issueAggregates.get(details.fingerprint);
820
+ if (!state) {
821
+ return;
822
+ }
823
+ pruneIssueState(state, timestamp);
824
+ if (state.timestamps.length === 0) {
825
+ issueAggregates.delete(details.fingerprint);
826
+ return;
827
+ }
828
+ if (!triggerThreshold) {
829
+ return;
830
+ }
831
+ const thresholdCallback = resolvedConfig.errorReporting.onThresholdReached;
832
+ if (!thresholdCallback) {
833
+ return;
834
+ }
835
+ if (state.timestamps.length < resolvedConfig.errorReporting.thresholdCount) {
836
+ return;
837
+ }
838
+ const lastTriggeredAt = state.lastTriggeredAt;
839
+ if (lastTriggeredAt !== void 0 && timestamp - lastTriggeredAt < resolvedConfig.errorReporting.thresholdWindowMs) {
840
+ return;
841
+ }
842
+ state.lastTriggeredAt = timestamp;
843
+ const report = buildIssueReport(details.fingerprint, state);
844
+ if (!report) {
845
+ return;
846
+ }
847
+ try {
848
+ thresholdCallback({
849
+ source: resolvedConfig.source,
850
+ channel: resolvedConfig.channel,
851
+ runtime: resolvedConfig.runtime,
852
+ thresholdCount: resolvedConfig.errorReporting.thresholdCount,
853
+ windowMs: resolvedConfig.errorReporting.thresholdWindowMs,
854
+ report
855
+ });
856
+ } catch (error) {
857
+ resolvedConfig.onError?.(error);
858
+ }
859
+ };
860
+ const getIssueReports = () => {
861
+ const now = Date.now();
862
+ for (const [fingerprint, state] of issueAggregates.entries()) {
863
+ pruneIssueState(state, now);
864
+ if (state.timestamps.length === 0) {
865
+ issueAggregates.delete(fingerprint);
866
+ }
867
+ }
868
+ return Array.from(issueAggregates.entries()).map(([fingerprint, state]) => buildIssueReport(fingerprint, state)).filter((report) => report !== null).sort((left, right) => {
869
+ if (right.count !== left.count) {
870
+ return right.count - left.count;
871
+ }
872
+ return right.lastSeen - left.lastSeen;
873
+ });
874
+ };
875
+ const enqueueRecord = (record) => {
876
+ queue.push(record);
877
+ trimQueue();
878
+ persistQueue();
879
+ if (record.kind === "error" && record.error) {
880
+ recordIssue(record.error, record.timestamp, true);
881
+ }
882
+ if (queue.length >= resolvedConfig.batchSize) {
883
+ void flush();
884
+ }
885
+ };
886
+ const canSendBatchToEndpoint = (events) => {
887
+ if (!resolvedConfig.endpoint || !resolvedConfig.errorReporting.secureEndpointOnly || isSecureEndpoint(resolvedConfig.endpoint)) {
888
+ return true;
889
+ }
890
+ if (!events.some((event) => event.kind === "error")) {
891
+ return true;
892
+ }
893
+ resolvedConfig.onError?.(
894
+ new Error(
895
+ `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
896
+ )
897
+ );
898
+ return false;
899
+ };
218
900
  const flushWithBeacon = () => {
219
901
  if (!resolvedConfig.endpoint || queue.length === 0) {
220
902
  return false;
@@ -223,6 +905,9 @@ function createLocalSpaceAnalyticsClient(config) {
223
905
  return false;
224
906
  }
225
907
  const events = queue.slice(0, resolvedConfig.batchSize);
908
+ if (!canSendBatchToEndpoint(events)) {
909
+ return false;
910
+ }
226
911
  try {
227
912
  const body = createPayload(resolvedConfig, events);
228
913
  const blob = new Blob([body], { type: JSON_CONTENT_TYPE_HEADER });
@@ -248,6 +933,9 @@ function createLocalSpaceAnalyticsClient(config) {
248
933
  return;
249
934
  }
250
935
  const events = queue.slice(0, resolvedConfig.batchSize);
936
+ if (!canSendBatchToEndpoint(events)) {
937
+ return;
938
+ }
251
939
  const body = createPayload(resolvedConfig, events);
252
940
  isFlushing = true;
253
941
  try {
@@ -303,6 +991,11 @@ function createLocalSpaceAnalyticsClient(config) {
303
991
  document.addEventListener("visibilitychange", handleVisibilityChange);
304
992
  window.addEventListener("pagehide", handlePageHide);
305
993
  }
994
+ for (const record of queue) {
995
+ if (record.kind === "error" && record.error) {
996
+ recordIssue(record.error, record.timestamp, false);
997
+ }
998
+ }
306
999
  startFlushTimer();
307
1000
  const trackWithChannel = (event, channel) => {
308
1001
  const trackableEvent = {
@@ -317,10 +1010,13 @@ function createLocalSpaceAnalyticsClient(config) {
317
1010
  }
318
1011
  const eventChannel = event.channel ?? resolvedConfig.channel;
319
1012
  const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
1013
+ const kind = event.kind === "error" ? "error" : "interaction";
1014
+ const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
320
1015
  const record = {
321
1016
  id: createId("event"),
322
1017
  component: event.component,
323
1018
  action: event.action,
1019
+ kind,
324
1020
  channel: eventChannel,
325
1021
  runtime: resolvedConfig.runtime,
326
1022
  label: event.label,
@@ -330,14 +1026,58 @@ function createLocalSpaceAnalyticsClient(config) {
330
1026
  source: resolvedConfig.source,
331
1027
  sessionId: resolvedConfig.sessionId,
332
1028
  timestamp: event.timestamp ?? Date.now(),
333
- context: createMergedContext(resolvedConfig, eventChannel, event.context)
1029
+ context: createMergedContext(resolvedConfig, eventChannel, event.context),
1030
+ error: normalizedError
334
1031
  };
335
- queue.push(record);
336
- trimQueue();
337
- persistQueue();
338
- if (queue.length >= resolvedConfig.batchSize) {
339
- void flush();
1032
+ enqueueRecord(record);
1033
+ };
1034
+ const reportError = (report) => {
1035
+ if (isDestroyed || !resolvedConfig.enabled) {
1036
+ return;
1037
+ }
1038
+ if (!resolvedConfig.errorReporting.enabled) {
1039
+ return;
340
1040
  }
1041
+ if (resolvedConfig.errorReporting.secureEndpointOnly && resolvedConfig.endpoint && !isSecureEndpoint(resolvedConfig.endpoint)) {
1042
+ resolvedConfig.onError?.(
1043
+ new Error(
1044
+ `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
1045
+ )
1046
+ );
1047
+ return;
1048
+ }
1049
+ const eventChannel = report.channel ?? resolvedConfig.channel;
1050
+ const timestamp = report.timestamp ?? Date.now();
1051
+ const normalizedError = normalizeErrorReport(report, resolvedConfig.errorReporting);
1052
+ const {
1053
+ context: errorContext,
1054
+ identifiers
1055
+ } = sanitizeErrorContext(report.context, resolvedConfig.errorReporting);
1056
+ errorContext.errorFingerprint = normalizedError.fingerprint;
1057
+ errorContext.errorBoundary = normalizedError.boundary;
1058
+ errorContext.errorSeverity = normalizedError.severity;
1059
+ errorContext.errorHandled = normalizedError.handled;
1060
+ errorContext.clientIdentity = prepareCrashIdentityForStorage(
1061
+ buildCrashIdentityPayload(resolvedConfig, identifiers)
1062
+ );
1063
+ if (normalizedError.tags && normalizedError.tags.length > 0) {
1064
+ errorContext.errorTags = normalizedError.tags;
1065
+ }
1066
+ const record = {
1067
+ id: createId("event"),
1068
+ component: normalizedError.boundary,
1069
+ action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
1070
+ kind: "error",
1071
+ channel: eventChannel,
1072
+ runtime: resolvedConfig.runtime,
1073
+ label: normalizedError.fingerprint,
1074
+ source: resolvedConfig.source,
1075
+ sessionId: resolvedConfig.sessionId,
1076
+ timestamp,
1077
+ context: createMergedContext(resolvedConfig, eventChannel, errorContext),
1078
+ error: normalizedError
1079
+ };
1080
+ enqueueRecord(record);
341
1081
  };
342
1082
  return {
343
1083
  get source() {
@@ -353,6 +1093,8 @@ function createLocalSpaceAnalyticsClient(config) {
353
1093
  trackBackend(event) {
354
1094
  trackWithChannel(event, "backend");
355
1095
  },
1096
+ reportError,
1097
+ getIssueReports,
356
1098
  flush,
357
1099
  updateConfig(nextConfig) {
358
1100
  if (isDestroyed) {
@@ -426,6 +1168,7 @@ function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "fronten
426
1168
  batchSize: DEFAULT_BATCH_SIZE,
427
1169
  maxQueueSize: DEFAULT_MAX_QUEUE_SIZE,
428
1170
  storageKey: buildDefaultStorageKey(source, channel),
1171
+ errorReporting: resolveErrorReportingConfig(void 0),
429
1172
  transport: async () => void 0,
430
1173
  onError: void 0
431
1174
  };
@@ -435,6 +1178,8 @@ function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "fronten
435
1178
  track: () => void 0,
436
1179
  trackFrontend: () => void 0,
437
1180
  trackBackend: () => void 0,
1181
+ reportError: () => void 0,
1182
+ getIssueReports: () => [],
438
1183
  flush: async () => void 0,
439
1184
  updateConfig: () => void 0,
440
1185
  getConfig: () => noopConfig,