import { deflateSync, inflateSync, strToU8, strFromU8 } from 'fflate' // The document lives in the URL hash as: '#' + base64url(version byte + raw // DEFLATE of the UTF-8 text). The hash fragment is never sent to the server, // and base64url needs no percent-escaping, so the link survives copy/paste // through chat clients and email intact. const VERSION = 1 function toBase64Url(bytes: Uint8Array): string { let bin = '' const chunk = 0x8000 for (let i = 0; i < bytes.length; i += chunk) { bin += String.fromCharCode(...bytes.subarray(i, i + chunk)) } return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') } function fromBase64Url(s: string): Uint8Array { const b64 = s.replace(/-/g, '+').replace(/_/g, '/') const bin = atob(b64) const bytes = new Uint8Array(bin.length) for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) return bytes } export function encodeDocument(text: string): string { const compressed = deflateSync(strToU8(text), { level: 9 }) const payload = new Uint8Array(compressed.length + 1) payload[0] = VERSION payload.set(compressed, 1) return toBase64Url(payload) } export function decodeDocument(encoded: string): string { const payload = fromBase64Url(encoded) if (payload.length === 0 || payload[0] !== VERSION) { throw new Error(`unsupported document encoding (version ${payload[0]})`) } return strFromU8(inflateSync(payload.subarray(1))) }