mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-05 02:44:02 +00:00
Merge remote-tracking branch 'origin/main' into HEAD
This commit is contained in:
commit
3748e9c23a
85 files changed
+3409
-195
No files matched your search
@@ -21,3 +21,6 @@ qa-artifacts/
|
||||
3d-models/
|
||||
pinokio/ENVIRONMENT
|
||||
pinokio/.installed
|
||||
|
||||
# Transient: a release interrupted mid-assembly (npm run changelog recovers it)
|
||||
changelog.d/.assembling/
|
||||
+5
-21
@@ -1,26 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
- Local FM seek finds stations after wrapping around 87.5–108 MHz, covers both
|
||||
band edges, skips the starting station and rejects spectra from an earlier
|
||||
tune (Aditya, @Rohilalala, #1174).
|
||||
- Local RTL-SDR keeps USB reads queued in order and bounds pending decoder
|
||||
work. A stalled or overloaded decoder stops with an explicit error; stopping
|
||||
terminates its worker and rejects late audio. FM playback buffers short
|
||||
scheduling gaps, caps its audio queue at 256 ms, and reduces display updates
|
||||
and spectrum calculations while listening.
|
||||
|
||||
- Add Bogotá (Tembici, 250 stations) and Santiago de Chile (Bike Itaú, 200
|
||||
stations) to the GBFS bikeshare registry, the layer's first stations in
|
||||
Colombia and Chile. Both are PBSC feeds like the Brazilian Bike Itaú cities,
|
||||
so no proxy change is needed. Both feeds also list depot stations on other
|
||||
continents (São Paulo, Madrid) as in service; stations outside a city's load
|
||||
radius are now dropped instead of drawn as live docks.
|
||||
|
||||
- Add Barcelona's bike share to the GBFS registry: Bicing (543 stations, the
|
||||
city's PBSC system) and AMBici (237 e-bike stations across the metropolitan
|
||||
area, run by nextbike). Both are keyless GBFS 2.3 feeds listed in
|
||||
MobilityData's systems catalogue; AMBici's is CC0. `gbfs.nextbike.net` joins
|
||||
the proxy allowlist. These are the layer's first stations in Spain.
|
||||
- The tracked-aircraft descriptor now publishes `verticalRateMps`, on both the
|
||||
civil and military layers, so a consumer reading `getTrackedInfo()` no longer
|
||||
has to reach past it into the raw poll record for climb/descent. Reported,
|
||||
never derived: an aircraft that has not transmitted a rate reads as `null`
|
||||
rather than a level-flight `0`.
|
||||
|
||||
- Add nine Ontario transit feeds: TTC, MiWay, Hamilton HSR, Durham Region,
|
||||
YRT/Viva, Guelph, Burlington, Barrie and Kingston, each carrying its own
|
||||
|
||||
+1
-1
@@ -150,7 +150,7 @@ ownership and adoption process.
|
||||
|
||||
1. Branch off `main`.
|
||||
2. Keep `npm run build`, `npm test`, and `npm run test:track` green and avoid new console errors, plus the [feature gate](#feature-regression-gates) for the area you touched.
|
||||
3. If you change runtime behavior, update `docs/CURRENT-STATE.md` and `CHANGELOG.md` in the same PR.
|
||||
3. If you change runtime behavior, update `docs/CURRENT-STATE.md` in the same PR, and add your changelog entry as `changelog.d/<pr-number>-<slug>.md` instead of editing `CHANGELOG.md` — see [changelog.d/README.md](changelog.d/README.md). Distinct filenames don't conflict; a release assembles the directory into `CHANGELOG.md`. A documentation claim that needs a regression test should assert against `docs/CURRENT-STATE.md` or `README.md`, which a PR still edits directly.
|
||||
4. If you add or change a data source, update [DATA_SOURCES.md](DATA_SOURCES.md) with its license and attribution. **Don't add data you don't have the right to redistribute** — fetch it at runtime instead.
|
||||
5. Describe what you changed and how you verified it (screenshots welcome for anything visual).
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ Start with the included data sources, then add your own. Each layer is a separat
|
||||
- **🔭 Satellite passes:** Ask by voice when any loaded satellite next rises over you: rise, peak and set times, and whether you can see it.
|
||||
- **🔎 Analyst answers:** Count, filter and rank satellites, datacenters and dams by voice, alongside flights, ships, fires and quakes; answers say when a feed is stale or on a fallback.
|
||||
- **🧭 Tilt and North Up:** Switch between straight-down and a 35° oblique, or put north at the top, while a tracked target stays centered.
|
||||
- **🔍 Keyless search:** Type coordinates or a bundled city or landmark to fly there with no network request; other names use Google when configured, then Photon and Nominatim.
|
||||
- **🔍 Keyless search:** Type decimal coordinates, a two-dimensional WGS84 `geo:` URI (for example, `geo:39.7392,-104.9903`), or a bundled city or landmark to fly there with no geocoder request; other names use Google when configured, then Photon and Nominatim.
|
||||
- **📦 Shareable scenes:** Import, preview and share Director scenes as files or bundles, with camera anchors, authored moves and data packs.
|
||||
- **🌊 Nepal flood scene:** Replay the Bhote Koshi flood: flood path, witness sources and before-and-after imagery (bundled data is non-commercial; see [DATA_SOURCES.md](DATA_SOURCES.md)).
|
||||
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ The data proxies under `server/providers/` are written so the browser cannot tur
|
||||
- **Sanitized errors** — internal error details are not echoed back to clients.
|
||||
- **Coalesced OAuth refresh** and cached successful responses only (OpenSky).
|
||||
- **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing.
|
||||
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control.
|
||||
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, and `/api/tomtom/*`, backed by its persistent daily tile budget) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control.
|
||||
- **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements.
|
||||
|
||||
Allowing `maps.googleapis.com` in `script-src` also trusts its JSONP endpoints, which can bypass the script allowlist if an HTML-injection bug exists; this is an accepted limitation of loading the Maps JavaScript API, alongside the existing `'unsafe-eval'` allowance.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
- On Windows, `npm run doctor` and the Pinokio install no longer print Node's
|
||||
DEP0190 warning ("Passing args to a child process with shell option true can
|
||||
lead to security vulnerabilities"): npm.cmd's fixed subcommand is now part of
|
||||
the shell command string instead of an argument array (quanticsoul4772, #1057).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Location search accepts two-dimensional WGS84 `geo:` URIs offline, with
|
||||
the existing coordinate framing and label. Unsupported URI fields are passed
|
||||
to the remaining search providers unchanged (cj-vana, #1071).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Military aircraft keep their last heading and speed when an adsb.lol row omits
|
||||
`track` or `gs`, instead of turning north and stopping; a grounded row without
|
||||
a speed still reads 0 (Aditya, @Rohilalala, #1096).
|
||||
@@ -0,0 +1,5 @@
|
||||
- Overpass data whose element tags contain a failure phrase ("timed out",
|
||||
"runtime error", "too many requests" and similar, e.g. a place named "Timed
|
||||
Out Escape Rooms") is returned as data instead of being refused and putting
|
||||
the endpoint on cooldown; upstream failures are read from the remark (Aditya,
|
||||
@Rohilalala, #1097).
|
||||
@@ -0,0 +1,5 @@
|
||||
- A failed Esri Satellite or keyless terrain load still shows OSM or flat terrain
|
||||
at once, but no longer lasts the whole session: while the fallback is on
|
||||
screen, the real provider is retried in the background (30 seconds, doubling
|
||||
to a 10-minute cap) and replaces it live once it loads. Map switches never
|
||||
wait for a retry (Aditya, @Rohilalala, #1111).
|
||||
@@ -0,0 +1,2 @@
|
||||
- Exclude aircraft without a reported altitude from requested altitude bands;
|
||||
unfiltered aircraft queries still retain them (rudycelekli, #1115).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Release superseded Google Street View open waits and suppress metadata
|
||||
requests whose viewer was unmounted while the service loaded (rudycelekli,
|
||||
#1117).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Label camera-tool Street View fallbacks as historical Google imagery rather
|
||||
than the current camera view; keep unknown frame provenance explicit
|
||||
(rudycelekli, #1118).
|
||||
@@ -0,0 +1,5 @@
|
||||
- Scenes keep the "Scene not saved" status when a capture, update, append or
|
||||
import cannot be saved, and an unreadable saved project no longer overwrites
|
||||
the recovery checkpoint. `startScene()` resolves to its documented result,
|
||||
`afterShotId` works without an explicit scene, and `scenesRun` counts the
|
||||
distinct scenes queued (djabhi31, #1135).
|
||||
@@ -0,0 +1,6 @@
|
||||
- Fire-perimeter queries handle outlines and holes crossing the antimeridian:
|
||||
areas enclosed near ±180° are included, areas at the opposite meridian are
|
||||
excluded, and returned perimeter coordinates stay near the dateline. Incident
|
||||
cards use the same circular longitude mean and compare multipart outline
|
||||
areas along short longitude edges, keeping the card on the largest polygon
|
||||
(Arianna Method, @ariannamethod, #1142).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Director shot actions land on the requested shot. A seek to a shot's start
|
||||
could round a hair below it and select the end of the previous shot for some
|
||||
shot counts and durations (Aditya, @Rohilalala, #1171).
|
||||
@@ -0,0 +1,13 @@
|
||||
- Keep missing CCTV numbers unknown instead of reading them as zero. `Number`
|
||||
turns null, blank strings and booleans into 0 or 1, and the camera source
|
||||
list sends an unknown number as JSON null, so a source-pack camera that left
|
||||
out its pose reached the browser as zeros clamped to each field's floor —
|
||||
facing north, pitch −2°, FOV 20°, range 120 m, mount 6 m and ground 0 m —
|
||||
instead of the defaults (id-hash heading, −17°, 74°, 700 m, 24 m and the
|
||||
city's ground); a null or blank position placed the camera at 0,0. The
|
||||
server's `toFiniteNumber` and the browser's `safeNumber` now treat absent,
|
||||
blank and boolean values as missing. The same conversion also stops a
|
||||
Tallinn row with a null heading reading as a confident north-facing camera,
|
||||
a Caltrans camera with a blank elevation losing its 150 m ground prior, and
|
||||
a TfL or Catalonia camera with a null or blank coordinate being kept at 0,0
|
||||
or on the zero meridian (omerbberk, #1172).
|
||||
@@ -0,0 +1,10 @@
|
||||
- Flights' ground floor works across the antimeridian. The viewer-distance
|
||||
check behind the 150 km floor radius and its copy in the photoreal mesh-floor
|
||||
sampler subtracted longitudes without wrapping, so two points 21 km apart
|
||||
across 180° measured about 38,000 km and low or grounded aircraft just across
|
||||
the line from the viewer were never floored. A contact's display corridor
|
||||
walked a segment across 180° the long way round, spending its cell budget on
|
||||
ground behind the contact, and a contact on the seam lost its cell hysteresis.
|
||||
SEARCH NEARBY SITES on a view across 180° searched Google Places around
|
||||
longitude 0, on the far side of the globe, with a radius sized from the view's
|
||||
height alone; it now searches the view (Aditya, @Rohilalala, #1173).
|
||||
@@ -0,0 +1,7 @@
|
||||
- Changelog entries are now one file per pull request. A change adds
|
||||
`changelog.d/<pull request>-<slug>.md` instead of editing the top of
|
||||
`CHANGELOG.md`, which two pull requests in flight could not share — it was the
|
||||
most frequent merge conflict in the open queue, and for six of them the only
|
||||
one. `npm run changelog` splices the directory into `CHANGELOG.md` at release
|
||||
time and empties it; `npm run changelog:check` reports the batch and changes
|
||||
nothing. Fragment text is copied through unchanged (daikaginza, #787).
|
||||
@@ -0,0 +1,3 @@
|
||||
- Recent Imagery: opening DETAILS scrolls its card into view when it opens below
|
||||
the fold. The panel used to restore the previous scroll position right after
|
||||
the reveal, so the card stayed out of sight (Ian Blenke, #970).
|
||||
@@ -0,0 +1,4 @@
|
||||
- Cross-site browser requests can no longer spend the TomTom traffic-tile
|
||||
budget through `/api/tomtom/*`. The shared same-site gate runs before status,
|
||||
cache, and upstream work; same-origin app requests and non-browser local
|
||||
callers remain supported (Sunil56224972, #973).
|
||||
@@ -0,0 +1,52 @@
|
||||
# Changelog fragments
|
||||
|
||||
One file per entry. A pull request adds a file here instead of editing
|
||||
`CHANGELOG.md`, and a release concatenates them into it.
|
||||
|
||||
```
|
||||
changelog.d/<pull request number>-<slug>.md
|
||||
```
|
||||
|
||||
`723-atc-decision-layer.md`, for example. The slug is lowercase, words separated
|
||||
by `-`. Two pull requests never pick the same filename, because the pull request
|
||||
number is already unique — which is the point: new `CHANGELOG.md` entries go at
|
||||
the top of the file, so two pull requests in flight write into the same few lines
|
||||
and git has nothing to merge on.
|
||||
|
||||
Write the file exactly as the entry should read in `CHANGELOG.md`: a `-` bullet,
|
||||
wrapped the way the surrounding entries are, crediting yourself and the pull
|
||||
request.
|
||||
|
||||
```markdown
|
||||
- Report which upstream declined a Street Traffic road load. The layer row now
|
||||
reads `Overpass rate-limited` instead of a general "Road data temporarily
|
||||
unavailable" (yourname, #665).
|
||||
```
|
||||
|
||||
The text is spliced in unchanged apart from trailing whitespace, so what you
|
||||
write here is what ships. Fragments are deliberately outside
|
||||
`scripts/format-scope.json`, so `npm run format` never reflows one.
|
||||
|
||||
At release time:
|
||||
|
||||
```
|
||||
npm run changelog:check # list what would move, change nothing
|
||||
npm run changelog # move every fragment into CHANGELOG.md
|
||||
```
|
||||
|
||||
The assembler refuses a batch rather than guessing: a filename that is not
|
||||
`<pull request>-<slug>.md`, or two fragments claiming one pull request number,
|
||||
stops the run before anything is written and names the files.
|
||||
|
||||
If `npm run changelog` fails part-way (a full disk, a killed process), run it
|
||||
again. The batch is staged in `changelog.d/.assembling/` and only lands when the
|
||||
assembled file replaces `CHANGELOG.md` in a single rename, so the rerun either
|
||||
finishes that batch or puts its fragments back first. It never adds an entry
|
||||
twice or drops one. `npm run changelog:check` names a staged batch, if one is
|
||||
left over, instead of reporting past it.
|
||||
|
||||
A documentation claim that needs a regression test — the way
|
||||
`src/annotations/drawTool.test.mjs` asserts against `CHANGELOG.md` — should
|
||||
assert against `docs/CURRENT-STATE.md` or `README.md` instead. A pull request
|
||||
still edits those directly, so the text is in the file while the change is under
|
||||
review; a fragment does not reach `CHANGELOG.md` until release.
|
||||
+78
-11
@@ -100,11 +100,26 @@ shared `area` argument (place name, bounding box, or point and radius) and cap
|
||||
lists at 25 rows by default. Voice offers the same queries next to its app
|
||||
actions: the session lists them, and the browser runs them through the same
|
||||
catalog, loaded on first use. See [tools and the MCP server](TOOLS.md).
|
||||
Aircraft altitude-band queries require a reported barometric or geometric altitude
|
||||
for each match, so a grounded contact that reports none is left out of a band too.
|
||||
Queries without an altitude band retain unknown-altitude contacts.
|
||||
|
||||
Catalog calls check their cancellation signal immediately before executing a
|
||||
tool. Already-cancelled queries do not start; cancellation after execution starts
|
||||
continues to follow the existing tool and caller behavior.
|
||||
|
||||
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
|
||||
longitudes, matching the short-edge convention used for boundary intersections.
|
||||
An outline crossing ±180° contains nearby boxes and radius areas without also
|
||||
containing their counterparts near Greenwich. Returned perimeter coordinates
|
||||
use a circular mean for longitude, including multipart outlines. Incident cards
|
||||
also use a circular longitude mean over the largest outer ring (excluding its
|
||||
repeated closing vertex). Their relative-area comparison follows short longitude
|
||||
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
|
||||
Regression coverage lives in `src/tools/area.test.mjs`,
|
||||
`src/tools/queries/environment.test.mjs` and
|
||||
`src/layers/perimeters/cards.test.mjs`.
|
||||
|
||||
## Cyber HUD — September 30, 2026
|
||||
|
||||
Display > HUD > Layout includes Cyber, also available through the HUD voice
|
||||
@@ -369,7 +384,12 @@ doubling to a 15 s cap, with every retry waiting behind one shared cooldown
|
||||
plus up to 1.5 s of jitter, and `Retry-After` extending the cooldown when the
|
||||
upstream exposes it. One console warning is logged per cooldown window. Other
|
||||
failures keep Cesium's handling and the flat `EllipsoidTerrainProvider`
|
||||
fallback. `scripts/qa-terrain-429.mjs` reproduces the burst against a keyless
|
||||
fallback; while that flat terrain is on a shown globe the map controller
|
||||
retries Re:Earth in the background (30 s, doubling to a 10-minute cap, each
|
||||
attempt abandoned after 60 s) and installs the real terrain without waiting
|
||||
for a map switch or an imagery retry. Behind a 3D tileset it neither retries
|
||||
nor installs; the next globe activation does.
|
||||
`scripts/qa-terrain-429.mjs` reproduces the burst against a keyless
|
||||
dev server, counts real throttles with their headers as evidence, synthesises
|
||||
throttles with `--inject N` when the upstream is not throttling, and fails if
|
||||
a throttled tile never loads.
|
||||
@@ -427,6 +447,8 @@ reference. Legacy projects retain their ordinary flights, content and edits.
|
||||
Seeking between ordinary camera poses uses the shortest longitude arc across the
|
||||
dateline while preserving both authored endpoint longitudes, and turns heading
|
||||
and roll the short way for any authored angles.
|
||||
A seek to a shot's start, as a shot action makes, selects that shot rather than
|
||||
the end of the previous one.
|
||||
See [camera directions](DIRECTOR-CAMERA.md).
|
||||
|
||||
Realtime voice composes separate connection, response/tool, Radio handoff, input
|
||||
@@ -525,7 +547,7 @@ are protected from fallback writes. Version 6 is the export format, with
|
||||
zero pitch, low camera heights, scope and detection edits preserved. See [the document contract](SCENE-DOCUMENT.md);
|
||||
see [Director](DIRECTOR.md) for camera, pack, action and sharing support.
|
||||
|
||||
Search framing and annotations request semantic map features from an explicit source. The Overpass adapter owns bounded queries, member/tag decoding and request deadlines; callers retain candidate ranking, outline caching, deferred retries and scene placement. Empty, unavailable, transient and throttled outcomes remain distinct. Traffic sources return road records and installation sources return mapped records with freshness/saturation metadata, so their layers no longer decode upstream elements. ALPR already normalizes its records in the source. Traffic uses OpenFreeMap roads with optional matched TomTom congestion; ALPR uses an hourly OpenStreetMap extract. Keyless installations use military-area tiles. Detailed feature queries require operator-configured Overpass.
|
||||
Search framing and annotations request semantic map features from an explicit source. The Overpass adapter owns bounded queries, member/tag decoding and request deadlines; callers retain candidate ranking, outline caching, deferred retries and scene placement. Empty, unavailable, transient and throttled outcomes remain distinct; a data reply is refused only for its `remark`, never for text in element tags. Traffic sources return road records and installation sources return mapped records with freshness/saturation metadata, so their layers no longer decode upstream elements. ALPR already normalizes its records in the source. Traffic uses OpenFreeMap roads with optional matched TomTom congestion; ALPR uses an hourly OpenStreetMap extract. Keyless installations use military-area tiles. Detailed feature queries require operator-configured Overpass.
|
||||
|
||||
Nepal media preloads survive repeated camera-flight updates, but Stop, event disable and replacement remove abandoned frames and revoke pending Facebook sessions. Fallback evidence-card clicks respect the shared drawing-tool pointer lease.
|
||||
|
||||
@@ -584,7 +606,9 @@ pinning, first-position grace, source time and sea-surface placement are unchang
|
||||
|
||||
Military flights also separate portable records and source acquisition from
|
||||
Cesium snapshot application. The metadata owner retains aviation feet, source
|
||||
fix times, sticky fields and partial-feed retention. Rendering retains ground
|
||||
fix times, sticky fields and partial-feed retention. A row without track or
|
||||
speed holds the last known value, as civil records do; a grounded row without
|
||||
speed reads 0. Rendering retains ground
|
||||
model ownership, motion history, military registration and tracking cleanup.
|
||||
|
||||
Civil flights separate source acquisition, portable record reconciliation and
|
||||
@@ -842,6 +866,13 @@ use the supplied asset resolver, including the preload path. Enrichment receives
|
||||
an abort signal and cannot update a later lifecycle after destruction. Existing
|
||||
camera, terrain floor, trail, selection and measured model-size policies remain.
|
||||
|
||||
The tracked-aircraft descriptor both flight layers hand to the cockpit carries
|
||||
`verticalRateMps` beside `velocityMps` and `track`. Civil records store the rate as
|
||||
`verticalRate` and military records as `verticalRateMps`; the query seam maps both to
|
||||
one name, so `resolveTrackedAircraftInfo` returns a single shape for either layer. The
|
||||
rate is reported, never derived: a blank poll keeps the last transmitted value and an
|
||||
absent rate stays null rather than reading as level flight.
|
||||
|
||||
## Transponder emergency highlighting
|
||||
|
||||
`src/data/aircraftEmergency.js` derives one status per poll from the Mode A
|
||||
@@ -1344,6 +1375,27 @@ outside its promise, so an unusual mirror status cannot crash the server.
|
||||
Node-only package entries expose both provider factories. Routes, payloads,
|
||||
fallback behavior and existing dev/preview hook registration are preserved;
|
||||
browser rendering is unchanged.
|
||||
The portable frame source retains the proxy's known `X-CCTV-Source` kind. Camera
|
||||
snapshot tools label Street View fallback imagery as historical and credit Google,
|
||||
while upstream frames retain their current-view label and catalog attribution.
|
||||
Synthetic placeholders are unavailable as snapshots. Injected frame sources may
|
||||
supply `sourceKind`; missing or unknown provenance keeps `current_view` null and
|
||||
does not claim the image is current. The `current_view` field distinguishes camera-feed
|
||||
provenance from historical fallback imagery; it does not measure capture time or
|
||||
image freshness.
|
||||
|
||||
## CCTV missing numeric fields
|
||||
|
||||
CCTV numbers are read as missing when they are absent, null, blank or boolean,
|
||||
on the server (`toFiniteNumber`, every pack and the file/env source packs) and
|
||||
in the browser (`safeNumber`). `/api/cctv/sources` sends an unknown number as
|
||||
JSON null; the browser then uses the bundled seed camera's value when one
|
||||
shares the id, else the field's default — id-hash heading, pitch −17°, FOV 74°
|
||||
(which a matched datasheet can still replace), range 700 m, mount 24 m, the
|
||||
city's ground elevation — rather than reading zero and clamping it to the
|
||||
field's floor. A camera with a missing latitude or longitude and no seed
|
||||
position is skipped by the browser catalog instead of being placed at 0,0.
|
||||
Real zeros, including `"0"`, are kept.
|
||||
|
||||
## Terrain, traffic, fire and bike-share provider modules
|
||||
|
||||
@@ -1353,7 +1405,10 @@ plugin order, server-key selection, validation, disk caches, budgets, retries
|
||||
and stale/error responses remain unchanged. Each has a Node-only package entry
|
||||
under `gods-eye-view/server/providers/`. Portable terrain mechanics, traffic tile
|
||||
math and GBFS source rules are available under `gods-eye-view/sources/`.
|
||||
The browser layers and their rendering remain in their existing modules.
|
||||
The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before
|
||||
status, cache or upstream work, refusing cross-site browser requests while
|
||||
preserving same-origin app requests and non-browser local callers. The browser
|
||||
layers and their rendering remain in their existing modules.
|
||||
GBFS null or empty availability counts retain an unknown value through station
|
||||
parsing and rendering; they use the neutral station color rather than reporting
|
||||
an empty dock. Explicit zero and caller-supplied numeric fallbacks remain valid.
|
||||
@@ -3201,7 +3256,11 @@ test:track` 43 tracking invariants · headless QA harnesses under
|
||||
> metres low. `qa-floor-verify.mjs` now **exits non-zero on FAIL** (1 = FAIL,
|
||||
> 2 = INCONCLUSIVE); it previously exited 0 on every verdict, which is how the
|
||||
> burial stayed invisible. It also honours `QA_BASE_URL` and puppeteer's
|
||||
> pinned Chrome-for-Testing, like the other harnesses.
|
||||
> pinned Chrome-for-Testing, like the other harnesses. The viewer-distance
|
||||
> gate, the corridor walk and cell hysteresis take the short way across 180°
|
||||
> (`src/data/approxDistance.js` is the one distance both the flights records
|
||||
> and the mesh-floor sampler use), so contacts just across the antimeridian
|
||||
> are floored like any other.
|
||||
> - **2026-07-16:** the FIRMS Active Fires layer is **LIVE** —
|
||||
> the bundled 2026-05-25 snapshot (58 MB) is deleted; a new `/api/firms` proxy
|
||||
> (vite.config.js) merges VIIRS NOAA-20/NOAA-21/Suomi-NPP NRT world CSVs
|
||||
@@ -3458,7 +3517,10 @@ controls (the address goes in the caption); a pose goes out at once and
|
||||
again when the panorama's month, photographer and address arrive (one
|
||||
successful lookup per panorama per session, seeded by the nearest lookup;
|
||||
a details lookup that fails or takes over ten seconds waits five seconds
|
||||
before a view event can retry, and an unmount drops lookups in flight). A key
|
||||
before a view event can retry, and an unmount drops lookups in flight). Opening
|
||||
another panorama settles the previous open before registering its wait; closing
|
||||
then releases the current wait immediately. A details lookup released while its
|
||||
service loads makes no panorama request after that service becomes available. A key
|
||||
Google refuses (`gm_authFailure`: the API not enabled, a referrer it does
|
||||
not allow, billing off) reads KEY REJECTED and fails a pending open at
|
||||
once; a lookup or open Google never answers fails after 10 or 20 s. In CI
|
||||
@@ -4226,7 +4288,7 @@ silently demoting every later lookup for the session.
|
||||
- The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected.
|
||||
- The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies.
|
||||
- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft.
|
||||
- `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available.
|
||||
- `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width.
|
||||
- The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset.
|
||||
- Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`.
|
||||
- Space Missions is replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally.
|
||||
@@ -4663,12 +4725,17 @@ Coordinate input requires exactly two nonempty components; extra comma or semico
|
||||
|
||||
Location search/fly-to, annotations and Radio location lookup receive one
|
||||
`placeSearch.geocode(query, { bias, signal })` service. `src/standalone` composes
|
||||
two offline providers first — a strict decimal-degree coordinate reader and an
|
||||
two offline providers first — a strict decimal-degree/geo-URI coordinate reader and an
|
||||
exact-match reader over the bundled city and landmark names — then Google when
|
||||
configured and Photon/OpenStreetMap as fallback, including Google transport
|
||||
failures or declined requests. The offline pair answer with no request and no
|
||||
key, and decline everything they are not certain of: a coordinate must be a
|
||||
decimal-degree pair (either order when N/S/E/W fix the axes), and a bundled name
|
||||
decimal-degree pair (either order when N/S/E/W fix the axes), or a two-dimensional
|
||||
WGS84 `geo:latitude,longitude` URI with an optional `;crs=wgs84`. URI scheme and
|
||||
CRS names are case-insensitive; internal whitespace, altitude, uncertainty, other
|
||||
parameters, query strings and fragments decline rather than silently dropping
|
||||
information. For example, `geo:39.7392,-104.9903` resolves offline to the same exact
|
||||
point, decimal label and framing box as `39.7392, -104.9903`. A bundled name
|
||||
must match exactly, so `12junk, 34oops` and `austin, tx` both reach the
|
||||
geocoders instead of being answered from the bundle. Degrees/minutes/seconds and
|
||||
grid references are not parsed. An answer either provider gives is exact, so
|
||||
@@ -4725,7 +4792,7 @@ are omitted rather than framing the wrong part of the globe.
|
||||
- The bottom Visual Presets tray presents a **five-tile MAP SOURCE row** (`#map-stack-chips`, `src/mapStackChips.js`): Google 3D, Esri Satellite, Bing Aerial, Bing Labels, and OSM. The duplicate left `#stack-panel` is retired. The five tiles share one row on desktop and two rows on narrow screens, carry `aria-pressed` on the active source, and remain keyboard-reachable with a visible focus outline.
|
||||
- The lit tile follows controller state, not the click: a rejected switch (no ion token) or a superseded one (rapid A→B) leaves the genuinely active source lit, and the tray heading keeps its short-label status readout (`...` while switching, amber on `lastError`).
|
||||
- Ion stacks remain visible and keyboard-focusable when no ion token is configured, but expose `aria-disabled="true"` and do not switch. Their accessible label and tooltip quote `getStacks().unavailableReason` — the same string `setStack()` puts in the toast. OSM works keyless. The `ION` badge is gated on the stack's own `requiresIon`, so a `photoreal` chip unavailable because the Google tileset failed says so instead of falsely demanding an ion token.
|
||||
- Stack choice participates in share links (`src/sharelink.js`) and falls back to the best available stack when the requested one is unavailable (keyless boots land on Esri; OSM takes over automatically if Esri is unreachable). Share-link restore, the `set_map_stack` voice tool, and the chip row all land on the same `_setMapStack()` path.
|
||||
- Stack choice participates in share links (`src/sharelink.js`) and falls back to the best available stack when the requested one is unavailable (keyless boots land on Esri; OSM takes over automatically if Esri is unreachable; while that construction fallback is on screen Esri is retried in the background, 30 s doubling to a 10-minute cap with each attempt abandoned after 60 s, and replaces OSM once it loads. The switch to OSM after repeated Esri tile failures is not retried; selecting Esri again tries it). Share-link restore, the `set_map_stack` voice tool, and the chip row all land on the same `_setMapStack()` path.
|
||||
|
||||
### Voice Map Whiteboard / Annotations (June 2026)
|
||||
|
||||
@@ -4819,7 +4886,7 @@ pins and share links already supply complete boxes.
|
||||
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
|
||||
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
|
||||
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
|
||||
- **Panel.** `#recent-imagery-panel` is static rail markup in `src/ui/templates/context.html` beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`.
|
||||
- **Panel.** `#recent-imagery-panel` is static rail markup in `src/ui/templates/context.html` beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
|
||||
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
|
||||
- Regression surface: the colocated `*.test.mjs` beside each module (shared doubles in `src/layers/recentImagery/testDoubles.mjs`; `src/ui/recentImagery.test.mjs` includes a DOM-structure guard: every control keeps its place in the tree, nothing is hidden, and every fixed-height block keeps the class the stylesheet fixes its height by; it has no layout, so it cannot see movement), `src/ui/layerPanel.test.mjs` (mount), `src/maps/controller.test.mjs` (`subscribe`), `src/data/layerState.test.mjs` (codec), `src/sharelink.celestial.test.mjs` (panel token), and the live gate `scripts/qa-recent-imagery.mjs`, which also measures every control's rect, relative to the panel, across the transitions within 1 px; that measurement is the real layout-shift check. `QA_RECENT_IMAGERY_SLOW_RENDER=1` gives loaded software renderers a 4 s zoom deadline and an 8-sample stability tail; the default stays 2 s and 12 samples.
|
||||
|
||||
|
||||
@@ -49,7 +49,8 @@ failure elsewhere. These questions guide review, not a mandatory questionnaire.
|
||||
regressions? Prefer fixes whose tests fail on the base. Test-only PRs should
|
||||
close a real coverage gap with deterministic fixtures and useful assertions.
|
||||
Inspect removed/skipped tests, weakened assertions, mocks, snapshots, and runner
|
||||
changes. Update `CURRENT-STATE.md` and `CHANGELOG.md` for runtime changes, and
|
||||
changes. Update `CURRENT-STATE.md` and add a `changelog.d/<pr-number>-<slug>.md`
|
||||
fragment (not an edit to `CHANGELOG.md`) for runtime changes, and
|
||||
`DATA_SOURCES.md` for source changes.
|
||||
|
||||
## 3. Choose execution proportionate to risk
|
||||
@@ -124,6 +125,15 @@ Condition the merge on the reviewed head where supported; if revisions change,
|
||||
return to validation. Verify the merged tree matches the validated candidate and
|
||||
record the merge commit/PR URL; stop on mismatch.
|
||||
|
||||
Pending release notes live in `changelog.d/`, one file per PR, so integration never
|
||||
resolves the top of `CHANGELOG.md`. At release, `npm run changelog:check` previews
|
||||
the batch and its order; `npm run changelog` splices it into `CHANGELOG.md` and
|
||||
empties the directory. The assembler refuses a malformed filename or two fragments
|
||||
claiming one PR number before writing, and copies text through unchanged so the
|
||||
contributor's wording and credit ship. The write is staged in
|
||||
`changelog.d/.assembling/`, so if it fails part-way, rerunning `npm run changelog`
|
||||
finishes or rolls back the batch. It never duplicates or drops an entry.
|
||||
|
||||
Return this concise record privately unless posting is authorized. Keep sensitive
|
||||
security evidence in the private report:
|
||||
|
||||
|
||||
+1
-1
@@ -273,7 +273,7 @@ and the development server's internal routes. See SECURITY.md.
|
||||
| `next_satellite_pass` | `satellites` | Next pass over a place or point (default the ISS), with naked-eye visibility |
|
||||
| `satellites_overhead` | `satellites` | Satellites in a CelesTrak group above a place or point now, highest first |
|
||||
| `find_cctv_cameras` | `cctv` | Public cameras in an area, nearest first |
|
||||
| `get_cctv_snapshot` | `cctv` | The current image from one camera, returned as image content |
|
||||
| `get_cctv_snapshot` | `cctv` | An image from one camera, returned as image content; Street View fallbacks are labelled historical |
|
||||
| `find_alpr_cameras` | `alpr` | OpenStreetMap-mapped license plate readers in a US/Canadian area up to 3° |
|
||||
| `find_radio_stations` | `radio` | Radio Browser stations by area and/or search terms, with stream URLs |
|
||||
| `search_places` | `placeSearch` | Points of interest matching a query within an area (Google Places) |
|
||||
|
||||
@@ -38,6 +38,8 @@
|
||||
"i18n": "node scripts/i18n.mjs",
|
||||
"layer-token:next": "node scripts/next-layer-state-token.mjs",
|
||||
"layer-token:check": "node scripts/check-layer-state-tokens.mjs",
|
||||
"changelog": "node scripts/assemble-changelog.mjs --write",
|
||||
"changelog:check": "node scripts/assemble-changelog.mjs --check",
|
||||
"dev": "vite",
|
||||
"dev:secure": "./scripts/dev-secure.sh",
|
||||
"opensky:import": "./scripts/opensky-import-client.sh",
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import * as fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
/**
|
||||
* Release-time assembly of changelog fragments.
|
||||
*
|
||||
* A pull request adds `changelog.d/<pull request>-<slug>.md` instead of editing
|
||||
* `CHANGELOG.md`. Distinct filenames never conflict, so two pull requests in
|
||||
* flight no longer write into the same few lines at the top of one file. A
|
||||
* release splices the fragments in and empties the directory.
|
||||
*
|
||||
* Fragment text is copied through unchanged apart from trailing whitespace:
|
||||
* `src/annotations/drawTool.test.mjs` reads `CHANGELOG.md` as prose and slices a
|
||||
* fixed window after a heading, so reflowing an entry here could move text
|
||||
* across that window.
|
||||
*
|
||||
* A write is staged so that a failure at any point leaves a rerun unable to
|
||||
* duplicate or lose an entry. The assembled file is written into
|
||||
* `changelog.d/.assembling/` first, the fragments are renamed in beside it, and
|
||||
* renaming the assembled file over `CHANGELOG.md` is the single commit point.
|
||||
* While the assembled file is still staged the batch has not landed, so
|
||||
* recovery moves the fragments back; once it is gone the batch has landed, and
|
||||
* the staged fragments are leftovers to delete. Either way they are out of the
|
||||
* input directory, so they are never assembled twice.
|
||||
*/
|
||||
export const FRAGMENT_DIR = 'changelog.d';
|
||||
export const STAGING_DIR = '.assembling';
|
||||
const STAGED_CHANGELOG = 'CHANGELOG.md';
|
||||
const FRAGMENT_NAME = /^(\d+)-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
|
||||
const HEADING = '# Changelog\n';
|
||||
|
||||
/** Fragment file names a release may consume, highest pull request first. */
|
||||
export function orderFragmentNames(names) {
|
||||
const claimed = new Map();
|
||||
for (const name of names) {
|
||||
if (name === 'README.md') continue;
|
||||
const match = FRAGMENT_NAME.exec(name);
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`Unexpected file in ${FRAGMENT_DIR}/: ${name}` +
|
||||
' — expected <pull request>-<slug>.md with a lowercase slug',
|
||||
);
|
||||
}
|
||||
const number = Number(match[1]);
|
||||
const prior = claimed.get(number);
|
||||
if (prior) {
|
||||
throw new Error(
|
||||
`Two fragments claim pull request ${number}: ${prior} and ${name}`,
|
||||
);
|
||||
}
|
||||
claimed.set(number, name);
|
||||
}
|
||||
return [...claimed.entries()]
|
||||
.sort(([a], [b]) => b - a)
|
||||
.map(([, name]) => name);
|
||||
}
|
||||
|
||||
/** Splice fragment bodies above the existing entries, newest batch on top. */
|
||||
export function assembleChangelog(changelog, fragments) {
|
||||
if (!fragments.length) return changelog;
|
||||
if (!changelog.startsWith(HEADING)) {
|
||||
throw new Error('CHANGELOG.md must start with "# Changelog"');
|
||||
}
|
||||
const entries = changelog.slice(HEADING.length).replace(/^\n+/, '');
|
||||
const batch = fragments.map((text) => text.replace(/\s+$/, '')).join('\n\n');
|
||||
return `${HEADING}\n${batch}\n\n${entries}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish or roll back a batch an earlier `--write` left in the staging
|
||||
* directory. A no-op when there is none.
|
||||
*
|
||||
* @returns {Promise<'none'|'rolled-back'|'cleaned-up'>}
|
||||
*/
|
||||
export async function recoverInterruptedBatch(root, io = fs) {
|
||||
const directory = path.join(root, FRAGMENT_DIR);
|
||||
const staging = path.join(directory, STAGING_DIR);
|
||||
let staged;
|
||||
try {
|
||||
staged = await io.readdir(staging);
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return 'none';
|
||||
throw error;
|
||||
}
|
||||
if (!staged.includes(STAGED_CHANGELOG)) {
|
||||
// The assembled file was renamed over CHANGELOG.md: the batch landed.
|
||||
await io.rm(staging, { recursive: true, force: true });
|
||||
return 'cleaned-up';
|
||||
}
|
||||
// The batch never reached CHANGELOG.md, so every fragment goes back.
|
||||
const pending = new Set(await io.readdir(directory));
|
||||
const fragments = staged.filter((name) => name !== STAGED_CHANGELOG);
|
||||
const clash = fragments.filter((name) => pending.has(name));
|
||||
if (clash.length) {
|
||||
throw new Error(
|
||||
`Cannot roll back ${FRAGMENT_DIR}/${STAGING_DIR}/: ${clash.join(', ')}` +
|
||||
` also exist in ${FRAGMENT_DIR}/ — resolve by hand`,
|
||||
);
|
||||
}
|
||||
for (const name of fragments) {
|
||||
await io.rename(path.join(staging, name), path.join(directory, name));
|
||||
}
|
||||
await io.rm(staging, { recursive: true, force: true });
|
||||
return 'rolled-back';
|
||||
}
|
||||
|
||||
/**
|
||||
* Report or apply the pending fragments in `<root>/changelog.d`.
|
||||
*
|
||||
* The batch is validated in full before anything is written, so a malformed
|
||||
* filename or a duplicate pull request number leaves the directory untouched.
|
||||
* `--write` first recovers any batch an interrupted run left staged.
|
||||
*
|
||||
* @param {string} root repository root
|
||||
* @param {'--check'|'--write'} mode `--check` reports and changes nothing
|
||||
* @param {typeof fs} [io] filesystem calls, replaceable for failure injection
|
||||
* @returns {Promise<{ consumed: string[], changelog: string }>}
|
||||
*/
|
||||
export async function assembleFragments(root, mode, io = fs) {
|
||||
if (!['--check', '--write'].includes(mode)) {
|
||||
throw new Error(
|
||||
'Usage: node scripts/assemble-changelog.mjs --check|--write',
|
||||
);
|
||||
}
|
||||
const directory = path.join(root, FRAGMENT_DIR);
|
||||
const staging = path.join(directory, STAGING_DIR);
|
||||
const changelogFile = path.join(root, 'CHANGELOG.md');
|
||||
if (mode === '--write') {
|
||||
await recoverInterruptedBatch(root, io);
|
||||
}
|
||||
const names = await io.readdir(directory);
|
||||
if (names.includes(STAGING_DIR)) {
|
||||
throw new Error(
|
||||
`${FRAGMENT_DIR}/${STAGING_DIR}/ holds a batch an interrupted release` +
|
||||
' left behind — `npm run changelog` finishes or rolls it back',
|
||||
);
|
||||
}
|
||||
const consumed = orderFragmentNames(names);
|
||||
const bodies = [];
|
||||
for (const name of consumed) {
|
||||
bodies.push(await io.readFile(path.join(directory, name), 'utf8'));
|
||||
}
|
||||
const changelog = assembleChangelog(
|
||||
await io.readFile(changelogFile, 'utf8'),
|
||||
bodies,
|
||||
);
|
||||
if (mode === '--write' && consumed.length) {
|
||||
try {
|
||||
await io.mkdir(staging);
|
||||
await io.writeFile(
|
||||
path.join(staging, STAGED_CHANGELOG),
|
||||
changelog,
|
||||
'utf8',
|
||||
);
|
||||
for (const name of consumed) {
|
||||
await io.rename(path.join(directory, name), path.join(staging, name));
|
||||
}
|
||||
await io.rename(path.join(staging, STAGED_CHANGELOG), changelogFile);
|
||||
await io.rm(staging, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
try {
|
||||
await recoverInterruptedBatch(root, io);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`${error.message} — the batch is staged in ${FRAGMENT_DIR}/${STAGING_DIR}/,` +
|
||||
' and the next `npm run changelog` finishes or rolls it back',
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return { consumed, changelog };
|
||||
}
|
||||
|
||||
const invoked = process.argv[1]
|
||||
? pathToFileURL(path.resolve(process.argv[1])).href
|
||||
: '';
|
||||
if (import.meta.url === invoked) {
|
||||
try {
|
||||
if (process.argv.length !== 3) {
|
||||
throw new Error(
|
||||
'Usage: node scripts/assemble-changelog.mjs --check|--write',
|
||||
);
|
||||
}
|
||||
const mode = process.argv[2];
|
||||
const { consumed } = await assembleFragments(
|
||||
fileURLToPath(new URL('../', import.meta.url)),
|
||||
mode,
|
||||
);
|
||||
if (!consumed.length) {
|
||||
console.log(`No fragments in ${FRAGMENT_DIR}/.`);
|
||||
} else {
|
||||
console.log(
|
||||
`${mode === '--write' ? 'Assembled' : 'Would assemble'} ${consumed.length} fragment(s), in order:` +
|
||||
`\n ${consumed.join('\n ')}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,7 @@
|
||||
"server/providers/cctv/constants.js",
|
||||
"server/providers/cctv/media.js",
|
||||
"server/providers/cctv/normalize.js",
|
||||
"src/data/cctvMissingNumbers.test.mjs",
|
||||
"server/providers/cctv/sources.js",
|
||||
"server/providers/radio.js",
|
||||
"server/providers/radio/catalog.js",
|
||||
@@ -1058,5 +1059,7 @@
|
||||
"src/tooling/webAppIcons.test.mjs",
|
||||
"src/ui/flyToDataSource.js",
|
||||
"src/ui/flyToDataSource.test.mjs",
|
||||
"scripts/assemble-changelog.mjs",
|
||||
"src/tooling/changelogFragments.test.mjs",
|
||||
"src/data/gbfsProxyRateLimit.test.mjs"
|
||||
]
|
||||
@@ -131,7 +131,9 @@
|
||||
"server/providers/common/http.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/i18n/marker.js",
|
||||
"src/data/tomtomTiles.js"
|
||||
"src/data/tomtomTiles.js",
|
||||
"server/providers/common/same-site.js",
|
||||
"src/localRequestGate.mjs"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
@@ -901,6 +903,7 @@
|
||||
"src/data/aircraftIcons.js",
|
||||
"src/data/aircraftMeta.js",
|
||||
"src/data/aircraftNearbyPolicy.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/cockpitAirLod.js",
|
||||
"src/data/cockpitContactDot.js",
|
||||
"src/data/contactMatch.js",
|
||||
@@ -1649,6 +1652,7 @@
|
||||
"src/ui/radioPanelPlacement.js",
|
||||
"src/cyberSonarGpu.js",
|
||||
"src/scenes/nepalEvidencePack.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/bhoteKoshiEvent.js",
|
||||
"src/ui/imagerySplit.js",
|
||||
"src/data/bhoteKoshiEmbeddedMedia.js",
|
||||
@@ -2500,6 +2504,7 @@
|
||||
"exports": ["./application/layers"],
|
||||
"modules": [
|
||||
"src/cyberSonar.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/bhoteKoshiEvent.js",
|
||||
"src/ui/imagerySplit.js",
|
||||
"src/maps/imageryComparison.js",
|
||||
@@ -3067,6 +3072,7 @@
|
||||
"src/app/operations.js",
|
||||
"src/sources/sourceSlot.js",
|
||||
"src/app/surfaceServices.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/dataCredits.js",
|
||||
"src/data/geoid.js",
|
||||
"src/data/local_data/natural_earth/marine.json",
|
||||
@@ -3226,6 +3232,7 @@
|
||||
"src/layers/flights/records.js",
|
||||
"src/layers/flights/recordPolicy.js",
|
||||
"src/data/aircraftMeta.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/renderAltitude.js",
|
||||
"src/data/aircraftClass.js",
|
||||
"src/data/aircraftEmergency.js"
|
||||
@@ -3236,7 +3243,8 @@
|
||||
"exports": ["./layers/flights/ingestion"],
|
||||
"modules": [
|
||||
"src/layers/flights/ingestion.js",
|
||||
"src/layers/flights/recordPolicy.js"
|
||||
"src/layers/flights/recordPolicy.js",
|
||||
"src/data/approxDistance.js"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
@@ -3547,6 +3555,7 @@
|
||||
"src/cyberSonar.js",
|
||||
"src/app/sourceSlot.js",
|
||||
"src/celestialRing.js",
|
||||
"src/data/approxDistance.js",
|
||||
"src/data/cameraSensitivity.js",
|
||||
"src/data/contactPlayback.js",
|
||||
"src/data/contactTrailRenderer.js",
|
||||
|
||||
@@ -24,8 +24,8 @@ export function runChecked(command, args, { shell = false } = {}) {
|
||||
export function installPinokioDependencies() {
|
||||
applyPinokioEnvironment();
|
||||
rmSync(READY_FILE, { force: true });
|
||||
const npm = npmProcessSpec();
|
||||
runChecked(npm.command, ['ci'], { shell: npm.shell });
|
||||
const npm = npmProcessSpec(['ci']);
|
||||
runChecked(npm.command, npm.args, { shell: npm.shell });
|
||||
|
||||
// Pinokio starts Vite directly and loads only its ENVIRONMENT file plus the
|
||||
// normal dotenv ladder. Unlike dev-fresh.sh, it does not import macOS
|
||||
|
||||
@@ -84,6 +84,63 @@ try {
|
||||
() => window.__godsEyeView.styleManager._activePoiIndex === 1,
|
||||
),
|
||||
);
|
||||
const geocoderRequests = [];
|
||||
const recordGeocoderRequest = (request) => {
|
||||
const url = new URL(request.url());
|
||||
if (
|
||||
url.pathname === '/api/geocode' ||
|
||||
url.pathname === '/api/google/geocode' ||
|
||||
(url.hostname === 'photon.komoot.io' && url.pathname === '/api/')
|
||||
)
|
||||
geocoderRequests.push(request.url());
|
||||
};
|
||||
page.on('request', recordGeocoderRequest);
|
||||
await page.$eval('#location-search', (input) => {
|
||||
input.value = 'geo:39.7392,-104.9903';
|
||||
input.focus();
|
||||
});
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(
|
||||
() => {
|
||||
const state =
|
||||
window.__godsEyeView.styleManager._locationLookup.getState();
|
||||
return (
|
||||
state.query === 'geo:39.7392,-104.9903' && state.status === 'found'
|
||||
);
|
||||
},
|
||||
{ timeout: 30000 },
|
||||
);
|
||||
await page.waitForFunction(
|
||||
() => !window.__godsEyeView.viewer.camera._currentFlight,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
check(
|
||||
'native geo URI search shows the decimal coordinate readout',
|
||||
await page.evaluate(() => {
|
||||
const ui = window.__godsEyeView.styleManager;
|
||||
return (
|
||||
ui._searchedLocationLabel === '39.7392° N, 104.9903° W' &&
|
||||
ui._locationMiniCity.textContent.includes('39.7392° N') &&
|
||||
ui._locationMiniPoi.textContent === '104.9903° W'
|
||||
);
|
||||
}),
|
||||
);
|
||||
check(
|
||||
'geo URI navigation settles near the requested coordinate',
|
||||
await page.evaluate(() => {
|
||||
const position = window.__godsEyeView.viewer.camera.positionCartographic;
|
||||
const degrees = 180 / Math.PI;
|
||||
return (
|
||||
Math.abs(position.latitude * degrees - 39.7392) < 0.05 &&
|
||||
Math.abs(position.longitude * degrees + 104.9903) < 0.05
|
||||
);
|
||||
}),
|
||||
);
|
||||
check(
|
||||
'geo URI search makes no geocoder request',
|
||||
geocoderRequests.length === 0,
|
||||
);
|
||||
page.off('request', recordGeocoderRequest);
|
||||
await page.evaluate(() => {
|
||||
const lookup = window.__godsEyeView.styleManager._locationLookup;
|
||||
window.__qaSearchRequests = [];
|
||||
@@ -96,6 +153,7 @@ try {
|
||||
window.__qaSearchRequests.push({ query, options, resolve }),
|
||||
);
|
||||
document.getElementById('location-search').value = 'First';
|
||||
document.getElementById('location-search').focus();
|
||||
});
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(() => window.__qaSearchRequests.length === 1);
|
||||
|
||||
@@ -76,10 +76,15 @@ export function hasRequiredDependencies(rootDir = ROOT) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Return the npm command and spawn mode required by the target platform. */
|
||||
export function npmProcessSpec(platform = process.platform) {
|
||||
const windows = platform === 'win32';
|
||||
return { command: windows ? 'npm.cmd' : 'npm', shell: windows };
|
||||
/**
|
||||
* Return the npm command, arguments and spawn mode for the target platform.
|
||||
* Windows must run npm.cmd through a shell, and Node 24 deprecates passing an
|
||||
* argument array with `shell: true` (DEP0190), so there the arguments, which
|
||||
* are fixed npm subcommands, join the command string.
|
||||
*/
|
||||
export function npmProcessSpec(args, platform = process.platform) {
|
||||
if (platform !== 'win32') return { command: 'npm', args, shell: false };
|
||||
return { command: ['npm.cmd', ...args].join(' '), args: [], shell: true };
|
||||
}
|
||||
|
||||
/** Read one key from Vite's dotenv file ladder without depending on Vite. */
|
||||
@@ -190,8 +195,8 @@ export function buildCapabilitySummary(
|
||||
|
||||
export function inspectSetup({ includeKeychain = true, authoritativeEnvironment = false, rootDir = ROOT } = {}) {
|
||||
const node = classifyNodeVersion();
|
||||
const npm = npmProcessSpec();
|
||||
const npmResult = spawnSync(npm.command, ['--version'], {
|
||||
const npm = npmProcessSpec(['--version']);
|
||||
const npmResult = spawnSync(npm.command, npm.args, {
|
||||
encoding: 'utf8',
|
||||
shell: npm.shell,
|
||||
});
|
||||
|
||||
@@ -39,11 +39,21 @@ export function escapeXml(text) {
|
||||
/**
|
||||
* Coerce a value to a finite number, returning fallback if NaN/Infinity.
|
||||
*
|
||||
* Absent, blank and boolean values take the fallback too: `Number` reads
|
||||
* null, '' and false as 0, which would turn a missing coordinate, heading or
|
||||
* elevation into a real zero.
|
||||
*
|
||||
* @param {*} value
|
||||
* @param {number} [fallback=NaN]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function toFiniteNumber(value, fallback = NaN) {
|
||||
if (
|
||||
value == null ||
|
||||
typeof value === 'boolean' ||
|
||||
(typeof value === 'string' && !value.trim())
|
||||
)
|
||||
return fallback;
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : fallback;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import { simplifyOverpassPayloadBody } from './geometry.js';
|
||||
* Checks for known rate-limit phrases in the body text regardless of
|
||||
* HTTP status code, since some mirrors return 200 with an error payload.
|
||||
*
|
||||
* @param {string} bodyText - Upstream response body.
|
||||
* @param {string} bodyText - The remark of a data reply, or a non-data body.
|
||||
* @returns {boolean} True if the body looks rate-limited.
|
||||
*/
|
||||
function overpassLooksRateLimited(bodyText) {
|
||||
@@ -41,6 +41,14 @@ function overpassLooksRuntimeError(bodyText) {
|
||||
);
|
||||
}
|
||||
|
||||
function parseJson(text) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True only for an upstream response that is actually Overpass data.
|
||||
*
|
||||
@@ -151,15 +159,22 @@ async function fetchOverpassPayload(
|
||||
signal: controller.signal,
|
||||
});
|
||||
const responseBody = await readBody(upstream, maxResponseBytes);
|
||||
const parsed = parseJson(responseBody);
|
||||
// An Overpass data reply reports failure in its remark; its element
|
||||
// tags are data and can contain any phrase. Any other body (an error
|
||||
// page, or JSON without elements) is matched whole.
|
||||
const failureText = Array.isArray(parsed?.elements)
|
||||
? String(parsed.remark || '')
|
||||
: responseBody;
|
||||
const rateLimited =
|
||||
upstream.status === 429 ||
|
||||
upstream.status === 406 ||
|
||||
overpassLooksRateLimited(responseBody);
|
||||
overpassLooksRateLimited(failureText);
|
||||
if (
|
||||
rateLimited ||
|
||||
upstream.status < 200 ||
|
||||
upstream.status >= 300 ||
|
||||
overpassLooksRuntimeError(responseBody)
|
||||
overpassLooksRuntimeError(failureText)
|
||||
) {
|
||||
const failures = (previous?.failures || 0) + 1;
|
||||
const delay = retryDelay(
|
||||
@@ -178,7 +193,6 @@ async function fetchOverpassPayload(
|
||||
failure = refusal(status, delay);
|
||||
continue;
|
||||
}
|
||||
const parsed = JSON.parse(responseBody);
|
||||
if (!Array.isArray(parsed?.elements) || parsed.remark)
|
||||
throw new Error('Malformed Overpass response');
|
||||
cooldowns.delete(endpoint);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
normalizeBudget as normalizeTomTomBudget,
|
||||
isOverBudget as isTomTomOverBudget,
|
||||
} from '../../src/data/tomtomTiles.js';
|
||||
import { admitSameSite } from './common/same-site.js';
|
||||
|
||||
/**
|
||||
* TomTom traffic-flow vector-tile proxy with a daily budget governor.
|
||||
@@ -35,6 +36,13 @@ import {
|
||||
* for the rest of the billing period. 6,000/day keeps a full 31-day month
|
||||
* inside the allowance (186,000) with headroom to spare.
|
||||
*
|
||||
* Cross-site gate: both routes refuse cross-site browser requests with 403
|
||||
* (the gate Mapillary, OpenAI and Places already use). Every uncached tile is
|
||||
* a billed upstream attempt counted against the persistent daily budget, so
|
||||
* without the gate any web page the user visits could fire `<img>` requests
|
||||
* at distinct tiles, spend the TomTom quota and leave the traffic layer on
|
||||
* 429 budget for the rest of the UTC day.
|
||||
*
|
||||
* GET /api/tomtom/status → {hasKey, dailyCount, budget, date}. Keyless mode:
|
||||
* status reports hasKey:false and the tile endpoint 503s {error:'no_key'}
|
||||
* without touching upstream — the traffic layer then stays in simulation mode.
|
||||
@@ -161,6 +169,8 @@ export function tomtomProxy() {
|
||||
|
||||
const installMiddleware = (server) => {
|
||||
server.middlewares.use('/api/tomtom', async (req, res) => {
|
||||
// Gate first: a cross-site <img>/fetch must not reach the budget counter.
|
||||
if (admitSameSite(req, res)) return;
|
||||
// Sanitized responses only (proxy/security baseline): no upstream
|
||||
// error details, and never echo the key or the upstream URL.
|
||||
const sendJson = (status, obj, extraHeaders = {}) => {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Local equirectangular distance in km, for viewer-proximity gates. Takes the
|
||||
* short way round, so points either side of 180° stay close.
|
||||
*/
|
||||
export function approxDistanceKm(lat1, lon1, lat2, lon2) {
|
||||
const dLat = (lat2 - lat1) * 111.32;
|
||||
let dLonDeg = lon2 - lon1;
|
||||
dLonDeg -= 360 * Math.round(dLonDeg / 360);
|
||||
const dLon =
|
||||
dLonDeg * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
|
||||
return Math.hypot(dLat, dLon);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
fallbackHeadingFromId,
|
||||
isLikelyCataloniaCoordinate,
|
||||
toFiniteNumber,
|
||||
} from '../../server/providers/cctv/normalize.js';
|
||||
import {
|
||||
loadCaltransSourcesFromOpenData,
|
||||
loadTallinnSourcesFromCatalog,
|
||||
loadTflSourcesFromOpenData,
|
||||
parseCataloniaXml,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
import { createCatalog } from '../layers/cctv/catalog.js';
|
||||
import { createModel } from '../layers/cctv/model.js';
|
||||
|
||||
/** Values `Number` reads as 0 (or 1) although they carry no number. */
|
||||
const ABSENT = [null, undefined, '', ' ', false, true];
|
||||
|
||||
/** Set env vars for one test and restore them afterwards. */
|
||||
function withEnv(t, env) {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
const previous = process.env[name];
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env[name];
|
||||
else process.env[name] = previous;
|
||||
});
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/** Silence the loaders' progress and failure logging. */
|
||||
function quiet(t) {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
}
|
||||
|
||||
/** The production browser model; only the catalog's pose pass is stubbed. */
|
||||
function browserModel() {
|
||||
const parts = {};
|
||||
parts.model = createModel({
|
||||
state: {},
|
||||
services: { focus: {} },
|
||||
parts,
|
||||
source: {},
|
||||
});
|
||||
return parts.model;
|
||||
}
|
||||
|
||||
/** The browser catalog over the production model. */
|
||||
function browserCatalog(model, cityPois = {}) {
|
||||
return createCatalog({
|
||||
state: {},
|
||||
services: { locations: { CITY_POIS: cityPois } },
|
||||
parts: { model: { ...model, ensureCameraPose: () => {} } },
|
||||
source: {},
|
||||
});
|
||||
}
|
||||
|
||||
/** GET /api/cctv/sources through the real proxy middleware. */
|
||||
async function requestSources(plugin) {
|
||||
let handler;
|
||||
plugin.configureServer({
|
||||
middlewares: {
|
||||
use(_route, fn) {
|
||||
handler = fn;
|
||||
},
|
||||
},
|
||||
});
|
||||
const res = {
|
||||
writeHead(status, headers) {
|
||||
Object.assign(this, { status, headers });
|
||||
},
|
||||
end(body) {
|
||||
this.body = body;
|
||||
},
|
||||
};
|
||||
await handler({ url: '/sources', method: 'GET' }, res);
|
||||
assert.equal(res.status, 200);
|
||||
return JSON.parse(res.body);
|
||||
}
|
||||
|
||||
test('absent, blank and boolean values take the fallback on both sides of the source list', () => {
|
||||
const { safeNumber } = browserModel();
|
||||
for (const value of ABSENT) {
|
||||
assert.ok(Number.isNaN(toFiniteNumber(value)), `server ${String(value)}`);
|
||||
assert.equal(toFiniteNumber(value, 15), 15, `server ${String(value)}`);
|
||||
assert.ok(Number.isNaN(safeNumber(value)), `browser ${String(value)}`);
|
||||
assert.equal(safeNumber(value, 74), 74, `browser ${String(value)}`);
|
||||
}
|
||||
for (const [value, expected] of [
|
||||
[0, 0],
|
||||
['0', 0],
|
||||
[-17, -17],
|
||||
[' 12.5 ', 12.5],
|
||||
]) {
|
||||
assert.equal(toFiniteNumber(value, 99), expected);
|
||||
assert.equal(safeNumber(value, 99), expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('a source-pack camera that omits or nulls its pose gets the browser defaults, not the clamp floors', async (t) => {
|
||||
quiet(t);
|
||||
const pose = {
|
||||
headingDeg: null,
|
||||
pitchDeg: null,
|
||||
fovDeg: null,
|
||||
rangeM: null,
|
||||
mountHeightM: null,
|
||||
groundElevationM: null,
|
||||
};
|
||||
const at = { cityId: 'austin', lat: 30.2672, lon: -97.7431 };
|
||||
withEnv(t, {
|
||||
CCTV_SOURCES_FILE: path.join(tmpdir(), 'gev-no-such-pack.json'),
|
||||
CCTV_SOURCES_JSON: JSON.stringify([
|
||||
{ id: 'pack-pose-omitted', ...at, feedType: 'image' },
|
||||
{ id: 'pack-pose-null', ...at, ...pose, feedType: 'image' },
|
||||
{ id: 'pack-coords-null', lat: null, lon: null, feedType: 'image' },
|
||||
{ id: 'pack-coords-blank', lat: '', lon: ' ', feedType: 'image' },
|
||||
]),
|
||||
});
|
||||
|
||||
const body = await requestSources(cctvProxy({ sourceRoot: tmpdir() }));
|
||||
const model = browserModel();
|
||||
const cameras = browserCatalog(model, {
|
||||
austin: { name: 'Austin', groundElevation: 150 },
|
||||
}).buildCatalogFromSources(body.sources);
|
||||
const byId = new Map(cameras.map((camera) => [camera.id, camera]));
|
||||
|
||||
for (const id of ['pack-pose-omitted', 'pack-pose-null']) {
|
||||
const camera = byId.get(id);
|
||||
assert.ok(camera, id);
|
||||
assert.equal(camera.headingDeg, model.headingFromId(id), id);
|
||||
assert.equal(camera.pitchDeg, -17, id);
|
||||
assert.equal(camera.fovDeg, 74, id);
|
||||
assert.equal(camera.rangeM, 700, id);
|
||||
assert.equal(camera.mountHeightM, 24, id);
|
||||
assert.equal(camera.groundElevationM, 150, id);
|
||||
}
|
||||
// No position is not a camera in the Gulf of Guinea.
|
||||
assert.equal(byId.has('pack-coords-null'), false);
|
||||
assert.equal(byId.has('pack-coords-blank'), false);
|
||||
});
|
||||
|
||||
test('Tallinn rows with a null heading or ground keep the low-confidence prior', (t) => {
|
||||
quiet(t);
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'gev-tallinn-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const file = path.join(root, 'tallinn.json');
|
||||
writeFileSync(
|
||||
file,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 'tln-null-heading',
|
||||
lat: 59.437,
|
||||
lon: 24.753,
|
||||
headingDeg: null,
|
||||
groundElevationM: null,
|
||||
url: 'https://ristmikud.tallinn.ee/last/cam001.jpg',
|
||||
},
|
||||
]),
|
||||
);
|
||||
withEnv(t, { CCTV_TALLINN_SOURCES_FILE: file });
|
||||
|
||||
const [camera] = loadTallinnSourcesFromCatalog({ sourceRoot: root });
|
||||
assert.equal(camera.headingConfidence, 'low');
|
||||
assert.equal(camera.headingDeg, fallbackHeadingFromId('tln-null-heading'));
|
||||
assert.equal(camera.groundElevationM, 15);
|
||||
});
|
||||
|
||||
test('TfL JamCams with null coordinates are dropped instead of placed at 0,0', async (t) => {
|
||||
quiet(t);
|
||||
const jamCam = (id, lat, lon) => ({
|
||||
id: `JamCams_${id}`,
|
||||
commonName: `JamCam ${id}`,
|
||||
lat,
|
||||
lon,
|
||||
additionalProperties: [
|
||||
{ key: 'available', value: 'true' },
|
||||
{
|
||||
key: 'imageUrl',
|
||||
value: `https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/${id}.jpg`,
|
||||
},
|
||||
],
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async () =>
|
||||
Response.json([
|
||||
jamCam('00001.00001', 51.5072, -0.1276),
|
||||
jamCam('00001.00002', null, null),
|
||||
jamCam('00001.00003', 51.5072, ''),
|
||||
]),
|
||||
);
|
||||
|
||||
const cameras = await loadTflSourcesFromOpenData();
|
||||
assert.deepEqual(
|
||||
cameras.map((camera) => camera.id),
|
||||
['tfl-00001.00001'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a Catalonia feature with a blank longitude is not read as the zero meridian', () => {
|
||||
const feature = (coordinates) => `<gml:featureMember>
|
||||
<cite:cameres fid="cameres.1">
|
||||
<gml:coordinates>${coordinates}</gml:coordinates>
|
||||
<cite:link>https://example.org/cam.jpg</cite:link>
|
||||
</cite:cameres>
|
||||
</gml:featureMember>`;
|
||||
const [blank, valid] = parseCataloniaXml(
|
||||
feature(',41.5') + feature('2.17,41.39'),
|
||||
);
|
||||
// 0 °E at 41.5 °N is inside the Catalonia box, so a zero would pass it.
|
||||
assert.ok(Number.isNaN(blank.lon));
|
||||
assert.equal(isLikelyCataloniaCoordinate(blank.lat, blank.lon), false);
|
||||
assert.equal(isLikelyCataloniaCoordinate(valid.lat, valid.lon), true);
|
||||
});
|
||||
|
||||
test('a Caltrans camera with a blank elevation keeps the 150 m ground prior', async (t) => {
|
||||
quiet(t);
|
||||
withEnv(t, { CCTV_CALTRANS_DISTRICTS: '4' });
|
||||
t.mock.method(globalThis, 'fetch', async () =>
|
||||
Response.json({
|
||||
data: [
|
||||
{
|
||||
cctv: {
|
||||
inService: 'true',
|
||||
location: {
|
||||
latitude: '37.8044',
|
||||
longitude: '-122.2712',
|
||||
elevation: '',
|
||||
locationName: 'TV101 -- I-880 : Test Ave',
|
||||
},
|
||||
imageData: {
|
||||
static: {
|
||||
currentImageURL:
|
||||
'https://cwwp2.dot.ca.gov/data/d4/cctv/image/tv101/tv101.jpg',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const [camera] = await loadCaltransSourcesFromOpenData();
|
||||
assert.ok(camera);
|
||||
assert.equal(camera.groundElevationM, 150);
|
||||
});
|
||||
@@ -726,7 +726,15 @@ const LABEL_ICAO = 'ae1fa4';
|
||||
const LABEL_POSITION = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
|
||||
|
||||
/** Seed one civil contact through the production refresh seam. */
|
||||
function seedLabelContact({ callsign, registration, tracked = false }) {
|
||||
function seedLabelContact({
|
||||
callsign,
|
||||
registration,
|
||||
tracked = false,
|
||||
// Per-test metadata overrides, spread last so a test can set a field to
|
||||
// `undefined` to model "the feed never sent it" — a default parameter
|
||||
// could not express that, it would just re-supply the default.
|
||||
meta: metaOverrides = {},
|
||||
}) {
|
||||
_setTrackedFlightRefreshStateForTest({
|
||||
icao24: LABEL_ICAO,
|
||||
entity: null,
|
||||
@@ -752,6 +760,7 @@ function seedLabelContact({ callsign, registration, tracked = false }) {
|
||||
turnRateDps: 0,
|
||||
rawLat: 30.21,
|
||||
rawLon: -97.71,
|
||||
...metaOverrides,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -825,6 +834,44 @@ test('civil label chain: the cockpit descriptor exposes a trimmed registration',
|
||||
assert.equal(flightsLayer.getTrackedInfo()?.registration, null);
|
||||
});
|
||||
|
||||
test('the tracked descriptor publishes the reported vertical rate', () => {
|
||||
// `mapAnalystRecord` has always published `verticalRateMps`; the tracked
|
||||
// seam did not, so a consumer that needs climb/descent (a flight-phase
|
||||
// classifier, the cockpit) had to reach past getTrackedInfo() into the
|
||||
// raw record. Both seams now answer with the same field name and unit.
|
||||
seedLabelContact({
|
||||
callsign: 'SWA696',
|
||||
registration: 'N123AB',
|
||||
tracked: true,
|
||||
meta: { verticalRate: -6.4 },
|
||||
});
|
||||
assert.equal(flightsLayer.getTrackedInfo()?.verticalRateMps, -6.4);
|
||||
assert.equal(
|
||||
mapAnalystRecord(LABEL_ICAO, { verticalRate: -6.4 }).verticalRateMps,
|
||||
-6.4,
|
||||
'the analyst seam and the tracked seam must agree',
|
||||
);
|
||||
});
|
||||
|
||||
test('an unreported vertical rate stays null, never a level-flight zero', () => {
|
||||
// Absent is not level. `stickyNumber` seeds this field with null, so a
|
||||
// contact that has never transmitted a rate must not read as 0 m/s — a
|
||||
// phase classifier would call that cruise while the aircraft climbs.
|
||||
for (const missing of [undefined, null, Number.NaN]) {
|
||||
seedLabelContact({
|
||||
callsign: 'SWA696',
|
||||
registration: 'N123AB',
|
||||
tracked: true,
|
||||
meta: { verticalRate: missing },
|
||||
});
|
||||
assert.equal(
|
||||
flightsLayer.getTrackedInfo()?.verticalRateMps,
|
||||
null,
|
||||
`vertical rate ${String(missing)} must publish as null`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('civil label chain: identity stays icao24 while the label moves', () => {
|
||||
for (const fixture of [
|
||||
{ callsign: 'SWA696', registration: 'N123AB' },
|
||||
|
||||
@@ -257,6 +257,32 @@ test('stickyFloorCell does not stick to a far-away stale cell', () => {
|
||||
assert.deepEqual(stickyFloorCell(30.2004, -97.6604, prev), { lat: 30.2, lon: -97.66 });
|
||||
});
|
||||
|
||||
// --- Antimeridian ------------------------------------------------------------
|
||||
// Raw longitude arithmetic walks a segment across 180° the long way round and
|
||||
// reads a contact on the seam as half a world from its previous cell.
|
||||
|
||||
test('corridorFloorCells walks across the antimeridian, not the long way round', () => {
|
||||
for (const [from, to, across, behind] of [
|
||||
[179.999, -179.998, -179.999, 179.998],
|
||||
[-179.999, 179.998, 179.999, -179.998],
|
||||
]) {
|
||||
const cells = corridorFloorCells([{ lat: -16.69, lon: from }, { lat: -16.69, lon: to }]);
|
||||
const lons = cells.map((c) => c.lon);
|
||||
assert.equal(lons[0], from);
|
||||
assert.equal(lons.at(-1), to);
|
||||
assert.ok(lons.includes(across), `crosses through ${across}: ${lons}`);
|
||||
assert.ok(!lons.includes(behind), `never walks back through ${behind}: ${lons}`);
|
||||
assert.ok(lons.every((lon) => Math.abs(lon) <= 180), `normalised: ${lons}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('stickyFloorCell holds across the antimeridian', () => {
|
||||
for (const [prevLon, lon] of [[180, -179.9998], [-180, 179.9998]]) {
|
||||
const prev = { lat: -16.69, lon: prevLon };
|
||||
assert.deepEqual(stickyFloorCell(-16.69, lon, prev), prev);
|
||||
}
|
||||
});
|
||||
|
||||
// --- F2: corridor budget fairness ------------------------------------------
|
||||
// The first cut spent the budget in Map insertion order and decremented it
|
||||
// BEFORE deduping, so parked contacts (whose corridor is the fix cell the poll
|
||||
|
||||
@@ -128,3 +128,12 @@ test('sampler: outside the google-3d regime nothing is sampled at all', () => {
|
||||
setMeshFloorPreferred(true);
|
||||
assert.equal(cachedMeshFloor(cell.lat, cell.lon), null);
|
||||
});
|
||||
|
||||
test('sampler: a cell just across the antimeridian is still near the viewer', () => {
|
||||
reset();
|
||||
let calls = 0;
|
||||
const scene = fakeScene(() => { calls += 1; return undefined; });
|
||||
sampleMeshFloorCells(scene, [{ lat: -16.8, lon: -179.999 }], { viewerLat: -16.8, viewerLon: 179.999 });
|
||||
sampleMeshFloorCells(scene, [{ lat: -16.81, lon: 179.999 }], { viewerLat: -16.81, viewerLon: -179.999 });
|
||||
assert.equal(calls, 2, 'about 200 m apart, so both cells are probed');
|
||||
});
|
||||
@@ -834,3 +834,48 @@ test('two contacts matching at the same strength resolve deterministically', ()
|
||||
'and the same query resolves the same way every time',
|
||||
);
|
||||
});
|
||||
|
||||
test('the military tracked descriptor publishes the reported vertical rate', () => {
|
||||
// Shape parity with the civil layer's getTrackedInfo(). The two layers store
|
||||
// the rate under different record keys (`verticalRateMps` here,
|
||||
// `verticalRate` there), so `resolveTrackedAircraftInfo` only hands back one
|
||||
// shape if BOTH descriptors map it — a consumer that reads the field off the
|
||||
// civil seam and finds it missing on the military one would silently treat
|
||||
// every military contact as level flight.
|
||||
const seedRate = (verticalRateMps) =>
|
||||
_setTrackedMilitaryRefreshStateForTest({
|
||||
icao24: 'ae7f01',
|
||||
entity: { gevLabelModel: { title: 'TEST', details: [] } },
|
||||
billboard: {
|
||||
position: Cesium.Cartesian3.fromDegrees(-97.0, 31.0, 8_000),
|
||||
color: Cesium.Color.WHITE,
|
||||
show: true,
|
||||
},
|
||||
billboardCollection: { show: true, remove() {} },
|
||||
viewer: { camera: { positionCartographic: null }, scene: {} },
|
||||
meta: {
|
||||
callsign: 'RCH512',
|
||||
rawLat: 31,
|
||||
rawLon: -97,
|
||||
altitudeFt: 26_000,
|
||||
speedMps: 220,
|
||||
track: 95,
|
||||
onGround: false,
|
||||
verticalRateMps,
|
||||
},
|
||||
});
|
||||
|
||||
seedRate(12.7);
|
||||
assert.equal(militaryFlightsLayer.getTrackedInfo()?.verticalRateMps, 12.7);
|
||||
|
||||
// Absent is not level: a contact that has never transmitted a rate must read
|
||||
// as null, not as a 0 m/s a phase classifier would call cruise.
|
||||
for (const missing of [undefined, null, Number.NaN]) {
|
||||
seedRate(missing);
|
||||
assert.equal(
|
||||
militaryFlightsLayer.getTrackedInfo()?.verticalRateMps,
|
||||
null,
|
||||
`vertical rate ${String(missing)} must publish as null`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { gstime } from 'satellite.js';
|
||||
import { createModel } from '../layers/launches/model.js';
|
||||
import rocketLaunchesLayer, {
|
||||
_setRocketMissionOverlayHostForTest,
|
||||
_setSelectedRocketMissionForTest,
|
||||
@@ -759,6 +760,126 @@ test('normalizes detailed payload and stage recovery records', () => {
|
||||
assert.equal(launches[0].recoveryStages[0].lon, -76.2);
|
||||
});
|
||||
|
||||
test('finiteCoordinate normalizes finite numbers and rejects non-numeric or non-finite inputs', () => {
|
||||
const model = createModel({});
|
||||
assert.equal(model.finiteCoordinate(42.5), 42.5);
|
||||
assert.equal(model.finiteCoordinate('28.5619'), 28.5619);
|
||||
assert.equal(model.finiteCoordinate('-80.5772'), -80.5772);
|
||||
assert.equal(model.finiteCoordinate(0), 0);
|
||||
assert.equal(model.finiteCoordinate('0'), 0);
|
||||
assert.equal(model.finiteCoordinate(undefined), null);
|
||||
assert.equal(model.finiteCoordinate('invalid'), null);
|
||||
assert.equal(model.finiteCoordinate('TBD'), null);
|
||||
assert.equal(model.finiteCoordinate(Number.NaN), null);
|
||||
assert.equal(model.finiteCoordinate(Number.POSITIVE_INFINITY), null);
|
||||
assert.equal(model.finiteCoordinate(Number.NEGATIVE_INFINITY), null);
|
||||
});
|
||||
|
||||
test('normalizes recovery stage coordinates, downrange distance, and flight numbers with non-finite fallbacks', () => {
|
||||
const launches = normalizeRocketLaunches(
|
||||
{
|
||||
results: [
|
||||
{
|
||||
id: 'recovery-fallbacks',
|
||||
name: 'Falcon 9 | Edge Case Stage Normalization',
|
||||
net: '2026-07-20T10:00:00Z',
|
||||
pad: { latitude: '28.608', longitude: '-80.604' },
|
||||
rocket: {
|
||||
launcher_stage: [
|
||||
{
|
||||
id: 88,
|
||||
type: { name: 'Booster' },
|
||||
launcher_flight_number: 'invalid-flight',
|
||||
landing: {
|
||||
attempt: true,
|
||||
success: false,
|
||||
downrange_distance: 'TBD',
|
||||
landing_location: {
|
||||
name: 'Ocean Impact',
|
||||
latitude: 'N/A',
|
||||
longitude: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 89,
|
||||
type: { name: 'Expended Stage' },
|
||||
landing: {
|
||||
attempt: false,
|
||||
type: { name: 'Expendable' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
NOW,
|
||||
);
|
||||
|
||||
assert.equal(launches[0].recoveryStages.length, 2);
|
||||
|
||||
const booster = launches[0].recoveryStages[0];
|
||||
assert.equal(booster.status, 'LOST');
|
||||
assert.equal(booster.success, false);
|
||||
assert.equal(booster.attempted, true);
|
||||
assert.equal(booster.flightNumber, null);
|
||||
assert.equal(booster.downrangeKm, null);
|
||||
assert.equal(booster.lat, null);
|
||||
assert.equal(booster.lon, null);
|
||||
|
||||
const expendable = launches[0].recoveryStages[1];
|
||||
assert.equal(expendable.status, 'EXPENDABLE');
|
||||
assert.equal(expendable.attempted, false);
|
||||
assert.equal(expendable.success, null);
|
||||
});
|
||||
|
||||
test('normalizes payload amounts and fractional string masses', () => {
|
||||
const launches = normalizeRocketLaunches(
|
||||
{
|
||||
results: [
|
||||
{
|
||||
id: 'payload-edge-cases',
|
||||
name: 'Electron | Mixed Payloads',
|
||||
net: '2026-07-20T10:00:00Z',
|
||||
pad: { latitude: '-39.26', longitude: '177.86' },
|
||||
rocket: {
|
||||
payloads: [
|
||||
{
|
||||
id: 601,
|
||||
amount: 'not-a-number',
|
||||
payload: { id: 11, name: 'Unknown Amount Payload' },
|
||||
},
|
||||
{
|
||||
id: 602,
|
||||
amount: 3,
|
||||
payload: { id: 12, name: 'Triple Payload' },
|
||||
},
|
||||
{
|
||||
id: 603,
|
||||
payload: {
|
||||
id: 13,
|
||||
name: 'Valid Fractional Mass Payload',
|
||||
mass: '12.75',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
NOW,
|
||||
);
|
||||
|
||||
// Blank, negative and non-numeric masses are pinned by "missing payload
|
||||
// details stay unknown without inventing mass or classification".
|
||||
const payloads = launches[0].payloads;
|
||||
assert.equal(payloads.length, 3);
|
||||
assert.equal(payloads[0].amount, 1);
|
||||
assert.equal(payloads[1].amount, 3);
|
||||
assert.equal(payloads[2].massKg, 12.75);
|
||||
});
|
||||
|
||||
test('keeps payload and recovery collections empty when LL2 does not disclose them', () => {
|
||||
const launches = normalizeRocketLaunches({ results: [{
|
||||
id: 'undisclosed',
|
||||
|
||||
@@ -72,19 +72,27 @@ export function sceneSeekState(scene, progress, durationForShot, holdForShot) {
|
||||
let shotIndex = scene.shots.length - 1;
|
||||
for (let index = 0; index < scene.shots.length; index += 1) {
|
||||
const endElapsedSec = startElapsedSec + durations[index];
|
||||
if (targetSec < endElapsedSec || index === scene.shots.length - 1) {
|
||||
// Compare in progress units: a shot's startProgress (start / total)
|
||||
// times total can round below its start and select the previous shot.
|
||||
if (
|
||||
normalized < endElapsedSec / totalSec ||
|
||||
index === scene.shots.length - 1
|
||||
) {
|
||||
shotIndex = index;
|
||||
break;
|
||||
}
|
||||
startElapsedSec = endElapsedSec;
|
||||
}
|
||||
// Keep the elapsed time inside the selected shot, so it agrees with
|
||||
// shotIndex when targetSec rounded below the shot's start.
|
||||
const elapsedSec = Math.max(targetSec, startElapsedSec);
|
||||
const shot = scene.shots[shotIndex];
|
||||
const flightDurationSec = shot.durationSec || DEFAULT_SHOT_DURATION_SEC;
|
||||
const holdDurationSec = holdForShot(scene, shot);
|
||||
const shotDurationSec = Math.max(0.001, flightDurationSec + holdDurationSec);
|
||||
const shotElapsedSec = Math.max(
|
||||
0,
|
||||
Math.min(shotDurationSec, targetSec - startElapsedSec),
|
||||
Math.min(shotDurationSec, elapsedSec - startElapsedSec),
|
||||
);
|
||||
const cameraProgress = clamp01(
|
||||
shotElapsedSec / Math.max(0.001, flightDurationSec),
|
||||
@@ -99,8 +107,8 @@ export function sceneSeekState(scene, progress, durationForShot, holdForShot) {
|
||||
);
|
||||
const move = resolveCameraMove(scene, shot);
|
||||
return {
|
||||
sceneProgress: totalSec > 0 ? targetSec / totalSec : 0,
|
||||
sceneElapsedSec: targetSec,
|
||||
sceneProgress: totalSec > 0 ? elapsedSec / totalSec : 0,
|
||||
sceneElapsedSec: elapsedSec,
|
||||
sceneDurationSec: totalSec,
|
||||
shotIndex,
|
||||
shot,
|
||||
|
||||
@@ -49,3 +49,39 @@ test('camera seeking preserves cubic easing and shortest-angle orientation', ()
|
||||
);
|
||||
assert.deepEqual(cameraAtProgress(null, camera(20, 350), 0), camera(20, 350));
|
||||
});
|
||||
|
||||
test('seeking to a shot start lands in that shot for every shot count and duration', () => {
|
||||
const misses = [];
|
||||
for (let count = 2; count <= 12; count += 1) {
|
||||
for (let flightTenths = 1; flightTenths <= 100; flightTenths += 1) {
|
||||
for (let holdTenths = 0; holdTenths <= 50; holdTenths += 1) {
|
||||
const shots = Array.from({ length: count }, (_, index) => ({
|
||||
id: `s${index}`,
|
||||
// Every third shot is longer, so boundaries are not all equal steps.
|
||||
durationSec: flightTenths / 10 + (index % 3 === 2 ? 1.7 : 0),
|
||||
holdSec: holdTenths / 10,
|
||||
camera: camera(20, 0),
|
||||
}));
|
||||
const mixed = { shots };
|
||||
for (const [index, shot] of shots.entries()) {
|
||||
const { startProgress, startElapsedSec } = sceneTimingForShot(
|
||||
mixed,
|
||||
shot,
|
||||
duration,
|
||||
);
|
||||
const seek = sceneSeekState(mixed, startProgress, duration, hold);
|
||||
// One or two ulps earlier still belongs to the previous shot.
|
||||
const before = startProgress * (1 - Number.EPSILON);
|
||||
const previous = sceneSeekState(mixed, before, duration, hold);
|
||||
if (
|
||||
seek.shotIndex !== index ||
|
||||
seek.sceneElapsedSec < startElapsedSec ||
|
||||
previous.shotIndex !== Math.max(0, index - 1)
|
||||
)
|
||||
misses.push(`${count}x${flightTenths}/${holdTenths}#${index}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(misses.slice(0, 5), []);
|
||||
});
|
||||
@@ -97,12 +97,23 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Coerces a value to a finite number or returns the fallback.
|
||||
*
|
||||
* Absent, blank and boolean values return the fallback as well. The source
|
||||
* list serializes an unknown number (NaN) as JSON null, and `Number(null)`
|
||||
* is 0, so without this an unknown pose field arrived as zero and was
|
||||
* clamped to the field's floor instead of taking its default.
|
||||
* @param {*} value
|
||||
* @param {number} [fallback=NaN]
|
||||
* @returns {number}
|
||||
*/
|
||||
|
||||
function safeNumber(value, fallback = NaN) {
|
||||
if (
|
||||
value == null ||
|
||||
typeof value === 'boolean' ||
|
||||
(typeof value === 'string' && !value.trim())
|
||||
)
|
||||
return fallback;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,12 @@ import {
|
||||
FRAME_ENDPOINT,
|
||||
MEDIA_ENDPOINT,
|
||||
} from './sourcePolicy.js';
|
||||
const FRAME_SOURCE_KINDS = new Set([
|
||||
'upstream-image',
|
||||
'hls-pull',
|
||||
'streetview',
|
||||
'synthetic',
|
||||
]);
|
||||
function safeNumber(value, fallback = NaN) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
@@ -51,7 +57,7 @@ export function createCctvSource({
|
||||
},
|
||||
getFrameUrl: frameUrlFor,
|
||||
getMediaUrl: mediaUrlFor,
|
||||
/** Read one current frame through the registered frame endpoint. */
|
||||
/** Read a registered frame and its provenance, including fallback frames. */
|
||||
async getFrame(camera, { signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl(frameUrlFor(camera), {
|
||||
@@ -62,7 +68,12 @@ export function createCctvSource({
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
signal?.throwIfAborted();
|
||||
const type = response.headers.get('content-type') || '';
|
||||
return { contentType: type.split(';')[0].trim().toLowerCase(), bytes };
|
||||
const sourceKind = response.headers.get('x-cctv-source');
|
||||
return {
|
||||
contentType: type.split(';')[0].trim().toLowerCase(),
|
||||
bytes,
|
||||
sourceKind: FRAME_SOURCE_KINDS.has(sourceKind) ? sourceKind : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -173,3 +173,26 @@ test('frames are read through the registered frame endpoint', async () => {
|
||||
});
|
||||
await assert.rejects(failing.getFrame(camera), /Camera frame HTTP 502/);
|
||||
});
|
||||
|
||||
test('frame provenance admits the proxy kinds and leaves missing or unknown headers unknown', async () => {
|
||||
for (const kind of [
|
||||
'upstream-image',
|
||||
'hls-pull',
|
||||
'streetview',
|
||||
'synthetic',
|
||||
'other',
|
||||
null,
|
||||
]) {
|
||||
const source = createCctvSource({
|
||||
fetchImpl: async () =>
|
||||
new Response(new Uint8Array([1]), {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
...(kind ? { 'X-CCTV-Source': kind } : {}),
|
||||
},
|
||||
}),
|
||||
});
|
||||
const frame = await source.getFrame(camera);
|
||||
assert.equal(frame.sourceKind, kind === 'other' ? null : kind);
|
||||
}
|
||||
});
|
||||
@@ -114,7 +114,7 @@ export function createQueries({
|
||||
* Build a public descriptor for one aircraft using its best current position
|
||||
* (dead-reckoned when history exists, billboard position otherwise).
|
||||
* @param {string} icao24 - ICAO 24-bit transponder address.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Descriptor with a cloned position, or null if the aircraft is unknown.
|
||||
*/
|
||||
|
||||
@@ -164,6 +164,15 @@ export function createQueries({
|
||||
onGround: info?.onGround === true,
|
||||
velocityMps: displayed.speedMps,
|
||||
track: displayed.trackDeg,
|
||||
// Climb/descent rate, the one kinematic field `mapAnalystRecord` already
|
||||
// published (as `verticalRateMps`) but this descriptor did not, so a
|
||||
// consumer reading the tracked seam had to reach back into `_flightData`
|
||||
// for it. Reported, never derived: `stickyNumber` in records.js keeps the
|
||||
// last value across a blank poll, and an absent rate stays null rather
|
||||
// than becoming a level-flight 0 the aircraft never transmitted.
|
||||
verticalRateMps: Number.isFinite(info?.verticalRate)
|
||||
? info.verticalRate
|
||||
: null,
|
||||
stale: Boolean(
|
||||
flightState.records.missingPolls.get(icao24) ||
|
||||
flightState.feed._backoff,
|
||||
@@ -856,7 +865,7 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Describe the currently tracked aircraft at its dead-reckoned position.
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Tracked aircraft info, or null when nothing is tracked.
|
||||
*/
|
||||
getTrackedInfo() {
|
||||
|
||||
@@ -13,9 +13,4 @@ export const MISSING_POLL_LIMIT = 3;
|
||||
export const ERROR_BACKOFF_INTERVAL = 20000;
|
||||
|
||||
/** Local equirectangular distance used for viewer-proximate floor sampling. */
|
||||
export function approxDistanceKm(lat1, lon1, lat2, lon2) {
|
||||
const dLat = (lat2 - lat1) * 111.32;
|
||||
const dLon =
|
||||
(lon2 - lon1) * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
|
||||
return Math.hypot(dLat, dLon);
|
||||
}
|
||||
export { approxDistanceKm } from '../../data/approxDistance.js';
|
||||
@@ -0,0 +1,18 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
approxDistanceKm,
|
||||
GROUND_FLOOR_CLAMP_RADIUS_KM,
|
||||
} from './recordPolicy.js';
|
||||
|
||||
test('approximate distance takes the short way across the antimeridian', () => {
|
||||
// 0.2° of longitude at Taveuni, Fiji (16.8° S) is about 21 km.
|
||||
for (const [lon1, lon2] of [
|
||||
[179.9, -179.9],
|
||||
[-179.9, 179.9],
|
||||
]) {
|
||||
const km = approxDistanceKm(-16.8, lon1, -16.8, lon2);
|
||||
assert.ok(Math.abs(km - 21.31) < 0.01, `${lon1} → ${lon2}: ${km} km`);
|
||||
assert.ok(km <= GROUND_FLOOR_CLAMP_RADIUS_KM);
|
||||
}
|
||||
});
|
||||
@@ -134,15 +134,16 @@ export function createIngestion({
|
||||
let placesError = null;
|
||||
if (layerState.googleSearchRequested) {
|
||||
layerState.googleSearchRequested = false;
|
||||
// A view across 180° has west > east; its width runs through 180°.
|
||||
const lonSpan = box.east - box.west + (box.east < box.west ? 360 : 0);
|
||||
const latitude = (box.south + box.north) / 2;
|
||||
const longitude = (box.west + box.east) / 2;
|
||||
let longitude = box.west + lonSpan / 2;
|
||||
if (longitude > 180) longitude -= 360;
|
||||
const radiusM = Math.min(
|
||||
50000,
|
||||
Math.max(
|
||||
1000,
|
||||
Math.round(
|
||||
Math.max(box.north - box.south, box.east - box.west) * 55_000,
|
||||
),
|
||||
Math.round(Math.max(box.north - box.south, lonSpan) * 55_000),
|
||||
),
|
||||
);
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
|
||||
// Taveuni, Fiji: Cesium reports a view across 180° with west > east. Each view
|
||||
// is 0.4° wide and 0.2° tall; the last one does not cross 180°.
|
||||
for (const [west, east, centre] of [
|
||||
[179.7, -179.9, 179.9],
|
||||
[179.9, -179.7, -179.9],
|
||||
[179.5, 179.9, 179.7],
|
||||
])
|
||||
test(`a nearby search is centred on the view at ${centre}`, async () => {
|
||||
const box = { south: -17, west, north: -16.8, east };
|
||||
const searches = [];
|
||||
const state = {
|
||||
enabled: true,
|
||||
viewer: {},
|
||||
records: [],
|
||||
googleSearchRequested: true,
|
||||
};
|
||||
const ingestion = createIngestion({
|
||||
state,
|
||||
source: {
|
||||
getMappedSites: async () => ({ records: [], wide: true }),
|
||||
searchNearby: async (query) => {
|
||||
searches.push(query);
|
||||
return { places: [] };
|
||||
},
|
||||
},
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
ground: { resolveGroundFloorCellsBounded: async () => {} },
|
||||
},
|
||||
parts: {
|
||||
viewport: {
|
||||
loadArea: () => ({ box, coverage: {} }),
|
||||
clearUnavailableRetry() {},
|
||||
scheduleUnavailableRetry() {},
|
||||
},
|
||||
model: { installationWithinViewport: () => true },
|
||||
rendering: { renderRecords() {}, warmInstallationFloors() {} },
|
||||
},
|
||||
});
|
||||
await ingestion.loadInstallations();
|
||||
assert.equal(searches.length, 1);
|
||||
const { latitude, longitude, radiusM } = searches[0];
|
||||
assert.ok(Math.abs(latitude + 16.9) < 1e-9);
|
||||
assert.ok(Math.abs(longitude - centre) < 1e-9, `longitude ${longitude}`);
|
||||
// The width, not the height, sets the radius.
|
||||
assert.equal(radiusM, 22000);
|
||||
});
|
||||
@@ -88,7 +88,7 @@ export function createQueries({
|
||||
* Build a public descriptor for one aircraft using its best current position
|
||||
* (dead-reckoned when history exists, billboard position otherwise).
|
||||
* @param {string} icao24 - ICAO hex identifier of the aircraft.
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Descriptor with a cloned position, or null if the aircraft is unknown.
|
||||
*/
|
||||
|
||||
@@ -131,6 +131,13 @@ export function createQueries({
|
||||
onGround: info?.onGround === true,
|
||||
velocityMps: displayed.speedMps,
|
||||
track: displayed.trackDeg,
|
||||
// Same field, same name, same null-when-absent rule as the civil
|
||||
// descriptor — the two layers store the record under different keys
|
||||
// (`verticalRateMps` here, `verticalRate` there), so only the mapping
|
||||
// makes `resolveTrackedAircraftInfo` hand back one shape for both.
|
||||
verticalRateMps: Number.isFinite(info?.verticalRateMps)
|
||||
? info.verticalRateMps
|
||||
: null,
|
||||
stale: Boolean(
|
||||
flightState.records.missingPolls.get(icao24) ||
|
||||
flightState.feed._backoff,
|
||||
@@ -777,7 +784,7 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Describe the currently tracked aircraft at its dead-reckoned position.
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
|
||||
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
|
||||
* Tracked aircraft info, or null when nothing is tracked.
|
||||
*/
|
||||
getTrackedInfo() {
|
||||
|
||||
@@ -39,8 +39,6 @@ export class MilitaryFlightRecords {
|
||||
? prevMeta.altitudeFt * 0.3048
|
||||
: 0
|
||||
: 3048);
|
||||
const track = aircraft.courseDeg || 0;
|
||||
const speedMps = aircraft.speedMps ?? 0;
|
||||
const verticalRateMps = aircraft.verticalRateMps;
|
||||
const callsign = aircraft.callsign;
|
||||
const type = aircraft.typeCode;
|
||||
@@ -148,8 +146,15 @@ export class MilitaryFlightRecords {
|
||||
// altitudeFt/baro).
|
||||
geoAltitudeM,
|
||||
renderAltitudeM,
|
||||
speedMps: stickyNumber(speedMps, prevMeta?.speedMps, null),
|
||||
track: stickyNumber(track, prevMeta?.track, null),
|
||||
// A poll that omits track/speed holds the last values, like the civil
|
||||
// records; 0 only until one is known. A grounded row without a speed
|
||||
// reads 0, so a parked plane never coasts at its landing speed.
|
||||
speedMps: stickyNumber(
|
||||
aircraft.speedMps,
|
||||
onGround ? 0 : prevMeta?.speedMps,
|
||||
0,
|
||||
),
|
||||
track: stickyNumber(aircraft.courseDeg, prevMeta?.track, 0),
|
||||
// Analyst seam (additive): sticky like the other kinematics.
|
||||
verticalRateMps: stickyNumber(
|
||||
verticalRateMps,
|
||||
|
||||
@@ -114,3 +114,39 @@ test('military emergency status follows the latest poll instead of sticking', ()
|
||||
);
|
||||
assert.equal(next.meta.emergency, null);
|
||||
});
|
||||
|
||||
test('military records hold the last track and speed when a poll omits them', () => {
|
||||
const records = store();
|
||||
records.receive(observation({ courseDeg: 270, speedMps: 200 }), context());
|
||||
const missing = records.receive(
|
||||
observation({ courseDeg: null, speedMps: null }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(missing.meta.track, 270);
|
||||
assert.equal(missing.meta.speedMps, 200);
|
||||
const north = records.receive(
|
||||
observation({ courseDeg: 0, speedMps: 0 }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(north.meta.track, 0);
|
||||
assert.equal(north.meta.speedMps, 0);
|
||||
const unseen = store().receive(
|
||||
observation({ courseDeg: undefined, speedMps: undefined }),
|
||||
context(),
|
||||
);
|
||||
assert.equal(unseen.meta.track, 0);
|
||||
assert.equal(unseen.meta.speedMps, 0);
|
||||
const landing = store();
|
||||
landing.receive(observation({ courseDeg: 90, speedMps: 70 }), context());
|
||||
const parked = landing.receive(
|
||||
observation({
|
||||
onGround: true,
|
||||
baroAltitudeM: null,
|
||||
courseDeg: null,
|
||||
speedMps: null,
|
||||
}),
|
||||
context(),
|
||||
);
|
||||
assert.equal(parked.meta.speedMps, 0);
|
||||
assert.equal(parked.meta.track, 90);
|
||||
});
|
||||
@@ -11,20 +11,26 @@ export function containmentAccent(containedPct) {
|
||||
return '#8bc34a';
|
||||
}
|
||||
|
||||
/** Shoelace area (degree², sign dropped) — relative sizes only. */
|
||||
/** Shoelace area along short longitude edges (degree², relative sizes only). */
|
||||
function ringArea(ring) {
|
||||
let sum = 0;
|
||||
for (let i = 0; i < ring.length - 1; i++) {
|
||||
const [x1, y1] = ring[i];
|
||||
const [x2, y2] = ring[i + 1];
|
||||
let [x1, y1] = ring[0];
|
||||
for (let i = 1; i < ring.length; i++) {
|
||||
let delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) delta -= 360;
|
||||
else if (delta < -180) delta += 360;
|
||||
const x2 = x1 + delta;
|
||||
const y2 = ring[i][1];
|
||||
sum += x1 * y2 - x2 * y1;
|
||||
x1 = x2;
|
||||
y1 = y2;
|
||||
}
|
||||
return Math.abs(sum / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor point for the incident card: the centroid of the largest polygon's
|
||||
* outer ring. Degrees, so callers own the Cartesian conversion.
|
||||
* Anchor point for the incident card: the vertex mean of the largest polygon's
|
||||
* outer ring, with circular longitude. Callers own the Cartesian conversion.
|
||||
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
|
||||
* @returns {{lon: number, lat: number}}
|
||||
*/
|
||||
@@ -41,14 +47,17 @@ export function perimeterAnchorDegrees(polygons) {
|
||||
}
|
||||
// Vertex mean over the closed ring (first == last point dropped): perimeters
|
||||
// are compact enough that this stays inside or near the polygon.
|
||||
let lon = 0;
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let lat = 0;
|
||||
const count = best.length - 1;
|
||||
const toRad = Math.PI / 180;
|
||||
for (let i = 0; i < count; i++) {
|
||||
lon += best[i][0];
|
||||
sinLon += Math.sin(best[i][0] * toRad);
|
||||
cosLon += Math.cos(best[i][0] * toRad);
|
||||
lat += best[i][1];
|
||||
}
|
||||
return { lon: lon / count, lat: lat / count };
|
||||
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,12 +16,79 @@ const tiny = [
|
||||
[-107.01, 34.0],
|
||||
];
|
||||
|
||||
test('the card anchors at the centroid of the largest polygon', () => {
|
||||
test('the card anchors at the vertex mean of the largest polygon', () => {
|
||||
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
|
||||
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
|
||||
});
|
||||
|
||||
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
|
||||
const vertices = [
|
||||
[179, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
];
|
||||
for (let start = 0; start < vertices.length; start++) {
|
||||
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
|
||||
for (const points of [rotated, [...rotated].reverse()]) {
|
||||
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
|
||||
for (const boundary of [-180, 180]) {
|
||||
const ring = [
|
||||
[179, 10],
|
||||
[boundary, 10],
|
||||
[-179, 10],
|
||||
[-179, 12],
|
||||
[179, 12],
|
||||
[179, 10],
|
||||
];
|
||||
const anchor = perimeterAnchorDegrees([[ring]]);
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('multipart cards compare polygon areas along short dateline edges', () => {
|
||||
const ordinary = [
|
||||
[10, 20],
|
||||
[11, 20],
|
||||
[11, 21],
|
||||
[10, 21],
|
||||
[10, 20],
|
||||
];
|
||||
for (const width of [0.2, 2]) {
|
||||
const crossing = [
|
||||
[180 - width / 2, 10],
|
||||
[-180 + width / 2, 10],
|
||||
[-180 + width / 2, 10 + width],
|
||||
[180 - width / 2, 10 + width],
|
||||
[180 - width / 2, 10],
|
||||
];
|
||||
for (const ring of [crossing, [...crossing].reverse()]) {
|
||||
for (const polygons of [
|
||||
[[ring], [ordinary]],
|
||||
[[ordinary], [ring]],
|
||||
]) {
|
||||
const anchor = perimeterAnchorDegrees(polygons);
|
||||
if (width < 1) {
|
||||
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
|
||||
} else {
|
||||
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
|
||||
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a full incident row renders name, size, containment, and ages', () => {
|
||||
const now = 1758000000000;
|
||||
const card = buildIncidentCard(
|
||||
|
||||
@@ -97,6 +97,8 @@ export function createGoogleViewer({ loader, getService, render } = {}) {
|
||||
service ||= getService
|
||||
? await getService()
|
||||
: new (await ensureLibrary()).StreetViewService();
|
||||
if (!current())
|
||||
throw new Error('Street View details lookup was released');
|
||||
return service.getPanorama({ pano: panoId });
|
||||
})().then(resolve, reject);
|
||||
});
|
||||
@@ -236,6 +238,7 @@ export function createGoogleViewer({ loader, getService, render } = {}) {
|
||||
const panoId = String(imageId);
|
||||
if (!host) throw new Error('Street View is not mounted');
|
||||
if (loader.authFailed()) throw new Error(KEY_REJECTED_MESSAGE);
|
||||
cancelShown?.();
|
||||
pendingOpen = panoId;
|
||||
const instance = await ensurePanorama(host);
|
||||
if (pendingOpen !== panoId) return;
|
||||
|
||||
@@ -403,3 +403,69 @@ test('a remount looks up again a panorama whose lookup hung', async () => {
|
||||
await settle();
|
||||
assert.equal(poses.length, count);
|
||||
});
|
||||
|
||||
test('superseded panorama waits cannot steal the current close cleanup', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const { OPEN_TIMEOUT_MS } = await import('./policy.js');
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
};
|
||||
const { fake, loader, viewer, host } = setup();
|
||||
await viewer.mount(host);
|
||||
const [panorama] = fake.built;
|
||||
panorama.setPano = (id) => {
|
||||
panorama.pano = id;
|
||||
};
|
||||
const first = viewer.open('pano-a');
|
||||
await flush();
|
||||
const second = viewer.open('pano-b');
|
||||
await flush();
|
||||
panorama.fire('position_changed'); // new panorama has not reached OK
|
||||
await flush();
|
||||
viewer.close();
|
||||
const remaining = loader.listenerCount();
|
||||
t.mock.timers.tick(OPEN_TIMEOUT_MS);
|
||||
await Promise.allSettled([first, second]);
|
||||
assert.equal(
|
||||
remaining,
|
||||
0,
|
||||
'close disposes every pending open without waiting 20 seconds',
|
||||
);
|
||||
assert.equal(panorama.visible, false);
|
||||
});
|
||||
|
||||
test('unmount during details-service acquisition makes no later billed lookup', async () => {
|
||||
const fake = fakeStreetViewLibrary({ panoramas: PANORAMAS });
|
||||
const loader = fakeMapsLoader(fake.library);
|
||||
const { createGoogleProvider } = await import('./index.js');
|
||||
let release;
|
||||
const acquiring = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const importLibrary = loader.importLibrary.bind(loader);
|
||||
let imports = 0;
|
||||
loader.importLibrary = async (name) => {
|
||||
if (++imports > 1) await acquiring;
|
||||
return importLibrary(name);
|
||||
};
|
||||
const provider = createGoogleProvider({
|
||||
getApiKey: () => 'fixture-key',
|
||||
loader,
|
||||
});
|
||||
const instance = provider.create({
|
||||
notify() {},
|
||||
actions: { reportError() {} },
|
||||
});
|
||||
const viewer = instance.viewer;
|
||||
await viewer.mount(fakeHost());
|
||||
await viewer.open('pano-a');
|
||||
viewer.unmount();
|
||||
release();
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
assert.equal(
|
||||
fake.lookups.length,
|
||||
0,
|
||||
'teardown invalidates the request before calling getPanorama',
|
||||
);
|
||||
instance.destroy();
|
||||
});
|
||||
+191
-8
@@ -9,6 +9,18 @@ import { acquireImageryComparison } from './imageryComparison.js';
|
||||
*/
|
||||
const AUTOMATIC = Symbol('automatic switch');
|
||||
|
||||
/** Background retries of a fallback in use back off from 30 s to 10 min. */
|
||||
const FALLBACK_RETRY_MS = 30_000;
|
||||
const FALLBACK_RETRY_MAX_MS = 600_000;
|
||||
/** A retry attempt still unsettled after a minute counts as failed. */
|
||||
const FALLBACK_ATTEMPT_MS = 60_000;
|
||||
|
||||
const resolved = (provider, effectiveStackId) => ({
|
||||
provider,
|
||||
effectiveStackId,
|
||||
fallbackMessage: null,
|
||||
});
|
||||
|
||||
/** Coordinate source lifetimes and scene changes; the registry owns provider choices. */
|
||||
export class MapSourceController {
|
||||
constructor(
|
||||
@@ -46,8 +58,18 @@ export class MapSourceController {
|
||||
this._lastError = null;
|
||||
this._imageryLayer = null;
|
||||
this._activeImageryProvider = null;
|
||||
this._activeResolution = null;
|
||||
this._removeImageryErrorListener = null;
|
||||
this._terrainMode = null;
|
||||
this._terrainFallback = null;
|
||||
this._retryTimer = null;
|
||||
this._retrying = false;
|
||||
this._retryRequested = false;
|
||||
this._retryDelay = FALLBACK_RETRY_MS;
|
||||
/** Expire callbacks of retry attempts in flight; destroy() runs them. */
|
||||
this._retryDeadlines = new Set();
|
||||
/** A fallback terrain a retry replaced while it stayed installed. */
|
||||
this._replacedTerrain = null;
|
||||
this._subscribers = new Set();
|
||||
this._destroyed = false;
|
||||
}
|
||||
@@ -285,21 +307,171 @@ export class MapSourceController {
|
||||
this._showTileset(null);
|
||||
this.viewer.scene.globe.show = true;
|
||||
this._activeId = resolution.effectiveStackId;
|
||||
this._activeResolution = resolution;
|
||||
if (source?.terrain && source.terrain.id !== this._terrainMode) {
|
||||
const terrain = source.terrain;
|
||||
const result = await this._cached(
|
||||
this._terrainProviders,
|
||||
terrain.id,
|
||||
() => terrain.create({ signal: this._abort.signal }),
|
||||
const pending = this._cached(this._terrainProviders, terrain.id, () =>
|
||||
terrain.create({ signal: this._abort.signal }),
|
||||
);
|
||||
let result = await pending;
|
||||
if (gen !== this._switchGen) return;
|
||||
if (result.terrain) this.viewer.scene.setTerrain(result.terrain);
|
||||
else this.viewer.terrainProvider = result.provider;
|
||||
// A background retry may have replaced a fallback while this waited.
|
||||
const latest = this._terrainProviders.get(terrain.id);
|
||||
if (latest !== pending) result = await latest;
|
||||
if (gen !== this._switchGen) return;
|
||||
this._applyTerrain(result);
|
||||
this._terrainMode = terrain.id;
|
||||
}
|
||||
if (resolution.fallbackFor || this._terrainFallback) this._scheduleRetry();
|
||||
return resolution;
|
||||
}
|
||||
|
||||
_applyTerrain(result) {
|
||||
if (result.terrain) this.viewer.scene.setTerrain(result.terrain);
|
||||
else this.viewer.terrainProvider = result.provider;
|
||||
this._terrainFallback = result.fallback ? result : null;
|
||||
if (this._replacedTerrain && this._replacedTerrain !== result) {
|
||||
this._dispose(this._replacedTerrain.provider);
|
||||
this._replacedTerrain = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One timer retries the real provider behind whichever fallback is on
|
||||
* screen: Esri's OSM stand-in, or flat terrain on a shown globe. Fallbacks
|
||||
* stay cached and shown meanwhile, so no switch waits on a retry; a
|
||||
* fallback out of use is left alone until an activation shows it again.
|
||||
* One retry runs at a time; a request made meanwhile re-arms once it ends.
|
||||
*/
|
||||
_scheduleRetry() {
|
||||
if (this._retryTimer || this._destroyed) return;
|
||||
if (this._retrying) {
|
||||
this._retryRequested = true;
|
||||
return;
|
||||
}
|
||||
this._retryTimer = setTimeout(() => {
|
||||
this._retryTimer = null;
|
||||
void this._retryFallbacks();
|
||||
}, this._retryDelay);
|
||||
}
|
||||
|
||||
async _retryFallbacks() {
|
||||
const resolution = this._activeResolution;
|
||||
const flat = this.viewer.scene.globe.show ? this._terrainFallback : null;
|
||||
const id = resolution?.fallbackFor;
|
||||
let terrain = flat && this._sources.get(this._activeId)?.terrain;
|
||||
if (terrain?.id !== this._terrainMode) terrain = null;
|
||||
if (!id && !terrain) return;
|
||||
this._retrying = true;
|
||||
this._retryRequested = false;
|
||||
// An attempt that outlives its deadline counts as a failure. Its signal is
|
||||
// aborted, but the Esri and keyless factories ignore it and Cesium's
|
||||
// requests have no timeout, so a late result is released, never used.
|
||||
const attempt = async (create, release) => {
|
||||
const expiry = new AbortController();
|
||||
let expire;
|
||||
const deadline = new Promise((resolve) => {
|
||||
expire = () => {
|
||||
clearTimeout(timer);
|
||||
resolve(expiry);
|
||||
};
|
||||
});
|
||||
const timer = setTimeout(expire, FALLBACK_ATTEMPT_MS);
|
||||
this._retryDeadlines.add(expire);
|
||||
const pending = Promise.resolve().then(() =>
|
||||
create?.({
|
||||
signal: AbortSignal.any([this._abort.signal, expiry.signal]),
|
||||
}),
|
||||
);
|
||||
try {
|
||||
const result = await Promise.race([pending, deadline]);
|
||||
if (result !== expiry) return result;
|
||||
expiry.abort();
|
||||
pending.then(release, () => {});
|
||||
return null;
|
||||
} catch {
|
||||
return null; // Still unavailable: keep the fallback.
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this._retryDeadlines.delete(expire);
|
||||
}
|
||||
};
|
||||
// Each recovers as soon as it loads, never waiting on the other.
|
||||
const retryImagery = async () => {
|
||||
const cached = this._imageryProviders.get(id);
|
||||
const provider = await attempt(this._sources.get(id).imagery, (late) =>
|
||||
this._dispose(late),
|
||||
);
|
||||
// Obsolete: destroyed, or the cache moved on while this was in flight.
|
||||
if (this._destroyed || this._imageryProviders.get(id) !== cached) {
|
||||
this._dispose(provider);
|
||||
return true;
|
||||
}
|
||||
if (!provider) return false;
|
||||
this._imageryProviders.set(id, Promise.resolve(resolved(provider, id)));
|
||||
// Still showing the fallback once any switch settles: use the real one.
|
||||
const recover = () => {
|
||||
if (this._activeResolution === resolution)
|
||||
void this.setStack(id, { [AUTOMATIC]: true });
|
||||
};
|
||||
if (!this._isSwitching) recover();
|
||||
else {
|
||||
const stop = this.subscribe(() => {
|
||||
stop();
|
||||
recover();
|
||||
});
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const retryTerrain = async () => {
|
||||
const cached = this._terrainProviders.get(terrain.id);
|
||||
const real = await attempt(terrain.create, (late) =>
|
||||
this._dispose(late?.provider),
|
||||
);
|
||||
if (
|
||||
this._destroyed ||
|
||||
this._terrainProviders.get(terrain.id) !== cached ||
|
||||
!real ||
|
||||
real.fallback
|
||||
) {
|
||||
this._dispose(real?.provider);
|
||||
return Boolean(real && !real.fallback);
|
||||
}
|
||||
this._terrainProviders.set(terrain.id, Promise.resolve(real));
|
||||
if (this._terrainFallback === flat && this.viewer.scene.globe.show) {
|
||||
this._applyTerrain(real);
|
||||
this._dispose(flat.provider);
|
||||
this._requestRender('map-stack');
|
||||
} else {
|
||||
this._terrainMode = null; // The next globe activation installs it.
|
||||
// Release the replaced fallback once nothing shows it.
|
||||
if (this._terrainFallback === flat) this._replacedTerrain = flat;
|
||||
else this._dispose(flat.provider);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const settled = (retry) =>
|
||||
retry().catch((error) => {
|
||||
console.warn('[MapSourceController] fallback recovery failed:', error);
|
||||
return false;
|
||||
});
|
||||
let failed = false;
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
id && settled(retryImagery),
|
||||
terrain && settled(retryTerrain),
|
||||
]);
|
||||
failed = results.includes(false);
|
||||
} finally {
|
||||
this._retrying = false;
|
||||
}
|
||||
if (this._destroyed) return;
|
||||
this._retryDelay = failed
|
||||
? Math.min(this._retryDelay * 2, FALLBACK_RETRY_MAX_MS)
|
||||
: FALLBACK_RETRY_MS;
|
||||
if (failed || this._retryRequested) this._scheduleRetry();
|
||||
}
|
||||
|
||||
_cached(cache, id, create) {
|
||||
if (cache.has(id)) return cache.get(id);
|
||||
const promise = Promise.resolve()
|
||||
@@ -323,7 +495,7 @@ export class MapSourceController {
|
||||
try {
|
||||
const provider = await source.imagery({ signal: this._abort.signal });
|
||||
if (this._destroyed) this._dispose(provider);
|
||||
return { provider, effectiveStackId: stack.id, fallbackMessage: null };
|
||||
return resolved(provider, stack.id);
|
||||
} catch (error) {
|
||||
const fallback = source.constructionFallback;
|
||||
if (this._destroyed || !fallback || !this.isStackAvailable(fallback.id))
|
||||
@@ -333,7 +505,11 @@ export class MapSourceController {
|
||||
this.getStack(fallback.id),
|
||||
next,
|
||||
);
|
||||
return { ...resolution, fallbackMessage: fallback.message };
|
||||
return {
|
||||
...resolution,
|
||||
fallbackMessage: fallback.message,
|
||||
fallbackFor: stack.id,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -388,6 +564,7 @@ export class MapSourceController {
|
||||
this.viewer.imageryLayers.remove(this._imageryLayer, true);
|
||||
this._imageryLayer = null;
|
||||
this._activeImageryProvider = null;
|
||||
this._activeResolution = null;
|
||||
}
|
||||
_dispose(value) {
|
||||
if (!value || this._disposed.has(value)) return;
|
||||
@@ -401,6 +578,12 @@ export class MapSourceController {
|
||||
this._subscribers.clear();
|
||||
this._switchGen++;
|
||||
this._abort.abort();
|
||||
clearTimeout(this._retryTimer);
|
||||
for (const expire of this._retryDeadlines) expire();
|
||||
this._retryDeadlines.clear();
|
||||
this._retrying = false;
|
||||
this._dispose(this._replacedTerrain?.provider);
|
||||
this._replacedTerrain = null;
|
||||
this._isSwitching = false;
|
||||
this._removeImageryLayer();
|
||||
this._credits.destroy();
|
||||
|
||||
@@ -70,7 +70,7 @@ const settle = async () => {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
};
|
||||
const descriptor = (id) => ({ id, label: id, kind: 'imagery' });
|
||||
function publicFixture() {
|
||||
function publicFixture(options) {
|
||||
const tileset = { show: true };
|
||||
const registry = createDefaultMapSources({ googleTileset: tileset });
|
||||
const providers = new Map();
|
||||
@@ -84,7 +84,7 @@ function publicFixture() {
|
||||
create: async () => ({ provider: { id: 'terrain' } }),
|
||||
};
|
||||
}
|
||||
return { ...fixture(registry), registry, providers, tileset };
|
||||
return { ...fixture(registry, options), registry, providers, tileset };
|
||||
}
|
||||
|
||||
test('an additional imagery source needs no controller branch and owns its cached resources', async () => {
|
||||
@@ -839,3 +839,546 @@ test('each switch generation reports its origin: an outside setStack is manual,
|
||||
]);
|
||||
recovering.controller.destroy();
|
||||
});
|
||||
|
||||
function failingEsri(env) {
|
||||
const esri = { failing: true, attempts: 0, next: null };
|
||||
env.registry.sources.find(
|
||||
(source) => source.descriptor.id === 'esri-imagery',
|
||||
).imagery = async () => {
|
||||
esri.attempts++;
|
||||
if (esri.next) await esri.next;
|
||||
if (esri.failing) throw new Error('Esri unreachable');
|
||||
return env.providers.get('esri-imagery');
|
||||
};
|
||||
return esri;
|
||||
}
|
||||
const deferred = () => {
|
||||
let resolve;
|
||||
const promise = new Promise((done) => (resolve = done));
|
||||
return { promise, resolve };
|
||||
};
|
||||
|
||||
test('a failed Esri construction shows OSM at once, backs off while retries fail, and recovers in place', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(env.controller.getActiveId(), 'osm');
|
||||
const osmLayer = env.imagery.at(-1);
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'one background retry');
|
||||
assert.equal(env.imagery.at(-1), osmLayer, 'a failed retry keeps the layer');
|
||||
await env.controller.setStack('osm');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(esri.attempts, 2, 'a reselection does not retry at once');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'the second retry waits twice as long');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 3);
|
||||
esri.failing = false;
|
||||
t.mock.timers.tick(120_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 4);
|
||||
assert.equal(env.controller.getActiveId(), 'esri-imagery');
|
||||
assert.equal(env.controller.getSwitchOrigin(), 'automatic');
|
||||
assert.equal(env.controller.getState().lastError, null);
|
||||
assert.equal(env.imagery.at(-1).provider, env.providers.get('esri-imagery'));
|
||||
t.mock.timers.tick(600_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 4, 'the real provider ends the retries');
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('retries of a fallback that keeps failing back off to a 10 minute cap', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
for (const delay of [30, 60, 120, 240, 480, 600, 600]) {
|
||||
t.mock.timers.tick(delay * 1000);
|
||||
await settle();
|
||||
}
|
||||
assert.equal(esri.attempts, 8);
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('Esri is retried only while its fallback is shown', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
await env.controller.setStack('osm');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 1, 'no retry while OSM was chosen');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(esri.attempts, 1, 'the cached fallback shows at once');
|
||||
assert.equal(env.controller.getActiveId(), 'osm');
|
||||
esri.failing = false;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2);
|
||||
assert.equal(env.controller.getActiveId(), 'esri-imagery');
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('an Esri recovery that lands mid-switch applies once the switch settles', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
const retry = deferred();
|
||||
esri.next = retry.promise;
|
||||
esri.failing = false;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
// The fallback activates OSM's terrain; make that switch slow.
|
||||
const slow = deferred();
|
||||
env.registry.sources.find(
|
||||
(source) => source.descriptor.id === 'osm',
|
||||
).terrain = { id: 'slow', create: () => slow.promise };
|
||||
const switching = env.controller.setStack('esri-imagery');
|
||||
retry.resolve();
|
||||
await settle();
|
||||
assert.equal(env.controller.getActiveId(), 'osm', 'the switch is still open');
|
||||
slow.resolve({ provider: { id: 'slow' } });
|
||||
await switching;
|
||||
await settle();
|
||||
assert.equal(env.controller.getActiveId(), 'esri-imagery');
|
||||
assert.equal(env.imagery.at(-1).provider, env.providers.get('esri-imagery'));
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
function terrainFixture(t, create) {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let renders = 0;
|
||||
const env = publicFixture({ requestRender: () => renders++ });
|
||||
const installed = [];
|
||||
Object.defineProperty(env.viewer, 'terrainProvider', {
|
||||
get: () => installed.at(-1),
|
||||
set: (provider) => installed.push(provider),
|
||||
});
|
||||
const terrain = { id: 'keyless', calls: 0 };
|
||||
terrain.create = () => create(++terrain.calls);
|
||||
for (const source of env.registry.sources)
|
||||
if (source.imagery) source.terrain = terrain;
|
||||
return { env, installed, terrain, renders: () => renders };
|
||||
}
|
||||
const flatTerrain = (n) => ({ provider: { id: `flat-${n}` }, fallback: true });
|
||||
|
||||
test('flat fallback terrain stays installed while retries run, and real terrain replaces it live', async (t) => {
|
||||
const real = { id: 'real' };
|
||||
let working = false;
|
||||
const { env, installed, terrain, renders } = terrainFixture(t, async (n) =>
|
||||
working ? { provider: real } : flatTerrain(n),
|
||||
);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
const [flat] = installed;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 2, 'one background retry');
|
||||
await env.controller.setStack('osm');
|
||||
assert.deepEqual(installed, [flat], 'failed retries and switches keep it');
|
||||
working = true;
|
||||
const before = renders();
|
||||
t.mock.timers.tick(60_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 3);
|
||||
assert.deepEqual(installed, [flat, real]);
|
||||
assert.equal(renders(), before + 1, 'the live swap requests a render');
|
||||
t.mock.timers.tick(600_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 3, 'the real terrain ends the retries');
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('terrain is not retried or installed while a 3D tileset hides the globe', async (t) => {
|
||||
const real = { id: 'real' };
|
||||
let working = false;
|
||||
const { env, installed, terrain } = terrainFixture(t, async (n) =>
|
||||
working ? { provider: real } : flatTerrain(n),
|
||||
);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
await env.controller.setStack('photoreal');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 1, 'no retry behind a hidden globe');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
const hidden = deferred();
|
||||
terrain.create = async () => {
|
||||
terrain.calls++;
|
||||
await hidden.promise;
|
||||
return { provider: real };
|
||||
};
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 2, 'the globe activation re-arms the retry');
|
||||
await env.controller.setStack('photoreal');
|
||||
hidden.resolve();
|
||||
await settle();
|
||||
assert.equal(installed.length, 1, 'nothing is installed behind a tileset');
|
||||
await env.controller.setStack('osm');
|
||||
assert.equal(installed.at(-1), real, 'the next globe activation installs it');
|
||||
assert.equal(terrain.calls, 2);
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('a switch that read the flat fallback installs the terrain a retry just cached', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
// Sweep the microtask distance between the retry landing and the switch.
|
||||
for (let hops = 0; hops < 12; hops++) {
|
||||
const real = { id: 'real' },
|
||||
gate = deferred();
|
||||
const keyless = {
|
||||
id: 'keyless',
|
||||
create: async () => {
|
||||
if (!keyless.retried) return flatTerrain(1);
|
||||
await gate.promise;
|
||||
return { provider: real };
|
||||
},
|
||||
};
|
||||
const other = { id: 'other', create: async () => ({ provider: {} }) };
|
||||
const source = (id, terrain) => ({
|
||||
descriptor: descriptor(id),
|
||||
imagery: async () => ({ id }),
|
||||
terrain,
|
||||
});
|
||||
const env = fixture({
|
||||
defaultId: 'a',
|
||||
sources: [source('a', keyless), source('c', other)],
|
||||
});
|
||||
const installed = [];
|
||||
Object.defineProperty(env.viewer, 'terrainProvider', {
|
||||
get: () => installed.at(-1),
|
||||
set: (provider) => installed.push(provider),
|
||||
});
|
||||
await env.controller.setStack('a');
|
||||
keyless.retried = true;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
await env.controller.setStack('c');
|
||||
gate.resolve();
|
||||
for (let i = 0; i < hops; i++) await null;
|
||||
await env.controller.setStack('a');
|
||||
await settle();
|
||||
assert.equal(installed.at(-1), real, `hops ${hops}`);
|
||||
env.controller.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('destroy cancels a pending retry and releases one in flight', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
env.controller.destroy();
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 1, 'a pending retry is cancelled');
|
||||
|
||||
const late = publicFixture();
|
||||
const lateEsri = failingEsri(late);
|
||||
await late.controller.setStack('esri-imagery');
|
||||
const retry = deferred();
|
||||
lateEsri.next = retry.promise;
|
||||
lateEsri.failing = false;
|
||||
let destroyed = 0;
|
||||
late.providers.get('esri-imagery').destroy = () => destroyed++;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
late.controller.destroy();
|
||||
retry.resolve();
|
||||
await settle();
|
||||
assert.equal(destroyed, 1, 'a late provider is released');
|
||||
assert.equal(late.imagery.length, 0);
|
||||
t.mock.timers.tick(600_000);
|
||||
await settle();
|
||||
assert.equal(lateEsri.attempts, 2);
|
||||
});
|
||||
|
||||
test('retries stay single-flight when an activation re-shows the fallback mid-retry', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const created = [],
|
||||
pending = [];
|
||||
let attempts = 0;
|
||||
env.registry.sources.find(
|
||||
(source) => source.descriptor.id === 'esri-imagery',
|
||||
).imagery = async () => {
|
||||
if (++attempts === 1) throw new Error('Esri unreachable');
|
||||
const gate = deferred();
|
||||
pending.push(gate);
|
||||
await gate.promise;
|
||||
const provider = { id: `esri-${attempts}`, errorEvent: event() };
|
||||
provider.destroy = () => (provider.destroyed = true);
|
||||
created.push(provider);
|
||||
return provider;
|
||||
};
|
||||
await env.controller.setStack('esri-imagery');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(attempts, 2, 'retry #1 is in flight');
|
||||
await env.controller.setStack('osm');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(env.controller.getActiveId(), 'osm', 'the fallback is shown');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(attempts, 2, 'no second retry while one is in flight');
|
||||
for (const gate of pending.reverse()) {
|
||||
gate.resolve();
|
||||
await settle();
|
||||
}
|
||||
const shown = env.imagery.at(-1).provider;
|
||||
assert.equal(env.controller.getActiveId(), 'esri-imagery');
|
||||
await env.controller.setStack('osm');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(env.imagery.at(-1).provider, shown, 'the cached one is shown');
|
||||
env.controller.destroy();
|
||||
await settle();
|
||||
assert.ok(created.length > 0);
|
||||
for (const provider of created)
|
||||
assert.equal(provider.destroyed, true, `${provider.id} is disposed`);
|
||||
});
|
||||
|
||||
test('a stalled terrain retry does not hold back recovered imagery', async (t) => {
|
||||
const stalled = deferred();
|
||||
const { env, terrain } = terrainFixture(t, async (n) => {
|
||||
if (n > 1) await stalled.promise;
|
||||
return flatTerrain(n);
|
||||
});
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(env.controller.getActiveId(), 'osm');
|
||||
esri.failing = false;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(terrain.calls, 2, 'the terrain retry is in flight');
|
||||
assert.equal(env.controller.getActiveId(), 'esri-imagery');
|
||||
assert.equal(env.imagery.at(-1).provider, env.providers.get('esri-imagery'));
|
||||
stalled.resolve();
|
||||
await settle();
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('a stalled imagery retry does not hold back recovered terrain', async (t) => {
|
||||
const real = { id: 'real' };
|
||||
const { env, installed } = terrainFixture(t, async (n) =>
|
||||
n > 1 ? { provider: real } : flatTerrain(n),
|
||||
);
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
const stalled = deferred();
|
||||
esri.next = stalled.promise;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'the imagery retry is in flight');
|
||||
assert.equal(installed.at(-1), real, 'real terrain is installed');
|
||||
stalled.resolve();
|
||||
await settle();
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('a retry attempt that never settles is abandoned at its deadline and released if it lands late', async (t) => {
|
||||
const hung = deferred();
|
||||
const late = { id: 'late', destroy: () => (late.destroyed = true) };
|
||||
const { env, installed, terrain } = terrainFixture(t, async (n) => {
|
||||
if (n === 2) await hung.promise;
|
||||
return n === 2 ? { provider: late } : flatTerrain(n);
|
||||
});
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'imagery failed');
|
||||
assert.equal(terrain.calls, 2, 'terrain hangs');
|
||||
t.mock.timers.tick(60_000); // The hung attempt's deadline.
|
||||
await settle();
|
||||
t.mock.timers.tick(60_000); // The doubled backoff.
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 3, 'imagery is retried again');
|
||||
assert.equal(terrain.calls, 3, 'terrain is retried again');
|
||||
hung.resolve();
|
||||
await settle();
|
||||
assert.equal(late.destroyed, true, 'the late provider is released');
|
||||
assert.ok(!installed.includes(late), 'and never installed');
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('a failed retry after a mid-retry re-show re-arms once, after the doubled delay', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
const gate = deferred();
|
||||
esri.next = gate.promise;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
await env.controller.setStack('osm');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
gate.resolve();
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2);
|
||||
t.mock.timers.tick(59_999);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'not before the doubled delay');
|
||||
t.mock.timers.tick(1);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 3, 'one retry after it');
|
||||
t.mock.timers.tick(119_999);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 3, 'no second timer was armed');
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('destroy releases recovered imagery and terrain that lands afterwards', async (t) => {
|
||||
const stalled = deferred();
|
||||
const real = { id: 'real', destroy: () => (real.destroyed = true) };
|
||||
const { env, installed } = terrainFixture(t, async (n) => {
|
||||
if (n === 1) return flatTerrain(n);
|
||||
await stalled.promise;
|
||||
return { provider: real };
|
||||
});
|
||||
const esri = failingEsri(env);
|
||||
const imagery = env.providers.get('esri-imagery');
|
||||
imagery.destroy = () => (imagery.destroyed = true);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
esri.failing = false;
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(env.imagery.at(-1).provider, imagery, 'imagery has landed');
|
||||
env.controller.destroy();
|
||||
stalled.resolve();
|
||||
await settle();
|
||||
assert.equal(imagery.destroyed, true);
|
||||
assert.equal(real.destroyed, true);
|
||||
assert.ok(!installed.includes(real));
|
||||
});
|
||||
|
||||
function liveTimers(t) {
|
||||
const live = new Set();
|
||||
const { setTimeout: set, clearTimeout: clear } = globalThis;
|
||||
globalThis.setTimeout = (fn, ms, ...args) => {
|
||||
const id = set(
|
||||
(...values) => {
|
||||
live.delete(id);
|
||||
fn(...values);
|
||||
},
|
||||
ms,
|
||||
...args,
|
||||
);
|
||||
live.add(id);
|
||||
return id;
|
||||
};
|
||||
globalThis.clearTimeout = (id) => {
|
||||
live.delete(id);
|
||||
clear(id);
|
||||
};
|
||||
t.after(() =>
|
||||
Object.assign(globalThis, { setTimeout: set, clearTimeout: clear }),
|
||||
);
|
||||
return live;
|
||||
}
|
||||
|
||||
test('destroy during a hung retry attempt clears its deadline at once', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const live = liveTimers(t);
|
||||
const env = publicFixture();
|
||||
const esri = failingEsri(env);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
esri.next = new Promise(() => {});
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(esri.attempts, 2, 'the attempt hangs');
|
||||
assert.equal(live.size, 1, 'only its deadline is armed');
|
||||
env.controller.destroy();
|
||||
assert.equal(live.size, 0, 'destroy clears the deadline');
|
||||
assert.equal(env.controller._retrying, false);
|
||||
await settle();
|
||||
assert.equal(live.size, 0, 'and nothing re-arms');
|
||||
});
|
||||
|
||||
function destroyableFlat(n) {
|
||||
const provider = { id: `flat-${n}` };
|
||||
provider.destroy = () => (provider.destroyed = true);
|
||||
return { provider, fallback: true };
|
||||
}
|
||||
|
||||
test('terrain recovered on screen releases the fallback it replaced', async (t) => {
|
||||
const real = { id: 'real' };
|
||||
let flat;
|
||||
const { env, installed } = terrainFixture(t, async (n) =>
|
||||
n === 1 ? (flat = destroyableFlat(n)) : { provider: real },
|
||||
);
|
||||
await env.controller.setStack('esri-imagery');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
assert.equal(installed.at(-1), real);
|
||||
assert.equal(flat.provider.destroyed, true);
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('terrain recovered behind a tileset releases the fallback once a globe replaces it', async (t) => {
|
||||
const real = { id: 'real' };
|
||||
const gate = deferred();
|
||||
let flat;
|
||||
const { env, installed } = terrainFixture(t, async (n) => {
|
||||
if (n === 1) return (flat = destroyableFlat(n));
|
||||
await gate.promise;
|
||||
return { provider: real };
|
||||
});
|
||||
await env.controller.setStack('esri-imagery');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
await env.controller.setStack('photoreal');
|
||||
gate.resolve();
|
||||
await settle();
|
||||
assert.equal(installed.at(-1), flat.provider);
|
||||
assert.ok(!flat.provider.destroyed, 'still installed behind the tileset');
|
||||
await env.controller.setStack('osm');
|
||||
assert.equal(installed.at(-1), real);
|
||||
assert.equal(flat.provider.destroyed, true);
|
||||
env.controller.destroy();
|
||||
});
|
||||
|
||||
test('a hung imagery attempt that lands after its deadline is released, never cached or shown', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const env = publicFixture();
|
||||
const hung = deferred();
|
||||
const late = { id: 'late', errorEvent: event() };
|
||||
const good = { id: 'good', errorEvent: event() };
|
||||
for (const provider of [late, good])
|
||||
provider.destroy = () => (provider.destroyed = true);
|
||||
let attempts = 0;
|
||||
env.registry.sources.find(
|
||||
(source) => source.descriptor.id === 'esri-imagery',
|
||||
).imagery = async () => {
|
||||
if (++attempts === 1) throw new Error('Esri unreachable');
|
||||
if (attempts === 2) {
|
||||
await hung.promise;
|
||||
return late;
|
||||
}
|
||||
return good;
|
||||
};
|
||||
await env.controller.setStack('esri-imagery');
|
||||
t.mock.timers.tick(30_000);
|
||||
await settle();
|
||||
t.mock.timers.tick(60_000); // The deadline.
|
||||
await settle();
|
||||
hung.resolve();
|
||||
await settle();
|
||||
assert.equal(late.destroyed, true, 'the late provider is released');
|
||||
assert.equal(env.controller.getActiveId(), 'osm', 'and not shown');
|
||||
t.mock.timers.tick(60_000);
|
||||
await settle();
|
||||
assert.equal(attempts, 3);
|
||||
assert.equal(env.imagery.at(-1).provider, good, 'the next retry installs');
|
||||
await env.controller.setStack('osm');
|
||||
await env.controller.setStack('esri-imagery');
|
||||
assert.equal(env.imagery.at(-1).provider, good, 'only its own is cached');
|
||||
env.controller.destroy();
|
||||
await settle();
|
||||
assert.equal(good.destroyed, true);
|
||||
});
|
||||
@@ -317,3 +317,13 @@ test('both Google 3D routes keep tiles drawing while draped imagery loads', asyn
|
||||
assert.equal(calls[1][1].asynchronouslyLoadImagery, true);
|
||||
assert.equal(calls[1][1].enableCollision, true);
|
||||
});
|
||||
|
||||
test('unreachable keyless terrain falls back to flat terrain marked as a fallback', async (t) => {
|
||||
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async () => {
|
||||
throw new Error('layer.json unreachable');
|
||||
});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const result = await createKeylessTerrain();
|
||||
assert.ok(result.provider instanceof Cesium.EllipsoidTerrainProvider);
|
||||
assert.equal(result.fallback, true);
|
||||
});
|
||||
+1
-1
@@ -59,6 +59,6 @@ export async function createKeylessTerrain() {
|
||||
'[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain:',
|
||||
error,
|
||||
);
|
||||
return { provider: new Cesium.EllipsoidTerrainProvider() };
|
||||
return { provider: new Cesium.EllipsoidTerrainProvider(), fallback: true };
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,32 @@ test('production reader rejects oversized, malformed and runtime-failure bodies'
|
||||
}
|
||||
});
|
||||
|
||||
test('element data that mentions a failure phrase is data, and sets no cooldown', async () => {
|
||||
const names = ['Timed Out Escape Rooms', 'Runtime Error Bar', 'Out of Memory Lane', 'Too Many Requests Cafe', 'rate_limited'];
|
||||
for (const [i, name] of names.entries()) {
|
||||
const body = JSON.stringify({ elements: [{ type: 'node', id: 1, lat: 1, lon: 2, tags: { name } }] });
|
||||
let count = 0;
|
||||
const options = { endpoints: [`https://phrase-${i}.example/`], fetchImpl: async () => {
|
||||
count++; return new Response(body);
|
||||
} };
|
||||
const payload = await fetchOverpassPayload('first', 1024, options);
|
||||
assert.equal(payload.status, 200, name);
|
||||
assert.ok(overpassPayloadIsData(payload), name);
|
||||
assert.ok(payload.body.includes(name), name);
|
||||
await fetchOverpassPayload('different', 1024, options);
|
||||
assert.equal(count, 2, name);
|
||||
}
|
||||
const remark = JSON.stringify({ elements: [], remark: 'runtime error: rate_limited' });
|
||||
const limited = await fetchOverpassPayload('x', 1024, { endpoints: ['https://remark.example/'],
|
||||
fetchImpl: async () => new Response(remark, { headers: { 'Retry-After': '90' } }) });
|
||||
assert.equal(limited.status, 429);
|
||||
assert.equal(limited.retryAfterMs, 90_000);
|
||||
const error = await fetchOverpassPayload('x', 1024, { endpoints: ['https://error.example/'],
|
||||
fetchImpl: async () => new Response('{"error":"rate_limited"}', { headers: { 'Retry-After': '120' } }) });
|
||||
assert.equal(error.status, 429);
|
||||
assert.equal(error.retryAfterMs, 120_000);
|
||||
});
|
||||
|
||||
function proxyHandler() {
|
||||
const plugin = createViteConfig({ mode: 'test' }).plugins.find(p => p.name === 'overpass-proxy');
|
||||
const routes = new Map();
|
||||
|
||||
+50
-39
@@ -189,20 +189,22 @@ export class SceneDirector {
|
||||
...this._presentation,
|
||||
hasRun: !!this._lastRunJson,
|
||||
}));
|
||||
this._bootstrapLegacyShotPacks();
|
||||
// Upgrade only already-installed packs; unrelated Scenes are untouched.
|
||||
for (const scene of this._project.scenes) {
|
||||
for (const marker of [...(scene.appliedShotPacks || [])]) {
|
||||
const recipe = getSceneAppendRecipeById(marker.id);
|
||||
if (
|
||||
recipe?.expansionFromVersion &&
|
||||
marker.version > 0 &&
|
||||
marker.version <= recipe.expansionFromVersion
|
||||
) {
|
||||
this.appendShotPack(scene.id, marker.id, {
|
||||
render: false,
|
||||
announce: false,
|
||||
});
|
||||
if (!this._storageReadError) {
|
||||
this._bootstrapLegacyShotPacks();
|
||||
// Upgrade only already-installed packs; unrelated Scenes are untouched.
|
||||
for (const scene of this._project.scenes) {
|
||||
for (const marker of [...(scene.appliedShotPacks || [])]) {
|
||||
const recipe = getSceneAppendRecipeById(marker.id);
|
||||
if (
|
||||
recipe?.expansionFromVersion &&
|
||||
marker.version > 0 &&
|
||||
marker.version <= recipe.expansionFromVersion
|
||||
) {
|
||||
this.appendShotPack(scene.id, marker.id, {
|
||||
render: false,
|
||||
announce: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,13 +326,14 @@ export class SceneDirector {
|
||||
'Scene not saved — existing saved project could not be read. Export edits or import a valid file.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
this._project.updatedAt = new Date().toISOString();
|
||||
try {
|
||||
const payload = JSON.stringify(this._project);
|
||||
parseSceneDocument(payload);
|
||||
localStorage.setItem(STORAGE_KEY, payload);
|
||||
return true;
|
||||
} catch (e) {
|
||||
// Private browsing / block-all-cookies / quota-exceeded throws here. The
|
||||
// in-memory project stays usable this session, but persistence failed —
|
||||
@@ -351,6 +354,7 @@ export class SceneDirector {
|
||||
})
|
||||
: undefined,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -923,12 +927,12 @@ export class SceneDirector {
|
||||
}
|
||||
this._selectedSceneId = scene.id;
|
||||
this._selectedShotId = appendedShots[0]?.id || this._selectedShotId;
|
||||
this._saveProject();
|
||||
const saved = this._saveProject();
|
||||
if (render) {
|
||||
this._renderSceneSelect();
|
||||
this._renderShotList();
|
||||
}
|
||||
if (announce) {
|
||||
if (announce && saved) {
|
||||
this._updateStatus(
|
||||
marker
|
||||
? tn(
|
||||
@@ -984,14 +988,16 @@ export class SceneDirector {
|
||||
|
||||
scene.shots.push(shot);
|
||||
this._selectedShotId = shot.id;
|
||||
this._saveProject();
|
||||
const saved = this._saveProject();
|
||||
this._shotOutcome('shot-captured', scene, shot);
|
||||
this._updateStatus(
|
||||
t('Captured: {scene} / {shot}', {
|
||||
scene: displaySceneTitle(scene),
|
||||
shot: displayShotTitle(shot.title, shot, scene),
|
||||
}),
|
||||
);
|
||||
if (saved) {
|
||||
this._updateStatus(
|
||||
t('Captured: {scene} / {shot}', {
|
||||
scene: displaySceneTitle(scene),
|
||||
shot: displayShotTitle(shot.title, shot, scene),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1017,14 +1023,16 @@ export class SceneDirector {
|
||||
shot.visual = this.styleManager.getVisualState();
|
||||
shot.layers = this._captureLayerStates();
|
||||
|
||||
this._saveProject();
|
||||
const saved = this._saveProject();
|
||||
this._shotOutcome('shot-updated', scene, shot);
|
||||
this._updateStatus(
|
||||
t('Updated: {scene} / {shot}', {
|
||||
scene: displaySceneTitle(scene),
|
||||
shot: displayShotTitle(shot.title, shot, scene),
|
||||
}),
|
||||
);
|
||||
if (saved) {
|
||||
this._updateStatus(
|
||||
t('Updated: {scene} / {shot}', {
|
||||
scene: displaySceneTitle(scene),
|
||||
shot: displayShotTitle(shot.title, shot, scene),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1755,13 +1763,13 @@ export class SceneDirector {
|
||||
) {
|
||||
if (this._running) return { started: false, reason: 'already-running' };
|
||||
|
||||
let queue = this._buildPlaybackQueue(
|
||||
sceneId || this._selectedSceneId || this._project.scenes[0]?.id,
|
||||
{ single },
|
||||
);
|
||||
const startSceneId =
|
||||
sceneId || this._selectedSceneId || this._project.scenes[0]?.id;
|
||||
let queue = this._buildPlaybackQueue(startSceneId, { single });
|
||||
if (afterShotId !== null) {
|
||||
const index = queue.findIndex(
|
||||
({ scene, shot }) => scene.id === sceneId && shot.id === afterShotId,
|
||||
({ scene, shot }) =>
|
||||
scene.id === startSceneId && shot.id === afterShotId,
|
||||
);
|
||||
if (index < 0) return { started: false, reason: 'shot-not-found' };
|
||||
queue = queue.slice(index + 1);
|
||||
@@ -1834,7 +1842,7 @@ export class SceneDirector {
|
||||
title: 'Editable Scene Run',
|
||||
startedAt: new Date().toISOString(),
|
||||
estimatedDurationSec,
|
||||
scenesRun: queue.length,
|
||||
scenesRun: new Set(queue.map(({ scene }) => scene.id)).size,
|
||||
events: [],
|
||||
};
|
||||
|
||||
@@ -1842,6 +1850,7 @@ export class SceneDirector {
|
||||
this._logEvent('scene_run_start', { count: queue.length });
|
||||
this._setPlaybackKeyboardEnabled(true);
|
||||
|
||||
let runResult = { started: true, shots: queue.length };
|
||||
try {
|
||||
await playSceneQueue(queue, {
|
||||
token,
|
||||
@@ -1860,9 +1869,11 @@ export class SceneDirector {
|
||||
this._logEvent('scene_run_error', {
|
||||
message: error.message || 'unknown error',
|
||||
});
|
||||
runResult = { started: false, reason: 'run-failed' };
|
||||
} finally {
|
||||
this._finishRun();
|
||||
}
|
||||
return runResult;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2090,9 +2101,9 @@ export class SceneDirector {
|
||||
this._selectedShotId =
|
||||
selection?.shotId || project.scenes[0]?.shots[0]?.id || null;
|
||||
this._loadedSceneId = null;
|
||||
this._saveProject();
|
||||
const saved = this._saveProject();
|
||||
this._publish({ type: 'project-imported', project });
|
||||
this._updateStatus(t('Imported {file}', { file: file.name }));
|
||||
if (saved) this._updateStatus(t('Imported {file}', { file: file.name }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (
|
||||
|
||||
@@ -601,8 +601,12 @@ const PROJECT_FIXTURE = {
|
||||
}],
|
||||
};
|
||||
|
||||
/** Stub the browser globals the director touches, headlessly. */
|
||||
function installSceneRuntime(project = PROJECT_FIXTURE) {
|
||||
/**
|
||||
* Stub the browser globals the director touches, headlessly. `storage` replaces
|
||||
* the seeded entries (key -> raw string); setting `localStorage.full` makes
|
||||
* every write throw a quota error.
|
||||
*/
|
||||
function installSceneRuntime(project = PROJECT_FIXTURE, { storage } = {}) {
|
||||
const originalDocument = globalThis.document;
|
||||
const originalLocalStorage = globalThis.localStorage;
|
||||
const noopClassList = { add() {}, remove() {}, toggle() {}, contains: () => false };
|
||||
@@ -614,10 +618,17 @@ function installSceneRuntime(project = PROJECT_FIXTURE) {
|
||||
removeEventListener() {},
|
||||
body: { classList: noopClassList, appendChild() {} },
|
||||
};
|
||||
const stored = new Map([['godsEyeView.sceneProject.v2', JSON.stringify(project)]]);
|
||||
const stored = new Map(storage
|
||||
? Object.entries(storage)
|
||||
: [['godsEyeView.sceneProject.v2', JSON.stringify(project)]]);
|
||||
globalThis.localStorage = {
|
||||
stored,
|
||||
full: false,
|
||||
getItem: (key) => stored.get(key) ?? null,
|
||||
setItem: (key, value) => stored.set(key, value),
|
||||
setItem(key, value) {
|
||||
if (this.full) throw new DOMException('quota exceeded', 'QuotaExceededError');
|
||||
stored.set(key, value);
|
||||
},
|
||||
removeItem: (key) => stored.delete(key),
|
||||
};
|
||||
|
||||
@@ -718,7 +729,8 @@ async function settle(turns = 8) {
|
||||
|
||||
/** Build a director over doubles, with the fixture project loaded. */
|
||||
function makeDirector(options = {}) {
|
||||
const restore = installSceneRuntime(options.project);
|
||||
const restore = installSceneRuntime(options.project, { storage: options.storage });
|
||||
const storage = globalThis.localStorage;
|
||||
const viewer = fakeViewer();
|
||||
const styleManager = fakeStyleManager(options.style);
|
||||
const dataManager = fakeDataManager(options.data);
|
||||
@@ -728,7 +740,7 @@ function makeDirector(options = {}) {
|
||||
// Telemetry is only accumulated during a run; observable-failure assertions
|
||||
// need the accumulator without driving a whole run.
|
||||
director._activeRun = { events: [] };
|
||||
return { director, viewer, styleManager, dataManager, restore };
|
||||
return { director, viewer, styleManager, dataManager, storage, restore };
|
||||
}
|
||||
|
||||
test('only Play Shot or a scene run grants transient media authority; LOAD, Stop and replacement revoke it', async () => {
|
||||
@@ -1584,3 +1596,65 @@ test('camera refusal starts no authored frame or playback clock', async () => {
|
||||
assert.deepEqual(viewer.flights, []);
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
test('an unreadable saved project does not overwrite its recovery checkpoint (#971)', async () => {
|
||||
const unreadable = '{"version":99,"scenes":[]}';
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
const { director, storage, restore } = makeDirector({ storage: {
|
||||
'godsEyeView.sceneProject.v2': unreadable,
|
||||
'godsEyeView.sceneProject.checkpoint.v1': 'EARLIER-CHECKPOINT',
|
||||
} });
|
||||
try {
|
||||
assert.equal(storage.stored.get('godsEyeView.sceneProject.v2'), unreadable);
|
||||
assert.equal(storage.stored.get('godsEyeView.sceneProject.checkpoint.v1'), 'EARLIER-CHECKPOINT');
|
||||
} finally { console.warn = warn; await director.destroy(); restore(); }
|
||||
});
|
||||
|
||||
test('a capture, update or import that cannot be saved keeps the "Scene not saved" status (#971)', async () => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
const { director, storage, restore } = makeDirector();
|
||||
let status = '';
|
||||
director.subscribe(({ state }) => { status = state.status; });
|
||||
try {
|
||||
storage.full = true;
|
||||
director._selectedSceneId = 'scene-1';
|
||||
director._selectedShotId = 'shot-a';
|
||||
director.captureShot();
|
||||
assert.match(status, /^Scene not saved/, 'failed capture keeps the save failure');
|
||||
director.updateSelectedShot();
|
||||
assert.match(status, /^Scene not saved/, 'failed update keeps the save failure');
|
||||
assert.equal(await director.importProjectFile(
|
||||
{ name: 'fixture.json' },
|
||||
{ prepared: { project: structuredClone(PROJECT_FIXTURE), assets: [] } },
|
||||
), true);
|
||||
assert.match(status, /^Scene not saved/, 'failed import keeps the save failure');
|
||||
} finally { console.warn = warn; await director.destroy(); restore(); }
|
||||
});
|
||||
|
||||
test('startScene resolves its result, resumes after a shot without a scene id, and counts distinct scenes (#971)', async () => {
|
||||
const { director, restore } = makeDirector();
|
||||
try {
|
||||
const options = { single: true, preview: false };
|
||||
assert.deepEqual(await director.startScene('scene-1', options), { started: true, shots: 2 });
|
||||
assert.equal(director._lastRun.scenesRun, 1, 'one scene with two shots is one scene run');
|
||||
assert.deepEqual(
|
||||
await director.startScene(undefined, { ...options, afterShotId: 'shot-a' }),
|
||||
{ started: true, shots: 1 },
|
||||
);
|
||||
} finally { await director.destroy(); restore(); }
|
||||
});
|
||||
|
||||
test('a caught run failure resolves as run-failed, not success (#971)', async () => {
|
||||
const { director, styleManager, restore } = makeDirector();
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
styleManager.applyVisualState = async () => { throw new Error('visual failed'); };
|
||||
try {
|
||||
assert.deepEqual(
|
||||
await director.startScene('scene-1', { single: true, preview: false }),
|
||||
{ started: false, reason: 'run-failed' },
|
||||
);
|
||||
} finally { console.warn = warn; await director.destroy(); restore(); }
|
||||
});
|
||||
@@ -22,7 +22,7 @@ function boundedBox(lat, lon, halfSpan) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer a decimal-degree query without asking anyone.
|
||||
* Answer a decimal-degree or geo-URI query without asking anyone.
|
||||
*
|
||||
* It sits ahead of the network geocoders, so a coordinate costs no request and
|
||||
* works with no key. Anything that is not exactly a coordinate is passed on
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* as 12, 34 flies the operator somewhere they did not ask for and looks like a
|
||||
* successful search. So every rule here is exact — a component is a decimal
|
||||
* number, optionally signed, optionally marked with one hemisphere letter, and
|
||||
* nothing else. Degrees/minutes/seconds and grid references are not handled;
|
||||
* nothing else. Two-dimensional WGS84 geo URIs use their own strict grammar.
|
||||
* Degrees/minutes/seconds and grid references are not handled;
|
||||
* they fall through to the geocoders, which is what happens today.
|
||||
*/
|
||||
|
||||
@@ -13,6 +14,10 @@
|
||||
const COMPONENT =
|
||||
/^([NSEW])?\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*°?\s*([NSEW])?$/i;
|
||||
|
||||
/** RFC 5870's 2D WGS84 subset; never discard altitude or uncertainty. */
|
||||
const GEO_URI =
|
||||
/^geo:(-?\d{1,2}(?:\.\d+)?),(-?\d{1,3}(?:\.\d+)?)(?:;crs=wgs84)?$/i;
|
||||
|
||||
/** Hemisphere letters, by the axis each one can name. */
|
||||
const LATITUDE_LETTERS = new Set(['N', 'S']);
|
||||
|
||||
@@ -61,20 +66,25 @@ export function formatCoordinateLabel(lat, lon) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a decimal-degree query, or return null.
|
||||
* Parse a decimal-degree pair or a two-dimensional WGS84 geo URI, or return null.
|
||||
*
|
||||
* Both orders are accepted when the hemisphere letters say which is which
|
||||
* (`W 40, N 74` is longitude then latitude); with no letters the conventional
|
||||
* latitude-then-longitude order applies. Two letters naming the same axis, a
|
||||
* letter that fixes nothing, an out-of-range latitude or longitude, and any
|
||||
* trailing text all decline.
|
||||
* Geo URIs accept only latitude/longitude and an optional `;crs=wgs84`;
|
||||
* altitude, uncertainty, other parameters and query/fragment suffixes decline.
|
||||
*
|
||||
* @param {string} query
|
||||
* @returns {{ lat: number, lon: number, label: string } | null}
|
||||
*/
|
||||
export function parseCoordinateQuery(query) {
|
||||
if (typeof query !== 'string') return null;
|
||||
const parts = splitComponents(query);
|
||||
const text = query.trim();
|
||||
const parts = /^geo:/i.test(text)
|
||||
? GEO_URI.exec(text)?.slice(1, 3)
|
||||
: splitComponents(text);
|
||||
if (!parts) return null;
|
||||
|
||||
const first = readComponent(parts[0]);
|
||||
|
||||
@@ -132,3 +132,67 @@ test('the poles and the dateline are inside the accepted range', () => {
|
||||
assert.deepEqual(parseCoordinateQuery('90, 180')?.lat, 90);
|
||||
assert.deepEqual(parseCoordinateQuery('-90, -180')?.lon, -180);
|
||||
});
|
||||
|
||||
test('two-dimensional WGS84 geo URIs resolve to the same decimal coordinate', () => {
|
||||
for (const query of [
|
||||
'geo:39.7392,-104.9903',
|
||||
'geo:39.7392,-104.9903;crs=wgs84',
|
||||
' GEO:39.7392,-104.9903;CRS=WGS84 ',
|
||||
]) {
|
||||
assert.deepEqual(parseCoordinateQuery(query), {
|
||||
lat: 39.7392,
|
||||
lon: -104.9903,
|
||||
label: '39.7392° N, 104.9903° W',
|
||||
});
|
||||
}
|
||||
for (const [query, decimal] of [
|
||||
['geo:0,0', '0,0'],
|
||||
['geo:-33.8568,151.2153', '-33.8568,151.2153'],
|
||||
['geo:90,180', '90,180'],
|
||||
['geo:-90,-180;crs=wgs84', '-90,-180'],
|
||||
['geo:09,007', '9,7'],
|
||||
['geo:-0,-0', '-0,-0'],
|
||||
]) {
|
||||
assert.deepEqual(
|
||||
parseCoordinateQuery(query),
|
||||
parseCoordinateQuery(decimal),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed or unsupported geo URIs are refused without losing their meaning', () => {
|
||||
for (const query of [
|
||||
'geo:',
|
||||
'geo:39.7392',
|
||||
'geo:,104.9903',
|
||||
'geo:39.7392,,104.9903',
|
||||
'geo:39.7392,-104.9903,',
|
||||
'geo:91,0',
|
||||
'geo:-90.1,0',
|
||||
'geo:0,181',
|
||||
'geo:0,-180.1',
|
||||
'geo:000,0',
|
||||
'geo:0,0000',
|
||||
'geo:+39.7392,-104.9903',
|
||||
'geo:.5,-.25',
|
||||
'geo:1e1,2',
|
||||
'geo:NaN,0',
|
||||
'geo:Infinity,0',
|
||||
'geo:39.7392, -104.9903',
|
||||
'geo:39.7392;-104.9903',
|
||||
'geo:39.7392N,104.9903W',
|
||||
'geo:39.7392,-104.9903,1600',
|
||||
'geo:39.7392,-104.9903;u=10',
|
||||
'geo:39.7392,-104.9903;crs=unknown',
|
||||
'geo:39.7392,-104.9903;crs=wgs84;crs=wgs84',
|
||||
'geo:39.7392,-104.9903;crs=wgs84;u=0',
|
||||
'geo:39.7392,-104.9903;custom=value',
|
||||
'geo:0,0?q=39.7392,-104.9903(Denver)',
|
||||
'geo:39.7392,-104.9903#Denver',
|
||||
'geo:39.7392,-104.9903 trailing text',
|
||||
'geo://39.7392,-104.9903',
|
||||
'https://example.com/geo:39.7392,-104.9903',
|
||||
]) {
|
||||
assert.equal(parseCoordinateQuery(query), null, query);
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import assert from 'node:assert/strict';
|
||||
import { createCoordinateGeocoder } from './coordinateGeocoder.js';
|
||||
import { createPresetGeocoder } from './presetGeocoder.js';
|
||||
import { createPlaceSearch } from './placeSearch.js';
|
||||
import { createDefaultPlaceSearch } from './defaults.js';
|
||||
|
||||
const PRESETS = {
|
||||
austin: {
|
||||
@@ -189,3 +190,52 @@ test('a cancelled search stops the offline providers too', async () => {
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('default search resolves a geo URI exactly without requesting a geocoder', async () => {
|
||||
const requests = [];
|
||||
const search = createDefaultPlaceSearch({
|
||||
resolveApiKey: () => 'test-key',
|
||||
fetchImpl: async (url) => {
|
||||
requests.push(url);
|
||||
throw new Error('No network request should be needed');
|
||||
},
|
||||
});
|
||||
const { place, fallbackUsed } = await search.geocode(
|
||||
'geo:39.7392,-104.9903;crs=wgs84',
|
||||
);
|
||||
assert.deepEqual(requests, []);
|
||||
assert.equal(fallbackUsed, false);
|
||||
assert.equal(place.lat, 39.7392);
|
||||
assert.equal(place.lng, -104.9903);
|
||||
assert.equal(place.exact, true);
|
||||
assert.deepEqual(place.types, ['coordinate']);
|
||||
assert.ok(place.viewport.southwest.lat < place.lat);
|
||||
assert.ok(place.viewport.northeast.lat > place.lat);
|
||||
assert.ok(place.viewport.southwest.lng < place.lng);
|
||||
assert.ok(place.viewport.northeast.lng > place.lng);
|
||||
});
|
||||
|
||||
test('unsupported geo URIs reach the next search provider unchanged', async () => {
|
||||
const queries = [
|
||||
'geo:39.7392,-104.9903,1600',
|
||||
'geo:39.7392,-104.9903;u=10',
|
||||
'geo:39.7392,-104.9903;crs=unknown',
|
||||
'geo:0,0?q=Denver',
|
||||
];
|
||||
const received = [];
|
||||
const search = createPlaceSearch({
|
||||
providers: [
|
||||
createCoordinateGeocoder(),
|
||||
{
|
||||
async geocode(query) {
|
||||
received.push(query);
|
||||
return { place: null, answered: true };
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
for (const query of queries) {
|
||||
assert.equal((await search.geocode(query)).place, null);
|
||||
}
|
||||
assert.deepEqual(received, queries);
|
||||
});
|
||||
+18
-11
@@ -204,12 +204,16 @@ export function createGroundFloor({ terrain, signal }) {
|
||||
* @returns {{lat: number, lon: number}} The cell to read.
|
||||
*/
|
||||
function stickyFloorCell(lat, lon, previousCell) {
|
||||
if (
|
||||
previousCell &&
|
||||
Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG &&
|
||||
Math.abs(lon - previousCell.lon) <= 0.0005 + CELL_HYSTERESIS_DEG
|
||||
) {
|
||||
return previousCell;
|
||||
if (previousCell) {
|
||||
// The short way round, so a contact on the 180° seam keeps its cell.
|
||||
let dLon = lon - previousCell.lon;
|
||||
dLon -= 360 * Math.round(dLon / 360);
|
||||
if (
|
||||
Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG &&
|
||||
Math.abs(dLon) <= 0.0005 + CELL_HYSTERESIS_DEG
|
||||
) {
|
||||
return previousCell;
|
||||
}
|
||||
}
|
||||
return coarseFloorCoord(lat, lon);
|
||||
}
|
||||
@@ -269,17 +273,20 @@ export function createGroundFloor({ terrain, signal }) {
|
||||
const a = points[s];
|
||||
const b = points[s + 1];
|
||||
if (![a?.lat, a?.lon, b?.lat, b?.lon].every(Number.isFinite)) continue;
|
||||
// The short way round, so a segment across 180° walks across it.
|
||||
let dLon = b.lon - a.lon;
|
||||
dLon -= 360 * Math.round(dLon / 360);
|
||||
const steps = Math.ceil(
|
||||
Math.max(Math.abs(b.lat - a.lat), Math.abs(b.lon - a.lon)) /
|
||||
Math.max(Math.abs(b.lat - a.lat), Math.abs(dLon)) /
|
||||
CORRIDOR_WALK_STEP_DEG,
|
||||
);
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
if (out.length >= prefixLimit) break walk;
|
||||
const t = i / steps;
|
||||
const cell = coarseFloorCoord(
|
||||
a.lat + (b.lat - a.lat) * t,
|
||||
a.lon + (b.lon - a.lon) * t,
|
||||
);
|
||||
let lon = a.lon + dLon * t;
|
||||
if (lon > 180) lon -= 360;
|
||||
else if (lon < -180) lon += 360;
|
||||
const cell = coarseFloorCoord(a.lat + (b.lat - a.lat) * t, lon);
|
||||
const key = `${cell.lat},${cell.lon}`;
|
||||
if (seen.has(key) || key === destKey) continue;
|
||||
seen.add(key);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { approxDistanceKm } from '../data/approxDistance.js';
|
||||
|
||||
/** Construct an instance-owned meshFloorSampler service with explicit dependencies. */
|
||||
export function createMeshFloorSampler({
|
||||
@@ -79,16 +80,6 @@ export function createMeshFloorSampler({
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equirectangular distance (km) — same approximation the flights clamp uses.
|
||||
*/
|
||||
function _approxKm(lat1, lon1, lat2, lon2) {
|
||||
const dLat = (lat2 - lat1) * 111.32;
|
||||
const dLon =
|
||||
(lon2 - lon1) * 111.32 * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
|
||||
return Math.hypot(dLat, dLon);
|
||||
}
|
||||
|
||||
/**
|
||||
* Samples the rendered mesh height for the coarse cells containing `points`,
|
||||
* one-shot per cell, budget-capped, viewer-proximity-gated. Call ONCE per
|
||||
@@ -133,7 +124,8 @@ export function createMeshFloorSampler({
|
||||
if (
|
||||
Number.isFinite(viewerLat) &&
|
||||
Number.isFinite(viewerLon) &&
|
||||
_approxKm(viewerLat, viewerLon, cell.lat, cell.lon) > MAX_SAMPLE_DIST_KM
|
||||
approxDistanceKm(viewerLat, viewerLon, cell.lat, cell.lon) >
|
||||
MAX_SAMPLE_DIST_KM
|
||||
) {
|
||||
continue; // too far: tiles not streamed there, probe would be a guaranteed miss
|
||||
}
|
||||
|
||||
@@ -69,12 +69,22 @@ test('placeholder values are never counted as configured credentials', () => {
|
||||
});
|
||||
|
||||
test('doctor selects a Windows-safe npm process without changing Unix behavior', () => {
|
||||
assert.deepEqual(npmProcessSpec('win32'), {
|
||||
command: 'npm.cmd',
|
||||
// Windows passes no argument array with shell: true (Node DEP0190).
|
||||
assert.deepEqual(npmProcessSpec(['ci'], 'win32'), {
|
||||
command: 'npm.cmd ci',
|
||||
args: [],
|
||||
shell: true,
|
||||
});
|
||||
assert.deepEqual(npmProcessSpec('darwin'), { command: 'npm', shell: false });
|
||||
assert.deepEqual(npmProcessSpec('linux'), { command: 'npm', shell: false });
|
||||
assert.deepEqual(npmProcessSpec(['--version'], 'darwin'), {
|
||||
command: 'npm',
|
||||
args: ['--version'],
|
||||
shell: false,
|
||||
});
|
||||
assert.deepEqual(npmProcessSpec(['ci'], 'linux'), {
|
||||
command: 'npm',
|
||||
args: ['ci'],
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('doctor recognizes every OpenSky OAuth keychain alias used by dev-fresh', () => {
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import {
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
writeFile,
|
||||
readFile,
|
||||
readdir,
|
||||
rm,
|
||||
} from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
FRAGMENT_DIR,
|
||||
STAGING_DIR,
|
||||
assembleChangelog,
|
||||
assembleFragments,
|
||||
orderFragmentNames,
|
||||
recoverInterruptedBatch,
|
||||
} from '../../scripts/assemble-changelog.mjs';
|
||||
|
||||
const EXISTING =
|
||||
'# Changelog\n\n- An entry that was already released (someone, #1).\n';
|
||||
|
||||
const repositoryRoot = fileURLToPath(new URL('../..', import.meta.url));
|
||||
|
||||
async function fixture(t, fragments = {}) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'gev-changelog-'));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
await mkdir(path.join(root, FRAGMENT_DIR));
|
||||
await writeFile(
|
||||
path.join(root, FRAGMENT_DIR, 'README.md'),
|
||||
'# How to add one\n',
|
||||
);
|
||||
await writeFile(path.join(root, 'CHANGELOG.md'), EXISTING);
|
||||
for (const [name, body] of Object.entries(fragments)) {
|
||||
await writeFile(path.join(root, FRAGMENT_DIR, name), body);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
test('the batch reads newest pull request first', () => {
|
||||
assert.deepEqual(orderFragmentNames(['7-b.md', '112-c.md', '19-a.md']), [
|
||||
'112-c.md',
|
||||
'19-a.md',
|
||||
'7-b.md',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the directory README is documentation, never an entry', () => {
|
||||
assert.deepEqual(orderFragmentNames(['README.md', '5-a.md']), ['5-a.md']);
|
||||
});
|
||||
|
||||
test('two fragments claiming one pull request fail loudly, not silently', () => {
|
||||
assert.throws(
|
||||
() => orderFragmentNames(['5-first.md', '5-second.md']),
|
||||
/Two fragments claim pull request 5/,
|
||||
);
|
||||
});
|
||||
|
||||
test('a name that is not <pull request>-<slug>.md is refused', () => {
|
||||
for (const name of ['notes.md', '5_underscore.md', '5-Caps.md', '5-a.txt']) {
|
||||
assert.throws(() => orderFragmentNames([name]), /Unexpected file/, name);
|
||||
}
|
||||
});
|
||||
|
||||
test('fragment text is spliced in unchanged, above the existing entries', () => {
|
||||
// Wrapped, indented and punctuated the way a real entry is: the continuation
|
||||
// indent and the blank line inside the entry are the parts a reflow would eat.
|
||||
const entry = [
|
||||
'- A new thing, with `code` and a — dash. The second line is indented the',
|
||||
' way the surrounding entries wrap, and it keeps its two spaces.',
|
||||
'',
|
||||
' A second paragraph, because some entries have one (someone, #9).',
|
||||
].join('\n');
|
||||
const result = assembleChangelog(EXISTING, [`${entry}\n\n\n`]);
|
||||
assert.equal(
|
||||
result,
|
||||
`# Changelog\n\n${entry}\n\n- An entry that was already released (someone, #1).\n`,
|
||||
);
|
||||
// The entry survives byte for byte: drawTool.test.mjs reads this file as
|
||||
// prose and slices a fixed window, so reflowing would move text across it.
|
||||
assert.ok(result.includes(entry));
|
||||
});
|
||||
|
||||
test('a CHANGELOG without the heading is refused rather than prepended to', () => {
|
||||
assert.throws(
|
||||
() => assembleChangelog('- orphan entry\n', ['- new\n']),
|
||||
/must start with "# Changelog"/,
|
||||
);
|
||||
});
|
||||
|
||||
test('assembling consumes the fragments and leaves the README', async (t) => {
|
||||
const root = await fixture(t, {
|
||||
'20-second.md': '- Second (someone, #20).',
|
||||
'100-first.md': '- First (someone, #100).',
|
||||
});
|
||||
const { consumed } = await assembleFragments(root, '--write');
|
||||
assert.deepEqual(consumed, ['100-first.md', '20-second.md']);
|
||||
const changelog = await readFile(path.join(root, 'CHANGELOG.md'), 'utf8');
|
||||
assert.match(
|
||||
changelog,
|
||||
/# Changelog\n\n- First \(someone, #100\)\.\n\n- Second \(someone, #20\)\.\n\n- An entry that was already released/,
|
||||
);
|
||||
assert.deepEqual(await readdir(path.join(root, FRAGMENT_DIR)), ['README.md']);
|
||||
});
|
||||
|
||||
test('a rejected batch leaves the directory and the file untouched', async (t) => {
|
||||
const root = await fixture(t, {
|
||||
'8-first.md': '- First (someone, #8).',
|
||||
'8-again.md': '- Again (someone, #8).',
|
||||
});
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write'),
|
||||
/Two fragments claim pull request 8/,
|
||||
);
|
||||
assert.equal(
|
||||
await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
EXISTING,
|
||||
);
|
||||
assert.deepEqual((await readdir(path.join(root, FRAGMENT_DIR))).sort(), [
|
||||
'8-again.md',
|
||||
'8-first.md',
|
||||
'README.md',
|
||||
]);
|
||||
});
|
||||
|
||||
test('check mode changes nothing on disk', async (t) => {
|
||||
const root = await fixture(t, { '3-a.md': '- Something (someone, #3).' });
|
||||
const { consumed } = await assembleFragments(root, '--check');
|
||||
assert.deepEqual(consumed, ['3-a.md']);
|
||||
assert.equal(
|
||||
await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
EXISTING,
|
||||
);
|
||||
assert.deepEqual((await readdir(path.join(root, FRAGMENT_DIR))).sort(), [
|
||||
'3-a.md',
|
||||
'README.md',
|
||||
]);
|
||||
});
|
||||
|
||||
test('an empty directory is a no-op, so a release can always run it', async (t) => {
|
||||
const root = await fixture(t);
|
||||
const { consumed } = await assembleFragments(root, '--write');
|
||||
assert.deepEqual(consumed, []);
|
||||
assert.equal(
|
||||
await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
EXISTING,
|
||||
);
|
||||
});
|
||||
|
||||
test('a mode that is neither check nor write is refused', async (t) => {
|
||||
const root = await fixture(t);
|
||||
await assert.rejects(assembleFragments(root, '--force'), /--check\|--write/);
|
||||
});
|
||||
|
||||
// Failure injection. Every filesystem call the write path makes is a point
|
||||
// where a release can die: a full disk, a permissions error, a killed process.
|
||||
|
||||
const IO_CALLS = ['readdir', 'readFile', 'mkdir', 'writeFile', 'rename', 'rm'];
|
||||
const BATCH = {
|
||||
'20-second.md': '- Second (someone, #20).',
|
||||
'100-first.md': '- First (someone, #100).',
|
||||
'7-third.md': '- Third (someone, #7).',
|
||||
};
|
||||
|
||||
/**
|
||||
* The real filesystem, except that `call` throws the `nth` time it runs. With
|
||||
* `crash`, every later call throws as well, the way a killed process makes no
|
||||
* further calls: the in-process rollback cannot run either, so the next
|
||||
* invocation is the only thing that can recover.
|
||||
*/
|
||||
function failing(call, nth, { crash = false } = {}) {
|
||||
let seen = 0;
|
||||
let dead = false;
|
||||
const io = { ...fs };
|
||||
for (const name of IO_CALLS) {
|
||||
io[name] = async (...args) => {
|
||||
if (dead) throw new Error('process already gone');
|
||||
if (name === call && ++seen === nth) {
|
||||
dead = crash;
|
||||
throw new Error(`injected ${call} failure #${nth}`);
|
||||
}
|
||||
return fs[name](...args);
|
||||
};
|
||||
}
|
||||
return io;
|
||||
}
|
||||
|
||||
/** How many times one uninterrupted `--write` makes each filesystem call. */
|
||||
async function countCalls(t) {
|
||||
const root = await fixture(t, BATCH);
|
||||
const counts = Object.fromEntries(IO_CALLS.map((name) => [name, 0]));
|
||||
const io = { ...fs };
|
||||
for (const name of IO_CALLS) {
|
||||
io[name] = (...args) => {
|
||||
counts[name] += 1;
|
||||
return fs[name](...args);
|
||||
};
|
||||
}
|
||||
await assembleFragments(root, '--write', io);
|
||||
return {
|
||||
counts,
|
||||
expected: await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
};
|
||||
}
|
||||
|
||||
test('a write that fails at any call never lets a retry duplicate or lose an entry', async (t) => {
|
||||
const { counts, expected } = await countCalls(t);
|
||||
// The write path itself: one mkdir, one writeFile, a rename per fragment plus
|
||||
// the commit rename, and the cleanup rm. Fewer would mean a step went missing.
|
||||
assert.ok(counts.rename >= Object.keys(BATCH).length + 1);
|
||||
for (const crash of [false, true]) {
|
||||
for (const call of IO_CALLS) {
|
||||
for (let nth = 1; nth <= counts[call]; nth += 1) {
|
||||
const label = `${crash ? 'crash' : 'error'} at ${call} #${nth}`;
|
||||
const root = await fixture(t, BATCH);
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write', failing(call, nth, { crash })),
|
||||
/injected|already gone/,
|
||||
label,
|
||||
);
|
||||
await assembleFragments(root, '--write');
|
||||
const changelog = await readFile(
|
||||
path.join(root, 'CHANGELOG.md'),
|
||||
'utf8',
|
||||
);
|
||||
assert.equal(changelog, expected, label);
|
||||
for (const pr of [100, 20, 7, 1]) {
|
||||
assert.equal(
|
||||
changelog.split(`(someone, #${pr}).`).length - 1,
|
||||
1,
|
||||
`${label}: #${pr} appears exactly once`,
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
await readdir(path.join(root, FRAGMENT_DIR)),
|
||||
['README.md'],
|
||||
label,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('an error before the commit rolls the batch back in the same run', async (t) => {
|
||||
const root = await fixture(t, BATCH);
|
||||
// The second rename has already moved one fragment into the staging directory.
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write', failing('rename', 2)),
|
||||
/injected rename failure #2/,
|
||||
);
|
||||
assert.equal(
|
||||
await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
EXISTING,
|
||||
);
|
||||
assert.deepEqual(
|
||||
(await readdir(path.join(root, FRAGMENT_DIR))).sort(),
|
||||
[...Object.keys(BATCH), 'README.md'].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
test('check mode reports a batch an interrupted release left staged', async (t) => {
|
||||
const root = await fixture(t, BATCH);
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write', failing('rename', 2, { crash: true })),
|
||||
);
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--check'),
|
||||
new RegExp(`${STAGING_DIR}/ holds a batch an interrupted release`),
|
||||
);
|
||||
assert.equal(await recoverInterruptedBatch(root), 'rolled-back');
|
||||
assert.equal(await recoverInterruptedBatch(root), 'none');
|
||||
});
|
||||
|
||||
test('recovery refuses to roll a fragment back over a file of the same name', async (t) => {
|
||||
const root = await fixture(t, BATCH);
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write', failing('rename', 2, { crash: true })),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(root, FRAGMENT_DIR, '100-first.md'),
|
||||
'- Rewritten.',
|
||||
);
|
||||
await assert.rejects(
|
||||
assembleFragments(root, '--write'),
|
||||
/Cannot roll back .*100-first\.md/,
|
||||
);
|
||||
assert.equal(
|
||||
await readFile(path.join(root, 'CHANGELOG.md'), 'utf8'),
|
||||
EXISTING,
|
||||
);
|
||||
});
|
||||
|
||||
// The two below run against the repository itself, so a fragment that the
|
||||
// release could not assemble fails `npm test` in the pull request that adds it
|
||||
// rather than at release time, when its author has moved on.
|
||||
|
||||
test('every pending fragment in the repository can be assembled', async () => {
|
||||
const names = await readdir(path.join(repositoryRoot, FRAGMENT_DIR));
|
||||
assert.ok(
|
||||
names.includes('README.md'),
|
||||
`${FRAGMENT_DIR}/README.md documents the convention and keeps the directory tracked`,
|
||||
);
|
||||
// Throws on a name that is not <pull request>-<slug>.md, and on two fragments
|
||||
// claiming one pull request number. Every other file is an entry.
|
||||
assert.equal(orderFragmentNames(names).length, names.length - 1);
|
||||
});
|
||||
|
||||
test('CHANGELOG.md still carries the heading a release splices under', async () => {
|
||||
const changelog = await readFile(
|
||||
path.join(repositoryRoot, 'CHANGELOG.md'),
|
||||
'utf8',
|
||||
);
|
||||
assert.ok(changelog.startsWith('# Changelog\n'));
|
||||
});
|
||||
@@ -7,9 +7,10 @@ import { firmsProxy } from 'gods-eye-view/server/providers/firms';
|
||||
import { gbfsProxy } from 'gods-eye-view/server/providers/gbfs';
|
||||
import { localProviderPlugins } from '../../server/providers/local.js';
|
||||
|
||||
function install(plugin) {
|
||||
function install(plugin, hook = 'configureServer') {
|
||||
const routes = new Map();
|
||||
plugin.configureServer({
|
||||
assert.equal(typeof plugin[hook], 'function', `${hook} is available`);
|
||||
plugin[hook]({
|
||||
middlewares: {
|
||||
use(route, handler) {
|
||||
routes.set(route, handler);
|
||||
@@ -17,9 +18,16 @@ function install(plugin) {
|
||||
},
|
||||
});
|
||||
assert.equal(routes.size, 1);
|
||||
return async (url = '/', method = 'GET') => {
|
||||
return async (url = '/', method = 'GET', headers = {}) => {
|
||||
const res = {
|
||||
headersSent: false,
|
||||
headers: {},
|
||||
set statusCode(status) {
|
||||
this.status = status;
|
||||
},
|
||||
setHeader(name, value) {
|
||||
this.headers[name.toLowerCase()] = value;
|
||||
},
|
||||
writeHead(status, headers) {
|
||||
Object.assign(this, { status, headers, headersSent: true });
|
||||
},
|
||||
@@ -27,7 +35,7 @@ function install(plugin) {
|
||||
this.body = body;
|
||||
},
|
||||
};
|
||||
await [...routes.values()][0]({ url, method }, res);
|
||||
await [...routes.values()][0]({ url, method, headers, socket: {} }, res);
|
||||
return res;
|
||||
};
|
||||
}
|
||||
@@ -191,6 +199,64 @@ test('traffic middleware preserves keyless mode, caching, stale budget fallback
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('traffic refuses cross-site requests in dev and preview before spending the TomTom budget', async (t) => {
|
||||
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '3' });
|
||||
let calls = 0;
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
calls++;
|
||||
return new Response(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
const host = 'localhost:5173';
|
||||
const refused = [
|
||||
{ host, 'sec-fetch-site': 'cross-site' }, // <img src> from any web page
|
||||
{ host, 'sec-fetch-site': 'same-site' },
|
||||
{ host, origin: 'https://evil.example' }, // fetch from another page
|
||||
{ host, origin: 'null' }, // sandboxed frame
|
||||
{ host, 'x-forwarded-for': '203.0.113.9' }, // through a proxy
|
||||
];
|
||||
for (const [mode, hook] of [
|
||||
['dev', 'configureServer'],
|
||||
['preview', 'configurePreviewServer'],
|
||||
]) {
|
||||
const request = install(tomtomProxy(), hook);
|
||||
// Each refused shape asks for distinct uncached tiles: without the gate
|
||||
// every one would be a billed attempt counted against the daily budget.
|
||||
let x = 0;
|
||||
for (const headers of refused)
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const res = await request(`/flow/16/${x++}/0.pbf`, 'GET', headers);
|
||||
assert.equal(res.status, 403, `${mode}: ${JSON.stringify(headers)}`);
|
||||
}
|
||||
assert.equal(
|
||||
(await request('/status', 'GET', refused[0])).status,
|
||||
403,
|
||||
`${mode}: status is gated too`,
|
||||
);
|
||||
assert.equal(
|
||||
calls,
|
||||
mode === 'dev' ? 0 : 2,
|
||||
`${mode}: no refused upstream work`,
|
||||
);
|
||||
const app = { host, 'sec-fetch-site': 'same-origin' };
|
||||
assert.equal(json(await request('/status', 'GET', app)).dailyCount, 0);
|
||||
// The app itself and loopback tools (no browser headers) still get tiles.
|
||||
const tile = await request('/flow/8/1/1.pbf', 'GET', app);
|
||||
assert.equal(tile.status, 200);
|
||||
assert.equal(tile.headers['x-tomtom-cache'], 'MISS');
|
||||
assert.equal((await request('/flow/8/2/1.pbf')).status, 200);
|
||||
assert.equal(
|
||||
(
|
||||
await request('/flow/8/1/1.pbf', 'GET', {
|
||||
host,
|
||||
origin: `http://${host}`,
|
||||
})
|
||||
).headers['x-tomtom-cache'],
|
||||
'HIT',
|
||||
);
|
||||
assert.equal(calls, mode === 'dev' ? 2 : 4);
|
||||
}
|
||||
});
|
||||
|
||||
test('traffic middleware answers 502 to an oversized tile without caching it', async (t) => {
|
||||
isolate(t, { TOMTOM_API_KEY: 'fixture-key', TOMTOM_DAILY_TILE_BUDGET: '' });
|
||||
const bodies = [];
|
||||
|
||||
+21
-4
@@ -323,13 +323,30 @@ export function lineTouchesArea(coords, area) {
|
||||
|
||||
/** Whether a point lies inside a ring of `[lon, lat]` vertices (ray casting). */
|
||||
function ringContains(ring, point) {
|
||||
if (ring.length < 3) return false;
|
||||
// Keep adjacent vertices on the same longitude sheet, as the edge tests do.
|
||||
// Wrapping each vertex around the query point would split a dateline ring
|
||||
// when queried from Greenwich and mistake its complement for its interior.
|
||||
let previous = ring[0][0];
|
||||
let west = previous;
|
||||
let east = previous;
|
||||
const vertices = ring.map(([lon, lat]) => {
|
||||
if (Math.abs(lon - previous) > 180)
|
||||
lon += 360 * Math.round((previous - lon) / 360);
|
||||
previous = lon;
|
||||
west = Math.min(west, lon);
|
||||
east = Math.max(east, lon);
|
||||
return [lon, lat];
|
||||
});
|
||||
const middle = (west + east) / 2;
|
||||
const lon = point.lon + 360 * Math.round((middle - point.lon) / 360);
|
||||
let inside = false;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
|
||||
const [xi, yi] = ring[i];
|
||||
const [xj, yj] = ring[j];
|
||||
for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i, i += 1) {
|
||||
const [xi, yi] = vertices[i];
|
||||
const [xj, yj] = vertices[j];
|
||||
if (
|
||||
yi > point.lat !== yj > point.lat &&
|
||||
point.lon < ((xj - xi) * (point.lat - yi)) / (yj - yi) + xi
|
||||
lon < ((xj - xi) * (point.lat - yi)) / (yj - yi) + xi
|
||||
)
|
||||
inside = !inside;
|
||||
}
|
||||
|
||||
@@ -262,3 +262,78 @@ test('a box radius reaches every point of the box, however large', async () => {
|
||||
const small = await resolveArea({ bbox: [-97.94, 30.1, -97.56, 30.52] });
|
||||
assert.ok(areaRadiusKm(small) < 30);
|
||||
});
|
||||
|
||||
test('polygon containment follows the short edges across the antimeridian', async () => {
|
||||
const ring = [
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
];
|
||||
const areas = [
|
||||
[{ bbox: [179.4, -0.1, 179.6, 0.1] }, true],
|
||||
[{ bbox: [-179.6, -0.1, -179.4, 0.1] }, true],
|
||||
[{ bbox: [179.8, -0.1, -179.8, 0.1] }, true],
|
||||
[{ lat: 0, lon: 179.5, radius_km: 10 }, true],
|
||||
[{ lat: 0, lon: -179.5, radius_km: 10 }, true],
|
||||
[{ lat: 0, lon: 180, radius_km: 10 }, true],
|
||||
[{ lat: 0, lon: -180, radius_km: 10 }, true],
|
||||
[{ bbox: [-0.1, -0.1, 0.1, 0.1] }, false],
|
||||
[{ lat: 0, lon: 0, radius_km: 10 }, false],
|
||||
];
|
||||
for (const vertices of [
|
||||
ring,
|
||||
[...ring, [...ring[0]]],
|
||||
[...ring].reverse(),
|
||||
[...ring.slice(2), ...ring.slice(0, 2)],
|
||||
]) {
|
||||
for (const [input, expected] of areas) {
|
||||
assert.equal(
|
||||
polygonsTouchArea([[vertices]], await resolveArea(input)),
|
||||
expected,
|
||||
JSON.stringify({ vertices, input }),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('antimeridian polygons keep holes empty and include their boundaries', async () => {
|
||||
const outer = [
|
||||
[178, -3],
|
||||
[-178, -3],
|
||||
[-178, 3],
|
||||
[178, 3],
|
||||
];
|
||||
const hole = [
|
||||
[179, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[179, 1],
|
||||
];
|
||||
for (const input of [
|
||||
{ bbox: [179.4, -0.1, 179.6, 0.1] },
|
||||
{ bbox: [-179.6, -0.1, -179.4, 0.1] },
|
||||
{ lat: 0, lon: 180, radius_km: 10 },
|
||||
]) {
|
||||
const area = await resolveArea(input);
|
||||
assert.ok(polygonsTouchArea([[outer]], area));
|
||||
assert.ok(!polygonsTouchArea([[outer, hole]], area));
|
||||
assert.ok(!polygonsTouchArea([[outer, [...hole].reverse()]], area));
|
||||
}
|
||||
const solid = await resolveArea({ bbox: [178.4, -0.1, 178.6, 0.1] });
|
||||
assert.ok(polygonsTouchArea([[outer, hole]], solid));
|
||||
const boundary = await resolveArea({ bbox: [178.9, -0.1, 179.1, 0.1] });
|
||||
assert.ok(polygonsTouchArea([[outer, hole]], boundary));
|
||||
});
|
||||
|
||||
test('polygon containment retains rings spanning more than half the globe', async () => {
|
||||
const longitudes = [-170, -110, -50, 10, 70, 130];
|
||||
const ring = [
|
||||
...longitudes.map((lon) => [lon, -5]),
|
||||
...[...longitudes].reverse().map((lon) => [lon, 5]),
|
||||
];
|
||||
const inside = await resolveArea({ bbox: [99, -1, 101, 1] });
|
||||
const outside = await resolveArea({ bbox: [169, -1, 171, 1] });
|
||||
assert.ok(polygonsTouchArea([[ring]], inside));
|
||||
assert.ok(!polygonsTouchArea([[ring]], outside));
|
||||
});
|
||||
@@ -111,6 +111,8 @@ export const aircraftInArea = defineTool({
|
||||
(record) =>
|
||||
areaContains(area, { lat: record.latitude, lon: record.longitude }) &&
|
||||
!(args.airborne_only && record.onGround) &&
|
||||
((args.min_altitude_m == null && args.max_altitude_m == null) ||
|
||||
Number.isFinite(altitude(record))) &&
|
||||
(args.min_altitude_m == null ||
|
||||
altitude(record) >= args.min_altitude_m) &&
|
||||
(args.max_altitude_m == null ||
|
||||
|
||||
@@ -388,3 +388,62 @@ test('the real OpenSky source marks an hour-old snapshot stale for searches', as
|
||||
assert.deepEqual(result.data.stale_feeds, ['civil']);
|
||||
assert.match(result.summary, /may be stale\.$/);
|
||||
});
|
||||
|
||||
test('altitude bands require a reported altitude from normalized OpenSky records', async () => {
|
||||
const { normalizeOpenSkyAircraft } =
|
||||
await import('../../sources/live/aircraft.js');
|
||||
const state = (id, baro, geometric) =>
|
||||
normalizeOpenSkyAircraft([
|
||||
id,
|
||||
'TEST',
|
||||
'Test',
|
||||
1767225600,
|
||||
1767225600,
|
||||
0,
|
||||
0,
|
||||
baro,
|
||||
false,
|
||||
10,
|
||||
90,
|
||||
0,
|
||||
[],
|
||||
geometric,
|
||||
]);
|
||||
const records = [
|
||||
state('abc001', null, null),
|
||||
state('abc002', 0, null),
|
||||
state('abc003', null, 50),
|
||||
state('abc004', 500, null),
|
||||
];
|
||||
const catalog = composeCatalog({
|
||||
tools: coreTools,
|
||||
services: {
|
||||
aircraft: { getSnapshot: async () => ({ records }) },
|
||||
},
|
||||
});
|
||||
const area = { bbox: [-1, -1, 1, 1] };
|
||||
assert.equal(
|
||||
(await catalog.call('aircraft_in_area', { area })).data.total,
|
||||
4,
|
||||
'unfiltered answers retain unknown altitude',
|
||||
);
|
||||
for (const band of [
|
||||
{ max_altitude_m: 100 },
|
||||
{ min_altitude_m: -500, max_altitude_m: 100 },
|
||||
]) {
|
||||
const result = await catalog.call('aircraft_in_area', { area, ...band });
|
||||
assert.deepEqual(
|
||||
result.data.rows.map((row) => row.id),
|
||||
['abc002', 'abc003'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.data.rows.map((row) => row.altitude_m),
|
||||
[0, 50],
|
||||
);
|
||||
}
|
||||
const minimum = await catalog.call('aircraft_in_area', {
|
||||
area,
|
||||
min_altitude_m: -500,
|
||||
});
|
||||
assert.equal(minimum.data.total, 3);
|
||||
});
|
||||
@@ -288,20 +288,25 @@ export const getFirePerimeters = defineTool({
|
||||
},
|
||||
});
|
||||
|
||||
/** The average vertex of a perimeter's outer rings, enough to place it in an area. */
|
||||
/** Average outer-ring vertices, using a circular longitude mean at the dateline. */
|
||||
function polygonCenter(polygons) {
|
||||
let lat = 0;
|
||||
let lon = 0;
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let count = 0;
|
||||
const toRad = Math.PI / 180;
|
||||
for (const polygon of polygons || []) {
|
||||
for (const [x, y] of polygon?.[0] || []) {
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
lon += x;
|
||||
sinLon += Math.sin(x * toRad);
|
||||
cosLon += Math.cos(x * toRad);
|
||||
lat += y;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count ? { lat: lat / count, lon: lon / count } : null;
|
||||
return count
|
||||
? { lat: lat / count, lon: Math.atan2(sinLon, cosLon) / toRad }
|
||||
: null;
|
||||
}
|
||||
|
||||
export const getTerrainHeight = defineTool({
|
||||
|
||||
@@ -227,6 +227,97 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
});
|
||||
});
|
||||
|
||||
test('fire perimeter queries include dateline interiors and exclude the opposite meridian', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const catalog = catalogWith({ perimeters });
|
||||
for (const area of [
|
||||
{ bbox: [179.4, -0.1, 179.6, 0.1] },
|
||||
{ bbox: [-179.6, -0.1, -179.4, 0.1] },
|
||||
{ lat: 0, lon: 180, radius_km: 10 },
|
||||
]) {
|
||||
const result = await catalog.call('get_fire_perimeters', { area });
|
||||
assert.deepEqual(
|
||||
result.data.rows.map((row) => row.id),
|
||||
['dateline'],
|
||||
);
|
||||
}
|
||||
const elsewhere = await catalog.call('get_fire_perimeters', {
|
||||
area: { bbox: [-0.1, -0.1, 0.1, 0.1] },
|
||||
});
|
||||
assert.equal(elsewhere.data.total, 0);
|
||||
});
|
||||
|
||||
test('fire perimeter coordinates stay at the dateline for closed and multipart outlines', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [178, -3, -178, 3] },
|
||||
});
|
||||
assert.equal(result.data.total, 2);
|
||||
for (const row of result.data.rows) {
|
||||
assert.ok(Math.abs(row.lon) > 179, `${row.id}: ${row.lon}`);
|
||||
assert.ok(Math.abs(row.lon) <= 180);
|
||||
}
|
||||
});
|
||||
|
||||
test('terrain heights are returned in request order', async () => {
|
||||
const terrain = {
|
||||
async getHeights(points) {
|
||||
|
||||
@@ -118,9 +118,11 @@ export const findCctvCameras = defineTool({
|
||||
|
||||
export const getCctvSnapshot = defineTool({
|
||||
name: 'get_cctv_snapshot',
|
||||
title: 'Current camera view',
|
||||
title: 'Camera snapshot',
|
||||
description:
|
||||
'The current image from one public camera, by the id from find_cctv_cameras.',
|
||||
'An image from one public camera, by the id from find_cctv_cameras. ' +
|
||||
'Street View fallback imagery is historical, not the current camera view; ' +
|
||||
'unknown frame provenance is explicit.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { camera_id: { type: 'string', minLength: 1, maxLength: 200 } },
|
||||
@@ -138,7 +140,7 @@ export const getCctvSnapshot = defineTool({
|
||||
`No camera has id ${args.camera_id}; use find_cctv_cameras first`,
|
||||
);
|
||||
const frame = await services.cctv.getFrame(camera, { signal });
|
||||
if (!FRAME_TYPES.has(frame.contentType))
|
||||
if (frame.sourceKind === 'synthetic' || !FRAME_TYPES.has(frame.contentType))
|
||||
throw new ToolError(
|
||||
'unavailable',
|
||||
`Camera ${camera.name || camera.id} has no still image right now`,
|
||||
@@ -149,8 +151,22 @@ export const getCctvSnapshot = defineTool({
|
||||
'The camera image is too large to return',
|
||||
);
|
||||
const name = text(camera.name) || camera.id;
|
||||
const fallback = frame.sourceKind === 'streetview';
|
||||
const current = ['upstream-image', 'hls-pull'].includes(frame.sourceKind);
|
||||
const credit = fallback ? 'Google Street View' : text(camera.credit);
|
||||
const label = fallback
|
||||
? 'Street View fallback for'
|
||||
: current
|
||||
? 'Current view from'
|
||||
: 'Image from';
|
||||
return {
|
||||
summary: `Current view from ${name}${camera.city ? ` in ${camera.city}` : ''}${camera.credit ? `, courtesy of ${camera.credit}` : ''}.`,
|
||||
summary:
|
||||
`${label} ${name}${camera.city ? ` in ${camera.city}` : ''}${credit ? `, courtesy of ${credit}` : ''}.` +
|
||||
(fallback
|
||||
? ' Historical imagery; the current camera frame is unavailable.'
|
||||
: current
|
||||
? ''
|
||||
: ' Frame provenance is unknown.'),
|
||||
data: {
|
||||
view: suggestView(services, {
|
||||
point: { lat: camera.lat, lon: camera.lon },
|
||||
@@ -160,8 +176,10 @@ export const getCctvSnapshot = defineTool({
|
||||
id: camera.id,
|
||||
name,
|
||||
city: text(camera.city),
|
||||
provider: text(camera.provider),
|
||||
credit: text(camera.credit),
|
||||
provider: fallback ? 'Google Street View' : text(camera.provider),
|
||||
credit,
|
||||
source_kind: frame.sourceKind ?? null,
|
||||
current_view: current ? true : fallback ? false : null,
|
||||
mime_type: frame.contentType,
|
||||
bytes: frame.bytes.byteLength,
|
||||
},
|
||||
|
||||
@@ -30,7 +30,13 @@ const cameras = [
|
||||
{ id: 'no-position', name: 'Unplaced' },
|
||||
];
|
||||
const PNG = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const cctv = (frame = { contentType: 'image/png', bytes: PNG }) => ({
|
||||
const cctv = (
|
||||
frame = {
|
||||
contentType: 'image/png',
|
||||
bytes: PNG,
|
||||
sourceKind: 'upstream-image',
|
||||
},
|
||||
) => ({
|
||||
frames: [],
|
||||
async getCatalog() {
|
||||
return { sources: cameras };
|
||||
@@ -104,6 +110,183 @@ test('a snapshot returns the frame as an image with its credit', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('mounted camera fallback provenance survives the source and MCP image result', async (t) => {
|
||||
const { cctvProxy } = await import('../../../server/providers/cctv.js');
|
||||
const { createCctvSource } = await import('../../layers/cctv/source.js');
|
||||
const camera = {
|
||||
id: 'fixture-camera',
|
||||
name: 'Fixture crossing',
|
||||
city: 'Fixture City',
|
||||
provider: 'Fixture transport agency',
|
||||
credit: 'Fixture transport agency',
|
||||
lat: 30.2685,
|
||||
lon: -97.7425,
|
||||
headingDeg: 180,
|
||||
fovDeg: 60,
|
||||
url: 'https://camera.example/current.png',
|
||||
feedType: 'image',
|
||||
};
|
||||
const environment = {
|
||||
CCTV_SOURCES_JSON: JSON.stringify([camera]),
|
||||
CCTV_PREFER_AUSTIN: '0',
|
||||
CCTV_FORCE_AUSTIN: '0',
|
||||
CCTV_SOURCES_FILE: 'missing-cctv-provenance-fixture.json',
|
||||
GOOGLE_MAPS_SERVER_API_KEY: 'fixture-key',
|
||||
GOOGLE_MAPS_API_KEY: '',
|
||||
};
|
||||
for (const [name, value] of Object.entries(environment)) {
|
||||
const previous = process.env[name];
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env[name];
|
||||
else process.env[name] = previous;
|
||||
});
|
||||
process.env[name] = value;
|
||||
}
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
let upstreamAvailable = false;
|
||||
const calls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (raw) => {
|
||||
const url = new URL(raw);
|
||||
calls.push(url.origin);
|
||||
if (url.origin === 'https://camera.example')
|
||||
return upstreamAvailable
|
||||
? new Response(PNG, { headers: { 'Content-Type': 'image/png' } })
|
||||
: new Response(null, { status: 503 });
|
||||
assert.equal(
|
||||
url.origin,
|
||||
'https://maps.googleapis.com',
|
||||
'no actual upstream is contacted',
|
||||
);
|
||||
assert.equal(url.searchParams.get('key'), 'fixture-key');
|
||||
return new Response(PNG, { headers: { 'Content-Type': 'image/png' } });
|
||||
});
|
||||
let middleware;
|
||||
cctvProxy().configureServer({
|
||||
middlewares: {
|
||||
use(route, handler) {
|
||||
assert.equal(route, '/api/cctv');
|
||||
middleware = handler;
|
||||
},
|
||||
},
|
||||
});
|
||||
const source = createCctvSource({
|
||||
fetchImpl: async (path) => {
|
||||
assert.ok(path.startsWith('/api/cctv/'));
|
||||
const response = {
|
||||
writeHead(status, headers) {
|
||||
this.status = status;
|
||||
this.headers = headers;
|
||||
},
|
||||
end(body) {
|
||||
this.body = body;
|
||||
},
|
||||
};
|
||||
await middleware(
|
||||
{ url: path.slice('/api/cctv'.length), method: 'GET', headers: {} },
|
||||
response,
|
||||
);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
headers: response.headers,
|
||||
});
|
||||
},
|
||||
});
|
||||
const catalog = composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { cctv: source },
|
||||
});
|
||||
const fallback = await catalog.call('get_cctv_snapshot', {
|
||||
camera_id: camera.id,
|
||||
});
|
||||
assert.equal(fallback.data.source_kind, 'streetview');
|
||||
assert.equal(fallback.data.current_view, false);
|
||||
assert.equal(fallback.data.credit, 'Google Street View');
|
||||
assert.match(fallback.summary, /Street View fallback/);
|
||||
assert.match(fallback.summary, /Historical imagery/);
|
||||
assert.doesNotMatch(
|
||||
fallback.summary,
|
||||
/Current view|courtesy of Fixture transport agency/,
|
||||
);
|
||||
assert.equal(
|
||||
fallback.images.length,
|
||||
1,
|
||||
'the historical image stays available with its caveat',
|
||||
);
|
||||
assert.deepEqual(calls, [
|
||||
'https://camera.example',
|
||||
'https://maps.googleapis.com',
|
||||
]);
|
||||
upstreamAvailable = true;
|
||||
const current = await catalog.call('get_cctv_snapshot', {
|
||||
camera_id: camera.id,
|
||||
});
|
||||
assert.equal(current.data.source_kind, 'upstream-image');
|
||||
assert.equal(current.data.current_view, true);
|
||||
assert.equal(current.data.credit, camera.credit);
|
||||
assert.match(current.summary, /^Current view from/);
|
||||
const server = createMcpServer({ catalog, name: 'test', version: '1' });
|
||||
upstreamAvailable = false;
|
||||
const result = await server.handle({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: { name: 'get_cctv_snapshot', arguments: { camera_id: camera.id } },
|
||||
});
|
||||
assert.ok(
|
||||
result.result.content.some(
|
||||
(entry) => entry.type === 'text' && /Historical imagery/.test(entry.text),
|
||||
),
|
||||
);
|
||||
assert.ok(result.result.content.some((entry) => entry.type === 'image'));
|
||||
process.env.GOOGLE_MAPS_SERVER_API_KEY = '';
|
||||
const placeholder = await source.getFrame(camera);
|
||||
assert.equal(placeholder.sourceKind, 'synthetic');
|
||||
assert.equal(placeholder.contentType, 'image/svg+xml');
|
||||
await assert.rejects(
|
||||
catalog.call('get_cctv_snapshot', { camera_id: camera.id }),
|
||||
(error) => error.code === 'unavailable',
|
||||
);
|
||||
const unavailable = await server.handle({
|
||||
jsonrpc: '2.0',
|
||||
id: 2,
|
||||
method: 'tools/call',
|
||||
params: { name: 'get_cctv_snapshot', arguments: { camera_id: camera.id } },
|
||||
});
|
||||
assert.equal(unavailable.result.isError, true);
|
||||
assert.ok(
|
||||
!unavailable.result.content.some((entry) => entry.type === 'image'),
|
||||
);
|
||||
});
|
||||
|
||||
test('snapshot placeholders are refused and unknown frame provenance is explicit', async () => {
|
||||
const synthetic = composeCatalog({
|
||||
tools: coreTools,
|
||||
services: {
|
||||
cctv: cctv({
|
||||
contentType: 'image/png',
|
||||
bytes: PNG,
|
||||
sourceKind: 'synthetic',
|
||||
}),
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
synthetic.call('get_cctv_snapshot', { camera_id: 'austin-1' }),
|
||||
(error) => error.code === 'unavailable',
|
||||
);
|
||||
const unknown = await composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { cctv: cctv({ contentType: 'image/png', bytes: PNG }) },
|
||||
}).call('get_cctv_snapshot', { camera_id: 'austin-1' });
|
||||
assert.equal(unknown.data.current_view, null);
|
||||
assert.equal(
|
||||
unknown.data.credit,
|
||||
cameras[0].credit,
|
||||
'catalog attribution is preserved',
|
||||
);
|
||||
assert.match(unknown.summary, /provenance is unknown/);
|
||||
assert.doesNotMatch(unknown.summary, /Current view/);
|
||||
});
|
||||
|
||||
test('unknown cameras, video-only feeds and oversized frames are reported', async () => {
|
||||
const catalog = (frame) =>
|
||||
composeCatalog({ tools: coreTools, services: { cctv: cctv(frame) } });
|
||||
|
||||
@@ -344,7 +344,6 @@ export function createRecentImageryPanel({
|
||||
const detailsHost = el('div', 'ri-details', root);
|
||||
detailsHost.id = 'ri-details';
|
||||
let detailsOpen = false;
|
||||
let detailsShownOpen = false;
|
||||
const details = createRailCards({
|
||||
container: detailsHost,
|
||||
document,
|
||||
@@ -352,6 +351,8 @@ export function createRecentImageryPanel({
|
||||
onOpen: () => {
|
||||
detailsOpen = !detailsOpen;
|
||||
render();
|
||||
// After the render: preserveScroll() puts the old position back.
|
||||
if (detailsOpen) revealCard(container, detailsHost.children[0]);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -875,9 +876,6 @@ export function createRecentImageryPanel({
|
||||
],
|
||||
},
|
||||
]);
|
||||
if (detailsOpen && !detailsShownOpen)
|
||||
revealCard(container, detailsHost.children[0]);
|
||||
detailsShownOpen = detailsOpen;
|
||||
}
|
||||
|
||||
// ---- divider ----------------------------------------------------------
|
||||
|
||||
@@ -1147,6 +1147,29 @@ test('the body scroll position survives renders even when DOM mutations reset it
|
||||
assert.equal(f.body.scrollTop, 120);
|
||||
});
|
||||
|
||||
test('opening DETAILS scrolls its card into view, and closing it does not scroll', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
// The body is 100 px high and scrolled 40 px; the card opens 150 px down.
|
||||
f.body.scrollTop = 40;
|
||||
f.body.clientHeight = 100;
|
||||
f.body.getBoundingClientRect = () => ({ top: 0 });
|
||||
const header = f
|
||||
.byId('ri-details')
|
||||
.find((node) => node.classList.contains('rail-card-header'));
|
||||
const card = header.parentNode;
|
||||
card.getBoundingClientRect = () => ({
|
||||
top: 150,
|
||||
height: card.dataset.open === 'true' ? 60 : 0,
|
||||
});
|
||||
header.click();
|
||||
assert.equal(card.dataset.open, 'true');
|
||||
assert.equal(f.body.scrollTop, 150);
|
||||
header.click();
|
||||
assert.equal(card.dataset.open, 'false');
|
||||
assert.equal(f.body.scrollTop, 150);
|
||||
});
|
||||
|
||||
test('destroy returns every listener, the divider and the panel state', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
|
||||
Reference in new issue
Block a user