@chrom-ar/collector 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,21 @@
1
1
  # Changelog
2
2
 
3
- ## 0.2.0 (unreleased)
3
+ ## 0.3.1 (2026-11-07)
4
+
5
+ - `Collector.test()` sends one test error and resolves to `{ ok: true, id }`
6
+ or `{ ok: false, reason }`, logging one console line either way. With
7
+ `debug: true`, it's also `window.__collector.test()` for the browser
8
+ console.
9
+
10
+ ## 0.3.0 (2026-11-07)
11
+
12
+ - Heartbeats: once a day per release and environment, a few seconds after
13
+ `init()`, the SDK tells Collector the app is running, so a healthy app
14
+ shows as set up before its first error. It sends only the SDK name and
15
+ version, release and environment, and remembers the day in
16
+ `localStorage`. Turn it off with `heartbeat: false`.
17
+
18
+ ## 0.2.0 (2026-11-05)
4
19
 
5
20
  - Source maps: `init()` uses the release injected by
6
21
  `@chrom-ar/collector-cli/vite` (the `__COLLECTOR_RELEASE__` build constant)
package/README.md CHANGED
@@ -66,6 +66,24 @@ browser console:
66
66
 
67
67
  - **Vue:** add `app.config.errorHandler = (error) => Collector.captureException(error);`
68
68
 
69
+ ## Checking your setup
70
+
71
+ Send one test error and see what Collector answered:
72
+
73
+ ```ts
74
+ const result = await Collector.test();
75
+ // { ok: true, id: "…" } or { ok: false, reason: "Collector rejected the key (HTTP 401)…" }
76
+ ```
77
+
78
+ It also logs one line to the console, `[collector] Test event sent (202)…`
79
+ or why it wasn't. The event is a `CollectorTest` error tagged
80
+ `collector.test: "true"`, and every test groups into one issue. It skips
81
+ `ignoreErrors`, duplicate detection and the rate cap; `beforeSend` edits
82
+ apply, but if `beforeSend` drops it, it's sent anyway.
83
+
84
+ With `debug: true`, it's also on `window.__collector.test()`, so you can
85
+ run it from the browser's console without importing anything.
86
+
69
87
  ## Reporting things yourself
70
88
 
71
89
  ```ts
@@ -107,6 +125,12 @@ Collector.setTag("plan", "pro");
107
125
  as they are, errors as `Type: message`, and only the first level of an
108
126
  object's keys (`{id: 4812, email: "…"}`). If your app logs personal
109
127
  data, turn them off with `breadcrumbs: { console: false }`.
128
+ - Once a day per release and environment, a few seconds after `init()`,
129
+ the SDK sends a heartbeat so Collector knows the app is running even
130
+ before its first error. It carries only the SDK's name and version, the
131
+ release and the environment: no user, URL, user agent or browser id. The
132
+ day it was sent is kept in `localStorage` (`collector:heartbeat:…`).
133
+ Turn it off with `heartbeat: false`.
110
134
  - `beforeSend` sees every event last, and can edit it or drop it:
111
135
 
112
136
  ```ts
@@ -135,6 +159,7 @@ Collector.setTag("plan", "pro");
135
159
  | `breadcrumbs` | all on | `{ console, dom, fetch, xhr, history }`, each `true`/`false` |
136
160
  | `maxBreadcrumbs` | `50` | How many breadcrumbs to keep |
137
161
  | `autoCapture` | both on | `{ onerror, onunhandledrejection }`, or `false` for neither |
