GLOBALGRID2050 / EXPLORE CODE

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

Arrival Identity Browser and 1 more file

A JavaScript module in the proofs folder of GridAtlas that reads Renewable Energy Planning Database (REPD) and solar. It is built from the proof map class (`ProofMap`).

488 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 648 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. Arrival Identity Browser render · gridatlas / tools/proofs/202609040229-arrival-identity.browser.mjs lines 1–309
  2. PDF Export Outcomes Browser render · gridatlas / tools/proofs/202609051329-pdf-export-outcomes.browser.mjs lines 1–179

Arrival Identity Browser

A JavaScript module in the proofs folder of GridAtlas that reads Renewable Energy Planning Database (REPD) and solar. It is built from the proof map class (`ProofMap`).

rendergridatlas / tools/proofs/202609040229-arrival-identity.browser.mjs · lines 1–309 of 309 · version 2026-09-04 02:29 · Entry point · pattern ProofMap (shared by 3 files)

What it does
It loads REPD and solar. Defines capture, ProofMap. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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: solar.
Inputs & outputs
In: JSON file current.json; JSON file repd_v9_manifest_202608290716.json.
Downstream impact
Used directly by 2 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); GridAtlas Cartridge Proof Workflow (gridatlas).
What it achieves
Defines `capture` and `ProofMap`.
Why it matters
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/. Run by GridAtlas Cartridge Proof Workflow.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:http, node:fs/promises, node:path, node:module, node:url, playwright
Used by
linked from Code Generator — Substation Finder Page (link), run by GridAtlas Cartridge Proof Workflow (workflow run)
Produces
capture, ProofMap
Defines here
capture, ProofMap
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/proofs/202609040229-arrival-identity.browser.mjs:1-309 · blob 2b59b09048dd5996738ba226e7b08a5d1c33f989 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const require = createRequire(import.meta.url);
let playwright;
try {
  playwright = require('playwright');
} catch {
  playwright = require(path.resolve(ROOT, '..', '..', 'gridatlas-v9104-fullscreen',
    'node_modules', 'playwright'));
}
const { chromium } = playwright;
const CURRENT = JSON.parse(await readFile(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const GENERATION = CURRENT.generation;
const VIEWPORT = { width: 393, height: 852 };
const REPD_MANIFEST_URL =
  'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202608290716.json';
const MIME = new Map([
  ['.html', 'text/html; charset=utf-8'], ['.js', 'text/javascript; charset=utf-8'],
  ['.mjs', 'text/javascript; charset=utf-8'], ['.json', 'application/json; charset=utf-8'],
  ['.css', 'text/css; charset=utf-8'], ['.wasm', 'application/wasm'],
  ['.parquet', 'application/octet-stream']
]);

const server = createServer(async (request, response) => {
  try {
    const requestPath = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
    const relative = requestPath.replace(/^\/+/, '') || 'index.html';
    let target = path.resolve(ROOT, relative);
    if (!target.startsWith(`${ROOT}${path.sep}`) && target !== ROOT) {
      response.writeHead(403).end('outside repository');
      return;
    }
    if ((await stat(target)).isDirectory()) target = path.join(target, 'index.html');
    const bytes = await readFile(target);
    response.writeHead(200, {
      'content-type': MIME.get(path.extname(target).toLowerCase())
        || 'application/octet-stream',
      'cache-control': 'no-store', 'access-control-allow-origin': '*'
    });
    response.end(bytes);
  } catch {
    response.writeHead(404).end('not found');
  }
});
await new Promise((resolve, reject) => {
  server.once('error', reject);
  server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address();

const fixtures = [{
  label: 'supplied-point active-register absence', identity: 'NOT_IN_ACTIVE_REGISTER',
  verification: 'NOT_IN_ACTIVE_REGISTER', measures: true,
  query: { repd_ref: '12453', project: 'Thorpe Marsh Power Station - Battery Energy Storage',
    technology: 'bess', capacity_mw: '1450', latitude: '53.5802575',
    longitude: '-1.0850616', zoom: '12' }
}, {
  label: 'ref-only active-register absence', identity: 'NOT_IN_ACTIVE_REGISTER',
  verification: 'NOT_IN_ACTIVE_REGISTER', measures: false,
  query: { repd_ref: '12453' }
}, {
  label: 'failed owner retries to official match', identity: 'RESOLVED',
  verification: null, measures: true, retry: true,
  query: { repd_ref: '12588' }
}, {
  label: 'failed owner retries to active-register absence',
  identity: 'NOT_IN_ACTIVE_REGISTER', verification: 'NOT_IN_ACTIVE_REGISTER',
  measures: false, retry: true, query: { repd_ref: '12453' }
}, {
  label: 'official active-register match', identity: 'RESOLVED',
  verification: 'VERIFIED', measures: true,
  query: { repd_ref: '12588', project: 'Botley West, Botley - Botley West Solar Project',
    technology: 'solar', capacity_mw: '840', latitude: '51.8132088',
    longitude: '-1.3489728', zoom: '12' }
}];
const filter = String(process.env.GRIDATLAS_BROWSER_FIXTURE || '').trim();
const selected = filter ? fixtures.filter(({ label }) => label.includes(filter)) : fixtures;
assert.ok(selected.length, `no fixture matched GRIDATLAS_BROWSER_FIXTURE=${filter}`);

const browser = await chromium.launch({ headless: true });
const receipts = [];
try {
  for (const fixture of selected) {
    const context = await browser.newContext({ viewport: VIEWPORT, isMobile: true,
      hasTouch: true, deviceScaleFactor: 1 });
    const page = await context.newPage();
    const pageErrors = [];
    const consoleErrors = [];
    const requestFailures = [];
    const requests = [];
    let manifestAttempts = 0;
    let beforeRetry = null;
    let inducedFailure = null;
    if (fixture.retry) {
      await page.route(REPD_MANIFEST_URL, async (route) => {
        manifestAttempts += 1;
        if (manifestAttempts === 1) await route.abort('failed');
        else await route.continue();
      });
    }
    page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));
    page.on('console', (message) => {
      if (message.type() === 'error') consoleErrors.push(message.text());
    });
    page.on('request', (request) => requests.push(request.url()));
    page.on('requestfailed', (request) => requestFailures.push({
      url: request.url(), error: request.failure()?.errorText || 'unknown'
    }));
    await page.addInitScript(() => {
      let value;
      const capture = (candidate) => {
        if (!candidate || typeof candidate.Map !== 'function'
            || candidate.Map.__gridatlasProofWrapped) return candidate;
        const OriginalMap = candidate.Map;
        function ProofMap(...args) {
          const instance = Reflect.construct(OriginalMap, args,
            new.target === ProofMap ? OriginalMap : new.target);
          window.__GRIDATLAS_PROOF_MAP__ = instance;
          return instance;
        }
        Object.setPrototypeOf(ProofMap, OriginalMap);
        ProofMap.prototype = OriginalMap.prototype;
        ProofMap.__gridatlasProofWrapped = true;
        candidate.Map = ProofMap;
        return candidate;
      };
      Object.defineProperty(window, 'maplibregl', { configurable: true, enumerable: true,
        get: () => value, set: (candidate) => { value = capture(candidate); } });
    });

    const url = `http://127.0.0.1:${port}/atlas/?${new URLSearchParams(fixture.query)}`;
    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 120_000 });
    await page.waitForFunction((generation) =>
      document.documentElement.dataset.gridatlasGeneration === generation,
    GENERATION, { timeout: 120_000 });
    await page.waitForFunction(() =>
      window.__GRIDATLAS_MODULES__?.menuBar?.installed === true
        && document.querySelectorAll('#gridatlas-menu-bar .gm-title').length === 6
        && window.__GRIDATLAS_PROOF_MAP__, null, { timeout: 120_000 });

    if (fixture.retry) {
      await page.waitForFunction(() =>
        window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'FAILED'
          && document.querySelector('#gridatlas-boot-status button')?.textContent.trim()
            === 'Try again', null, { timeout: 120_000 });
      beforeRetry = await page.evaluate(() => ({
        status: window.__GRIDATLAS_PLACE_SEARCH__.deep_link.status,
        epoch: window.__GRIDATLAS_PLACE_SEARCH__.deep_link.owner_epoch,
        queries: window.__GRIDATLAS_PLACE_SEARCH__.query_count,
        retries: window.__GRIDATLAS_PLACE_SEARCH__.identity_retry_count
      }));
      inducedFailure = { pageErrors: [...pageErrors], consoleErrors: [...consoleErrors],
        requestFailures: [...requestFailures] };
      await page.click('#gridatlas-boot-status button');
      pageErrors.length = 0;
      consoleErrors.length = 0;
      requestFailures.length = 0;
    }

    try {
      await page.waitForFunction(({ identity, verification, measures }) => {
        const owner = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
        const link = window.__GRIDATLAS_NEON_LINKS__;
        return owner?.status === identity
          && (!verification || link?.identity_verification?.status === verification)
          && (measures ? link?.links_drawn > 0 && link?.last_selection?.nearest_km > 0
            : link?.links_drawn === 0
              && /not in the active-register snapshot/u.test(link?.status_message || ''));
      }, { identity: fixture.identity, verification: fixture.verification,
        measures: fixture.measures }, { timeout: 180_000 });
    } catch (error) {
      const diagnostic = await page.evaluate(() => ({
        owner: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link || null,
        query_count: window.__GRIDATLAS_PLACE_SEARCH__?.query_count ?? null,
        retry_count: window.__GRIDATLAS_PLACE_SEARCH__?.identity_retry_count ?? null,
        link: window.__GRIDATLAS_NEON_LINKS__ ? {
          origin: window.__GRIDATLAS_NEON_LINKS__.origin_source || null,
          identity: window.__GRIDATLAS_NEON_LINKS__.identity_verification || null,
          links: window.__GRIDATLAS_NEON_LINKS__.links_drawn,
          selection: window.__GRIDATLAS_NEON_LINKS__.last_selection || null,
          retry: window.__GRIDATLAS_NEON_LINKS__.arrival_retry || null,
          reconciliation: window.__GRIDATLAS_NEON_LINKS__.arrival_reconciliation || null,
          gate: window.__GRIDATLAS_NEON_LINKS__.measure?.arrivalGate?.snapshot?.() || null,
          failures: window.__GRIDATLAS_NEON_LINKS__.failures || []
        } : null,
        status: document.getElementById('gridatlas-boot-status')?.innerText || null
      }));
      throw new Error(`${fixture.label} did not finish: ${JSON.stringify({
        manifestAttempts, diagnostic, pageErrors, consoleErrors, requestFailures
      })}`, { cause: error });
    }

    // Mobile project cards intentionally arrive minimised. Verify the actual
    // reader action before asserting that their measurement text is visible.
    const restore = page.locator('.maplibregl-popup.gridatlas-min .gridatlas-card-bar .min');
    if (fixture.measures && await restore.count()) {
      await restore.tap();
      await page.waitForFunction(() => !document.querySelector('.maplibregl-popup.gridatlas-min'));
    }
    const result = await page.evaluate(() => {
      const state = window.__GRIDATLAS_PLACE_SEARCH__;
      const owner = state.deep_link;
      const link = window.__GRIDATLAS_NEON_LINKS__;
      const popup = document.querySelector('.maplibregl-popup-content');
      const popupText = popup?.innerText.replace(/\s+/g, ' ').trim() || '';
      return {
        runtime_generation: document.documentElement.dataset.gridatlasGeneration,
        owner_generation: state.generation, source_generation: state.source_generation,
        owner, query_count: state.query_count, retry_count: state.identity_retry_count,
        menus: [...document.querySelectorAll('#gridatlas-menu-bar .gm-title')]
          .map((node) => node.textContent.trim()),
        links_drawn: link.links_drawn,
        nearest_km: link.last_selection?.nearest_km ?? null,
        origin_source: link.origin_source || null,
        verification: link.identity_verification || null,
        status_message: link.status_message || null,
        failures: link.failures || [],
        arrival_retry: link.arrival_retry || null,
        reconciliation: link.arrival_reconciliation || null,
        gate: link.measure?.arrivalGate?.snapshot?.() || null,
        popup_text: popupText,
        visible_measurement: /\d+(?:\.\d+)? km straight/u.test(popupText)
      };
    });

    assert.equal(result.runtime_generation, GENERATION);
    assert.equal(result.owner_generation, GENERATION);
    assert.equal(result.source_generation, '202609040229');
    assert.deepEqual(result.menus, ['File', 'Edit', 'View', 'Scope', 'Grid', 'About']);
    assert.equal(result.owner.status, fixture.identity);
    assert.equal(result.owner.repd_ref, fixture.query.repd_ref);
    assert.equal(requests.some((request) => request.includes('/uk_renewables_pipeline/')),
      false, 'legacy wrong-domain Pipeline request was issued');
    if (fixture.retry) {
      assert.equal(beforeRetry.status, 'FAILED');
      assert.equal(beforeRetry.queries, 0);
      assert.equal(beforeRetry.retries, 0);
      assert.equal(result.query_count, 1);
      assert.equal(result.retry_count, 1);
      assert.ok(result.owner.owner_epoch > beforeRetry.epoch);
      assert.equal(result.arrival_retry.owner_epoch, result.owner.owner_epoch);
      assert.equal(result.arrival_retry.measurement_epoch, result.owner.owner_epoch);
      assert.equal(result.reconciliation.epoch, result.owner.owner_epoch);
      assert.equal(result.reconciliation.owner_epoch, result.owner.owner_epoch);
      assert.equal(result.gate.epoch, result.owner.owner_epoch);
      assert.equal(result.arrival_retry.status,
        fixture.identity === 'NOT_IN_ACTIVE_REGISTER'
          ? 'NOT_IN_ACTIVE_REGISTER' : 'RESOLVED');
      assert.ok(manifestAttempts >= 2);
      assert.ok(inducedFailure.consoleErrors.some((message) =>
        /V9 EXACT REPD DEEP LINK/u.test(message)));
    }
    if (fixture.measures) {
      assert.ok(result.links_drawn > 0);
      assert.ok(result.nearest_km > 0);
      assert.equal(result.visible_measurement, true);
    } else {
      assert.equal(result.links_drawn, 0);
      assert.equal(result.nearest_km, null);
      assert.match(result.status_message, /not in the active-register snapshot/u);
      assert.match(result.status_message, /supplies no coordinates/u);
      assert.match(result.status_message, /No official status or location is inferred/u);
    }
    if (fixture.identity === 'NOT_IN_ACTIVE_REGISTER') {
      assert.equal(result.owner.identity_source, 'ARRIVAL_LINK');
      assert.equal(result.owner.official_active_register_match, false);
      assert.equal(result.owner.status_value ?? null, null);
      assert.equal(result.verification.status, 'NOT_IN_ACTIVE_REGISTER');
      if (fixture.measures) {
        assert.equal(result.owner.name, fixture.query.project);
        assert.equal(result.origin_source, 'link-supplied-not-in-active-register');
        assert.match(result.popup_text, /Thorpe Marsh Power Station/u);
        assert.doesNotMatch(result.popup_text, /Revised/u);
      } else {
        assert.equal(result.owner.name, null);
        assert.equal(result.origin_source, 'not-in-active-register-no-supplied-point');
      }
    } else {
      assert.equal(result.owner.identity_source, 'OFFICIAL_ACTIVE_REGISTER');
      assert.equal(result.owner.official_active_register_match, true);
      assert.equal(result.owner.status_value, 'application submitted');
      assert.match(result.popup_text, /Botley West/u);
    }
    assert.deepEqual(result.failures, []);
    assert.deepEqual(pageErrors, []);
    assert.deepEqual(consoleErrors, []);
    const materialFailures = requestFailures.filter(({ url: failedUrl }) =>
      !/basemaps\.cartocdn\.com/u.test(failedUrl));
    assert.deepEqual(materialFailures, []);

    receipts.push({ label: fixture.label, url, manifest_attempts: manifestAttempts,
      induced_failure: inducedFailure, page_errors: pageErrors,
      console_errors: consoleErrors, material_request_failures: materialFailures,
      obsolete_pipeline_requests: requests.filter((request) =>
        request.includes('/uk_renewables_pipeline/')), ...result });
    await context.close();
  }
  console.log(JSON.stringify({ status: 'PASS', generation: GENERATION,
    viewport: VIEWPORT, cases: receipts }, null, 2));
} finally {
  await browser.close();
  await new Promise((resolve) => server.close(resolve));
}

