@hullop/tlm 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-11-22)
4
+
5
+ - For apps without a bundler (Rails with importmap, plain
6
+ `<script type="module">`): `dist/tlm.esm.js` and `dist/rum.esm.js`, one
7
+ file each, without imports, minified, each starting with its license line.
8
+ - `Tlm.init()` takes `dsn`, `environment` and `release` from the page's
9
+ `<meta name="tlm-dsn">`, `tlm-environment` and `tlm-release` when they
10
+ aren't given, the user from `tlm-user` and the RUM route from `tlm-route`.
11
+ `rum()` without a `sampleRate` reads `tlm-rum-sample-rate`.
12
+ - Follows Turbo: each `turbo:load` reads `tlm-user` and `tlm-route` again
13
+ and counts as a navigation. A `tlm-user` that disappears clears the user.
14
+ - On pages with an importmap, libraries pinned in it aren't in-app frames.
15
+ `<meta name="tlm-in-app">` lists the app's own specifiers; without it,
16
+ scoped pins and pins whose file isn't named after them are libraries.
17
+ - `tlm.esm.js`'s own frames are never in-app.
18
+
3
19
  ## 0.1.0 (2026-11-22)
4
20
 
5
21
  First release.
package/README.md CHANGED
@@ -5,7 +5,7 @@ which groups them into issues, emails you when one is new or comes back,
5
5
  and shows you what broke and why.
6
6
 
7
7
  Works with any framework (React, Vue, Svelte, Angular, plain pages), has
8
- no dependencies and weighs about 6 KB gzipped.
8
+ no dependencies and weighs under 10 KB gzipped.
9
9
 
10
10
  ## Installation
11
11
 
@@ -92,6 +92,58 @@ network, and your Content-Security-Policy's connect-src." CSP violation reports
92
92
 
93
93
  - **Vue:** add `app.config.errorHandler = (error) => Tlm.captureException(error);`
94
94
 
95
+ ### Without a bundler (Rails, importmap)
96
+
97
+ The package ships two self-contained ES modules for pages that load
98
+ scripts as they are: `dist/tlm.esm.js` (the SDK) and `dist/rum.esm.js`
99
+ ([RUM](#page-speed-rum)). Neither imports anything, and each starts with
100
+ its license line, so you can copy them into your app as they are. With
101
+ importmap-rails, put them in `vendor/javascript` and pin them under the
102
+ package's names:
103
+
104
+ ```ruby
105
+ # config/importmap.rb
106
+ pin "@hullop/tlm", to: "tlm.esm.js"
107
+ pin "@hullop/tlm/rum", to: "rum.esm.js"
108
+ ```
109
+
110
+ Let the server render the settings into the layout's `<head>`, and call
111
+ `init()` with no DSN:
112
+
113
+ ```html
114
+ <meta name="tlm-dsn" content="https://tlm_…@tlm.hullop.com">
115
+ <meta name="tlm-environment" content="production">
116
+ <meta name="tlm-release" content="4b6c3f8">
117
+ <meta name="tlm-user" content="42">
118
+ <meta name="tlm-route" content="/orders/:id(.:format)">
119
+ <meta name="tlm-rum-sample-rate" content="0.1">
120
+ <meta name="tlm-in-app" content="application controllers/">
121
+ ```
122
+
123
+ ```js
124
+ import * as Tlm from "@hullop/tlm";
125
+ import { rum } from "@hullop/tlm/rum";
126
+
127
+ Tlm.init({ rum: rum() });
128
+ ```
129
+
130
+ - **What each tag sets:** `tlm-dsn`, `tlm-environment` and
131
+ `tlm-release` stand in for the `init()` options of the same names, and
132
+ options you pass win. `tlm-user` is the user's id (see
133
+ [Users and tags](#users-and-tags)). `tlm-route` names the page for RUM.
134
+ `rum()` without a `sampleRate` reads `tlm-rum-sample-rate`, and RUM
135
+ stays off without one. Missing or empty tags are left out.
136
+ - **Turbo:** on every `turbo:load`, the SDK reads `tlm-user` and
137
+ `tlm-route` again and counts the visit as a navigation. When
138
+ `tlm-user` is gone (the user signed out), the user is cleared. A user
139
+ you set with `setUser` is left alone.
140
+ - **Your code and your libraries:** everything an importmap app loads
141
+ comes from your own origin, so the SDK reads the page's
142
+ `<script type="importmap">` to tell them apart (see
143
+ [How errors are grouped](#how-errors-are-grouped)). `tlm-in-app` lists
144
+ the specifiers that are your own code, a trailing `/` covering a whole
145
+ directory. Every other pin is then a library.
146
+
95
147
  ## Checking your setup
96
148
 
97
149
  Send one test error and see what Tlm answered:
@@ -173,9 +225,9 @@ Tlm.setTag("plan", "pro");
173
225
 
174
226
  | Option | Default | |
175
227
  |---|---|---|
176
- | `dsn` | none | Your project's DSN. Without it, nothing is sent |
177
- | `environment` | none | e.g. `"production"`, `"staging"` |
178
- | `release` | none | Your app's version or git sha |
228
+ | `dsn` | `tlm-dsn` meta tag | Your project's DSN. Without it, nothing is sent |
229
+ | `environment` | `tlm-environment` meta tag | e.g. `"production"`, `"staging"` |
230
+ | `release` | `tlm-release` meta tag | Your app's version or git sha |
179
231
  | `debug` | `false` | Logs what the SDK does, prefixed `[tlm]` |
180
232
  | `enabled` | `true` | `false` turns everything off |
181
233
  | `beforeSend` | none | `(event) => event \| null`, to edit or drop events |
@@ -196,7 +248,7 @@ Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })
196
248
  Real User Monitoring shows how fast your pages are for the people using
197
249
  them: Web Vitals per page, the slow requests pages make, and single
198
250
  visits. It's off by default and ships as a separate import, so apps that
199
- don't use it don't download it (about 4.5 KB gzipped):
251
+ don't use it don't download it (under 5 KB gzipped):
200
252
 
201
253
  ```ts
202
254
  import * as Tlm from "@hullop/tlm";
@@ -206,7 +258,9 @@ Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
206
258
  ```
207
259
 
208
260
  - **Sampling:** `sampleRate` is the share of browser tabs measured,
209
- decided once per tab. A measured tab sends all its page views.
261
+ decided once per tab. A measured tab sends all its page views. Without
262
+ it, `rum()` reads `<meta name="tlm-rum-sample-rate">` and stays off when
263
+ there's none.
210
264
  - **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
211
265
  in-app navigations to a new path (pushState, LiveView; a new query
212
266
  string alone, like a filter or a search box, stays the same page view),
@@ -246,8 +300,17 @@ frame as your code when its script is on the page's own origin (or is a
246
300
  webpack dev module, `webpack-internal:///./src/…`) and
247
301
  isn't a dependency bundle (`node_modules`, `.vite/deps`, `vendor` chunks,
248
302
  Next.js framework chunks). Content hashes in file names are ignored, so
249
- a new deploy doesn't open new issues. If your scripts come from a CDN,
250
- say so:
303
+ a new deploy doesn't open new issues. The SDK's own `tlm.esm.js` is
304
+ never your code.
305
+
306
+ On pages with a `<script type="importmap">`, libraries pinned in it are
307
+ not your code either. With a `tlm-in-app` meta tag, that's every pin it
308
+ doesn't list. Without one, the SDK guesses: scoped pins
309
+ (`@hotwired/turbo-rails`) and pins whose file isn't named after them
310
+ (`turbo.min.js`) are libraries. A vendored `lodash` served as
311
+ `lodash-….js` looks like your own code until you add the tag.
312
+
313
+ If your scripts come from a CDN, say so:
251
314
 
252
315
  ```ts
253
316
  Tlm.init({ dsn: "…", inAppUrls: ["https://cdn.example.com/app/"] });
@@ -1,3 +1,9 @@
1
+ // src/meta.ts
2
+ function metaContent(doc, name) {
3
+ const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
4
+ return content === "" ? void 0 : content;
5
+ }
6
+
1
7
  // src/util.ts
2
8
  function uuid4() {
3
9
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
@@ -53,4 +59,4 @@ function rumUrl(base, url) {
53
59
  }
54
60
  }
55
61
 
56
- export { rumUrl, safeStringify, stripUrl, truncate, uuid4 };
62
+ export { metaContent, rumUrl, safeStringify, stripUrl, truncate, uuid4 };
package/dist/index.cjs CHANGED
@@ -154,7 +154,7 @@ function toFrames(raw, opts) {
154
154
  }
155
155
  return frames;
156
156
  }
157
- function toFrame(raw, { origin, inAppUrls }) {
157
+ function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
158
158
  let url;
159
159
  try {
160
160
  url = new URL(raw.url, origin);
@@ -165,7 +165,10 @@ function toFrame(raw, { origin, inAppUrls }) {
165
165
  const sameOrigin = url?.origin === origin || webpackInternal;
166
166
  let file = stripUrl(raw.url);
167
167
  if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
168
- const inApp = inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file));
168
+ const absolute = url ? stripUrl(url.href) : void 0;
169
+ const own = absolute !== void 0 && absolute === ownUrl;
170
+ const dependency = absolute !== void 0 && isDependency?.(absolute) === true;
171
+ const inApp = !own && (inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file)) && !dependency);
169
172
  const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
170
173
  if (raw.line !== void 0) frame.line = raw.line;
171
174
  if (raw.column !== void 0) frame.column = raw.column;
@@ -195,7 +198,7 @@ function errorType(error) {
195
198
  function eventFromException(error, env, ctx, mechanism = "manual") {
196
199
  const event = baseEvent(env, ctx);
197
200
  if (isErrorLike(error)) {
198
- const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
201
+ const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, isDependency: env.isDependency, ownUrl: env.ownUrl }) : [];
199
202
  event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
200
203
  if (frames.length > 0) event.exception.frames = frames;
201
204
  } else {
@@ -229,7 +232,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
229
232
  platform: "javascript",
230
233
  level: toLevel(ctx.level),
231
234
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
232
- sdk: { name: SDK_NAME, version: "0.1.0" }
235
+ sdk: { name: SDK_NAME, version: "0.2.0" }
233
236
  };
234
237
  const environment = environmentOf(options);
235
238
  if (environment !== void 0) event.environment = environment;
@@ -359,7 +362,7 @@ async function beat({ url, key, fetch, options, logger }) {
359
362
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
360
363
  let status;
361
364
  try {
362
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.1.0" }, environment, release });
365
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.2.0" }, environment, release });
363
366
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
364
367
  ({ status } = response);
365
368
  } catch (error) {
@@ -374,6 +377,56 @@ async function beat({ url, key, fetch, options, logger }) {
374
377
  }
375
378
  }
376
379
 
380
+ // src/meta.ts
381
+ function metaContent(doc, name) {
382
+ const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
383
+ return content === "" ? void 0 : content;
384
+ }
385
+
386
+ // src/importmap.ts
387
+ var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
388
+ function pinsOf(doc, base) {
389
+ const pins = [];
390
+ for (const script of doc.querySelectorAll('script[type="importmap"]')) {
391
+ let map;
392
+ try {
393
+ map = JSON.parse(script.textContent);
394
+ } catch {
395
+ continue;
396
+ }
397
+ const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
398
+ if (typeof imports !== "object" || imports === null) continue;
399
+ for (const [specifier, target] of Object.entries(imports)) {
400
+ if (!isBare(specifier) || typeof target !== "string") continue;
401
+ try {
402
+ pins.push({ specifier, url: stripUrl(new URL(target, base).href) });
403
+ } catch {
404
+ }
405
+ }
406
+ }
407
+ return pins;
408
+ }
409
+ function namedAfterPin({ specifier, url }) {
410
+ const name = specifier.replace(/\/$/, "");
411
+ const path = normalizeModule(new URL(url).pathname).replace(/\.m?js$/, "").replace(/\/$/, "");
412
+ return path.endsWith(`/${name}`) || path.endsWith(`/${name}/index`);
413
+ }
414
+ function listedIn(inApp, specifier) {
415
+ return inApp.some((entry) => entry.endsWith("/") ? specifier.startsWith(entry) || specifier === entry.slice(0, -1) : specifier === entry);
416
+ }
417
+ function importmapDependencies(doc, base) {
418
+ const inApp = metaContent(doc, "in-app")?.split(/\s+/);
419
+ const isDependency = (pin) => inApp ? !listedIn(inApp, pin.specifier) : pin.specifier.startsWith("@") || !namedAfterPin(pin);
420
+ const exact = /* @__PURE__ */ new Set();
421
+ const prefixes = [];
422
+ for (const pin of pinsOf(doc, base)) {
423
+ if (!isDependency(pin)) continue;
424
+ if (pin.specifier.endsWith("/")) prefixes.push(pin.url);
425
+ else exact.add(pin.url);
426
+ }
427
+ return (url) => exact.has(url) || prefixes.some((prefix) => url.startsWith(prefix));
428
+ }
429
+
377
430
  // src/describe.ts
378
431
  var MAX_KEYS = 10;
379
432
  var MAX_STRING = 100;
@@ -907,6 +960,7 @@ var INSTRUMENTS = {
907
960
  history: instrumentHistory
908
961
  };
909
962
  var DEFAULT_MAX_BREADCRUMBS = 50;
963
+ var OWN_URL = void 0;
910
964
  var TEST_TIMEOUT_MS = 1e4;
911
965
  function testFailure(result) {
912
966
  if ("error" in result) {
@@ -962,7 +1016,7 @@ var Client = class {
962
1016
  }
963
1017
  if (typeof options.dsn !== "string" || options.dsn === "") {
964
1018
  this.logger.debug("no DSN given: nothing will be sent");
965
- this.inactive = "no DSN given to init().";
1019
+ this.inactive = `no DSN given to init() or in <meta name="tlm-dsn">.`;
966
1020
  return;
967
1021
  }
968
1022
  const endpoint = parseDsn(options.dsn);
@@ -993,7 +1047,7 @@ var Client = class {
993
1047
  }
994
1048
  if (options.rum && !this.transport.disabled) {
995
1049
  try {
996
- this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.1.0" }, environment: environmentOf(options), release: releaseOf(options) });
1050
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.2.0" }, environment: environmentOf(options), release: releaseOf(options) });
997
1051
  } catch (error) {
998
1052
  this.logger.debug("RUM didn't start", error);
999
1053
  }
@@ -1008,6 +1062,16 @@ var Client = class {
1008
1062
  this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
1009
1063
  }
1010
1064
  }
1065
+ this.isDependency = importmapDependencies(win.document, win.location.href);
1066
+ this.followMeta();
1067
+ const onTurboLoad = () => {
1068
+ this.rum?.navigate();
1069
+ this.followMeta();
1070
+ };
1071
+ win.document.addEventListener("turbo:load", onTurboLoad);
1072
+ this.cleanups.push(() => {
1073
+ win.document.removeEventListener("turbo:load", onTurboLoad);
1074
+ });
1011
1075
  const onPageHide = () => {
1012
1076
  this.transport?.sendQueuedNow();
1013
1077
  };
@@ -1108,6 +1172,16 @@ var Client = class {
1108
1172
  }
1109
1173
  }
1110
1174
  }
1175
+ /** The page's user and route from its meta tags. A user the app set itself is left alone. */
1176
+ followMeta() {
1177
+ const doc = this.win.document;
1178
+ const user = metaContent(doc, "user");
1179
+ const current = this.scope.user?.id;
1180
+ if (current === void 0 || current === this.metaUser) this.scope.setUser(user === void 0 ? null : { id: user });
1181
+ this.metaUser = user;
1182
+ const route = metaContent(doc, "route");
1183
+ if (route !== void 0) this.setRoute(route);
1184
+ }
1111
1185
  env() {
1112
1186
  const { win } = this;
1113
1187
  return {
@@ -1116,7 +1190,9 @@ var Client = class {
1116
1190
  origin: win.location.origin,
1117
1191
  href: win.location.href,
1118
1192
  userAgent: win.navigator.userAgent,
1119
- session: this.rum?.session
1193
+ session: this.rum?.session,
1194
+ isDependency: this.isDependency,
1195
+ ownUrl: OWN_URL
1120
1196
  };
1121
1197
  }
1122
1198
  capture(build) {
@@ -1162,7 +1238,7 @@ var Client = class {
1162
1238
  };
1163
1239
 
1164
1240
  // src/index.ts
1165
- var SDK_VERSION = "0.1.0";
1241
+ var SDK_VERSION = "0.2.0";
1166
1242
  var client;
1167
1243
  var pendingRoute;
1168
1244
  var pendingScope = new Scope();
@@ -1177,12 +1253,20 @@ function safely(fn, fallback) {
1177
1253
  return fallback;
1178
1254
  }
1179
1255
  }
1180
- function init(options) {
1256
+ function withMeta(options, doc) {
1257
+ return {
1258
+ ...options,
1259
+ dsn: options.dsn ?? metaContent(doc, "dsn"),
1260
+ environment: options.environment ?? metaContent(doc, "environment"),
1261
+ release: options.release ?? metaContent(doc, "release")
1262
+ };
1263
+ }
1264
+ function init(options = {}) {
1181
1265
  safely(() => {
1182
1266
  if (typeof window === "undefined") return;
1183
1267
  const kept = scope();
1184
1268
  client?.close();
1185
- client = new Client(options, window, kept);
1269
+ client = new Client(withMeta(options, window.document), window, kept);
1186
1270
  if (pendingRoute) client.setRoute(pendingRoute.name);
1187
1271
  pendingRoute = void 0;
1188
1272
  if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-CmaNTQav.cjs';
2
- export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-CmaNTQav.cjs';
1
+ import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-BluGo23D.cjs';
2
+ export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-BluGo23D.cjs';
3
3
 
4
4
  /** The version of this SDK, as sent in every event's `sdk.version`. */
5
5
  declare const SDK_VERSION: string;
@@ -13,10 +13,13 @@ declare const SDK_VERSION: string;
13
13
  * Tlm.init({ dsn: "https://tlm_…@tlm.hullop.com" });
14
14
  * ```
15
15
  *
16
- * Without a `dsn`, nothing is captured or sent. Calling it again replaces the
17
- * options. Safe to import during server-side rendering: it does nothing there.
16
+ * Options not given are read from the page's meta tags (`tlm-dsn`,
17
+ * `tlm-environment`, `tlm-release`), so a server-rendered page can call a
18
+ * bare `Tlm.init()`. Without a DSN, nothing is captured or sent. Calling it
19
+ * again replaces the options. Safe to import during server-side rendering:
20
+ * it does nothing there.
18
21
  */
