Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Valo-Plex8 * File : e2e/cartes.mjs9 * Module : e2e10 * Repository : https://git.spboucher.ai/valo-plex11 * Project Website : https://www.valo-plex.com12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Parcours de bout en bout des cartes KA Maps de Valo-Plex, sans fenêtre.44// BASE=http://127.0.0.1:8198 node e2e/cartes.mjs [--captures dossier] [--rendu webgpu|webgl2] [--navigateur webkit|firefox]45// Avec --navigateur webkit ou firefox : un seul parcours, au rendu que le navigateur offre (« auto »), sans l essai sans GPU.46// Chaque parcours est joué deux fois : WebGPU, puis WebGL 2 forcé (`?rendu=webgl2`, option d'essai du site).47// Garde permanente : aucune erreur ni aucun avertissement dans la console (validation WebGPU / WGSL / WebGL comprise),48// aucune violation de la politique de contenu, aucune requête vers un hôte de carte tiers.49import fs from "node:fs";50import path from "node:path";51import { chromium, firefox, webkit } from "playwright";5253const BASE = (process.env.BASE ?? "http://127.0.0.1:8198").replace(/\/$/, "");54const arg = (nom) => {55 const i = process.argv.indexOf(`--${nom}`);56 return i > 0 ? process.argv[i + 1] : null;57};58const CAPTURES = arg("captures");59const NAVIGATEUR = arg("navigateur") ?? "chromium";60const RENDUS = NAVIGATEUR !== "chromium" ? [arg("rendu") ?? NAVIGATEUR] : arg("rendu") ? [arg("rendu")] : ["webgpu", "webgl2"];61const GPU = ["--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist", "--enable-unsafe-webgpu"];62const SANS_GPU = ["--disable-gpu", "--disable-webgl", "--disable-webgl2", "--disable-3d-apis"];63const HOTES_CARTE = ["tiles.spboucher.ai", "terrain.spboucher.ai", "geo.spboucher.ai", "maps.spboucher.ai"];64const INTERDITS = /maplibre|openfreemap|openstreetmap\.org|mapbox|cartocdn|carto\.com|tile\.osm|googleapis|gstatic/i;65const BUREAU = { width: 1440, height: 900 };66const MOBILE = { width: 390, height: 844 };6768let reussis = 0;69const echecs = [];70let courant = "";71const parSection = {};72function verifier(cond, quoi, detail = "") {73 parSection[courant] ??= [0, 0];74 parSection[courant][cond ? 0 : 1]++;75 if (cond) reussis++;76 else {77 echecs.push(`[${courant}] ${quoi}${detail ? ` — ${detail}` : ""}`);78 console.log(` ✗ ${quoi}${detail ? ` — ${detail}` : ""}`);79 }80}81const avec = (chemin, rendu) => (rendu === "webgl2" ? chemin + (chemin.includes("?") ? "&" : "?") + "rendu=webgl2" : chemin).replace(/(#[^?]*)\?(.*)$/, "?$2$1");8283async function ouvrir(nav, format, { sombre = false, mobile = false } = {}) {84 const ctx = await nav.newContext({ viewport: format, locale: "fr-CA", timezoneId: "America/Toronto", colorScheme: sombre ? "dark" : "light", hasTouch: mobile, ...(NAVIGATEUR === "firefox" ? {} : { isMobile: mobile }), deviceScaleFactor: mobile ? 2 : 1 });85 await ctx.addInitScript(() => {86 window.__csp = [];87 document.addEventListener("securitypolicyviolation", (e) => window.__csp.push(`${e.violatedDirective} ${e.blockedURI}`));88 });89 const page = await ctx.newPage();90 const s = { console: [], tiers: [], hotes: new Set() };91 page.on("console", (m) => {92 // Firefox : quatre avis du navigateur, connus et sans effet (WebGPU en liste de blocage → repli WebGL 2 attendu,93 // extension de diagnostic dépréciée, note sur le filtrage des textures de profondeur, police préchargée).94 if (NAVIGATEUR === "firefox" && /WebGPU is disabled by blocklist|WEBGL_debug_renderer_info is deprecated|Depth texture comparison requests|preloaded with link preload was not used/.test(m.text())) return;95 if (m.type() === "error" || m.type() === "warning") s.console.push(`${m.type()}: ${m.text().slice(0, 240)}`);96 });97 page.on("pageerror", (e) => s.console.push(`exception: ${e.message.slice(0, 240)}`));98 page.on("request", (r) => {99 const u = new URL(r.url());100 if (u.protocol === "data:" || u.protocol === "blob:") {101 if (u.protocol === "blob:") s.tiers.push(r.url().slice(0, 80));102 return;103 }104 s.hotes.add(u.host);105 if (u.origin !== BASE && !HOTES_CARTE.includes(u.host)) s.tiers.push(r.url().slice(0, 120));106 if (INTERDITS.test(r.url())) s.tiers.push(`interdit: ${r.url().slice(0, 120)}`);107 });108 return { ctx, page, s };109}110111async function carte(page, nom = "__vxCarte") {112 await page.waitForFunction((n) => window[n], nom, { timeout: 30000 });113 await page.evaluate(async (n) => {114 const c = window[n];115 await c.whenLoaded();116 await Promise.race([c.whenIdle(), new Promise((r) => setTimeout(r, 15000))]);117 }, nom);118}119const repos = async (page, nom = "__vxCarte") => {120 await page.waitForTimeout(600);121 await page.evaluate((n) => Promise.race([window[n].whenIdle(), new Promise((r) => setTimeout(r, 12000))]), nom);122 await page.waitForTimeout(500);123};124const etat = (page) => page.evaluate(() => {125 const c = window.__vxCarte;126 const e = window.__vxEtat?.() ?? {};127 return { backend: c.backend, mode: c.getMode(), cam: c.getCamera(), theme: c.getTheme().name, marque: c.getTheme().brand, couches: Object.fromEntries(c.listLayers().map((l) => [l.id, l.count])), bilan: e.bilan ?? null, donnees: e.donnees ? { mode: e.donnees.mode, cases: e.donnees.cases.length, points: e.donnees.points.length } : null };128});129async function capture(page, nom, cible = null) {130 if (!CAPTURES) return;131 fs.mkdirSync(CAPTURES, { recursive: true });132 const fichier = path.join(CAPTURES, `${nom}.jpg`);133 if (cible) await page.locator(cible).first().screenshot({ path: fichier, type: "jpeg", quality: 70 });134 else await page.screenshot({ path: fichier, type: "jpeg", quality: 70 });135}136/** Part des pixels du canevas dont la teinte est une des teintes de plex (rouge nettement au-dessus du bleu). */137async function partTeintee(page) {138 const png = await page.locator("canvas.ka-maps-canvas").first().screenshot({ type: "png" });139 return page.evaluate(async (b64) => {140 const img = new Image();141 img.src = `data:image/png;base64,${b64}`;142 await img.decode();143 const k = document.createElement("canvas");144 k.width = img.width;145 k.height = img.height;146 const x = k.getContext("2d");147 x.drawImage(img, 0, 0);148 const d = x.getImageData(0, 0, k.width, k.height).data;149 let n = 0;150 for (let i = 0; i < d.length; i += 4) if (d[i] > 90 && d[i] - d[i + 2] > 55 && d[i] - d[i + 1] > 25) n++;151 return n / (d.length / 4);152 }, png.toString("base64"));153}154function garde(s, page, quoi) {155 return page.evaluate(() => window.__csp).then((csp) => {156 verifier(s.console.length === 0, `${quoi} : console sans erreur ni avertissement`, s.console.slice(0, 4).join(" | "));157 verifier(csp.length === 0, `${quoi} : aucune violation de la politique de contenu`, csp.slice(0, 3).join(" | "));158 verifier(s.tiers.length === 0, `${quoi} : aucune requête hors du site et des services KA Maps`, s.tiers.slice(0, 3).join(" | "));159 });160}161162// ---------------------------------------------------------------------------------- parcours avec rendu163async function parcours(nav, rendu) {164 courant = rendu;165 console.log(`\n== ${rendu}`);166 const u = (c) => BASE + avec(c, rendu);167168 // 1. /carte par défaut : 3D, vrais bâtiments teintés169 {170 const { ctx, page, s } = await ouvrir(nav, BUREAU);171 await page.goto(u("/carte"));172 await carte(page);173 await page.waitForFunction(() => window.__vxEtat?.().bilan, null, { timeout: 20000 }).catch(() => {});174 await repos(page);175 const e = await etat(page);176 verifier(NAVIGATEUR === "chromium" ? e.backend === rendu : ["webgpu", "webgl2"].includes(e.backend), "rendu attendu", `obtenu ${e.backend}`);177 if (NAVIGATEUR !== "chromium") console.log(` rendu obtenu dans ${NAVIGATEUR} : ${e.backend}`);178 verifier(e.mode === "3d" && e.cam.pitch > 40, "ouverture en volume", JSON.stringify(e.cam));179 verifier(e.theme === "signature" && e.marque === "valoplex", "thème signature, marque valoplex", `${e.theme} / ${e.marque}`);180 verifier(e.couches.plex > 500 && e.couches.cases === 0, "plex posés sur la couche des bâtiments réels", JSON.stringify(e.couches));181 verifier(e.bilan && e.bilan.dedans + e.bilan.pres + e.bilan.sans + e.bilan.attente === e.couches.plex, "bilan final du rattachement : rattachés + sans empreinte + hors zone dessinée = plex de la vue", JSON.stringify(e.bilan));182 verifier(e.bilan && e.bilan.dedans + e.bilan.pres >= 0.8 * (e.couches.plex - e.bilan.attente), "au moins 80 % des plex des tuiles chargées rattachés à une empreinte réelle", JSON.stringify(e.bilan));183 const part = await partTeintee(page);184 verifier(part > 0.06, "les bâtiments sont visiblement teintés (pixels de teinte brique)", `${(part * 100).toFixed(1)} %`);185 const legende = await page.locator(".parc-legende").innerText();186 verifier(/estimation, pas un prix de vente/i.test(legende) && /vx-\d+/.test(legende), "légende : nature de la valeur et modèle", legende.slice(0, 80));187 verifier(/bâtiment réel/.test(legende) && /Rattachement : [\d\s ]+sur une empreinte/.test(legende), "légende : méthode et bilan du rattachement");188 const comptes = await page.locator(".parc-classes li b").allInnerTexts();189 const somme = comptes.slice(0, 6).reduce((t, x) => t + Number(x.replace(/\D/g, "")), 0);190 verifier(somme > 0 && somme <= e.donnees.points, "légende : effectifs par classe comptés sur la vue", `${somme} / ${e.donnees.points}`);191 verifier(/[?&]c=45\.5\d+,-73\.5\d+&z=16\.2/.test(page.url()), "état de la carte dans l'adresse", page.url());192 await capture(page, `carte-3d-bureau-jour-${rendu}`);193194 // 2. plan : mêmes bâtiments à plat, choix d'un bâtiment par un clic195 await page.getByRole("button", { name: "Plan", exact: true }).click();196 await page.waitForFunction(() => window.__vxCarte.getMode() === "2d" && window.__vxCarte.getCamera().pitch < 1, null, { timeout: 8000 }).catch(() => {});197 await repos(page);198 const plan = await etat(page);199 verifier(plan.mode === "2d" && plan.cam.pitch < 1 && Math.abs(plan.cam.bearing) < 1 && /vue=plan/.test(page.url()), "bascule en plan : vue à plat, nord en haut, inscrite dans l'adresse", JSON.stringify(plan.cam));200 const partPlan = await partTeintee(page);201 verifier(partPlan > 0.04, "plan : empreintes teintées", `${(partPlan * 100).toFixed(1)} %`);202 await capture(page, `carte-plan-bureau-jour-${rendu}`);203 const cible = await page.evaluate(() => {204 const c = window.__vxCarte;205 const { donnees } = window.__vxEtat();206 const r = c.getCanvasElement().getBoundingClientRect();207 for (const p of donnees.points) {208 const xy = c.project([p.lng, p.lat]);209 if (!xy || xy[0] < 200 || xy[1] < 120 || xy[0] > r.width - 80 || xy[1] > r.height - 80) continue;210 const f = c.queryRendered(xy, {}).find((x) => x.source === "app" && x.layer === "plex");211 if (f && String(f.id) === p.id) return { id: p.id, x: r.left + xy[0], y: r.top + xy[1] };212 }213 return null;214 });215 verifier(!!cible, "un plex de la vue répond sous son propre bâtiment (queryRendered)");216 if (cible) {217 await page.mouse.click(cible.x, cible.y);218 await page.locator(".parc-fiche").waitFor({ timeout: 5000 }).catch(() => {});219 const lien = await page.locator(".parc-fiche a.bouton").getAttribute("href").catch(() => null);220 verifier(lien === `/immeuble/${cible.id}`, "clic sur un bâtiment teinté : sa fiche s'ouvre dans le panneau", String(lien));221 verifier(page.url().includes(`sel=${cible.id}`), "immeuble choisi inscrit dans l'adresse");222 const fiche = await page.locator(".parc-fiche").innerText().catch(() => "");223 verifier(/Valeur estimée|Aucune valeur/.test(fiche), "fiche : la valeur est dite estimée");224 verifier(/hauteur (mesurée|déduite|estimée|du bloc|de provenance)/.test(fiche), "fiche : provenance de la hauteur du bâtiment", fiche.replace(/\s+/g, " ").slice(0, 160));225 await page.waitForTimeout(700);226 await capture(page, `carte-plan-choix-${rendu}`);227 await page.locator(".parc-fermer").click();228 verifier((await page.locator(".parc-fiche").count()) === 0 && !/sel=/.test(page.url()), "fermeture de la fiche");229 }230231 // la rampe du style courant est celle de la légende : pixel du bâtiment comparé à la pastille de sa classe232 const teinteVsLegende = async () => {233 const m = await page.evaluate(() => {234 const c = window.__vxCarte;235 const r = c.getCanvasElement().getBoundingClientRect();236 const bornes = [150000, 200000, 250000, 325000, 425000];237 const out = [];238 for (const b of c.queryLayer("plex")) {239 if (b.type !== "building" || (b.members?.length ?? 0) !== 1 || !(b.aggregate?.value > 0) || out.length >= 12) continue;240 const xy = [(b.rect[0] + b.rect[2]) / 2, (b.rect[1] + b.rect[3]) / 2];241 if (xy[0] < 200 || xy[1] < 120 || xy[0] > r.width - 80 || xy[1] > r.height - 80) continue;242 const f = c.queryRendered(xy, {}).find((x) => x.source === "app" && x.layer === "plex");243 if (!f || String(f.id) !== String(b.members[0])) continue;244 const { donnees } = window.__vxEtat();245 if (donnees.points.find((p) => p.id === String(b.members[0]))?.av) continue;246 let k = 0;247 while (k < bornes.length && b.aggregate.value >= bornes[k]) k++;248 out.push({ x: Math.round(r.left + xy[0]), y: Math.round(r.top + xy[1]), classe: k });249 }250 const legende = [...document.querySelectorAll(".parc-classes li i")].slice(0, 6).map((i) => getComputedStyle(i).backgroundColor.match(/\d+/g).slice(0, 3).map(Number));251 return { out, legende };252 });253 const png = await page.screenshot({ type: "png" });254 const pix = await page.evaluate(async ({ b64, pts }) => {255 const img = new Image();256 img.src = `data:image/png;base64,${b64}`;257 await img.decode();258 const k = document.createElement("canvas");259 k.width = img.width;260 k.height = img.height;261 const x = k.getContext("2d", { willReadFrequently: true });262 x.drawImage(img, 0, 0);263 return pts.map((p) => [...x.getImageData(p.x, p.y, 1, 1).data].slice(0, 3));264 }, { b64: png.toString("base64"), pts: m.out });265 const ecarts = m.out.map((p, i) => Math.max(...pix[i].map((v, j) => Math.abs(v - m.legende[p.classe][j]))));266 return { n: m.out.length, bons: ecarts.filter((e) => e <= 14).length, pire: Math.max(0, ...ecarts) };267 };268 const tj = await teinteVsLegende();269 verifier(tj.n >= 6 && tj.bons >= tj.n - 1, "jour : la teinte dessinée d'un bâtiment est celle de sa classe dans la légende", JSON.stringify(tj));270271 // 2 bis. un bâtiment qui abrite plusieurs plex : la vraie liste « Dans le même bâtiment » (members du moteur)272 const partage = await page.evaluate(() => {273 const c = window.__vxCarte;274 const { donnees } = window.__vxEtat();275 const r = c.getCanvasElement().getBoundingClientRect();276 for (const p of donnees.points) {277 const xy = c.project([p.lng, p.lat]);278 if (!xy || xy[0] < 200 || xy[1] < 120 || xy[0] > r.width - 80 || xy[1] > r.height - 80) continue;279 const f = c.queryRendered(xy, {}).find((x) => x.source === "app" && x.layer === "plex");280 if (f && (f.members?.length ?? 0) > 1) return { x: r.left + xy[0], y: r.top + xy[1], membres: f.members.map(String), agregat: f.aggregate };281 }282 return null;283 });284 verifier(!!partage && partage.agregat?.op === "median", "un bâtiment partagé rend ses membres et sa médiane", JSON.stringify(partage)?.slice(0, 160));285 if (partage) {286 await page.mouse.click(partage.x, partage.y);287 await page.locator(".parc-voisins").waitFor({ timeout: 5000 }).catch(() => {});288 const titre = await page.locator(".parc-voisins .etiquette").innerText().catch(() => "");289 const n = await page.locator(".parc-voisins button").count();290 verifier(/dans le même bâtiment/i.test(titre) && n === Math.min(24, partage.membres.length - 1), "« Dans le même bâtiment » : tous les autres plex de l'empreinte", `${n} pour ${partage.membres.length} membres`);291 await page.locator(".parc-voisins button").first().click();292 verifier((await page.locator(".parc-voisins button").count()) === n, "passer à un voisin garde la liste du bâtiment");293 await page.waitForTimeout(600);294 await capture(page, `carte-plan-meme-batiment-${rendu}`);295 // le même immeuble choisi dans la liste de la vue : cerne sur le bâtiment rattaché, même liste (queryLayer)296 const idPartage = await page.locator(".parc-fiche a.bouton").getAttribute("href");297 await page.locator(".parc-fermer").click();298 const dansListe = await page.evaluate((href) => {299 const { donnees } = window.__vxEtat();300 const c = window.__vxCarte;301 const p = donnees.points.find((x) => `/immeuble/${x.id}` === href);302 c.jumpTo({ center: [p.lng, p.lat] });303 return true;304 }, idPartage);305 await repos(page);306 await page.waitForFunction(() => window.__vxEtat().bilan, null, { timeout: 10000 }).catch(() => {});307 await page.waitForTimeout(400);308 await page.locator(".parc-liste li button").first().scrollIntoViewIfNeeded();309 await page.locator(".parc-liste li button").first().click();310 await page.waitForTimeout(500);311 const parListe = { href: await page.locator(".parc-fiche a.bouton").getAttribute("href").catch(() => null), n: await page.locator(".parc-voisins button").count(), hauteur: /hauteur/.test(await page.locator(".parc-fiche").innerText().catch(() => "")) };312 verifier(dansListe && parListe.href === idPartage && parListe.n === n && parListe.hauteur, "choisi dans la liste : « Dans le même bâtiment » et la hauteur du bâtiment rattaché s'affichent aussi", JSON.stringify(parListe));313314 verifier((await page.locator(".parc-panneau").evaluate((el) => el.scrollTop)) === 0, "choisi dans la liste : le panneau revient sur l immeuble choisi");315 await page.waitForTimeout(600);316 await capture(page, `carte-plan-meme-batiment-liste-${rendu}`);317 await page.locator(".parc-fermer").click();318 await page.evaluate(() => window.__vxCarte.jumpTo({ center: [-73.5795, 45.5265] }));319 await repos(page);320 }321322 // 3. clavier : zoom, déplacement, liste de la vue323 const avant = (await etat(page)).cam;324 await page.locator("canvas.ka-maps-canvas").focus();325 await page.keyboard.press("+");326 await page.waitForTimeout(900);327 await page.keyboard.press("ArrowRight");328 await page.waitForTimeout(900);329 const apres = (await etat(page)).cam;330 verifier(apres.zoom > avant.zoom + 0.2 && apres.center[0] > avant.center[0], "clavier : + rapproche, → déplace", `${avant.zoom}→${apres.zoom}`);331 await repos(page);332 const premier = page.locator(".parc-liste li button").first();333 await premier.focus();334 await page.keyboard.press("Enter");335 verifier((await page.locator(".parc-fiche h2").count()) === 1, "clavier : Entrée sur un immeuble de la liste ouvre sa fiche");336 verifier((await page.locator("canvas.ka-maps-canvas").getAttribute("aria-label")) === "Carte de tous les plex du Québec", "nom accessible de la carte");337338 // 4. nuit339 await page.getByRole("button", { name: "Nuit", exact: true }).click();340 await page.waitForFunction(() => window.__vxCarte.getTheme().name === "midnight", null, { timeout: 8000 }).catch(() => {});341 await repos(page);342 verifier((await etat(page)).theme === "midnight" && /nuit=1/.test(page.url()) && (await page.locator(".parc[data-nuit]").count()) === 1, "mode sombre : thème midnight, panneau sombre, adresse", page.url());343 await page.locator(".parc-fermer").click().catch(() => {});344 await page.waitForTimeout(600);345 const tn = await teinteVsLegende();346 verifier(tn.n >= 6 && tn.bons >= tn.n - 1, "nuit : la rampe de nuit de la marque est celle de la légende (le plus cher est le plus clair)", JSON.stringify(tn));347 const clairs = await page.evaluate(() => [...document.querySelectorAll(".parc-classes li i")].slice(0, 6).map((i) => getComputedStyle(i).backgroundColor.match(/\d+/g).slice(0, 3).reduce((t, v) => t + Number(v), 0)));348 verifier(clairs.every((v, i) => i === 0 || v > clairs[i - 1]), "nuit : légende du plus sombre au plus clair", clairs.join(","));349 await capture(page, `carte-plan-bureau-nuit-${rendu}`);350 await page.getByRole("button", { name: "3D", exact: true }).click();351 await page.waitForFunction(() => window.__vxCarte.getMode() === "3d", null, { timeout: 8000 }).catch(() => {});352 await repos(page);353 await page.waitForTimeout(1200);354 await capture(page, `carte-3d-bureau-nuit-${rendu}`);355 await garde(s, page, "/carte de près");356 await ctx.close();357 }358359 // 5. province : cercles par case, sans empilement ; filtres ; à vendre en grappes360 {361 const { ctx, page, s } = await ouvrir(nav, BUREAU);362 await page.goto(u("/carte?c=46.9,-71.9&z=6.2&vue=plan"));363 await carte(page);364 await page.waitForFunction(() => window.__vxEtat?.().donnees, null, { timeout: 15000 });365 await repos(page);366 const e = await etat(page);367 verifier(e.donnees.mode === "cases" && e.couches.cases === e.donnees.cases && e.couches.plex === 0, "vue d'ensemble : un cercle par case", JSON.stringify(e.couches));368 const cercles = () => page.evaluate(() => {369 const c = window.__vxCarte;370 const { donnees, rayons } = window.__vxEtat();371 const boite = c.getCanvasElement().getBoundingClientRect();372 const obst = [...document.querySelectorAll(".parc-carte .ka-maps-nav, .parc-carte .ka-maps-scale")].map((el) => el.getBoundingClientRect());373 const montres = [];374 donnees.cases.forEach((k, i) => {375 const xy = c.project([k.lng, k.lat]);376 if (!xy || xy[0] < 0 || xy[1] < 0 || xy[0] > boite.width || xy[1] > boite.height) return;377 if (c.queryRendered(xy, { layers: ["cases"] }).some((f) => f.layer === "cases" && Number(f.id) === i)) montres.push({ xy, r: rayons[i] });378 });379 let touchent = 0, sous = 0;380 for (let i = 0; i < montres.length; i++) {381 for (let j = i + 1; j < montres.length; j++) if (Math.hypot(montres[i].xy[0] - montres[j].xy[0], montres[i].xy[1] - montres[j].xy[1]) < montres[i].r + montres[j].r) touchent++;382 if (obst.some((o) => montres[i].xy[0] + boite.left > o.left && montres[i].xy[0] + boite.left < o.right && montres[i].xy[1] + boite.top > o.top && montres[i].xy[1] + boite.top < o.bottom)) sous++;383 }384 return { cases: donnees.cases.length, montres: montres.length, declares: c.listLayers().find((l) => l.id === "cases").shown, touchent, sous, pitch: c.getCamera().pitch };385 });386 const empiles = await cercles();387 verifier(empiles.montres > 20 && empiles.touchent === 0, "province : aucun cercle n'en touche un autre", JSON.stringify(empiles));388 verifier(empiles.sous === 0, "province : aucun cercle sous les commandes de la carte", JSON.stringify(empiles));389 const panneau = await page.evaluate(() => {390 const c = document.querySelector(".parc-carte").getBoundingClientRect();391 return [...document.querySelectorAll(".parc-panneau, .parc-barre")].every((el) => {392 const r = el.getBoundingClientRect();393 return r.right <= c.left + 1 || r.left >= c.right - 1 || r.bottom <= c.top + 1 || r.top >= c.bottom - 1;394 });395 });396 verifier(panneau, "aucun panneau de l'interface ne recouvre la carte");397 const legende = await page.locator(".parc-legende").innerText();398 verifier(/un cercle par case/.test(legende) && /surface/.test(legende) && /médiane/.test(legende) && /le plus grand cercle : [\d\s ]+/.test(legende), "légende de la vue d'ensemble : méthode et effectifs");399 await page.waitForFunction(() => /Autour de/.test(document.querySelector(".parc-liste")?.textContent ?? ""), null, { timeout: 8000 }).catch(() => {});400 verifier(/Autour de/.test(await page.locator(".parc-liste").innerText()), "secteurs nommés par le service géographique maison");401 await capture(page, `carte-province-bureau-${rendu}`);402403 // en 3D la vue d'ensemble reste inclinée : les cercles sont couchés sur le sol et ne se touchent pas davantage404 await page.getByRole("button", { name: "3D", exact: true }).click();405 await page.waitForFunction(() => window.__vxCarte.getCamera().pitch > 50, null, { timeout: 8000 }).catch(() => {});406 await page.evaluate(() => window.__vxCarte.jumpTo({ center: [-73.6, 45.53], zoom: 11.5 }));407 await page.waitForFunction(() => window.__vxEtat().donnees?.mode === "cases" && window.__vxEtat().donnees.cases.length > 30, null, { timeout: 8000 }).catch(() => {});408 await repos(page);409 const loin = await etat(page);410 verifier(loin.mode === "3d" && loin.cam.pitch > 50, "3D de loin : la vue reste inclinée", JSON.stringify(loin.cam));411 await capture(page, `carte-3d-montreal-ensemble-${rendu}`);412 await page.evaluate(() => window.__vxCarte.jumpTo({ center: [-71.2253, 46.8131], zoom: 16 }));413 await page.waitForFunction(() => window.__vxEtat().donnees?.mode === "points", null, { timeout: 8000 }).catch(() => {});414 await repos(page);415 const pres = await etat(page);416 verifier(pres.cam.pitch > 50 && pres.couches.plex > 50, "3D de près (Québec) : les bâtiments sont teintés", JSON.stringify({ cam: pres.cam, plex: pres.couches.plex }));417 await capture(page, `carte-3d-quebec-${rendu}`);418 await page.getByRole("button", { name: "Plan", exact: true }).click();419 await page.waitForFunction(() => window.__vxCarte.getCamera().pitch < 1 && Math.abs(window.__vxCarte.getCamera().bearing) < 1, null, { timeout: 8000 }).catch(() => {});420 await page.evaluate(() => window.__vxCarte.jumpTo({ center: [-71.9, 46.9], zoom: 6.2 }));421 await page.waitForFunction(() => window.__vxCarte.getCamera().pitch < 1 && window.__vxEtat().donnees?.mode === "cases", null, { timeout: 8000 }).catch(() => {});422 await repos(page);423424 await page.locator(".parc-barre select").selectOption("triplex");425 await page.waitForResponse((r) => r.url().includes("/api/v1/carte") && r.url().includes("classe=triplex"), { timeout: 8000 }).catch(() => verifier(false, "filtre de type transmis à l'API"));426 await page.waitForTimeout(500);427 verifier(/classe=triplex/.test(page.url()) && /moyenne/.test(await page.locator(".parc-legende").innerText()), "filtre par type : adresse et légende (moyenne, pas médiane)");428 await page.locator(".parc-barre select").selectOption("");429430 await page.getByLabel("À vendre seulement").check();431 await page.waitForFunction(() => window.__vxCarte.listLayers().find((l) => l.id === "avendre").count > 100, null, { timeout: 10000 }).catch(() => {});432 await repos(page);433 const grappes = await page.evaluate(() => {434 const m = window.__vxCarte.queryLayer("avendre");435 let chev = 0;436 for (let i = 0; i < m.length; i++) for (let j = i + 1; j < m.length; j++) {437 const a = m[i].rect, b = m[j].rect;438 if (a[0] < b[2] - 1 && b[0] < a[2] - 1 && a[1] < b[3] - 1 && b[1] < a[3] - 1) chev++;439 }440 return { n: m.length, grappes: m.filter((x) => x.type === "cluster").length, chev };441 });442 verifier(grappes.grappes > 10 && grappes.chev === 0, "à vendre, de loin : grappes chiffrées sans aucune plaque empilée", JSON.stringify(grappes));443 verifier(/prix demandé/i.test(await page.locator(".parc-legende").innerText()) && /vendre=1/.test(page.url()), "à vendre : la légende parle de prix demandés (observés)");444 await capture(page, `carte-avendre-province-${rendu}`);445 await garde(s, page, "/carte de loin");446 await ctx.close();447 }448449 // 6. adresse : état complet relu, ancienne ancre, lien d'une page de ville450 {451 const { ctx, page, s } = await ouvrir(nav, BUREAU);452 await page.goto(u("/carte?c=46.81300,-71.22500&z=15.6&vue=plan&classe=duplex&nuit=1"));453 await carte(page);454 await repos(page);455 let e = await etat(page);456 verifier(Math.abs(e.cam.center[1] - 46.813) < 0.002 && Math.abs(e.cam.zoom - 15.6) < 0.05 && e.mode === "2d" && e.theme === "midnight" && (await page.locator(".parc-barre select").inputValue()) === "duplex", "adresse relue : centre, zoom, plan, nuit, type", JSON.stringify(e.cam));457 await page.goto(u("/ville/23027"));458 const lien = page.locator('a[href^="/carte#"]').first();459 verifier((await lien.count()) === 1, "page de ville : lien vers la carte (ancienne ancre gardée)");460 if (await lien.count()) {461 const href = await lien.getAttribute("href");462 await page.goto(u(href));463 await carte(page);464 await repos(page);465 e = await etat(page);466 const m = href.match(/#(-?[\d.]+),(-?[\d.]+),([\d.]+)z/);467 verifier(m && Math.abs(e.cam.center[1] - Number(m[1])) < 0.01 && Math.abs(e.cam.zoom - Number(m[3])) < 0.05, "ancienne ancre #lat,lng,zoom relue", `${href} → ${JSON.stringify(e.cam.center)}`);468 }469 await garde(s, page, "adresses");470 await ctx.close();471 }472473 // 7. mobile 390 × 844474 {475 const { ctx, page, s } = await ouvrir(nav, MOBILE, { mobile: true });476 await page.goto(u("/carte"));477 await carte(page);478 await page.waitForFunction(() => window.__vxEtat?.().bilan, null, { timeout: 20000 }).catch(() => {});479 await repos(page);480 const m = await page.evaluate(() => ({ large: document.scrollingElement.scrollWidth, carte: document.querySelector(".parc-carte").getBoundingClientRect(), boutons: [...document.querySelectorAll(".ka-maps-btn, .parc-mode button")].map((b) => b.getBoundingClientRect().height) }));481 verifier(m.large <= 390, "mobile : aucun débordement horizontal", String(m.large));482 verifier(m.carte.height >= 320 && m.carte.bottom <= 844, "mobile : la carte tient dans le premier écran", JSON.stringify(m.carte));483 verifier(m.boutons.length >= 6 && m.boutons.every((h) => h >= 38), "mobile : cibles tactiles d'au moins 38 px", m.boutons.join(","));484 await capture(page, `carte-3d-mobile-jour-${rendu}`);485 await page.getByRole("button", { name: "Plan", exact: true }).tap();486 await page.waitForFunction(() => window.__vxCarte.getMode() === "2d" && window.__vxCarte.getCamera().pitch < 1, null, { timeout: 8000 }).catch(() => {});487 await repos(page);488 const cible = await page.evaluate(() => {489 const c = window.__vxCarte;490 const { donnees } = window.__vxEtat();491 const r = c.getCanvasElement().getBoundingClientRect();492 for (const p of donnees.points) {493 const xy = c.project([p.lng, p.lat]);494 if (!xy || xy[0] < 90 || xy[1] < 40 || xy[0] > r.width - 30 || xy[1] > r.height - 40) continue;495 const f = c.queryRendered(xy, {}).find((x) => x.source === "app" && x.layer === "plex");496 if (f && String(f.id) === p.id) return { id: p.id, x: r.left + xy[0], y: r.top + xy[1] };497 }498 return null;499 });500 if (cible) {501 await page.touchscreen.tap(cible.x, cible.y);502 await page.locator(".parc-fiche").waitFor({ timeout: 5000 }).catch(() => {});503 await page.waitForTimeout(900);504 const vu = await page.evaluate(() => {505 const r = document.querySelector(".parc-fiche h2")?.getBoundingClientRect();506 return r ? r.top >= 0 && r.bottom <= window.innerHeight : false;507 });508 verifier(vu, "mobile : l'immeuble touché est amené à l'écran sous la carte");509 await capture(page, `carte-plan-mobile-choix-${rendu}`);510 } else verifier(false, "mobile : un bâtiment à toucher");511 await page.getByRole("button", { name: "Nuit", exact: true }).tap();512 await page.waitForFunction(() => window.__vxCarte.getTheme().name === "midnight", null, { timeout: 8000 }).catch(() => {});513 await page.evaluate(() => window.scrollTo(0, 0));514 await repos(page);515 await capture(page, `carte-plan-mobile-nuit-${rendu}`);516 await garde(s, page, "/carte mobile");517 await ctx.close();518 }519520 // 8. carte de la fiche d'un immeuble521 {522 const { ctx, page, s } = await ouvrir(nav, BUREAU);523 const id = await (await ctx.request.get(`${BASE}/api/v1/carte?o=-73.582&s=45.525&e=-73.577&n=45.528&z=16`)).json().then((d) => d.points.find((p) => p.v && p.s === "ferme")?.id ?? d.points[0].id);524 await page.goto(u(`/immeuble/${id}`));525 await page.locator(".carte").scrollIntoViewIfNeeded();526 await carte(page, "__vxCarteFiche");527 await repos(page, "__vxCarteFiche");528 const f = await page.evaluate(() => {529 const c = window.__vxCarteFiche;530 return { backend: c.backend, mode: c.getMode(), cam: c.getCamera(), couches: Object.fromEntries(c.listLayers().map((l) => [l.id, l.count])), repere: c.queryLayer("reperes").map((m) => ({ label: m.label, rect: m.rect })) };531 });532 verifier((NAVIGATEUR !== "chromium" || f.backend === rendu) && f.mode === "3d" && f.cam.zoom >= 15.19, "fiche : carte en volume, de près", JSON.stringify(f.cam));533 verifier(f.couches.immeubles >= 1 && f.couches.reperes === f.couches.immeubles, "fiche : immeuble et comparables sur les bâtiments réels, un repère chacun", JSON.stringify(f.couches));534 verifier(f.repere.length < 2 || f.repere.some((m) => /\$/.test(m.label ?? "")), "fiche : les comparables portent leur prix payé", f.repere.map((m) => m.label).join(", "));535 const sujet = f.repere.find((m) => m.label === "Cet immeuble");536 const point = await page.evaluate(() => window.__vxCarteFiche.project(window.__vxCarteFiche.getCamera().center));537 verifier(sujet && point[1] - sujet.rect[3] >= 20 && Math.abs((sujet.rect[0] + sujet.rect[2]) / 2 - point[0]) < 4, "fiche : « Cet immeuble » est écartée au-dessus de son bâtiment (offset du moteur)", JSON.stringify({ rect: sujet?.rect, point }));538 if (sujet) {539 const boite = await page.locator(".carte canvas.ka-maps-canvas").boundingBox();540 await page.mouse.click(boite.x + (sujet.rect[0] + sujet.rect[2]) / 2, boite.y + (sujet.rect[1] + sujet.rect[3]) / 2);541 await page.locator(".carte-bulle").waitFor({ timeout: 4000 }).catch(() => {});542 verifier(/cet immeuble/.test(await page.locator(".carte-bulle").innerText().catch(() => "")), "fiche : un clic sur le repère nomme l'immeuble");543 await page.mouse.click(boite.x + 5, boite.y + boite.height - 60);544 }545 await page.waitForTimeout(800);546 await capture(page, `fiche-carte-bureau-${rendu}`, ".carte");547 await garde(s, page, "carte de la fiche");548 await ctx.close();549 }550}551552// ---------------------------------------------------------------------------------- sans GPU : listes de repli553async function sansGpu() {554 courant = "sans GPU";555 console.log("\n== sans GPU (ni WebGPU ni WebGL 2)");556 const nav = await chromium.launch({ args: SANS_GPU });557 const { ctx, page } = await ouvrir(nav, BUREAU);558 await page.goto(`${BASE}/carte`);559 await page.locator(".parc[data-sans-carte]").waitFor({ timeout: 30000 }).catch(() => {});560 verifier((await page.locator(".parc[data-sans-carte]").count()) === 1, "repli : la page le dit et garde ses filtres");561 await page.waitForFunction(() => document.querySelectorAll(".parc-liste li").length > 0, null, { timeout: 10000 }).catch(() => {});562 const n1 = await page.locator(".parc-liste li").count();563 verifier(n1 > 0, "repli : la liste de la zone est remplie", String(n1));564 const avant = await page.locator(".parc-etat").innerText();565 await page.getByRole("button", { name: "Élargir la zone" }).click();566 await page.waitForFunction((a) => document.querySelector(".parc-etat").textContent !== a, avant, { timeout: 8000 }).catch(() => {});567 verifier((await page.locator(".parc-etat").innerText()) !== avant && /z=15\.2/.test(page.url()), "repli : « Élargir la zone » recharge la liste et l'adresse", page.url());568 await page.locator(".parc-liste li button").first().click();569 verifier((await page.locator(".parc-fiche a.bouton").count()) === 1, "repli : un immeuble de la liste ouvre sa fiche");570 await capture(page, "carte-sans-gpu");571 const id = await (await ctx.request.get(`${BASE}/api/v1/carte?o=-73.582&s=45.525&e=-73.577&n=45.528&z=16`)).json().then((d) => d.points[0].id);572 await page.goto(`${BASE}/immeuble/${id}`);573 await page.locator(".carte-repli").waitFor({ timeout: 30000 }).catch(() => {});574 verifier((await page.locator(".carte-repli li").count()) >= 1, "repli de la fiche : liste de l'immeuble et de ses comparables");575 await ctx.close();576 await nav.close();577}578579// ---------------------------------------------------------------------------------- en-têtes et pages580async function statique() {581 courant = "en-têtes";582 console.log("\n== en-têtes et pages");583 const r = await fetch(`${BASE}/carte`);584 const csp = r.headers.get("content-security-policy") ?? "";585 verifier(!INTERDITS.test(csp) && !/blob:/.test(csp), "CSP : ni hôte de carte tiers ni blob:", csp);586 verifier(HOTES_CARTE.every((h) => csp.includes(`https://${h}`)) && /'wasm-unsafe-eval'/.test(csp) && /worker-src 'self'(;|$)/.test(csp), "CSP : les quatre services KA Maps, wasm, worker de même origine");587 const html = await r.text();588 verifier(!INTERDITS.test(html), "page /carte : aucune mention d'un fournisseur de carte tiers");589 for (const chemin of ["/", "/a-vendre", "/portefeuille", "/comparer", "/marche", "/calculateur", "/ville/66023"]) {590 const p = await fetch(BASE + chemin);591 verifier(p.ok && !INTERDITS.test(await p.text()), `${chemin} : page servie, sans mention d'un fournisseur de carte tiers`, String(p.status));592 }593 const conf = await (await fetch(`${BASE}/confidentialite`)).text();594 verifier(!/OpenFreeMap|MapLibre/i.test(conf) && /KA Maps/.test(conf), "confidentialité : cartes servies par nos serveurs");595 const wasm = await fetch(`${BASE}/ka-maps/0.4.2/km_wasm_bg.wasm`, { method: "HEAD" });596 verifier(wasm.ok && wasm.headers.get("content-type") === "application/wasm" && /immutable/.test(wasm.headers.get("cache-control") ?? ""), "moteur servi par le site : type wasm, cache immuable");597 if (/sslip\.io|127\.0\.0\.1:8198/.test(BASE)) {598 verifier(/noindex/.test(r.headers.get("x-robots-tag") ?? ""), "préproduction : X-Robots-Tag noindex");599 verifier(/Disallow: \/\s*$/m.test(await (await fetch(`${BASE}/robots.txt`)).text()), "préproduction : robots.txt ferme tout");600 }601}602603const debut = Date.now();604await statique();605if (!arg("rendu") && NAVIGATEUR === "chromium") await sansGpu();606const nav = NAVIGATEUR === "webkit" ? await webkit.launch() : NAVIGATEUR === "firefox" ? await firefox.launch() : await chromium.launch({ args: GPU });607for (const r of RENDUS) await parcours(nav, r);608await nav.close();609console.log("\n" + Object.entries(parSection).map(([k, [ok, ko]]) => `${k} : ${ok} réussies${ko ? `, ${ko} échec(s)` : ""}`).join(" · "));610console.log(`${reussis} vérifications réussies, ${echecs.length} échec(s), ${((Date.now() - debut) / 1000).toFixed(0)} s`);611if (echecs.length) {612 console.log(echecs.map((e) => ` - ${e}`).join("\n"));613 process.exit(1);614}615