tests/snapshot.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  example,
5  Stack,
6  Shelf,
7  Switcher,
8  type Composition,
9} from "../documentation/components/source/composition.ts";
10import {
11  decodeSnapshot,
12  encodeSnapshot,
13  SnapshotError,
14  snapshotLimit,
15  type SnapshotProblem,
16} from "../documentation/components/source/snapshot.ts";
17import { workingCopyLimits } from "../documentation/components/source/working-copy.ts";
18
19const text = (value: string): Composition => ({ kind: "Text", text: value });
20const heading = (value: string): Composition => ({
21  kind: "Heading",
22  text: value,
23});
24const meta = (value: string): Composition => ({ kind: "Meta", text: value });
25/** Node's own base64url, so the tests do not lean on the module's. */
26const written = (value: string | Uint8Array) =>
27  Buffer.from(value).toString("base64url");
28const payloadOf = (value: unknown) => written(JSON.stringify(value));
29const jsonIn = (payload: string) =>
30  Buffer.from(payload, "base64url").toString("utf8");
31const snapshot = (composition: unknown, version: unknown = 1) =>
32  payloadOf({ version, composition });
33/** A chain of `levels` Stacks, the innermost empty. */
34const nested = (levels: number): Composition =>
35  levels === 1 ? Stack() : Stack(nested(levels - 1));
36function problem(action: () => unknown): SnapshotProblem | "no error" {
37  try {
38    action();
39  } catch (error) {
40    assert.ok(error instanceof SnapshotError, String(error));
41    assert.ok(error.message.length > 20, "it says what happened");
42    return error.problem;
43  }
44  return "no error";
45}
46
47const notice = Stack(
48  heading("Repair café"),
49  Switcher(text("Saturday"), text("10 am–1 pm"), meta("Updated today")),
50  Shelf(),
51  Stack(text("only member")),
52);
53
54test("a snapshot reads back as the composition it was written from", () => {
55  for (const tree of [
56    notice,
57    Stack(),
58    Switcher(Shelf(Stack())),
59    example("article"),
60    example("investigation"),
61    nested(workingCopyLimits.ancestors + 1),
62    Stack(
63      ...Array.from({ length: workingCopyLimits.nodes - 1 }, (_, index) =>
64        text(`Fact ${index}`),
65      ),
66    ),
67  ]) {
68    const payload = encodeSnapshot(tree);
69    assert.match(payload, /^[A-Za-z0-9_-]+$/, "safe in a link's fragment");
70    assert.ok(payload.length <= snapshotLimit);
71    assert.deepEqual(decodeSnapshot(payload), tree);
72    assert.equal(encodeSnapshot(tree), payload, "the same text every time");
73    assert.equal(encodeSnapshot(decodeSnapshot(payload)), payload);
74  }
75});
76
77test("the format is versioned JSON of the composition, in unpadded base64url", () => {
78  const tree = Stack(heading("Title"), Switcher());
79  assert.equal(
80    encodeSnapshot(tree),
81    written(
82      '{"version":1,"composition":{"kind":"Stack","children":[{"kind":"Heading","text":"Title"},{"kind":"Switcher","children":[]}]}}',
83    ),
84  );
85});
86
87test("a snapshot carries the composition and nothing else", () => {
88  // What an editor holds around a composition does not travel with it.
89  const carrying = {
90    kind: "Stack",
91    width: 480,
92    chosen: ["0.0"],
93    undo: [{ model: Stack() }],
94    children: [{ kind: "Text", text: "a", selected: true, id: "x1" }],
95  } as unknown as Composition;
96  const payload = encodeSnapshot(carrying);
97  assert.equal(
98    jsonIn(payload),
99    '{"version":1,"composition":{"kind":"Stack","children":[{"kind":"Text","text":"a"}]}}',
100  );
101  assert.equal(payload, encodeSnapshot(Stack(text("a"))));
102});
103
104test("wording survives exactly, in any script", () => {
105  const wordings = [
106    "",
107    " leading and trailing ",
108    "Café — naïve façade",
109    "修理カフェは土曜日です",
110    "مقهى الإصلاح يوم السبت",
111    "🛠️ Repair café 👩🏽‍🔧",
112    "e\u0301 and \u00e9 stay different",
113    "tab\tnewline\ncarriage\rreturn",
114    "nul \u0000 and bell \u0007",
115    "a lone surrogate \ud83d stays as typed",
116    "\ufeffstarts with a byte order mark",
117    "\u2028 and \u2029 line separators",
118  ];
119  const tree = Stack(...wordings.map(text));
120  const payload = encodeSnapshot(tree);
121  assert.match(payload, /^[A-Za-z0-9_-]+$/);
122  assert.deepEqual(decodeSnapshot(payload), tree);
123});
124
125test("wording that looks like markup or code stays literal wording", () => {
126  const wordings = [
127    '<script>alert("x")</script>',
128    '"><img src=x onerror=alert(1)>',
129    "</code></pre><h1>not a heading</h1>",
130    'Stack(Text("nested source"))',
131    "${globalThis.location} `backticks`",
132    '{"kind":"Stack","children":[]}',
133    "__proto__",
134    "javascript:alert(1)",
135    "#snapshot=AAAA&edit=BBBB",
136    "%3Cscript%3E + spaces & ampersands = signs",
137    '\\u0000 \\n \\" backslashes',
138  ];
139  const tree = Stack(Switcher(...wordings.map(text)), heading(wordings[0]!));
140  const read = decodeSnapshot(encodeSnapshot(tree));
141  assert.deepEqual(read, tree);
142  // Still six kinds of node and nothing more: none of it became structure.
143  assert.deepEqual(
144    "children" in read && read.children.map((member) => member.kind),
145    ["Switcher", "Heading"],
146  );
147});
148
149test("reading builds a new composition from known fields only", () => {
150  const hostile = JSON.parse(
151    `{
152      "version": 1,
153      "composition": {
154        "kind": "Stack",
155        "__proto__": { "polluted": true },
156        "constructor": { "prototype": { "polluted": true } },
157        "children": [
158          { "kind": "Text", "text": "a", "children": [], "onclick": "x()" },
159          { "kind": "Shelf", "children": [], "text": "ignored", "width": 900 }
160        ],
161        "chosen": ["0.0"],
162        "width": 480
163      },
164      "undo": [{ "model": { "kind": "Stack", "children": [] } }],
165      "width": 480,
166      "then": "not a promise"
167    }`,
168  ) as unknown;
169  const read = decodeSnapshot(payloadOf(hostile));
170  assert.deepEqual(read, Stack(text("a"), Shelf()));
171  assert.equal(
172    JSON.stringify(read),
173    '{"kind":"Stack","children":[{"kind":"Text","text":"a"},{"kind":"Shelf","children":[]}]}',
174  );
175  assert.equal(Object.getPrototypeOf(read), Object.prototype);
176  assert.equal(({} as { polluted?: boolean }).polluted, undefined);
177
178  const payload = encodeSnapshot(notice);
179  assert.notEqual(decodeSnapshot(payload), decodeSnapshot(payload));
180  assert.deepEqual(decodeSnapshot(payload), decodeSnapshot(payload));
181});
182
183test("a text that is not a snapshot is refused with its reason", () => {
184  const good = encodeSnapshot(Stack(text("a")));
185  const stack = { kind: "Stack", children: [] };
186  for (const [payload, expected] of [
187    ["", "malformed"],
188    [`${good}=`, "malformed"],
189    [`${good} `, "malformed"],
190    [` ${good}`, "malformed"],
191    [good.replace("e", "+"), "malformed"],
192    [good.replace("e", "/"), "malformed"],
193    [encodeURIComponent(`${good}==`), "malformed"],
194    [`${good}&width=480`, "malformed"],
195    [good.slice(0, -1), "malformed"],
196    [good.slice(0, good.length >> 1), "malformed"],
197    ["A", "malformed"],
198    ["AB", "malformed"],
199    [written("not json"), "malformed"],
200    [written('{"version":1,"composition":'), "malformed"],
201    [written(Uint8Array.of(0x7b, 0xff, 0xfe, 0x7d)), "malformed"],
202    [
203      written(`\ufeff${JSON.stringify({ version: 1, composition: stack })}`),
204      "malformed",
205    ],
206    [payloadOf(null), "malformed"],
207    [payloadOf("a string"), "malformed"],
208    [payloadOf(7), "malformed"],
209    [payloadOf([{ version: 1, composition: stack }]), "malformed"],
210    [snapshot(stack, 2), "unsupported-version"],
211    [snapshot(stack, 0), "unsupported-version"],
212    [snapshot(stack, "1"), "unsupported-version"],
213    [payloadOf({ composition: stack }), "unsupported-version"],
214    [payloadOf(stack), "unsupported-version"],
215    [payloadOf({ version: 1 }), "not-a-composition"],
216    [snapshot(null), "not-a-composition"],
217    [snapshot(text("a")), "not-a-composition"],
218    [snapshot({ kind: "Grid", children: [] }), "not-a-composition"],
219    [snapshot({ kind: "Stack" }), "not-a-composition"],
220    [
221      snapshot({ kind: "Stack", children: [{ kind: "Image", text: "a" }] }),
222      "not-a-composition",
223    ],
224    [
225      snapshot({ kind: "Stack", children: [{ kind: "Text", text: 7 }] }),
226      "not-a-composition",
227    ],
228    [snapshot(nested(workingCopyLimits.ancestors + 2)), "not-a-composition"],
229    [
230      snapshot(
231        Stack(
232          ...Array.from({ length: workingCopyLimits.nodes }, () => text("a")),
233        ),
234      ),
235      "not-a-composition",
236    ],
237    ["A".repeat(snapshotLimit + 1), "too-large"],
238    [`${good}${"A".repeat(snapshotLimit)}`, "too-large"],
239  ] as const)
240    assert.equal(
241      problem(() => decodeSnapshot(payload)),
242      expected,
243      payload.slice(0, 40),
244    );
245  assert.equal(
246    problem(() => decodeSnapshot(undefined as unknown as string)),
247    "malformed",
248  );
249  // A text with leftover bits in its last character is not how any value is written.
250  assert.equal(jsonIn("e30"), "{}");
251  assert.equal(jsonIn("e31"), "{}");
252  assert.equal(
253    problem(() => decodeSnapshot("e31")),
254    "malformed",
255  );
256  assert.equal(
257    problem(() => decodeSnapshot("e30")),
258    "unsupported-version",
259  );
260});
261
262test("a composition is written whole or not at all", () => {
263  const bytes = Math.floor((snapshotLimit * 3) / 4);
264  const fixed = jsonIn(encodeSnapshot(Stack(text("")))).length;
265
266  const fits = Stack(text("a".repeat(bytes - fixed)));
267  const payload = encodeSnapshot(fits);
268  assert.equal(payload.length, snapshotLimit, "exactly at the limit");
269  assert.deepEqual(decodeSnapshot(payload), fits);
270  assert.equal(
271    problem(() => encodeSnapshot(Stack(text("a".repeat(bytes - fixed + 1))))),
272    "too-large",
273  );
274
275  // The limit is on the link, so wording outside ASCII uses it up faster.
276  const accented = Math.floor((bytes - fixed) / 2);
277  assert.deepEqual(
278    decodeSnapshot(encodeSnapshot(Stack(text("é".repeat(accented))))),
279    Stack(text("é".repeat(accented))),
280  );
281  assert.equal(
282    problem(() => encodeSnapshot(Stack(text("é".repeat(accented + 1))))),
283    "too-large",
284  );
285  assert.equal(
286    problem(() => encodeSnapshot(Stack(text("a".repeat(1_000_000))))),
287    "too-large",
288  );
289
290  for (const tree of [
291    text("a"),
292    nested(workingCopyLimits.ancestors + 2),
293    Stack(...Array.from({ length: workingCopyLimits.nodes }, () => text("a"))),
294    { kind: "Grid", children: [] } as unknown as Composition,
295    undefined as unknown as Composition,
296  ])
297    assert.equal(
298      problem(() => encodeSnapshot(tree)),
299      "not-a-composition",
300    );
301});