Repository Public
1// /api/v1 — modèles de courriel : lecture, rendu, et résolution pour l'envoi par modèle (POST /messages/send avec template_id).2// Les modèles appartiennent à un utilisateur : une session voit les siens, une clé voit ceux de la personne qui l'a créée.3import { z } from "zod"4import { sql } from "../db.js"5import type { Principal } from "../keys.js"6import { getTemplate, renderRow } from "../templates.js"7import { bad } from "../util.js"8import { route } from "./registry.js"910function ownerOf(p: Principal): string {11 const id = p.type === "user" ? p.userId : p.createdBy12 if (!id) throw bad("not_found", 404, "This key has no owner and therefore no template library")13 return id14}1516const zVariable = z.object({ name: z.string(), description: z.string(), example: z.string(), required: z.boolean() })17const zTemplateSummary = z.object({18 id: z.string(), name: z.string(), category: z.string(), subject: z.string(), preheader: z.string(), variables: z.array(zVariable),19 source: z.enum(["manual", "ai"]), version: z.number(), size_bytes: z.number(), created_at: z.string(), updated_at: z.string(),20})21const zTemplate = zTemplateSummary.extend({ html: z.string(), text: z.string() })22const zRendered = z.object({ subject: z.string(), preheader: z.string(), html: z.string(), text: z.string(), missing: z.array(z.string()) })23const iso = (d: unknown) => new Date(d as string).toISOString()24const summary = (r: Record<string, any>) => ({25 id: r.id, name: r.name, category: r.category, subject: r.subject, preheader: r.preheader, variables: r.variables, source: r.source, version: r.version,26 size_bytes: Number(r.size_bytes ?? Buffer.byteLength(r.html ?? "")), created_at: iso(r.created_at), updated_at: iso(r.updated_at),27})2829/** Rend un modèle pour l'envoi : toutes les variables requises doivent être fournies (aucun exemple n'est substitué dans un vrai courriel). */30export async function renderForSend(p: Principal, templateId: string, values: Record<string, string>) {31 const row = await getTemplate(ownerOf(p), templateId).catch(() => { throw bad("unknown_template", 404, "Unknown template") })32 const declared = new Set((row.variables as { name: string }[]).map((v) => v.name))33 const unknown = Object.keys(values).filter((k) => !declared.has(k))34 if (unknown.length) throw bad("unknown_variables", 400, "These variables are not used by the template", { variables: unknown })35 const out = renderRow(row, values, false)36 if (out.missing.length) throw bad("missing_variables", 400, "Required template variables are missing", { variables: out.missing })37 return out38}3940route({41 method: "GET", path: "/templates", tag: "Templates", summary: "List the templates of the caller's library", scopes: ["mail.send", "mail.drafts"],42 response: z.object({ templates: z.array(zTemplateSummary) }),43 handler: async ({ principal }) => {44 const rows = await sql`select id, name, category, subject, preheader, variables, source, version, octet_length(html) as size_bytes, created_at, updated_at45 from templates where user_id = ${ownerOf(principal)} and archived_at is null order by updated_at desc limit 500`46 return { templates: rows.map(summary) }47 },48})4950route({51 method: "GET", path: "/templates/{id}", tag: "Templates", summary: "Get a template with its HTML and plain text", scopes: ["mail.send", "mail.drafts"],52 params: z.object({ id: z.string().uuid() }), response: zTemplate,53 handler: async ({ principal, params }) => {54 const r = await getTemplate(ownerOf(principal), params.id)55 return { ...summary(r), html: r.html, text: r.text_body }56 },57})5859route({60 method: "POST", path: "/templates/{id}/render", tag: "Templates", summary: "Render a template with variable values, without sending",61 description: "Values are HTML-escaped; a value placed in an href/src attribute must be an http(s) or mailto URL, otherwise it becomes `#`. With `use_examples` (default false) missing variables take their example value.",62 scopes: ["mail.send", "mail.drafts"], params: z.object({ id: z.string().uuid() }),63 body: z.object({ variables: z.record(z.string(), z.string().max(20_000)).default({}), use_examples: z.boolean().default(false) }).strict(), response: zRendered,64 handler: async ({ principal, params, body }) => renderRow(await getTemplate(ownerOf(principal), params.id), body.variables, body.use_examples),65})66