Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : tests/maps-library.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *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: support@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 */4243import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";44import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";45import { tmpdir } from "node:os";46import { join } from "node:path";47import { mapLibrary, mapSize } from "@/lib/maps";48import { resetRateLimits } from "@/lib/security/ratelimit";4950/** The Maps page library (src/lib/maps.ts) on throw-away distribution directories. */5152const dirs: string[] = [];53const saved = process.env.ORIX_MAPS_DIR;54let v1 = "";5556beforeEach(() => {57 const dir = mkdtempSync(join(tmpdir(), "orix-maps-lib-"));58 dirs.push(dir);59 v1 = join(dir, "v1");60 mkdirSync(v1, { recursive: true });61 process.env.ORIX_MAPS_DIR = dir;62});63afterEach(() => { if (saved === undefined) delete process.env.ORIX_MAPS_DIR; else process.env.ORIX_MAPS_DIR = saved; });64afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });6566const put = (relative: string, content: unknown) => {67 const file = join(v1, relative);68 mkdirSync(join(file, ".."), { recursive: true });69 writeFileSync(file, typeof content === "string" ? content : JSON.stringify(content, null, 2));70};71const schema = { major: 1, minor: 0 };72const latest = (id: string, downloadSize: number, over: Record<string, unknown> = {}) => ({73 buildDate: "2026-11-25T09:00:43Z", dataTimestamp: "2026-11-24T21:21:23Z", dataVersion: "2026.11.24", downloadSize, installedSize: downloadSize - 8000,74 path: `files/${id}/2026.11.24/${id}-2026.11.24.orixmap`, preambleSize: 1800, sha256: "a".repeat(64), signingKeyId: "0000000000000000", ...over,75});76const region = (id: string, names: Record<string, string>, downloadSize: number, over: Record<string, unknown> = {}) => ({77 id, names, bbox: { minLat: 0, minLon: 0, maxLat: 1, maxLon: 1 }, capabilities: ["map", "search", "routing"], latest: latest(id, downloadSize), ...over,78});79const licences = [80 { attribution: "© OpenStreetMap contributors", licence: "ODbL-1.0", source: "OpenStreetMap", url: "https://www.openstreetmap.org/copyright" },81 { attribution: "Made with Natural Earth", licence: "Public domain", source: "Natural Earth", url: "https://www.naturalearthdata.com/about/terms-of-use/" },82];83const detail = (r: ReturnType<typeof region>, over: Record<string, unknown> = {}) => ({84 schema, generatedAt: "2026-11-25T09:05:21Z", region: r, licences, languages: ["en", "fr"],85 components: [{ id: "map", length: 24138186, formatVersion: 3, mediaType: "application/vnd.pmtiles", sha256: "b".repeat(64) }, { id: "search", length: 6217728 }, { id: "routing", length: 10632648 }], ...over,86});87const catalog = (regions: unknown) => put("catalog.json", { schema, generatedAt: "2026-11-25T09:05:21Z", regions });8889const province = region("ca-qc", { en: "Québec (province)", fr: "Québec (province)" }, 1730559840);90const montreal = region("ca-qc-montreal", { en: "Greater Montréal", fr: "Grand Montréal" }, 221550600);91const quebec = region("ca-qc-quebec-city", { en: "Québec City region", fr: "Région de Québec" }, 40996296);9293describe("published catalogue", () => {94 it("lists every region, smallest download first, with names, sizes, data date and version", async () => {95 catalog([province, montreal, quebec]);96 for (const r of [province, montreal, quebec]) put(`regions/${r.id}.json`, detail(r));97 const lib = await mapLibrary();98 expect(lib.updated).toBe("2026-11-25T09:05:21Z");99 expect(lib.regions.map((r) => r.id)).toEqual(["ca-qc-quebec-city", "ca-qc-montreal", "ca-qc"]);100 const [q, m] = lib.regions;101 expect(q.names).toEqual({ en: "Québec City region", fr: "Région de Québec" });102 expect(m.names.fr).toBe("Grand Montréal");103 expect(q).toMatchObject({ downloadBytes: 40996296, installedBytes: 40988296, dataDate: "2026-11-24T21:21:23Z", dataVersion: "2026.11.24", capabilities: ["map", "search", "routing"] });104 expect(q.licences.map((l) => `${l.source}: ${l.attribution} (${l.licence})`)).toEqual(["OpenStreetMap: © OpenStreetMap contributors (ODbL-1.0)", "Natural Earth: Made with Natural Earth (Public domain)"]);105 expect(q.licences[0].url).toBe("https://www.openstreetmap.org/copyright");106 expect(q.components).toEqual([{ id: "map", bytes: 24138186 }, { id: "search", bytes: 6217728 }, { id: "routing", bytes: 10632648 }]);107 });108109 it("keeps only the capabilities the site knows, in a fixed order, and falls back to the English name", async () => {110 catalog([region("north", { en: "North" }, 5000, { capabilities: ["routing", "terrain", "map", 7] }), region("south", { fr: "Sud" }, 6000, { capabilities: "map" })]);111 const lib = await mapLibrary();112 expect(lib.regions[0]).toMatchObject({ id: "north", names: { en: "North", fr: "North" }, capabilities: ["map", "routing"] });113 expect(lib.regions[1]).toMatchObject({ id: "south", names: { en: "Sud", fr: "Sud" }, capabilities: [] });114 });115116 it("lists a region without credits when its document is missing, malformed, or describes another version", async () => {117 const stale = region("stale", { en: "Stale" }, 3000), broken = region("broken", { en: "Broken" }, 2000), alone = region("alone", { en: "Alone" }, 1000);118 catalog([stale, broken, alone]);119 put("regions/stale.json", detail({ ...stale, latest: latest("stale", 3000, { dataVersion: "2026.11.10" }) }));120 put("regions/broken.json", "{ not json");121 const lib = await mapLibrary();122 expect(lib.regions.map((r) => r.id)).toEqual(["alone", "broken", "stale"]);123 for (const r of lib.regions) { expect(r.licences).toEqual([]); expect(r.components).toEqual([]); }124 });125126 it("drops malformed licence and component rows and any link that is not https", async () => {127 const r = region("mixed", { en: "Mixed" }, 1000);128 catalog([r]);129 put("regions/mixed.json", detail(r, {130 licences: [{ source: "OpenStreetMap", attribution: "© OpenStreetMap contributors", licence: "ODbL-1.0", url: "javascript:alert(1)" }, { source: "No attribution" }, "text", null, { source: "Plain", attribution: "Plain data" }],131 components: [{ id: "map", length: 10 }, { id: "search", length: -1 }, { length: 5 }, "x"],132 }));133 const [m] = (await mapLibrary()).regions;134 expect(m.licences).toEqual([{ source: "OpenStreetMap", attribution: "© OpenStreetMap contributors", licence: "ODbL-1.0", url: null }, { source: "Plain", attribution: "Plain data", licence: "", url: null }]);135 expect(m.components).toEqual([{ id: "map", bytes: 10 }]);136 });137138 it("skips entries it cannot describe truthfully and keeps the others", async () => {139 catalog([140 quebec,141 region("../escape", { en: "Escape" }, 1000), region("UPPER", { en: "Upper" }, 1000), region("ca-qc-quebec-city", { en: "Duplicate" }, 999),142 region("no-size", { en: "No size" }, 1000, { latest: latest("no-size", 1000, { downloadSize: undefined }) }),143 region("zero", { en: "Zero" }, 1000, { latest: latest("zero", 1000, { downloadSize: 0 }) }),144 region("text-size", { en: "Text" }, 1000, { latest: latest("text-size", 1000, { downloadSize: "1000" }) }),145 region("bad-version", { en: "Bad version" }, 1000, { latest: latest("bad-version", 1000, { dataVersion: "../1" }) }),146 region("no-latest", { en: "No latest" }, 1000, { latest: null }), region("no-name", {}, 1000), "text", null, 42,147 region("odd-date", { en: "Odd date" }, 500, { latest: latest("odd-date", 500, { dataTimestamp: "yesterday", installedSize: "big" }) }),148 ]);149 const lib = await mapLibrary();150 expect(lib.regions.map((r) => r.id)).toEqual(["odd-date", "ca-qc-quebec-city"]);151 expect(lib.regions[0]).toMatchObject({ dataDate: null, installedBytes: null });152 expect(lib.regions[1].names.en).toBe("Québec City region");153 });154155 it("does not follow a region document that is a symbolic link leaving the distribution", async () => {156 const outside = mkdtempSync(join(tmpdir(), "orix-maps-out-"));157 dirs.push(outside);158 const r = region("linked", { en: "Linked" }, 1000);159 writeFileSync(join(outside, "linked.json"), JSON.stringify(detail(r)));160 catalog([r]);161 mkdirSync(join(v1, "regions"), { recursive: true });162 symlinkSync(join(outside, "linked.json"), join(v1, "regions/linked.json"));163 expect((await mapLibrary()).regions).toMatchObject([{ id: "linked", licences: [], components: [] }]);164 });165166 it("reads the directory the /maps/v1 route serves", async () => {167 catalog([quebec]);168 resetRateLimits();169 const { GET } = await import("@/app/maps/v1/[...path]/route");170 const served = await GET(new Request("https://orix.test/maps/v1/catalog.json"), { params: Promise.resolve({ path: ["catalog.json"] }) });171 expect(served.status).toBe(200);172 const ids = ((await served.json()) as { regions: { id: string }[] }).regions.map((r) => r.id);173 expect((await mapLibrary()).regions.map((r) => r.id)).toEqual(ids);174 });175});176177describe("empty or unreadable catalogue", () => {178 const empty = { regions: [], updated: null };179180 it("is an empty library when the distribution is empty or missing", async () => {181 expect(await mapLibrary()).toEqual(empty);182 process.env.ORIX_MAPS_DIR = join(v1, "missing");183 expect(await mapLibrary()).toEqual(empty);184 });185186 it("is an empty library when catalog.json is malformed or has another shape", async () => {187 for (const raw of ["", "{ not json", "null", "[]", "\"text\"", "{}", "{\"regions\":{}}", "{\"regions\":\"all\"}", "{\"regions\":[]}"]) {188 put("catalog.json", raw);189 expect(await mapLibrary(), raw).toEqual(empty);190 }191 });192193 it("is an empty library when catalog.json is a directory or a link leaving the distribution", async () => {194 mkdirSync(join(v1, "catalog.json"));195 expect(await mapLibrary()).toEqual(empty);196 rmSync(join(v1, "catalog.json"), { recursive: true });197 const outside = mkdtempSync(join(tmpdir(), "orix-maps-out-"));198 dirs.push(outside);199 writeFileSync(join(outside, "catalog.json"), JSON.stringify({ schema, generatedAt: "2026-11-25T09:05:21Z", regions: [quebec] }));200 symlinkSync(join(outside, "catalog.json"), join(v1, "catalog.json"));201 expect(await mapLibrary()).toEqual(empty);202 });203204 it("reports no catalogue date when the stamp is not a date", async () => {205 put("catalog.json", { schema, generatedAt: "soon", regions: [quebec] });206 const lib = await mapLibrary();207 expect(lib.regions).toHaveLength(1);208 expect(lib.updated).toBeNull();209 });210});211212describe("sizes", () => {213 it("uses the decimal units the application shows", () => {214 expect(mapSize(40996296, "en")).toBe("41 MB");215 expect(mapSize(221550600, "en")).toBe("222 MB");216 expect(mapSize(1730559840, "en")).toBe("1.7 GB");217 expect(mapSize(40996296, "fr")).toBe("41 Mo");218 expect(mapSize(1730559840, "fr")).toBe("1,7 Go");219 });220});221