GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/cartridges

Substation Intelligence V9 63 (part 22)

A JavaScript file in the cartridges folder of GridAtlas that maps elizabeth line, using haversine and SHA-256 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: Grid network and substations. Section 393 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. Substation Intelligence V9 63 geodesy · gridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js lines 6875–7574

Substation Intelligence V9 63

A JavaScript file in the cartridges folder of GridAtlas that maps elizabeth line, using haversine and SHA-256 and uses data from the Ventus Grid Engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 4 comment: * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit

geodesygridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js · lines 6875–7574 of 8609 · version 2026-11-18 00:26 (continued from section 383) · pattern switchOn (shared by 4 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 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 4 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Map Removal Test (gridatlas); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Genome Workflow (ventus-grid-engine).
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
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine. Checked by Map Removal Test.
Application
gridatlas · atlas/cartridges · 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
linked from Code Generator — Substation Finder Page (link), referenced by Map Removal Test (new URL import.meta.url), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL), mentioned in Standalone (comment link)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
stopTracks, pixelsFromSource, fromDisplay, screenFrame, bytes, join, pdfString, deflate, screenPdf, printPdf
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:6875-7574 · blob c6f9632fdb6e803baae03a54a542fe508431d153 · 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
   sheet whose bar already carries a 44px close. Two closes, one of them
   unhittable, is worse than one. */
.maplibregl-popup.gridatlas-sheet .maplibregl-popup-close-button{display:none !important}
/* WHEN A CONTROL AND THE ANSWER WANT THE SAME PIXELS, THE ANSWER WINS.
   Four bars printed over the card's text on every load: the tray with the
   GB PRICES and VERSIONS bars (all inside .map-controls at y 698-822), HIDE
   LAYERS at y 796 on z-index 9999, and the credit strip at y 827. None is
   deleted and none goes UNDER the sheet, which would make it unreachable:
   they are lifted clear, still on the map and still 44px. The offset reads
   the same var the sheet is sized from, so the two cannot disagree. */
html.gridatlas-sheet-open .map-controls{
  bottom:calc(var(--gridatlas-sheet-h,56dvh) + 12px) !important;
  max-height:calc(100dvh - var(--gridatlas-sheet-h,56dvh) - 120px) !important;
  overflow-y:auto;overscroll-behavior:contain}
html.gridatlas-sheet-open #gridatlas-dash-toggle{
  bottom:calc(var(--gridatlas-sheet-h,56dvh) + 12px) !important}
/* Not an attribution: the OSM and CARTO credit is .custom-map-attrib at the
   top of the map and does not move. This is a shout-out that was printing
   across the card's sentences. Hidden only while a sheet is open. */
html.gridatlas-sheet-open .podcast-shoutout{display:none !important}`;
  },
  bootStatus(STATUS_ID) {
    return `
#${STATUS_ID}{position:absolute;left:50%;top:14px;transform:translateX(-50%);
  z-index:5;max-width:min(92vw,420px);padding:7px 11px;border-radius:4px;
  background:rgba(6,18,21,.93);border:1px solid #21454b;color:#9fb3ba;
  font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;
  text-align:center;pointer-events:auto}
#${STATUS_ID}[data-kind="failed"]{border-color:#7a4a4a;color:#d0a9a9}
#${STATUS_ID} button{display:block;margin:7px auto 0;padding:4px 12px;
  background:#0a1a1d;border:1px solid #2f6f75;border-radius:3px;color:#bfe9ee;
  font:inherit;text-transform:uppercase;letter-spacing:.06em;cursor:pointer}
#${STATUS_ID} button:hover{border-color:#5fbdc2}
@media (prefers-reduced-motion:no-preference){
  #${STATUS_ID}[data-kind="waiting"]{animation:ga-status-pulse 2.4s ease-in-out infinite}
}
@keyframes ga-status-pulse{0%,100%{opacity:.72}50%{opacity:1}}`;
  },
  versionLedger(LEDGER_ID) {
    return `
#${LEDGER_ID}{margin-top:6px;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
#${LEDGER_ID} > button{display:block;width:100%;padding:6px 8px;background:#0a1a1d;
  border:1px solid #2f6f75;border-radius:3px;color:#8fb3b8;font:inherit;
  letter-spacing:.06em;text-transform:uppercase;cursor:pointer;text-align:left}
#${LEDGER_ID} > button:hover{border-color:#5fbdc2;color:#bfe9ee}
#${LEDGER_ID} .vl-body{display:none;margin-top:5px;padding:8px;border:1px solid #1d3238;
  border-radius:3px;background:rgba(6,18,21,.94);max-width:min(88vw,300px);
  max-height:min(56vh,380px);overflow:auto;overscroll-behavior:contain}