19
- declare function init(options: TlmOptions): void;
22
+ declare function init(options?: TlmOptions): void;
20
23
  /**
21
24
  * Sends one test error, to check your setup end to end. Resolves to
22
25
  * `{ ok: true, id }` once Tlm accepts it, or `{ ok: false, reason }`,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-CmaNTQav.js';
2
- export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-CmaNTQav.js';
1
+ import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-BluGo23D.js';
2
+ export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-BluGo23D.js';
3
3
 
4
4
  /** The version of this SDK, as sent in every event's `sdk.version`. */
5
5
  declare const SDK_VERSION: string;
@@ -13,10 +13,13 @@ declare const SDK_VERSION: string;
13
13
  * Tlm.init({ dsn: "https://tlm_…@tlm.hullop.com" });
14
14
  * ```
15
15
  *
16
- * Without a `dsn`, nothing is captured or sent. Calling it again replaces the
17
- * options. Safe to import during server-side rendering: it does nothing there.
16
+ * Options not given are read from the page's meta tags (`tlm-dsn`,
17
+ * `tlm-environment`, `tlm-release`), so a server-rendered page can call a
18
+ * bare `Tlm.init()`. Without a DSN, nothing is captured or sent. Calling it
19
+ * again replaces the options. Safe to import during server-side rendering:
20
+ * it does nothing there.
18
21
  */
19
- declare function init(options: TlmOptions): void;
22
+ declare function init(options?: TlmOptions): void;
20
23
  /**
21
24
  * Sends one test error, to check your setup end to end. Resolves to
22
25
  * `{ ok: true, id }` once Tlm accepts it, or `{ ok: false, reason }`,
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-YN5N3X7X.js';
1
+ import { metaContent, truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-ECMQ35KU.js';
2
2
 
3
3
  // src/dsn.ts
4
4
  function parseDsn(dsn) {
@@ -99,7 +99,7 @@ function toFrames(raw, opts) {
99
99
  }
100
100
  return frames;
101
101
  }
102
- function toFrame(raw, { origin, inAppUrls }) {
102
+ function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
103
103
  let url;
104
104
  try {
105
105
  url = new URL(raw.url, origin);
@@ -110,7 +110,10 @@ function toFrame(raw, { origin, inAppUrls }) {
110
110
  const sameOrigin = url?.origin === origin || webpackInternal;
111
111
  let file = stripUrl(raw.url);
112
112
  if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
113
- const inApp = inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file));
113
+ const absolute = url ? stripUrl(url.href) : void 0;
114
+ const own = absolute !== void 0 && absolute === ownUrl;
115
+ const dependency = absolute !== void 0 && isDependency?.(absolute) === true;
116
+ const inApp = !own && (inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file)) && !dependency);
114
117
  const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
115
118
  if (raw.line !== void 0) frame.line = raw.line;
116
119
  if (raw.column !== void 0) frame.column = raw.column;
@@ -140,7 +143,7 @@ function errorType(error) {
140
143
  function eventFromException(error, env, ctx, mechanism = "manual") {
141
144
  const event = baseEvent(env, ctx);
142
145
  if (isErrorLike(error)) {
143
- const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
146
+ const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, isDependency: env.isDependency, ownUrl: env.ownUrl }) : [];
144
147
  event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
145
148
  if (frames.length > 0) event.exception.frames = frames;
146
149
  } else {
@@ -174,7 +177,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
174
177
  platform: "javascript",
175
178
  level: toLevel(ctx.level),
176
179
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
177
- sdk: { name: SDK_NAME, version: "0.1.0" }
180
+ sdk: { name: SDK_NAME, version: "0.2.0" }
178
181
  };
179
182
  const environment = environmentOf(options);
180
183
  if (environment !== void 0) event.environment = environment;
@@ -304,7 +307,7 @@ async function beat({ url, key, fetch, options, logger }) {
304
307
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
305
308
  let status;
306
309
  try {
307
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.1.0" }, environment, release });
310
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.2.0" }, environment, release });
308
311
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
309
312
  ({ status } = response);
310
313
  } catch (error) {
@@ -319,6 +322,50 @@ async function beat({ url, key, fetch, options, logger }) {
319
322
  }
320
323
  }
321
324
 
325
+ // src/importmap.ts
326
+ var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
327
+ function pinsOf(doc, base) {
328
+ const pins = [];
329
+ for (const script of doc.querySelectorAll('script[type="importmap"]')) {
330
+ let map;
331
+ try {
332
+ map = JSON.parse(script.textContent);
333
+ } catch {
334
+ continue;
335
+ }
336
+ const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
337
+ if (typeof imports !== "object" || imports === null) continue;
338
+ for (const [specifier, target] of Object.entries(imports)) {
339
+ if (!isBare(specifier) || typeof target !== "string") continue;
340
+ try {
341
+ pins.push({ specifier, url: stripUrl(new URL(target, base).href) });
342
+ } catch {
343
+ }
344
+ }
345
+ }
346
+ return pins;
347
+ }
348
+ function namedAfterPin({ specifier, url }) {
349
+ const name = specifier.replace(/\/$/, "");
350
+ const path = normalizeModule(new URL(url).pathname).replace(/\.m?js$/, "").replace(/\/$/, "");
351
+ return path.endsWith(`/${name}`) || path.endsWith(`/${name}/index`);
352
+ }
353
+ function listedIn(inApp, specifier) {
354
+ return inApp.some((entry) => entry.endsWith("/") ? specifier.startsWith(entry) || specifier === entry.slice(0, -1) : specifier === entry);
355
+ }
356
+ function importmapDependencies(doc, base) {
357
+ const inApp = metaContent(doc, "in-app")?.split(/\s+/);
358
+ const isDependency = (pin) => inApp ? !listedIn(inApp, pin.specifier) : pin.specifier.startsWith("@") || !namedAfterPin(pin);
359
+ const exact = /* @__PURE__ */ new Set();
360
+ const prefixes = [];
361
+ for (const pin of pinsOf(doc, base)) {
362
+ if (!isDependency(pin)) continue;
363
+ if (pin.specifier.endsWith("/")) prefixes.push(pin.url);
364
+ else exact.add(pin.url);
365
+ }
366
+ return (url) => exact.has(url) || prefixes.some((prefix) => url.startsWith(prefix));
367
+ }
368
+
322
369
  // src/describe.ts
323
370
  var MAX_KEYS = 10;
324
371
  var MAX_STRING = 100;
@@ -852,6 +899,7 @@ var INSTRUMENTS = {
852
899
  history: instrumentHistory
853
900
  };
854
901
  var DEFAULT_MAX_BREADCRUMBS = 50;
902
+ var OWN_URL = void 0;
855
903
  var TEST_TIMEOUT_MS = 1e4;
856
904
  function testFailure(result) {
857
905
  if ("error" in result) {
@@ -907,7 +955,7 @@ var Client = class {
907
955
  }
908
956
  if (typeof options.dsn !== "string" || options.dsn === "") {
909
957
  this.logger.debug("no DSN given: nothing will be sent");
910
- this.inactive = "no DSN given to init().";
958
+ this.inactive = `no DSN given to init() or in <meta name="tlm-dsn">.`;
911
959
  return;
912
960
  }
913
961
  const endpoint = parseDsn(options.dsn);
@@ -938,7 +986,7 @@ var Client = class {
938
986
  }
939
987
  if (options.rum && !this.transport.disabled) {
940
988
  try {
941
- this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.1.0" }, environment: environmentOf(options), release: releaseOf(options) });
989
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.2.0" }, environment: environmentOf(options), release: releaseOf(options) });
942
990
  } catch (error) {
943
991
  this.logger.debug("RUM didn't start", error);
944
992
  }
@@ -953,6 +1001,16 @@ var Client = class {
953
1001
  this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
954
1002
  }
955
1003
  }
1004
+ this.isDependency = importmapDependencies(win.document, win.location.href);
1005
+ this.followMeta();
1006
+ const onTurboLoad = () => {
1007
+ this.rum?.navigate();
1008
+ this.followMeta();
1009
+ };
1010
+ win.document.addEventListener("turbo:load", onTurboLoad);
1011
+ this.cleanups.push(() => {
1012
+ win.document.removeEventListener("turbo:load", onTurboLoad);
1013
+ });
956
1014
  const onPageHide = () => {
957
1015
  this.transport?.sendQueuedNow();
958
1016
  };
@@ -1053,6 +1111,16 @@ var Client = class {
1053
1111
  }
1054
1112
  }
1055
1113
  }
1114
+ /** The page's user and route from its meta tags. A user the app set itself is left alone. */
1115
+ followMeta() {
1116
+ const doc = this.win.document;
1117
+ const user = metaContent(doc, "user");
1118
+ const current = this.scope.user?.id;
1119
+ if (current === void 0 || current === this.metaUser) this.scope.setUser(user === void 0 ? null : { id: user });
1120
+ this.metaUser = user;
1121
+ const route = metaContent(doc, "route");
1122
+ if (route !== void 0) this.setRoute(route);
1123
+ }
1056
1124
  env() {
1057
1125
  const { win } = this;
1058
1126
  return {
@@ -1061,7 +1129,9 @@ var Client = class {
1061
1129
  origin: win.location.origin,
1062
1130
  href: win.location.href,
1063
1131
  userAgent: win.navigator.userAgent,
1064
- session: this.rum?.session
1132
+ session: this.rum?.session,
1133
+ isDependency: this.isDependency,
1134
+ ownUrl: OWN_URL
1065
1135
  };
1066
1136
  }
1067
1137
  capture(build) {
@@ -1107,7 +1177,7 @@ var Client = class {
1107
1177
  };
1108
1178
 
1109
1179
  // src/index.ts
1110
- var SDK_VERSION = "0.1.0";
1180
+ var SDK_VERSION = "0.2.0";
1111
1181
  var client;
1112
1182
  var pendingRoute;
1113
1183
  var pendingScope = new Scope();
@@ -1122,12 +1192,20 @@ function safely(fn, fallback) {
1122
1192
  return fallback;
1123
1193
  }
1124
1194
  }
1125
- function init(options) {
1195
+ function withMeta(options, doc) {
1196
+ return {
1197
+ ...options,
1198
+ dsn: options.dsn ?? metaContent(doc, "dsn"),
1199
+ environment: options.environment ?? metaContent(doc, "environment"),
1200
+ release: options.release ?? metaContent(doc, "release")
1201
+ };
1202
+ }
1203
+ function init(options = {}) {
1126
1204
  safely(() => {
1127
1205
  if (typeof window === "undefined") return;
1128
1206
  const kept = scope();
1129
1207
  client?.close();
1130
- client = new Client(options, window, kept);
1208
+ client = new Client(withMeta(options, window.document), window, kept);
1131
1209
  if (pendingRoute) client.setRoute(pendingRoute.name);
1132
1210
  pendingRoute = void 0;
1133
1211
  if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
package/dist/rum.cjs CHANGED
@@ -1,5 +1,11 @@
1
1
  'use strict';
2
2
 
3
+ // src/meta.ts
4
+ function metaContent(doc, name) {
5
+ const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
6
+ return content === "" ? void 0 : content;
7
+ }
8
+
3
9
  // src/util.ts
4
10
  function uuid4() {
5
11
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
@@ -517,11 +523,12 @@ function observeVitals() {
517
523
  var SEND_EVERY = 10;
518
524
  var SEND_INTERVAL_MS = 5 * 6e4;
519
525
  var load;
520
- function rum(options) {
526
+ function rum(options = {}) {
521
527
  return { start: (ctx) => start(ctx, options) };
522
528
  }
523
529
  function start(ctx, options) {
524
- const { id, sampled } = sessionFor(options.sampleRate);
530
+ const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? 0);
531
+ const { id, sampled } = sessionFor(sampleRate);
525
532
  if (!sampled) {
526
533
  ctx.logger.debug("RUM: this tab wasn't sampled");
527
534
  const nothing = () => void 0;
@@ -538,7 +545,7 @@ function start(ctx, options) {
538
545
  logger: ctx.logger,
539
546
  sdk: ctx.sdk,
540
547
  session: id,
541
- sampleRate: options.sampleRate,
548
+ sampleRate,
542
549
  environment: ctx.environment,
543
550
  release: ctx.release,
544
551
  beforeSendPageview: options.beforeSendPageview
package/dist/rum.d.cts CHANGED
@@ -34,8 +34,12 @@ interface PageView {
34
34
  }
35
35
 
36
36
  interface RumOptions {
37
- /** Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start. */
38
- sampleRate: number;
37
+ /**
38
+ * Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
39
+ * `0.1` is a good start. Default: the page's
40
+ * `<meta name="tlm-rum-sample-rate">`, or no RUM without one.
41
+ */
42
+ sampleRate?: number;
39
43
  /** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
40
44
  route?: (location: Location) => string | undefined;
41
45
  /** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
@@ -50,8 +54,10 @@ interface RumOptions {
50
54
  *
51
55
  * Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
52
56
  * ```
