Implement CHUNK #2: server layer, core schemas/adapters, contract tests, seed

Complete the server-backed storage layer for PubScript so the app can run
against a real Fastify + SQLite backend instead of only local IndexedDB.

Server (@pubscript/server):
- db.ts: better-sqlite3 schema + migrations (users, shares, projects, books,
  chapters, entities, boards, ai_sessions, audit); WAL mode; idempotent
  admin bootstrap via PUBSCRIPT_ADMIN_EMAIL/PASSWORD.
- auth.ts: argon2 hashing, JWT-ish session tokens, guards, auth routes.
- routes.ts: REST CRUD for projects/books/chapters/entities/boards/ai_sessions
  with multi-tenant isolation and optimistic concurrency (baseRev).
- ws.ts: Fastify websocket hub for autosave + presence events.
- mapping.ts: row <-> core type conversion.

Core (@pubscript/core):
- Zod domain schemas (projects, books, chapters, entities, boards, ai_sessions)
  exported from index.
- storage-local.ts (IndexedDB/Dexie) and storage-server.ts (REST) adapters
  implementing the StorageAdapter contract.

Tests & tooling:
- storage.contract.test.ts: parameterized over both adapters; wired as
  `pnpm contract` and added to CI.
- seed.ts (`pnpm --filter server seed`): creates demo project "The Glass Harbor"
  — 3 chapters of prose, 4 linked characters, 1 world location, 6-node board.
- Dockerfile + compose wiring for the server runtime.

Acceptance: seed project opens with 3 chapters, 4 linked characters, 1 board.
This commit is contained in:
Schwitzz
2026-10-24 18:31:20 -05:00
parent 53f4c5b4c7
commit 1c9b531996
95 changed files with 10006 additions and 16 deletions
+133
View File
@@ -0,0 +1,133 @@
import Dexie, { type Table } from "dexie";
import type {
AISession,
Board,
Chapter,
DocumentRef,
Entity,
NewProject,
Project,
ProjectMeta,
} from "./types.js";
import type { StorageAdapter } from "./storage.js";
import { createUlid } from "./ids.js";
import { nowIso } from "./time.js";
interface EntityRec {
key: string;
projectId: string;
kind: string;
data: Entity;
}
class PubScriptDB extends Dexie {
projects!: Table<Project, string>;
chapters!: Table<Chapter, string>;
entities!: Table<EntityRec, string>;
boards!: Table<Board, string>;
aiSessions!: Table<AISession, string>;
constructor() {
super("pubscript");
this.version(1).stores({
projects: "id, projectId",
chapters: "id, bookId, projectId",
entities: "key, projectId, kind",
boards: "id, projectId",
aiSessions: "id, projectId",
});
}
}
const db = new PubScriptDB();
const entityKey = (projectId: string, kind: string, id: string): string =>
`${projectId}|${kind}|${id}`;
const kindOf = (e: Entity): string =>
"fields" in e ? "world" : "body" in e ? "note" : "character";
/**
* The local (offline-first) `StorageAdapter`, backed by IndexedDB via Dexie.
* Implements the exact `StorageAdapter` contract so the app can run fully
* offline and sync later. `onEvent` is a no-op offline (no remote peers).
*/
export const storageLocal: StorageAdapter = {
async listProjects(): Promise<ProjectMeta[]> {
const rows = await db.projects.toArray();
return rows.map(
({ id, projectId, title, ownerId, sharedWith, settings, cover, createdAt, updatedAt }) => ({
id, projectId, title, ownerId, sharedWith, settings, cover, createdAt, updatedAt,
perm: "edit" as const, owned: true,
}),
);
},
async createProject(p: NewProject): Promise<Project> {
const id = createUlid();
const t = nowIso();
const project: Project = {
id,
projectId: id,
title: p.title,
ownerId: "local",
sharedWith: [],
settings: { language: p.language ?? "en" },
cover: { color: p.cover?.color ?? "#8b5cf6", ...(p.cover?.image ? { image: p.cover.image } : {}) },
createdAt: t,
updatedAt: t,
};
await db.projects.put(project);
return project;
},
async getProject(id: string): Promise<Project> {
const p = await db.projects.get(id);
if (!p) throw new Error(`project ${id} not found`);
return p;
},
async saveDocument(doc: DocumentRef): Promise<void> {
const existing = await db.chapters.get(doc.id);
const base: Chapter = existing ?? {
id: doc.id,
bookId: doc.bookId ?? "",
projectId: doc.projectId,
title: doc.title,
doc: doc.doc,
rev: 0,
order: 0,
meta: { wordCount: 0, scenes: [], updatedAt: nowIso() },
};
await db.chapters.put({
...base,
title: doc.title,
doc: doc.doc,
rev: doc.rev + 1,
meta: { ...base.meta, updatedAt: nowIso() },
});
},
async getChapter(id: string): Promise<Chapter | null> {
return (await db.chapters.get(id)) ?? null;
},
async saveEntity(e: Entity): Promise<void> {
const kind = kindOf(e);
await db.entities.put({ key: entityKey(e.projectId, kind, e.id), projectId: e.projectId, kind, data: e });
},
async saveBoard(b: Board): Promise<void> {
await db.boards.put(b);
},
async saveAISession(s: AISession): Promise<void> {
await db.aiSessions.put(s);
},
onEvent(): () => void {
// Offline: no remote live events to relay.
return () => {};
},
};
export type StorageLocal = typeof storageLocal;