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:
@@ -0,0 +1,75 @@
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import cookie from "@fastify/cookie";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { ZodError } from "zod";
|
||||
import { config } from "./config.js";
|
||||
import { openDb, ensureAdmin } from "./db.js";
|
||||
import { hashPassword, registerAuthHook, registerAuthRoutes } from "./auth.js";
|
||||
import { registerRoutes } from "./routes.js";
|
||||
import { registerWs } from "./ws.js";
|
||||
|
||||
/** A Fastify error carrying a status code and a serializable payload. */
|
||||
export interface HttpError extends Error {
|
||||
statusCode: number;
|
||||
payload: object;
|
||||
}
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyInstance {
|
||||
/** Create a throwable HTTP error: `throw app.httpErrors.create(404, { error: "not_found" })`. */
|
||||
httpErrors: { create(status: number, payload: object): HttpError };
|
||||
}
|
||||
}
|
||||
|
||||
function makeHttpError(status: number, payload: object): HttpError {
|
||||
const e = new Error("http_error") as HttpError;
|
||||
e.statusCode = status;
|
||||
e.payload = payload;
|
||||
return e;
|
||||
}
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({ logger: true });
|
||||
await app.register(cors, { origin: true, credentials: true });
|
||||
await app.register(cookie);
|
||||
await app.register(websocket);
|
||||
|
||||
const db = openDb();
|
||||
app.decorate("db", db);
|
||||
app.decorate("httpErrors", { create: makeHttpError });
|
||||
await ensureAdmin(db, hashPassword);
|
||||
|
||||
// Serialize thrown errors into the API's `{ error: "code" }` shape.
|
||||
app.setErrorHandler((err, _req, reply) => {
|
||||
if (err instanceof ZodError) {
|
||||
return reply.code(400).send({ error: "invalid_input", issues: err.issues });
|
||||
}
|
||||
const status = (err as HttpError).statusCode ?? 500;
|
||||
const payload = (err as HttpError).payload ?? { error: "internal_error" };
|
||||
return reply.code(status).send(payload);
|
||||
});
|
||||
|
||||
app.get("/api/health", async () => {
|
||||
let dbUp = false;
|
||||
try {
|
||||
dbUp = db.prepare("SELECT 1").get() != null;
|
||||
} catch {
|
||||
dbUp = false;
|
||||
}
|
||||
return { ok: dbUp, db: dbUp ? "up" : "down", version: config.version, uptime: process.uptime() };
|
||||
});
|
||||
|
||||
registerAuthHook(app);
|
||||
registerAuthRoutes(app);
|
||||
registerRoutes(app);
|
||||
registerWs(app);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function start() {
|
||||
const app = await buildApp();
|
||||
await app.listen({ port: config.port, host: "0.0.0.0" });
|
||||
return app;
|
||||
}
|
||||
Reference in New Issue
Block a user