Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : sdk/web/tests/unit/server-side.test.ts9 * Module : sdk10 * 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// Environnement Node nu (ni window ni document) : ce que voit un rendu serveur Next.js.43import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';44import { tmpdir } from 'node:os';45import { join } from 'node:path';46import { describe, expect, it } from 'vitest';4748describe('import côté serveur', () => {49 it('le module principal s’importe sans navigateur et ne charge pas le moteur', async () => {50 expect(typeof window).toBe('undefined');51 const m = await import('../../src/index.js');52 expect(typeof m.KaMap.create).toBe('function');53 expect(m.isSupported()).toBe(false);54 expect(m.KaMap.isSupported()).toBe(false);55 expect(m.VERSION).toMatch(/^\d+\.\d+\.\d+/);56 await expect(m.preload()).resolves.toBeUndefined();57 expect(typeof m.geo.search).toBe('function');58 });5960 it('KaMap.create côté serveur : rejet explicite (code unsupported), pas d’exception synchrone', async () => {61 const { KaMap, KaMapError } = await import('../../src/index.js');62 const p = KaMap.create('#carte');63 await expect(p).rejects.toBeInstanceOf(KaMapError);64 await expect(p).rejects.toMatchObject({ code: 'unsupported' });65 });6667 it('le module React s’importe côté serveur (aucun accès à window à l’import)', async () => {68 const r = await import('../../src/react/index.js');69 expect(typeof r.KaMapView).toBe('function');70 expect(typeof r.useKaMap).toBe('function');71 });7273 it('rendu serveur de <KaMapView> : un conteneur vide, sans style en ligne, avec le contenu de chargement', async () => {74 const { createElement } = await import('react');75 const { renderToString } = await import('react-dom/server');76 const { KaMapView } = await import('../../src/react/index.js');77 const html = renderToString(createElement(KaMapView, { className: 'carte', loading: 'Chargement…', options: { zoom: 12 } }));78 expect(html).toContain('class="carte"');79 expect(html).toContain('Chargement…');80 expect(html).not.toContain('style=');81 expect(html).not.toContain('<canvas');82 });83});8485describe('aides Node (Next.js, CSP, copie des actifs)', () => {86 it('kaMapsCsp : directives exactes, avec et sans CDN', async () => {87 const { kaMapsCsp } = await import('../../src/next.js');88 expect(kaMapsCsp()).toEqual({89 'script-src': ["'wasm-unsafe-eval'"],90 'worker-src': ["'self'"],91 'connect-src': ['https://tiles.spboucher.ai', 'https://terrain.spboucher.ai', 'https://geo.spboucher.ai', 'https://maps.spboucher.ai'],92 });93 const cdn = kaMapsCsp({ cdn: true });94 expect(cdn['worker-src']).toEqual(["'self'", 'blob:']);95 expect(cdn['script-src']).toContain('https://maps.spboucher.ai');96 });9798 it('withKaMaps : garde la configuration et ses en-têtes, ajoute ceux des actifs', async () => {99 const { withKaMaps, VERSION } = await import('../../src/next.js');100 // Une configuration typée (sans signature d'index, comme `NextConfig`) passe et garde son type.101 interface TypedConfig {102 reactStrictMode?: boolean;103 images?: { remotePatterns: { hostname: string }[] };104 headers?: () => Promise<{ source: string; headers: { key: string; value: string }[] }[]>;105 }106 const typed: TypedConfig = { reactStrictMode: true, images: { remotePatterns: [{ hostname: 'x' }] }, headers: async () => [{ source: '/x', headers: [{ key: 'A', value: 'b' }] }] };107 const cfg: TypedConfig = withKaMaps(typed, { copy: false });108 expect(cfg.reactStrictMode).toBe(true);109 expect(cfg.images?.remotePatterns[0].hostname).toBe('x');110 const h = await cfg.headers!();111 expect(h[0]).toEqual({ source: '/x', headers: [{ key: 'A', value: 'b' }] });112 expect(h).toContainEqual({ source: `/ka-maps/${VERSION}/km_wasm_bg.wasm`, headers: [{ key: 'Content-Type', value: 'application/wasm' }] });113 expect(h.some((r) => r.source === `/ka-maps/${VERSION}/:file*` && r.headers[0].value.includes('immutable'))).toBe(true);114 });115116 // Le paquet construit (dist/) est requis pour la copie réelle des actifs.117 const dist = new URL('../../dist/', import.meta.url);118 it.skipIf(!existsSync(new URL('assets/km_wasm_bg.wasm', dist)))('copyAssets : copie versionnée, idempotente (paquet construit)', async () => {119 const { copyAssets, VERSION } = (await import(new URL('assets-node.js', dist).href)) as typeof import('../../src/assets-node.js');120 const pub = mkdtempSync(join(tmpdir(), 'ka-maps-pub-'));121 try {122 const first = copyAssets(pub);123 expect(first.dir).toBe(join(pub, 'ka-maps', VERSION));124 expect(first.written.map((f) => f.split('/').pop()).sort()).toEqual(['ka-maps-worker.js', 'km_wasm_bg.wasm']);125 expect(statSync(join(first.dir, 'km_wasm_bg.wasm')).size).toBeGreaterThan(1_000_000);126 expect(readFileSync(join(first.dir, 'km_wasm_bg.wasm')).subarray(0, 4)).toEqual(Buffer.from([0, 0x61, 0x73, 0x6d]));127 expect(copyAssets(pub).written).toEqual([]);128 } finally {129 rmSync(pub, { recursive: true, force: true });130 }131 });132});133