Merge branch 'main' into feat/blender-camera-interchange-submit

This commit is contained in:
German Khokhlov authored and GitHub committed 2026-11-20 16:53:45 +04:00
commit 5b1c1ede29
374 files changed
+30189 -1769

No files matched your search

+10
View File
@@ -37,6 +37,8 @@ GOOGLE_MAPS_API_KEY=
GOOGLE_MAPS_SERVER_API_KEY=
# Per-IP rate limit for the Google Places cost endpoints
# (/api/google/nearby-places + /api/google/text-search), in requests per minute.
# The CCTV Street View fallback counts in its own window with the same cap;
# over it, a frame gets the placeholder image instead of a 429.
# DEFAULTS TO 120, the value the Pinokio build already ships. Raise or lower it
# with a positive integer; 60 is a sensible tightening whenever HOST is not
# localhost. Set it to exactly 0 to run unthrottled. An unreadable value (a
@@ -136,6 +138,14 @@ OPENSKY_CLIENT_SECRET=
# Optional paid Patreon tokens raise request limits; there is no free API key.
LL2_API_TOKEN=
# Optional: NASA's public ISS telemetry (the ISSLive feed, served by
# Lightstreamer). Off by default: the feed publishes no terms of use, so the
# server contacts it only when this is 1. It then holds one connection, open
# only while a browser has the ISS model on screen, and the model's solar
# arrays, radiators and Ku-band dish take their real angles from it. No key.
# See DATA_SOURCES.md.
# ISS_TELEMETRY_ENABLED=
# Optional: OpenSky credentials JSON file path, used when the two values above
# are empty: the credentials.json your OpenSky account page downloads when you
# create an API client. Use an absolute path for compatibility with launchers.
+22 -7
View File
@@ -1,13 +1,13 @@
# Data Sources & Attribution
God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources. The bundled 3D models are the project's own procedural fleet models, MIT-licensed with the code ([`public/models/README.md`](public/models/README.md)).
God's Eye View's **code** is [MIT](LICENSE)-licensed. **The MIT grant covers the source code only — it does NOT extend to third-party data or visual assets.** Every third-party source keeps its own license and terms. This file documents the live and bundled data sources. The bundled 3D models are the project's own procedural fleet models, MIT-licensed with the code, except NASA's ISS model (`public/models/iss.glb`) ([`public/models/README.md`](public/models/README.md)).
How to read this:
- **The non-permissive datasets are carved out, not omitted.** Some bundled data (e.g. TeleGeography, CC BY-NC-SA) isn't MIT-compatible. Rather than hide it, we **bundle it with a clear license carve-out** so the app works out of the box — but it stays under the provider's terms.
- **If your use doesn't fit a dataset's license, remove that dataset.** Most importantly: TeleGeography is **NonCommercial** — commercial users must delete it (or license it from TeleGeography). It's one self-contained folder.
- **Attribution is shown in-app** and listed here. Keep it intact. The required Google/Cesium credit renders on the on-globe credit line (bottom-left, `#cesium-credits`), and every per-layer credit below is registered into the expandable **"Data attribution"** lightbox on that line (`src/data/dataCredits.js` → `viewer.creditDisplay.addStaticCredit`). Both stay visible in clean-view and recording modes.
- **The bundled 3D models are the project's own.** Every model under `public/models/` is a procedural fleet model generated by the project maintainers and covered by the repository's MIT license; [`public/models/README.md`](public/models/README.md) describes the set.
- **The bundled 3D models are the project's own, but one.** Every model under `public/models/` except `iss.glb` is a procedural model generated by the project maintainers (the fleet, and Tiangong from `scripts/build-tiangong-model.py`) and covered by the repository's MIT license; `iss.glb` is NASA's public-domain model of the ISS (see NASA 3D Resources below); [`public/models/README.md`](public/models/README.md) describes the set.
---
@@ -34,6 +34,10 @@ How to read this:
| **Open Vessel Photos** (`openvesselphotos.org/v1/mmsi/{mmsi}`) | One photo of the selected vessel, by MMSI, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI | Free, keyless public API ([README](https://github.com/louptheron/openvesselphotos)); each photo keeps the open licence its author chose (CC BY, CC BY-SA, CC0, or public domain), given with it in the API | "Photo: {photographer} · {licence}" beside every photo, linked to the vessel's Open Vessel Photos page; "Open Vessel Photos" in Data attribution |
| **AISStream.io** | Live vessels (AIS) | Free, beta, no formal ToS; AIS is a public broadcast | "AISStream.io" (courtesy) |
| **CelesTrak** | Satellite TLEs (SGP4) and SATCAT records (object type, operational status, owner) that file each satellite under a class | US-government-origin data, no license; citation requested | "CelesTrak (celestrak.org), Dr. T.S. Kelso" |
| **NASA 3D Resources** (`public/models/iss.glb`) | The ISS drawn as a 3D model when the camera is near it (satellites layer): NASA/JSC IGOAL's "International Space Station (ISS) (D)" (https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/), reduced and re-rigged as `public/models/README.md` records. Its moving parts are computed by the app unless the telemetry relay in the next row is switched on: arrays and radiators from the Sun's position, the Ku-band dishes toward the TDRS fleet's nominal slots (41°W, 171°W, 85°E), the robotic arms as an illustrative sway | NASA media, not subject to copyright in the United States; NASA's Images and Media Usage Guidelines (https://www.nasa.gov/nasa-brand-center/images-and-media) ask that use not imply endorsement and that the insignia not be used; the model's textures carry the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks as flown on the station, kept to show it as it is, implying no endorsement by NASA or any partner | "ISS model: NASA 3D Resources" |
| **Project model** (`public/models/tiangong.glb`) | Tiangong drawn as a 3D model when the camera is near it (satellites layer): an original model of the station's T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward and nadir, a Tianzhou aft) made for God's Eye View from primitives with procedurally generated textures; dimensions from Wang, Zhang & Wang 2023, "Design and Application Prospect of China's Tiangong Space Station", Space: Science & Technology (https://doi.org/10.34133/space.0035, CC BY 4.0) and eoPortal's Tiangong page, the approximate parts listed in `public/models/README.md`. Its moving parts are computed by the app: the wings from the Sun's position, the high-gain antenna toward the Tianlian II nominal slots (79.9°E, 171.04°E, 10.5°E), the two arms as an illustrative sway; China publishes no live telemetry for the station | MIT, with the rest of the project's own work (`LICENSE`): an original asset with no third-party geometry, textures or images; the published dimensions are facts taken from a CC BY 4.0 paper and eoPortal | "Tiangong model: made for God's Eye View; dimensions from Wang, Zhang & Wang 2023 (CC BY 4.0) and eoPortal" |
| **NASA ISSLive telemetry** (`push.lightstreamer.com`, adapter set `ISSLIVE`) | **Off by default.** With `ISS_TELEMETRY_ENABLED=1` the server holds one connection to NASA's public ISS telemetry stream, open only while a browser has the ISS model on screen, and relays the latest joint angles at `/api/iss-telemetry`: the two alpha joints, the eight array beta joints, the two radiator joints and the Ku-band dish (Canadarm2's joints are relayed but not used yet). While the station has signal the ISS model takes those angles in place of the computed ones. The app stores nothing from it | The public subset of ISS telemetry NASA released as the ISSLive project, served for NASA by Lightstreamer. No terms of use are published for the feed, so it is opt-in and no request is made by default | "ISS joint telemetry: NASA ISSLive, via Lightstreamer" |
| **NASA ISS live streams on YouTube** (`youtube-nocookie.com/embed/ROboUHfPUrU`, `.../M3HKLzjvKPc`) | NASA's official live video from the ISS, two broadcasts ("Live High-Definition Views from the International Space Station" from the exterior cameras, and the live video with space-to-ground audio), offered in a LIVE section of Context, and on the Cockpit briefing's LIVE page, while the ISS is selected on the map, and played, muted, in YouTube's own embedded player only after the viewer presses Play; collapsing the section, closing Context or leaving the Cockpit page removes the player; the app stores nothing from it (`src/data/liveStreams.js`) | NASA video, not subject to copyright in the United States, distributed through YouTube under YouTube's Terms of Service, which permit embedding with the public embeddable player; the player API script loads from `www.youtube.com` and the video from the privacy-enhanced host `www.youtube-nocookie.com`, and the viewer's IP address reaches YouTube only once they press Play, under a line that says so | "NASA video, via YouTube", with a link to the stream's own page |
| **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) |
| **Esri World Imagery** (ArcGIS Online tile service) | The keyless satellite basemap — the default landing when no Google/ion credential is configured, and the "Esri Satellite" map stack | [Esri Master Agreement](https://www.esri.com/en-us/legal/terms/full-master-agreement): the public World Imagery service is usable in public-facing apps with attribution; no key is required for this classic endpoint, but Esri governs and can change access — an app at scale should review current ArcGIS Location Platform terms | "Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community" (provider carries the service's own credit line) |
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
@@ -68,7 +72,7 @@ How to read this:
| **Caltrans (cwwp2.dot.ca.gov)** | CCTV camera catalogs + frames, California districts | Public Caltrans traffic camera data | "Caltrans — cwwp2.dot.ca.gov" (courtesy) |
| **DelDOT (video.deldot.gov)** | CCTV camera catalog (`tmc.deldot.gov/json/videocamera.json`, cached for 15 minutes) + live HTTPS HLS video, Delaware. Keyless | Public DelDOT traffic camera streams via the [DelDOT traffic map](https://deldot.gov/map/) | "DelDOT — Delaware Department of Transportation" (courtesy) |
| **TfL Open Data (JamCams)** | CCTV camera catalog + frames, London | [TfL Open Data terms](https://tfl.gov.uk/info-for/open-data-users/) — attribution REQUIRED | "Powered by TfL Open Data. Contains OS data © Crown copyright and database rights" |
| **Ontario 511** | CCTV camera catalog + frames, Ontario highways including Kitchener-area routes | [Open Government Licence – Ontario](https://www.ontario.ca/page/open-government-licence-ontario) | "Ontario 511" plus Open Government Licence - Ontario |
| **Ontario 511** | CCTV camera catalog + frames, Ontario highways including Kitchener-area routes | [Open Government Licence – Ontario](https://www.ontario.ca/page/open-government-licence-ontario) | "Ontario 511. Contains information licensed under the Open Government Licence – Ontario" |
| **Fintraffic / Digitraffic (weathercams)** | CCTV camera catalog + frames, Finland | [CC BY 4.0](https://www.digitraffic.fi/en/terms-of-service/) — attribution REQUIRED | "Fintraffic / digitraffic.fi, license CC BY 4.0" |
| **DriveBC** (Government of British Columbia) | CCTV camera catalog + frames, British Columbia highways | [Open Government Licence – British Columbia](https://www2.gov.bc.ca/gov/content/data/open-data/open-government-licence-bc) — attribution REQUIRED | "DriveBC. Contains information licensed under the Open Government Licence – British Columbia" |
| **Open Calgary** (`data.calgary.ca`) | CCTV camera catalog + frames, Calgary | [Open Government Licence – City of Calgary](https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – City of Calgary" |
@@ -247,7 +251,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Open Vessel Photos.** When you select a vessel with a nine-digit MMSI, the browser asks `https://openvesselphotos.org/v1/mmsi/{mmsi}` directly (the API is keyless and answers cross-origin, so no key and no server proxy are involved; account credentials are never sent) for that vessel only, once per MMSI per session, with an 8-second timeout. A miss (a 404 or a vessel without photos) is remembered for the session; a failed request may be asked again after five minutes. The first photo whose image is an `https://openvesselphotos.org` URL and which names a licence is shown, at the 800 px size, in the CONTEXT panel's CONTACTS view under the vessel's name and MMSI (`src/ui/views/panels/AwarenessPanel.vue`), and nowhere else (`src/data/openVesselPhoto.js`, `src/layers/vessels/photos.js`). The image is hotlinked from the URL the API gives (never copied or re-hosted); the photographer and licence are visible text next to it ("Photo: {photographer} · {licence}", or "Photo · {licence}" when the answer names no one), and the photo and credit link to the vessel's Open Vessel Photos page with `target="_blank" rel="noopener"`. If the image fails to load, the photo and its credit are hidden.
- **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 `511on.ca/api/v2/get/cameras` endpoint, which now requires a free developer key (`ONTARIO_511_API_KEY`: sign up at 511on.ca/my511/register, then request it while logged in at 511on.ca/developers/doc; throttled to 10 calls a minute). Without the key the pack is skipped. Frames are server-registered still images under `511on.ca/map/Cctv/`. The source is live-fetched at runtime and attributed under the Open Government Licence - Ontario. Access is governed by Ontario 511's Developer's Access Agreement (511on.ca/developers/resources): the data stays under the Open Government Licence - Ontario unless otherwise specified; key requests are reviewed case by case and ask for the intended use and any third parties that will receive the data; attribution by link to 511on.ca is encouraged, and the Ontario 511 logo may not be altered or used to imply endorsement (this app links and shows no logo); and the data is provided "as is", a disclaimer distributors should pass on, which the credit does.
- **Ontario 511 CCTV.** The camera list comes from the `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.
@@ -411,7 +415,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
| Dataset | Folder | License | Commercial use? | Attribution |
| --------------------------------------------------------------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------- |
| **Datacenters** (4,352) | `datacenters/` | **ODbL 1.0** (OpenStreetMap extract) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) |
| **Dams** (704) | `dams/` | **ODbL 1.0** (OpenInfraMap / OSM extract) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Open Infrastructure Map |
| **Dams** (706) | `dams/` | **ODbL 1.0** (OpenInfraMap / OSM extract + OSM API) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Open Infrastructure Map |
| **Military area names** (36,466) | `osm_military_names/` | **ODbL 1.0** (OpenStreetMap, via Overture Maps) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + Overture Maps Foundation |
| **Ukraine outline** (Rail layer no-positions rule; 1 ring, 7,801 points) | `src/data/railNoPositions.js` | **ODbL 1.0** (OpenStreetMap, via geoBoundaries gbOpen UKR ADM0, commit 9469f09; simplified to 0.0005°) | ✅ (attribution + share-alike on data) | © OpenStreetMap contributors (shared credit) + geoBoundaries |
| **Québec CCTV source catalog** (1,120 locations) | `public/quebec-cameras.json` | Mixed: MTQ locations CC BY 4.0; Montréal camera nodes ODbL 1.0; scenic records retain per-record provenance. No video files are bundled or cached. | Location data is per-record; video remains hosted by Québec 511 and its platform terms apply; scenic source pages may have separate terms | MTQ / Données Québec CC BY 4.0; © OpenStreetMap contributors (ODbL); scenic operator and position source shown in the selected-camera panel |
@@ -432,7 +436,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
| **Yale Bright Star Catalogue** (9,096 stars, sky background) | `sky/` | **Public domain** | ✅ (no restrictions) | "Yale Bright Star Catalogue (Hoffleit & Warren, via CDS)" (courtesy credit) |
| **ESO Milky Way panorama** (eso0932a, blurred cube map, sky background) | `sky/` | **CC BY 4.0** | ✅ (attribution; changes stated) | "ESO/S. Brunier" |
| **CCTV ground heights** (3,445 cameras) | `cctv_ground_heights/` | Precomputed camera placement heights, aligned to work with Google Photorealistic 3D Tiles (folder README) | — | — |
| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 camera-model records) | `src/layers/cctv/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) |
| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 CCTV and 15 ALPR camera-model records) | `src/layers/cctv/modelSpecs.js`, `src/layers/alpr/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) |
### ⚠️ TeleGeography is bundled but NonCommercial
@@ -458,6 +462,17 @@ commercial use with attribution and applicable database share-alike/access
obligations; it does not license the application code. Trimmed test-only tile
fixtures retain their provenance in `src/data/fixtures/README.md`.
A mapped `model` tag that names datasheet hardware adds a spec line to the
selected card. The specs are 16 CC0-1.0 records from the CCTV Camera Database
model-enrichment extract (v2.29.0): 15 compiled into
`src/layers/alpr/modelSpecs.js`, with the bare product codes mappers tag added
as aliases and the SharpV G3 and SharpX XGA titles naming their variant, plus
the CCTV layer's Bosch MIC-7522-Z30 record. Nothing is fetched at runtime, and
an unrecognised tag is never displayed. The default hourly extract does not
carry `model` yet, so the line appears only with a source that supplies it: an
Overpass-backed source or a custom adapter whose records include the optional
`model` field.
### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`)
The CCTV layer's hardware-model specs are a small extract (v2.26.0, plus the Bosch MIC
@@ -474,7 +489,7 @@ credits it anyway as `SPECS: CCTV-DATABASE.COM` beside any spec line it renders.
### Bundled OpenStreetMap data
Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/), separately from the MIT code: [datacenters](src/data/local_data/datacenters/), [dams](src/data/local_data/dams/) (via Open Infrastructure Map), [military names](src/data/local_data/osm_military_names/), the Rail layer's Ukraine outline in [`railNoPositions.js`](src/data/railNoPositions.js) (OpenStreetMap via geoBoundaries gbOpen, Runfola et al. 2020, simplified; the module's code stays MIT), and [OSM test fixtures](src/data/fixtures/). Keep © OpenStreetMap contributors and offer modified databases under ODbL.
Bundled OSM-derived data is distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/), separately from the MIT code: [datacenters](src/data/local_data/datacenters/), [dams](src/data/local_data/dams/) (from Open Infrastructure Map and the OpenStreetMap API), [military names](src/data/local_data/osm_military_names/), the Rail layer's Ukraine outline in [`railNoPositions.js`](src/data/railNoPositions.js) (OpenStreetMap via geoBoundaries gbOpen, Runfola et al. 2020, simplified; the module's code stays MIT), and [OSM test fixtures](src/data/fixtures/). Keep © OpenStreetMap contributors and offer modified databases under ODbL.
### NASA FIRMS acknowledgement
+1 -1
View File
@@ -480,7 +480,7 @@ In the app, **Data Layers** groups them as Movement, Cameras, Infrastructure, Ev
| 🟡 A free Cesium ion token | **Google Photorealistic 3D cities** and world terrain — eligible personal, non-commercial use; current ion terms and quotas apply |
| 🔴 A Google Maps key | The same 3D direct from Google, plus Google place search — the billing-enabled, metered route |
**Also on the globe:** neighborhood overlays · an optional cockpit WX cloud effect. **Bundled static infrastructure:** Datacenters (4,352), Dams (704), and Submarine Cables (712).
**Also on the globe:** neighborhood overlays · an optional cockpit WX cloud effect. **Bundled static infrastructure:** Datacenters (4,352), Dams (706), and Submarine Cables (712).
**Missing a layer you want?** Open an issue — or add it and send the PR.
+4 -2
View File
@@ -68,10 +68,12 @@ browser-key fallback for existing single-key setups.
The data proxies under `server/providers/` are written so the browser cannot turn the server into an open relay:
- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). Other proxies target fixed upstream hosts.
- **No arbitrary-URL fetching.** The CCTV frame proxy fetches only server-registered camera/frame URLs — clients cannot pass an upstream URL to fetch (SSRF mitigation). The key-bearing Street View fallback likewise answers only for a registered camera, at its catalog position; a request sets only the heading, field of view and pitch, never the location. Other proxies target fixed upstream hosts.
- **Live HLS is bounded and origin-pinned.** Registered HTTP(S) HLS sources use a Node puller that rejects redirects and off-origin playlist references, bounds playlists to 256 KiB and segment bodies to 8 MiB while streaming, and aborts timed-out or released sessions. At most two sessions retain 12 segments/24 MiB each, plus bounded download buffers. Stores are memory-only and idle sessions expire after 15 seconds. RTMP/ffmpeg execution is not enabled. Locally configured source URLs remain an operator trust boundary.
- **Radio is not an audio relay.** `/api/radio/stations` contacts only allowlisted Radio Browser HTTPS hosts and paths, rejects redirects, rejects any hostname with a loopback/private/link-local/metadata/non-public A or AAAA result, and pins each TLS connection to a validated address. It returns normalized public HTTPS stream URLs; `/api/radio/click/:uuid` applies the same destination policy and accepts only station IDs from the current bounded catalog. The browser then connects directly to the broadcaster after an explicit playback action, so the broadcaster sees the listener's IP address. GEV never proxies, caches, records, or redistributes audio.
- **Québec 511 video plays in the browser, opt-in and after Play.** With `CCTV_QUEBEC_VIDEO_ENABLED=1`, `/api/cctv/sources` lists, for each MTQ camera, one URL built server-side from its numeric id on `https://www.quebec511.info/Carte/Fenetres/camera.ashx`; the overlay accepts no other host, path or format. The browser loads that clip only after the viewer presses Play for the selected camera, so Québec 511 sees the viewer's IP address, and the panel says so before Play. Selecting a camera by click, auto-hop, a scene or voice never loads it, and switching cameras stops playback. GEV never proxies, caches or reads the video's pixels. With the flag unset (the default) the browser makes no request to Québec 511.
- **Station live video plays only after Play.** The LIVE section of Context and the Cockpit briefing's LIVE page load YouTube's player (the IFrame API from `www.youtube.com`, the video on `www.youtube-nocookie.com`) only after the viewer presses Play, under a line saying that YouTube sees their IP address. Selecting a station by click, a share link that follows it, a scene or voice shows the poster and loads nothing. The player goes when the section is collapsed, Context is closed or collapsed, the Cockpit leaves its LIVE page, the Cockpit is entered or left, or the selection moves to an object without that stream. GEV never proxies, caches or reads the video's pixels.
- **The ISS telemetry relay is opt-in, keyless and read-only.** With `ISS_TELEMETRY_ENABLED=1`, `/api/iss-telemetry` answers from one shared WebSocket the server opens to NASA's public ISSLive feed (`wss://push.lightstreamer.com`), only while a browser has asked in the last two minutes; every byte from the feed is parsed as untrusted text, a frame over 64 KB closes the socket (retried on the backoff ladder), and only the listed joint and clock items are kept. The route uses the keyless same-site checks and a per-client rate limit; with the flag unset (the default) it answers `{ configured: false }` and the server opens no socket.
- **No verbatim client headers upstream.** The CCTV media route is the one route that relays a request header (`Range`, for video seeking). It is parsed and canonicalized before it is forwarded: one `bytes=` range only, with every accepted form — explicit span, open-ended and suffix — bounded to the same 64 MiB ceiling the relay applies to a declared response body. Multi-range, malformed, inverted and non-`bytes` values are dropped and the request proceeds without a `Range`, as RFC 7233 §3.1 prescribes. Bounding the request bounds what is asked for: a response that declares no length — live streamed media, or a chunked body from an upstream that ignores the `Range` — has no ceiling. An upstream request the browser has stopped waiting for is cancelled rather than left running, whether the viewer leaves before the headers arrive or during the body.
- **The Data Library proxy fetches manifest upstreams only.** `/api/library/data/<id>`, `/api/library/tile/<id>/<z>/<x>/<y>` and `/api/library/index/<id>` (a partitioned GeoParquet entry's file index, built from an S3 ListObjectsV2 listing and one ranged footer read per file, cached in memory for the entry's `cacheSeconds`) resolve the id against the validated manifests in `src/library/entries/`; the browser never supplies a URL, and every derived request must stay on the manifest's https host. Redirects are refused, dataset bodies are capped while streaming at the manifest's `maxBytes` (at most 32 MiB) and tiles at 2 MiB of `image/png`, `image/jpeg` or `image/webp`, responses are cached in memory only (at most 512 tiles), requests are rate-limited per client, and upstream error text is never returned. A keyed entry must be proxied; its key is read from this server's environment through the key registry and its routes refuse cross-site and forwarded requests like the other cost-bearing routes. Browser-direct entries are fetched by the browser with no cookies or referrer.
- **Transit fetches registered feeds only.** `/api/transit/vehicles/<id>` resolves the id against `src/data/transitFeeds.js`; the browser never supplies a URL, and a feed that is registered but disabled does not resolve at all. Redirects are followed manually and each hop is validated against the feed's own https origin before it is requested, so an off-origin or downgraded hop is refused rather than contacted. Bodies are capped at 8 MB, the protobuf is decoded server-side under entity-count and string-length ceilings, a differential feed is refused, and snapshots live 15 s in memory with no disk cache. A per-feed admission limiter and a failure cooldown ladder bound what this process can ask of any operator.
@@ -98,7 +100,7 @@ The dev server is a **key broker**: every server-side key above is spendable by
- **Local-only by default.** `./scripts/dev-fresh.sh` (and the Vite config itself) bind to `localhost`, so only your machine can reach the server — and only local names are accepted (`allowedHosts` stays restricted, which also blunts DNS-rebinding tricks). Binding to all interfaces keeps that restriction: IP addresses and `localhost` work, and LAN hostnames must be listed in `GEV_ALLOWED_HOSTS` (for example `GEV_ALLOWED_HOSTS=globe.lan`); suffix and wildcard entries are ignored.
- **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.
- **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`). Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. Both defaults sit well above what the app itself generates; set either to exactly `0` to run unthrottled. They are **per-IP, process-local, in-memory guards** — they reset on restart, a caller with several addresses gets a bucket per address, and they are **not billing caps**.
- **App-level throttles (on by default):** `GEV_RATELIMIT_OPENAI_PER_MIN` (default `30`) and `GEV_RATELIMIT_GOOGLE_PER_MIN` (default `120`) — the values the Pinokio build already ships — cap the cost-bearing endpoints per client IP per minute (over-limit requests receive a sanitized `429`). The CCTV Street View fallback has its own per-IP window on `GEV_RATELIMIT_GOOGLE_PER_MIN`, separate from the Places and Geocoding one; over it, a frame gets the placeholder instead of a `429`. Typed chat keeps its own per-IP window, set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`; left unset, each takes its provider's resolved cap (`GEV_RATELIMIT_OPENAI_PER_MIN`, or `GEV_RATELIMIT_GEMINI_PER_MIN`, default `30`), so lowering a provider throttle lowers chat too, while an explicit chat value, including `0`, wins. 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
network's gateway, never from `127.0.0.1`, so a loopback-only Provider
+6 -4
View File
@@ -55,7 +55,8 @@ function photonEndpointSetting(value) {
* Content-Security-Policy for every document the dev/preview server serves.
* No inline script is permitted, and the only foreign script origins are the
* three that the Bhote Koshi event's embedded media needs (YouTube, Facebook
* and X), which frame-src matches for their players and posts. 'unsafe-eval' is
* and X), which frame-src matches for their players and posts; the stations'
* LIVE video uses the same YouTube player, after the viewer presses Play. 'unsafe-eval' is
* required: Knockout (bundled inside @cesium/widgets) resolves the global
* object with `(0, eval)("this")` at module load, and without it the Cesium
* widget never initializes (verified in headless Chrome). It also covers
@@ -66,9 +67,10 @@ function photonEndpointSetting(value) {
*/
export const BROWSER_CSP = [
"default-src 'self'",
// The Bhote Koshi event's embedded media: the YouTube player API, the
// Facebook video SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js);
// and the Maps JavaScript API that Street Level's Google Street View runs on.
// The Bhote Koshi event's embedded media: the YouTube player API (also the
// stations' LIVE video, src/data/youtubeLivePlayer.js), the Facebook video
// SDK and X's post widget (src/data/bhoteKoshiEmbeddedMedia.js); and the
// Maps JavaScript API that Street Level's Google Street View runs on.
"script-src 'self' 'unsafe-eval' blob: https://www.youtube.com https://connect.facebook.net https://platform.twitter.com https://maps.googleapis.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' data: https://fonts.gstatic.com",
+3
View File
@@ -0,0 +1,3 @@
- Add the Acaray and Yacyretá dams from OpenStreetMap to the Dams layer, and
credit the layer to OpenStreetMap / OpenInfraMap instead of USACE (radianx,
#1152).
+13
View File
@@ -0,0 +1,13 @@
- Refuse Ontario 511 catalog redirects and keep the key-bearing request URL
and upstream error text out of failure logs, which now name only the error
class and system code; release the body of an error response. Credit
Ontario 511 with the Open Government Licence – Ontario attribution statement
(asturksever, #1266).
- Abort the other Tarktee (Estonia) DATEX request as soon as one fails, before
its headers or while its body is read, instead of waiting out the shared
30 s deadline; a response that arrives after the failure is released too.
The Lithuania pack reads its two catalogs through the same helper
(asturksever, #1266).
- Frame the calibration gizmo before the CCTV QA drag regression drags it;
default autofocus could leave the arrow shorter than the 10 px grab
threshold (asturksever, #1266).
+7
View File
@@ -0,0 +1,7 @@
- Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware
(Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show
a datasheet spec line on their card, from 16 vendored CCTV Camera Database
records, when their source supplies `model` (an Overpass-backed source or an
integration adapter; the default hourly extract does not yet); unknown,
generation-ambiguous or mis-attributed models show nothing
(bassem chagra, @ch-bas, #1360).
@@ -0,0 +1,9 @@
- Keep the phone Cockpit's Display and Radio launchers off the flight
instruments. In the phone layout (720 px wide and below), the collapsed row
of the flight and bridge views now sits centred on the Reset/Exit axis
above the reticle, clear of the destination cue, instead of right-anchored
over the ground speed and altitude readouts. On short landscape phones it
stays on screen and tappable below the vision controls, though it may cover
the top of the readouts. Very short or narrow split-screen windows keep
the old place above Reset/Exit. The first-visit Stories announcement waits until
Cockpit closes (Denis Groshev, @ZloyS, #1549).
@@ -0,0 +1,2 @@
- Stop the browser caching a refused Google Places or Geocoding answer, so a
fixed key works at once (Rudy Celekli, @rudycelekli, #1570).
@@ -0,0 +1,5 @@
- The CCTV Street View fallback answers only for cameras the server lists, at
their catalog position; a request sets only the view. Bundled seed cameras
get the placeholder. A per-IP limit on `GEV_RATELIMIT_GOOGLE_PER_MIN`
(default 120) keeps the Google key from serving as an unmetered Street View
service (asturksever, #1602).
@@ -0,0 +1,5 @@
- Keep the CCTV camera picked with NEAREST, FOCUS or by a scene when it is
the camera CCTV switched to after the view moved. The pick did not stick:
NEAREST's own flight, or the next pan, switched to another camera, so the
panel showed a camera nobody had picked. To keep the camera the list
already shows, press FOCUS (gekh, #1702).
+42
View File
@@ -0,0 +1,42 @@
- Draw the ISS as NASA's 3D model of the current station when the camera is
near it, its moving parts following computed rules: the solar arrays and
radiators by the Sun, the Ku-band dishes toward the relay satellites, the
robotic arms in an illustrative sway. The model draws through the renderer
contract, whose model items gain `nodes` for a model's moving joints
(Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Draw China's Tiangong station as a 3D model up close, the second station
after the ISS: an original model of the T configuration with a Shenzhou
forward and nadir and a Tianzhou aft, its wings following the Sun, its
antenna aimed at the Tianlian relay satellites and its two arms swaying for
illustration (computed values; China publishes no telemetry). The model
stands in for the dots of the entries docked to it (Denis Groshev, @ZloyS,
#1767).
- Add a STATION section to Context while a space station is selected on the
map: Automatic says where the moving parts' angles come from, Manual offers
Sun positions, array and radiator folding as a labelled demonstration, dish
aim and the arms joint by joint, and Zoom brings the camera to the station.
Selecting a module or a docked vehicle offers it as selecting the station
does (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Let the ISS model's solar arrays, radiators and Ku-band dish take their
real angles from NASA's public ISSLive telemetry. Off by default: set
`ISS_TELEMETRY_ENABLED=1` and the server relays the feed over one
connection, open only while the model is on screen; without signal the
joints keep their computed rules (Denis Groshev, @ZloyS; Kevin Rajan,
@kvnloo, #1767).
- Add a LIVE section to Context while the ISS is selected: NASA's two live
streams (exterior cameras; live video with space-to-ground audio), stepped
with arrows, in YouTube's embedded player. Nothing loads until you press
Play, under a line saying YouTube sees your IP address, and collapsing the
section stops it. In the Cockpit the same stream is the briefing's fourth
page, LIVE (Itallo Brandão, @IMBrandao; Denis Groshev, @ZloyS, #1767).
- Ride a space station in the Cockpit from views on its model instead of
the straight-down picture: Nauka, Zarya, Poisk, the Cupola, Kibo and a
docked vehicle on the ISS; Tianhe, Wentian, Mengtian and a docked vehicle
on Tiangong. Two arrows step through them, the readout describes the module
each view is from, and leaving selects the station (Denis Groshev, @ZloyS,
#1767).
- Let a click on a mapped installation's label box select the site, as a
click on its 7 px dot does: from orbit the label is what a click lands on.
The label takes a click only where nothing else is drawn under it, so an
aircraft or vessel under a base's label stays selectable (Denis Groshev,
@ZloyS, #1767).
@@ -1,4 +1,4 @@
- Clicking a shot row anywhere (its number, title or summary), or pressing
Enter or Space on its title, now goes to the shot, as LOAD did; the LOAD
button is gone. In its place, up and down arrows swap the shot with its
neighbour, saved with the project (Sameh Khamis, @samehkhamis, #XXXX).
neighbour, saved with the project (Sameh Khamis, @samehkhamis, #1803).
+8
View File
@@ -0,0 +1,8 @@
- Zoomed out, a CCTV ground cell with two or more cameras is now one round
marker with a camera icon and the count (`999`, `1.7K`, `12K` in every
language). It grows with the count, merges with markers it would overlap,
takes in a lone camera right beside it, and zooms in on click until the
group splits. Idle cameras and markers are green. The active camera stays
amber and video cameras violet. Cameras on one mount draw side by side, and
a camera the terrain height service never answered for stands on the drawn
terrain (gekh, #1808).
+1 -1
View File
@@ -3,4 +3,4 @@
posing, and the vessel hull sprites are part of the package's public entry
points as `gods-eye-view/fleet`, with declarations, so contacts can be drawn
exactly as the Flights and Vessels layers draw them (Sameh Khamis,
@samehkhamis, #XXXX).
@samehkhamis, #1820).
+3
View File
@@ -0,0 +1,3 @@
- The remaining selects, pressed toggles and close buttons in the views are
kit controls, and a test now keeps every view that way (manjunath22466,
samehkhamis, #1854).
@@ -0,0 +1,3 @@
- The command dock's and Context's buttons and glyphs are now kit controls,
and the style buttons say whether they are pressed (manjunath22466,
samehkhamis, #1855).
@@ -0,0 +1,3 @@
- The small views' buttons and glyphs (locale picker, phone tabs, globe
actions and compass, News and rail cards, credits, the Omnibar guide's
rings and others) are now kit controls (manjunath22466, samehkhamis, #1856).
@@ -0,0 +1,3 @@
- Wheel and trackpad zoom no longer freeze below 150 km while an aircraft or
vessel icon is under the centre of the view: icons drawn over depth write a
depth of exactly 0, which the camera's depth pick ignores (asturksever, #1857).
+2
View File
@@ -0,0 +1,2 @@
- The Cockpit HUD's buttons and glyphs are now kit controls, and its rim
pointers are hidden from screen readers (manjunath22466, samehkhamis, #1858).
@@ -0,0 +1,4 @@
- Opening the bare address starts with the default layers again, instead of
bringing back the last session's: a link still restores everything it
carries, so clearing the address always resets the view (samehkhamis,
#1861).
+2
View File
@@ -0,0 +1,2 @@
- The AI chat panel's and voice control's buttons and glyphs are now kit
controls (manjunath22466, samehkhamis, #1862).
+2
View File
@@ -0,0 +1,2 @@
- Draw's and Import's buttons and glyphs are now kit controls
(manjunath22466, samehkhamis, #1863).
@@ -0,0 +1,2 @@
- Space Missions', Contacts', Radio's, the RTL-SDR card's and key setup's
buttons and glyphs are now kit controls (manjunath22466, samehkhamis, #1864).
@@ -0,0 +1,3 @@
- The Bhote Koshi panel's buttons are kit controls, CINEMATIC's pressed
state is Vue state, and its media cards are a Vue view (manjunath22466,
samehkhamis, #1865).
+3
View File
@@ -0,0 +1,3 @@
- Tapping the search box or any other text field on an iPhone no longer leaves
the page zoomed in: the page stays at its own scale and the map does the
zooming (samehkhamis, #1866).
+4
View File
@@ -0,0 +1,4 @@
- An application can name the layers a bare address starts with
(`startLayers` on `createApplicationControls`; none by default): they turn on
without being saved as the user's own choice, and a link's own layers always
win (samehkhamis, #1867).
@@ -0,0 +1,3 @@
- Street Level's photo viewer is a Vue view with kit step buttons, and a
provider switch always gets a fresh panorama canvas (manjunath22466,
samehkhamis, #1868).
+3
View File
@@ -0,0 +1,3 @@
- The view scan now forbids any hand-written button, Material glyph,
checkbox or range in the views, and any control built in script
(manjunath22466, samehkhamis, #1869).
+4
View File
@@ -0,0 +1,4 @@
- A selected vessel or aircraft can be found again from its card: while it is
off screen or has left its feed (the clock moved, or the view moved away),
Find it flies back to it, looking it up where it was at the clock's time
when the feed no longer has it (samehkhamis, #1870).
@@ -0,0 +1,3 @@
- Street Level's photo viewer settles every open and mount, draws one
viewer at a time and states its view contract (manjunath22466,
samehkhamis, #1871).
+3
View File
@@ -0,0 +1,3 @@
- On a phone the search field is centred when no language picker sits beside
it, instead of keeping the picker's room empty on its right (samehkhamis,
#1872).
@@ -0,0 +1,4 @@
- Satellite clouds draw again in a built app instead of showing "Weather
imagery unavailable": the weather shell read its texture limit in a
parameter default, which esbuild compiles for older browsers into code that
throws. A test now refuses the form under `src/` (samehkhamis, #1873).
+3
View File
@@ -0,0 +1,3 @@
- Weather imagery and shells say what they show (`shows`, such as
`'clouds'`), so a renderer can tell such a layer apart; nothing draws
differently (samehkhamis, #1875).
@@ -0,0 +1,2 @@
- On desktop the search dock sits above the World Timeline, which takes the
dock's floor (Sameh Khamis, @samehkhamis, #1876).
@@ -0,0 +1,4 @@
- A plane that lands and is reported on the ground with no altitude stays on
the ground, instead of hanging at its approach height until it takes off
or its 3D model appears; its labels read "On the ground" (samehkhamis,
#1877).
+3
View File
@@ -31,6 +31,8 @@ const ctx = {
toEcef,
assets: {
model: '/models/fleet/aircraft/c172.glb',
// Its one node, which the `nodes` check moves.
modelNode: 'c172',
// Not served: the model failure check loads it.
missingModel: '/models/conformance-missing.glb',
},
@@ -47,6 +49,7 @@ const HARNESSES = {
cesium: () => [
createCesiumHarness({
model: ctx.assets.model,
modelNode: ctx.assets.modelNode,
missingModel: ctx.assets.missingModel,
}),
{ only: (id) => CESIUM_CHECKS.has(id) },
+363 -35
View File
@@ -10,6 +10,20 @@ or an older position from another feed) and one reported slower than 2 m/s
give no course and keep the last; an aircraft with no course at all faces
north.
A selected vessel, aircraft or military aircraft can be found again from its
Context card. While it is off screen, behind the globe or out of its layer's
feed (the clock jumped to a time the feed lacks it, or the view moved away
from it), the card's header shows Find it (`store.locate()`,
`src/ui/stores/entityCard.js`). One still in its feed is flown to (an
aircraft followed). One out of its feed is looked up at the layer's time on
its own track (`locate` on the vessels, flights and military layers, through
`locateOnTrack` in `src/data/locate.js`): the newest point at or before the
world clock's time while the layer follows the clock, else the newest. The card
moves to it and says how old that reading is, and the camera flies there. Once
the feed has it again, its layer selects it again (an aircraft is followed).
With no point at or before the time, the card says there is no reading then and
the camera stays. A followed item is never counted as off screen.
While anything moves (a layer in motion, the camera, a followed contact), the
globe draws at the display's own refresh rate; there is no fixed 60 FPS cap.
The render governor (`src/renderGovernor.js`) caps a parked scene at
@@ -93,6 +107,16 @@ settling. Oblique views below 300 km are left alone.
`QA_BASE_URL=http://localhost:4173 node scripts/qa-zoom-out-guard.mjs` exercises
the real browser controller at desktop and phone widths with keyless fixtures.
Below 150 km Cesium sizes a wheel or pinch zoom step from the depth it picks at
the canvas centre. Icons drawn over depth (aircraft, vessels and most markers:
`disableDepthTest: Infinity`) sit on the near plane and write a depth of
exactly 0 there (`src/render/cesium/iconSetPrimitive.js`), which that pick
reads as nothing drawn, so it keeps the ground under the icon. Any depth past
the near plane would be taken for a surface a near plane's distance from the
camera, and the zoom would stop while an icon is under the centre.
`QA_BASE_URL=http://localhost:5173 node scripts/qa-zoom-under-icon.mjs` checks
this against a dev server (`npm run dev`).
Cesium's free look (Shift+drag, which turns the camera in place) works only
below 1,000 km. Above that height a few drags could turn the whole planet out of
frame and leave only stars, so Shift+drag does nothing there. Cesium also turns
@@ -1191,9 +1215,11 @@ every width, right to left it takes the bottom right at every width, and
`src/ui/creditLineHeight.js` keeps its height in `--credit-line-height`: the
coordinates (and, right to left, the Tactical readout) stay 6px above it
however many lines it wraps onto, and the dock and World Timeline rise when
it is taller than their usual clearance. Narrower than 1120px the dock leaves
no room between the corners, so the coordinates and the readout sit above
the dock, and above the World Timeline while it shows. Outside that layout
it is taller than their usual clearance. The World Timeline takes the dock's
floor and the dock (with the Omnibar's field) sits above it, rising by the
bar's height while it shows, as the plain dock does. Narrower than 1120px the
dock leaves no room between the corners, so the coordinates and the readout
sit above the dock. Outside that layout
Cesium's credit box wraps from 1200px, as before; the phone shell, clean
view, recording and scene playback lay the line out themselves.
The left rail treats the centered World Timeline and voice control as
@@ -1933,6 +1959,16 @@ The row count explicitly says **nearby**: loaded records can be outside the
screen. Cyan camera badges use Manjunath's camera artwork; selection switches to a
larger coral badge with corner brackets and an animated tactical card. Numeric
mapped bearings draw illustrative 90 m direction wedges (not measured coverage).
A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant,
Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras
in October 2026) gets a `SPEC` line on its card from vendored datasheet records
(`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's
`createModelSpecLookup`). A `manufacturer` naming another maker rejects the
match, and the raw tag text is never shown.
Unversioned `AutoVu SharpV` and `AutoVu SharpX` tags show no specs; G1/G2
tags show the G2 (1280x960) record and G3 tags the G3 record. The default
hourly extract has no `model` field yet; an Overpass-backed source or a custom
adapter record's optional `model` fills it.
The shared overlay paints gradients for at most 64 nearby cameras, promoting the
selected camera; farther cameras keep native Cesium badges without wedges.
Native ground-clamped wedges (a ground polyline plus a classification polygon per
@@ -1993,16 +2029,54 @@ and follows redirects only on the camera's origin. Catalog image URLs, and
redirects on those hosts, are pinned by parsed URL to the agency's image
directory. Every `/api/cctv` route refuses cross-site browser requests but
accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded
request skips the key-bearing Street View fallback and gets the placeholder.
request skips the key-bearing Street View fallback and gets the placeholder. The
fallback answers only for cameras the server lists, at their catalog position,
so position calibration never reaches it. Heading, field of view (clamped to
20–120°) and pitch (clamped to −40–20°) come from the request, else from the
catalog pose. A bundled seed camera, shown when the server catalog is empty,
gets the placeholder. The fallback counts in its own per-IP Google window (see
the cost-bearing proxies below).
The CCTV layer draws only the cameras on or near the screen. Zoomed out, it
keeps one camera per ground cell sized to the view, preferring a healthy feed,
and the cells are anchored to the ground so a pan keeps the same cameras. The
active camera always shows. Ground placement and coverage geometry load only
for the cameras in view, with at most two attempts per camera and view regime.
The view pass reruns while the camera moves, paced by its own cost. The camera
picker lists the cameras in view, active camera first, and closes with the
count of cameras outside the view.
The CCTV layer draws only the cameras on or near the screen. Zoomed out, a
ground cell with two or more cameras shows one marker at their mean position. A
green camera pictogram sits under its top edge and the count just below its
middle. The marker grows with the count and paints on the world overlay at
callout resolution. The count covers the whole cell up to the horizon, including
its off-screen cameras. Overlapping markers merge and add their counts. A lone
camera whose icon would touch a marker joins the nearest one, unless the HUD
hides the merged marker. In that case the lone camera keeps its icon and the
count stays where it was before the merge. If the marker there would still cover
the icon, the camera stays in its count when the label fits. The active camera
keeps its own icon beside any marker that would cover it and stays out of the
count. A click on a marker zooms in on its group, at least halving the distance
each time. If halving would leave the group wider or taller than the frame, the
view zooms in on the nearest of the group's ground cells with two or more
cameras. The cockpit or a tracked object holds the view in place. Ambient cards
and coverage attach only to
cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A
camera the height batch never answered for takes the drawn terrain as its ground
once it is near the screen. It reads that height again from much closer, once
the terrain in view has loaded, or when the terrain source changes. A later
Re:Earth answer replaces it. A fallback preserves it. Close up every camera
shows. Cameras on one mount draw side by side and their records keep the mount.
Ground placement has at most two attempts per camera and view regime. The view
pass reruns while the camera moves, paced by its own cost, and when the terrain
in view finishes loading. The camera picker lists the active camera first, then
one camera per visible cell, preferring healthy feeds. It ends with the count of
catalog cameras missing from the list.
Turning CCTV on opens on the camera nearest the view. Until someone picks a
camera, each settled move, such as a shared view's flight landing, moves it to
the camera then nearest the view. Automatic selection ends at the first pick:
NEAREST, PREV or NEXT, FOCUS, a camera chosen in the picker, a click on a
camera, a click on empty ground that deselects, an auto-hop step, or a call to
`selectCamera`, `focusNearest`, `focusNearestToPoint` or
`setParams({ selectedCameraId })`, which voice and scenes use. Picking the
camera that is already active counts. The picker shows the automatic camera
as its own option, and a native list sends no change for the option it
already shows, so the list cannot pick that camera: FOCUS does, and so does
NEAREST when that camera is the nearest. Closing the list without a choice
keeps automatic selection.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them.
@@ -2041,6 +2115,213 @@ tracked satellite's dot a set of its own drawn where the follow camera framed
it, and the orbit rings a line set dimmed behind the globe and turned with the
Earth each second. A caller handing it a Cesium viewer, with no
renderer bound, loads the `./render/cesium/unbound` export once first.
The ISS (NORAD 25544, by number, not name) is drawn as NASA's 3D model within
1,500 km of the camera and as its dot beyond; the two split the distance range,
so exactly one draws (the tracked dot too). The model is at its real 109 m span
with a 72 px floor, flies the station's usual attitude (modules along the
velocity, the same side to the Earth) from its own per-frame SGP4 sample, sits
on the follow camera's sample while tracked, loads only once the ISS is shown,
and hides with the dot's own rules. A click on it tracks the ISS.
The station has several catalog entries that are one body: the ISS itself
(listed as ISS (ZARYA)), ISS (NAUKA) and whatever vehicle is docked, each with
a dot of its own, so a click on the station's dot can land on any of them.
`issTrackedOnStation` (`policy.js`) treats a tracked entry as the station when
it is the ISS or the ISS shares its position (`_dockedCompanions`). For such
an entry the model sits on the tracked entry's own per-frame sample, as it
does for the ISS (drawn from a later sample it stood a frame of orbital
motion, over 100 m, off the camera's centre); its tracked dot and orbit ring
leave the near range to the model, its card keeps clear of the model, and the
command panel and the live video show as they do for the ISS. Such an entry
draws no orbit ring of its own (its elements would put a second line beside
the ISS's through the same station): when tracking judges it docked (both
orbits at one instant within 5 km) the ISS's ring shows for it, even with the
Stations class hidden.
In the Cockpit, a station entry is ridden from the station itself instead of
the straight-down picture: the camera sits at a point on the model
(`issMounts.js`), with the model drawn, and looks out, away from the station.
There are six views, the same whichever entry was selected: from Nauka (the
one it opens on; its lower end, out ahead to port), from Zarya (its port
side, out across the track), from Poisk (its top, out behind to starboard),
from the Cupola (just below it, out aft past the Russian segment), from Kibo
(outside the two windows on its port end, out over the Exposed Facility;
the port solar arrays turn through it as they follow the Sun, as they do past
the real windows)
and, while a vehicle is docked, from that vehicle (behind Zvezda's aft port,
out behind the station; the catalog does not say which port a vehicle is
on). The Cupola and Kibo have no catalog entries: their views ride the ISS's
and show cards of their own (`ISS_MOUNT_CARDS`: the Cupola as ESA's
observation module with 7 windows, launched 8 Feb 2010 on STS-130, on
Tranquility's Earth-facing port; Kibo as JAXA's laboratory module with 2
windows, launched 31 May 2008 on STS-124, on Harmony's port side) in place of
the entry's NORAD number, owner and TLE; altitude, velocity and the
sub-satellite point stay the station's.
Each looks 20° to 30° below level, which keeps the Earth's limb in the frame.
The points were chosen by casting rays across the view against the model at
rest: over a meter clear of every surface, at most a tenth of the frame
meeting the station and none of it nearer than 12 m. The satellites layer's
`getCockpitMount(key)` gives the eye point, the view frame, the view shown,
the catalog entry it belongs to (ISS (NAUKA), the ISS itself for Zarya,
POISK, the docked vehicle) and the views on offer, worked out from the same
sample the model is then placed on, so the camera stays on the model. The
Cockpit rides the view's own entry (`switchOrbitalSatellite`, as riding
another satellite from Live Signals), so the readout, the TLE and the signals
describe the module the view is from; a view whose entry is missing or cannot
be tracked keeps the entry ridden, and is not retried until the view changes.
Leaving the Cockpit from a station view selects Nauka (when the catalog has
it) and puts the follow camera on it, whichever view it ended on; leaving
any other satellite's view refocuses that satellite as before. `cockpitOrbitalView.js` puts the
camera there, turns the arrow-key look about the view's own frame, keeps the
chosen view for the session (also while the model is away) and publishes its
name (`mount`) and the number on offer (`mountViews`). The HUD shows STATION
VIEW with the view's name between two arrows that step back and forth
through them, wrapping round,
and leaves out the nadir reticle, north pointer, swath and sensor strip. A
ground focus (a click on a mapped installation, or its Live Signals row)
works from a station view as from the nadir picture: it aims from the
view's camera point and turns about the view's own frame, with the same
±45° reach, so the sites listed and focusable are those within reach of
where the view looks; their rows still give the angle from straight down.
Switching views ends a focus.
Until the model has loaded, or with the model not shown, the entry keeps the
nadir picture, and the TRACK ACQUIRED line follows the change. Zoom, the
place line and the identity readouts are unchanged.
While the station is selected on the map, Context gains a LIVE section
(`src/ui/liveControls.js`, `LivePanel.vue`, the `gev-live` store): the live
streams attached to the selected object. The list is fixed
(`src/data/liveStreams.js`: NASA's exterior cameras, and its live video with
space-to-ground audio, both on YouTube) and each stream names the subject
keys it belongs to; a layer names its selected subject's keys with
`getLiveSubjectKeys` (the satellites layer answers `station:iss` for the ISS,
Nauka and a docked vehicle, and `station:tiangong` for Tiangong's entries,
which no stream is listed for yet), and the keys are read again every 2 s while
something is selected, since a docked entry is judged so only once both
orbits have been compared. The section shows the subject, the stream's name
with two arrows when there are several, a screen and a status line. It
starts collapsed, and nothing loads on selection: the screen is a poster
with Play, under the line "Video plays from YouTube, which sees your IP
address." Play is the one thing that loads the player:
`youtubeLivePlayer.js` builds YouTube's player (the IFrame API from
`www.youtube.com`, the video on `www.youtube-nocookie.com`), muted, and reads
its state back. Collapsing the section, collapsing or closing Context, or the
section leaving the page removes the player, so nothing plays unseen. ON AIR
with a blinking red dot while it plays; LOADING with an amber dot while it
starts; an offline card ("Stream is offline", with Try again) when
the player reports the video ended, errored or did not start within 25 s,
which is how an off-air broadcast shows, or when YouTube's player API does not
load (Try again loads it afresh); "This stream cannot play here" when the
owner refuses embedding. Stepping to another
stream hands a playing one over; a selection that moves to an object
without that stream, clearing it or turning the layer off removes the
player, while another entry of the same station (a module, a docked vehicle,
the Cockpit stepping between views) keeps it. In the Cockpit the rail is hidden, so the
briefing card gains a fourth page, LIVE (SIG / NEWS / LOCAL / LIVE,
`CockpitLivePage.vue`), with the same subject line, arrows, screen, states
and credit, and the same poster with Play under the IP line; it is offered
only while the ridden subject has a stream, and with none the briefing keeps
its three pages. There is one player: entering or leaving the Cockpit
removes it (an embedded player cannot change parents without reloading, and
the view it was in is hidden), and so does leaving the LIVE page; the view
now shown offers Play again. Previous, Next and the tabs reach the LIVE page;
the automatic 9-second cycle never turns to it and waits while it is shown.
The credit links the owner and the stream's own page.
The model is NASA/JSC IGOAL's current-configuration station, reduced to 3 MB
with its joints kept as nodes (`public/models/README.md`), fetched only once
the camera nears its range, and drawn as an item of a `models` set of the
renderer's draw port, its joints posed through the item's `nodes`.
`issArticulation.js` turns them every frame, by default from computation: the two alpha joints and eight beta joints face
the arrays to the Sun (feathered along the flight direction in the Earth's
shadow, taken as a cylinder), the two radiator joints keep the radiators
edge-on to it, the two Ku-band dishes aim at the highest TDRS nominal slots
(41°W, 171°W, 85°E) above the station's horizon plane, and Canadarm2, Dextre's
arms and the Japanese arm sway a few degrees about NASA's filed pose, which is
illustrative only (no public source gives their real pose; the European arm has
no joints in the file). Joints turn at most 12°/s of wall time. Docked objects
are found by comparing both orbits at one instant, since dots are moved at
different moments. Selecting the station on the map also gives Context a
STATION section (`stationPanel.js` presents it through the `gev-station`
store; `StationPanel.vue` renders it; `issStation.js` describes the ISS, and
another station plugs in with a description of its own): the station's badge
and the selected entry's name, **Automatic** / **Manual**, a status line, and
**Zoom to the ISS** (offered beyond 1 km while the viewer's follow camera is
on the station's entity; it shortens the camera's offset from the station,
a step per frame, to 260 m, and never moves along the view direction, which
ran away when the camera was not looking at the station).
Automatic (the default) leaves the joints to their rules and says where the
angles come from: "Telemetry · updated 4 s ago" with a green dot while the
relay's answer is fresh, "No signal since 12:04 · computed values" when the
feed lost the station, "Telemetry unavailable · last update 3 min ago ·
computed values" when the relay cannot be reached, "Telemetry not enabled on
this server · computed values" when it is switched off, and a lit/shadow
line. Manual pauses telemetry ("Manual · telemetry paused") and offers the
controls: replace the Sun with a chosen position or a 40 s orbit, fold the
arrays and radiators as a labelled demonstration, aim the dishes and pose
Canadarm2 by joint. Automatic, a new selection, the Cockpit (the rail is
hidden there, and the section with it) or turning the layer off hand every
joint back. `issCommand.js` keeps the rules these share (the zoom's range and
step, the fast orbit, the status wording).
With `ISS_TELEMETRY_ENABLED=1` (off by default: the feed publishes no terms)
`server/providers/space/issTelemetry.js` relays NASA's public ISSLive telemetry
at `/api/iss-telemetry`. It speaks Lightstreamer's text protocol over `ws`,
holds one connection for the whole server, opens it on the first request,
closes it after two minutes without one, retries on a 5 s to 5 min ladder and
recycles a socket that is silent for 30 s. The body is
`{ configured, status, generatedAt, items }`: `status` is `live` only while the
station clock ticked with signal in the last 20 s, and each item is
`[value, epoch ms it was true at]`. On a socket loss the relay discards that
connection's joint samples and station-clock credit, so fresh signal after
reconnection cannot present old angles as live telemetry. Unset, the route answers
`{ configured: false }` without contacting the feed, and the browser asks once.
`issTelemetry.js` in the satellites layer polls it every 5 s while the model is
drawn and, in Automatic, replaces the computed targets with the feed's: each
alpha joint its own angle (port `+`, starboard `-`), each beta joint
`±angle + 90°`, each radiator joint its angle, and the first dish the direction
its elevation and cross-elevation give (the second holds still: the feed
reports one dish and not which). The mapping was fitted on a recording of the
feed: the dish direction stayed within 0.3° of a TDRS satellite across a
hand-over, and the arrays sat 5° to 9° off the Sun; the radiator joints did not
move in the recording, so their sign is not fitted. With no relay, no signal,
an answer older than 20 s, Manual, or a Sun chosen by hand, the joints keep the
computed rules, and the STATION section's status line and note say which
holds. The arms still sway for illustration.
Tiangong is the second station, drawn the same way: `stationModel.js` is the
station-independent model part (load on approach, placement from its own SGP4
sample or the tracked entry's, dot and companion hand-over, ring hidden up
close, card anchor and clearance), driven by a spec; `issModel.js` gives the
ISS's and `tiangongModel.js` Tiangong's (`CSS (TIANHE)`, NORAD 48274, with
`CSS (WENTIAN)`, `CSS (MENGTIAN)` and the Shenzhou and Tianzhou ships as its
docked entries). `policy.js` lists both stations (`STATIONS`) and
`stationModels.js` says which station a tracked entry belongs to, so the card,
the detection marks, the LIVE keys, the Cockpit's mounts and the STATION
section work per station rather than for the ISS alone (tracking records
`_trackedDockedToStation`; the ISS's ring keeps its own rules). The model
(`public/models/tiangong.glb`, 382 KB, 26 k triangles) is the project's own,
built from primitives with procedural textures, in meters and in the ISS
file's frame, so it takes the ISS's flight-axes mapping: the station is
assumed to fly with Tianhe along the velocity, the node forward, the labs
across the orbit and nadir to the Earth. `tiangongJoints.js` carries the
file's 37 joint and dock nodes (pivot, axis, kind) and
`tiangongArticulation.js` drives them, all computed, since China publishes no
telemetry: Tianhe's and the ships' one-axis wings turn about their booms to
face the Sun, the lab wings turn about the lab's axis then their own (the
SARJ/BGA pair), in the Earth's shadow every wing turns flat to the Earth
(edge into the flight direction), the high-gain antenna aims at the highest
Tianlian II nominal slot (79.9°E, 171.04°E, 10.5°E) above the horizon plane,
and the two arms sway a few degrees on one side of their folded pose (so they
lift off the hull), at the ISS's 12°/s cap. The STATION section for Tiangong
(`tiangongStation.js`) says "No public telemetry · computed values", offers
the Sun positions and the fast orbit, every wing on a slider of its own
(Tianhe's two; the labs' four, alpha and beta each: a wing set by hand holds
its angle, reached at the joint rate, while the rest keep following the Sun,
and "Follow the Sun" frees them), and the Tianhe and Wentian arms by joint;
**Zoom to Tiangong** uses the ISS's zoom range. In the Cockpit, Tiangong is
ridden from views on its model (`tiangongMounts.js`), as the ISS is: from
Tianhe (the one it opens on; its port side, out across the track), from the
outer end of Wentian and of Mengtian (out past their wings, which turn through
the view as they follow the Sun) and from the docked vehicle (standing in on
the aft port, looking behind the station); each rides its own catalog entry,
so no cards are needed, and leaving selects Tianhe. The visiting ships are
always drawn; they are not yet toggled by what the catalog shows docked.
The mission factory separates paths, replay, camera, panel, overlays and placement.
Its markers, lines, live rings and pad zone are renderer draw sets, and it
follows a mission through the camera port, so a caller handing it a Cesium
@@ -2121,7 +2402,10 @@ trail, a route. A layer under another layer's card or label
(`isUnderOtherCard`) does nothing: it neither acts on its item there nor
treats the click as empty space, so a tracked aircraft stays tracked and a
selection stays selected. Context (`src/ui/entityContextBridge.js`) names
nothing under a card. With no card on top, the scene rules are unchanged.
nothing under a card. A layer can claim a target it paints outside the overlay's
entries (`registerClickClaim`) where no card or label is on top. A CCTV count
claims each click that zooms to it, so a tracked aircraft stays tracked.
With no card or claim on top, the scene rules are unchanged.
World-overlay hit rectangles are what is painted on screen until the next
paint: an overlay change (a click subscriber publishing its selection card)
no longer clears them mid-click, and a paint that draws nothing clears them
@@ -2761,9 +3045,16 @@ frame the arrows tilt, so the site stays at the centre as the satellite
moves. The turn onto it (and between sites) eases what is left of the swing
with the arrows' easing on a slower clock (250 ms time constant, about
0.75 s to 95%), then holds the site exactly, and cuts under
`prefers-reduced-motion`. A single click on a site's marker focuses it too:
the pick is resolved through the layer's own pick ids (`findByPick`: a named
marker's `{ installationId }` or a site entity). A click anywhere else
`prefers-reduced-motion`. A single click on a site's marker, or on the label
box the overlay paints for it, focuses it too: the click is resolved through
the layer's own lookup (`findAt`: `scene.pick` for a named marker's
`{ installationId }` or a site entity, else the box the overlay painted for
the label; from orbit the dot is 7 px, so the label is what a click lands
on). The map's own click selection reads the label the same way, through a
click claim (`registerClickClaim`) rather than as an interactive card: the
label takes a click only where nothing another layer draws is under it, so
an aircraft or vessel drawn under a base's label stays selectable, and
another layer's card painted over the label keeps its click. A click anywhere else
(a site beyond the reach included), the
focused site's row, NADIR, Home or `0` ends the focus and the view eases
back to nadir on the same clock; an arrow ends it (or the ease back) and
@@ -3525,6 +3816,9 @@ unaffected. `GEV_RATELIMIT_OPENAI_PER_MIN` and `GEV_RATELIMIT_GOOGLE_PER_MIN` ov
those; exactly `0` disables the limiter, while a value that cannot be read as a
number falls back to the default rather than to unlimited. Over-limit requests
receive a sanitized `429` with `Retry-After: 5` and never reach the provider.
The CCTV Street View fallback counts in a separate window with the Google cap.
An IPv6 /64 counts as one client. Over the cap, a frame gets the placeholder
image instead of a `429`.
Typed chat (`/api/openai/chat`, `/api/gemini/chat`) counts in its own window,
set by `GEV_RATELIMIT_OPENAI_CHAT_PER_MIN` and `GEV_RATELIMIT_GEMINI_CHAT_PER_MIN`.
Left unset, each takes its provider's resolved cap — `GEV_RATELIMIT_OPENAI_PER_MIN`
@@ -5108,9 +5402,20 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> stacking. Narrow mobile Cockpit
> viewports suppress the legacy layer stack, peripheral HUD, and secondary
> Context/briefing panes so the flight instruments and primary controls remain
> unobstructed. Outside Cockpit, Radio starts collapsed while off and lives
> only in its section inside Context; the detailed panel's normal accordion
> control owns its disclosure and its Enable/Disable action owns power.
> unobstructed. In the phone layout (720 px wide and below) the flight and
> bridge views put the collapsed Display and Radio launchers in one row
> centred on the Reset/Exit axis, above the reticle and clear of the
> destination cue: below the roll arc in portrait, over the arc's lower tick
> ends in landscape. On short landscape screens the row stays
> on screen and tappable below the vision controls but may cover the top of
> the speed and altitude readouts. Windows under 240 px tall, and those under
> 390 px wide and 450 px tall, keep the row above Reset/Exit at the right.
> Satellite and provider views keep the row
> above Reset/Exit at the right, where their own layouts expect it. The
> first-visit Stories announcement waits, unread, until Cockpit closes.
> Outside Cockpit, Radio starts collapsed while off and lives only in its
> section inside Context; the detailed panel's normal accordion control
> owns its disclosure and its Enable/Disable action owns power.
> Radio volume in the full and Cockpit surfaces, plus Space Mission
> replay speed, use Display / Sharpen's muted 3px rail, circular cyan thumb,
> glow, and mono value treatment. Their larger transparent hit areas, keyboard
@@ -6308,7 +6613,17 @@ caption has no place name (KartaView's is where the drive began) and links to
the full-size photo through the image proxy, since kartaview.org's photo
pages fail for signed-out visitors. The viewer itself is `photoViewer.js`,
shared with Panoramax: each provider hands it a `PhotoSources` table (first
and sharper flat and panorama URLs, and the caption fields).
and sharper flat and panorama URLs, and the caption fields). It builds no
element: it presents the viewer through the layer's
`subscribePhotoViewer()`, which the application shell publishes to the
`gev-street-level-photo` store, and `StreetLevelPhotoViewer` draws it in the
viewer host and hands back the canvas the panorama is drawn on (a fresh one
after a lost context). Each mount and each canvas has a key of its own, so
a viewer never draws on another one's elements, and of two viewers
mounting at once only the later one is drawn (`photoViewers.js`): the
earlier one's mount closes. A view may draw at once or later; what it
reads (`mountKey`, `actions.supersede()`) is `ViewerAdapter.subscribeView`
in `registry.js`. Without a subscribed view these photos cannot open.
Panoramax (`providers/panoramax/`) is keyless and browser-side: the
meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and
@@ -7520,7 +7835,7 @@ 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). Camera icons are cyan for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES`
periodic white flash). Camera icons are green 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
@@ -7529,7 +7844,7 @@ silently demoting every later lookup for the session.
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
@@ -7544,11 +7859,17 @@ silently demoting every later lookup for the session.
empty keeps the old catalog and is retried after another 15 minutes, not on the next
request. Estonia's Tarktee DATEX feeds, which answer in 2 to 16.6 s, get 30 s
(`TARKTEE_FETCH_TIMEOUT_MS`) where other packs get 15 s.
Both Tarktee XML catalogs refuse redirects and have a 4 MiB per-document
limit, enforced against declared length and streamed bytes. A rejected fetch,
unsuccessful response, or body-read failure releases both available response
bodies; read failures also cancel an active sibling reader. Cameras sharing
an image number are deduplicated before the Tarktee pack cap is applied.
Ontario catalog requests refuse redirects and log only the error class and
system code for transport/JSON failures, never the request URL or key.
Both Tarktee XML catalogs share that 30 s deadline, refuse redirects and
have a 4 MiB per-document limit, enforced against declared length and
streamed bytes. A failed request, unsuccessful response or body read aborts
the other feed at once and releases every response body, including one that
arrives after the failure. The Lithuania pack reads its two catalogs
through the same helper (`readCatalogsTogether`,
`server/providers/cctv/catalogPair.js`) with its 15 s deadline. An Ontario
error response has its body released. 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
@@ -8336,7 +8657,8 @@ Providers normalize coordinates, canonical name, label, place types and optional
bounds. Camera framing, nearby landmark recovery and footprint selection remain
in their consumers, including the Capitol identity/containment safeguards.
Radio keeps localized country names in labels rather than station filters.
Nearby/text-search endpoints retain their existing behavior.
Nearby/text-search cache and error rules are listed under Proxy/Security
Baseline below.
**Google geocoding is a server route, not a browser call** (#363). Forward and
reverse lookups go to `/api/google/geocode` and `/api/google/reverse-geocode`,
@@ -8566,7 +8888,7 @@ pins and share links already supply complete boxes.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
- **Aircraft models skip Cesium's dynamic environment map (2026-10-24).** Flights, Military Flights and Local ADS-B pass `environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS` (`{ enabled: false }`, `src/data/aircraftModelLighting.js`) to every drawn model. Otherwise each `Model` renders the sky around it and reads it back from the GPU (`readPixels`) when it is first placed, and again whenever it moves more than 1 km, the scene's atmosphere settings change, or (under sunlight dynamic lighting) an hour of scene time passes (`DynamicEnvironmentMapManager`, Cesium 1.138). The models are lit from Cesium's default spherical harmonics instead, with no specular environment map, so the sky's model-lighting cube map no longer reaches aircraft. `src/data/aircraftModelLighting.test.mjs` pins the option at every drawn model call; every model is built from the fleet set loaded up front, so there is no separate preload.
- The DISPLAY-rail `3D` toggle is the user-facing activation path for both aircraft layers. Their small approved GLBs build their render resources without Cesium's frame-spread job queue, preventing continuous Photorealistic 3D Tiles streaming from starving model readiness; model caps, tracking, camera, and fallback billboards are unchanged.
- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only within 3 km of the camera and only for the nearest `MODEL_MAX` — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. **Consequence for returning users:** a stored `gev:layer-state:v2` blob is a FULL options snapshot, so a session that wrote one before this change carries `models3d:false` and keeps 3D off until the operator flips it (or clears the key) — the durable snapshot is treated as the recipient's own state, by design.
- **The `3D` toggle DEFAULTS ON in `proximity` on a first run.** Proximity is itself the budget — models appear only within 3 km of the camera and only for the nearest `MODEL_MAX` — so the default costs nothing at globe scale, and `all` remains a deliberate opt-in. A fresh boot runs NO layer-state restoration (`LayerStateCoordinator.start()` returns early with neither a share payload nor stored state), so four independent initializers decide what a first-run operator sees and must agree: `booleanOption('models3d', 'e', true)` in `src/data/layerState.js`, `_models3dEnabled = true` in BOTH flight layers, `this._models3dEnabled = true` in `src/ui/aircraftDisplay.js`, and the `active` / `visible` classes on `#models3d-toggle` / `#models3d-mode-row` in `index.html`. All four are pinned together in `src/data/layerState.test.mjs`. Explicit state still wins: because the codec omits default-valued options, `models3d: false` is now what travels in a link (`lo=…f.e.0`) and restores OFF at both aircraft layers. Start-up never reads a stored `gev:layer-state:v2` blob back: a bare URL starts from these defaults and a link from its hash (`src/ui/shareRestoration.js`, `allowLocalState: false`), so clearing the address always resets the view.
- Civilian and military 2D aircraft use the established distance scale: `3×` near
the camera and a `0.5×` floor from 8,000 km outward. A standard 20 px ambient
icon therefore remains about 10 px at globe altitude while retaining the
@@ -8656,6 +8978,7 @@ apply to `public/` assets or built-preview serving.
- `AISSTREAM_API_KEY` is server-side only; the browser reads the same-origin `/api/vessels` cache.
- `/api/google/nearby-places` keeps the Google key out of Places requests issued for voice scene context.
- `/api/google/text-search` keeps the Google key server-side for view-biased Places recovery used by annotation resolution.
- The Places and geocode routes cache only an answer (`private, max-age=300`). For geocode, that means an HTTP success with `OK` or `ZERO_RESULTS`, because Google sends `REQUEST_DENIED` and `OVER_QUERY_LIMIT` as HTTP 200. Every other reply, including an unreadable Places 200 (now a 502), is `no-store`.
- `/api/overpass` is bounded by body/response caps, per-client/global rate limits, concurrency limits, operator-configured upstreams, in-flight dedupe, cache bounds, and static validation that every selector is spatially bounded.
- `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity.
- `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors; routing outages return 502.
@@ -8756,7 +9079,7 @@ apply to `public/` assets or built-preview serving.
The ship bridge and the orbital view have their own own-layer gates
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered with nothing Line truncated
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical layout), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a **cockpit briefing carousel** of three pages: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo; a fourth page, LIVE, is offered while the ridden subject has a live stream (the ISS; see the LIVE section) and shows the same muted player. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus, never turns to the LIVE page and waits while it is shown, and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOLine truncated
- **Cockpit left-panel clearance:** the Cockpit Contact card and peripheral HUD participate in the adaptive left accordion's live obstacle measurements, including live viewport-height changes. Expanding Layers or Authoring keeps the active panel in the available upper-left corridor with internal scrolling; it does not cover the Contact card, lower Cockpit controls, or Cesium credit line. Outside Cockpit the hidden card does not alter the normal corridor.
- **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey.
- **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged.
@@ -8767,7 +9090,7 @@ apply to `public/` assets or built-preview serving.
- **Cockpit weather status:** the earlier multi-canvas atmospheric compositor remains fail-closed and is not attached to the live viewer. Cockpit clouds are a separate transparent WebGL pass with a capped 520×320 framebuffer, 24 ray steps, three FBM octaves, and a 12 FPS ceiling. It defaults off and starts only when local storage explicitly contains the persisted `WX ON` opt-in (`'1'`). When opted in, observations refresh after five minutes or 25 km of aircraft movement, fail transparent when unavailable or clear, and stop on exit or disable. `WX OFF` governs atmospheric rendering only: the briefing still fetches source-backed Natural Earth region, headline, and Open-Meteo local-information data, aborting and replacing any in-flight request when the selected aircraft changes. No weather effect runs in map mode and no synthetic fallback is shown.
- **Cockpit trail visibility:** entering cockpit hides the selected aircraft's trail body and head so they cannot cross the first-person view; exit restores them. This cockpit-only presentation change does not alter the normal map-mode invariant that aircraft trails render through terrain using their depth-fail material.
- **Aircraft course slew:** civilian and military 3D models retain the 60°/s course limiter, but each rendered frame can consume at most 250 ms of accumulated slew time. A long tile/render stall therefore catches up over multiple visible frames instead of turning one delayed frame into a heading snap.
- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode. Live signal data continues refreshing in either state.
- **Manual-first cockpit briefing:** the right-side Live Signals / Regional News / Local Info carousel (plus LIVE while the ridden subject has a stream) does not advance automatically on page load. Previous, Next, and direct page controls remain available; the visible `CYCLE OFF` / `CYCLE ON` toggle explicitly starts or stops the nine-second page cycle, which still pauses on hover/focus and while collapsed, hidden, or outside cockpit mode, and which never turns to the LIVE page. Live signal data continues refreshing in either state.
- **Photoreal horizon blend:** Cesium's sky atmosphere remains enabled behind the hidden base globe, but its light intensity, saturation, and brightness are reduced from the library defaults so the distant Google Photorealistic 3D Tiles boundary blends into the sky instead of producing a bright cyan horizon seam.
- **Cockpit direction and speed tapes:** plausible destination metadata now drives one translucent, isometric visor chevron labeled directly below with the estimated geographic bearing; the prior full geodesic dashed path is not rendered. A mirrored live ground-speed tape follows the inside-left keyhole rim using the same responsive curve, end fades, fixed pointer, and fractional tick motion as the altitude tape on the right. Speed values scroll upward as they increase while altitude values scroll downward. Its tick endpoints and current-speed pointer share the rail's inset-circle origin, so the markings stay attached to the visible curve rather than drifting inward with the text-label gutter.
- Voice control UI (`#gev-voice-control`) shows status states OFF / CONNECTING / LISTENING / EXECUTING / ERROR.
@@ -8809,13 +9132,18 @@ that era's default (`scf` → 35, `ko` → 5). Every link since carries both fie
explicitly, because the generator always writes them, so no era whose default
later changed depends on a fallback either way.
**They do NOT all persist the same way, and only one of them persists at all.**
**None of them comes back from storage on a bare URL; only the hash carries them.**
Worth stating plainly, because "a default you can override" and "a default that
remembers" are different promises:
- **3D models** have durable storage — `gev:layer-state:v2` in local storage,
written by `LayerStateCoordinator` on explicit intent. A session that stored a
snapshot keeps whatever it stored, across tabs and restarts.
- **3D models** are written to `gev:layer-state:v2` in local storage by
`LayerStateCoordinator` on explicit intent, but start-up never reads it back:
a link restores what its hash carries, and a bare URL starts with the default
layers and options (`src/ui/shareRestoration.js` passes
`allowLocalState: false`), so clearing the address always resets the view.
A host may name the layers a bare URL starts with (`startLayers` on
`createApplicationControls`, e.g. `['flights', 'satellites']`); they are
restored passively, never written to storage, and a link's own layers win.
- **Detection mode/density and scope feather have NO storage key at all.** Their
only durable carrier is the URL hash (`dm`/`dd`, `scf`), written on a 500 ms
debounce. A same-URL reload therefore keeps them only if that debounce already
+1
View File
@@ -107,6 +107,7 @@ Call it before views render. `onLocaleChange` listeners word their text again at
- **Translate the label, not the value.** Layer ids, enums, share-link parameters, API fields, voice tool schemas and feed data (callsigns, vessel and place names) stay as they are; translate only the text shown for them.
- **No `t()` at module top level.** Keep the English in `msg()` and call `t()` when rendering.
- **Numbers and dates** go through `formatNumber`, `formatDate`, `formatRelativeTime` and `formatUtcDayMonth` from `src/i18n/index.js`, which follow the active language.
Compact CCTV count badges painted on the map use Latin digits, a decimal point and a `K` suffix for thousands (`999`, `1.7K`, `12K`). Each badge keeps its width and reads the same across locales. Format these badges only with `formatCameraCount` in `src/data/cctvCellCounts.js`.
- **Identical English means identical translation,** unless you give it a context: `t('CLEAR', { context: 'action' })` (a button) is its own catalog entry, `action|CLEAR`, while `t('CLEAR')` (the sky) stays separate. English output is the same.
- **Text that should stay English** (a brand, a code, a unit symbol) is simply not wrapped.
+2 -2
View File
@@ -83,6 +83,6 @@ Consumers use the package exports, which do not import standalone application
globals.
Dataset files and source/license notices remain under `src/data/local_data/`.
Their input counts are 4,352 datacenter features and 704 dam features. A multipart
Their input counts are 4,352 datacenter features and 706 dam features. A multipart
geometry draws as several parts, each with its own stem; part and stem counts are
different measurements from feature counts. This change does not refresh or relicense the datasets.
different measurements from feature counts.
+11
View File
@@ -343,6 +343,17 @@ correction turns them to, paints the mask in a custom shader per colour
clipping plane through the model's origin. The checks `draw.models.bytes`
and `draw.models.fleet` cover them.
An articulated model's joints are its item's `nodes`: transforms of the
model's named glTF nodes, each a column-major 4×4 matrix in the node's
parent frame that replaces the node's own (the ISS's solar arrays,
radiators, dishes and arms). They change live; a node whose name leaves the
map goes back to its authored pose, and names the model lacks are ignored.
A renderer that poses nodes lists `modelNodes`; one without it draws the
model as authored. The Cesium port lists it, and writes each node's matrix
once the model is ready, and again only when its numbers change. The check
`draw.models.nodes` moves the harness model's node off the screen's centre
and back.
The Cesium port draws timed imagery (`imageryFrames`): a layer given a timed
source hides its own imagery and draws each frame its clock shows as a Cesium
imagery layer just above it (in `blend` mode the later frame over the earlier
+232 -41
View File
@@ -37,9 +37,12 @@ one-panel rule too. Share links continue to record which panels are open.
## Component kit
`src/ui/kit/` holds the generic components: `UiRail`, `UiTooltip`, `UiIcon`,
`UiButton`, `UiCloseButton`, `UiPanel`, `UiSegmented`, `UiSlider`, `UiChip`,
`UiSelect`, `UiSearchField`, `UiCheckbox`, `UiDialog`, `UiBadge` and `UiEmpty` so far, with more
joining as the controls they serve are converted. One component
`UiButton`, `UiCloseButton`, `UiPanel`, `UiPanelToggle` (a panel's collapse
button, which `UiPanel` and `PanelCollapseButton` draw), `UiPanelEdge` (a
panel header's edge switch), `UiSegmented`, `UiSlider`, `UiChip`,
`UiSelect`, `UiSearchField`, `UiCheckbox`, `UiDialog`, `UiBadge` and
`UiEmpty` so far, with more joining as the controls they serve are
converted. One component
serves every use of a control, with props for the differences (`UiPanel`'s
`sideways`, `glow`, `scroll`), rather than a copy per panel. The components
are styled by the existing stylesheet and custom properties, and they contain
@@ -81,16 +84,44 @@ Home and End), since each of Core's groups keeps its own keyboard policy, and
once and asks for a change only when it lands on another option. Every
segmented group in Core is a `UiSegmented`; the old `segmentedControl.js`
adapter is gone.
No view hand-writes a control the kit has: every button in an SFC outside
the kit is a `UiButton`, `UiCloseButton` or another kit control, every
Material Symbols glyph a `UiIcon`, every checkbox a `UiCheckbox`, every
select a `UiSelect`, and every range a `UiSlider` except the radio
tuner's and the world timeline's, for the reasons given below. No module
outside the kit, and no SFC's script, builds a button, select, field or
Material glyph in script or writes one as markup in a string, apart from
the globe panel's standalone page (`src/tools/globePanel.js`), plain HTML
a host serves with no Vue or kit, whose Expand and Open buttons are
written as markup (`src/ui/kit/viewControls.test.mjs` pins all of it).
The native fields left are the text, number, password and file inputs
and the two text areas (the chat's message box and the scene dialog's
multiline field) the kit has no control for, and the search fields whose
surfaces this document names. The scene dialog's single-line field takes
its type from its caller, which passes text-like types only.
`UiButton` adds `pressedClass`, Core's class on a pressed toggle (most use
`active`); its pressed classes toggle through `classList`, so a class other
code adds (a voice highlight) survives a press. Not every pressed toggle in
the views is one yet: the context view and a few panel buttons still
hand-write theirs, and
Bhote Koshi's cinematic button and the tilt-map button have owners that
write their state into the DOM. Core's
pressable chips and pills (rail card chips, map sources, cities and places)
are `UiButton`s too; `UiChip` is a non-interactive label chip, used by
the voice card.
code adds (a voice highlight) survives a press. Every pressed toggle (a
control with `aria-pressed`) in the views is a `UiButton` with `pressed`
except Explore's story cards, which keep their own `aria-pressed` since
they are `role="button"` elements, not buttons
(`src/ui/kit/viewControls.test.mjs` pins it). Where the
converted buttons draw Material symbols (the tilt-map button, the Context
header's search and expand, the imported files' row actions and the rail
chips' icons), the glyphs are `UiIcon`s with `:size="null"`, so the site
rules still size them. Core's pressable chips and pills (the rail cards'
chips and action chips, Recent Imagery's day chips, SWAP and ZOOM IN, map
sources, cities and places, the view context's place and layer chips and
the key setup chip) are `UiButton`s too. `UiChip` is a non-interactive
label chip, used by the voice card.
header's search and expand, Draw, Import, the imported files' and drawn
shapes' row actions and the rail chips' icons), the glyphs are `UiIcon`s
with `:size="null"`, so the site rules still size them. Core's pressable
chips and pills (the rail cards' chips and action chips, Recent Imagery's
day chips, SWAP and ZOOM IN, map sources, cities and places, and the view
context's place and layer chips) are `UiButton`s too; the key setup chip
is still a plain button. `UiChip`
is a non-interactive label chip, used by the voice card.
The welcome card's buttons (SKIP, the three start tiles, BROWSE STORIES,
BACK and the main NEXT / ENTER GOD MODE action) are ghost `UiButton`s:
the start tiles are pressed toggles, and all but SKIP keep `aria-disabled`
@@ -106,11 +137,30 @@ Story screen's Context button and the timeline's Expand map are pressed
toggles, with no pressed class since their skins read `aria-pressed`;
Explore's story cards are `role="button"` elements and keep their own
`aria-pressed`. Their glyphs are inline SVG drawn for Stories, which no
Material symbol the page loads draws the same, so they stay SVG; the two
search fields keep their own markup, since `UiSearchField`'s Material
magnifier would replace their SVG one, and their clear buttons, which draw
an SVG cross, are ghost `UiButton`s rather than `UiCloseButton`s
(`src/ui/kit/storiesControls.test.mjs` pins it).
Material symbol the page loads draws the same, so they stay SVG; the three
search fields (Explore's two and the Story context sheet's story search, a
combobox) keep their own markup, since `UiSearchField`'s Material
magnifier would replace their SVG one, and Explore's two clear buttons,
which draw an SVG cross, are ghost `UiButton`s rather than
`UiCloseButton`s (`src/ui/kit/storiesControls.test.mjs` pins it).
Explore's sort is a `UiSelect`.
Every button in the Cockpit HUD (`CockpitView` and its panels: the vision
selector, Look ahead, the view switcher's Reset and Exit, the utility
strip's launchers, collapse buttons, Radio transport and desktop rail, the
briefing card's paging, Auto, collapse and page tabs, the Contact card's
navigation, collapse and Weather, a signal row's target, the orbital
view's TLE, Nadir, zoom and Sensor, and the bridge radar's range) is a
ghost `UiButton` that keeps its id and classes, so the Cockpit
controller's listeners and the cockpit stylesheets still find it. Radio's
Enable (with `active`), Auto and Weather are pressed toggles; the
disclosures keep `aria-expanded` and the page tabs `aria-current`. Its
glyphs (the rim pointers, the reticle, the heading caret, the chevrons and
panel glyphs, the contact and route arrows) are `UiIcon`s with
`:size="null"`; the heading caret's rule reads
`.cockpit-compass .cockpit-heading-caret`, so it still outranks the kit's
`.ui-icon`, which loads after cockpit.css
(`src/ui/kit/cockpitControls.test.mjs` pins it). The −, ◀ ▶ and + glyphs
are text characters and stay text, and the Radio volume is a `UiSlider`.
The Omnibar's mic (a pressed toggle with `active`) and its suggestion
strip's chips (options, so `aria-current` rather than `pressed`) are
ghost `UiButton`s, and its search, row and chip glyphs are `UiIcon`s with
@@ -138,6 +188,23 @@ context view shows too). Their glyphs are `UiIcon`s with `:size="null"`,
so entity-card.css and spot-conditions.css still size them
(`src/ui/kit/entityCardControls.test.mjs` pins it). Ask GEV's chat bubble
stays inline SVG, since no Material symbol the page loads draws it.
The command dock's buttons (the six style buttons, the two tray toggles,
Location's collapse and the search toggle, beside the pins and pills that
already were) are ghost `UiButton`s. The style buttons are pressed toggles
with `active` as their pressed class, so they now carry `aria-pressed`;
Normal is the pressed one until a style is published. Their glyphs, the
search 🔎 and the collapse + are text characters, not Material symbols, and
stay plain text. The Context panel's buttons (its two tabs, Contacts, the
cockpit entry and SEARCH NEARBY SITES, beside the header's search and
expand and the TR-3B chip) are ghost `UiButton`s; the tabs and Contacts
are `role="tab"` controls, chosen through `aria-selected` with their own
`active` class rather than `pressed`. The view context it shows while
nothing is picked (a worldwide tile that turns a layer on, an item's row,
the place and layer chips and Ask GEV) is on the kit too, and the glyphs of
all three are `UiIcon`s with `:size="null"`, so their site rules still size
them; an item's motion glyph keeps `role="img"` and its name, with the
kit's `aria-hidden` taken off (`src/ui/kit/commandDockControls.test.mjs`
pins it). Ask GEV's chat bubble stays inline SVG.
The Layer Finder's buttons (Search, Filter, the filter menu's Status and
Category options and the bar's two clear chips) are ghost `UiButton`s.
Search and the options are pressed toggles; the options' pressed class is
@@ -147,13 +214,109 @@ while a query is typed. The Filter button opens a disclosure and carries
a `UiIcon` with `:size="null"`, so `layer-finder.css` still sizes them
(`src/ui/kit/layerFinderControls.test.mjs` pins it); the search field's
magnifier is `UiSearchField`'s own span.
The Space Missions panel's buttons (a mission's roster row, FOCUS,
REPLAY ASCENT, the replay's pause, PREV, NEXT and SHOW ALL / DESELECT),
the Contacts panel's (PREV, FOCUS, NEXT and a contact's row), the Radio
panel's (Enable, PREV, PLAY, NEXT and STOP), the RTL-SDR card's (Connect,
Locate, Change device, FM, ADS-B, Tune and the two seeks) and the key
setup's (the POWER UP chip, a key's REMOVE, the voice auth toggle and
SAVE KEYS) are ghost `UiButton`s. Radio's Enable and the card's Connect,
FM and ADS-B are pressed toggles with `active`; PLAY and Locate keep
their own `active` class without `aria-pressed`, since their words say
what they will do or have done. The chip's bolt is a `UiIcon` with
`:size="null"`, so provider-settings.css still sizes it
(`src/ui/kit/missionsRadioControls.test.mjs` pins it). The card's FM
frequency stays a native number field, which the kit has no control for,
and the replay's pause, the roster's chevron and the compass arrows are
text characters, not Material symbols.
Utilities' Draw and Import are on the kit. Draw (a pressed toggle with
`active`), Clear and Import are ghost `UiButton`s, their glyphs `UiIcon`s
with `pp-icon` and `:size="null"`. Draw's five colour swatches, in the
toolbar and in a drawn shape's row, are ghost `UiButton`s with
`role="radio"`: they say they are chosen with `aria-checked` and their own
`active` class, never `aria-pressed`. A drawn shape's row (its swatch,
show/hide, the application's row actions and fly to, beside its remove
`UiCloseButton`) is on the kit too, its glyphs `UiIcon`s with
`:size="null"`, so `controls.css` still sizes them; show/hide says what it
does in its name (Show …, Hide …) rather than being pressed. The Street
Level panel's controls already were kit controls; its EXPAND ⤢ ⤡ and its
errors' ⚠ are text characters and stay text
(`src/ui/kit/drawControls.test.mjs` pins it).
The AI chat panel's and the voice control's buttons are ghost
`UiButton`s: the chat's Settings, quick prompts, attachment removes,
Attach layer, Attach a file, Expand conversation, command suggestions,
Expand chat, Add attachment and Send (a submit button that turns into
Stop reply), and the voice control's Open AI chat, Back to chat, Back to
voice, its Preview and Settings tabs and the error tray's DISMISS, beside
the tier button, the mic and the dock and minimize buttons, which already
were. The tier button and dock are pressed toggles; the mic is one only
while its owner has a state for it; the tabs keep `role="tab"` and
`aria-selected`. DISMISS is a text button, not a cross, so it is not a
`UiCloseButton`. The Settings and tab glyphs are `UiIcon`s with
`:size="null"`, so voice-cost.css and voice-card.css still size them
(`src/ui/kit/chatVoiceControls.test.mjs` pins it). The chat bubble,
globe, attach, send and stop, expand and Back glyphs stay inline SVG,
since no Material symbol the page loads draws them the same, and the
message box, file picker and inactivity minutes stay native fields, which
the kit has none of. The voice modules build no controls in script.
The small surfaces' buttons are ghost `UiButton`s: the locale picker's
button, the phone tab bar's tabs, the globe actions' Clear, Share, Reset
and north-up compass, the imagery divider's handle, the scene sharing
dialog's buttons, the layer group index's ticks, the title logo, Exit
clean view, the HUD's cockpit entry, a News card's face, a rail card's
header, a layer row's toggle, the credits line's Data attribution and the
camera calibration chips. None is a pressed toggle; the disclosures keep
`aria-expanded`. Their Material glyphs (the tabs', the globe actions', the
compass needle, the cockpit entry's and the celestial ring's sun and moon)
are `UiIcon`s with `:size="null"`, so the site rules still size them. The
locale picker's globe, caret and check and a News card's category icon stay
inline SVG. The Omnibar guide draws the extra rings of a step with several
targets in its template, as many as `view.subRings` says, rather than
building them in script; the Omnibar's one other `material-symbols-outlined`
is a stylesheet selector, and the layer disclosure only names a button in a
comment (`src/ui/kit/smallSurfacesControls.test.mjs` pins it).
The Street Level photo viewer of KartaView and Panoramax (the photo, the
panorama canvas and the ‹ › buttons) is `StreetLevelPhotoViewer`, drawn
from what the photo viewer presents rather than built in script. Its ‹ and
› are ghost `UiButton`s, not pressed toggles, whose glyphs are text
characters; the viewer builds no element, and the street-level layer it
belongs to needs no Vue (`src/ui/kit/streetLevelPhotoControls.test.mjs`
pins it). The notice the God's Eye View panel page shows when it loses its
3D graphics (`#status`, in `src/app/globePanelRuntime.js`) stays built in
script: that script is sent to the host as source text and runs in the
host's panel page before the app loads, so it can import nothing.
The Bhote Koshi reconstruction panel's buttons (previous and next beat,
Play, Play scene, Cinematic, Full story, Open original, Lower gorge, the
field reports and Open public map) are ghost `UiButton`s that keep their
`data-action` hooks. Cinematic is a pressed toggle with no pressed class,
since bhote-koshi.css reads its `aria-pressed`: the event layer presents
its state as the record's `pressed`, which the panel passes to the
button, instead of writing an `aria-pressed` attribute. The ‹ and ›
arrows are text characters. The event's embedded media cards (each
anchored witness clip's frame, leader line, title, status and original
link, and the hidden YouTube preload) are drawn by
`BhoteKoshiMediaCards`, which `src/data/bhoteKoshiEmbeddedMedia.js`
renders into its overlay root with `h()` and `render()` on every change,
words again on a locale change, and places after each frame; they hold
no control, and the original link stays a link. The script still builds
the provider SDKs' script and preconnect tags, the overlay root, and the
Facebook player node: that node is warmed hidden before its card exists
and carried, loaded, into the card's player, where the SDK replaces its
contents, so a template could only rebuild it and reload the player; the
X post is likewise built by its SDK inside the player
(`src/ui/kit/bhoteKoshiControls.test.mjs` pins it).
`UiSelect` renders the bare native select (Core's labels sit outside it or
come as an `aria-label`) with `v-model`, `options` and `disabled`;
options that carry their own attributes come through the slot, a caller's
`@change` still reaches the select, and `hold` works as in `UiSlider`.
Without `hold`, a select takes its model back after its own change renders,
so a pick its owner refuses goes back; an owner that answers later (the SDR
gain) takes `hold`. Every select in the views is a `UiSelect`.
gain) takes `hold`. A layer row's range ends are repainted on a later frame
and may come back reordered (a start picked after the end swaps them), so
they take a plain `value` instead of a model: a pick stays until the owner
publishes a different value, which shows at once, focused or not
(`src/ui/layerPanel/rowRange.test.mjs`). Every select in the views is a
`UiSelect` (`src/ui/kit/viewControls.test.mjs` pins it).
`UiBadge` takes a `tone` and carries Core's `gev-status-badge`; its
density variants and colours stay caller classes, and it renders the CCTV
source and calibration badges and the rail card badges. `UiEmpty` takes
@@ -165,13 +328,16 @@ empty rows stay a paragraph and table cells.
no tip unless the site passes a `title`; attributes and classes pass through,
so each site keeps its id, feature class and look. Every close, dismiss and
clear button in the views that draws a cross is one
(`src/ui/kit/closeButtons.test.mjs` pins it) except Story Explore's two
search clears, whose SVG cross is neither of its glyphs; the Story context
(`src/ui/kit/closeButtons.test.mjs` and `viewControls.test.mjs` pin it,
for a bare × or one in a span) except Story Explore's two search clears,
whose SVG cross is neither of its glyphs, and an imported file's
Remove, one of the row's icon `UiButton`s (show or hide, fly to, remove)
that draw the icon the file import names for each. The Story context
sheet's Close is a text button, a plain `UiButton`. Street Level's and the
space mission's keep `bare`, since their skins set their own padding and
border, and so does the credits list's. The
Quebec CCTV overlay's close is one too, and so is the Omnibar guide's,
which keeps its feature class and tip.
space mission's (its deselect and the replay's Cancel) keep `bare`, since
their skins set their own padding and border, and so does the credits
list's. The Quebec CCTV overlay's close is one too, and so is the Omnibar
guide's, which keeps its feature class and tip.
`UiSearchField` takes `v-model`, a required `label` (the input's
accessible name), `placeholder` and `tag` (`div`, given `role="search"` by
the site, or `label`); attributes and classes go to the frame, and
@@ -215,7 +381,8 @@ classes, styles and listeners go to the dialog, and `element` is exposed.
The Data Library and the scene sharing dialogs are `UiDialog`s
(`src/ui/kit/dialogs.test.mjs` pins it); the panels drawn as
`role="dialog"` (key setup, the welcome launcher, the CCTV popup, Story
Explore's filter, the credits) and the render failure's `alertdialog` are
Explore's filter, the credits, the Omnibar guide's callout) and the render
failure's `alertdialog` are
other controls. The two dialogs share no declarations, so it has no kit
rules.
`UiSlider` keeps the native range input rather than drawing a
@@ -227,9 +394,12 @@ are, without Core's slider surface). A caller's own input, change and blur
handlers still reach the input, and a null model leaves it as it is. It is
a functional render-function component, so the portable `./ui/input` rows
use it without a component compiler. Every range in the views is a
`UiSlider` except the radio tuner's: its owner moves the handle back to the
`UiSlider` except two. The radio tuner's owner moves the handle back to the
selected station on a drag's first input without changing the slot, which
a functional component would not render again.
a functional component would not render again. The world timeline's
scrubber is a bare range inside its own gesture track: its `step="any"`
bounds follow the zoomed view, and a pinch puts the input back on the
handle itself.
Controls share one skin, so every panel reads the same. Every scrolling
surface carries the kit's `.ui-scroll`, which draws the thin
@@ -240,11 +410,17 @@ page declares no dark `color-scheme`. Selects and number fields are
and keeps native spinners dark; ranges are `.gev-quantitative-slider`, with
a feature supplying only its accent.
`t()` is not reactive. Words a view passes to a kit component as a prop
(`UiCloseButton`'s `label`) follow a locale change on the view's next
render, but words in a kit component's slot do not: the compiled slot does
not render the child again. A view whose words must follow the locale at
once passes the locale itself as a prop or key, as the credits line does.
`t()` is reactive only while the locale is bound to a ref (the app binds
it to vue-i18n's). Words a view passes to a kit component as a prop
(`UiCloseButton`'s `label`) follow the view's render at once. Words and
props read in a kit component's slot follow a tick later, in the child's
own update, and never when the locale is unbound; a slot that reads a
`v-for` variable is already redrawn with its view. A view whose owner
patches synchronously and reads the result at once (a News card, a rail
card, the credits line, the Omnibar guide's buttons) gives such a slot
under a named condition that is always true
(`<template v-if="redrawWithView" #default>`): Vue redraws a conditional
slot whenever its view is drawn.
## Phases
@@ -309,7 +485,20 @@ once passes the locale itself as a prop or key, as the credits line does.
(done: `RecentImageryReadout` and its day cards, the same way),
Street level (done: `StreetLevelPanel` renders the `gev-street-level`
store that `StreetLevelControls` publishes to; the controls keep their
listeners, EXPAND, focus and resizing), CCTV (done: `CctvPanel` renders
listeners, EXPAND, focus and resizing; `StreetLevelPhotoViewer`, beside
it in the layer panels, teleports into the viewer host the photo viewer
KartaView and Panoramax mount there, which `createPhotoViewer()`
presents through the layer's `subscribePhotoViewer()` and the
application shell publishes to the `gev-street-level-photo` store, so
the portable `./layers/street-level` entries need no Vue; the viewer
keeps every decision, the photo loading, keys, drag and zoom, and draws
its panorama on the canvas the view hands back, a fresh one after a lost
WebGL context; each mount and canvas is keyed, so no viewer reuses
another's elements, and of two viewers mounting at once only the later
is drawn while the earlier one's mount closes; with no view
subscribed, as when the layer runs without the application shell, a
KartaView or Panoramax photo cannot mount),
CCTV (done: `CctvPanel` renders
the whole panel from the `gev-cctv` store, including the camera picker,
the inline pose editor, the frame preview, source badge and typed
summary; `CctvControls` keeps its listeners, the frame requests and the
@@ -411,7 +600,8 @@ once passes the locale itself as a prop or key, as the credits line does.
reconstruction panel (`BhoteKoshiPanel`, last in the context rail,
renders what the event layer publishes to the `gev-bhote-koshi-panel`
store: each control's text, hidden, disabled, value and attributes as
the layer writes them, unchanged frames sending nothing; the rail takes
the layer writes them, and the cinematic button's pressed state,
unchanged frames sending nothing; the rail takes
`bhote-event-active` while it shows), the full-globe celestial ring
(`CelestialRing` teleports into the globe container what `CelestialRing`
in `src/celestialRing.js` publishes to the `gev-celestial-ring` store and
@@ -500,14 +690,15 @@ once passes the locale itself as a prop or key, as the credits line does.
records surface by surface; [Building UI](../CONTRIBUTING.md#building-ui)
now requires the pattern for new UI. The page-level markup tests read
`renderApplicationHtml()`, the real views rendered on the server, and new
tests mount components; two tests still read a `.vue` file's source
(`panelStorageDocs`, `geoFileImport`). The views translate with `t()`
while rendering, and vue-i18n holds the locale they read; the attribute
translation pass is left for static page markup (the loading screen and a
host's own markup). An explicit API for hosts to register panels and rail items is
deferred until a host adds one: no host does today (the hosted
application's account interface is its own markup), and the first such
panel, the hosted timeline, will shape it.
tests mount components. Many tests still read `.vue` sources: the kit's
control scans in `src/ui/kit/` (`viewControls`, `closeButtons`,
`checkboxes`, `dialogs` and the per-surface ones) and markup checks such
as `contextTabKeyboard`, `geoFileImport` and `panelStorageDocs`. The
views translate with `t()` while rendering, and vue-i18n holds the
locale they read; the attribute translation pass is left for static page
markup (the loading screen and a host's own markup). An explicit API for
hosts to register panels and rail items is deferred until a host needs
one.
## Verification
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1" />
<title>God's Eye View</title>
<!-- Raster fallbacks: Safari ignores an SVG apple-touch-icon and falls back to a
screenshot of the page, so an installed app needs a real PNG. Regenerate
+79 -2
View File
@@ -1,11 +1,13 @@
# Bundled 3D Models
Every 3D model shipped in this directory is one of the project's procedural
Every 3D model shipped in this directory but two is one of the project's procedural
fleet models under [`fleet/`](fleet/): aircraft, helicopters, ships, buoys,
transit and rail vehicles, and a few other airborne and ground objects. They
are generated from code by the project maintainers, contain no third-party
artwork, and are covered by the repository's [MIT license](../../LICENSE)
like the source code.
like the source code. The exceptions are the two space stations: NASA's model
of the ISS, described in [its own section](#the-iss-model-issglb) below, and
the project's own Tiangong model, [after it](#the-tiangong-model-tiangongglb).
| Path | What it holds |
|---|---|
@@ -37,3 +39,78 @@ How the layers use them:
`src/data/fleetModels.js` reads the set and chooses each vehicle's model;
`src/data/fleetModels.test.mjs` checks that every model `types.json` names is
in the catalog and on disk, and that no GLB exceeds 3 MB.
## The ISS model (`iss.glb`)
Two models sit outside the fleet set. The first is `iss.glb`, the International
Space Station drawn by the satellites layer up close. It is not procedural and not
covered by the MIT license. It is NASA's own model of the station, which is
not subject to copyright in the United States
([NASA Images and Media Usage Guidelines](https://www.nasa.gov/nasa-brand-center/images-and-media));
its use does not imply endorsement by NASA. It loads only when the camera
nears the station.
- **Original work:** “International Space Station (ISS) (D) (IGOAL)”, NASA
Johnson Space Center, Integrated Graphics, Operations and Analysis
Laboratory, on
[NASA 3D Resources](https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/).
- **Reduction:** from the 96 MB original (2.7 M triangles) to 3 MB (314 k
triangles): handrails left out; geometry simplified within 15 cm
(structure) or 40 cm (small details) of the original surface, normals
rebuilt; normal maps dropped; textures resized to 512 px WebP;
Draco-compressed.
- **Frame:** every part is baked into one frame in meters (glTF +Y zenith,
+X port, +Z forward), and the scene root moves the bounding-box centre to
the origin.
- **Corrections:** NASA's file is a mirror image of the station (port and
starboard swapped), which is undone; 15 materials NASA marks as blended
are made opaque, because blended they draw see-through.
- **Marks on the textures:** the station's textures carry the marks it flies
with: the NASA insignia and the ESA, Columbus, JAXA and Nanoracks marks on
the partners' modules. They are kept as flown, to show the station as it
is; their presence implies no endorsement by NASA or by any partner.
- **Moving parts:** parts that move stay separate nodes at the joints NASA
names (two alpha joints, eight array beta joints, two radiator joints,
Canadarm2's seven joints, two joints on each Dextre arm, three on the
Japanese arm). The two Ku-band dishes and three of the four power-module
radiators, welded into the truss in NASA's file, are cut out by position.
## The Tiangong model (`tiangong.glb`)
The second model outside the fleet set is `tiangong.glb`, China's Tiangong
station in its T configuration (Tianhe, Wentian, Mengtian, a Shenzhou forward
and nadir, a Tianzhou aft), drawn by the satellites layer up close. It is an
original model made for God's Eye View and, unlike the ISS model, it is the
project's own work under the repository's [MIT license](../../LICENSE): no
third-party geometry, texture or image is in it. It loads only when the camera
nears the station.
- **Built:** in Blender 5.3 from primitives only (cylinders, cones, spheres,
tori, boxes), every texture generated procedurally by the build script,
[`scripts/build-tiangong-model.py`](../../scripts/build-tiangong-model.py)
(`blender -b --python scripts/build-tiangong-model.py -- <out_dir>`).
26,460 triangles, 12 materials, 15 WebP textures (`EXT_texture_webp`),
Draco-compressed, 382 KB.
- **Dimensions, as published:** Wang, Zhang & Wang 2023, "Design and
Application Prospect of China's Tiangong Space Station", *Space: Science &
Technology*, [doi:10.34133/space.0035](https://doi.org/10.34133/space.0035)
(CC BY 4.0), and [eoPortal's Tiangong page](https://www.eoportal.org/satellite-missions/tiangong):
Tianhe 16.6 m × 4.2 m with its port layout; Wentian and Mengtian 17.9 m ×
4.2 m, one each side of the node; lab wings 27 × ~4 m, two per lab,
two-axis; Tianhe wings 12.6 m per wing (the paper's figure; eoPortal gives
a 60 m total span), one-axis; the Tianhe arm ~10 m and the Wentian arm
~5 m, seven joints each; Shenzhou 9.25 × 2.8 m (17 m span), Tianzhou
10.6 × 3.35 m (14.9 m span) and their docking ports.
- **Approximate (the author's estimates):** the node sphere, small-cylinder
and resource-section diameters, section lengths and cones, hatch and port
tubes; wing widths, root offsets, masts and drive housings; the airlocks,
radiators, high-gain antenna and node antennas; both arms entirely (bases,
booms, joint spacing, rest pose); the ships' module proportions and arrays.
- **Frame:** meters, glTF +X port, +Y zenith, +Z forward (the ISS file's);
the scene root `tiangong` is translated so the station's bounding-box
centre (without the ships) is at the origin.
- **Moving parts:** joints are nodes with identity rest transforms and the
pivot, axis, kind and range in their `extras` (also in
`src/layers/satellites/tiangongJoints.js`): two Tianhe wing drives, four
lab wing alpha + beta pairs, the antenna gimbal, seven joints per arm, two
drives per ship, six dock markers.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
+54 -1
View File
@@ -157,6 +157,7 @@
"server/providers/cctv/groundHeights.js",
"server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js",
"server/providers/cctv/catalogPair.js",
"src/data/cctvLithuania.test.mjs",
"server/providers/cctv/taiwan.js",
"src/data/cctvTaiwan.test.mjs",
@@ -649,6 +650,9 @@
"src/layers/cctv/health.js",
"src/data/cctv.js",
"src/data/cctvCatalogCap.test.mjs",
"src/data/cctvCellCounts.test.mjs",
"src/data/cctvViewPass.test.mjs",
"src/data/cctvViewThinning.test.mjs",
"src/data/cctvDisplayCode.test.mjs",
"src/data/cctvFootprint.js",
"src/data/cctvGroundHeights.test.mjs",
@@ -667,12 +671,17 @@
"src/data/cctvTxdotSource.test.mjs",
"src/layers/cctv/source.test.mjs",
"src/layers/cctv/frames.test.mjs",
"src/layers/cctv/countMarkers.test.mjs",
"src/layers/cctv/count_click_overlay.test.mjs",
"src/layers/cctv/count_click_framing.test.mjs",
"src/layers/cctv/ground.test.mjs",
"src/layers/cctv/rendering.test.mjs",
"src/data/alprCameras.js",
"src/data/alprCameras.test.mjs",
"src/data/dataCredits.test.mjs",
"src/layers/alpr/index.js",
"src/layers/alpr/model.js",
"src/layers/alpr/modelSpecs.test.mjs",
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/presentation.test.mjs",
@@ -1157,6 +1166,8 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/photoViewers.test.mjs",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -1299,6 +1310,7 @@
"src/render/cesium/zoomOutGuard.test.mjs",
"src/app/controls.test.mjs",
"scripts/qa-zoom-out-guard.mjs",
"scripts/qa-zoom-under-icon.mjs",
"src/hudSummaryGate.test.mjs",
"src/hudSummaryLine.test.mjs",
"src/testSupport/stubMgrs.mjs",
@@ -1341,6 +1353,7 @@
"src/ui/kit/UiCloseButton.vue",
"src/ui/kit/UiCloseButton.test.mjs",
"src/ui/kit/closeButtons.test.mjs",
"src/ui/kit/viewControls.test.mjs",
"src/ui/styles/close-button.css",
"src/ui/kit/UiSearchField.vue",
"src/ui/kit/UiSearchField.test.mjs",
@@ -1358,6 +1371,16 @@
"src/ui/kit/welcomeControls.test.mjs",
"src/ui/kit/omnibarControls.test.mjs",
"src/ui/kit/storiesControls.test.mjs",
"src/ui/kit/chatVoiceControls.test.mjs",
"src/ui/kit/cockpitControls.test.mjs",
"src/ui/kit/smallSurfacesControls.test.mjs",
"src/ui/kit/commandDockControls.test.mjs",
"src/ui/kit/streetLevelPhotoControls.test.mjs",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/kit/bhoteKoshiControls.test.mjs",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/ui/kit/missionsRadioControls.test.mjs",
"src/ui/kit/drawControls.test.mjs",
"src/ui/styles/chip.css",
"src/ui/styles/empty-state.css",
"src/ui/rail/RailChips.vue",
@@ -1433,6 +1456,7 @@
"src/data/firmsIntensity.test.mjs",
"src/ui/layerPanel/RowSwitch.vue",
"src/ui/layerPanel/RowRange.vue",
"src/ui/layerPanel/rowRange.test.mjs",
"src/ui/layerPanel/RowSlider.vue",
"src/sources/phaseTiming.test.mjs",
"scripts/build-census-places.mjs",
@@ -1648,5 +1672,34 @@
"src/layers/firms/selection.test.mjs",
"src/layers/vessels/selection.test.mjs",
"src/layers/bikeshare/selection.test.mjs",
"src/layers/satellites/interaction.test.mjs"
"src/layers/satellites/interaction.test.mjs",
"server/providers/space/issTelemetry.test.mjs",
"src/data/liveStreams.test.mjs",
"src/data/youtubeLivePlayer.test.mjs",
"src/data/youtubeApi.test.mjs",
"src/layers/installations/labelBoxClick.test.mjs",
"src/layers/satellites/cockpitSubject.test.mjs",
"src/layers/satellites/issArticulation.test.mjs",
"src/layers/satellites/issCommand.test.mjs",
"src/layers/satellites/issModel.test.mjs",
"src/layers/satellites/issMounts.test.mjs",
"src/layers/satellites/issTelemetry.test.mjs",
"src/layers/satellites/offCesium.test.mjs",
"src/layers/satellites/stationModel.test.mjs",
"src/layers/satellites/stationModels.test.mjs",
"src/layers/satellites/stationPanel.test.mjs",
"src/layers/satellites/stationResume.test.mjs",
"src/layers/satellites/tiangongArticulation.test.mjs",
"src/layers/satellites/tiangongModel.test.mjs",
"src/layers/satellites/tiangongMounts.test.mjs",
"src/layers/satellites/tiangongStation.test.mjs",
"src/render/cesium/draw.test.mjs",
"src/ui/cockpitBriefing.test.mjs",
"src/ui/cockpitOrbitalFocus.test.mjs",
"src/ui/cockpitOrbitalView.test.mjs",
"src/ui/liveControls.test.mjs",
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css"
]
+2
View File
@@ -649,6 +649,8 @@ const ZH_HANT_CORRECTIONS = [
['箇中', '個中'],
// 周 as a week: the time-lapse speed in weeks per second.
[' 周/秒', ' 週/秒'],
// 后 as "behind" after a module name (问天, 梦天), not 天后 (empress).
['天后側', '天後側'],
];
let s2tw;
+101 -7
View File
@@ -211,7 +211,9 @@
"src/ui/stores/windInspection.js",
"src/ui/views/panels/WindInspectionMarker.vue",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/views/panels/MissionReplayOverlay.vue",
"src/ui/views/panels/StreetLevelPhotoViewer.vue",
"src/ui/stores/bhoteKoshiPanel.js",
"src/ui/views/panels/BhoteKoshiPanel.vue",
"src/ui/stores/celestialRing.js",
@@ -313,7 +315,13 @@
"src/search/gridReference.js",
"src/search/coordinateParser.js",
"src/search/placeSuggestions.js",
"src/search/bip39Words.js"
"src/search/bip39Words.js",
"src/ui/stores/station.js",
"src/ui/views/panels/StationPanel.vue",
"src/ui/stores/live.js",
"src/ui/views/panels/LivePanel.vue",
"src/ui/views/panels/CockpitLivePage.vue",
"src/ui/liveScreen.js"
],
"external": ["vue", "pinia", "vue-i18n"]
},
@@ -563,6 +571,7 @@
"server/providers/cctv/groundHeights.js",
"server/providers/cctv/catalog.js",
"server/providers/cctv/lithuania.js",
"server/providers/cctv/catalogPair.js",
"server/providers/cctv/taiwan.js",
"server/providers/cctv/quebec.js",
"server/providers/cctv/ottawa.js",
@@ -581,7 +590,9 @@
"src/data/cctvFootprint.js",
"src/sources/cctvTypes.js",
"src/sources/httpBody.js",
"src/i18n/marker.js"
"src/i18n/marker.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js"
],
"external": []
},
@@ -1289,7 +1300,9 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js"
],
"external": ["cesium", "kdbush"]
},
@@ -1604,6 +1617,7 @@
"src/ui/stores/status.js",
"src/ui/toast.js",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/stores/celestialRing.js",
"src/ui/stores/worldOverlayActions.js",
"src/ui/stores/awarenessDirection.js",
@@ -1687,10 +1701,19 @@
"src/data/aircraftEmergency.js",
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/data/locate.js",
"src/data/trackingClickGesture.js",
"src/ui/stores/sceneSharing.js",
"src/maps/attribution.js",
"src/data/dataCredits.js"
"src/data/dataCredits.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/ui/stores/station.js",
"src/ui/stores/live.js",
"src/data/liveStreams.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js"
],
"external": [
"cesium",
@@ -1963,6 +1986,7 @@
"src/layers/flights/policy.js",
"src/render/color.js",
"src/layers/flights/queries.js",
"src/data/locate.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
"src/render/cesium/query.js",
@@ -2114,6 +2138,7 @@
"src/layers/military/policy.js",
"src/render/color.js",
"src/layers/military/queries.js",
"src/data/locate.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
"src/render/cesium/query.js",
@@ -2281,6 +2306,7 @@
"src/layers/vessels/lifecycle.js",
"src/layers/vessels/policy.js",
"src/layers/vessels/queries.js",
"src/data/locate.js",
"src/geo/vector.js",
"src/layers/vessels/rendering.js",
"src/render/camera/poseSignature.js",
@@ -2852,7 +2878,21 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
],
"external": ["cesium", "satellite.js", "kdbush"]
},
@@ -3351,6 +3391,9 @@
"src/data/cctvCards.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cameraFraming.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/iconOrientation.js",
"src/data/screenRotation.js",
@@ -3556,6 +3599,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -3641,6 +3685,8 @@
"src/render/cesium/common.js",
"src/render/cesium/internals.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/cctv/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -4181,6 +4227,7 @@
"src/render/cesium/heights.js",
"src/ui/imagerySplit.js",
"src/data/bhoteKoshiEmbeddedMedia.js",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/data/bhoteKoshiLocator.js",
"src/data/bhoteKoshiIncidentPlaces.js",
"src/data/bhoteKoshiFloodPath.js",
@@ -4313,6 +4360,8 @@
"src/data/cctvFootprint.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/cockpitAirLod.js",
"src/data/cockpitContactDot.js",
@@ -4439,6 +4488,7 @@
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -5150,6 +5200,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -5368,6 +5419,7 @@
"src/ui/stores/windInspection.js",
"src/layers/wind/inspectionMarker.js",
"src/ui/stores/missionReplay.js",
"src/ui/stores/streetLevelPhoto.js",
"src/ui/stores/bhoteKoshiPanel.js",
"src/ui/stores/celestialRing.js",
"src/ui/stores/screenAnnotations.js",
@@ -5521,7 +5573,28 @@
"src/data/entityContext.js",
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/render/cesium/cardPreviews.js"
"src/data/locate.js",
"src/render/cesium/cardPreviews.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/ui/stores/live.js",
"src/ui/stores/station.js",
"src/data/liveStreams.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/data/youtubeApi.js",
"src/data/youtubeLivePlayer.js",
"src/ui/liveControls.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongModel.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js"
],
"external": [
"hls.js",
@@ -5583,6 +5656,7 @@
"src/ui/imagerySplit.js",
"src/maps/imageryComparison.js",
"src/data/bhoteKoshiEmbeddedMedia.js",
"src/ui/bhoteKoshi/BhoteKoshiMediaCards.vue",
"src/data/bhoteKoshiLocator.js",
"src/render/cesium/camera.js",
"src/render/cesium/frame.js",
@@ -5654,6 +5728,8 @@
"src/data/cctvFootprint.js",
"src/data/cctvGizmo.js",
"src/data/cctvLod.js",
"src/data/cctvCellCounts.js",
"src/layers/cctv/countMarkers.js",
"src/data/cctvViewshed.js",
"src/data/cockpitAirLod.js",
"src/data/cockpitContactDot.js",
@@ -5728,6 +5804,7 @@
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/visuals.js",
"src/layers/alpr/modelSpecs.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/markerState.js",
"src/layers/alpr/source.js",
@@ -5959,6 +6036,7 @@
"src/layers/vessels/lifecycle.js",
"src/layers/vessels/policy.js",
"src/layers/vessels/queries.js",
"src/data/locate.js",
"src/layers/vessels/rendering.js",
"src/render/motion/iconBook.js",
"src/layers/vessels/iconBook.js",
@@ -6213,6 +6291,7 @@
"src/layers/streetLevel/providers/panoramax/decode.js",
"src/layers/streetLevel/providers/panoramax/viewer.js",
"src/layers/streetLevel/photoViewer.js",
"src/layers/streetLevel/photoViewers.js",
"src/layers/streetLevel/limiter.js",
"src/layers/streetLevel/imageSize.js",
"src/layers/streetLevel/tileCache.js",
@@ -6356,7 +6435,22 @@
"src/data/placementProvider.js",
"src/data/courseFromFixes.js",
"src/time/frameWait.js",
"src/maps/attribution.js"
"src/maps/attribution.js",
"src/layers/satellites/issModel.js",
"src/layers/satellites/issTelemetry.js",
"src/layers/satellites/issMounts.js",
"src/layers/satellites/tiangongMounts.js",
"src/layers/satellites/issArticulation.js",
"src/layers/satellites/issCommand.js",
"src/data/youtubeApi.js",
"src/layers/satellites/stationPanel.js",
"src/layers/satellites/issStation.js",
"src/layers/satellites/stationModels.js",
"src/layers/satellites/stationModel.js",
"src/layers/satellites/tiangongStation.js",
"src/layers/satellites/tiangongJoints.js",
"src/layers/satellites/tiangongArticulation.js",
"src/layers/satellites/tiangongModel.js"
],
"external": [
"hls.js",
+37
View File
@@ -1790,6 +1790,43 @@ 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. The gizmo is drawn
// through the renderer ports, so its arrow is read from the layer's drawn
// state (plain {x,y,z} points), not from viewer.entities.
const dragFraming = await page.evaluate(async () => {
const viewer = window.__godsEyeView.viewer;
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
const arrow = () =>
mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east']?.positions;
if (!arrow()?.length) return null;
const Cartesian3 = viewer.camera.positionWC.constructor;
const measure = () => {
const pts = arrow();
if (!pts?.length) return { shaftPx: null, rangeM: null };
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: Cartesian3.distance(viewer.camera.positionWC, pts[0]),
};
};
const before = measure();
const target = Cartesian3.clone(arrow()[0]);
viewer.camera.cancelFlight();
viewer.camera.lookAt(target, new Cartesian3(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 };
});
record(
'drag fixture frames the east arrow above the 10px grab threshold',
dragFraming?.after?.shaftPx >= 10,
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.
+148
View File
@@ -2050,6 +2050,151 @@ try {
JSON.stringify(narrowViewActions),
);
// A fresh profile has not seen the Stories announcement: Cockpit keeps
// it unread and off the phone row until it closes.
const storiesPopupDisplay = () => {
const popup = document.getElementById('hPop');
return popup ? getComputedStyle(popup).display : null;
};
const storiesPopupInCockpit = await page.evaluate(storiesPopupDisplay);
check('the unread Stories announcement waits while Cockpit is open',
storiesPopupInCockpit === 'none', String(storiesPopupInCockpit));
// Windows too short for the centred row keep it above Reset/Exit.
for (const [width, height] of [[360, 370], [320, 360], [568, 188], [667, 190]]) {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
const glyphHits = await page.evaluate(async () => {
const manager = window.__godsEyeView.styleManager;
manager._setCockpitDisclosure('display', false);
manager._setCockpitDisclosure('radio', false);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
return [...document.querySelectorAll(
'#cockpit-utility-controls .cockpit-utility-glyph',
)].map((glyph) => {
const box = glyph.getBoundingClientRect();
const target = document.elementFromPoint(
box.left + box.width / 2,
box.top + box.height / 2,
);
return target && glyph.contains(target) ? 'ok' : target?.closest('[id]')?.id || null;
});
});
check(
`${width}×${height} Cockpit Display/Radio glyph centres reach their own launchers`,
glyphHits.length === 2 && glyphHits.every((hit) => hit === 'ok'),
JSON.stringify(glyphHits),
);
}
// The phone row's place in each room: centred on Reset/Exit, on screen,
// tappable, and clear of what that room has space to clear.
for (const [width, height, room] of [
[360, 740, 'portrait'],
[720, 360, 'landscape'],
[667, 240, 'short'],
[390, 844, 'portrait'],
]) {
await page.setViewport({ width, height, deviceScaleFactor: 1 });
const phoneRow = await page.evaluate(async () => {
const manager = window.__godsEyeView.styleManager;
manager._setCockpitDisclosure('display', false);
manager._setCockpitDisclosure('radio', false);
await new Promise(requestAnimationFrame);
manager.cockpitView.syncSignalLayout();
await new Promise(requestAnimationFrame);
const rect = (element) => element?.getBoundingClientRect().toJSON() || null;
const hud = (selector) => document.querySelector(`#cockpit-hud ${selector}`);
const route = document.getElementById('cockpit-route-direction');
// A live flight may have no route, which hides the DEST cue. Show it while
// measuring so the clearance check always has a cue to clear.
const wasHidden = route.hidden;
try {
route.hidden = false;
const controls = [...document.querySelectorAll(
'#cockpit-utility-controls .cockpit-utility-control',
)];
const launchers = controls.map(rect);
const rowLeft = Math.min(...launchers.map((launcher) => launcher.left));
const rowRight = Math.max(...launchers.map((launcher) => launcher.right));
// Taps beside the row reach what is under it.
const besideHits = [];
if (launchers.length) {
const middle = launchers[0].top + launchers[0].height / 2;
for (const x of [rowLeft - 8, rowRight + 8]) {
const target = document.elementFromPoint(x, middle);
besideHits.push(Boolean(target?.closest('#cockpit-utility-controls')));
}
}
return {
launchers,
rowLeft,
rowRight,
besideHits,
hits: controls.map((control) => {
const glyph = control.querySelector('.cockpit-utility-glyph');
const box = glyph?.getBoundingClientRect();
const target = box && document.elementFromPoint(
box.left + box.width / 2,
box.top + box.height / 2,
);
return Boolean(target && glyph.contains(target));
}),
speed: rect(hud('.cockpit-speed')),
altitude: rect(hud('.cockpit-altitude')),
route: rect(route),
chevron: rect(route.querySelector('.cockpit-route-chevron')),
reticle: rect(hud('.cockpit-reticle')),
rollArc: rect(hud('.cockpit-roll-arc')),
vision: rect(hud('.cockpit-vision-controls')),
switcher: rect(document.getElementById('view-switcher')),
viewport: { width: innerWidth, height: innerHeight },
};
} finally {
route.hidden = wasHidden;
}
});
const obstacles = {
portrait: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'rollArc', 'vision'],
// The row covers the roll arc's lower tick ends; ticks and labels stay readable.
landscape: ['speed', 'altitude', 'route', 'chevron', 'reticle', 'vision'],
// No free band between the instruments: only the vision controls.
short: ['vision'],
}[room];
const overlaps = (a, b) => Boolean(a && b)
&& a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
const { rowLeft, rowRight } = phoneRow;
const switcherCentre = (phoneRow.switcher?.left + phoneRow.switcher?.right) / 2;
const [first, second] = phoneRow.launchers;
check(
`${width}×${height} Cockpit Display/Radio row is centred in one line, on screen, tappable and clear of ${obstacles.join(', ')}`,
phoneRow.launchers.length === 2
&& phoneRow.launchers.every((launcher) => launcher.width > 0)
&& phoneRow.speed?.width > 0
&& phoneRow.altitude?.width > 0
&& (room === 'short' || (phoneRow.route?.width > 0 && phoneRow.chevron?.width > 0))
&& phoneRow.hits.every(Boolean)
&& phoneRow.besideHits.every((inside) => !inside)
&& Math.abs((first?.top + first?.bottom) / 2 - (second?.top + second?.bottom) / 2) <= 1
&& phoneRow.launchers.every((launcher) => obstacles.every(
(name) => !overlaps(launcher, phoneRow[name]),
))
&& Math.abs((rowLeft + rowRight) / 2 - switcherCentre) <= 2
&& rowLeft >= 0
&& rowRight <= phoneRow.viewport.width
&& phoneRow.launchers.every((launcher) => (
launcher.top >= 0 && launcher.bottom <= phoneRow.viewport.height
)),
JSON.stringify(phoneRow),
);
}
// A Stories tap that Cockpit refuses leaves the announcement unread.
await page.evaluate(() => document.getElementById('hStories').click());
await page.waitForFunction(
() => document.querySelector('#toast.visible')?.textContent === 'Exit cockpit to open Stories',
);
const resetResult = await page.evaluate(() => {
// Both the UI and compatibility facade delegate to this navigation owner.
const manager = window.__godsEyeView.styleManager._locationNavigation;
@@ -2121,6 +2266,9 @@ try {
&& resetState.visionRestored,
JSON.stringify(resetState),
);
const storiesPopupAfterReset = await page.evaluate(storiesPopupDisplay);
check('the Stories announcement returns once Cockpit closes',
storiesPopupAfterReset !== null && storiesPopupAfterReset !== 'none', String(storiesPopupAfterReset));
check('runtime console remains clean', consoleErrors.length === 0 && localHttpErrors.length === 0,
[...localHttpErrors, ...consoleErrors].slice(0, 6).join(' | '));
} finally {
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env node
/**
* Real-app regression: the wheel zooms with an over-depth icon under the
* centre of the canvas. Start a dev server (`npm run dev`), then run this
* file with QA_BASE_URL set to it.
*
* Below 150 km Cesium sizes a zoom step from the depth it picks at the canvas
* centre. An icon drawn over depth must leave nothing there for that pick, or
* the camera takes the icon (a metre away, on the near plane) for the ground
* and stops zooming.
*/
import assert from 'node:assert/strict';
import puppeteer from 'puppeteer';
const origin = process.env.QA_BASE_URL || 'http://localhost:4173';
const CAMERA_HEIGHT_M = 15_000;
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
...(process.platform === 'darwin'
? ['--use-angle=metal', '--enable-gpu']
: [
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
]),
],
protocolTimeout: 120_000,
});
const errors = [];
try {
const page = await browser.newPage();
page.on('pageerror', (error) => errors.push(error.message));
const viewport = { width: 1200, height: 800 };
await page.setViewport(viewport);
await page.goto(`${origin}/?welcome=0`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(
() =>
window.__godsEyeView?.viewer &&
window.__godsEyeView.viewer.scene.screenSpaceCameraController
.enableInputs &&
document.getElementById('loading-screen')?.classList.contains('hidden'),
{ timeout: 90_000 },
);
const setup = await page.evaluate(async (cameraHeight) => {
const C = await import('/node_modules/cesium/Build/Cesium/index.js');
const { drawOf } = await import('/src/render/rendererOf.js');
const viewer = window.__godsEyeView.viewer;
const scene = viewer.scene;
viewer.camera.cancelFlight();
viewer.trackedEntity = undefined;
// Explicit real renders make each gesture independent of host frame rate.
viewer.useDefaultRenderLoop = false;
const controller = scene.screenSpaceCameraController;
controller.inertiaZoom = 0;
controller.inertiaSpin = 0;
const lon = -30;
const lat = 40; // open Atlantic: nothing else of the app's draws here
const icons = drawOf(viewer).icons({ id: 'qa-zoom-under-icon' });
const item = {
id: 'qa-icon',
pos: C.Cartesian3.fromDegrees(lon, lat, 100),
// Held in place on the GPU, as a live aircraft or vessel icon is.
motion: { kind: 'hold', courseDeg: 0 },
image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#f0f"/></svg>',
)}`,
size: [64, 64],
disableDepthTest: Infinity,
};
const centre = () =>
new C.Cartesian2(
scene.canvas.clientWidth / 2,
scene.canvas.clientHeight / 2,
);
const frame = () => {
scene.requestRender();
viewer.render();
};
const qa = {
height: () => viewer.camera.positionCartographic.height,
setIcon(shown) {
icons.set(shown ? [item] : []);
},
reset() {
viewer.camera.cancelFlight();
viewer.camera.lookAtTransform(C.Matrix4.IDENTITY);
viewer.camera.setView({
destination: C.Cartesian3.fromDegrees(lon, lat, cameraHeight),
orientation: { heading: 0, pitch: -C.Math.PI_OVER_TWO, roll: 0 },
});
frame();
},
async frames(count) {
for (let i = 0; i < count; i++) {
frame();
await new Promise((resolve) => setTimeout(resolve, 0));
}
return qa.height();
},
/** Whether the icon is what a click at the canvas centre picks. */
iconAtCentre() {
const picked = scene.pick(centre());
return JSON.stringify(picked?.id ?? null).includes('qa-icon');
},
/** Metres from the camera to what the depth pick finds at the centre. */
centreDepthM() {
frame();
const point = scene.pickPositionWorldCoordinates(centre());
return point
? C.Cartesian3.distance(point, viewer.camera.positionWC)
: null;
},
};
window.__zoomUnderIconQa = qa;
const gl = scene.context._gl;
const debug = gl.getExtension('WEBGL_debug_renderer_info');
return {
renderer: gl.getParameter(
debug ? debug.UNMASKED_RENDERER_WEBGL : gl.RENDERER,
),
logDepth: scene.logarithmicDepthBuffer,
pickPosition: scene.pickPositionSupported,
};
}, CAMERA_HEIGHT_M);
console.log(
`[INFO] WebGL renderer: ${setup.renderer}; log depth ${setup.logDepth}`,
);
assert.ok(setup.pickPosition, 'the context must support depth picks');
const qa = (method, ...args) =>
page.evaluate(
(name, rest) => window.__zoomUnderIconQa[name](...rest),
method,
args,
);
const x = viewport.width / 2;
const y = viewport.height / 2;
await page.mouse.move(x, y);
/** Wheel `deltaY` at the canvas centre, then the settled camera height. */
const wheel = async (deltaY) => {
await qa('reset');
await page.evaluate(
({ x, y, deltaY }) => {
window.__godsEyeView.viewer.canvas.dispatchEvent(
new WheelEvent('wheel', {
deltaY,
clientX: x,
clientY: y,
bubbles: true,
cancelable: true,
}),
);
},
{ x, y, deltaY },
);
return qa('frames', 40);
};
// The ground alone: what the icon must not change.
await qa('setIcon', false);
await qa('reset');
await qa('frames', 10);
const groundDepth = await qa('centreDepthM');
const groundIn = await wheel(-600);
const groundOut = await wheel(600);
console.log(
`[INFO] no icon: centre depth ${groundDepth?.toFixed(1)} m, wheel in to ${groundIn.toFixed(0)} m, out to ${groundOut.toFixed(0)} m`,
);
assert.ok(groundIn < CAMERA_HEIGHT_M * 0.95, 'control: wheel in zooms in');
assert.ok(groundOut > CAMERA_HEIGHT_M * 1.05, 'control: wheel out zooms out');
await qa('setIcon', true);
await qa('reset');
await page.waitForFunction(
async () => {
await window.__zoomUnderIconQa.frames(1);
return window.__zoomUnderIconQa.iconAtCentre();
},
{ timeout: 30_000 },
);
console.log('[PASS] the icon draws under the canvas centre');
const depth = await qa('centreDepthM');
const zoomedIn = await wheel(-600);
const zoomedOut = await wheel(600);
console.log(
`[INFO] icon at centre: depth pick ${depth === null ? 'finds nothing' : `${depth.toFixed(3)} m away`}, wheel in to ${zoomedIn.toFixed(0)} m, out to ${zoomedOut.toFixed(0)} m`,
);
assert.ok(
depth === null || depth > 100,
`the depth pick must not land on the icon (${depth} m from the camera)`,
);
console.log('[PASS] the depth pick at the centre ignores the icon');
assert.ok(
zoomedIn < CAMERA_HEIGHT_M * 0.95,
`wheel in must zoom in under an icon (height ${zoomedIn.toFixed(1)} m)`,
);
console.log('[PASS] wheel in zooms in');
assert.ok(
zoomedOut > CAMERA_HEIGHT_M * 1.05,
`wheel out must zoom out under an icon (height ${zoomedOut.toFixed(1)} m)`,
);
console.log('[PASS] wheel out zooms out');
assert.ok(await qa('iconAtCentre'), 'the icon must still pick by click');
console.log('[PASS] the icon still picks by click');
assert.deepEqual(errors, [], 'no JavaScript page errors');
console.log('[PASS] no JavaScript page errors');
} finally {
await browser.close();
}
+36 -13
View File
@@ -21,8 +21,13 @@ import { PROXY_SIGNALS } from '../../src/localRequestGate.mjs';
import { createHlsPuller } from './cctv/stream.js';
import { isMlitRiverAdjustmentImage } from './cctv/worldCameras.js';
import { ottawaAuthorizedFrameUrl } from './cctv/ottawa.js';
import { googleServerApiKey } from './places/google-key.js';
import {
GOOGLE_DEFAULT_PER_MIN,
googleServerApiKey,
} from './places/google-key.js';
import { clientNetworkKey, makeCostRateLimiter } from './common/rate-limit.js';
export { CCTV_FRAME_FETCH_TIMEOUT_MS, fetchCctvImageFromUpstream };
/**
* Vite plugin: CCTV camera proxy with source registry, frame/media serving,
* fallback chain (upstream -> Street View -> synthetic SVG), and health tracking.
@@ -198,17 +203,31 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
};
};
let streetViewBudget; // undefined = not built yet; null = the explicit 0 opt-out
/**
* Fetch a Google Street View static image as a fallback frame. Server-side
* call, never reaches the browser — prefers GOOGLE_MAPS_SERVER_API_KEY
* (#33: a key scoped to Street View Static/Places, restricted by server IP
* rather than HTTP referrer) and falls back to the browser-exposed
* GOOGLE_MAPS_API_KEY for setups that haven't split the two yet.
* Each IP (or IPv6 /64) has its own GEV_RATELIMIT_GOOGLE_PER_MIN window,
* separate from Places. Setting it to 0 disables the limit.
*/
const streetViewFallback = async ({ lat, lon, heading, fov, pitch }) => {
const streetViewFallback = async (
client,
{ lat, lon, heading, fov, pitch },
) => {
const streetViewKey = googleServerApiKey();
if (!streetViewKey || !Number.isFinite(lat) || !Number.isFinite(lon))
return null;
// Built on first use, after the standalone env has loaded.
if (streetViewBudget === undefined)
streetViewBudget = makeCostRateLimiter(
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
GOOGLE_DEFAULT_PER_MIN,
);
if (streetViewBudget && !streetViewBudget(client)) return null;
try {
const sv = new URL('https://maps.googleapis.com/maps/api/streetview');
sv.searchParams.set('size', '960x540');
@@ -264,6 +283,8 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
// keyless gate keeps the routes reachable behind a reverse proxy; the
// key-bearing Street View fallback below has its own check.
if (admitSameSiteKeyless(req, res)) return;
// Read before any await: a socket the client has closed has no address.
const client = clientNetworkKey(req);
const sources = await getCctvSources();
const sourceById = new Map(
sources.map((source) => [source.id, source]),
@@ -635,8 +656,7 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
const source = sourceById.get(cameraId);
const label = url.searchParams.get('label') || source?.name || cameraId;
const city = url.searchParams.get('city') || source?.city || '';
const lat = Number(url.searchParams.get('lat') || source?.lat);
const lon = Number(url.searchParams.get('lon') || source?.lon);
// The query sets only the view, the pose the browser draws.
const heading = Number(
url.searchParams.get('heading') || source?.headingDeg,
);
@@ -731,18 +751,21 @@ export function cctvProxy({ sourceRoot = process.cwd() } = {}) {
// request (whose client this server cannot see) gets the placeholder,
// as if no key were configured. Any forwarding header counts, even an
// empty one.
// It also answers only for catalog cameras, at the catalog position;
// the query never sets the location.
const forwarded = PROXY_SIGNALS.some(
(name) => req.headers?.[name] !== undefined,
);
const sv = forwarded
? null
: await streetViewFallback({
lat,
lon,
heading,
fov,
pitch,
});
const sv =
forwarded || !source
? null
: await streetViewFallback(client, {
lat: source.lat,
lon: source.lon,
heading,
fov,
pitch,
});
if (sv?.ok) {
setHealth(cameraId, {
status: 'degraded',
+53
View File
@@ -0,0 +1,53 @@
import { readResponseTextCapped } from '../common/http.js';
/**
* Read catalogs that are only useful together, because the pack joins them.
*
* The requests share one deadline and refuse redirects. Whichever fails first
* (before its headers, on its status, or while its capped body is read or
* parsed) aborts the others at once, so a stalled feed is not waited on until
* the deadline. Every response body is released, including one that arrives
* after another feed has already failed.
*
* @param {Array<{url: string, label: string}>} feeds `label` names the feed
* in the error ("locations download failed: 503").
* @param {{accept: string, maxBytes: number, timeoutMs: number,
* parse?: (text: string) => unknown}} options
* @returns {Promise<unknown[]>} The parsed bodies (texts without `parse`), in
* feed order.
*/
export async function readCatalogsTogether(
feeds,
{ accept, maxBytes, timeoutMs, parse = (text) => text },
) {
const sibling = new AbortController();
const signal = AbortSignal.any([
sibling.signal,
AbortSignal.timeout(timeoutMs),
]);
return Promise.all(
feeds.map(async ({ url, label }) => {
let response;
try {
response = await fetch(url, {
headers: { Accept: accept },
redirect: 'manual',
signal,
});
signal.throwIfAborted();
if (!response.ok) {
throw new Error(
response.status >= 300 && response.status < 400
? `${label} catalog redirected; redirects are not followed`
: `${label} download failed: ${response.status}`,
);
}
return parse(await readResponseTextCapped(response, maxBytes, signal));
} catch (error) {
sibling.abort();
await response?.body?.cancel().catch(() => {});
throw error;
}
}),
);
}
+13 -38
View File
@@ -4,7 +4,7 @@ import {
fallbackHeadingFromId,
prioritizeSources,
} from './normalize.js';
import { readResponseJsonCapped } from '../common/http.js';
import { readCatalogsTogether } from './catalogPair.js';
const BASE = 'https://eismoinfo.lt/eismoinfo-backend';
export const LITHUANIA_CAMERAS_URL = `${BASE}/camera-info-table`;
@@ -81,46 +81,21 @@ export function lithuaniaCameraToSource(row, feature) {
};
}
async function readCatalog(url, sibling) {
const signal = AbortSignal.any([
AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
sibling.signal,
]);
try {
const response = await fetch(url, {
headers: { Accept: 'application/json' },
redirect: 'manual',
signal,
});
if (!response.ok) {
await response.body?.cancel().catch(() => {});
throw new Error(
response.status >= 300 && response.status < 400
? 'catalog redirected; redirects are not followed'
: `Catalog HTTP ${response.status}`,
);
}
return await readResponseJsonCapped(
response,
LITHUANIA_MAX_CATALOG_BYTES,
signal,
);
} catch (error) {
// The join needs both catalogs; release the other request at once
// rather than leaving its body open until the timeout.
sibling.abort();
throw error;
}
}
/** Two bounded requests per shared catalog refresh, no API key required. */
export async function loadLithuaniaSources() {
try {
const sibling = new AbortController();
const [rows, layers] = await Promise.all([
readCatalog(LITHUANIA_CAMERAS_URL, sibling),
readCatalog(LITHUANIA_LOCATIONS_URL, sibling),
]);
const [rows, layers] = await readCatalogsTogether(
[
{ url: LITHUANIA_CAMERAS_URL, label: 'cameras' },
{ url: LITHUANIA_LOCATIONS_URL, label: 'locations' },
],
{
accept: 'application/json',
maxBytes: LITHUANIA_MAX_CATALOG_BYTES,
timeoutMs: CCTV_SOURCE_FETCH_TIMEOUT_MS,
parse: JSON.parse,
},
);
if (!Array.isArray(rows) || !Array.isArray(layers)) return [];
const features = layers.find((layer) => layer?.layer === 'VKR')?.features;
if (!Array.isArray(features)) return [];
+92
View File
@@ -127,3 +127,95 @@ for (const status of [429, 500, 503]) {
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);
});
test('Ontario names a refused redirect and a system code without the request text', async (t) => {
const lines = captureConsole(t);
const key = 'synthetic-secret';
const failures = [
// The shape Node's fetch gives a refused redirect and a DNS failure.
new TypeError('fetch failed', {
cause: new Error('unexpected redirect'),
}),
new TypeError('fetch failed', {
cause: Object.assign(new Error(`getaddrinfo ENOTFOUND ${key}`), {
code: 'ENOTFOUND',
}),
}),
];
t.mock.method(globalThis, 'fetch', async () => {
throw failures.shift();
});
for (let i = 0; i < 2; i++) {
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: key }),
[],
);
}
assert.deepEqual(lines, [
'[CCTV] Ontario 511 camera download error (TypeError, redirect refused)',
'[CCTV] Ontario 511 camera download error (TypeError ENOTFOUND)',
]);
});
test('Ontario releases the body of an error response', async (t) => {
captureConsole(t);
let cancelled = false;
t.mock.method(
globalThis,
'fetch',
async () =>
new Response(
new ReadableStream({
cancel() {
cancelled = true;
},
}),
{ status: 503 },
),
);
assert.deepEqual(
await loadOntarioSourcesFromOpenData({}, { ONTARIO_511_API_KEY: 'k' }),
[],
);
assert.equal(cancelled, true);
});
+34 -70
View File
@@ -43,6 +43,7 @@ import {
TARKTEE_IMAGE_ORIGIN,
DEFAULT_TARKTEE_MAX_SOURCES,
TARKTEE_MAX_CATALOG_BYTES,
TARKTEE_FETCH_TIMEOUT_MS,
TARKTEE_ANCHORS,
DEFAULT_WARENDORF_SOURCE_FILE,
WARENDORF_IMAGE_ORIGINS,
@@ -82,7 +83,6 @@ import {
HK_ANCHORS,
HK_MAX_CATALOG_BYTES,
CCTV_SOURCE_FETCH_TIMEOUT_MS,
TARKTEE_FETCH_TIMEOUT_MS,
DELDOT_CCTV_URL,
DEFAULT_DELDOT_MAX_SOURCES,
DELDOT_ANCHORS,
@@ -172,6 +172,7 @@ import {
pinnedCameraUrl,
} from './normalize.js';
import { directionToHeading } from '../../../src/data/directionText.js';
import { readCatalogsTogether } from './catalogPair.js';
import {
readResponseBytesCapped,
readResponseJsonCapped,
@@ -561,6 +562,22 @@ export function _resetOntarioKeyWarningForTest() {
ontarioKeyMissingLogged = false;
}
/**
* What failed in an Ontario download, without upstream text: the error class,
* plus the system code (`ENOTFOUND`) or a refused redirect when there is one.
* @param {unknown} error
* @returns {string}
*/
function ontarioFailureKind(error) {
const name = /^[A-Za-z]{1,40}$/.test(error?.name) ? error.name : 'Error';
if (error?.cause?.message === 'unexpected redirect')
return `${name}, redirect refused`;
const code = error?.cause?.code;
return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/.test(code)
? `${name} ${code}`
: name;
}
/**
* 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
@@ -593,6 +610,7 @@ export async function loadOntarioSourcesFromOpenData(
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) {
@@ -604,6 +622,7 @@ export async function loadOntarioSourcesFromOpenData(
console.warn(
`[CCTV] Ontario 511 camera download failed: ${resp.status}${keyHint}`,
);
await resp.body?.cancel().catch(() => {});
return [];
}
const rows = await resp.json();
@@ -658,7 +677,7 @@ export async function loadOntarioSourcesFromOpenData(
url: view.url,
snapshotUrl: view.url,
sourceKind: 'ontario-511-open-data',
license: 'Open Government Licence - Ontario',
license: 'Open Government Licence – Ontario',
});
}
@@ -677,9 +696,10 @@ export async function loadOntarioSourcesFromOpenData(
);
return prioritized;
} catch (error) {
// Transport and JSON errors may reflect the credential-bearing request,
// so only the error class and a system code are logged, never the text.
console.warn(
'[CCTV] Ontario 511 camera download error:',
error?.message || error,
`[CCTV] Ontario 511 camera download error (${ontarioFailureKind(error)})`,
);
return [];
}
@@ -1279,73 +1299,17 @@ export function parseTarkteeDatexImages(xml) {
*/
export async function loadTarkteeSourcesFromDatex() {
try {
const responses = await Promise.allSettled([
fetch(TARKTEE_LOCATIONS_URL, {
headers: { Accept: 'application/xml,text/xml,*/*' },
redirect: 'manual',
signal: AbortSignal.timeout(TARKTEE_FETCH_TIMEOUT_MS),
}),
fetch(TARKTEE_IMAGES_URL, {
headers: { Accept: 'application/xml,text/xml,*/*' },
redirect: 'manual',
signal: AbortSignal.timeout(TARKTEE_FETCH_TIMEOUT_MS),
}),
]);
const [locResp, imgResp] = responses.map((result) =>
result.status === 'fulfilled' ? result.value : undefined,
const [locXml, imgXml] = await readCatalogsTogether(
[
{ url: TARKTEE_LOCATIONS_URL, label: 'locations' },
{ url: TARKTEE_IMAGES_URL, label: 'images' },
],
{
accept: 'application/xml,text/xml,*/*',
maxBytes: TARKTEE_MAX_CATALOG_BYTES,
timeoutMs: TARKTEE_FETCH_TIMEOUT_MS,
},
);
// Both responses are fetched in parallel; if either is rejected or overflows
// its byte cap, both bodies must be released so neither transport leaks.
const discardBoth = async () => {
await Promise.allSettled([
locResp?.body?.cancel(),
imgResp?.body?.cancel(),
]);
return [];
};
const rejected = responses.find((result) => result.status === 'rejected');
if (rejected) {
await discardBoth();
throw rejected.reason;
}
if (
(locResp.status >= 300 && locResp.status < 400) ||
(imgResp.status >= 300 && imgResp.status < 400)
) {
console.warn(
'[CCTV] Tarktee DATEX catalog redirected; redirects are not followed',
);
return discardBoth();
}
if (!locResp.ok) {
console.warn('[CCTV] Tarktee locations download failed:', locResp.status);
return discardBoth();
}
if (!imgResp.ok) {
console.warn('[CCTV] Tarktee images download failed:', imgResp.status);
return discardBoth();
}
let locXml;
let imgXml;
const readAbort = new AbortController();
try {
[locXml, imgXml] = await Promise.all([
readResponseTextCapped(
locResp,
TARKTEE_MAX_CATALOG_BYTES,
readAbort.signal,
),
readResponseTextCapped(
imgResp,
TARKTEE_MAX_CATALOG_BYTES,
readAbort.signal,
),
]);
} catch (error) {
readAbort.abort();
await discardBoth();
throw error;
}
const locations = parseTarkteeDatexLocations(locXml);
const images = parseTarkteeDatexImages(imgXml);
if (!locations.size || !images.size) {
+2
View File
@@ -1,6 +1,7 @@
import path from 'node:path';
import { openSkyProxy } from './aircraft/opensky.js';
import { celestrakProxy, rocketLaunchesProxy } from './space.js';
import { issTelemetryProxy } from './space/issTelemetry.js';
import { tomtomProxy } from './traffic.js';
import { firmsProxy } from './firms.js';
import { terrainHeightsProxy } from './terrain.js';
@@ -58,6 +59,7 @@ function localProviderPlugins({
return [
openSkyProxy(),
celestrakProxy(),
issTelemetryProxy(),
tomtomProxy(),
firmsProxy(),
rocketLaunchesProxy(),
+8
View File
@@ -1,5 +1,13 @@
import { resolveGoogleServerKey } from '../../../scripts/google-server-key.mjs';
/**
* Default GEV_RATELIMIT_GOOGLE_PER_MIN for the Places and Geocoding window
* and the separate CCTV Street View window, in requests per minute per IP.
* The Pinokio build sets the same default in pinokio/_ENVIRONMENT.
* `.env.example` suggests 60 for hosts other than localhost.
*/
export const GOOGLE_DEFAULT_PER_MIN = 120;
/**
* Optional Google place context is an empty capability when no key is present,
* not a server outage. Returning 200 keeps a deliberately keyless session out
+29 -25
View File
@@ -1,4 +1,5 @@
import {
GOOGLE_DEFAULT_PER_MIN,
googleServerApiKey,
keylessGooglePlacesResponse,
keylessGoogleGeocodeResponse,
@@ -15,17 +16,7 @@ import {
// undefined = not built yet; null = the explicit 0 opt-out; fn = active limiter
let _googleRateLimiter;
/**
* Requests/min/IP applied when GEV_RATELIMIT_GOOGLE_PER_MIN is unset. This is
* the value the Pinokio build already ships (pinokio/_ENVIRONMENT), so the
* packaged app keeps behaving exactly as it does today and only an
* unconfigured server changes — from unlimited to what the product already
* runs with. Places calls are user-driven (a search, a nearby lookup, an
* installation probe) rather than polled, so this sits far above what the app
* generates and bites only a caller enumerating the endpoint. `.env.example`
* suggests a tighter 60 when the host is not localhost; that still applies.
*/
export const GOOGLE_DEFAULT_PER_MIN = 120;
export { GOOGLE_DEFAULT_PER_MIN };
/** Google cost endpoints (nearby-places, text-search, geocoding). Null only when set to 0. */
function googleRateLimiter() {
@@ -71,6 +62,8 @@ const GEOCODE_UPSTREAM_TIMEOUT_MS = 10_000;
const GEOCODE_MAX_RESPONSE_BYTES = 256 * 1024;
const GEOCODE_ANSWER_STATUSES = new Set(['OK', 'ZERO_RESULTS']);
/** Validate a free-text geocoder query before consuming request quota. */
export function validateGeocodeAddress(searchParams) {
const address = String(searchParams.get('address') || '').trim();
@@ -114,6 +107,10 @@ export function googlePlacesContextProxy({
// Gate first, like the OpenAI routes: a cross-site caller learns nothing
// about this endpoint's method surface.
if (admitSameSite(req, res)) return;
// Default to no-store. The browser caches only the 200 answer below.
// A cached refusal (bad key, API off, quota) would outlive the key fix
// by five minutes.
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
@@ -129,7 +126,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -194,18 +190,21 @@ export function googlePlacesContextProxy({
}),
},
);
const data = await response.json().catch(() => ({}));
const places = projectNearbyPlaces(data, latitude, longitude);
const data = await response.json().catch(() => null);
// A 200 we could not read is an upstream failure, not an empty answer.
if (response.ok && !data)
throw new Error('Google Places request failed');
const places = projectNearbyPlaces(data || {}, latitude, longitude);
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300');
res.end(
JSON.stringify({
places,
error: response.ok
? null
: data.error?.message || 'Google Places request failed',
: data?.error?.message || 'Google Places request failed',
}),
);
} catch (error) {
@@ -222,11 +221,12 @@ export function googlePlacesContextProxy({
// Text Search: resolve a named landmark/POI to a real coordinate, biased to
// the view. Geocoding scatters obscure monument/POI names across the city;
// a view-biased Text Search lands on the actual feature. Same key, field
// mask, throttle, and `places: []` error contract as nearby-places above.
// a view-biased Text Search lands on the actual feature. Same key, throttle,
// cache rule, and `places: []` error contract as nearby-places above.
middlewares.use('/api/google/text-search', async (req, res) => {
// Paid like nearby-places, so gated the same way, first.
if (admitSameSite(req, res)) return;
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
@@ -242,7 +242,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -315,18 +314,20 @@ export function googlePlacesContextProxy({
}),
},
);
const data = await response.json().catch(() => ({}));
const places = projectTextSearchPlaces(data, latitude, longitude);
const data = await response.json().catch(() => null);
if (response.ok && !data)
throw new Error('Google Places request failed');
const places = projectTextSearchPlaces(data || {}, latitude, longitude);
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
if (response.ok) res.setHeader('Cache-Control', 'private, max-age=300');
res.end(
JSON.stringify({
places,
error: response.ok
? null
: data.error?.message || 'Google Places request failed',
: data?.error?.message || 'Google Places request failed',
}),
);
} catch (error) {
@@ -366,6 +367,7 @@ export function googlePlacesContextProxy({
// Gate first, like the Places routes above: a cross-site caller learns
// nothing about this endpoint's method surface.
if (admitSameSite(req, res)) return;
res.setHeader('Cache-Control', 'no-store');
if (req.method !== 'GET') {
refuse(405, 'Method not allowed');
return;
@@ -379,7 +381,6 @@ export function googlePlacesContextProxy({
if (keyless) {
res.statusCode = keyless.statusCode;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(keyless.payload));
return;
}
@@ -446,7 +447,10 @@ export function googlePlacesContextProxy({
res.statusCode = response.ok ? 200 : response.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'private, max-age=300');
// Geocoding reports a denied key or spent quota as HTTP 200 with a
// status of its own; only an answer is worth keeping.
if (response.ok && GEOCODE_ANSWER_STATUSES.has(data.status))
res.setHeader('Cache-Control', 'private, max-age=300');
res.end(JSON.stringify(data));
} catch {
// Fixed public text: a transport, URL or runtime message would
+468
View File
@@ -0,0 +1,468 @@
import { createRequire } from 'node:module';
import { clientNetworkKey, makeRateLimiter } from '../common/rate-limit.js';
import { admitSameSiteKeyless } from '../common/same-site.js';
/**
* NASA's public ISS telemetry (the ISSLive feed), relayed as a small snapshot.
*
* The feed is a push stream served by Lightstreamer for NASA. This module
* holds ONE connection to it for the whole server and gives browsers the
* latest value of each joint item at `/api/iss-telemetry`, so many viewers
* cost the public server one subscriber.
*
* Off by default: the feed publishes no terms of use, so nothing here
* contacts it unless the operator sets `ISS_TELEMETRY_ENABLED=1`. Without the
* flag the route answers `{ configured: false }` and the browser stops asking.
* With it, the connection opens on the first request and closes again once
* nobody has asked for a while.
*/
/** The route browsers poll. */
export const ISS_TELEMETRY_ROUTE = '/api/iss-telemetry';
const FEED_URL = 'wss://push.lightstreamer.com/lightstreamer';
/** Lightstreamer's text protocol (TLCP), spoken directly over the socket. */
const FEED_PROTOCOL = 'TLCP-2.4.0.lightstreamer.com';
const FEED_ADAPTER_SET = 'ISSLIVE';
/** The client id Lightstreamer assigns to custom TLCP clients. */
const FEED_CLIENT_ID = 'mgQkwtwdysogQz2BJ4Ji%20kOj2Bg';
/** The station clock; it ticks only while the ground has signal. */
const SIGNAL_ITEM = 'TIME_000001';
/** `Status.Class` of an item received with signal. */
const SIGNAL_CLASS = '24';
/**
* The items relayed: the joints the ISS model can turn, plus the station
* clock that says whether the feed has signal.
*/
export const ISS_TELEMETRY_ITEMS = Object.freeze([
// Alpha joints (SARJ): port, starboard.
'S0000004',
'S0000003',
// Array beta joints (BGA): 2A, 4A, 2B, 4B, 1A, 3A, 1B, 3B.
'P4000007',
'P4000008',
'P6000008',
'P6000007',
'S4000007',
'S4000008',
'S6000008',
'S6000007',
// Radiator joints (TRRJ): port, starboard.
'S0000002',
'S0000001',
// Ku-band dish: elevation, cross-elevation, transmitting.
'Z1000014',
'Z1000015',
'Z1000013',
// Canadarm2: shoulder roll, yaw, pitch; elbow; wrist pitch, yaw, roll.
'CSASSRMS004',
'CSASSRMS005',
'CSASSRMS006',
'CSASSRMS007',
'CSASSRMS008',
'CSASSRMS009',
'CSASSRMS010',
SIGNAL_ITEM,
]);
const FEED_FIELDS = Object.freeze(['TimeStamp', 'Value', 'Status.Class']);
/** No station clock tick for this long means the signal is gone. */
const SIGNAL_STALE_MS = 20_000;
/** No frame at all for this long (the server probes every 5 s) recycles the socket. */
const SILENCE_MS = 30_000;
/** Nobody asking for this long closes the connection. */
const IDLE_MS = 120_000;
/** Waits between connection attempts, the last one repeating. */
const RETRY_LADDER_MS = Object.freeze([5_000, 15_000, 60_000, 300_000]);
/**
* A session that has run this long has proved itself: its updates bring the
* retry ladder back to its first step. One that ends sooner (a snapshot and
* then `END`, over and over) keeps climbing the ladder.
*/
const STABLE_SESSION_MS = 60_000;
/** The opening handshake with the feed gives up after this. */
const HANDSHAKE_TIMEOUT_MS = 10_000;
/** A frame larger than this is not telemetry; it is dropped unread. */
const MAX_FRAME_BYTES = 64 * 1024;
const TICK_MS = 5_000;
/**
* Whether the operator switched the relay on. Only "1" does.
* @param {Record<string, string|undefined>} [env]
* @returns {boolean}
*/
export function issTelemetryEnabled(env = process.env) {
return String(env.ISS_TELEMETRY_ENABLED || '').trim() === '1';
}
/**
* The feed's time stamp as epoch milliseconds. The feed counts hours from the
* start of the day before January 1st (day of year × 24 + hours of the day),
* with no year; the year is taken from `nowMs`, stepping back one when that
* would put the stamp in the future (a value last sent in December, read in
* January).
* @param {number} hours
* @param {number} nowMs
* @returns {number|null}
*/
export function issTelemetryTimeMs(hours, nowMs) {
if (!Number.isFinite(hours) || hours < 0) return null;
const year = new Date(nowMs).getUTCFullYear();
const at = Date.UTC(year, 0, 0) + hours * 3_600_000;
// A day of slack for clock differences.
return at > nowMs + 86_400_000
? Date.UTC(year - 1, 0, 0) + hours * 3_600_000
: at;
}
/**
* Decode one TLCP update line, `U,<subscription>,<item>,<fields>`, against
* the item's previous field values. Fields are `|`-separated and
* percent-encoded: an empty field is unchanged, `#` is null, `$` is the empty
* string and `^n` stands for n unchanged fields.
* @param {string} line
* @param {(item: number) => Array<string|null>|undefined} previousOf
* @param {number} fieldCount
* @returns {{item: number, fields: Array<string|null>}|null} Null for a line
* that is not a well-formed update.
*/
export function parseTlcpUpdate(line, previousOf, fieldCount) {
if (!line.startsWith('U,')) return null;
const second = line.indexOf(',', 2);
const third = second < 0 ? -1 : line.indexOf(',', second + 1);
if (third < 0) return null;
const item = Number(line.slice(second + 1, third));
if (!Number.isInteger(item) || item < 1) return null;
const previous = previousOf(item) ?? [];
const fields = [];
for (const raw of line.slice(third + 1).split('|')) {
if (fields.length >= fieldCount) return null;
if (raw === '') fields.push(previous[fields.length] ?? null);
else if (raw === '#') fields.push(null);
else if (raw === '$') fields.push('');
else if (raw[0] === '^') {
const run = Number(raw.slice(1));
if (!Number.isInteger(run) || run < 1 || fields.length + run > fieldCount)
return null;
for (let i = 0; i < run; i++)
fields.push(previous[fields.length] ?? null);
} else {
try {
fields.push(decodeURIComponent(raw));
} catch {
return null;
}
}
}
return fields.length === fieldCount ? { item, fields } : null;
}
/**
* The relay: the connection's lifecycle and the snapshot it serves. It owns
* no timers; the caller drives `tick()` every few seconds.
* @param {{createSocket: () => object|null, now?: () => number}} options
* `createSocket` opens the feed and returns a `ws`-style socket (`on`,
* `send`, `terminate`), or null when no socket can be made.
*/
export function createIssTelemetryRelay({ createSocket, now = Date.now }) {
/** @type {Map<string, {value: number, at: number|null}>} */
const values = new Map();
/** Per item index, the raw field values the next update is decoded against. */
const fields = new Map();
let socket = null;
/** Bumped on every connect and dispose, so a dead socket's events are ignored. */
let generation = 0;
let lastDemandAt = null;
let lastFrameAt = null;
let signalAt = null;
let signalClass = null;
let failures = 0;
let retryAt = 0;
let unavailable = false;
/** When the live socket was opened, or null without one. */
let connectedAt = null;
function drop() {
generation += 1;
const old = socket;
socket = null;
connectedAt = null;
fields.clear();
// A replacement session must rebuild both its joint snapshot and signal
// credit; a new clock tick cannot make the old session's angles live.
values.clear();
signalAt = null;
signalClass = null;
try {
old?.terminate?.();
} catch {
// A socket that will not terminate is abandoned; the generation guard
// keeps its events out.
}
}
function fail() {
drop();
const wait =
RETRY_LADDER_MS[Math.min(failures, RETRY_LADDER_MS.length - 1)];
failures += 1;
retryAt = now() + wait;
}
function onLine(line) {
if (line.startsWith('CONOK,')) {
socket?.send(
`control\r\nLS_reqId=1&LS_op=add&LS_subId=1&LS_mode=MERGE&LS_group=${encodeURIComponent(
ISS_TELEMETRY_ITEMS.join(' '),
)}&LS_schema=${encodeURIComponent(FEED_FIELDS.join(' '))}&LS_snapshot=true`,
);
return;
}
// The session was refused, ended, or asks to be re-bound: start over.
if (/^(CONERR|END|LOOP|REQERR),/.test(line)) {
fail();
return;
}
const update = parseTlcpUpdate(
line,
(item) => fields.get(item),
FEED_FIELDS.length,
);
if (!update) return;
const name = ISS_TELEMETRY_ITEMS[update.item - 1];
if (!name) return;
fields.set(update.item, update.fields);
if (connectedAt !== null && now() - connectedAt >= STABLE_SESSION_MS)
failures = 0;
const [stamp, raw, statusClass] = update.fields;
const at = now();
if (name === SIGNAL_ITEM) {
signalAt = at;
signalClass = statusClass;
return;
}
const value = raw === null || raw === '' ? Number.NaN : Number(raw);
if (!Number.isFinite(value)) return;
values.set(name, {
value,
at:
stamp === null || stamp === ''
? null
: issTelemetryTimeMs(Number(stamp), at),
});
}
function connect() {
let opened;
try {
opened = createSocket();
} catch {
opened = null;
}
if (!opened) {
unavailable = true;
return;
}
unavailable = false;
generation += 1;
const mine = generation;
socket = opened;
connectedAt = now();
lastFrameAt = now();
opened.on('open', () => {
if (mine !== generation) return;
opened.send(
`create_session\r\nLS_adapter_set=${FEED_ADAPTER_SET}&LS_cid=${FEED_CLIENT_ID}&LS_send_sync=false&LS_cause=api`,
);
});
opened.on('message', (data) => {
if (mine !== generation) return;
// Nothing the feed sends may take the server down.
try {
if (data?.length > MAX_FRAME_BYTES) return;
lastFrameAt = now();
for (const line of String(data).split('\r\n')) {
if (mine !== generation) return;
if (line) onLine(line);
}
} catch {
fail();
}
});
const lost = () => {
if (mine === generation) fail();
};
opened.on('error', lost);
opened.on('close', lost);
}
/** Whether anyone asked recently enough to keep the connection. */
function wanted() {
return lastDemandAt !== null && now() - lastDemandAt < IDLE_MS;
}
/**
* Housekeeping, every few seconds: close when idle, recycle a silent
* socket, retry a failed one.
* @returns {boolean} False once there is nothing left to watch.
*/
function tick() {
if (!wanted()) {
dispose();
return false;
}
if (socket && now() - lastFrameAt > SILENCE_MS) fail();
if (!socket && !unavailable && now() >= retryAt) connect();
return true;
}
/** Record that a browser asked, opening the connection if it is closed. */
function demand() {
lastDemandAt = now();
if (!socket && !unavailable && now() >= retryAt) connect();
}
function status() {
if (unavailable) return 'unavailable';
if (!socket) return 'reconnecting';
if (signalAt === null) return 'connecting';
return signalClass === SIGNAL_CLASS && now() - signalAt < SIGNAL_STALE_MS
? 'live'
: 'no-signal';
}
/** The body served to browsers: each item's `[value, epoch ms it was true at]`. */
function snapshot() {
const items = {};
for (const [name, { value, at }] of values) items[name] = [value, at];
return { configured: true, status: status(), generatedAt: now(), items };
}
/** Close the connection and forget what it said. */
function dispose() {
drop();
values.clear();
lastDemandAt = null;
signalAt = null;
signalClass = null;
failures = 0;
retryAt = 0;
unavailable = false;
}
return { demand, tick, snapshot, dispose };
}
let webSocketImpl;
/**
* Load `ws` once, lazily: the vessel feed's socket library, so a missing
* optional dependency turns this relay off instead of breaking the server.
* @returns {Function|null}
*/
function loadWebSocket() {
if (webSocketImpl !== undefined) return webSocketImpl;
try {
webSocketImpl = createRequire(import.meta.url)('ws');
} catch {
webSocketImpl = null;
console.warn(
'[ISS telemetry] `ws` is unavailable; the telemetry relay is off.',
);
}
return webSocketImpl;
}
function json(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
});
res.end(JSON.stringify(body));
}
/**
* The Vite plugin that mounts the relay's route.
* @param {{env?: Record<string, string|undefined>, createSocket?: () => object|null,
* now?: () => number}} [options] Test seams; the defaults read the process
* environment at request time and open the real feed.
*/
export function issTelemetryProxy({
env,
createSocket = () => {
const WebSocket = loadWebSocket();
// `ws` buffers a whole frame before handing it over, up to 100 MiB by
// default: the frame cap applies on the socket, not only after it.
return WebSocket
? new WebSocket(FEED_URL, FEED_PROTOCOL, {
maxPayload: MAX_FRAME_BYTES,
handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
})
: null;
},
now = Date.now,
} = {}) {
const relay = createIssTelemetryRelay({ createSocket, now });
// A browser polls every few seconds; this leaves room for several tabs.
const allow = makeRateLimiter({ windowMs: 60_000, max: 60, globalMax: 1200 });
let timer = null;
function stop() {
if (timer) clearInterval(timer);
timer = null;
relay.dispose();
}
function watch() {
if (timer) return;
timer = setInterval(() => {
if (relay.tick()) return;
clearInterval(timer);
timer = null;
}, TICK_MS);
timer.unref?.();
}
function handle(req, res) {
if (admitSameSiteKeyless(req, res)) return;
// The route is the one path: anything under it is not found, as JSON.
const path = String(req.url ?? '/').split('?')[0];
if (path !== '/' && path !== '') {
json(res, 404, { error: 'Not Found' });
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
json(res, 405, { error: 'Method Not Allowed' });
return;
}
// Read per request: the environment is loaded after this module is.
if (!issTelemetryEnabled(env ?? process.env)) {
json(res, 200, { configured: false });
return;
}
// IPv6 clients fold to their /64, so one host cannot spread across it.
if (!allow(clientNetworkKey(req))) {
json(res, 429, { error: 'Too Many Requests' });
return;
}
relay.demand();
watch();
json(res, 200, relay.snapshot());
}
function install(server) {
server.middlewares.use(ISS_TELEMETRY_ROUTE, handle);
// Vite restarts the server in-process while this module's state lives on.
server.httpServer?.on('close', stop);
}
return {
name: 'iss-telemetry-proxy',
configureServer: install,
configurePreviewServer: install,
// Middleware mode has no httpServer to hang 'close' on.
closeBundle: stop,
};
}
@@ -0,0 +1,430 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ISS_TELEMETRY_ITEMS,
ISS_TELEMETRY_ROUTE,
createIssTelemetryRelay,
issTelemetryEnabled,
issTelemetryProxy,
issTelemetryTimeMs,
parseTlcpUpdate,
} from './issTelemetry.js';
/** A `ws`-shaped socket the test drives by hand. */
function fakeSocket() {
const handlers = {};
return {
sent: [],
terminated: false,
on(event, handler) {
handlers[event] = handler;
},
send(text) {
this.sent.push(text);
},
terminate() {
this.terminated = true;
},
emit(event, payload) {
handlers[event]?.(payload);
},
};
}
const index = (name) => ISS_TELEMETRY_ITEMS.indexOf(name) + 1;
/** A relay on a hand-moved clock, with every socket it opened. */
function relayAt(startMs) {
const clock = { ms: startMs };
const sockets = [];
const relay = createIssTelemetryRelay({
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => clock.ms,
});
return { relay, sockets, clock };
}
const NOV_13 = Date.UTC(2026, 10, 13, 11, 0, 0);
/** The feed's stamp for a moment: day of year × 24 + hours of that day. */
const stampOf = (ms) =>
(ms - Date.UTC(new Date(ms).getUTCFullYear(), 0, 0)) / 3_600_000;
test('only ISS_TELEMETRY_ENABLED=1 switches the relay on', () => {
assert.equal(issTelemetryEnabled({}), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '0' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: 'true' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: ' 1 ' }), true);
});
test("the feed's stamp is hours from the day before January 1st", () => {
// 13 November 2026 is day 317: 317 × 24 + 11 hours.
assert.equal(issTelemetryTimeMs(317 * 24 + 11, NOV_13), NOV_13);
assert.equal(
issTelemetryTimeMs(stampOf(NOV_13 - 5000), NOV_13),
NOV_13 - 5000,
);
// A value last sent on 30 December, read on 2 January, belongs to last year.
const january = Date.UTC(2027, 0, 2, 0, 0, 0);
assert.equal(
issTelemetryTimeMs(364 * 24, january),
Date.UTC(2026, 11, 30, 0, 0, 0),
);
assert.equal(issTelemetryTimeMs(Number.NaN, NOV_13), null);
assert.equal(issTelemetryTimeMs(-1, NOV_13), null);
});
test('an update line decodes against the previous field values', () => {
const previous = new Map([[3, ['7000.5', '10.25', '24']]]);
const of = (item) => previous.get(item);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.6|11.5|24', of, 3), {
item: 3,
fields: ['7000.6', '11.5', '24'],
});
// Empty = unchanged, ^n = n unchanged, # = null, $ = empty string.
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.7||', of, 3).fields, [
'7000.7',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.8|^2', of, 3).fields, [
'7000.8',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,#|$|24', of, 3).fields, [
null,
'',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,a%7Cb|1|24', of, 3).fields[0], 'a|b');
// Not updates, or malformed ones.
for (const line of [
'PROBE',
'SUBOK,1,23,3',
'U,1',
'U,1,x,1|2|3',
'U,1,0,1|2|3',
'U,1,3,1|2',
'U,1,3,1|2|3|4',
'U,1,3,^9',
'U,1,3,%E0%A4%A|1|24',
])
assert.equal(parseTlcpUpdate(line, of, 3), null, line);
});
test('the relay opens on the first request, subscribes, and reports live values', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
assert.equal(sockets.length, 0, 'nothing is contacted before a request');
relay.demand();
assert.equal(sockets.length, 1);
assert.equal(relay.snapshot().status, 'connecting');
const socket = sockets[0];
socket.emit('open');
assert.match(socket.sent[0], /^create_session\r\nLS_adapter_set=ISSLIVE&/);
socket.emit(
'message',
'CONOK,S1,50000,5000,*\r\nSERVNAME,x\r\nCLIENTIP,192.0.2.1',
);
assert.match(
socket.sent[1],
/^control\r\n.*LS_mode=MERGE.*LS_schema=TimeStamp%20Value%20Status\.Class/,
);
assert.ok(socket.sent[1].includes('S0000004%20S0000003'));
const stamp = stampOf(NOV_13 - 2000);
socket.emit(
'message',
`U,1,${index('S0000004')},${stamp}|346.12|24\r\nU,1,${index('TIME_000001')},${stamp}|123|24`,
);
let body = relay.snapshot();
assert.equal(body.configured, true);
assert.equal(body.status, 'live');
assert.deepEqual(body.items.S0000004, [346.12, NOV_13 - 2000]);
assert.equal(body.items.TIME_000001, undefined, 'the clock is not a joint');
assert.equal(JSON.stringify(body).includes('192.0.2.1'), false);
// A later update with an unchanged stamp field keeps the old stamp.
clock.ms += 1000;
socket.emit('message', `U,1,${index('S0000004')},|346.5|`);
body = relay.snapshot();
assert.deepEqual(body.items.S0000004, [346.5, NOV_13 - 2000]);
});
test('no station clock tick for 20 s, or a clock without signal, is no-signal', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
const clockLine = (cls) =>
`U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|${cls}`;
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
clock.ms += 19_000;
socket.emit('message', 'PROBE');
assert.equal(relay.snapshot().status, 'live');
clock.ms += 2_000;
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('1'));
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
});
test('a lost or silent connection is retried on a ladder, and stale events are ignored', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const first = sockets[0];
first.emit('open');
first.emit('close');
assert.equal(first.terminated, true);
assert.equal(relay.snapshot().status, 'reconnecting');
// Not before 5 s.
clock.ms += 4_000;
relay.demand();
relay.tick();
assert.equal(sockets.length, 1);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 2);
// The dead socket's late events change nothing.
first.emit('message', `U,1,${index('S0000004')},1|999|24`);
assert.equal(relay.snapshot().items.S0000004, undefined);
// A second failure waits 15 s.
sockets[1].emit('error', new Error('x'));
clock.ms += 14_000;
relay.demand();
assert.equal(sockets.length, 2);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 3);
// A socket that goes silent for 30 s is recycled by the tick.
const third = sockets[2];
third.emit('open');
third.emit('message', 'CONOK,S1,50000,5000,*');
clock.ms += 29_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, false);
clock.ms += 2_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, true);
});
test("a reconnect cannot mark the previous socket's joint samples live", () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const first = sockets[0];
first.emit('open');
first.emit('message', 'CONOK,S1,50000,5000,*');
const stamp = stampOf(clock.ms);
first.emit(
'message',
`U,1,${index('S0000004')},${stamp}|17|24\r\n` +
`U,1,${index('TIME_000001')},${stamp}|1|24`,
);
assert.equal(relay.snapshot().status, 'live');
assert.deepEqual(relay.snapshot().items.S0000004, [17, clock.ms]);
first.emit('close');
assert.equal(relay.snapshot().status, 'reconnecting');
clock.ms += 5_000;
relay.demand();
assert.equal(sockets.length, 2);
assert.equal(relay.snapshot().status, 'connecting');
assert.deepEqual(relay.snapshot().items, {});
const second = sockets[1];
second.emit('open');
second.emit('message', 'CONOK,S2,50000,5000,*');
// The clock can return before any new joint snapshot is delivered.
second.emit(
'message',
`U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|24`,
);
assert.equal(relay.snapshot().status, 'live');
assert.deepEqual(
relay.snapshot().items,
{},
'the new clock must not revive old joint angles',
);
second.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|23|24`);
assert.deepEqual(relay.snapshot().items.S0000004, [23, clock.ms]);
});
test('a refused or ended session starts over', () => {
for (const line of ['CONERR,2,x', 'END,31,x', 'LOOP,0', 'REQERR,1,17,x']) {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
sockets[0].emit('open');
sockets[0].emit('message', line);
assert.equal(sockets[0].terminated, true, line);
assert.equal(relay.snapshot().status, 'reconnecting', line);
}
});
test('with nobody asking for two minutes the connection closes and the values go', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', `U,1,${index('S0000003')},${stampOf(clock.ms)}|14|24`);
clock.ms += 119_000;
socket.emit('message', 'PROBE');
assert.equal(relay.tick(), true);
assert.equal(socket.terminated, false);
clock.ms += 2_000;
assert.equal(relay.tick(), false);
assert.equal(socket.terminated, true);
assert.deepEqual(relay.snapshot().items, {});
// The next request opens a fresh connection.
relay.demand();
assert.equal(sockets.length, 2);
});
test('an oversized or malformed frame is dropped without taking the relay down', () => {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', { length: 10_000_000 });
socket.emit('message', `U,1,${index('S0000004')},1|not-a-number|24`);
socket.emit('message', 'U,1,999,1|2|24');
assert.deepEqual(relay.snapshot().items, {});
assert.equal(socket.terminated, false);
});
test('without a socket library the relay says unavailable', () => {
const relay = createIssTelemetryRelay({ createSocket: () => null });
relay.demand();
assert.equal(relay.snapshot().status, 'unavailable');
});
/** Mount the plugin on a fake Connect stack and return a request function. */
function install(plugin, preview = false) {
const routes = new Map();
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: { use: (route, handler) => routes.set(route, handler) },
});
return (method = 'GET', headers = {}, url = '/') => {
const res = {
headers: {},
writeHead(status, headers) {
Object.assign(this, { status, headers });
},
setHeader(name, value) {
this.headers[name] = value;
},
end(body) {
this.body = body;
this.status ??= this.statusCode;
},
};
routes.get(ISS_TELEMETRY_ROUTE)({ url, method, headers, socket: {} }, res);
return res;
};
}
test('the route is off by default and never opens the feed', () => {
let opened = 0;
const plugin = issTelemetryProxy({
env: {},
createSocket: () => {
opened += 1;
return fakeSocket();
},
});
assert.equal(typeof plugin.configurePreviewServer, 'function');
for (const preview of [false, true]) {
const res = install(plugin, preview)();
assert.equal(res.status, 200);
assert.deepEqual(JSON.parse(res.body), { configured: false });
assert.equal(res.headers['Cache-Control'], 'no-store');
}
assert.equal(opened, 0);
});
test('switched on, the route opens the feed once and serves the snapshot', () => {
const sockets = [];
const plugin = issTelemetryProxy({
env: { ISS_TELEMETRY_ENABLED: '1' },
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => NOV_13,
});
const request = install(plugin);
try {
const first = JSON.parse(request().body);
assert.equal(first.configured, true);
assert.equal(first.status, 'connecting');
request();
assert.equal(sockets.length, 1, 'one connection for every request');
assert.equal(request('POST').status, 405);
const unknown = request('GET', {}, '/anything');
assert.equal(unknown.status, 404);
assert.deepEqual(JSON.parse(unknown.body), { error: 'Not Found' });
assert.equal(request('GET', {}, '/?t=1').status, 200, 'a query is fine');
assert.equal(
request('GET', { 'sec-fetch-site': 'cross-site' }).status,
403,
);
// Sixty requests a minute from one client, then 429.
let limited = 0;
for (let i = 0; i < 70; i++) if (request().status === 429) limited += 1;
assert.ok(limited > 0);
} finally {
plugin.closeBundle();
}
assert.equal(sockets[0].terminated, true);
});
test('a session that keeps ending soon after its snapshot climbs the retry ladder', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
/** The current socket opens, sends a snapshot update, then ends. */
const shortSession = () => {
const socket = sockets.at(-1);
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit(
'message',
`U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`,
);
socket.emit('message', 'END,41,session closed');
};
// Each wait is the next step: 5 s, 15 s, 60 s, then 5 minutes.
for (const wait of [5_000, 15_000, 60_000, 300_000, 300_000]) {
shortSession();
const before = sockets.length;
clock.ms += wait - 1_000;
relay.demand();
assert.equal(sockets.length, before, `not before ${wait / 1000} s`);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, before + 1, `again after ${wait / 1000} s`);
}
// A session that runs a minute before its updates brings the ladder down.
const socket = sockets.at(-1);
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
clock.ms += 60_000;
relay.demand();
socket.emit('message', `U,1,${index('S0000004')},${stampOf(clock.ms)}|17|24`);
socket.emit('message', 'END,41,session closed');
const before = sockets.length;
clock.ms += 5_000;
relay.demand();
assert.equal(sockets.length, before + 1, 'back to 5 s');
});
+1
View File
@@ -126,6 +126,7 @@ export function createApplicationCatalog({
});
const satellites = createApplicationSatellites({
source: sources.satellites,
...(resolveAsset ? { resolveAsset } : {}),
});
const catalog = createLayerCatalog(
[
+4
View File
@@ -21,6 +21,8 @@ export { START_VIEW };
* `homeView` is where the title's logo goes back to (with the clock live): the
* start view unless given, for a host whose `startView` only carries a view
* across a rebuild.
* `startLayers` are the layer ids a bare address (one that carries no link)
* starts with: none by default; a host may pass `['flights', 'satellites']`.
* `services.cockpitSubjects` adds the application's own first-person subjects
* to the Cockpit (src/cockpitSubjectProviders.js).
*/
@@ -36,6 +38,7 @@ export function createApplicationControls({
localePicker = true,
startView = START_VIEW,
homeView = startView,
startLayers = [],
}) {
// Every boot starts from the same view, before share restoration flies on.
applyStartView(viewer, startView);
@@ -59,6 +62,7 @@ export function createApplicationControls({
initialShareCode,
localePicker,
homeView,
startLayers,
});
defer(() => styleManager.orbitController.stop());
defer(() => styleManager.hud.destroy());
+2 -1
View File
@@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js';
import * as credits from '../../data/dataCredits.js';
import * as sprites from '../../data/spriteOrder.js';
import * as activation from '../../cctvFocusRequest.js';
import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import { CITY_POIS } from '../../cityPois.js';
import * as picking from '../../data/pickRegistry.js';
@@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) {
credits,
sprites,
activation,
overlays,
overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry },
locations: { CITY_POIS },
picking,
terrain,
+4
View File
@@ -1,12 +1,16 @@
import {
clearOverlaySource,
getOverlayPaintRect,
getWorldOverlayDiagnostics,
hitTestWorldOverlay,
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
export const overlayHost = Object.freeze({
clearSource: clearOverlaySource,
getDiagnostics: getWorldOverlayDiagnostics,
hitTest: hitTestWorldOverlay,
paintRect: getOverlayPaintRect,
setEntries: setOverlayEntries,
setVisible: setOverlaySourceVisible,
});
+6 -1
View File
@@ -8,9 +8,14 @@ import * as render from '../../renderGovernor.js';
import * as layerState from '../../data/layerState.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationSatellites({ source }) {
export function createApplicationSatellites({
source,
resolveAsset = (url) =>
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
}) {
return createSatellitesLayer({
source,
resolveAsset,
services: {
picking,
focus,
+8 -2
View File
@@ -90,8 +90,14 @@ test('the ring renders its overlay in the viewer container', async (t) => {
['DIV', 'celestial-ring-outline'],
['CANVAS', 'celestial-ring-canvas celestial-sun-canvas'],
['CANVAS', 'celestial-ring-canvas celestial-moon-canvas'],
['SPAN', 'celestial-marker celestial-sun material-symbols-outlined'],
['SPAN', 'celestial-marker celestial-moon material-symbols-outlined'],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-sun',
],
[
'SPAN',
'ui-icon material-symbols-outlined celestial-marker celestial-moon',
],
],
);
assert.equal(root.children[0].style.display, 'none');
+42 -11
View File
@@ -74,10 +74,14 @@ const voiceActions = fs.readFileSync(
test('Cockpit has one reset action beside its bottom exit path', () => {
assert.doesNotMatch(html, /id="cockpit-quick-entry"/);
assert.doesNotMatch(html, /id="cockpit-exit"/);
assert.match(
html,
/id="map-view-switch"[^>]*aria-label="Exit cockpit view"[^>]*aria-keyshortcuts="Escape"[\s\S]*?close_fullscreen[\s\S]*?EXIT COCKPIT/,
// The exit button's attributes, in whatever order the button renders them.
const exit = html.match(
/<button\b(?=[^>]*\sid="map-view-switch")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(exit, 'Cockpit exit is missing');
assert.match(exit[1], /\saria-label="Exit cockpit view"/);
assert.match(exit[1], /\saria-keyshortcuts="Escape"/);
assert.match(exit[2], /close_fullscreen[\s\S]*?EXIT COCKPIT/);
const topCenterActions = html.match(
/<nav id="top-center-actions"[\s\S]*?<\/nav>/,
);
@@ -108,9 +112,18 @@ test('Cockpit has one reset action beside its bottom exit path', () => {
/id="reset-globe-view"/,
'map-only reset must stay outside Cockpit',
);
assert.match(
viewSwitcher[0],
/id="cockpit-reset-globe"[^>]*type="button"[^>]*aria-label="Reset cockpit to full globe view"[^>]*hidden[\s\S]*?public[\s\S]*?RESET[\s\S]*?id="map-view-switch"/,
// The reset button's attributes, in whatever order the button renders them.
const reset = viewSwitcher[0].match(
/<button\b(?=[^>]*\sid="cockpit-reset-globe")([^>]*)>([\s\S]*?)<\/button>/,
);
assert.ok(reset, 'Cockpit Reset is missing from the view switcher');
assert.match(reset[1], /\stype="button"/);
assert.match(reset[1], /\saria-label="Reset cockpit to full globe view"/);
assert.match(reset[1], /\shidden(?=[\s>=]|$)/);
assert.match(reset[2], /public[\s\S]*?RESET/);
assert.ok(
viewSwitcher[0].indexOf('id="map-view-switch"') > reset.index,
'Cockpit Reset must sit before the exit button',
);
const actions = html.match(
@@ -194,12 +207,12 @@ test('Cockpit vision cycle exposes every map preset exactly once', () => {
test('Contacts uses the approved radar icon', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(button, 'Contacts button is missing');
assert.match(
button[0],
/material-symbols-outlined" aria-hidden="true">radar<\/span>/,
/material-symbols-outlined"[^>]*aria-hidden="true">radar<\/span>/,
);
});
@@ -369,11 +382,11 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
assert.doesNotMatch(html, /data-cockpit-display-slot="presets"/);
assert.match(
html,
/id="clear-selected-layers"[^>]*aria-label="Clear selected data layers"/,
/<button\b(?=[^>]*\bid="clear-selected-layers")[^>]*aria-label="Clear selected data layers"/,
);
assert.match(
html,
/id="reset-globe-view"[^>]*aria-label="Reset to full globe view"/,
/<button\b(?=[^>]*\bid="reset-globe-view")[^>]*aria-label="Reset to full globe view"/,
);
assert.match(
css,
@@ -1144,6 +1157,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-controls[\s\S]*?bottom:\s*152px;/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode\.mobile-shell[^{]*?\.cockpit-utility-controls \{[^}]*?top:[^;]*?var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1162,6 +1184,15 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
);
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
);
});
test('cockpit route direction uses self-contained vector artwork, not a font ligature', () => {
const match = html.match(/<div id="cockpit-route-direction"[\s\S]*?<\/div>/);
assert.ok(match, 'cockpit route-direction markup is missing');
@@ -1231,7 +1262,7 @@ test('Cockpit Contact navigation omits the redundant Focus camera action', () =>
test('Global Context names its mixed contact cycle without changing the stable mode id', () => {
const match = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
);
assert.ok(match, 'Global Context contacts button is missing');
assert.match(match[0], />CONTACTS</);
+4 -4
View File
@@ -25,12 +25,12 @@ const css = readStylesheet(new URL('../style.css', import.meta.url));
test('Contacts stays in the keyboard sequence and Space Missions owns its rail item', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
/<button\b[^>]*\bid="global-context-flights-btn"[\s\S]*?<\/button>/,
)?.[0];
assert.ok(button, 'Contacts control is missing');
assert.match(button, /role="tab"/);
assert.match(button, /tabindex="0"/);
const tag = contextView.match(/<button id="global-context-flights-btn"[^>]*>/)?.[0];
const tag = contextView.match(/<UiButton id="global-context-flights-btn"[^>]*>/)?.[0];
assert.ok(tag, 'Contacts control is missing from the view');
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
@@ -111,7 +111,7 @@ test('Context async action buttons remain focused while busy', () => {
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
const search = contextView.match(
/<button id="installations-search-btn"[^>]*>/,
/<UiButton id="installations-search-btn"[^>]*>/,
)?.[0];
assert.ok(search, 'nearby sites search is missing');
assert.doesNotMatch(search, /:disabled|\sdisabled/);
@@ -140,7 +140,7 @@ test('Context async action buttons remain focused while busy', () => {
'utf8',
);
const clearButton = globeActions.match(
/<button id="clear-selected-layers"[^>]*>/,
/<UiButton id="clear-selected-layers"[^>]*>/,
)?.[0];
assert.ok(clearButton, 'Clear selected layers button is missing');
assert.doesNotMatch(clearButton, /disabled(?!=")|:disabled=/);
+1
View File
@@ -335,6 +335,7 @@ test('the Google places route throttles by default and keeps its places[] contra
const overLimit = await request(handler, { url, method: 'GET' });
assert.equal(overLimit.status, 429);
assert.equal(overLimit.headers['retry-after'], '5');
assert.equal(overLimit.headers['cache-control'], 'no-store');
// Every error response on this route carries places[]; the client reads it
// unconditionally, so a throttled reply must not be the one shape that omits it.
assert.deepEqual(JSON.parse(overLimit.body).places, []);
+19 -6
View File
@@ -912,10 +912,12 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
'#command-dock:has(#location-bar:not(.collapsed))',
'#command-dock:has(#control-panel:not(.collapsed))',
];
assert.equal(
omnibarVar('--world-timeline-lift'),
'0px',
'the Omnibar layout holds the timeline lift at 0',
// The dock rises over the World Timeline by world-timeline.css's lift, as
// the plain dock does; the Omnibar scope leaves the lift alone.
assert.doesNotMatch(
fs.readFileSync(path.join(ROOT, 'src/ui/styles/omnibar-dock.css'), 'utf8'),
/--world-timeline-lift\s*:/,
'the Omnibar layout leaves the timeline lift to world-timeline.css',
);
for (const width of WIDTHS.filter((w) => w >= OMNIBAR_MIN_WIDTH)) {
for (const height of HEIGHTS) {
@@ -968,10 +970,21 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
credit.part.startsWith(OMNIBAR_SCOPE),
`the Omnibar owns the credit row at ${width}px`,
);
const dockBottom = omnibarPx(
// The dock rises over the World Timeline from the dock's floor, and
// the bar takes that floor: the floor is what clears the credit.
assert.equal(
dock.decl.value,
'var(--omnibar-dock-raised)',
`Omnibar dock bottom at ${width}px`,
);
assert.equal(
omnibarVar('--omnibar-dock-raised').replace(/\s+/g, ' '),
'calc( var(--omnibar-dock-bottom) + var(--world-timeline-lift, 0px) )',
);
const dockBottom = omnibarPx(
'var(--omnibar-dock-bottom)',
height,
'Omnibar dock bottom',
'Omnibar dock floor',
);
const creditTop =
omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') +
+2
View File
@@ -50,6 +50,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
'surveillance:type': 'ALPR',
operator: 'Flock Safety',
'camera:type': 'fixed',
model: ' L6Q ',
'surveillance:zone': 'traffic',
'camera:direction': '270',
ref: 'ATX-001',
@@ -63,6 +64,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
longitude: -97.7431,
operator: 'Flock Safety',
manufacturer: null,
model: 'L6Q',
cameraType: 'fixed',
zone: 'traffic',
directionDeg: 270,
+174 -232
View File
@@ -5,7 +5,10 @@ import {
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { loadYouTubeApi } from './youtubeApi.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
const YOUTUBE_HOSTS = new Set([
'youtube.com',
@@ -98,59 +101,7 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
if (typeof globalRef.YT?.Player === 'function')
return Promise.resolve(globalRef.YT);
if (youtubeApis.has(documentRef)) return youtubeApis.get(documentRef);
const pending = new Promise((resolve, reject) => {
const previous = globalRef.onYouTubeIframeAPIReady;
let timer;
let settled = false;
const script = documentRef.createElement('script');
const finish = (error) => {
if (settled) return;
settled = true;
globalRef.clearTimeout(timer);
if (globalRef.onYouTubeIframeAPIReady === ready)
globalRef.onYouTubeIframeAPIReady = previous;
if (error) {
script.remove();
reject(error);
} else resolve(globalRef.YT);
};
const ready = () => {
try {
previous?.();
} finally {
finish(
typeof globalRef.YT?.Player === 'function'
? null
: new Error('YouTube API unavailable'),
);
}
};
globalRef.onYouTubeIframeAPIReady = ready;
script.src = 'https://www.youtube.com/iframe_api';
script.async = true;
script.addEventListener(
'error',
() => finish(new Error('YouTube API unavailable')),
{ once: true },
);
timer = globalRef.setTimeout(
() => finish(new Error('YouTube API timed out')),
5000,
);
documentRef.head.append(script);
}).catch((error) => {
youtubeApis.delete(documentRef);
throw error;
});
youtubeApis.set(documentRef, pending);
return pending;
}
let _cardSequence = 0;
/** A trimmed clip follows provider time, never time spent loading its iframe. */
export function createTrimmedYouTubePlayback({
@@ -682,32 +633,61 @@ export function createBhoteKoshiEmbeddedMedia({
let record = null;
let warmRecord = null;
let generation = 0;
// Text the cards show, kept as the calls that word it so a locale change
// words it again. A node is forgotten once it has left the page.
const worded = new Map();
function forgetDetached() {
for (const node of worded.keys())
if (!node.isConnected) worded.delete(node);
let destroyed = false;
// The cards in the root, in the order they were shown: the current one and
// any still leaving. Their text is kept as the calls that word it, so a
// locale change words it again.
const cards = [];
/** Render the cards and the YouTube preload into the root, synchronously. */
function render() {
if (destroyed) return;
const warmFrame = warmRecord?.frame;
renderVue(
h(BhoteKoshiMediaCards, {
warm: warmFrame
? {
key: warmRecord.key,
src: warmFrame.src,
title: warmFrame.title(),
}
: null,
cards: cards.map((current) => ({
id: current.id,
provider: current.source.provider,
portrait: current.portrait,
entering: current.entering,
leaving: current.leaving,
unavailable: current.unavailable,
label: current.label(),
title: current.title(),
status: current.status(),
url: current.source.url,
frame: current.frame && {
src: current.frame.src,
title: current.frame.title(),
onLoad: current.frame.onLoad,
},
bind: current.bind,
})),
}),
root,
);
}
function word(node, property, text) {
let properties = worded.get(node);
if (!properties) worded.set(node, (properties = new Map()));
properties.set(property, text);
writeWord(node, property, text());
}
function writeWord(node, property, value) {
if (property === 'textContent' || property === 'title')
node[property] = value;
else node.setAttribute(property, value);
}
const offLocale = onLocaleChange(() => {
forgetDetached();
for (const [node, properties] of worded)
for (const [property, text] of properties)
writeWord(node, property, text());
});
const offLocale = onLocaleChange(render);
const leavingRecords = new Set();
/** Word a card's status and draw it. */
function setStatus(current, text) {
current.status = text;
render();
}
/** Mark a card unavailable or not and draw it. */
function setUnavailable(current, unavailable) {
current.unavailable = unavailable;
render();
}
const prefersReducedMotion = () =>
globalRef.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ===
true;
@@ -848,9 +828,10 @@ export function createBhoteKoshiEmbeddedMedia({
if (current.exitTimer != null) globalRef.clearTimeout?.(current.exitTimer);
destroyFacebookSession(current.facebookSession);
current.youtubeSession?.destroy();
current.card?.remove?.();
const at = cards.indexOf(current);
if (at !== -1) cards.splice(at, 1);
leavingRecords.delete(current);
forgetDetached();
render();
}
const position = () => {
@@ -866,7 +847,8 @@ export function createBhoteKoshiEmbeddedMedia({
current.enterFrame = scheduleFrame(() => {
current.enterFrame = null;
if (token !== generation || record !== current) return;
current.card.classList.add('is-entering');
current.entering = true;
render();
});
}
}
@@ -888,9 +870,10 @@ export function createBhoteKoshiEmbeddedMedia({
removeRecord(current);
return;
}
current.card.classList.remove('is-entering');
current.card.classList.add('is-leaving');
current.entering = false;
current.leaving = true;
leavingRecords.add(current);
render();
current.exitTimer =
globalRef.setTimeout?.(
() => removeRecord(current),
@@ -900,11 +883,10 @@ export function createBhoteKoshiEmbeddedMedia({
function clearWarm(key = null) {
if (!warmRecord || (key && warmRecord.key !== key)) return;
if (warmRecord.facebookSession)
destroyFacebookSession(warmRecord.facebookSession);
else warmRecord.iframe?.remove?.();
const facebookSession = warmRecord.facebookSession;
warmRecord = null;
forgetDetached();
if (facebookSession) destroyFacebookSession(facebookSession);
else render();
}
function takeWarmFacebook(key, host) {
@@ -944,29 +926,26 @@ export function createBhoteKoshiEmbeddedMedia({
warmRecord = { key, facebookSession };
return true;
}
const iframe = documentRef.createElement('iframe');
iframe.className = 'bhote-embedded-media-warmup';
iframe.src = embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
});
word(iframe, 'title', () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
);
iframe.tabIndex = -1;
iframe.setAttribute('aria-hidden', 'true');
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
root.append(iframe);
warmRecord = { key, iframe };
warmRecord = {
key,
frame: {
src: embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
}),
title: () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
},
};
render();
return true;
}
async function mountX(current, token) {
word(current.status, 'textContent', () => t('LOADING X POST…'));
setStatus(current, () => t('LOADING X POST…'));
try {
const api = await xLoader(documentRef, globalRef);
if (token !== generation || record !== current) return;
@@ -986,14 +965,12 @@ export function createBhoteKoshiEmbeddedMedia({
throw new Error(
msg('The X post is unavailable or cannot be embedded.'),
);
word(current.status, 'textContent', () =>
t('X POST · PROVIDER CONTROLS'),
);
setStatus(current, () => t('X POST · PROVIDER CONTROLS'));
position();
} catch (error) {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(String(error?.message || msg('X embed unavailable'))),
}),
@@ -1010,16 +987,14 @@ export function createBhoteKoshiEmbeddedMedia({
session.shouldPlay = autoplay === true;
session.onReady = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('FACEBOOK · PROVIDER CONTROLS'),
);
current.card.classList.remove('is-unavailable');
current.status = () => t('FACEBOOK · PROVIDER CONTROLS');
setUnavailable(current, false);
position();
};
session.onError = (error) => {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(
String(error?.message || msg('Facebook embed unavailable')),
@@ -1030,9 +1005,7 @@ export function createBhoteKoshiEmbeddedMedia({
};
session.onPlaybackBlocked = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
);
setStatus(current, () => t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'));
};
if (session.ready) session.onReady();
else if (session.error) session.onError(session.error);
@@ -1078,104 +1051,69 @@ export function createBhoteKoshiEmbeddedMedia({
if (warmRecord && warmRecord.key !== warmKey) clearWarm();
hide({ preserveWarm: true });
const token = ++generation;
const card = documentRef.createElement('section');
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
card.dataset.provider = source.provider;
word(card, 'aria-label', () =>
t('Embedded {provider} media for {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
const leader = documentRef.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);
leader.classList.add('bhote-embedded-callout-leader');
leader.setAttribute('aria-hidden', 'true');
leader.innerHTML =
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
const player = documentRef.createElement('div');
player.className = 'bhote-embedded-callout-player ui-scroll';
const footer = documentRef.createElement('footer');
const title = documentRef.createElement('strong');
word(title, 'textContent', () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
);
const status = documentRef.createElement('small');
status.setAttribute('role', 'status');
word(status, 'textContent', () =>
t('{provider} · EMBEDDED SOURCE', {
provider: providerLabel(source.provider),
}),
);
const link = documentRef.createElement('a');
link.href = source.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
record = {
const providerName = () => providerLabel(source.provider);
const sourceName = () =>
observation?.title
? bhoteEventText(observation.title)
: t('witness source');
const current = {
id: ++_cardSequence,
key,
source,
anchor,
card,
leader,
player,
status,
portrait: isPortraitMedia(media),
entering: false,
leaving: false,
unavailable: false,
label: () =>
t('Embedded {provider} media for {source}', {
provider: providerName(),
source: sourceName(),
}),
title: () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
status: () =>
t('{provider} · EMBEDDED SOURCE', { provider: providerName() }),
frame: null,
frameElement: null,
card: null,
leader: null,
player: null,
entered: false,
};
if (source.provider === 'x') {
void mountX(record, token);
} else if (source.provider === 'facebook') {
bindFacebook(record, token, warmKey, autoplay);
} else {
const iframe = documentRef.createElement('iframe');
iframe.src = embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
});
const controlled =
// The elements the card's view draws: placed after each frame, filled by
// the provider.
current.bind = (name, element) => {
if (element) current[name] = element;
};
let controlled = false;
if (source.provider === 'youtube') {
const url = new URL(
embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
}),
);
controlled =
autoplay &&
Number.isFinite(Number(endAtSec)) &&
Number(endAtSec) > startAtSec;
if (controlled) {
const url = new URL(iframe.src);
url.searchParams.set('enablejsapi', '1');
if (globalRef.location?.origin)
url.searchParams.set('origin', globalRef.location.origin);
iframe.src = url.href;
}
word(iframe, 'title', () =>
t('{provider} media: {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
iframe.allow =
'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
iframe.addEventListener?.(
'load',
() => {
current.frame = {
src: url.href,
title: () =>
t('{provider} media: {source}', {
provider: providerName(),
source: sourceName(),
}),
onLoad: () => {
if (token !== generation || record?.key !== key) return;
clearWarm(warmKey);
if (
@@ -1184,38 +1122,41 @@ export function createBhoteKoshiEmbeddedMedia({
record.youtubeSession.getState().phase,
)
) {
word(status, 'textContent', () =>
t('{provider} · PROVIDER CONTROLS', {
provider: providerLabel(source.provider),
}),
setStatus(current, () =>
t('{provider} · PROVIDER CONTROLS', { provider: providerName() }),
);
}
position();
},
{ once: true },
);
player.append(iframe);
if (controlled) {
const current = record;
current.youtubeSession = createTrimmedYouTubePlayback({
iframe,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
word(status, 'textContent', () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
};
}
record = current;
cards.push(current);
render();
if (source.provider === 'x') {
void mountX(current, token);
} else if (source.provider === 'facebook') {
bindFacebook(current, token, warmKey, autoplay);
} else if (controlled) {
current.youtubeSession = createTrimmedYouTubePlayback({
iframe: current.frameElement,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
setStatus(current, () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
position();
return true;
@@ -1223,11 +1164,12 @@ export function createBhoteKoshiEmbeddedMedia({
function destroy() {
offLocale();
worded.clear();
hide({ immediate: true });
for (const current of [...leavingRecords]) removeRecord(current);
clearWarm();
removePostRender?.();
destroyed = true;
renderVue(null, root);
root.remove();
}
+171 -68
View File
@@ -1,3 +1,4 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
@@ -12,6 +13,31 @@ import {
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
// The cards draw provider frames; the tests never load their pages, and the
// page's note that each one is not loaded is dropped.
window.happyDOM.settings.disableIframePageLoading = true;
const consoleError = console.error;
console.error = (error, ...rest) => {
if (!/Iframe page loading is disabled/.test(String(error?.message)))
consoleError(error, ...rest);
};
/**
* Embedded media in a fresh globe container of the page, and the overlay
* root it renders into.
*/
function domFixture(options = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const media = createBhoteKoshiEmbeddedMedia({
viewer: { container },
documentRef: document,
globalRef: {},
...options,
});
return { media, container, root: container.firstElementChild };
}
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
const media = createBhoteKoshiEmbeddedMedia({
@@ -186,31 +212,138 @@ test('trimmed YouTube teardown revokes pending SDK and player callbacks', async
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const { media, container, root } = domFixture();
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
const card = root.querySelector('section');
const frame = card.querySelector('iframe');
assert.ok(card.isConnected);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
assert.equal(card.isConnected, false);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(root.querySelector('section'), null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
assert.notEqual(root.querySelector('section iframe'), frame);
media.destroy();
assert.equal(container.children.length, 0);
});
test('a card draws its provider, source, status and original link, and words them again in a new locale', async () => {
const { setLocale } = await import('../i18n/index.js');
const { media, root } = domFixture();
assert.equal(media.show({
observation: { title: 'Flood footage', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k', orientation: 'portrait' } },
anchor: {},
}), true);
const card = root.querySelector('section');
assert.equal(card.className, 'bhote-embedded-callout is-youtube is-portrait');
assert.equal(card.dataset.provider, 'youtube');
assert.equal(card.getAttribute('aria-label'), 'Embedded YOUTUBE media for Flood footage');
const leader = card.firstElementChild;
assert.equal(leader.namespaceURI, 'http://www.w3.org/2000/svg');
assert.equal(leader.getAttribute('class'), 'bhote-embedded-callout-leader');
assert.equal(leader.getAttribute('aria-hidden'), 'true');
assert.equal(leader.querySelector('path').getAttribute('pathLength'), '1');
assert.equal(leader.querySelector('circle').getAttribute('r'), '4');
const body = card.querySelector('.bhote-embedded-callout-body');
assert.equal(body.getAttribute('data-overlay-input'), '');
const player = body.firstElementChild;
assert.equal(player.className, 'bhote-embedded-callout-player ui-scroll');
const frame = player.firstElementChild;
assert.equal(frame.tagName, 'IFRAME');
assert.equal(new URL(frame.src).pathname, '/embed/DbqRexFxv3k');
assert.equal(frame.title, 'YOUTUBE media: Flood footage');
assert.equal(frame.getAttribute('allow'), 'autoplay; encrypted-media; picture-in-picture; fullscreen');
assert.equal(frame.hasAttribute('allowfullscreen'), true);
assert.equal(frame.getAttribute('referrerpolicy'), 'strict-origin-when-cross-origin');
const [title, status, link] = body.querySelector('footer').children;
assert.equal(title.tagName, 'STRONG');
assert.equal(title.textContent, 'FLOOD FOOTAGE');
assert.equal(status.getAttribute('role'), 'status');
assert.equal(status.textContent, 'YOUTUBE · EMBEDDED SOURCE');
assert.equal(link.href, 'https://www.youtube.com/watch?v=DbqRexFxv3k');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(link.textContent, 'OPEN ORIGINAL ↗');
frame.dispatchEvent(new Event('load'));
assert.equal(status.textContent, 'YOUTUBE · PROVIDER CONTROLS');
try {
await setLocale('es');
assert.notEqual(link.textContent, 'OPEN ORIGINAL ↗', 'the link is worded again');
assert.notEqual(status.textContent, 'YOUTUBE · PROVIDER CONTROLS', 'the status is worded again');
assert.ok(root.querySelector('section') === card, 'in place');
} finally {
await setLocale('en');
}
media.destroy();
});
test('an X post is built by the provider inside the card and its failure marks the card', async () => {
let fail = false;
const { media, root } = domFixture({
xLoader: async () => ({ widgets: { createTweet: async (id, target) => {
if (fail) return null;
target.append(Object.assign(document.createElement('div'), { className: 'twitter-tweet', textContent: id }));
return {};
} } }),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://x.com/Indowatchosint/status/2092640554568007958' } };
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const status = card.querySelector('[role="status"]');
assert.equal(status.textContent, 'LOADING X POST…');
await new Promise((resolve) => setTimeout(resolve));
assert.equal(card.querySelector('.bhote-embedded-callout-player .twitter-tweet').textContent, '2092640554568007958');
assert.equal(status.textContent, 'X POST · PROVIDER CONTROLS');
assert.equal(card.classList.contains('is-unavailable'), false);
media.hide({ immediate: true });
fail = true;
assert.equal(media.show({ observation, anchor: {} }), true);
await new Promise((resolve) => setTimeout(resolve));
const failed = root.querySelector('section');
assert.ok(failed.classList.contains('is-unavailable'));
assert.equal(failed.querySelector('[role="status"]').textContent, 'The X post is unavailable or cannot be embedded. OPEN ORIGINAL.');
media.destroy();
});
test('a warmed Facebook player moves into the card and stays through its redraws', async () => {
let ready;
const { media, root } = domFixture({
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() {} },
XFBML: { parse() {} },
}),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://www.facebook.com/reel/1571491657757829' } };
media.warm({ observation });
await Promise.resolve(); await Promise.resolve();
const host = root.querySelector('.bhote-embedded-media-warmup');
const embed = host.querySelector('.fb-video');
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const player = card.querySelector('.bhote-embedded-callout-player');
assert.ok(host.parentNode === player, 'the warmed player is carried over, not rebuilt');
assert.equal(host.className, 'bhote-facebook-player-host');
assert.equal(host.hasAttribute('aria-hidden'), false);
ready({ type: 'video', id: embed.id, instance: { mute() {}, play() {}, pause() {} } });
assert.equal(card.querySelector('[role="status"]').textContent, 'FACEBOOK · PROVIDER CONTROLS');
assert.ok(host.parentNode === player, 'a redraw keeps the provider player');
media.destroy();
});
test('a leaving card animates out and is removed after its exit', () => {
const timers = [];
const { media, root } = domFixture({ globalRef: { setTimeout: (fn) => timers.push(fn), clearTimeout() {} } });
media.show({ observation: { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {} });
const card = root.querySelector('section');
card.hidden = false;
media.hide();
assert.ok(card.isConnected);
assert.ok(card.classList.contains('is-leaving'));
assert.equal(card.classList.contains('is-entering'), false);
timers.forEach((fn) => fn());
assert.equal(card.isConnected, false);
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
@@ -303,28 +436,8 @@ test('Mailung playback stops at source timestamp 0:07 without changing other cli
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
const { media, root } = domFixture(options);
return { media, root };
}
for (const operation of ['pause', 'hide', 'destroy']) {
@@ -343,16 +456,18 @@ test('camera updates retain a preload until the visible player loads', () => {
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
assert.equal(frame.className, 'bhote-embedded-media-warmup');
assert.equal(frame.getAttribute('aria-hidden'), 'true');
assert.equal(frame.tabIndex, -1);
assert.equal(frame.title, 'Preloading YOUTUBE media');
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.ok(root.children[0] === frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
assert.ok(frame.parentNode === root, 'keep the preload while the visible player starts');
root.querySelector('section .bhote-embedded-callout-body > .bhote-embedded-callout-player > iframe')
.dispatchEvent(new Event('load'));
assert.equal(frame.isConnected, false, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
@@ -420,25 +535,9 @@ test('a media card stays between the panels when right-to-left swaps their sides
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
const container = document.body.appendChild(document.createElement('div'));
const viewer = { container, canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
@@ -454,14 +553,18 @@ test('a shown card follows its anchor through the renderer ports', () => {
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef: document, globalRef: {} });
const root = container.firstElementChild;
root.getBoundingClientRect = () => ({ left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
const card = root.querySelector('section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// The leader runs from the anchor to the card's near edge.
assert.equal(card.querySelector('path').getAttribute('d'), `M ${300 + 10 - 352} ${200 + 5 - parseFloat(card.style.top)} L 0 ${Math.max(16, Math.min(360 - 16, 200 + 5 - parseFloat(card.style.top)))}`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
+3 -2
View File
@@ -989,9 +989,10 @@ function createPanelRecords(event) {
textContent: t('▶ PLAY SCENE'),
hidden: true,
}),
// `pressed` is the button's pressed state; the view renders it as one.
cinematicButton: panelRecord({
textContent: t('◉ CINEMATIC'),
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: panelRecord({ textContent: t('↺ FULL STORY') }),
corridorButton: panelRecord(),
@@ -2860,7 +2861,7 @@ export function createBhoteKoshiEventLayer({
'textContent',
_cinematicActive ? t('■ RELEASE CAMERA') : t('◉ CINEMATIC'),
);
setElementAttribute(button, 'aria-pressed', String(_cinematicActive));
setElementProperty(button, 'pressed', _cinematicActive);
return true;
}
+4
View File
@@ -101,6 +101,7 @@ function eventPanel() {
get textContent() { return record().textContent; },
get hidden() { return record().hidden; },
get disabled() { return record().disabled; },
get pressed() { return record().pressed; },
get value() { return typed ?? record().value; },
set value(value) { typed = value; },
getAttribute: (name) => record().attributes[name] ?? null,
@@ -2711,6 +2712,8 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
play.dispatch('click');
assert.equal(layer.getCinematicState().active, true);
assert.equal(layer.getPlaybackState().progress, 0);
const cinematicControl = panel.querySelector('[data-action="cinematic"]');
assert.equal(cinematicControl.pressed, true, 'the cinematic button is pressed while it owns the camera');
assert.equal(layer.getPlaybackState().playing, true);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
@@ -2720,6 +2723,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
panel.querySelector('[data-action="cinematic"]').dispatch('click');
assert.equal(layer.getCinematicState().active, false);
assert.equal(viewer._test.cameraTransforms.length, 2);
assert.equal(cinematicControl.pressed, false, 'releasing the camera unpresses the button');
animationCallbacks[1](91001);
assert.equal(play.textContent, '↺ REPLAY');
const cameraLookCount = viewer._test.cameraLooks.length;
+8 -1
View File
@@ -38,7 +38,7 @@ function presentation(patch = {}) {
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
cinematicButton: record({
textContent: '◉ CINEMATIC',
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
corridorButton: record(),
@@ -156,6 +156,10 @@ test('a later presentation updates the controls in place', async (t) => {
disabled: true,
attributes: { 'aria-label': 'Play Global context' },
});
next.refs.cinematicButton = record({
textContent: '■ RELEASE CAMERA',
pressed: true,
});
next.refs.progressInput = record({ value: '250', hidden: true });
next.refs.imagerySection = record({ hidden: true });
store.publish(next);
@@ -164,6 +168,9 @@ test('a later presentation updates the controls in place', async (t) => {
assert.equal(play.textContent, '▶ PLAY SHOT');
assert.equal(play.disabled, true);
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
const cinematic = $('[data-action="cinematic"]');
assert.equal(cinematic.getAttribute('aria-pressed'), 'true');
assert.equal(cinematic.textContent, '■ RELEASE CAMERA');
assert.ok(
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
);
+1 -1
View File
@@ -1,4 +1,4 @@
import { toRadians } from '../geo/index.js';
import { toRadians } from '../geo/vector.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
+15 -1
View File
@@ -85,7 +85,9 @@ import {
} from '../cctvFocusRequest.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
IDLE_CAMERA_ICON,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
@@ -353,7 +355,7 @@ 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', () => {
test('camera icons are violet for video feeds, green for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
// Every catalog record is placed as it is made, and drawn there.
@@ -385,6 +387,18 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
const image = (record) => icons.item(record.camera.id).image;
const idleImage = image(idleStill);
assert.equal(idleImage, IDLE_CAMERA_ICON);
assert.equal(image(activeVideo), CAMERA_ICON);
assert.equal(image(idleVideo), CAMERA_ICON);
idleStill.camera.feedType = 'hls';
refreshCoverageStyles();
assert.equal(image(idleStill), CAMERA_ICON);
idleStill.camera.feedType = 'image';
refreshCoverageStyles();
assert.equal(image(idleStill), idleImage);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
+2
View File
@@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000;
const RETRY_MAX_MS = 5 * 60 * 1000;
export const CCTV_OVERLAY_SOURCE_ID = 'cctv';
/** The source a CCTV count marker takes clicks as. */
export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count';
export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
fullEnd: CCTV_CARD_SCALE_FULL_M,
midEnd: CCTV_CARD_SCALE_MID_M,
+238
View File
@@ -0,0 +1,238 @@
import { fromDegrees } from '../geo/ellipsoid.js';
/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */
export function formatCameraCount(count) {
if (count < 1000) return String(count);
const thousands =
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
return `${thousands}K`;
}
/** An empty cell and its on-screen picker candidate. */
export function createCameraCell(key) {
return {
key,
count: 0,
latSum: 0,
lonSum: 0,
heightSum: 0,
south: Infinity,
north: -Infinity,
west: Infinity,
east: -Infinity,
low: Infinity,
high: -Infinity,
winner: null,
rank: Infinity,
};
}
/** Accumulate one horizon-visible mount in its ground cell. */
export function addCellCamera(cell, camera) {
const { lat, lon, absoluteHeightM: height = 0 } = camera;
cell.count++;
// Integer sums make the mean independent of catalog order, to about a centimetre.
cell.latSum += Math.round(lat * 1e7);
cell.lonSum += Math.round(lon * 1e7);
cell.heightSum += Math.round(height * 100);
cell.south = Math.min(cell.south, lat);
cell.north = Math.max(cell.north, lat);
cell.west = Math.min(cell.west, lon);
cell.east = Math.max(cell.east, lon);
cell.low = Math.min(cell.low, height);
cell.high = Math.max(cell.high, height);
}
const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180;
/** Mean longitude and latitude of a cell's mounts, in degrees. */
export function cellLonLat(cell) {
return {
lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)),
lat: cell.latSum / (1e7 * cell.count),
};
}
/**
* Geographic mean of the mounts. Its height is the drawn ground under it
* when the cell carries one (`groundM`), since a camera nobody has looked at
* yet may still hold a catalog height far from the terrain; otherwise the
* mean mount height.
*/
export function cellCenter(cell) {
const { lon, lat } = cellLonLat(cell);
return fromDegrees(
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
/** Half the east-west and north-south ground extent of a cell's mounts, in metres. */
export function cellHalfExtents(cell) {
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
return {
halfWidthM: 0.5 * (cell.east - cell.west) * 111_320 * Math.cos(parallel),
halfHeightM: 0.5 * (cell.north - cell.south) * 111_320,
};
}
/** A padded sphere over the rectangle and every mount, centred at groundM
* when set, otherwise at the mid mount height. */
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = wrapLongitude((cell.east + cell.west) / 2);
const height = Number.isFinite(cell.groundM)
? cell.groundM
: (cell.high + cell.low) / 2;
const { halfWidthM, halfHeightM } = cellHalfExtents(cell);
const halfWidth = Math.hypot(halfWidthM, halfHeightM);
const vertical = Math.max(cell.high - height, height - cell.low);
const radius = 1.2 * Math.hypot(halfWidth, vertical);
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
}
/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */
function addCell(target, cell) {
// Across the antimeridian a cell joins on the side of the group's mean.
const shift = target.count
? 360 *
Math.round(
(target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9,
)
: 0;
target.count += cell.count;
target.latSum += cell.latSum;
target.lonSum += cell.lonSum + shift * 1e7 * cell.count;
target.heightSum += cell.heightSum;
target.south = Math.min(target.south, cell.south);
target.north = Math.max(target.north, cell.north);
target.west = Math.min(target.west, cell.west + shift);
target.east = Math.max(target.east, cell.east + shift);
target.low = Math.min(target.low, cell.low);
target.high = Math.max(target.high, cell.high);
}
/** Visit the touching pills in this marker's bucket and its eight neighbors. */
function visitNeighbors(marker, grid, gap, visit) {
for (let col = -1; col <= 1; col++) {
for (let row = -1; row <= 1; row++) {
const bucket = grid.get(`${marker.col + col},${marker.row + row}`);
if (!bucket) continue;
for (const other of bucket) {
// Distance between the horizontal centre segments of the two pills.
const extra = marker.halfSegment + other.halfSegment;
const dx = Math.max(0, Math.abs(marker.x - other.x) - extra);
const dy = marker.y - other.y;
const reach = marker.radius + other.radius + gap;
if (dx * dx + dy * dy >= reach * reach) continue;
visit(other, dx * dx + dy * dy, reach);
}
}
}
}
/**
* Merge connected groups of overlapping horizontal pills. Each marker occupies
* one grid bucket. Even the widest pill can only touch its eight neighbors.
* A cell with one camera takes the footprint `sizeFor(1)` gives its icon and
* joins the nearest count it touches. Lone cameras never join each other
* or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways.
* A merged group lists its ground cells in `parts`.
* Ground cells stay intact for the camera picker and individual-icon pass.
*/
export function mergeCountCells(cells, project, sizeFor, gap) {
let columnWidth = 0;
let rowHeight = 0;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
const { width, height } = sizeFor(cell.count, cell);
columnWidth = Math.max(columnWidth, width + gap);
rowHeight = Math.max(rowHeight, height + gap);
// The view projector reuses its result object.
return {
cell,
x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined,
y: screen?.y,
halfSegment: (width - height) / 2,
radius: height / 2,
};
});
const grid = new Map();
for (const marker of markers) {
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
marker.col = Math.floor(marker.x / columnWidth);
marker.row = Math.floor(marker.y / rowHeight);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
if (marker.cell.count > 1) marker.bucket.add(marker);
}
for (const marker of markers) {
if (marker.cell.count !== 1 || !marker.bucket) continue;
let best = Infinity;
visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => {
const clearance = Math.sqrt(distanceSquared) - reach;
if (clearance < best) {
best = clearance;
marker.nearest = other;
}
});
}
// Only counts were candidates for nearest. Now they can claim lone cameras.
for (const marker of markers)
if (marker.cell.count === 1) marker.bucket?.add(marker);
const members = [];
for (const seed of markers) {
if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue;
members.length = 0;
members.push(seed);
for (const marker of members) {
if (marker.cell.count === 1) continue;
visitNeighbors(marker, grid, gap, (other) => {
if (other.cell.count === 1 && other.nearest !== marker) return;
other.bucket.delete(other);
members.push(other);
});
}
if (members.length === 1) {
seed.result = seed.cell;
} else {
const group = createCameraCell(seed.cell.key);
group.lone = [];
group.parts = [];
for (const { cell } of members) {
addCell(group, cell);
group.parts.push(...(cell.parts ?? [cell]));
if (cell.count === 1) group.lone.push(cell);
else if (cell.lone) group.lone.push(...cell.lone);
}
seed.result = group;
}
}
const groups = [];
for (const marker of markers) {
if (marker.result) groups.push(marker.result);
else if (!marker.bucket || marker.bucket.has(marker))
groups.push(marker.cell);
}
return groups;
}
/** Rebuild a group's count under its original key, keeping only the lone cameras in `keep`. */
export function withoutLoneCameras(group, keep = []) {
const counts = (group.parts ?? []).filter((cell) => cell.count > 1);
if (!counts.length) return null;
const core = createCameraCell(group.key);
core.parts = [...counts, ...keep];
if (keep.length) core.lone = [...keep];
for (const cell of core.parts) addCell(core, cell);
return core;
}
+216
View File
@@ -0,0 +1,216 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fromDegrees } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import { getLocale, setLocale } from '../i18n/index.js';
import {
createCameraCell,
addCellCamera,
cellCenter,
cellBounds,
formatCameraCount,
mergeCountCells,
} from './cctvCellCounts.js';
test('camera counts use Latin digits and K notation whatever the UI language', () => {
const previous = getLocale();
const examples = [
[2, '2'],
[999, '999'],
[1000, '1K'],
[1150, '1.2K'],
[1687, '1.7K'],
[9960, '10K'],
[10000, '10K'],
[12345, '12K'],
[12500, '13K'],
[1000000, '1000K'],
];
try {
setLocale('ar');
for (const [count, label] of examples)
assert.equal(formatCameraCount(count), label);
} finally {
setLocale(previous);
}
});
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
const cameras = [
{ lon: 12, lat: 52, absoluteHeightM: 30 },
{ lon: 12, lat: 52, absoluteHeightM: 40 },
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
];
const cell = createCameraCell();
for (const camera of cameras) addCellCamera(cell, camera);
const expected = fromDegrees(12.001, 52.002, 40);
assert.ok(distance(cellCenter(cell), expected) < 0.001);
const bounds = cellBounds(cell);
for (const { lon, lat, absoluteHeightM } of cameras) {
assert.ok(
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
bounds.radius,
);
}
});
function mergeCounts(sizes, counts, positions) {
const cells = counts.map((count, i) => ({
...createCameraCell(String(i)),
count,
}));
let i = 0;
const groups = mergeCountCells(
cells,
() => positions[i++],
(count) => sizes[count],
4,
);
return { cells, groups };
}
test('stadiums merge by their own radii and segment lengths across grid boundaries', () => {
const sizes = {
2: { width: 28, height: 28 },
7350: { width: 80, height: 48 },
};
const check = (counts, positions, expected) => {
const { groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
assert.equal(
groups.reduce((sum, cell) => sum + cell.count, 0),
counts[0] + counts[1],
);
};
const origin = { x: 35, y: 37 };
// Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear.
check([2, 7350], [origin, { x: 35, y: 78 }], [7352]);
check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]);
// The large pill's centre segment extends 16 pixels towards the circle.
check([7350, 2], [origin, { x: 92, y: 37 }], [7352]);
check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]);
check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]);
// Large pills can reach across a row boundary at their full diameter.
check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]);
});
test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => {
const sizes = {
1: { width: 24, height: 24 },
9: { width: 40, height: 40 },
};
const check = (counts, positions, expected) => {
const { cells, groups } = mergeCounts(sizes, counts, positions);
assert.deepEqual(
groups.map((cell) => cell.count),
expected,
);
// A lone camera that stays apart is still its own cell object.
assert.deepEqual(
groups.filter((cell) => cell.count === 1),
cells.filter((cell) => groups.includes(cell) && cell.count === 1),
);
};
const at = (x, y = 100) => ({ x, y });
// Radii 20 and 12: the four-pixel gap is clear at 36 pixels.
check([9, 1], [at(100), at(135)], [10]);
check([9, 1], [at(100), at(136)], [9, 1]);
check([1, 9], [at(135), at(100)], [10]);
// Overlapping icons with no count beside them stay two icons.
check([1, 1], [at(100), at(110)], [1, 1]);
// A count takes every lone camera it touches, on either side.
check([1, 9, 1], [at(70), at(100), at(130)], [11]);
// A lone camera that only touches another lone camera is left alone.
check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]);
});
test('cells merged across the antimeridian stay at the antimeridian', () => {
for (const lon of [179.9, 179.99, 179.999]) {
for (const reversed of [false, true]) {
const east = createCameraCell('e');
const west = createCameraCell('w');
for (let i = 0; i < 2; i++) {
addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 });
addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 });
}
const cells = reversed ? [west, east] : [east, west];
const screens = [
{ x: 100, y: 100 },
{ x: 120, y: 100 },
];
let i = 0;
const [group, ...rest] = mergeCountCells(
cells,
() => screens[i++],
() => ({ width: 40, height: 40 }),
4,
);
assert.equal(rest.length, 0);
assert.equal(group.count, 4);
const expected = fromDegrees(180, 0, 0);
assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`);
const bounds = cellBounds(group);
assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`);
for (const l of [lon, -lon])
assert.ok(
distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius,
);
}
}
});
test('flight bounds on drawn ground still contain every mount', () => {
// Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m.
const flat = createCameraCell('k');
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 });
flat.groundM = 0;
const fb = cellBounds(flat);
assert.ok(
distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius,
'flat',
);
// Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them.
const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180));
const ravine = createCameraCell('r');
addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 });
addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 });
ravine.groundM = 0;
const rb = cellBounds(ravine);
for (const lon of [10, east])
assert.ok(
distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius,
'ravine',
);
});
test('a lone camera between two counts joins one of them and does not merge them', () => {
const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } };
const run = (counts, xs) =>
mergeCounts(
sizes,
counts,
xs.map((x) => ({ x, y: 100 })),
)
.groups.map((cell) => cell.count)
.sort((a, b) => a - b);
assert.deepEqual(run([9, 9], [70, 130]), [9, 9]);
for (const [counts, xs] of [
[
[9, 1, 9],
[70, 100, 130],
],
[
[1, 9, 9],
[100, 70, 130],
],
[
[9, 9, 1],
[70, 130, 100],
],
])
assert.deepEqual(run(counts, xs), [9, 10], String(counts));
});
+155 -54
View File
@@ -12,6 +12,14 @@ import {
parseTarkteeDatexLocations,
} from '../../server/providers/cctv/sources.js';
/**
* Disarm the 30 s deadline, so a loader that only stops at that deadline
* fails at the test timeout instead of passing late.
*/
function withoutDeadline(t) {
t.mock.method(AbortSignal, 'timeout', () => new AbortController().signal);
}
/** Silence the loaders' progress and failure logging. */
function quiet(t) {
t.mock.method(console, 'log', () => {});
@@ -97,6 +105,29 @@ test('Tarktee DATEX image parser rejects non-official hosts', () => {
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"?>
@@ -168,46 +199,6 @@ test('Tarktee loader refuses a redirect and cancels both response bodies', async
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(), []);
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;
@@ -264,25 +255,135 @@ test('Tarktee loader cancels the sibling body when one feed fails or overflows t
);
});
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', () => {});
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`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(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;
// A late transport answers once the sibling is aborted, or on release.
if (lateSibling)
await Promise.race([
gate,
new Promise((resolve) =>
init.signal.addEventListener('abort', resolve, { once: true }),
),
]);
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`,
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(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(
String(url).includes('roadCameraLocations')
? SAMPLE_LOCATIONS_XML
: SAMPLE_IMAGES_XML,
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));
},
}),
),
);
const cameras = await loadTarkteeSourcesFromDatex();
assert.deepEqual(timeouts, [30_000, 30_000]);
assert.equal(cameras.length, 1);
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',
{ timeout: 2000 },
async (t) => {
quiet(t);
withoutDeadline(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);
},
);
+112
View File
@@ -0,0 +1,112 @@
// A body-phase failure of one Tarktee DATEX feed must abort the sibling that is
// still waiting for headers instead of leaving it until the 30 s deadline.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import {
TARKTEE_IMAGES_URL,
TARKTEE_LOCATIONS_URL,
TARKTEE_MAX_CATALOG_BYTES,
} from '../../server/providers/cctv/constants.js';
import { loadTarkteeSourcesFromDatex } from '../../server/providers/cctv/sources.js';
/** The sibling sends its headers this late; the loader must not wait for it. */
const SIBLING_HEADER_DELAY_MS = 2000;
/** Generous bound for "at once" on a loaded CI machine. */
const FAIL_FAST_MS = 1000;
function startServer(handlers) {
const server = http.createServer((req, res) => handlers[req.url](req, res));
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => resolve(server));
});
}
/** Send the two DATEX URLs to the local server through the real fetch. */
function routeFetchTo(t, port) {
const realFetch = globalThis.fetch;
t.mock.method(globalThis, 'fetch', (url, init) => {
const path =
String(url) === TARKTEE_LOCATIONS_URL
? '/loc'
: String(url) === TARKTEE_IMAGES_URL
? '/img'
: null;
assert.ok(path, `unexpected url ${url}`);
return realFetch(`http://127.0.0.1:${port}${path}`, init);
});
}
/** The sibling answers late and reports whether it was cut off before headers. */
function slowSibling() {
const arrived = Promise.withResolvers();
const closed = Promise.withResolvers();
return {
arrived: arrived.promise,
closed: closed.promise,
handler(req, res) {
arrived.resolve();
const timer = setTimeout(() => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.end('<d2LogicalModel/>');
}, SIBLING_HEADER_DELAY_MS);
res.on('close', () => {
clearTimeout(timer);
closed.resolve({ beforeHeaders: !res.headersSent });
});
},
};
}
const failingBodies = {
'declares a body over the byte cap': (req, res) => {
res.writeHead(200, {
'content-type': 'application/xml',
'content-length': String(TARKTEE_MAX_CATALOG_BYTES + 1),
});
res.write('<d2LogicalModel>');
},
'resets the connection mid-body': (req, res) => {
res.writeHead(200, { 'content-type': 'application/xml' });
res.write('<d2LogicalModel><payloadPublication>');
setTimeout(() => res.socket.destroy(), 20);
},
};
for (const [label, failingFeed] of Object.entries(failingBodies)) {
for (const [failing, pending] of [
['/loc', '/img'],
['/img', '/loc'],
]) {
test(`Tarktee aborts ${pending} pending headers when ${failing} ${label}`, { timeout: 10_000 }, async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const sibling = slowSibling();
const server = await startServer({
[failing]: (req, res) =>
sibling.arrived.then(() => failingFeed(req, res)),
[pending]: sibling.handler,
});
t.after(() => {
server.closeAllConnections();
server.close();
});
routeFetchTo(t, server.address().port);
const started = Date.now();
const cameras = await loadTarkteeSourcesFromDatex();
const elapsed = Date.now() - started;
assert.deepEqual(cameras, []);
assert.ok(
elapsed < FAIL_FAST_MS,
`loader waited ${elapsed} ms for the sibling's headers instead of aborting it`,
);
assert.deepEqual(
await sibling.closed,
{ beforeHeaders: true },
`${pending} was not aborted`,
);
});
}
}
@@ -0,0 +1,138 @@
// An explicit pick of the camera that a settled move just re-opened must end
// the opening pick. That pick goes through setActiveCamera's UNCHANGED path
// (same camera, already activated); if that path keeps the provisional flag,
// the next settled move (a pan, or the landing of NEAREST's own flight)
// switches the camera away from the one the user chose.
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import cctvLayer, {
_setCctvCoverageStateForTest,
_setCctvOverlayHostForTest,
reopenNearestCamera,
} from './cctv.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
const BASE = {
headingDeg: 41,
pitchDeg: -5,
fovDeg: 56,
rangeM: 210,
mountHeightM: 100,
groundElevationM: 0,
city: 'London',
};
function record(id, lat, lon) {
return {
camera: { ...BASE, id, name: `Camera ${id}`, lat, lon },
coverageEntities: [],
projection: null,
activationDone: true,
groundResolved: {},
groundSamples: {},
groundPrior: 0,
frustumGeometry: null,
frustumPositions: null,
probeClampRangeM: null,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 100),
};
}
function viewerAt(lat, lon) {
const viewer = {
isDestroyed: () => false,
eye: { lat, lon, height: 300 },
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
primitives: { add: (p) => p, remove: () => true },
requestRender() {},
},
};
// The layer reads the eye and flies through the renderer's camera port.
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...viewer.eye }),
on: () => () => {},
followed: null,
flyToBounds() {},
},
}).draw;
return viewer;
}
function moveViewer(viewer, lat, lon) {
viewer.eye = { lat, lon, height: 300 };
}
function withReopenedLayer(fn) {
_setCctvOverlayHostForTest({
setEntries() {},
setVisible() {},
clearSource() {},
});
// Activation builds the projection canvas and frame image.
const originalDocument = globalThis.document;
const originalImage = globalThis.Image;
globalThis.document = { createElement: () => ({ getContext: () => null }) };
globalThis.Image = class {};
try {
const trafalgar = record('a-trafalgar', 51.508, -0.128);
const cambridge = record('b-cambridge', 51.513, -0.129);
// enable() assigned the opening camera without activating it.
trafalgar.activationDone = false;
const viewer = viewerAt(51.5081, -0.1281);
_setCctvCoverageStateForTest({
viewer,
records: [trafalgar, cambridge],
activeCameraId: 'a-trafalgar',
enabled: true,
openingCameraProvisional: true,
});
// A settled move next to Cambridge Circus re-opens there, still as the
// opening pick.
moveViewer(viewer, 51.5131, -0.1291);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
fn(viewer);
} finally {
globalThis.document = originalDocument;
globalThis.Image = originalImage;
_setCctvOverlayHostForTest();
_setCctvCoverageStateForTest({ enabled: false });
}
}
for (const [name, pick] of [
['NEAREST (focusNearest)', () => cctvLayer.focusNearest({ focus: false })],
['selectCamera', () => cctvLayer.selectCamera('b-cambridge')],
[
'setParams({ selectedCameraId })',
() => cctvLayer.setParams({ selectedCameraId: 'b-cambridge' }),
],
[
'focusNearestToPoint',
() => cctvLayer.focusNearestToPoint(51.513, -0.129, { focus: false }),
],
]) {
test(`an explicit ${name} pick of the re-opened camera ends the opening pick`, () => {
withReopenedLayer((viewer) => {
pick();
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
// A later settled move (a pan, or the landing of the pick's own flight)
// leaves the explicit choice alone.
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), false);
assert.equal(cctvLayer.getUIState().activeCameraId, 'b-cambridge');
});
});
}
test('without a pick, the next settled move still follows the view', () => {
withReopenedLayer((viewer) => {
moveViewer(viewer, 51.5081, -0.1281);
assert.equal(reopenNearestCamera(), true);
assert.equal(cctvLayer.getUIState().activeCameraId, 'a-trafalgar');
});
});
+20 -17
View File
@@ -140,25 +140,28 @@ for (const [label, flag] of [
});
}
test('a failed catalog cancels the sibling request instead of waiting for the timeout', async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) {
return new Response('', { status: 503 });
}
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
for (const [failure, camerasResponse] of [
['failed', () => new Response('', { status: 503 })],
['malformed', () => new Response('<html>error page</html>')],
]) {
test(`a ${failure} catalog cancels the sibling request instead of waiting for the timeout`, async (t) => {
t.mock.method(console, 'warn', () => {});
let siblingSignal;
t.mock.method(globalThis, 'fetch', async (url, options) => {
if (url === LITHUANIA_CAMERAS_URL) return camerasResponse();
siblingSignal = options.signal;
// Never settles on its own; only an abort ends it.
return new Promise((_, reject) => {
options.signal.addEventListener('abort', () =>
reject(options.signal.reason),
);
});
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
assert.deepEqual(await loadLithuaniaSources(), []);
assert.equal(siblingSignal?.aborted, true);
assert.notEqual(siblingSignal.reason?.name, 'TimeoutError');
});
}
test('a redirected catalog is reported as not followed', async (t) => {
const warnings = [];
+103 -2
View File
@@ -111,6 +111,7 @@ function mount(t, respond) {
austin: process.env.CCTV_FORCE_AUSTIN,
serverKey: process.env.GOOGLE_MAPS_SERVER_API_KEY,
browserKey: process.env.GOOGLE_MAPS_API_KEY,
rateLimit: process.env.GEV_RATELIMIT_GOOGLE_PER_MIN,
};
process.env.CCTV_SOURCES_JSON = JSON.stringify([
STILL,
@@ -125,6 +126,8 @@ function mount(t, respond) {
// than a network call this file does not model.
delete process.env.GOOGLE_MAPS_SERVER_API_KEY;
delete process.env.GOOGLE_MAPS_API_KEY;
// The default Google budget, whatever the shell sets.
delete process.env.GEV_RATELIMIT_GOOGLE_PER_MIN;
const nativeFetch = globalThis.fetch;
const requests = [];
globalThis.fetch = async (url, init = {}) => {
@@ -139,6 +142,7 @@ function mount(t, respond) {
['CCTV_FORCE_AUSTIN', before.austin],
['GOOGLE_MAPS_SERVER_API_KEY', before.serverKey],
['GOOGLE_MAPS_API_KEY', before.browserKey],
['GEV_RATELIMIT_GOOGLE_PER_MIN', before.rateLimit],
]) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
@@ -155,9 +159,9 @@ function mount(t, respond) {
});
assert.ok(handler, 'the CCTV provider must mount a middleware');
const call = async (path, headers = {}) => {
const call = async (path, headers = {}, socket) => {
const { res, done } = recordingResponse();
await handler({ url: path, headers, method: 'GET', on() {} }, res);
await handler({ url: path, headers, method: 'GET', on() {}, socket }, res);
await done;
return res;
};
@@ -528,3 +532,100 @@ test('a forwarded same-origin request reaches every CCTV route but not the Stree
assert.equal(direct.body, 'street-view');
assert.equal(streetViewCalls(), 1);
});
test('the Street View fallback frames catalog cameras only, from the catalog position', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
const streetView = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
);
const unknown = await app.call('/frame/not-a-camera?lat=48.85&lon=2.29');
assert.equal(unknown.headers['X-CCTV-Source'], 'synthetic');
assert.deepEqual(streetView(), [], 'no Google call for an unknown id');
const steered = await app.call(
`/frame/${STILL.id}?lat=48.85&lon=2.29&heading=90&fov=74&pitch=-17`,
);
assert.equal(steered.headers['X-CCTV-Source'], 'streetview');
const sv = new URL(streetView()[0].url).searchParams;
assert.equal(sv.get('location'), `${STILL.lat},${STILL.lon}`);
assert.equal(sv.get('heading'), '90');
assert.equal(sv.get('fov'), '74');
assert.equal(sv.get('pitch'), '-17');
});
test('the Street View fallback spends a per-IP Google budget, and only with a key', async (t) => {
const app = mount(t, ({ url }) =>
url.startsWith('https://maps.googleapis.com/')
? trackedUpstream({
headers: { 'content-type': 'image/jpeg' },
body: 'street-view',
}).response
: upstreamResponse({ status: 503 }),
);
// Read when the first keyed fallback builds the limiter, so after mount().
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '2';
const streetViewCalls = () =>
app.requests.filter(({ url }) =>
url.startsWith('https://maps.googleapis.com/'),
).length;
const first = { remoteAddress: '203.0.113.7' };
const frameSource = async (socket) =>
(await app.call(`/frame/${STILL.id}`, {}, socket)).headers['X-CCTV-Source'];
// Without a key nothing is spent.
for (let i = 0; i < 3; i++)
assert.equal(await frameSource(first), 'synthetic');
assert.equal(streetViewCalls(), 0);
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
// Neither an unknown id nor a forwarded request spends the window.
assert.equal(
(await app.call('/frame/not-a-camera', {}, first)).headers['X-CCTV-Source'],
'synthetic',
);
assert.equal(
(
await app.call(
`/frame/${STILL.id}`,
{ 'x-forwarded-for': '203.0.113.9' },
first,
)
).headers['X-CCTV-Source'],
'synthetic',
);
assert.deepEqual(
[
await frameSource(first),
await frameSource(first),
await frameSource(first),
],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(streetViewCalls(), 2, 'no Google call over the budget');
// Another address has a budget of its own.
assert.equal(
await frameSource({ remoteAddress: '203.0.113.8' }),
'streetview',
);
assert.equal(streetViewCalls(), 3);
// Addresses within one IPv6 /64 share a budget.
const v6 = (remoteAddress) => frameSource({ remoteAddress });
assert.deepEqual(
[await v6('2001:db8::1'), await v6('2001:db8::2'), await v6('2001:db8::3')],
['streetview', 'streetview', 'synthetic'],
);
assert.equal(await v6('2001:db8:0:1::1'), 'streetview', 'another /64');
assert.equal(streetViewCalls(), 6);
});
@@ -0,0 +1,87 @@
// Real sockets: a client that closes its connection while the camera upstream
// is still pending must not get a Street View call outside its own budget.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { cctvProxy } from '../../server/providers/cctv.js';
const CAM = {
id: 'still-fixture',
name: 'Still fixture',
lat: 30.27,
lon: -97.74,
feedType: 'image',
url: 'https://cams.upstream.invalid/still.jpg',
};
test('a client that disconnects mid-fetch stays inside its own Street View budget', async (t) => {
const saved = { ...process.env };
process.env.CCTV_SOURCES_JSON = JSON.stringify([CAM]);
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
process.env.CCTV_FORCE_AUSTIN = '0';
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
delete process.env.GOOGLE_MAPS_API_KEY;
process.env.GEV_RATELIMIT_GOOGLE_PER_MIN = '1';
const nativeFetch = globalThis.fetch;
let streetViewCalls = 0;
globalThis.fetch = async (url) => {
if (String(url).startsWith('https://maps.googleapis.com/')) {
streetViewCalls += 1;
return new Response('street-view', {
headers: { 'content-type': 'image/jpeg' },
});
}
await new Promise((r) => setTimeout(r, 400));
return new Response(null, { status: 503 });
};
let handler;
cctvProxy().configureServer({
middlewares: { use: (_r, fn) => (handler = fn) },
});
const server = http.createServer((req, res) => {
req.url = req.url.replace(/^\/api\/cctv/, '');
handler(req, res, () => res.end());
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => {
server.close();
globalThis.fetch = nativeFetch;
for (const k of Object.keys(process.env))
if (!(k in saved)) delete process.env[k];
Object.assign(process.env, saved);
});
const { port } = server.address();
const get = (abortAfterMs) =>
new Promise((resolve) => {
const req = http.get(
{
host: '127.0.0.1',
port,
path: `/api/cctv/frame/${CAM.id}`,
headers: { host: `localhost:${port}` },
agent: false,
},
(res) => {
res.resume();
res.on('end', () => resolve(res.headers['x-cctv-source']));
},
);
req.on('error', () => resolve('aborted'));
if (abortAfterMs)
setTimeout(() => {
req.destroy();
resolve('aborted');
}, abortAfterMs);
});
assert.equal(await get(), 'streetview');
assert.equal(await get(), 'synthetic', 'the cap of one is spent');
assert.equal(streetViewCalls, 1);
await get(50);
await new Promise((r) => setTimeout(r, 800));
assert.equal(
streetViewCalls,
1,
'an aborted request spent the key outside its own budget',
);
});
+254
View File
@@ -0,0 +1,254 @@
import { afterEach, beforeEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
refreshHorizonCulling,
} from './cctv.js';
const WIDTH = 800;
const HEIGHT = 600;
const bindings = [];
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
measureText: (text) => ({
width: text.length * 8,
actualBoundingBoxAscent: 4,
actualBoundingBoxDescent: 4,
}),
}),
}),
};
});
afterEach(() => {
delete globalThis.document;
for (const unbind of bindings.splice(0)) unbind();
});
function recordsAt(lonLats, height = 10) {
return lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
return {
camera: {
id: `cam-${String(index).padStart(4, '0')}`,
name: `Camera ${index}`,
city: 'Test',
lat,
lon,
headingDeg: 0,
pitchDeg: -18,
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
absoluteHeightM: height,
},
position: { x: position.x, y: position.y, z: position.z },
groundSamples: {},
groundResolved: {},
coverageEntities: [],
projection: null,
};
});
}
const plain = ({ x, y, z }) => ({ x, y, z });
function lookingAt(eye, target, ports = {}) {
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
return {
viewer: viewerWithAxes(eye, direction, right, up, ports),
direction,
right,
up,
};
}
function topDown(height, ports = {}) {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, height);
return viewerWithAxes(
eye,
{ x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 0, y: 0, z: 1 },
ports,
);
}
function viewerWithAxes(eye, direction, right, up, ports) {
const carto = Cesium.Cartographic.fromCartesian(eye);
const { port } = fakeCameraPort({
pose: {
lon: Cesium.Math.toDegrees(carto.longitude),
lat: Cesium.Math.toDegrees(carto.latitude),
height: carto.height,
position: plain(eye),
direction: plain(direction),
up: plain(up),
right: plain(right),
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
draw: fakeDrawPort(),
...ports,
}),
);
return viewer;
}
/** Pinhole projection, as the layer's projector. */
function project(view, eye, point) {
const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3());
const z = Cesium.Cartesian3.dot(d, view.direction);
const t = Math.tan(Math.PI / 6);
const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT));
const y = Cesium.Cartesian3.dot(d, view.up) / z / t;
return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z };
}
for (const [label, horizontalM, aboveM] of [
['100 m approach', 100, 4],
['800 m approach', 800, 50],
]) {
test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => {
const ground = 1872;
const records = recordsAt([
[0, 0],
[0, 0],
]);
// geoid fallback after a 429
for (const r of records)
r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' };
const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8);
const eye = Cesium.Cartesian3.fromDegrees(
0,
-horizontalM / 111_320,
ground + 8 + aboveM,
);
const reads = [];
const view = lookingAt(eye, mount, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return ground;
},
},
});
_setCctvCoverageStateForTest({ viewer: view.viewer, records });
const stale = project(view, eye, records[0].position);
const truth = project(view, eye, mount);
assert.ok(stale.y > HEIGHT * 2);
assert.ok(truth.y > 0 && truth.y < HEIGHT);
refreshHorizonCulling();
refreshHorizonCulling();
assert.equal(records[0].groundPrior.ellipsoid, ground);
assert.ok(reads.length > 0, 'the stale camera was never read');
});
}
test('cameras off the visible screen cannot spend the whole terrain read budget', () => {
// 300 cameras with no prior around the screen edge, tiles not loaded; the
// 301st at the screen centre over a loaded tile.
const lonLats = [];
for (let i = 0; i < 300; i++) {
const a = (i / 300) * 2 * Math.PI;
// ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide)
lonLats.push([
(Math.cos(a) * 250) / 111_320,
(Math.sin(a) * 190) / 111_320,
]);
}
lonLats.push([0, 0]);
const records = recordsAt(lonLats);
const perPass = [];
let reads;
const viewer = topDown(200, {
globe: { isGlobeVisible: () => true },
query: {
sampleHeightNow(point) {
reads.push(point);
return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9
? 40
: null;
},
},
});
_setCctvCoverageStateForTest({ viewer, records });
for (let pass = 0; pass < 3; pass++) {
reads = [];
refreshHorizonCulling();
perPass.push(reads.length);
}
const last = records.at(-1);
assert.equal(last.groundPrior?.ellipsoid, 40);
assert.ok(perPass.every((n) => n <= 300));
});
test("the active camera's icon moves beside a count that would cover it", () => {
const records = recordsAt([
[0, 0],
[0, 0],
[0, 0],
]);
const viewer = topDown(20_000);
_setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const [marker] = cctvLayer._cctvDrawnForTest().counts.markers;
const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990;
const apartPx =
Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) /
metresPerPixel;
assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon');
});
test('a lone camera just inside the grouping threshold joins the count beside it', () => {
const h = 740;
// mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10
const records = recordsAt([
[0, 235 / 111_320],
[0, 255 / 111_320],
[0, 255 / 111_320],
]);
for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' };
const viewer = topDown(h + 10);
_setCctvCoverageStateForTest({ viewer, records });
refreshHorizonCulling();
const icons = _cctvIconsForTest();
const markers = cctvLayer._cctvDrawnForTest().counts.markers;
assert.deepEqual(
markers.map((marker) => marker.cell.count),
[3],
);
assert.equal(
icons.item('cam-0000').show,
false,
'the near singleton still draws beside the count',
);
});
File diff suppressed because it is too large. Load diff
+27 -3
View File
@@ -166,6 +166,30 @@ export const DATA_CREDITS = [
'(<a href="https://celestrak.org" target="_blank" rel="noopener">celestrak.org</a>), ' +
'Dr. T.S. Kelso',
},
{
key: 'nasa-iss-model',
html:
'ISS model: ' +
'<a href="https://science.nasa.gov/3d-resources/international-space-station-iss-d-igoal/" target="_blank" rel="noopener">NASA 3D Resources</a> (JSC IGOAL)',
},
{
key: 'tiangong-model',
html:
"Tiangong model: made for God's Eye View; dimensions from " +
'<a href="https://doi.org/10.34133/space.0035" target="_blank" rel="noopener">Wang, Zhang &amp; Wang 2023</a> ' +
'(CC BY 4.0) and eoPortal',
},
{
key: 'nasa-iss-telemetry',
html: 'ISS joint telemetry (where switched on): NASA ISSLive, via Lightstreamer',
},
{
key: 'nasa-iss-live',
html:
'ISS live video (LIVE section): NASA, via YouTube ' +
'(<a href="https://www.youtube.com/watch?v=ROboUHfPUrU" target="_blank" rel="noopener">exterior cameras</a>, ' +
'<a href="https://www.youtube.com/watch?v=M3HKLzjvKPc" target="_blank" rel="noopener">live video and audio</a>)',
},
{
key: 'ucs-satellite-database',
html:
@@ -303,9 +327,9 @@ export const DATA_CREDITS = [
key: 'ontario-511-cctv',
html:
'CCTV cameras &amp; 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>) ' +
'· provided as is, without warranty; actual road conditions may differ',
'<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',
+12
View File
@@ -173,6 +173,18 @@ test('the NYC camera credit carries NYC DOT’s requested disclaimer', () => {
assert.match(credit.html, /observe posted signage/);
});
test('the Ontario 511 camera credit carries the licence attribution statement', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'ontario-511-cctv');
assert.ok(credit, 'Ontario 511 camera frames must be credited');
assert.ok(
credit.html.includes(
'Contains information licensed under the <a href="https://www.ontario.ca/page/open-government-licence-ontario"',
),
);
assert.match(credit.html, />Open Government Licence – Ontario<\/a>/);
assert.match(credit.html, /Provided as is, without warranty/);
});
test("the Houston camera credit names TranStar's terms and the permission they require", () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'houston-cctv');
assert.ok(credit, 'Houston TranStar camera frames must be credited');
+1 -1
View File
@@ -32,7 +32,7 @@ export function createInfrastructureLayers(services) {
name: 'Dams',
color: '#0088ff', // Blue
icon: '▰',
source: 'USACE',
source: 'OpenStreetMap / OpenInfraMap',
osmDerived: true,
labels: true,
labelMax: 900,
+79 -2
View File
@@ -6,6 +6,7 @@ import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { parseGeojsonLines } from '../sources/infrastructureData.js';
function services() {
const records = new Map();
@@ -34,6 +35,20 @@ function services() {
};
}
// Added from the OSM API, not the OpenInfraMap extract: [id, name, OSM
// object, version]. Both must stay polygons: the Dams layer skips
// LineStrings.
const OSM_API_DAMS = [
[262532166, 'Acaray', 'way/262532166', 7],
[-5671745, 'Represa Yacyretá-Apipé', 'relation/5671745', 2],
];
const DAMS = parseGeojsonLines(
readFileSync(
new URL('./local_data/dams/dams.geojsonl', import.meta.url),
'utf8',
),
);
test('package exports import without an application, DOM, fetch, or timers', () => {
const result = spawnSync(
process.execPath,
@@ -66,7 +81,11 @@ test('infrastructure factory preserves identity and creates independent state wi
first.map(({ id, name, source }) => ({ id, name, source })),
[
{ id: 'local-datacenters', name: 'Datacenters', source: 'Local' },
{ id: 'local-dams', name: 'Dams', source: 'USACE' },
{
id: 'local-dams',
name: 'Dams',
source: 'OpenStreetMap / OpenInfraMap',
},
],
);
first.forEach((layer, index) => {
@@ -84,7 +103,7 @@ test('infrastructure factory preserves identity and creates independent state wi
test('dataset URLs still name the complete bundled sources', () => {
for (const [file, count] of [
['datacenters', 4352],
['dams', 704],
['dams', 706],
]) {
const lines = readFileSync(
new URL(`./local_data/${file}/${file}.geojsonl`, import.meta.url),
@@ -96,6 +115,64 @@ test('dataset URLs still name the complete bundled sources', () => {
}
});
test('Acaray and Yacyretá appear once each with OSM provenance', () => {
for (const [id, name, object, version] of OSM_API_DAMS) {
const matches = DAMS.filter((feature) => feature.id === id);
assert.equal(matches.length, 1);
const { properties } = matches[0];
assert.equal(properties.name, name);
assert.equal(properties.osm_id, id);
assert.equal(properties.source_version, version);
assert.equal(
properties.source_url,
`https://www.openstreetmap.org/${object}`,
);
assert.equal(properties.retrieved_at, '2026-10-15');
}
});
test('Acaray and Yacyretá each get a stem, a selection context and an analyst record', async (t) => {
const added = DAMS.filter((feature) =>
OSM_API_DAMS.some(([id]) => id === feature.id),
);
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
text: async () =>
added.map((feature) => JSON.stringify(feature)).join('\n'),
}));
const host = services();
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
name: 'Dams',
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
},
host,
);
const viewer = {
scene: { screenSpaceCameraController: { enableInputs: true } },
};
const fake = bindFakeGroundRenderer(viewer);
fakeInput(viewer);
t.after(() => layer.destroy(viewer));
await layer.enable(viewer);
const names = OSM_API_DAMS.map(([, name]) => name).sort();
assert.equal(fake.set('stems').items.size, 2, 'both dams get a stem');
assert.deepEqual(
[...host.records.values()].map((record) => record.label).sort(),
names,
);
assert.deepEqual(
layer
.getAnalystRecords()
.map((record) => record.name)
.sort(),
names,
);
});
test('two viewers use their supplied contexts and dispose independently', async (t) => {
t.mock.method(globalThis, 'fetch', async () => ({
ok: true,
+43
View File
@@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a
]);
coordinator.destroy();
});
test('start layers turn on when nothing names any, and are never written as the user choice', async () => {
const storage = memoryStorage();
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage,
});
const results = await coordinator.start({
allowLocalState: false,
startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'],
});
assert.equal(coordinator.source, 'start');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [
'earthquakes',
'traffic',
]);
assert.equal(manager.isEnabled('earthquakes'), true);
assert.equal(manager.isEnabled('traffic'), true);
assert.equal(
results.every((result) => result.persistenceWrite === false),
true,
);
assert.deepEqual(storage.writes, []);
coordinator.destroy();
});
test('a shared layer payload wins over start layers', async () => {
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage: memoryStorage(),
});
const shared = createDefaultLayerState();
shared.enabledLayerIds = ['radio'];
await coordinator.start({
shareLayerState: shared,
allowLocalState: false,
startLayerIds: ['earthquakes'],
});
assert.equal(coordinator.source, 'share');
assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']);
assert.equal(manager.isEnabled('earthquakes'), false);
coordinator.destroy();
});
+8 -1
View File
@@ -103,6 +103,7 @@ export class LayerStateCoordinator {
shareLayerState = null,
allowLocalState = true,
shareCreatedAtMs = null,
startLayerIds = [],
} = {}) {
if (this._destroyed)
throw new Error('Layer-state coordinator is destroyed');
@@ -125,7 +126,13 @@ export class LayerStateCoordinator {
selected = this._normalize(stored);
this._source = 'local';
}
} else {
}
if (!selected && startLayerIds.length) {
// The layers the application starts with when nothing names any:
// restored passively, so they are never written as the user's choice.
selected = this._normalize({ enabledLayerIds: startLayerIds });
this._source = 'start';
} else if (!selected && !allowLocalState) {
// A valid historical camera/style share with no v2 layer payload keeps
// the exact legacy default-layer behavior. It must not inherit an
// unrelated recipient's saved local layer preferences.
+83
View File
@@ -0,0 +1,83 @@
import { msg } from '../i18n/marker.js';
/**
* Live streams the app can show for a selected object: a fixed list, each
* entry a broadcast on a platform's own player (YouTube today), attached to
* the subjects it shows by key. Any layer can name its selected subject's
* keys (`getLiveSubjectKeys`), and the LIVE section in Context offers the
* streams that match; the satellites layer names the ISS as `station:iss`
* whichever of the station's catalog entries is selected.
*
* These are broadcasts in the platform's embedded player, not camera feeds:
* the CCTV layer is for those. A stream's id changes when its broadcaster
* restarts it, so each entry is one line to update.
*/
/** Where YouTube's embedded player is served from: the privacy-enhanced host. */
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
/** @typedef {{id: string, platform: 'youtube', videoId: string, title: string,
* owner: string, ownerUrl: string, subjects: readonly string[],
* note: string}} LiveStream */
/** @type {readonly LiveStream[]} */
export const LIVE_STREAMS = Object.freeze([
Object.freeze({
id: 'iss-exterior',
platform: 'youtube',
videoId: 'ROboUHfPUrU',
title: msg('Exterior cameras'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
Object.freeze({
id: 'iss-crew',
platform: 'youtube',
videoId: 'M3HKLzjvKPc',
title: msg('Live video and space-to-ground audio'),
owner: 'NASA',
ownerUrl: 'https://www.youtube.com/@NASA',
subjects: Object.freeze(['station:iss']),
note: msg('NASA video, via YouTube'),
}),
]);
/**
* The streams attached to any of `subjectKeys`, in list order.
* @param {Iterable<string>|null|undefined} subjectKeys
* @param {readonly LiveStream[]} [streams]
* @returns {LiveStream[]}
*/
export function liveStreamsFor(subjectKeys, streams = LIVE_STREAMS) {
const keys = new Set(subjectKeys ?? []);
if (!keys.size) return [];
return streams.filter((stream) =>
stream.subjects.some((subject) => keys.has(subject)),
);
}
/** The video's own page, for the "Open on YouTube" link. */
export function youtubeWatchUrl(videoId) {
return `https://www.youtube.com/watch?v=${encodeURIComponent(videoId)}`;
}
/**
* The parameters the live player is created with: starts on creation (the
* player is built only when the viewer presses Play), muted so the browser
* lets it start once the player API has loaded, inline on phones, no related
* videos, and the page's origin so the player API may be spoken to.
* @param {string} origin The page's origin.
* @returns {Record<string, string|number>}
*/
export function youtubeLivePlayerVars(origin) {
return {
autoplay: 1,
mute: 1,
playsinline: 1,
rel: 0,
enablejsapi: 1,
...(origin ? { origin } : {}),
};
}
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff. Show more