documentation/components/source/snapshot.ts

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 their
5 * arrangements, and content with its roles and wording, in order. It has no
6 * width, no selection and no history, so wherever it is opened the
7 * composition responds to the space it finds there. A snapshot never
8 * 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 with
11 * no padding. Reading one is parsing and checking. Nothing in it is
12 * 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 a
16 * working copy's Undo history.
17 */
18import type { Composition } from "./composition.ts";
19import { restoreWorkingTree } from "./working-copy.ts";
20
21/** The format written by `encodeSnapshot`, and the only one read. */
22export const snapshotVersion = 1;
23
24/**
25 * The most characters a snapshot may have. A composition that needs more is
26 * refused, never cut short, and a longer text is not read at all.
27 */
28export const snapshotLimit = 16_384;
29/** Four characters carry three bytes. */
30const byteLimit = Math.floor((snapshotLimit * 3) / 4);
31
32/** Why a composition has no snapshot, or a text is not one. */
33export type SnapshotProblem =
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";
42
43/** Thrown by `encodeSnapshot` and `decodeSnapshot`. Its message is for an author. */
44export class SnapshotError extends Error {
45  readonly problem: SnapshotProblem;
46  constructor(problem: SnapshotProblem, message: string) {
47    super(message);
48    this.name = "SnapshotError";
49    this.problem = problem;
50  }
51}
52
53const urlSafe = /^[A-Za-z0-9_-]+$/;
54
55function textOf(bytes: Uint8Array): string {
56  let binary = "";
57  for (const byte of bytes) binary += String.fromCharCode(byte);
58  return btoa(binary)
59    .replaceAll("+", "-")
60    .replaceAll("/", "_")
61    .replace(/=+$/, "");
62}
63
64/** The bytes `text` stands for, when `text` is exactly how they are written. */
65function bytesOf(text: string): Uint8Array | undefined {
66  if (!urlSafe.test(text) || text.length % 4 === 1) return undefined;
67  const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
68  const bytes = Uint8Array.from(binary, (unit) => unit.charCodeAt(0));
69  // Leftover bits in the last character would make two texts for one value.
70  return textOf(bytes) === text ? bytes : undefined;
71}
72
73/**
74 * Writes `tree` as a snapshot. Only the composition is written: anything
75 * else the value carries is left out.
76 *
77 * Throws a `SnapshotError` when `tree` is not a composition a working copy
78 * accepts, or when it needs more than `snapshotLimit` characters.
79 */
80export function encodeSnapshot(tree: Composition): string {
81  const composition = restoreWorkingTree(tree);
82  if (!composition)
83    throw new SnapshotError(
84      "not-a-composition",
85      "Only a composition can be shared as a link.",
86    );
87  const tooLarge = () =>
88    new SnapshotError(
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    );
92  const json = JSON.stringify({ version: snapshotVersion, composition });
93  // Every character needs at least one byte.
94  if (json.length > byteLimit) throw tooLarge();
95  const bytes = new TextEncoder().encode(json);
96  if (bytes.length > byteLimit) throw tooLarge();
97  return textOf(bytes);
98}
99
100/**
101 * Reads a snapshot. The result is a new composition each time, holding only
102 * kinds, members and wording.
103 *
104 * Throws a `SnapshotError` for a text over `snapshotLimit`, a text that is
105 * not this encoding, another version, or contents that are not a
106 * composition a working copy accepts.
107 */
108export function decodeSnapshot(payload: string): Composition {
109  const malformed = () =>
110    new SnapshotError(
111      "malformed",
112      "This link is damaged or incomplete, so its composition cannot be opened. Ask for the link again.",
113    );
114  if (typeof payload !== "string") throw malformed();
115  if (payload.length > snapshotLimit)
116    throw new SnapshotError(
117      "too-large",
118      "This link is longer than a snapshot can be, so it was not opened.",
119    );
120  const bytes = bytesOf(payload);
121  if (!bytes) throw malformed();
122  let saved: unknown;
123  try {
124    saved = JSON.parse(
125      new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes),
126    );
127  } catch {
128    throw malformed();
129  }
130  if (!saved || typeof saved !== "object" || Array.isArray(saved))
131    throw malformed();
132  const record = saved as Record<string, unknown>;
133  if (record.version !== snapshotVersion)
134    throw new SnapshotError(
135      "unsupported-version",
136      "This link uses a snapshot format this playground cannot read. It may have been made by a newer version.",
137    );
138  const composition = restoreWorkingTree(record.composition);
139  if (!composition)
140    throw new SnapshotError(
141      "not-a-composition",
142      "This link does not hold a composition this playground can open.",
143    );
144  return composition;
145}