GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / uk_renewables_pipeline/202609071221/scripts/core

Neon Substation Links V9 6 and 3 more files

A JavaScript file in the cartridges folder of GridAtlas that maps grid substations, 33kV, solar and wind, using haversine.

700 lines of JavaScript from globalgrid2050, graphics-engines-open-source, gridatlas, in 4 files. Topic: Grid network and substations. Section 369 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Atlas Interconnector Link V9 8 energy-data · globalgrid2050 / uk_renewables_pipeline/202609071221/scripts/core/atlas-interconnector-link-v9-8.js lines 1–75
  2. Interconnectors V9 8 energy-data · globalgrid2050 / uk_renewables_pipeline/202609071221/scripts/data/interconnectors-v9-8.js lines 1–52
  3. Substation Picker electrical · graphics-engines-open-source / web/substation-picker.mjs lines 1–45
  4. Neon Substation Links V9 6 geodesy · gridatlas / atlas/cartridges/202608311910-neon-substation-links-v9-6.js lines 1–528

Atlas Interconnector Link V9 8

A JavaScript module in the core folder of GlobalGrid2050 that works with interconnectors and the Renewable Energy Planning Database (REPD) register.

energy-dataglobalgrid2050 / uk_renewables_pipeline/202609071221/scripts/core/atlas-interconnector-link-v9-8.js · lines 1–75 of 75 · version 2026-09-07 12:21

What it does
It calculates interconnectors and the REPD register. Defines interconnectorIdentityV9_8, buildAtlasInterconnectorLinkV9_8, interconnectorMapNoteV9_8, interconnectorMapUnavailableReasonV9_8.
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: interconnectors, the REPD register. README: "Their MAP link carries the link's own identity - `interconnector=INTNED`, `technology=interconnector` - against the same canonical Atlas receiver as every REPD row, and never a `repd_ref`."
Downstream impact
Used directly by 8 files: Check V9 8 (globalgrid2050); Projects V9 9 (globalgrid2050); Check V9 9 (globalgrid2050); Check V9 10 (globalgrid2050); and 4 more. Reached from 15 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 Pn V973 Capacity Reports Workflow (globalgrid2050).
What it achieves
It builds atlas interconnector link v9 (`buildAtlasInterconnectorLinkV9_8`) and is built from the interconnector identity v9 8 helper (`interconnectorIdentityV9_8`). A REPD row's MAP link carries `repd_ref`, and the Atlas resolves the project from the register.
Why it matters
Imported by 4 files, including Projects V9 9, Renewable Energy Planning Database (REPD) Liquid and Renewable Energy Planning Database (REPD) Reports. Checked by 4 tests, including Check V9 8.
Application
globalgrid2050 · uk_renewables_pipeline/202609071221/scripts/core · JavaScript module
Uses
Atlas Receiver V9 7 (import)
Used by
referenced by Check V9 8 (new URL import.meta.url), imported by Projects V9 9 (import), referenced by Check V9 9 (new URL import.meta.url), referenced by Check V9 10 (new URL import.meta.url), referenced by Check V9 11 (new URL import.meta.url), imported by Renewable Energy Planning Database (REPD) Liquid (import), imported by Renewable Energy Planning Database (REPD) Reports (import), imported by Projects V9 8 (import)
Produces
INTERCONNECTOR_PARAMS, interconnectorIdentityV9_8, buildAtlasInterconnectorLinkV9_8, interconnectorMapNoteV9_8, interconnectorMapUnavailableReasonV9_8
Defines here
interconnectorIdentityV9_8, buildAtlasInterconnectorLinkV9_8, interconnectorMapNoteV9_8, interconnectorMapUnavailableReasonV9_8
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609071221/scripts/core/atlas-interconnector-link-v9-8.js:1-75 · blob ccac4fc7bc240c1ebf82511821e6c003669d0fd7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* THE MAP LINK FOR AN INTERCONNECTOR ROW.
 *
 * A REPD row's MAP link carries repd_ref, and the Atlas resolves the project
 * from the register. An interconnector has no REPD reference and is in no
 * register the Atlas reads, so its link carries the link's own identity -
 * `interconnector=INTNED` - and `technology=interconnector`, against the same
 * canonical receiver every other MAP cell uses. The receiver is the one the
 * compiled deep-link contract names (core/atlas-receiver-v9-7.js); this module
 * adds no second route and follows the same withdrawal.
 *
 * WHAT THE COORDINATE IN THE LINK IS.
 *   valid        both converters known: the great-circle midpoint, sent as a
 *                LABEL ANCHOR with zoom 7 so the whole span is in view. The
 *                Atlas's interconnector module reads `interconnector=` and
 *                fires its span model at both converters:
 *                    40km <- Grain --[ BritNed 234.9 km ]-- Maasvlakte -> 40km
 *                Measuring from the midpoint would report the sea; it is not
 *                done, and the parameter `anchor=midpoint` says so.
 *   gb_end_only  the GB converter, zoom 10, `anchor=gb_converter`.
 *   missing      no link. The cell says why, in the row, because a title
 *                attribute is unreachable on a phone.
 */
