Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : server/km-maps/lib/kmr.ts9 * Module : server10 * 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// Appel de `kmr` (validation stricte par le moteur, rendu hors écran). Un processus par tâche,43// borné en nombre et en durée ; JSON sur l'entrée standard, jamais d'argument construit à partir44// d'une donnée extérieure.45import { spawn } from 'node:child_process';4647export const KMR_BIN = process.env.KMR_BIN ?? '/usr/local/bin/kmr';4849export class Gate {50 private running = 0;51 private waiting: (() => void)[] = [];52 private max: number;53 private maxQueue: number;54 constructor(max: number, maxQueue: number) {55 this.max = max;56 this.maxQueue = maxQueue;57 }58 get load() {59 return { running: this.running, waiting: this.waiting.length };60 }61 async run<T>(fn: () => Promise<T>): Promise<T> {62 if (this.running >= this.max) {63 if (this.waiting.length >= this.maxQueue) throw Object.assign(new Error('file de rendu pleine'), { code: 'BUSY' });64 await new Promise<void>((r) => this.waiting.push(r));65 }66 this.running++;67 try {68 return await fn();69 } finally {70 this.running--;71 this.waiting.shift()?.();72 }73 }74}7576export function runKmr(args: string[], input: unknown, timeoutMs = 30_000): Promise<{ code: number; out: any; stderr: string }> {77 return new Promise((resolve, reject) => {78 const child = spawn(KMR_BIN, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin', HOME: process.env.HOME ?? '/tmp', XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR ?? '/tmp', ...(process.env.VK_ICD_FILENAMES ? { VK_ICD_FILENAMES: process.env.VK_ICD_FILENAMES } : {}) } });79 let out = '';80 let err = '';81 const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);82 child.stdout.on('data', (d) => (out += d));83 child.stderr.on('data', (d) => (err = (err + d).slice(-4000)));84 child.on('error', (e) => {85 clearTimeout(timer);86 reject(e);87 });88 child.on('close', (code, signal) => {89 clearTimeout(timer);90 if (signal) return reject(new Error(`kmr interrompu (${signal})`));91 const line = out.trim().split('\n').pop() ?? '';92 try {93 resolve({ code: code ?? 1, out: JSON.parse(line), stderr: err });94 } catch {95 reject(new Error(`kmr : sortie illisible (${code}) ${err.slice(-300)}`));96 }97 });98 child.stdin.on('error', () => {});99 child.stdin.end(JSON.stringify(input));100 });101}102103export type StyleIssue = { scope: string; path: string; message: string };104105/** Analyse stricte d'un thème (et d'une marque). `effective` : document après application de la marque. */106export async function kmrValidate(theme: unknown, brand?: unknown, effective = false): Promise<{ ok: boolean; errors: StyleIssue[]; warnings: string[]; effective?: any; summary?: any }> {107 const r = await runKmr(['validate'], { theme, brand, effective }, 15_000);108 return r.out;109}110111export async function kmrRender(job: Record<string, unknown>, outPath: string, timeoutMs = 45_000): Promise<{ ok: boolean; errors: any[]; width?: number; height?: number; ms?: number; settled?: boolean; attribution?: string }> {112 const r = await runKmr(['render', '--out', outPath], job, timeoutMs);113 return r.out;114}115