import { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm'; import { db, tables } from './db/index.ts'; import { insertIndexedScene, lastOpenedScene } from './manuscript.ts'; import { clearProject, indexNote, reindexBook } from './search.ts'; /** * The Digital Rust failure accents that storylines and note types share, worn on * a project card. */ export const PROJECT_ACCENTS = [ { value: 'rust', label: 'Rust' }, { value: 'dead-thread', label: 'Dead Thread' }, { value: 'stack-overglow', label: 'Stack Overglow' }, { value: 'blue-screen', label: 'Blue Screen' }, { value: 'fractured-shell', label: 'Fractured Shell' }, { value: 'memory-leek', label: 'Memory Leek' }, { value: 'thermal-throttle', label: 'Thermal Throttle' } ] as const; export const DEFAULT_PROJECT_ACCENT = 'rust'; export type ProjectDetails = { title: string; subtitle?: string; description?: string; author?: string; accent?: string; }; export class ProjectDetailsError extends Error { constructor(message: string) { super(message); this.name = 'ProjectDetailsError'; } } const MAX_TITLE = 120; const MAX_SUBTITLE = 160; const MAX_AUTHOR = 120; const MAX_DESCRIPTION = 600; export type ProjectCard = { role: 'owner' | 'co_author' | 'reader'; id: string; title: string; subtitle: string | null; description: string | null; author: string | null; accent: string; isExample: boolean; updatedAt: Date; books: number; scenes: number; words: number; /** The scene left open last, so the card resumes it instead of starting over. */ resumed: ReturnType; /** * The file the project was imported from, and whether this instance still * holds a copy. Null for a project that was never imported. */ importedFrom: { name: string; source: boolean } | null; }; /** * Totals are computed in SQL rather than loaded and summed, so a project with a * hundred thousand words still opens the library instantly. */ export function listProjects(ownerId: string): ProjectCard[] { const rows = db .select({ id: tables.project.id, role: tables.projectMember.role, title: tables.project.title, subtitle: tables.project.subtitle, description: tables.project.description, author: tables.project.author, accent: tables.project.accent, isExample: tables.project.isExample, updatedAt: tables.project.updatedAt, books: sql`( select count(*) from ${tables.book} where ${tables.book.projectId} = ${tables.project.id} and ${tables.book.deletedAt} is null )`, scenes: sql`( select count(*) from ${tables.scene} join ${tables.chapter} on ${tables.chapter.id} = ${tables.scene.chapterId} join ${tables.book} on ${tables.book.id} = ${tables.chapter.bookId} left join ${tables.part} on ${tables.part.id} = ${tables.chapter.partId} where ${tables.book.projectId} = ${tables.project.id} and ${tables.scene.deletedAt} is null and ${tables.chapter.deletedAt} is null and ${tables.book.deletedAt} is null and ${tables.part.deletedAt} is null and (${tables.chapter.partId} is null or ${tables.part.bookId} = ${tables.book.id}) )`, importedName: tables.importReport.sourceName, importedSource: tables.importReport.sourceId, words: sql`coalesce(( select sum(${tables.scene.wordCount}) from ${tables.scene} join ${tables.chapter} on ${tables.chapter.id} = ${tables.scene.chapterId} join ${tables.book} on ${tables.book.id} = ${tables.chapter.bookId} left join ${tables.part} on ${tables.part.id} = ${tables.chapter.partId} where ${tables.book.projectId} = ${tables.project.id} and ${tables.scene.deletedAt} is null and ${tables.chapter.deletedAt} is null and ${tables.book.deletedAt} is null and ${tables.part.deletedAt} is null and (${tables.chapter.partId} is null or ${tables.part.bookId} = ${tables.book.id}) ), 0)` }) .from(tables.project) .innerJoin(tables.projectMember, eq(tables.projectMember.projectId, tables.project.id)) .leftJoin(tables.importReport, eq(tables.importReport.projectId, tables.project.id)) .where(and(eq(tables.projectMember.userId, ownerId), isNull(tables.project.deletedAt))) .orderBy(sql`${tables.project.updatedAt} desc`) .all(); return rows.map(({ importedName, importedSource, ...row }) => ({ ...row, books: Number(row.books), scenes: Number(row.scenes), words: Number(row.words), resumed: lastOpenedScene(row.id), importedFrom: importedName === null ? null : { name: importedName.trim() || 'the imported file', source: importedSource !== null } })); } export function createProject(ownerId: string, title: string): string { const id = crypto.randomUUID(); const now = new Date(); db.transaction((tx) => { tx.insert(tables.project).values({ id, ownerId, title, createdAt: now, updatedAt: now }).run(); tx.insert(tables.projectMember) .values({ id: crypto.randomUUID(), projectId: id, userId: ownerId, role: 'owner', createdAt: now }) .run(); // A new project starts with a book, a chapter and a scene, so the writer lands // on a page they can type into instead of a form. const bookId = crypto.randomUUID(); const chapterId = crypto.randomUUID(); tx.insert(tables.book) .values({ id: bookId, projectId: id, title: title, ordinal: 0, createdAt: now, updatedAt: now }) .run(); tx.insert(tables.chapter) .values({ id: chapterId, bookId, title: 'Chapter 1', ordinal: 0, createdAt: now, updatedAt: now }) .run(); insertIndexedScene(tx, { chapterId, title: 'Scene 1', ordinal: 0, createdAt: now, updatedAt: now }); }); return id; } /** * Gives every project's owner a membership row, because access is decided from * that row: a project whose row is missing, such as one written by an older * build, is invisible to its own owner. Runs at boot, and costs one scan of the * project table on a consistent instance. */ export function ensureOwnerMembership() { const orphans = db .select({ projectId: tables.project.id, ownerId: tables.project.ownerId }) .from(tables.project) .where( sql`not exists ( select 1 from ${tables.projectMember} where ${tables.projectMember.projectId} = ${tables.project.id} and ${tables.projectMember.userId} = ${tables.project.ownerId} )` ) .all(); for (const row of orphans) { db.insert(tables.projectMember) .values({ id: crypto.randomUUID(), projectId: row.projectId, userId: row.ownerId, role: 'owner', createdAt: new Date() }) .onConflictDoNothing() .run(); } } /** * The caller has already checked that this writer can write to the project. An * empty field is stored as null, because every reader tests for null to decide * whether it has something to show. */ export function updateProjectDetails(projectId: string, input: ProjectDetails) { const title = input.title.trim().slice(0, MAX_TITLE); if (title.length === 0) throw new ProjectDetailsError('A project needs a name.'); db.update(tables.project) .set({ title, subtitle: field(input.subtitle, MAX_SUBTITLE), description: field(input.description, MAX_DESCRIPTION), author: field(input.author, MAX_AUTHOR), accent: readAccent(input.accent), updatedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run(); } function field(value: string | undefined, max: number): string | null { const text = (value ?? '').trim().slice(0, max); return text.length > 0 ? text : null; } function readAccent(value: string | undefined): string { const known = PROJECT_ACCENTS.find((accent) => accent.value === value); return known?.value ?? DEFAULT_PROJECT_ACCENT; } /** * The caller has already checked that this writer owns the project, because * deleting takes it from everyone else in it. */ export function deleteProject(projectId: string) { db.transaction(() => { db.update(tables.project) .set({ deletedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run(); clearProject(projectId); }); } /** * The caller has already checked ownership and that the project is in the trash. * Membership and child rows cascade from the project row. Upload files stay on * disk until `prune-uploads` runs, because a copy can share an image id. */ export function purgeProject(projectId: string) { db.transaction(() => { const project = db .select({ deletedAt: tables.project.deletedAt }) .from(tables.project) .where(eq(tables.project.id, projectId)) .get(); if (!project?.deletedAt) { throw new Error('Only a project in the trash can be deleted forever.'); } clearProject(projectId); db.delete(tables.project).where(eq(tables.project.id, projectId)).run(); }); } export function listDeletedProjects(userId: string) { return db .select({ id: tables.project.id, title: tables.project.title, deletedAt: tables.project.deletedAt }) .from(tables.project) .innerJoin(tables.projectMember, eq(tables.projectMember.projectId, tables.project.id)) .where( and( eq(tables.projectMember.userId, userId), eq(tables.projectMember.role, 'owner'), isNotNull(tables.project.deletedAt) ) ) .orderBy(desc(tables.project.deletedAt)) .all(); } export function restoreProject(projectId: string) { db.transaction(() => { db.update(tables.project) .set({ deletedAt: null, updatedAt: new Date() }) .where(eq(tables.project.id, projectId)) .run(); for (const book of db .select() .from(tables.book) .where(eq(tables.book.projectId, projectId)) .all()) { reindexBook(book.id); } for (const note of db .select() .from(tables.note) .where(eq(tables.note.projectId, projectId)) .all()) { indexNote(note.id); } }); }