@spectosh/browser 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +44 -10
- package/dist/specto-browser.cjs +23 -21
- package/dist/specto-browser.js +2224 -1583
- package/package.json +22 -7
- package/src/index.js +36 -5
- package/src/recorder.js +664 -176
- package/src/recorder.worker.js +14 -25
- package/src/uploader.js +95 -0
package/src/recorder.js
CHANGED
|
@@ -1,28 +1,39 @@
|
|
|
1
|
-
// Specto recorder SDK
|
|
1
|
+
// Specto recorder SDK.
|
|
2
2
|
//
|
|
3
3
|
// Captures, in one correlated stream:
|
|
4
|
-
// - DOM: rrweb full snapshot + incremental mutations
|
|
5
|
-
//
|
|
6
|
-
// -
|
|
7
|
-
// -
|
|
4
|
+
// - DOM: rrweb full snapshot + incremental mutations (+ a fresh checkpoint
|
|
5
|
+
// every 5 minutes, so one lost batch never ruins the rest of a replay)
|
|
6
|
+
// - console: log/info/warn/error (PII-scrubbed; off in strict privacy)
|
|
7
|
+
// - network: fetch + XHR (method, url, status, duration) plus devtools-style
|
|
8
|
+
// request details — bodies and auth headers are never captured
|
|
9
|
+
// - events: JS errors (with scrubbed stack frames), rage clicks, SPA
|
|
10
|
+
// navigations, custom events (track) and user identity (identify)
|
|
11
|
+
// - backend traces (opt-in): a W3C traceparent header on same-origin
|
|
12
|
+
// requests; the request's trace id links it to the server's spans
|
|
13
|
+
// - heatmaps: each click's page position and a selector (tag, id,
|
|
14
|
+
// classes — never text), and how far down each page view scrolled
|
|
8
15
|
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
16
|
+
// Sessions: one visitor's continuous activity, kept across page loads in
|
|
17
|
+
// sessionStorage; a new session starts after 30 minutes without interaction
|
|
18
|
+
// or after 4 hours. Batches are numbered so the server de-duplicates retries.
|
|
12
19
|
//
|
|
13
|
-
//
|
|
14
|
-
// the
|
|
20
|
+
// Privacy: inputs are always masked; strict privacy masks all text and keeps
|
|
21
|
+
// only the path of recorded URLs;
|
|
22
|
+
// `specto-mask` / `specto-block` classes for fine control; sensitive
|
|
23
|
+
// attributes, URL credentials and PII-looking text are scrubbed in the
|
|
24
|
+
// browser. Honors Do-Not-Track / Global Privacy Control, an opt-out flag, and
|
|
25
|
+
// consent mode (nothing is recorded or stored until Specto.consent(true)).
|
|
15
26
|
import { record } from 'rrweb'
|
|
27
|
+
import { createUploader } from './uploader.js'
|
|
16
28
|
|
|
17
|
-
const
|
|
29
|
+
export const SDK_VERSION = '0.2.0'
|
|
18
30
|
|
|
31
|
+
// ---- privacy helpers --------------------------------------------------------
|
|
19
32
|
// Attribute scrubbing — rrweb masks text/inputs but NOT element attributes,
|
|
20
33
|
// which routinely carry PII (data-*, title, alt, placeholder, aria-label).
|
|
21
|
-
// We rewrite them to '***' in the serialized node tree before upload, so the
|
|
22
|
-
// PII never leaves the browser. This is the gap most replay tools leave open.
|
|
23
34
|
const SENSITIVE_ATTR = (k) => {
|
|
24
35
|
k = k.toLowerCase()
|
|
25
|
-
return k.startsWith('data-') || k === 'title' || k === 'alt' || k === 'placeholder' || k === 'aria-label'
|
|
36
|
+
return k.startsWith('data-') || k === 'title' || k === 'alt' || k === 'placeholder' || k === 'aria-label' || k === 'value'
|
|
26
37
|
}
|
|
27
38
|
function scrubAttrMap(attrs) {
|
|
28
39
|
if (!attrs || typeof attrs !== 'object') return
|
|
@@ -35,9 +46,10 @@ function scrubNode(n) {
|
|
|
35
46
|
if (n.attributes) scrubAttrMap(n.attributes)
|
|
36
47
|
if (Array.isArray(n.childNodes)) n.childNodes.forEach(scrubNode)
|
|
37
48
|
}
|
|
38
|
-
function scrubEvent(e) {
|
|
49
|
+
function scrubEvent(e, strict) {
|
|
39
50
|
try {
|
|
40
|
-
if (e.type ===
|
|
51
|
+
if (e.type === 4 && typeof e.data?.href === 'string') e.data.href = scrubUrl(e.data.href, strict) // Meta: the page address
|
|
52
|
+
else if (e.type === 2 && e.data?.node) scrubNode(e.data.node) // FullSnapshot
|
|
41
53
|
else if (e.type === 3 && e.data) { // IncrementalSnapshot (mutations)
|
|
42
54
|
if (Array.isArray(e.data.adds)) e.data.adds.forEach((a) => scrubNode(a.node))
|
|
43
55
|
if (Array.isArray(e.data.attributes)) e.data.attributes.forEach((a) => scrubAttrMap(a.attributes))
|
|
@@ -46,216 +58,692 @@ function scrubEvent(e) {
|
|
|
46
58
|
return e
|
|
47
59
|
}
|
|
48
60
|
|
|
61
|
+
// Free text the app itself produces (console lines, error messages) can carry
|
|
62
|
+
// PII. Redact the shapes that are never useful for debugging.
|
|
63
|
+
const TEXT_SCRUBBERS = [
|
|
64
|
+
[/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]'],
|
|
65
|
+
[/\beyJ[\w-]{6,}\.[\w-]{6,}\.[\w-]{6,}\b/g, '[jwt]'],
|
|
66
|
+
[/\b(Bearer|Basic)\s+[\w.~+/=-]{8,}/gi, '$1 [token]'],
|
|
67
|
+
[/\b(?:\d[ -]?){13,19}\b/g, '[number]'], // card / account numbers
|
|
68
|
+
[/\b(sk|pk|rk)_(live|test)_[\w]{8,}\b/g, '[key]'],
|
|
69
|
+
]
|
|
70
|
+
export function scrubText(s) {
|
|
71
|
+
let out = String(s ?? '')
|
|
72
|
+
for (const [re, rep] of TEXT_SCRUBBERS) out = out.replace(re, rep)
|
|
73
|
+
return out
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---- network capture helpers ------------------------------------------------
|
|
77
|
+
// fetch() accepts a string, a URL (has .href, NOT .url), a Request (has .url),
|
|
78
|
+
// or anything stringifiable.
|
|
79
|
+
function urlOf(input) {
|
|
80
|
+
if (typeof input === 'string') return input
|
|
81
|
+
if (input && typeof input.href === 'string') return input.href // URL
|
|
82
|
+
if (input && typeof input.url === 'string') return input.url // Request
|
|
83
|
+
return input == null ? '' : String(input)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const MAX_URL = 600
|
|
87
|
+
// Query strings routinely carry credentials; scrub values of suspicious keys
|
|
88
|
+
// before upload — same client-side-only redaction stance as DOM masking.
|
|
89
|
+
const SENSITIVE_PARAM = /(?:^|[-_.])(token|secret|password|passwd|auth|authorization|key|apikey|api[-_]?key|session|sid|code|signature|credential|email)s?$/i
|
|
90
|
+
// strict privacy keeps only the path: query strings carry search terms and
|
|
91
|
+
// record ids as often as credentials, and a hash route keeps its route but
|
|
92
|
+
// not its parameters (#/search?q=… → #/search). Ingest applies the same rule.
|
|
93
|
+
const routeOnly = (hash) => hash.split(/[?&=]/)[0]
|
|
94
|
+
function scrubUrl(u, dropQuery = false) {
|
|
95
|
+
const raw = String(u ?? '')
|
|
96
|
+
try {
|
|
97
|
+
const url = new URL(raw, location.href)
|
|
98
|
+
let changed = false
|
|
99
|
+
// userinfo (user:password@host) is a credential — never upload it
|
|
100
|
+
if (url.username || url.password) { url.username = ''; url.password = ''; changed = true }
|
|
101
|
+
if (dropQuery && (url.search || routeOnly(url.hash) !== url.hash)) { url.search = ''; url.hash = routeOnly(url.hash); changed = true }
|
|
102
|
+
for (const k of [...url.searchParams.keys()]) {
|
|
103
|
+
if (SENSITIVE_PARAM.test(k)) { url.searchParams.set(k, '***'); changed = true }
|
|
104
|
+
}
|
|
105
|
+
// fragments carry credentials too (OAuth implicit #access_token=…)
|
|
106
|
+
if (url.hash) {
|
|
107
|
+
const scrubbed = url.hash.replace(/([?&#]|^)([^=&?#]+)=([^&#]*)/g,
|
|
108
|
+
(m, sep, k) => (SENSITIVE_PARAM.test(k) ? `${sep}${k}=***` : m))
|
|
109
|
+
if (scrubbed !== url.hash) { url.hash = scrubbed; changed = true }
|
|
110
|
+
}
|
|
111
|
+
// emails in path segments (/users/jane@acme.io)
|
|
112
|
+
const path = scrubText(decodeURIComponent(url.pathname))
|
|
113
|
+
if (path !== decodeURIComponent(url.pathname)) { url.pathname = path; changed = true }
|
|
114
|
+
if (!changed) return raw.slice(0, MAX_URL)
|
|
115
|
+
const isRelative = !/^[a-z][a-z0-9+.-]*:/i.test(raw)
|
|
116
|
+
return (isRelative ? url.pathname + url.search + url.hash : url.href).slice(0, MAX_URL)
|
|
117
|
+
} catch { return scrubText(dropQuery ? raw.split('?')[0] : raw).slice(0, MAX_URL) }
|
|
118
|
+
}
|
|
119
|
+
const absoluteUrl = (u) => { try { return new URL(u, location.href).href } catch { return String(u ?? '') } }
|
|
120
|
+
|
|
121
|
+
// Response headers are captured via a small allowlist — never Set-Cookie,
|
|
122
|
+
// never anything auth-shaped.
|
|
123
|
+
const SAFE_HEADERS = ['content-type', 'content-length', 'content-encoding', 'cache-control', 'etag', 'vary', 'age', 'server-timing', 'x-request-id']
|
|
124
|
+
function pickHeaders(get) {
|
|
125
|
+
const out = {}
|
|
126
|
+
for (const h of SAFE_HEADERS) {
|
|
127
|
+
try { const v = get(h); if (v) out[h] = String(v).slice(0, 200) } catch { /* opaque response */ }
|
|
128
|
+
}
|
|
129
|
+
return Object.keys(out).length ? out : undefined
|
|
130
|
+
}
|
|
131
|
+
function headerValue(h, name) {
|
|
132
|
+
try {
|
|
133
|
+
if (!h) return undefined
|
|
134
|
+
if (typeof h.get === 'function') return h.get(name) || undefined
|
|
135
|
+
if (Array.isArray(h)) { const hit = h.find((p) => String(p?.[0]).toLowerCase() === name); return hit ? String(hit[1]) : undefined }
|
|
136
|
+
for (const k of Object.keys(h)) if (k.toLowerCase() === name) return String(h[k])
|
|
137
|
+
} catch { /* exotic headers value */ }
|
|
138
|
+
return undefined
|
|
139
|
+
}
|
|
140
|
+
// Size only — request bodies themselves never leave the page.
|
|
141
|
+
function bodySize(b) {
|
|
142
|
+
try {
|
|
143
|
+
if (b == null) return undefined
|
|
144
|
+
if (typeof b === 'string') return b.length
|
|
145
|
+
if (typeof Blob !== 'undefined' && b instanceof Blob) return b.size
|
|
146
|
+
if (b instanceof ArrayBuffer) return b.byteLength
|
|
147
|
+
if (ArrayBuffer.isView(b)) return b.byteLength
|
|
148
|
+
if (typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams) return String(b).length
|
|
149
|
+
return undefined // FormData / streams: unknown without reading — never read
|
|
150
|
+
} catch { return undefined }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Best-effort devtools-grade phases from PerformanceResourceTiming.
|
|
154
|
+
function attachTiming(payload, absUrl, startedAt) {
|
|
155
|
+
if (typeof performance === 'undefined' || !performance.getEntriesByName) return
|
|
156
|
+
setTimeout(() => {
|
|
157
|
+
try {
|
|
158
|
+
let best = null
|
|
159
|
+
for (const e of performance.getEntriesByName(absUrl, 'resource')) {
|
|
160
|
+
const gap = Math.abs(e.startTime - startedAt)
|
|
161
|
+
if (gap < 1500 && (!best || gap < Math.abs(best.startTime - startedAt))) best = e
|
|
162
|
+
}
|
|
163
|
+
if (!best) return
|
|
164
|
+
const d = payload.detail || (payload.detail = {})
|
|
165
|
+
if (best.transferSize) d.xfer = Math.round(best.transferSize)
|
|
166
|
+
if (best.decodedBodySize && d.resSize == null) d.resSize = Math.round(best.decodedBodySize)
|
|
167
|
+
// cross-origin without Timing-Allow-Origin zeroes every boundary except
|
|
168
|
+
// responseEnd — only trust phase math when responseStart is exposed
|
|
169
|
+
if (best.responseStart > 0) {
|
|
170
|
+
const tlsStart = best.secureConnectionStart > 0 ? best.secureConnectionStart : best.connectEnd
|
|
171
|
+
const phases = {
|
|
172
|
+
dns: best.domainLookupEnd - best.domainLookupStart,
|
|
173
|
+
tcp: tlsStart - best.connectStart,
|
|
174
|
+
tls: best.secureConnectionStart > 0 ? best.connectEnd - best.secureConnectionStart : 0,
|
|
175
|
+
ttfb: best.responseStart - best.requestStart,
|
|
176
|
+
dl: best.responseEnd - best.responseStart,
|
|
177
|
+
}
|
|
178
|
+
d.timing = {}
|
|
179
|
+
for (const k of Object.keys(phases)) if (phases[k] > 0) d.timing[k] = Math.round(phases[k] * 10) / 10
|
|
180
|
+
if (!Object.keys(d.timing).length) delete d.timing
|
|
181
|
+
}
|
|
182
|
+
} catch { /* never break the app */ }
|
|
183
|
+
}, 300)
|
|
184
|
+
}
|
|
185
|
+
|
|
49
186
|
function newId(prefix = 'rec_') {
|
|
50
187
|
const r = (typeof crypto !== 'undefined' && crypto.getRandomValues)
|
|
51
|
-
? Array.from(crypto.getRandomValues(new Uint8Array(
|
|
52
|
-
: Math.abs((Date.now() ^ (performance.now() * 1000)) | 0).toString(16)
|
|
188
|
+
? Array.from(crypto.getRandomValues(new Uint8Array(12))).map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
189
|
+
: Math.abs((Date.now() ^ (performance.now() * 1000)) | 0).toString(16) + Math.random().toString(16).slice(2, 10)
|
|
53
190
|
return prefix + r
|
|
54
191
|
}
|
|
55
192
|
|
|
193
|
+
// The session key: sent with every batch of the session, so ingest accepts
|
|
194
|
+
// appends only from whoever started it — an id alone (a replay link shows
|
|
195
|
+
// it) can't write to the session. 128 random bits; none without a CSPRNG.
|
|
196
|
+
function newSessionKey() {
|
|
197
|
+
if (typeof crypto === 'undefined' || !crypto.getRandomValues) return null
|
|
198
|
+
const b = crypto.getRandomValues(new Uint8Array(16))
|
|
199
|
+
return btoa(String.fromCharCode(...b)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---- storage (all access guarded: private modes and sandboxed iframes throw)
|
|
203
|
+
const store = {
|
|
204
|
+
get(area, k) { try { return JSON.parse(window[area].getItem(k)) } catch { return null } },
|
|
205
|
+
set(area, k, v) { try { window[area].setItem(k, JSON.stringify(v)) } catch { /* unavailable */ } },
|
|
206
|
+
del(area, k) { try { window[area].removeItem(k) } catch { /* unavailable */ } },
|
|
207
|
+
}
|
|
208
|
+
const OPTOUT_KEY = 'specto-optout'
|
|
209
|
+
const CONSENT_KEY = 'specto-consent'
|
|
210
|
+
export const isOptedOut = () => store.get('localStorage', OPTOUT_KEY) === true
|
|
211
|
+
export const hasConsent = () => store.get('localStorage', CONSENT_KEY) === 'granted'
|
|
212
|
+
|
|
56
213
|
// stable anonymous visitor id (per browser, per site) — powers retention
|
|
57
214
|
// cohorts. No fingerprinting: just a random id in localStorage.
|
|
58
215
|
function visitorId() {
|
|
216
|
+
let v = store.get('localStorage', 'specto-vid')
|
|
217
|
+
if (typeof v !== 'string') { v = newId('v_'); store.set('localStorage', 'specto-vid', v) }
|
|
218
|
+
return v
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const SESSION_IDLE_MS = 30 * 60_000
|
|
222
|
+
const SESSION_MAX_MS = 4 * 3600_000
|
|
223
|
+
// how long the upload worker gets to confirm it runs before the page uploads
|
|
224
|
+
const WORKER_READY_MS = 4000
|
|
225
|
+
|
|
226
|
+
// Remote project config (Settings → Privacy & masking), edge-cacheable. The
|
|
227
|
+
// STRICTER of local and remote settings always wins; failures fall back to
|
|
228
|
+
// the local options (the server enforces privacy settings again at ingest).
|
|
229
|
+
async function remoteConfig(url, key) {
|
|
230
|
+
if (!url) return null
|
|
59
231
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
232
|
+
const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null
|
|
233
|
+
const t = ctrl && setTimeout(() => ctrl.abort(), 3000)
|
|
234
|
+
const res = await fetch(`${url}?key=${encodeURIComponent(key)}`, { credentials: 'omit', signal: ctrl?.signal })
|
|
235
|
+
if (t) clearTimeout(t)
|
|
236
|
+
return res.ok ? await res.json() : null
|
|
237
|
+
} catch { return null }
|
|
64
238
|
}
|
|
65
239
|
|
|
240
|
+
/**
|
|
241
|
+
* startRecording(opts) → api
|
|
242
|
+
* key (required) publishable project key
|
|
243
|
+
* endpoint ingest URL (default /api/ingest)
|
|
244
|
+
* configUrl project config URL (default: endpoint's /api/sdk/config; false = none)
|
|
245
|
+
* privacy 'balanced' | 'strict' (strict masks all text, drops console text and URL query strings)
|
|
246
|
+
* sampleRate 0..1 — fraction of sessions recorded (decided once per session)
|
|
247
|
+
* consent 'granted' (default) | 'required' (wait for Specto.consent(true))
|
|
248
|
+
* console capture console (default true)
|
|
249
|
+
* networkDetails devtools-style request details (default true)
|
|
250
|
+
* traces send a W3C traceparent header with same-origin requests so
|
|
251
|
+
* backend spans join the replay (default false)
|
|
252
|
+
* traceOrigins more origins to send it to, e.g. ['https://api.example.com']
|
|
253
|
+
* (their CORS must allow the traceparent header)
|
|
254
|
+
* createWorker () => Worker (the snippet/npm builds pass an inlined worker)
|
|
255
|
+
*/
|
|
66
256
|
export function startRecording(opts = {}) {
|
|
257
|
+
if (typeof window === 'undefined') return { disabled: true, reason: 'no window', stop() {} }
|
|
258
|
+
// idempotency: never run two recorders (and two upload workers) at once
|
|
259
|
+
if (window.__spectoRec && !window.__spectoRec.disabled) return window.__spectoRec
|
|
260
|
+
if (!opts.key) throw new Error('Specto: a publishable key is required')
|
|
261
|
+
const key = String(opts.key)
|
|
67
262
|
const endpoint = opts.endpoint || '/api/ingest'
|
|
68
|
-
const
|
|
69
|
-
const sessionId = opts.sessionId || newId()
|
|
70
|
-
const onUpdate = opts.onUpdate || (() => {})
|
|
263
|
+
const configUrl = opts.configUrl === false ? null : (opts.configUrl || String(endpoint).replace(/\/api\/ingest$/, '/api/sdk/config'))
|
|
71
264
|
|
|
72
|
-
|
|
73
|
-
if (
|
|
265
|
+
const handle = { disabled: true, reason: 'starting', sessionId: null, stop() {}, flushNow() {}, count: () => 0, identify() {}, track() {}, sessionUrl: () => null }
|
|
266
|
+
if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl) return Object.assign(handle, { reason: 'dnt' })
|
|
267
|
+
if (isOptedOut()) return Object.assign(handle, { reason: 'opted-out' })
|
|
268
|
+
if (opts.consent === 'required' && !hasConsent()) return Object.assign(handle, { reason: 'consent-required' })
|
|
74
269
|
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
270
|
+
// start after the project config resolves (one edge-cached request)
|
|
271
|
+
const api = createRecorder(opts, key, endpoint)
|
|
272
|
+
window.__spectoRec = api
|
|
273
|
+
remoteConfig(configUrl, key).then((remote) => api._begin(remote)).catch(() => api._begin(null))
|
|
274
|
+
return api
|
|
275
|
+
}
|
|
79
276
|
|
|
277
|
+
function createRecorder(opts, key, endpoint) {
|
|
80
278
|
let buffer = []
|
|
81
279
|
let total = 0
|
|
82
|
-
|
|
280
|
+
let started = false
|
|
281
|
+
let stopped = false
|
|
282
|
+
let stopDom = null
|
|
283
|
+
const restore = []
|
|
83
284
|
const t0 = performance.now()
|
|
84
285
|
const rel = () => Math.round(performance.now() - t0)
|
|
286
|
+
const sessKey = `specto-session:${key}`
|
|
287
|
+
let session = null // { id, sk, b, started, active, sampled }
|
|
288
|
+
let cfg = null
|
|
289
|
+
let worker = null
|
|
290
|
+
let workerReady = false
|
|
291
|
+
// batches handed to the worker before it said it runs: a Content Security
|
|
292
|
+
// Policy without `worker-src blob:` blocks it WITHOUT an exception, and
|
|
293
|
+
// postMessage to a worker that never started drops them silently
|
|
294
|
+
let unconfirmed = []
|
|
295
|
+
let mainUploader = null
|
|
296
|
+
let lastActive = Date.now()
|
|
85
297
|
|
|
298
|
+
// identify/track called before recording begins (the project's settings
|
|
299
|
+
// are still loading — e.g. identify() right after startRecording()) are
|
|
300
|
+
// kept and sent once it does; dropped if it never starts
|
|
301
|
+
const early = []
|
|
86
302
|
const push = (kind, payload) => {
|
|
303
|
+
if (stopped) return
|
|
304
|
+
if (!started) { if (early.length < 50) early.push([kind, payload]); return }
|
|
87
305
|
buffer.push({ kind, payload })
|
|
88
306
|
total++
|
|
89
|
-
onUpdate({ total, kind })
|
|
307
|
+
opts.onUpdate?.({ total, kind })
|
|
90
308
|
}
|
|
309
|
+
const persist = () => store.set('sessionStorage', sessKey, session)
|
|
91
310
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
maskTextClass: 'specto-mask',
|
|
102
|
-
maskTextSelector: strict ? '*' : undefined,
|
|
103
|
-
blockClass: 'specto-block',
|
|
104
|
-
recordCanvas: false,
|
|
105
|
-
collectFonts: false,
|
|
106
|
-
sampling: { mousemove: 50, scroll: 150, input: 'last' },
|
|
107
|
-
})
|
|
108
|
-
|
|
109
|
-
// ---- console ----
|
|
110
|
-
const origConsole = {}
|
|
111
|
-
for (const level of ['log', 'info', 'warn', 'error']) {
|
|
112
|
-
origConsole[level] = console[level]
|
|
113
|
-
console[level] = (...args) => {
|
|
114
|
-
try {
|
|
115
|
-
push('console', { t: rel(), level, text: args.map(fmt).join(' ').slice(0, 2000) })
|
|
116
|
-
} catch { /* never break the app */ }
|
|
117
|
-
origConsole[level].apply(console, args)
|
|
311
|
+
function openSession(fresh) {
|
|
312
|
+
const now = Date.now()
|
|
313
|
+
const prev = fresh ? null : store.get('sessionStorage', sessKey)
|
|
314
|
+
const resumed = Boolean(prev && typeof prev.id === 'string' && now - prev.active < SESSION_IDLE_MS && now - prev.started < SESSION_MAX_MS)
|
|
315
|
+
if (resumed) {
|
|
316
|
+
session = prev
|
|
317
|
+
} else {
|
|
318
|
+
const rate = Math.max(0, Math.min(1, cfg.sampleRate))
|
|
319
|
+
session = { id: newId(), sk: newSessionKey(), b: 0, started: now, active: now, sampled: Math.random() < rate }
|
|
118
320
|
}
|
|
321
|
+
session.active = now
|
|
322
|
+
persist()
|
|
323
|
+
return resumed
|
|
119
324
|
}
|
|
120
325
|
|
|
121
|
-
//
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
try {
|
|
128
|
-
const res = await origFetch.apply(window, args)
|
|
129
|
-
let traceId
|
|
130
|
-
try { traceId = res.headers.get('x-trace-id') || undefined } catch { /* opaque */ }
|
|
131
|
-
push('network', { t: rel(), method, url: String(url).slice(0, 300), status: res.status, dur: Math.round(performance.now() - started), ...(traceId ? { traceId } : {}) })
|
|
132
|
-
return res
|
|
133
|
-
} catch (err) {
|
|
134
|
-
push('network', { t: rel(), method, url: String(url).slice(0, 300), status: 0, dur: Math.round(performance.now() - started), error: true })
|
|
135
|
-
throw err
|
|
136
|
-
}
|
|
326
|
+
// a new session: new id, batch counter reset, and a fresh full snapshot
|
|
327
|
+
function rotate() {
|
|
328
|
+
handoff()
|
|
329
|
+
openSession(true)
|
|
330
|
+
if (!session.sampled) return api.stop('not-sampled')
|
|
331
|
+
try { record.takeFullSnapshot(true) } catch { /* rrweb not running */ }
|
|
137
332
|
}
|
|
138
333
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const m = this.__specto
|
|
149
|
-
let traceId
|
|
150
|
-
try { traceId = this.getResponseHeader('x-trace-id') || undefined } catch { /* ignore */ }
|
|
151
|
-
push('network', { t: rel(), method: m.method, url: m.url, status: this.status, dur: Math.round(performance.now() - m.started), ...(traceId ? { traceId } : {}) })
|
|
152
|
-
})
|
|
153
|
-
}
|
|
154
|
-
return origSend.apply(this, arguments)
|
|
334
|
+
function send(events) {
|
|
335
|
+
if (!events.length || !session?.sampled) return
|
|
336
|
+
const item = { b: session.b++, json: JSON.stringify({ key, sessionId: session.id, ...(session.sk ? { sk: session.sk } : {}), b: session.b - 1, sdk: SDK_VERSION, meta: { page: scrubUrl(location.pathname), userAgent: navigator.userAgent, visitorId: visitorId() }, events }) }
|
|
337
|
+
session.active = Math.max(session.active, lastActive)
|
|
338
|
+
persist()
|
|
339
|
+
if (worker) {
|
|
340
|
+
worker.postMessage({ t: 'upload', item })
|
|
341
|
+
if (!workerReady) unconfirmed.push(item)
|
|
342
|
+
} else mainUploader.push(item)
|
|
155
343
|
}
|
|
156
344
|
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
history.replaceState = function (...a) { const r = origReplace.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
|
|
167
|
-
window.addEventListener('popstate', pushNav)
|
|
168
|
-
window.addEventListener('hashchange', pushNav)
|
|
169
|
-
|
|
170
|
-
// ---- rage clicks (>=3 clicks within 800ms near same spot) ----
|
|
171
|
-
let clicks = []
|
|
172
|
-
const onClick = (e) => {
|
|
173
|
-
const now = performance.now()
|
|
174
|
-
clicks = clicks.filter((c) => now - c.t < 800)
|
|
175
|
-
clicks.push({ t: now, x: e.clientX, y: e.clientY })
|
|
176
|
-
if (clicks.length >= 3) {
|
|
177
|
-
const sel = e.target?.tagName ? e.target.tagName.toLowerCase() + (e.target.id ? '#' + e.target.id : '') : 'element'
|
|
178
|
-
push('event', { t: rel(), type: 'rage', target: sel.slice(0, 80), count: clicks.length })
|
|
179
|
-
clicks = []
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
window.addEventListener('click', onClick, true)
|
|
183
|
-
|
|
184
|
-
// ---- upload: off-main-thread serialize + gzip + POST via a Web Worker ----
|
|
185
|
-
// The main thread only buffers (cheap) and hands batches to the worker every
|
|
186
|
-
// 2s. Privacy transforms (input masking, attribute scrubbing) already ran on
|
|
187
|
-
// the main thread before events were buffered, so the worker only sees clean
|
|
188
|
-
// data. On pagehide we sendBeacon the residual directly (workers may be
|
|
189
|
-
// killed on unload), so no tail is lost.
|
|
190
|
-
const meta = { page: location.pathname, userAgent: navigator.userAgent, startedAt, visitorId: visitorId() }
|
|
191
|
-
let worker = null
|
|
192
|
-
try {
|
|
193
|
-
// Callers provide the worker factory: the app passes createDefaultWorker
|
|
194
|
-
// (worker-factory.js), the SDK/npm builds pass an inlined worker. recorder.js
|
|
195
|
-
// itself never references import.meta, so the IIFE/CJS bundles stay valid.
|
|
196
|
-
// No factory → main-thread upload (below).
|
|
197
|
-
worker = opts.createWorker ? opts.createWorker() : null
|
|
198
|
-
if (worker) worker.postMessage({ t: 'init', cfg: { endpoint, key, sessionId, meta } })
|
|
199
|
-
} catch { worker = null /* fall back to main-thread upload below */ }
|
|
200
|
-
|
|
201
|
-
async function mainUpload(batch) {
|
|
202
|
-
let gz = null
|
|
203
|
-
if (typeof CompressionStream !== 'undefined') {
|
|
204
|
-
try { gz = await new Response(new Blob([JSON.stringify({ sessionId, key, meta, events: batch })]).stream().pipeThrough(new CompressionStream('gzip'))).blob() } catch { gz = null }
|
|
205
|
-
}
|
|
206
|
-
const json = JSON.stringify({ sessionId, key, meta, events: batch })
|
|
207
|
-
await origFetch.call(window, endpoint, gz
|
|
208
|
-
? { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'x-specto-gzip': '1' }, body: gz, keepalive: true }
|
|
209
|
-
: { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: json, keepalive: true })
|
|
345
|
+
// the upload worker never came up (CSP, an extension, a broken engine):
|
|
346
|
+
// upload from the page instead and resend what the worker was handed —
|
|
347
|
+
// batches are numbered, so anything it did send is de-duplicated
|
|
348
|
+
function uploadFromPage() {
|
|
349
|
+
if (mainUploader) return
|
|
350
|
+
try { worker?.terminate() } catch { /* already gone */ }
|
|
351
|
+
worker = null
|
|
352
|
+
mainUploader = createUploader({ endpoint, onEvent: onUploader })
|
|
353
|
+
for (const item of unconfirmed.splice(0)) mainUploader.push(item)
|
|
210
354
|
}
|
|
211
355
|
|
|
212
356
|
function handoff() {
|
|
213
357
|
if (!buffer.length) return
|
|
214
358
|
const batch = buffer
|
|
215
359
|
buffer = []
|
|
216
|
-
|
|
217
|
-
else mainUpload(batch).catch(() => { buffer = batch.concat(buffer) })
|
|
360
|
+
send(batch)
|
|
218
361
|
}
|
|
219
362
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
363
|
+
function onUploader(ev) {
|
|
364
|
+
if (ev.t === 'stop') api.stop(ev.code)
|
|
365
|
+
else if (ev.t === 'rotate') rotate()
|
|
366
|
+
opts.onDelivery?.(ev)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// pagehide: the worker may be killed mid-request, so the residual buffer
|
|
370
|
+
// goes out as sendBeacon chunks (text/plain: no preflight; ≤ ~60 KB each)
|
|
371
|
+
function beaconResidual() {
|
|
372
|
+
if (!buffer.length || !navigator.sendBeacon || !session?.sampled) return
|
|
373
|
+
const events = buffer
|
|
374
|
+
buffer = []
|
|
375
|
+
let chunk = []
|
|
376
|
+
let size = 0
|
|
377
|
+
const flushChunk = () => {
|
|
378
|
+
if (!chunk.length) return
|
|
379
|
+
const body = JSON.stringify({ key, sessionId: session.id, ...(session.sk ? { sk: session.sk } : {}), b: session.b++, sdk: SDK_VERSION, meta: { page: scrubUrl(location.pathname) }, events: chunk })
|
|
380
|
+
try { navigator.sendBeacon(endpoint, new Blob([body], { type: 'text/plain;charset=UTF-8' })) } catch { /* best effort */ }
|
|
381
|
+
chunk = []; size = 0
|
|
382
|
+
}
|
|
383
|
+
for (const e of events) {
|
|
384
|
+
const n = JSON.stringify(e).length
|
|
385
|
+
if (size + n > 55_000) flushChunk()
|
|
386
|
+
if (n > 55_000) continue // a single huge event cannot ride a beacon
|
|
387
|
+
chunk.push(e); size += n
|
|
226
388
|
}
|
|
389
|
+
flushChunk()
|
|
390
|
+
persist()
|
|
227
391
|
}
|
|
228
|
-
window.addEventListener('pagehide', onHide)
|
|
229
392
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
393
|
+
const api = {
|
|
394
|
+
disabled: false,
|
|
395
|
+
get sessionId() { return session?.id || null },
|
|
396
|
+
count: () => total,
|
|
397
|
+
flushNow: () => handoff(),
|
|
398
|
+
// attach your own user id (+ a few flat traits) to the current session
|
|
399
|
+
identify(id, traits) {
|
|
400
|
+
if (id == null || id === '') return
|
|
401
|
+
push('identify', { id: String(id).slice(0, 256), traits: traits && typeof traits === 'object' ? traits : undefined })
|
|
402
|
+
},
|
|
403
|
+
// custom product events, searchable on the session timeline
|
|
404
|
+
track(name, props) {
|
|
405
|
+
if (!name) return
|
|
406
|
+
push('event', { t: rel(), type: 'custom', name: String(name).slice(0, 120), props: props && typeof props === 'object' ? JSON.parse(JSON.stringify(props, (k, v) => (typeof v === 'string' ? scrubText(v).slice(0, 500) : v))) : undefined })
|
|
407
|
+
},
|
|
408
|
+
sessionUrl() {
|
|
409
|
+
try { return session ? `${new URL(endpoint, location.href).origin}/#replay/${session.id}` : null } catch { return null }
|
|
410
|
+
},
|
|
411
|
+
stop(reason) {
|
|
412
|
+
if (stopped) return
|
|
413
|
+
stopped = true
|
|
414
|
+
api.disabled = true
|
|
415
|
+
api.reason = reason || 'stopped'
|
|
416
|
+
try { stopDom?.() } catch { /* already stopped */ }
|
|
417
|
+
for (const undo of restore.splice(0)) { try { undo() } catch { /* best effort */ } }
|
|
418
|
+
handoff()
|
|
419
|
+
// stopped before the worker confirmed it runs: the last batches go from the page
|
|
420
|
+
if (worker && !workerReady && unconfirmed.length) uploadFromPage()
|
|
421
|
+
const w = worker
|
|
422
|
+
if (w) setTimeout(() => w.terminate(), 2000)
|
|
423
|
+
if (window.__spectoRec === api) delete window.__spectoRec
|
|
424
|
+
},
|
|
425
|
+
_begin(remote) {
|
|
426
|
+
if (stopped || started) return
|
|
427
|
+
const r = remote && typeof remote === 'object' ? remote : {}
|
|
428
|
+
if (r.enabled === false) return api.stop('recording-disabled')
|
|
429
|
+
cfg = {
|
|
430
|
+
strict: opts.privacy === 'strict' || r.privacy === 'strict',
|
|
431
|
+
console: opts.console !== false && r.captureConsole !== false,
|
|
432
|
+
networkDetails: opts.networkDetails !== false && r.captureNetworkDetails !== false,
|
|
433
|
+
sampleRate: Math.min(opts.sampleRate ?? 1, typeof r.sampleRate === 'number' ? r.sampleRate : 1),
|
|
434
|
+
}
|
|
435
|
+
const resumed = openSession(false)
|
|
436
|
+
if (!session.sampled) return api.stop('not-sampled')
|
|
437
|
+
started = true
|
|
438
|
+
for (const [kind, payload] of early.splice(0)) push(kind, payload)
|
|
439
|
+
|
|
440
|
+
try {
|
|
441
|
+
worker = opts.createWorker ? opts.createWorker() : null
|
|
442
|
+
if (worker) {
|
|
443
|
+
worker.onmessage = (e) => {
|
|
444
|
+
const m = e.data || {}
|
|
445
|
+
if (m.t === 'ready') { workerReady = true; unconfirmed = []; return }
|
|
446
|
+
onUploader(m)
|
|
447
|
+
}
|
|
448
|
+
worker.onerror = () => { if (!workerReady) uploadFromPage() }
|
|
449
|
+
worker.postMessage({ t: 'init', endpoint })
|
|
450
|
+
const readyTimer = setTimeout(() => { if (!workerReady) uploadFromPage() }, WORKER_READY_MS)
|
|
451
|
+
restore.push(() => clearTimeout(readyTimer))
|
|
452
|
+
}
|
|
453
|
+
} catch { worker = null }
|
|
454
|
+
if (!worker) mainUploader = createUploader({ endpoint, onEvent: onUploader })
|
|
455
|
+
|
|
456
|
+
instrument(resumed)
|
|
457
|
+
const timer = setInterval(handoff, 2000)
|
|
458
|
+
restore.push(() => clearInterval(timer))
|
|
459
|
+
},
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// resumed: this page load continues a session started on an earlier page
|
|
463
|
+
function instrument(resumed) {
|
|
464
|
+
// ---- DOM via rrweb ----
|
|
465
|
+
stopDom = record({
|
|
466
|
+
emit: (e) => push('dom', scrubEvent(e, cfg.strict)),
|
|
467
|
+
maskAllInputs: true,
|
|
468
|
+
maskInputOptions: { password: true, email: true, tel: true, color: false },
|
|
469
|
+
maskTextClass: 'specto-mask',
|
|
470
|
+
maskTextSelector: cfg.strict ? '*' : undefined,
|
|
471
|
+
blockClass: 'specto-block',
|
|
472
|
+
recordCanvas: false,
|
|
473
|
+
collectFonts: false,
|
|
474
|
+
checkoutEveryNms: 5 * 60_000,
|
|
475
|
+
sampling: { mousemove: 50, scroll: 150, input: 'last' },
|
|
476
|
+
})
|
|
477
|
+
|
|
478
|
+
// ---- activity → session liveness; idle past the timeout → new session
|
|
479
|
+
const bump = () => {
|
|
480
|
+
const now = Date.now()
|
|
481
|
+
if (now - lastActive > SESSION_IDLE_MS) { lastActive = now; rotate(); return }
|
|
482
|
+
lastActive = now
|
|
483
|
+
}
|
|
484
|
+
for (const ev of ['click', 'keydown', 'scroll', 'pointerdown']) {
|
|
485
|
+
window.addEventListener(ev, bump, { capture: true, passive: true })
|
|
486
|
+
restore.push(() => window.removeEventListener(ev, bump, { capture: true }))
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ---- console ----
|
|
490
|
+
if (cfg.console) {
|
|
491
|
+
for (const level of ['log', 'info', 'warn', 'error']) {
|
|
492
|
+
const orig = console[level]
|
|
493
|
+
console[level] = (...args) => {
|
|
494
|
+
try {
|
|
495
|
+
// strict privacy: keep the signal (a warning/error happened), not its text
|
|
496
|
+
push('console', { t: rel(), level, text: cfg.strict ? '[masked]' : scrubText(args.map(fmt).join(' ')).slice(0, 2000) })
|
|
497
|
+
} catch { /* never break the app */ }
|
|
498
|
+
orig.apply(console, args)
|
|
499
|
+
}
|
|
500
|
+
restore.push(() => { console[level] = orig })
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ---- network: fetch ----
|
|
505
|
+
if (cfg.networkDetails) { try { performance.setResourceTimingBufferSize?.(1000) } catch { /* older engines */ } }
|
|
506
|
+
const origFetch = window.fetch
|
|
507
|
+
// the SDK's own uploads (the page uploader when no worker runs) are not
|
|
508
|
+
// the app's traffic: recording them made every upload trigger the next
|
|
509
|
+
let ingestUrl = null
|
|
510
|
+
try { ingestUrl = new URL(endpoint, location.href).href.split(/[?#]/)[0] } catch { /* relative-only engines */ }
|
|
511
|
+
const isOwn = (u) => { try { return ingestUrl != null && new URL(u, location.href).href.split(/[?#]/)[0] === ingestUrl } catch { return false } }
|
|
512
|
+
// backend traces (opt-in): which requests carry a traceparent
|
|
513
|
+
const traceOrigins = new Set((Array.isArray(opts.traceOrigins) ? opts.traceOrigins : []).map((o) => { try { return new URL(o).origin } catch { return null } }).filter(Boolean))
|
|
514
|
+
const tracing = Boolean(opts.traces) || traceOrigins.size > 0
|
|
515
|
+
const traced = (u) => {
|
|
516
|
+
if (!tracing) return false
|
|
517
|
+
try { const o = new URL(u, location.href).origin; return o === location.origin || traceOrigins.has(o) } catch { return false }
|
|
518
|
+
}
|
|
519
|
+
// → [args with a traceparent, its trace id]; an app's own header is kept
|
|
520
|
+
const withTraceparent = (args) => {
|
|
521
|
+
try {
|
|
522
|
+
const [input, init] = args
|
|
523
|
+
const fromRequest = typeof Request !== 'undefined' && input instanceof Request
|
|
524
|
+
const headers = new Headers(init?.headers ?? (fromRequest ? input.headers : undefined))
|
|
525
|
+
const existing = TRACEPARENT.exec(headers.get('traceparent') || '')
|
|
526
|
+
if (existing) return [args, existing[1].toLowerCase()]
|
|
527
|
+
const traceId = randomHex(16)
|
|
528
|
+
headers.set('traceparent', `00-${traceId}-${randomHex(8)}-01`)
|
|
529
|
+
return [[input, { ...init, headers }], traceId]
|
|
530
|
+
} catch { return [args, undefined] } // never break the app's request
|
|
531
|
+
}
|
|
532
|
+
window.fetch = async (...args) => {
|
|
533
|
+
if (isOwn(urlOf(args[0]))) return origFetch.apply(window, args)
|
|
534
|
+
const t = performance.now()
|
|
535
|
+
const rawUrl = urlOf(args[0])
|
|
536
|
+
const url = scrubUrl(rawUrl, cfg.strict)
|
|
537
|
+
const method = (args[1]?.method || (typeof args[0] !== 'string' && args[0]?.method) || 'GET').toUpperCase()
|
|
538
|
+
let sentTrace
|
|
539
|
+
if (traced(rawUrl)) [args, sentTrace] = withTraceparent(args)
|
|
540
|
+
try {
|
|
541
|
+
const res = await origFetch.apply(window, args)
|
|
542
|
+
let traceId = sentTrace
|
|
543
|
+
try { traceId = traceId || res.headers.get('x-trace-id') || undefined } catch { /* opaque */ }
|
|
544
|
+
const payload = { t: rel(), method, url, status: res.status, dur: Math.round(performance.now() - t), ...(traceId ? { traceId } : {}) }
|
|
545
|
+
if (cfg.networkDetails) {
|
|
546
|
+
const detail = { initiator: 'fetch' }
|
|
547
|
+
try {
|
|
548
|
+
if (res.statusText) detail.statusText = String(res.statusText).slice(0, 80)
|
|
549
|
+
const hdr = pickHeaders((h) => res.headers.get(h))
|
|
550
|
+
if (hdr) detail.headers = hdr
|
|
551
|
+
if (hdr?.['content-type']) detail.resType = hdr['content-type'].split(';')[0]
|
|
552
|
+
const len = Number(hdr?.['content-length'])
|
|
553
|
+
if (hdr?.['content-length'] != null && Number.isFinite(len)) detail.resSize = len
|
|
554
|
+
const init = args[1] || (typeof args[0] === 'object' ? args[0] : null)
|
|
555
|
+
const reqCt = headerValue(init?.headers, 'content-type')
|
|
556
|
+
if (reqCt) detail.reqType = reqCt.split(';')[0].slice(0, 80)
|
|
557
|
+
const reqSize = bodySize(args[1]?.body)
|
|
558
|
+
if (reqSize != null) detail.reqSize = reqSize
|
|
559
|
+
} catch { /* detail is best-effort */ }
|
|
560
|
+
payload.detail = detail
|
|
561
|
+
attachTiming(payload, absoluteUrl(rawUrl), t)
|
|
562
|
+
}
|
|
563
|
+
push('network', payload)
|
|
564
|
+
return res
|
|
565
|
+
} catch (err) {
|
|
566
|
+
push('network', {
|
|
567
|
+
t: rel(), method, url, status: 0, dur: Math.round(performance.now() - t), error: true,
|
|
568
|
+
...(cfg.networkDetails ? { detail: { initiator: 'fetch', message: scrubText(String(err?.message || err)).slice(0, 200) } } : {}),
|
|
569
|
+
})
|
|
570
|
+
throw err
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
restore.push(() => { window.fetch = origFetch })
|
|
574
|
+
|
|
575
|
+
// ---- network: XHR ----
|
|
576
|
+
const XHR = window.XMLHttpRequest
|
|
577
|
+
const origOpen = XHR.prototype.open
|
|
578
|
+
const origSend = XHR.prototype.send
|
|
579
|
+
const origSetHeader = XHR.prototype.setRequestHeader
|
|
580
|
+
XHR.prototype.open = function (method, url) {
|
|
581
|
+
this.__specto = { method: String(method).toUpperCase(), url: scrubUrl(url, cfg.strict), rawUrl: absoluteUrl(url), started: 0, trace: traced(url) }
|
|
582
|
+
return origOpen.apply(this, arguments)
|
|
583
|
+
}
|
|
584
|
+
XHR.prototype.setRequestHeader = function (name, value) {
|
|
585
|
+
const h = String(name).toLowerCase()
|
|
586
|
+
if (this.__specto && h === 'content-type') this.__specto.reqType = String(value).split(';')[0].slice(0, 80)
|
|
587
|
+
if (this.__specto && h === 'traceparent') { const m = TRACEPARENT.exec(String(value)); if (m) this.__specto.traceId = m[1].toLowerCase(); this.__specto.trace = false }
|
|
588
|
+
return origSetHeader.apply(this, arguments)
|
|
589
|
+
}
|
|
590
|
+
XHR.prototype.send = function (body) {
|
|
591
|
+
if (this.__specto) {
|
|
592
|
+
if (this.__specto.trace) {
|
|
593
|
+
try {
|
|
594
|
+
const traceId = randomHex(16)
|
|
595
|
+
origSetHeader.call(this, 'traceparent', `00-${traceId}-${randomHex(8)}-01`)
|
|
596
|
+
this.__specto.traceId = traceId
|
|
597
|
+
} catch { /* never break the app's request */ }
|
|
598
|
+
}
|
|
599
|
+
this.__specto.started = performance.now()
|
|
600
|
+
if (cfg.networkDetails) this.__specto.reqSize = bodySize(body)
|
|
601
|
+
this.addEventListener('loadend', () => {
|
|
602
|
+
const m = this.__specto
|
|
603
|
+
let traceId = m.traceId
|
|
604
|
+
try { traceId = traceId || this.getResponseHeader('x-trace-id') || undefined } catch { /* ignore */ }
|
|
605
|
+
const payload = { t: rel(), method: m.method, url: m.url, status: this.status, dur: Math.round(performance.now() - m.started), ...(traceId ? { traceId } : {}), ...(this.status === 0 ? { error: true } : {}) }
|
|
606
|
+
if (cfg.networkDetails) {
|
|
607
|
+
const detail = { initiator: 'xhr' }
|
|
608
|
+
try {
|
|
609
|
+
if (this.statusText) detail.statusText = String(this.statusText).slice(0, 80)
|
|
610
|
+
const hdr = pickHeaders((h) => this.getResponseHeader(h))
|
|
611
|
+
if (hdr) detail.headers = hdr
|
|
612
|
+
if (hdr?.['content-type']) detail.resType = hdr['content-type'].split(';')[0]
|
|
613
|
+
const len = Number(hdr?.['content-length'])
|
|
614
|
+
if (hdr?.['content-length'] != null && Number.isFinite(len)) detail.resSize = len
|
|
615
|
+
if (m.reqType) detail.reqType = m.reqType
|
|
616
|
+
if (m.reqSize != null) detail.reqSize = m.reqSize
|
|
617
|
+
} catch { /* best-effort */ }
|
|
618
|
+
payload.detail = detail
|
|
619
|
+
attachTiming(payload, m.rawUrl, m.started)
|
|
620
|
+
}
|
|
621
|
+
push('network', payload)
|
|
622
|
+
})
|
|
623
|
+
}
|
|
624
|
+
return origSend.apply(this, arguments)
|
|
625
|
+
}
|
|
626
|
+
restore.push(() => { XHR.prototype.open = origOpen; XHR.prototype.send = origSend; XHR.prototype.setRequestHeader = origSetHeader })
|
|
627
|
+
|
|
628
|
+
// ---- JS errors (message + a few scrubbed stack frames) ----
|
|
629
|
+
const onError = (e) => {
|
|
630
|
+
const err = e.error || e.reason
|
|
631
|
+
const stack = err?.stack ? scrubText(String(err.stack)).split('\n').slice(0, 6).map((l) => l.replace(/\?[^\s:)]*/g, '').slice(0, 300)).join('\n') : undefined
|
|
632
|
+
push('event', { t: rel(), type: 'error', message: scrubText(String(e.message || err?.message || e.reason || 'error')).slice(0, 500), ...(stack ? { stack } : {}) })
|
|
633
|
+
}
|
|
634
|
+
window.addEventListener('error', onError)
|
|
635
|
+
window.addEventListener('unhandledrejection', onError)
|
|
636
|
+
restore.push(() => { window.removeEventListener('error', onError); window.removeEventListener('unhandledrejection', onError) })
|
|
637
|
+
|
|
638
|
+
// ---- SPA navigations (history API + hash) — powers funnels/paths ----
|
|
639
|
+
let viewChanged = () => {} // heatmaps: a new path is a new page view (below)
|
|
640
|
+
const pushNav = () => {
|
|
641
|
+
viewChanged()
|
|
642
|
+
push('event', { t: rel(), type: 'nav', path: scrubUrl(location.pathname + location.search + location.hash, cfg.strict).slice(0, 300) })
|
|
643
|
+
}
|
|
644
|
+
const origPush = history.pushState, origReplace = history.replaceState
|
|
645
|
+
history.pushState = function (...a) { const r = origPush.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
|
|
646
|
+
history.replaceState = function (...a) { const r = origReplace.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
|
|
647
|
+
window.addEventListener('popstate', pushNav)
|
|
648
|
+
window.addEventListener('hashchange', pushNav)
|
|
649
|
+
restore.push(() => {
|
|
650
|
+
history.pushState = origPush; history.replaceState = origReplace
|
|
651
|
+
window.removeEventListener('popstate', pushNav); window.removeEventListener('hashchange', pushNav)
|
|
652
|
+
})
|
|
653
|
+
// a page load inside a running session is a navigation too (multi-page
|
|
654
|
+
// sites), and so is a hash route on the first page — the session's page
|
|
655
|
+
// is only the path
|
|
656
|
+
if (resumed || location.hash.length > 1) { try { pushNav() } catch { /* never break start */ } }
|
|
657
|
+
|
|
658
|
+
// ---- rage clicks (>=3 clicks within 800ms near same spot) ----
|
|
659
|
+
let clicks = []
|
|
660
|
+
const onClick = (e) => {
|
|
661
|
+
const now = performance.now()
|
|
662
|
+
clicks = clicks.filter((c) => now - c.t < 800 && Math.abs(c.x - e.clientX) < 40 && Math.abs(c.y - e.clientY) < 40)
|
|
663
|
+
clicks.push({ t: now, x: e.clientX, y: e.clientY })
|
|
664
|
+
if (clicks.length >= 3) {
|
|
665
|
+
const sel = e.target?.tagName ? e.target.tagName.toLowerCase() + (e.target.id ? '#' + e.target.id : '') : 'element'
|
|
666
|
+
push('event', { t: rel(), type: 'rage', target: sel.slice(0, 80), count: clicks.length })
|
|
667
|
+
clicks = []
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
window.addEventListener('click', onClick, true)
|
|
671
|
+
restore.push(() => window.removeEventListener('click', onClick, true))
|
|
672
|
+
|
|
673
|
+
// ---- heatmaps: clicks with their page position; the deepest point each
|
|
674
|
+
// page view scrolled to, sent when it ends (navigation, tab hidden) —
|
|
675
|
+
// sent again if it goes deeper later, the server keeps the maximum
|
|
676
|
+
const docHeight = () => Math.max(document.documentElement?.scrollHeight || 0, document.body?.scrollHeight || 0)
|
|
677
|
+
let view = null // { id, path, depth, clicks }
|
|
678
|
+
const measure = () => {
|
|
679
|
+
const h = docHeight()
|
|
680
|
+
if (view && h > 0) view.depth = Math.max(view.depth, Math.min(1, (window.scrollY + window.innerHeight) / h))
|
|
681
|
+
}
|
|
682
|
+
const newView = () => { view = { id: Math.random().toString(36).slice(2, 10), path: scrubUrl(location.pathname, cfg.strict).slice(0, 300), depth: 0, clicks: 0 }; measure() }
|
|
683
|
+
const flushView = () => {
|
|
684
|
+
if (view) push('event', { t: rel(), type: 'scroll', path: view.path, pv: view.id, depth: Math.round(view.depth * 1000) / 1000, vw: window.innerWidth, dh: docHeight() })
|
|
685
|
+
}
|
|
686
|
+
newView()
|
|
687
|
+
viewChanged = () => {
|
|
688
|
+
if (scrubUrl(location.pathname, cfg.strict).slice(0, 300) === view?.path) return
|
|
689
|
+
flushView()
|
|
690
|
+
newView()
|
|
691
|
+
}
|
|
692
|
+
let scrollPending = false
|
|
693
|
+
const onScroll = () => {
|
|
694
|
+
if (scrollPending) return
|
|
695
|
+
scrollPending = true
|
|
696
|
+
requestAnimationFrame(() => { scrollPending = false; measure() })
|
|
697
|
+
}
|
|
698
|
+
const onHeatClick = (e) => {
|
|
699
|
+
if (!view || view.clicks >= 300) return
|
|
700
|
+
view.clicks++
|
|
701
|
+
push('event', { t: rel(), type: 'click', path: view.path, pv: view.id, x: Math.round(e.pageX), y: Math.round(e.pageY), vw: window.innerWidth, dh: docHeight(), sel: selectorOf(e.target) })
|
|
702
|
+
}
|
|
703
|
+
window.addEventListener('scroll', onScroll, { passive: true, capture: true })
|
|
704
|
+
window.addEventListener('click', onHeatClick, true)
|
|
705
|
+
restore.push(() => { window.removeEventListener('scroll', onScroll, { capture: true }); window.removeEventListener('click', onHeatClick, true) })
|
|
706
|
+
|
|
707
|
+
// ---- lifecycle: flush on hide; retry promptly when the network returns
|
|
708
|
+
const onHide = () => { flushView(); beaconResidual() }
|
|
709
|
+
const onVisible = () => { if (document.visibilityState === 'hidden') { flushView(); beaconResidual() } }
|
|
710
|
+
const onOnline = () => { worker ? worker.postMessage({ t: 'nudge' }) : mainUploader?.nudge() }
|
|
711
|
+
window.addEventListener('pagehide', onHide)
|
|
712
|
+
document.addEventListener('visibilitychange', onVisible)
|
|
713
|
+
window.addEventListener('online', onOnline)
|
|
714
|
+
restore.push(() => {
|
|
715
|
+
window.removeEventListener('pagehide', onHide)
|
|
716
|
+
document.removeEventListener('visibilitychange', onVisible)
|
|
717
|
+
window.removeEventListener('online', onOnline)
|
|
718
|
+
})
|
|
251
719
|
}
|
|
252
720
|
|
|
253
|
-
const api = { sessionId, stop, flushNow: handoff, count: () => total }
|
|
254
|
-
if (typeof window !== 'undefined') window.__spectoRec = api
|
|
255
721
|
return api
|
|
256
722
|
}
|
|
257
723
|
|
|
724
|
+
// W3C trace context: a fresh trace for each request the app makes
|
|
725
|
+
const randomHex = (bytes) => {
|
|
726
|
+
const a = new Uint8Array(bytes)
|
|
727
|
+
crypto.getRandomValues(a)
|
|
728
|
+
return Array.from(a, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
729
|
+
}
|
|
730
|
+
const TRACEPARENT = /^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/i
|
|
731
|
+
|
|
732
|
+
// a click's target as tag#id or tag.class.class, up to 3 levels below
|
|
733
|
+
// <body> — never text
|
|
734
|
+
function selectorOf(el) {
|
|
735
|
+
const parts = []
|
|
736
|
+
for (let n = el, i = 0; n && n.nodeType === 1 && i < 3 && n !== document.body && n !== document.documentElement; n = n.parentElement, i++) {
|
|
737
|
+
const tag = String(n.tagName || '').toLowerCase()
|
|
738
|
+
if (n.id) { parts.unshift(`${tag}#${n.id}`); break }
|
|
739
|
+
const cls = typeof n.className === 'string' ? n.className.trim().split(/\s+/).filter((c) => c && !c.startsWith('specto-')).slice(0, 2) : []
|
|
740
|
+
parts.unshift(cls.length ? `${tag}.${cls.join('.')}` : tag)
|
|
741
|
+
}
|
|
742
|
+
return scrubText(parts.join(' > ') || 'body').slice(0, 160)
|
|
743
|
+
}
|
|
744
|
+
|
|
258
745
|
function fmt(a) {
|
|
259
746
|
if (typeof a === 'string') return a
|
|
747
|
+
if (a instanceof Error) return `${a.name}: ${a.message}`
|
|
260
748
|
try { return JSON.stringify(a) } catch { return String(a) }
|
|
261
749
|
}
|