GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Unified Native Gazetteer

A JavaScript file in the atlas folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

621 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 594 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Unified Native Gazetteer geodesy · gridatlas / atlas/modules/unified-native-gazetteer.js lines 353–973

Unified Native Gazetteer

A JavaScript file in the atlas folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

Set aside from the main view: 91% of its lines are the same as atlas/cartridges/202611180026-place-global-search-v9-5.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Place Global Search V9 5; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9074 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-place-global-search-v9-5.js:1-931 c3ef9b6b82b3e983feb93015b168fed3d11322b9
  • sha256 d34e4ea12d80c28eb8adb0075154eac9581ae7b189f416997b3deab5d48377c8
  • target sha256 575721ea584187c2b9b857408a3e6136879d7f6876f1e6d7a0b925051124a49c
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/unified-native-gazetteer.js · lines 353–973 of 973 (continued from section 593) · Not reached from any entry point (candidate for review) · pattern loadDerivedCoordinates (shared by 4 files)

What it does
It maps REPD projects, offshore coordinates, postcodes and the REPD register. Defines 44 functions or classes, including invalidateSearch, invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, the REPD register.
Inputs & outputs
In: data source: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202611132345.parquet; JSON file repd_v9_manifest_202611132345.json; JSON file offshore-coordinates.json; DuckDB queries. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). V9.201 candidate derivative; original native gazetteer remains byte-identical. It responds to gridatlas, click and input events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
VEDIC
QUERY (GG2050-VEDIC-000046): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_predicate
VEDIC
SCORE (GG2050-VEDIC-000047): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_sort_expression
VEDIC
UK GEOCODE (GG2050-VEDIC-000048): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → uk_location_candidates
Uses
none found
Used by
none found
Produces
invalidateSearch, invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime
Defines here
derivedCoordinateFor, setDeepLink, selectResult, geocoderGet, joinParts, queryUkGazetteer, queryGlobalGazetteer, dedupeGlobalLocations, selectLocation, renderResults, current, appendTransfer, renderLocationLane, executeSearch, waitForCapturedMap, suppliedArrivalFields, numberOrNull, textOrNull, receiveExactRepdDeepLink, stillOwned, retryExactRepdDeepLink, bindSearch
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/modules/unified-native-gazetteer.js:353-973 · blob b6991e464f618824f20edd55ed8060d8abdc1bea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
        // derived point is available, which is the state this code replaces.
        xhr.onerror = () => resolve({});
        xhr.send();
      } catch (_) { resolve({}); }
    });
    return derivedIndex;
  }

  async function derivedCoordinateFor(repdRef) {
    const index = await loadDerivedCoordinates();
    const row = index[String(repdRef)];
    if (!row) return null;
    const candidate = { longitude: row.longitude, latitude: row.latitude };
    // The same safety test the register's own points must pass.
    if (!hasSafeMapPoint(candidate)) return null;
    return {
      longitude: row.longitude,
      latitude: row.latitude,
      source: row.method || 'DERIVED',
      lease: row.matched_lease || null,
      tenant: row.tenant || null,
    };
  }

  function setDeepLink(result) {
    const url = new URL(window.location.href);
    url.searchParams.set('repd_ref', result.repd_ref);
    history.replaceState(history.state, '', url);
  }

  function selectResult(result, options = {}) {
    const deepLinkEpoch = Number.isInteger(options.deepLinkEpoch)
      ? options.deepLinkEpoch : null;
    if (deepLinkEpoch === null) {
      invalidatePendingDeepLink('project-search-selection');
    } else if (!arrivalCoordinator()?.arrivalGate.isCurrent(deepLinkEpoch)) {
      return false;
    }
    setDeepLink(result);
    const map = window.__GRIDATLAS_V9_MAP__;
    const canMap = hasSafeMapPoint(result) && map && typeof map.flyTo === 'function';
    state.last_selection = {
      repd_ref: result.repd_ref,
      name: result.name,
      postcode: result.postcode,
      mapped: Boolean(canMap),
      longitude: result.longitude,
      latitude: result.latitude,
      // Published since 202609011141: the measurement cartridge consumes a
      // resolved identity rather than requiring the URL to restate what the
      // register already knows. This lane resolved them; it publishes them.
      technology: result.technology,
      capacity_mw: result.capacity_mw
    };
    if (!canMap) return true;
    map.flyTo({ center: [result.longitude, result.latitude], zoom: 12, duration: 1200, essential: true });
    const cap = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
    const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
    new window.maplibregl.Popup({ maxWidth: '340px' })
      .setLngLat([result.longitude, result.latitude])
      .setHTML(`<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHtml(result.name)}</b><br><span style="color:#888">${escapeHtml(result.technology)}</span>${cap ? `<br><span style="color:#ffae00">${escapeHtml(cap)}</span>` : ''}<br><span style="color:#aaa;font-size:10px">${escapeHtml(location)}</span><br><span style="color:#555;font-siz  … [line shortened here: 488 characters; full line on GitHub]
      .addTo(map);
    return true;
  }

  // ---- 202608301136 UK gazetteer lane (LOCATION_ONLY, never claims REPD identity) ----
  const FULL_POSTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?[0-9][A-Z]{2}$/;
  const OUTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?$/;
  let locationPopup = null;

  async function geocoderGet(path, query) {
    state.geocoder_requests += 1;
    try {
      const response = await fetch(`${GEOCODER_BASE}${path}`, { cache: 'default' });
      if (response.status === 404) return null;
      if (!response.ok) throw new Error(`postcodes.io ${response.status} for ${path}`);
      const body = await response.json();
      return body?.result ?? null;
    } catch (error) {
      state.geocoder_failures.push({
        query: String(query ?? ''),
        path,
        message: String(error?.message || error)
      });
      throw error;
    }
  }

  function joinParts(...parts) {
    return parts.filter(Boolean).join(' · ');
  }

  async function queryUkGazetteer(query) {
    const raw = String(query ?? '').trim();
    if (raw.length < 2) return [];
    const compact = normaliseCompact(raw);
    const out = [];
    try {
      if (FULL_POSTCODE.test(compact)) {
        const result = await geocoderGet(`/postcodes/${encodeURIComponent(compact)}`, raw);
        if (result && Number.isFinite(result.longitude) && Number.isFinite(result.latitude)) {
          out.push({
            kind: 'postcode',
            provider: 'postcodes.io',
            label: result.postcode,
            sublabel: joinParts(result.admin_district, result.admin_county, result.region),
            longitude: result.longitude,
            latitude: result.latitude
          });
          return out;
        }
      } else if (OUTCODE.test(compact)) {
        const result = await geocoderGet(`/outcodes/${encodeURIComponent(compact)}`, raw);
        if (result && Number.isFinite(result.longitude) && Number.isFinite(result.latitude)) {
          out.push({
            kind: 'postcode_district',
            provider: 'postcodes.io',
            label: result.outcode,
            sublabel: joinParts(
              Array.isArray(result.admin_district) ? result.admin_district.join(', ') : result.admin_district,
              Array.isArray(result.region) ? result.region.join(', ') : result.region
            ),
            longitude: result.longitude,
            latitude: result.latitude
          });
          return out;
        }
      }

      const places = await geocoderGet(`/places?q=${encodeURIComponent(raw)}&limit=8`, raw);
      for (const place of Array.isArray(places) ? places : []) {
        if (!Number.isFinite(place.longitude) || !Number.isFinite(place.latitude)) continue;
        out.push({
          kind: 'place',
          provider: 'postcodes.io',
          label: place.name_1,
          sublabel: joinParts(place.local_type, place.county_unitary, place.region),
          longitude: place.longitude,
          latitude: place.latitude
        });
      }
    } catch (error) {
      console.warn('[V9 UK GAZETTEER]', error);
    }
    return out;
  }

  async function queryGlobalGazetteer(query) {
    const raw = String(query ?? '').trim();
    if (raw.length < 2) return [];
    const compact = normaliseCompact(raw);
    if (FULL_POSTCODE.test(compact) || OUTCODE.test(compact)) return [];
    state.global_geocoder_requests += 1;
    try {
      const url = new URL(GLOBAL_GEOCODER_URL);
      url.searchParams.set('format', 'jsonv2');
      url.searchParams.set('limit', '8');
      url.searchParams.set('addressdetails', '1');
      url.searchParams.set('accept-language', 'en');
      url.searchParams.set('q', raw);
      const response = await fetch(url, {
        cache: 'default',
        headers: { Accept: 'application/json' }
      });
      if (!response.ok) throw new Error(`Nominatim ${response.status}`);
      const body = await response.json();
      const out = [];
      for (const row of Array.isArray(body) ? body : []) {
        const longitude = Number(row.lon);
        const latitude = Number(row.lat);
        if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) continue;
        const display = String(row.display_name || '').trim();
        const label = String(row.name || row.address?.city || row.address?.town || row.address?.village || display.split(',')[0] || raw).trim();
        out.push({
          kind: 'global_place',
          provider: 'Nominatim / OpenStreetMap',
          label,
          sublabel: display || raw,
          longitude,
          latitude
        });
      }
      return out;
    } catch (error) {
      state.geocoder_failures.push({
        query: raw,
        path: GLOBAL_GEOCODER_URL,
        provider: 'Nominatim / OpenStreetMap',
        message: String(error?.message || error)
      });
      console.warn('[V9.5 GLOBAL GAZETTEER]', error);
      return [];
    }
  }

  function dedupeGlobalLocations(ukResults, globalResults) {
    return globalResults.filter(globalResult => !ukResults.some(ukResult => {
      const sameLabel = String(globalResult.label).trim().toLowerCase() === String(ukResult.label).trim().toLowerCase();
      const close = Math.abs(globalResult.longitude - ukResult.longitude) < 0.03 && Math.abs(globalResult.latitude - ukResult.latitude) < 0.03;
      return sameLabel && close;
    }));
  }

  function selectLocation(result) {
    invalidatePendingDeepLink('location-search-selection');
    const url = new URL(window.location.href);
    url.searchParams.delete('repd_ref');
    history.replaceState(history.state, '', url);
    const map = window.__GRIDATLAS_V9_MAP__;
    const canMap = hasSafeMapPoint(result) && map && typeof map.flyTo === 'function';
    state.last_location_selection = { ...result, mapped: Boolean(canMap) };
    if (!canMap) return;
    const zoom = result.kind === 'postcode' ? 13 : result.kind === 'postcode_district' ? 11 : result.kind === 'global_place' ? 12 : 12;
    const provider = result.provider || 'postcodes.io';
    map.flyTo({ center: [result.longitude, result.latitude], zoom, duration: 1200, essential: true });
    if (locationPopup) locationPopup.remove();
    locationPopup = new window.maplibregl.Popup({ maxWidth: '300px' })
      .setLngLat([result.longitude, result.latitude])
      .setHTML(`<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHtml(result.label)}</b><br><span style="color:#aaa;font-size:10px">${escapeHtml(result.sublabel)}</span><br><span style="color:#555;font-size:9px">Location only · ${escapeHtml(provider)} · no project identity claimed</span></div>`)
      .addTo(map);
  }

  function renderResults(repdResults, resultsEl, ukResults = [], globalResults = [], ticket = null) {
    const renderSerial = activeQuerySerial;
    const current = () => renderSerial === activeQuerySerial;
    resultsEl.innerHTML = '';
    if (!repdResults.length && !ukResults.length && !globalResults.length) {
      const empty = document.createElement('div');
      empty.className = 'search-no-results';
      empty.textContent = 'No REPD project, postcode, address or place match';
      resultsEl.appendChild(empty);
      resultsEl.style.display = 'block';
      return;
    }

    const candidates = [...repdResults,...ukResults,...globalResults].filter(hasSafeMapPoint);
    const handles = ticket && destinationGate ? destinationGate.publish(ticket,candidates.map((r,i)=>({id:'search:'+i,at:[r.longitude,r.latitude],label:r.name||r.label,provider:r.provider||'REPD',precision:r.kind||'project'}))) : null;
    const byResult = new Map(candidates.map((r,i)=>[r,handles?.[i]]));
    function appendTransfer(result) {
      const handle = byResult.get(result); if (!handle) return;
      const button = document.createElement('button'); button.type='button';
      button.textContent='Use as SatNav destination';
      if (result.kind === 'postcode' || result.kind === 'postcode_district') {
        const precision=document.createElement('small'); precision.textContent='Approximate postcode location; check the actual entrance.'; resultsEl.append(precision);
      }
      button.style.cssText='min-height:44px;width:100%;background:#10252a;color:#aef8ff;border:1px solid #467781;cursor:pointer';
      const status = document.createElement('div'); status.setAttribute('role','status');
      button.addEventListener('click',event=>{
        event.preventDefault();event.stopPropagation();
        if (!current()) return;
        const survey=document.getElementById('satnav-compact')?.satnavSurvey;
        const outcome=destinationGate.transfer(handle,h=>survey?.transferSearchDestination(h)||{ok:false,reason:'SatNav not ready'});
        if (!outcome.ok) {status.textContent=outcome.reason;return;}
        invalidateSearch();resultsEl.style.display='none';
      });
      resultsEl.append(button,status);
    }
    for (const result of repdResults) {
      const item = document.createElement('div');
      item.className = 'search-result-item';
      item.dataset.repdRef = result.repd_ref;
      const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
      const capacity = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
      item.innerHTML = `<b>${escapeHtml(result.name)}</b><br><span>${escapeHtml(location)}</span>${capacity ? `<br><span style="color:#ffae00">${escapeHtml(capacity)}</span>` : ''}<span style="color:#555"> · REPD ${escapeHtml(result.repd_ref)}</span>`;
      item.addEventListener('click', event => {
        event.preventDefault();
        event.stopPropagation();
        if (!current()) return;
        invalidateSearch();
        resultsEl.style.display = 'none';
        selectResult(result);
      });
      resultsEl.appendChild(item);
      appendTransfer(result);
    }

    function renderLocationLane(title, locations) {
      if (!locations.length) return;
      const divider = document.createElement('div');
      divider.className = 'search-no-results';
      divider.textContent = title;
      resultsEl.appendChild(divider);
      for (const result of locations) {
        const item = document.createElement('div');
        item.className = 'search-result-item';
        item.dataset.locationKind = result.kind;
        item.dataset.locationProvider = result.provider || '';
        item.innerHTML = `<b>${escapeHtml(result.label)}</b><br><span>${escapeHtml(result.sublabel)}</span><span style="color:#555"> · fly to only, not a REPD project</span>`;
        item.addEventListener('click', event => {
          event.preventDefault();
          event.stopPropagation();
          if (!current()) return;
          invalidateSearch();
          resultsEl.style.display = 'none';
          selectLocation(result);
        });
        resultsEl.appendChild(item);
        appendTransfer(result);
      }
    }

    renderLocationLane('UK location', ukResults);
    renderLocationLane('Global location', globalResults);
    resultsEl.style.display = 'block';
  }

  async function executeSearch(input, resultsEl, includeGlobal = false) {
    debounceTimer=null;
    const serial = ++activeQuerySerial;
    const query = input.value.trim();
    const ticket = destinationGate?.beginRequest(destinationGate.onInput(query));
    if (query.length < 2) {
      resultsEl.innerHTML = '';
      resultsEl.style.display = 'none';
      return;
    }
    resultsEl.style.display = 'block';
    resultsEl.innerHTML = '<div class="search-no-results">Searching REPD projects, postcodes, addresses and places…</div>';
    try {
      const lanes = await Promise.allSettled([
        queryOfficialRepd(query, serial),
        queryUkGazetteer(query),
        includeGlobal ? queryGlobalGazetteer(query) : Promise.resolve([])
      ]);
      if (serial !== activeQuerySerial) return;
      const names = ['REPD project','UK location','Global location'];
      const failed = lanes.flatMap((lane,i) => lane.status==='rejected' ? [names[i]] : []);
      lanes.forEach((lane,i)=>{if(lane.status==='rejected')state.failures.push({query,lane:names[i],message:String(lane.reason?.message||lane.reason)});});
      const [results,ukLocations,rawGlobalLocations]=lanes.map(lane=>lane.status==='fulfilled'?lane.value:[]);
      const globalLocations = dedupeGlobalLocations(ukLocations, rawGlobalLocations);
      renderResults(results, resultsEl, ukLocations, globalLocations,ticket);
      if (failed.length) {
        const warning=document.createElement('div'); warning.className='search-no-results'; warning.setAttribute('role','status');
        warning.textContent=failed.join(', ')+' search unavailable; results from available sources only.';
        if(!results.length&&!ukLocations.length&&!globalLocations.length) resultsEl.replaceChildren(warning);
        else resultsEl.append(warning);
      }
      if (!ticket && (results.length||ukLocations.length||globalLocations.length)) {
        const warning=document.createElement('div');warning.className='search-no-results';warning.textContent='SatNav transfer not ready; retry search to transfer a destination.';resultsEl.append(warning);
      }
    } catch (error) {
      if (serial !== activeQuerySerial) return;
      state.failures.push({ query, message: String(error?.message || error) });
      resultsEl.innerHTML = '<div class="search-no-results">Search unavailable — V8 map remains usable</div>';
      resultsEl.style.display = 'block';
      console.error('[V9.5 PLACE SEARCH]', error);
    }
  }

  async function waitForCapturedMap(timeoutMs = 60000) {
    const started = performance.now();
    while (performance.now() - started < timeoutMs) {
      const map = window.__GRIDATLAS_V9_MAP__;
      if (map && typeof map.flyTo === 'function') return map;
      await new Promise(resolve => setTimeout(resolve, 50));
    }
    throw new Error('GridAtlas map was not captured for exact REPD deep link');
  }

  function suppliedArrivalFields(params, repdRef) {
    const numberOrNull = (name) => {
      const raw = params.get(name);
      if (raw === null || String(raw).trim() === '') return null;
      const value = Number(raw);
      return Number.isFinite(value) ? value : null;
    };
    const textOrNull = (name) => {
      const value = String(params.get(name) || '').trim();
      return value || null;
    };
    return Object.freeze({
      repd_ref: repdRef,
      name: textOrNull('project'),
      technology: textOrNull('technology'),
      capacity_mw: numberOrNull('capacity_mw'),
      longitude: numberOrNull('longitude'),
      latitude: numberOrNull('latitude'),
      // Pipeline News 0144 does not send status. Retain it only when another
      // authorised producer explicitly supplies it; never present it as an
      // official active-register value.
      supplied_status: textOrNull('status')
    });
  }

  async function receiveExactRepdDeepLink(input, resultsEl,
    expectedOwnerEpoch = null) {
    const params = new URLSearchParams(window.location.search);
    const repdRef = String(params.get('repd_ref') || '').trim();
    if (!repdRef) {
      state.deep_link = { status: 'ABSENT', repd_ref: null, resolved: false, mapped: false };
      return;
    }

    const arrival = suppliedArrivalFields(params, repdRef);
    let coordinator = null;
    let ownerEpoch = null;
    try {
      invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
      coordinator = arrivalCoordinator();
      invariant(coordinator, 'shared arrival coordinator unavailable');
      if (Number.isInteger(expectedOwnerEpoch)) {
        if (!coordinator.arrivalGate.isCurrent(expectedOwnerEpoch)) return;
        ownerEpoch = expectedOwnerEpoch;
      } else {
        ownerEpoch = coordinator.claimPendingArrival(window.location.search);
      }
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'RECEIVING',
        resolved: false, mapped: false,
        identity_source: 'ACTIVE_REGISTER_PENDING'
      };
      const stillOwned = () => coordinator.arrivalGate.isCurrent(ownerEpoch);
      const querySerial = ++activeQuerySerial;
      input.value = repdRef;
      const results = await queryOfficialRepd(repdRef, querySerial, stillOwned);
      if (!stillOwned() || querySerial !== activeQuerySerial) return;
      const exact = results.find(result => String(result.repd_ref) === repdRef);
      if (!exact) {
        // A successful query with no exact row is evidence about this active
        // snapshot, not a network failure and not evidence that the supplied
        // project never existed. Keep the link's point and identity separate.
        renderResults(results, resultsEl);
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'not-in-active-register';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          status: 'NOT_IN_ACTIVE_REGISTER',
          resolved: false,
          mapped: false,
          supplied_point_usable: hasSafeMapPoint(arrival),
          identity_source: 'ARRIVAL_LINK',
          official_active_register_match: false,
          statement: 'No exact identity in the active-register snapshot; supplied arrival fields retained.'
        };
        return;
      }
      renderResults(results, resultsEl);
      await waitForCapturedMap();
      if (!stillOwned()) return;

      /* A ref the register does not locate used to be treated worse than a ref
         the register does not contain. The not-in-register branch above keeps
         the supplied arrival point and degrades gracefully; this branch found
         its row, could not map it, and threw - so a project present in the
         register but without a coordinate showed the user a failure card.
         Measured on the live page: between 3 and 8 of 20 MAP links carry no
         coordinate at all, so there was nothing to fall back to either.

         Offshore is where this bites. 8 of 101 offshore rows carry no easting
         or northing, and the Crown Estate leases the seabed under them, so a
         derived point exists for 6 of the 8 in atlas/data/offshore-coordinates.json.
         Using it is honest as long as the card says the coordinate is derived
         and the identity is not: the register named the project, the lease
         located it. */
      const derived = !hasSafeMapPoint(exact) ? await derivedCoordinateFor(repdRef) : null;
      if (derived) {
        exact.longitude = derived.longitude;
        exact.latitude = derived.latitude;
      }
      /* No register point and no lease point. Measured offline on v9.144:
         13432 is in the register, has no coordinate, is in no lease, and
         still reached the invariant below and showed a failure card. A name
         the register confirmed is worth more than a card that says try again,
         so the identity stands and the map does not move. If the link itself
         carried a usable point it is used and labelled as the link's, never
         as the register's. */
      const linkPoint = !hasSafeMapPoint(exact) && hasSafeMapPoint(arrival)
        ? { longitude: arrival.longitude, latitude: arrival.latitude } : null;
      if (linkPoint) {
        exact.longitude = linkPoint.longitude;
        exact.latitude = linkPoint.latitude;
      }
      if (!hasSafeMapPoint(exact)) {
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'resolved-unmapped';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          repd_ref: repdRef,
          status: 'RESOLVED_UNMAPPED',
          resolved: true,
          mapped: false,
          name: exact.name,
          technology: exact.technology,
          capacity_mw: exact.capacity_mw,
          status_value: exact.status,
          identity_source: 'OFFICIAL_ACTIVE_REGISTER',
          official_active_register_match: true,
          coordinate_source: 'NONE',
          coordinate_derived: false,
          coordinate_lease: null,
          coordinate_tenant: null,
          coordinate_statement: 'The register names this project but holds no coordinate for it, and no Crown Estate lease covers it. Identity confirmed; position unknown; the map was not moved.',
          statement: 'Exact identity in the active-register snapshot; no coordinate from any source held.'
        };
        return;
      }
      if (!selectResult(exact, { deepLinkEpoch: ownerEpoch })) return;
      if (!stillOwned()) return;
      invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
      invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
      document.body.dataset.gridatlasRepdRef = repdRef;
      document.body.dataset.gridatlasRepdDeepLink = 'resolved';
      state.deep_link = {
        status: 'RESOLVED',
        owner_epoch: ownerEpoch,
        repd_ref: repdRef,
        resolved: true,
        mapped: true,
        /* Identity and coordinate have different provenance and are reported
           separately. The register named this project; where it did not locate
           it, a Crown Estate lease did, and the card must not present the two
           as one fact. */
        coordinate_source: derived ? derived.source : linkPoint ? 'ARRIVAL_LINK' : 'OFFICIAL_ACTIVE_REGISTER',
        coordinate_derived: Boolean(derived),
        coordinate_lease: derived ? derived.lease : null,
        coordinate_tenant: derived ? derived.tenant : null,
        coordinate_statement: derived
          ? 'Position derived from Crown Estate lease geometry because the register carries no coordinate for this project. The identity is the register’s; the position is not.'
          : linkPoint
            ? 'Position taken from the arrival link because the register carries no coordinate for this project and no lease covers it. The identity is the register’s; the position is the link’s.'
            : 'Position as published in the active register.',
        name: exact.name,
        postcode: exact.postcode,
        longitude: exact.longitude,
        latitude: exact.latitude,
        technology: exact.technology,
        capacity_mw: exact.capacity_mw,
        status_value: exact.status,
        identity_source: 'OFFICIAL_ACTIVE_REGISTER',
        official_active_register_match: true
      };
    } catch (error) {
      if (coordinator && Number.isInteger(ownerEpoch)
          && !coordinator.arrivalGate.isCurrent(ownerEpoch)) return;
      const message = String(error?.message || error);
      state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'FAILED',
        resolved: false, mapped: false, message,
        identity_source: 'ACTIVE_REGISTER_CHECK_FAILED'
      };
      document.body.dataset.gridatlasRepdDeepLink = 'failed';
      console.error('[V9 EXACT REPD DEEP LINK]', error);
    }
  }

  async function retryExactRepdDeepLink(input, resultsEl, ownerEpoch) {
    const coordinator = arrivalCoordinator();
    invariant(coordinator, 'shared arrival coordinator unavailable for retry');
    invariant(Number.isInteger(ownerEpoch), 'identity retry requires one shared owner epoch');
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    state.identity_retry_count += 1;
    await resetOfficialRuntime();
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    return receiveExactRepdDeepLink(input, resultsEl, ownerEpoch);
  }

  function bindSearch() {
    const input = document.getElementById('search-input');
    const button = document.getElementById('search-btn');
    const resultsEl = document.getElementById('search-results');
    invariant(input && button && resultsEl, 'V8 search controls missing');
    input.setAttribute('placeholder', 'Search project, address, postcode or place...');
    input.setAttribute('aria-label', 'Search project, address, postcode or place');

    input.addEventListener('input', event => {
      event.stopImmediatePropagation();
      invalidateSearch();
      resultsEl.style.display='none';
      invalidatePendingDeepLink('user-search-input');
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => executeSearch(input, resultsEl, false), 180);
    }, true);

    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopImmediatePropagation();
        invalidatePendingDeepLink('user-search-submit');
        clearTimeout(debounceTimer);
        executeSearch(input, resultsEl, true);
      } else if (event.key === 'Escape') {
        event.stopImmediatePropagation();
        invalidateSearch();
        invalidatePendingDeepLink('user-search-dismiss');
        resultsEl.style.display = 'none';
      }
    }, true);

    button.addEventListener('click', event => {
      event.preventDefault();
      event.stopImmediatePropagation();
      invalidatePendingDeepLink('user-search-submit');
      clearTimeout(debounceTimer);
      executeSearch(input, resultsEl, true);
    }, true);

    document.addEventListener('pointerdown',event=>{
      if (!resultsEl.contains(event.target) && event.target!==input && event.target!==button && !button.contains(event.target)) {
        if (debounceTimer!==null || resultsEl.style.display!=='none') {invalidateSearch();resultsEl.style.display='none';}
      }
    },true);
    state.retry_exact_deep_link = (ownerEpoch) =>
      retryExactRepdDeepLink(input, resultsEl, ownerEpoch);
    state.ready = true;
  }

  window.addEventListener('DOMContentLoaded', async () => {
    try {
      bindSearch();
      const input = document.getElementById('search-input');
      const resultsEl = document.getElementById('search-results');
      void receiveExactRepdDeepLink(input, resultsEl);
    } catch (error) {
      state.failures.push({ phase: 'bind', message: String(error?.message || error) });
      console.error('[V9 PLACE SEARCH INIT]', error);
    }
  }, { once: true });
})();