SPB Git

Repository Public

validate.ts 9.2 KB 182 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/server/validate.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// Validation d'un thème : schéma JSON (toutes les erreurs, chemins précis) puis analyse stricte du43// moteur (km-core, par kmr) qui reste l'arbitre.44import { readFileSync } from 'node:fs';45import { dirname, join } from 'node:path';46import { fileURLToPath } from 'node:url';47import Ajv2020 from 'ajv/dist/2020.js';48import { kmrValidate } from '../../server/km-maps/lib/kmr.ts';4950export type Issue = { source: 'schema' | 'engine'; path: string; message: string; soft?: boolean };5152const dir = join(dirname(fileURLToPath(import.meta.url)), '..', 'schema');53export const THEME_SCHEMA = JSON.parse(readFileSync(join(dir, 'kastyle-1.schema.json'), 'utf8'));54export const BRAND_SCHEMA = JSON.parse(readFileSync(join(dir, 'kastyle-1-brand.schema.json'), 'utf8'));55const ajv = new (Ajv2020 as any)({ allErrors: true, strict: false, verbose: false });56ajv.addSchema(THEME_SCHEMA, 'kastyle-1.schema.json');57const validateThemeSchema = ajv.getSchema('kastyle-1.schema.json');58const validateBrandSchema = ajv.compile(BRAND_SCHEMA);5960/** `/layers/3/paint/width` → `layers[3].paint.width` (la notation des erreurs du moteur). */61export function pointerToPath(ptr: string): string {62  return ptr63    .split('/')64    .slice(1)65    .map((seg) => seg.replace(/~1/g, '/').replace(/~0/g, '~'))66    .reduce((acc, seg) => (/^\d+$/.test(seg) ? `${acc}[${seg}]` : acc ? `${acc}.${seg}` : seg), '');67}6869function message(e: any): string {70  const p = e.params ?? {};71  switch (e.keyword) {72    case 'required': return `clé requise manquante : ${p.missingProperty}`;73    case 'additionalProperties': return `clé inconnue : ${p.additionalProperty}`;74    case 'type': return `type attendu : ${Array.isArray(p.type) ? p.type.join(' ou ') : p.type}`;75    case 'enum': return `valeur admise : ${(p.allowedValues ?? []).join(', ')}`;76    case 'const': return `valeur attendue : ${JSON.stringify(p.allowedValue)}`;77    case 'pattern': return /color/i.test(e.schemaPath) ? 'couleur invalide (#rgb, #rrggbb, #rrggbbaa, rgb(), hsl(), @nom de palette)' : `format invalide (${p.pattern})`;78    case 'minimum': return `doit être ≥ ${p.limit}`;79    case 'maximum': return `doit être ≤ ${p.limit}`;80    case 'exclusiveMinimum': return `doit être > ${p.limit}`;81    case 'minItems': return `au moins ${p.limit} élément(s)`;82    case 'maxItems': return `au plus ${p.limit} élément(s)`;83    case 'items': case 'unevaluatedItems': return `trop d'éléments (au plus ${p.limit})`;84    case 'minLength': return 'ne peut pas être vide';85    case 'maxLength': return `au plus ${p.limit} caractères`;86    case 'propertyNames': return `nom de clé invalide : ${p.propertyName}`;87    default: return e.message ?? e.keyword;88  }89}9091function schemaIssues(errors: any[] | null | undefined): Issue[] {92  const seen = new Set<string>();93  const out: Issue[] = [];94  for (const e of errors ?? []) {95    if (e.keyword === 'if' || (e.keyword === 'pattern' && /propertyNames/.test(e.schemaPath))) continue;96    const base = pointerToPath(e.instancePath);97    const path = e.keyword === 'additionalProperties' ? (base ? `${base}.${e.params.additionalProperty}` : e.params.additionalProperty) : base;98    // « Souple » : clé ou opérateur que ce schéma ne connaît pas. Si le moteur, lui, accepte le document,99    // c'est le schéma qui est en retard sur le format : avertissement, pas refus.100    const soft = e.keyword === 'additionalProperties' || e.keyword === 'anyOf' || ((e.keyword === 'enum' || e.keyword === 'const') && /\[0\]$/.test(path));101    const issue: Issue = { source: 'schema', path, message: message(e), ...(soft ? { soft } : {}) };102    const k = `${issue.path}|${issue.message}`;103    if (!seen.has(k)) {104      seen.add(k);105      out.push(issue);106    }107  }108  return out.slice(0, 200);109}110111/** Ajoute à un chemin `layers[12]…` l'identifiant de la couche, pour que l'erreur se lise sans compter. */112function annotate(doc: any, issues: Issue[]): Issue[] {113  return issues.map((i) => {114    const m = /^layers\[(\d+)\]/.exec(i.path);115    const id = m && Array.isArray(doc?.layers) ? doc.layers[Number(m[1])]?.id : undefined;116    return typeof id === 'string' ? { ...i, message: `${i.message} (couche « ${id} »)` } : i;117  });118}119120/** Le moteur est l'arbitre : s'il accepte le document, une clé ou un opérateur inconnu du schéma devient un avertissement. */121export function reconcile(issues: Issue[], engineOk: boolean): { errors: Issue[]; late: string[] } {122  if (!engineOk) return { errors: issues, late: [] };123  return { errors: issues.filter((x) => !x.soft), late: issues.filter((x) => x.soft).map((e) => `${e.path} : ${e.message} — accepté par le moteur, inconnu du schéma du Studio`) };124}125126export async function validateTheme(doc: unknown, brand?: unknown): Promise<{ ok: boolean; errors: Issue[]; warnings: string[]; summary?: any }> {127  if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) return { ok: false, errors: [{ source: 'schema', path: '', message: 'un objet JSON est attendu' }], warnings: [] };128  let errors = validateThemeSchema(doc) ? [] : schemaIssues(validateThemeSchema.errors);129  const engine = await kmrValidate(doc, brand);130  const settled = reconcile(errors, engine.ok);131  errors = settled.errors;132  const late = settled.late;133  for (const e of engine.errors ?? []) {134    const path = e.scope === 'brand' ? `(marque) ${e.path}` : e.path;135    if (!errors.some((x) => x.path === path)) errors.push({ source: 'engine', path, message: e.message });136  }137  return { ok: errors.length === 0, errors: annotate(doc, errors).map(({ soft, ...e }) => e), warnings: [...(engine.warnings ?? []), ...late.slice(0, 20)], summary: engine.summary };138}139140export function validateBrandShape(brand: unknown): Issue[] {141  return validateBrandSchema(brand) ? [] : schemaIssues(validateBrandSchema.errors);142}143144// ---------- différences entre deux documents145146export type Change = { path: string; kind: 'added' | 'removed' | 'changed' | 'moved'; before?: unknown; after?: unknown };147148const isObj = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);149const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);150151/** Différences propriété par propriété. Les couches sont appariées par identifiant (pas par rang) ;152 *  un tableau de valeurs (arrêts de zoom, expression de couleur) est comparé en bloc. */153export function diffDocs(a: any, b: any): Change[] {154  const out: Change[] = [];155  const walk = (x: unknown, y: unknown, path: string) => {156    if (same(x, y)) return;157    if (x === undefined) return void out.push({ path, kind: 'added', after: y });158    if (y === undefined) return void out.push({ path, kind: 'removed', before: x });159    if (isObj(x) && isObj(y) && !('stops' in x) && !('stops' in y)) {160      for (const k of new Set([...Object.keys(x), ...Object.keys(y)])) walk(x[k], y[k], path ? `${path}.${k}` : k);161      return;162    }163    out.push({ path, kind: 'changed', before: x, after: y });164  };165  const { layers: la, ...ra } = a ?? {};166  const { layers: lb, ...rb } = b ?? {};167  walk(ra, rb, '');168  const A: any[] = Array.isArray(la) ? la : [];169  const B: any[] = Array.isArray(lb) ? lb : [];170  const ia = new Map(A.map((l, i) => [l?.id, i]));171  const ib = new Map(B.map((l, i) => [l?.id, i]));172  for (const l of A) if (!ib.has(l?.id)) out.push({ path: `layers[${l?.id}]`, kind: 'removed', before: l });173  for (const l of B) {174    if (!ia.has(l?.id)) out.push({ path: `layers[${l?.id}]`, kind: 'added', after: l });175    else walk(A[ia.get(l.id)!], l, `layers[${l.id}]`);176  }177  const keptA = A.filter((l) => ib.has(l?.id)).map((l) => l.id);178  const keptB = B.filter((l) => ia.has(l?.id)).map((l) => l.id);179  if (!same(keptA, keptB)) out.push({ path: 'layers', kind: 'moved', before: keptA, after: keptB });180  return out;181}182
Files main
Menu

Theme