GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

G203 Regional Native Viewport (part 6)

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 582 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. G203 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 3901–4600

G203 Regional Native Viewport

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: 99% of its lines are the same as atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.987 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 7645828021ee561333c34c0ecaad2b46bd87029ca9101601714d7e520bb680b1
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g203-regional-native-viewport.js · lines 3901–4600 of 8664 (continued from section 576) · pattern regionalEligible (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 241 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. 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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 1 file: G203 Swarm 06 Viewport Lifecycle Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Checked by G203 Swarm 06 Viewport Lifecycle Test.
Application
gridatlas · atlas/modules · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
referenced by G203 Swarm 06 Viewport Lifecycle Test (new URL import.meta.url)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
band, count, byPair, boundaries, pin, url, encode, digestBytes, digestHex, verify, forCable, array, cleanText, layerKey, layerLabel, layerGroup, inventory, required, installStyle
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/modules/g203-regional-native-viewport.js:3901-4600 · blob 013cf98a02bb6c09199c357ac96a2b588892c0f4 · 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
        .filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);

      const nodes = nodeNames.map((name) => ({
        node: name,
        voltage_kv: graph.nodeVoltageKv(name),
        transmission_owner: ownerOfNode(name) || UNKNOWN
      }));

      /* Assets are counted once per site even when both ends are here,
         and grouped under the declared voltage of the node they were
         first met at in sorted node order. */
      const seen = new Set();
      const bands = new Map();
      const boundary_circuits = [];
      const boundary_transformers = [];
      const undetermined = [];
      const asset_owner_differs = [];

      function band(kv) {
        const k = bandKey(kv);
        if (!bands.has(k)) {
          bands.set(k, { voltage_kv: kv, by_owner: {}, circuits: 0, transformers: 0, nodes: 0 });
        }
        return bands.get(k);
      }
      function count(b, owner, what) {
        const o = owner || UNKNOWN;
        if (!b.by_owner[o]) b.by_owner[o] = { nodes: 0, circuits: 0, transformers: 0 };
        b.by_owner[o][what] += 1;
        b[what] += 1;
      }

      for (const n of nodes) count(band(n.voltage_kv), n.transmission_owner, 'nodes');

      for (const nodeName of nodeNames) {
        for (const entry of graph.edgesAt(nodeName)) {
          if (seen.has(entry.row)) continue;
          seen.add(entry.row);
          const d = describe(entry, nodeName);
          const b = band(d.from_voltage_kv);
          count(b, d.asset_owner === UNKNOWN ? null : d.asset_owner,
            entry.kind === 'circuit' ? 'circuits' : 'transformers');
          if (d.ends === 'boundary') {
            (entry.kind === 'circuit' ? boundary_circuits : boundary_transformers).push(d);
          } else if (d.ends === 'undetermined') {
            undetermined.push(d);
          }
          if (d.asset_owner_matches_an_end === false) asset_owner_differs.push(d);
        }
      }

      const by_voltage = [...bands.entries()]
        .sort((a, b) => {
          if (a[0] === UNDECLARED) return 1;
          if (b[0] === UNDECLARED) return -1;
          return Number(b[0]) - Number(a[0]);
        })
        .map(([, b]) => b);

      const owners = new Set();
      for (const b of by_voltage) for (const o of Object.keys(b.by_owner)) owners.add(o);

      const byPair = (list) => list.sort((a, b) =>
        String(a.from_node).localeCompare(String(b.from_node))
        || String(a.to_node).localeCompare(String(b.to_node)));

      return {
        schema: SCHEMA,
        source: ACCEPTS,
        site: {
          code: site.code,
          name: site.name,
          transmission_owner: asString(site.transmission_owner) || UNKNOWN
        },
        requested_voltage_kv: voltageKv,
        scope: voltageKv == null
          ? 'every node of this site, counted within its own declared voltage; '
            + 'no count here spans two voltages'
          : 'nodes this site declares at ' + voltageKv + ' kV only',
        nodes,
        by_voltage,
        owners_present: [...owners].sort(),
        boundary_circuits: byPair(boundary_circuits),
        boundary_transformers: byPair(boundary_transformers),
        undetermined: byPair(undetermined),
        asset_owner_differs_from_both_ends: byPair(asset_owner_differs),
        counts: {
          nodes: nodes.length,
          nodes_with_unknown_owner: nodes.filter((n) => n.transmission_owner === UNKNOWN).length,
          owners_present: owners.size,
          circuits: by_voltage.reduce((s, b) => s + b.circuits, 0),
          transformers: by_voltage.reduce((s, b) => s + b.transformers, 0),
          boundary_circuits: boundary_circuits.length,
          boundary_transformers: boundary_transformers.length,
          undetermined: undetermined.length,
          asset_owner_differs_from_both_ends: asset_owner_differs.length
        },
        not_a_counterparty: NOT_A_COUNTERPARTY,
        never_inferred: NEVER_INFERRED,
        not_an_assessment: NOT_AN_ASSESSMENT
      };
    }

    /**
     * Every boundary branch in the product, each reported once, with both
     * owners named. The seam between the networks as a list.
     */
    function boundaries() {
      const out = [];
      const seen = new Set();
      const pairs = {};
      for (const [kind, rows] of [['circuit', product.circuits], ['transformer', product.transformers]]) {
        for (const row of rows || []) {
          if (!row || seen.has(row)) continue;
          seen.add(row);
          const d = describe({ kind, row, near: 'node_1', far: 'node_2' }, row.node_1);
          if (d.ends !== 'boundary') continue;
          out.push(d);
          const pair = [d.from_owner, d.to_owner].sort().join('/');
          pairs[pair] = (pairs[pair] || 0) + 1;
        }
      }
      return {
        schema: SCHEMA,
        source: ACCEPTS,
        branches: out.sort((a, b) =>
          String(a.from_node).localeCompare(String(b.from_node))
          || String(a.to_node).localeCompare(String(b.to_node))),
        counts: {
          boundary_circuits: out.filter((d) => d.kind === 'circuit').length,
          boundary_transformers: out.filter((d) => d.kind === 'transformer').length,
          by_owner_pair: pairs
        },
        not_a_counterparty: NOT_A_COUNTERPARTY,
        never_inferred: NEVER_INFERRED,
        not_an_assessment: NOT_AN_ASSESSMENT
      };
    }

    const ownerTally = {};
    for (const node of product.nodes || []) {
      const o = (node && asString(node.transmission_owner)) || UNKNOWN;
      ownerTally[o] = (ownerTally[o] || 0) + 1;
    }

    return {
      schema: SCHEMA,
      source: ACCEPTS,
      counts: {
        nodes: nodeOwner.size,
        nodes_by_owner: ownerTally
      },
      site: base.site,
      at,
      boundaries
    };
  }

  NS.ownerBoundary = Object.freeze({
    schema: SCHEMA,
    accepts: ACCEPTS,
    requires: REQUIRES,
    unknown: UNKNOWN,
    not_a_counterparty: NOT_A_COUNTERPARTY,
    never_inferred: NEVER_INFERRED,
    not_an_assessment: NOT_AN_ASSESSMENT,
    index
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   pinned-products - the runtime data this Atlas reads, by commit and by digest
   ══════════════════════════════════════════════════════════════════════

   A published Atlas release is immutable. Three of its runtime fetches were
   not: they named a BRANCH.

     data-grid-gb        main/derived/connection-points.v3.json
     data-grid-gb        main/derived/gb-transmission-network.v1.json
     data-gb-electricity main/derived/price-decade-rollup.json

   The only defence was a schema string, and a schema string defends SHAPE
   and is blind to VALUES. On 2026-09-03 that stopped being theoretical. A
   correction on data-grid-gb - branch codex/20260903-phase0-integrity,
   commit b91e45b - publishes deduplicated transformer counts under the
   IDENTICAL schema `data-grid-gb.connection-points.v3`:

     COWLEY   transformers  10 -> 5
     ABHAM    transformers   4 -> 2
     located                502 -> 489     (886 points either way)

   Every record in the file differs. A factor of two on a number the card
   prints, invisible to every check the consumer had. An immutable release
   would have changed what it said with none of its own bytes changing.

   So the ref is a commit and the bytes are hashed. The NESO inputs upstream
   are pinned by SHA-256 with exactly this rationale - document ids are
   stable and "latest" links are not - and the discipline simply had not
   reached the estate's own last hop.

   MOVING A PIN IS A CUT, AND THAT IS THE POINT. A data correction and a map
   release become one event a reader can see. It is also a real cost: the
   correction above does NOT reach a reader until the pin moves here. That is
   the right trade, because the alternative is not knowing which of the two
   numbers is on the card - and this file is where a human decides.

   This module lives in the substation-intelligence cartridge, which the
   shell evaluates before the sandbox, so both consumers read one table
   rather than each carrying its own copy of the constants and the digest
   arithmetic.
   ══════════════════════════════════════════════════════════════════════ */
(() => {
  'use strict';

  const SCHEMA = 'gridatlas.module.pinned-products.v1';
  const RAW = 'https://raw.githubusercontent.com/Ventusltd/';

  /* Each entry: the repository, the 40-character commit the Atlas was built
     against, the path, and the SHA-256 of the bytes served at that commit.
     `bytes` is recorded beside the digest because a truncated response is
     the failure mode a digest catches last and a length catches first. */
  const PINS = {
    'connection-points.v3': {
      repository: 'data-grid-gb',
      ref: '1c9909d1138704b29235c27fd769436dda8a0b18',
      path: 'derived/connection-points.v3.json',
      sha256: '11e28859a6d17cc8ee4047c2032d55d043be98f7123743f3b2b03225e07a4c0c',
      bytes: 2896561,
      schema: 'data-grid-gb.connection-points.v3'
    },
    'gb-transmission-network.v1': {
      repository: 'data-grid-gb',
      ref: '1c9909d1138704b29235c27fd769436dda8a0b18',
      path: 'derived/gb-transmission-network.v1.json',
      sha256: 'fc331cc20b061f85adf18d890762a164328a1c5e84acef6a23d35d36f849fc8a',
      bytes: 10069966,
      schema: 'data-grid-gb.transmission-network.v1'
    },
    'price-decade-rollup': {
      repository: 'data-gb-electricity',
      ref: 'd310e3cec8cd14bc7cd3eef1e37037197bcb0798',
      path: 'derived/price-decade-rollup.json',
      sha256: '18da5059c93cf09f6036bfcaabf56afaedf16d5f03e664c3cf0b0cff1dca970d',
      bytes: 6873,
      schema: 'data-gb-electricity.price-decade-rollup.v2'
    }
  };

  function pin(id) {
    return Object.prototype.hasOwnProperty.call(PINS, id) ? PINS[id] : null;
  }

  function url(id) {
    const entry = pin(id);
    return entry ? RAW + entry.repository + '/' + entry.ref + '/' + entry.path : null;
  }

  /* Absent crypto is NOT a mismatch.
     ------------------------------------------------------------------
     `crypto.subtle` exists only in a secure context, so a page served over
     plain http - a local check-out, a preview server - has no digest to
     offer. That is reported as unverified and the product is still read.
     Only a real disagreement between the bytes and the recorded digest
     refuses, because refusing on absence would make the Atlas unusable
     anywhere but production while proving nothing about the bytes. */
  function encode(text) {
    try {
      return typeof TextEncoder === 'function'
        ? new TextEncoder().encode(text) : null;
    } catch (_) { return null; }
  }

  async function digestBytes(bytes) {
    try {
      const subtle = (window.crypto || {}).subtle;
      if (!subtle || !bytes) return null;
      const digest = await subtle.digest('SHA-256', bytes);
      return Array.from(new Uint8Array(digest))
        .map(byte => byte.toString(16).padStart(2, '0')).join('');
    } catch (_) {
      /* A thrown digest is an unavailable digest, not a wrong one. */
      return null;
    }
  }

  async function digestHex(text) {
    return digestBytes(encode(text));
  }

  /**
   * @returns { state, sha256, expected, ref, bytes_seen, bytes_expected }
   *   state is 'verified', 'MISMATCH', or a stated reason it is unverified.
   *   Only 'MISMATCH' means the caller must refuse.
   *
   * `bytes_seen` is BYTES. The first cut of this module reported
   * `text.length`, which is UTF-16 code units: the node/branch product is
   * 10,069,964 characters and 10,069,966 bytes, so the field disagreed with
   * the `bytes` it was being compared against by two, on a file that was
   * entirely correct. A length is checked as well as a digest because
   * truncation is the failure a length names immediately and a digest only
   * says "different" about.
   */
  async function verify(id, text) {
    const entry = pin(id);
    const bytes = encode(text);
    const seen = bytes ? bytes.length : null;
    if (!entry) {
      return { state: 'unverified: no pin for ' + String(id), sha256: null,
        expected: null, ref: null, bytes_seen: seen, bytes_expected: null };
    }
    const digest = await digestBytes(bytes);
    const answer = { sha256: digest, expected: entry.sha256, ref: entry.ref,
      bytes_seen: seen, bytes_expected: entry.bytes };
    if (seen !== null && seen !== entry.bytes) {
      answer.state = 'MISMATCH';
      answer.detail = 'the response at ' + entry.ref + ' is ' + seen
        + ' bytes, not the recorded ' + entry.bytes;
    } else if (digest === null) {
      answer.state = 'unverified: no subtle crypto in this context';
    } else if (digest === entry.sha256) {
      answer.state = 'verified';
    } else {
      answer.state = 'MISMATCH';
      answer.detail = 'bytes at ' + entry.ref + ' hash to ' + digest
        + ', not the recorded ' + entry.sha256;
    }
    return answer;
  }

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  NS.pinnedProducts = Object.freeze({
    schema: SCHEMA,
    ids: Object.freeze(Object.keys(PINS)),
    pin,
    url,
    digestHex,
    verify,
    why: 'A branch ref lets an immutable release change what it says without '
      + 'any of its own bytes changing. The schema string defends shape and is '
      + 'blind to values: a correction to data-grid-gb halves published '
      + 'transformer counts under the same schema. The ref is a commit and the '
      + 'bytes are hashed, so a data correction and a map release are one event.',
    not_an_assessment: 'A pin says which bytes were read. It says nothing '
      + 'about whether those bytes are right.'
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   version-ledger - what every generation of this Atlas changed
   ══════════════════════════════════════════════════════════════════════

   The page shows its own version history (202609010204, v9.40), and the cut
   writes the newest row rather than a human appending it (202609012130,
   v9.65, after v9.64 shipped a ledger whose newest entry named v9.63 and so
   told a reader it was running the generation before the one it was running).

   It lived in the sandbox body. That is 13,655 characters of pure data in the
   cartridge with the least room: the sandbox stood at 339,367 characters
   against the 340,000 guard its own proof asserts, and every cut adds another
   row. Three card-facing changes could not be made without either raising
   that guard - which v9.76 considered and rejected, and so did every cut
   tonight - or moving something out.

   So it moves to the cartridge that has room, exactly as the five network
   modules did at v9.76. The shell evaluates substation-intelligence before
   the sandbox, so the sandbox reads it the same way it reads geodesy.

   The array literal below keeps its exact original spelling, because that
   spelling is what tools/recompose.mjs matches when it appends a row at the
   cut. Naming it here in full would be matched too - and was: the first
   version of this comment quoted the declaration, recompose found the comment
   before it found the data, and tried to JSON.parse this sentence. A comment
   that a tool reads is code. The
   appending happens for the parts of every RESTAMPED cartridge, and every cut
   in this repository restamps both - the sandbox proof derives the generation
   from its own filename and holds the manifest to it, so a cut that skipped
   the sandbox would fail three identity checks. If one ever did skip it, the
   ledger would stop growing silently; the check that its newest row is the
   composed version is what would catch that, and it is asserted against
   atlas/current.json rather than against a string in the same file.
   ══════════════════════════════════════════════════════════════════════ */
(() => {
  'use strict';

  const VERSION_LEDGER = [{"g":"202608312121","v":"v9.16","s":"the project arriving from Pipeline News is visible: its own technology layer is enabled and a pin owned by this cartridge is dropped on it, with a toggle on the card"},{"g":"202608312133","v":"v9.17","s":"central AC sizing: the limiting nameplate, not a squared product"},{"g":"202608312140","v":"v9.18","s":"the project marker is a ring  … [line shortened here: 24,969 characters; full line on GitHub]

  const REJECTED_PRE_PROMOTION = Object.freeze({
    '202609040021': 'never live: the mobile project card could cover the engine layer panel',
    '202609040046': 'never live: its generation proof reported 748/755',
    '202609040047': 'never live: a late identity could restore an arrival after a user selection or clear'
  });
  for (const entry of VERSION_LEDGER) {
    if (!REJECTED_PRE_PROMOTION[entry.g]) continue;
    entry.status = 'REJECTED_PRE_PROMOTION';
    entry.reason = REJECTED_PRE_PROMOTION[entry.g];
  }

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  NS.versionLedger = Object.freeze({
    schema: 'gridatlas.module.version-ledger.v1',
    entries: VERSION_LEDGER,
    written_by: 'tools/recompose.mjs, at the cut, never by hand',
    not_an_assessment: 'A ledger row says what a generation changed. It does '
      + 'not say the change was right, and nothing here grades one.'
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   corridor-estimate - a straight line is not a route, and this says how far off
   ══════════════════════════════════════════════════════════════════════

   Every distance this Atlas prints is a great-circle distance between two
   points. No cable is ever laid that way. The question a reader actually has
   is how much longer the built thing would be, and until now the card said
   nothing at all about it.

   THE SCALAR, AND WHAT IT WAS MEASURED ON.

   Route factor 1.245, calibrated against the published built lengths of GB
   transmission CABLE circuits in the operator's own node/branch model:

     median absolute error   8.45%
     within 15%              73% of circuits
     sample                  95 circuits spanning 59 DISTINCT SITE PAIRS

   The sample is 59, not 95. Parallel circuits between the same two sites
   duplicate the geometry exactly, so quoting 95 would be counting the same
   measurement up to four times and claiming a precision the data has not got.

   WHAT IT IS NOT FOR.

   Not overhead line. The measured OHL factor is 1.13, and it is a different
   number for a physical reason rather than a statistical one: a tower line
   crosses open country in long straight spans, while a cable follows the
   highway network, its bends and its wayleaves. Applying a cable factor to an
   overhead question would overstate the route by about ten per cent and would
   be the wrong model regardless of the error.

   Not below about a kilometre. Where the two ends are under 1 km apart the
   site-centroid resolution dominates the geometry: in that band the median
   published length is 0.59 km against a median error of 52.5%, which is not
   the route factor being wrong, it is the straight line not being a
   measurement of anything at that scale. Those separations are refused rather
   than scaled.

   It is a screening estimate for a corridor. It is not a connection offer, a
   constructability assessment or a consenting design, and the caveat below
   travels with every number this module produces.
   ══════════════════════════════════════════════════════════════════════ */
(() => {
  'use strict';

  const SCHEMA = 'gridatlas.module.corridor-estimate.v1';

  const CABLE_FACTOR = 1.245;
  const OHL_FACTOR = 1.13;
  const MINIMUM_KM = 1;

  const BASIS = Object.freeze({
    factor: CABLE_FACTOR,
    median_absolute_error_pct: 8.45,
    within_15_pct: 73,
    circuits: 95,
    distinct_site_pairs: 59,
    source: 'published built lengths of GB transmission cable circuits',
    sample_note: 'parallel circuits between the same two sites duplicate the '
      + 'geometry, so the sample is 59 distinct site pairs and not 95 circuits',
    minimum_separation_km: MINIMUM_KM,
    below_minimum: 'under about a kilometre the site-centroid resolution '
      + 'dominates: median published length 0.59 km against a median error of '
      + '52.5%, so a straight line between centroids is not measuring route '
      + 'factor and no estimate is offered'
  });

  const CAVEAT = 'Indicative highway-corridor screening only. Not a connection '
    + 'offer, not a constructability assessment and not a consenting design.';

  const NOT_FOR_OVERHEAD = 'Calibrated on cable circuits, which follow the '
    + 'highway network. Overhead line crosses open country and measures 1.13; '
    + 'this factor is not applied to an overhead-line question.';

  /**
   * The corridor estimate for a CABLE route of `km` straight-line distance.
   * @returns null when there is nothing honest to say - no distance, or a
   *   separation short enough that the straight line is not measuring
   *   route factor. Null is the answer, not zero.
   */
  function forCable(km) {
    const straight = Number(km);
    if (!Number.isFinite(straight) || straight <= 0) return null;
    if (straight < MINIMUM_KM) {
      return { km: null, factor: CABLE_FACTOR, straight_km: straight,
        withheld: BASIS.below_minimum };
    }
    return {
      km: straight * CABLE_FACTOR,
      factor: CABLE_FACTOR,
      straight_km: straight,
      withheld: null
    };
  }

  /* Deliberately no forOverhead(). A module that offered one would be used,
     and the 1.13 above is published here so a reader can see WHY the cable
     factor is not the answer to that question - not so that this cartridge
     can start answering it. */

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  NS.corridorEstimate = Object.freeze({
    schema: SCHEMA,
    factor: CABLE_FACTOR,
    overhead_factor: OHL_FACTOR,
    minimum_km: MINIMUM_KM,
    basis: BASIS,
    caveat: CAVEAT,
    not_for_overhead: NOT_FOR_OVERHEAD,
    forCable,
    not_an_assessment: 'An estimated corridor length says nothing about '
      + 'whether a connection is available, consentable or affordable.'
  });
})();

/* GridAtlas menu bar.

   v9.94 proved that the conventional menu is the right shape and the wrong
   implementation can still strand the product. That version enumerated only
   direct children of .map-controls and then hid the whole owner container.
   Scope, Clear and their result surfaces were nested, so they disappeared.

   This successor has a stricter admission rule:

   - it installs nothing until the engine's 60 layer controls and the three
     Pipeline News controls are all present and uniquely identified;
   - the Grid menu proxies those 63 ORIGINAL inputs, so their delegated engine
     handlers remain the only implementation of behaviour;
   - action buttons are moved as the same DOM nodes, preserving listeners and
     state, while result panels stay with the map that owns them;
   - legacy containers collapse only after the complete inventory is built.
     A missing control leaves the old interface reachable and is published as
     a failure instead of being silently skipped.

   The six names are the architect's current vocabulary. In particular Grid
   is not exposed through the abandoned "Select layers" alias. */
(function gridAtlasMenuBar() {
  'use strict';

  if (typeof window === 'undefined' || typeof document === 'undefined') return;

  var SCHEMA = 'gridatlas.menu-bar.v2';
  var BAR_ID = 'gridatlas-menu-bar';
  var STYLE_ID = BAR_ID + '-css';
  var FAILURE_ID = BAR_ID + '-failure';
  var MENUS = ['File', 'Edit', 'View', 'Scope', 'Grid', 'About'];
  var EXPECTED_ENGINE_LAYERS = 61;
  var EXPECTED_PIPELINE_LAYERS = 3;
  var EXPECTED_LAYER_CONTROLS = 64;
  var MAX_TRIES = 160;             // 40 s: the register UI is built after map load

  var NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.menuBar && NS.menuBar.schema === SCHEMA) return;

  var state = {
    schema: SCHEMA,
    menus: MENUS.slice(),
    bar_id: BAR_ID,
    installed: false,
    controls_moved: 0,
    layer_controls: 0,
    engine_layer_controls: 0,
    pipeline_layer_controls: 0,
    expected_layer_controls: EXPECTED_LAYER_CONTROLS,
    panel_counts: {},
    failure: null,
    tries: 0,
    listeners: 0,
    closed_at_rest: true,
    one_identity_surface: false
  };
  NS.menuBar = state;

  var bar = null;
  var panels = {};
  var titles = [];
  var layerTargets = Object.create(null);
  var layerProxies = Object.create(null);
  var forwardingLayerChoice = false;
  var observer = null;
  var timer = null;
  var brandSlot = null;    // holds the v8 .hud-header (VENTUS wordmark), fused into the bar itself
  var gridHead = null;     // holds the v8 .scada-brand + .status-legend, restored at the top of Grid
  var gridBody = null;     // holds the layer groups, so gridHead never enters the 2-column flow

  function array(value) {
    return Array.prototype.slice.call(value || []);
  }

  function cleanText(value) {
    return String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
  }

  function layerKey(input) {
    if (!input || !input.getAttribute) return '';
    var engine = input.getAttribute('data-layer-id');
    if (engine) return 'engine:' + engine;
    var pipeline = input.getAttribute('data-pn-layer');
    return pipeline ? 'pipeline:' + pipeline : '';
  }

  function layerLabel(input) {
    var label = input && input.closest ? input.closest('label') : null;
    var span = label && label.querySelector
      ? label.querySelector('[data-base-label], [data-pn-label], span') : null;
    var base = span && span.getAttribute ? span.getAttribute('data-base-label') : '';
    /* The V8 panel exposes WAIT/LOAD/OK/FAIL beside every layer.  The first
       menu implementation preferred data-base-label, which deliberately
       strips that live suffix.  That made a successful load and a failed
       load indistinguishable in the only layer surface left on a phone. */
    var text = cleanText((span && span.textContent) || base
      || (label && label.textContent) || layerKey(input).split(':').slice(1).join(':'));
    return text || layerKey(input);
  }

  function layerGroup(input) {
    var group = input && input.closest ? input.closest('.key-group') : null;
    var title = group && group.querySelector ? group.querySelector('.key-title') : null;
    return cleanText(title && title.textContent) || 'Other layers';
  }

  function inventory(doc) {
    var host = doc.getElementById('scada-ui-container');
    var engine = host ? array(host.querySelectorAll(
      'input[type="checkbox"][data-layer-id]')) : [];
    var pipeline = host ? array(host.querySelectorAll(
      'input[type="checkbox"][data-pn-layer]')) : [];
    var controls = engine.concat(pipeline);
    var keys = controls.map(layerKey);
    var unique = new Set(keys);
    return {
      host: host,
      engine: engine,
      pipeline: pipeline,
      controls: controls,
      keys: keys,
      complete: engine.length === EXPECTED_ENGINE_LAYERS
        && pipeline.length === EXPECTED_PIPELINE_LAYERS
        && controls.length === EXPECTED_LAYER_CONTROLS
        && unique.has('engine:ukpn_secondary')
        && unique.size === EXPECTED_LAYER_CONTROLS
        && !keys.includes('')
    };
  }

  state.inspect = function () {
    var found = inventory(document);
    return {
      engine: found.engine.length,
      pipeline: found.pipeline.length,
      total: found.controls.length,
      unique: new Set(found.keys).size,
      complete: found.complete
    };
  };

  function required(doc) {
    var found = inventory(doc);
    var nodes = {
      host: doc.querySelector('.map-container'),
      stack: doc.querySelector('.map-controls'),
      search: doc.querySelector('.search-bar-wrapper'),
      header: doc.querySelector('.hud-header'),
      exportButton: doc.getElementById('btn-export'),
      statusButton: doc.getElementById('btn-status'),
      fullscreenButton: doc.getElementById('btn-fullscreen'),
      radiusButton: doc.getElementById('btn-radius'),
      radiusAreaButton: doc.getElementById('btn-radius-area'),
      zoneButton: doc.getElementById('btn-zonedraw'),
      measureButton: doc.getElementById('btn-measure')
    };
    var missing = Object.keys(nodes).filter(function (key) { return !nodes[key]; });
    if (!found.complete) missing.push('63 unique layer controls');
    return { found: found, nodes: nodes, missing: missing };
  }

  function installStyle(doc) {
    if (doc.getElementById(STYLE_ID)) return;
    var style = doc.createElement('style');
    style.id = STYLE_ID;
    style.textContent = [
      '#' + BAR_ID + '{position:absolute;top:0;left:0;right:0;height:36px;z-index:10020;',
      'display:flex;align-items:stretch;gap:0;padding-left:env(safe-area-inset-left);',
      'padding-right:env(safe-area-inset-right);box-sizing:border-box;',
      'background:rgba(4,10,13,.95);border-bottom:1px solid rgba(80,220,240,.3);',
      'font:11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;',
      '-webkit-backdrop-filter:blur(7px);backdrop-filter:blur(7px);',
      'isolation:isolate;pointer-events:auto}',
      '#' + BAR_ID + ' .gm-menu{position:relative;min-width:0}',
      '#' + BAR_ID + ' .gm-title{appearance:none;border:0;background:transparent;color:#cfeef6;',
      'min-height:36px;padding:0 11px;cursor:pointer;font:inherit;letter-spacing:.05em;',
      'text-transform:uppercase;white-space:nowrap}',
      '#' + BAR_ID + ' .gm-title:hover,#' + BAR_ID + ' .gm-title:focus-visible,',