Several libraries on the server: one directory, store, notice stream, link index, pending links, reviewer and jobs each; /api/libraries and /api/l/<id>/…; the page holds one library, named by its address, and switches by a page load
The old single-library layout is not opened (the server says to run the migration, which comes next); the per-document migration, /recover and the old replicas check are gone. A server lock keeps two servers off one data directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
045a8459da
commit
79aa85e883
22 files changed
+1468
-759
No files matched your search
+18
-7
@@ -42,9 +42,20 @@ export async function nodeAt(page: Page, ...path: string[]): Promise<string> {
|
||||
return find(s, ...path);
|
||||
}
|
||||
|
||||
/** Go to the address of the section at these titles from the library root (none: the library, `/`), and wait for the page. */
|
||||
/** The id of the library the tests share: the server's first (what the unprefixed routes act on). */
|
||||
export async function libraryId(page: Page): Promise<string> {
|
||||
return (await (await page.request.get("/api/state")).json()).library;
|
||||
}
|
||||
|
||||
/** An address in the shared library: `/l/<id>` for its root, then a path within it (`/n/<node id>`, `/w/en/Octopus`). */
|
||||
export async function libraryPath(page: Page, part = "/"): Promise<string> {
|
||||
const base = `/l/${await libraryId(page)}`;
|
||||
return part === "/" ? base : base + part;
|
||||
}
|
||||
|
||||
/** Go to the address of the section at these titles from the library root (none: the library, `/l/<id>`), and wait for the page. */
|
||||
export async function openAt(page: Page, ...path: string[]) {
|
||||
await page.goto(path.length ? `/n/${encodeURIComponent(await nodeAt(page, ...path))}` : "/");
|
||||
await page.goto(await libraryPath(page, path.length ? `/n/${encodeURIComponent(await nodeAt(page, ...path))}` : "/"));
|
||||
await page.waitForSelector("article");
|
||||
}
|
||||
|
||||
@@ -61,12 +72,12 @@ export async function openPage(page: Page, ...path: string[]) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Go somewhere: an address as it is (`/`, `/w/en/Octopus`), or a top-level section by its title,
|
||||
* opened as the page (openPage). Does not wait for the page.
|
||||
* Go somewhere: an address in the shared library (`/` its root, `/w/en/Octopus`), or a top-level
|
||||
* section by its title, opened as the page (openPage). Does not wait for the page.
|
||||
*/
|
||||
export async function visit(page: Page, where: string) {
|
||||
if (where.startsWith("/")) return void (await page.goto(where));
|
||||
await page.goto(`/n/${encodeURIComponent(await nodeAt(page, where))}`);
|
||||
if (where.startsWith("/")) return void (await page.goto(await libraryPath(page, where)));
|
||||
await page.goto(await libraryPath(page, `/n/${encodeURIComponent(await nodeAt(page, where))}`));
|
||||
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
await hoistHere(page);
|
||||
}
|
||||
@@ -77,7 +88,7 @@ export async function visit(page: Page, where: string) {
|
||||
* has the focus.
|
||||
*/
|
||||
export async function addTop(page: Page, title: string, text: string) {
|
||||
await page.goto("/");
|
||||
await page.goto(await libraryPath(page));
|
||||
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
await page.keyboard.press("a");
|
||||
await page.keyboard.type(title);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Several libraries, from the page: every address names its library (`/l/<id>`), `/` opens the one
|
||||
* last used, :/library lists, makes and opens them (a page load), a new library starts with its root
|
||||
* alone, nothing of one library is found from another (the jump box, nearby and Related, a node's
|
||||
* address), and each library keeps its own view. The panel that lists them is step 4's; these
|
||||
* tests use the command and the API. They make their own libraries and delete them at the end: the
|
||||
* other specs share the first.
|
||||
*/
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { command, keys, libraryId, settle, state } from "./helpers";
|
||||
|
||||
const ready = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
const status = (page: Page) => page.locator(".status .message");
|
||||
const lib = (page: Page) => state(page, (s) => s.library as string);
|
||||
|
||||
test.describe.configure({ mode: "serial" });
|
||||
test.afterEach(({ page }) => settle(page));
|
||||
|
||||
test("a new library starts with its root alone, has an address of its own, and finds nothing of the first", async ({ page }) => {
|
||||
const first = await libraryId(page);
|
||||
await page.goto("/");
|
||||
await ready(page);
|
||||
// `/` opens the first library in a browser that has used none, at its own address.
|
||||
expect(await lib(page)).toBe(first);
|
||||
await expect(page).toHaveURL(new RegExp(`/l/${first}$`));
|
||||
|
||||
await command(page, "/library new Work notes");
|
||||
await page.waitForURL((u) => /^\/l\/[0-9a-z]+$/.test(u.pathname) && !u.pathname.endsWith(first));
|
||||
await ready(page);
|
||||
const work = await lib(page);
|
||||
expect(work).not.toBe(first);
|
||||
await expect(page.locator(".top h1")).toHaveText("Work notes");
|
||||
await expect(page.locator(".docbar .lib-name")).toHaveText("Work notes");
|
||||
// Its root alone: no seed, no starter trees.
|
||||
expect(await state(page, (s) => s.snap.nodes[s.snap.root].children.length)).toBe(0);
|
||||
|
||||
// A section with the same title as one in the first library, and text that mentions the first's titles.
|
||||
await keys(page, "a");
|
||||
await page.keyboard.type("Fixed points");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(() => Object.values((globalThis as any).__ie.snap.nodes).some((n: any) => n.title === "Fixed points"));
|
||||
await page.waitForFunction(() => (globalThis as any).__ie.synced());
|
||||
|
||||
// The jump box offers this library's nodes only.
|
||||
await keys(page, "/");
|
||||
await page.keyboard.type("Amphidromes");
|
||||
await expect(page.locator(".jump li[data-hit]")).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await keys(page, "/");
|
||||
await page.keyboard.type("Fixed points");
|
||||
await expect(page.locator(".jump li[data-hit]")).toHaveCount(1);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// The server's routes for it hold only it.
|
||||
const tree = await (await page.request.get(`/api/l/${work}/tree`)).json();
|
||||
expect(Object.values(tree.nodes).map((n: any) => n.title).sort()).toEqual(["Fixed points", "Work notes"]);
|
||||
const firstTree = await (await page.request.get(`/api/l/${first}/tree`)).json();
|
||||
expect(Object.values(firstTree.nodes).some((n: any) => n.title === "Work notes")).toBe(false);
|
||||
// Nearby and Related never come from the first library, though it has a "Fixed points" too.
|
||||
const mine = Object.values(tree.nodes).find((n: any) => n.title === "Fixed points") as { id: string };
|
||||
const nearby = await (await page.request.get(`/api/l/${work}/links/nearby?node=${encodeURIComponent(mine.id)}`)).json();
|
||||
for (const n of nearby.nearby) expect(tree.nodes[n.handle]).toBeTruthy();
|
||||
const related = await (await page.request.get(`/api/l/${work}/links/related?node=${encodeURIComponent(mine.id)}`)).json();
|
||||
for (const r of related.related) expect(tree.nodes[r.node]).toBeTruthy();
|
||||
|
||||
// A node of the first library, at this library's address, is not found here.
|
||||
const amph = Object.values(firstTree.nodes).find((n: any) => n.title === "Amphidromes") as { id: string };
|
||||
await page.goto(`/l/${work}/n/${encodeURIComponent(amph.id)}`);
|
||||
await ready(page);
|
||||
await expect(page.locator(".top h1")).toHaveText("Work notes");
|
||||
await expect(status(page)).toContainText(amph.id);
|
||||
|
||||
// `/` now opens the library last used here.
|
||||
await page.goto("/");
|
||||
await ready(page);
|
||||
expect(await lib(page)).toBe(work);
|
||||
// :/library with a name opens another, by a page load; each keeps its own view.
|
||||
await command(page, "/library Library");
|
||||
await page.waitForURL(new RegExp(`/l/${first}`));
|
||||
await ready(page);
|
||||
expect(await lib(page)).toBe(first);
|
||||
await expect(page.locator(".top h1")).toHaveText("Library");
|
||||
const keysNow = await page.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("ie:view:")).sort());
|
||||
expect(keysNow).toEqual(expect.arrayContaining([`ie:view:${first}:main`, `ie:view:${work}:main`]));
|
||||
});
|
||||
|
||||
test("rename and delete over the API; an unknown library's address goes to the first; the last library cannot be deleted", async ({ page }) => {
|
||||
const first = await libraryId(page);
|
||||
const listed = (await (await page.request.get("/api/libraries")).json()).libraries as { id: string; title: string }[];
|
||||
const work = listed.find((l) => l.title === "Work notes")!;
|
||||
expect(work).toBeTruthy();
|
||||
const renamed = await page.request.patch(`/api/libraries/${work.id}`, { data: { title: "Work, renamed" } });
|
||||
expect(renamed.ok()).toBe(true);
|
||||
await page.goto(`/l/${work.id}`);
|
||||
await ready(page);
|
||||
await expect(page.locator(".top h1")).toHaveText("Work, renamed");
|
||||
// The page learns of its library's deletion and stops sending.
|
||||
const gone = await page.request.delete(`/api/libraries/${work.id}`);
|
||||
expect(gone.ok()).toBe(true);
|
||||
expect((await gone.json()).movedTo).toContain(".deleted");
|
||||
await expect(status(page)).toContainText("This library has been deleted");
|
||||
// Its address now goes to the first library, saying so.
|
||||
await page.goto(`/l/${work.id}`);
|
||||
await page.waitForURL(new RegExp(`/l/${first}$`));
|
||||
await ready(page);
|
||||
await expect(status(page)).toContainText(`There is no library ${work.id} here`);
|
||||
// The first, now alone, cannot be deleted.
|
||||
const last = await page.request.delete(`/api/libraries/${first}`);
|
||||
expect(last.status()).toBe(409);
|
||||
});
|
||||
+1
-1
@@ -79,7 +79,7 @@ test("hoisting makes one node the whole page; Esc at its top steps out to its pa
|
||||
await expect(page).toHaveURL(/\/n\/[^/]+$/);
|
||||
// On the root itself, the address is the library's.
|
||||
await page.keyboard.press("O");
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
await expect(page).toHaveURL(/\/l\/[0-9a-z]+$/);
|
||||
});
|
||||
|
||||
test("with speculation on, the focused sentence is already being written when it is asked for", async ({ page }) => {
|
||||
|
||||
+2
-2
@@ -68,10 +68,10 @@ test("the library root is the first page and a node like any other: its sections
|
||||
const first = await state(page, (s) => s.focus.node);
|
||||
await expect(page).toHaveURL(new RegExp(`/n/${encodeURIComponent(first)}$`));
|
||||
await expect(page).toHaveTitle("Infinispand");
|
||||
// Back up onto the root itself: its address is /, and it is the node the keys act on.
|
||||
// Back up onto the root itself: its address is the library's, /l/<id>, and it is the node the keys act on.
|
||||
await keys(page, "h k");
|
||||
expect(await state(page, (s) => s.focus.node === s.snap.root)).toBe(true);
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
await expect(page).toHaveURL(/\/l\/[0-9a-z]+$/);
|
||||
await expect(page).toHaveTitle("Library");
|
||||
await keys(page, "D");
|
||||
await expect(status(page)).toHaveText("The library itself cannot be deleted.");
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Everything the server keeps for one library, and the routes that act on it. Each library has its
|
||||
* own store, notice stream, node index (vectors), pending links, link reviewer and background jobs,
|
||||
* all bound to that library's database alone, so nothing one library holds can reach a request
|
||||
* about another: a route finds its library first and is handed only that library's bundle.
|
||||
*
|
||||
* What is shared holds no library's content: the model, Wikipedia (and its cache) and the embedding
|
||||
* model.
|
||||
*
|
||||
* Routes, after /api/l/<id>/ (or after /api/ for the first library):
|
||||
*
|
||||
* GET state what the page needs to start
|
||||
* GET events the library's notice stream (server-sent events)
|
||||
* GET branch/<b>, POST sync/<b> what replicas use
|
||||
* GET tree[/<b>], POST ops[/<b>] the op API
|
||||
* GET nodes/<id>/tree|export[/<b>], POST nodes/<id>/import
|
||||
* … links/* link discovery (links/routes.ts)
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { join } from "node:path";
|
||||
import { VersionVector } from "loro-crdt";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model";
|
||||
import { encodeVV, history } from "../src/core/repo";
|
||||
import { IMPORT_MAX, importTree } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import type { LLM } from "../src/llm/types";
|
||||
import type { Embedder } from "./embed";
|
||||
import { LibraryStore, validBranch } from "./library";
|
||||
import { Jobs } from "./links/jobs";
|
||||
import { NodeIndex } from "./links/nodeIndex";
|
||||
import { PendingStore } from "./links/pending";
|
||||
import { Reviewer } from "./links/review";
|
||||
import { linkRoutes } from "./links/routes";
|
||||
import { Linker } from "./links/scan";
|
||||
import { HttpError, readBody, readJson, sendJson as json } from "./util";
|
||||
import type { WikiClient } from "./wiki";
|
||||
|
||||
/** What every library's bundle is given: shared, and holding no library's content. */
|
||||
export interface Shared {
|
||||
llm: () => LLM | null;
|
||||
wiki: () => WikiClient | null;
|
||||
embed: Embedder | null;
|
||||
reviewCalls: number;
|
||||
user: string;
|
||||
/** What /state says besides the library's own part. */
|
||||
state: () => Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Largest replica update a sync accepts. */
|
||||
const SYNC_MAX = 256 * 1024 * 1024;
|
||||
|
||||
const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON());
|
||||
|
||||
export class Bundle {
|
||||
readonly listeners = new Set<ServerResponse>();
|
||||
readonly nodeIndex: NodeIndex;
|
||||
readonly pending: PendingStore;
|
||||
readonly reviewer: Reviewer;
|
||||
readonly jobs: Jobs;
|
||||
private linker: Linker | null = null;
|
||||
private handleLinks: ReturnType<typeof linkRoutes>;
|
||||
|
||||
constructor(
|
||||
readonly store: LibraryStore,
|
||||
private shared: Shared,
|
||||
) {
|
||||
const main = () => store.main;
|
||||
// The embedding model is loaded on first use, in a worker thread shared by every library; each
|
||||
// library's vectors are its own. Pending suggestions are derived data, kept beside the library.
|
||||
this.nodeIndex = new NodeIndex(main, { file: join(store.dir, "vectors", "nodes"), embedder: shared.embed });
|
||||
this.nodeIndex.watch(store.main);
|
||||
const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex }));
|
||||
this.pending = new PendingStore(join(store.dir, "links", "pending.json"));
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls.
|
||||
this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() });
|
||||
this.jobs = new Jobs({
|
||||
snap: () => store.main.snap(),
|
||||
linker: getLinker,
|
||||
wiki: shared.wiki,
|
||||
index: this.nodeIndex,
|
||||
pending: this.pending,
|
||||
announce: (state) => this.announce({ linkJob: state }),
|
||||
reviewer: this.reviewer,
|
||||
reviewCalls: shared.reviewCalls,
|
||||
});
|
||||
this.handleLinks = linkRoutes({ main, linker: getLinker, index: this.nodeIndex, pending: this.pending, jobs: this.jobs, embedder: shared.embed, reviewer: this.reviewer, wrote: () => this.wrote("main") });
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this.store.id;
|
||||
}
|
||||
|
||||
/** A notice to every page open on this library. */
|
||||
announce(message: Record<string, unknown>) {
|
||||
const line = `data: ${JSON.stringify(message)}\n\n`;
|
||||
for (const res of this.listeners) res.write(line);
|
||||
}
|
||||
|
||||
/** A server-side write to a branch: saved shortly and announced to every replica. */
|
||||
wrote(branch: string) {
|
||||
this.store.saveSoon(branch);
|
||||
this.announce({ branch, from: "api" });
|
||||
}
|
||||
|
||||
/** Write what is waiting, on the way out. */
|
||||
flush() {
|
||||
this.store.flush();
|
||||
this.pending.flush();
|
||||
}
|
||||
|
||||
/** The library is being moved aside: stop its job, write what is waiting, tell its pages, and write nothing more. */
|
||||
close() {
|
||||
this.jobs.cancel();
|
||||
this.nodeIndex.close();
|
||||
this.pending.close();
|
||||
this.store.close();
|
||||
this.announce({ library: "deleted" });
|
||||
for (const res of this.listeners) res.end();
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
/** A request about this library; `parts` is the path after its prefix, `url` rewritten to /api/<parts>. */
|
||||
async handle(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<boolean> {
|
||||
const [a, b] = parts;
|
||||
const method = req.method ?? "GET";
|
||||
if (a === "state" && method === "GET") {
|
||||
const store = this.store;
|
||||
json(res, 200, {
|
||||
...this.shared.state(),
|
||||
library: store.id,
|
||||
title: store.title,
|
||||
branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })),
|
||||
linkJob: this.jobs.current,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (a === "nodes") return (await this.nodeApi(req, res, url, parts.slice(1)), true);
|
||||
if (a && ["events", "branch", "sync", "tree", "ops"].includes(a)) return (await this.libraryApi(req, res, url, a, b), true);
|
||||
if (a === "links") {
|
||||
this.nodeIndex.activate();
|
||||
return this.handleLinks(req, res, url);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The library as a whole: what replicas use, and the op API. */
|
||||
private async libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) {
|
||||
const method = req.method ?? "GET";
|
||||
const store = this.store;
|
||||
const name = b || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
|
||||
if (action === "events" && method === "GET") {
|
||||
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
||||
res.write(": connected\n\n");
|
||||
this.listeners.add(res);
|
||||
req.on("close", () => this.listeners.delete(res));
|
||||
return;
|
||||
}
|
||||
|
||||
// A replica fetches a branch whole.
|
||||
if (action === "branch" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id });
|
||||
return res.end(doc.snapshotBytes());
|
||||
}
|
||||
|
||||
// A replica pushes what it has and gets back what it lacks. Request header x-vv is the
|
||||
// replica's version; the response carries the server's. A replica must name the library it
|
||||
// belongs to: bytes from another library (an old tab, a browser that outlived its data
|
||||
// directory, a page of another library) would add a second root to this one. A beacon cannot
|
||||
// send headers, so it names the library in the query.
|
||||
if (action === "sync" && method === "POST") {
|
||||
if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) {
|
||||
return json(res, 409, { error: "This page belongs to a different library than the server has here. Reload the page.", library: store.id });
|
||||
}
|
||||
const bytes = await readBody(req, SYNC_MAX);
|
||||
let doc = store.branches.get(name);
|
||||
const before = doc ? vvHeader(doc) : "";
|
||||
if (!doc) {
|
||||
if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
doc = Doc.load(bytes, "server");
|
||||
if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" });
|
||||
store.addBranch(name, doc);
|
||||
} else if (bytes.length) {
|
||||
doc.loro.import(bytes);
|
||||
doc.touch();
|
||||
}
|
||||
if (vvHeader(doc) !== before) {
|
||||
store.saveSoon(name);
|
||||
this.announce({ branch: name, from: String(req.headers["x-client"] ?? "") });
|
||||
}
|
||||
const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map();
|
||||
const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) });
|
||||
return res.end(update);
|
||||
}
|
||||
|
||||
// For outside agents: read the library as JSON…
|
||||
if (action === "tree" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
return json(res, 200, { ...doc.snap(), library: store.id, conflicts: doc.conflicts(), history: history(doc).slice(0, 50) });
|
||||
}
|
||||
|
||||
// …and write to it with the same ops everyone else uses. Node ids are the library's, so one
|
||||
// batch can work anywhere in it (moving a node from one place to another is a move).
|
||||
if (action === "ops" && method === "POST") return this.opsApi(req, res, name);
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
private async opsApi(req: IncomingMessage, res: ServerResponse, name: string) {
|
||||
const doc = this.store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req);
|
||||
if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" });
|
||||
const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api";
|
||||
try {
|
||||
return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" })));
|
||||
} catch (err) {
|
||||
if (err instanceof OpError) return json(res, 422, { error: err.message });
|
||||
throw err;
|
||||
} finally {
|
||||
this.wrote(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One node and everything under it, by its id: the subtree as JSON with its conflicts, the text
|
||||
* format as a download, or a file in the text format imported under it. An import is an ordinary
|
||||
* commit on main; the browser makes the same commits in its own replica.
|
||||
*/
|
||||
private async nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
|
||||
const method = req.method ?? "GET";
|
||||
const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined];
|
||||
const name = branch || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
const doc = this.store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const snap = doc.snap();
|
||||
if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` });
|
||||
|
||||
// GET nodes/<id>/tree[/<branch>]: the subtree, as tree returns the library.
|
||||
if (action === "tree" && method === "GET") {
|
||||
const ids = new Set([id, ...descendants(snap, id)]);
|
||||
return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) });
|
||||
}
|
||||
// GET nodes/<id>/export[/<branch>]: the text format, as a download.
|
||||
if (action === "export" && method === "GET") {
|
||||
const { text, skipped } = serializeDoc(snap, id);
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/markdown; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
|
||||
"x-skipped": JSON.stringify(skipped),
|
||||
});
|
||||
return res.end(text);
|
||||
}
|
||||
// POST nodes/<id>/import?name=file.md, with the file as the body: a new last child of the node (on main).
|
||||
if (action === "import" && !branch && method === "POST") {
|
||||
const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
|
||||
let text: string;
|
||||
try {
|
||||
text = (await readBody(req, IMPORT_MAX)).toString("utf8");
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` });
|
||||
throw err;
|
||||
}
|
||||
const main = this.store.main;
|
||||
if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` });
|
||||
try {
|
||||
const top = importTree(main, text, file, { creator: this.shared.user, parent: id });
|
||||
this.wrote("main");
|
||||
return json(res, 201, { node: top, title: main.snap().nodes[top].title });
|
||||
} catch (err) {
|
||||
if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
}
|
||||
@@ -394,6 +394,11 @@ export class VectorIndex {
|
||||
|
||||
// -- persistence --
|
||||
|
||||
/** Write nothing more (its directory is being moved aside). */
|
||||
detach() {
|
||||
this.file = null;
|
||||
}
|
||||
|
||||
save() {
|
||||
if (!this.file) return;
|
||||
const model = this.embedder?.spec.id ?? null;
|
||||
|
||||
+110
-214
@@ -1,42 +1,35 @@
|
||||
/**
|
||||
* The local server. It does three small things:
|
||||
* - relays library updates between replicas (tabs, people, agents) and keeps a copy on disk
|
||||
* - relays each library's updates between replicas (tabs, people, agents) and keeps a copy on disk
|
||||
* - holds the API key and proxies model calls
|
||||
* - exposes the op API over HTTP, so an outside agent can read and edit the tree
|
||||
* - exposes the op API over HTTP, so an outside agent can read and edit a library
|
||||
* In development it also hosts Vite; in production it serves the built files.
|
||||
*
|
||||
* The whole library is one database: /api/tree, /api/ops, /api/sync… act on all of it, and
|
||||
* /api/nodes/<id>/… on one node and what is under it. See README.md for the list.
|
||||
* There are several libraries, each a database of its own (libraries.ts): /api/libraries lists,
|
||||
* makes, renames and deletes them, and /api/l/<id>/… acts on one of them (bundle.ts), the same
|
||||
* routes without the prefix on the first. See README.md for the list.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { userInfo } from "node:os";
|
||||
import { extname, join, resolve } from "node:path";
|
||||
import { VersionVector } from "loro-crdt";
|
||||
import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model";
|
||||
import { encodeVV, history } from "../src/core/repo";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { IMPORT_MAX, importTree, writeSeed } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import { writeSeed } from "../src/core/seed";
|
||||
import { mockLLM } from "../src/llm/mock";
|
||||
import { LLMUnavailable, type JsonReq, type LLM, type Req, type TurnReq } from "../src/llm/types";
|
||||
import { seed } from "../src/seed/tree";
|
||||
import { Bundle, type Shared } from "./bundle";
|
||||
import { claudeLLM, describeError } from "./claude";
|
||||
import { LibraryStore, validBranch } from "./library";
|
||||
import { Libraries, NeedsMigration, importStarters } from "./libraries";
|
||||
import { lockHolder, takeLock } from "./lock";
|
||||
import { SubscriptionError, queryPlanUsage, subscriptionLLM } from "./subscription";
|
||||
import { usage, withMockUsage } from "./usage";
|
||||
import { HttpError, ROOT as root, abortOnClose, dataDir, readBody, readJson, sendJson as json } from "./util";
|
||||
import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util";
|
||||
import { applyWebPolicy, webConfig } from "./web";
|
||||
import { WikiClient, validContact, wiki, wikiLang } from "./wiki";
|
||||
import { makeMockWikiFetch } from "./wikiMock";
|
||||
import { wikiOff, wikiRoutes } from "./wikiRoutes";
|
||||
import { embedder } from "./embed";
|
||||
import { Jobs } from "./links/jobs";
|
||||
import { NodeIndex } from "./links/nodeIndex";
|
||||
import { PendingStore } from "./links/pending";
|
||||
import { JOB_CALLS, Reviewer } from "./links/review";
|
||||
import { linkRoutes } from "./links/routes";
|
||||
import { Linker } from "./links/scan";
|
||||
import { JOB_CALLS } from "./links/review";
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 4747);
|
||||
// Host names the dev server answers to besides localhost. Tailscale names are allowed so that
|
||||
@@ -103,89 +96,84 @@ const wikiState = { mode: wikiMode, lang: wikiLang(process.env.IE_WIKI_LANG), co
|
||||
/** A short reason for a failed model call, whichever provider made it. */
|
||||
const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err));
|
||||
|
||||
// ---- the library on disk ----
|
||||
// ---- the libraries on disk ----
|
||||
|
||||
mkdirSync(DATA, { recursive: true });
|
||||
const started = performance.now();
|
||||
const store = new LibraryStore(DATA).open();
|
||||
store.seedFirst((doc) => writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed));
|
||||
store.importLibrary(LIBRARY);
|
||||
const startMs = Math.round(performance.now() - started);
|
||||
// Writes are gathered before they go to disk; whatever is waiting goes on the way out.
|
||||
process.on("exit", () => store.flush());
|
||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0));
|
||||
|
||||
const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON());
|
||||
|
||||
// ---- link discovery (server/links) ----
|
||||
|
||||
// The embedding model is loaded on first use, in a worker thread; IE_EMBED=off turns it off, and
|
||||
// scanning then matches by text alone. Pending suggestions are derived data, kept beside the library.
|
||||
const embed = process.env.IE_EMBED === "off" ? null : embedder();
|
||||
const nodeIndex = new NodeIndex(() => store.main, { file: join(DATA, "vectors", "nodes"), embedder: embed });
|
||||
nodeIndex.watch(store.main);
|
||||
let linker: Linker | null = null;
|
||||
const getLinker = () => (linker ??= new Linker({ doc: () => store.main, wiki: wikiClient, embedder: embed, index: nodeIndex }));
|
||||
const pending = new PendingStore(join(DATA, "links", "pending.json"));
|
||||
process.on("exit", () => pending.flush());
|
||||
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls.
|
||||
const reviewer = new Reviewer({ llm: () => llm, wiki: wikiClient, pending, snap: () => store.main.snap() });
|
||||
const reviewCalls = Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS);
|
||||
const jobs = new Jobs({
|
||||
snap: () => store.main.snap(),
|
||||
linker: getLinker,
|
||||
wiki: wikiClient,
|
||||
index: nodeIndex,
|
||||
pending,
|
||||
announce: (state) => announce({ linkJob: state }),
|
||||
reviewer,
|
||||
reviewCalls,
|
||||
});
|
||||
const handleLinks = linkRoutes({ main: () => store.main, linker: getLinker, index: nodeIndex, pending, jobs, embedder: embed, reviewer, wrote: () => wrote("main") });
|
||||
|
||||
// ---- live notifications ----
|
||||
|
||||
const listeners = new Set<ServerResponse>();
|
||||
function announce(message: Record<string, unknown>) {
|
||||
const line = `data: ${JSON.stringify(message)}\n\n`;
|
||||
for (const res of listeners) res.write(line);
|
||||
// A data directory in an older layout is never opened, nor migrated without being asked: the
|
||||
// migration (npm run migrate) has a dry run and verifies what it writes.
|
||||
const held = lockHolder(DATA);
|
||||
if (held) {
|
||||
console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set IE_DATA to another directory.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const libraries = new Libraries(DATA);
|
||||
try {
|
||||
libraries.open((doc) => {
|
||||
writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed);
|
||||
console.log("seeded the first tree from src/seed");
|
||||
importStarters(doc, LIBRARY);
|
||||
});
|
||||
} catch (err) {
|
||||
if (!(err instanceof NeedsMigration)) throw err;
|
||||
console.error(err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
takeLock(DATA, PORT);
|
||||
const startMs = Math.round(performance.now() - started);
|
||||
|
||||
// ---- each library's link discovery, notices and routes (server/bundle.ts) ----
|
||||
|
||||
// The embedding model is loaded on first use, in a worker thread shared by every library;
|
||||
// IE_EMBED=off turns it off, and scanning then matches by text alone.
|
||||
const embed = process.env.IE_EMBED === "off" ? null : embedder();
|
||||
const shared: Shared = {
|
||||
llm: () => llm,
|
||||
wiki: wikiClient,
|
||||
embed,
|
||||
reviewCalls: Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS),
|
||||
user: USER,
|
||||
state: () => ({
|
||||
user: USER,
|
||||
llm: llm?.kind ?? "off",
|
||||
model: llm?.model ?? null,
|
||||
wiki: wikiState,
|
||||
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
web: { on: web.on, searches: web.searches, fetches: web.fetches },
|
||||
libraries: libraries.list(),
|
||||
}),
|
||||
};
|
||||
const bundles = new Map<string, Bundle>();
|
||||
for (const [id, store] of libraries.stores) bundles.set(id, new Bundle(store, shared));
|
||||
// Writes are gathered before they go to disk; whatever is waiting goes on the way out.
|
||||
process.on("exit", () => {
|
||||
for (const b of bundles.values()) b.flush();
|
||||
});
|
||||
for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0));
|
||||
|
||||
// ---- http plumbing ----
|
||||
|
||||
/** Largest replica update a sync accepts. */
|
||||
const SYNC_MAX = 256 * 1024 * 1024;
|
||||
function needLLM(): LLM {
|
||||
if (!llm) throw new LLMUnavailable();
|
||||
return llm;
|
||||
}
|
||||
|
||||
/** A server-side write to a branch: saved shortly and announced to every replica. */
|
||||
function wrote(branch: string) {
|
||||
store.saveSoon(branch);
|
||||
announce({ branch, from: "api" });
|
||||
}
|
||||
|
||||
async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
const parts = url.pathname.split("/").slice(2).map(decodeURIComponent); // after /api/
|
||||
const [a, b] = parts;
|
||||
const method = req.method ?? "GET";
|
||||
|
||||
if (a === "state" && method === "GET") {
|
||||
return json(res, 200, {
|
||||
user: USER,
|
||||
llm: llm?.kind ?? "off",
|
||||
model: llm?.model ?? null,
|
||||
library: store.id,
|
||||
branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })),
|
||||
migrated: store.migrated(),
|
||||
wiki: wikiState,
|
||||
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off",
|
||||
web: { on: web.on, searches: web.searches, fetches: web.fetches },
|
||||
linkJob: jobs.current,
|
||||
});
|
||||
// One library: /api/l/<id>/…, everything that reads or writes a library's content.
|
||||
if (a === "l") {
|
||||
const bundle = b ? bundles.get(b) : undefined;
|
||||
if (!bundle) return json(res, 404, { error: `no library ${b ?? ""}` });
|
||||
const rest = parts.slice(2);
|
||||
if (await bundle.handle(req, res, rebased(url, rest), rest)) return;
|
||||
return json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
if (a === "libraries") return librariesApi(req, res, parts.slice(1));
|
||||
|
||||
if (a === "usage" && method === "GET") return json(res, 200, usage.summary());
|
||||
|
||||
if (a === "llm" && method === "POST") {
|
||||
@@ -227,148 +215,56 @@ async function api(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
}
|
||||
}
|
||||
|
||||
if (a === "nodes") return nodeApi(req, res, url, parts.slice(1));
|
||||
if (["events", "branch", "sync", "tree", "ops"].includes(a)) return libraryApi(req, res, url, a, b);
|
||||
if (await handleWiki(req, res, url)) return;
|
||||
if (url.pathname.startsWith("/api/links/")) nodeIndex.activate();
|
||||
if (await handleLinks(req, res, url)) return;
|
||||
|
||||
// Without a library named, the first one: so `curl /api/tree` still reads a library.
|
||||
const first = bundles.get(libraries.first().id)!;
|
||||
if (await first.handle(req, res, url, parts)) return;
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
/** The library as a whole: what replicas use, and the op API. */
|
||||
async function libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) {
|
||||
const method = req.method ?? "GET";
|
||||
const name = b || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
|
||||
if (action === "events" && method === "GET") {
|
||||
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
||||
res.write(": connected\n\n");
|
||||
listeners.add(res);
|
||||
req.on("close", () => listeners.delete(res));
|
||||
return;
|
||||
}
|
||||
|
||||
// A replica fetches a branch whole.
|
||||
if (action === "branch" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id });
|
||||
return res.end(doc.snapshotBytes());
|
||||
}
|
||||
|
||||
// A replica pushes what it has and gets back what it lacks. Request header x-vv is the
|
||||
// replica's version; the response carries the server's. A replica must name the library it
|
||||
// belongs to: bytes from another library (an old tab, a browser that outlived its data
|
||||
// directory) would add a second root to this one. A beacon cannot send headers, so it names
|
||||
// the library in the query.
|
||||
if (action === "sync" && method === "POST") {
|
||||
if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) {
|
||||
return json(res, 409, { error: "This page belongs to a different library than the server has now. Reload the page.", library: store.id });
|
||||
}
|
||||
const bytes = await readBody(req, SYNC_MAX);
|
||||
let doc = store.branches.get(name);
|
||||
const before = doc ? vvHeader(doc) : "";
|
||||
if (!doc) {
|
||||
if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
doc = Doc.load(bytes, "server");
|
||||
if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" });
|
||||
store.addBranch(name, doc);
|
||||
} else if (bytes.length) {
|
||||
doc.loro.import(bytes);
|
||||
doc.touch();
|
||||
}
|
||||
if (vvHeader(doc) !== before) {
|
||||
store.saveSoon(name);
|
||||
announce({ branch: name, from: String(req.headers["x-client"] ?? "") });
|
||||
}
|
||||
const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map();
|
||||
const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) });
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) });
|
||||
return res.end(update);
|
||||
}
|
||||
|
||||
// For outside agents: read the library as JSON…
|
||||
if (action === "tree" && method === "GET") {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
return json(res, 200, { ...doc.snap(), conflicts: doc.conflicts(), history: history(doc).slice(0, 50) });
|
||||
}
|
||||
|
||||
// …and write to it with the same ops everyone else uses. Node ids are the library's, so one
|
||||
// batch can work anywhere in it (moving a node from one place to another is a move).
|
||||
if (action === "ops" && method === "POST") return opsApi(req, res, name);
|
||||
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
|
||||
async function opsApi(req: IncomingMessage, res: ServerResponse, name: string) {
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req);
|
||||
if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" });
|
||||
const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api";
|
||||
try {
|
||||
return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" })));
|
||||
} catch (err) {
|
||||
if (err instanceof OpError) return json(res, 422, { error: err.message });
|
||||
throw err;
|
||||
} finally {
|
||||
wrote(name);
|
||||
}
|
||||
/** The URL a library's routes see: /api/<rest>, its query kept. */
|
||||
function rebased(url: URL, rest: string[]): URL {
|
||||
const out = new URL(url);
|
||||
out.pathname = `/api/${rest.map(encodeURIComponent).join("/")}`;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One node and everything under it, by its id: the subtree as JSON with its conflicts, the text
|
||||
* format as a download, or a file in the text format imported under it. An import is an ordinary
|
||||
* commit on main; the browser makes the same commits in its own replica.
|
||||
* The libraries:
|
||||
* GET /api/libraries → { libraries: [{ id, title, created, nodes, branches }] }, in order
|
||||
* POST /api/libraries { title } → 201 { library }: a new library, its root alone, at the end
|
||||
* PATCH /api/libraries/<id> { title } → { library }: renamed (a commit on its root's title)
|
||||
* DELETE /api/libraries/<id> → { deleted, movedTo }: moved aside whole; never the last one
|
||||
*/
|
||||
async function nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) {
|
||||
async function librariesApi(req: IncomingMessage, res: ServerResponse, parts: string[]) {
|
||||
const method = req.method ?? "GET";
|
||||
const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined];
|
||||
const name = branch || "main";
|
||||
if (!validBranch(name)) return json(res, 400, { error: "not a branch name" });
|
||||
const doc = store.branches.get(name);
|
||||
if (!doc) return json(res, 404, { error: `no such branch: ${name}` });
|
||||
const snap = doc.snap();
|
||||
if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` });
|
||||
|
||||
// GET /api/nodes/<id>/tree[/<branch>]: the subtree, as /api/tree returns the library.
|
||||
if (action === "tree" && method === "GET") {
|
||||
const ids = new Set([id, ...descendants(snap, id)]);
|
||||
return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) });
|
||||
const [id] = parts;
|
||||
const info = (lib: string) => libraries.list().find((l) => l.id === lib);
|
||||
if (!id && method === "GET") return json(res, 200, { libraries: libraries.list() });
|
||||
if (!id && method === "POST") {
|
||||
const input = await readJson<{ title?: unknown }>(req);
|
||||
const store = libraries.create(input.title as string);
|
||||
bundles.set(store.id, new Bundle(store, shared));
|
||||
console.log(`libraries: made “${store.title}” (${store.id})`);
|
||||
return json(res, 201, { library: info(store.id) });
|
||||
}
|
||||
// GET /api/nodes/<id>/export[/<branch>]: the text format, as a download.
|
||||
if (action === "export" && method === "GET") {
|
||||
const { text, skipped } = serializeDoc(snap, id);
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/markdown; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`,
|
||||
"x-skipped": JSON.stringify(skipped),
|
||||
});
|
||||
return res.end(text);
|
||||
}
|
||||
// POST /api/nodes/<id>/import?name=file.md, with the file as the body: a new last child of the node (on main).
|
||||
if (action === "import" && !branch && method === "POST") {
|
||||
const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md";
|
||||
let text: string;
|
||||
try {
|
||||
text = (await readBody(req, IMPORT_MAX)).toString("utf8");
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` });
|
||||
throw err;
|
||||
}
|
||||
const main = store.main;
|
||||
if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` });
|
||||
try {
|
||||
const top = importTree(main, text, file, { creator: USER, parent: id });
|
||||
wrote("main");
|
||||
return json(res, 201, { node: top, title: main.snap().nodes[top].title });
|
||||
} catch (err) {
|
||||
if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems });
|
||||
throw err;
|
||||
if (id && parts.length === 1 && (method === "PATCH" || method === "POST")) {
|
||||
const input = await readJson<{ title?: unknown }>(req);
|
||||
const store = libraries.rename(id, input.title as string);
|
||||
bundles.get(id)?.announce({ branch: "main", from: "api" });
|
||||
return json(res, 200, { library: info(store.id) });
|
||||
}
|
||||
if (id && parts.length === 1 && method === "DELETE") {
|
||||
const bundle = bundles.get(id);
|
||||
if (!bundle) return json(res, 404, { error: `no library ${id}` });
|
||||
if (libraries.stores.size <= 1) return json(res, 409, { error: "the last library cannot be deleted" });
|
||||
bundle.close();
|
||||
const movedTo = libraries.remove(id);
|
||||
bundles.delete(id);
|
||||
console.log(`libraries: deleted ${id}; its files are in ${movedTo}`);
|
||||
return json(res, 200, { deleted: id, movedTo });
|
||||
}
|
||||
json(res, 404, { error: "not found" });
|
||||
}
|
||||
@@ -438,9 +334,9 @@ createServer(async (req, res) => {
|
||||
serveStatic(res, path);
|
||||
}
|
||||
}).listen(PORT, "127.0.0.1", () => {
|
||||
const nodes = Object.keys(store.main.snap().nodes).length;
|
||||
console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
|
||||
console.log(`library: ${store.titles().length} top-level sections, ${nodes} nodes, opened in ${startMs} ms`);
|
||||
for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`);
|
||||
console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`);
|
||||
console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`);
|
||||
console.log(
|
||||
`wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`,
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* The libraries on disk. Each is a tree of its own, with its own history, and nothing in one refers
|
||||
* to anything in another: a library is its own Loro database, with its own id, and what is derived
|
||||
* from it (link suggestions, the reviewer's verdicts, vectors) is kept in its own directory.
|
||||
*
|
||||
* <data>/libraries/index.json the libraries, in order: id, title, when made, whether deleted
|
||||
* <data>/libraries/<id>/<branch>.loro the library (library.ts)
|
||||
* <data>/libraries/<id>/links/pending.json link suggestions and the decisions about them (derived)
|
||||
* <data>/libraries/<id>/vectors/nodes.* its sections as vectors (derived)
|
||||
* <data>/libraries/.deleted/<id>-<time>/ a deleted library, moved aside whole
|
||||
*
|
||||
* What holds no library's content is shared: <data>/wiki-cache/ and <data>/models/.
|
||||
*
|
||||
* A library's id is its database's id (`meta.library`, base 36), also its directory's name and the
|
||||
* `/l/<id>` of its addresses. Its name is its root's title; the index keeps a copy so it can be read
|
||||
* without opening the database.
|
||||
*
|
||||
* An empty data directory starts with one library, the first, which gets the seed and the starter
|
||||
* trees; a library made later starts with its root alone. A data directory in the single-library
|
||||
* layout from before (`<data>/library/main.loro`) is not opened: `npm run migrate` brings it over
|
||||
* (migrateLibraries.ts).
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { LIBRARY_ID } from "../src/core/address";
|
||||
import { FormatError } from "../src/core/format";
|
||||
import { Doc, retitleOps } from "../src/core/model";
|
||||
import { writeText } from "../src/core/seed";
|
||||
import { LibraryStore } from "./library";
|
||||
import { HttpError, writeAtomic } from "./util";
|
||||
|
||||
export const LIBRARIES = "libraries";
|
||||
/** What the single-library layout kept at the top of the data directory, all of it moved aside by the migration. */
|
||||
export const OLD_FILES = ["library", "library.json", "links", "vectors"];
|
||||
|
||||
export interface LibraryEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
/** When it was made (ISO). */
|
||||
created: string;
|
||||
/** When it was deleted (ISO), and where it was moved to, relative to the libraries directory. */
|
||||
deleted?: string;
|
||||
movedTo?: string;
|
||||
}
|
||||
|
||||
/** A library as the API lists it. */
|
||||
export interface LibraryInfo {
|
||||
id: string;
|
||||
title: string;
|
||||
created: string;
|
||||
nodes: number;
|
||||
branches: string[];
|
||||
}
|
||||
|
||||
export type Layout =
|
||||
| { kind: "empty" }
|
||||
| { kind: "libraries" }
|
||||
/** The single-library layout: <data>/library/main.loro and what goes with it. */
|
||||
| { kind: "old"; found: string[] }
|
||||
/** A migration that wrote the libraries but did not move the old files aside. */
|
||||
| { kind: "unfinished"; found: string[] }
|
||||
/** Older still: one database per document (<data>/docs/) or a single document (<data>/*.loro). */
|
||||
| { kind: "older"; found: string[] };
|
||||
|
||||
/** What a data directory holds. */
|
||||
export function layout(data: string): Layout {
|
||||
const have = (f: string) => existsSync(join(data, f));
|
||||
const old = OLD_FILES.filter(have);
|
||||
if (have(join(LIBRARIES, "index.json"))) return old.length ? { kind: "unfinished", found: old } : { kind: "libraries" };
|
||||
if (have(join("library", "main.loro"))) return { kind: "old", found: old };
|
||||
const older = [...(have("docs") ? ["docs"] : []), ...(existsSync(data) ? readdirSync(data).filter((f) => f.endsWith(".loro")) : [])];
|
||||
if (older.length) return { kind: "older", found: older };
|
||||
if (old.length) return { kind: "old", found: old };
|
||||
return { kind: "empty" };
|
||||
}
|
||||
|
||||
/** The data directory is not in the libraries layout: the server will not open it. */
|
||||
export class NeedsMigration extends Error {}
|
||||
|
||||
/** One line saying what to do about a data directory the server cannot open. */
|
||||
export function migrationNeeded(data: string, l: Layout): string | null {
|
||||
switch (l.kind) {
|
||||
case "empty":
|
||||
case "libraries":
|
||||
return null;
|
||||
case "old":
|
||||
return `${data} holds a library in the old single-library layout (${l.found.join(", ")}): stop any server using it and run \`npm run migrate\` (\`npm run migrate -- --check\` first for a dry run that writes nothing).`;
|
||||
case "unfinished":
|
||||
return `${data} holds both libraries/ and old files (${l.found.join(", ")}) from a migration that did not finish: run \`npm run migrate\` to move the old files aside.`;
|
||||
case "older":
|
||||
return `${data} holds data from before the single library (${l.found.join(", ")}): open it once with a version from before libraries (commit c4d6856) to bring it into one library, then run \`npm run migrate\`.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A time stamp for directory names: 20261117-013500. */
|
||||
export const stamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-");
|
||||
|
||||
export function readIndex(dir: string): LibraryEntry[] {
|
||||
const raw = JSON.parse(readFileSync(join(dir, "index.json"), "utf8")) as { libraries?: LibraryEntry[] };
|
||||
if (!Array.isArray(raw.libraries)) throw new Error(`${join(dir, "index.json")} lists no libraries`);
|
||||
return raw.libraries.filter((e) => e && typeof e.id === "string" && LIBRARY_ID.test(e.id));
|
||||
}
|
||||
|
||||
export const indexText = (entries: LibraryEntry[]) => JSON.stringify({ version: 1, libraries: entries }, null, 2) + "\n";
|
||||
|
||||
/**
|
||||
* Write each starter file (the text format) as a top of the library, in file name order. A file that
|
||||
* does not parse is logged and skipped; it never stops the server.
|
||||
*/
|
||||
export function importStarters(doc: Doc, dir: string, log: (msg: string) => void = console.log) {
|
||||
if (!existsSync(dir)) return;
|
||||
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
||||
try {
|
||||
const id = writeText(doc, readFileSync(join(dir, f), "utf8"), `library/${f}`);
|
||||
log(`library: imported ${f} as “${doc.snap().nodes[id].title}”`);
|
||||
} catch (err) {
|
||||
log(`library: skipped ${f}:\n ${err instanceof FormatError ? err.problems.join("\n ") : String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Libraries {
|
||||
readonly dir: string;
|
||||
entries: LibraryEntry[] = [];
|
||||
readonly stores = new Map<string, LibraryStore>();
|
||||
|
||||
constructor(
|
||||
readonly data: string,
|
||||
private log: (msg: string) => void = console.log,
|
||||
) {
|
||||
this.dir = join(data, LIBRARIES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open every library. On an empty data directory, make the first library and hand it to `seed`
|
||||
* (the seed and the starter trees). Throws NeedsMigration on any other layout.
|
||||
*/
|
||||
open(seed: (doc: Doc) => void): this {
|
||||
const l = layout(this.data);
|
||||
const why = migrationNeeded(this.data, l);
|
||||
if (why) throw new NeedsMigration(why);
|
||||
if (l.kind === "empty") {
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
const doc = Doc.library("server");
|
||||
seed(doc);
|
||||
this.add(doc);
|
||||
return this;
|
||||
}
|
||||
this.entries = readIndex(this.dir);
|
||||
for (const e of this.entries) {
|
||||
if (e.deleted) continue;
|
||||
const dir = join(this.dir, e.id);
|
||||
if (!existsSync(join(dir, "main.loro"))) {
|
||||
this.log(`libraries: “${e.title}” (${e.id}) is listed but ${dir} holds no main.loro; left out`);
|
||||
continue;
|
||||
}
|
||||
const store = new LibraryStore(dir).open();
|
||||
if (store.id !== e.id) this.log(`libraries: ${dir} holds library ${store.id}, not ${e.id}; opened as ${e.id}`);
|
||||
this.stores.set(e.id, store);
|
||||
}
|
||||
// Every library deleted by hand: start again with an empty one rather than with none.
|
||||
if (!this.stores.size) this.add(Doc.library("server"));
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A library's store, if it exists and is not deleted. */
|
||||
get(id: string): LibraryStore | undefined {
|
||||
return this.stores.get(id);
|
||||
}
|
||||
|
||||
/** The first library in the index that is open. */
|
||||
first(): LibraryStore {
|
||||
for (const e of this.entries) {
|
||||
const s = this.stores.get(e.id);
|
||||
if (s) return s;
|
||||
}
|
||||
throw new Error("no library is open");
|
||||
}
|
||||
|
||||
/** The open libraries, in order, with their names read from their roots. */
|
||||
list(): LibraryInfo[] {
|
||||
const out: LibraryInfo[] = [];
|
||||
let renamed = false;
|
||||
for (const e of this.entries) {
|
||||
const s = this.stores.get(e.id);
|
||||
if (!s) continue;
|
||||
const title = s.title;
|
||||
if (title !== e.title) {
|
||||
e.title = title;
|
||||
renamed = true;
|
||||
}
|
||||
out.push({ id: e.id, title, created: e.created, nodes: Object.keys(s.main.snap().nodes).length, branches: [...s.branches.keys()] });
|
||||
}
|
||||
if (renamed) this.saveIndex();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A new library, with its root alone, at the end of the list. */
|
||||
create(title: string): LibraryStore {
|
||||
const name = cleanTitle(title);
|
||||
return this.add(Doc.library("server", undefined, name));
|
||||
}
|
||||
|
||||
private add(doc: Doc): LibraryStore {
|
||||
const id = doc.libraryId!;
|
||||
if (this.entries.some((e) => e.id === id) || existsSync(join(this.dir, id))) throw new Error(`a library ${id} exists already`);
|
||||
const store = LibraryStore.create(join(this.dir, id), doc);
|
||||
this.stores.set(id, store);
|
||||
this.entries.push({ id, title: store.title, created: new Date().toISOString() });
|
||||
this.saveIndex();
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Rename a library: an ordinary commit on its root's title (on main), so it syncs and versions like any rename. */
|
||||
rename(id: string, title: string): LibraryStore {
|
||||
const store = this.need(id);
|
||||
const name = cleanTitle(title);
|
||||
const doc = store.main;
|
||||
const snap = doc.snap();
|
||||
if (snap.nodes[snap.root].title !== name) {
|
||||
doc.as("server", () => doc.apply(retitleOps(snap, snap.root, name), `Rename the library to “${name}”`, { actor: "human" }));
|
||||
store.save("main");
|
||||
}
|
||||
const e = this.entries.find((x) => x.id === id)!;
|
||||
e.title = name;
|
||||
this.saveIndex();
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a library: its directory is moved, whole and unchanged, to libraries/.deleted/<id>-<time>,
|
||||
* and the index keeps its entry, marked deleted. The last library cannot be deleted.
|
||||
*/
|
||||
remove(id: string): string {
|
||||
const store = this.need(id);
|
||||
if (this.stores.size <= 1) throw new HttpError(409, "the last library cannot be deleted");
|
||||
store.close();
|
||||
const rel = join(".deleted", `${id}-${stamp()}`);
|
||||
mkdirSync(join(this.dir, ".deleted"), { recursive: true });
|
||||
renameSync(store.dir, join(this.dir, rel));
|
||||
this.stores.delete(id);
|
||||
const e = this.entries.find((x) => x.id === id)!;
|
||||
e.deleted = new Date().toISOString();
|
||||
e.movedTo = rel;
|
||||
this.saveIndex();
|
||||
return join(this.dir, rel);
|
||||
}
|
||||
|
||||
private need(id: string): LibraryStore {
|
||||
const store = this.stores.get(id);
|
||||
if (!store) throw new HttpError(404, `no library ${id}`);
|
||||
return store;
|
||||
}
|
||||
|
||||
saveIndex() {
|
||||
writeAtomic(join(this.dir, "index.json"), indexText(this.entries));
|
||||
}
|
||||
|
||||
/** Write every library's waiting changes. */
|
||||
flush() {
|
||||
for (const s of this.stores.values()) s.flush();
|
||||
}
|
||||
}
|
||||
|
||||
function cleanTitle(title: unknown): string {
|
||||
if (typeof title !== "string") throw new HttpError(400, "give the library a title");
|
||||
const t = title.replace(/\s+/g, " ").trim();
|
||||
if (!t) throw new HttpError(400, "give the library a title");
|
||||
if (t.length > 200) throw new HttpError(400, "a library's title is at most 200 characters");
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Whether a path is a directory (for the migration's checks). */
|
||||
export const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
|
||||
+34
-82
@@ -1,22 +1,18 @@
|
||||
/**
|
||||
* The library on disk: one Loro database, a snapshot per branch.
|
||||
* One library on disk: one Loro database, a snapshot per branch, in the library's own directory.
|
||||
*
|
||||
* <data>/library/<branch>.loro the library on that branch
|
||||
* <data>/library/migrated.json what was brought over from the per-document layout, if anything was
|
||||
* <data>/library.json starter files already imported (by file name), so a deleted one stays deleted
|
||||
* <data>/libraries/<id>/<branch>.loro the library on that branch
|
||||
*
|
||||
* Branch names are percent-encoded into file names, so no request can name a file outside it.
|
||||
* Writes are gathered for a moment before they go to disk: with the whole library in one file, a
|
||||
* save per keystroke would rewrite the whole library each time. Replicas keep what has not been
|
||||
* saved and send it again, so a crash loses nothing that a browser still holds.
|
||||
*
|
||||
* The libraries themselves, their index and what is derived from each, are in libraries.ts.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { FormatError } from "../src/core/format";
|
||||
import { Doc, tops } from "../src/core/model";
|
||||
import { writeText } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
import { SEED_KEY, migrate } from "./migrate";
|
||||
import { writeAtomic } from "./util";
|
||||
|
||||
export const validBranch = (b: string) => b.length > 0 && b.length <= 100 && !/[\u0000-\u001f]/.test(b);
|
||||
@@ -26,27 +22,31 @@ const SAVE_DELAY = 250;
|
||||
|
||||
export class LibraryStore {
|
||||
readonly branches = new Map<string, Doc>();
|
||||
readonly dir: string;
|
||||
private timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
/** Set once the library has been moved aside: nothing more is written. */
|
||||
closed = false;
|
||||
|
||||
constructor(readonly data: string, private log: (msg: string) => void = console.log) {
|
||||
this.dir = join(data, "library");
|
||||
}
|
||||
constructor(readonly dir: string) {}
|
||||
|
||||
/** Migrate an older layout if there is one and no library yet, then load every branch. */
|
||||
/** Load every branch. A directory without main is not a library. */
|
||||
open(): this {
|
||||
if (!existsSync(this.dir)) migrate(this.data, this.log);
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
for (const f of readdirSync(this.dir)) {
|
||||
if (f.endsWith(".loro")) this.branches.set(decodeURIComponent(f.slice(0, -5)), Doc.load(readFileSync(join(this.dir, f)), "server"));
|
||||
}
|
||||
if (!this.branches.has("main")) {
|
||||
this.branches.set("main", Doc.library("server"));
|
||||
this.save("main");
|
||||
}
|
||||
if (!this.branches.has("main")) throw new Error(`${this.dir} has no main.loro`);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** A new library in a new directory, written at once. */
|
||||
static create(dir: string, doc: Doc): LibraryStore {
|
||||
if (existsSync(join(dir, "main.loro"))) throw new Error(`${dir} already holds a library`);
|
||||
const store = new LibraryStore(dir);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
store.branches.set("main", doc);
|
||||
store.save("main");
|
||||
return store;
|
||||
}
|
||||
|
||||
get main(): Doc {
|
||||
return this.branches.get("main")!;
|
||||
}
|
||||
@@ -55,21 +55,18 @@ export class LibraryStore {
|
||||
return this.main.libraryId ?? "";
|
||||
}
|
||||
|
||||
/** The library's name: its root's title. */
|
||||
get title(): string {
|
||||
const snap = this.main.snap();
|
||||
return snap.nodes[snap.root].title;
|
||||
}
|
||||
|
||||
/** The titles of the root's children on main, in order. */
|
||||
titles(): string[] {
|
||||
const snap = this.main.snap();
|
||||
return tops(snap).map((id) => snap.nodes[id].title);
|
||||
}
|
||||
|
||||
/** What the migration recorded, for browsers that still hold replicas of the old documents. */
|
||||
migrated(): unknown {
|
||||
try {
|
||||
return JSON.parse(readFileSync(join(this.dir, "migrated.json"), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- writing ----
|
||||
|
||||
/** Write a branch to disk now. */
|
||||
@@ -77,13 +74,13 @@ export class LibraryStore {
|
||||
clearTimeout(this.timers.get(name));
|
||||
this.timers.delete(name);
|
||||
const doc = this.branches.get(name);
|
||||
if (!doc) return;
|
||||
if (!doc || this.closed) return;
|
||||
writeAtomic(join(this.dir, `${encodeURIComponent(name)}.loro`), doc.snapshotBytes());
|
||||
}
|
||||
|
||||
/** Write a branch to disk shortly, with whatever else arrives meanwhile. */
|
||||
saveSoon(name: string) {
|
||||
if (this.timers.has(name)) return;
|
||||
if (this.timers.has(name) || this.closed) return;
|
||||
this.timers.set(name, setTimeout(() => this.save(name), SAVE_DELAY));
|
||||
}
|
||||
|
||||
@@ -92,60 +89,15 @@ export class LibraryStore {
|
||||
for (const name of [...this.timers.keys()]) this.save(name);
|
||||
}
|
||||
|
||||
/** Write what is waiting, then write nothing more (the directory is about to be moved aside). */
|
||||
close() {
|
||||
this.flush();
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
/** A branch pushed by a replica that the server has not seen yet. */
|
||||
addBranch(name: string, doc: Doc) {
|
||||
this.branches.set(name, doc);
|
||||
this.save(name);
|
||||
}
|
||||
|
||||
// ---- starter files ----
|
||||
|
||||
private libraryFile() {
|
||||
return join(this.data, "library.json");
|
||||
}
|
||||
imported(): string[] {
|
||||
try {
|
||||
return JSON.parse(readFileSync(this.libraryFile(), "utf8")).imported ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
markImported(id: string) {
|
||||
const ids = this.imported();
|
||||
if (!ids.includes(id)) writeFileSync(this.libraryFile(), JSON.stringify({ imported: [...ids, id] }, null, 2) + "\n");
|
||||
}
|
||||
|
||||
/** The first tree, written once. Like a starter file, it is not written again after being deleted. */
|
||||
seedFirst(write: (doc: Doc) => void) {
|
||||
if (this.imported().includes(SEED_KEY)) return;
|
||||
write(this.main);
|
||||
this.save("main");
|
||||
this.markImported(SEED_KEY);
|
||||
this.log("seeded the first tree from src/seed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Import each starter file that has never been imported (by its file name), as a child of the
|
||||
* root at its end. A file that does not parse is logged and skipped (and tried again next start);
|
||||
* it never stops the server.
|
||||
*/
|
||||
importLibrary(dir: string) {
|
||||
if (!existsSync(dir)) return;
|
||||
const done = new Set(this.imported());
|
||||
let changed = false;
|
||||
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
||||
const key = slugify(f.slice(0, -3));
|
||||
if (done.has(key)) continue;
|
||||
try {
|
||||
const text = readFileSync(join(dir, f), "utf8");
|
||||
const id = writeText(this.main, text, `library/${f}`);
|
||||
this.markImported(key);
|
||||
changed = true;
|
||||
this.log(`library: imported ${f} as “${this.main.snap().nodes[id].title}”`);
|
||||
} catch (err) {
|
||||
this.log(`library: skipped ${f}:\n ${err instanceof FormatError ? err.problems.join("\n ") : String(err)}`);
|
||||
}
|
||||
}
|
||||
if (changed) this.save("main");
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,14 @@ export class NodeIndex {
|
||||
}
|
||||
private active = false;
|
||||
|
||||
/** Stop keeping the index and write nothing more: the library is being moved aside. */
|
||||
close() {
|
||||
this.active = false;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.vectors.detach();
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (this.timer || !this.delay || !this.active) return;
|
||||
this.timer = setTimeout(() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Suggestions and what was decided about them. Derived data, so they live on the server under
|
||||
* <IE_DATA>/links/pending.json and never in the library.
|
||||
* <IE_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library.
|
||||
*
|
||||
* A scan replaces what was pending for its node, but what was decided is kept: the model
|
||||
* reviewer's verdict (link or not, and why), a person's decision, and when an approved link was
|
||||
@@ -176,6 +176,14 @@ export class PendingStore {
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
/** Write what is waiting, then nothing more (the library is being moved aside). */
|
||||
close() {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.flush();
|
||||
this.file = null;
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (!this.file) return;
|
||||
try {
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Whether a server has a data directory open. A server writes <data>/server.lock (its pid) while
|
||||
* it runs and removes it on the way out; a lock whose process is gone is stale and ignored.
|
||||
*
|
||||
* Servers from before the lock wrote none. For them (the migration must not run under one), on a
|
||||
* system with /proc, every process running `server/index.ts` is looked at: its checkout is found
|
||||
* from its command line and working directory, and it counts if that checkout's default data
|
||||
* directory (`<checkout>/.data`) is this one. Only command lines and working directories are read,
|
||||
* never a process's environment, so a server started with IE_DATA pointing elsewhere is still
|
||||
* reported if it runs from the checkout whose `.data` this is.
|
||||
*/
|
||||
import { existsSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { writeAtomic } from "./util";
|
||||
|
||||
export const LOCK = "server.lock";
|
||||
|
||||
interface Lock {
|
||||
pid: number;
|
||||
port?: number;
|
||||
started?: string;
|
||||
}
|
||||
|
||||
const alive = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return (err as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
const real = (p: string) => {
|
||||
try {
|
||||
return realpathSync(p);
|
||||
} catch {
|
||||
return resolve(p);
|
||||
}
|
||||
};
|
||||
|
||||
/** The process holding the lock on this data directory, if it is still running (and is not this one). */
|
||||
export function lockHolder(data: string): Lock | null {
|
||||
const file = join(data, LOCK);
|
||||
if (!existsSync(file)) return null;
|
||||
try {
|
||||
const lock = JSON.parse(readFileSync(file, "utf8")) as Lock;
|
||||
if (!Number.isInteger(lock.pid) || lock.pid === process.pid || !alive(lock.pid)) return null;
|
||||
// A pid can be reused: where /proc says what runs under it, it must be a server.
|
||||
const cmd = cmdline(lock.pid);
|
||||
if (cmd && !cmd.some((a) => a.endsWith("server/index.ts"))) return null;
|
||||
return lock;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function cmdline(pid: number): string[] | null {
|
||||
try {
|
||||
return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\u0000").filter(Boolean);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Servers without a lock: processes running server/index.ts from the checkout whose `.data` this is. */
|
||||
export function unlockedServers(data: string): number[] {
|
||||
if (!existsSync("/proc")) return [];
|
||||
const want = real(data);
|
||||
const out: number[] = [];
|
||||
for (const name of readdirSync("/proc")) {
|
||||
if (!/^\d+$/.test(name)) continue;
|
||||
const pid = Number(name);
|
||||
if (pid === process.pid) continue;
|
||||
const args = cmdline(pid);
|
||||
const script = args?.find((a) => a.endsWith("server/index.ts"));
|
||||
if (!script) continue;
|
||||
try {
|
||||
const cwd = readlinkSync(`/proc/${pid}/cwd`);
|
||||
const checkout = dirname(dirname(resolve(cwd, script)));
|
||||
if (real(join(checkout, ".data")) === want) out.push(pid);
|
||||
} catch {
|
||||
/* gone, or not ours to look at */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Why the data directory is not free, or null if no server has it open. */
|
||||
export function busy(data: string): string | null {
|
||||
const lock = lockHolder(data);
|
||||
if (lock) return `a server (pid ${lock.pid}${lock.port ? `, port ${lock.port}` : ""}) has ${data} open`;
|
||||
const pids = unlockedServers(data);
|
||||
if (pids.length) return `a server (pid ${pids.join(", ")}) is running from the checkout whose data directory is ${data}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Take the lock for this process; it is let go on exit. */
|
||||
export function takeLock(data: string, port: number) {
|
||||
const file = join(data, LOCK);
|
||||
writeAtomic(file, JSON.stringify({ pid: process.pid, port, started: new Date().toISOString() }) + "\n");
|
||||
process.on("exit", () => {
|
||||
try {
|
||||
const lock = JSON.parse(readFileSync(file, "utf8")) as Lock;
|
||||
if (lock.pid === process.pid) rmSync(file, { force: true });
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* From one Loro database per document to one library, once, on the first start that finds the
|
||||
* older layout and no library:
|
||||
*
|
||||
* <data>/docs/<id>/<branch>.loro the per-document layout
|
||||
* <data>/<branch>.loro the single-document layout before it (the first document)
|
||||
*
|
||||
* Every document's main branch is imported into one new Loro database, histories and all: each
|
||||
* document's ops keep their ids, so its notes stay anchored, its open conflicts stay open, and
|
||||
* every commit it ever made can still be checked out and verified (a checkout from before the
|
||||
* library shows that document alone, as it stood). One commit then makes the Library root and
|
||||
* moves each document's root under it, in order. A document that shares
|
||||
* history with one already imported (a duplicate, which began as a byte copy) cannot be imported
|
||||
* beside it without merging into it, so it is copied in as content instead.
|
||||
*
|
||||
* The library is written to a temporary directory and renamed into place; only then is the old
|
||||
* `docs` directory renamed to `docs.migrated-<time>` (and flat files moved into
|
||||
* `flat.migrated-<time>`). Nothing in them is changed or deleted.
|
||||
* Branches other than main are not carried over; the log and migrated.json list them.
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { LoroDoc } from "loro-crdt";
|
||||
import { Doc, LIBRARY_TITLE, initRoot, randomPeer, type NodeId } from "../src/core/model";
|
||||
import { encodeVV } from "../src/core/repo";
|
||||
|
||||
/** The first document's old id (its directory, and its entry in library.json). */
|
||||
export const SEED_KEY = "infinite-expand";
|
||||
const SEED_SLUG = SEED_KEY;
|
||||
/** An old document id: also a directory name, so nothing that could leave its directory. */
|
||||
const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
|
||||
|
||||
interface Source {
|
||||
id: string;
|
||||
dir: string | null;
|
||||
main: Uint8Array;
|
||||
/** Every branch's version, for browsers checking what they hold against what was migrated. */
|
||||
versions: Record<string, string>;
|
||||
uid: string | null;
|
||||
changed: number;
|
||||
}
|
||||
|
||||
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-");
|
||||
|
||||
function sources(data: string, log: (m: string) => void): Source[] {
|
||||
const out: Source[] = [];
|
||||
const read = (id: string, dir: string, files: string[]) => {
|
||||
const versions: Record<string, string> = {};
|
||||
let main: Uint8Array | null = null;
|
||||
for (const f of files) {
|
||||
const bytes = readFileSync(join(dir, f));
|
||||
const name = decodeURIComponent(f.slice(0, -5));
|
||||
if (name === "main") main = bytes;
|
||||
try {
|
||||
versions[name] = encodeVV(Doc.load(bytes, "migration").loro.version().toJSON());
|
||||
} catch (err) {
|
||||
log(`migration: ${join(dir, f)} could not be read (${err instanceof Error ? err.message : err}); left as it is`);
|
||||
}
|
||||
}
|
||||
if (!main) return log(`migration: ${dir} has no main.loro; left as it is`);
|
||||
let uid: string | null = null;
|
||||
try {
|
||||
uid = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")).uid ?? null;
|
||||
} catch {
|
||||
/* the single-document layout had no meta.json */
|
||||
}
|
||||
out.push({ id, dir, main, versions, uid, changed: statSync(join(dir, "main.loro")).mtimeMs });
|
||||
};
|
||||
const docs = join(data, "docs");
|
||||
if (existsSync(docs)) {
|
||||
for (const id of readdirSync(docs).sort()) {
|
||||
const dir = join(docs, id);
|
||||
if (!SLUG.test(id) || !statSync(dir).isDirectory()) continue;
|
||||
read(id, dir, readdirSync(dir).filter((f) => f.endsWith(".loro")));
|
||||
}
|
||||
}
|
||||
const flat = readdirSync(data).filter((f) => f.endsWith(".loro"));
|
||||
if (flat.length) {
|
||||
if (out.some((s) => s.id === SEED_SLUG)) log(`migration: ${flat.join(", ")} in ${data} left aside: docs/${SEED_SLUG} is the newer copy`);
|
||||
else read(SEED_SLUG, data, flat);
|
||||
}
|
||||
// The first document first, then the order the documents menu showed: most recently changed first.
|
||||
return out.sort((a, b) => (a.id === SEED_SLUG ? -1 : b.id === SEED_SLUG ? 1 : b.changed - a.changed));
|
||||
}
|
||||
|
||||
/** Build the library from the older layout. Returns false if there was nothing to migrate. */
|
||||
export function migrate(data: string, log: (m: string) => void): boolean {
|
||||
if (!existsSync(data)) return false;
|
||||
const found = sources(data, log);
|
||||
if (!found.length) return false;
|
||||
|
||||
const lib = new Doc(new LoroDoc(), "migration");
|
||||
lib.loro.setPeerId(randomPeer());
|
||||
const plan: { src: Source; snap: ReturnType<Doc["snap"]>; root: NodeId; kept: boolean; commits: number; conflicts: number }[] = [];
|
||||
for (const src of found) {
|
||||
const old = Doc.load(src.main, "migration");
|
||||
const snap = old.snap();
|
||||
const ours = lib.loro.version().toJSON();
|
||||
const shared = [...old.loro.version().toJSON().keys()].some((peer) => ours.has(peer));
|
||||
if (!shared) lib.loro.import(src.main);
|
||||
const commits = [...old.loro.getAllChanges().values()].reduce((n, cs) => n + cs.length, 0);
|
||||
plan.push({ src, snap, root: snap.root, kept: !shared, commits, conflicts: old.conflicts().filter((c) => c.status === "open").length });
|
||||
}
|
||||
|
||||
const message = `Gather ${plan.length} document${plan.length > 1 ? "s" : ""} into the library`;
|
||||
lib.begin(message, "human", "migrate");
|
||||
const tree = lib.tree;
|
||||
const root = tree.createNode();
|
||||
initRoot(root, LIBRARY_TITLE, "", "human");
|
||||
root.data.set("library", true);
|
||||
lib.loro.getMap("meta").set("library", randomPeer().toString(36));
|
||||
for (const p of plan) {
|
||||
if (p.kept) tree.move(p.root, root.id, root.children()?.length ?? 0);
|
||||
else lib.graft(p.snap, p.snap.root, root.id);
|
||||
}
|
||||
lib.reread();
|
||||
lib.commit(message, "human", "migrate");
|
||||
|
||||
// Every document must have come across whole before anything is written. A copied one can
|
||||
// differ only by anchors that were already lost (an orphaned note's empty span is not copied).
|
||||
const snap = lib.snap();
|
||||
for (const [i, p] of plan.entries()) {
|
||||
const id = snap.nodes[root.id].children[i];
|
||||
const same = !!id && lib.shape(snap, id) === lib.shape(p.snap, p.snap.root);
|
||||
if (!same && (p.kept || !id)) throw new Error(`migration: “${p.src.id}” did not come across intact; nothing was changed on disk`);
|
||||
if (!same) log(`migration: “${p.src.id}” was copied without the empty spans of its orphaned notes`);
|
||||
}
|
||||
|
||||
const when = stamp();
|
||||
const moved = existsSync(join(data, "docs")) ? `docs.migrated-${when}` : null;
|
||||
const flatFiles = readdirSync(data).filter((f) => f.endsWith(".loro"));
|
||||
const flatMoved = flatFiles.length ? `flat.migrated-${when}` : null;
|
||||
const record = {
|
||||
at: new Date().toISOString(),
|
||||
from: [moved, flatMoved].filter(Boolean),
|
||||
docs: plan.map((p) => ({
|
||||
slug: p.src.id,
|
||||
uid: p.src.uid,
|
||||
title: p.snap.nodes[p.snap.root].title,
|
||||
nodes: Object.keys(p.snap.nodes).length,
|
||||
history: p.kept ? "kept" : "copied",
|
||||
commits: p.commits,
|
||||
openConflicts: p.kept ? p.conflicts : 0,
|
||||
versions: p.src.versions,
|
||||
})),
|
||||
branchesNotCarried: plan.flatMap((p) => Object.keys(p.src.versions).filter((b) => b !== "main").map((b) => ({ doc: p.src.id, branch: b }))),
|
||||
};
|
||||
|
||||
const tmp = join(data, `library.tmp-${stamp()}`);
|
||||
mkdirSync(tmp, { recursive: true });
|
||||
writeFileSync(join(tmp, "main.loro"), lib.snapshotBytes());
|
||||
writeFileSync(join(tmp, "migrated.json"), JSON.stringify(record, null, 2) + "\n");
|
||||
renameSync(tmp, join(data, "library"));
|
||||
|
||||
// Only now that the library is in place does the old layout move aside, renamed, untouched.
|
||||
if (moved) renameSync(join(data, "docs"), join(data, moved));
|
||||
if (flatMoved) {
|
||||
mkdirSync(join(data, flatMoved));
|
||||
for (const f of flatFiles) renameSync(join(data, f), join(data, flatMoved, f));
|
||||
}
|
||||
const kept = [moved, flatMoved].filter(Boolean).map((d) => join(data, d!)).join(" and ");
|
||||
|
||||
log(`migration: built ${join(data, "library", "main.loro")} from ${plan.length} document${plan.length > 1 ? "s" : ""}:`);
|
||||
for (const d of record.docs) {
|
||||
log(
|
||||
` ${d.slug} “${d.title}” ${d.nodes} nodes, ${d.history === "kept" ? `history kept (${d.commits} changes)` : "copied as content (it shares history with another document, so its history is not carried)"}${d.openConflicts ? `, ${d.openConflicts} open conflict${d.openConflicts > 1 ? "s" : ""}` : ""}`,
|
||||
);
|
||||
}
|
||||
if (record.branchesNotCarried.length) {
|
||||
log(`migration: branches other than main were not carried over (they are still in ${kept}):`);
|
||||
for (const b of record.branchesNotCarried) log(` ${b.doc}: ${b.branch}`);
|
||||
}
|
||||
log(`migration: the old files are in ${kept}, unchanged.`);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Where the page's requests about its library go. The page holds one library, named by its
|
||||
* address (`/l/<id>`); everything that reads or writes a library's content asks under
|
||||
* `/api/l/<id>/`, and what holds no library's content (the model, Wikipedia, usage) under `/api/`.
|
||||
* Switching library is a page load (`/l/<other id>`), so the prefix is set once, at boot.
|
||||
*/
|
||||
let library: string | null = null;
|
||||
|
||||
/** Set the library this page holds. */
|
||||
export function setLibrary(id: string) {
|
||||
library = id;
|
||||
}
|
||||
|
||||
/** The library this page holds, once boot has chosen it. */
|
||||
export const currentLibrary = () => library;
|
||||
|
||||
/**
|
||||
* A path under this library's API: libApi("/links/jobs") → /api/l/<id>/links/jobs. Before a library
|
||||
* is chosen (only in the tests: the page chooses one before anything asks) the unprefixed route,
|
||||
* which the server answers for its first library.
|
||||
*/
|
||||
export function libApi(path: string): string {
|
||||
return library ? `/api/l/${encodeURIComponent(library)}${path}` : `/api${path}`;
|
||||
}
|
||||
|
||||
/** A library as /api/libraries lists it. */
|
||||
export interface LibraryInfo {
|
||||
id: string;
|
||||
title: string;
|
||||
created: string;
|
||||
nodes: number;
|
||||
branches: string[];
|
||||
}
|
||||
|
||||
async function call<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(path, init);
|
||||
let body: Record<string, unknown> = {};
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
if (!res.ok) throw new Error(String(body.error ?? `${res.status} ${res.statusText}`));
|
||||
return body as T;
|
||||
}
|
||||
const send = (method: string, body?: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
|
||||
/** The libraries, in order. */
|
||||
export const listLibraries = () => call<{ libraries: LibraryInfo[] }>("/api/libraries").then((r) => r.libraries);
|
||||
/** A new library (its root alone), at the end of the list. */
|
||||
export const createLibrary = (title: string) => call<{ library: LibraryInfo }>("/api/libraries", send("POST", { title })).then((r) => r.library);
|
||||
/** Rename a library (a commit on its root's title). */
|
||||
export const renameLibrary = (id: string, title: string) => call<{ library: LibraryInfo }>(`/api/libraries/${encodeURIComponent(id)}`, send("PATCH", { title })).then((r) => r.library);
|
||||
/** Delete a library: the server moves it aside whole. Refused for the last one. */
|
||||
export const deleteLibrary = (id: string) => call<{ deleted: string; movedTo: string }>(`/api/libraries/${encodeURIComponent(id)}`, send("DELETE"));
|
||||
+2
-1
@@ -88,6 +88,7 @@ export const HELP: [string, [string, string][]][] = [
|
||||
"The library",
|
||||
[
|
||||
["", "everything is a node of one tree, whose root is the library: the first page. Any node can be moved under any other (M, > <), copied (/duplicate), saved to a file (/export) or given a file's tree under it (/import); each acts on the node you are on, with everything under it. The ⋯ menu of any node offers the same"],
|
||||
["", "there can be several libraries, each a tree of its own with its own address (/l/…): nothing links, moves or is found from one to another (export, then import, carries a tree across). :/library lists them, :/library name opens one, :/library new name makes one"],
|
||||
],
|
||||
],
|
||||
[
|
||||
@@ -121,7 +122,7 @@ export const HELP: [string, [string, string][]][] = [
|
||||
["/duplicate title", "save the node you are on, with everything under it, as a copy just after it (titled \"… (copy)\" unless given one); the copy has the focus"],
|
||||
["/export", "save the node you are on, with everything under it, to a .md file (on the library root, the whole library)"],
|
||||
["/import", "read a .md file into the node you are on, as its last child (on the library root, a new top-level node)"],
|
||||
["/recover", "save edits this browser made before the library existed, and never sent, as .md files"],
|
||||
["/library [name]", "list the libraries; with a name, open that library (a page load); /library new name makes one and opens it. Libraries are separate trees: nothing links, moves or is found across them"],
|
||||
["/link target", "link the selection (or the node): w:Title, /Top title/Section (titles from the library root), an address, or a Wikipedia title"],
|
||||
["/unlink", "remove the link on the selection (for good: its words are declined; a note that also links keeps its text), or the node's own target"],
|
||||
["/autolink review|suggest|on|off", "after an edit: the model reviews what was found and links what it approves (review, the default with a model; u undoes, S lists every decision), suggest everything for you to decide (suggest; what review does without a model, or when the model fails or its limit is reached), link the scanner's sure ones unreviewed (on), or look for nothing (off)"],
|
||||
|
||||
+4
-3
@@ -17,6 +17,7 @@ import { applyLinks, nodeRef, phraseKey } from "../core/links";
|
||||
import type { Mark } from "../core/marks";
|
||||
import { ancestors, isLibraryRoot, isLink, label, notesOf, topOf, tops, type Doc, type NodeId, type Op, type Snap } from "../core/model";
|
||||
import { describeTarget, sameTarget, type Ref } from "../core/ref";
|
||||
import { libApi } from "./api";
|
||||
import { clip, overlaps, type Range } from "../core/text";
|
||||
import type { Nearby } from "../llm/prompts";
|
||||
|
||||
@@ -76,7 +77,7 @@ interface Task {
|
||||
const idle = (fn: () => void) => (typeof requestIdleCallback === "function" ? requestIdleCallback(fn, { timeout: 1000 }) : setTimeout(fn, 50));
|
||||
|
||||
const post = (path: string, body: unknown, signal?: AbortSignal) =>
|
||||
fetch(`/api/links/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });
|
||||
fetch(libApi(`/links/${path}`), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });
|
||||
|
||||
/** Turned down: declined by a person, or rejected by the reviewer and not linked by a person since. */
|
||||
const turnedDown = (snap: Snap, s: Sugg) => !!snap.nodes[s.node]?.nolink?.includes(s.key) || s.decided?.link === false || (s.review?.link === false && !s.decided?.link);
|
||||
@@ -356,7 +357,7 @@ export class Linker {
|
||||
if (!force && this.fetched.has(id)) return { found: [], apply: [] };
|
||||
this.fetched.add(id);
|
||||
try {
|
||||
const res = await fetch(`/api/links/pending?node=${encodeURIComponent(id)}&subtree=1&all=1${claim ? "&claim=1" : ""}`);
|
||||
const res = await fetch(libApi(`/links/pending?node=${encodeURIComponent(id)}&subtree=1&all=1${claim ? "&claim=1" : ""}`));
|
||||
if (!res.ok) return { found: [], apply: [] };
|
||||
const r = (await res.json()) as { suggestions: Sugg[]; apply?: Sugg[] };
|
||||
const by = new Map<NodeId, Sugg[]>();
|
||||
@@ -502,7 +503,7 @@ export class Linker {
|
||||
}
|
||||
|
||||
async cancelJob(): Promise<boolean> {
|
||||
const res = await fetch("/api/links/jobs", { method: "DELETE" });
|
||||
const res = await fetch(libApi("/links/jobs"), { method: "DELETE" });
|
||||
const r = await res.json().catch(() => ({}));
|
||||
if (r.job) this.job = r.job;
|
||||
return !!r.cancelled;
|
||||
|
||||
+5
-4
@@ -5,6 +5,7 @@
|
||||
import { VersionVector } from "loro-crdt";
|
||||
import { Doc } from "../core/model";
|
||||
import { Repo, decodeVV, encodeVV, mergeUpdate, vvIncludes, type MergeReport } from "../core/repo";
|
||||
import { libApi } from "./api";
|
||||
import { idbGet, idbSet } from "./idb";
|
||||
|
||||
type VV = Map<`${number}`, number>;
|
||||
@@ -85,7 +86,7 @@ export class Session {
|
||||
}
|
||||
|
||||
private async fetchBranch(name: string): Promise<Doc | null> {
|
||||
const res = await fetch(`/api/branch/${encodeURIComponent(name)}`);
|
||||
const res = await fetch(libApi(`/branch/${encodeURIComponent(name)}`));
|
||||
if (!res.ok) return null;
|
||||
if (res.headers.get("x-library") !== this.library) {
|
||||
this.lost();
|
||||
@@ -131,7 +132,7 @@ export class Session {
|
||||
const known = this.serverVV.get(name);
|
||||
if (known && vvIncludes(known, doc.loro.version().toJSON())) continue;
|
||||
const bytes = known ? doc.loro.export({ mode: "update", from: new VersionVector(known) }) : doc.snapshotBytes();
|
||||
navigator.sendBeacon(`/api/sync/${encodeURIComponent(name)}?library=${encodeURIComponent(this.library)}`, new Blob([bytes as BlobPart], { type: "application/octet-stream" }));
|
||||
navigator.sendBeacon(libApi(`/sync/${encodeURIComponent(name)}?library=${encodeURIComponent(this.library)}`), new Blob([bytes as BlobPart], { type: "application/octet-stream" }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,7 +170,7 @@ export class Session {
|
||||
let ok = false;
|
||||
try {
|
||||
const bytes = !known ? doc.snapshotBytes() : vvIncludes(known, mine) ? new Uint8Array() : doc.loro.export({ mode: "update", from: new VersionVector(known) });
|
||||
const res = await fetch(`/api/sync/${encodeURIComponent(name)}`, {
|
||||
const res = await fetch(libApi(`/sync/${encodeURIComponent(name)}`), {
|
||||
method: "POST",
|
||||
headers: { "x-vv": encodeVV(mine), "x-client": this.clientId, "x-library": this.library, "content-type": "application/octet-stream" },
|
||||
body: bytes as BodyInit,
|
||||
@@ -203,7 +204,7 @@ export class Session {
|
||||
/** Listen for other writers. */
|
||||
connect() {
|
||||
if (this.events || this.foreign) return;
|
||||
const events = new EventSource("/api/events");
|
||||
const events = new EventSource(libApi("/events"));
|
||||
events.onmessage = (e) => {
|
||||
const msg = JSON.parse(e.data) as { branch?: string; from?: string };
|
||||
if (msg.branch && msg.from !== this.clientId) void this.sync(msg.branch);
|
||||
|
||||
+132
-66
@@ -13,10 +13,10 @@ import {
|
||||
staleness, topOf, tops, type NodeId, type Op, type Snap,
|
||||
} from "../core/model";
|
||||
import { FormatError, serializeDoc } from "../core/format";
|
||||
import { address, resolve } from "../core/address";
|
||||
import { address, inLibrary, resolve, splitLibrary } from "../core/address";
|
||||
import { IMPORT_MAX, importTree } from "../core/seed";
|
||||
import {
|
||||
Repo, at, decodeVV, healAnchors, history, reopenConflict, resolveConflict, revertSubtreeTo, revertTo, touched, vvIncludes, type Commit,
|
||||
Repo, at, healAnchors, history, reopenConflict, resolveConflict, revertSubtreeTo, revertTo, touched, type Commit,
|
||||
type MergeReport,
|
||||
} from "../core/repo";
|
||||
import { clip, formFor, plain, rangeAt, sentences, slugify, words, type Form, type Range } from "../core/text";
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
} from "../llm/tasks";
|
||||
import type { LLM } from "../llm/types";
|
||||
import { DEFAULT_LIMITS, wantsResearch } from "../llm/web";
|
||||
import { idbGet, idbKeys, idbSet } from "./idb";
|
||||
import { createLibrary, deleteLibrary, libApi, listLibraries, renameLibrary, setLibrary, type LibraryInfo } from "./api";
|
||||
import { remoteLLM } from "./remote";
|
||||
import { Session } from "./session";
|
||||
import { refreshAfterCalls } from "./usage";
|
||||
@@ -140,19 +140,6 @@ export interface Sample {
|
||||
at?: number;
|
||||
}
|
||||
|
||||
/** A replica of a document from before the library, holding edits the server never received. */
|
||||
interface OldReplica {
|
||||
slug: string;
|
||||
title: string;
|
||||
branch: string;
|
||||
bytes: Uint8Array;
|
||||
}
|
||||
|
||||
/** What the server recorded when it built the library from separate documents. */
|
||||
interface Migrated {
|
||||
docs: { slug: string; uid: string | null; title: string; versions: Record<string, string> }[];
|
||||
}
|
||||
|
||||
// ---- store ----
|
||||
|
||||
const clientId = Math.random().toString(36).slice(2);
|
||||
@@ -289,7 +276,9 @@ class Store {
|
||||
/** Set at a keypress; cleared when the resulting frame has been painted. */
|
||||
t0: { what: string; at: number } | null = null;
|
||||
/** Replicas of pre-library documents whose edits never reached the server. */
|
||||
oldReplicas: OldReplica[] = [];
|
||||
/** The library this page holds (its id, as in its address), and every library the server has, as it last said. */
|
||||
library = "";
|
||||
libraries: LibraryInfo[] = [];
|
||||
|
||||
/** The panes as a forest of forks (forks.ts); its focused branch is `trail`, and `paneAt` is the pane on it that holds the focus: the active pane. */
|
||||
forest: Forest<PaneRef, Back> = { trees: [], at: 0 };
|
||||
@@ -1112,15 +1101,41 @@ class Store {
|
||||
|
||||
async boot() {
|
||||
try {
|
||||
let state: { user: string; llm: LLM["kind"]; model: string | null; library?: string; branches?: { name: string }[]; migrated?: Migrated | null; wiki?: WikiConfig; linkJob?: JobState | null; web?: { on: boolean; searches: number; fetches: number } } | null = null;
|
||||
// The address names the library; an address without one (`/`, or one from before libraries)
|
||||
// is read in the library last used here, if the server still has it, else in the first.
|
||||
const { library: named, part } = splitLibrary(location.pathname);
|
||||
let library = named;
|
||||
if (!library) {
|
||||
let list: LibraryInfo[] | null = null;
|
||||
try {
|
||||
const res = await fetch("/api/state");
|
||||
list = await listLibraries();
|
||||
} catch {
|
||||
/* offline: fall back to what is stored locally */
|
||||
}
|
||||
const last = lsGet<string | null>("ie:library", null);
|
||||
library = list ? ((list.find((l) => l.id === last) ?? list[0])?.id ?? null) : last;
|
||||
if (!library) throw new Error("Could not load a library: the server is not reachable and nothing is stored in this browser.");
|
||||
window.history.replaceState(null, "", inLibrary(library, part));
|
||||
}
|
||||
setLibrary(library);
|
||||
this.library = library;
|
||||
let state: { user: string; llm: LLM["kind"]; model: string | null; library?: string; title?: string; libraries?: LibraryInfo[]; branches?: { name: string }[]; wiki?: WikiConfig; linkJob?: JobState | null; web?: { on: boolean; searches: number; fetches: number } } | null = null;
|
||||
try {
|
||||
const res = await fetch(libApi("/state"));
|
||||
if (res.status === 404) {
|
||||
// Not a library of this server (deleted, or from another data directory): to the first one.
|
||||
if (lsGet("ie:library", null) === library) lsSet("ie:library", null);
|
||||
sessionStorage.setItem("ie:flash", `There is no library ${library} here; this is the first one.`);
|
||||
location.replace("/");
|
||||
return;
|
||||
}
|
||||
if (res.ok) state = await res.json();
|
||||
} catch {
|
||||
/* offline: fall back to what is stored locally */
|
||||
}
|
||||
if (state && !state.library) throw new Error("This page is newer than the server it came from. Restart the server (npm run dev) and reload.");
|
||||
this.online = !!state;
|
||||
this.libraries = state?.libraries ?? [];
|
||||
if (state?.wiki) this.wiki = state.wiki;
|
||||
this.web = state?.web ?? { on: false, searches: 0, fetches: 0 };
|
||||
if (state?.linkJob?.state === "running") this.links.job = state.linkJob;
|
||||
@@ -1132,8 +1147,6 @@ class Store {
|
||||
});
|
||||
this.user = lsGet("ie:user", state?.user ?? "you");
|
||||
if (state) this.llm = refreshAfterCalls(remoteLLM(state.llm, state.model ?? undefined));
|
||||
const library = state?.library ?? lsGet<string | null>("ie:library", null);
|
||||
if (!library) throw new Error("Could not load the library: the server is not reachable and nothing is stored in this browser.");
|
||||
lsSet("ie:library", library);
|
||||
|
||||
this.session = new Session(library, this.user, clientId, {
|
||||
@@ -1153,16 +1166,26 @@ class Store {
|
||||
foreign: () => this.say("The server now holds a different library than this page. Edits here are no longer sent; reload the page."),
|
||||
message: (msg) => {
|
||||
if (msg.linkJob) this.jobUpdate(msg.linkJob as JobState);
|
||||
if (msg.library === "deleted") {
|
||||
this.session.foreign = true;
|
||||
this.session.disconnect();
|
||||
this.say("This library has been deleted (the server moved its files aside). Edits here are no longer sent; go to / for another library.");
|
||||
}
|
||||
},
|
||||
});
|
||||
await this.session.load((state?.branches ?? []).map((b) => b.name), this.online);
|
||||
const branch = lsGet("ie:branch", "main");
|
||||
const branch = lsGet(this.branchKey(), "main");
|
||||
this.repo.current = this.repo.branches.has(branch) ? branch : "main";
|
||||
this.restoreView();
|
||||
this.undoManager();
|
||||
this.navigate(location.pathname, "replace");
|
||||
this.navigate(splitLibrary(location.pathname).part, "replace");
|
||||
this.ready = true;
|
||||
this.prefetchLinks(this.focus.node);
|
||||
const flash = sessionStorage.getItem("ie:flash");
|
||||
if (flash) {
|
||||
sessionStorage.removeItem("ie:flash");
|
||||
this.say(flash);
|
||||
}
|
||||
this.emit();
|
||||
// The first commit hashes the whole library once (later ones only the path to what they
|
||||
// changed); do that while the page is idle rather than on the reader's first edit.
|
||||
@@ -1177,52 +1200,91 @@ class Store {
|
||||
this.session.connect();
|
||||
}
|
||||
// Back and forward move between places in the library.
|
||||
addEventListener("popstate", () => this.navigate(location.pathname, "none"));
|
||||
if (state?.migrated) void this.checkOldReplicas(state.migrated);
|
||||
addEventListener("popstate", () => {
|
||||
const at = splitLibrary(location.pathname);
|
||||
// Another library's address (one this page did not push): that library, by a page load.
|
||||
if (at.library && at.library !== this.library) location.reload();
|
||||
else this.navigate(at.part, "none");
|
||||
});
|
||||
} catch (err) {
|
||||
this.fatal = err instanceof Error ? err.message : String(err);
|
||||
this.emit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The version that kept each document separately stored its replicas under `doc:<uid>:…`. They
|
||||
* are never loaded into the library, but one may hold edits made offline that never reached the
|
||||
* server: compare each with what the server had when it built the library, and say so if it is
|
||||
* ahead.
|
||||
*/
|
||||
private async checkOldReplicas(migrated: Migrated) {
|
||||
const flag = `lib:${this.session.library}:old-checked`;
|
||||
if (await idbGet(flag)) return;
|
||||
const keys = await idbKeys();
|
||||
const found: OldReplica[] = [];
|
||||
const check = async (key: string, entry: Migrated["docs"][number] | undefined, branch: string) => {
|
||||
const bytes = await idbGet<Uint8Array>(key);
|
||||
if (!bytes || !entry) return;
|
||||
const had = entry.versions[branch];
|
||||
const mine = Doc.load(bytes, this.user).loro.version().toJSON();
|
||||
if (!had || !vvIncludes(decodeVV(had) as never, mine)) found.push({ slug: entry.slug, title: entry.title, branch, bytes });
|
||||
};
|
||||
for (const key of keys) {
|
||||
const m = /^doc:([0-9a-f]+):branch:(.+)$/.exec(key);
|
||||
if (m) await check(key, migrated.docs.find((d) => d.uid === m[1]), m[2]);
|
||||
}
|
||||
this.oldReplicas = found;
|
||||
if (!found.length) return void idbSet(flag, true);
|
||||
const names = found.map((r) => `“${clip(r.title, 30)}”${r.branch === "main" ? "" : ` (${r.branch})`}`).join(", ");
|
||||
this.say(`This browser holds edits made before the library existed that never reached the server: ${names}. They were not merged. :/recover saves each as a .md file.`);
|
||||
// ---- libraries ----
|
||||
|
||||
/** The libraries the server has, in order (also kept in `libraries`). */
|
||||
async listLibraries(): Promise<LibraryInfo[]> {
|
||||
this.libraries = await listLibraries();
|
||||
this.emit();
|
||||
return this.libraries;
|
||||
}
|
||||
|
||||
/** :/recover: save each old replica that is ahead of the server as a file, then stop mentioning them. */
|
||||
recover() {
|
||||
if (!this.oldReplicas.length) return this.say("Nothing to recover: no old replica in this browser holds unsent edits.");
|
||||
for (const r of this.oldReplicas) {
|
||||
const { text } = serializeDoc(Doc.load(r.bytes, this.user).snap());
|
||||
download(`${r.slug}${r.branch === "main" ? "" : `-${r.branch.replace(/[^\w-]+/g, "-")}`}-unsent.md`, text);
|
||||
/** Open another library: a page load, so nothing of this one stays in memory. */
|
||||
switchLibrary(id: string) {
|
||||
this.session?.flush();
|
||||
location.assign(inLibrary(id, "/"));
|
||||
}
|
||||
this.say(`Saved ${this.oldReplicas.length} file${this.oldReplicas.length > 1 ? "s" : ""}; :/import brings one in under the node you are on.`);
|
||||
this.oldReplicas = [];
|
||||
void idbSet(`lib:${this.session.library}:old-checked`, true);
|
||||
|
||||
/** A new library, with its root alone; `open` switches to it. */
|
||||
async createLibrary(title: string, open = false): Promise<LibraryInfo | null> {
|
||||
try {
|
||||
const lib = await createLibrary(title);
|
||||
await this.listLibraries();
|
||||
if (open) this.switchLibrary(lib.id);
|
||||
else this.say(`Made the library “${lib.title}”.`);
|
||||
return lib;
|
||||
} catch (err) {
|
||||
this.say(`Could not make the library: ${(err as Error).message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Rename a library (an ordinary commit on its root's title, made by the server). */
|
||||
async renameLibrary(id: string, title: string): Promise<boolean> {
|
||||
try {
|
||||
const lib = await renameLibrary(id, title);
|
||||
await this.listLibraries();
|
||||
this.say(`Renamed the library to “${lib.title}”.`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.say(`Could not rename the library: ${(err as Error).message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete a library: the server moves its files aside; the last one cannot go. Deleting this one goes to the first other. */
|
||||
async deleteLibrary(id: string): Promise<boolean> {
|
||||
try {
|
||||
await deleteLibrary(id);
|
||||
const left = await this.listLibraries();
|
||||
if (id === this.library) {
|
||||
sessionStorage.setItem("ie:flash", "Deleted the library; its files were moved aside on the server.");
|
||||
this.switchLibrary(left[0].id);
|
||||
} else this.say("Deleted the library; its files were moved aside on the server.");
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.say(`Could not delete the library: ${(err as Error).message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* :/library: with no name, list the libraries; with a name (or id), switch to it; `new <name>`
|
||||
* makes one and switches to it.
|
||||
*/
|
||||
async libraryCommand(arg: string) {
|
||||
const list = await this.listLibraries().catch(() => this.libraries);
|
||||
const words = arg.trim();
|
||||
if (!words) return this.say(`Libraries: ${list.map((l) => `${l.id === this.library ? "▸ " : ""}${l.title} (${l.nodes} nodes)`).join(" · ")}. :/library <name> opens one, :/library new <name> makes one.`);
|
||||
const made = /^new\s+(.+)$/.exec(words);
|
||||
if (made) return void this.createLibrary(made[1], true);
|
||||
const lower = words.toLowerCase();
|
||||
const hit = list.find((l) => l.id === words) ?? list.find((l) => l.title.toLowerCase() === lower) ?? list.find((l) => l.title.toLowerCase().startsWith(lower));
|
||||
if (!hit) return this.say(`No library “${words}”. :/library lists them.`);
|
||||
if (hit.id === this.library) return this.say(`This is “${hit.title}”.`);
|
||||
this.switchLibrary(hit.id);
|
||||
}
|
||||
|
||||
/** The window's title: the article on the column's article page, else the node the reader is on. */
|
||||
@@ -1242,8 +1304,12 @@ class Store {
|
||||
return this.session.synced();
|
||||
}
|
||||
|
||||
/** Views and the branch are kept per library, so each library opens where it was left. */
|
||||
private viewKey(branch = this.repo.current) {
|
||||
return `ie:view:${branch}`;
|
||||
return `ie:view:${this.library}:${branch}`;
|
||||
}
|
||||
private branchKey() {
|
||||
return `ie:branch:${this.library}`;
|
||||
}
|
||||
private restoreView() {
|
||||
const s = this.doc.snap();
|
||||
@@ -1280,11 +1346,11 @@ class Store {
|
||||
|
||||
/** The address of what is on screen: the focused node, so a reload, a link or Back lands on it again. */
|
||||
here(): string {
|
||||
if (!this.panes && this.colWiki) return `/w/${this.colWiki.lang}/${encodeURIComponent(this.colWiki.title.replace(/ /g, "_"))}`;
|
||||
if (!this.panes && this.colWiki) return inLibrary(this.library, `/w/${this.colWiki.lang}/${encodeURIComponent(this.colWiki.title.replace(/ /g, "_"))}`);
|
||||
const s = this.snap;
|
||||
// An annotation has no address of its own: the address stays on what shows its article.
|
||||
if (inArticles(s, this.focus.node)) return location.pathname;
|
||||
return address(s, this.focus.node);
|
||||
return inLibrary(this.library, address(s, this.focus.node));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1306,7 +1372,7 @@ class Store {
|
||||
else this.addressTimer = setTimeout(write, 250);
|
||||
}
|
||||
|
||||
/** Show what a path names: on boot, and on Back and Forward. */
|
||||
/** Show what a path within the library names (`/`, `/n/<id>`, `/w/<lang>/<title>`): on boot, and on Back and Forward. */
|
||||
navigate(path: string, history: "replace" | "none") {
|
||||
const s = this.snap;
|
||||
// An article page of the column has an address of its own, so Back returns to it and from it.
|
||||
@@ -2181,6 +2247,7 @@ class Store {
|
||||
this.branchFrom = null;
|
||||
},
|
||||
switch: () => this.switchBranch(arg),
|
||||
library: () => void this.libraryCommand(arg),
|
||||
merge: () => this.mergeFrom(arg),
|
||||
user: () => {
|
||||
this.user = arg || this.user;
|
||||
@@ -2196,7 +2263,6 @@ class Store {
|
||||
duplicate: () => this.duplicateNode(arg),
|
||||
export: () => this.exportNode(),
|
||||
import: () => this.pickFile(),
|
||||
recover: () => this.recover(),
|
||||
link: () => this.linkTo(arg),
|
||||
unlink: () => this.unlink(),
|
||||
autolink: () => this.setAutolink(arg),
|
||||
@@ -3416,7 +3482,7 @@ class Store {
|
||||
if (!this.repo.branches.has(name)) return this.say(`No branch named ${name}.`);
|
||||
this.preview = null;
|
||||
this.repo.switch(name);
|
||||
lsSet("ie:branch", name);
|
||||
lsSet(this.branchKey(), name);
|
||||
this.restoreView();
|
||||
// Undo covers everything done on this branch from here on.
|
||||
this.undoManager();
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Several libraries: the registry on disk (server/libraries.ts), and the server's routes for them,
|
||||
* driven over HTTP as a page or an outside agent would (a real server, on a temporary data
|
||||
* directory). Nothing of one library may reach another: not an op, a sync, a link suggestion, a
|
||||
* nearby or Related list, a pending entry or a vector.
|
||||
*/
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { Libraries, readIndex } from "../server/libraries";
|
||||
import { LOCK } from "../server/lock";
|
||||
import { Doc } from "../src/core/model";
|
||||
|
||||
const ROOT = new URL("..", import.meta.url).pathname;
|
||||
const temps: string[] = [];
|
||||
const temp = () => {
|
||||
const d = mkdtempSync(join(tmpdir(), "ie-libs-"));
|
||||
temps.push(d);
|
||||
return d;
|
||||
};
|
||||
const servers: ChildProcess[] = [];
|
||||
afterAll(() => {
|
||||
for (const s of servers) s.kill("SIGKILL");
|
||||
for (const d of temps) rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("the libraries on disk", () => {
|
||||
it("makes, lists, renames and deletes libraries, each in its own directory; the last one stays", () => {
|
||||
const data = temp();
|
||||
const libs = new Libraries(data, () => {}).open((doc) => doc.apply([{ op: "create", parent: doc.snap().root, title: "Seeded", body: "Text." }], "seed"));
|
||||
const first = libs.first();
|
||||
const work = libs.create(" Work notes ");
|
||||
expect(work.title).toBe("Work notes");
|
||||
expect(work.titles()).toEqual([]);
|
||||
expect(work.id).not.toBe(first.id);
|
||||
expect(libs.list().map((l) => [l.title, l.nodes])).toEqual([
|
||||
["Library", 2],
|
||||
["Work notes", 1],
|
||||
]);
|
||||
// An op on one never touches the other: separate databases, separate files.
|
||||
const hash = first.main.stateHash();
|
||||
work.main.apply([{ op: "create", parent: work.main.snap().root, title: "Only here", body: "" }], "add");
|
||||
work.save("main");
|
||||
expect(first.main.stateHash()).toBe(hash);
|
||||
expect(existsSync(join(data, "libraries", work.id, "main.loro"))).toBe(true);
|
||||
// Renamed: a commit on its root's title, which the list reads.
|
||||
libs.rename(work.id, "Work");
|
||||
expect(work.main.snap().nodes[work.main.snap().root].title).toBe("Work");
|
||||
expect(libs.list()[1].title).toBe("Work");
|
||||
// A rename made in a replica (the root's title edited) shows in the list and the index.
|
||||
first.main.apply([{ op: "update", id: first.main.snap().root, title: "Mine" }], "rename");
|
||||
first.save("main");
|
||||
expect(libs.list()[0].title).toBe("Mine");
|
||||
expect(readIndex(join(data, "libraries"))[0].title).toBe("Mine");
|
||||
// Deleted: moved aside whole, still listed in the index as deleted, gone from the list.
|
||||
const moved = libs.remove(work.id);
|
||||
expect(moved).toContain(join("libraries", ".deleted", `${work.id}-`));
|
||||
expect(existsSync(join(moved, "main.loro"))).toBe(true);
|
||||
expect(existsSync(join(data, "libraries", work.id))).toBe(false);
|
||||
expect(libs.list().map((l) => l.id)).toEqual([first.id]);
|
||||
expect(readIndex(join(data, "libraries"))[1]).toMatchObject({ id: work.id, deleted: expect.any(String), movedTo: expect.stringContaining(".deleted") });
|
||||
expect(() => libs.remove(first.id)).toThrow(/last library/);
|
||||
// Opened again: the same libraries, the deleted one left out, nothing seeded.
|
||||
first.flush();
|
||||
const again = new Libraries(data, () => {}).open(() => {
|
||||
throw new Error("must not seed again");
|
||||
});
|
||||
expect(again.list().map((l) => [l.id, l.title])).toEqual([[first.id, "Mine"]]);
|
||||
});
|
||||
|
||||
it("refuses a title that is empty or too long", () => {
|
||||
const libs = new Libraries(temp(), () => {}).open(() => {});
|
||||
expect(() => libs.create(" ")).toThrow(/title/);
|
||||
expect(() => libs.create("x".repeat(201))).toThrow(/200/);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the server ----
|
||||
|
||||
const PORT = 4804;
|
||||
const base = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
function serve(data: string, library: string, port = PORT): { child: ChildProcess; out: string[]; exited: Promise<number | null> } {
|
||||
const out: string[] = [];
|
||||
const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, IE_PROD: "1", IE_LLM: "mock", IE_MOCK_DELAY: "0", IE_WIKI: "mock", IE_EMBED: "fake", IE_DATA: data, IE_LIBRARY: library, PORT: String(port), IE_USER: "tester" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
servers.push(child);
|
||||
child.stdout!.on("data", (d) => out.push(String(d)));
|
||||
child.stderr!.on("data", (d) => out.push(String(d)));
|
||||
const exited = new Promise<number | null>((r) => child.once("exit", (code) => r(code)));
|
||||
return { child, out, exited };
|
||||
}
|
||||
|
||||
async function up() {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
try {
|
||||
if ((await fetch(`${base}/api/libraries`)).ok) return;
|
||||
} catch {
|
||||
/* not yet */
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
throw new Error("the server did not start");
|
||||
}
|
||||
|
||||
const get = async (path: string) => (await fetch(base + path)).json();
|
||||
const send = (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) => fetch(base + path, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const ops = async (lib: string, list: unknown[]) => {
|
||||
const res = await send("POST", `/api/l/${lib}/ops`, { ops: list, author: "test", actor: "human" });
|
||||
expect(res.status).toBe(200);
|
||||
return (await res.json()).created as string[];
|
||||
};
|
||||
|
||||
describe("the server with several libraries", () => {
|
||||
it("will not open a data directory in the old layout: one line saying to run the migration, and nothing written", async () => {
|
||||
const data = temp();
|
||||
cpSync(new URL("./fixtures/migrate/main/library", import.meta.url).pathname, join(data, "library"), { recursive: true });
|
||||
const before = readdirSync(data).sort();
|
||||
const s = serve(data, temp());
|
||||
expect(await s.exited).toBe(1);
|
||||
const text = s.out.join("").trim();
|
||||
expect(text.split("\n")).toHaveLength(1);
|
||||
expect(text).toMatch(/old single-library layout.*npm run migrate/);
|
||||
expect(readdirSync(data).sort()).toEqual(before);
|
||||
}, 30_000);
|
||||
|
||||
it("keeps libraries apart: ops, syncs, link suggestions, nearby, Related, pending entries and vectors", async () => {
|
||||
const data = temp();
|
||||
const starters = temp();
|
||||
writeFileSync(join(starters, "tides.md"), "# Tides\n\nThe sea rises and falls twice a day, pulled by the Moon.\n\n## Tidal locking\n\nA body that always shows the same face to what it orbits.\n");
|
||||
const s = serve(data, starters);
|
||||
await up();
|
||||
// An empty data directory: one library, with the seed and the starter trees.
|
||||
const [a] = (await get("/api/libraries")).libraries;
|
||||
expect(a.title).toBe("Library");
|
||||
const treeA = await get(`/api/l/${a.id}/tree`);
|
||||
const topsA = treeA.nodes[treeA.root].children.map((c: string) => treeA.nodes[c].title);
|
||||
expect(topsA).toEqual(["Infinispand", "Tides"]);
|
||||
// The unprefixed routes are the first library's.
|
||||
expect((await get("/api/tree")).library).toBe(a.id);
|
||||
expect((await get("/api/state")).library).toBe(a.id);
|
||||
expect(existsSync(join(data, LOCK))).toBe(true);
|
||||
|
||||
// A new library: its root alone, under the given title.
|
||||
const made = await send("POST", "/api/libraries", { title: "Second" });
|
||||
expect(made.status).toBe(201);
|
||||
const b = (await made.json()).library;
|
||||
expect(b).toMatchObject({ title: "Second", nodes: 1 });
|
||||
const state = await get(`/api/l/${b.id}/state`);
|
||||
expect(state).toMatchObject({ library: b.id, title: "Second" });
|
||||
expect(state.libraries.map((l: { id: string }) => l.id)).toEqual([a.id, b.id]);
|
||||
// The same titles as the first library's, and text that names them.
|
||||
const rootB = (await get(`/api/l/${b.id}/tree`)).root;
|
||||
const [tidesB, lockingB, moon] = await ops(b.id, [
|
||||
{ op: "create", parent: rootB, title: "Tides", body: "Water moving under the pull of the Moon and the Sun." },
|
||||
{ op: "create", parent: "$0", title: "Tidal locking", body: "A body that always shows the same face to what it orbits, as the Moon does to Earth." },
|
||||
{ op: "create", parent: rootB, title: "Moon", body: "The Moon shows one face to Earth because of tidal locking, which slowed its spin." },
|
||||
]);
|
||||
const after = await get(`/api/l/${a.id}/tree`);
|
||||
expect(Object.keys(after.nodes).length).toBe(Object.keys(treeA.nodes).length);
|
||||
expect(after.history[0].message).toBe(treeA.history[0].message);
|
||||
const treeB = await get(`/api/l/${b.id}/tree`);
|
||||
expect(Object.keys(treeB.nodes)).toHaveLength(4);
|
||||
for (const id of Object.keys(treeB.nodes)) expect(after.nodes[id]).toBeUndefined();
|
||||
|
||||
// A replica of one library cannot sync into the other.
|
||||
const bytes = Doc.library("x").snapshotBytes();
|
||||
const foreign = await fetch(`${base}/api/l/${b.id}/sync/main`, { method: "POST", headers: { "x-library": a.id, "x-vv": "[]" }, body: bytes as BodyInit });
|
||||
expect(foreign.status).toBe(409);
|
||||
// A node of one library is not found under the other's prefix.
|
||||
expect((await send("GET", `/api/l/${b.id}/nodes/${encodeURIComponent(treeA.root)}/tree`)).status).toBe(404);
|
||||
expect((await send("GET", "/api/l/nosuchlibrary/tree")).status).toBe(404);
|
||||
|
||||
// Link discovery in the second library proposes its own nodes only.
|
||||
const scan = await (await send("POST", `/api/l/${b.id}/links/scan`, { node: moon })).json();
|
||||
const nodeTargets = scan.suggestions.filter((x: { target: { kind: string } }) => x.target.kind === "node");
|
||||
expect(nodeTargets.length).toBeGreaterThan(0);
|
||||
for (const x of nodeTargets) expect(treeB.nodes[x.target.id]).toBeTruthy();
|
||||
expect(nodeTargets.map((x: { target: { id: string } }) => x.target.id)).toEqual([lockingB]);
|
||||
expect(treeB.nodes[tidesB].title).toBe("Tides");
|
||||
const related = await get(`/api/l/${b.id}/links/related?node=${encodeURIComponent(moon)}`);
|
||||
for (const r of related.related) expect(treeB.nodes[r.node]).toBeTruthy();
|
||||
const nearby = await get(`/api/l/${b.id}/links/nearby?node=${encodeURIComponent(moon)}&k=10`);
|
||||
expect(nearby.nearby.length).toBeGreaterThan(0);
|
||||
for (const n of nearby.nearby) expect(treeB.nodes[n.handle]).toBeTruthy();
|
||||
// And the first library's lists never name the second's nodes.
|
||||
const tidesA = treeA.nodes[treeA.root].children.find((c: string) => treeA.nodes[c].title === "Tides");
|
||||
const nearA = await get(`/api/l/${a.id}/links/nearby?node=${encodeURIComponent(tidesA)}&k=10`);
|
||||
for (const n of nearA.nearby) expect(treeA.nodes[n.handle]).toBeTruthy();
|
||||
// Pending entries and vectors are kept in each library's own directory.
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const pendingB = JSON.parse(readFileSync(join(data, "libraries", b.id, "links", "pending.json"), "utf8"));
|
||||
expect(Object.keys(pendingB)).toEqual([moon]);
|
||||
expect(existsSync(join(data, "libraries", a.id, "links", "pending.json"))).toBe(false);
|
||||
const vecB = JSON.parse(readFileSync(join(data, "libraries", b.id, "vectors", "nodes.json"), "utf8"));
|
||||
const vecA = JSON.parse(readFileSync(join(data, "libraries", a.id, "vectors", "nodes.json"), "utf8"));
|
||||
const ids = (v: unknown) => JSON.stringify(v);
|
||||
for (const id of Object.keys(treeB.nodes)) expect(ids(vecA)).not.toContain(id);
|
||||
for (const id of Object.keys(treeA.nodes)) expect(ids(vecB)).not.toContain(id);
|
||||
expect(existsSync(join(data, "links"))).toBe(false);
|
||||
expect(existsSync(join(data, "vectors"))).toBe(false);
|
||||
|
||||
// Renamed, then deleted: moved aside, its routes gone; the last library stays.
|
||||
expect((await send("PATCH", `/api/libraries/${b.id}`, { title: "Second, renamed" })).status).toBe(200);
|
||||
expect((await get(`/api/l/${b.id}/tree`)).nodes[rootB].title).toBe("Second, renamed");
|
||||
const del = await send("DELETE", `/api/libraries/${b.id}`);
|
||||
expect(del.status).toBe(200);
|
||||
const { movedTo } = await del.json();
|
||||
expect(existsSync(join(movedTo, "main.loro"))).toBe(true);
|
||||
expect(existsSync(join(movedTo, "links", "pending.json"))).toBe(true);
|
||||
expect((await send("GET", `/api/l/${b.id}/state`)).status).toBe(404);
|
||||
expect((await get("/api/libraries")).libraries.map((l: { id: string }) => l.id)).toEqual([a.id]);
|
||||
expect((await send("DELETE", `/api/libraries/${a.id}`)).status).toBe(409);
|
||||
|
||||
// A second server on the same data is refused while the first runs.
|
||||
const second = serve(data, starters, PORT + 1);
|
||||
expect(await second.exited).toBe(1);
|
||||
expect(second.out.join("")).toMatch(/Another server \(pid \d+, port 4804\)/);
|
||||
// Stopped, the first lets go of its lock; started again, the same library, nothing seeded twice.
|
||||
s.child.kill("SIGTERM");
|
||||
await s.exited;
|
||||
expect(existsSync(join(data, LOCK))).toBe(false);
|
||||
const again = serve(data, starters);
|
||||
await up();
|
||||
const listed = (await get("/api/libraries")).libraries;
|
||||
expect(listed.map((l: { id: string; nodes: number }) => [l.id, l.nodes])).toEqual([[a.id, Object.keys(treeA.nodes).length]]);
|
||||
again.child.kill("SIGTERM");
|
||||
await again.exited;
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* Migration from one database per document (and from the single-document layout before that) to
|
||||
* one library: every document's content equal, histories kept, conflicts still open, the old files
|
||||
* untouched, and a second start that does nothing.
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, relative } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { Doc, descendants, isStale, tops, type NodeId } from "../src/core/model";
|
||||
import { at, history, mergeBranch, revertSubtreeTo, revertTo, verifyHistory } from "../src/core/repo";
|
||||
|
||||
const temp = () => mkdtempSync(join(tmpdir(), "ie-migrate-"));
|
||||
|
||||
/** A document as the per-document version made them: a single tree, with notes, a pin and a form. */
|
||||
function oldDoc(title: string) {
|
||||
const doc = Doc.create("alice", title, "Alpha is first. Beta is second. Gamma is third.");
|
||||
const root = doc.snap().root;
|
||||
doc.apply(
|
||||
[
|
||||
{ op: "create", parent: root, title: "One", body: "The first child, with a phrase worth a note." },
|
||||
{ op: "create", parent: root, title: "Two", body: "The second child." },
|
||||
{ op: "create", parent: root, kind: "note", quote: "Beta", form: "gloss", lens: "define", body: "the second letter" },
|
||||
{ op: "create", parent: "$0" as NodeId, kind: "note", quote: "a phrase worth a note", form: "passage", body: "A passage." },
|
||||
{ op: "bless", id: root },
|
||||
],
|
||||
"Pre-generate",
|
||||
{ actor: "llm" },
|
||||
);
|
||||
return doc;
|
||||
}
|
||||
|
||||
/** Every file under a directory, with a hash of its bytes. */
|
||||
function sums(dir: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const walk = (d: string) => {
|
||||
for (const f of readdirSync(d)) {
|
||||
const p = join(d, f);
|
||||
if (statSync(p).isDirectory()) walk(p);
|
||||
else out[relative(dir, p)] = createHash("sha256").update(readFileSync(p)).digest("hex");
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return out;
|
||||
}
|
||||
|
||||
function write(data: string, id: string, branches: Record<string, Doc>, mtime: number) {
|
||||
const dir = join(data, "docs", id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [name, doc] of Object.entries(branches)) {
|
||||
writeFileSync(join(dir, `${encodeURIComponent(name)}.loro`), doc.snapshotBytes());
|
||||
utimesSync(join(dir, `${encodeURIComponent(name)}.loro`), mtime, mtime);
|
||||
}
|
||||
writeFileSync(join(dir, "meta.json"), JSON.stringify({ uid: createHash("md5").update(id).digest("hex").slice(0, 12), created: "2026-11-01T00:00:00Z" }));
|
||||
}
|
||||
|
||||
describe("migration from the per-document layout", () => {
|
||||
it("builds one library from every document's main branch, keeping content, histories and open conflicts, and touches nothing old", () => {
|
||||
const data = temp();
|
||||
// The first document, with work on it: a human edit (a pin), and an open conflict from a merge.
|
||||
const first = oldDoc("Infinite Expand");
|
||||
const one = first.snap().nodes[first.snap().root].children[0];
|
||||
first.apply([{ op: "update", id: one, body: "A person rewrote this, keeping a phrase worth a note." }], "Human edit");
|
||||
const bob = first.fork("bob");
|
||||
first.apply([{ op: "update", id: one, title: "One, says main" }], "Main retitles");
|
||||
bob.apply([{ op: "update", id: one, title: "One, says bob" }], "Bob retitles");
|
||||
mergeBranch(first, bob, "bob");
|
||||
expect(first.conflicts().filter((c) => c.status === "open")).toHaveLength(1);
|
||||
const alt = first.fork();
|
||||
alt.apply([{ op: "update", id: alt.snap().root, title: "On alt" }], "alt edit");
|
||||
const tides = oldDoc("The tides");
|
||||
// A duplicate began as a byte copy of another document, so it shares that document's history.
|
||||
const copy = Doc.load(tides.snapshotBytes(), "x");
|
||||
copy.apply([{ op: "update", id: copy.snap().root, title: "The tides (copy)" }], "Duplicate");
|
||||
write(data, "infinite-expand", { main: first, alt }, 1_700_000_000);
|
||||
write(data, "tides", { main: tides }, 1_700_000_300);
|
||||
write(data, "tides-copy", { main: copy }, 1_700_000_200);
|
||||
writeFileSync(join(data, "library.json"), JSON.stringify({ imported: ["infinite-expand", "tides"] }));
|
||||
const before = sums(data);
|
||||
const oldCommits = history(first).length;
|
||||
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
const lib = store.main;
|
||||
const snap = lib.snap();
|
||||
|
||||
// One library: the first document first, then most recently changed first.
|
||||
expect(snap.library).toBe(true);
|
||||
expect(store.titles()).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
|
||||
const [nFirst, nTides, nCopy] = tops(snap);
|
||||
for (const [node, old] of [[nFirst, first], [nTides, tides], [nCopy, copy]] as const) {
|
||||
expect(lib.shape(snap, node)).toBe(old.shape());
|
||||
// Exactly what was stale before is stale now (the first document's edits left its root out of date).
|
||||
const was = old.snap();
|
||||
expect([node, ...descendants(snap, node)].filter((n) => isStale(snap, n)).length).toBe(Object.keys(was.nodes).filter((n) => isStale(was, n as NodeId)).length);
|
||||
}
|
||||
expect(isStale(snap, snap.root)).toBe(false);
|
||||
// Kept documents keep their node ids, so anchors and conflict records still point at them.
|
||||
expect(nFirst).toBe(first.snap().root);
|
||||
expect(nTides).toBe(tides.snap().root);
|
||||
expect(nCopy).not.toBe(copy.snap().root);
|
||||
expect(lib.conflicts().filter((c) => c.status === "open").map((c) => c.node)).toEqual([one]);
|
||||
expect(snap.nodes[one].pinned).toBe(true);
|
||||
|
||||
// The first document's history is the library's history from before it existed, and verifies.
|
||||
const h = history(lib);
|
||||
expect(h[0]).toMatchObject({ tag: "migrate", message: "Gather 3 documents into the library" });
|
||||
expect(h.filter((c) => ["Human edit", "Main retitles", "Bob retitles"].includes(c.message) || c.message.startsWith("Merge bob"))).toHaveLength(4);
|
||||
expect(h.length).toBe(oldCommits + history(tides).length + 1); // the copy's history is not carried
|
||||
expect(verifyHistory(lib)).toMatchObject({ unhashed: 0, mismatches: [] });
|
||||
const then = at(lib, h.find((c) => c.message === "Human edit")!).snap();
|
||||
expect(then.library).toBe(false);
|
||||
expect(then.nodes[then.root].title).toBe("Infinite Expand");
|
||||
expect(then.nodes[one].body).toBe("A person rewrote this, keeping a phrase worth a note.");
|
||||
// Reverting the whole library to before it existed is refused; reverting the document to then works.
|
||||
const humanEdit = h.find((c) => c.message === "Human edit")!;
|
||||
expect(() => revertTo(lib, humanEdit)).toThrow(/before the library existed/);
|
||||
revertSubtreeTo(lib, humanEdit, first.snap().root);
|
||||
expect(lib.snap().nodes[one].title).toBe("One");
|
||||
expect(lib.shape(lib.snap(), nTides)).toBe(tides.shape());
|
||||
expect(verifyHistory(lib).mismatches).toEqual([]);
|
||||
|
||||
// The old directory is renamed, every byte as it was; the record says what was and was not carried.
|
||||
const moved = readdirSync(data).find((f) => f.startsWith("docs.migrated-"))!;
|
||||
expect(existsSync(join(data, "docs"))).toBe(false);
|
||||
const after = sums(data);
|
||||
for (const [file, hash] of Object.entries(before)) expect(after[file.replace(/^docs\//, `${moved}/`)]).toBe(hash);
|
||||
const record = JSON.parse(readFileSync(join(data, "library", "migrated.json"), "utf8"));
|
||||
expect(record.docs.map((d: { slug: string; history: string }) => [d.slug, d.history])).toEqual([["infinite-expand", "kept"], ["tides", "kept"], ["tides-copy", "copied"]]);
|
||||
expect(record.branchesNotCarried).toEqual([{ doc: "infinite-expand", branch: "alt" }]);
|
||||
expect(Object.keys(record.docs[0].versions).sort()).toEqual(["alt", "main"]);
|
||||
expect(logs.join("\n")).toMatch(/infinite-expand: alt/);
|
||||
expect(logs.join("\n")).toMatch(/tides-copy .*copied as content/);
|
||||
|
||||
// A second start is a no-op.
|
||||
store.save("main");
|
||||
const settled = sums(data);
|
||||
const again: string[] = [];
|
||||
const store2 = new LibraryStore(data, (m) => again.push(m)).open();
|
||||
expect(again).toEqual([]);
|
||||
expect(sums(data)).toEqual(settled);
|
||||
expect(store2.main.stateHash()).toBe(lib.stateHash());
|
||||
});
|
||||
|
||||
it("migrates the single-document layout's flat files the same way", () => {
|
||||
const data = temp();
|
||||
const main = oldDoc("Infinite Expand");
|
||||
const alt = main.fork();
|
||||
alt.apply([{ op: "update", id: alt.snap().root, title: "On alt" }], "alt edit");
|
||||
writeFileSync(join(data, "main.loro"), main.snapshotBytes());
|
||||
writeFileSync(join(data, "my%20branch.loro"), alt.snapshotBytes());
|
||||
writeFileSync(join(data, "notes.txt"), "not a branch");
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
const snap = store.main.snap();
|
||||
expect(store.titles()).toEqual(["Infinite Expand"]);
|
||||
expect(store.main.shape(snap, tops(snap)[0])).toBe(main.shape());
|
||||
expect(readdirSync(data).filter((f) => f.endsWith(".loro"))).toEqual([]);
|
||||
expect(existsSync(join(data, "notes.txt"))).toBe(true); // anything else is left alone
|
||||
const flat = readdirSync(data).find((f) => f.startsWith("flat.migrated-"))!;
|
||||
expect(readdirSync(join(data, flat)).sort()).toEqual(["main.loro", "my%20branch.loro"]);
|
||||
expect(readFileSync(join(data, flat, "main.loro")).equals(Buffer.from(main.snapshotBytes()))).toBe(true);
|
||||
expect(logs.join("\n")).toMatch(/infinite-expand: my branch/);
|
||||
});
|
||||
|
||||
it("starts a fresh library when there is nothing to migrate", () => {
|
||||
const data = temp();
|
||||
const store = new LibraryStore(data, () => {}).open();
|
||||
expect(store.main.snap().library).toBe(true);
|
||||
expect(store.titles()).toEqual([]);
|
||||
expect(readdirSync(data)).toEqual(["library"]);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -85,7 +85,7 @@ describe("a large library", () => {
|
||||
mkdirSync(join(data, "library"));
|
||||
writeFileSync(join(data, "library", "main.loro"), bytes);
|
||||
t = performance.now();
|
||||
const store = new LibraryStore(data, () => {}).open();
|
||||
const store = new LibraryStore(join(data, "library")).open();
|
||||
expect(store.titles()).toHaveLength(100);
|
||||
const serverStart = performance.now() - t;
|
||||
|
||||
|
||||
+70
-27
@@ -1,11 +1,11 @@
|
||||
/** The library on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
|
||||
/** The libraries on disk (seeding and starter files), and a node with everything under it: imported, exported, copied, moved and addressed wherever it is. */
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { Libraries, importStarters, readIndex } from "../server/libraries";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { address, resolve } from "../src/core/address";
|
||||
import { LIBRARY_ID, address, inLibrary, resolve, splitLibrary } from "../src/core/address";
|
||||
import { resolveNode } from "../src/core/links";
|
||||
import { Doc, descendants, isStale, sections, staleness, tops } from "../src/core/model";
|
||||
import { SEED_TITLE, importTree, writeSeed } from "../src/core/seed";
|
||||
@@ -16,46 +16,39 @@ const temp = () => mkdtempSync(join(tmpdir(), "ie-lib-"));
|
||||
const quiet = () => {};
|
||||
const MD = (title: string) => `# ${title}\n\nA root body with a phrase.\n\n## One\n\nSection text.\n\n^ "Section" gloss: a note\n`;
|
||||
|
||||
describe("the library on disk", () => {
|
||||
describe("the libraries on disk", () => {
|
||||
it("starts an empty data directory as one library with the first tree, written once", () => {
|
||||
const data = temp();
|
||||
const store = new LibraryStore(data, quiet).open();
|
||||
store.seedFirst((doc) => writeSeed(doc, prompt, seed));
|
||||
let seeded = 0;
|
||||
const libs = new Libraries(data, quiet).open((doc) => (seeded++, writeSeed(doc, prompt, seed)));
|
||||
const store = libs.first();
|
||||
expect(seeded).toBe(1);
|
||||
expect(store.titles()).toEqual([SEED_TITLE]);
|
||||
expect(store.main.snap().library).toBe(true);
|
||||
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual(["infinite-expand"]);
|
||||
expect(readIndex(join(data, "libraries")).map((e) => e.id)).toEqual([store.id]);
|
||||
store.flush();
|
||||
// A second start loads the same library (same id) and writes nothing new.
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
again.seedFirst(() => {
|
||||
// A second start loads the same library (same id) and seeds nothing.
|
||||
const again = new Libraries(data, quiet).open(() => {
|
||||
throw new Error("should not seed twice");
|
||||
});
|
||||
expect(again.id).toBe(store.id);
|
||||
expect(again.main.stateHash()).toBe(store.main.stateHash());
|
||||
expect(again.first().id).toBe(store.id);
|
||||
expect(again.first().main.stateHash()).toBe(store.main.stateHash());
|
||||
});
|
||||
|
||||
it("imports each starter file once, as a child of the root; a deleted one stays deleted and a broken one is skipped", () => {
|
||||
it("writes the starter files, in file name order, into the first library only; a broken one is skipped", () => {
|
||||
const data = temp();
|
||||
const lib = temp();
|
||||
writeFileSync(join(lib, "good-one.md"), MD("Good one"));
|
||||
writeFileSync(join(lib, "Second File.md"), MD("Second"));
|
||||
writeFileSync(join(lib, "broken.md"), MD("Broken").replace('"Section"', '"Missing"'));
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
store.importLibrary(lib);
|
||||
expect(store.titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
|
||||
const libs = new Libraries(data, quiet).open((doc) => importStarters(doc, lib, (m) => logs.push(m)));
|
||||
expect(libs.first().titles()).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
|
||||
expect(logs.join("\n")).toMatch(/skipped broken\.md:\n {2}library\/broken\.md:9: in “One”: quote not found: "Missing"/);
|
||||
|
||||
const good = tops(store.main.snap()).find((id) => store.main.snap().nodes[id].title === "Good one")!;
|
||||
store.main.apply([{ op: "delete", id: good }], "Delete “Good one”");
|
||||
store.save("main");
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
again.importLibrary(lib);
|
||||
expect(again.titles()).toEqual(["Second"]);
|
||||
// Once fixed, the broken file is picked up.
|
||||
writeFileSync(join(lib, "broken.md"), MD("Broken"));
|
||||
again.importLibrary(lib);
|
||||
expect(again.titles()).toEqual(["Second", "Broken"]);
|
||||
// A new library starts with its root alone, whatever the starter directory holds.
|
||||
const work = libs.create("Work");
|
||||
expect(work.titles()).toEqual([]);
|
||||
expect(work.title).toBe("Work");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,4 +129,54 @@ describe("a node and everything under it, wherever it is", () => {
|
||||
expect(resolve(lib.snap(), "/doc/tides")).toEqual({ missing: "no page /doc/tides" });
|
||||
expect(resolve(lib.snap(), "/n/%E0%A4%A")).toMatchObject({ missing: expect.any(String) });
|
||||
});
|
||||
|
||||
it("is addressed under its library: /l/<library>/n/<id>; an address without a library is read in the one last used", () => {
|
||||
expect(inLibrary("abc", "/")).toBe("/l/abc");
|
||||
expect(inLibrary("abc", "/n/1%402")).toBe("/l/abc/n/1%402");
|
||||
expect(splitLibrary("/l/abc")).toEqual({ library: "abc", part: "/" });
|
||||
expect(splitLibrary("/l/abc/n/1%402")).toEqual({ library: "abc", part: "/n/1%402" });
|
||||
expect(splitLibrary("/l/abc/w/en/Octopus")).toEqual({ library: "abc", part: "/w/en/Octopus" });
|
||||
expect(splitLibrary("/")).toEqual({ library: null, part: "/" });
|
||||
expect(splitLibrary("/n/1%402")).toEqual({ library: null, part: "/n/1%402" });
|
||||
expect(splitLibrary("/doc/tides")).toEqual({ library: null, part: "/doc/tides" });
|
||||
const lib = Doc.library("alice");
|
||||
expect(LIBRARY_ID.test(lib.libraryId!)).toBe(true);
|
||||
});
|
||||
|
||||
it("is copied into another library whole by graft: flags, notes on the root's text, and a map of old ids to new", () => {
|
||||
const from = Doc.library("alice");
|
||||
const root = from.snap().root;
|
||||
const [top, , box] = from.apply(
|
||||
[
|
||||
{ op: "update", id: root, body: "Root text with words." },
|
||||
{ op: "create", parent: root, title: "Top", body: "Some text." },
|
||||
{ op: "create", parent: root, kind: "note", quote: "words", body: "On the root." },
|
||||
{ op: "create", parent: root, kind: "section", title: "Wikipedia", body: "", articles: true },
|
||||
],
|
||||
"make",
|
||||
).created;
|
||||
from.apply([{ op: "update", id: top, pinned: false, nolink: ["text"] }], "flags");
|
||||
const src = from.snap();
|
||||
const into = Doc.library("bob");
|
||||
const to = into.snap().root;
|
||||
into.begin("copy", "human");
|
||||
(into.tree.getNodeByID(to)!.data.get("body") as { insert(i: number, t: string): void }).insert(0, src.nodes[root].body);
|
||||
const ids = new Map();
|
||||
for (const c of src.nodes[root].children) into.graft(src, c, to, { keepAnchors: true, ids });
|
||||
into.commit("copy", "human");
|
||||
const got = into.snap();
|
||||
expect(ids.size).toBe(3);
|
||||
const note = got.nodes[ids.get(src.nodes[root].children[1])];
|
||||
expect(note.anchors.map((a) => a.text)).toEqual(["words"]);
|
||||
expect(got.nodes[ids.get(box)].articles).toBe(true);
|
||||
expect(got.nodes[ids.get(top)]).toMatchObject({ title: "Top", pinned: false, nolink: ["text"] });
|
||||
// Without keepAnchors, a note at the top of a graft into another text loses its anchors, as before.
|
||||
into.begin("again", "human");
|
||||
const lone = into.graft(src, src.nodes[root].children[1], to);
|
||||
into.commit("again", "human");
|
||||
expect(into.snap().nodes[lone].anchors).toEqual([]);
|
||||
// The Wikipedia flag goes only where create allows it: under a library root.
|
||||
const nested = from.apply([{ op: "copy", id: box, parent: top }], "copy box").created[0];
|
||||
expect(from.snap().nodes[nested].articles).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user