In this section
- Single-Line Diagram (SLD) Sandbox Arrival Identity geodesy · gridatlas / atlas/parts/202609040229-sld-sandbox-arrival-identity.js lines 3887–4586
Single-Line Diagram (SLD) Sandbox Arrival Identity
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.
geodesygridatlas / atlas/parts/202609040229-sld-sandbox-arrival-identity.js · lines 3887–4586 of 5948 · version 2026-09-04 02:29 (continued from section 419) · Not reached from any entry point (candidate for review) · pattern retryIdentityOwnerThenArrival (shared by 8 files)
- What it does
- It maps grid substations, solar, transformers and 400kV. Defines 187 functions or classes, including coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: solar, transformers, 400kV, 750kV, 415kV, 275kV.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; browser storage (getItem); DuckDB queries; form fields (user input). Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 66kV, 33kV.
- What it achieves
- It resolves declared connection (`resolveDeclaredConnection`), opens corridor sheet (`openCorridorSheet`) and runs grid point (`runGridAtPoint`). GridAtlas cartridge — neon substation links and the SLD layout sandbox. Its code works with 400 kV, 33 kV and 132 kV. It responds to click, keydown and touchstart events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/parts · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- none found
- Used by
- none found
- Produces
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet
- Defines here
- installGbConditions, setSourceData, interactiveLayerIds, install, selectAt, waitForResolvedIdentity, runDeepLink, framed, honourRequestedZoom, apply, coordsUsable, enableBoth, arrive, runArrivalSelection
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040229-sld-sandbox-arrival-identity.js:3887-4586 · blob 2c1486ea5aef879022fc222d4363b779d22e165b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: duplicate_candidate
button.addEventListener('click', (event) => {
event.stopPropagation();
pointArmed = !pointArmed;
button.setAttribute('aria-pressed', String(pointArmed));
button.style.outline = pointArmed ? '1px solid currentColor' : '';
link.grid_point_armed = pointArmed;
if (!pointArmed) clearScope();
});
tray.appendChild(button);
}());
const grid = quickChip('\u26a1 Grid', GRID_LINE_LAYERS);
const subs = quickChip('\u25c9 Subs', ['subs']);
/* Arming is explicit. A map that analysed every stray tap would put a
card over the thing the reader was trying to look at. */
const scopeChip = document.createElement('button');
scopeChip.type = 'button';
scopeChip.textContent = '\u25ce Scope';
scopeChip.setAttribute('aria-pressed', 'false');
scopeChip.addEventListener('click', (event) => {
event.stopPropagation();
scopeArmed = !scopeArmed;
scopeChip.setAttribute('aria-pressed', String(scopeArmed));
if (!scopeArmed) clearScope();
link.grid_scope_armed = scopeArmed;
});
const clearChip = document.createElement('button');
clearChip.type = 'button';
clearChip.textContent = '\u2715 Clear';
clearChip.addEventListener('click', (event) => {
event.stopPropagation();
clearScope();
clearLinks();
});
tray.appendChild(tools);
tray.appendChild(grid);
tray.appendChild(subs);
tray.appendChild(scopeChip);
tray.appendChild(clearChip);
tray.addEventListener('click', (event) => event.stopPropagation());
stack.insertBefore(tray, stack.firstChild);
// The engine builds its switches only after the map loads; the chips
// wake when the switches exist and follow them wherever they are
// toggled from - scada panel, fullscreen curtain, or a deep link.
document.addEventListener('change', (event) => {
if (event.target?.dataset?.layerId) { grid.gmReflect(); subs.gmReflect(); }
});
let polls = 0;
const poll = setInterval(() => {
grid.gmReflect(); subs.gmReflect(); polls += 1;
if (!grid.disabled || polls > 200) clearInterval(poll);
}, 300);
link.mobile_tray = {
installed: true,
tools_collapsed: true,
grid_quick_layers: GRID_LINE_LAYERS.length,
subs_quick: true
};
}
function installGbConditions() {
if (document.getElementById(GB_ID)) return;
const stack = document.querySelector('.map-controls');
if (!stack) { link.failures.push('no map-controls for the GB panel'); return; }
const style = document.createElement('style');
style.id = GB_ID + '-style';
style.textContent = `
#${GB_ID}{margin-top:6px;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
#${GB_ID} > button{display:block;width:100%;padding:6px 8px;background:#0a1a1d;
border:1px solid #2f6f75;border-radius:3px;color:#8fb3b8;font:inherit;
letter-spacing:.06em;text-transform:uppercase;cursor:pointer;text-align:left}
#${GB_ID} > button:hover{border-color:#5fbdc2;color:#bfe9ee}
#${GB_ID} .gb-body{display:none;margin-top:5px;padding:8px;border:1px solid #1d3238;
border-radius:3px;background:rgba(6,18,21,.94);max-width:min(88vw,260px);
max-height:min(52vh,340px);overflow:auto;overscroll-behavior:contain}
#${GB_ID}[data-open="1"] .gb-body{display:block}
#${GB_ID} .gb-row{display:flex;justify-content:space-between;gap:8px;
padding:2px 0;border-bottom:1px solid #142226}
#${GB_ID} .gb-k{color:#7d8f95}
#${GB_ID} .gb-v{color:#bfe9ee;font-weight:bold}
#${GB_ID} .gb-v em{color:#5f7a80;font-style:normal;font-weight:normal;font-size:10px}
#${GB_ID} .gb-note{margin:7px 0 0;color:#6f8288;font-size:10px;line-height:1.45}
#${GB_ID} .gb-note.gb-point{color:#9fb3ba;border-top:1px solid #142226;padding-top:6px}
#${GB_ID} .gb-note.gb-point b{color:#d8a76a}
#${GB_ID} .gb-more{display:block;margin-top:7px;color:#5fbdc2;font-size:10px;
text-decoration:none;letter-spacing:.04em}
#${GB_ID} .gb-more:hover{text-decoration:underline}`;
document.head.appendChild(style);
const panel = document.createElement('div');
panel.id = GB_ID;
panel.dataset.open = '0';
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'GB prices · historic ▸';
button.setAttribute('aria-expanded', 'false');
const body = document.createElement('div');
body.className = 'gb-body';
panel.appendChild(button);
panel.appendChild(body);
let loaded = false;
button.addEventListener('click', (event) => {
// The panel lives inside the map container, so without this the click
// carries on to the map underneath and selects whatever is there.
event.stopPropagation();
event.preventDefault();
const open = panel.dataset.open === '1';
panel.dataset.open = open ? '0' : '1';
button.textContent = open ? 'GB prices · historic ▸' : 'GB prices · historic ▾';
button.setAttribute('aria-expanded', String(!open));
// Fetched on first open, never at boot: nothing about the map should
// wait on a third party, and most sessions never open this.
if (!open && !loaded) {
loaded = true;
body.innerHTML = '<p class="gb-note">Reading the decade…</p>';
renderGbConditions(body);
}
});
panel.addEventListener('click', (event) => event.stopPropagation());
stack.appendChild(panel);
link.gb_panel_installed = true;
}
/* Never dereference a source without checking it is there.
----------------------------------------------------------------------
addSource throws if the style is not loaded, and a source that failed to
add reads back as null. Both happen: the basemap CDN served style.json and
then no tiles at all on this estate tonight, and the cartridge now boots on
the style rather than a painted frame precisely so it can work in that
condition.
The pin was guarded when that was found. Five call sites were not, and
they are the ones that draw the links, the nodes and the whole layout — so
the guarded convenience survived while the substance would have thrown.
Codex's gate has been finding this class all night; this is the last of it
in this file.
Returning false rather than throwing means a missing source costs the
drawing, not the card, the distances or the session. */
function setSourceData(map, id, data) {
try {
const source = map?.getSource?.(id);
if (!source || typeof source.setData !== 'function') {
link.failures.push('source missing, nothing drawn: ' + id);
return false;
}
source.setData(data);
return true;
} catch (error) {
link.failures.push('source ' + id + ': ' + String(error?.message || error));
return false;
}
}
function interactiveLayerIds(map) {
// Whatever the engine has made visible and interactive. Reading the style
// rather than hard-coding ids keeps this working as layers come and go.
try {
return map.getStyle().layers
.filter(layer => /^l-/.test(layer.id) && layer.type !== 'background')
.map(layer => layer.id)
.filter(id => {
try { return map.getLayoutProperty(id, 'visibility') !== 'none'; }
catch (_) { return false; }
});
} catch (_) {
return [];
}
}
function install(map) {
installStyles();
ensureLayers(map);
/* Warm the substation payload immediately. It is 1.2 MB and every
measurement needs it; until v9.54 it was first requested only after
the arrival had finished waiting for the engine's layer controls,
so a phone paid for the wait AND the fetch in series. The promise is
cached, so the arrival reuses whatever this started. */
try { loadSubstations(); } catch (_) { /* the arrival will retry */ }
// The lines belong to the card. When the card closes, they go with it --
// leaving neon on the map with nothing explaining it is how a screenshot
// ends up quoted without its caveat.
const popupWatcher = new MutationObserver(() => {
if (link.links_drawn > 0 && !document.querySelector('.maplibregl-popup')) clearLinks();
});
try {
popupWatcher.observe(map.getContainer(), { childList: true, subtree: true });
} catch (error) {
link.failures.push(String(error?.message || error));
}
// Registered after the engine's own click handler, so the engine's popup
// opens first and this decorates it rather than racing it.
// Measure and draw for one selection. Split out of the click handler so a
// deep link, which opens a card without anybody clicking, goes through
// exactly the same path.
async function selectAt(origin, name, tech, fromSubstation, statedMw,
expectedArrivalEpoch = null) {
const fromCurrentArrival = Number.isInteger(expectedArrivalEpoch);
if (fromCurrentArrival) {
if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
} else {
invalidatePendingArrival('new-selection');
}
clearScope();
// Keep a provisional declared block standing until the measured one
// replaces it; clearing here would blank the card mid-arrival.
if (!currentDeclared?.pending) currentDeclared = null;
currentNearest400 = null;
currentPolicy = null;
if (fromSubstation) {
// No fetch needed: the projects are already in the engine's own
// source, and reading them there keeps one set of coordinates.
const found = nearestProjects(map, origin[0], origin[1]);
drawLinks(map, origin, name, tech, found.links, 'from-substation',
null, found.loaded);
return;
}
/* OFFSHORE MEASURES NOW.
--------------------------------------------------------------------
This used to return here with an empty link list and a card that
explained why nothing was measured. It measures instead. An offshore
project reaches an offshore substation, an export cable and a
landfall before anything onshore - every word of that is still true
and still printed - but the export cable does land at an onshore
substation, so the distance to the nearest mapped one is a
measurement of a real thing rather than a number with nothing behind
it. Withholding it was over-caution.
The route reasoning is not deleted; it moves from being the reason
there is no number to being the caveat beside the number, which is
where the estate puts every other thing a distance cannot answer.
No onshore-only filter is applied, and the card says so. The pinned
substation product carries the OSM `location` tag on zero of its
5,800 features, and of the 14 whose NAME contains "offshore" at least
4 are onshore substations serving an offshore farm - Hornsea at
400/220 kV among them, which is exactly a landfall connection. A
name-based filter would drop those four from the search it was meant
to sharpen. Measured, not assumed; the module carries the counts. */
const policy = coverage.policy(tech);
currentPolicy = policy;
if (!link.substations_qualifying) {
injectStatusStyle();
showStatus('Loading the substation data \u2014 the links need it.',
'waiting');
}
const subs = await loadSubstations();
if (fromCurrentArrival && !arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
if (!subs.length) {
/* The register carries 5,800 substations; zero qualifying means the
payload did not arrive, not that the map is empty here. Drawing
nothing silently is how this looked broken on a phone. */
injectStatusStyle();
showStatus('The substation data did not load, so no links can be '
+ 'drawn. This is usually the network rather than the project.',
'failed');
return;
}
clearStatus();
currentDeclared = resolveDeclaredConnection(currentRepdRef, origin, subs);
currentNearest400 = nearestTransmission(origin, subs);
drawLinks(map, origin, name, tech,
nearestSubstations(origin[0], origin[1], subs), 'to-substation', statedMw);
return true;
}
link.selectAt = selectAt;
map.on('click', async (event) => {
try {
if (fromOwnUi(event)) return;
const ids = interactiveLayerIds(map);
if (!ids.length) return;
let features = [];
try { features = map.queryRenderedFeatures(event.point, { layers: ids }); }
catch (_) { return; }
if (!features.length) { clearLinks(); return; }
// Either end of a link is a valid place to start. Whichever pixel was
// clicked, the card that came up is the one the distances are written
// onto, and the lines run to the other end.
const hit = features.find(feature => {
const properties = feature.properties || {};
const tech = String(properties.tech || properties.type || '');
return isProjectTech(tech) || feature.layer?.id === SUBS_LAYER_ID;
});
if (!hit) {
/* The anchor is untouched: a project or substation click still
draws the neons. Only a click that hit NEITHER reaches here,
and only then if the reader armed the scope. */
clearLinks();
if (pointArmed) await runGridAtPoint(map, event.lngLat.lng, event.lngLat.lat);
if (scopeArmed) await runGridScope(map, [event.lngLat.lng, event.lngLat.lat]);
return;
}
const properties = hit.properties || {};
const fromSubstation = hit.layer?.id === SUBS_LAYER_ID;
const tech = String(properties.tech || properties.type || '');
const origin = representativePoint(hit.geometry)
|| [event.lngLat.lng, event.lngLat.lat];
const name = properties.name || properties.SiteName || properties['Site Name']
|| (fromSubstation ? 'Unnamed substation' : 'Unnamed project');
const stated = Number(properties.capacity);
currentRepdRef = fromSubstation
? null : String(properties.repd_ref || properties.repdRef || '');
await selectAt(origin, name, tech, fromSubstation,
Number.isFinite(stated) && stated > 0 ? stated : null);
} catch (error) {
link.failures.push(String(error?.message || error));
}
});
/* ── arrival by identity ─────────────────────────────────────────────
The search cartridge resolves repd_ref against the register - DuckDB
over the pinned parquet - flies there and opens the card. When a link
carries only that identity, this lane used to stop at its URL guards
while the card opened anyway, which reads as a broken map. The register
knows the coordinates and technology better than any URL restatement,
so when the identity lane has resolved, its published result is the
arrival. One resolver per composition; this lane only consumes.
The budget is generous because the identity lane boots a 35.7 MB query
engine first on a cold phone. Terminal failure or absence returns null
and is the caller's decision to record. */
async function waitForResolvedIdentity(options = {}) {
const announce = options.announce !== false;
/* v9.44 gave this a fixed 120s budget and Vikram's phone exceeded it:
the identity lane boots a 35.7 MB query engine first, the budget
expired, this lane gave up permanently, and the card then opened
anyway - a resolved identity with nothing computed for it. The
estate's own late-layers lesson, relearned: a fixed budget is always
the wrong number. RESOLVED, FAILED and ABSENT are terminal; the only
unbounded case is "still working", and waiting through it is the
correct behaviour. The user is told what is being waited for; ten
minutes is kept as a last-resort stop for a lane that died silently. */
const started = Date.now();
let told = false;
for (;;) {
const dl = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
if (dl) {
if (dl.status === 'RESOLVED') { if (told) clearStatus(); return dl; }
if (dl.status === 'FAILED' || dl.status === 'ABSENT'
|| dl.status === 'NOT_IN_ACTIVE_REGISTER'
|| dl.status === 'CANCELLED') {
if (told) clearStatus();
return dl;
}
}
const waited = Date.now() - started;
if (announce && !told && waited > 6000) {
told = true;
injectStatusStyle();
showStatus('Resolving the project against the register \u2014 a cold '
+ 'phone boots the query engine first, and this can take a minute.',
'waiting');
}
if (waited > 600000) {
link.failures.push('identity lane still not terminal after 10 minutes');
if (told) clearStatus();
return null;
}
await new Promise(resolve => setTimeout(resolve, 250));
}
}
// A deep link opens the project card on its own, with no click anywhere.
// Arriving that way is how most people reach the Atlas -- the MAP button in
// Pipeline News sends them here -- so the measurement has to run for it
// too, or the card that brought them arrives with nothing on it.
async function runDeepLink(expectedArrivalEpoch = null) {
try {
const q = new URLSearchParams(window.location.search);
const epoch = Number.isInteger(expectedArrivalEpoch)
? expectedArrivalEpoch : claimPendingArrival(window.location.search);
if (!arrivalGate.isCurrent(epoch)) return false;
link.arrival_reconciliation = {
status: 'MEASUREMENT_CLAIMED', epoch,
owner_epoch: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.owner_epoch ?? null
};
/* Number(null) is 0, not NaN, so a link with no coordinates used to
pass the finite guard as Null Island and only the technology
guard stopped it. Absent now means absent. */
const rawLon = q.get('longitude');
const rawLat = q.get('latitude');
const receiverPlan = deepLinkPlan(rawLon, rawLat, q.get('repd_ref'));
let lon = receiverPlan.longitude;
let lat = receiverPlan.latitude;
const repdRef = receiverPlan.repd_ref;
let tech = String(q.get('technology') || '');
let name = q.get('project') || 'Deep-linked project';
let stated = Number(q.get('capacity_mw'));
const suppliedStatus = String(q.get('status') || '').trim();
currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;
/* zoom: set on every deep link, and until now read by nobody.
------------------------------------------------------------------
The deep scan of 202609012230 compared both sides of the contract:
Pipeline News sets seven parameters and GridAtlas read six. There is
no get('zoom') anywhere in this repository. Arrival zoom came from
`map.flyTo({ zoom: 12 })` hard-coded in the immutable shell, and
Pipeline News happens to send 12 - so the two agreed by coincidence,
and the day somebody tuned the sending side nothing would have moved.
The shell cannot be edited, so the cartridge honours the parameter
after the shell has finished its own move. Bounded to what MapLibre
and the payload can actually render, and a value outside that range
is recorded rather than clamped silently. */
const rawZoom = q.get('zoom');
const requestedZoom = rawZoom === null ? null : Number(rawZoom);
const zoomUsable = requestedZoom !== null && Number.isFinite(requestedZoom)
&& requestedZoom >= 3 && requestedZoom <= 18;
if (rawZoom !== null && !zoomUsable) {
link.failures.push('deep link: unusable zoom "' + rawZoom + '"');
}
link.requested_zoom = zoomUsable ? requestedZoom : null;
/* 12 shows 3.6x more ground at 1400 px than at 393, so a shared
link opens wide on a desktop. Frame by viewport, not by number. */
const framed = () => Math.min(18, Math.max(3, requestedZoom
+ Math.log2(Math.max(innerWidth, 320) / 393)));
function honourRequestedZoom(map) {
if (!zoomUsable) return;
/* One shot, after the shell's own flyTo has settled. Racing it
would be a fight the shell wins, and re-applying on every idle
would take the map away from a user who has since zoomed. */
let done = false;
const apply = () => {
if (done) return;
done = true;
try {
map.off('idle', apply);
if (Math.abs(map.getZoom() - framed()) < 0.01) {
link.zoom_applied = 'already there';
return;
}
map.easeTo({ zoom: framed(), duration: 400 });
link.zoom_applied = framed();
} catch (error) {
noteFailure('deep link zoom: ' + String(error?.message || error));
}
};
try { map.once('idle', apply); } catch (_) { /* shimmed map in a proof */ }
// A map that never goes idle must not swallow the request.
setTimeout(apply, 2600);
}
const coordsUsable = () => Number.isFinite(lon) && Number.isFinite(lat)
&& Math.abs(lon) <= 180 && Math.abs(lat) <= 90
&& !(Math.abs(lon) < 1e-9 && Math.abs(lat) < 1e-9);
/* Vikram, phone acceptance 13:01: "arrive in full screen mode from
pipeline news with all the clutter minimised". On a touch screen
the normal page is a small map fighting a popup, chips, a HUD and
a panel below; fullscreen is the only honest arrival surface. The
shell's own control does it - CSS classes, and on an iPhone the
element fullscreen API simply does not exist, so nothing here is
gesture-gated - and the tray keeps the tool buttons collapsed. */
if ((q.get('repd_ref') !== null || coordsUsable()) && trayTarget()) {
try {
window.enterFullscreen?.();
link.arrival_fullscreen = true;
setTimeout(() => { try { map.resize(); } catch (_) { /* cosmetic */ } }, 120);
} catch (error) {
link.failures.push('arrival fullscreen: ' + String(error?.message || error));
}
}
/* A VALID LINK POINT ANSWERS FIRST; THE REGISTER VERIFIES IT.
---------------------------------------------------------
v9.91 put `await waitForResolvedIdentity()` before selectAt for every
repd_ref. Across Pipeline News that serialized a 35.7 MB query
engine ahead of 8,743 links that already carried a usable point;
2,430 then waited only to fall back to that same point. Coordinates
are enough for a geometric measurement. They are therefore used at
once, explicitly as link-supplied, while the one identity owner
verifies them concurrently. A different resolved point replaces the
selection and is measured again; FAILED/ABSENT never erases a valid
supplied point. A ref-only link still waits because it has no point
from which an honest measurement can be made. */
let identityVerification = null;
if (receiverPlan.route === 'MEASURE_LINK_FIRST' && repdRef) {
link.origin_source = 'link-supplied';
link.deep_link_identity = 'verifying-concurrently';
link.identity_verification = {
status: 'PENDING', repd_ref: repdRef, supplied_coordinates_used: true
};
identityVerification = waitForResolvedIdentity({ announce: false })
.then((owner) => ({
resolved: owner?.status === 'RESOLVED' ? owner : null,
terminal: owner?.status || 'UNKNOWN'
}))
.catch((error) => ({ resolved: null, terminal: 'FAILED', error }));
} else if (receiverPlan.route === 'WAIT_FOR_REGISTER') {
/* A ref-only link has no safe provisional geometry. This is the one
case that must await the identity owner before measuring. */
const owner = await waitForResolvedIdentity();
if (!arrivalGate.isCurrent(epoch) || owner?.status === 'CANCELLED') return;
if (owner?.status === 'RESOLVED') {
const resolved = owner;
const rLon = Number(resolved.longitude);
const rLat = Number(resolved.latitude);
if (Number.isFinite(rLon) && Number.isFinite(rLat)
&& Math.abs(rLon) <= 180 && Math.abs(rLat) <= 90
&& !(Math.abs(rLon) < 1e-9 && Math.abs(rLat) < 1e-9)) {
lon = rLon;
lat = rLat;
link.origin_source = 'register';
}
if (typeof resolved.technology === 'string' && resolved.technology) {
tech = resolved.technology;
}
if (resolved.name) name = String(resolved.name);
const cap = Number(resolved.capacity_mw);
if (Number.isFinite(cap) && cap > 0) stated = cap;
currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;
link.deep_link_identity = 'resolved-by-search-lane';
} else if (owner?.status === 'NOT_IN_ACTIVE_REGISTER') {
link.origin_source = 'not-in-active-register-no-supplied-point';
link.deep_link_identity = 'terminal-not-in-active-register';
link.identity_verification = {
status: 'NOT_IN_ACTIVE_REGISTER', repd_ref: repdRef,
supplied_coordinates_kept: false,
official_active_register_match: false
};
injectStatusStyle();
showStatus('REPD ' + repdRef + ' is not in the active-register '
+ 'snapshot, and this link supplies no coordinates from which '
+ 'to measure. No official status or location is inferred.',
'unavailable');
return;
} else {
injectStatusStyle();
const message = String(owner?.message || 'identity loader unavailable');
showStatus('The active-register identity check failed: ' + message
+ '. No location was supplied, so the grid measurement cannot '
+ 'start until the check succeeds.', 'failed');
retryArrival = retryIdentityOwnerThenArrival;
return;
}
} else {
link.origin_source = 'link-supplied';
}
if (!coordsUsable()) return;
/* Put the supplied point on screen with the supplied-point answer.
The old rule flew only links without repd_ref and therefore left a
valid coordinate link waiting for the register just to move the
camera. If verification later finds a different point, the identity
lane and the reconciliation below replace it together. */
try {
const arrivalZoom = zoomUsable ? requestedZoom : 12;
map.flyTo({ center: [lon, lat], zoom: arrivalZoom,
duration: 1200, essential: true });
link.camera_from_link = { longitude: lon, latitude: lat,
zoom: arrivalZoom, reason: identityVerification
? 'supplied coordinates while register verification runs'
: (repdRef ? 'resolved repd_ref coordinates'
: 'no repd_ref, so no other lane flies') };
} catch (error) {
noteFailure('deep link camera: ' + String(error?.message || error));
}
honourRequestedZoom(map);
/* An unrecognised technology used to abandon the whole arrival.
`return` cost the card, the ring, the nearest-substation
measurement, the declared connection and the substation layer -
all arithmetic over two coordinates and a register row. Only the
one technology layer needs the id, so that is all it costs now.
PROJECT_TECHS accepts 11,065 of the 11,069 ids the register
writes. What the guard really catches is a link that omits or
garbles the parameter, or carries an id from a newer register,
and for all three the answer is the map, not a blank. Recorded on
its own surface, not in `link.failures`, which since 202609011434
means the arrival lost something. This one did not. */
let technologyKnown = isProjectTech(tech);
link.technology_layer = {
requested: tech || null,
enabled: technologyKnown,
reason: technologyKnown ? null
: 'deep link: unknown technology "' + tech + '" - the arrival '
+ 'continues and this layer alone is not switched on'
};
// Turn the substations on. Arriving from the MAP button in Pipeline
// News, the whole point is to see the project against the network, and
// a user who has to find a checkbox first has been handed a puzzle
// rather than an answer. The engine owns the layer, so this ticks its
// own control rather than reaching past it into the map.
// The dashboard is built from the engine's own data and does not
// exist yet on a cold load -- measured at zero checkboxes twenty
// seconds in. Ticking a control that has not been rendered silently
// did nothing, and the layers the arrival depends on stayed off.
// Named, so Try again re-runs exactly the arrival rather than
// reloading and paying for the whole engine a second time.
let currentArrival = Object.freeze({ lon, lat, name, tech, stated, repdRef, suppliedStatus });
const enableBoth = () => {
if (!arrivalGate.isCurrent(epoch)) return false;
enableSubstationLayer();
if (technologyKnown) enableTechnologyLayer(currentArrival.tech);
return true;
};
const arrive = async () => {
clearStatus();
const ready = await waitForLayerControls(12000);
enableBoth();
// Late is not never. If the dashboard turns up after the budget, the
// layers still go on, without the user having to do anything.
if (!ready) watchForLayerControls(enableBoth);
return ready;
};
retryArrival = () => { runDeepLink(); };
/* Measure first. The distances are arithmetic over substation
coordinates and need no layer control, no dashboard and no
painted basemap; only the layers need the engine's controls.
Until v9.54 this awaited arrive() - up to twelve seconds - before
the measurement was even attempted, and Vikram's West Burton
journey on a phone showed exactly what that buys: a card, and
nothing beside it, for long enough to conclude the map is
broken. The layer switch-on runs alongside and finishes whenever
the engine is ready. */
const layersReady = arrive();
async function runArrivalSelection(arrival, waitForOwnerCard = false,
expectedArrivalEpoch = epoch) {
if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
/* A ref-only arrival already paid for canonical identity, so it can
briefly yield to that owner's richer card. A supplied coordinate
arrival must not wait for a card before it can measure: it creates
the explicit link-provenance card below on the same turn. */
if (waitForOwnerCard) {
for (let i = 0; i < 40; i += 1) {
if (document.querySelector('.maplibregl-popup-content')) break;
const idStatus = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status;
if (idStatus === 'FAILED' || idStatus === 'ABSENT') break;
await new Promise(resolve => setTimeout(resolve, 250));
if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
}
}
/* The card must exist BEFORE the lines. The popup watcher enforces
"the lines belong to the card" and clears any drawing standing
with no card on screen - watched live: a register-absent arrival
drew five links and the watcher wiped them in the same breath,
because the fallback card was opened after the measurement.
ensureArrivalCard is a no-op when a card is already up, so the
resolved-register path is unchanged. */
currentRepdRef = arrival.repdRef;
ensureArrivalCard(arrival.lon, arrival.lat, arrival.name,
arrival.tech, arrival.stated, arrival.repdRef, arrival.suppliedStatus);
/* Answer now, measure next. Everything in this block came from
the made Order and the link; nothing here waits on a network. */
currentDeclared = provisionalDeclaredConnection(currentRepdRef);
if (currentDeclared) injectDeclaredOnly();
try {
if (capturedMap) setPin(capturedMap,
[arrival.lon, arrival.lat], arrival.name, arrival.tech);
}
catch (_) { /* the measurement will draw it */ }
link.deep_linked = true;
const selected = await selectAt([arrival.lon, arrival.lat], arrival.name,
arrival.tech, false,
Number.isFinite(arrival.stated) && arrival.stated > 0
? arrival.stated : null, expectedArrivalEpoch);
return selected !== false && arrivalGate.isCurrent(expectedArrivalEpoch);
}
const firstStarted = performance.now();
const firstSelectionCurrent = await runArrivalSelection(currentArrival,
Boolean(repdRef && !identityVerification), epoch);
if (!firstSelectionCurrent) return;
link.first_coordinate_answer_ms = Math.round((performance.now() - firstStarted) * 10) / 10;
link.first_coordinate_origin = link.origin_source;
if (identityVerification) {
/* Attach reconciliation only after the supplied-point selection has
completed. A warm identity can resolve on the first microtask;
sequencing it here prevents two selections racing each other. */
continueVerifiedArrival(arrivalGate, epoch, identityVerification,
async ({ resolved, terminal, error }) => {
if (!resolved) {
const ownerState = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link || null;
const message = error ? String(error?.message || error)
: String(ownerState?.message || '');
link.origin_source = terminal === 'NOT_IN_ACTIVE_REGISTER'
? 'link-supplied-not-in-active-register'
: 'link-supplied-register-' + String(terminal).toLowerCase();
link.deep_link_identity = 'terminal-' + String(terminal).toLowerCase();
link.identity_verification = {
status: terminal, repd_ref: repdRef,
supplied_coordinates_kept: true,
arrival_fields: {
name: currentArrival.name,
technology: currentArrival.tech,
capacity_mw: Number.isFinite(currentArrival.stated)
? currentArrival.stated : null,