GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / uk_renewables_pipeline/202609051156/tests

Browser Smoke V8 1 and 3 more files

A JavaScript module in the tests folder of GlobalGrid2050 that tests major project news, projects plugin, the Renewable Energy Planning Database (REPD) register and wind.

561 lines of JavaScript from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 921 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. Browser Smoke V8 1 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v8_1.mjs lines 1–230
  2. Browser Smoke V9 1 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_1.mjs lines 1–40
  3. Browser Smoke V9 2 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_2.mjs lines 1–76
  4. Browser Smoke V9 3 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_3.mjs lines 1–215

Browser Smoke V8 1

A JavaScript module in the tests folder of GlobalGrid2050 that tests major project news, projects plugin, the Renewable Energy Planning Database (REPD) register and wind.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v8_1.mjs · lines 1–230 of 230 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review) · pattern preparePage (shared by 7 files)

What it does
It tests major project news, projects plugin, the REPD register and wind. Defines 7 functions or classes, including preparePage, serveFrozenNews, waitForMvp, assertGaugeValues, assertSearch. Uses libraries node:assert/strict, node:fs, node:module, node:url, node:path. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, wind.
Inputs & outputs
In: JSON file major_project_news_v5.json; JSON file projects-plugin.v7.2.json.
What it achieves
It prepares page (`preparePage`), serves frozen news (`serveFrozenNews`) and reads download (`readDownload`). Defines `preparePage`, `serveFrozenNews`, `waitForMvp` and 3 more.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:fs, node:module, node:url, node:path, playwright
Used by
mentioned in Standalone (comment link)
Produces
preparePage, serveFrozenNews, waitForMvp, assertGaugeValues, assertSearch, readDownload, main
Defines here
preparePage, serveFrozenNews, waitForMvp, assertGaugeValues, assertSearch, readDownload, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v8_1.mjs:1-230 · blob 8afe0d38e786808b9c5e8714e569094c1dc22d85 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from "node:assert/strict";
import fs from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import path from "node:path";

const require = createRequire(import.meta.url);
const { chromium } = require("playwright");
const testDirectory = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(testDirectory, "../../..");
const v8Root = path.resolve(testDirectory, "..");
const newsBody = fs.readFileSync(path.join(repoRoot, "dist/major_project_news_v5.json"));
const projectContract = JSON.parse(fs.readFileSync(
  path.join(v8Root, "contracts/projects-plugin.v7.2.json"),
  "utf8",
));
const expectedCsvHeader = projectContract.interface.export.columns
  .map(({ label }) => `"${label.replaceAll('"', '""')}"`)
  .join(",");
const baseUrl = process.env.V8_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v8/";

async function preparePage(browser, viewport = { width: 1440, height: 1000 }) {
  const context = await browser.newContext({ viewport });
  const page = await context.newPage();
  await page.addInitScript(() => {
    window.Chart = class ChartV81Stub {
      constructor(_canvas, config) {
        this.data = config.data;
      }

      update() {}
    };
  });
  await page.route("https://cdn.jsdelivr.net/npm/chart.js", (route) => route.fulfill({
    status: 200,
    contentType: "application/javascript",
    body: "",
  }));
  return { context, page };
}

async function serveFrozenNews(page) {
  await page.route("**/dist/major_project_news_v5.json*", (route) => route.fulfill({
    status: 200,
    contentType: "application/json",
    body: newsBody,
  }));
  await page.route("https://raw.githubusercontent.com/**", (route) => route.fulfill({
    status: 200,
    contentType: "application/json",
    body: newsBody,
  }));
}

async function waitForMvp(page) {
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 766);
  await page.waitForFunction(() => document.querySelectorAll("#stories .story").length === 125);
}

async function assertGaugeValues(page, expected) {
  const actual = await Promise.all(["#v1", "#v2", "#v3", "#v4"].map(
    (selector) => page.locator(selector).textContent(),
  ));
  assert.deepEqual(actual, expected);
}

async function assertSearch(page, query, count, patterns = []) {
  await page.locator("#search").fill(query);
  assert.equal(await page.locator("#tbody tr").count(), count, `search ${query}`);
  const text = await page.locator("#tbody").textContent();
  patterns.forEach((pattern) => assert.match(text, pattern, `search ${query} contains ${pattern}`));
}

