Versions 155 to 318
new file, 66 lines
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { test } from "node:test"; 4+import { equalJsonValues, jsonValueChunks } from "../json-value-chunks.ts"; 6+test("canonical JSON chunks preserve scalar, container and toJSON encoding", () => { 16+ { z: undefined, a: [undefined, null, 'quoted"\n\t\\', "\ud800", "\udc00", "\u2028\u2029"] }, 18+ { 20: "twenty", 2: "two", before: 1, after: 2 }, 21+ toJSON(key: string) { 22+ return { key, value: "converted" }; 26+ JSON.parse('{"__proto__":"data","constructor":"also data"}'), 28+ for (const value of values) assert.equal([...jsonValueChunks(value)].join(""), JSON.stringify(value)); 29+ for (const left of values) 30+ for (const right of values) 31+ assert.equal(equalJsonValues(left, right), JSON.stringify(left) === JSON.stringify(right)); 34+test("canonical JSON string chunks preserve every surrogate split and bound escaped output", () => { 35+ for (const offset of [16382, 16383, 16384, 16385]) { 36+ const value = { text: `${"a".repeat(offset)}\ud83d\ude80${"\u0000".repeat(40000)}\ud800` }; 37+ const hash = createHash("sha256"); 38+ for (const chunk of jsonValueChunks(value)) { 39+ assert.ok(chunk.length <= 16384 * 6); 42+ assert.equal(hash.digest("hex"), createHash("sha256").update(JSON.stringify(value)).digest("hex")); 46+test("canonical JSON visits large arrays incrementally and rejects cycles", () => { 48+ const values = new Proxy(new Array(10000), { 49+ get(target, key, receiver) { 50+ if (typeof key === "string" && /^[0-9]+$/.test(key)) { 54+ return Reflect.get(target, key, receiver); 57+ const chunks = jsonValueChunks(values); 58+ assert.equal(chunks.next().value, "["); 59+ assert.equal(reads, 0); 60+ assert.equal(chunks.next().value, "0"); 61+ assert.equal(reads, 1); 63+ const cyclic: unknown[] = []; 65+ assert.throws(() => [...jsonValueChunks(cyclic)], /cyclic/);