3e0fff3mdshare: markdown editor with the document stored in the URLJeremy Magland 1import { deflateSync, inflateSync, strToU8, strFromU8 } from 'fflate'
3// The document lives in the URL hash as: '#' + base64url(version byte + raw
4// DEFLATE of the UTF-8 text). The hash fragment is never sent to the server,
5// and base64url needs no percent-escaping, so the link survives copy/paste
6// through chat clients and email intact.
8const VERSION = 1
10function toBase64Url(bytes: Uint8Array): string {
11 let bin = ''
12 const chunk = 0x8000
13 for (let i = 0; i < bytes.length; i += chunk) {
14 bin += String.fromCharCode(...bytes.subarray(i, i + chunk))
15 }
16 return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
17}
19function fromBase64Url(s: string): Uint8Array {
20 const b64 = s.replace(/-/g, '+').replace(/_/g, '/')
21 const bin = atob(b64)
22 const bytes = new Uint8Array(bin.length)
23 for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
24 return bytes
25}
27export function encodeDocument(text: string): string {
28 const compressed = deflateSync(strToU8(text), { level: 9 })
29 const payload = new Uint8Array(compressed.length + 1)
30 payload[0] = VERSION
31 payload.set(compressed, 1)
32 return toBase64Url(payload)
33}
35export function decodeDocument(encoded: string): string {
36 const payload = fromBase64Url(encoded)
37 if (payload.length === 0 || payload[0] !== VERSION) {
38 throw new Error(`unsupported document encoding (version ${payload[0]})`)
39 }
40 return strFromU8(inflateSync(payload.subarray(1)))
41}