async function readDownload(download) {
  const downloadPath = await download.path();
  assert.ok(downloadPath, "download path is available");
  return fs.readFileSync(downloadPath);
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  try {
    const { context, page } = await preparePage(browser);
    const pageErrors = [];
    page.on("pageerror", (error) => pageErrors.push(error.message));
    await serveFrozenNews(page);
    await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
    await waitForMvp(page);

    assert.equal(await page.locator("#tbody tr").count(), 766);
    assert.equal(await page.locator("#stories .story").count(), 125);
    assert.match(await page.locator("#newsMeta").textContent(), /^125 headlines · 559 eligible projects/);
    assert.match(await page.locator(".strap").textContent(), /Legacy V5 newspaper · project bindings unverified/i);
    await assertGaugeValues(page, ["34,073.49", "106,338.18", "766", "1,450"]);

    assert.equal(await page.locator('[data-technology="wind"]').count(), 0);
    assert.deepEqual(
      await page.locator("#tech [data-technology]").evaluateAll((buttons) => (
        buttons.map((button) => button.dataset.technology)
      )),
      ["all", "solar", "bess"],
    );
    assert.equal(await page.locator("#tbody .badge").filter({ hasText: /wind/i }).count(), 0);

    await page.locator('[data-technology="solar"]').click();
    assert.equal(await page.locator("#tbody tr").count(), 384);
    await assertGaugeValues(page, ["34,073.49", "0", "384", "840"]);

    await page.locator('[data-technology="bess"]').click();
    assert.equal(await page.locator("#tbody tr").count(), 382);
    await assertGaugeValues(page, ["0", "106,338.18", "382", "1,450"]);

    await page.locator('[data-technology="all"]').click();
    await assertSearch(page, "Beacon Fen", 2, [/Beacon Fen Energy Park/, /13599/, /13600/]);
    await assertSearch(page, "13599", 1, [
      /Beacon Fen Energy Park/,
      /GG2050-REPD-13599/,
      /EN010151/,
    ]);
    await assertSearch(page, "GG2050-REPD-13600", 1, [
      /Beacon Fen Energy Park/,
      /13600/,
      /EN010151/,
    ]);
    await assertSearch(page, "GG2050-DEV-E13842D4D80DEC", 2, [/13599/, /13600/]);
    await assertSearch(page, "EN010151", 2, [/13599/, /13600/]);
    await page.locator("#search").fill("");
    assert.equal(await page.locator("#tbody tr").count(), 766);

    const fullDownloadPromise = page.waitForEvent("download");
    await page.locator("#export").click();
    const fullDownload = await fullDownloadPromise;
    assert.match(
      fullDownload.suggestedFilename(),
      /^globalgrid2050_uk_renewables_pipeline_v8_1_\d{4}-\d{2}-\d{2}\.csv$/,
    );
    const fullBytes = await readDownload(fullDownload);
    assert.deepEqual([...fullBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf]);
    const fullCsv = fullBytes.toString("utf8", 3);
    const fullLines = fullCsv.split("\r\n");
    assert.equal(fullLines[0], expectedCsvHeader);
    assert.equal(fullLines.length, 767, "CSV has one header and 766 canonical records");

    await page.locator("#search").fill("NO SUCH CANONICAL PROJECT 8C66E56A");
    assert.equal(await page.locator("#tbody tr").count(), 0);
    await assertGaugeValues(page, ["0", "0", "0", "0"]);
    const emptyDownloadPromise = page.waitForEvent("download");
    await page.locator("#export").click();
    const emptyDownload = await emptyDownloadPromise;
    assert.match(
      emptyDownload.suggestedFilename(),
      /^globalgrid2050_uk_renewables_pipeline_v8_1_\d{4}-\d{2}-\d{2}\.csv$/,
    );
    const emptyBytes = await readDownload(emptyDownload);
    assert.deepEqual([...emptyBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf]);
    assert.equal(emptyBytes.toString("utf8", 3), expectedCsvHeader);
    await page.locator("#search").fill("");
    assert.equal(await page.locator("#tbody tr").count(), 766);

    for (const width of [390, 768]) {
      await page.setViewportSize({ width, height: 844 });
      const mobile = await page.evaluate(() => {
        const selectors = [".main", ".header", ".status", ".newspaper", ".gauges", ".tablewrap"];
        const bounds = Object.fromEntries(selectors.map((selector) => {
          const rect = document.querySelector(selector).getBoundingClientRect();
          return [selector, { left: rect.left, right: rect.right }];
        }));
        const tableWrap = document.querySelector(".tablewrap");
        return {
          bodyDisplay: getComputedStyle(document.body).display,
          storyColumns: getComputedStyle(document.querySelector(".stories")).gridTemplateColumns.split(" ").length,
          gaugeColumns: getComputedStyle(document.querySelector(".gauges")).gridTemplateColumns.split(" ").length,
          searchWidth: Math.round(document.querySelector("#search").getBoundingClientRect().width),
          clientWidth: document.documentElement.clientWidth,
          scrollWidth: document.documentElement.scrollWidth,
          internalTableOverflow: tableWrap.scrollWidth > tableWrap.clientWidth,
          bounds,
        };
      });
      assert.equal(mobile.bodyDisplay, "block", `${width}px body layout`);
      assert.equal(mobile.storyColumns, 1, `${width}px story columns`);
      assert.equal(mobile.gaugeColumns, 1, `${width}px gauge columns`);
      assert.ok(mobile.searchWidth >= width - 24, `${width}px search width`);
      assert.ok(mobile.internalTableOverflow, `${width}px wide table is contained by its own scroller`);
      assert.ok(
        mobile.scrollWidth <= mobile.clientWidth,
        `${width}px document overflow: ${mobile.scrollWidth}px > ${mobile.clientWidth}px`,
      );
      for (const [selector, bounds] of Object.entries(mobile.bounds)) {
        assert.ok(bounds.left >= -0.5, `${width}px ${selector} crosses left edge`);
        assert.ok(bounds.right <= width + 0.5, `${width}px ${selector} crosses right edge`);
      }
    }
    assert.deepEqual(pageErrors, []);
    await context.close();

    const newsFailure = await preparePage(browser);
    await newsFailure.page.route("**/dist/major_project_news_v5.json*", (route) => route.abort());
    await newsFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
    await newsFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
    await newsFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 766);
    await newsFailure.page.waitForFunction(() => document.querySelector("#newsMeta").textContent === "feed unavailable");
    assert.equal(await newsFailure.page.locator("#stories .story").count(), 0);
    assert.match(
      await newsFailure.page.locator("#stories").textContent(),
      /Daily newspaper feed unavailable\. REPD analytics below remain live\./,
    );
    await assertGaugeValues(newsFailure.page, ["34,073.49", "106,338.18", "766", "1,450"]);
    await newsFailure.context.close();

    const projectFailure = await preparePage(browser);
    await serveFrozenNews(projectFailure.page);
    await projectFailure.page.route("**/data/v7.2/projects.json*", (route) => route.abort());
    await projectFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
    await projectFailure.page.waitForFunction(() => document.querySelectorAll("#stories .story").length === 125);
    await projectFailure.page.waitForFunction(() => (
      document.querySelector("#tbody").textContent.includes("Canonical REPD project data is unavailable.")
    ));
    assert.equal(await projectFailure.page.locator("#stories .story").count(), 125);
    assert.equal(await projectFailure.page.locator("#tbody tr").count(), 1);
    await assertGaugeValues(projectFailure.page, ["0", "0", "0", "0"]);
    await projectFailure.context.close();

    console.log("V8.1 browser smoke: PASS (canonical projects, legacy news, mobile, CSV, independent failures)");
  } finally {
    await browser.close();
  }
}

