Repository Public
1import { and, asc, desc, eq, gt, inArray, isNull, sql as dsql, ne } from "drizzle-orm";2import { db, schema } from "@/db";3import { docText, wordCount, extractPageRefs, emptyDoc, ensureBlockIds, type PMNode } from "@/lib/editor/text";4import { enqueue, QUEUES } from "@/lib/jobs";5import { HttpError } from "@/lib/errors";6/** Postgres array literal for parameterised any()/all() */7const pgArr = (a: string[]) => `{${a.map((x) => `"${x.replace(/"/g, "")}"`).join(",")}}`;89export type Page = typeof schema.pages.$inferSelect;10export const pageSummary = { id: schema.pages.id, parentId: schema.pages.parentId, databaseId: schema.pages.databaseId, type: schema.pages.type, section: schema.pages.section, title: schema.pages.title, icon: schema.pages.icon, cover: schema.pages.cover, position: schema.pages.position, pinned: schema.pages.pinned, archived: schema.pages.archived, inboxAt: schema.pages.inboxAt, wordCount: schema.pages.wordCount, updatedAt: schema.pages.updatedAt, createdAt: schema.pages.createdAt, lastOpenedAt: schema.pages.lastOpenedAt, properties: schema.pages.properties };1112export async function getPage(workspaceId: string, id: string, opts: { includeDeleted?: boolean } = {}) {13 const [p] = await db.select().from(schema.pages).where(and(eq(schema.pages.id, id), eq(schema.pages.workspaceId, workspaceId), opts.includeDeleted ? undefined : isNull(schema.pages.deletedAt)));14 if (!p) throw new HttpError(404, "Page not found");15 return p;16}17export async function listTree(workspaceId: string) {18 return db.select(pageSummary).from(schema.pages).where(and(eq(schema.pages.workspaceId, workspaceId), isNull(schema.pages.deletedAt), isNull(schema.pages.databaseId), eq(schema.pages.archived, false))).orderBy(asc(schema.pages.position), asc(schema.pages.createdAt));19}20export async function createPage(workspaceId: string, input: { title?: string; parentId?: string | null; section?: string; type?: string; content?: PMNode; icon?: string | null; properties?: Record<string, unknown>; databaseId?: string | null; inboxAt?: Date | null; captureKind?: string | null }) {21 const [{ max }] = await db.select({ max: dsql<number>`coalesce(max(position),0)` }).from(schema.pages).where(and(eq(schema.pages.workspaceId, workspaceId), input.parentId ? eq(schema.pages.parentId, input.parentId) : isNull(schema.pages.parentId)));22 const content = ensureBlockIds(input.content ?? emptyDoc()).doc; const plain = docText(content);23 const [p] = await db.insert(schema.pages).values({ workspaceId, title: input.title?.trim() || "Untitled", parentId: input.parentId ?? null, section: input.section ?? "notes", type: input.type ?? "page", content, plainText: plain, wordCount: wordCount(plain), icon: input.icon ?? null, properties: input.properties ?? {}, databaseId: input.databaseId ?? null, position: Number(max) + 1, inboxAt: input.inboxAt ?? null, captureKind: input.captureKind ?? null }).returning();24 await afterContentChange(p);25 return p;26}27/** Fields whose change bumps `pages.version` and is protected by optimistic concurrency. */28const VERSIONED = ["title", "content", "properties"] as const;29export type PagePatch = Partial<{ title: string; content: PMNode; icon: string | null; cover: string | null; properties: Record<string, unknown>; parentId: string | null; section: string; position: number; pinned: boolean; archived: boolean; type: string; inboxAt: Date | null }>;30export const conflictPayload = (p: Page) => ({ server: { version: p.version, title: p.title, content: p.content, properties: p.properties, updatedAt: p.updatedAt } });31/**32 * Update a page. When `opts.baseVersion` is given (every interactive save sends it), the write only happens if the row is still at that33 * version: the check and the write are ONE statement, so two sessions can never silently overwrite each other — the loser gets34 * HttpError 409 `conflict` carrying the current server copy, and nothing is written. Callers without a base version (imports, agents after35 * approval, restore) keep "apply on top of whatever is there", but still bump the version so open editors notice.36 */37export async function updatePage(workspaceId: string, id: string, patch: PagePatch, opts: { versionReason?: string; baseVersion?: number } = {}) {38 const prev = await getPage(workspaceId, id);39 if (patch.parentId !== undefined && patch.parentId === id) throw new HttpError(400, "A page cannot be its own parent");40 const versioned = VERSIONED.some((k) => patch[k] !== undefined);41 const set: Record<string, unknown> = { updatedAt: new Date() };42 if (patch.title !== undefined) set.title = patch.title.trim() || "Untitled";43 if (patch.content !== undefined) { const withIds = ensureBlockIds(patch.content).doc; const plain = docText(withIds); set.content = withIds; set.plainText = plain; set.wordCount = wordCount(plain); }44 for (const k of ["icon", "cover", "properties", "parentId", "section", "position", "pinned", "archived", "type", "inboxAt"] as const) if (patch[k] !== undefined) set[k] = patch[k];45 if (versioned) set.version = dsql`${schema.pages.version} + 1`;46 const expect = versioned && opts.baseVersion !== undefined ? opts.baseVersion : null;47 if (expect !== null && prev.version !== expect) throw new HttpError(409, "This note was changed in another session", "conflict", conflictPayload(prev));48 const [p] = await db.update(schema.pages).set(set as any).where(and(eq(schema.pages.id, id), eq(schema.pages.workspaceId, workspaceId), expect !== null ? eq(schema.pages.version, expect) : undefined)).returning();49 if (!p) { const cur = await getPage(workspaceId, id); throw new HttpError(409, "This note was changed in another session", "conflict", conflictPayload(cur)); }50 // Versioning: snapshot the PREVIOUS state when content/title changed and (every 20 versions, or > 10 min since last snapshot, or explicit reason)51 if (patch.content !== undefined || patch.title !== undefined) {52 const [last] = await db.select({ v: schema.pageVersions.version, at: schema.pageVersions.createdAt }).from(schema.pageVersions).where(and(eq(schema.pageVersions.pageId, id), gt(schema.pageVersions.version, 0))).orderBy(desc(schema.pageVersions.version)).limit(1);53 const due = !last || opts.versionReason || prev.version - last.v >= 20 || Date.now() - last.at.getTime() > 10 * 60_000;54 if (due) { await snapshot(prev, opts.versionReason ?? "autosave"); await pruneVersions(id); }55 await afterContentChange(p);56 }57 return p;58}59/** History entries for copies that were never the live state of the page (discarded side of a conflict, closed-tab leftovers) use negative, time-based numbers so they never collide with real versions. */60export const unappliedVersion = () => -Math.floor(Date.now() / 1000);61/** Keep a copy of a page state in the history (idempotent per version number). */62export async function snapshot(p: Pick<Page, "id" | "version" | "title" | "content" | "properties" | "wordCount">, reason: string, version = p.version) {63 await db.insert(schema.pageVersions).values({ pageId: p.id, version, title: p.title, content: p.content, properties: p.properties, reason: reason.slice(0, 100), wordCount: p.wordCount }).onConflictDoNothing();64}65/**66 * Resolve a save conflict. BOTH copies always survive in the version history, whatever the choice:67 * mine → the server copy is snapshotted, then replaced by the local copy;68 * theirs → the local copy is stored as a (non-applied) history entry, the page keeps the server copy;69 * both → the local copy becomes a new sibling page "… (conflict copy)", the page keeps the server copy.70 * `serverVersion` is the version the user was shown; if the page moved again meanwhile, a fresh 409 is returned instead of guessing.71 */72export async function resolveConflict(workspaceId: string, id: string, input: { choice: "mine" | "theirs" | "both"; serverVersion: number; mine: { title?: string; content?: PMNode } }) {73 const cur = await getPage(workspaceId, id);74 if (cur.version !== input.serverVersion) throw new HttpError(409, "The note changed again while you were deciding", "conflict", conflictPayload(cur));75 const mineTitle = input.mine.title?.trim() || cur.title; const mineContent = input.mine.content ?? (cur.content as PMNode); const minePlain = docText(mineContent);76 if (input.choice === "mine") {77 await snapshot(cur, "conflict · other session's copy");78 const p = await updatePage(workspaceId, id, { title: mineTitle, content: mineContent }, { baseVersion: cur.version, versionReason: "conflict · other session's copy" });79 return { page: p, copyId: null as string | null };80 }81 if (input.choice === "theirs") {82 await snapshot({ id, version: unappliedVersion(), title: mineTitle, content: mineContent, properties: cur.properties, wordCount: wordCount(minePlain) }, "conflict · this device's copy (not applied)");83 await pruneVersions(id);84 return { page: cur, copyId: null as string | null };85 }86 const copy = await createPage(workspaceId, { title: `${mineTitle} (conflict copy)`.slice(0, 500), parentId: cur.parentId, section: cur.section, type: cur.type === "page" ? "page" : cur.type, content: mineContent, icon: cur.icon, properties: {} });87 return { page: cur, copyId: copy.id };88}89async function pruneVersions(pageId: string) {90 const old = await db.select({ id: schema.pageVersions.id }).from(schema.pageVersions).where(eq(schema.pageVersions.pageId, pageId)).orderBy(desc(schema.pageVersions.createdAt)).offset(200);91 if (old.length) await db.delete(schema.pageVersions).where(inArray(schema.pageVersions.id, old.map((o) => o.id)));92}93/** Links/backlinks + knowledge edges + async indexing. */94async function afterContentChange(p: Page) {95 const refs = extractPageRefs(p.content as PMNode).filter((r) => r !== p.id);96 await db.delete(schema.links).where(and(eq(schema.links.fromPageId, p.id), eq(schema.links.kind, "link")));97 if (refs.length) {98 const valid = await db.select({ id: schema.pages.id }).from(schema.pages).where(and(inArray(schema.pages.id, refs), eq(schema.pages.workspaceId, p.workspaceId)));99 if (valid.length) {100 await db.insert(schema.links).values(valid.map((v) => ({ fromPageId: p.id, toPageId: v.id, kind: "link" }))).onConflictDoNothing();101 await db.insert(schema.knowledgeEdges).values(valid.map((v) => ({ workspaceId: p.workspaceId, fromId: p.id, toId: v.id, kind: "link", status: "accepted" }))).onConflictDoNothing();102 }103 }104 await db.delete(schema.knowledgeEdges).where(and(eq(schema.knowledgeEdges.fromId, p.id), eq(schema.knowledgeEdges.kind, "link"), refs.length ? dsql`to_id <> all(${pgArr(refs)}::uuid[])` : dsql`true`));105 await enqueue(QUEUES.index, { sourceType: "page", sourceId: p.id, workspaceId: p.workspaceId }, { singletonKey: `page:${p.id}`, singletonSeconds: 20, singletonNextSlot: true }); // at most one indexing per page per 20 s, and an edit inside that window is indexed in the next one — never dropped106}107export async function softDeletePage(workspaceId: string, id: string) {108 const ids = await descendants(workspaceId, id); ids.push(id);109 await db.update(schema.pages).set({ deletedAt: new Date() }).where(inArray(schema.pages.id, ids));110 await db.delete(schema.chunks).where(and(eq(schema.chunks.sourceType, "page"), inArray(schema.chunks.sourceId, ids)));111 return ids.length;112}113export async function restorePage(workspaceId: string, id: string) {114 const ids = await descendants(workspaceId, id, true); ids.push(id);115 await db.update(schema.pages).set({ deletedAt: null }).where(inArray(schema.pages.id, ids));116 for (const pid of ids) await enqueue(QUEUES.index, { sourceType: "page", sourceId: pid, workspaceId });117}118export async function purgePage(workspaceId: string, id: string) {119 const ids = [...(await descendants(workspaceId, id, true)), id];120 await db.delete(schema.chunks).where(and(eq(schema.chunks.sourceType, "page"), inArray(schema.chunks.sourceId, ids)));121 await db.delete(schema.pages).where(and(eq(schema.pages.id, id), eq(schema.pages.workspaceId, workspaceId)));122}123export async function descendants(workspaceId: string, id: string, includeDeleted = false): Promise<string[]> {124 const rows = await db.execute(dsql`with recursive t as (select id from pages where parent_id = ${id} and workspace_id = ${workspaceId} ${includeDeleted ? dsql`` : dsql`and deleted_at is null`} union all select p.id from pages p join t on p.parent_id = t.id ${includeDeleted ? dsql`` : dsql`where p.deleted_at is null`}) select id from t`);125 return (rows as any[]).map((r) => r.id);126}127export async function backlinks(workspaceId: string, id: string) {128 return db.select({ id: schema.pages.id, title: schema.pages.title, icon: schema.pages.icon, section: schema.pages.section, updatedAt: schema.pages.updatedAt }).from(schema.links).innerJoin(schema.pages, eq(schema.pages.id, schema.links.fromPageId)).where(and(eq(schema.links.toPageId, id), eq(schema.pages.workspaceId, workspaceId), isNull(schema.pages.deletedAt), ne(schema.pages.id, id)));129}130export async function breadcrumb(workspaceId: string, id: string) {131 const rows = await db.execute(dsql`with recursive t as (select id, parent_id, title, icon, 0 as d from pages where id = ${id} and workspace_id = ${workspaceId} union all select p.id, p.parent_id, p.title, p.icon, t.d + 1 from pages p join t on p.id = t.parent_id where t.d < 20) select id, title, icon from t order by d desc`);132 return rows as unknown as { id: string; title: string; icon: string | null }[];133}134export async function touchOpened(id: string) { await db.update(schema.pages).set({ lastOpenedAt: new Date() }).where(eq(schema.pages.id, id)); }135export async function duplicatePage(workspaceId: string, id: string) {136 const p = await getPage(workspaceId, id);137 return createPage(workspaceId, { title: `${p.title} (copy)`, parentId: p.parentId, section: p.section, type: p.type, content: p.content as PMNode, icon: p.icon, properties: p.properties as any });138}139