1/**2 * A snapshot: a composition written as text that can travel in a link.3 *4 * A snapshot holds what was authored and nothing else: groups with their5 * arrangements, and content with its roles and wording, in order. It has no6 * width, no selection and no history, so wherever it is opened the7 * composition responds to the space it finds there. A snapshot never8 * changes. Editing starts from a copy of what it holds.9 *10 * The text is versioned JSON, as UTF-8, in the URL-safe base64 alphabet with11 * no padding. Reading one is parsing and checking. Nothing in it is12 * evaluated, and the composition is built afresh from the six known kinds,13 * so no other field a link carried survives.14 *15 * This is not `Snapshot` in `working-copy.ts`, which is one state in a16 * working copy's Undo history.17 */18importtype { Composition } from"./composition.ts";19import { restoreWorkingTree } from"./working-copy.ts";2021/** The format written by `encodeSnapshot`, and the only one read. */22exportconstsnapshotVersion=1;2324/**25 * The most characters a snapshot may have. A composition that needs more is26 * refused, never cut short, and a longer text is not read at all.27 */28exportconstsnapshotLimit=16_384;29/** Four characters carry three bytes. */30constbyteLimit=Math.floor((snapshotLimit*3) /4);3132/** Why a composition has no snapshot, or a text is not one. */33exporttypeSnapshotProblem=34/** It needs more than `snapshotLimit` characters. */35|"too-large"36/** The text is not this encoding of JSON: damaged, cut short or not one. */37|"malformed"38/** It states a version other than `snapshotVersion`. */39|"unsupported-version"40/** What it holds is not a composition a working copy accepts. */41|"not-a-composition";4243/** Thrown by `encodeSnapshot` and `decodeSnapshot`. Its message is for an author. */44exportclassSnapshotErrorextendsError {45readonlyproblem:SnapshotProblem;46constructor(problem:SnapshotProblem, message:string) {47super(message);48this.name="SnapshotError";49this.problem=problem;50 }51}5253consturlSafe=/^[A-Za-z0-9_-]+$/;5455functiontextOf(bytes:Uint8Array):string {56letbinary="";57for (constbyteofbytes) binary+=String.fromCharCode(byte);58returnbtoa(binary)59 .replaceAll("+", "-")60 .replaceAll("/", "_")61 .replace(/=+$/, "");62}6364/** The bytes `text` stands for, when `text` is exactly how they are written. */65functionbytesOf(text:string):Uint8Array|undefined {66if (!urlSafe.test(text) ||text.length%4===1) returnundefined;67constbinary=atob(text.replaceAll("-", "+").replaceAll("_", "/"));68constbytes=Uint8Array.from(binary, (unit) =>unit.charCodeAt(0));69// Leftover bits in the last character would make two texts for one value.70returntextOf(bytes) ===text?bytes:undefined;71}7273/**74 * Writes `tree` as a snapshot. Only the composition is written: anything75 * else the value carries is left out.76 *77 * Throws a `SnapshotError` when `tree` is not a composition a working copy78 * accepts, or when it needs more than `snapshotLimit` characters.79 */80exportfunctionencodeSnapshot(tree:Composition):string {81constcomposition=restoreWorkingTree(tree);82if (!composition)83thrownewSnapshotError(84"not-a-composition",85"Only a composition can be shared as a link.",86 );87consttooLarge= () =>88newSnapshotError(89"too-large",90"This composition is too large to share as a link. Shorten its wording or remove some of its content, then try again.",91 );92constjson=JSON.stringify({ version: snapshotVersion, composition });93// Every character needs at least one byte.94if (json.length>byteLimit) throwtooLarge();95constbytes=newTextEncoder().encode(json);96if (bytes.length>byteLimit) throwtooLarge();97returntextOf(bytes);98}99100/**101 * Reads a snapshot. The result is a new composition each time, holding only102 * kinds, members and wording.103 *104 * Throws a `SnapshotError` for a text over `snapshotLimit`, a text that is105 * not this encoding, another version, or contents that are not a106 * composition a working copy accepts.107 */108exportfunctiondecodeSnapshot(payload:string):Composition {109constmalformed= () =>110newSnapshotError(111"malformed",112"This link is damaged or incomplete, so its composition cannot be opened. Ask for the link again.",113 );114if (typeofpayload!=="string") throwmalformed();115if (payload.length>snapshotLimit)116thrownewSnapshotError(117"too-large",118"This link is longer than a snapshot can be, so it was not opened.",119 );120constbytes=bytesOf(payload);121if (!bytes) throwmalformed();122letsaved:unknown;123try {124saved=JSON.parse(125newTextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes),126 );127 } catch {128throwmalformed();129 }130if (!saved||typeofsaved!=="object"||Array.isArray(saved))131throwmalformed();132constrecord=savedasRecord<string, unknown>;133if (record.version!==snapshotVersion)134thrownewSnapshotError(135"unsupported-version",136"This link uses a snapshot format this playground cannot read. It may have been made by a newer version.",137 );138constcomposition=restoreWorkingTree(record.composition);139if (!composition)140thrownewSnapshotError(141"not-a-composition",142"This link does not hold a composition this playground can open.",143 );144returncomposition;145}