@hullop/tlm 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-22)
4
+
5
+ First release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hullop
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,303 @@
1
- # Temporary Holding Version
1
+ # @hullop/tlm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reports your browser app's errors to [Tlm](https://tlm.hullop.com),
4
+ which groups them into issues, emails you when one is new or comes back,
5
+ and shows you what broke and why.
6
+
7
+ Works with any framework (React, Vue, Svelte, Angular, plain pages), has
8
+ no dependencies and weighs about 6 KB gzipped.
9
+
10
+ ## Installation
11
+
12
+ ```sh
13
+ npm install @hullop/tlm
14
+ ```
15
+
16
+ Then, as early as possible in your app's entry point (`main.ts`,
17
+ `index.js`, …), before the app renders:
18
+
19
+ ```ts
20
+ import * as Tlm from "@hullop/tlm";
21
+
22
+ Tlm.init({
23
+ dsn: "https://tlm_…@tlm.hullop.com", // from your project's setup page
24
+ environment: "production",
25
+ release: "web@1.4.2",
26
+ });
27
+ ```
28
+
29
+ That's it. From now on, uncaught errors and unhandled promise rejections
30
+ are reported on their own, along with what happened right before them:
31
+ clicks, navigation, network requests and console messages.
32
+
33
+ The DSN is public: it can only send events, so it's fine in browser code.
34
+ Without a DSN nothing is captured or sent, so dev and tests stay quiet
35
+ when you leave it out:
36
+
37
+ ```ts
38
+ Tlm.init({ dsn: import.meta.env.VITE_TLM_DSN });
39
+ ```
40
+
41
+ `environment` and `release` are optional. Issues are counted per
42
+ environment, and `release` tells you which deploy an error came from.
43
+
44
+ ### New domains
45
+
46
+ The first time events arrive from a new domain, Tlm keeps them and
47
+ asks the project's admins whether that domain is yours. If an admin
48
+ blocks it, pages there stop sending, and you'll see this once in the
49
+ browser console:
50
+
51
+ > [tlm] This site's domain (https://…) is blocked for this project in Tlm (HTTP 403). Events won't be sent from this page.
52
+
53
+ ### Content Security Policy
54
+
55
+ If your site sends a Content Security Policy, add your DSN's origin (its
56
+ scheme, host and port) to `connect-src`, next to the ones you already
57
+ allow:
58
+
59
+ ```
60
+ Content-Security-Policy: connect-src 'self' https://tlm.hullop.com
61
+ ```
62
+
63
+ That's all it needs, with or without RUM:
64
+
65
+ - Events, heartbeats, page views and `Tlm.test()` go out with
66
+ `fetch` or `navigator.sendBeacon`, which `connect-src` covers.
67
+ - Nothing for `script-src`: the package is bundled with your code, and it
68
+ doesn't load scripts or use `eval` or `new Function`.
69
+ - RUM's performance measurements and its `sessionStorage` entry aren't
70
+ covered by CSP.
71
+
72
+ If `connect-src` is missing it, the browser blocks the requests and logs
73
+ its own CSP error in the console; nothing reaches Tlm.
74
+ `Tlm.test()` (see [Checking your setup](#checking-your-setup))
75
+ then answers "couldn't reach Tlm (…). Check the DSN's host, your
76
+ network, and your Content-Security-Policy's connect-src." CSP violation reports
77
+ (`report-uri`, `report-to`) go wherever your policy says, not to Tlm.
78
+
79
+ ### Framework notes
80
+
81
+ - **Next.js, Nuxt, SvelteKit and other SSR frameworks:** importing the
82
+ package on the server is safe, and `init` does nothing there. Call it
83
+ from client-only code (e.g. a `"use client"` component's effect, or
84
+ `instrumentation-client.ts` in Next.js).
85
+ - **React:** errors caught by an error boundary aren't uncaught, so
86
+ report them yourself from `componentDidCatch`, or from `onCaughtError`
87
+ in React 19's `createRoot`:
88
+
89
+ ```ts
90
+ createRoot(el, { onCaughtError: (error) => Tlm.captureException(error) });
91
+ ```
92
+
93
+ - **Vue:** add `app.config.errorHandler = (error) => Tlm.captureException(error);`
94
+
95
+ ## Checking your setup
96
+
97
+ Send one test error and see what Tlm answered:
98
+
99
+ ```ts
100
+ const result = await Tlm.test();
101
+ // { ok: true, id: "…" } or { ok: false, reason: "Tlm rejected the key (HTTP 401)…" }
102
+ ```
103
+
104
+ It also logs one line to the console, `[tlm] Test event sent (202)…`
105
+ or why it wasn't. The event is a `TlmTest` error tagged
106
+ `tlm.test: "true"`, and every test groups into one issue. It skips
107
+ `ignoreErrors`, duplicate detection and the rate cap; `beforeSend` edits
108
+ apply, but if `beforeSend` drops it, it's sent anyway.
109
+
110
+ With `debug: true`, it's also on `window.__tlm.test()`, so you can
111
+ run it from the browser's console without importing anything.
112
+
113
+ ## Reporting things yourself
114
+
115
+ ```ts
116
+ try {
117
+ await checkout(cart);
118
+ } catch (error) {
119
+ Tlm.captureException(error, { tags: { step: "payment" } });
120
+ showRetry();
121
+ }
122
+
123
+ Tlm.captureMessage("Payment gateway slow", "warning");
124
+ ```
125
+
126
+ Both return the event's id, or `undefined` when nothing was sent.
127
+
128
+ ## Users and tags
129
+
130
+ Say who hit the error, by id (an id, not personal data), and add tags to
131
+ filter by:
132
+
133
+ ```ts
134
+ Tlm.setUser({ id: currentUser.id });
135
+ Tlm.setTag("plan", "pro");
136
+ ```
137
+
138
+ `setUser(null)` clears the user on logout.
139
+
140
+ ## Privacy
141
+
142
+ - Query strings and `#hashes` are removed from every URL sent (the page
143
+ URL and the breadcrumbs). Hash-router routes (`#/orders/7`) are kept in
144
+ navigation breadcrumbs, without their query. Turn it off with
145
+ `stripQuery: false`.
146
+ - Click breadcrumbs describe the element (`form.checkout > button#buy`),
147
+ never its text or input values.
148
+ - Cookies and request headers are never sent, only the user agent.
149
+ Usernames and passwords in URLs are removed.
150
+ - Console breadcrumbs keep a short summary of what was logged: strings
151
+ as they are, errors as `Type: message`, and only the first level of an
152
+ object's keys (`{id: 4812, email: "…"}`). If your app logs personal
153
+ data, turn them off with `breadcrumbs: { console: false }`.
154
+ - Once a day per release and environment, a few seconds after `init()`,
155
+ the SDK sends a heartbeat so Tlm knows the app is running even
156
+ before its first error. It carries only the SDK's name and version, the
157
+ release and the environment: no user, URL, user agent or browser id. The
158
+ day it was sent is kept in `localStorage` (`tlm:heartbeat:…`).
159
+ Turn it off with `heartbeat: false`.
160
+ - `beforeSend` sees every event last, and can edit it or drop it:
161
+
162
+ ```ts
163
+ Tlm.init({
164
+ dsn: "…",
165
+ beforeSend(event) {
166
+ if (event.request) event.request.url = event.request.url.replace(/\/users\/\d+/, "/users/:id");
167
+ return event; // or null to drop it
168
+ },
169
+ });
170
+ ```
171
+
172
+ ## Options
173
+
174
+ | Option | Default | |
175
+ |---|---|---|
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 |
179
+ | `debug` | `false` | Logs what the SDK does, prefixed `[tlm]` |
180
+ | `enabled` | `true` | `false` turns everything off |
181
+ | `beforeSend` | none | `(event) => event \| null`, to edit or drop events |
182
+ | `ignoreErrors` | browser noise | Strings (matched anywhere in `"Type: message"`) or regexps. Added to the built-in list (`ResizeObserver loop…`, `Script error.`) |
183
+ | `inAppUrls` | same origin | Strings or regexps for script URLs that are your app's own code (see below) |
184
+ | `stripQuery` | `true` | Remove `?query` and `#hash` from URLs |
185
+ | `breadcrumbs` | all on | `{ console, dom, fetch, xhr, history }`, each `true`/`false` |
186
+ | `maxBreadcrumbs` | `50` | How many breadcrumbs to keep |
187
+ | `autoCapture` | both on | `{ onerror, onunhandledrejection }`, or `false` for neither |
188
+ | `heartbeat` | `true` | `false` stops the daily heartbeat (see [Privacy](#privacy)) |
189
+
190
+ Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })`,
191
+ `flush(timeoutMs?)` (waits until queued events are sent) and `close()`
192
+ (removes everything the SDK installed).
193
+
194
+ ## Page speed (RUM)
195
+
196
+ Real User Monitoring shows how fast your pages are for the people using
197
+ them: Web Vitals per page, the slow requests pages make, and single
198
+ 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):
200
+
201
+ ```ts
202
+ import * as Tlm from "@hullop/tlm";
203
+ import { rum } from "@hullop/tlm/rum";
204
+
205
+ Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
206
+ ```
207
+
208
+ - **Sampling:** `sampleRate` is the share of browser tabs measured,
209
+ decided once per tab. A measured tab sends all its page views.
210
+ - **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
211
+ in-app navigations to a new path (pushState, LiveView; a new query
212
+ string alone, like a filter or a search box, stays the same page view),
213
+ INP, CLS and a navigation
214
+ time, from the click until the page's requests have finished and the DOM
215
+ has been quiet for half a second (at most 10 s). Plus the page's fetch
216
+ and XHR calls, and for slow pages the slowest resources it loaded.
217
+ - **When it sends:** in batches, when the tab is hidden or closed, and
218
+ every 10 page views or 5 minutes while it stays open. Batches over 1 KB
219
+ are gzipped. If Tlm is down or slow, page views are dropped
220
+ quietly; nothing is retried.
221
+ - **Privacy:** no cookies, no user id, no query strings or fragments. A
222
+ random id for the tab's visit, and the tab's sampling decision, are kept
223
+ in `sessionStorage` (key `tlm:rum`) and end with the tab. Errors
224
+ from a measured tab carry the visit's id, so an issue links to the visit.
225
+ Tlm derives the country and browser and doesn't store the IP or
226
+ user agent. Whether you need consent for analytics is your call.
227
+ - **Routes:** Tlm groups pages by guessing which path segments are
228
+ ids (`/orders/81` → `/orders/:id`). If your router knows the route, say
229
+ it after each navigation:
230
+
231
+ ```ts
232
+ Tlm.setRoute("/orders/:id");
233
+ ```
234
+
235
+ or pass `route: (location) => …` to `rum()`. Apps that route in the
236
+ `#hash` need this: fragments are never sent, so every page would
237
+ otherwise be `/`.
238
+ - **Editing or dropping page views:** `rum({ sampleRate, beforeSendPageview(pv) { … return pv; } })`;
239
+ return `null` to drop one.
240
+
241
+ ## How errors are grouped
242
+
243
+ Tlm groups events into issues by the error type and the functions
244
+ in your app's own code that it passed through. The SDK marks a stack
245
+ frame as your code when its script is on the page's own origin (or is a
246
+ webpack dev module, `webpack-internal:///./src/…`) and
247
+ isn't a dependency bundle (`node_modules`, `.vite/deps`, `vendor` chunks,
248
+ 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:
251
+
252
+ ```ts
253
+ Tlm.init({ dsn: "…", inAppUrls: ["https://cdn.example.com/app/"] });
254
+ ```
255
+
256
+ ## Source maps
257
+
258
+ Upload your build's source maps and Tlm shows your original files,
259
+ lines and function names, and groups errors by them. Upload them with the
260
+ [`tlm` CLI](https://github.com/cirope/tlm-cli) before you
261
+ deploy, with `TLM_UPLOAD_TOKEN` (from your project's settings) and
262
+ `TLM_DSN` set in your CI:
263
+
264
+ ```sh
265
+ tlm upload ./dist --release "$GIT_SHA"
266
+ ```
267
+
268
+ Make the app report the same release: pass it to `init({ release })`, or
269
+ define the `__TLM_RELEASE__` constant at build time. With Vite, build
270
+ hidden source maps so the bundle doesn't point to them, and delete the maps
271
+ before you deploy (`tlm upload --delete` does it):
272
+
273
+ ```ts
274
+ // vite.config.ts
275
+ export default defineConfig({
276
+ build: { sourcemap: "hidden" },
277
+ define: { __TLM_RELEASE__: JSON.stringify(process.env.GIT_SHA) },
278
+ });
279
+ ```
280
+
281
+ With webpack: `new DefinePlugin({ __TLM_RELEASE__: JSON.stringify(sha) })`.
282
+
283
+ ## What it won't do (yet)
284
+
285
+ - **Minified stack traces without source maps.** Upload them (see
286
+ [Source maps](#source-maps)); without them, frames show the built code
287
+ and the same error can open a new issue after a deploy.
288
+ - **Browsers name functions differently.** The SDK normalizes names
289
+ (`Cart.checkout` in Chrome and `checkout` in Firefox both become
290
+ `checkout`), but Safari sometimes leaves frames out, so the same error
291
+ can occasionally group separately per browser.
292
+ - **Browsers only.** For servers, use a server SDK: Node
293
+ ([`@hullop/tlm-node`](https://www.npmjs.com/package/@hullop/tlm-node),
294
+ for Express and Next.js) or [Elixir](https://hex.pm/packages/tlm).
295
+
296
+ It never throws into your app, never blocks it, and keeps quiet in the
297
+ console unless something's misconfigured (or you set `debug: true`).
298
+ When an error repeats in a loop, it sends it once; and it sends at most
299
+ 30 events every 10 seconds per page.
300
+
301
+ ## License
302
+
303
+ MIT
@@ -0,0 +1,56 @@
1
+ // src/util.ts
2
+ function uuid4() {
3
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
4
+ const b = crypto.getRandomValues(new Uint8Array(16));
5
+ b[6] = (b[6] ?? 0) & 15 | 64;
6
+ b[8] = (b[8] ?? 0) & 63 | 128;
7
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
8
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
9
+ }
10
+ function truncate(s, max) {
11
+ if (s.length <= max) return s;
12
+ const last = s.charCodeAt(max - 1);
13
+ return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
14
+ }
15
+ function safeStringify(value, max = 8192) {
16
+ return truncate(stringify(value), max);
17
+ }
18
+ function stringify(value) {
19
+ if (typeof value === "string") return value;
20
+ if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
21
+ return String(value);
22
+ }
23
+ const seen = /* @__PURE__ */ new WeakSet();
24
+ try {
25
+ return JSON.stringify(value, (_key, v) => {
26
+ if (typeof v === "bigint") return v.toString();
27
+ if (typeof v === "object" && v !== null) {
28
+ if (seen.has(v)) return "[Circular]";
29
+ seen.add(v);
30
+ }
31
+ return v;
32
+ });
33
+ } catch {
34
+ try {
35
+ return String(value);
36
+ } catch {
37
+ return "[unserializable]";
38
+ }
39
+ }
40
+ }
41
+ function stripUrl(url) {
42
+ const i = url.search(/[?#]/);
43
+ return i === -1 ? url : url.slice(0, i);
44
+ }
45
+ var MAX_URL = 500;
46
+ function rumUrl(base, url) {
47
+ try {
48
+ const parsed = new URL(url, base);
49
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
50
+ return (parsed.origin + parsed.pathname).slice(0, MAX_URL);
51
+ } catch {
52
+ return void 0;
53
+ }
54
+ }
55
+
56
+ export { rumUrl, safeStringify, stripUrl, truncate, uuid4 };