57
+ *
58
+ * Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`.
53
59
  */
54
- declare function rum(options: RumOptions): RumPlugin;
60
+ declare function rum(options?: RumOptions): RumPlugin;
55
61
 
56
62
  export { rum };
57
63
  export type { PageView, RumOptions };
package/dist/rum.d.ts CHANGED
@@ -34,8 +34,12 @@ interface PageView {
34
34
  }
35
35
 
36
36
  interface RumOptions {
37
- /** Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start. */
38
- sampleRate: number;
37
+ /**
38
+ * Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
39
+ * `0.1` is a good start. Default: the page's
40
+ * `<meta name="tlm-rum-sample-rate">`, or no RUM without one.
41
+ */
42
+ sampleRate?: number;
39
43
  /** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
40
44
  route?: (location: Location) => string | undefined;
41
45
  /** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
@@ -50,8 +54,10 @@ interface RumOptions {
50
54
  *
51
55
  * Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
52
56
  * ```
57
+ *
58
+ * Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`.
53
59
  */
54
- declare function rum(options: RumOptions): RumPlugin;
60
+ declare function rum(options?: RumOptions): RumPlugin;
55
61
 
56
62
  export { rum };
57
63
  export type { PageView, RumOptions };
@@ -0,0 +1,2 @@
1
+ /*! @hullop/tlm/rum 0.2.0 | MIT */
2
+ function N(i,e){let t=i.querySelector(`meta[name="tlm-${e}"]`)?.getAttribute("content")?.trim();return t===""?void 0:t}function R(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let i=crypto.getRandomValues(new Uint8Array(16));i[6]=(i[6]??0)&15|64,i[8]=(i[8]??0)&63|128;let e=Array.from(i,t=>t.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function O(i){let e=i.search(/[?#]/);return e===-1?i:i.slice(0,e)}var K=500;function B(i,e){try{let t=new URL(e,i);return t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(t.origin+t.pathname).slice(0,K)}catch{return}}var D=500,z=1e4,G=1e3,Q=50,Y=30,H=300,x={lcp:4e3,inp:500,nav:2500},_=()=>location.pathname,E=class{constructor(e){this.options=e;this.finished=[];this.lastKey=_();this.lastClick=-1/0;this.closed=false;this.resources=[];this.cleanups=[];e.first&&(this.current=this.begin("hard",0),e.hardId!==void 0&&(this.current.id=e.hardId));let t=()=>{this.lastClick=performance.now();},o=n=>{n.persisted&&this.next(performance.now());};document.addEventListener("click",t,true),window.addEventListener("pageshow",o),this.cleanups.push(()=>{document.removeEventListener("click",t,true),window.removeEventListener("pageshow",o);});try{if(typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("resource")){let n=new PerformanceObserver(r=>{for(let l of r.getEntries())this.resources.push({name:l.name,type:l.initiatorType,start:l.startTime,duration:l.duration,size:l.transferSize});this.resources.length>H&&this.resources.splice(0,this.resources.length-H);});n.observe({type:"resource",buffered:!0}),this.cleanups.push(()=>{n.disconnect();});}}catch{}}navigate(){if(this.closed||_()===this.lastKey)return;let e=performance.now(),t=this.lastClick>=(this.current?.start??-1/0)&&e-this.lastClick<=G?this.lastClick:e;this.lastClick=-1/0,this.next(t);}requestStart(){return this.current&&(this.current.pending+=1),this.current}request(e,t){let o=[this.current,...this.finished].filter(r=>r!==void 0),n=t===void 0?o.filter(r=>r.start<=e.start).sort((r,l)=>l.start-r.start)[0]:o.find(r=>r===t);n&&(n.pending=Math.max(0,n.pending-1),n.requests.length<Q&&n.requests.push(e),n===this.current&&this.settle?.());}setRoute(e){this.current&&(this.current.route=e===void 0?void 0:O(e));}currentId(){return this.current?.id}finishedCount(){return this.finished.length}takeFinished(){let e=this.finished.splice(0).map(t=>this.toPageView(t));return e.length>0&&this.current&&this.options.vitals()?.prune(this.current.start),e}snapshot(){return [...this.finished,...this.current?[this.current]:[]].map(t=>this.toPageView(t))}close(){this.closed=true,this.settle=void 0;for(let e of this.cleanups.splice(0))e();}next(e){this.closed||(this.current&&(this.current.end=e,this.finished.push(this.current)),this.current=this.begin("soft",e),this.watch(this.current));}begin(e,t){this.lastKey=_();let o;try{o=this.options.route?.(location);}catch{}return {id:R(),key:this.lastKey,path:location.pathname,navigation:e,start:t,route:o===void 0?void 0:O(o),requests:[],pending:0}}watch(e){this.settle?.();let t=e.start,o,n,r=s=>{clearTimeout(o),clearTimeout(h),n?.disconnect(),this.settle===a&&(this.settle=void 0),e.nav=Math.round(s);},l=()=>{e.pending===0&&r(t-e.start);},a=()=>{t=performance.now(),clearTimeout(o),o=setTimeout(l,D);},h=setTimeout(()=>{r(z);},z);try{n=new MutationObserver(a),n.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});}catch{}this.settle=()=>{if(e!==this.current||this.closed){clearTimeout(o),clearTimeout(h),n?.disconnect();return}a();},o=setTimeout(l,D);}toPageView(e){let t=this.options.vitals(),o=e.end??performance.now(),n={...e.navigation==="hard"?t?.hard():{},...t?.span(e.start,o),...e.nav===void 0?{}:{nav:e.nav}},r={id:e.id,at:new Date(performance.timeOrigin+e.start).toISOString(),path:e.path,navigation:e.navigation};if(e.route!==void 0&&e.route!==""&&(r.route=e.route),Object.keys(n).length>0&&(r.vitals=n),e.requests.length>0&&(r.requests=e.requests.map(a=>({method:a.method,url:a.url,status:a.status,start:Math.max(0,Math.round(a.start-e.start)),duration:Math.round(a.end-a.start)}))),(n.lcp??0)>x.lcp||(n.inp??0)>x.inp||(n.nav??0)>x.nav){let h=this.resources.flatMap(s=>{let p=B(location.href,s.name),g=s.start>=e.start&&(e.end===void 0||s.start<e.end);return p!==void 0&&g&&!this.options.own(s.name)?[{...s,name:p}]:[]}).sort((s,p)=>p.duration-s.duration).slice(0,Y);h.length>0&&(r.waterfall=h.map(s=>({name:s.name,type:s.type,start:Math.round(s.start-e.start),duration:Math.round(s.duration),...s.size>0?{size:s.size}:{}})));}return r}};var A="text/plain;charset=UTF-8",Z=new TextEncoder,ee=i=>Z.encode(i).length,V=class{constructor(e){this.options=e;this.stopped=false;this.pausedUntil=0;this.compressing=new Set;this.sent=new Map;}undispatched(){return [...this.compressing].flatMap(e=>e.pageviews)}async send(e,t){if(this.stopped||Date.now()<this.pausedUntil)return;let o=e.flatMap(r=>this.prepare(r)).filter(r=>this.sent.get(r.id)!==JSON.stringify(r)),n=this.batches(o);if(t!=="visible"&&(n=te(n,48e3,this.options.logger)),t==="pagehide"){for(let r of n)this.unload(r);return}if(t==="hidden"){await Promise.all(n.map(async r=>this.post(r,t)));return}for(let r of n)await this.post(r,t);}prepare(e){let t=this.options.beforeSendPageview;if(!t)return [e];let o;try{o=t(e);}catch(n){return this.options.logger.debug("beforeSendPageview threw; sending the page view unchanged",n),[e]}return o===null?[]:typeof o=="object"&&"then"in o?(this.options.logger.warnOnce("beforeSendPageview returned a Promise, so the page view was dropped. It must return the page view (or null) right away, not async."),[]):[o]}batches(e){let{sdk:t,environment:o,release:n,session:r,sampleRate:l}=this.options,a=p=>{let g=JSON.stringify({v:1,sdk:t,environment:o,release:n,session:r,sample_rate:l,pageviews:p});return {body:g,pageviews:p,bytes:ee(g)}},h=[],s=[];for(let p of e){if(a([...s,p]).bytes<=32e3){s.push(p);continue}s.length>0&&h.push(a(s)),s=[p],a(s).bytes>32e3&&(this.options.logger.debug("dropped a page view that is too big to send",p.id),s=[]);}return s.length>0&&h.push(a(s)),h}dispatched(e){for(let t of e.pageviews)this.sent.delete(t.id),this.sent.set(t.id,JSON.stringify(t));for(let t of [...this.sent.keys()].slice(0,Math.max(0,this.sent.size-200)))this.sent.delete(t);}unload(e){this.dispatched(e);let t=false;try{t=navigator.sendBeacon(this.options.url,new Blob([e.body],{type:A}));}catch{}if(!t)try{this.options.fetch(this.options.url,{method:"POST",body:e.body,headers:{"Content-Type":A},keepalive:!0,credentials:"omit"}).catch(()=>{});}catch{}}async post(e,t){let{url:o,fetch:n,logger:r}=this.options,l={"Content-Type":A},a=e.body;if(e.bytes>1024&&typeof CompressionStream=="function"){this.compressing.add(e);try{a=await ne(e.body),l["Content-Encoding"]="gzip";}catch{a=e.body;}finally{this.compressing.delete(e);}}this.dispatched(e);let h;try{h=await n(o,{method:"POST",body:a,headers:l,keepalive:!0,credentials:"omit"});}catch(p){t==="hidden"?this.unload(e):r.debug("page views not sent",p);return}let{status:s}=h;if(s===401||s===403||s===404)this.stopped=true,r.debug(`Tlm turned RUM down (HTTP ${String(s)}): no more page views from this page`);else if(s===429){let p=Number.parseInt(h.headers.get("Retry-After")??"",10);this.pausedUntil=Date.now()+(p>=0?p:60)*1e3;}else (s<200||s>=300)&&r.debug(`page views dropped (HTTP ${String(s)})`);}};function te(i,e,t){let o=[],n=0;for(let r of [...i].reverse()){if(n+r.bytes>e){t.debug("an unloading page can't send this much; dropped the oldest page views");break}n+=r.bytes,o.unshift(r);}return o}async function ne(i){let e=new Response(i).body;if(!e)throw new Error("no stream");return new Response(e.pipeThrough(new CompressionStream("gzip"))).arrayBuffer()}var F="tlm:rum",$;function ie(){let i;try{i=sessionStorage.getItem(F);}catch{return $}if(i!==null)try{let e=JSON.parse(i);if(typeof e=="object"&&e!==null&&"session"in e&&"rate"in e&&"sampled"in e){let{session:t,rate:o,sampled:n}=e;if(typeof t=="string"&&typeof o=="number"&&typeof n=="boolean")return {session:t,rate:o,sampled:n}}}catch{}}function W(i,e=Math.random){let t=ie();if(t?.rate===i)return {id:t.session,sampled:t.sampled};let o=i>0&&i<=1,n={session:R(),rate:i,sampled:o&&e()<i};$=n;try{sessionStorage.setItem(F,JSON.stringify(n));}catch{}return {id:n.session,sampled:n.sampled}}function k(i,e){let t=i===void 0?void 0:Reflect.get(i,e);return typeof t=="number"?t:void 0}var re=1e3,se=5e3;function X(){let i=performance.getEntriesByType("navigation")[0],e=k(i,"activationStart")??0,t=k(i,"responseStart"),o=t===void 0?void 0:Math.max(0,t-e),n=document.visibilityState==="hidden"&&Reflect.get(document,"prerendering")!==true?0:1/0,r=1/0,l,a,h=[],s=[],p=()=>{document.visibilityState==="hidden"&&(n=Math.min(n,performance.now()));};document.addEventListener("visibilitychange",p,true);let g=[],v=(d,u,f)=>{try{if(typeof PerformanceObserver>"u"||!PerformanceObserver.supportedEntryTypes.includes(d))return;let c=new PerformanceObserver(m=>{try{u(m.getEntries());}catch{}});c.observe({type:d,buffered:!0,...f}),g.push(c);}catch{}},w=d=>{for(let u of d){let f=k(u,"interactionId")??0;f>0&&s.length<5e3&&s.push({id:f,t:u.startTime,d:u.duration});}};v("first-input",d=>{for(let u of d)r=Math.min(r,u.startTime);w(d);}),v("paint",d=>{for(let u of d)u.name==="first-contentful-paint"&&u.startTime<n&&(a=u.startTime);}),v("largest-contentful-paint",d=>{for(let u of d)u.startTime<Math.min(n,r)&&(l=u.startTime);}),v("layout-shift",d=>{for(let u of d){let f=k(u,"value");f!==void 0&&Reflect.get(u,"hadRecentInput")!==!0&&h.length<5e3&&h.push({t:u.startTime,v:f});}}),v("event",w,{durationThreshold:16});let S=d=>d===void 0?void 0:Math.round(Math.max(0,d-e)),T=(d,u)=>f=>f.t>=d&&f.t<u;return {hard(){let d={},u=S(l),f=S(a);return u!==void 0&&(d.lcp=u),f!==void 0&&(d.fcp=f),o!==void 0&&(d.ttfb=Math.round(o)),d},span(d,u){let f={},c=0,m=0,M=-1/0,C=-1/0,U=false;for(let{t:b,v:P}of h.filter(T(d,u)).sort((j,J)=>j.t-J.t))U=true,(b-C>re||b-M>=se)&&(M=b,m=0),m+=P,C=b,c=Math.max(c,m);U&&(f.cls=c);let I=new Map;for(let{id:b,d:P}of s.filter(T(d,u)))I.set(b,Math.max(I.get(b)??0,P));let L=[...I.values()].sort((b,P)=>P-b),q=L[Math.min(L.length-1,Math.floor(L.length/50))];return q!==void 0&&(f.inp=Math.round(q)),f},prune(d){let u=f=>{let c=f.filter(m=>m.t>=d);f.splice(0,f.length,...c);};u(h),u(s);},stop(){for(let d of g)d.disconnect();document.removeEventListener("visibilitychange",p,true);}}}var oe=10,ae=5*6e4,y;function Te(i={}){return {start:e=>de(e,i)}}function de(i,e){let t=e.sampleRate??Number(N(i.win.document,"rum-sample-rate")??0),{id:o,sampled:n}=W(t);if(!n){i.logger.debug("RUM: this tab wasn't sampled");let c=()=>{};return {session:void 0,requestStart:c,request:c,navigate:c,setRoute:c,close:c}}let r=i.url.slice(0,i.url.indexOf("/api/pageviews")),l=X(),a=new E({vitals:()=>l,route:e.route,own:c=>c.startsWith(`${r}/`),first:y?.open??true,hardId:y?.id}),h=a.currentId();y??(y={id:h??"",open:h!==void 0});let s=new V({url:i.url,fetch:i.fetch,logger:i.logger,sdk:i.sdk,session:o,sampleRate:t,environment:i.environment,release:i.release,beforeSendPageview:e.beforeSendPageview}),p=false,g,v=()=>{p=true,clearTimeout(g),a.close(),l.stop(),document.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u);},w=(c,m)=>{c.length!==0&&s.send(c,m).then(()=>{s.stopped&&!p&&v();},()=>{});},S=c=>{w([...a.takeFinished(),...a.snapshot()],c);},T=()=>{clearTimeout(g),g=void 0,w(a.takeFinished(),"visible");},d=()=>{document.visibilityState==="hidden"&&S("hidden");},u=()=>{let c=[...s.undispatched(),...a.takeFinished(),...a.snapshot()];w([...new Map(c.map(m=>[m.id,m])).values()],"pagehide");};document.addEventListener("visibilitychange",d),window.addEventListener("pagehide",u);let f=c=>(...m)=>{if(!p)try{c(...m);}catch(M){i.logger.debug("RUM error",M);}};return {session:o,requestStart:f(()=>{a.requestStart();}),request:f(c=>{a.request(c);}),navigate:f(()=>{a.navigate(),y&&a.currentId()!==y.id&&(y.open=!1);let c=a.finishedCount();c>=oe?T():c>0&&(g??(g=setTimeout(T,ae)));}),setRoute:f(c=>{a.setRoute(c);}),close:f(()=>{S("visible"),v();})}}export{Te as rum};
package/dist/rum.js CHANGED
@@ -1,4 +1,4 @@
1
- import { uuid4, stripUrl, rumUrl } from './chunk-YN5N3X7X.js';
1
+ import { metaContent, uuid4, stripUrl, rumUrl } from './chunk-ECMQ35KU.js';
2
2
 
3
3
  // src/rum/pageviews.ts
4
4
  var QUIET_MS = 500;
@@ -493,11 +493,12 @@ function observeVitals() {
493
493
  var SEND_EVERY = 10;
494
494
  var SEND_INTERVAL_MS = 5 * 6e4;
495
495
  var load;
496
- function rum(options) {
496
+ function rum(options = {}) {
497
497
  return { start: (ctx) => start(ctx, options) };
498
498
  }
499
499
  function start(ctx, options) {
500
- const { id, sampled } = sessionFor(options.sampleRate);
500
+ const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? 0);
501
+ const { id, sampled } = sessionFor(sampleRate);
501
502
  if (!sampled) {
502
503
  ctx.logger.debug("RUM: this tab wasn't sampled");
503
504
  const nothing = () => void 0;
@@ -514,7 +515,7 @@ function start(ctx, options) {
514
515
  logger: ctx.logger,
515
516
  sdk: ctx.sdk,
516
517
  session: id,
517
- sampleRate: options.sampleRate,
518
+ sampleRate,
518
519
  environment: ctx.environment,
519
520
  release: ctx.release,
520
521
  beforeSendPageview: options.beforeSendPageview
@@ -0,0 +1,7 @@
1
+ /*! @hullop/tlm 0.2.0 | MIT */
2
+ function Z(t){let e;try{e=new URL(t);}catch{return null}if(e.protocol!=="https:"&&e.protocol!=="http:"||e.username==="")return null;let n=e.origin+e.pathname.replace(/\/+$/,""),r=e.username;return {url:`${n}/api/events?key=${r}`,heartbeatUrl:`${n}/api/heartbeats?key=${r}`,pageviewsUrl:`${n}/api/pageviews?key=${r}`,base:n,key:r}}function ee(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=crypto.getRandomValues(new Uint8Array(16));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function T(t,e){if(t.length<=e)return t;let n=t.charCodeAt(e-1);return t.slice(0,n>=55296&&n<=56319?e-1:e)}function H(t,e=8192){return T(_e(t),e)}function _e(t){if(typeof t=="string")return t;if(t===void 0||typeof t=="function"||typeof t=="symbol"||typeof t=="bigint")return String(t);let e=new WeakSet;try{return JSON.stringify(t,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r!==null){if(e.has(r))return "[Circular]";e.add(r);}return r})}catch{try{return String(t)}catch{return "[unserializable]"}}}function g(t){let e=t.search(/[?#]/);return e===-1?t:t.slice(0,e)}var ke=500;function te(t,e){try{let n=new URL(e,t);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:(n.origin+n.pathname).slice(0,ke)}catch{return}}var Oe=250,Le=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/,Ae=/^(.*?)@(.*):(\d+):(\d+)$/,Ue=/\((\S+?):(\d+):(\d+)\)/,Ne=/^(.*?) line (\d+) > (?:eval|Function)/,$e=new Set(["global code","module code","eval code"]);function ne(t){let e=[];for(let n of t.split(`
3
+ `)){let r=De(n)??Ie(n);r&&e.push(r);}return e}function De(t){let e=Le.exec(t);if(e?.[2]===void 0)return;let n=e[2],r=Number(e[3]),i=Number(e[4]);if(n.startsWith("eval at ")){let s=Ue.exec(n);if(s?.[1]===void 0)return;n=s[1],r=Number(s[2]),i=Number(s[3]);}return {function:W(e[1]),url:n,line:r,column:i}}function Ie(t){let e=Ae.exec(t);if(e?.[2]===void 0||e[2]==="")return;let n=e[1],r=/^([^*]*)\*(.*)$/.exec(n??"");if(r){if(r[1]!=="async")return;n=r[2];}let i=Ne.exec(e[2]);return i?.[1]!==void 0&&i[1]!==""?{function:W(n),url:i[1],line:Number(i[2]),column:void 0}:{function:W(n),url:e[2],line:Number(e[3]),column:Number(e[4])}}function W(t){if(t===void 0||t===""||$e.has(t))return;let e=t.replace(/^async\*/,"").replace(/^(?:async|new) /,"").replace(/ \[as [^\]]*\]$/,"").replace(/[/<]+$/,""),n=e.slice(Math.max(e.lastIndexOf("."),e.lastIndexOf("/"))+1);return n!==""&&n!=="<anonymous>"?n:void 0}function K(t){return /^(?:chrome|moz|safari|safari-web)-extension:\/\//.test(t)}var Me=[/\/node_modules\//,/\/\.vite\/deps\//,/\/vendors?(?:\/|[-.~][^/]*$)/,/chunk-vendors/,/vendors~/,/\/@vite\//,/\/@react-refresh/,/\/_next\/static\/chunks\/(?:framework|main|webpack)[-.]/],Be=/[-.~]([A-Za-z0-9_]{8,}|[A-Za-z0-9_-]{8})(?=\.)/g;function Pe(t){return /\d/.test(t)?true:t.length!==8?false:/[_-]/.test(t)||/[A-Z]/.test(t)&&/[a-z]/.test(t)&&!/[a-z]{3}/.test(t)}function X(t){let e=g(t),n=e.lastIndexOf("/")+1,r=e.slice(n).replace(Be,(i,s)=>Pe(s)?"":i);return e.slice(0,n)+r}function re(t,e){let n=[];for(let r of t)if(r.function?.startsWith("__tlm")!==true){if(n.length===Oe)break;n.push(Fe(r,e));}return n}function Fe(t,{origin:e,inAppUrls:n,isDependency:r,ownUrl:i}){let s;try{s=new URL(t.url,e);}catch{s=void 0;}let o=t.url.startsWith("webpack-internal://"),d=s?.origin===e||o,c=g(t.url);s&&!o&&(c=d?s.pathname:g(s.href));let u=s?g(s.href):void 0,a=u!==void 0&&u===i,l=u!==void 0&&r?.(u)===true,h=!a&&(n?n.some(v=>typeof v=="string"?t.url.includes(v):v.test(t.url)):d&&!K(t.url)&&!Me.some(v=>v.test(c))&&!l),m={module:X(c),function:t.function??"?",file:c,in_app:h};return t.line!==void 0&&(m.line=t.line),t.column!==void 0&&(m.column=t.column),m}var G=8192,Ce=new Set(["fatal","error","warning","info"]),je={debug:"info",log:"info",warn:"warning",critical:"fatal"};function qe(t){return typeof t!="string"?"error":Ce.has(t)?t:je[t]??"error"}var x="@hullop/tlm";function He(t){if(t instanceof Error)return true;if(typeof t!="object"||t===null)return false;let e=t;return typeof e.message=="string"&&(typeof e.name=="string"||typeof e.stack=="string")}function We(t){if(typeof t.name=="string"&&t.name!=="")return t.name;let e=t.constructor?.name;return typeof e=="string"&&e!==""&&e!=="Object"?e:"Error"}function V(t,e,n,r="manual"){let i=se(e,n);if(He(t)){let s=typeof t.stack=="string"?re(ne(t.stack),{origin:e.origin,inAppUrls:e.options.inAppUrls,isDependency:e.isDependency,ownUrl:e.ownUrl}):[];i.exception={type:We(t),message:T(String(t.message),G)},s.length>0&&(i.exception.frames=s);}else i.exception={type:r==="onunhandledrejection"?"UnhandledRejection":"NonError",message:H(t,G)};return i}function ie(t,e,n){let r=se(e,n);return r.message=H(t,G),r}function Ke(){return typeof __TLM_RELEASE__=="string"?__TLM_RELEASE__:void 0}function _(t){let e=t.release??Ke();return e===""?void 0:e}function k(t){return typeof t.environment=="string"&&t.environment!==""?t.environment:void 0}function se({options:t,scope:e,href:n,userAgent:r,session:i},s={}){let o={v:1,uuid:ee(),timestamp:new Date().toISOString(),platform:"javascript",level:qe(s.level),request:{url:t.stripQuery===false?n:g(n),headers:{"user-agent":r}},sdk:{name:x,version:"0.2.0"}},d=k(t);d!==void 0&&(o.environment=d);let c=_(t);c!==void 0&&(o.release=c),i!==void 0&&(o.session=i),s.fingerprint&&s.fingerprint.length>0&&(o.fingerprint=s.fingerprint.map(String));let u=s.user?{id:String(s.user.id)}:e.user;u&&(o.user=u);let a={...e.tags,...s.tags};Object.keys(a).length>0&&(o.tags=a);let l=e.getBreadcrumbs();return l.length>0&&(o.breadcrumbs=l),o}var oe=["ResizeObserver loop limit exceeded","ResizeObserver loop completed with undelivered notifications",/^(?:Error: )?Script error\.?$/];function ae(t){let{exception:e}=t;return e?e.message!==void 0&&e.message!==""?`${e.type}: ${e.message}`:e.type:t.message??""}function ue(t,e){let n=t.exception?.frames;if(n!==void 0&&n.length>0&&n.every(i=>K(i.file)))return true;let r=ae(t);return e.some(i=>typeof i=="string"?r.includes(i):i.test(r))}var U=class{constructor(e=1e3){this.windowMs=e;this.lastAt=0;}isDuplicate(e,n){let r=(e.exception?.frames??[]).slice(0,5).map(o=>`${o.file}:${String(o.line)}:${String(o.column)}`),i=`${ae(e)}
4
+ ${r.join(`
5
+ `)}`,s=i===this.last&&n-this.lastAt<=this.windowMs;return this.last=i,this.lastAt=n,s}},N=class{constructor(e=30,n=1e4){this.max=e;this.windowMs=n;this.times=[];}take(e){return this.times=this.times.filter(n=>e-n<this.windowMs),this.times.length>=this.max?false:(this.times.push(e),true)}};function de(t,e,n){let r=s=>{try{if(typeof s.target?.nodeType=="number")return;let o=s;e(o.error??Ge(o),"onerror");}catch{}},i=s=>{try{e(s.reason,"onunhandledrejection");}catch{}};return n.onerror&&t.addEventListener("error",r),n.onunhandledrejection&&t.addEventListener("unhandledrejection",i),()=>{t.removeEventListener("error",r),t.removeEventListener("unhandledrejection",i);}}var Xe=/^(?:Uncaught |uncaught exception: )?(null|undefined)$/;function Ge(t){let e=Xe.exec(t.message),n=new Error(e?.[1]??(t.message!==""?t.message:"Unknown error"));return e&&(n.name="NonError"),n.stack=typeof t.filename=="string"&&t.filename!==""?`${n.name}: ${n.message}
6
+ at ? (${t.filename}:${String(t.lineno)}:${String(t.colno)})`:"",n}var ce=5e3,Ve="tlm:heartbeat:",le=new Set;function fe(t){let e,n=()=>{Qe(t);},r=setTimeout(()=>{"requestIdleCallback"in globalThis?e=requestIdleCallback(n,{timeout:ce}):n();},ce);return ()=>{clearTimeout(r),e!==void 0&&cancelIdleCallback(e);}}function ze(t){try{return localStorage.getItem(t)}catch{return null}}async function Qe({url:t,key:e,fetch:n,options:r,logger:i}){let s=_(r),o=k(r),d=Ve+e,c=JSON.stringify([new Date().toISOString().slice(0,10),s??"",o??""]);if(ze(d)===c||le.has(d+c))return;let u;try{let a=JSON.stringify({v:1,sdk:{name:x,version:"0.2.0"},environment:o,release:s});({status:u}=await n(t,{method:"POST",body:a,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:!0,credentials:"omit"}));}catch(a){i.debug("heartbeat not sent",a);return}if(!(u===429||u>=500))try{localStorage.setItem(d,c);}catch{le.add(d+c);}}function w(t,e){let n=t.querySelector(`meta[name="tlm-${e}"]`)?.getAttribute("content")?.trim();return n===""?void 0:n}var Je=t=>!/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(t);function Ye(t,e){let n=[];for(let r of t.querySelectorAll('script[type="importmap"]')){let i;try{i=JSON.parse(r.textContent);}catch{continue}let s=typeof i=="object"&&i!==null&&"imports"in i?i.imports:void 0;if(!(typeof s!="object"||s===null)){for(let[o,d]of Object.entries(s))if(!(!Je(o)||typeof d!="string"))try{n.push({specifier:o,url:g(new URL(d,e).href)});}catch{}}}return n}function Ze({specifier:t,url:e}){let n=t.replace(/\/$/,""),r=X(new URL(e).pathname).replace(/\.m?js$/,"").replace(/\/$/,"");return r.endsWith(`/${n}`)||r.endsWith(`/${n}/index`)}function et(t,e){return t.some(n=>n.endsWith("/")?e.startsWith(n)||e===n.slice(0,-1):e===n)}function pe(t,e){let n=w(t,"in-app")?.split(/\s+/),r=o=>n?!et(n,o.specifier):o.specifier.startsWith("@")||!Ze(o),i=new Set,s=[];for(let o of Ye(t,e))r(o)&&(o.specifier.endsWith("/")?s.push(o.url):i.add(o.url));return o=>i.has(o)||s.some(d=>o.startsWith(d))}var $=10,tt=100;function D(t,e=false){if(typeof t=="string")return e?JSON.stringify(T(t,tt)):t;if(t===null||typeof t!="object")return typeof t=="function"?`[Function ${t.name!==""?t.name:"anonymous"}]`:String(t);let n=t;if(t instanceof Error||typeof n.message=="string"&&typeof n.name=="string")return `${String(n.name)}: ${String(n.message)}`;if(typeof n.nodeType=="number")return typeof n.tagName=="string"?`<${n.tagName.toLowerCase()}>`:"[Node]";if(e)return Array.isArray(t)?`[Array(${String(t.length)})]`:"{\u2026}";if(Array.isArray(t))return `[${t.slice(0,$).map(i=>D(i,true)).join(", ")}${t.length>$?", \u2026":""}]`;try{let r=Object.keys(t);return `{${r.slice(0,$).map(s=>`${s}: ${D(t[s],!0)}`).join(", ")}${r.length>$?", \u2026":""}}`}catch{return "{\u2026}"}}var me="__tlm_original__";function E(t,e,n){let r=t[e];if(typeof r!="function"||r[me]!==void 0)return ()=>true;let i=n(r);return Object.defineProperty(i,me,{value:r}),t[e]=i,()=>t[e]!==i?false:(t[e]=r,true)}function p(t){try{t();}catch{}}function R(t,e,n){let r=e;try{let i=new URL(e,t.location.href);i.username="",i.password="",r=i.origin===t.location.origin?i.pathname+i.search+i.hash:i.href;}catch{}return n?g(r):r}function I(t,e,n,r){let i=t.onRequest?te(e.location.href,r):void 0;if(i===void 0)return ()=>{};let s=performance.now(),o=t.onRequestStart?.();return d=>{t.onRequest?.({method:n.toUpperCase(),url:i,status:d??0,start:s,end:performance.now()},o);}}function M(t,e){try{return new URL(e,t.location.href).href}catch{return e}}function B(t){return t===void 0||t>=500?"error":t>=400?"warning":"info"}function P(t,e,n){return `${t.toUpperCase()} ${e} \u2192 ${n===void 0?"failed":String(n)}`}var ge={error:"error",warn:"warning",log:"info",info:"info"};function he(t,e,n){let r=t.console,i=Object.keys(ge).map(s=>E(r,s,o=>function(...c){p(()=>{e({category:"console",level:ge[s],message:T(c.map(u=>D(u)).join(" "),500)});}),o.apply(this,c);}));return ()=>i.map(s=>s()).every(Boolean)}var nt=3;function rt(t){let e=[],n=t;for(;n&&e.length<nt&&n.tagName!=="BODY"&&n.tagName!=="HTML";){let r=n.tagName.toLowerCase();n.id!==""&&(r+=`#${n.id}`);for(let i of Array.from(n.classList))r+=`.${i}`;e.unshift(r),n=n.parentElement;}return e.join(" > ")}function ye(t,e,n){let r=i=>{p(()=>{let s=i.target;if(s?.nodeType!==1)return;let o=rt(s);o!==""&&e({category:"ui.click",level:"info",message:o});});};return t.document.addEventListener("click",r,true),()=>(t.document.removeEventListener("click",r,true),true)}function it(t,e){let n=typeof Request<"u"&&t instanceof Request,r;return n?r=t.url:t instanceof URL?r=t.href:r=String(t),{method:e?.method??(n?t.method:"GET"),url:r}}function be(t,e,n){return E(t,"fetch",r=>async function(s,o){let d=r.apply(this,arguments),c=u=>{};return p(()=>{let{method:u,url:a}=it(s,o);if(n.skipUrl(M(t,a)))return;let l=R(t,a,n.stripQuery),h=I(n,t,u,a);c=m=>{p(()=>{h(m),e({category:"fetch",level:B(m),message:P(u,l,m)});});};}),d.then(u=>(c(u.status),u),u=>{throw c(void 0),u})})}function ve(t,e,n){let r=()=>{let a=R(t,t.location.href,n.stripQuery),{hash:l}=t.location;return !n.stripQuery||!/^#!?\//.test(l)?a:`${a}#${g(l.slice(1))}`},i=r(),s=()=>{p(()=>{let a=r();a!==i&&(e({category:"navigation",level:"info",message:`${i} \u2192 ${a}`}),i=a);});},o=a=>E(t.history,a,l=>function(...m){l.apply(this,m),s(),d();}),d=()=>{p(()=>{n.onNavigate?.();});},c=()=>{s(),d();},u=[o("pushState"),o("replaceState")];return t.addEventListener("popstate",c),t.addEventListener("hashchange",s),()=>u.map(a=>a()).every(Boolean)?(t.removeEventListener("popstate",c),t.removeEventListener("hashchange",s),true):false}function Te(t,e,n){let r=t.XMLHttpRequest;if(!r)return ()=>true;let i=r.prototype,s=new WeakMap,o=E(i,"open",c=>function(...a){p(()=>{let[l,h]=a;s.set(this,{method:String(l),url:h instanceof URL?h.href:String(h)});}),c.apply(this,a);}),d=E(i,"send",c=>function(a){p(()=>{let l=s.get(this);if(!l||n.skipUrl(M(t,l.url)))return;let h=R(t,l.url,n.stripQuery),m=I(n,t,l.method,l.url);this.addEventListener("loadend",()=>{p(()=>{let v=this.status!==0?this.status:void 0;m(v),e({category:"xhr",level:B(v),message:P(l.method,h,v)});});},{once:!0});}),c.call(this,a);});return ()=>[o(),d()].every(Boolean)}function we(t){let e=new Set,{debug:n,info:r,warn:i}=console;return {debug(...s){t()&&n.call(console,"[tlm]",...s);},warnOnce(s){e.has(s)||(e.add(s),i.call(console,`[tlm] ${s}`));},info(s){r.call(console,`[tlm] ${s}`);},warn(s){i.call(console,`[tlm] ${s}`);}}}var st=500,S=class{constructor(){this.tags={};this.breadcrumbs=[];}setUser(e){this.user=e?{id:String(e.id)}:void 0;}setTag(e,n){this.tags[e]=String(n);}setTags(e){for(let[n,r]of Object.entries(e))this.setTag(n,r);}addBreadcrumb(e,n){this.breadcrumbs.push({...e,timestamp:e.timestamp??new Date().toISOString(),message:T(String(e.message),st)}),this.breadcrumbs.length>n&&this.breadcrumbs.splice(0,this.breadcrumbs.length-n);}getBreadcrumbs(){return this.breadcrumbs.map(e=>({...e}))}clear(){this.user=void 0,this.tags={},this.breadcrumbs=[];}};function O(t,e){let{onAnswer:n}=t;t.onAnswer=void 0,n?.(e);}var z=1e3,ot=6e4,at=8,ut=60,Ee=6e4,Q=1e6,dt=50,ct=new TextEncoder,L=t=>ct.encode(t).length,F=class{constructor(e){this.deps=e;this.disabled=false;this.queue=[];this.inFlight=false;this.paused=false;this.backoff=z;this.inFlightKeepaliveBytes=0;this.idleWaiters=[];this.maxQueue=e.maxQueue??30;}send(e,n){if(!this.disabled){if(this.queue.length>=this.maxQueue){let r=this.queue.shift();r&&O(r,{error:new Error("dropped: too many events queued")}),this.deps.logger.debug("queue full, dropped the oldest event");}this.queue.push({event:e,attempts:0,...n?{onAnswer:n}:{}}),this.dispatch();}}async flush(e=2e3){return this.isIdle()?Promise.resolve(true):new Promise(n=>{let r=setTimeout(()=>{this.idleWaiters=this.idleWaiters.filter(s=>s!==i),n(false);},e),i=()=>{clearTimeout(r),n(true);};this.idleWaiters.push(i);})}sendQueuedNow(){if(this.disabled||this.paused)return;let e=Ee-this.inFlightKeepaliveBytes;for(let{event:n}of this.queue.splice(0)){let r=Se(n);if(r===void 0)continue;let i=L(r),s=i<=e;s&&(e-=i);try{this.deps.fetch(this.deps.url,{method:"POST",body:r,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:s,credentials:"omit"}).catch(()=>{});}catch{}}this.notifyIfIdle();}isIdle(){return !this.inFlight&&(this.queue.length===0||this.disabled)}dispatch(){let e=this.inFlight||this.paused||this.disabled?void 0:this.queue.shift();if(!e){this.notifyIfIdle();return}let n=Se(e.event);if(n===void 0){this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable",e.event.uuid),O(e,{error:new Error("dropped: over 1 MB or not JSON-encodable")}),this.dispatch();return}this.inFlight=true;let r=L(n),i=r<=Ee;this.inFlightKeepaliveBytes=i?r:0;let s;try{s=this.deps.fetch(this.deps.url,{method:"POST",body:n,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:i,credentials:"omit"});}catch(o){s=Promise.reject(o instanceof Error?o:new Error(String(o)));}s.then(o=>{this.handle(e,o);},o=>{this.retry(e,o);});}handle(e,n){this.inFlight=false,this.inFlightKeepaliveBytes=0;let{status:r}=n;if(O(e,{status:r}),r>=200&&r<300)this.backoff=z;else if(r===429)this.backoff=z,this.pause(lt(n.headers.get("Retry-After"))*1e3);else if(r===401||r===403)this.disable(r);else if(r>=500){this.retry(e,`HTTP ${String(r)}`);return}else {let{logger:i}=this.deps;n.text().then(s=>{i.debug(`Tlm rejected an event (HTTP ${String(r)})`,e.event.uuid,s);},()=>{i.debug(`Tlm rejected an event (HTTP ${String(r)})`,e.event.uuid);});}this.dispatch();}retry(e,n){O(e,{error:n}),this.inFlight=false,this.inFlightKeepaliveBytes=0,e.attempts+=1,e.attempts>=at?this.deps.logger.debug(`gave up on an event after ${String(e.attempts)} tries`,n):(this.deps.logger.debug("sending failed, will retry",n),this.queue.unshift(e));let r=this.backoff;this.backoff=Math.min(this.backoff*2,ot),this.pause(r);}pause(e){this.paused=true,setTimeout(()=>{this.paused=false,this.dispatch();},e);}disable(e){this.disabled=true;for(let r of this.queue.splice(0))O(r,{error:new Error(`dropped: Tlm rejected this DSN (HTTP ${String(e)})`)});this.deps.onDisable?.();let n=this.deps.origin??"unknown origin";this.deps.logger.warnOnce(e===401?"Tlm rejected the key (HTTP 401): check the DSN on your project's setup page. Nothing more will be sent from this page.":`This site's domain (${n}) is blocked for this project in Tlm (HTTP 403). Events won't be sent from this page. A project admin can unblock it in the project's settings.`);}notifyIfIdle(){if(!this.isIdle())return;let e=this.idleWaiters;this.idleWaiters=[];for(let n of e)n();}};function lt(t){let e=Number.parseInt(t??"",10);return e>=0?e:ut}function Se(t){try{return ft(t)}catch{return}}function ft(t){let e=JSON.stringify(t);if(L(e)<=Q)return e;let n={...t};if(delete n.breadcrumbs,e=JSON.stringify(n),L(e)<=Q||n.exception?.frames&&(n.exception={...n.exception,frames:n.exception.frames.slice(0,dt)},e=JSON.stringify(n),L(e)<=Q))return e}var pt={console:he,dom:ye,fetch:be,xhr:Te,history:ve},mt=50,gt=import.meta.url,Re=1e4;function ht(t){if("error"in t)return `couldn't reach Tlm (${t.error instanceof Error?t.error.message:String(t.error)}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;let{status:e}=t;if(!(e>=200&&e<300))return e===401?"Tlm rejected the key (HTTP 401). Check the DSN on your project's setup page.":e===403?"this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.":e===429?"Tlm asked to slow down (HTTP 429). Try again in a minute.":e>=500?`Tlm had an error (HTTP ${String(e)}). The event will be retried.`:`Tlm rejected the event (HTTP ${String(e)}).`}var y,C=new Map,yt={skipUrl:t=>y?.isOwnUrl(t)??false,get stripQuery(){return y?.options.stripQuery!==false},onRequestStart:()=>y?.rum?.requestStart(),onRequest:(t,e)=>{y?.rum?.request(t,e);},onNavigate:()=>{y?.rum?.navigate();}},bt=new Set(["fetch","xhr","history"]),xe=new Set,vt=t=>e=>{y&&y.options.breadcrumbs?.[t]!==false&&y.addBreadcrumb(e);};function Tt(t){return t.__tlm_original__??t}var j=class{constructor(e,n,r=new S){this.options=e;this.win=n;this.scope=r;this.cleanups=[];this.deduper=new U;this.rateGuard=new N;this.closed=false;if(this.logger=we(()=>e.debug===true),this.ignore=[...oe,...e.ignoreErrors??[]],e.enabled===false){this.logger.debug("disabled (enabled: false): nothing will be sent"),this.inactive="the SDK is off (enabled: false).";return}if(typeof e.dsn!="string"||e.dsn===""){this.logger.debug("no DSN given: nothing will be sent"),this.inactive='no DSN given to init() or in <meta name="tlm-dsn">.';return}let i=Z(e.dsn);if(!i){this.logger.debug("invalid DSN: nothing will be sent",e.dsn),this.inactive="invalid DSN. Copy it from your project's setup page.";return}this.endpointBase=i.base;let s=Tt(n.fetch).bind(n),{url:o}=i;this.transport=new F({url:o,fetch:s,logger:this.logger,origin:n.location.origin,onDisable:()=>xe.add(o)}),xe.has(o)?(this.transport.disabled=true,this.logger.debug("Tlm already rejected this DSN on this page: nothing will be sent")):e.heartbeat!==false&&this.cleanups.push(fe({url:i.heartbeatUrl,key:i.key,fetch:s,options:e,logger:this.logger}));let d=e.autoCapture;if(d!==false&&this.cleanups.push(de(n,(a,l)=>this.captureException(a,void 0,l),{onerror:d?.onerror!==false,onunhandledrejection:d?.onunhandledrejection!==false})),e.rum&&!this.transport.disabled)try{this.rum=e.rum.start({win:n,url:i.pageviewsUrl,fetch:s,logger:this.logger,options:e,sdk:{name:x,version:"0.2.0"},environment:k(e),release:_(e)});}catch(a){this.logger.debug("RUM didn't start",a);}y=this;for(let[a,l]of Object.entries(pt))if(!(!(e.breadcrumbs?.[a]!==false||this.rum!==void 0&&bt.has(a))||C.has(a)))try{C.set(a,l(n,vt(a),yt));}catch(m){this.logger.debug(`couldn't record ${a} breadcrumbs`,m);}this.isDependency=pe(n.document,n.location.href),this.followMeta();let c=()=>{this.rum?.navigate(),this.followMeta();};n.document.addEventListener("turbo:load",c),this.cleanups.push(()=>{n.document.removeEventListener("turbo:load",c);});let u=()=>{this.transport?.sendQueuedNow();};n.addEventListener("pagehide",u),this.cleanups.push(()=>{n.removeEventListener("pagehide",u);});}captureException(e,n,r="manual"){return this.capture(()=>V(e,this.env(),n,r))}captureMessage(e,n){let r=typeof n=="string"?{level:n}:n;return this.capture(()=>ie(e,this.env(),r))}async test(){let e=s=>(this.logger.warn(`Test event not sent: ${s}`),{ok:false,reason:s}),{transport:n}=this;if(this.closed)return Promise.resolve(e("the SDK was closed."));if(!n)return Promise.resolve(e(this.inactive??"the SDK isn't sending."));if(n.disabled)return Promise.resolve(e("Tlm already rejected this DSN on this page (HTTP 401/403)."));let r;try{let s=new Error("Test event from Tlm.test(). If you can see it in Tlm, your setup works.");throw s.name="TlmTest",s}catch(s){r=V(s,this.env(),{tags:{"tlm.test":"true"},fingerprint:["tlm.test"]});}let i=this.beforeSend(r)??r;return new Promise(s=>{let o=false,d=u=>{o||(o=true,clearTimeout(c),s(u));},c=setTimeout(()=>{d(e(`no answer from Tlm within ${String(Re/1e3)} s.`));},Re);n.send(i,u=>{if(o)return;let a=ht(u);if(a!==void 0){d(e(a));return}this.logger.info(`Test event sent (${"status"in u?String(u.status):"?"}). Look for "TlmTest" in your project: ${i.uuid}`),d({ok:true,id:i.uuid});});})}addBreadcrumb(e){this.scope.addBreadcrumb(e,this.options.maxBreadcrumbs??mt);}async flush(e){return this.transport?this.transport.flush(e):Promise.resolve(true)}setRoute(e){this.rum?.setRoute(e);}isOwnUrl(e){return this.endpointBase!==void 0&&e.startsWith(`${this.endpointBase}/`)}close(){this.closed=true;try{this.rum?.close();}catch(e){this.logger.debug("RUM didn't close cleanly",e);}if(y===this){y=void 0;for(let[e,n]of C)try{n()&&C.delete(e);}catch{}}for(let e of this.cleanups.splice(0).reverse())try{e();}catch(n){this.logger.debug("cleanup failed",n);}}followMeta(){let e=this.win.document,n=w(e,"user"),r=this.scope.user?.id;(r===void 0||r===this.metaUser)&&this.scope.setUser(n===void 0?null:{id:n}),this.metaUser=n;let i=w(e,"route");i!==void 0&&this.setRoute(i);}env(){let{win:e}=this;return {options:this.options,scope:this.scope,origin:e.location.origin,href:e.location.href,userAgent:e.navigator.userAgent,session:this.rum?.session,isDependency:this.isDependency,ownUrl:gt}}capture(e){let n=this.transport;if(!n||this.closed||n.disabled)return;let r=e();if(ue(r,this.ignore)){this.logger.debug("ignored",r.exception?.type??r.message);return}let i=Date.now();if(this.deduper.isDuplicate(r,i))return;let s=this.beforeSend(r);if(s){if(!this.rateGuard.take(i)){this.logger.debug("too many events, dropped one");return}return n.send(s),s.uuid}}beforeSend(e){let n=this.options.beforeSend;if(!n)return e;let r;try{r=n(e);}catch(i){return this.logger.debug("beforeSend threw; sending the event unchanged",i),e}if(r!==null){if((typeof r=="object"||typeof r=="function")&&"then"in r&&typeof r.then=="function"){this.logger.warnOnce("beforeSend returned a Promise, so the event was dropped. It must return the event (or null) right away, not async.");return}if(typeof r!="object"||Array.isArray(r)||!("uuid"in r)||typeof r.uuid!="string"){this.logger.debug("beforeSend returned neither an event nor null; dropped",r);return}return r}}};var On="0.2.0",f,A,Y=new S;function q(){return f?.scope??Y}function b(t,e){try{return t()}catch(n){return f?.logger.debug("internal error",n),e}}function wt(t,e){return {...t,dsn:t.dsn??w(e,"dsn"),environment:t.environment??w(e,"environment"),release:t.release??w(e,"release")}}function Ln(t={}){b(()=>{if(typeof window>"u")return;let e=q();f?.close(),f=new j(wt(t,window.document),window,e),A&&f.setRoute(A.name),A=void 0,t.debug===!0?Object.defineProperty(window,J,{value:{test:Et},configurable:!0,writable:!0}):Reflect.deleteProperty(window,J);},void 0);}var J="__tlm";async function Et(){let t=()=>{let e="init() hasn't run on this page (or this isn't a browser).";return console.warn(`[tlm] Test event not sent: ${e}`),{ok:false,reason:e}};return b(async()=>f?f.test():Promise.resolve(t()),Promise.resolve({ok:false,reason:"internal error."}))}function An(t,e){return b(()=>f?.captureException(t,e),void 0)}function Un(t,e){return b(()=>f?.captureMessage(t,e),void 0)}function Nn(t){b(()=>{q().setUser(t);},void 0);}function $n(t,e){b(()=>{q().setTag(t,e);},void 0);}function Dn(t){b(()=>{q().setTags(t);},void 0);}function In(t){b(()=>{f?f.addBreadcrumb(t):Y.addBreadcrumb(t,50);},void 0);}async function Mn(t){return b(async()=>f?.flush(t)??Promise.resolve(true),Promise.resolve(false))}function Bn(t){b(()=>{f?f.setRoute(t):A={name:t};},void 0);}function Pn(){b(()=>{f?.close(),f=void 0,Y=new S,A=void 0,typeof window<"u"&&Reflect.deleteProperty(window,J);},void 0);}
7
+ export{On as SDK_VERSION,In as addBreadcrumb,An as captureException,Un as captureMessage,Pn as close,Mn as flush,Ln as init,Bn as setRoute,$n as setTag,Dn as setTags,Nn as setUser,Et as test};
@@ -126,11 +126,11 @@ type TestResult = {
126
126
  };
