SPB Git

Repository Public

next-p-offline.test.ts 10.8 KB 125 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-p-offline.test.ts9 * Description      : pure rules of the web offline-first layer — mutation10 *                    journal (request mapping with client ids, coalescing,11 *                    de-duplication, error classification, labels), offline12 *                    image bounds, and the canonical JSON behind the integrity13 *                    hash.14 * Module           : tests15 * Repository       : https://git.spboucher.ai/note-spboucher-ai16 * Project Website  : https://note.spboucher.ai17 * Created          : 2026-11-1918 * Last Modified    : 2026-11-1919 *20 * Author           : Simon-Pierre Boucher21 * Position         : Professor of Finance22 * Institution      : Université du Québec en Outaouais (UQO)23 * Organization     : SP Boucher24 * Website          : https://spboucher.ai25 * Git              : https://git.spboucher.ai26 *27 * Preferred Contact: contact@spboucher.ai28 * Development      : dev@spboucher.ai29 * Support          : support@spboucher.ai30 * Security/Admin   : admin@spboucher.ai31 *32 * Copyright (c) 202633 * Simon-Pierre Boucher34 * All rights reserved where applicable. This file is governed by the35 * applicable project license, copyright notices and relevant law.36 * Existing third-party rights and notices remain unaffected.37 *38 * License          : None specified (no license file in this repository)39 *40 * Do not embed credentials, private keys, access tokens,41 * certificates or confidential personal information.42 *43 * =============================================================================44 * END OF SP BOUCHER SOURCE HEADER45 * =============================================================================46 */4748import { test } from "node:test";49import assert from "node:assert/strict";50import { createHash } from "node:crypto";51import { canQueueImage, classify, describe, mergeIntoQueue, requestOf, IMAGE_MAX, BLOBS_MAX, type JournalEntry } from "../../src/lib/client/journal-core";52import { stableJson, INTEGRITY_ALGORITHM } from "../../src/lib/stable-json";5354let n = 0;55const E = (kind: JournalEntry["kind"], entityId: string, body: Record<string, unknown> = {}, extra: Partial<JournalEntry> = {}): JournalEntry => ({ seq: ++n, id: `k${n}`, kind, entityId, body, createdAt: n, attempts: 0, state: "pending", ...extra });56const P = "11111111-1111-4111-8111-111111111111", Q = "22222222-2222-4222-8222-222222222222";5758test("journal: every entry maps to one request, creates carry the client id", () => {59  assert.deepEqual(requestOf(E("page.create", P, { title: "A", section: "notes" })), { method: "POST", url: "/api/pages", json: { title: "A", section: "notes", id: P } });60  assert.deepEqual(requestOf(E("page.update", P, { pinned: true })), { method: "PATCH", url: `/api/pages/${P}`, json: { pinned: true } });61  assert.deepEqual(requestOf(E("page.trash", P)), { method: "DELETE", url: `/api/pages/${P}` });62  assert.deepEqual(requestOf(E("page.restore", P)), { method: "POST", url: `/api/pages/${P}?action=restore` });63  assert.deepEqual(requestOf(E("page.tags", P, { tags: ["a", "b"] })), { method: "PUT", url: `/api/pages/${P}/tags`, json: { tags: ["a", "b"] } });64  assert.deepEqual(requestOf(E("task.create", Q, { title: "T", pageId: P })), { method: "POST", url: "/api/tasks", json: { title: "T", pageId: P, id: Q } });65  assert.deepEqual(requestOf(E("task.update", Q, { status: "done" })), { method: "PATCH", url: `/api/tasks/${Q}`, json: { status: "done" } });66  assert.deepEqual(requestOf(E("task.delete", Q)), { method: "DELETE", url: `/api/tasks/${Q}` });67  assert.equal(requestOf(E("upload", Q)).upload, true);68  // a body can never smuggle another id into a create69  assert.equal((requestOf(E("page.create", P, { id: Q })).json as any).id, P);70});71test("journal: a create already queued is not queued twice (de-duplication)", () => {72  const q = [E("page.create", P, { title: "A" })];73  assert.deepEqual(mergeIntoQueue(q, E("page.create", P, { title: "A" })), { skip: true });74  assert.deepEqual(mergeIntoQueue([E("task.create", Q, { title: "T" }, { state: "failed" })], E("task.create", Q, { title: "T" })), { skip: true }, "even when the first attempt was refused");75  assert.ok("put" in mergeIntoQueue(q, E("page.create", Q, { title: "B" })));76});77test("journal: consecutive updates of one entity are one entry; the order of effects is never changed", () => {78  const u1 = E("page.update", P, { pinned: true, title: "A" }); const m = mergeIntoQueue([u1], E("page.update", P, { title: "B", archived: true }));79  assert.ok("put" in m); assert.equal(m.put.seq, u1.seq); assert.equal(m.put.id, u1.id, "same idempotency key"); assert.deepEqual(m.put.body, { pinned: true, title: "B", archived: true });80  // an update separated from the previous one by a trash is NOT merged backwards81  const q = [E("page.update", P, { pinned: true }), E("page.trash", P)]; const next = E("page.update", P, { pinned: false }); const r = mergeIntoQueue(q, next); assert.ok("put" in r); assert.equal(r.put, next);82  // another entity in between does not prevent the merge (per-entity order is what matters)83  const a = E("page.update", P, { pinned: true }); const r2 = mergeIntoQueue([a, E("page.update", Q, { pinned: true })], E("page.update", P, { pinned: false })); assert.ok("put" in r2); assert.equal(r2.put.seq, a.seq); assert.deepEqual(r2.put.body, { pinned: false });84  const t = mergeIntoQueue([E("page.tags", P, { tags: ["a"] })], E("page.tags", P, { tags: ["a", "b"] })); assert.ok("put" in t); assert.deepEqual(t.put.body, { tags: ["a", "b"] });85  const tk = mergeIntoQueue([E("task.update", Q, { title: "x" })], E("task.update", Q, { status: "done" })); assert.ok("put" in tk); assert.deepEqual(tk.put.body, { title: "x", status: "done" });86});87test("journal: an update folds into a create that was never sent, only with keys the create route accepts", () => {88  const c = E("page.create", P, { title: "" }); const m = mergeIntoQueue([c], E("page.update", P, { title: "Named", section: "projects" }));89  assert.ok("put" in m); assert.equal(m.put.kind, "page.create"); assert.deepEqual(m.put.body, { title: "Named", section: "projects" });90  const pin = E("page.update", P, { pinned: true }); const m2 = mergeIntoQueue([c], pin); assert.ok("put" in m2); assert.equal(m2.put, pin, "pinned is not a create field: appended");91  const sent = E("page.create", P, { title: "" }, { attempts: 1 }); const up = E("page.update", P, { title: "Late" }); const m3 = mergeIntoQueue([sent], up); assert.ok("put" in m3); assert.equal(m3.put, up, "a create already attempted may have reached the server: never rewritten");92  const tc = E("task.create", Q, { title: "T" }); const m4 = mergeIntoQueue([tc], E("task.update", Q, { status: "done" })); assert.ok("put" in m4); assert.equal(m4.put.kind, "task.create"); assert.deepEqual(m4.put.body, { title: "T", status: "done" });93  // a failed entry never absorbs anything94  const failed = E("page.update", P, { title: "bad" }, { state: "failed" }); const nx = E("page.update", P, { pinned: true }); const m5 = mergeIntoQueue([failed], nx); assert.ok("put" in m5); assert.equal(m5.put, nx);95});96test("journal: classification — transient errors stop the replay, refusals are parked, a deletion of something gone is done", () => {97  for (const s of [0, 500, 502, 503, 401, 408, 425, 429]) assert.equal(classify("page.update", s), "retry", String(s));98  for (const s of [200, 201, 204]) assert.equal(classify("page.create", s), "done");99  for (const s of [400, 403, 404, 409, 413, 422]) assert.equal(classify("page.update", s), "failed", String(s));100  assert.equal(classify("page.trash", 404), "done"); assert.equal(classify("task.delete", 404), "done"); assert.equal(classify("task.update", 404), "failed"); assert.equal(classify("page.create", 409), "failed");101});102test("journal: labels shown in the inspector", () => {103  assert.equal(describe(E("page.create", P, { title: "Plan" })), "New note “Plan”"); assert.equal(describe(E("page.create", P, { title: "" })), "New note");104  assert.equal(describe(E("page.update", P, { pinned: true })), "Pin"); assert.equal(describe(E("page.update", P, { archived: true })), "Archive"); assert.equal(describe(E("page.update", P, { parentId: Q, position: 3 })), "Move");105  assert.equal(describe(E("page.update", P, { title: "New name" })), "Rename “New name”");106  assert.equal(describe(E("task.update", Q, { status: "done" })), "Complete task"); assert.equal(describe(E("task.create", Q, { title: "Call" })), "New task “Call”");107  assert.equal(describe(E("page.tags", P, { tags: ["a", "b"] })), "Tags: #a #b"); assert.equal(describe(E("upload", Q, { name: "x.png" })), "Image upload x.png"); assert.equal(describe(E("page.trash", P)), "Move to trash");108});109test("offline images: only images, 10 MB each, 100 MB queued in total", () => {110  assert.equal(IMAGE_MAX, 10 * 1024 * 1024); assert.equal(BLOBS_MAX, 100 * 1024 * 1024);111  assert.deepEqual(canQueueImage({ type: "image/png", size: 5_000 }, 0), { ok: true });112  assert.deepEqual(canQueueImage({ type: "image/jpeg", size: IMAGE_MAX }, 0), { ok: true });113  const big = canQueueImage({ type: "image/png", size: IMAGE_MAX + 1 }, 0); assert.equal(big.ok, false); assert.match((big as any).reason, /limit 10 MB/);114  const pdf = canQueueImage({ type: "application/pdf", size: 10 }, 0); assert.equal(pdf.ok, false); assert.match((pdf as any).reason, /Only images/);115  const full = canQueueImage({ type: "image/png", size: 2 }, BLOBS_MAX - 1); assert.equal(full.ok, false); assert.match((full as any).reason, /queue is full/);116});117test("integrity: canonical JSON ignores key order and undefined, keeps array order; the hash is stable across a jsonb round trip", () => {118  assert.equal(INTEGRITY_ALGORITHM, "sha256-stable-json-1");119  const a = { type: "doc", content: [{ type: "paragraph", attrs: { id: "x", textAlign: null }, content: [{ type: "text", text: "é\"\n", marks: [{ type: "bold" }] }] }] };120  const b = { content: [{ content: [{ marks: [{ type: "bold" }], text: "é\"\n", type: "text" }], attrs: { textAlign: null, id: "x", gone: undefined }, type: "paragraph" }], type: "doc" };121  assert.equal(stableJson(a), stableJson(b)); assert.equal(stableJson(a), '{"content":[{"attrs":{"id":"x","textAlign":null},"content":[{"marks":[{"type":"bold"}],"text":"é\\"\\n","type":"text"}],"type":"paragraph"}],"type":"doc"}');122  assert.notEqual(stableJson({ a: [1, 2] }), stableJson({ a: [2, 1] })); assert.equal(stableJson(null), "null"); assert.equal(stableJson([undefined, 1]), "[null,1]"); assert.equal(stableJson({ n: 1.5, t: true, s: "" }), '{"n":1.5,"s":"","t":true}');123  const h = (v: unknown) => createHash("sha256").update(stableJson(v)).digest("hex"); assert.equal(h(a), h(b)); assert.equal(h(a).length, 64);124});125
Files main
Menu

Theme