V1 remains intact on main and in history. This branch replaces it with a new application: node:sqlite storage with migrations, scrypt auth and sessions, content/SRS/attempt/stats services, document extraction and chunking, a provider-neutral AI layer (OpenAI, Anthropic, Gemini, OpenAI-compatible, Ollama), the generation pipeline and the tool-using assistant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
63 lines
2 KiB
TypeScript
63 lines
2 KiB
TypeScript
import type { Context } from 'hono';
|
|
import { z } from 'zod';
|
|
import type { Config } from './config.ts';
|
|
import type { DB } from './db.ts';
|
|
|
|
/** Everything a route needs. Built once in main.ts (or per test). */
|
|
export interface AppContext {
|
|
db: DB;
|
|
config: Config;
|
|
log: (level: 'info' | 'warn' | 'error', message: string, extra?: unknown) => void;
|
|
}
|
|
|
|
export class HttpError extends Error {
|
|
status: number;
|
|
code: string;
|
|
details?: unknown;
|
|
constructor(status: number, code: string, message: string, details?: unknown) {
|
|
super(message);
|
|
this.name = 'HttpError';
|
|
this.status = status;
|
|
this.code = code;
|
|
this.details = details;
|
|
}
|
|
}
|
|
|
|
export const notFound = (what = 'Item') => new HttpError(404, 'not_found', `${what} not found`);
|
|
export const badRequest = (message: string, details?: unknown) => new HttpError(400, 'bad_request', message, details);
|
|
export const conflict = (message: string) => new HttpError(409, 'conflict', message);
|
|
|
|
export interface FieldIssue {
|
|
path: string;
|
|
message: string;
|
|
}
|
|
|
|
export function zodIssues(error: z.ZodError): FieldIssue[] {
|
|
return error.issues.map((i) => ({ path: i.path.join('.'), message: i.message }));
|
|
}
|
|
|
|
export function parse<S extends z.ZodType>(schema: S, data: unknown): z.output<S> {
|
|
const result = schema.safeParse(data);
|
|
if (!result.success) {
|
|
const issues = zodIssues(result.error);
|
|
const first = issues[0];
|
|
throw new HttpError(422, 'validation', first ? `${first.path ? `${first.path}: ` : ''}${first.message}` : 'Invalid input', issues);
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
export async function readBody<S extends z.ZodType>(c: Context, schema: S): Promise<z.output<S>> {
|
|
let json: unknown;
|
|
try {
|
|
json = await c.req.json();
|
|
} catch {
|
|
throw badRequest('Request body must be JSON');
|
|
}
|
|
return parse(schema, json);
|
|
}
|
|
|
|
export const idParam = (c: Context, name = 'id'): string => {
|
|
const v = c.req.param(name);
|
|
if (!v || v.length > 64) throw badRequest('Invalid id');
|
|
return v;
|
|
};
|