@chrom-ar/collector 0.3.0 → 0.4.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,3 +1,5 @@
1
+ import { truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-YN5N3X7X.js';
2
+
1
3
  // src/dsn.ts
2
4
  function parseDsn(dsn) {
3
5
  let parsed;
@@ -9,52 +11,7 @@ function parseDsn(dsn) {
9
11
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
10
12
  const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
11
13
  const key = parsed.username;
12
- return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
13
- }
14
-
15
- // src/util.ts
16
- function uuid4() {
17
- if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
18
- const b = crypto.getRandomValues(new Uint8Array(16));
19
- b[6] = (b[6] ?? 0) & 15 | 64;
20
- b[8] = (b[8] ?? 0) & 63 | 128;
21
- const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
22
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
23
- }
24
- function truncate(s, max) {
25
- if (s.length <= max) return s;
26
- const last = s.charCodeAt(max - 1);
27
- return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
28
- }
29
- function safeStringify(value, max = 8192) {
30
- return truncate(stringify(value), max);
31
- }
32
- function stringify(value) {
33
- if (typeof value === "string") return value;
34
- if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
35
- return String(value);
36
- }
37
- const seen = /* @__PURE__ */ new WeakSet();
38
- try {
39
- return JSON.stringify(value, (_key, v) => {
40
- if (typeof v === "bigint") return v.toString();
41
- if (typeof v === "object" && v !== null) {
42
- if (seen.has(v)) return "[Circular]";
43
- seen.add(v);
44
- }
45
- return v;
46
- });
47
- } catch {
48
- try {
49
- return String(value);
50
- } catch {
51
- return "[unserializable]";
52
- }
53
- }
54
- }
55
- function stripUrl(url) {
56
- const i = url.search(/[?#]/);
57
- return i === -1 ? url : url.slice(0, i);
14
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
58
15
  }
59
16
 
60
17
  // src/stacktrace.ts
@@ -209,7 +166,7 @@ function releaseOf(options) {
209
166
  function environmentOf(options) {
210
167
  return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
211
168
  }
212
- function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
169
+ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
213
170
  const event = {
214
171
  v: 1,
215
172
  uuid: uuid4(),
@@ -217,12 +174,13 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
217
174
  platform: "javascript",
218
175
  level: toLevel(ctx.level),
219
176
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
220
- sdk: { name: SDK_NAME, version: "0.3.0" }
177
+ sdk: { name: SDK_NAME, version: "0.4.0" }
221
178
  };
222
179
  const environment = environmentOf(options);
223
180
  if (environment !== void 0) event.environment = environment;
224
181
  const release = releaseOf(options);
225
182
  if (release !== void 0) event.release = release;
183
+ if (session !== void 0) event.session = session;
226
184
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
227
185
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
228
186
  if (user) event.user = user;
@@ -346,7 +304,7 @@ async function beat({ url, key, fetch, options, logger }) {
346
304
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
347
305
  let status;
348
306
  try {
349
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.0" }, environment, release });
307
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.4.0" }, environment, release });
350
308
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
351
309
  ({ status } = response);
352
310
  } catch (error) {
@@ -392,6 +350,15 @@ function displayUrl(win, url, stripQuery) {
392
350
  }
393
351
  return stripQuery ? stripUrl(shown) : shown;
394
352
  }
353
+ function timeRequest(opts, win, method, url) {
354
+ const target = opts.onRequest ? rumUrl(win.location.href, url) : void 0;
355
+ if (target === void 0) return () => void 0;
356
+ const start = performance.now();
357
+ const token = opts.onRequestStart?.();
358
+ return (status) => {
359
+ opts.onRequest?.({ method: method.toUpperCase(), url: target, status: status ?? 0, start, end: performance.now() }, token);
360
+ };
361
+ }
395
362
  function absoluteUrl(win, url) {
396
363
  try {
397
364
  return new URL(url, win.location.href).href;
@@ -502,8 +469,10 @@ function instrumentFetch(win, record, opts) {
502
469
  const { method, url } = describe2(input, init2);
503
470
  if (opts.skipUrl(absoluteUrl(win, url))) return;
504
471
  const shown = displayUrl(win, url, opts.stripQuery);
472
+ const timing = timeRequest(opts, win, method, url);
505
473
  done = (status) => {
506
474
  safeRecord(() => {
475
+ timing(status);
507
476
  record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
508
477
  });
509
478
  };
@@ -545,14 +514,24 @@ function instrumentHistory(win, record, opts) {
545
514
  (original) => function __collectorWrapped(...args) {
546
515
  original.apply(this, args);
547
516
  moved();
517
+ navigated();
548
518
  }
549
519
  );
520
+ const navigated = () => {
521
+ safeRecord(() => {
522
+ opts.onNavigate?.();
523
+ });
524
+ };
525
+ const popped = () => {
526
+ moved();
527
+ navigated();
528
+ };
550
529
  const restores = [wrapState("pushState"), wrapState("replaceState")];
551
- win.addEventListener("popstate", moved);
530
+ win.addEventListener("popstate", popped);
552
531
  win.addEventListener("hashchange", moved);
553
532
  return () => {
554
533
  if (!restores.map((restore) => restore()).every(Boolean)) return false;
555
- win.removeEventListener("popstate", moved);
534
+ win.removeEventListener("popstate", popped);
556
535
  win.removeEventListener("hashchange", moved);
557
536
  return true;
558
537
  };
@@ -583,9 +562,11 @@ function instrumentXhr(win, record, opts) {
583
562
  const request = requests.get(this);
584
563
  if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
585
564
  const shown = displayUrl(win, request.url, opts.stripQuery);
565
+ const timing = timeRequest(opts, win, request.method, request.url);
586
566
  this.addEventListener("loadend", () => {
587
567
  safeRecord(() => {
588
568
  const status = this.status !== 0 ? this.status : void 0;
569
+ timing(status);
589
570
  record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
590
571
  });
591
572
  }, { once: true });
@@ -599,7 +580,7 @@ function instrumentXhr(win, record, opts) {
599
580
  // src/logger.ts
600
581
  function createLogger(isDebug) {
601
582
  const warned = /* @__PURE__ */ new Set();
602
- const { debug, warn } = console;
583
+ const { debug, info, warn } = console;
603
584
  return {
604
585
  debug(...args) {
605
586
  if (isDebug()) debug.call(console, "[collector]", ...args);
@@ -608,6 +589,12 @@ function createLogger(isDebug) {
608
589
  if (warned.has(message)) return;
609
590
  warned.add(message);
610
591
  warn.call(console, `[collector] ${message}`);
592
+ },
593
+ info(message) {
594
+ info.call(console, `[collector] ${message}`);
595
+ },
596
+ warn(message) {
597
+ warn.call(console, `[collector] ${message}`);
611
598
  }
612
599
  };
613
600
  }
@@ -649,6 +636,11 @@ var Scope = class {
649
636
  };
650
637
 
651
638
  // src/transport.ts
639
+ function answer(pending, result) {
640
+ const { onAnswer } = pending;
641
+ pending.onAnswer = void 0;
642
+ onAnswer?.(result);
643
+ }
652
644
  var FIRST_BACKOFF = 1e3;
653
645
  var MAX_BACKOFF = 6e4;
654
646
  var MAX_ATTEMPTS = 8;
@@ -670,14 +662,15 @@ var Transport = class {
670
662
  this.idleWaiters = [];
671
663
  this.maxQueue = deps.maxQueue ?? 30;
672
664
  }
673
- /** Queues the event. Never blocks, never throws. */
674
- send(event) {
665
+ /** Queues the event. Never blocks, never throws. `onAnswer` gets the first attempt's answer. */
666
+ send(event, onAnswer) {
675
667
  if (this.disabled) return;
676
668
  if (this.queue.length >= this.maxQueue) {
677
- this.queue.shift();
669
+ const dropped = this.queue.shift();
670
+ if (dropped) answer(dropped, { error: new Error("dropped: too many events queued") });
678
671
  this.deps.logger.debug("queue full, dropped the oldest event");
679
672
  }
680
- this.queue.push({ event, attempts: 0 });
673
+ this.queue.push({ event, attempts: 0, ...onAnswer ? { onAnswer } : {} });
681
674
  this.dispatch();
682
675
  }
683
676
  /** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
@@ -727,6 +720,7 @@ var Transport = class {
727
720
  const body = encode(pending.event);
728
721
  if (body === void 0) {
729
722
  this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
723
+ answer(pending, { error: new Error("dropped: over 1 MB or not JSON-encodable") });
730
724
  this.dispatch();
731
725
  return;
732
726
  }
@@ -759,6 +753,7 @@ var Transport = class {
759
753
  this.inFlight = false;
760
754
  this.inFlightKeepaliveBytes = 0;
761
755
  const { status } = response;
756
+ answer(pending, { status });
762
757
  if (status >= 200 && status < 300) {
763
758
  this.backoff = FIRST_BACKOFF;
764
759
  } else if (status === 429) {
@@ -783,6 +778,7 @@ var Transport = class {
783
778
  this.dispatch();
784
779
  }
785
780
  retry(pending, error) {
781
+ answer(pending, { error });
786
782
  this.inFlight = false;
787
783
  this.inFlightKeepaliveBytes = 0;
788
784
  pending.attempts += 1;
@@ -805,7 +801,7 @@ var Transport = class {
805
801
  }
806
802
  disable(status) {
807
803
  this.disabled = true;
808
- this.queue = [];
804
+ for (const pending of this.queue.splice(0)) answer(pending, { error: new Error(`dropped: Collector rejected this DSN (HTTP ${String(status)})`) });
809
805
  this.deps.onDisable?.();
810
806
  const where = this.deps.origin ?? "unknown origin";
811
807
  this.deps.logger.warnOnce(
@@ -854,14 +850,36 @@ var INSTRUMENTS = {
854
850
  history: instrumentHistory
855
851
  };
856
852
  var DEFAULT_MAX_BREADCRUMBS = 50;
853
+ var TEST_TIMEOUT_MS = 1e4;
854
+ function testFailure(result) {
855
+ if ("error" in result) {
856
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
857
+ return `couldn't reach Collector (${message}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;
858
+ }
859
+ const { status } = result;
860
+ if (status >= 200 && status < 300) return void 0;
861
+ if (status === 401) return "Collector rejected the key (HTTP 401). Check the DSN on your project's setup page.";
862
+ if (status === 403) return "this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.";
863
+ if (status === 429) return "Collector asked to slow down (HTTP 429). Try again in a minute.";
864
+ if (status >= 500) return `Collector had an error (HTTP ${String(status)}). The event will be retried.`;
865
+ return `Collector rejected the event (HTTP ${String(status)}).`;
866
+ }
857
867
  var active;
858
868
  var installed = /* @__PURE__ */ new Map();
859
869
  var sharedOptions = {
860
870
  skipUrl: (url) => active?.isOwnUrl(url) ?? false,
861
871
  get stripQuery() {
862
872
  return active?.options.stripQuery !== false;
873
+ },
874
+ onRequestStart: () => active?.rum?.requestStart(),
875
+ onRequest: (timing, token) => {
876
+ active?.rum?.request(timing, token);
877
+ },
878
+ onNavigate: () => {
879
+ active?.rum?.navigate();
863
880
  }
864
881
  };
882
+ var RUM_KINDS = /* @__PURE__ */ new Set(["fetch", "xhr", "history"]);
865
883
  var rejected = /* @__PURE__ */ new Set();
866
884
  var recorderFor = (kind) => (crumb) => {
867
885
  if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
@@ -882,15 +900,18 @@ var Client = class {
882
900
  this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
883
901
  if (options.enabled === false) {
884
902
  this.logger.debug("disabled (enabled: false): nothing will be sent");
903
+ this.inactive = "the SDK is off (enabled: false).";
885
904
  return;
886
905
  }
887
906
  if (typeof options.dsn !== "string" || options.dsn === "") {
888
907
  this.logger.debug("no DSN given: nothing will be sent");
908
+ this.inactive = "no DSN given to init().";
889
909
  return;
890
910
  }
891
911
  const endpoint = parseDsn(options.dsn);
892
912
  if (!endpoint) {
893
913
  this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
914
+ this.inactive = "invalid DSN. Copy it from your project's setup page.";
894
915
  return;
895
916
  }
896
917
  this.endpointBase = endpoint.base;
@@ -913,9 +934,17 @@ var Client = class {
913
934
  )
914
935
  );
915
936
  }
937
+ if (options.rum && !this.transport.disabled) {
938
+ try {
939
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.4.0" }, environment: environmentOf(options), release: releaseOf(options) });
940
+ } catch (error) {
941
+ this.logger.debug("RUM didn't start", error);
942
+ }
943
+ }
916
944
  active = this;
917
945
  for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
918
- if (options.breadcrumbs?.[kind] === false || installed.has(kind)) continue;
946
+ const needed = options.breadcrumbs?.[kind] !== false || this.rum !== void 0 && RUM_KINDS.has(kind);
947
+ if (!needed || installed.has(kind)) continue;
919
948
  try {
920
949
  installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
921
950
  } catch (error) {
@@ -937,12 +966,62 @@ var Client = class {
937
966
  const context = typeof ctx === "string" ? { level: ctx } : ctx;
938
967
  return this.capture(() => eventFromMessage(message, this.env(), context));
939
968
  }
969
+ /**
970
+ * Sends one test error to check the setup end to end. Skips the filters
971
+ * (ignoreErrors, duplicates, the rate cap); `beforeSend` edits apply, but
972
+ * if it drops the event the original is sent anyway.
973
+ */
974
+ async test() {
975
+ const fail = (reason) => {
976
+ this.logger.warn(`Test event not sent: ${reason}`);
977
+ return { ok: false, reason };
978
+ };
979
+ const { transport } = this;
980
+ if (this.closed) return Promise.resolve(fail("the SDK was closed."));
981
+ if (!transport) return Promise.resolve(fail(this.inactive ?? "the SDK isn't sending."));
982
+ if (transport.disabled) return Promise.resolve(fail("Collector already rejected this DSN on this page (HTTP 401/403)."));
983
+ let event;
984
+ try {
985
+ const error = new Error("Test event from Collector.test(). If you can see it in Collector, your setup works.");
986
+ error.name = "CollectorTest";
987
+ throw error;
988
+ } catch (error) {
989
+ event = eventFromException(error, this.env(), { tags: { "collector.test": "true" }, fingerprint: ["collector.test"] });
990
+ }
991
+ const final = this.beforeSend(event) ?? event;
992
+ return new Promise((resolve) => {
993
+ let settled = false;
994
+ const settle = (result) => {
995
+ if (settled) return;
996
+ settled = true;
997
+ clearTimeout(timer);
998
+ resolve(result);
999
+ };
1000
+ const timer = setTimeout(() => {
1001
+ settle(fail(`no answer from Collector within ${String(TEST_TIMEOUT_MS / 1e3)} s.`));
1002
+ }, TEST_TIMEOUT_MS);
1003
+ transport.send(final, (answer2) => {
1004
+ if (settled) return;
1005
+ const reason = testFailure(answer2);
1006
+ if (reason !== void 0) {
1007
+ settle(fail(reason));
1008
+ return;
1009
+ }
1010
+ this.logger.info(`Test event sent (${"status" in answer2 ? String(answer2.status) : "?"}). Look for "CollectorTest" in your project: ${final.uuid}`);
1011
+ settle({ ok: true, id: final.uuid });
1012
+ });
1013
+ });
1014
+ }
940
1015
  addBreadcrumb(crumb) {
941
1016
  this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
942
1017
  }
943
1018
  async flush(timeoutMs) {
944
1019
  return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
945
1020
  }
1021
+ /** Names the current RUM page view. Does nothing without RUM. */
1022
+ setRoute(name) {
1023
+ this.rum?.setRoute(name);
1024
+ }
946
1025
  /** True for requests to Collector itself. */
947
1026
  isOwnUrl(url) {
948
1027
  return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
@@ -950,6 +1029,11 @@ var Client = class {
950
1029
  /** Removes every listener and wrapper it can. Events already queued still go out. */
951
1030
  close() {
952
1031
  this.closed = true;
1032
+ try {
1033
+ this.rum?.close();
1034
+ } catch (error) {
1035
+ this.logger.debug("RUM didn't close cleanly", error);
1036
+ }
953
1037
  if (active === this) {
954
1038
  active = void 0;
955
1039
  for (const [kind, restore] of installed) {
@@ -974,7 +1058,8 @@ var Client = class {
974
1058
  scope: this.scope,
975
1059
  origin: win.location.origin,
976
1060
  href: win.location.href,
977
- userAgent: win.navigator.userAgent
1061
+ userAgent: win.navigator.userAgent,
1062
+ session: this.rum?.session
978
1063
  };
979
1064
  }
980
1065
  capture(build) {
@@ -1020,8 +1105,9 @@ var Client = class {
1020
1105
  };
1021
1106
 
1022
1107
  // src/index.ts
1023
- var SDK_VERSION = "0.3.0";
1108
+ var SDK_VERSION = "0.4.0";
1024
1109
  var client;
1110
+ var pendingRoute;
1025
1111
  var pendingScope = new Scope();
1026
1112
  function scope() {
1027
1113
  return client?.scope ?? pendingScope;
@@ -1040,8 +1126,21 @@ function init(options) {
1040
1126
  const kept = scope();
1041
1127
  client?.close();
1042
1128
  client = new Client(options, window, kept);
1129
+ if (pendingRoute) client.setRoute(pendingRoute.name);
1130
+ pendingRoute = void 0;
1131
+ if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1132
+ else Reflect.deleteProperty(window, CONSOLE_HANDLE);
1043
1133
  }, void 0);
1044
1134
  }
1135
+ var CONSOLE_HANDLE = "__collector";
1136
+ async function test() {
1137
+ const notInitialized = () => {
1138
+ const reason = "init() hasn't run on this page (or this isn't a browser).";
1139
+ console.warn(`[collector] Test event not sent: ${reason}`);
1140
+ return { ok: false, reason };
1141
+ };
1142
+ return safely(async () => client ? client.test() : Promise.resolve(notInitialized()), Promise.resolve({ ok: false, reason: "internal error." }));
1143
+ }
1045
1144
  function captureException(error, context) {
1046
1145
  return safely(() => client?.captureException(error, context), void 0);
1047
1146
  }
@@ -1072,12 +1171,20 @@ function addBreadcrumb(crumb) {
1072
1171
  async function flush(timeoutMs) {
1073
1172
  return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
1074
1173
  }
1174
+ function setRoute(name) {
1175
+ safely(() => {
1176
+ if (client) client.setRoute(name);
1177
+ else pendingRoute = { name };
1178
+ }, void 0);
1179
+ }
1075
1180
  function close() {
1076
1181
  safely(() => {
1077
1182
  client?.close();
1078
1183
  client = void 0;
1079
1184
  pendingScope = new Scope();
1185
+ pendingRoute = void 0;
1186
+ if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1080
1187
  }, void 0);
1081
1188
  }
1082
1189
 
1083
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser };
1190
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setRoute, setTag, setTags, setUser, test };