#${LEDGER_ID}[data-open="1"] .vl-body{display:block}
#${LEDGER_ID} .vl-row{padding:4px 0;border-bottom:1px solid #142226}
#${LEDGER_ID} .vl-head{display:flex;justify-content:space-between;gap:8px}
#${LEDGER_ID} .vl-ver{color:#bfe9ee;font-weight:bold}
#${LEDGER_ID} .vl-status{margin-left:5px;color:#ff9b73;font-size:9px;font-weight:bold}
#${LEDGER_ID} .vl-when{color:#5f7a80;font-size:10px}
#${LEDGER_ID} .vl-scope{color:#9fb3ba;font-size:10px;line-height:1.4;margin-top:1px}
#${LEDGER_ID} .vl-reason{color:#df9b83;font-size:9px;line-height:1.35;margin-top:2px}
#${LEDGER_ID} .vl-note{margin:7px 0 0;color:#6f8288;font-size:10px;line-height:1.45}`;
  },
  mobileTray(TRAY_ID) {
    return `
#${TRAY_ID}{display:flex;gap:4px;font:11px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace}
#${TRAY_ID} button{min-height:44px;padding:6px 10px;background:#0a1a1d;
  border:1px solid #2f6f75;border-radius:3px;color:#8fb3b8;font:inherit;
  letter-spacing:.06em;text-transform:uppercase;cursor:pointer}
#${TRAY_ID} button[aria-pressed="true"]{border-color:#5fbdc2;color:#bfe9ee;
  background:rgba(0,255,255,0.08)}
#${TRAY_ID} button[disabled]{opacity:.45;cursor:default}
.map-controls.gm-tools-collapsed > .map-ctrl-btn{display:none}`;
  },
  gbConditions(GB_ID) {
    return `
#${GB_ID}{margin-top:6px;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
#${GB_ID} > button{display:block;width:100%;padding:6px 8px;background:#0a1a1d;
  border:1px solid #2f6f75;border-radius:3px;color:#8fb3b8;font:inherit;
  letter-spacing:.06em;text-transform:uppercase;cursor:pointer;text-align:left}
#${GB_ID} > button:hover{border-color:#5fbdc2;color:#bfe9ee}
#${GB_ID} .gb-body{display:none;margin-top:5px;padding:8px;border:1px solid #1d3238;
  border-radius:3px;background:rgba(6,18,21,.94);max-width:min(88vw,260px);
  max-height:min(52vh,340px);overflow:auto;overscroll-behavior:contain}
#${GB_ID}[data-open="1"] .gb-body{display:block}
#${GB_ID} .gb-row{display:flex;justify-content:space-between;gap:8px;
  padding:2px 0;border-bottom:1px solid #142226}
#${GB_ID} .gb-k{color:#7d8f95}
#${GB_ID} .gb-v{color:#bfe9ee;font-weight:bold}
#${GB_ID} .gb-v em{color:#5f7a80;font-style:normal;font-weight:normal;font-size:10px}
#${GB_ID} .gb-note{margin:7px 0 0;color:#6f8288;font-size:10px;line-height:1.45}
#${GB_ID} .gb-note.gb-point{color:#9fb3ba;border-top:1px solid #142226;padding-top:6px}
#${GB_ID} .gb-note.gb-point b{color:#d8a76a}
#${GB_ID} .gb-more{display:block;margin-top:7px;color:#5fbdc2;font-size:10px;
  text-decoration:none;letter-spacing:.04em}
#${GB_ID} .gb-more:hover{text-decoration:underline}`;
  },
  sldPanel(PANEL_ID) {
    return `
/* Top RIGHT, below the search box. The Atlas keeps its own tool buttons down
   the left edge -- EXPORT CSV, RADIUS SEARCH, ZONE DRAW, MEASURE -- and a
   panel on that side covers them, and the search bar occupies 72-96px inside
   the map container on the right, so the panel clears it at 112px. Both offsets
   were measured on the live map: no headless test catches a collision with a
   component the panel knows nothing about. */
#${PANEL_ID}{position:absolute;right:14px;top:112px;bottom:14px;z-index:11;width:310px;
  max-width:calc(100% - 28px);box-sizing:border-box;overflow:auto;font:11px/1.5 'Courier New',monospace;
  color:#cfe9ee;background:rgba(2,8,11,.93);border:1px solid #0b5f63;border-radius:5px;
  padding:11px 12px;box-shadow:0 0 22px rgba(0,255,255,.14);backdrop-filter:blur(3px);display:none}
#${PANEL_ID}[data-open="true"]{display:block}
#${PANEL_ID} h4{margin:0 0 2px;font-size:10px;letter-spacing:.09em;color:#5fbdc2;text-transform:uppercase;
  display:flex;align-items:center;gap:7px}
#${PANEL_ID} .sld-beta{font-size:8px;padding:1px 4px;border-radius:2px;background:#3a2f12;
  color:#e0b050;border:1px solid #6a5320}
#${PANEL_ID} .sld-site{color:#fff;font-size:12px;font-weight:bold;margin:2px 0 8px;
  overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#${PANEL_ID} h4.sld-drag{cursor:grab;user-select:none;touch-action:none}
#${PANEL_ID} h4.sld-drag:active{cursor:grabbing}
#${PANEL_ID} .sld-min{margin-left:auto}
#${PANEL_ID} .sld-min,#${PANEL_ID} .sld-close{cursor:pointer;background:#050a0d;
  border:1px solid #2f6f75;color:#5fbdc2;font:inherit;font-size:12px;line-height:1;
  min-width:44px;height:44px;border-radius:3px;padding:0 5px}
#${PANEL_ID} .sld-min:hover{color:#bfe9ee;border-color:#5fbdc2}
#${PANEL_ID} .sld-close:hover{color:#ff8f8f;border-color:#ff5d5d}
#${PANEL_ID}[data-min="true"] > *:not(h4){display:none}
#${PANEL_ID}[data-min="true"]{width:auto;padding:7px 9px;
  box-shadow:0 0 14px rgba(95,189,194,.25)}
#${PANEL_ID}[data-min="true"] h4{margin:0}
#${PANEL_ID}[data-min="true"] .sld-min{border-color:#5fbdc2;color:#bfe9ee}
#${PANEL_ID} .sld-to{color:#8b9aa1;font-size:9.5px;margin:-6px 0 8px}
#${PANEL_ID} .sld-target{margin:0 0 9px;padding:7px 8px;border:1px solid #1d3238;
  border-radius:3px;background:#050a0d}
#${PANEL_ID} .sld-target-row{display:flex;justify-content:space-between;align-items:baseline}
#${PANEL_ID} .sld-target-row b{color:#e0b050;font-variant-numeric:tabular-nums}
#${PANEL_ID} .sld-basis{display:flex;align-items:center;gap:6px;margin-top:5px}
#${PANEL_ID} .sld-basis span{color:#8b9aa1;font-size:10px;white-space:nowrap}
#${PANEL_ID} .sld-basis select{flex:1}
#${PANEL_ID} .sld-danger{margin-top:6px;color:#ff5d5d;font-size:9px;line-height:1.5;
  border-left:2px solid #ff5d5d;padding-left:6px}
#${PANEL_ID} .sld-fitted{margin-top:6px;color:#8b9aa1;font-size:9px;line-height:1.5}
#${PANEL_ID} .sld-fitted b{color:#6fb582}
#${PANEL_ID} .sld-fitted b.sld-off{color:#ff5d5d}
#${PANEL_ID} .sld-ratio-note{margin-top:6px;color:#d9b45f;font-size:9px;line-height:1.5;
  border-left:2px solid #8b6c28;padding-left:6px}
#${PANEL_ID} .sld-tabs{display:flex;gap:5px;margin-bottom:8px}
#${PANEL_ID} .sld-tabs button{flex:1;background:#050a0d;border:1px solid #1d3238;color:#7f939a;
  font:inherit;font-size:9px;padding:4px;cursor:pointer;border-radius:3px;text-transform:uppercase}
#${PANEL_ID} .sld-tabs button[data-on="true"]{color:#5fbdc2;border-color:#5fbdc2}
#${PANEL_ID} .sld-grid{display:grid;grid-template-columns:1fr 62px;gap:3px 7px;align-items:center}
#${PANEL_ID} label{color:#8b9aa1;font-size:10px}
#${PANEL_ID} input,#${PANEL_ID} select{width:100%;background:#050a0d;border:1px solid #1d3238;
  color:#d8dee6;font:inherit;font-size:10px;padding:2px 4px;border-radius:2px}
#${PANEL_ID} input:focus,#${PANEL_ID} select:focus{outline:1px solid #5fbdc2}
#${PANEL_ID} .sld-out{margin-top:9px;padding-top:8px;border-top:1px solid #10262b;
  display:grid;grid-template-columns:1fr auto;gap:2px 8px}
#${PANEL_ID} .sld-out b{color:#e0b050;font-variant-numeric:tabular-nums}
#${PANEL_ID} .sld-out .lit{color:#5fbdc2}
#${PANEL_ID} .sld-warn{margin-top:7px;color:#d9963c;font-size:9px;line-height:1.45}
#${PANEL_ID} .sld-caveat{margin-top:7px;padding-top:7px;border-top:1px solid #10262b;
  color:#68797f;font-size:9px;line-height:1.5}
#${PANEL_ID} .sld-caveat b{color:#8b9aa1}
#${PANEL_ID} .sld-hint{margin-top:6px;color:#5f7a80;font-size:9px;line-height:1.45}
#${PANEL_ID} .sld-finance{margin-top:9px;border-top:1px solid #214047;padding-top:7px}
#${PANEL_ID} .sld-finance summary{min-height:32px;display:flex;align-items:center;cursor:pointer;
  color:#d9b45f;font-weight:bold;letter-spacing:.05em;user-select:none}
#${PANEL_ID} .sld-fin-grid{display:grid;grid-template-columns:1fr 76px;gap:3px 7px;align-items:center}
#${PANEL_ID} .sld-fin-section{grid-column:1/-1;margin-top:7px;padding-top:5px;
  border-top:1px solid #10262b;color:#5fbdc2;font-size:9px;text-transform:uppercase}
#${PANEL_ID} .sld-fin-grid input[type="checkbox"]{width:24px;justify-self:end}
#${PANEL_ID} .sld-fin-out{margin:8px 0;padding:7px;background:#050a0d;border:1px solid #1d3238;
  display:grid;grid-template-columns:1fr auto;gap:2px 8px}
#${PANEL_ID} .sld-fin-out b{color:#d9b45f;font-variant-numeric:tabular-nums;text-align:right}
#${PANEL_ID} .sld-fin-note{margin:6px 0;color:#8b9aa1;font-size:9px;line-height:1.5}
@media (max-width:700px){#${PANEL_ID}{width:auto;left:8px;right:8px;top:96px;bottom:8px}}
@media (pointer:coarse){
  #${PANEL_ID} .sld-tabs button,#${PANEL_ID} input,#${PANEL_ID} select,
  #${PANEL_ID} .sld-finance summary{min-height:44px}
}`;
  },
  fullscreenLayers() {
    return `.gridatlas-fs-layers{position:absolute !important;left:0;right:0;bottom:0;
      max-height:42vh;overflow:auto;z-index:9;background:rgba(2,8,11,.94);
      border-top:1px solid #0b5f63;backdrop-filter:blur(3px)}`;
  }
  });
})();