162
+ | `heartbeat` | `true` | `false` stops the daily heartbeat (see [Privacy](#privacy)) |
138
163
 
139
164
  Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })`,
140
165
  `flush(timeoutMs?)` (waits until queued events are sent) and `close()`
package/dist/index.cjs CHANGED
@@ -10,7 +10,8 @@ function parseDsn(dsn) {
10
10
  }
11
11
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
12
12
  const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
13
- return { url: `${base}/api/events?key=${parsed.username}`, base };
13
+ const key = parsed.username;
14
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
14
15
  }
15
16
 
16
17
  // src/util.ts
@@ -203,6 +204,13 @@ function eventFromMessage(message, env, ctx) {
203
204
  function injectedRelease() {
204
205
  return typeof __COLLECTOR_RELEASE__ === "string" ? __COLLECTOR_RELEASE__ : void 0;
205
206
  }
207
+ function releaseOf(options) {
208
+ const release = options.release ?? injectedRelease();
209
+ return release === "" ? void 0 : release;
210
+ }
211
+ function environmentOf(options) {
212
+ return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
213
+ }
206
214
  function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
207
215
  const event = {
208
216
  v: 1,
@@ -211,11 +219,12 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
211
219
  platform: "javascript",
212
220
  level: toLevel(ctx.level),
213
221
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
214
- sdk: { name: SDK_NAME, version: "0.2.0" }
222
+ sdk: { name: SDK_NAME, version: "0.3.1" }
215
223
  };
216
- if (typeof options.environment === "string" && options.environment !== "") event.environment = options.environment;
217
- const release = options.release ?? injectedRelease();
218
- if (release !== void 0 && release !== "") event.release = release;
224
+ const environment = environmentOf(options);
225
+ if (environment !== void 0) event.environment = environment;
226
+ const release = releaseOf(options);
227
+ if (release !== void 0) event.release = release;
219
228
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
220
229
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
221
230
  if (user) event.user = user;
@@ -306,6 +315,54 @@ function errorFromLocation(e) {
306
315
  return error;
307
316
  }
308
317
 
318
+ // src/heartbeat.ts
319
+ var HEARTBEAT_DELAY_MS = 5e3;
320
+ var STORAGE_PREFIX = "collector:heartbeat:";
321
+ var sentThisPage = /* @__PURE__ */ new Set();
322
+ function scheduleHeartbeat(deps) {
323
+ let idle;
324
+ const run = () => {
325
+ void beat(deps);
326
+ };
327
+ const timer = setTimeout(() => {
328
+ if ("requestIdleCallback" in globalThis) idle = requestIdleCallback(run, { timeout: HEARTBEAT_DELAY_MS });
329
+ else run();
330
+ }, HEARTBEAT_DELAY_MS);
331
+ return () => {
332
+ clearTimeout(timer);
333
+ if (idle !== void 0) cancelIdleCallback(idle);
334
+ };
335
+ }
336
+ function storedMark(storageKey) {
337
+ try {
338
+ return localStorage.getItem(storageKey);
339
+ } catch {
340
+ return null;
341
+ }
342
+ }
343
+ async function beat({ url, key, fetch, options, logger }) {
344
+ const release = releaseOf(options);
345
+ const environment = environmentOf(options);
346
+ const storageKey = STORAGE_PREFIX + key;
347
+ const mark = JSON.stringify([(/* @__PURE__ */ new Date()).toISOString().slice(0, 10), release ?? "", environment ?? ""]);
348
+ if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
349
+ let status;
350
+ try {
351
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.1" }, environment, release });
352
+ const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
353
+ ({ status } = response);
354
+ } catch (error) {
355
+ logger.debug("heartbeat not sent", error);
356
+ return;
357
+ }
358
+ if (status === 429 || status >= 500) return;
359
+ try {
360
+ localStorage.setItem(storageKey, mark);
361
+ } catch {
362
+ sentThisPage.add(storageKey + mark);
363
+ }
364
+ }
365
+
309
366
  // src/instrument/common.ts
310
367
  var ORIGINAL = "__collector_original__";
311
368
  function wrap(obj, name, make) {
@@ -544,7 +601,7 @@ function instrumentXhr(win, record, opts) {
544
601
  // src/logger.ts
545
602
  function createLogger(isDebug) {
546
603
  const warned = /* @__PURE__ */ new Set();
547
- const { debug, warn } = console;
604
+ const { debug, info, warn } = console;
548
605
  return {
549
606
  debug(...args) {
550
607
  if (isDebug()) debug.call(console, "[collector]", ...args);
@@ -553,6 +610,12 @@ function createLogger(isDebug) {
553
610
  if (warned.has(message)) return;
554
611
  warned.add(message);
555
612
  warn.call(console, `[collector] ${message}`);
613
+ },
614
+ info(message) {
615
+ info.call(console, `[collector] ${message}`);
616
+ },
617
+ warn(message) {
618
+ warn.call(console, `[collector] ${message}`);
556
619
  }
557
620
  };
558
621
  }
@@ -594,6 +657,11 @@ var Scope = class {
594
657
  };
595
658
 
596
659
  // src/transport.ts
660
+ function answer(pending, result) {
661
+ const { onAnswer } = pending;
662
+ pending.onAnswer = void 0;
663
+ onAnswer?.(result);
664
+ }
597
665
  var FIRST_BACKOFF = 1e3;
598
666
  var MAX_BACKOFF = 6e4;
599
667
  var MAX_ATTEMPTS = 8;
@@ -615,14 +683,15 @@ var Transport = class {
615
683
  this.idleWaiters = [];
616
684
  this.maxQueue = deps.maxQueue ?? 30;
617
685
  }
618
- /** Queues the event. Never blocks, never throws. */
619
- send(event) {
686
+ /** Queues the event. Never blocks, never throws. `onAnswer` gets the first attempt's answer. */
687
+ send(event, onAnswer) {
620
688
  if (this.disabled) return;
621
689
  if (this.queue.length >= this.maxQueue) {
622
- this.queue.shift();
690
+ const dropped = this.queue.shift();
691
+ if (dropped) answer(dropped, { error: new Error("dropped: too many events queued") });
623
692
  this.deps.logger.debug("queue full, dropped the oldest event");
624
693
  }
625
- this.queue.push({ event, attempts: 0 });
694
+ this.queue.push({ event, attempts: 0, ...onAnswer ? { onAnswer } : {} });
626
695
  this.dispatch();
627
696
  }
628
697
  /** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
@@ -672,6 +741,7 @@ var Transport = class {
672
741
  const body = encode(pending.event);
673
742
  if (body === void 0) {
674
743
  this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
744
+ answer(pending, { error: new Error("dropped: over 1 MB or not JSON-encodable") });
675
745
  this.dispatch();
676
746
  return;
677
747
  }
@@ -704,6 +774,7 @@ var Transport = class {
704
774
  this.inFlight = false;
705
775
  this.inFlightKeepaliveBytes = 0;
706
776
  const { status } = response;
777
+ answer(pending, { status });
707
778
  if (status >= 200 && status < 300) {
708
779
  this.backoff = FIRST_BACKOFF;
709
780
  } else if (status === 429) {
@@ -728,6 +799,7 @@ var Transport = class {
728
799
  this.dispatch();
729
800
  }
730
801
  retry(pending, error) {
802
+ answer(pending, { error });
731
803
  this.inFlight = false;
732
804
  this.inFlightKeepaliveBytes = 0;
733
805
  pending.attempts += 1;
@@ -750,7 +822,7 @@ var Transport = class {
750
822
  }
751
823
  disable(status) {
752
824
  this.disabled = true;
753
- this.queue = [];
825
+ for (const pending of this.queue.splice(0)) answer(pending, { error: new Error(`dropped: Collector rejected this DSN (HTTP ${String(status)})`) });
754
826
  this.deps.onDisable?.();
755
827
  const where = this.deps.origin ?? "unknown origin";
756
828
  this.deps.logger.warnOnce(
@@ -799,6 +871,20 @@ var INSTRUMENTS = {
799
871
  history: instrumentHistory
800
872
  };
801
873
  var DEFAULT_MAX_BREADCRUMBS = 50;
874
+ var TEST_TIMEOUT_MS = 1e4;
875
+ function testFailure(result) {
876
+ if ("error" in result) {
877
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
878
+ return `couldn't reach Collector (${message}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;
879
+ }
880
+ const { status } = result;
881
+ if (status >= 200 && status < 300) return void 0;
882
+ if (status === 401) return "Collector rejected the key (HTTP 401). Check the DSN on your project's setup page.";
883
+ 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.";
884
+ if (status === 429) return "Collector asked to slow down (HTTP 429). Try again in a minute.";
885
+ if (status >= 500) return `Collector had an error (HTTP ${String(status)}). The event will be retried.`;
886
+ return `Collector rejected the event (HTTP ${String(status)}).`;
887
+ }
802
888
  var active;
