In this section
- UK Gazetteer Flyto energy-data · code-generator / apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js lines 701–817
- V9 Parquet Fetch Bridge render · code-generator / apps/substation-finder/Ug/v9-parquet-fetch-bridge.js lines 1–164
- Nearest Search render · code-generator / apps/substation-finder/Vn/nearest-search.mjs lines 1–90
- V9 Nearest Search render · code-generator / apps/substation-finder/Vn/v9-nearest-search.js lines 1–90
- Code Generator — Substation Finder Page render · code-generator / apps/substation-finder/index.html lines 1–112
UK Gazetteer Flyto
A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from the GridAtlas repository.
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
energy-datacode-generator / apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js · lines 701–817 of 817 · version 2026-09-05 16:23 (continued from section 311) · pattern queryPipelineIdentity (shared by 2 files)
- What it does
- It maps REPD projects, postcodes and the REPD register. Defines 40 functions or classes, including invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: postcodes, the REPD register.
- Inputs & outputs
- In: data source: gridatlas data; data source: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202608290716.parquet; JSON file repd_v9_manifest_202608290716.json; DuckDB queries. Out: interactive map.
- Downstream impact
- Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
- What it achieves
- It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). Place-global-search-v9-5. It responds to gridatlas, click and input events.
- Why it matters
- Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
- Application
- code-generator · apps/substation-finder/Ug · script
- VEDIC
- QUERY (GG2050-VEDIC-000046): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_predicate
- VEDIC
- SCORE (GG2050-VEDIC-000047): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_sort_expression
- VEDIC
- UK GEOCODE (GG2050-VEDIC-000048): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → uk_location_candidates
- Uses
- none found
- Used by
- linked from Code Generator — Substation Finder Page (link)
- Produces
- invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
- Defines here
- retryExactRepdDeepLink, bindSearch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js:701-817 · blob f5ba42357785598131bb4f19d0c6027f6bc88dc7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
};
return;
}
renderResults(results, resultsEl);
if (!hasSafeMapPoint(exact)) {
state.deep_link = {...exact, owner_epoch:ownerEpoch, status:'IDENTIFIED_NO_GEOMETRY', resolved:true, mapped:false, official_active_register_match:false};
document.body.dataset.gridatlasRepdRef=repdRef;
document.body.dataset.gridatlasRepdDeepLink='identified-no-geometry';
resultsEl.innerHTML = '<h3>' + escapeHtml(exact.name) + '</h3><p>REPD ' + escapeHtml(repdRef) + ' / ' + escapeHtml(String(exact.capacity_mw)) + ' MW</p><p>Location unavailable: this Pipeline REPD snapshot supplies no coordinates. No map pin or grid-distance calculation can be shown.</p>';
Object.assign(resultsEl.style,{display:'block',position:'fixed',top:'128px',left:'12px',right:'12px',width:'auto',maxWidth:'420px',maxHeight:'60vh',overflow:'auto',zIndex:'6000',padding:'16px',background:'#08151c',color:'#e2f8ff',boxSizing:'border-box'});
return;
}
await waitForCapturedMap();
if (!stillOwned()) return;
if (!selectResult(exact, { deepLinkEpoch: ownerEpoch })) return;
if (!stillOwned()) return;
invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
document.body.dataset.gridatlasRepdRef = repdRef;
document.body.dataset.gridatlasRepdDeepLink = 'resolved';
state.deep_link = {
status: 'RESOLVED',
owner_epoch: ownerEpoch,
repd_ref: repdRef,
resolved: true,
mapped: true,
name: exact.name,
postcode: exact.postcode,
longitude: exact.longitude,
latitude: exact.latitude,
technology: exact.technology,
capacity_mw: exact.capacity_mw,
status_value: exact.status,
location_provenance: exact.location_provenance || null,
identity_source: exact.identity_source || 'OFFICIAL_ACTIVE_REGISTER',
official_active_register_match: !exact.identity_source
};
} catch (error) {
if (coordinator && Number.isInteger(ownerEpoch)
&& !coordinator.arrivalGate.isCurrent(ownerEpoch)) return;
const message = String(error?.message || error);
state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
state.deep_link = {
...arrival, owner_epoch: ownerEpoch, status: 'FAILED',
resolved: false, mapped: false, message,
identity_source: 'ACTIVE_REGISTER_CHECK_FAILED'
};
document.body.dataset.gridatlasRepdDeepLink = 'failed';
console.error('[V9 EXACT REPD DEEP LINK]', error);
}
}
async function retryExactRepdDeepLink(input, resultsEl, ownerEpoch) {
const coordinator = arrivalCoordinator();
invariant(coordinator, 'shared arrival coordinator unavailable for retry');
invariant(Number.isInteger(ownerEpoch), 'identity retry requires one shared owner epoch');
if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
state.identity_retry_count += 1;
await resetOfficialRuntime();
if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
return receiveExactRepdDeepLink(input, resultsEl, ownerEpoch);
}
function bindSearch() {
const input = document.getElementById('search-input');
const button = document.getElementById('search-btn');
const resultsEl = document.getElementById('search-results');
invariant(input && button && resultsEl, 'V8 search controls missing');
input.setAttribute('placeholder', 'Search project, address, postcode or place...');
input.setAttribute('aria-label', 'Search project, address, postcode or place');
input.addEventListener('input', event => {
event.stopImmediatePropagation();
invalidatePendingDeepLink('user-search-input');
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => executeSearch(input, resultsEl, false), 180);
}, true);
input.addEventListener('keydown', event => {
if (event.key === 'Enter') {
event.preventDefault();
event.stopImmediatePropagation();
invalidatePendingDeepLink('user-search-submit');
clearTimeout(debounceTimer);
executeSearch(input, resultsEl, true);
} else if (event.key === 'Escape') {
event.stopImmediatePropagation();
invalidatePendingDeepLink('user-search-dismiss');
resultsEl.style.display = 'none';
}
}, true);
button.addEventListener('click', event => {
event.preventDefault();
event.stopImmediatePropagation();
invalidatePendingDeepLink('user-search-submit');
clearTimeout(debounceTimer);
executeSearch(input, resultsEl, true);
}, true);
state.retry_exact_deep_link = (ownerEpoch) =>
retryExactRepdDeepLink(input, resultsEl, ownerEpoch);
state.ready = true;
}
window.addEventListener('DOMContentLoaded', () => {
try {
bindSearch();
const input = document.getElementById('search-input');
const resultsEl = document.getElementById('search-results');
void receiveExactRepdDeepLink(input, resultsEl);
} catch (error) {
state.failures.push({ phase: 'bind', message: String(error?.message || error) });
console.error('[V9 PLACE SEARCH INIT]', error);
}
}, { once: true });
})();V9 Parquet Fetch Bridge
A JavaScript file in the substation finder folder of Code Generator that reads Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256 from the data-GridAtlas repository.
rendercode-generator / apps/substation-finder/Ug/v9-parquet-fetch-bridge.js · lines 1–164 of 164 · pattern resolvePartition (shared by 6 files)
- What it does
- It loads REPD master and heavy emitters UK. Defines 11 functions or classes, including invariant, sha256Hex, getManifest, getRuntime, requestPath. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: data source: data-gridatlas data; JSON file repd_master.json; JSON file heavy_emitters_uk.json; DuckDB queries.
- Downstream impact
- Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
- What it achieves
- It gets manifest (`getManifest`), gets runtime (`getRuntime`) and resolves partition (`resolvePartition`). Defines `invariant`, `sha256Hex`, `getManifest` and 8 more.
- Why it matters
- Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
- Application
- code-generator · apps/substation-finder/Ug · script
- Uses
- Data GridAtlas — Data GridAtlas Page (estate URL)
- Used by
- linked from Code Generator — Substation Finder Page (link)
- Produces
- invariant, sha256Hex, getManifest, getRuntime, requestPath, legacyStem, shouldIntercept, resolvePartition, rowObject, querySource, task
- Defines here
- invariant, sha256Hex, getManifest, getRuntime, requestPath, legacyStem, shouldIntercept, resolvePartition, rowObject, querySource, task
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ug/v9-parquet-fetch-bridge.js:1-164 · blob 06a044dc1aa55eda59acbedb561a6d2daabf2000 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
(() => {
'use strict';
const DATA_BASE = 'https://ventusltd.github.io/data-gridatlas/202608291237-data-gridatlas/';
const MANIFEST_URL = `${DATA_BASE}data/manifest.json`;
const MANIFEST_SHA256 = '3246dbdaa042ae8352ec9b7128cb6c2fe65e4f1aba0534302510661828df2526';
const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';
const nativeFetch = window.fetch.bind(window);
const sourceCache = new Map();
let manifestPromise = null;
let runtimePromise = null;
let queue = Promise.resolve();
const state = {
schema: 'gridatlas.v9-v8-parquet-fetch-bridge.v1',
dataRelease: '202608291237-data-gridatlas',
intercepted: 0,
loaded: {},
failures: []
};
window.__GRIDATLAS_V9_BRIDGE__ = state;
function invariant(condition, message) {
if (!condition) throw new Error(message);
}
async function sha256Hex(bytes) {
const digest = await crypto.subtle.digest('SHA-256', bytes);
return [...new Uint8Array(digest)].map(value => value.toString(16).padStart(2, '0')).join('');
}
async function getManifest() {
manifestPromise ||= (async () => {
const response = await nativeFetch(MANIFEST_URL, { cache: 'no-store' });
invariant(response.ok, `manifest HTTP ${response.status}`);
const bytes = await response.arrayBuffer();
invariant(await sha256Hex(bytes) === MANIFEST_SHA256, 'data manifest SHA-256 mismatch');
const manifest = JSON.parse(new TextDecoder().decode(bytes));
invariant(manifest?.schema === 'data-gridatlas.v8-transplant-manifest.v1', 'data manifest schema mismatch');
invariant(manifest?.closure?.sources === 56, 'V8 source closure mismatch');
invariant(manifest?.closure?.layers === 60, 'V8 layer closure mismatch');
invariant(manifest?.closure?.features === 541282, 'V8 feature closure mismatch');
return manifest;
})();
return manifestPromise;
}
async function getRuntime() {
runtimePromise ||= (async () => {
const duckdb = await import(DUCKDB_MODULE);
const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
invariant(bundle?.mainModule && bundle?.mainWorker, 'DuckDB-WASM bundle unavailable');
const workerUrl = URL.createObjectURL(new Blob([
`importScripts(${JSON.stringify(bundle.mainWorker)});`
], { type: 'text/javascript' }));
const worker = new Worker(workerUrl);
const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
const database = new duckdb.AsyncDuckDB(logger, worker);
try {
await database.instantiate(bundle.mainModule, bundle.pthreadWorker);
} finally {
URL.revokeObjectURL(workerUrl);
}
const connection = await database.connect();
return { connection, database, worker };
})();
return runtimePromise;
}
function requestPath(input) {
try {
const raw = typeof input === 'string' ? input : input?.url;
return new URL(raw, window.location.href).pathname;
} catch {
return '';
}
}
function legacyStem(pathname) {
const name = decodeURIComponent(pathname.split('/').pop() || '').toLowerCase();
if (name === 'repd_master.json') return 'repd_master_v8_oracle';
if (name === 'heavy_emitters_uk.json') return 'heavy_emitters_uk';
if (name.endsWith('.geojson')) return name.slice(0, -8);
return '';
}
function shouldIntercept(pathname) {
return Boolean(legacyStem(pathname));
}
async function resolvePartition(pathname) {
const stem = legacyStem(pathname);
invariant(stem, `unsupported V8 data path: ${pathname}`);
const expected = `partitions/${stem}.parquet`.toLowerCase();
const manifest = await getManifest();
const artifact = (manifest.artifacts || []).find(item => String(item.path || '').toLowerCase() === expected);
invariant(artifact, `no V9 Parquet partition for V8 source ${pathname}`);
invariant(/^[a-f0-9]{64}$/.test(artifact.sha256 || ''), `bad partition digest for ${artifact.path}`);
return artifact;
}
function rowObject(row) {
return row && typeof row.toJSON === 'function' ? row.toJSON() : row;
}
async function querySource(pathname) {
if (sourceCache.has(pathname)) return sourceCache.get(pathname);
const task = async () => {
const artifact = await resolvePartition(pathname);
const parquetUrl = `${DATA_BASE}data/${artifact.path}`;
const { connection } = await getRuntime();
const escaped = parquetUrl.replaceAll("'", "''");
const table = await connection.query(`
SELECT source_id, feature_index, feature_id, geometry_json, properties_json
FROM read_parquet('${escaped}')
ORDER BY feature_index
`);
const features = table.toArray().map(raw => {
const row = rowObject(raw);
const geometry = JSON.parse(String(row.geometry_json));
const properties = JSON.parse(String(row.properties_json || '{}'));
return {
type: 'Feature',
id: row.feature_id || `${row.source_id}:${row.feature_index}`,
geometry,
properties
};
});
state.loaded[pathname] = {
parquet: artifact.path,
rows: features.length,
sha256: artifact.sha256
};
return { type: 'FeatureCollection', features };
};
const result = queue.then(task, task);
queue = result.catch(() => {});
sourceCache.set(pathname, result);
try {
return await result;
} catch (error) {
sourceCache.delete(pathname);
state.failures.push({ pathname, message: String(error?.message || error) });
throw error;
}
}
window.fetch = async function gridAtlasV9Fetch(input, init = undefined) {
const pathname = requestPath(input);
if (!shouldIntercept(pathname)) return nativeFetch(input, init);
state.intercepted += 1;
if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
const payload = await querySource(pathname);
if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
return new Response(JSON.stringify(payload), {
status: 200,
headers: {
'Content-Type': 'application/geo+json; charset=utf-8',
'Cache-Control': 'no-store',
'X-GridAtlas-Data-Plane': 'V9-PARQUET-DUCKDB'
}
});
};
})();Nearest Search
A JavaScript module in the substation finder folder of Code Generator covering substations. It is built from the normalise step (`normalise`) and the index step (`index`).
rendercode-generator / apps/substation-finder/Vn/nearest-search.mjs · lines 1–90 of 90
- What it does
- It lists and searches substations. Defines normalise, index. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: substations, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
- What it achieves
- Module: nearest-search (substation-lookup).
- Why it matters
- Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
- Application
- code-generator · apps/substation-finder/Vn · JavaScript module
- Uses
- ./geodesy.mjs
- Used by
- linked from Code Generator — Substation Finder Page (link)
- Produces
- normalise, index, schema
- Defines here
- normalise, index
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Vn/nearest-search.mjs:1-90 · blob 313da356166b05aad0c99adb736abf25b79bc31c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/**
* Module: nearest-search (substation-lookup)
*
* Extracted from gridatlas/atlas/modules/202609011950-substation-lookup.js.
*
* IMPORTANT PROVENANCE NOTE (see ../duplication.md 2(a)):
* This module is committed to the gridatlas repo but is NOT referenced by
* any composition/parts manifest and is NOT loaded by the live Atlas. The
* nearest-substation search that actually runs in production is a
* byte-different inline duplicate inside
* atlas/cartridges/202609041330-substation-intelligence-v9-63.js
* (state.nearest, lines 6083-6092 of that file). Both implementations do a
* full exhaustive O(n) scan with no bbox/ring pre-filter, so neither has
* the ring-search-excludes-true-nearest bug; the divergence is purely
* architectural (dead module vs. hand-rolled duplicate), documented in
* duplication.md.
*
* Finding a substation by the name someone wrote, and by position. Two
* jobs, one boundary:
*
* normalise(name) the lookup key, matching the one data-grid-gb's own
* join uses, so a name that matched there matches here
* index(points) a name map and a located list, built once
* nearest(...) the closest located sites, measured on the estate's
* single radius via the geodesy module
*
* It does NOT fetch, render, summarise or decide. The cartridge fetches;
* the summary module writes sentences; this only finds.
*
* CHANGED: source is an IIFE that reads its geodesy dependency off
* `window.__GRIDATLAS_MODULES__.geodesy` and throws at load time if it is
* absent. Replaced with a static ES import of ./geodesy.mjs. No formula or
* control flow changed otherwise.
*/
import { distanceKm } from './geodesy.mjs';
/* Deliberately dull. This is a lookup key, not a search engine, and it
must stay byte-compatible with the normalisation the owner product's
join uses - if the two drift, a name that joined upstream stops
resolving downstream and nobody sees it happen. */
const NOISE = /\b(SUBSTATION|SUB STATION|SUBSTN|GRID|SUPPLY|POINT|GSP|NATIONAL|POWER|STATION|WIND|FARM|WINDFARM|OFFSHORE|ONSHORE|EXTENSION|400KV|275KV|132KV|66KV|33KV|11KV|NGET|SSE|SP|SHE)\b/g;
export function normalise(name) {
return String(name || '').toUpperCase()
.replace(/[^A-Z0-9 ]/g, ' ')
.replace(NOISE, ' ')
.split(/\s+/).filter(Boolean).join(' ');
}
export function index(points) {
const byName = new Map();
const located = [];
for (const point of points || []) {
const key = normalise(point && point.name);
if (key && !byName.has(key)) byName.set(key, point);
if (point && point.location) located.push(point);
}
return {
size: byName.size,
located: located.length,
byName: (name) => byName.get(normalise(name)) || null,
/* Nearest by measurement, not by guess. minimumKv filters on the
highest voltage the site declares; limit 1 returns one match or
null, anything else returns a sorted list.
NOTE: this is an exhaustive scan over every located point -- no
bbox/ring pre-filter -- so it cannot exhibit the ring-search bug
(a pre-filter that excludes the true nearest node). It is O(n) per
call; grid-distance-maths' SpatialIndex.nearest() is the estate's
answer for when that stops being fast enough, with a proven
early-termination bound (see ./nearest-search-spatial-index.mjs). */
nearest: (lon, lat, options) => {
const minimumKv = (options && options.minimumKv) || 0;
const limit = (options && options.limit) || 1;
const found = [];
for (const point of located) {
const voltages = point.voltages_kv || [];
if (!voltages.length || Math.max(...voltages) < minimumKv) continue;
found.push({
point,
km: distanceKm(lon, lat, point.location.lon, point.location.lat)
});
}
found.sort((a, b) => a.km - b.km);
return limit === 1 ? (found[0] || null) : found.slice(0, limit);
}
};
}
export const schema = 'gridatlas.module.substation-lookup.v1';V9 Nearest Search
A JavaScript module in the substation finder folder of Code Generator covering substations. It is built from the normalise step (`normalise`) and the index step (`index`).
Set aside from the main view: 97% of its lines are the same as apps/substation-finder/Vn/nearest-search.mjs (code-generator), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Nearest Search; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9718 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Vn/nearest-search.mjs:1-90 313da356166b05aad0c99adb736abf25b79bc31c
- sha256 28cc8b973f9c294882ceffa9e27c3a2f14062e5263a8f82a08f5a861fb2b43fc
- target sha256 7972abbbbf44c5e287fb1aa6a344bd8be443a60b71cd257a754a415bcb7c4385
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
rendercode-generator / apps/substation-finder/Vn/v9-nearest-search.js · lines 1–90 of 90
- What it does
- It lists and searches substations. Defines normalise, index. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: substations, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 5 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Compute Observer Proof (ventus-grid-engine); V9 Engine Proof (ventus-grid-engine); and 1 more. Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- What it achieves
- Module: nearest-search (substation-lookup).
- Why it matters
- Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, Compute Observer Proof and V9 Engine Proof, from Ventus Grid Engine.
- Application
- code-generator · apps/substation-finder/Vn · JavaScript module
- Uses
- ./v9-geodesy.js
- Used by
- linked from Code Generator — Substation Finder Page (link), named by URL in Build Graph (estate URL), imported by Compute Observer Proof (import), imported by V9 Engine Proof (import), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- normalise, index, schema
- Defines here
- normalise, index
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Vn/v9-nearest-search.js:1-90 · blob d2ab3b111eb09f7af3df3a9fce9ad0a9dc1dea99 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/**
* Module: nearest-search (substation-lookup)
*
* Extracted from gridatlas/atlas/modules/202609011950-substation-lookup.js.
*
* IMPORTANT PROVENANCE NOTE (see ../duplication.md 2(a)):
* This module is committed to the gridatlas repo but is NOT referenced by
* any composition/parts manifest and is NOT loaded by the live Atlas. The
* nearest-substation search that actually runs in production is a
* byte-different inline duplicate inside
* atlas/cartridges/202609041330-substation-intelligence-v9-63.js
* (state.nearest, lines 6083-6092 of that file). Both implementations do a
* full exhaustive O(n) scan with no bbox/ring pre-filter, so neither has
* the ring-search-excludes-true-nearest bug; the divergence is purely
* architectural (dead module vs. hand-rolled duplicate), documented in
* duplication.md.
*
* Finding a substation by the name someone wrote, and by position. Two
* jobs, one boundary:
*
* normalise(name) the lookup key, matching the one data-grid-gb's own
* join uses, so a name that matched there matches here
* index(points) a name map and a located list, built once
* nearest(...) the closest located sites, measured on the estate's
* single radius via the geodesy module
*
* It does NOT fetch, render, summarise or decide. The cartridge fetches;
* the summary module writes sentences; this only finds.
*
* CHANGED: source is an IIFE that reads its geodesy dependency off
* `window.__GRIDATLAS_MODULES__.geodesy` and throws at load time if it is
* absent. Replaced with a static ES import of ./geodesy.mjs. No formula or
* control flow changed otherwise.
*/
import { distanceKm } from './v9-geodesy.js';
/* Deliberately dull. This is a lookup key, not a search engine, and it
must stay byte-compatible with the normalisation the owner product's
join uses - if the two drift, a name that joined upstream stops
resolving downstream and nobody sees it happen. */
const NOISE = /\b(SUBSTATION|SUB STATION|SUBSTN|GRID|SUPPLY|POINT|GSP|NATIONAL|POWER|STATION|WIND|FARM|WINDFARM|OFFSHORE|ONSHORE|EXTENSION|400KV|275KV|132KV|66KV|33KV|11KV|NGET|SSE|SP|SHE)\b/g;
export function normalise(name) {
return String(name || '').toUpperCase()
.replace(/[^A-Z0-9 ]/g, ' ')
.replace(NOISE, ' ')
.split(/\s+/).filter(Boolean).join(' ');
}
export function index(points) {
const byName = new Map();
const located = [];
for (const point of points || []) {
const key = normalise(point && point.name);
if (key && !byName.has(key)) byName.set(key, point);
if (point && point.location) located.push(point);
}
return {
size: byName.size,
located: located.length,
byName: (name) => byName.get(normalise(name)) || null,
/* Nearest by measurement, not by guess. minimumKv filters on the
highest voltage the site declares; limit 1 returns one match or
null, anything else returns a sorted list.
NOTE: this is an exhaustive scan over every located point -- no
bbox/ring pre-filter -- so it cannot exhibit the ring-search bug
(a pre-filter that excludes the true nearest node). It is O(n) per
call; grid-distance-maths' SpatialIndex.nearest() is the estate's
answer for when that stops being fast enough, with a proven
early-termination bound (see ./nearest-search-spatial-index.mjs). */
nearest: (lon, lat, options) => {
const minimumKv = (options && options.minimumKv) || 0;
const limit = (options && options.limit) || 1;
const found = [];
for (const point of located) {
const voltages = point.voltages_kv || [];
if (!voltages.length || Math.max(...voltages) < minimumKv) continue;
found.push({
point,
km: distanceKm(lon, lat, point.location.lon, point.location.lat)
});
}
found.sort((a, b) => a.km - b.km);
return limit === 1 ? (found[0] || null) : found.slice(0, limit);
}
};
}
export const schema = 'gridatlas.module.substation-lookup.v1';Code Generator — Substation Finder Page
A web page that draws parts, substations, postcodes and the Renewable Energy Planning Database (REPD) register. Published at https://ventusltd.github.io/code-generator/apps/substation-finder/. It applies inputs (`applyInputs`), loads one (`loadOne`) and loads lib (`loadLib`).
rendercode-generator / apps/substation-finder/index.html · lines 1–112 of 112 · Entry point · pattern applyInputs (shared by 2 files)
- What it does
- It draws parts, substations, postcodes and the REPD register. Defines $, note, applyInputs, loadOne, loadLib. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: substations, postcodes, the REPD register.
- Inputs & outputs
- In: JSON file parts.json; JSON file substation-finder-1.json; form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/code-generator/apps/substation-finder/.
- What it achieves
- Substation finder on a map. It responds to error and unhandledrejection events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder · page
- Uses
- Substation Intelligence V9 63 (link), Menu Bar (link), Ventus Corev8engine Deep Link Receiver (link), Ventus Corev8engine (link), Ventus Corev7engine (link), Nearest Search (link), V9 Nearest Search (link), Place Global Search V9 5 (link), and 13 more
- Used by
- none found
- Produces
- $, note, applyInputs, loadOne, loadLib
- Defines here
- $, note, applyInputs, loadOne, loadLib
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/index.html:1-112 · blob 5e121e4246aeee377646e0873d2ee1e5ed39e25a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Substation finder on a map · assembly</title>
<style>
:root{color-scheme:dark}
body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#eef2fb;font:15px/1.5 Inter,ui-sans-serif,system-ui,sans-serif}
a{color:#00e5ff} h1{font-size:22px;margin:0 0 4px} h2{font-size:15px;font-family:ui-monospace,monospace;letter-spacing:.14em;text-transform:uppercase;color:#9aa3b5;margin:22px 0 8px}
.ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff} .muted{color:#9aa3b5}
.card{border:1px solid #262b36;border-radius:14px;padding:14px 16px;margin:12px 0;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014))}
label{display:block;margin:10px 0 4px} label b{font-family:ui-monospace,monospace} label small{color:#9aa3b5;display:block}
input{width:100%;box-sizing:border-box;padding:9px 12px;background:#12151c;border:1px solid #262b36;color:inherit;font:inherit;border-radius:10px}
.btn{background:#0f1218;border:1px solid #00e5ff;color:#eef2fb;padding:9px 14px;border-radius:999px;font:inherit;cursor:pointer;margin:12px 8px 0 0} .btn:disabled{opacity:.4;cursor:not-allowed}
table{border-collapse:collapse;width:100%;font-size:13px} td,th{padding:6px 8px;border-bottom:1px solid #1a1f2a;text-align:left;vertical-align:top} th{color:#9aa3b5;font-weight:500}
.ok{color:#39d353} .bad{color:#ff5555} .wait{color:#9aa3b5} .amber{color:#ffd54a} .mono{font-family:ui-monospace,monospace;font-size:12px}
details{margin:8px 0} summary{cursor:pointer;color:#9aa3b5} .wrap{overflow-x:auto}
</style>
<div class="ey">Ventus · Global Grid 2050 · Code generator · assembly</div>
<h1>Substation finder on a map</h1>
<div class="muted">Built 2026-09-14 13:00 UTC from 5 parts: Si substation-intelligence, Vn Nearest substation search, Ug uk-gazetteer-flyto, Ps Place search and arrival, Dt The MAP button (deep-link contract). Every file is copied unchanged from GitHub at a pinned commit; this page loads them in dependency order and reports what happened. <a href="REPORT.md">Report</a> · <a href="WORK-ORDERS.md">W … [line shortened here: 454 characters; full line on GitHub]
<div class="card" id="inputs-card">
<h2>Values still needed</h2>
<p class="muted">These names are used by the parts but defined nowhere in the table. Give each a value here to try the assembly; each also has a work order for the agents.</p><form id="inputs"><label for="need-maplibregl"><b>maplibregl</b> <span class="muted">· library (global object) · used by Si · <a href="../../requests/substation-finder-1.json">work order substation-finder-1</a></span><small … [line shortened here: 593 characters; full line on GitHub]
<button class="btn" id="go">Load the parts</button> <span class="muted" id="state">not started</span>
</div>
<div class="card">
<h2>What loaded</h2>
<div class="wrap"><table id="files"><thead><tr><th>order</th><th>part</th><th>file</th><th>kind</th><th>result</th></tr></thead><tbody>
<tr data-file="Si/202609062358-substation-intelligence-v9-63.js"><td>1</td><td class="mono">Si</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/cartridges/202609062358-substation-intelligence-v9-63.js">Si/202609062358-substation-intelligence-v9-63.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Si/202609031958-menu-bar.js"><td>2</td><td class="mono">Si</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/modules/202609031958-menu-bar.js">Si/202609031958-menu-bar.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Si/202609040045-ventus-corev8engine-deep-link-receiver.js"><td>3</td><td class="mono">Si</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/parts/202609040045-ventus-corev8engine-deep-link-receiver.js">Si/202609040045-ventus-corev8engine-deep-link-receiver.js</a></td><td>script</td><td class="wait res">waiting</ … [line shortened here: 408 characters; full line on GitHub]
<tr data-file="Si/ventus-corev8engine.js"><td>4</td><td class="mono">Si</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/releases/202608300453-atlas-v9/ventus-corev8engine.js">Si/ventus-corev8engine.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Si/ventus-corev7engine.js"><td>5</td><td class="mono">Si</td><td class="mono"><a href="https://github.com/Ventusltd/code-generator/blob/130a182bd4ec84525f985700bab9448921812ba5/apps/substation-finder/Si/ventus-corev7engine.js">Si/ventus-corev7engine.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Vn/nearest-search.mjs"><td>6</td><td class="mono">Vn</td><td class="mono"><a href="https://github.com/Ventusltd/code-generator/blob/130a182bd4ec84525f985700bab9448921812ba5/apps/substation-finder/Vn/nearest-search.mjs">Vn/nearest-search.mjs</a></td><td>module</td><td class="wait res">waiting</td></tr>
<tr data-file="Vn/v9-nearest-search.js"><td>7</td><td class="mono">Vn</td><td class="mono"><a href="https://github.com/Ventusltd/code-generator/blob/130a182bd4ec84525f985700bab9448921812ba5/apps/substation-finder/Vn/v9-nearest-search.js">Vn/v9-nearest-search.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/202609071213-place-global-search-v9-5.js"><td>8</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/cartridges/202609071213-place-global-search-v9-5.js">Ug/202609071213-place-global-search-v9-5.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/202609040229-place-global-search-arrival-identity.js"><td>9</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/parts/202609040229-place-global-search-arrival-identity.js">Ug/202609040229-place-global-search-arrival-identity.js</a></td><td>script</td><td class="wait res">waiting</td></t … [line shortened here: 402 characters; full line on GitHub]
<tr data-file="Ug/202609041945-place-global-search-v9-5.js"><td>10</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/testcode/blob/e8f6222226a7254ce08091b549803c3c1b92d979/sandbox/202609051152/atlas/cartridges/202609041945-place-global-search-v9-5.js">Ug/202609041945-place-global-search-v9-5.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/202609052028-uk-gazetteer-flyto.js"><td>11</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/testcode/blob/e8f6222226a7254ce08091b549803c3c1b92d979/sandbox/202609052028/atlas/cartridges/202609052028-uk-gazetteer-flyto.js">Ug/202609052028-uk-gazetteer-flyto.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/202608301136-place-postcode-search.js"><td>12</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/cartridges/202608301136-place-postcode-search.js">Ug/202608301136-place-postcode-search.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/202608291818-place-postcode-search.js"><td>13</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/releases/202608300453-atlas-v9/202608291818-place-postcode-search.js">Ug/202608291818-place-postcode-search.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ug/v9-parquet-fetch-bridge.js"><td>14</td><td class="mono">Ug</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/releases/202608291818-atlas-v9/v9-parquet-fetch-bridge.js">Ug/v9-parquet-fetch-bridge.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ps/202609071213-place-global-search-v9-5.js"><td>15</td><td class="mono">Ps</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/cartridges/202609071213-place-global-search-v9-5.js">Ps/202609071213-place-global-search-v9-5.js</a></td><td>script</td><td class="wait res">waiting</td></tr>
<tr data-file="Ps/202609040219-transit-layer-availability.browser.mjs"><td>16</td><td class="mono">Ps</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/tools/proofs/202609040219-transit-layer-availability.browser.mjs">Ps/202609040219-transit-layer-availability.browser.mjs</a></td><td>module</td><td class="wait res">waiting</td></tr … [line shortened here: 401 characters; full line on GitHub]
<tr data-file="Ps/202609040229-arrival-identity.browser.mjs"><td>17</td><td class="mono">Ps</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/tools/proofs/202609040229-arrival-identity.browser.mjs">Ps/202609040229-arrival-identity.browser.mjs</a></td><td>module</td><td class="wait res">waiting</td></tr>
<tr data-file="Ps/202608282348-verify-v9-6-2-equivalence.mjs"><td>18</td><td class="mono">Ps</td><td class="mono"><a href="https://github.com/Ventusltd/pipelinenews/blob/4980096b57cb35f63ad2d80bded5687beb2a9532/atman/202608282348-verify-v9-6-2-equivalence.mjs">Ps/202608282348-verify-v9-6-2-equivalence.mjs</a></td><td>module</td><td class="wait res">waiting</td></tr>
<tr data-file="Dt/review.py"><td>19</td><td class="mono">Dt</td><td class="mono"><a href="https://github.com/Ventusltd/chatgpt-audits/blob/2ffb435d105d3729be764e20f1fce6720d681133/automation/202608310209-hourly-logic-review/review.py">Dt/review.py</a></td><td>python</td><td class="muted res">Python: not loadable in a page</td></tr>
<tr data-file="Dt/202608310050-build-n1-deep-link-candidates.py"><td>20</td><td class="mono">Dt</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/202608310050-gridatlas-next-version-builders/tools/202608310050-build-n1-deep-link-candidates.py">Dt/202608310050-build-n1-deep-link-candidates.py</a></td><td>python</td><td class="muted … [line shortened here: 445 characters; full line on GitHub]
<tr data-file="Dt/202608310050-build-repd-ref-index.py"><td>21</td><td class="mono">Dt</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/202608310050-gridatlas-next-version-builders/tools/202608310050-build-repd-ref-index.py">Dt/202608310050-build-repd-ref-index.py</a></td><td>python</td><td class="muted res">Python: not loadable i … [line shortened here: 418 characters; full line on GitHub]
<tr data-file="Dt/202608310050-calibrate-design-freeze.py"><td>22</td><td class="mono">Dt</td><td class="mono"><a href="https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/202608310050-gridatlas-next-version-builders/tools/202608310050-calibrate-design-freeze.py">Dt/202608310050-calibrate-design-freeze.py</a></td><td>python</td><td class="muted res">Python: not l … [line shortened here: 427 characters; full line on GitHub]
</tbody></table></div>
<p class="amber">Untested combinations: Si+Vn, Vn+Ug, Vn+Ps, Vn+Dt. Whatever this page reports for their files is the first evidence.</p>
</div>
<div class="card">
<h2>Provided by the browser</h2>
<p class="muted">Names the parts use that a web browser supplies. Checked when the page opens.</p>
<div class="mono" id="provided"><span data-provided="alert">alert</span> · <span data-provided="atob">atob</span> · <span data-provided="Blob">Blob</span> · <span data-provided="CompressionStream">CompressionStream</span> · <span data-provided="createImageBitmap">createImageBitmap</span> · <span data-provided="crypto">crypto</span> · <span data-provided="document">document</span> · <span data-pr … [line shortened here: 1,299 characters; full line on GitHub]
<details><summary>51 other names the table listed as needs, and why nothing is written for them</summary><div class="wrap"><table><thead><tr><th>name</th><th>what it is</th></tr></thead><tbody><tr><td class="mono">position</td><td>defined by another block of the table: add it (Sa)</td></tr><tr><td class="mono">resolve</td><td>defined by another block of the table: add it (Ss, Wf)</td></tr><tr><t … [line shortened here: 5,017 characters; full line on GitHub]
</div>
<script type="application/json" id="plan">{"name":"substation-finder","title":"Substation finder on a map","generated_utc":"2026-09-14T13:00:52.380Z","plan":[{"part":"Si","title":"substation-intelligence","saved":"Si/202609062358-substation-intelligence-v9-63.js","kind":"script","load":true,"source":"https://github.com/Ventusltd/gridatlas/blob/ece848117a6d21b7fccb232557194877698c48a9/atlas/cartrid … [line shortened here: 12,755 characters; full line on GitHub]
<script>
(function () {
var plan = JSON.parse(document.getElementById('plan').textContent);
var $ = function (s) { return document.querySelector(s); };
var rows = {}; plan.plan.forEach(function (f) { rows[f.saved] = document.querySelector('tr[data-file="' + f.saved.replace(/"/g, '"') + '"] .res'); });
var current = null, errors = {};
function note(file, cls, text) { var r = rows[file]; if (!r) return; r.className = 'res ' + cls; r.textContent = text; }
window.addEventListener('error', function (e) {
var file = current; var src = e.filename || '';
plan.plan.forEach(function (f) { if (src && src.indexOf(f.saved) >= 0) file = f.saved; });
if (!file) return; errors[file] = (errors[file] || []).concat([(e.message || String(e.error || e))]);
note(file, 'bad', 'threw: ' + errors[file].join(' | '));
});
window.addEventListener('unhandledrejection', function (e) { if (!current) return; var m = e.reason && e.reason.message || String(e.reason); errors[current] = (errors[current] || []).concat([m]); note(current, 'bad', 'rejected: ' + errors[current].join(' | ')); });
plan.provided.forEach(function (n) { var el = document.querySelector('[data-provided="' + n + '"]'); var ok; try { ok = typeof window[n] !== 'undefined' || (n in window); } catch (x) { ok = false; } if (el) el.className = ok ? 'ok' : 'bad'; });
function applyInputs() {
var missing = [];
Array.prototype.forEach.call(document.querySelectorAll('input[data-need]'), function (i) {
var v = i.value.trim(), n = i.dataset.need;
if (!v) { missing.push(n); return; }
try { if (/^function|^class/.test(i.dataset.type)) window[n] = (0, eval)('(' + v + ')'); else if (/^library/.test(i.dataset.type)) window['__lib_' + n] = v; else { try { window[n] = JSON.parse(v); } catch (x) { window[n] = v; } } }
catch (x) { missing.push(n + ' (' + x.message + ')'); }
});
return missing;
}
function loadOne(f) {
return new Promise(function (resolve) {
current = f.saved;
var s = document.createElement('script'); if (f.kind === 'module') s.type = 'module'; s.src = f.saved;
s.onload = function () { setTimeout(function () { if (!errors[f.saved]) note(f.saved, 'ok', 'loaded'); current = null; resolve(); }, 0); };
s.onerror = function () { note(f.saved, 'bad', 'failed to load (not served, or a module that could not be fetched)'); current = null; resolve(); };
note(f.saved, 'wait', 'loading…'); document.body.appendChild(s);
});
}
function loadLib(url) { return new Promise(function (resolve) { var s = document.createElement('script'); s.src = url; s.onload = resolve; s.onerror = resolve; document.body.appendChild(s); }); }
$('#go').onclick = function () {
var missing = applyInputs();
var libs = Object.keys(window).filter(function (k) { return k.indexOf('__lib_') === 0; }).map(function (k) { return window[k]; });
$('#go').disabled = true; $('#state').textContent = missing.length ? 'loading without ' + missing.join(', ') : 'loading';
var q = Promise.resolve(); libs.forEach(function (u) { q = q.then(function () { return loadLib(u); }); });
plan.plan.filter(function (f) { return f.load; }).forEach(function (f) { q = q.then(function () { return loadOne(f); }); });
q.then(function () { var bad = Object.keys(errors).length, all = plan.plan.filter(function (f) { return f.load; }).length; $('#state').textContent = (all - bad) + ' of ' + all + ' file' + (all === 1 ? '' : 's') + ' loaded clean' + (bad ? '; ' + bad + ' threw' : '') + (missing.length ? '; still missing ' + missing.join(', ') : ''); $('#state').className = bad || missing.length ? 'amber' : 'ok'; … [line shortened here: 404 characters; full line on GitHub]
};
if (!plan.inputs.length && location.search.indexOf('auto') >= 0) $('#go').click();
})();
</script>
</html>