Compare commits

..
Author SHA1 Message Date
Claude 56586a234b feat(vcam): use a phone on the network as a virtual camera
SCENES > VCAM pairs a phone through a QR code and turns it into a
handheld camera, after Unreal's Live Link VCAM and Blender's VirtuCamera:

- Android Chrome tracks 6DoF through WebXR immersive-ar; iPhone Safari,
  which has no WebXR AR, tracks rotation through DeviceOrientation, and
  thumb sticks dolly, truck, crane and pan.
- A motion scale (1:1 walk to 1:10000 orbit), smoothing, height and
  horizon locks, hold/clutch and recenter, none of which make the camera
  jump. Focal length and scale-aware depth of field with tap-to-focus.
- The phone shows the app's render as a monitor (newest-frame JPEG pull).
- REC records a take as a version-7 track shot in the selected scene.
- The rig claims the camera through the navigation seam (Cockpit refuses
  it) and holds on any other navigation, scene run or globe input.

Pairing never exposes the app: a loopback-only session request starts a
separate HTTPS listener (VCAM_PORT, default 4174) that serves only the
static phone page and a token-paired relay, and stops after the last
session. Its certificate comes from a local CA built with node:crypto, which
an iPhone can trust once; without it the phone falls back from WebSocket to
HTTPS requests, which iOS allows past a certificate warning.

scripts/qa-vcam.mjs drives it end to end: the real phone page over the
HTTPS fallback, a scripted 6DoF phone, a recorded and replayed take, depth
of field and camera handoff.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015H1iLusTzWpVKitGic2AW8
2026-10-19 04:03:02 +00:00
Claude c330eb801a feat(director): recorded camera tracks and shot lens (scene document v7)
Scene documents gain a second kind of explicit move: `move.track`, timed
samples of position, orientation and an optional 35 mm-equivalent focal
length. Playback, Load, Replay and seek share one sampler, which stretches
the recording to the shot's duration (so editing durationSec retimes a
take), takes the short arc for longitude/heading/roll and returns recorded
samples exactly. Tracks require the ellipsoid altitude reference and are
bounded to 10,000 samples.

Shots may also carry a `lens`: focal length and a thin-lens depth of field
whose distances are divided by a miniature scale, so a 1:1000 rig renders
the city like a tabletop model. A new camera-lens owner applies it to the
frustum and a depth-of-field post-process stage; shots without a lens
restore the default view. SceneDirector accepts the lens as an injected
dependency, captures a changed lens with a shot and gains addRecordedShot()
for takes. Versions 1-6 import unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015H1iLusTzWpVKitGic2AW8
2026-10-19 04:03:02 +00:00
339 changed files with 24288 additions and 31418 deletions

No files matched your search

+8 -18
View File
@@ -83,12 +83,6 @@ OPENAI_REALTIME_TRANSCRIBE_MODEL=gpt-4o-mini-transcribe
# keep them while debugging; delete the log when you are done. # keep them while debugging; delete the log when you are done.
GEV_VOICE_LOG_CONTENT= GEV_VOICE_LOG_CONTENT=
OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano
# Optional: Gemini Live voice, selected in the GEV MIC provider chooser.
# Server-only key. Do not prefix with VITE_. Provider Settings can save it.
GEMINI_API_KEY=
GEMINI_LIVE_MODEL=gemini-3.8-live
# Token starts per IP per minute; 0 disables the throttle, not provider quotas.
# GEV_RATELIMIT_GEMINI_PER_MIN=30
# Per-IP rate limit for the OpenAI cost endpoints # Per-IP rate limit for the OpenAI cost endpoints
# (/api/realtime/token + /api/openai/hud-summary), in requests per minute. # (/api/realtime/token + /api/openai/hud-summary), in requests per minute.
# DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary # DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary
@@ -124,8 +118,8 @@ OPENSKY_AUTH_MODE=oauth
OPENSKY_CLIENT_ID= OPENSKY_CLIENT_ID=
OPENSKY_CLIENT_SECRET= OPENSKY_CLIENT_SECRET=
# Launch Library 2: leave blank for standard public access (no key needed). # Optional: higher Launch Library 2 request allowance. Public access works
# Optional paid Patreon tokens raise request limits; there is no free API key. # without a token.
LL2_API_TOKEN= LL2_API_TOKEN=
# Optional: OpenSky credentials JSON file path (alternative to above) # Optional: OpenSky credentials JSON file path (alternative to above)
@@ -147,6 +141,12 @@ PORT=4173
# wildcard entries are ignored. # wildcard entries are ignored.
# GEV_ALLOWED_HOSTS= # GEV_ALLOWED_HOSTS=
# SCENES › VCAM (phone virtual camera, docs/VCAM.md): the HTTPS listener a
# paired phone connects to. It starts only when you open a pairing session and
# serves only the phone page and relay, not the app or its keys.
# VCAM_PORT=4174
# VCAM_HOST=0.0.0.0
# Optional: NASA FIRMS live active fires. SERVER-SIDE ONLY (never reaches the # Optional: NASA FIRMS live active fires. SERVER-SIDE ONLY (never reaches the
# browser — the client polls the /api/firms proxy). Free key: # browser — the client polls the /api/firms proxy). Free key:
# https://firms.modaps.eosdis.nasa.gov/api/map_key/ # https://firms.modaps.eosdis.nasa.gov/api/map_key/
@@ -207,7 +207,6 @@ AISSTREAM_API_KEY=
# CCTV_TFL_ENABLED=1 # set 0 to disable Transport for London JamCams # CCTV_TFL_ENABLED=1 # set 0 to disable Transport for London JamCams
# CCTV_TFL_MAX_SOURCES=250 # cap cameras loaded from TfL # CCTV_TFL_MAX_SOURCES=250 # cap cameras loaded from TfL
# CCTV_ONTARIO_ENABLED=1 # set 0 to disable Ontario 511 cameras # CCTV_ONTARIO_ENABLED=1 # set 0 to disable Ontario 511 cameras
# ONTARIO_511_API_KEY= # free developer key: sign up at 511on.ca/my511/register, then request it at 511on.ca/developers/doc
# CCTV_ONTARIO_MAX_SOURCES=1000 # cap cameras loaded from Ontario 511 # CCTV_ONTARIO_MAX_SOURCES=1000 # cap cameras loaded from Ontario 511
# CCTV_FINTRAFFIC_ENABLED=1 # set 0 to drop the Fintraffic (Finland) pack # CCTV_FINTRAFFIC_ENABLED=1 # set 0 to drop the Fintraffic (Finland) pack
# CCTV_FINTRAFFIC_MAX_SOURCES=300 # cap cameras loaded from the Fintraffic catalog # CCTV_FINTRAFFIC_MAX_SOURCES=300 # cap cameras loaded from the Fintraffic catalog
@@ -228,9 +227,6 @@ AISSTREAM_API_KEY=
# CCTV_CALGARY_ROWS_URL= # override the Open Calgary catalog URL # CCTV_CALGARY_ROWS_URL= # override the Open Calgary catalog URL
# CCTV_CATALONIA_ENABLED=1 # set 0 to disable the Servei Català de Trànsit cameras # CCTV_CATALONIA_ENABLED=1 # set 0 to disable the Servei Català de Trànsit cameras
# CCTV_CATALONIA_MAX_SOURCES=150 # cap cameras loaded from Catalonia (~130 exist today) # CCTV_CATALONIA_MAX_SOURCES=150 # cap cameras loaded from Catalonia (~130 exist today)
# CCTV_HK_ENABLED=1 # set 0 to disable the Hong Kong Transport Department cameras
# CCTV_HK_MAX_SOURCES=1100 # cap cameras loaded from Hong Kong (~1,013 exist today); min 8, max 1200
# CCTV_HK_CAMERAS_URL= # override the DATA.GOV.HK camera locations XML URL
# CCTV_KINGCOUNTY_ENABLED=1 # set 0 to disable the King County (Washington) road cameras # CCTV_KINGCOUNTY_ENABLED=1 # set 0 to disable the King County (Washington) road cameras
# CCTV_KINGCOUNTY_MAX_SOURCES=125 # cap cameras loaded from the King County catalog # CCTV_KINGCOUNTY_MAX_SOURCES=125 # cap cameras loaded from the King County catalog
# CCTV_WSDOT_ENABLED=1 # set 0 to disable the WSDOT (Washington State) highway cameras # CCTV_WSDOT_ENABLED=1 # set 0 to disable the WSDOT (Washington State) highway cameras
@@ -238,7 +234,6 @@ AISSTREAM_API_KEY=
# CCTV_VEGVESEN_ENABLED=1 # set 0 to disable the Statens vegvesen (Norway) road cameras # CCTV_VEGVESEN_ENABLED=1 # set 0 to disable the Statens vegvesen (Norway) road cameras
# CCTV_VEGVESEN_MAX_SOURCES=900 # cap cameras loaded from Statens vegvesen (default loads all ~850 live; max 1000) # CCTV_VEGVESEN_MAX_SOURCES=900 # cap cameras loaded from Statens vegvesen (default loads all ~850 live; max 1000)
# CCTV_VEGVESEN_VIDEO=1 # set 0 to show stills instead of live HLS for Statens vegvesen video cameras # CCTV_VEGVESEN_VIDEO=1 # set 0 to show stills instead of live HLS for Statens vegvesen video cameras
# CCTV_VEGVESEN_HEIGHTS=1 # set 0 to skip Kartverket ground heights for Statens vegvesen cameras (flat prior instead)
# CCTV_VEGVESEN_URL= # override the Statens vegvesen catalog URL # CCTV_VEGVESEN_URL= # override the Statens vegvesen catalog URL
# CCTV_NYC_ENABLED= # off by default; set 1 only if you hold a NYC DOT data-sharing agreement ([email protected]) for the camera feed # CCTV_NYC_ENABLED= # off by default; set 1 only if you hold a NYC DOT data-sharing agreement ([email protected]) for the camera feed
# CCTV_NYC_MAX_SOURCES=250 # cap cameras loaded from the NYC TMC catalog (nearest borough cores first) # CCTV_NYC_MAX_SOURCES=250 # cap cameras loaded from the NYC TMC catalog (nearest borough cores first)
@@ -248,11 +243,6 @@ AISSTREAM_API_KEY=
# CCTV_TORONTO_LIST_URL= # override the Toronto RESCU camera list URL # CCTV_TORONTO_LIST_URL= # override the Toronto RESCU camera list URL
# CCTV_LITHUANIA_ENABLED= # off by default; set 1 to load Via Lietuva / Eismoinfo road cameras (photo licence unconfirmed; see DATA_SOURCES.md) # CCTV_LITHUANIA_ENABLED= # off by default; set 1 to load Via Lietuva / Eismoinfo road cameras (photo licence unconfirmed; see DATA_SOURCES.md)
# CCTV_LITHUANIA_MAX_SOURCES=400 # cap Lithuanian cameras; no API key required # CCTV_LITHUANIA_MAX_SOURCES=400 # cap Lithuanian cameras; no API key required
# CCTV_FLORIDA_ENABLED= # off by default; set 1 to load FL511 (Florida) cameras (individual, personal use only; any other use, including a public deployment, needs FDOT's express written consent; see DATA_SOURCES.md)
# CCTV_FLORIDA_MAX_SOURCES=500 # cap cameras loaded from the FL511 catalog (nearest regional anchors first)
# CCTV_TAIWAN_ENABLED=1 # set 0 to skip Taiwan Freeway Bureau (MOTC) road cameras
# CCTV_TAIWAN_MAX_SOURCES=600 # cap Taiwan freeway cameras (1-2000); no API key required
# CCTV_TAIWAN_URL= # override the Freeway Bureau MOTC 2.0 CCTV.xml URL
# CCTV_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs # CCTV_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs
# CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry # CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry
# CCTV_FORCE_AUSTIN= # force live default sources when a source-pack JSON is configured # CCTV_FORCE_AUSTIN= # force live default sources when a source-pack JSON is configured
+6
View File
@@ -67,6 +67,8 @@ jobs:
timeout-minutes: 30 timeout-minutes: 30
env: env:
GEV_REQUIRE_ALLOCATION_GATE: '0' GEV_REQUIRE_ALLOCATION_GATE: '0'
# Fail on a missed header press unless the panel itself moved.
QA_FAIL_ON_RETRY: '1'
steps: steps:
- name: Check out source - name: Check out source
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
@@ -102,6 +104,10 @@ jobs:
- name: Street Level gate with Mapillary fixtures - name: Street Level gate with Mapillary fixtures
run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173 run: npm run qa:street-level:fixtures -- --strict --url http://localhost:4173
- name: Portable panel gate
if: success() || failure()
run: npm run qa:panel-resize -- --url http://localhost:4173
- name: Preview server log - name: Preview server log
if: failure() if: failure()
run: cat preview.log run: cat preview.log
-4
View File
@@ -16,10 +16,6 @@ output/
.gev-cache/ .gev-cache/
# Browser QA gate evidence (screenshots, console and network dumps). # Browser QA gate evidence (screenshots, console and network dumps).
qa-artifacts/ qa-artifacts/
# Playwright MCP session logs: browser consoles can carry tokens in URLs.
.playwright-mcp/
# Local Claude Code settings and preview configs.
.claude/
.DS_Store .DS_Store
.gstack/ .gstack/
3d-models/ 3d-models/
+20 -14
View File
@@ -317,8 +317,9 @@
[NotProniss](https://github.com/NotProniss) (#1084). [NotProniss](https://github.com/NotProniss) (#1084).
- Street Level: Panoramax is the fourth provider, keyless. Light its chip - Street Level: Panoramax is the fourth provider, keyless. Light its chip
(orange; off by default, one provider at a time): below about 60 km the (orange; off by default, one provider at a time): from orbit dots show
federated commons' sequences draw as lines from `api.panoramax.xyz` vector tiles. A click on a where the federated commons has pictures, and below about 60 km its
sequences draw as lines from `api.panoramax.xyz` vector tiles. A click on a
line opens that sequence's picture nearest the click without moving the line opens that sequence's picture nearest the click without moving the
camera, flat or 360°, with cones along the sequence around it and ‹ › / camera, flat or 360°, with cones along the sequence around it and ‹ › /
← → following the picture's own links. The 360° and since filters apply, ← → following the picture's own links. The 360° and since filters apply,
@@ -376,10 +377,10 @@
Maps JavaScript API) and click a street, or press OPEN STREET VIEW, to Maps JavaScript API) and click a street, or press OPEN STREET VIEW, to
open Google's own panorama in open Google's own panorama in
the panel, with its arrows, the address and month in the caption, a link the panel, with its arrows, the address and month in the caption, a link
to Google Maps. Share links carry it in the provider switches to Google Maps and FOLLOW. Share links carry it in the provider switches
(`r.google-1`). One provider is lit at a time (lighting one switches the (`r.google-1`). One provider is lit at a time (lighting one switches the
other off), Mapillary by default since it is free. Street View's panoramas other off), Mapillary by default since it is free. Street View's panoramas
are all 360°, so the IMAGERY and SINCE filters apply to are all 360°, so the IMAGERY and SINCE filters and the legend apply to
Mapillary only and hide while GOOGLE STREET VIEW is lit; its globe marker Mapillary only and hide while GOOGLE STREET VIEW is lit; its globe marker
is a Google-blue view cone. is a Google-blue view cone.
@@ -418,16 +419,21 @@
proposed diagnosis in #927, and [kvnloo](https://github.com/kvnloo) for identifying proposed diagnosis in #927, and [kvnloo](https://github.com/kvnloo) for identifying
the repair race. Windows/Claude Desktop Cowork confirmation remains outstanding. the repair race. Windows/Claude Desktop Cowork confirmation remains outstanding.
- Street Level: street-level imagery from providers, Mapillary first (free - Street Level: a street-level imagery layer modelled on the iD editor's photo
client token, CC BY-SA 4.0). A right-rail panel holds a chip per provider, overlay, with Mapillary as its first provider (free client token, CC BY-SA 4.0
360°/flat and captured-since filters and an embedded viewer with EXPAND and imagery). One right-rail panel holds a chip per provider, shared 360°/flat and
FIT/FILL. Coverage lines (below 60 km) and image cones drape on terrain and captured-since filters, and an embedded viewer with EXPAND, FIT/FILL and
Google 3D tiles; opening a photo frames it with one camera flight. Share FOLLOW (Google 3D only). Coverage lines and image cones are drawn from orbit
links carry the provider switches, the filters and the panel's collapsed down to a single street; on Google 3D they sit on the bare earth, refined
state. A server proxy adds the token to Mapillary coverage tiles, trims and against the rendered mesh near the camera, so trees and buildings hide them.
caches them for 24 h, refuses cross-site requests and redirects, and limits Share links carry the provider switches, the filters and the panel's collapsed
load per IP and upstream. The panel reads KEY REQUIRED without a token and state. A server proxy caches Mapillary coverage tiles (24 h, 1 GiB on disk),
KEY REJECTED when Mapillary refuses it. refuses cross-site requests, rate-limits per IP and backs off when Mapillary
rejects the token or rate-limits.
- The CCTV and Street Level panels are portable: drag the header to float the
panel, resize it from any edge or corner, and double-click the header to dock
it again. The position persists across reloads.
- Add Norway's city bikes to the Bike Share layer: Oslo, Bergen and - Add Norway's city bikes to the Bike Share layer: Oslo, Bergen and
Trondheim Bysykkel (Urban Sharing), Kolumbus Bysykkel in Stavanger and Trondheim Bysykkel (Urban Sharing), Kolumbus Bysykkel in Stavanger and
+8 -6
View File
@@ -54,8 +54,9 @@ head -40 scripts/qa-radio.mjs # what this runnable gate proves and how to run i
Runnable gate entrypoints document what they assert and how to invoke them. Runnable gate entrypoints document what they assert and how to invoke them.
Most need a dev server; some also need a specific provider key or port. Follow Most need a dev server; some also need a specific provider key or port. Follow
the entrypoint's header rather than assuming every matching file accepts the the entrypoint's header rather than assuming every matching file accepts the
same arguments. Four have an `npm run` alias: `qa:map-source-tray`, same arguments. Five have an `npm run` alias: `qa:map-source-tray`,
`qa:street-level`, `qa:street-level:fixtures` and `qa:transit`. `qa:panel-resize`, `qa:street-level`, `qa:street-level:fixtures` and
`qa:transit`.
If you aren't sure which gate covers your change, search `docs/CURRENT-STATE.md` If you aren't sure which gate covers your change, search `docs/CURRENT-STATE.md`
for the feature: it names the gate for many of them, and it's the authoritative for the feature: it names the gate for many of them, and it's the authoritative
@@ -65,10 +66,11 @@ gate for the feature you changed.
> **CI covers only two of these for you.** The workflow runs the setup policy > **CI covers only two of these for you.** The workflow runs the setup policy
> checks, the formatting and package-boundary checks, the unit suite and the > checks, the formatting and package-boundary checks, the unit suite and the
> production build, plus a Windows onboarding job. It runs neither > production build, plus a Windows onboarding job, and against the built preview
> `npm run test:track` nor any `qa-*.mjs` gate except the Street Level fixture > it runs `qa:street-level:fixtures` and `qa:panel-resize`. It does not run
> gate (`street-level-browser` job) — they need a live dev server and a > `npm run test:track` or any other `qa-*.mjs` gate — those need a live dev
> browser. Include the applicable local run in your PR's validation evidence. > server and a browser. Include the applicable local run in your PR's
> validation evidence.
## Share-link layer tokens ## Share-link layer tokens
+3 -10
View File
@@ -20,10 +20,10 @@ How to read this:
| **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" | | **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" |
| **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" | | **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" |
| **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" | | **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" |
| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on | | **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles cached for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
| **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer | | **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer |
| **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on | | **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
| **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence | | **Panoramax** (`api.panoramax.xyz` meta-catalogue: vector tiles and STAC search; pictures from the federated instance holding each one, e.g. `panoramax.openstreetmap.fr`, `panoramax.ign.fr`) | Street Level: coverage lines and density points, nearest-picture lookups, a sequence's pictures as cones, and the picture itself, fetched by the browser. Keyless; tiles cached by the browser for an hour (the API's own header) | Per picture: mostly [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), IGN's [Licence Ouverte 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/); the API needs no token | "© Panoramax contributors, licence per picture" on the globe while the provider is on; the caption names each picture's author and licence |
| **OpenStreetMap** | Map and place data (roads, military areas and names, ALPR, place search, outlines); via vector tiles, hourly ALPR extract, bundled data, Nominatim and optional self-configured Overpass | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | © OpenStreetMap contributors | | **OpenStreetMap** | Map and place data (roads, military areas and names, ALPR, place search, outlines); via vector tiles, hourly ALPR extract, bundled data, Nominatim and optional self-configured Overpass | [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/) | © OpenStreetMap contributors |
| **Google Map Tiles API** (Photorealistic 3D Tiles) + Places/Geocoding | The 3D globe, voice scene context, and on-demand nearby installation search | Google Maps Platform ToS (proprietary, your own key + billing) | "Google" / "Google Maps" logo — **shown in-app**, required | | **Google Map Tiles API** (Photorealistic 3D Tiles) + Places/Geocoding | The 3D globe, voice scene context, and on-demand nearby installation search | Google Maps Platform ToS (proprietary, your own key + billing) | "Google" / "Google Maps" logo — **shown in-app**, required |
| **OpenSky Network** | Primary worldwide live-flight snapshot | Non-commercial research/education license | Schäfer et al., _"Bringing Up OpenSky"_, IPSN 2014 + opensky-network.org | | **OpenSky Network** | Primary worldwide live-flight snapshot | Non-commercial research/education license | Schäfer et al., _"Bringing Up OpenSky"_, IPSN 2014 + opensky-network.org |
@@ -48,7 +48,6 @@ How to read this:
| **GDELT Project DOC 2.0** | Fail-soft fallback for location-matched cockpit headlines | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic/commercial/governmental dataset use, with citation and link required; linked articles retain publisher terms | "GDELT Project" plus each article's linked publisher/domain | | **GDELT Project DOC 2.0** | Fail-soft fallback for location-matched cockpit headlines | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic/commercial/governmental dataset use, with citation and link required; linked articles retain publisher terms | "GDELT Project" plus each article's linked publisher/domain |
| **City of Austin Open Data** | CCTV camera catalog + frames | City of Austin Open Data Terms of Use | "City of Austin, TX — data.austintexas.gov" | | **City of Austin Open Data** | CCTV camera catalog + frames | City of Austin Open Data Terms of Use | "City of Austin, TX — data.austintexas.gov" |
| **TxDOT ITS (its.txdot.gov)** | CCTV camera catalogs + frames, Texas districts | Public TxDOT traffic camera data | "Texas Department of Transportation" (courtesy) | | **TxDOT ITS (its.txdot.gov)** | CCTV camera catalogs + frames, Texas districts | Public TxDOT traffic camera data | "Texas Department of Transportation" (courtesy) |
| **FL511 (Florida DOT)** | CCTV camera catalog + frames, Florida statewide | FL511 content, individual personal use only; any other use needs FDOT's express written consent ([terms](https://fl511.com/privacy#disclaimer)). **Off by default**; set `CCTV_FLORIDA_ENABLED=1` to enable | "Florida DOT — FL511.com" (courtesy) |
| **City of Tallinn (ristmikud.tallinn.ee)** | CCTV camera catalog + frames, Tallinn intersections | Public City of Tallinn traffic camera data | "City of Tallinn — ristmikud.tallinn.ee" (courtesy) | | **City of Tallinn (ristmikud.tallinn.ee)** | CCTV camera catalog + frames, Tallinn intersections | Public City of Tallinn traffic camera data | "City of Tallinn — ristmikud.tallinn.ee" (courtesy) |
| **Transpordiamet / Tarktee** | CCTV camera catalog + frames, Estonia road-weather cameras | Public Transpordiamet / Tarktee road camera data | "Transpordiamet / Tarktee — tarktee.transpordiamet.ee" (courtesy) | | **Transpordiamet / Tarktee** | CCTV camera catalog + frames, Estonia road-weather cameras | Public Transpordiamet / Tarktee road camera data | "Transpordiamet / Tarktee — tarktee.transpordiamet.ee" (courtesy) |
| **Stadt Warendorf webcam** | Webcam frames, Marktplatz / Historisches Rathaus (`config/cctv_sources.warendorf.json`) | Public municipal webcam data | "Stadt Warendorf — webcam.warendorf.de" (courtesy) | | **Stadt Warendorf webcam** | Webcam frames, Marktplatz / Historisches Rathaus (`config/cctv_sources.warendorf.json`) | Public municipal webcam data | "Stadt Warendorf — webcam.warendorf.de" (courtesy) |
@@ -63,9 +62,7 @@ How to read this:
| **Servei Català de Trànsit** (+ Ajuntament de Barcelona, Ajuntament de Terrassa) | CCTV camera catalog + frames, Catalonia | [Llicència oberta d'ús d'informació - Catalunya](https://web.gencat.cat/ca/generalitat/dades-indicadors/dades-obertes/llicencies) — attribution REQUIRED | "Servei Català de Trànsit"; partner-supplied cameras also name their owner | | **Servei Català de Trànsit** (+ Ajuntament de Barcelona, Ajuntament de Terrassa) | CCTV camera catalog + frames, Catalonia | [Llicència oberta d'ús d'informació - Catalunya](https://web.gencat.cat/ca/generalitat/dades-indicadors/dades-obertes/llicencies) — attribution REQUIRED | "Servei Català de Trànsit"; partner-supplied cameras also name their owner |
| **King County Road Services** (`services.arcgis.com`, King County GIS) | CCTV camera catalog + frames, unincorporated King County WA road network | [KCGIS Center terms](https://kingcounty.gov/en/dept/kcit/data-information-services/gis-center/about/terms-conditions-copyrights) — attribution required; public ArcGIS layer | "King County Road Services" (partner-city cameras name their owner) | | **King County Road Services** (`services.arcgis.com`, King County GIS) | CCTV camera catalog + frames, unincorporated King County WA road network | [KCGIS Center terms](https://kingcounty.gov/en/dept/kcit/data-information-services/gis-center/about/terms-conditions-copyrights) — attribution required; public ArcGIS layer | "King County Road Services" (partner-city cameras name their owner) |
| **WSDOT** (`data.wsdot.wa.gov`) | CCTV camera catalog + frames, Washington State highways | [WSDOT travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer) — public "low volume" feed; catalog cached, frames on WSDOT's own image host only | "Washington State Department of Transportation (Travel Center)" (courtesy) | | **WSDOT** (`data.wsdot.wa.gov`) | CCTV camera catalog + frames, Washington State highways | [WSDOT travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer) — public "low volume" feed; catalog cached, frames on WSDOT's own image host only | "Washington State Department of Transportation (Travel Center)" (courtesy) |
| **Hong Kong Transport Department / DATA.GOV.HK** | CCTV camera catalog + frames, Hong Kong traffic snapshot cameras | [DATA.GOV.HK Terms of Use](https://data.gov.hk/en/terms-and-conditions) — attribution REQUIRED | "Hong Kong Transport Department / DATA.GOV.HK" |
| **Statens vegvesen** (catalog `ogckart-sn1.atlas.vegvesen.no`, frames `kamera.atlas.vegvesen.no`, HLS `kamera.vegvesen.no`) | CCTV camera catalog + frames + live HLS video, Norway road cameras | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) distributed by Statens vegvesen" | | **Statens vegvesen** (catalog `ogckart-sn1.atlas.vegvesen.no`, frames `kamera.atlas.vegvesen.no`, HLS `kamera.vegvesen.no`) | CCTV camera catalog + frames + live HLS video, Norway road cameras | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) distributed by Statens vegvesen" |
| **Kartverket** (`ws.geonorge.no/hoydedata/v1/punkt`) | Terrain heights (NN2000) used as the ground prior for Statens vegvesen cameras | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — attribution REQUIRED | "© Kartverket", modified (heights over water set to 0 m, rounded to 0.1 m) |
| **NYC DOT Traffic Management Center** (`webcams.nyctmc.org`) | CCTV camera catalog + frames, New York City five boroughs | NYC DOT requires developers to sign a [data-sharing agreement](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) for the camera feed. **Off by default**; enable only under your own agreement | "NYC DOT Traffic Management Center" + NYC DOT's required application disclaimer (in the Data attribution popover) | | **NYC DOT Traffic Management Center** (`webcams.nyctmc.org`) | CCTV camera catalog + frames, New York City five boroughs | NYC DOT requires developers to sign a [data-sharing agreement](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) for the camera feed. **Off by default**; enable only under your own agreement | "NYC DOT Traffic Management Center" + NYC DOT's required application disclaimer (in the Data attribution popover) |
| **City of Toronto Open Data** (`opendata.toronto.ca`) | CCTV camera catalog + frames, Toronto city streets | [Open Government Licence – Toronto](https://www.toronto.ca/city-government/data-research-maps/open-data/open-data-licence/) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – Toronto" | | **City of Toronto Open Data** (`opendata.toronto.ca`) | CCTV camera catalog + frames, Toronto city streets | [Open Government Licence – Toronto](https://www.toronto.ca/city-government/data-research-maps/open-data/open-data-licence/) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – Toronto" |
| **GBFS (Lyft / BCycle / Social Bicycles / PBSC)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` | | **GBFS (Lyft / BCycle / Social Bicycles / PBSC)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` |
@@ -113,7 +110,6 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
**Quebec is thinly represented**, and that is upstream rather than a filter here: the province runs its own Info-Smog program, so only a handful of Quebec stations appear in ECCC's national feed. The reporting station count also varies hour to hour as stations report or fall silent. **Quebec is thinly represented**, and that is upstream rather than a filter here: the province runs its own Info-Smog program, so only a handful of Quebec stations appear in ECCC's national feed. The reporting station count also varies hour to hour as stations report or fall silent.
- **Via Lietuva / Eismoinfo (Lithuania).** Public road-camera catalogs and periodically updated still images from [Eismoinfo](https://eismoinfo.lt/), credited to Via Lietuva / eismoinfo.lt in the app. **Off by default.** The camera endpoints are the eismoinfo.lt website backend and are not among the services listed in Via Lietuva's [open-data statement](https://eismoinfo.lt/eismoinfo-backend/content?id=44), whose conditions are attribution and reuse on the same terms. Until the statement is confirmed to cover the camera photos, the pack loads only when an operator sets `CCTV_LITHUANIA_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to Eismoinfo. `eismoinfo-backend/camera-info-table` is joined by ID to `layer-static-features/VKR`. Without `lks=true`, the latter returns WGS84 `[latitude, longitude]`; the table's `x/y` instead use LKS-94 metres. Only the official HTTPS `/eismoinfo-backend/image-provider/camera/last?id=…` image endpoint is registered. Catalogs use the shared 15-minute cache; frames are fetched on demand and never bundled or archived. These are periodic snapshots, not continuous video. Camera headings are low-confidence estimates. No API key is required. `CCTV_LITHUANIA_MAX_SOURCES` defaults to 400. - **Via Lietuva / Eismoinfo (Lithuania).** Public road-camera catalogs and periodically updated still images from [Eismoinfo](https://eismoinfo.lt/), credited to Via Lietuva / eismoinfo.lt in the app. **Off by default.** The camera endpoints are the eismoinfo.lt website backend and are not among the services listed in Via Lietuva's [open-data statement](https://eismoinfo.lt/eismoinfo-backend/content?id=44), whose conditions are attribution and reuse on the same terms. Until the statement is confirmed to cover the camera photos, the pack loads only when an operator sets `CCTV_LITHUANIA_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to Eismoinfo. `eismoinfo-backend/camera-info-table` is joined by ID to `layer-static-features/VKR`. Without `lks=true`, the latter returns WGS84 `[latitude, longitude]`; the table's `x/y` instead use LKS-94 metres. Only the official HTTPS `/eismoinfo-backend/image-provider/camera/last?id=…` image endpoint is registered. Catalogs use the shared 15-minute cache; frames are fetched on demand and never bundled or archived. These are periodic snapshots, not continuous video. Camera headings are low-confidence estimates. No API key is required. `CCTV_LITHUANIA_MAX_SOURCES` defaults to 400.
- **Freeway Bureau, MOTC (Taiwan).** National freeway cameras from the Freeway Bureau's keyless [CCTV static table](https://tisvcloud.freeway.gov.tw/history/motc20/CCTV.xml) in the MOTC 2.0 standard, refreshed daily and fetched at runtime (never bundled). Freeway Bureau traffic data is published under the [Open Government Data License, Taiwan (Version 1.0)](https://data.gov.tw/license), which permits reuse, including commercial reuse, with attribution; the app credits the Freeway Bureau, MOTC, names the dataset and links the licence, as its attribution exhibit asks. The table publishes each camera's MJPEG stream on one of four official camera servers (`cctvn`, `cctvn5`, `cctvc`, `cctvs` under `freeway.gov.tw`). The frame proxy relays single images, so each published stream URL is mapped to the same server's single-JPEG path for the same camera number (`/abs2mjpg/bmjpg` → `/abs2mjpg/jpg`, `/live-view/mjpg/video.cgi` → `/live-view/jpg/image.cgi`); only those exact HTTPS pairs are registered, and the still path is not itself listed in the table. These are on-demand snapshots, not continuous video. Camera headings are low-confidence estimates. No API key is required. The table host does not answer from some networks outside Taiwan (the camera servers do); there the pack is empty, logs one warning and retries hourly. On by default; `CCTV_TAIWAN_ENABLED=0` skips the pack, and `CCTV_TAIWAN_MAX_SOURCES` defaults to 600 (bounded to 1–2000).
- **Google Maps Platform.** You supply your own API key and are bound by [Google's ToS](https://cloud.google.com/maps-platform/terms). Google Maps Content (tiles, geocodes, places) **may not be cached, stored, rehosted, or committed** — this app only ever uses it live, which is the compliant pattern. The "Google" attribution is displayed on the globe and must stay visible. Restrict your key (see [SECURITY.md](SECURITY.md)). - **Google Maps Platform.** You supply your own API key and are bound by [Google's ToS](https://cloud.google.com/maps-platform/terms). Google Maps Content (tiles, geocodes, places) **may not be cached, stored, rehosted, or committed** — this app only ever uses it live, which is the compliant pattern. The "Google" attribution is displayed on the globe and must stay visible. Restrict your key (see [SECURITY.md](SECURITY.md)).
- **OpenSky Network.** Its license is **non-commercial**, and operational use of the REST API in a live product can require a prior written agreement with OpenSky — even for non-profit/government use. If you deploy this commercially, contact OpenSky for your own terms. The flights layer is a toggle and runs anonymously by default. - **OpenSky Network.** Its license is **non-commercial**, and operational use of the REST API in a live product can require a prior written agreement with OpenSky — even for non-profit/government use. If you deploy this commercially, contact OpenSky for your own terms. The flights layer is a toggle and runs anonymously by default.
@@ -156,7 +152,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **adsbdb enrichment.** `/api/adsbdb` resolves an ICAO hex to aircraft type, model name and registration, and the tracked flight's callsign to an airline and an origin/destination pair. Fan-out is deliberately small because adsbdb is a free community API that publishes no quota: at most 4 requests in flight, dispatches dripped to roughly 5/s, and each key asked for at most once per session, with route lookups reserved for the tracked aircraft. The dev-server proxy caches each key for 24 hours in `.gev-cache/adsbdb.json`, negative answers included, so fresh entries survive server restarts. That gitignored cache remains local to the deployment and is not bundled with this repo. adsbdb publishes no general service license; its README says the route data may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh. Deployers are responsible for obtaining any permission their use requires. Enrichment is best-effort and fail-silent — a flight that gets no answer keeps what the flight feed already gave it. - **adsbdb enrichment.** `/api/adsbdb` resolves an ICAO hex to aircraft type, model name and registration, and the tracked flight's callsign to an airline and an origin/destination pair. Fan-out is deliberately small because adsbdb is a free community API that publishes no quota: at most 4 requests in flight, dispatches dripped to roughly 5/s, and each key asked for at most once per session, with route lookups reserved for the tracked aircraft. The dev-server proxy caches each key for 24 hours in `.gev-cache/adsbdb.json`, negative answers included, so fresh entries survive server restarts. That gitignored cache remains local to the deployment and is not bundled with this repo. adsbdb publishes no general service license; its README says the route data may not be copied, published, or incorporated into other databases without the explicit permission of David J Taylor, Edinburgh. Deployers are responsible for obtaining any permission their use requires. Enrichment is best-effort and fail-silent — a flight that gets no answer keeps what the flight feed already gave it.
- **Launch Library 2.** `/api/launches` makes a server-side rolling-30-day query against the supported v2.3 detailed launch endpoint, caches successful responses for 15 minutes in memory and on disk, and serves the last successful response during a throttle or transient outage. Anonymous access is limited to 15 calls/hour; deployments can provide `LL2_API_TOKEN` for authenticated access. The Space Devs' published terms permit using and sharing the API data in any form, ask users not to forward it without adding value, disclaim complete accuracy, and encourage—but do not require—attribution. This app keeps a courtesy credit. Payload and stage/recovery records are shown only when supplied. Failed launches expose their source status and never receive fallback orbit geometry or a live/estimated marker. LL2 supplies launch context and event timing, not continuous ascent telemetry or live orbital state. - **Launch Library 2.** `/api/launches` makes a server-side rolling-30-day query against the supported v2.3 detailed launch endpoint, caches successful responses for 15 minutes in memory and on disk, and serves the last successful response during a throttle or transient outage. Anonymous access is limited to 15 calls/hour; deployments can provide `LL2_API_TOKEN` for authenticated access. The Space Devs' published terms permit using and sharing the API data in any form, ask users not to forward it without adding value, disclaim complete accuracy, and encourage—but do not require—attribution. This app keeps a courtesy credit. Payload and stage/recovery records are shown only when supplied. Failed launches expose their source status and never receive fallback orbit geometry or a live/estimated marker. LL2 supplies launch context and event timing, not continuous ascent telemetry or live orbital state.
- **TfL JamCams.** The camera list comes from the keyless `api.tfl.gov.uk` endpoint (an optional `TFL_APP_KEY` raises its rate limit); frames come from TfL's public S3 bucket. The "Powered by TfL Open Data" attribution is required by TfL's terms and is registered in the Data attribution popover. - **TfL JamCams.** The camera list comes from the keyless `api.tfl.gov.uk` endpoint (an optional `TFL_APP_KEY` raises its rate limit); frames come from TfL's public S3 bucket. The "Powered by TfL Open Data" attribution is required by TfL's terms and is registered in the Data attribution popover.
- **Ontario 511 CCTV.** The camera list comes from the `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence - Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does. - **Ontario 511 CCTV.** The camera list comes from the keyless `511on.ca/api/v2/get/cameras` endpoint; frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario.
- **DelDOT live video cameras.** The keyless `tmc.deldot.gov/json/videocamera.json` catalog supplies active cameras and official `https://video.deldot.gov/live/…/playlist.m3u8` links. The local server transiently buffers bounded MPEG-TS segments in memory and deletes them on session release or idle expiry. No recordings are retained. `CCTV_DELDOT_ENABLED=0` disables the pack. Public availability is not a blanket redistribution license; deployment beyond personal local viewing needs confirmation of applicable DelDOT terms. - **DelDOT live video cameras.** The keyless `tmc.deldot.gov/json/videocamera.json` catalog supplies active cameras and official `https://video.deldot.gov/live/…/playlist.m3u8` links. The local server transiently buffers bounded MPEG-TS segments in memory and deletes them on session release or idle expiry. No recordings are retained. `CCTV_DELDOT_ENABLED=0` disables the pack. Public availability is not a blanket redistribution license; deployment beyond personal local viewing needs confirmation of applicable DelDOT terms.
- **Fintraffic weathercams.** The camera list is one keyless GeoJSON request to `tie.digitraffic.fi/api/weathercam/v1/stations` (809 stations / 2,275 presets), sent with the `Digitraffic-User: gods-eye-view` header the service asks clients to identify themselves with and with gzip; frames are stills on `weathercam.digitraffic.fi`, refreshed on each station's 600 s collection interval, which is also the client's ambient-still refresh cadence for this pack (the active camera keeps the usual 10-second refresh). One preset (a fixed camera view) is one camera; stations not `GATHERING` and presets not `inCollection` are dropped. Attribution is required by the CC BY 4.0 licence and is registered in the Data attribution popover. `CCTV_FINTRAFFIC_ENABLED=0` is the kill switch. - **Fintraffic weathercams.** The camera list is one keyless GeoJSON request to `tie.digitraffic.fi/api/weathercam/v1/stations` (809 stations / 2,275 presets), sent with the `Digitraffic-User: gods-eye-view` header the service asks clients to identify themselves with and with gzip; frames are stills on `weathercam.digitraffic.fi`, refreshed on each station's 600 s collection interval, which is also the client's ambient-still refresh cadence for this pack (the active camera keeps the usual 10-second refresh). One preset (a fixed camera view) is one camera; stations not `GATHERING` and presets not `inCollection` are dropped. Attribution is required by the CC BY 4.0 licence and is registered in the Data attribution popover. `CCTV_FINTRAFFIC_ENABLED=0` is the kill switch.
- **DriveBC highway cameras.** The camera list comes from the keyless `https://www.drivebc.ca/api/webcams/` endpoint served by the DriveBC.ca site ([bcgov/DriveBC.ca](https://github.com/bcgov/DriveBC.ca)); frames come from `https://www.drivebc.ca/images/<id>.jpg`, built from the numeric camera id. DataBC's [DriveBC HighwayCams](https://catalogue.data.gov.bc.ca/dataset/bc-highwaycams) catalogue entry publishes the same cameras under the Open Government Licence – British Columbia, but its CSV still lists the retired `images.drivebc.ca` frame URLs, which now return a placeholder. The licence's attribution statement is required and is registered in the Data attribution popover. By default the 250 cameras nearest Vancouver and Victoria load; `CCTV_DRIVEBC_MAX_SOURCES` changes the cap and `CCTV_DRIVEBC_ENABLED=0` turns the pack off. Some cameras in the feed are supplied by partners (TransLink, the City of Vancouver, the City of Surrey, Parks Canada / Alberta Motor Association and others); the feed's per-camera credit is carried onto the camera record and shown beside the provider in the CCTV panel. - **DriveBC highway cameras.** The camera list comes from the keyless `https://www.drivebc.ca/api/webcams/` endpoint served by the DriveBC.ca site ([bcgov/DriveBC.ca](https://github.com/bcgov/DriveBC.ca)); frames come from `https://www.drivebc.ca/images/<id>.jpg`, built from the numeric camera id. DataBC's [DriveBC HighwayCams](https://catalogue.data.gov.bc.ca/dataset/bc-highwaycams) catalogue entry publishes the same cameras under the Open Government Licence – British Columbia, but its CSV still lists the retired `images.drivebc.ca` frame URLs, which now return a placeholder. The licence's attribution statement is required and is registered in the Data attribution popover. By default the 250 cameras nearest Vancouver and Victoria load; `CCTV_DRIVEBC_MAX_SOURCES` changes the cap and `CCTV_DRIVEBC_ENABLED=0` turns the pack off. Some cameras in the feed are supplied by partners (TransLink, the City of Vancouver, the City of Surrey, Parks Canada / Alberta Motor Association and others); the feed's per-camera credit is carried onto the camera record and shown beside the provider in the CCTV panel.
@@ -166,13 +162,10 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Warendorf webcam.** The Stadt Warendorf Marktplatz webcam, registered from the curated `config/cctv_sources.warendorf.json` (the Kreis Warendorf registration-office cameras from the contributing PR are indoor waiting rooms and were left out); only the municipal image host is proxied, frames are fetched at request time and never stored or redistributed. Disable with `CCTV_WARENDORF_ENABLED=0`. - **Warendorf webcam.** The Stadt Warendorf Marktplatz webcam, registered from the curated `config/cctv_sources.warendorf.json` (the Kreis Warendorf registration-office cameras from the contributing PR are indoor waiting rooms and were left out); only the municipal image host is proxied, frames are fetched at request time and never stored or redistributed. Disable with `CCTV_WARENDORF_ENABLED=0`.
- **Live Traffic NSW cameras.** The camera list is the keyless public `data.livetraffic.com/cameras/traffic-cam.json` feed (Transport for NSW open data, CC BY 4.0); frames are stills on `webcams.transport.nsw.gov.au`, and only that host is registered. That image host answers non-browser clients with an HTML placeholder, so the proxy identifies as a browser for that one host and as itself everywhere else. Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_NSW_ENABLED=0`. - **Live Traffic NSW cameras.** The camera list is the keyless public `data.livetraffic.com/cameras/traffic-cam.json` feed (Transport for NSW open data, CC BY 4.0); frames are stills on `webcams.transport.nsw.gov.au`, and only that host is registered. That image host answers non-browser clients with an HTML placeholder, so the proxy identifies as a browser for that one host and as itself everywhere else. Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_NSW_ENABLED=0`.
- **Open Calgary traffic cameras.** Keyless. The camera list is the public Socrata dataset `k7p9-kppz` on `data.calgary.ca`; frames are stills on the city's own `trafficcam.calgary.ca` host, and only that host is registered. Most rows publish an `http://` frame URL and the host redirects those to HTTPS, so URLs are upgraded and pinned to that origin before registration. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `quadrant` field and the quadrant suffix on each camera name are Calgary's address grid, not a bearing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. The licence requires the attribution statement above. Disable with `CCTV_CALGARY_ENABLED=0`. - **Open Calgary traffic cameras.** Keyless. The camera list is the public Socrata dataset `k7p9-kppz` on `data.calgary.ca`; frames are stills on the city's own `trafficcam.calgary.ca` host, and only that host is registered. Most rows publish an `http://` frame URL and the host redirects those to HTTPS, so URLs are upgraded and pinned to that origin before registration. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `quadrant` field and the quadrant suffix on each camera name are Calgary's address grid, not a bearing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. The licence requires the attribution statement above. Disable with `CCTV_CALGARY_ENABLED=0`.
- **FL511 Florida cameras.** Off by default; set `CCTV_FLORIDA_ENABLED=1` to load them. The camera list is the keyless FL511 traffic camera layer on ArcGIS (`services.arcgis.com/.../FL511_Traffic_Cameras`), published from a Florida Division of Emergency Management account rather than by FL511 directly, and the service carries no licence text of its own. It is paged up to 2,000 rows at a time, ordered by the layer's object id and following ArcGIS's `exceededTransferLimit`, to cover the ~4,000-camera statewide set. Frames are stills on two Divas Cloud hosts (`images-dis.divas.cloud`, `snapshots.divas.cloud`); both are host-pinned and a row whose image resolves elsewhere is dropped. `CCTV_FLORIDA_MAX_SOURCES` caps the pack (default 500, anchored per region across the state). Each catalog page is read under a 2 MiB cap and redirects are refused. Frames are fetched live at request time and never stored or redistributed. FL511's terms (fl511.com/privacy#disclaimer) license its content for individual, personal use only; any other use, including a public deployment, needs FDOT's express written consent.
- **Catalonia (Servei Català de Trànsit) cameras.** The camera list is the keyless `https://www.gencat.cat/transit/opendata/cameres.xml` WFS/GML feed, fetched over https with redirects refused and the body read capped at 1 MiB, since the list decides ids, coordinates and which allowlisted frame path is proxied. It carries a `font` field naming the real publisher per camera; this pack keeps SCT's own highway cameras plus hotlinked Barcelona (IMI) and Terrassa municipal cameras (~130 total), each confirmed to return a real frame, so frame URLs are checked against a small host allowlist (`mct.gencat.cat`, `www.bcn.cat`, `emap.terrassa.cat`) rather than one pinned origin (a link carrying `user:pass@` userinfo or an explicit port, or pointing outside that host's frame directory, is rejected even on an allowed host; an SCT `sctidcam` must be a bare `.gif`/`.jpg` filename), and every non-SCT camera carries its real owner as a `credit` shown beside the shared `provider`. The feed carries no compass heading, so every camera loads at low heading confidence (same as TfL and Fintraffic). SCT's own feed link (`RenderService`) needed a workaround: it always 302s to a second endpoint (`TransitCamera`) on a Location the upstream hardcodes as plain http even when requested over https — refused by `fetchWithinHost`'s same-origin (scheme-included) redirect policy — and separately, `mct.gencat.cat`'s TLS setup fails the handshake with Node's fetch outright (`ERR_SSL_WRONG_SIGNATURE_TYPE`) even though other HTTP clients complete it. The loader therefore builds the `TransitCamera` URL itself, over plain http, from `RenderService`'s `sctidcam` id, rather than registering the (broken) upstream link — the only transport this one host actually serves to this runtime. Camera ids are built from the SCT camera file or the partner image path, not the feed's `fid` (which embeds an upstream server-start stamp and changes on every upstream restart), and rows the feed lists more than once collapse to one camera. The feed carries no camera status field, so a camera its publisher has taken offline still registers and shows the publisher's own "image unavailable" still (SCT and Barcelona both serve one with HTTP 200), the same as other packs without a status field. Frames are fetched at request time and never stored or redistributed. The feed itself states no licence; the pack relies on the Generalitat de Catalunya open-data portal's terms for this dataset (the licence and attribution above). Disable with `CCTV_CATALONIA_ENABLED=0`. - **Catalonia (Servei Català de Trànsit) cameras.** The camera list is the keyless `https://www.gencat.cat/transit/opendata/cameres.xml` WFS/GML feed, fetched over https with redirects refused and the body read capped at 1 MiB, since the list decides ids, coordinates and which allowlisted frame path is proxied. It carries a `font` field naming the real publisher per camera; this pack keeps SCT's own highway cameras plus hotlinked Barcelona (IMI) and Terrassa municipal cameras (~130 total), each confirmed to return a real frame, so frame URLs are checked against a small host allowlist (`mct.gencat.cat`, `www.bcn.cat`, `emap.terrassa.cat`) rather than one pinned origin (a link carrying `user:pass@` userinfo or an explicit port, or pointing outside that host's frame directory, is rejected even on an allowed host; an SCT `sctidcam` must be a bare `.gif`/`.jpg` filename), and every non-SCT camera carries its real owner as a `credit` shown beside the shared `provider`. The feed carries no compass heading, so every camera loads at low heading confidence (same as TfL and Fintraffic). SCT's own feed link (`RenderService`) needed a workaround: it always 302s to a second endpoint (`TransitCamera`) on a Location the upstream hardcodes as plain http even when requested over https — refused by `fetchWithinHost`'s same-origin (scheme-included) redirect policy — and separately, `mct.gencat.cat`'s TLS setup fails the handshake with Node's fetch outright (`ERR_SSL_WRONG_SIGNATURE_TYPE`) even though other HTTP clients complete it. The loader therefore builds the `TransitCamera` URL itself, over plain http, from `RenderService`'s `sctidcam` id, rather than registering the (broken) upstream link — the only transport this one host actually serves to this runtime. Camera ids are built from the SCT camera file or the partner image path, not the feed's `fid` (which embeds an upstream server-start stamp and changes on every upstream restart), and rows the feed lists more than once collapse to one camera. The feed carries no camera status field, so a camera its publisher has taken offline still registers and shows the publisher's own "image unavailable" still (SCT and Barcelona both serve one with HTTP 200), the same as other packs without a status field. Frames are fetched at request time and never stored or redistributed. The feed itself states no licence; the pack relies on the Generalitat de Catalunya open-data portal's terms for this dataset (the licence and attribution above). Disable with `CCTV_CATALONIA_ENABLED=0`.
- **King County road cameras.** Keyless. The camera list is one public ArcGIS FeatureServer GeoJSON query (King County DOT Road Services, "King County and WSDOT Traffic Cameras"). The `outFields` list is explicit on purpose: the layer also carries asset-administration columns — including staff names — that are never fetched. Only live, active cameras with frames on the county's own `info.kingcounty.gov` image handler are registered (the feed writes `http://`; the handler serves HTTPS, so URLs are upgraded and pinned before registration). WSDOT-owned rows in the layer are skipped because their frames are WSDOT-hosted, outside the pinned image origin; partner-city cameras hosted on the county image handler (e.g. Newcastle) name their owner as the per-camera credit. The layer publishes no facing, so headings use the shared id-hash fallback at low confidence. Uniquely, the county publishes each camera's hardware `Manufacturer`/`Model` (Cohu 3950/3965, Bosch AUTODOME, Axis PTZ domes); both are carried on the source (and served by `/api/cctv/sources`) as `model` and `manufacturer` for identified-hardware consumers (vendor-generic strings such as `PTZ` name no model and are omitted). Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_KINGCOUNTY_ENABLED=0`. - **King County road cameras.** Keyless. The camera list is one public ArcGIS FeatureServer GeoJSON query (King County DOT Road Services, "King County and WSDOT Traffic Cameras"). The `outFields` list is explicit on purpose: the layer also carries asset-administration columns — including staff names — that are never fetched. Only live, active cameras with frames on the county's own `info.kingcounty.gov` image handler are registered (the feed writes `http://`; the handler serves HTTPS, so URLs are upgraded and pinned before registration). WSDOT-owned rows in the layer are skipped because their frames are WSDOT-hosted, outside the pinned image origin; partner-city cameras hosted on the county image handler (e.g. Newcastle) name their owner as the per-camera credit. The layer publishes no facing, so headings use the shared id-hash fallback at low confidence. Uniquely, the county publishes each camera's hardware `Manufacturer`/`Model` (Cohu 3950/3965, Bosch AUTODOME, Axis PTZ domes); both are carried on the source (and served by `/api/cctv/sources`) as `model` and `manufacturer` for identified-hardware consumers (vendor-generic strings such as `PTZ` name no model and are omitted). Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_KINGCOUNTY_ENABLED=0`.
- **WSDOT highway cameras.** Keyless. The camera list is the Esri JSON layer `data.wsdot.wa.gov/travelcenter/Cameras.json` — the same layer WSDOT's own Travel Center map consumes (~1,700 point features, EPSG:3857 geometry converted to WGS84 on load; the body carries Windows-1252 bytes and is decoded as such). Only frames on WSDOT's own `images.wsdot.wa.gov` host are registered — the catalog also lists ~70 partner cameras (Oregon DOT, City of Seattle, lodges, airports) whose own terms apply, and those are skipped rather than proxied. WSDOT's layer metadata marks the feed for "low volume" use (see WSDOT's [travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer)). The catalog is fetched once per CCTV catalog refresh (every 15 minutes), and a camera's frame is fetched only when that camera is viewed; frames are never stored or redistributed. The live feed's `CompassDirection` is a single cardinal (N/E/S/W), `B` (both directions — most rows), `O`, or null. A single cardinal gives a high-confidence heading (the diagonals NE/SE/SW/NW are mapped too should they appear); `B`, `O`, null, and any other code carry no single facing and use the shared id-hash fallback at low confidence. By default the 250 cameras nearest Seattle and Spokane load; `CCTV_WSDOT_MAX_SOURCES` changes the cap (8–1,200) and `CCTV_WSDOT_ENABLED=0` turns the pack off. A keyed WSDOT Traveler Information API serves the same population for higher-volume use and is deliberately not required here. - **WSDOT highway cameras.** Keyless. The camera list is the Esri JSON layer `data.wsdot.wa.gov/travelcenter/Cameras.json` — the same layer WSDOT's own Travel Center map consumes (~1,700 point features, EPSG:3857 geometry converted to WGS84 on load; the body carries Windows-1252 bytes and is decoded as such). Only frames on WSDOT's own `images.wsdot.wa.gov` host are registered — the catalog also lists ~70 partner cameras (Oregon DOT, City of Seattle, lodges, airports) whose own terms apply, and those are skipped rather than proxied. WSDOT's layer metadata marks the feed for "low volume" use (see WSDOT's [travel information disclaimer](https://wsdot.wa.gov/about/policies/travel-information-disclaimer)). The catalog is fetched once per CCTV catalog refresh (every 15 minutes), and a camera's frame is fetched only when that camera is viewed; frames are never stored or redistributed. The live feed's `CompassDirection` is a single cardinal (N/E/S/W), `B` (both directions — most rows), `O`, or null. A single cardinal gives a high-confidence heading (the diagonals NE/SE/SW/NW are mapped too should they appear); `B`, `O`, null, and any other code carry no single facing and use the shared id-hash fallback at low confidence. By default the 250 cameras nearest Seattle and Spokane load; `CCTV_WSDOT_MAX_SOURCES` changes the cap (8–1,200) and `CCTV_WSDOT_ENABLED=0` turns the pack off. A keyed WSDOT Traveler Information API serves the same population for higher-volume use and is deliberately not required here.
- **Hong Kong Transport Department traffic snapshot cameras.** Keyless. The English camera list is the public DATA.GOV.HK XML at `static.data.gov.hk/td/traffic-snapshot-images/code/Traffic_Camera_Locations_En.xml`; frames are stills on `tdcctv.data.one.gov.hk`, and only that host is registered. Frame URLs are rebuilt from each camera key (`https://tdcctv.data.one.gov.hk/{KEY}.JPG`) rather than taken verbatim from the catalog. Stills were probed to answer directly on that origin with no redirect hop. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. By default nearly the full catalog loads (~1,013; pack cap 1,100), prioritized nearest Central, Tsim Sha Tsui, Sha Tin, Tsuen Wan, Tai Po, Fanling, Tuen Mun, Yuen Long and Tseung Kwan O so a lowered cap still spans Hong Kong Island, Kowloon and the New Territories. When the sum of packs exceeds the catalog-wide ceiling, shared round-robin keeps every lane represented. `CCTV_HK_MAX_SOURCES` (8–1200) changes the cap and `CCTV_HK_ENABLED=0` turns the pack off. The DATA.GOV.HK Terms of Use require attribution to the Government / Transport Department / DATA.GOV.HK.
- **Statens vegvesen road cameras.** Keyless. The camera list is one GeoJSON request to the OGC API Features view of the official DATEX 3.1 CCTV site table (`ogckart-sn1.atlas.vegvesen.no/ogc/features/v1/collections/datex_3_1:CctvSimple/items`), so no DATEX account is needed; frames are stills on `kamera.atlas.vegvesen.no/api/images/<cameraId>`, and only that exact path per camera is registered. Cameras the feed reports as faulty are dropped. About 135 working cameras also publish live HLS (`kamera.vegvesen.no/public/<cameraId>/manifest.m3u8`, MPEG-TS); those play as live video through the bounded in-memory HLS relay, with the still as the snapshot fallback, and only that exact manifest path per camera is registered. `CCTV_VEGVESEN_VIDEO=0` keeps every camera on stills. `orientationDescription` names the place a camera faces, not a bearing, so it goes into the label and headings use the id-hash fallback at low confidence. By default every live camera loads (~850); `CCTV_VEGVESEN_MAX_SOURCES` (8–1000) lowers the cap, keeping the cameras nearest Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Bodø and Tromsø and `CCTV_VEGVESEN_ENABLED=0` turns the pack off. Frames are fetched at request time and never stored or redistributed. The NLOD attribution is registered in the Data attribution popover. - **Statens vegvesen road cameras.** Keyless. The camera list is one GeoJSON request to the OGC API Features view of the official DATEX 3.1 CCTV site table (`ogckart-sn1.atlas.vegvesen.no/ogc/features/v1/collections/datex_3_1:CctvSimple/items`), so no DATEX account is needed; frames are stills on `kamera.atlas.vegvesen.no/api/images/<cameraId>`, and only that exact path per camera is registered. Cameras the feed reports as faulty are dropped. About 135 working cameras also publish live HLS (`kamera.vegvesen.no/public/<cameraId>/manifest.m3u8`, MPEG-TS); those play as live video through the bounded in-memory HLS relay, with the still as the snapshot fallback, and only that exact manifest path per camera is registered. `CCTV_VEGVESEN_VIDEO=0` keeps every camera on stills. `orientationDescription` names the place a camera faces, not a bearing, so it goes into the label and headings use the id-hash fallback at low confidence. By default every live camera loads (~850); `CCTV_VEGVESEN_MAX_SOURCES` (8–1000) lowers the cap, keeping the cameras nearest Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Bodø and Tromsø and `CCTV_VEGVESEN_ENABLED=0` turns the pack off. Frames are fetched at request time and never stored or redistributed. The NLOD attribution is registered in the Data attribution popover.
- **Kartverket ground heights for Statens vegvesen cameras.** The camera feed's points are 2D, so the loader asks Kartverket's keyless point-height API (`ws.geonorge.no/hoydedata/v1/punkt`, CC BY 4.0) for the terrain height at each camera. Requests carry 20 points: the API accepts 50, but above ~20 it answers the extra points from contour lines (`hoydekurver`, metres to ~20 m off) or not at all. Eight requests run at a time, about 36 for the whole country: a cold lookup took 6–13 s in testing (single requests 0.6–9.5 s). Answers are matched by the coordinates the API echoes and recorded only for points that request asked about. Over water the API returns the sea-floor depth (`dybdekurver` or `Havflate`), which is replaced by 0 m, the water surface; for the ~14 bridge cameras that is below the deck, but much closer than the sea floor or the flat prior. Heights are cached in memory by position for the life of the server, and points with no height (a few ferry quays and bridges, or a point a 200 answer leaves out) for 6 h, so the 15-minute catalog refresh only asks about new or moved cameras. The first failing request (a 408, 429 or 5xx, a network error, a request over 10 s, or an unreadable or oversized body) stops the lookup, with no retries, and no new lookup starts until the backoff ends (Retry-After when sent, else 30 min, longer than the refresh; bounded to 1 min–1 h). Any other 4xx marks that request's points as having no height and the lookup carries on. The whole lookup has a 30 s deadline; a lookup cut short by it resumes on the next refresh without a backoff. The lane waits at most 12 s, counted from the start of the loader, and only when more than 10% of the cameras have no answer yet; a few new cameras or expired misses are looked up in the background. A slower lookup keeps filling the cache, and the cameras it had not reached keep the flat prior until the next 15-minute refresh (about 190 of 865 on one slow first run). Only coordinates are sent, with the same User-Agent as the other CCTV requests. `CCTV_VEGVESEN_HEIGHTS=0` turns the lookup off. The Kartverket credit, with a note that heights over water are set to 0 m and heights are rounded to 0.1 m, is shown beside the Statens vegvesen entry in the Data attribution popover.
- **NYC DOT Traffic Management Center cameras.** Off by default. NYC DOT's [developer data feeds page](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) asks developers who want the camera feed to contact `[email protected]` and sign a data-sharing agreement. This project does not hold one that covers downstream installations, so the pack loads only when an operator who holds their own agreement sets `CCTV_NYC_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to NYC DOT. The endpoint needs no key. The camera list is the public `webcams.nyctmc.org/api/cameras` catalog (~980 cameras across the five boroughs); frames are stills at `webcams.nyctmc.org/api/cameras/<uuid>/image`, synthesized from a validated UUID rather than taken from the payload, and only that host is registered. Cameras the feed reports as offline are dropped. The catalog publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. Once enabled, the 250 cameras nearest the borough cores load; `CCTV_NYC_MAX_SOURCES` (8–400) changes the cap. Frames are fetched at request time and never stored or redistributed. NYC DOT asks every application that uses its data to carry its disclaimer; it is registered verbatim in the Data attribution popover. - **NYC DOT Traffic Management Center cameras.** Off by default. NYC DOT's [developer data feeds page](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) asks developers who want the camera feed to contact `[email protected]` and sign a data-sharing agreement. This project does not hold one that covers downstream installations, so the pack loads only when an operator who holds their own agreement sets `CCTV_NYC_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to NYC DOT. The endpoint needs no key. The camera list is the public `webcams.nyctmc.org/api/cameras` catalog (~980 cameras across the five boroughs); frames are stills at `webcams.nyctmc.org/api/cameras/<uuid>/image`, synthesized from a validated UUID rather than taken from the payload, and only that host is registered. Cameras the feed reports as offline are dropped. The catalog publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. Once enabled, the 250 cameras nearest the borough cores load; `CCTV_NYC_MAX_SOURCES` (8–400) changes the cap. Frames are fetched at request time and never stored or redistributed. NYC DOT asks every application that uses its data to carry its disclaimer; it is registered verbatim in the Data attribution popover.
- **City of Toronto RESCU cameras.** Keyless. The camera list is the City's public `tmcearthcameras.json` on `opendata.toronto.ca` (dataset "Traffic Cameras", Transportation Services), served as JSONP and unwrapped with an anchored pattern. This is the municipal network the Ontario 511 pack does not carry: downtown arterials plus the Gardiner, DVP, Allen and Lake Shore. The list publishes no frame URL, so frame URLs are BUILT from the documented `CameraImages/loc####.jpg` convention and a strictly-digits camera number, pinning the frame proxy to the portal origin by construction; the list fetch refuses redirects and bounds the body it buffers. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `D1`-`D4` fields are the directions of the *comparison* images (static reference stills captured in 2016 under a different path), not a bearing for the live pan-tilt-zoom frame, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. A camera that is temporarily out of service still answers 200 with a byte-identical "Image Unavailable" placeholder rather than an error (about 6% of the network at any moment), so such a camera reads as healthy; the frame it shows is the agency's, not a synthesized one. The licence requires the attribution statement above. Disable with `CCTV_TORONTO_ENABLED=0`. - **City of Toronto RESCU cameras.** Keyless. The camera list is the City's public `tmcearthcameras.json` on `opendata.toronto.ca` (dataset "Traffic Cameras", Transportation Services), served as JSONP and unwrapped with an anchored pattern. This is the municipal network the Ontario 511 pack does not carry: downtown arterials plus the Gardiner, DVP, Allen and Lake Shore. The list publishes no frame URL, so frame URLs are BUILT from the documented `CameraImages/loc####.jpg` convention and a strictly-digits camera number, pinning the frame proxy to the portal origin by construction; the list fetch refuses redirects and bounds the body it buffers. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `D1`-`D4` fields are the directions of the *comparison* images (static reference stills captured in 2016 under a different path), not a bearing for the live pan-tilt-zoom frame, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. A camera that is temporarily out of service still answers 200 with a byte-identical "Image Unavailable" placeholder rather than an error (about 6% of the network at any moment), so such a camera reads as healthy; the frame it shows is the agency's, not a synthesized one. The licence requires the attribution statement above. Disable with `CCTV_TORONTO_ENABLED=0`.
- **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals.
+19 -12
View File
@@ -66,6 +66,7 @@ Start with the included data sources, then add your own. Each layer is a separat
- **🎖️ Military HUD:** Tactical heads-up display with intelligence-style telemetry. - **🎖️ Military HUD:** Tactical heads-up display with intelligence-style telemetry.
- **🌐 Global Context:** Stage the full situational picture with one switch — and get your exact view back when you leave. - **🌐 Global Context:** Stage the full situational picture with one switch — and get your exact view back when you leave.
- **🎥 Scene director:** Capture cinematic camera tours for clips and demos. - **🎥 Scene director:** Capture cinematic camera tours for clips and demos.
- **📱 Phone virtual camera:** Scan a QR code and your phone becomes the camera — walk the room at 1:1, or set 1:1000 and one step crosses the city. Focal length, depth of field and recorded takes that land in the scene editor ([docs/VCAM.md](docs/VCAM.md)).
- **🔗 Share Links:** Camera, style, layers, and even one tracked target serialize into a URL — a live target is a handoff, not a bookmark. - **🔗 Share Links:** Camera, style, layers, and even one tracked target serialize into a URL — a live target is a handoff, not a bookmark.
- **🏠 Reset Globe:** One control — or one sentence — back to the full Earth. - **🏠 Reset Globe:** One control — or one sentence — back to the full Earth.
- **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC cyclone tracks. No key needed. - **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC cyclone tracks. No key needed.
@@ -307,12 +308,20 @@ _Why cockpit mode exists: you're riding a real aircraft over real terrain — an
--- ---
## 📱 Phone Virtual Camera
> Frame the shot with your hands, like a virtual-production VCAM.
Open **SCENES › VCAM** and scan the code with a phone on the same Wi-Fi. The phone shows the globe as a monitor and becomes the camera: on Android Chrome it tracks position and rotation through WebXR AR, and on iPhone Safari it tracks rotation while two thumb sticks dolly, truck, crane and pan. The motion scale sets the world under you, from 1:1 street level through 1:100 drone to 1:10000 orbit, and changing it never makes the camera jump.
Dial in a focal length from 12 to 400 mm, turn on depth of field and tap the picture to focus. Distances are scaled with the rig, so at 1:1000 the city falls out of focus like a tabletop miniature. Press **REC** and the move becomes a take: a shot in the selected scene, with every sample's position, orientation and focal length, which replays, seeks and retimes like any other.
Nothing extra is exposed by default: pairing starts a separate HTTPS listener that serves only the phone page and its relay, never the app or its keys. See [docs/VCAM.md](docs/VCAM.md) for trusting the local certificate on iPhone and for the protocol.
---
## 🎙️ Talk to It ## 🎙️ Talk to It
The standalone app offers **OpenAI** and **Gemini** in the GEV MIC provider chooser. OpenAI is the initial default; your choice is saved in this browser. To use Gemini, add `GEMINI_API_KEY` in Provider Settings or your local `.env` file, then select Gemini. `GEMINI_LIVE_MODEL` defaults to `gemini-3.8-live`. The permanent key stays on the local server, which issues a constrained, single-use session credential.
Changing provider ends the current conversation. If voice is on, the new provider starts with the same open-mic or push-to-talk mode; a held Space key is not carried over. Gemini uses the same map actions and captions, but has no OpenAI cost meter or MINI tier. When Gemini reports that its session has expired, start voice again for a new conversation. The provider chooser does not change the OpenAI-backed AI HUD summary.
> Voice can use an **OpenAI API key** or, on the same machine, an opt-in signed-in **ChatGPT/Codex OAuth** session. The API-key path remains the default. Selecting ChatGPT OAuth in Provider Settings reuses an existing local sign-in or starts the Codex browser sign-in flow and selects OAuth when it completes. The OpenAI key still drives the **AI HUD summary**: a terse, five-word intelligence-style readout of the current view that regenerates as you move. > Voice can use an **OpenAI API key** or, on the same machine, an opt-in signed-in **ChatGPT/Codex OAuth** session. The API-key path remains the default. Selecting ChatGPT OAuth in Provider Settings reuses an existing local sign-in or starts the Codex browser sign-in flow and selects OAuth when it completes. The OpenAI key still drives the **AI HUD summary**: a terse, five-word intelligence-style readout of the current view that regenerates as you move.
The OAuth option is experimental. OpenAI documents ChatGPT plan usage for the [Responses API](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference); a supported third-party Realtime contract for reusing Codex tokens has not been confirmed. A successful token mint does not establish billing or support terms. The OAuth option is experimental. OpenAI documents ChatGPT plan usage for the [Responses API](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference); a supported third-party Realtime contract for reusing Codex tokens has not been confirmed. A successful token mint does not establish billing or support terms.
@@ -381,15 +390,15 @@ Twenty layers and map sources. **Eighteen have a keyless path.** Some offer addi
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 | | 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
| ◍ **Air quality** | Live AQHI on the published 1–10+ health-risk scale, with a Weather-panel card showing the band legend and the highest readings in view. **Canada only** — ECCC is the first registered provider | ECCC MSC GeoMet | 🟢 | | ◍ **Air quality** | Live AQHI on the published 1–10+ health-risk scale, with a Weather-panel card showing the band legend and the highest readings in view. **Canada only** — ECCC is the first registered provider | ECCC MSC GeoMet | 🟢 |
| 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds | | 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds |
| 📹 **CCTV Mesh** | ~4,000 public cameras (shared cap) projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511, free developer key) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen) · Toronto · King County (WA) · Washington (WSDOT) · Catalonia (Servei Català de Trànsit) · Hong Kong (Transport Department) · Taiwan (Freeway Bureau, MOTC), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement), opt-in Lithuania (Via Lietuva / Eismoinfo, photo licence unconfirmed) and opt-in Florida (FL511, individual personal use only; other use needs FDOT's written consent). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 | | 📹 **CCTV Mesh** | ~4,000 public cameras (shared cap) projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen) · Toronto · King County (WA) · Washington (WSDOT) · Catalonia (Servei Català de Trànsit), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement) and opt-in Lithuania (Via Lietuva / Eismoinfo, photo licence unconfirmed). Positions are published; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 |
| 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 | | 📷 **Mapped ALPR Cameras** | License-plate-reader camera locations tagged by OpenStreetMap contributors, loaded one city-sized view at a time, with **SHOW NEAREST**. Locations and tags only: no plate data, no video | OpenStreetMap (incl. DeFlock mapping) | 🟢 |
| 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer with full-screen **EXPAND**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key | | 📷 **Street Level** | Street-level photos behind one panel, one chip per provider: coverage on the streets, image cones, an embedded viewer and **FOLLOW**. Mapillary, Google Street View, KartaView and Panoramax | Mapillary · Google · KartaView · Panoramax | 🟢 KartaView, Panoramax · 🟡 Mapillary token · 🔴 Google Maps key |
| 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 | | 📻 **Radio** | Geolocated world radio with an **analog tuner** — drag the needle across up to 750 stations and the globe flies to each broadcaster | Radio Browser / broadcasters | 🟢 |
| 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 | | 🚌 **Transit** | Live buses, trams, metros, trains and ferries with delayed playback between reports, selected-vehicle trails, and mode-coloured DETECT labels — Boston, Austin, Minneapolis, Helsinki, the Netherlands, Norway, South East Queensland, and nine in Ontario: Toronto (surface vehicles; the subway publishes no positions), Mississauga, Hamilton, Durham Region, York Region, Guelph, Burlington, Barrie and Kingston | Operator GTFS-Realtime feeds | 🟢 |
| 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 | | 🚲 **Bikeshare** | Live station availability | GBFS | 🟢 |
| 🧭 **Directions** | Click A and B on the globe for a street-following drive, walk or cycle route draped on the terrain with turn-by-turn steps — then FLY the camera along it. No key, no geocoder, no mic | OSRM on FOSSGIS servers (OpenStreetMap) | 🟢 | | 🧭 **Directions** | Click A and B on the globe for a street-following drive, walk or cycle route draped on the terrain with turn-by-turn steps — then FLY the camera along it. No key, no geocoder, no mic | OSRM on FOSSGIS servers (OpenStreetMap) | 🟢 |
| 🔥 **Active Fires** | Live NASA FIRMS detections, trailing 24h | NASA FIRMS | 🟡 | | 🔥 **Active Fires** | Live NASA FIRMS detections, trailing 24h | NASA FIRMS | 🟡 |
| 🚀 **Space Missions** | Rolling 30-day launches with payload, stage, and recovery detail | Launch Library 2 | 🟢 (🔴 optional paid token raises the allowance) | | 🚀 **Space Missions** | Rolling 30-day launches with payload, stage, and recovery detail | Launch Library 2 | 🟢 (🟡 optional token raises the allowance) |
| 🎖️ **Mapped Installations** | Viewport-bounded military-site context from community mapping — incomplete by nature, and labeled that way | OpenStreetMap | 🟢 | | 🎖️ **Mapped Installations** | Viewport-bounded military-site context from community mapping — incomplete by nature, and labeled that way | OpenStreetMap | 🟢 |
| 🌬️ **Wind** | Animated 10 m forecast wind with an optional speed, temperature or pressure color field and a reading at map center | NOAA GFS / ECMWF IFS | 🟢 | | 🌬️ **Wind** | Animated 10 m forecast wind with an optional speed, temperature or pressure color field and a reading at map center | NOAA GFS / ECMWF IFS | 🟢 |
| 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 | | 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 |
@@ -425,9 +434,9 @@ _The Space Missions layer replaying a Falcon 9 ascent — labeled `RECONSTRUCTED
**Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless. **Setup.** At [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), register an application with **Read** access and copy its **Client Token** (`MLY|…`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart. Without it the panel reads **KEY REQUIRED**. **Google Street View** uses `GOOGLE_MAPS_API_KEY` with the **Maps JavaScript API** enabled for it in Google Cloud; its chip starts off, since every panorama is billed to the key. **KartaView** and **Panoramax** need nothing: their public APIs are keyless.
**Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. Zoom in to street level (below 60 km) for the coverage lines; from orbit the panel says to zoom in. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary, KartaView and Panoramax; Street View panoramas are all 360°, so with Street View lit the filters are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it beside the SINCE value (ANY DATE (by upload date)); KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND** (full screen; Esc leaves) and **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo. **Use.** Turn on **Street Level** under DATA LAYERS → Cameras, or with the pill in the STREET LEVEL panel header. Each provider has a chip in its own colour (Mapillary green), and one is lit at a time: lighting one switches the others off. Mapillary, which is free, is lit by default. The **IMAGERY** (ALL / 360° / FLAT) and **SINCE** filters apply to Mapillary, KartaView and Panoramax; Street View panoramas are all 360°, so with Street View lit the filters and legend are hidden. Click a coverage line for its image cones and a cone to open the photo. Light **KARTAVIEW** (purple) and zoom in below about 6 km: its lines are the streets KartaView has photos of, and a click on one opens the photo nearest the click, flat or 360° (drag to look around), with cones along its drive; **‹ ›** or ← → step through the drive (Shift+← →, ↑ ↓ and + − look around a 360° photo; pinch zooms on a phone). Photos KartaView has archived are skipped, and where all are archived the panel says so. For KartaView, **SINCE** goes by upload date, as KartaView's own map does (it can filter by nothing else), and the panel notes it under the slider; KartaView filters its lines on its own server, and a filtered area KartaView has not drawn before can take several seconds, and the unfiltered lines show meanwhile. Light **PANORAMAX** (orange) for the open, federated commons (strongest in France and Belgium): from orbit its dots show where it has pictures, and below about 60 km its lines are sequences. A click on a line opens that sequence's picture nearest the click without moving the camera, flat or 360°, with cones along the sequence around it; **‹ ›** or ← → step through it, and both filters apply. Its caption names the picture's authors (or the instance holding it) and licence (mostly CC BY-SA 4.0; pictures on the IGN instance are Licence Ouverte 2.0). On the **Google 3D** map (Google's terms keep Street View off other maps, where it does not appear), light **GOOGLE STREET VIEW** and click a street from below 3 km, or press **OPEN STREET VIEW** for the view centre, to open Google's panorama there; step along its arrows. Above the photo: **EXPAND**, **FIT / FILL** (Mapillary, and flat KartaView and Panoramax photos), and **FOLLOW** (the globe camera follows the photo's view; Google 3D map only). The caption links to the image on the provider's site, and the globe credits each provider that is on ("© Mapillary contributors, CC BY-SA 4.0", "Street View imagery © Google", "© KartaView contributors, CC BY-SA 4.0", "© Panoramax contributors, licence per picture"). KartaView's own photo pages fail for signed-out visitors, so its link opens the full-size photo.
Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`. Drag the panel header to float the panel, and resize it from any edge. Double-click the header or collapse it to put it back in the rail. Share links carry the provider switches and filters (`0.m.0` Mapillary off, `0.m.0_0.r.google-1` Street View on, `0.m.0_0.r.google-0*kartaview-1*panoramax-0` KartaView on and `0.m.0_0.r.google-0*kartaview-0*panoramax-1` Panoramax on, as the app writes them (`0.m.0_0.r.kartaview-1` and `0.m.0_0.r.panoramax-1` work too; a link that leaves out `m` keeps Mapillary, the default, lit), `0.p.p` panoramas only, `0.s.365` the last year). To add a provider, implement the contract in `src/layers/streetLevel/registry.js` and register it in `src/app/layers/streetLevel.js`.
## 🎖️ Field Missions ## 🎖️ Field Missions
@@ -531,11 +540,9 @@ _What the TomTom key buys you: rush-hour density painted on the city — then di
| | Key | Why | Get it | | | Key | Why | Get it |
| --- | -------------------- | ------------------------------------------------------------- | -------------------------------------------------- | | --- | -------------------- | ------------------------------------------------------------- | -------------------------------------------------- |
| 🟡 | **OpenSky** | ✈️ More flight-polling credits (🟢 anonymous works without) | [opensky-network.org](https://opensky-network.org) | | 🟡 | **OpenSky** | ✈️ More flight-polling credits (🟢 anonymous works without) | [opensky-network.org](https://opensky-network.org) |
| 🔴 | **Launch Library 2** | 🚀 Optional paid token for higher limits (🟢 no key needed for public access) | [thespacedevs.com/supportus](https://thespacedevs.com/supportus) | | 🟡 | **Launch Library 2** | 🚀 Higher space-missions request allowance (🟢 works without) | [thespacedevs.com](https://thespacedevs.com) |
Add these if you need higher polling allowances. Add these if you need higher polling allowances.
Leave `LL2_API_TOKEN` blank for standard public access. LL2 tokens are optional
paid Patreon upgrades for higher limits; there is no free API-key signup.
`npm run doctor` reports Node/npm readiness, the primary provider routes, and `npm run doctor` reports Node/npm readiness, the primary provider routes, and
where each configured provider was found without printing credential values. where each configured provider was found without printing credential values.
+3 -2
View File
@@ -29,7 +29,7 @@ These are designed to be used directly in the browser (like a Mapbox public toke
1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers Street View (Maps JavaScript API; add it to the key's API restrictions). **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you. Restrict it to the **Map Tiles API and Maps JavaScript API only**: a referrer restriction applies to the Maps JavaScript API and the client SDKs, not to the web services, so a key carrying Geocoding under one is refused with `API keys with referer restrictions cannot be used with this API`. Search does not need it — geocoding goes through the server proxies above (#363). 1. **Google Maps API key** — loads Photorealistic 3D Tiles directly and powers Street View (Maps JavaScript API; add it to the key's API restrictions). **Restrict it** (HTTP referrer + API restriction to the required Google APIs) in the Google Cloud Console. An unrestricted key in a public deployment can be abused and billed to you. Restrict it to the **Map Tiles API and Maps JavaScript API only**: a referrer restriction applies to the Maps JavaScript API and the client SDKs, not to the web services, so a key carrying Geocoding under one is refused with `API keys with referer restrictions cannot be used with this API`. Search does not need it — geocoding goes through the server proxies above (#363).
2. **Cesium ion token** (`CESIUM_ION_TOKEN`, optional — for ion-hosted Google Photorealistic 3D Tiles, Bing world imagery, and world terrain) — used as `Cesium.Ion.defaultAccessToken` client-side. Use a public **`assets:read`** token with **URL restrictions** for any hosted deployment. The Community plan has eligibility and usage limits; a public token is not a secret, but it can still consume the account's quota. 2. **Cesium ion token** (`CESIUM_ION_TOKEN`, optional — for ion-hosted Google Photorealistic 3D Tiles, Bing world imagery, and world terrain) — used as `Cesium.Ion.defaultAccessToken` client-side. Use a public **`assets:read`** token with **URL restrictions** for any hosted deployment. The Community plan has eligibility and usage limits; a public token is not a secret, but it can still consume the account's quota.
3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy, which sends it only to `tiles.mapillary.com` over HTTPS (an upstream redirect is refused and answered 502, never followed) and caches tiles in memory only. Mapillary client tokens are meant for browser use. 3. **Mapillary client token** (`MAPILLARY_CLIENT_TOKEN`, optional, Street Level) — used by the MapillaryJS viewer and Graph API lookups in the browser, and by the server's coverage-tile proxy. Mapillary client tokens are meant for browser use.
> The explicit browser `define` block in `build/vite.js` controls exactly what reaches the client: only these three keys. Everything else stays server-side. > The explicit browser `define` block in `build/vite.js` controls exactly what reaches the client: only these three keys. Everything else stays server-side.
@@ -73,7 +73,7 @@ The data proxies under `server/providers/` are written so the browser cannot tur
- **Sanitized errors** — internal error details are not echoed back to clients. - **Sanitized errors** — internal error details are not echoed back to clients.
- **Coalesced OAuth refresh** and cached successful responses only (OpenSky). - **Coalesced OAuth refresh** and cached successful responses only (OpenSky).
- **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing. - **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing.
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, and `/api/tomtom/*`, backed by its persistent daily tile budget) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control. The keyless terrain route (`/api/terrain/heights`) uses the same cross-site checks, minus the forwarding-header refusal: it guards only the per-client quota and point cache, not a key or a bill, and the map needs it to render behind a reverse proxy. - **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, and `/api/tomtom/*`, backed by its persistent daily tile budget) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control.
- **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements. - **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements.
Allowing `maps.googleapis.com` in `script-src` also trusts its JSONP endpoints, which can bypass the script allowlist if an HTML-injection bug exists; this is an accepted limitation of loading the Maps JavaScript API, alongside the existing `'unsafe-eval'` allowance. Allowing `maps.googleapis.com` in `script-src` also trusts its JSONP endpoints, which can bypass the script allowlist if an HTML-injection bug exists; this is an accepted limitation of loading the Maps JavaScript API, alongside the existing `'unsafe-eval'` allowance.
@@ -86,6 +86,7 @@ The dev server is a **key broker**: every server-side key above is spendable by
- **Local-only by default.** `./scripts/dev-fresh.sh` (and the Vite config itself) bind to `localhost`, so only your machine can reach the server — and only local names are accepted (`allowedHosts` stays restricted, which also blunts DNS-rebinding tricks). Binding to all interfaces keeps that restriction: IP addresses and `localhost` work, and LAN hostnames must be listed in `GEV_ALLOWED_HOSTS` (for example `GEV_ALLOWED_HOSTS=globe.lan`); suffix and wildcard entries are ignored. - **Local-only by default.** `./scripts/dev-fresh.sh` (and the Vite config itself) bind to `localhost`, so only your machine can reach the server — and only local names are accepted (`allowedHosts` stays restricted, which also blunts DNS-rebinding tricks). Binding to all interfaces keeps that restriction: IP addresses and `localhost` work, and LAN hostnames must be listed in `GEV_ALLOWED_HOSTS` (for example `GEV_ALLOWED_HOSTS=globe.lan`); suffix and wildcard entries are ignored.
- **LAN exposure is an explicit opt-in**: `HOST=0.0.0.0 ./scripts/dev-fresh.sh`. The launcher prints a prominent warning plus your LAN URL. Understand what opting in means: **every device on that network can drive the proxies and spend your OpenAI / Google / OpenSky / AISStream / TomTom / FIRMS quota** for as long as the server runs. Do this only on networks you trust. - **LAN exposure is an explicit opt-in**: `HOST=0.0.0.0 ./scripts/dev-fresh.sh`. The launcher prints a prominent warning plus your LAN URL. Understand what opting in means: **every device on that network can drive the proxies and spend your OpenAI / Google / OpenSky / AISStream / TomTom / FIRMS quota** for as long as the server runs. Do this only on networks you trust.
- **The phone camera (SCENES › VCAM) opens a separate, narrow LAN listener — only on request.** Creating a pairing session (a loopback, same-origin request from the app, behind the same gate as `/mcp`) starts an HTTPS listener on `VCAM_PORT` (default `4174`, all interfaces unless `VCAM_HOST` narrows it); it stops two minutes after the last session ends. It serves only the static phone page, a local CA certificate download and the phone side of a relay: never the app, its provider proxies or any key, so pairing a phone does not amount to the `HOST=0.0.0.0` opt-in. A phone joins with the six-character code shown on the desktop (about 30 bits; eight wrong codes rotate it) and receives a per-phone key; the relay forwards bounded JSON (4 KiB, 120/s) and one newest JPEG preview frame, and WebSockets on both ends must come from their own page's origin. The listener answers only IP addresses, `localhost` and `GEV_ALLOWED_HOSTS` names. Its TLS certificate is issued by a CA created in `.gev-cache/vcam/` (private keys owner-only), constrained to server certificates (path length 0); a phone that installs and trusts it trusts certificates from this machine's CA, so remove the profile when you no longer need it. **Limit:** anyone on the network who reads the code off your screen can drive your camera and see its preview until you press END.
- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**. - **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**.
- **Docker trusts one address, and only because the port is on loopback.** - **Docker trusts one address, and only because the port is on loopback.**
Docker delivers the host's own browser to the container from the container Docker delivers the host's own browser to the container from the container
-12
View File
@@ -1,12 +0,0 @@
- `aircraft_in_area` and `vessels_in_area` take `group_by` and `stats`, so an
MCP client can ask which airlines, countries, aircraft types or ship types
dominate an area, or the average altitude or speed, over every match instead
of estimating from the returned rows. Airlines come from the ICAO designator
in each callsign (SWA1234 counts as SWA), so the breakdown works on feeds
that report no operator; operator and type are counted only where the feed
reports them. Ship types count by family, so AIS codes 70 to 79 are all
cargo; type 0 ("not available") and the reserved codes 100 to 255 count as
unknown. Altitude and speed stats cover airborne aircraft only, so parked
aircraft do not pull the means down. Every vessel answer, `find_vessel`
included, now reads AIS ship-type codes as their family and a destination
with no letters as unknown (quanticsoul4772, #1056).
@@ -1,5 +0,0 @@
- Share Launch Library request cache keys across installations refreshing in the
same UTC minute, identify the app to the provider, and explain that standard
space-missions access needs no key. Optional higher-rate LL2 tokens are paid
upgrades; existing local cache and server-only token handling are unchanged
(rudycelekli, #1197).
@@ -1,3 +0,0 @@
- Keep Space Missions marked STALE when Launch Library 2 falls back to cached
launch data, and return to NOMINAL after a fresh response without discarding
retained missions (rudycelekli, #1199).
-5
View File
@@ -1,5 +0,0 @@
- Color CCTV cameras with a video feed violet. Cameras with an HLS, MP4 or
WebM feed were the same cyan as stills, so a DelDOT or Statens vegvesen
video camera could only be found by opening it. Stills stay cyan and the
active camera stays amber, and focus de-emphasis fades the violet the same
way (Danielslay86, #1200).
-4
View File
@@ -1,4 +0,0 @@
- Draw CCTV stills at their source aspect on the monitor plane instead of
stretching them to the 16:9 canvas. Most DOT cameras publish 4:3 frames, so
every still was widened; they are now centered and pillarboxed on the dark
the placeholder already ends on (Danielslay86, #1201).
-3
View File
@@ -1,3 +0,0 @@
- Report actual outcomes when voice enables or disables CCTV through the shared
layer lifecycle, including failed and cancelled changes (manjunath22466,
#1205).
-3
View File
@@ -1,3 +0,0 @@
- Avoid starting or queuing a reply when the local channel rejects a typed OpenAI
command, while preserving an earlier accepted deferred input
(Manjunath, #1220).
-4
View File
@@ -1,4 +0,0 @@
- Load Ontario 511 cameras again. 511on.ca's camera endpoint now requires a
free developer key; set `ONTARIO_511_API_KEY` to enable the pack, which is
otherwise skipped with one log line saying where to get a key
(quanticsoul4772, #1228).
@@ -1,4 +0,0 @@
- Harden the Tarktee (Estonia) DATEX2 camera catalog fetches: refuse redirects,
cancel both response streams when either response fails or overflows the 4 MB
byte cap, and deduplicate camera IDs before per-pack prioritization
(yaka0007, #1233).
@@ -1,5 +0,0 @@
- Serve the camera catalog while it refreshes. An expired catalog made every
camera request wait for the slowest pack to reload; it is now answered at
once while one background refresh runs, so only the first load waits. Estonia's
slow Tarktee feeds get 30 s instead of 15 s, so the pack no longer drops out
on about a third of loads (quanticsoul4772, #1234).
-3
View File
@@ -1,3 +0,0 @@
- Require a geocoded containment anchor for ambiguous analyst region names,
preserve boundary provenance and cancellation safety, and retain exact-name
precedence for natural outlines (manjunath22466, #1235).
-4
View File
@@ -1,4 +0,0 @@
- Add Taiwan's national freeway cameras from the Freeway Bureau, MOTC to CCTV:
~1,800 cameras read at runtime from the official MOTC 2.0 open-data table,
with on-demand snapshots and attribution. No API key is required; set
`CCTV_TAIWAN_ENABLED=0` to skip it (419vive, #1237).
@@ -1,3 +0,0 @@
- Gate CCTV HLS media requests before session work, bind leases to the direct
peer, and bound per-peer leases across shared sessions (asturksever, #1267).
- Keep headful CCTV QA rendering active when its window is occluded (asturksever, #1267).
@@ -1,3 +0,0 @@
- Report cached CelesTrak satellite records as stale in the Data Layers row,
preserving separate core and dense catalog provenance through refresh,
removal and lifecycle cleanup (rudycelekli, #1283).
@@ -1,3 +0,0 @@
- Keep aircraft route labels on the scheduled airport leg instead of accepting
its distant great-circle extensions, preserving generous endpoint tolerance
across the signed-angle branch cut (rudycelekli, #1284).
-4
View File
@@ -1,4 +0,0 @@
- The Street Level SINCE note sits on the value's line, in its type and a
size smaller: with KartaView lit it reads ANY DATE (by upload date). It
had lost its size variable in the Street Level slim-down and rendered
larger than the value, on a line of its own (asturksever, #1286).
-3
View File
@@ -1,3 +0,0 @@
- Give ordinary sliders a shared native control and consistent track, thumb,
value, focus and disabled styling while preserving feature behavior and
specialized controls (mazy1998, #1287).
@@ -1,5 +0,0 @@
- Unify segmented selectors for model coverage, detection allocation, drawing
shape, Street View and imagery comparison while preserving their existing
behavior. Keep compact labels such as FILL and FLAT on one line, and let
collapsed Weather release space to the open rail panel. Reserve the full mode
button height in Recent Imagery so keyboard focus is not clipped (mazy1998, #1301).
-9
View File
@@ -1,9 +0,0 @@
- Add FL511 (Florida DOT) traffic cameras as an opt-in CCTV source pack:
the statewide ArcGIS catalog, read a page at a time under a byte cap with
redirects refused, and frames pinned to FL511's two image hosts over HTTPS.
FL511's terms limit its content to individual, personal use, and any other
use (a public deployment included) needs FDOT's express written consent, so
the pack stays off unless `CCTV_FLORIDA_ENABLED=1`. Headings come from the
catalog's direction codes, and camera ids come from the image channel, since
the catalog's ID column repeats across regions. `CCTV_FLORIDA_MAX_SOURCES`
sets the cap (Danielslay86, #605).
@@ -1,9 +0,0 @@
- Bound what a caller can grow through `/api/terrain/heights`. Every distinct
5-decimal point was a permanent in-memory entry, a permanent line in an
uncapped `.gev-cache/terrain-heights.json`, and a live upstream call, with
nothing limiting the rate. The point cache now holds at most 50,000 entries
and evicts oldest-first, a cache file above
24 MB is not read back, and the route is limited to 90 requests/minute per
client (270 global). Evicting a point costs one refetch, never a wrong
answer, since terrain does not move. Ordinary use is unaffected: a full
`test:track` run drives 10 requests, peaking at 8/min (daikaginza, #686).
@@ -1,7 +0,0 @@
- Close the compact Radio disclosure when an adaptive tactical right-rail
restore directly expands Context, before Space Missions can be covered.
A repeated Context-open request also clears stale disclosure state.
Real PanelChrome constructor wiring and the rail reflow path are covered
by focused regressions. Credits: kvnloo (#816), raysung-2026's original
#804 report, asturksever's review, and quanticsoul4772's independent
Windows diagnosis.
-4
View File
@@ -1,4 +0,0 @@
- Add optional Gemini Live voice to the standalone app, with a provider chooser,
server-held API key, microphone streaming, shared map actions and captions.
Switching providers ends the old conversation and preserves the input mode
(Manjunath, #872).
-6
View File
@@ -1,6 +0,0 @@
- Extract a reusable model-free World Packet from the existing voice
`get_current_view_state` owner without restoring disabled layers to the
model context. Keep the enabled-only payload, disabled-layer count, source
provenance, action result and view-state contract; read the layer roster once
per packet; voice retains the speech/card envelope at its own boundary.
Credits: original GEV voice/layer contributors and #880 implementation.
@@ -1,17 +0,0 @@
- Give each Statens vegvesen camera its own ground height from Kartverket's
keyless point-height API (CC BY 4.0) instead of one flat 150 m prior, so
mountain-pass cameras no longer sit hundreds of metres below the terrain
where neither the point-height prior nor the ground snap resolves. About 850
of ~855 cameras get a height; the rest keep the old prior. Requests carry 20
points, the most the API answers from its 1 m terrain model, eight at a
time; a cold lookup takes about 6–13 s. Cameras over water use the water
surface rather than the sea-floor depth the API returns there; for bridge
cameras that is still below the deck. Heights are cached for good and misses
for 6 h, so a refresh only asks about new or moved cameras. After a
failing request (a 408, 429 or 5xx, a network error, a request over 10 s or
an unreadable body) the lookup stops and backs off (Retry-After, else
30 min, longer than the refresh). The lane waits at most 12 s from its
start, and only on a cold cache; a slower first lookup leaves the cameras it
had not reached on the flat prior until the next 15-minute refresh, and
keeps filling the cache meanwhile.
`CCTV_VEGVESEN_HEIGHTS=0` turns it off. Follow-up to #929 (trygvehhh, #945).
-6
View File
@@ -1,6 +0,0 @@
- Street Level is rebuilt around one small provider registry: Mapillary,
KartaView, Panoramax and Google Street View share one coverage drawer and
one photo viewer, one source lit at a time. Floating and docked panels,
FOLLOW, surface modes, the legend and the Mapillary proxy's disk cache are
gone; `.gev-cache/mapillary/` from earlier runs is no longer read and can be
deleted (gekh, #974).
@@ -1,8 +0,0 @@
- Cross-site pages can no longer fill the terrain-height cache or spend the
visitor's own `/api/terrain/heights` rate-limit quota through the visitor's
browser. The route refuses a cross-site `Sec-Fetch-Site` or a foreign or
opaque `Origin` before rate limiting, cache access or upstream work. Unlike
the cost-bearing routes it still answers same-origin requests that arrive
through a reverse proxy, so terrain keeps rendering behind nginx, Caddy or
Cloudflare instead of falling back to the geoid (Sunil56224972, daikaginza,
#975).
-7
View File
@@ -1,7 +0,0 @@
- Add Hong Kong Transport Department traffic snapshot cameras as a keyless CCTV
source pack: the public DATA.GOV.HK English locations XML, frames pinned to
`tdcctv.data.one.gov.hk`, with DATA.GOV.HK Terms of Use attribution. By
default nearly the full TD catalog (~1,013 cameras; cap 1,100) loads,
prioritized across Hong Kong Island, Kowloon and the New Territories. Headings
use the shared id-hash fallback at low confidence. `CCTV_HK_MAX_SOURCES` sets
the cap (8–1,200) and `CCTV_HK_ENABLED=0` turns the pack off (JCY2515, #990).
+2 -2
View File
@@ -356,8 +356,8 @@ drag or final change. Feature adapters own data mapping and service subscription
generic modules own DOM/listeners/timers and release them in `destroy()`. generic modules own DOM/listeners/timers and release them in `destroy()`.
Keep persistence with panel chrome: collapse uses Keep persistence with panel chrome: collapse uses
`godsEyeView.v6.panelCollapsed.<panelId>`, positions are `godsEyeView.v6.panelCollapsed.<panelId>`, position uses
not stored (`godsEyeView.v8.panelPos.<panelId>` stays reserved), and share state uses the registered panel id. `godsEyeView.v8.panelPos.<panelId>`, and share state uses the registered panel id.
Do not rename existing Do not rename existing
ids or reset persistence versions when adding a body. The WEATHER adapter is ids or reset persistence versions when adding a body. The WEATHER adapter is
`src/ui/weatherPanel.js`; its observed-history selection remains transient. `src/ui/weatherPanel.js`; its observed-history selection remains transient.
+94 -218
View File
@@ -1,21 +1,5 @@
# God's Eye View Current State # God's Eye View Current State
Analyst region queries resolve unique Natural Earth names offline without
geocoding, so Gold Coast and Ivory Coast name the West African natural regions.
Duplicate names require a geocoded containment anchor; when several entries for
the same name contain that anchor, the lookup stays unresolved rather than
selecting the largest entry. Natural outlines try exact names before aliases and
broader suffix variants. Follow-ups retain boundary provenance, and cancelled
lookups preserve the previous analyst cohort and boundary source. Navigation
search keeps a successful geocode, with no search or view-based region recovery.
CCTV live-media requests are same-site gated before catalog or media work, including
HLS renewal, segment reads and DELETE cleanup. HLS leases belong to their socket
peer (IPv4-mapped IPv6 is normalized), with eight leases per peer across the two
global sessions. Peers behind the same NAT share that budget; this is resource
admission, not authentication. Native same-origin video and range requests remain
supported.
Shared distance checks use `src/geoDistance.js` with `{ lat, lon }` points and Shared distance checks use `src/geoDistance.js` with `{ lat, lon }` points and
the IUGG mean spherical Earth radius, 6371.0088 km. `greatCircleKm` is the IUGG mean spherical Earth radius, 6371.0088 km. `greatCircleKm` is
canonical; `greatCircleMeters` is its exact metre conversion. Missing, canonical; `greatCircleMeters` is its exact metre conversion. Missing,
@@ -128,14 +112,7 @@ perimeters, terrain height, military installations and map features, plus a
combined situation brief, military awareness around a point, the app's heads-up display caption, and a link that combined situation brief, military awareness around a point, the app's heads-up display caption, and a link that
opens the app over an area. Tools reuse the layers' portable source factories, take a opens the app over an area. Tools reuse the layers' portable source factories, take a
shared `area` argument (place name, bounding box, or point and radius) and cap shared `area` argument (place name, bounding box, or point and radius) and cap
lists at 25 rows by default. `aircraft_in_area` and `vessels_in_area` can also lists at 25 rows by default. Voice offers the same queries next to its app
count every match by a field (`group_by`: airline, read from the ICAO
designator in the callsign, or operator, country or type for aircraft; type or
destination for ships; the ten largest groups, then other and unknown counts;
the summary says when a feed reports none of the field) and summarize airborne
altitude and speed (`stats`: count, min, median, mean, max).
Both cover all matches, not just the rows returned; voice leaves these two
tools out, so they reach MCP clients only. Voice offers the same queries next to its app
actions: the session lists them, and the browser runs them through the same actions: the session lists them, and the browser runs them through the same
catalog, loaded on first use. See [tools and the MCP server](TOOLS.md). catalog, loaded on first use. See [tools and the MCP server](TOOLS.md).
Aircraft altitude-band queries require a reported barometric or geometric altitude Aircraft altitude-band queries require a reported barometric or geometric altitude
@@ -452,6 +429,20 @@ or unknown freshness and transport failures retain their warnings. Partial
snapshots still retain missing contacts within the existing age and row limits. snapshots still retain missing contacts within the existing age and row limits.
A complete successful snapshot clears the partial indicator. A complete successful snapshot clears the partial indicator.
SCENES › VCAM pairs a phone on the same network as a virtual camera. Opening
the card creates a loopback-only session and starts a separate HTTPS phone
listener (`VCAM_PORT`, default 4174) that serves only the phone page and relay;
END, or two minutes after the last session, stops it. Android Chrome tracks
6DoF through WebXR `immersive-ar`; iPhone Safari tracks rotation through
DeviceOrientation with on-screen sticks, falling back from WebSocket to HTTPS
requests under an untrusted certificate. The rig claims the camera through the
navigation seam (Cockpit refuses it) and holds on any other navigation, scene
run or globe pointer input. Motion scale, smoothing, height and horizon locks,
focal length and scale-aware depth of field are shared by phone and card. REC
writes version-7 track shots (`move.track`, up to 10,000 samples with focal
length) into the selected scene; shots may also carry a `lens`. See
[VCAM](VCAM.md); gate: `node scripts/qa-vcam.mjs`.
Director imports now open a non-mutating preview before Apply. EDIT DETAILS Director imports now open a non-mutating preview before Apply. EDIT DETAILS
authors validated anchor, camera, pack and interaction drafts; SHARE SCENE exports authors validated anchor, camera, pack and interaction drafts; SHARE SCENE exports
a selected scene or a bounded bundle of explicitly chosen pack files. Bundled a selected scene or a bounded bundle of explicitly chosen pack files. Bundled
@@ -512,11 +503,6 @@ to layer toggles, fly_to_location, frame_overhead, select_nearest_aircraft,
get_entity_context, annotate_map and analyst_query. Analyst speech and the card get_entity_context, annotate_map and analyst_query. Analyst speech and the card
share one deterministic count/scope headline; lower bounds use "At least" and share one deterministic count/scope headline; lower bounds use "At least" and
partial answers name the unanswered layers. `get_current_view_state` lists enabled layers only. partial answers name the unanswered layers. `get_current_view_state` lists enabled layers only.
The model-free `gods-eye-view/agent/world-packet` export exposes
`getWorldPacket({ viewer, styleManager, dataManager, sceneDirector })` to
non-voice consumers. It reads the same enabled-only state and feed
provenance before voice adds speech/card fields, with no new network requests
or mutations.
The voice card nested in the mic control (`voiceCard.js`) shows captions, plan The voice card nested in the mic control (`voiceCard.js`) shows captions, plan
steps and the result. `resultDisplay.js` is the one adapter from a result to steps and the result. `resultDisplay.js` is the one adapter from a result to
the card: builder results show as built, and analyst results show a title the card: builder results show as built, and analyst results show a title
@@ -634,20 +620,10 @@ Reference feed construction is exported through `sources/reference`; the cable s
Source factories have dedicated `layers/<family>/source` exports. ALPR and earthquake record normalization and CCTV source policy no longer pull rendering into source consumers. Catalog construction and voice feed reads use their focused owners; compatibility entries remain available. Settings filesystem hardening lives under `server/standalone/`. Import-direction checks complement export ownership checks; source behavior, settings policy and rendering are unchanged. Source factories have dedicated `layers/<family>/source` exports. ALPR and earthquake record normalization and CCTV source policy no longer pull rendering into source consumers. Catalog construction and voice feed reads use their focused owners; compatibility entries remain available. Settings filesystem hardening lives under `server/standalone/`. Import-direction checks complement export ownership checks; source behavior, settings policy and rendering are unchanged.
Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/progress/result, interruption, completion and turn-metrics events; stopping or replacing a session cancels pending actions. An active session's normal Stop publishes one idle transition, including adapters that emit their own terminal state; a restart triggered by that transition keeps ownership of its new startup state. Alternate adapters can use the same controls and action runner. Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/progress/result, interruption, completion and turn-metrics events; stopping or replacing a session cancels pending actions. Alternate adapters can use the same controls and action runner.
The standalone app offers OpenAI and Gemini Live through an explicit provider chooser. Gemini keeps its permanent API key on the local server and mints a short-lived, single-use credential with server-owned instructions and the standalone action catalog. Its native WebSocket adapter supports open microphone and push-to-talk input, streaming audio, captions and the existing action runner. In push-to-talk, a tool call that arrives with no input, reply or tool result outstanding is answered with a failure and never runs, and neither does any other call in the reply it starts; open-microphone turns start on Gemini's server-side activity detection, which reports no boundary to check. Switching providers ends the old conversation and releases its microphone and connection; only the input mode carries over. Gemini uses bounded shutdown draining and explicit manual restart, without automatic reconnection or a promise of uninterrupted session duration. Hosts that do not opt into the provider facade retain their existing default or custom adapter.
Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds 30 tools using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields. Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds 30 tools using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields.
`createGevActionRunner` routes `control_cctv` enable/disable through the shared
layer visibility lifecycle. Results distinguish successful changes from
manager-reported failures or cancellation and report enabled state and lifecycle
uncertainty. A caller-supplied abort signal reaches the manager; a late abort
preserves an already committed change. Missing-layer errors and other CCTV
actions retain their existing behavior. The exported `controlCctv` helper refuses direct
enable/disable requests and directs callers to `set_layer_visibility`.
`src/voice/layerManifest.js` declares each catalog layer's voice capabilities: spoken aliases, `toggle`, in-view `context`, `track`, and analyst `query` fields with type and unit, or `noQuery` with the reason. The `set_layer_visibility`, `show_data_layers_menu`, `get_entity_context` and `analyst_query` layer enums, the runner's alias table and the analyst field hints are generated from it. `src/voice/layerManifest.test.mjs` fails when a catalog layer is neither listed nor named in `VOICE_OFF_LAYERS` (today only the two scene-driven Bhote Koshi layers). Global Context is listed with `toggle: false`; `set_context_mode` reaches it. `set_panel_open` also opens `weather-panel` and `recent-imagery-panel`. `src/voice/layerManifest.js` declares each catalog layer's voice capabilities: spoken aliases, `toggle`, in-view `context`, `track`, and analyst `query` fields with type and unit, or `noQuery` with the reason. The `set_layer_visibility`, `show_data_layers_menu`, `get_entity_context` and `analyst_query` layer enums, the runner's alias table and the analyst field hints are generated from it. `src/voice/layerManifest.test.mjs` fails when a catalog layer is neither listed nor named in `VOICE_OFF_LAYERS` (today only the two scene-driven Bhote Koshi layers). Global Context is listed with `toggle: false`; `set_context_mode` reaches it. `set_panel_open` also opens `weather-panel` and `recent-imagery-panel`.
Portable source exports provide Radio Browser station normalization, CCTV feed types and regional records independently of HTTP middleware. Radio normalization accepts an explicit URL policy; the standalone directory retains its existing HTTPS rules. Tile coordinate validation accepts explicit zoom bounds with unchanged traffic defaults. Cache, request and rendering owners remain unchanged. Portable source exports provide Radio Browser station normalization, CCTV feed types and regional records independently of HTTP middleware. Radio normalization accepts an explicit URL policy; the standalone directory retains its existing HTTPS rules. Tile coordinate validation accepts explicit zoom bounds with unchanged traffic defaults. Cache, request and rendering owners remain unchanged.
@@ -675,7 +651,7 @@ The UI facade composes separate owners for navigation authority, share restorati
visual settings and panel chrome. Navigation owns request generations and follow visual settings and panel chrome. Navigation owns request generations and follow
handoff; restoration owns its coordinator, deferred notices, gestures and timer; handoff; restoration owns its coordinator, deferred notices, gestures and timer;
visual settings own style/detection overrides and sensor cleanup; panel chrome visual settings own style/detection overrides and sensor cleanup; panel chrome
owns disclosure and Cockpit panel snapshots. Each takes explicit owns disclosure, docking and Cockpit panel snapshots. Each takes explicit
operations and reads instead of the complete shell. Existing controls, share operations and reads instead of the complete shell. Existing controls, share
formats and one-application-per-page behavior are preserved. formats and one-application-per-page behavior are preserved.
@@ -841,11 +817,7 @@ Viewport limits, saturation retry, placement, query caps and controls are retain
Satellite and mission layers expose separate factories through `./layers/satellites` Satellite and mission layers expose separate factories through `./layers/satellites`
and `./layers/launches`. Each owns its catalog, render state, tracking, interaction and `./layers/launches`. Each owns its catalog, render state, tracking, interaction
and teardown. Satellite core and dense catalogs retain upstream stale-cache and teardown. Source adapters retain the existing CelesTrak and Launch Library
provenance only for admitted records; duplicate or invalid entries cannot taint
a fresh winning record. Dense removal clears only its own provenance, and a
fresh core rebuild or lifecycle reset replaces the corresponding ownership.
Source adapters retain the existing CelesTrak and Launch Library
endpoints; standalone entries provide scene services and the satellite dependency. endpoints; standalone entries provide scene services and the satellite dependency.
The mission factory separates paths, replay, camera, panel, overlays and placement. The mission factory separates paths, replay, camera, panel, overlays and placement.
Launch Library pad coordinates retain unknown values: missing fields use the Launch Library pad coordinates retain unknown values: missing fields use the
@@ -854,11 +826,7 @@ position stay off the map. Genuine zero coordinates remain valid. Undisclosed
stage coordinates, downrange distance and flight numbers remain unknown; the stage coordinates, downrange distance and flight numbers remain unknown; the
mission panel omits the flight-number label when no number was reported. mission panel omits the flight-number label when no number was reported.
Pending mission requests abort on disable/destruction and malformed launch Pending mission requests abort on disable/destruction and malformed launch
snapshots preserve the last accepted display. A Launch Library stale-cache fallback snapshots preserve the last accepted display. Catalog groups, propagation cadence,
retains its missions but reports STALE in Data Layers; a fresh snapshot clears that
provenance. Hiding retained missions does not relabel them as fresh, and teardown
clears the instance state. Injected getLaunches-only sources remain supported.
Catalog groups, propagation cadence,
tracking intent, replay timing, controls and source attribution remain unchanged. tracking intent, replay timing, controls and source attribution remain unchanged.
The fire layer now exposes `./layers/firms`: an instance factory with separate The fire layer now exposes `./layers/firms`: an instance factory with separate
@@ -1005,9 +973,10 @@ start with current state, isolate listener failures and stop on disposal.
The standalone entry composes the UI with the application's existing layer, The standalone entry composes the UI with the application's existing layer,
terrain, navigation and rendering operations. The shell receives those instances terrain, navigation and rendering operations. The shell receives those instances
and assembles the controls. Panel layout scheduling, loading notices, recording presentation and DOM lookup have focused and assembles the controls. Panel layout scheduling, position preferences and
active drags, loading notices, recording presentation and DOM lookup have focused
owners. Disposal revokes queued presentation and listeners before asynchronous owners. Disposal revokes queued presentation and listeners before asynchronous
Context restoration, restores the Context restoration, cancels an unfinished drag without saving it, restores the
recording HUD and releases status decoration without replacing accessible text. recording HUD and releases status decoration without replacing accessible text.
The ordinary control snapshot includes the current 3D model toggle and mode. The ordinary control snapshot includes the current 3D model toggle and mode.
@@ -1120,26 +1089,6 @@ The images are periodically updated road-condition photographs, not continuous
video; camera poses use the existing low-confidence heading prior. video; camera poses use the existing low-confidence heading prior.
`CCTV_LITHUANIA_MAX_SOURCES` sets its cap (default 400, bounded to 1–1000). `CCTV_LITHUANIA_MAX_SOURCES` sets its cap (default 400, bounded to 1–1000).
## Taiwan CCTV source pack
The CCTV catalog includes Taiwan national freeway cameras from the Freeway
Bureau, MOTC. One keyless request reads the daily MOTC 2.0 `CCTV.xml` table
(~1,800 cameras); the request refuses redirects, has a 15-second deadline and a
6 MiB response cap, and uses the shared 15-minute cache and fair catalog
allocation. A failed download serves the last good table (up to a day old),
or an empty pack, and is not retried for an hour: the catalog host does not
answer from some networks outside Taiwan, and without the backoff every refresh
there would wait out the connect timeout. The table
publishes MJPEG stream URLs; each is mapped to the same camera server's
single-JPEG path for the same camera number, and only those exact HTTPS pairs
on the four `freeway.gov.tw` camera servers are registered with the frame
proxy. Camera keys come from the server and camera number, because published
CCTV IDs contain Chinese place names and a few repeat across cameras. Poses use
the low-confidence heading prior. `CCTV_TAIWAN_ENABLED=0` disables the pack;
`CCTV_TAIWAN_MAX_SOURCES` sets its cap (default 600, bounded to 1–2000), and
`CCTV_TAIWAN_URL` overrides the table URL.
Gate: `src/data/cctvTaiwan.test.mjs`.
## DriveBC CCTV source pack ## DriveBC CCTV source pack
The CCTV catalog adds DriveBC highway cameras for British Columbia alongside the The CCTV catalog adds DriveBC highway cameras for British Columbia alongside the
@@ -1231,32 +1180,6 @@ The application supplies actions and retains effect settings, restore claims and
rendering. Native keyboard editing, model modes and current defaults are preserved. rendering. Native keyboard editing, model modes and current defaults are preserved.
Destroying the UI removes these listeners before asynchronous teardown. Destroying the UI removes these listeners before asynchronous teardown.
Ordinary sliders share the native range component in `ui/slider.js` and the
`gev-quantitative-slider` surface in `ui/styles/slider.css`. Display, shader
parameters, volume, replay speed, weather settings/history, imagery opacity and
Street View's date filter use the same rail, thumb, value styling, keyboard focus and disabled state.
Generated controls use `createSlider`; static templates apply the same class.
Feature owners retain bounds, steps, formatted values, input/change timing and
listener cleanup. The radio tuning dial, imagery comparison divider and event
comparison/progression controls keep their specialized presentation and behavior.
## Segmented selectors
Segmented selectors use the controlled DOM adapter in `ui/segmentedControl.js`
and the shared `gev-segmented` / `gev-segment` surface. Model coverage, label
allocation, drawing shape, Street View fit/panorama filters and imagery mode keep
their feature-owned values, actions and persistence. Painting a restored value
does not emit a change or move focus. Existing keyboard policies remain explicit:
Street View uses arrows/Home/End with one tab stop, imagery mode uses arrows from
its controlled selection, and Display keeps its existing native button behavior.
Pure value navigation is separate from DOM rendering for reuse by a future view.
Segments keep their word minimum width: compact inline groups such as FIT/FILL
and ALL/360°/FLAT must not break short labels mid-word. Collapsed Weather follows
the same exclusive-rail hiding rule as the other readouts.
The imagery mode row reserves 26px for the 24px buttons and group borders so
the complete button and inset keyboard-focus outline remain visible.
Browser acceptance: `QA_BASE_URL=http://127.0.0.1:4173 node scripts/qa-segmented-controls.mjs`.
## Application shortcuts and shader parameter controls ## Application shortcuts and shader parameter controls
`ui/input` supplies the bubbling application shortcut listener and generated `ui/input` supplies the bubbling application shortcut listener and generated
@@ -1283,10 +1206,6 @@ Automatic collapse remains presentation only, prioritizes the latest explicit
panel, and honors keyboard focus on the right. Mobile layout still releases panel, and honors keyboard focus on the right. Mobile layout still releases
desktop allocation styles. Stable Display allocation avoids unnecessary style desktop allocation styles. Stable Display allocation avoids unnecessary style
writes. This extraction does not change panel positions or layout defaults. writes. This extraction does not change panel positions or layout defaults.
Context expansion through the panel owner or adaptive right-rail restoration
closes an open compact Radio disclosure before Context/Space Missions becomes
visible. The mini remains available while Context is collapsed. This fixes the
Radio-overlap path reported in #804 without changing z-index or layout policy.
The right rail skips panels hidden by other CSS (computed `display: none`), but The right rail skips panels hidden by other CSS (computed `display: none`), but
keeps the collapsed panels its own exclusive presentation hides, so automatic keeps the collapsed panels its own exclusive presentation hides, so automatic
collapse can still be undone. collapse can still be undone.
@@ -1536,18 +1455,6 @@ an empty dock. Explicit zero and caller-supplied numeric fallbacks remain valid.
## Terrain height cache bound ## Terrain height cache bound
The `/api/terrain/heights` route refuses cross-site browser requests before
rate limiting, cache access or upstream work: a `Sec-Fetch-Site` other than
`same-origin`/`none` (an `<img>` on another page), or a foreign or opaque
`Origin`, gets `403`. The per-client limiter keys on the socket address, which
for such a request is the visitor's own browser, so without the gate any page
could spend the visitor's 90/min quota and leave the app's own lookups on
`429`. Unlike the cost-bearing routes, the terrain gate does not refuse
reverse-proxy forwarding headers: terrain is keyless and needed for rendering,
and a `403` there would send every chunk to the geoid fallback for an instance
served behind the documented reverse proxy. Same-origin app requests,
non-browser local callers and proxied same-origin requests keep working.
The terrain proxy parser rejects finite longitudes outside [-180, 180] and The terrain proxy parser rejects finite longitudes outside [-180, 180] and
latitudes outside [-90, 90] for every client before upstream resolution. One latitudes outside [-90, 90] for every client before upstream resolution. One
out-of-range point rejects the whole batch; inclusive WGS84 bounds remain valid. out-of-range point rejects the whole batch; inclusive WGS84 bounds remain valid.
@@ -1585,14 +1492,6 @@ The Node-only `gods-eye-view/server/providers/space` export supplies factories;
`sources/space` supplies fixed upstream URL builders with no I/O or environment `sources/space` supplies fixed upstream URL builders with no I/O or environment
access. Callers retain validation, transport and response policy. access. Callers retain validation, transport and response policy.
LL2 recent-launch requests use UTC minute-aligned bounds over the same 30-day
window, so installations refreshing in the same minute share an upstream cache
key. The upper bound trails the current time by less than one minute. Requests
identify the app and repository through User-Agent; the existing 15-minute local
cache, stale fallback and optional server-only Authorization remain unchanged.
Provider Settings identifies LL2 tokens as optional paid higher-rate upgrades:
standard public access needs no key, and its field can remain blank.
The shared TLE text parser skips incomplete named sets and resumes at the next The shared TLE text parser skips incomplete named sets and resumes at the next
complete set. A missing orbital line does not discard the later satellites in complete set. A missing orbital line does not discard the later satellites in
the catalog. A set whose two lines carry different catalog numbers, or a the catalog. A set whose two lines carry different catalog numbers, or a
@@ -2779,17 +2678,6 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> tunings. Ambient overlap includes each sprite's own rendered extent. The > tunings. Ambient overlap includes each sprite's own rendered extent. The
> gated AIS, CCTV, and satellite passes retain an active-emphasis count so a > gated AIS, CCTV, and satellite passes retain an active-emphasis count so a
> settled dim contact always completes its release after tracking ends. > settled dim contact always completes its release after tracking ends.
> - **Terrain-height bounds:** because every distinct 5-decimal point is its own
> cache key, its own line in `.gev-cache/terrain-heights.json`, and its own
> upstream call, four limits bound what a caller can grow. Coordinates outside
> WGS-84 range are rejected with `400` at parse (finite is not the same as on
> Earth); the point cache holds at most 50,000 entries, evicting oldest-first
> — terrain does not move, so an evicted point costs one refetch and never a
> wrong answer; a cache file above 24 MB is not read back into memory (the
> ceiling `rocketLaunchesProxy` already applies); and the route carries an
> always-on limiter of 90 requests/minute/client, 270 global. That cap is an
> order of magnitude above measured demand — a full `npm run test:track` run
> drove 10 requests, peaking at 8/min.
> - **Terrain-height resilience:** `/api/terrain/heights` caches canonical > - **Terrain-height resilience:** `/api/terrain/heights` caches canonical
> 5-decimal points individually, reconstructs reordered/overlapping batches > 5-decimal points individually, reconstructs reordered/overlapping batches
> in exact request order, and refreshes only missing or stale points. Upstream > in exact request order, and refreshes only missing or stale points. Upstream
@@ -3059,13 +2947,6 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> position getter reads only `_trackedDisplayCached`, the same authoritative > position getter reads only `_trackedDisplayCached`, the same authoritative
> Cartesian already consumed by the tracked visual and camera, and never > Cartesian already consumed by the tracked visual and camera, and never
> advances dead reckoning from the host frame. > advances dead reckoning from the host frame.
> - **Scheduled route plausibility:** Aircraft route labels and selected-route
> context reject the distant backwards, forwards and antipodal extensions of
> an airport pair's great circle. The existing 130 km endpoint admission and
> 200 km cross-track tolerance remain; a projected fix outside the finite
> origin-to-destination minor arc also has a generous 200 km extension at
> either end. Missing coordinates and coincident or antipodal endpoint pairs
> retain their loose, unjudgeable behavior; vertical-trend checks are unchanged.
> - **Aircraft label convention (both flight layers, 2026-08-18):** every civil > - **Aircraft label convention (both flight layers, 2026-08-18):** every civil
> and military label surface resolves **callsign → registration → icao24** > and military label surface resolves **callsign → registration → icao24**
> (`_contactLabel()` in `flights.js`; the same chain inline in > (`_contactLabel()` in `flights.js`; the same chain inline in
@@ -3528,7 +3409,7 @@ its criteria cannot be silently ignored.
| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | | Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s |
| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | | Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min |
| Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache | | Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache |
| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + King County (WA) Open Data + WSDOT (WA) Open Data + NYC DOT TMC (opt-in) + City of Toronto RESCU + Catalonia (Servei Català de Trànsit) + Hong Kong Transport Department + FL511 (FL, opt-in) + Freeway Bureau, MOTC (Taiwan) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | | CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS) + King County (WA) Open Data + WSDOT (WA) Open Data + NYC DOT TMC (opt-in) + City of Toronto RESCU + Catalonia (Servei Català de Trànsit) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) |
| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | | Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh |
| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | | Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) |
| Bikeshare 🚲 | GBFS (Lyft + BCycle + Social Bicycles + PBSC incl. Bike Share Toronto, Bike Itaú (Brazil), Bicing (Barcelona) and seven other Spanish cities + Urban Sharing, Entur, JCDecaux (Lillestrøm, Valencia, Seville) + nextbike (AMBici)) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | | Bikeshare 🚲 | GBFS (Lyft + BCycle + Social Bicycles + PBSC incl. Bike Share Toronto, Bike Itaú (Brazil), Bicing (Barcelona) and seven other Spanish cities + Urban Sharing, Entur, JCDecaux (Lillestrøm, Valencia, Seville) + nextbike (AMBici)) | `src/data/bikeshare.js` | `/api/gbfs` | 60s |
@@ -3537,7 +3418,7 @@ its criteria cannot be silently ignored.
| Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static | | Dams ▰ | OpenInfraMap/OSM extract (bundled) | `src/data/localLayers.js` | — | static |
| Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static | | Submarine Cables ◠ | TeleGeography public map (bundled) | `src/data/telegeographySubmarineCables.js` | — | static |
| FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) | | FIRMS Active Fires ▲ | NASA FIRMS live (VIIRS ×3 NRT + MODIS NRT, trailing 24h) | `src/data/firmsHeatmap.js` | `/api/firms` (`FIRMS_MAP_KEY`) | 10 min (proxy TTL 30 min) |
| Street Level 📷 | Mapillary street-level imagery (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, server memory cache 24 h) | | Street Level 📷 | Street-level imagery; Mapillary is the first provider (vector tiles, Graph API, MapillaryJS) | `src/layers/streetLevel/` via `src/app/layers/streetLevel.js` | `/api/mapillary/status`, `/api/mapillary/tiles/coverage/{z}/{x}/{y}` (`MAPILLARY_CLIENT_TOKEN`) | camera-driven (320 ms debounce, ≤9 tiles, cached 24 h) |
| Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) | | Wind 🌬 | NOAA GFS 10 m wind (keyless, 0.25°→1° grid; animated particles) | `src/data/wind.js` | `/api/wind` | 1 h (forecast cycle) |
| GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) | | GNSS Integrity 📡 (`gnss-integrity`) | adsb.lol point snapshot, low navigation accuracy binned per 0.5° cell (GEV NIC/NACp threshold + gpsjam.org formula and bands, keyless, ODbL) | `src/layers/gnss/` via `src/app/layers/gnss.js` | `/api/gnss-integrity` | camera-driven (600 ms debounce, minimum 2.5 s between reads) + 60s poll (server cache 60 s; 30 min rolling window) |
| Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) | | Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) |
@@ -3569,8 +3450,8 @@ by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment. Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
Street Level is a docked, collapsible right-rail panel (`#street-level-panel`, Street Level is a collapsible right-rail panel (`#street-level-panel`, layer
layer token `0`, option owner `street-level`, panel `ui` token `t`) that starts token `0`, option owner `street-level`, panel `ui` token `t`) that starts
collapsed. It opens itself only when the user, voice or a tool switches the collapsed. It opens itself only when the user, voice or a tool switches the
layer on or a photo opens, never on a restore, and those opens are not stored. layer on or a photo opens, never on a restore, and those opens are not stored.
Like the iD editor's photo overlay, it has one chip per registered provider, Like the iD editor's photo overlay, it has one chip per registered provider,
@@ -3582,30 +3463,31 @@ sequence is GEV cyan. Share options: `m` (Mapillary), `r` (the other providers'
e.g. `google-1` for Street View), `p` (`a`/`p`/`f` panoramas), `s` (since, days). Mapillary, Google e.g. `google-1` for Street View), `p` (`a`/`p`/`f` panoramas), `s` (since, days). Mapillary, Google
Street View, KartaView and Panoramax are registered. Without Street View, KartaView and Panoramax are registered. Without
`MAPILLARY_CLIENT_TOKEN` the panel reads KEY REQUIRED and the controls are `MAPILLARY_CLIENT_TOKEN` the panel reads KEY REQUIRED and the controls are
disabled. With it, coverage draws as z11–14 sequence lines below 60 km; the proxy strips the unused `image` layer from z14 disabled. With it, coverage draws as z0–5 overview points from orbit and z11–14
sequence lines below 60 km; the proxy strips the unused `image` layer from z14
tiles (12 MB → ~80 KB) and shares one upstream fetch between concurrent tiles (12 MB → ~80 KB) and shares one upstream fetch between concurrent
requests for a tile. requests for a tile.
Coverage is z11–14 sequence lines below 60 km; above that nothing is drawn and Mapillary coverage ranks unique tile addresses before applying the 16-tile
the panel says to zoom in. Tiles come from the visible ground within range of overview budget. Overlapping dateline halves in a polar view therefore do not
the camera, nearest first, at most 9 (the halves of a view across waste overview slots on the same tile; loading already skips duplicate keys.
the date line count a shared tile once). Lines are draped
`GroundPolylinePrimitive`s (`ClassificationType.BOTH`), so they follow terrain
and Google 3D tiles alike; cones and the photo marker are ground-clamped
billboards with a horizon cull. Without `MAPILLARY_CLIENT_TOKEN` the panel
reads KEY REQUIRED, says which key to add and disables the filters; a rejected
key reads KEY REJECTED and stops tile requests until the layer goes off; a 429
pauses them for its Retry-After.
The server proxy (`server/providers/mapillary.js`) adds the token to On Google 3D (`photoreal`) at street zoom (in below 1,400 m above ground, out
coverage-tile requests (the browser holds it too, for MapillaryJS and the Graph above 1,800 m) the surface mode switches from `draped` to `terrain`: draped
API), serves only z11–14 coverage, refuses upstream redirects, strips the lines land on roofs and tree tops, so `groundCast.js` instead places lines,
unused `image` layer, shares one fetch per tile, runs at most six at once cones and the marker 2 m above the bare earth from `/api/terrain/heights`, and
(cancelling those every client has left) and keeps tiles in memory for 24 h the mesh hides what is behind buildings and trees. A tile is drawn draped until
(a body too big to be a trimmed tile is served but not kept). While Mapillary its heights arrive; a geoid fallback leaves it draped. Within 900 m of the
rate-limits, the proxy answers 429 itself until the Retry-After (seconds or an camera, `meshSampler.js` samples the rendered surface (`scene.sampleHeight`,
HTTP date, at most 10 minutes) is over, so the rest of a view does not go on ~11 m cells, nearest first, 6 ms idle budget) so lines also follow trenches,
asking. steep streets and roads under trees. It uses the mesh floor's rules (the
visible tileset has finished streaming, a real bare-earth prior, the shared
mesh window) and probes a cell again once the camera is half as far from it,
down to 40 m, so coarse early samples are replaced as finer tiles load. A
failed probe keeps the last good sample and distance and is retried after the
miss cooldown. Roads on elevated decks are still drawn at
ground level. Framing a photo ignores mesh samples far below the bare earth
(unloaded tiles).
The header pill is the layer switch. Lighting a chip swaps the source; The header pill is the layer switch. Lighting a chip swaps the source;
clicking the lit chip turns the layer off. A chip without a usable key clicking the lit chip turns the layer off. A chip without a usable key
@@ -3616,18 +3498,19 @@ their keys but a switched-off one would draw with a key already set (no
Mapillary token, Street View on Google 3D with a Google key), the layer Mapillary token, Street View on Google 3D with a Google key), the layer
reports it (`keyAlternatives`), and the panel's KEY REQUIRED, its coverage reports it (`keyAlternatives`), and the panel's KEY REQUIRED, its coverage
line and the layer row's tooltip say to light it. The line and the layer row's tooltip say to light it. The
viewer sits under the header with EXPAND, FIT/FILL and close above the viewer sits under the header with EXPAND, FIT/FILL, FOLLOW and close above the
image. SINCE is a stepped slider whose readout names the cut-off date. image. FOLLOW needs the Google 3D map stack (`attachMapStackController`) and
stops when the stack changes. Camera moves go through the application's
MapillaryJS loads on the first photo. Opening one frames it with a single navigation (`attachNavigation`), which releases aircraft and satellite tracking
camera flight through the application's deferred navigation (`begin` / and is refused in the cockpit: turning FOLLOW on claims the camera at once, and
`reassert`): it releases tracking, is refused in the cockpit, and is skipped FOLLOW stops when another feature takes it; a photo takes a deferred ticket
if newer navigation took the camera while the photo loaded; closing the photo when it starts opening and frames only if nothing newer took the camera while
cancels it. EXPAND is the browser's Fullscreen API on the viewer element; on it loaded. SINCE is a stepped slider whose readout names the
iPhone, which has no element fullscreen, the viewer opens as a top-layer cut-off date. The panel is portable (`street-level-panel` spec, minimum
popover instead (hidden where neither API exists). Clean View, recording and 320 × 280, `dockOnCollapse`): a floating window gives spare height to the
the cockpit take an expanded photo out of full screen. At phone width the viewer, and collapsing it, double-clicking the header or SHRINK after EXPAND
viewer height comes from the rail band so the whole photo fits. docks it. At phone width (≤720 px) the viewer height is derived from the rail
band so the whole photo fits.
Providers implement the contract in `src/layers/streetLevel/registry.js`. The Providers implement the contract in `src/layers/streetLevel/registry.js`. The
core routes clicks by pick prefix, swaps viewer adapters in the one host, core routes clicks by pick prefix, swaps viewer adapters in the one host,
@@ -3636,10 +3519,9 @@ add a provider: implement the definition, register it in
`src/app/layers/streetLevel.js` and add its modules to `src/app/layers/streetLevel.js` and add its modules to
`scripts/package-boundaries.json`; its share switch travels in `r` by id. `scripts/package-boundaries.json`; its share switch travels in `r` by id.
A provider with line coverage builds it on `lineCoverage.js` (camera-driven A provider with line coverage builds it on `lineCoverage.js` (camera-driven
XYZ tiles near the ground, draped, the selected sequence drawn again over XYZ tiles, draped or cast to bare earth, selection recolouring) and its cones
them) and its cones
on `sequenceCones.js`, passing its tile fetch, zoom ladder, colours and pick on `sequenceCones.js`, passing its tile fetch, zoom ladder, colours and pick
prefixes; Mapillary, KartaView and Panoramax all do. With providers on different keys the prefixes; Mapillary's `coverage.js` and `sequences.js` are such wrappers. With providers on different keys the
layer's `requiresKeyId` is null and each chip reports its own key. layer's `requiresKeyId` is null and each chip reports its own key.
Google Street View (`providers/google/`) runs on the Maps JavaScript API with Google Street View (`providers/google/`) runs on the Maps JavaScript API with
@@ -3648,7 +3530,7 @@ on first use (`mapsLoader.js`, CSP `script-src https://maps.googleapis.com`).
Its chip starts off (`defaultOn: false`; a link without its switch keeps it off) because every Its chip starts off (`defaultOn: false`; a link without its switch keeps it off) because every
panorama load is billed to the key. Google's terms forbid Street View beside panorama load is billed to the key. Google's terms forbid Street View beside
non-Google maps, so the provider declares `requiresMapStack: 'photoreal'`: non-Google maps, so the provider declares `requiresMapStack: 'photoreal'`:
off Google 3D it does not appear at all (no chip, globe off Google 3D it does not appear at all (no chip, legend swatch, globe
credit, layer source or button, and Google's script is not loaded), lookups credit, layer source or button, and Google's script is not loaded), lookups
and opens skip it, and leaving Google 3D closes its panorama; the share and opens skip it, and leaving Google 3D closes its panorama; the share
option keeps the user's choice for when Google 3D returns. Google offers no coverage layer option keeps the user's choice for when Google 3D returns. Google offers no coverage layer
@@ -3670,8 +3552,9 @@ marker is a Google-blue view cone (`marker: {kind: 'view-cone'}`) in place
of GEV's amber pin. Its of GEV's amber pin. Its
panoramas are all 360° and it draws no coverage, so it declares `filters: []` panoramas are all 360° and it draws no coverage, so it declares `filters: []`
(a provider's `filters` default to both `pano` and `since`): lookups ignore (a provider's `filters` default to both `pano` and `since`): lookups ignore
the IMAGERY and SINCE filters, and the panel hides each filter row no lit provider the IMAGERY and SINCE filters, the panel hides each filter row no lit provider
honours (`filterControls`). The viewer is Google's `StreetViewPanorama` in its own honours (`filterControls`), and the legend lists only providers that draw
lines, with "Selected" only beside one of them. The viewer is Google's `StreetViewPanorama` in its own
element in the viewer host, without Google's fullscreen, close and address element in the viewer host, without Google's fullscreen, close and address
controls (the address goes in the caption); a pose goes out at once and controls (the address goes in the caption); a pose goes out at once and
again when the panorama's month, photographer and address arrive (one again when the panorama's month, photographer and address arrive (one
@@ -3698,7 +3581,8 @@ are no KartaView photos in it. A tile's lines are OSM way segments with
photos and carry no sequence, date or projection, so `decode.js` chains photos and carry no sequence, date or projection, so `decode.js` chains
segments that meet end to start (about four times fewer lines; linear time, segments that meet end to start (about four times fewer lines; linear time,
at most 20,000 segments a tile and 5,000 points a line), they are at most 20,000 segments a tile and 5,000 points a line), they are
drawn as `kv:line:<z/x/y/n>`, up to 1,600 per tile, and never highlighted, and the drawn as `kv:line:<z/x/y/n>`, up to 1,600 per tile, and never highlighted
(`highlightsSequence: false`, so the legend has no "Selected"), and the
provider declares `filters: ['pano', 'since']` and `coverageLabel` ("N provider declares `filters: ['pano', 'since']` and `coverageLabel` ("N
streets in view · click a line for its nearest photo"). KartaView filters streets in view · click a line for its nearest photo"). KartaView filters
coverage only in its PNG tiles (`/sequence/tiles/{x}/{y}/{z}.png?fieldOfView=360|plane&startDate=YYYY-MM-DD`; coverage only in its PNG tiles (`/sequence/tiles/{x}/{y}/{z}.png?fieldOfView=360|plane&startDate=YYYY-MM-DD`;
@@ -3707,7 +3591,8 @@ asked for), so a filtered tile is drawn from the cached JSON segments that
lie on the filtered PNG's drawn pixels (`maskedSegments`: at least half the lie on the filtered PNG's drawn pixels (`maskedSegments`: at least half the
points sampled every 2 px have a drawn pixel within one; on Jakarta's 360° points sampled every 2 px have a drawn pixel within one; on Jakarta's 360°
filter, 332 of 1,041 segments lie on it, 676 miss it, 33 fall between). filter, 332 of 1,041 segments lie on it, 676 miss it, 33 fall between).
A filter change reloads the lines (`lineCoverage.reload`), keeps the JSON segments, and caches masks per A filter change reloads the lines (`lineCoverage.reload`: the drawn ones show
until the new ones are in), keeps the JSON segments, and caches masks per
filter and tile. A dense filtered PNG can take KartaView over a minute the filter and tile. A dense filtered PNG can take KartaView over a minute the
first time (it answers 504 at 60 s and keeps drawing), so a timeout or 5xx is first time (it answers 504 at 60 s and keeps drawing), so a timeout or 5xx is
asked again 4 s later, four tries in all; then the panel says it did not asked again 4 s later, four tries in all; then the panel says it did not
@@ -3718,8 +3603,8 @@ lookup asks the photo API for the projection (`SPHERE`/`PLANE`; it ignores
`fieldOfView`) and upload date and checks each answer the same way (when `fieldOfView`) and upload date and checks each answer the same way (when
photos are near but none passes, the panel says so), and the cones pass on photos are near but none passes, the panel says so), and the cones pass on
each photo's projection and upload date. The provider declares each photo's projection and upload date. The provider declares
`sinceBasis: 'upload'`, so while it is lit the panel shows "(by `sinceBasis: 'upload'`, so while it is lit the panel shows "KartaView: by
upload date)" beside the SINCE value, as ANY DATE (by upload date) (`sinceNote` in the UI state). Tiles come uncompressed and upload date" under the SINCE slider (`sinceNote` in the UI state). Tiles come uncompressed and
uncacheable, so the last 24 decoded tiles are kept for 10 minutes while uncacheable, so the last 24 decoded tiles are kept for 10 minutes while
KartaView is lit (`createTileCache`, dropped when it is switched off); one KartaView is lit (`createTileCache`, dropped when it is switched off); one
that does not answer in 20 s is asked once more, and one that is not a line that does not answer in 20 s is asked once more, and one that is not a line
@@ -3734,7 +3619,7 @@ remembered; a storage timeout or 5xx is asked again. The open photo's
sequence draws as cones from the 250-photo page holding it sequence draws as cones from the 250-photo page holding it
(`/2.0/sequence/{id}/photos`); the panel counts the drive's own photos (`/2.0/sequence/{id}/photos`); the panel counts the drive's own photos
(`countActivePhotos`, asked once per sequence). The camera direction (the (`countActivePhotos`, asked once per sequence). The camera direction (the
marker, cones and a panorama's centre) is the direction of travel marker, cones, FOLLOW, and a panorama's centre) is the direction of travel
to the next photo a few metres on (`assignCourses`): KartaView is dashcam to the next photo a few metres on (`assignCourses`): KartaView is dashcam
imagery, while its `heading` is the device compass, which reads 0 for whole imagery, while its `heading` is the device compass, which reads 0 for whole
drives without one and can sit a steady 110° off inside a car. Until the drives without one and can sit a steady 110° off inside a car. Until the
@@ -3791,18 +3676,23 @@ to 30 km and z10 to 60 km, as Mapillary's (a dense z10 tile over Paris is
line (Douglas–Peucker to the segment, 4 units of a 4,096 tile: about a line (Douglas–Peucker to the segment, 4 units of a 4,096 tile: about a
pixel where it is drawn, 6–10% of a GPS track's points), and the tiles in pixel where it is drawn, 6–10% of a GPS track's points), and the tiles in
view draw their longest lines within 90,000 points (`maxPoints`, view draw their longest lines within 90,000 points (`maxPoints`,
`keepOrder`), split evenly between the tiles in view (10,000 points `keepOrder`), shared out once loading settles so a sparse tile keeps all
each). Every point becomes ~8 ground-line vertices: it has and a dense one (a city centre) takes the rest; the selected
sequence is always drawn. Every point becomes ~8 ground-line vertices:
unsimplified, the lines hung the tab. Decoded tiles are kept while the unsimplified, the lines hung the tab. Decoded tiles are kept while the
provider is on (16, ten minutes, `tileCache.js`, shared with KartaView). provider is on (16, ten minutes, `tileCache.js`, shared with KartaView),
Above 60 km nothing is drawn and the panel says to zoom in. and above
60 km the `grid` layer's 0.1°
density cells, binned to at most 96×96 points a tile (a z0 tile holds
~70,000 cells) and not counted as sequences: the panel says to zoom in.
A tile decodes in slices of about 8 ms, the page getting a turn between A tile decodes in slices of about 8 ms, the page getting a turn between
them (a 2 MB z10 tile is ~200 ms of work). A busy API (429/503) holds the them (a 2 MB z10 tile is ~200 ms of work). A busy API (429/503) holds the
tiles back for its Retry-After, which the browser cannot read here (the API tiles back for its Retry-After, which the browser cannot read here (the API
exposes no headers), so the wait doubles from 5 s to 5 minutes until it exposes no headers), so the wait doubles from 5 s to 5 minutes until it
answers; an answer may take as long as it keeps arriving (silent for 15 s answers; an answer may take as long as it keeps arriving (silent for 15 s
is given up), so a slow link still gets its megabyte tiles. Both is given up), so a slow link still gets its megabyte tiles. Both
filters apply: lines carry their day and camera type. A click on a filters apply: lines carry their day and camera type, and a cell stays while
it holds pictures of the kind asked for (cells are undated). A click on a
line asks the core (`actions.openNearest`) for that sequence's picture line asks the core (`actions.openNearest`) for that sequence's picture
nearest the click, within the camera height / 100 (50–400 m: from high up nearest the click, within the camera height / 100 (50–400 m: from high up
a click lands well off a line), without framing, then any sequence's within a click lands well off a line), without framing, then any sequence's within
@@ -3851,9 +3741,8 @@ runs against real Mapillary and needs `MAPILLARY_CLIENT_TOKEN`. `npm run
qa:street-level:fixtures -- --url <server>` answers every Mapillary request qa:street-level:fixtures -- --url <server>` answers every Mapillary request
from fixtures (`providers/mapillary/coverageFixture.mjs`, from fixtures (`providers/mapillary/coverageFixture.mjs`,
`scripts/fixtures/street-level/`), and KartaView's and Panoramax's too, so it `scripts/fixtures/street-level/`), and KartaView's and Panoramax's too, so it
needs no network. It opens and closes a photo from Mapillary, KartaView and needs no network and covers the whole photo flow. CI runs the fixture gate and `qa:panel-resize`
Panoramax; stepping, EXPAND, FIT/FILL, the filters and Street View stay with against a production build served by `vite preview` with a dummy token.
the unit tests. CI runs the fixture gate against a production build served by `vite preview` with a dummy token.
Directions is a keyless front end to the routing the voice agent already Directions is a keyless front end to the routing the voice agent already
uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the
@@ -4491,7 +4380,7 @@ silently demoting every later lookup for the session.
- **FIRMS**: no ground clamping (zero 3D-tiles height sampling), ≤18 screen-decluttered ambient labels, click-to-inspect detail card, 2.5k/3k sprite budgets viewport-clipped by FRP. - **FIRMS**: no ground clamping (zero 3D-tiles height sampling), ≤18 screen-decluttered ambient labels, click-to-inspect detail card, 2.5k/3k sprite budgets viewport-clipped by FRP.
- **CCTV v2 foundation:** a pitched - **CCTV v2 foundation:** a pitched
frustum wireframe (4 corner rays + far-cap rectangle) with a monitor plane at the frustum's frustum wireframe (4 corner rays + far-cap rectangle) with a monitor plane at the frustum's
far cap, retargeting the existing video/canvas texture pipeline. Stills are drawn at their source aspect, centered on the placeholder dark (`#01070c`), instead of being stretched to the 16:9 canvas. Manual calibration only — far cap, retargeting the existing video/canvas texture pipeline. Manual calibration only —
auto-calibration and the drape mesh pipeline are deleted. A one-shot activation obstruction auto-calibration and the drape mesh pipeline are deleted. A one-shot activation obstruction
probe (`pickFromRay` on camera activation, clamping the plane short of the first hit) remains; probe (`pickFromRay` on camera activation, clamping the plane short of the first hit) remains;
ground placement is superseded by the shared-floor v3 behavior below. Calibration persists to ground placement is superseded by the shared-floor v3 behavior below. Calibration persists to
@@ -4509,14 +4398,12 @@ silently demoting every later lookup for the session.
ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to
the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active
camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a
periodic white flash). Camera icons are cyan for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` periodic white flash). Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES`
default 36 → 250, hard bound 300), filtered to `camera_status === TURNED_ON` (~815 live of default 36 → 250, hard bound 300), filtered to `camera_status === TURNED_ON` (~815 live of
1,003 rows). City packs (2026-07-04): Caltrans (districts 4/7/11/3 — SF, LA, San Diego, 1,003 rows). City packs (2026-07-04): Caltrans (districts 4/7/11/3 — SF, LA, San Diego,
Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default
sources. Ontario 511 (2026-09-12) adds highway cameras including Kitchener-area routes sources. Ontario 511 (2026-09-12) adds keyless highway cameras including Kitchener-area routes
(cap 1,000, all enabled rows from the current ~944-camera catalog). The 511on.ca API now (cap 1,000, all enabled rows from the current ~944-camera catalog). All sources are RAW PRIOR
requires a developer key, so the pack needs `ONTARIO_511_API_KEY` and is skipped without one
(#1228). All sources are RAW PRIOR
poses, and the layer is stills-first. poses, and the layer is stills-first.
sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`, sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_SOURCES`,
kill switch `CCTV_FINTRAFFIC_ENABLED=0`) are the fourth pack: one keyless GeoJSON station list kill switch `CCTV_FINTRAFFIC_ENABLED=0`) are the fourth pack: one keyless GeoJSON station list
@@ -4524,18 +4411,7 @@ silently demoting every later lookup for the session.
GATHERING stations carry 2,256 in-collection presets, prioritized to 300 against seven anchors GATHERING stations carry 2,256 in-collection presets, prioritized to 300 against seven anchors
on the main road spine. `CCTV_MAX_SOURCES` is a 4,000 catalog-wide ceiling shared round-robin on the main road spine. `CCTV_MAX_SOURCES` is a 4,000 catalog-wide ceiling shared round-robin
across packs, so a lower global cap thins every region instead of starving the last pack. across packs, so a lower global cap thins every region instead of starving the last pack.
~1,100 cameras total, all RAW PRIOR poses, stills-first. The catalog lives for 15 minutes; once ~1,100 cameras total, all RAW PRIOR poses, stills-first.
it expires, `/api/cctv` keeps answering from it while one background refresh reloads every
pack, so only the very first load waits for the slowest pack (a live first load took about
22 s, and is bounded by Tarktee's 30 s). A background refresh that fails or comes back
empty keeps the old catalog and is retried after another 15 minutes, not on the next
request. Estonia's Tarktee DATEX feeds, which answer in 2 to 16.6 s, get 30 s
(`TARKTEE_FETCH_TIMEOUT_MS`) where other packs get 15 s.
Both Tarktee XML catalogs refuse redirects and have a 4 MiB per-document
limit, enforced against declared length and streamed bytes. A rejected fetch,
unsuccessful response, or body-read failure releases both available response
bodies; read failures also cancel an active sibling reader. Cameras sharing
an image number are deduplicated before the Tarktee pack cap is applied.
- **CCTV v3 UX — viewshed + calibration gizmo** (built 2026-07-05 and field - **CCTV v3 UX — viewshed + calibration gizmo** (built 2026-07-05 and field
validated 2026-07-21): the COVERAGE toggle is a validated 2026-07-21): the COVERAGE toggle is a
tri-state cycle `OFF → ON → VIEWSHED`; viewshed mode renders each visible camera's frustum tri-state cycle `OFF → ON → VIEWSHED`; viewshed mode renders each visible camera's frustum
@@ -4852,7 +4728,7 @@ and unreachable upstream (502/504) separately from road geometry.
- **Every selectable layer writes that one slot** (2026-08-21). The tracking layers — flights, military, satellites — publish selection on their own awareness lane (`gev:awareness-subject-selected`, consumed by the readout card and the Contacts panel) and for the life of the voice tools never wrote the shared slot, so `scope:'selected'` silently answered `in_view` with a contact plainly selected on screen. They now call `selectTrackedSubjectContext` / `refreshTrackedSubjectContext` / `clearTrackedSubjectContext` (`src/data/contextStore.js`) on select / poll / deselect. **Invariants: (a)** that write path must NOT dispatch `gev:entity-selected` — tracking layers already own an event lane and a second one makes two surfaces fight over one subject; **(b)** exactly one record per tracking layer, because a frozen snapshot of a moved contact must never reach the visible-entity scan; **(c)** precedence is recency, not layer — one slot, last selection wins, so clicking an overlay entity supersedes a tracked plane as the voice subject while the plane stays tracked. Satellites refresh on the 1 s propagation beat, not per frame. - **Every selectable layer writes that one slot** (2026-08-21). The tracking layers — flights, military, satellites — publish selection on their own awareness lane (`gev:awareness-subject-selected`, consumed by the readout card and the Contacts panel) and for the life of the voice tools never wrote the shared slot, so `scope:'selected'` silently answered `in_view` with a contact plainly selected on screen. They now call `selectTrackedSubjectContext` / `refreshTrackedSubjectContext` / `clearTrackedSubjectContext` (`src/data/contextStore.js`) on select / poll / deselect. **Invariants: (a)** that write path must NOT dispatch `gev:entity-selected` — tracking layers already own an event lane and a second one makes two surfaces fight over one subject; **(b)** exactly one record per tracking layer, because a frozen snapshot of a moved contact must never reach the visible-entity scan; **(c)** precedence is recency, not layer — one slot, last selection wins, so clicking an overlay entity supersedes a tracked plane as the voice subject while the plane stays tracked. Satellites refresh on the 1 s propagation beat, not per frame.
- **Context-mode vocabulary is symmetric** (2026-08-21). `set_context_mode` accepts `contacts`; the internal id is `flights`. Every model-readable field (`mode`, `entering`, `priorMode`, nested `context`/`contextRollback`, and the transition diagnostic text) is reported in the accepted vocabulary, with the internal id preserved as `<field>Internal`; an absent secondary mode stays `null` rather than claiming to be `off`. Mapping lives in `src/contextModePolicy.js` so UI text and voice payloads cannot drift. Reporting the internal id made the model read `mode:'flights'` as "Contacts is off" and refuse to answer from the `contactsWindow` counts in the same payload. - **Context-mode vocabulary is symmetric** (2026-08-21). `set_context_mode` accepts `contacts`; the internal id is `flights`. Every model-readable field (`mode`, `entering`, `priorMode`, nested `context`/`contextRollback`, and the transition diagnostic text) is reported in the accepted vocabulary, with the internal id preserved as `<field>Internal`; an absent secondary mode stays `null` rather than claiming to be `off`. Mapping lives in `src/contextModePolicy.js` so UI text and voice payloads cannot drift. Reporting the internal id made the model read `mode:'flights'` as "Contacts is off" and refuse to answer from the `contactsWindow` counts in the same payload.
- **Analyst → track handoff carries a key, not just a label** (2026-08-21). `analyst_query` items include `icao24`/`mmsi` alongside the display `id`, and contact lookup uses the shared tiered ranking in `src/data/contactMatch.js`: hex exact → callsign exact → registration exact → callsign prefix → registration prefix → callsign substring → registration substring. The tiers keep an exact callsign ahead of a colliding registration regardless of feed order, and registrations compare separator-insensitively (`G-ABCD`/`GABCD`, `05-8152`/`058152`, `N123AB`/`N-123AB`). - **Analyst → track handoff carries a key, not just a label** (2026-08-21). `analyst_query` items include `icao24`/`mmsi` alongside the display `id`, and contact lookup uses the shared tiered ranking in `src/data/contactMatch.js`: hex exact → callsign exact → registration exact → callsign prefix → registration prefix → callsign substring → registration substring. The tiers keep an exact callsign ahead of a colliding registration regardless of feed order, and registrations compare separator-insensitively (`G-ABCD`/`GABCD`, `05-8152`/`058152`, `N123AB`/`N-123AB`).
- **A typed command supersedes the turn it interrupts** (2026-08-21; hardened 2026-10-17). `sendTextCommand` defers its `response.create` behind an active response instead of colliding with it, marks that response superseded so a late function call from it is refused rather than dispatched, and drops the old turn's queued follow-up. A refused call is still ANSWERED — a terminal `{ok:false, superseded:true}` `function_call_output` — because an unanswered `function_call` strands a pending call and deadlocks the model; the refusal creates no response of its own. A burst of typed commands coalesces into one response while keeping both conversation items. If the local channel rejects the user item, that command requests no response and adds no deferred answer; earlier accepted deferred input remains queued. Interruption and pointer preparation still happen before the send attempt. - **A typed command supersedes the turn it interrupts** (2026-08-21). `sendTextCommand` defers its `response.create` behind an active response instead of colliding with it, marks that response superseded so a late function call from it is refused rather than dispatched, and drops the old turn's queued follow-up. A refused call is still ANSWERED — a terminal `{ok:false, superseded:true}` `function_call_output` — because an unanswered `function_call` strands a pending call and deadlocks the model; the refusal creates no response of its own. A burst of typed commands coalesces into one response while keeping both conversation items.
- **Subject reconciliation across satellite catalog rebuilds** (2026-08-21). A dense↔core toggle or TLE refresh clears and repopulates the catalog, so the published subject is re-resolved against the new satrec; a subject that did NOT survive releases the slot. The per-frame refresh cannot do this itself — `_getTrackedFramePosition` returns early once the satellite has no catalog entry — so the reconcile runs at rebuild completion. An empty catalog is a rebuild in flight, not a disappearance. - **Subject reconciliation across satellite catalog rebuilds** (2026-08-21). A dense↔core toggle or TLE refresh clears and repopulates the catalog, so the published subject is re-resolved against the new satrec; a subject that did NOT survive releases the slot. The per-frame refresh cannot do this itself — `_getTrackedFramePosition` returns early once the satellite has no catalog entry — so the reconcile runs at rebuild completion. An empty catalog is a rebuild in flight, not a disappearance.
- **One aircraft-proximity snapshot** (2026-08-22; hardened 2026-09-30). `collectAircraftProximityWindow` (`src/data/militaryAwareness.js`) computes the Contacts panel cohort once. The voice analyst reads the exact retained snapshot and evaluation timestamp instead of re-scanning live layers, so the panel readout and spoken count for one centre cannot cross snapshots. **Invariant: do not re-derive a proximity count anywhere else.** Each layer retains 20,000 rows and samples one row beyond the cap; a saturated cohort reports `complete:false`, `truncated:true`, and is spoken as a lower bound. They diverged before because the panel read live billboard positions while the analyst used last-fix coordinates over a 2,000-record slice — 111 on screen, 15 spoken. Explicit regions, arbitrary points, and a radius different from the panel radius deliberately keep the general record engine. Entity-centred results carry `window: {engine:'contacts-window', centeredOn, radiusKm, flights, military, aircraft, complete, evaluatedAt}`. - **One aircraft-proximity snapshot** (2026-08-22; hardened 2026-09-30). `collectAircraftProximityWindow` (`src/data/militaryAwareness.js`) computes the Contacts panel cohort once. The voice analyst reads the exact retained snapshot and evaluation timestamp instead of re-scanning live layers, so the panel readout and spoken count for one centre cannot cross snapshots. **Invariant: do not re-derive a proximity count anywhere else.** Each layer retains 20,000 rows and samples one row beyond the cap; a saturated cohort reports `complete:false`, `truncated:true`, and is spoken as a lower bound. They diverged before because the panel read live billboard positions while the analyst used last-fix coordinates over a 2,000-record slice — 111 on screen, 15 spoken. Explicit regions, arbitrary points, and a radius different from the panel radius deliberately keep the general record engine. Entity-centred results carry `window: {engine:'contacts-window', centeredOn, radiusKm, flights, military, aircraft, complete, evaluatedAt}`.
- **Centre precedence for nearby asks**: explicit place in the question > Contacts subject (a selected non-contact entity never silently becomes the centre) > an entity the user names > the current view, said aloud. Contacts active with no subject uses the view rather than reading an empty panel. - **Centre precedence for nearby asks**: explicit place in the question > Contacts subject (a selected non-contact entity never silently becomes the centre) > an entity the user names > the current view, said aloud. Contacts active with no subject uses the view rather than reading an empty panel.
@@ -5159,7 +5035,7 @@ pins and share links already supply complete boxes.
Pixel-mode pinch deltas receive bounded amplification before reaching the Pixel-mode pinch deltas receive bounded amplification before reaching the
canvas; ordinary wheel, line/page-mode and native touch-pinch paths are left canvas; ordinary wheel, line/page-mode and native touch-pinch paths are left
unchanged. The application scene owns and removes the relay listener. unchanged. The application scene owns and removes the relay listener.
- Z ladder: panels around 100, voice pill 150, toast 200, clean-view exit 300. - Z ladder: panels promote within 100–139 (renormalized on wrap), voice pill 150, toast 200, clean-view exit 300.
- Panel POSITION keys are versioned `v8` (`godsEyeView.v8.panelPos.<id>`); collapsed-state keys remain `v6`. The one-time position reset clears stale DISPLAY placements that could overlap the Context rail. - Panel POSITION keys are versioned `v8` (`godsEyeView.v8.panelPos.<id>`); collapsed-state keys remain `v6`. The one-time position reset clears stale DISPLAY placements that could overlap the Context rail.
- Map Source lives in the bottom Visual Presets tray. The left accordion contains no MAP STACK panel, and the `k` panel token that addressed it is gone from the share registry, so legacy `ui=k...` state takes the ordinary unknown-token skip. - Map Source lives in the bottom Visual Presets tray. The left accordion contains no MAP STACK panel, and the `k` panel token that addressed it is gone from the share registry, so legacy `ui=k...` state takes the ordinary unknown-token skip.
- A dock popover (Visual Presets, Location) auto-dismisses on mouse-away unless pinned. Focus inside the tray defers that dismissal only when the browser reports `:focus-visible` — keyboard focus and typed-into fields hold the tray open; a mouse-clicked tile does not, because Chromium focuses a `<button>` on press. - A dock popover (Visual Presets, Location) auto-dismisses on mouse-away unless pinned. Focus inside the tray defers that dismissal only when the browser reports `:focus-visible` — keyboard focus and typed-into fields hold the tray open; a mouse-clicked tile does not, because Chromium focuses a `<button>` on press.
@@ -5370,8 +5246,8 @@ easier to meet (detection is now on more often), but does not create it.
samples and constant elevation during E/N drag; one shared-floor resolution on samples and constant elevation during E/N drag; one shared-floor resolution on
release; late one-shot shared-cell work is permitted during viewshed idle. The release; late one-shot shared-cell work is permitted during viewshed idle. The
A+B harness intentionally excludes citywide LOD assertions. A+B harness intentionally excludes citywide LOD assertions.
- Panel positions have a versioned storage name, `godsEyeView.v8.panelPos.<panel-id>`, but the current rails lay panels out adaptively and write none. Collapsed state does persist for every panel at `godsEyeView.v6.panelCollapsed.<panel-id>` (`'0'` open, `'1'` closed, absent means the panel's own default). - Panel positions have a versioned storage name, `godsEyeView.v8.panelPos.<panel-id>`. Docked panels store nothing; a portable panel (CCTV, Street Level) stores `{ left, top, width, height, floating: true }` once a header drag lifts it out of the rail, and a header double-click removes it. Double presses are detected in the header's `pointerdown` handler, because its `preventDefault()` suppresses native `dblclick`. Collapsed state persists for every panel at `godsEyeView.v6.panelCollapsed.<panel-id>` (`'0'` open, `'1'` closed, absent means the panel's own default).
- Legacy draggable-panel position keys may remain in local storage for backward compatibility, but the map-mode right rail ignores them; collapsed states still persist at `godsEyeView.v6.panelCollapsed.<panel-id>`. - Legacy draggable-panel position keys may remain in local storage for backward compatibility, but the map-mode right rail ignores them unless they describe a portable panel's floating window; collapsed states still persist at `godsEyeView.v6.panelCollapsed.<panel-id>`.
- Flight/military tracked entities cache dead-reckoned positions per frame to avoid callback desync flicker. - Flight/military tracked entities cache dead-reckoned positions per frame to avoid callback desync flicker.
- Aircraft 3D-model and tracking invariants are covered by `npm run test:track`; run this before touching `flights.js`, `militaryFlights.js`, `detection.js`, or `trackedReadout.js`. - Aircraft 3D-model and tracking invariants are covered by `npm run test:track`; run this before touching `flights.js`, `militaryFlights.js`, `detection.js`, or `trackedReadout.js`.
- Annotation resolver behavior is pinned by `src/annotations/annotationResolver.test.mjs`; re-run that suite before changing place-resolution scoring. - Annotation resolver behavior is pinned by `src/annotations/annotationResolver.test.mjs`; re-run that suite before changing place-resolution scoring.
+60
View File
@@ -108,3 +108,63 @@ Version-1/2/3 projects migrate to version 4 without converting their ordinary
shots into explicit moves. IDs, positions, durations, visual settings, packs and shots into explicit moves. IDs, positions, durations, visual settings, packs and
source attribution survive. The bloom scale remains independent of the document source attribution survive. The bloom scale remains independent of the document
version; version-3 bloom is never interpreted as the older inverted scale. version; version-3 bloom is never interpreted as the older inverted scale.
## Recorded tracks
Version 7 adds a second kind of explicit move: a recorded track, which is what
[VCAM](VCAM.md) takes write. Instead of `from` and `easing`, `move.track` holds
timed samples:
```json
{
"id": "take-1",
"title": "Take 1",
"durationSec": 6.4,
"holdSec": 0,
"camera": { "lat": 30.27, "lon": -97.74, "alt": 950, "heading": 20,
"pitch": -25, "roll": 0, "altitudeReference": "ellipsoid" },
"move": {
"track": {
"altitudeReference": "ellipsoid",
"samples": [
[0, -97.7431, 30.2672, 900, 10, -30, 0, 24],
[6.4, -97.7400, 30.2700, 950, 20, -25, 0, 50]
]
}
},
"lens": { "focalMm": 50, "dof": { "enabled": true, "focusM": 300, "fStop": 2, "scale": 100 } }
}
```
Each sample is `[t, lon, lat, alt, heading, pitch, roll, focalMm?]`: seconds from
the start of the take, then the same coordinate, height and orientation
conventions as a pose, then an optional 35 mm-equivalent focal length (4 to
2,000 mm). The first sample is at 0 seconds and times strictly increase. A track
has 2 to 10,000 samples and requires the ellipsoid altitude reference. The shot
`camera` stays the destination: the final sample, which Load, Capture and the
ordinary flight from the previous shot use.
Playback stretches the recorded time to `durationSec`, so changing the duration
retimes the take without touching its samples. Between samples, latitude, height,
pitch and focal length interpolate linearly; longitude, heading and roll take
the short arc. A time that lands on a sample returns that sample exactly,
including both ends. Playback, Load, Replay and seek all use
`sampleCameraMove`, which dispatches to `sampleCameraTrack` for tracks.
## Lens
Version 7 shots may carry an optional `lens`:
- `focalMm`: 35 mm-equivalent focal length across the frame's longer side
(4 to 2,000 mm), applied to the camera's field of view. Cesium's default
60-degree view is about 31 mm.
- `dof`: depth of field, with `enabled`, `focusM` (focus distance in metres,
0.1 to 10⁸), `fStop` (0.5 to 64) and `scale` (0.001 to 10⁷). The blur is a
thin-lens circle of confusion computed after dividing distances by `scale`,
so a scale of 1,000 renders the scene as a 1:1000 miniature.
A shot's lens is applied after its visual state. A shot without one restores
the application's field of view and turns depth of field off, so older shots
look as they always did. Capture and Update Shot store the live lens only when
it differs from the default. A track's per-sample focal length overrides
`focalMm` while the track plays.
+3 -2
View File
@@ -57,8 +57,9 @@ Related keys (current versions):
- Panel collapsed state: `godsEyeView.v6.panelCollapsed.<panel-id>` — `'0'` open, - Panel collapsed state: `godsEyeView.v6.panelCollapsed.<panel-id>` — `'0'` open,
`'1'` closed, absent means the panel's own default. A view opened from a share `'1'` closed, absent means the panel's own default. A view opened from a share
link ignores the stored value entirely. link ignores the stored value entirely.
- Panel positions: `godsEyeView.v8.panelPos.<panel-id>` — the current layout - Panel positions: `godsEyeView.v8.panelPos.<panel-id>` — written only for a
writes none. floating portable panel (CCTV, Street Level). Deleting it, or double-clicking
the panel header, docks the panel again.
- CCTV calibration: `godsEyeView.cctv.calibration.v2` - CCTV calibration: `godsEyeView.cctv.calibration.v2`
--- ---
+5
View File
@@ -103,3 +103,8 @@ change with this document boundary.
Version 5 additionally accepts scene `dataPacks` and shot `dataPackIds`, as Version 5 additionally accepts scene `dataPacks` and shot `dataPackIds`, as
defined in [data packs](DIRECTOR-DATA-PACKS.md). Version-4 camera documents defined in [data packs](DIRECTOR-DATA-PACKS.md). Version-4 camera documents
continue to import without adding any packs. continue to import without adding any packs.
Version 7 is the write format. It additionally accepts recorded camera tracks
(`move.track`) and an optional shot `lens` (focal length and depth of field), as
defined in [camera directions](DIRECTOR-CAMERA.md#recorded-tracks). Versions 1
to 6 import unchanged; their shots receive no lens and keep the default view.
+2 -2
View File
@@ -263,11 +263,11 @@ and the development server's internal routes. See SECURITY.md.
| `get_earthquakes` | `earthquakes` | USGS M2.5+ events in the last 24 hours, strongest first | | `get_earthquakes` | `earthquakes` | USGS M2.5+ events in the last 24 hours, strongest first |
| `get_active_fires` | `fires` | NASA FIRMS detections in an area, highest radiative power first | | `get_active_fires` | `fires` | NASA FIRMS detections in an area, highest radiative power first |
| `get_recent_launches` | `launches` | Launch Library 2 launches in the last 30 days, newest first | | `get_recent_launches` | `launches` | Launch Library 2 launches in the last 30 days, newest first |
| `aircraft_in_area` | `aircraft` | Aircraft in an area, nearest first; `military: true` reads the `military` feed; `group_by` and `stats` count and summarize every match | | `aircraft_in_area` | `aircraft` | Aircraft in an area, nearest first; `military: true` reads the `military` feed |
| `find_aircraft` | `aircraft` | Aircraft anywhere by callsign, ICAO address or registration | | `find_aircraft` | `aircraft` | Aircraft anywhere by callsign, ICAO address or registration |
| `get_aircraft_track` | `aircraft` | Recent positions of one aircraft, thinned to 200 points | | `get_aircraft_track` | `aircraft` | Recent positions of one aircraft, thinned to 200 points |
| `get_aircraft_info` | `aircraft` | Aircraft type and registration, and flight route, from adsbdb | | `get_aircraft_info` | `aircraft` | Aircraft type and registration, and flight route, from adsbdb |
| `vessels_in_area` | `vessels` | Ships reported by AIS in an area, nearest first, optionally by type; `group_by` and `stats` count and summarize every match | | `vessels_in_area` | `vessels` | Ships reported by AIS in an area, nearest first, optionally by type |
| `find_vessel` | `vessels` | Ships anywhere by MMSI, IMO number or name | | `find_vessel` | `vessels` | Ships anywhere by MMSI, IMO number or name |
| `get_vessel_track` | `vessels` | Recent positions of one ship, thinned to 200 points | | `get_vessel_track` | `vessels` | Recent positions of one ship, thinned to 200 points |
| `next_satellite_pass` | `satellites` | Next pass over a place or point (default the ISS), with naked-eye visibility | | `next_satellite_pass` | `satellites` | Next pass over a place or point (default the ISS), with naked-eye visibility |
+165
View File
@@ -0,0 +1,165 @@
# VCAM: a phone as the virtual camera
VCAM turns a phone on the same network into a handheld camera for the globe,
like Unreal's Live Link VCAM or Blender's VirtuCamera. Walk around the room
holding the phone and the app's camera moves with it. A motion scale decides
how big a step is: 1:1 walks the street, 1:100 is a drone, 1:1000 flies over
the city. The phone shows the app's render as a monitor, and **REC** records the
move as a take: a shot in the selected scene that replays, seeks and retimes
like any other shot.
## Using it
1. Open **SCENES › VCAM**. The card shows a QR code, a six-character code and
the phone URL (`https://<this computer>:4174/`).
2. Scan the code with the phone's camera app, or open the URL and type the
code. The phone and the computer must be on the same network.
3. The page warns about the certificate the first time (see [Trust](#trust));
continue past it, or install the local certificate once.
4. Choose **START AR CAMERA** (6DoF) or **START GYRO CAMERA** (3DoF).
5. Hold the phone like a camera. The rig starts from wherever the globe camera
is, so nothing jumps.
6. **REC** on the phone or in the card records a take. Takes are added to the
scene selected in the Scenes panel.
| Control | Phone | Card | What it does |
| --- | --- | --- | --- |
| Motion scale | SCALE drawer | SCALE | World metres per phone metre, 0.01 to 100,000. Presets: 1:1 walk, 1:10 crane, 1:100 drone, 1:1000 flyover, 1:10000 orbit. Changing it never moves the camera. |
| Move stick | left | | Dolly and truck along the camera's heading, at 2.5 m/s × scale. |
| Crane · pan stick | right | | Raise or lower the rig; pan about the camera itself. |
| Hold | HOLD | HOLD / RESUME | Freeze the camera to reposition yourself (a clutch). Release re-anchors where the camera is. |
| Recenter | RECENTER | RECENTER | Keep the camera where it is and point the phone's current heading along it. |
| Smoothing | SCALE drawer | | Damps hand shake (0 raw to 100 heavy). |
| Height lock | SCALE drawer | | Ignore the phone's vertical motion. |
| Horizon lock | SCALE drawer | | Keep the horizon level (no roll). |
| Focal length | LENS drawer | LENS | 35 mm-equivalent, 12 to 400 mm. Recorded per sample. |
| Depth of field | LENS drawer | DEPTH OF FIELD | Thin-lens blur; tap the phone's picture to focus. |
| Aperture | LENS drawer | APERTURE | f/1.2 to f/22. |
| Record | ● | ● REC | Start and stop a take. |
The rig yields the camera whenever something else takes it, as scene playback
does: a search or route, a scene starting, Cockpit, or a mouse press or wheel on
the globe. It then reads **Held**. Tap HOLD on the phone (or RESUME) to continue
from wherever the camera now is. Cockpit refuses the camera, as it does for
scenes.
### Tracking: what each phone gets
| Phone and browser | Mode | Position | Rotation |
| --- | --- | --- | --- |
| Android Chrome with Google Play Services for AR | AR (WebXR `immersive-ar`) | tracked (6DoF) | tracked |
| iPhone Safari | Gyro (DeviceOrientation) | sticks only | tracked (3DoF) |
| Other browsers without WebXR AR | Gyro | sticks only | tracked |
iPhone Safari does not offer WebXR AR, so a web page cannot read ARKit's
position. Gyro mode tracks the phone's rotation and the sticks move it. WebXR
browsers that do offer `immersive-ar` on iOS get the AR mode automatically.
### Depth of field and the miniature look
The blur follows a thin-lens circle of confusion. Distances are divided by the
motion scale first, so the lens treats the world at the rig's size. At 1:1 a
city a kilometre away is effectively sharp, as it is through a real lens. At
1:1000 the same city focuses like a tabletop model and falls off like
tilt-shift miniature photography. Tap the phone's picture to set the focus
distance at that point.
## Takes in the Director
A take is a version-7 scene-document shot with a recorded track
([camera directions](DIRECTOR-CAMERA.md#recorded-tracks)). Each sample stores
time, position, heading, pitch, roll and focal length, about 30 per second. A
take holds at most 10,000 samples (about 5½ minutes); recording stops and
saves at that limit. Editing the shot's `durationSec` retimes the take: a longer
duration plays the same path in slow motion. Depth of field is stored in the
shot's `lens`. Takes export, import and share like any other shot.
Takes live in the browser's scene storage like other shots. A browser that
refuses to save a long take keeps it for the session and shows the usual
storage warning; use EXPORT PRESETS to keep it.
## Trust
Phones expose motion tracking only to secure (HTTPS) pages, so the phone
listener serves HTTPS with a certificate from a local certificate authority it
creates on first use (`.gev-cache/vcam/`, git-ignored, private keys owner-only).
The server certificate names this computer's current LAN addresses and is
reissued when they change; the CA stays the same.
- **Android Chrome:** continue past the warning once. AR and the live
connection work.
- **iPhone Safari:** the page loads past the warning, but Safari refuses its
WebSocket, so the phone falls back to HTTPS requests (an amber dot rather
than green). It works with a little more latency. To trust the computer:
open **Phone certificate** in the card (or the link on the phone's pairing
page), allow the profile, install it under **Settings › General › VPN &
Device Management**, then enable it under **Settings › General › About ›
Certificate Trust Settings**.
The CA is constrained to sign server certificates only (path length 0). Remove
the profile from the phone, or delete `.gev-cache/vcam/`, to revoke it.
## How it is built
```
phone (HTTPS :4174) desktop app (http://localhost:4173)
server/vcam/phone/* ── pose JSON ──▶ relay ──▶ /api/vcam/host (WebSocket)
◀── state ───── ◀── src/vcam/controller.js
◀── JPEG pull ── newest frame only
```
- **`server/vcam/plugin.js`**: on the app's server, loopback-only routes behind
the `/mcp` gate (`POST`/`DELETE /api/vcam/session`, `/api/vcam/ca.crt`, the
host WebSocket). It starts a separate HTTPS listener (`VCAM_PORT`, default
4174, on `VCAM_HOST`, default all interfaces) only when a session is created,
and stops it two minutes after the last one ends. That listener serves the
static phone page and the phone side of the relay, never the app or its
provider proxies.
- **`server/vcam/relay.js`**: pairing and forwarding, independent of transport.
The phone exchanges the six-character code (31 unambiguous characters, about
30 bits, case and separators ignored) for its own key; eight wrong codes
rotate every session's code and the card updates. Messages are JSON objects of
at most 4 KiB, at most 120 a second with a burst of 240. The host's JPEG
preview is held as the newest frame only; the phone pulls it, so a slow link
drops frames instead of queueing them.
- **`server/vcam/tls.js`**: the local CA and server certificate, DER-encoded with
`node:crypto`; there is no OpenSSL or dependency.
- **`server/vcam/phone/`**: the phone page. It uses a WebSocket when it can,
otherwise POSTs poses (newest-wins) and listens on server-sent events. Poses
are a quaternion and position in WebXR's Y-up frame (+x right, +y up, −z
forward); gyro mode converts DeviceOrientation into the same frame.
- **`src/vcam/rig.js`**: the renderer-independent mapping from phone pose to an
east-north-up camera offset and basis around a geographic anchor. Recenter,
scale changes and stick moves shift the anchor rather than the phone's origin,
so the camera stays continuous.
- **`src/vcam/controller.js`**: session lifecycle, camera ownership, per-frame
placement (`scene.preUpdate`), recording and preview capture
(`scene.postRender`, 720 px JPEG at 12 frames a second).
- **`src/scenes/cameraLens.js`**: focal length (frustum field of view) and the
depth-of-field post-process stage, shared with scene playback.
- **`src/vcam/qr.js`**: a QR encoder (byte mode, level M, versions 1–10).
`node scripts/qa-vcam.mjs` drives all of it end to end against a running dev
server: the real phone page in gyro mode over the HTTPS fallback, a scripted
6DoF phone over a WebSocket, a take recorded and replayed, and camera handoff.
## Configuration
| Variable | Default | |
| --- | --- | --- |
| `VCAM_PORT` | `4174` | Phone listener port. |
| `VCAM_HOST` | `0.0.0.0` | Phone listener interface. Set an address to restrict it. |
The Docker image publishes only the app's port on loopback, so VCAM needs the
phone port published as well (see [SECURITY.md](../SECURITY.md)).
## Next
- Preview over WebRTC (`canvas.captureStream`) for lower latency and higher
resolution, with the JPEG pull kept as the fallback.
- Bookmarks and a take browser in the phone UI; slate and take naming.
- Focus pulls and animated aperture recorded per sample.
- A full-quality offline render of a take (fixed-step, every frame).
- iPhone 6DoF through an ARKit companion (an App Clip or a small native app
speaking the same relay protocol).
- Phone page translation through the app's catalogs.
+2 -2
View File
@@ -49,6 +49,7 @@
"test": "node scripts/run-unit-tests.mjs", "test": "node scripts/run-unit-tests.mjs",
"test:track": "node scripts/track-regression.mjs", "test:track": "node scripts/track-regression.mjs",
"qa:map-source-tray": "node scripts/qa-map-source-tray.mjs", "qa:map-source-tray": "node scripts/qa-map-source-tray.mjs",
"qa:panel-resize": "node scripts/qa-panel-resize.mjs",
"qa:street-level": "node scripts/qa-street-level.mjs", "qa:street-level": "node scripts/qa-street-level.mjs",
"qa:street-level:fixtures": "node scripts/qa-street-level.mjs --fixtures", "qa:street-level:fixtures": "node scripts/qa-street-level.mjs --fixtures",
"check:boundaries": "node scripts/check-import-directions.mjs && node scripts/check-package-boundaries.mjs", "check:boundaries": "node scripts/check-import-directions.mjs && node scripts/check-package-boundaries.mjs",
@@ -276,7 +277,6 @@
"./tools/mcp": "./src/tools/mcp/index.js", "./tools/mcp": "./src/tools/mcp/index.js",
"./tools/panel": "./src/tools/panel.js", "./tools/panel": "./src/tools/panel.js",
"./tools/services": "./src/tools/services.js", "./tools/services": "./src/tools/services.js",
"./view": "./src/view/index.js", "./view": "./src/view/index.js"
"./agent/world-packet": "./src/agent/worldPacket.js"
} }
} }
@@ -49,6 +49,11 @@ export function resetKartaViewFixture() {
nearestLookups = 0; nearestLookups = 0;
} }
/** Nearest lookups answered since the last reset (the first got a 429). */
export function kartaViewLookups() {
return nearestLookups;
}
/** The drive's photos, south to north; every tenth is 360°, every odd one archived. */ /** The drive's photos, south to north; every tenth is 360°, every odd one archived. */
export function kartaViewPhotos() { export function kartaViewPhotos() {
const step = KV_SPACING_M / METRES_PER_DEG_LAT; const step = KV_SPACING_M / METRES_PER_DEG_LAT;
@@ -2,8 +2,8 @@ import { readFileSync } from 'node:fs';
/** /**
* Mapillary Graph API and image CDN answered from fixtures, covering every * Mapillary Graph API and image CDN answered from fixtures, covering every
* request the provider and MapillaryJS make while opening and closing a * request the provider and MapillaryJS make while opening, stepping and
* photo, so the gate needs no network and no real token. * closing a photo, so the gate needs no network and no real token.
* *
* No `merge_cc` or `sfm_cluster` means MapillaryJS never asks for a mesh or * No `merge_cc` or `sfm_cluster` means MapillaryJS never asks for a mesh or
* cluster, and empty S2 cells mean no spatial edges, which the gate does not * cluster, and empty S2 cells mean no spatial edges, which the gate does not
@@ -21,7 +21,7 @@ export const PHOTO_LINE = Object.freeze({
north: 38.591, north: 38.591,
}); });
/** Metres between consecutive photos on the line (≥ the 3 m cone thinning). */ /** Metres between consecutive photos on the line (≥ the 3 m cone thinning). */
const PHOTO_SPACING_M = 30; export const PHOTO_SPACING_M = 30;
/** Fixture thumbnail host (answered, never reached). */ /** Fixture thumbnail host (answered, never reached). */
export const THUMB_HOST = 'qa-fixture.mapillary.com'; export const THUMB_HOST = 'qa-fixture.mapillary.com';
@@ -181,6 +181,18 @@ export function answerMapillaryRequest({ method, url, images }) {
: []; : [];
return { ...json(200, { data }), known: true }; return { ...json(200, { data }), known: true };
} }
if (q.has('lat') && q.has('lng')) {
const at = { lat: Number(q.get('lat')), lon: Number(q.get('lng')) };
const radius = Math.min(50, Number(q.get('radius')) || 50);
const limit = Number(q.get('limit')) || 10;
// In no particular order, as the real API answers.
const data = photos
.filter((image) => metresApart(at, image) <= radius)
.reverse()
.slice(0, limit)
.map((image) => withFields(imageRecord(image), fields));
return { ...json(200, { data }), known: true };
}
if (q.has('s2')) return { ...json(200, { data: [] }), known: true }; if (q.has('s2')) return { ...json(200, { data: [] }), known: true };
return { return {
...json(400, { error: 'unsupported images query' }), ...json(400, { error: 'unsupported images query' }),
+1 -1
View File
@@ -28,7 +28,7 @@ export const PNX_PARK = Object.freeze({
height: 700, height: 700,
pitch: -1.4, pitch: -1.4,
}); });
const PNX_CREATOR = 'Fixture Mapper'; export const PNX_CREATOR = 'Fixture Mapper';
const PNX_SPACING_M = 10; const PNX_SPACING_M = 10;
const METRES_PER_DEG_LON = 111_320 * Math.cos((PNX_LINE.lat * Math.PI) / 180); const METRES_PER_DEG_LON = 111_320 * Math.cos((PNX_LINE.lat * Math.PI) / 180);
const API = 'https://api.panoramax.xyz/api'; const API = 'https://api.panoramax.xyz/api';
+33 -39
View File
@@ -46,6 +46,9 @@
"scripts/qa-voice-auth-focus.mjs", "scripts/qa-voice-auth-focus.mjs",
"src/codexOauthRealtime.test.mjs", "src/codexOauthRealtime.test.mjs",
"src/voice/cloudVoiceAuth.test.mjs", "src/voice/cloudVoiceAuth.test.mjs",
"scripts/qa-panel-resize.mjs",
"scripts/qa-panelDrag.mjs",
"src/tooling/panelResizeQa.test.mjs",
"scripts/qa-terrain-429.mjs", "scripts/qa-terrain-429.mjs",
"src/app/application.js", "src/app/application.js",
"src/app/application.test.mjs", "src/app/application.test.mjs",
@@ -93,7 +96,6 @@
"server/providers/space/launch-library.js", "server/providers/space/launch-library.js",
"src/data/spaceProviderRequests.js", "src/data/spaceProviderRequests.js",
"src/tooling/spaceProviders.test.mjs", "src/tooling/spaceProviders.test.mjs",
"src/tooling/ll2Integration.test.mjs",
"server/providers/terrain.js", "server/providers/terrain.js",
"server/providers/traffic.js", "server/providers/traffic.js",
"server/providers/firms.js", "server/providers/firms.js",
@@ -112,8 +114,6 @@
"server/providers/cctv/catalog.js", "server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js", "server/providers/cctv/lithuania.js",
"src/data/cctvLithuania.test.mjs", "src/data/cctvLithuania.test.mjs",
"server/providers/cctv/taiwan.js",
"src/data/cctvTaiwan.test.mjs",
"server/providers/cctv/constants.js", "server/providers/cctv/constants.js",
"server/providers/cctv/media.js", "server/providers/cctv/media.js",
"server/providers/cctv/normalize.js", "server/providers/cctv/normalize.js",
@@ -181,6 +181,7 @@
"src/ui/panelRails.js", "src/ui/panelRails.js",
"src/ui/leftPanelRail.js", "src/ui/leftPanelRail.js",
"src/ui/rightPanelRail.js", "src/ui/rightPanelRail.js",
"src/ui/panelResize.test.mjs",
"src/ui/panelMeasurement.js", "src/ui/panelMeasurement.js",
"src/ui/panelRailGeometry.js", "src/ui/panelRailGeometry.js",
"src/ui/panelRails.test.mjs", "src/ui/panelRails.test.mjs",
@@ -190,10 +191,7 @@
"src/ui/visualInput.js", "src/ui/visualInput.js",
"src/ui/visualInput.test.mjs", "src/ui/visualInput.test.mjs",
"scripts/qa-visual-input.mjs", "scripts/qa-visual-input.mjs",
"scripts/qa-segmented-controls.mjs",
"src/ui/displayControls.js", "src/ui/displayControls.js",
"src/ui/segmentedControl.test.mjs",
"src/ui/styles/segmented-control.css",
"src/ui/displayControls.test.mjs", "src/ui/displayControls.test.mjs",
"src/ui/cameraOrientationControls.js", "src/ui/cameraOrientationControls.js",
"src/ui/cameraOrientationControls.test.mjs", "src/ui/cameraOrientationControls.test.mjs",
@@ -286,7 +284,6 @@
"src/ui/applicationShell.js", "src/ui/applicationShell.js",
"src/ui/panelLayoutController.js", "src/ui/panelLayoutController.js",
"src/ui/panelPositionControls.js", "src/ui/panelPositionControls.js",
"src/ui/panelPositionControls.test.mjs",
"src/ui/recordingControls.js", "src/ui/recordingControls.js",
"src/ui/shellElements.js", "src/ui/shellElements.js",
"src/ui/shellFeedback.js", "src/ui/shellFeedback.js",
@@ -304,7 +301,6 @@
"src/ui/styles/status.css", "src/ui/styles/status.css",
"src/ui/styles/layers.css", "src/ui/styles/layers.css",
"src/ui/styles/controls.css", "src/ui/styles/controls.css",
"src/ui/styles/slider.css",
"src/ui/styles/cctv.css", "src/ui/styles/cctv.css",
"src/ui/styles/foundation.css", "src/ui/styles/foundation.css",
"src/ui/styles/first-run.css", "src/ui/styles/first-run.css",
@@ -449,9 +445,7 @@
"src/data/satellites.js", "src/data/satellites.js",
"src/data/rocketLaunches.js", "src/data/rocketLaunches.js",
"src/layers/satellites/source.test.mjs", "src/layers/satellites/source.test.mjs",
"src/layers/satellites/stale.test.mjs",
"src/layers/launches/source.test.mjs", "src/layers/launches/source.test.mjs",
"src/layers/launches/ingestion.test.mjs",
"src/layers/installations/lifecycle.js", "src/layers/installations/lifecycle.js",
"src/layers/installations/viewport.js", "src/layers/installations/viewport.js",
"src/layers/installations/controls.js", "src/layers/installations/controls.js",
@@ -556,14 +550,11 @@
"src/data/cctvWarendorf.test.mjs", "src/data/cctvWarendorf.test.mjs",
"src/data/cctvCalgary.test.mjs", "src/data/cctvCalgary.test.mjs",
"src/data/cctvCataloniaSource.test.mjs", "src/data/cctvCataloniaSource.test.mjs",
"src/data/cctvHk.test.mjs",
"src/data/cctvVegvesen.test.mjs", "src/data/cctvVegvesen.test.mjs",
"src/data/cctvNyc.test.mjs", "src/data/cctvNyc.test.mjs",
"src/data/cctvNswSource.test.mjs", "src/data/cctvNswSource.test.mjs",
"src/data/cctvTxdotSource.test.mjs", "src/data/cctvTxdotSource.test.mjs",
"src/layers/cctv/source.test.mjs", "src/layers/cctv/source.test.mjs",
"src/layers/cctv/frames.test.mjs",
"src/layers/cctv/rendering.test.mjs",
"src/data/alprCameras.js", "src/data/alprCameras.js",
"src/data/alprCameras.test.mjs", "src/data/alprCameras.test.mjs",
"src/data/dataCredits.test.mjs", "src/data/dataCredits.test.mjs",
@@ -644,7 +635,6 @@
"src/voice/control.js", "src/voice/control.js",
"src/voice/realtimeBackend.js", "src/voice/realtimeBackend.js",
"src/voice/realtimeBackend.test.mjs", "src/voice/realtimeBackend.test.mjs",
"src/agent/worldPacket.test.mjs",
"src/voice/layerSummary.js", "src/voice/layerSummary.js",
"build/application-html.js", "build/application-html.js",
"src/app/sourceSlot.js", "src/app/sourceSlot.js",
@@ -700,7 +690,6 @@
"src/ui/shareRestoration.js", "src/ui/shareRestoration.js",
"src/ui/visualSettings.js", "src/ui/visualSettings.js",
"src/ui/panelChrome.js", "src/ui/panelChrome.js",
"src/ui/panelChrome.radioOwnership.test.mjs",
"src/testSupport/readShellSource.mjs", "src/testSupport/readShellSource.mjs",
"src/ui/stateOwners.test.mjs", "src/ui/stateOwners.test.mjs",
"src/layers/flights/records.js", "src/layers/flights/records.js",
@@ -917,32 +906,27 @@
"src/ui/streetLevelPresentation.test.mjs", "src/ui/streetLevelPresentation.test.mjs",
"src/app/layers/streetLevel.js", "src/app/layers/streetLevel.js",
"src/tooling/mapillaryProvider.test.mjs", "src/tooling/mapillaryProvider.test.mjs",
"src/app/layers/streetLevel.test.mjs",
"src/data/idSwitches.js",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/providers/mapillary/provider.test.mjs",
"src/layers/streetLevel/params.js",
"src/layers/streetLevel/params.test.mjs",
"src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/pickRouter.test.mjs",
"src/layers/streetLevel/providerSwitches.test.mjs",
"src/layers/streetLevel/registry.js",
"src/layers/streetLevel/registry.test.mjs",
"src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/uiState.test.mjs",
"src/layers/streetLevel/providers/mapillary/source.test.mjs", "src/layers/streetLevel/providers/mapillary/source.test.mjs",
"src/streetLevelMarkup.test.mjs", "src/streetLevelMarkup.test.mjs",
"src/layers/streetLevel/index.js", "src/layers/streetLevel/index.js",
"src/layers/streetLevel/policy.js", "src/layers/streetLevel/policy.js",
"src/layers/streetLevel/filter.js", "src/layers/streetLevel/filter.js",
"src/layers/streetLevel/registry.js",
"src/layers/streetLevel/params.js",
"src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/groundCast.js",
"src/layers/streetLevel/meshSampler.js",
"src/layers/streetLevel/view.js", "src/layers/streetLevel/view.js",
"src/layers/streetLevel/marker.js", "src/layers/streetLevel/marker.js",
"src/layers/streetLevel/cameraFraming.js", "src/layers/streetLevel/cameraFollow.js",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/state.js", "src/layers/streetLevel/state.js",
"src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/providers/mapillary/policy.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/providers/mapillary/coverage.js",
"src/layers/streetLevel/providers/mapillary/sequences.js",
"src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/glyphs.js",
"src/layers/streetLevel/providers/mapillary/decode.js", "src/layers/streetLevel/providers/mapillary/decode.js",
"src/layers/streetLevel/tileMath.js", "src/layers/streetLevel/tileMath.js",
@@ -955,6 +939,7 @@
"src/layers/streetLevel/providers/google/viewer.js", "src/layers/streetLevel/providers/google/viewer.js",
"src/layers/streetLevel/providers/google/mapsLoader.js", "src/layers/streetLevel/providers/google/mapsLoader.js",
"src/layers/streetLevel/groundClick.test.mjs", "src/layers/streetLevel/groundClick.test.mjs",
"src/app/layers/streetLevel.test.mjs",
"src/layers/streetLevel/providers/google/provider.test.mjs", "src/layers/streetLevel/providers/google/provider.test.mjs",
"src/layers/streetLevel/providers/google/viewer.test.mjs", "src/layers/streetLevel/providers/google/viewer.test.mjs",
"src/layers/streetLevel/providers/google/mapsLoader.test.mjs", "src/layers/streetLevel/providers/google/mapsLoader.test.mjs",
@@ -964,6 +949,8 @@
"src/layers/streetLevel/providers/kartaview/decode.js", "src/layers/streetLevel/providers/kartaview/decode.js",
"src/layers/streetLevel/providers/kartaview/viewer.js", "src/layers/streetLevel/providers/kartaview/viewer.js",
"src/layers/streetLevel/panorama.js", "src/layers/streetLevel/panorama.js",
"src/layers/streetLevel/lineCoverage.js",
"src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/providers/kartaview/policy.test.mjs", "src/layers/streetLevel/providers/kartaview/policy.test.mjs",
"src/layers/streetLevel/providers/kartaview/decode.test.mjs", "src/layers/streetLevel/providers/kartaview/decode.test.mjs",
"src/layers/streetLevel/providers/kartaview/source.test.mjs", "src/layers/streetLevel/providers/kartaview/source.test.mjs",
@@ -992,6 +979,8 @@
"src/testSupport/kartaViewFakes.mjs", "src/testSupport/kartaViewFakes.mjs",
"src/testSupport/googleStreetViewFakes.mjs", "src/testSupport/googleStreetViewFakes.mjs",
"server/providers/mapillary.js", "server/providers/mapillary.js",
"server/providers/mapillary/routes.js",
"server/providers/mapillary/constants.js",
"server/providers/mapillary/tiles.js", "server/providers/mapillary/tiles.js",
"server/providers/mapillary/trim.js", "server/providers/mapillary/trim.js",
"src/layers/streetLevel/tileMath.test.mjs", "src/layers/streetLevel/tileMath.test.mjs",
@@ -1004,15 +993,23 @@
"scripts/fixtures/street-level/kartaView.mjs", "scripts/fixtures/street-level/kartaView.mjs",
"scripts/fixtures/street-level/panoramax.mjs", "scripts/fixtures/street-level/panoramax.mjs",
"src/layers/streetLevel/filter.test.mjs", "src/layers/streetLevel/filter.test.mjs",
"src/layers/streetLevel/registry.test.mjs",
"src/layers/streetLevel/params.test.mjs",
"src/layers/streetLevel/pickRouter.test.mjs",
"src/layers/streetLevel/uiState.test.mjs",
"src/layers/streetLevel/groundCast.test.mjs",
"src/layers/streetLevel/meshSampler.test.mjs",
"src/layers/streetLevel/view.test.mjs", "src/layers/streetLevel/view.test.mjs",
"src/layers/streetLevel/providers/mapillary/mapillary.test.mjs", "src/layers/streetLevel/providers/mapillary/provider.test.mjs",
"src/layers/streetLevel/providers/mapillary/decode.test.mjs", "src/layers/streetLevel/providers/mapillary/decode.test.mjs",
"src/layers/streetLevel/providers/mapillary/coverage.test.mjs",
"src/layers/streetLevel/providers/mapillary/coverageFixture.mjs", "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
"src/layers/streetLevel/cameraFraming.test.mjs", "src/layers/streetLevel/cameraFollow.test.mjs",
"src/ui/streetLevelControls.test.mjs", "src/ui/streetLevelControls.test.mjs",
"src/ui/panelDock.test.mjs",
"src/layers/streetLevel/marker.test.mjs", "src/layers/streetLevel/marker.test.mjs",
"src/layers/streetLevel/viewerHost.test.mjs", "src/layers/streetLevel/viewerHost.test.mjs",
"src/layers/streetLevel/sequenceCones.test.mjs", "src/layers/streetLevel/providers/mapillary/sequences.test.mjs",
"src/layers/streetLevel/selection.test.mjs", "src/layers/streetLevel/selection.test.mjs",
"src/layers/streetLevel/index.test.mjs", "src/layers/streetLevel/index.test.mjs",
"scripts/qa-overpass-offload.mjs", "scripts/qa-overpass-offload.mjs",
@@ -1029,7 +1026,6 @@
"scripts/qa-context-arrivals.mjs", "scripts/qa-context-arrivals.mjs",
"src/tools/catalog.test.mjs", "src/tools/catalog.test.mjs",
"src/tools/area.test.mjs", "src/tools/area.test.mjs",
"src/tools/results.test.mjs",
"src/tools/queries/queries.test.mjs", "src/tools/queries/queries.test.mjs",
"src/tools/mcp/mcp.test.mjs", "src/tools/mcp/mcp.test.mjs",
"src/tools/localServer.test.mjs", "src/tools/localServer.test.mjs",
@@ -1066,7 +1062,5 @@
"src/ui/flyToDataSource.test.mjs", "src/ui/flyToDataSource.test.mjs",
"scripts/assemble-changelog.mjs", "scripts/assemble-changelog.mjs",
"src/tooling/changelogFragments.test.mjs", "src/tooling/changelogFragments.test.mjs",
"src/data/gbfsProxyRateLimit.test.mjs", "src/data/gbfsProxyRateLimit.test.mjs"
"src/data/routeSegment.test.mjs",
"src/terrainHeightsBounds.test.mjs"
] ]
+54 -79
View File
@@ -114,11 +114,7 @@
"exports": ["./server/providers/terrain"], "exports": ["./server/providers/terrain"],
"modules": [ "modules": [
"server/providers/terrain.js", "server/providers/terrain.js",
"src/data/terrainHeightsProxy.js", "src/data/terrainHeightsProxy.js"
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js",
"server/providers/common/same-site.js",
"src/localRequestGate.mjs"
], ],
"external": [] "external": []
}, },
@@ -187,13 +183,10 @@
"exports": ["./server/providers/cctv"], "exports": ["./server/providers/cctv"],
"modules": [ "modules": [
"server/providers/cctv.js", "server/providers/cctv.js",
"server/providers/common/same-site.js",
"src/localRequestGate.mjs",
"server/providers/cctv/cap.js", "server/providers/cctv/cap.js",
"server/providers/cctv/groundHeights.js", "server/providers/cctv/groundHeights.js",
"server/providers/cctv/catalog.js", "server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js", "server/providers/cctv/lithuania.js",
"server/providers/cctv/taiwan.js",
"server/providers/cctv/constants.js", "server/providers/cctv/constants.js",
"server/providers/cctv/media.js", "server/providers/cctv/media.js",
"server/providers/cctv/normalize.js", "server/providers/cctv/normalize.js",
@@ -217,6 +210,8 @@
"exports": ["./server/providers/mapillary"], "exports": ["./server/providers/mapillary"],
"modules": [ "modules": [
"server/providers/mapillary.js", "server/providers/mapillary.js",
"server/providers/mapillary/routes.js",
"server/providers/mapillary/constants.js",
"server/providers/mapillary/tiles.js", "server/providers/mapillary/tiles.js",
"server/providers/mapillary/trim.js", "server/providers/mapillary/trim.js",
"server/providers/common/same-site.js", "server/providers/common/same-site.js",
@@ -424,7 +419,6 @@
"src/ui/visualInput.js", "src/ui/visualInput.js",
"src/ui/applicationShortcuts.js", "src/ui/applicationShortcuts.js",
"src/ui/styleParameters.js", "src/ui/styleParameters.js",
"src/ui/slider.js",
"src/i18n/index.js", "src/i18n/index.js",
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/es.json", "src/i18n/locales/es.json",
@@ -434,7 +428,7 @@
}, },
"display-controls": { "display-controls": {
"exports": ["./ui/display"], "exports": ["./ui/display"],
"modules": ["src/ui/displayControls.js", "src/ui/segmentedControl.js"], "modules": ["src/ui/displayControls.js"],
"external": [] "external": []
}, },
"visual-effects": { "visual-effects": {
@@ -483,7 +477,6 @@
"src/ui/weatherPanel.js", "src/ui/weatherPanel.js",
"src/ui/railCards.js", "src/ui/railCards.js",
"src/ui/railCardBlocks.js", "src/ui/railCardBlocks.js",
"src/ui/slider.js",
"src/ui/chipGroup.js", "src/ui/chipGroup.js",
"src/ui/rowList.js", "src/ui/rowList.js",
"src/ui/railTimeline.js", "src/ui/railTimeline.js",
@@ -705,7 +698,6 @@
"src/ui/contextSubscriptions.js", "src/ui/contextSubscriptions.js",
"src/ui/contextTransactions.js", "src/ui/contextTransactions.js",
"src/ui/displayControls.js", "src/ui/displayControls.js",
"src/ui/segmentedControl.js",
"src/ui/effects.js", "src/ui/effects.js",
"src/ui/frameRateMonitor.js", "src/ui/frameRateMonitor.js",
"src/ui/layerPanel.js", "src/ui/layerPanel.js",
@@ -728,6 +720,7 @@
"src/ui/panelLayoutController.js", "src/ui/panelLayoutController.js",
"src/ui/panelMeasurement.js", "src/ui/panelMeasurement.js",
"src/ui/panelPositionControls.js", "src/ui/panelPositionControls.js",
"src/ui/panelResize.js",
"src/ui/panelRailGeometry.js", "src/ui/panelRailGeometry.js",
"src/ui/panelRails.js", "src/ui/panelRails.js",
"src/ui/radio.js", "src/ui/radio.js",
@@ -744,7 +737,6 @@
"src/ui/shellElements.js", "src/ui/shellElements.js",
"src/ui/shellFeedback.js", "src/ui/shellFeedback.js",
"src/ui/styleParameters.js", "src/ui/styleParameters.js",
"src/ui/slider.js",
"src/ui/surfaceKeyboard.js", "src/ui/surfaceKeyboard.js",
"src/ui/uiLifetime.js", "src/ui/uiLifetime.js",
"src/ui/visualEffects.js", "src/ui/visualEffects.js",
@@ -761,7 +753,6 @@
"src/ui/shellFacade.js", "src/ui/shellFacade.js",
"src/ui/streetLevelControls.js", "src/ui/streetLevelControls.js",
"src/ui/streetLevelPresentation.js", "src/ui/streetLevelPresentation.js",
"src/layers/streetLevel/policy.js",
"src/ui/localSdrControls.js", "src/ui/localSdrControls.js",
"src/layers/localAdsb/feedNames.js", "src/layers/localAdsb/feedNames.js",
"src/ui/localSdrPresentation.js", "src/ui/localSdrPresentation.js",
@@ -1049,7 +1040,6 @@
"src/layers/vessels/tracking.js", "src/layers/vessels/tracking.js",
"src/data/iconOrientation.js", "src/data/iconOrientation.js",
"src/data/vesselLabels.js", "src/data/vesselLabels.js",
"src/data/vesselTypes.js",
"src/layers/vessels/records.js", "src/layers/vessels/records.js",
"src/layers/vessels/recordPolicy.js", "src/layers/vessels/recordPolicy.js",
"src/layers/vessels/snapshotRenderer.js", "src/layers/vessels/snapshotRenderer.js",
@@ -1388,13 +1378,15 @@
], ],
"modules": [ "modules": [
"src/layers/streetLevel/index.js", "src/layers/streetLevel/index.js",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/providers/mapillary/index.js", "src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js", "src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/cameraFraming.js", "src/layers/streetLevel/credits.js",
"src/layers/streetLevel/cameraFollow.js",
"src/layers/streetLevel/marker.js", "src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js", "src/layers/streetLevel/view.js",
"src/layers/streetLevel/uiState.js", "src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/groundCast.js",
"src/layers/streetLevel/meshSampler.js",
"src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/pickRouter.js",
"src/data/idSwitches.js", "src/data/idSwitches.js",
"src/layers/streetLevel/params.js", "src/layers/streetLevel/params.js",
@@ -1402,8 +1394,9 @@
"src/layers/streetLevel/filter.js", "src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js", "src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js", "src/layers/streetLevel/state.js",
"src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/providers/mapillary/policy.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/providers/mapillary/coverage.js",
"src/layers/streetLevel/providers/mapillary/sequences.js",
"src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/glyphs.js",
"src/layers/streetLevel/providers/mapillary/decode.js", "src/layers/streetLevel/providers/mapillary/decode.js",
"src/layers/streetLevel/providers/mapillary/coverageFixture.mjs", "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
@@ -1430,13 +1423,14 @@
"src/layers/streetLevel/imageSize.js", "src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js", "src/layers/streetLevel/tileCache.js",
"src/layers/streetLevel/panorama.js", "src/layers/streetLevel/panorama.js",
"src/layers/streetLevel/lineCoverage.js",
"src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/providers/mapillary/source.js", "src/layers/streetLevel/providers/mapillary/source.js",
"scripts/qa-street-level.mjs", "scripts/qa-street-level.mjs",
"src/i18n/index.js", "src/i18n/index.js",
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/es.json", "src/i18n/locales/es.json",
"src/i18n/locales/ru.json", "src/i18n/locales/ru.json"
"src/layers/streetLevel/providers/mapillary/policy.js"
], ],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"] "external": ["cesium", "pbf", "@mapbox/vector-tile", "mapillary-js"]
}, },
@@ -1634,15 +1628,7 @@
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/es.json", "src/i18n/locales/es.json",
"src/i18n/locales/ru.json", "src/i18n/locales/ru.json",
"src/ui/statusText.js", "src/ui/statusText.js"
"src/voice/providerCommands.js",
"src/voice/providerCapabilities.js",
"src/voice/geminiSession.js",
"src/voice/geminiAudio.js",
"src/voice/geminiCaptureWorklet.js",
"src/sources/httpBody.js",
"src/sources/requestDeadline.js",
"src/i18n/marker.js"
], ],
"external": [] "external": []
}, },
@@ -1855,7 +1841,6 @@
"src/data/trafficQueue.js", "src/data/trafficQueue.js",
"src/data/trailRenderer.js", "src/data/trailRenderer.js",
"src/data/vesselLabels.js", "src/data/vesselLabels.js",
"src/data/vesselTypes.js",
"src/firstRunExperience.js", "src/firstRunExperience.js",
"src/hud.js", "src/hud.js",
"src/hudLocality.js", "src/hudLocality.js",
@@ -2182,7 +2167,6 @@
"src/ui/contextSubscriptions.js", "src/ui/contextSubscriptions.js",
"src/ui/contextTransactions.js", "src/ui/contextTransactions.js",
"src/ui/displayControls.js", "src/ui/displayControls.js",
"src/ui/segmentedControl.js",
"src/ui/effects.js", "src/ui/effects.js",
"src/ui/frameRateMonitor.js", "src/ui/frameRateMonitor.js",
"src/ui/layerPanel.js", "src/ui/layerPanel.js",
@@ -2205,6 +2189,7 @@
"src/ui/panelLayoutController.js", "src/ui/panelLayoutController.js",
"src/ui/panelMeasurement.js", "src/ui/panelMeasurement.js",
"src/ui/panelPositionControls.js", "src/ui/panelPositionControls.js",
"src/ui/panelResize.js",
"src/ui/panelRailGeometry.js", "src/ui/panelRailGeometry.js",
"src/ui/panelRails.js", "src/ui/panelRails.js",
"src/ui/radio.js", "src/ui/radio.js",
@@ -2221,7 +2206,6 @@
"src/ui/shellElements.js", "src/ui/shellElements.js",
"src/ui/shellFeedback.js", "src/ui/shellFeedback.js",
"src/ui/styleParameters.js", "src/ui/styleParameters.js",
"src/ui/slider.js",
"src/ui/surfaceKeyboard.js", "src/ui/surfaceKeyboard.js",
"src/ui/uiLifetime.js", "src/ui/uiLifetime.js",
"src/ui/visualEffects.js", "src/ui/visualEffects.js",
@@ -2231,7 +2215,6 @@
"src/voice/commands.js", "src/voice/commands.js",
"src/voice/control.js", "src/voice/control.js",
"src/voice/gevActions.js", "src/voice/gevActions.js",
"src/agent/worldPacket.js",
"src/voice/speech.js", "src/voice/speech.js",
"src/ui/layerNames.js", "src/ui/layerNames.js",
"src/voice/earcon.js", "src/voice/earcon.js",
@@ -2425,22 +2408,24 @@
"src/ui/streetLevelControls.js", "src/ui/streetLevelControls.js",
"src/ui/streetLevelPresentation.js", "src/ui/streetLevelPresentation.js",
"src/layers/streetLevel/index.js", "src/layers/streetLevel/index.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/cameraFollow.js",
"src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/uiState.js", "src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/groundCast.js",
"src/layers/streetLevel/meshSampler.js",
"src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/params.js", "src/layers/streetLevel/params.js",
"src/layers/streetLevel/registry.js", "src/layers/streetLevel/registry.js",
"scripts/qa-street-level.mjs",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/cameraFraming.js",
"src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/filter.js", "src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js", "src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js", "src/layers/streetLevel/state.js",
"src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/providers/mapillary/policy.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/providers/mapillary/coverage.js",
"src/layers/streetLevel/providers/mapillary/sequences.js",
"src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/glyphs.js",
"src/layers/streetLevel/providers/mapillary/decode.js", "src/layers/streetLevel/providers/mapillary/decode.js",
"src/layers/streetLevel/providers/mapillary/coverageFixture.mjs", "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
@@ -2467,6 +2452,8 @@
"src/layers/streetLevel/imageSize.js", "src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js", "src/layers/streetLevel/tileCache.js",
"src/layers/streetLevel/panorama.js", "src/layers/streetLevel/panorama.js",
"src/layers/streetLevel/lineCoverage.js",
"src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/providers/mapillary/source.js", "src/layers/streetLevel/providers/mapillary/source.js",
"src/app/layers/streetLevel.js", "src/app/layers/streetLevel.js",
"src/layers/alpr/tileRecords.js", "src/layers/alpr/tileRecords.js",
@@ -2479,6 +2466,7 @@
"src/data/cameraArrival.js", "src/data/cameraArrival.js",
"src/layers/alpr/floors.js", "src/layers/alpr/floors.js",
"src/data/militaryNames.js", "src/data/militaryNames.js",
"src/sources/requestDeadline.js",
"src/data/local_data/osm_military_names/names.json", "src/data/local_data/osm_military_names/names.json",
"src/layers/installations/namedMarkers.js", "src/layers/installations/namedMarkers.js",
"src/data/infrastructureOverlayEntry.js", "src/data/infrastructureOverlayEntry.js",
@@ -2503,12 +2491,12 @@
"src/layers/airQuality/model.js", "src/layers/airQuality/model.js",
"src/layers/airQuality/source.js", "src/layers/airQuality/source.js",
"src/ui/statusText.js", "src/ui/statusText.js",
"src/layers/streetLevel/providers/mapillary/policy.js", "src/scenes/cameraLens.js",
"src/voice/providerCommands.js", "src/director/lens.js",
"src/voice/providerCapabilities.js", "src/vcam/controller.js",
"src/voice/geminiSession.js", "src/vcam/rig.js",
"src/voice/geminiAudio.js", "src/vcam/qr.js",
"src/voice/geminiCaptureWorklet.js" "src/ui/vcamPanel.js"
], ],
"external": [ "external": [
"hls.js", "hls.js",
@@ -2647,7 +2635,6 @@
"src/data/trafficQueue.js", "src/data/trafficQueue.js",
"src/data/trailRenderer.js", "src/data/trailRenderer.js",
"src/data/vesselLabels.js", "src/data/vesselLabels.js",
"src/data/vesselTypes.js",
"src/keylessGeocoder.js", "src/keylessGeocoder.js",
"src/layers/aircraft/classification.js", "src/layers/aircraft/classification.js",
"src/layers/alpr/index.js", "src/layers/alpr/index.js",
@@ -3003,22 +2990,24 @@
"src/layers/recentImagery/thumbnails.js", "src/layers/recentImagery/thumbnails.js",
"src/maps/imageryHost.js", "src/maps/imageryHost.js",
"src/layers/streetLevel/index.js", "src/layers/streetLevel/index.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/cameraFollow.js",
"src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/uiState.js", "src/layers/streetLevel/uiState.js",
"src/layers/streetLevel/groundCast.js",
"src/layers/streetLevel/meshSampler.js",
"src/layers/streetLevel/pickRouter.js", "src/layers/streetLevel/pickRouter.js",
"src/layers/streetLevel/params.js", "src/layers/streetLevel/params.js",
"src/layers/streetLevel/registry.js", "src/layers/streetLevel/registry.js",
"scripts/qa-street-level.mjs",
"src/layers/streetLevel/credits.js",
"src/layers/streetLevel/providers/mapillary/index.js",
"src/layers/streetLevel/viewerHost.js",
"src/layers/streetLevel/cameraFraming.js",
"src/layers/streetLevel/marker.js",
"src/layers/streetLevel/view.js",
"src/layers/streetLevel/filter.js", "src/layers/streetLevel/filter.js",
"src/layers/streetLevel/policy.js", "src/layers/streetLevel/policy.js",
"src/layers/streetLevel/state.js", "src/layers/streetLevel/state.js",
"src/layers/streetLevel/lineCoverage.js", "src/layers/streetLevel/providers/mapillary/policy.js",
"src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/providers/mapillary/coverage.js",
"src/layers/streetLevel/providers/mapillary/sequences.js",
"src/layers/streetLevel/glyphs.js", "src/layers/streetLevel/glyphs.js",
"src/layers/streetLevel/providers/mapillary/decode.js", "src/layers/streetLevel/providers/mapillary/decode.js",
"src/layers/streetLevel/providers/mapillary/coverageFixture.mjs", "src/layers/streetLevel/providers/mapillary/coverageFixture.mjs",
@@ -3045,6 +3034,8 @@
"src/layers/streetLevel/imageSize.js", "src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js", "src/layers/streetLevel/tileCache.js",
"src/layers/streetLevel/panorama.js", "src/layers/streetLevel/panorama.js",
"src/layers/streetLevel/lineCoverage.js",
"src/layers/streetLevel/sequenceCones.js",
"src/layers/streetLevel/providers/mapillary/source.js", "src/layers/streetLevel/providers/mapillary/source.js",
"src/app/layers/streetLevel.js", "src/app/layers/streetLevel.js",
"src/layers/alpr/tileRecords.js", "src/layers/alpr/tileRecords.js",
@@ -3057,6 +3048,7 @@
"src/data/cameraArrival.js", "src/data/cameraArrival.js",
"src/layers/alpr/floors.js", "src/layers/alpr/floors.js",
"src/data/militaryNames.js", "src/data/militaryNames.js",
"src/sources/requestDeadline.js",
"src/data/local_data/osm_military_names/names.json", "src/data/local_data/osm_military_names/names.json",
"src/layers/installations/namedMarkers.js", "src/layers/installations/namedMarkers.js",
"src/data/infrastructureOverlayEntry.js", "src/data/infrastructureOverlayEntry.js",
@@ -3074,8 +3066,7 @@
"src/layers/airQuality/model.js", "src/layers/airQuality/model.js",
"src/layers/airQuality/source.js", "src/layers/airQuality/source.js",
"src/ui/statusText.js", "src/ui/statusText.js",
"src/ui/layerNames.js", "src/ui/layerNames.js"
"src/layers/streetLevel/providers/mapillary/policy.js"
], ],
"external": [ "external": [
"hls.js", "hls.js",
@@ -3215,13 +3206,11 @@
"src/ui/applicationShortcuts.js", "src/ui/applicationShortcuts.js",
"src/ui/effects.js", "src/ui/effects.js",
"src/ui/styleParameters.js", "src/ui/styleParameters.js",
"src/ui/slider.js",
"src/ui/uiLifetime.js", "src/ui/uiLifetime.js",
"src/ui/visualEffects.js", "src/ui/visualEffects.js",
"src/ui/visualInput.js", "src/ui/visualInput.js",
"src/ui/visualPresets.js", "src/ui/visualPresets.js",
"src/ui/visualSettings.js", "src/ui/visualSettings.js",
"src/ui/segmentedControl.js",
"src/i18n/index.js", "src/i18n/index.js",
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/es.json", "src/i18n/locales/es.json",
@@ -3241,6 +3230,7 @@
"src/ui/panelLayoutController.js", "src/ui/panelLayoutController.js",
"src/ui/panelMeasurement.js", "src/ui/panelMeasurement.js",
"src/ui/panelPositionControls.js", "src/ui/panelPositionControls.js",
"src/ui/panelResize.js",
"src/ui/panelRailGeometry.js", "src/ui/panelRailGeometry.js",
"src/ui/panelRails.js", "src/ui/panelRails.js",
"src/ui/rightPanelRail.js", "src/ui/rightPanelRail.js",
@@ -3393,8 +3383,7 @@
"src/i18n/locale.js", "src/i18n/locale.js",
"src/i18n/locales/es.json", "src/i18n/locales/es.json",
"src/i18n/locales/ru.json", "src/i18n/locales/ru.json",
"src/ui/statusText.js", "src/ui/statusText.js"
"src/voice/providerCapabilities.js"
], ],
"external": [] "external": []
}, },
@@ -3799,7 +3788,6 @@
"src/tools/queries/maritime.js", "src/tools/queries/maritime.js",
"src/tools/queries/share.js", "src/tools/queries/share.js",
"src/data/idSwitches.js", "src/data/idSwitches.js",
"src/data/vesselTypes.js",
"src/data/layerState.js", "src/data/layerState.js",
"src/data/layerStateTokenReservations.json", "src/data/layerStateTokenReservations.json",
"src/sources/gbfsStations.js", "src/sources/gbfsStations.js",
@@ -3961,18 +3949,5 @@
"src/i18n/marker.js" "src/i18n/marker.js"
], ],
"external": [] "external": []
},
"agent-world-packet": {
"exports": ["./agent/world-packet"],
"modules": [
"src/agent/worldPacket.js",
"src/data/layerSnapshot.js",
"src/data/feedState.js",
"src/contextModePolicy.js",
"src/loadingFeedback.js",
"src/data/installationFeedback.js",
"src/i18n/marker.js"
],
"external": ["cesium"]
} }
} }
+1 -3
View File
@@ -326,10 +326,8 @@ async function main() {
'src/data/local_data/cctv_ground_heights/cctv_ground_heights.json', 'src/data/local_data/cctv_ground_heights/cctv_ground_heights.json',
); );
let sidecar = await loadSidecar(output); let sidecar = await loadSidecar(output);
// A cold catalog waits for its slowest pack (Tarktee gets 30 s), so allow
// more than that.
const response = await fetch(`${base}/api/cctv/sources`, { const response = await fetch(`${base}/api/cctv/sources`, {
signal: AbortSignal.timeout(60_000), signal: AbortSignal.timeout(30_000),
}); });
if (!response.ok) throw new Error(`Catalog HTTP ${response.status}`); if (!response.ok) throw new Error(`Catalog HTTP ${response.status}`);
const catalog = await response.json(); const catalog = await response.json();
+2 -2
View File
@@ -7,10 +7,10 @@ import fs from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
/** Console messages and failed requests kept per page. */ /** Console messages and failed requests kept per page. */
const EVIDENCE_LIMIT = 200; export const EVIDENCE_LIMIT = 200;
/** Cesium's console line when the render loop throws (CesiumWidget). */ /** Cesium's console line when the render loop throws (CesiumWidget). */
const RENDER_ERROR_PATTERN = /An error occurred while rendering/i; export const RENDER_ERROR_PATTERN = /An error occurred while rendering/i;
/** Mask tokens in a URL or message before it is printed or saved. */ /** Mask tokens in a URL or message before it is printed or saved. */
export function redact(text) { export function redact(text) {
+106 -241
View File
@@ -11,10 +11,8 @@
* exactly once per camera ACTIVATION (the §9.1 obstruction probe) and * exactly once per camera ACTIVATION (the §9.1 obstruction probe) and
* never again in steady state; shared mesh-floor sampling fires at most * never again in steady state; shared mesh-floor sampling fires at most
* once per coarse cell during the staggered geometry-load drain, and * once per coarse cell during the staggered geometry-load drain, and
* actually COMPLETES once tiles load in photoreal mode (>=1 real sample * actually COMPLETES once tiles load (>=1 real sample — the
* — the ceiling alone would pass trivially at Δ=0 if the snap never * ceiling alone would pass trivially at Δ=0 if the snap never finished),
* finished). Globe mode instead proves the rendered mount uses a real
* terrain height with zero mesh samples. Sampling
* stays flat while idle, and stays flat for non-positional pose edits. * stays flat while idle, and stays flat for non-positional pose edits.
* 2. Geometry contract: the 5-polyline frustum wireframe + far-cap plane * 2. Geometry contract: the 5-polyline frustum wireframe + far-cap plane
* exist for the active camera, the plane's corners coincide with the * exist for the active camera, the plane's corners coincide with the
@@ -141,56 +139,6 @@ function record(name, ok, detail) {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Each page.evaluate is bounded by puppeteer's `protocolTimeout` (default
// 180s). Waits never come close: they poll from Node (below). The headroom is
// for the few long evaluates, such as enabling the full ~3,700-camera catalog
// on a real GPU, and matches the other qa-*.mjs harnesses.
const PROTOCOL_TIMEOUT_MS = 300_000;
/**
* Polls an in-page predicate from Node, one short page.evaluate per tick,
* until it holds or the budget runs out. Used instead of page.waitForFunction
* for two reasons: its default rAF polling stops in a minimised or hidden
* headful window (timers keep running, rAF does not), and its result is one
* CDP call that protocolTimeout cuts off, while the headful drain budget
* reaches ~50 minutes. A predicate that throws fails the run instead of
* silently spending the budget.
* @param {import('puppeteer').Page} page
* @param {Function} predicate - In-page predicate.
* @param {object} opts
* @param {number} opts.timeoutMs - Overall budget.
* @param {number} [opts.intervalMs=250] - Delay between checks.
* @param {unknown[]} [opts.args=[]] - Arguments passed to the predicate.
* The predicate must return a boolean: its result crosses CDP by value.
* @returns {Promise<boolean>} True if the predicate held within the budget.
*/
async function waitForPredicate(
page,
predicate,
{ timeoutMs, intervalMs = 250, args = [] },
) {
// performance.now() is monotonic and doesn't advance while the machine
// sleeps, so neither a clock change nor a laptop sleep eats the budget.
const deadline = performance.now() + timeoutMs;
for (;;) {
try {
if (await page.evaluate(predicate, ...args)) return true;
} catch (err) {
// A navigation or Vite reload replaces the execution context: poll again.
if (
!/Execution context was destroyed|Cannot find context/.test(
err?.message ?? '',
)
) {
throw err;
}
}
const remaining = deadline - performance.now();
if (remaining <= 0) return false;
await sleep(Math.min(intervalMs, remaining));
}
}
// SwiftShader can spend tens of seconds servicing the hover drillPick emitted // SwiftShader can spend tens of seconds servicing the hover drillPick emitted
// by page.mouse.move(), before the LEFT_DOWN under test even runs. Position the // by page.mouse.move(), before the LEFT_DOWN under test even runs. Position the
// pointer while ADJUST is disabled, then re-enable it and explicitly render a // pointer while ADJUST is disabled, then re-enable it and explicitly render a
@@ -207,58 +155,29 @@ async function positionPointerForGizmoDrag(page, point, frameCount = 3) {
gev.dataManager.layers gev.dataManager.layers
.get('cctv') .get('cctv')
.module.setParams({ calibrationMode: true }); .module.setParams({ calibrationMode: true });
return (await window.__qaRenderFrames(count, 5000)) >= count; const scene = gev.viewer.scene;
}, frameCount); let rendered = 0;
} return new Promise((resolve) => {
let settled = false;
/** const finish = (complete) => {
* Saves a screenshot for human review. These are never a gate, so a capture if (settled) return;
* that fails (for example when the renderer stalls in a hidden headful window) settled = true;
* is logged instead of ending the run. clearTimeout(timer);
* @param {import('puppeteer').Page} page remove();
* @param {string} file resolve(complete);
* @param {string} label };
*/ const remove = scene.postRender.addEventListener(() => {
async function saveReviewShot(page, file, label) { rendered += 1;
try { if (rendered >= count) {
await page.screenshot({ path: file }); finish(true);
console.log(` screenshot (${label}) → ${path.relative(REPO_ROOT, file)}`); return;
} catch (err) { }
console.warn(
` screenshot skipped (${label}): ${path.relative(REPO_ROOT, file)}: ${err?.message ?? err}`,
);
}
}
/**
* Installs window.__qaRenderFrames(count, capMs) in the page: requests renders
* until `count` frames have passed scene.postRender or capMs runs out, and
* resolves with the number of frames rendered. The cap keeps a stalled
* renderer (headful window asleep or hidden) from hanging the CDP call.
* @param {import('puppeteer').Page} page
*/
function installRenderFramesHelper(page) {
return page.evaluate(() => {
window.__qaRenderFrames = (count, capMs) =>
new Promise((resolve) => {
const scene = window.__godsEyeView.viewer.scene;
let frames = 0;
const finish = () => {
clearTimeout(timer);
remove();
resolve(frames);
};
const remove = scene.postRender.addEventListener(() => {
if (++frames >= count) {
finish();
return;
}
scene.requestRender();
});
const timer = setTimeout(finish, capMs);
scene.requestRender(); scene.requestRender();
}); });
}); const timer = setTimeout(() => finish(false), 5000);
scene.requestRender();
});
}, frameCount);
} }
// In-page helper (stringified and re-defined inside each evaluate that needs // In-page helper (stringified and re-defined inside each evaluate that needs
@@ -361,21 +280,23 @@ const BEARING_SHIFT_SRC = `
* @returns {Promise<boolean>} True if tilesLoaded was observed within the timeout. * @returns {Promise<boolean>} True if tilesLoaded was observed within the timeout.
*/ */
function waitForTilesLoaded(page, timeoutMs = 15000) { function waitForTilesLoaded(page, timeoutMs = 15000) {
return waitForPredicate( return page
page, .waitForFunction(
() => { () => {
const scene = window.__godsEyeView.viewer.scene; const scene = window.__godsEyeView.viewer.scene;
const prims = scene.primitives; const prims = scene.primitives;
for (let i = 0; i < prims.length; i++) { for (let i = 0; i < prims.length; i++) {
const p = prims.get(i); const p = prims.get(i);
if (p && p.constructor && p.constructor.name === 'Cesium3DTileset') { if (p && p.constructor && p.constructor.name === 'Cesium3DTileset') {
return p.tilesLoaded === true; return p.tilesLoaded === true;
}
} }
} return true; // no tileset in the scene — nothing to wait for
return true; // no tileset in the scene — nothing to wait for },
}, { timeout: timeoutMs },
{ timeoutMs }, )
); .then(() => true)
.catch(() => false);
} }
/** /**
@@ -443,10 +364,6 @@ async function main() {
const chromeExecutable = findChromeExecutable(); const chromeExecutable = findChromeExecutable();
const browser = await puppeteer.launch({ const browser = await puppeteer.launch({
headless: HEADFUL ? false : 'new', headless: HEADFUL ? false : 'new',
protocolTimeout: PROTOCOL_TIMEOUT_MS,
// Talk CDP over a pipe, so no debugging port stays open on localhost for
// the length of a headful run.
pipe: true,
...(chromeExecutable ? { executablePath: chromeExecutable } : {}), ...(chromeExecutable ? { executablePath: chromeExecutable } : {}),
args: [ args: [
'--no-sandbox', '--no-sandbox',
@@ -454,7 +371,6 @@ async function main() {
...(HEADFUL ? [] : ['--use-gl=angle', '--use-angle=swiftshader']), ...(HEADFUL ? [] : ['--use-gl=angle', '--use-angle=swiftshader']),
'--disable-dev-shm-usage', '--disable-dev-shm-usage',
'--disable-web-security', '--disable-web-security',
'--disable-backgrounding-occluded-windows',
'--disable-background-timer-throttling', '--disable-background-timer-throttling',
'--disable-renderer-backgrounding', '--disable-renderer-backgrounding',
'--window-size=1280,800', '--window-size=1280,800',
@@ -481,18 +397,13 @@ async function main() {
}); });
console.log('Loading app...'); console.log('Loading app...');
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 }); await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
const appReady = await waitForPredicate( await page.waitForFunction(
page,
() => () =>
Boolean( window.__godsEyeView &&
window.__godsEyeView && window.__godsEyeView.viewer &&
window.__godsEyeView.viewer && window.__godsEyeView.dataManager,
window.__godsEyeView.dataManager, { timeout: 60000 },
),
{ timeoutMs: 60000 },
); );
if (!appReady) throw new Error('app did not initialise within 60s');
await installRenderFramesHelper(page);
// Let the initial fly-to Austin and first tiles settle. // Let the initial fly-to Austin and first tiles settle.
await sleep(4000); await sleep(4000);
@@ -564,15 +475,18 @@ async function main() {
console.log( console.log(
`Waiting for geometry-load queue to drain (N=${camCount}, budget ${Math.round(drainBudgetMs / 1000)}s)...`, `Waiting for geometry-load queue to drain (N=${camCount}, budget ${Math.round(drainBudgetMs / 1000)}s)...`,
); );
const drained = await waitForPredicate( const drained = await page
page, .waitForFunction(
() => { () => {
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; const mod =
const ui = mod.getUIState(); window.__godsEyeView.dataManager.layers.get('cctv').module;
return Boolean(ui.loading) && ui.loading.active === false; const ui = mod.getUIState();
}, return ui.loading && ui.loading.active === false;
{ timeoutMs: drainBudgetMs, intervalMs: 1000 }, },
); { timeout: drainBudgetMs },
)
.then(() => true)
.catch(() => false);
record( record(
`geometry-load queue drains within ${Math.round(drainBudgetMs / 1000)}s (N=${camCount})`, `geometry-load queue drains within ${Math.round(drainBudgetMs / 1000)}s (N=${camCount})`,
drained ? true : HEADFUL ? false : null, drained ? true : HEADFUL ? false : null,
@@ -661,87 +575,27 @@ async function main() {
// (existence, not just ceiling). The wait below tolerates the update-tick // (existence, not just ceiling). The wait below tolerates the update-tick
// latency of the completion pass (update interval is 10s). // latency of the completion pass (update interval is 10s).
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
const globeMode = await page.evaluate( console.log('Waiting for tiles + the one-shot completion pass...');
() => window.__godsEyeView.viewer.scene.globe?.show !== false, const tilesSeenLoaded = await waitForTilesLoaded(page, 45000);
); let sampleFloorOk = false;
if (globeMode) { if (tilesSeenLoaded) {
// Globe stacks intentionally perform no scene.sampleHeight query. sampleFloorOk = await page
// Require independently fetched DEM heights and the actual rendered .waitForFunction(
// mount, so a catalog/geoid fallback cannot turn zero samples into a pass.
console.log(
'Checking terrain-globe completion against live DEM heights...',
);
const terrain = await page.evaluate(async () => {
const camera = window.__godsEyeView.dataManager.layers
.get('cctv')
.module.getUIState().activeCamera;
const exact = `${camera.lon.toFixed(5)},${camera.lat.toFixed(5)}`;
const cell = `${camera.lon.toFixed(3)},${camera.lat.toFixed(3)}`;
const response = await fetch(
`/api/terrain/heights?points=${encodeURIComponent(`${exact};${cell}`)}`,
{ signal: AbortSignal.timeout(30000) },
);
const body = await response.json();
return { ok: response.ok, results: body.results };
});
const heights = terrain.results?.map((result) => result?.ellipsoid);
const terrainReady =
terrain.ok && heights?.length === 2 && heights.every(Number.isFinite);
const mountResolved =
terrainReady &&
(await waitForPredicate(
page,
(expected, base) => {
const { viewer, dataManager } = window.__godsEyeView;
const camera = dataManager.layers
.get('cctv')
.module.getUIState().activeCamera;
const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`);
const mount = ray?.polyline?.positions.getValue(
viewer.clock.currentTime,
)?.[0];
const height =
mount &&
viewer.scene.globe.ellipsoid.cartesianToCartographic(mount)
.height;
return (
Number.isFinite(camera.groundPriorM) &&
Math.abs(camera.groundPriorM - expected[0]) < 0.01 &&
Number.isFinite(height) &&
expected.some(
(ground) =>
Math.abs(height - ground - camera.mountHeightM) < 0.05,
) &&
window.__qaCounters.sampleHeight === base
);
},
{ timeoutMs: 30000, args: [heights, c0.sampleHeight] },
));
record(
'terrain-globe completion uses a real DEM height at the rendered mount without mesh samples',
Boolean(mountResolved),
`terrain=${JSON.stringify(heights)}, mesh sample Δ=${(await readCounters()).sampleHeight - c0.sampleHeight}`,
);
} else {
console.log('Waiting for tiles + the one-shot completion pass...');
const tilesSeenLoaded = await waitForTilesLoaded(page, 45000);
let sampleFloorOk = false;
if (tilesSeenLoaded) {
sampleFloorOk = await waitForPredicate(
page,
(base) => window.__qaCounters.sampleHeight - base >= 1, (base) => window.__qaCounters.sampleHeight - base >= 1,
{ timeoutMs: 30000, args: [c0.sampleHeight] }, { timeout: 30000 },
); c0.sampleHeight,
} )
const cFloor = await readCounters(); .then(() => true)
record( .catch(() => false);
'>=1 real ground sample once tilesLoaded observed (one-shot snap completed)',
tilesSeenLoaded ? sampleFloorOk : null,
tilesSeenLoaded
? `total real samples since enable=${cFloor.sampleHeight - c0.sampleHeight}`
: 'tilesLoaded never observed within 45s — floor not assessable this run',
);
} }
const cFloor = await readCounters();
record(
'>=1 real ground sample once tilesLoaded observed (one-shot snap completed)',
tilesSeenLoaded ? sampleFloorOk : null,
tilesSeenLoaded
? `total real samples since enable=${cFloor.sampleHeight - c0.sampleHeight}`
: 'tilesLoaded never observed within 45s — floor not assessable this run',
);
// Let the completion pass finish before the steady-state window: require // Let the completion pass finish before the steady-state window: require
// the sampleHeight counter quiet for 12s (> the 10s update interval, so // the sampleHeight counter quiet for 12s (> the 10s update interval, so
@@ -1504,7 +1358,18 @@ async function main() {
}, },
}); });
window.__qaCctvSiblingOwner = owner; window.__qaCctvSiblingOwner = owner;
const framesRendered = await window.__qaRenderFrames(3, 10000); await new Promise((resolve) => {
let frames = 0;
const remove = scene.postRender.addEventListener(() => {
if (++frames < 3) {
scene.requestRender();
return;
}
remove();
resolve();
});
scene.requestRender();
});
const rect = scene.canvas.getBoundingClientRect(); const rect = scene.canvas.getBoundingClientRect();
const picked = scene.pick(canvasPoint); const picked = scene.pick(canvasPoint);
const pickedId = picked?.id?.id ?? picked?.id ?? null; const pickedId = picked?.id?.id ?? picked?.id ?? null;
@@ -1517,33 +1382,26 @@ async function main() {
typeof pickedId === 'string' ? pickedId : (pickedId?.id ?? null), typeof pickedId === 'string' ? pickedId : (pickedId?.id ?? null),
ownerId: owner.id, ownerId: owner.id,
ownsExactObject: picked?.id === owner, ownsExactObject: picked?.id === owner,
framesRendered,
projectionDelta: Math.hypot( projectionDelta: Math.hypot(
projected.x - canvasPoint.x, projected.x - canvasPoint.x,
projected.y - canvasPoint.y, projected.y - canvasPoint.y,
), ),
}; };
}, emptyClickPoint); }, emptyClickPoint);
const siblingOwnsPick =
siblingTarget?.pickedId === 'qa-cctv-sibling-owner' &&
siblingTarget.ownsExactObject;
// No frame at all within the 10s cap points at a stalled renderer rather
// than at picking, though the harness can't rule out both. Fail it on the
// real-GPU sign-off path; leave it inconclusive under headless GL. A slow
// SwiftShader frame (1-2 of 3) still counts as a real miss.
const siblingRendererStalled =
siblingTarget && !siblingOwnsPick && siblingTarget.framesRendered === 0;
record( record(
'sibling test object owns its canvas pick', 'sibling test object owns its canvas pick',
!siblingTarget
? null
: siblingOwnsPick ||
(siblingRendererStalled && !HEADFUL ? null : false),
siblingTarget siblingTarget
? `${siblingRendererStalled ? 'renderer stalled: ' : ''}frames=${siblingTarget.framesRendered}/3 picked=${siblingTarget.pickedId} exactOwner=${siblingTarget.ownsExactObject} projectionΔ=${siblingTarget.projectionDelta}` ? siblingTarget.pickedId === 'qa-cctv-sibling-owner' &&
siblingTarget.ownsExactObject
: null,
siblingTarget
? `picked=${siblingTarget.pickedId} exactOwner=${siblingTarget.ownsExactObject} projectionΔ=${siblingTarget.projectionDelta}`
: 'no previously verified empty canvas ray was available', : 'no previously verified empty canvas ray was available',
); );
if (siblingOwnsPick) { if (
siblingTarget?.pickedId === 'qa-cctv-sibling-owner' &&
siblingTarget.ownsExactObject
) {
await page.mouse.click(siblingTarget.x, siblingTarget.y); await page.mouse.click(siblingTarget.x, siblingTarget.y);
await sleep(250); await sleep(250);
} }
@@ -1568,7 +1426,8 @@ async function main() {
}); });
record( record(
'sibling canvas click passes through without CCTV selection or deselection', 'sibling canvas click passes through without CCTV selection or deselection',
siblingOwnsPick siblingTarget?.pickedId === 'qa-cctv-sibling-owner' &&
siblingTarget.ownsExactObject
? siblingClick.activeId === clickEvidenceSetup.activeId && ? siblingClick.activeId === clickEvidenceSetup.activeId &&
siblingClick.transitions === siblingClick.baselineTransitions && siblingClick.transitions === siblingClick.baselineTransitions &&
siblingClick.focusEvents === 0 && siblingClick.focusEvents === 0 &&
@@ -1767,7 +1626,10 @@ async function main() {
); );
const viewshedShot = path.join(SHOTS_DIR, 'cctv-v3-viewshed.png'); const viewshedShot = path.join(SHOTS_DIR, 'cctv-v3-viewshed.png');
await saveReviewShot(page, viewshedShot, 'visual review only'); await page.screenshot({ path: viewshedShot });
console.log(
` screenshot (visual review only) → ${path.relative(REPO_ROOT, viewshedShot)}`,
);
// ========================================================================= // =========================================================================
// Group 7: calibration gizmo (v3 design §3c — ADJUST mode + drag) // Group 7: calibration gizmo (v3 design §3c — ADJUST mode + drag)
@@ -2101,7 +1963,10 @@ async function main() {
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
await sleep(1000); await sleep(1000);
const shot = path.join(SHOTS_DIR, 'cctv-v2-active.png'); const shot = path.join(SHOTS_DIR, 'cctv-v2-active.png');
await saveReviewShot(page, shot, 'visual review only, not a gate'); await page.screenshot({ path: shot });
console.log(
` screenshot (visual review only, not a gate) → ${path.relative(REPO_ROOT, shot)}`,
);
// No console errors during the whole exercise. // No console errors during the whole exercise.
record( record(
+481
View File
@@ -0,0 +1,481 @@
#!/usr/bin/env node
/**
* Browser QA for the floating CCTV panel: lift, resize from every handle,
* minimum size, reload, and dock again. `--fail-on-retry` (or
* QA_FAIL_ON_RETRY=1) fails on any header-press retry.
*/
import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';
import { RESIZE_DIRECTIONS, resizeBox } from '../src/ui/panelResize.js';
import {
describePress,
dockPanelByDoubleClick,
dragPointer,
liftPanelByHeader,
nextFrames,
} from './qa-panelDrag.mjs';
import {
hookRenderErrors,
readRenderErrors,
saveFailureArtifacts,
watchPage,
} from './qa-browserEvidence.mjs';
export const PANEL_ID = 'cctv-panel';
export const STORAGE_KEY = `godsEyeView.v8.panelPos.${PANEL_ID}`;
export const MIN_SIZE = { width: 300, height: 160 };
export const ARTIFACT_DIR = 'qa-artifacts/panel-resize';
const VIEWPORT = { width: 1400, height: 900 };
const EDGE_BY_SIDE = { n: 'top', s: 'bottom', e: 'right', w: 'left' };
/** Box edges a resize in `dir` must leave exactly where they were. */
export function pinnedEdges(dir) {
return Object.entries(EDGE_BY_SIDE)
.filter(([side]) => !dir.includes(side))
.map(([, edge]) => edge);
}
/** Pointer travel that grows a panel by `amount` on every edge named in `dir`. */
export function growthDelta(dir, amount) {
return {
dx: dir.includes('e') ? amount : dir.includes('w') ? -amount : 0,
dy: dir.includes('s') ? amount : dir.includes('n') ? -amount : 0,
};
}
/**
* Viewport point inside the handle for `dir`, given the panel's client rect.
* Edge strips straddle the border by 3px; corners and the grip sit inside.
*/
export function handlePoint(rect, dir) {
const inset = dir.length === 2 ? 4 : 1;
const x = dir.includes('w')
? rect.left + inset
: dir.includes('e')
? rect.right - inset
: rect.left + rect.width / 2;
const y = dir.includes('n')
? rect.top + inset
: dir.includes('s')
? rect.bottom - inset
: rect.top + rect.height / 2;
return { x, y };
}
/** Pinned edges that moved during a resize in `dir`. */
export function driftedEdges(before, after, dir, tolerance = 1.5) {
const edges = (box) => ({
left: box.left,
top: box.top,
right: box.left + box.width,
bottom: box.top + box.height,
});
const a = edges(before);
const b = edges(after);
return pinnedEdges(dir).filter(
(edge) => Math.abs(a[edge] - b[edge]) > tolerance,
);
}
function near(actual, expected, tolerance, label) {
assert.ok(
Math.abs(actual - expected) <= tolerance,
`${label}: expected ${expected} ± ${tolerance}, got ${actual}`,
);
}
async function main() {
const { default: puppeteer } = await import('puppeteer');
const args = process.argv.slice(2);
const urlIndex = args.indexOf('--url');
const url = urlIndex >= 0 ? args[urlIndex + 1] : 'http://localhost:4173';
if (args.includes('--fail-on-retry')) process.env.QA_FAIL_ON_RETRY = '1';
const browser = await puppeteer.launch({
headless: true,
executablePath:
process.env.PUPPETEER_EXECUTABLE_PATH ||
(await puppeteer.executablePath()),
args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'],
});
const monitors = [];
try {
const page = await browser.newPage();
await page.setViewport(VIEWPORT);
const errors = [];
monitors.push(watchPage(page, { name: 'panel', errors }));
await hookRenderErrors(page);
const boot = async () => {
await page.goto(`${url}/`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => window.__godsEyeView?.viewer, {
timeout: 90_000,
});
await page.waitForSelector(`#${PANEL_ID} .panel-header`);
await page.evaluate(() => {
document.querySelector('.first-run-explore')?.click();
});
await page.keyboard.press('Escape');
await page.evaluate(() => {
document.getElementById('first-run-launcher')?.remove();
for (const node of document.querySelectorAll('[class*=first-run]'))
node.remove();
});
await page.mouse.click(VIEWPORT.width / 2, VIEWPORT.height / 2);
await nextFrames(page);
};
const readPanel = () =>
page.evaluate((id) => {
const panel = document.getElementById(id);
const rect = panel.getBoundingClientRect();
return {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
// handlePoint() reads the far edges for s/e handles.
right: rect.right,
bottom: rect.bottom,
floating: panel.classList.contains('panel-floating'),
collapsed: panel.classList.contains('collapsed'),
inRail: panel.parentElement?.id === 'right-context-rail',
allocated: panel.style.getPropertyValue(
'--right-panel-allocated-height',
),
inlineWidth: panel.style.width,
inlineHeight: panel.style.height,
stored: localStorage.getItem(`godsEyeView.v8.panelPos.${id}`),
};
}, PANEL_ID);
/**
* Best effort: wait for the box to hold still for half a second. The lift
* is checked against the box at pointerdown, so a timeout only costs time.
*/
const settle = async () => {
try {
await page.waitForFunction(
(id) => {
const r = document.getElementById(id).getBoundingClientRect();
const box = [r.left, r.top, r.width, r.height]
.map(Math.round)
.join(',');
const now = performance.now();
if (window.__qaLastBox !== box) {
window.__qaLastBox = box;
window.__qaSince = now;
}
return now - window.__qaSince >= 500;
},
{ polling: 100, timeout: 20_000 },
PANEL_ID,
);
} catch (error) {
if (error?.name !== 'TimeoutError') throw error;
console.log('note: the CCTV panel was still moving; lifting anyway');
}
};
const headerPoint = async () => {
const rect = await page.evaluate((id) => {
const title = document.querySelector(
`#${id} .panel-header .panel-title`,
);
const r = title.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}, PANEL_ID);
return rect;
};
const drag = (from, dx, dy) => dragPointer(page, from, dx, dy);
await page.goto(`${url}/`, { waitUntil: 'domcontentloaded' });
await page.evaluate((key) => {
localStorage.removeItem(key);
localStorage.removeItem('godsEyeView.v8.panelFloatHintShown');
}, STORAGE_KEY);
await boot();
await page.evaluate((id) => {
const panel = document.getElementById(id);
if (panel.classList.contains('collapsed'))
document
.querySelector(`.panel-collapse-btn[data-collapse-target="${id}"]`)
.click();
}, PANEL_ID);
await page.waitForFunction(
(id) => !document.getElementById(id).classList.contains('collapsed'),
{},
PANEL_ID,
);
// The rail animates panel heights, and on a slow software renderer the
// panels above CCTV can still be moving after a fixed sleep.
await settle();
const docked = await readPanel();
assert.equal(docked.floating, false);
assert.equal(docked.inRail, true);
// Names whatever above CCTV in the rail shifted it, for a retry note.
const railAbove = () =>
page.evaluate((id) => {
const out = [];
for (const node of document.getElementById('right-context-rail')
?.children || []) {
if (node.id === id) break;
out.push(
`${node.id || node.className}:${Math.round(node.offsetHeight)}`,
);
}
return out.join(' ');
}, PANEL_ID);
const aboveAtDock = await railAbove();
// On CI a panel above CCTV grows after load and can shift the header out
// from under the press; the helper retries only such a provable miss.
const attempt = await liftPanelByHeader(page, PANEL_ID, {
dx: -200,
dy: -100,
note: async () =>
`rail above CCTV ${aboveAtDock} -> ${await railAbove()}`,
});
const { pressed } = attempt;
const lifted = await readPanel();
assert.equal(
lifted.floating,
true,
`a header drag lifts the panel out (${describePress(attempt)}; panel docked at ${docked.top}, at press ${pressed?.top})`,
);
assert.equal(
lifted.collapsed,
false,
'the drag-ending click must not collapse',
);
const moved = `docked at ${docked.left},${docked.top}; pressed at ${pressed.left},${pressed.top}`;
near(
lifted.left,
Math.max(6, pressed.left - 200),
2,
`lifted left (${moved})`,
);
near(
lifted.top,
Math.max(6, pressed.top - 100),
2,
`lifted top (${moved})`,
);
near(lifted.width, pressed.width, 2, 'lifted width');
// The rail lets go of the lifted panel on its next layout pass.
await page
.waitForFunction(
(id) =>
document
.getElementById(id)
.style.getPropertyValue('--right-panel-allocated-height') === '',
{ timeout: 5_000 },
PANEL_ID,
)
.catch(() => {});
const afterLayout = await readPanel();
assert.equal(afterLayout.allocated, '', 'the rail no longer allocates it');
const railExcludes = await page.evaluate((id) => {
const rail = document.getElementById('right-context-rail');
// Same rule as the rail: hidden panels take no room.
const counted = [...rail.children].filter((panel) =>
panel.matches(
'[data-panel-id]:not(.panel-floating):not(.collapsed):not([hidden])',
),
);
return {
expandedCount: rail.dataset.expandedCount,
counted: counted.length,
includesPanel: counted.some((panel) => panel.id === id),
};
}, PANEL_ID);
assert.equal(railExcludes.includesPanel, false);
if (railExcludes.expandedCount !== undefined)
assert.equal(Number(railExcludes.expandedCount), railExcludes.counted);
const storedAfterLift = JSON.parse(afterLayout.stored);
assert.equal(storedAfterLift.floating, true);
assert.equal(
'height' in storedAfterLift,
false,
'a drag alone must not freeze the measured height',
);
console.log('PASS: header drag lifts CCTV out of the rail');
// Park near the top: the voice dock would cover the south corners once
// the loop below has grown the window.
{
const header = await headerPoint();
await drag(header, 0, 120 - header.y);
}
const limits = {
minWidth: MIN_SIZE.width,
minHeight: MIN_SIZE.height,
viewportWidth: VIEWPORT.width,
viewportHeight: VIEWPORT.height,
};
for (const dir of RESIZE_DIRECTIONS) {
const before = await readPanel();
const { dx, dy } = growthDelta(dir, 40);
const point = handlePoint(before, dir);
const hit = await page.evaluate(({ x, y }) => {
const node = document.elementFromPoint(x, y);
if (!node) return 'nothing';
const dirAttr = node.dataset?.dir
? `[data-dir=${node.dataset.dir}]`
: '';
return `${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}.${[...node.classList].join('.')}${dirAttr}`;
}, point);
await drag(point, dx, dy);
const after = await readPanel();
const expected = resizeBox(before, dir, dx, dy, limits);
for (const key of ['left', 'top', 'width', 'height'])
near(after[key], expected[key], 2, `${dir} ${key} (pointer on ${hit})`);
assert.deepEqual(driftedEdges(before, after, dir, 2), [], `${dir} pins`);
}
console.log('PASS: eight resize handles keep the opposite edge pinned');
let before = await readPanel();
await drag(handlePoint(before, 'se'), -2000, -2000);
let after = await readPanel();
near(after.width, MIN_SIZE.width, 2, 'min width (se)');
near(after.height, MIN_SIZE.height, 2, 'min height (se)');
assert.deepEqual(driftedEdges(before, after, 'se', 2), []);
before = after;
await drag(handlePoint(before, 'nw'), 2000, 2000);
after = await readPanel();
near(after.width, MIN_SIZE.width, 2, 'min width (nw)');
near(after.height, MIN_SIZE.height, 2, 'min height (nw)');
assert.deepEqual(driftedEdges(before, after, 'nw', 2), []);
console.log('PASS: minimum size holds from both corners');
const saved = await readPanel();
const record = JSON.parse(saved.stored);
assert.equal(record.floating, true);
await boot();
const restored = await readPanel();
assert.equal(restored.floating, true, 'floating survives a reload');
for (const key of ['left', 'top', 'width', 'height'])
near(restored[key], record[key], 2, `restored ${key}`);
console.log('PASS: reload restores position and size');
// A collapsed window keeps the height chosen for it, through a drag of
// its header strip and a reload.
const setCollapsed = async (collapsed) => {
await page.evaluate(
(id, want) => {
const panel = document.getElementById(id);
if (panel.classList.contains('collapsed') !== want)
document
.querySelector(
`.panel-collapse-btn[data-collapse-target="${id}"]`,
)
.click();
},
PANEL_ID,
collapsed,
);
await page.waitForFunction(
(id, want) =>
document.getElementById(id).classList.contains('collapsed') === want,
{},
PANEL_ID,
collapsed,
);
await nextFrames(page);
};
// Grow it from the corner once the restored window holds still, with the
// pointer really on the handle (a press beside it selects page text).
let chosen = await readPanel();
const tried = [];
for (
let attempt = 0;
attempt < 3 && chosen.height <= MIN_SIZE.height + 150;
attempt++
) {
await settle();
const box = await readPanel();
const corner = handlePoint(box, 'se');
const hit = await page.evaluate(({ x, y }) => {
const node = document.elementFromPoint(x, y);
return {
dir: node?.dataset?.dir || null,
target: node
? `${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}.${[...node.classList].join('.')}`
: 'nothing',
};
}, corner);
tried.push(
`${Math.round(corner.x)},${Math.round(corner.y)} on ${hit.target} (box ${Math.round(box.left)},${Math.round(box.top)} ${Math.round(box.width)}x${Math.round(box.height)})`,
);
if (hit.dir === 'se') await drag(corner, 0, 200);
chosen = await readPanel();
}
assert.ok(
chosen.height > MIN_SIZE.height + 150,
`the window grew to ${chosen.height}px; tried ${tried.join('; ')}`,
);
await setCollapsed(true);
const strip = await readPanel();
assert.ok(strip.height < chosen.height - 100, 'collapsed to its header');
await drag(await headerPoint(), 40, 30);
const movedStrip = await readPanel();
assert.equal(movedStrip.floating, true, 'the strip stays a window');
near(
JSON.parse(movedStrip.stored).height,
chosen.height,
2,
'stored height while collapsed',
);
await boot();
await setCollapsed(false);
near(
(await readPanel()).height,
chosen.height,
2,
'height after expanding',
);
console.log(
'PASS: a collapsed window keeps its height through a drag and a reload',
);
const dock = await dockPanelByDoubleClick(page, PANEL_ID);
const snapped = await readPanel();
assert.equal(
snapped.floating,
false,
`double-click snaps back (${describePress(dock)})`,
);
assert.equal(snapped.inRail, true);
assert.equal(snapped.inlineWidth, '');
assert.equal(snapped.inlineHeight, '');
assert.equal(snapped.stored, null, 'the storage key is gone');
console.log('PASS: header double-click returns the panel to the rail');
const renderErrors = await readRenderErrors(page);
assert.deepEqual(
[...errors, ...renderErrors.map((text) => `scene.renderError: ${text}`)],
[],
'no page errors and no Cesium render-loop errors',
);
console.log('PASS: no page errors and no render-loop errors');
} catch (error) {
const dir = await saveFailureArtifacts({
dir: ARTIFACT_DIR,
browser,
monitors,
error,
}).catch(() => null);
if (dir) console.error(`failure evidence saved in ${dir}/`);
throw error;
} finally {
await browser.close();
}
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
main().catch((error) => {
console.error(error.stack || error.message);
process.exit(1);
});
}
+319
View File
@@ -0,0 +1,319 @@
/**
* Header press-and-verify for the QA gates that lift a rail panel into a
* floating window and dock it again. The rail animates panel heights, so a
* point read once can be under another panel by the time the pointer goes
* down. Only a provable miss (a recorded press outside the header) is
* retried, with a GitHub `::warning::`. With QA_FAIL_ON_RETRY=1 a miss the
* panel's own movement cannot explain fails the run instead.
*/
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Retries after the first attempt, and the pause before each. */
export const PRESS_RETRIES = 2;
const RETRY_PAUSE_MS = 1000;
/** Whether a retry fails the run (QA_FAIL_ON_RETRY=1 or --fail-on-retry). */
export function failOnRetryDefault(
env = process.env,
argv = process.argv.slice(2),
) {
return env.QA_FAIL_ON_RETRY === '1' || argv.includes('--fail-on-retry');
}
/**
* A failed attempt whose press landed outside the header. No recorded press
* is a failure, not a miss: a retry would only hide it.
* @param {{done: boolean, pressed: {inHeader: boolean}|null}} attempt
*/
export function pressMissed(attempt) {
return !attempt.done && attempt.pressed?.inHeader === false;
}
/** Whether the panel's box changed by more than 2 px between two reads. */
export function panelMoved(before, after) {
if (!before || !after) return false;
return ['left', 'top', 'width', 'height'].some(
(key) => Math.abs((after[key] ?? NaN) - (before[key] ?? NaN)) > 2,
);
}
/** The panel's box, rounded, as `left,top widthxheight`. */
export function formatBox(box) {
if (!box) return 'unknown';
const r = (value) => Math.round(value ?? NaN);
return `${r(box.left)},${r(box.top)} ${r(box.width)}x${r(box.height)}`;
}
function panelBox(page, panelId) {
return page.evaluate((id) => {
const r = document.getElementById(id).getBoundingClientRect();
return { left: r.left, top: r.top, width: r.width, height: r.height };
}, panelId);
}
export function headerPoint(page, panelId) {
return page.evaluate((id) => {
const title = document.querySelector(`#${id} .panel-header .panel-title`);
const r = title.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}, panelId);
}
/** Name the element at a point, and whether it is the panel's header. */
export function hitAt(page, point, panelId) {
return page.evaluate(
({ x, y, id }) => {
const node = document.elementFromPoint(x, y);
if (!node) return { target: 'nothing', inHeader: false };
return {
target: `${node.tagName.toLowerCase()}${node.id ? `#${node.id}` : ''}.${[...node.classList].join('.')}`,
inHeader: Boolean(node.closest(`#${id} .panel-header`)),
};
},
{ ...point, id: panelId },
);
}
/**
* Re-resolve the header point until it hits the header or the wait runs out
* (the press then records the miss).
*/
export async function headerTarget(
page,
panelId,
{ tries = 20, intervalMs = 500 } = {},
) {
let point = await headerPoint(page, panelId);
let hit = await hitAt(page, point, panelId);
for (let i = 0; i < tries && !hit.inHeader; i++) {
await delay(intervalMs);
point = await headerPoint(page, panelId);
hit = await hitAt(page, point, panelId);
}
const box = await panelBox(page, panelId);
return { point, hit, timedOut: !hit.inHeader, box };
}
/**
* Best effort: wait until the panel's box has held still for `stillMs`, so
* the header does not move between the hit check and the press.
*/
export async function waitForStill(
page,
panelId,
{ stillMs = 300, timeout = 5000 } = {},
) {
try {
await page.waitForFunction(
(id, ms) => {
const r = document.getElementById(id).getBoundingClientRect();
const box = [r.left, r.top, r.width, r.height].map(Math.round).join();
const now = performance.now();
if (window.__qaStillBox !== box) {
window.__qaStillBox = box;
window.__qaStillSince = now;
}
return now - window.__qaStillSince >= ms;
},
{ polling: 100, timeout },
panelId,
stillMs,
);
return true;
} catch (error) {
if (error?.name !== 'TimeoutError') throw error;
return false;
}
}
/** Record the next pointerdown's target and the panel's box at that moment. */
export function recordNextPress(page, panelId) {
return page.evaluate((id) => {
window.__qaPressBox = null;
window.addEventListener(
'pointerdown',
(event) => {
const r = document.getElementById(id).getBoundingClientRect();
const target = event.target;
window.__qaPressBox = {
left: r.left,
top: r.top,
width: r.width,
height: r.height,
target: `${target.tagName?.toLowerCase()}${target.id ? `#${target.id}` : ''}.${[...(target.classList || [])].join('.')}`,
inHeader: Boolean(target.closest?.(`#${id} .panel-header`)),
};
},
{ capture: true, once: true },
);
}, panelId);
}
function readPress(page) {
return page.evaluate(() => window.__qaPressBox ?? null);
}
export async function waitForFloating(
page,
panelId,
floating,
{ timeout = 3000 } = {},
) {
try {
await page.waitForFunction(
(id, want) =>
document.getElementById(id).classList.contains('panel-floating') ===
want,
{ polling: 50, timeout },
panelId,
floating,
);
return true;
} catch (error) {
if (error?.name !== 'TimeoutError') throw error;
return false;
}
}
/** Two paints: by then every layout change an input caused is on screen. */
export function nextFrames(page) {
return page.evaluate(
() =>
new Promise((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
),
);
}
export async function dragPointer(page, from, dx, dy, { steps = 6 } = {}) {
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move(from.x + dx / 2, from.y + dy / 2, { steps });
await page.mouse.move(from.x + dx, from.y + dy, { steps });
await page.mouse.up();
await nextFrames(page);
}
export function describeRetry(
panelId,
attempt,
{ round, retries, extra = '' },
) {
const { hit, pressed, timedOut, still, box } = attempt;
return [
`retry ${round + 1}/${retries}: the press missed the ${panelId} header (on ${pressed?.target ?? hit.target})`,
`pre-press hit check ${timedOut ? `timed out (on ${hit.target})` : 'passed'}`,
`stillness ${still === false ? 'timed out' : 'held'}`,
`panel box at hit check ${formatBox(box)} -> at press ${formatBox(pressed)}`,
]
.concat(extra ? [extra] : [])
.join('; ');
}
/** Retry `press` only while it provably misses the header. */
async function pressUntilDecided(
page,
panelId,
press,
{
retries,
log,
note,
pauseMs = RETRY_PAUSE_MS,
failOnRetry = failOnRetryDefault(),
},
) {
for (let round = 0; ; round++) {
const still = await waitForStill(page, panelId);
await recordNextPress(page, panelId);
const { point, hit, timedOut, box } = await headerTarget(page, panelId);
const done = await press(point);
const attempt = {
point,
hit,
timedOut,
still,
box,
done,
pressed: await readPress(page),
retries: round,
};
if (round >= retries || !pressMissed(attempt)) return attempt;
const why = describeRetry(panelId, attempt, {
round,
retries,
extra: note ? await note() : '',
});
if (failOnRetry && !panelMoved(box, attempt.pressed))
throw new Error(
`QA_FAIL_ON_RETRY=1 turns this retry into a failure: ${why}`,
);
log(`note: ${why}; retrying`);
log(`::warning title=Panel press retried::${why}`);
await delay(pauseMs);
}
}
/**
* Lift a docked panel into a floating window with a header drag.
* @returns {Promise<{point: {x: number, y: number}, hit: {target: string, inHeader: boolean}, done: boolean, pressed: object|null}>}
*/
export function liftPanelByHeader(
page,
panelId,
{
dx,
dy,
retries = PRESS_RETRIES,
log = console.log,
note,
pauseMs,
failOnRetry,
} = {},
) {
return pressUntilDecided(
page,
panelId,
async (point) => {
await dragPointer(page, point, dx, dy);
return waitForFloating(page, panelId, true);
},
{ retries, log, note, pauseMs, failOnRetry },
);
}
/** Dock a floating panel with a header double-click; same result as lifting. */
export function dockPanelByDoubleClick(
page,
panelId,
{
retries = PRESS_RETRIES,
log = console.log,
note,
pauseMs,
failOnRetry,
} = {},
) {
return pressUntilDecided(
page,
panelId,
async (point) => {
await page.mouse.click(point.x, point.y, { clickCount: 1 });
await page.mouse.click(point.x, point.y, { clickCount: 2 });
return waitForFloating(page, panelId, false);
},
{ retries, log, note, pauseMs, failOnRetry },
);
}
/** Where an attempt pressed, for an assertion message. */
export function describePress(attempt) {
const { point, hit, pressed } = attempt;
const where = `pressed ${Math.round(point.x)},${Math.round(point.y)}`;
if (!pressed)
return `${where}: no pointerdown reached the page (hit check on ${hit.target}, in header: ${hit.inHeader})`;
const n = attempt.retries || 0;
const retried = n ? `, after ${n} ${n === 1 ? 'retry' : 'retries'}` : '';
return `${where} on ${pressed.target}, in header: ${pressed.inHeader}${retried}`;
}
-322
View File
@@ -1,322 +0,0 @@
#!/usr/bin/env node
/** Run against a dev server or built preview with QA_BASE_URL (default :4179). */
import fs from 'node:fs';
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({
executablePath:
process.env.PUPPETEER_EXECUTABLE_PATH || (await puppeteer.executablePath()),
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
const page = await browser.newPage();
const errors = [];
const failures = [];
page.on('pageerror', (error) => errors.push(error.message));
const check = (name, passed, detail = '') => {
console.log(
`[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`,
);
if (!passed) failures.push(name);
};
const base = process.env.QA_BASE_URL || 'http://localhost:4179';
const shots = process.env.QA_SHOTS_DIR || 'qa-shots/segmented-controls';
fs.mkdirSync(shots, { recursive: true });
try {
await page.setViewport({ width: 1440, height: 900 });
await page.goto(`${base}/?welcome=0`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(
() => window.__godsEyeView?.styleManager?._applicationShortcuts,
{ timeout: 60000 },
);
await page.waitForFunction(
() =>
document.getElementById('loading-screen')?.classList.contains('hidden'),
{ timeout: 60000 },
);
await page.evaluate(() =>
window.__godsEyeView.styleManager.setPanelCollapsed('pp-toggles', false, {
persist: false,
syncShare: false,
}),
);
const surface = await page.evaluate(() => {
const groups = [...document.querySelectorAll('[role="radiogroup"]')];
const buttons = groups.flatMap((group) => [
...group.querySelectorAll('[role="radio"]'),
]);
return {
groups: groups.length,
buttons: buttons.length,
shared:
groups.every((g) => g.classList.contains('gev-segmented')) &&
buttons.every((b) => {
const style = getComputedStyle(b);
return (
b.classList.contains('gev-segment') &&
style.fontSize === '9px' &&
style.minHeight === '24px' &&
style.borderRadius === '0px'
);
}),
};
});
check(
'all six one-of-many groups use the shared surface',
surface.groups === 6 && surface.buttons === 15 && surface.shared,
JSON.stringify(surface),
);
await page.evaluate(() =>
document.getElementById('models3d-mode-all').click(),
);
check(
'model selection reaches both aircraft layers',
await page.evaluate(() => {
const dm = window.__godsEyeView.dataManager;
return (
['flights', 'military'].every(
(id) => dm.layers.get(id).module.getParams().models3dMode === 'all',
) &&
document
.getElementById('models3d-mode-all')
.getAttribute('aria-checked') === 'true'
);
}),
);
await page.focus('#models3d-mode-all');
await page.keyboard.press('ArrowLeft');
check(
'Display retains its click-only arrow policy',
await page.evaluate(
() =>
document
.getElementById('models3d-mode-all')
.getAttribute('aria-checked') === 'true',
),
);
await page.focus('#models3d-mode-proximity');
await page.keyboard.press('Space');
check(
'native Space selects model coverage',
await page.evaluate(
() =>
document
.getElementById('models3d-mode-proximity')
.getAttribute('aria-checked') === 'true',
),
);
await page.evaluate(() =>
document.getElementById('detection-allocation-weighted').click(),
);
check(
'allocation selection still updates application tuning',
await page.evaluate(
() =>
window.__godsEyeView.styleManager._detectionAllocationPreference ===
'WEIGHTED' &&
document
.getElementById('detection-allocation-weighted')
.getAttribute('aria-checked') === 'true',
),
);
await page.evaluate(() =>
document.querySelector('[data-shape="pin"]').click(),
);
check(
'drawing shape still uses its existing feature action',
await page.evaluate(
() =>
window.__gevDrawTool?.shape === 'pin' &&
document
.querySelector('[data-shape="pin"]')
.getAttribute('aria-checked') === 'true',
),
);
// Off-layer controls still own params; no catalog/provider request is needed.
await page.evaluate(() =>
document.querySelector('[data-sl-pano="flat"]').click(),
);
check(
'panorama choice reaches the Street Level layer',
await page.evaluate(
() =>
window.__godsEyeView.dataManager.layers
.get('street-level')
.module.getParams().pano === 'flat',
),
);
await page.evaluate(() =>
document.querySelector('[data-sl-pano="flat"]').dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Home',
bubbles: true,
cancelable: true,
}),
),
);
check(
'Street Level Home retains selection and roving tab state',
await page.evaluate(
() =>
window.__godsEyeView.dataManager.layers
.get('street-level')
.module.getParams().pano === 'all' &&
document
.querySelector('[data-sl-pano="all"]')
.getAttribute('tabindex') === '0',
),
);
await page.evaluate(() =>
document.querySelector('[data-sl-render="fill"]').click(),
);
check(
'fit/fill keeps its stored render preference',
await page.evaluate(
() =>
localStorage.getItem('gev:street-level:render-mode') === 'fill' &&
document
.querySelector('[data-sl-render="fill"]')
.getAttribute('aria-checked') === 'true',
),
);
await page.evaluate(() =>
document.querySelector('.ri-mode-btn[data-mode="ab"]').click(),
);
check(
'imagery mode reaches its controlled layer state',
await page.evaluate(
() =>
window.__godsEyeView.dataManager.layers
.get('recent-imagery')
.module.getSnapshot().mode === 'ab',
),
);
await page.evaluate(() =>
document.getElementById('ri-mode').dispatchEvent(
new KeyboardEvent('keydown', {
key: 'ArrowRight',
bubbles: true,
cancelable: true,
}),
),
);
check(
'imagery arrows wrap from the current selected value',
await page.evaluate(
() =>
window.__godsEyeView.dataManager.layers
.get('recent-imagery')
.module.getSnapshot().mode === 'image' &&
document
.querySelector('.ri-mode-btn[data-mode="image"]')
.getAttribute('aria-checked') === 'true',
),
);
await page.evaluate(() => {
const manager = window.__godsEyeView.styleManager;
manager._setDetectionAllocation('ELASTIC', {
syncShare: false,
persist: false,
});
document
.getElementById('models3d-mode-proximity')
.scrollIntoView({ block: 'center' });
});
await page.screenshot({ path: `${shots}/desktop.png` });
await page.setViewport({ width: 620, height: 900 });
await page.evaluate(() =>
document
.getElementById('models3d-mode-proximity')
.scrollIntoView({ block: 'center' }),
);
await page.screenshot({ path: `${shots}/narrow.png` });
check(
'narrow selectors stay within their panel',
await page.evaluate(() =>
[...document.querySelectorAll('.pp-mode-seg')]
.filter((g) => g.getClientRects().length)
.every((group) => group.scrollWidth <= group.clientWidth + 1),
),
);
const cyber = await page.evaluate(() => {
const root = document.documentElement;
const previous = root.getAttribute('data-ui-theme');
root.setAttribute('data-ui-theme', 'cyber');
const selected = [
...document.querySelectorAll('.gev-segment[aria-checked="true"]'),
];
// Check the final theme colors, independent of software-GL frame cadence.
for (const button of selected)
for (const animation of button.getAnimations()) animation.finish();
const backgrounds = selected.map(
(button) => getComputedStyle(button).backgroundColor,
);
const radii = [...document.querySelectorAll('.gev-segmented')].map(
(group) => getComputedStyle(group).borderRadius,
);
const consistent =
selected.length === 6 &&
backgrounds.every((color) => color === backgrounds[0]) &&
radii.every((radius) => radius === '1px');
if (previous === null) root.removeAttribute('data-ui-theme');
else root.setAttribute('data-ui-theme', previous);
return { consistent, count: selected.length, backgrounds, radii };
});
check(
'Cyber theme styles every selected segment consistently',
cyber.consistent,
JSON.stringify(cyber),
);
await page.evaluate(async () => {
const { dataManager, styleManager } = window.__godsEyeView;
await dataManager.setEnabled('recent-imagery', true);
styleManager.setPanelCollapsed('recent-imagery-panel', false, {
persist: false,
syncShare: false,
});
});
for (const width of [1440, 620, 390]) {
await page.setViewport({ width, height: 900 });
await page.focus('.ri-mode-btn[aria-checked="true"]');
const modeLayout = await page.evaluate(() => {
const group = document.getElementById('ri-mode');
const bounds = group.getBoundingClientRect();
const style = getComputedStyle(group);
const top = bounds.top + parseFloat(style.borderTopWidth);
const bottom = bounds.bottom - parseFloat(style.borderBottomWidth);
const buttons = [...group.querySelectorAll('[role="radio"]')];
return {
visible: bounds.width > 0 && bounds.height > 0,
contained: buttons.every((button) => {
const rect = button.getBoundingClientRect();
return rect.top >= top - 0.5 && rect.bottom <= bottom + 0.5;
}),
groupHeight: bounds.height,
buttonHeights: buttons.map(
(button) => button.getBoundingClientRect().height,
),
};
});
check(
`imagery mode buttons and focus outline fit their row at ${width}px`,
modeLayout.visible && modeLayout.contained,
JSON.stringify(modeLayout),
);
}
check('no uncaught browser errors', errors.length === 0, errors.join(' | '));
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: `${shots}/failure.png` }).catch(() => {});
throw error;
} finally {
await browser.close();
}
console.log(`RESULT: ${failures.length} failures`);
process.exitCode = failures.length ? 1 : 0;
+2781 -554
View File
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -43,7 +43,11 @@ try {
const fpsReadout = document.querySelector('.frame-rate-readout'); const fpsReadout = document.querySelector('.frame-rate-readout');
const fpsWasVisible = fpsReadout && !fpsReadout.hidden; const fpsWasVisible = fpsReadout && !fpsReadout.hidden;
const watchObserver = (name) => { const watchObserver = (name) => {
const observer = ui._panelLayout[name]; const owner =
name === '_draggableResizeObserver'
? ui._panelPosition
: ui._panelLayout;
const observer = owner[name];
if (!observer) return false; if (!observer) return false;
const disconnect = observer.disconnect.bind(observer); const disconnect = observer.disconnect.bind(observer);
counts[name] = 0; counts[name] = 0;
@@ -55,6 +59,7 @@ try {
}; };
const observed = [ const observed = [
'_commandDockTrayObserver', '_commandDockTrayObserver',
'_draggableResizeObserver',
'_leftStackResizeObserver', '_leftStackResizeObserver',
'_rightStackResizeObserver', '_rightStackResizeObserver',
'_leftStackMutationObserver', '_leftStackMutationObserver',
@@ -134,6 +139,7 @@ try {
const focusBefore = document.activeElement; const focusBefore = document.activeElement;
const stoppedBeforeRestoration = const stoppedBeforeRestoration =
ui._panelLayout.destroyed && ui._panelLayout.destroyed &&
ui._panelPosition.destroyed &&
ui._feedback.destroyed && ui._feedback.destroyed &&
ui._recording.destroyed && ui._recording.destroyed &&
cockpit.destroyed && cockpit.destroyed &&
@@ -188,7 +194,11 @@ try {
counts[field] === 1 && ui._contextControls[field] === null, counts[field] === 1 && ui._contextControls[field] === null,
), ),
observersReleased: observed.every( observersReleased: observed.every(
(name) => counts[name] === 1 && ui._panelLayout[name] === null, (name) =>
counts[name] === 1 &&
(name === '_draggableResizeObserver'
? ui._panelPosition
: ui._panelLayout)[name] === null,
), ),
subscriptionReleased: subscriptionReleased:
counts.cctv === 1 && ui._cctvControls._cctvUnsubscribe === null, counts.cctv === 1 && ui._cctvControls._cctvUnsubscribe === null,
+365
View File
@@ -0,0 +1,365 @@
#!/usr/bin/env node
/**
* qa-vcam.mjs — phone virtual camera, end to end.
*
* Drives the real desktop app and the real phone page (served by the HTTPS
* phone listener) in one browser, plus a scripted 6DoF phone over the same
* relay:
*
* 1. SCENES ▸ VCAM starts a session and draws a QR code for the pairing URL.
* 2. The phone page pairs from the URL fragment, falls back to HTTPS requests
* when WebSockets are refused (as iOS does under a certificate warning),
* starts the gyro camera and turns the desktop camera with device
* orientation; the desktop's render arrives on the phone's monitor.
* 3. The phone's lens preset and REC button reach the desktop; the recorded
* take becomes a validated track shot in the selected scene and replays.
* 4. A scripted 6DoF phone moves one metre at 1:100 and the camera moves
* about a hundred metres; desktop navigation holds the rig.
*
* Needs the dev server (default http://localhost:4173, or QA_BASE_URL) and
* its phone listener on VCAM_PORT (default 4174), reachable on loopback.
* Screenshots go to qa-shots/vcam/.
*
* npm run dev # in another terminal
* node scripts/qa-vcam.mjs
*/
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import puppeteer from 'puppeteer';
import WebSocket from 'ws';
const BASE = process.env.QA_BASE_URL || 'http://localhost:4173';
const output = path.resolve('qa-shots/vcam');
fs.mkdirSync(output, { recursive: true });
let failed = 0;
function check(name, passed, detail = '') {
console.log(`[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`);
if (!passed) failed++;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Separate browsers, like separate devices: a background tab would hide the
// desktop page, which suspends its render loop.
const launch = () =>
puppeteer.launch({
headless: true,
acceptInsecureCerts: true,
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
args: ['--no-sandbox', '--disable-dev-shm-usage', '--ignore-certificate-errors'],
});
const browser = await launch();
const phoneBrowser = await launch();
const errors = [];
try {
const desk = await browser.newPage();
desk.on('pageerror', (error) => errors.push(`desktop: ${error.message}`));
if (process.env.QA_VCAM_DEBUG) desk.on('pageerror', (error) => console.log('DESKTOP ERROR', error.stack || error.message));
await desk.setViewport({ width: 1280, height: 800 });
await desk.goto(`${BASE}/?welcome=0`, { waitUntil: 'domcontentloaded' });
await desk.waitForFunction(
() =>
window.__godsEyeView?.vcam &&
document.getElementById('loading-screen')?.classList.contains('hidden'),
{ timeout: 90000 },
);
// A shader that fails to compile stops Cesium's render loop.
await desk.evaluate(() => {
window.__vcamRenderErrors = [];
window.__godsEyeView.viewer.scene.renderError.addEventListener((_scene, error) =>
window.__vcamRenderErrors.push(String(error?.message || error)),
);
});
// Start from a known city view.
await desk.evaluate(() =>
window.__godsEyeView.styleManager.applyCameraState(
{ lat: 30.2672, lon: -97.7431, alt: 1200, heading: 0, pitch: -30, roll: 0 },
0.2,
),
);
await sleep(800);
// 1. Pairing UI.
await desk.evaluate(() => {
const panel = document.getElementById('scene-panel');
if (panel.classList.contains('collapsed'))
panel.querySelector('.panel-collapse-btn')?.click();
});
await desk.click('#vcam-toggle-btn');
if (process.env.QA_VCAM_DEBUG)
await desk.evaluate(() => {
window.__vcamSeen = [];
window.__godsEyeView.vcam.subscribe((s) =>
window.__vcamSeen.push([s.status, s.phoneConnected, s.driving, s.held, s.holdReason].join(',')),
);
});
await desk.waitForFunction(() => window.__godsEyeView.vcam.getState().code, { timeout: 15000 });
const pairing = await desk.evaluate(() => {
const state = window.__godsEyeView.vcam.getState();
const qr = document.getElementById('vcam-qr');
return {
state,
shownCode: document.getElementById('vcam-code').textContent,
qrDrawn: !qr.hidden && qr.width > 100,
link: document.getElementById('vcam-url').textContent,
};
});
check('VCAM opens a pairing session with a code and QR', pairing.qrDrawn && pairing.shownCode === pairing.state.code, pairing.link);
const phoneUrl = `https://127.0.0.1:${pairing.state.port}/#${pairing.state.code}`;
// 2. The real phone page, with WebSockets refused as on iOS.
const phone = await phoneBrowser.newPage();
phone.on('pageerror', (error) => errors.push(`phone: ${error.message}`));
if (process.env.QA_VCAM_DEBUG)
phone.on('request', (request) => {
if (request.url().includes('/api/') && !request.url().includes('/api/frame'))
console.log('PHONE', request.method(), request.url().split('?')[0], request.postData()?.slice(0, 90) ?? '');
});
await phone.emulate({
viewport: { width: 390, height: 844, isMobile: true, hasTouch: true, deviceScaleFactor: 2 },
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1',
});
await phone.evaluateOnNewDocument(() => {
window.WebSocket = class {
static OPEN = 1;
readyState = 0;
constructor() {
setTimeout(() => {
this.onerror?.(new Event('error'));
this.onclose?.({ code: 1006 });
}, 50);
}
close() {}
};
});
await phone.goto(phoneUrl, { waitUntil: 'domcontentloaded' });
await phone.waitForSelector('#start:not([hidden])', { timeout: 10000 });
check('the phone pairs from the QR link and clears the code from the address bar',
!(await phone.evaluate(() => location.hash)));
await phone.click('#start-gyro');
await phone.waitForSelector('#camera:not([hidden])', { timeout: 5000 });
const orient = (alpha, beta = 90, gamma = 0) =>
phone.evaluate((a, b, g) => {
window.dispatchEvent(new DeviceOrientationEvent('deviceorientation', { alpha: a, beta: b, gamma: g }));
}, alpha, beta, gamma);
await orient(0);
await desk
.waitForFunction(() => window.__godsEyeView.vcam.getState().driving, { timeout: 10000 })
.catch(async (error) => {
const { status, phoneConnected, held, holdReason, mode } = await desk.evaluate(() =>
window.__godsEyeView.vcam.getState(),
);
if (process.env.QA_VCAM_DEBUG)
console.log('SEEN', await desk.evaluate(() => JSON.stringify([...new Set(window.__vcamSeen)])));
throw new Error(`rig never drove: ${JSON.stringify({ status, phoneConnected, held, holdReason, mode })}`, {
cause: error,
});
});
const linkState = await phone.evaluate(() => document.getElementById('link-dot').className);
check('the phone falls back to HTTPS requests when WebSockets fail', linkState.includes('slow'), linkState);
const before = await desk.evaluate(() => window.__godsEyeView.styleManager.getCameraState());
for (let alpha = 0; alpha <= 45; alpha += 3) {
await orient(alpha);
await sleep(40);
}
// Headless WebGL renders a few frames a second; wait for the rig to settle.
const headingAfter = (target) =>
desk
.waitForFunction(
(from, wanted) => {
const { heading } = window.__godsEyeView.styleManager.getCameraState();
return Math.abs((((from - heading + 540) % 360) - 180) - wanted) < 1;
},
{ timeout: 15000, polling: 100 },
before.heading,
target,
)
.catch(() => {});
await headingAfter(45);
const turned = await desk.evaluate(() => window.__godsEyeView.styleManager.getCameraState());
const headingDelta = ((before.heading - turned.heading + 540) % 360) - 180;
check('turning the phone 45° left turns the camera 45° left', Math.abs(headingDelta - 45) < 1,
`heading ${before.heading.toFixed(1)} → ${turned.heading.toFixed(1)}`);
check('an upright phone looks at the horizon', Math.abs(turned.pitch) < 5, `pitch ${turned.pitch.toFixed(1)}`);
const vcamMode = await desk.evaluate(() => window.__godsEyeView.vcam.getState().mode);
check('the desktop reports gyro (3DoF) tracking', vcamMode === '3dof');
await phone.waitForFunction(() => document.getElementById('monitor').naturalWidth > 0, { timeout: 10000 });
check('the desktop render reaches the phone monitor', true);
// 3. Lens and a take from the phone.
await phone.click('#lens-btn');
await phone.click('#focal-presets button[data-focal="85"]');
await desk.waitForFunction(() => Math.abs(window.__godsEyeView.lens.getFocalLength() - 85) < 0.01, { timeout: 5000 });
const fov = await desk.evaluate(() => window.__godsEyeView.viewer.camera.frustum.fov);
check('the phone lens preset sets the desktop focal length', Math.abs(fov - 2 * Math.atan(18 / 85)) < 1e-6);
await phone.click('#lens-btn');
const shotsBefore = await desk.evaluate(() => {
const d = window.__godsEyeView.sceneDirector;
return d._getSelectedScene().shots.length;
});
await phone.click('#record-btn');
await desk.waitForFunction(() => window.__godsEyeView.vcam.getState().recording, { timeout: 5000 });
for (let alpha = 45; alpha >= -20; alpha -= 2) {
await orient(alpha, 80);
await sleep(50);
}
await phone.click('#record-btn');
await desk.waitForFunction(() => !window.__godsEyeView.vcam.getState().recording, { timeout: 5000 });
const take = await desk.evaluate(() => {
const d = window.__godsEyeView.sceneDirector;
const scene = d._getSelectedScene();
const shot = scene.shots.at(-1);
return {
count: scene.shots.length,
title: shot.title,
samples: shot.move?.track?.samples?.length || 0,
duration: shot.durationSec,
focal: shot.move?.track?.samples?.[0]?.[7],
listed: document.getElementById('scene-shot-list').textContent.includes(shot.title),
saved: JSON.parse(localStorage.getItem('godsEyeView.sceneProject.v2')).scenes.some((s) => s.shots.some((x) => x.id === shot.id)),
sceneId: scene.id,
shotId: shot.id,
last: shot.move?.track?.samples?.at(-1),
};
});
// One sample per rendered frame, at most 30 a second.
check('REC on the phone adds a track shot to the selected scene',
take.count === shotsBefore + 1 && take.samples >= 2 && take.duration > 2 &&
take.samples <= take.duration * 30 + 2 && take.listed && take.saved,
`${take.title}: ${take.samples} samples over ${take.duration}s`);
check('the take records the focal length per sample', take.focal === 85);
await desk.screenshot({ path: path.join(output, 'desktop-take.png') });
await phone.screenshot({ path: path.join(output, 'phone-camera.png') });
// Replaying the take ends exactly on its last sample.
await desk.evaluate(() => window.__godsEyeView.vcam.hold());
await desk.evaluate(({ sceneId, shotId }) =>
window.__godsEyeView.sceneDirector.loadShot(sceneId, shotId), take);
await desk.waitForFunction(({ last }) => {
const c = window.__godsEyeView.styleManager.getCameraState();
return Math.abs(c.lat - last[2]) < 1e-5 && Math.abs(c.lon - last[1]) < 1e-5;
}, { timeout: 20000 }, take).catch(() => {});
const replayed = await desk.evaluate(() => window.__godsEyeView.styleManager.getCameraState());
check('loading the take plays it to its final recorded pose',
Math.abs(replayed.lat - take.last[2]) < 1e-5 && Math.abs(replayed.alt - take.last[3]) < 0.5,
`alt ${replayed.alt.toFixed(1)} vs ${take.last[3]}`);
await phone.close();
// 4. A scripted 6DoF phone: translation follows the motion scale.
const join = await new Promise((resolve) => {
const request = https.request(
`https://127.0.0.1:${pairing.state.port}/api/join`,
{ method: 'POST', rejectUnauthorized: false, headers: { 'Content-Type': 'application/json' } },
(response) => {
let body = '';
response.on('data', (chunk) => (body += chunk));
response.on('end', () => resolve({ ok: response.statusCode === 200, body }));
},
);
request.on('error', () => resolve({ ok: false }));
request.end(JSON.stringify({ code: pairing.state.code }));
});
let sixDof = null;
if (join.ok) {
const { phoneKey } = JSON.parse(join.body);
sixDof = new WebSocket(`wss://127.0.0.1:${pairing.state.port}/ws?key=${phoneKey}`, {
origin: `https://127.0.0.1:${pairing.state.port}`,
rejectUnauthorized: false,
});
await new Promise((resolve, reject) => {
sixDof.once('open', resolve);
sixDof.once('error', reject);
});
}
check('a second phone can pair over a WebSocket', !!sixDof);
if (sixDof) {
const pose = (z, extra = {}) =>
sixDof.send(JSON.stringify({ type: 'pose', t: Date.now(), q: [0, 0, 0, 1], p: [0, 1.5, z], j: [0, 0, 0, 0], ...extra }));
sixDof.send(JSON.stringify({ type: 'set', key: 'scale', value: 100 }));
sixDof.send(JSON.stringify({ type: 'set', key: 'smoothing', value: 0 }));
sixDof.send(JSON.stringify({ type: 'cmd', cmd: 'release' }));
for (let i = 0; i < 10; i++) {
pose(0);
await sleep(30);
}
await desk.waitForFunction(() => window.__godsEyeView.vcam.getState().driving && window.__godsEyeView.vcam.getState().mode === '6dof', { timeout: 5000 });
const position = () =>
desk.evaluate(() => {
const { x, y, z } = window.__godsEyeView.viewer.camera.positionWC;
return [x, y, z];
});
const start = await position();
for (let i = 1; i <= 20; i++) {
pose(-i / 20);
await sleep(30);
}
await desk
.waitForFunction(
(from) => {
const { x, y, z } = window.__godsEyeView.viewer.camera.positionWC;
return Math.abs(Math.hypot(x - from[0], y - from[1], z - from[2]) - 100) < 1;
},
{ timeout: 15000, polling: 100 },
start,
)
.catch(() => {});
const end = await position();
const moved = Math.hypot(end[0] - start[0], end[1] - start[1], end[2] - start[2]);
check('one metre of phone motion at 1:100 moves the camera 100 m', Math.abs(moved - 100) < 1, `${moved.toFixed(1)} m`);
// Depth of field at a miniature scale, focused by a tap at the centre.
sixDof.send(JSON.stringify({ type: 'set', key: 'scale', value: 1000 }));
sixDof.send(JSON.stringify({ type: 'set', key: 'dof', value: true }));
sixDof.send(JSON.stringify({ type: 'set', key: 'fStop', value: 4 }));
// Pitch down 30 degrees, let the rig settle, then focus on the ground ahead.
for (let i = 0; i < 20; i++) {
pose(-1, { q: [-0.2588, 0, 0, 0.9659] });
await sleep(50);
}
await desk
.waitForFunction(() => window.__godsEyeView.styleManager.getCameraState().pitch < -29, {
timeout: 15000,
polling: 100,
})
.catch(() => {});
sixDof.send(JSON.stringify({ type: 'focus', x: 0.5, y: 0.5 }));
await sleep(2000);
const dof = await desk.evaluate(() => {
const { lens, viewer } = window.__godsEyeView;
const stage = viewer.scene.postProcessStages;
let found = null;
for (let i = 0; i < stage.length; i++)
if (stage.get(i).name === 'godsEyeView_depthOfField') found = stage.get(i);
return {
state: lens.getDepthOfField(),
enabled: !!found?.enabled,
ready: !!found?.ready,
errors: window.__vcamRenderErrors,
};
});
check('tap-to-focus enables depth of field at the rig scale',
dof.enabled && dof.state.scale === 1000 && dof.state.focusM > 1000 && dof.state.focusM < 5000 && dof.state.fStop === 4,
`focus ${dof.state.focusM?.toFixed?.(0)} m at 1:${dof.state.scale}`);
check('the depth-of-field shader compiles and renders', dof.ready && dof.errors.length === 0, dof.errors.join(' | '));
await desk.screenshot({ path: path.join(output, 'desktop-dof.png') });
// Mouse navigation on the globe holds the rig instead of fighting it.
await desk.mouse.click(640, 400);
const held = await desk.evaluate(() => window.__godsEyeView.vcam.getState());
check('desktop mouse input holds the rig', held.held && !held.driving, held.holdReason);
sixDof.close();
}
await desk.click('#vcam-end-btn');
await desk.waitForFunction(() => window.__godsEyeView.vcam.getState().status === 'idle', { timeout: 5000 });
check('END closes the session', true);
} catch (error) {
console.error(error);
failed++;
} finally {
await browser.close();
await phoneBrowser.close();
}
const relevant = errors.filter((message) => !/Failed to fetch|NetworkError|tile|imagery/i.test(message));
check('no page errors', relevant.length === 0, relevant.slice(0, 3).join(' | '));
console.log(failed ? `\n${failed} check(s) failed` : '\nAll VCAM checks passed');
process.exit(failed ? 1 : 0);
-32
View File
@@ -183,38 +183,6 @@ try {
return manager.bloomEnabled !== before; return manager.bloomEnabled !== before;
}), }),
); );
const sliders = await page.evaluate(() => {
const ordinary = [
...document.querySelectorAll('input[type="range"]'),
].filter(
(input) => !input.matches('#radio-tuner-slider, .bhote-event-range'),
);
return {
count: ordinary.length,
shared: ordinary.every((input) =>
input.classList.contains('gev-quantitative-slider'),
),
surface: ordinary.every((input) => {
const style = getComputedStyle(input);
return (
style.height === '18px' &&
style.appearance === 'none' &&
style.padding === '0px' &&
style.borderWidth === '0px' &&
(!input.disabled ||
(style.opacity === '0.42' && style.cursor === 'not-allowed'))
);
}),
tunerSeparate: !document
.getElementById('radio-tuner-slider')
.classList.contains('gev-quantitative-slider'),
};
});
check(
'ordinary sliders share one native surface',
sliders.count > 10 && sliders.shared && sliders.surface,
);
check('radio tuning keeps its specialized control', sliders.tunerSeparate);
fs.mkdirSync('qa-shots/visual-input', { recursive: true }); fs.mkdirSync('qa-shots/visual-input', { recursive: true });
await page.screenshot({ path: 'qa-shots/visual-input/desktop.png' }); await page.screenshot({ path: 'qa-shots/visual-input/desktop.png' });
await page.setViewport({ width: 620, height: 900 }); await page.setViewport({ width: 620, height: 900 });
+3 -5
View File
@@ -1745,9 +1745,8 @@ async function runBehaviorLayer() {
'behavior: analyst follow-up re-filters the remembered set', 'behavior: analyst follow-up re-filters the remembered set',
`count=${r?.count} followUp=${r?.coverage?.followUp}`, `count=${r?.count} followUp=${r?.coverage?.followUp}`,
); );
// Require the bundled boundary source and the existing whole-query limit. // A marine region resolves from the bundled Natural Earth pack in the page,
// This elapsed time includes record acquisition and filtering; the region // without the slower geocode fallback.
// resolver has its own separate fallback budget.
const gulfStarted = Date.now(); const gulfStarted = Date.now();
r = await run('analyst_query', { r = await run('analyst_query', {
layers: ['flights'], layers: ['flights'],
@@ -1758,10 +1757,9 @@ async function runBehaviorLayer() {
report( report(
r?.ok === true && r?.ok === true &&
String(r?.coverage?.scope || '').includes('Gulf of Mexico') && String(r?.coverage?.scope || '').includes('Gulf of Mexico') &&
r?.coverage?.scopeSource === 'natural-earth' &&
gulfMs < 3000, gulfMs < 3000,
'behavior: analyst resolves the Gulf of Mexico from the bundled pack', 'behavior: analyst resolves the Gulf of Mexico from the bundled pack',
`scope=${r?.coverage?.scope} source=${r?.coverage?.scopeSource} ms=${gulfMs} err=${r?.error || ''}`, `scope=${r?.coverage?.scope} ms=${gulfMs} err=${r?.error || ''}`,
); );
// (5) zoom_to_globe is ABSOLUTE full-earth (>12,000 km band) // (5) zoom_to_globe is ABSOLUTE full-earth (>12,000 km band)
+5 -20
View File
@@ -17,7 +17,6 @@ import {
CCTV_MAX_SOURCES_CEILING, CCTV_MAX_SOURCES_CEILING,
} from './cctv/constants.js'; } from './cctv/constants.js';
import { sanitizeCctvRangeHeader } from './cctv/range.js'; import { sanitizeCctvRangeHeader } from './cctv/range.js';
import { admitSameSite } from './common/same-site.js';
import { createHlsPuller } from './cctv/stream.js'; import { createHlsPuller } from './cctv/stream.js';
import { googleServerApiKey } from './places/google-key.js'; import { googleServerApiKey } from './places/google-key.js';
export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream }; export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream };
@@ -136,22 +135,15 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
}); });
server.middlewares.use('/api/cctv', async (req, res) => { server.middlewares.use('/api/cctv', async (req, res) => {
try { try {
const url = new URL(req.url || '/', 'http://localhost');
// Refuse before catalog I/O, session creation, renewal or release.
if (url.pathname.startsWith('/media/') && admitSameSite(req, res))
return;
const clientId = String(req.socket?.remoteAddress || 'unknown').replace(
/^::ffff:/,
'',
);
const sources = await getCctvSources(); const sources = await getCctvSources();
const sourceById = new Map( const sourceById = new Map(
sources.map((source) => [source.id, source]), sources.map((source) => [source.id, source]),
); );
const url = new URL(req.url || '/', 'http://localhost');
if (url.pathname === '/sources') { if (url.pathname === '/sources') {
const body = { const body = {
trimmedPacks: getCctvSources.trimmedPacks?.(sources) ?? [], trimmedPacks: getCctvSources.trimmedPacks?.() ?? [],
sources: sources.map((source) => ({ sources: sources.map((source) => ({
id: source.id, id: source.id,
pack: source.pack, pack: source.pack,
@@ -246,7 +238,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
return; return;
} }
if (req.method === 'DELETE') { if (req.method === 'DELETE') {
if (leaseId) puller.release(cameraId, leaseId, clientId); if (leaseId) puller.release(cameraId, leaseId);
res.writeHead(204); res.writeHead(204);
res.end(); res.end();
return; return;
@@ -276,7 +268,6 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
url.searchParams.get('session'), url.searchParams.get('session'),
Number(match[3]), Number(match[3]),
leaseId, leaseId,
clientId,
); );
res.writeHead(body ? 200 : 404, { res.writeHead(body ? 200 : 404, {
'Content-Type': 'video/mp2t', 'Content-Type': 'video/mp2t',
@@ -288,15 +279,10 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
const downstream = watchDownstreamClose(res); const downstream = watchDownstreamClose(res);
let entry; let entry;
const cancelPending = () => { const cancelPending = () => {
if (entry) puller.release(cameraId, leaseId, clientId); if (entry) puller.release(cameraId, leaseId);
}; };
try { try {
entry = await puller.ensure( entry = await puller.ensure(cameraId, mediaUrl, leaseId);
cameraId,
mediaUrl,
leaseId,
clientId,
);
if (downstream.closed) { if (downstream.closed) {
cancelPending(); cancelPending();
return; return;
@@ -310,7 +296,6 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
entry, entry,
cameraId, cameraId,
leaseId, leaseId,
clientId,
); );
if (downstream.closed) return; if (downstream.closed) return;
if (!playlist) throw new Error('Stream unavailable'); if (!playlist) throw new Error('Stream unavailable');
+12 -59
View File
@@ -5,7 +5,6 @@ import { allocateSourceCap, resolveCatalogCap } from './cap.js';
import { loadGroundHeights, joinGroundHeights } from './groundHeights.js'; import { loadGroundHeights, joinGroundHeights } from './groundHeights.js';
import { cameraRegion, normalizeSourceItem } from './normalize.js'; import { cameraRegion, normalizeSourceItem } from './normalize.js';
import { loadLithuaniaSources } from './lithuania.js'; import { loadLithuaniaSources } from './lithuania.js';
import { loadTaiwanSources } from './taiwan.js';
import { import {
loadAustinSourcesFromOpenData, loadAustinSourcesFromOpenData,
loadCaltransSourcesFromOpenData, loadCaltransSourcesFromOpenData,
@@ -20,14 +19,12 @@ import {
loadNswSourcesFromOpenData, loadNswSourcesFromOpenData,
loadCalgarySourcesFromOpenData, loadCalgarySourcesFromOpenData,
loadCataloniaSourcesFromOpenData, loadCataloniaSourcesFromOpenData,
loadHkSourcesFromOpenData,
loadDelDOTSourcesFromOpenData, loadDelDOTSourcesFromOpenData,
loadKingCountySourcesFromOpenData, loadKingCountySourcesFromOpenData,
loadWsdotSourcesFromOpenData, loadWsdotSourcesFromOpenData,
loadVegvesenSourcesFromOpenData, loadVegvesenSourcesFromOpenData,
loadNycSourcesFromOpenData, loadNycSourcesFromOpenData,
loadTorontoSourcesFromOpenData, loadTorontoSourcesFromOpenData,
loadFloridaSourcesFromOpenData,
} from './sources.js'; } from './sources.js';
/** Env kill switch: unset or anything but "0" means enabled. */ /** Env kill switch: unset or anything but "0" means enabled. */
@@ -108,11 +105,6 @@ const LIVE_PACKS = [
enabled: () => envEnabled('CCTV_CATALONIA_ENABLED'), enabled: () => envEnabled('CCTV_CATALONIA_ENABLED'),
load: loadCataloniaSourcesFromOpenData, load: loadCataloniaSourcesFromOpenData,
}, },
{
name: 'hk',
enabled: () => envEnabled('CCTV_HK_ENABLED'),
load: loadHkSourcesFromOpenData,
},
{ {
name: 'deldot', name: 'deldot',
enabled: () => envEnabled('CCTV_DELDOT_ENABLED'), enabled: () => envEnabled('CCTV_DELDOT_ENABLED'),
@@ -152,19 +144,6 @@ const LIVE_PACKS = [
enabled: () => envOptIn('CCTV_LITHUANIA_ENABLED'), enabled: () => envOptIn('CCTV_LITHUANIA_ENABLED'),
load: loadLithuaniaSources, load: loadLithuaniaSources,
}, },
{
// FL511's terms limit its content to individual, personal use (other use
// needs FDOT's written consent), so the pack is off unless the operator
// opts in (see DATA_SOURCES.md).
name: 'florida',
enabled: () => envOptIn('CCTV_FLORIDA_ENABLED'),
load: loadFloridaSourcesFromOpenData,
},
{
name: 'taiwan',
enabled: () => envEnabled('CCTV_TAIWAN_ENABLED'),
load: loadTaiwanSources,
},
]; ];
/** /**
* Load CCTV sources from a local JSON file (CCTV_SOURCES_FILE env or default). * Load CCTV sources from a local JSON file (CCTV_SOURCES_FILE env or default).
@@ -216,19 +195,16 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
/** @type {Promise<Array<object>>|null} In-flight refresh, shared by concurrent /** @type {Promise<Array<object>>|null} In-flight refresh, shared by concurrent
* callers so a post-TTL burst launches ONE refetch, not one per request. */ * callers so a post-TTL burst launches ONE refetch, not one per request. */
let _cctvSourceInflight = null; let _cctvSourceInflight = null;
/** @type {WeakMap<Array<object>, Array<{pack: string, available: number, served: number}>>} /** @type {Array<{pack: string, available: number, served: number}>} Packs
* Packs that serve fewer cameras than they offer, keyed by the source list * that serve fewer cameras than they offer. */
* they describe, so a request served the old list during a background let _cctvTrimmedPacks = [];
* refresh never pairs it with the new list's trim notes. */
const _cctvTrimmedPacks = new WeakMap();
/** /**
* Assemble and cache the merged CCTV source list. * Assemble and cache the merged CCTV source list.
* *
* Merges every source pack (live open-data packs, local file, env * Merges every source pack (live open-data packs, local file, env
* variable), deduplicates by ID, shares the catalog cap fairly across * variable), deduplicates by ID, shares the catalog cap fairly across
* packs, and caches for CCTV_SOURCE_CACHE_MS. Past that, the cached list is * packs, and caches for CCTV_SOURCE_CACHE_MS.
* returned while a background refresh replaces it; only a first load waits.
* *
* @returns {Promise<Array<object>>} Deduplicated, capped source list. * @returns {Promise<Array<object>>} Deduplicated, capped source list.
*/ */
@@ -243,31 +219,11 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
// Single-flight: a burst of requests arriving past the TTL shares ONE refresh // Single-flight: a burst of requests arriving past the TTL shares ONE refresh
// instead of each launching the full multi-provider refetch. The `.finally` // instead of each launching the full multi-provider refetch. The `.finally`
// clears the ref so the next post-TTL cycle starts fresh. // clears the ref so the next post-TTL cycle starts fresh.
if (!_cctvSourceInflight) { if (_cctvSourceInflight) return _cctvSourceInflight;
_cctvSourceInflight = refreshCctvSources().finally(() => { _cctvSourceInflight = refreshCctvSources().finally(() => {
_cctvSourceInflight = null; _cctvSourceInflight = null;
}); });
// A background refresh has no caller waiting on it: report its failure return _cctvSourceInflight;
// here, once per refresh rather than once per request it serves. Keep
// the old catalog for another TTL, as an empty refresh does, so a refresh
// that keeps failing is retried once per TTL, not back to back.
if (_cctvSourceCache.length) {
_cctvSourceInflight.catch((error) => {
_cctvSourceCacheAt = Date.now();
console.warn(
'[CCTV] background catalog refresh failed; serving',
_cctvSourceCache.length,
'cameras from the last catalog:',
error?.message || error,
);
});
}
}
// With a catalog in hand, answer with it while the refresh runs: the
// refresh lasts as long as the slowest pack (Tarktee's DATEX feeds take up
// to its 30 s timeout), and every /api/cctv request would otherwise wait
// for it. Only the first load, with nothing to serve yet, waits.
return _cctvSourceCache.length ? _cctvSourceCache : _cctvSourceInflight;
} }
/** /**
@@ -357,7 +313,7 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
} }
if (capped.length > 0 || _cctvSourceCache.length === 0) { if (capped.length > 0 || _cctvSourceCache.length === 0) {
_cctvSourceCache = capped; _cctvSourceCache = capped;
_cctvTrimmedPacks.set(capped, trimmedPacks); _cctvTrimmedPacks = trimmedPacks;
} else { } else {
// Every source came back empty (all live packs timed out / upstream outage) // Every source came back empty (all live packs timed out / upstream outage)
// but a good catalog is already cached — serve it stale rather than blanking // but a good catalog is already cached — serve it stale rather than blanking
@@ -371,10 +327,7 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
return _cctvSourceCache; return _cctvSourceCache;
} }
/** Packs serving fewer cameras than they offer in `sources` (by default the /** Packs serving fewer cameras than they offer, as of the last refresh. */
* current catalog). Pass the list a request was served to keep the two in getCctvSources.trimmedPacks = () => _cctvTrimmedPacks;
* step while a background refresh swaps the catalog. */
getCctvSources.trimmedPacks = (sources = _cctvSourceCache) =>
_cctvTrimmedPacks.get(sources) ?? [];
return getCctvSources; return getCctvSources;
} }
+1 -101
View File
@@ -113,34 +113,13 @@ export const CALTRANS_ANCHORS = [
{ lat: 32.7157, lon: -117.1611 }, // San Diego { lat: 32.7157, lon: -117.1611 }, // San Diego
{ lat: 38.5816, lon: -121.4944 }, // Sacramento { lat: 38.5816, lon: -121.4944 }, // Sacramento
]; ];
export const FLORIDA_CCTV_URL =
'https://services.arcgis.com/3wFbqsFPLeKqOlIK/arcgis/rest/services/FL511_Traffic_Cameras/FeatureServer/0/query';
export const FLORIDA_IMAGE_HOSTS = [
'images-dis.divas.cloud',
'snapshots.divas.cloud',
];
export const DEFAULT_FLORIDA_MAX_SOURCES = 500;
/** Byte cap per catalog page (2,000 rows, about 650 KiB measured). */
export const FLORIDA_MAX_CATALOG_BYTES = 2 * 1024 * 1024;
/** Catalog page ceiling: 40 pages covers 4,000+ cameras even at 100 rows a page. */
export const FLORIDA_MAX_CATALOG_PAGES = 40;
export const FLORIDA_ANCHORS = [
{ lat: 25.7617, lon: -80.1918 }, // Miami
{ lat: 28.5384, lon: -81.3789 }, // Orlando
{ lat: 27.9506, lon: -82.4572 }, // Tampa
{ lat: 30.3322, lon: -81.6557 }, // Jacksonville
{ lat: 30.4383, lon: -84.2807 }, // Tallahassee
{ lat: 26.1224, lon: -80.1373 }, // Fort Lauderdale
{ lat: 26.7153, lon: -80.0534 }, // West Palm Beach
{ lat: 30.4213, lon: -87.2169 }, // Pensacola (panhandle)
];
/** TfL JamCams: one keyless list endpoint; frames live on a public S3 bucket. */ /** TfL JamCams: one keyless list endpoint; frames live on a public S3 bucket. */
export const TFL_JAMCAM_URL = 'https://api.tfl.gov.uk/Place/Type/JamCam'; export const TFL_JAMCAM_URL = 'https://api.tfl.gov.uk/Place/Type/JamCam';
export const TFL_IMAGE_ORIGIN = export const TFL_IMAGE_ORIGIN =
'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/'; 'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/';
export const DEFAULT_TFL_MAX_SOURCES = 250; export const DEFAULT_TFL_MAX_SOURCES = 250;
export const LONDON_CENTER = { lat: 51.5074, lon: -0.1278 }; export const LONDON_CENTER = { lat: 51.5074, lon: -0.1278 };
/** Ontario 511: CARS/511 camera catalog, which needs a developer key (ONTARIO_511_API_KEY); frame URLs are still images. */ /** Ontario 511: keyless CARS/511 camera catalog; frame URLs are still images. */
export const ONTARIO_511_CAMERAS_URL = export const ONTARIO_511_CAMERAS_URL =
'https://511on.ca/api/v2/get/cameras?format=json&lang=en'; 'https://511on.ca/api/v2/get/cameras?format=json&lang=en';
export const ONTARIO_511_IMAGE_ORIGIN = 'https://511on.ca/map/Cctv/'; export const ONTARIO_511_IMAGE_ORIGIN = 'https://511on.ca/map/Cctv/';
@@ -209,8 +188,6 @@ export const TARKTEE_IMAGES_URL =
'https://tarktee.transpordiamet.ee/api/v1/datex/roadCameraImages'; 'https://tarktee.transpordiamet.ee/api/v1/datex/roadCameraImages';
export const TARKTEE_IMAGE_ORIGIN = 'https://tarktee.transpordiamet.ee/images/'; export const TARKTEE_IMAGE_ORIGIN = 'https://tarktee.transpordiamet.ee/images/';
export const DEFAULT_TARKTEE_MAX_SOURCES = 179; export const DEFAULT_TARKTEE_MAX_SOURCES = 179;
/** Hard ceiling per Tarktee DATEX XML document (~120–165 KB live). */
export const TARKTEE_MAX_CATALOG_BYTES = 4 * 1024 * 1024;
export const TARKTEE_ANCHORS = [ export const TARKTEE_ANCHORS = [
{ lat: 59.437, lon: 24.753 }, // Tallinn { lat: 59.437, lon: 24.753 }, // Tallinn
{ lat: 58.378, lon: 26.729 }, // Tartu { lat: 58.378, lon: 26.729 }, // Tartu
@@ -309,36 +286,6 @@ export const CATALONIA_ANCHORS = [
{ lat: 41.5636, lon: 2.0111 }, // Terrassa { lat: 41.5636, lon: 2.0111 }, // Terrassa
]; ];
/** Hong Kong Transport Department traffic snapshot cameras: keyless English
* locations XML on DATA.GOV.HK; frames are stills on the TD CCTV host. */
export const DEFAULT_HK_CAMERAS_URL =
'https://static.data.gov.hk/td/traffic-snapshot-images/code/Traffic_Camera_Locations_En.xml';
/** The only origin HK camera frames may come from. Verified 2026-10-11: still
* URLs answer 200 on this host with no redirect hop. */
export const HK_IMAGE_ORIGIN = 'https://tdcctv.data.one.gov.hk/';
/** Above the full TD English catalog (~1,013 cameras) so a default install
* keeps nearly all of them. Catalog-wide round-robin still applies when the
* sum of packs exceeds DEFAULT_CCTV_MAX_SOURCES (Norway-style). */
export const DEFAULT_HK_MAX_SOURCES = 1100;
/** Prioritization anchors across Hong Kong Island, Kowloon and the New
* Territories so a lowered cap keeps territory-wide coverage rather than
* only the harbour corridor. */
export const HK_ANCHORS = [
{ lat: 22.2819, lon: 114.158 }, // Central
{ lat: 22.2976, lon: 114.1722 }, // Tsim Sha Tsui
{ lat: 22.3827, lon: 114.19 }, // Sha Tin
{ lat: 22.3701, lon: 114.114 }, // Tsuen Wan
{ lat: 22.4503, lon: 114.1688 }, // Tai Po
{ lat: 22.493, lon: 114.139 }, // Fanling
{ lat: 22.391, lon: 113.977 }, // Tuen Mun
{ lat: 22.4445, lon: 114.022 }, // Yuen Long
{ lat: 22.307, lon: 114.26 }, // Tseung Kwan O
];
/** Hard ceiling on the locations XML body. The live English list is ~400 KB
* for ~1,000 cameras; this only exists so an unbounded upstream cannot be
* buffered without limit. */
export const HK_MAX_CATALOG_BYTES = 4 * 1024 * 1024;
/** Statens vegvesen (Norway) road cameras: the keyless OGC API Features view /** Statens vegvesen (Norway) road cameras: the keyless OGC API Features view
* of the official DATEX 3.1 CCTV site table, one GeoJSON request for the whole * of the official DATEX 3.1 CCTV site table, one GeoJSON request for the whole
* country (~900 cameras). The raw DATEX node needs an account; this view does * country (~900 cameras). The raw DATEX node needs an account; this view does
@@ -370,49 +317,6 @@ export const NORWAY_ANCHORS = [
{ lat: 69.6492, lon: 18.9553 }, // Tromsø { lat: 69.6492, lon: 18.9553 }, // Tromsø
]; ];
/** Kartverket's keyless point-height API (CC BY 4.0): terrain height above
* sea level (NN2000), used as the Vegvesen cameras' ground prior because the
* camera feed's points are 2D. */
export const KARTVERKET_HEIGHT_URL =
'https://ws.geonorge.no/hoydedata/v1/punkt';
/** Points per request. The API takes up to 50, but above ~20 it answers the
* extra points from contour lines (`hoydekurver`, metres to ~20 m off) or not
* at all; at 20 nearly every camera resolves from the 1 m terrain model. */
export const KARTVERKET_MAX_POINTS = 20;
/** Requests in flight at once. The whole country is ~36 requests of
* 0.6-9.5 s each, so a cold lookup takes ~6-13 s. */
export const KARTVERKET_CONCURRENCY = 8;
/** Deadline for one complete lookup, shared by every request. A lookup cut
* short by it is resumed on the next refresh, without a backoff. */
export const KARTVERKET_LOOKUP_TIMEOUT_MS = 30 * 1000;
/** One request that takes longer than this counts as a failing service. */
export const KARTVERKET_REQUEST_TIMEOUT_MS = 10 * 1000;
/** The Vegvesen lane's budget, measured from the start of the loader (catalog
* fetch included), for waiting on heights. Under the 15 s per-provider fetch
* timeout so this pack is never the catalog's slowest lane. A lookup still
* running after it keeps filling the cache for the next refresh. */
export const KARTVERKET_CATALOG_WAIT_MS = 12 * 1000;
/** The lane only waits when more than this share of its cameras has no
* answer yet (a cold cache). A few new cameras or expired misses are looked
* up in the background instead of holding the refresh. */
export const KARTVERKET_WAIT_MISSING_SHARE = 0.1;
/** A point Kartverket has no height for (some ferry quays and bridges) is not
* asked about again for this long. */
export const KARTVERKET_NULL_TTL_MS = 6 * 60 * 60 * 1000;
/** After a failing request (408, 429, 5xx, a network error, a request
* timeout or an unreadable body), no lookup starts for this long, or for the
* Retry-After the service sent, bounded to [1 min, 1 h]. Longer than the
* 15-minute catalog refresh (CCTV_SOURCE_CACHE_MS), so a failing service
* costs one attempt per backoff, not one per refresh. */
export const KARTVERKET_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
export const KARTVERKET_MAX_BACKOFF_MS = 60 * 60 * 1000;
export const KARTVERKET_MAX_RESPONSE_BYTES = 256 * 1024;
/** Plausible Norwegian terrain: below sea level only at the shore, and no road
* camera sits above ~1,500 m. Anything outside is treated as no height. */
export const KARTVERKET_HEIGHT_RANGE_M = Object.freeze({ min: -20, max: 2500 });
/** Same identity the other CCTV upstream requests send. */
export const KARTVERKET_USER_AGENT = 'gods-eye-view-cctv-proxy/1.0';
/** NYC DOT Traffic Management Center cameras: one keyless JSON list for the /** NYC DOT Traffic Management Center cameras: one keyless JSON list for the
* five boroughs (~980 cameras). Frames are stills synthesized from each * five boroughs (~980 cameras). Frames are stills synthesized from each
* camera UUID on the city's webcam host — never taken from the payload. */ * camera UUID on the city's webcam host — never taken from the payload. */
@@ -535,10 +439,6 @@ export const CCTV_SOURCE_CACHE_MS = 15 * 60 * 1000;
* pending forever — a hung fetch aborts, the loader returns [], and * pending forever — a hung fetch aborts, the loader returns [], and
* serve-stale/other packs take over. */ * serve-stale/other packs take over. */
export const CCTV_SOURCE_FETCH_TIMEOUT_MS = 15 * 1000; export const CCTV_SOURCE_FETCH_TIMEOUT_MS = 15 * 1000;
/** Tarktee's two DATEX feeds (120 and 160 KB) answered in 2 to 16.6 s across
* ten requests on 2026-10-18, so the shared 15 s timeout dropped the Estonian
* pack on about a third of loads. Both must arrive for any camera to load. */
export const TARKTEE_FETCH_TIMEOUT_MS = 30 * 1000;
/** Individual CCTV image fetches must settle before the active 10-second /** Individual CCTV image fetches must settle before the active 10-second
* client refresh cadence. A bounded miss can fall through to Street View or * client refresh cadence. A bounded miss can fall through to Street View or
* the synthetic frame instead of leaving the browser preview pending. */ * the synthetic frame instead of leaving the browser preview pending. */
-22
View File
@@ -377,17 +377,6 @@ export function isLikelyCalgaryCoordinate(lat, lon) {
); );
} }
/** Florida statewide, Key West to Georgia state line, with slack at each edge */
export function isLikelyFloridaCoordinate(lat, lon) {
return (
isPlausibleLatLon(lat, lon) &&
lat >= 24.3 &&
lat <= 31.1 &&
lon >= -87.7 &&
lon <= -79.8
);
}
/** New York City's five boroughs, with slack for the harbor and city line. */ /** New York City's five boroughs, with slack for the harbor and city line. */
export function isLikelyNycCoordinate(lat, lon) { export function isLikelyNycCoordinate(lat, lon) {
return ( return (
@@ -399,17 +388,6 @@ export function isLikelyNycCoordinate(lat, lon) {
); );
} }
/** Hong Kong SAR extent, with slack for the outlying islands. */
export function isLikelyHongKongCoordinate(lat, lon) {
return (
isPlausibleLatLon(lat, lon) &&
lat >= 22.15 &&
lat <= 22.6 &&
lon >= 113.8 &&
lon <= 114.45
);
}
/** Mainland Norway, with slack for the coast and the Finnmark border. */ /** Mainland Norway, with slack for the coast and the Finnmark border. */
export function isLikelyNorwayCoordinate(lat, lon) { export function isLikelyNorwayCoordinate(lat, lon) {
return ( return (
-129
View File
@@ -1,129 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
_resetOntarioKeyWarningForTest,
loadOntarioSourcesFromOpenData,
} from './sources.js';
const ROW = {
Id: '42',
Latitude: 43.6532,
Longitude: -79.3832,
Location: 'Hwy 401 near Yonge St',
Direction: 'Eastbound',
Views: [
{
Status: 'Enabled',
Url: 'https://511on.ca/map/Cctv/4201',
Description: 'Eastbound',
},
],
};
function captureConsole(t) {
const lines = [];
const capture = (...args) => lines.push(args.join(' '));
t.mock.method(console, 'warn', capture);
t.mock.method(console, 'log', capture);
return lines;
}
test.beforeEach(() => _resetOntarioKeyWarningForTest());
test('without ONTARIO_511_API_KEY the Ontario pack is skipped, logged once', async (t) => {
const lines = captureConsole(t);
let fetches = 0;
t.mock.method(globalThis, 'fetch', async () => {
fetches += 1;
return Response.json([ROW]);
});
assert.deepEqual(await loadOntarioSourcesFromOpenData({}, {}), []);
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: ' ' }),
[],
);
assert.equal(fetches, 0);
assert.equal(lines.length, 1);
assert.match(lines[0], /ONTARIO_511_API_KEY/);
});
test('with a key the camera list is requested with it and parsed', async (t) => {
const lines = captureConsole(t);
const requested = [];
t.mock.method(globalThis, 'fetch', async (url) => {
requested.push(String(url));
return Response.json([ROW]);
});
const cameras = await loadOntarioSourcesFromOpenData(
{ sourceRoot: '/ignored' },
{ ONTARIO_511_API_KEY: ' test-key ' },
);
assert.equal(requested.length, 1);
const url = new URL(requested[0]);
assert.equal(url.host, '511on.ca');
assert.equal(url.searchParams.get('key'), 'test-key');
assert.equal(url.searchParams.get('format'), 'json');
assert.equal(cameras.length, 1);
assert.equal(cameras[0].id, 'on-42');
assert.equal(cameras[0].url, 'https://511on.ca/map/Cctv/4201');
// The records go to the browser through /api/cctv; the key must stay on
// the server-side catalog request.
assert.doesNotMatch(JSON.stringify(cameras), /test-key/);
assert.doesNotMatch(lines.join('\n'), /test-key/);
});
test('the source cap is read from the same environment as the key', async (t) => {
captureConsole(t);
const rows = Array.from({ length: 12 }, (_, i) => ({
...ROW,
Id: String(100 + i),
Latitude: ROW.Latitude + i * 0.01,
Views: [{ ...ROW.Views[0], Url: `https://511on.ca/map/Cctv/${100 + i}` }],
}));
t.mock.method(globalThis, 'fetch', async () => Response.json(rows));
const cameras = await loadOntarioSourcesFromOpenData(
{},
{ ONTARIO_511_API_KEY: 'test-key', CCTV_ONTARIO_MAX_SOURCES: '8' },
);
assert.equal(cameras.length, 8);
});
for (const status of [400, 401, 403]) {
test(`a ${status} points at the key by name, never by value`, async (t) => {
const lines = captureConsole(t);
t.mock.method(globalThis, 'fetch', async () =>
Response.json({ Message: 'Invalid Key' }, { status }),
);
const cameras = await loadOntarioSourcesFromOpenData(
{},
{ ONTARIO_511_API_KEY: 'secret-key-value' },
);
assert.deepEqual(cameras, []);
assert.match(
lines.join('\n'),
new RegExp(`failed: ${status} \\(check ONTARIO_511_API_KEY\\)`),
);
assert.doesNotMatch(lines.join('\n'), /secret-key-value/);
});
}
for (const status of [429, 500, 503]) {
test(`a ${status} is reported without blaming the key`, async (t) => {
const lines = captureConsole(t);
t.mock.method(globalThis, 'fetch', async () =>
Response.json({}, { status }),
);
const cameras = await loadOntarioSourcesFromOpenData(
{},
{ ONTARIO_511_API_KEY: 'secret-key-value' },
);
assert.deepEqual(cameras, []);
assert.equal(lines.length, 1);
assert.equal(
lines[0],
`[CCTV] Ontario 511 camera download failed: ${status}`,
);
assert.doesNotMatch(lines[0], /secret-key-value/);
});
}
File diff suppressed because it is too large. Load diff
+13 -46
View File
@@ -4,7 +4,6 @@ import { randomUUID } from 'node:crypto';
export const HLS_LIMITS = Object.freeze({ export const HLS_LIMITS = Object.freeze({
sessions: 2, sessions: 2,
leasesPerSession: 8, leasesPerSession: 8,
leasesPerClient: 8,
playlistBytes: 256 * 1024, playlistBytes: 256 * 1024,
segmentBytes: 4 * 1024 * 1024, segmentBytes: 4 * 1024 * 1024,
sessionBytes: 24 * 1024 * 1024, sessionBytes: 24 * 1024 * 1024,
@@ -139,37 +138,25 @@ export function createHlsPuller({
entry.upstream.clear(); entry.upstream.clear();
entry.bytes = 0; entry.bytes = 0;
}; };
const release = (cameraId, leaseId, clientId = 'legacy') => { const release = (cameraId, leaseId) => {
const entry = active.get(cameraId); const entry = active.get(cameraId);
const lease = entry?.leases.get(leaseId); const lease = entry?.leases.get(leaseId);
if (!lease || lease.clientId !== clientId) return; if (!lease) return;
clearTimeout(lease.timer); clearTimeout(lease.timer);
entry.leases.delete(leaseId); entry.leases.delete(leaseId);
if (!entry.leases.size) stop(cameraId, entry.token); if (!entry.leases.size) stop(cameraId, entry.token);
}; };
const touch = (entry, leaseId, create = false, clientId = 'legacy') => { const touch = (entry, leaseId, create = false) => {
let lease = entry.leases.get(leaseId); let lease = entry.leases.get(leaseId);
if (lease && lease.clientId !== clientId)
throw new Error('HLS lease belongs to another client');
if (!lease) { if (!lease) {
const clientLeases = [...active.values()].reduce(
(count, session) =>
count +
[...session.leases.values()].filter(
(item) => item.clientId === clientId,
).length,
0,
);
if (clientLeases >= limits.leasesPerClient)
throw new Error('HLS client lease capacity reached');
if (!create || entry.leases.size >= limits.leasesPerSession) if (!create || entry.leases.size >= limits.leasesPerSession)
throw new Error('HLS lease capacity reached'); throw new Error('HLS lease capacity reached');
lease = { clientId }; lease = {};
entry.leases.set(leaseId, lease); entry.leases.set(leaseId, lease);
} }
clearTimeout(lease.timer); clearTimeout(lease.timer);
lease.timer = setTimeout( lease.timer = setTimeout(
() => release(entry.cameraId, leaseId, clientId), () => release(entry.cameraId, leaseId),
limits.idleMs, limits.idleMs,
); );
lease.timer.unref?.(); lease.timer.unref?.();
@@ -261,12 +248,7 @@ export function createHlsPuller({
} }
} }
}; };
const ensure = async ( const ensure = async (cameraId, url, leaseId = 'legacy') => {
cameraId,
url,
leaseId = 'legacy',
clientId = 'legacy',
) => {
if (closed) throw new Error('HLS service closed'); if (closed) throw new Error('HLS service closed');
sameOriginHlsUrl(url, url); sameOriginHlsUrl(url, url);
let entry = active.get(cameraId); let entry = active.get(cameraId);
@@ -275,7 +257,7 @@ export function createHlsPuller({
entry = null; entry = null;
} }
if (entry) { if (entry) {
touch(entry, leaseId, true, clientId); touch(entry, leaseId, true);
return entry; return entry;
} }
// Reserve synchronously, before any await: concurrent creation is singleflight. // Reserve synchronously, before any await: concurrent creation is singleflight.
@@ -297,8 +279,8 @@ export function createHlsPuller({
pendingDiscontinuity: false, pendingDiscontinuity: false,
discontinuitiesRemoved: 0, discontinuitiesRemoved: 0,
}; };
touch(entry, leaseId, true, clientId);
active.set(cameraId, entry); active.set(cameraId, entry);
touch(entry, leaseId, true);
entry.polling = poll(entry); entry.polling = poll(entry);
return entry; return entry;
}; };
@@ -310,14 +292,9 @@ export function createHlsPuller({
} }
return false; return false;
}; };
const buildPlaylist = async ( const buildPlaylist = async (entry, cameraId, leaseId = 'legacy') => {
entry,
cameraId,
leaseId = 'legacy',
clientId = 'legacy',
) => {
if (entry.stopping || entry.segments.size < 2) return null; if (entry.stopping || entry.segments.size < 2) return null;
touch(entry, leaseId, false, clientId); touch(entry, leaseId);
const segments = [...entry.segments.values()].sort((a, b) => a.seq - b.seq); const segments = [...entry.segments.values()].sort((a, b) => a.seq - b.seq);
const lines = [ const lines = [
'#EXTM3U', '#EXTM3U',
@@ -341,22 +318,12 @@ export function createHlsPuller({
} }
return lines.join('\n') + '\n'; return lines.join('\n') + '\n';
}; };
const getSegment = ( const getSegment = (cameraId, token, seq, leaseId = 'legacy') => {
cameraId,
token,
seq,
leaseId = 'legacy',
clientId = 'legacy',
) => {
const entry = active.get(cameraId); const entry = active.get(cameraId);
if ( if (!entry || entry.token !== token || !entry.leases.has(leaseId))
!entry ||
entry.token !== token ||
entry.leases.get(leaseId)?.clientId !== clientId
)
return null; return null;
const body = entry.segments.get(seq)?.body; const body = entry.segments.get(seq)?.body;
if (body) touch(entry, leaseId, false, clientId); if (body) touch(entry, leaseId);
return body || null; return body || null;
}; };
const shutdown = async () => { const shutdown = async () => {
-303
View File
@@ -1,303 +0,0 @@
import { CCTV_SOURCE_FETCH_TIMEOUT_MS } from './constants.js';
import {
cameraDisplayCode,
fallbackHeadingFromId,
prioritizeSources,
} from './normalize.js';
import { readResponseTextCapped } from '../common/http.js';
/** Freeway Bureau (MOTC) CCTV static table in the national MOTC 2.0 XML
* standard, published keyless and refreshed daily (~1,800 cameras). */
export const TAIWAN_FREEWAY_CCTV_URL =
'https://tisvcloud.freeway.gov.tw/history/motc20/CCTV.xml';
/** The whole network is ~1.2 MB. */
export const TAIWAN_MAX_CATALOG_BYTES = 6 * 1024 * 1024;
export const DEFAULT_TAIWAN_MAX_SOURCES = 600;
/** After a failed download, wait this long before asking again. The catalog
* host does not answer from some networks outside Taiwan, and every attempt
* there holds the shared catalog refresh until the connect timeout. */
export const TAIWAN_RETRY_AFTER_FAILURE_MS = 60 * 60 * 1000;
/** The table is republished daily; a good copy stands in for a failed
* download for up to this long. */
export const TAIWAN_LAST_GOOD_MAX_AGE_MS = 24 * 60 * 60 * 1000;
// The table publishes each camera's MJPEG stream. The same camera servers
// answer a single JPEG for the same camera ID on a sibling path, which is what
// the frame proxy can relay; only these exact pairs are ever registered.
const STREAM_TO_FRAME = new Map([
['cctvn.freeway.gov.tw', ['/abs2mjpg/bmjpg', '/abs2mjpg/jpg']],
['cctvn5.freeway.gov.tw', ['/abs2mjpg/bmjpg', '/abs2mjpg/jpg']],
['cctvc.freeway.gov.tw', ['/abs2mjpg/bmjpg', '/abs2mjpg/jpg']],
[
'cctvs.freeway.gov.tw',
['/live-view/mjpg/video.cgi', '/live-view/jpg/image.cgi'],
],
]);
const DIRECTIONS = { N: 'N', S: 'S', E: 'E', W: 'W' };
/** Prioritization anchors, north to south, so a cap keeps the whole island
* rather than only greater Taipei. */
const ANCHORS = [
{ lat: 25.033, lon: 121.5654 }, // Taipei
{ lat: 24.9936, lon: 121.301 }, // Taoyuan
{ lat: 24.8138, lon: 120.9675 }, // Hsinchu
{ lat: 24.7021, lon: 121.7378 }, // Yilan
{ lat: 24.1477, lon: 120.6736 }, // Taichung
{ lat: 22.9999, lon: 120.227 }, // Tainan
{ lat: 22.6273, lon: 120.3014 }, // Kaohsiung
];
/** Taiwan main island with slack for the coast; the freeway network has no
* offshore-island cameras. */
export function isLikelyTaiwanCoordinate(lat, lon) {
return (
Number.isFinite(lat) &&
Number.isFinite(lon) &&
lat >= 21.8 &&
lat <= 25.4 &&
lon >= 119.9 &&
lon <= 122.1
);
}
const XML_ENTITIES = {
amp: '&',
lt: '<',
gt: '>',
quot: '"',
apos: "'",
};
function codePoint(value, radix) {
const code = parseInt(value, radix);
return Number.isInteger(code) && code > 0 && code <= 0x10ffff
? String.fromCodePoint(code)
: '';
}
function decodeXml(text) {
return String(text ?? '')
.replace(
/&(?:(amp|lt|gt|quot|apos)|#(\d{1,7})|#x([0-9a-fA-F]{1,6}));/g,
(_, name, dec, hex) =>
name ? XML_ENTITIES[name] : codePoint(dec ?? hex, dec ? 10 : 16),
)
.trim();
}
function tag(block, name) {
const match = new RegExp(`<${name}>([^<]*)</${name}>`).exec(block);
return match ? decodeXml(match[1]) : '';
}
/**
* Parse the MOTC 2.0 `CCTVList` document into flat rows. Regex-based like the
* Catalonia and Tarktee parsers: the schema is flat, and only the fields used
* below are read.
*
* @param {string} xml
* @returns {Array<object>}
*/
export function parseTaiwanCctvXml(xml) {
const rows = [];
const blockRe = /<CCTV>([\s\S]*?)<\/CCTV>/g;
let match;
while ((match = blockRe.exec(String(xml || ''))) !== null) {
const block = match[1];
rows.push({
cctvId: tag(block, 'CCTVID'),
streamUrl: tag(block, 'VideoStreamURL'),
lat: Number(tag(block, 'PositionLat')),
lon: Number(tag(block, 'PositionLon')),
roadName: tag(block, 'RoadName'),
direction: tag(block, 'RoadDirection'),
sectionStart: tag(block, 'Start'),
sectionEnd: tag(block, 'End'),
mile: tag(block, 'LocationMile'),
});
}
return rows;
}
/**
* Published MJPEG stream URL -> the same camera's still, plus the host and
* camera number that identify it, or null.
*
* @param {string} streamUrl
* @returns {?{frameUrl: string, host: string, camera: string}}
*/
export function taiwanFrame(streamUrl) {
let url;
try {
url = new URL(String(streamUrl ?? ''));
} catch {
return null;
}
if (url.protocol !== 'https:' || url.username || url.password || url.port)
return null;
const paths = STREAM_TO_FRAME.get(url.hostname);
if (!paths || url.pathname !== paths[0]) return null;
const camera = url.searchParams.get('camera') || '';
if (!/^[A-Za-z0-9-]{1,40}$/.test(camera)) return null;
return {
// Reconstruct so extra query parameters cannot alter the request.
frameUrl: `https://${url.hostname}${paths[1]}?camera=${camera}`,
host: url.hostname.split('.')[0],
camera,
};
}
/**
* One parsed Freeway Bureau row -> one catalog source, or null.
*
* @param {object} row - Output of parseTaiwanCctvXml.
* @returns {?object}
*/
export function taiwanCameraToSource(row) {
if (!row || typeof row !== 'object') return null;
const { lat, lon } = row;
if (!isLikelyTaiwanCoordinate(lat, lon)) return null;
const frame = taiwanFrame(row.streamUrl);
if (!frame) return null;
const imageUrl = frame.frameUrl;
// CCTVID carries Chinese place names and a few IDs repeat across distinct
// cameras, so the stable key is the camera server plus its camera number.
const rawId = String(row.cctvId ?? '')
.trim()
.slice(0, 80);
const cameraId = `tw-freeway-${frame.host}-${frame.camera.toLowerCase()}`;
const road = String(row.roadName ?? '').trim();
const direction = DIRECTIONS[String(row.direction ?? '').trim()] || '';
const mile = String(row.mile ?? '').trim();
const section = [row.sectionStart, row.sectionEnd]
.map((part) => String(part ?? '').trim())
.filter(Boolean)
.join('→');
// A bare carriageway letter is not a name; fall back to the published ID.
const name =
(road || mile || section
? [road, direction, mile, section].filter(Boolean).join(' ')
: '') ||
rawId ||
`Freeway camera ${frame.camera}`;
return {
id: cameraId,
name: name.slice(0, 160),
// One island-wide category in the camera picker, like Finland and Norway.
city: 'Taiwan / 臺灣',
cityId: 'taiwan',
provider: 'Freeway Bureau, MOTC',
lat,
lon,
// The table gives the carriageway direction, not the camera's bearing,
// so the pose uses the shared low-confidence prior.
headingDeg: fallbackHeadingFromId(cameraId),
headingConfidence: 'low',
pitchDeg: -18,
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
feedType: 'image',
url: imageUrl,
snapshotUrl: imageUrl,
sourceKind: 'tw-freeway-motc',
license:
'Freeway Bureau, MOTC open data, Open Government Data License, Taiwan (Version 1.0)',
code: cameraDisplayCode(
`${road} ${mile}`.trim().toUpperCase() || frame.camera,
),
};
}
let lastGood = null;
let lastGoodAt = 0;
let retryAfter = 0;
/** Forget the last good table and any failure backoff (tests only). */
export function resetTaiwanSourcesCache() {
lastGood = null;
lastGoodAt = 0;
retryAfter = 0;
}
function fallbackSources() {
return lastGood && Date.now() - lastGoodAt <= TAIWAN_LAST_GOOD_MAX_AGE_MS
? lastGood
: [];
}
function taiwanSourceCap() {
const rawCap = Number(
process.env.CCTV_TAIWAN_MAX_SOURCES || DEFAULT_TAIWAN_MAX_SOURCES,
);
return Number.isFinite(rawCap)
? Math.max(1, Math.min(2000, Math.floor(rawCap)))
: DEFAULT_TAIWAN_MAX_SOURCES;
}
/**
* Fetch Taiwan Freeway Bureau cameras from the keyless MOTC 2.0 XML table.
* One bounded request per shared catalog refresh. A failed download serves the
* last good table (up to a day old) and is not retried for an hour, so a host
* that cannot reach the Freeway Bureau does not wait on it every refresh.
*
* @returns {Promise<Array<object>>}
*/
export async function loadTaiwanSources() {
if (Date.now() < retryAfter) return fallbackSources();
try {
const signal = AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS);
const response = await fetch(
process.env.CCTV_TAIWAN_URL || TAIWAN_FREEWAY_CCTV_URL,
{
headers: { Accept: 'application/xml,text/xml' },
redirect: 'manual',
signal,
},
);
if (!response.ok) {
await response.body?.cancel().catch(() => {});
throw new Error(
response.status >= 300 && response.status < 400
? 'catalog redirected; redirects are not followed'
: `HTTP ${response.status}`,
);
}
const xml = await readResponseTextCapped(
response,
TAIWAN_MAX_CATALOG_BYTES,
signal,
);
const cameras = new Map();
for (const row of parseTaiwanCctvXml(xml)) {
const camera = taiwanCameraToSource(row);
if (camera && !cameras.has(camera.id)) cameras.set(camera.id, camera);
}
if (!cameras.size) throw new Error('no usable cameras in the table');
const sources = prioritizeSources(
[...cameras.values()],
taiwanSourceCap(),
ANCHORS,
);
console.log(
`[CCTV] Loaded Taiwan camera sources: ${cameras.size} (using ${sources.length})`,
);
lastGood = sources;
lastGoodAt = Date.now();
retryAfter = 0;
return sources;
} catch (error) {
retryAfter = Date.now() + TAIWAN_RETRY_AFTER_FAILURE_MS;
const fallback = fallbackSources();
console.warn(
`[CCTV] Taiwan camera download failed (${error?.message || error}); ` +
(fallback.length
? `serving the last good ${fallback.length} cameras`
: 'no Taiwan cameras') +
', next attempt in 1 h',
);
return fallback;
}
}
+8 -53
View File
@@ -14,34 +14,16 @@ async function readRequestBodyCapped(req, maxBytes) {
return Buffer.concat(chunks); return Buffer.concat(chunks);
} }
/** Optional cancellation discards buffered data while the request drains. */ function readRequestBody(req, maxBytes = 1024 * 1024) {
function readRequestBody(req, maxBytes = 1024 * 1024, signal) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let total = 0; let total = 0;
let bodyTooLarge = false; let bodyTooLarge = false;
let settled = false;
const chunks = []; const chunks = [];
const stopReading = () => { req.on('data', (chunk) => {
if (!signal) return;
req.off('data', data);
req.off('end', end);
signal.removeEventListener('abort', abort);
};
const fail = (error) => {
if (signal) {
if (settled) return;
settled = true;
chunks.length = 0;
signal.removeEventListener('abort', abort);
}
reject(error);
};
const abort = () => fail(signal.reason);
const data = (chunk) => {
// Keep draining after the cap without retaining more bytes. Destroying // Keep draining after the cap without retaining more bytes. Destroying
// the request also destroys its socket, so the handler cannot deliver // the request also destroys its socket, so the handler cannot deliver
// the fixed error response it constructs for BODY_TOO_LARGE. // the fixed error response it constructs for BODY_TOO_LARGE.
if (bodyTooLarge || settled) return; if (bodyTooLarge) return;
total += chunk.length; total += chunk.length;
if (total > maxBytes) { if (total > maxBytes) {
// Same marker readRequestBodyCapped sets, so a caller can tell an // Same marker readRequestBodyCapped sets, so a caller can tell an
@@ -50,42 +32,15 @@ function readRequestBody(req, maxBytes = 1024 * 1024, signal) {
chunks.length = 0; chunks.length = 0;
const error = new Error(`Request body exceeds ${maxBytes} bytes`); const error = new Error(`Request body exceeds ${maxBytes} bytes`);
error.code = 'BODY_TOO_LARGE'; error.code = 'BODY_TOO_LARGE';
fail(error); reject(error);
return; return;
} }
chunks.push(chunk); chunks.push(chunk);
}; });
const end = () => { req.on('end', () => {
if (settled) {
stopReading();
return;
}
if (!bodyTooLarge) resolve(Buffer.concat(chunks).toString('utf8')); if (!bodyTooLarge) resolve(Buffer.concat(chunks).toString('utf8'));
if (signal) { });
settled = true; req.on('error', reject);
chunks.length = 0;
stopReading();
}
};
const close = () => {
fail(
new DOMException('Request closed before its body ended', 'AbortError'),
);
stopReading();
req.off('error', fail);
req.off('close', close);
};
if (signal) {
// Abort/overflow release retained bytes but keep draining. Retain an
// error handler until close, including a late error after end/abort.
req.on('close', close);
signal.addEventListener('abort', abort, { once: true });
if (signal.aborted) abort();
}
req.on('data', data);
req.on('end', end);
req.on('error', fail);
if (signal && req.destroyed) close();
}); });
} }
-137
View File
@@ -1,137 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter, getEventListeners } from 'node:events';
import { readRequestBody } from './request.js';
function fixture() {
const req = new EventEmitter();
req.pause = () => assert.fail('The reader must keep draining');
req.destroy = () =>
assert.fail('The reader must preserve the response socket');
const owner = new AbortController();
return { req, owner };
}
function finish(req, owner) {
assert.doesNotThrow(() => req.emit('error', new Error('late stream error')));
req.emit('end');
assert.doesNotThrow(() => req.emit('error', new Error('error before close')));
req.emit('close');
for (const event of ['data', 'end', 'error', 'close'])
assert.equal(req.listenerCount(event), 0, event);
assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
}
test('default and cancellable readers preserve byte caps and UTF-8 across chunks', async () => {
for (const useSignal of [false, true]) {
for (const text of ['', 'hello', 'é']) {
const { req, owner } = fixture();
const bytes = Buffer.from(text);
const body = readRequestBody(
req,
bytes.length,
useSignal ? owner.signal : undefined,
);
for (const byte of bytes) req.emit('data', Buffer.from([byte]));
req.emit('end');
assert.equal(await body, text);
if (useSignal) finish(req, owner);
}
}
});
test('default overflow rejects before end and drains without pausing or destroying', async () => {
const { req } = fixture();
const rejection = assert.rejects(readRequestBody(req, 2), {
code: 'BODY_TOO_LARGE',
});
req.emit('data', Buffer.from('é'));
req.emit('data', Buffer.from('!'));
await rejection;
req.emit('data', Buffer.alloc(4096));
assert.doesNotThrow(() => req.emit('error', new Error('late')));
req.emit('end');
});
test('partial abort settles before end, discards late data and guards errors until close', async () => {
const { req, owner } = fixture();
const reason = new Error('request deadline');
const rejection = assert.rejects(
readRequestBody(req, 1024, owner.signal),
(error) => error === reason,
);
req.emit('data', Buffer.from('partial'));
owner.abort(reason);
await rejection;
assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
req.emit('data', Buffer.alloc(4096));
finish(req, owner);
});
test('already-aborted and already-closed requests settle and release their listeners', async () => {
for (const closed of [false, true]) {
const { req, owner } = fixture();
if (closed) req.destroyed = true;
else owner.abort();
await assert.rejects(readRequestBody(req, 1024, owner.signal), {
name: 'AbortError',
});
if (!closed) finish(req, owner);
for (const event of ['data', 'end', 'error', 'close'])
assert.equal(req.listenerCount(event), 0);
assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
}
});
test('overflow keeps its first failure through later abort and stream errors', async () => {
const { req, owner } = fixture();
const rejection = assert.rejects(readRequestBody(req, 2, owner.signal), {
code: 'BODY_TOO_LARGE',
});
req.emit('data', Buffer.from('é!'));
await rejection;
owner.abort(new Error('later deadline'));
req.emit('data', Buffer.alloc(4096));
finish(req, owner);
});
test('early close and request error reject once; successful end wins over later abort', async () => {
for (const event of ['close', 'error', 'end']) {
const { req, owner } = fixture();
const reason = new Error('request failed');
const body = readRequestBody(req, 32, owner.signal);
const observed =
event === 'end'
? body.then((value) => assert.equal(value, 'ok'))
: assert.rejects(
body,
event === 'close'
? { name: 'AbortError' }
: (error) => error === reason,
);
req.emit('data', Buffer.from('ok'));
req.emit(event, reason);
owner.abort(new Error('later abort'));
await observed;
if (event !== 'close') finish(req, owner);
assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
}
});
test('a prior data observer can abort synchronously without retaining or resolving that chunk', async () => {
const { req, owner } = fixture();
const reason = new Error('observer stopped request');
const external = () => owner.abort(reason);
req.on('data', external);
const rejection = assert.rejects(
readRequestBody(req, 1024, owner.signal),
(error) => error === reason,
);
req.emit('data', Buffer.from('must be discarded'));
await rejection;
req.emit('end');
req.emit('close');
assert.deepEqual(req.listeners('data'), [external]);
assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
req.off('data', external);
});
-45
View File
@@ -41,48 +41,3 @@ export function sameSiteGated(handler) {
return handler(req, res, next); return handler(req, res, next);
}; };
} }
/**
* Proxy header values arrive client-controlled; read one only when it is a
* single scheme token, never a comma-separated chain.
* @param {import('node:http').IncomingMessage} req
* @returns {'http:'|'https:'}
*/
function forwardedProtocol(req) {
if (req.socket?.encrypted) return 'https:';
const proto = String(req.headers?.['x-forwarded-proto'] || '')
.trim()
.toLowerCase();
return proto === 'https' ? 'https:' : 'http:';
}
/**
* Cross-site gate for keyless routes the map needs in order to render
* (`/api/terrain/heights`). It refuses the same cross-site browser shapes as
* `admitSameSite` (a `Sec-Fetch-Site` other than same-origin/none, a foreign
* or opaque `Origin`) but does not refuse reverse-proxy forwarding headers:
* those protect credentials and spend, which a keyless route has neither of,
* and refusing them would break rendering for an instance served behind the
* reverse proxy the README documents. A single `X-Forwarded-Proto` supplies
* the scheme an `Origin` is compared against. That header cannot be attached
* to a cross-site browser request without a CORS preflight this server never
* answers, and `Sec-Fetch-Site` is still enforced regardless.
* @param {import('node:http').IncomingMessage} req
* @param {import('node:http').ServerResponse} res
* @returns {boolean} True when a 403 was sent.
*/
export function admitSameSiteKeyless(req, res) {
const verdict = admitSameSiteRequest({
hostHeader: req.headers?.host,
protocol: forwardedProtocol(req),
origin: req.headers?.origin,
secFetchSite: req.headers?.['sec-fetch-site'],
proxyHeaders: {},
});
if (verdict.ok) return false;
res.statusCode = verdict.status;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify({ error: verdict.error }));
return true;
}
-22
View File
@@ -1,22 +0,0 @@
import { createGeminiTokenHandler } from './gemini/realtime.js';
/** Mint constrained Live API credentials; the permanent key stays on Node. */
function geminiLiveProxy({ annotationGuidance, realtime = {} } = {}) {
function install(middlewares) {
middlewares.use(
'/api/gemini/token',
createGeminiTokenHandler({ ...realtime, annotationGuidance }),
);
}
return {
name: 'gemini-live-proxy',
configureServer(server) {
install(server.middlewares);
},
configurePreviewServer(server) {
install(server.middlewares);
},
};
}
export { geminiLiveProxy };
-53
View File
@@ -1,53 +0,0 @@
import { realtimeInstructions } from '../openai/instructions.js';
import { GEV_REALTIME_TOOLS } from '../openai/tools.js';
export const GEMINI_LIVE_MODEL_DEFAULT = 'gemini-3.8-live';
export const GEMINI_TOKEN_ENDPOINT =
'https://generativelanguage.googleapis.com/v1beta/auth_tokens';
export const GEMINI_LIVE_WEBSOCKET_URL =
'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained';
export function normalizeGeminiModel(value) {
const model = String(value ?? GEMINI_LIVE_MODEL_DEFAULT)
.trim()
.replace(/^models\//, '');
return /^gemini-[a-z0-9][a-z0-9.-]{0,119}$/.test(model) ? model : null;
}
/** REST BidiGenerateContentSetup fields, excluding its model resource name. */
export function createGeminiLiveConfig(
annotationGuidance,
inputMode = 'open-mic',
tools = GEV_REALTIME_TOOLS,
) {
if (!['open-mic', 'push-to-talk'].includes(inputMode))
throw new Error('Invalid Gemini input mode');
const config = {
generationConfig: { responseModalities: ['AUDIO'] },
systemInstruction: {
parts: [{ text: realtimeInstructions(annotationGuidance) }],
},
tools: [
{
functionDeclarations: tools.map(
({ name, description, parameters }) => ({
name,
description,
// GEV's canonical schemas are JSON Schema, not Google's Schema.
parametersJsonSchema: structuredClone(parameters),
// App actions must finish before the model confirms their result.
behavior: 'BLOCKING',
}),
),
},
],
inputAudioTranscription: {},
outputAudioTranscription: {},
contextWindowCompression: { slidingWindow: {} },
};
if (inputMode === 'push-to-talk')
config.realtimeInputConfig = {
automaticActivityDetection: { disabled: true },
};
return config;
}
-208
View File
@@ -1,208 +0,0 @@
import { waitForSignal } from '../../../src/sources/requestDeadline.js';
import { clientKey, makeCostRateLimiter } from '../common/rate-limit.js';
import { readResponseJsonCapped } from '../../../src/sources/httpBody.js';
import {
GEMINI_TOKEN_ENDPOINT,
GEMINI_LIVE_WEBSOCKET_URL,
GEMINI_LIVE_MODEL_DEFAULT,
createGeminiLiveConfig,
normalizeGeminiModel,
} from './config.js';
import {
isGeminiRequestOriginAllowed,
readGeminiTokenRequest,
} from './request.js';
const UPSTREAM_RESPONSE_BYTES = 32 * 1024;
const MINT_FAILURE = 'Gemini voice could not connect. Try again.';
export function createGeminiTokenHandler({
annotationGuidance,
tools,
fetchImpl = (...args) => fetch(...args),
resolveApiKey = () => process.env.GEMINI_API_KEY,
resolveModel = () =>
process.env.GEMINI_LIVE_MODEL || GEMINI_LIVE_MODEL_DEFAULT,
resolveHost = () => process.env.HOST,
resolveAllowedHosts = () => process.env.GEV_ALLOWED_HOSTS,
resolveRateLimit = () => process.env.GEV_RATELIMIT_GEMINI_PER_MIN ?? '30',
now = Date.now,
timeoutMs = 15_000,
} = {}) {
let limiter;
return async (req, res) => {
if (req.aborted || res.destroyed || res.writableEnded) return;
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('X-Content-Type-Options', 'nosniff');
const reply = (status, errorOrPayload) => {
if (res.destroyed || res.writableEnded) return;
res.statusCode = status;
if (status >= 400) res.setHeader('Connection', 'close');
res.end(
JSON.stringify(
typeof errorOrPayload === 'string'
? { error: errorOrPayload }
: errorOrPayload,
),
);
};
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
return reply(405, 'Method not allowed');
}
let apiKey;
let model;
try {
if (
!isGeminiRequestOriginAllowed(req, resolveHost(), resolveAllowedHosts())
)
return reply(403, 'Gemini voice requires a same-origin app request');
apiKey = String(resolveApiKey() || '').trim();
if (!apiKey)
return reply(503, 'Add a Gemini API key in Provider Settings');
model = normalizeGeminiModel(resolveModel());
if (!model)
return reply(503, 'The Gemini Live model configuration is invalid');
if (limiter === undefined)
limiter = makeCostRateLimiter(resolveRateLimit(), 30);
if (limiter && !limiter(clientKey(req))) {
res.setHeader('Retry-After', '60');
return reply(
429,
'Gemini voice is starting too often. Try again shortly.',
);
}
} catch {
// Connect does not observe the handler's returned promise. A synchronous
// configuration resolver must fail with a bounded, fixed response.
return reply(503, MINT_FAILURE);
}
const lifetime = new AbortController();
let disconnected = false;
const disconnect = () => {
disconnected = true;
lifetime.abort(new DOMException('Request closed', 'AbortError'));
};
const responseClosed = () => {
if (!res.writableEnded) disconnect();
};
req.once('aborted', disconnect);
res.once('close', responseClosed);
const deadline = setTimeout(() => {
lifetime.abort(
new DOMException('Token request timed out', 'TimeoutError'),
);
}, timeoutMs);
deadline.unref?.();
let acquiredResponse;
try {
const inputMode = await readGeminiTokenRequest(req, lifetime.signal);
lifetime.signal.throwIfAborted();
const config = createGeminiLiveConfig(
annotationGuidance,
inputMode,
tools,
);
const issuedAt = now();
// REST uses bidiGenerateContentSetup. liveConnectConstraints is the SDK
// input shape, converted before transport. With no fieldMask the complete
// setup is locked to this server-owned configuration.
const request = {
uses: 1,
expireTime: new Date(issuedAt + 30 * 60_000).toISOString(),
newSessionExpireTime: new Date(issuedAt + 60_000).toISOString(),
bidiGenerateContentSetup: { model: `models/${model}`, ...config },
};
const acquisition = Promise.resolve(
fetchImpl(GEMINI_TOKEN_ENDPOINT, {
method: 'POST',
redirect: 'error',
signal: lifetime.signal,
headers: {
'x-goog-api-key': apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
}),
);
// A fetch implementation can ignore abort. Bound this caller's wait and
// discard a response that arrives after timeout/disconnection.
void acquisition.then(
(late) => {
acquiredResponse = late;
if (lifetime.signal.aborted) void late.body?.cancel().catch(() => {});
},
() => {},
);
const response = await waitForSignal(acquisition, lifetime.signal);
lifetime.signal.throwIfAborted();
if (
response.redirected ||
(response.url && response.url !== GEMINI_TOKEN_ENDPOINT)
) {
void response.body?.cancel().catch(() => {});
throw new Error('Unexpected token response destination');
}
if (!response.ok) {
// Never forward upstream bodies, headers or exception messages.
void response.body?.cancel().catch(() => {});
if (response.status === 429) {
res.setHeader('Retry-After', '60');
return reply(429, 'Gemini quota is unavailable. Try again later.');
}
if (response.status === 401 || response.status === 403)
return reply(
503,
'Gemini access was refused. Check the API key and model access.',
);
if (response.status === 400 || response.status === 404)
return reply(
502,
'Gemini Live is unavailable for the configured model.',
);
return reply(502, MINT_FAILURE);
}
const data = await readResponseJsonCapped(
response,
UPSTREAM_RESPONSE_BYTES,
lifetime.signal,
);
lifetime.signal.throwIfAborted();
if (
!data ||
Array.isArray(data) ||
typeof data !== 'object' ||
typeof data.name !== 'string' ||
data.name.length > 8192 ||
!/^auth_tokens\/[A-Za-z0-9._~+/=-]+$/.test(data.name) ||
data.name.includes(apiKey)
)
throw new Error('Invalid ephemeral token');
reply(200, {
token: data.name,
model,
config,
websocketUrl: GEMINI_LIVE_WEBSOCKET_URL,
});
} catch (error) {
if (disconnected || req.aborted) return;
if (error?.code === 'BODY_TOO_LARGE')
return reply(413, 'Token request is too large');
if (error?.code === 'BAD_CONTENT_TYPE')
return reply(415, 'Use an empty JSON token request');
if (error?.code === 'BAD_BODY')
return reply(400, 'Use an empty JSON token request');
reply(lifetime.signal.aborted ? 504 : 502, MINT_FAILURE);
} finally {
// Abort can happen after acquisition resolves but before this handler
// resumes and passes ownership to the body reader.
if (lifetime.signal.aborted)
void acquiredResponse?.body?.cancel().catch(() => {});
clearTimeout(deadline);
req.off('aborted', disconnect);
res.off('close', responseClosed);
}
};
}
-79
View File
@@ -1,79 +0,0 @@
import { readRequestBody } from '../common/request.js';
import { admitSameSiteRequest } from '../../../src/localRequestGate.mjs';
import {
isAllowedHost,
resolveAllowedHosts,
} from '../../../build/allowedHosts.js';
/** Use the app's Host and request policies, with a required browser Origin. */
export function isGeminiRequestOriginAllowed(
req,
configuredHost = '',
configuredAllowedHosts,
) {
const host = req.headers?.host;
const origin = req.headers?.origin;
if (
typeof host !== 'string' ||
typeof origin !== 'string' ||
!host ||
!origin ||
/[\s/?#@\\]/.test(host)
)
return false;
const protocol = req.socket?.encrypted ? 'https:' : 'http:';
if (
!admitSameSiteRequest({
hostHeader: host,
protocol,
origin,
secFetchSite: req.headers?.['sec-fetch-site'],
proxyHeaders: req.headers || {},
}).ok
)
return false;
// The shared gate compares a present Origin exactly with this authority;
// this route also requires the Origin and an allowed Host.
const boundHost = String(configuredHost || '')
.trim()
.toLowerCase();
return isAllowedHost(host, resolveAllowedHosts(configuredAllowedHosts), [
boundHost,
]);
}
/** Admit only the existing input gesture; callers cannot supply model/setup. */
export async function readGeminiTokenRequest(req, signal, maxBytes = 1024) {
const declared = Number(req.headers?.['content-length']);
const fail = (code) =>
Object.assign(new Error('Invalid token request'), { code });
const body = await readRequestBody(
req,
maxBytes,
Number.isFinite(declared) && declared > maxBytes
? AbortSignal.abort(fail('BODY_TOO_LARGE'))
: signal,
);
if (!body.trim()) return 'open-mic';
if (
!/^application\/json(?:\s*;|$)/i.test(req.headers?.['content-type'] || '')
)
throw fail('BAD_CONTENT_TYPE');
let parsed;
try {
parsed = JSON.parse(body);
} catch {
throw fail('BAD_BODY');
}
if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object')
throw fail('BAD_BODY');
const keys = Object.keys(parsed);
if (!keys.length) return 'open-mic';
if (
keys.length === 1 &&
keys[0] === 'inputMode' &&
parsed.inputMode === 'push-to-talk'
)
return 'push-to-talk';
throw fail('BAD_BODY');
}
+2 -4
View File
@@ -19,7 +19,6 @@ import { adsbLolProxy } from './aircraft/adsb-lol.js';
import { aisLiveProxy } from './vessels/ais-live.js'; import { aisLiveProxy } from './vessels/ais-live.js';
import { trackBackfillProxies } from './aircraft/tracks.js'; import { trackBackfillProxies } from './aircraft/tracks.js';
import { openAiRealtimeProxy } from './openai.js'; import { openAiRealtimeProxy } from './openai.js';
import { geminiLiveProxy } from './gemini.js';
import { googlePlacesContextProxy } from './places.js'; import { googlePlacesContextProxy } from './places.js';
import { mapillaryProxy } from './mapillary.js'; import { mapillaryProxy } from './mapillary.js';
import { keySetupEndpoint } from '../standalone/key-setup.js'; import { keySetupEndpoint } from '../standalone/key-setup.js';
@@ -31,9 +30,9 @@ import { windProxy } from './wind.js';
/** /**
* Construct the local provider plugins in their established order. * Construct the local provider plugins in their established order.
* `realtime` configures OpenAI; `gemini` explicitly opts into Gemini Live. * `realtime` configures the voice session token endpoint.
*/ */
function localProviderPlugins({ realtime, gemini } = {}) { function localProviderPlugins({ realtime } = {}) {
return [ return [
openSkyProxy(), openSkyProxy(),
celestrakProxy(), celestrakProxy(),
@@ -56,7 +55,6 @@ function localProviderPlugins({ realtime, gemini } = {}) {
aisLiveProxy(), aisLiveProxy(),
trackBackfillProxies(), trackBackfillProxies(),
openAiRealtimeProxy({ realtime }), openAiRealtimeProxy({ realtime }),
...(gemini ? [geminiLiveProxy({ realtime: gemini })] : []),
googlePlacesContextProxy(), googlePlacesContextProxy(),
windProxy(), windProxy(),
weatherProxy(), weatherProxy(),
+12 -99
View File
@@ -1,106 +1,19 @@
import { sameSiteGated } from './common/same-site.js'; import { installMapillaryRoutes } from './mapillary/routes.js';
import { makeRateLimiter, clientKey } from './common/rate-limit.js';
import {
fetchTile,
mapillaryToken,
parseTilePath,
retryAfterWait,
TileUpstreamError,
} from './mapillary/tiles.js';
/** /**
* Tile requests per client IP per minute, cache hits included: over 60 new * Vite plugin: cached Mapillary coverage tiles (token added server-side) and a
* 9-tile views a minute, more than a person flying the camera reaches. * status route that says whether a token is configured.
*/ */
export const TILE_ROUTE_MAX_PER_MIN = 600; function mapillaryProxy() {
function sendJson(res, status, payload) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(payload));
}
/** GET /api/mapillary/status — whether a token is configured, never its value. */
function handleStatus(req, res) {
if (req.method !== 'GET')
return sendJson(res, 405, { error: 'Method not allowed' });
sendJson(res, 200, { configured: Boolean(mapillaryToken()) });
}
/** GET /api/mapillary/tiles/coverage/{z}/{x}/{y} — trimmed protobuf tile. */
async function handleTile(req, res, allow) {
if (req.method !== 'GET')
return sendJson(res, 405, { error: 'Method not allowed' });
if (!allow(clientKey(req))) {
res.setHeader('Retry-After', '5');
return sendJson(res, 429, {
error: 'Too many tile requests',
retryAfter: 5,
});
}
const address = parseTilePath((req.url || '').split('?')[0]);
if (!address)
return sendJson(res, 400, {
error: 'Tile path must be /coverage/{z}/{x}/{y} with z 11–14',
});
if (!mapillaryToken())
return sendJson(res, 503, { error: 'no_key', keyRequired: true });
// A client that leaves (a tile the camera moved past) cancels its fetch.
const left = new AbortController();
res.on?.('close', () => {
if (!res.writableEnded) left.abort();
});
try {
const { bytes, source } = await fetchTile(address, { signal: left.signal });
res.statusCode = bytes.length ? 200 : 204;
res.setHeader('Content-Type', 'application/x-protobuf');
res.setHeader('Cache-Control', 'public, max-age=3600');
res.setHeader('X-Gev-Cache', source);
res.end(bytes.length ? bytes : undefined);
} catch (error) {
if (left.signal.aborted) return;
const status = error instanceof TileUpstreamError ? error.status : 0;
// A rejected token is a key problem the panel can name, not a fault.
if (status === 401 || status === 403)
return sendJson(res, 403, {
error: 'Mapillary rejected the access token',
keyRejected: true,
});
if (status === 429) {
const retryAfter = retryAfterWait(error.retryAfter);
res.setHeader('Retry-After', String(retryAfter));
return sendJson(res, 429, {
error: 'Mapillary is rate-limiting tile requests',
retryAfter,
});
}
// An upstream 400 must not read as a malformed request to this proxy.
sendJson(res, 502, { error: error?.message || 'Tile fetch failed' });
}
}
/**
* Vite plugin: Mapillary coverage tiles with the token added server-side, and
* a status route. Both refuse cross-site requests so another page cannot
* spend the token.
*/
export function mapillaryProxy() {
const install = (middlewares) => {
const allow = makeRateLimiter({
windowMs: 60_000,
max: TILE_ROUTE_MAX_PER_MIN,
globalMax: TILE_ROUTE_MAX_PER_MIN * 4,
});
middlewares.use('/api/mapillary/status', sameSiteGated(handleStatus));
middlewares.use(
'/api/mapillary/tiles',
sameSiteGated((req, res) => handleTile(req, res, allow)),
);
};
return { return {
name: 'mapillary-proxy', name: 'mapillary-proxy',
configureServer: (server) => install(server.middlewares), configureServer(server) {
configurePreviewServer: (server) => install(server.middlewares), installMapillaryRoutes(server.middlewares);
},
configurePreviewServer(server) {
installMapillaryRoutes(server.middlewares);
},
}; };
} }
export { mapillaryProxy };
+72
View File
@@ -0,0 +1,72 @@
import path from 'node:path';
/** Mapillary vector tile root; the path template is /{layer}/2/{z}/{x}/{y}. */
export const MAPILLARY_TILE_HOST = 'https://tiles.mapillary.com/maps/vtp';
/** Public tile layer names this proxy exposes, mapped to Mapillary's ids. */
export const TILE_LAYERS = Object.freeze({
// Region-sized z6–10 tiles are refused; the app never asks for them. The
// z14 `image` layer is ~98% of a tile and unused (positions come from the
// graph API), so it is dropped in transit.
coverage: Object.freeze({
upstream: 'mly1_public',
zoomRanges: Object.freeze([Object.freeze([0, 5]), Object.freeze([11, 14])]),
dropLayers: Object.freeze(['image']),
}),
});
/** Disk cache root, alongside the other providers' caches. */
export const MAPILLARY_CACHE_DIR = path.join(
process.cwd(),
'.gev-cache',
'mapillary',
);
export const TILE_DISK_DIR = path.join(MAPILLARY_CACHE_DIR, 'tiles');
/**
* Longer than the 15-minute upstream Cache-Control: tiles change only when new
* imagery is processed, and a day avoids re-downloading a city per camera move.
*/
export const TILE_DISK_TTL_MS = 24 * 60 * 60 * 1000;
/**
* A tile write starts a background sweep at most this often: expired files go
* first, then the oldest until the cache fits in TILE_DISK_MAX_BYTES.
*/
export const TILE_DISK_SWEEP_INTERVAL_MS = 15 * 60 * 1000;
export const TILE_DISK_MAX_BYTES = 1024 * 1024 * 1024;
/** Per-file cost on top of its size, so empty tiles still count. */
export const TILE_DISK_FILE_OVERHEAD_BYTES = 4096;
/** A z14 image tile over a dense city is ~11 MB; anything past this is wrong. */
export const TILE_MAX_BYTES = 48 * 1024 * 1024;
export const TILE_MEMORY_BUDGET_BYTES = 96 * 1024 * 1024;
/** Per-entry cost on top of its bytes, so empty tiles still count. */
export const TILE_MEMORY_ENTRY_OVERHEAD_BYTES = 1024;
export const TILE_FETCH_TIMEOUT_MS = 60_000;
/**
* Upstream fetches at once; further misses queue. A view needs at most 25
* tiles, and the cap stops a burst of misses opening thousands of requests.
*/
export const TILE_UPSTREAM_CONCURRENCY = 6;
/**
* Tile requests per client IP per minute, cache hits included. 600 is 24 new
* 25-tile views a minute, more than a person flying the camera reaches, but it
* stops one page draining the shared token into a Mapillary rate limit.
*/
export const TILE_ROUTE_MAX_PER_MIN = 600;
/**
* How long a 401/403 answers tile misses before asking Mapillary again. A
* changed token is tried at once.
*/
export const TILE_KEY_REJECTED_HOLD_MS = 5 * 60 * 1000;
/** After a 429 without a usable Retry-After, hold tile misses this long. */
export const TILE_RATE_LIMIT_HOLD_MS = 60_000;
/** The longest Retry-After honoured, so a bad header cannot stall coverage. */
export const TILE_RATE_LIMIT_MAX_HOLD_MS = 10 * 60 * 1000;
/** The client token lives in the browser by design; the server adds it to tile URLs too. */
export function mapillaryToken() {
return String(process.env.MAPILLARY_CLIENT_TOKEN || '').trim();
}
+95
View File
@@ -0,0 +1,95 @@
import { sameSiteGated } from '../common/same-site.js';
import { makeRateLimiter, clientKey } from '../common/rate-limit.js';
import { fetchTile, TileRequestError, TileUpstreamError } from './tiles.js';
import { mapillaryToken, TILE_ROUTE_MAX_PER_MIN } from './constants.js';
function sendJson(res, status, payload) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(payload));
}
/** GET /api/mapillary/status — whether a token is configured, never its value. */
function handleStatus(req, res) {
if (req.method !== 'GET')
return sendJson(res, 405, { error: 'Method not allowed' });
sendJson(res, 200, { configured: Boolean(mapillaryToken()) });
}
/** GET /api/mapillary/tiles/coverage/{z}/{x}/{y} — cached protobuf tile. */
async function handleTile(req, res, allow) {
if (req.method !== 'GET')
return sendJson(res, 405, { error: 'Method not allowed' });
if (!allow(clientKey(req))) {
res.setHeader('Retry-After', '5');
return sendJson(res, 429, {
error: 'Too many tile requests',
retryAfter: 5,
});
}
const match = /^\/(coverage)\/(\d{1,2})\/(\d{1,6})\/(\d{1,6})$/.exec(
(req.url || '').split('?')[0],
);
if (!match)
return sendJson(res, 400, {
error: 'Tile path must be /coverage/{z}/{x}/{y}',
});
if (!mapillaryToken())
return sendJson(res, 503, { error: 'no_key', keyRequired: true });
const abandoned = new AbortController();
req.on?.('aborted', () => abandoned.abort());
res.on?.('close', () => abandoned.abort());
try {
const { bytes, source } = await fetchTile(
{ layer: match[1], z: match[2], x: match[3], y: match[4] },
{ signal: abandoned.signal },
);
if (res.writableEnded) return;
res.statusCode = bytes.length ? 200 : 204;
res.setHeader('Content-Type', 'application/x-protobuf');
res.setHeader('Cache-Control', 'public, max-age=3600');
res.setHeader('X-Gev-Cache', source);
res.end(bytes.length ? bytes : undefined);
} catch (error) {
if (res.writableEnded || abandoned.signal.aborted) return;
if (error instanceof TileRequestError)
return sendJson(res, error.status, { error: error.message });
if (error instanceof TileUpstreamError) {
// A rejected token is a key problem the panel can name, not a fault.
if (error.keyRejected)
return sendJson(res, 403, {
error: 'Mapillary rejected the access token',
keyRejected: true,
});
if (error.status === 429) {
const retryAfter = error.retryAfterSec || 60;
res.setHeader('Retry-After', String(retryAfter));
return sendJson(res, 429, {
error: 'Mapillary is rate-limiting tile requests',
retryAfter,
});
}
// An upstream 400 must not read as a malformed request to this proxy.
return sendJson(res, 502, { error: error.message });
}
sendJson(res, 502, { error: error?.message || 'Tile fetch failed' });
}
}
/**
* Attach the Mapillary routes. Both refuse cross-site requests so another page
* cannot spend the token or provoke a 429 that holds every tile miss.
*/
export function installMapillaryRoutes(middlewares) {
const allow = makeRateLimiter({
windowMs: 60_000,
max: TILE_ROUTE_MAX_PER_MIN,
globalMax: TILE_ROUTE_MAX_PER_MIN * 4,
});
middlewares.use('/api/mapillary/status', sameSiteGated(handleStatus));
middlewares.use(
'/api/mapillary/tiles',
sameSiteGated((req, res) => handleTile(req, res, allow)),
);
}
+455 -202
View File
@@ -1,265 +1,518 @@
import path from 'node:path';
import { promises as fsp } from 'node:fs';
import { readResponseBytesCapped } from '../common/http.js'; import { readResponseBytesCapped } from '../common/http.js';
import { stripTileLayers } from './trim.js'; import { stripTileLayers } from './trim.js';
import {
MAPILLARY_TILE_HOST,
TILE_LAYERS,
TILE_DISK_DIR,
TILE_DISK_TTL_MS,
TILE_DISK_SWEEP_INTERVAL_MS,
TILE_DISK_MAX_BYTES,
TILE_DISK_FILE_OVERHEAD_BYTES,
TILE_MAX_BYTES,
TILE_MEMORY_BUDGET_BYTES,
TILE_MEMORY_ENTRY_OVERHEAD_BYTES,
TILE_FETCH_TIMEOUT_MS,
TILE_UPSTREAM_CONCURRENCY,
TILE_KEY_REJECTED_HOLD_MS,
TILE_RATE_LIMIT_HOLD_MS,
TILE_RATE_LIMIT_MAX_HOLD_MS,
mapillaryToken,
} from './constants.js';
/** Mapillary vector tiles, /{layer}/2/{z}/{x}/{y}: the only host the token goes to. */ /** Log without the stack; the token is never in scope here. */
const TILE_HOST = 'https://tiles.mapillary.com/maps/vtp'; function warn(what, error) {
/** Only the street zooms the app draws are proxied. */ console.warn(`[Mapillary Proxy] ${what}:`, error?.message || error);
const MIN_ZOOM = 11;
const MAX_ZOOM = 14;
/**
* The z14 `image` layer is ~98% of a tile (12 MB over a dense city) and unused
* (positions come from the Graph API), so it is dropped in transit.
*/
const DROP_LAYERS = ['image'];
/** A z14 tile with its image layer is ~12 MB; anything past this is wrong. */
export const TILE_MAX_BYTES = 48 * 1024 * 1024;
const FETCH_TIMEOUT_MS = 60_000;
/** Upstream fetches at once; more wait their turn. */
export const TILE_UPSTREAM_CONCURRENCY = 6;
/** Tiles change only when new imagery is processed. */
export const TILE_TTL_MS = 24 * 60 * 60 * 1000;
/** Trimmed tiles are ~80 KB: a dozen 9-tile views, well under 100 MB. */
export const TILE_MEMORY_MAX_TILES = 120;
/** A trimmed tile is ~80 KB; a body this big failed to trim and is not kept. */
export const TILE_MEMORY_MAX_TILE_BYTES = 4 * 1024 * 1024;
/** The longest upstream Retry-After honoured, in seconds. */
export const MAX_RETRY_AFTER_SEC = 600;
/** The client token lives in the browser by design; the server adds it to tile URLs too. */
export function mapillaryToken() {
return String(process.env.MAPILLARY_CLIENT_TOKEN || '').trim();
} }
/** Mapillary answered with an error status (or a size this proxy refuses). */ /** Thrown for a request this proxy refuses before contacting Mapillary. */
export class TileRequestError extends Error {
constructor(message, status = 400) {
super(message);
this.name = 'TileRequestError';
this.status = status;
}
}
/** Mapillary answered with an error status; 401/403 set `keyRejected`. */
export class TileUpstreamError extends Error { export class TileUpstreamError extends Error {
constructor(status, message, retryAfter = null) { constructor(status, message, { retryAfterSec = null } = {}) {
super(message || `Mapillary tiles HTTP ${status}`); super(message || `Mapillary tiles HTTP ${status}`);
this.name = 'TileUpstreamError'; this.name = 'TileUpstreamError';
this.status = status; this.status = status;
/** The upstream Retry-After header, as sent. */ this.keyRejected = status === 401 || status === 403;
this.retryAfter = retryAfter; this.retryAfterSec = retryAfterSec;
} }
} }
/** Seconds a Retry-After header asks for (an integer or an HTTP date), else null. */
export function retryAfterSeconds(header, now = Date.now()) {
const text = String(header ?? '').trim();
if (!text) return null;
const seconds = /^\d+$/.test(text)
? Number(text)
: (Date.parse(text) - now) / 1000;
return Number.isFinite(seconds) && seconds > 0 ? Math.ceil(seconds) : null;
}
/** The wait a 429 asks for, bounded; a missing or malformed header means a minute. */
export function retryAfterWait(header, now = Date.now()) {
return Math.min(retryAfterSeconds(header, now) ?? 60, MAX_RETRY_AFTER_SEC);
}
/** /**
* While Mapillary rate-limits, tile misses are refused here until the wait is * A rejected token or rate limit that answers every tile miss until it expires
* over, so the rest of a view (and the fetches queued behind the first 429) * (or the token changes). Cached tiles are still served meanwhile.
* do not go on asking. Scoped to the token that was refused. * @type {{status: number, until: number, token: string}|null}
* @type {{until: number, token: string}|null}
*/ */
let refusal = null; let _upstreamHold = null;
/** The refusal still in force for `token`, as the error to answer with. */ /** Milliseconds to wait from a Retry-After header (seconds or an HTTP date). */
function refusedNow(token) { function retryAfterMs(header, now = Date.now()) {
if (!refusal) return null; const text = String(header ?? '').trim();
const left = refusal.until - Date.now(); let ms = NaN;
if (left <= 0 || refusal.token !== token) { if (/^\d+$/.test(text)) ms = Number(text) * 1000;
refusal = null; else if (text) ms = Date.parse(text) - now;
if (!Number.isFinite(ms) || ms <= 0) return TILE_RATE_LIMIT_HOLD_MS;
return Math.min(ms, TILE_RATE_LIMIT_MAX_HOLD_MS);
}
function heldRefusal(token) {
const hold = _upstreamHold;
if (!hold) return null;
const left = hold.until - Date.now();
if (left <= 0 || hold.token !== token) {
_upstreamHold = null;
return null; return null;
} }
return new TileUpstreamError(429, undefined, String(Math.ceil(left / 1000))); return new TileUpstreamError(hold.status, undefined, {
retryAfterSec: Math.ceil(left / 1000),
});
} }
/** /**
* Parse `/coverage/{z}/{x}/{y}`; null unless z is 11–14 and x/y are on the grid. * Validate a tile address against the layer's zoom ranges.
* @returns {{z: number, x: number, y: number, key: string}|null} * @returns {{layer:string, upstream:string, z:number, x:number, y:number, key:string}}
*/ */
export function parseTilePath(pathname) { export function normalizeTileAddress({ layer, z, x, y }) {
const match = /^\/coverage\/(\d{1,2})\/(\d{1,6})\/(\d{1,6})$/.exec(pathname); const spec = Object.hasOwn(TILE_LAYERS, layer) ? TILE_LAYERS[layer] : null;
if (!match) return null; if (!spec) throw new TileRequestError(`Unknown tile layer: ${layer}`);
const [z, x, y] = match.slice(1).map(Number); const zi = Number(z);
if (z < MIN_ZOOM || z > MAX_ZOOM || x >= 2 ** z || y >= 2 ** z) return null; const xi = Number(x);
return { z, x, y, key: `${z}/${x}/${y}` }; const yi = Number(y);
if (
![zi, xi, yi].every((v) => Number.isInteger(v) && v >= 0) ||
!spec.zoomRanges.some(([min, max]) => zi >= min && zi <= max)
)
throw new TileRequestError(
`Tile zoom for ${layer} must be ${spec.zoomRanges
.map(([min, max]) => `${min}–${max}`)
.join(' or ')}`,
);
const n = 2 ** zi;
if (xi >= n || yi >= n)
throw new TileRequestError('Tile address out of range');
return {
layer,
upstream: spec.upstream,
dropLayers: spec.dropLayers || [],
z: zi,
x: xi,
y: yi,
key: `${layer}/${zi}/${xi}/${yi}`,
};
} }
function trim(bytes) { /** @type {Map<string, {bytes: Buffer, at: number}>} insertion-ordered LRU */
try { const _memory = new Map();
return stripTileLayers(bytes, DROP_LAYERS); let _memoryBytes = 0;
} catch (error) { const memoryCost = (bytes) => bytes.length + TILE_MEMORY_ENTRY_OVERHEAD_BYTES;
console.warn('[Mapillary Proxy] tile trim failed:', error?.message); /**
return bytes; * Upstream fetches shared by every request for the same tile; the last waiter
* to leave cancels it (see `joinFlight`).
* @type {Map<string, {controller: AbortController, promise: Promise<Buffer>, waiters: number}>}
*/
const _inFlight = new Map();
function memoryGet(key) {
const hit = _memory.get(key);
if (!hit) return null;
// Same life as the disk copy, so a long-running server never serves stale
// coverage.
if (Date.now() - hit.at > TILE_DISK_TTL_MS) {
_memory.delete(key);
_memoryBytes -= memoryCost(hit.bytes);
return null;
}
_memory.delete(key);
_memory.set(key, hit);
return hit.bytes;
}
/** `at` is when Mapillary served the bytes (a disk tile's mtime). */
function memoryPut(key, bytes, at = Date.now()) {
if (memoryCost(bytes) > TILE_MEMORY_BUDGET_BYTES / 2) return;
const existing = _memory.get(key);
if (existing) _memoryBytes -= memoryCost(existing.bytes);
_memory.set(key, { bytes, at });
_memoryBytes += memoryCost(bytes);
while (_memoryBytes > TILE_MEMORY_BUDGET_BYTES && _memory.size) {
const [oldest, entry] = _memory.entries().next().value;
_memory.delete(oldest);
_memoryBytes -= memoryCost(entry.bytes);
} }
} }
/** One tile from Mapillary, trimmed; empty bytes mean no coverage. */ /** Disk cache root; tests point it at a temporary directory. */
async function fetchUpstream({ z, x, y }, signal) { let _diskDir = TILE_DISK_DIR;
const token = mapillaryToken();
const refused = refusedNow(token); function diskPath({ layer, z, x, y }, root = _diskDir) {
if (refused) throw refused; return path.join(root, layer, String(z), `${x}-${y}.pbf`);
const response = await fetch( }
`${TILE_HOST}/mly1_public/2/${z}/${x}/${y}?access_token=${encodeURIComponent(token)}`,
{ async function readDisk(address) {
signal: AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]), const file = diskPath(address);
// The token is in the query: a redirect is never followed (a 3xx is a 502). try {
redirect: 'manual', const stat = await fsp.stat(file);
headers: { Accept: 'application/x-protobuf' }, if (Date.now() - stat.mtimeMs > TILE_DISK_TTL_MS) return null;
}, return { bytes: await fsp.readFile(file), at: stat.mtimeMs };
} catch {
return null;
}
}
/** Unsettled background writes and sweeps; requests never wait on them. */
const _background = new Set();
function track(task) {
const settled = task
.catch(() => {})
.finally(() => _background.delete(settled));
_background.add(settled);
return settled;
}
/** @type {Map<string, number>} cache file to its newest write's sequence */
const _diskWrites = new Map();
let _diskWriteSeq = 0;
function diskWritePending(address) {
return _diskWrites.has(diskPath(address));
}
/**
* Write a tile in the background. `at` keeps a rewrite's original fetch time
* so it does not extend the tile's life. An overtaken write steps aside.
*/
function writeDisk(address, bytes, at = null) {
// Sweep this write's root even if the cache dir has moved since.
const root = _diskDir;
const file = diskPath(address, root);
const seq = ++_diskWriteSeq;
const tmp = `${file}.${process.pid}-${seq}.tmp`;
const newest = () => _diskWrites.get(file) === seq;
_diskWrites.set(file, seq);
return track(
fsp
.mkdir(path.dirname(file), { recursive: true })
.then(() => fsp.writeFile(tmp, bytes))
.then(() => at != null && fsp.utimes(tmp, new Date(), new Date(at)))
.then(() => {
if (!newest()) return fsp.rm(tmp, { force: true });
return fsp.rename(tmp, file).then(() => scheduleSweep(root));
})
.catch(async (error) => {
await fsp.rm(tmp, { force: true }).catch(() => {});
warn('tile cache write failed', error);
})
.finally(() => {
if (newest()) _diskWrites.delete(file);
}),
); );
if (!response.ok || response.status === 204) { }
await response.body?.cancel().catch(() => {});
if (response.status === 204 || response.status === 404) let _lastSweepAt = 0;
return Buffer.alloc(0); let _sweeping = null;
const retryAfter = response.headers.get('retry-after'); let _sweepWarned = false;
if (response.status === 429)
refusal = { function scheduleSweep(root) {
token, if (_sweeping || Date.now() - _lastSweepAt < TILE_DISK_SWEEP_INTERVAL_MS)
until: Date.now() + retryAfterWait(retryAfter) * 1000, return;
}; _lastSweepAt = Date.now();
throw new TileUpstreamError(response.status, undefined, retryAfter); const sweep = sweepTileDisk({ root })
} .catch((error) => {
if (_sweepWarned) return;
_sweepWarned = true;
warn('tile cache sweep failed', error);
})
.finally(() => {
if (_sweeping === tracked) _sweeping = null;
});
const tracked = track(sweep);
_sweeping = tracked;
}
/** Every file under `dir` with size and mtime; a missing dir is empty. */
async function listCacheFiles(dir) {
let entries;
try { try {
const bytes = await readResponseBytesCapped(response, TILE_MAX_BYTES); entries = await fsp.readdir(dir, { withFileTypes: true });
return trim(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length)); } catch (error) {
if (error?.code === 'ENOENT') return [];
throw error;
}
const files = [];
for (const entry of entries) {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) files.push(...(await listCacheFiles(file)));
else if (entry.isFile()) {
const stat = await fsp.stat(file).catch(() => null);
if (stat) files.push({ file, size: stat.size, at: stat.mtimeMs });
}
}
return files;
}
/**
* Delete expired tiles, then the oldest until the rest fit in `maxBytes`.
* @returns {Promise<{removed: number, bytes: number}>} files deleted, charged bytes kept
*/
export async function sweepTileDisk({
root = _diskDir,
maxBytes = TILE_DISK_MAX_BYTES,
} = {}) {
const now = Date.now();
const files = (await listCacheFiles(root)).sort((a, b) => a.at - b.at);
const cost = (size) => size + TILE_DISK_FILE_OVERHEAD_BYTES;
let bytes = files.reduce((sum, { size }) => sum + cost(size), 0);
let removed = 0;
for (const { file, size, at } of files) {
if (now - at <= TILE_DISK_TTL_MS && bytes <= maxBytes) break;
await fsp.rm(file, { force: true });
bytes -= cost(size);
removed++;
}
return { removed, bytes };
}
/** The one origin the tile token may be sent to, at every redirect hop. */
const TILE_ORIGIN = new URL(MAPILLARY_TILE_HOST).origin;
export const TILE_MAX_REDIRECTS = 3;
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
/**
* Follow redirects by hand so every hop stays HTTPS on the tile origin and the
* token in the query never reaches another host. A bad redirect is a 502.
*/
async function fetchPinned(url, init) {
let next = url;
for (let hop = 0; ; hop++) {
const response = await fetch(next, { ...init, redirect: 'manual' });
if (!REDIRECT_STATUSES.has(response.status)) return response;
await response.body?.cancel().catch(() => {});
if (hop >= TILE_MAX_REDIRECTS)
throw new TileUpstreamError(502, 'Mapillary tile redirected too often');
let target = null;
try {
target = new URL(response.headers.get('location') ?? '', next);
} catch {
/* unparseable Location */
}
if (
!response.headers.get('location') ||
target?.protocol !== 'https:' ||
target.origin !== TILE_ORIGIN ||
target.username ||
target.password
)
throw new TileUpstreamError(
502,
'Mapillary tile redirect left the tile origin',
);
next = target.href;
}
}
async function fetchUpstream(address, signal) {
const token = mapillaryToken();
if (!token) throw new TileRequestError('Mapillary token not configured', 503);
const held = heldRefusal(token);
if (held) throw held;
const url = `${MAPILLARY_TILE_HOST}/${address.upstream}/2/${address.z}/${address.x}/${address.y}?access_token=${encodeURIComponent(token)}`;
const timeout = AbortSignal.timeout(TILE_FETCH_TIMEOUT_MS);
const oversize = new AbortController();
const response = await fetchPinned(url, {
signal: AbortSignal.any([signal, timeout, oversize.signal].filter(Boolean)),
headers: { Accept: 'application/x-protobuf' },
});
if (response.status === 404 || response.status === 204) {
await response.body?.cancel().catch(() => {});
return Buffer.alloc(0);
}
if (!response.ok) {
await response.body?.cancel().catch(() => {});
const error = new TileUpstreamError(response.status);
if (error.keyRejected)
_upstreamHold = {
status: response.status,
until: Date.now() + TILE_KEY_REJECTED_HOLD_MS,
token,
};
else if (response.status === 429) {
const wait = retryAfterMs(response.headers.get('retry-after'));
_upstreamHold = { status: 429, until: Date.now() + wait, token };
error.retryAfterSec = Math.ceil(wait / 1000);
}
throw error;
}
// Chunked or compressed bodies have no Content-Length: the cap applies as
// the body streams, and an oversized one also aborts the request.
try {
const bytes = await readResponseBytesCapped(
response,
TILE_MAX_BYTES,
signal,
);
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
} catch (error) { } catch (error) {
if (error?.code !== 'RESPONSE_TOO_LARGE') throw error; if (error?.code !== 'RESPONSE_TOO_LARGE') throw error;
oversize.abort();
throw new TileUpstreamError(502, 'Mapillary tile exceeds size cap'); throw new TileUpstreamError(502, 'Mapillary tile exceeds size cap');
} }
} }
let upstreamActive = 0; /** @type {{active: number, queue: Array<() => void>}} upstream slots */
/** @type {Array<() => void>} fetches waiting for a slot, oldest first */ let _slots = { active: 0, queue: [] };
const upstreamWaiting = [];
/** /**
* Run `task` in an upstream slot, waiting for one unless `signal` aborts * Resolve with a release function once a slot is free. An abort while
* first. A freed slot passes straight to the oldest waiter, still counted, so * queued leaves the queue.
* a request arriving meanwhile cannot take it first. * @returns {Promise<() => void>}
*/ */
async function withUpstreamSlot(signal, task) { function acquireUpstreamSlot(signal) {
if (upstreamActive < TILE_UPSTREAM_CONCURRENCY) upstreamActive++; const slots = _slots;
else
await new Promise((resolve, reject) => {
const wake = () => {
signal.removeEventListener('abort', leave);
resolve();
};
const leave = () => {
const at = upstreamWaiting.indexOf(wake);
if (at !== -1) upstreamWaiting.splice(at, 1);
reject(signal.reason);
};
upstreamWaiting.push(wake);
signal.addEventListener('abort', leave, { once: true });
});
try {
// Handed a slot after leaving: it goes on to the next waiter.
signal.throwIfAborted();
return await task();
} finally {
const next = upstreamWaiting.shift();
if (next) next();
else upstreamActive--;
}
}
/** `promise`, or a rejection as soon as `signal` aborts. */
function unlessAborted(promise, signal) {
if (!signal) return promise;
signal.throwIfAborted();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const leave = () => reject(signal.reason); if (signal.aborted) return reject(signal.reason);
signal.addEventListener('abort', leave, { once: true }); const onAbort = () => {
promise const index = slots.queue.indexOf(grant);
.then(resolve, reject) if (index !== -1) slots.queue.splice(index, 1);
.finally(() => signal.removeEventListener('abort', leave)); reject(signal.reason);
};
function grant() {
signal.removeEventListener('abort', onAbort);
slots.active++;
let released = false;
resolve(() => {
if (released) return;
released = true;
slots.active--;
slots.queue.shift()?.();
});
}
if (slots.active < TILE_UPSTREAM_CONCURRENCY) return grant();
signal.addEventListener('abort', onAbort, { once: true });
slots.queue.push(grant);
}); });
} }
/** @type {Map<string, {bytes: Buffer, at: number}>} least recently used first */ function trim(address, bytes) {
const memory = new Map(); if (!address.dropLayers.length || !bytes.length) return bytes;
try {
return stripTileLayers(bytes, address.dropLayers);
} catch (error) {
warn('tile trim failed, serving raw', error);
return bytes;
}
}
/** /**
* Upstream fetches shared per tile, with the requests still waiting on each. * Fetch one tile from memory, disk, a shared flight, then Mapillary. Empty
* @type {Map<string, {promise: Promise<Buffer>, controller: AbortController, waiters: number}>} * bytes mean no coverage.
* @param {{layer:string,z:number|string,x:number|string,y:number|string}} request
* @param {{signal?: AbortSignal}} [options]
* @returns {Promise<{bytes: Buffer, source: 'memory'|'disk'|'inflight'|'upstream', address: object}>}
*/ */
const inFlight = new Map(); export async function fetchTile(request, { signal } = {}) {
const address = normalizeTileAddress(request);
function remember(key, bytes, at = Date.now()) { const memory = memoryGet(address.key);
if (bytes.length > TILE_MEMORY_MAX_TILE_BYTES) return; if (memory) return { bytes: memory, source: 'memory', address };
memory.delete(key); const disk = await readDisk(address);
memory.set(key, { bytes, at }); if (disk) {
for (const oldest of memory.keys()) { // Older cache files may be untrimmed: rewrite once, keeping the fetch time.
if (memory.size <= TILE_MEMORY_MAX_TILES) break; const bytes = trim(address, disk.bytes);
memory.delete(oldest); if (bytes !== disk.bytes && !diskWritePending(address))
writeDisk(address, bytes, disk.at);
memoryPut(address.key, bytes, disk.at);
return { bytes, source: 'disk', address };
} }
// A caller gone while the disk was read must not start a fetch nobody joins.
signal?.throwIfAborted();
let flight = _inFlight.get(address.key);
const joined = Boolean(flight) && !flight.controller.signal.aborted;
if (!joined) flight = startFlight(address);
const bytes = await joinFlight(flight, signal);
return { bytes, source: joined ? 'inflight' : 'upstream', address };
} }
function recall(key) { /** Start the shared upstream fetch; it holds a slot until the body is read. */
const hit = memory.get(key);
if (!hit) return null;
if (Date.now() - hit.at > TILE_TTL_MS) {
memory.delete(key);
return null;
}
remember(key, hit.bytes, hit.at); // most recently used again
return hit.bytes;
}
/** Start the upstream fetch for a tile, shared until its last request leaves. */
function startFlight(address) { function startFlight(address) {
const controller = new AbortController(); const controller = new AbortController();
const flight = { controller, waiters: 0 }; const flight = { controller, waiters: 0, promise: null };
flight.promise = withUpstreamSlot(controller.signal, () => flight.promise = acquireUpstreamSlot(controller.signal)
fetchUpstream(address, controller.signal), .then((release) =>
) fetchUpstream(address, controller.signal).finally(release),
)
.then((raw) => trim(address, raw))
.then((bytes) => { .then((bytes) => {
remember(address.key, bytes); memoryPut(address.key, bytes);
writeDisk(address, bytes);
return bytes; return bytes;
}) })
.finally(() => { .finally(() => {
if (inFlight.get(address.key) === flight) inFlight.delete(address.key); if (_inFlight.get(address.key) === flight) _inFlight.delete(address.key);
}); });
// Every request may have left; the rejection is then nobody's. // Every waiter may have left before it settles; nobody awaits it then.
flight.promise.catch(() => {}); flight.promise.catch(() => {});
inFlight.set(address.key, flight); _inFlight.set(address.key, flight);
return flight; return flight;
} }
/** /**
* One tile from memory, a shared in-flight fetch, or Mapillary. `signal` * Wait on a shared flight. A caller's abort rejects only that caller; the
* aborts when the request's client leaves; the fetch stops once all have. * fetch is cancelled when the last waiter leaves.
* @param {{z: number, x: number, y: number, key: string}} address from parseTilePath
* @param {{signal?: AbortSignal}} [options]
* @returns {Promise<{bytes: Buffer, source: 'memory'|'inflight'|'upstream'}>}
*/ */
export async function fetchTile(address, { signal } = {}) { function joinFlight(flight, signal) {
const cached = recall(address.key); signal?.throwIfAborted();
if (cached) return { bytes: cached, source: 'memory' };
let flight = inFlight.get(address.key);
const shared = Boolean(flight);
flight ||= startFlight(address);
flight.waiters++; flight.waiters++;
try { return new Promise((resolve, reject) => {
const bytes = await unlessAborted(flight.promise, signal); let done = false;
return { bytes, source: shared ? 'inflight' : 'upstream' }; const leave = () => {
} finally { if (done) return false;
if (--flight.waiters === 0) { done = true;
// A later request for the tile must not join a cancelled fetch. signal?.removeEventListener('abort', onAbort);
if (inFlight.get(address.key) === flight) inFlight.delete(address.key); flight.waiters--;
flight.controller.abort(); return true;
} };
} const onAbort = () => {
if (!leave()) return;
if (flight.waiters === 0) flight.controller.abort();
reject(signal.reason);
};
signal?.addEventListener('abort', onAbort, { once: true });
flight.promise.then(
(bytes) => leave() && resolve(bytes),
(error) => leave() && reject(error),
);
});
} }
/** Test seam: forget every cached and in-flight tile. */ /** Test seam: forget every cached tile held in memory. */
export function _resetTileCacheForTest() { export function _resetTileMemoryForTest() {
memory.clear(); _memory.clear();
inFlight.clear(); _memoryBytes = 0;
refusal = null; _inFlight.clear();
upstreamActive = 0; _upstreamHold = null;
upstreamWaiting.length = 0; _slots = { active: 0, queue: [] };
}
/** Test seam: how many tiles memory holds and the bytes charged for them. */
export function _tileMemoryForTest() {
return { entries: _memory.size, bytes: _memoryBytes };
}
/** Test seam: wait for every background write and the sweeps they start. */
export async function _settleTileWritesForTest() {
while (_background.size) await Promise.allSettled([..._background]);
}
/** Test seam: keep the disk cache in `dir` (null restores the default). */
export function _setTileCacheDirForTest(dir) {
_diskDir = dir || TILE_DISK_DIR;
_lastSweepAt = 0;
} }
+13
View File
@@ -41,3 +41,16 @@ export function stripTileLayers(bytes, dropNames) {
}, null); }, null);
return dropped ? Buffer.from(writer.finish()) : bytes; return dropped ? Buffer.from(writer.finish()) : bytes;
} }
/** Names of the layers inside a vector tile, in order. */
export function listTileLayers(bytes) {
const names = [];
if (!bytes?.length) return names;
new PbfReader(bytes).readFields((tag, _result, pbf) => {
if (tag !== TILE_LAYER_FIELD) return;
const end = pbf.readVarint() + pbf.pos;
names.push(layerName(bytes.subarray(pbf.pos, end)));
pbf.pos = end;
}, null);
return names;
}
-2
View File
@@ -13,8 +13,6 @@ export function launchLibraryRequestHeaders(token = process.env.LL2_API_TOKEN) {
const normalized = String(token || '').trim(); const normalized = String(token || '').trim();
return { return {
Accept: 'application/json', Accept: 'application/json',
'User-Agent':
'gods-eye-view-launch-library-proxy/1.0 (+https://github.com/bilawalsidhu/gods-eye-view)',
...(normalized ? { Authorization: `Token ${normalized}` } : {}), ...(normalized ? { Authorization: `Token ${normalized}` } : {}),
}; };
} }
+4 -99
View File
@@ -8,8 +8,6 @@ import {
terrainPointKey, terrainPointKey,
validTerrainResult, validTerrainResult,
} from '../../src/data/terrainHeightsProxy.js'; } from '../../src/data/terrainHeightsProxy.js';
import { makeRateLimiter, clientKey } from './common/rate-limit.js';
import { admitSameSiteKeyless } from './common/same-site.js';
/** /**
* Re:Earth terrain point-height proxy: batched lon/lat → ellipsoidal height * Re:Earth terrain point-height proxy: batched lon/lat → ellipsoidal height
@@ -22,31 +20,11 @@ import { admitSameSiteKeyless } from './common/same-site.js';
* Only missing/stale points go upstream; the response is rebuilt in exact * Only missing/stale points go upstream; the response is rebuilt in exact
* request order. Larger requests are chunked sequentially, and one failing * request order. Larger requests are chunked sequentially, and one failing
* chunk does not discard the chunks that resolved. * chunk does not discard the chunks that resolved.
*
* Bounds, because every distinct 5dp point is its own key: coordinates must be
* in WGS-84 range (rejected at parse), the point cache has an entry ceiling
* with oldest-first eviction, an over-large cache file is not read back, and
* the route carries an always-on per-client limiter. The route also refuses
* cross-site browser requests, so another web page cannot use the visitor's
* browser to fill the cache or spend the visitor's own rate-limit quota.
* Reverse-proxied same-origin requests are admitted: terrain is keyless and
* needed for rendering, and a 403 would send every chunk to the geoid fallback.
*/ */
export function terrainHeightsProxy(options = {}) { export function terrainHeightsProxy() {
// Destructured in the body, not the signature: `proxyErrorResponses.test.mjs`
// extracts these proxies by slicing to the first closing brace in column
// zero, so a multi-line parameter list would cut the function in half.
// Overridable so the ceilings can be exercised as behaviour rather than
// asserted as constants; production constructs this with no arguments.
const {
cacheMaxEntries = 50_000,
cacheMaxDiskBytes = 24 * 1024 * 1024,
cachePath,
} = options;
const TTL_MS = 30 * 24 * 3600_000; const TTL_MS = 30 * 24 * 3600_000;
const CACHE_PATH = const CACHE_DIR = path.join(process.cwd(), '.gev-cache');
cachePath || path.join(process.cwd(), '.gev-cache', 'terrain-heights.json'); const CACHE_PATH = path.join(CACHE_DIR, 'terrain-heights.json');
const CACHE_DIR = path.dirname(CACHE_PATH);
// Sized against measured upstream latency, not the documented page cap. // Sized against measured upstream latency, not the documented page cap.
// Re:Earth serves 87-186 ms/point depending on load (observed 2026-09-12, // Re:Earth serves 87-186 ms/point depending on load (observed 2026-09-12,
// a 2x swing within one hour). 256 points therefore costs 22-48 s and blows // a 2x swing within one hour). 256 points therefore costs 22-48 s and blows
@@ -56,50 +34,9 @@ export function terrainHeightsProxy(options = {}) {
// that range. // that range.
const UPSTREAM_CHUNK = 64; const UPSTREAM_CHUNK = 64;
const MAX_POINTS = 2000; const MAX_POINTS = 2000;
/**
* Entry ceiling for the point cache, and with it the file written from it.
*
* Every distinct 5dp point is a separate key, so without a ceiling the map
* — and the JSON dumped from it verbatim — grow for as long as a caller
* supplies new coordinates. Measured against real use rather than guessed:
* this checkout's `.gev-cache/terrain-heights.json` held 6,189 entries in
* 1.0 MB after ordinary sessions, i.e. ~168 bytes/entry. 50,000 entries is
* eight times that working set and ~8 MB on disk, comfortably inside the
* 24 MB ceiling `rocketLaunchesProxy` already applies to its own cache file.
*/
const CACHE_MAX_ENTRIES = cacheMaxEntries;
/** Refuse to load a cache file larger than this (mirrors rocketLaunchesProxy). */
const CACHE_MAX_DISK_BYTES = cacheMaxDiskBytes;
/**
* Requests/min/client. Terrain is keyless and free, so this guards the point
* cache and the upstream community service rather than a bill. Sized from
* measurement: across a full `npm run test:track` run — the heaviest
* exercise this app has — the route served 10 requests, peaking at 8/min.
* 90/min is an order of magnitude above that, and the band `/api/overpass`
* and `/api/military-installations` already use.
*/
const RATE_PER_MIN = 90;
const allow = makeRateLimiter({
windowMs: 60_000,
max: RATE_PER_MIN,
globalMax: RATE_PER_MIN * 3,
});
/** @type {Map<string, {at:number, result:object}>} keyed by canonical 5dp lon/lat. */ /** @type {Map<string, {at:number, result:object}>} keyed by canonical 5dp lon/lat. */
const mem = new Map(); const mem = new Map();
/**
* Drop the oldest entries until the map is back inside its ceiling.
* Oldest-first by fetch time, the same shape `trackBackfillProxies` uses.
* Terrain does not move, so evicting an old point costs one refetch, never
* a wrong answer.
*/
function evictOverflow() {
if (mem.size <= CACHE_MAX_ENTRIES) return;
const byAge = [...mem.entries()].sort((a, b) => a[1].at - b[1].at);
for (let i = 0; i < byAge.length && mem.size > CACHE_MAX_ENTRIES; i += 1)
mem.delete(byAge[i][0]);
}
/** @type {Map<string, Promise<Array<object>>>} single-flight per missing-point subset. */ /** @type {Map<string, Promise<Array<object>>>} single-flight per missing-point subset. */
const inflight = new Map(); const inflight = new Map();
let diskLoaded = false; let diskLoaded = false;
@@ -110,21 +47,6 @@ export function terrainHeightsProxy(options = {}) {
if (diskLoaded) return; if (diskLoaded) return;
diskLoaded = true; diskLoaded = true;
try { try {
// A cache file past the ceiling is not read back into memory: loading it
// would reinstate exactly the unbounded map the ceiling exists to stop.
// The next flush rewrites a bounded one.
//
// "Cannot measure it" is not "too large": if stat is unavailable, fall
// through and let readFile decide, so an absent file behaves exactly as
// it did before this guard existed.
let sizeBytes = null;
try {
sizeBytes = (await fsp.stat(CACHE_PATH)).size;
} catch {
sizeBytes = null;
}
if (sizeBytes !== null && sizeBytes > CACHE_MAX_DISK_BYTES)
throw new Error('cache file too large');
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8')); const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
const pointEntries = const pointEntries =
parsed?.version === 2 && parsed?.version === 2 &&
@@ -165,7 +87,6 @@ export function terrainHeightsProxy(options = {}) {
} }
diskDirty = mem.size > 0; diskDirty = mem.size > 0;
} }
evictOverflow();
} catch { } catch {
/* no disk cache yet */ /* no disk cache yet */
} }
@@ -236,25 +157,12 @@ export function terrainHeightsProxy(options = {}) {
const installMiddleware = (server) => { const installMiddleware = (server) => {
server.middlewares.use('/api/terrain/heights', async (req, res) => { server.middlewares.use('/api/terrain/heights', async (req, res) => {
// Refuse cross-site browser requests (an <img> or fetch from another
// site) before the limiter, cache or upstream see them. Same-origin app
// requests, non-browser loopback callers (MCP panel_request) and the app
// served behind a reverse proxy pass.
if (admitSameSiteKeyless(req, res)) return;
const send = (status, bodyObj) => { const send = (status, bodyObj) => {
if (res.headersSent) return; if (res.headersSent) return;
res.writeHead(status, { 'Content-Type': 'application/json' }); res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(bodyObj)); res.end(JSON.stringify(bodyObj));
}; };
try { try {
if (!allow(clientKey(req))) {
res.writeHead(429, {
'Content-Type': 'application/json',
'Retry-After': '10',
});
res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
return;
}
await loadDiskOnce(); await loadDiskOnce();
const parsedUrl = new URL(req.url || '', 'http://internal'); const parsedUrl = new URL(req.url || '', 'http://internal');
const rawPoints = parsedUrl.searchParams.get('points'); const rawPoints = parsedUrl.searchParams.get('points');
@@ -279,10 +187,7 @@ export function terrainHeightsProxy(options = {}) {
fetchMissing: fetchMissingSingleFlight, fetchMissing: fetchMissingSingleFlight,
ttlMs: TTL_MS, ttlMs: TTL_MS,
}); });
if (outcome.cacheChanged) { if (outcome.cacheChanged) diskDirty = true;
evictOverflow();
diskDirty = true;
}
if (outcome.upstreamError) { if (outcome.upstreamError) {
console.warn( console.warn(
'[terrain-heights-proxy] refresh incomplete' + '[terrain-heights-proxy] refresh incomplete' +
+3 -2
View File
@@ -7,6 +7,7 @@ import { localMcpPlugin } from '../mcp/plugin.js';
import { apiNotFoundPlugin } from './api-not-found.js'; import { apiNotFoundPlugin } from './api-not-found.js';
import { standaloneVoiceTools } from './voiceTools.js'; import { standaloneVoiceTools } from './voiceTools.js';
import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js'; import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js';
import { vcamPlugin } from '../vcam/plugin.js';
const root = fileURLToPath(new URL('../../', import.meta.url)); const root = fileURLToPath(new URL('../../', import.meta.url));
@@ -16,11 +17,11 @@ export default defineConfig(({ command, mode }) => {
for (const [key, value] of Object.entries(loaded)) { for (const [key, value] of Object.entries(loaded)) {
if (process.env[key] === undefined) process.env[key] = value; if (process.env[key] === undefined) process.env[key] = value;
} }
const tools = standaloneVoiceTools();
return createBrowserViteConfig({ return createBrowserViteConfig({
plugins: [ plugins: [
...localProviderPlugins({ realtime: { tools }, gemini: { tools } }), ...localProviderPlugins({ realtime: { tools: standaloneVoiceTools() } }),
localMcpPlugin(), localMcpPlugin(),
vcamPlugin(),
apiNotFoundPlugin(), apiNotFoundPlugin(),
unwatchedRuntimeDirsPlugin(), unwatchedRuntimeDirsPlugin(),
], ],
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#0a0a0f"/><circle cx="32" cy="32" r="17" fill="none" stroke="#00d4ff" stroke-width="3"/><circle cx="32" cy="32" r="7" fill="#00d4ff"/><path d="M32 6v8M32 50v8M6 32h8M50 32h8" stroke="#00d4ff" stroke-width="3" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 343 B

+154
View File
@@ -0,0 +1,154 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no"
/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="theme-color" content="#0a0a0f" />
<title>GEV Virtual Camera</title>
<link rel="icon" href="icon.svg" />
<link rel="stylesheet" href="phone.css" />
</head>
<body>
<main id="app">
<section id="pair" class="screen">
<img class="logo" src="icon.svg" alt="" />
<h1>VIRTUAL CAMERA</h1>
<p class="lede">
Enter the code shown in God's Eye View under SCENES › VCAM.
</p>
<form id="pair-form" autocomplete="off">
<input
id="code"
inputmode="text"
autocapitalize="characters"
autocorrect="off"
spellcheck="false"
maxlength="6"
placeholder="CODE"
aria-label="Pairing code"
/>
<button id="join" type="submit" class="primary">PAIR</button>
</form>
<p id="pair-status" class="status" role="status"></p>
<details class="help">
<summary>Connection drops on iPhone?</summary>
<p>
Safari can load this page past a certificate warning but may still
refuse its live connection, so the camera falls back to slower
requests. To fix that once:
</p>
<ol>
<li>
<a id="ca-link" href="/ca.crt">Download the local certificate</a>
and allow the profile.
</li>
<li>Settings › General › VPN &amp; Device Management: install it.</li>
<li>
Settings › General › About › Certificate Trust Settings: turn on
full trust for "God's Eye View Local VCam CA".
</li>
</ol>
<p>The certificate only lets your phone trust this computer.</p>
</details>
</section>
<section id="start" class="screen" hidden>
<img class="logo" src="icon.svg" alt="" />
<h1>PAIRED</h1>
<p id="support" class="lede"></p>
<button id="start-xr" class="primary" hidden>START AR CAMERA</button>
<button id="start-gyro" class="primary">START GYRO CAMERA</button>
<p class="hint">
AR tracks position and rotation (6DoF). Gyro tracks rotation only;
move with the on-screen sticks.
</p>
<p id="start-status" class="status" role="status"></p>
</section>
<section id="camera" class="screen camera" hidden>
<img id="monitor" alt="" draggable="false" />
<div id="focus-ring" hidden></div>
<div class="topbar">
<span id="link-dot" class="dot" title="Connection"></span>
<span id="mode-readout" class="chip">—</span>
<span id="rec-readout" class="chip rec" hidden>● 00:00</span>
<span class="spacer"></span>
<span id="scale-readout" class="chip">1:1</span>
<span id="focal-readout" class="chip">31mm</span>
</div>
<p id="camera-status" class="toast" role="status" hidden></p>
<div class="stick left" id="stick-left" aria-label="Move">
<div class="knob"></div>
<span>MOVE</span>
</div>
<div class="stick right" id="stick-right" aria-label="Crane and pan">
<div class="knob"></div>
<span>CRANE · PAN</span>
</div>
<div class="bottombar">
<button id="hold-btn" class="tool" aria-pressed="false">HOLD</button>
<button id="recenter-btn" class="tool">RECENTER</button>
<button id="record-btn" class="record" aria-pressed="false">
<span class="record-dot"></span><span class="sr">RECORD</span>
</button>
<button id="scale-btn" class="tool" aria-expanded="false">
SCALE
</button>
<button id="lens-btn" class="tool" aria-expanded="false">LENS</button>
</div>
<div id="scale-drawer" class="drawer" hidden>
<div class="presets" id="scale-presets">
<button data-scale="1">1:1<small>WALK</small></button>
<button data-scale="10">1:10<small>CRANE</small></button>
<button data-scale="100">1:100<small>DRONE</small></button>
<button data-scale="1000">1:1K<small>FLYOVER</small></button>
<button data-scale="10000">1:10K<small>ORBIT</small></button>
</div>
<label
>MOTION SCALE <output id="scale-value">1:1</output>
<input id="scale-range" type="range" min="0" max="5" step="0.01" value="0"
/></label>
<label
>SMOOTHING <output id="smooth-value">30%</output>
<input id="smooth-range" type="range" min="0" max="100" step="1" value="30"
/></label>
<div class="toggles">
<label><input id="height-lock" type="checkbox" /> HEIGHT LOCK</label>
<label><input id="horizon-lock" type="checkbox" /> HORIZON LOCK</label>
</div>
</div>
<div id="lens-drawer" class="drawer" hidden>
<label
>FOCAL LENGTH <output id="focal-value">31mm</output>
<input id="focal-range" type="range" min="0" max="1" step="0.001" value="0.3"
/></label>
<div class="presets" id="focal-presets">
<button data-focal="14">14</button>
<button data-focal="24">24</button>
<button data-focal="35">35</button>
<button data-focal="50">50</button>
<button data-focal="85">85</button>
<button data-focal="200">200</button>
</div>
<div class="toggles">
<label><input id="dof-toggle" type="checkbox" /> DEPTH OF FIELD</label>
</div>
<label
>APERTURE <output id="fstop-value">f/2.8</output>
<input id="fstop-range" type="range" min="0" max="1" step="0.001" value="0.35"
/></label>
<p class="hint">Tap the picture to focus there.</p>
</div>
</section>
</main>
<script type="module" src="phone.js"></script>
</body>
</html>
+45
View File
@@ -0,0 +1,45 @@
/**
* Device orientation to the virtual camera's Y-up pose frame (+x right,
* +y up, -z forward), shared by the phone page and its tests.
*/
export const quat = {
multiply(a, b) {
const [ax, ay, az, aw] = a;
const [bx, by, bz, bw] = b;
return [
aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz,
];
},
axisAngle(axis, angle) {
const s = Math.sin(angle / 2);
return [axis[0] * s, axis[1] * s, axis[2] * s, Math.cos(angle / 2)];
},
};
const DEG = Math.PI / 180;
// Device orientation is device→earth (x east, y north, z up). Rotating -90°
// about x maps that earth frame to the Y-up frame (north becomes -z).
const EARTH_TO_Y_UP = quat.axisAngle([1, 0, 0], -Math.PI / 2);
/** W3C DeviceOrientation (Z-X'-Y'') to a Y-up quaternion for the current screen orientation. */
export function orientationQuaternion(alpha, beta, gamma, screenAngle) {
const x = (beta || 0) * DEG;
const y = (gamma || 0) * DEG;
const z = (alpha || 0) * DEG;
const cX = Math.cos(x / 2);
const cY = Math.cos(y / 2);
const cZ = Math.cos(z / 2);
const sX = Math.sin(x / 2);
const sY = Math.sin(y / 2);
const sZ = Math.sin(z / 2);
const device = [
sX * cY * cZ - cX * sY * sZ,
cX * sY * cZ + sX * cY * sZ,
cX * cY * sZ + sX * sY * cZ,
cX * cY * cZ - sX * sY * sZ,
];
const screen = quat.axisAngle([0, 0, 1], -(screenAngle || 0) * DEG);
return quat.multiply(EARTH_TO_Y_UP, quat.multiply(device, screen));
}
+39
View File
@@ -0,0 +1,39 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { orientationQuaternion } from './orientation.js';
import { rotateByQuaternion } from '../../../src/vcam/rig.js';
const close = (actual, expected, message) =>
actual.forEach((value, i) =>
assert.ok(Math.abs(value - expected[i]) < 1e-9, `${message}: ${actual} vs ${expected}`),
);
const axes = (q) => ({
forward: rotateByQuaternion(q, [0, 0, -1]),
up: rotateByQuaternion(q, [0, 1, 0]),
});
test('an upright portrait phone looks out of its back along the Y-up forward axis', () => {
// beta 90: stood up from flat, screen toward the user, back toward north.
const { forward, up } = axes(orientationQuaternion(0, 90, 0, 0));
close(forward, [0, 0, -1], 'faces north (-z)');
close(up, [0, 1, 0], 'top edge up');
});
test('alpha turns the phone counterclockwise seen from above', () => {
const { forward } = axes(orientationQuaternion(90, 90, 0, 0));
close(forward, [-1, 0, 0], 'faces west');
});
test('a landscape screen reports the picture\'s up, not the device\'s top edge', () => {
// Rotated a quarter turn counterclockwise: the top edge points west and the
// right edge up, the back still faces north, and the screen angle is 90.
const { forward, up } = axes(orientationQuaternion(90, 0, -90, 90));
close(forward, [0, 0, -1], 'still faces north');
close(up, [0, 1, 0], 'picture up is world up');
});
test('a phone lying flat, screen up, looks straight down', () => {
const { forward, up } = axes(orientationQuaternion(0, 0, 0, 0));
close(forward, [0, -1, 0], 'down');
close(up, [0, 0, -1], 'top edge toward north');
});
+371
View File
@@ -0,0 +1,371 @@
:root {
--bg: #0a0a0f;
--glass: rgba(12, 12, 20, 0.72);
--border: rgba(255, 255, 255, 0.12);
--accent: #00d4ff;
--accent-dim: rgba(0, 212, 255, 0.18);
--text: #e8eaed;
--muted: rgba(232, 234, 237, 0.6);
--rec: #ff3b4e;
--mono: 'SF Mono', ui-monospace, 'JetBrains Mono', Menlo, monospace;
--sans: -apple-system, BlinkMacSystemFont, 'Inter', system-ui, sans-serif;
color-scheme: dark;
}
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html,
body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
overscroll-behavior: none;
}
[hidden] {
display: none !important;
}
button {
font: inherit;
color: inherit;
cursor: pointer;
}
.screen {
min-height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
padding: max(24px, env(safe-area-inset-top)) 24px
max(24px, env(safe-area-inset-bottom));
text-align: center;
}
.logo {
width: 64px;
height: 64px;
}
h1 {
margin: 0;
font-family: var(--mono);
font-size: 20px;
letter-spacing: 0.18em;
}
.lede,
.hint,
.status {
margin: 0;
max-width: 34ch;
color: var(--muted);
font-size: 14px;
line-height: 1.45;
}
.status:empty {
display: none;
}
.status.error {
color: #ff8a95;
}
#pair-form {
display: flex;
gap: 8px;
}
#code {
width: 9.5ch;
padding: 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--glass);
color: var(--text);
font: 600 22px var(--mono);
letter-spacing: 0.2em;
text-align: center;
text-transform: uppercase;
}
.primary {
min-width: 220px;
padding: 14px 20px;
border: 1px solid var(--accent);
border-radius: 10px;
background: var(--accent-dim);
font: 600 15px var(--mono);
letter-spacing: 0.12em;
}
#pair-form .primary {
min-width: 0;
}
.help {
max-width: 36ch;
color: var(--muted);
font-size: 13px;
text-align: left;
}
.help summary {
cursor: pointer;
text-align: center;
}
.help a {
color: var(--accent);
}
/* Camera monitor: the desktop's render fills the screen. */
.camera {
position: fixed;
inset: 0;
padding: 0;
overflow: hidden;
touch-action: none;
user-select: none;
-webkit-user-select: none;
background: #000;
}
#monitor {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain;
background: #000;
}
.topbar,
.bottombar {
position: absolute;
left: max(10px, env(safe-area-inset-left));
right: max(10px, env(safe-area-inset-right));
display: flex;
align-items: center;
gap: 8px;
}
.topbar {
top: max(10px, env(safe-area-inset-top));
}
.bottombar {
bottom: max(12px, env(safe-area-inset-bottom));
justify-content: center;
gap: 10px;
}
.spacer {
flex: 1;
}
.chip {
padding: 5px 9px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--glass);
font: 600 12px var(--mono);
letter-spacing: 0.06em;
}
.chip.rec {
border-color: var(--rec);
color: var(--rec);
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #777;
box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.4);
}
.dot.live {
background: #3ddc84;
}
.dot.slow {
background: #ffb020;
}
.toast {
position: absolute;
top: calc(max(10px, env(safe-area-inset-top)) + 40px);
left: 50%;
transform: translateX(-50%);
margin: 0;
padding: 7px 12px;
border-radius: 10px;
background: var(--glass);
font-size: 13px;
white-space: nowrap;
}
.tool {
min-width: 64px;
padding: 10px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--glass);
font: 600 11px var(--mono);
letter-spacing: 0.08em;
}
.tool[aria-pressed='true'],
.tool[aria-expanded='true'] {
border-color: var(--accent);
background: var(--accent-dim);
}
.record {
display: grid;
place-items: center;
width: 64px;
height: 64px;
border: 3px solid #fff;
border-radius: 50%;
background: rgba(0, 0, 0, 0.35);
}
.record-dot {
width: 44px;
height: 44px;
border-radius: 50%;
background: var(--rec);
transition:
border-radius 150ms,
width 150ms,
height 150ms;
}
.record[aria-pressed='true'] .record-dot {
width: 24px;
height: 24px;
border-radius: 5px;
}
.sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
/* Virtual sticks sit low on each side, under the thumbs. */
.stick {
position: absolute;
bottom: calc(max(12px, env(safe-area-inset-bottom)) + 84px);
width: 128px;
height: 128px;
border: 1px solid var(--border);
border-radius: 50%;
background: rgba(12, 12, 20, 0.38);
touch-action: none;
}
.stick.left {
left: max(18px, env(safe-area-inset-left));
}
.stick.right {
right: max(18px, env(safe-area-inset-right));
}
.stick span {
position: absolute;
bottom: -20px;
left: 0;
right: 0;
color: var(--muted);
font: 600 10px var(--mono);
letter-spacing: 0.1em;
text-align: center;
}
.knob {
position: absolute;
top: 50%;
left: 50%;
width: 52px;
height: 52px;
margin: -26px 0 0 -26px;
border: 1px solid var(--accent);
border-radius: 50%;
background: var(--accent-dim);
}
.drawer {
position: absolute;
left: 50%;
bottom: calc(max(12px, env(safe-area-inset-bottom)) + 84px);
transform: translateX(-50%);
width: min(360px, calc(100% - 24px));
max-height: 60%;
overflow: auto;
padding: 14px;
border: 1px solid var(--border);
border-radius: 16px;
background: rgba(12, 12, 20, 0.9);
display: flex;
flex-direction: column;
gap: 12px;
font: 600 11px var(--mono);
letter-spacing: 0.08em;
z-index: 2;
}
.drawer label {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 6px;
}
.drawer input[type='range'] {
width: 100%;
accent-color: var(--accent);
}
.drawer output {
color: var(--accent);
}
.presets {
display: flex;
gap: 6px;
}
.presets button {
flex: 1;
padding: 8px 2px;
border: 1px solid var(--border);
border-radius: 8px;
background: transparent;
font: 600 12px var(--mono);
}
.presets button.active {
border-color: var(--accent);
background: var(--accent-dim);
}
.presets small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
.toggles {
display: flex;
flex-wrap: wrap;
gap: 14px;
}
.toggles label {
justify-content: flex-start;
align-items: center;
}
.drawer .hint {
font: 12px var(--sans);
letter-spacing: 0;
}
#focus-ring {
position: absolute;
width: 64px;
height: 64px;
margin: -32px 0 0 -32px;
border: 2px solid #ffd60a;
border-radius: 6px;
pointer-events: none;
animation: focus 700ms ease-out forwards;
}
@keyframes focus {
from {
transform: scale(1.5);
opacity: 1;
}
to {
transform: scale(1);
opacity: 0;
}
}
@media (orientation: landscape) and (max-height: 500px) {
.stick {
width: 112px;
height: 112px;
bottom: calc(max(12px, env(safe-area-inset-bottom)) + 24px);
}
.bottombar {
left: 160px;
right: 160px;
}
}
+770
View File
@@ -0,0 +1,770 @@
/**
* God's Eye View virtual camera — phone side.
*
* Streams this phone's pose to the desktop app and shows the app's render as
* a monitor. Tracking uses WebXR `immersive-ar` (6DoF, Android Chrome with
* ARCore) when available, otherwise device orientation (3DoF, iPhone Safari)
* with on-screen sticks for movement. Poses are sent in one Y-up frame for
* both: +x right, +y up, -z forward (WebXR's convention); yaw is arbitrary
* and the desktop aligns it on recenter.
*
* Transport: a WebSocket when the connection allows it, otherwise HTTPS
* requests (iOS refuses WebSockets under a tapped-through certificate). The
* monitor always pulls the newest frame, so a slow network drops frames
* instead of building a backlog.
*/
import { orientationQuaternion } from './orientation.js';
const $ = (id) => document.getElementById(id);
const KEY_STORAGE = 'gevVcam.phoneKey';
const CODE_STORAGE = 'gevVcam.code';
const SCALE_PRESETS = [1, 10, 100, 1000, 10000];
const FOCAL_RANGE = [12, 400];
const FSTOP_RANGE = [1.2, 22];
const STICK_DEADZONE = 0.12;
const store = {
get(key) {
try {
return sessionStorage.getItem(key);
} catch {
return null;
}
},
set(key, value) {
try {
if (value === null) sessionStorage.removeItem(key);
else sessionStorage.setItem(key, value);
} catch {
// Private browsing: pairing still works for this page load.
}
},
};
const logMap = ([low, high], v) => low * (high / low) ** v;
const logUnmap = ([low, high], value) =>
Math.log(value / low) / Math.log(high / low);
const round = (value, places = 5) => {
const k = 10 ** places;
return Math.round(value * k) / k;
};
const formatScale = (scale) =>
scale >= 1000
? `1:${+(scale / 1000).toFixed(scale >= 10000 ? 0 : 1)}K`
: `1:${+scale.toFixed(scale < 10 ? 1 : 0)}`;
const formatTime = (sec) => {
const s = Math.max(0, Math.floor(sec));
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
};
const screenAngle = () =>
screen.orientation?.angle ?? (Number(window.orientation) || 0);
// ------------------------------------------------------------------ transport
class Link {
constructor(key, { onMessage, onStatus, onUnpaired }) {
this.key = key;
this.onMessage = onMessage;
this.onStatus = onStatus;
this.onUnpaired = onUnpaired;
this.ws = null;
this.events = null;
this.mode = 'connecting';
this.queue = [];
this.pendingPose = null;
this.inFlight = false;
this.closed = false;
this.webSocketFailed = false;
this.retryTimer = null;
}
async start() {
if (this.closed) return;
this.onStatus('connecting');
if (!this.webSocketFailed && (await this.openWebSocket())) return;
this.webSocketFailed = true;
this.openHttp();
}
openWebSocket() {
return new Promise((resolve) => {
let settled = false;
let ws;
try {
ws = new WebSocket(
`wss://${location.host}/ws?key=${encodeURIComponent(this.key)}`,
);
} catch {
resolve(false);
return;
}
const done = (ok) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(ok);
};
const timer = setTimeout(() => {
ws.close();
done(false);
}, 3500);
ws.onopen = () => {
this.ws = ws;
this.mode = 'ws';
this.onStatus('live');
done(true);
};
ws.onerror = () => done(false);
ws.onmessage = (event) => this.receive(event.data);
ws.onclose = (event) => {
done(false);
if (this.ws !== ws) return;
this.ws = null;
this.mode = 'connecting';
this.handleClose(event.code);
};
});
}
openHttp() {
if (this.closed) return;
this.mode = 'http';
const events = new EventSource(
`/api/events?key=${encodeURIComponent(this.key)}`,
);
this.events = events;
events.onopen = () => this.onStatus('slow');
events.onmessage = (event) => this.receive(event.data);
events.onerror = async () => {
if (events.readyState !== EventSource.CLOSED || this.closed) return;
this.events = null;
// A closed stream is either a lost network or an ended session.
try {
const probe = await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Vcam-Key': this.key,
},
body: '[]',
cache: 'no-store',
});
if (probe.status === 403) return this.handleClose(4003);
} catch {
// Offline: retry below.
}
this.handleClose(1006);
};
this.flush();
}
handleClose(code) {
if (this.closed) return;
if (code === 4003 || code === 4000) {
this.onUnpaired(code === 4000 ? 'ended' : 'unpaired');
return;
}
if (code === 4001) {
this.onStatus('replaced');
this.close();
return;
}
this.onStatus('connecting');
clearTimeout(this.retryTimer);
this.retryTimer = setTimeout(() => this.start(), 1000);
}
receive(text) {
try {
this.onMessage(JSON.parse(text));
} catch {
// Ignore malformed relay input.
}
}
/** Poses are latest-wins; every other message is delivered in order. */
send(message) {
if (this.closed) return;
// 1 is WebSocket.OPEN.
if (this.ws && this.ws.readyState === 1) {
this.ws.send(JSON.stringify(message));
return;
}
if (message.type === 'pose') this.pendingPose = message;
else this.queue.push(message);
if (this.mode === 'http') this.flush();
}
async flush() {
if (this.inFlight || this.mode !== 'http' || this.closed) return;
const batch = this.queue.splice(0, 32);
if (this.pendingPose) batch.push(this.pendingPose);
this.pendingPose = null;
if (!batch.length) return;
this.inFlight = true;
try {
const response = await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Vcam-Key': this.key,
},
body: JSON.stringify(batch),
cache: 'no-store',
});
if (response.status === 403) this.handleClose(4003);
} catch {
// The event stream's error handling owns reconnection.
} finally {
this.inFlight = false;
}
if (this.queue.length || this.pendingPose) this.flush();
}
close() {
this.closed = true;
clearTimeout(this.retryTimer);
this.ws?.close();
this.events?.close();
this.ws = null;
this.events = null;
}
}
// --------------------------------------------------------------------- state
const app = {
key: store.get(KEY_STORAGE),
link: null,
tracking: null, // { mode: '6dof'|'3dof', stop() }
orientation: null,
sticks: { left: [0, 0], right: [0, 0] },
host: {
connected: false,
recording: false,
elapsedSec: 0,
scale: 1,
focalMm: 31.18,
fStop: 2.8,
dof: false,
held: false,
smoothing: 0.3,
heightLock: false,
horizonLock: false,
},
recordingSince: 0,
monitorRunning: false,
wakeLock: null,
};
function show(screenId) {
for (const id of ['pair', 'start', 'camera']) $(id).hidden = id !== screenId;
}
function setStatus(element, text, error = false) {
element.textContent = text || '';
element.classList.toggle('error', !!error);
}
let toastTimer = null;
function toast(text) {
const element = $('camera-status');
element.textContent = text;
element.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (element.hidden = true), 2600);
}
// ------------------------------------------------------------------- pairing
async function join(code) {
setStatus($('pair-status'), 'Pairing…');
try {
const response = await fetch('/api/join', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
cache: 'no-store',
});
if (response.status === 403) {
setStatus(
$('pair-status'),
'That code is not active. Check the code on the desktop.',
true,
);
return false;
}
if (!response.ok) throw new Error(String(response.status));
const { phoneKey } = await response.json();
app.key = phoneKey;
store.set(KEY_STORAGE, phoneKey);
store.set(CODE_STORAGE, code);
setStatus($('pair-status'), '');
connect();
showStart();
return true;
} catch {
setStatus(
$('pair-status'),
'Could not reach the desktop. Is it on the same network?',
true,
);
return false;
}
}
function connect() {
app.link?.close();
app.link = new Link(app.key, {
onMessage: handleMessage,
onStatus: presentLink,
onUnpaired: async (reason) => {
app.link?.close();
app.link = null;
store.set(KEY_STORAGE, null);
stopTracking();
const code = store.get(CODE_STORAGE);
if (reason === 'unpaired' && code && (await join(code))) return;
show('pair');
setStatus(
$('pair-status'),
reason === 'ended'
? 'The desktop ended this session. Enter a new code.'
: 'Pairing expired. Enter the code shown on the desktop.',
true,
);
},
});
app.link.start();
}
function presentLink(status) {
const dot = $('link-dot');
dot.classList.toggle('live', status === 'live');
dot.classList.toggle('slow', status === 'slow');
dot.title =
status === 'live'
? 'Live connection'
: status === 'slow'
? 'Fallback connection (install the certificate for lower latency)'
: 'Connecting…';
if (status === 'replaced') toast('Another phone took over this session');
}
async function showStart() {
show('start');
const xr = await xrSupported();
$('start-xr').hidden = !xr;
$('support').textContent = xr
? 'This phone supports AR tracking. Point it like a camera.'
: 'AR tracking is not available in this browser, so the gyro camera tracks rotation and the sticks move you.';
}
async function xrSupported() {
try {
return !!(await navigator.xr?.isSessionSupported('immersive-ar'));
} catch {
return false;
}
}
// ------------------------------------------------------------------ tracking
function sendPose(q, p) {
const { left, right } = app.sticks;
app.link?.send({
type: 'pose',
t: Math.round(performance.now()),
mode: app.tracking?.mode,
q: q.map((v) => round(v)),
p: p ? p.map((v) => round(v, 4)) : null,
j: [left[0], left[1], right[0], right[1]].map((v) => round(v, 3)),
});
}
async function startXr() {
setStatus($('start-status'), 'Starting AR…');
try {
const root = $('camera');
const session = await navigator.xr.requestSession('immersive-ar', {
requiredFeatures: ['local'],
optionalFeatures: ['dom-overlay'],
domOverlay: { root },
});
// Screen taps on controls must not become XR select input.
root.addEventListener('beforexrselect', (event) => event.preventDefault());
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl', { xrCompatible: true, alpha: true });
await gl.makeXRCompatible?.();
session.updateRenderState({ baseLayer: new XRWebGLLayer(session, gl) });
const space = await session.requestReferenceSpace('local');
let stopped = false;
const onFrame = (_time, frame) => {
if (stopped) return;
session.requestAnimationFrame(onFrame);
const pose = frame.getViewerPose(space);
if (pose) {
const { position, orientation } = pose.transform;
sendPose(
[orientation.x, orientation.y, orientation.z, orientation.w],
pose.emulatedPosition ? null : [position.x, position.y, position.z],
);
}
const layer = session.renderState.baseLayer;
gl.bindFramebuffer(gl.FRAMEBUFFER, layer.framebuffer);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
};
session.requestAnimationFrame(onFrame);
session.addEventListener('end', () => {
stopped = true;
if (app.tracking?.session === session) {
app.tracking = null;
showStart();
}
});
app.tracking = {
mode: '6dof',
session,
stop: () => session.end().catch(() => {}),
};
enterCamera();
} catch (error) {
setStatus(
$('start-status'),
`AR could not start (${error?.message || error}). Try the gyro camera.`,
true,
);
}
}
async function startGyro() {
// iOS asks for motion access only from a tap, before anything else awaits.
try {
if (typeof DeviceOrientationEvent?.requestPermission === 'function') {
const answer = await DeviceOrientationEvent.requestPermission();
if (answer !== 'granted') {
setStatus(
$('start-status'),
'Motion access was denied. Allow it in Safari settings for this site, then reload.',
true,
);
return;
}
}
} catch {
setStatus($('start-status'), 'Motion access is unavailable.', true);
return;
}
let stopped = false;
const onOrientation = (event) => {
if (event.alpha === null && event.beta === null) return;
app.orientation = orientationQuaternion(
event.alpha,
event.beta,
event.gamma,
screenAngle(),
);
};
window.addEventListener('deviceorientation', onOrientation);
const tick = () => {
if (stopped) return;
requestAnimationFrame(tick);
if (app.orientation) sendPose(app.orientation, null);
};
requestAnimationFrame(tick);
app.tracking = {
mode: '3dof',
stop: () => {
stopped = true;
window.removeEventListener('deviceorientation', onOrientation);
},
};
document.documentElement.requestFullscreen?.().catch(() => {});
enterCamera();
setTimeout(() => {
if (!app.orientation && !stopped)
toast('No motion data yet — this browser may block the gyroscope');
}, 1500);
}
function stopTracking() {
app.tracking?.stop();
app.tracking = null;
app.monitorRunning = false;
}
async function enterCamera() {
show('camera');
$('mode-readout').textContent =
app.tracking?.mode === '6dof' ? 'AR 6DOF' : 'GYRO 3DOF';
app.link?.send({
type: 'hello',
mode: app.tracking?.mode,
screen: [window.innerWidth, window.innerHeight],
});
try {
app.wakeLock = await navigator.wakeLock?.request('screen');
} catch {
// Optional: the screen may dim during long takes.
}
runMonitor();
}
// ------------------------------------------------------------------- monitor
async function runMonitor() {
if (app.monitorRunning) return;
app.monitorRunning = true;
const monitor = $('monitor');
let seq = 0;
let previousUrl = null;
while (app.monitorRunning && app.key) {
if (document.hidden) {
await new Promise((resolve) => setTimeout(resolve, 500));
continue;
}
try {
const response = await fetch(
`/api/frame?key=${encodeURIComponent(app.key)}&after=${seq}`,
{ cache: 'no-store' },
);
if (response.status === 403) break;
if (response.status !== 200) continue;
seq = Number(response.headers.get('X-Frame-Seq')) || seq + 1;
const url = URL.createObjectURL(await response.blob());
await new Promise((resolve) => {
monitor.onload = resolve;
monitor.onerror = resolve;
monitor.src = url;
});
if (previousUrl) URL.revokeObjectURL(previousUrl);
previousUrl = url;
} catch {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
app.monitorRunning = false;
}
// ------------------------------------------------------------------ controls
function stick(element, target) {
const knob = element.querySelector('.knob');
let pointer = null;
const set = (x, y) => {
target[0] = x;
target[1] = y;
const radius = element.clientWidth / 2 - 26;
knob.style.transform = `translate(${x * radius}px, ${-y * radius}px)`;
};
const move = (event) => {
const rect = element.getBoundingClientRect();
const radius = rect.width / 2;
let x = (event.clientX - rect.left - radius) / radius;
let y = -(event.clientY - rect.top - radius) / radius;
const length = Math.hypot(x, y);
if (length > 1) {
x /= length;
y /= length;
}
// Rescale past the dead zone so small nudges stay precise.
const live = Math.min(1, Math.hypot(x, y));
const scale =
live < STICK_DEADZONE
? 0
: (live - STICK_DEADZONE) / (1 - STICK_DEADZONE) / live;
set(x * scale, y * scale);
};
element.addEventListener('pointerdown', (event) => {
if (pointer !== null) return;
pointer = event.pointerId;
element.setPointerCapture(pointer);
move(event);
});
element.addEventListener('pointermove', (event) => {
if (event.pointerId === pointer) move(event);
});
const release = (event) => {
if (event.pointerId !== pointer) return;
pointer = null;
set(0, 0);
};
element.addEventListener('pointerup', release);
element.addEventListener('pointercancel', release);
}
const sendSet = (key, value) => app.link?.send({ type: 'set', key, value });
const sendCommand = (command) => app.link?.send({ type: 'cmd', cmd: command });
function presentHost() {
const h = app.host;
$('record-btn').setAttribute('aria-pressed', String(h.recording));
$('rec-readout').hidden = !h.recording;
$('hold-btn').setAttribute('aria-pressed', String(h.held));
$('scale-readout').textContent = formatScale(h.scale);
$('scale-value').textContent = formatScale(h.scale);
$('focal-readout').textContent = `${Math.round(h.focalMm)}mm`;
$('focal-value').textContent = `${Math.round(h.focalMm)}mm`;
$('fstop-value').textContent = `f/${h.fStop.toFixed(1)}`;
$('smooth-value').textContent = `${Math.round(h.smoothing * 100)}%`;
const active = (element) =>
element === document.activeElement && element.matches(':active');
if (!active($('scale-range')))
$('scale-range').value = String(Math.log10(h.scale));
if (!active($('focal-range')))
$('focal-range').value = String(logUnmap(FOCAL_RANGE, h.focalMm));
if (!active($('fstop-range')))
$('fstop-range').value = String(logUnmap(FSTOP_RANGE, h.fStop));
if (!active($('smooth-range')))
$('smooth-range').value = String(Math.round(h.smoothing * 100));
$('dof-toggle').checked = h.dof;
$('height-lock').checked = h.heightLock;
$('horizon-lock').checked = h.horizonLock;
for (const button of $('scale-presets').querySelectorAll('button'))
button.classList.toggle(
'active',
Math.abs(Number(button.dataset.scale) - h.scale) < 1e-6,
);
for (const button of $('focal-presets').querySelectorAll('button'))
button.classList.toggle(
'active',
Math.abs(Number(button.dataset.focal) - h.focalMm) < 0.5,
);
}
function handleMessage(message) {
if (message.type === 'state') {
const wasRecording = app.host.recording;
Object.assign(app.host, message.state);
if (app.host.recording && !wasRecording)
app.recordingSince = performance.now() - app.host.elapsedSec * 1000;
presentHost();
} else if (message.type === 'peer' && message.role === 'host') {
app.host.connected = message.connected;
if (!message.connected) toast('Desktop disconnected — waiting…');
} else if (message.type === 'toast' && typeof message.text === 'string') {
toast(message.text.slice(0, 140));
}
}
function toggleDrawer(name) {
for (const other of ['scale', 'lens']) {
const open = other === name && $(`${other}-drawer`).hidden;
$(`${other}-drawer`).hidden = !open;
$(`${other}-btn`).setAttribute('aria-expanded', String(open));
}
}
function bindControls() {
$('pair-form').addEventListener('submit', (event) => {
event.preventDefault();
const code = $('code').value.trim().toUpperCase();
if (code) join(code);
});
$('start-xr').addEventListener('click', startXr);
$('start-gyro').addEventListener('click', startGyro);
stick($('stick-left'), app.sticks.left);
stick($('stick-right'), app.sticks.right);
$('record-btn').addEventListener('click', () =>
sendCommand(app.host.recording ? 'stop' : 'record'),
);
$('hold-btn').addEventListener('click', () =>
sendCommand(app.host.held ? 'release' : 'hold'),
);
$('recenter-btn').addEventListener('click', () => sendCommand('recenter'));
$('scale-btn').addEventListener('click', () => toggleDrawer('scale'));
$('lens-btn').addEventListener('click', () => toggleDrawer('lens'));
$('scale-presets').addEventListener('click', (event) => {
const value = Number(event.target.closest('button')?.dataset.scale);
if (SCALE_PRESETS.includes(value)) sendSet('scale', value);
});
$('scale-range').addEventListener('input', (event) => {
const scale = 10 ** Number(event.target.value);
$('scale-value').textContent = formatScale(scale);
sendSet('scale', round(scale, 3));
});
$('smooth-range').addEventListener('input', (event) =>
sendSet('smoothing', Number(event.target.value) / 100),
);
$('height-lock').addEventListener('change', (event) =>
sendSet('heightLock', event.target.checked),
);
$('horizon-lock').addEventListener('change', (event) =>
sendSet('horizonLock', event.target.checked),
);
$('focal-range').addEventListener('input', (event) => {
const focal = logMap(FOCAL_RANGE, Number(event.target.value));
$('focal-value').textContent = `${Math.round(focal)}mm`;
sendSet('focalMm', round(focal, 2));
});
$('focal-presets').addEventListener('click', (event) => {
const value = Number(event.target.closest('button')?.dataset.focal);
if (value) sendSet('focalMm', value);
});
$('dof-toggle').addEventListener('change', (event) =>
sendSet('dof', event.target.checked),
);
$('fstop-range').addEventListener('input', (event) => {
const fStop = logMap(FSTOP_RANGE, Number(event.target.value));
$('fstop-value').textContent = `f/${fStop.toFixed(1)}`;
sendSet('fStop', round(fStop, 2));
});
// Tap the monitor to focus: coordinates are within the shown picture.
$('monitor').addEventListener('click', (event) => {
const monitor = $('monitor');
if (!monitor.naturalWidth) return;
const rect = monitor.getBoundingClientRect();
const fit = Math.min(
rect.width / monitor.naturalWidth,
rect.height / monitor.naturalHeight,
);
const width = monitor.naturalWidth * fit;
const height = monitor.naturalHeight * fit;
const x = (event.clientX - rect.left - (rect.width - width) / 2) / width;
const y = (event.clientY - rect.top - (rect.height - height) / 2) / height;
if (x < 0 || x > 1 || y < 0 || y > 1) return;
app.link?.send({ type: 'focus', x: round(x, 4), y: round(y, 4) });
const ring = $('focus-ring');
ring.hidden = true;
ring.style.left = `${event.clientX}px`;
ring.style.top = `${event.clientY}px`;
void ring.offsetWidth;
ring.hidden = false;
});
setInterval(() => {
if (app.host.recording)
$('rec-readout').textContent =
`● ${formatTime((performance.now() - app.recordingSince) / 1000)}`;
}, 250);
// The system releases a wake lock whenever the page is hidden.
document.addEventListener('visibilitychange', async () => {
if (document.hidden || !app.tracking) return;
if (app.wakeLock && !app.wakeLock.released) return;
try {
app.wakeLock = await navigator.wakeLock?.request('screen');
} catch {
// Optional.
}
});
}
function boot() {
bindControls();
presentHost();
const fromLink = decodeURIComponent(location.hash.slice(1))
.toUpperCase()
.replace(/[^0-9A-Z]/g, '');
if (fromLink) {
$('code').value = fromLink;
store.set(CODE_STORAGE, fromLink);
// Keep the code out of the address bar once read.
history.replaceState(null, '', location.pathname);
}
if (app.key) {
connect();
showStart();
} else if (fromLink) {
join(fromLink);
} else {
show('pair');
}
}
boot();
+522
View File
@@ -0,0 +1,522 @@
/**
* Virtual camera: lets a phone on the same network act as the app's camera.
*
* Two surfaces, deliberately separate:
*
* - On the app's own server (loopback only, behind the same gate as /mcp):
* `POST /api/vcam/session` creates a pairing session, `DELETE` ends it,
* `GET /api/vcam/ca.crt` downloads the local CA, and the desktop page joins
* its session over the `/api/vcam/host` WebSocket.
* - A separate HTTPS listener on the LAN (VCAM_PORT, default 4174) that starts
* only when the desktop creates a session and stops after the last one
* ends. It serves the static phone page and the phone side of the relay
* and nothing else, so pairing a phone never exposes the app's provider
* proxies or API keys to the network.
*
* The phone transport prefers a WebSocket and falls back to plain HTTPS
* requests (POST for poses, server-sent events for state), which work under
* a tapped-through certificate warning where iOS refuses WebSockets.
*/
import fs from 'node:fs';
import https from 'node:https';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { WebSocketServer } from 'ws';
import { isAllowedHost } from '../../build/allowedHosts.js';
import { isSharingEnabled } from '../../src/keySetupCore.mjs';
import { isLocalMcpRequest } from '../mcp/plugin.js';
import { MAX_FRAME_BYTES, MAX_TEXT_BYTES, createVcamRelay } from './relay.js';
import { loadLocalCertificates } from './tls.js';
const PHONE_DIR = fileURLToPath(new URL('./phone/', import.meta.url));
const PHONE_FILES = Object.freeze({
'/': ['index.html', 'text/html; charset=utf-8'],
'/index.html': ['index.html', 'text/html; charset=utf-8'],
'/phone.js': ['phone.js', 'text/javascript; charset=utf-8'],
'/orientation.js': ['orientation.js', 'text/javascript; charset=utf-8'],
'/phone.css': ['phone.css', 'text/css; charset=utf-8'],
'/icon.svg': ['icon.svg', 'image/svg+xml'],
});
const DEFAULT_PORT = 4174;
const MAX_BATCH_BYTES = 64 * 1024;
const BODY_TIMEOUT_MS = 10000;
const SSE_KEEPALIVE_MS = 15000;
// The listener lingers after the last session in case the desktop reloads.
const IDLE_SHUTDOWN_MS = 120000;
const CA_CONTENT_TYPE = 'application/x-x509-ca-cert';
/** Headers for every phone-listener response; the page is static. */
export const PHONE_HEADERS = Object.freeze({
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' blob: data:",
"connect-src 'self' wss:",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
"object-src 'none'",
].join('; '),
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Cache-Control': 'no-store',
'Permissions-Policy': 'xr-spatial-tracking=(self), camera=(self)',
});
/**
* IPv4 addresses a phone on the same network could reach, private ranges
* first (home and office Wi-Fi), then others. Loopback and link-local are
* left out.
*/
export function lanAddresses(interfaces = os.networkInterfaces()) {
const rank = (address) =>
address.startsWith('192.168.')
? 0
: address.startsWith('10.')
? 1
: /^172\.(1[6-9]|2\d|3[01])\./.test(address)
? 2
: 3;
const found = [];
for (const entries of Object.values(interfaces || {}))
for (const entry of entries || []) {
const family = entry.family === 4 ? 'IPv4' : entry.family;
if (family !== 'IPv4' || entry.internal) continue;
if (entry.address.startsWith('169.254.')) continue;
if (!found.includes(entry.address)) found.push(entry.address);
}
return found.sort((a, b) => rank(a) - rank(b));
}
const json = (res, status, body) => {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(body));
};
function readBody(req, limit) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
const timer = setTimeout(() => {
reject(Object.assign(new Error('timeout'), { status: 408 }));
req.destroy();
}, BODY_TIMEOUT_MS);
req.on('data', (chunk) => {
size += chunk.length;
if (size > limit) {
clearTimeout(timer);
reject(Object.assign(new Error('too large'), { status: 413 }));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => {
clearTimeout(timer);
resolve(Buffer.concat(chunks).toString('utf8'));
});
req.on('error', (error) => {
clearTimeout(timer);
reject(error);
});
});
}
/** Whether a desktop request may control pairing (loopback, same-origin). */
function isDesktopRequest(req, env, { requireOrigin = true } = {}) {
if (requireOrigin && !req.headers.origin) return false;
return isLocalMcpRequest({
remoteAddress: req.socket?.remoteAddress,
localPort: req.socket?.localPort,
host: req.headers.host || '',
origin: req.headers.origin,
headers: req.headers,
env,
});
}
/**
* Create the virtual-camera service: the relay, the lazily started phone
* listener and the handlers both servers mount.
*/
export function createVcamService({
env = process.env,
cacheDir = path.join(process.cwd(), '.gev-cache', 'vcam'),
port = Number.parseInt(env.VCAM_PORT, 10) || DEFAULT_PORT,
host = env.VCAM_HOST || '0.0.0.0',
addresses = () => lanAddresses(),
allowedHosts = [],
logger = console,
} = {}) {
let listener = null;
let listenerNames = '';
let starting = null;
let idleTimer = null;
let certificates = null;
const relay = createVcamRelay({
onSessionClosed: () => {
if (relay.size === 0) scheduleIdleShutdown();
},
});
const sockets = new WebSocketServer({
noServer: true,
maxPayload: MAX_FRAME_BYTES,
});
function scheduleIdleShutdown() {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
if (relay.size === 0) stopListener();
}, IDLE_SHUTDOWN_MS);
idleTimer.unref?.();
}
function stopListener() {
const current = listener;
listener = null;
listenerNames = '';
current?.closeAllConnections?.();
current?.close();
}
/** Start (or restart for a changed address) the HTTPS phone listener. */
async function ensureListener(requested) {
clearTimeout(idleTimer);
const names = [...new Set(requested)];
const key = names.join(',');
if (listener && listenerNames === key) return;
if (starting) await starting.catch(() => {});
if (listener && listenerNames === key) return;
stopListener();
certificates = loadLocalCertificates(cacheDir, names);
const server = https.createServer(
{ cert: certificates.cert, key: certificates.key },
(req, res) => handlePhoneRequest(req, res),
);
server.on('upgrade', (req, socket, head) =>
handlePhoneUpgrade(req, socket, head),
);
server.on('clientError', (_error, socket) => socket.destroy());
starting = new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, host, () => {
server.off('error', reject);
resolve();
});
});
try {
await starting;
} finally {
starting = null;
}
listener = server;
listenerNames = key;
logger.info?.(
`[vcam] phone listener on https://${names[0]}:${port}/ (pairing session only)`,
);
}
const phoneHostAllowed = (req) =>
isAllowedHost(req.headers.host, allowedHosts);
function servePhoneFile(req, res, pathname) {
const entry = PHONE_FILES[pathname];
if (!entry) return false;
const [file, type] = entry;
let body;
try {
body = fs.readFileSync(path.join(PHONE_DIR, file));
} catch {
json(res, 500, { error: 'phone page unavailable' });
return true;
}
res.statusCode = 200;
res.setHeader('Content-Type', type);
res.end(req.method === 'HEAD' ? undefined : body);
return true;
}
function sendCa(res) {
res.statusCode = 200;
res.setHeader('Content-Type', CA_CONTENT_TYPE);
res.setHeader(
'Content-Disposition',
'attachment; filename="gods-eye-view-vcam-ca.crt"',
);
res.end(certificates?.ca || '');
}
function phoneSession(req, url) {
const key = req.headers['x-vcam-key'] || url.searchParams.get('key');
return relay.sessionForPhone(key);
}
async function handlePhoneRequest(req, res) {
for (const [name, value] of Object.entries(PHONE_HEADERS))
res.setHeader(name, value);
if (!phoneHostAllowed(req)) return json(res, 421, { error: 'bad host' });
let url;
try {
url = new URL(req.url, 'https://phone.invalid');
} catch {
return json(res, 400, { error: 'bad request' });
}
const { pathname } = url;
try {
if (req.method === 'GET' || req.method === 'HEAD') {
if (servePhoneFile(req, res, pathname)) return;
if (pathname === '/ca.crt') return sendCa(res);
}
if (pathname === '/api/join' && req.method === 'POST') {
let code = '';
try {
code = JSON.parse(await readBody(req, 1024))?.code;
} catch (error) {
if (error?.status) throw error;
}
const joined = relay.joinPhone(code);
if (!joined.ok) return json(res, 403, { error: joined.reason });
return json(res, 200, {
phoneKey: joined.phoneKey,
sessionId: joined.sessionId,
limits: { text: MAX_TEXT_BYTES },
});
}
if (pathname === '/api/send' && req.method === 'POST') {
const session = phoneSession(req, url);
if (!session) return json(res, 403, { error: 'unpaired' });
let messages;
try {
messages = JSON.parse(await readBody(req, MAX_BATCH_BYTES));
} catch (error) {
if (error?.status) throw error;
return json(res, 400, { error: 'expected a JSON array' });
}
if (!Array.isArray(messages) || messages.length > 64)
return json(res, 400, { error: 'expected a JSON array' });
let accepted = 0;
for (const message of messages)
if (relay.relay(session, 'phone', JSON.stringify(message)))
accepted += 1;
return json(res, 200, { accepted });
}
if (pathname === '/api/events' && req.method === 'GET')
return openEventStream(req, res, phoneSession(req, url));
if (pathname === '/api/frame' && req.method === 'GET') {
const session = phoneSession(req, url);
if (!session) return json(res, 403, { error: 'unpaired' });
const after = Number.parseInt(url.searchParams.get('after'), 10) || 0;
const frame = await relay.nextFrame(session, after, 2000);
if (!frame) {
res.statusCode = 204;
return res.end();
}
res.statusCode = 200;
res.setHeader('Content-Type', 'image/jpeg');
res.setHeader('X-Frame-Seq', String(frame.seq));
return res.end(frame.bytes);
}
json(res, 404, { error: 'not found' });
} catch (error) {
if (!res.headersSent)
json(res, error?.status || 500, { error: 'request failed' });
else res.end();
}
}
function openEventStream(req, res, session) {
if (!session) return json(res, 403, { error: 'unpaired' });
res.statusCode = 200;
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders?.();
const keepAlive = setInterval(
() => res.write(': keep-alive\n\n'),
SSE_KEEPALIVE_MS,
);
const peer = {
send: (text) => res.write(`data: ${text}\n\n`),
close: () => res.end(),
};
const attached = relay.attachPhone(
req.headers['x-vcam-key'] ||
new URL(req.url, 'https://phone.invalid').searchParams.get('key'),
peer,
);
if (!attached) {
clearInterval(keepAlive);
return res.end();
}
req.on('close', () => {
clearInterval(keepAlive);
relay.detach(attached, 'phone', peer);
});
}
function refuseUpgrade(socket, status) {
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
}
function handlePhoneUpgrade(req, socket, head) {
let url;
try {
url = new URL(req.url, 'https://phone.invalid');
} catch {
return refuseUpgrade(socket, '400 Bad Request');
}
if (url.pathname !== '/ws' || !phoneHostAllowed(req))
return refuseUpgrade(socket, '404 Not Found');
// A WebSocket is not subject to CORS: only this page's own origin may open one.
if (req.headers.origin !== `https://${req.headers.host}`)
return refuseUpgrade(socket, '403 Forbidden');
const key = url.searchParams.get('key');
if (!relay.sessionForPhone(key))
return refuseUpgrade(socket, '403 Forbidden');
sockets.handleUpgrade(req, socket, head, (ws) => {
const peer = {
send: (text) => ws.readyState === ws.OPEN && ws.send(text),
close: (code, reason) => ws.close(code, reason),
};
const session = relay.attachPhone(key, peer);
if (!session) return ws.close(4003, 'unpaired');
ws.on('message', (data, isBinary) => {
if (isBinary) return;
relay.relay(session, 'phone', data.toString('utf8'));
});
ws.on('close', () => relay.detach(session, 'phone', peer));
ws.on('error', () => ws.terminate());
});
}
/** Mount the desktop routes on the app's own (dev or preview) server. */
function install(server) {
server.middlewares.use('/api/vcam', async (req, res, next) => {
const pathname = (req.url || '/').split('?')[0];
try {
if (pathname === '/ca.crt' && req.method === 'GET') {
if (!isDesktopRequest(req, env, { requireOrigin: false }))
return json(res, 403, { error: 'local only' });
if (!certificates)
certificates = loadLocalCertificates(cacheDir, [
...addresses(),
'localhost',
'127.0.0.1',
]);
return sendCa(res);
}
if (pathname !== '/session') return next();
if (!isDesktopRequest(req, env))
return json(res, 403, { error: 'local only' });
if (isSharingEnabled(env))
return json(res, 403, { error: 'sharing is enabled' });
if (req.method === 'POST') {
const lan = addresses();
if (!lan.length)
return json(res, 503, {
error: 'no network address',
code: 'no-network',
});
try {
await ensureListener([...lan, 'localhost', '127.0.0.1']);
} catch (error) {
return json(res, 503, {
error: 'phone listener unavailable',
code: error?.code === 'EADDRINUSE' ? 'port-in-use' : 'listen',
port,
});
}
const session = relay.createSession();
return json(res, 200, {
sessionId: session.id,
hostKey: session.hostKey,
code: session.code,
port: listener.address()?.port ?? port,
addresses: lan,
caFingerprint: certificates.caFingerprint,
});
}
if (req.method === 'DELETE') {
relay.endSession(req.headers['x-vcam-host-key']);
return json(res, 200, { ended: true });
}
return json(res, 405, { error: 'method not allowed' });
} catch {
if (!res.headersSent) json(res, 500, { error: 'request failed' });
}
});
server.httpServer?.on('upgrade', (req, socket, head) => {
let url;
try {
url = new URL(req.url, 'http://local.invalid');
} catch {
return;
}
if (url.pathname !== '/api/vcam/host') return;
// Browsers always send Origin on a WebSocket; it must be this app.
if (!isDesktopRequest(req, env))
return refuseUpgrade(socket, '403 Forbidden');
const key = url.searchParams.get('key');
if (!relay.sessionForHost(key))
return refuseUpgrade(socket, '403 Forbidden');
sockets.handleUpgrade(req, socket, head, (ws) => {
const peer = {
send: (text) => ws.readyState === ws.OPEN && ws.send(text),
close: (code, reason) => ws.close(code, reason),
};
const session = relay.attachHost(key, peer);
if (!session) return ws.close(4003, 'unknown session');
ws.on('message', (data, isBinary) => {
if (isBinary) relay.publishFrame(session, Buffer.from(data));
else relay.relay(session, 'host', data.toString('utf8'));
});
ws.on('close', () => relay.detach(session, 'host', peer));
ws.on('error', () => ws.terminate());
});
});
server.httpServer?.once('close', () => destroy());
}
function destroy() {
clearTimeout(idleTimer);
relay.closeAll();
stopListener();
sockets.close();
}
return {
install,
destroy,
relay,
ensureListener,
get listening() {
return !!listener;
},
get port() {
return listener?.address()?.port ?? port;
},
};
}
/** Vite plugin mounting the virtual-camera desktop routes and phone listener. */
export function vcamPlugin(options = {}) {
let service = null;
const install = (server) => {
service ??= createVcamService({
allowedHosts: server.config?.server?.allowedHosts || [],
logger: server.config?.logger || console,
...options,
});
service.install(server);
};
return {
name: 'gev-vcam',
configureServer: install,
configurePreviewServer: install,
};
}
+274
View File
@@ -0,0 +1,274 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
import { createVcamService, lanAddresses, PHONE_HEADERS } from './plugin.js';
/** The slice of a Vite server the service mounts on. */
function appServer() {
const stack = [];
const httpServer = http.createServer((req, res) => {
const layer = stack.find(({ prefix }) => req.url.startsWith(prefix));
if (!layer) {
res.statusCode = 404;
return res.end();
}
req.url = req.url.slice(layer.prefix.length) || '/';
layer.handle(req, res, () => {
res.statusCode = 404;
res.end();
});
});
return {
httpServer,
middlewares: { use: (prefix, handle) => stack.push({ prefix, handle }) },
};
}
const listen = (server) =>
new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
function request(url, { method = 'GET', headers = {}, body, ca, checkServerIdentity } = {}) {
const target = new URL(url);
const client = target.protocol === 'https:' ? https : http;
return new Promise((resolve, reject) => {
const req = client.request(
target,
{ method, headers, ca, ...(checkServerIdentity ? { checkServerIdentity } : {}) },
(res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () =>
resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }),
);
},
);
req.on('error', reject);
req.end(body);
});
}
/** Buffer a socket's messages from creation so back-to-back sends are never missed. */
const inboxes = new WeakMap();
function connect(url, options) {
const ws = new WebSocket(url, options);
const box = { queued: [], waiting: [] };
inboxes.set(ws, box);
ws.on('message', (data) => {
const message = JSON.parse(data.toString());
const waiter = box.waiting.shift();
if (waiter) waiter(message);
else box.queued.push(message);
});
return ws;
}
function nextMessage(ws) {
const box = inboxes.get(ws);
if (box.queued.length) return Promise.resolve(box.queued.shift());
return new Promise((resolve) => box.waiting.push(resolve));
}
const opened = (ws) =>
new Promise((resolve, reject) => {
ws.once('open', resolve);
ws.once('error', reject);
ws.once('unexpected-response', (_req, res) => reject(new Error(`HTTP ${res.statusCode}`)));
});
async function harness(t) {
const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-vcam-'));
const service = createVcamService({
env: {},
cacheDir,
port: 0,
host: '127.0.0.1',
// The phone reaches the listener on loopback in this test.
addresses: () => ['127.0.0.1'],
logger: {},
});
const app = appServer();
service.install(app);
await listen(app.httpServer);
const appOrigin = `http://127.0.0.1:${app.httpServer.address().port}`;
t.after(() => {
service.destroy();
app.httpServer.close();
fs.rmSync(cacheDir, { recursive: true, force: true });
});
const session = async () => {
const response = await request(`${appOrigin}/api/vcam/session`, {
method: 'POST',
headers: { Origin: appOrigin },
});
assert.equal(response.status, 200);
return JSON.parse(response.body);
};
const ca = () => fs.readFileSync(path.join(cacheDir, 'ca.crt'));
return { service, appOrigin, session, ca };
}
test('the desktop pairs a phone over a trusted local CA and both legs relay', async (t) => {
const { appOrigin, session, ca } = await harness(t);
const created = await session();
assert.equal(created.code.length, 6);
assert.deepEqual(created.addresses, ['127.0.0.1']);
const phoneOrigin = `https://127.0.0.1:${created.port}`;
const page = await request(`${phoneOrigin}/`, { ca: ca() });
assert.equal(page.status, 200);
assert.match(page.body.toString(), /VIRTUAL CAMERA/);
for (const [name, value] of Object.entries(PHONE_HEADERS))
assert.equal(page.headers[name.toLowerCase()], value);
assert.equal((await request(`${phoneOrigin}/api/vcam/session`, { method: 'POST', ca: ca() })).status, 404,
'the phone listener exposes none of the desktop routes');
const certificate = await request(`${phoneOrigin}/ca.crt`, { ca: ca() });
assert.equal(certificate.headers['content-type'], 'application/x-x509-ca-cert');
assert.equal(certificate.body.toString(), ca().toString());
const host = connect(
`ws://127.0.0.1:${new URL(appOrigin).port}/api/vcam/host?key=${created.hostKey}`,
{ origin: appOrigin },
);
const hostCode = nextMessage(host);
await opened(host);
assert.deepEqual(await hostCode, { type: 'code', code: created.code });
await nextMessage(host); // phone not yet connected
const join = await request(`${phoneOrigin}/api/join`, {
method: 'POST', ca: ca(), body: JSON.stringify({ code: created.code }),
});
assert.equal(join.status, 200);
const { phoneKey } = JSON.parse(join.body);
const phone = connect(`wss://127.0.0.1:${created.port}/ws?key=${phoneKey}`, {
ca: ca(), origin: phoneOrigin,
});
const hostSeesPhone = nextMessage(host);
await opened(phone);
assert.deepEqual(await hostSeesPhone, { type: 'peer', role: 'phone', connected: true });
const pose = { type: 'pose', t: 1, q: [0, 0, 0, 1], p: [0, 1.5, 0] };
const received = nextMessage(host);
phone.send(JSON.stringify(pose));
assert.deepEqual(await received, pose);
await nextMessage(phone); // host presence
const state = nextMessage(phone);
host.send(JSON.stringify({ type: 'state', state: { recording: true } }));
assert.deepEqual(await state, { type: 'state', state: { recording: true } });
// The host's binary messages are preview frames the phone pulls over HTTPS.
host.send(Buffer.from([0xff, 0xd8, 0xff, 0xe0, 7]));
const frame = await request(`${phoneOrigin}/api/frame?after=0`, { ca: ca(), headers: { 'X-Vcam-Key': phoneKey } });
assert.equal(frame.status, 200);
assert.equal(frame.headers['content-type'], 'image/jpeg');
assert.equal(frame.headers['x-frame-seq'], '1');
assert.equal(frame.body.at(-1), 7);
phone.close();
host.close();
});
test('the HTTPS fallback relays poses by POST and state by server-sent events', async (t) => {
const { appOrigin, session, ca } = await harness(t);
const created = await session();
const phoneOrigin = `https://127.0.0.1:${created.port}`;
const host = connect(
`ws://127.0.0.1:${new URL(appOrigin).port}/api/vcam/host?key=${created.hostKey}`,
{ origin: appOrigin },
);
await opened(host);
const { phoneKey } = JSON.parse(
(await request(`${phoneOrigin}/api/join`, { method: 'POST', ca: ca(), body: JSON.stringify({ code: created.code }) })).body,
);
const events = await new Promise((resolve) => {
https.get(`${phoneOrigin}/api/events?key=${phoneKey}`, { ca: ca() }, resolve);
});
assert.equal(events.headers['content-type'], 'text/event-stream; charset=utf-8');
const firstEvent = new Promise((resolve) => events.once('data', (chunk) => resolve(chunk.toString())));
assert.match(await firstEvent, /^data: \{"type":"peer","role":"host","connected":true\}/);
const relayed = [];
const collect = async () => {
for (;;) relayed.push(await nextMessage(host));
};
collect();
const sent = await request(`${phoneOrigin}/api/send`, {
method: 'POST', ca: ca(), headers: { 'X-Vcam-Key': phoneKey },
body: JSON.stringify([{ type: 'cmd', cmd: 'record' }, { type: 'pose', t: 2 }, 'not an object']),
});
assert.deepEqual(JSON.parse(sent.body), { accepted: 2 });
await new Promise((resolve) => setTimeout(resolve, 50));
assert.deepEqual(relayed.filter(({ type }) => !['peer', 'code'].includes(type)), [{ type: 'cmd', cmd: 'record' }, { type: 'pose', t: 2 }]);
const downstream = new Promise((resolve) => events.once('data', (chunk) => resolve(chunk.toString())));
host.send(JSON.stringify({ type: 'toast', text: 'hi' }));
assert.equal(await downstream, 'data: {"type":"toast","text":"hi"}\n\n');
const ended = new Promise((resolve) => events.once('end', resolve));
await request(`${appOrigin}/api/vcam/session`, { method: 'DELETE', headers: { Origin: appOrigin, 'X-Vcam-Host-Key': created.hostKey } });
await ended;
const after = await request(`${phoneOrigin}/api/send`, {
method: 'POST', ca: ca(), headers: { 'X-Vcam-Key': phoneKey }, body: '[]',
});
assert.equal(after.status, 403, 'an ended session revokes the phone');
host.close();
});
test('pairing refuses foreign origins, bad codes, bad keys and cross-site sockets', async (t) => {
const { appOrigin, session, ca } = await harness(t);
const noOrigin = await request(`${appOrigin}/api/vcam/session`, { method: 'POST' });
assert.equal(noOrigin.status, 403, 'a session needs the page origin');
const foreign = await request(`${appOrigin}/api/vcam/session`, { method: 'POST', headers: { Origin: 'https://evil.example' } });
assert.equal(foreign.status, 403);
const proxied = await request(`${appOrigin}/api/vcam/session`, { method: 'POST', headers: { Origin: appOrigin, 'X-Forwarded-For': '1.2.3.4' } });
assert.equal(proxied.status, 403);
const created = await session();
const phoneOrigin = `https://127.0.0.1:${created.port}`;
const badJoin = await request(`${phoneOrigin}/api/join`, { method: 'POST', ca: ca(), body: '{"code":"222222"}' });
assert.equal(badJoin.status, 403);
const hugeJoin = await request(`${phoneOrigin}/api/join`, { method: 'POST', ca: ca(), body: 'x'.repeat(5000) }).catch(() => ({ status: 413 }));
assert.equal(hugeJoin.status, 413);
const badHost = await request(`${phoneOrigin}/`, {
ca: ca(), headers: { Host: 'rebind.example' }, checkServerIdentity: () => undefined,
});
assert.equal(badHost.status, 421, 'the phone listener answers IP addresses and allowed hosts only');
await assert.rejects(
opened(new WebSocket(`ws://127.0.0.1:${new URL(appOrigin).port}/api/vcam/host?key=${created.hostKey}`, { origin: 'https://evil.example' })),
/403/,
);
await assert.rejects(
opened(new WebSocket(`ws://127.0.0.1:${new URL(appOrigin).port}/api/vcam/host?key=wrong`, { origin: appOrigin })),
/403/,
);
const { phoneKey } = JSON.parse(
(await request(`${phoneOrigin}/api/join`, { method: 'POST', ca: ca(), body: JSON.stringify({ code: created.code }) })).body,
);
await assert.rejects(
opened(new WebSocket(`wss://127.0.0.1:${created.port}/ws?key=${phoneKey}`, { ca: ca(), origin: 'https://evil.example' })),
/403/,
);
await assert.rejects(
opened(new WebSocket(`wss://127.0.0.1:${created.port}/ws?key=wrong`, { ca: ca(), origin: phoneOrigin })),
/403/,
);
});
test('LAN addresses prefer private ranges and skip loopback and link-local', () => {
assert.deepEqual(
lanAddresses({
lo: [{ family: 'IPv4', address: '127.0.0.1', internal: true }],
docker0: [{ family: 'IPv4', address: '172.17.0.1', internal: false }],
en0: [
{ family: 'IPv6', address: 'fe80::1', internal: false },
{ family: 4, address: '192.168.1.23', internal: false },
],
tun0: [{ family: 'IPv4', address: '100.64.0.2', internal: false }],
bad: [{ family: 'IPv4', address: '169.254.3.3', internal: false }],
}),
['192.168.1.23', '172.17.0.1', '100.64.0.2'],
);
});
+319
View File
@@ -0,0 +1,319 @@
/**
* Pairing and message relay between the desktop app (host) and one phone.
*
* Transport-agnostic: a peer is `{ send(text), close(code, reason) }`, so the
* WebSocket and HTTP-fallback transports share every rule here. The desktop
* creates a session from a loopback request and receives a host key. The
* phone proves possession of the short pairing code shown on the desktop
* (carried in the QR code's URL fragment) and receives its own key. Too many
* wrong codes rotate the code, so guessing cannot outlast the session.
*
* Messages are small JSON texts the relay forwards without interpreting,
* bounded in size and rate. The newest preview frame (a JPEG the host sends)
* is held for the phone to pull, so a slow phone drops frames instead of
* queueing them.
*/
import crypto from 'node:crypto';
// No 0/O, 1/I/L: the code is read off a screen.
const CODE_ALPHABET = '23456789ABCDEFGHJKMNPQRSTUVWXYZ';
export const PAIRING_CODE_LENGTH = 6;
export const MAX_TEXT_BYTES = 4096;
export const MAX_FRAME_BYTES = 768 * 1024;
const MAX_CODE_FAILURES = 8;
const MESSAGE_BURST = 240;
const MESSAGES_PER_SECOND = 120;
// A host that disappears (a reload, a closed tab) may come back this soon.
const HOST_GRACE_MS = 60000;
const MAX_SESSIONS = 4;
const randomKey = () => crypto.randomBytes(24).toString('base64url');
function pairingCode(randomBytes = crypto.randomBytes) {
const bytes = randomBytes(PAIRING_CODE_LENGTH);
let code = '';
for (const byte of bytes) code += CODE_ALPHABET[byte % CODE_ALPHABET.length];
return code;
}
const sameSecret = (a, b) => {
const left = Buffer.from(String(a));
const right = Buffer.from(String(b));
return left.length === right.length && crypto.timingSafeEqual(left, right);
};
const normalizeCode = (code) =>
String(code ?? '')
.toUpperCase()
.replace(/[^0-9A-Z]/g, '')
.slice(0, 32);
/**
* @param {object} [options]
* @param {() => number} [options.now]
* @param {(session: object) => void} [options.onSessionClosed]
*/
export function createVcamRelay({
now = () => Date.now(),
onSessionClosed = () => {},
setTimer = setTimeout,
clearTimer = clearTimeout,
} = {}) {
/** @type {Map<string, object>} */
const sessions = new Map();
const bucket = () => ({ tokens: MESSAGE_BURST, at: now() });
function admit(rate) {
const at = now();
rate.tokens = Math.min(
MESSAGE_BURST,
rate.tokens + ((at - rate.at) / 1000) * MESSAGES_PER_SECOND,
);
rate.at = at;
if (rate.tokens < 1) return false;
rate.tokens -= 1;
return true;
}
function notify(peer, message) {
try {
peer?.send(JSON.stringify(message));
} catch {
// A failed send belongs to that transport's own close handling.
}
}
function closeSession(session, reason = 'ended') {
if (!sessions.has(session.id)) return;
sessions.delete(session.id);
clearTimer(session.hostTimer);
for (const role of ['host', 'phone']) {
const peer = session[role];
session[role] = null;
try {
peer?.close(4000, reason);
} catch {
// Already closed.
}
}
for (const waiter of session.frameWaiters.splice(0)) waiter(null);
onSessionClosed(session);
}
function scheduleHostExpiry(session) {
clearTimer(session.hostTimer);
session.hostTimer = setTimer(() => {
if (!session.host) closeSession(session, 'host-gone');
}, HOST_GRACE_MS);
session.hostTimer?.unref?.();
}
/** Create a session for the desktop; older sessions beyond the cap close. */
function createSession() {
while (sessions.size >= MAX_SESSIONS)
closeSession(sessions.values().next().value, 'replaced');
const session = {
id: crypto.randomUUID(),
hostKey: randomKey(),
code: pairingCode(),
phoneKey: null,
failures: 0,
host: null,
phone: null,
hostRate: bucket(),
phoneRate: bucket(),
frame: null,
frameSeq: 0,
frameWaiters: [],
createdAt: now(),
};
sessions.set(session.id, session);
scheduleHostExpiry(session);
return session;
}
const sessionForHost = (hostKey) =>
[...sessions.values()].find((s) => sameSecret(s.hostKey, hostKey)) || null;
const sessionForPhone = (phoneKey) =>
(phoneKey &&
[...sessions.values()].find(
(s) => s.phoneKey && sameSecret(s.phoneKey, phoneKey),
)) ||
null;
/**
* Exchange a pairing code for a phone key. A new join replaces the previous
* phone. Wrong codes count against every session; enough of them rotate
* the codes and tell the desktop to show the new one.
*
* @returns {{ ok: true, phoneKey: string, sessionId: string } | { ok: false, reason: string }}
*/
function joinPhone(code) {
const wanted = normalizeCode(code);
const session =
wanted.length === PAIRING_CODE_LENGTH
? [...sessions.values()].find((s) => sameSecret(s.code, wanted))
: null;
if (!session) {
for (const candidate of sessions.values()) {
candidate.failures += 1;
if (candidate.failures >= MAX_CODE_FAILURES) {
candidate.failures = 0;
candidate.code = pairingCode();
notify(candidate.host, { type: 'code', code: candidate.code });
}
}
return { ok: false, reason: 'invalid-code' };
}
session.failures = 0;
session.phoneKey = randomKey();
if (session.phone) {
const previous = session.phone;
session.phone = null;
try {
previous.close(4001, 'replaced');
} catch {
// Already closed.
}
}
return { ok: true, phoneKey: session.phoneKey, sessionId: session.id };
}
/** Attach a desktop transport; returns the session or null for a bad key. */
function attachHost(hostKey, peer) {
const session = sessionForHost(hostKey);
if (!session) return null;
const previous = session.host;
session.host = peer;
clearTimer(session.hostTimer);
if (previous && previous !== peer) {
try {
previous.close(4001, 'replaced');
} catch {
// Already closed.
}
}
notify(peer, { type: 'code', code: session.code });
notify(peer, { type: 'peer', role: 'phone', connected: !!session.phone });
return session;
}
/** Attach a phone transport; returns the session or null for a bad key. */
function attachPhone(phoneKey, peer) {
const session = sessionForPhone(phoneKey);
if (!session) return null;
const previous = session.phone;
session.phone = peer;
if (previous && previous !== peer) {
try {
previous.close(4001, 'replaced');
} catch {
// Already closed.
}
}
notify(session.host, { type: 'peer', role: 'phone', connected: true });
notify(peer, { type: 'peer', role: 'host', connected: !!session.host });
return session;
}
/** Detach a transport if it is still the session's current one. */
function detach(session, role, peer) {
if (!session || session[role] !== peer) return;
session[role] = null;
const other = role === 'host' ? session.phone : session.host;
notify(other, { type: 'peer', role, connected: false });
if (role === 'host') scheduleHostExpiry(session);
}
/**
* Forward one text message to the other peer. Refuses oversize, non-JSON
* and over-rate input; the caller may close a peer that keeps sending it.
*
* @returns {boolean} Whether the message was admitted.
*/
function relay(session, role, text) {
if (!session || !sessions.has(session.id)) return false;
if (typeof text !== 'string' || Buffer.byteLength(text) > MAX_TEXT_BYTES)
return false;
if (!admit(role === 'host' ? session.hostRate : session.phoneRate))
return false;
try {
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
return false;
} catch {
return false;
}
const target = role === 'host' ? session.phone : session.host;
if (target) {
try {
target.send(text);
} catch {
// The target transport owns its own close handling.
}
}
return true;
}
/** Hold the host's newest JPEG preview frame and wake waiting phones. */
function publishFrame(session, bytes) {
if (!session || !sessions.has(session.id)) return false;
if (!Buffer.isBuffer(bytes) || !bytes.length) return false;
if (bytes.length > MAX_FRAME_BYTES) return false;
// JPEG start-of-image marker: the phone page only ever shows JPEG.
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return false;
session.frame = bytes;
session.frameSeq += 1;
for (const waiter of session.frameWaiters.splice(0)) waiter(session);
return true;
}
/**
* Resolve with the newest frame after `afterSeq`, waiting up to `waitMs`.
* @returns {Promise<{ seq: number, bytes: Buffer } | null>}
*/
function nextFrame(session, afterSeq, waitMs = 2000) {
const current = () =>
session.frame && session.frameSeq > afterSeq
? { seq: session.frameSeq, bytes: session.frame }
: null;
const ready = current();
if (ready || waitMs <= 0) return Promise.resolve(ready);
return new Promise((resolve) => {
let timer = null;
const waiter = (live) => {
clearTimer(timer);
resolve(live ? current() : null);
};
session.frameWaiters.push(waiter);
timer = setTimer(() => {
const index = session.frameWaiters.indexOf(waiter);
if (index >= 0) session.frameWaiters.splice(index, 1);
resolve(current());
}, waitMs);
});
}
return {
createSession,
joinPhone,
attachHost,
attachPhone,
detach,
relay,
publishFrame,
nextFrame,
sessionForHost,
sessionForPhone,
closeSession,
endSession(hostKey) {
const session = sessionForHost(hostKey);
if (session) closeSession(session, 'ended');
return !!session;
},
get size() {
return sessions.size;
},
closeAll() {
for (const session of [...sessions.values()])
closeSession(session, 'shutdown');
},
};
}
+166
View File
@@ -0,0 +1,166 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
MAX_FRAME_BYTES,
MAX_TEXT_BYTES,
PAIRING_CODE_LENGTH,
createVcamRelay,
} from './relay.js';
function peer() {
const sent = [];
const closed = [];
return {
sent,
closed,
messages: () => sent.map((text) => JSON.parse(text)),
send: (text) => sent.push(text),
close: (code, reason) => closed.push([code, reason]),
};
}
function clock() {
let at = 0;
const timers = new Set();
return {
now: () => at,
advance(ms) {
at += ms;
for (const timer of [...timers])
if (timer.due <= at) {
timers.delete(timer);
timer.fn();
}
},
setTimer: (fn, ms) => {
const timer = { fn, due: at + ms };
timers.add(timer);
return timer;
},
clearTimer: (timer) => timers.delete(timer),
};
}
test('a phone pairs with the displayed code and relays both ways', () => {
const relay = createVcamRelay();
const session = relay.createSession();
assert.equal(session.code.length, PAIRING_CODE_LENGTH);
assert.match(session.code, /^[2-9A-HJKMNP-Z]+$/, 'no ambiguous characters');
const host = peer();
assert.equal(relay.attachHost(session.hostKey, host), session);
assert.deepEqual(host.messages(), [
{ type: 'code', code: session.code },
{ type: 'peer', role: 'phone', connected: false },
]);
const joined = relay.joinPhone(` ${session.code.toLowerCase().slice(0, 3)}-${session.code.slice(3)} `);
assert.equal(joined.ok, true, 'codes are case- and separator-insensitive');
const phone = peer();
assert.equal(relay.attachPhone(joined.phoneKey, phone), session);
assert.deepEqual(host.messages().at(-1), { type: 'peer', role: 'phone', connected: true });
assert.ok(relay.relay(session, 'phone', '{"type":"pose","q":[0,0,0,1]}'));
assert.equal(host.sent.at(-1), '{"type":"pose","q":[0,0,0,1]}');
assert.ok(relay.relay(session, 'host', '{"type":"state"}'));
assert.equal(phone.sent.at(-1), '{"type":"state"}');
relay.detach(session, 'phone', phone);
assert.deepEqual(host.messages().at(-1), { type: 'peer', role: 'phone', connected: false });
});
test('keys are per role and a new phone join replaces the previous phone', () => {
const relay = createVcamRelay();
const session = relay.createSession();
assert.equal(relay.attachPhone(session.hostKey, peer()), null);
assert.equal(relay.attachHost('nope', peer()), null);
const first = relay.joinPhone(session.code);
const phone = peer();
relay.attachPhone(first.phoneKey, phone);
const second = relay.joinPhone(session.code);
assert.notEqual(first.phoneKey, second.phoneKey);
assert.deepEqual(phone.closed, [[4001, 'replaced']]);
assert.equal(relay.sessionForPhone(first.phoneKey), null, 'the old key is revoked');
});
test('wrong codes rotate the pairing code and tell the desktop', () => {
const relay = createVcamRelay();
const session = relay.createSession();
const host = peer();
relay.attachHost(session.hostKey, host);
const original = session.code;
for (let i = 0; i < 7; i++) assert.equal(relay.joinPhone('ZZZZZZ').ok, false);
assert.equal(session.code, original);
relay.joinPhone('ZZZZZZ');
assert.notEqual(session.code, original);
assert.deepEqual(host.messages().at(-1), { type: 'code', code: session.code });
assert.equal(relay.joinPhone(original).ok, false, 'the old code no longer pairs');
assert.equal(relay.joinPhone(session.code).ok, true);
});
test('oversize, non-object and over-rate messages are refused', () => {
const time = clock();
const relay = createVcamRelay(time);
const session = relay.createSession();
const host = peer();
relay.attachHost(session.hostKey, host);
const big = JSON.stringify({ type: 'x', pad: 'a'.repeat(MAX_TEXT_BYTES) });
assert.equal(relay.relay(session, 'phone', big), false);
assert.equal(relay.relay(session, 'phone', 'not json'), false);
assert.equal(relay.relay(session, 'phone', '[1,2]'), false);
let admitted = 0;
for (let i = 0; i < 400; i++) if (relay.relay(session, 'phone', '{}')) admitted++;
// The two malformed messages above already spent their tokens.
assert.equal(admitted, 238, 'a burst is capped, malformed input included');
time.advance(500);
assert.equal(relay.relay(session, 'phone', '{}'), true, 'tokens refill over time');
});
test('the newest preview frame is pulled, not queued', async () => {
const relay = createVcamRelay();
const session = relay.createSession();
const jpeg = (n) => Buffer.from([0xff, 0xd8, n]);
assert.equal(relay.publishFrame(session, Buffer.from('GIF89a')), false, 'only JPEG');
assert.equal(relay.publishFrame(session, Buffer.alloc(MAX_FRAME_BYTES + 1, 0xff)), false);
assert.equal(await relay.nextFrame(session, 0, 0), null);
const waiting = relay.nextFrame(session, 0, 5000);
relay.publishFrame(session, jpeg(1));
relay.publishFrame(session, jpeg(2));
const first = await waiting;
assert.equal(first.seq, 1);
const latest = await relay.nextFrame(session, first.seq, 0);
assert.equal(latest.seq, 2, 'a slow phone skips straight to the newest frame');
assert.equal(latest.bytes[2], 2);
relay.closeSession(session);
assert.equal(relay.publishFrame(session, jpeg(3)), false);
});
test('a session outlives a desktop reload but not a departed desktop', () => {
const time = clock();
const closed = [];
const relay = createVcamRelay({ ...time, onSessionClosed: (s) => closed.push(s.id) });
const session = relay.createSession();
const host = peer();
relay.attachHost(session.hostKey, host);
const phone = peer();
relay.attachPhone(relay.joinPhone(session.code).phoneKey, phone);
relay.detach(session, 'host', host);
assert.deepEqual(phone.messages().at(-1), { type: 'peer', role: 'host', connected: false });
time.advance(30000);
relay.attachHost(session.hostKey, peer());
time.advance(60000);
assert.equal(relay.size, 1, 'a reattached host keeps the session');
relay.detach(session, 'host', relay.sessionForHost(session.hostKey).host);
time.advance(60001);
assert.equal(relay.size, 0);
assert.deepEqual(closed, [session.id]);
assert.deepEqual(phone.closed, [[4000, 'host-gone']]);
});
test('ending a session closes both peers and only the host key can end it', () => {
const relay = createVcamRelay();
const session = relay.createSession();
const phone = peer();
relay.attachPhone(relay.joinPhone(session.code).phoneKey, phone);
assert.equal(relay.endSession('wrong'), false);
assert.equal(relay.endSession(session.hostKey), true);
assert.deepEqual(phone.closed, [[4000, 'ended']]);
for (let i = 0; i < 6; i++) relay.createSession();
assert.equal(relay.size, 4, 'sessions are capped');
});
+237
View File
@@ -0,0 +1,237 @@
/**
* Local certificate authority for the virtual-camera phone listener.
*
* Phones only expose camera tracking (WebXR, DeviceOrientation) to secure
* contexts, so the LAN listener must speak HTTPS. A tapped-through
* self-signed certificate is not enough on iOS: Safari loads the page but
* refuses its WebSocket. Instead this module keeps one long-lived local CA,
* which a phone can install and trust once, and issues the listener a short
* server certificate for this machine's current LAN addresses.
*
* Certificates are encoded here with node:crypto (EC P-256, ECDSA-SHA256), so
* no OpenSSL binary or dependency is needed. Keys never leave the cache
* directory, which is git-ignored and outside the dev server's watcher.
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { isIP } from 'node:net';
const DAY_MS = 86400000;
// Apple rejects user-trusted TLS server certificates valid for over 825 days.
const SERVER_VALIDITY_DAYS = 397;
const CA_VALIDITY_DAYS = 3650;
// Reissue the server certificate this long before it expires.
const RENEW_MARGIN_DAYS = 30;
const length = (n) =>
n < 0x80
? Buffer.from([n])
: n < 0x100
? Buffer.from([0x81, n])
: Buffer.from([0x82, n >> 8, n & 0xff]);
const tlv = (tag, ...parts) => {
const body = Buffer.concat(parts);
return Buffer.concat([Buffer.from([tag]), length(body.length), body]);
};
const sequence = (...parts) => tlv(0x30, ...parts);
const set = (...parts) => tlv(0x31, ...parts);
const explicit = (n, ...parts) => tlv(0xa0 + n, ...parts);
const octets = (buffer) => tlv(0x04, buffer);
const bits = (buffer, unused = 0) => tlv(0x03, Buffer.from([unused]), buffer);
const boolean = (value) => tlv(0x01, Buffer.from([value ? 0xff : 0]));
const utf8 = (text) => tlv(0x0c, Buffer.from(text, 'utf8'));
function integer(buffer) {
let bytes = Buffer.from(buffer);
while (bytes.length > 1 && bytes[0] === 0 && !(bytes[1] & 0x80))
bytes = bytes.subarray(1);
if (bytes[0] & 0x80) bytes = Buffer.concat([Buffer.from([0]), bytes]);
return tlv(0x02, bytes);
}
function oid(dotted) {
const [first, second, ...rest] = dotted.split('.').map(Number);
const bytes = [40 * first + second];
for (const part of rest) {
const group = [part & 0x7f];
for (let v = part >>> 7; v; v >>>= 7) group.unshift((v & 0x7f) | 0x80);
bytes.push(...group);
}
return tlv(0x06, Buffer.from(bytes));
}
function time(date) {
const iso = date.toISOString().replace(/[-:T]/g, '').slice(0, 14);
// RFC 5280: UTCTime through 2049, GeneralizedTime from 2050.
return date.getUTCFullYear() < 2050
? tlv(0x17, Buffer.from(`${iso.slice(2)}Z`))
: tlv(0x18, Buffer.from(`${iso}Z`));
}
const name = (commonName) =>
sequence(
set(sequence(oid('2.5.4.10'), utf8("God's Eye View"))),
set(sequence(oid('2.5.4.3'), utf8(commonName))),
);
const extension = (id, critical, value) =>
sequence(oid(id), ...(critical ? [boolean(true)] : []), octets(value));
const ECDSA_SHA256 = sequence(oid('1.2.840.10045.4.3.2'));
const spkiOf = (publicKey) => publicKey.export({ type: 'spki', format: 'der' });
// RFC 5280 method 1: SHA-1 of the subjectPublicKey bit string's contents.
const keyIdentifier = (spki) =>
crypto.createHash('sha1').update(spki.subarray(-65)).digest();
function subjectAltNames(names) {
return sequence(
...names.map((entry) =>
isIP(entry) === 4
? tlv(0x87, Buffer.from(entry.split('.').map(Number)))
: tlv(0x82, Buffer.from(entry, 'ascii')),
),
);
}
function sign({ subject, issuer, publicKey, signingKey, days, extensions }) {
const now = Date.now();
const tbs = sequence(
explicit(0, integer(Buffer.from([2]))),
integer(crypto.randomBytes(16)),
ECDSA_SHA256,
issuer,
sequence(time(new Date(now - DAY_MS)), time(new Date(now + days * DAY_MS))),
subject,
spkiOf(publicKey),
explicit(3, sequence(...extensions)),
);
const signature = crypto.sign('sha256', tbs, signingKey);
return sequence(tbs, ECDSA_SHA256, bits(signature));
}
const pem = (label, der) =>
`-----BEGIN ${label}-----\n${der
.toString('base64')
.match(/.{1,64}/g)
.join('\n')}\n-----END ${label}-----\n`;
const keyPem = (key) => key.export({ type: 'pkcs8', format: 'pem' });
const CA_COMMON_NAME = "God's Eye View Local VCam CA";
/** Create a CA that may only sign server certificates (path length 0). */
export function createCertificateAuthority(commonName = CA_COMMON_NAME) {
const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'P-256',
});
const subject = name(commonName);
const der = sign({
subject,
issuer: subject,
publicKey,
signingKey: privateKey,
days: CA_VALIDITY_DAYS,
extensions: [
extension(
'2.5.29.19',
true,
sequence(boolean(true), integer(Buffer.from([0]))),
),
// keyCertSign and cRLSign.
extension('2.5.29.15', true, bits(Buffer.from([0x06]), 1)),
extension('2.5.29.14', false, octets(keyIdentifier(spkiOf(publicKey)))),
],
});
return { cert: pem('CERTIFICATE', der), key: keyPem(privateKey) };
}
/** Issue a TLS server certificate for the given IP addresses and DNS names. */
export function issueServerCertificate(authority, names) {
const caKey = crypto.createPrivateKey(authority.key);
const caCert = new crypto.X509Certificate(authority.cert);
const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'P-256',
});
const caSpki = spkiOf(caCert.publicKey);
const der = sign({
subject: name(names[0]),
issuer: name(caCert.subject.match(/CN=([^\n]+)/)?.[1] ?? CA_COMMON_NAME),
publicKey,
signingKey: caKey,
days: SERVER_VALIDITY_DAYS,
extensions: [
extension('2.5.29.19', true, sequence()),
// digitalSignature.
extension('2.5.29.15', true, bits(Buffer.from([0x80]), 7)),
extension('2.5.29.37', false, sequence(oid('1.3.6.1.5.5.7.3.1'))),
extension('2.5.29.17', false, subjectAltNames(names)),
extension('2.5.29.35', false, sequence(tlv(0x80, keyIdentifier(caSpki)))),
],
});
return { cert: pem('CERTIFICATE', der), key: keyPem(privateKey) };
}
function readPair(directory, base) {
try {
return {
cert: fs.readFileSync(path.join(directory, `${base}.crt`), 'utf8'),
key: fs.readFileSync(path.join(directory, `${base}.key`), 'utf8'),
};
} catch {
return null;
}
}
function writePair(directory, base, pair) {
fs.writeFileSync(path.join(directory, `${base}.key`), pair.key, {
mode: 0o600,
});
fs.writeFileSync(path.join(directory, `${base}.crt`), pair.cert);
}
function serverCertificateCovers(pair, authority, names) {
try {
const cert = new crypto.X509Certificate(pair.cert);
if (!cert.verify(new crypto.X509Certificate(authority.cert).publicKey))
return false;
if (Date.parse(cert.validTo) - Date.now() < RENEW_MARGIN_DAYS * DAY_MS)
return false;
const listed = new Set(
String(cert.subjectAltName || '')
.split(',')
.map((entry) => entry.trim().replace(/^(DNS|IP Address):/, '')),
);
return names.every((entry) => listed.has(entry));
} catch {
return false;
}
}
/**
* Load or create the cached CA and a server certificate covering `names`.
* The CA survives restarts so a phone's one-time trust keeps working; the
* server certificate is reissued when an address changes or it nears expiry.
*
* @param {string} directory - Cache directory, created with owner-only access.
* @param {string[]} names - IPv4 addresses and DNS names; the first is the subject.
* @returns {{ ca: string, cert: string, key: string, caFingerprint: string }}
*/
export function loadLocalCertificates(directory, names) {
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
let authority = readPair(directory, 'ca');
try {
if (authority && !new crypto.X509Certificate(authority.cert).ca)
authority = null;
} catch {
authority = null;
}
if (!authority) {
authority = createCertificateAuthority();
writePair(directory, 'ca', authority);
}
let server = readPair(directory, 'server');
if (!server || !serverCertificateCovers(server, authority, names)) {
server = issueServerCertificate(authority, names);
writePair(directory, 'server', server);
}
return {
ca: authority.cert,
cert: server.cert,
key: server.key,
caFingerprint: new crypto.X509Certificate(authority.cert).fingerprint256,
};
}
-170
View File
@@ -1,170 +0,0 @@
import * as Cesium from 'cesium';
import {
feedProvenanceEnvelope,
layerSnapshot,
layerSnapshots,
} from '../data/layerSnapshot.js';
import { contextModeWord } from '../contextModePolicy.js';
export const TRACKABLE_FAMILIES = Object.freeze([
{ layerId: 'flights', kind: 'aircraft' },
{ layerId: 'military', kind: 'aircraft' },
{ layerId: 'ais-live-vessels', kind: 'vessel' },
{ layerId: 'satellites', kind: 'satellite' },
]);
const CONTEXT_MODE_RESULT_FIELDS = Object.freeze([
{ field: 'mode', emptyAs: 'off' },
{ field: 'entering', emptyAs: null },
{ field: 'priorMode', emptyAs: null },
]);
const NESTED_CONTEXT_RESULT_FIELDS = Object.freeze([
'context',
'contextRollback',
]);
/**
* Translate context-mode payloads into the public tool vocabulary while
* retaining the internal id beside each translated field.
*/
export function withContextModeVocabulary(state) {
if (!state || typeof state !== 'object') return state;
let out = state;
const mutable = () => {
if (out === state) out = { ...state };
return out;
};
for (const { field, emptyAs } of CONTEXT_MODE_RESULT_FIELDS) {
if (!(field in state)) continue;
const internal = state[field] ?? null;
const target = mutable();
target[field] = contextModeWord(internal, { emptyAs });
target[`${field}Internal`] = internal;
}
for (const field of NESTED_CONTEXT_RESULT_FIELDS) {
const nested = state[field];
if (!nested || typeof nested !== 'object') continue;
const translated = withContextModeVocabulary(nested);
if (translated !== nested) mutable()[field] = translated;
}
return out;
}
/** Read tracked entities from their canonical layer owners. */
export function collectTrackedEntities(dataManager) {
const tracked = [];
for (const family of TRACKABLE_FAMILIES) {
const module = dataManager?.layers?.get(family.layerId)?.module;
if (!module) continue;
try {
const info =
family.kind === 'vessel'
? module.getSelectedInfo?.()
: module.getTrackedInfo?.();
if (info)
tracked.push({
kind: family.kind,
layerId: family.layerId,
...info,
});
} catch {
// A not-yet-ready layer contributes no tracked observation.
}
}
return tracked;
}
/** Read the active Contacts window from its owning awareness layer. */
export function activeContactsWindow(dataManager) {
try {
const layer = dataManager?.layers?.get('military-awareness')?.module;
return (
layer?.contactsWindowFromSnapshot?.(layer.getContextSnapshot?.()) ?? null
);
} catch {
return null;
}
}
/**
* Build the model-free fast World Packet from existing application owners.
*
* This performs no network requests and intentionally mirrors the historical
* get_current_view_state payload so voice can delegate without behavior drift.
*/
export function getWorldPacket(options = {}) {
const {
viewer,
styleManager,
dataManager,
sceneDirector = null,
now: requestedNow,
} = options ?? {};
// A default parameter only covers undefined; null or NaN would age every
// feed against the epoch and report stale data as "just now".
const now = Number.isFinite(requestedNow) ? requestedNow : Date.now();
if (!viewer?.camera?.positionWC)
throw new TypeError('World Packet requires a viewer camera');
if (!dataManager || typeof dataManager.getAll !== 'function')
throw new TypeError('World Packet requires a data manager');
const cartographic = Cesium.Cartographic.fromCartesian(
viewer.camera.positionWC,
);
// Read the roster once. Voice must not rewalk disabled layers: preserving the
// current enabled-only view keeps the model's context budget bounded.
const rows = dataManager.getAll();
const enabledRows = rows.filter((layer) => layer.enabled);
const contactsWindow = activeContactsWindow(dataManager);
const contextState =
typeof styleManager?.getContextModeState === 'function'
? withContextModeVocabulary(styleManager.getContextModeState())
: null;
return {
ok: true,
action: 'get_current_view_state',
camera: {
latitude: Cesium.Math.toDegrees(cartographic.latitude),
longitude: Cesium.Math.toDegrees(cartographic.longitude),
heightM: cartographic.height,
},
style: styleManager?.activeStyle || 'normal',
context: contextState
? {
...contextState,
...(contactsWindow ? { contactsWindow } : {}),
}
: null,
cockpit:
typeof styleManager?.getCockpitState === 'function'
? styleManager.getCockpitState()
: null,
controls:
typeof styleManager?.getControlState === 'function'
? styleManager.getControlState()
: null,
scenePlayback: sceneDirector?.getPlaybackStatus?.() || null,
tracked: collectTrackedEntities(dataManager),
disabledLayerCount: rows.length - enabledRows.length,
// Preserve get_current_view_state's existing compact enabled-only shape.
layers: enabledRows.map((layer) => {
const snapshot = layerSnapshot(layer, { now });
return {
id: layer.id,
name: layer.name,
enabled: layer.enabled,
count: layer.stats?.count || 0,
error: layer.stats?.error || null,
feedState: snapshot.feedState,
source: snapshot.source,
lastUpdate: snapshot.lastUpdate,
};
}),
feedProvenance: feedProvenanceEnvelope(
layerSnapshots(rows, { now }).filter((layer) => layer.enabled),
{ now },
),
};
}
-335
View File
@@ -1,335 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { getWorldPacket } from './worldPacket.js';
import { createGevActionRunner } from '../voice/gevActions.js';
function withoutVoicePresentation(result) {
const packet = { ...result };
delete packet.say;
delete packet.display;
delete packet.schedule;
return packet;
}
function harness() {
const position = Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 500);
const viewer = {
trackedEntity: undefined,
clock: { onTick: { addEventListener: () => () => {} } },
scene: {
canvas: {
clientWidth: 1200,
clientHeight: 800,
addEventListener() {},
removeEventListener() {},
},
globe: { getHeight: () => 0 },
tweens: [],
},
camera: {
positionWC: position,
positionCartographic: Cesium.Cartographic.fromCartesian(position),
heading: 0,
pitch: Cesium.Math.toRadians(-45),
moveEnd: { addEventListener: () => () => {} },
cancelFlight() {},
lookAtTransform() {},
},
};
const rows = [
{
id: 'traffic',
name: 'Traffic',
enabled: true,
stats: {
count: 3,
source: 'fixture',
lastUpdate: null,
},
},
];
const dataManager = {
layers: new Map([['traffic', { module: null }]]),
getAll: () => rows,
};
const styleManager = {
activeStyle: 'normal',
getContextModeState: () => ({ mode: 'flights' }),
getCockpitState: () => null,
getControlState: () => ({ hud: { visible: 'auto' } }),
};
return { viewer, dataManager, styleManager };
}
test('World Packet preserves get_current_view_state parity', async () => {
const { viewer, dataManager, styleManager } = harness();
const packet = getWorldPacket({ viewer, dataManager, styleManager });
const runner = createGevActionRunner({ viewer, dataManager, styleManager });
const voice = await runner('get_current_view_state');
assert.deepEqual(withoutVoicePresentation(voice), packet);
assert.equal(packet.context.mode, 'contacts');
assert.equal(packet.context.modeInternal, 'flights');
assert.equal(packet.layers[0].feedState, 'nominal');
assert.equal(packet.feedProvenance.overall, 'nominal');
});
test('World Packet keeps stale/unavailable feed semantics distinct from empty', () => {
const { viewer, dataManager, styleManager } = harness();
dataManager.getAll = () => [
{
id: 'traffic',
name: 'Traffic',
enabled: true,
stats: {
count: 0,
source: 'fixture',
error: 'fixture unavailable',
lastUpdate: null,
},
},
];
const packet = getWorldPacket({ viewer, dataManager, styleManager });
assert.equal(packet.layers[0].count, 0);
assert.notEqual(packet.layers[0].feedState, 'nominal');
assert.notEqual(packet.feedProvenance.overall, 'nominal');
assert.match(packet.feedProvenance.note, /fixture unavailable/i);
});
// The 2026-10 main voice contract omits disabled layers from the model payload.
test('World Packet and voice preserve enabled-only payload and count disabled layers', async () => {
const { viewer, dataManager, styleManager } = harness();
const rows = dataManager.getAll();
rows.push({
id: 'earthquakes',
name: 'Earthquakes',
enabled: false,
stats: { count: 99, source: 'fixture', error: 'stale' },
});
let reads = 0;
dataManager.getAll = () => {
reads += 1;
return rows;
};
const packet = getWorldPacket({ viewer, dataManager, styleManager });
assert.equal(reads, 1, 'collect the roster once rather than repeatedly');
assert.equal(packet.disabledLayerCount, 1);
assert.deepEqual(
packet.layers.map((layer) => layer.id),
['traffic'],
);
assert.equal(packet.feedProvenance.overall, 'nominal');
const runner = createGevActionRunner({ viewer, dataManager, styleManager });
const voice = await runner('get_current_view_state');
assert.deepEqual(withoutVoicePresentation(voice), packet);
});
const PINNED_NOW = Date.UTC(2026, 9, 17, 12, 0, 0);
// Exercises every packet field: context vocabulary and Contacts window,
// cockpit, controls, scene playback, tracked families (one not ready),
// enabled and disabled layers, and an aged and an unavailable feed.
function pinnedHarness() {
const { viewer } = harness();
const rows = [
{
id: 'flights',
name: 'Flights',
enabled: true,
stats: {
count: 12,
source: 'fixture-adsb',
lastUpdate: PINNED_NOW - 90_000,
},
},
{
id: 'traffic',
name: 'Traffic',
enabled: true,
stats: {
count: 0,
source: 'fixture',
error: 'fixture unavailable',
lastUpdate: null,
},
},
{
id: 'earthquakes',
name: 'Earthquakes',
enabled: false,
stats: { count: 99, source: 'fixture', error: 'stale' },
},
];
const module = (methods) => ({ module: methods });
const dataManager = {
layers: new Map([
[
'flights',
module({
getTrackedInfo: () => ({ icao24: 'abc123', callsign: 'TEST1' }),
}),
],
[
'ais-live-vessels',
module({ getSelectedInfo: () => ({ mmsi: '366000001' }) }),
],
[
'satellites',
module({
getTrackedInfo: () => {
throw new Error('not ready');
},
}),
],
[
'military-awareness',
module({
getContextSnapshot: () => ({ snapshot: true }),
contactsWindowFromSnapshot: (snapshot) =>
snapshot ? { windowMin: 30, count: 4 } : null,
}),
],
]),
getAll: () => rows,
};
const styleManager = {
activeStyle: 'night-vision',
getContextModeState: () => ({
mode: 'flights',
entering: null,
priorMode: null,
}),
getCockpitState: () => ({ active: false }),
getControlState: () => ({ hud: { visible: 'auto' } }),
};
const sceneDirector = {
getPlaybackStatus: () => ({ playing: false, sceneId: 'fixture' }),
};
return { viewer, dataManager, styleManager, sceneDirector };
}
// Captured from main's get_current_view_state before the extraction
// (bilawalsidhu/gods-eye-view@3d8e1ef0) with Date.now pinned to PINNED_NOW,
// minus the speech envelope. Key order is part of the contract.
const PRE_EXTRACTION_PAYLOAD = {
ok: true,
action: 'get_current_view_state',
camera: {
latitude: 30.259999999999994,
longitude: -97.74,
heightM: 499.99999999901877,
},
style: 'night-vision',
context: {
mode: 'contacts',
entering: null,
priorMode: null,
modeInternal: 'flights',
enteringInternal: null,
priorModeInternal: null,
contactsWindow: { windowMin: 30, count: 4 },
},
cockpit: { active: false },
controls: { hud: { visible: 'auto' } },
scenePlayback: { playing: false, sceneId: 'fixture' },
tracked: [
{
kind: 'aircraft',
layerId: 'flights',
icao24: 'abc123',
callsign: 'TEST1',
},
{ kind: 'vessel', layerId: 'ais-live-vessels', mmsi: '366000001' },
],
disabledLayerCount: 1,
layers: [
{
id: 'flights',
name: 'Flights',
enabled: true,
count: 12,
error: null,
feedState: 'nominal',
source: 'fixture-adsb',
lastUpdate: 1792238310000,
},
{
id: 'traffic',
name: 'Traffic',
enabled: true,
count: 0,
error: 'fixture unavailable',
feedState: 'unavailable',
source: 'fixture',
lastUpdate: 0,
},
],
feedProvenance: {
overall: 'unavailable',
layers: [
{
id: 'flights',
name: 'Flights',
enabled: true,
feedState: 'nominal',
source: 'fixture-adsb',
count: 12,
lastUpdate: 1792238310000,
ageSec: 90,
ageLabel: '1m ago',
error: null,
},
{
id: 'traffic',
name: 'Traffic',
enabled: true,
feedState: 'unavailable',
source: 'fixture',
count: 0,
lastUpdate: 0,
ageSec: null,
ageLabel: null,
error: 'fixture unavailable',
},
],
note: 'Traffic is UNAVAILABLE (fixture, fixture unavailable). Narrate that provenance with any count; do not describe this as live.',
},
};
function assertPinnedPayload(actual) {
assert.deepEqual(actual, PRE_EXTRACTION_PAYLOAD);
// deepEqual ignores key order; the serialized form does not.
assert.equal(JSON.stringify(actual), JSON.stringify(PRE_EXTRACTION_PAYLOAD));
}
test('World Packet matches the pre-extraction get_current_view_state payload', () => {
const packet = getWorldPacket({ ...pinnedHarness(), now: PINNED_NOW });
assertPinnedPayload(packet);
});
test('voice get_current_view_state still returns the pre-extraction payload', async (t) => {
t.mock.method(Date, 'now', () => PINNED_NOW);
const runner = createGevActionRunner(pinnedHarness());
const voice = await runner('get_current_view_state');
assertPinnedPayload(withoutVoicePresentation(voice));
});
test('World Packet ages feeds against the clock when now is not a finite number', (t) => {
t.mock.method(Date, 'now', () => PINNED_NOW);
for (const now of [null, Number.NaN, '2026-10-17']) {
const packet = getWorldPacket({ ...pinnedHarness(), now });
const flights = packet.feedProvenance.layers.find(
(layer) => layer.id === 'flights',
);
assert.equal(flights.ageSec, 90, `now: ${String(now)}`);
assert.equal(flights.ageLabel, '1m ago', `now: ${String(now)}`);
}
});
test('World Packet rejects null options with the camera requirement', () => {
assert.throws(() => getWorldPacket(null), /requires a viewer camera/);
});
-87
View File
@@ -120,93 +120,6 @@ test('Georgia resolves from camera geography without a geocoder', async () => {
assert.deepEqual(geocodes, []); assert.deepEqual(geocodes, []);
}); });
test('Gold Coast in Australia cannot acquire its West African namesake outline', async () => {
for (const types of [['locality', 'political'], ['natural_feature']]) {
const { resolve, geocodes } = harness({
lat: -28.0167,
lng: 153.4,
label: 'Gold Coast, Australia',
name: 'Gold Coast',
types,
});
const resolved = await resolve('Gold Coast', viewerAt(-28.0167, 153.4));
assert.equal(resolved?.source, 'geocode');
assert.equal(resolved.lat, -28.0167);
assert.equal(resolved.lon, 153.4);
assert.equal(resolved.naturalRegion, undefined);
const outline = await resolved.resolveOutline();
assert.equal(outline?.naturalRegion, undefined);
assert.deepEqual(geocodes, ['Gold Coast']);
}
});
test('natural annotation outlines require a geocoded anchor', async () => {
for (const viewer of [AUSTIN, {}, viewerAt(46.5, 10, 248_000)]) {
const miss = harness();
assert.equal(await miss.resolve('the Alps', viewer), null);
assert.ok(miss.geocodes.includes('the Alps'));
}
const anchored = harness({
lat: 46.5,
lng: 10,
label: 'Alps',
name: 'Alps',
types: ['natural_feature'],
});
const resolved = await anchored.resolve('the Alps', {});
assert.equal(resolved.source, 'geocode');
const outline = await resolved.resolveOutline();
assert.equal(outline.naturalRegion, 'Alps');
assert.ok(outline.ring.length >= 8);
});
test('overlapping natural candidates continue through geocoding without choosing a ring', async () => {
const { resolve, geocodes } = harness({
lat: 45.6336,
lng: -74.86493,
label: 'Canadian Shield',
name: 'Canadian Shield',
types: ['natural_feature'],
});
const resolved = await resolve(
'Canadian Shield',
viewerAt(45.6336, -74.86493),
);
assert.equal(resolved?.source, 'geocode');
assert.equal((await resolved.resolveOutline())?.naturalRegion, undefined);
assert.deepEqual(geocodes, ['Canadian Shield']);
});
test('geocoded natural outlines respect district and around intent', async () => {
for (const extra of [
{ entityKind: 'district' },
{ intent: 'around_the_thing' },
]) {
const { resolve, geocodes } = harness({
lat: 46.5,
lng: 10,
label: 'Alps',
name: 'Alps',
types:
extra.entityKind === 'district' ? ['locality'] : ['natural_feature'],
});
const resolved = await resolve('the Alps', viewerAt(46.5, 10), extra);
assert.ok(geocodes.includes('the Alps'));
assert.equal((await resolved.resolveOutline())?.naturalRegion, undefined);
}
});
test('cancellation while a bundled admin lookup is pending cannot publish an annotation', async () => {
const controller = new AbortController();
const { resolve, geocodes } = harness();
const pending = resolve('the Alps', viewerAt(46.5, 10), {
signal: controller.signal,
});
controller.abort();
await assert.rejects(pending, { name: 'AbortError' });
assert.deepEqual(geocodes, []);
});
test('country asks and geocoded country scopes use the bundled outline', async () => { test('country asks and geocoded country scopes use the bundled outline', async () => {
const direct = harness(); const direct = harness();
for (const name of ['Switzerland', 'Iran', 'France', 'Japan']) { for (const name of ['Switzerland', 'Iran', 'France', 'Japan']) {
+10 -10
View File
@@ -30,7 +30,6 @@
* at finish, deliberately and in one place — see `finishSpec` in drawMode.js. * at finish, deliberately and in one place — see `finishSpec` in drawMode.js.
*/ */
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createSegmentedControl } from '../ui/segmentedControl.js';
import { pickWorldFromScreen } from './annotationResolver.js'; import { pickWorldFromScreen } from './annotationResolver.js';
import { import {
claimPointer, claimPointer,
@@ -433,21 +432,22 @@ export function initDrawTool({ viewer, annotations }) {
const shapeButtons = [ const shapeButtons = [
...(modeRow?.querySelectorAll('.pp-mode-btn[data-shape]') || []), ...(modeRow?.querySelectorAll('.pp-mode-btn[data-shape]') || []),
]; ];
const shapeControl = createSegmentedControl({ for (const btn of shapeButtons) {
buttons: shapeButtons, listen(btn, 'click', () => {
valueOf: (button) => button.dataset.shape, shape = normalizeShape(btn.dataset.shape);
listen, for (const other of shapeButtons) {
onChange: (value) => { const on = other === btn;
shape = normalizeShape(value); other.classList.toggle('active', on);
shapeControl.update(shape); other.setAttribute('aria-checked', String(on));
}
if (active) { if (active) {
generation += 1; generation += 1;
session = createDrawSession(shape); session = createDrawSession(shape);
cursor = null; cursor = null;
syncPreview(); syncPreview();
} }
}, });
}); }
listen(colorSelect, 'change', () => { listen(colorSelect, 'change', () => {
color = COLORS.includes(colorSelect.value) ? colorSelect.value : 'primary'; color = COLORS.includes(colorSelect.value) ? colorSelect.value : 'primary';
syncPreview(); syncPreview();
-106
View File
@@ -44,115 +44,10 @@ test('region ring: Natural Earth names resolve without a geocoder', async () =>
for (const name of ['Gulf of Mexico', 'the Alps']) { for (const name of ['Gulf of Mexico', 'the Alps']) {
const region = await resolveRegionRingForQuery(name); const region = await resolveRegionRingForQuery(name);
assert.ok(region?.ring?.length >= 3, `${name} resolves to a ring`); assert.ok(region?.ring?.length >= 3, `${name} resolves to a ring`);
assert.equal(region.source, 'natural-earth');
assert.equal(region.error, undefined); assert.equal(region.error, undefined);
} }
}); });
test('region ring: duplicate natural names need a containing geocoded anchor', async () => {
const { resolveRegionRingForQuery } = createAnnotationResolver({
featureSource: featureSource(),
});
const miss = geocoderFor(null);
assert.equal(
await resolveRegionRingForQuery('Cordillera Oriental', undefined, miss),
null,
);
assert.deepEqual(miss.calls, ['Cordillera Oriental']);
const inside = geocoderFor({
lat: 5,
lng: -73,
label: 'Cordillera Oriental',
name: 'Cordillera Oriental',
types: ['natural_feature'],
});
const region = await resolveRegionRingForQuery(
'Cordillera Oriental',
undefined,
inside,
);
assert.equal(region?.source, 'natural-earth');
assert.equal(region.name, 'Cordillera Oriental');
assert.ok(region.ring.length >= 8);
assert.deepEqual(inside.calls, ['Cordillera Oriental']);
});
test('region ring: outside and overlapping geocoded natural anchors stay unresolved', async () => {
const { resolveRegionRingForQuery } = createAnnotationResolver({
featureSource: featureSource(),
});
for (const [name, lat, lng] of [
['Cordillera Oriental', 30.27, -97.74],
['Canadian Shield', 45.6336, -74.86493],
]) {
const geocoder = geocoderFor({
lat,
lng,
label: name,
name,
types: ['natural_feature'],
});
assert.equal(
await resolveRegionRingForQuery(name, undefined, geocoder),
null,
);
assert.deepEqual(geocoder.calls, [name]);
}
});
test('region ring: geocoded administrative scope wins over duplicate natural geography', async () => {
const lookups = [];
const { resolveRegionRingForQuery } = createAnnotationResolver({
featureSource: featureSource({
getAdministrativeAreas: async (point) => {
lookups.push(point);
return [];
},
}),
});
const geo = geocoderFor({
lat: 5,
lng: -73,
label: 'Cordillera Oriental',
name: 'Cordillera Oriental',
types: ['locality'],
});
const resolved = await resolveRegionRingForQuery(
'Cordillera Oriental',
undefined,
geo,
);
assert.equal(
resolved,
null,
'an unavailable city boundary is not a natural-region outline',
);
assert.deepEqual(lookups, [{ lat: 5, lon: -73 }]);
assert.deepEqual(geo.calls, ['Cordillera Oriental']);
});
test('region ring: cancellation during bundled lookup and geocode never returns a region', async () => {
const { resolveRegionRingForQuery } = createAnnotationResolver({
featureSource: featureSource(),
});
const controller = new AbortController();
const pending = resolveRegionRingForQuery('the Alps', controller.signal);
controller.abort();
await assert.rejects(pending, { name: 'AbortError' });
const later = new AbortController();
await assert.rejects(
resolveRegionRingForQuery('Cordillera Oriental', later.signal, {
async geocode() {
later.abort();
return { place: null };
},
}),
{ name: 'AbortError' },
);
});
test('region ring: a slow admin-boundary lookup returns region-timeout within the budget', async () => { test('region ring: a slow admin-boundary lookup returns region-timeout within the budget', async () => {
let adminSignal; let adminSignal;
let release; let release;
@@ -224,7 +119,6 @@ test('region ring: bundled states and counties resolve without a geocoder', asyn
]) { ]) {
const region = await resolveRegionRingForQuery(query, undefined, geocoder); const region = await resolveRegionRingForQuery(query, undefined, geocoder);
assert.equal(region?.name, name, query); assert.equal(region?.name, name, query);
assert.equal(region.source, 'bundled-admin');
assert.ok(region.ring.length >= 8, `${query} has a real ring`); assert.ok(region.ring.length >= 8, `${query} has a real ring`);
} }
assert.deepEqual(geocoder.calls, [], 'no geocoding'); assert.deepEqual(geocoder.calls, [], 'no geocoding');
+8 -40
View File
@@ -444,7 +444,6 @@ export function createAnnotationResolver({
* AFTER the anchor mark is drawn and upgrade the mark in place. * AFTER the anchor mark is drawn and upgrade the mark in place.
*/ */
const resolveOutline = async () => { const resolveOutline = async () => {
signal?.throwIfAborted();
let scope = baseScope; let scope = baseScope;
const isAdmin = const isAdmin =
scope === 'country' || scope === 'country' ||
@@ -470,7 +469,6 @@ export function createAnnotationResolver({
const ne = await lookupNaturalRegionOutline(target, lat, lon).catch( const ne = await lookupNaturalRegionOutline(target, lat, lon).catch(
() => null, () => null,
); );
signal?.throwIfAborted();
if (ne) { if (ne) {
registerDynamicCredit(viewer, NATURAL_EARTH_CREDIT); registerDynamicCredit(viewer, NATURAL_EARTH_CREDIT);
const neCentroid = ringCentroid(ne.ring); const neCentroid = ringCentroid(ne.ring);
@@ -2006,8 +2004,8 @@ export function createAnnotationResolver({
/** /**
* Region ring for ANALYST queries ("how many flights over Texas / the Alps") — * Region ring for ANALYST queries ("how many flights over Texas / the Alps") —
* a name-only entry point that reuses this module's boundary machinery * a name-only entry point that reuses this module's boundary machinery
* without the annotation pipeline. Unique Natural Earth names resolve first * without the annotation pipeline. Natural Earth pack first (offline,
* (offline); duplicate names require a geocoded containment anchor, then * instant; largest-area match is correct for a global name-only ask), then
* geocode + admin boundary for states/countries/counties (Tier A disk-cached * geocode + admin boundary for states/countries/counties (Tier A disk-cached
* Overpass, so repeat asks are instant). Returns null when the name doesn't * Overpass, so repeat asks are instant). Returns null when the name doesn't
* resolve to a region-like boundary — the analyst engine reports that * resolve to a region-like boundary — the analyst engine reports that
@@ -2022,7 +2020,7 @@ export function createAnnotationResolver({
* @param {AbortSignal} [signal] * @param {AbortSignal} [signal]
* @param {object} [placeSearch] * @param {object} [placeSearch]
* @param {{budgetMs?: number}} [options] `Infinity` waits for the lookup. * @param {{budgetMs?: number}} [options] `Infinity` waits for the lookup.
* @returns {Promise<{name:string, ring:Array<[number,number]>, source:string}|{name:string, ring:null, error:'region-timeout'}|null>} * @returns {Promise<{name:string, ring:Array<[number,number]>}|{name:string, ring:null, error:'region-timeout'}|null>}
*/ */
async function resolveRegionRingForQuery( async function resolveRegionRingForQuery(
name, name,
@@ -2039,24 +2037,16 @@ export function createAnnotationResolver({
const q = String(name || '').trim(); const q = String(name || '').trim();
if (!q) return null; if (!q) return null;
const ne = await findNaturalRegion(q).catch(() => null); const ne = await findNaturalRegion(q).catch(() => null);
signal?.throwIfAborted(); if (ne?.polygons?.length) {
if (ne?.candidates === 1 && ne.polygons?.length) {
// Largest ring carries the query scope; multi-ring regions (Andes) keep // Largest ring carries the query scope; multi-ring regions (Andes) keep
// their main cordillera — good enough for containment counting. // their main cordillera — good enough for containment counting.
const ring = [...ne.polygons].sort((a, b) => b.length - a.length)[0]; const ring = [...ne.polygons].sort((a, b) => b.length - a.length)[0];
if (ring?.length >= 3) if (ring?.length >= 3) return { name: ne.name, ring };
return { name: ne.name, ring, source: 'natural-earth' };
} }
// Bundled states/provinces/counties by name (offline); the main part only, // Bundled states/provinces/counties by name (offline); the main part only,
// like the Natural Earth rung above. // like the Natural Earth rung above.
const admin = await findAdminArea(q).catch(() => null); const admin = await findAdminArea(q).catch(() => null);
signal?.throwIfAborted(); if (admin) return { name: admin.name, ring: [...admin.ring] };
if (admin)
return {
name: admin.name,
ring: [...admin.ring],
source: 'bundled-admin',
};
const lookup = resolveAdminRegionRing(q, signal, placeSearch); const lookup = resolveAdminRegionRing(q, signal, placeSearch);
if (!Number.isFinite(budgetMs)) return lookup; if (!Number.isFinite(budgetMs)) return lookup;
let timer; let timer;
@@ -2077,26 +2067,8 @@ export function createAnnotationResolver({
const geo = await geocodePlace(q, null, signal, placeSearch).catch( const geo = await geocodePlace(q, null, signal, placeSearch).catch(
() => null, () => null,
); );
signal?.throwIfAborted();
if (!geo) return null; if (!geo) return null;
const scope = scopeFromTypes(geo.types); const scope = scopeFromTypes(geo.types);
if (
scope === 'auto' ||
(scope === 'compound' && geo.types?.includes('natural_feature'))
) {
const natural = await lookupNaturalRegionOutline(
q,
geo.lat,
geo.lon,
).catch(() => null);
signal?.throwIfAborted();
if (natural)
return {
name: natural.name,
ring: natural.ring,
source: 'natural-earth',
};
}
if (!['country', 'state', 'county', 'city'].includes(scope)) return null; if (!['country', 'state', 'county', 'city'].includes(scope)) return null;
if (scope === 'state' || scope === 'county' || scope === 'country') { if (scope === 'state' || scope === 'county' || scope === 'country') {
const admin = await findAdminAreaAt( const admin = await findAdminAreaAt(
@@ -2105,16 +2077,12 @@ export function createAnnotationResolver({
geo.lon, geo.lon,
scope, scope,
).catch(() => null); ).catch(() => null);
signal?.throwIfAborted(); if (admin) return { name: q, ring: [...admin.ring] };
if (admin)
return { name: q, ring: [...admin.ring], source: 'bundled-admin' };
} }
const fp = await fetchAdminArea(geo.lat, geo.lon, q, scope, signal).catch( const fp = await fetchAdminArea(geo.lat, geo.lon, q, scope, signal).catch(
() => null, () => null,
); );
signal?.throwIfAborted(); if (fp?.ring?.length >= 3) return { name: q, ring: fp.ring };
if (fp?.ring?.length >= 3)
return { name: q, ring: fp.ring, source: 'remote-boundary' };
return null; return null;
} }
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more