/** * Content model shared by the server, the admin app and the public study pages. * Zod schemas here are the single source of truth for what a valid quiz, question, * deck or card looks like. */ import { z } from 'zod'; export const LIMITS = { title: 200, description: 4000, markdown: 20000, option: 4000, topic: 80, tag: 40, tags: 12, options: 10, questionsPerQuiz: 1000, cardsPerDeck: 5000, noteContent: 400000, } as const; export const QUESTION_TYPES = ['single', 'multi'] as const; export type QuestionType = (typeof QUESTION_TYPES)[number]; export const DIFFICULTIES = ['easy', 'medium', 'hard'] as const; export type Difficulty = (typeof DIFFICULTIES)[number]; export const CLASS_COLORS = ['cobalt', 'teal', 'moss', 'amber', 'coral', 'rose', 'plum', 'slate'] as const; export type ClassColor = (typeof CLASS_COLORS)[number]; export const QUESTION_TYPE_LABEL: Record = { single: 'Multiple choice', multi: 'Select all that apply', }; /* ------------------------------------------------------------------ */ /* Stored shapes */ /* ------------------------------------------------------------------ */ export interface Option { id: string; text: string; correct: boolean; /** Optional per-option rationale ("why this is right / wrong"). */ why: string; } export interface Question { id: string; quizId: string; type: QuestionType; stem: string; options: Option[]; rationale: string; topic: string; difficulty: Difficulty; tags: string[]; sortOrder: number; createdAt: number; updatedAt: number; } export interface Card { id: string; deckId: string; front: string; back: string; hint: string; tags: string[]; sortOrder: number; suspended: boolean; /** FSRS state: 0 new, 1 learning, 2 review, 3 relearning. */ state: number; due: number | null; stability: number; difficulty: number; scheduledDays: number; reps: number; lapses: number; lastReview: number | null; createdAt: number; updatedAt: number; } /* ------------------------------------------------------------------ */ /* Input schemas */ /* ------------------------------------------------------------------ */ const tagSchema = z.string().trim().min(1).max(LIMITS.tag); export const optionInputSchema = z.object({ id: z.string().min(1).max(40).optional(), text: z.string().trim().min(1, 'Answer choice is empty').max(LIMITS.option), correct: z.boolean(), why: z.string().max(LIMITS.markdown).optional().default(''), }); export const questionInputSchema = z .object({ id: z.string().min(1).max(40).optional(), type: z.enum(QUESTION_TYPES), stem: z.string().trim().min(1, 'Question text is required').max(LIMITS.markdown), options: z.array(optionInputSchema).min(2, 'Add at least two answer choices').max(LIMITS.options), rationale: z.string().max(LIMITS.markdown).optional().default(''), topic: z.string().trim().max(LIMITS.topic).optional().default(''), difficulty: z.enum(DIFFICULTIES).optional().default('medium'), tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]), }) .superRefine((q, ctx) => { const correct = q.options.filter((o) => o.correct).length; if (q.type === 'single' && correct !== 1) { ctx.addIssue({ code: 'custom', path: ['options'], message: 'Multiple choice needs exactly one correct answer' }); } if (q.type === 'multi' && correct < 1) { ctx.addIssue({ code: 'custom', path: ['options'], message: 'Select-all needs at least one correct answer' }); } }); export type QuestionInput = z.input; export const cardInputSchema = z.object({ id: z.string().min(1).max(40).optional(), front: z.string().trim().min(1, 'Front is required').max(LIMITS.markdown), back: z.string().trim().min(1, 'Back is required').max(LIMITS.markdown), hint: z.string().max(LIMITS.markdown).optional().default(''), tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]), }); export type CardInput = z.input; export const titleSchema = z.string().trim().min(1, 'Title is required').max(LIMITS.title); export const descriptionSchema = z.string().max(LIMITS.description).optional().default(''); export const quizCreateSchema = z.object({ classId: z.string().min(1), folderId: z.string().min(1).nullish(), title: titleSchema, description: descriptionSchema, questions: z.array(questionInputSchema).max(LIMITS.questionsPerQuiz).optional().default([]), }); export const deckCreateSchema = z.object({ classId: z.string().min(1), folderId: z.string().min(1).nullish(), title: titleSchema, description: descriptionSchema, cards: z.array(cardInputSchema).max(LIMITS.cardsPerDeck).optional().default([]), }); /* ------------------------------------------------------------------ */ /* Drafts: lenient shapes used by import previews and AI generation */ /* ------------------------------------------------------------------ */ export interface DraftOption { text: string; correct: boolean; why?: string; } export interface DraftQuestion { type: QuestionType; stem: string; options: DraftOption[]; rationale: string; topic: string; difficulty: Difficulty; tags: string[]; /** Citation for generated questions ("Cardiac lecture, p. 12"). Stored at the end of the rationale on save. */ source?: string; } export interface DraftCard { front: string; back: string; hint?: string; tags: string[]; } export interface QuizDraft { kind: 'quiz'; title: string; description: string; questions: DraftQuestion[]; } export interface DeckDraft { kind: 'deck'; title: string; description: string; cards: DraftCard[]; } export interface NoteDraft { kind: 'note'; title: string; content: string; } export type ContentDraft = QuizDraft | DeckDraft | NoteDraft; export interface Issue { level: 'error' | 'warning'; /** Index of the question / card the issue belongs to; undefined for item-level issues. */ index?: number; field?: string; message: string; } export function validateDraftQuestion(q: DraftQuestion, index: number): Issue[] { const issues: Issue[] = []; const err = (field: string, message: string) => issues.push({ level: 'error', index, field, message }); const warn = (field: string, message: string) => issues.push({ level: 'warning', index, field, message }); if (!q.stem?.trim()) err('stem', 'Question text is missing'); const options = q.options ?? []; if (options.length < 2) err('options', 'Needs at least two answer choices'); if (options.length > LIMITS.options) err('options', `No more than ${LIMITS.options} answer choices`); if (options.some((o) => !o.text?.trim())) err('options', 'An answer choice is empty'); const correct = options.filter((o) => o.correct).length; if (q.type === 'single' && correct !== 1) { err('options', correct === 0 ? 'No correct answer is marked' : 'Multiple choice can only have one correct answer'); } if (q.type === 'multi' && correct < 1) err('options', 'No correct answer is marked'); const seen = new Set(); for (const o of options) { const key = o.text?.trim().toLowerCase(); if (key && seen.has(key)) { warn('options', 'Two answer choices are identical'); break; } if (key) seen.add(key); } if (!q.rationale?.trim() && !options.some((o) => o.why?.trim())) warn('rationale', 'No rationale'); return issues; } export function validateDraftCard(c: DraftCard, index: number): Issue[] { const issues: Issue[] = []; if (!c.front?.trim()) issues.push({ level: 'error', index, field: 'front', message: 'Front is empty' }); if (!c.back?.trim()) issues.push({ level: 'error', index, field: 'back', message: 'Back is empty' }); return issues; } export function validateDraft(draft: ContentDraft): Issue[] { const issues: Issue[] = []; if (!draft.title?.trim()) issues.push({ level: 'error', field: 'title', message: 'Title is required' }); if (draft.kind === 'quiz') { if (draft.questions.length === 0) issues.push({ level: 'error', field: 'questions', message: 'Add at least one question' }); draft.questions.forEach((q, i) => issues.push(...validateDraftQuestion(q, i))); } else if (draft.kind === 'deck') { if (draft.cards.length === 0) issues.push({ level: 'error', field: 'cards', message: 'Add at least one card' }); draft.cards.forEach((c, i) => issues.push(...validateDraftCard(c, i))); } else if (!draft.content?.trim()) { issues.push({ level: 'error', field: 'content', message: 'The note is empty' }); } return issues; } export function blankQuestion(type: QuestionType = 'single'): DraftQuestion { return { type, stem: '', options: [ { text: '', correct: false, why: '' }, { text: '', correct: false, why: '' }, { text: '', correct: false, why: '' }, { text: '', correct: false, why: '' }, ], rationale: '', topic: '', difficulty: 'medium', tags: [], }; } export function blankCard(): DraftCard { return { front: '', back: '', hint: '', tags: [] }; } /** Converts a stored question into the editable draft shape. */ export function questionToDraft(q: Pick): DraftQuestion { return { type: q.type, stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct, why: o.why ?? '' })), rationale: q.rationale, topic: q.topic, difficulty: q.difficulty, tags: [...q.tags], }; } /* ------------------------------------------------------------------ */ /* Scoring */ /* ------------------------------------------------------------------ */ export type SataScoring = 'partial' | 'strict'; export interface ScorableQuestion { type: QuestionType; options: { id: string; correct: boolean }[]; } /** * Scores one question on a 0..1 scale. * - single: 1 if the one selected option is correct. * - multi (partial): NCLEX-style +/- scoring. Each correct pick earns a point, each wrong pick * costs one, floored at zero, divided by the number of correct options. * - multi (strict): all-or-nothing. */ export function scoreQuestion(question: ScorableQuestion, selected: string[], sata: SataScoring = 'partial'): number { const picked = new Set(selected); const correctIds = question.options.filter((o) => o.correct).map((o) => o.id); if (correctIds.length === 0 || picked.size === 0) return 0; if (question.type === 'single') { return picked.size === 1 && correctIds.includes([...picked][0]) ? 1 : 0; } let right = 0; let wrong = 0; for (const id of picked) { if (correctIds.includes(id)) right += 1; else if (question.options.some((o) => o.id === id)) wrong += 1; } if (sata === 'strict') return right === correctIds.length && wrong === 0 ? 1 : 0; return Math.max(0, right - wrong) / correctIds.length; } export function isFullyCorrect(score: number): boolean { return score >= 0.999; } export function percent(score: number, max: number): number { if (!max) return 0; return Math.round((score / max) * 100); } /* ------------------------------------------------------------------ */ /* Misc helpers */ /* ------------------------------------------------------------------ */ /** Deterministic shuffle (mulberry32) so a saved session can be reproduced from its seed. */ export function seededShuffle(items: readonly T[], seed: number): T[] { const out = [...items]; let s = seed >>> 0; const rand = () => { s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; for (let i = out.length - 1; i > 0; i -= 1) { const j = Math.floor(rand() * (i + 1)); [out[i], out[j]] = [out[j], out[i]]; } return out; } export function optionLetter(index: number): string { return String.fromCharCode(65 + index); }