PDF Export Outcomes Browser

A JavaScript module in the proofs folder of GridAtlas. It is built from the check step (`check`).

rendergridatlas / tools/proofs/202609051329-pdf-export-outcomes.browser.mjs · lines 1–179 of 179 · version 2026-09-05 13:29 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines check. Uses libraries playwright, node:fs, node:os, node:path. Side effects: changes the web page (DOM); 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: command-line arguments.
What it achieves
DOES PRESSING "SAVE THIS VIEW AS A PDF" PUT A REAL PDF ON THE READER'S DISK? --------------------------------------------------------------------------- Not "does a function called `savePdf` exist", not "is /DCTDecode present in the source".
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/proofs · JavaScript module
Uses
playwright, node:fs, node:os, node:path
Used by
none found
Produces
check
Defines here
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/proofs/202609051329-pdf-export-outcomes.browser.mjs:1-179 · blob c41357194058ddb65f903373bfb85a3e98787c29 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * DOES PRESSING "SAVE THIS VIEW AS A PDF" PUT A REAL PDF ON THE READER'S DISK?
 * ---------------------------------------------------------------------------
 * Not "does a function called savePdf exist", not "is /DCTDecode present in the
 * source". This drives the actual control in a real browser, waits for the
 * browser's own download event, saves the file, and reads the bytes back.
 *
 * WHY IT EXISTS. On 2026-09-05 the architect opened the print preview in
 * FIREFOX, saw the sheet render correctly, pressed Print with a physical Dell
 * printer selected -- and got no file at all. Every path to a PDF up to that
 * point went through the browser's print pipeline: window.print(), a dialog, a
 * destination, a driver. None of that is ours, and that is the part that
 * failed. #gridatlas-export-pdf writes the bytes itself, so this proof must
 * establish that the bytes are a valid PDF containing the map -- independently
 * of any print dialog.
 *
 * WHAT IT ASSERTS, AND WHY EACH ONE CAN GO RED
 *   - a download event fires at all            (fails if the control refuses)
 *   - the file begins %PDF-1.4 and ends %%EOF  (fails on a truncated writer)
 *   - it carries an image XObject with
 *     /DCTDecode and non-zero dimensions       (fails on a blank capture)
 *   - the embedded stream really is a JPEG,
 *     ffd8 .. ffd9                             (fails if the base64 slice is wrong)
 *   - PAGE aspect equals IMAGE aspect          (fails the moment the sheet
 *                                               letterboxes or crops -- this is
 *                                               the "no white space" assertion)
 *   - the xref offsets resolve                 (fails on a mis-assembled file)
 *
 * The aspect check is the one that matters for the brochure requirement: a page
 * whose ratio differs from the raster's either leaves white bands or crops
 * ground the reader was looking at. Equality to within 0.5% is the only shape
 * that does neither.
 *
 * Three engines, because "it works in Chrome" is not the requirement:
 * "it must be compatible to ALL browsers natively".
 *
 *   node tools/proofs/202609051329-pdf-export-outcomes.browser.mjs <base-url>
 */