/**
 * TELEPRINT CONTROLS -- GENERATED. DO NOT EDIT THIS FILE.
 *
 * Built by teleprinter/drivers/gridatlas/build-part.mjs from the drivers in
 * that directory, which are where any change belongs. Editing this copy makes
 * the served bytes disagree with the source they claim to come from, and
 * --verify will say so.
 *
 * Two SEPARATE functions, on the architect's instruction:
 *   Print PDF          a picture of the reader's screen, for a person
 *   Print source code  the entire source and its dependencies, for a machine
 *
 * Sources:
 *   screen-frame.js  sha256 18e15c8780df9d6cd16b6bf2841443941ae2ad44222812096aceb6adb237ed8e
 *   print-pdf.js  sha256 c440394609fbd267f3101549d3afccdf275f4089858bb69931d59c692e52b358
 *   print-source-code.js  sha256 8d47ace65048d1874a71e4b8de30f5f5e60a5a58b36e32f289f9063d6a92a34e
 *   gridatlas-wiring.js  sha256 b76b3b8eec0962b0a8f089f5fb53c85fbab5e2f8cc9b92a011b38cdfb82727b5
 */
(function () {
  'use strict';

  /* ---- screen-frame.js (sha256 18e15c8780df9d6c) ---- */
  /**
   * GET THE FRAME THE READER IS LOOKING AT.
   * ---------------------------------------------------------------------------
   * One job, and one refusal.
   *
   * The job: return the pixels currently on the reader's screen, with their real
   * dimensions and a note saying HOW they were obtained.
   *
   * The refusal: this never reconstructs the page. There is a tempting shortcut
   * -- serialise the DOM into an <svg><foreignObject>, draw that to a canvas, and
   * call the result a screenshot. It is not one. It drops cross-origin images,
   * loses most pseudo-elements, cannot see into shadow roots, and silently
   * substitutes fallback fonts. A reader handed that would be looking at a
   * drawing of their screen while being told it was a record of it, which is the
   * one thing a teleprinter must never do. If no honest frame can be had, this
   * throws and the caller says so.
   *
   * TWO SOURCES, IN ORDER, AND THE RECORD ALWAYS NAMES THE ONE USED
   *
   *   'host'     a capture function supplied by the embedder. This exists so a
   *              test harness can hand in the browser's own screenshot and
   *              exercise every downstream byte without a permission chooser --
   *              and so a future native shell can supply a real device grab.
   *
   *   'display'  navigator.mediaDevices.getDisplayMedia({preferCurrentTab:true}).
   *              The compositor's own output: every layer, WebGL and DOM
   *              together, at the resolution the reader is actually looking at.
   *              Costs one permission click. That click is the price of an
   *              honest record and it is worth paying.
   *
   * WHY NOT canvas.toDataURL ALONE. GridAtlas draws its map into a WebGL canvas
   * created without preserveDrawingBuffer, so the drawing buffer is gone by the
   * time anything outside the frame that drew it goes looking. Reading it gives
   * a fully transparent image that encodes to a perfectly valid, perfectly blank
   * PNG. That is the failure that produced white sheets, and it is why a canvas
   * read is a MAP source, never a SCREEN source.
   */

  /** Milliseconds to wait for the capture track to actually produce a frame. */
  const FRAME_TIMEOUT_MS = 10000;

  /* A display track that never paints must not hang the reader's browser
     forever. Chrome will happily keep an unstarted <video> pending, so the wait
     is bounded and the tracks are stopped whatever happens -- an abandoned
     capture leaves the tab's sharing indicator lit, which reads to the reader as
     "this page is still watching my screen". */
  function stopTracks(stream) {
    if (!stream || typeof stream.getTracks !== 'function') return;
    for (const track of stream.getTracks()) {
      try { track.stop(); } catch (_) { /* already stopped */ }
    }
  }

  function pixelsFromSource(source, width, height) {
    if (!width || !height) throw new Error('The captured frame has no size.');
    /* 40 megapixels is about a 8K screen at dpr 2. Past that the RGBA buffer
       alone is 160 MB and the tab is more likely to die than to print. */
    if (width * height > 40000000) {
      throw new Error('The screen is too large to print in one page.');
    }
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const context = canvas.getContext('2d', { willReadFrequently: true });
    if (!context) throw new Error('This browser refused a 2D context.');
    context.drawImage(source, 0, 0, width, height);
    return { width, height, rgba: context.getImageData(0, 0, width, height).data };
  }

  async function fromDisplay() {
    const media = navigator.mediaDevices;
    if (!media || typeof media.getDisplayMedia !== 'function') {
      /* This used to say: take a screenshot and use "Print a screenshot"
         instead. THERE IS NO SUCH CONTROL IN THIS LANE. Telling a reader on the
         one platform where this path fails to go and press a button that does
         not exist is worse than telling them nothing, and it went unnoticed
         because no test reads error strings. Say only what is true. */
      throw new Error('This browser will not let a page capture the screen — '
        + 'iOS Safari does not offer it. Print source code still works here, and '
        + 'it records the screen state.');
    }
    /* preferCurrentTab is Chromium-only and is a HINT: it puts this tab at the
       top of the chooser. Elsewhere the reader picks, which is correct -- their
       screen, their choice. */
    /* ASK FOR THE SCREEN'S REAL RESOLUTION.
       ------------------------------------------------------------------------
       getDisplayMedia hands back whatever size the browser feels like unless it
       is asked, and what it feels like is frequently NOT the reader's pixels. On
       a 393x852 phone viewport at devicePixelRatio 3 -- 1179x2556 real pixels --
       an unconstrained capture came back 786x1704: an effective scale of 2.0
       against a dpr of 3, holding 1.34 of the screen's 3.01 megapixels. FORTY-
       FOUR PERCENT of the record, and the receipt said "1:1" because the PDF
       page equalled the captured image, which it did. The page was 1:1 with the
       capture; the capture was not 1:1 with the screen.

       So the real pixel count is asked for explicitly, and whatever arrives is
       MEASURED against it rather than assumed. */
    const wantWidth = Math.round(window.innerWidth * (window.devicePixelRatio || 1));
    const wantHeight = Math.round(window.innerHeight * (window.devicePixelRatio || 1));
    const stream = await media.getDisplayMedia({
      video: {
        frameRate: 1,
        width: { ideal: wantWidth },
        height: { ideal: wantHeight }
      },
      audio: false,
      preferCurrentTab: true,
      selfBrowserSurface: 'include'
    });
    try {
      /* ImageCapture FIRST, because a <video> is the wrong instrument here.
         ---------------------------------------------------------------------
         Piping the track into a detached <video> and reading videoWidth gave
         786x1704 from a track that declares -- and caps at -- 1179x2556. Waiting
         for the resolution to ramp did not fix it: a video element with no
         layout is handed a reduced frame and keeps being handed one.

         ImageCapture.grabFrame() asks the track for a frame directly and returns
         it at the track's own size, with no element and no layout in the path.
         The <video> route is kept only as a fallback for engines that have no
         ImageCapture. */
      const directTrack = stream.getVideoTracks()[0];
      if (typeof ImageCapture === 'function' && directTrack) {
        try {
          /* RETRY WHILE THE TRACK RAMPS.
             WAIT FOR THE FRAME TO STOP CHANGING, NOT FOR A SIZE IT WILL NEVER
             REACH. The first version of this loop waited until the frame matched
             track.getSettings().width, and the comment it carried -- that the
             track "climbs to its own declared size" -- IS CONTRADICTED BY
             MEASUREMENT. On a display track Chrome reports
             `resizeMode: "crop-and-scale", width: 1179, height: 2556`: those are
             the values that were ASKED FOR, echoed back, not the frames being
             produced. It delivered 786x1704 throughout. So the exit condition was
             unsatisfiable, the loop burned its whole timeout on every print, and
             accepted the first frame anyway. There is no ramp on this track.

             Waiting for stability is the honest version: grab until two
             consecutive frames are the same size, which exits immediately when
             the first frame is already final and still catches a source that
             genuinely does climb. It also removes a five-second stall paid on
             every print whose width is odd -- 2326 never reaches 2327. */
          const capture = new ImageCapture(directTrack);
          let grabbed = await capture.grabFrame();
          const rampEnd = Date.now() + 5000;
          let previousWidth = -1;
          let previousHeight = -1;
          while ((grabbed.width !== previousWidth || grabbed.height !== previousHeight)
            && (grabbed.width < wantWidth || grabbed.height < wantHeight)
            && Date.now() < rampEnd) {
            previousWidth = grabbed.width;
            previousHeight = grabbed.height;
            if (typeof grabbed.close === 'function') grabbed.close();
            await new Promise(resolve => setTimeout(resolve, 200));
            grabbed = await capture.grabFrame();
          }
          try {
            const settings = typeof directTrack.getSettings === 'function'
              ? directTrack.getSettings() : {};
            return {
              ...pixelsFromSource(grabbed, grabbed.width, grabbed.height),
              method: 'display',
              screenWidth: wantWidth,
              screenHeight: wantHeight,
              trackWidth: Number(settings.width) || null,
              trackHeight: Number(settings.height) || null,
              /* BOTH AXES. captureScale was width-only, so a frame that was
                 full width and short in height reported as complete. The receipt
                 now carries the exact pixel counts and a flag that is an INTEGER
                 EQUALITY, not a threshold. */
              captureScale: wantWidth ? grabbed.width / wantWidth : null,
              captureScaleHeight: wantHeight ? grabbed.height / wantHeight : null,
              everyScreenPixel: grabbed.width >= wantWidth && grabbed.height >= wantHeight
            };
          } finally {
            if (typeof grabbed.close === 'function') grabbed.close();
          }
        } catch (_) { /* fall through to the video element */ }
      }
      const video = document.createElement('video');
      video.muted = true;
      video.playsInline = true;
      video.srcObject = stream;
      await video.play();
      await new Promise((resolve, reject) => {
        const timer = setTimeout(
          () => reject(new Error('No screen frame arrived within 10 seconds.')),
          FRAME_TIMEOUT_MS
        );
        /* requestVideoFrameCallback fires on a frame that has actually been
           composited. readyState alone can be satisfied by a track that has
           produced metadata and no picture. */
        if (typeof video.requestVideoFrameCallback === 'function') {
          video.requestVideoFrameCallback(() => { clearTimeout(timer); resolve(); });
        } else {
          const poll = setInterval(() => {
            if (video.videoWidth > 0 && video.readyState >= 2) {
              clearInterval(poll);
              clearTimeout(timer);
              resolve();
            }
          }, 60);
        }
      });
      /* WAIT FOR THE CAPTURE TO REACH ITS OWN FULL SIZE.
         ---------------------------------------------------------------------
         This is where the "44% of the screen" defect actually lived, and it was
         not a browser limit. Probed on 2026-09-05 at a 393x852 viewport, dpr 3:
         the TRACK reports width 1179, height 2556, and getCapabilities gives a
         max of exactly 1179x2556 -- the whole screen, available. But the first
         composited frame arrives smaller and Chrome ramps up over the following
         frames, so a capture taken on the first frame yielded 786x1704 and the
         receipt called it the screen.

         (min and exact constraints cannot be used to force it: Chrome rejects
         both outright on getDisplayMedia -- "min constraints are not supported",
         "exact constraints are not supported". Asking politely and then WAITING
         is the whole technique.)

         So the track's own declared size is the target, and this waits for the
         decoded frame to reach it. If it never does, whatever arrived is used
         and the shortfall is reported rather than hidden. */
      const track = stream.getVideoTracks()[0];
      const declared = track && typeof track.getSettings === 'function'
        ? track.getSettings() : {};
      const targetWidth = Math.max(Number(declared.width) || 0, 0) || wantWidth;
      const targetHeight = Math.max(Number(declared.height) || 0, 0) || wantHeight;
      const rampDeadline = Date.now() + 4000;
      while (video.videoWidth < targetWidth && Date.now() < rampDeadline) {
        await new Promise(resolve => {
          if (typeof video.requestVideoFrameCallback === 'function') {
            video.requestVideoFrameCallback(() => resolve());
            setTimeout(resolve, 200);
          } else {
            setTimeout(resolve, 100);
          }
        });
      }

      const frame = pixelsFromSource(video, video.videoWidth, video.videoHeight);
      video.pause();
      video.srcObject = null;
      return {
        ...frame,
        method: 'display',
        screenWidth: wantWidth,
        screenHeight: wantHeight,
        trackWidth: targetWidth,
        trackHeight: targetHeight,
        /* 1 means the file holds every pixel that was on the screen. Anything
           less is a reduction and must be printed on the receipt as one. */
        captureScale: wantWidth ? frame.width / wantWidth : null,
        captureScaleHeight: wantHeight ? frame.height / wantHeight : null,
        everyScreenPixel: frame.width >= wantWidth && frame.height >= wantHeight
      };
    } finally {
      stopTracks(stream);
    }
  }

  /**
   * @param {object} [options]
   * @param {function} [options.capture] host-supplied capture returning a Blob,
   *        an ImageBitmap, or {width,height,rgba}. Used by the proof harness.
   * @returns {Promise<{width:number,height:number,rgba:Uint8ClampedArray,method:string}>}
   */
  async function screenFrame({ capture } = {}) {
    if (typeof capture === 'function') {
      const supplied = await capture();
      if (supplied && supplied.rgba && supplied.width && supplied.height) {
        return { ...supplied, method: supplied.method || 'host' };
      }
      if (supplied && typeof createImageBitmap === 'function') {
        /* colorSpaceConversion:'none' matters: the browser's image decoder will
           otherwise shift sample values by a level or two on a tagged image, and
           a print engine that claims to preserve pixels must not quietly alter
           them. Codex measured exactly this in WebKit on 2026-09-05. */
        const bitmap = await createImageBitmap(supplied, {
          colorSpaceConversion: 'none',
          premultiplyAlpha: 'none'
        });
        try {
          return { ...pixelsFromSource(bitmap, bitmap.width, bitmap.height), method: 'host' };
        } finally {
          bitmap.close();
        }
      }
      throw new Error('The supplied capture produced nothing usable.');
    }
    return fromDisplay();
  }


  /* ---- print-pdf.js (sha256 c440394609fbd267) ---- */
  /**
   * PRINT PDF -- one PDF unit per captured pixel, and a strip that says where it
   * came from.
   * ---------------------------------------------------------------------------
   * This is the FIRST of the two Teleprinter functions and it is entirely
   * separate from the second. It answers "give me what is on my screen as a
   * file". It knows nothing about source code.
   *
   * NO PAPER. The page box is exactly the captured raster's width, and its
   * height is the raster plus one provenance strip. Not A4, not A3, not "the
   * long edge scaled to 1190pt" -- that last one was real, it shipped, and on a
   * 1390x518 desktop capture it emitted a 1190x443 page: a 14% REDUCTION of the
   * record presented as the record. "THE PRINT MUST BE HIGH RES OF WHAT THE USER
   * SEES NOT A REDUCED CRAP VERSION". "WE ARE NOT USING PAPER".
   *
   * WHY FLATE AND RAW RGB RATHER THAN JPEG. JPEG is lossy, and a lossy record is
   * an edited one: text in the layer panel and the thin 400 kV lines are exactly
   * the content its ringing artefacts damage most. /FlateDecode over raw RGB
   * samples is bit-exact, so the bytes in the file ARE the bytes that were on
   * the screen, and a reviewer can say so rather than hope so.
   *
   * WHY THE STRIP IS OUTSIDE THE IMAGE. The furniture used to be painted over
   * the map. It covered the menu bar at the top and the legend at the bottom,
   * and on a real sheet it truncated the generation stamp to "generation
   * 202609051211 - 2026-09-". The record must not be written on. So the page is
   * made taller than the capture and the strip lives in the space that adds:
   * every pixel of the reader's screen survives untouched, and the provenance is
   * still on the sheet. "I like the headers and footers thats nice ... KEEP
   * THAT".
   */

  const encoder = new TextEncoder();
  const bytes = (text) => encoder.encode(text);

  function join(parts) {
    let length = 0;
    for (const part of parts) length += part.length;
    const out = new Uint8Array(length);
    let at = 0;
    for (const part of parts) { out.set(part, at); at += part.length; }
    return out;
  }

  /* PDF strings are parenthesised, so a literal parenthesis or backslash in a
     project name would end the string early and corrupt every object offset
     after it. Non-ASCII is dropped rather than guessed at: WinAnsi is not UTF-8
     and a mojibake stamp is worse than a plain one. */
  function pdfString(text) {
    return String(text == null ? '' : text)
      .replace(/[\\()]/g, '\\$&')
      .replace(/[^\x20-\x7e]/g, '');
  }

  async function deflate(data) {
    if (typeof CompressionStream !== 'function') {
      throw new Error('This browser cannot compress the page.');
    }
    const stream = new Blob([data]).stream().pipeThrough(new CompressionStream('deflate'));
    return new Uint8Array(await new Response(stream).arrayBuffer());
  }

  /**
   * Build a one-page PDF whose page is the capture plus a provenance strip.
   *
   * @param {{width:number,height:number,rgba:Uint8ClampedArray}} frame
   * @param {{brand?:string,title?:string,url?:string,stamp?:string,credit?:string,method?:string}} [note]
   */
  async function screenPdf(frame, note = {}) {
    const { width, height, rgba } = frame || {};
    if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height)
        || width < 1 || height < 1) {
      throw new Error('The captured frame has invalid dimensions.');
    }
    if (!rgba || rgba.length !== width * height * 4) {
      throw new Error('The captured frame has the wrong number of samples.');
    }

    /* The strip scales with the record, not with an assumed sheet: a 2514px-tall
       phone capture and a 518px-tall desktop one both need a legible credit, and
       a fixed 9pt is illegible on one and enormous on the other. */
    const unit = Math.max(1, Math.min(width, height) / 900);
    const headSize = Math.max(9, Math.round(13 * unit));
    const footSize = Math.max(7, Math.round(9 * unit));
    const pad = Math.max(10, Math.round(14 * unit));
    const strip = headSize + footSize + pad * 2 + Math.round(pad * 0.6);
    const pageH = height + strip;

    const rgb = new Uint8Array(width * height * 3);
    for (let i = 0, o = 0; i < rgba.length; i += 4, o += 3) {
      rgb[o] = rgba[i]; rgb[o + 1] = rgba[i + 1]; rgb[o + 2] = rgba[i + 2];
    }
    const image = await deflate(rgb);

    const heading = pdfString(note.title || 'GlobalGrid2050 · Grid Atlas');
    const brand = pdfString(note.brand || 'VENTUS · GLOBALGRID2050 · GRID ATLAS');
    const left = pdfString(note.credit || '');
    const right = pdfString([note.stamp, note.method && ('capture: ' + note.method)]
      .filter(Boolean).join('  ·  '));
    const link = pdfString(note.url || '');

    /* The image is placed at y=strip so the strip occupies the BOTTOM of the
       page, below the record, in PDF's origin-at-bottom-left space. */
    const content = [
      'q', `${width} 0 0 ${height} 0 ${strip} cm`, '/Screen Do', 'Q',
      'q', '0.016 0.039 0.047 rg', `0 0 ${width} ${strip} re f`, 'Q',
      `BT /F1 ${headSize} Tf 1 1 1 rg ${pad} ${strip - pad - headSize + Math.round(headSize * 0.25)} Td (${brand}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${pad} ${Math.round(pad * 0.9) + footSize} Td (${heading}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55)} Td (${link}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55) + footSize + 2} Td (${left}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${Math.max(pad, width - pad - right.length * footSize * 0.52)} ${Math.round(pad * 0.9) + footSize} Td (${right}) Tj ET`
    ].join('\n');
    const contentBytes = await deflate(bytes(content));

    const objects = [
      bytes('<< /Type /Catalog /Pages 2 0 R >>'),
      bytes('<< /Type /Pages /Kids [3 0 R] /Count 1 >>'),
      bytes(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${width} ${pageH}] `
        + '/Resources << /XObject << /Screen 5 0 R >> /Font << /F1 6 0 R >> >> '
        + '/Contents 4 0 R >>'),
      join([bytes(`<< /Length ${contentBytes.length} /Filter /FlateDecode >>\nstream\n`),
        contentBytes, bytes('\nendstream')]),
      join([bytes('<< /Type /XObject /Subtype /Image '
        + `/Width ${width} /Height ${height} /ColorSpace /DeviceRGB `
        + '/BitsPerComponent 8 /Interpolate false /Filter /FlateDecode '
        + `/Length ${image.length} >>\nstream\n`), image, bytes('\nendstream')]),
      bytes('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>')
    ];

    const chunks = [bytes('%PDF-1.4\n')];
    const offsets = [];
    let at = chunks[0].length;
    objects.forEach((body, index) => {
      offsets.push(at);
      const piece = join([bytes(`${index + 1} 0 obj\n`), body, bytes('\nendobj\n')]);
      chunks.push(piece);
      at += piece.length;
    });
    let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
    for (const offset of offsets) xref += String(offset).padStart(10, '0') + ' 00000 n \n';
    chunks.push(bytes(xref + `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\n`
      + `startxref\n${at}\n%%EOF\n`));

    return { bytes: join(chunks), pageWidth: width, pageHeight: pageH, strip };
  }

  /**
   * Capture the screen and put a PDF of it on the reader's disk.
   *
   * Separate from printSourceCode() on purpose: one produces a picture of the
   * screen, the other produces text for a machine to read, and conflating them
   * gives a reader a file that is bad at both.
   */
  async function printPdf({ capture, note = {}, filename } = {}) {
    const frame = await screenFrame({ capture });
    const built = await screenPdf(frame, { ...note, method: frame.method });
    const blob = new Blob([built.bytes], { type: 'application/pdf' });
    const name = filename
      || `gridatlas-screen-${new Date().toISOString().replace(/[:.]/g, '-')}.pdf`;
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name;
    link.rel = 'noopener';
    document.body.appendChild(link);
    link.click();
    /* Revoking immediately races the browser's own fetch of the blob on some
       builds; 30 s is long enough for any of them and short enough that a reader
       printing repeatedly does not accumulate them. */
    setTimeout(() => {
      URL.revokeObjectURL(url);
      if (link.parentNode) link.parentNode.removeChild(link);
    }, 30000);
    return {
      method: frame.method,
      width: frame.width,
      height: frame.height,
      /* Carried out so the caller can tell the reader the truth about what the
         file holds rather than repeating a "1:1" that describes only the
         relationship between the page and the image inside it. */
      screenWidth: frame.screenWidth || null,
      screenHeight: frame.screenHeight || null,
      captureScale: typeof frame.captureScale === 'number' ? frame.captureScale : null,
      captureScaleHeight: typeof frame.captureScaleHeight === 'number' ? frame.captureScaleHeight : null,
      everyScreenPixel: frame.everyScreenPixel === true,
      pageWidth: built.pageWidth,
      pageHeight: built.pageHeight,
      bytes: built.bytes.length,
      filename: name
    };
  }


  /* ---- print-source-code.js (sha256 8d47ace65048d187) ---- */
  /**
   * PRINT SOURCE CODE -- the entire source and its dependencies, as the browser
   * actually has them, in one plain text file an AI can read.
   * ---------------------------------------------------------------------------
   * This is the SECOND Teleprinter function and it shares nothing with the
   * first. Print PDF makes a picture of the screen for a person. This makes text
   * for a machine: "the ENTIRE SOURCE CODE AND DEPENDENCIES IN THE BROWSER FOR
   * AI REVIEW", so a reader on a phone can attach one file in ChatGPT and get a
   * real answer about the thing they are looking at.
   *