Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

read-proof.ts

35 lines1.1 KB

1import { isSequence, ShapeProtocolError } from './index'
2import type { Sequence } from './index'
3​
4/** Evidence for the requested byte boundary, recovered on ordinary GET reads. */
5export interface ReadProof {
6 version: 1
7 offset: string
8 afterSeq: Sequence
9 baselineComplete: boolean
10 nativeCursor?: string
12​
13export function encodeReadProof(proof: ReadProof): string {
14 return `neon1.${encodeURIComponent(JSON.stringify(proof))}`
16​
17export function decodeReadProof(value: string | null): ReadProof {
18 try {
19 if (!value?.startsWith('neon1.')) throw new Error()
20 const proof = JSON.parse(decodeURIComponent(value.slice(6)))
21 if (
22 proof.version !== 1 ||
23 typeof proof.offset !== 'string' ||
24 !isSequence(proof.afterSeq) ||
25 typeof proof.baselineComplete !== 'boolean' ||
26 (proof.nativeCursor !== undefined &&
27 typeof proof.nativeCursor !== 'string') ||
28 (proof.afterSeq === '0' && proof.baselineComplete)
29 )
30 throw new Error()
31 return proof
32 } catch {
33 throw new ShapeProtocolError('Missing or invalid shape read-boundary proof')
34 }