Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/server/themes.ts9 * Module : studio10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Thèmes : brouillons (chaque enregistrement est une révision), versions immuables numérotées,43// diffusion progressive par application et plateforme, retour arrière.44import { type AppConfig, brandDocument, defaultAppConfig } from '../../server/km-maps/lib/brand.ts';45import { sha256hex } from '../../server/km-maps/lib/http.ts';46import { APPS, PLATFORMS } from '../../server/km-maps/lib/rollout.ts';47import { parseSemver } from '../../server/km-maps/lib/semver.ts';48import { type Actor, audit, bumpRevision, type Db, HttpError, type Tx, tx } from './db.ts';49import { diffDocs, validateTheme } from './validate.ts';5051export type Target = { app: string; platform: string };52export const ALL_TARGETS: Target[] = APPS.flatMap((app) => PLATFORMS.map((platform) => ({ app, platform })));5354export function parseTargets(v: unknown): Target[] {55 if (v === undefined || v === null || v === 'all') return ALL_TARGETS;56 if (!Array.isArray(v) || v.length === 0) throw new HttpError(400, 'targets : liste de {app, platform} ou "all"');57 const out: Target[] = [];58 for (const t of v) {59 if (!(APPS as readonly string[]).includes(t?.app) || !(PLATFORMS as readonly string[]).includes(t?.platform)) throw new HttpError(400, `cible inconnue : ${JSON.stringify(t)}`);60 if (!out.some((x) => x.app === t.app && x.platform === t.platform)) out.push({ app: t.app, platform: t.platform });61 }62 return out;63}6465export function parsePercent(v: unknown): number {66 if (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 100) throw new HttpError(400, 'percent : entier de 0 à 100');67 return v as number;68}6970const THEME_ID = /^[a-z][a-z0-9-]{1,30}$/;7172/** Sérialisation à clés triées : compare deux valeurs JSON sans dépendre de l'ordre des clés (jsonb le change). */73export function canon(v: unknown): string {74 if (Array.isArray(v)) return `[${v.map(canon).join(',')}]`;75 if (v !== null && typeof v === 'object') return `{${Object.keys(v as object).sort().map((k) => `${JSON.stringify(k)}:${canon((v as any)[k])}`).join(',')}}`;76 return JSON.stringify(v);77}7879async function currentApps(c: Tx | Db['pool'], schema: string): Promise<Map<string, { rev: number; config: AppConfig }>> {80 const r = await c.query(`SELECT DISTINCT ON (app) app, id, config FROM ${schema}.app_config_rev ORDER BY app, id DESC`);81 return new Map(r.rows.map((x: any) => [x.app, { rev: x.id, config: x.config }]));82}8384/** Un thème doit rester lisible avec la marque de chaque application qui l'active. */85async function checkBrands(c: Tx | Db['pool'], schema: string, themeId: string, doc: unknown) {86 for (const [app, { config }] of await currentApps(c, schema)) {87 if (!config.themes.includes(themeId)) continue;88 const r = await validateTheme(doc, brandDocument(app, config));89 if (!r.ok) throw new HttpError(422, `thème incompatible avec la marque ${app}`, { errors: r.errors });90 }91}9293export async function listThemes(db: Db) {94 const s = db.schema;95 const [themes, versions, drafts, channels] = await Promise.all([96 db.pool.query(`SELECT id, title, created_at, created_by, archived_at FROM ${s}.theme ORDER BY archived_at IS NOT NULL, id`),97 db.pool.query(`SELECT theme_id, max(version) AS latest, count(*)::int AS n, max(created_at) AS at FROM ${s}.theme_version GROUP BY theme_id`),98 db.pool.query(`SELECT DISTINCT ON (theme_id) theme_id, id, created_at, author_name, base_version FROM ${s}.theme_draft ORDER BY theme_id, id DESC`),99 db.pool.query(`SELECT theme_id, app, platform, stable_version, candidate_version, candidate_percent FROM ${s}.channel`),100 ]);101 return themes.rows.map((t) => {102 const v = versions.rows.find((x) => x.theme_id === t.id);103 const d = drafts.rows.find((x) => x.theme_id === t.id);104 const vAt = v ? new Date(v.at).getTime() : 0;105 return {106 ...t,107 latestVersion: v?.latest ?? null,108 versions: v?.n ?? 0,109 draft: d ? { id: d.id, at: d.created_at, author: d.author_name, unpublished: new Date(d.created_at).getTime() > vAt } : null,110 channels: channels.rows.filter((c) => c.theme_id === t.id).map(({ theme_id, ...c }) => c),111 };112 });113}114115export async function getTheme(db: Db, id: string) {116 const s = db.schema;117 const t = (await db.pool.query(`SELECT id, title, created_at, created_by, archived_at FROM ${s}.theme WHERE id = $1`, [id])).rows[0];118 if (!t) throw new HttpError(404, 'thème inconnu');119 const [versions, drafts, channels, events] = await Promise.all([120 db.pool.query(`SELECT version, sha256, min_engine, note, author_name, draft_id, created_at, octet_length(doc_text) AS bytes FROM ${s}.theme_version WHERE theme_id = $1 ORDER BY version DESC`, [id]),121 db.pool.query(`SELECT id, note, author_name, base_version, created_at FROM ${s}.theme_draft WHERE theme_id = $1 ORDER BY id DESC LIMIT 100`, [id]),122 db.pool.query(`SELECT app, platform, stable_version, candidate_version, candidate_percent, updated_at, updated_by FROM ${s}.channel WHERE theme_id = $1 ORDER BY app, platform`, [id]),123 db.pool.query(`SELECT id, at, app, platform, action, version, percent, prev_stable, prev_candidate, prev_percent, author_name, note FROM ${s}.rollout_event WHERE theme_id = $1 ORDER BY id DESC LIMIT 200`, [id]),124 ]);125 const latestVersion = versions.rows[0]?.version ?? null;126 const head = drafts.rows[0] ?? null;127 // Document de travail : le dernier brouillon s'il est plus récent que la dernière version, sinon cette version.128 let doc: any = null;129 let docSource: any = null;130 const publishedDraft = versions.rows[0]?.draft_id ?? 0;131 if (head && head.id > publishedDraft) {132 doc = (await db.pool.query(`SELECT doc FROM ${s}.theme_draft WHERE id = $1`, [head.id])).rows[0].doc;133 docSource = { kind: 'draft', id: head.id };134 } else if (latestVersion !== null) {135 doc = JSON.parse((await db.pool.query(`SELECT doc_text FROM ${s}.theme_version WHERE theme_id = $1 AND version = $2`, [id, latestVersion])).rows[0].doc_text);136 docSource = { kind: 'version', version: latestVersion };137 }138 return { theme: t, doc, docSource, latestVersion, versions: versions.rows, drafts: drafts.rows, channels: channels.rows, events: events.rows };139}140141export async function getVersionDoc(db: Db, id: string, version: number): Promise<any> {142 const r = await db.pool.query(`SELECT doc_text FROM ${db.schema}.theme_version WHERE theme_id = $1 AND version = $2`, [id, version]);143 if (!r.rows[0]) throw new HttpError(404, 'version inconnue');144 return JSON.parse(r.rows[0].doc_text);145}146147export async function getDraftDoc(db: Db, id: string, draftId: number): Promise<any> {148 const r = await db.pool.query(`SELECT doc FROM ${db.schema}.theme_draft WHERE theme_id = $1 AND id = $2`, [id, draftId]);149 if (!r.rows[0]) throw new HttpError(404, 'brouillon inconnu');150 return r.rows[0].doc;151}152153export async function createTheme(db: Db, actor: Actor, body: any) {154 const id = body?.id;155 const title = String(body?.title ?? '').trim();156 if (typeof id !== 'string' || !THEME_ID.test(id)) throw new HttpError(400, 'identifiant : minuscules, chiffres et tirets (2 à 31 caractères)');157 if (title.length < 2 || title.length > 80) throw new HttpError(400, 'titre : 2 à 80 caractères');158 let doc: any;159 if (body.copyFrom) {160 const src = await getTheme(db, String(body.copyFrom));161 if (!src.doc) throw new HttpError(400, 'le thème source est vide');162 doc = { ...src.doc, name: id, version: '0.0.0' };163 delete doc._description;164 } else if (body.doc) doc = body.doc;165 else throw new HttpError(400, 'copyFrom ou doc requis');166 if (doc?.name !== id) throw new HttpError(422, 'document invalide', { errors: [{ source: 'schema', path: 'name', message: `doit valoir « ${id} »` }] });167 const v = await validateTheme(doc);168 if (!v.ok) throw new HttpError(422, 'document invalide', { errors: v.errors });169 return tx(db, async (c) => {170 const ex = await c.query(`SELECT 1 FROM ${db.schema}.theme WHERE id = $1`, [id]);171 if (ex.rows[0]) throw new HttpError(409, 'cet identifiant existe déjà');172 await c.query(`INSERT INTO ${db.schema}.theme (id, title, created_by) VALUES ($1, $2, $3)`, [id, title, actor.name]);173 const d = await c.query(`INSERT INTO ${db.schema}.theme_draft (theme_id, doc, note, author_id, author_name) VALUES ($1, $2, $3, $4, $5) RETURNING id`, [id, JSON.stringify(doc), body.copyFrom ? `copie de ${body.copyFrom}` : 'création', actor.id, actor.name]);174 await audit(c, db.schema, actor, 'theme.create', id, { title, copyFrom: body.copyFrom ?? null });175 return { id, draftId: d.rows[0].id };176 });177}178179export async function saveDraft(db: Db, actor: Actor, id: string, body: any) {180 const doc = body?.doc;181 const note = String(body?.note ?? '').slice(0, 500);182 const theme = (await db.pool.query(`SELECT id, archived_at FROM ${db.schema}.theme WHERE id = $1`, [id])).rows[0];183 if (!theme) throw new HttpError(404, 'thème inconnu');184 if (theme.archived_at) throw new HttpError(409, 'thème archivé');185 if (doc?.name !== id) throw new HttpError(422, 'document invalide', { errors: [{ source: 'schema', path: 'name', message: `doit valoir « ${id} »` }] });186 const v = await validateTheme(doc);187 if (!v.ok) throw new HttpError(422, 'document invalide', { errors: v.errors });188 return tx(db, async (c) => {189 const base = await c.query(`SELECT max(version) AS v FROM ${db.schema}.theme_version WHERE theme_id = $1`, [id]);190 const d = await c.query(`INSERT INTO ${db.schema}.theme_draft (theme_id, doc, note, author_id, author_name, base_version) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, created_at`, [id, JSON.stringify(doc), note, actor.id, actor.name, base.rows[0].v]);191 await audit(c, db.schema, actor, 'theme.draft', id, { draft: d.rows[0].id, note });192 return { draftId: d.rows[0].id, at: d.rows[0].created_at, warnings: v.warnings };193 });194}195196/** Écrit l'état des canaux visés et journalise chaque changement. Dans la transaction de l'appelant. */197async function applyChannels(c: Tx, schema: string, actor: Actor, themeId: string, targets: Target[], action: 'publish' | 'rollout' | 'rollback' | 'seed', version: number, percent: number, note: string) {198 const changed: any[] = [];199 for (const t of targets) {200 const cur = (await c.query(`SELECT stable_version, candidate_version, candidate_percent FROM ${schema}.channel WHERE theme_id = $1 AND app = $2 AND platform = $3 FOR UPDATE`, [themeId, t.app, t.platform])).rows[0] ?? { stable_version: null, candidate_version: null, candidate_percent: 0 };201 let next = { stable: cur.stable_version as number | null, candidate: cur.candidate_version as number | null, percent: cur.candidate_percent as number };202 let act: string = action;203 if (action === 'rollback' || action === 'seed') next = { stable: version, candidate: null, percent: 0 };204 else if (percent >= 100) {205 next = { stable: version, candidate: null, percent: 0 };206 if (action === 'rollout') act = 'promote';207 } else if (percent === 0) {208 if (action === 'publish') continue; // publiée, pas encore diffusée sur ce canal209 if (next.candidate !== version) continue;210 next = { stable: next.stable, candidate: null, percent: 0 };211 act = 'cancel';212 } else {213 if (next.stable === version) throw new HttpError(409, `la version ${version} est déjà la version stable de ${t.app}/${t.platform}`);214 next = { stable: next.stable, candidate: version, percent };215 }216 if (next.stable === cur.stable_version && next.candidate === cur.candidate_version && next.percent === cur.candidate_percent) continue;217 await c.query(218 `INSERT INTO ${schema}.channel (theme_id, app, platform, stable_version, candidate_version, candidate_percent, updated_by) VALUES ($1, $2, $3, $4, $5, $6, $7)219 ON CONFLICT (theme_id, app, platform) DO UPDATE SET stable_version = EXCLUDED.stable_version, candidate_version = EXCLUDED.candidate_version, candidate_percent = EXCLUDED.candidate_percent, updated_at = now(), updated_by = EXCLUDED.updated_by`,220 [themeId, t.app, t.platform, next.stable, next.candidate, next.percent, actor.name],221 );222 await c.query(223 `INSERT INTO ${schema}.rollout_event (theme_id, app, platform, action, version, percent, prev_stable, prev_candidate, prev_percent, author_name, note) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,224 [themeId, t.app, t.platform, act, version, act === 'cancel' ? 0 : next.candidate === null ? 100 : next.percent, cur.stable_version, cur.candidate_version, cur.candidate_percent, actor.name, note],225 );226 changed.push({ ...t, action: act, stable: next.stable, candidate: next.candidate, percent: next.percent });227 }228 return changed;229}230231/** Publie un brouillon : version immuable n+1, puis diffusion sur les canaux visés — une seule transaction. */232export async function publish(db: Db, actor: Actor, id: string, body: any, opts: { action?: 'publish' | 'seed' } = {}) {233 const s = db.schema;234 const note = String(body?.note ?? '').trim().slice(0, 500);235 const percent = parsePercent(body?.percent ?? 0);236 const targets = parseTargets(body?.targets);237 if (!Number.isInteger(body?.draftId)) throw new HttpError(400, 'draftId requis');238 const draft = (await db.pool.query(`SELECT id, doc FROM ${s}.theme_draft WHERE theme_id = $1 AND id = $2`, [id, body.draftId])).rows[0];239 if (!draft) throw new HttpError(404, 'brouillon inconnu');240 const pre = await validateTheme(draft.doc);241 if (!pre.ok) throw new HttpError(422, 'document invalide', { errors: pre.errors });242 await checkBrands(db.pool, s, id, draft.doc);243 return tx(db, async (c) => {244 const theme = (await c.query(`SELECT id, archived_at FROM ${s}.theme WHERE id = $1 FOR UPDATE`, [id])).rows[0];245 if (!theme) throw new HttpError(404, 'thème inconnu');246 if (theme.archived_at) throw new HttpError(409, 'thème archivé');247 const last = (await c.query(`SELECT version, sha256, draft_id FROM ${s}.theme_version WHERE theme_id = $1 ORDER BY version DESC LIMIT 1`, [id])).rows[0];248 const version = (last?.version ?? 0) + 1;249 const doc = { ...draft.doc, name: id, version: `${version}.0.0` };250 if (!parseSemver(doc.minEngine)) doc.minEngine = '0.1.0';251 const text = JSON.stringify(doc);252 if (last && sha256hex(JSON.stringify({ ...doc, version: `${last.version}.0.0` })) === last.sha256) throw new HttpError(409, `aucun changement depuis la version ${last.version}`);253 await c.query(`INSERT INTO ${s}.theme_version (theme_id, version, doc, doc_text, sha256, min_engine, note, author_id, author_name, draft_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [id, version, text, text, sha256hex(text), doc.minEngine, note, actor.id, actor.name, draft.id]);254 const channels = await applyChannels(c, s, actor, id, targets, opts.action ?? 'publish', version, percent, note);255 await bumpRevision(c, s);256 await audit(c, s, actor, 'theme.publish', id, { version, draft: draft.id, percent, targets: targets.length === ALL_TARGETS.length ? 'all' : targets, note, sha256: sha256hex(text) });257 return { version, sha256: sha256hex(text), minEngine: doc.minEngine, channels };258 });259}260261export async function rollout(db: Db, actor: Actor, id: string, body: any) {262 const s = db.schema;263 const percent = parsePercent(body?.percent);264 const targets = parseTargets(body?.targets);265 const note = String(body?.note ?? '').trim().slice(0, 500);266 if (!Number.isInteger(body?.version)) throw new HttpError(400, 'version requise');267 return tx(db, async (c) => {268 const v = await c.query(`SELECT 1 FROM ${s}.theme_version WHERE theme_id = $1 AND version = $2`, [id, body.version]);269 if (!v.rows[0]) throw new HttpError(404, 'version inconnue');270 const channels = await applyChannels(c, s, actor, id, targets, 'rollout', body.version, percent, note);271 if (channels.length) await bumpRevision(c, s);272 await audit(c, s, actor, 'theme.rollout', id, { version: body.version, percent, targets: targets.length === ALL_TARGETS.length ? 'all' : targets, changed: channels.length, note });273 return { channels };274 });275}276277/** Retour arrière : la version choisie redevient la version stable des canaux visés, toute diffusion en cours est annulée. */278export async function rollback(db: Db, actor: Actor, id: string, body: any) {279 const s = db.schema;280 const targets = parseTargets(body?.targets);281 const note = String(body?.note ?? '').trim().slice(0, 500);282 if (!Number.isInteger(body?.version)) throw new HttpError(400, 'version requise');283 const doc = await getVersionDoc(db, id, body.version);284 await checkBrands(db.pool, s, id, doc);285 return tx(db, async (c) => {286 const channels = await applyChannels(c, s, actor, id, targets, 'rollback', body.version, 100, note);287 if (channels.length) await bumpRevision(c, s);288 await audit(c, s, actor, 'theme.rollback', id, { version: body.version, targets: targets.length === ALL_TARGETS.length ? 'all' : targets, changed: channels.length, note });289 return { channels };290 });291}292293export async function diff(db: Db, id: string, from: string, to: string) {294 const load = async (ref: string) => {295 if (/^v\d+$/.test(ref)) return getVersionDoc(db, id, Number(ref.slice(1)));296 if (/^d\d+$/.test(ref)) return getDraftDoc(db, id, Number(ref.slice(1)));297 if (ref === 'none') return { layers: [] };298 throw new HttpError(400, 'référence : vN (version), dN (brouillon) ou none');299 };300 const [a, b] = await Promise.all([load(from), load(to)]);301 // Le numéro de version est posé par la publication : il n'est pas un changement de l'auteur.302 const strip = ({ version, ...rest }: any) => rest;303 return { from, to, changes: diffDocs(strip(a), strip(b)) };304}305306export async function archiveTheme(db: Db, actor: Actor, id: string, archived: boolean) {307 return tx(db, async (c) => {308 if (archived) {309 const used = [...(await currentApps(c, db.schema))].filter(([, v]) => v.config.themes.includes(id)).map(([a]) => a);310 if (used.length) throw new HttpError(409, `thème encore activé pour : ${used.join(', ')}`);311 }312 const r = await c.query(`UPDATE ${db.schema}.theme SET archived_at = ${archived ? 'now()' : 'NULL'} WHERE id = $1 RETURNING id`, [id]);313 if (!r.rows[0]) throw new HttpError(404, 'thème inconnu');314 await bumpRevision(c, db.schema);315 await audit(c, db.schema, actor, archived ? 'theme.archive' : 'theme.restore', id, {});316 return { ok: true };317 });318}319320// ---------- import depuis themes/*.json (ligne de commande)321322/** Importe un dossier de thèmes. Nouveau thème : version 1 en service partout. Thème existant et323 * document différent : nouvelle version, diffusée à `percent` % (0 = publiée sans diffusion). */324export async function importThemes(db: Db, actor: Actor, files: { name: string; doc: any }[], brands: { app: string; doc: any }[], percent: number) {325 const report: any[] = [];326 const s = db.schema;327 for (const f of files) {328 const id = f.doc?.name;329 if (typeof id !== 'string' || !THEME_ID.test(id)) {330 report.push({ file: f.name, result: 'refusé', reason: 'name absent ou invalide' });331 continue;332 }333 const v = await validateTheme(f.doc);334 if (!v.ok) {335 report.push({ file: f.name, theme: id, result: 'refusé', errors: v.errors.slice(0, 5) });336 continue;337 }338 const exists = (await db.pool.query(`SELECT 1 FROM ${s}.theme WHERE id = $1`, [id])).rows[0];339 const last = (await db.pool.query(`SELECT version, doc_text FROM ${s}.theme_version WHERE theme_id = $1 ORDER BY version DESC LIMIT 1`, [id])).rows[0];340 if (last) {341 const strip = ({ version, ...rest }: any) => JSON.stringify(rest);342 if (strip(JSON.parse(last.doc_text)) === strip(f.doc)) {343 report.push({ file: f.name, theme: id, result: 'inchangé', version: last.version });344 continue;345 }346 }347 if (!exists) await db.pool.query(`INSERT INTO ${s}.theme (id, title, created_by) VALUES ($1, $2, $3)`, [id, id.charAt(0).toUpperCase() + id.slice(1), actor.name]);348 const d = await db.pool.query(`INSERT INTO ${s}.theme_draft (theme_id, doc, note, author_id, author_name, base_version) VALUES ($1, $2, $3, NULL, $4, $5) RETURNING id`, [id, JSON.stringify(f.doc), `import de ${f.name}`, actor.name, last?.version ?? null]);349 const first = !last;350 const r = await publish(db, actor, id, { draftId: d.rows[0].id, note: `import de ${f.name}`, percent: first ? 100 : percent, targets: 'all' }, { action: first ? 'seed' : 'publish' });351 report.push({ file: f.name, theme: id, result: first ? 'créé' : 'nouvelle version', version: r.version, diffusion: first ? 100 : percent });352 }353 // Configurations d'application : créées si absentes ; une marque différente crée une révision.354 const themeIds = (await db.pool.query(`SELECT id FROM ${s}.theme WHERE archived_at IS NULL ORDER BY id`)).rows.map((r) => r.id);355 const apps = await currentApps(db.pool, s);356 for (const app of APPS) {357 const b = brands.find((x) => x.app === app);358 const brand: any = {};359 for (const k of ['palette', 'markers', 'scales', 'layers']) if (b?.doc?.[k] && typeof b.doc[k] === 'object') brand[k] = b.doc[k];360 const cur = apps.get(app);361 let next: AppConfig | null = null;362 if (!cur) next = { ...defaultAppConfig(themeIds), brand };363 else if (b && canon(cur.config.brand) !== canon(brand)) next = { ...cur.config, brand };364 if (!next) {365 report.push({ app, result: 'inchangé', rev: cur?.rev });366 continue;367 }368 const r = await tx(db, async (c) => {369 const ins = await c.query(`INSERT INTO ${s}.app_config_rev (app, config, note, author_name) VALUES ($1, $2, $3, $4) RETURNING id`, [app, JSON.stringify(next), 'import', actor.name]);370 await bumpRevision(c, s);371 await audit(c, s, actor, 'app.config', app, { rev: ins.rows[0].id, note: 'import' });372 return ins.rows[0].id;373 });374 report.push({ app, result: cur ? 'marque mise à jour' : 'configuration créée', rev: r });375 }376 return report;377}378