Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : sdk/web/tests/e2e/v042.spec.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// 0.4.2 : la panique que la 0.4.1 gardait (retour VP12, correctif moteur 10b0088). Les rattachements des couches43// `buildings` de la trame d'avant n'étaient pas oubliés : après un `removeLayer` de n'importe quelle couche, ou un44// `setLayerData` plus court sur une couche `buildings`, une interrogation ou un clic sur un bâtiment teinté avant la45// trame suivante arrêtait le moteur. Données synthétiques posées sur de vrais bâtiments.46import { test, expect, type Page } from '@playwright/test';47import { openDemo, settle, gpuMessages } from './helpers.js';4849test.afterEach(async ({ page }) => {50 expect(gpuMessages(page), 'validation graphique dans la console').toEqual([]);51});5253async function watchFatal(page: Page): Promise<unknown[]> {54 const fatal: unknown[] = [];55 await page.exposeFunction('__kaFatal', (e: unknown) => fatal.push(e));56 await page.evaluate(() => window.kaMap!.on('error', (e) => (e as { fatal?: boolean }).fatal && (window as unknown as { __kaFatal(e: unknown): void }).__kaFatal(e)));57 return fatal;58}5960/** Vrais bâtiments sous la vue : un point à l'intérieur de chacun (coordonnée et pixel). */61async function pickBuildings(page: Page, n: number) {62 return page.evaluate((n) => {63 const m = window.kaMap!;64 const c = m.getCanvas() as HTMLCanvasElement;65 const seen = new Set<unknown>();66 const out: { lngLat: [number, number]; px: [number, number] }[] = [];67 for (let y = 110; y < c.clientHeight - 90 && out.length < n; y += 38)68 for (let x = 110; x < c.clientWidth - 110 && out.length < n; x += 38) {69 const b = m.queryRendered([x, y]).find((f) => f.layer === 'building');70 if (b && !seen.has(b.id)) {71 seen.add(b.id);72 out.push({ lngLat: m.unproject([x, y])!, px: [x, y] });73 }74 }75 return out;76 }, n);77}7879test('couche buildings : interrogation ou clic sur un bâtiment teinté entre un changement de couche et la trame suivante', async ({ page }, testInfo) => {80 const problems = await openDemo(page, testInfo, { layers: '', zoom: 16.4, controls: 0 });81 await settle(page);82 const fatal = await watchFatal(page);83 const picked = await pickBuildings(page, 14);84 expect(picked.length).toBeGreaterThanOrEqual(10);85 const r = await page.evaluate(async (picked) => {86 const m = window.kaMap!;87 const c = m.getCanvas() as HTMLCanvasElement;88 const frame = () => new Promise<void>((res) => requestAnimationFrame(() => requestAnimationFrame(() => res())));89 const plex = (k: number) => picked.slice(0, k).flatMap((p, i) => [0, 1].map((j) => ({ id: `b${i}-${j}`, lon: p.lngLat[0], lat: p.lngLat[1], value: 1000 + i * 100 + j })));90 const others = picked.map((p, i) => ({ id: `m${i}`, lon: p.lngLat[0] + 0.0004, lat: p.lngLat[1], value: 1500, label: '1 500 $' }));91 const out: string[] = [];92 const step = (name: string, fn: () => unknown) => {93 try {94 fn();95 } catch (e) {96 out.push(`${name} : ${String((e as Error).message).slice(0, 140)}`);97 }98 };99 const ask = (tag: string) => {100 step(`${tag} — queryLayer()`, () => m.queryLayer());101 step(`${tag} — queryLayer(plex)`, () => m.hasLayer('plex') && m.queryLayer('plex'));102 step(`${tag} — queryRendered`, () => { for (const p of picked) m.queryRendered(p.px); });103 step(`${tag} — clic sur un bâtiment teinté`, () => {104 const rect = c.getBoundingClientRect();105 for (const p of picked.slice(0, 6)) {106 const o = { bubbles: true, clientX: rect.left + p.px[0], clientY: rect.top + p.px[1], pointerId: 1, pointerType: 'mouse', isPrimary: true, button: 0 };107 c.dispatchEvent(new PointerEvent('pointermove', o));108 c.dispatchEvent(new PointerEvent('pointerdown', { ...o, buttons: 1 }));109 c.dispatchEvent(new PointerEvent('pointerup', o));110 c.dispatchEvent(new MouseEvent('click', o));111 }112 });113 };114 const setup = async () => {115 for (const id of ['plex', 'autre', 'pts']) if (m.hasLayer(id)) m.removeLayer(id);116 m.addLayer({ id: 'autre', type: 'markers', data: others, options: { cluster: false } });117 m.addLayer({ id: 'pts', type: 'points', data: others.map((o) => ({ ...o, label: undefined })), options: { radius: 5 } });118 m.addLayer({ id: 'plex', type: 'buildings', data: plex(picked.length), options: { aggregate: 'median', scale: { type: 'linear', stops: [[1000, '#ffe9c4'], [2600, '#c2410c']] } } });119 await frame();120 await frame();121 await frame();122 return m.queryLayer('plex').filter((i) => i.type === 'building').length;123 };124 const tinted: number[] = [];125 for (let round = 0; round < 3; round++) {126 // (1) retrait d'une AUTRE couche, puis interrogations et clic dans le même tour.127 tinted.push(await setup());128 m.removeLayer('autre');129 ask('removeLayer d’une autre couche');130 await frame();131 // (2) données raccourcies sur la couche buildings.132 tinted.push(await setup());133 m.setLayerData('plex', plex(2));134 ask('setLayerData raccourci sur buildings');135 await frame();136 // (3) données vidées.137 tinted.push(await setup());138 m.setLayerData('plex', []);139 ask('setLayerData vide sur buildings');140 await frame();141 // (4) retrait de la couche buildings elle-même (ce que fait le démontage d'un useKaLayer / <KaLayer>).142 tinted.push(await setup());143 m.removeLayer('plex');144 ask('removeLayer de la couche buildings');145 await frame();146 // (5) tout retiré d'un coup (changement d'écran).147 tinted.push(await setup());148 for (const id of ['pts', 'plex', 'autre']) m.removeLayer(id);149 ask('toutes les couches retirées');150 await frame();151 }152 return { out, tinted, alive: !m.isDestroyed };153 }, picked);154 expect(Math.min(...r.tinted), 'des bâtiments sont teintés avant chaque changement').toBeGreaterThanOrEqual(8);155 expect(r.out, 'commandes en erreur').toEqual([]);156 expect(fatal, 'erreur fatale du moteur (panique)').toEqual([]);157 expect(problems.errors.filter((e) => /panic|unreachable|RuntimeError|index out of bounds|pageerror/i.test(e))).toEqual([]);158 // La carte vit encore : la couche revient, se teinte et se laisse interroger.159 await page.evaluate((picked) => window.kaMap!.addLayer({ id: 'fin', type: 'buildings', data: picked.map((p, i) => ({ id: i, lon: p.lngLat[0], lat: p.lngLat[1], value: 1000 + i })), options: { color: '#c2410c' } }), picked);160 await settle(page);161 expect((await page.evaluate(() => window.kaMap!.queryLayer('fin'))).filter((i) => i.type === 'building').length).toBeGreaterThanOrEqual(8);162 expect(fatal).toEqual([]);163});164165test('mélange aléatoire (graine fixe) d’ajouts, de retraits, de données vidées et d’interrogations sur cinq types de couches', async ({ page }, testInfo) => {166 const problems = await openDemo(page, testInfo, { layers: '', zoom: 16.2, controls: 0 });167 await settle(page);168 const fatal = await watchFatal(page);169 const picked = await pickBuildings(page, 12);170 expect(picked.length).toBeGreaterThanOrEqual(8);171 const r = await page.evaluate(async (picked) => {172 const m = window.kaMap!;173 const c = m.getCanvas() as HTMLCanvasElement;174 let s = 20261201;175 const rnd = () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296);176 const frame = () => new Promise<void>((res) => requestAnimationFrame(() => res()));177 const b = m.getBounds();178 const pt = () => picked[Math.floor(rnd() * picked.length)];179 const near = (n: number) => Array.from({ length: n }, (_, i) => { const p = pt(); return { id: `d${i}`, lon: p.lngLat[0] + (rnd() - 0.5) * 0.0006, lat: p.lngLat[1] + (rnd() - 0.5) * 0.0004, value: 900 + Math.floor(rnd() * 2000), label: `${900 + i} $`, count: rnd() < 0.2 ? 5 : undefined }; });180 const square = (i: number) => { const x = b[0] + (b[2] - b[0]) * rnd() * 0.8; const y = b[1] + (b[3] - b[1]) * rnd() * 0.8; const w = (b[2] - b[0]) * 0.15; return { type: 'Feature', properties: { nom: `Zone ${i}`, value: 1000 + i }, geometry: { type: 'Polygon', coordinates: [[[x, y], [x + w, y], [x + w, y + w * 0.6], [x, y + w * 0.6], [x, y]]] } }; };181 const data: Record<string, (n: number) => unknown> = {182 markers: (n) => near(n),183 points: (n) => near(n).map((d) => ({ ...d, count: undefined })),184 buildings: (n) => near(n).map((d) => ({ id: d.id, lon: d.lon, lat: d.lat, value: d.value })),185 polygons: (n) => ({ type: 'FeatureCollection', features: Array.from({ length: Math.min(n, 6) }, (_, i) => square(i)) }),186 lines: (n) => ({ type: 'FeatureCollection', features: Array.from({ length: Math.min(n, 4) }, () => ({ type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: [pt().lngLat, pt().lngLat, pt().lngLat] } })) }),187 };188 const options: Record<string, object> = { markers: { cluster: { radius: 40, maxZoom: 17 } }, points: { radius: 6 }, buildings: { aggregate: 'median', color: '#c2410c' }, polygons: { fillColor: '#1f4e9c', fillOpacity: 0.3, label: 'nom' }, lines: { color: '#0b57d0', width: 3 } };189 const types = Object.keys(data);190 const errors: string[] = [];191 const counts: Record<string, number> = {};192 const run = (name: string, fn: () => unknown) => {193 counts[name] = (counts[name] ?? 0) + 1;194 try {195 fn();196 } catch (e) {197 errors.push(`${name} : ${String((e as Error).message).slice(0, 140)}`);198 }199 };200 const rect = c.getBoundingClientRect();201 for (let i = 0; i < 400 && errors.length === 0; i++) {202 const t = types[Math.floor(rnd() * types.length)];203 const id = `${t}-${Math.floor(rnd() * 2)}`;204 const op = rnd();205 if (op < 0.22) run('addLayer', () => { if (!m.hasLayer(id)) m.addLayer({ id, type: t as 'markers', data: data[t](4 + Math.floor(rnd() * 40)) as never, options: options[t] as never }); });206 else if (op < 0.36) run('removeLayer', () => { if (m.hasLayer(id)) m.removeLayer(id); });207 else if (op < 0.5) run('setLayerData plus court', () => { if (m.hasLayer(id)) m.setLayerData(id, data[t](1 + Math.floor(rnd() * 3)) as never); });208 else if (op < 0.58) run('setLayerData vide', () => { if (m.hasLayer(id)) m.setLayerData(id, (t === 'polygons' || t === 'lines' ? { type: 'FeatureCollection', features: [] } : []) as never); });209 else if (op < 0.7) run('queryLayer', () => m.queryLayer(rnd() < 0.5 && m.hasLayer(id) ? id : undefined));210 else if (op < 0.84) run('queryRendered', () => m.queryRendered(rnd() < 0.7 ? pt().px : [rnd() * c.clientWidth, rnd() * c.clientHeight]));211 else if (op < 0.94) run('clic', () => { const p = pt().px; const o = { bubbles: true, clientX: rect.left + p[0], clientY: rect.top + p[1], pointerId: 1, pointerType: 'mouse', isPrimary: true, button: 0 }; c.dispatchEvent(new PointerEvent('pointermove', o)); c.dispatchEvent(new PointerEvent('pointerdown', { ...o, buttons: 1 })); c.dispatchEvent(new PointerEvent('pointerup', o)); });212 else run('setLayerVisible', () => { if (m.hasLayer(id)) m.setLayerVisible(id, rnd() < 0.5); });213 // Une trame de temps en temps seulement : la plupart des opérations s'enchaînent dans le même tour.214 if (rnd() < 0.18) await frame();215 }216 await frame();217 return { errors, counts, layers: m.listLayers().length, alive: !m.isDestroyed };218 }, picked);219 testInfo.annotations.push({ type: 'mesure', description: `opérations : ${JSON.stringify(r.counts)}` });220 expect(r.errors, 'commandes en erreur').toEqual([]);221 expect(fatal, 'erreur fatale du moteur (panique)').toEqual([]);222 expect(problems.errors.filter((e) => /panic|unreachable|RuntimeError|index out of bounds|pageerror/i.test(e))).toEqual([]);223 await settle(page);224 expect(await page.evaluate(() => window.kaMap!.getPerf().tiles)).toBeGreaterThan(0);225});226