// The degenerate sync transport: a zip of full doc snapshots plus the local // blob store. Importing is the same idempotent Loro merge every other transport // uses, so a pack can move a workspace between devices with no server anywhere, // and doubles as a backup format. import { unzipSync, zipSync } from 'fflate'; import * as db from '../data/db'; import * as blobs from '../data/blobs'; import { importRemote, openDoc, persistNow } from '../data/loro'; const PACK_VERSION = 1; interface PackManifest { version: number; docs: string[]; blobs: string[]; } export interface ExportOptions { // Include the full edit history (every past change) in the pack. Off by // default: a shallow snapshot exports only the current state, which is far // smaller and is what a backup or device transfer wants. Turn it on to keep // the History tab's timeline after an export/import round-trip. history?: boolean; } export async function exportPack(opts: ExportOptions = {}): Promise { const files: Record = {}; const docIds = await db.listDocIds(); for (const docId of docIds) { const doc = await openDoc(docId); // A shallow snapshot at the current frontiers folds all history into a // fresh baseline, dropping the op log; a full snapshot keeps it. files[`docs/${encodeURIComponent(docId)}.snapshot`] = opts.history ? doc.export({ mode: 'snapshot' }) : doc.export({ mode: 'shallow-snapshot', frontiers: doc.frontiers() }); } const hashes = await db.listBlobHashes(); for (const hash of hashes) { const stored = await db.getBlob(hash); if (stored) files[`blobs/${hash}`] = stored.bytes; } const manifest: PackManifest = { version: PACK_VERSION, docs: docIds, blobs: hashes }; files['manifest.json'] = new TextEncoder().encode(JSON.stringify(manifest)); const zipped = zipSync(files); const bytes = new Uint8Array(zipped.length); bytes.set(zipped); return new Blob([bytes.buffer as ArrayBuffer], { type: 'application/zip' }); } export interface ImportOptions { // Reports install progress as a 0..1 fraction over the manifest's docs and // blobs, so a caller can drive a progress bar. Called once per item; the // synchronous unzip that precedes the loops is not covered (it has no steps // to observe), so a caller showing download progress should treat unzip as a // brief indeterminate gap before the first callback. onProgress?: (fraction: number) => void; } export async function importPack( pack: Blob, opts: ImportOptions = {}, ): Promise<{ docs: number; blobs: number }> { const files = unzipSync(new Uint8Array(await pack.arrayBuffer())); const manifestBytes = files['manifest.json']; if (!manifestBytes) throw new Error('Not a Synapse pack (missing manifest)'); const manifest = JSON.parse(new TextDecoder().decode(manifestBytes)) as PackManifest; if (manifest.version !== PACK_VERSION) throw new Error('Unsupported pack version'); const total = manifest.docs.length + manifest.blobs.length; let done = 0; const step = () => opts.onProgress?.(total ? ++done / total : 1); let docs = 0; for (const docId of manifest.docs) { const bytes = files[`docs/${encodeURIComponent(docId)}.snapshot`]; if (bytes) { await importRemote(docId, [bytes]); docs++; } step(); } let blobCount = 0; for (const hash of manifest.blobs) { const bytes = files[`blobs/${hash}`]; // A pack is untrusted input: only store bytes that hash to the manifest's // claimed hash, so a crafted pack can't poison a document's content. if ( bytes && !(await db.getBlob(hash)) && (await blobs.putVerified(hash, bytes, 'application/octet-stream')) ) { blobCount++; } step(); } await persistNow(); return { docs, blobs: blobCount }; }