import { randomUUID } from 'node:crypto'; import { diffAxTree, type BrowserAxNode } from './browserAxState.js'; export interface ObservationIdentity { targetId: string; frameId: string; documentEpoch: string; } export interface ObservationCoverage { collected: 'complete' | 'partial'; scope: 'frame'; reasons: string[]; } export interface BrowserObservation { schemaVersion: 2; snapshotId: string; baseSnapshotId?: string; identity: ObservationIdentity; capturedAt: string; captureFinishedAt?: string; consistency?: 'best_effort_same_document'; source: 'ax' | 'dom'; url: string; title: string; focusedRef?: string; coverage: ObservationCoverage; mode: 'full' | 'diff'; resetReason?: string; records: Array< | { kind: 'added' | 'changed'; node: BrowserAxNode } | { kind: 'removed'; id: string } >; delivery: { complete: boolean; offset: number; returned: number; total: number; nextCursor?: string; }; } type Stored = { owner: string; expires: number; nodes: BrowserAxNode[]; observation: BrowserObservation; bytes: number; delivered: boolean; continuations: Map; }; /** Immutable snapshots. A missing base never means an empty page. Cursors are * opaque, owner-bound and point into a fixed snapshot, not the live browser. */ export class BrowserSnapshotStore { private snapshots = new Map(); private cursors = new Map< string, { owner: string; id: string; offset: number } >(); constructor( private readonly ttlMs = 15 * 60_000, private readonly maxBytes = 24_000_000, ) {} private prune(): void { for (const [id, entry] of this.snapshots) if (entry.expires <= Date.now()) this.snapshots.delete(id); let bytes = [...this.snapshots.values()].reduce( (sum, item) => sum + item.bytes, 0, ); for (const [id, entry] of this.snapshots) { if (bytes <= this.maxBytes && this.snapshots.size <= 128) break; this.snapshots.delete(id); bytes -= entry.bytes; } for (const [cursor, entry] of this.cursors) if (!this.snapshots.has(entry.id)) this.cursors.delete(cursor); while (this.cursors.size > 2048) this.cursors.delete(this.cursors.keys().next().value!); } publish( owner: string, input: Omit< BrowserObservation, 'schemaVersion' | 'snapshotId' | 'mode' | 'records' | 'delivery' >, nodes: BrowserAxNode[], ): BrowserObservation { this.prune(); const base = input.baseSnapshotId ? this.snapshots.get(input.baseSnapshotId) : undefined; const compatible = base && base.owner === owner && base.delivered && JSON.stringify(base.observation.identity) === JSON.stringify(input.identity) && base.observation.coverage.collected === 'complete' && input.coverage.collected === 'complete'; const diff = diffAxTree( compatible ? new Map(base.nodes.map((n) => [n.id, n])) : undefined, nodes, 1, 1, ); const snapshotId = randomUUID(); const observation: BrowserObservation = { ...input, schemaVersion: 2, snapshotId, baseSnapshotId: compatible ? input.baseSnapshotId : undefined, mode: compatible ? 'diff' : 'full', ...(input.baseSnapshotId && !compatible ? { resetReason: 'base_expired_or_incompatible' } : {}), records: [ ...diff.added.map((node) => ({ kind: 'added' as const, node })), ...diff.changed.map((node) => ({ kind: 'changed' as const, node })), ...diff.removed.map((id) => ({ kind: 'removed' as const, id })), ], delivery: { complete: true, offset: 0, returned: 0, total: 0 }, }; const entry = { owner, expires: Date.now() + this.ttlMs, nodes: structuredClone(nodes), observation: structuredClone(observation), bytes: JSON.stringify({ nodes, observation }).length * 2, delivered: false, continuations: new Map(), }; if (entry.bytes > this.maxBytes) throw new Error('observation_too_large: narrow the frame or page scope'); this.snapshots.set(snapshotId, entry); this.prune(); return this.page(owner, snapshotId, 0); } read(owner: string, cursor: string): BrowserObservation { this.prune(); const entry = this.cursors.get(cursor); if (!entry || entry.owner !== owner) throw new Error('snapshot_expired_or_not_owned: observe again'); return this.page(owner, entry.id, entry.offset); } readField( owner: string, snapshotId: string, nodeId: string, field: 'name' | 'description' | 'value' | 'valueText', offset = 0, ) { this.prune(); const entry = this.snapshots.get(snapshotId); if (!entry || entry.owner !== owner) throw new Error('snapshot_expired_or_not_owned'); if ( !['name', 'description', 'value', 'valueText'].includes(field) || !Number.isSafeInteger(offset) || offset < 0 ) throw new Error('invalid_field_request'); const node = entry.nodes.find((n) => n.id === nodeId); const value = node?.[field]; if (typeof value !== 'string' || offset > value.length) throw new Error('field_unavailable'); if (offset > 0 && /[\uDC00-\uDFFF]/.test(value[offset] ?? '') && /[\uD800-\uDBFF]/.test(value[offset - 1]!)) throw new Error('invalid_field_request'); let end = Math.min(offset + 8000, value.length); if (end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1]!)) end--; return { schemaVersion: 2, snapshotId, nodeId, field, text: value.slice(offset, end), offset, length: value.length, complete: end === value.length, nextOffset: end < value.length ? end : undefined, redacted: node?.redacted === true, }; } private page(owner: string, id: string, offset: number): BrowserObservation { const entry = this.snapshots.get(id); if (!entry || entry.owner !== owner) throw new Error('snapshot_expired_or_not_owned: observe again'); const records: BrowserObservation['records'] = []; let size = 0; for (const raw of entry.observation.records.slice(offset)) { const record = structuredClone(raw); if ('node' in record) for (const key of [ 'name', 'description', 'value', 'valueText', ] as const) { const value = record.node[key]; if (value && value.length > 800) { record.node[key] = value.slice(0, 800).replace(/[\uD800-\uDBFF]$/, ''); (record.node.clippedFields ??= []).push(key); (record.node.fieldLengths ??= {})[key] = value.length; } } const length = JSON.stringify(record).length; if (size + length > 10_000 && records.length) break; records.push(record); size += length; } const complete = offset + records.length >= entry.observation.records.length; if (complete) entry.delivered = true; const nextOffset = offset + records.length; let nextCursor = complete ? undefined : entry.continuations.get(nextOffset); // Re-reading an immutable page (including network retries) must not // manufacture new handles and evict unrelated live continuations. if (!complete && (!nextCursor || !this.cursors.has(nextCursor))) { nextCursor = randomUUID(); entry.continuations.set(nextOffset, nextCursor); this.cursors.set(nextCursor, { owner, id, offset: nextOffset, }); } return structuredClone({ ...entry.observation, records, delivery: { complete, offset, returned: records.length, total: entry.observation.records.length, ...(nextCursor ? { nextCursor } : {}), }, }); } } export const browserSnapshots = new BrowserSnapshotStore();