Files
Lucas RayanandClaude Opus 5.5 b7462c14fa
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.

Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.

Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.

Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:45:59 -03:00

409 lines
25 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
// Generates internal/server/web/admin1-<cc>.json: first-level subdivisions (states, provinces,
// regions) of each country, simplified for the Geography page. Source: Natural Earth
// "ne_10m_admin_1_states_provinces" (public domain), GeoJSON build from the
// natural-earth-vector repository. Only needed when the data should change.
//
// curl -LO https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_1_states_provinces.geojson
// node scripts/gen-admin1.mjs ne_10m_admin_1_states_provinces.geojson internal/server/web \
// [--dbip regions.json] # optional: report how well DB-IP region names match
//
// Output per country (coordinates are integers in a local equirectangular projection):
// { cc, bbox:[minLon,minLat,maxLon,maxLat], w, h, main:[x0,y0,x1,y1],
// proj:{ lon0, lat1, kx, ky }, // x=(lon-lon0)*kx, y=(lat1-lat)*ky
// regions:[{ name, names:[...], code, path, c:[lon,lat], b:[x0,y0,x1,y1] }] }
// Longitudes are unwrapped around the antimeridian (Russia, USA, Fiji, NZ), so lon may exceed 180
// or go below -180; clients map a point with the same rule used for "bbox".
// Shared borders are simplified once (topology aware), so neighbours never open gaps, and
// regions of countries whose DB-IP names are coarser than Natural Earth are dissolved.
import { readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
const args = process.argv.slice(2);
const flag = (n) => { const i = args.indexOf(n); if (i < 0) return null; const v = args[i + 1]; args.splice(i, 2); return v; };
const dbipFile = flag('--dbip');
const [srcFile, outDir] = args;
if (!srcFile || !outDir) { console.error('usage: gen-admin1.mjs <geojson> <outdir> [--dbip regions.json]'); process.exit(2); }
const SIZE = 3000; // longest side of a country's main land mass, in units
const MAXDIM = 24000; // cap on the whole extent (countries with far overseas territories)
const _unused = 0; // longest side of a country, in units
const TOL = 1.1; // Douglas-Peucker tolerance, in units
const MIN_AREA = 2; // drops specks smaller than this (units^2)
// Country-specific grouping of Natural Earth units into the level DB-IP reports.
// 'region' -> property "region" (French regions, Spanish communities, Italian regions...)
// 'geonunit' -> property "geonunit" (England/Scotland/Wales/Northern Ireland)
const GROUP = { FR: 'region', ES: 'region', IT: 'region', GB: 'geonunit', UG: 'region', BF: 'region',
PH: 'region', BE: 'region', BA: 'region', MW: 'region' };
// Regions left out of the country's "main" box (overseas or far from the rest), by NE name or group.
const FAR = { US: ['Alaska', 'Hawaii'], FR: ['Guyane française', 'Martinique', 'Guadeloupe', 'Réunion', 'Mayotte'], NL: ['Bonaire', 'St. Eustatius', 'Saba', 'Sint Eustatius'],
NO: ['Svalbard', 'Bouvet Island'], ES: ['Canary Is.'], PT: ['Azores', 'Madeira', 'Região Autónoma dos Açores', 'Região Autónoma da Madeira'] };
// Explicit merges (Natural Earth unit -> the unit DB-IP reports), applied before grouping.
const IRE = { Connacht: ['Galway', 'Leitrim', 'Mayo', 'Roscommon', 'Sligo'], Munster: ['Clare', 'Cork', 'Kerry', 'Limerick', 'Tipperary', 'Waterford'], Ulster: ['Cavan', 'Donegal', 'Monaghan'] };
const NOR = { Troms: 'Troms og Finnmark', Finnmark: 'Troms og Finnmark', Akershus: 'Viken', Buskerud: 'Viken', 'Østfold': 'Viken', Hordaland: 'Vestland',
'Sogn og Fjordane': 'Vestland', 'Nord-Trøndelag': 'Trøndelag', 'Sør-Trøndelag': 'Trøndelag', Oppland: 'Innlandet', Hedmark: 'Innlandet',
Vestfold: 'Vestfold og Telemark', Telemark: 'Vestfold og Telemark', 'Aust-Agder': 'Agder', 'Vest-Agder': 'Agder' };
const MERGE = {
NO: (p) => NOR[p.name] || p.name,
IE: (p) => { for (const k in IRE) if (IRE[k].includes(p.name)) return k; return 'Leinster'; },
TW: (p) => (/Taipei City|Kaohsiung City/.test(p.name) ? p.name : p.region === 'Fujian Province' ? 'Fukien' : 'Taiwan'),
};
// Countries whose Natural Earth units are too far from what DB-IP reports (match < 25%).
const SKIP = new Set(['MA', 'LK', 'AZ', 'MK', 'RS', 'CI', 'MR', 'TC', 'KI', 'MH', 'ST', 'LU']);
// Names DB-IP uses that no Natural Earth field carries. { cc: { 'NE name or group': [aliases] } }
const ALIASES = {
FR: { 'Bretagne': ['=Brittany'], 'Normandie': ['=Normandy'], 'Corse': ['=Corsica'], 'Nouvelle-Aquitaine': ['New Aquitaine'],
'Auvergne-Rhône-Alpes': ['Rhône-Alpes'], 'Bourgogne-Franche-Comté': ['Bourgogne'], "Provence-Alpes-Côte-d'Azur": ['Provence', "Provence-Alpes-Côte d'Azur"] },
IT: { Lombardia: ['=Lombardy'], Piemonte: ['=Piedmont'], Toscana: ['=Tuscany'], Sardegna: ['=Sardinia'], Marche: ['The Marches'], Basilicata: ['Basilicate'],
"Valle d'Aosta": ['Aosta Valley'], 'Trentino-Alto Adige': ['Trentino-South Tyrol'], 'Emilia-Romagna': ['Emilia-Romagna'] },
ES: { 'Cataluña': ['=Catalonia'], 'Andalucía': ['=Andalusia'], Valenciana: ['=Valencia', 'Valencian Community'], 'País Vasco': ['=Basque Country'],
'Castilla y León': ['=Castille and León'], 'Canary Is.': ['=Canary Islands'], 'Islas Baleares': ['=Balearic Islands'], 'Castilla-La Mancha': ['Castille-La Mancha'],
Madrid: ['Community of Madrid'], 'Foral de Navarra': ['Navarre'], Murcia: ['Region of Murcia'], Asturias: ['Principality of Asturias'] },
BR: { 'Distrito Federal': ['=Federal District'] },
GB: { England: ['England'], Scotland: ['Scotland'], Wales: ['Wales'], 'Northern Ireland': ['Northern Ireland'] },
BE: { Flemish: ['=Flanders', 'Flemish Region'], Walloon: ['=Wallonia', 'Walloon Region'], 'Capital Region': ['=Brussels', 'Brussels Capital', 'Brussels-Capital Region'] },
BA: { 'Federacija Bosna i Hercegovina': ['=Federation of B&H', 'Federation of Bosnia and Herzegovina'], 'Repuplika Srpska': ['=Republika Srpska','Srpska', 'Republika Srpska'] },
IE: { Connacht: ['Connaught'] },
DE: { Hamburg: ['Free and Hanseatic City of Hamburg'], Bremen: ['Free Hanseatic City of Bremen', 'City state Bremen'], Berlin: ['State of Berlin'] },
FI: { 'Northern Ostrobothnia': ['North Ostrobothnia'], 'Northern Savonia': ['North Savo'], 'Southern Savonia': ['South Savo'], 'Southern Ostrobothnia': ['South Ostrobothnia'],
'Finland Proper': ['Southwest Finland'], 'Tavastia Proper': ['Kanta-Häme'], 'Päijät-Häme': ['Päijänne Tavastia'] },
PL: { 'Lower Silesian': ['Lower Silesia'], Subcarpathian: ['Subcarpathia'], 'Warmian-Masurian': ['Warmia-Masuria'], 'West Pomeranian': ['West Pomerania'], Podlachian: ['Podlasie'], Silesian: ['Silesia'], Pomeranian: ['Pomerania'], Masovian: ['Masovia'] },
DK: { Syddanmark: ['South Denmark'], Midtjylland: ['Central Jutland'], Nordjylland: ['North Jutland'], Hovedstaden: ['Capital Region', 'Capital Region of Denmark'], 'Sjaælland': ['Zealand', 'Region Zealand'] },
NO: { 'Troms og Finnmark': ['Troms', 'Finnmark', 'Troms and Finnmark'], Viken: ['Akershus', 'Østfold', 'Buskerud'], 'Vestfold og Telemark': ['Telemark', 'Vestfold'],
Agder: ['Vest-Agder', 'Aust-Agder'], Vestland: ['Hordaland', 'Sogn og Fjordane'], 'Trøndelag': ['Nord-Trøndelag', 'Sør-Trøndelag'], Innlandet: ['Oppland', 'Hedmark'] },
CL: { 'Región Metropolitana de Santiago': ['=Santiago Metropolitan', 'Santiago Metropolitan Region'] },
VE: { 'Distrito Capital': ['Distrito Federal', 'Capital District'], Vargas: ['=La Guaira', 'Estado La Guaira'] },
MX: { 'Distrito Federal': ['=Mexico City', 'Ciudad de México'] },
CO: { Bogota: ['=Bogotá D.C.','Bogota D.C.', 'Bogotá D.C.'] },
BG: { 'Grad Sofiya': ['=Sofia City','Sofia-grad', 'Sofia City', 'Sofia-Capital'] },
AR: { 'Ciudad de Buenos Aires': ['=Buenos Aires City','Buenos Aires F.D.', 'Autonomous City of Buenos Aires', 'Ciudad Autónoma de Buenos Aires'] },
BY: { Grodno: ['Grodnenskaya'], Gomel: ['Homyel’ Voblasc’', 'Gomel Region'], 'City of Minsk': ['Minsk City'], Brest: ['Brestskaya'], Mogilev: ['Mogilevskaya', 'Mahilyowskaya'], Vitebsk: ['Vitebskaya'], Minsk: ['Minskaya'] },
PE: { Lima: ['=Lima Region','Lima region', 'Lima Region'] },
RU: { Moskva: ['=Moscow'], Moskovskaya: ['=Moscow Oblast'], 'City of St. Petersburg': ['Saint Petersburg'] },
BH: { 'Al Manāmah': ['Manama', 'Capital'] },
TW: { Taiwan: ['Taiwan'], Fukien: ['Fukien', 'Fujian'] },
};
// ---------------------------------------------------------------- names
const STOP = new Set(['province', 'provincia', 'department', 'departamento', 'region', 'regional', 'state', 'county', 'district',
'governorate', 'municipality', 'parish', 'prefecture', 'oblast', 'oblisi', 'kray', 'republic', 'city', 'of', 'the', 'de', 'del',
'la', 'el', 'and', 'autonomous', 'canton', 'division', 'zone', 'voivodeship', 'county', 'commune', 'raion', 'okrug', 'territory']);
// strict: accents, case, punctuation. loose: also drops generic words ("Pernambuco State" = "Pernambuco").
// The same two functions live in geo.js; keep them identical.
export function normStrict(s) {
return String(s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/&/g, ' and ')
.replace(/\([^)]*\)/g, ' ').replace(/['’`ʼ]/g, '').replace(/[^a-z0-9]+/g, ' ').trim();
}
export function normLoose(s) {
const t = normStrict(s).split(' ').filter((w) => w && !STOP.has(w));
return t.join(' ');
}
const NAME_FIELDS = ['name', 'name_en', 'name_local', 'woe_name', 'gn_name', 'name_alt', 'name_pt', 'name_es', 'name_fr', 'name_de',
'name_it', 'name_nl', 'name_id', 'name_tr', 'name_sv', 'name_pl', 'name_hu', 'abbrev'];
function namesOf(p) {
const out = [];
for (const k of NAME_FIELDS) {
const v = p[k];
if (!v || typeof v !== 'string') continue;
for (const x of v.split('|')) { const y = x.trim(); if (y) out.push(y); }
}
return out;
}
const uniq = (arr) => {
const seen = new Set(), out = [];
for (const x of arr) { const k = normStrict(x); if (!k || seen.has(k)) continue; seen.add(k); out.push(x); }
return out;
};
// ---------------------------------------------------------------- geometry
const sh = (n, k) => n + k * 360;
const ringArea = (r) => { let a = 0; for (let i = 0; i < r.length; i++) { const p = r[i], q = r[(i + 1) % r.length]; a += p[0] * q[1] - q[0] * p[1]; } return a / 2; };
const bboxPts = (pts) => { let a = 1e9, b = 1e9, c = -1e9, d = -1e9; for (const [x, y] of pts) { if (x < a) a = x; if (x > c) c = x; if (y < b) b = y; if (y > d) d = y; } return [a, b, c, d]; };
function dp(pts, tol) {
const n = pts.length;
if (n < 3) return pts.slice();
const keep = new Uint8Array(n); keep[0] = 1; keep[n - 1] = 1;
const st = [[0, n - 1]];
const t2 = tol * tol;
while (st.length) {
const [a, b] = st.pop();
if (b <= a + 1) continue;
const [ax, ay] = pts[a], [bx, by] = pts[b];
const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy;
let md = -1, mi = -1;
for (let i = a + 1; i < b; i++) {
const [px, py] = pts[i];
let d;
if (L === 0) d = (px - ax) ** 2 + (py - ay) ** 2;
else {
let u = ((px - ax) * dx + (py - ay) * dy) / L; u = u < 0 ? 0 : u > 1 ? 1 : u;
d = (px - ax - u * dx) ** 2 + (py - ay - u * dy) ** 2;
}
if (d > md) { md = d; mi = i; }
}
if (md > t2) { keep[mi] = 1; st.push([a, mi], [mi, b]); }
}
const out = [];
for (let i = 0; i < n; i++) if (keep[i]) out.push(pts[i]);
return out;
}
const keyOf = (p) => p[0] + ',' + p[1];
// Topology-aware simplification. rings: [{ id, grp, pts }]. Returns, per ring, the list of
// chains [{ pts, sig, internal }] already simplified (shared chains simplified once).
function simplifyRings(rings, grpOf) {
const at = new Map(); // point -> ring ids
for (const r of rings) for (const p of r.pts) { const k = keyOf(p); let s = at.get(k); if (!s) at.set(k, (s = [])); if (s[s.length - 1] !== r.id) s.push(r.id); }
const sigOf = (p) => { const s = at.get(keyOf(p)); return s.length === 1 ? String(s[0]) : s.slice().sort((a, b) => a - b).join('.'); };
const cache = new Map();
for (const r of rings) {
const n = r.pts.length;
const sig = r.pts.map(sigOf);
let start = -1;
for (let i = 0; i < n; i++) if (sig[i] !== sig[(i + n - 1) % n] || sig[i] !== sig[(i + 1) % n]) { start = i; break; }
let rot, rsig;
if (start < 0) {
// no junction: closed ring, start at the smallest point (same for both neighbours of an enclave)
let m = 0; for (let i = 1; i < n; i++) if (r.pts[i][0] < r.pts[m][0] || (r.pts[i][0] === r.pts[m][0] && r.pts[i][1] < r.pts[m][1])) m = i;
start = m;
}
rot = r.pts.slice(start).concat(r.pts.slice(0, start)); rsig = sig.slice(start).concat(sig.slice(0, start));
// split into chains at nodes
const isNode = rot.map((_, i) => rsig[i] !== rsig[(i + n - 1) % n] || rsig[i] !== rsig[(i + 1) % n] || i === 0);
const chains = [];
let cur = [rot[0]], csig = [rsig[0]];
for (let i = 1; i <= n; i++) {
const p = rot[i % n];
cur.push(p); csig.push(rsig[i % n]);
if (i === n || isNode[i]) { chains.push({ pts: cur, sigs: csig }); cur = [p]; csig = [rsig[i % n]]; }
}
r.chains = chains.map((c) => {
// sig of the chain's interior (or its end nodes when it has none)
const mid = c.sigs[Math.floor(c.sigs.length / 2)];
const ids = mid.split('.').map(Number);
const a = c.pts[0], b = c.pts[c.pts.length - 1];
const fwd = a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || (a[1] === b[1] && c.pts.length > 2 && (c.pts[1][0] < c.pts[c.pts.length - 2][0] || (c.pts[1][0] === c.pts[c.pts.length - 2][0] && c.pts[1][1] <= c.pts[c.pts.length - 2][1])))));
const canon = fwd ? c.pts : c.pts.slice().reverse();
const ck = keyOf(canon[0]) + ';' + keyOf(canon[canon.length - 1]) + ';' + canon.length + ';' + keyOf(canon[canon.length >> 1]) + ';' + mid;
let simp = cache.get(ck);
if (!simp) { simp = dp(canon, TOL); cache.set(ck, simp); }
const pts = fwd ? simp : simp.slice().reverse();
const internal = ids.length === 2 && ids.every((i) => grpOf(i) === grpOf(r.id)) && ids.includes(r.id);
return { pts, internal };
});
}
}
function stitch(chains) {
// chains: arrays of points oriented along their ring; returns rings of points
const byStart = new Map();
for (const c of chains) { const k = keyOf(c[0]); let l = byStart.get(k); if (!l) byStart.set(k, (l = [])); l.push(c); }
const used = new Set(), out = [];
for (const c0 of chains) {
if (used.has(c0)) continue;
used.add(c0);
let ring = c0.slice(), guard = 0;
while (keyOf(ring[ring.length - 1]) !== keyOf(ring[0]) && guard++ < 100000) {
const l = byStart.get(keyOf(ring[ring.length - 1])) || [];
const nx = l.find((c) => !used.has(c));
if (!nx) break;
used.add(nx); ring = ring.concat(nx.slice(1));
}
if (keyOf(ring[ring.length - 1]) === keyOf(ring[0])) ring.pop();
out.push(ring);
}
return out;
}
const pathOf = (rings) => {
let d = '';
for (const r of rings) {
if (r.length < 3) continue;
d += `M${r[0][0]} ${r[0][1]}`;
let px = r[0][0], py = r[0][1];
for (let i = 1; i < r.length; i++) { d += `l${r[i][0] - px} ${r[i][1] - py}`; px = r[i][0]; py = r[i][1]; }
d += 'z';
}
return d;
};
// ---------------------------------------------------------------- build
const geo = JSON.parse(readFileSync(srcFile, 'utf8'));
const byCC = new Map();
for (const f of geo.features) {
let cc = f.properties.iso_a2;
if (!cc || !/^[A-Z]{2}$/.test(cc)) continue;
if (!byCC.has(cc)) byCC.set(cc, []);
byCC.get(cc).push(f);
}
mkdirSync(outDir, { recursive: true });
for (const f of readdirSync(outDir)) if (/^admin1-[a-z0-9-]+\.json$/.test(f)) unlinkSync(join(outDir, f));
let totalBytes = 0, files = 0;
const report = {};
for (const [cc, feats] of byCC) {
if (cc === 'AQ') continue;
if (SKIP.has(cc)) continue;
const mode = MERGE[cc] ? 'merge' : GROUP[cc] || 'unit';
// polygons (array of rings) per feature, longitudes unwrapped around the largest polygon
const polys = [];
feats.forEach((f, fi) => {
const g = f.geometry; if (!g) return;
const list = g.type === 'Polygon' ? [g.coordinates] : g.type === 'MultiPolygon' ? g.coordinates : [];
for (const poly of list) polys.push({ fi, rings: poly.map((r) => r.slice(0, -1)) });
});
if (!polys.length) continue;
let big = polys[0], ba = -1;
for (const p of polys) { const a = Math.abs(ringArea(p.rings[0])); p.area = a; if (a > ba) { ba = a; big = p; } }
const refLon = bboxPts(big.rings[0]).filter((_, i) => i % 2 === 0).reduce((a, b) => a + b, 0) / 2;
for (const p of polys) {
const b = bboxPts(p.rings[0]); const mid = (b[0] + b[2]) / 2;
let k = 0; while (mid + k * 360 - refLon > 180) k--; while (mid + k * 360 - refLon < -180) k++;
p.k = k;
if (k) p.rings = p.rings.map((r) => r.map(([x, y]) => [sh(x, k), y]));
}
// group id per feature
const gkey = (f) => {
const p = f.properties;
if (mode === 'region') return p.region || p.name;
if (mode === 'geonunit') return p.geonunit || p.name;
if (mode === 'merge') return MERGE[cc](p);
return String(f.properties.adm1_code || f.properties.name);
};
const grpIds = new Map(); const grpFeats = [];
feats.forEach((f) => { const k = gkey(f); if (!grpIds.has(k)) { grpIds.set(k, grpIds.size); grpFeats.push({ key: k, feats: [] }); } grpFeats[grpIds.get(k)].feats.push(f); });
if (grpFeats.length < 2) continue;
const fgrp = feats.map((f) => grpIds.get(gkey(f)));
const all = polys.flatMap((p) => p.rings[0]);
const bb = bboxPts(all);
// "main" box (degrees): the large land masses and what touches them, without far overseas pieces
// (Fernando de Noronha, French Guiana, Svalbard...). Regions listed in FAR stay out of it as a
// whole (Alaska and Hawaii remain reachable from the list). The scale is set on this box.
const farSet = new Set(FAR[cc] || []);
const cand = polys.filter((p) => !farSet.has(feats[p.fi].properties.name) && !farSet.has(gkey(feats[p.fi])))
.map((p) => ({ b: bboxPts(p.rings[0]), a: Math.abs(ringArea(p.rings[0])) }));
const pool = cand.length ? cand : polys.map((p) => ({ b: bboxPts(p.rings[0]), a: Math.abs(ringArea(p.rings[0])) }));
const top = Math.max(...pool.map((x) => x.a));
const inMain = new Set();
let mbox = null;
const addM = (x) => { inMain.add(x); mbox = mbox ? [Math.min(mbox[0], x.b[0]), Math.min(mbox[1], x.b[1]), Math.max(mbox[2], x.b[2]), Math.max(mbox[3], x.b[3])] : x.b.slice(); };
for (const x of pool) if (x.a >= top * 0.25) addM(x);
const eM = 0.03 * Math.max(mbox[2] - mbox[0], mbox[3] - mbox[1]);
for (let grew = true; grew;) {
grew = false;
for (const x of pool) {
if (inMain.has(x)) continue;
if (x.b[0] <= mbox[2] + eM && x.b[2] >= mbox[0] - eM && x.b[1] <= mbox[3] + eM && x.b[3] >= mbox[1] - eM) { addM(x); grew = true; }
}
}
const lat0 = (mbox[1] + mbox[3]) / 2, ckx = Math.max(0.05, Math.cos((lat0 * Math.PI) / 180));
let ky = SIZE / Math.max((mbox[2] - mbox[0]) * ckx, mbox[3] - mbox[1]);
ky = Math.min(ky, MAXDIM / Math.max((bb[2] - bb[0]) * ckx, bb[3] - bb[1])); // far territories must not blow the numbers up
const kx = ky * ckx;
const W = Math.round((bb[2] - bb[0]) * kx), H = Math.round((bb[3] - bb[1]) * ky);
const prj = ([lo, la]) => [Math.round((lo - bb[0]) * kx), Math.round((bb[3] - la) * ky)];
const main = [Math.round((mbox[0] - bb[0]) * kx), Math.round((bb[3] - mbox[3]) * ky), Math.round((mbox[2] - bb[0]) * kx), Math.round((bb[3] - mbox[1]) * ky)];
const rings = []; const ringGrp = [];
for (const p of polys) {
for (const r of p.rings) {
let pts = r.map(prj), q = [];
for (const pt of pts) { const l = q[q.length - 1]; if (!l || l[0] !== pt[0] || l[1] !== pt[1]) q.push(pt); }
while (q.length > 1 && q[0][0] === q[q.length - 1][0] && q[0][1] === q[q.length - 1][1]) q.pop();
if (q.length < 3 || Math.abs(ringArea(q)) < MIN_AREA) continue;
rings.push({ id: rings.length, grp: fgrp[p.fi], poly: p, pts: q });
ringGrp.push(fgrp[p.fi]);
}
}
simplifyRings(rings, (id) => ringGrp[id]);
const regions = grpFeats.map((g, gi) => {
const mine = rings.filter((r) => r.grp === gi);
const chains = [];
const loops = [];
for (const r of mine) {
const keep = r.chains.filter((c) => !c.internal);
if (keep.length === r.chains.length) { // untouched ring: keep as it is
let pts = []; r.chains.forEach((c, i) => { pts = pts.concat(i ? c.pts.slice(1) : c.pts); });
pts.pop(); if (pts.length >= 3) loops.push(pts);
} else for (const c of keep) chains.push(c.pts);
}
let rs = loops.concat(chains.length ? stitch(chains) : []);
rs = rs.filter((r) => r.length >= 3 && Math.abs(ringArea(r)) >= MIN_AREA);
const f0 = g.feats[0].properties;
let names = [], codes = [];
if (mode === 'unit') names = namesOf(f0);
else names = [g.key];
const A = ALIASES[cc] || {};
const alRaw = A[g.key] || A[f0.name] || A[f0.iso_3166_2] || A[f0.name_en] || [];
const eq = alRaw.find((x) => x.startsWith('='));
const al = alRaw.map((x) => x.replace(/^=/, ''));
names = uniq(names.concat(al));
const display = eq ? eq.slice(1) : mode === 'unit' ? (f0.name_en || f0.name || al[0] || f0.iso_3166_2) : g.key;
const code = mode === 'unit' ? (f0.iso_3166_2 || '') : '';
// label point: mean of members' NE label points, unwrapped like the polygons
let sx = 0, sy = 0, sn = 0;
for (const f of g.feats) { const p = f.properties; if (typeof p.longitude === 'number' && typeof p.latitude === 'number') { let lo = p.longitude; while (lo - refLon > 180 + 30) lo -= 360; while (lo - refLon < -180 - 30) lo += 360; sx += lo; sy += p.latitude; sn++; } }
const big2 = rs.slice().sort((a, b) => Math.abs(ringArea(b)) - Math.abs(ringArea(a)))[0];
// "main" box: drops far islands that dwarf the layout
const boxes = rs.map((r) => ({ b: bboxPts(r), a: Math.abs(ringArea(r)) }));
const maxA = Math.max(...boxes.map((x) => x.a), 1);
let mb = null;
for (const x of boxes) { if (x.a < maxA * 0.08 && boxes.length > 1) continue; mb = mb ? [Math.min(mb[0], x.b[0]), Math.min(mb[1], x.b[1]), Math.max(mb[2], x.b[2]), Math.max(mb[3], x.b[3])] : x.b.slice(); }
const lab = {};
if (mode === 'unit') { const en = display, pt = (cc === 'BR' || cc === 'PT') ? f0.name : f0.name_pt || f0.name; if (pt && en && pt !== en) { lab.pt = pt; lab.en = en; } }
return { name: display, ...(lab.pt ? { label: lab } : {}), names, code, path: pathOf(rs), c: sn ? [+(sx / sn).toFixed(3), +(sy / sn).toFixed(3)] : null, b: mb, _a: maxA };
}).filter((r) => r.path);
// a normalized name belongs to one region only: primary names win over variants (e.g. "Buenos Aires")
const owner = new Map();
for (const r of regions) { const q = normStrict(r.names[0]); if (!owner.has(q)) owner.set(q, r); }
for (const r of regions) r.names = r.names.filter((n, i) => { const q = normStrict(n); const o = owner.get(q); if (!o) { owner.set(q, r); return true; } return o === r; });
if (regions.length < 2) continue;
for (const r of regions) { delete r._a; }
const out = { cc, bbox: bb.map((n) => +n.toFixed(4)), w: W, h: H, main, proj: { lon0: +bb[0].toFixed(5), lat1: +bb[3].toFixed(5), kx: +kx.toFixed(5), ky: +ky.toFixed(5) }, regions };
const text = JSON.stringify(out);
writeFileSync(join(outDir, `admin1-${cc.toLowerCase()}.json`), text);
totalBytes += text.length; files++;
report[cc] = { regions: regions.map((r) => ({ name: r.name, names: r.names })), bytes: text.length };
}
// index so the page only asks for files that exist (no 404 noise in the console)
writeFileSync(join(outDir, 'admin1-index.json'), JSON.stringify({ cc: Object.keys(report).sort() }));
console.error(`${files} files, ${(totalBytes / 1048576).toFixed(2)} MB`);
// ---------------------------------------------------------------- DB-IP match report
if (dbipFile) {
const d = JSON.parse(readFileSync(dbipFile, 'utf8'));
const rows = [];
for (const cc of Object.keys(d)) {
const rep = report[cc];
if (!rep) { rows.push({ cc, status: 'no-file' }); continue; }
const strict = new Set(), loose = new Set();
for (const r of rep.regions) for (const n of r.names) { strict.add(normStrict(n)); loose.add(normLoose(n)); }
let tot = 0, ok = 0, nreg = 0, nok = 0; const miss = [];
for (const [n, v] of Object.entries(d[cc])) {
tot += v.N; if (!n) continue; nreg++;
if (strict.has(normStrict(n)) || loose.has(normLoose(n))) { ok += v.N; nok++; } else miss.push([n, v.N]);
}
miss.sort((a, b) => b[1] - a[1]);
rows.push({ cc, status: 'ok', rate: tot ? ok / tot : 0, nreg, nok, miss: miss.slice(0, 8) });
}
const want = (process.env.WANT || 'BR,US,NL,DE,CN,IN,GB,FR').split(',');
console.error('--- match rate by sampled IP space (named regions) ---');
for (const cc of want) { const r = rows.find((x) => x.cc === cc); if (r) console.error(cc, r.status === 'ok' ? `${(r.rate * 100).toFixed(1)}% by IPs, ${r.nok}/${r.nreg} names` : r.status, r.miss ? r.miss.map((m) => m.join(':')).join(', ') : ''); }
const worst = rows.filter((r) => r.status === 'ok' && r.rate < 0.9).sort((a, b) => b.nreg - a.nreg);
console.error('--- below 90% ---');
for (const r of worst) console.error(r.cc, (r.rate * 100).toFixed(0) + '%', `${r.nok}/${r.nreg}`, r.miss.map((m) => m.join(':')).join(', '));
const all = rows.filter((r) => r.status === 'ok');
console.error('countries with file:', all.length, 'of', rows.length, 'DB-IP countries; >=90%:', all.filter((r) => r.rate >= 0.9).length);
}