Add HTTP routes, app wiring, V1 migration, backups, templates and API tests

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:22:47 -07:00
parent 3e74ecd843
commit eae109c166
11 changed files with 2085 additions and 1 deletions

71
server/main.ts Normal file
View file

@ -0,0 +1,71 @@
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 { 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> {
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)`);
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);
});