mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-07 03:44:00 +00:00
Compare commits
185
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
664c18d97a | ||
|
|
de2138e84c | ||
|
|
f0e0ea42ce | ||
|
|
89ef90af04 | ||
|
|
5597c81e7c | ||
|
|
fb3506cc20 | ||
|
|
f927ef288a | ||
|
|
97630a598a | ||
|
|
3744a97f00 | ||
|
|
d90bae49b6 | ||
|
|
ea09a59877 | ||
|
|
5b4f5ed4a0 | ||
|
|
1bccc295f0 | ||
|
|
4416a491d2 | ||
|
|
4171ebb6a8 | ||
|
|
59646e52f9 | ||
|
|
38e037d3a7 | ||
|
|
ca71b27791 | ||
|
|
b7fe29b5cc | ||
|
|
12b8fd0c1d | ||
|
|
474d44c4db | ||
|
|
05f668dfa7 | ||
|
|
93c1f6cd45 | ||
|
|
3e39bb2cf4 | ||
|
|
194a547955 | ||
|
|
2f171c7d79 | ||
|
|
a1508a386e | ||
|
|
1c727842df | ||
|
|
bd2342dc81 | ||
|
|
5c513684f5 | ||
|
|
ba5a1e25ee | ||
|
|
4e3c1628b2 | ||
|
|
7fe95b76e9 | ||
|
|
2120130997 | ||
|
|
10916227cb | ||
|
|
c808bfe609 | ||
|
|
b66d02df7c | ||
|
|
0561277dcb | ||
|
|
e9a234094b | ||
|
|
29fb756a5c | ||
|
|
35c612c5f6 | ||
|
|
bd087d6096 | ||
|
|
86eca5abf3 | ||
|
|
0f51eb21ba | ||
|
|
9f6e0ef60f | ||
|
|
5fd5d688dc | ||
|
|
d80683c44b | ||
|
|
56c5d03b65 | ||
|
|
b8bfeb7aa2 | ||
|
|
7214f71878 | ||
|
|
8e635c9a3a | ||
|
|
1959b33c48 | ||
|
|
daaaa348b7 | ||
|
|
0f237a32d4 | ||
|
|
4ecbe54997 | ||
|
|
4999f6dc60 | ||
|
|
3d8e1ef00f | ||
|
|
326c41df9c | ||
|
|
beca41c676 | ||
|
|
a29d5a6874 | ||
|
|
839442b20b | ||
|
|
c174742e2c | ||
|
|
4c383214f7 | ||
|
|
5d480a5fc2 | ||
|
|
7712ecf6ed | ||
|
|
7cdaf40fd0 | ||
|
|
256d7c273e | ||
|
|
d921a1b801 | ||
|
|
0a4d520e79 | ||
|
|
695cce967d | ||
|
|
42c95a8a24 | ||
|
|
29d8fb4101 | ||
|
|
7a31ef5e8a | ||
|
|
7dfecd7d98 | ||
|
|
ea06c9fc64 | ||
|
|
cd7e29c635 | ||
|
|
ada7d8852f | ||
|
|
7844e765b4 | ||
|
|
5b12f51e98 | ||
|
|
f747c4828e | ||
|
|
a310cbc2f0 | ||
|
|
ca9dbea060 | ||
|
|
9b400622af | ||
|
|
3792d7377e | ||
|
|
1b66d284c4 | ||
|
|
f26586bb3e | ||
|
|
6b3f7a3ec1 | ||
|
|
83b9940733 | ||
|
|
91461381ee | ||
|
|
cd0956eef7 | ||
|
|
fa085cbd64 | ||
|
|
48c8a64c97 | ||
|
|
59db4ac227 | ||
|
|
15208b5c40 | ||
|
|
80a0954030 | ||
|
|
8d3c929740 | ||
|
|
7688e53424 | ||
|
|
558b0275a4 | ||
|
|
50559723a5 | ||
|
|
d39256e700 | ||
|
|
97816a35de | ||
|
|
d06e485c12 | ||
|
|
7bf268ec42 | ||
|
|
661e1d7fa3 | ||
|
|
aec4f67ca9 | ||
|
|
5a87fb3b15 | ||
|
|
548e7f23d1 | ||
|
|
daff74fe04 | ||
|
|
a1bd7ff37c | ||
|
|
672191497a | ||
|
|
1c4c903ac6 | ||
|
|
c09865e582 | ||
|
|
83fc895442 | ||
|
|
e4f526415d | ||
|
|
f4a4df5044 | ||
|
|
3e23b4cd39 | ||
|
|
cefbad3c2a | ||
|
|
c1dd4171db | ||
|
|
c7ff33ac2e | ||
|
|
77768e9fff | ||
|
|
5d0c367315 | ||
|
|
db73c6908e | ||
|
|
2a6ba1180d | ||
|
|
c6706a5a52 | ||
|
|
c869b248b7 | ||
|
|
2b5a5128fe | ||
|
|
d604b97a4d | ||
|
|
8f6671b6c2 | ||
|
|
5acf254f8b | ||
|
|
60444cca53 | ||
|
|
1d418fd5af | ||
|
|
52863a9f42 | ||
|
|
8abc99aa0a | ||
|
|
4fde920665 | ||
|
|
2bec3d521b | ||
|
|
202a310c7a | ||
|
|
acd75efc7c | ||
|
|
e2dacd92ea | ||
|
|
38b95fb3b1 | ||
|
|
9688f15af7 | ||
|
|
edf0392248 | ||
|
|
c90e212049 | ||
|
|
e312a007ab | ||
|
|
2aa0ae851f | ||
|
|
702ecc38e2 | ||
|
|
f11a532139 | ||
|
|
77dfa718a9 | ||
|
|
436ffbb21c | ||
|
|
6f054408da | ||
|
|
166190b710 | ||
|
|
1a0b9c8b0f | ||
|
|
19372875e2 | ||
|
|
d9e2c8a7e7 | ||
|
|
a15747ca61 | ||
|
|
1371a86713 | ||
|
|
603f428397 | ||
|
|
2110d06e36 | ||
|
|
e38672b45d | ||
|
|
d19e9f8b93 | ||
|
|
ff799d1520 | ||
|
|
939264d30e | ||
|
|
1e1ddfca0f | ||
|
|
34d53edc91 | ||
|
|
c43f58dc3f | ||
|
|
bea76df454 | ||
|
|
2b7f832f45 | ||
|
|
a194da21dd | ||
|
|
abea3f2feb | ||
|
|
914df05346 | ||
|
|
cbd3b13afb | ||
|
|
8acb526d1f | ||
|
|
3c53d63def | ||
|
|
6a6703e0c6 | ||
|
|
58b7d2d95e | ||
|
|
05b13e9a78 | ||
|
|
c55d4d7c25 | ||
|
|
6439575d15 | ||
|
|
3c163d09a1 | ||
|
|
5c044a3d8d | ||
|
|
4fc813e175 | ||
|
|
b22e6d519a | ||
|
|
b79ab84a1a | ||
|
|
a4ce7381d8 | ||
|
|
f0e28a83cb | ||
|
|
be7187cea7 |
No files matched your search
+12
-8
@@ -83,6 +83,12 @@ OPENAI_REALTIME_TRANSCRIBE_MODEL=gpt-4o-mini-transcribe
|
||||
# keep them while debugging; delete the log when you are done.
|
||||
GEV_VOICE_LOG_CONTENT=
|
||||
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
|
||||
# (/api/realtime/token + /api/openai/hud-summary), in requests per minute.
|
||||
# DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary
|
||||
@@ -118,8 +124,8 @@ OPENSKY_AUTH_MODE=oauth
|
||||
OPENSKY_CLIENT_ID=
|
||||
OPENSKY_CLIENT_SECRET=
|
||||
|
||||
# Optional: higher Launch Library 2 request allowance. Public access works
|
||||
# without a token.
|
||||
# Launch Library 2: leave blank for standard public access (no key needed).
|
||||
# Optional paid Patreon tokens raise request limits; there is no free API key.
|
||||
LL2_API_TOKEN=
|
||||
|
||||
# Optional: OpenSky credentials JSON file path (alternative to above)
|
||||
@@ -141,12 +147,6 @@ PORT=4173
|
||||
# wildcard entries are ignored.
|
||||
# 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
|
||||
# browser — the client polls the /api/firms proxy). Free key:
|
||||
# https://firms.modaps.eosdis.nasa.gov/api/map_key/
|
||||
@@ -207,6 +207,7 @@ AISSTREAM_API_KEY=
|
||||
# CCTV_TFL_ENABLED=1 # set 0 to disable Transport for London JamCams
|
||||
# CCTV_TFL_MAX_SOURCES=250 # cap cameras loaded from TfL
|
||||
# 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_FINTRAFFIC_ENABLED=1 # set 0 to drop the Fintraffic (Finland) pack
|
||||
# CCTV_FINTRAFFIC_MAX_SOURCES=300 # cap cameras loaded from the Fintraffic catalog
|
||||
@@ -234,6 +235,7 @@ AISSTREAM_API_KEY=
|
||||
# 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_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_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)
|
||||
@@ -243,6 +245,8 @@ AISSTREAM_API_KEY=
|
||||
# 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_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_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs
|
||||
# CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry
|
||||
# CCTV_FORCE_AUSTIN= # force live default sources when a source-pack JSON is configured
|
||||
|
||||
+5
-1
@@ -48,6 +48,7 @@ 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 |
|
||||
| **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) |
|
||||
| **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) |
|
||||
| **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) |
|
||||
@@ -63,6 +64,7 @@ How to read this:
|
||||
| **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) |
|
||||
| **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) |
|
||||
| **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` |
|
||||
@@ -152,7 +154,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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
@@ -162,10 +164,12 @@ 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`.
|
||||
- **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`.
|
||||
- **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`.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -66,7 +66,6 @@ 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.
|
||||
- **🌐 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.
|
||||
- **📱 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.
|
||||
- **🏠 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.
|
||||
@@ -308,20 +307,12 @@ _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
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -390,7 +381,7 @@ Twenty layers and map sources. **Eighteen have a keyless path.** Some offer addi
|
||||
| 🌍 **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 | 🟢 |
|
||||
| 🚗 **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) · 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 | 🟢 |
|
||||
| 📹 **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), 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 | 🟢 |
|
||||
| 📷 **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 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 | 🟢 |
|
||||
@@ -398,7 +389,7 @@ Twenty layers and map sources. **Eighteen have a keyless path.** Some offer addi
|
||||
| 🚲 **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) | 🟢 |
|
||||
| 🔥 **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 token raises the allowance) |
|
||||
| 🚀 **Space Missions** | Rolling 30-day launches with payload, stage, and recovery detail | Launch Library 2 | 🟢 (🔴 optional paid token raises the allowance) |
|
||||
| 🎖️ **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 | 🟢 |
|
||||
| 🌦️ **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 | 🟢 |
|
||||
@@ -540,9 +531,11 @@ _What the TomTom key buys you: rush-hour density painted on the city — then di
|
||||
| | Key | Why | Get it |
|
||||
| --- | -------------------- | ------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| 🟡 | **OpenSky** | ✈️ More flight-polling credits (🟢 anonymous works without) | [opensky-network.org](https://opensky-network.org) |
|
||||
| 🟡 | **Launch Library 2** | 🚀 Higher space-missions request allowance (🟢 works without) | [thespacedevs.com](https://thespacedevs.com) |
|
||||
| 🔴 | **Launch Library 2** | 🚀 Optional paid token for higher limits (🟢 no key needed for public access) | [thespacedevs.com/supportus](https://thespacedevs.com/supportus) |
|
||||
|
||||
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
|
||||
where each configured provider was found without printing credential values.
|
||||
|
||||
+1
-2
@@ -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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
@@ -86,7 +86,6 @@ 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.
|
||||
- **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**.
|
||||
- **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
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
- `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).
|
||||
@@ -0,0 +1,6 @@
|
||||
- Make CCTV QA ground-sampling checks respect the active terrain regime and
|
||||
frame the actual calibration gizmo for the drag regression, preserving the
|
||||
photoreal completion floor and all drag invariants.
|
||||
- Measure the tracking arrival regression on the first visible frame within
|
||||
250 ms, accounting for the 80 ms fleet cadence while rejecting a stale
|
||||
first-visible orientation instead of retrying until it is correct.
|
||||
@@ -0,0 +1,5 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,3 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,5 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,4 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Avoid starting or queuing a reply when the local channel rejects a typed OpenAI
|
||||
command, while preserving an earlier accepted deferred input
|
||||
(Manjunath, #1220).
|
||||
@@ -0,0 +1,6 @@
|
||||
- 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).
|
||||
- Refuse Ontario catalog redirects and keep credential-bearing URLs and provider
|
||||
exception text out of failure logs; retain the Ontario licence attribution.
|
||||
@@ -0,0 +1,5 @@
|
||||
- Harden the Tarktee (Estonia) DATEX2 camera catalog fetches: refuse redirects,
|
||||
abort pending siblings and cancel received or late response streams when either
|
||||
request fails before headers or overflows the 4 MB
|
||||
byte cap, retain the shared 30 s dual-XML fetch deadline, and deduplicate camera
|
||||
IDs before per-pack prioritization (yaka0007, #1233).
|
||||
@@ -0,0 +1,5 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,9 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,9 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,7 @@
|
||||
- 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.
|
||||
@@ -0,0 +1,4 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,6 @@
|
||||
- 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.
|
||||
@@ -0,0 +1,17 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,8 @@
|
||||
- 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).
|
||||
+82
-25
@@ -112,7 +112,14 @@ 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
|
||||
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
|
||||
lists at 25 rows by default. Voice offers the same queries next to its app
|
||||
lists at 25 rows by default. `aircraft_in_area` and `vessels_in_area` can also
|
||||
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
|
||||
catalog, loaded on first use. See [tools and the MCP server](TOOLS.md).
|
||||
Aircraft altitude-band queries require a reported barometric or geometric altitude
|
||||
@@ -429,20 +436,6 @@ or unknown freshness and transport failures retain their warnings. Partial
|
||||
snapshots still retain missing contacts within the existing age and row limits.
|
||||
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
|
||||
authors validated anchor, camera, pack and interaction drafts; SHARE SCENE exports
|
||||
a selected scene or a bounded bundle of explicitly chosen pack files. Bundled
|
||||
@@ -503,6 +496,11 @@ to layer toggles, fly_to_location, frame_overhead, select_nearest_aircraft,
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -620,7 +618,9 @@ 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -826,7 +826,11 @@ position stay off the map. Genuine zero coordinates remain valid. Undisclosed
|
||||
stage coordinates, downrange distance and flight numbers remain unknown; the
|
||||
mission panel omits the flight-number label when no number was reported.
|
||||
Pending mission requests abort on disable/destruction and malformed launch
|
||||
snapshots preserve the last accepted display. Catalog groups, propagation cadence,
|
||||
snapshots preserve the last accepted display. A Launch Library stale-cache fallback
|
||||
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.
|
||||
|
||||
The fire layer now exposes `./layers/firms`: an instance factory with separate
|
||||
@@ -1206,6 +1210,10 @@ Automatic collapse remains presentation only, prioritizes the latest explicit
|
||||
panel, and honors keyboard focus on the right. Mobile layout still releases
|
||||
desktop allocation styles. Stable Display allocation avoids unnecessary style
|
||||
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
|
||||
keeps the collapsed panels its own exclusive presentation hides, so automatic
|
||||
collapse can still be undone.
|
||||
@@ -1455,6 +1463,18 @@ an empty dock. Explicit zero and caller-supplied numeric fallbacks remain valid.
|
||||
|
||||
## 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
|
||||
latitudes outside [-90, 90] for every client before upstream resolution. One
|
||||
out-of-range point rejects the whole batch; inclusive WGS84 bounds remain valid.
|
||||
@@ -1492,6 +1512,14 @@ 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
|
||||
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
|
||||
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
|
||||
@@ -2678,6 +2706,17 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> tunings. Ambient overlap includes each sprite's own rendered extent. The
|
||||
> gated AIS, CCTV, and satellite passes retain an active-emphasis count so a
|
||||
> 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
|
||||
> 5-decimal points individually, reconstructs reordered/overlapping batches
|
||||
> in exact request order, and refreshes only missing or stale points. Upstream
|
||||
@@ -3409,7 +3448,7 @@ its criteria cannot be silently ignored.
|
||||
| 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 |
|
||||
| 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) + 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) |
|
||||
| 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) + FL511 (FL, opt-in) + 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 |
|
||||
| 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 |
|
||||
@@ -4380,7 +4419,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.
|
||||
- **CCTV v2 foundation:** a pitched
|
||||
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. Manual calibration only —
|
||||
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 —
|
||||
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;
|
||||
ground placement is superseded by the shared-floor v3 behavior below. Calibration persists to
|
||||
@@ -4398,20 +4437,38 @@ 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
|
||||
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
|
||||
periodic white flash). Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES`
|
||||
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`
|
||||
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,
|
||||
Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default
|
||||
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). All sources are RAW PRIOR
|
||||
sources. Ontario 511 (2026-09-12) adds highway cameras including Kitchener-area routes
|
||||
(cap 1,000, all enabled rows from the current ~944-camera catalog). The 511on.ca API now
|
||||
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.
|
||||
sources. Fintraffic Finland road weather cameras (2026-09-13; cap 300, `CCTV_FINTRAFFIC_MAX_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
|
||||
covering the whole country, where one _preset_ (a station's fixed view) is one camera — 806
|
||||
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
|
||||
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.
|
||||
~1,100 cameras total, all RAW PRIOR poses, stills-first. The catalog lives for 15 minutes; once
|
||||
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.
|
||||
Ontario catalog requests refuse redirects and log only a fixed diagnostic for
|
||||
transport/JSON failures, so reflected request URLs or keys cannot reach logs.
|
||||
Tarktee owns both XML requests with one 30-second deadline and shared abort;
|
||||
a failed header or body read cancels its sibling, including a response arriving
|
||||
after cleanup.
|
||||
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
|
||||
validated 2026-07-21): the COVERAGE toggle is a
|
||||
tri-state cycle `OFF → ON → VIEWSHED`; viewshed mode renders each visible camera's frustum
|
||||
@@ -4728,7 +4785,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.
|
||||
- **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`).
|
||||
- **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.
|
||||
- **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.
|
||||
- **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}`.
|
||||
- **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.
|
||||
|
||||
@@ -108,63 +108,3 @@ Version-1/2/3 projects migrate to version 4 without converting their ordinary
|
||||
shots into explicit moves. IDs, positions, durations, visual settings, packs and
|
||||
source attribution survive. The bloom scale remains independent of the document
|
||||
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.
|
||||
@@ -103,8 +103,3 @@ change with this document boundary.
|
||||
Version 5 additionally accepts scene `dataPacks` and shot `dataPackIds`, as
|
||||
defined in [data packs](DIRECTOR-DATA-PACKS.md). Version-4 camera documents
|
||||
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
@@ -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_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 |
|
||||
| `aircraft_in_area` | `aircraft` | Aircraft in an area, nearest first; `military: true` reads the `military` feed |
|
||||
| `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 |
|
||||
| `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_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 |
|
||||
| `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 |
|
||||
| `find_vessel` | `vessels` | Ships anywhere by MMSI, IMO number or name |
|
||||
| `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 |
|
||||
|
||||
-165
@@ -1,165 +0,0 @@
|
||||
# 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
-1
@@ -277,6 +277,7 @@
|
||||
"./tools/mcp": "./src/tools/mcp/index.js",
|
||||
"./tools/panel": "./src/tools/panel.js",
|
||||
"./tools/services": "./src/tools/services.js",
|
||||
"./view": "./src/view/index.js"
|
||||
"./view": "./src/view/index.js",
|
||||
"./agent/world-packet": "./src/agent/worldPacket.js"
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,7 @@
|
||||
"server/providers/space/launch-library.js",
|
||||
"src/data/spaceProviderRequests.js",
|
||||
"src/tooling/spaceProviders.test.mjs",
|
||||
"src/tooling/ll2Integration.test.mjs",
|
||||
"server/providers/terrain.js",
|
||||
"server/providers/traffic.js",
|
||||
"server/providers/firms.js",
|
||||
@@ -446,6 +447,7 @@
|
||||
"src/data/rocketLaunches.js",
|
||||
"src/layers/satellites/source.test.mjs",
|
||||
"src/layers/launches/source.test.mjs",
|
||||
"src/layers/launches/ingestion.test.mjs",
|
||||
"src/layers/installations/lifecycle.js",
|
||||
"src/layers/installations/viewport.js",
|
||||
"src/layers/installations/controls.js",
|
||||
@@ -555,6 +557,8 @@
|
||||
"src/data/cctvNswSource.test.mjs",
|
||||
"src/data/cctvTxdotSource.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.test.mjs",
|
||||
"src/data/dataCredits.test.mjs",
|
||||
@@ -635,6 +639,7 @@
|
||||
"src/voice/control.js",
|
||||
"src/voice/realtimeBackend.js",
|
||||
"src/voice/realtimeBackend.test.mjs",
|
||||
"src/agent/worldPacket.test.mjs",
|
||||
"src/voice/layerSummary.js",
|
||||
"build/application-html.js",
|
||||
"src/app/sourceSlot.js",
|
||||
@@ -690,6 +695,7 @@
|
||||
"src/ui/shareRestoration.js",
|
||||
"src/ui/visualSettings.js",
|
||||
"src/ui/panelChrome.js",
|
||||
"src/ui/panelChrome.radioOwnership.test.mjs",
|
||||
"src/testSupport/readShellSource.mjs",
|
||||
"src/ui/stateOwners.test.mjs",
|
||||
"src/layers/flights/records.js",
|
||||
@@ -1026,6 +1032,7 @@
|
||||
"scripts/qa-context-arrivals.mjs",
|
||||
"src/tools/catalog.test.mjs",
|
||||
"src/tools/area.test.mjs",
|
||||
"src/tools/results.test.mjs",
|
||||
"src/tools/queries/queries.test.mjs",
|
||||
"src/tools/mcp/mcp.test.mjs",
|
||||
"src/tools/localServer.test.mjs",
|
||||
@@ -1062,5 +1069,6 @@
|
||||
"src/ui/flyToDataSource.test.mjs",
|
||||
"scripts/assemble-changelog.mjs",
|
||||
"src/tooling/changelogFragments.test.mjs",
|
||||
"src/data/gbfsProxyRateLimit.test.mjs"
|
||||
"src/data/gbfsProxyRateLimit.test.mjs",
|
||||
"src/terrainHeightsBounds.test.mjs"
|
||||
]
|
||||
@@ -114,7 +114,11 @@
|
||||
"exports": ["./server/providers/terrain"],
|
||||
"modules": [
|
||||
"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": []
|
||||
},
|
||||
@@ -1040,6 +1044,7 @@
|
||||
"src/layers/vessels/tracking.js",
|
||||
"src/data/iconOrientation.js",
|
||||
"src/data/vesselLabels.js",
|
||||
"src/data/vesselTypes.js",
|
||||
"src/layers/vessels/records.js",
|
||||
"src/layers/vessels/recordPolicy.js",
|
||||
"src/layers/vessels/snapshotRenderer.js",
|
||||
@@ -1628,7 +1633,15 @@
|
||||
"src/i18n/locale.js",
|
||||
"src/i18n/locales/es.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": []
|
||||
},
|
||||
@@ -1841,6 +1854,7 @@
|
||||
"src/data/trafficQueue.js",
|
||||
"src/data/trailRenderer.js",
|
||||
"src/data/vesselLabels.js",
|
||||
"src/data/vesselTypes.js",
|
||||
"src/firstRunExperience.js",
|
||||
"src/hud.js",
|
||||
"src/hudLocality.js",
|
||||
@@ -2215,6 +2229,7 @@
|
||||
"src/voice/commands.js",
|
||||
"src/voice/control.js",
|
||||
"src/voice/gevActions.js",
|
||||
"src/agent/worldPacket.js",
|
||||
"src/voice/speech.js",
|
||||
"src/ui/layerNames.js",
|
||||
"src/voice/earcon.js",
|
||||
@@ -2491,12 +2506,11 @@
|
||||
"src/layers/airQuality/model.js",
|
||||
"src/layers/airQuality/source.js",
|
||||
"src/ui/statusText.js",
|
||||
"src/scenes/cameraLens.js",
|
||||
"src/director/lens.js",
|
||||
"src/vcam/controller.js",
|
||||
"src/vcam/rig.js",
|
||||
"src/vcam/qr.js",
|
||||
"src/ui/vcamPanel.js"
|
||||
"src/voice/providerCommands.js",
|
||||
"src/voice/providerCapabilities.js",
|
||||
"src/voice/geminiSession.js",
|
||||
"src/voice/geminiAudio.js",
|
||||
"src/voice/geminiCaptureWorklet.js"
|
||||
],
|
||||
"external": [
|
||||
"hls.js",
|
||||
@@ -2635,6 +2649,7 @@
|
||||
"src/data/trafficQueue.js",
|
||||
"src/data/trailRenderer.js",
|
||||
"src/data/vesselLabels.js",
|
||||
"src/data/vesselTypes.js",
|
||||
"src/keylessGeocoder.js",
|
||||
"src/layers/aircraft/classification.js",
|
||||
"src/layers/alpr/index.js",
|
||||
@@ -3383,7 +3398,8 @@
|
||||
"src/i18n/locale.js",
|
||||
"src/i18n/locales/es.json",
|
||||
"src/i18n/locales/ru.json",
|
||||
"src/ui/statusText.js"
|
||||
"src/ui/statusText.js",
|
||||
"src/voice/providerCapabilities.js"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
@@ -3788,6 +3804,7 @@
|
||||
"src/tools/queries/maritime.js",
|
||||
"src/tools/queries/share.js",
|
||||
"src/data/idSwitches.js",
|
||||
"src/data/vesselTypes.js",
|
||||
"src/data/layerState.js",
|
||||
"src/data/layerStateTokenReservations.json",
|
||||
"src/sources/gbfsStations.js",
|
||||
@@ -3949,5 +3966,18 @@
|
||||
"src/i18n/marker.js"
|
||||
],
|
||||
"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"]
|
||||
}
|
||||
}
|
||||
@@ -326,8 +326,10 @@ async function main() {
|
||||
'src/data/local_data/cctv_ground_heights/cctv_ground_heights.json',
|
||||
);
|
||||
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`, {
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Catalog HTTP ${response.status}`);
|
||||
const catalog = await response.json();
|
||||
|
||||
+269
-107
@@ -11,8 +11,10 @@
|
||||
* exactly once per camera ACTIVATION (the §9.1 obstruction probe) and
|
||||
* never again in steady state; shared mesh-floor sampling fires at most
|
||||
* once per coarse cell during the staggered geometry-load drain, and
|
||||
* actually COMPLETES once tiles load (>=1 real sample — the
|
||||
* ceiling alone would pass trivially at Δ=0 if the snap never finished),
|
||||
* actually COMPLETES once tiles load in photoreal mode (>=1 real sample
|
||||
* — the ceiling alone would pass trivially at Δ=0 if the snap never
|
||||
* 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.
|
||||
* 2. Geometry contract: the 5-polyline frustum wireframe + far-cap plane
|
||||
* exist for the active camera, the plane's corners coincide with the
|
||||
@@ -139,6 +141,56 @@ function record(name, ok, detail) {
|
||||
|
||||
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
|
||||
// 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
|
||||
@@ -155,29 +207,58 @@ async function positionPointerForGizmoDrag(page, point, frameCount = 3) {
|
||||
gev.dataManager.layers
|
||||
.get('cctv')
|
||||
.module.setParams({ calibrationMode: true });
|
||||
const scene = gev.viewer.scene;
|
||||
let rendered = 0;
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (complete) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
remove();
|
||||
resolve(complete);
|
||||
};
|
||||
const remove = scene.postRender.addEventListener(() => {
|
||||
rendered += 1;
|
||||
if (rendered >= count) {
|
||||
finish(true);
|
||||
return;
|
||||
}
|
||||
return (await window.__qaRenderFrames(count, 5000)) >= count;
|
||||
}, frameCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a screenshot for human review. These are never a gate, so a capture
|
||||
* that fails (for example when the renderer stalls in a hidden headful window)
|
||||
* is logged instead of ending the run.
|
||||
* @param {import('puppeteer').Page} page
|
||||
* @param {string} file
|
||||
* @param {string} label
|
||||
*/
|
||||
async function saveReviewShot(page, file, label) {
|
||||
try {
|
||||
await page.screenshot({ path: file });
|
||||
console.log(` screenshot (${label}) → ${path.relative(REPO_ROOT, file)}`);
|
||||
} 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();
|
||||
});
|
||||
const timer = setTimeout(() => finish(false), 5000);
|
||||
scene.requestRender();
|
||||
});
|
||||
}, frameCount);
|
||||
});
|
||||
}
|
||||
|
||||
// In-page helper (stringified and re-defined inside each evaluate that needs
|
||||
@@ -280,23 +361,21 @@ const BEARING_SHIFT_SRC = `
|
||||
* @returns {Promise<boolean>} True if tilesLoaded was observed within the timeout.
|
||||
*/
|
||||
function waitForTilesLoaded(page, timeoutMs = 15000) {
|
||||
return page
|
||||
.waitForFunction(
|
||||
() => {
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
const prims = scene.primitives;
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims.get(i);
|
||||
if (p && p.constructor && p.constructor.name === 'Cesium3DTileset') {
|
||||
return p.tilesLoaded === true;
|
||||
}
|
||||
return waitForPredicate(
|
||||
page,
|
||||
() => {
|
||||
const scene = window.__godsEyeView.viewer.scene;
|
||||
const prims = scene.primitives;
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims.get(i);
|
||||
if (p && p.constructor && p.constructor.name === 'Cesium3DTileset') {
|
||||
return p.tilesLoaded === true;
|
||||
}
|
||||
return true; // no tileset in the scene — nothing to wait for
|
||||
},
|
||||
{ timeout: timeoutMs },
|
||||
)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
}
|
||||
return true; // no tileset in the scene — nothing to wait for
|
||||
},
|
||||
{ timeoutMs },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,6 +443,10 @@ async function main() {
|
||||
const chromeExecutable = findChromeExecutable();
|
||||
const browser = await puppeteer.launch({
|
||||
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 } : {}),
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
@@ -397,13 +480,18 @@ async function main() {
|
||||
});
|
||||
console.log('Loading app...');
|
||||
await page.goto(APP_URL, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||
await page.waitForFunction(
|
||||
const appReady = await waitForPredicate(
|
||||
page,
|
||||
() =>
|
||||
window.__godsEyeView &&
|
||||
window.__godsEyeView.viewer &&
|
||||
window.__godsEyeView.dataManager,
|
||||
{ timeout: 60000 },
|
||||
Boolean(
|
||||
window.__godsEyeView &&
|
||||
window.__godsEyeView.viewer &&
|
||||
window.__godsEyeView.dataManager,
|
||||
),
|
||||
{ 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.
|
||||
await sleep(4000);
|
||||
|
||||
@@ -475,18 +563,15 @@ async function main() {
|
||||
console.log(
|
||||
`Waiting for geometry-load queue to drain (N=${camCount}, budget ${Math.round(drainBudgetMs / 1000)}s)...`,
|
||||
);
|
||||
const drained = await page
|
||||
.waitForFunction(
|
||||
() => {
|
||||
const mod =
|
||||
window.__godsEyeView.dataManager.layers.get('cctv').module;
|
||||
const ui = mod.getUIState();
|
||||
return ui.loading && ui.loading.active === false;
|
||||
},
|
||||
{ timeout: drainBudgetMs },
|
||||
)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
const drained = await waitForPredicate(
|
||||
page,
|
||||
() => {
|
||||
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
|
||||
const ui = mod.getUIState();
|
||||
return Boolean(ui.loading) && ui.loading.active === false;
|
||||
},
|
||||
{ timeoutMs: drainBudgetMs, intervalMs: 1000 },
|
||||
);
|
||||
record(
|
||||
`geometry-load queue drains within ${Math.round(drainBudgetMs / 1000)}s (N=${camCount})`,
|
||||
drained ? true : HEADFUL ? false : null,
|
||||
@@ -575,27 +660,87 @@ async function main() {
|
||||
// (existence, not just ceiling). The wait below tolerates the update-tick
|
||||
// latency of the completion pass (update interval is 10s).
|
||||
// -----------------------------------------------------------------------
|
||||
console.log('Waiting for tiles + the one-shot completion pass...');
|
||||
const tilesSeenLoaded = await waitForTilesLoaded(page, 45000);
|
||||
let sampleFloorOk = false;
|
||||
if (tilesSeenLoaded) {
|
||||
sampleFloorOk = await page
|
||||
.waitForFunction(
|
||||
(base) => window.__qaCounters.sampleHeight - base >= 1,
|
||||
{ timeout: 30000 },
|
||||
c0.sampleHeight,
|
||||
)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
}
|
||||
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',
|
||||
const globeMode = await page.evaluate(
|
||||
() => window.__godsEyeView.viewer.scene.globe?.show !== false,
|
||||
);
|
||||
if (globeMode) {
|
||||
// Globe stacks intentionally perform no scene.sampleHeight query.
|
||||
// Require independently fetched DEM heights and the actual rendered
|
||||
// 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,
|
||||
{ timeoutMs: 30000, args: [c0.sampleHeight] },
|
||||
);
|
||||
}
|
||||
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
|
||||
// the sampleHeight counter quiet for 12s (> the 10s update interval, so
|
||||
@@ -1358,18 +1503,7 @@ async function main() {
|
||||
},
|
||||
});
|
||||
window.__qaCctvSiblingOwner = owner;
|
||||
await new Promise((resolve) => {
|
||||
let frames = 0;
|
||||
const remove = scene.postRender.addEventListener(() => {
|
||||
if (++frames < 3) {
|
||||
scene.requestRender();
|
||||
return;
|
||||
}
|
||||
remove();
|
||||
resolve();
|
||||
});
|
||||
scene.requestRender();
|
||||
});
|
||||
const framesRendered = await window.__qaRenderFrames(3, 10000);
|
||||
const rect = scene.canvas.getBoundingClientRect();
|
||||
const picked = scene.pick(canvasPoint);
|
||||
const pickedId = picked?.id?.id ?? picked?.id ?? null;
|
||||
@@ -1382,26 +1516,33 @@ async function main() {
|
||||
typeof pickedId === 'string' ? pickedId : (pickedId?.id ?? null),
|
||||
ownerId: owner.id,
|
||||
ownsExactObject: picked?.id === owner,
|
||||
framesRendered,
|
||||
projectionDelta: Math.hypot(
|
||||
projected.x - canvasPoint.x,
|
||||
projected.y - canvasPoint.y,
|
||||
),
|
||||
};
|
||||
}, 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(
|
||||
'sibling test object owns its canvas pick',
|
||||
!siblingTarget
|
||||
? null
|
||||
: siblingOwnsPick ||
|
||||
(siblingRendererStalled && !HEADFUL ? null : false),
|
||||
siblingTarget
|
||||
? siblingTarget.pickedId === 'qa-cctv-sibling-owner' &&
|
||||
siblingTarget.ownsExactObject
|
||||
: null,
|
||||
siblingTarget
|
||||
? `picked=${siblingTarget.pickedId} exactOwner=${siblingTarget.ownsExactObject} projectionΔ=${siblingTarget.projectionDelta}`
|
||||
? `${siblingRendererStalled ? 'renderer stalled: ' : ''}frames=${siblingTarget.framesRendered}/3 picked=${siblingTarget.pickedId} exactOwner=${siblingTarget.ownsExactObject} projectionΔ=${siblingTarget.projectionDelta}`
|
||||
: 'no previously verified empty canvas ray was available',
|
||||
);
|
||||
if (
|
||||
siblingTarget?.pickedId === 'qa-cctv-sibling-owner' &&
|
||||
siblingTarget.ownsExactObject
|
||||
) {
|
||||
if (siblingOwnsPick) {
|
||||
await page.mouse.click(siblingTarget.x, siblingTarget.y);
|
||||
await sleep(250);
|
||||
}
|
||||
@@ -1426,8 +1567,7 @@ async function main() {
|
||||
});
|
||||
record(
|
||||
'sibling canvas click passes through without CCTV selection or deselection',
|
||||
siblingTarget?.pickedId === 'qa-cctv-sibling-owner' &&
|
||||
siblingTarget.ownsExactObject
|
||||
siblingOwnsPick
|
||||
? siblingClick.activeId === clickEvidenceSetup.activeId &&
|
||||
siblingClick.transitions === siblingClick.baselineTransitions &&
|
||||
siblingClick.focusEvents === 0 &&
|
||||
@@ -1626,10 +1766,7 @@ async function main() {
|
||||
);
|
||||
|
||||
const viewshedShot = path.join(SHOTS_DIR, 'cctv-v3-viewshed.png');
|
||||
await page.screenshot({ path: viewshedShot });
|
||||
console.log(
|
||||
` screenshot (visual review only) → ${path.relative(REPO_ROOT, viewshedShot)}`,
|
||||
);
|
||||
await saveReviewShot(page, viewshedShot, 'visual review only');
|
||||
|
||||
// =========================================================================
|
||||
// Group 7: calibration gizmo (v3 design §3c — ADJUST mode + drag)
|
||||
@@ -1660,6 +1797,34 @@ async function main() {
|
||||
gizmoStates.map((s, i) => `${GIZMO_PARTS[i]}=${s}`).join(' '),
|
||||
);
|
||||
|
||||
// Frame the actual gizmo for the drag fixture. Default autofocus can leave
|
||||
// its shaft below the 10px interaction threshold; that distant view is not
|
||||
// the drag-usability scenario this regression exercises.
|
||||
const dragFraming = await page.evaluate(async () => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const e = viewer.entities.getById('cctv-gizmo-move-east');
|
||||
if (!e) return null;
|
||||
const pts = e.polyline.positions.getValue(viewer.clock.currentTime);
|
||||
const target = pts?.[0];
|
||||
if (!target) return null;
|
||||
const measure = () => {
|
||||
const a = viewer.scene.cartesianToCanvasCoordinates(pts[0]);
|
||||
const b = viewer.scene.cartesianToCanvasCoordinates(pts[pts.length - 1]);
|
||||
return {
|
||||
shaftPx: a && b ? Math.hypot(b.x - a.x, b.y - a.y) : null,
|
||||
rangeM: target.constructor.distance(viewer.camera.positionWC, target),
|
||||
};
|
||||
};
|
||||
const before = measure();
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.camera.lookAt(target, new target.constructor(0, -200, 180));
|
||||
viewer.camera.lookAtTransform(viewer.camera.transform.constructor.IDENTITY);
|
||||
viewer.scene.requestRender();
|
||||
const frames = await window.__qaRenderFrames(3, 10000);
|
||||
return { before, after: measure(), frames };
|
||||
});
|
||||
console.log('Drag fixture framing:', JSON.stringify(dragFraming));
|
||||
|
||||
// Synthetic CDP drag on the EAST arrow — the owner's field-test
|
||||
// regression. Sample effective elevation after every mouse move: it must
|
||||
// stay frozen until release, with no transient sampleHeight calls.
|
||||
@@ -1963,10 +2128,7 @@ async function main() {
|
||||
// -----------------------------------------------------------------------
|
||||
await sleep(1000);
|
||||
const shot = path.join(SHOTS_DIR, 'cctv-v2-active.png');
|
||||
await page.screenshot({ path: shot });
|
||||
console.log(
|
||||
` screenshot (visual review only, not a gate) → ${path.relative(REPO_ROOT, shot)}`,
|
||||
);
|
||||
await saveReviewShot(page, shot, 'visual review only, not a gate');
|
||||
|
||||
// No console errors during the whole exercise.
|
||||
record(
|
||||
|
||||
@@ -298,11 +298,12 @@ async function main() {
|
||||
);
|
||||
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.
|
||||
// Park above and right of the voice dock and its raised provider chooser:
|
||||
// growing every edge must leave the south handles clear of both controls.
|
||||
{
|
||||
const panel = await readPanel();
|
||||
const header = await headerPoint();
|
||||
await drag(header, 0, 120 - header.y);
|
||||
await drag(header, 900 - panel.left, 120 - header.y);
|
||||
}
|
||||
|
||||
const limits = {
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
#!/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);
|
||||
@@ -2696,9 +2696,9 @@ async function main() {
|
||||
// Staged deterministically: park the camera nadir over the synthetic
|
||||
// cluster, let rotations settle, TAMPER a billboard's rotation, then
|
||||
// trigger each path with the camera idle. The idle-drift catch-up
|
||||
// (ROTATION_REFRESH_MS = 1 s) can coincidentally mask a regression in a
|
||||
// ~300 ms SwiftShader frame window, so a regression shows as an
|
||||
// intermittent (not guaranteed) failure — never a false failure.
|
||||
// (ROTATION_REFRESH_MS = 1 s) must not repair a stale first-visible nose
|
||||
// before we inspect it: capture that first postRender, with a 250 ms
|
||||
// deadline that admits the 80 ms fleet cadence without waiting a second.
|
||||
// ============================================================
|
||||
console.log('\nChange 4 — arrival rotation: moveEnd settle pass + horizon-reveal pass');
|
||||
const arrival = await evalPage(async () => {
|
||||
@@ -2762,6 +2762,43 @@ async function main() {
|
||||
});
|
||||
await nextFrames(3);
|
||||
const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b)));
|
||||
// Render frames are not fleet ticks: at 60/120 Hz four frames can
|
||||
// precede the next 80 ms fleet pass. Observe elapsed time instead, and
|
||||
// freeze the angle on the FIRST visible frame, even when it is wrong.
|
||||
const observeFirstReveal = (bb, course, budgetMs = 250) => new Promise((resolve) => {
|
||||
const startedAt = performance.now();
|
||||
let frames = 0;
|
||||
let settled = false;
|
||||
const finish = (shown, elapsedMs) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
remove();
|
||||
const expected = shown
|
||||
? screenProjectedRotation(v.scene, bb.position, course, null)
|
||||
: null;
|
||||
resolve({
|
||||
shown,
|
||||
flipFrame: shown ? frames : -1,
|
||||
revealElapsedMs: elapsedMs,
|
||||
revealWithinBudget: shown && elapsedMs <= budgetMs,
|
||||
dReveal: shown && Number.isFinite(expected) ? angDiff(bb.rotation, expected) : null,
|
||||
});
|
||||
};
|
||||
const remove = v.scene.postRender.addEventListener(() => {
|
||||
frames += 1;
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
if (bb.show) {
|
||||
finish(true, elapsedMs);
|
||||
} else if (elapsedMs >= budgetMs) {
|
||||
finish(false, elapsedMs);
|
||||
} else {
|
||||
v.scene.requestRender();
|
||||
}
|
||||
});
|
||||
const timer = setTimeout(() => finish(false, performance.now() - startedAt), budgetMs);
|
||||
v.scene.requestRender();
|
||||
});
|
||||
const probe = async (id, course) => {
|
||||
const bb = findBB(id);
|
||||
if (!bb || !bb.show) return { error: `${id} missing/hidden` };
|
||||
@@ -2779,25 +2816,17 @@ async function main() {
|
||||
const expectedMoveEnd = screenProjectedRotation(v.scene, bb.position, course, null);
|
||||
// (b) reveal pass: tamper + hide — the next fleet tick must flip it
|
||||
// visible AND correct the nose in that same tick (camera still idle,
|
||||
// no moveEnd raised). Diagnostic fields (round 5): record WHICH frame
|
||||
// the flip landed on (flipFrame; -1 = never within the extended
|
||||
// window) and whether a 3D model owns this id — distinguishes "tick
|
||||
// slow under load" from "occluder says hidden" from "model handoff".
|
||||
// no moveEnd raised). Record frame count as diagnostics only: the
|
||||
// first visible postRender must already have the corrected rotation.
|
||||
bb.rotation = r0 + 1.5;
|
||||
bb.show = false;
|
||||
let flipFrame = -1;
|
||||
for (let f = 1; f <= 6; f++) {
|
||||
await nextFrames(1);
|
||||
if (bb.show && flipFrame === -1) flipFrame = f;
|
||||
if (f >= 2 && flipFrame !== -1) break;
|
||||
}
|
||||
const expectedReveal = screenProjectedRotation(v.scene, bb.position, course, null);
|
||||
const reveal = await observeFirstReveal(bb, course);
|
||||
const hasModel = !!(window.__g3dFindModel && window.__g3dFindModel(id));
|
||||
return {
|
||||
r0,
|
||||
dMoveEnd: angDiff(afterMoveEnd, expectedMoveEnd),
|
||||
dReveal: angDiff(bb.rotation, expectedReveal),
|
||||
shown: bb.show, flipFrame, hasModel,
|
||||
...reveal,
|
||||
hasModel,
|
||||
};
|
||||
};
|
||||
const flightCourse = window.__SYNTH.flights.find((f) => f.icao === 'aaa002')?.track ?? 0;
|
||||
@@ -2808,20 +2837,18 @@ async function main() {
|
||||
};
|
||||
});
|
||||
const fmtArr = (a) => (!a ? `no result (${arrival?.error || 'phase error'})` : a.error ? a.error
|
||||
: `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${(a.dReveal * 180 / Math.PI).toFixed(1)}° shown=${a.shown} flipFrame=${a.flipFrame} hasModel=${a.hasModel}`);
|
||||
: `settle-err=${(a.dMoveEnd * 180 / Math.PI).toFixed(1)}° reveal-err=${a.dReveal === null ? 'unobserved' : (a.dReveal * 180 / Math.PI).toFixed(1) + '°'} shown=${a.shown} flipFrame=${a.flipFrame} revealMs=${a.revealElapsedMs.toFixed(1)} hasModel=${a.hasModel}`);
|
||||
const TAMPER_DEG = 1.5 * 180 / Math.PI; // ≈ 86° — an uncorrected nose stays this far off
|
||||
// Reveal budget re-pinned 2 → 4 frames (round 5): the diagnostic probe
|
||||
// shows the military flip consistently lands on frame 2 — the exact edge
|
||||
// of the old budget — so any load hiccup flaked it (flights lands frame
|
||||
// 1). The regression this protects against is a reveal that waits for
|
||||
// the 1 s idle catch-up (~30-60 frames) or never re-aims; 4 frames still
|
||||
// catches that with a wide margin, with zero-headroom flakes gone.
|
||||
// 250 ms spans multiple 80 ms fleet opportunities while remaining well
|
||||
// below the 1 s idle catch-up. Never retry until the angle becomes correct:
|
||||
// dReveal is the immutable first-visible-frame observation above.
|
||||
const arrOk = (a) => !!a && !a.error && a.shown
|
||||
&& (a.flipFrame === -1 ? false : a.flipFrame <= 4)
|
||||
&& a.revealWithinBudget && a.revealElapsedMs <= 250
|
||||
&& a.dReveal !== null
|
||||
&& a.dMoveEnd * 180 / Math.PI < 10 && a.dReveal * 180 / Math.PI < 10;
|
||||
record(`arrival: moveEnd + reveal both re-aim within 4 frames, flights (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
record(`arrival: moveEnd re-aims and first reveal is correct within 250 ms, flights (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
arrOk(arrival.flights), fmtArr(arrival.flights));
|
||||
record(`arrival: moveEnd + reveal both re-aim within 4 frames, military (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
record(`arrival: moveEnd re-aims and first reveal is correct within 250 ms, military (tamper was ${TAMPER_DEG.toFixed(0)}°)`,
|
||||
arrOk(arrival.military), fmtArr(arrival.military));
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -143,7 +143,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
|
||||
|
||||
if (url.pathname === '/sources') {
|
||||
const body = {
|
||||
trimmedPacks: getCctvSources.trimmedPacks?.() ?? [],
|
||||
trimmedPacks: getCctvSources.trimmedPacks?.(sources) ?? [],
|
||||
sources: sources.map((source) => ({
|
||||
id: source.id,
|
||||
pack: source.pack,
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
loadVegvesenSourcesFromOpenData,
|
||||
loadNycSourcesFromOpenData,
|
||||
loadTorontoSourcesFromOpenData,
|
||||
loadFloridaSourcesFromOpenData,
|
||||
} from './sources.js';
|
||||
|
||||
/** Env kill switch: unset or anything but "0" means enabled. */
|
||||
@@ -144,6 +145,14 @@ const LIVE_PACKS = [
|
||||
enabled: () => envOptIn('CCTV_LITHUANIA_ENABLED'),
|
||||
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,
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Load CCTV sources from a local JSON file (CCTV_SOURCES_FILE env or default).
|
||||
@@ -195,16 +204,19 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
|
||||
/** @type {Promise<Array<object>>|null} In-flight refresh, shared by concurrent
|
||||
* callers so a post-TTL burst launches ONE refetch, not one per request. */
|
||||
let _cctvSourceInflight = null;
|
||||
/** @type {Array<{pack: string, available: number, served: number}>} Packs
|
||||
* that serve fewer cameras than they offer. */
|
||||
let _cctvTrimmedPacks = [];
|
||||
/** @type {WeakMap<Array<object>, Array<{pack: string, available: number, served: number}>>}
|
||||
* Packs that serve fewer cameras than they offer, keyed by the source list
|
||||
* they describe, so a request served the old list during a background
|
||||
* refresh never pairs it with the new list's trim notes. */
|
||||
const _cctvTrimmedPacks = new WeakMap();
|
||||
|
||||
/**
|
||||
* Assemble and cache the merged CCTV source list.
|
||||
*
|
||||
* Merges every source pack (live open-data packs, local file, env
|
||||
* variable), deduplicates by ID, shares the catalog cap fairly across
|
||||
* packs, and caches for CCTV_SOURCE_CACHE_MS.
|
||||
* packs, and caches for CCTV_SOURCE_CACHE_MS. Past that, the cached list is
|
||||
* returned while a background refresh replaces it; only a first load waits.
|
||||
*
|
||||
* @returns {Promise<Array<object>>} Deduplicated, capped source list.
|
||||
*/
|
||||
@@ -219,11 +231,31 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
|
||||
// Single-flight: a burst of requests arriving past the TTL shares ONE refresh
|
||||
// instead of each launching the full multi-provider refetch. The `.finally`
|
||||
// clears the ref so the next post-TTL cycle starts fresh.
|
||||
if (_cctvSourceInflight) return _cctvSourceInflight;
|
||||
_cctvSourceInflight = refreshCctvSources().finally(() => {
|
||||
_cctvSourceInflight = null;
|
||||
});
|
||||
return _cctvSourceInflight;
|
||||
if (!_cctvSourceInflight) {
|
||||
_cctvSourceInflight = refreshCctvSources().finally(() => {
|
||||
_cctvSourceInflight = null;
|
||||
});
|
||||
// A background refresh has no caller waiting on it: report its failure
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -313,7 +345,7 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
|
||||
}
|
||||
if (capped.length > 0 || _cctvSourceCache.length === 0) {
|
||||
_cctvSourceCache = capped;
|
||||
_cctvTrimmedPacks = trimmedPacks;
|
||||
_cctvTrimmedPacks.set(capped, trimmedPacks);
|
||||
} else {
|
||||
// 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
|
||||
@@ -327,7 +359,10 @@ export function createCctvCatalog({ sourceRoot = process.cwd() } = {}) {
|
||||
return _cctvSourceCache;
|
||||
}
|
||||
|
||||
/** Packs serving fewer cameras than they offer, as of the last refresh. */
|
||||
getCctvSources.trimmedPacks = () => _cctvTrimmedPacks;
|
||||
/** Packs serving fewer cameras than they offer in `sources` (by default the
|
||||
* current catalog). Pass the list a request was served to keep the two in
|
||||
* step while a background refresh swaps the catalog. */
|
||||
getCctvSources.trimmedPacks = (sources = _cctvSourceCache) =>
|
||||
_cctvTrimmedPacks.get(sources) ?? [];
|
||||
return getCctvSources;
|
||||
}
|
||||
@@ -113,13 +113,34 @@ export const CALTRANS_ANCHORS = [
|
||||
{ lat: 32.7157, lon: -117.1611 }, // San Diego
|
||||
{ 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. */
|
||||
export const TFL_JAMCAM_URL = 'https://api.tfl.gov.uk/Place/Type/JamCam';
|
||||
export const TFL_IMAGE_ORIGIN =
|
||||
'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/';
|
||||
export const DEFAULT_TFL_MAX_SOURCES = 250;
|
||||
export const LONDON_CENTER = { lat: 51.5074, lon: -0.1278 };
|
||||
/** Ontario 511: keyless CARS/511 camera catalog; frame URLs are still images. */
|
||||
/** Ontario 511: CARS/511 camera catalog, which needs a developer key (ONTARIO_511_API_KEY); frame URLs are still images. */
|
||||
export const ONTARIO_511_CAMERAS_URL =
|
||||
'https://511on.ca/api/v2/get/cameras?format=json&lang=en';
|
||||
export const ONTARIO_511_IMAGE_ORIGIN = 'https://511on.ca/map/Cctv/';
|
||||
@@ -188,6 +209,8 @@ export const TARKTEE_IMAGES_URL =
|
||||
'https://tarktee.transpordiamet.ee/api/v1/datex/roadCameraImages';
|
||||
export const TARKTEE_IMAGE_ORIGIN = 'https://tarktee.transpordiamet.ee/images/';
|
||||
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 = [
|
||||
{ lat: 59.437, lon: 24.753 }, // Tallinn
|
||||
{ lat: 58.378, lon: 26.729 }, // Tartu
|
||||
@@ -317,6 +340,49 @@ export const NORWAY_ANCHORS = [
|
||||
{ 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
|
||||
* five boroughs (~980 cameras). Frames are stills synthesized from each
|
||||
* camera UUID on the city's webcam host — never taken from the payload. */
|
||||
@@ -439,6 +505,10 @@ export const CCTV_SOURCE_CACHE_MS = 15 * 60 * 1000;
|
||||
* pending forever — a hung fetch aborts, the loader returns [], and
|
||||
* serve-stale/other packs take over. */
|
||||
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
|
||||
* client refresh cadence. A bounded miss can fall through to Street View or
|
||||
* the synthetic frame instead of leaving the browser preview pending. */
|
||||
|
||||
@@ -377,6 +377,17 @@ 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. */
|
||||
export function isLikelyNycCoordinate(lat, lon) {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
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/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const failure of ['transport', 'invalid-json']) {
|
||||
test(`Ontario ${failure} failures cannot log reflected keys or request URLs`, async (t) => {
|
||||
const lines = captureConsole(t);
|
||||
const key = 'synthetic secret&/=%value';
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
if (failure === 'transport')
|
||||
throw new Error(`request failed: ${url} ${key}`);
|
||||
return new Response(`not JSON: ${url} ${key}`);
|
||||
});
|
||||
assert.deepEqual(
|
||||
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: key }),
|
||||
[],
|
||||
);
|
||||
assert.equal(lines.length, 1);
|
||||
assert.match(lines[0], /Ontario 511 camera download error/);
|
||||
assert.equal(lines[0].includes(key), false);
|
||||
assert.equal(lines[0].includes('synthetic'), false);
|
||||
assert.equal(lines[0].includes('https://'), false);
|
||||
});
|
||||
}
|
||||
|
||||
test('Ontario encodes reserved key characters and refuses credential-bearing redirects', async (t) => {
|
||||
const lines = captureConsole(t);
|
||||
const key = 'synthetic &/=% value';
|
||||
let request;
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
request = { url: new URL(url), init };
|
||||
return Response.json([ROW]);
|
||||
});
|
||||
const cameras = await loadOntarioSourcesFromOpenData(
|
||||
{},
|
||||
{ ONTARIO_511_API_KEY: key },
|
||||
);
|
||||
assert.equal(request.url.searchParams.get('key'), key);
|
||||
assert.equal(request.init.redirect, 'error');
|
||||
assert.equal(cameras.length, 1);
|
||||
assert.equal(JSON.stringify(cameras).includes('synthetic'), false);
|
||||
assert.equal(lines.join(' ').includes('synthetic'), false);
|
||||
});
|
||||
@@ -42,6 +42,8 @@ import {
|
||||
TARKTEE_IMAGES_URL,
|
||||
TARKTEE_IMAGE_ORIGIN,
|
||||
DEFAULT_TARKTEE_MAX_SOURCES,
|
||||
TARKTEE_MAX_CATALOG_BYTES,
|
||||
TARKTEE_FETCH_TIMEOUT_MS,
|
||||
TARKTEE_ANCHORS,
|
||||
DEFAULT_WARENDORF_SOURCE_FILE,
|
||||
WARENDORF_IMAGE_ORIGINS,
|
||||
@@ -55,6 +57,12 @@ import {
|
||||
DEFAULT_CALGARY_MAX_SOURCES,
|
||||
CALGARY_DOWNTOWN,
|
||||
CALGARY_MAX_CATALOG_BYTES,
|
||||
FLORIDA_CCTV_URL,
|
||||
FLORIDA_IMAGE_HOSTS,
|
||||
DEFAULT_FLORIDA_MAX_SOURCES,
|
||||
FLORIDA_ANCHORS,
|
||||
FLORIDA_MAX_CATALOG_BYTES,
|
||||
FLORIDA_MAX_CATALOG_PAGES,
|
||||
CATALONIA_CAMERAS_URL,
|
||||
CATALONIA_MAX_CATALOG_BYTES,
|
||||
CATALONIA_IMAGE_HOSTS,
|
||||
@@ -89,6 +97,19 @@ import {
|
||||
DEFAULT_VEGVESEN_MAX_SOURCES,
|
||||
VEGVESEN_MAX_CATALOG_BYTES,
|
||||
NORWAY_ANCHORS,
|
||||
KARTVERKET_HEIGHT_URL,
|
||||
KARTVERKET_MAX_POINTS,
|
||||
KARTVERKET_CONCURRENCY,
|
||||
KARTVERKET_LOOKUP_TIMEOUT_MS,
|
||||
KARTVERKET_REQUEST_TIMEOUT_MS,
|
||||
KARTVERKET_WAIT_MISSING_SHARE,
|
||||
KARTVERKET_CATALOG_WAIT_MS,
|
||||
KARTVERKET_NULL_TTL_MS,
|
||||
KARTVERKET_FAILURE_BACKOFF_MS,
|
||||
KARTVERKET_MAX_BACKOFF_MS,
|
||||
KARTVERKET_USER_AGENT,
|
||||
KARTVERKET_MAX_RESPONSE_BYTES,
|
||||
KARTVERKET_HEIGHT_RANGE_M,
|
||||
NYC_CAMERAS_URL,
|
||||
NYC_IMAGE_URL,
|
||||
NYC_CAMERA_ID_RE,
|
||||
@@ -113,6 +134,7 @@ import {
|
||||
isLikelyTexasCoordinate,
|
||||
isLikelyNswCoordinate,
|
||||
isLikelyCalgaryCoordinate,
|
||||
isLikelyFloridaCoordinate,
|
||||
isLikelyCataloniaCoordinate,
|
||||
decodeNumericEntities,
|
||||
isLikelyNycCoordinate,
|
||||
@@ -502,22 +524,57 @@ function pickOntarioCctvView(views) {
|
||||
);
|
||||
}
|
||||
|
||||
let ontarioKeyMissingLogged = false;
|
||||
|
||||
/** Test seam: let the next keyless call log the missing-key line again. */
|
||||
export function _resetOntarioKeyWarningForTest() {
|
||||
ontarioKeyMissingLogged = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Ontario 511 CCTV cameras. Keyless: the catalog is exposed by the
|
||||
* public 511 API, while frame URLs are stable still-image endpoints under
|
||||
* 511on.ca/map/Cctv/. Only rows with finite Ontario coords and at least one
|
||||
* enabled official still view are kept.
|
||||
* Fetch Ontario 511 CCTV cameras. The camera list comes from the 511 API,
|
||||
* which now requires a free developer key (511on.ca/developers/doc, "Requires a
|
||||
* developer key"; unkeyed calls answer 400 "Invalid Key"), read from
|
||||
* ONTARIO_511_API_KEY. Without one the pack is skipped with a single log line.
|
||||
* Frame URLs are stable still-image endpoints under 511on.ca/map/Cctv/. Only
|
||||
* rows with finite Ontario coords and at least one enabled official still
|
||||
* view are kept.
|
||||
*
|
||||
* @param {object} [_options] The catalog's loader options (unused).
|
||||
* @param {object} [env] Environment to read the key and the source cap from.
|
||||
* @returns {Promise<Array<object>>} Normalized camera source objects.
|
||||
*/
|
||||
export async function loadOntarioSourcesFromOpenData() {
|
||||
export async function loadOntarioSourcesFromOpenData(
|
||||
_options = {},
|
||||
env = process.env,
|
||||
) {
|
||||
const key = String(env.ONTARIO_511_API_KEY ?? '').trim();
|
||||
if (!key) {
|
||||
if (!ontarioKeyMissingLogged) {
|
||||
ontarioKeyMissingLogged = true;
|
||||
console.warn(
|
||||
'[CCTV] Ontario 511 cameras skipped: the 511on.ca API needs a free developer key (set ONTARIO_511_API_KEY)',
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const resp = await fetch(ONTARIO_511_CAMERAS_URL, {
|
||||
const url = new URL(ONTARIO_511_CAMERAS_URL);
|
||||
url.searchParams.set('key', key);
|
||||
const resp = await fetch(url, {
|
||||
headers: { Accept: 'application/json' },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
console.warn('[CCTV] Ontario 511 camera download failed:', resp.status);
|
||||
// The API answers 400 "Invalid Key" to a wrong or revoked key.
|
||||
const keyHint =
|
||||
resp.status === 400 || resp.status === 401 || resp.status === 403
|
||||
? ' (check ONTARIO_511_API_KEY)'
|
||||
: '';
|
||||
console.warn(
|
||||
`[CCTV] Ontario 511 camera download failed: ${resp.status}${keyHint}`,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
const rows = await resp.json();
|
||||
@@ -580,7 +637,7 @@ export async function loadOntarioSourcesFromOpenData() {
|
||||
new Map(cameras.map((camera) => [camera.id, camera])).values(),
|
||||
);
|
||||
const maxRaw = Number(
|
||||
process.env.CCTV_ONTARIO_MAX_SOURCES || DEFAULT_ONTARIO_MAX_SOURCES,
|
||||
env.CCTV_ONTARIO_MAX_SOURCES || DEFAULT_ONTARIO_MAX_SOURCES,
|
||||
);
|
||||
const maxCount = Number.isFinite(maxRaw)
|
||||
? Math.max(8, Math.min(1000, Math.floor(maxRaw)))
|
||||
@@ -590,10 +647,11 @@ export async function loadOntarioSourcesFromOpenData() {
|
||||
`[CCTV] Loaded Ontario 511 camera sources: ${unique.length} enabled (using nearest ${prioritized.length})`,
|
||||
);
|
||||
return prioritized;
|
||||
} catch (error) {
|
||||
} catch {
|
||||
// Transport and JSON errors may reflect the credential-bearing request.
|
||||
// Do not log upstream exception text, response bodies or URLs.
|
||||
console.warn(
|
||||
'[CCTV] Ontario 511 camera download error:',
|
||||
error?.message || error,
|
||||
'[CCTV] Ontario 511 camera download error (network or invalid response)',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
@@ -1190,28 +1248,49 @@ export function parseTarkteeDatexImages(xml) {
|
||||
* @returns {Promise<Array<object>>} Normalized camera source objects.
|
||||
*/
|
||||
export async function loadTarkteeSourcesFromDatex() {
|
||||
// Own both transports before either can reject. A response that arrives
|
||||
// after cleanup must also be discarded instead of escaping Promise.all.
|
||||
const abort = new AbortController();
|
||||
const signal = AbortSignal.any([
|
||||
abort.signal,
|
||||
AbortSignal.timeout(TARKTEE_FETCH_TIMEOUT_MS),
|
||||
]);
|
||||
const responses = [];
|
||||
const discardBoth = async () => {
|
||||
abort.abort();
|
||||
await Promise.allSettled(
|
||||
responses.map((response) => response.body?.cancel()),
|
||||
);
|
||||
return [];
|
||||
};
|
||||
const fetchXml = async (url) => {
|
||||
const response = await fetch(url, {
|
||||
headers: { Accept: 'application/xml,text/xml,*/*' },
|
||||
redirect: 'manual',
|
||||
signal,
|
||||
});
|
||||
if (signal.aborted) {
|
||||
await Promise.allSettled([response.body?.cancel()]);
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
responses.push(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
response.status >= 300 && response.status < 400
|
||||
? 'catalog redirected; redirects are not followed'
|
||||
: `catalog HTTP ${response.status}`,
|
||||
);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
try {
|
||||
const [locResp, imgResp] = await Promise.all([
|
||||
fetch(TARKTEE_LOCATIONS_URL, {
|
||||
headers: { Accept: 'application/xml,text/xml,*/*' },
|
||||
signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
|
||||
}),
|
||||
fetch(TARKTEE_IMAGES_URL, {
|
||||
headers: { Accept: 'application/xml,text/xml,*/*' },
|
||||
signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
|
||||
}),
|
||||
fetchXml(TARKTEE_LOCATIONS_URL),
|
||||
fetchXml(TARKTEE_IMAGES_URL),
|
||||
]);
|
||||
if (!locResp.ok) {
|
||||
console.warn('[CCTV] Tarktee locations download failed:', locResp.status);
|
||||
return [];
|
||||
}
|
||||
if (!imgResp.ok) {
|
||||
console.warn('[CCTV] Tarktee images download failed:', imgResp.status);
|
||||
return [];
|
||||
}
|
||||
const [locXml, imgXml] = await Promise.all([
|
||||
locResp.text(),
|
||||
imgResp.text(),
|
||||
readResponseTextCapped(locResp, TARKTEE_MAX_CATALOG_BYTES, signal),
|
||||
readResponseTextCapped(imgResp, TARKTEE_MAX_CATALOG_BYTES, signal),
|
||||
]);
|
||||
const locations = parseTarkteeDatexLocations(locXml);
|
||||
const images = parseTarkteeDatexImages(imgXml);
|
||||
@@ -1224,6 +1303,7 @@ export async function loadTarkteeSourcesFromDatex() {
|
||||
}
|
||||
|
||||
const cameras = [];
|
||||
const seen = new Set();
|
||||
for (const [locationId, loc] of locations.entries()) {
|
||||
const imageUrl = images.get(locationId);
|
||||
if (!imageUrl) continue;
|
||||
@@ -1235,6 +1315,8 @@ export async function loadTarkteeSourcesFromDatex() {
|
||||
const cameraId = numMatch
|
||||
? `ee-tarktee-${numMatch[1]}`
|
||||
: `ee-tarktee-${locationId}`;
|
||||
if (seen.has(cameraId)) continue;
|
||||
seen.add(cameraId);
|
||||
cameras.push({
|
||||
id: cameraId,
|
||||
name: loc.name,
|
||||
@@ -1270,6 +1352,7 @@ export async function loadTarkteeSourcesFromDatex() {
|
||||
);
|
||||
return prioritized;
|
||||
} catch (error) {
|
||||
await discardBoth();
|
||||
console.warn(
|
||||
'[CCTV] Tarktee DATEX download error:',
|
||||
error?.message || error,
|
||||
@@ -2386,14 +2469,11 @@ export function vegvesenCameraToSource(feature) {
|
||||
fovDeg: 44,
|
||||
rangeM: 145,
|
||||
mountHeightM: 8,
|
||||
// KNOWN LIMITATION: the feed's coordinates are 2D, so this is one flat
|
||||
// prior for the whole country, while cameras run from sea level to
|
||||
// mountain passes near 1,000 m (Haukelifjell, Sjonfjellet, Rugeldalen).
|
||||
// The point-height prior and the client's one-shot ground snap correct it
|
||||
// where they resolve; on a stack where neither does (no 3D tiles), a pass
|
||||
// camera stays hundreds of metres below the terrain, the same risk the
|
||||
// Caltrans pack documents. A per-camera height (e.g. Kartverket's keyless
|
||||
// point-height API) would remove it.
|
||||
// The feed's coordinates are 2D. The loader replaces this flat prior with
|
||||
// Kartverket's terrain height for each camera (applyVegvesenGroundHeights);
|
||||
// it only survives when that lookup fails, and then a mountain-pass camera
|
||||
// can sit below the terrain on a stack without 3D tiles, the same risk the
|
||||
// Caltrans pack documents.
|
||||
groundElevationM: 150,
|
||||
feedType: videoUrl ? 'hls' : 'image',
|
||||
url: videoUrl || imageUrl,
|
||||
@@ -2413,6 +2493,7 @@ export function vegvesenCameraToSource(feature) {
|
||||
* @returns {Promise<Array<object>>} Normalized camera source objects.
|
||||
*/
|
||||
export async function loadVegvesenSourcesFromOpenData() {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const endpoint = process.env.CCTV_VEGVESEN_URL || DEFAULT_VEGVESEN_CCTV_URL;
|
||||
const resp = await fetch(endpoint, {
|
||||
@@ -2458,6 +2539,12 @@ export async function loadVegvesenSourcesFromOpenData() {
|
||||
? Math.max(8, Math.min(1000, Math.floor(maxRaw)))
|
||||
: DEFAULT_VEGVESEN_MAX_SOURCES;
|
||||
const prioritized = prioritizeSources(cameras, maxCount, NORWAY_ANCHORS);
|
||||
await applyVegvesenGroundHeights(prioritized, {
|
||||
waitMs: Math.max(
|
||||
0,
|
||||
KARTVERKET_CATALOG_WAIT_MS - (Date.now() - startedAt),
|
||||
),
|
||||
});
|
||||
console.log(
|
||||
`[CCTV] Loaded Vegvesen camera sources: ${cameras.length} (using nearest ${prioritized.length})`,
|
||||
);
|
||||
@@ -2471,6 +2558,322 @@ export async function loadVegvesenSourcesFromOpenData() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kartverket answers by rounded position: `{z, expires}`, where z is metres or
|
||||
* null for "no height there". Heights never expire (camera positions barely
|
||||
* change); nulls expire after KARTVERKET_NULL_TTL_MS. The 15-minute catalog
|
||||
* refresh therefore only asks about new or moved cameras. Bounded well above
|
||||
* the ~900 cameras the pack can load.
|
||||
*/
|
||||
const kartverketHeightCache = new Map();
|
||||
const KARTVERKET_CACHE_LIMIT = 5000;
|
||||
/** The lookup in flight, so overlapping catalog loads never start a second. */
|
||||
let kartverketPending = null;
|
||||
/** No lookup starts before this time (epoch ms) after a transport failure. */
|
||||
let kartverketBackoffUntil = 0;
|
||||
/** Bumped by clearKartverketHeightCache, so a lookup started before a clear
|
||||
* can no longer write to the cache, the backoff or the pending slot. */
|
||||
let kartverketGeneration = 0;
|
||||
|
||||
/** Cache key for one position, at the ~0.1 m precision the request sends. */
|
||||
const kartverketKey = (lon, lat) => `${lon.toFixed(6)},${lat.toFixed(6)}`;
|
||||
|
||||
/** Statuses that say the service, not the request, is failing. */
|
||||
const isKartverketTransportStatus = (status) =>
|
||||
status === 408 || status === 429 || status >= 500;
|
||||
|
||||
/** Forget cached heights, the backoff and any lookup in flight. Tests only. */
|
||||
export function clearKartverketHeightCache() {
|
||||
kartverketGeneration += 1;
|
||||
kartverketHeightCache.clear();
|
||||
kartverketPending = null;
|
||||
kartverketBackoffUntil = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to back off after a failed request: the Retry-After the service
|
||||
* sent (seconds or an HTTP date), else the default, bounded to [1 min, 1 h].
|
||||
*
|
||||
* @param {?string} retryAfter - The Retry-After header, if any.
|
||||
* @param {number} now - Epoch ms.
|
||||
* @returns {number} Milliseconds.
|
||||
*/
|
||||
export function kartverketBackoffMs(retryAfter, now = Date.now()) {
|
||||
let ms = KARTVERKET_FAILURE_BACKOFF_MS;
|
||||
const text = String(retryAfter ?? '').trim();
|
||||
if (/^\d+$/.test(text)) ms = Number(text) * 1000;
|
||||
else if (text && Number.isFinite(Date.parse(text))) {
|
||||
ms = Date.parse(text) - now;
|
||||
}
|
||||
return Math.max(60 * 1000, Math.min(KARTVERKET_MAX_BACKOFF_MS, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Terrain heights above sea level (NN2000) from Kartverket's keyless
|
||||
* point-height API, KARTVERKET_MAX_POINTS points per request. Each answer is
|
||||
* matched back by the coordinates the API echoes, and only for points that
|
||||
* request asked about, then reported through `into.set(key, z)` as its
|
||||
* request lands, so a caller that stops waiting keeps what has arrived. `z` is
|
||||
* metres, or null when the API has no usable height there. A point a 200
|
||||
* answer leaves out is reported as null too, so it is not asked again on
|
||||
* every refresh.
|
||||
*
|
||||
* Over water `/punkt` returns the depth of the sea floor (`datakilde:
|
||||
* dybdekurver`, `terreng: Havflate`; −547 m under Nordhordlandsbrua). Either
|
||||
* marker counts as 0 m, the water surface. For the ~14 bridge cameras that is
|
||||
* below the deck, but far closer than the sea floor or a flat prior.
|
||||
*
|
||||
* The first transport failure (a 408, 429 or 5xx, a network error, a request
|
||||
* past KARTVERKET_REQUEST_TIMEOUT_MS, an unreadable or oversized body, or the
|
||||
* shared deadline) stops the lookup: no further requests start, and the
|
||||
* failure is returned so the caller can back off. Points in failed requests
|
||||
* are not reported, so they are asked again later. Any other 4xx rejects that
|
||||
* request's points, not the service: they are reported as null and the lookup
|
||||
* carries on.
|
||||
*
|
||||
* @param {Array<{lon:number, lat:number}>} points
|
||||
* @param {{into?: {set: Function}, timeoutMs?: number, requestTimeoutMs?: number}} [options]
|
||||
* @returns {Promise<{heights: Map<string, ?number>, failure: ?{status: ?number, retryAfter: ?string, deadline: boolean}}>}
|
||||
* `heights` is `into` when it is a Map, else a Map of what was reported.
|
||||
* `failure.deadline` is true when only the shared deadline ran out.
|
||||
*/
|
||||
export async function fetchKartverketHeights(
|
||||
points,
|
||||
{
|
||||
into = new Map(),
|
||||
timeoutMs = KARTVERKET_LOOKUP_TIMEOUT_MS,
|
||||
requestTimeoutMs = KARTVERKET_REQUEST_TIMEOUT_MS,
|
||||
} = {},
|
||||
) {
|
||||
const heights = into instanceof Map ? into : new Map();
|
||||
const report = (key, z) => {
|
||||
if (heights !== into) heights.set(key, z);
|
||||
into.set(key, z);
|
||||
};
|
||||
const unique = Array.from(
|
||||
new Map(
|
||||
(points || [])
|
||||
.filter((p) => isLikelyNorwayCoordinate(p?.lat, p?.lon))
|
||||
.map((p) => [kartverketKey(p.lon, p.lat), p]),
|
||||
).values(),
|
||||
);
|
||||
let failure = null;
|
||||
if (!unique.length) return { heights, failure };
|
||||
const batches = [];
|
||||
for (let i = 0; i < unique.length; i += KARTVERKET_MAX_POINTS) {
|
||||
batches.push(unique.slice(i, i + KARTVERKET_MAX_POINTS));
|
||||
}
|
||||
const deadline = AbortSignal.timeout(timeoutMs);
|
||||
const fetchBatch = async (batch) => {
|
||||
const asked = new Set(batch.map((p) => kartverketKey(p.lon, p.lat)));
|
||||
const url = new URL(KARTVERKET_HEIGHT_URL);
|
||||
url.searchParams.set(
|
||||
'punkter',
|
||||
JSON.stringify(
|
||||
batch.map((p) => [Number(p.lon.toFixed(6)), Number(p.lat.toFixed(6))]),
|
||||
),
|
||||
);
|
||||
url.searchParams.set('koordsys', '4258');
|
||||
const resp = await fetch(url, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'User-Agent': KARTVERKET_USER_AGENT,
|
||||
},
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.any([
|
||||
deadline,
|
||||
AbortSignal.timeout(requestTimeoutMs),
|
||||
]),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
try {
|
||||
await resp.body?.cancel();
|
||||
} catch {
|
||||
/* no-op */
|
||||
}
|
||||
if (!isKartverketTransportStatus(resp.status)) {
|
||||
console.warn(
|
||||
`[CCTV] Kartverket rejected ${asked.size} points: HTTP ${resp.status}`,
|
||||
);
|
||||
for (const key of asked) report(key, null);
|
||||
return;
|
||||
}
|
||||
const error = new Error(`HTTP ${resp.status}`);
|
||||
error.status = resp.status;
|
||||
error.retryAfter = resp.headers.get('retry-after');
|
||||
throw error;
|
||||
}
|
||||
const payload = await readResponseJsonCapped(
|
||||
resp,
|
||||
KARTVERKET_MAX_RESPONSE_BYTES,
|
||||
);
|
||||
for (const point of Array.isArray(payload?.punkter)
|
||||
? payload.punkter
|
||||
: []) {
|
||||
const x = toFiniteNumber(point?.x);
|
||||
const y = toFiniteNumber(point?.y);
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
const key = kartverketKey(x, y);
|
||||
// Only the points this request asked about: an odd answer can neither
|
||||
// grow the cache nor overwrite another camera.
|
||||
if (!asked.has(key)) continue;
|
||||
asked.delete(key);
|
||||
// `z: null` means no height there; Number(null) would read 0.
|
||||
const raw = point?.z;
|
||||
let z =
|
||||
raw === null || raw === undefined || raw === ''
|
||||
? NaN
|
||||
: toFiniteNumber(raw);
|
||||
if (
|
||||
Number.isFinite(z) &&
|
||||
(point?.datakilde === 'dybdekurver' || point?.terreng === 'Havflate')
|
||||
) {
|
||||
z = 0;
|
||||
}
|
||||
const usable =
|
||||
Number.isFinite(z) &&
|
||||
z >= KARTVERKET_HEIGHT_RANGE_M.min &&
|
||||
z <= KARTVERKET_HEIGHT_RANGE_M.max;
|
||||
report(key, usable ? z : null);
|
||||
}
|
||||
// A 200 that leaves a point out has no height for it either.
|
||||
for (const key of asked) report(key, null);
|
||||
};
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < batches.length && !failure) {
|
||||
const batch = batches[next++];
|
||||
try {
|
||||
await fetchBatch(batch);
|
||||
} catch (error) {
|
||||
if (!failure) {
|
||||
failure = {
|
||||
status: Number.isFinite(error?.status) ? error.status : null,
|
||||
retryAfter: error?.retryAfter ?? null,
|
||||
deadline: deadline.aborted,
|
||||
};
|
||||
console.warn(
|
||||
'[CCTV] Kartverket height lookup failed:',
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(
|
||||
Array.from(
|
||||
{ length: Math.min(KARTVERKET_CONCURRENCY, batches.length) },
|
||||
worker,
|
||||
),
|
||||
);
|
||||
return { heights, failure };
|
||||
}
|
||||
|
||||
/**
|
||||
* Give each Vegvesen camera its own terrain height as the ground prior, in
|
||||
* place. Waits at most `waitMs` for positions it has no answer for, and only
|
||||
* when more than KARTVERKET_WAIT_MISSING_SHARE of the cameras are missing
|
||||
* (a cold cache); a few new cameras or expired misses are looked up in the
|
||||
* background. A lookup still running when the wait ends keeps filling the
|
||||
* cache for the next catalog refresh. Cameras without a height keep the flat
|
||||
* prior. After a transport failure no lookup starts until the backoff ends,
|
||||
* which outlasts the 15-minute catalog refresh, so a failing Kartverket costs
|
||||
* one attempt per backoff, not one per refresh. A lookup cut short only by its
|
||||
* shared deadline is resumed on the next refresh without a backoff. Cameras
|
||||
* without finite coordinates are skipped. Never throws.
|
||||
* CCTV_VEGVESEN_HEIGHTS=0 turns it off.
|
||||
*
|
||||
* @param {Array<object>} cameras - Sources from vegvesenCameraToSource().
|
||||
* @param {{waitMs?: number, now?: () => number, timeoutMs?: number}} [options]
|
||||
* `timeoutMs` is the lookup's shared deadline.
|
||||
* @returns {Promise<number>} How many cameras got a terrain height.
|
||||
*/
|
||||
export async function applyVegvesenGroundHeights(
|
||||
cameras,
|
||||
{
|
||||
waitMs = KARTVERKET_CATALOG_WAIT_MS,
|
||||
now = Date.now,
|
||||
timeoutMs = KARTVERKET_LOOKUP_TIMEOUT_MS,
|
||||
} = {},
|
||||
) {
|
||||
if (String(process.env.CCTV_VEGVESEN_HEIGHTS || '1').trim() === '0') return 0;
|
||||
const list = (Array.isArray(cameras) ? cameras : []).filter(
|
||||
(c) => Number.isFinite(c?.lon) && Number.isFinite(c?.lat),
|
||||
);
|
||||
const startedAt = now();
|
||||
const missing = list.filter((c) => {
|
||||
const entry = kartverketHeightCache.get(kartverketKey(c.lon, c.lat));
|
||||
return !entry || entry.expires <= startedAt;
|
||||
});
|
||||
if (
|
||||
missing.length &&
|
||||
!kartverketPending &&
|
||||
startedAt >= kartverketBackoffUntil
|
||||
) {
|
||||
if (kartverketHeightCache.size + missing.length > KARTVERKET_CACHE_LIMIT) {
|
||||
kartverketHeightCache.clear();
|
||||
}
|
||||
const generation = kartverketGeneration;
|
||||
const current = () => generation === kartverketGeneration;
|
||||
const sink = {
|
||||
set: (key, z) => {
|
||||
if (!current()) return;
|
||||
kartverketHeightCache.set(key, {
|
||||
z,
|
||||
expires: z === null ? now() + KARTVERKET_NULL_TTL_MS : Infinity,
|
||||
});
|
||||
},
|
||||
};
|
||||
const pending = fetchKartverketHeights(missing, { into: sink, timeoutMs })
|
||||
.then(({ failure }) => {
|
||||
if (failure && !failure.deadline && current()) {
|
||||
kartverketBackoffUntil =
|
||||
now() + kartverketBackoffMs(failure.retryAfter, now());
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (current()) {
|
||||
kartverketBackoffUntil = now() + KARTVERKET_FAILURE_BACKOFF_MS;
|
||||
}
|
||||
console.warn(
|
||||
'[CCTV] Kartverket height lookup error:',
|
||||
error?.message || error,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (kartverketPending === pending) kartverketPending = null;
|
||||
});
|
||||
kartverketPending = pending;
|
||||
}
|
||||
const cold = missing.length > list.length * KARTVERKET_WAIT_MISSING_SHARE;
|
||||
if (cold && kartverketPending && waitMs > 0) {
|
||||
let timer;
|
||||
await Promise.race([
|
||||
kartverketPending,
|
||||
new Promise((resolve) => {
|
||||
timer = setTimeout(resolve, waitMs);
|
||||
timer.unref?.();
|
||||
}),
|
||||
]);
|
||||
clearTimeout(timer);
|
||||
}
|
||||
let applied = 0;
|
||||
for (const camera of list) {
|
||||
const z = kartverketHeightCache.get(
|
||||
kartverketKey(camera.lon, camera.lat),
|
||||
)?.z;
|
||||
if (!Number.isFinite(z)) continue;
|
||||
camera.groundElevationM = Math.round(z * 10) / 10;
|
||||
applied += 1;
|
||||
}
|
||||
if (list.length) {
|
||||
console.log(
|
||||
`[CCTV] Kartverket ground heights: ${applied}/${list.length} Vegvesen cameras`,
|
||||
);
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
const NYC_BOROUGHS = new Set([
|
||||
'Manhattan',
|
||||
'Brooklyn',
|
||||
@@ -2784,3 +3187,203 @@ export async function loadTorontoSourcesFromOpenData() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** FL511 DIRECTION codes as headings; "NOT DIRECTIONAL" has none. */
|
||||
const FLORIDA_DIRECTION_HEADINGS = Object.freeze({
|
||||
N: 0,
|
||||
E: 90,
|
||||
S: 180,
|
||||
W: 270,
|
||||
});
|
||||
|
||||
/**
|
||||
* Stable camera id from a frame URL. FL511's ID column repeats across regions
|
||||
* (ID 1220 is both an I-75 and an I-95 camera), so the image channel is the
|
||||
* key, as Calgary keys on its frame filename. Falls back to a path slug.
|
||||
*
|
||||
* @param {string} imageUrl - A host-pinned FL511 frame URL.
|
||||
* @returns {?string} Provider-stable id, or null when underivable.
|
||||
*/
|
||||
export function floridaCameraId(imageUrl) {
|
||||
let path;
|
||||
try {
|
||||
path = new URL(String(imageUrl ?? '')).pathname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const channel = /\/chan-(\d+)_[a-z]+\.jpg$/i.exec(path);
|
||||
if (channel) return `fl-${channel[1]}`;
|
||||
const slug = path
|
||||
.replace(/^\/+|\.[a-z0-9]+$/gi, '')
|
||||
.replace(/[^a-zA-Z0-9]+/g, '-')
|
||||
.toLowerCase();
|
||||
return slug ? `fl-${slug}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One FL511 ArcGIS feature -> one catalog source, or null. DIRECTION is a
|
||||
* one-letter code the free-text parser won't read, so a table maps it.
|
||||
*
|
||||
* @param {object} feature - ArcGIS feature from the FL511 camera layer.
|
||||
* @returns {?object}
|
||||
*/
|
||||
export function floridaCameraToSource(feature) {
|
||||
const a = feature?.attributes;
|
||||
if (!a || typeof a !== 'object') return null;
|
||||
const lat = toFiniteNumber(a.LATITUDE);
|
||||
const lon = toFiniteNumber(a.LONGITUDE);
|
||||
if (!isLikelyFloridaCoordinate(lat, lon)) return null;
|
||||
|
||||
const imageUrl = String(a.IMAGE || '');
|
||||
let image;
|
||||
try {
|
||||
image = new URL(imageUrl);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
// Official image hosts only, HTTPS, no embedded credentials.
|
||||
if (
|
||||
image.protocol !== 'https:' ||
|
||||
!FLORIDA_IMAGE_HOSTS.includes(image.host) ||
|
||||
image.username ||
|
||||
image.password
|
||||
)
|
||||
return null;
|
||||
|
||||
const cameraId = floridaCameraId(imageUrl);
|
||||
if (!cameraId) return null;
|
||||
|
||||
const heading =
|
||||
FLORIDA_DIRECTION_HEADINGS[
|
||||
String(a.DIRECTION || '')
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
];
|
||||
const hasHeading = Number.isFinite(heading);
|
||||
|
||||
return {
|
||||
id: cameraId,
|
||||
name: String(a.DESCRIPT || '').trim() || `FL511 ${cameraId.slice(3)}`,
|
||||
city: String(a.COUNTY ? `${a.COUNTY} County` : 'Florida'),
|
||||
cityId: 'florida',
|
||||
provider: 'FL511',
|
||||
lat,
|
||||
lon,
|
||||
headingDeg: hasHeading ? heading : fallbackHeadingFromId(cameraId),
|
||||
headingConfidence: hasHeading ? 'high' : 'low',
|
||||
pitchDeg: hasHeading ? -24 : -18,
|
||||
fovDeg: hasHeading ? 56 : 44,
|
||||
rangeM: hasHeading ? 210 : 145,
|
||||
mountHeightM: hasHeading ? 10 : 8,
|
||||
groundElevationM: 5, // Coastal prior; the client's ground snap corrects.
|
||||
feedType: 'image',
|
||||
url: imageUrl,
|
||||
snapshotUrl: imageUrl,
|
||||
sourceKind: 'fl511-open-data',
|
||||
license:
|
||||
'FL511 (FDOT), individual personal use only; other use needs FDOT written consent',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch FL511 (Florida DOT) cameras, keyless: an ArcGIS FeatureServer paged
|
||||
* up to 2,000 rows at a time, ordered by the layer's object id so offsets are
|
||||
* stable. Paging follows `exceededTransferLimit` and advances by the rows each
|
||||
* page returned, so a lower server-side max record count still reads the whole
|
||||
* layer. Frames are stills on the Divas Cloud hosts. A redirect on any page
|
||||
* drops the pack; any other failed page keeps the rows already read.
|
||||
*
|
||||
* @returns {Promise<Array<object>>} Normalized camera source objects.
|
||||
*/
|
||||
export async function loadFloridaSourcesFromOpenData() {
|
||||
try {
|
||||
const cameras = [];
|
||||
const seen = new Set();
|
||||
const pageSize = 2000;
|
||||
let offset = 0;
|
||||
// Page ceiling, in case the service ignores resultOffset.
|
||||
for (let page = 0; ; page += 1) {
|
||||
if (page >= FLORIDA_MAX_CATALOG_PAGES) {
|
||||
console.warn(
|
||||
`[CCTV] Florida catalog stopped at the ${FLORIDA_MAX_CATALOG_PAGES}-page ceiling; the catalog may be incomplete`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
// OBJECTID_1 is this layer's object id field (a plain OBJECTID is a 400).
|
||||
const url = `${FLORIDA_CCTV_URL}?where=1%3D1&outFields=*&orderByFields=OBJECTID_1&f=json&resultRecordCount=${pageSize}&resultOffset=${offset}`;
|
||||
let resp;
|
||||
try {
|
||||
resp = await fetch(url, {
|
||||
headers: { Accept: 'application/json' },
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[CCTV] Florida catalog page failed:',
|
||||
error?.message || error,
|
||||
);
|
||||
break;
|
||||
}
|
||||
// Release the body on every path that will not read it.
|
||||
const discard = async () => {
|
||||
try {
|
||||
await resp.body?.cancel();
|
||||
} catch {
|
||||
/* no-op */
|
||||
}
|
||||
};
|
||||
if (resp.status >= 300 && resp.status < 400) {
|
||||
console.warn(
|
||||
'[CCTV] Florida catalog redirected; redirects are not followed',
|
||||
);
|
||||
await discard();
|
||||
return [];
|
||||
}
|
||||
if (!resp.ok) {
|
||||
console.warn('[CCTV] Florida camera download failed:', resp.status);
|
||||
await discard();
|
||||
break;
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
body = await readResponseJsonCapped(resp, FLORIDA_MAX_CATALOG_BYTES);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[CCTV] Florida catalog page unreadable:',
|
||||
error?.message || error,
|
||||
);
|
||||
break;
|
||||
}
|
||||
const feats = Array.isArray(body?.features) ? body.features : [];
|
||||
for (const feature of feats) {
|
||||
const camera = floridaCameraToSource(feature);
|
||||
if (!camera || seen.has(camera.id)) continue;
|
||||
seen.add(camera.id);
|
||||
cameras.push(camera);
|
||||
}
|
||||
// ArcGIS sets exceededTransferLimit while more rows remain. A page may
|
||||
// be shorter than pageSize when the layer's max record count is lower.
|
||||
if (body?.exceededTransferLimit !== true || feats.length === 0) break;
|
||||
offset += feats.length;
|
||||
}
|
||||
|
||||
const maxRaw = Number(
|
||||
process.env.CCTV_FLORIDA_MAX_SOURCES || DEFAULT_FLORIDA_MAX_SOURCES,
|
||||
);
|
||||
const maxCount = Number.isFinite(maxRaw)
|
||||
? Math.max(8, Math.min(4200, Math.floor(maxRaw)))
|
||||
: DEFAULT_FLORIDA_MAX_SOURCES;
|
||||
const prioritized = prioritizeSources(cameras, maxCount, FLORIDA_ANCHORS);
|
||||
console.log(
|
||||
`[CCTV] Loaded Florida camera sources: ${cameras.length} (using nearest ${prioritized.length})`,
|
||||
);
|
||||
return prioritized;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[CCTV] Florida camera download error:',
|
||||
error?.message || error,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,34 @@ async function readRequestBodyCapped(req, maxBytes) {
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
function readRequestBody(req, maxBytes = 1024 * 1024) {
|
||||
/** Optional cancellation discards buffered data while the request drains. */
|
||||
function readRequestBody(req, maxBytes = 1024 * 1024, signal) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let total = 0;
|
||||
let bodyTooLarge = false;
|
||||
let settled = false;
|
||||
const chunks = [];
|
||||
req.on('data', (chunk) => {
|
||||
const stopReading = () => {
|
||||
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
|
||||
// the request also destroys its socket, so the handler cannot deliver
|
||||
// the fixed error response it constructs for BODY_TOO_LARGE.
|
||||
if (bodyTooLarge) return;
|
||||
if (bodyTooLarge || settled) return;
|
||||
total += chunk.length;
|
||||
if (total > maxBytes) {
|
||||
// Same marker readRequestBodyCapped sets, so a caller can tell an
|
||||
@@ -32,15 +50,42 @@ function readRequestBody(req, maxBytes = 1024 * 1024) {
|
||||
chunks.length = 0;
|
||||
const error = new Error(`Request body exceeds ${maxBytes} bytes`);
|
||||
error.code = 'BODY_TOO_LARGE';
|
||||
reject(error);
|
||||
fail(error);
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => {
|
||||
};
|
||||
const end = () => {
|
||||
if (settled) {
|
||||
stopReading();
|
||||
return;
|
||||
}
|
||||
if (!bodyTooLarge) resolve(Buffer.concat(chunks).toString('utf8'));
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (signal) {
|
||||
settled = true;
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
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);
|
||||
});
|
||||
@@ -41,3 +41,48 @@ export function sameSiteGated(handler) {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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 };
|
||||
@@ -0,0 +1,53 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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');
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { adsbLolProxy } from './aircraft/adsb-lol.js';
|
||||
import { aisLiveProxy } from './vessels/ais-live.js';
|
||||
import { trackBackfillProxies } from './aircraft/tracks.js';
|
||||
import { openAiRealtimeProxy } from './openai.js';
|
||||
import { geminiLiveProxy } from './gemini.js';
|
||||
import { googlePlacesContextProxy } from './places.js';
|
||||
import { mapillaryProxy } from './mapillary.js';
|
||||
import { keySetupEndpoint } from '../standalone/key-setup.js';
|
||||
@@ -30,9 +31,9 @@ import { windProxy } from './wind.js';
|
||||
|
||||
/**
|
||||
* Construct the local provider plugins in their established order.
|
||||
* `realtime` configures the voice session token endpoint.
|
||||
* `realtime` configures OpenAI; `gemini` explicitly opts into Gemini Live.
|
||||
*/
|
||||
function localProviderPlugins({ realtime } = {}) {
|
||||
function localProviderPlugins({ realtime, gemini } = {}) {
|
||||
return [
|
||||
openSkyProxy(),
|
||||
celestrakProxy(),
|
||||
@@ -55,6 +56,7 @@ function localProviderPlugins({ realtime } = {}) {
|
||||
aisLiveProxy(),
|
||||
trackBackfillProxies(),
|
||||
openAiRealtimeProxy({ realtime }),
|
||||
...(gemini ? [geminiLiveProxy({ realtime: gemini })] : []),
|
||||
googlePlacesContextProxy(),
|
||||
windProxy(),
|
||||
weatherProxy(),
|
||||
|
||||
@@ -13,6 +13,8 @@ export function launchLibraryRequestHeaders(token = process.env.LL2_API_TOKEN) {
|
||||
const normalized = String(token || '').trim();
|
||||
return {
|
||||
Accept: 'application/json',
|
||||
'User-Agent':
|
||||
'gods-eye-view-launch-library-proxy/1.0 (+https://github.com/bilawalsidhu/gods-eye-view)',
|
||||
...(normalized ? { Authorization: `Token ${normalized}` } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
terrainPointKey,
|
||||
validTerrainResult,
|
||||
} 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
|
||||
@@ -20,11 +22,31 @@ import {
|
||||
* Only missing/stale points go upstream; the response is rebuilt in exact
|
||||
* request order. Larger requests are chunked sequentially, and one failing
|
||||
* 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() {
|
||||
export function terrainHeightsProxy(options = {}) {
|
||||
// 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 CACHE_DIR = path.join(process.cwd(), '.gev-cache');
|
||||
const CACHE_PATH = path.join(CACHE_DIR, 'terrain-heights.json');
|
||||
const CACHE_PATH =
|
||||
cachePath || path.join(process.cwd(), '.gev-cache', 'terrain-heights.json');
|
||||
const CACHE_DIR = path.dirname(CACHE_PATH);
|
||||
// Sized against measured upstream latency, not the documented page cap.
|
||||
// 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
|
||||
@@ -34,9 +56,50 @@ export function terrainHeightsProxy() {
|
||||
// that range.
|
||||
const UPSTREAM_CHUNK = 64;
|
||||
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. */
|
||||
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. */
|
||||
const inflight = new Map();
|
||||
let diskLoaded = false;
|
||||
@@ -47,6 +110,21 @@ export function terrainHeightsProxy() {
|
||||
if (diskLoaded) return;
|
||||
diskLoaded = true;
|
||||
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 pointEntries =
|
||||
parsed?.version === 2 &&
|
||||
@@ -87,6 +165,7 @@ export function terrainHeightsProxy() {
|
||||
}
|
||||
diskDirty = mem.size > 0;
|
||||
}
|
||||
evictOverflow();
|
||||
} catch {
|
||||
/* no disk cache yet */
|
||||
}
|
||||
@@ -157,12 +236,25 @@ export function terrainHeightsProxy() {
|
||||
|
||||
const installMiddleware = (server) => {
|
||||
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) => {
|
||||
if (res.headersSent) return;
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(bodyObj));
|
||||
};
|
||||
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();
|
||||
const parsedUrl = new URL(req.url || '', 'http://internal');
|
||||
const rawPoints = parsedUrl.searchParams.get('points');
|
||||
@@ -187,7 +279,10 @@ export function terrainHeightsProxy() {
|
||||
fetchMissing: fetchMissingSingleFlight,
|
||||
ttlMs: TTL_MS,
|
||||
});
|
||||
if (outcome.cacheChanged) diskDirty = true;
|
||||
if (outcome.cacheChanged) {
|
||||
evictOverflow();
|
||||
diskDirty = true;
|
||||
}
|
||||
if (outcome.upstreamError) {
|
||||
console.warn(
|
||||
'[terrain-heights-proxy] refresh incomplete' +
|
||||
|
||||
@@ -7,7 +7,6 @@ import { localMcpPlugin } from '../mcp/plugin.js';
|
||||
import { apiNotFoundPlugin } from './api-not-found.js';
|
||||
import { standaloneVoiceTools } from './voiceTools.js';
|
||||
import { unwatchedRuntimeDirsPlugin } from './unwatched-cache.js';
|
||||
import { vcamPlugin } from '../vcam/plugin.js';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
|
||||
@@ -17,11 +16,11 @@ export default defineConfig(({ command, mode }) => {
|
||||
for (const [key, value] of Object.entries(loaded)) {
|
||||
if (process.env[key] === undefined) process.env[key] = value;
|
||||
}
|
||||
const tools = standaloneVoiceTools();
|
||||
return createBrowserViteConfig({
|
||||
plugins: [
|
||||
...localProviderPlugins({ realtime: { tools: standaloneVoiceTools() } }),
|
||||
...localProviderPlugins({ realtime: { tools }, gemini: { tools } }),
|
||||
localMcpPlugin(),
|
||||
vcamPlugin(),
|
||||
apiNotFoundPlugin(),
|
||||
unwatchedRuntimeDirsPlugin(),
|
||||
],
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 343 B |
@@ -1,154 +0,0 @@
|
||||
<!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 & 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>
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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');
|
||||
});
|
||||
@@ -1,371 +0,0 @@
|
||||
: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;
|
||||
}
|
||||
}
|
||||
@@ -1,770 +0,0 @@
|
||||
/**
|
||||
* 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();
|
||||
@@ -1,522 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
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'],
|
||||
);
|
||||
});
|
||||
@@ -1,319 +0,0 @@
|
||||
/**
|
||||
* 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');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
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');
|
||||
});
|
||||
@@ -1,237 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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 },
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
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/);
|
||||
});
|
||||
@@ -1,7 +1,4 @@
|
||||
import { SceneDirector } from '../scenes/director.js';
|
||||
import { createCameraLens } from '../scenes/cameraLens.js';
|
||||
import { createVcamController } from '../vcam/controller.js';
|
||||
import { bindVcamPanel } from '../ui/vcamPanel.js';
|
||||
import { initAnnotations } from '../annotations/index.js';
|
||||
import { initDrawTool } from '../annotations/drawTool.js';
|
||||
import { initGeoFileImport } from '../ui/geoFileImport.js';
|
||||
@@ -35,36 +32,16 @@ export function createApplicationTools({
|
||||
const { viewer, tileset, mapStackController, operations } = scene;
|
||||
const { styleManager, weatherEffects, cockpitCloudEffects } = controls;
|
||||
const { dataManager } = data;
|
||||
// Focal length and depth of field, shared by scene playback and the VCAM.
|
||||
const lens = createCameraLens(viewer, {
|
||||
requestRender: (reason) => governorRequestRender(reason),
|
||||
});
|
||||
const sceneDirector = new SceneDirector(viewer, styleManager, dataManager, {
|
||||
dataPacks: sceneDataPacks,
|
||||
isMapStackAvailable: (id) =>
|
||||
mapStackController?.isStackAvailable(id) === true,
|
||||
lens,
|
||||
});
|
||||
dataManager.layers
|
||||
.get('bhote-koshi-2026')
|
||||
?.module.attachSceneController(sceneDirector);
|
||||
defer(() => sceneDirector.destroy());
|
||||
onSceneDirector?.(sceneDirector);
|
||||
// SCENES ▸ VCAM: a phone on the same network becomes the camera; its
|
||||
// takes are recorded into the selected scene. Torn down before the lens
|
||||
// and director it drives.
|
||||
const vcam = createVcamController({
|
||||
viewer,
|
||||
navigation: styleManager,
|
||||
director: sceneDirector,
|
||||
lens,
|
||||
});
|
||||
const unbindVcamPanel = bindVcamPanel(vcam);
|
||||
defer(() => lens.destroy());
|
||||
defer(() => {
|
||||
unbindVcamPanel();
|
||||
vcam.destroy();
|
||||
});
|
||||
const annotations = initAnnotations({
|
||||
viewer,
|
||||
tileset,
|
||||
@@ -189,8 +166,6 @@ export function createApplicationTools({
|
||||
getRenderGovernorDiagnostics,
|
||||
surfaceServices: operations.surface,
|
||||
requestRender: governorRequestRender,
|
||||
vcam,
|
||||
lens,
|
||||
};
|
||||
const debug = window.__godsEyeView;
|
||||
defer(() => {
|
||||
|
||||
@@ -77,6 +77,11 @@ import {
|
||||
CCTV_FOCUS_REQUEST_EVENT,
|
||||
activateCctvCameraFromWorldClick,
|
||||
} from '../cctvFocusRequest.js';
|
||||
import {
|
||||
ACTIVE_CAMERA_COLOR,
|
||||
IDLE_CAMERA_COLOR,
|
||||
LIVE_CAMERA_COLOR,
|
||||
} from '../layers/cctv/policy.js';
|
||||
|
||||
const CCTV_PRESENTATION_SOURCE = fs.readFileSync(
|
||||
path.join(
|
||||
@@ -360,6 +365,37 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
|
||||
}
|
||||
});
|
||||
|
||||
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
|
||||
const record = (id, feedType) => ({
|
||||
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
|
||||
billboard: {},
|
||||
coverageEntities: [],
|
||||
projection: null,
|
||||
});
|
||||
const idleVideo = record('idle-hls', 'hls');
|
||||
const idleStill = record('idle-image', 'image');
|
||||
const activeVideo = record('active-hls', 'hls');
|
||||
const viewer = { entities: { add: (entity) => entity } };
|
||||
|
||||
try {
|
||||
// Disabled keeps the active video camera from opening a real projection;
|
||||
// icon colors are assigned either way.
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer,
|
||||
records: [idleVideo, idleStill, activeVideo],
|
||||
activeCameraId: activeVideo.camera.id,
|
||||
enabled: false,
|
||||
coverageMode: 'off',
|
||||
});
|
||||
refreshCoverageStyles();
|
||||
assert.equal(idleVideo.billboard.color, LIVE_CAMERA_COLOR);
|
||||
assert.equal(idleStill.billboard.color, IDLE_CAMERA_COLOR);
|
||||
assert.equal(activeVideo.billboard.color, ACTIVE_CAMERA_COLOR);
|
||||
} finally {
|
||||
_setCctvCoverageStateForTest({ enabled: false });
|
||||
}
|
||||
});
|
||||
|
||||
test('geometry drain pacing yields to tracked and cockpit camera ownership', () => {
|
||||
assert.deepEqual(cctvGeometryDrainPacing(), { batchSize: 4, delayMs: 120 });
|
||||
assert.deepEqual(
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from '../../server/providers/cctv/cap.js';
|
||||
import {
|
||||
CCTV_MAX_SOURCES_CEILING,
|
||||
CCTV_SOURCE_CACHE_MS,
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
@@ -160,3 +161,224 @@ test('a pack trimmed to its nearest cameras reports how many it offered', async
|
||||
assert.equal(kept.available, 5);
|
||||
assert.deepEqual(kept.region, { west: 0, south: 0, east: 0, north: 4 });
|
||||
});
|
||||
|
||||
/** A CCTV_SOURCES_JSON value with `count` cameras named `<prefix>-<i>`. */
|
||||
const envSources = (prefix, count = 3) =>
|
||||
JSON.stringify(
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: `${prefix}-${i}`,
|
||||
name: `${prefix} ${i}`,
|
||||
lat: 30 + i * 0.01,
|
||||
lon: -97,
|
||||
url: `https://example.test/${prefix}-${i}.jpg`,
|
||||
})),
|
||||
);
|
||||
|
||||
/** Let a background refresh that needs no timers run to completion. */
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
/** Restore process.env to a snapshot taken with `{ ...process.env }`. */
|
||||
const restoreEnv = (saved) => {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in saved)) delete process.env[key];
|
||||
}
|
||||
Object.assign(process.env, saved);
|
||||
};
|
||||
|
||||
test('an expired catalog is served at once while a slow pack refreshes in the background', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
// Live packs run alongside the env pack, so one slow upstream can hold
|
||||
// the refresh open.
|
||||
process.env.CCTV_FORCE_AUSTIN = '1';
|
||||
process.env.CCTV_SOURCES_FILE = '/nonexistent/cctv.json';
|
||||
process.env.CCTV_SOURCES_JSON = envSources('old');
|
||||
let now = 1_000_000;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const hung = [];
|
||||
let hang = false;
|
||||
t.mock.method(globalThis, 'fetch', () =>
|
||||
hang
|
||||
? new Promise((_, reject) => {
|
||||
hung.push(() => reject(new Error('upstream gave up')));
|
||||
})
|
||||
: Promise.reject(new Error('offline')),
|
||||
);
|
||||
const getSources = createCctvCatalog({ sourceRoot: '/nonexistent' });
|
||||
assert.deepEqual(
|
||||
(await getSources()).map((s) => s.id),
|
||||
['old-0', 'old-1', 'old-2'],
|
||||
);
|
||||
|
||||
// Past the TTL, with every live pack's upstream hanging.
|
||||
now += CCTV_SOURCE_CACHE_MS + 1;
|
||||
hang = true;
|
||||
process.env.CCTV_SOURCES_JSON = envSources('new');
|
||||
let timer;
|
||||
const served = await Promise.race([
|
||||
getSources(),
|
||||
new Promise((resolve) => {
|
||||
timer = setTimeout(() => resolve('waited'), 200);
|
||||
}),
|
||||
]);
|
||||
clearTimeout(timer);
|
||||
assert.notEqual(
|
||||
served,
|
||||
'waited',
|
||||
'a stale request waited for the background refresh',
|
||||
);
|
||||
assert.deepEqual(
|
||||
served.map((s) => s.id),
|
||||
['old-0', 'old-1', 'old-2'],
|
||||
);
|
||||
|
||||
// Requests during the refresh share it rather than starting another.
|
||||
const pause = () => new Promise((resolve) => setTimeout(resolve, 50));
|
||||
await pause();
|
||||
const inFlight = hung.length;
|
||||
assert.ok(inFlight > 0, 'the refresh reached the hanging upstreams');
|
||||
await getSources();
|
||||
await getSources();
|
||||
await pause();
|
||||
assert.equal(hung.length, inFlight, 'only one refresh ran');
|
||||
|
||||
// When the slow pack gives up, the refreshed catalog replaces the old one.
|
||||
hang = false;
|
||||
for (const giveUp of hung) giveUp();
|
||||
for (let i = 0; i < 50; i += 1) {
|
||||
const ids = (await getSources()).map((s) => s.id);
|
||||
if (ids[0] === 'new-0') break;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
assert.deepEqual(
|
||||
(await getSources()).map((s) => s.id),
|
||||
['new-0', 'new-1', 'new-2'],
|
||||
);
|
||||
} finally {
|
||||
restoreEnv(saved);
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed background refresh keeps the catalog, warns once, and waits a TTL to retry', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
const unhandled = [];
|
||||
const onUnhandled = (reason) => unhandled.push(reason);
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
try {
|
||||
process.env.CCTV_PREFER_AUSTIN = '0';
|
||||
process.env.CCTV_SOURCES_FILE = '/nonexistent/cctv.json';
|
||||
process.env.CCTV_SOURCES_JSON = envSources('old', 9);
|
||||
process.env.CCTV_MAX_SOURCES = '8';
|
||||
let now = 1_000_000;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
// Nine cameras over a cap of eight make every refresh warn; throwing from
|
||||
// that warning is how this test makes a refresh reject.
|
||||
let failRefresh = false;
|
||||
let failedRefreshes = 0;
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (...args) => {
|
||||
const text = args.join(' ');
|
||||
if (failRefresh && text.includes('exceeds cap')) {
|
||||
failedRefreshes += 1;
|
||||
throw new Error('refresh broke');
|
||||
}
|
||||
warnings.push(text);
|
||||
});
|
||||
const getSources = createCctvCatalog({ sourceRoot: '/nonexistent' });
|
||||
const old = await getSources();
|
||||
assert.equal(old.length, 8);
|
||||
|
||||
// Past the TTL the refresh throws: the old catalog is still served.
|
||||
now += CCTV_SOURCE_CACHE_MS + 1;
|
||||
failRefresh = true;
|
||||
assert.equal(await getSources(), old);
|
||||
await settle();
|
||||
assert.equal(failedRefreshes, 1);
|
||||
assert.equal(
|
||||
warnings.filter((w) => w.includes('background catalog refresh failed'))
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
|
||||
// The failure is not retried on every request until the next TTL.
|
||||
assert.equal(await getSources(), old);
|
||||
assert.equal(await getSources(), old);
|
||||
await settle();
|
||||
assert.equal(failedRefreshes, 1, 'a failed refresh was retried at once');
|
||||
|
||||
// After it, a refresh that works replaces the catalog. With no live packs
|
||||
// the refresh finishes before the request that started it returns.
|
||||
now += CCTV_SOURCE_CACHE_MS + 1;
|
||||
failRefresh = false;
|
||||
process.env.CCTV_SOURCES_JSON = envSources('new');
|
||||
await getSources();
|
||||
await settle();
|
||||
const fresh = await getSources();
|
||||
assert.deepEqual(
|
||||
fresh.map((s) => s.id),
|
||||
['new-0', 'new-1', 'new-2'],
|
||||
);
|
||||
// Trim notes stay with the list they describe, so a request served the
|
||||
// old list during the refresh never reports the new list's notes.
|
||||
assert.deepEqual(
|
||||
getSources.trimmedPacks(old).map((p) => [p.pack, p.available, p.served]),
|
||||
[['env', 9, 8]],
|
||||
);
|
||||
assert.deepEqual(getSources.trimmedPacks(fresh), []);
|
||||
assert.deepEqual(getSources.trimmedPacks(), []);
|
||||
assert.deepEqual(unhandled, []);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
restoreEnv(saved);
|
||||
}
|
||||
});
|
||||
|
||||
test('an empty background refresh keeps the catalog and waits a TTL before fetching again', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
process.env.CCTV_FORCE_AUSTIN = '1';
|
||||
process.env.CCTV_SOURCES_FILE = '/nonexistent/cctv.json';
|
||||
process.env.CCTV_SOURCES_JSON = envSources('old');
|
||||
let now = 1_000_000;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
||||
let fetches = 0;
|
||||
t.mock.method(globalThis, 'fetch', () => {
|
||||
fetches += 1;
|
||||
return Promise.reject(new Error('offline'));
|
||||
});
|
||||
const getSources = createCctvCatalog({ sourceRoot: '/nonexistent' });
|
||||
const old = await getSources();
|
||||
|
||||
// Past the TTL every pack comes back empty, as in an upstream outage.
|
||||
now += CCTV_SOURCE_CACHE_MS + 1;
|
||||
process.env.CCTV_SOURCES_JSON = '[]';
|
||||
assert.equal(await getSources(), old);
|
||||
for (let i = 0; i < 50; i += 1) {
|
||||
if (warnings.some((w) => w.includes('source refresh returned empty')))
|
||||
break;
|
||||
await settle();
|
||||
}
|
||||
assert.ok(
|
||||
warnings.some((w) => w.includes('serving 3 stale cameras')),
|
||||
'the empty refresh kept the old catalog',
|
||||
);
|
||||
|
||||
// Until the next TTL, requests are served without touching any upstream.
|
||||
const fetchesAfterRefresh = fetches;
|
||||
assert.equal(await getSources(), old);
|
||||
assert.equal(await getSources(), old);
|
||||
await settle();
|
||||
assert.equal(
|
||||
fetches,
|
||||
fetchesAfterRefresh,
|
||||
'an empty refresh reran at once',
|
||||
);
|
||||
} finally {
|
||||
restoreEnv(saved);
|
||||
}
|
||||
});
|
||||
@@ -1,11 +1,24 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
TARKTEE_IMAGES_URL,
|
||||
TARKTEE_LOCATIONS_URL,
|
||||
TARKTEE_MAX_CATALOG_BYTES,
|
||||
TARKTEE_FETCH_TIMEOUT_MS,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import {
|
||||
loadTallinnSourcesFromCatalog,
|
||||
loadTarkteeSourcesFromDatex,
|
||||
parseTarkteeDatexImages,
|
||||
parseTarkteeDatexLocations,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
|
||||
/** Silence the loaders' progress and failure logging. */
|
||||
function quiet(t) {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
}
|
||||
|
||||
const SAMPLE_LOCATIONS_XML = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<d2LogicalModel xmlns="http://datex2.eu/schema/2/2_0">
|
||||
<payloadPublication>
|
||||
@@ -84,3 +97,305 @@ test('Tarktee DATEX image parser rejects non-official hosts', () => {
|
||||
const images = parseTarkteeDatexImages(xml);
|
||||
assert.equal(images.size, 0);
|
||||
});
|
||||
|
||||
test('Tarktee DATEX requests wait 30 s, past the slow answers measured live', async (t) => {
|
||||
const timeouts = [];
|
||||
const timeout = AbortSignal.timeout;
|
||||
t.mock.method(AbortSignal, 'timeout', (ms) => {
|
||||
timeouts.push(ms);
|
||||
return timeout.call(AbortSignal, ms);
|
||||
});
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async (url) =>
|
||||
new Response(
|
||||
String(url).includes('roadCameraLocations')
|
||||
? SAMPLE_LOCATIONS_XML
|
||||
: SAMPLE_IMAGES_XML,
|
||||
),
|
||||
);
|
||||
const cameras = await loadTarkteeSourcesFromDatex();
|
||||
assert.deepEqual(timeouts, [30_000]);
|
||||
assert.equal(cameras.length, 1);
|
||||
});
|
||||
|
||||
test('Tarktee loader deduplicates cameras sharing an image number before the cap', async (t) => {
|
||||
quiet(t);
|
||||
const dupLocationsXml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<d2LogicalModel xmlns="http://datex2.eu/schema/2/2_0">
|
||||
<payloadPublication>
|
||||
<predefinedLocationContainer id="TRAFFIC_CAMERAS" version="0">
|
||||
<predefinedLocation id="loc-1" version="0">
|
||||
<predefinedLocationName><values><value lang="et">Tallinn Ringtee</value></values></predefinedLocationName>
|
||||
<location><pointByCoordinates><pointCoordinates><latitude>59.4370</latitude><longitude>24.7530</longitude></pointCoordinates></pointByCoordinates></location>
|
||||
</predefinedLocation>
|
||||
<predefinedLocation id="loc-2" version="0">
|
||||
<predefinedLocationName><values><value lang="et">Tallinn Ringtee duplicate</value></values></predefinedLocationName>
|
||||
<location><pointByCoordinates><pointCoordinates><latitude>59.4371</latitude><longitude>24.7531</longitude></pointCoordinates></pointByCoordinates></location>
|
||||
</predefinedLocation>
|
||||
</predefinedLocationContainer>
|
||||
</payloadPublication>
|
||||
</d2LogicalModel>`;
|
||||
const dupImagesXml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<d2LogicalModel xmlns="http://datex2.eu/schema/2/2_0">
|
||||
<payloadPublication>
|
||||
<trafficView id="1"><linearTrafficView id="1"><linearPredefinedLocationReference id="loc-1"/><trafficViewRecord id="1-1"><urlLink><urlLinkAddress>https://tarktee.transpordiamet.ee/images/42/42_1.jpg</urlLinkAddress></urlLink></trafficViewRecord></linearTrafficView></trafficView>
|
||||
<trafficView id="2"><linearTrafficView id="2"><linearPredefinedLocationReference id="loc-2"/><trafficViewRecord id="2-1"><urlLink><urlLinkAddress>https://tarktee.transpordiamet.ee/images/42/42_2.jpg</urlLinkAddress></urlLink></trafficViewRecord></linearTrafficView></trafficView>
|
||||
</payloadPublication>
|
||||
</d2LogicalModel>`;
|
||||
|
||||
const seen = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
seen.push([String(url), init?.redirect]);
|
||||
const body =
|
||||
String(url) === TARKTEE_LOCATIONS_URL ? dupLocationsXml : dupImagesXml;
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/xml' },
|
||||
});
|
||||
});
|
||||
|
||||
const cameras = await loadTarkteeSourcesFromDatex();
|
||||
assert.deepEqual(seen, [
|
||||
[TARKTEE_LOCATIONS_URL, 'manual'],
|
||||
[TARKTEE_IMAGES_URL, 'manual'],
|
||||
]);
|
||||
assert.equal(cameras.length, 1);
|
||||
assert.equal(cameras[0].id, 'ee-tarktee-42');
|
||||
assert.equal(cameras[0].name, 'Tallinn Ringtee');
|
||||
});
|
||||
|
||||
test('Tarktee loader refuses a redirect and cancels both response bodies', async (t) => {
|
||||
quiet(t);
|
||||
const cancelled = { locations: false, images: false };
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const isLocations = String(url) === TARKTEE_LOCATIONS_URL;
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('<xml/>'));
|
||||
},
|
||||
cancel() {
|
||||
if (isLocations) cancelled.locations = true;
|
||||
else cancelled.images = true;
|
||||
},
|
||||
});
|
||||
return new Response(body, {
|
||||
status: isLocations ? 302 : 200,
|
||||
headers: isLocations ? { location: 'https://evil.example/loc.xml' } : {},
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.equal(cancelled.locations, true, 'redirected body is cancelled');
|
||||
assert.equal(cancelled.images, true, 'sibling 200 body is also cancelled');
|
||||
});
|
||||
|
||||
test('Tarktee loader cancels fulfilled bodies when either fetch rejects', async (t) => {
|
||||
for (const failedUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
|
||||
for (const delayedSibling of [false, true]) {
|
||||
await t.test(
|
||||
`${failedUrl}, delayed sibling: ${delayedSibling}`,
|
||||
async (t) => {
|
||||
quiet(t);
|
||||
let cancelled = false;
|
||||
const response = new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('<xml/>'));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}),
|
||||
);
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
if (String(url) === failedUrl) throw new TypeError('fetch failed');
|
||||
if (delayedSibling) await new Promise(setImmediate);
|
||||
return response;
|
||||
});
|
||||
|
||||
try {
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
// An aborted mock transport may still deliver its queued response.
|
||||
if (delayedSibling) await new Promise(setImmediate);
|
||||
assert.equal(
|
||||
cancelled,
|
||||
true,
|
||||
'fulfilled sibling body is cancelled',
|
||||
);
|
||||
} finally {
|
||||
await response.body.cancel();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Tarktee loader cancels the sibling body when one feed fails or overflows the byte cap', async (t) => {
|
||||
quiet(t);
|
||||
let siblingCancelled = false;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const isLocations = String(url) === TARKTEE_LOCATIONS_URL;
|
||||
if (isLocations) {
|
||||
return new Response('', { status: 503 });
|
||||
}
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(SAMPLE_IMAGES_XML));
|
||||
},
|
||||
cancel() {
|
||||
siblingCancelled = true;
|
||||
},
|
||||
});
|
||||
return new Response(body, { status: 200 });
|
||||
});
|
||||
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.equal(
|
||||
siblingCancelled,
|
||||
true,
|
||||
'sibling 200 stream is cancelled on 503',
|
||||
);
|
||||
|
||||
let overflowSiblingCancelled = false;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const isLocations = String(url) === TARKTEE_LOCATIONS_URL;
|
||||
if (isLocations) {
|
||||
const padded =
|
||||
SAMPLE_LOCATIONS_XML + ' '.repeat(TARKTEE_MAX_CATALOG_BYTES);
|
||||
return new Response(padded, {
|
||||
status: 200,
|
||||
headers: { 'Content-Length': String(padded.length) },
|
||||
});
|
||||
}
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(SAMPLE_IMAGES_XML));
|
||||
},
|
||||
cancel() {
|
||||
overflowSiblingCancelled = true;
|
||||
},
|
||||
});
|
||||
return new Response(body, { status: 200 });
|
||||
});
|
||||
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.equal(
|
||||
overflowSiblingCancelled,
|
||||
true,
|
||||
'sibling stream is cancelled when the other feed exceeds the byte cap',
|
||||
);
|
||||
});
|
||||
|
||||
for (const failingUrl of [TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL]) {
|
||||
for (const lateSibling of [false, true]) {
|
||||
test(`Tarktee cancels a ${lateSibling ? 'late' : 'received'} sibling when ${failingUrl} rejects before headers`, async (t) => {
|
||||
quiet(t);
|
||||
let cancelled = false;
|
||||
let siblingSignal;
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
if (String(url) === failingUrl) throw new Error('headers unavailable');
|
||||
siblingSignal = init.signal;
|
||||
if (lateSibling) await gate;
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('<xml/>'));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
// Also exercise a response arriving after abort, as a queued transport
|
||||
// completion can race the rejection owner even when fetch honors abort.
|
||||
if (lateSibling) {
|
||||
release();
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
assert.equal(cancelled, true, 'every obtained body must be cancelled');
|
||||
assert.equal(
|
||||
siblingSignal.aborted,
|
||||
true,
|
||||
'a pending transport is aborted immediately',
|
||||
);
|
||||
});
|
||||
}
|
||||
test(`Tarktee aborts a pending sibling when ${failingUrl} rejects`, async (t) => {
|
||||
quiet(t);
|
||||
let aborted = false;
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
if (String(url) === failingUrl) throw new Error('headers unavailable');
|
||||
return new Promise((resolve, reject) => {
|
||||
init.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
aborted = true;
|
||||
reject(init.signal.reason);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.equal(aborted, true, 'do not wait for the 30-second deadline');
|
||||
});
|
||||
}
|
||||
|
||||
test('Tarktee cancels both lengthless streams when one exceeds the byte cap', async (t) => {
|
||||
quiet(t);
|
||||
const cancelled = [];
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async (url) =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
const oversized = String(url) === TARKTEE_LOCATIONS_URL;
|
||||
controller.enqueue(
|
||||
new Uint8Array(oversized ? TARKTEE_MAX_CATALOG_BYTES + 1 : 1),
|
||||
);
|
||||
},
|
||||
cancel() {
|
||||
cancelled.push(String(url));
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.deepEqual(
|
||||
cancelled.sort(),
|
||||
[TARKTEE_LOCATIONS_URL, TARKTEE_IMAGES_URL].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
test('Tarktee aborts pending headers as soon as its sibling returns an HTTP error', async (t) => {
|
||||
quiet(t);
|
||||
let aborted = false;
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
if (String(url) === TARKTEE_LOCATIONS_URL)
|
||||
return new Response('unavailable', { status: 503 });
|
||||
return new Promise((resolve, reject) => {
|
||||
init.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
aborted = true;
|
||||
reject(init.signal.reason);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
assert.deepEqual(await loadTarkteeSourcesFromDatex(), []);
|
||||
assert.equal(aborted, true);
|
||||
});
|
||||
@@ -0,0 +1,376 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
floridaCameraId,
|
||||
floridaCameraToSource,
|
||||
loadFloridaSourcesFromOpenData,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
FLORIDA_CCTV_URL,
|
||||
FLORIDA_MAX_CATALOG_BYTES,
|
||||
FLORIDA_MAX_CATALOG_PAGES,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import {
|
||||
fallbackHeadingFromId,
|
||||
isLikelyFloridaCoordinate,
|
||||
} from '../../server/providers/cctv/normalize.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
|
||||
const IMAGE_HOST = 'https://images-dis.divas.cloud/DGI/';
|
||||
|
||||
/** A response with a live body, plus a flag that flips when it is cancelled. */
|
||||
const streamingResponse = (init = {}) => {
|
||||
const state = { cancelled: false };
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('{'));
|
||||
},
|
||||
cancel() {
|
||||
state.cancelled = true;
|
||||
},
|
||||
});
|
||||
return { response: new Response(body, init), state };
|
||||
};
|
||||
|
||||
/** One FL511 feature, shaped like the live FeatureServer payload. */
|
||||
const feature = (overrides = {}) => ({
|
||||
attributes: {
|
||||
OBJECTID_1: 6,
|
||||
ID: '1220',
|
||||
DESCRIPT: 'I-75 @ MM 346.5 SB',
|
||||
COUNTY: 'Marion',
|
||||
HIGHWAY: 'I-75',
|
||||
DIRECTION: 'S',
|
||||
LATITUDE: 29.107363,
|
||||
LONGITUDE: -82.188334,
|
||||
IMAGE: `${IMAGE_HOST}chan-9431_h.jpg`,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
|
||||
/** One catalog page of `count` distinct cameras, channels from `start`. */
|
||||
const page = (start, count, extra = {}) => ({
|
||||
features: Array.from({ length: count }, (_, i) =>
|
||||
feature({ IMAGE: `${IMAGE_HOST}chan-${start + i}_h.jpg` }),
|
||||
),
|
||||
...extra,
|
||||
});
|
||||
|
||||
const offsetOf = (url) =>
|
||||
Number(new URL(String(url)).searchParams.get('resultOffset'));
|
||||
|
||||
/** Lift the pack cap for one test so every loaded camera comes back. */
|
||||
const uncapped = (t) => {
|
||||
const previous = process.env.CCTV_FLORIDA_MAX_SOURCES;
|
||||
process.env.CCTV_FLORIDA_MAX_SOURCES = '4200';
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env.CCTV_FLORIDA_MAX_SOURCES;
|
||||
else process.env.CCTV_FLORIDA_MAX_SOURCES = previous;
|
||||
});
|
||||
};
|
||||
|
||||
test('an FL511 feature maps to a source on a pinned HTTPS frame host', () => {
|
||||
const source = floridaCameraToSource(feature());
|
||||
assert.equal(source.id, 'fl-9431');
|
||||
assert.equal(source.name, 'I-75 @ MM 346.5 SB');
|
||||
assert.equal(source.city, 'Marion County');
|
||||
assert.equal(source.cityId, 'florida');
|
||||
assert.equal(source.provider, 'FL511');
|
||||
assert.equal(source.lat, 29.107363);
|
||||
assert.equal(source.lon, -82.188334);
|
||||
assert.equal(source.headingDeg, 180);
|
||||
assert.equal(
|
||||
floridaCameraToSource(feature({ DIRECTION: 'E' })).headingDeg,
|
||||
90,
|
||||
);
|
||||
assert.equal(source.headingConfidence, 'high');
|
||||
assert.equal(source.feedType, 'image');
|
||||
assert.equal(source.url, `${IMAGE_HOST}chan-9431_h.jpg`);
|
||||
assert.equal(source.url, source.snapshotUrl);
|
||||
assert.equal(source.sourceKind, 'fl511-open-data');
|
||||
assert.match(source.license, /personal use only/);
|
||||
assert.match(source.license, /written consent/);
|
||||
});
|
||||
|
||||
test('NOT DIRECTIONAL takes the id-hash fallback at low confidence', () => {
|
||||
const source = floridaCameraToSource(
|
||||
feature({ DIRECTION: 'NOT DIRECTIONAL' }),
|
||||
);
|
||||
assert.equal(source.headingConfidence, 'low');
|
||||
assert.equal(source.headingDeg, fallbackHeadingFromId('fl-9431'));
|
||||
});
|
||||
|
||||
test('rows outside Florida, off-host frames and unusable rows are dropped', () => {
|
||||
const dropped = [
|
||||
feature({ LATITUDE: 33.749, LONGITUDE: -84.388 }), // Atlanta
|
||||
feature({ LATITUDE: 0, LONGITUDE: 0 }),
|
||||
feature({ LATITUDE: -82.188334, LONGITUDE: 29.107363 }), // swapped
|
||||
feature({ LATITUDE: '', LONGITUDE: '' }),
|
||||
feature({ IMAGE: 'https://evil.example/DGI/chan-9431_h.jpg' }),
|
||||
feature({ IMAGE: 'http://images-dis.divas.cloud/DGI/chan-9431_h.jpg' }),
|
||||
feature({
|
||||
IMAGE: 'https://user:[email protected]/DGI/chan-9431_h.jpg',
|
||||
}),
|
||||
feature({ IMAGE: 'not a url' }),
|
||||
{ attributes: null },
|
||||
null,
|
||||
];
|
||||
for (const row of dropped) assert.equal(floridaCameraToSource(row), null);
|
||||
});
|
||||
|
||||
test('camera ids come from the image channel, not the repeating ID column', () => {
|
||||
// FL511 reuses ID across regions: 1220 is both an I-75 and an I-95 camera.
|
||||
const marion = floridaCameraToSource(feature());
|
||||
const broward = floridaCameraToSource(
|
||||
feature({
|
||||
DESCRIPT: 'I-95 SB before E Cypress Rd',
|
||||
COUNTY: 'Broward',
|
||||
LATITUDE: 26.22006,
|
||||
LONGITUDE: -80.13676,
|
||||
IMAGE: `${IMAGE_HOST}chan-6351_h.jpg`,
|
||||
}),
|
||||
);
|
||||
assert.equal(marion.id, 'fl-9431');
|
||||
assert.equal(broward.id, 'fl-6351');
|
||||
// Any resolution suffix keys the same way.
|
||||
assert.equal(floridaCameraId(`${IMAGE_HOST}chan-77_l.jpg`), 'fl-77');
|
||||
// A filename without a channel falls back to a stable path slug.
|
||||
assert.equal(
|
||||
floridaCameraId('https://snapshots.divas.cloud/US-1%20at%20SR-5.jpg'),
|
||||
'fl-us-1-20at-20sr-5',
|
||||
);
|
||||
assert.equal(floridaCameraId('not a url'), null);
|
||||
});
|
||||
|
||||
test('isLikelyFloridaCoordinate spans the state and rejects the rest', () => {
|
||||
const inside = [
|
||||
[24.5551, -81.78], // Key West
|
||||
[30.4213, -87.2169], // Pensacola
|
||||
[30.99, -84.0], // Georgia line
|
||||
[25.7617, -80.1918], // Miami
|
||||
];
|
||||
const outside = [
|
||||
[33.749, -84.388], // Atlanta
|
||||
[25.0443, -77.3504], // Nassau
|
||||
[0, 0],
|
||||
[-81.78, 24.5551], // swapped
|
||||
[NaN, -81],
|
||||
];
|
||||
for (const [lat, lon] of inside)
|
||||
assert.equal(isLikelyFloridaCoordinate(lat, lon), true);
|
||||
for (const [lat, lon] of outside)
|
||||
assert.equal(isLikelyFloridaCoordinate(lat, lon), false);
|
||||
});
|
||||
|
||||
test('the loader pages until exceededTransferLimit clears and collapses repeated rows', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
uncapped(t);
|
||||
const calls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
assert.ok(String(url).startsWith(FLORIDA_CCTV_URL));
|
||||
calls.push([offsetOf(url), init.redirect]);
|
||||
if (offsetOf(url) === 0)
|
||||
return Response.json(page(0, 2000, { exceededTransferLimit: true }));
|
||||
// Last page (no exceededTransferLimit): two new cameras and a repeat.
|
||||
return Response.json(page(1999, 3));
|
||||
});
|
||||
const cameras = await loadFloridaSourcesFromOpenData();
|
||||
assert.deepEqual(calls, [
|
||||
[0, 'manual'],
|
||||
[2000, 'manual'],
|
||||
]);
|
||||
assert.equal(cameras.length, 2002);
|
||||
assert.equal(new Set(cameras.map((camera) => camera.id)).size, 2002);
|
||||
});
|
||||
|
||||
test('pages shorter than requested keep paging while the server says more remain', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
uncapped(t);
|
||||
const offsets = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const params = new URL(String(url)).searchParams;
|
||||
// Offset paging is only stable over a fixed order on the object id.
|
||||
assert.equal(params.get('orderByFields'), 'OBJECTID_1');
|
||||
const offset = offsetOf(url);
|
||||
offsets.push(offset);
|
||||
// A layer whose max record count was lowered to 1,000.
|
||||
return Response.json(
|
||||
page(offset, offset < 2000 ? 1000 : 500, {
|
||||
exceededTransferLimit: offset < 2000,
|
||||
}),
|
||||
);
|
||||
});
|
||||
const cameras = await loadFloridaSourcesFromOpenData();
|
||||
assert.deepEqual(offsets, [0, 1000, 2000]);
|
||||
assert.equal(cameras.length, 2500);
|
||||
});
|
||||
|
||||
test('a service that ignores resultOffset stops at the page ceiling with a warning', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
||||
uncapped(t);
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return Response.json(page(0, 2000, { exceededTransferLimit: true }));
|
||||
});
|
||||
const cameras = await loadFloridaSourcesFromOpenData();
|
||||
assert.equal(calls, FLORIDA_MAX_CATALOG_PAGES);
|
||||
assert.equal(cameras.length, 2000);
|
||||
assert.ok(warnings.some((line) => /page ceiling/.test(line)));
|
||||
});
|
||||
|
||||
test('a redirect on any page drops the whole pack and releases it', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const redirected = streamingResponse({
|
||||
status: 302,
|
||||
headers: { location: 'https://evil.example/cameras' },
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
offsetOf(url) === 0
|
||||
? Response.json(page(0, 2000, { exceededTransferLimit: true }))
|
||||
: redirected.response,
|
||||
);
|
||||
assert.deepEqual(await loadFloridaSourcesFromOpenData(), []);
|
||||
assert.equal(
|
||||
redirected.state.cancelled,
|
||||
true,
|
||||
'the redirect body is cancelled',
|
||||
);
|
||||
});
|
||||
|
||||
test('a failed later page keeps the pages already read', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
uncapped(t);
|
||||
const failed = streamingResponse({ status: 503 });
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
offsetOf(url) === 0
|
||||
? Response.json(page(0, 2000, { exceededTransferLimit: true }))
|
||||
: failed.response,
|
||||
);
|
||||
assert.equal((await loadFloridaSourcesFromOpenData()).length, 2000);
|
||||
assert.equal(failed.state.cancelled, true, 'the failed body is cancelled');
|
||||
|
||||
// A network error on a later page keeps them too.
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
if (offsetOf(url) === 0)
|
||||
return Response.json(page(0, 2000, { exceededTransferLimit: true }));
|
||||
throw new Error('network down');
|
||||
});
|
||||
assert.equal((await loadFloridaSourcesFromOpenData()).length, 2000);
|
||||
});
|
||||
|
||||
test('an oversized catalog page is refused', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () =>
|
||||
new Response(JSON.stringify(page(0, 1)), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'content-length': String(FLORIDA_MAX_CATALOG_BYTES + 1),
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(await loadFloridaSourcesFromOpenData(), []);
|
||||
|
||||
// So is a body that only turns out too long while streaming.
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
const oversized = 'x'.repeat(FLORIDA_MAX_CATALOG_BYTES + 1024);
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(oversized));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
});
|
||||
assert.deepEqual(await loadFloridaSourcesFromOpenData(), []);
|
||||
});
|
||||
|
||||
/**
|
||||
* Serve a two-camera FL511 page to the Florida endpoint and an empty payload
|
||||
* to every other pack, so one catalog refresh exercises the registration
|
||||
* without reaching the network. Returns the URLs that were requested.
|
||||
*/
|
||||
const runCatalogWithMockedUpstreams = async (t) => {
|
||||
const requested = [];
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const href = String(url);
|
||||
requested.push(href);
|
||||
if (href.startsWith(FLORIDA_CCTV_URL)) return Response.json(page(0, 2));
|
||||
return Response.json([]);
|
||||
});
|
||||
// No curated catalogs or ground-height sidecar, so only live lanes are in play.
|
||||
const sources = await createCctvCatalog({ sourceRoot: '/nonexistent' })();
|
||||
return { requested, sources };
|
||||
};
|
||||
|
||||
/** Put process.env back exactly as it was. */
|
||||
const restoreEnv = (saved) => {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (key in saved) continue;
|
||||
delete process.env[key];
|
||||
}
|
||||
Object.assign(process.env, saved);
|
||||
};
|
||||
|
||||
test('with CCTV_FLORIDA_ENABLED=1 the Florida lane is wired into the catalog', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
delete process.env.CCTV_SOURCES_FILE;
|
||||
delete process.env.CCTV_SOURCES_JSON;
|
||||
process.env.CCTV_FLORIDA_ENABLED = '1';
|
||||
const { requested, sources } = await runCatalogWithMockedUpstreams(t);
|
||||
assert.ok(
|
||||
requested.some((href) => href.startsWith(FLORIDA_CCTV_URL)),
|
||||
'the catalog refresh invokes the Florida loader',
|
||||
);
|
||||
assert.deepEqual(
|
||||
sources
|
||||
.filter((s) => s.cityId === 'florida')
|
||||
.map((s) => s.id)
|
||||
.sort(),
|
||||
['fl-0', 'fl-1'],
|
||||
'Florida cameras reach the served catalog through the registered lane',
|
||||
);
|
||||
} finally {
|
||||
restoreEnv(saved);
|
||||
}
|
||||
});
|
||||
|
||||
test('the Florida lane stays off unless CCTV_FLORIDA_ENABLED=1', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
delete process.env.CCTV_SOURCES_FILE;
|
||||
delete process.env.CCTV_SOURCES_JSON;
|
||||
delete process.env.CCTV_FLORIDA_ENABLED;
|
||||
const { requested, sources } = await runCatalogWithMockedUpstreams(t);
|
||||
assert.equal(
|
||||
requested.some((href) => href.startsWith(FLORIDA_CCTV_URL)),
|
||||
false,
|
||||
'the disabled lane never reaches its upstream',
|
||||
);
|
||||
assert.deepEqual(
|
||||
sources.filter((s) => s.cityId === 'florida'),
|
||||
[],
|
||||
);
|
||||
} finally {
|
||||
restoreEnv(saved);
|
||||
}
|
||||
});
|
||||
@@ -2,11 +2,24 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
applyVegvesenGroundHeights,
|
||||
clearKartverketHeightCache,
|
||||
fetchKartverketHeights,
|
||||
kartverketBackoffMs,
|
||||
loadVegvesenSourcesFromOpenData,
|
||||
vegvesenCameraToSource,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
DEFAULT_VEGVESEN_CCTV_URL,
|
||||
KARTVERKET_HEIGHT_URL,
|
||||
KARTVERKET_CATALOG_WAIT_MS,
|
||||
KARTVERKET_CONCURRENCY,
|
||||
KARTVERKET_FAILURE_BACKOFF_MS,
|
||||
KARTVERKET_MAX_POINTS,
|
||||
KARTVERKET_MAX_RESPONSE_BYTES,
|
||||
KARTVERKET_NULL_TTL_MS,
|
||||
KARTVERKET_USER_AGENT,
|
||||
CCTV_SOURCE_CACHE_MS,
|
||||
VEGVESEN_IMAGE_ORIGIN,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
@@ -104,6 +117,8 @@ test('faulty cameras, off-host frames and bad geometry are dropped', () => {
|
||||
});
|
||||
|
||||
test('the loader dedupes, and failures degrade to an empty pack', async (t) => {
|
||||
clearKartverketHeightCache();
|
||||
t.after(clearKartverketHeightCache);
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const requested = [];
|
||||
@@ -127,7 +142,11 @@ test('the loader dedupes, and failures degrade to an empty pack', async (t) => {
|
||||
});
|
||||
});
|
||||
const cameras = await loadVegvesenSourcesFromOpenData();
|
||||
assert.deepEqual(requested, [DEFAULT_VEGVESEN_CCTV_URL]);
|
||||
// The catalog first; the rest is the Kartverket height lookup.
|
||||
assert.equal(requested[0], DEFAULT_VEGVESEN_CCTV_URL);
|
||||
// Two unique positions: one Kartverket request.
|
||||
assert.equal(requested.length, 2);
|
||||
assert.ok(requested[1].startsWith(KARTVERKET_HEIGHT_URL));
|
||||
// Nearest-to-anchor first: Oslo leads.
|
||||
assert.deepEqual(
|
||||
cameras.map((c) => c.id),
|
||||
@@ -200,3 +219,604 @@ test('CCTV_VEGVESEN_ENABLED=0 keeps the lane from being loaded', async (t) => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/** Answer a Kartverket request the way the live API does: echo every point,
|
||||
* with the height `heightFor(x, y)` returns (null = outside coverage). */
|
||||
const kartverketResponse = (url, heightFor) => {
|
||||
const points = JSON.parse(new URL(url).searchParams.get('punkter'));
|
||||
return Response.json({
|
||||
koordsys: 4258,
|
||||
punkter: points.map(([x, y]) => ({ x, y, z: heightFor(x, y) })),
|
||||
});
|
||||
};
|
||||
|
||||
/** Cameras at distinct Norwegian positions. */
|
||||
const cameraAt = (i) => ({
|
||||
id: `no-vegvesen-${i}`,
|
||||
lat: 60 + i * 0.001,
|
||||
lon: 7 + i * 0.001,
|
||||
groundElevationM: 150,
|
||||
});
|
||||
|
||||
const withHeightsEnv = (t) => {
|
||||
const saved = process.env.CCTV_VEGVESEN_HEIGHTS;
|
||||
delete process.env.CCTV_VEGVESEN_HEIGHTS;
|
||||
clearKartverketHeightCache();
|
||||
t.after(() => {
|
||||
clearKartverketHeightCache();
|
||||
if (saved === undefined) delete process.env.CCTV_VEGVESEN_HEIGHTS;
|
||||
else process.env.CCTV_VEGVESEN_HEIGHTS = saved;
|
||||
});
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
};
|
||||
|
||||
const sentPoints = (url) =>
|
||||
JSON.parse(new URL(url).searchParams.get('punkter'));
|
||||
|
||||
test('Kartverket heights come in batches of 20, matched by echoed coordinates', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
requested.push(String(url));
|
||||
assert.ok(String(url).startsWith(KARTVERKET_HEIGHT_URL));
|
||||
assert.equal(init.headers['User-Agent'], KARTVERKET_USER_AGENT);
|
||||
// Redirects are refused, so a request can never leave the fixed host.
|
||||
assert.equal(init.redirect, 'error');
|
||||
// Reply in reverse order: matching must not depend on list position.
|
||||
const response = kartverketResponse(url, (x) =>
|
||||
x > 7.04 ? null : Math.round((x - 7) * 10000),
|
||||
);
|
||||
const body = await response.json();
|
||||
body.punkter.reverse();
|
||||
return Response.json(body);
|
||||
});
|
||||
const { heights, failure } = await fetchKartverketHeights(
|
||||
Array.from({ length: 50 }, (_, i) => cameraAt(i)),
|
||||
);
|
||||
assert.equal(failure, null);
|
||||
// One pass, no retries: 20 + 20 + 10.
|
||||
assert.deepEqual(
|
||||
requested.map((url) => sentPoints(url).length),
|
||||
[KARTVERKET_MAX_POINTS, 20, 10],
|
||||
);
|
||||
for (const url of requested) {
|
||||
assert.equal(new URL(url).searchParams.get('koordsys'), '4258');
|
||||
}
|
||||
assert.equal(heights.size, 50);
|
||||
assert.equal(heights.get('7.010000,60.010000'), 100);
|
||||
// Past x = 7.04 the API has no height: recorded as null, never as 0.
|
||||
assert.equal(heights.get('7.049000,60.049000'), null);
|
||||
});
|
||||
|
||||
test('only the points a request asked about are recorded', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const points = sentPoints(url);
|
||||
return Response.json({
|
||||
koordsys: 4258,
|
||||
punkter: [
|
||||
...points.map(([x, y]) => ({ x, y, z: 10 })),
|
||||
{ x: 7.5, y: 60.5, z: 999 }, // never asked
|
||||
],
|
||||
});
|
||||
});
|
||||
const { heights } = await fetchKartverketHeights([cameraAt(0)]);
|
||||
assert.deepEqual([...heights.entries()], [['7.000000,60.000000', 10]]);
|
||||
});
|
||||
|
||||
test('either water marker counts as the surface', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const [a, b, c] = sentPoints(url);
|
||||
return Response.json({
|
||||
koordsys: 4258,
|
||||
punkter: [
|
||||
{
|
||||
x: a[0],
|
||||
y: a[1],
|
||||
z: -547.1,
|
||||
datakilde: 'dybdekurver',
|
||||
terreng: null,
|
||||
},
|
||||
{ x: b[0], y: b[1], z: -9.2, datakilde: 'dtm1', terreng: 'Havflate' },
|
||||
{
|
||||
x: c[0],
|
||||
y: c[1],
|
||||
z: -0.2,
|
||||
datakilde: 'dtm1',
|
||||
terreng: 'ÅpentOmråde',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
const { heights } = await fetchKartverketHeights([
|
||||
cameraAt(0),
|
||||
cameraAt(1),
|
||||
cameraAt(2),
|
||||
]);
|
||||
assert.equal(heights.get('7.000000,60.000000'), 0);
|
||||
assert.equal(heights.get('7.001000,60.001000'), 0);
|
||||
// A quay just below the datum on land data stays as measured.
|
||||
assert.equal(heights.get('7.002000,60.002000'), -0.2);
|
||||
});
|
||||
|
||||
test('heights outside -20..2500 m and points outside Norway are not used', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
const zs = [-20, -20.5, 2500, 2500.5];
|
||||
const points = sentPoints(url);
|
||||
return Response.json({
|
||||
koordsys: 4258,
|
||||
punkter: points.map(([x, y], i) => ({ x, y, z: zs[i] })),
|
||||
});
|
||||
});
|
||||
const { heights } = await fetchKartverketHeights([
|
||||
cameraAt(0),
|
||||
cameraAt(1),
|
||||
cameraAt(2),
|
||||
cameraAt(3),
|
||||
{ lat: 55.68, lon: 12.57 }, // Copenhagen: never sent
|
||||
]);
|
||||
assert.equal(requested.length, 1);
|
||||
assert.equal(sentPoints(requested[0]).length, 4);
|
||||
assert.deepEqual(
|
||||
[0, 1, 2, 3].map((i) =>
|
||||
heights.get(
|
||||
`${(7 + i * 0.001).toFixed(6)},${(60 + i * 0.001).toFixed(6)}`,
|
||||
),
|
||||
),
|
||||
[-20, null, 2500, null],
|
||||
);
|
||||
});
|
||||
|
||||
test('no more than eight requests are in flight', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
inFlight += 1;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
inFlight -= 1;
|
||||
return kartverketResponse(url, () => 1);
|
||||
});
|
||||
const { heights } = await fetchKartverketHeights(
|
||||
Array.from({ length: 400 }, (_, i) => cameraAt(i)),
|
||||
);
|
||||
assert.equal(heights.size, 400);
|
||||
assert.equal(peak, KARTVERKET_CONCURRENCY);
|
||||
});
|
||||
|
||||
test('a transport failure stops the lookup: no retries, no new requests', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return new Response('busy', {
|
||||
status: 429,
|
||||
headers: { 'Retry-After': '120' },
|
||||
});
|
||||
});
|
||||
const { heights, failure } = await fetchKartverketHeights(
|
||||
Array.from({ length: 400 }, (_, i) => cameraAt(i)),
|
||||
);
|
||||
// The first wave is already in flight when the first failure lands; nothing
|
||||
// after it starts, and no point is resent.
|
||||
assert.equal(calls, KARTVERKET_CONCURRENCY);
|
||||
assert.equal(heights.size, 0);
|
||||
assert.deepEqual(failure, {
|
||||
status: 429,
|
||||
retryAfter: '120',
|
||||
deadline: false,
|
||||
});
|
||||
});
|
||||
|
||||
/** A fetch that never answers, and rejects only when its signal aborts. */
|
||||
const hangingFetch = (url, init) => {
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
return new Promise((_, reject) => {
|
||||
init.signal.addEventListener('abort', () => reject(init.signal.reason));
|
||||
});
|
||||
};
|
||||
|
||||
test('the lookup deadline bounds a hanging service', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', hangingFetch);
|
||||
const started = Date.now();
|
||||
const { heights, failure } = await fetchKartverketHeights([cameraAt(0)], {
|
||||
timeoutMs: 30,
|
||||
});
|
||||
const elapsed = Date.now() - started;
|
||||
assert.ok(elapsed >= 25 && elapsed < 2000, `elapsed ${elapsed} ms`);
|
||||
assert.equal(heights.size, 0);
|
||||
assert.deepEqual(failure, { status: null, retryAfter: null, deadline: true });
|
||||
});
|
||||
|
||||
test('one hanging request times out on its own, as a failing service', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', hangingFetch);
|
||||
const { failure } = await fetchKartverketHeights([cameraAt(0)], {
|
||||
timeoutMs: 60_000,
|
||||
requestTimeoutMs: 20,
|
||||
});
|
||||
assert.deepEqual(failure, {
|
||||
status: null,
|
||||
retryAfter: null,
|
||||
deadline: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('the deadline is shared: later requests do not get a fresh one', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', (url, init) => {
|
||||
calls += 1;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => resolve(kartverketResponse(url, () => 1)),
|
||||
40,
|
||||
);
|
||||
init.signal.addEventListener('abort', () => {
|
||||
clearTimeout(timer);
|
||||
reject(init.signal.reason);
|
||||
});
|
||||
});
|
||||
});
|
||||
// Five waves of 40 ms against a 100 ms deadline for the whole lookup.
|
||||
const { heights, failure } = await fetchKartverketHeights(
|
||||
Array.from({ length: 5 * KARTVERKET_CONCURRENCY * 20 }, (_, i) =>
|
||||
cameraAt(i),
|
||||
),
|
||||
{ timeoutMs: 100 },
|
||||
);
|
||||
assert.equal(failure?.deadline, true);
|
||||
assert.ok(heights.size < 5 * KARTVERKET_CONCURRENCY * 20);
|
||||
assert.ok(calls < 5 * KARTVERKET_CONCURRENCY, `calls ${calls}`);
|
||||
});
|
||||
|
||||
test('a 503, an unreadable or an oversized body stops the lookup', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const answers = {
|
||||
503: () => new Response('down', { status: 503 }),
|
||||
'not json': () =>
|
||||
new Response('<html>maintenance</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
}),
|
||||
oversized: () =>
|
||||
Response.json({
|
||||
punkter: [],
|
||||
pad: 'x'.repeat(KARTVERKET_MAX_RESPONSE_BYTES + 1),
|
||||
}),
|
||||
};
|
||||
for (const [label, answer] of Object.entries(answers)) {
|
||||
clearKartverketHeightCache();
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls += 1;
|
||||
return answer();
|
||||
});
|
||||
const { heights, failure } = await fetchKartverketHeights(
|
||||
Array.from({ length: 400 }, (_, i) => cameraAt(i)),
|
||||
);
|
||||
assert.equal(calls, KARTVERKET_CONCURRENCY, label);
|
||||
assert.equal(heights.size, 0, label);
|
||||
assert.equal(failure?.deadline, false, label);
|
||||
assert.equal(failure?.status, label === '503' ? 503 : null, label);
|
||||
}
|
||||
});
|
||||
|
||||
test('a 4xx rejects that request only: its points get no height, the rest go on', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
sentPoints(url)[0][0] === 7
|
||||
? new Response('bad point', { status: 400 })
|
||||
: kartverketResponse(url, () => 42),
|
||||
);
|
||||
const { heights, failure } = await fetchKartverketHeights(
|
||||
Array.from({ length: 40 }, (_, i) => cameraAt(i)),
|
||||
);
|
||||
assert.equal(failure, null);
|
||||
assert.equal(heights.size, 40);
|
||||
assert.equal(heights.get('7.000000,60.000000'), null);
|
||||
assert.equal(heights.get('7.020000,60.020000'), 42);
|
||||
});
|
||||
|
||||
test('a point a 200 answer leaves out is cached as no height', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const points = sentPoints(url).slice(1); // drop the first point
|
||||
return Response.json({
|
||||
koordsys: 4258,
|
||||
punkter: points.map(([x, y]) => ({ x, y, z: 7 })),
|
||||
});
|
||||
});
|
||||
const cameras = [cameraAt(0), cameraAt(1)];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras), 1);
|
||||
assert.equal(cameras[0].groundElevationM, 150);
|
||||
// The next refresh asks nothing: the left-out point is a cached miss.
|
||||
assert.equal(await applyVegvesenGroundHeights([cameraAt(0), cameraAt(1)]), 1);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
});
|
||||
|
||||
test('Retry-After sets the backoff, bounded to [1 min, 1 h]', () => {
|
||||
const now = Date.parse('2026-10-06T12:00:00Z');
|
||||
assert.equal(kartverketBackoffMs('120', now), 120_000);
|
||||
assert.equal(kartverketBackoffMs('5', now), 60_000);
|
||||
assert.equal(kartverketBackoffMs('86400', now), 3_600_000);
|
||||
assert.equal(
|
||||
kartverketBackoffMs('Mon, 06 Oct 2026 12:05:00 GMT', now),
|
||||
300_000,
|
||||
);
|
||||
assert.equal(kartverketBackoffMs(null, now), KARTVERKET_FAILURE_BACKOFF_MS);
|
||||
assert.equal(kartverketBackoffMs('soon', now), KARTVERKET_FAILURE_BACKOFF_MS);
|
||||
});
|
||||
|
||||
test('heights are cached, and misses are not asked again until they expire', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let clock = 1_000_000;
|
||||
const now = () => clock;
|
||||
const asked = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
asked.push(sentPoints(url).length);
|
||||
return kartverketResponse(url, (x) => (x < 7.002 ? 1043.26 : null));
|
||||
});
|
||||
const cameras = [cameraAt(0), cameraAt(1), cameraAt(5)];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras, { now }), 2);
|
||||
assert.deepEqual(
|
||||
cameras.map((c) => c.groundElevationM),
|
||||
[1043.3, 1043.3, 150],
|
||||
);
|
||||
// The next refresh asks nothing: heights and the miss are both cached.
|
||||
assert.equal(
|
||||
await applyVegvesenGroundHeights([cameraAt(0), cameraAt(1), cameraAt(5)], {
|
||||
now,
|
||||
}),
|
||||
2,
|
||||
);
|
||||
assert.deepEqual(asked, [3]);
|
||||
// Once the miss expires, only that point is asked again.
|
||||
clock += KARTVERKET_NULL_TTL_MS + 1;
|
||||
await applyVegvesenGroundHeights([cameraAt(0), cameraAt(5)], { now });
|
||||
assert.deepEqual(asked, [3, 1]);
|
||||
});
|
||||
|
||||
test('after a failure no lookup starts until the backoff ends', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let clock = 1_000_000;
|
||||
const now = () => clock;
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new Error('offline');
|
||||
});
|
||||
const cameras = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras, { now }), 0);
|
||||
assert.equal(cameras[0].groundElevationM, 150);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
|
||||
// The default backoff outlasts the catalog refresh, so the next refresh
|
||||
// and every one inside the backoff cost nothing.
|
||||
assert.ok(KARTVERKET_FAILURE_BACKOFF_MS > CCTV_SOURCE_CACHE_MS);
|
||||
clock += CCTV_SOURCE_CACHE_MS;
|
||||
assert.equal(await applyVegvesenGroundHeights([cameraAt(0)], { now }), 0);
|
||||
clock += KARTVERKET_FAILURE_BACKOFF_MS - CCTV_SOURCE_CACHE_MS - 1;
|
||||
assert.equal(await applyVegvesenGroundHeights([cameraAt(0)], { now }), 0);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
|
||||
// After it, the failed point is asked again.
|
||||
clock += 2;
|
||||
fetchMock.mock.mockImplementation(async (url) =>
|
||||
kartverketResponse(url, () => 321),
|
||||
);
|
||||
const later = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(later, { now }), 1);
|
||||
assert.equal(later[0].groundElevationM, 321);
|
||||
assert.equal(fetchMock.mock.callCount(), 2);
|
||||
});
|
||||
|
||||
test('a 429 backs off for its Retry-After, not the default', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let clock = 1_000_000;
|
||||
const now = () => clock;
|
||||
const retryAfterS = 50 * 60;
|
||||
const fetchMock = t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () =>
|
||||
new Response('busy', {
|
||||
status: 429,
|
||||
headers: { 'Retry-After': String(retryAfterS) },
|
||||
}),
|
||||
);
|
||||
await applyVegvesenGroundHeights([cameraAt(0)], { now });
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
clock += KARTVERKET_FAILURE_BACKOFF_MS + 1;
|
||||
await applyVegvesenGroundHeights([cameraAt(0)], { now });
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
clock += retryAfterS * 1000 - KARTVERKET_FAILURE_BACKOFF_MS;
|
||||
await applyVegvesenGroundHeights([cameraAt(0)], { now });
|
||||
assert.equal(fetchMock.mock.callCount(), 2);
|
||||
});
|
||||
|
||||
test('a lookup cut short by its deadline resumes on the next refresh', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let clock = 1_000_000;
|
||||
const now = () => clock;
|
||||
t.mock.method(globalThis, 'fetch', hangingFetch);
|
||||
// The lookup runs out of time; that is not a failing service.
|
||||
assert.equal(
|
||||
await applyVegvesenGroundHeights([cameraAt(0)], {
|
||||
now,
|
||||
timeoutMs: 10,
|
||||
waitMs: 1000,
|
||||
}),
|
||||
0,
|
||||
);
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
kartverketResponse(url, () => 64),
|
||||
);
|
||||
clock += CCTV_SOURCE_CACHE_MS;
|
||||
const cameras = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras, { now }), 1);
|
||||
assert.equal(cameras[0].groundElevationM, 64);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
});
|
||||
|
||||
test('overlapping refreshes share one lookup', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
await gate;
|
||||
return kartverketResponse(url, () => 3);
|
||||
});
|
||||
await Promise.all([
|
||||
applyVegvesenGroundHeights([cameraAt(0)], { waitMs: 5 }),
|
||||
applyVegvesenGroundHeights([cameraAt(0)], { waitMs: 5 }),
|
||||
]);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
release();
|
||||
});
|
||||
|
||||
test('a warm cache does not wait for a few new cameras', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const cameras = Array.from({ length: 20 }, (_, i) => cameraAt(i));
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
kartverketResponse(url, () => 500),
|
||||
);
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras), 20);
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
await gate;
|
||||
return kartverketResponse(url, () => 600);
|
||||
});
|
||||
const refresh = [...cameras, cameraAt(20)];
|
||||
const started = Date.now();
|
||||
assert.equal(
|
||||
await applyVegvesenGroundHeights(refresh, { waitMs: 5_000 }),
|
||||
20,
|
||||
);
|
||||
assert.ok(Date.now() - started < 1000);
|
||||
assert.equal(fetchMock.mock.callCount(), 1);
|
||||
// The background lookup fills the cache for the next refresh.
|
||||
release();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const next = [...cameras, cameraAt(20)];
|
||||
assert.equal(await applyVegvesenGroundHeights(next), 21);
|
||||
assert.equal(next[20].groundElevationM, 600);
|
||||
});
|
||||
|
||||
test('cameras without numeric coordinates are skipped, never thrown on', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
kartverketResponse(url, () => 9),
|
||||
);
|
||||
const cameras = [
|
||||
{ id: 'no-coordinates' },
|
||||
null,
|
||||
{ id: 'strings', lat: '60', lon: '7' },
|
||||
cameraAt(0),
|
||||
];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras), 1);
|
||||
assert.equal(cameras[3].groundElevationM, 9);
|
||||
});
|
||||
|
||||
test('a lookup started before a cache clear cannot write after it', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
await gate;
|
||||
return kartverketResponse(url, () => 111);
|
||||
});
|
||||
await applyVegvesenGroundHeights([cameraAt(0)], { waitMs: 5 });
|
||||
clearKartverketHeightCache();
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
kartverketResponse(url, () => 222),
|
||||
);
|
||||
const fresh = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(fresh), 1);
|
||||
assert.equal(fresh[0].groundElevationM, 222);
|
||||
release();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const later = [cameraAt(0)];
|
||||
await applyVegvesenGroundHeights(later, { waitMs: 0 });
|
||||
assert.equal(later[0].groundElevationM, 222);
|
||||
});
|
||||
|
||||
test('CCTV_VEGVESEN_HEIGHTS=0 skips the lookup', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
kartverketResponse(url, () => 5),
|
||||
);
|
||||
process.env.CCTV_VEGVESEN_HEIGHTS = '0';
|
||||
const cameras = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(cameras), 0);
|
||||
assert.equal(cameras[0].groundElevationM, 150);
|
||||
assert.equal(fetchMock.mock.callCount(), 0);
|
||||
});
|
||||
|
||||
test('a slow lookup does not hold the catalog; the next refresh applies it', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
await gate;
|
||||
return kartverketResponse(url, () => 812);
|
||||
});
|
||||
const first = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(first, { waitMs: 20 }), 0);
|
||||
assert.equal(first[0].groundElevationM, 150);
|
||||
release();
|
||||
// The lookup kept running and filled the cache for the next refresh.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const next = [cameraAt(0)];
|
||||
assert.equal(await applyVegvesenGroundHeights(next, { waitMs: 20 }), 1);
|
||||
assert.equal(next[0].groundElevationM, 812);
|
||||
});
|
||||
|
||||
test('the loader applies Kartverket heights to the cameras it returns', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
if (String(url).startsWith(KARTVERKET_HEIGHT_URL)) {
|
||||
return kartverketResponse(url, () => 987.6);
|
||||
}
|
||||
return Response.json({ type: 'FeatureCollection', features: [feature()] });
|
||||
});
|
||||
const cameras = await loadVegvesenSourcesFromOpenData();
|
||||
assert.deepEqual(
|
||||
cameras.map((c) => [c.id, c.groundElevationM]),
|
||||
[['no-vegvesen-3000063_1', 987.6]],
|
||||
);
|
||||
});
|
||||
|
||||
test('the loader budgets the height wait from its own start', async (t) => {
|
||||
withHeightsEnv(t);
|
||||
const realNow = Date.now.bind(Date);
|
||||
let offset = 0;
|
||||
t.mock.method(Date, 'now', () => realNow() + offset);
|
||||
t.mock.method(globalThis, 'fetch', (url, init) => {
|
||||
if (String(url).startsWith(KARTVERKET_HEIGHT_URL)) {
|
||||
return hangingFetch(url, init);
|
||||
}
|
||||
// The catalog fetch uses up all but 10 ms of the lane's budget.
|
||||
offset += KARTVERKET_CATALOG_WAIT_MS - 10;
|
||||
return Promise.resolve(
|
||||
Response.json({ type: 'FeatureCollection', features: [feature()] }),
|
||||
);
|
||||
});
|
||||
const started = performance.now();
|
||||
const cameras = await loadVegvesenSourcesFromOpenData();
|
||||
assert.ok(performance.now() - started < 1000);
|
||||
assert.equal(cameras[0].groundElevationM, 150);
|
||||
});
|
||||
+15
-3
@@ -238,8 +238,9 @@ export const DATA_CREDITS = [
|
||||
key: 'ontario-511-cctv',
|
||||
html:
|
||||
'CCTV cameras & frames (Ontario): ' +
|
||||
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a> ' +
|
||||
'(<a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence - Ontario</a>)',
|
||||
'<a href="https://511on.ca/" target="_blank" rel="noopener">Ontario 511</a>. ' +
|
||||
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario" target="_blank" rel="noopener">Open Government Licence – Ontario</a>. ' +
|
||||
'Provided as is, without warranty; actual road conditions may differ.',
|
||||
},
|
||||
{
|
||||
key: 'fintraffic-cctv',
|
||||
@@ -263,6 +264,14 @@ export const DATA_CREDITS = [
|
||||
'Traffic cameras (Calgary): contains information licensed under the ' +
|
||||
'<a href="https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa" target="_blank" rel="noopener">Open Government Licence – City of Calgary</a>',
|
||||
},
|
||||
{
|
||||
key: 'florida-cctv',
|
||||
html:
|
||||
'Traffic cameras (Florida): FL511, Florida Department of Transportation. ' +
|
||||
'Individual, personal use only under the ' +
|
||||
'<a href="https://fl511.com/privacy#disclaimer" target="_blank" rel="noopener">FL511 terms</a>; ' +
|
||||
"any other use needs FDOT's express written consent",
|
||||
},
|
||||
{
|
||||
key: 'catalonia-cctv',
|
||||
html:
|
||||
@@ -285,7 +294,10 @@ export const DATA_CREDITS = [
|
||||
html:
|
||||
'Road cameras (Norway): contains data under the ' +
|
||||
'<a href="https://data.norge.no/nlod/en/2.0" target="_blank" rel="noopener">Norwegian licence for Open Government data (NLOD)</a> ' +
|
||||
'distributed by Statens vegvesen',
|
||||
'distributed by Statens vegvesen · camera ground heights © ' +
|
||||
'<a href="https://kartverket.no/en/api-and-data/terrengdata" target="_blank" rel="noopener">Kartverket</a> ' +
|
||||
'(<a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>); ' +
|
||||
'modified: heights over water set to 0 m and rounded to 0.1 m',
|
||||
},
|
||||
{
|
||||
key: 'nyc-cctv',
|
||||
|
||||
@@ -59,9 +59,13 @@ test('new data proxies install the same routes in dev and preview servers', () =
|
||||
|
||||
test('Launch Library uses a 15-minute cache and optional server-side token header', () => {
|
||||
assert.equal(LL2_CACHE_TTL_MS, 15 * 60_000);
|
||||
assert.deepEqual(launchLibraryRequestHeaders(''), { Accept: 'application/json' });
|
||||
assert.deepEqual(launchLibraryRequestHeaders(' secret '), {
|
||||
const headers = {
|
||||
Accept: 'application/json',
|
||||
'User-Agent': 'gods-eye-view-launch-library-proxy/1.0 (+https://github.com/bilawalsidhu/gods-eye-view)',
|
||||
};
|
||||
assert.deepEqual(launchLibraryRequestHeaders(''), headers);
|
||||
assert.deepEqual(launchLibraryRequestHeaders(' secret '), {
|
||||
...headers,
|
||||
Authorization: 'Token secret',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,10 +7,12 @@ export function celestrakTleUrl(group) {
|
||||
}
|
||||
|
||||
export function launchLibraryRecentUrl(end) {
|
||||
const start = new Date(end.getTime() - 30 * 86400000);
|
||||
// Stable minute boundaries let different installations share LL2's cache.
|
||||
const roundedEnd = new Date(Math.floor(end.getTime() / 60000) * 60000);
|
||||
const start = new Date(roundedEnd.getTime() - 30 * 86400000);
|
||||
const url = new URL('https://ll.thespacedevs.com/2.3.0/launches/');
|
||||
url.searchParams.set('net__gte', start.toISOString());
|
||||
url.searchParams.set('net__lte', end.toISOString());
|
||||
url.searchParams.set('net__lte', roundedEnd.toISOString());
|
||||
url.searchParams.set('limit', '100');
|
||||
url.searchParams.set('mode', 'detailed');
|
||||
return url;
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
*/
|
||||
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import { normalizeVesselType } from './vesselTypes.js';
|
||||
|
||||
export { normalizeVesselType };
|
||||
|
||||
export const VESSEL_OVERLAY_SOURCE_ID = 'ais-live-vessels';
|
||||
/** Existing selector grid size; one ambient winner is retained per cell. */
|
||||
@@ -43,31 +46,6 @@ const TYPE_STYLES = [
|
||||
];
|
||||
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
|
||||
|
||||
const NUMERIC_TYPE_SPECIALS = {
|
||||
30: 'FISHING',
|
||||
31: 'TOWING',
|
||||
32: 'TOWING',
|
||||
33: 'DREDGER',
|
||||
34: 'DIVE OPS',
|
||||
35: 'MILITARY',
|
||||
36: 'SAILING',
|
||||
37: 'PLEASURE',
|
||||
50: 'PILOT',
|
||||
51: 'SAR',
|
||||
52: 'TUG',
|
||||
53: 'PORT TENDER',
|
||||
54: 'ANTI-POLLUTION',
|
||||
55: 'LAW ENFORCE',
|
||||
58: 'MEDICAL',
|
||||
};
|
||||
const NUMERIC_TYPE_FAMILIES = {
|
||||
4: 'HIGH-SPEED',
|
||||
6: 'PASSENGER',
|
||||
7: 'CARGO',
|
||||
8: 'TANKER',
|
||||
9: 'OTHER',
|
||||
};
|
||||
|
||||
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
|
||||
// and tests match on them.
|
||||
const TYPE_DISPLAY_KEYS = Object.freeze({
|
||||
@@ -104,21 +82,6 @@ export function displayVesselType(type) {
|
||||
return key ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an AIS type to display text: bare numeric ship-type codes map to
|
||||
* family names ("71" → "CARGO"); text types pass through unchanged.
|
||||
* @param {string} type Raw AIS type.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeVesselType(type) {
|
||||
const text = String(type || '').trim();
|
||||
if (!text || !/^\d{1,2}$/.test(text)) return text;
|
||||
const code = Number(text);
|
||||
if (code <= 0) return '';
|
||||
if (NUMERIC_TYPE_SPECIALS[code]) return NUMERIC_TYPE_SPECIALS[code];
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
|
||||
/** AIS ship type → CSS hex hue for the billboard chevron. */
|
||||
export function vesselTypeCss(type) {
|
||||
return styleForType(type).css;
|
||||
|
||||
@@ -29,6 +29,8 @@ test('normalizeVesselType preserves text and degrades unknown codes', () => {
|
||||
assert.equal(normalizeVesselType('Crude Oil Tanker'), 'Crude Oil Tanker');
|
||||
assert.equal(normalizeVesselType('0'), '');
|
||||
assert.equal(normalizeVesselType('25'), 'OTHER');
|
||||
assert.equal(normalizeVesselType('100'), '');
|
||||
assert.equal(normalizeVesselType('255'), '');
|
||||
assert.equal(normalizeVesselType(undefined), '');
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @module vesselTypes
|
||||
* @description AIS ship-type codes (ITU-R M.1371) to family names, with no
|
||||
* browser or i18n dependencies so the server-side query tools can use it.
|
||||
*/
|
||||
|
||||
const NUMERIC_TYPE_SPECIALS = {
|
||||
30: 'FISHING',
|
||||
31: 'TOWING',
|
||||
32: 'TOWING',
|
||||
33: 'DREDGER',
|
||||
34: 'DIVE OPS',
|
||||
35: 'MILITARY',
|
||||
36: 'SAILING',
|
||||
37: 'PLEASURE',
|
||||
50: 'PILOT',
|
||||
51: 'SAR',
|
||||
52: 'TUG',
|
||||
53: 'PORT TENDER',
|
||||
54: 'ANTI-POLLUTION',
|
||||
55: 'LAW ENFORCE',
|
||||
58: 'MEDICAL',
|
||||
};
|
||||
const NUMERIC_TYPE_FAMILIES = {
|
||||
4: 'HIGH-SPEED',
|
||||
6: 'PASSENGER',
|
||||
7: 'CARGO',
|
||||
8: 'TANKER',
|
||||
9: 'OTHER',
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve an AIS type to display text: bare numeric ship-type codes map to
|
||||
* family names ("71" → "CARGO"); text types pass through unchanged. Code 0
|
||||
* ("not available") and the reserved codes 100 to 255 name no type and
|
||||
* resolve to "".
|
||||
* @param {string} type Raw AIS type.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeVesselType(type) {
|
||||
const text = String(type || '').trim();
|
||||
if (!text || !/^\d+$/.test(text)) return text;
|
||||
const code = Number(text);
|
||||
if (code <= 0 || code >= 100) return '';
|
||||
if (NUMERIC_TYPE_SPECIALS[code]) return NUMERIC_TYPE_SPECIALS[code];
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export function editSceneDetails(
|
||||
'holdSec',
|
||||
'dataPackIds',
|
||||
'interactions',
|
||||
'lens',
|
||||
].includes(key)
|
||||
)
|
||||
throw new Error('Unsupported shot detail');
|
||||
@@ -39,7 +38,6 @@ export function editSceneDetails(
|
||||
'holdSec',
|
||||
'dataPackIds',
|
||||
'interactions',
|
||||
'lens',
|
||||
]) {
|
||||
delete shot[key];
|
||||
if (Object.hasOwn(shotDetails, key)) shot[key] = shotDetails[key];
|
||||
|
||||
@@ -17,45 +17,9 @@ export function resolveCameraPose(scene, camera) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Columns of one recorded track sample; focal length is optional. */
|
||||
export const CAMERA_TRACK_COLUMNS = Object.freeze([
|
||||
't',
|
||||
'lon',
|
||||
'lat',
|
||||
'alt',
|
||||
'heading',
|
||||
'pitch',
|
||||
'roll',
|
||||
'focalMm',
|
||||
]);
|
||||
|
||||
/** Expand one compact track sample into a pose; `t` stays in recorded seconds. */
|
||||
export function cameraTrackSample(sample) {
|
||||
const pose = {
|
||||
t: sample[0],
|
||||
lon: sample[1],
|
||||
lat: sample[2],
|
||||
alt: sample[3],
|
||||
heading: sample[4],
|
||||
pitch: sample[5],
|
||||
roll: sample[6],
|
||||
};
|
||||
if (Number.isFinite(sample[7])) pose.focalMm = sample[7];
|
||||
return pose;
|
||||
}
|
||||
|
||||
/** Resolve both authored endpoints. An explicit move never depends on the live viewport. */
|
||||
export function resolveCameraMove(scene, shot) {
|
||||
if (!shot?.move) return null;
|
||||
if (shot.move.track) {
|
||||
const samples = shot.move.track.samples;
|
||||
return {
|
||||
from: sampleCameraTrack(samples, 0),
|
||||
to: sampleCameraTrack(samples, 1),
|
||||
track: samples,
|
||||
durationSec: shot.durationSec,
|
||||
};
|
||||
}
|
||||
return {
|
||||
from: resolveCameraPose(scene, shot.move.from),
|
||||
to: resolveCameraPose(scene, shot.camera),
|
||||
@@ -69,57 +33,8 @@ export function normalizeCameraLongitude(longitude) {
|
||||
return ((((longitude + 180) % 360) + 360) % 360) - 180;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample a recorded track at normalized progress. The recording is stretched
|
||||
* to the shot duration, so editing `durationSec` retimes a take without
|
||||
* touching its samples. Angles and longitude take the short arc between
|
||||
* neighbouring samples.
|
||||
*/
|
||||
export function sampleCameraTrack(samples, progress) {
|
||||
const t = Math.max(0, Math.min(1, Number(progress) || 0));
|
||||
const last = samples.length - 1;
|
||||
const exact = (sample) => {
|
||||
const { t: _recorded, ...pose } = cameraTrackSample(sample);
|
||||
return pose;
|
||||
};
|
||||
if (t === 0) return exact(samples[0]);
|
||||
if (t === 1) return exact(samples[last]);
|
||||
const target = t * samples[last][0];
|
||||
let low = 0;
|
||||
let high = last;
|
||||
while (high - low > 1) {
|
||||
const middle = (low + high) >> 1;
|
||||
if (samples[middle][0] <= target) low = middle;
|
||||
else high = middle;
|
||||
}
|
||||
const a = cameraTrackSample(samples[low]);
|
||||
const b = cameraTrackSample(samples[high]);
|
||||
const span = b.t - a.t;
|
||||
const k = span > 0 ? Math.max(0, Math.min(1, (target - a.t) / span)) : 1;
|
||||
// A time that lands on a recorded sample returns it unchanged.
|
||||
if (k === 0) return exact(samples[low]);
|
||||
if (k === 1) return exact(samples[high]);
|
||||
const lerp = (from, to) => from + (to - from) * k;
|
||||
const angle = (from, to) =>
|
||||
from + (((((to - from + 540) % 360) + 360) % 360) - 180) * k;
|
||||
const pose = {
|
||||
lat: lerp(a.lat, b.lat),
|
||||
lon: normalizeCameraLongitude(angle(a.lon, b.lon)),
|
||||
alt: lerp(a.alt, b.alt),
|
||||
heading: angle(a.heading, b.heading),
|
||||
pitch: lerp(a.pitch, b.pitch),
|
||||
roll: angle(a.roll, b.roll),
|
||||
};
|
||||
if (Number.isFinite(a.focalMm) && Number.isFinite(b.focalMm))
|
||||
pose.focalMm = lerp(a.focalMm, b.focalMm);
|
||||
else if (Number.isFinite(a.focalMm ?? b.focalMm))
|
||||
pose.focalMm = a.focalMm ?? b.focalMm;
|
||||
return pose;
|
||||
}
|
||||
|
||||
/** Sample the same authored curve for playback and seeking, taking the short longitude/angle arc. */
|
||||
export function sampleCameraMove(move, progress) {
|
||||
if (move.track) return sampleCameraTrack(move.track, progress);
|
||||
const t = Math.max(0, Math.min(1, Number(progress) || 0));
|
||||
if (t === 0) return { ...move.from };
|
||||
if (t === 1) return { ...move.to };
|
||||
|
||||
@@ -73,7 +73,7 @@ test('v3 unversioned bloom already uses scale 2 and is not migrated again in lat
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(project.version, 7);
|
||||
assert.equal(project.version, 6);
|
||||
assert.equal(project.scenes[0].shots[0].visual.bloom.intensity, 50);
|
||||
});
|
||||
test('move endpoints, easing, shortest arcs and hold agree with scene seeking', () => {
|
||||
|
||||
@@ -50,59 +50,6 @@ function pose(value, path, version, anchorIds, explicit = false) {
|
||||
}
|
||||
}
|
||||
|
||||
// Recorded focal lengths are 35 mm-equivalent; the range spans fisheye to supertele.
|
||||
export const FOCAL_LENGTH_MM = Object.freeze([4, 2000]);
|
||||
const TRACK_COLUMNS = [
|
||||
[-1, 86400],
|
||||
POSITION.lon,
|
||||
POSITION.lat,
|
||||
POSITION.alt,
|
||||
ORIENTATION.heading,
|
||||
ORIENTATION.pitch,
|
||||
ORIENTATION.roll,
|
||||
FOCAL_LENGTH_MM,
|
||||
];
|
||||
function track(value, path) {
|
||||
fields(value, path, ['altitudeReference', 'samples']);
|
||||
reference(value.altitudeReference, `${path}.altitudeReference`);
|
||||
array(value.samples, `${path}.samples`);
|
||||
if (value.samples.length < 2)
|
||||
fail(`${path}.samples`, 'expected at least two samples');
|
||||
let previous = -1;
|
||||
value.samples.forEach((sample, i) => {
|
||||
const at = `${path}.samples[${i}]`;
|
||||
if (!Array.isArray(sample) || sample.length < 7 || sample.length > 8)
|
||||
fail(at, 'expected [t, lon, lat, alt, heading, pitch, roll, focalMm?]');
|
||||
sample.forEach((item, column) =>
|
||||
number(item, `${at}[${column}]`, ...TRACK_COLUMNS[column], false),
|
||||
);
|
||||
if (i === 0 ? sample[0] !== 0 : sample[0] <= previous)
|
||||
fail(
|
||||
`${at}[0]`,
|
||||
i === 0
|
||||
? 'expected the first sample at 0 seconds'
|
||||
: 'expected increasing sample times',
|
||||
);
|
||||
previous = sample[0];
|
||||
});
|
||||
}
|
||||
|
||||
/** Validate a shot lens: focal length and an optional depth-of-field focus. */
|
||||
export function validateShotLens(lens, path) {
|
||||
fields(lens, path, ['focalMm', 'dof']);
|
||||
optional(lens, 'focalMm', path, (v, p) =>
|
||||
number(v, p, ...FOCAL_LENGTH_MM, false),
|
||||
);
|
||||
optional(lens, 'dof', path, (dof, field) => {
|
||||
fields(dof, field, ['enabled', 'focusM', 'fStop', 'scale']);
|
||||
if (typeof dof.enabled !== 'boolean')
|
||||
fail(`${field}.enabled`, 'expected a boolean');
|
||||
optional(dof, 'focusM', field, (v, p) => number(v, p, 0.1, 1e8, false));
|
||||
optional(dof, 'fStop', field, (v, p) => number(v, p, 0.5, 64, false));
|
||||
optional(dof, 'scale', field, (v, p) => number(v, p, 1e-3, 1e7, false));
|
||||
});
|
||||
}
|
||||
|
||||
/** Validate scene-local anchor IDs, camera references and explicit motion without reading terrain or applying state. */
|
||||
export function validateSceneCameras(scene, path, version) {
|
||||
const anchorIds = new Set();
|
||||
@@ -126,14 +73,6 @@ export function validateSceneCameras(scene, path, version) {
|
||||
scene.shots.forEach((shot, index) => {
|
||||
const at = `${path}.shots[${index}]`;
|
||||
optional(shot, 'move', at, (move, field) => {
|
||||
if (version >= 7 && Object.hasOwn(move || {}, 'track')) {
|
||||
fields(move, field, ['track']);
|
||||
track(move.track, `${field}.track`);
|
||||
pose(shot.camera, `${at}.camera`, version, anchorIds, true);
|
||||
number(shot.durationSec, `${at}.durationSec`, 0.2, 86400, false);
|
||||
number(shot.holdSec, `${at}.holdSec`, 0, 86400, false);
|
||||
return;
|
||||
}
|
||||
fields(move, field, ['from', 'easing']);
|
||||
if (!['linear', 'cubic-in-out'].includes(move.easing))
|
||||
fail(`${field}.easing`, 'expected linear or cubic-in-out');
|
||||
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
jsonTree,
|
||||
} from './documentFields.js';
|
||||
import { validateSceneDataPacks } from './packs/manifest.js';
|
||||
import { validateSceneCameras, validateShotLens } from './cameraDocument.js';
|
||||
import { validateSceneCameras } from './cameraDocument.js';
|
||||
export { SCENE_DOCUMENT_LIMITS, SceneDocumentError } from './documentFields.js';
|
||||
import { validateSceneInteractions } from './interactions/document.js';
|
||||
export const SCENE_DOCUMENT_VERSION = 7;
|
||||
export const SCENE_DOCUMENT_VERSION = 6;
|
||||
|
||||
function visual(value, path, legacy) {
|
||||
fields(value, path, [
|
||||
@@ -67,7 +67,7 @@ export function validateSceneDocument(project) {
|
||||
'scenes',
|
||||
]);
|
||||
const version = Object.hasOwn(project, 'version') ? project.version : 1;
|
||||
if (![1, 2, 3, 4, 5, 6, 7].includes(version))
|
||||
if (![1, 2, 3, 4, 5, 6].includes(version))
|
||||
fail('$.version', 'unsupported scene project version');
|
||||
const legacy = version < 3;
|
||||
for (const key of ['createdAt', 'updatedAt'])
|
||||
@@ -128,7 +128,6 @@ export function validateSceneDocument(project) {
|
||||
...(version >= 4 ? ['move'] : []),
|
||||
...(version >= 5 ? ['dataPackIds'] : []),
|
||||
...(version >= 6 ? ['interactions'] : []),
|
||||
...(version >= 7 ? ['lens'] : []),
|
||||
]);
|
||||
uniqueId(shot, at, shotIds);
|
||||
optional(shot, 'title', at, (v, p) => string(v, p, 4096));
|
||||
@@ -141,7 +140,6 @@ export function validateSceneDocument(project) {
|
||||
);
|
||||
optional(shot, 'holdSec', at, (v, p) => number(v, p, 0, 86400, legacy));
|
||||
optional(shot, 'visual', at, (v, p) => visual(v, p, legacy));
|
||||
optional(shot, 'lens', at, validateShotLens);
|
||||
optional(shot, 'layers', at, (layers, field) => {
|
||||
object(layers, field);
|
||||
for (const [id, entry] of Object.entries(layers)) {
|
||||
|
||||
@@ -59,7 +59,7 @@ test('v1/v2 bloom migrates once; IDs, edits, pack bindings and zero holds surviv
|
||||
const migrated = normalizeProject(
|
||||
parseSceneDocument(JSON.stringify(project)),
|
||||
);
|
||||
assert.equal(migrated.version, 7);
|
||||
assert.equal(migrated.version, 6);
|
||||
assert.equal(migrated.scenes[0].shots[0].visual.bloom.intensity, 150);
|
||||
assert.equal(migrated.scenes[0].shots[0].id, 'shot');
|
||||
assert.deepEqual(
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* Renderer-independent lens math. Focal lengths are 35 mm full-frame
|
||||
* equivalents measured across the frame's longer side (36 mm), which is the
|
||||
* dimension Cesium's `PerspectiveFrustum.fov` describes.
|
||||
*/
|
||||
export const SENSOR_LONG_SIDE_MM = 36;
|
||||
|
||||
/** Cesium's default 60-degree field of view expressed as a focal length. */
|
||||
export const DEFAULT_FOCAL_MM = SENSOR_LONG_SIDE_MM / 2 / Math.tan(Math.PI / 6);
|
||||
|
||||
/** Field of view in radians across the longer side for a focal length. */
|
||||
export function focalLengthToFov(focalMm) {
|
||||
return 2 * Math.atan(SENSOR_LONG_SIDE_MM / (2 * focalMm));
|
||||
}
|
||||
|
||||
/** Focal length in millimetres for a field of view across the longer side. */
|
||||
export function fovToFocalLength(fovRad) {
|
||||
return SENSOR_LONG_SIDE_MM / (2 * Math.tan(fovRad / 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Thin-lens circle-of-confusion radius in pixels. `sceneScale` divides world
|
||||
* distances first, so a 1:1000 rig focuses on the city as if it were a
|
||||
* tabletop model and produces the matching shallow depth of field. The
|
||||
* depth-of-field shader evaluates the same expression per pixel.
|
||||
*/
|
||||
export function circleOfConfusionPx({
|
||||
focalMm,
|
||||
fStop,
|
||||
focusM,
|
||||
distanceM,
|
||||
sceneScale = 1,
|
||||
viewportPx,
|
||||
}) {
|
||||
const f = focalMm / 1000;
|
||||
const focus = Math.max(focusM / sceneScale, f * 1.01);
|
||||
const distance = Math.max(distanceM / sceneScale, 1e-4);
|
||||
const diameterM =
|
||||
((f * f) / (fStop * (focus - f))) * (Math.abs(distance - focus) / distance);
|
||||
return (0.5 * diameterM * 1000 * viewportPx) / SENSOR_LONG_SIDE_MM;
|
||||
}
|
||||
@@ -51,7 +51,7 @@ test('v5 packs and shot references round trip through project migration without
|
||||
JSON.stringify({ version, scenes: [{ id: 'old', shots: [] }] }),
|
||||
),
|
||||
);
|
||||
assert.equal(old.version, 7);
|
||||
assert.equal(old.version, 6);
|
||||
assert.equal(old.scenes[0].dataPacks, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseSceneDocument, stringifySceneDocument } from './document.js';
|
||||
import { normalizeProject } from '../scenes/project.js';
|
||||
import {
|
||||
resolveCameraMove,
|
||||
sampleCameraMove,
|
||||
sampleCameraTrack,
|
||||
} from './camera.js';
|
||||
import { sceneSeekState } from './timeline.js';
|
||||
import {
|
||||
DEFAULT_FOCAL_MM,
|
||||
circleOfConfusionPx,
|
||||
focalLengthToFov,
|
||||
fovToFocalLength,
|
||||
} from './lens.js';
|
||||
|
||||
const samples = () => [
|
||||
[0, 179.9, 10, 500, 350, -30, 0, 24],
|
||||
[1, -179.9, 10.5, 600, 10, -20, 2, 50],
|
||||
[3, -179.7, 11, 400, 30, -10, 4, 50],
|
||||
];
|
||||
const fixture = (move = { track: { altitudeReference: 'ellipsoid', samples: samples() } }) => ({
|
||||
version: 7,
|
||||
scenes: [
|
||||
{
|
||||
id: 'scene',
|
||||
shots: [
|
||||
{
|
||||
id: 'take',
|
||||
title: 'Take 1',
|
||||
durationSec: 3,
|
||||
holdSec: 1,
|
||||
camera: { lat: 11, lon: -179.7, alt: 400, heading: 30, pitch: -10, roll: 4, altitudeReference: 'ellipsoid' },
|
||||
move,
|
||||
lens: { focalMm: 50, dof: { enabled: true, focusM: 250, fStop: 1.8, scale: 1000 } },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
test('a recorded track round trips through the document and project migration', () => {
|
||||
const project = normalizeProject(parseSceneDocument(JSON.stringify(fixture())));
|
||||
const shot = project.scenes[0].shots[0];
|
||||
assert.deepEqual(shot.move.track.samples, samples());
|
||||
assert.deepEqual(shot.lens, fixture().scenes[0].shots[0].lens);
|
||||
assert.deepEqual(parseSceneDocument(stringifySceneDocument(project)).scenes[0].shots[0].move, fixture().scenes[0].shots[0].move);
|
||||
});
|
||||
|
||||
test('track samples interpolate by recorded time, take short arcs and keep exact endpoints', () => {
|
||||
const rows = samples();
|
||||
assert.deepEqual(sampleCameraTrack(rows, 0), { lon: 179.9, lat: 10, alt: 500, heading: 350, pitch: -30, roll: 0, focalMm: 24 });
|
||||
assert.deepEqual(sampleCameraTrack(rows, 1), { lon: -179.7, lat: 11, alt: 400, heading: 30, pitch: -10, roll: 4, focalMm: 50 });
|
||||
const mid = sampleCameraTrack(rows, 1 / 6); // 0.5 s, halfway through the first segment
|
||||
assert.ok(Math.abs(Math.abs(mid.lon) - 180) < 1e-9, 'longitude crosses the dateline, not the globe');
|
||||
assert.ok(Math.abs(mid.heading - 360) < 1e-9 || Math.abs(mid.heading) < 1e-9);
|
||||
assert.equal(mid.alt, 550);
|
||||
assert.equal(mid.focalMm, 37);
|
||||
const late = sampleCameraTrack(rows, 2 / 3); // 2 s, halfway through the second segment
|
||||
assert.equal(late.alt, 500);
|
||||
assert.equal(late.heading, 20);
|
||||
const noFocal = sampleCameraTrack(rows.map((row) => row.slice(0, 7)), 0.5);
|
||||
assert.equal(Object.hasOwn(noFocal, 'focalMm'), false);
|
||||
});
|
||||
|
||||
test('a track stretches to its shot duration and drives scene seeking', () => {
|
||||
const scene = normalizeProject(parseSceneDocument(JSON.stringify(fixture()))).scenes[0];
|
||||
const shot = scene.shots[0];
|
||||
const move = resolveCameraMove(scene, shot);
|
||||
assert.equal(move.from.alt, 500);
|
||||
assert.equal(move.to.alt, 400);
|
||||
assert.deepEqual(sampleCameraMove(move, 2 / 3), sampleCameraTrack(shot.move.track.samples, 2 / 3));
|
||||
// Doubling the duration plays the same path at half speed.
|
||||
shot.durationSec = 6;
|
||||
const seek = sceneSeekState(scene, 2 / 7, (_, item) => item.durationSec + item.holdSec, (_, item) => item.holdSec);
|
||||
assert.equal(seek.cameraProgress, 1 / 3);
|
||||
assert.equal(seek.camera.alt, 600);
|
||||
});
|
||||
|
||||
test('malformed tracks and lenses are rejected with a field path', () => {
|
||||
const bad = (mutate, pattern) => {
|
||||
const doc = fixture();
|
||||
mutate(doc.scenes[0].shots[0]);
|
||||
assert.throws(() => parseSceneDocument(JSON.stringify(doc)), pattern);
|
||||
};
|
||||
bad((shot) => { shot.move.track.samples = [shot.move.track.samples[0]]; }, /at least two samples/);
|
||||
bad((shot) => { shot.move.track.samples[0][0] = 0.1; }, /first sample at 0/);
|
||||
bad((shot) => { shot.move.track.samples[2][0] = 1; }, /increasing sample times/);
|
||||
bad((shot) => { shot.move.track.samples[1] = [1, 0, 0]; }, /samples\[1\]: expected \[t, lon/);
|
||||
bad((shot) => { shot.move.track.samples[1][2] = 91; }, /samples\[1\]\[2\]/);
|
||||
bad((shot) => { shot.move.track.samples[1][7] = 1; }, /samples\[1\]\[7\]/);
|
||||
bad((shot) => { delete shot.move.track.altitudeReference; }, /altitudeReference/);
|
||||
bad((shot) => { shot.move.easing = 'linear'; }, /move\.easing: unsupported field/);
|
||||
bad((shot) => { shot.lens.focalMm = 1; }, /lens\.focalMm/);
|
||||
bad((shot) => { shot.lens.dof.enabled = 'yes'; }, /lens\.dof\.enabled/);
|
||||
bad((shot) => { shot.lens.aperture = 2; }, /lens\.aperture: unsupported field/);
|
||||
const v6 = fixture();
|
||||
v6.version = 6;
|
||||
assert.throws(() => parseSceneDocument(JSON.stringify(v6)), /lens: unsupported field/);
|
||||
delete v6.scenes[0].shots[0].lens;
|
||||
assert.throws(() => parseSceneDocument(JSON.stringify(v6)), /move\.track: unsupported field/);
|
||||
});
|
||||
|
||||
test('focal lengths convert to Cesium field of view and back', () => {
|
||||
assert.ok(Math.abs(focalLengthToFov(DEFAULT_FOCAL_MM) - Math.PI / 3) < 1e-12);
|
||||
assert.ok(Math.abs(fovToFocalLength(focalLengthToFov(85)) - 85) < 1e-9);
|
||||
assert.ok(focalLengthToFov(14) > focalLengthToFov(200));
|
||||
});
|
||||
|
||||
test('the miniature scale turns invisible real-world blur into tabletop depth of field', () => {
|
||||
const lens = { focalMm: 35, fStop: 2.8, focusM: 500, distanceM: 1000, viewportPx: 1920 };
|
||||
assert.ok(circleOfConfusionPx(lens) < 0.05, 'a real 35 mm lens barely blurs a city');
|
||||
const miniature = circleOfConfusionPx({ ...lens, sceneScale: 1000 });
|
||||
assert.ok(miniature > 10 && miniature < 20, `1:1000 blurs like a model (${miniature})`);
|
||||
assert.equal(circleOfConfusionPx({ ...lens, distanceM: 500, sceneScale: 1000 }), 0);
|
||||
assert.ok(circleOfConfusionPx({ ...lens, sceneScale: 1000, fStop: 16 }) < miniature / 4);
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { localProviderPlugins } from '../server/providers/local.js';
|
||||
import { standaloneVoiceTools } from '../server/standalone/voiceTools.js';
|
||||
import {
|
||||
KEY_SETUP_KEYS,
|
||||
keySetupStatus,
|
||||
validateKeySetupUpdates,
|
||||
upsertDotenvValues,
|
||||
} from './keySetupCore.mjs';
|
||||
|
||||
test('local hosts opt into Gemini explicitly and retain the default plugin order', (t) => {
|
||||
t.mock.method(globalThis, 'fetch', () => {
|
||||
throw Error('construction must not fetch');
|
||||
});
|
||||
const defaults = localProviderPlugins().map((plugin) => plugin.name);
|
||||
assert.ok(!defaults.includes('gemini-live-proxy'));
|
||||
const enabled = localProviderPlugins({ gemini: {} }).map(
|
||||
(plugin) => plugin.name,
|
||||
);
|
||||
assert.equal(
|
||||
enabled.filter((name) => name === 'gemini-live-proxy').length,
|
||||
1,
|
||||
);
|
||||
assert.deepEqual(
|
||||
enabled.filter((name) => name !== 'gemini-live-proxy'),
|
||||
defaults,
|
||||
);
|
||||
});
|
||||
|
||||
for (const hook of ['configureServer', 'configurePreviewServer']) {
|
||||
test(`opted-in ${hook} locks the standalone catalog into the Gemini token`, async () => {
|
||||
const tools = standaloneVoiceTools();
|
||||
const calls = [];
|
||||
const plugin = localProviderPlugins({
|
||||
gemini: {
|
||||
tools,
|
||||
resolveApiKey: () => 'fixture-key',
|
||||
resolveModel: () => 'gemini-3.8-live',
|
||||
resolveHost: () => '',
|
||||
resolveAllowedHosts: () => '',
|
||||
resolveRateLimit: () => '0',
|
||||
fetchImpl: async (url, options) => {
|
||||
calls.push({ url, options });
|
||||
return Response.json({ name: 'auth_tokens/fixture' });
|
||||
},
|
||||
},
|
||||
}).find((entry) => entry.name === 'gemini-live-proxy');
|
||||
let handler;
|
||||
plugin[hook]({
|
||||
middlewares: {
|
||||
use(route, value) {
|
||||
assert.equal(route, '/api/gemini/token');
|
||||
handler = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
const req = new PassThrough();
|
||||
req.method = 'POST';
|
||||
req.headers = {
|
||||
host: 'localhost:5173',
|
||||
origin: 'http://localhost:5173',
|
||||
'content-type': 'application/json',
|
||||
};
|
||||
req.socket = { remoteAddress: '127.0.0.1' };
|
||||
const res = new EventEmitter();
|
||||
res.setHeader = () => {};
|
||||
res.end = (body) => {
|
||||
res.body = JSON.parse(body);
|
||||
res.writableEnded = true;
|
||||
};
|
||||
req.end('{}');
|
||||
await handler(req, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(calls.length, 1);
|
||||
const locked = JSON.parse(calls[0].options.body).bidiGenerateContentSetup
|
||||
.tools[0].functionDeclarations;
|
||||
assert.deepEqual(
|
||||
locked.map(({ name }) => name),
|
||||
tools.map(({ name }) => name),
|
||||
);
|
||||
assert.deepEqual(
|
||||
locked.map(({ parametersJsonSchema }) => parametersJsonSchema),
|
||||
tools.map(({ parameters }) => parameters),
|
||||
);
|
||||
assert.ok(locked.every(({ behavior }) => behavior === 'BLOCKING'));
|
||||
assert.deepEqual(res.body.config.tools[0].functionDeclarations, locked);
|
||||
assert.ok(!JSON.stringify(res.body).includes('fixture-key'));
|
||||
});
|
||||
}
|
||||
|
||||
test('Gemini key setup uses the existing server-only status and save contract', () => {
|
||||
const entry = KEY_SETUP_KEYS.find(({ id }) => id === 'gemini');
|
||||
assert.deepEqual(entry.envVars, ['GEMINI_API_KEY']);
|
||||
assert.ok(!entry.clientExposed);
|
||||
assert.equal(
|
||||
keySetupStatus({}).keys.find(({ id }) => id === 'gemini').set,
|
||||
false,
|
||||
);
|
||||
const env = { GEMINI_API_KEY: 'fixture-private-key' };
|
||||
const status = keySetupStatus(env);
|
||||
assert.equal(status.keys.find(({ id }) => id === 'gemini').set, true);
|
||||
assert.ok(!JSON.stringify(status).includes(env.GEMINI_API_KEY));
|
||||
assert.equal(validateKeySetupUpdates(env).ok, true);
|
||||
assert.match(
|
||||
upsertDotenvValues('GEMINI_API_KEY=old\n', env),
|
||||
/^GEMINI_API_KEY=fixture-private-key\n$/,
|
||||
);
|
||||
assert.equal(
|
||||
validateKeySetupUpdates({ VITE_GEMINI_API_KEY: 'fixture-private-key' }).ok,
|
||||
false,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
+53
-49
@@ -842,7 +842,8 @@
|
||||
"Real live traffic (keyless runs a simulation)": "Tráfico real en vivo (sin clave se usa una simulación)",
|
||||
"Bing imagery map stacks + world terrain": "Imágenes de Bing + terreno mundial",
|
||||
"More flight-polling credits (anonymous works without)": "Más créditos de consulta de vuelos (sin clave funciona el modo anónimo)",
|
||||
"Higher space-missions request allowance": "Mayor límite de peticiones para misiones espaciales",
|
||||
"Public space-missions access needs no key. Leave blank for standard use; paid tokens only raise request limits.": "El acceso público a misiones espaciales no necesita clave. Déjalo en blanco para el uso estándar; los tokens de pago solo aumentan los límites de solicitudes.",
|
||||
"Optional paid token — public access works without one": "Token opcional de pago — el acceso público funciona sin él",
|
||||
"Scene action failed": "La acción de escena falló",
|
||||
"Project exported": "Proyecto exportado",
|
||||
"Next session: {pendingId} — this session stays on {modelId}": "Sesión siguiente: {pendingId} — esta sesión sigue en {modelId}",
|
||||
@@ -2890,52 +2891,55 @@
|
||||
"SDR decoder did not start; receiver stopped": "El decodificador SDR no arrancó; receptor detenido",
|
||||
"SDR decoder stopped responding; receiver stopped": "El decodificador SDR dejó de responder; receptor detenido",
|
||||
"SDR decoder fell behind; receiver stopped": "El decodificador SDR se quedó atrás; receptor detenido",
|
||||
"Held from the phone": "En pausa desde el teléfono",
|
||||
"Held: you moved the globe — press RESUME or tap HOLD on the phone": "En pausa: moviste el globo — pulsa REANUDAR o toca PAUSA en el teléfono",
|
||||
"Held": "En pausa",
|
||||
"Held: another view took the camera": "En pausa: otra vista tomó la cámara",
|
||||
"Starting…": "Iniciando…",
|
||||
"Phone camera off": "Cámara del teléfono apagada",
|
||||
"Scan the code with a phone on the same Wi-Fi": "Escanea el código con un teléfono en la misma red Wi-Fi",
|
||||
"AR tracking (6DoF)": "Seguimiento AR (6DoF)",
|
||||
"Gyro tracking (3DoF)": "Seguimiento por giroscopio (3DoF)",
|
||||
"Recording {time} · {mode}": "Grabando {time} · {mode}",
|
||||
"Phone connected · {mode} · {count} takes": {
|
||||
"one": "Teléfono conectado · {mode} · {count} toma",
|
||||
"many": "Teléfono conectado · {mode} · {count} tomas",
|
||||
"other": "Teléfono conectado · {mode} · {count} tomas"
|
||||
},
|
||||
"Phone connected · {mode}": "Teléfono conectado · {mode}",
|
||||
"HOLD": "PAUSA",
|
||||
"■ STOP": "■ DETENER",
|
||||
"● REC": "● GRABAR",
|
||||
"The phone camera service is unavailable": "El servicio de cámara del teléfono no está disponible",
|
||||
"The phone camera port is in use (set VCAM_PORT)": "El puerto de la cámara del teléfono está en uso (configura VCAM_PORT)",
|
||||
"No network connection for a phone to reach": "No hay conexión de red a la que pueda llegar un teléfono",
|
||||
"Phone camera session ended": "Sesión de cámara del teléfono finalizada",
|
||||
"Nothing to focus on there": "No hay nada que enfocar ahí",
|
||||
"Take reached its length limit and was saved": "La toma alcanzó su duración máxima y se guardó",
|
||||
"Take saved to the scene": "Toma guardada en la escena",
|
||||
"Take too short to keep": "Toma demasiado corta para guardarla",
|
||||
"Recorded: {scene} / {shot}": "Grabado: {scene} / {shot}",
|
||||
"Use a phone on this network as a virtual camera": "Usa un teléfono de esta red como cámara virtual",
|
||||
"Phone virtual camera": "Cámara virtual del teléfono",
|
||||
"Pairing QR code": "Código QR de vinculación",
|
||||
"SCAN WITH YOUR PHONE": "ESCANEA CON TU TELÉFONO",
|
||||
"Network address": "Dirección de red",
|
||||
"SCALE": "ESCALA",
|
||||
"1:1 WALK": "1:1 A PIE",
|
||||
"1:10 CRANE": "1:10 GRÚA",
|
||||
"1:100 DRONE": "1:100 DRON",
|
||||
"1:1000 FLYOVER": "1:1000 SOBREVUELO",
|
||||
"1:10000 ORBIT": "1:10000 ÓRBITA",
|
||||
"LENS": "LENTE",
|
||||
"DEPTH OF FIELD": "PROFUNDIDAD DE CAMPO",
|
||||
"APERTURE": "APERTURA",
|
||||
"RECENTER": "RECENTRAR",
|
||||
"END": "TERMINAR",
|
||||
"Takes become shots in the selected scene.": "Las tomas se convierten en planos de la escena seleccionada.",
|
||||
"Phone certificate": "Certificado del teléfono",
|
||||
"VCAM": "VCAM",
|
||||
"Exit cockpit to use the phone camera": "Sal de la cabina para usar la cámara del teléfono"
|
||||
"Gemini returned an oversized audio chunk": "Gemini devolvió un fragmento de audio demasiado grande",
|
||||
"Gemini returned an unsupported audio format": "Gemini devolvió un formato de audio no compatible",
|
||||
"Gemini returned an invalid audio sample rate": "Gemini devolvió una frecuencia de muestreo de audio no válida",
|
||||
"Gemini returned incomplete PCM audio": "Gemini devolvió audio PCM incompleto",
|
||||
"This browser does not support Gemini microphone audio": "Este navegador no admite audio del micrófono para Gemini",
|
||||
"Microphone audio processing failed": "Falló el procesamiento del audio del micrófono",
|
||||
"Gemini audio playback fell behind. Reconnect to continue.": "La reproducción de audio de Gemini se ha retrasado. Vuelve a conectar para continuar.",
|
||||
"Gemini token response did not include an ephemeral credential": "La respuesta de Gemini no incluyó una credencial temporal",
|
||||
"Invalid Gemini connection endpoint": "El destino de conexión de Gemini no es válido",
|
||||
"Voice command context is too large": "El contexto del comando de voz es demasiado grande",
|
||||
"Gemini reliable transport exceeded its queue limit. Start voice again.": "La cola de envío fiable de Gemini superó su límite. Vuelve a iniciar la voz.",
|
||||
"Gemini reliable transport did not drain. Start voice again.": "La cola de envío fiable de Gemini no se vació. Vuelve a iniciar la voz.",
|
||||
"Gemini token request failed (HTTP {status})": "Falló la solicitud de credencial de Gemini (HTTP {status})",
|
||||
"Gemini token response did not include a valid model": "La respuesta de Gemini no incluyó un modelo válido",
|
||||
"Gemini token response did not include session settings": "La respuesta de Gemini no incluyó la configuración de la sesión",
|
||||
"Gemini session settings do not match the input mode": "La configuración de la sesión de Gemini no coincide con el modo de entrada",
|
||||
"Gemini could not submit this input. Start voice again.": "Gemini no pudo enviar esta entrada. Vuelve a iniciar la voz.",
|
||||
"Connecting to Gemini": "Conectando con Gemini",
|
||||
"Gemini returned an oversized message": "Gemini devolvió un mensaje demasiado grande",
|
||||
"Gemini Live connection failed. Check network access, then start voice again.": "Falló la conexión con Gemini Live. Comprueba el acceso a la red y vuelve a iniciar la voz.",
|
||||
"Gemini Live connection ended. Start voice again for a new conversation.": "La conexión con Gemini Live terminó. Vuelve a iniciar la voz para una nueva conversación.",
|
||||
"Gemini Live could not start. Start voice again to request a fresh session.": "Gemini Live no pudo iniciarse. Vuelve a iniciar la voz para solicitar una nueva sesión.",
|
||||
"Start voice again for a fresh token and a new conversation.": "Vuelve a iniciar la voz para obtener una credencial nueva y comenzar otra conversación.",
|
||||
"Start voice again to request a fresh session credential.": "Vuelve a iniciar la voz para solicitar una nueva credencial de sesión.",
|
||||
"Microphone permission was denied. Allow microphone access and try again.": "Se denegó el permiso del micrófono. Permite el acceso al micrófono e inténtalo de nuevo.",
|
||||
"Gemini connection timed out. Try again.": "Se agotó el tiempo de conexión con Gemini. Inténtalo de nuevo.",
|
||||
"Gemini voice could not start": "No se pudo iniciar la voz de Gemini",
|
||||
"Gemini did not finish the interrupted reply. Start voice again.": "Gemini no terminó la respuesta interrumpida. Vuelve a iniciar la voz.",
|
||||
"Gemini session expiring; finishing the current reply": "La sesión de Gemini va a caducar; terminando la respuesta actual",
|
||||
"Gemini rejected the voice session. Start voice again to request a fresh session.": "Gemini rechazó la sesión de voz. Vuelve a iniciar la voz para solicitar una nueva sesión.",
|
||||
"Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.": "Vuelve a iniciar la voz para obtener una nueva credencial de sesión. Si se repite, comprueba el modelo de Gemini y el acceso a la API.",
|
||||
"Gemini action history is full. Start voice again for a fresh session.": "El historial de acciones de Gemini está lleno. Vuelve a iniciar la voz para una nueva sesión.",
|
||||
"Gemini requested too many simultaneous actions": "Gemini solicitó demasiadas acciones simultáneas",
|
||||
"Voice text command is too long": "El comando de voz escrito es demasiado largo",
|
||||
"Gemini voice is not connected": "La voz de Gemini no está conectada",
|
||||
"Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "La entrada interrumpida de Gemini superó el límite de búfer o de espera. Vuelve a iniciar la voz.",
|
||||
"Gemini Live connection is expiring. Start voice again for a new conversation.": "La conexión con Gemini Live va a caducar. Vuelve a iniciar la voz para una nueva conversación.",
|
||||
"Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Las sesiones de voz de Gemini tienen un límite de tiempo. Cuando caduque la sesión, vuelve a iniciar la voz para una nueva conversación.",
|
||||
"Gemini Live voice control": "Control por voz con Gemini Live",
|
||||
"Voice provider": "Proveedor de voz",
|
||||
"Changing provider reconnects voice if it is on.": "Cambiar de proveedor vuelve a conectar la voz si está activada.",
|
||||
"Gemini voice could not connect. Try again.": "No se pudo conectar la voz de Gemini. Inténtalo de nuevo.",
|
||||
"Gemini voice requires a same-origin app request": "La voz de Gemini requiere una solicitud del mismo origen que la aplicación",
|
||||
"Add a Gemini API key in Provider Settings": "Añade una clave de API de Gemini en los ajustes de proveedores",
|
||||
"The Gemini Live model configuration is invalid": "La configuración del modelo de Gemini Live no es válida",
|
||||
"Gemini voice is starting too often. Try again shortly.": "La voz de Gemini se está iniciando con demasiada frecuencia. Vuelve a intentarlo en breve.",
|
||||
"Gemini quota is unavailable. Try again later.": "La cuota de Gemini no está disponible. Inténtalo más tarde.",
|
||||
"Gemini access was refused. Check the API key and model access.": "Se denegó el acceso a Gemini. Comprueba la clave de API y el acceso al modelo.",
|
||||
"Gemini Live is unavailable for the configured model.": "Gemini Live no está disponible para el modelo configurado.",
|
||||
"Token request is too large": "La solicitud de credencial es demasiado grande",
|
||||
"Use an empty JSON token request": "Usa una solicitud de credencial con un objeto JSON vacío"
|
||||
}
|
||||
+53
-50
@@ -74,7 +74,8 @@
|
||||
"Removed from {store}. Restarting — this page reloads itself.": "Удалено: {store}. Перезапуск — страница перезагрузится сама.",
|
||||
"More flight-polling credits (anonymous works without)": "Повышенный лимит запросов рейсов (анонимно работает и без ключа)",
|
||||
"Street-level imagery and coverage in the Street Level layer. Free: register an app in the Mapillary developer dashboard and paste its Client Token": "Уличные снимки и покрытие в слое «Уличные снимки». Бесплатно: зарегистрируйте приложение в панели разработчика Mapillary и вставьте его клиентский токен (Client Token).",
|
||||
"Higher space-missions request allowance": "Повышенный лимит запросов для космических миссий",
|
||||
"Public space-missions access needs no key. Leave blank for standard use; paid tokens only raise request limits.": "Общедоступные данные космических миссий не требуют ключа. Для обычного использования оставьте поле пустым; платные токены только повышают лимиты запросов.",
|
||||
"Optional paid token — public access works without one": "Необязательный платный токен — публичный доступ работает без него",
|
||||
"Places context + Street View fallback; optional separate key": "Контекст Places + резерв: Просмотр улиц; отдельный ключ — по желанию",
|
||||
"Voice control — API key or ChatGPT OAuth": "Голосовое управление — ключ API или ChatGPT OAuth",
|
||||
"Live ships, worldwide": "Суда в реальном времени по всему миру",
|
||||
@@ -2957,53 +2958,55 @@
|
||||
"SDR decoder did not start; receiver stopped": "Декодер SDR не запустился; приёмник остановлен",
|
||||
"SDR decoder stopped responding; receiver stopped": "Декодер SDR перестал отвечать; приёмник остановлен",
|
||||
"SDR decoder fell behind; receiver stopped": "Декодер SDR не успевает; приёмник остановлен",
|
||||
"Held from the phone": "Пауза с телефона",
|
||||
"Held: you moved the globe — press RESUME or tap HOLD on the phone": "Пауза: вы сдвинули глобус — нажмите ПРОДОЛЖИТЬ или ПАУЗА на телефоне",
|
||||
"Held": "Пауза",
|
||||
"Held: another view took the camera": "Пауза: камеру занял другой вид",
|
||||
"Starting…": "Запуск…",
|
||||
"Phone camera off": "Камера телефона выключена",
|
||||
"Scan the code with a phone on the same Wi-Fi": "Отсканируйте код телефоном в той же сети Wi-Fi",
|
||||
"AR tracking (6DoF)": "AR-трекинг (6DoF)",
|
||||
"Gyro tracking (3DoF)": "Гироскоп (3DoF)",
|
||||
"Recording {time} · {mode}": "Запись {time} · {mode}",
|
||||
"Phone connected · {mode} · {count} takes": {
|
||||
"one": "Телефон подключён · {mode} · {count} дубль",
|
||||
"few": "Телефон подключён · {mode} · {count} дубля",
|
||||
"many": "Телефон подключён · {mode} · {count} дублей",
|
||||
"other": "Телефон подключён · {mode} · {count} дубля"
|
||||
},
|
||||
"Phone connected · {mode}": "Телефон подключён · {mode}",
|
||||
"HOLD": "ПАУЗА",
|
||||
"■ STOP": "■ СТОП",
|
||||
"● REC": "● ЗАПИСЬ",
|
||||
"The phone camera service is unavailable": "Служба камеры телефона недоступна",
|
||||
"The phone camera port is in use (set VCAM_PORT)": "Порт камеры телефона занят (задайте VCAM_PORT)",
|
||||
"No network connection for a phone to reach": "Нет сетевого подключения, доступного телефону",
|
||||
"Phone camera session ended": "Сеанс камеры телефона завершён",
|
||||
"Nothing to focus on there": "Здесь не на чем сфокусироваться",
|
||||
"Take reached its length limit and was saved": "Дубль достиг предельной длины и сохранён",
|
||||
"Take saved to the scene": "Дубль сохранён в сцену",
|
||||
"Take too short to keep": "Дубль слишком короткий",
|
||||
"Recorded: {scene} / {shot}": "Записано: {scene} / {shot}",
|
||||
"Use a phone on this network as a virtual camera": "Использовать телефон в этой сети как виртуальную камеру",
|
||||
"Phone virtual camera": "Виртуальная камера телефона",
|
||||
"Pairing QR code": "QR-код для подключения",
|
||||
"SCAN WITH YOUR PHONE": "ОТСКАНИРУЙТЕ ТЕЛЕФОНОМ",
|
||||
"Network address": "Сетевой адрес",
|
||||
"SCALE": "МАСШТАБ",
|
||||
"1:1 WALK": "1:1 ПЕШКОМ",
|
||||
"1:10 CRANE": "1:10 КРАН",
|
||||
"1:100 DRONE": "1:100 ДРОН",
|
||||
"1:1000 FLYOVER": "1:1000 ПРОЛЁТ",
|
||||
"1:10000 ORBIT": "1:10000 ОРБИТА",
|
||||
"LENS": "ОБЪЕКТИВ",
|
||||
"DEPTH OF FIELD": "ГЛУБИНА РЕЗКОСТИ",
|
||||
"APERTURE": "ДИАФРАГМА",
|
||||
"RECENTER": "ЦЕНТРИРОВАТЬ",
|
||||
"END": "ЗАВЕРШИТЬ",
|
||||
"Takes become shots in the selected scene.": "Дубли становятся кадрами выбранной сцены.",
|
||||
"Phone certificate": "Сертификат для телефона",
|
||||
"VCAM": "VCAM",
|
||||
"Exit cockpit to use the phone camera": "Выйдите из кабины, чтобы использовать камеру телефона"
|
||||
"Gemini returned an oversized audio chunk": "Gemini вернул слишком большой фрагмент аудио",
|
||||
"Gemini returned an unsupported audio format": "Gemini вернул неподдерживаемый формат аудио",
|
||||
"Gemini returned an invalid audio sample rate": "Gemini вернул недопустимую частоту дискретизации аудио",
|
||||
"Gemini returned incomplete PCM audio": "Gemini вернул неполные аудиоданные PCM",
|
||||
"This browser does not support Gemini microphone audio": "Этот браузер не поддерживает звук с микрофона для Gemini",
|
||||
"Microphone audio processing failed": "Не удалось обработать звук с микрофона",
|
||||
"Gemini audio playback fell behind. Reconnect to continue.": "Воспроизведение звука Gemini отстаёт. Подключитесь заново, чтобы продолжить.",
|
||||
"Gemini token response did not include an ephemeral credential": "В ответе Gemini нет временных учётных данных",
|
||||
"Invalid Gemini connection endpoint": "Недопустимый адрес подключения к Gemini",
|
||||
"Voice command context is too large": "Контекст голосовой команды слишком велик",
|
||||
"Gemini reliable transport exceeded its queue limit. Start voice again.": "Очередь надёжной передачи Gemini превысила лимит. Запустите голосовой режим заново.",
|
||||
"Gemini reliable transport did not drain. Start voice again.": "Очередь надёжной передачи Gemini не освободилась. Запустите голосовой режим заново.",
|
||||
"Gemini token request failed (HTTP {status})": "Не удалось запросить токен Gemini (HTTP {status})",
|
||||
"Gemini token response did not include a valid model": "В ответе Gemini нет допустимой модели",
|
||||
"Gemini token response did not include session settings": "В ответе Gemini нет настроек сеанса",
|
||||
"Gemini session settings do not match the input mode": "Настройки сеанса Gemini не соответствуют режиму ввода",
|
||||
"Gemini could not submit this input. Start voice again.": "Gemini не удалось отправить эти данные. Запустите голосовой режим заново.",
|
||||
"Connecting to Gemini": "Подключение к Gemini",
|
||||
"Gemini returned an oversized message": "Gemini вернул слишком большое сообщение",
|
||||
"Gemini Live connection failed. Check network access, then start voice again.": "Не удалось подключиться к Gemini Live. Проверьте доступ к сети и запустите голосовой режим заново.",
|
||||
"Gemini Live connection ended. Start voice again for a new conversation.": "Соединение с Gemini Live завершено. Запустите голосовой режим заново для нового разговора.",
|
||||
"Gemini Live could not start. Start voice again to request a fresh session.": "Не удалось запустить Gemini Live. Запустите голосовой режим заново, чтобы запросить новый сеанс.",
|
||||
"Start voice again for a fresh token and a new conversation.": "Запустите голосовой режим заново, чтобы получить новый токен и начать новый разговор.",
|
||||
"Start voice again to request a fresh session credential.": "Запустите голосовой режим заново, чтобы запросить новые учётные данные сеанса.",
|
||||
"Microphone permission was denied. Allow microphone access and try again.": "Доступ к микрофону запрещён. Разрешите доступ и повторите попытку.",
|
||||
"Gemini connection timed out. Try again.": "Время ожидания подключения к Gemini истекло. Повторите попытку.",
|
||||
"Gemini voice could not start": "Не удалось запустить голосовой режим Gemini",
|
||||
"Gemini did not finish the interrupted reply. Start voice again.": "Gemini не завершил прерванный ответ. Запустите голосовой режим заново.",
|
||||
"Gemini session expiring; finishing the current reply": "Сеанс Gemini истекает; завершается текущий ответ",
|
||||
"Gemini rejected the voice session. Start voice again to request a fresh session.": "Gemini отклонил голосовой сеанс. Запустите голосовой режим заново, чтобы запросить новый сеанс.",
|
||||
"Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.": "Запустите голосовой режим заново для получения новых учётных данных. Если ошибка повторится, проверьте модель Gemini и доступ к API.",
|
||||
"Gemini action history is full. Start voice again for a fresh session.": "История действий Gemini заполнена. Запустите голосовой режим заново для нового сеанса.",
|
||||
"Gemini requested too many simultaneous actions": "Gemini запросил слишком много одновременных действий",
|
||||
"Voice text command is too long": "Текст голосовой команды слишком длинный",
|
||||
"Gemini voice is not connected": "Голосовой режим Gemini не подключён",
|
||||
"Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "Прерванный ввод Gemini превысил лимит буфера или ожидания. Запустите голосовой режим заново.",
|
||||
"Gemini Live connection is expiring. Start voice again for a new conversation.": "Соединение с Gemini Live истекает. Запустите голосовой режим заново для нового разговора.",
|
||||
"Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Время голосовых сеансов Gemini ограничено. Когда сеанс истечёт, запустите голосовой режим заново для нового разговора.",
|
||||
"Gemini Live voice control": "Голосовое управление через Gemini Live",
|
||||
"Voice provider": "Поставщик голосового сервиса",
|
||||
"Changing provider reconnects voice if it is on.": "Смена поставщика переподключает голосовой режим, если он включён.",
|
||||
"Gemini voice could not connect. Try again.": "Не удалось подключить голосовой режим Gemini. Повторите попытку.",
|
||||
"Gemini voice requires a same-origin app request": "Голосовой режим Gemini требует запрос из того же источника, что и приложение",
|
||||
"Add a Gemini API key in Provider Settings": "Добавьте ключ API Gemini в настройках поставщиков",
|
||||
"The Gemini Live model configuration is invalid": "Недопустимая конфигурация модели Gemini Live",
|
||||
"Gemini voice is starting too often. Try again shortly.": "Голосовой режим Gemini запускается слишком часто. Повторите попытку чуть позже.",
|
||||
"Gemini quota is unavailable. Try again later.": "Квота Gemini недоступна. Повторите попытку позже.",
|
||||
"Gemini access was refused. Check the API key and model access.": "Доступ к Gemini запрещён. Проверьте ключ API и доступ к модели.",
|
||||
"Gemini Live is unavailable for the configured model.": "Gemini Live недоступен для выбранной модели.",
|
||||
"Token request is too large": "Запрос токена слишком велик",
|
||||
"Use an empty JSON token request": "Используйте запрос токена с пустым объектом JSON"
|
||||
}
|
||||
@@ -89,7 +89,6 @@
|
||||
"Techno",
|
||||
"Trance",
|
||||
"USB {rate} msg/s",
|
||||
"VCAM",
|
||||
"VISUAL",
|
||||
"VS",
|
||||
"WHOT/BHOT",
|
||||
@@ -132,7 +131,6 @@
|
||||
"NVG",
|
||||
"R&B",
|
||||
"REC",
|
||||
"VCAM",
|
||||
"VS",
|
||||
"WHOT/BHOT"
|
||||
]
|
||||
|
||||
+4
-2
@@ -215,7 +215,7 @@ export function stripKeylessBasemapFromHash(hash) {
|
||||
}
|
||||
}
|
||||
|
||||
const TIER_DOTS = Object.freeze({ metered: '🔴', free: '🟡' });
|
||||
const TIER_DOTS = Object.freeze({ metered: '🔴', paid: '🔴', free: '🟡' });
|
||||
|
||||
function updateCloudVoiceAuthControl(auth, busy = false) {
|
||||
const mode = readStoredCloudVoiceAuthMode();
|
||||
@@ -259,7 +259,9 @@ function buildRow(documentRef, key) {
|
||||
tier.title =
|
||||
key.tier === 'metered'
|
||||
? t('Metered — a billing-enabled account')
|
||||
: t('Free key — register, paste, done');
|
||||
: key.tier === 'paid'
|
||||
? t('Optional paid token — public access works without one')
|
||||
: t('Free key — register, paste, done');
|
||||
head.append(led, title, tier);
|
||||
if (key.clientExposed) {
|
||||
const exposed = documentRef.createElement('span');
|
||||
|
||||
+16
-5
@@ -19,7 +19,7 @@ import { hasProxySignals } from './localRequestGate.mjs';
|
||||
/** Longest accepted key/token value. Real provider keys are all far shorter. */
|
||||
export const KEY_SETUP_VALUE_LIMIT = 512;
|
||||
|
||||
/** Most env vars accepted in one save. The registry defines ten. */
|
||||
/** Most env vars accepted in one save. */
|
||||
export const KEY_SETUP_UPDATE_LIMIT = 16;
|
||||
|
||||
/** Header line written above keys the panel appends to a .env file. */
|
||||
@@ -29,7 +29,8 @@ export const KEY_SETUP_APPEND_HEADER =
|
||||
/**
|
||||
* Provider credentials, in display order — most magic per
|
||||
* minute first. `tier` mirrors the README's color legend: 'metered' (🔴) is a
|
||||
* billing-enabled account, 'free' (🟡) is a register-and-paste key.
|
||||
* billing-enabled account, 'free' (🟡) is a register-and-paste key, and
|
||||
* 'paid' (🔴) is an optional paid higher-rate token.
|
||||
* `clientExposed` marks the keys that are injected into the browser
|
||||
* bundle by design (restrict them at the provider, per SECURITY.md).
|
||||
* `hidden` keeps advanced configuration out of the panel and missing-key count.
|
||||
@@ -64,6 +65,14 @@ export const KEY_SETUP_KEYS = Object.freeze([
|
||||
envVars: Object.freeze(['OPENAI_API_KEY']),
|
||||
tier: 'metered',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'gemini',
|
||||
title: 'GEMINI', // i18n-ignore: provider product name
|
||||
unlocks: msg('Gemini Live voice control'),
|
||||
getUrl: 'https://aistudio.google.com/apikey',
|
||||
envVars: Object.freeze(['GEMINI_API_KEY']),
|
||||
tier: 'metered',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'aisstream',
|
||||
title: 'AISSTREAM', // i18n-ignore: provider product name
|
||||
@@ -119,10 +128,12 @@ export const KEY_SETUP_KEYS = Object.freeze([
|
||||
Object.freeze({
|
||||
id: 'launch-library',
|
||||
title: 'LAUNCH LIBRARY', // i18n-ignore: provider product name
|
||||
unlocks: msg('Higher space-missions request allowance'),
|
||||
getUrl: 'https://thespacedevs.com',
|
||||
unlocks: msg(
|
||||
'Public space-missions access needs no key. Leave blank for standard use; paid tokens only raise request limits.',
|
||||
),
|
||||
getUrl: 'https://thespacedevs.com/supportus',
|
||||
envVars: Object.freeze(['LL2_API_TOKEN']),
|
||||
tier: 'free',
|
||||
tier: 'paid',
|
||||
}),
|
||||
]);
|
||||
|
||||
|
||||
+44
-10
@@ -3,6 +3,7 @@ import {
|
||||
FRAME_SIGNATURE_H,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
PROJECTION_MATTE_COLOR,
|
||||
PROJECTION_TEXTURE_SWAP_MS,
|
||||
ACTIVE_FRAME_REFRESH_MS,
|
||||
FRAME_ENDPOINT,
|
||||
@@ -12,6 +13,37 @@ import {
|
||||
PLACEHOLDER_REPAINT_MS,
|
||||
} from './policy.js';
|
||||
|
||||
/**
|
||||
* Contain-fits a source frame into the projection canvas: scaled to the
|
||||
* largest size that fits, centered, with the margins left for the matte fill.
|
||||
* Falls back to the full canvas when either dimension is missing or zero.
|
||||
*
|
||||
* @param {number} sourceW - Source width in pixels.
|
||||
* @param {number} sourceH - Source height in pixels.
|
||||
* @returns {{x:number,y:number,w:number,h:number}} Draw rectangle in canvas pixels.
|
||||
*/
|
||||
export function fitToProjection(sourceW, sourceH) {
|
||||
if (!sourceW || !sourceH)
|
||||
return {
|
||||
x: 0,
|
||||
y: 0,
|
||||
w: PROJECTION_CANVAS_WIDTH,
|
||||
h: PROJECTION_CANVAS_HEIGHT,
|
||||
};
|
||||
const scale = Math.min(
|
||||
PROJECTION_CANVAS_WIDTH / sourceW,
|
||||
PROJECTION_CANVAS_HEIGHT / sourceH,
|
||||
);
|
||||
const w = Math.round(sourceW * scale);
|
||||
const h = Math.round(sourceH * scale);
|
||||
return {
|
||||
x: Math.round((PROJECTION_CANVAS_WIDTH - w) / 2),
|
||||
y: Math.round((PROJECTION_CANVAS_HEIGHT - h) / 2),
|
||||
w,
|
||||
h,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFrames({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw
|
||||
@@ -182,7 +214,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
const g = ctx.createLinearGradient(0, 0, w, h);
|
||||
g.addColorStop(0, '#05111a');
|
||||
g.addColorStop(1, '#01070c');
|
||||
g.addColorStop(1, PROJECTION_MATTE_COLOR);
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
|
||||
@@ -320,7 +352,14 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
// base color (planeMaterial color = WHITE, alpha .95) for the frame or
|
||||
// two Cesium needs to rebind, which IS the periodic white flash from the
|
||||
// owner field tests (2026-07-04 and 2026-07-30).
|
||||
const signature = projectionFrameSignature(runtime);
|
||||
const fit = fitToProjection(
|
||||
runtime.image.naturalWidth,
|
||||
runtime.image.naturalHeight,
|
||||
);
|
||||
// Pixels are hashed at a fixed size, so the fit carries the aspect.
|
||||
const pixels = projectionFrameSignature(runtime);
|
||||
const signature =
|
||||
pixels === null ? null : `${pixels}:${fit.w}x${fit.h}`;
|
||||
runtime.drawnImageStamp = runtime.imageStamp;
|
||||
if (signature !== null && signature === runtime.lastFrameSignature) {
|
||||
// Identical pixels — leave the canvas, and therefore the bound
|
||||
@@ -328,19 +367,14 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
return;
|
||||
}
|
||||
runtime.lastFrameSignature = signature;
|
||||
runtime.ctx.clearRect(
|
||||
0,
|
||||
0,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
);
|
||||
runtime.ctx.drawImage(
|
||||
runtime.image,
|
||||
runtime.ctx.fillStyle = PROJECTION_MATTE_COLOR;
|
||||
runtime.ctx.fillRect(
|
||||
0,
|
||||
0,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
);
|
||||
runtime.ctx.drawImage(runtime.image, fit.x, fit.y, fit.w, fit.h);
|
||||
runtime.canvasStamp = (runtime.canvasStamp || 0) + 1;
|
||||
runtime.lastPlaceholderPaintAt = 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// src/layers/cctv/frames.test.mjs
|
||||
// Still-frame fit (#1201): stills draw at their source aspect, centered on the
|
||||
// 1920x1080 projection canvas, instead of being stretched to fill it.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFrames, fitToProjection } from './frames.js';
|
||||
import {
|
||||
FRAME_SIGNATURE_W,
|
||||
FRAME_SIGNATURE_H,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
PROJECTION_MATTE_COLOR,
|
||||
} from './policy.js';
|
||||
|
||||
// The expected rectangles below are written for a 1920x1080 canvas.
|
||||
assert.equal(PROJECTION_CANVAS_WIDTH, 1920);
|
||||
assert.equal(PROJECTION_CANVAS_HEIGHT, 1080);
|
||||
|
||||
const FULL_CANVAS = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
w: PROJECTION_CANVAS_WIDTH,
|
||||
h: PROJECTION_CANVAS_HEIGHT,
|
||||
};
|
||||
|
||||
test('a 4:3 still is pillarboxed at full height', () => {
|
||||
assert.deepEqual(fitToProjection(640, 480), {
|
||||
x: 240,
|
||||
y: 0,
|
||||
w: 1440,
|
||||
h: 1080,
|
||||
});
|
||||
});
|
||||
|
||||
test('a source wider than 16:9 is letterboxed at full width', () => {
|
||||
assert.deepEqual(fitToProjection(3840, 1080), {
|
||||
x: 0,
|
||||
y: 270,
|
||||
w: 1920,
|
||||
h: 540,
|
||||
});
|
||||
});
|
||||
|
||||
test('a 16:9 still fills the canvas', () => {
|
||||
assert.deepEqual(fitToProjection(1920, 1080), FULL_CANVAS);
|
||||
});
|
||||
|
||||
test('a missing or zero dimension falls back to the full canvas', () => {
|
||||
assert.deepEqual(fitToProjection(0, 480), FULL_CANVAS);
|
||||
assert.deepEqual(fitToProjection(640, 0), FULL_CANVAS);
|
||||
assert.deepEqual(fitToProjection(640, undefined), FULL_CANVAS);
|
||||
assert.deepEqual(fitToProjection(undefined, undefined), FULL_CANVAS);
|
||||
});
|
||||
|
||||
// Draw path: the fit reaches drawImage, and the unchanged-frame skip keys on the
|
||||
// fitted size as well as the pixels (the 64x36 hash alone drops aspect).
|
||||
function stillHarness() {
|
||||
const calls = [];
|
||||
const ctx = {
|
||||
fillStyle: null,
|
||||
fillRect: (...rect) => calls.push(['fillRect', ctx.fillStyle, ...rect]),
|
||||
clearRect: () => {},
|
||||
drawImage: (_image, ...rect) => calls.push(['drawImage', ...rect]),
|
||||
};
|
||||
// Every frame downsamples to the same pixels, so only the size differs.
|
||||
const pixels = new Uint8ClampedArray(
|
||||
FRAME_SIGNATURE_W * FRAME_SIGNATURE_H * 4,
|
||||
).fill(7);
|
||||
const runtime = {
|
||||
mode: 'image',
|
||||
ctx,
|
||||
image: { naturalWidth: 0, naturalHeight: 0 },
|
||||
imageReady: true,
|
||||
// In flight, so refreshProjectionImage returns before touching image.src.
|
||||
imageLoading: true,
|
||||
imageStamp: 0,
|
||||
drawnImageStamp: -1,
|
||||
lastFrameSignature: null,
|
||||
canvasStamp: 0,
|
||||
signatureCtx: {
|
||||
clearRect: () => {},
|
||||
drawImage: () => {},
|
||||
getImageData: () => ({ data: pixels }),
|
||||
},
|
||||
};
|
||||
const record = { camera: { id: 'still' }, projection: runtime };
|
||||
const { drawProjectionFrame } = createFrames({
|
||||
state: { _healthById: new Map(), _activeCameraId: null },
|
||||
services: {},
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
const load = (width, height) => {
|
||||
runtime.image = { naturalWidth: width, naturalHeight: height };
|
||||
runtime.imageStamp += 1;
|
||||
calls.length = 0;
|
||||
drawProjectionFrame(record);
|
||||
return calls.slice();
|
||||
};
|
||||
return { runtime, load };
|
||||
}
|
||||
|
||||
test('a still is drawn into its fitted rectangle over a full matte', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
assert.deepEqual(load(640, 480), [
|
||||
[
|
||||
'fillRect',
|
||||
PROJECTION_MATTE_COLOR,
|
||||
0,
|
||||
0,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
],
|
||||
['drawImage', 240, 0, 1440, 1080],
|
||||
]);
|
||||
assert.equal(runtime.canvasStamp, 1);
|
||||
});
|
||||
|
||||
test('same pixels at the same size skip the redraw', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
load(640, 480);
|
||||
assert.deepEqual(load(640, 480), []);
|
||||
assert.equal(runtime.canvasStamp, 1);
|
||||
});
|
||||
|
||||
test('same pixels at a new aspect redraw at the new fit', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
load(640, 480);
|
||||
assert.deepEqual(load(1920, 1080), [
|
||||
[
|
||||
'fillRect',
|
||||
PROJECTION_MATTE_COLOR,
|
||||
0,
|
||||
0,
|
||||
PROJECTION_CANVAS_WIDTH,
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
],
|
||||
['drawImage', 0, 0, 1920, 1080],
|
||||
]);
|
||||
assert.equal(runtime.canvasStamp, 2);
|
||||
});
|
||||
|
||||
test('same pixels at a new resolution with the same fit skip the redraw', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
load(640, 480);
|
||||
assert.deepEqual(load(1280, 960), []);
|
||||
assert.equal(runtime.canvasStamp, 1);
|
||||
assert.equal(runtime.drawnImageStamp, 2);
|
||||
});
|
||||
|
||||
test('changed pixels redraw even when the fitted rectangle is unchanged', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
load(640, 480);
|
||||
const changedPixels = new Uint8ClampedArray(
|
||||
FRAME_SIGNATURE_W * FRAME_SIGNATURE_H * 4,
|
||||
).fill(90);
|
||||
runtime.signatureCtx.getImageData = () => ({ data: changedPixels });
|
||||
const calls = load(640, 480);
|
||||
assert.equal(calls[0][0], 'fillRect');
|
||||
assert.deepEqual(calls[1], ['drawImage', 240, 0, 1440, 1080]);
|
||||
assert.equal(runtime.canvasStamp, 2);
|
||||
});
|
||||
|
||||
test('a failed pixel signature redraws rather than assuming equal content', () => {
|
||||
const { runtime, load } = stillHarness();
|
||||
load(640, 480);
|
||||
runtime.signatureCtx.getImageData = () => {
|
||||
throw new Error('tainted canvas');
|
||||
};
|
||||
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
|
||||
assert.equal(runtime.canvasStamp, 2);
|
||||
});
|
||||
@@ -35,6 +35,9 @@ export const PROJECTION_CANVAS_WIDTH = 1920;
|
||||
|
||||
export const PROJECTION_CANVAS_HEIGHT = 1080;
|
||||
|
||||
/** Matte behind fitted stills; the placeholder gradient's dark end. */
|
||||
export const PROJECTION_MATTE_COLOR = '#01070c';
|
||||
|
||||
// Downsample grid for the unchanged-frame signature (drawProjectionFrame).
|
||||
// 64x36 keeps the 16:9 aspect and reads ~9 KB per check versus the 8.3 MB a
|
||||
// full-resolution compare would touch.
|
||||
@@ -410,6 +413,9 @@ export const IDLE_CAMERA_COLOR =
|
||||
export const ACTIVE_CAMERA_COLOR =
|
||||
Cesium.Color.fromCssColorString('#ffd97a').withAlpha(0.95);
|
||||
|
||||
export const LIVE_CAMERA_COLOR =
|
||||
Cesium.Color.fromCssColorString('#b48cff').withAlpha(0.88);
|
||||
|
||||
export const IDLE_COVERAGE_COLOR =
|
||||
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.24);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { isHeadingEstimated } from './headingConfidence.js';
|
||||
import {
|
||||
ACTIVE_CAMERA_COLOR,
|
||||
IDLE_CAMERA_COLOR,
|
||||
LIVE_CAMERA_COLOR,
|
||||
ACTIVE_COVERAGE_CENTER,
|
||||
IDLE_COVERAGE_CENTER_MUTED,
|
||||
ACTIVE_COVERAGE_CENTER_DEPTHFAIL,
|
||||
@@ -18,6 +19,15 @@ export function createRendering({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
|
||||
function cameraColorFor(record) {
|
||||
if (record.camera.id === layerState._activeCameraId)
|
||||
return ACTIVE_CAMERA_COLOR;
|
||||
if (parts.model.isVideoFeedType(record.camera.feedType))
|
||||
return LIVE_CAMERA_COLOR;
|
||||
return IDLE_CAMERA_COLOR;
|
||||
}
|
||||
|
||||
const {
|
||||
focusNowMs,
|
||||
getFocusTarget,
|
||||
@@ -58,10 +68,7 @@ export function createRendering({
|
||||
),
|
||||
cameraDistanceFor: (position) =>
|
||||
Cesium.Cartesian3.distance(camera.positionWC, position),
|
||||
baseColorFor: (record) =>
|
||||
record.camera.id === layerState._activeCameraId
|
||||
? ACTIVE_CAMERA_COLOR
|
||||
: IDLE_CAMERA_COLOR,
|
||||
baseColorFor: cameraColorFor,
|
||||
});
|
||||
layerState._activeFocusStyleCount = result.activeCount;
|
||||
}
|
||||
@@ -208,9 +215,7 @@ export function createRendering({
|
||||
for (const record of layerState._records) {
|
||||
const isActive = record.camera.id === activeId;
|
||||
if (record.billboard) {
|
||||
record.billboard.color = isActive
|
||||
? ACTIVE_CAMERA_COLOR
|
||||
: IDLE_CAMERA_COLOR;
|
||||
record.billboard.color = cameraColorFor(record);
|
||||
record.billboard.scale = isActive ? 1.25 : 1.0;
|
||||
// disableDepthTestDistance stays POSITIVE_INFINITY for every billboard
|
||||
// (set at creation) — see the field-test far-zoom submerge fix there.
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// src/layers/cctv/rendering.test.mjs
|
||||
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
|
||||
// from the same base color the coverage refresh assigns, so a video-feed camera
|
||||
// stays violet while it dims instead of falling back to the idle cyan.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRendering } from './rendering.js';
|
||||
import {
|
||||
ACTIVE_CAMERA_COLOR,
|
||||
IDLE_CAMERA_COLOR,
|
||||
LIVE_CAMERA_COLOR,
|
||||
} from './policy.js';
|
||||
import { isVideoFeedType } from '../../sources/cctvTypes.js';
|
||||
|
||||
const FOCUS_FACTOR = 0.5;
|
||||
|
||||
function assertFadedFrom(actual, base, label) {
|
||||
assert.ok(actual, `${label}: color written`);
|
||||
assert.deepEqual(
|
||||
[actual.red, actual.green, actual.blue],
|
||||
[base.red, base.green, base.blue],
|
||||
`${label}: hue`,
|
||||
);
|
||||
assert.equal(actual.alpha, base.alpha * FOCUS_FACTOR, `${label}: alpha`);
|
||||
}
|
||||
|
||||
test('focus de-emphasis fades each icon from its own color', () => {
|
||||
const record = (id, feedType) => ({
|
||||
camera: { id, feedType },
|
||||
// No position, so the pass skips screen projection; the focus stub below
|
||||
// decides the factor on its own.
|
||||
billboard: { show: true },
|
||||
});
|
||||
const idleVideo = record('idle-hls', 'hls');
|
||||
const idleStill = record('idle-image', 'image');
|
||||
const activeVideo = record('active-hls', 'hls');
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_viewer: { scene: {}, camera: {} },
|
||||
_records: [idleVideo, idleStill, activeVideo],
|
||||
_activeCameraId: activeVideo.camera.id,
|
||||
_activeFocusStyleCount: 0,
|
||||
_lastFocusStyleAt: -Infinity,
|
||||
};
|
||||
const focus = {
|
||||
focusNowMs: (nowMs) => nowMs,
|
||||
getFocusTarget: () => ({}),
|
||||
focusPassIsNeeded: () => true,
|
||||
advanceSpriteFocus: () => ({
|
||||
factor: FOCUS_FACTOR,
|
||||
active: true,
|
||||
transitioning: false,
|
||||
}),
|
||||
focusAlphaNeedsWrite: () => true,
|
||||
};
|
||||
const { refreshCctvFocusStyles } = createRendering({
|
||||
state,
|
||||
services: { focus },
|
||||
parts: { model: { isVideoFeedType } },
|
||||
source: {},
|
||||
});
|
||||
|
||||
refreshCctvFocusStyles(1000);
|
||||
|
||||
assertFadedFrom(idleVideo.billboard.color, LIVE_CAMERA_COLOR, 'idle video');
|
||||
assertFadedFrom(idleStill.billboard.color, IDLE_CAMERA_COLOR, 'idle still');
|
||||
assertFadedFrom(
|
||||
activeVideo.billboard.color,
|
||||
ACTIVE_CAMERA_COLOR,
|
||||
'active video',
|
||||
);
|
||||
assert.equal(state._activeFocusStyleCount, 3);
|
||||
});
|
||||
|
||||
test('focus release restores video hue and alpha after the style throttle', () => {
|
||||
let target = {};
|
||||
const records = ['mp4', 'webm'].map((feedType) => ({
|
||||
camera: { id: feedType, feedType },
|
||||
billboard: { show: true, color: LIVE_CAMERA_COLOR },
|
||||
}));
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_viewer: { scene: {}, camera: {} },
|
||||
_records: records,
|
||||
_activeCameraId: null,
|
||||
_activeFocusStyleCount: 0,
|
||||
_lastFocusStyleAt: -Infinity,
|
||||
};
|
||||
const focus = {
|
||||
focusNowMs: (nowMs) => nowMs,
|
||||
getFocusTarget: () => target,
|
||||
focusPassIsNeeded: (value, count) => !!value || count > 0,
|
||||
advanceSpriteFocus: () => ({
|
||||
factor: target ? FOCUS_FACTOR : 1,
|
||||
active: !!target,
|
||||
transitioning: false,
|
||||
}),
|
||||
focusAlphaNeedsWrite: (before, after) => before !== after,
|
||||
};
|
||||
const { refreshCctvFocusStyles } = createRendering({
|
||||
state,
|
||||
services: { focus },
|
||||
parts: { model: { isVideoFeedType } },
|
||||
source: {},
|
||||
});
|
||||
|
||||
refreshCctvFocusStyles(1000);
|
||||
for (const record of records) {
|
||||
assertFadedFrom(
|
||||
record.billboard.color,
|
||||
LIVE_CAMERA_COLOR,
|
||||
record.camera.id,
|
||||
);
|
||||
}
|
||||
const dimmed = records.map((record) => record.billboard.color);
|
||||
target = null;
|
||||
refreshCctvFocusStyles(1050);
|
||||
for (let i = 0; i < records.length; i += 1) {
|
||||
assert.equal(records[i].billboard.color, dimmed[i]);
|
||||
}
|
||||
refreshCctvFocusStyles(1100);
|
||||
for (const record of records) {
|
||||
assert.deepEqual(record.billboard.color, LIVE_CAMERA_COLOR);
|
||||
}
|
||||
assert.equal(state._activeFocusStyleCount, 0);
|
||||
});
|
||||
Vendored
+1
@@ -57,6 +57,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
orbitMatches: layerState._orbitMatches,
|
||||
lastUpdate: layerState._lastUpdate,
|
||||
error: layerState._lastError,
|
||||
stale: layerState._stale,
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -168,9 +168,16 @@ export function createIngestion({
|
||||
async function performMissionUpdate(token) {
|
||||
try {
|
||||
ensureActiveTleLookup(token);
|
||||
const payload = await source.getLaunches({
|
||||
signal: layerState._sourceController.signal,
|
||||
});
|
||||
const { payload, stale } = source.getLaunchSnapshot
|
||||
? await source.getLaunchSnapshot({
|
||||
signal: layerState._sourceController.signal,
|
||||
})
|
||||
: {
|
||||
payload: await source.getLaunches({
|
||||
signal: layerState._sourceController.signal,
|
||||
}),
|
||||
stale: false,
|
||||
};
|
||||
const launches = parts.model.normalizeRocketLaunches(payload);
|
||||
if (
|
||||
!layerState._enabled ||
|
||||
@@ -214,6 +221,7 @@ export function createIngestion({
|
||||
parts.panel.renderMissionPanel();
|
||||
layerState._lastUpdate = Date.now();
|
||||
layerState._lastError = null;
|
||||
layerState._stale = stale === true;
|
||||
} catch (error) {
|
||||
if (layerState._enabled && token === layerState._lifecycleToken) {
|
||||
layerState._lastError = error.message;
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createLaunchSource } from './source.js';
|
||||
import { createState } from './state.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
async function fixture({ legacySource = false } = {}) {
|
||||
const launch = {
|
||||
id: 'owned-launch',
|
||||
name: 'Owned mission fixture',
|
||||
net: new Date(Date.now() - 3600000).toISOString(),
|
||||
status: { name: 'Launch Successful' },
|
||||
pad: { name: 'Owned pad', latitude: 28.6, longitude: -80.6 },
|
||||
rocket: { payloads: [] },
|
||||
};
|
||||
const mode = { cache: 'HIT', results: [launch], hold: false };
|
||||
let arrival;
|
||||
let release;
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.url === '/api/celestrak/active') {
|
||||
res.end('');
|
||||
return;
|
||||
}
|
||||
assert.equal(req.url, '/api/launches');
|
||||
const send = () => {
|
||||
if (res.destroyed) return;
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'X-GEV-Cache': mode.cache,
|
||||
});
|
||||
res.end(JSON.stringify({ results: mode.results }));
|
||||
};
|
||||
if (mode.hold) {
|
||||
release = send;
|
||||
arrival?.();
|
||||
} else send();
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const launchSource = createLaunchSource({
|
||||
fetchImpl: (url, options) => {
|
||||
assert.ok(['/api/launches', '/api/celestrak/active'].includes(url));
|
||||
return fetch(new URL(url, origin), options);
|
||||
},
|
||||
});
|
||||
const source = legacySource
|
||||
? {
|
||||
getLaunches: launchSource.getLaunches,
|
||||
getActiveTle: launchSource.getActiveTle,
|
||||
}
|
||||
: launchSource;
|
||||
const services = {
|
||||
overlays: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
|
||||
};
|
||||
const state = createState({ services });
|
||||
state._enabled = true;
|
||||
state._lifecycleToken = 1;
|
||||
state._dataSource = new Cesium.CustomDataSource('owned-qualification');
|
||||
const canvas = Object.assign(new EventTarget(), {
|
||||
disableRootEvents: true,
|
||||
onwheel: null,
|
||||
style: {},
|
||||
});
|
||||
const viewer = {
|
||||
dataSources: new Cesium.DataSourceCollection(),
|
||||
scene: { canvas, preRender: new Cesium.Event(), drillPick: () => [] },
|
||||
};
|
||||
await viewer.dataSources.add(state._dataSource);
|
||||
// Only presentation boundaries are inert. Source, normalization, state,
|
||||
// ingestion, lifecycle, stats and feed-state policy execute unchanged.
|
||||
const parts = {
|
||||
panel: {
|
||||
createMissionPanel: noop,
|
||||
renderMissionRoster: noop,
|
||||
renderMissionPanel: noop,
|
||||
clearMissionRosterHover: noop,
|
||||
},
|
||||
replay: { stopMissionReplay: noop },
|
||||
selection: {
|
||||
setSelectedMission: noop,
|
||||
focusMission: noop,
|
||||
stopMissionZoomAnchor: noop,
|
||||
},
|
||||
orbitRendering: {
|
||||
removeMissionOrbitPrimitives: noop,
|
||||
syncMissionOrbitPrimitiveVisibility: noop,
|
||||
},
|
||||
overlays: {
|
||||
createReplayVehicleOverlay: noop,
|
||||
clearMissionOverlaySources: noop,
|
||||
hideReplayVehicleOverlay: noop,
|
||||
destroyReplayVehicleOverlay: noop,
|
||||
},
|
||||
launchPad: {
|
||||
initLaunchPadZonePrimitive: noop,
|
||||
hideLaunchPadZone: noop,
|
||||
destroyLaunchPadZonePrimitive: noop,
|
||||
},
|
||||
rendering: {
|
||||
updateMissionFrame: noop,
|
||||
addLaunchEntity(record) {
|
||||
state._dataSource.entities.add({
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
position: Cesium.Cartesian3.fromDegrees(record.lon, record.lat),
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
const context = { state, services, parts, source };
|
||||
parts.model = createModel(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.controls = createControls(context);
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
const current = () => {
|
||||
const stats = parts.controls.methods.getStats();
|
||||
return {
|
||||
stats,
|
||||
feed: layerFeedState(stats),
|
||||
rendered: state._dataSource?.entities.values.map((x) => x.id) || [],
|
||||
enabled: state._enabled,
|
||||
};
|
||||
};
|
||||
return {
|
||||
mode,
|
||||
state,
|
||||
source,
|
||||
current,
|
||||
viewer,
|
||||
init: () => parts.lifecycle.methods.init(viewer),
|
||||
update: () => parts.ingestion.methods.update(),
|
||||
disable: () => parts.lifecycle.methods.disable(),
|
||||
destroy: () => parts.lifecycle.methods.destroy(viewer),
|
||||
holdArrival: () =>
|
||||
new Promise((resolve) => {
|
||||
arrival = resolve;
|
||||
}),
|
||||
release: () => release?.(),
|
||||
async close() {
|
||||
await parts.lifecycle.methods.destroy(viewer);
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('fresh launches remain nominal through ingestion and the layer stats', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.update();
|
||||
const value = f.current();
|
||||
assert.equal(value.feed, 'nominal');
|
||||
assert.equal(value.stats.count, 1);
|
||||
assert.deepEqual(value.rendered, ['owned-launch']);
|
||||
assert.equal(value.stats.error, null);
|
||||
assert.ok(value.stats.lastUpdate);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('STALE-ERROR provenance reaches the layer feed state without dropping records', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
assert.equal((await f.source.getLaunchSnapshot()).stale, true);
|
||||
await f.update();
|
||||
const value = f.current();
|
||||
assert.equal(value.stats.count, 1);
|
||||
assert.deepEqual(value.rendered, ['owned-launch']);
|
||||
assert.equal(value.feed, 'stale');
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('a fresh recovery clears stale launch provenance', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
await f.update();
|
||||
const stale = f.current();
|
||||
f.mode.cache = 'MISS';
|
||||
await f.update();
|
||||
const recovered = f.current();
|
||||
assert.equal(recovered.feed, 'nominal');
|
||||
assert.equal(recovered.stats.count, 1);
|
||||
assert.equal(recovered.stats.error, null);
|
||||
assert.equal(stale.feed, 'stale');
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('an empty stale snapshot still identifies its fallback provenance', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
f.mode.results = [];
|
||||
await f.update();
|
||||
assert.equal(f.current().stats.count, 0);
|
||||
assert.equal(f.current().feed, 'stale');
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('getLaunches-only injected sources remain supported', async () => {
|
||||
const f = await fixture({ legacySource: true });
|
||||
try {
|
||||
await f.update();
|
||||
assert.equal(f.current().feed, 'nominal');
|
||||
assert.deepEqual(f.current().rendered, ['owned-launch']);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('disable cancels a pending stale response without committing it', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.update();
|
||||
const healthy = f.current();
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
f.mode.hold = true;
|
||||
const arrived = f.holdArrival();
|
||||
const pending = f.update();
|
||||
await arrived;
|
||||
await f.disable();
|
||||
f.release();
|
||||
await pending;
|
||||
const value = f.current();
|
||||
assert.equal(value.enabled, false);
|
||||
assert.equal(value.stats.lastUpdate, healthy.stats.lastUpdate);
|
||||
assert.equal(value.feed, 'nominal');
|
||||
assert.equal(f.state._sourceController.signal.aborted, true);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('hiding retained stale records does not relabel them as fresh', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
await f.update();
|
||||
await f.disable();
|
||||
assert.equal(f.current().feed, 'stale');
|
||||
assert.equal(f.current().stats.count, 1);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('destroy clears the previous feed state and records', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
await f.update();
|
||||
await f.destroy();
|
||||
const value = f.current();
|
||||
assert.equal(value.stats.count, 0);
|
||||
assert.equal(value.stats.lastUpdate, null);
|
||||
assert.equal(value.feed, 'nominal');
|
||||
assert.equal(value.enabled, false);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('destroy followed by actual init starts a clean instance with owned handlers', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
f.mode.cache = 'STALE-ERROR';
|
||||
await f.update();
|
||||
await f.destroy();
|
||||
await f.init();
|
||||
const value = f.current();
|
||||
assert.equal(value.feed, 'nominal');
|
||||
assert.equal(value.stats.count, 0);
|
||||
assert.equal(value.stats.lastUpdate, null);
|
||||
assert.equal(value.stats.error, null);
|
||||
assert.equal(value.enabled, false);
|
||||
assert.equal(f.viewer.dataSources.length, 1);
|
||||
assert.equal(f.viewer.scene.preRender.numberOfListeners, 1);
|
||||
const click = f.state._clickHandler;
|
||||
const move = f.state._moveHandler;
|
||||
assert.ok(click instanceof Cesium.ScreenSpaceEventHandler);
|
||||
assert.ok(move instanceof Cesium.ScreenSpaceEventHandler);
|
||||
assert.equal(
|
||||
typeof click.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK),
|
||||
'function',
|
||||
);
|
||||
await f.destroy();
|
||||
assert.equal(click.isDestroyed(), true);
|
||||
assert.equal(move.isDestroyed(), true);
|
||||
assert.equal(f.viewer.dataSources.length, 0);
|
||||
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user