import { atlasReceiverV9_7, atlasReceiverFailureV9_7 } from "./atlas-receiver-v9-7.js";

export const INTERCONNECTOR_PARAMS = Object.freeze([
  "interconnector", "technology", "project", "capacity_mw", "anchor", "latitude", "longitude", "zoom",
]);

export function interconnectorIdentityV9_8(record) {
  if (!record || record.technology !== "interconnector") return "";
  return String(record.bmrs_code || record.repd_ref || "").replace(/^IC-/, "");
}

export function buildAtlasInterconnectorLinkV9_8(record) {
  const route = atlasReceiverV9_7();
  if (!route) return "";
  const identity = interconnectorIdentityV9_8(record);
  if (!identity) return "";
  if (record.geometry_status !== "valid" && record.geometry_status !== "gb_end_only") return "";
  const values = {
    interconnector: identity,
    technology: "interconnector",
    project: record.name,
    capacity_mw: record.capacity_mw,
    anchor: record.geometry_status === "valid" ? "midpoint" : "gb_converter",
    latitude: record.latitude,
    longitude: record.longitude,
    zoom: record.geometry_status === "valid" ? "7" : "10",
  };
  const url = new URL(route);
  for (const key of INTERCONNECTOR_PARAMS) {
    const value = values[key];
    if (value === undefined || value === null || value === "") continue;
    url.searchParams.set(key, String(value));
  }
  return url.href;
}

export function interconnectorMapNoteV9_8(record) {
  if (!record) return "";
  switch (record.geometry_status) {
    case "valid":
      return `Straight line converter to converter, ${record.span.straight_line_km} km. The map opens on the midpoint as a label anchor, not a location; the Atlas measures each end within its own search radius.`;
    case "gb_end_only":
      return `GB converter located (${record.gb_end.name}); the far converter is not yet held, so the map opens on the GB end only.`;
    default:
      return "";
  }
}

export function interconnectorMapUnavailableReasonV9_8(record) {
  if (!atlasReceiverV9_7()) return `MAP unavailable: ${atlasReceiverFailureV9_7()}`;
  if (!interconnectorIdentityV9_8(record)) return "MAP unavailable: this row carries no interconnector identity";
  return "MAP unavailable: no converter coordinates are held for this link yet. The row stays in the table, the CSV and the search.";
}

Interconnectors V9 8

A JavaScript module in the data folder of GlobalGrid2050 that fetches interconnectors, using SHA-256. It fetches text (`fetchText`) and loads interconnectors v9 (`loadInterconnectorsV9_8`).

energy-dataglobalgrid2050 / uk_renewables_pipeline/202609071221/scripts/data/interconnectors-v9-8.js · lines 1–52 of 52 · version 2026-09-07 12:21 · pattern fetchText (shared by 3 files)

What it does
It fetches interconnectors. Defines invariant, fetchText, sha256Hex, loadInterconnectorsV9_8. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'interconnectors'): 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: interconnectors.
Inputs & outputs
In: JSON file interconnectors_manifest.json.
Downstream impact
Used directly by 2 files: Projects V9 9 (globalgrid2050); Projects V9 8 (globalgrid2050). Reached from 12 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 Pn V973 Capacity Reports Workflow (globalgrid2050).
What it achieves
Loads the interconnector data product, and refuses anything but the pinned one.
Why it matters
Imported by Projects V9 9 and Projects V9 8.
Application
globalgrid2050 · uk_renewables_pipeline/202609071221/scripts/data · JavaScript module
Uses
none found
Used by
imported by Projects V9 9 (import), imported by Projects V9 8 (import)
Produces
loadInterconnectorsV9_8
Defines here
invariant, fetchText, sha256Hex, loadInterconnectorsV9_8
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609071221/scripts/data/interconnectors-v9-8.js:1-52 · blob 8929de767f44a5009062b20ce5fb812de351fb9b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Loads the interconnector data product, and refuses anything but the pinned one.
 *
 * Same discipline as canonical-projects: the manifest names the partition and
 * its sha256; the partition is read, hashed and counted; a mismatch fails
 * closed. Nothing cross-origin, nothing derived at read time. */
const MANIFEST_URL = "data/v9.8/interconnectors_manifest.json";
const MANIFEST_SCHEMA = "globalgrid2050.v9.interconnector-build.v9.8";
const PARTITION_SCHEMA = "globalgrid2050.v9.interconnector-partition.v9.8";
const TECHNOLOGY = "interconnector";

function invariant(condition, message) {
  if (!condition) throw new Error(`V9.8 interconnectors: ${message}`);
}