await main();

Browser Smoke V9 1

A JavaScript module in the tests folder of GlobalGrid2050 that tests battery storage (BESS).

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_1.mjs · lines 1–40 of 40 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review)

What it does
It tests battery storage (BESS). Uses libraries node:assert/strict, node:module, playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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: battery storage (BESS).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:module, playwright
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_1.mjs:1-40 · blob 5329a95f6b0a732b081380e01e54861fbb6579ed · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from "node:assert/strict";
import { createRequire } from "node:module";

const require = createRequire("/workspace/scratch/c4bced7b19ae/globalgrid2050-audit/uk_renewables_pipeline/v7/package.json");
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9/";

const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
  const errors = [];
  page.on("pageerror", (error) => errors.push(error.message));
  await page.addInitScript(() => {
    window.Chart = class ChartStub {
      constructor(_canvas, config) { this.data = config.data; }
      update() {}
    };
  });
  await page.route("https://cdn.jsdelivr.net/**", (route) => route.fulfill({ status: 200, contentType: "application/javascript", body: "" }));
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 30000 });
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  assert.deepEqual(await page.locator("#tech [data-technology]").evaluateAll((buttons) => buttons.map((button) => button.dataset.technology)), ["all", "solar", "bess", "wind_onshore", "wind_offshore"]);

  await page.locator('[data-technology="wind_offshore"]').click();
  assert.equal(await page.locator("#tbody tr").count(), 109);
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["80,535", "109", "4,100"]);

  await page.locator('[data-technology="all"]').click();
  await page.locator("#search").fill("12453");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.match(await page.locator("#tbody").textContent(), /GG2050-REPD-12453/);
  const atlas = new URL(await page.locator("#tbody .atlaslink").getAttribute("href"));
  assert.equal(atlas.searchParams.get("repd_ref"), "12453");
  assert.equal(atlas.searchParams.get("technology"), "bess");
  assert.deepEqual(errors, []);
  console.log("V9.1 browser smoke: PASS (three gauges, 7,680 rows, wind filters, canonical search and Atlas link)");
} finally {
  await browser.close();
}

