mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
build(atlas): build the globe geometry from the bundled boundaries
scripts/build-atlas-mesh.mjs turns the admin-0 and admin-1 GeoJSON the server already ships into TopoJSON at three levels of detail per world and two per country's regions, smoothed, quantized and Brotli-packed under content-hashed names, plus a manifest with every country's anchor, box and region index. It runs at build time (npm run build, npm run dev when the sources changed, and the Docker server stage); the output is not committed. /api/addons/atlas/mesh serves the manifest and the files as they are (immutable, a year), decompressing as a stream for a client without br.
This commit is contained in:
@@ -74,3 +74,6 @@ minio-licence.key
|
||||
|
||||
.run
|
||||
.full-review
|
||||
|
||||
# Built by server/scripts/build-atlas-mesh.mjs (npm run dev/build, Docker build)
|
||||
server/assets/atlas-mesh/
|
||||
|
||||
@@ -41,6 +41,9 @@ COPY server/package.json ./server/
|
||||
RUN npm ci --workspace=server --ignore-scripts
|
||||
COPY --from=shared-builder /app/shared/dist ./shared/dist
|
||||
COPY server/ ./server/
|
||||
# The globe Atlas geometry is built from the committed boundary files (no network,
|
||||
# deterministic) here rather than committed; it lands in server/assets with the rest.
|
||||
RUN node server/scripts/build-atlas-mesh.mjs
|
||||
RUN npm run build --workspace=server
|
||||
|
||||
# ── Stage 4: production runtime ──────────────────────────────────────────────
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
"axios": "^1.21.0",
|
||||
"dexie": "^4.4.7",
|
||||
"drag-drop-touch": "^1.3.1",
|
||||
"earcut": "^3.0.2",
|
||||
"heic-to": "^1.6.7",
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
@@ -126,6 +127,7 @@
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"tz-lookup": "^6.1.25",
|
||||
"zod": "^4.6.7",
|
||||
"zustand": "^5.0.15"
|
||||
@@ -145,6 +147,7 @@
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
|
||||
Generated
+99
@@ -87,6 +87,7 @@
|
||||
"axios": "^1.21.0",
|
||||
"dexie": "^4.4.7",
|
||||
"drag-drop-touch": "^1.3.1",
|
||||
"earcut": "^3.0.2",
|
||||
"heic-to": "^1.6.7",
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
@@ -105,6 +106,7 @@
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"tz-lookup": "^6.1.25",
|
||||
"zod": "^4.6.7",
|
||||
"zustand": "^5.0.15"
|
||||
@@ -124,6 +126,7 @@
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
@@ -10850,6 +10853,27 @@
|
||||
"@types/superagent": "^8.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/topojson-client": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/topojson-client/-/topojson-client-3.1.5.tgz",
|
||||
"integrity": "sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/geojson": "*",
|
||||
"@types/topojson-specification": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/topojson-specification": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/topojson-specification/-/topojson-specification-1.0.5.tgz",
|
||||
"integrity": "sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/geojson": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
@@ -19643,6 +19667,16 @@
|
||||
"node": ">=14.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/polylabel": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/polylabel/-/polylabel-2.1.0.tgz",
|
||||
"integrity": "sha512-ZCL9pc/BpnyBB1Es5Eh6baziBhZFS0fTlEXGarLMqbMYbAyawqGAjyo2+MfignMggSubmllMgRGcR0L0liOugg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"tinyqueue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
@@ -23011,6 +23045,67 @@
|
||||
"url": "https://github.com/sponsors/Borewit"
|
||||
}
|
||||
},
|
||||
"node_modules/topojson-client": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/topojson-client/-/topojson-client-3.1.0.tgz",
|
||||
"integrity": "sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"commander": "2"
|
||||
},
|
||||
"bin": {
|
||||
"topo2geo": "bin/topo2geo",
|
||||
"topomerge": "bin/topomerge",
|
||||
"topoquantize": "bin/topoquantize"
|
||||
}
|
||||
},
|
||||
"node_modules/topojson-client/node_modules/commander": {
|
||||
"version": "2.20.3",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
|
||||
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/topojson-server": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/topojson-server/-/topojson-server-3.0.1.tgz",
|
||||
"integrity": "sha512-/VS9j/ffKr2XAOjlZ9CgyyeLmgJ9dMwq6Y0YEON8O7p/tGGk+dCWnrE03zEdu7i4L7YsFZLEPZPzCvcB7lEEXw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"commander": "2"
|
||||
},
|
||||
"bin": {
|
||||
"geo2topo": "bin/geo2topo"
|
||||
}
|
||||
},
|
||||
"node_modules/topojson-server/node_modules/commander": {
|
||||
"version": "2.20.3",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
|
||||
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/topojson-simplify": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/topojson-simplify/-/topojson-simplify-3.0.3.tgz",
|
||||
"integrity": "sha512-V+pBjLVzSQ3+hSOxBiV01OVXgFiCmMO8ia3huxKEyIMTC1ApQHBcdXdOqcQ6U2JJJD31TZduwY6KyF15R8sUgg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"commander": "2",
|
||||
"topojson-client": "3"
|
||||
},
|
||||
"bin": {
|
||||
"toposimplify": "bin/toposimplify"
|
||||
}
|
||||
},
|
||||
"node_modules/topojson-simplify/node_modules/commander": {
|
||||
"version": "2.20.3",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
|
||||
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
|
||||
@@ -25385,9 +25480,13 @@
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"polylabel": "^2.0.1",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"supertest": "^7.3.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"topojson-server": "^3.0.1",
|
||||
"topojson-simplify": "^3.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"unplugin-swc": "^1.6.0",
|
||||
"vitest": "^5.1.2"
|
||||
|
||||
+7
-2
@@ -7,8 +7,9 @@
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"start": "node --require tsconfig-paths/register dist/index.js",
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"build": "node scripts/build.mjs",
|
||||
"dev": "node scripts/build-atlas-mesh.mjs --if-stale && node scripts/dev.mjs",
|
||||
"build:atlas-mesh": "node scripts/build-atlas-mesh.mjs --if-stale",
|
||||
"build": "node scripts/build-atlas-mesh.mjs --if-stale && node scripts/build.mjs",
|
||||
"start:prod": "node --require tsconfig-paths/register dist/index.js",
|
||||
"reset-admin": "node reset-admin.js",
|
||||
"db:move-to-postgres": "node --import tsx src/move-to-postgres.ts",
|
||||
@@ -149,9 +150,13 @@
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"polylabel": "^2.0.1",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"supertest": "^7.3.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"topojson-server": "^3.0.1",
|
||||
"topojson-simplify": "^3.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"unplugin-swc": "^1.6.0",
|
||||
"vitest": "^5.1.2"
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Builds the Atlas globe geometry from the committed boundary files.
|
||||
*
|
||||
* Input: server/assets/atlas/admin0.geojson.gz and admin1/<A2>.geojson.gz
|
||||
* Output: server/assets/atlas-mesh/manifest.json, world-<lod>.<hash>.json.br,
|
||||
* regions/<A2>-<lod>.<hash>.json.br
|
||||
*
|
||||
* Runs in the Docker build (server-builder stage), from `npm run build` and from
|
||||
* `npm run dev`. With --if-stale it does nothing when the inputs and this script
|
||||
* are unchanged since the last run (a hash in atlas-mesh/.source-hash); the
|
||||
* output is not committed.
|
||||
*
|
||||
* Every level of detail is a TopoJSON topology simplified on its shared arcs, so
|
||||
* neighbours keep identical borders and no slivers open between them. Small
|
||||
* detached islands are dropped from the coarse levels. The browser decodes,
|
||||
* triangulates and tessellates in a worker. Reads local files only, so the
|
||||
* output is deterministic and the file names carry a content hash.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { gunzipSync, brotliCompressSync, constants as zc } from 'node:zlib';
|
||||
import polylabel from 'polylabel';
|
||||
import { quantize } from 'topojson-client';
|
||||
import { topology } from 'topojson-server';
|
||||
import { presimplify, simplify, quantile, filter, filterAttachedWeight, planarRingArea } from 'topojson-simplify';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const SRC = join(HERE, '..', 'assets', 'atlas');
|
||||
const OUT = join(HERE, '..', 'assets', 'atlas-mesh');
|
||||
|
||||
/**
|
||||
* keep: share of points kept (topojson-simplify quantile).
|
||||
* island: detached rings below this planar area (square degrees) are dropped.
|
||||
* q: quantization grid of the output.
|
||||
*/
|
||||
// keep is measured after smoothing, which quadruples the points of every arc.
|
||||
const WORLD_LODS = [
|
||||
{ id: 'l0', keep: 0.003, island: 0.05, q: 1e4 },
|
||||
{ id: 'l1', keep: 0.0125, island: 0.004, q: 3e4 },
|
||||
{ id: 'l2', keep: 0.055, island: 0, q: 1e5 },
|
||||
];
|
||||
const REGION_LODS = [
|
||||
{ id: 'r0', keep: 0.015, island: 0.002, q: 1e4 },
|
||||
{ id: 'r1', keep: 0.07, island: 0, q: 4e4 },
|
||||
];
|
||||
// Regions that can be marked but are not part of the "x of n" total.
|
||||
const COUNT_EXCLUDE = { US: ['US-DC', 'US-PR', 'US-AS', 'US-GU', 'US-MP', 'US-VI', 'US-UM'] };
|
||||
|
||||
const readGz = (p) => JSON.parse(gunzipSync(readFileSync(p)).toString('utf8'));
|
||||
|
||||
function polygonsOf(geom) {
|
||||
if (!geom) return [];
|
||||
if (geom.type === 'Polygon') return [geom.coordinates];
|
||||
if (geom.type === 'MultiPolygon') return geom.coordinates;
|
||||
return [];
|
||||
}
|
||||
|
||||
function ringArea(r) {
|
||||
let a = 0;
|
||||
for (let i = 0, n = r.length - 1; i < n; i++) a += r[i][0] * r[i + 1][1] - r[i + 1][0] * r[i][1];
|
||||
return Math.abs(a / 2);
|
||||
}
|
||||
|
||||
/** Planar centroid of a ring in a space where longitude is scaled by kx. */
|
||||
function ringCentroid(ring, kx) {
|
||||
let a = 0;
|
||||
let cx = 0;
|
||||
let cy = 0;
|
||||
for (let i = 0, n = ring.length - 1; i < n; i++) {
|
||||
const x0 = ring[i][0] * kx,
|
||||
y0 = ring[i][1];
|
||||
const x1 = ring[i + 1][0] * kx,
|
||||
y1 = ring[i + 1][1];
|
||||
const f = x0 * y1 - x1 * y0;
|
||||
a += f;
|
||||
cx += (x0 + x1) * f;
|
||||
cy += (y0 + y1) * f;
|
||||
}
|
||||
if (Math.abs(a) < 1e-12) return null;
|
||||
return [cx / (3 * a) / kx, cy / (3 * a)];
|
||||
}
|
||||
|
||||
function pointInPolygon(pt, poly) {
|
||||
let inside = false;
|
||||
for (const ring of poly) {
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
const [xi, yi] = ring[i];
|
||||
const [xj, yj] = ring[j];
|
||||
if (yi > pt[1] !== yj > pt[1] && pt[0] < ((xj - xi) * (pt[1] - yi)) / (yj - yi) + xi) inside = !inside;
|
||||
}
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Label anchor: the visual centre of the largest polygon, measured with
|
||||
* longitude shrunk by the cosine of its latitude as on screen. The centroid where
|
||||
* it falls inside the shape (most countries), else the pole of inaccessibility
|
||||
* in the same space (crescents such as Croatia or Chile).
|
||||
*/
|
||||
function anchorOf(f) {
|
||||
let best = null;
|
||||
let bestA = -1;
|
||||
for (const poly of polygonsOf(f.geometry)) {
|
||||
const a = ringArea(poly[0]);
|
||||
if (a > bestA) {
|
||||
bestA = a;
|
||||
best = poly;
|
||||
}
|
||||
}
|
||||
if (!best) return null;
|
||||
let lat0 = 0;
|
||||
for (const p of best[0]) lat0 += p[1];
|
||||
lat0 /= best[0].length;
|
||||
const kx = Math.max(0.2, Math.cos((lat0 * Math.PI) / 180));
|
||||
const c = ringCentroid(best[0], kx);
|
||||
if (c && pointInPolygon(c, best)) return [round3(c[0]), round3(c[1])];
|
||||
const scaled = best.map((ring) => ring.map(([x, y]) => [x * kx, y]));
|
||||
const p = polylabel(scaled, 0.02);
|
||||
return [round3(p[0] / kx), round3(p[1])];
|
||||
}
|
||||
|
||||
const round3 = (v) => Math.round(v * 1000) / 1000;
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function totalArea(f) {
|
||||
let a = 0;
|
||||
for (const poly of polygonsOf(f.geometry)) a += ringArea(poly[0]);
|
||||
return a;
|
||||
}
|
||||
|
||||
function bboxOf(features) {
|
||||
let w = 180;
|
||||
let s = 90;
|
||||
let e = -180;
|
||||
let n = -90;
|
||||
for (const f of features)
|
||||
for (const poly of polygonsOf(f.geometry))
|
||||
for (const p of poly[0] ?? []) {
|
||||
if (p[0] < w) w = p[0];
|
||||
if (p[0] > e) e = p[0];
|
||||
if (p[1] < s) s = p[1];
|
||||
if (p[1] > n) n = p[1];
|
||||
}
|
||||
return [w, s, e, n];
|
||||
}
|
||||
|
||||
/**
|
||||
* Snaps a ring onto a grid of `step` degrees and drops repeated points. Borders
|
||||
* that nearly coincide in the source then share their vertices, so the topology
|
||||
* finds them as one arc instead of thousands of two-point pieces.
|
||||
*/
|
||||
function snapRing(ring, step) {
|
||||
const out = [];
|
||||
for (const [x, y] of ring) {
|
||||
const p = [Math.round(x / step) * step, Math.round(y / step) * step];
|
||||
const last = out[out.length - 1];
|
||||
if (!last || last[0] !== p[0] || last[1] !== p[1]) out.push(p);
|
||||
}
|
||||
if (out.length > 1) {
|
||||
const a = out[0],
|
||||
b = out[out.length - 1];
|
||||
if (a[0] !== b[0] || a[1] !== b[1]) out.push([a[0], a[1]]);
|
||||
}
|
||||
return out.length >= 4 ? out : null;
|
||||
}
|
||||
|
||||
/** Keeps only the snapped geometry and a numeric id, so the topology carries no names. */
|
||||
function slim(features, step) {
|
||||
return features.map((f, i) => {
|
||||
const polys = [];
|
||||
for (const poly of polygonsOf(f.geometry)) {
|
||||
const outer = snapRing(poly[0], step);
|
||||
if (!outer) continue;
|
||||
polys.push([
|
||||
outer,
|
||||
...poly
|
||||
.slice(1)
|
||||
.map((r) => snapRing(r, step))
|
||||
.filter(Boolean),
|
||||
]);
|
||||
}
|
||||
return { type: 'Feature', id: i, properties: null, geometry: { type: 'MultiPolygon', coordinates: polys } };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Two rounds of Chaikin corner cutting on one arc, ends kept. The sources sit on
|
||||
* a 0.01 degree grid, which shows as stair steps when zoomed in; smoothing the
|
||||
* shared arcs (not the rings) keeps neighbours on one identical border.
|
||||
*/
|
||||
function smoothArc(arc) {
|
||||
let pts = arc;
|
||||
for (let round = 0; round < 2; round++) {
|
||||
if (pts.length < 3) return pts;
|
||||
const out = [pts[0]];
|
||||
for (let i = 0; i < pts.length - 1; i++) {
|
||||
const [x0, y0] = pts[i];
|
||||
const [x1, y1] = pts[i + 1];
|
||||
out.push([x0 * 0.75 + x1 * 0.25, y0 * 0.75 + y1 * 0.25], [x0 * 0.25 + x1 * 0.75, y0 * 0.25 + y1 * 0.75]);
|
||||
}
|
||||
out.push(pts[pts.length - 1]);
|
||||
pts = out;
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
function buildTopo(features, name, lod) {
|
||||
const step = Math.max(0.01, 360 / lod.q);
|
||||
const topo = topology({ [name]: { type: 'FeatureCollection', features: slim(features, step) } });
|
||||
topo.arcs = topo.arcs.map(smoothArc);
|
||||
const pre = presimplify(topo);
|
||||
let simp = simplify(pre, quantile(pre, lod.keep));
|
||||
if (lod.island > 0) simp = filter(simp, filterAttachedWeight(simp, lod.island, planarRingArea));
|
||||
for (const arc of simp.arcs) for (const p of arc) p.length = 2;
|
||||
const q = quantize(simp, lod.q);
|
||||
delete q.bbox;
|
||||
return Buffer.from(JSON.stringify(q));
|
||||
}
|
||||
|
||||
function write(rel, buf, files) {
|
||||
const h = createHash('sha256').update(buf).digest('hex').slice(0, 12);
|
||||
const name = rel.replace(/\.json$/, `.${h}.json`);
|
||||
mkdirSync(dirname(join(OUT, name)), { recursive: true });
|
||||
const br = brotliCompressSync(buf, { params: { [zc.BROTLI_PARAM_QUALITY]: 11 } });
|
||||
writeFileSync(join(OUT, name + '.br'), br);
|
||||
files[rel] = name;
|
||||
return { name, raw: buf.length, br: br.length };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- main
|
||||
/** Hash of everything the output depends on: the boundary files and this script. */
|
||||
function sourceHash() {
|
||||
const h = createHash('sha256');
|
||||
h.update(readFileSync(fileURLToPath(import.meta.url)));
|
||||
h.update(readFileSync(join(SRC, 'admin0.geojson.gz')));
|
||||
for (const name of readdirSync(join(SRC, 'admin1')).sort())
|
||||
h.update(name).update(readFileSync(join(SRC, 'admin1', name)));
|
||||
return h.digest('hex');
|
||||
}
|
||||
const SOURCE = sourceHash();
|
||||
const STAMP = join(OUT, '.source-hash');
|
||||
if (process.argv.includes('--if-stale')) {
|
||||
let have = '';
|
||||
try {
|
||||
have = readFileSync(STAMP, 'utf8').trim();
|
||||
} catch {
|
||||
have = '';
|
||||
}
|
||||
if (have === SOURCE) {
|
||||
console.log('[atlas-mesh] up to date');
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
rmSync(OUT, { recursive: true, force: true });
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const files = {};
|
||||
|
||||
const admin0 = readGz(join(SRC, 'admin0.geojson.gz')).features;
|
||||
const countries = admin0.map((f) => ({
|
||||
a2: f.properties.ISO_A2 ?? null,
|
||||
a3: f.properties.ADM0_A3,
|
||||
name: f.properties.NAME,
|
||||
anchor: anchorOf(f),
|
||||
bbox: bboxOf([f]).map(round2),
|
||||
area: Math.round(totalArea(f) * 10) / 10,
|
||||
}));
|
||||
|
||||
for (const lod of WORLD_LODS) {
|
||||
const r = write(`world-${lod.id}.json`, buildTopo(admin0, 'countries', lod), files);
|
||||
console.log(`world ${lod.id}: ${r.raw} B raw, ${r.br} B br`);
|
||||
}
|
||||
|
||||
const regions = {};
|
||||
let regionBytes = 0;
|
||||
for (const file of readdirSync(join(SRC, 'admin1')).filter((n) => n.endsWith('.geojson.gz'))) {
|
||||
const a2 = file.slice(0, 2);
|
||||
const feats = readGz(join(SRC, 'admin1', file)).features;
|
||||
if (!feats.length) continue;
|
||||
const exclude = new Set(COUNT_EXCLUDE[a2] ?? []);
|
||||
const entry = {
|
||||
bbox: bboxOf(feats).map(round2),
|
||||
counted: feats.filter((f) => !exclude.has(f.properties.iso_3166_2)).length,
|
||||
features: feats.map((f) => ({
|
||||
code: f.properties.iso_3166_2 ?? null,
|
||||
name: f.properties.name ?? null,
|
||||
nameEn: f.properties.name_en ?? null,
|
||||
anchor: anchorOf(f),
|
||||
counted: !exclude.has(f.properties.iso_3166_2),
|
||||
})),
|
||||
files: {},
|
||||
};
|
||||
for (const lod of REGION_LODS) {
|
||||
const r = write(`regions/${a2}-${lod.id}.json`, buildTopo(feats, 'regions', lod), files);
|
||||
entry.files[lod.id] = r.name;
|
||||
regionBytes += r.br;
|
||||
}
|
||||
regions[a2] = entry;
|
||||
}
|
||||
|
||||
// The world manifest stays small; each country's region index ships as its own file.
|
||||
const regionIndex = {};
|
||||
for (const [a2, entry] of Object.entries(regions)) {
|
||||
const r = write(`regions/${a2}-index.json`, Buffer.from(JSON.stringify(entry)), files);
|
||||
regionIndex[a2] = { bbox: entry.bbox, counted: entry.counted, total: entry.features.length, index: r.name };
|
||||
}
|
||||
|
||||
// One small file to search every region by name without loading 198 indexes.
|
||||
const searchRows = [];
|
||||
for (const [a2, entry] of Object.entries(regions)) {
|
||||
for (const f of entry.features) {
|
||||
if (!f.anchor) continue;
|
||||
searchRows.push([a2, f.code, f.name, f.nameEn && f.nameEn !== f.name ? f.nameEn : null, f.anchor[0], f.anchor[1]]);
|
||||
}
|
||||
}
|
||||
const search = write('regions/search.json', Buffer.from(JSON.stringify(searchRows)), files);
|
||||
console.log(`region search ${search.raw} B raw, ${search.br} B br`);
|
||||
|
||||
const manifest = {
|
||||
version: 1,
|
||||
lods: WORLD_LODS.map((l) => l.id),
|
||||
regionLods: REGION_LODS.map((l) => l.id),
|
||||
world: Object.fromEntries(WORLD_LODS.map((l) => [l.id, files[`world-${l.id}.json`]])),
|
||||
countries,
|
||||
regions: regionIndex,
|
||||
regionSearch: search.name,
|
||||
attribution: ['geoBoundaries (CC BY 4.0)', 'CGAZ / LSIB', 'Tailte Éireann (CC BY 4.0)'],
|
||||
};
|
||||
const mjson = Buffer.from(JSON.stringify(manifest));
|
||||
writeFileSync(join(OUT, 'manifest.json'), mjson);
|
||||
const mbr = brotliCompressSync(mjson).length;
|
||||
console.log(
|
||||
`manifest ${mjson.length} B raw, ${mbr} B br; regions ${regionBytes} B br over ${Object.keys(regions).length} countries`,
|
||||
);
|
||||
writeFileSync(STAMP, SOURCE);
|
||||
@@ -0,0 +1,72 @@
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { Controller, Get, Headers, NotFoundException, Param, Res, UseGuards } from '@nestjs/common';
|
||||
|
||||
import type { Response } from 'express';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pipeline } from 'node:stream';
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
// __dirname is server/dist/nest/atlas at runtime and server/src/nest/atlas under vitest;
|
||||
// both resolve ../../../assets to server/assets.
|
||||
const MESH_DIR = path.join(__dirname, '..', '..', '..', 'assets', 'atlas-mesh');
|
||||
|
||||
/** A hashed geometry file name as the build script writes it; nothing else names a file. */
|
||||
const FILE_NAME = /^[A-Za-z0-9-]{2,24}\.[0-9a-f]{12}\.json$/;
|
||||
|
||||
/**
|
||||
* /api/addons/atlas/mesh: the geometry of the globe Atlas, built by
|
||||
* scripts/build-atlas-mesh.mjs. The manifest is revalidated on every load; the
|
||||
* topology files carry their content hash in the name and are cached for a year.
|
||||
* Files are stored Brotli-compressed and sent as they are; a client that does not
|
||||
* accept br gets them decompressed as a stream. Nothing is held in memory. Same guard as the rest of the Atlas routes.
|
||||
*/
|
||||
@Controller('api/addons/atlas/mesh')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class AtlasMeshController {
|
||||
// response-contract-exempt: sends the built manifest file through @Res() as it is.
|
||||
@Get('manifest')
|
||||
manifest(@Res() res: Response): void {
|
||||
const file = path.join(MESH_DIR, 'manifest.json');
|
||||
if (!fs.existsSync(file)) throw new NotFoundException({ error: 'Atlas geometry not built' });
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.sendFile('manifest.json', { root: MESH_DIR, acceptRanges: false });
|
||||
}
|
||||
|
||||
// response-contract-exempt: sends a pre-compressed topology file through @Res() as it is.
|
||||
@Get('world/:file')
|
||||
world(@Param('file') file: string, @Headers('accept-encoding') enc: string | undefined, @Res() res: Response): void {
|
||||
this.send('', file, enc, res);
|
||||
}
|
||||
|
||||
// response-contract-exempt: sends a pre-compressed topology file through @Res() as it is.
|
||||
@Get('regions/:file')
|
||||
regions(
|
||||
@Param('file') file: string,
|
||||
@Headers('accept-encoding') enc: string | undefined,
|
||||
@Res() res: Response,
|
||||
): void {
|
||||
this.send('regions', file, enc, res);
|
||||
}
|
||||
|
||||
private send(dir: string, file: string, enc: string | undefined, res: Response): void {
|
||||
if (!FILE_NAME.test(file)) throw new NotFoundException({ error: 'Not found' });
|
||||
const full = path.join(MESH_DIR, dir, `${file}.br`);
|
||||
if (!fs.existsSync(full)) throw new NotFoundException({ error: 'Not found' });
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
res.setHeader('Vary', 'Accept-Encoding');
|
||||
if (/\bbr\b/.test(enc ?? '')) {
|
||||
res.setHeader('Content-Encoding', 'br');
|
||||
res.sendFile(`${file}.br`, { root: path.join(MESH_DIR, dir), acceptRanges: false, lastModified: false });
|
||||
return;
|
||||
}
|
||||
// No br (a plain-http install: browsers offer it over HTTPS only): decompress
|
||||
// as a stream, so neither the packed nor the unpacked file sits in memory and
|
||||
// the event loop never waits on a whole file.
|
||||
pipeline(fs.createReadStream(full), zlib.createBrotliDecompress(), res, (err) => {
|
||||
if (err && !res.headersSent) res.status(500).end();
|
||||
else if (err) res.destroy(err);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user