async function fetchText(path) {
  const response = await fetch(path, { cache: "default" });
  invariant(response.ok, `${path} returned HTTP ${response.status}`);
  invariant(new URL(response.url).origin === window.location.origin, `${path} redirected cross-origin`);
  return response.text();
}

async function sha256Hex(text) {
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
}

export async function loadInterconnectorsV9_8() {
  const manifest = JSON.parse(await fetchText(MANIFEST_URL));
  invariant(manifest.schema === MANIFEST_SCHEMA, "manifest schema mismatch");
  invariant(manifest.technology === TECHNOLOGY, "manifest technology mismatch");
  const partitionText = await fetchText(manifest.partition.path);
  const digest = await sha256Hex(partitionText);
  invariant(digest === manifest.partition.sha256, `${manifest.partition.path} sha256 mismatch`);
  const partition = JSON.parse(partitionText);
  invariant(partition.schema === PARTITION_SCHEMA, "partition schema mismatch");
  invariant(Array.isArray(partition.records) && partition.records.length === manifest.record_count, "record count mismatch");
  invariant(partition.record_count === partition.records.length, "partition count mismatch");
  const refs = new Set();
  for (const record of partition.records) {
    invariant(record.technology === TECHNOLOGY, `${record.name}: technology is not ${TECHNOLOGY}`);
    invariant(typeof record.repd_ref === "string" && record.repd_ref.startsWith("IC-"), `${record.name}: ref must be IC-…`);
    invariant(!refs.has(record.repd_ref), `${record.repd_ref}: duplicate ref`);
    refs.add(record.repd_ref);
    invariant(Number.isFinite(record.capacity_mw) && record.capacity_mw > 0, `${record.name}: capacity`);
    if (record.geometry_status === "valid" || record.geometry_status === "gb_end_only") {
      invariant(Number.isFinite(record.longitude) && Number.isFinite(record.latitude), `${record.name}: located but no anchor`);
    } else {
      invariant(record.longitude === null && record.latitude === null, `${record.name}: unlocated but carries an anchor`);
    }
  }
  return { records: partition.records, manifest, partition };
}

Substation Picker

A JavaScript module in Graphics Engines Open Source covering substations and cables, using SHA-256. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.

electricalgraphics-engines-open-source / web/substation-picker.mjs · lines 1–45 of 45 · Entry point

What it does
It draws substations and cables. Defines make, refresh. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): 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: substations, cables.
Downstream impact
Used directly by 1 file: Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/). Reached from 1 other entry point, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/.
What it achieves
Defines `make` and `refresh`. It responds to input and click events.
Why it matters
Loaded by the Graphics Engines Open Source page at https://ventusltd.github.io/graphics-engines-open-source/web/.
Application
graphics-engines-open-source · web · JavaScript module
Uses
GridAtlas (import)
Used by
loaded by Graphics Engines Open Source — Index Page (script src)
Produces
make, refresh
Defines here
make, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/substation-picker.mjs:1-45 · blob fe4be74a7014966c96e8c5be64dac14d5cc8df80 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
import { loadGridAtlasSubstations, GRIDATLAS_SUBSTATION_SOURCE } from './gridatlas.mjs';

const mount = document.getElementById('substation-picker');
if (mount) {
  const make = (tag, text) => { const node = document.createElement(tag); node.textContent = text; return node; };
  const title = make('h2', 'Public substations');
  const load = make('button', 'Load substation points'); load.type = 'button';
  const label = make('label', 'Snapshot ID');
  const query = make('input', ''); query.type = 'search'; query.placeholder = '0–5799'; query.disabled = true; label.append(query);
  const listLabel = make('label', 'Substation');
  const select = make('select', ''); select.disabled = true; listLabel.append(select);
  const apply = make('button', 'Anchor illustrative layout'); apply.type = 'button'; apply.disabled = true;
  const status = make('p', 'Published points only; the layout and cables remain illustrative.');
  status.className = 'muted'; status.setAttribute('role', 'status');
  const provenance = make('a', 'GridAtlas substation snapshot');
  provenance.href = GRIDATLAS_SUBSTATION_SOURCE.url; provenance.target = '_blank'; provenance.rel = 'noopener noreferrer'; provenance.style.color = '#a5cfff';
  mount.append(title, load, label, listLabel, apply, status, provenance);
  let substations = [], matches = [];
  function refresh() {
    const term = query.value.trim().replace(/^substation-/i, '');
    matches = substations.filter(point => !term || String(point.source_index).includes(term)).slice(0, 40);
    select.replaceChildren(...matches.map(point => { const option = make('option', `Substation ${point.source_index}`); option.value = point.id; return option; }));
    select.disabled = apply.disabled = matches.length === 0;
    status.textContent = `${substations.length} public points loaded; ${matches.length} matches shown (maximum 40). IDs identify rows in this snapshot.`;
  }
  query.addEventListener('input', refresh);
  load.addEventListener('click', async () => {
    load.disabled = true; status.textContent = 'Loading and verifying public substation snapshot…';
    const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 20000);
    try {
      const data = await loadGridAtlasSubstations({ signal: controller.signal });
      substations = data.substations; query.disabled = false; load.textContent = 'Substation snapshot loaded'; refresh();
    } catch (error) { status.textContent = `Could not load substations: ${error.name === 'AbortError' ? 'request timed out' : error.message}. Retry loading.`; load.disabled = false; }
    finally { clearTimeout(timeout); }
  });
  apply.addEventListener('click', () => {
    const point = matches.find(item => item.id === select.value), scene = window.electricalExplorer;
    if (!point) return;
    if (!scene?.state?.gpu || typeof scene.setOrigin !== 'function') { status.textContent = 'The GPU scene is unavailable.'; return; }
    try {
      scene.setOrigin({ latitude: point.latitude, longitude: point.longitude, label: `Substation ${point.source_index}` });
      status.textContent = `Anchored substation ${point.source_index}. Published voltage(s), volts: ${point.voltage ?? 'unavailable'}. Snapshot ${GRIDATLAS_SUBSTATION_SOURCE.generation}; SHA-256 ${point.snapshot_sha256.slice(0, 12)}…. Layout and cable routes remain illustrative.`;
    } catch (error) { status.textContent = `Could not anchor substation: ${error.message}`; }
  });
}