127
127
  type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
128
128
  interface TlmOptions {
129
- /** Your project's DSN, from its setup page in Tlm. Without it, nothing is sent. */
129
+ /** Your project's DSN, from its setup page in Tlm. Default: `<meta name="tlm-dsn">`. Without one, nothing is sent. */
130
130
  dsn?: string;
131
- /** e.g. `"production"`, `"staging"`. Issues are counted per environment. */
131
+ /** e.g. `"production"`, `"staging"`. Issues are counted per environment. Default: `<meta name="tlm-environment">`. */
132
132
  environment?: string;
133
- /** Your app's version or git sha, e.g. `"web@1.4.2"`. */
133
+ /** Your app's version or git sha, e.g. `"web@1.4.2"`. Default: `<meta name="tlm-release">`. */
134
134
  release?: string;
135
135
  /** Logs what the SDK does to the console, prefixed `[tlm]`. Default `false`. */
136
136
  debug?: boolean;
@@ -126,11 +126,11 @@ type TestResult = {
126
126
  };
127
127
  type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
128
128
  interface TlmOptions {
129
- /** Your project's DSN, from its setup page in Tlm. Without it, nothing is sent. */
129
+ /** Your project's DSN, from its setup page in Tlm. Default: `<meta name="tlm-dsn">`. Without one, nothing is sent. */
130
130
  dsn?: string;
131
- /** e.g. `"production"`, `"staging"`. Issues are counted per environment. */
131
+ /** e.g. `"production"`, `"staging"`. Issues are counted per environment. Default: `<meta name="tlm-environment">`. */
132
132
  environment?: string;
133
- /** Your app's version or git sha, e.g. `"web@1.4.2"`. */
133
+ /** Your app's version or git sha, e.g. `"web@1.4.2"`. Default: `<meta name="tlm-release">`. */
134
134
  release?: string;
135
135
  /** Logs what the SDK does to the console, prefixed `[tlm]`. Default `false`. */
136
136
  debug?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hullop/tlm",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Reports your browser app's errors to Tlm.",
5
5
  "keywords": [
6
6
  "error-tracking",
@@ -52,12 +52,12 @@
52
52
  "access": "public"
53
53
  },
54
54
  "scripts": {
55
- "build": "tsup",
55
+ "build": "rm -rf dist && tsup",
56
56
  "test": "vitest run --project unit",
57
57
  "test:browser": "vitest run --project browser",
58
58
  "typecheck": "tsc --noEmit",
59
59
  "size": "size-limit",
60
- "check": "npm run typecheck && npm test && npm run build && npm run size",
60
+ "check": "npm run typecheck && npm test && npm run build && node scripts/check-standalone.mjs && npm run size",
61
61
  "prepublishOnly": "npm run check"
62
62
  },
63
63
  "devDependencies": {