SPB Git

Repository Public

adapter.ts 13.2 KB 217 lines typescript

1/**2 * Pure conversions from the curriculum repository's formats to the platform's canonical ones.3 * No filesystem access here (see scripts/lib/importer.ts). Repository content is treated as data:4 * nothing is evaluated, compiled or executed.5 */6import { z } from "zod";7import { Manifest, type Bibliography, type Glossary, type Publication, type Question, type Quiz, type Session } from "./schema";8import { sessionSlug, slugify } from "./urls";910/* ---- Source schemas (what the course repository provides) ---- */1112export const SourceCourse = z.object({13  course: z.object({14    id: z.string(), title: z.string(), short_title: z.string(), tagline: z.string(), subtitle: z.string(),15    language: z.literal("fr-CA"), version: z.coerce.string(), endorsement_notice: z.string(),16  }),17  author: z.object({ name: z.string(), role: z.string(), institution: z.string(), institution_short: z.string(), department: z.string() }),18  parts: z.array(z.object({ id: z.string(), short: z.string(), title: z.string() })).min(1),19  sessions: z.array(z.object({20    id: z.string().regex(/^S\d{2,3}$/), slug: z.string().regex(/^[a-z0-9-]+$/), part: z.string(),21    level: z.enum(["débutant", "intermédiaire", "avancé"]), title: z.string(), short: z.string(),22    depends_on: z.array(z.string()).default([]), tags: z.array(z.string()).default([]), outcomes: z.array(z.string()).default([]),23  })).min(1),24});25export type SourceCourse = z.infer<typeof SourceCourse>;2627/** Only the fields the platform relies on. A session directory being written by someone else may lack any of them. */28export const SourceMetadata = z.object({29  id: z.string(),30  status: z.enum(["planned", "draft", "implemented", "validated"]),31  last_reviewed: z.coerce.string().optional(),32  effort_minutes: z.record(z.string(), z.tuple([z.number(), z.number()])).optional(),33  deliverables: z.object({ video_recorded: z.boolean().optional() }).loose().optional(),34}).loose();35export type SourceMetadata = z.infer<typeof SourceMetadata>;3637const SourceOption = z.object({ id: z.coerce.string(), text: z.coerce.string() });38export const SourceQuiz = z.object({39  session: z.string(),40  title: z.string(),41  passing_score: z.number().int().optional(),42  questions: z.array(z.object({43    id: z.string(), type: z.string(), prompt: z.string(), explanation: z.string(),44    outcome: z.number().int().optional(), level: z.string().optional(),45    options: z.array(SourceOption).optional(),46    answer: z.union([z.string(), z.number(), z.boolean(), z.array(z.coerce.string())]).optional(),47    distractors: z.record(z.string(), z.string()).optional(),48    tolerance: z.number().optional(), unit: z.string().optional(),49    slides: z.array(z.coerce.string()).optional(),50  }).loose()),51});5253export interface Converted<T> { value: T | null; warnings: string[] }5455/** Course quiz YAML → canonical quiz. Unknown question types are skipped with a warning, never guessed. */56export function convertQuiz(raw: unknown): Converted<Quiz> {57  const parsed = SourceQuiz.safeParse(raw);58  if (!parsed.success) return { value: null, warnings: [`quiz illisible : ${parsed.error.issues[0]?.message ?? "format inattendu"}`] };59  const src = parsed.data, warnings: string[] = [], questions: Question[] = [];60  for (const q of src.questions) {61    // Slide references are kept only when they are well-formed identifiers; anything else is dropped, never guessed.62    const slides = [...new Set((q.slides ?? []).filter((s) => /^S\d{2,3}-D\d{2,3}$/.test(s)))].slice(0, 12);63    const base = { id: q.id, prompt: q.prompt, explanation: q.explanation, ...(q.outcome !== undefined ? { outcome: q.outcome } : {}), ...(q.level ? { level: q.level } : {}), ...(slides.length ? { slides } : {}) };64    const options = (q.options ?? []).map((o) => ({ id: o.id, text: o.text, ...(q.distractors?.[o.id] ? { feedback: q.distractors[o.id] } : {}) }));65    const ids = new Set(options.map((o) => o.id));66    if (q.type === "choix-unique") {67      if (typeof q.answer !== "string" || !ids.has(q.answer)) { warnings.push(`${q.id} : réponse absente des options, question ignorée`); continue; }68      questions.push({ ...base, type: "single", options, answer: q.answer });69    } else if (q.type === "choix-multiple") {70      const answers = Array.isArray(q.answer) ? q.answer : [];71      if (!answers.length || !answers.every((a) => ids.has(a))) { warnings.push(`${q.id} : réponses absentes des options, question ignorée`); continue; }72      questions.push({ ...base, type: "multiple", options, answers });73    } else if (q.type === "vrai-faux") {74      let answer: boolean | null = typeof q.answer === "boolean" ? q.answer : null;75      if (typeof q.answer === "string") {76        const text = options.find((o) => o.id === q.answer)?.text ?? q.answer;77        answer = /^vrai$/i.test(text.trim()) ? true : /^faux$/i.test(text.trim()) ? false : null;78      }79      if (answer === null) { warnings.push(`${q.id} : réponse vrai/faux indéterminable, question ignorée`); continue; }80      const wrong = Object.values(q.distractors ?? {})[0];81      questions.push({ ...base, type: "true-false", answer, ...(wrong ? { feedbackWrong: wrong } : {}) });82    } else if (q.type === "numerique" || q.type === "numérique") {83      if (typeof q.answer !== "number") { warnings.push(`${q.id} : réponse numérique absente, question ignorée`); continue; }84      questions.push({ ...base, type: "numeric", answer: q.answer, tolerance: q.tolerance ?? 0, ...(q.unit ? { unit: q.unit } : {}) });85    } else {86      warnings.push(`${q.id} : type « ${q.type} » non pris en charge par l'importateur, question ignorée`);87    }88  }89  if (!questions.length) return { value: null, warnings: [...warnings, "aucune question importable"] };90  return { value: { id: `${src.session}-quiz`, title: src.title, ...(src.passing_score !== undefined ? { passingScore: Math.min(src.passing_score, questions.length) } : {}), questions }, warnings };91}9293const stripMd = (s: string) => s.replace(/\*\*?([^*]+)\*\*?/g, "$1").replace(/`([^`]+)`/g, "$1").trim();9495/** Reads the « Glossaire » table of a session README (| terme français | terme anglais | définition |). */96export function parseGlossary(readme: string, sessionId: string): Converted<Glossary> {97  const lines = readme.split(/\r?\n/);98  const start = lines.findIndex((l) => /^#{1,4}\s+Glossaire/i.test(l));99  if (start < 0) return { value: null, warnings: ["aucune section « Glossaire » dans le README"] };100  const terms: Glossary["terms"] = [], seen = new Set<string>();101  for (const line of lines.slice(start + 1)) {102    if (/^#{1,4}\s/.test(line)) break;103    if (!line.trim().startsWith("|")) continue;104    const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((c) => stripMd(c));105    if (cells.length < 3 || /^-+$/.test(cells[0]!.replace(/[\s:]/g, "")) || /^terme/i.test(cells[0]!)) continue;106    const [term, english, definition] = cells as [string, string, string];107    const id = slugify(term.replace(/\(.*?\)/g, ""));108    if (!id || !definition || seen.has(id)) continue;109    seen.add(id);110    terms.push({ id, term, english: english || null, definition, session: sessionId });111  }112  return terms.length ? { value: { terms }, warnings: [] } : { value: null, warnings: ["tableau du glossaire vide ou illisible"] };113}114115const debrace = (s: string) => s.replace(/[{}]/g, "").replace(/--/g, "–").replace(/\\&/g, "&").replace(/\s+/g, " ").trim();116117/** Minimal BibTeX reader: enough for the reference list (authors, title, year, venue, URL). */118export function parseBibtex(source: string): Bibliography {119  const entries: Bibliography["entries"] = [];120  const re = /@(\w+)\s*\{\s*([^,\s]+)\s*,/g;121  let m: RegExpExecArray | null;122  while ((m = re.exec(source))) {123    const type = m[1]!.toLowerCase();124    if (type === "comment" || type === "string" || type === "preamble") continue;125    // Find the matching closing brace of the entry.126    let depth = 1, i = re.lastIndex;127    for (; i < source.length && depth > 0; i++) { if (source[i] === "{") depth++; else if (source[i] === "}") depth--; }128    const body = source.slice(re.lastIndex, i - 1);129    const fields: Record<string, string> = {};130    const fre = /(\w+)\s*=\s*/g;131    let f: RegExpExecArray | null;132    while ((f = fre.exec(body))) {133      let j = fre.lastIndex, value = "";134      if (body[j] === "{") { let d = 1; j++; const s = j; for (; j < body.length && d > 0; j++) { if (body[j] === "{") d++; else if (body[j] === "}") d--; } value = body.slice(s, j - 1); }135      else if (body[j] === '"') { const e = body.indexOf('"', j + 1); value = body.slice(j + 1, e < 0 ? body.length : e); j = e < 0 ? body.length : e + 1; }136      else { const e = body.slice(j).search(/[,\n]/); value = body.slice(j, e < 0 ? body.length : j + e); j = e < 0 ? body.length : j + e; }137      fields[f[1]!.toLowerCase()] = debrace(value);138      fre.lastIndex = j;139    }140    const authors = (fields.author ?? fields.editor ?? "").split(/\s+and\s+/).filter(Boolean).map((a) => { const [last, first] = a.split(/,\s*/); return first ? `${first} ${last}` : a; }).join(", ");141    let url: string | null = null;142    try { const u = new URL(fields.url ?? ""); if (u.protocol === "https:" || u.protocol === "http:") url = u.toString(); } catch { /* no usable URL */ }143    if (!fields.title) continue;144    entries.push({ key: m[2]!, type, authors, title: fields.title, year: fields.year ?? "s. d.", venue: fields.journal ?? fields.booktitle ?? fields.publisher ?? fields.howpublished ?? null, url });145    re.lastIndex = i;146  }147  return { entries };148}149150/**151 * Accepts only inert SVG: no script, no event handler, no foreignObject, no external reference.152 * Figures are additionally served as images with a locked-down CSP, so this is defence in depth.153 */154export function checkSvg(svg: string): { ok: true; width?: number; height?: number } | { ok: false; reason: string } {155  if (!/<svg[\s>]/i.test(svg)) return { ok: false, reason: "pas un document SVG" };156  if (/<script[\s/>]/i.test(svg)) return { ok: false, reason: "contient un élément script" };157  if (/<foreignObject[\s/>]/i.test(svg)) return { ok: false, reason: "contient un élément foreignObject" };158  if (/\son[a-z]+\s*=/i.test(svg)) return { ok: false, reason: "contient un gestionnaire d'événement" };159  if (/(?:href|src)\s*=\s*["']\s*(?!#|data:image\/(?:png|jpeg);)[^"']/i.test(svg)) return { ok: false, reason: "contient une référence externe" };160  if (/javascript:/i.test(svg) || /<!ENTITY/i.test(svg)) return { ok: false, reason: "contient un contenu actif" };161  const vb = /viewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(svg);162  return vb ? { ok: true, width: Number(vb[1]), height: Number(vb[2]) } : { ok: true };163}164165/* ---- Manifest assembly ---- */166167export interface ImportedSession {168  id: string;169  status: Session["source"]["status"];170  lastReviewed: string | null;171  videoRecorded: boolean;172  effortMinutes: Session["effortMinutes"];173  hash: string;174  sections: Session["sections"];175}176177/**178 * Merges the imported material with the editorial layer. Rules:179 *  - the importer alone never opens anything: default state is `planned` (or `draft` once material exists)180 *    and every imported section is `private`;181 *  - only the editorial layer raises a state or a visibility, and only for sections that were imported.182 */183export function assembleManifest(course: SourceCourse, imported: ImportedSession[], publication: Publication, info: { sourceHash: string; files: number }): Manifest {184  const byId = new Map(imported.map((s) => [s.id, s]));185  const sessions: Session[] = course.sessions.map((src, index) => {186    const imp = byId.get(src.id), ed = publication.sessions[src.id];187    const number = Number(src.id.slice(1)) || index + 1;188    const slug = ed?.slug ?? sessionSlug(number, src.short);189    const hasMaterial = imp && Object.keys(imp.sections).length > 0;190    const sections: Session["sections"] = {};191    for (const [key, ref] of Object.entries(imp?.sections ?? {})) sections[key as keyof Session["sections"]] = { ...ref!, visibility: ed?.sections?.[key as keyof Session["sections"]] ?? "private" };192    return {193      id: src.id, number, slug,194      aliases: [...new Set([src.slug, src.id.toLowerCase(), ...(ed?.aliases ?? [])])].filter((a) => a !== slug),195      part: src.part, level: src.level, title: src.title, short: src.short, outcomes: src.outcomes, dependsOn: src.depends_on, tags: src.tags,196      publication: ed?.publication ?? (hasMaterial ? "draft" : "planned"),197      source: { status: imp?.status ?? "unknown", lastReviewed: imp?.lastReviewed ?? null, videoRecorded: imp?.videoRecorded ?? false, hash: imp?.hash ?? "0".repeat(64) },198      effortMinutes: imp?.effortMinutes ?? null,199      sections, capsules: [], resources: [], revisions: ed?.revisions ?? [],200    };201  });202  return Manifest.parse({203    schemaVersion: 1,204    course: {205      id: course.course.id, title: course.course.title, shortTitle: course.course.short_title, tagline: course.course.tagline, subtitle: course.course.subtitle,206      language: course.course.language, version: course.course.version, endorsementNotice: course.course.endorsement_notice, license: publication.license,207    },208    author: { name: course.author.name, role: course.author.role, institution: course.author.institution, institutionShort: course.author.institution_short, department: course.author.department },209    parts: course.parts,210    sessions,211    diagrams: publication.diagrams,212    exposeTags: publication.exposeTags,213    redirects: publication.redirects,214    import: info,215  });216}217
Files main
Menu

Theme