SPB Git

Repository Public

themes.test.ts 16.8 KB 275 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/test/themes.test.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// Versions, publication, diffusion progressive, compatibilité, retour arrière — vérifiés de bout en43// bout : le Studio publie, le service de manifeste (même base) sert.44import assert from 'node:assert/strict';45import { readFileSync } from 'node:fs';46import { join } from 'node:path';47import { after, before, test } from 'node:test';48import { inRollout } from '../../server/km-maps/lib/rollout.ts';49import { importThemes } from '../server/themes.ts';50import { CLI, type Client, enrolled, makeDb, startMaps, startStudio, THEMES_DIR } from './helpers.ts';5152let db: Awaited<ReturnType<typeof makeDb>>;53let s: Awaited<ReturnType<typeof startStudio>>;54let m: Awaited<ReturnType<typeof startMaps>>;55let c: Client;56const load = (f: string) => JSON.parse(readFileSync(join(THEMES_DIR, f), 'utf8'));57const files = () => ['city3d.json', 'midnight.json', 'signature.json'].map((name) => ({ name, doc: load(name) }));58const brands = () => ['louka', 'immoka', 'vraiprix', 'valoplex'].map((app) => ({ app, doc: load(`brands/${app}.json`) }));59const manifest = async (q: string) => {60  await m.app.refresh();61  const r = await fetch(`${m.base}/v1/manifest.json?${q}`);62  return { status: r.status, data: (await r.json()) as any, headers: r.headers };63};64const served = (man: any, id = 'signature') => man.themes.find((t: any) => t.id === id);6566before(async () => {67  db = await makeDb();68  const report = await importThemes(db, CLI, files(), brands(), 0);69  assert.deepEqual(report.filter((r) => r.theme).map((r) => [r.theme, r.result, r.version]), [['city3d', 'créé', 1], ['midnight', 'créé', 1], ['signature', 'créé', 1]]);70  s = await startStudio(db);71  m = await startMaps(db);72  c = (await enrolled(db, s.base)).client;73});74after(async () => {75  await m.close();76  await s.close();77  await db.drop();78});7980test('import initial : version 1 en service sur les 12 canaux, réimport sans changement = rien', async () => {81  const ch = await db.pool.query(`SELECT count(*)::int AS n FROM ${db.schema}.channel WHERE stable_version = 1 AND candidate_version IS NULL`);82  assert.equal(ch.rows[0].n, 36);83  const again = await importThemes(db, CLI, files(), brands(), 0);84  assert.ok(again.every((r) => r.result === 'inchangé'), JSON.stringify(again));85  const man = await manifest('app=louka&platform=ios&engine=0.1.0&bucket=5');86  assert.equal(man.status, 200);87  assert.deepEqual(man.data.themes.map((t: any) => [t.id, t.version, t.channel]), [['city3d', 1, 'stable'], ['midnight', 1, 'stable'], ['signature', 1, 'stable']]);88  assert.equal(man.data.config.defaultTheme, 'signature');89  assert.match(man.headers.get('cache-control')!, /max-age=60, stale-while-revalidate=600/);90  assert.ok(man.headers.get('etag'));91});9293test('document publié : octets immuables, condensé du manifeste exact, ETag et 304', async () => {94  const man = await manifest('app=immoka');95  const t = served(man.data);96  const r = await fetch(`${m.base}/v1/themes/signature/1.json`);97  const text = await r.text();98  const { createHash } = await import('node:crypto');99  assert.equal(createHash('sha256').update(text).digest('hex'), t.sha256);100  assert.equal(Buffer.byteLength(text), t.bytes);101  assert.match(r.headers.get('cache-control')!, /immutable/);102  assert.equal(JSON.parse(text).version, '1.0.0');103  const not = await fetch(`${m.base}/v1/themes/signature/1.json`, { headers: { 'if-none-match': r.headers.get('etag')! } });104  assert.equal(not.status, 304);105  await assert.rejects(db.pool.query(`UPDATE ${db.schema}.theme_version SET note = 'x' WHERE theme_id = 'signature'`), /immuable/);106  await assert.rejects(db.pool.query(`DELETE FROM ${db.schema}.theme_version WHERE theme_id = 'signature'`), /immuable/);107});108109test('brouillon invalide refusé avec chemin précis ; brouillon valide = nouvelle révision', async () => {110  const d = (await c.get('/api/themes/signature')).data;111  assert.deepEqual(d.docSource, { kind: 'version', version: 1 });112  const bad = structuredClone(d.doc);113  bad.palette.water = '#12';114  bad.layers[4].paint.colour = '#fff';115  bad.light.altitude = 120;116  const r = await c.post('/api/themes/signature/drafts', { doc: bad, note: 'essai' });117  assert.equal(r.status, 422);118  const paths = r.data.detail.errors.map((e: any) => e.path);119  assert.ok(paths.includes('palette.water'), paths.join());120  assert.ok(paths.includes('layers[4].paint.colour'), paths.join());121  assert.ok(paths.includes('light.altitude'), paths.join());122  const before = (await db.pool.query(`SELECT count(*)::int AS n FROM ${db.schema}.theme_draft WHERE theme_id = 'signature'`)).rows[0].n;123  const ok = structuredClone(d.doc);124  ok.minEngine = '0.0.5';125  ok.palette.water = '#b7c9d2';126  const r1 = await c.post('/api/themes/signature/drafts', { doc: ok, note: 'eau plus bleue' });127  assert.equal(r1.status, 200);128  ok.palette.water = '#aac0cc';129  const r2 = await c.post('/api/themes/signature/drafts', { doc: ok, note: 'eau encore' });130  assert.ok(r2.data.draftId > r1.data.draftId);131  const afterN = (await db.pool.query(`SELECT count(*)::int AS n FROM ${db.schema}.theme_draft WHERE theme_id = 'signature'`)).rows[0].n;132  assert.equal(afterN, before + 2);133  const d2 = (await c.get('/api/themes/signature')).data;134  assert.equal(d2.docSource.kind, 'draft');135  assert.equal(d2.doc.palette.water, '#aac0cc');136  assert.deepEqual(Object.keys(d2.doc.palette), Object.keys(d.doc.palette), "l'ordre des clés du document est conservé");137});138139test('publication à 10 % : seules les tranches visées reçoivent la version 2 ; puis 50 %, 100 %', async () => {140  const d = (await c.get('/api/themes/signature')).data;141  const diff = (await c.get(`/api/themes/signature/diff?from=v1&to=d${d.docSource.id}`)).data;142  const v1 = (await c.get('/api/themes/signature/versions/1')).data.doc;143  assert.deepEqual(diff.changes, [{ path: 'minEngine', kind: 'changed', before: '0.1.0', after: '0.0.5' }, { path: 'palette.water', kind: 'changed', before: v1.palette.water, after: '#aac0cc' }]);144  const pub = await c.post('/api/themes/signature/publish', { draftId: d.docSource.id, note: 'eau', percent: 10, targets: [{ app: 'louka', platform: 'web' }] });145  assert.equal(pub.status, 200, JSON.stringify(pub.data));146  assert.equal(pub.data.version, 2);147148  const count = async (percent: number) => {149    let n = 0;150    for (let b = 0; b < 100; b++) {151      const man = await manifest(`app=louka&platform=web&engine=0.1.0&bucket=${b}`);152      const t = served(man.data);153      const expect = inRollout('signature', b, percent);154      assert.equal(t.version, expect ? 2 : 1, `tranche ${b} à ${percent} %`);155      assert.equal(t.channel, expect ? 'candidate' : 'stable');156      if (expect) n++;157    }158    return n;159  };160  assert.equal(await count(10), 10);161  // les autres canaux, et une requête sans tranche, restent sur la version stable162  assert.equal(served((await manifest('app=louka&platform=ios&bucket=0')).data).version, 1);163  assert.equal(served((await manifest('app=immoka&platform=web&bucket=0')).data).version, 1);164  assert.equal(served((await manifest('app=louka&platform=web')).data).version, 1);165  // la candidate sert bien le nouveau document166  const doc2 = await (await fetch(`${m.base}/v1/themes/signature/2.json`)).json();167  assert.equal((doc2 as any).palette.water, '#aac0cc');168  assert.equal((doc2 as any).version, '2.0.0');169170  assert.equal((await c.post('/api/themes/signature/rollout', { version: 2, percent: 50, targets: [{ app: 'louka', platform: 'web' }] })).status, 200);171  assert.equal(await count(50), 50);172  assert.equal((await c.post('/api/themes/signature/rollout', { version: 2, percent: 100, targets: [{ app: 'louka', platform: 'web' }] })).status, 200);173  const ch = (await db.pool.query(`SELECT stable_version, candidate_version, candidate_percent FROM ${db.schema}.channel WHERE theme_id = 'signature' AND app = 'louka' AND platform = 'web'`)).rows[0];174  assert.deepEqual(ch, { stable_version: 2, candidate_version: null, candidate_percent: 0 });175  assert.equal(served((await manifest('app=louka&platform=web')).data).version, 2);176  const ev = (await db.pool.query(`SELECT action, version, percent FROM ${db.schema}.rollout_event WHERE theme_id = 'signature' AND app = 'louka' AND platform = 'web' ORDER BY id`)).rows;177  assert.deepEqual(ev.map((e) => [e.action, e.version, e.percent]), [['seed', 1, 100], ['publish', 2, 10], ['rollout', 2, 50], ['promote', 2, 100]]);178});179180test('compatibilité : un moteur plus ancien reçoit la plus récente version qu’il sait lire', async () => {181  // v1 exige 0.1.0, v2 (ci-dessus) 0.0.5 ; la v3 exige de nouveau 0.1.0.182  const d = (await c.get('/api/themes/signature')).data;183  const doc = structuredClone(d.doc);184  doc.minEngine = '0.1.0';185  doc.palette.park = '#c9d8bb';186  const dr = await c.post('/api/themes/signature/drafts', { doc, note: 'exige 0.1' });187  const pub = await c.post('/api/themes/signature/publish', { draftId: dr.data.draftId, note: 'exige 0.1', percent: 100, targets: 'all' });188  assert.equal(pub.data.version, 3, JSON.stringify([dr.data, pub.data]).slice(0, 600));189  assert.equal(pub.data.minEngine, '0.1.0');190  const old = await manifest('app=louka&platform=web&engine=0.0.9&bucket=1');191  assert.equal(served(old.data).version, 2);192  assert.deepEqual(served(old.data).compatibility, { target: 3, served: 2 });193  assert.deepEqual(old.data.unavailable, [{ id: 'city3d', reason: 'engine' }, { id: 'midnight', reason: 'engine' }]);194  assert.equal(served((await manifest('app=immoka&platform=ios&engine=0.0.9')).data).version, 2, 'la plus récente version lisible, même jamais diffusée sur ce canal');195  assert.equal(served((await manifest('app=louka&platform=web&engine=0.1.0')).data).version, 3);196  assert.equal(served((await manifest('app=louka&platform=web&engine=1.0.0')).data).version, 3);197  const ancient = await manifest('app=louka&platform=web&engine=0.0.4');198  assert.equal(served(ancient.data), undefined);199  assert.deepEqual(ancient.data.unavailable, [{ id: 'city3d', reason: 'engine' }, { id: 'midnight', reason: 'engine' }, { id: 'signature', reason: 'engine' }]);200  assert.equal(ancient.data.config.defaultTheme, null);201  assert.equal(served((await manifest('app=louka&platform=web')).data).version, 3, 'sans version de moteur : pas de filtre');202  // le Studio ne publie pas un thème que son propre moteur ne sait pas lire203  doc.minEngine = '9.0.0';204  const future = await c.post('/api/themes/signature/drafts', { doc, note: 'futur' });205  assert.equal(future.status, 422);206  assert.equal(future.data.detail.errors[0].path, 'minEngine');207});208209test('retour arrière en une action vers une version antérieure, diffusion en cours annulée', async () => {210  const d = (await c.get('/api/themes/signature')).data;211  const doc = structuredClone(d.doc);212  doc.palette.park = '#bfd0b0';213  const dr = await c.post('/api/themes/signature/drafts', { doc, note: 'parc' });214  const pub = await c.post('/api/themes/signature/publish', { draftId: dr.data.draftId, note: 'parc', percent: 25, targets: 'all' });215  assert.equal(pub.data.version, 4);216  const rb = await c.post('/api/themes/signature/rollback', { version: 1, note: 'retour' });217  assert.equal(rb.status, 200);218  assert.equal(rb.data.channels.length, 12);219  const rows = (await db.pool.query(`SELECT DISTINCT stable_version, candidate_version, candidate_percent FROM ${db.schema}.channel WHERE theme_id = 'signature'`)).rows;220  assert.deepEqual(rows, [{ stable_version: 1, candidate_version: null, candidate_percent: 0 }]);221  for (const b of [0, 37, 99]) assert.equal(served((await manifest(`app=vraiprix&platform=android&engine=0.5.0&bucket=${b}`)).data).version, 1);222  assert.equal(served((await manifest('app=vraiprix&platform=android&engine=0.0.9')).data), undefined, 'jamais une version postérieure à celle du retour arrière');223  assert.equal((await c.post('/api/themes/signature/rollback', { version: 99 })).status, 404);224  // les versions 2 à 4 existent toujours, intactes225  assert.equal((await fetch(`${m.base}/v1/themes/signature/4.json`)).status, 200);226  const audit = (await db.pool.query(`SELECT action FROM ${db.schema}.audit WHERE action LIKE 'theme.%' ORDER BY id DESC LIMIT 1`)).rows[0].action;227  assert.equal(audit, 'theme.rollback');228});229230test('publication refusée sans changement ; cibles et pourcentage validés ; atomicité', async () => {231  const d = (await c.get('/api/themes/midnight')).data;232  const dr = await c.post('/api/themes/midnight/drafts', { doc: d.doc, note: 'identique' });233  assert.equal((await c.post('/api/themes/midnight/publish', { draftId: dr.data.draftId, percent: 100 })).status, 409);234  const doc = structuredClone(d.doc);235  doc.palette.water = '#101418';236  const dr2 = await c.post('/api/themes/midnight/drafts', { doc, note: 'eau' });237  assert.equal((await c.post('/api/themes/midnight/publish', { draftId: dr2.data.draftId, percent: 140 })).status, 400);238  assert.equal((await c.post('/api/themes/midnight/publish', { draftId: dr2.data.draftId, percent: 10, targets: [{ app: 'nope', platform: 'web' }] })).status, 400);239  const rev0 = (await db.pool.query(`SELECT value FROM ${db.schema}.state`)).rows[0].value;240  // une cible refusée en cours de transaction (déjà stable) annule tout : pas de version 2 orpheline241  const first = await c.post('/api/themes/midnight/publish', { draftId: dr2.data.draftId, percent: 100, targets: [{ app: 'louka', platform: 'web' }] });242  assert.equal(first.data.version, 2);243  const conflict = await c.post('/api/themes/midnight/rollout', { version: 2, percent: 30, targets: [{ app: 'immoka', platform: 'web' }, { app: 'louka', platform: 'web' }] });244  assert.equal(conflict.status, 409);245  const im = (await db.pool.query(`SELECT candidate_version FROM ${db.schema}.channel WHERE theme_id = 'midnight' AND app = 'immoka' AND platform = 'web'`)).rows[0];246  assert.equal(im.candidate_version, null, 'la première cible du lot refusé n’a pas été modifiée');247  const rev1 = (await db.pool.query(`SELECT value FROM ${db.schema}.state`)).rows[0].value;248  assert.equal(rev1, rev0 + 1);249});250251test('réimport d’un thème modifié : nouvelle version, non diffusée par défaut', async () => {252  const f = files();253  f[0].doc.palette.water = '#99aabb';254  const rep = await importThemes(db, CLI, [f[0]], [], 0);255  assert.deepEqual([rep[0].theme, rep[0].result, rep[0].version, rep[0].diffusion], ['city3d', 'nouvelle version', 2, 0]);256  assert.equal(served((await manifest('app=louka&platform=web&bucket=3')).data, 'city3d').version, 1);257});258259test('thème + marque : document effectif immuable par (version, révision), couches coupées retirées', async () => {260  const man = (await manifest('app=louka&platform=web')).data;261  const t = served(man, 'midnight');262  const eff = await fetch(t.effectiveUrl.replace('https://maps.test', m.base));263  assert.equal(eff.status, 200);264  assert.match(eff.headers.get('cache-control')!, /immutable/);265  const doc = (await eff.json()) as any;266  assert.equal(doc.palette.accent, load('brands/louka.json').palette.accent);267  const cur = await fetch(`${m.base}/v1/themes/midnight/current.json?app=louka&platform=web`);268  assert.equal(cur.headers.get('x-ka-theme-version'), String(t.version));269  assert.deepEqual(await cur.json(), doc);270  const brand = (await (await fetch(man.brand.url.replace('https://maps.test', m.base))).json()) as any;271  assert.equal(brand.brand, 'louka');272  assert.equal((await fetch(`${m.base}/v1/themes/midnight/current.json?app=louka&platform=tv`)).status, 400);273  assert.equal((await fetch(`${m.base}/v1/themes/nope/current.json?app=louka`)).status, 404);274});275
Files main
Menu

Theme