In this section
- Document Context Test test · gridatlas / tools/vicinity/document-context.test.mjs lines 1–103
- Model Test test · gridatlas / tools/vicinity/model.test.mjs lines 1–88
- Asset Context transform · gridatlas / tools/vicinity/src/asset-context.mjs lines 1–54
- Bootstrap interaction · gridatlas / tools/vicinity/src/bootstrap.js lines 1–347
- Document Context transform · gridatlas / tools/vicinity/src/document-context.mjs lines 1–94
Document Context Test
A test in the vicinity folder of GridAtlas that checks Document Context and Declared Connections, using SHA-256.
testgridatlas / tools/vicinity/document-context.test.mjs · lines 1–103 of 103 · Entry point
- What it does
- It tests the REPD register and substations. Uses libraries node:test, node:assert/strict, node:fs, node:vm, node:crypto. Side effects: changes the web page (DOM); reads or writes files.
- 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: the REPD register, substations.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/vicinity · test
- Uses
- Document Context (import), Declared Connections (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm, node:crypto
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- 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
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity/document-context.test.mjs:1-103 · blob 2fba74bc192416f8e38a06da6ffd35ed5489d6e4 · 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: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {createHash} from 'node:crypto';
import {DOCUMENT_CONTEXT_PROVENANCE, DOCUMENT_CONTEXT_NOTICES, documentContextFor} from './src/document-context.mjs';
const source = fs.readFileSync(new URL('../../atlas/modules/202609012128-declared-connections.js', import.meta.url), 'utf8').replace(/\r\n/g, '\n');
const context = {window: {__GRIDATLAS_MODULES__: {geodesy: {distanceKm() { throw Error('No distance calculation permitted'); }}}}};
vm.runInNewContext(source, context);
const canonical = context.window.__GRIDATLAS_MODULES__.declaredConnections;
test('canonical declaration input matches its immutable provenance pin', () => {
const pin = DOCUMENT_CONTEXT_PROVENANCE.declaredModule;
assert.equal(Buffer.byteLength(source), pin.bytes);
assert.equal(createHash('sha256').update(source).digest('hex'), pin.sha256);
assert.match(pin.sourceUrl, new RegExp('/blob/' + pin.commit + '/'));
});
test('exact REPD owner keys reuse declared works without promoting or mutating owner classification', () => {
const before = JSON.stringify(canonical.records['14806']);
const result = documentContextFor({type: 'repd', id: 'repd:14806'}, {declaredConnections: canonical});
assert.equal(result.matchedRecords.length, 1);
const record = result.matchedRecords[0];
assert.equal(record.declaredStatus, 'not_built');
assert.equal(record.declaration.poc_status_note, canonical.records['14806'].poc_status_note);
assert.equal(record.sourceTitle, canonical.records['14806'].source);
assert.equal(record.verifiedAssetAssociation, false);
assert.equal(record.status, 'EXISTING_PUBLISHED_DECLARATION_UNREVALIDATED');
assert.equal(result.verifiedAssetJoins, 0);
assert.equal(JSON.stringify(canonical.records['14806']), before);
});
test('absent status, dates, capacity and inferred electrical connections stay unknown', () => {
const result = documentContextFor({type: 'repd', id: 'repd:10914'}, {declaredConnections: canonical});
const record = result.matchedRecords[0];
assert.equal(record.declaredStatus, null);
assert.equal(record.date, null);
assert.equal(record.datePrecision, 'UNKNOWN');
assert.equal(Object.hasOwn(record, 'capacityMw'), false);
assert.equal(result.realConnectionsInferred, 0);
});
test('nearby coordinates, matching names and a different asset type do not produce joins', () => {
for (const origin of [{type: 'substation', id: 'grid_substations:14806', name: 'High Marnham Substation', at: [-0.8, 53]}, {type: 'datacentre', id: '14806'}, {type: 'repd', id: 'repd:2470', name: 'Sea Link'}, {type: 'repd', id: 'repd:014806'}]) {
assert.equal(documentContextFor(origin, {declaredConnections: canonical}).matchedRecords.length, 0);
}
});
test('missing or unsupported identity and an absent canonical owner module give explicit gaps', () => {
for (const origin of [null, {type: 'location', id: '14806'}, {type: 'repd', id: 14806}, {type: 'repd', id: 'repd:14806\n'}]) {
const result = documentContextFor(origin, {declaredConnections: canonical});
assert.equal(result.origin, null);
assert.equal(result.matchedRecords.length, 0);
assert.match(result.limitations[0], /stable source identity/);
}
assert.equal(documentContextFor({type: 'repd', id: 'repd:14806'}).matchedRecords.length, 0);
});
test('inherited source arrays or wrong module schemas cannot supply an exact declaration', () => {
const inherited = Object.create({'14806': canonical.records['14806']});
assert.equal(documentContextFor({type: 'repd', id: 'repd:14806'}, {declaredConnections: {schema: canonical.schema, records: inherited}}).matchedRecords.length, 0);
assert.equal(documentContextFor({type: 'repd', id: 'repd:14806'}, {declaredConnections: {schema: 'other', records: canonical.records}}).matchedRecords.length, 0);
});
test('Sea Link stays standalone even when an origin has the same name or location', () => {
const result = documentContextFor({type: 'substation', id: 'unmatched', name: 'Sea Link', at: [1.5, 52]});
assert.equal(result.unassociatedNotices.length, 1);
const notice = result.unassociatedNotices[0];
assert.equal(notice.applicationRef, 'EN020026');
assert.equal(notice.verifiedAssetJoins, 0);
for (const key of ['currentCapacityMw', 'commissioned', 'connection', 'repdRef', 'coordinates']) assert.equal(notice[key], null);
assert.deepEqual(notice.date, {value: '2026-10-30', precision: 'DAY'});
assert.equal(notice.plannedMetric.kind, 'planned_transmission_upper_bound');
assert.equal(notice.plannedMetric.value, 2000);
assert.match(notice.scope, /No association/);
});
test('two government sources preserve historical hashes and qualify changed current HTML separately', () => {
const notice = DOCUMENT_CONTEXT_NOTICES[0];
assert.equal(notice.sources.length, 2);
for (const source of notice.sources) {
assert.equal(new URL(source.url).origin, 'https://www.gov.uk');
assert.equal(source.sourceUpdatedAt, null);
assert.notEqual(source.archivedReceipt.sha256, source.currentObservation.sha256);
assert.match(source.currentObservation.scope, /differs from archived/);
assert.equal(source.archivedReceipt.bytes, source.currentObservation.bytes);
}
assert.equal(notice.rightsScope, 'government_html_facts_only_no_images_or_third_party_material');
assert.equal(DOCUMENT_CONTEXT_PROVENANCE.noticeProducer.reviewReferences.length, 2);
});
test('output and source metadata are immutable and contain no generated route geometry', () => {
const result = documentContextFor({type: 'repd', id: 'repd:10914'}, {declaredConnections: canonical});
assert.equal(Object.isFrozen(result), true);
assert.equal(Object.isFrozen(result.matchedRecords[0].declaration), true);
assert.throws(() => { result.matchedRecords[0].declaration.source = 'changed'; });
assert.equal(Object.hasOwn(result, 'geometry'), false);
});
test('every pinned owner declaration retains its exact source fields, including circuit and unbuilt cases', () => {
const refs = Object.keys(canonical.records);
assert.equal(refs.length, 19, 'Source records, not unique schemes or physical upgrades');
for (const ref of refs) {
const result = documentContextFor({type: 'repd', id: 'repd:' + ref}, {declaredConnections: canonical});
assert.equal(result.matchedRecords.length, 1, ref);
const record = result.matchedRecords[0], raw = canonical.records[ref];
for (const key of Object.keys(raw)) assert.equal(record.declaration[key], raw[key], ref + ':' + key);
assert.equal(record.declaredStatus, raw.poc_status ?? null);
assert.equal(result.counts.verifiedAssetJoins, 0);
}
});Model Test
A test in the vicinity folder of GridAtlas that checks Model and Build, using SHA-256.
testgridatlas / tools/vicinity/model.test.mjs · lines 1–88 of 88 · Entry point · pattern feature (shared by 12 files)
- What it does
- It tests the REPD register and wind. Defines feature. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
- 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: the REPD register, wind.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `feature`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/vicinity · test
- Uses
- Model (import), Build (import), Geodesy (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- feature
- Defines here
- feature
- 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/vicinity/model.test.mjs:1-88 · blob 5945bd8638f0e63fe8387ff5fe48f8484de0746e · 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: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, stationRecords, exploreVicinity, vicinityGeoJSON, VOLTAGE_BANDS, validateNewsContextBase, newsContextHref} from './src/model.mjs';
import {assemble, BUDGET} from './build.mjs';
const context = {window: {}};
vm.runInNewContext(fs.readFileSync(new URL('../../atlas/modules/202609011950-geodesy.js', import.meta.url), 'utf8'), context);
const geodesy = context.window.__GRIDATLAS_MODULES__.geodesy;
const origin = {at: [-0.1,51.5], type: 'repd', id: 'repd:2470', name: 'Chosen real project'};
const link = '?journey=vicinity&origin_type=repd&origin_id=repd%3A2470&latitude=51.5&longitude=-0.1&radius_km=10';
const feature = (id, at, voltage, extra = {}) => ({type:'Feature',id,geometry:{type:'Point',coordinates:at},properties:{name:id,voltage,...extra}});
test('radius accepts whole km only, including both boundaries; invalid values do not become defaults', () => {
assert.equal(radiusKm(1),1); assert.equal(radiusKm('50'),50);
for (const v of [0,51,1.5,'1.5',null,'',undefined,Infinity,NaN,true,false,[2],{},1n]) assert.throws(() => radiusKm(v));
});
test('origin coordinates do not accept nulls, strings, null-island or out-of-range positions', () => {
for (const at of [[null,51],['-1',51],[0,0],[181,51],[-1,91],[NaN,51]]) assert.equal(validCoordinate(at),false);
assert.equal(validCoordinate([0,51.5]),true); assert.equal(validCoordinate([-1,0]),true);
assert.deepEqual(normaliseOrigin(origin),origin);
});
test('one URL intent consumer preserves opaque identity and explicitly rejects missing/ambiguous fields', () => {
assert.deepEqual(parseVicinityIntent(link),{origin:{...origin,name:'repd repd:2470'},radiusKm:10});
assert.equal(parseVicinityIntent('?repd_ref=2470'),null);
for (const bad of [link.replace('radius_km=10','radius_km=1.5'),link+'&longitude=1',link.replace('origin_id=repd%3A2470','origin_id='),link.replace('origin_type=repd','origin_type=unknown'),link.replace('latitude=51.5','latitude='),link.replace('longitude=-0.1','longitude=null')]) assert.throws(() => parseVicinityIntent(bad));
for (const type of ['datacentre','substation']) assert.equal(parseVicinityIntent(link.replace('origin_type=repd','origin_type='+type)).origin.type,type);
});
test('originless entry requests explicit manual selection and rejects every partial origin tuple', () => {
assert.deepEqual(parseVicinityIntent('?journey=vicinity'),{manual:true,radiusKm:10});
assert.deepEqual(parseVicinityIntent('?journey=vicinity&radius_km=50'),{manual:true,radiusKm:50});
for (const extra of ['origin_id=x','origin_type=','latitude=51.5','longitude=-0.1','origin_type=repd&origin_id=repd:2470','radius_km=1.5','radius_km=10&radius_km=20']) assert.throws(()=>parseVicinityIntent('?journey=vicinity&'+extra));
const optional=parseVicinityIntent('?journey=vicinity&news_context_url=https%3A%2F%2Fevil.test%2F');assert.equal(optional.manual,true);assert.match(optional.newsContextError,/not applied/);
});
test('canonical voltage parser keeps explicit units and unknown values; missing IDs remain missing', () => {
const rows = stationRecords([feature('volts',[-0.11,51.5],'33000;11000'),feature('traction',[-0.12,51.5],'750'),feature('unknown',[-0.13,51.5],null),feature('kv',[-0.14,51.5],null,{kv:'132'}),{geometry:{type:'Point',coordinates:[-0.15,51.5]},properties:{name:'No source ID'}}],geodesy);
assert.deepEqual(rows[0].kv,[33,11]); assert.deepEqual(rows[0].bands,['33','11']);
assert.deepEqual(rows[1].kv,[0.75]); assert.deepEqual(rows[1].bands,['other']);
assert.deepEqual(rows[2].kv,[]); assert.deepEqual(rows[2].bands,['unknown']);
assert.deepEqual(rows[3].kv,[132]); assert.equal(rows[4].id,null);
});
test('deduplicates tile repeats, filters only matching known voltage bands and reports all matches before display cap', () => {
const a = feature('A',[-0.11,51.5],'33000'), b = feature('B',[-0.12,51.5],'11000');
const rows = stationRecords([a,a,b,feature('Far',[2,51.5],'33000')],geodesy);
assert.equal(rows.length,3);
const result = exploreVicinity({origin,radius:10,records:rows,bands:['33'],geodesy,limit:1});
assert.equal(result.matching,1); assert.equal(result.shown[0].name,'A');
assert.equal(result.loadedRecords,3); assert.equal(result.truncated,false);
const capped = exploreVicinity({origin,radius:10,records:rows,bands:['33','11'],geodesy,limit:1});
assert.equal(capped.matching,2); assert.equal(capped.truncated,true); assert.equal(capped.shown.length,1);
assert.equal(exploreVicinity({origin,radius:10,records:rows,bands:[],geodesy}).matching,0);
});
test('inclusive exact-radius test delegates distance to canonical engine; no electrical graph is created', () => {
const edge = geodesy.destinationPoint(...origin.at,10,90), outside = geodesy.destinationPoint(...origin.at,10.01,90);
const rows = stationRecords([feature('Near',origin.at,'33000'),feature('Outside',outside,'33000')],geodesy);
const result = exploreVicinity({origin,radius:10,records:rows,bands:['33'],geodesy});
assert.equal(result.matching,1); assert.equal(result.shown[0].km,0);
assert.ok(geodesy.distanceKm(...origin.at,...edge) > 9.9999);
assert.match(result.statement,/connectivity unknown/);
assert.equal('edges' in result,false);
});
test('radius geometry uses canonical destinationPoint and retains actual point coordinates', () => {
const rows = stationRecords([feature('A',[-0.11,51.5],'33000')],geodesy);
const result = exploreVicinity({origin,radius:50,records:rows,bands:['33'],geodesy});
const geo = vicinityGeoJSON(result,geodesy), boundary = geo.features[0];
assert.equal(boundary.properties.kind,'radius'); assert.equal(boundary.geometry.coordinates.length,97);
for (const at of boundary.geometry.coordinates) assert.ok(Math.abs(geodesy.distanceKm(...origin.at,...at)-50)<1e-8);
assert.deepEqual(geo.features[2].geometry.coordinates,[-0.11,51.5]);
assert.equal(geo.features.filter(f=>f.geometry.type==='LineString').length,1,'radius boundary only; no inferred circuit');
});
test('module source rebuild is deterministic, generation stamped, bounded and syntactically valid', () => {
const first=assemble({generation:'202611180100'}),second=assemble({generation:'202611180100'});
assert.equal(first.body,second.body); assert.equal(first.sha256,second.sha256); assert.ok(first.bytes<BUDGET);
new vm.Script(first.body); assert.match(first.body,/USER_ASSUMED_LOCAL_MODEL/);
assert.equal(VOLTAGE_BANDS.length,8); assert.throws(()=>assemble({generation:'../bad'}));
});
test('news return links accept only supplied dated exact-host bases and build bounded topic context', () => {
const base='https://globalgrid2050.com/uk_renewables_pipeline/202611171940/';
assert.equal(validateNewsContextBase(base),base); assert.equal(validateNewsContextBase(base+'index.html'),base+'index.html');
for(const bad of [base+'?url=https://evil.test',base+'#x',base.replace('https:','http:'),base.replace('.com/','.com:443/'),base.replace('.com/','.com.evil.test/'),base.replace('globalgrid2050.com','user@globalgrid2050.com'),base.replace('202611171940/','latest/'),'javascript:alert(1)'])assert.throws(()=>validateNewsContextBase(bad));
const url=new URL(newsContextHref(base,origin,'wind'));
assert.equal(url.searchParams.get('news_origin_id'),'repd:2470');assert.equal(url.searchParams.get('news_topic'),'wind');assert.equal(url.hash,'#headlinesHeading');
assert.deepEqual([...url.searchParams.keys()],['news_origin_type','news_origin_id','news_topic']);
const intent=parseVicinityIntent(link+'&news_context_url='+encodeURIComponent(base)+'&news_topic=wind');assert.equal(intent.newsContextUrl,base);assert.equal(intent.newsTopic,'wind');
for(const optional of ['&news_context_url='+encodeURIComponent(base)+'&news_topic=bad','&news_context_url=https%3A%2F%2Fevil.test%2F','&news_context_url='+encodeURIComponent(base)+'&news_context_url='+encodeURIComponent(base)]) {
const degraded=parseVicinityIntent(link+optional);assert.equal(degraded.origin.id,'repd:2470');assert.equal(degraded.radiusKm,10);assert.match(degraded.newsContextError,/not applied/);assert.equal(degraded.newsContextUrl,undefined);
}
});Asset Context
A JavaScript module in the vicinity folder of GridAtlas that works with the Renewable Energy Planning Database (REPD) register.
transformgridatlas / tools/vicinity/src/asset-context.mjs · lines 1–54 of 54 · Not reached from any entry point (candidate for review) · pattern collectAssetContext (shared by 3 files)
- What it does
- It calculates the REPD register. Defines 6 functions or classes, including assetCoordinate, statedMw, assetId, collectAssetContext, get.
- 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: the REPD register.
- What it achieves
- It is built from the asset coordinate helper (`assetCoordinate`), the stated MW helper (`statedMw`) and the asset id helper (`assetId`). Read-only context from existing Atlas source owners.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/vicinity/src · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- ASSET_CONTEXT_CATEGORIES, collectAssetContext
- Defines here
- assetCoordinate, statedMw, assetId, collectAssetContext, get, add
- 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/vicinity/src/asset-context.mjs:1-54 · blob b6352b5af6730906c9733d23a78b8489e8a5a8c9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Read-only context from existing Atlas source owners. No fetching or electrical inference. */
export const ASSET_CONTEXT_CATEGORIES = Object.freeze([
['generation','REPD generation context'],['storage','REPD storage context'],['datacentre','Data-centre listings'],
['conventional','Listed conventional power context'],['demand-context','Other potential demand context']
]);
const assetCoordinate = at => Array.isArray(at)&&at.length>=2&&at.slice(0,2).every(v=>typeof v==='number'&&Number.isFinite(v))&&Math.abs(at[0])<=180&&Math.abs(at[1])<=90&&(at[0]!==0||at[1]!==0);
const statedMw = value => {const v=value&&typeof value==='object'?value.value:value;if(typeof v!=='number'&&typeof v!=='string')return null;if(typeof v==='string'&&!/^\d+(?:\.\d+)?$/.test(v.trim()))return null;const n=Number(v);return Number.isFinite(n)&&n>0?n:null;};
const assetId = value => (typeof value==='string'||typeof value==='number')&&String(value).trim()&&String(value).length<=256?String(value).trim():null;
function assetPrecision(p){for(const [field,value]of[['location.precision',p.location?.precision],['coordinate_precision',p.coordinate_precision],['location_precision',p.location_precision]])if(typeof value==='string'&&value.trim())return{precision:value,precisionField:field,approximateLocation:/approx|centroid|postcode|settlement|area/i.test(value)};return{precision:null,precisionField:null,appro … [line shortened here: 423 characters; full line on GitHub]
export function collectAssetContext({map,registry={},origin,radiusKm,geodesy,limit=200}={}){
const at=origin?.at;
if(!assetCoordinate(at)||!Number.isInteger(radiusKm)||radiusKm<1||radiusKm>50)throw Error('Located origin and integer radius 1-50 km are required.');
if(!geodesy?.distanceKm||!geodesy?.representativePoint)throw Error('Canonical Atlas geodesy is required.');
if(!Number.isInteger(limit)||limit<1||limit>200)throw Error('Asset result limit must be 1-200.');
const categories=ASSET_CONTEXT_CATEGORIES.map(([id,label])=>({id,label,availability:'NOT_LOADED',source:null,count:0,loadedRecords:0,truncated:false,rows:[]}));
const get=id=>categories.find(c=>c.id===id),seen=new Map(categories.map(c=>[c.id,new Set()]));
function add(category,row){
const c=get(category);c.loadedRecords++;
if(!assetCoordinate(row.at))return;
// Source IDs deduplicate records; coincident coordinates alone never merge facilities.
const key=row.id===null?null:row.source+'|'+row.id;
if(key!==null){if(seen.get(category).has(key))return;seen.get(category).add(key);}
const km=geodesy.distanceKm(at[0],at[1],row.at[0],row.at[1]);
if(!Number.isFinite(km)||km<0||km>radiusKm)return;
c.rows.push({...row,at:row.at.slice(0,2),km,demandMw:null,facilityVerified:null,connection:null});
}
let features=null;
try{const data=map?.getSource?.('src-repd')?.serialize?.().data;if(data?.type==='FeatureCollection'&&Array.isArray(data.features)&&data.features.length)features=data.features;}catch{/* Explicit NOT_LOADED below; no replacement fetch. */}
if(features){
for(const id of ['generation','storage'])Object.assign(get(id),{availability:'LOADED',source:'Existing loaded src-repd GeoJSON'});
features.forEach((f,i)=>{
const p=f?.properties||{},point=geodesy.representativePoint(f?.geometry),tech=String(p.tech||p.technology||p.technology_type||'Not stated');
const category=/^(?:bess(?:[_ -].*)?|battery(?:[_ -].*)?|storage|flywheel|caes)$/i.test(tech)?'storage':'generation';
const ref=assetId(p.repd_ref??p.ref_id),id=ref??assetId(p.id??f?.id);
add(category,{id,originId:ref&&/^\d+$/.test(ref)?'repd:'+ref:null,name:String(p.name||'Unnamed REPD record'),at:point,kind:category,status:String(p.status||'Not stated'),technology:tech,
capacityMw:statedMw(p.capacity_mw??p.capacity),capacityBasis:typeof p.capacity_basis==='string'?p.capacity_basis:'REGISTER_STATED_POWER_BASIS_NOT_DECLARED',
metrics:{itLoadMw:null,gridConnectionMw:null,unclassifiedMw:null},...assetPrecision(p),source:'src-repd',sourceRow:i});
});
}
const owner=registry.ukOfftakers?.state, data=owner?.data, dots=Array.isArray(data?.dots)?data.dots:null;
if(dots){
for(const id of ['datacentre','conventional','demand-context'])Object.assign(get(id),{availability:'LOADED',source:id==='conventional'?'Loaded potential-offtaker power-station listing; not the full conventional dataset':'Existing loaded off-taker owner records'});
dots.forEach((r,i)=>{
const p=r?.p||{},category=r?.k==='c'?'datacentre':r?.k==='b'?'conventional':['a','d','s','e'].includes(r?.k)?'demand-context':null;if(!category)return;
const id=assetId(p.id??r.id),size=p.size_metric;
const capacity=category==='conventional'?(typeof size?.unit==='string'&&/^MW(?:\b|_)/.test(size.unit)?statedMw(size.value):statedMw(p.mw)):null;
add(category,{id,originId:id,name:String(r.n||p.name||'Unnamed listed site'),at:r.a,kind:category,status:String(p.status||'Not stated'),technology:String(p.technology||p.fuel||r.sub||'Not stated'),
capacityMw:capacity,capacityBasis:capacity===null?null:'SOURCE_STATED_POWER_NOT_CURRENT_OUTPUT',metrics:category==='datacentre'?{itLoadMw:statedMw(p.it_load_mw),gridConnectionMw:statedMw(p.grid_connection_mw),unclassifiedMw:statedMw(p.unclassified_mw)}:{itLoadMw:null,gridConnectionMw:null,unclassifiedMw:null},
...assetPrecision(p),source:category==='datacentre'&&r.dc?'ukOfftakers.data-centre-pipeline':'ukOfftakers.loaded-listing',sourceRow:i});
});
}
for(const c of categories){c.rows.sort((a,b)=>a.km-b.km||a.name.localeCompare(b.name,'en')||String(a.id).localeCompare(String(b.id),'en'));c.count=c.rows.length;c.truncated=c.count>limit;c.rows=c.rows.slice(0,limit);}
return{categories,radiusKm,connectionsInferred:0,limitations:['Loaded source records only; NOT_LOADED is not zero nearby assets.','Register power, IT load and connection figures remain separate; demand and present output are unknown.','A supplied location and source ID do not verify a facility or its connections; source precision is retained.']};
}Bootstrap
A JavaScript file in the vicinity folder of GridAtlas that maps substations and the Renewable Energy Planning Database (REPD) register.
interactiongridatlas / tools/vicinity/src/bootstrap.js · lines 1–347 of 347 · Not reached from any entry point (candidate for review) · pattern renderDocumentContext (shared by 2 files)
- What it does
- It maps substations and the REPD register. Defines 31 functions or classes, including createController, el, listen, sourceAnchor, rowOrigin. Side effects: changes the web page (DOM); reads or writes files.
- 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: substations, the REPD register, 33kV. README: "`build.mjs` deterministically assembles `src/model.mjs`, `src/bootstrap.js` and `src/vicinity.css` into one bounded module."
- Inputs & outputs
- Voltage levels named: 33kV.
- What it achieves
- It creates controller (`createController`), renders asset context (`renderAssetContext`) and renders document context (`renderDocumentContext`). The README says: `build.mjs` deterministically assembles `src/model.mjs`, `src/bootstrap.js` and `src/vicinity.css` into one bounded module. Its code works with 33 kV. It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/vicinity/src · script
- Uses
- none found
- Used by
- none found
- Produces
- createController, el, listen, sourceAnchor, rowOrigin, text, renderAssetContext, renderDocumentContext, readRecords, draw, removeMap, showError
- Defines here
- createController, el, listen, sourceAnchor, rowOrigin, text, renderAssetContext, renderDocumentContext, readRecords, draw, removeMap, showError, clearNews, clearSelectedContext, addStation, refresh, setOrigin, mapCentre, fitRadius, installControls, open, shut, clicked, sourced, styled, removed, onIntent, onCard, destroy, mount
- 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/vicinity/src/bootstrap.js:1-347 · blob bac7add0a406738c19cde3dbf53ab877e26f2fd6 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const W = window, D = document, NS = W.__GRIDATLAS_MODULES__ = W.__GRIDATLAS_MODULES__ || {};
if (!NS.gridVicinity) {
let controller = null, timer = null, stopped = false, pendingIntent = null, intentError = null;
try { pendingIntent = parseVicinityIntent(W.location.search); } catch (error) { intentError = error.message; }
function createController(map) {
const geodesy = NS.geodesy;
if (!geodesy?.distanceKm || !geodesy?.voltagesKv || !geodesy?.representativePoint) throw new Error('Canonical Atlas geodesy is not ready.');
const host = map.getContainer(), prior = D.getElementById('gridatlas-vicinity');
if (prior) throw new Error('Vicinity UI already mounted.');
let alive = true, opened = false, origin = null, radius = 10, picking = false, result = null, records = [], contextSource = 'No loaded substation data', error = null, phase = 'CHOOSE_ORIGIN';
let source = null, sourceUnavailable = false, selectionEpoch = 0, refreshTimer = null, returning = null, newsBase = null, newsTopic = null, assetContext = null, documentContext = null, assetSignature = null, stationSignature = null, documentSignature = null;
const categoryElements = new Map();
const bands = new Set(VOLTAGE_BANDS.map(b => b[0])), listeners = [], groups = [], controls = [], ownedLayers = new Map();
const SOURCE = 'gridatlas-vicinity-context', LAYERS = ['gridatlas-vicinity-radius', 'gridatlas-vicinity-points', 'gridatlas-vicinity-model'];
const root = D.createElement('div'); root.id = 'gridatlas-vicinity'; host.appendChild(root);
const style = D.createElement('style'); style.textContent = VICINITY_CSS; root.appendChild(style);
function el(tag, text, parent, attrs = {}) { const e = D.createElement(tag); if (text != null) e.textContent = text; for (const [k,v] of Object.entries(attrs)) e.setAttribute(k, v); parent?.appendChild(e); return e; }
function listen(target, type, fn) { target.addEventListener(type, fn); listeners.push(() => target.removeEventListener(type, fn)); }
const launch = el('button', 'Great Grid Journeys', root, {type: 'button', class: 'vic-launch', 'aria-expanded': 'false', 'aria-controls': 'gridatlas-vicinity-panel'});
const panel = el('section', null, root, {id: 'gridatlas-vicinity-panel', class: 'vic-panel', 'aria-label': 'Vicinity familiarisation'}); panel.hidden = true;
const heading = el('div', null, panel, {class: 'vic-head'}); el('h2', 'Explore the nearby grid', heading);
const close = el('button', 'Close', heading, {type: 'button', 'aria-label': 'Close vicinity explorer'});
const compact=el('section',null,root,{class:'vic-train-compact','aria-label':'Journey map controls'});compact.hidden=true;
const compactActions=el('div',null,compact,{class:'vic-actions'});
const compactPause=el('button','Pause',compactActions,{type:'button','aria-label':'Pause journey'}),compactPrevious=el('button','Previous',compactActions,{type:'button','aria-label':'Previous journey stop'}),compactNext=el('button','Next',compactActions,{type:'button','aria-label':'Next journey stop'}),compactEdit=el('button','Edit',compactActions,{type:'button','aria-label':'Edit journey'});
const compactStatus=el('p','Learning cursor; electrical flow unknown.',compact,{role:'status'});
const mapLegend=el('p','Solid — reviewed GIS. Long dash — topology (schematic). Dotted — SIMULATED. Proposed pin — FEED concept. Electrical flow and rights unknown.',root,{class:'vic-train-map-legend'});mapLegend.hidden=true;
const originLabel = el('p', '', panel, {class: 'vic-origin'});
const originPrecision = el('p', 'Source-provided location; coordinate precision not supplied.', panel, {class: 'vic-origin-precision'});
el('p', 'Spatial vicinity, connectivity unknown. Mapped points and voltage tags are context, not capacity or an electrical path.', panel, {class: 'vic-caption'});
const actions = el('div', null, panel, {class: 'vic-actions'});
const centre = el('button', 'Use map centre', actions, {type: 'button'});
const pick = el('button', 'Pick origin on map', actions, {type: 'button', 'aria-pressed': 'false'});
const fit = el('button', 'Fit radius', actions, {type: 'button'});
const physical = el('button', 'Show physical grid', actions, {type: 'button'});
const news = el('a', 'News context', actions, {target: '_blank', rel: 'noopener noreferrer', 'aria-label': 'Open news topic context in the supplied dated edition'}); news.hidden = true;
news.style.cssText = 'display:inline-flex;align-items:center;min-height:44px;padding:7px 10px;color:#0ff;background:#061216;border:1px solid #367078';
const newsCaption = el('p', 'Topic context only; a headline is not an association with this asset.', panel, {class: 'vic-news-caption'}); newsCaption.hidden = true;
const radial = el('fieldset', null, panel); el('legend', 'Radius in whole kilometres', radial);
const rangeLabel = el('label', '', radial, {for: 'gridatlas-vicinity-radius-input'});
const slider = el('input', null, radial, {id: 'gridatlas-vicinity-radius-input', type: 'range', min: '1', max: '50', step: '1', value: '10', 'aria-label': 'Vicinity radius in kilometres'});
const voltage = el('fieldset', null, panel); el('legend', 'Source voltage tags', voltage);
const bandBox = el('div', null, voltage, {class: 'vic-bands'});
for (const [key, name, colour] of VOLTAGE_BANDS) {
const label = el('label', null, bandBox), input = el('input', null, label, {type: 'checkbox', value: key, 'aria-label': name}); input.checked = true;
const text = el('span', name, label); text.style.color = colour;
listen(input, 'change', () => { input.checked ? bands.add(key) : bands.delete(key); refresh(); });
}
const status = el('p', '', panel, {class: 'vic-status', role: 'status', 'aria-live': 'polite'});
const failure = el('p', '', panel, {class: 'vic-error', role: 'alert'}); failure.hidden = true;
el('p', 'Nearby mapped substations · straight-line distance', panel);
const list = el('ol', null, panel, {class: 'vic-results'});
el('p', 'Existing Atlas substation layer; source tags and coverage may be incomplete. Reuses the map’s existing data loader.', panel, {class: 'vic-source'});
const energy = el('fieldset', null, panel, {class: 'vic-energy-context'}); el('legend', 'Nearby generation and demand context', energy);
el('p', 'Counts describe loaded source records. Nameplates, IT load, grid requests and actual electricity demand are different quantities.', energy);
const loadAssets = el('button', 'Load existing asset layers', energy, {type: 'button'});
const energyRows = el('div', null, energy, {class: 'vic-energy-categories'});
const documents = el('details', null, panel, {class: 'vic-document-context'}); el('summary', 'Documented works and official notices', documents);
const documentRows = el('div', null, documents);
panel.insertBefore(energy, list); panel.insertBefore(documents, list);
const train = createGreatGridJourney({map,registry:NS,geodesy,parent:panel,onMapView:()=>{panel.hidden=true;compact.hidden=false;const target=train.snapshot().proposedPicking?map.getCanvas():compactEdit;target.focus({preventScroll:true});},onStatus:message=>{if(!compact.hidden&&compactStatus.textContent!==message)compactStatus.textContent=message;},onRideState:state=>{const message=`${state.pl … [line shortened here: 727 characters; full line on GitHub]
if(!map.getStyle?.())return null;
const data=map.getSource('src-subs')?.serialize?.().data;
return data&&typeof data==='object'&&Array.isArray(data.features)?data.features:null;
}});
panel.insertBefore(train.element,originLabel);
listen(compactPause,'click',()=>train.pause());listen(compactPrevious,'click',()=>train.previousStop());listen(compactNext,'click',()=>train.nextStop());listen(compactEdit,'click',()=>{train.pause();compact.hidden=true;panel.hidden=false;close.focus();});
for(const type of ['click','dblclick','pointerdown','touchstart'])listen(compact,type,event=>event.stopPropagation());
listen(compact,'keydown',event=>{if(event.key==='Escape'){event.preventDefault();shut();}});
// Keep the fixed Close row outside the scrolling content so native scroll-to-focus cannot hide a control behind it.
const scroller=el('div',null,null,{class:'vic-panel-body'});
for(const child of [...panel.children])if(child!==heading)scroller.appendChild(child);
panel.appendChild(scroller);
function sourceAnchor(parent, title, href) {
try { const url = new URL(href); if (url.protocol !== 'https:' || url.username || url.password) return; el('a', title, parent, {href: url.href, target: '_blank', rel: 'noopener noreferrer'}); } catch (_) {}
}
function rowOrigin(row) {
return {at: row.at, name: row.name, id: row.originId || row.id, type: row.kind === 'datacentre' ? 'datacentre' : ['generation','storage'].includes(row.kind) ? 'repd' : 'context-asset'};
}
function text(node, value) { if (node.textContent !== value) node.textContent = value; }
function renderAssetContext() {
assetContext = collectAssetContext({map, registry: NS, origin, radiusKm: radius, geodesy, limit: 40});
const originRow = assetContext.categories.flatMap(category => category.rows).find(row => (row.originId || row.id) === origin.id && row.at.every((v,i) => v === origin.at[i]));
text(originPrecision, ['map-centre','map-point'].includes(origin.type) ? 'User-chosen map point; no facility identity was inferred.'
: originRow?.approximateLocation ? 'Source-provided location is approximate' + (originRow.precision ? ': ' + originRow.precision.replace(/_/g,' ').toLowerCase() : '') + '.'
: originRow?.precision ? 'Source location tag: ' + originRow.precision.replace(/_/g,' ').toLowerCase() + '. Facility position has not been independently verified.'
: 'Source-provided location; coordinate precision not supplied. A stable ID and coordinates alone do not verify a facility location.');
const signature = JSON.stringify(assetContext);
if (signature === assetSignature) return;
assetSignature = signature;
const scroll = scroller.scrollTop;
for (const category of assetContext.categories) {
let view = categoryElements.get(category.id);
if (!view) {
const section = el('details', null, energyRows, {'data-vicinity-category': category.id});
view = {section, heading: el('summary','',section), source: el('p','',section), hint: el('p','',section), rows: el('ol',null,section), records: new Map()};
categoryElements.set(category.id, view);
}
text(view.heading, category.availability === 'LOADED' ? `${category.label}: ${category.count} within ${radius} km · ${category.loadedRecords} loaded records` : `${category.label}: not loaded; nearby count unknown`);
text(view.source, `${category.source || 'Existing Atlas layer'}${category.truncated ? ' · showing nearest 40; narrow the radius for more detail.' : ''}`);
text(view.hint, 'Use Load existing asset layers to request the map’s existing data.'); view.hint.hidden = category.availability === 'LOADED';
const retained = new Set();
for (const [index,row] of category.rows.entries()) {
// A source-row index is a DOM cache key only; it never becomes an asset identity.
const key = row.source + '|' + (row.originId || row.id || 'missing-source-id:' + row.sourceRow);
retained.add(key);
let entry = view.records.get(key);
if (!entry) {
const item = el('li',null,null,{'data-vicinity-asset-id':row.originId || row.id || ''});
entry = {item, title: el('span','',item), meta: el('span','',item,{class:'vic-row-meta'}), row};
const buttons = el('div',null,item,{class:'vic-actions'});
entry.recenter = el('button','Use as origin',buttons,{type:'button'}); entry.add = el('button','Find stations nearby',buttons,{type:'button'});
entry.recenter.addEventListener('click',()=>setOrigin(rowOrigin(entry.row))); entry.add.addEventListener('click',()=>train.nearContext(entry.row));
view.records.set(key,entry);
}
entry.row = row; text(entry.title,row.name);
entry.recenter.setAttribute('aria-label','Use '+row.name+' as origin'); entry.add.setAttribute('aria-label','Find stations near '+row.name);
const facts = [`${row.km.toFixed(2)} km straight-line`, row.status, row.technology].filter(Boolean);
const basis = row.capacityBasis === 'REGISTER_STATED_POWER_BASIS_NOT_DECLARED' ? 'register power; basis not supplied' : row.capacityBasis === 'SOURCE_STATED_POWER_NOT_CURRENT_OUTPUT' ? 'source-stated power, not current output' : row.capacityBasis || 'source-stated basis not supplied';
if (row.capacityMw != null) facts.push(`${row.capacityMw} MW (${basis})`);
if (row.metrics?.itLoadMw != null) facts.push(`${row.metrics.itLoadMw} MW IT load`);
if (row.metrics?.gridConnectionMw != null) facts.push(`${row.metrics.gridConnectionMw} MW grid-connection statement`);
if (row.metrics?.unclassifiedMw != null) facts.push(`${row.metrics.unclassifiedMw} MW (basis unclassified)`);
if (row.kind === 'datacentre' || row.kind === 'demand-context') facts.push('Actual electricity demand unknown');
if (row.kind === 'storage') facts.push('Storage energy (MWh) unknown');
if (row.approximateLocation) facts.push('Approximate source location' + (row.precision ? ': ' + row.precision.replace(/_/g,' ').toLowerCase() : ''));
else facts.push(row.precision ? 'Source location tag: ' + row.precision.replace(/_/g,' ').toLowerCase() : 'Coordinate precision not supplied');
text(entry.meta,facts.join(' · '));
if (view.rows.children[index] !== entry.item) view.rows.insertBefore(entry.item,view.rows.children[index] || null);
}
for (const [key,entry] of view.records) if (!retained.has(key)) { entry.item.remove(); view.records.delete(key); }
}
scroller.scrollTop = scroll;
}
function renderDocumentContext() {
documentContext = documentContextFor(origin, {declaredConnections: NS.declaredConnections});
const signature = JSON.stringify(documentContext); if (signature === documentSignature) return; documentSignature = signature;
documentRows.replaceChildren();
el('p', documentContext.matchedRecords?.length ? 'Existing published works context; source citations have not been revalidated in this release.' : 'No exact documentary works context is available for this asset.', documentRows);
for (const row of (documentContext.matchedRecords || []).slice(0,10)) {
const box = el('div', null, documentRows); el('strong', row.title || 'Existing source declaration', box);
el('p', row.statement || '', box); el('p', 'Existing published declaration; not independently revalidated.', box); sourceAnchor(box, 'Source record', row.sourceUrl);
}
for (const row of (documentContext.unassociatedNotices || []).slice(0,5)) {
const box = el('div', null, documentRows); el('strong', row.title || 'Unassociated official notice', box);
el('p', row.statement || 'No verified association to the selected asset.', box); sourceAnchor(box, 'Official notice context', row.sourceUrl);
}
for (const text of documentContext.limitations || []) el('p', String(text), documentRows);
}
function readRecords() {
let features = [];
try {
const data = map.getSource('src-subs')?.serialize?.().data;
if (data?.type === 'FeatureCollection' && Array.isArray(data.features) && data.features.length) {
contextSource = 'Existing loaded Atlas substation GeoJSON'; return stationRecords(data.features, geodesy);
}
} catch (_) {}
try { if (map.getSource('src-subs')) features = map.querySourceFeatures('src-subs') || []; } catch (_) {}
if (features.length) { contextSource = 'Loaded viewport subset of Atlas substations; use Fit radius to load this view'; return stationRecords(features, geodesy); }
const loaded = W.__GRIDATLAS_NEON_LINKS__?.substations || W.__GRIDATLAS_SUBSTATIONS__ || [];
if (loaded.length) {
contextSource = 'Loaded Atlas ≥33 kV screening subset; lower voltages are not included';
return stationRecords(loaded.map(row => ({type: 'Feature', id: row.id ?? undefined, geometry: {type: 'Point', coordinates: row.at},
properties: {name: row.name, operator: row.operator, kv: (row.kv || []).join(';'), source: row.source || 'Existing Atlas screening subset'}})), geodesy);
}
contextSource = 'Substation layer is not loaded yet'; return [];
}
function draw() {
if (!opened || !result || !alive) return;
try {
let current = map.getSource(SOURCE);
if (current && current !== source) { sourceUnavailable = true; return; }
for (const id of LAYERS) {
const existing = map.getLayer(id);
if (existing && existing !== ownedLayers.get(id)) { sourceUnavailable = true; showError('A map layer ID is already in use. Results remain available; existing layers were preserved.'); return; }
}
if (!current) { map.addSource(SOURCE, {type: 'geojson', data: {type: 'FeatureCollection', features: []}}); source = map.getSource(SOURCE); }
sourceUnavailable = false;
const specs = [
{id: LAYERS[0], type: 'line', source: SOURCE, filter: ['==', ['get', 'kind'], 'radius'], paint: {'line-color': '#0ff', 'line-width': 1.5, 'line-dasharray': [3,3], 'line-opacity': 0.8}},
{id: LAYERS[1], type: 'circle', source: SOURCE, filter: ['in', ['get', 'kind'], ['literal', ['origin','substation']]], paint: {'circle-color': ['case', ['==', ['get', 'kind'], 'origin'], '#ff4fd8', ['get', 'colour']], 'circle-radius': ['case', ['==', ['get', 'kind'], 'origin'], 8, 5], 'circle-stroke-color': '#020809', 'circle-stroke-width': 1.5}},
{id: LAYERS[2], type: 'line', source: SOURCE, filter: ['==', ['get', 'kind'], 'user-model'], paint: {'line-color': '#ff4fd8', 'line-width': 3, 'line-dasharray': [2,3]}}
];
for (const spec of specs) if (!map.getLayer(spec.id)) { map.addLayer(spec); ownedLayers.set(spec.id, map.getLayer(spec.id)); }
const data = vicinityGeoJSON(result, geodesy);
source.setData(data);
} catch (e) { sourceUnavailable = true; failure.textContent = 'Map overlay not ready. Results remain available below.'; failure.hidden = false; }
}
function removeMap(mapRemoved = false) {
if (!source || mapRemoved) { source = null; ownedLayers.clear(); return; }
try {
if (map.getSource(SOURCE) === source) {
for (const id of [...LAYERS].reverse()) if (map.getLayer(id) && map.getLayer(id) === ownedLayers.get(id)) map.removeLayer(id);
const foreignDependency = (map.getStyle()?.layers || []).some(layer => layer.source === SOURCE);
if (!foreignDependency && map.getSource(SOURCE) === source) map.removeSource(SOURCE);
}
} catch (_) {}
source = null; ownedLayers.clear();
}
function showError(message) { error = message; failure.textContent = message; failure.hidden = !message; }
function clearNews() { newsBase = null; newsTopic = null; news.removeAttribute('href'); news.hidden = newsCaption.hidden = true; }
function clearSelectedContext() { origin = null; result = null; assetContext = null; documentContext = null; assetSignature = stationSignature = documentSignature = null; categoryElements.clear(); list.replaceChildren(); energyRows.replaceChildren(); documentRows.replaceChildren(); news.hidden = newsCaption.hidden = true; removeMap(); }
function addStation(row) { train.addSourceStation(row); }
function refresh() {
if (!alive || !opened) return;
if (!origin) { rangeLabel.textContent = `${radius} km radius`; slider.value = String(radius); train.refreshInventory(); return; }
try {
records = readRecords(); result = exploreVicinity({origin, radius, records, bands, geodesy});
originLabel.textContent = `Origin: ${origin.name}${origin.id ? ' · source ID ' + origin.id : ''}`;
if (newsBase) { news.href = newsContextHref(newsBase, origin, newsTopic); news.hidden = newsCaption.hidden = false; }
rangeLabel.textContent = `${radius} km radius`; slider.value = String(radius);
status.textContent = `${result.matching} matching mapped stations within ${radius} km · ${result.loadedRecords} loaded records. ${result.truncated ? 'Showing nearest 200. ' : ''}${contextSource}.`;
const nextStationSignature = JSON.stringify(result);
if (nextStationSignature !== stationSignature) {
stationSignature = nextStationSignature; list.replaceChildren();
for (const row of result.shown) {
const item = el('li', row.name, list); el('span', `${row.km.toFixed(2)} km · ${row.kv.length ? row.kv.join(' / ') + ' kV' : 'Voltage not stated'}${row.operator ? ' · ' + row.operator : ''}`, item, {class: 'vic-row-meta'});
const buttons = el('div', null, item, {class: 'vic-actions'});
const recenter = el('button', 'Use as origin', buttons, {type: 'button', 'aria-label': 'Use ' + row.name + ' as origin'});
const add = el('button', 'Add to my model', buttons, {type: 'button', 'aria-label': 'Add ' + row.name + ' to my model'});
recenter.addEventListener('click', () => setOrigin({at: row.at, name: row.name, id: row.id, type: 'substation'}));
add.addEventListener('click', () => addStation(row));
}
}
renderAssetContext(); renderDocumentContext(); draw(); train.refreshInventory();
} catch (e) { showError(e.message); }
}
function setOrigin(next) {
train.cancelProposedPick();
try { const validated = normaliseOrigin(next); origin = validated; phase = 'READY'; selectionEpoch++; picking = false; pick.setAttribute('aria-pressed', 'false'); pick.textContent = 'Pick origin on map'; showError(null); refresh(); return true; }
catch (e) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Origin was not applied.'; showError(e.message); return false; }
}
function mapCentre() { const c = map.getCenter(); return {at: [c.lng, c.lat], type: 'map-centre', id: null, name: 'Chosen map centre'}; }
function fitRadius() {
if (!result) return;
const points = vicinityGeoJSON(result, geodesy).features[0].geometry.coordinates;
const lngs = points.map(p => p[0]), lats = points.map(p => p[1]);
map.fitBounds([[Math.min(...lngs), Math.min(...lats)], [Math.max(...lngs), Math.max(...lats)]], {padding: 32, duration: 0});
}
function installControls() {
for (const host of [D.getElementById('scada-ui-container'), D.getElementById('fs-curtain-keys'), D.querySelector('#gridatlas-menu-bar-panel-4 .gm-panel-body')]) {
if (!host || groups.some(g => g.parentNode === host)) continue;
if (host.id === 'scada-ui-container' && !host.querySelector('input[data-layer-id]')) continue;
if (host.id === 'fs-curtain-keys' && !host.querySelector('input[data-layer-id]')) continue;
if (host.closest?.('#gridatlas-menu-bar-panel-4') && !NS.menuBar?.installed) continue;
const group = el('div', null, host, {class: 'key-group', 'data-vicinity-group': 'true'}); group.style.gridColumn = '1/-1'; el('div', 'Vicinity familiarisation', group, {class: 'key-title'});
const button = el('button', 'Explore nearby grid · 1–50 km', group, {type: 'button', class: 'map-ctrl-btn', 'aria-expanded': String(opened), 'aria-controls': panel.id});
button.style.minHeight = '44px'; listen(button, 'click', event => { event.stopPropagation(); NS.menuBar?.closeAll?.(); open({mode:'vicinity'}, button); });
const journeyButton=el('button','Great Grid Journeys',group,{type:'button',class:'map-ctrl-btn','aria-controls':panel.id});journeyButton.style.minHeight='44px';listen(journeyButton,'click',event=>{event.stopPropagation();NS.menuBar?.closeAll?.();open({mode:'journey'},journeyButton);});
groups.push(group); controls.push(button);
}
}
function open(options = {}, invoker = null) {
if (!alive) return false;
returning = invoker || (D.activeElement && D.activeElement !== D.body && D.activeElement !== D.documentElement ? D.activeElement : launch); opened = true; panel.hidden = false; compact.hidden=true; launch.setAttribute('aria-expanded', 'true'); for (const b of controls) b.setAttribute('aria-expanded', 'true');
try {
train.open();if(!train.setMode(options.mode||'vicinity')) {showError('Selected stops exceed the requested mode. Remove stops explicitly before changing mode.');close.focus();return false;}
if (options.error) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Journey link was not applied. Choose an origin to explore.'; status.textContent = ''; showError(options.error); close.focus(); return false; }
let newsError = options.newsContextError || null;
if (newsError) clearNews();
else if (options.newsContextUrl !== undefined) {
try { const base = validateNewsContextBase(options.newsContextUrl), topic = normaliseNewsTopic(options.newsTopic, options.origin); newsBase = base; newsTopic = topic; }
catch (e) { clearNews(); newsError = 'News context link was not applied: ' + e.message; }
}
radius = radiusKm(options.radiusKm ?? radius);
if (options.manual || !options.origin && !origin) {
clearSelectedContext(); phase = 'CHOOSE_ORIGIN'; picking = false; pick.setAttribute('aria-pressed','false'); pick.textContent = 'Pick origin on map';
originLabel.textContent = 'Choose an origin to begin.'; originPrecision.textContent = 'Use map centre or pick a point; no location is chosen automatically.';
status.textContent = 'Choose a location, then explore the grid within your selected radius.'; refresh(); showError(newsError ? newsError + ' Choose a location to continue grid exploration.' : null); close.focus(); return true;
}
if (!setOrigin(options.origin || origin)) return false;
try { W.__GRIDATLAS_NEON_LINKS__?.enableSubstationLayer?.(); } catch (_) {}
refresh(); if (newsError) showError(newsError + ' Grid exploration continues.'); close.focus(); return true;
} catch (e) { clearSelectedContext(); phase = 'REFUSED'; originLabel.textContent = 'Journey request was not applied. Choose a valid origin and radius.'; showError(e.message); close.focus(); return false; }
}
function shut() {
if (!alive) return;
opened = false; picking = false; panel.hidden = true; compact.hidden=true;mapLegend.hidden=true; launch.setAttribute('aria-expanded', 'false'); for (const b of controls) b.setAttribute('aria-expanded', 'false');
train.close(); removeMap(); const candidate = returning?.isConnected && returning.getClientRects().length ? returning : D.getElementById('gridatlas-menu-bar-title-4') || launch; candidate.focus();
}
listen(launch, 'click', () => { opened ? shut() : open({mode:'journey'}, launch); }); listen(close, 'click', shut);
listen(centre, 'click', () => setOrigin(mapCentre())); listen(fit, 'click', fitRadius);
listen(loadAssets, 'click', event => {
event.stopPropagation();
const ids = ['solar','solar_operational','solar_roof','wind','wind_onshore_operational','wind_offshore_operational','bess','bess_operational','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes'];
const boxes = ids.map(id => D.querySelector(`#scada-ui-container input[data-layer-id="${id}"]`)).filter(Boolean);
for (const box of boxes) if (!box.checked) box.click();
NS.ukOfftakers?.setOn?.(true); refresh();
});
listen(physical, 'click', event => {
event.stopPropagation();
const boxes = ['400','275','220','132','66','subs'].map(id => D.querySelector(`#scada-ui-container input[data-layer-id="${id}"]`)).filter(Boolean);
if (!boxes.length) { showError('Physical grid controls are loading. Try again when the map controls appear.'); return; }
for (const box of boxes) if (!box.checked) box.click();
showError(null); status.textContent = 'Existing physical grid layers switched on. Source-mapped corridors are context; crossings and proximity do not establish a connection.';
fitRadius();
});
listen(pick, 'click', () => { train.cancelProposedPick(); picking = !picking; pick.setAttribute('aria-pressed', String(picking)); pick.textContent = picking ? 'Tap a point on the map' : 'Pick origin on map'; });
listen(slider, 'input', () => { try { radius = radiusKm(slider.value); showError(null); refresh(); } catch (e) { showError(e.message); } });
listen(panel, 'keydown', event => { if (event.key === 'Escape') { event.preventDefault(); shut(); } });
for (const type of ['click','dblclick','pointerdown','touchstart']) listen(panel, type, event => event.stopPropagation());
const clicked = event => { if (opened && picking && event.lngLat) setOrigin({at: [event.lngLat.lng,event.lngLat.lat], name: 'Chosen map point', type: 'map-point', id: null}); };
const sourced = event => { if (opened && (!event || ['src-subs','src-repd','gridatlas-offtakers'].includes(event.sourceId))) { clearTimeout(refreshTimer); refreshTimer = setTimeout(refresh, 100); } };
const styled = () => { if (!map.getSource(SOURCE)) source = null; if (opened) refresh(); };
const removed = () => destroy(true);
map.on('click', clicked); map.on('sourcedata', sourced); map.on('style.load', styled); map.on('remove', removed);
const onIntent = event => open(event.detail || {}); listen(W, 'gridatlas:vicinity-open', onIntent);
const onCard = event => { if (event.detail?.origin && opened && !train.snapshot().proposedPicking) setOrigin(event.detail.origin); }; listen(W, 'gridatlas:card-open', onCard);
const observer = new MutationObserver(installControls); observer.observe(D.documentElement, {childList: true, subtree: true}); installControls();
function destroy(mapRemoved = false) {
if (!alive) return; alive = false; clearTimeout(refreshTimer); observer.disconnect(); listeners.forEach(off => off());
map.off('click', clicked); map.off('sourcedata', sourced); map.off('style.load', styled); map.off('remove', removed); removeMap(mapRemoved);
train.destroy(); groups.forEach(g => g.remove()); root.remove();
}
return Object.freeze({open, close: shut, setOrigin, refresh, destroy, snapshot: () => ({alive, opened, phase, generation: VICINITY_GENERATION, radiusKm: radius,
origin: origin ? {...origin,at: origin.at.slice()} : null, matching: result?.matching ?? null, shown: result?.shown.length ?? 0, loadedRecords: records.length,
newsContextUrl: newsBase, newsHref: newsBase && origin ? newsContextHref(newsBase, origin, newsTopic) : null,
assetContext: assetContext ? {...assetContext, categories: assetContext.categories.map(category => ({...category, rows: category.rows.map(({sourceRow, ...row}) => row)}))} : null,
documentContext,
selectedBands: [...bands], contextSource, sourceUnavailable, train:train.snapshot(), modelStations: train.snapshot().itinerary.stops.map(row => ({name: row.name, id: row.id, at: row.at.slice()})),
modelEvidence: 'USER_ASSUMED_LOCAL_MODEL', realConnectionsInferred: 0, error, selectionEpoch})});
}
function mount(map = W.__GRIDATLAS_V9_MAP__) {
if (controller?.snapshot().alive) return controller;
if (!map?.getContainer) return null;
controller = createController(map); return controller;
}
let tries = 0;
function attach() {
if (stopped) return;
try {
if (mount()) {
if (pendingIntent) { controller.open(pendingIntent); pendingIntent = null; }
else if (intentError) { controller.open({error: 'Journey link refused: ' + intentError}); intentError = null; }
return;
}
} catch (e) { console.warn('[Vicinity]', e.message); }
if (++tries < 240) timer = setTimeout(attach, 250);
}
NS.gridVicinity = Object.freeze({schema: 'gridatlas.vicinity.v1', generation: VICINITY_GENERATION, mount,
open(options) { return mount()?.open(options); }, setOrigin(origin) { return mount()?.setOrigin(origin); },
snapshot: () => controller?.snapshot() || {alive: false, opened: false, status: 'map-unavailable'},
destroy() { stopped = true; clearTimeout(timer); controller?.destroy(); controller = null; }});
attach();
}Document Context
A JavaScript module in the vicinity folder of GridAtlas that works with notice, the Renewable Energy Planning Database (REPD) register and substations, using SHA-256.
transformgridatlas / tools/vicinity/src/document-context.mjs · lines 1–94 of 94 · pattern freezeDocumentContext (shared by 3 files)
- What it does
- It calculates notice, the REPD register and substations. Defines freezeDocumentContext, documentOrigin, documentContextFor.
- 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: the REPD register, substations.
- Inputs & outputs
- In: JSON file notice.json.
- Downstream impact
- Used directly by 1 file: Document Context Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It is built from the freeze document context helper (`freezeDocumentContext`), the document origin helper (`documentOrigin`) and the document context for helper (`documentContextFor`). Existing documentary context only. No fetch, name matching or spatial joins.
- Why it matters
- Checked by Document Context Test.
- Application
- gridatlas · tools/vicinity/src · JavaScript module
- Uses
- Declared Connections (estate URL)
- Used by
- imported by Document Context Test (import)
- Produces
- DOCUMENT_CONTEXT_PROVENANCE, DOCUMENT_CONTEXT_NOTICES, documentContextFor
- Defines here
- freezeDocumentContext, documentOrigin, documentContextFor
- 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/vicinity/src/document-context.mjs:1-94 · blob b22317e42ed1a4c19e4c9df36a28d39741c727c9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Existing documentary context only. No fetch, name matching or spatial joins. */
function freezeDocumentContext(value) {
if (value && typeof value === 'object') { for (const child of Object.values(value)) freezeDocumentContext(child); Object.freeze(value); }
return value;
}
export const DOCUMENT_CONTEXT_PROVENANCE = freezeDocumentContext({
declaredModule: {
repository: 'Ventusltd/gridatlas', commit: 'b52693aaf513e63240acd8ab99a698df5b738cc6',
path: 'atlas/modules/202609012128-declared-connections.js', bytes: 15461,
sha256: 'a44520ebd644e725f644e7f3aea76839982c82d577022ac04583c5bc3346a371',
sourceUrl: 'https://github.com/Ventusltd/gridatlas/blob/b52693aaf513e63240acd8ab99a698df5b738cc6/atlas/modules/202609012128-declared-connections.js'
},
noticeProducer: {
repository: 'Ventusltd/globalgrid2050', commit: '07bff3a6d1cdc4d845062cafa1cf49161b135c96',
path: 'automation/grid_notice_ui/20261117-v938/notice.json', bytes: 5300,
sha256: 'bef90e1a64e4f1921c62f85ee61d636d1fe02fcebd30ea1570a7b3bfd49f5148',
factsSha256: 'f9802c96444c21e84b328d612475353861c8053cde31f55196d1ea5862918afb',
sourceUrl: 'https://github.com/Ventusltd/globalgrid2050/blob/07bff3a6d1cdc4d845062cafa1cf49161b135c96/automation/grid_notice_ui/20261117-v938/notice.json',
reviewReferences: ['https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-6953350836', 'https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-6953404444']
}
});
export const DOCUMENT_CONTEXT_NOTICES = freezeDocumentContext([{
id: 'government:EN020026:consented:2026-10-30', title: 'Sea Link development consent',
applicationRef: 'EN020026', status: 'NARROW_FACTS_REVIEWED_NO_ASSET_ASSOCIATION',
sourceUrl: 'https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008',
sourceTitle: 'Department for Energy Security and Net Zero: Sea Link development consent order',
date: {value: '2026-10-30', precision: 'DAY'},
statement: 'Government decision records development consent for the Suffolk–Kent transmission proposal. Its planned transmission upper bound is 2,000 MW; current capacity, commissioning and available headroom are unknown.',
scope: 'Standalone official planning context. No association with the selected asset or its vicinity has been established.',
plannedMetric: {value: 2000, unit: 'MW', kind: 'planned_transmission_upper_bound'},
currentCapacityMw: null, commissioned: null, connection: null, repdRef: null, coordinates: null,
verifiedAssetJoins: 0,
rightsScope: 'government_html_facts_only_no_images_or_third_party_material',
licenceUrl: 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/',
sources: [
{title: 'Planning Inspectorate: Sea Link development consent decision announced', url: 'https://www.gov.uk/government/news/sea-link-development-consent-decision-announced',
publishedDate: {value: '2026-10-30', precision: 'DAY'}, sourceUpdatedAt: null,
archivedReceipt: {retrievedAt: '2026-11-17T15:48:11Z', bytes: 68432, sha256: 'b9ba26b90820292e0b181da7993d2d3a2180fc2de0ac53cc6239adeb4cccfaeb'},
currentObservation: {retrievedAt: '2026-11-18T00:35:01.291330Z', bytes: 68432, sha256: 'b404ca2c91a4b84def5c521ceccab617c4b3bda860d40d2da32fd3e9298f599a', scope: 'Decision day and stated OGL footer reconfirmed; current HTML differs from archived receipt.'}},
{title: 'Department for Energy Security and Net Zero: Sea Link development consent order', url: 'https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008',
publishedDate: {value: '2026-10-30', precision: 'DAY'}, sourceUpdatedAt: null,
archivedReceipt: {retrievedAt: '2026-11-17T15:48:11Z', bytes: 69536, sha256: 'c26f93aa307740f8b4ec8ad150b152fb6d30e77f201e5bc31a6da52bba16e0d0'},
currentObservation: {retrievedAt: '2026-11-18T00:35:01.437596Z', bytes: 69536, sha256: 'f15b12f35fa4fd1364894d550d3f053dfa680550ad7d83a56fa5b794624e4084', scope: 'Decision day and stated OGL footer reconfirmed; current HTML differs from archived receipt.'}}
]
}]);
function documentOrigin(origin) {
if (!origin || !['repd', 'datacentre', 'substation'].includes(origin.type) || typeof origin.id !== 'string'
|| !origin.id || origin.id.length > 256 || /[\s\u0000-\u001f\u007f]/.test(origin.id)) return null;
return {type: origin.type, id: origin.id};
}
export function documentContextFor(origin, {declaredConnections} = {}) {
const identity = documentOrigin(origin), matchedRecords = [];
const limitations = [
'No independently verified asset-to-upgrade or asset-to-notice crosswalk is supplied by this adapter.',
'A published declaration or planning consent does not establish construction, energisation, a surveyed route, electrical connection, power flow or available capacity.',
'The standalone Sea Link notice is not linked to the selected asset, nearby substations or a distance radius.'
];
// Read the canonical already-published owner table; do not fork its records or
// attach works to a nearby/name-matching substation. Its status stays verbatim.
const ref = identity?.type === 'repd' && /^repd:[1-9]\d*$/.test(identity.id) ? identity.id.slice(5) : null;
const canonical = declaredConnections?.schema === 'gridatlas.module.declared-connections.v1' ? declaredConnections.records : null;
const declaration = ref && canonical && Object.hasOwn(canonical, ref) ? canonical[ref] : null;
if (declaration && typeof declaration.source === 'string') {
const statement = [declaration.works, declaration.poc_works, declaration.via].filter(v => typeof v === 'string' && v).join('; ');
if (statement) matchedRecords.push({
id: 'existing-atlas-declaration:' + ref, originId: identity.id,
title: 'Existing published declaration for REPD ' + ref,
sourceUrl: DOCUMENT_CONTEXT_PROVENANCE.declaredModule.sourceUrl, sourceTitle: declaration.source,
statement, status: 'EXISTING_PUBLISHED_DECLARATION_UNREVALIDATED',
scope: 'Existing published declaration; source citation not revalidated here. Exact REPD key only; not an independently verified asset-to-document association.',
matchBasis: 'EXACT_REPD_KEY_IN_CANONICAL_OWNER_MODULE', verifiedAssetAssociation: false,
date: null, datePrecision: 'UNKNOWN',
declaredStatus: declaration.poc_status ?? null,
// Preserve the original owner's fields and classification separately from
// this adapter's review status. Never infer an absent status or date.
declaration: Object.fromEntries(['works', 'poc_works', 'substation', 'circuit', 'via', 'source', 'poc_status', 'poc_status_note', 'poc_kind', 'kv']
.filter(k => Object.hasOwn(declaration, k)).map(k => [k, declaration[k]]))
});
}
if (!identity) limitations.unshift('No supported stable source identity was supplied; names and coordinates were not used to create a match.');
else if (!matchedRecords.length) limitations.unshift('No exact existing documentary declaration is available for this source identity.');
return freezeDocumentContext({
schema: 'gridatlas.vicinity.document-context.v1', origin: identity,
status: matchedRecords.length ? 'EXISTING_DECLARATION_ONLY' : 'NO_EXACT_ASSET_DOCUMENT_CONTEXT',
matchedRecords, unassociatedNotices: DOCUMENT_CONTEXT_NOTICES,
verifiedAssetJoins: 0, realConnectionsInferred: 0,
counts: {existingDeclarations: matchedRecords.length, unassociatedNotices: 1, governmentDocuments: 2, verifiedAssetJoins: 0},
limitations, provenance: DOCUMENT_CONTEXT_PROVENANCE
});
}