SPB Git

Repository Public

pages.test.ts 11.9 KB 136 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/pages.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Data integrity of pages: optimistic concurrency, conflict resolution (both copies survive), history, inbox triage + undo, tags.45 * Runs against a *_dev database; everything it creates is purged at the end.46 */47import "../helpers/testdb";48import { test, before, after } from "node:test";49import assert from "node:assert/strict";50import { and, eq, inArray } from "drizzle-orm";51import { db, schema, sql } from "../../src/db/index";52import { createPage, getPage, updatePage, resolveConflict, softDeletePage, restorePage } from "../../src/lib/pages/service";53import { capture, listInbox, triage, undoTriage, setPageTags, pageTags } from "../../src/lib/inbox/service";54import { assertDoc } from "../../src/lib/editor/validate";5556let ws: string; const made: string[] = [];57const doc = (t: string) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: t }] }] });58const mk = async (title: string, text = "v1") => { const p = await createPage(ws, { title, content: doc(text) }); made.push(p.id); return p; };59const status = async (p: Promise<unknown>) => { try { await p; return 200; } catch (e: any) { return e.status ?? 500; } };60before(async () => { const [w] = await db.select().from(schema.workspaces).limit(1); assert.ok(w, "workspace missing"); ws = w.id; });61after(async () => {62  const kids = made.length ? await db.select({ id: schema.pages.id }).from(schema.pages).where(inArray(schema.pages.id, made)) : [];63  if (kids.length) { await db.delete(schema.tasks).where(inArray(schema.tasks.pageId, kids.map((k) => k.id))); await db.delete(schema.pages).where(inArray(schema.pages.id, kids.map((k) => k.id))); }64  await db.delete(schema.tags).where(and(eq(schema.tags.workspaceId, ws), inArray(schema.tags.name, ["unit-a", "unit-b"])));65  await sql.end();66});6768test("a save with the current base version passes and bumps the version", async () => {69  const p = await mk("unit · versions"); const a = await updatePage(ws, p.id, { content: doc("v2") }, { baseVersion: p.version });70  assert.equal(a.version, p.version + 1); assert.equal(a.plainText, "v2");71  const b = await updatePage(ws, p.id, { title: "unit · versions (renamed)" }, { baseVersion: a.version }); assert.equal(b.version, a.version + 1);72  const c = await updatePage(ws, p.id, { pinned: true }, { baseVersion: 0 }); assert.equal(c.version, b.version, "metadata does not bump or check the version");73});74test("a stale save is refused with the server copy and writes nothing", async () => {75  const p = await mk("unit · stale"); await updatePage(ws, p.id, { content: doc("from session A") }, { baseVersion: p.version });76  let err: any; try { await updatePage(ws, p.id, { content: doc("from session B") }, { baseVersion: p.version }); } catch (e) { err = e; }77  assert.equal(err?.status, 409); assert.equal(err?.code, "conflict"); assert.equal(err.extra.server.version, p.version + 1); assert.equal(err.extra.server.content.content[0].content[0].text, "from session A"); assert.ok(err.extra.server.content.content[0].attrs.id, "blocks get a stable id on the server");78  assert.equal((await getPage(ws, p.id)).plainText, "from session A");79});80test("two simultaneous saves on the same base: exactly one wins", async () => {81  const p = await mk("unit · race");82  const r = await Promise.all([status(updatePage(ws, p.id, { content: doc("A") }, { baseVersion: p.version })), status(updatePage(ws, p.id, { content: doc("B") }, { baseVersion: p.version }))]);83  assert.deepEqual([...r].sort(), [200, 409]); assert.equal((await getPage(ws, p.id)).version, p.version + 1);84});85for (const choice of ["mine", "theirs", "both"] as const) test(`conflict resolution "${choice}" keeps both copies`, async () => {86  const p = await mk(`unit · resolve ${choice}`, "base"); const srv = await updatePage(ws, p.id, { content: doc("server text") }, { baseVersion: p.version });87  const r = await resolveConflict(ws, p.id, { choice, serverVersion: srv.version, mine: { title: p.title, content: doc("my text") as any } }); if (r.copyId) made.push(r.copyId);88  const now = await getPage(ws, p.id); const hist = await db.select().from(schema.pageVersions).where(eq(schema.pageVersions.pageId, p.id)); const texts = hist.map((h) => JSON.stringify(h.content));89  if (choice === "mine") { assert.equal(now.plainText, "my text"); assert.ok(texts.some((t) => t.includes("server text")), "server copy is in the history"); }90  if (choice === "theirs") { assert.equal(now.plainText, "server text"); const kept = hist.find((h) => JSON.stringify(h.content).includes("my text")); assert.ok(kept, "my copy is in the history"); assert.ok(kept!.version < 0, "unapplied copies use negative version numbers"); assert.equal(now.version, srv.version, "page untouched"); }91  if (choice === "both") { assert.equal(now.plainText, "server text"); assert.ok(r.copyId); const copy = await getPage(ws, r.copyId!); assert.equal(copy.plainText, "my text"); assert.match(copy.title, /conflict copy/); }92  // a second resolution on an outdated server version is refused, not guessed93  assert.equal(await status(resolveConflict(ws, p.id, { choice: "mine", serverVersion: srv.version - 1, mine: { content: doc("x") as any } })), 409);94});95test("history: a snapshot is taken on first change and prunable copies never exceed 200", async () => {96  const p = await mk("unit · history"); let v = p.version;97  for (let i = 0; i < 3; i++) v = (await updatePage(ws, p.id, { content: doc(`edit ${i}`) }, { baseVersion: v })).version;98  const hist = await db.select().from(schema.pageVersions).where(eq(schema.pageVersions.pageId, p.id)); assert.ok(hist.length >= 1 && hist.length <= 200); assert.equal(hist[0].version, p.version);99});100test("trash and restore keep the page and its descendants", async () => {101  const parent = await mk("unit · parent"); const child = await createPage(ws, { title: "unit · child", parentId: parent.id, content: doc("c") }); made.push(child.id);102  assert.equal(await softDeletePage(ws, parent.id), 2); assert.equal(await status(getPage(ws, child.id)), 404);103  await restorePage(ws, parent.id); assert.equal((await getPage(ws, child.id)).plainText, "c");104});105test("documents are validated before storage", () => {106  assert.throws(() => assertDoc({ type: "paragraph" }), /Invalid document/); assert.throws(() => assertDoc(null)); assert.throws(() => assertDoc({ type: "doc", content: [{ type: 5 }] }));107  assert.throws(() => assertDoc({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "x", marks: [{ type: "link", attrs: { href: "javascript:alert(1)" } }] }] }] }), /Unsafe URL/);108  assert.throws(() => assertDoc({ type: "doc", content: [{ type: "image", attrs: { src: " JavaScript:void(0)" } }] }), /Unsafe URL/);109  let deep: any = { type: "paragraph" }; for (let i = 0; i < 80; i++) deep = { type: "blockquote", content: [deep] }; assert.throws(() => assertDoc({ type: "doc", content: [deep] }), /nested too deeply/);110  assert.doesNotThrow(() => assertDoc(doc("ok")));111});112test("capture lands in the inbox; kinds build the right content", async () => {113  const n = await capture(ws, { kind: "note", text: "unit capture title\nsecond line" }); made.push(n.id); assert.ok(n.inboxAt); assert.equal(n.title, "unit capture title"); assert.equal(n.captureKind, "note");114  const t = await capture(ws, { kind: "tasks", text: "buy milk\ncall Bob" }); made.push(t.id); assert.equal((t.content as any).content[0].type, "taskList"); assert.equal((t.content as any).content[0].content.length, 2);115  const l = await capture(ws, { kind: "link", text: "https://example.org/a?b=1\nworth reading" }); made.push(l.id); assert.equal(l.title, "example.org"); assert.equal((l.content as any).content[0].content[0].marks[0].attrs.href, "https://example.org/a?b=1");116  assert.equal(await status(capture(ws, { kind: "link", text: "javascript:alert(1)" })), 400); assert.equal(await status(capture(ws, { kind: "note", text: "   " })), 400);117  const inbox = await listInbox(ws); const mine = inbox.filter((i) => [n.id, t.id, l.id].includes(i.id)); assert.equal(mine.length, 3); assert.equal(mine.find((i) => i.id === t.id)!.openTasks, 2); assert.equal(mine.find((i) => i.id === l.id)!.url, "https://example.org/a?b=1");118});119test("every triage action can be undone", async () => {120  const state = async (id: string) => { const [p] = await db.select().from(schema.pages).where(eq(schema.pages.id, id)); return { inbox: Boolean(p.inboxAt), archived: p.archived, section: p.section, deleted: Boolean(p.deletedAt) }; };121  const k = await capture(ws, { kind: "note", text: "unit triage keep" }); made.push(k.id);122  const a1 = await triage(ws, k.id, { action: "keep", section: "projects" }); assert.deepEqual(await state(k.id), { inbox: false, archived: false, section: "projects", deleted: false });123  assert.equal(await status(triage(ws, k.id, { action: "archive" })), 409, "an item already filed cannot be triaged twice");124  await undoTriage(ws, a1.actionId); assert.deepEqual(await state(k.id), { inbox: true, archived: false, section: "notes", deleted: false });125  assert.equal((await undoTriage(ws, a1.actionId)).already, true, "undo is idempotent");126  const t = await capture(ws, { kind: "tasks", text: "unit task one\nunit task two" }); made.push(t.id);127  const a2 = await triage(ws, t.id, { action: "task", priority: "high" }); let tasks = await db.select().from(schema.tasks).where(eq(schema.tasks.pageId, t.id)); assert.equal(tasks.filter((x) => !x.deletedAt).length, 2); assert.equal(tasks[0].priority, "high");128  await undoTriage(ws, a2.actionId); tasks = await db.select().from(schema.tasks).where(eq(schema.tasks.pageId, t.id)); assert.equal(tasks.filter((x) => !x.deletedAt).length, 0); assert.equal((await state(t.id)).inbox, true);129  const a3 = await triage(ws, t.id, { action: "archive" }); assert.equal((await state(t.id)).archived, true); await undoTriage(ws, a3.actionId); assert.equal((await state(t.id)).archived, false);130  const a4 = await triage(ws, t.id, { action: "trash" }); assert.equal((await state(t.id)).deleted, true); await undoTriage(ws, a4.actionId); assert.deepEqual(await state(t.id), { inbox: true, archived: false, section: "notes", deleted: false });131});132test("tags are normalised, replaced as a set, and listed", async () => {133  const p = await mk("unit · tags"); assert.deepEqual(await setPageTags(ws, p.id, ["#Unit-A", "unit-b ", "unit-a", ""]), ["unit-a", "unit-b"]);134  assert.deepEqual(await setPageTags(ws, p.id, ["unit-b"]), ["unit-b"]); assert.deepEqual(await pageTags(p.id), ["unit-b"]);135});136
Files main
Menu

Theme