Browser Smoke V9 2

A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_2.mjs · lines 1–76 of 76 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review)

What it does
It tests the REPD register. Uses libraries node:assert/strict, node:fs/promises, node:module, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file build_manifest.json.
What it achieves
It reads `data/v9.1/build_manifest.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:fs/promises, node:module, playwright
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_2.mjs:1-76 · blob 887df4088aa67118ebf1e3d7cb8dbc222ec32e1d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

const require = createRequire(new URL("../package.json", import.meta.url));
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9/";

const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
  const errors = [];
  page.on("pageerror", (error) => errors.push(error.message));
  await page.addInitScript(() => {
    window.Chart = class ChartStub {
      constructor(_canvas, config) { this.data = config.data; }
      update() {}
    };
  });
  await page.route("https://cdn.jsdelivr.net/**", (route) => route.fulfill({ status: 200, contentType: "application/javascript", body: "" }));
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });

  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["356,474.09", "7,680", "4,100"]);
  assert.equal(await page.locator("thead th").count(), 8);
  assert.equal(await page.locator("#resultsMeta").getAttribute("data-filtered-count"), "7680");
  assert.equal((await page.locator(".gauges").evaluate((element) => getComputedStyle(element).gridTemplateColumns.split(" ").length)), 3);

  await page.setViewportSize({ width: 900, height: 1000 });
  assert.equal((await page.locator(".gauges").evaluate((element) => getComputedStyle(element).gridTemplateColumns.split(" ").length)), 3);
  await page.setViewportSize({ width: 390, height: 844 });
  assert.equal((await page.locator(".gauges").evaluate((element) => getComputedStyle(element).gridTemplateColumns.split(" ").length)), 1);
  assert.equal(await page.locator(".header").evaluate((element) => getComputedStyle(element).flexDirection), "row");
  await page.setViewportSize({ width: 1440, height: 1000 });

  await page.locator('[data-technology="wind_offshore"]').click();
  assert.equal(await page.locator("#tbody tr").count(), 109);
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["80,535.3", "109", "4,100"]);

  await page.locator("#clearFilters").click();
  await page.locator("#search").fill("GG2050-REPD-9873 Berwick");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  const atlas = new URL(await page.locator("#tbody .atlaslink").getAttribute("href"));
  assert.equal(atlas.searchParams.get("repd_ref"), "9873");
  assert.equal(atlas.searchParams.get("technology"), "wind_offshore");

  const missingRef = await page.evaluate(async () => {
    const manifest = await fetch("data/v9.1/build_manifest.json").then((response) => response.json());
    for (const partition of manifest.project_partitions) {
      const payload = await fetch(partition.path).then((response) => response.json());
      const missing = payload.projects.find((project) => project.geometry_status !== "valid");
      if (missing) return missing.repd_ref;
    }
    return "";
  });
  assert.ok(missingRef);
  await page.locator("#search").fill(missingRef);
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .action-disabled").textContent(), "NO MAP");
  assert.equal(await page.locator("#tbody .atlaslink").count(), 0);

  await page.locator("#search").fill("definitely-no-such-repd-project-v9-2");
  assert.equal(await page.locator("#tbody tr").count(), 0);
  const downloadPromise = page.waitForEvent("download");
  await page.locator("#exportInline").click();
  const download = await downloadPromise;
  const path = await download.path();
  const csv = await readFile(path, "utf8");
  assert.equal(csv.trimEnd().split(/\r?\n/).length, 1);
  assert.match(csv, /Site Name/);

  assert.deepEqual(errors, []);
  console.log("V9.2 browser smoke: PASS (V5 breakpoints, full default universe, wind, missing geometry and zero-result CSV)");
} finally {
  await browser.close();
}

Browser Smoke V9 3

A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_3.mjs · lines 1–215 of 215 · version 2026-09-05 11:56 · pattern assertContained (shared by 5 files)

What it does
It tests the REPD register. Defines preparePage, layoutSnapshot, assertContained. Uses libraries node:assert/strict, node:fs/promises, node:module, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file build_manifest.json.
Downstream impact
Used directly by 1 file: Run V9 3 (globalgrid2050).
What it achieves
It prepares page (`preparePage`) and is built from the layout snapshot helper (`layoutSnapshot`) and the assert contained helper (`assertContained`). Defines `preparePage`, `layoutSnapshot` and `assertContained`. It reads `data/v9.1/build_manifest.json`.
Why it matters
Checked by Run V9 3.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:fs/promises, node:module, playwright
Used by
run by Run V9 3 (script call), mentioned in Standalone (comment link)
Produces
preparePage, layoutSnapshot, assertContained
Defines here
preparePage, layoutSnapshot, assertContained
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_3.mjs:1-215 · blob a2d3de3036741007a2a1822ecb87caede426cb5d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

const require = createRequire(new URL("../package.json", import.meta.url));
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9/";

async function preparePage(browser, { chartStub = true } = {}) {
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
  const page = await context.newPage();
  if (chartStub) {
    await page.addInitScript(() => {
      window.Chart = class ChartStub {
        constructor(_canvas, config) { this.data = config.data; }
        update() {}
      };
    });
  }
  await page.route("https://cdn.jsdelivr.net/**", (route) => (
    chartStub
      ? route.fulfill({ status: 200, contentType: "application/javascript", body: "" })
      : route.abort()
  ));
  return { context, page };
}

async function layoutSnapshot(page) {
  return page.evaluate(() => {
    const selectors = [".main", ".header", ".status", ".newspaper", ".tablewrap"];
    const bounds = Object.fromEntries(selectors.map((selector) => {
      const rect = document.querySelector(selector).getBoundingClientRect();
      return [selector, { left: rect.left, right: rect.right }];
    }));
    return {
      bodyDisplay: getComputedStyle(document.body).display,
      gaugeColumns: getComputedStyle(document.querySelector(".gauges")).gridTemplateColumns.split(" ").length,
      storyColumns: getComputedStyle(document.querySelector(".stories")).gridTemplateColumns.split(" ").length,
      headerDirection: getComputedStyle(document.querySelector(".header")).flexDirection,
      statusWhiteSpace: getComputedStyle(document.querySelector(".status")).whiteSpace,
      searchWidth: Math.round(document.querySelector("#search").getBoundingClientRect().width),
      clientWidth: document.documentElement.clientWidth,
      scrollWidth: document.documentElement.scrollWidth,
      bounds,
    };
  });
}

function assertContained(layout, width, label) {
  assert.ok(layout.scrollWidth <= layout.clientWidth, `${label} document overflow: ${layout.scrollWidth}px > ${layout.clientWidth}px`);
  for (const [selector, bounds] of Object.entries(layout.bounds)) {
    assert.ok(bounds.left >= -0.5, `${label} ${selector} crosses left edge`);
    assert.ok(bounds.right <= width + 0.5, `${label} ${selector} crosses right edge`);
  }
}

const browser = await chromium.launch({ headless: true });
try {
  const { context, page } = await preparePage(browser);
  const errors = [];
  page.on("pageerror", (error) => errors.push(error.message));
  await page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await page.waitForFunction(() => document.querySelectorAll("#stories .story").length > 0, null, { timeout: 30000 });
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");

  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "7,680 of 7,680 records · 356,474 MW · largest 4,100 MW");
  assert.equal(await page.locator("thead th").count(), 11);
  assert.deepEqual(await page.locator("thead th").allTextContents(), [
    "SITE NAME", "COUNTY", "OPERATOR", "TECHNOLOGY", "OFFICIAL REPD STATUS", "OFFICIAL CAPACITY",
    "REPD REF", "GLOBALGRID REF", "REPD UPDATED", "NEWS SIGNAL", "ACTIONS",
  ]);
  assert.equal(await page.locator("#resultsMeta").getAttribute("data-filtered-count"), "7680");
  assert.equal(await page.locator("#releaseMeta").textContent(), "V9.3.1 interface · V9.1 canonical data spine · all 7,680 qualifying records loaded");

  const firstIdentity = await page.locator("#tbody tr").first().evaluate((row) => ({
    repd: row.querySelector(".repd-ref")?.textContent,
    globalgrid: row.querySelector(".globalgrid-ref")?.textContent,
    updated: row.querySelector(".repd-updated")?.textContent,
  }));
  assert.ok(/^\d+$/.test(firstIdentity.repd));
  assert.equal(firstIdentity.globalgrid, `GG2050-REPD-${firstIdentity.repd}`);
  assert.match(firstIdentity.updated, /^(?:\d{2}\/\d{2}\/\d{4}|not supplied by REPD)$/);

  await page.locator("#sortProjects").selectOption("updated_desc");
  const newestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(newestDates.every((value, index) => index === 0 || value <= newestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_desc(?:&|$)/);

  await page.locator("#sortProjects").selectOption("updated_asc");
  const oldestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(oldestDates.every((value, index) => index === 0 || value >= oldestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_asc(?:&|$)/);

  await page.locator("#clearFilters").click();
  assert.equal(await page.locator("#sortProjects").inputValue(), "capacity_desc");

  for (const width of [1440, 1000, 921]) {
    await page.setViewportSize({ width, height: 1000 });
    const desktop = await layoutSnapshot(page);
    assert.equal(desktop.bodyDisplay, "flex", `${width}px desktop body layout`);
    assert.equal(desktop.gaugeColumns, 3, `${width}px desktop gauge columns`);
    assert.equal(desktop.headerDirection, "row", `${width}px desktop header direction`);
    assert.equal(desktop.statusWhiteSpace, "nowrap", `${width}px desktop status wrapping`);
    assertContained(desktop, width, `${width}px desktop`);
  }

  for (const width of [769, 800, 900, 920]) {
    await page.setViewportSize({ width, height: 900 });
    const intermediate = await layoutSnapshot(page);
    assert.equal(intermediate.bodyDisplay, "flex", `${width}px intermediate body layout`);
    assert.equal(intermediate.gaugeColumns, 3, `${width}px intermediate gauge columns`);
    assert.equal(intermediate.headerDirection, "column", `${width}px intermediate header direction`);
    assert.equal(intermediate.statusWhiteSpace, "normal", `${width}px intermediate status wrapping`);
    assertContained(intermediate, width, `${width}px intermediate`);
  }

  for (const width of [390, 430, 440, 768]) {
    await page.setViewportSize({ width, height: 844 });
    const mobile = await layoutSnapshot(page);
    assert.equal(mobile.bodyDisplay, "block", `${width}px mobile body layout`);
    assert.equal(mobile.gaugeColumns, 1, `${width}px mobile gauge columns`);
    assert.equal(mobile.storyColumns, 1, `${width}px mobile story columns`);
    assert.equal(mobile.headerDirection, "column", `${width}px mobile header direction`);
    assert.equal(mobile.statusWhiteSpace, "normal", `${width}px mobile status wrapping`);
    assert.ok(mobile.searchWidth >= width - 50, `${width}px mobile search width`);
    assertContained(mobile, width, `${width}px mobile`);
  }

  await page.setViewportSize({ width: 1440, height: 1000 });
  await page.locator('[data-technology="wind_offshore"]').click();
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "80,535");
  assert.equal(await page.locator("#tbody tr").count(), 109);
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["80,535", "109", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "109 of 7,680 records · 80,535 MW · largest 4,100 MW");

  await page.locator("#clearFilters").click();
  await page.locator("#search").fill("GG2050-REPD-9873 Berwick");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  const atlas = new URL(await page.locator("#tbody .atlaslink").getAttribute("href"));
  assert.equal(atlas.searchParams.get("repd_ref"), "9873");
  assert.equal(atlas.searchParams.get("technology"), "wind_offshore");

  await page.locator("#tbody .project-record summary").click();
  assert.equal(await page.locator("#tbody .project-record").getAttribute("open"), "");
  assert.match(await page.locator("#tbody .record-grid").textContent(), /PLANNING AUTHORITY/);

  await page.locator("#tbody .copy-id").click();
  await page.waitForFunction(() => document.querySelector("#tbody .copy-id")?.textContent === "COPIED");
  assert.equal(await page.locator("#tbody .copy-id").textContent(), "COPIED");

  const missingRef = await page.evaluate(async () => {
    const manifest = await fetch("data/v9.1/build_manifest.json").then((response) => response.json());
    for (const partition of manifest.project_partitions) {
      const payload = await fetch(partition.path).then((response) => response.json());
      const missing = payload.projects.find((project) => project.geometry_status !== "valid");
      if (missing) return missing.repd_ref;
    }
    return "";
  });
  assert.ok(missingRef);
  await page.locator("#search").fill(missingRef);
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .action-disabled").textContent(), "NO MAP");
  assert.equal(await page.locator("#tbody .atlaslink").count(), 0);

  await page.locator('[data-news="RELEVANT"]').click();
  const relevantCount = await page.locator("#stories .story").count();
  assert.ok(relevantCount > 0 && relevantCount < 125);
  await page.locator('[data-news="ALL"]').click();

  await page.locator("#search").fill("definitely-no-such-repd-project-v9-3");
  assert.equal(await page.locator("#tbody tr").count(), 0);
  const downloadPromise = page.waitForEvent("download");
  await page.locator("#exportInline").click();
  const download = await downloadPromise;
  assert.match(download.suggestedFilename(), /^globalgrid2050_uk_renewables_pipeline_v9_3_\d{4}-\d{2}-\d{2}\.csv$/);
  const csv = await readFile(await download.path(), "utf8");
  assert.equal(csv.trimEnd().split(/\r?\n/).length, 1);
  assert.match(csv, /Site Name/);

  assert.deepEqual(errors, []);
  await context.close();

  const newsFailure = await preparePage(browser);
  await newsFailure.page.route("**/dist/major_project_news_v5.json*", (route) => route.abort());
  await newsFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await newsFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await newsFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await newsFailure.page.waitForFunction(() => document.querySelector("#newsMeta").textContent === "feed unavailable");
  await newsFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  await newsFailure.context.close();

  const projectFailure = await preparePage(browser);
  await projectFailure.page.route("**/contracts/release.v9.3.json*", (route) => route.abort());
  await projectFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await projectFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await projectFailure.page.waitForFunction(() => document.querySelectorAll("#stories .story").length > 0, null, { timeout: 30000 });
  await projectFailure.page.waitForFunction(() => document.querySelector("#tbody").textContent.includes("V9.3.1 has failed closed."));
  await projectFailure.context.close();

  const chartFailure = await preparePage(browser, { chartStub: false });
  await chartFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await chartFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await chartFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await chartFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => chartFailure.page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  await chartFailure.context.close();

  console.log("V9.3.1 browser smoke: PASS (official references, REPD date sorting, full pipeline, CSV, news and Atlas)");
} finally {
  await browser.close();
}