GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/journey/src

Annotations and 2 more files

A JavaScript module in the lineage folder of GridAtlas that fetches the Renewable Energy Planning Database (REPD) register and substations, using SHA-256.

641 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 632 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. Controller render · gridatlas / tools/journey/src/controller.mjs lines 1–202
  2. Build storage · gridatlas / tools/lightning/build.mjs lines 1–160
  3. Annotations interaction · gridatlas / tools/lightning/lineage/annotations.mjs lines 1–279

Controller

A JavaScript module in the journey folder of GridAtlas that maps cables, using SHA-256. It creates journey controller (`createJourneyController`), removes map (`removeMap`) and writes cursor (`writeCursor`).

rendergridatlas / tools/journey/src/controller.mjs · lines 1–202 of 202 · pattern createJourneyController (shared by 2 files)

What it does
It maps cables. Defines 26 functions or classes, including createJourneyController, empty, el, listen, isReduced. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: cables.
Downstream impact
Used directly by 1 file: Controller Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Native MapLibre presentation only. The pinned engine owns evidence and traversal. It responds to change events.
Why it matters
Checked by Controller Test.
Application
gridatlas · tools/journey/src · JavaScript module
Uses
none found
Used by
imported by Controller Test (import)
Produces
createJourneyController
Defines here
createJourneyController, empty, el, listen, isReduced, report, pauseMotion, controlsState, removeMap, installMap, writeCursor, lineFor, frameRoute, showStep, advance, resetPlan, animate, frame, choose, installLayerControls, setOrigin, open, styleLoad, preferenceChange, mapRemoved, destroy
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/journey/src/controller.mjs:1-202 · blob f649a4b0ece08b522aec343edd92d9eda662aad5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Native MapLibre presentation only. The pinned engine owns evidence and traversal. */
export function createJourneyController({map, document: D, window: W, planner, fixture, css, generation}) {
  const NS = 'gridatlas-gj03', source = NS + '-route', cursor = NS + '-cursor';
  const layerIds = [NS + '-verified', NS + '-schematic', NS + '-cursor'];
  const empty = () => ({type: 'FeatureCollection', features: []});
  const caveat = 'The travelling light is a learning cursor, not measured current or a power-flow simulation. Dotted links are schematic, not cable routes. Flow direction unavailable.';
  const layerGroups = [], layerLaunchers = [];
  let layerObserver = null, returnFocus = null, originContext = null;
  const on = [], ownedSources = new Map(), ownedLayers = new Map();
  let alive = true, opened = false, plan = null, step = 0, raf = null, playing = false, epoch = 0, demo = false, routeData = empty(), cursorData = empty();
  if (!map || !['addSource', 'addLayer', 'getSource', 'getLayer', 'removeSource', 'removeLayer', 'on', 'off'].every(k => typeof map[k] === 'function')) throw new Error('Native MapLibre map unavailable');
  if (D.getElementById(NS)) throw new Error('Journey already mounted');
  const container = D.getElementById('map-container') || map.getContainer?.();
  const initialPadding = map.getPadding?.();
  if (!container) throw new Error('Native map container unavailable');
  function el(tag, text, parent, attrs = {}) { const e = D.createElement(tag); if (text) e.textContent = text; for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); parent?.appendChild(e); return e; }
  function listen(e, type, fn) { e.addEventListener(type, fn); on.push(() => e.removeEventListener(type, fn)); }
  const root = el('div', null, container, {id: NS, 'data-generation': generation});
  const style = el('style', css, root);
  const opener = el('button', 'Grid Journeys', root, {type: 'button', 'aria-expanded': 'false', 'aria-controls': NS + '-panel', class: 'gj-launch'});
  const panel = el('section', null, root, {id: NS + '-panel', 'aria-label': 'Grid Journeys', hidden: '', class: 'gj-panel'});
  const heading = el('div', null, panel, {class: 'gj-heading'});
  el('strong', 'GRID JOURNEYS', heading);
  const close = el('button', 'Close', heading, {type: 'button', 'aria-label': 'Close Grid Journey'});
  const caption = el('p', caveat, panel, {class: 'gj-caveat'});
  const state = el('p', 'Explore the physical grid on the map, or choose a learning demonstration below.', panel, {role: 'status', 'aria-live': 'polite', class: 'gj-status'});
  const context = el('p', 'Select an asset on the map to explore its surroundings.', panel, {class: 'gj-origin'});
  const realGrid = el('button', 'Explore real grid nearby', panel, {type: 'button'});
  const demoButton = el('button', 'Load SYNTHETIC demonstration', panel, {type: 'button'});
  const label = el('label', 'Explicit starting node ', panel, {class: 'gj-node'});
  const select = el('select', null, label, {'aria-label': 'Explicit starting node', disabled: ''});
  el('option', 'Choose a reviewed node…', select, {value: ''});
  const controls = el('div', null, panel, {class: 'gj-controls'});
  const start = el('button', 'Start', controls, {type: 'button', disabled: ''});
  const pause = el('button', 'Pause', controls, {type: 'button', disabled: ''});
  const next = el('button', 'Next', controls, {type: 'button', disabled: ''});
  const reset = el('button', 'Reset', controls, {type: 'button', disabled: ''});
  const evidence = el('details', null, panel, {class: 'gj-evidence'});
  el('summary', 'Input evidence and limits', evidence);
  evidence.appendChild(caption);
  const receipt = el('pre', 'Real routes: 0 accepted. No measured or modelled MW inputs. Synthetic data loads only on explicit request.', evidence);
  const media = W.matchMedia?.('(prefers-reduced-motion: reduce)');
  function isReduced() { return media?.matches === true; }
  function report(s) { if (alive) state.textContent = s; }
  function pauseMotion() { playing = false; if (raf !== null) W.cancelAnimationFrame(raf); raf = null; pause.disabled = true; start.disabled = !plan?.steps.length || step >= plan.steps.length; }
  function controlsState() { const usable = !!plan?.steps.length; start.disabled = !usable || step >= plan.steps.length || playing; next.disabled = !usable || playing || step >= plan.steps.length; reset.disabled = !plan; pause.disabled = !playing; start.textContent = isReduced() ? 'Start · manual' : 'Start'; }
  function removeMap() {
    for (const [id, object] of [...ownedLayers].reverse()) { if (map.getLayer(id) === object) map.removeLayer(id); ownedLayers.delete(id); }
    for (const [id, object] of ownedSources) { if (map.getSource(id) === object) map.removeSource(id); } ownedSources.clear();
  }
  function installMap() {
    if (!alive || !opened || !plan) return false;
    // isStyleLoaded also waits on map resources; a loaded stylesheet can accept sources earlier.
    if (typeof map.getStyle === 'function' && !map.getStyle()) return true;
    try {
      for (const id of [source, cursor]) if (map.getSource(id) && ownedSources.get(id) !== map.getSource(id)) throw new Error('Journey source collision; existing map source preserved');
      for (const id of layerIds) if (map.getLayer(id) && ownedLayers.get(id) !== map.getLayer(id)) throw new Error('Journey layer collision; existing map layer preserved');
      for (const [id, data] of [[source, routeData], [cursor, cursorData]]) { if (!map.getSource(id)) { map.addSource(id, {type: 'geojson', data}); ownedSources.set(id, map.getSource(id)); } else map.getSource(id).setData(data); }
      const layers = [
        {id: layerIds[0], type: 'line', source, filter: ['==', ['get', 'schematic'], false], paint: {'line-color': '#00ffff', 'line-width': 3}},
        {id: layerIds[1], type: 'line', source, filter: ['==', ['get', 'schematic'], true], paint: {'line-color': '#ffd84d', 'line-width': 3, 'line-dasharray': [1, 3]}},
        {id: layerIds[2], type: 'circle', source: cursor, paint: {'circle-color': '#fff', 'circle-radius': 5, 'circle-stroke-color': '#00ffff', 'circle-stroke-width': 3}}
      ];
      for (const l of layers) if (!map.getLayer(l.id)) { map.addLayer(l); ownedLayers.set(l.id, map.getLayer(l.id)); }
      return true;
    } catch (e) { pauseMotion(); report('WITHHELD: ' + e.message); removeMap(); plan = null; controlsState(); return false; }
  }
  function writeCursor(coordinates) {
    cursorData = {type: 'FeatureCollection', features: coordinates ? [{type: 'Feature', properties: {meaning: 'learning cursor only'}, geometry: {type: 'Point', coordinates}}] : []};
    if (ownedSources.has(cursor) && ownedSources.get(cursor) === map.getSource(cursor)) map.getSource(cursor).setData(cursorData);
  }
  function lineFor(s) { const e = plan.edgeCatalog.find(e => e.edgeUid === s.edgeUid); if (!e?.coordinates) return null; const coords = e.coordinates.map(p => [...p]); if (s.direction === 'reverse') coords.reverse(); return {e, coords}; }
  function frameRoute() {
    if (!alive || !opened || !plan) return;
    const pts = plan.edgeCatalog.flatMap(e => e.coordinates || []);
    const r = map.getContainer?.().getBoundingClientRect?.(), q = panel.getBoundingClientRect?.();
    let padding = 65;
    if (r && q) { const top = Math.max(45, q.bottom - r.top + 12); padding = q.width > r.width * .6 && r.height - top > 130 ? {left: 35, right: 35, top, bottom: 50} : {left: 45, right: Math.min(r.width * .6, q.width + 25), top: 55, bottom: 55}; }
    if (pts.length && map.fitBounds) { map.setPadding?.({top: 0, right: 0, bottom: 0, left: 0}); map.fitBounds([[Math.min(...pts.map(p => p[0])), Math.min(...pts.map(p => p[1]))], [Math.max(...pts.map(p => p[0])), Math.max(...pts.map(p => p[1]))]], {padding, maxZoom: 9, duration: 0}); }
  }
  function showStep(index) {
    const s = plan.steps[index], line = lineFor(s);
    writeCursor(line?.coords.at(-1) || null);
    report(`SYNTHETIC ONLY · ${index + 1}/${plan.steps.length} · ${s.traversal} ${s.nearNode} → ${s.farNode} · ${s.geometryStatus === 'published_node_unlocated' ? 'UNLOCATED: text only' : line?.e.schematic ? 'DOTTED SCHEMATIC: not a cable route' : 'synthetic reviewed polyline'} · journey heading, flow direction unavailable`);
    step = index + 1; controlsState();
  }
  function advance() { pauseMotion(); if (plan && step < plan.steps.length) showStep(step); }
  function resetPlan() { pauseMotion(); step = 0; writeCursor(null); if (plan) report(`SYNTHETIC ONLY · ready · ${plan.visitedUniqueEdges} source-row edges; ${plan.steps.length} moves including explicit backtracking; physical units unknown`); controlsState(); }
  function animate() {
    if (!alive || !opened || !plan || step >= plan.steps.length) { pauseMotion(); controlsState(); return; }
    if (isReduced()) { pauseMotion(); controlsState(); return; }
    const index = step, s = plan.steps[index], line = lineFor(s); let began;
    function frame(now) {
      if (!alive || !opened || !playing) return;
      if (isReduced()) { pauseMotion(); controlsState(); return; }
      began ??= now; const t = Math.min(1, (now - began) / 1000);
      // Only a reviewed polyline gets a travelling light. Schematic/unlocated moves are discrete.
      if (line && !line.e.schematic) {
        const p = t * (line.coords.length - 1), i = Math.min(line.coords.length - 2, Math.floor(p)), f = p - i;
        writeCursor(line.coords[i].map((v, k) => v + (line.coords[i + 1][k] - v) * f));
      }
      if (t < 1) raf = W.requestAnimationFrame(frame);
      else { showStep(index); if (playing) animate(); }
    }
    raf = W.requestAnimationFrame(frame);
  }
  async function choose() {
    const ticket = ++epoch; pauseMotion(); plan = null; routeData = empty(); cursorData = empty(); removeMap(); controlsState();
    if (!select.value || !demo) { report('Choose an explicit reviewed synthetic node. No nearest-node or project connection is inferred.'); return; }
    report('Checking exact source bytes and review ledger…');
    try {
      const candidate = await planner({sourceBytes: fixture.networkText, ledger: fixture.ledger, query: {seed: {chosenNode: select.value}, bounds: {maxNodes: 25, maxEdges: 30, maxMoves: 60, maxGeometryBytes: 16000}}});
      if (!alive || ticket !== epoch || !opened) return;
      if (candidate.status === 'refused' || !candidate.steps.length) { report('WITHHELD: ' + (candidate.refusal || 'no eligible reviewed edges')); return; }
      // The engine classifies evidence. Presentation refuses unsupported output as well.
      if (candidate.edgeCatalog.some(e => !['verified_circuit_and_polyline', 'published_topology_only', 'published_node_unlocated'].includes(e.geometryStatus))) throw new Error('Unsupported geometry evidence');
      plan = candidate;
      routeData = {type: 'FeatureCollection', features: plan.edgeCatalog.filter(e => e.coordinates).map(e => ({type: 'Feature', properties: {edgeUid: e.edgeUid, schematic: e.schematic, meaning: e.label}, geometry: {type: 'LineString', coordinates: e.coordinates}}))};
      receipt.textContent = `SYNTHETIC TEST ONLY; no real assets or third-party approval\nsource SHA256 ${plan.sourceBundleSha}\nreview SHA256 ${plan.reviewLedgerSha}\nplan SHA256 ${plan.planSha256}\n${plan.edgeCatalog.filter(e => e.geometryStatus === 'verified_circuit_and_polyline').length} synthetic polylines; ${plan.edgeCatalog.filter(e => e.schematic).length} schematic; ${plan.edgeCatalog.filt  … [line shortened here: 760 characters; full line on GitHub]
      if (!installMap()) return;
      resetPlan();
      frameRoute();
    } catch (e) { if (alive && ticket === epoch) report('WITHHELD: ' + e.message); }
  }
  function installLayerControls() {
    const hosts = ['scada-ui-container', 'fs-curtain-keys'].map(id => [id, D.getElementById(id)]);
    hosts.push(['native-grid-menu', D.querySelector?.('#gridatlas-menu-bar-panel-4 .gm-panel-body')]);
    for (const [id, host] of hosts) {
      if (!host || layerGroups.some(g => g.parentNode === host || g.parent === host)) continue;
      // Other native modules use .key-group as the engine-dashboard ready marker.
      // Never create that marker before the engine's original controls exist.
      if (id !== 'native-grid-menu' && !host.querySelector?.('input[data-layer-id]')) continue;
      const group = el('div', null, host, {class: 'key-group', 'data-journey-group': id});
      const title = el('div', 'Grid Journeys', group, {class: 'key-title'});
      const button = el('button', 'Open Grid Journey', group, {type: 'button', class: 'map-ctrl-btn', 'aria-controls': NS + '-panel', 'aria-expanded': String(opened)});
      button.style.cssText = 'min-height:44px;min-width:44px;';
      el('p', 'Exploratory only; real routes require reviewed circuit evidence.', group);
      listen(button, 'click', e => { e.stopPropagation?.(); returnFocus = button; W.__GRIDATLAS_MODULES__?.menuBar?.closeAll?.(); const curtain = D.getElementById('fs-curtain'); if (id === 'fs-curtain-keys' && curtain?.classList?.contains('curtain-open')) D.getElementById('fs-curtain-tab')?.click(); open(); });
      layerGroups.push(group); layerLaunchers.push(button);
    }
  }
  function setOrigin(origin) {
    originContext = null;
    if (origin && typeof origin === 'object') {
      const name = typeof origin.name === 'string' ? origin.name.slice(0, 160) : '';
      const id = typeof origin.id === 'string' || typeof origin.id === 'number' ? String(origin.id).slice(0, 80) : '';
      if (name || id) { originContext = {name, id}; if (Array.isArray(origin.at) && origin.at.length === 2 && origin.at.every(Number.isFinite) && Math.abs(origin.at[0]) <= 180 && Math.abs(origin.at[1]) <= 90 && (origin.at[0] !== 0 || origin.at[1] !== 0)) originContext.at = [...origin.at]; if (['repd', 'datacentre', 'substation'].includes(origin.type)) originContext.type = origin.type; }
    }
    context.textContent = originContext ? 'Selected asset: ' + [originContext.name, originContext.id].filter(Boolean).join(' ? ') + '. Nearby assets are map context; connections need source evidence.' : 'Select an asset on the map to explore its surroundings.';
    realSelection(false);
  }
  function shut() { ++epoch; pauseMotion(); opened = false; panel.hidden = true; opener.setAttribute('aria-expanded', 'false'); removeMap(); if (initialPadding) map.setPadding(initialPadding); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'false'); const target = returnFocus?.isConnected === false || (returnFocus?.getClientRects && !returnFocus.getClientRects().length) ? D.getEle  … [line shortened here: 491 characters; full line on GitHub]
  function open(options) { if (!alive) return; if (options?.origin) setOrigin(options.origin); opened = true; panel.hidden = false; opener.setAttribute('aria-expanded', 'true'); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'true'); installMap(); frameRoute(); close.focus(); }
  function realSelection(clearContext = true) { if (clearContext) { originContext = null; context.textContent = 'Selected asset has no reviewed circuit identity. Real circuit journeys remain withheld.'; } ++epoch; pauseMotion(); plan = null; demo = false; select.value = ''; select.disabled = true; removeMap(); controlsState(); report('Explore this asset and the surrounding grid. Nearby assets do n  … [line shortened here: 431 characters; full line on GitHub]
  listen(opener, 'click', () => {returnFocus = opener; opened ? shut() : open();}); listen(close, 'click', shut);
  listen(panel, 'keydown', e => { if (e.key === 'Escape') { e.preventDefault(); shut(); } });
  listen(demoButton, 'click', () => { ++epoch; pauseMotion(); plan = null; removeMap(); demo = true; select.disabled = false; select.replaceChildren(); el('option', 'Choose a reviewed synthetic node…', select, {value: ''}); for (const n of fixture.ledger.nodes) el('option', 'SYNTHETIC ' + n.nodeId, select, {value: n.nodeId}); report('SYNTHETIC DEMONSTRATION LOADED. These are invented assets; choos  … [line shortened here: 453 characters; full line on GitHub]
  listen(realGrid, 'click', event => {
    event.stopPropagation?.();
    const vicinity = W.__GRIDATLAS_MODULES__?.gridVicinity;
    if (!vicinity?.open) {
      const grid = D.getElementById('gridatlas-menu-bar-title-4');
      if (!grid?.click) {
        const layers = D.getElementById('scada-ui-container');
        if (!layers?.scrollIntoView) { report('Grid layers are loading. Try Explore grid again when the map controls appear.'); return; }
        if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
        shut(); layers.scrollIntoView({block: 'start', behavior: 'instant'});
        layers.querySelector?.('input[data-layer-id]')?.focus();
        return;
      }
      if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
      shut();
      if (grid.getAttribute?.('aria-expanded') !== 'true') grid.click();
      grid.focus();
      return;
    }
    pauseMotion(); vicinity.open({origin: originContext?.at ? {...originContext, at: [...originContext.at]} : undefined, radiusKm: 10}); shut();
  });
  listen(select, 'change', choose); listen(next, 'click', advance); listen(reset, 'click', resetPlan);
  listen(start, 'click', () => { if (!plan) return; if (isReduced()) { advance(); return; } playing = true; controlsState(); animate(); });
  listen(pause, 'click', () => { pauseMotion(); controlsState(); });
  listen(W, 'gridatlas:card-open', e => { if (e.detail?.origin) setOrigin(e.detail.origin); else realSelection(); });
  listen(W, 'gridatlas:journey-open', e => open(e.detail));
  installLayerControls();
  if (W.MutationObserver && D.documentElement) { layerObserver = new W.MutationObserver(installLayerControls); layerObserver.observe(D.documentElement, {childList: true, subtree: true}); }
  const styleLoad = () => { pauseMotion(); installMap(); controlsState(); }; map.on('style.load', styleLoad);
  map.on('resize', frameRoute);
  const preferenceChange = () => { if (isReduced()) pauseMotion(); controlsState(); };
  if (media?.addEventListener) { media.addEventListener('change', preferenceChange); on.push(() => media.removeEventListener('change', preferenceChange)); }
  function mapRemoved() { destroy(true); }
  function destroy(mapWasRemoved = false) {
    if (!alive) return; alive = false; ++epoch; pauseMotion();
    try {
      map.off('style.load', styleLoad); map.off('resize', frameRoute); map.off('remove', mapRemoved); for (const off of on.splice(0)) off();
      // MapLibre fires remove AFTER destroying its style. Its layers/sources have already gone.
      if (mapWasRemoved) { ownedLayers.clear(); ownedSources.clear(); } else { removeMap(); if (initialPadding) map.setPadding(initialPadding); }
    } finally { layerObserver?.disconnect(); for (const group of layerGroups) group.remove(); root.remove(); }
  }
  map.on('remove', mapRemoved);
  controlsState();
  return Object.freeze({open, setOrigin, close: shut, snapshot: () => ({alive, opened, playing, step, status: plan?.status || 'withheld', synthetic: demo, origin: originContext ? {...originContext} : null, layerControls: layerGroups.length, steps: plan?.steps.length || 0, edgeCount: plan?.edgeCatalog.length || 0}), destroy});
}

Build

A JavaScript module in the lightning folder of GridAtlas that reads generations, using SHA-256.

storagegridatlas / tools/lightning/build.mjs · lines 1–160 of 160 · Entry point · pattern modulePath (shared by 2 files)

What it does
It loads generations. Defines 7 functions or classes, including sha256, modulePath, readGenerations, sourceFiles, assemble. Uses libraries node:fs, node:path, node:crypto, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
Inputs & outputs
In: JSON file generations.json; command-line arguments.
Downstream impact
Used directly by 3 files: CI PR Gate (gridatlas); Make Generation (gridatlas); Build (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Map Promotion Rehearsal (gridatlas).
What it achieves
It reads generations (`readGenerations`) and is built from the sha256 step (`sha256`) and the module path helper (`modulePath`). Build the UK lightning overlay module (`atlas/modules/` `-uk-lightning-overlay.js`) from its readable source in `tools/lightning/src/`.
Why it matters
Imported by Make Generation and a file of the same name. Run by CI PR Gate.
Application
gridatlas · tools/lightning · JavaScript module
Uses
node:fs, node:path, node:crypto, node:url
Used by
run by CI PR Gate (script call), imported by Make Generation (import), imported by Build (import)
Produces
SRC_DIR, GENERATIONS, modulePath, readGenerations, sourceFiles, assemble, newestModule, check
Defines here
sha256, modulePath, readGenerations, sourceFiles, assemble, newestModule, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/build.mjs:1-160 · blob 454ab0847135e2bc0dcaae7682a09da981b5bbce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
 * Build the UK lightning overlay module (atlas/modules/<GEN>-uk-lightning-overlay.js) from its readable source in
 * tools/lightning/src/. Node built-ins only. docs/LIGHTNING-SOURCE.md explains the source format and how to cut a
 * generation from it.
 *
 *   node tools/lightning/build.mjs --gen 202610290050              # build the variant generations.json names; print size + sha256
 *   node tools/lightning/build.mjs --gen <GEN> --variant m4b --out <file>
 *   node tools/lightning/build.mjs --check                         # the CI check (tools/ci/pr-gate.mjs, "lightning-source")
 *
 * The build is a deterministic text transform, not a minifier. The shipped bytes are the source with its source-only
 * layer taken out, in this order:
 *   1. the files src/*.js are concatenated in file-name order (each must end in "\n"; no CR anywhere);
 *   2. variant blocks: a line `///#if <variant>[,<variant>…]`, an optional `///#else` and `///#endif` (whole lines,
 *      not nested) keep the lines of the branch that names the variant being built and drop the others;
 *   3. every remaining line whose first non-blank characters are `///` is a source-only comment and is dropped;
 *   4. a line that ends in `///` continues on the next line: the three slashes, the line break and the next line's
 *      leading blanks are removed. This is how a long golfed line is laid out readably and stays byte-identical;
 *   5. every `@@GEN@@` becomes the generation stamp (the header comment and `GEN='…'`).
 * Nothing else changes: `//` and `/* … *\/` comments without a third slash ship as they are.
 *
 * --check: the newest lightning generation in atlas/modules/ must be listed in tools/lightning/generations.json, and
 * every listed generation must rebuild from src/ byte for byte (sha256 of the raw bytes, which are LF-only). Exit 1
 * otherwise.
 */
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
export const SRC_DIR = path.join(HERE, 'src');
export const GENERATIONS = path.join(HERE, 'generations.json');
const MODULE_RE = /^(\d{12})-uk-lightning-overlay\.js$/;

const sha256 = buf => createHash('sha256').update(buf).digest('hex');
export const modulePath = gen => path.join(ROOT, 'atlas', 'modules', `${gen}-uk-lightning-overlay.js`);

export function readGenerations(file = GENERATIONS) {
  const j = JSON.parse(fs.readFileSync(file, 'utf8'));
  if (!Array.isArray(j.variants) || !j.variants.length) throw new Error(`${path.relative(ROOT, file)}: "variants" must list the variant names`);
  for (const [g, e] of Object.entries(j.generations || {})) {
    if (!/^\d{12}$/.test(g)) throw new Error(`generations.json: bad generation ${g}`);
    if (!j.variants.includes(e.variant)) throw new Error(`generations.json: ${g} names unknown variant ${e.variant}`);
  }
  return j;
}

/** The source files, in build order. */
export function sourceFiles(srcDir = SRC_DIR) {
  const names = fs.readdirSync(srcDir).filter(n => n.endsWith('.js')).sort();
  if (!names.length) throw new Error(`no *.js in ${srcDir}`);
  return names.map(n => path.join(srcDir, n));
}

/** Assemble the module text for one variant and generation stamp. Throws on any malformed source. */
export function assemble({ variant, gen, variants, srcDir = SRC_DIR }) {
  if (!/^\d{12}$/.test(gen)) throw new Error(`--gen must be YYYYMMDDHHMM, got ${gen}`);
  if (variants && !variants.includes(variant)) throw new Error(`unknown variant ${variant} (known: ${variants.join(', ')})`);
  const lines = [], where = [];
  for (const f of sourceFiles(srcDir)) {
    const t = fs.readFileSync(f, 'utf8');
    if (t.includes('\r')) throw new Error(`${path.basename(f)}: contains CR (the module is LF-only)`);
    if (!t.endsWith('\n')) throw new Error(`${path.basename(f)}: must end with a newline`);
    t.slice(0, -1).split('\n').forEach((l, i) => { lines.push(l); where.push(`${path.basename(f)}:${i + 1}`); });
  }
  const kept = [];
  let block = null; // { on: boolean, seenElse: boolean, line: string }
  lines.forEach((line, i) => {
    const t = line.trimStart(), at = where[i];
    let m;
    if ((m = /^\/\/\/#if ([\w,]+)\s*$/.exec(t))) {
      if (block) throw new Error(`${at}: nested ///#if (block opened at ${block.line})`);
      const names = m[1].split(',');
      for (const n of names) if (variants && !variants.includes(n)) throw new Error(`${at}: ///#if names unknown variant ${n}`);
      block = { on: names.includes(variant), seenElse: false, line: at };
    } else if (/^\/\/\/#else\s*$/.test(t)) {
      if (!block || block.seenElse) throw new Error(`${at}: stray ///#else`);
      block.on = !block.on; block.seenElse = true;
    } else if (/^\/\/\/#endif\s*$/.test(t)) {
      if (!block) throw new Error(`${at}: stray ///#endif`);
      block = null;
    } else if (/^\/\/\/#/.test(t)) {
      throw new Error(`${at}: unknown directive ${t.slice(0, 40)}`);
    } else if (block && !block.on) {
      // the other variant's line
    } else if (t.startsWith('///')) {
      // source-only comment
    } else kept.push(line);
  });
  if (block) throw new Error(`///#if at ${block.line} is never closed`);
  let out = '', cont = false;
  for (const line of kept) {
    const piece = cont ? line.trimStart() : line;
    if (piece.endsWith('///')) { out += piece.slice(0, -3); cont = true; } else { out += piece + '\n'; cont = false; }
  }
  if (cont) throw new Error('the last line ends in a /// continuation');
  if (out.includes('@@') && out.split('@@GEN@@').join('').includes('@@')) throw new Error('a stray @@ placeholder remains');
  return out.split('@@GEN@@').join(gen);
}

/** The newest lightning overlay generation present in atlas/modules/. */
export function newestModule() {
  const gens = fs.readdirSync(path.join(ROOT, 'atlas', 'modules')).map(n => (MODULE_RE.exec(n) || [])[1]).filter(Boolean).sort();
  return gens[gens.length - 1] || null;
}

/** The CI check. Returns { ok, lines }. */
export function check() {
  const lines = [], bad = [];
  let reg;
  try { reg = readGenerations(); } catch (e) { return { ok: false, lines: [`FAIL ${e.message}`] }; }
  const listed = Object.keys(reg.generations || {}).sort();
  const newest = newestModule();
  if (!newest) bad.push('no lightning overlay module in atlas/modules/');
  else if (!listed.includes(newest)) bad.push(`the newest lightning generation ${newest} is not listed in tools/lightning/generations.json: ` +
    'cut it from tools/lightning/src with tools/lightning/make-generation.mjs (docs/LIGHTNING-SOURCE.md)');
  for (const g of listed) {
    const { variant } = reg.generations[g], file = modulePath(g);
    if (!fs.existsSync(file)) { bad.push(`${g}: ${path.relative(ROOT, file)} missing`); continue; }
    const want = fs.readFileSync(file);
    let got;
    try { got = Buffer.from(assemble({ variant, gen: g, variants: reg.variants }), 'utf8'); }
    catch (e) { bad.push(`${g} (${variant}): source does not assemble: ${e.message}`); continue; }
    if (got.equals(want)) lines.push(`ok   ${g} ${variant}: ${want.length} B sha256 ${sha256(want)} rebuilt byte for byte`);
    else {
      let i = 0; while (i < got.length && i < want.length && got[i] === want[i]) i++;
      const lineNo = want.subarray(0, i).toString('utf8').split('\n').length;
      bad.push(`${g} (${variant}): rebuild differs from the committed module at byte ${i} (module line ${lineNo}); ` +
        `built ${got.length} B ${sha256(got).slice(0, 12)}…, committed ${want.length} B ${sha256(want).slice(0, 12)}…`);
    }
  }
  for (const b of bad) lines.push(`FAIL ${b}`);
  return { ok: bad.length === 0, lines };
}

/* ---------------------------------------------------------------- CLI */
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const a = process.argv.slice(2), opt = {};
  for (let i = 0; i < a.length; i++) {
    if (a[i] === '--check') opt.check = true;
    else if (/^--(gen|variant|out)$/.test(a[i]) && a[i + 1] !== undefined) opt[a[i].slice(2)] = a[++i];
    else { console.error(`build.mjs: bad argument ${a[i]}`); process.exit(2); }
  }
  if (opt.check) {
    const r = check();
    for (const l of r.lines) console.log(l);
    process.exit(r.ok ? 0 : 1);
  }
  if (!opt.gen) { console.error('build.mjs: --gen <YYYYMMDDHHMM> or --check is required'); process.exit(2); }
  const reg = readGenerations();
  const variant = opt.variant || (reg.generations[opt.gen] || {}).variant;
  if (!variant) { console.error(`build.mjs: ${opt.gen} is not in generations.json; pass --variant (${reg.variants.join('|')})`); process.exit(2); }
  const buf = Buffer.from(assemble({ variant, gen: opt.gen, variants: reg.variants }), 'utf8');
  if (opt.out) fs.writeFileSync(opt.out, buf);
  const committed = fs.existsSync(modulePath(opt.gen)) ? fs.readFileSync(modulePath(opt.gen)) : null;
  console.log(JSON.stringify({ gen: opt.gen, variant, bytes: buf.length, sha256: sha256(buf), out: opt.out || null,
    matches_committed_module: committed ? committed.equals(buf) : null }));
}

Annotations

A JavaScript module in the lineage folder of GridAtlas that fetches the Renewable Energy Planning Database (REPD) register and substations, using SHA-256.

interactiongridatlas / tools/lightning/lineage/annotations.mjs · lines 1–279 of 279 · Not reached from any entry point (candidate for review)

What it does
It fetches the REPD register and substations. Defines N. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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, substations, 33kV.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Reconstruct (gridatlas).
What it achieves
The source-only layer of `tools/lightning/src`: file sections and `///` comments, anchored to text in the M4 module ('A', variant layers) or, with in:'B', the M4b module (variant dots). Its code works with 33 kV. It responds to change events.
Why it matters
Imported by Reconstruct.
Application
gridatlas · tools/lightning/lineage · JavaScript module
Uses
none found
Used by
imported by Reconstruct (import)
Produces
FILES, NOTES
Defines here
N
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/lineage/annotations.mjs:1-279 · blob 2312d8cdf653223467b8b7cd4fd9fb9face57145 · 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: unreached_review
// annotations.mjs: the source-only layer of tools/lightning/src: file sections and `///` comments, anchored to text in the
// M4 module ('A', variant layers) or, with in:'B', the M4b module (variant dots). Comment text is restored from the
// module's own history (the header and // comments stripped by build-M stage A1/A2 from L3 202610281340, the K
// 202610280950 comments trimmed in L) and from the build scripts that made each change (build-L3, build-M, build-M2,
// build-M3, build-M4, fixes-m4, build-M4b; lane reports named per change).

export const FILES = [
  { name: '00-header.js', at: null, head: `
UK lightning overlay: readable source. Build: node tools/lightning/build.mjs (docs/LIGHTNING-SOURCE.md).
Lines starting with /// (like this one) and the ///#if / ///#else / ///#endif variant blocks are source only; a line
ending in /// continues on the next line. Everything else ships byte for byte in atlas/modules/<GEN>-uk-lightning-overlay.js.
Variants: "layers" (M4 202610290045: the listed technologies' own REPD layers are switched on) and "dots" (M4b
202610290050: only the listed sites are drawn, as REPD-styled dots). @@GEN@@ is the generation stamp.

00 header: the shipped header comments, the IIFE, the aliases and the constants.` },
  { name: '01-helpers.js', at: "ymd=t=>new Date(t).toISOString()", head: `
01 helpers: date and number formatting, GeoJSON guards, the device cap, month arithmetic and the published state S.` },
  { name: '02-transport.js', at: 'note=m=>S.errors.push', head: `
02 transport: fetch for .json (no redirects, 15 s timeout that also covers the body), XMLHttpRequest for the live feed,
and the LRU of day/grid promises.` },
  { name: '03-index.js', at: 'vk=r=>{let n=r&&r.count', head: `
03 archive index v2 (Ventusltd/lightning data/history/index.json): every row validated; coverage from scan_windows.` },
  { name: '04-windows.js', at: 'wf=now=>{', head: `
04 windows and day files: UTC, end-anchored [start,end) windows; hourly or daily shard targets; a 4-wide fan-out.` },
  { name: '05-cells.js', at: "ok=f=>f&&f.type==='Feature'", head: `
05 flashes and cells: feature validation and de-duplication, month grids, the REPD land mask, the cell layer data.` },
  { name: '06-load.js', at: 'ff=async(w,now,reason)=>{', head: `
06 tiers: the live feed (7 days only), the archive overview (cells), the archive detail (points, budgeted).` },
  { name: '07-captions.js', at: 'cf=(r,now)=>{', head: `
07 state and captions: the state machine (cf) and the caption lines (cp). Unknown is never shown as zero.` },
  { name: '08-map.js', at: "mh=()=>{let m=window.__GRIDATLAS_V9_MAP__", head: `
08 map: the map handle, the card position, the cell layers, the point layers and the tap handler.` },
  { name: '09-card.js', at: "cd=(m,x,y,lb,ti,su,de,wh,o={})=>{", head: `
09 card: the docked card (flash, cell or REPD project), the cell card and the short flash ID.` },
  { name: '10-neon.js', at: "NP='gridatlas-lightning-neon'", head: `
10 nearest substations and the camera: the original's own measure drawn as its neon arrival in Lightning-owned layers,
and the framing rules (M2R-layout F1-F3, M2R-camera fix C, M2R-taps T1).` },
  { name: '11-repd-map.js', at: '/* ---- M4b: the listed REPD sites', in: 'B', head: `
11 REPD on the map, per variant: "layers" switches the listed technologies' own REPD layers on through their Layers
checkboxes (M3/M4); "dots" draws only the listed sites as REPD-styled dots and never touches a Layers control (M4b).` },
  { name: '12-repd.js', at: '/* ---- REPD projects near a tap (M2, M3)', head: `
12 REPD projects near a tap (M, M2, M3): the register, the filter chips, the list, the links and the project view.` },
  { name: '13-panel.js', at: 'BTN=(a,t,x)=>', head: `
13 panel: the Layers-panel group (main and fullscreen curtain), its label and status line, and the batched repaint pt.` },
  { name: '14-actions.js', at: 'sp=p=>{S.period=p;', head: `
14 actions: period, navigation, load, the ON/OFF switch, the toggle binding and the HIDE LAYERS clearance.` },
  { name: '15-install.js', at: 'ins=()=>{if(S.installed)return true;', head: `
15 install: after the menu bar, Pipeline News and the map exist; the public NS.ukLightning surface.` },
];

const N = (at, text, opt = {}) => ({ at, text, ...opt });
export const NOTES = [
  // ---------------------------------------------------------------- 00 header
  N('/* uk-lightning-overlay, generation', `
The L3 header, as written before build-M stage A1 shortened it to one line (generation 202610281340):
  EUMETSAT MTG Lightning Imager (L2-LFL) optical flashes, OFF by default, appended last to the original Layers panel
  and fullscreen curtain; no request, source, layer or listener until switched on; never persisted. Optical flashes are
  NOT confirmed ground strikes; a day never searched is unknown, never zero. Above the device cap the window draws as
  tappable ≈10 km cells (data/history/grid) within 30 km of a REPD site.
Rules trimmed from lightning history-window.mjs (data-plane/hourly-lookback-index-v2 @ f7db76c). No engine, Pipeline
News or menu-proxy attribute. Name glossary: docs/lightning/CANDIDATE-202610261949.md.
The shipped header comments below are part of the module bytes (the generation proof reads them).`),
  N("let MX=Math.max", `
Aliases (build-M A3): Math.max/min, Array.isArray, Date.parse (static, no this), appendChild and getBoundingClientRect
helpers, and U, the phrase every unknown count carries. NS is the shared window.__GRIDATLAS_MODULES__ namespace, the only
global this module writes.`),
  N("let GEN='@@GEN@@'", `
Identity and sources. GEN is stamped by the build. AR: the archive (index, days, grid) on Ventusltd/lightning main;
FEED: the 7-day live feed. TMO: the 15 s request timeout; BUDGET: the most points ever drawn; RQ: the most day files per
window (and the LRU size). PERIODS: [key, label, ms] or [key, label, -months]; custom = CUSTOM UTC dates. LONG: periods
that need the archive. COLOUR: status dot colour by state letter (LOADING, PARTIAL, UNKNOWN, BEFORE-ARCHIVE, FAIL).`),

  // ---------------------------------------------------------------- 01 helpers
  N("ymd=t=>new Date(t).toISOString()", `
ymd: UTC date; ds: date -> ms; Q: getElementById; E: throw. T/Ts: UTC minute/second text, 'unknown' if not finite.`),
  N("N=n=>Number(n).toLocaleString('en-GB')", `
N: grouped number; pl: plural; dm/hm/dt: short date, hh:mm, both; du: duration in h/min (LR-words W8: hours grouped);
hz: a window of 48 h or less (hour clip); de: end text; sv: "x of y searched"; lr: when the collector last ran and how far
it searched; F7: the live-feed flash phrase; AGO: age, via du (LR-words W6).`),
  N('ov=(a,b,c,d)=>', `
ov: overlap of [a,b) and [c,d); FC: FeatureCollection; bx: inside the UK box; isFC; tm: a flash's time (Z added when
missing); msg: an error's text, sanitised by cs (LR-security S3).`),
  N("ph=()=>{try{return matchMedia", `
The device point cap: 10,000 on a phone (coarse pointer or <= 700 px), else 40,000. Above it a window draws as cells.`),
  N('mm=(t,k)=>{', `
mm: t minus k calendar months, the day clamped to the target month (3M, 6M, 12M).`),
  N("S={schema:'gridatlas.module.uk-lightning-overlay.v1'", `
State machine (published as NS.ukLightning.state): installed, waiting_for, on, requests, errors, last; period, end and h
(the PREV/NEXT stack of window ends), from/to (CUSTOM), consent (LOAD POINTS), serial (cancels stale loads), idx/ie (index
and its error), res (the drawn result), sfs (the panel groups). lru: url -> {p: promise, sealed}.`),

  // ---------------------------------------------------------------- 02 transport
  N('gj=(u,cache,raw)=>', `
gj: fetch JSON (or bytes with raw) with the 15 s timeout covering the body; a redirect is refused; "HTTP n" on error.
M2 (build-M2 gj-abort): once its own timer has aborted, any rejection (a body stream that errors on abort, as the
bridge's may) is reported as the timeout, not as "Failed to fetch".`),
  N('gx=u=>{S.requests++', `
gx: the live feed by XMLHttpRequest (same timeout; a redirect is refused through responseURL).`),
  N('lg=k=>{if(!lru.has(k))return', `
lg/ls: LRU get and set, at most RQ entries.`),

  // ---------------------------------------------------------------- 03 index
  N('vk=r=>{let n=r&&r.count', `
vk: one index v2 row; parts are hourly days/YYYY/MM/DD/HH.json with integer counts; a bad row throws with its date.`),
  N('ni=raw=>{', `
ni: normalise the index: schema, observation, generated_utc, cutoff and the scan windows; by = date -> row; lost
(shard_lost) days are unknown, never searched.`),
  N('stale=(g,now,f=g)=>', `
stale: the archive last searched more than 4 h ago, or its index is dated more than 15 min after the device clock.`),
  N("li=q=>{if(!S.ip)", `
li: load the index once (q busts the cache after a mismatch); unsealed LRU entries are dropped when it changes.`),
  N('cv=(x,ws,we)=>{', `
cv: coverage of [ws,we) from scan_windows (union): f fraction searched, r runs, a/b first/last scan, d dates, u unknown
dates, l lost days, ny not yet searched (ms at the end), bf before the archive (ms), k known days, pp partly searched days.`),

  // ---------------------------------------------------------------- 04 windows
  N('wf=now=>{', `
wf: the window {s, e, span, atLatest, period, label, clamped, custom}; S.end anchors PREV/NEXT, CUSTOM uses whole UTC dates.`),
  N('tg=(row,ws,we)=>', `
tg: the shard targets of one index row inside the window (a daily file, or the hourly parts that overlap it).`),
  N('sh=(t,date)=>{', `
sh: fetch one day file (the HTTP cache is used only for a sealed day), check schema, date, count, bytes and sha256 against its index row.`),
  N('fr=async(rows,ws,we,sn)=>', `
fr: fan out over the shard targets, 4 at a time, abandoned when S.serial moves on; failures are kept per day.`),

  // ---------------------------------------------------------------- 05 cells
  N("ok=f=>f&&f.type==='Feature'", `
ok: a valid optical-flash Point inside the UK box with a finite time and a scalar id. co: collect the features of the
window, de-duplicated by id (or time and position), sorted by time; a.bad counts the rejected ones.`),
  N("gg=mo=>{if(!/^\\d{4}-\\d\\d$/.test(mo))", `
Cells: month grids grid/YYYY-MM.json (0.1°, per UTC day); a day counts only if coverage, count and sha256 match its index
row. LR-security S1: 2 MB cap, checked on the raw bytes before parsing. The const below stays const: test-engine asserts
its text (build-M A5 KEEP).`),
  N("LM=()=>{if(!LM.a)", `
Land mask: cells whose centre is within 30 km of an onshore REPD site, as run lengths over the 140 x 120 grid; totals keep
every cell. L3 (LR-bugs LRB1) dropped the REPD placeholder 49.766807,-7.55716 (OSGB 0,0): 5,508 -> 5,472 cells. The
const in the loop below stays const (build-M A5 KEEP).`),
  N('gd=async(rows,sn)=>{', `
gd: the cell layer data for the window's known days: n flashes in all cells, k drawn inside the mask, st days not yet in a
grid, e the refused month's reason (LR-bugs LRB3), T the glow floor = max(30, p95 of drawn cells). LRB2: if every grid day
is stale, fall back to the summary.`),

  // ---------------------------------------------------------------- 06 load
  N('ff=async(w,now,reason)=>{', `
ff: the live feed tier (7 days only); reason names why the archive was not used.`),
  N('lw=async(now,sn,q)=>{', `
lw: load a window: the index, then BEFORE-ARCHIVE, overview (cells) or detail (points). Within the device cap, 32 MB and
RQ files, points load for any window; above, cells draw and LOAD POINTS asks first (S.consent). arch counts whole UTC
days above 48 h (LR-bugs LRB4 + LR-numbers F1), J's hour clip at 48 h or less.`),
  N('let got=await fr(tf,w.s,w.e,sn)', `
A sha256 mismatch on an unsealed day means the archive is being rewritten: reload the index once, then say so.`),

  // ---------------------------------------------------------------- 07 captions
  N('cf=(r,now)=>{', `
cf: classify a result: FAIL, BEFORE-ARCHIVE, PARTIAL, UNKNOWN, READY·DETAIL, READY·OVERVIEW or EMPTY, with reasons.`),
  N('DN=r=>{let g=r.gd;', `
DN: the cell caption (LR-words W1 with LRB3's reason): what the map shows, what is counted but not drawn.`),
  N('cp=(r,now,k)=>{', `
cp: the caption lines window, days, actual, flashes, refresh, searched, warning and footer. Every number is either
measured or named unknown; a day never searched is never zero (complexity 82: see reports/V-maintain.md).`),

  // ---------------------------------------------------------------- 08 map
  N("mh=()=>{let m=window.__GRIDATLAS_V9_MAP__", `
mh: the original's MapLibre map (window.__GRIDATLAS_V9_MAP__), or null. sf: the text font the style already uses.`),
  N("HIT=SRC+'-hit'", `
pc: close the card and its neon layers. cs: strip format characters (bidi) and cap at 200 (LR-security). el: element
with inline style and text (DOM: shell classes, inline styles on own nodes only).`),
  N('cpos=()=>{let c=S.pp', `
cpos: dock the card at the bottom of the map like the original's (kv-card), lifted clear of the original's bottom
controls, never over the menu bar. M2R-layout F1 (MAJOR-1): an open card never rises above the container top + 320 px.
M2R-camera fix C (fixes-m4): on a map under 500 px tall with at least 300 px beside the card, the card docks right (c.sd).`),
  N('cx=()=>{let m=mh();pc();', `
cx: remove every Lightning source and layer.`),
  N("CS=SRC+'-cells'", `
Cells: REPD-style graduated core (n <= 3 about 1 px, faint) and a glow for the top 5 %, violet ramp on log10 n
(1/3/10/30/100/300); ids avoid 'l-'. RP: the original's project and substation layers, which win a tap; *glow* layers
never do (LR-taps F3). Cells sit below the original's projects.`),
  N('dw=(fc,cl)=>{', `
dw: one source, a points layer, an invisible 44 px hit layer and (clustered) count labels; hidden until data.`),
  N('tap=e=>{let m=mh();if(!S.on||S.busy', `
tap: a flash (or cluster) under the tap wins, then the nearest cell unless a project or substation of the original is
hit. No work while loading or with no hit layer (LR-regress m2, LR-taps F2). Other click handlers always run.`),
  N("let p=f.properties||{};if(p.cluster){let go=z=>(cm(m)", `
A cluster tap zooms in; cm(m) first drops the module's pending framing (M4, M2R-taps T1).`),
  N("let rq=S.pp&&S.pp.ps&&m.getLayer(NI[13])", `
dots: a tap on a drawn listed site opens that site's project view, as its row does.`, { in: 'B' }),
  N('if(h&&h.length){for(let q of h)S.ly', `
layers: a tap on a drawn REPD dot belongs to the engine and closes the card (as L3); the tapped dot's technology is handed
to the reader and every other layer this module switched on is released (M2R-l3regress MINOR M3-L1, fixes-m4).`),

  // ---------------------------------------------------------------- 09 card
  N("cd=(m,x,y,lb,ti,su,de,wh,o={})=>{", `
cd: the card. lb aria label, ti title, su summary, de detail, wh what was tapped ("optical flash" | "cell centre" |
"project"); o: np (no REPD list: the project view), open, foot, back [label, action], g (dots: the site to draw).
c.re re-opens the same card (for "◀ back"); the title wraps (LR-layout). M2R-layout F3: re-frame on expand, collapse and
minimise. M2R-a11y MAJOR-1: one visually hidden polite status region per card, outside the closed <details>.`),
  N('cb=p=>{let c=p.cell', `
cb: a cell's south-west corner, only for a well-formed cell of the drawn result (LR-security S2: safe-integer n).
cc: the cell card (LR-words W3: "N optical flashes in this ≈10 km cell").`),
  N('sid=s=>{', `
sid: short ID = product sensing window + flash index (W_XX-..._<start>_<end>_N__..._0000:<index>); the full ID stays
in the detail line.`),

  // ---------------------------------------------------------------- 10 neon and camera
  N("NP='gridatlas-lightning-neon'", `
The neon layer and source ids; the REPD ones (p-*) join the set so close, period, LATEST and OFF remove them too (build-M
B1; dots adds p-glow, p-dot and the pdots source).`),
  N('nr=(m,c,x,y)=>{', `
nr: nearest substations: the original's own measure (__GRIDATLAS_NEON_LINKS__.measure.nearestSubstations: >= 33 kV,
<= 40 km, 5 links) drawn as its neon arrival (glow, core, two flow layers, teal nodes, labels, pale origin ring; kv-neon)
in Lightning-owned layers, in the technology colour #d8c96a. link.selectAt is not used: it treats its origin as a project
(stale project reference, cancelled arrivals, a false arrival record; kv-arrival-api). S.fk: the points to frame.`),
  N('if(!c.o.np)Rp(m,c,x,y,M);', `
The REPD list runs for lightning cards only, never in the project view (build-M2 nr-repd).`),
  N("let rm=false;try{rm=matchMedia('(prefers-reduced-motion", `
Flow: the cartridge's own 24 frozen dash patterns (measure.flowDash) when present; off under reduced motion.`),
  N('nf=(m,c,x,y,n)=>{', `
nf: fired on the tap; retried every 2 s (15 times) while the same card is open if the substation list is not loaded yet.
The project view always flies to the project, even with no substation within 40 km (build-M2 nf-fly).`),
  N('cw=()=>Promise.resolve()', `
M4 (M2R-taps MAJOR T1): MapLibre 3.6.2's stop() fires moveend synchronously, so a pending once('moveend', ck) ran its
fitBounds nested inside the next camera move, left an orphan render frame and froze redraws after fast row/back cycles.
cw: the pending framing runs in a microtask after the stop that fired it, only when the map is then not moving.
cm: every module camera move first drops the module's pending framing (nz, ck, RpR, the cluster zoom, the fit button).`),
  N('nz=(m,x,y)=>{try{cm(m)', `
nz: the original arrival's flyTo (zoom 12, 1200 ms), then frame at moveend.`),
  N('ck=f=>{try{let m=mh()', `
ck: frame S.fk when an end is outside the free area (screen pixels: x 20..W-R+20, y T-20..H-B), or always with f === 1
(M2R-layout F2). Padding: top 150, sides 40, bottom card + 24 capped at H-270 only when L3's fit is impossible
(M2R-diff MD1); docked card (c.sd, fix C): top 60, right card width + 32, bottom 100.`),

  // ---------------------------------------------------------------- 12 repd
  N('Rp=(m,c,x,y,M)=>{', `
Rp: the REPD list of a lightning card: every register row is measured once (all 10,784 rows), then RpR renders it.`),
  N('RpR=(m,c,pd,box)=>{', `
RpR: render the list for the current filter (MR3: ties with the 10th site are kept), the summary, the chips, the rows,
the links and the camera. Every filter press re-renders it.`),
  N("let lt=RpU(P.flatMap(g=>g.parts)", `
layers (M3): switch on the listed technologies' layers (Ry), name them on the card.`),
  N("c.ps=P;if(P.length)ap(box", `
dots (M4b): keep the drawn list for dot taps and say what the map shows.`, { in: 'B' }),
  N('RpV=(m,c,g)=>{', `
RpV: the project view of one site (a row or, with dots, a dot tap).`),

  // ---------------------------------------------------------------- 13 panel
  N('BTN=(a,t,x)=>', `
BTN/NAV/DATE: the panel controls, in the shell's own classes. bg: build one panel group (key = main | fs); the menu's
bubble-phase click closer never sees these controls.`),
  N('txt=(n,s)=>', `
txt/flag: write only on change. lt: the Layers label ("Lightning Flashes (Optical) [...]"); sl: the status line.`),
  N('pt=loading=>{', `
pt: one batched repaint of every group: toggle, label, chips, CUSTOM, PREV/NEXT/LATEST, status dot and captions; S.last
is the published summary.`),

  // ---------------------------------------------------------------- 14 actions
  N('sp=p=>{S.period=p;', `
sp: choose a period (resets the PREV/NEXT stack and the LOAD POINTS consent).`),
  N('fb=()=>{let e=S.res&&S.res.ev', `
fb: the fit button: frame every drawn flash (a camera move: cm first).`),
  N('nv=(which,sf)=>{', `
nv: PREV, NEXT, LATEST, FIT, LOAD POINTS and CUSTOM apply. LATEST closes the card and its links (LR-taps F1).`),
  N('ld=refresh=>{', `
ld: load and draw the current window; a newer load (S.serial) or OFF discards this one. The cell layer draws in its own
try, so a failed cell layer never marks the load FAIL (LR-regress m1). A period or page change closes the card.`),
  N('so=on=>{if(S.on===on)return;', `
so: switch ON (first request, map click listener, 10-minute refresh while at LATEST) or OFF (everything removed).`),
  N("bt=c=>c.addEventListener('change'", `
bt: the panel's change listener (toggle). layers: a reader's tick or untick of a layer this module holds makes it the
reader's (the module's own dispatch runs with S.lyx set).`),
  N('fit=()=>{let d=Q(', `
fit: keep Lightning-owned text clear of the shell's fixed HIDE LAYERS button (its live rect + 16 px; 96 px if absent).`),

  // ---------------------------------------------------------------- 15 install
  N('ins=()=>{if(S.installed)return true;', `
ins: install after the menu bar, Pipeline News and the map exist; appended last to the Layers panel and the fullscreen
curtain. Polled every 250 ms and on DOM mutations until it succeeds.`),
  N('NS.ukLightning=Object.freeze(', `
The public surface: schema, generation, state, install, setOn, load, windowFor.`),
];