SPB Git

Repository Public

api.ts 4.2 KB 95 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/web/src/api.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// Appels à l'API du Studio. Le jeton CSRF vit en mémoire seulement ; le témoin de session est HttpOnly.43let csrf = '';44export const setCsrf = (t: string) => (csrf = t);4546export class ApiError extends Error {47  status: number;48  detail: any;49  constructor(status: number, message: string, detail?: any) {50    super(message);51    this.status = status;52    this.detail = detail;53  }54}55export let onUnauthorized: () => void = () => {};56export const setOnUnauthorized = (f: () => void) => (onUnauthorized = f);5758async function call(method: string, path: string, body?: unknown, raw = false): Promise<any> {59  const headers: Record<string, string> = {};60  if (method !== 'GET') {61    headers['Content-Type'] = 'application/json';62    if (csrf) headers['X-CSRF-Token'] = csrf;63  }64  const r = await fetch(path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), credentials: 'same-origin' });65  if (r.status === 401 && !path.startsWith('/api/auth/')) onUnauthorized();66  if (!r.ok) {67    const data = await r.json().catch(() => ({}));68    throw new ApiError(r.status, data.error ?? `erreur ${r.status}`, data.detail);69  }70  if (raw) return r;71  const data = await r.json();72  if (data && typeof data.csrf === 'string') csrf = data.csrf;73  return data;74}75export const api = {76  get: (p: string) => call('GET', p),77  post: (p: string, b: unknown = {}) => call('POST', p, b),78  put: (p: string, b: unknown = {}) => call('PUT', p, b),79  del: (p: string) => call('DELETE', p),80  blob: async (p: string, b: unknown) => {81    const r: Response = await call('POST', p, b, true);82    return { blob: await r.blob(), ms: Number(r.headers.get('X-Render-Ms') ?? 0) };83  },84};8586export const fmtDate = (s: string | null | undefined) => (s ? new Date(s).toLocaleString('fr-CA', { dateStyle: 'medium', timeStyle: 'short' }) : '—');87export const fmtBytes = (n: number | null | undefined) => (n == null ? '—' : n > 1e9 ? `${(n / 1e9).toFixed(1)} Go` : n > 1e6 ? `${(n / 1e6).toFixed(1)} Mo` : n > 1e3 ? `${(n / 1e3).toFixed(1)} ko` : `${n} o`);88export const fmtNum = (n: number) => n.toLocaleString('fr-CA', { maximumFractionDigits: 1 });89export const APP_LABEL: Record<string, string> = { louka: 'Lou-Ka', immoka: 'Immo-Ka', vraiprix: 'Vrai-Prix', valoplex: 'Valo-Plex' };90export const PLATFORM_LABEL: Record<string, string> = { web: 'Web', ios: 'iOS', android: 'Android' };9192// base64url ⇄ ArrayBuffer pour WebAuthn93export const b64uToBuf = (s: string) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)).buffer;94export const bufToB64u = (b: ArrayBuffer) => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');95
Files main
Menu

Theme