In this section
- Secondary Vicinity ingest · gridatlas / tools/satnav/guidance/secondary-vicinity.mjs lines 1–92
- GeoJSON Interchange geodesy · gridatlas / tools/satnav/interchange/geojson-interchange.mjs lines 1–65
- GeoJSON Interchange Test test · gridatlas / tools/satnav/interchange/geojson-interchange.test.mjs lines 1–17
- GeoJSON geodesy · gridatlas / tools/satnav/interchange/geojson.mjs lines 1–72
- GeoJSON Test test · gridatlas / tools/satnav/interchange/geojson.test.mjs lines 1–38
- Layout Browser render · gridatlas / tools/satnav/interchange/layout-browser.py lines 1–128
- Layout Import ingest · gridatlas / tools/satnav/interchange/layout-import.mjs lines 1–129
Secondary Vicinity
A JavaScript module in the guidance folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register, substations and transformers, using SHA-256.
ingestgridatlas / tools/satnav/guidance/secondary-vicinity.mjs · lines 1–92 of 92 · pattern patch (shared by 11 files)
- What it does
- It loads the REPD register, substations and transformers. Defines patch, buildSecondaryVicinity. Uses libraries node:fs, node:crypto, node:vm. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: the REPD register, substations, transformers.
- Downstream impact
- Used directly by 3 files: Convergence 2km Test (gridatlas); Convergence Preview (gridatlas); Owner Test Proof (gridatlas). Reached from 4 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); CI PR Gate (gridatlas); Map Promotion Rehearsal (gridatlas).
- What it achieves
- It is built from the patch step (`patch`). Only transformation of the two immutable V9.197 Vicinity modules.
- Why it matters
- Imported by Convergence Preview. Checked by 2 tests, including Convergence 2km Test.
- Application
- gridatlas · tools/satnav/guidance · JavaScript module
- Uses
- GridAtlas — Index Page (new URL import.meta.url), node:fs, node:crypto, node:vm
- Used by
- imported by Convergence 2km Test (import), imported by Convergence Preview (import), imported by Owner Test Proof (import)
- Produces
- buildSecondaryVicinity
- Defines here
- patch, buildSecondaryVicinity
- 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/satnav/guidance/secondary-vicinity.mjs:1-92 · blob 063a25580463391c51b3bd3c5023427b718a0495 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SPDX-License-Identifier: Apache-2.0
// Candidate-only transformation of the two immutable V9.197 Vicinity modules.
// Reuses the existing 30/30/30 engine, swipe, CSV and map. Never invents a REPD ID.
import {readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
import vm from 'node:vm';
const pins = [
{
"path": "atlas/modules/202611222000-uk-offtakers-overlay.js",
"sha256": "badb2745d6e339d0d863e6369ad76139f9d3690e98bf4153ab849154ead38a46"
},
{
"path": "atlas/modules/202611222130-vicinity-focus.js",
"sha256": "8ea2546b2a1fab3007d3b7a81aa509baae323051b888afd252edb6bc4726f14e"
}
];
const engineEdits = [
[
"project=!!o.project,w=DMW(p)",
"project=!!o.project,secondary=project&&p.origin_kind==='ukpn-secondary',w=DMW(p)"
],
[
"project?'Project vicinity (screening)':'Data centre (screening)'",
"secondary?'Secondary substation vicinity (screening)':project?'Project vicinity (screening)':'Data centre (screening)'"
],
[
"project?`${NM(r)} · REPD ${cs(p.repd_ref)}`",
"secondary?`${NM(r)} · UKPN secondary ${cs(p.site_id)}`:project?`${NM(r)} · REPD ${cs(p.repd_ref)}`"
],
[
"project?`${cs(p.technology||'Technology not stated')} · ${p.capacity_mw>0?N(p.capacity_mw)+' MW registered':'MW not stated'}`",
"secondary?'UKPN transformer register · installed ratings are not available capacity':project?`${cs(p.technology||'Technology not stated')} · ${p.capacity_mw>0?N(p.capacity_mw)+' MW registered':'MW not stated'}`"
],
[
"project?'REPD project vicinity. Distances are straight-line; connectivity and capacity unknown.':DHEAD",
"secondary?'UKPN secondary substation vicinity. Distances are straight-line; connectivity and capacity unknown.':project?'REPD project vicinity. Distances are straight-line; connectivity and capacity unknown.':DHEAD"
],
[
"${c.project?'Project vicinity':'Data centre'}",
"${c.r.p.origin_kind==='ukpn-secondary'?'Secondary vicinity':c.project?'Project vicinity':'Data centre'}"
],
[
"a.download=`datacentre-vicinity-${GEN}-",
"a.download=`${c.r.p.origin_kind==='ukpn-secondary'?'secondary':'datacentre'}-vicinity-${GEN}-"
],
[
"[(c.project?'REPD project':'data centre'),0,NM(r),id,c.project?cs(r.p.technology||'not stated'):'data centre',sl,'','',c.project?(r.p.capacity_mw||'not stated'):M(w.it),c.project?'registered MW':'IT load',0,x,y,'site',c.project?'PipelineNews map origin':r.dc?'data-centre dataset':'OpenStreetMap',c.project?'REPD (DESNZ)':'ODbL 1.0','']",
"[r.p.origin_kind==='ukpn-secondary'?'UKPN secondary':c.project?'REPD project':'data centre',0,NM(r),id,r.p.origin_kind==='ukpn-secondary'?'secondary substation':c.project?cs(r.p.technology||'not stated'):'data centre',sl,'','',r.p.origin_kind==='ukpn-secondary'?'not stated':c.project?(r.p.capacity_mw||'not stated'):M(w.it),r.p.origin_kind==='ukpn-secondary'?'not stated':c.project?'registered … [line shortened here: 656 characters; full line on GitHub]
],
[
"${c.project?'REPD project':'data-centre'} vicinity sheet",
"${r.p.origin_kind==='ukpn-secondary'?'UKPN secondary':c.project?'REPD project':'data-centre'} vicinity sheet"
],
[
"c.project?'# REPD project context from PipelineNews MAP URL; MW does not establish connection capacity.'",
"r.p.origin_kind==='ukpn-secondary'?'# Origin: UKPN secondary transformer register; no connection or available capacity inferred.':c.project?'# REPD project context from PipelineNews MAP URL; MW does not establish connection capacity.'"
],
[
"function initProjectSwipe(map,card){",
"function openSecondaryVicinity(input){\n const site=typeof input?.site==='string'?input.site.trim():'',at=input?.at;\n if(!site||site.length>180||!Array.isArray(at)||at.length!==2||!at.every(Number.isFinite)||at[0]<-11||at[0]>3||at[1]<49.5||at[1]>61.5)return false;\n const map=mh();if(!map||!NS.gridScope||typeof NS.gridScope.scope!=='function')return false;\n const source=map.getSource('src-u … [line shortened here: 1,040 characters; full line on GitHub]
],
[
"setOn:so,openProjectVicinity});",
"setOn:so,openProjectVicinity,openSecondaryVicinity});"
]
];
const focusEdits = [
[
" return{title:card.r?.n||'Selected REPD project',kind:'REPD project (origin)',",
" if(p.origin_kind==='ukpn-secondary')return{title:card.r?.n||'Selected secondary substation',kind:'UKPN secondary (origin)',\n source:'UK Power Networks transformer register · CC BY 4.0',\n rows:[['Distance','0 km straight line (origin)'],['UKPN site reference',safely(p.site_id)],['Interpretation','Installed ratings are not available capacity']],\n index:'origin',count:s … [line shortened here: 506 characters; full line on GitHub]
],
[
"card.setAttribute('aria-label','Project vicinity asset browser');",
"card.setAttribute('aria-label',card.r?.p?.origin_kind==='ukpn-secondary'?'Secondary substation vicinity asset browser':'Project vicinity asset browser');"
]
];
function patch(source,edits) {
for (const [from,to] of edits) {
if (source.split(from).length!==2) throw Error('Vicinity anchor mismatch: '+from.slice(0,100));
source=source.replace(from,to);
}
new vm.Script(source);
return source;
}
export function buildSecondaryVicinity(root=new URL('../../../',import.meta.url)) {
const originals=pins.map(({path,sha256})=>{
const bytes=readFileSync(new URL(path,root));
if(createHash('sha256').update(bytes).digest('hex')!==sha256)throw Error('Vicinity predecessor integrity mismatch: '+path);
return bytes.toString('utf8');
});
return {engine:patch(originals[0],engineEdits),focus:patch(originals[1],focusEdits)};
}GeoJSON Interchange
A JavaScript module in the SatNav folder of GridAtlas that imports GIS route snapshot (`importGisRouteSnapshot`). It exports geo JSON (`exportGeoJSON`), imports geo JSON (`importGeoJSON`) and imports GIS route snapshot (`importGisRouteSnapshot`).
geodesygridatlas / tools/satnav/interchange/geojson-interchange.mjs · lines 1–65 of 65 · pattern exportGeoJSON (shared by 5 files)
- What it does
- It calculates its inputs. Defines 12 functions or classes, including fail, point, points, same, ring.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 3 files: GeoJSON Interchange Test (gridatlas); Layout Import (gridatlas); Layout Import Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- SV07: pure, explicit local interchange; no GPS, network or financial mutation.
- Why it matters
- Imported by Layout Import. Checked by 2 tests, including GeoJSON Interchange Test.
- Application
- gridatlas · tools/satnav/interchange · JavaScript module
- Uses
- none found
- Used by
- imported by GeoJSON Interchange Test (import), imported by Layout Import (import), imported by Layout Import Test (import)
- Produces
- exportGeoJSON, importGeoJSON, importGisRouteSnapshot
- Defines here
- fail, point, points, same, ring, fix, track, feature, exportGeoJSON, importGeoJSON, ordered, importGisRouteSnapshot
- 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/satnav/interchange/geojson-interchange.mjs:1-65 · blob 2af99498b4997bd003b4adda0d414bf4efcc451a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SV07: pure, explicit local interchange; no GPS, network or financial mutation.
const SCHEMA = 'ventus.satnav.geojson.v1';
const MAX = 20000;
const fail = msg => { throw new TypeError(msg); };
function point(p) {
if (!Array.isArray(p) || p.length !== 2 || !p.every(Number.isFinite) || Math.abs(p[0]) > 180 || Math.abs(p[1]) > 90) fail('Expected WGS84 [longitude, latitude]');
return [...p];
}
function points(a, min=0) {
if (!Array.isArray(a) || a.length < min || a.length > MAX) fail('Invalid coordinate count');
return a.map(point);
}
const same = (a,b) => a[0]===b[0] && a[1]===b[1];
function ring(a) {
const r=points(a,4);
if (!same(r[0],r.at(-1)) || new Set(r.slice(0,-1).map(p=>p.join(','))).size<3) fail('Expected closed polygon with three distinct vertices');
return r;
}
function fix(f) {
if (!f || !Number.isFinite(f.timestamp) || f.timestamp<0 || !Number.isFinite(f.accuracy) || f.accuracy<0) fail('Invalid measured fix metadata');
return {coordinate:point(f.coordinate),timestamp:f.timestamp,accuracy:f.accuracy};
}
function track(a) {
if(!Array.isArray(a)||a.length>MAX)fail('Invalid track count');
const t=a.map(fix);
if(t.some((f,i)=>i>0&&f.timestamp<t[i-1].timestamp))fail('Track timestamps not ordered');
return t;
}
const feature=(role,type,coordinates,props={})=>({type:'Feature',geometry:{type,coordinates},properties:{role,...props}});
export function exportGeoJSON({pins=[],plannedRoute=null,perimeter=null,walkedTrack=[]}={}) {
const features=points(pins).map((p,i)=>feature('waypoint','Point',p,{order:i}));
if(plannedRoute!==null)features.push(feature('planned-route','LineString',points(plannedRoute,2)));
if(perimeter!==null)features.push(feature('perimeter','Polygon',[ring(perimeter)]));
const t=track(walkedTrack);
// Separate point features preserve individual GPS fixes, including a single fix.
for(const [i,f] of t.entries())features.push(feature('walked-fix','Point',f.coordinate,{order:i,timestamp:f.timestamp,accuracy:f.accuracy}));
return {type:'FeatureCollection',schema:SCHEMA,features};
}
export function importGeoJSON(doc) {
if(!doc||doc.type!=='FeatureCollection'||!Array.isArray(doc.features)||doc.features.length>2*MAX+2)fail('Expected bounded FeatureCollection');
if(doc.schema!==undefined&&doc.schema!==SCHEMA)fail('Unsupported schema');
const state={pins:[],plannedRoute:null,perimeter:null,walkedTrack:[]};
const pins=[], fixes=[];
for(const f of doc.features){
if(f?.type!=='Feature'||!f.geometry)fail('Invalid feature');
const {type,coordinates:c}=f.geometry;
const p=f.properties??{};
// Untagged standard features: Points are waypoints, never measured GPS fixes.
const role=p.role??({Point:'waypoint',LineString:'planned-route',Polygon:'perimeter'}[type]);
if(role==='waypoint'&&type==='Point')pins.push({order:p.order??pins.length,value:point(c)});
else if(role==='planned-route'&&type==='LineString'&&state.plannedRoute===null)state.plannedRoute=points(c,2);
else if(role==='perimeter'&&type==='Polygon'&&Array.isArray(c)&&c.length===1&&state.perimeter===null)state.perimeter=ring(c[0]);
else if(role==='walked-fix'&&type==='Point')fixes.push({order:p.order,value:fix({coordinate:c,timestamp:p.timestamp,accuracy:p.accuracy})});
else fail('Unsupported, duplicate or ambiguous feature');
}
function ordered(a){if(a.length>MAX)fail('Too many points');a.sort((x,y)=>x.order-y.order);if(a.some((v,i)=>v.order!==i))fail('Invalid point order');return a.map(v=>v.value);}
state.pins=ordered(pins);state.walkedTrack=track(ordered(fixes));
return state;
}
export function importGisRouteSnapshot(snapshot){
if(snapshot?.schema!=='ventus.gis-route.v1'||snapshot.status!=='available'||snapshot.committed!==true||snapshot.route?.geometry?.type!=='LineString')fail('GIS route is not committed and available');
const route=points(snapshot.route.geometry.coordinates,2);
// Original manual route geometry is authoritative. Never modify source pins or financial metadata.
return {pins:route.map(p=>[...p]),plannedRoute:route,perimeter:null,walkedTrack:[]};
}GeoJSON Interchange Test
A test in the SatNav folder of GridAtlas that checks GeoJSON Interchange.
testgridatlas / tools/satnav/interchange/geojson-interchange.test.mjs · lines 1–17 of 17 · Entry point
- What it does
- It tests its inputs. Defines raw. Uses libraries node:test, node:assert/strict.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `raw`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/satnav/interchange · test
- Uses
- GeoJSON Interchange (import), node:test, node:assert/strict
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- raw
- Defines here
- raw
- 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/satnav/interchange/geojson-interchange.test.mjs:1-17 · blob a80acf46e34173f5d2abb4a2a10a0821c2c7a1c5 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {exportGeoJSON,importGeoJSON,importGisRouteSnapshot} from './geojson-interchange.mjs';
const a=[-0.3,51.5],b=[-0.31,51.51],c=[-0.32,51.5];
const data={pins:[a,b,c],plannedRoute:[a,b,c],perimeter:[a,b,c,a],walkedTrack:[{coordinate:b,timestamp:1000,accuracy:5},{coordinate:c,timestamp:2000,accuracy:8}]};
const raw=(type,coordinates,properties={})=>({type:'FeatureCollection',features:[{type:'Feature',geometry:{type,coordinates},properties}]});
test('full roundtrip retains independent planned and measured geometry',()=>assert.deepEqual(importGeoJSON(exportGeoJSON(data)),data));
test('one recorded fix survives',()=>assert.deepEqual(importGeoJSON(exportGeoJSON({walkedTrack:[data.walkedTrack[0]]})).walkedTrack,[data.walkedTrack[0]]));
test('untagged point is never measured GPS',()=>assert.deepEqual(importGeoJSON(raw('Point',a)).walkedTrack,[]));
test('generic line becomes planned route',()=>assert.deepEqual(importGeoJSON(raw('LineString',[a,b])).plannedRoute,[a,b]));
test('reject invalid coordinate and open polygon',()=>{assert.throws(()=>exportGeoJSON({pins:[[181,0]]}));assert.throws(()=>exportGeoJSON({perimeter:[a,b,c,b]}));});
test('reject unsupported holes rather than discard them',()=>assert.throws(()=>importGeoJSON(raw('Polygon',[[a,b,c,a],[a,b,c,a]]))));
test('reject bad GPS metadata and reverse time',()=>{assert.throws(()=>exportGeoJSON({walkedTrack:[{coordinate:a,timestamp:1,accuracy:-1}]}));assert.throws(()=>exportGeoJSON({walkedTrack:[...data.walkedTrack].reverse()}));});
test('reject duplicate waypoint order',()=>{const d=exportGeoJSON({pins:[a,b]});d.features[1].properties.order=0;assert.throws(()=>importGeoJSON(d));});
test('committed GIS route copied, source not mutated',()=>{const snap={schema:'ventus.gis-route.v1',status:'available',committed:true,route:{geometry:{type:'LineString',coordinates:[a,b]},properties:{export_cable_length_km:42}}};const before=JSON.stringify(snap);const out=importGisRouteSnapshot(snap);out.pins[0][0]=0;assert.deepEqual(out.plannedRoute,[a,b]);assert.equal(JSON.stringify(snap),before … [line shortened here: 405 characters; full line on GitHub]
test('editing, unavailable and uncommitted snapshots rejected',()=>{for(const status of ['editing','unavailable','invalid','ambiguous'])assert.throws(()=>importGisRouteSnapshot({schema:'ventus.gis-route.v1',status,committed:true}));assert.throws(()=>importGisRouteSnapshot({schema:'ventus.gis-route.v1',status:'available',committed:false}));});
test('export strips unrelated private properties',()=>assert.equal(JSON.stringify(exportGeoJSON({...data,account:'secret'})).includes('secret'),false));GeoJSON
A JavaScript module in the interchange folder of GridAtlas. It normalises geo JSON (`normaliseGeoJSON`) and exports geo JSON (`exportGeoJSON`).
geodesygridatlas / tools/satnav/interchange/geojson.mjs · lines 1–72 of 72 · pattern exportGeoJSON (shared by 5 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including normaliseGeoJSON, fail, point, line, feature.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 3 files: GeoJSON Test (gridatlas); Interchange (gridatlas); Model (gridatlas). Reached from 4 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Interchange Test (gridatlas); Layout Import Test (gridatlas).
- What it achieves
- Local 2D WGS84 interchange only; no network, legal access, engineering accuracy or route calculation.
- Why it matters
- Imported by Interchange and Model. Checked by GeoJSON Test.
- Application
- gridatlas · tools/satnav/interchange · JavaScript module
- Uses
- none found
- Used by
- imported by GeoJSON Test (import), imported by Interchange (import), imported by Model (import)
- Produces
- normaliseGeoJSON, fromGisSnapshot, exportGeoJSON
- Defines here
- normaliseGeoJSON, fail, point, line, feature, fromGisSnapshot, exportGeoJSON
- 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/satnav/interchange/geojson.mjs:1-72 · blob 21ccda11b5cee32296722d72a460b77893664804 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SPDX-License-Identifier: Apache-2.0
// Local 2D WGS84 interchange only; no network, legal access, engineering accuracy or route calculation.
// Source: GIS SLD read-only ventus.gis-route.v1 snapshot contract.
export function normaliseGeoJSON(input) {
const data=typeof input==="string"?JSON.parse(input):input;
const fail=message=>{throw Error(message);};
const MAX=20000;
let count=0;
const point=p=>{
if(!Array.isArray(p)||p.length!==2||!p.every(Number.isFinite)||Math.abs(p[0])>180||Math.abs(p[1])>90)fail("INVALID_WGS84_COORDINATE");
if(++count>MAX)fail("COORDINATE_LIMIT");
return p.slice();
};
const line=(p,min)=>{
if(!Array.isArray(p)||p.length<min||p.length>MAX)fail("INVALID_COORDINATE_SEQUENCE");
return p.map(point);
};
const feature=f=>{
if(f?.type!=="Feature"||!f.geometry)fail("INVALID_FEATURE");
const {type,coordinates}=f.geometry;
const source=f.properties??{};
if(typeof source!=="object"||Array.isArray(source))fail("INVALID_PROPERTIES");
const role=source.satnavRole??({Point:"waypoint",LineString:"planned-route",Polygon:"perimeter"}[type]);
const expected={"waypoint":"Point","planned-route":"LineString","perimeter":"Polygon","walked-track":"LineString"};
if(!Object.hasOwn(expected,role)||expected[role]!==type)fail("UNSUPPORTED_GEOMETRY_OR_ROLE");
let geometry,properties={satnavRole:role};
if(typeof source.name==="string")properties.name=source.name.slice(0,200);
if(type==="Point")geometry={type,coordinates:point(coordinates)};
else if(type==="LineString")geometry={type,coordinates:line(coordinates,2)};
else {
if(!Array.isArray(coordinates)||coordinates.length!==1)fail("ONLY_SINGLE_RING_SUPPORTED");
const ring=line(coordinates[0],4);
const first=ring[0],last=ring[ring.length-1];
if(first[0]!==last[0]||first[1]!==last[1])fail("RING_NOT_CLOSED");
if(new Set(ring.slice(0,-1).map(p=>JSON.stringify(p))).size<3)fail("RING_TOO_FEW_DISTINCT_POINTS");
geometry={type,coordinates:[ring]};
}
if(role==="walked-track"){
for(const key of ["timestampMs","accuracyM"]){
if(source[key]===undefined)continue;
const values=source[key];
if(!Array.isArray(values)||values.length!==geometry.coordinates.length||values.some(x=>x!==null&&(!Number.isFinite(x)||x<0)))fail("INVALID_TRACK_METADATA");
if(key==="timestampMs"){
let last=-Infinity;
for(const t of values){if(t===null)continue;if(t<last)fail("NON_MONOTONIC_TRACK_TIMESTAMPS");last=t;}
}
properties[key]=values.slice();
}
}
const result={type:"Feature",geometry,properties};
if(typeof f.id==="string"&&f.id.length<=200)result.id=f.id;
return result;
};
let features;
if(data?.type==="FeatureCollection")features=data.features;
else if(data?.type==="Feature")features=[data];
else if(["Point","LineString","Polygon"].includes(data?.type))features=[{type:"Feature",geometry:data}];
else fail("UNSUPPORTED_GEOJSON");
if(!Array.isArray(features)||features.length>MAX)fail("FEATURE_LIMIT");
const output=features.map(feature);
const ids=output.filter(f=>f.id!==undefined).map(f=>f.id);
if(new Set(ids).size!==ids.length)fail("DUPLICATE_FEATURE_ID");
return {type:"FeatureCollection",features:output};
}
export function fromGisSnapshot(snapshot){
if(snapshot?.schema!=="ventus.gis-route.v1"||snapshot.status!=="available"||snapshot.route?.geometry?.type!=="LineString")throw Error("GIS_ROUTE_UNAVAILABLE");
const route={type:"Feature",geometry:snapshot.route.geometry,properties:{satnavRole:"planned-route"}};
return normaliseGeoJSON(route);
}
export function exportGeoJSON(input){return JSON.stringify(normaliseGeoJSON(input),null,2);}GeoJSON Test
A test in the interchange folder of GridAtlas that checks GeoJSON. It runs tests (`runTests`).
testgridatlas / tools/satnav/interchange/geojson.test.mjs · lines 1–38 of 38 · Entry point · pattern reject (shared by 5 files)
- What it does
- It tests its inputs. Defines runTests, eq, reject, f.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `runTests` and `reject`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/satnav/interchange · test
- Uses
- GeoJSON (import)
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- runTests, eq, reject, f
- Defines here
- runTests, eq, reject, f
- 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/satnav/interchange/geojson.test.mjs:1-38 · blob 4bc53dfbb405298abf8ce8129663c1779d70eb6d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import { normaliseGeoJSON, fromGisSnapshot, exportGeoJSON } from "./geojson.mjs";
function runTests(normaliseGeoJSON,fromGisSnapshot,exportGeoJSON){
const eq=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error("ASSERT_EQUAL");};
const reject=(fn,msg)=>{try{fn();}catch(e){if(e.message===msg)return;throw e;}throw Error("EXPECTED "+msg);};
const f=(type,coordinates,properties={})=>({type:"Feature",geometry:{type,coordinates},properties});
const coords=[[-0.3,51.5],[-0.31,51.51]];
const track=f("LineString",coords,{satnavRole:"walked-track",timestampMs:[100,200],accuracyM:[5,null],untrusted:"discard"});
const route=f("LineString",coords,{name:"Cable design"});
const perimeter=f("Polygon",[[[0,0],[1,0],[1,1],[0,0]]]);
const point=f("Point",coords[0]);
const collection={type:"FeatureCollection",features:[point,route,perimeter,track]};
const tests=[
()=>eq(normaliseGeoJSON(collection).features.map(x=>x.properties.satnavRole),["waypoint","planned-route","perimeter","walked-track"]),
()=>eq(normaliseGeoJSON(exportGeoJSON(collection)),normaliseGeoJSON(collection)),
()=>eq(normaliseGeoJSON(track).features[0].properties,{satnavRole:"walked-track",timestampMs:[100,200],accuracyM:[5,null]}),
()=>{const a=normaliseGeoJSON(collection);a.features[0].geometry.coordinates[0]=9;eq(point.geometry.coordinates[0],-0.3);},
()=>eq(fromGisSnapshot({schema:"ventus.gis-route.v1",status:"available",route}).features[0].geometry,route.geometry),
()=>reject(()=>fromGisSnapshot({schema:"ventus.gis-route.v1",status:"editing",route}),"GIS_ROUTE_UNAVAILABLE"),
()=>reject(()=>normaliseGeoJSON(f("Point",[181,0])),"INVALID_WGS84_COORDINATE"),
()=>reject(()=>normaliseGeoJSON(f("Point",[0,NaN])),"INVALID_WGS84_COORDINATE"),
()=>reject(()=>normaliseGeoJSON(f("Point",[0,0,10])),"INVALID_WGS84_COORDINATE"),
()=>reject(()=>normaliseGeoJSON(f("Polygon",[[[0,0],[1,0],[1,1],[0,1]]])),"RING_NOT_CLOSED"),
()=>reject(()=>normaliseGeoJSON(f("Polygon",[[[0,0],[1,0],[1,0],[0,0]]])),"RING_TOO_FEW_DISTINCT_POINTS"),
()=>reject(()=>normaliseGeoJSON(f("Polygon",[perimeter.geometry.coordinates[0],perimeter.geometry.coordinates[0]])),"ONLY_SINGLE_RING_SUPPORTED"),
()=>reject(()=>normaliseGeoJSON(f("Point",[0,0],{satnavRole:"walked-track"})),"UNSUPPORTED_GEOMETRY_OR_ROLE"),
()=>reject(()=>normaliseGeoJSON(f("LineString",coords,{satnavRole:"walked-track",timestampMs:[200,100]})),"NON_MONOTONIC_TRACK_TIMESTAMPS"),
()=>reject(()=>normaliseGeoJSON(f("LineString",coords,{satnavRole:"walked-track",accuracyM:[5]})),"INVALID_TRACK_METADATA"),
()=>reject(()=>normaliseGeoJSON(f("LineString",coords,{satnavRole:"walked-track",accuracyM:[-1,2]})),"INVALID_TRACK_METADATA"),
()=>eq(normaliseGeoJSON(f("LineString",coords,{satnavRole:"walked-track"})).features[0].properties,{satnavRole:"walked-track"}),
()=>reject(()=>normaliseGeoJSON({type:"FeatureCollection",features:[{...point,id:"a"},{...point,id:"a"}]}),"DUPLICATE_FEATURE_ID"),
()=>reject(()=>normaliseGeoJSON(f("LineString",Array.from({length:20001},()=>[0,0]))),"INVALID_COORDINATE_SEQUENCE"),
()=>eq(normaliseGeoJSON({type:"Point",coordinates:[0,0]}).features[0].properties,{satnavRole:"waypoint"}),
()=>reject(()=>normaliseGeoJSON(f("Point",[0,0],{satnavRole:"__proto__"})),"UNSUPPORTED_GEOMETRY_OR_ROLE"),
];
tests.forEach((t,i)=>{try{t();}catch(e){throw Error(`Test ${i+1}: ${e.message}`);}});
return tests.length;
}
console.log(`${runTests(normaliseGeoJSON,fromGisSnapshot,exportGeoJSON)} tests passed`);Layout Browser
A Python command-line tool in the interchange folder of GridAtlas that reads field, native GIS single-line diagram (SLD), cables and 33kV, using EPSG:27700.
rendergridatlas / tools/satnav/interchange/layout-browser.py · lines 1–128 of 128 · Entry point · pattern local_file (shared by 2 files)
- What it does
- It loads field, native GIS SLD, cables and 33kV. Defines feature, local_file, check_browser. Uses libraries json, os, runpy, pathlib, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables, 33kV.
- Inputs & outputs
- In: user-supplied file (file picker). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It checks browser (`check_browser`) and is built from the feature step (`feature`) and the local file helper (`local_file`). Exercise local layout import, edit, export and failure recovery on the V4 map. Its code works with 33 kV.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/satnav/interchange · Python CLI
- Uses
- json, os, runpy, pathlib, playwright.sync_api
- Used by
- none found
- Produces
- feature, local_file, check_browser
- Defines here
- feature, local_file, check_browser
- 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/satnav/interchange/layout-browser.py:1-128 · blob eebdbcb082233f49c89341aa27e4a67b18091a14 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Exercise local layout import, edit, export and failure recovery on the V4 map."""
import json
import os
import runpy
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
SATNAV = Path(__file__).resolve().parents[1]
GPS_SPY = runpy.run_path(str(SATNAV / "compact-browser.py"))["GPS_SPY"]
SITE = os.environ.get("LINE_TEST_URL", "http://127.0.0.1:8873/atlas/v/satnav-layout-202611281330/")
A, B, C = [-2.605, 51.45], [-2.606, 51.451], [-2.607, 51.45]
def feature(kind, coords, **properties):
return {"type": "Feature", "geometry": {"type": kind, "coordinates": coords}, "properties": properties}
def local_file(input_element, data):
input_element.set_input_files({
"name": "field.geojson", "mimeType": "application/geo+json",
"buffer": json.dumps(data).encode(),
})
def check_browser(browser, name, width, height):
with browser.new_context(viewport={"width": width, "height": height}, is_mobile=True, has_touch=True) as context:
context.add_init_script(GPS_SPY)
page = context.new_page()
leaks = []
marker = "SV07-local-roundtrip-probe"
page.on("request", lambda req: leaks.append(req.url) if marker in (req.url + (req.post_data or "")) else None)
page.goto(SITE, wait_until="domcontentloaded")
locate = page.locator("#satnav-location")
expect(locate).to_be_enabled(timeout=45000)
locate.tap()
page.evaluate("at => window.__lineGpsTest.emit(at, 5)", A)
survey = "document.querySelector('#satnav-compact').satnavSurvey"
page.wait_for_function(survey + ".getFix() !== null")
panel = page.locator("#satnav-layout")
panel.locator("summary").tap()
picker = panel.locator("input[type=file]")
walk = panel.get_by_role("button", name="Use for walk")
status = panel.get_by_role("status")
data = {"type": "FeatureCollection", "features": [
feature("LineString", [A, B], satnavRole="planned-route", name=marker),
feature("Point", C, satnavRole="waypoint", name="Design pole"),
feature("Point", A, satnavRole="walked-fix", timestampMs=1000, accuracyM=5),
feature("LineString", [B, C], satnavRole="walked-track", timestampMs=[2000, 3000], accuracyM=[4, 4]),
]}
local_file(picker, data)
expect(status).to_contain_text("2 design · 2 recorded")
page.wait_for_function("""() => {
const map = window.__GRIDATLAS_V9_MAP__;
const features = map?.getSource('satnav-imported-layout')?.serialize()?.data?.features;
return features?.length === 4 && map.getLayer('satnav-imported-layout-design') &&
map.getLayer('satnav-imported-layout-fix');
}""")
assert panel.locator("select option").count() == 2
assert page.evaluate(survey + ".getEndpoints()") == [A, None]
panel.get_by_role("combobox").select_option(label=marker)
walk.tap()
assert page.evaluate(survey + ".getEndpoints()") == [A, B]
panel.get_by_role("combobox").select_option(label="Design pole")
walk.tap()
assert page.evaluate(survey + ".getEndpoints()") == [A, C]
assert page.evaluate("window.__lineGpsTest.records") == {"starts": [1], "stops": []}
with page.expect_download() as export:
panel.get_by_role("button", name="Save layout GeoJSON").tap()
assert json.loads(export.value.path().read_text()) == data
invalid = {**data, "crs": {"type": "name", "properties": {"name": "EPSG:27700"}}}
local_file(picker, invalid)
expect(status).to_contain_text("Import failed")
assert page.evaluate(survey + ".getEndpoints()") == [A, C]
assert panel.locator("select option").count() == 2
assert page.evaluate("window.__GRIDATLAS_V9_MAP__.getSource('satnav-imported-layout').serialize().data") == data
local_file(picker, data["features"][2])
expect(status).to_contain_text("0 design · 1 recorded")
expect(walk).to_be_hidden()
assert page.evaluate(survey + ".getEndpoints()") == [A, C]
panel.get_by_role("button", name="Show layout on map").tap()
centre = page.evaluate("window.__GRIDATLAS_V9_MAP__.getCenter().toArray()")
assert all(abs(x-y) < 0.00001 for x, y in zip(centre, A)), centre
local_file(picker, {"schema": "ventus.gis-route.v1", "status": "available", "committed": True,
"route": feature("LineString", [C, B], type="export_cable"), "pins": []})
expect(status).to_contain_text("1 design · 0 recorded")
walk.tap()
assert page.evaluate(survey + ".getEndpoints()") == [C, B]
native_fixture = Path(__file__).parent / "fixtures/native-gis-sld.geojson"
native = json.loads(native_fixture.read_text())
cable = next(f["geometry"]["coordinates"] for f in native["features"] if f["properties"]["type"] == "export_cable")
picker.set_input_files(native_fixture)
expect(status).to_contain_text("15 design · 0 recorded")
options = panel.locator("select option").all_text_contents()
assert options[0] == "Export cable 1" and "33 kV collector trunk 1" in options and "33 kV block branch 2" in options, options
assert all("Ordered waypoints" not in item for item in options)
walk.tap()
assert page.evaluate(survey + ".getPins().map(pin => pin.coordinate)") == cable
with page.expect_download() as native_export:
panel.get_by_role("button", name="Save layout GeoJSON").tap()
converted = json.loads(native_export.value.path().read_text())
assert {f["properties"]["gisRole"] for f in converted["features"] if "gisRole" in f["properties"]} == {"collector_trunk", "block_branch"}
assert "fin_total_capex_gbp" not in json.dumps(converted)
local_file(picker, converted)
expect(status).to_contain_text("field.geojson · 15 design")
assert panel.locator("select option").all_text_contents() == options
page.locator("#satnav-stop").tap()
assert page.evaluate("window.__lineGpsTest.records") == {"starts": [1], "stops": [1]}
assert not leaks, leaks
print(f"{name} {width}×{height}: GIS import, layout selection, GPS continuity, role separation, "
"GeoJSON download and failed-import recovery passed", flush=True)
if __name__ == "__main__":
with sync_playwright() as driver:
for engine in os.environ.get("LINE_TEST_BROWSERS", "chromium,webkit").split(","):
options = {"args": ["--enable-webgl", "--use-gl=angle", "--use-angle=swiftshader",
"--enable-unsafe-swiftshader"]} if engine == "chromium" else {}
with getattr(driver, engine).launch(**options) as browser:
for viewport in [(390, 664), (664, 390)]:
check_browser(browser, engine, *viewport)Layout Import
A JavaScript module in the interchange folder of GridAtlas that checks reference system (`checkReferenceSystem`) and reads features (`readFeatures`), covering cables, using EPSG:4326.
ingestgridatlas / tools/satnav/interchange/layout-import.mjs · lines 1–129 of 129
- What it does
- Defines 6 functions or classes, including checkReferenceSystem, sourceFeature, readFeatures, readLayout, layoutChoices.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- Used directly by 1 file: Layout Import Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It checks reference system (`checkReferenceSystem`), reads features (`readFeatures`) and reads layout (`readLayout`). Its `readLayout` function gives validated survey layout features with geometry and role metadata from GeoJSON object or JSON text, supported layout schema and WGS84 coordinates (VEDIC: import engineering layout).
- Why it matters
- Checked by Layout Import Test.
- Application
- gridatlas · tools/satnav/interchange · JavaScript module
- VEDIC
- IMPORT ENGINEERING LAYOUT (GG2050-VEDIC-000101): SatNav · Location and navigation data. GeoJSON object or JSON text, supported layout schema and WGS84 coordinates → Validated survey layout features with geometry and role metadata.
- Uses
- Interchange (import), GeoJSON Interchange (import)
- Used by
- imported by Layout Import Test (import)
- Produces
- MAX_FILE_BYTES, readLayout, layoutChoices, walkLayoutChoice
- Defines here
- checkReferenceSystem, sourceFeature, readFeatures, readLayout, layoutChoices, walkLayoutChoice
- 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/satnav/interchange/layout-import.mjs:1-129 · blob c69eed26260fc5ad3d2bdb72d5730b3cf47ffd19 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import { readSurveyLayout, editableCoordinates, GIS_TYPES, RADIAL_NAMES } from '../survey/interchange.mjs';
import {
importGeoJSON as readLegacySurvey,
exportGeoJSON as writeLegacySurvey,
} from './geojson-interchange.mjs';
export const MAX_FILE_BYTES = 16 * 1024 * 1024;
const MAX_COORDINATES = 64000;
const MAX_ROUTE_PINS = 20000;
const WGS84 = new Set(['OGC:CRS84', 'URN:OGC:DEF:CRS:OGC:1.3:CRS84', 'EPSG:4326', 'URN:OGC:DEF:CRS:EPSG::4326']);
const ROLE_NAMES = {
waypoint: 'Waypoint', 'planned-route': 'Planned line', perimeter: 'Perimeter',
'walked-track': 'Recorded track', 'walked-fix': 'Recorded fix',
};
function checkReferenceSystem(value) {
if (!value?.crs) return;
const name = value.crs.properties?.name;
if (value.crs.type !== 'name' || typeof name !== 'string' || !WGS84.has(name.toUpperCase())) {
throw Error('Convert the layout to WGS84 longitude and latitude before importing.');
}
}
// Preserve an engineering layer label when the GIS exporter only supplies its type.
function sourceFeature(feature, nativeLayout = false) {
if (feature?.type !== 'Feature' || !feature.geometry) throw Error('Each layout feature needs a geometry.');
checkReferenceSystem(feature);
checkReferenceSystem(feature.geometry);
const props = feature.properties ?? {};
if (typeof props !== 'object' || Array.isArray(props)) throw Error('Invalid feature properties.');
const known = Object.hasOwn(GIS_TYPES, props.type);
const extra = {};
const hasName = typeof props.name === 'string' && props.name.trim();
if (typeof props.label === 'string' && props.label.trim() && !hasName) extra.name = props.label.trim().slice(0, 200);
if (nativeLayout && !known && feature.geometry.type === 'LineString' && !props.satnavRole && !props.role) {
extra.gisReferenceOnly = true;
}
return { ...feature, properties: { ...props, ...extra } };
}
function readFeatures(doc) {
checkReferenceSystem(doc);
if (doc?.schema === 'ventus.gis-route.v1') {
checkReferenceSystem(doc.route);
checkReferenceSystem(doc.route?.geometry);
const [route] = readSurveyLayout(doc).features;
route.properties.type = 'export_cable';
const name = doc.route.properties?.name;
if (typeof name === 'string' && name.trim()) route.properties.name = name.trim().slice(0, 200);
return [route];
}
if (doc?.schema === 'ventus.satnav.geojson.v1') {
if (!Array.isArray(doc.features) || doc.features.length > MAX_COORDINATES) throw Error('Too many features.');
for (const feature of doc.features) {
checkReferenceSystem(feature);
checkReferenceSystem(feature?.geometry);
if (feature?.properties?.satnavRole !== undefined && feature.properties.satnavRole !== feature.properties.role) {
throw Error('A survey feature has conflicting roles.');
}
}
return writeLegacySurvey(readLegacySurvey(doc)).features;
}
if (doc?.schema !== undefined) throw Error('Unsupported layout schema.');
if (doc?.type === 'FeatureCollection') return doc.features;
if (doc?.type === 'Feature') return [doc];
if (['Point', 'LineString', 'Polygon'].includes(doc?.type)) return [{ type: 'Feature', geometry: doc }];
throw Error('Choose a GeoJSON layout or a GIS SLD route snapshot.');
}
export function readLayout(input) {
const doc = typeof input === 'string' ? JSON.parse(input) : input;
const features = readFeatures(doc);
if (!Array.isArray(features) || !features.length || features.length > MAX_COORDINATES) {
throw Error('The layout is empty or exceeds the feature limit.');
}
const nativeLayout = features.some(f => Object.hasOwn(GIS_TYPES, f?.properties?.type));
const result = readSurveyLayout({ type: 'FeatureCollection', features: features.map(f => sourceFeature(f, nativeLayout)) });
let count = 0;
for (const { geometry } of result.features) {
const coordinates = geometry.coordinates;
count += geometry.type === 'Point' ? 1 : geometry.type === 'Polygon' ? coordinates[0].length : coordinates.length;
if (count > MAX_COORDINATES) throw Error('The layout exceeds 64,000 coordinates.');
}
return result;
}
export function layoutChoices(layout) {
const choices = [];
const cables = [];
const pins = [];
const counts = Object.create(null);
const nativeLayout = layout.features.some(f => Object.hasOwn(GIS_TYPES, f.properties.type));
for (const [index, feature] of layout.features.entries()) {
const {satnavRole:role, type, gisRole, gisReferenceOnly} = feature.properties;
if (role === 'walked-track' || role === 'walked-fix' || gisReferenceOnly) continue;
const sourceLabel = Object.hasOwn(GIS_TYPES, type) ? GIS_TYPES[type][1] : '';
const kind = Object.hasOwn(RADIAL_NAMES, gisRole) ? RADIAL_NAMES[gisRole] :
sourceLabel || (nativeLayout && role === 'waypoint' ? 'Site point' : ROLE_NAMES[role]);
counts[kind] = (counts[kind] ?? 0) + 1;
const label = feature.properties.name?.trim() || kind + ' ' + counts[kind];
const target = type === 'export_cable' ? cables : choices;
target.push({index, label, role});
if (role === 'waypoint' && !nativeLayout) pins.push(index);
}
if (pins.length > 1 && pins.length <= MAX_ROUTE_PINS) {
choices.unshift({ index: -1, label: 'Ordered waypoints (' + pins.length + ')', role: 'waypoints', pins });
}
return cables.concat(choices);
}
export function walkLayoutChoice(survey, layout, choice) {
if (!choice) throw Error('Select a design feature for the walk.');
if (choice.role === 'waypoints') {
if (layout.features.some(f => Object.hasOwn(GIS_TYPES, f.properties.type))) throw Error('Select a design line or individual site point.');
const coordinates = choice.pins.map(index => {
const pin = layout.features[index];
if (pin?.properties.satnavRole !== 'waypoint') throw Error('Invalid waypoint selection.');
return [...pin.geometry.coordinates];
});
return survey.replacePlan(coordinates);
}
const selected = layout.features[choice.index];
const role = selected?.properties.satnavRole;
const points = editableCoordinates(selected);
if (!points) throw Error('Choose a design feature for the walk.');
if (role === 'waypoint') return survey.setDestination(points[0]);
if (role === 'perimeter') points.push([...points[0]]);
return survey.replacePlan(points);
}