@backtrack-js/browser 0.4.0 → 0.4.2

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/README.md CHANGED
@@ -1,291 +1,364 @@
1
- # Backtrack (@backtrack-js/browser)
2
-
3
- [![npm version](https://img.shields.io/npm/v/@backtrack-js/browser.svg)](https://www.npmjs.com/package/@backtrack-js/browser)
4
- [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
-
6
- **Backtrack** is a privacy-first, client-side session recorder and time-travel engine for web applications. It captures pre-bug context (DOM mutations, console logs, network requests, navigation, and unhandled errors) in a rolling local ring-buffer, allowing developers to backtrack user sessions and reproduce bugs with exact fidelity.
7
-
8
- - 🔒 **Privacy-First:** Strict data masking (passwords, credit cards, inputs, authorization headers). No data leaves the browser unless explicitly exported.
9
- - ⚡ **Lightweight & Framework-Agnostic:** Pure TypeScript core. Zero framework dependencies (no React required in your client bundle).
10
- - 🔄 **Rolling Ring Buffer:** Continuously stores the last $N$ minutes of user activity in IndexedDB with automatic retention and storage limits.
11
- - 🎬 **Full Session Replay:** Powered by [rrweb](https://github.com/rrweb-io/rrweb) with synchronized timeline events.
12
- - 🛠 **Built-in Incident Viewer:** Includes an interactive web inspector and CLI to replay incidents offline.
13
-
14
- ---
15
-
16
- ## Installation
17
-
18
- ```bash
19
- # npm
20
- npm install @backtrack-js/browser
21
-
22
- # yarn
23
- yarn add @backtrack-js/browser
24
-
25
- # pnpm
26
- pnpm add @backtrack-js/browser
27
- ```
28
-
29
- ---
30
-
31
- ## Quick Start
32
-
33
- ```typescript
34
- import { Backtrack } from '@backtrack-js/browser';
35
-
36
- // 1. Initialize Backtrack
37
- const recorder = new Backtrack({
38
- bufferMinutes: 5, // Keep last 5 minutes of activity in rolling buffer
39
- afterErrorSeconds: 15, // Keep recording for 15 seconds after an error occurs
40
- maxStorageMb: 50, // Retention target for rolling buffer (protected incidents are never auto-pruned)
41
- captureHttpStatus: [500, 502, 503, 504], // Auto-trigger on server errors
42
- network: {
43
- capturePayloads: false, // Bodies are disabled by default for privacy
44
- maxPayloadSize: 64 * 1024
45
- },
46
- privacy: {
47
- maskAllInputs: true, // Mask all form inputs by default
48
- blockMedia: true // Replace images/media with placeholders
49
- }
50
- });
51
-
52
- // 2. Start recording
53
- await recorder.start();
54
-
55
- // 3. (Optional) Manually trigger an incident on user feedback or caught error
56
- const incidentId = await recorder.capture('User reported payment bug', 30);
57
- console.log('Incident captured:', incidentId);
58
- ```
59
-
60
- ---
61
-
62
- ## Privacy & Data Masking
63
-
64
- Backtrack is designed with strict security defaults:
65
-
66
- - **Inputs & Forms:** All `<input>`, `<textarea>`, and `<select>` values are masked by default (`maskAllInputs: true`).
67
- - **Network Headers:** Authorization, Cookies, API keys, and Bearer tokens are automatically redacted.
68
- - **Sensitive Selectors:** Use standard selectors or CSS classes to protect proprietary or personal data:
69
-
70
- ```typescript
71
- const recorder = new Backtrack({
72
- privacy: {
73
- maskAllInputs: true,
74
- blockMedia: true,
75
- blockSelector: '.backtrack-block, [data-private]', // Completely hides elements in replay
76
- maskTextSelector: '.backtrack-mask, .customer-pII', // Scrambles text content
77
- sanitizeUrl: (url) => {
78
- // Remove sensitive query parameters
79
- url.searchParams.delete('token');
80
- return url.toString();
81
- }
82
- }
83
- });
84
- ```
85
-
86
- ---
87
-
88
- ## Network & Payload Capture
89
-
90
- Network requests and responses can be configured using `network` options:
91
-
92
- ```typescript
93
- const recorder = new Backtrack({
94
- network: {
95
- capturePayloads: false,
96
- maxPayloadSize: 64 * 1024
97
- }
98
- });
99
- ```
100
-
101
- - **Bodies are not captured by default (`capturePayloads: false`):** Request and response bodies are disabled by default to prevent unintentional data leakage. HTTP method, URL, status, timing, and sanitized headers continue to be captured.
102
- - **Enabling bodies increases the risk of PII:** Enabling `capturePayloads: true` should be done mindfully according to your compliance and privacy requirements.
103
- - **Sanitization remains active:** Even when payload capture is explicitly enabled, Backtrack continues to sanitize and redact known sensitive keys (passwords, tokens, credentials, etc.) and patterns (Bearer tokens, emails, CPFs, cards).
104
- - **`maxPayloadSize` is a limit per payload, not per incident:** It bounds each individual request or response body (default is `64 * 1024` bytes). Payloads exceeding this limit are truncated safely with a truncation marker.
105
-
106
- ---
107
-
108
- ## Capturing Incidents
109
-
110
- ### Automatic Triggers
111
- Backtrack automatically triggers and freezes an incident when:
112
- 1. An unhandled window exception occurs (`window.onerror`).
113
- 2. An unhandled promise rejection occurs (`unhandledrejection`).
114
- 3. An HTTP request returns a matching error status (`captureHttpStatus`).
115
-
116
- ### Manual Capture
117
- You can trigger incident recording manually anywhere in your code (e.g. from an error boundary or user feedback modal):
118
-
119
- ```typescript
120
- // Capture the last 60 seconds of context
121
- const incidentId = await recorder.capture('Checkout error', 60);
122
-
123
- // Export the complete incident artifact as a JSON object
124
- const artifact = await recorder.exportIncident(incidentId);
125
-
126
- // Download or send artifact to your support/logging service
127
- const jsonBlob = new Blob([JSON.stringify(artifact, null, 2)], { type: 'application/json' });
128
- ```
129
-
130
- ### Exception Capture
131
- In React Error Boundaries or try/catch blocks:
132
-
133
- ```typescript
134
- recorder.captureException(error, {
135
- source: 'react',
136
- componentStack: errorInfo.componentStack
137
- });
138
- ```
139
-
140
- ---
141
-
142
- ## Remote Transport & beforeSend
143
-
144
- Backtrack allows applications to automatically dispatch finalized incidents to any remote endpoint or telemetry backend using `transport` and `beforeSend`:
145
-
146
- ```typescript
147
- const recorder = new Backtrack({
148
- transport: {
149
- async send(artifact) {
150
- const response = await fetch('/api/backtrack/incidents', {
151
- method: 'POST',
152
- headers: {
153
- 'content-type': 'application/json'
154
- },
155
- body: JSON.stringify(artifact)
156
- });
157
-
158
- if (!response.ok) {
159
- throw new Error(`Upload failed: ${response.status}`);
160
- }
161
- }
162
- },
163
-
164
- beforeSend(artifact) {
165
- if (artifact.environment.url.includes('/healthcheck')) {
166
- return null;
167
- }
168
-
169
- return artifact;
170
- }
171
- });
172
- ```
173
-
174
- ### Dispatch Flow & Semantics
175
-
176
- - **Sent Only When Finalized:** Incidents are dispatched only after they have been completely finalized and safely written to IndexedDB.
177
- ```text
178
- incidente finalizado
179
- ↓
180
- montar artefato
181
- ↓
182
- beforeSend
183
- ↓
184
- null? cancela envio
185
- ↓
186
- transport.send
187
- ```
188
- - **Role of `beforeSend`:**
189
- - Affects **only** the automated transmission via `transport.send`.
190
- - Does **not** mutate the artifact stored in local IndexedDB.
191
- - Does **not** affect `getArtifact()` or explicit file downloads via `exportIncident()`.
192
- - Returning `null` cancels the upload.
193
- - If `beforeSend` throws an error, the upload is aborted cleanly without affecting the application or the recorded incident.
194
- - **Fault Isolation:** Network or transport errors will never break the host application, reject user captures, delete local incidents, prevent finalization, or trigger unhandled promise rejections.
195
- - **Concurrency & Delivery Guarantees:**
196
- - Each finalized incident triggers at most one upload attempt.
197
- - Multiple incidents can upload concurrently.
198
- - `stop()` does not wait for pending network uploads.
199
- - There is currently no delivery guarantee (persistent retry queue, offline backoff, etc.); if transport fails, the incident remains saved in local IndexedDB and can be accessed or resent by the application.
200
-
201
- ---
202
-
203
- ## Release and trace correlation
204
-
205
- Backtrack artifacts (`formatVersion: 2`) provide an observability `context` to correlate client-side replays with backend traces, application releases, and environments.
206
-
207
- ### Static Context
208
-
209
- Configure static metadata when initializing Backtrack:
210
-
211
- ```typescript
212
- const recorder = new Backtrack({
213
- context: {
214
- release: 'checkout-web@2.14.0',
215
- environment: 'production',
216
- traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
217
- spanId: '00f067aa0ba902b7'
218
- }
219
- });
220
- ```
221
-
222
- ### Dynamic Context (`getContext`)
223
-
224
- When trace IDs or active environments change dynamically during user navigation (e.g. from OpenTelemetry, Datadog, Sentry, or custom APM SDKs), use `getContext` to evaluate the latest context at incident export time:
225
-
226
- ```typescript
227
- const recorder = new Backtrack({
228
- context: {
229
- release: 'checkout-web@2.14.0',
230
- environment: 'production'
231
- },
232
- getContext: async () => {
233
- const activeSpan = tracer.getActiveSpan();
234
- const spanContext = activeSpan?.spanContext();
235
-
236
- return {
237
- release: 'checkout-web@2.14.0',
238
- environment: 'production',
239
- traceId: spanContext?.traceId,
240
- spanId: spanContext?.spanId
241
- };
242
- }
243
- });
244
- ```
245
-
246
- ### Correlation Semantics
247
-
248
- - **Precedence:** `getContext() > context (static) > environment metadata`.
249
- - **Trace correlation scope:** Backtrack **only correlates** external trace and span identifiers supplied by your application. It does **not** generate backend traces, start trace spans, or perform distributed instrumentation on its own.
250
- - **Normalization:** `traceId` (32 hex characters) and `spanId` (16 hex characters) are validated and normalized to lowercase. A `spanId` cannot be supplied without an accompanying `traceId`.
251
- - **Fault Resilience:** If `getContext()` throws an error or rejects, incident export continues safely using available static context without failing the export or losing incident data.
252
-
253
- ---
254
-
255
- ## Inspecting Incidents (Viewer)
256
-
257
- Backtrack includes an offline visualizer with video replay, console logs, network inspection, and breadcrumbs.
258
-
259
- ### Launch the Viewer CLI
260
- Run the embedded CLI to launch the local visualizer:
261
-
262
- ```bash
263
- npx backtrack
264
- ```
265
-
266
- This starts a local server at `http://localhost:5173/` and opens your default browser. Drag and drop any exported incident `.json` file to replay it!
267
-
268
- ---
269
-
270
- ## API Reference
271
-
272
- ### `Backtrack` (`FlightRecorder`)
273
-
274
- | Method | Return Type | Description |
275
- | --- | --- | --- |
276
- | `start()` | `Promise<void>` | Initializes storage and begins recording. |
277
- | `stop()` | `Promise<void>` | Stops recording, flushes pending batches to storage, and detaches listeners. |
278
- | `capture(reason?, windowSeconds?)` | `Promise<string>` | Manually captures and finalizes an incident. Returns incident ID. |
279
- | `captureException(error, context?)` | `Promise<string \| undefined> \| void` | Records a caught exception and triggers an incident. |
280
- | `listIncidents()` | `Promise<IncidentSummary[]>` | Lists all stored incidents. |
281
- | `getArtifact(incidentId)` | `Promise<FlightRecorderArtifact>` | Retrieves the full artifact for an incident (v1 or v2). |
282
- | `exportIncident(incidentId)` | `Promise<FlightRecorderArtifact>` | Exports the artifact and marks it finalized. |
283
- | `deleteIncident(incidentId)` | `Promise<void>` | Deletes an incident from local storage. |
284
- | `clear()` | `Promise<void>` | Clears all stored chunks, sessions, and incidents. |
285
- | `getHealth()` | `RecorderHealth` | Returns current buffer status, storage usage, and state. |
286
-
287
- ---
288
-
289
- ## License
290
-
291
- [MIT](LICENSE)
1
+ # Backtrack
2
+
3
+ A flight recorder for your web app. Replay the exact moments before a bug, privately and offline.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@backtrack-js/browser.svg)](https://www.npmjs.com/package/@backtrack-js/browser)
6
+ [![license](https://img.shields.io/badge/license-Free_to_Use-blue.svg)](LICENSE)
7
+
8
+ <!-- TODO: add a GIF or screenshot of the Incident Viewer here (this is the highest-impact change) -->
9
+ <!-- ![Backtrack Incident Viewer](./docs/viewer.gif) -->
10
+
11
+ Your users hit a bug you can't reproduce. Error trackers tell you what broke, but not what the user did before it did.
12
+
13
+ Backtrack keeps the last few minutes of DOM changes, clicks, network calls, console logs and errors in a rolling local buffer. When something breaks (or the user asks for help), it freezes that buffer into a replayable incident file. Open it in the built-in viewer and press play.
14
+
15
+ - **Private by default.** Passwords, card numbers, CPFs and form inputs are masked. Request and response bodies are off unless you turn them on. Nothing leaves the browser unless you export an incident or configure a transport.
16
+ - **Light on the page.** Recording runs into a ring buffer in IndexedDB with automatic retention, so old events are dropped instead of piling up.
17
+ - **Framework-agnostic.** Pure TypeScript core, no React or other framework in your client bundle. ESM and CommonJS builds.
18
+ - **Replay offline.** An interactive viewer with DOM playback, a synchronized timeline, and console and network panels. No account, no server.
19
+ - **Readable production stack traces.** `backtrack symbolize` maps minified frames like `app.min.js:1:48213` back to your original TypeScript, with the surrounding source lines.
20
+ - **Send it where you want.** `transport` and `beforeSend` let you forward incidents to your own backend or observability stack.
21
+
22
+ ---
23
+
24
+ ## Why Backtrack?
25
+
26
+ | Feature | Error trackers | Hosted session replay | Backtrack |
27
+ | :--- | :---: | :---: | :---: |
28
+ | Shows the error and stack trace | ✅ | ✅ | ✅ |
29
+ | Shows what the user did before it | ⚠️ limited breadcrumbs | ✅ | ✅ |
30
+ | Data stays in the browser by default | ❌ | ❌ | ✅ |
31
+ | Works fully offline | ❌ | ❌ | ✅ |
32
+ | Only records around incidents | n/a | ❌ usually continuous upload | ✅ rolling buffer |
33
+
34
+ Backtrack doesn't replace your error tracker. It gives you the context your error tracker is missing, and you can correlate the two with `traceId` and `release` (see [Release and trace correlation](#release-and-trace-correlation)).
35
+
36
+ ---
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ # npm
42
+ npm install @backtrack-js/browser
43
+
44
+ # yarn
45
+ yarn add @backtrack-js/browser
46
+
47
+ # pnpm
48
+ pnpm add @backtrack-js/browser
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Quick Start
54
+
55
+ ```typescript
56
+ import { Backtrack } from '@backtrack-js/browser';
57
+
58
+ const recorder = new Backtrack({
59
+ bufferMinutes: 5, // keep the last 5 minutes in the rolling buffer
60
+ afterErrorSeconds: 15, // keep recording 15s after an error
61
+ });
62
+
63
+ await recorder.start();
64
+
65
+ // Optional: capture manually, e.g. from a "Report a problem" button
66
+ const incidentId = await recorder.capture('User reported payment bug', 30);
67
+ ```
68
+
69
+ Then inspect it:
70
+
71
+ ```bash
72
+ npx backtrack
73
+ ```
74
+
75
+ Drag an exported incident `.json` into the viewer and hit play.
76
+
77
+ ---
78
+
79
+ ## Readable production stack traces (`backtrack symbolize`)
80
+
81
+ Production bundles are minified, so a stack frame like `app.3f9a1c.js:1:48213` tells you nothing. `backtrack symbolize` reads your source maps and rewrites the incident's errors with the original file, line, column and the surrounding source code.
82
+
83
+ ```bash
84
+ npx backtrack symbolize <incident> --sourcemaps <directory> [options]
85
+ ```
86
+
87
+ | Argument / option | Description |
88
+ | :--- | :--- |
89
+ | `<incident>` | Path to an exported incident: `.json`, `.ffr.json`, `.gz` or `.ffr.json.gz`. Gzip is detected automatically. |
90
+ | `--sourcemaps <directory>` | Directory containing your `.js.map`, `.mjs.map` and `.cjs.map` files. Searched recursively (e.g. `./dist`, `./build`). |
91
+ | `--output <file>` | Custom output path. Defaults to `<name>.symbolicated.ffr.json` next to the original. The output can never overwrite the input file. |
92
+ | `--context-lines <number>` | Lines of original source shown before and after the failing line. Range 0–10, default 3. |
93
+ | `-h, --help` | Show help. |
94
+
95
+ ### Example
96
+
97
+ ```bash
98
+ npx backtrack symbolize ./incidents/checkout-bug.ffr.json --sourcemaps ./dist --context-lines 5
99
+ ```
100
+
101
+ ```text
102
+ [Backtrack] Symbolication concluída.
103
+
104
+ Incidente: inc_1727500000_3f2a
105
+ Erros encontrados: 1
106
+ Frames resolvidos: 4
107
+ Frames não resolvidos: 0
108
+ Saída: /projects/app/incidents/checkout-bug.symbolicated.ffr.json
109
+ ```
110
+
111
+ If some frames have no matching source map, the command reports a partial symbolication with warnings instead of failing.
112
+
113
+ Open the `.symbolicated.ffr.json` file in the viewer (`npx backtrack`) and the error tab shows the resolved stack trace, with the failing line highlighted:
114
+
115
+ ```text
116
+ applyCoupon src/cart/coupon.ts:42:18
117
+
118
+ 40 function applyCoupon(cart, coupon) {
119
+ 41 // coupon discount might be missing from API
120
+ 42 const off = coupon.discount.percent; <-- highlighted
121
+ 43 return cart.total * (1 - off / 100);
122
+ 44 }
123
+ ```
124
+
125
+ ### What it does (and doesn't do)
126
+
127
+ - **Validates safely:** Reads the incident (up to 50 MB, gzip supported) and validates its schema with a strict validator. The original file is never modified.
128
+ - **Maps V8 frames:** Finds error events that carry a stack and maps each minified frame with [@jridgewell/trace-mapping](https://github.com/jridgewell/trace-mapping).
129
+ - **Extracts source context:** Extracts the original code from `sourcesContent`, so your source maps must include it.
130
+ - **Doesn't leak local paths:** File paths are normalized (e.g. `C:\Users\alice\...` or `/home/bob/...` become paths starting at `src/`).
131
+ - **Atomic write:** Writes the result atomically (to a `.tmp` file, then renames) and stores it in a new `resolvedStack` field.
132
+
133
+ ---
134
+
135
+ ## Privacy & Data Masking
136
+
137
+ Backtrack is designed with strict security defaults:
138
+
139
+ - **Inputs & Forms:** All `<input>`, `<textarea>`, and `<select>` values are masked by default (`maskAllInputs: true`).
140
+ - **Network Headers:** Authorization, Cookies, API keys, and Bearer tokens are automatically redacted.
141
+ - **Sensitive Selectors:** Use standard selectors or CSS classes to protect proprietary or personal data:
142
+
143
+ ```typescript
144
+ const recorder = new Backtrack({
145
+ privacy: {
146
+ maskAllInputs: true,
147
+ blockMedia: true,
148
+ blockSelector: '.backtrack-block, [data-private]', // Completely hides elements in replay
149
+ maskTextSelector: '.backtrack-mask, .customer-pII', // Scrambles text content
150
+ sanitizeUrl: (url) => {
151
+ // Remove sensitive query parameters
152
+ url.searchParams.delete('token');
153
+ return url.toString();
154
+ }
155
+ }
156
+ });
157
+ ```
158
+
159
+ ---
160
+
161
+ ## Network & Payload Capture
162
+
163
+ Network requests and responses can be configured using `network` options:
164
+
165
+ ```typescript
166
+ const recorder = new Backtrack({
167
+ network: {
168
+ capturePayloads: false, // Bodies are disabled by default for privacy
169
+ maxPayloadSize: 64 * 1024
170
+ }
171
+ });
172
+ ```
173
+
174
+ - **Bodies are not captured by default (`capturePayloads: false`):** Request and response bodies are disabled by default to prevent unintentional data leakage. HTTP method, URL, status, timing, and sanitized headers continue to be captured.
175
+ - **Enabling bodies increases the risk of PII:** Enabling `capturePayloads: true` should be done mindfully according to your compliance and privacy requirements.
176
+ - **Sanitization remains active:** Even when payload capture is explicitly enabled, Backtrack continues to sanitize and redact known sensitive keys (passwords, tokens, credentials, etc.) and patterns (Bearer tokens, emails, CPFs, cards).
177
+ - **`maxPayloadSize` is a limit per payload, not per incident:** It bounds each individual request or response body (default is `64 * 1024` bytes). Payloads exceeding this limit are truncated safely with a truncation marker.
178
+
179
+ ---
180
+
181
+ ## Capturing Incidents
182
+
183
+ ### Automatic Triggers
184
+ Backtrack automatically triggers and freezes an incident when:
185
+ 1. An unhandled window exception occurs (`window.onerror`).
186
+ 2. An unhandled promise rejection occurs (`unhandledrejection`).
187
+ 3. An HTTP request returns a matching error status (`captureHttpStatus`).
188
+
189
+ ### Manual Capture
190
+ You can trigger incident recording manually anywhere in your code (e.g. from an error boundary or user feedback modal):
191
+
192
+ ```typescript
193
+ // Capture the last 60 seconds of context
194
+ const incidentId = await recorder.capture('Checkout error', 60);
195
+
196
+ // Export the complete incident artifact as a JSON object
197
+ const artifact = await recorder.exportIncident(incidentId);
198
+
199
+ // Download or send artifact to your support/logging service
200
+ const jsonBlob = new Blob([JSON.stringify(artifact, null, 2)], { type: 'application/json' });
201
+ ```
202
+
203
+ ### Exception Capture
204
+ In React Error Boundaries or try/catch blocks:
205
+
206
+ ```typescript
207
+ recorder.captureException(error, {
208
+ source: 'react',
209
+ componentStack: errorInfo.componentStack
210
+ });
211
+ ```
212
+
213
+ ---
214
+
215
+ ## Remote Transport & beforeSend
216
+
217
+ Backtrack allows applications to automatically dispatch finalized incidents to any remote endpoint or telemetry backend using `transport` and `beforeSend`:
218
+
219
+ ```typescript
220
+ const recorder = new Backtrack({
221
+ transport: {
222
+ async send(artifact) {
223
+ const response = await fetch('/api/backtrack/incidents', {
224
+ method: 'POST',
225
+ headers: {
226
+ 'content-type': 'application/json'
227
+ },
228
+ body: JSON.stringify(artifact)
229
+ });
230
+
231
+ if (!response.ok) {
232
+ throw new Error(`Upload failed: ${response.status}`);
233
+ }
234
+ }
235
+ },
236
+
237
+ beforeSend(artifact) {
238
+ if (artifact.environment.url.includes('/healthcheck')) {
239
+ return null;
240
+ }
241
+
242
+ return artifact;
243
+ }
244
+ });
245
+ ```
246
+
247
+ ### Dispatch Flow & Semantics
248
+
249
+ - **Sent Only When Finalized:** Incidents are dispatched only after they have been completely finalized and safely written to IndexedDB.
250
+ ```text
251
+ incident finalized
252
+ ↓
253
+ build artifact
254
+ ↓
255
+ beforeSend
256
+ ↓
257
+ null? cancel upload
258
+ ↓
259
+ transport.send
260
+ ```
261
+ - **Role of `beforeSend`:**
262
+ - Affects **only** the automated transmission via `transport.send`.
263
+ - Does **not** mutate the artifact stored in local IndexedDB.
264
+ - Does **not** affect `getArtifact()` or explicit file downloads via `exportIncident()`.
265
+ - Returning `null` cancels the upload.
266
+ - If `beforeSend` throws an error, the upload is aborted cleanly without affecting the application or the recorded incident.
267
+ - **Fault Isolation:** Network or transport errors will never break the host application, reject user captures, delete local incidents, prevent finalization, or trigger unhandled promise rejections.
268
+ - **Concurrency & Delivery Guarantees:**
269
+ - Each finalized incident triggers at most one upload attempt.
270
+ - Multiple incidents can upload concurrently.
271
+ - `stop()` does not wait for pending network uploads.
272
+ - There is currently no delivery guarantee (persistent retry queue, offline backoff, etc.); if transport fails, the incident remains saved in local IndexedDB and can be accessed or resent by the application.
273
+
274
+ ---
275
+
276
+ ## Release and trace correlation
277
+
278
+ Backtrack artifacts (`formatVersion: 2`) provide an observability `context` to correlate client-side replays with backend traces, application releases, and environments.
279
+
280
+ ### Static Context
281
+
282
+ Configure static metadata when initializing Backtrack:
283
+
284
+ ```typescript
285
+ const recorder = new Backtrack({
286
+ context: {
287
+ release: 'checkout-web@2.14.0',
288
+ environment: 'production',
289
+ traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
290
+ spanId: '00f067aa0ba902b7'
291
+ }
292
+ });
293
+ ```
294
+
295
+ ### Dynamic Context (`getContext`)
296
+
297
+ When trace IDs or active environments change dynamically during user navigation (e.g. from OpenTelemetry, Datadog, Sentry, or custom APM SDKs), use `getContext` to evaluate the latest context at incident export time:
298
+
299
+ ```typescript
300
+ const recorder = new Backtrack({
301
+ context: {
302
+ release: 'checkout-web@2.14.0',
303
+ environment: 'production'
304
+ },
305
+ getContext: async () => {
306
+ const activeSpan = tracer.getActiveSpan();
307
+ const spanContext = activeSpan?.spanContext();
308
+
309
+ return {
310
+ release: 'checkout-web@2.14.0',
311
+ environment: 'production',
312
+ traceId: spanContext?.traceId,
313
+ spanId: spanContext?.spanId
314
+ };
315
+ }
316
+ });
317
+ ```
318
+
319
+ ### Correlation Semantics
320
+
321
+ - **Precedence:** `getContext() > context (static) > environment metadata`.
322
+ - **Trace correlation scope:** Backtrack **only correlates** external trace and span identifiers supplied by your application. It does **not** generate backend traces, start trace spans, or perform distributed instrumentation on its own.
323
+ - **Normalization:** `traceId` (32 hex characters) and `spanId` (16 hex characters) are validated and normalized to lowercase. A `spanId` cannot be supplied without an accompanying `traceId`.
324
+ - **Fault Resilience:** If `getContext()` throws an error or rejects, incident export continues safely using available static context without failing the export or losing incident data.
325
+
326
+ ---
327
+
328
+ ## Inspecting Incidents (Viewer)
329
+
330
+ Backtrack includes an offline visualizer with video replay, console logs, network inspection, and breadcrumbs.
331
+
332
+ ### Launch the Viewer CLI
333
+ Run the embedded CLI to launch the local visualizer:
334
+
335
+ ```bash
336
+ npx backtrack
337
+ ```
338
+
339
+ This starts a local server at `http://localhost:5173/` and opens your default browser. Drag and drop any exported incident `.json` file to replay it!
340
+
341
+ ---
342
+
343
+ ## API Reference
344
+
345
+ ### `Backtrack`
346
+
347
+ | Method | Return Type | Description |
348
+ | --- | --- | --- |
349
+ | `start()` | `Promise<void>` | Initializes storage and begins recording. |
350
+ | `stop()` | `Promise<void>` | Stops recording, flushes pending batches to storage, and detaches listeners. |
351
+ | `capture(reason?, windowSeconds?)` | `Promise<string>` | Manually captures and finalizes an incident. Returns incident ID. |
352
+ | `captureException(error, context?)` | `Promise<string \| undefined> \| void` | Records a caught exception and triggers an incident. |
353
+ | `listIncidents()` | `Promise<IncidentSummary[]>` | Lists all stored incidents. |
354
+ | `getArtifact(incidentId)` | `Promise<FlightRecorderArtifact>` | Retrieves the full artifact for an incident (v1 or v2). |
355
+ | `exportIncident(incidentId)` | `Promise<FlightRecorderArtifact>` | Exports the artifact and marks it finalized. |
356
+ | `deleteIncident(incidentId)` | `Promise<void>` | Deletes an incident from local storage. |
357
+ | `clear()` | `Promise<void>` | Clears all stored chunks, sessions, and incidents. |
358
+ | `getHealth()` | `RecorderHealth` | Returns current buffer status, storage usage, and state. |
359
+
360
+ ---
361
+
362
+ ## License
363
+
364
+ [Backtrack Free-Use License](LICENSE) — Free for personal and commercial integration. Redistribution, copying, or creating derivative/competing works is strictly prohibited.