In this section
- Data GridAtlas Client storage · gridatlas / atlas/releases/202608291430-atlas-v9/assets/data-gridatlas-client.mjs lines 1–300
- Renewable Energy Planning Database (REPD) Routing Client energy-data · gridatlas / atlas/releases/202608291430-atlas-v9/assets/repd-routing-client.mjs lines 1–152
Data GridAtlas Client
A JavaScript module in the assets folder that fetches membership and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagegridatlas / atlas/releases/202608291430-atlas-v9/assets/data-gridatlas-client.mjs · lines 1–300 of 300 · version 2026-08-29 14:30 · Not reached from any entry point (candidate for review) · pattern runtime (shared by 10 files)
- What it does
- It fetches membership and the REPD register. Defines 24 functions or classes, including invariant, hasPlaceholder, normaliseBaseUrl, validateReleaseManifest, sha256Hex. Side effects: makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file release.json; JSON file browser-layer-registry.json; Parquet file layer_membership.parquet; JSON file release-manifest.json; DuckDB queries. Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 2 files: Atlas V9 (gridatlas); Renewable Energy Planning Database (REPD) Routing Client (gridatlas).
- What it achieves
- It normalises base URL (`normaliseBaseUrl`), validates release manifest (`validateReleaseManifest`) and fetches verified JSON (`fetchVerifiedJson`). Defines `invariant`, `hasPlaceholder`, `normaliseBaseUrl` and 21 more.
- Why it matters
- Imported by Atlas V9 and Renewable Energy Planning Database (REPD) Routing Client.
- Application
- gridatlas · atlas/releases/202608291430-atlas-v9/assets · JavaScript module
- Uses
- none found
- Used by
- imported by Atlas V9 (import), imported by Renewable Energy Planning Database (REPD) Routing Client (import)
- Produces
- validateReleaseManifest, fetchVerifiedJson, validateDataClosure, normaliseBounds, buildLayerQuery, rowsToGeoJSON, loadReleaseContract, loadDataCatalog, createGridAtlasDataClient
- Defines here
- invariant, hasPlaceholder, normaliseBaseUrl, validateReleaseManifest, sha256Hex, fetchVerifiedJson, dataUrl, payloadUrl, flattenLayers, validateDataClosure, sqlLiteral, finiteBound, normaliseBounds, buildLayerQuery, plainArrowRow, rowsToGeoJSON, instantiateDuckDb, loadReleaseContract, loadDataCatalog, createGridAtlasDataClient, runtime, queryLayer, task, close
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/releases/202608291430-atlas-v9/assets/data-gridatlas-client.mjs:1-300 · blob 9115e1e974f9f20afcd1a979f3e741d332aac76a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const RELEASE_SCHEMA = "gridatlas.timestamped-live-release.v1";
const REGISTRY_SCHEMA = "data-gridatlas.live-browser-layer-registry.v1";
const DATA_RELEASE_SCHEMA = "data-gridatlas.immutable-live-data-release.v1";
const SAFE_LAYER_ID = /^[a-z0-9_]+$/;
const SAFE_PARQUET_PATH = /^(?:partitions|derived)\/[a-z0-9_]+\.parquet$/;
const SAFE_LIVE_PARQUET_PATH = /^data\/(?:partitions|derived)\/[a-z0-9_]+\.parquet$/;
const SHA256 = /^[a-f0-9]{64}$/;
function invariant(condition, message) {
if (!condition) throw new Error(message);
}
function hasPlaceholder(value) {
return typeof value === "string" && value.includes("__");
}
function normaliseBaseUrl(value) {
const url = new URL(value);
invariant(url.protocol === "https:", "data release must use HTTPS");
invariant(url.hostname === "ventusltd.github.io", "unexpected data release host");
invariant(url.pathname.endsWith("/202608291237-data-gridatlas/"), "unexpected immutable data release path");
url.search = "";
url.hash = "";
return url.href;
}
export function validateReleaseManifest(manifest, { sealed = true } = {}) {
invariant(manifest?.schema === RELEASE_SCHEMA, "application release schema mismatch");
invariant(manifest.release_id === "202608291430-atlas-v9", "application release identity mismatch");
invariant(manifest.generation === "202608291430", "application generation mismatch");
invariant(manifest.classification === "LIVE_RELEASE", "application is not classified live");
invariant(manifest.immutable === true && manifest.current === true, "application release flags are not live and immutable");
invariant(manifest.parent_release?.publication_commit === "1898184ccbf52ca836cf1482362fc5933baf3e8d", "last-green parent drift");
invariant(manifest.repd?.generation === "202608290716" && manifest.repd.rows === 11069, "REPD preservation contract mismatch");
invariant(manifest.repd?.selectable_rows === 11033 && manifest.repd.excluded_false_origin_rows === 36, "safe REPD closure mismatch");
invariant(manifest.repd?.role === "NORMAL_SEARCH_AND_BASE_MAP", "normal REPD registry role mismatch");
invariant(manifest.repd_routing?.release_id === "202608291410-repd-routing", "routing release identity mismatch");
invariant(manifest.repd_routing?.projects === 7680, "routing project closure mismatch");
invariant(manifest.repd_routing?.map_identities === 7652 && manifest.repd_routing?.no_map_identities === 28, "routing MAP/NO MAP closure mismatch");
invariant(manifest.repd_routing?.routing_only_map_fallbacks === 2419 && manifest.repd_routing?.normal_plus_fallback_union === 13452, "safe union closure mismatch");
invariant(manifest.repd_routing?.missing_map_identities === 0 && manifest.repd_routing?.no_map_selectable_intersection === 0, "routing completeness mismatch");
invariant(manifest.repd_routing?.role === "LAZY_EXACT_DEEP_LINK_FALLBACK_ONLY", "routing role mismatch");
invariant(manifest.route_contract?.identity_rule === "EXACT_REPD_REF_ONLY", "routing identity rule mismatch");
invariant(manifest.route_contract?.normal_registry_precedence === true, "normal registry precedence missing");
invariant(manifest.route_contract?.query_coordinates_ignored === true, "query coordinates must be ignored");
invariant(manifest.data_release?.source_generation === "202608291015", "data generation mismatch");
invariant(manifest.data_release?.release_id === "202608291237-data-gridatlas", "data release identity mismatch");
invariant(manifest.data_release?.layers === 60 && manifest.data_release?.sources === 56, "data closure mismatch");
invariant(manifest.data_release?.release_path === "release.json", "data release path mismatch");
invariant(manifest.data_release?.browser_registry_path === "browser-layer-registry.json", "browser registry path mismatch");
invariant(manifest.data_release?.data_root === "data/", "data root mismatch");
invariant(manifest.loading_contract?.parquet_on_boot === 0, "Parquet boot budget must be zero");
invariant(manifest.loading_contract?.activation === "EXPLICIT_USER_LAYER_TOGGLE", "layer activation is not lazy");
normaliseBaseUrl(manifest.data_release.base_url);
if (sealed) {
for (const [name, value] of Object.entries({
source_commit: manifest.source_commit,
data_source_commit: manifest.data_release.source_commit,
data_release_sha256: manifest.data_release.release_sha256,
data_registry_sha256: manifest.data_release.browser_registry_sha256,
routing_publication_commit: manifest.repd_routing.publication_commit,
routing_source_commit: manifest.repd_routing.source_commit,
routing_release_sha256: manifest.repd_routing.release_sha256,
routing_projects_sha256: manifest.repd_routing.projects_sha256,
created_at: manifest.created_at,
committed_at: manifest.committed_at
})) invariant(!hasPlaceholder(value), `${name} is not sealed`);
invariant(SHA256.test(manifest.data_release.release_sha256), "data release digest is invalid");
invariant(SHA256.test(manifest.data_release.browser_registry_sha256), "browser registry digest is invalid");
invariant(SHA256.test(manifest.repd_routing.release_sha256), "routing release digest is invalid");
invariant(SHA256.test(manifest.repd_routing.projects_sha256), "routing projects digest is invalid");
invariant(/^[a-f0-9]{40}$/.test(manifest.repd_routing.publication_commit), "routing publication commit is invalid");
invariant(/^[a-f0-9]{40}$/.test(manifest.repd_routing.source_commit), "routing source commit is invalid");
invariant(/^[a-f0-9]{40}$/.test(manifest.source_commit), "application source commit is invalid");
invariant(/^[a-f0-9]{40}$/.test(manifest.data_release.source_commit), "data source commit is invalid");
invariant(/^\d{4}-\d{2}-\d{2}T/.test(manifest.committed_at), "application commit timestamp is invalid");
}
return manifest;
}
async function sha256Hex(bytes) {
const digest = await crypto.subtle.digest("SHA-256", bytes);
return [...new Uint8Array(digest)].map(value => value.toString(16).padStart(2, "0")).join("");
}
export async function fetchVerifiedJson(url, expectedSha256, expectedBytes = null) {
invariant(SHA256.test(expectedSha256), `invalid expected digest for ${url}`);
const response = await fetch(url, { cache: "no-store" });
invariant(response.ok, `${url} returned HTTP ${response.status}`);
const bytes = await response.arrayBuffer();
if (Number.isInteger(expectedBytes)) invariant(bytes.byteLength === expectedBytes, `${url} byte count mismatch`);
invariant(await sha256Hex(bytes) === expectedSha256, `${url} SHA-256 mismatch`);
return JSON.parse(new TextDecoder().decode(bytes));
}
function dataUrl(release, path) {
invariant(typeof path === "string" && !path.startsWith("/") && !path.includes(".."), `unsafe data path: ${path}`);
const base = normaliseBaseUrl(release.data_release.base_url);
const resolved = new URL(path, base);
invariant(resolved.href.startsWith(base), `data path escaped immutable release: ${path}`);
return resolved.href;
}
function payloadUrl(release, path) {
invariant(release.data_release.data_root === "data/", "data root mismatch");
const livePath = path.startsWith("data/") ? path : `${release.data_release.data_root}${path}`;
invariant(SAFE_LIVE_PARQUET_PATH.test(livePath) || livePath === "data/layer_membership.parquet", `unsafe payload path: ${livePath}`);
return dataUrl(release, livePath);
}
function flattenLayers(registry) {
invariant(Array.isArray(registry.groups), "browser layer groups missing");
const layers = [];
registry.groups.forEach((group, groupIndex) => {
invariant(typeof group.group === "string" && Array.isArray(group.layers), `invalid group ${groupIndex}`);
group.layers.forEach((layer, layerIndex) => {
invariant(SAFE_LAYER_ID.test(layer.id), `unsafe layer id: ${layer.id}`);
invariant(SAFE_PARQUET_PATH.test(layer.v9_data?.parquet_path || ""), `unsafe Parquet path for ${layer.id}`);
invariant(layer.v9_data?.parquet_url === `data/${layer.v9_data.parquet_path}`, `live Parquet alias mismatch for ${layer.id}`);
invariant(layer.v9_data?.membership_url === "data/layer_membership.parquet", `membership alias mismatch for ${layer.id}`);
invariant(layer.v9_data?.data_live === true, `layer is not live: ${layer.id}`);
invariant(layer.available === true && layer.publishable === true && layer.enabled === true, `layer is not selectable: ${layer.id}`);
invariant(layer.default_visible === false && layer.preload === false, `layer violates lazy startup: ${layer.id}`);
invariant(typeof layer.v9_data?.source_id === "string", `source id missing for ${layer.id}`);
layers.push(Object.freeze({ ...layer, group: group.group, groupIndex, layerIndex }));
});
});
invariant(layers.length === 60, `expected 60 layers, received ${layers.length}`);
invariant(new Set(layers.map(layer => layer.id)).size === 60, "duplicate layer ids");
return layers;
}
export function validateDataClosure(release, dataRelease, registry) {
invariant(dataRelease?.schema === DATA_RELEASE_SCHEMA, "data release schema mismatch");
invariant(dataRelease.release_id === release.data_release.release_id, "data release identity mismatch");
invariant(dataRelease.classification === "LIVE_IMMUTABLE_DATA_RELEASE", "data release classification mismatch");
invariant(dataRelease.release === true && dataRelease.immutable === true && dataRelease.current_pointer === false, "data release flags mismatch");
invariant(dataRelease.v8_untouched === true, "data release changed V8");
invariant(dataRelease.authority_licence_and_quarantine_labels_preserved === true, "data evidence labels were not preserved");
invariant(dataRelease.candidate_closure?.features === 541282 && dataRelease.candidate_closure?.layers === 60 && dataRelease.candidate_closure?.sources === 56, "data release closure mismatch");
invariant(dataRelease.candidate_closure?.layer_membership_rows === 526388, "data membership closure mismatch");
invariant(Array.isArray(dataRelease.files) && dataRelease.files.some(item => item.path === "data/layer_membership.parquet"), "data release membership file missing");
invariant(registry?.schema === REGISTRY_SCHEMA, "browser registry schema mismatch");
invariant(registry.generation === release.data_release.release_id, "browser registry generation mismatch");
invariant(registry.candidate_generation === release.data_release.source_generation, "browser registry candidate generation mismatch");
invariant(registry.classification === "LIVE_IMMUTABLE_DATA_RELEASE", "browser registry classification mismatch");
invariant(registry.release === true && registry.current_pointer === false && registry.pages_publication === true, "browser registry flags mismatch");
invariant(registry.data_base_path === "data/", "browser registry data root mismatch");
invariant(registry.base_url === release.data_release.base_url, "browser registry base URL mismatch");
invariant(registry.load_policy?.initial_fetches === 0, "browser registry startup fetch budget mismatch");
invariant(registry.load_policy?.fetch_on_user_enable_only === true, "browser registry is not user-lazy");
invariant(Array.isArray(registry.load_policy?.default_visible_layers) && registry.load_policy.default_visible_layers.length === 0, "browser registry has startup-visible layers");
return flattenLayers(registry);
}
function sqlLiteral(value) {
return `'${String(value).replaceAll("'", "''")}'`;
}
function finiteBound(value, name) {
const number = Number(value);
invariant(Number.isFinite(number), `invalid map bound ${name}`);
return number;
}
export function normaliseBounds(bounds) {
const west = finiteBound(bounds.west, "west");
const south = finiteBound(bounds.south, "south");
const east = finiteBound(bounds.east, "east");
const north = finiteBound(bounds.north, "north");
invariant(west >= -180 && west <= 180 && east >= -180 && east <= 180, "longitude bound outside WGS84");
invariant(south >= -90 && south <= 90 && north >= -90 && north <= 90 && south <= north, "latitude bound outside WGS84");
return { west, south, east, north };
}
export function buildLayerQuery(release, layer, bounds) {
invariant(SAFE_LAYER_ID.test(layer.id), "unsafe layer id");
invariant(SAFE_PARQUET_PATH.test(layer.v9_data?.parquet_path || ""), "unsafe layer Parquet path");
const box = normaliseBounds(bounds);
const partitionUrl = payloadUrl(release, layer.v9_data.parquet_url || layer.v9_data.parquet_path);
const membershipUrl = payloadUrl(release, `${release.data_release.data_root}${release.data_release.membership_path}`);
const longitudeClause = box.west <= box.east
? `p.max_x >= ${box.west} AND p.min_x <= ${box.east}`
: `(p.max_x >= ${box.west} OR p.min_x <= ${box.east})`;
return `
SELECT p.source_id, p.feature_index, p.feature_id,
p.geometry_type, p.geometry_json, p.properties_json,
p.original_feature_sha256, p.projected_feature_sha256
FROM read_parquet(${sqlLiteral(partitionUrl)}) AS p
SEMI JOIN read_parquet(${sqlLiteral(membershipUrl)}) AS m
ON m.source_id = p.source_id
AND m.feature_index = p.feature_index
AND m.layer_id = ${sqlLiteral(layer.id)}
WHERE ${longitudeClause}
AND p.max_y >= ${box.south} AND p.min_y <= ${box.north}
ORDER BY p.feature_index
`.trim();
}
function plainArrowRow(row) {
return row && typeof row.toJSON === "function" ? row.toJSON() : row;
}
export function rowsToGeoJSON(rows, layer) {
const features = [];
for (const arrowRow of rows) {
const row = plainArrowRow(arrowRow);
const geometry = JSON.parse(String(row.geometry_json));
const properties = JSON.parse(String(row.properties_json || "{}"));
features.push({
type: "Feature",
id: `${row.source_id}:${row.feature_index}`,
geometry,
properties: {
...properties,
_atlas_layer_id: layer.id,
_atlas_source_id: String(row.source_id),
_atlas_feature_index: Number(row.feature_index),
_atlas_original_sha256: String(row.original_feature_sha256),
_atlas_projected_sha256: String(row.projected_feature_sha256)
}
});
}
return { type: "FeatureCollection", features };
}
async function instantiateDuckDb(release, onStatus) {
const dependency = release.runtime_dependencies.find(item => item.id === "duckdb-wasm");
invariant(dependency?.version === "1.29.0", "DuckDB-WASM pin mismatch");
onStatus("Starting browser DuckDB…");
const testModule = globalThis.__GRIDATLAS_DUCKDB_TEST_MODULE__;
const duckdb = testModule || await import(dependency.module);
globalThis.__GRIDATLAS_DUCKDB_MODE__ = testModule ? "test" : "real";
const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
invariant(bundle?.mainModule && bundle?.mainWorker, "no compatible DuckDB-WASM bundle");
const workerUrl = URL.createObjectURL(new Blob([`importScripts(${JSON.stringify(bundle.mainWorker)});`], { type: "text/javascript" }));
const worker = new Worker(workerUrl);
const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
const database = new duckdb.AsyncDuckDB(logger, worker);
try {
await database.instantiate(bundle.mainModule, bundle.pthreadWorker);
} finally {
URL.revokeObjectURL(workerUrl);
}
const connection = await database.connect();
return { database, connection, worker };
}
export async function loadReleaseContract(manifestUrl = "./release-manifest.json") {
const response = await fetch(manifestUrl, { cache: "no-store" });
invariant(response.ok, `application manifest HTTP ${response.status}`);
return validateReleaseManifest(await response.json());
}
export async function loadDataCatalog(release) {
const dataRelease = await fetchVerifiedJson(
dataUrl(release, release.data_release.release_path),
release.data_release.release_sha256
);
const registry = await fetchVerifiedJson(
dataUrl(release, release.data_release.browser_registry_path),
release.data_release.browser_registry_sha256
);
return { dataRelease, registry, layers: validateDataClosure(release, dataRelease, registry) };
}
export function createGridAtlasDataClient(release, { onStatus = () => {} } = {}) {
validateReleaseManifest(release);
let runtimePromise = null;
let queue = Promise.resolve();
async function runtime() {
runtimePromise ||= instantiateDuckDb(release, onStatus);
return runtimePromise;
}
function queryLayer(layer, bounds) {
const task = async () => {
const { connection } = await runtime();
onStatus(`Querying ${layer.label} in this map view…`);
const table = await connection.query(buildLayerQuery(release, layer, bounds));
const geojson = rowsToGeoJSON(table.toArray(), layer);
onStatus(`${layer.label}: ${geojson.features.length.toLocaleString()} visible features`);
return geojson;
};
const result = queue.then(task, task);
queue = result.catch(() => {});
return result;
}
async function close() {
if (!runtimePromise) return;
const { connection, database, worker } = await runtimePromise;
await connection.close();
await database.terminate();
worker.terminate();
}
return Object.freeze({ queryLayer, close });
}Renewable Energy Planning Database (REPD) Routing Client
A JavaScript module in the assets folder of GridAtlas that works with the REPD register, using SHA-256.
energy-datagridatlas / atlas/releases/202608291430-atlas-v9/assets/repd-routing-client.mjs · lines 1–152 of 152 · version 2026-08-29 14:30 · Not reached from any entry point (candidate for review) · pattern invariant (shared by 75 files)
- What it does
- It calculates the REPD register. Defines 7 functions or classes, including invariant, dictionaryValue, immutableRoutingUrl, decodeRoutingProjects, resolveRoutingRecord.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'routing'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: the REPD register.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 1 file: Atlas V9 (gridatlas).
- What it achieves
- It decodes routing projects (`decodeRoutingProjects`), resolves routing record (`resolveRoutingRecord`) and loads routing deep link fallback (`loadRoutingDeepLinkFallback`). Defines `invariant`, `dictionaryValue`, `immutableRoutingUrl` and 4 more.
- Why it matters
- Imported by Atlas V9.
- Application
- gridatlas · atlas/releases/202608291430-atlas-v9/assets · JavaScript module
- Uses
- Data GridAtlas Client (import)
- Used by
- imported by Atlas V9 (import)
- Produces
- REPD_ROUTING_CONTRACT, decodeRoutingProjects, resolveRoutingRecord, loadRoutingDeepLinkFallback, clearRoutingCacheForTests
- Defines here
- invariant, dictionaryValue, immutableRoutingUrl, decodeRoutingProjects, resolveRoutingRecord, loadRoutingDeepLinkFallback, clearRoutingCacheForTests
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/releases/202608291430-atlas-v9/assets/repd-routing-client.mjs:1-152 · blob 92426d58462f71ef87f292448c4509e2532a2e69 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: IPP_developer, EPC_contractor, landowner_planner · canonical: unreached_review
import { fetchVerifiedJson } from "./data-gridatlas-client.mjs";
export const REPD_ROUTING_CONTRACT = Object.freeze({
schema: "pipelinenews.v8.fast-project-index.v1",
generation: "202608270055",
releaseId: "202608291410-repd-routing",
projects: 7680,
mapIdentities: 7652,
noMapIdentities: 28,
identityKey: "repd_ref"
});
const EXACT_FIELDS = Object.freeze([
"repd_ref", "gg_project_id", "name", "technology", "status", "capacity_mw",
"county", "region", "operator", "repd_record_updated", "geometry_status",
"latitude", "longitude"
]);
function invariant(condition, message) {
if (!condition) throw new Error(message);
}
function dictionaryValue(dictionaries, name, index) {
const values = dictionaries[name];
invariant(Array.isArray(values), `routing dictionary missing: ${name}`);
invariant(Number.isInteger(index) && index >= 0 && index < values.length, `routing dictionary index invalid: ${name}`);
return values[index];
}
function immutableRoutingUrl(manifest, relative) {
const routing = manifest.repd_routing;
invariant(routing?.release_id === REPD_ROUTING_CONTRACT.releaseId, "routing release identity mismatch");
invariant(relative === routing.release_path || relative === routing.projects_path, "routing path is not allowlisted");
const base = new URL(routing.base_url);
invariant(base.protocol === "https:" && base.hostname === "ventusltd.github.io", "routing host mismatch");
invariant(base.pathname === "/data-gridatlas/202608291410-repd-routing/", "routing timestamp path mismatch");
const resolved = new URL(relative, base);
invariant(resolved.href.startsWith(base.href), "routing path escaped immutable folder");
return resolved.href;
}
export function decodeRoutingProjects(payload) {
invariant(payload?.schema === REPD_ROUTING_CONTRACT.schema, "routing projects schema mismatch");
invariant(payload.generation === REPD_ROUTING_CONTRACT.generation, "routing projects generation mismatch");
invariant(JSON.stringify(payload.fields) === JSON.stringify(EXACT_FIELDS), "routing projects fields mismatch");
invariant(payload.dictionaries && typeof payload.dictionaries === "object", "routing dictionaries missing");
invariant(Array.isArray(payload.rows) && payload.rows.length === REPD_ROUTING_CONTRACT.projects, "routing row closure mismatch");
const field = Object.fromEntries(payload.fields.map((name, index) => [name, index]));
const records = [];
const byRef = new Map();
let mapIdentities = 0;
let noMapIdentities = 0;
for (const row of payload.rows) {
invariant(Array.isArray(row) && row.length === EXACT_FIELDS.length, "routing row width mismatch");
const repdRef = row[field.repd_ref];
invariant(typeof repdRef === "string" && /^\d+$/.test(repdRef), "routing repd_ref is not an exact numeric string");
invariant(!byRef.has(repdRef), `duplicate routing repd_ref: ${repdRef}`);
const geometryStatus = dictionaryValue(payload.dictionaries, "geometry_status", row[field.geometry_status]);
invariant(["valid", "missing", "invalid"].includes(geometryStatus), `unknown geometry status: ${geometryStatus}`);
const rawLatitude = row[field.latitude];
const rawLongitude = row[field.longitude];
let latitude = null;
let longitude = null;
let selectable = false;
if (geometryStatus === "valid") {
invariant(rawLatitude !== null && rawLongitude !== null, `valid routing geometry is null: ${repdRef}`);
latitude = Number(rawLatitude);
longitude = Number(rawLongitude);
invariant(Number.isFinite(latitude) && Number.isFinite(longitude), `valid routing geometry is non-finite: ${repdRef}`);
invariant(latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180, `routing geometry outside WGS84: ${repdRef}`);
invariant(!(latitude === 0 && longitude === 0), `false zero-origin routing point: ${repdRef}`);
invariant(!(latitude === 49.766807 && longitude === -7.55716), `transformed false-origin routing point: ${repdRef}`);
selectable = true;
mapIdentities += 1;
} else {
invariant(rawLatitude === null && rawLongitude === null, `NO MAP routing geometry contains coordinates: ${repdRef}`);
noMapIdentities += 1;
}
const record = Object.freeze({
repd_ref: repdRef,
gg_project_id: String(row[field.gg_project_id]),
name: String(row[field.name]),
technology: dictionaryValue(payload.dictionaries, "technology", row[field.technology]),
repd_technology: dictionaryValue(payload.dictionaries, "technology", row[field.technology]),
status: dictionaryValue(payload.dictionaries, "status", row[field.status]).toLowerCase(),
capacity_mw: Number(row[field.capacity_mw]),
county: dictionaryValue(payload.dictionaries, "county", row[field.county]) || null,
region: dictionaryValue(payload.dictionaries, "region", row[field.region]) || null,
repd_operator_or_applicant: dictionaryValue(payload.dictionaries, "operator", row[field.operator]) || null,
source_record_updated: row[field.repd_record_updated] || null,
geometry_status: geometryStatus,
latitude,
longitude,
selectable,
routing_source: "EXACT_DATA_GRIDATLAS_PROJECTS_JSON"
});
records.push(record);
byRef.set(repdRef, record);
}
invariant(mapIdentities === REPD_ROUTING_CONTRACT.mapIdentities, `routing MAP closure mismatch: ${mapIdentities}`);
invariant(noMapIdentities === REPD_ROUTING_CONTRACT.noMapIdentities, `routing NO MAP closure mismatch: ${noMapIdentities}`);
return Object.freeze({ records: Object.freeze(records), byRef, mapIdentities, noMapIdentities });
}
export function resolveRoutingRecord(decoded, repdRef) {
if (typeof repdRef !== "string" || !/^\d+$/.test(repdRef)) {
return Object.freeze({ found: false, selectable: false, reason: "INVALID_EXACT_REPD_REF", record: null });
}
const record = decoded.byRef.get(repdRef) || null;
if (!record) return Object.freeze({ found: false, selectable: false, reason: "REPD_REF_NOT_IN_ROUTING_ORACLE", record: null });
if (!record.selectable) {
return Object.freeze({ found: true, selectable: false, reason: `NO_MAP_${record.geometry_status.toUpperCase()}`, record });
}
return Object.freeze({ found: true, selectable: true, reason: "MAP_EXACT_REPD_REF", record });
}
let routingCache = null;
export async function loadRoutingDeepLinkFallback(manifest, repdRef) {
invariant(typeof repdRef === "string" && /^\d+$/.test(repdRef), "deep-link fallback requires exact numeric repd_ref");
const routing = manifest.repd_routing;
const release = await fetchVerifiedJson(
immutableRoutingUrl(manifest, routing.release_path),
routing.release_sha256
);
invariant(release?.schema === "data-gridatlas.repd-routing-release.v1", "routing release schema mismatch");
invariant(release.release_id === routing.release_id && release.immutable === true, "routing release contract mismatch");
invariant(release.source_commit === routing.source_commit, "routing source commit mismatch");
invariant(release.classification === "IMMUTABLE_REPD_ROUTING_RELEASE", "routing release is not immutable-live routing data");
invariant(release.public_url === routing.base_url, "routing release URL mismatch");
invariant(release.coverage?.projects === REPD_ROUTING_CONTRACT.projects, "routing release project closure mismatch");
invariant(release.coverage?.map_identities === REPD_ROUTING_CONTRACT.mapIdentities, "routing release MAP closure mismatch");
invariant(release.coverage?.no_map_identities === REPD_ROUTING_CONTRACT.noMapIdentities, "routing release NO MAP closure mismatch");
invariant(release.files?.projects?.path === routing.projects_path, "routing projects receipt path mismatch");
invariant(release.files?.projects?.bytes === routing.projects_bytes, "routing projects receipt bytes mismatch");
invariant(release.files?.projects?.sha256 === routing.projects_sha256, "routing projects receipt hash mismatch");
routingCache ||= fetchVerifiedJson(
immutableRoutingUrl(manifest, routing.projects_path),
routing.projects_sha256,
routing.projects_bytes
).then(decodeRoutingProjects);
return resolveRoutingRecord(await routingCache, repdRef);
}
export function clearRoutingCacheForTests() {
routingCache = null;
}