Study/server/main.ts
Elijah ccdad9728b
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 33s
Add drag reordering, exam deadlines, frozen shared quizzes, batched OCR and semantic search
- Drag-to-reorder for class materials, folders, quiz questions and deck cards. Pointer-based
  so touch works, plus keyboard (arrows/Home/End) with screen-reader announcements.
- Timed exams get a wall-clock deadline. The server refuses late answers, submits overdue
  exams with what was saved, and the countdown keeps running while the page is closed.
- Shared quiz sessions keep a frozen copy of their questions and flag later owner edits.
- Scanned PDFs are read in cached 8-page batches with real page numbers (pdf-lib), removing
  the 30 MB whole-file limit. Compatible providers now receive PDFs as file parts.
- Semantic search: embeddings for OpenAI, Gemini, Ollama and compatible servers, background
  indexing into chunk_vectors (migration 2), hybrid keyword + vector ranking for search, the
  assistant and focused generation, and a Settings -> AI section.

181 tests pass locally and in the Docker test stage on Node 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:48:20 -07:00

79 lines
3 KiB
TypeScript

import { serve } from '@hono/node-server';
import { tidyDrafts } from './ai/generate.ts';
import { createApp } from './app.ts';
import { initAuth } from './auth.ts';
import { loadConfig } from './config.ts';
import { openDatabase } from './db.ts';
import type { AppContext } from './http.ts';
import { APP_VERSION } from './routes/data.ts';
import { startBackupSchedule } from './services/backup.ts';
import { resumeQueue } from './services/documents.ts';
import { scheduleIndexing } from './services/semantic.ts';
import { seedTemplates } from './services/templates.ts';
function log(level: 'info' | 'warn' | 'error', message: string, extra?: unknown): void {
const line = `${new Date().toISOString()} ${level.toUpperCase().padEnd(5)} ${message}`;
const detail = extra instanceof Error ? (extra.stack ?? extra.message) : extra !== undefined ? JSON.stringify(extra) : '';
(level === 'error' ? console.error : console.log)(detail ? `${line}\n${detail}` : line);
}
async function main(): Promise<void> {
// Optional .env file for running outside Docker. Real environment variables always win.
try {
process.loadEnvFile('.env');
} catch {
/* no .env file: that is the normal case in a container */
}
const config = loadConfig();
log('info', `Study Desk ${APP_VERSION} starting (data: ${config.dataDir})`);
const { db, report } = openDatabase(config.dbPath, config.backupsDir);
if (report.applied.length > 0) log('info', `Database migrated: ${report.applied.join(', ')}${report.backup ? ` (backup: ${report.backup})` : ''}`);
const app: AppContext = { db, config, log };
await initAuth(app);
seedTemplates(db);
tidyDrafts(db);
const resumed = resumeQueue(app);
if (resumed > 0) log('info', `Resuming processing of ${resumed} document(s)`);
scheduleIndexing(app);
const stopBackups = startBackupSchedule(app);
const server = serve({ fetch: createApp(app).fetch, port: config.port, hostname: config.host }, (info) => {
log('info', `Listening on http://${info.address === '::' || info.address === '0.0.0.0' ? 'localhost' : info.address}:${info.port}`);
if (!config.webDir) log('warn', 'No built web app found (dist/web). API only: use the Vite dev server for the UI.');
});
let closing = false;
const shutdown = (signal: string) => {
if (closing) return;
closing = true;
log('info', `${signal} received, shutting down`);
stopBackups();
server.close(() => {
try {
db.close();
} catch {
/* already closed */
}
process.exit(0);
});
// Do not let an open event stream hold the process forever.
setTimeout(() => {
try {
db.close();
} catch {
/* ignore */
}
process.exit(0);
}, 5000).unref();
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('unhandledRejection', (reason) => log('error', 'Unhandled promise rejection', reason));
}
main().catch((err) => {
log('error', 'Failed to start', err);
process.exit(1);
});