import { chromium, firefox, webkit } from 'playwright';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const BASE = process.argv[2];
if (!BASE) {
  console.error('usage: node 202609051329-pdf-export-outcomes.browser.mjs <base-url>');
  process.exit(2);
}
const OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'gridatlas-pdf-proof-'));
const VIEWPORTS = [
  { name: '393x852 phone', width: 393, height: 852 },
  { name: '1400x900 desktop', width: 1400, height: 900 }
];
const ENGINES = [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]];

const results = [];
const check = (name, ok, detail) => {
  results.push({ name, ok: Boolean(ok), detail });
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? `  [${detail}]` : ''}`);
};

for (const [engineName, engine] of ENGINES) {
  const browser = await engine.launch();
  try {
    for (const viewport of VIEWPORTS) {
      const label = `${engineName} ${viewport.name}`;
      const context = await browser.newContext({
        viewport: { width: viewport.width, height: viewport.height },
        acceptDownloads: true
      });
      const page = await context.newPage();
      const pageErrors = [];
      page.on('pageerror', (error) => pageErrors.push(String(error).slice(0, 160)));
      try {
        await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 60000 });
        await page.waitForFunction(() => Boolean(window.__GRIDATLAS_V9_MAP__), null, { timeout: 60000 });
        /* The map must have drawn: a canvas without preserveDrawingBuffer is
           transparent to any reader outside the frame that drew it, so a
           capture taken too early is a legitimately blank one. */
        await page.waitForTimeout(7000);

        /* The owning menu is found by containment, never by the word "File",
           and opened explicitly -- openMenu() is a toggle, so a blind click on
           an already-open panel closes the very thing this needs open. */
        const menu = page.locator('#gridatlas-menu-bar .gm-menu')
          .filter({ has: page.locator('button[data-gm-export]') }).first();
        const alreadyOpen = await menu.evaluate((node) => node.classList.contains('gm-open')).catch(() => false);
        if (!alreadyOpen) await menu.locator('.gm-title').first().click({ timeout: 12000 });
        const menuState = await menu.evaluate((node) => {
          const title = node.querySelector('.gm-title');
          const panel = node.querySelector('.gm-panel');
          return { open: node.classList.contains('gm-open'), expanded: title && title.getAttribute('aria-expanded'), hidden: panel && panel.hidden };
        });
        check(`${label}: the export menu is open before the PDF control is clicked`,
          menuState.open && menuState.expanded === 'true' && menuState.hidden === false,
          `open=${menuState.open} aria-expanded=${menuState.expanded} panel.hidden=${menuState.hidden}`);

        /* Resolved by id. savePdf() REWRITES the button's text on click, so a
           selector that reads its words loses it the moment it is used. */
        /* The download wait is armed BEFORE the click, and its rejection is
           absorbed here rather than left floating. When this proof is run
           against bytes that have no PDF control -- which is exactly how it
           was made to fail first -- the click times out at 15 s and this
           promise then rejects at 30 s with nobody awaiting it. An unhandled
           rejection kills the process, so the file crashed instead of
           reporting FAIL. A proof that cannot report its own failure is the
           defect this whole suite exists to catch. */
        const downloadPromise = page.waitForEvent('download', { timeout: 30000 })
          .catch((error) => ({ failed: String(error).slice(0, 120) }));
        await page.locator('#gridatlas-export-pdf').click({ timeout: 15000 });
        const download = await downloadPromise;
        if (!download || download.failed) throw new Error(download ? download.failed : 'no download event');
        const file = path.join(OUT, `${engineName}-${viewport.width}.pdf`);
        await download.saveAs(file);
        const bytes = fs.readFileSync(file);
        const latin = bytes.toString('latin1');
        check(`${label}: the browser received a download`, bytes.length > 0,
          `${download.suggestedFilename()} ${bytes.length} bytes`);

        check(`${label}: the file is a PDF, opened and closed`,
          latin.startsWith('%PDF-1.4') && latin.trimEnd().endsWith('%%EOF'),
          `head=${JSON.stringify(latin.slice(0, 8))} tail=${JSON.stringify(latin.trimEnd().slice(-6))}`);

        const mediaBox = /\/MediaBox \[0 0 (\d+) (\d+)\]/.exec(latin);
        const image = /\/Subtype \/Image[\s\S]{0,320}?\/Width (\d+)[\s\S]{0,320}?\/Height (\d+)/.exec(latin);
        check(`${label}: the PDF carries a rasterised map, not an empty page`,
          Boolean(image) && latin.includes('/DCTDecode') && Number(image?.[1]) > 0 && Number(image?.[2]) > 0,
          image ? `${image[1]}x${image[2]} /DCTDecode=${latin.includes('/DCTDecode')}` : 'no image XObject');

        /* An image XObject entry could name any bytes. Decode the stream. */
        const stream = /\/Filter \/DCTDecode \/Length (\d+) >>\s*stream\r?\n/.exec(latin);
        let jpegOk = false;
        let jpegDetail = 'no DCTDecode stream';
        if (stream) {
          const start = stream.index + stream[0].length;
          const jpeg = bytes.subarray(start, start + Number(stream[1]));
          jpegOk = jpeg[0] === 0xff && jpeg[1] === 0xd8 && jpeg[jpeg.length - 2] === 0xff && jpeg[jpeg.length - 1] === 0xd9;
          jpegDetail = `${jpeg.length} bytes, ${jpeg.subarray(0, 2).toString('hex')}..${jpeg.subarray(-2).toString('hex')}`;
        }
        check(`${label}: that stream really is a JPEG, start of image to end of image`, jpegOk, jpegDetail);

        /* THE NO-WHITE-SPACE ASSERTION. */
        let aspectOk = false;
        let aspectDetail = 'no MediaBox or no image';
        if (mediaBox && image) {
          const pageAspect = Number(mediaBox[1]) / Number(mediaBox[2]);
          const imageAspect = Number(image[1]) / Number(image[2]);
          aspectOk = Math.abs(pageAspect - imageAspect) / imageAspect < 0.005;
          aspectDetail = `page ${mediaBox[1]}x${mediaBox[2]}pt aspect ${pageAspect.toFixed(4)}`
            + ` vs image ${image[1]}x${image[2]} aspect ${imageAspect.toFixed(4)}`;
        }
        check(`${label}: the page is the shape of the map, so the sheet has no white space and nothing is cropped`,
          aspectOk, aspectDetail);

        const xref = /startxref\s+(\d+)/.exec(latin);
        check(`${label}: the cross-reference table resolves`,
          Boolean(xref) && latin.slice(Number(xref[1]), Number(xref[1]) + 4) === 'xref',
          xref ? `startxref ${xref[1]} -> ${JSON.stringify(latin.slice(Number(xref[1]), Number(xref[1]) + 4))}` : 'no startxref');

        check(`${label}: no page errors while writing the PDF`, pageErrors.length === 0, pageErrors.join(' | '));
      } catch (error) {
        check(`${label}: the PDF export completed`, false, String(error).split('\n')[0].slice(0, 160));
      } finally {
        await context.close();
      }
    }
  } finally {
    await browser.close();
  }
}

fs.rmSync(OUT, { recursive: true, force: true });
const failed = results.filter((entry) => !entry.ok);
console.log(`\n${results.length - failed.length}/${results.length} PDF export outcome checks passed`);
if (failed.length) {
  console.log(`${failed.length} failed:`);
  for (const entry of failed) console.log(`  ${entry.name}  [${entry.detail}]`);
}
process.exit(failed.length ? 1 : 0);