Neon Substation Links V9 6

A JavaScript file in the cartridges folder of GridAtlas that maps grid substations, 33kV, solar and wind, using haversine.

geodesygridatlas / atlas/cartridges/202608311910-neon-substation-links-v9-6.js · lines 1–528 of 707 · version 2026-08-31 19:10 · pattern interactiveLayerIds (shared by 10 files)

What it does
It maps grid substations, 33kV, solar and wind. Defines 24 functions or classes, including distanceKm, voltagesKv, representativePoint, loadSubstations, nearestSubstations. Side effects: changes the web page (DOM); makes network requests.
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: 33kV, solar, wind, 11kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson. Out: interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 33kV, 11kV.
Downstream impact
Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It loads substations (`loadSubstations`), removes card block (`removeCardBlock`) and stops animation (`stopAnimation`). Slot: replace-script for… Its code works with 33 kV and 11 kV. It responds to keydown and visibilitychange events.
Why it matters
Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
Application
gridatlas · atlas/cartridges · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
none found
Used by
named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
distanceKm, voltagesKv, representativePoint, loadSubstations, nearestSubstations, nearestProjects, installStyles, escapeHtml, caveatHtml, cardBlockHtml, injectIntoCard, removeCardBlock
Defines here
distanceKm, voltagesKv, representativePoint, loadSubstations, nearestSubstations, nearestProjects, installStyles, escapeHtml, caveatHtml, cardBlockHtml, injectIntoCard, removeCardBlock, emptyCollection, ensureLayers, stopAnimation, startAnimation, step, clearLinks
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/cartridges/202608311910-neon-substation-links-v9-6.js:1-528 · blob bd525ab78b2c589a662a6a08d4a0489e7c24c7dd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
 * GridAtlas cartridge — neon substation links.
 *
 * Generation 202608311910 (UTC). Slot: replace-script for
 * 202608292126-pre-snapped-config-adapter.js.
 *
 * WHAT IT DOES
 * ------------
 * Select a solar, battery or onshore wind project and the map draws animated
 * neon lines from it to the nearest substations at 33 kV and above. The same
 * distances are written onto the project card the engine has just opened,
 * marked BETA, with the reasons a distance is not a connection stated on the
 * card itself rather than hidden in a tooltip.
 *
 * WHY IT REPLACES THE CONFIG ADAPTER RATHER THAN ADDING A SCRIPT
 * -------------------------------------------------------------
 * The composer in atlas/index.html supports exactly one slot, `replace-script`.
 * There is no append slot, and inventing one would mean changing the composer,
 * which is a larger contract change than this feature is worth. So this
 * cartridge carries the pre-snapped config adapter's behaviour VERBATIM -- same
 * layer ids, same closure assertion, same failure mode, same public state
 * object -- and adds the link layer beside it. The immutable shell is not
 * touched, and `__GRIDATLAS_PRE_SNAPPED_CONFIG__` still reports exactly what it
 * reported before, so anything asserting on it keeps working.
 *
 * HOW IT HOOKS IN WITHOUT SHELL MUTATION
 * --------------------------------------
 * Two decorators, both of things the engine has already published by the time
 * this script runs:
 *
 *   window.initVentusMap  wrapped for the pre-snap config, as before.
 *   maplibregl.Map        wrapped to capture the instance, because the engine
 *                         keeps `map` in a closure and returns nothing. The
 *                         engine constructs its map inside initVentusMap, which
 *                         runs after this file, so the constructor is still
 *                         ours to wrap.
 *
 * THE MEASUREMENT
 * ---------------
 * Haversine on R = 6378.137 km, the same constant as ventus-corev8engine.js,
 * pipelinenews and Ventusltd/grid-distance-maths, so a distance read here
 * equals the same distance read there. Substations are mapped as points AND as
 * polygons; a polygon is reduced to its ring mean, because its first vertex is
 * a corner rather than the site.
 *
 * Scope is 33 kV and above. 11 kV is rare for utility-scale export and where it
 * occurs is often a private network behind the meter, so it is not a screening
 * signal. `voltage` is written `33000`, `33000;11000` for two voltages, and
 * `33000:11000` for a transformer ratio -- a 33/11 primary still carries 33 kV.
 *
 * WHAT A LINE IS NOT
 * ------------------
 * A straight line to mapped geometry. Not a cable route, not a connection
 * length, no wayleave, crossing, terrain or consent content. A mapped
 * substation does not confirm capacity, voltage suitability or connection
 * rights, and fault level and thermal headroom cannot be inferred from distance
 * at all -- they need DNO network data such as source impedance and a
 * connection study, alongside right of way, wayleaves and easements, land
 * control and consent. The card says all of that on screen.
 */
