@spectosh/browser 0.2.5 → 0.3.1

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.
@@ -0,0 +1,198 @@
1
+ // Point's trigger (VISION.md §4.4) — the only part of Point in the base SDK.
2
+ // It waits for the project's settings, decides whether this visitor may use
3
+ // Point at all, and on the configured gesture loads the rest (./index.js) and
4
+ // opens it. Everything else loads on first use.
5
+ //
6
+ // Modes (Settings → Point):
7
+ // double-ctrl tap Ctrl (⌘ on a Mac also works) twice quickly — the default
8
+ // hold-alt hold Alt / Option alone for 400 ms
9
+ // hold-ctrl hold Ctrl alone for 400 ms
10
+ // chord Alt+Shift+P
11
+ // custom the project's own combination ({ key, alt, ctrl, shift, meta })
12
+ // none no gesture: the launcher, links and Specto.point() only
13
+ // A modifier that is part of a shortcut (Ctrl+C), a click (Ctrl+click opens
14
+ // a tab) or a key repeat never arms. Who: 'everyone', 'identified' (people
15
+ // the host app identified, plus link holders) or 'link' (only people who
16
+ // opened a page with ?specto=point — remembered for the browser tab).
17
+
18
+ const HOLD_MS = 400
19
+ const TAP_MS = 250 // a tap is shorter than this
20
+ const DOUBLE_MS = 330 // and the second follows within this (release to release)
21
+ const QUIET_MS = 300 // no other key just before the first tap: it is not mid-typing
22
+ const GAP_MIN_MS = 40 // a real double tap has a gap; key chatter does not
23
+ const LINK_KEY = 'specto-point'
24
+ const RECEIPTS = 'specto-point-receipts' // entry.js keeps them: [{ r, at }]
25
+ const CHECK_MS = 6e5 // ask about them at most every 10 minutes
26
+
27
+ // The gesture state machine, DOM-free so it can be tested on its own.
28
+ // feed(event) takes { type: 'keydown'|'keyup'|'pointerdown'|'wheel'|'blur', key,
29
+ // code, repeat, altKey, ctrlKey, metaKey, shiftKey, time } and calls arm()
30
+ // when the gesture completes; release() when a held trigger is let go.
31
+ // the modifier an event is about: by `key`, else by `code` (some synthetic
32
+ // and remote-desktop events carry only one of them)
33
+ const CODE_KEY = { ControlLeft: 'Control', ControlRight: 'Control', AltLeft: 'Alt', AltRight: 'Alt', MetaLeft: 'Meta', MetaRight: 'Meta' }
34
+ const keyOf = (e) => e.key || CODE_KEY[e.code] || ''
35
+
36
+ // a combination matches on the physical key (Alt changes e.key on a Mac);
37
+ // the settings send the chord's too ({ key: 'P', alt: true, shift: true })
38
+ const combo = (e, s) => !!s && !!e.altKey === !!s.alt && !!e.shiftKey === !!s.shift && !!e.ctrlKey === !!s.ctrl && !!e.metaKey === !!s.meta
39
+ && String(e.code || e.key).replace(/^(Key|Digit)/, '').toUpperCase() === s.key
40
+
41
+ export function createTrigger(mode, { arm, release = () => {}, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout, shortcut } = {}) {
42
+ const holdKey = mode === 'hold-alt' ? 'Alt' : mode === 'hold-ctrl' ? 'Control' : null
43
+ let timer = null
44
+ let holding = false // the hold completed and Point was armed by it
45
+ let down = null // { key, at } the lone modifier pressed, nothing else since
46
+ let lastTap = 0
47
+ let lastOther = -Infinity // the last key that was not the tap key
48
+ const cancel = () => { if (timer) clearTimer(timer); timer = null; down = null }
49
+ const isTapKey = (k) => k === 'Control' || k === 'Meta'
50
+ return {
51
+ feed(raw) {
52
+ const e = { ...raw, key: keyOf(raw) }
53
+ const t = e.time ?? now()
54
+ if (e.type === 'blur') { cancel(); lastTap = 0; if (holding) { holding = false; release() } return }
55
+ if (e.type === 'pointerdown' || e.type === 'wheel') { cancel(); lastTap = 0; return } // modifier+click / Ctrl+wheel zoom are the app's
56
+ if (e.type === 'keydown') {
57
+ if (e.repeat) return
58
+ if (shortcut || mode === 'none') {
59
+ if (combo(e, shortcut)) arm(mode)
60
+ return
61
+ }
62
+ if (holdKey) {
63
+ if (e.key === holdKey && !down) {
64
+ down = { key: e.key, at: t }
65
+ timer = setTimer(() => { timer = null; if (down) { down = null; holding = true; arm(mode) } }, HOLD_MS)
66
+ } else cancel() // another key: a shortcut
67
+ return
68
+ }
69
+ // double-ctrl
70
+ if (isTapKey(e.key) && !down) down = { key: e.key, at: t, quiet: t - lastOther >= QUIET_MS }
71
+ else { down = null; lastTap = 0; lastOther = t }
72
+ return
73
+ }
74
+ if (e.type === 'keyup') {
75
+ if (holdKey) {
76
+ if (e.key === holdKey) { cancel(); if (holding) { holding = false; release() } }
77
+ return
78
+ }
79
+ if (mode === 'double-ctrl' && down && e.key === down.key) {
80
+ const d = down
81
+ down = null
82
+ if (t - d.at >= TAP_MS) { lastTap = 0; return }
83
+ // the second tap: soon after the first, but not chatter
84
+ if (lastTap && t - lastTap < DOUBLE_MS && d.at - lastTap >= GAP_MIN_MS) { lastTap = 0; arm('double-ctrl'); return }
85
+ // a first tap counts only when nothing else was being typed
86
+ lastTap = d.quiet ? t : 0
87
+ }
88
+ }
89
+ },
90
+ cancel,
91
+ }
92
+ }
93
+
94
+ // a report this browser sent asked to hear when it's fixed (entry.js keeps
95
+ // the receipts): ask, now and then; a fixed one shows its note once
96
+ function fixedYet(rec, load, open) {
97
+ try {
98
+ const t = Date.now()
99
+ const list = JSON.parse(localStorage.getItem(RECEIPTS) || '[]').filter((x) => t - x.at < 7776e6)
100
+ if (!list.length || t - (+localStorage.getItem(RECEIPTS + '-at') || 0) < CHECK_MS) return
101
+ localStorage.setItem(RECEIPTS + '-at', t)
102
+ fetch(rec._point.endpoint + '-status', { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=UTF-8' }, credentials: 'omit', body: JSON.stringify({ key: rec._point.key, receipts: list.map((x) => x.r) }) })
103
+ .then((r) => (r.ok ? r.json() : null))
104
+ .then((j) => {
105
+ if (!j) return
106
+ const done = [...(j.gone || []), ...(j.fixed || []).map((x) => x.receipt)]
107
+ localStorage.setItem(RECEIPTS, JSON.stringify(list.filter((x) => !done.includes(x.r))))
108
+ if (j.fixed?.length) load().then((m) => m.showFixed?.(j.fixed, { open }))
109
+ }).catch(() => {})
110
+ } catch { /* storage off */ }
111
+ }
112
+
113
+ // may this visitor use Point? (the project's `who`)
114
+ export function allowed(who, { identified, link }) {
115
+ if (who === 'everyone') return true
116
+ if (who === 'link') return link
117
+ return link || Boolean(identified) // 'identified' (default): identified people and link holders
118
+ }
119
+
120
+ // ?specto=point (or #…specto=point) anywhere in the address
121
+ function linkGranted() {
122
+ try {
123
+ if (/[?&#]specto=point\b/.test(location.href)) sessionStorage.setItem(LINK_KEY, '1')
124
+ return sessionStorage.getItem(LINK_KEY) === '1'
125
+ } catch { return false }
126
+ }
127
+
128
+ // Wire the trigger to a running recorder. load() → Promise<{ openPoint,
129
+ // mountEntry }>. Returns { open(via), stop() } — open() is the host app's own
130
+ // entry point (Specto.point()): it skips the gesture and the `who` check,
131
+ // since the app chose to offer it. A ?specto=point link opens Point on
132
+ // arrival; the launcher, the nudge and the reminder (VISION.md §4.10) live
133
+ // in point.js, loaded on idle once this visitor may use Point. `launcher`:
134
+ // the page's own say over the launcher (false: none here; { position,
135
+ // offset, label, color } over Settings → Point) — also launcher() later.
136
+ export function installPoint(rec, load, { launcher } = {}) {
137
+ let cfg = null
138
+ let session = null // the open Point, while it is open
139
+ let opening = null
140
+ let entry = null // the launcher, nudge and reminder, once mounted
141
+ let mount = null // mounts them once this visitor may use Point
142
+ const may = () => allowed(cfg.who, { identified: rec._point?.identified(), link: linkGranted() })
143
+ const open = async (via = 'api', target = null, about = null) => {
144
+ if (session || opening || !rec?._point) return session
145
+ opening = (async () => {
146
+ const remote = await rec._ready
147
+ cfg = remote?.point || cfg
148
+ if (!cfg?.enabled) return null
149
+ const mod = await load()
150
+ session = mod.openPoint(rec, { ...cfg, via, target, about, onClose: () => { session = null } })
151
+ return session
152
+ })().catch((e) => { try { console.warn('[specto] Point:', e?.message || e) } catch { /* no console */ } return null }).finally(() => { opening = null })
153
+ return opening
154
+ }
155
+ let trigger = null
156
+ const onKey = (e) => {
157
+ // keys typed into Point itself (its notes) are its own
158
+ if (session && e.composedPath?.().some((n) => n?.id === 'specto-point')) return
159
+ trigger?.feed({ type: e.type, key: e.key, code: e.code, repeat: e.repeat, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey })
160
+ }
161
+ const feed = (type) => () => trigger?.feed({ type })
162
+ // [target, event, handler, options]
163
+ const L = [[window, 'keydown', onKey, true], [window, 'keyup', onKey, true], [window, 'pointerdown', feed('pointerdown'), true], [window, 'wheel', feed('wheel'), { capture: true, passive: true }], [window, 'blur', feed('blur')]]
164
+ let listening = false
165
+ rec._ready?.then((remote) => {
166
+ cfg = remote?.point || null
167
+ if (!cfg?.enabled) return
168
+ linkGranted() // remember ?specto=point for the tab, whatever page it was on
169
+ // who may use it is checked at each gesture: identify() can come later
170
+ trigger = createTrigger(cfg.trigger, {
171
+ shortcut: cfg.shortcut,
172
+ arm: () => {
173
+ if (!may()) return
174
+ if (session) session.toggle?.()
175
+ else open('shortcut')
176
+ },
177
+ release: () => session?.released?.(),
178
+ })
179
+ for (const [t, ev, fn, o] of L) t.addEventListener(ev, fn, o)
180
+ listening = true
181
+ // a link from the "fixed" email carries #specto-about=<receipt>
182
+ const about = (location.hash.match(/specto-about=([\w-]{20,40})/) || [])[1]
183
+ if (/[?&#]specto=point\b/.test(location.href)) open(about ? 'fixed' : 'link', null, about)
184
+ if (cfg.notify) fixedYet(rec, load, open)
185
+ mount = () => { if (listening && !entry) may() ? load().then((m) => { entry = entry || m.mountEntry?.(rec, cfg, { open, may, local: launcher }) }) : setTimeout(mount, 2000) }
186
+ if ((cfg.launcher && launcher !== false) || launcher || cfg.nudge || cfg.hint || (cfg.context && cfg.context !== 'off')) setTimeout(mount, 600)
187
+ })
188
+ return {
189
+ open: (via) => open(via || 'api'),
190
+ launcher(o) { launcher = o; entry ? entry.launcher(o) : o && mount?.() },
191
+ stop() {
192
+ if (listening) for (const [t, ev, fn, o] of L) t.removeEventListener(ev, fn, o)
193
+ listening = false
194
+ session?.close?.()
195
+ entry?.stop?.()
196
+ },
197
+ }
198
+ }
@@ -0,0 +1,131 @@
1
+ // Talking while pointing (VISION.md §4.6). Only when the instance can
2
+ // transcribe and the project left voice on (the settings say `voice: true`),
3
+ // and only after the person agrees — the first time the rail explains it and
4
+ // the browser asks for the microphone.
5
+ //
6
+ // Live, phrase by phrase: the microphone feeds one MediaRecorder per phrase.
7
+ // A phrase ends at a pause (quiet for PAUSE_MS after speech), when the
8
+ // person moves to another marker (cut()), or at MAX_PHRASE_MS; each finished
9
+ // phrase is a complete little file handed to onPhrase, which the rail sends
10
+ // to the instance's transcription service — the words come back in about a
11
+ // second and land on the marker that was current. Phrases with no speech in
12
+ // them are dropped unsent. The Web Speech API is never used: it sends audio
13
+ // to a party no one chose.
14
+ //
15
+ // `keep` also records the whole thing in one file, for a project that lets
16
+ // people attach their recording (30 days, then purged — speech.js).
17
+ // `level()` reads the loudness (0..1) for the pulsing ring.
18
+
19
+ const TYPES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm']
20
+ const SPEAKING = 0.08 // level that counts as speech (the room's hum stays near 0.02)
21
+ const PAUSE_MS = 700
22
+ const MAX_PHRASE_MS = 20_000
23
+ export const voiceSupported = () => typeof window !== 'undefined' && typeof window.MediaRecorder !== 'undefined' && Boolean(navigator.mediaDevices?.getUserMedia)
24
+
25
+ export async function startVoice({ onPhrase = () => {}, keep = false } = {}) {
26
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } })
27
+ const mimeType = TYPES.find((t) => { try { return MediaRecorder.isTypeSupported(t) } catch { return false } }) || ''
28
+ const opts = { ...(mimeType ? { mimeType } : {}), audioBitsPerSecond: 16_000 } // speech: Whisper hears 16 kHz anyway — ~2 KB/s
29
+ const startedAt = Date.now()
30
+ // loudness: for the ring and for finding pauses
31
+ let analyser = null
32
+ let ctx = null
33
+ let data = null
34
+ try {
35
+ const AC = window.AudioContext || window.webkitAudioContext
36
+ ctx = new AC()
37
+ const src = ctx.createMediaStreamSource(stream)
38
+ analyser = ctx.createAnalyser()
39
+ analyser.fftSize = 1024 // ~20 ms a look: short syllables are not missed
40
+ data = new Uint8Array(analyser.fftSize)
41
+ src.connect(analyser)
42
+ } catch { /* no pauses found: phrases end at marker changes and MAX_PHRASE_MS */ }
43
+ const level = () => {
44
+ if (!analyser) return 0
45
+ analyser.getByteTimeDomainData(data)
46
+ let sum = 0
47
+ for (const v of data) sum += (v - 128) * (v - 128)
48
+ return Math.min(1, Math.sqrt(sum / data.length) / 40)
49
+ }
50
+
51
+ // ---- phrases ------------------------------------------------------------------
52
+ let phrase = null // { rec, chunks, at, spoke, loudAt }
53
+ let closing = false
54
+ const begin = () => {
55
+ if (closing) return
56
+ const rec = new MediaRecorder(stream, opts)
57
+ const p = { rec, chunks: [], at: Date.now(), spoke: !analyser, loudAt: 0 }
58
+ rec.ondataavailable = (e) => { if (e.data?.size) p.chunks.push(e.data) }
59
+ rec.start()
60
+ phrase = p
61
+ }
62
+ // end the current phrase → Promise (resolves once it was handed over)
63
+ const end = () => new Promise((resolve) => {
64
+ const p = phrase
65
+ phrase = null
66
+ if (!p) return resolve()
67
+ p.rec.onstop = () => {
68
+ if (p.spoke && p.chunks.length) {
69
+ const mime = p.rec.mimeType || mimeType || 'audio/webm'
70
+ try { onPhrase({ blob: new Blob(p.chunks, { type: mime }), mime, startedAt: p.at, endedAt: Date.now() }) } catch { /* the rail's problem */ }
71
+ }
72
+ resolve()
73
+ }
74
+ try { p.rec.stop() } catch { resolve() }
75
+ })
76
+ // a new phrase from now: what follows belongs to the marker that is current
77
+ // now, even if nothing was said yet (end() drops a phrase without speech)
78
+ const cut = () => { if (phrase) { end(); begin() } }
79
+ begin()
80
+ const timer = setInterval(() => {
81
+ if (!phrase) return
82
+ const now = Date.now()
83
+ if (analyser && level() >= SPEAKING) { phrase.spoke = true; phrase.loudAt = now }
84
+ if (phrase.spoke && ((phrase.loudAt && now - phrase.loudAt > PAUSE_MS) || now - phrase.at > MAX_PHRASE_MS)) cut()
85
+ }, 50)
86
+
87
+ // ---- the whole recording, when it may be kept ------------------------------------
88
+ let whole = null
89
+ if (keep) {
90
+ whole = { rec: new MediaRecorder(stream, opts), chunks: [] }
91
+ whole.rec.ondataavailable = (e) => { if (e.data?.size) whole.chunks.push(e.data) }
92
+ whole.rec.start(1000)
93
+ }
94
+
95
+ let stopped = null
96
+ // → { blob, mime, startedAt } of the whole recording when kept, else null;
97
+ // the last phrase is handed over first, and the tracks are released
98
+ const stop = () => {
99
+ if (stopped) return stopped
100
+ closing = true
101
+ clearInterval(timer)
102
+ stopped = (async () => {
103
+ await end()
104
+ let out = null
105
+ if (whole) {
106
+ out = await new Promise((resolve) => {
107
+ const mime = whole.rec.mimeType || mimeType || 'audio/webm'
108
+ const done = () => resolve({ blob: new Blob(whole.chunks, { type: mime }), mime, startedAt })
109
+ if (whole.rec.state === 'inactive') return done()
110
+ whole.rec.onstop = done
111
+ try { whole.rec.stop() } catch { done() }
112
+ })
113
+ }
114
+ for (const t of stream.getTracks()) t.stop()
115
+ try { ctx?.close() } catch { /* already closed */ }
116
+ return out
117
+ })()
118
+ return stopped
119
+ }
120
+ return { startedAt, level, cut, stop }
121
+ }
122
+
123
+ // a Blob → base64 (reports and phrases travel as JSON bodies)
124
+ export function base64Of(blob) {
125
+ return new Promise((resolve, reject) => {
126
+ const r = new FileReader()
127
+ r.onload = () => resolve(String(r.result).split(',')[1] || '')
128
+ r.onerror = () => reject(r.error)
129
+ r.readAsDataURL(blob)
130
+ })
131
+ }
package/src/react.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // records the page, not a component). On the server it renders its children
16
16
  // and does nothing else. React is a peer dependency.
17
17
  import { Component, createContext, createElement, useContext, useEffect, useState } from 'react'
18
- import { startRecording, identify, track, captureError, sessionUrl, stopRecording, grantConsent, revokeConsent, optOut, optIn } from './index.js'
18
+ import { startRecording, identify, track, captureError, sessionUrl, stopRecording, grantConsent, revokeConsent, optOut, optIn, openPoint } from './index.js'
19
19
 
20
20
  const api = { identify, track, captureError, sessionUrl, stop: stopRecording, grantConsent, revokeConsent, optOut, optIn }
21
21
  const SpectoContext = createContext(api)
@@ -63,8 +63,14 @@ export class SpectoErrorBoundary extends Component {
63
63
  render() {
64
64
  const { error } = this.state
65
65
  if (!error) return this.props.children
66
- const { fallback } = this.props
67
- return typeof fallback === 'function' ? fallback({ error, reset: this.reset }) : (fallback ?? null)
66
+ const { fallback, reportButton } = this.props
67
+ // reportButton: a "Show us what happened" button under the fallback that
68
+ // opens Point (VISION.md §4.10) — true for ours, or a string for its label
69
+ const report = () => openPoint('error')
70
+ const shown = typeof fallback === 'function' ? fallback({ error, reset: this.reset, report }) : (fallback ?? null)
71
+ if (!reportButton) return shown
72
+ const button = createElement('button', { type: 'button', onClick: report, 'data-specto-report': '' }, typeof reportButton === 'string' ? reportButton : 'Show us what happened')
73
+ return createElement('div', null, shown, button)
68
74
  }
69
75
  }
70
76
 
package/src/recorder.js CHANGED
@@ -12,6 +12,10 @@
12
12
  // requests; the request's trace id links it to the server's spans
13
13
  // - heatmaps: each click's page position and a selector (tag, id,
14
14
  // classes — never text), and how far down each page view scrolled
15
+ // - dead clicks: a click on something that looks clickable and does
16
+ // nothing — no DOM change, request or navigation within a second
17
+ // - for Point (the cursor mode, ./point/): a short in-memory memory of
18
+ // recent requests, console lines and clicks — never sent by itself
15
19
  //
16
20
  // Starts capturing the moment startRecording runs: errors, console, network
17
21
  // and the DOM are held in memory while the project's settings load (one
@@ -23,17 +27,21 @@
23
27
  // sessionStorage; a new session starts after 30 minutes without interaction
24
28
  // or after 4 hours. Batches are numbered so the server de-duplicates retries.
25
29
  //
26
- // Privacy: inputs are always masked; strict privacy masks all text and keeps
27
- // only the path of recorded URLs;
30
+ // Privacy: inputs are always masked; strict privacy masks all text (except
31
+ // what the site shows: `specto-unmask`, the `unmask` option or the
32
+ // project's selectors) and keeps only the path of recorded URLs;
28
33
  // `specto-mask` / `specto-block` classes for fine control; sensitive
29
34
  // attributes, URL credentials and PII-looking text are scrubbed in the
30
- // browser. Honors Do-Not-Track / Global Privacy Control, an opt-out flag, and
31
- // consent mode (nothing is recorded or stored until Specto.consent(true)).
35
+ // browser. Honors an opt-out flag, Do-Not-Track / Global Privacy Control when
36
+ // the project or the page asks (Brave sends GPC on every page, so honoring it
37
+ // by default would hide every Brave visitor), and consent mode (nothing is
38
+ // recorded or stored until Specto.consent(true)).
32
39
  import { record } from 'rrweb'
33
40
  import { createUploader } from './uploader.js'
34
41
  import { resolveDestination } from './destination.js'
42
+ import { scrubText, showsText } from './scrub.js'
35
43
 
36
- export const SDK_VERSION = '0.2.5'
44
+ export const SDK_VERSION = '0.3.1'
37
45
 
38
46
  // ---- privacy helpers --------------------------------------------------------
39
47
  // Attribute scrubbing — rrweb masks text/inputs but NOT element attributes,
@@ -65,20 +73,7 @@ function scrubEvent(e, strict) {
65
73
  return e
66
74
  }
67
75
 
68
- // Free text the app itself produces (console lines, error messages) can carry
69
- // PII. Redact the shapes that are never useful for debugging.
70
- const TEXT_SCRUBBERS = [
71
- [/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]'],
72
- [/\beyJ[\w-]{6,}\.[\w-]{6,}\.[\w-]{6,}\b/g, '[jwt]'],
73
- [/\b(Bearer|Basic)\s+[\w.~+/=-]{8,}/gi, '$1 [token]'],
74
- [/\b(?:\d[ -]?){13,19}\b/g, '[number]'], // card / account numbers
75
- [/\b(sk|pk|rk)_(live|test)_[\w]{8,}\b/g, '[key]'],
76
- ]
77
- export function scrubText(s) {
78
- let out = String(s ?? '')
79
- for (const [re, rep] of TEXT_SCRUBBERS) out = out.replace(re, rep)
80
- return out
81
- }
76
+ export { scrubText }
82
77
 
83
78
  // ---- network capture helpers ------------------------------------------------
84
79
  // fetch() accepts a string, a URL (has .href, NOT .url), a Request (has .url),
@@ -258,7 +253,12 @@ async function remoteConfig(url, key) {
258
253
  * endpoint full ingest URL (legacy; overrides host)
259
254
  * configUrl project config URL (default: endpoint's /api/sdk/config; false = none)
260
255
  * privacy 'balanced' | 'strict' (strict masks all text, drops console text and URL query strings)
256
+ * unmask under strict privacy, a CSS selector list whose text is shown (scrubbed),
257
+ * e.g. 'nav, .price' — also the `specto-unmask` class / data-specto-unmask
261
258
  * sampleRate 0..1 — fraction of sessions recorded (decided once per session)
259
+ * privacySignals 'respect' never records visitors whose browser sends
260
+ * Do-Not-Track or Global Privacy Control; by default the
261
+ * project's setting decides (Settings → Privacy & masking)
262
262
  * consent 'granted' (default) | 'required' (wait for Specto.consent(true))
263
263
  * console capture console (default true)
264
264
  * networkDetails devtools-style request details (default true)
@@ -266,6 +266,8 @@ async function remoteConfig(url, key) {
266
266
  * backend spans join the replay (default false)
267
267
  * traceOrigins more origins to send it to, e.g. ['https://api.example.com']
268
268
  * (their CORS must allow the traceparent header)
269
+ * release your build's version (a git SHA or tag): bugs know the release that
270
+ * introduced them (also <meta name="specto-release"> or data-release)
269
271
  * createWorker () => Worker (the snippet/npm builds pass an inlined worker)
270
272
  */
271
273
  export function startRecording(opts = {}) {
@@ -280,14 +282,17 @@ export function startRecording(opts = {}) {
280
282
  const { key, endpoint, configUrl } = dest
281
283
 
282
284
  const handle = { disabled: true, reason: 'starting', sessionId: null, stop() {}, flushNow() {}, count: () => 0, identify() {}, track() {}, sessionUrl: () => null }
283
- if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl) return Object.assign(handle, { reason: 'dnt' })
285
+ // Do-Not-Track / GPC: honored here when the page asks; otherwise once the
286
+ // project's setting arrives (_begin) — nothing is sent before it does
287
+ const signal = navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true
288
+ if (signal && opts.privacySignals === 'respect') return Object.assign(handle, { reason: 'dnt' })
284
289
  if (isOptedOut()) return Object.assign(handle, { reason: 'opted-out' })
285
290
  if (opts.consent === 'required' && !hasConsent()) return Object.assign(handle, { reason: 'consent-required' })
286
291
 
287
292
  // capture starts now; it's sent once the project config resolves (one
288
293
  // edge-cached request). A host the SDK assumed must confirm the key first:
289
294
  // a couple of retries, then nothing is recorded on this page.
290
- const api = createRecorder(opts, dest)
295
+ const api = createRecorder(opts, dest, signal)
291
296
  window.__spectoRec = api
292
297
  const confirm = (attempt) => remoteConfig(configUrl, key).then((remote) => {
293
298
  if (remote?.failed && dest.guessed && attempt < 3) return setTimeout(() => confirm(attempt + 1), attempt * 2000)
@@ -303,7 +308,7 @@ const warn = (msg) => { try { console.warn(`[specto] ${msg}`) } catch { /* no co
303
308
  // DOM limit the replay restarts from a fresh snapshot instead
304
309
  const EARLY_MAX = { dom: 4000, console: 200, network: 300, event: 300, identify: 20 }
305
310
 
306
- function createRecorder(opts, dest) {
311
+ function createRecorder(opts, dest, signal = false) {
307
312
  const { key, endpoint } = dest
308
313
  let buffer = []
309
314
  let total = 0
@@ -317,7 +322,7 @@ function createRecorder(opts, dest) {
317
322
  let session = null // { id, sk, b, started, active, sampled }
318
323
  // the page's own settings apply until the project's arrive (then the
319
324
  // stricter of both); `now()` is whichever is in force
320
- const local = { strict: opts.privacy === 'strict', console: opts.console !== false, networkDetails: opts.networkDetails !== false }
325
+ const local = { strict: opts.privacy === 'strict', unmask: typeof opts.unmask === 'string' ? opts.unmask : '', console: opts.console !== false, networkDetails: opts.networkDetails !== false }
321
326
  let cfg = null
322
327
  const now = () => cfg || local
323
328
  // the page an error or rage click happened on (sessions span page loads)
@@ -332,6 +337,26 @@ function createRecorder(opts, dest) {
332
337
  let unconfirmed = []
333
338
  let mainUploader = null
334
339
  let lastActive = Date.now()
340
+ // epoch ms of the recorder's clock origin: payload `t` + this = when
341
+ const epoch0 = Date.now() - (performance.now() - t0)
342
+ const release = releaseOf(opts)
343
+
344
+ // Point's memory (never sent by itself): the last few requests, console
345
+ // lines and interactions with their times, and the elements last clicked
346
+ // (kept as references only, to find the requests a click caused)
347
+ const recent = { network: [], console: [], event: [], clicks: [] }
348
+ const RECENT_MAX = { network: 100, console: 60, event: 80, clicks: 40 }
349
+ const remember = (kind, p) => {
350
+ const list = recent[kind]
351
+ if (!list || !p || typeof p !== 'object') return
352
+ list.push({ ...p, at: Math.round(epoch0 + (Number(p.t) || 0)) })
353
+ if (list.length > RECENT_MAX[kind]) list.shift()
354
+ }
355
+ let netSeen = 0 // requests and errors so far (a dead click watches it stay put)
356
+ let identified = null
357
+ let pointOn = false // Point is open: its clicks are not the app's
358
+ let readyResolve
359
+ const ready = new Promise((r) => { readyResolve = r })
335
360
 
336
361
  // everything captured before recording begins (the project's settings are
337
362
  // still loading): kept in memory, sent once it does — filtered by those
@@ -341,6 +366,7 @@ function createRecorder(opts, dest) {
341
366
  let domOverflow = false
342
367
  const push = (kind, payload) => {
343
368
  if (stopped) return
369
+ if (kind !== 'dom') { remember(kind, payload); if (kind === 'network' || payload?.type === 'error') netSeen++ }
344
370
  if (!started) {
345
371
  const n = (earlyCount[kind] = (earlyCount[kind] || 0) + 1)
346
372
  if (n > (EARLY_MAX[kind] ?? 100)) { if (kind === 'dom') domOverflow = true; return }
@@ -378,7 +404,7 @@ function createRecorder(opts, dest) {
378
404
 
379
405
  function send(events) {
380
406
  if (!events.length || !session?.sampled) return
381
- 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 }) }
407
+ 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(), ...(release ? { release } : {}) }, events }) }
382
408
  session.active = Math.max(session.active, lastActive)
383
409
  persist()
384
410
  if (worker) {
@@ -443,7 +469,8 @@ function createRecorder(opts, dest) {
443
469
  // attach your own user id (+ a few flat traits) to the current session
444
470
  identify(id, traits) {
445
471
  if (id == null || id === '') return
446
- push('identify', { id: String(id).slice(0, 256), traits: traits && typeof traits === 'object' ? traits : undefined })
472
+ identified = String(id).slice(0, 256)
473
+ push('identify', { id: identified, traits: traits && typeof traits === 'object' ? traits : undefined })
447
474
  },
448
475
  // custom product events, searchable on the session timeline
449
476
  track(name, props) {
@@ -464,8 +491,22 @@ function createRecorder(opts, dest) {
464
491
  sessionUrl() {
465
492
  try { return session ? `${dest.host || new URL(endpoint, location.href).origin}/#replay/${session.id}` : null } catch { return null }
466
493
  },
494
+ // ---- for Point (./point/) ----
495
+ // resolves with the project's settings once they arrive (null: never)
496
+ _ready: ready,
497
+ _point: {
498
+ key,
499
+ endpoint: endpoint.replace(/\/api\/ingest$/, '/api/point'),
500
+ release,
501
+ strict: () => now().strict,
502
+ unmask: () => now().unmask || '',
503
+ identified: () => identified,
504
+ recent: () => ({ network: recent.network.slice(), console: recent.console.slice(), event: recent.event.slice(), clicks: recent.clicks.slice() }),
505
+ active: (on) => { pointOn = Boolean(on) },
506
+ },
467
507
  stop(reason) {
468
508
  if (stopped) return
509
+ readyResolve(null)
469
510
  stopped = true
470
511
  api.disabled = true
471
512
  api.reason = reason || 'stopped'
@@ -490,9 +531,14 @@ function createRecorder(opts, dest) {
490
531
  api.stop('unconfirmed')
491
532
  return warn(`couldn't reach ${where} to confirm the key ${key}, so this page isn't recorded.`)
492
533
  }
493
- if (r.enabled === false) return api.stop('recording-disabled')
534
+ if (r.enabled === false) { readyResolve(null); return api.stop('recording-disabled') }
535
+ // a privacy signal the project honors — or one we couldn't ask about
536
+ if (signal && (r.respectPrivacySignals === true || r.failed)) return api.stop('dnt')
537
+ readyResolve(r)
494
538
  cfg = {
495
539
  strict: opts.privacy === 'strict' || r.privacy === 'strict',
540
+ // the text a strict page shows: the page's own list and the project's
541
+ unmask: [typeof opts.unmask === 'string' ? opts.unmask : '', typeof r.unmask === 'string' ? r.unmask : ''].filter(Boolean).join(','),
496
542
  console: opts.console !== false && r.captureConsole !== false,
497
543
  networkDetails: opts.networkDetails !== false && r.captureNetworkDetails !== false,
498
544
  sampleRate: Math.min(opts.sampleRate ?? 1, typeof r.sampleRate === 'number' ? r.sampleRate : 1),
@@ -542,6 +588,9 @@ function createRecorder(opts, dest) {
542
588
  maskInputOptions: { password: true, email: true, tel: true, color: false },
543
589
  maskTextClass: 'specto-mask',
544
590
  maskTextSelector: strict ? '*' : undefined,
591
+ // every masked text comes here: shown (and scrubbed) only where a strict
592
+ // page shows it, never inside specto-mask
593
+ maskTextFn: (text, el) => (now().strict && showsText(el, now().unmask) ? scrubText(text) : String(text).replace(/\S/g, '*')),
545
594
  blockClass: 'specto-block',
546
595
  recordCanvas: false,
547
596
  collectFonts: false,
@@ -771,6 +820,7 @@ function createRecorder(opts, dest) {
771
820
  // ---- rage clicks (>=3 clicks within 800ms near same spot) ----
772
821
  let clicks = []
773
822
  const onClick = (e) => {
823
+ if (pointOn) return
774
824
  const now = performance.now()
775
825
  clicks = clicks.filter((c) => now - c.t < 800 && Math.abs(c.x - e.clientX) < 40 && Math.abs(c.y - e.clientY) < 40)
776
826
  clicks.push({ t: now, x: e.clientX, y: e.clientY })
@@ -809,10 +859,34 @@ function createRecorder(opts, dest) {
809
859
  requestAnimationFrame(() => { scrollPending = false; measure() })
810
860
  }
811
861
  const onHeatClick = (e) => {
862
+ if (pointOn) return
863
+ recent.clicks.push({ at: Date.now(), el: e.target })
864
+ if (recent.clicks.length > RECENT_MAX.clicks) recent.clicks.shift()
865
+ watchDead(e)
812
866
  if (!view || view.clicks >= 300) return
813
867
  view.clicks++
814
868
  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) })
815
869
  }
870
+ // ---- dead clicks: something that looks clickable, clicked, and for a
871
+ // second nothing — no DOM change, no request, no navigation (and no
872
+ // error: then the error is the bug)
873
+ let deadWatch = null
874
+ const watchDead = (e) => {
875
+ const t = e.target
876
+ const el = t?.closest?.('a,button,[role=button],[role=link],[role=tab],[onclick],[type=submit],summary') || (t?.nodeType === 1 && cursorIsPointer(t) ? t : null)
877
+ if (!el || deadWatch || typeof MutationObserver === 'undefined') return
878
+ const net0 = netSeen
879
+ const href = location.href
880
+ let changed = false
881
+ const mo = new MutationObserver(() => { changed = true })
882
+ try { mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }) } catch { return }
883
+ deadWatch = setTimeout(() => {
884
+ mo.disconnect()
885
+ deadWatch = null
886
+ if (!changed && netSeen === net0 && location.href === href && !pointOn) push('event', { t: rel(), type: 'dead', target: selectorOf(el), path: herePath() })
887
+ }, 1000)
888
+ }
889
+ restore.push(() => { if (deadWatch) clearTimeout(deadWatch) })
816
890
  window.addEventListener('scroll', onScroll, { passive: true, capture: true })
817
891
  window.addEventListener('click', onHeatClick, true)
818
892
  restore.push(() => { window.removeEventListener('scroll', onScroll, { capture: true }); window.removeEventListener('click', onHeatClick, true) })
@@ -849,12 +923,14 @@ const randomHex = (bytes) => {
849
923
  }
850
924
  const TRACEPARENT = /^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/i
851
925
 
852
- // a click's target as tag#id or tag.class.class, up to 3 levels below
853
- // <body> — never text
926
+ // a click's target as tag[data-testid], tag#id or tag.class.class, up to 3
927
+ // levels below <body> — never text
854
928
  function selectorOf(el) {
855
929
  const parts = []
856
930
  for (let n = el, i = 0; n && n.nodeType === 1 && i < 3 && n !== document.body && n !== document.documentElement; n = n.parentElement, i++) {
857
931
  const tag = String(n.tagName || '').toLowerCase()
932
+ const tid = n.getAttribute('data-testid')
933
+ if (tid) { parts.unshift(`[data-testid="${tid}"]`); break }
858
934
  if (n.id) { parts.unshift(`${tag}#${n.id}`); break }
859
935
  const cls = typeof n.className === 'string' ? n.className.trim().split(/\s+/).filter((c) => c && !c.startsWith('specto-')).slice(0, 2) : []
860
936
  parts.unshift(cls.length ? `${tag}.${cls.join('.')}` : tag)
@@ -862,6 +938,17 @@ function selectorOf(el) {
862
938
  return scrubText(parts.join(' > ') || 'body').slice(0, 160)
863
939
  }
864
940
 
941
+ // the customer's release: the option, or <meta name="specto-release"
942
+ // content="…"> (the snippet passes data-release as the option)
943
+ function releaseOf(opts) {
944
+ let r = opts.release
945
+ try { if (!r) r = document.querySelector('meta[name="specto-release"]')?.getAttribute('content') } catch { /* no document */ }
946
+ return r ? String(r).trim().slice(0, 80) || null : null
947
+ }
948
+ function cursorIsPointer(el) {
949
+ try { return getComputedStyle(el).cursor === 'pointer' } catch { return false }
950
+ }
951
+
865
952
  function fmt(a) {
866
953
  if (typeof a === 'string') return a
867
954
  if (a instanceof Error) return `${a.name}: ${a.message}`