803
889
  var installed = /* @__PURE__ */ new Map();
804
890
  var sharedOptions = {
@@ -827,15 +913,18 @@ var Client = class {
827
913
  this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
828
914
  if (options.enabled === false) {
829
915
  this.logger.debug("disabled (enabled: false): nothing will be sent");
916
+ this.inactive = "the SDK is off (enabled: false).";
830
917
  return;
831
918
  }
832
919
  if (typeof options.dsn !== "string" || options.dsn === "") {
833
920
  this.logger.debug("no DSN given: nothing will be sent");
921
+ this.inactive = "no DSN given to init().";
834
922
  return;
835
923
  }
836
924
  const endpoint = parseDsn(options.dsn);
837
925
  if (!endpoint) {
838
926
  this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
927
+ this.inactive = "invalid DSN. Copy it from your project's setup page.";
839
928
  return;
840
929
  }
841
930
  this.endpointBase = endpoint.base;
@@ -845,6 +934,8 @@ var Client = class {
845
934
  if (rejected.has(url)) {
846
935
  this.transport.disabled = true;
847
936
  this.logger.debug("Collector already rejected this DSN on this page: nothing will be sent");
937
+ } else if (options.heartbeat !== false) {
938
+ this.cleanups.push(scheduleHeartbeat({ url: endpoint.heartbeatUrl, key: endpoint.key, fetch: fetchFn, options, logger: this.logger }));
848
939
  }
849
940
  const auto = options.autoCapture;
850
941
  if (auto !== false) {
@@ -880,6 +971,52 @@ var Client = class {
880
971
  const context = typeof ctx === "string" ? { level: ctx } : ctx;
881
972
  return this.capture(() => eventFromMessage(message, this.env(), context));
882
973
  }
974
+ /**
975
+ * Sends one test error to check the setup end to end. Skips the filters
976
+ * (ignoreErrors, duplicates, the rate cap); `beforeSend` edits apply, but
977
+ * if it drops the event the original is sent anyway.
978
+ */
979
+ async test() {
980
+ const fail = (reason) => {
981
+ this.logger.warn(`Test event not sent: ${reason}`);
982
+ return { ok: false, reason };
983
+ };
984
+ const { transport } = this;
985
+ if (this.closed) return Promise.resolve(fail("the SDK was closed."));
986
+ if (!transport) return Promise.resolve(fail(this.inactive ?? "the SDK isn't sending."));
987
+ if (transport.disabled) return Promise.resolve(fail("Collector already rejected this DSN on this page (HTTP 401/403)."));
988
+ let event;
989
+ try {
990
+ const error = new Error("Test event from Collector.test(). If you can see it in Collector, your setup works.");
991
+ error.name = "CollectorTest";
992
+ throw error;
993
+ } catch (error) {
994
+ event = eventFromException(error, this.env(), { tags: { "collector.test": "true" }, fingerprint: ["collector.test"] });
995
+ }
996
+ const final = this.beforeSend(event) ?? event;
997
+ return new Promise((resolve) => {
998
+ let settled = false;
999
+ const settle = (result) => {
1000
+ if (settled) return;
1001
+ settled = true;
1002
+ clearTimeout(timer);
1003
+ resolve(result);
1004
+ };
1005
+ const timer = setTimeout(() => {
1006
+ settle(fail(`no answer from Collector within ${String(TEST_TIMEOUT_MS / 1e3)} s.`));
1007
+ }, TEST_TIMEOUT_MS);
1008
+ transport.send(final, (answer2) => {
1009
+ if (settled) return;
1010
+ const reason = testFailure(answer2);
1011
+ if (reason !== void 0) {
1012
+ settle(fail(reason));
1013
+ return;
1014
+ }
1015
+ this.logger.info(`Test event sent (${"status" in answer2 ? String(answer2.status) : "?"}). Look for "CollectorTest" in your project: ${final.uuid}`);
1016
+ settle({ ok: true, id: final.uuid });
1017
+ });
1018
+ });
1019
+ }
883
1020
  addBreadcrumb(crumb) {
884
1021
  this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
885
1022
  }
@@ -963,7 +1100,7 @@ var Client = class {
963
1100
  };
964
1101
 
965
1102
  // src/index.ts
966
- var SDK_VERSION = "0.2.0";
1103
+ var SDK_VERSION = "0.3.1";
967
1104
  var client;
968
1105
  var pendingScope = new Scope();
969
1106
  function scope() {
@@ -983,8 +1120,19 @@ function init(options) {
983
1120
  const kept = scope();
984
1121
  client?.close();
985
1122
  client = new Client(options, window, kept);
1123
+ if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1124
+ else Reflect.deleteProperty(window, CONSOLE_HANDLE);
986
1125
  }, void 0);
987
1126
  }
1127
+ var CONSOLE_HANDLE = "__collector";
1128
+ async function test() {
1129
+ const notInitialized = () => {
1130
+ const reason = "init() hasn't run on this page (or this isn't a browser).";
1131
+ console.warn(`[collector] Test event not sent: ${reason}`);
1132
+ return { ok: false, reason };
1133
+ };
1134
+ return safely(async () => client ? client.test() : Promise.resolve(notInitialized()), Promise.resolve({ ok: false, reason: "internal error." }));
1135
+ }
988
1136
  function captureException(error, context) {
989
1137
  return safely(() => client?.captureException(error, context), void 0);
990
1138
  }
@@ -1020,6 +1168,7 @@ function close() {
1020
1168
  client?.close();
1021
1169
  client = void 0;
1022
1170
  pendingScope = new Scope();
1171
+ if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1023
1172
  }, void 0);
1024
1173
  }
1025
1174
 
@@ -1033,3 +1182,4 @@ exports.init = init;
1033
1182
  exports.setTag = setTag;
1034
1183
  exports.setTags = setTags;
1035
1184
  exports.setUser = setUser;
1185
+ exports.test = test;
package/dist/index.d.cts CHANGED
@@ -62,6 +62,14 @@ interface CaptureContext {
62
62
  id: string | number;
63
63
  };
64
64
  }
