SPB Git

Repository Public

next-p-ra-live.test.ts 12.8 KB 142 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-p-ra-live.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *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 * Living blocks, client side (SPEC §4.7): the reader of `POST /api/query` is pinned against REAL answers of the server function45 * (`runQuery`, JSON round-tripped exactly as the route sends it) for the five sources, plus the strictness of the reader, the request46 * bodies, the device snapshot store and the "last refreshed" label. Runs against a *_dev database.47 */48import { test, before, after } from "node:test";49import assert from "node:assert/strict";50import { workspace, mk, doc, made, cleanup } from "../helpers/next";51import { runQuery } from "../../src/lib/knowledge/query";52import { createTask } from "../../src/lib/tasks/service";53import { createReference } from "../../src/lib/research/references";54import { ensureDatabase, createProperty, createRow } from "../../src/lib/databases/service";55import { normaliseQueryResult, QueryShapeError, queryBody, chartQueryBody, tableColumns, groupByStatus, sameTable, refreshedLabel, queryKeyOf, saveQuerySnapshot, loadQuerySnapshot, cellDisplay } from "../../src/lib/editor/query";56import { chartModel, defaultChartConfig } from "../../src/lib/editor/chart";5758let ws: string; const PFX = "nx-pra-live ·";59before(async () => { ws = await workspace(); }); after(async () => { await cleanup(ws, PFX); });60const wire = <T>(v: T): unknown => JSON.parse(JSON.stringify(v));61const memory = () => { const m = new Map<string, string>(); return { m, getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => { m.set(k, v); }, removeItem: (k: string) => { m.delete(k); } }; };6263test("contract: the reader accepts the real answer of every source and derives the display model from it", async () => {64  const p = await mk(ws, `${PFX} page`, doc("corps de la page"), { section: "documents" });65  const linker = await mk(ws, `${PFX} linker`, { type: "doc", content: [{ type: "paragraph", content: [{ type: "mention", attrs: { id: p.id, label: `${PFX} page` } }] }] });66  const t1 = await createTask(ws, { title: `${PFX} t1`, pageId: p.id, blockId: "blk1", dueAt: "2020-01-02", priority: "high" }); const t2 = await createTask(ws, { title: `${PFX} t2 done`, pageId: p.id, status: "done" }); made.tasks.push(t1.task.id, t2.task.id);67  const ref = await createReference(ws, { title: `${PFX} A paper`, authors: ["Jane Doe", "John Roe"], year: 2021, journal: "J. Tests", entryType: "article", pageId: p.id } as any); made.references.push(ref.id);6869  // tasks70  const raw = wire(await runQuery(ws, { source: "tasks", filter: { parentId: p.id, status: "all" } })) as any;71  assert.deepEqual(Object.keys(raw), ["source", "columns", "rows", "total", "limit", "table", "resolvedAt"], "§4.7 top-level keys");72  assert.deepEqual(Object.keys(raw.columns[0]), ["key", "label", "type"]);73  const tasks = normaliseQueryResult(raw, "tasks");74  assert.equal(tasks.total, 2); assert.equal(tasks.limit, 25); assert.equal(tasks.resolvedAt, raw.resolvedAt); assert.deepEqual(tasks.columns.map((c) => c.key), ["title", "status", "priority", "dueAt", "pageTitle", "project"]);75  const a = tasks.rows.find((r) => r.key === t1.task.id)!, b = tasks.rows.find((r) => r.key === t2.task.id)!;76  assert.deepEqual([a.title, a.status, a.done, a.href, a.subtitle, a.cells.priority], [`${PFX} t1`, "todo", false, `/p/${p.id}#block-blk1`, `${PFX} page`, "high"]);77  assert.match(a.due ?? "", /^2020-01-02T/); assert.deepEqual([b.status, b.done, b.due], ["done", true, null]);78  assert.deepEqual(groupByStatus(tasks.rows).map((g) => g.status).sort(), ["done", "todo"]);79  assert.deepEqual(tableColumns(tasks).map((c) => c.key), ["status", "priority", "dueAt", "pageTitle", "project"], "the title column is not repeated in the table layout");80  assert.deepEqual(tasks.table.columns, raw.table.columns); assert.deepEqual(tasks.table.rows, raw.table.rows);8182  // pages83  const pages = normaliseQueryResult(wire(await runQuery(ws, { source: "pages", filter: { text: `${PFX} page` } })), "pages");84  const pr = pages.rows.find((r) => r.key === p.id)!; assert.deepEqual([pr.title, pr.href, pr.status, pr.done, pr.due], [`${PFX} page`, `/p/${p.id}`, null, false, null]); assert.equal(pr.cells.section, "documents");8586  // references87  const refs = normaliseQueryResult(wire(await runQuery(ws, { source: "references", filter: { text: `${PFX} A paper` } })), "references");88  const rr = refs.rows.find((r) => r.key === ref.id)!; assert.equal(rr.title, `${PFX} A paper`); assert.equal(rr.subtitle, "Jane Doe, John Roe · 2021 · J. Tests"); assert.equal(rr.cells.authors, "Jane Doe, John Roe"); assert.equal(rr.cells.year, "2021"); assert.equal(rr.href, `/p/${p.id}`);8990  // backlinks91  const back = normaliseQueryResult(wire(await runQuery(ws, { source: "backlinks", pageId: p.id })), "backlinks");92  assert.deepEqual(back.rows.map((r) => [r.key, r.href]), [[linker.id, `/p/${linker.id}`]]);9394  // database → also what a chart with `source` plots95  const host = await mk(ws, `${PFX} db`, undefined, { type: "database", section: "databases" }); const d = await ensureDatabase(ws, host.id);96  const num = await createProperty(ws, d.id, { name: "Score", type: "number" }); const st = await createProperty(ws, d.id, { name: "Status", type: "select", config: { options: [{ id: "o1", name: "Read", color: "green" }] } }); const chk = await createProperty(ws, d.id, { name: "Seen", type: "checkbox" });97  const r1 = await createRow(ws, d.id, { title: `${PFX} row A`, values: { [num.id]: 21, [st.id]: "o1", [chk.id]: true } }); const r2 = await createRow(ws, d.id, { title: `${PFX} row B`, values: { [num.id]: 4 } }); made.pages.push(r1.pageId, r2.pageId);98  const body = chartQueryBody({ databaseId: host.id }); assert.deepEqual(body, { source: "database", databaseId: host.id, filter: {}, limit: 500 });99  const dbRaw = wire(await runQuery(ws, body as any)) as any; assert.equal(dbRaw.name, d.name); assert.equal(dbRaw.databaseId, d.id);100  const dbr = normaliseQueryResult(dbRaw, "database"); assert.equal(dbr.name, d.name); assert.deepEqual(dbr.columns.map((c) => [c.label, c.type]), [["Name", "page"], ["Score", "number"], ["Status", "select"], ["Seen", "checkbox"]]);101  const ra = dbr.rows.find((r) => r.key === r1.id)!; assert.deepEqual([ra.title, ra.status, ra.href, ra.cells[num.id], ra.cells[chk.id]], [`${PFX} row A`, "Read", `/p/${r1.pageId}`, "21", "Yes"]);102  assert.deepEqual(tableColumns(dbr).map((c) => c.label), ["Score", "Status", "Seen"]);103  assert.deepEqual(dbr.table.columns, ["Name", "Score", "Status", "Seen"]); assert.deepEqual(dbr.table.rows.find((r) => r[0] === `${PFX} row A`)?.slice(0, 3), [`${PFX} row A`, 21, "Read"]);104  // the flattened table is directly plottable: the chart model draws one bar per row from the live data105  const cfg = defaultChartConfig(dbr.table.columns, dbr.table.rows); assert.equal(cfg.x, "Name"); assert.ok(cfg.y.includes("Score"));106  const model = chartModel({ kind: "bar", title: "", columns: dbr.table.columns, rows: dbr.table.rows, x: cfg.x, y: ["Score"] }, { width: 600, height: 300 }); assert.deepEqual(model.problems, []); assert.equal(model.rects.length, 2);107});108109test("contract: anything that is not the §4.7 shape is an error, never an empty view", () => {110  const ok = { source: "tasks", columns: [{ key: "title", label: "Tâche", type: "text" }], rows: [{ id: "x", pageId: null, title: "T" }], total: 1, limit: 25, table: { columns: ["Tâche"], rows: [["T"]] }, resolvedAt: "2026-11-19T18:30:22.355Z" };111  assert.equal(normaliseQueryResult(ok, "tasks").rows.length, 1);112  for (const bad of [null, [], [{ id: "a", title: "x" }], { rows: [] }, { ...ok, columns: ["Tâche"] }, { ...ok, columns: [{ name: "Tâche" }] }, { ...ok, rows: [{ title: "no id" }] }, { ...ok, table: undefined }, { ...ok, table: { columns: ["a"], rows: [{}] } }, { items: [{ id: "a" }] }])113    assert.throws(() => normaliseQueryResult(bad, "tasks"), QueryShapeError, JSON.stringify(bad));114  // an unknown column type is displayed as text; unknown extra keys are ignored115  assert.equal(normaliseQueryResult({ ...ok, columns: [{ key: "title", label: "T", type: "future" }], extra: 1 }, "tasks").columns[0].type, "text");116  assert.equal(cellDisplay(["a", "b"], "tags"), "a, b"); assert.equal(cellDisplay(false, "checkbox"), "No"); assert.equal(cellDisplay({ title: "Linked" }, "json"), "Linked"); assert.equal(cellDisplay(null, "number"), "");117});118119test("request bodies, snapshot comparison and the refreshed label", () => {120  assert.deepEqual(queryBody({ source: "tasks", databaseId: null, viewId: null, filter: { status: "open", tag: " " }, limit: 999 }), { source: "tasks", filter: { status: "open" }, limit: 200 });121  assert.deepEqual(chartQueryBody({ databaseId: "d", viewId: "v" }), { source: "database", databaseId: "d", viewId: "v", filter: {}, limit: 500 });122  assert.equal(sameTable({ columns: ["a"], rows: [[1], [null]] }, { columns: ["a"], rows: [[1], [null]] }), true);123  assert.equal(sameTable({ columns: ["a"], rows: [[1]] }, { columns: ["a"], rows: [["1"]] }), false); assert.equal(sameTable({ columns: ["a"], rows: [[1]] }, { columns: ["b"], rows: [[1]] }), false); assert.equal(sameTable({ columns: ["a"], rows: [] }, { columns: ["a"], rows: [[1]] }), false);124  const now = new Date("2026-11-19T18:00:00Z");125  assert.equal(refreshedLabel("2026-11-19T17:59:40Z", now), "just now"); assert.equal(refreshedLabel("2026-11-19T17:48:00Z", now), "12 min ago"); assert.equal(refreshedLabel(null, now), ""); assert.equal(refreshedLabel("nope", now), "");126  assert.match(refreshedLabel("2026-11-17T10:00:00Z", now), /17/, "another day shows the date");127});128129test("device snapshot: last answer per request, key independent of key order, bounded, never throws", () => {130  const s = memory(); const answer = { source: "tasks", columns: [{ key: "title", label: "Tâche", type: "text" }], rows: [{ id: "x", pageId: null, title: "Kept" }], total: 1, limit: 25, table: { columns: ["Tâche"], rows: [["Kept"]] }, resolvedAt: "2026-11-19T18:30:22.355Z" };131  assert.equal(queryKeyOf({ source: "tasks", filter: { a: 1, b: 2 }, limit: 5 }), queryKeyOf({ limit: 5, filter: { b: 2, a: 1 }, source: "tasks" })); assert.notEqual(queryKeyOf({ source: "tasks" }), queryKeyOf({ source: "pages" }));132  assert.equal(loadQuerySnapshot(s, { source: "tasks" }, "tasks"), null);133  assert.equal(saveQuerySnapshot(s, { source: "tasks" }, answer), true);134  const back = loadQuerySnapshot(s, { source: "tasks" }, "tasks")!; assert.equal(back.rows[0].title, "Kept"); assert.equal(back.resolvedAt, "2026-11-19T18:30:22.355Z", "the snapshot keeps the time the server resolved it");135  for (let i = 0; i < 45; i++) saveQuerySnapshot(s, { source: "pages", limit: i + 1 }, answer);136  assert.equal([...s.m.keys()].filter((k) => k !== "spn.query.index").length, 40, "oldest snapshots are dropped"); assert.equal(loadQuerySnapshot(s, { source: "tasks" }, "tasks"), null);137  assert.equal(saveQuerySnapshot(s, { source: "big" }, { blob: "x".repeat(210_000) }), false, "oversized answers are not kept");138  s.m.set("spn.query." + queryKeyOf({ source: "broken" }), "{not json"); assert.equal(loadQuerySnapshot(s, { source: "broken" }, "tasks"), null);139  const full = { getItem: () => null, setItem: () => { throw new Error("QuotaExceededError"); }, removeItem: () => {} }; assert.equal(saveQuerySnapshot(full, { source: "tasks" }, answer), false);140  assert.equal(saveQuerySnapshot(null, {}, answer), false); assert.equal(loadQuerySnapshot(undefined, {}, "tasks"), null);141});142
Files main
Menu

Theme