(() => {
  'use strict';

  const GENERATION = '202608311910';

  /* ══════════════════════════════════════════════════════════════════════
     PART 1 — the pre-snapped config adapter, carried forward unchanged.
     ══════════════════════════════════════════════════════════════════════ */

  const PRE_SNAPPED_LAYER_IDS = new Set(['400', '275', '220', '132', '66']);
  const originalInit = window.initVentusMap;

  if (typeof originalInit !== 'function') {
    throw new Error('V8 engine init function is unavailable before map-ready adapter');
  }

  const state = {
    schema: 'gridatlas.pre-snapped-config-adapter.v1',
    generation: '202608292126',
    applied: false,
    changed_layer_ids: [],
    preserved_preload_flags: true,
    failures: []
  };
  window.__GRIDATLAS_PRE_SNAPPED_CONFIG__ = state;

  window.initVentusMap = function gridAtlasMapReadyInit(options) {
    try {
      const changed = [];
      const config = options.config.map(group => ({
        ...group,
        layers: group.layers.map(layer => {
          if (!PRE_SNAPPED_LAYER_IDS.has(String(layer.id))) return layer;
          if (layer.snap !== true) {
            throw new Error(`expected V8 snap=true for topology layer ${layer.id}`);
          }
          changed.push(String(layer.id));
          return { ...layer, snap: false };
        })
      }));

      const expected = [...PRE_SNAPPED_LAYER_IDS].sort();
      if (JSON.stringify([...changed].sort()) !== JSON.stringify(expected)) {
        throw new Error(`pre-snapped layer closure mismatch: ${JSON.stringify(changed)}`);
      }

      state.applied = true;
      state.changed_layer_ids = changed;
      return originalInit({ ...options, config });
    } catch (error) {
      state.failures.push(String(error?.message || error));
      throw error;
    }
  };

  /* ══════════════════════════════════════════════════════════════════════
     PART 2 — neon substation links.
     ══════════════════════════════════════════════════════════════════════ */

  const R_ATLAS = 6378.137;          // WGS84 semi-major axis. The house constant.
  const DEG = Math.PI / 180;
  const MIN_KV = 33;
  const LINK_COUNT = 5;              // how many substations to reach for
  const MAX_LINK_KM = 40;            // beyond this, silence is more honest
  const SUBS_URL = 'data/grid_substations.geojson';
  const SUBS_LAYER_ID = 'l-subs';    // engine convention: layer `l-<id>`, source `src-<id>`

  // Project technologies this fires for. Onshore only: an offshore turbine's
  // export route is nothing like a straight line to the nearest onshore
  // substation, so drawing one would be a picture of a lie.
  const PROJECT_TECHS = new Set([
    'solar', 'solar_operational', 'solar_roof',
    'bess', 'bess_operational',
    'wind', 'wind_onshore_operational'
  ]);

  // SCADA on a dark map, not arcade neon. These are the muted siblings of the
  // engine's own layer colours: enough saturation to read as live, low enough
  // not to shout over the basemap or the grid layers underneath.
  const TECH_COLOUR = {
    solar: '#d8c96a', solar_operational: '#d8c96a', solar_roof: '#d8c96a',
    bess: '#d9963c', bess_operational: '#d9963c',
    wind: '#6fb582', wind_onshore_operational: '#6fb582'
  };
  const SUBSTATION_COLOUR = '#5fbdc2';   // teal, the substation end of a link
  const FLOW_COLOUR = '#bfe9ee';         // pale cyan travelling pulse, not white

  const SRC = 'gridatlas-neon-links';
  const SRC_NODES = 'gridatlas-neon-nodes';
  const L_GLOW = 'l-neon-glow';
  const L_CORE = 'l-neon-core';
  const L_FLOW = 'l-neon-flow';
  const L_NODE = 'l-neon-node';
  const L_NODE_RING = 'l-neon-node-ring';
  const L_LABEL = 'l-neon-label';

  const link = {
    schema: 'gridatlas.neon-substation-links.v1',
    generation: GENERATION,
    minimum_kv: MIN_KV,
    map_captured: false,
    installed: false,
    substations_loaded: 0,
    substations_qualifying: 0,
    last_selection: null,
    links_drawn: 0,
    reduced_motion: false,
    failures: []
  };
  window.__GRIDATLAS_NEON_LINKS__ = link;

  /* ── geodesy ─────────────────────────────────────────────────────────── */

  // Identical in form and constant to ventus-corev8engine.js haversine().
  function distanceKm(lon1, lat1, lon2, lat2) {
    const dLat = (lat2 - lat1) * DEG;
    const dLon = (lon2 - lon1) * DEG;
    const x = Math.sin(dLat / 2) ** 2
      + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
    return R_ATLAS * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
  }

  /* ── substation layer ────────────────────────────────────────────────── */

  // `33000`, `33000;11000` (two voltages) and `33000:11000` (a transformer
  // ratio) all mean 33 kV is present. Splitting only on ';' drops the ratios.
  function voltagesKv(properties) {
    const raw = properties?.voltage ?? properties?.kv ?? '';
    const out = [];
    for (const token of String(raw).split(/[;,|:\s]+/)) {
      if (!token) continue;
      const value = Number(token);
      if (!Number.isFinite(value)) continue;
      out.push(value > 1000 ? value / 1000 : value);
    }
    return out;
  }

  // A polygon's first ring vertex is a corner, not the site.
  function representativePoint(geometry) {
    if (!geometry) return null;
    const { type, coordinates } = geometry;
    if (type === 'Point') return [coordinates[0], coordinates[1]];
    const ring = type === 'Polygon' ? coordinates[0]
      : type === 'MultiPolygon' ? coordinates[0]?.[0] : null;
    if (!Array.isArray(ring) || !ring.length) return null;
    let x = 0; let y = 0;
    for (const p of ring) { x += p[0]; y += p[1]; }
    return [x / ring.length, y / ring.length];
  }

  // Exposed so a proof can check this arithmetic against
  // Ventusltd/grid-distance-maths rather than trusting the comment above it.
  // Pure functions only; nothing here touches the map or the DOM.
  link.measure = { distanceKm, voltagesKv, representativePoint };

  let substationsPromise = null;
  function loadSubstations() {
    if (substationsPromise) return substationsPromise;
    substationsPromise = (async () => {
      // The engine may already hold the layer; prefer that over a second fetch.
      const response = await fetch(new URL(SUBS_URL, document.baseURI), { cache: 'force-cache' });
      if (!response.ok) throw new Error(`substations HTTP ${response.status}`);
      const collection = await response.json();
      const features = Array.isArray(collection?.features) ? collection.features : [];
      link.substations_loaded = features.length;
      const out = [];
      for (const feature of features) {
        const kv = voltagesKv(feature.properties);
        if (!kv.length || Math.max(...kv) < MIN_KV - 0.5) continue;
        const at = representativePoint(feature.geometry);
        if (!at) continue;
        out.push({
          at,
          kv: kv.filter(v => v >= MIN_KV - 0.5).sort((a, b) => b - a),
          name: feature.properties?.name || '',
          operator: feature.properties?.operator
            || feature.properties?.['operator:short'] || ''
        });
      }
      link.substations_qualifying = out.length;
      return out;
    })().catch(error => {
      link.failures.push(String(error?.message || error));
      substationsPromise = null;
      return [];
    });
    return substationsPromise;
  }

  function nearestSubstations(lon, lat, subs) {
    const scored = [];
    for (const sub of subs) {
      const km = distanceKm(lon, lat, sub.at[0], sub.at[1]);
      if (km > MAX_LINK_KM) continue;
      scored.push({ ...sub, km });
    }
    scored.sort((a, b) => a.km - b.km);
    return scored.slice(0, LINK_COUNT);
  }

  // The mirror of nearestSubstations: given a substation, the projects around
  // it. Read from the loaded source rather than the viewport, so panning the
  // map does not change the answer -- querySourceFeatures returns what the
  // GeoJSON source holds, queryRenderedFeatures returns only what is on screen.
  function nearestProjects(map, lon, lat) {
    let features = [];
    try { features = map.querySourceFeatures('src-repd') || []; }
    catch (_) { return []; }
    const seen = new Set();
    const scored = [];
    for (const feature of features) {
      const properties = feature.properties || {};
      const tech = String(properties.tech || properties.type || '');
      if (!PROJECT_TECHS.has(tech)) continue;
      const at = representativePoint(feature.geometry);
      if (!at) continue;
      // One source, many tiles: the same project surfaces more than once.
      const key = properties.repd_ref || properties.repdRef
        || `${at[0].toFixed(5)},${at[1].toFixed(5)}`;
      if (seen.has(key)) continue;
      seen.add(key);
      const km = distanceKm(lon, lat, at[0], at[1]);
      if (km > MAX_LINK_KM) continue;
      const capacity = parseFloat(properties.capacity);
      scored.push({
        at, km, tech,
        kv: [],
        name: properties.name || properties.SiteName || properties['Site Name'] || '',
        mw: Number.isFinite(capacity) ? capacity : null
      });
    }
    scored.sort((a, b) => a.km - b.km);
    return scored.slice(0, LINK_COUNT);
  }

  link.measure.nearestSubstations = nearestSubstations;
  link.measure.MIN_KV = MIN_KV;
  link.measure.MAX_LINK_KM = MAX_LINK_KM;
  link.measure.LINK_COUNT = LINK_COUNT;
  link.measure.PROJECT_TECHS = PROJECT_TECHS;

  /* ── the project card ────────────────────────────────────────────────── */

  const BLOCK_CLASS = 'gridatlas-neon-block';
  const CSS_ID = 'gridatlas-neon-css';

  // The distances belong ON the card the user just opened, not in a separate
  // panel they have to notice. The engine builds that card with openPopup(),
  // which is a closure, so this appends to the rendered popup instead --
  // matching the engine's own idiom: monospace on black, cyan heading, amber
  // for a figure, grey for provenance.
  function installStyles() {
    if (document.getElementById(CSS_ID)) return;
    const style = document.createElement('style');
    style.id = CSS_ID;
    style.textContent = `
.${BLOCK_CLASS}{margin-top:7px;padding-top:6px;border-top:1px solid #123;font-family:monospace}
.${BLOCK_CLASS} .neon-hd{display:flex;align-items:center;gap:6px;font-size:10px;letter-spacing:.06em;
  color:#5fbdc2;font-weight:bold;text-transform:uppercase}
.${BLOCK_CLASS} .neon-beta{font-size:8px;letter-spacing:.06em;padding:1px 4px;border-radius:2px;
  background:#3a2f12;color:#e0b050;border:1px solid #6a5320;text-transform:uppercase}
.${BLOCK_CLASS} ol{list-style:none;margin:5px 0 0;padding:0}
.${BLOCK_CLASS} li{display:flex;align-items:baseline;gap:6px;padding:2px 0}
.${BLOCK_CLASS} .neon-km{color:#5fbdc2;font-weight:bold;font-variant-numeric:tabular-nums;
  min-width:54px;text-shadow:0 0 6px rgba(95,189,194,.35)}
.${BLOCK_CLASS} .neon-name{color:#9fb3ba;overflow:hidden;text-overflow:ellipsis;
  white-space:nowrap;flex:1;max-width:150px}
.${BLOCK_CLASS} .neon-kv{color:#ffae00;font-size:9px;white-space:nowrap}
.${BLOCK_CLASS} .neon-caveat{margin-top:6px;color:#68797f;font-size:9px;line-height:1.5}
.${BLOCK_CLASS} .neon-caveat b{color:#8b9aa1;font-weight:bold}`;
    document.head.appendChild(style);
  }

  function escapeHtml(value) {
    return String(value).replace(/[&<>"']/g, c => (
      { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  }

  // BETA here marks SCOPE, not doubt about the arithmetic. The measurement is
  // published and checked; what it does not cover is stated, and the things a
  // distance cannot answer at any precision are named rather than implied.
  function caveatHtml() {
    return `<div class="neon-caveat">`
      + `<b>Beta analytics, not an actual grid connection.</b> Straight-line distance to mapped `
      + `geometry &mdash; not a cable route, not a connection length, and no route has been `
      + `walked. A real connection depends on factors that must be studied: network impedance `
      + `and fault level, thermal headroom, existing committed connections and queue position, `
      + `right of way, wayleaves and easements, crossings, terrain, land control and consent. `
      + `None of those can be inferred from a distance. A mapped substation does not confirm `
      + `capacity, voltage suitability or acceptance by any network party, and absence from a `
      + `mapped layer is not absence on the ground.`
      + `</div>`;
  }

  function cardBlockHtml(links, direction) {
    installStyles();
    const toSubstations = direction !== 'from-substation';
    const title = toSubstations
      ? `Nearest substations &ge;${MIN_KV} kV`
      : 'Nearest projects';
    const fallbackName = toSubstations ? 'Unnamed substation' : 'Unnamed project';
    const head = `<div class="neon-hd">${title}<span class="neon-beta">Beta</span></div>`;
    if (!links.length) {
      const nothing = toSubstations
        ? `No mapped substation at ${MIN_KV} kV or above within ${MAX_LINK_KM} km of this point.`
        : `No mapped project within ${MAX_LINK_KM} km of this substation, among the layers `
          + `currently loaded.`;
      return `<div class="${BLOCK_CLASS}">${head}`
        + `<div class="neon-caveat">${nothing}</div>${caveatHtml()}</div>`;
    }
    const rows = links.map(l => {
      const tail = l.kv && l.kv.length ? `${l.kv[0]} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      return `<li><span class="neon-km">${l.km.toFixed(2)} km</span>`
        + `<span class="neon-name">${escapeHtml(l.name || fallbackName)}</span>`
        + (tail ? `<span class="neon-kv">${escapeHtml(tail)}</span>` : '') + `</li>`;
    }).join('');
    return `<div class="${BLOCK_CLASS}">${head}<ol>${rows}</ol>${caveatHtml()}</div>`;
  }

  // The engine opens its popup in its own click handler. This one is registered
  // afterwards, so by the time it runs the popup is in the DOM and can be
  // extended rather than replaced.
  function injectIntoCard(links, direction) {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content) return false;
    content.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
    const holder = document.createElement('div');
    holder.innerHTML = cardBlockHtml(links, direction);
    const block = holder.firstElementChild;
    if (!block) return false;
    (content.firstElementChild || content).appendChild(block);
    return true;
  }

  function removeCardBlock() {
    document.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
  }

  /* ── the map layers ──────────────────────────────────────────────────── */

  let capturedMap = null;
  let animationHandle = null;
  let dashPhase = 0;

  function emptyCollection() {
    return { type: 'FeatureCollection', features: [] };
  }

  function ensureLayers(map) {
    if (map.getSource(SRC)) return;

    map.addSource(SRC, { type: 'geojson', data: emptyCollection() });
    map.addSource(SRC_NODES, { type: 'geojson', data: emptyCollection() });

    // Three stacked strokes make the neon: a wide soft glow, a bright core, and
    // a dashed overlay whose offset is animated so the line reads as flowing
    // towards the substation.
    map.addLayer({
      id: L_GLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 5, 12, 12],
        'line-opacity': 0.10,
        'line-blur': ['interpolate', ['linear'], ['zoom'], 6, 3, 12, 8]
      }
    });
    map.addLayer({
      id: L_CORE, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': ['get', 'strength']
      }
    });
    map.addLayer({
      id: L_FLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'butt' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 1, 12, 2],
        'line-opacity': 0.55,
        'line-dasharray': [0.2, 3.2]
      }
    });

    map.addLayer({
      id: L_NODE_RING, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 6, 12, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': SUBSTATION_COLOUR,
        'circle-stroke-width': 1,
        'circle-stroke-opacity': 0.4
      }
    });
    map.addLayer({
      id: L_NODE, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 2.2, 12, 4],
        'circle-color': SUBSTATION_COLOUR,
        'circle-opacity': 0.8
      }
    });
    map.addLayer({
      id: L_LABEL, type: 'symbol', source: SRC_NODES,
      layout: {
        'text-field': ['get', 'label'],
        'text-size': 10,
        'text-offset': [0, -1.5],
        'text-anchor': 'bottom',
        'text-allow-overlap': false,
        'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold']
      },
      paint: {
        'text-color': '#a9c4c9',
        'text-halo-color': '#000c10',
        'text-halo-width': 1.5,
        'text-opacity': 0.9
      }
    });

    link.installed = true;
  }

  function stopAnimation() {
    if (animationHandle !== null) {
      cancelAnimationFrame(animationHandle);
      animationHandle = null;
    }
  }

  function startAnimation(map) {
    stopAnimation();
    const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
    link.reduced_motion = reduced;
    if (reduced) {
      // Motion is a preference, not a requirement. The lines, the nodes and
      // every number stay; only the travelling dash stops.
      try { map.setPaintProperty(L_FLOW, 'line-opacity', 0); } catch (_) { /* layer gone */ }
      return;
    }
    const step = () => {
      dashPhase = (dashPhase + 0.09) % 3.4;
      try {
        map.setPaintProperty(L_FLOW, 'line-dasharray',
          [0.001, dashPhase, 0.55, 3.4 - dashPhase]);
      } catch (_) {
        stopAnimation();
        return;
      }
      animationHandle = requestAnimationFrame(step);
    };
    animationHandle = requestAnimationFrame(step);
  }

  function clearLinks() {
    stopAnimation();
    const map = capturedMap;
    if (map && map.getSource(SRC)) {
      map.getSource(SRC).setData(emptyCollection());
      map.getSource(SRC_NODES).setData(emptyCollection());
    }
    removeCardBlock();
    link.links_drawn = 0;