65
+ /** What `test()` resolves to: the event's id, or why it wasn't accepted. */
66
+ type TestResult = {
67
+ ok: true;
68
+ id: string;
69
+ } | {
70
+ ok: false;
71
+ reason: string;
72
+ };
65
73
  type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
66
74
  interface CollectorOptions {
67
75
  /** Your project's DSN, from its setup page in Collector. Without it, nothing is sent. */
@@ -95,6 +103,12 @@ interface CollectorOptions {
95
103
  breadcrumbs?: Partial<Record<BreadcrumbKind, boolean>>;
96
104
  /** How many breadcrumbs to keep. Default `50`. */
97
105
  maxBreadcrumbs?: number;
106
+ /**
107
+ * Tell Collector once a day that the app is running (its release and
108
+ * environment, nothing about the user), so it shows as set up before any
109
+ * error. Default `true`.
110
+ */
111
+ heartbeat?: boolean;
98
112
  /** Report uncaught errors and unhandled promise rejections. Default: both on. */
99
113
  autoCapture?: false | {
100
114
  onerror?: boolean;
@@ -118,6 +132,13 @@ declare const SDK_VERSION: string;
118
132
  * options. Safe to import during server-side rendering: it does nothing there.
119
133
  */
120
134
  declare function init(options: CollectorOptions): void;
135
+ /**
136
+ * Sends one test error, to check your setup end to end. Resolves to
137
+ * `{ ok: true, id }` once Collector accepts it, or `{ ok: false, reason }`,
138
+ * and logs one line to the console either way. With `debug: true` it's also
139
+ * `window.__collector.test()`, for the browser console.
140
+ */
141
+ declare function test(): Promise<TestResult>;
121
142
  /**
122
143
  * Reports an error you caught. Returns the event id, or `undefined` if it
123
144
  * wasn't sent (no DSN, ignored, duplicate, dropped by `beforeSend`).
@@ -140,5 +161,5 @@ declare function flush(timeoutMs?: number): Promise<boolean>;
140
161
  /** Stops capturing and removes everything the SDK installed. */
141
162
  declare function close(): void;
142
163
 
143
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser };
144
- export type { Breadcrumb, BreadcrumbKind, CaptureContext, CollectorEvent, CollectorOptions, Frame, Level };
164
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
165
+ export type { Breadcrumb, BreadcrumbKind, CaptureContext, CollectorEvent, CollectorOptions, Frame, Level, TestResult };
package/dist/index.d.ts CHANGED
@@ -62,6 +62,14 @@ interface CaptureContext {
62
62
  id: string | number;
63
63
  };
64
64
  }
65
+ /** What `test()` resolves to: the event's id, or why it wasn't accepted. */
66
+ type TestResult = {
67
+ ok: true;
68
+ id: string;
69
+ } | {
70
+ ok: false;
71
+ reason: string;
72
+ };
65
73
  type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
66
74
  interface CollectorOptions {
67
75
  /** Your project's DSN, from its setup page in Collector. Without it, nothing is sent. */
@@ -95,6 +103,12 @@ interface CollectorOptions {
95
103
  breadcrumbs?: Partial<Record<BreadcrumbKind, boolean>>;
96
104
  /** How many breadcrumbs to keep. Default `50`. */
97
105
  maxBreadcrumbs?: number;
106
+ /**
107
+ * Tell Collector once a day that the app is running (its release and
108
+ * environment, nothing about the user), so it shows as set up before any
109
+ * error. Default `true`.
110
+ */
111
+ heartbeat?: boolean;
98
112
  /** Report uncaught errors and unhandled promise rejections. Default: both on. */
99
113
  autoCapture?: false | {
100
114
  onerror?: boolean;
@@ -118,6 +132,13 @@ declare const SDK_VERSION: string;
118
132
  * options. Safe to import during server-side rendering: it does nothing there.
119
133
  */
120
134
  declare function init(options: CollectorOptions): void;
135
+ /**
136
+ * Sends one test error, to check your setup end to end. Resolves to
137
+ * `{ ok: true, id }` once Collector accepts it, or `{ ok: false, reason }`,
138
+ * and logs one line to the console either way. With `debug: true` it's also
139
+ * `window.__collector.test()`, for the browser console.
140
+ */
141
+ declare function test(): Promise<TestResult>;
121
142
  /**
122
143
  * Reports an error you caught. Returns the event id, or `undefined` if it
123
144
  * wasn't sent (no DSN, ignored, duplicate, dropped by `beforeSend`).
@@ -140,5 +161,5 @@ declare function flush(timeoutMs?: number): Promise<boolean>;
140
161
  /** Stops capturing and removes everything the SDK installed. */
141
162
  declare function close(): void;
142
163
 
143
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser };
144
- export type { Breadcrumb, BreadcrumbKind, CaptureContext, CollectorEvent, CollectorOptions, Frame, Level };
164
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
165
+ export type { Breadcrumb, BreadcrumbKind, CaptureContext, CollectorEvent, CollectorOptions, Frame, Level, TestResult };
package/dist/index.js CHANGED
@@ -8,7 +8,8 @@ function parseDsn(dsn) {
8
8
  }
9
9
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
10
10
  const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
11
- return { url: `${base}/api/events?key=${parsed.username}`, base };
11
+ const key = parsed.username;
12
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
12
13
  }
13
14
 
14
15
  // src/util.ts
@@ -201,6 +202,13 @@ function eventFromMessage(message, env, ctx) {
201
202
  function injectedRelease() {
202
203
  return typeof __COLLECTOR_RELEASE__ === "string" ? __COLLECTOR_RELEASE__ : void 0;
203
204
  }
205
+ function releaseOf(options) {
206
+ const release = options.release ?? injectedRelease();
207
+ return release === "" ? void 0 : release;
208
+ }
209
+ function environmentOf(options) {
210
+ return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
211
+ }
204
212
  function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
205
213
  const event = {
206
214
  v: 1,
@@ -209,11 +217,12 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
209
217
  platform: "javascript",
210
218
  level: toLevel(ctx.level),
211
219
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
212
- sdk: { name: SDK_NAME, version: "0.2.0" }
220
+ sdk: { name: SDK_NAME, version: "0.3.1" }
213
221
  };
214
- if (typeof options.environment === "string" && options.environment !== "") event.environment = options.environment;
215
- const release = options.release ?? injectedRelease();
216
- if (release !== void 0 && release !== "") event.release = release;
222
+ const environment = environmentOf(options);
223
+ if (environment !== void 0) event.environment = environment;
224
+ const release = releaseOf(options);
225
+ if (release !== void 0) event.release = release;
217
226
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
218
227
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
219
228
  if (user) event.user = user;
@@ -304,6 +313,54 @@ function errorFromLocation(e) {
304
313
  return error;
305
314
  }
306
315
 
316
+ // src/heartbeat.ts
317
+ var HEARTBEAT_DELAY_MS = 5e3;
318
+ var STORAGE_PREFIX = "collector:heartbeat:";
319
+ var sentThisPage = /* @__PURE__ */ new Set();
320
+ function scheduleHeartbeat(deps) {
321
+ let idle;
322
+ const run = () => {
323
+ void beat(deps);
324
+ };
325
+ const timer = setTimeout(() => {
326
+ if ("requestIdleCallback" in globalThis) idle = requestIdleCallback(run, { timeout: HEARTBEAT_DELAY_MS });
327
+ else run();
328
+ }, HEARTBEAT_DELAY_MS);
329
+ return () => {
330
+ clearTimeout(timer);
331
+ if (idle !== void 0) cancelIdleCallback(idle);
332
+ };
333
+ }
334
+ function storedMark(storageKey) {
335
+ try {
336
+ return localStorage.getItem(storageKey);
337
+ } catch {
338
+ return null;
339
+ }
340
+ }
341
+ async function beat({ url, key, fetch, options, logger }) {
342
+ const release = releaseOf(options);
343
+ const environment = environmentOf(options);
344
+ const storageKey = STORAGE_PREFIX + key;
345
+ const mark = JSON.stringify([(/* @__PURE__ */ new Date()).toISOString().slice(0, 10), release ?? "", environment ?? ""]);
346
+ if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
347
+ let status;
348
+ try {
349
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.1" }, environment, release });
350
+ const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
351
+ ({ status } = response);
352
+ } catch (error) {
353
+ logger.debug("heartbeat not sent", error);
354
+ return;
355
+ }
356
+ if (status === 429 || status >= 500) return;
357
+ try {
358
+ localStorage.setItem(storageKey, mark);
359
+ } catch {
360
+ sentThisPage.add(storageKey + mark);
361
+ }
362
+ }
363
+
307
364
  // src/instrument/common.ts
308
365
  var ORIGINAL = "__collector_original__";
309
366
  function wrap(obj, name, make) {
@@ -542,7 +599,7 @@ function instrumentXhr(win, record, opts) {
542
599
  // src/logger.ts
543
600
  function createLogger(isDebug) {
544
601
  const warned = /* @__PURE__ */ new Set();
545
- const { debug, warn } = console;
602
+ const { debug, info, warn } = console;
546
603
  return {
547
604
  debug(...args) {
548
605
  if (isDebug()) debug.call(console, "[collector]", ...args);
@@ -551,6 +608,12 @@ function createLogger(isDebug) {
551
608
  if (warned.has(message)) return;
552
609
  warned.add(message);
553
610
  warn.call(console, `[collector] ${message}`);
611
+ },
612
+ info(message) {
613
+ info.call(console, `[collector] ${message}`);
614
+ },
615
+ warn(message) {
616
+ warn.call(console, `[collector] ${message}`);
554
617
  }
555
618
  };
556
619
  }
@@ -592,6 +655,11 @@ var Scope = class {
592
655
  };
593
656
 
594
657
  // src/transport.ts
658
+ function answer(pending, result) {
659
+ const { onAnswer } = pending;
660
+ pending.onAnswer = void 0;
661
+ onAnswer?.(result);
662
+ }
595
663
  var FIRST_BACKOFF = 1e3;
596
664
  var MAX_BACKOFF = 6e4;
597
665
  var MAX_ATTEMPTS = 8;
@@ -613,14 +681,15 @@ var Transport = class {
613
681
  this.idleWaiters = [];
614
682
  this.maxQueue = deps.maxQueue ?? 30;
615
683
  }
616
- /** Queues the event. Never blocks, never throws. */
617
- send(event) {
684
+ /** Queues the event. Never blocks, never throws. `onAnswer` gets the first attempt's answer. */
685
+ send(event, onAnswer) {
618
686
  if (this.disabled) return;
619
687
  if (this.queue.length >= this.maxQueue) {
620
- this.queue.shift();
688
+ const dropped = this.queue.shift();
689
+ if (dropped) answer(dropped, { error: new Error("dropped: too many events queued") });
621
690
  this.deps.logger.debug("queue full, dropped the oldest event");
622
691
  }
623
- this.queue.push({ event, attempts: 0 });
692
+ this.queue.push({ event, attempts: 0, ...onAnswer ? { onAnswer } : {} });
624
693
  this.dispatch();
625
694
  }
626
695
  /** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
@@ -670,6 +739,7 @@ var Transport = class {
670
739
  const body = encode(pending.event);
671
740
  if (body === void 0) {
672
741
  this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
742
+ answer(pending, { error: new Error("dropped: over 1 MB or not JSON-encodable") });
673
743
  this.dispatch();
674
744
  return;
675
745
  }
@@ -702,6 +772,7 @@ var Transport = class {
702
772
  this.inFlight = false;
703
773
  this.inFlightKeepaliveBytes = 0;
704
774
  const { status } = response;
775
+ answer(pending, { status });
705
776
  if (status >= 200 && status < 300) {
706
777
  this.backoff = FIRST_BACKOFF;
707
778
  } else if (status === 429) {
@@ -726,6 +797,7 @@ var Transport = class {
726
797
  this.dispatch();
727
798
  }
728
799
  retry(pending, error) {
800
+ answer(pending, { error });
729
801
  this.inFlight = false;
730
802
  this.inFlightKeepaliveBytes = 0;
731
803
  pending.attempts += 1;
@@ -748,7 +820,7 @@ var Transport = class {
748
820
  }
749
821
  disable(status) {
750
822
  this.disabled = true;
751
- this.queue = [];
823
+ for (const pending of this.queue.splice(0)) answer(pending, { error: new Error(`dropped: Collector rejected this DSN (HTTP ${String(status)})`) });
752
824
  this.deps.onDisable?.();
753
825
  const where = this.deps.origin ?? "unknown origin";
754
826
  this.deps.logger.warnOnce(
@@ -797,6 +869,20 @@ var INSTRUMENTS = {
797
869
  history: instrumentHistory
798
870
  };
799
871
  var DEFAULT_MAX_BREADCRUMBS = 50;
872
+ var TEST_TIMEOUT_MS = 1e4;
873
+ function testFailure(result) {
874
+ if ("error" in result) {
875
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
876
+ return `couldn't reach Collector (${message}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;
877
+ }
878
+ const { status } = result;
879
+ if (status >= 200 && status < 300) return void 0;
880
+ if (status === 401) return "Collector rejected the key (HTTP 401). Check the DSN on your project's setup page.";
881
+ 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.";
882
+ if (status === 429) return "Collector asked to slow down (HTTP 429). Try again in a minute.";
883
+ if (status >= 500) return `Collector had an error (HTTP ${String(status)}). The event will be retried.`;
884
+ return `Collector rejected the event (HTTP ${String(status)}).`;
885
+ }
800
886
  var active;
801
887
  var installed = /* @__PURE__ */ new Map();
802
888
  var sharedOptions = {
@@ -825,15 +911,18 @@ var Client = class {
825
911
  this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
826
912
  if (options.enabled === false) {
827
913
  this.logger.debug("disabled (enabled: false): nothing will be sent");
914
+ this.inactive = "the SDK is off (enabled: false).";
828
915
  return;
829
916
  }
830
917
  if (typeof options.dsn !== "string" || options.dsn === "") {
831
918
  this.logger.debug("no DSN given: nothing will be sent");
919
+ this.inactive = "no DSN given to init().";
832
920
  return;
833
921
  }
834
922
  const endpoint = parseDsn(options.dsn);
835
923
  if (!endpoint) {
836
924
  this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
925
+ this.inactive = "invalid DSN. Copy it from your project's setup page.";
837
926
  return;
838
927
  }
839
928
  this.endpointBase = endpoint.base;
@@ -843,6 +932,8 @@ var Client = class {
843
932
  if (rejected.has(url)) {
844
933
  this.transport.disabled = true;
845
934
  this.logger.debug("Collector already rejected this DSN on this page: nothing will be sent");
935
+ } else if (options.heartbeat !== false) {
936
+ this.cleanups.push(scheduleHeartbeat({ url: endpoint.heartbeatUrl, key: endpoint.key, fetch: fetchFn, options, logger: this.logger }));
846
937
  }
847
938
  const auto = options.autoCapture;
848
939
  if (auto !== false) {
@@ -878,6 +969,52 @@ var Client = class {
878
969
  const context = typeof ctx === "string" ? { level: ctx } : ctx;
879
970
  return this.capture(() => eventFromMessage(message, this.env(), context));
880
971
  }
972
+ /**
973
+ * Sends one test error to check the setup end to end. Skips the filters
974
+ * (ignoreErrors, duplicates, the rate cap); `beforeSend` edits apply, but
975
+ * if it drops the event the original is sent anyway.
976
+ */
977
+ async test() {
978
+ const fail = (reason) => {
979
+ this.logger.warn(`Test event not sent: ${reason}`);
980
+ return { ok: false, reason };
981
+ };
982
+ const { transport } = this;
983
+ if (this.closed) return Promise.resolve(fail("the SDK was closed."));
984
+ if (!transport) return Promise.resolve(fail(this.inactive ?? "the SDK isn't sending."));
985
+ if (transport.disabled) return Promise.resolve(fail("Collector already rejected this DSN on this page (HTTP 401/403)."));
986
+ let event;
987
+ try {
988
+ const error = new Error("Test event from Collector.test(). If you can see it in Collector, your setup works.");
989
+ error.name = "CollectorTest";
990
+ throw error;
991
+ } catch (error) {
992
+ event = eventFromException(error, this.env(), { tags: { "collector.test": "true" }, fingerprint: ["collector.test"] });
993
+ }
994
+ const final = this.beforeSend(event) ?? event;
995
+ return new Promise((resolve) => {
996
+ let settled = false;
997
+ const settle = (result) => {
998
+ if (settled) return;
999
+ settled = true;
1000
+ clearTimeout(timer);
1001
+ resolve(result);
1002
+ };
1003
+ const timer = setTimeout(() => {
1004
+ settle(fail(`no answer from Collector within ${String(TEST_TIMEOUT_MS / 1e3)} s.`));
1005
+ }, TEST_TIMEOUT_MS);
1006
+ transport.send(final, (answer2) => {
1007
+ if (settled) return;
1008
+ const reason = testFailure(answer2);
1009
+ if (reason !== void 0) {
1010
+ settle(fail(reason));
1011
+ return;
1012
+ }
1013
+ this.logger.info(`Test event sent (${"status" in answer2 ? String(answer2.status) : "?"}). Look for "CollectorTest" in your project: ${final.uuid}`);
1014
+ settle({ ok: true, id: final.uuid });
1015
+ });
1016
+ });
1017
+ }
881
1018
  addBreadcrumb(crumb) {
882
1019
  this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
883
1020
  }
@@ -961,7 +1098,7 @@ var Client = class {
961
1098
  };
962
1099
 
963
1100
  // src/index.ts
964
- var SDK_VERSION = "0.2.0";
1101
+ var SDK_VERSION = "0.3.1";
965
1102
  var client;
966
1103
  var pendingScope = new Scope();
967
1104
  function scope() {
@@ -981,8 +1118,19 @@ function init(options) {
981
1118
  const kept = scope();
982
1119
  client?.close();
983
1120
  client = new Client(options, window, kept);
1121
+ if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1122
+ else Reflect.deleteProperty(window, CONSOLE_HANDLE);
984
1123
  }, void 0);
985
1124
  }
1125
+ var CONSOLE_HANDLE = "__collector";
1126
+ async function test() {
1127
+ const notInitialized = () => {
1128
+ const reason = "init() hasn't run on this page (or this isn't a browser).";
1129
+ console.warn(`[collector] Test event not sent: ${reason}`);
1130
+ return { ok: false, reason };
1131
+ };
1132
+ return safely(async () => client ? client.test() : Promise.resolve(notInitialized()), Promise.resolve({ ok: false, reason: "internal error." }));
1133
+ }
986
1134
  function captureException(error, context) {
987
1135
  return safely(() => client?.captureException(error, context), void 0);
988
1136
  }
@@ -1018,7 +1166,8 @@ function close() {
1018
1166
  client?.close();
1019
1167
  client = void 0;
1020
1168
  pendingScope = new Scope();
1169
+ if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1021
1170
  }, void 0);
1022
1171
  }
1023
1172
 
1024
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser };
1173
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrom-ar/collector",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Reports your browser app's errors to Collector.",
5
5
  "keywords": [
6
6
  "error-tracking",
@@ -11,6 +11,11 @@
11
11
  "collector"
12
12
  ],
13
13
  "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/chrom-ar/collector-js.git",
17
+ "directory": "packages/collector"
18
+ },
14
19
  "type": "module",
15
20
  "sideEffects": false,
16
21
  "main": "./dist/index.cjs",