@edraj/sauron-browser 1.0.0 → 1.3.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 +19 -0
- package/README.md +988 -53
- package/dist/index.cjs +181 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +91 -5
- package/dist/index.d.ts +91 -5
- package/dist/index.js +178 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
# @edraj/sauron-browser
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
package.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
Client-side SDK for **Sauron** — error reporting and product analytics for the
|
|
4
|
+
browser in one small package. It runs in the page (or any browser-like host) and
|
|
5
|
+
posts a canonical JSON envelope to the Sauron ingest gateway. For a Node.js
|
|
6
|
+
process — an API server, a worker, a CLI — use the server SDK
|
|
7
|
+
[`@edraj/sauron-node`](../node) instead; this package assumes browser globals
|
|
8
|
+
(`window`, `document`, `localStorage`) and ships a public, write-only DSN key.
|
|
8
9
|
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
-
|
|
12
|
-
|
|
10
|
+
- Auto-instruments `window.onerror`, `onunhandledrejection`, `console`, DOM
|
|
11
|
+
clicks, `fetch`, `XMLHttpRequest`, and SPA History navigations out of the box.
|
|
12
|
+
- Opt-in performance transactions (navigation timing, per-`fetch` HTTP spans,
|
|
13
|
+
SPA route spans) and opt-in screen tracking.
|
|
14
|
+
- Batches, gzips, retries with jitter, and parks failed envelopes in a
|
|
15
|
+
`localStorage` queue that drains on the next page load or `online` event.
|
|
16
|
+
- One runtime dependency (`fflate`, lazily imported only as a gzip fallback).
|
|
17
|
+
- Ships ESM + CJS + type declarations, `sideEffects: false`, tree-shakeable.
|
|
13
18
|
|
|
14
19
|
## Install
|
|
15
20
|
|
|
@@ -17,20 +22,17 @@ Sauron ingest gateway.
|
|
|
17
22
|
npm install @edraj/sauron-browser
|
|
18
23
|
```
|
|
19
24
|
|
|
25
|
+
Node >= 18 is required for the build/test tooling (`engines.node`). The shipped
|
|
26
|
+
bundle targets ES2020 and needs no polyfills in evergreen browsers.
|
|
27
|
+
|
|
20
28
|
## Quick start
|
|
21
29
|
|
|
22
30
|
```ts
|
|
23
31
|
import { Sauron } from '@edraj/sauron-browser';
|
|
24
32
|
|
|
25
33
|
Sauron.init({
|
|
26
|
-
dsn: 'https://pk_test@ingest.
|
|
27
|
-
environment: 'production',
|
|
34
|
+
dsn: 'https://pk_test@ingest.example.com/42',
|
|
28
35
|
release: 'web@1.4.2',
|
|
29
|
-
sampleRate: 1, // fraction of errors to send
|
|
30
|
-
maxBreadcrumbs: 50,
|
|
31
|
-
beforeSend(item) { // PII escape hatch — return null to drop
|
|
32
|
-
return item;
|
|
33
|
-
},
|
|
34
36
|
});
|
|
35
37
|
|
|
36
38
|
Sauron.identify('u_123', { plan: 'pro' });
|
|
@@ -41,69 +43,1002 @@ try {
|
|
|
41
43
|
} catch (err) {
|
|
42
44
|
Sauron.captureException(err);
|
|
43
45
|
}
|
|
46
|
+
|
|
47
|
+
// Optional: force delivery now instead of waiting for the 5 s flush tick.
|
|
48
|
+
await Sauron.flush(2000);
|
|
44
49
|
```
|
|
45
50
|
|
|
46
|
-
|
|
51
|
+
Uncaught errors and unhandled rejections need no code at all — `init()` installs
|
|
52
|
+
the global handlers.
|
|
47
53
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
| `captureMessage(msg, level?)` | Report a plain message. |
|
|
53
|
-
| `track(name, props?)` | Record a product-analytics event. |
|
|
54
|
-
| `trackTransaction(input)` | Record a performance transaction (navigation / http / screen load). |
|
|
55
|
-
| `identify(id, traits?)` | Associate the session with a user. |
|
|
56
|
-
| `addBreadcrumb(crumb)` | Manually add a breadcrumb. |
|
|
57
|
-
| `setUser(user \| null)` | Set or clear the current user. |
|
|
58
|
-
| `flush(timeoutMs?)` | Send everything pending; resolves `false` on timeout. |
|
|
59
|
-
| `close(timeoutMs?)` | Flush, then restore all patched globals. |
|
|
54
|
+
## Configuration
|
|
55
|
+
|
|
56
|
+
`init(options)` takes an `InitOptions` object. Only `dsn` is required; anything
|
|
57
|
+
missing falls back to the default below (resolved in `resolveOptions()`).
|
|
60
58
|
|
|
61
|
-
|
|
59
|
+
| Option | Type | Default | Description |
|
|
60
|
+
| --- | --- | --- | --- |
|
|
61
|
+
| `dsn` | `string` | — **(required)** | `https://<public_key>@<host>/<environment_id>`. A non-string or empty value throws `Error`; a malformed URL throws `DsnError`. |
|
|
62
|
+
| `release` | `string` | `null` | Stamped on `header.release`; the part after the last `@` also becomes `context.app.version` (`web@1.4.2` → `1.4.2`). |
|
|
63
|
+
| `sampleRate` | `number` | `1` | Fraction of **error items** sent, clamped into `[0, 1]`. Applies to `captureException`, `captureMessage` and the global handlers only — events, identifies and transactions are never sampled. |
|
|
64
|
+
| `maxBreadcrumbs` | `number` | `50` | Ring-buffer size; oldest entries are evicted first. Negative values are treated as `0`, which disables breadcrumbs entirely. |
|
|
65
|
+
| `beforeSend` | `(item: EnvelopeItem, hint?: Hint) => EnvelopeItem \| null` | `undefined` | Runs on **every** item type just before the transport. Return `null` to drop. If it throws, the original item is sent and a warning is logged in `debug` mode. |
|
|
66
|
+
| `beforeBreadcrumb` | `(breadcrumb: Breadcrumb, hint?: Hint) => Breadcrumb \| null` | `undefined` | Runs on every breadcrumb before it enters the buffer. Return `null` to drop. Throwing keeps the original. |
|
|
67
|
+
| `transport` | `TransportOptions` | see below | Batching / queue tuning. |
|
|
68
|
+
| `performance` | `boolean` | `false` | Opt-in performance auto-capture (see [Automatic instrumentation](#automatic-instrumentation)). Manual `trackTransaction()` works regardless. |
|
|
69
|
+
| `screen` | `string` | `undefined` | Seeds the initial screen name. Seeding does **not** emit a `$screen` event — only a later `setScreen()` change does. |
|
|
70
|
+
| `screenTracking` | `boolean` | `false` | Opt-in: set the screen to the new path on every SPA History navigation (which emits `$screen`). `setScreen()` works regardless. |
|
|
71
|
+
| `tags` | `Record<string, string>` | `{}` | Default tags seeded into the global scope. |
|
|
72
|
+
| `contexts` | `Record<string, Record<string, unknown>>` | `{}` | Default named context blocks seeded into the global scope. |
|
|
73
|
+
| `extra` | `Record<string, unknown>` | `{}` | Default freeform values seeded into the global scope. |
|
|
74
|
+
| `debug` | `boolean` | `false` | Log SDK diagnostics to `console` with a `[sauron]` prefix. |
|
|
75
|
+
|
|
76
|
+
`TransportOptions`:
|
|
77
|
+
|
|
78
|
+
| Option | Type | Default | Description |
|
|
79
|
+
| --- | --- | --- | --- |
|
|
80
|
+
| `flushIntervalMs` | `number` | `5000` | Periodic flush cadence. A value `<= 0` disables the timer (you must call `flush()` yourself). |
|
|
81
|
+
| `maxBatch` | `number` | `30` | Items per envelope before an eager flush. Clamped into `[1, 1000]` — 1000 is the server's per-envelope item limit. |
|
|
82
|
+
| `maxQueueBytes` | `number` | `1048576` | Byte cap on the offline `localStorage` queue (1 MiB). Negative values are treated as `0`. |
|
|
83
|
+
|
|
84
|
+
Every option set at once:
|
|
62
85
|
|
|
63
86
|
```ts
|
|
87
|
+
import { Sauron } from '@edraj/sauron-browser';
|
|
88
|
+
|
|
64
89
|
Sauron.init({
|
|
65
|
-
dsn:
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
90
|
+
dsn: 'https://pk_test@ingest.example.com/42',
|
|
91
|
+
release: 'web@1.4.2',
|
|
92
|
+
sampleRate: 0.5,
|
|
93
|
+
maxBreadcrumbs: 100,
|
|
94
|
+
beforeSend(item, hint) {
|
|
95
|
+
if (item.type === 'error' && item.exception.value?.includes('token=')) {
|
|
96
|
+
return null; // PII escape hatch
|
|
97
|
+
}
|
|
98
|
+
return item;
|
|
99
|
+
},
|
|
100
|
+
beforeBreadcrumb(crumb) {
|
|
101
|
+
return crumb.category === 'console' ? null : crumb;
|
|
76
102
|
},
|
|
77
|
-
|
|
78
|
-
|
|
103
|
+
transport: {
|
|
104
|
+
flushIntervalMs: 5000,
|
|
105
|
+
maxBatch: 30,
|
|
106
|
+
maxQueueBytes: 1048576,
|
|
107
|
+
},
|
|
108
|
+
performance: true,
|
|
109
|
+
screen: '/',
|
|
110
|
+
screenTracking: true,
|
|
111
|
+
tags: { tier: 'free' },
|
|
112
|
+
contexts: { deploy: { region: 'eu-west-1' } },
|
|
113
|
+
extra: { build: 'ci-42' },
|
|
114
|
+
debug: true,
|
|
79
115
|
});
|
|
80
116
|
```
|
|
81
117
|
|
|
82
|
-
##
|
|
118
|
+
## API reference
|
|
119
|
+
|
|
120
|
+
Everything is exported both as a named function and as a member of the `Sauron`
|
|
121
|
+
facade (also the default export). The two are the same function:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { Sauron } from '@edraj/sauron-browser'; // facade
|
|
125
|
+
import Sauron from '@edraj/sauron-browser'; // default export
|
|
126
|
+
import { init, captureException } from '@edraj/sauron-browser'; // named
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
The facade carries `init`, `captureException`, `captureMessage`, `track`,
|
|
130
|
+
`trackTransaction`, `identify`, `addBreadcrumb`, `setUser`, `setTag`, `setTags`,
|
|
131
|
+
`setContext`, `setExtra`, `setScreen`, `getScreen`, `startWorkflow`,
|
|
132
|
+
`endWorkflow`, `cancelWorkflow`, `getWorkflow`, `flush`, `close` and
|
|
133
|
+
`getClient`.
|
|
134
|
+
|
|
135
|
+
Before `init()` every capture, analytics and scope function is a silent no-op,
|
|
136
|
+
`getScreen()`/`getWorkflow()` return `null`, `startWorkflow`/`endWorkflow`/
|
|
137
|
+
`cancelWorkflow` resolve to `{ status: 'disabled' }`, and `flush()`/`close()`
|
|
138
|
+
resolve to `false`. Nothing throws. After `close()` the capture and scope
|
|
139
|
+
functions stay no-ops (the client is disabled) and the screen and active
|
|
140
|
+
workflow are reset to `null`.
|
|
141
|
+
|
|
142
|
+
The same disabled state is also reached **automatically, mid-session**, the
|
|
143
|
+
moment the gateway answers a delivery with `401`/`403` (a revoked or invalid
|
|
144
|
+
DSN key) — no call to `close()`/`disable()` required. Check
|
|
145
|
+
[`isEnabled()`](#sauronclient) rather than assuming the SDK is live just
|
|
146
|
+
because you never explicitly disabled it.
|
|
147
|
+
|
|
148
|
+
### `init(options)`
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
function init(options: InitOptions): SauronClient
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
| Parameter | Type | Default | Description |
|
|
155
|
+
| --- | --- | --- | --- |
|
|
156
|
+
| `options` | `InitOptions` | — (required) | See [Configuration](#configuration). |
|
|
157
|
+
|
|
158
|
+
Resolves defaults, parses the DSN, seeds `tags`/`contexts`/`extra` into the
|
|
159
|
+
global scope, installs the integrations, starts the flush timer and drains the
|
|
160
|
+
offline queue. Returns the live `SauronClient`.
|
|
161
|
+
|
|
162
|
+
Idempotent: a second `init()` tears the previous client down first (restoring
|
|
163
|
+
every patched global, clearing the current screen) before installing a fresh
|
|
164
|
+
one. Throws `Error` when `dsn` is missing or not a string, and `DsnError` when
|
|
165
|
+
the DSN itself is malformed.
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
const client = Sauron.init({ dsn: 'https://pk_test@localhost:8081/1' });
|
|
169
|
+
client.options.release; // null
|
|
170
|
+
client.dsn.projectId; // '1'
|
|
171
|
+
```
|
|
83
172
|
|
|
84
|
-
|
|
173
|
+
### `captureException(err, hint?)`
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
function captureException(err: unknown, hint?: Hint): void
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
| Parameter | Type | Default | Description |
|
|
180
|
+
| --- | --- | --- | --- |
|
|
181
|
+
| `err` | `unknown` | — (required) | An `Error`, an error-like object (`name` + string `message`), a string, any object, or a primitive. Non-errors are reduced to `{type, value}` with an empty stack trace. |
|
|
182
|
+
| `hint` | `Hint` | `undefined` | Per-call overrides, also forwarded to `beforeSend`. |
|
|
183
|
+
|
|
184
|
+
Recognized `hint` keys:
|
|
185
|
+
|
|
186
|
+
| Key | Type | Default | Description |
|
|
187
|
+
| --- | --- | --- | --- |
|
|
188
|
+
| `level` | `Level` | `'error'` | `'debug' \| 'info' \| 'warning' \| 'error' \| 'fatal'`. |
|
|
189
|
+
| `mechanism` | `Mechanism` | `{ type: 'generic', handled: true }` | How the error reached the SDK. |
|
|
190
|
+
| `fingerprint` | `string[] \| null` | `null` | Overrides server-side grouping. |
|
|
191
|
+
| `screen` | `string` | current screen | Screen stamped on this item. |
|
|
192
|
+
| `event_id` | `string` | fresh UUID v4 | Correlation id for the report. |
|
|
193
|
+
| `message` | `string` | `undefined` | Human summary alongside the exception. |
|
|
194
|
+
| `tags` | `Record<string, string>` | `undefined` | Merged over scope tags (this call only). |
|
|
195
|
+
| `contexts` | `Record<string, Record<string, unknown>>` | `undefined` | Merged over scope contexts (this call only). |
|
|
196
|
+
| `extra` | `Record<string, unknown>` | `undefined` | Merged over scope extra (this call only). |
|
|
197
|
+
|
|
198
|
+
Any other key is passed through to `beforeSend` untouched. `originalException`
|
|
199
|
+
is always set to `err` on the hint the SDK hands to `beforeSend`. Returns
|
|
200
|
+
`void`; the item is buffered, not sent synchronously.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
try {
|
|
204
|
+
await placeOrder(orderId);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
Sauron.captureException(err, {
|
|
207
|
+
level: 'fatal',
|
|
208
|
+
fingerprint: ['checkout', 'place-order'],
|
|
209
|
+
tags: { flow: 'checkout' },
|
|
210
|
+
contexts: { order: { id: orderId } },
|
|
211
|
+
extra: { retry_count: 2 },
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### `captureMessage(message, level?, hint?)`
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
function captureMessage(message: string, level?: Level, hint?: Hint): void
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
| Parameter | Type | Default | Description |
|
|
223
|
+
| --- | --- | --- | --- |
|
|
224
|
+
| `message` | `string` | — (required) | Becomes `exception.value`; `exception.type` is `null`. |
|
|
225
|
+
| `level` | `Level` | `'info'` | Severity. |
|
|
226
|
+
| `hint` | `Hint` | `undefined` | Only `fingerprint`, `event_id`, `message`, `tags`, `contexts` and `extra` are read here — unlike `captureException`, `hint.level`, `hint.mechanism` and `hint.screen` are ignored. |
|
|
227
|
+
|
|
228
|
+
Emits an error item with mechanism `{ type: 'message', handled: true }`, an
|
|
229
|
+
empty stack trace, the current breadcrumb trail and the current screen. Counts
|
|
230
|
+
against `sampleRate` like any other error item. Returns `void`.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
Sauron.captureMessage('payment provider returned a soft decline', 'warning', {
|
|
234
|
+
tags: { provider: 'stripe' },
|
|
235
|
+
});
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### `track(name, properties?, options?)`
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
function track(
|
|
242
|
+
name: string,
|
|
243
|
+
properties?: Record<string, unknown>,
|
|
244
|
+
options?: TrackOptions,
|
|
245
|
+
): void
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
| Parameter | Type | Default | Description |
|
|
249
|
+
| --- | --- | --- | --- |
|
|
250
|
+
| `name` | `string` | — (required) | Event name. The SDK itself emits one reserved name, `$screen`. |
|
|
251
|
+
| `properties` | `Record<string, unknown>` | `{}` | Event properties, sent verbatim. |
|
|
252
|
+
| `options` | `TrackOptions` | `{}` | Per-call metadata, see below. |
|
|
253
|
+
|
|
254
|
+
`TrackOptions` (extends `CaptureOptions`):
|
|
255
|
+
|
|
256
|
+
| Field | Type | Default | Description |
|
|
257
|
+
| --- | --- | --- | --- |
|
|
258
|
+
| `tags` | `Record<string, string>` | `undefined` | Merged over scope tags. |
|
|
259
|
+
| `contexts` | `Record<string, Record<string, unknown>>` | `undefined` | Merged over scope contexts (per block name). |
|
|
260
|
+
| `extra` | `Record<string, unknown>` | `undefined` | Merged over scope extra. |
|
|
261
|
+
| `screen` | `string` | current screen | Screen stamped on this event only; does not change the current screen. |
|
|
262
|
+
|
|
263
|
+
The event carries `distinct_id` (the identified user id, else a lazily minted
|
|
264
|
+
`anon_<uuid>`), the session id and the screen. Events are never sampled.
|
|
265
|
+
Returns `void`.
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
Sauron.track('checkout_completed', { cart_value: 42.5, currency: 'EUR' }, {
|
|
269
|
+
tags: { experiment: 'new-cart' },
|
|
270
|
+
contexts: { cart: { items: 3 } },
|
|
271
|
+
extra: { coupon: 'SUMMER' },
|
|
272
|
+
screen: '/checkout/confirm',
|
|
273
|
+
});
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
### `identify(id, traits?)`
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
function identify(id: string, traits?: Record<string, unknown>): void
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
| Parameter | Type | Default | Description |
|
|
283
|
+
| --- | --- | --- | --- |
|
|
284
|
+
| `id` | `string` | — (required) | The distinct id (your user id). |
|
|
285
|
+
| `traits` | `Record<string, unknown>` | `{}` | Traits stored on the scope user and sent on the identify item. |
|
|
286
|
+
|
|
287
|
+
Sets the scope user to `{ id, traits }` and emits an identify item whose
|
|
288
|
+
`anonymous_id` is the previously minted anonymous id, or `null` when the session
|
|
289
|
+
never needed one. Note that this replaces the whole scope user — an `email` set
|
|
290
|
+
earlier via `setUser()` is cleared; call `setUser()` after `identify()` if you
|
|
291
|
+
need it. Returns `void`.
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
Sauron.identify('u_123', { plan: 'pro', signup_month: '2026-03' });
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### `trackTransaction(input)`
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
function trackTransaction(input: TransactionInput): void
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
| Field of `input` | Type | Default | Description |
|
|
304
|
+
| --- | --- | --- | --- |
|
|
305
|
+
| `name` | `string` | — (required) | Transaction name, e.g. `GET /api/orders`. |
|
|
306
|
+
| `durationMs` | `number` | — (required) | Wall-clock span in milliseconds. |
|
|
307
|
+
| `op` | `string` | `'custom'` | One of `'navigation' \| 'http' \| 'resource' \| 'screen_load' \| 'custom'`. Anything else is coerced to `'custom'`. |
|
|
308
|
+
| `status` | `string \| null` | `null` | Free-form outcome, e.g. `'ok'` / `'error'`. |
|
|
309
|
+
| `httpMethod` | `string \| null` | `null` | For `http` ops. |
|
|
310
|
+
| `httpStatus` | `number \| null` | `null` | For `http` ops. |
|
|
311
|
+
| `url` | `string \| null` | `null` | For `http` ops. |
|
|
312
|
+
|
|
313
|
+
The item is stamped with the current distinct id, session id and timestamp.
|
|
314
|
+
Never sampled. Returns `void`.
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
const started = performance.now();
|
|
318
|
+
const res = await fetch('/api/orders');
|
|
319
|
+
Sauron.trackTransaction({
|
|
320
|
+
name: 'GET /api/orders',
|
|
321
|
+
op: 'http',
|
|
322
|
+
durationMs: performance.now() - started,
|
|
323
|
+
status: res.ok ? 'ok' : 'error',
|
|
324
|
+
httpMethod: 'GET',
|
|
325
|
+
httpStatus: res.status,
|
|
326
|
+
url: '/api/orders',
|
|
327
|
+
});
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### `setScreen(name)`
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
function setScreen(name: string): void
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
| Parameter | Type | Default | Description |
|
|
337
|
+
| --- | --- | --- | --- |
|
|
338
|
+
| `name` | `string` | — (required) | The new screen/route name. |
|
|
339
|
+
|
|
340
|
+
Sets the current screen. On an actual change it also emits a `$screen` event
|
|
341
|
+
with `properties: { screen: name }` so dwell time can be computed server-side;
|
|
342
|
+
calling it again with the same name is a no-op. The current screen is stamped on
|
|
343
|
+
every subsequent event and error item. Returns `void`.
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
router.afterEach((to) => Sauron.setScreen(to.path));
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
### `getScreen()`
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
function getScreen(): string | null
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Returns the current screen name, or `null` when none was ever set (and after
|
|
356
|
+
`close()`, which resets it).
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
if (Sauron.getScreen() !== '/checkout') Sauron.setScreen('/checkout');
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### `startWorkflow(name, options?)`
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
function startWorkflow(name: string, options?: { force?: boolean }): WorkflowResult
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
| Parameter | Type | Default | Description |
|
|
369
|
+
| --- | --- | --- | --- |
|
|
370
|
+
| `name` | `string` | — (required) | Workflow name. Trimmed; rejected if empty after trimming or longer than 120 characters. |
|
|
371
|
+
| `options.force` | `boolean` | `false` | Replace an already-active workflow instead of rejecting the call. |
|
|
372
|
+
|
|
373
|
+
Starts a named, explicitly-bounded span of activity — e.g. `checkout`,
|
|
374
|
+
`onboarding` — and mints a fresh **client-generated UUID** as its
|
|
375
|
+
`workflowId`/wire `workflow_id`. While a workflow is active, every subsequent
|
|
376
|
+
`track`, `captureException`, `captureMessage` and `trackTransaction` call is
|
|
377
|
+
additionally stamped with `workflow_id` + `workflow_name`, alongside whatever
|
|
378
|
+
else it already carries. `startWorkflow` itself emits a reserved
|
|
379
|
+
`$workflow_start` event, stamped with the *new* workflow.
|
|
380
|
+
|
|
381
|
+
Workflows are entirely optional: an app that never calls `startWorkflow`
|
|
382
|
+
behaves exactly as before — no `workflow_id`/`workflow_name` fields are ever
|
|
383
|
+
added to any item.
|
|
384
|
+
|
|
385
|
+
Returns a `WorkflowResult`:
|
|
386
|
+
|
|
387
|
+
| `status` | Meaning |
|
|
388
|
+
| --- | --- |
|
|
389
|
+
| `'ok'` | Started (or replaced, with `force`). `workflowId` is the new id. |
|
|
390
|
+
| `'already_active'` | Another workflow is already active and `force` was not set. Nothing changed. |
|
|
391
|
+
| `'invalid_name'` | `name` was empty after trimming, or over 120 characters. Nothing changed. |
|
|
392
|
+
| `'disabled'` | Called before `init()`, after the client was closed/disabled, or after the transport auto-disabled itself on a `401`/`403` — also returned if an unexpected internal error occurred. Nothing changed. |
|
|
393
|
+
|
|
394
|
+
With `force: true`, the previously-active workflow is closed first — emitting
|
|
395
|
+
`$workflow_cancel` for it with `reason: 'superseded'` — and then the new one
|
|
396
|
+
starts. Without `force`, an active workflow simply blocks the call (logged as
|
|
397
|
+
a warning in `debug` mode). Telemetry never throws: every precondition failure
|
|
398
|
+
returns a status instead.
|
|
399
|
+
|
|
400
|
+
`'disabled'` always means *nothing changed*, so it is never worth retrying
|
|
401
|
+
blindly. If the workflow started but its `$workflow_start` event could not be
|
|
402
|
+
delivered, you still get `'ok'` and a `workflowId` — the workflow is live and
|
|
403
|
+
stamping is active, and the server materializes the workflow from the first
|
|
404
|
+
stamped event it receives regardless.
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
const result = Sauron.startWorkflow('checkout');
|
|
408
|
+
if (result.status === 'ok') {
|
|
409
|
+
console.log('workflow id', result.workflowId);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Force-replace whatever workflow (if any) is currently active:
|
|
413
|
+
Sauron.startWorkflow('checkout', { force: true });
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
### `endWorkflow(name?)`
|
|
417
|
+
|
|
418
|
+
```ts
|
|
419
|
+
function endWorkflow(name?: string): WorkflowResult
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
| Parameter | Type | Default | Description |
|
|
423
|
+
| --- | --- | --- | --- |
|
|
424
|
+
| `name` | `string` | current workflow | If given, must match the active workflow's name or the call is rejected. |
|
|
425
|
+
|
|
426
|
+
Ends the active workflow: emits `$workflow_end` carrying `duration_ms` (the
|
|
427
|
+
time since `startWorkflow`), then clears the active workflow.
|
|
428
|
+
|
|
429
|
+
| `status` | Meaning |
|
|
430
|
+
| --- | --- |
|
|
431
|
+
| `'ok'` | Ended. `workflowId` is the id that was closed. |
|
|
432
|
+
| `'not_active'` | No workflow is active. Nothing changed. |
|
|
433
|
+
| `'name_mismatch'` | `name` was given but does not match the active workflow. Nothing changed. |
|
|
434
|
+
| `'disabled'` | Called before `init()`, after the client was closed/disabled, or after the transport auto-disabled itself on a `401`/`403` — also returned if an unexpected internal error occurred. Nothing changed. |
|
|
435
|
+
|
|
436
|
+
A `name` that is itself malformed — empty, whitespace-only, or over 120
|
|
437
|
+
characters — reports `'name_mismatch'`, not `'invalid_name'`: it cannot match
|
|
438
|
+
the active workflow, and the call named a workflow that is not the active one.
|
|
439
|
+
`'invalid_name'` is reserved for `startWorkflow`, where the name is the thing
|
|
440
|
+
being created rather than a guard on which workflow to close.
|
|
441
|
+
|
|
442
|
+
`'ok'` always means the workflow really is closed locally, even in the rare
|
|
443
|
+
case where the `$workflow_end` event itself could not be delivered — so it is
|
|
444
|
+
never correct to see `'ok'` and still have `getWorkflow()` return non-null.
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
Sauron.startWorkflow('checkout');
|
|
448
|
+
// ... later
|
|
449
|
+
Sauron.endWorkflow(); // { status: 'ok', workflowId: '...' }
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
### `cancelWorkflow(name?, options?)`
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
function cancelWorkflow(name?: string, options?: { reason?: string }): WorkflowResult
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
| Parameter | Type | Default | Description |
|
|
459
|
+
| --- | --- | --- | --- |
|
|
460
|
+
| `name` | `string` | current workflow | If given, must match the active workflow's name or the call is rejected. |
|
|
461
|
+
| `options.reason` | `string` | `'user'` | Free-form cancellation reason. Trimmed and capped at 120 characters. |
|
|
462
|
+
|
|
463
|
+
Cancels the active workflow: emits `$workflow_cancel` carrying `duration_ms`
|
|
464
|
+
and `reason`, then clears the active workflow. Same status values and
|
|
465
|
+
preconditions as `endWorkflow` (`'ok'` / `'not_active'` / `'name_mismatch'` /
|
|
466
|
+
`'disabled'`), including the rule that a malformed `name` reports
|
|
467
|
+
`'name_mismatch'`. `startWorkflow(..., { force: true })` uses this internally
|
|
468
|
+
with `reason: 'superseded'` when it replaces an active workflow.
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
Sauron.cancelWorkflow(); // reason defaults to 'user'
|
|
472
|
+
Sauron.cancelWorkflow('checkout', { reason: 'payment declined' });
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
### `getWorkflow()`
|
|
476
|
+
|
|
477
|
+
```ts
|
|
478
|
+
function getWorkflow(): ActiveWorkflow | null
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
Returns the active workflow — `{ workflowId, name, startedAt }` — or `null`
|
|
482
|
+
when none is active (including before `init()`, and after `close()`, which
|
|
483
|
+
resets it).
|
|
484
|
+
|
|
485
|
+
A workflow with no stamped activity for 30 minutes is surfaced as `abandoned`
|
|
486
|
+
when queried on the dashboard/API. That status is derived on read from the
|
|
487
|
+
last stamped event's timestamp — it is never stored, so there is nothing for
|
|
488
|
+
the client to do; an "abandoned" workflow that later receives another stamped
|
|
489
|
+
event simply reads as active again.
|
|
490
|
+
|
|
491
|
+
```ts
|
|
492
|
+
const active = Sauron.getWorkflow();
|
|
493
|
+
if (active) {
|
|
494
|
+
console.log(`${active.name} running for`, Date.now() - Date.parse(active.startedAt), 'ms');
|
|
495
|
+
}
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
### `addBreadcrumb(breadcrumb, hint?)`
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
function addBreadcrumb(breadcrumb: BreadcrumbInput, hint?: Hint): void
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
| Field of `breadcrumb` | Type | Default | Description |
|
|
505
|
+
| --- | --- | --- | --- |
|
|
506
|
+
| `type` | `string` | `'default'` | Coarse kind, e.g. `'navigation'`. |
|
|
507
|
+
| `category` | `string` | `'default'` | Fine kind, e.g. `'ui.click'`, `'fetch'`. |
|
|
508
|
+
| `message` | `string \| null` | `null` | Short description. |
|
|
509
|
+
| `level` | `Level` | `'info'` | Severity. |
|
|
510
|
+
| `timestamp` | `string` | now, ISO-8601 UTC | Overrides the recorded time. |
|
|
511
|
+
| `data` | `Record<string, unknown> \| null` | `null` | Structured payload. |
|
|
512
|
+
|
|
513
|
+
| Parameter | Type | Default | Description |
|
|
514
|
+
| --- | --- | --- | --- |
|
|
515
|
+
| `hint` | `Hint` | `undefined` | Forwarded to `beforeBreadcrumb` only. |
|
|
516
|
+
|
|
517
|
+
The breadcrumb runs through `beforeBreadcrumb` and lands in the ring buffer.
|
|
518
|
+
Breadcrumbs are never sent on their own — the trail is copied onto every error
|
|
519
|
+
item. Returns `void`.
|
|
520
|
+
|
|
521
|
+
```ts
|
|
522
|
+
Sauron.addBreadcrumb({
|
|
523
|
+
type: 'default',
|
|
524
|
+
category: 'auth',
|
|
525
|
+
level: 'info',
|
|
526
|
+
message: 'token refreshed',
|
|
527
|
+
data: { expires_in: 3600 },
|
|
528
|
+
});
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### `setUser(user)`
|
|
532
|
+
|
|
533
|
+
```ts
|
|
534
|
+
function setUser(user: UserInput): void
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
| Field of `user` | Type | Default | Description |
|
|
538
|
+
| --- | --- | --- | --- |
|
|
539
|
+
| `id` | `string \| null` | `null` | User id; also becomes the `distinct_id` for later events. |
|
|
540
|
+
| `email` | `string \| null` | `null` | User email. |
|
|
541
|
+
| `traits` | `Record<string, unknown>` | `{}` | Arbitrary user traits. |
|
|
542
|
+
|
|
543
|
+
Pass `null` to clear the user entirely. The user is written to `context.user` on
|
|
544
|
+
every envelope, and onto `item.user` of error items while one is set. This is a
|
|
545
|
+
replace, not a merge. Returns `void`.
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
Sauron.setUser({ id: 'u_123', email: 'ada@example.com', traits: { plan: 'pro' } });
|
|
549
|
+
Sauron.setUser(null); // on logout
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
### `setTag(key, value)`
|
|
553
|
+
|
|
554
|
+
```ts
|
|
555
|
+
function setTag(key: string, value: string): void
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
| Parameter | Type | Default | Description |
|
|
559
|
+
| --- | --- | --- | --- |
|
|
560
|
+
| `key` | `string` | — (required) | Tag key. |
|
|
561
|
+
| `value` | `string` | — (required) | Tag value (strings only — tags are indexed). |
|
|
562
|
+
|
|
563
|
+
Sets one tag on the global scope; it is lifted onto every later error and event
|
|
564
|
+
item. Returns `void`.
|
|
565
|
+
|
|
566
|
+
```ts
|
|
567
|
+
Sauron.setTag('tenant', 'acme');
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
### `setTags(tags)`
|
|
571
|
+
|
|
572
|
+
```ts
|
|
573
|
+
function setTags(tags: Record<string, string>): void
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
| Parameter | Type | Default | Description |
|
|
577
|
+
| --- | --- | --- | --- |
|
|
578
|
+
| `tags` | `Record<string, string>` | — (required) | Batch of tags. |
|
|
579
|
+
|
|
580
|
+
Shallow-merges the batch into the scope, last-write-wins per key. Keys not
|
|
581
|
+
present are left alone. Returns `void`.
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
Sauron.setTags({ tenant: 'acme', tier: 'enterprise' });
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
### `setContext(name, block)`
|
|
588
|
+
|
|
589
|
+
```ts
|
|
590
|
+
function setContext(name: string, block: Record<string, unknown>): void
|
|
591
|
+
```
|
|
592
|
+
|
|
593
|
+
| Parameter | Type | Default | Description |
|
|
594
|
+
| --- | --- | --- | --- |
|
|
595
|
+
| `name` | `string` | — (required) | Block name, e.g. `'order'`. |
|
|
596
|
+
| `block` | `Record<string, unknown>` | — (required) | The block's contents. |
|
|
597
|
+
|
|
598
|
+
Replaces the whole named block (no deep merge). Dev-owned contexts are distinct
|
|
599
|
+
from the machine-detected `context` on the envelope and never overwrite it.
|
|
600
|
+
Returns `void`.
|
|
601
|
+
|
|
602
|
+
```ts
|
|
603
|
+
Sauron.setContext('order', { id: 7, total: 42.5 });
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
### `setExtra(key, value)`
|
|
607
|
+
|
|
608
|
+
```ts
|
|
609
|
+
function setExtra(key: string, value: unknown): void
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
| Parameter | Type | Default | Description |
|
|
613
|
+
| --- | --- | --- | --- |
|
|
614
|
+
| `key` | `string` | — (required) | Key in the freeform bag. |
|
|
615
|
+
| `value` | `unknown` | — (required) | Any JSON-serializable value. |
|
|
616
|
+
|
|
617
|
+
Sets one freeform value on the scope. Returns `void`.
|
|
618
|
+
|
|
619
|
+
```ts
|
|
620
|
+
Sauron.setExtra('feature_flags', ['new-cart', 'fast-checkout']);
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
### `flush(timeoutMs?)`
|
|
624
|
+
|
|
625
|
+
```ts
|
|
626
|
+
function flush(timeoutMs?: number): Promise<boolean>
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
| Parameter | Type | Default | Description |
|
|
630
|
+
| --- | --- | --- | --- |
|
|
631
|
+
| `timeoutMs` | `number` | `undefined` (wait indefinitely) | Give up after this many milliseconds. |
|
|
632
|
+
|
|
633
|
+
Drains the offline queue, then posts everything buffered in `maxBatch`-sized
|
|
634
|
+
envelopes. Resolves `true` on completion, `false` if `timeoutMs` elapsed first
|
|
635
|
+
or if `init()` was never called. Resolves `true` immediately when the client has
|
|
636
|
+
been disabled by a 401/403.
|
|
637
|
+
|
|
638
|
+
```ts
|
|
639
|
+
await Sauron.flush(2000);
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
### `close(timeoutMs?)`
|
|
643
|
+
|
|
644
|
+
```ts
|
|
645
|
+
function close(timeoutMs?: number): Promise<boolean>
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
| Parameter | Type | Default | Description |
|
|
649
|
+
| --- | --- | --- | --- |
|
|
650
|
+
| `timeoutMs` | `number` | `undefined` (wait indefinitely) | Passed straight to the inner flush. |
|
|
651
|
+
|
|
652
|
+
Flushes, then tears the SDK down: stops the flush timer and the `online`
|
|
653
|
+
listener, removes the unload listeners, clears the navigation hook and the
|
|
654
|
+
current screen, and restores every patched global in reverse order. Resolves to
|
|
655
|
+
the flush result. The client stays registered but disabled — call `init()` again
|
|
656
|
+
to restart.
|
|
657
|
+
|
|
658
|
+
```ts
|
|
659
|
+
await Sauron.close(2000);
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
### `getClient()`
|
|
663
|
+
|
|
664
|
+
```ts
|
|
665
|
+
function getClient(): SauronClient | null
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
Returns the active client, or `null` before `init()`.
|
|
669
|
+
|
|
670
|
+
```ts
|
|
671
|
+
const enabled = Sauron.getClient()?.isEnabled() ?? false;
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
### `SauronClient`
|
|
675
|
+
|
|
676
|
+
The client class, exported for typing and for the escape hatches below. You get
|
|
677
|
+
an instance from `init()` or `getClient()` — do not construct it yourself.
|
|
678
|
+
|
|
679
|
+
| Member | Signature | Description |
|
|
680
|
+
| --- | --- | --- |
|
|
681
|
+
| `options` | `readonly ResolvedOptions` | Fully-resolved options with defaults applied. |
|
|
682
|
+
| `dsn` | `readonly Dsn` | The parsed DSN. |
|
|
683
|
+
| `install()` | `(): void` | Install integrations + start the transport. Called by `init()`; a second call is a no-op. |
|
|
684
|
+
| `getScope()` | `(): Scope` | The mutable scope (user, breadcrumbs, tags, contexts, extra). |
|
|
685
|
+
| `isEnabled()` | `(): boolean` | `false` once the client has been explicitly `disable()`d/`teardown()`'d/`close()`d, **or** the transport has auto-disabled itself on a `401`/`403`. Computed from the transport's own state on every call, so a mid-session `401`/`403` flips this to `false` immediately — without the app ever calling `disable()`/`close()`. |
|
|
686
|
+
| `getDistinctId()` | `(): string \| null` | User id when identified, else the anonymous id (minting one if needed). |
|
|
687
|
+
| `getAnonymousId()` | `(): string \| null` | The anonymous id, or `null` if one was never needed. |
|
|
688
|
+
| `makeEnvelope(items)` | `(items: EnvelopeItem[]): Envelope` | Stamp a fresh envelope (new `sent_at`, current context) around `items`. |
|
|
689
|
+
| `addBreadcrumb(crumb, hint?)` | `(Breadcrumb, Hint?): void` | Full-shape breadcrumb, runs `beforeBreadcrumb`. |
|
|
690
|
+
| `captureItem(item, hint?)` | `(EnvelopeItem, Hint?): void` | Sampling + enrichment + workflow stamping + `beforeSend` + enqueue. |
|
|
691
|
+
| `flush(timeoutMs?)` | `(number?): Promise<boolean>` | Same as the module-level `flush`. |
|
|
692
|
+
| `disable()` | `(): void` | Stop accepting and sending; drops pending work. |
|
|
693
|
+
| `teardown()` | `(): void` | Restore globals and stop timers/listeners without flushing. |
|
|
694
|
+
| `close(timeoutMs?)` | `(number?): Promise<boolean>` | Flush, then `teardown()`. |
|
|
695
|
+
|
|
696
|
+
> **Workflow stamping happens inside `captureItem`.** That is why `track`,
|
|
697
|
+
> `captureException`, `captureMessage` and `trackTransaction` all pick up the active
|
|
698
|
+
> workflow automatically. If you hand-build an item and pass it to `captureItem` yourself,
|
|
699
|
+
> your own `workflow_id` / `workflow_name` win — the SDK will not overwrite them. Set
|
|
700
|
+
> **both or neither**: the server treats them as a pair and silently drops the attribution
|
|
701
|
+
> if only one is present, so the SDK logs a warning in that case. `identify` and
|
|
702
|
+
> breadcrumb-batch items are never stamped — the server has no workflow columns for them.
|
|
703
|
+
|
|
704
|
+
```ts
|
|
705
|
+
import { getClient } from '@edraj/sauron-browser';
|
|
706
|
+
|
|
707
|
+
const trail = getClient()?.getScope().getBreadcrumbs() ?? [];
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
### `parseDsn(dsn)` and `DsnError`
|
|
711
|
+
|
|
712
|
+
```ts
|
|
713
|
+
function parseDsn(dsn: string): Dsn
|
|
714
|
+
class DsnError extends Error
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
| Parameter | Type | Default | Description |
|
|
718
|
+
| --- | --- | --- | --- |
|
|
719
|
+
| `dsn` | `string` | — (required) | `https://<public_key>@<host>/<environment_id>`. |
|
|
720
|
+
|
|
721
|
+
Returns a `Dsn` with `raw`, `publicKey`, `host` (`host:port`), `hostname`,
|
|
722
|
+
`protocol` (`http` or `https`, no colon), `projectId` (the DSN's path
|
|
723
|
+
segment — despite the name, this is the **environment** id since the ingest
|
|
724
|
+
key now lives on the environment, not the app), `envelopeUrl`
|
|
725
|
+
(`<protocol>://<host>/api/<environment_id>/envelope`) and `beaconUrl` (the same
|
|
726
|
+
URL with `?k=<public_key>`).
|
|
727
|
+
|
|
728
|
+
Throws `DsnError` (message prefixed `[sauron] invalid DSN:`) for an empty or
|
|
729
|
+
non-string value, an unparseable URL, a protocol other than `http`/`https`, a
|
|
730
|
+
missing public key, a DSN that carries a password component, a missing host, or
|
|
731
|
+
a missing environment-id path segment.
|
|
732
|
+
|
|
733
|
+
```ts
|
|
734
|
+
import { parseDsn, DsnError } from '@edraj/sauron-browser';
|
|
735
|
+
|
|
736
|
+
try {
|
|
737
|
+
const dsn = parseDsn('https://pk_test@ingest.example.com/42');
|
|
738
|
+
console.log(dsn.envelopeUrl); // https://ingest.example.com/api/42/envelope
|
|
739
|
+
} catch (err) {
|
|
740
|
+
if (err instanceof DsnError) console.error(err.message);
|
|
741
|
+
}
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
### `buildEnvelope(header, context, items)`
|
|
745
|
+
|
|
746
|
+
```ts
|
|
747
|
+
function buildEnvelope(
|
|
748
|
+
header: EnvelopeHeader,
|
|
749
|
+
context: Context,
|
|
750
|
+
items: EnvelopeItem[],
|
|
751
|
+
): Envelope
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
| Parameter | Type | Default | Description |
|
|
755
|
+
| --- | --- | --- | --- |
|
|
756
|
+
| `header` | `EnvelopeHeader` | — (required) | `dsn`, `sdk`, `sent_at`, `release`. |
|
|
757
|
+
| `context` | `Context` | — (required) | `device`, `os`, `app`, `runtime`, `user`. |
|
|
758
|
+
| `items` | `EnvelopeItem[]` | — (required) | The payload items. |
|
|
759
|
+
|
|
760
|
+
A pure constructor for the canonical envelope shape (`header`, `context`,
|
|
761
|
+
`items`, in that order). Useful for tests and for hand-rolled delivery.
|
|
762
|
+
|
|
763
|
+
```ts
|
|
764
|
+
import { buildEnvelope, SDK_NAME, SDK_VERSION } from '@edraj/sauron-browser';
|
|
765
|
+
|
|
766
|
+
const envelope = buildEnvelope(
|
|
767
|
+
{
|
|
768
|
+
dsn: 'https://pk_test@localhost:8081/1',
|
|
769
|
+
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
770
|
+
sent_at: new Date().toISOString(),
|
|
771
|
+
release: null,
|
|
772
|
+
},
|
|
773
|
+
context,
|
|
774
|
+
[item],
|
|
775
|
+
);
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
### `parseStackString(stack)`, `parseError(err)`, `isInAppFrame(filename)`
|
|
779
|
+
|
|
780
|
+
```ts
|
|
781
|
+
function parseStackString(stack: string | undefined | null): Frame[]
|
|
782
|
+
function parseError(err: unknown): Frame[]
|
|
783
|
+
function isInAppFrame(filename: string | null): boolean
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
| Parameter | Type | Default | Description |
|
|
787
|
+
| --- | --- | --- | --- |
|
|
788
|
+
| `stack` | `string \| undefined \| null` | — (required) | A raw `Error.stack` string. `null`/`undefined` yields `[]`. |
|
|
789
|
+
| `err` | `unknown` | — (required) | Any value; its string `.stack` is parsed, else `[]`. |
|
|
790
|
+
| `filename` | `string \| null` | — (required) | A frame filename. |
|
|
791
|
+
|
|
792
|
+
`parseStackString` handles both the V8/Chrome/Node/Edge (`at fn (file:line:col)`)
|
|
793
|
+
and the Firefox/Safari (`fn@file:line:col`) formats, skips non-frame lines,
|
|
794
|
+
caps at 50 frames keeping the ones nearest the crash, and returns them with the
|
|
795
|
+
**crashing frame last**. No symbolication happens client-side.
|
|
796
|
+
|
|
797
|
+
`isInAppFrame` returns `true` for bare/relative paths and same-origin absolute
|
|
798
|
+
URLs, and `false` for cross-origin URLs, `<anonymous>`, `node:*` and
|
|
799
|
+
`internal/*`.
|
|
800
|
+
|
|
801
|
+
```ts
|
|
802
|
+
import { parseError, isInAppFrame } from '@edraj/sauron-browser';
|
|
803
|
+
|
|
804
|
+
const frames = parseError(new Error('boom'));
|
|
805
|
+
const appFrames = frames.filter((f) => isInAppFrame(f.filename));
|
|
806
|
+
```
|
|
807
|
+
|
|
808
|
+
### `SDK_NAME`, `SDK_VERSION`
|
|
809
|
+
|
|
810
|
+
```ts
|
|
811
|
+
const SDK_NAME: string // 'sauron.javascript'
|
|
812
|
+
const SDK_VERSION: string // '1.2.0'
|
|
813
|
+
```
|
|
814
|
+
|
|
815
|
+
The SDK identity embedded in `header.sdk` of every envelope.
|
|
816
|
+
|
|
817
|
+
### Exported types
|
|
818
|
+
|
|
819
|
+
All wire-contract and option types are exported for your own typing:
|
|
820
|
+
|
|
821
|
+
- Enums / unions: `Level`, `ItemType`, `TransactionOp`, `WorkflowStatus`.
|
|
822
|
+
- Item shapes: `Frame`, `Mechanism`, `ExceptionValue`, `Breadcrumb`, `ErrorItem`,
|
|
823
|
+
`EventItem`, `IdentifyItem`, `BreadcrumbBatchItem`, `TransactionItem`,
|
|
824
|
+
`EnvelopeItem`.
|
|
825
|
+
- Envelope shapes: `DeviceContext`, `OsContext`, `AppContext`, `RuntimeContext`,
|
|
826
|
+
`UserContext`, `Context`, `SdkInfo`, `EnvelopeHeader`, `Envelope`.
|
|
827
|
+
- Input / option shapes: `Hint`, `UserInput`, `BeforeSend`, `BeforeBreadcrumb`,
|
|
828
|
+
`TransportOptions`, `InitOptions`, `CaptureOptions`, `TrackOptions`,
|
|
829
|
+
`ResolvedOptions`, `BreadcrumbInput`, `TransactionInput`, `Dsn`,
|
|
830
|
+
`WorkflowResult`, `ActiveWorkflow`.
|
|
831
|
+
|
|
832
|
+
```ts
|
|
833
|
+
import type { EnvelopeItem, Hint, InitOptions } from '@edraj/sauron-browser';
|
|
834
|
+
|
|
835
|
+
const beforeSend = (item: EnvelopeItem, hint?: Hint): EnvelopeItem | null =>
|
|
836
|
+
item.type === 'error' ? item : null;
|
|
837
|
+
const options: InitOptions = { dsn: '...', beforeSend };
|
|
838
|
+
```
|
|
839
|
+
|
|
840
|
+
## Automatic instrumentation
|
|
841
|
+
|
|
842
|
+
`init()` patches the following globals. Every patch chains or defers to the
|
|
843
|
+
original — the app's own handlers, console output and `fetch` results are never
|
|
844
|
+
swallowed — and every one is restored by `close()`.
|
|
845
|
+
|
|
846
|
+
On by default:
|
|
847
|
+
|
|
848
|
+
| Global | What it records |
|
|
849
|
+
| --- | --- |
|
|
850
|
+
| `window.onerror` | Error item, mechanism `{ type: 'onerror', handled: false }`, level `error`. The previous handler is still called with its original arguments. |
|
|
851
|
+
| `window.onunhandledrejection` | Error item from `event.reason`, mechanism `{ type: 'onunhandledrejection', handled: false }`, level `error`. |
|
|
852
|
+
| `console.log/info/warn/error/debug` | Breadcrumb, category `console`, level mapped (`warn`→`warning`, `error`→`error`, `debug`→`debug`, else `info`), message = arguments joined and truncated to 512 chars, `data: { arguments: n }`. Output is untouched. |
|
|
853
|
+
| `document` click listener (capture, passive) | Breadcrumb, category `ui.click`, message = a `tag#id.class` selector (up to 3 classes). Element text and attribute values are never serialized. |
|
|
854
|
+
| `history.pushState` / `replaceState` / `popstate` | Breadcrumb, type `navigation`, category `history`, `data: { from, to }` as paths. Same-path transitions are skipped. |
|
|
855
|
+
| `fetch` | Breadcrumb, category `fetch`, message `METHOD url`, `data: { method, url, status_code }`, level `warning` for status >= 400. |
|
|
856
|
+
| `XMLHttpRequest.prototype.open` / `send` | Breadcrumb, category `xhr`, same shape as `fetch`. |
|
|
857
|
+
| `document` `visibilitychange` + window `pagehide` | Beacon flush of the pending batch on unload. |
|
|
858
|
+
| window `online` | Drains the offline queue. |
|
|
859
|
+
|
|
860
|
+
Opt-in:
|
|
861
|
+
|
|
862
|
+
| Option | What it adds |
|
|
863
|
+
| --- | --- |
|
|
864
|
+
| `performance: true` | A `navigation` transaction for the initial page load (Navigation Timing, captured on `load`), an `http` transaction per instrumented `fetch` (`name` = `METHOD /path`, `status` `ok`/`error`), and a `navigation` transaction per SPA route change measured over one animation frame. No-op when `document` is undefined. |
|
|
865
|
+
| `screenTracking: true` | Sets the screen to the new path on each SPA History navigation, which emits a `$screen` event on change. |
|
|
866
|
+
|
|
867
|
+
Two guards keep the SDK from observing itself: a reentrancy flag held while SDK
|
|
868
|
+
code runs, and a denylist on the DSN host. Requests the transport makes are
|
|
869
|
+
therefore never turned into breadcrumbs or transactions. Wrappers are tagged, so
|
|
870
|
+
a double `init()` never stacks two layers on the same global.
|
|
871
|
+
|
|
872
|
+
Integrations that need an absent global (no `document`, no `history`, no
|
|
873
|
+
`XMLHttpRequest`, no writable `localStorage`) simply skip installation, so
|
|
874
|
+
importing and initializing during SSR does not throw.
|
|
875
|
+
|
|
876
|
+
## Scope & metadata
|
|
877
|
+
|
|
878
|
+
There is a single global scope per client, holding the user, the breadcrumb ring
|
|
879
|
+
buffer, `tags`, `contexts` and `extra`.
|
|
880
|
+
|
|
881
|
+
Precedence for `tags` / `contexts` / `extra`, lowest to highest:
|
|
882
|
+
|
|
883
|
+
1. **`init` defaults** — `tags`, `contexts`, `extra` are seeded into the scope
|
|
884
|
+
when the client is constructed.
|
|
885
|
+
2. **Scope setters** — `setTag`, `setTags`, `setContext`, `setExtra` write into
|
|
886
|
+
that same store, so they overwrite the init defaults for the keys they touch
|
|
887
|
+
(last write wins) and leave the rest alone.
|
|
888
|
+
3. **Per-call overrides** — `hint.tags` / `hint.contexts` / `hint.extra` on
|
|
889
|
+
`captureException` and `captureMessage`, and `options.tags` /
|
|
890
|
+
`options.contexts` / `options.extra` on `track`. These win for that one item
|
|
891
|
+
and never mutate the scope.
|
|
892
|
+
|
|
893
|
+
The merge is shallow, per top-level key: a per-call tag replaces the scope tag
|
|
894
|
+
of the same key; a per-call **context block replaces the whole same-named scope
|
|
895
|
+
block** (no deep merge); other blocks and keys are preserved. When the merged
|
|
896
|
+
result is empty the field is omitted from the wire item entirely — the backend
|
|
897
|
+
defaults it to `{}`.
|
|
898
|
+
|
|
899
|
+
Other scope data:
|
|
900
|
+
|
|
901
|
+
- **user** — `setUser()` replaces it wholesale; `identify()` also replaces it
|
|
902
|
+
with `{ id, traits }`. It is written to `context.user` on every envelope, and
|
|
903
|
+
additionally onto `item.user` of error items while a user is set.
|
|
904
|
+
- **breadcrumbs** — capped at `maxBreadcrumbs`, FIFO eviction. The whole trail
|
|
905
|
+
is copied onto every error item; it is never sent on its own.
|
|
906
|
+
- **screen** — seeded by `init({ screen })`, changed by `setScreen()` (or
|
|
907
|
+
`screenTracking`). Stamped on every event and error item.
|
|
908
|
+
`TrackOptions.screen` overrides it for one event, `hint.screen` for one
|
|
909
|
+
`captureException`.
|
|
910
|
+
- **identity** — `device_id` persists in `localStorage` under
|
|
911
|
+
`sauron.device_id`; `session_id` persists in `sessionStorage` under
|
|
912
|
+
`sauron.session_id`. Both fall back to a per-process in-memory id when Web
|
|
913
|
+
Storage is unavailable.
|
|
914
|
+
|
|
915
|
+
```ts
|
|
916
|
+
Sauron.init({ dsn, tags: { tier: 'free' }, extra: { build: 'ci-42' } });
|
|
917
|
+
Sauron.setTag('tier', 'pro'); // scope beats init default
|
|
918
|
+
Sauron.track('upgraded', {}, { tags: { tier: 'trial' } });
|
|
919
|
+
// -> event tags: { tier: 'trial' }, extra: { build: 'ci-42' }
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
## Bundlers & CDN
|
|
923
|
+
|
|
924
|
+
- `"type": "module"` with a dual build: `import` resolves `dist/index.js`
|
|
925
|
+
(ESM), `require` resolves `dist/index.cjs`, types come from
|
|
926
|
+
`dist/index.d.ts`. `package.json` itself is exported as `./package.json`;
|
|
927
|
+
nothing else is deep-importable.
|
|
928
|
+
- `"sideEffects": false` — bundlers may drop unused exports. Importing the
|
|
929
|
+
package does nothing on its own; instrumentation is installed by `init()`.
|
|
930
|
+
- Built with tsup, target `es2020`, with source maps and generated declarations.
|
|
931
|
+
- No UMD/IIFE build is shipped, so a plain `<script src="...">` global tag is
|
|
932
|
+
not supported. On a CDN, use a module script against an ESM-serving CDN:
|
|
933
|
+
|
|
934
|
+
```html
|
|
935
|
+
<script type="module">
|
|
936
|
+
import { Sauron } from 'https://esm.sh/@edraj/sauron-browser@1.2.0';
|
|
937
|
+
Sauron.init({ dsn: 'https://pk_test@ingest.example.com/42' });
|
|
938
|
+
</script>
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
- The only runtime dependency is `fflate`, imported dynamically and only when
|
|
942
|
+
the platform lacks `CompressionStream`. Bundlers will emit it as a separate
|
|
943
|
+
async chunk.
|
|
944
|
+
- Initialize as early as possible — errors thrown before `init()` are not
|
|
945
|
+
captured.
|
|
946
|
+
|
|
947
|
+
## Transport & delivery
|
|
948
|
+
|
|
949
|
+
**Batching.** Items are buffered in memory and flushed every `flushIntervalMs`
|
|
950
|
+
(default 5000 ms), immediately once `maxBatch` items are pending (default 30,
|
|
951
|
+
clamped to `[1, 1000]`), and on demand via `flush()`/`close()`. Each `flush()`
|
|
952
|
+
drains the offline queue first, then posts the buffered items in
|
|
953
|
+
`maxBatch`-sized envelopes.
|
|
954
|
+
|
|
955
|
+
**Request.** `POST <protocol>://<host>/api/<environment_id>/envelope` with:
|
|
85
956
|
|
|
86
957
|
```
|
|
87
958
|
Content-Type: application/json
|
|
88
|
-
Content-Encoding: gzip # only when compressed (payloads ≳ 1 KB)
|
|
89
959
|
X-Sauron-Key: <public_key>
|
|
960
|
+
Content-Encoding: gzip # only when the body was compressed
|
|
90
961
|
```
|
|
91
962
|
|
|
92
|
-
|
|
93
|
-
|
|
963
|
+
The body is the canonical envelope — `header` + `context` + `items[]` —
|
|
964
|
+
identical across the JavaScript, Node, Python, Flutter and C# SDKs.
|
|
965
|
+
|
|
966
|
+
**Compression.** Payloads of 1024 bytes or more are gzipped with the native
|
|
967
|
+
`CompressionStream('gzip')` when available, falling back to a lazily imported
|
|
968
|
+
`fflate`. If neither works the envelope is sent uncompressed rather than
|
|
969
|
+
dropped. Smaller payloads are sent as plain JSON with no `Content-Encoding`.
|
|
94
970
|
|
|
95
|
-
|
|
96
|
-
|
|
971
|
+
**HTTP client.** The native `fetch` captured *before* the integrations wrap it,
|
|
972
|
+
so ingest traffic never instruments itself; `XMLHttpRequest` is the fallback
|
|
973
|
+
when `fetch` is absent. `keepalive: true` is set for bodies up to 64 KiB.
|
|
974
|
+
|
|
975
|
+
**Response handling.**
|
|
976
|
+
|
|
977
|
+
| Status | Action |
|
|
978
|
+
| --- | --- |
|
|
979
|
+
| `200`, `202` | Success — drop the batch. |
|
|
980
|
+
| `400` | Non-retryable — drop the batch. |
|
|
981
|
+
| `401`, `403` | Disable the client permanently: pending work is dropped and nothing further is sent until the next `init()`. |
|
|
982
|
+
| `408` | Retry with backoff. |
|
|
983
|
+
| `413` | Split the batch in half and retry each half. A single item that is still too large is parked in the offline queue. |
|
|
984
|
+
| `429` | Wait `Retry-After` (seconds or HTTP-date, clamped to 30 s; 1000 ms if unparseable), then retry. |
|
|
985
|
+
| `5xx` | Retry with backoff. |
|
|
986
|
+
| other `4xx` | Drop the batch. |
|
|
987
|
+
| network error / throw | Retry with backoff. |
|
|
988
|
+
|
|
989
|
+
Backoff is full-jitter: a uniform random delay in
|
|
990
|
+
`[0, min(30_000, 1000 * 2^attempt)]` ms. After 5 retries the serialized envelope
|
|
991
|
+
is parked in the offline queue.
|
|
992
|
+
|
|
993
|
+
**Offline queue.** A FIFO list under the `localStorage` key `sauron:queue:v1`,
|
|
994
|
+
byte-capped at `maxQueueBytes` (default 1 MiB); the oldest entries are evicted
|
|
995
|
+
first and at least one entry is always kept. It is drained at `init()`, at the
|
|
996
|
+
start of every `flush()`, and on the window `online` event. If a drained
|
|
997
|
+
envelope still fails, it is re-parked and draining stops to avoid a tight loop.
|
|
998
|
+
When `localStorage` is unavailable the queue is disabled and failed envelopes
|
|
999
|
+
are dropped.
|
|
1000
|
+
|
|
1001
|
+
**Page unload.** On `visibilitychange` → `hidden` and on `pagehide`, the pending
|
|
1002
|
+
batch is chunked to 1000 items and handed to `navigator.sendBeacon` as an
|
|
1003
|
+
uncompressed `application/json` Blob posted to
|
|
1004
|
+
`POST /api/<environment_id>/envelope?k=<public_key>` (the key moves to the query
|
|
1005
|
+
string because beacons cannot set headers). Chunks larger than 64 KiB, or a
|
|
1006
|
+
`sendBeacon` that is unavailable or refuses, are parked in the offline queue for
|
|
1007
|
+
the next page load.
|
|
1008
|
+
|
|
1009
|
+
## Troubleshooting
|
|
1010
|
+
|
|
1011
|
+
| Symptom | Cause | Fix |
|
|
1012
|
+
| --- | --- | --- |
|
|
1013
|
+
| Nothing arrives, no client-side errors | The gateway is not exposed at `/api/{environment_id}/envelope` on the host root. A DSN cannot express a path prefix, so the SDK posts to the root path and a proxy that serves ingest under a sub-path silently 404s. | Expose ingest at `/api/{environment_id}/envelope` on the DSN host root. |
|
|
1014
|
+
| Nothing arrives | `init()` was never called, or was called after the failing code ran. | Call `init()` first, as early in the page as possible. |
|
|
1015
|
+
| `[sauron] client disabled` in the console, or `isEnabled()` unexpectedly `false` mid-session | The gateway returned 401/403 — wrong, revoked or foreign-project public key. `isEnabled()` flips to `false` automatically; nothing else changes. | Fix the DSN key/project; re-`init()` after correcting. |
|
|
1016
|
+
| `DsnError` thrown at `init()` | Malformed DSN: bad protocol, missing public key, a password component, or a missing environment-id path segment. | Use `https://<public_key>@<host>/<environment_id>`. |
|
|
1017
|
+
| Only some errors show up | `sampleRate` below 1 (errors and messages are sampled; events, identifies and transactions are not). | Set `sampleRate: 1`. |
|
|
1018
|
+
| Errors arrive with no breadcrumbs | `maxBreadcrumbs: 0`, or `beforeBreadcrumb` returned `null`. | Raise `maxBreadcrumbs`; check the hook. |
|
|
1019
|
+
| Items disappear silently | `beforeSend` returned `null`, or it threw (the original is then sent and a warning logged). | Enable `debug: true` and read the `[sauron]` logs. |
|
|
1020
|
+
| Events lost when a tab closes after a busy session | The unload beacon chunk exceeded 64 KiB, or `sendBeacon` is unavailable. | Nothing to do — the payload is parked in `localStorage` and posted on the next page load. |
|
|
1021
|
+
| Nothing persists in private mode | `localStorage`/`sessionStorage` are blocked, so the offline queue is disabled and ids fall back to in-memory. | Expected; reduce `flushIntervalMs` to shorten the loss window. |
|
|
1022
|
+
| No transactions | `performance` defaults to `false`. | `init({ performance: true })`, or call `trackTransaction()` manually. |
|
|
1023
|
+
| Screen is always `null` | Neither `init({ screen })`, `setScreen()` nor `screenTracking: true` was used. | Set one of them. |
|
|
1024
|
+
| No debug output | `debug` defaults to `false`. | `init({ debug: true })`; logs are prefixed `[sauron]`. |
|
|
97
1025
|
|
|
98
1026
|
## Development
|
|
99
1027
|
|
|
100
1028
|
```bash
|
|
101
1029
|
npm install
|
|
102
|
-
npm run typecheck
|
|
103
|
-
npm
|
|
104
|
-
npm test
|
|
1030
|
+
npm run typecheck # tsc --noEmit
|
|
1031
|
+
npm test # vitest run
|
|
1032
|
+
npm run test:watch # vitest
|
|
1033
|
+
npm run build # tsup -> dist/ (esm + cjs + d.ts + sourcemaps)
|
|
1034
|
+
npm run dev # tsup --watch
|
|
105
1035
|
```
|
|
106
1036
|
|
|
1037
|
+
`npm run prepublishOnly` chains typecheck, tests and build.
|
|
1038
|
+
|
|
107
1039
|
## License
|
|
108
1040
|
|
|
109
1041
|
AGPL-3.0-only — GNU Affero General Public License v3.0.
|
|
1042
|
+
|
|
1043
|
+
Repo: <https://github.com/edraj/sauron> — wiki:
|
|
1044
|
+
<https://github.com/edraj/sauron/wiki>
|