Compare commits

..
Author SHA1 Message Date
Said Turksever 7ba53f6d0e fix(server): charge the track limiter for upstream calls only and stop replaying stale errors
A cached answer or a malformed request costs OpenSky nothing, so neither
is charged to the 30/min window. During a /tracks cooldown only a cached
track is replayed; an old cached error gives way to the cooldown refusal.
The 429 that arms the cooldown is no longer cached, so it and its repeats
carry Retry-After. No token is minted unless the upstream is called.
2026-11-23 01:23:44 +00:00
Said Turksever 2eef8cd902 Merge #685 (track backfill credit governor) onto current main 2026-11-23 01:20:39 +00:00
daika a01eaff89e Merge remote-tracking branch 'upstream/main' into fix/opensky-track-credit-governor 2026-11-09 17:55:50 +07:00
daikaginza d8a8f1b917 test(opensky): fail the retired-route case if it reaches any upstream
The stub answered every URL, so the case still passed had the military
route started fetching again while still answering 503. It now counts
non-OpenSky calls and requires zero.
2026-10-24 13:38:30 +07:00
daikaginza 678a816e65 Merge upstream main 9d3548c27 into fix/opensky-track-credit-governor
Upstream retired the ADSB.lol trace behind /api/military/track: the route
now answers a fixed 503 without contacting any upstream. The limiter this
branch put on that route guarded an adsb.lol call that no longer happens,
so it is dropped, and the limiter, its test, the changelog entry and
CURRENT-STATE now describe /api/flights/track alone. The military layer
backfills through its source's getTrack, so the demand note names only
the flights layer.
2026-10-24 13:22:50 +07:00
daikaginza bfcf12af49 fix(server): give /tracks its own credit cooldown, armed by its own 429
The branch read the /states/all cooldown from /api/flights and never set
one from /tracks/all, which is backwards for an API that meters the two
separately: a flights cooldown blocked backfill that still had credits,
and a /tracks 429 left every other icao24 free to ask again.

tracks.js now keeps a cooldown for the /tracks bucket, armed by a 429
from /tracks/all with OpenSky's retry-after (opensky.js exports its
existing parser so both buckets read the header the same way). The two
routes get separate limiters, and a limiter refusal sends Retry-After 60,
the window, rather than 10.
2026-10-23 12:34:46 +07:00
daikaginza a073e6e658 test(server): pin the /tracks credit bucket the way OpenSky meters it
OpenSky keeps /states/*, /tracks/* and /flights/* as three independent
credit buckets. The cases pin that a 429 from /tracks/all stands every
other icao24 down (review on #685), that a /states/all 429 does not, that
the two backfill routes meter separately, and that a limiter refusal
names its 60 s window. Four of them fail on the branch as it stands.
2026-10-23 12:34:46 +07:00
daikaginza f2e8e63c48 Merge remote-tracking branch 'upstream/main' into fix/opensky-track-credit-governor 2026-10-23 12:30:50 +07:00
daikaginza 5668c0c08b docs(changelog): move the entry into a changelog.d fragment
Main now takes pending entries as changelog.d/<pr>-<slug>.md
files (#787), so the entry leaves CHANGELOG.md for changelog.d/685-opensky-track-credit-governor.md.
2026-10-18 13:35:41 +07:00
daikaginza 2e2cae4701 Merge upstream/main 93ea088f4 2026-10-18 13:35:24 +07:00
daikaginza d380977928 Merge remote-tracking branch 'upstream/main' into fix/opensky-track-credit-governor
# Conflicts:
#	CHANGELOG.md
2026-10-16 09:21:54 +07:00
daikaginza 9bb557bc2a Merge remote-tracking branch 'upstream/main' into fix/opensky-track-credit-governor 2026-10-16 09:16:41 +07:00
daikaginza 0c1b017699 Merge upstream/main, following its route renames
main renamed the three routes this branch governs:

  /api/opensky       -> /api/flights
  /api/opensky-track -> /api/flights/track
  /api/adsblol/trace -> /api/military/track

The merge took main's names in the route registrations cleanly, which left the
branch's own material pointing at routes that no longer exist — including
`openSkyTrackGovernor.test.mjs`, which looks its handlers up BY path, so it
failed with "handler is not a function" rather than with anything that named
the cause. Renamed in the test, in both doc comments and in the CHANGELOG and
CURRENT-STATE entries this branch adds. The historical CHANGELOG entry that
main also carries is left alone: it records what was true at that release.

Nothing else about the change moved. The limiter, its sizing, the cooldown
read and the serve-stale path are byte-identical to the branch tip; the only
other differences from it are the two append-only bookkeeping files.

  node --test src/openSkyTrackGovernor.test.mjs \
    src/tooling/liveProviders.test.mjs src/proxyErrorResponses.test.mjs
    tests 34  pass 34  fail 0
  npm run format:check            Checked 1210 source files.
  npm run check:boundaries        clean
  npm run layer-token:check       28 published, 0 new
2026-10-05 17:39:29 +07:00
daikaginza 22804a46da Merge remote-tracking branch 'upstream/main' into fix/opensky-track-credit-governor 2026-09-28 08:47:27 +07:00
daikaginza 65018015a0 fix(server): stop track backfill from spending the OpenSky credit budget
`/api/opensky-track` costs 4 OpenSky credits per call against the same
~4000/day account as `/api/opensky`, but participated in none of that
proxy's credit governor. Its 60-second per-icao cache bounds memory, not
spend: `icao24` is six hex digits, so a caller that varies it produces a
fresh key and a fresh upstream call every time.

Both track-backfill routes now carry an always-on 30/min per-client
limiter (90 global) — the band `/api/geocode` and `/api/regional-brief`
already use, and far above the real demand, which is one backfill per
aircraft the operator selects.

`/api/opensky-track` additionally reads the 429 cooldown `/api/opensky`
already maintains. While the account is out of budget it serves any
cached track and otherwise answers 429 with the remaining cooldown,
instead of minting a token and spending four more credits. adsb.lol is
free and unmetered, so only the limiter applies there.
2026-09-27 23:01:01 +07:00
42 changed files with 631 additions and 3217 deletions

No files matched your search

@@ -1,6 +0,0 @@
- Recent Imagery takes a box dragged across the dateline as the short box across
±180° instead of refusing it as about 360° wide. A day counts when either side
has imagery. A side confirmed empty is not draped, and the VIIRS overview
drapes only a side confirmed to have data. Voice accepts named areas across
the dateline. EXPORT and `get_recent_imagery` refuse such a box, since
Worldview Snapshots cannot draw one (Byrd-IT, #1540).
-6
View File
@@ -1,6 +0,0 @@
- The app opens with the loading screen's logo turning into the globe: the
eye's arcs fly out, the planet in the pupil becomes the real globe, which
spins, grows and stops with the whole planet in view over your country, taken
from the browser's time zone. The title's logo goes back to that view. A
share link, a Stories link, reduced motion and `?intro=0` open as before
(gekh, #1909).
@@ -0,0 +1,11 @@
- Stop the OpenSky track-backfill proxy from turning a varied `icao24` into
unbounded upstream spend. `/api/flights/track` carries an always-on
30-per-minute per-client limiter (90 global) on upstream calls (a cached
answer or a malformed request is not charged), and a
`429` from OpenSky `/tracks/all` now starts a cooldown for that credit
bucket: until OpenSky's retry-after passes, any cached track is served and
other lookups are answered `429` locally instead of asking for 4 more
credits. The `/tracks/*` bucket is separate from the `/states/*` one
`/api/flights` spends, so a flights cooldown does not block backfill. The
existing 60-second per-key cache bounds memory, not spend. Single-aircraft
backfill, issued once per selected contact, is unaffected (daikaginza, #685).
+4 -3
View File
@@ -8890,10 +8890,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool,
pins and share links already supply complete boxes.
- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- **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. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. 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.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `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. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), 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. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset 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. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
- **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 rail markup in the Context view (`src/ui/views/ContextView.vue`) 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).
@@ -9011,6 +9011,7 @@ apply to `public/` assets or built-preview serving.
- `/api/flights`, `/api/military`, and `/api/route` answer `405 Method Not Allowed` with `Allow: GET` to anything but `GET`, before rate limiting and any upstream call.
- `/api/flights` negotiates gzip. The cached global snapshot and the regional adsb.lol fallback are each gzipped once per refresh (about 860 KB becomes about 250 KB). Clients that offer gzip get that frame; other clients, and bodies under 1 KiB or that gzip cannot shrink, get identity bytes. Both answers carry `Vary: Accept-Encoding`. Uncached bodies, such as auth failures, are never sent under a cached frame's encoding.
- Track endpoints: `/api/vessels/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/flights/track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/military/track?hex=` (400 for an invalid hex, otherwise `503 history_unavailable` with `Retry-After: 1800` and `Cache-Control: no-store`, no upstream request; military tracking uses its locally accumulated trail).
- `/api/flights/track` carries an always-on per-client limiter of 30 upstream calls/minute (90 global; refusals send `Retry-After: 60`; cached answers and malformed requests are not charged), because its 60s per-key cache bounds memory rather than spend: a caller varying `icao24` produces a fresh key and a fresh upstream call each time. A `429` from OpenSky `/tracks/all` starts a cooldown for the `/tracks/*` credit bucket (OpenSky's retry-after, bounded 30 s–30 min): while it runs, `/api/flights/track` serves any cached track (not a cached error) and otherwise answers `429` with the remaining cooldown, including to the request that tripped it, instead of spending 4 more credits. It does not read `/api/flights`'s `/states/*` cooldown, since OpenSky meters the two buckets independently.
- Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped.
- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message.
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env node
// Writes src/data/homeCountries.js: each time zone's country, and where the
// opening stops over that country.
//
// node scripts/build-home-countries.mjs [path/to/zone.tab]
//
// Zones come from tzdata's zone.tab (macOS and most Linux systems ship it at
// /usr/share/zoneinfo/zone.tab), with the older names ICU still reports for
// some of them (Asia/Calcutta for Asia/Kolkata): a browser may give either.
// A country's point is the centroid of its largest part in the Natural Earth
// countries pack (the contiguous United States, mainland France), or the
// zone's own place where the pack has no such country.
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { geometryOf } from '../src/data/adminBoundaries.js';
const root = new URL('../', import.meta.url);
const zoneTab = process.argv[2] ?? '/usr/share/zoneinfo/zone.tab';
const pack = JSON.parse(
readFileSync(
new URL('src/data/local_data/natural_earth/countries.json', root),
'utf8',
),
);
const out = new URL('src/data/homeCountries.js', root);
const round = (value) => Math.round(value * 10) / 10;
/** ISO 6709 `±DDMM[SS]±DDDMM[SS]` → [lat, lon]. */
function iso6709(text) {
const [, lat, lon] = text.match(/^([+-]\d+)([+-]\d+)$/);
const part = (s, degreeDigits) => {
const sign = s[0] === '-' ? -1 : 1;
const d = s.slice(1);
const deg = Number(d.slice(0, degreeDigits));
const min = Number(d.slice(degreeDigits, degreeDigits + 2));
const sec = Number(d.slice(degreeDigits + 2) || 0);
return sign * (deg + min / 60 + sec / 3600);
};
return [part(lat, 2), part(lon, 3)];
}
const largest = new Map();
for (const feature of pack.features) {
if (feature.type !== 'Country' || !/^[A-Z]{2}$/.test(feature.iso2)) continue;
const geometry = geometryOf({ feature, decimals: pack.meta.decimals });
const held = largest.get(feature.iso2);
if (!held || geometry.areaKm2 > held.areaKm2)
largest.set(feature.iso2, geometry);
}
const zones = new Map();
const centres = new Map();
const icuName = (zone) => {
try {
return new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions()
.timeZone;
} catch {
return null;
}
};
for (const line of readFileSync(zoneTab, 'utf8').split('\n')) {
if (!line || line.startsWith('#')) continue;
const [country, place, zone] = line.split('\t');
zones.set(zone, country);
const icu = icuName(zone);
if (icu && icu !== zone && !zones.has(icu)) zones.set(icu, country);
if (centres.has(country)) continue;
const label = largest.get(country)?.label;
centres.set(
country,
label ? [round(label.lat), round(label.lon)] : iso6709(place).map(round),
);
}
const sortedEntries = (map) =>
[...map].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
const lines = [
'// Generated by scripts/build-home-countries.mjs. Do not edit by hand.',
'// Sources: tzdata zone.tab (public domain) and the Natural Earth countries',
'// pack in src/data/local_data/natural_earth (public domain).',
'',
'/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */',
'export const COUNTRY_CENTRES = {',
...sortedEntries(centres).map(
([country, [lat, lon]]) => ` ${country}: [${lat}, ${lon}],`,
),
'};',
'',
'/** Time zone (tzdata and ICU names) → ISO 3166 country. */',
'export const ZONE_COUNTRIES = {',
...sortedEntries(zones).map(
([zone, country]) => ` '${zone}': '${country}',`,
),
'};',
'',
];
writeFileSync(out, lines.join('\n'));
console.log(
`${fileURLToPath(out)}: ${centres.size} countries, ${zones.size} zones`,
);
+2 -1
View File
@@ -1703,5 +1703,6 @@
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css"
"src/ui/styles/station.css",
"src/openSkyTrackGovernor.test.mjs"
]
+2 -1
View File
@@ -392,6 +392,8 @@
"server/providers/common/compress.js",
"server/providers/common/http.js",
"server/providers/common/query.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js",
"server/providers/aircraft/opensky.js",
"server/providers/aircraft/adsb-lol.js",
"server/providers/aircraft/enrichment.js",
@@ -4303,7 +4305,6 @@
"src/render/contract/index.js",
"src/sources/sourceSlot.js",
"src/app/sources.js",
"src/app/openingIntro.js",
"src/app/startupChrome.js",
"src/app/stateChannel.js",
"src/app/surfaceServices.js",
+4 -2
View File
@@ -43,11 +43,13 @@ const OPENSKY_STATES_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/**
* Credit-governor cooldown for a 429: OpenSky's retry-after bounded to
* 30 s … 30 min, or 2 min when the header is absent.
* 30 s … 30 min, or 2 min when the header is absent. Exported for the
* `/tracks/*` governor in tracks.js, which reads the same header for its own
* bucket.
* @param {Response} upstream Rate-limited response.
* @returns {number} Cooldown (ms).
*/
function openSkyRateLimitCooldownMs(upstream) {
export function openSkyRateLimitCooldownMs(upstream) {
// headers.get() gives null when absent, and Number(null) is 0, not NaN.
const header = upstream.headers.get('x-rate-limit-retry-after-seconds');
const retryAfterSec =
+110 -8
View File
@@ -1,12 +1,19 @@
import { getOpenSkyToken } from './opensky.js';
import { getOpenSkyToken, openSkyRateLimitCooldownMs } from './opensky.js';
import { readCappedResponseText } from '../common/http.js';
import { makeRateLimiter, clientKey } from '../common/rate-limit.js';
/**
* Vite plugin: aircraft track-history backfill proxies (PRD WS-F F1/F2).
*
* /api/flights/track?icao24=<hex6> — OpenSky GET /tracks/all (experimental;
* own credit bucket, 4 credits per call on the free tier). OAuth via the
* 4 credits per call from the `/tracks/*` bucket, which OpenSky keeps
* separate from the `/states/*` one `/api/flights` spends). OAuth via the
* shared coalesced token. 60s per-icao cache; 404/429 forwarded so the
* client can fall back to its accumulated trail silently.
* client can fall back to its accumulated trail silently. It has its own
* per-IP limiter, and a 429 from /tracks starts a cooldown for that
* bucket — the per-icao cache bounds memory, not spend, since a different
* `icao24` is simply a different key. The limiter counts upstream calls
* only: a malformed request or one answered from the cache costs OpenSky
* nothing and is not charged.
* /api/military/track?hex=<hex> — compatibility refusal for the retired,
* undocumented ADSB.lol trace route. The standalone military source uses
* locally accumulated trails; provider-supplied history remains optional.
@@ -15,9 +22,52 @@ export function trackBackfillProxies() {
const TRACK_CACHE_MS = 60000;
const TRACK_CACHE_MAX = 200;
const RESPONSE_CAP_BYTES = 5 * 1024 * 1024;
/**
* Requests/min/IP. The per-icao cache below bounds MEMORY, not request
* volume: every distinct `icao24` is a fresh key, and `icao24` is 6 hex
* digits, so varying it walks straight past the cache into a live call.
*
* Sized against demand, not guessed: a backfill is issued once per aircraft
* the operator SELECTS (`_backfillTrail`, fired from the tracked-contact
* path in the flights layer), and re-selecting the
* same aircraft inside a minute is served from cache. The assistant's
* `get_aircraft_track` tool asks once per call, a handful per turn. 30/min
* is a target switch every two seconds, sustained — well clear of either,
* and the same band `/api/geocode` and `/api/regional-brief` already use.
*/
const TRACK_RATE_PER_MIN = 30;
const TRACK_RATE_WINDOW_MS = 60_000;
const allowOpenSky = makeRateLimiter({
windowMs: TRACK_RATE_WINDOW_MS,
max: TRACK_RATE_PER_MIN,
globalMax: TRACK_RATE_PER_MIN * 3,
});
/**
* `/tracks/*` credit governor: a 429 from /tracks/all means that bucket is
* empty for every `icao24`, so no upstream call is made until OpenSky's
* retry-after passes. The `/states/*` cooldown in opensky.js is a different
* bucket and does not apply here.
*/
let openSkyTracksCooldownUntil = 0;
const openSkyTracksGovernor = {
remainingMs: () => Math.max(0, openSkyTracksCooldownUntil - Date.now()),
arm(upstream) {
openSkyTracksCooldownUntil =
Date.now() + openSkyRateLimitCooldownMs(upstream);
},
};
/** @type {Map<string, {at:number,status:number,body:string}>} */
const cache = new Map();
/** Shared refusal shape, matching the other rate-limited proxies. */
function refuse(res, retryAfterSeconds) {
res.writeHead(429, {
'Content-Type': 'application/json',
'Retry-After': String(Math.max(1, Math.ceil(retryAfterSeconds))),
});
res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
}
function cachePut(key, entry) {
cache.set(key, entry);
if (cache.size > TRACK_CACHE_MAX) {
@@ -26,19 +76,63 @@ export function trackBackfillProxies() {
}
}
async function proxyJson(res, key, upstreamUrl, headers = {}) {
/**
* @param {object} [options]
* @param {() => Promise<object>|object} [options.headers] Request headers,
* resolved only when the upstream is actually called.
* @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [options.governor]
* Credit cooldown for a metered upstream. While it is cooling the upstream
* is not called, though an already-fetched track may still be served (it
* costs nothing further); an upstream 429 arms it.
* @param {() => boolean} [options.admit] Asked once, immediately before an
* upstream call; false refuses the request with a 429.
*/
async function proxyJson(
res,
key,
upstreamUrl,
{ headers = () => ({}), governor, admit } = {},
) {
const blockedMs = governor?.remainingMs() ?? 0;
const cached = cache.get(key);
if (cached && Date.now() - cached.at < TRACK_CACHE_MS) {
const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS;
// Serve-stale while the account is cooling, the way `/api/flights` does:
// a stale trail beats no trail, and replaying a cached body spends no
// credits. Only a track is worth replaying past its window: an old error
// says nothing about now, so it gives way to the cooldown refusal.
const replayable =
cached && (fresh || (blockedMs > 0 && cached.status === 200));
if (replayable) {
res.statusCode = cached.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(cached.body);
return;
}
if (blockedMs > 0) {
refuse(res, blockedMs / 1000);
return;
}
if (admit && !admit()) {
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
return;
}
const upstream = await fetch(upstreamUrl, {
headers,
headers: await headers(),
signal: AbortSignal.timeout(12000),
});
if (upstream.status === 429 && governor) {
// The cooldown now answers for every key, with the time left; caching
// this 429 would replay it for the key without one.
governor.arm(upstream);
try {
await upstream.body?.cancel();
} catch {
/* nothing left to release */
}
refuse(res, governor.remainingMs() / 1000);
return;
}
const { tooLarge, text } = await readCappedResponseText(
upstream,
RESPONSE_CAP_BYTES,
@@ -78,12 +172,20 @@ export function trackBackfillProxies() {
);
return;
}
const token = await getOpenSkyToken();
await proxyJson(
res,
`osky:${icao24}`,
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
token ? { Authorization: `Bearer ${token}` } : {},
{
// Resolved only for a live call: no token is minted for a cached
// answer, a refusal, or while the /tracks bucket is cooling.
headers: async () => {
const token = await getOpenSkyToken();
return token ? { Authorization: `Bearer ${token}` } : {};
},
governor: openSkyTracksGovernor,
admit: () => allowOpenSky(clientKey(req)),
},
);
} catch (error) {
res.statusCode = 502;
-281
View File
@@ -1,281 +0,0 @@
import { cameraOf } from '../render/rendererOf.js';
/**
* The opening: once the world has loaded, the loading screen's logo turns
* into the globe. The words fade and the logo glides to the centre; the eye's
* arcs fly at the viewer; the drawn planet in the pupil gives way to the real
* one, drawn the same size behind it; the real one spins and grows, slowing
* until it stops, the whole planet in view, over the start view (the
* visitor's country). Everything is timed from one clock, in ms.
*/
export const OPENING = Object.freeze({
/** The words fade and the logo moves to the centre. */
centreMs: 450,
// The rest is timed from the end of the move.
/** The arcs grow and fade. */
arcsMs: 700,
/** The background clears to the globe. */
veilMs: Object.freeze([200, 700]),
/** The drawn planet fades into the real one. */
pupilMs: Object.freeze([500, 1100]),
/** The camera's flight in. */
flightStartMs: 300,
flightMs: 4200,
/** How far the globe turns on the way in, degrees. */
spinDeg: 360,
});
const EARTH_RADIUS_M = 6371000;
// logo.svg: its viewBox width and the drawn planet's radius, in its units.
const LOGO_WIDTH = 775;
const PUPIL_RADIUS = 120.33;
/** Never start further out than this, metres. */
const MAX_FAR_HEIGHT_M = 4e8;
/** Openings in progress on this page. */
let playing = 0;
/**
* Whether an opening is playing: the far start shows the globe as a speck,
* which the globe-in-view recovery would otherwise turn the camera back to.
*/
export function openingPlaying() {
return playing > 0;
}
const clamp01 = (x) => Math.min(1, Math.max(0, x));
const easeInCubic = (x) => x ** 3;
const easeOutCubic = (x) => 1 - (1 - x) ** 3;
const easeInOutCubic = (x) =>
x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
const span = (t, [from, to]) => clamp01((t - from) / (to - from));
/**
* Where each part of the opening stands `t` ms after it starts.
* @param {number} t
*/
export function openingStage(t, timing = OPENING) {
const move = clamp01(t / timing.centreMs);
const after = t - timing.centreMs;
const arcs = easeInCubic(clamp01(after / timing.arcsMs));
const flight = clamp01((after - timing.flightStartMs) / timing.flightMs);
return {
/** The words' opacity. */
text: 1 - move,
/** How far the logo has moved to the centre, 0–1. */
centre: easeInOutCubic(move),
arcsScale: 1 + 5 * arcs,
arcsOpacity: 1 - arcs,
/** The loading screen's background opacity. */
veil: 1 - span(after, timing.veilMs),
pupilOpacity: 1 - span(after, timing.pupilMs),
/** The flight's progress, 0–1. */
flight,
done: flight >= 1,
};
}
/**
* The camera `flight` (0–1) of the way in: from `farHeight` over the
* equator, a turn of `spinDeg` west to east that slows to a stop over
* `target`, closing in on `target.height`.
*/
export function openingPose(
flight,
{ target, farHeight, spinDeg = OPENING.spinDeg },
) {
const f = clamp01(flight);
const closing = easeInOutCubic(f);
const height = Math.exp(
Math.log(farHeight) +
(Math.log(target.height) - Math.log(farHeight)) * closing,
);
const lon = target.lon + spinDeg * (1 - easeOutCubic(f));
return {
lon: ((((lon + 180) % 360) + 360) % 360) - 180,
lat: target.lat * closing,
height,
};
}
/**
* The globe's radius on screen, pixels, from `height` metres straight above
* it, through a lens of vertical angle `fovy` on a view `viewportHeight`
* pixels tall.
*/
export function globeRadiusPx(height, { fovy, viewportHeight }) {
const angle = Math.asin(EARTH_RADIUS_M / (EARTH_RADIUS_M + height));
return (Math.tan(angle) / Math.tan(fovy / 2)) * (viewportHeight / 2);
}
/** The height at which the globe's radius on screen is `radiusPx`. */
export function heightForGlobeRadius(radiusPx, { fovy, viewportHeight }) {
const tangent = (radiusPx * Math.tan(fovy / 2)) / (viewportHeight / 2);
return EARTH_RADIUS_M / Math.sin(Math.atan(tangent)) - EARTH_RADIUS_M;
}
/**
* Whether the page opens with the opening: not where motion is reduced, not
* on a Stories link (Stories opens its own view) and not with `?intro=0`.
*/
export function openingWanted(win = globalThis.window) {
if (!win) return false;
if (win.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
return false;
const params = new URLSearchParams(win.location?.search ?? '');
return !(
params.get('intro') === '0' ||
params.has('story') ||
params.has('stories')
);
}
/**
* Play the opening over `loadingScreen`, from where the camera stands (the
* start view). Returns null when it does not play; else `done`, which
* settles when the camera has stopped, and `cancel()`. A click, a key or the
* wheel skips to the start view; any other camera move stops it where it is. The loading
* screen is `hidden` once the real globe shows, or at once on a cancel.
* @param {{viewer: object, loadingScreen: HTMLElement, win?: Window,
* camera?: object}} options `camera` is the viewer's camera port unless given.
*/
export function playOpeningIntro({
viewer,
loadingScreen,
win = globalThis.window,
camera = null,
}) {
if (!openingWanted(win)) return null;
try {
camera ??= cameraOf(viewer);
} catch {
return null;
}
const target = camera.pose();
if (
!Number.isFinite(target?.height) ||
!Number.isFinite(target.lon) ||
!Number.isFinite(target.lat)
)
return null;
const doc = loadingScreen.ownerDocument;
const logo = loadingScreen.querySelector('.loader-logo');
const svg = logo?.querySelector('svg');
const part = (id) => svg?.querySelector(`#${id}`);
const arcs = [part('outer_eye'), part('inner_eye')].filter(Boolean);
// The drawn planet; the whole logo where it is an <img>.
const pupil = svg
? [part('globe'), part('globe_cage')].filter(Boolean)
: [logo].filter(Boolean);
loadingScreen.classList.add('opening');
playing += 1;
// The planet looks out of the middle of the eye again.
for (const element of pupil) element.style.transform = 'none';
const globe = part('globe');
const pupilRect = (globe ?? logo)?.getBoundingClientRect();
const view = (
doc.getElementById('cesiumContainer') ?? doc.documentElement
).getBoundingClientRect();
const viewportHeight = view.height || win.innerHeight;
const aspect = (view.width || win.innerWidth) / viewportHeight;
// Cesium's default lens: 60° across the wider side.
const fovy = Number.isFinite(target.fovy)
? target.fovy
: aspect > 1
? 2 * Math.atan(Math.tan(Math.PI / 6) / aspect)
: Math.PI / 3;
const lens = { fovy, viewportHeight };
const pupilRadius = pupilRect
? globe
? pupilRect.width / 2
: (pupilRect.width * PUPIL_RADIUS) / LOGO_WIDTH
: 20;
const farHeight = Math.min(
MAX_FAR_HEIGHT_M,
Math.max(target.height * 2, heightForGlobeRadius(pupilRadius, lens)),
);
const toCentre = pupilRect
? {
x: view.left + view.width / 2 - (pupilRect.left + pupilRect.width / 2),
y: view.top + view.height / 2 - (pupilRect.top + pupilRect.height / 2),
}
: { x: 0, y: 0 };
const startRadius = globeRadiusPx(farHeight, lens);
let driving = false;
const place = (pose, heading = 0, pitch = -Math.PI / 2) => {
driving = true;
try {
camera.setView({
destination: pose,
orientation: { heading, pitch, roll: 0 },
});
} finally {
driving = false;
}
};
let resolveDone;
const done = new Promise((resolve) => {
resolveDone = resolve;
});
let frame = 0;
let finished = false;
const hide = () => loadingScreen.classList.add('hidden');
const stopCommands = camera.onCommand?.(() => {
if (!driving) finish();
});
const inputs = ['pointerdown', 'wheel', 'keydown', 'touchstart'];
// The person's own input skips to the end; another camera move stops it.
const onInput = () => finish({ land: true });
for (const type of inputs)
win.addEventListener(type, onInput, { capture: true, passive: true });
function finish({ land = false } = {}) {
if (finished) return;
finished = true;
playing -= 1;
if (frame) win.cancelAnimationFrame(frame);
stopCommands?.();
for (const type of inputs)
win.removeEventListener(type, onInput, { capture: true });
if (land)
place(
{ lon: target.lon, lat: target.lat, height: target.height },
target.heading ?? 0,
target.pitch ?? -Math.PI / 2,
);
hide();
resolveDone();
}
const start = win.performance.now();
const step = () => {
frame = 0;
if (finished) return;
const stage = openingStage(win.performance.now() - start);
if (stage.done) {
finish({ land: true });
return;
}
const pose = openingPose(stage.flight, { target, farHeight });
place(pose);
const scale = globeRadiusPx(pose.height, lens) / startRadius;
loadingScreen.style.setProperty('--opening-text', stage.text);
loadingScreen.style.setProperty('--opening-veil', stage.veil);
if (logo)
logo.style.transform = `translate(${toCentre.x * stage.centre}px, ${
toCentre.y * stage.centre
}px) scale(${scale})`;
for (const element of arcs) {
element.style.transform = `scale(${stage.arcsScale})`;
element.style.opacity = stage.arcsOpacity;
}
for (const element of pupil) element.style.opacity = stage.pupilOpacity;
if (stage.pupilOpacity === 0) hide();
frame = win.requestAnimationFrame(step);
};
step();
return { done, cancel: () => finish() };
}
-184
View File
@@ -1,184 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Window } from 'happy-dom';
import {
OPENING,
globeRadiusPx,
heightForGlobeRadius,
openingPlaying,
openingPose,
openingStage,
openingWanted,
playOpeningIntro,
} from './openingIntro.js';
const LENS = { fovy: Math.PI / 4, viewportHeight: 800 };
const TARGET = { lon: 10.4, lat: 51.1, height: 23e6, heading: 0, pitch: -1 };
const LANDED = { lon: TARGET.lon, lat: TARGET.lat, height: TARGET.height };
const END_MS = OPENING.centreMs + OPENING.flightStartMs + OPENING.flightMs + 1;
test('the arcs fly out and the words fade before the globe arrives', () => {
const start = openingStage(0);
assert.equal(start.text, 1);
assert.equal(start.veil, 1);
assert.equal(start.pupilOpacity, 1);
assert.equal(start.flight, 0);
const centred = openingStage(OPENING.centreMs);
assert.equal(centred.text, 0);
assert.equal(centred.centre, 1);
const arcsGone = openingStage(OPENING.centreMs + OPENING.arcsMs);
assert.equal(arcsGone.arcsOpacity, 0);
assert.ok(arcsGone.arcsScale > 5);
const real = openingStage(OPENING.centreMs + OPENING.pupilMs[1]);
assert.equal(real.pupilOpacity, 0);
assert.equal(real.veil, 0);
assert.ok(real.flight > 0 && real.flight < 1);
assert.equal(openingStage(END_MS).done, true);
});
test('the flight turns west to east, slows and stops over the target', () => {
const far = 4e8;
const start = openingPose(0, { target: TARGET, farHeight: far });
assert.ok(Math.abs(start.height - far) < 1);
assert.equal(start.lat, 0);
const end = openingPose(1, { target: TARGET, farHeight: far });
assert.ok(Math.abs(end.lon - TARGET.lon) < 1e-9);
assert.ok(Math.abs(end.lat - TARGET.lat) < 1e-9);
assert.ok(Math.abs(end.height - TARGET.height) < 1e-3);
// Unwrapped longitude falls all the way (the camera moves west, so the
// surface turns east), fastest at first.
let previous = Infinity;
let previousStep = Infinity;
for (let i = 0; i <= 10; i++) {
const f = i / 10;
const unwrapped = TARGET.lon + OPENING.spinDeg * (1 - (1 - (1 - f) ** 3));
assert.ok(unwrapped <= previous);
if (i > 0) {
const step = previous - unwrapped;
assert.ok(step <= previousStep + 1e-9, 'the turn slows');
previousStep = step;
}
previous = unwrapped;
const pose = openingPose(f, { target: TARGET, farHeight: far });
assert.ok(pose.lon >= -180 && pose.lon < 180);
}
});
test('the far start draws the globe the size of the pupil', () => {
for (const radius of [12, 20, 64]) {
const height = heightForGlobeRadius(radius, LENS);
assert.ok(Math.abs(globeRadiusPx(height, LENS) - radius) < 1e-6);
}
assert.ok(globeRadiusPx(4e8, LENS) < globeRadiusPx(23e6, LENS));
});
test('reduced motion, Stories links and ?intro=0 open without it', () => {
const win = (search, reduced = false) => ({
location: { search },
matchMedia: () => ({ matches: reduced }),
});
assert.equal(openingWanted(win('')), true);
assert.equal(openingWanted(win('', true)), false);
assert.equal(openingWanted(win('?intro=0')), false);
assert.equal(openingWanted(win('?story=abc')), false);
assert.equal(openingWanted(win('?stories')), false);
assert.equal(openingWanted(win('?intro=1')), true);
});
// A loading screen and a camera port; the test runs the frames by hand.
function stage() {
const window = new Window({ width: 1280, height: 800 });
const doc = window.document;
doc.body.innerHTML = `
<div id="cesiumContainer"></div>
<div id="loading-screen"><span class="loader-logo"><svg>
<path id="outer_eye"/><path id="inner_eye"/>
<path id="globe"/><path id="globe_cage"/>
</svg></span></div>`;
const screen = doc.getElementById('loading-screen');
let now = 0;
let frames = [];
window.performance.now = () => now;
window.requestAnimationFrame = (fn) => frames.push(fn);
window.cancelAnimationFrame = () => {
frames = [];
};
window.matchMedia = () => ({ matches: false });
const views = [];
const commandListeners = new Set();
const camera = {
pose: () => ({ ...TARGET, fovy: Math.PI / 4 }),
setView(spec) {
views.push(spec);
for (const cb of commandListeners) cb({ kind: 'setView' });
},
onCommand(cb) {
commandListeners.add(cb);
return () => commandListeners.delete(cb);
},
};
return {
window,
screen,
views,
camera,
commandListeners,
play: () =>
playOpeningIntro({
viewer: {},
loadingScreen: screen,
win: window,
camera,
}),
advance(ms) {
now += ms;
const run = frames;
frames = [];
for (const fn of run) fn();
},
otherMove: () => {
for (const cb of [...commandListeners]) cb({ kind: 'flyTo' });
},
};
}
test('the opening runs to the start view, then hides the cover', async () => {
const s = stage();
const opening = s.play();
assert.ok(opening);
assert.equal(openingPlaying(), true);
assert.ok(s.screen.classList.contains('opening'));
assert.ok(s.views[0].destination.height > TARGET.height * 2, 'far start');
s.advance(OPENING.centreMs + OPENING.pupilMs[1]);
assert.ok(s.screen.classList.contains('hidden'));
s.advance(OPENING.flightMs);
await opening.done;
const last = s.views.at(-1);
assert.deepEqual(last.destination, LANDED);
assert.equal(last.orientation.pitch, TARGET.pitch);
assert.equal(openingPlaying(), false);
assert.equal(s.commandListeners.size, 0);
});
test("the person's input skips to the start view", async () => {
const s = stage();
const opening = s.play();
s.advance(2000);
s.window.dispatchEvent(new s.window.Event('keydown'));
await opening.done;
assert.deepEqual(s.views.at(-1).destination, LANDED);
assert.ok(s.screen.classList.contains('hidden'));
assert.equal(openingPlaying(), false);
});
test('another camera move stops it where it is', async () => {
const s = stage();
const opening = s.play();
s.advance(2000);
const count = s.views.length;
s.otherMove();
await opening.done;
s.advance(1000);
assert.equal(s.views.length, count, 'no more frames');
assert.ok(s.screen.classList.contains('hidden'));
});
+1 -15
View File
@@ -1,9 +1,6 @@
import { initFirstRunExperience } from '../firstRunExperience.js';
/**
* Reveal welcome controls only after restoration and the loading transition.
* `playOpening` plays the opening on a bare address (src/app/openingIntro.js).
*/
/** Reveal welcome controls only after restoration and the loading transition. */
export function startApplicationChrome({
loadingScreen,
styleManager,
@@ -11,11 +8,9 @@ export function startApplicationChrome({
signal,
initializeWelcome = initFirstRunExperience,
initializeSettings,
playOpening = null,
}) {
let disposed = false;
let firstRun;
let opening = null;
let revealTimer;
let resolveDelay;
const minimumDelay = new Promise((resolve) => {
@@ -34,14 +29,6 @@ export function startApplicationChrome({
})
.then(() => {
if (disposed || signal.aborted) return;
// A bare address opens with the opening; welcome waits for its end.
opening = styleManager.hasShareState
? null
: playOpening?.({ viewer: styleManager.viewer, loadingScreen });
if (opening) {
void opening.done.then(revealFirstRun);
return;
}
loadingScreen.classList.add('hidden');
loadingScreen.addEventListener('transitionend', revealFirstRun, {
once: true,
@@ -57,7 +44,6 @@ export function startApplicationChrome({
);
return async () => {
disposed = true;
opening?.cancel();
clearTimeout(delayTimer);
clearTimeout(revealTimer);
resolveDelay();
+2 -4
View File
@@ -22,7 +22,6 @@ import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
import { createRecentImageryPanel } from '../ui/recentImagery.js';
import { createDataLibrary } from '../library/controller.js';
import { flyToLibraryExtent } from '../library/camera.js';
import { openingPlaying } from './openingIntro.js';
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
import { localGeoJsonServices } from './localGeojsonServices.js';
@@ -89,9 +88,8 @@ export function createApplicationTools({
installGlobeInViewRecovery(viewer, {
// The scope mask hides everything outside its keyhole.
keyholeRadius: () => (isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0),
// An authored scene frames its own shots, holds included, and the
// opening starts with the globe as a speck.
paused: () => sceneDirector.running || openingPlaying(),
// An authored scene frames its own shots, holds included.
paused: () => sceneDirector.running,
}),
);
onSceneDirector?.(sceneDirector);
-695
View File
@@ -1,695 +0,0 @@
// Generated by scripts/build-home-countries.mjs. Do not edit by hand.
// Sources: tzdata zone.tab (public domain) and the Natural Earth countries
// pack in src/data/local_data/natural_earth (public domain).
/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */
export const COUNTRY_CENTRES = {
AD: [42.5, 1.6],
AE: [23.9, 54.3],
AF: [33.8, 66],
AG: [17.1, -61.8],
AI: [18.2, -63.1],
AL: [41.1, 20.1],
AM: [40.3, 44.9],
AO: [-12.3, 17.6],
AQ: [-80.6, 20.8],
AR: [-35.2, -65.1],
AS: [-14.3, -170.7],
AT: [47.6, 14.1],
AU: [-25.6, 134.4],
AW: [12.5, -70],
AX: [60.2, 19.9],
AZ: [40.3, 47.7],
BA: [44.2, 17.8],
BB: [13.2, -59.6],
BD: [23.9, 90.2],
BE: [50.6, 4.6],
BF: [12.3, -1.8],
BG: [42.8, 25.2],
BH: [26.1, 50.5],
BI: [-3.4, 29.9],
BJ: [9.6, 2.3],
BL: [17.9, -62.8],
BM: [32.3, -64.8],
BN: [4.5, 114.6],
BO: [-16.7, -64.7],
BQ: [12.2, -68.3],
BR: [-10.8, -53.1],
BS: [24.7, -78],
BT: [27.4, 90.4],
BW: [-22.2, 23.8],
BY: [53.5, 28],
BZ: [17.2, -88.7],
CA: [57.9, -102.4],
CC: [-12.2, 96.9],
CD: [-2.9, 23.6],
CF: [6.6, 20.5],
CG: [-0.8, 15.2],
CH: [46.8, 8.2],
CI: [7.6, -5.6],
CK: [-21.2, -159.8],
CL: [-35.4, -71.2],
CM: [5.7, 12.7],
CN: [36.6, 103.8],
CO: [3.9, -73.1],
CR: [10, -84.2],
CU: [21.6, -79],
CV: [15.1, -23.6],
CW: [12.2, -69],
CX: [-10.4, 105.7],
CY: [34.9, 33],
CZ: [49.7, 15.3],
DE: [51.1, 10.4],
DJ: [11.8, 42.6],
DK: [56.2, 9.4],
DM: [15.4, -61.4],
DO: [18.9, -70.5],
DZ: [28.1, 2.7],
EC: [-1.4, -78.4],
EE: [58.7, 25.8],
EG: [26.5, 29.9],
EH: [24.2, -12.2],
ER: [15.4, 38.8],
ES: [40.4, -3.6],
ET: [8.6, 39.6],
FI: [64.5, 26.3],
FJ: [-17.8, 178],
FK: [-51.7, -58.8],
FM: [6.9, 158.2],
FO: [62.1, -7],
FR: [46.6, 2.5],
GA: [-0.6, 11.8],
GB: [53.9, -2.5],
GD: [12.1, -61.7],
GE: [42.2, 43.5],
GF: [4.9, -52.3],
GG: [49.5, -2.6],
GH: [8, -1.2],
GI: [36.1, -5.3],
GL: [74.8, -41.4],
GM: [13.4, -15.4],
GN: [10.4, -10.9],
GP: [16.2, -61.5],
GQ: [1.6, 10.5],
GR: [39.5, 22.6],
GS: [-54.4, -36.7],
GT: [15.7, -90.4],
GU: [13.4, 144.8],
GW: [12.1, -14.9],
GY: [4.8, -59],
HK: [22.4, 114.2],
HN: [14.8, -86.6],
HR: [45.2, 16.4],
HT: [18.9, -72.7],
HU: [47.2, 19.4],
ID: [-0.2, 114],
IE: [53.2, -8.1],
IL: [31.4, 35],
IM: [54.2, -4.5],
IN: [22.9, 79.6],
IO: [-7.3, 72.4],
IQ: [33, 43.7],
IR: [32.6, 54.3],
IS: [65, -18.6],
IT: [43.5, 12.2],
JE: [49.2, -2.1],
JM: [18.2, -77.3],
JO: [31.2, 36.8],
JP: [36.7, 138],
KE: [0.6, 37.8],
KG: [41.5, 74.5],
KH: [12.7, 104.9],
KI: [1.9, -157.4],
KM: [-11.7, 43.3],
KN: [17.3, -62.8],
KP: [40.2, 127.2],
KR: [36.5, 127.9],
KW: [29.3, 47.6],
KY: [19.3, -81.3],
KZ: [48.2, 67.3],
LA: [18.5, 103.7],
LB: [33.9, 35.9],
LC: [13.9, -61],
LI: [47.1, 9.5],
LK: [7.6, 80.7],
LR: [6.5, -9.3],
LS: [-29.6, 28.2],
LT: [55.3, 23.9],
LU: [49.8, 6.1],
LV: [56.9, 24.9],
LY: [27, 18],
MA: [29.8, -8.4],
MC: [43.7, 7.4],
MD: [47.2, 28.5],
ME: [42.8, 19.2],
MF: [18.1, -63.1],
MG: [-19.4, 46.7],
MH: [7.1, 171.2],
MK: [41.6, 21.7],
ML: [17.3, -3.5],
MM: [21.2, 96.5],
MN: [46.8, 103.1],
MO: [22.1, 113.6],
MP: [15.2, 145.7],
MQ: [14.6, -61.1],
MR: [20.3, -10.3],
MS: [16.7, -62.2],
MT: [35.9, 14.4],
MU: [-20.3, 57.6],
MV: [4.2, 73.5],
MW: [-13.2, 34.3],
MX: [23.9, -102.5],
MY: [3.6, 114.7],
MZ: [-17.3, 35.5],
NA: [-22.1, 17.2],
NC: [-21.3, 165.5],
NE: [17.4, 9.4],
NF: [-29, 168],
NG: [9.6, 8.1],
NI: [12.8, -85],
NL: [52.3, 5.6],
NO: [64.2, 14],
NP: [28.2, 83.9],
NR: [-0.5, 166.9],
NU: [-19, -169.9],
NZ: [-44, 170.5],
OM: [20.6, 56.1],
PA: [8.5, -80.1],
PE: [-9.2, -74.4],
PF: [-17.7, -149.4],
PG: [-6.6, 144.3],
PH: [16, 121.4],
PK: [29.9, 69.3],
PL: [52.1, 19.4],
PM: [47, -56.3],
PN: [-24.4, -128.3],
PR: [18.2, -66.5],
PS: [31.9, 35.3],
PT: [39.7, -8],
PW: [7.5, 134.6],
PY: [-23.2, -58.4],
QA: [25.3, 51.2],
RE: [-20.9, 55.5],
RO: [45.9, 25],
RS: [44.2, 20.8],
RU: [61.7, 99.1],
RW: [-2, 29.9],
SA: [24.1, 44.5],
SB: [-9.6, 160.2],
SC: [-4.7, 55.5],
SD: [16, 29.9],
SE: [62.8, 16.7],
SG: [1.4, 103.8],
SH: [-16, -5.7],
SI: [46.1, 14.8],
SJ: [78, 16],
SK: [48.7, 19.5],
SL: [8.6, -11.8],
SM: [43.9, 12.4],
SN: [14.4, -14.5],
SO: [4.8, 45.7],
SR: [4.1, -55.9],
SS: [7.3, 30.3],
ST: [0.2, 6.6],
SV: [13.7, -88.9],
SX: [18, -63.1],
SY: [35, 38.5],
SZ: [-26.6, 31.5],
TC: [21.8, -71.7],
TD: [15.3, 18.6],
TF: [-49.3, 69.5],
TG: [8.5, 1],
TH: [15.1, 101],
TJ: [38.5, 71],
TK: [-9.4, -171.2],
TL: [-8.8, 125.9],
TM: [39.1, 59.4],
TN: [34.1, 9.5],
TO: [-21.2, -175.2],
TR: [39, 35.4],
TT: [10.4, -61.3],
TV: [-8.5, 179.2],
TW: [23.8, 121],
TZ: [-6.3, 34.8],
UA: [49.2, 31.3],
UG: [1.3, 32.4],
UM: [5.9, -162.1],
US: [39.5, -99.1],
UY: [-32.8, -56],
UZ: [41.8, 63.1],
VA: [41.9, 12.5],
VC: [13.3, -61.2],
VE: [7.1, -66.2],
VG: [18.4, -64.6],
VI: [17.7, -64.8],
VN: [16.7, 106.3],
VU: [-15.2, 166.9],
WF: [-13.3, -176.2],
WS: [-13.6, -172.4],
YE: [15.9, 47.5],
YT: [-12.8, 45.2],
ZA: [-29, 25.2],
ZM: [-13.5, 27.8],
ZW: [-19, 29.9],
};
/** Time zone (tzdata and ICU names) → ISO 3166 country. */
export const ZONE_COUNTRIES = {
'Africa/Abidjan': 'CI',
'Africa/Accra': 'GH',
'Africa/Addis_Ababa': 'ET',
'Africa/Algiers': 'DZ',
'Africa/Asmara': 'ER',
'Africa/Asmera': 'ER',
'Africa/Bamako': 'ML',
'Africa/Bangui': 'CF',
'Africa/Banjul': 'GM',
'Africa/Bissau': 'GW',
'Africa/Blantyre': 'MW',
'Africa/Brazzaville': 'CG',
'Africa/Bujumbura': 'BI',
'Africa/Cairo': 'EG',
'Africa/Casablanca': 'MA',
'Africa/Ceuta': 'ES',
'Africa/Conakry': 'GN',
'Africa/Dakar': 'SN',
'Africa/Dar_es_Salaam': 'TZ',
'Africa/Djibouti': 'DJ',
'Africa/Douala': 'CM',
'Africa/El_Aaiun': 'EH',
'Africa/Freetown': 'SL',
'Africa/Gaborone': 'BW',
'Africa/Harare': 'ZW',
'Africa/Johannesburg': 'ZA',
'Africa/Juba': 'SS',
'Africa/Kampala': 'UG',
'Africa/Khartoum': 'SD',
'Africa/Kigali': 'RW',
'Africa/Kinshasa': 'CD',
'Africa/Lagos': 'NG',
'Africa/Libreville': 'GA',
'Africa/Lome': 'TG',
'Africa/Luanda': 'AO',
'Africa/Lubumbashi': 'CD',
'Africa/Lusaka': 'ZM',
'Africa/Malabo': 'GQ',
'Africa/Maputo': 'MZ',
'Africa/Maseru': 'LS',
'Africa/Mbabane': 'SZ',
'Africa/Mogadishu': 'SO',
'Africa/Monrovia': 'LR',
'Africa/Nairobi': 'KE',
'Africa/Ndjamena': 'TD',
'Africa/Niamey': 'NE',
'Africa/Nouakchott': 'MR',
'Africa/Ouagadougou': 'BF',
'Africa/Porto-Novo': 'BJ',
'Africa/Sao_Tome': 'ST',
'Africa/Tripoli': 'LY',
'Africa/Tunis': 'TN',
'Africa/Windhoek': 'NA',
'America/Adak': 'US',
'America/Anchorage': 'US',
'America/Anguilla': 'AI',
'America/Antigua': 'AG',
'America/Araguaina': 'BR',
'America/Argentina/Buenos_Aires': 'AR',
'America/Argentina/Catamarca': 'AR',
'America/Argentina/Cordoba': 'AR',
'America/Argentina/Jujuy': 'AR',
'America/Argentina/La_Rioja': 'AR',
'America/Argentina/Mendoza': 'AR',
'America/Argentina/Rio_Gallegos': 'AR',
'America/Argentina/Salta': 'AR',
'America/Argentina/San_Juan': 'AR',
'America/Argentina/San_Luis': 'AR',
'America/Argentina/Tucuman': 'AR',
'America/Argentina/Ushuaia': 'AR',
'America/Aruba': 'AW',
'America/Asuncion': 'PY',
'America/Atikokan': 'CA',
'America/Bahia': 'BR',
'America/Bahia_Banderas': 'MX',
'America/Barbados': 'BB',
'America/Belem': 'BR',
'America/Belize': 'BZ',
'America/Blanc-Sablon': 'CA',
'America/Boa_Vista': 'BR',
'America/Bogota': 'CO',
'America/Boise': 'US',
'America/Buenos_Aires': 'AR',
'America/Cambridge_Bay': 'CA',
'America/Campo_Grande': 'BR',
'America/Cancun': 'MX',
'America/Caracas': 'VE',
'America/Catamarca': 'AR',
'America/Cayenne': 'GF',
'America/Cayman': 'KY',
'America/Chicago': 'US',
'America/Chihuahua': 'MX',
'America/Ciudad_Juarez': 'MX',
'America/Coral_Harbour': 'CA',
'America/Cordoba': 'AR',
'America/Costa_Rica': 'CR',
'America/Coyhaique': 'CL',
'America/Creston': 'CA',
'America/Cuiaba': 'BR',
'America/Curacao': 'CW',
'America/Danmarkshavn': 'GL',
'America/Dawson': 'CA',
'America/Dawson_Creek': 'CA',
'America/Denver': 'US',
'America/Detroit': 'US',
'America/Dominica': 'DM',
'America/Edmonton': 'CA',
'America/Eirunepe': 'BR',
'America/El_Salvador': 'SV',
'America/Fort_Nelson': 'CA',
'America/Fortaleza': 'BR',
'America/Glace_Bay': 'CA',
'America/Godthab': 'GL',
'America/Goose_Bay': 'CA',
'America/Grand_Turk': 'TC',
'America/Grenada': 'GD',
'America/Guadeloupe': 'GP',
'America/Guatemala': 'GT',
'America/Guayaquil': 'EC',
'America/Guyana': 'GY',
'America/Halifax': 'CA',
'America/Havana': 'CU',
'America/Hermosillo': 'MX',
'America/Indiana/Indianapolis': 'US',
'America/Indiana/Knox': 'US',
'America/Indiana/Marengo': 'US',
'America/Indiana/Petersburg': 'US',
'America/Indiana/Tell_City': 'US',
'America/Indiana/Vevay': 'US',
'America/Indiana/Vincennes': 'US',
'America/Indiana/Winamac': 'US',
'America/Indianapolis': 'US',
'America/Inuvik': 'CA',
'America/Iqaluit': 'CA',
'America/Jamaica': 'JM',
'America/Jujuy': 'AR',
'America/Juneau': 'US',
'America/Kentucky/Louisville': 'US',
'America/Kentucky/Monticello': 'US',
'America/Kralendijk': 'BQ',
'America/La_Paz': 'BO',
'America/Lima': 'PE',
'America/Los_Angeles': 'US',
'America/Louisville': 'US',
'America/Lower_Princes': 'SX',
'America/Maceio': 'BR',
'America/Managua': 'NI',
'America/Manaus': 'BR',
'America/Marigot': 'MF',
'America/Martinique': 'MQ',
'America/Matamoros': 'MX',
'America/Mazatlan': 'MX',
'America/Mendoza': 'AR',
'America/Menominee': 'US',
'America/Merida': 'MX',
'America/Metlakatla': 'US',
'America/Mexico_City': 'MX',
'America/Miquelon': 'PM',
'America/Moncton': 'CA',
'America/Monterrey': 'MX',
'America/Montevideo': 'UY',
'America/Montserrat': 'MS',
'America/Nassau': 'BS',
'America/New_York': 'US',
'America/Nome': 'US',
'America/Noronha': 'BR',
'America/North_Dakota/Beulah': 'US',
'America/North_Dakota/Center': 'US',
'America/North_Dakota/New_Salem': 'US',
'America/Nuuk': 'GL',
'America/Ojinaga': 'MX',
'America/Panama': 'PA',
'America/Paramaribo': 'SR',
'America/Phoenix': 'US',
'America/Port-au-Prince': 'HT',
'America/Port_of_Spain': 'TT',
'America/Porto_Velho': 'BR',
'America/Puerto_Rico': 'PR',
'America/Punta_Arenas': 'CL',
'America/Rankin_Inlet': 'CA',
'America/Recife': 'BR',
'America/Regina': 'CA',
'America/Resolute': 'CA',
'America/Rio_Branco': 'BR',
'America/Santarem': 'BR',
'America/Santiago': 'CL',
'America/Santo_Domingo': 'DO',
'America/Sao_Paulo': 'BR',
'America/Scoresbysund': 'GL',
'America/Sitka': 'US',
'America/St_Barthelemy': 'BL',
'America/St_Johns': 'CA',
'America/St_Kitts': 'KN',
'America/St_Lucia': 'LC',
'America/St_Thomas': 'VI',
'America/St_Vincent': 'VC',
'America/Swift_Current': 'CA',
'America/Tegucigalpa': 'HN',
'America/Thule': 'GL',
'America/Tijuana': 'MX',
'America/Toronto': 'CA',
'America/Tortola': 'VG',
'America/Vancouver': 'CA',
'America/Whitehorse': 'CA',
'America/Winnipeg': 'CA',
'America/Yakutat': 'US',
'Antarctica/Casey': 'AQ',
'Antarctica/Davis': 'AQ',
'Antarctica/DumontDUrville': 'AQ',
'Antarctica/Macquarie': 'AU',
'Antarctica/Mawson': 'AQ',
'Antarctica/McMurdo': 'AQ',
'Antarctica/Palmer': 'AQ',
'Antarctica/Rothera': 'AQ',
'Antarctica/Syowa': 'AQ',
'Antarctica/Troll': 'AQ',
'Antarctica/Vostok': 'AQ',
'Arctic/Longyearbyen': 'SJ',
'Asia/Aden': 'YE',
'Asia/Almaty': 'KZ',
'Asia/Amman': 'JO',
'Asia/Anadyr': 'RU',
'Asia/Aqtau': 'KZ',
'Asia/Aqtobe': 'KZ',
'Asia/Ashgabat': 'TM',
'Asia/Atyrau': 'KZ',
'Asia/Baghdad': 'IQ',
'Asia/Bahrain': 'BH',
'Asia/Baku': 'AZ',
'Asia/Bangkok': 'TH',
'Asia/Barnaul': 'RU',
'Asia/Beirut': 'LB',
'Asia/Bishkek': 'KG',
'Asia/Brunei': 'BN',
'Asia/Calcutta': 'IN',
'Asia/Chita': 'RU',
'Asia/Colombo': 'LK',
'Asia/Damascus': 'SY',
'Asia/Dhaka': 'BD',
'Asia/Dili': 'TL',
'Asia/Dubai': 'AE',
'Asia/Dushanbe': 'TJ',
'Asia/Famagusta': 'CY',
'Asia/Gaza': 'PS',
'Asia/Hebron': 'PS',
'Asia/Ho_Chi_Minh': 'VN',
'Asia/Hong_Kong': 'HK',
'Asia/Hovd': 'MN',
'Asia/Irkutsk': 'RU',
'Asia/Jakarta': 'ID',
'Asia/Jayapura': 'ID',
'Asia/Jerusalem': 'IL',
'Asia/Kabul': 'AF',
'Asia/Kamchatka': 'RU',
'Asia/Karachi': 'PK',
'Asia/Kathmandu': 'NP',
'Asia/Katmandu': 'NP',
'Asia/Khandyga': 'RU',
'Asia/Kolkata': 'IN',
'Asia/Krasnoyarsk': 'RU',
'Asia/Kuala_Lumpur': 'MY',
'Asia/Kuching': 'MY',
'Asia/Kuwait': 'KW',
'Asia/Macau': 'MO',
'Asia/Magadan': 'RU',
'Asia/Makassar': 'ID',
'Asia/Manila': 'PH',
'Asia/Muscat': 'OM',
'Asia/Nicosia': 'CY',
'Asia/Novokuznetsk': 'RU',
'Asia/Novosibirsk': 'RU',
'Asia/Omsk': 'RU',
'Asia/Oral': 'KZ',
'Asia/Phnom_Penh': 'KH',
'Asia/Pontianak': 'ID',
'Asia/Pyongyang': 'KP',
'Asia/Qatar': 'QA',
'Asia/Qostanay': 'KZ',
'Asia/Qyzylorda': 'KZ',
'Asia/Rangoon': 'MM',
'Asia/Riyadh': 'SA',
'Asia/Saigon': 'VN',
'Asia/Sakhalin': 'RU',
'Asia/Samarkand': 'UZ',
'Asia/Seoul': 'KR',
'Asia/Shanghai': 'CN',
'Asia/Singapore': 'SG',
'Asia/Srednekolymsk': 'RU',
'Asia/Taipei': 'TW',
'Asia/Tashkent': 'UZ',
'Asia/Tbilisi': 'GE',
'Asia/Tehran': 'IR',
'Asia/Thimphu': 'BT',
'Asia/Tokyo': 'JP',
'Asia/Tomsk': 'RU',
'Asia/Ulaanbaatar': 'MN',
'Asia/Urumqi': 'CN',
'Asia/Ust-Nera': 'RU',
'Asia/Vientiane': 'LA',
'Asia/Vladivostok': 'RU',
'Asia/Yakutsk': 'RU',
'Asia/Yangon': 'MM',
'Asia/Yekaterinburg': 'RU',
'Asia/Yerevan': 'AM',
'Atlantic/Azores': 'PT',
'Atlantic/Bermuda': 'BM',
'Atlantic/Canary': 'ES',
'Atlantic/Cape_Verde': 'CV',
'Atlantic/Faeroe': 'FO',
'Atlantic/Faroe': 'FO',
'Atlantic/Madeira': 'PT',
'Atlantic/Reykjavik': 'IS',
'Atlantic/South_Georgia': 'GS',
'Atlantic/St_Helena': 'SH',
'Atlantic/Stanley': 'FK',
'Australia/Adelaide': 'AU',
'Australia/Brisbane': 'AU',
'Australia/Broken_Hill': 'AU',
'Australia/Darwin': 'AU',
'Australia/Eucla': 'AU',
'Australia/Hobart': 'AU',
'Australia/Lindeman': 'AU',
'Australia/Lord_Howe': 'AU',
'Australia/Melbourne': 'AU',
'Australia/Perth': 'AU',
'Australia/Sydney': 'AU',
'Europe/Amsterdam': 'NL',
'Europe/Andorra': 'AD',
'Europe/Astrakhan': 'RU',
'Europe/Athens': 'GR',
'Europe/Belgrade': 'RS',
'Europe/Berlin': 'DE',
'Europe/Bratislava': 'SK',
'Europe/Brussels': 'BE',
'Europe/Bucharest': 'RO',
'Europe/Budapest': 'HU',
'Europe/Busingen': 'DE',
'Europe/Chisinau': 'MD',
'Europe/Copenhagen': 'DK',
'Europe/Dublin': 'IE',
'Europe/Gibraltar': 'GI',
'Europe/Guernsey': 'GG',
'Europe/Helsinki': 'FI',
'Europe/Isle_of_Man': 'IM',
'Europe/Istanbul': 'TR',
'Europe/Jersey': 'JE',
'Europe/Kaliningrad': 'RU',
'Europe/Kiev': 'UA',
'Europe/Kirov': 'RU',
'Europe/Kyiv': 'UA',
'Europe/Lisbon': 'PT',
'Europe/Ljubljana': 'SI',
'Europe/London': 'GB',
'Europe/Luxembourg': 'LU',
'Europe/Madrid': 'ES',
'Europe/Malta': 'MT',
'Europe/Mariehamn': 'AX',
'Europe/Minsk': 'BY',
'Europe/Monaco': 'MC',
'Europe/Moscow': 'RU',
'Europe/Oslo': 'NO',
'Europe/Paris': 'FR',
'Europe/Podgorica': 'ME',
'Europe/Prague': 'CZ',
'Europe/Riga': 'LV',
'Europe/Rome': 'IT',
'Europe/Samara': 'RU',
'Europe/San_Marino': 'SM',
'Europe/Sarajevo': 'BA',
'Europe/Saratov': 'RU',
'Europe/Simferopol': 'UA',
'Europe/Skopje': 'MK',
'Europe/Sofia': 'BG',
'Europe/Stockholm': 'SE',
'Europe/Tallinn': 'EE',
'Europe/Tirane': 'AL',
'Europe/Ulyanovsk': 'RU',
'Europe/Vaduz': 'LI',
'Europe/Vatican': 'VA',
'Europe/Vienna': 'AT',
'Europe/Vilnius': 'LT',
'Europe/Volgograd': 'RU',
'Europe/Warsaw': 'PL',
'Europe/Zagreb': 'HR',
'Europe/Zurich': 'CH',
'Indian/Antananarivo': 'MG',
'Indian/Chagos': 'IO',
'Indian/Christmas': 'CX',
'Indian/Cocos': 'CC',
'Indian/Comoro': 'KM',
'Indian/Kerguelen': 'TF',
'Indian/Mahe': 'SC',
'Indian/Maldives': 'MV',
'Indian/Mauritius': 'MU',
'Indian/Mayotte': 'YT',
'Indian/Reunion': 'RE',
'Pacific/Apia': 'WS',
'Pacific/Auckland': 'NZ',
'Pacific/Bougainville': 'PG',
'Pacific/Chatham': 'NZ',
'Pacific/Chuuk': 'FM',
'Pacific/Easter': 'CL',
'Pacific/Efate': 'VU',
'Pacific/Enderbury': 'KI',
'Pacific/Fakaofo': 'TK',
'Pacific/Fiji': 'FJ',
'Pacific/Funafuti': 'TV',
'Pacific/Galapagos': 'EC',
'Pacific/Gambier': 'PF',
'Pacific/Guadalcanal': 'SB',
'Pacific/Guam': 'GU',
'Pacific/Honolulu': 'US',
'Pacific/Kanton': 'KI',
'Pacific/Kiritimati': 'KI',
'Pacific/Kosrae': 'FM',
'Pacific/Kwajalein': 'MH',
'Pacific/Majuro': 'MH',
'Pacific/Marquesas': 'PF',
'Pacific/Midway': 'UM',
'Pacific/Nauru': 'NR',
'Pacific/Niue': 'NU',
'Pacific/Norfolk': 'NF',
'Pacific/Noumea': 'NC',
'Pacific/Pago_Pago': 'AS',
'Pacific/Palau': 'PW',
'Pacific/Pitcairn': 'PN',
'Pacific/Pohnpei': 'FM',
'Pacific/Ponape': 'FM',
'Pacific/Port_Moresby': 'PG',
'Pacific/Rarotonga': 'CK',
'Pacific/Saipan': 'MP',
'Pacific/Tahiti': 'PF',
'Pacific/Tarawa': 'KI',
'Pacific/Tongatapu': 'TO',
'Pacific/Truk': 'FM',
'Pacific/Wake': 'UM',
'Pacific/Wallis': 'WF',
};
-52
View File
@@ -1,52 +0,0 @@
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
import { START_VIEW } from './camera.js';
/**
* The visitor's country, guessed from the browser's time zone and, for a zone
* that belongs to no country (UTC), the region of a preferred language
* ("en-GB"). Nothing leaves the browser. Null when neither names one.
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
* @returns {string|null} ISO 3166 code, e.g. 'DE'
*/
export function homeCountry({
timeZone = currentTimeZone(),
languages = globalThis.navigator?.languages ?? [],
} = {}) {
const byZone = ZONE_COUNTRIES[timeZone];
if (byZone) return byZone;
for (const language of languages) {
const region = regionOf(language);
if (region && COUNTRY_CENTRES[region]) return region;
}
return null;
}
/**
* The start view over the visitor's country: the planet from `base.height`,
* looking straight down on the country's centre. `base` where the country is
* unknown.
* @param {{timeZone?: string|null, languages?: readonly string[],
* base?: {lon: number, lat: number, height: number}}} [where]
*/
export function homeCountryView({ base = START_VIEW, ...where } = {}) {
const centre = COUNTRY_CENTRES[homeCountry(where)];
if (!centre) return base;
const [lat, lon] = centre;
return Object.freeze({ lon, lat, height: base.height });
}
function currentTimeZone() {
try {
return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
} catch {
return null;
}
}
function regionOf(language) {
try {
return new Intl.Locale(language).region ?? null;
} catch {
return null;
}
}
-53
View File
@@ -1,53 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { homeCountry, homeCountryView } from './homeCountry.js';
import { START_VIEW } from './camera.js';
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
test('the time zone names the country, in its tzdata or ICU name', () => {
assert.equal(homeCountry({ timeZone: 'Europe/Berlin', languages: [] }), 'DE');
assert.equal(homeCountry({ timeZone: 'Asia/Kolkata', languages: [] }), 'IN');
assert.equal(homeCountry({ timeZone: 'Asia/Calcutta', languages: [] }), 'IN');
assert.equal(homeCountry({ timeZone: 'Europe/Kiev', languages: [] }), 'UA');
assert.equal(
homeCountry({ timeZone: 'America/Chicago', languages: ['de-DE'] }),
'US',
'the zone outranks the language',
);
});
test("a zone of no country falls back to a language's region", () => {
assert.equal(
homeCountry({ timeZone: 'UTC', languages: ['fr', 'en-GB'] }),
'GB',
);
assert.equal(homeCountry({ timeZone: 'Etc/UTC', languages: ['ru'] }), null);
assert.equal(homeCountry({ timeZone: null, languages: [] }), null);
});
test('the start view looks down on the country from the planet height', () => {
const view = homeCountryView({ timeZone: 'Asia/Tokyo', languages: [] });
assert.deepEqual(
[view.lat, view.lon, view.height],
[...COUNTRY_CENTRES.JP, START_VIEW.height],
);
assert.equal(
homeCountryView({ timeZone: 'UTC', languages: [] }),
START_VIEW,
'unknown: the default start',
);
});
test('every zone has a country with a centre on the globe', () => {
for (const [zone, country] of Object.entries(ZONE_COUNTRIES)) {
const centre = COUNTRY_CENTRES[country];
assert.ok(centre, `${zone} → ${country}`);
const [lat, lon] = centre;
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, country);
}
// Countries whose largest part is not where their centroid would be.
const [usLat, usLon] = COUNTRY_CENTRES.US;
assert.ok(usLat > 30 && usLat < 45 && usLon > -110 && usLon < -85);
const [frLat, frLon] = COUNTRY_CENTRES.FR;
assert.ok(frLat > 42 && frLat < 50 && frLon > -2 && frLon < 8);
});
+2 -18
View File
@@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => {
};
await assert.rejects(
searchHls({
box: { west: -181, south: 0, east: -179, north: 1 },
box: { west: 179, south: 0, east: -179, north: 1 },
fetchImpl,
}),
/±180/,
/dateline/,
);
await assert.rejects(
searchHls({ box: BOX, now: 'never', fetchImpl }),
@@ -251,22 +251,6 @@ test('an invalid box or clock is refused before any request', async () => {
assert.equal(called, false);
});
test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => {
const calls = [];
const result = await searchHls({
box: { west: 179, south: 0, east: -179, north: 1 },
days: 2,
now: '2026-09-21T00:00:00Z',
fetchImpl: async (url) => {
calls.push(url);
return response({ json: { hits: 1, items: [ummItem({})] } });
},
});
assert.equal(calls.length, 2, 'one search per product');
assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1')));
assert.ok(result.candidates.some((candidate) => candidate.product === 'S30'));
});
test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => {
const items = (count) =>
Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` }));
+4 -9
View File
@@ -581,8 +581,6 @@ export function createRecentImageryLayer({
for (const slotId of SLOT_IDS) {
const candidate = candidateFor(shown[slotId]);
if (candidate && _hostInfo.collection) {
const { availableBoxes, emptyBoxes } =
thumbnails.get(candidate.key) ?? {};
renderer.showSlot(slotId, candidate, _box, {
alpha: _alpha,
splitDirection: !live
@@ -590,8 +588,6 @@ export function createRecentImageryLayer({
: (slotId === 'a') !== _swapped
? 'left'
: 'right',
availableBoxes,
emptyBoxes,
});
} else {
renderer.hideSlot(slotId);
@@ -901,22 +897,21 @@ export function createRecentImageryLayer({
// The new automatic day's probe may have been cancelled off-screen.
requestThumbnails();
}
if (pruned) syncRender();
const followed =
Boolean(_followKey) &&
_followKey === _focusKey &&
drapable(candidateFor(_followKey)) &&
applyPreview(_followKey);
// A pinned or previewed day that was still being probed drapes now.
const shown = plan();
const owned = renderer.getOwned?.() || {};
const drapesChanged = SLOT_IDS.some(
(slotId) => (owned[slotId]?.key || null) !== shown[slotId],
);
// One render per probe: the key can stay the same while its halves change.
// A host found moved changes the divider, so the panel renders in full.
const moved = !followed && syncHost();
if (!followed) syncRender();
if (drapesChanged && !pruned && !followed) syncRender();
notify('thumbnail');
if (pruned || followed || drapesChanged || moved) notify();
if (pruned || followed || drapesChanged) notify();
});
syncHost();
if (_box && !_candidates.length) void runSearch();
+1 -428
View File
@@ -1,10 +1,6 @@
import test from 'node:test';
import * as Cesium from 'cesium';
import assert from 'node:assert/strict';
import { until } from '../../testSupport/kartaViewFakes.mjs';
import { createRecentImagerySource } from './source.js';
import { createThumbnailLoader } from './thumbnails.js';
import { boxKey, nonCrossingBoxes } from './model.js';
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
import { MapSourceController } from '../../maps/controller.js';
@@ -18,16 +14,11 @@ import {
SPLIT_PUBLISH_MS,
createRecentImageryLayer,
} from './index.js';
import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { createImageryBoxPreview } from './rendering.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import {
BOX,
CANDIDATES,
FIJI_BOX,
boxToolFakes,
candidate,
fakeCatalog,
@@ -1573,424 +1564,6 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
assert.equal(f.snap().notice, 'Search cancelled');
});
test('a box dragged across the dateline is searched, listed and draped as one box', async () => {
const f = fixture();
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
f.layer.enable();
assert.equal(f.layer.setBox(box), true);
assert.equal(f.snap().boxError, null);
assert.deepEqual(f.catalog.searches.at(-1).request.box, box);
f.catalog.resolveLast();
await settle();
assert.equal(f.snap().candidates.length, 4);
assert.equal(f.snap().preview.key, S18);
assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped');
assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°');
});
test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => {
const f = fixture();
const priorGet = f.thumbnails.get;
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
const [west, east] = nonCrossingBoxes(box);
let boxes = [west];
f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes });
f.layer.enable();
f.layer.setBox(box);
f.catalog.resolveLast();
await settle();
f.thumbnails.probeRequested();
const slot = Object.keys(f.owned()).find((id) => f.owned()[id]);
assert.ok(slot, 'a day is already on the map');
const key = f.owned()[slot].key;
assert.deepEqual(f.owned()[slot].availableBoxes, [west]);
boxes = [west, east];
f.thumbnails.probe(key, 'present');
assert.deepEqual(f.owned()[slot].availableBoxes, boxes);
f.layer.destroy();
});
const sideOf = (url) =>
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
? 'west'
: 'east';
/** A snapshot response; `present: null` sends no Data-Present header. */
const snapshotAnswer = (present, status = 200) =>
new Response('img', {
status,
headers: present === null ? {} : { 'Data-Present': String(present) },
});
function realLayer({
fetchImpl,
candidates,
maxDecoded = 16,
halfDeadlineMs = 50,
}) {
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs });
let nextUrl = 0;
const loader = createThumbnailLoader({
requestThumbnail: source.getThumbnail,
createObjectUrl: () => `blob:${++nextUrl}`,
revokeObjectUrl: () => {},
maxDecoded,
});
const globe = fakeGlobePort();
const layer = createRecentImageryLayer({
catalog: {
searchHls: async () => ({ candidates, truncated: false, errors: [] }),
},
renderer: createRecentImageryRenderer(),
thumbnails: loader,
host: () => ({ collection: globe.imagery, kind: 'globe' }),
globeOf: () => globe,
now: () => new Date('2026-11-13T15:00:00Z'),
});
layer.init({ camera: {} });
return { layer, loader, globe };
}
test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => {
const day = candidate('VIIRS', '2026-11-10');
const sides = [];
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async (url) => {
const side = sideOf(url);
sides.push(side);
return snapshotAnswer(side === 'east');
},
});
layer.setSources({ viirs: true });
layer.enable();
assert.equal(layer.setBox(FIJI_BOX), true);
// The probe asks about both halves, wider first. The layer drapes the one with data.
assert.equal(
await until(() => globe.layers.length > 0, { ticks: 2000 }),
true,
);
assert.deepEqual(sides, ['east', 'west']);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[nonCrossingBoxes(FIJI_BOX)[1]],
);
assert.equal(loader.get(day.key).status, 'present');
const snapshot = layer.getSnapshot();
assert.equal(snapshot.candidates[0].thumbnail.status, 'present');
assert.equal(snapshot.candidates[0].drapable, true);
assert.equal(snapshot.auto?.key, day.key);
layer.destroy();
assert.equal(globe.layers.length, 0);
});
test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => {
const day = candidate('VIIRS', '2026-11-10');
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async () => snapshotAnswer(false),
});
layer.setSources({ viirs: true });
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }),
true,
);
assert.equal(globe.layers.length, 0);
assert.equal(
layer.getSnapshot().candidates.some((c) => c.key === day.key),
false,
'an empty day leaves the strip',
);
layer.destroy();
});
for (const [label, box] of [
['a plain box', { west: -98, south: 30, east: -97, north: 31 }],
['a dateline box', FIJI_BOX],
]) {
test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => {
const day = candidate('S30', '2026-11-10');
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const { layer, loader, globe } = realLayer({
candidates: [day],
halfDeadlineMs: 5000,
fetchImpl: async () => {
await gate;
return snapshotAnswer(true);
},
});
layer.enable();
layer.setBox(box);
assert.equal(
await until(() => globe.layers.length === nonCrossingBoxes(box).length, {
ticks: 2000,
}),
true,
);
const before = [...globe.layers];
const added = globe.added.length;
release();
assert.equal(
await until(() => loader.get(day.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(globe.added.length, added);
assert.deepEqual(globe.layers, before);
layer.destroy();
});
}
test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => {
const day1 = candidate('VIIRS', '2026-11-10');
const day2 = candidate('VIIRS', '2026-11-11');
let eastCalls = 0;
let releaseDay2;
const gate = new Promise((resolve) => {
releaseDay2 = resolve;
});
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) await gate;
else if (sideOf(url) === 'east' && ++eastCalls === 2)
throw new TypeError('Failed to fetch');
return snapshotAnswer(true);
},
});
layer.setSources({ hls: false, viirs: true });
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
releaseDay2();
assert.equal(
await until(() => loader.get(day2.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).objectUrl, null);
layer.setAssignment('a', day1.key);
assert.equal(
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).status, 'present');
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
const [west, east] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[west, east],
'a half that failed on the re-probe stays draped',
);
layer.destroy();
});
test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => {
const day1 = candidate('S30', '2026-11-10');
const day2 = candidate('S30', '2026-11-11');
let eastCalls = 0;
let releaseDay2;
const gate = new Promise((r) => (releaseDay2 = r));
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) {
await gate;
return snapshotAnswer(true);
}
if (sideOf(url) === 'east') {
eastCalls += 1;
if (eastCalls === 1) return snapshotAnswer(false);
throw new TypeError('Failed to fetch');
}
return snapshotAnswer(true);
},
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key).status === 'present', {
ticks: 2000,
}),
true,
);
const [west] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
assert.equal(loader.get(day1.key).emptyBoxes.length, 1);
releaseDay2();
assert.equal(
await until(() => loader.get(day2.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).objectUrl, null);
layer.setAssignment('a', day1.key);
assert.equal(
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
ticks: 2000,
}),
true,
);
await until(() => false, { ticks: 50 });
const entry = loader.get(day1.key);
assert.deepEqual(
{
available: entry.availableBoxes.length,
empty: entry.emptyBoxes.length,
layers: globe.layers.length,
},
{ available: 1, empty: 1, layers: 1 },
);
layer.destroy();
});
test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => {
const day = candidate('S30', '2026-11-10');
let release;
const gate = new Promise((r) => (release = r));
const { layer, loader, globe } = realLayer({
candidates: [day],
halfDeadlineMs: 5000,
fetchImpl: async () => {
await gate;
return snapshotAnswer(null);
},
});
layer.enable();
layer.setBox({ west: -98, south: 30, east: -97, north: 31 });
assert.equal(
await until(() => globe.layers.length === 1, { ticks: 2000 }),
true,
);
release();
assert.equal(
await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }),
true,
);
await until(() => false, { ticks: 50 });
assert.equal(globe.layers.length, 1);
layer.destroy();
});
for (const [label, failEast] of [
['answers 503', async () => snapshotAnswer(null, 503)],
[
'rejects',
async () => {
throw new TypeError('Failed to fetch');
},
],
['never answers', () => new Promise(() => {})],
]) {
test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => {
const day = candidate('S30', '2026-11-10');
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async (url) =>
sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(),
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day.key)?.status === 'error', {
ticks: 2000,
}),
true,
);
layer.setAssignment('a', day.key);
await until(() => false, { ticks: 50 });
const entry = loader.get(day.key);
const [west] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
{
empty: (entry.emptyBoxes ?? []).map(boxKey),
layers: globe.layers.length,
},
{ empty: [boxKey(west)], layers: 1 },
);
layer.destroy();
});
}
test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => {
const day1 = candidate('S30', '2026-11-10');
const day2 = candidate('S30', '2026-11-11');
let round = 0;
let releaseDay2;
const gate = new Promise((r) => (releaseDay2 = r));
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) {
await gate;
return snapshotAnswer(true);
}
if (round === 0)
return sideOf(url) === 'west'
? snapshotAnswer(true)
: snapshotAnswer(null);
return sideOf(url) === 'west'
? snapshotAnswer(null)
: snapshotAnswer(false);
},
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key)?.status === 'present', {
ticks: 2000,
}),
true,
);
round = 1;
releaseDay2();
assert.equal(
await until(
() =>
loader.get(day2.key)?.status === 'present' &&
loader.get(day1.key).objectUrl === null,
{ ticks: 2000 },
),
true,
);
layer.setAssignment('a', day1.key);
await until(() => false, { ticks: 50 });
await until(() => !loader.get(day1.key).loading, { ticks: 2000 });
await until(() => false, { ticks: 50 });
const entry = loader.get(day1.key);
const [, east] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
{
status: entry.status,
empty: (entry.emptyBoxes ?? []).map(boxKey),
layers: globe.layers.length,
},
{ status: 'present', empty: [boxKey(east)], layers: 1 },
);
layer.destroy();
});
test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => {
for (const order of [
[S18, V15],
+24 -93
View File
@@ -72,11 +72,13 @@ export const PRODUCTS = Object.freeze({
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/** A longitude brought back into ±180 after one step past it. */
const wrapLon = (value) =>
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
const pad2 = (value) => String(value).padStart(2, '0');
/**
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
* east are not swapped: west > east crosses the dateline and `validateBox`
* rejects it. Null when any edge is nonfinite.
*/
/** A box edge as a number, or null when it is missing, blank or not numeric. */
function edgeNumber(value) {
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
@@ -85,11 +87,6 @@ function edgeNumber(value) {
return Number.isFinite(number) ? number : null;
}
/**
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
* east are not swapped: west > east is the short arc across the dateline.
* Null when any edge is nonfinite.
*/
function normalizeBox(box) {
if (!box || typeof box !== 'object') return null;
const [west, south, east, north] = [
@@ -108,45 +105,8 @@ function normalizeBox(box) {
}
/**
* Degrees of longitude going east from `west` to `east`. A west > east pair
* wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and
* `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`,
* even the long way round.
* @param {number} west Degrees.
* @param {number} east Degrees.
* @returns {number}
*/
export function lonSpanDeg(west, east) {
return east >= west ? east - west : east + 360 - west;
}
/** A comparable key for a degrees box. */
export const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* One or two boxes with west <= east that cover the same area. A dateline
* box is split at ±180 so each side is a plain rectangle for a draped layer
* or a Worldview request. A box with a missing or nonfinite edge is [].
* So is a dateline box of zero width (west 180, east -180).
* @param {object} box Degrees box.
* @returns {Array<object>}
*/
export function nonCrossingBoxes(box) {
const normalized = normalizeBox(box);
if (!normalized) return [];
const { west, south, east, north } = normalized;
if (!(west > east)) return [normalized];
const parts = [];
if (west < 180) parts.push({ west, south, east: 180, north });
if (east > -180) parts.push({ west: -180, south, east, north });
return parts;
}
/**
* Side lengths of a box in km: the longitude span at its mid-latitude (the
* short arc when the box crosses the dateline; a west <= east box is not
* shortened), and its latitude span.
* Side lengths of a box in km: the box's own longitude span (never the
* shorter way round the globe) at its mid-latitude, and its latitude span.
* @param {object} box Degrees box.
* @returns {{ width: number, height: number }}
*/
@@ -156,7 +116,7 @@ export function boxSideKm(box) {
const midLat = (normalized.south + normalized.north) / 2;
return {
width:
lonSpanDeg(normalized.west, normalized.east) *
(normalized.east - normalized.west) *
KM_PER_DEG_LAT *
Math.cos(toRadians(midLat)),
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
@@ -166,11 +126,9 @@ export function boxSideKm(box) {
const refuse = (reason, message) => ({ ok: false, reason, message });
/**
* Validate a selection box for the catalog and the tile providers. A box
* with west > east is the short arc across the dateline and is accepted
* when that arc is under the size cap.
* Validate a selection box for the catalog and the tile providers.
* @param {object} box Degrees box.
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
*/
export function validateBox(box) {
const normalized = normalizeBox(box);
@@ -178,6 +136,8 @@ export function validateBox(box) {
const { west, south, east, north } = normalized;
if (Math.abs(west) > 180 || Math.abs(east) > 180)
return refuse('invalid', msg('Longitudes must be within ±180°'));
if (west > east)
return refuse('dateline', msg('Select one side of the dateline'));
if (
Math.abs(south) > MERCATOR_LAT_LIMIT ||
Math.abs(north) > MERCATOR_LAT_LIMIT
@@ -186,7 +146,7 @@ export function validateBox(box) {
'polar',
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
);
if (lonSpanDeg(west, east) === 0 || north === south)
if (east === west || north === south)
return refuse('degenerate', msg('Box must enclose an area'));
const { width, height } = boxSideKm(normalized);
if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)
@@ -223,9 +183,7 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
}
/**
* The centre of a box, in degrees. A dateline box (west > east) is centred
* on the short arc, not the arithmetic mean, which would be the other side
* of the globe.
* The centre of a box that does not cross the dateline, in degrees.
* @param {object} box Degrees box.
* @returns {{ lon: number, lat: number } | null}
*/
@@ -233,18 +191,14 @@ export function boxCentre(box) {
const normalized = normalizeBox(box);
if (!normalized) return null;
return {
lon: wrapLon(
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
),
lon: (normalized.west + normalized.east) / 2,
lat: (normalized.south + normalized.north) / 2,
};
}
/**
* A square box centred on a pin, `sideKm` on the ground (the east–west extent
* widens by 1/cos(lat)); null when the result would not validate. A pin whose
* box passes ±180 gets the short-arc box (west > east), the same convention
* as a dragged dateline box, with edges wrapped into ±180.
* widens by 1/cos(lat)); null when the result would not validate.
* @param {number} lon Degrees.
* @param {number} lat Degrees.
* @param {number} [sideKm]
@@ -253,19 +207,16 @@ export function boxCentre(box) {
export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {
if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)
return null;
if (Math.abs(lon) > 180) return null;
const cosLat = Math.cos(toRadians(lat));
if (cosLat <= 0) return null;
const halfLat = sideKm / 2 / KM_PER_DEG_LAT;
const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);
// A half-width of 90° or more is not a short arc; refuse rather than wrap.
if (halfLon >= 90) return null;
const clampLat = (value) =>
Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));
const result = validateBox({
west: wrapLon(lon - halfLon),
west: lon - halfLon,
south: clampLat(lat - halfLat),
east: wrapLon(lon + halfLon),
east: lon + halfLon,
north: clampLat(lat + halfLat),
});
return result.ok ? result.box : null;
@@ -498,31 +449,15 @@ export function coverageFor(candidate, box) {
.filter((ring) => Array.isArray(ring) && ring.length >= 3);
if (!normalized || !footprints.length) return 'unknown';
const { west, south, east, north } = normalized;
const centre = boxCentre(normalized);
// A dateline box is one continuous range starting at its west edge. A
// longitude on the east side (at or past ±180) shifts by 360. One just
// outside the west corner stays put: shifting every value below west would
// send that corner the long way round and miss a footprint that covers it.
const crossing = west > east;
const project = (lon) =>
crossing && lon < west && (lon <= east || lon - east < west - lon)
? lon + 360
: lon;
const samples = [
[project(west), south],
[project(east), south],
[project(east), north],
[project(west), north],
[project(centre.lon), centre.lat],
[west, south],
[east, south],
[east, north],
[west, north],
[(west + east) / 2, (south + north) / 2],
];
return samples.every(([lon, lat]) =>
footprints.some((ring) =>
pointInPolygon(
lon,
lat,
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
),
),
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
)
? 'full'
: 'partial';
@@ -671,10 +606,6 @@ export function wvsSnapshotUrl({
const normalized = normalizeBox(box);
if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);
if (!normalized) throw new TypeError('A finite box is required');
// Worldview Snapshots rejects a BBOX whose west is greater than its east
// (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse.
if (normalized.west > normalized.east)
throw new TypeError('A snapshot cannot cross the dateline');
const bbox = [
normalized.south,
normalized.west,
+9 -120
View File
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
import {
boxFromPin,
lonSpanDeg,
nonCrossingBoxes,
boxFromRectangle,
boxSideKm,
coverageFor,
@@ -53,20 +51,11 @@ function hls(product, day, clouds, extra = {}) {
return { ...groupGranulesByDay(granules)[0], ...extra };
}
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
const reason = (box) => validateBox(box).reason;
const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 });
assert.equal(dateline.ok, true);
assert.equal(dateline.box.west, 179);
assert.equal(dateline.box.east, -179);
assert.equal(
reason({ west: 170, south: 0, east: -170, north: 1 }),
'too-large',
'a 20° dateline arc is still over the 1,000 km cap',
);
assert.equal(
reason({ west: 180, south: 0, east: -180, north: 1 }),
'degenerate',
reason({ west: 179, south: 0, east: -179, north: 1 }),
'dateline',
);
assert.equal(
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
@@ -81,6 +70,10 @@ test('validateBox refuses polar, degenerate, invalid and oversized boxes, and ac
validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,
'Imagery stops at ±85.05° latitude',
);
assert.equal(
validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,
'Select one side of the dateline',
);
assert.equal(
validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,
true,
@@ -144,14 +137,10 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400
lon: 10,
lat: 5,
});
assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), {
lon: 180,
lat: 1,
});
assert.equal(boxCentre(null), null);
});
test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => {
test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {
const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });
assert.ok(Math.abs(equator.width - 111.32) < 1e-6);
assert.ok(Math.abs(equator.height - 111.32) < 1e-6);
@@ -160,13 +149,6 @@ test('box width is the longitude span at the mid-latitude; a dateline box uses t
const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };
assert.ok(boxSideKm(nearlyGlobal).width > 30000);
assert.equal(validateBox(nearlyGlobal).reason, 'too-large');
const crossing = boxSideKm({
west: 179,
south: -0.5,
east: -179,
north: 0.5,
});
assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width));
});
test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {
@@ -185,12 +167,7 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha
assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);
assert.equal(boxFromPin(NaN, 0), null);
assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');
assert.equal(boxFromPin(181, 0), null, 'longitude out of range');
assert.equal(
boxFromPin(0, 0, 400000),
null,
'half-width of 90 degrees or more',
);
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
});
@@ -321,34 +298,6 @@ test('coverage samples the box corners and centre against the union of footprint
assert.equal(coverageFor(withRings(null), BOX), 'unknown');
});
test('coverage of a dateline box uses the short arc, not the long way', () => {
const box = { west: 179, south: 0, east: -179, north: 1 };
const ring = (west, east, south = -0.1, north = 1.1) => [
[west, south],
[east, south],
[east, north],
[west, north],
];
const withRings = (...rings) => ({
granules: rings.map((footprint) => granule({ footprint })),
});
assert.equal(
coverageFor(withRings(ring(178.5, -178.5)), box),
'full',
'one footprint that crosses ±180',
);
assert.equal(
coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box),
'full',
'a pair split exactly at ±180',
);
assert.equal(
coverageFor(withRings(ring(179, 180)), box),
'partial',
'one side does not cover the other',
);
});
test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {
const candidates = [
hls('S30', '2026-09-20', [10, null]),
@@ -480,17 +429,6 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e
() => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),
TypeError,
);
assert.throws(
() =>
wvsSnapshotUrl({
product: 'S30',
day: '2026-09-18',
box: { west: 179, south: 0, east: -179, north: 1 },
width: 64,
height: 64,
}),
/snapshot cannot cross the dateline/,
);
});
test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {
@@ -499,52 +437,3 @@ test('thumbnails load the focused card, then the visible cards outward, then the
assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);
assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);
});
test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
const near = (a, b) => Math.abs(a - b) < 1e-6;
const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492
const spanOk = (box) => {
const { width, height } = boxSideKm(box);
assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`);
assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`);
assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span');
};
// 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side.
for (const lon of [179.9, -179.9]) {
const box = boxFromPin(lon, 0);
spanOk(box);
assert.ok(box.west < box.east, `no wrap needed at ${lon}`);
assert.ok(near((box.west + box.east) / 2, lon));
}
// A pin on the line, or close enough that the box passes it, wraps.
for (const lon of [180, -180, 179.99, -179.99]) {
const box = boxFromPin(lon, 0);
spanOk(box);
assert.ok(box.west > box.east, `crossing at ${lon}`);
assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180');
assert.ok(
near(
box.west,
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
),
);
assert.equal(
nonCrossingBoxes(box).length,
2,
'splits for tiling and Worldview',
);
assert.ok(
Math.abs(
Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon),
) < 1e-6,
);
}
// 0 is an ordinary box.
const mid = boxFromPin(0, 0);
spanOk(mid);
assert.ok(mid.west < mid.east && near(mid.west, -half));
// Off the equator the east-west extent widens but stays a short arc.
const high = boxFromPin(-179.99, 60);
spanOk(high);
assert.ok(high.west > high.east);
});
+24 -97
View File
@@ -1,7 +1,7 @@
/**
* Recent Imagery drapes two slots through the renderer's globe port, slot
* `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS
* layers, one per available part, on whichever surface the map stack draws.
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
* renderer's globe port, draped on whichever surface the map stack draws.
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
* requests pass a small semaphore of our own, shared by both slots, through
* each layer's admission hook; the renderer's own request limits stay
@@ -15,13 +15,7 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { markBaseTileset } from '../../render/baseTilesets.js';
import { drawOf } from '../../render/rendererOf.js';
import {
PRODUCTS,
boxKey,
gibsTemplate,
lonSpanDeg,
nonCrossingBoxes,
} from './model.js';
import { PRODUCTS, gibsTemplate } from './model.js';
const SLOT_IDS = ['a', 'b'];
const SPLITS = new Set(['left', 'right', 'none']);
@@ -35,27 +29,8 @@ function clampAlpha(value) {
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
}
/** One comparable key for a slot's draped parts. */
const partsKey = (parts) => parts.map(boxKey).sort().join(';');
/**
* The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would
* draw an empty side black, so it drapes only parts Worldview confirmed
* present, and no part of a dateline box before the probe answers. A PNG
* drapes every part not confirmed empty.
*/
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
const parts = nonCrossingBoxes(box);
const keys = (list) => new Set(list.map(boxKey));
if (PRODUCTS[candidate.product]?.format !== 'jpg') {
if (!Array.isArray(emptyBoxes)) return parts;
const empty = keys(emptyBoxes);
return parts.filter((part) => !empty.has(boxKey(part)));
}
if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts;
const proven = keys(availableBoxes);
return parts.filter((part) => proven.has(boxKey(part)));
}
const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* Admit a tile request while the semaphore has room. A request that finds
@@ -102,7 +77,7 @@ export function createRecentImageryRenderer({
let host = NO_HOST;
let destroyed = false;
const admission = { limit: maxTileRequests, inFlight: 0 };
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
const owned = { a: null, b: null };
const admit = admitTileRequests(admission, requestRender);
@@ -130,53 +105,36 @@ export function createRecentImageryRenderer({
const record = owned[slotId];
if (!record) return false;
owned[slotId] = null;
for (const layer of record.layers) layer.remove();
record.layer.remove();
return true;
}
function applyLook(record) {
for (const layer of record.layers) {
layer.alpha = record.alpha;
layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
record.layer.alpha = record.alpha;
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
function mount(slotId, { candidate, parts, alpha, split }) {
if (!parts.length) return false;
owned[slotId] = {
layers: parts.map((part) =>
host.globe.imagery.add(specFor(candidate, part)),
),
globe: host.globe,
candidate,
parts,
alpha,
split,
};
function mount(slotId, { candidate, box, alpha, split }) {
const layer = host.globe.imagery.add(specFor(candidate, box));
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
applyLook(owned[slotId]);
return true;
}
return {
/**
* Drape the parts of a candidate's box that the evidence allows (see drapedParts).
* The same candidate on the same port keeps the layer of each unchanged part.
* Drape a candidate into a slot. The same candidate on the same host only
* updates its look; anything else replaces the slot's layer.
* @param {'a'|'b'} slotId
* @param {object} candidate
* @param {object} box Degrees box.
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
* @returns {boolean} Whether a layer is now draped for the slot.
*/
showSlot(
slotId,
candidate,
box,
{
alpha = 1,
splitDirection = 'none',
availableBoxes = null,
emptyBoxes = null,
} = {},
{ alpha = 1, splitDirection = 'none' } = {},
) {
if (destroyed || !candidate?.key || !box) return false;
if (!host.globe) {
@@ -185,52 +143,21 @@ export function createRecentImageryRenderer({
}
const current = owned[slotId];
const look = { alpha: clampAlpha(alpha), split: splitDirection };
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
if (
current &&
current.globe === host.globe &&
current.candidate.key === candidate.key &&
parts.length
boxKey(current.box) === boxKey(box)
) {
if (partsKey(current.parts) !== partsKey(parts)) {
const previous = new Map(
current.parts.map((part, i) => [boxKey(part), current.layers[i]]),
);
// A new half goes right above the slot's surviving half, so both
// halves keep the same place against the other slot.
const survivor = parts
.map((part) => previous.get(boxKey(part)))
.find(Boolean);
const at = survivor
? host.globe.imagery.list().indexOf(survivor) + 1
: undefined;
const layers = parts.map((part) => {
const key = boxKey(part);
const layer = previous.get(key);
previous.delete(key);
return (
layer ?? host.globe.imagery.add(specFor(candidate, part), at)
);
});
for (const layer of previous.values()) layer.remove();
Object.assign(current, { layers, parts, ...look });
applyLook(current);
requestRender('recent-imagery-show');
} else if (
current.alpha !== look.alpha ||
current.split !== look.split
) {
if (current.alpha !== look.alpha || current.split !== look.split) {
Object.assign(current, look);
applyLook(current);
requestRender('recent-imagery-look');
}
return true;
}
const removed = removeOwned(slotId);
if (!mount(slotId, { candidate, parts, ...look })) {
if (removed) requestRender('recent-imagery-hide');
return false;
}
removeOwned(slotId);
mount(slotId, { candidate, box, ...look });
requestRender('recent-imagery-show');
return true;
},
@@ -294,7 +221,7 @@ export function createRecentImageryRenderer({
return out;
},
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
/** Number of layers this renderer owns (never above two). */
ownedCount() {
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
},
@@ -320,11 +247,11 @@ let previewSeq = 0;
/** A box with no area has no fill: a press, or a drag along one axis. */
const hasArea = (box) =>
Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
Boolean(box) && box.east > box.west && box.north > box.south;
/** A box with no extent draws nothing: a press that has not moved yet. */
const hasExtent = (box) =>
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
Boolean(box) && (box.east > box.west || box.north > box.south);
/**
* The box tool's preview: the box being dragged, a translucent fill and a
+1 -210
View File
@@ -5,9 +5,7 @@ import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { boxKey, nonCrossingBoxes } from './model.js';
import { BOX, FIJI_BOX } from './testDoubles.mjs';
import { BOX } from './testDoubles.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
@@ -273,210 +271,3 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe
box = { west: -96, south: 32, east: -95, north: 33 };
assert.doesNotThrow(() => preview.changed());
});
test('a dateline box drapes one layer on each side of ±180 and removes both', () => {
const { renderer, globe } = fixture();
const box = { west: 179, south: 0, east: -179, north: 1 };
assert.equal(
renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }),
true,
);
assert.equal(renderer.ownedCount(), 1);
assert.equal(globe.layers.length, 2);
assert.deepEqual(
globe.layers.map((item) => item.spec.rectangle),
[
{ west: 179, south: 0, east: 180, north: 1 },
{ west: -180, south: 0, east: -179, north: 1 },
],
);
assert.equal(globe.layers[0].alpha, 0.4);
assert.equal(globe.layers[1].alpha, 0.4);
assert.equal(globe.layers[0].split, 'left');
assert.equal(globe.layers[1].split, 'left');
renderer.setAlpha('a', 0.2);
assert.equal(globe.layers[0].alpha, 0.2);
assert.equal(globe.layers[1].alpha, 0.2);
renderer.showSlot('a', S30, box, { alpha: 0.2 });
assert.equal(globe.added.length, 2, 'the same box does not remount');
renderer.hideSlot('a');
assert.equal(globe.layers.length, 0);
});
test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => {
const { renderer, globe } = fixture();
const [west, east] = nonCrossingBoxes(FIJI_BOX);
assert.equal(
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }),
true,
);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[east],
);
renderer.showSlot('b', VIIRS, FIJI_BOX, {
availableBoxes: [east, west],
splitDirection: 'right',
});
assert.deepEqual(
globe.layers.map((layer) => layer.split),
['none', 'right', 'right'],
);
assert.equal(globe.layers.length, 3);
const next = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe: next });
assert.deepEqual(
next.layers.map((layer) => layer.spec.rectangle),
[east, west, east],
);
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] });
assert.equal(next.layers.length, 4);
renderer.destroy();
assert.equal(next.layers.length, 0);
});
test('no allowed half, or halves of another box, drapes nothing', () => {
const { renderer, globe } = fixture();
for (const availableBoxes of [[], [BOX]]) {
assert.equal(
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }),
false,
);
assert.equal(globe.layers.length, 0);
}
});
test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => {
const { renderer, globe } = fixture();
assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false);
assert.equal(globe.layers.length, 0);
assert.equal(renderer.showSlot('a', VIIRS, BOX), true);
assert.equal(globe.layers.length, 1);
assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true);
assert.equal(globe.layers.length, 3);
renderer.destroy();
});
test('evidence going from none to empty removes the drape', () => {
const { renderer, globe } = fixture();
renderer.showSlot('a', S30, FIJI_BOX);
assert.equal(globe.layers.length, 2);
assert.equal(
renderer.showSlot('a', S30, FIJI_BOX, {
availableBoxes: [],
emptyBoxes: nonCrossingBoxes(FIJI_BOX),
}),
false,
);
assert.equal(globe.layers.length, 0);
renderer.destroy();
});
test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => {
const [west, east] = nonCrossingBoxes(FIJI_BOX);
for (const [product, expected] of [
[S30, [west, east]],
[VIIRS, [east]],
]) {
const { renderer, globe } = fixture();
renderer.showSlot('a', product, FIJI_BOX, {
availableBoxes: [east],
emptyBoxes: [],
});
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
expected,
);
renderer.destroy();
}
});
test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => {
const renderer = createRecentImageryRenderer();
const globe = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe });
const [west, east] = nonCrossingBoxes(FIJI_BOX);
const layerFor = (box) =>
globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box));
// An HLS day drapes both halves before its probe answers.
renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' });
const kept = layerFor(west);
assert.ok(kept);
const added = globe.added.length;
// The probe confirms the east half empty: only the east layer goes.
renderer.showSlot('a', S30, FIJI_BOX, {
alpha: 0.4,
splitDirection: 'left',
availableBoxes: [west],
emptyBoxes: [east],
});
assert.equal(kept.removed, false, 'the west layer survives the narrowing');
assert.equal(globe.added.length, added, 'narrowing adds no layer');
assert.equal(layerFor(east), undefined);
// A later probe admits east again: only the east layer is added.
renderer.showSlot('a', S30, FIJI_BOX, {
alpha: 0.4,
splitDirection: 'left',
availableBoxes: [west, east],
emptyBoxes: [],
});
assert.equal(kept.removed, false, 'the west layer survives the widening');
assert.equal(globe.added.length, added + 1);
assert.equal(kept.alpha, 0.4);
assert.equal(kept.split, 'left');
renderer.destroy();
});
test('widening slot a over the dateline keeps it below slot b on both sides', () => {
const { renderer, globe } = fixture();
const [west, east] = nonCrossingBoxes(FIJI_BOX);
const topOn = (box) =>
globe.layers
.filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box))
.at(-1)
.spec.url.includes('S30')
? 'A'
: 'B';
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] });
renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] });
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] });
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
renderer.destroy();
});
test('the drag preview draws a wrapped fill and outline across the dateline', async () => {
const draw = fakeDrawPort();
let box = { west: 179, south: 0, east: 179, north: 0 };
const preview = createImageryBoxPreview({}, () => box, { draw });
const [fills, outlines] = draw.sets.values();
preview.setVisible(true);
box = { ...box, east: -179 };
preview.changed();
assert.equal(fills.items.size, 0);
assert.equal(outlines.items.get('edge').show, true);
assert.deepEqual(
outlines.items.get('edge').positions[1],
fromDegrees(-179, 0),
);
box = { ...box, north: 1 };
preview.changed();
assert.equal(fills.items.get('box').show, true);
assert.deepEqual(fills.items.get('box').geometry.rect, box);
const edge = outlines.items.get('edge');
assert.equal(edge.show, true);
assert.deepEqual(edge.positions, [
fromDegrees(179, 0),
fromDegrees(-179, 0),
fromDegrees(-179, 1),
fromDegrees(179, 1),
fromDegrees(179, 0),
]);
await preview.destroy();
});
+11 -152
View File
@@ -1,107 +1,10 @@
import { searchHls } from './catalog.js';
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
/**
* Deadline for one half's response headers, so a day whose other half
* answered is not held at "checking".
*/
const DEFAULT_HALF_DEADLINE_MS = 15_000;
/**
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
* probed as its two non-crossing halves, wider first. A plain box is its
* one normalized half. A day has data when either half does.
*/
function requestBoxes(box) {
return nonCrossingBoxes(box).sort(
(a, b) => b.east - b.west - (a.east - a.west),
);
}
/** A response's Data-Present answer in lower case, or '' when it failed or has none. */
export const dataPresent = (response) =>
response?.ok
? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase()
: '';
/**
* One half's snapshot fetch, raced against its own deadline so a half that
* never answers, even over a transport that ignores AbortSignal, still
* settles. Its deadline cancels only this half. The caller can cancel it
* at any time, including while its body is being read.
*/
function probeHalf(
url,
{ fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl },
) {
const controller = new AbortController();
return new Promise((resolve, reject) => {
let timer = null;
const finishTimeout = () => {
if (timer !== null) clearTimeoutImpl(timer);
timer = null;
};
const stop = (reason) => {
controller.abort(reason);
finishTimeout();
// Settle even if the transport ignores abort.
reject(reason);
};
if (signal?.aborted) {
stop(signal.reason);
return;
}
signal?.addEventListener('abort', () => stop(signal.reason), {
once: true,
});
if (deadlineMs > 0)
timer = setTimeoutImpl(
() =>
stop(new DOMException('Thumbnail half timed out', 'TimeoutError')),
deadlineMs,
);
let promise;
try {
promise = Promise.resolve(fetchImpl(url, { signal: controller.signal }));
} catch (error) {
finishTimeout();
reject(error);
return;
}
promise.then(
(value) => {
finishTimeout();
resolve(value);
},
(error) => {
finishTimeout();
reject(error);
},
);
});
}
/**
* Non-enumerable per-half evidence for the box's non-crossing halves:
* presentBoxes lists the halves Worldview confirmed present, emptyBoxes
* the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js.
*/
function withHalves(response, { presentBoxes, emptyBoxes }) {
Object.defineProperties(response, {
presentBoxes: { value: presentBoxes, configurable: true },
emptyBoxes: { value: emptyBoxes, configurable: true },
});
return response;
}
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
/**
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
* Thumbnail responses must expose Data-Present: true for image admission, or
* false for confirmed empty coverage, including injected getThumbnail sources.
* getThumbnail also sets presentBoxes and emptyBoxes (see withHalves),
* also on the error it throws when another half was confirmed empty.
* Without per-half evidence the renderer drapes every side of an HLS
* dateline box and no side of a VIIRS one.
*/
export function createRecentImagerySource({
fetchImpl = (...args) => globalThis.fetch(...args),
@@ -109,68 +12,24 @@ export function createRecentImagerySource({
thumbnailUrl = wvsSnapshotUrl,
tileTemplate = gibsTemplate,
credit = 'NASA GIBS',
halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS,
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
} = {}) {
return {
credit,
searchHls: (query) => search({ ...query, fetchImpl }),
async getThumbnail(candidate, box, { size = 256, signal } = {}) {
signal?.throwIfAborted();
const halves = requestBoxes(box);
const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0;
const results = await Promise.allSettled(
halves.map((half) =>
probeHalf(
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box: half,
width: size,
height: size,
}),
{
fetchImpl,
signal,
deadlineMs,
setTimeoutImpl,
clearTimeoutImpl,
},
),
),
const response = await fetchImpl(
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box,
width: size,
height: size,
}),
{ signal },
);
signal?.throwIfAborted();
// Per half, its Data-Present answer or null when it did not answer.
const answers = results.map((result) =>
result.status === 'fulfilled' ? dataPresent(result.value) : null,
);
const halvesWhere = (value) =>
halves.filter((_, i) => answers[i] === value);
// A missing answer is an error unless another half proved data. The
// error keeps a half confirmed empty (see withHalves).
const failure = results.find((result) => result.status === 'rejected');
if (failure && !answers.includes('true')) {
const emptyBoxes = halvesWhere('false');
if (Object.isExtensible(failure.reason))
withHalves(
failure.reason,
emptyBoxes.length
? { presentBoxes: [], emptyBoxes }
: { presentBoxes: null, emptyBoxes: null },
);
throw failure.reason;
}
// Show the first half with data (the wider wins a tie), else the first
// not confirmed empty, so an unreadable answer is never called empty.
// Every half answered here unless one proved data.
let shown = answers.indexOf('true');
if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false');
if (shown < 0) shown = 0;
return withHalves(results[shown].value, {
presentBoxes: halvesWhere('true'),
emptyBoxes: halvesWhere('false'),
});
return response;
},
getTileTemplate: (product, day) => tileTemplate(product, day),
};
+10 -253
View File
@@ -1,20 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { manualTimers } from './testDoubles.mjs';
import { createRecentImagerySource } from './source.js';
test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => {
const controller = new AbortController();
const query = {
box: { west: 0, east: 1, south: 0, north: 1 },
signal: controller.signal,
};
const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal };
const candidate = { product: 'S30', day: '2026-10-01' };
const calls = [];
const fetchImpl = async (...args) => {
calls.push(args);
return new Response('image');
};
const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); };
const source = createRecentImagerySource({
fetchImpl,
search: async (request) => {
@@ -23,263 +16,27 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
assert.equal(request.box, query.box);
return [candidate];
},
thumbnailUrl: ({ product, day, width }) =>
`https://imagery.example/${product}/${day}/${width}`,
tileTemplate: (product, day) =>
`https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`,
tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
credit: 'Example imagery',
});
assert.deepEqual(await source.searchHls(query), [candidate]);
assert.equal(
await (
await source.getThumbnail(candidate, query.box, {
signal: controller.signal,
})
).text(),
'image',
);
assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image');
assert.equal(calls.length, 1);
assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256');
// The fetch gets a private signal chained to the caller's.
const halfSignal = calls[0][1].signal;
assert.notEqual(halfSignal, controller.signal);
assert.equal(halfSignal.aborted, false);
controller.abort();
assert.equal(halfSignal.aborted, true);
assert.equal(
source.getTileTemplate(candidate.product, candidate.day),
'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}',
);
assert.equal(calls[0][1].signal, controller.signal);
assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}');
assert.equal(source.credit, 'Example imagery');
});
test('cancelled thumbnail acquisition does not return stale responses or retry', async () => {
const controller = new AbortController();
const box = { west: 0, south: 0, east: 1, north: 1 };
let calls = 0;
const source = createRecentImagerySource({
thumbnailUrl: () => 'https://imagery.example/thumbnail',
fetchImpl: async () => {
calls++;
controller.abort();
return new Response('image');
},
fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); },
});
await assert.rejects(
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
assert.equal(calls, 1);
});
test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => {
const requested = [];
const source = createRecentImagerySource({
thumbnailUrl: ({ box }) => {
requested.push(box);
return 'https://imagery.example/thumbnail';
},
fetchImpl: async () => new Response('image'),
});
const candidate = { product: 'S30', day: '2026-10-01' };
await source.getThumbnail(candidate, {
west: 179.9,
south: 0,
east: -179,
north: 1,
});
assert.deepEqual(requested, [
{ west: -180, south: 0, east: -179, north: 1 },
{ west: 179.9, south: 0, east: 180, north: 1 },
]);
requested.length = 0;
await source.getThumbnail(candidate, {
west: 179,
south: 0,
east: -179.9,
north: 1,
});
assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 });
assert.equal(requested.length, 2);
assert.ok(requested.every((box) => box.west <= box.east));
});
const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 };
// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG.
const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' };
const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 };
const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 };
const dated = (present, body = 'image') =>
new Response(body, { headers: { 'Data-Present': present } });
function halvesSource(answers, options = {}) {
const requested = [];
const source = createRecentImagerySource({
...options,
thumbnailUrl: ({ box }) =>
`https://imagery.example/${box.west}/${box.east}`,
fetchImpl: async (url) => {
requested.push(url);
const answer = answers[url.split('imagery.example/')[1]];
if (answer instanceof Error) throw answer;
return answer.clone ? answer : answer();
},
});
return { source, requested };
}
const candidate = { product: 'S30', day: '2026-10-01' };
test('a crossing box probes both halves and is present when only the narrow half has data', async () => {
const { source, requested } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(requested.length, 2);
assert.equal(response.headers.get('Data-Present'), 'true');
assert.equal(await response.text(), 'narrow');
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
assert.deepEqual(response.emptyBoxes, [WIDE_BOX]);
});
test('a crossing box with data only on the wider half is present and shows the wider side', async () => {
const { source } = halvesSource({
'-180/-179': dated('true', 'wide'),
'179.9/180': dated('false'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'wide');
});
test('a crossing box is empty only when both halves are confirmed empty', async () => {
const { source } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': dated('false'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(response.headers.get('Data-Present'), 'false');
assert.deepEqual(response.presentBoxes, []);
assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]);
});
test('a crossing box is not called empty when the other half failed', async () => {
const { source } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': () => new Response('x', { status: 503 }),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(response.ok, false);
});
test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => {
const { source } = halvesSource({
'-180/-179': dated('true', 'wide'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'wide');
assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]);
});
test('a rejected half does not hide data on the other half, and never reads as empty', async () => {
const { source } = halvesSource({
'-180/-179': new Error('network'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'narrow');
const failing = halvesSource({
'-180/-179': new Error('network'),
'179.9/180': dated('false'),
});
await assert.rejects(
failing.source.getThumbnail(candidate, NARROW_WEST),
/network/,
);
});
for (const [label, answer] of [
['rejected', new Error('network')],
['hung', () => new Promise(() => {})],
['answered without a presence', () => dated('unknown', 'maybe')],
]) {
for (const product of [JPEG_CANDIDATE, candidate]) {
test(`a ${product.product} half that ${label} is neither present nor empty`, async () => {
const { source } = halvesSource(
{ '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') },
{ halfDeadlineMs: 20 },
);
const response = await source.getThumbnail(product, NARROW_WEST);
assert.equal(response.headers.get('Data-Present'), 'true');
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
assert.deepEqual(response.emptyBoxes, []);
});
}
}
test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => {
const controller = new AbortController();
const source = createRecentImagerySource({
thumbnailUrl: () => 'https://example.invalid/',
halfDeadlineMs: 10000,
fetchImpl: () => {
controller.abort();
return new Promise(() => {});
},
});
const outcome = await Promise.race([
source
.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal })
.then(
() => 'resolved',
(error) => error.name,
),
new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)),
]);
assert.equal(outcome, 'AbortError');
});
test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => {
const hang = () => new Promise(() => {});
const { source, requested } = halvesSource(
{ '-180/-179': hang, '179.9/180': hang },
{ halfDeadlineMs: 10 },
);
await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), {
name: 'TimeoutError',
});
assert.equal(requested.length, 2);
});
test("the caller's cancellation rejects at once and stops every half", async () => {
const aborted = [];
const source = createRecentImagerySource({
thumbnailUrl: ({ box }) => String(box.west),
fetchImpl: (url, { signal }) => {
signal.addEventListener('abort', () => aborted.push(url), { once: true });
return new Promise(() => {});
},
});
const controller = new AbortController();
const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, {
signal: controller.signal,
});
controller.abort();
await assert.rejects(result, { name: 'AbortError' });
assert.deepEqual(aborted, ['-180', '179.9']);
});
test('a successful probe leaves no deadline timer behind', async () => {
const timers = manualTimers();
const { source } = halvesSource(
{ '-180/-179': dated('true'), '179.9/180': dated('false') },
timers,
);
await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
assert.equal(timers.armed(), 0);
assert.equal(timers.cleared.length, 2);
});
-7
View File
@@ -16,13 +16,6 @@ export const BOX = Object.freeze({
north: 30.3,
});
export const FIJI_BOX = Object.freeze({
west: 179,
south: -18,
east: -177,
north: -17,
});
export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
/** Timers that fire only when the test says so. */
+8 -43
View File
@@ -1,6 +1,6 @@
/**
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
* candidate day. The response's `Data-Present` header is the only proof that
* a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and
* `Acquisition-Time` carries the sensing time. Fetches are bounded, and so
* are decoded images: residency is least-recently-USED, where a request or a
@@ -8,28 +8,16 @@
* card on every render, so a read that counted would evict the visible cards
* first). Eviction revokes the image only; what the probe proved is kept.
*/
import { boxKey, thumbnailOrder } from './model.js';
import { createRecentImagerySource, dataPresent } from './source.js';
import { thumbnailOrder } from './model.js';
import { createRecentImagerySource } from './source.js';
const EMPTY = Object.freeze({
status: 'unknown',
objectUrl: null,
acquisitionTime: null,
availableBoxes: null,
emptyBoxes: null,
loading: false,
});
/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */
function keepProvenHalves(previous, next, opposite) {
if (!Array.isArray(next) || !Array.isArray(opposite)) return previous;
const drop = new Set([...next, ...opposite].map(boxKey));
return [
...next,
...(previous ?? []).filter((half) => !drop.has(boxKey(half))),
];
}
/**
* @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]
*/
@@ -102,22 +90,18 @@ export function createThumbnailLoader({
let status = 'error';
let objectUrl = null;
let acquisitionTime = null;
// Per-half evidence (see withHalves in source.js), or null without it.
let availableBoxes = null;
let emptyBoxes = null;
let cancelled = false;
try {
const response = await requestThumbnail(entry.candidate, entry.box, {
size,
signal: controller.signal,
});
// Each half's explicit answer counts even when the shown response fails.
availableBoxes = response?.presentBoxes ?? null;
emptyBoxes = response?.emptyBoxes ?? null;
if (controller.signal.aborted) {
cancelled = true;
} else if (response?.ok) {
const present = dataPresent(response);
const present = String(
response.headers?.get?.('Data-Present') ?? '',
).toLowerCase();
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
if (present === 'false') {
status = 'empty';
@@ -133,11 +117,7 @@ export function createThumbnailLoader({
} catch (error) {
if (controller.signal.aborted || error?.name === 'AbortError')
cancelled = true;
else {
status = 'error';
availableBoxes = error?.presentBoxes ?? availableBoxes;
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
}
else status = 'error';
} finally {
inFlight -= 1;
entry.loading = false;
@@ -149,17 +129,6 @@ export function createThumbnailLoader({
pump();
return;
}
// Each half keeps its latest explicit answer.
entry.availableBoxes = keepProvenHalves(
entry.availableBoxes,
availableBoxes,
emptyBoxes,
);
entry.emptyBoxes = keepProvenHalves(
entry.emptyBoxes,
emptyBoxes,
availableBoxes,
);
// A failed re-fetch of an evicted image keeps what the day proved.
if (status !== 'error' || entry.status !== 'present') {
entry.status = status;
@@ -227,8 +196,6 @@ export function createThumbnailLoader({
status: 'unknown',
objectUrl: null,
acquisitionTime: null,
availableBoxes: null,
emptyBoxes: null,
loading: false,
controller: null,
touched: 0,
@@ -305,7 +272,7 @@ export function createThumbnailLoader({
/**
* Read a day's state. A read is not a use: it never changes residency.
* @param {string} key Candidate key.
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
*/
get(key) {
const entry = entries.get(key);
@@ -314,8 +281,6 @@ export function createThumbnailLoader({
status: entry.status,
objectUrl: entry.objectUrl,
acquisitionTime: entry.acquisitionTime,
availableBoxes: entry.availableBoxes,
emptyBoxes: entry.emptyBoxes,
loading: entry.loading,
};
},
+7 -74
View File
@@ -1,9 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createThumbnailLoader } from './thumbnails.js';
import { createRecentImagerySource } from './source.js';
import { nonCrossingBoxes } from './model.js';
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
import { BOX, response, settle } from './testDoubles.mjs';
const candidate = (product, day) => ({
key: `${product}:${day}`,
product,
day,
});
/** A fetch whose responses the test releases, in any order. */
function fakeFetch() {
@@ -64,8 +68,6 @@ test('Data-Present decides the day: present with an object URL and sensing time,
status: 'present',
objectUrl: 'blob:1',
acquisitionTime: '2026-09-18T17:12:00Z',
availableBoxes: [BOX],
emptyBoxes: [],
loading: false,
});
assert.equal(loader.get('L30:2026-09-16').status, 'empty');
@@ -335,75 +337,6 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
assert.deepEqual(revoked, ['blob:1']);
});
test('the loader proves a dateline day present from one half and hands that half on', async () => {
const day = candidate('VIIRS', '2026-11-04');
const time = day.day + 'T22:10:00Z';
const { loader } = fixture({
fetchImpl: async (url) => {
const east =
new URL(url).searchParams.get('BBOX').split(',')[1] === '-180';
return response({
headers: east
? { 'Data-Present': 'true', 'Acquisition-Time': time }
: { 'Data-Present': 'false' },
});
},
});
loader.request(day, FIJI_BOX);
await settle();
const entry = loader.get(day.key);
assert.equal(entry.status, 'present');
assert.equal(entry.acquisitionTime, time);
assert.ok(entry.objectUrl);
assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]);
loader.destroy();
});
test('a dateline day whose halves both hang is an error, not "checking" forever', async () => {
const source = createRecentImagerySource({
fetchImpl: () => new Promise(() => {}),
halfDeadlineMs: 20,
});
const loader = createThumbnailLoader({
requestThumbnail: source.getThumbnail,
});
const day = candidate('VIIRS', '2026-11-04');
const settled = new Promise((resolve) => loader.subscribe(resolve));
loader.request(day, FIJI_BOX);
await settled;
assert.equal(loader.get(day.key).status, 'error');
loader.destroy();
});
test('a re-probe of a present day drops a half only when it is confirmed empty', async () => {
const box = { west: 179, south: 0, east: -179, north: 1 };
const [west, east] = nonCrossingBoxes(box);
const answers = [
{ presentBoxes: [west, east], emptyBoxes: [] },
{ presentBoxes: [west, east], emptyBoxes: [] },
{ presentBoxes: [west], emptyBoxes: [east] },
];
const { loader } = fixture({
maxDecoded: 1,
requestThumbnail: async () =>
Object.assign(
response({ headers: { 'Data-Present': 'true' } }),
answers.shift(),
),
});
const day1 = candidate('VIIRS', '2026-11-04');
const day2 = candidate('VIIRS', '2026-11-05');
loader.request(day1, box);
await settle();
loader.request(day2, box);
await settle();
assert.equal(loader.get(day1.key).objectUrl, null);
loader.request(day1, box);
await settle();
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
loader.destroy();
});
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
const { loader, fetch } = fixture({ maxInFlight: 1 });
const stale = candidate('S30', '2026-09-10');
+357
View File
@@ -0,0 +1,357 @@
// OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard.
//
// `/api/flights/track` spends 4 OpenSky credits per call from the `/tracks/*`
// bucket. OpenSky keeps three independent daily buckets (`/states/*`,
// `/tracks/*`, `/flights/*`), so this route neither spends nor is blocked by
// the `/states/all` budget `/api/flights` governs. Its 60s per-icao cache
// bounds MEMORY, not spend: `icao24` is six hex digits, so a caller that varies
// it walks past the cache into a live, credit-consuming call every time.
//
// These cases drive the real exported route handlers. No network: `fetch` is
// stubbed per test and restored afterwards, so a case that reaches upstream
// fails loudly rather than making a request.
//
// NOTE: the `/states/all` cooldown is module-scoped state in `opensky.js` and,
// once set, stays set for the life of the process (bounded 30s…30min). The case
// that arms it therefore runs LAST. The tracks cooldown lives in each
// `trackBackfillProxies()` instance, so every test gets a clear one.
//
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js';
import { openSkyProxy } from '../server/providers/aircraft/opensky.js';
/** Collect a plugin's routes into a path → handler map. */
function install(plugin) {
const routes = new Map();
const server = {
middlewares: {
use(path, handler) {
routes.set(path, handler);
},
},
};
plugin.configureServer(server);
return routes;
}
function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) {
return new Promise((resolve, reject) => {
const headers = new Map();
const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } };
const res = {
statusCode: 200,
setHeader(name, value) {
headers.set(String(name).toLowerCase(), String(value));
},
writeHead(status, hdrs = {}) {
this.statusCode = status;
for (const [name, value] of Object.entries(hdrs))
headers.set(String(name).toLowerCase(), String(value));
},
end(body = '') {
let parsed = null;
try {
parsed = body ? JSON.parse(String(body)) : null;
} catch {
parsed = String(body);
}
resolve({
statusCode: this.statusCode,
headers: Object.fromEntries(headers),
body: parsed,
});
},
};
Promise.resolve(handler(req, res)).catch(reject);
});
}
/** Replace global fetch for one test, restoring it afterwards. */
function stubFetch(t, impl) {
const original = globalThis.fetch;
globalThis.fetch = impl;
t.after(() => {
globalThis.fetch = original;
});
}
/** An OpenSky /tracks/all answer, shaped like the real one. */
const trackOk = () =>
new Response(JSON.stringify({ path: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', async (t) => {
let upstreamCalls = 0;
stubFetch(t, async () => {
upstreamCalls += 1;
return trackOk();
});
const track = install(trackBackfillProxies()).get('/api/flights/track');
const allowed = [];
for (let i = 0; i < 30; i += 1) {
// A DIFFERENT icao24 every time: each one is a fresh cache key, which is
// exactly the path the 60s cache cannot see.
const icao24 = (0x400000 + i).toString(16).padStart(6, '0');
allowed.push(await request(track, { url: `/?icao24=${icao24}` }));
}
assert.equal(
allowed.filter((r) => r.statusCode === 429).length,
0,
'the first 30 distinct lookups in a minute are ordinary use',
);
const refused = await request(track, { url: '/?icao24=4affff' });
assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused');
assert.deepEqual(refused.body, { error: 'Rate limit exceeded' });
assert.equal(
refused.headers['retry-after'],
'60',
'a refusal names the limiter window, not a shorter guess',
);
assert.equal(
upstreamCalls,
30,
'the refused request never reached OpenSky — the point is the credits',
);
});
test('each client gets its own quota rather than sharing one bucket', async (t) => {
stubFetch(t, async () => trackOk());
const track = install(trackBackfillProxies()).get('/api/flights/track');
for (let i = 0; i < 30; i += 1)
await request(track, {
url: `/?icao24=${(0x500000 + i).toString(16)}`,
remoteAddress: '198.51.100.7',
});
const exhausted = await request(track, {
url: '/?icao24=5affff',
remoteAddress: '198.51.100.7',
});
assert.equal(exhausted.statusCode, 429);
const neighbour = await request(track, {
url: '/?icao24=5abbbb',
remoteAddress: '198.51.100.8',
});
assert.notEqual(
neighbour.statusCode,
429,
'one noisy host must not take the layer away from everyone else',
);
});
test('the retired military route is not metered, so the OpenSky limiter never reaches it', async (t) => {
let militaryUpstreamCalls = 0;
stubFetch(t, async (url) => {
if (String(url).includes('/tracks/all')) return trackOk();
militaryUpstreamCalls += 1;
return new Response('{"trace":[]}', { status: 200 });
});
const routes = install(trackBackfillProxies());
const track = routes.get('/api/flights/track');
const trace = routes.get('/api/military/track');
for (let i = 0; i < 30; i += 1)
await request(track, { url: `/?icao24=${(0x610000 + i).toString(16)}` });
assert.equal(
(await request(track, { url: '/?icao24=61ffff' })).statusCode,
429,
);
// It answers a fixed refusal without any upstream call, so a limiter would
// only turn that refusal into a different one.
for (let i = 0; i < 31; i += 1) {
const military = await request(trace, {
url: `/?hex=${(0x620000 + i).toString(16)}`,
});
assert.equal(military.statusCode, 503);
}
assert.equal(militaryUpstreamCalls, 0, 'the refusal makes no upstream call');
});
test('a 429 from /tracks stands every other icao24 down until it clears', async (t) => {
let upstreamCalls = 0;
stubFetch(t, async () => {
upstreamCalls += 1;
return new Response('{}', {
status: 429,
headers: { 'x-rate-limit-retry-after-seconds': '120' },
});
});
const track = install(trackBackfillProxies()).get('/api/flights/track');
const first = await request(track, { url: '/?icao24=71a001' });
assert.equal(first.statusCode, 429);
assert.equal(upstreamCalls, 1);
// A DIFFERENT key: the per-icao cache cannot see it, only the cooldown can.
const second = await request(track, { url: '/?icao24=71a002' });
assert.equal(second.statusCode, 429, 'refused locally');
assert.equal(
upstreamCalls,
1,
'the /tracks bucket is empty, so no further credits are asked for',
);
const retryAfter = Number(second.headers['retry-after']);
assert.ok(
retryAfter > 60 && retryAfter <= 120,
`the refusal carries OpenSky's remaining cooldown (got ${retryAfter})`,
);
});
test('a cached track is still served while /tracks is cooling', async (t) => {
let cooling = false;
stubFetch(t, async () =>
cooling
? new Response('{}', {
status: 429,
headers: { 'x-rate-limit-retry-after-seconds': '120' },
})
: trackOk(),
);
const track = install(trackBackfillProxies()).get('/api/flights/track');
assert.equal(
(await request(track, { url: '/?icao24=72b001' })).statusCode,
200,
);
cooling = true;
assert.equal(
(await request(track, { url: '/?icao24=72b002' })).statusCode,
429,
);
const replay = await request(track, { url: '/?icao24=72b001' });
assert.equal(
replay.statusCode,
200,
'replaying a fetched body costs nothing',
);
});
test('a malformed icao24 is still rejected before any upstream call', async (t) => {
let upstreamCalls = 0;
stubFetch(t, async () => {
upstreamCalls += 1;
return trackOk();
});
const track = install(trackBackfillProxies()).get('/api/flights/track');
const bad = await request(track, { url: '/?icao24=nothex' });
assert.equal(bad.statusCode, 400);
assert.equal(upstreamCalls, 0);
});
// --- LAST: arming the /states/all cooldown is one-way for this process.
test('only upstream calls are charged: cached answers and malformed requests are free', async (t) => {
let upstreamCalls = 0;
stubFetch(t, async () => {
upstreamCalls += 1;
return trackOk();
});
const track = install(trackBackfillProxies()).get('/api/flights/track');
// Re-selecting one aircraft, and a burst of malformed requests: more than a
// window's worth of each, none of which costs OpenSky anything.
for (let i = 0; i < 40; i += 1) {
const repeat = await request(track, { url: '/?icao24=73c000' });
assert.equal(repeat.statusCode, 200);
const malformed = await request(track, { url: '/?icao24=nothex' });
assert.equal(malformed.statusCode, 400);
}
assert.equal(upstreamCalls, 1, 'one live call, 39 answers from the cache');
// The window still holds 29 more live calls for this client.
for (let i = 1; i < 30; i += 1) {
const icao24 = (0x73c000 + i).toString(16);
const live = await request(track, { url: `/?icao24=${icao24}` });
assert.equal(live.statusCode, 200, `live lookup ${i + 1} of 30 is allowed`);
}
const refused = await request(track, { url: '/?icao24=73cfff' });
assert.equal(refused.statusCode, 429, 'the 31st live lookup is refused');
assert.equal(upstreamCalls, 30);
});
test('the request that trips the cooldown, and repeats of it, carry the time left', async (t) => {
let upstreamCalls = 0;
stubFetch(t, async () => {
upstreamCalls += 1;
return new Response('{}', {
status: 429,
headers: { 'x-rate-limit-retry-after-seconds': '120' },
});
});
const track = install(trackBackfillProxies()).get('/api/flights/track');
for (const attempt of ['first', 'repeat']) {
const refused = await request(track, { url: '/?icao24=74d001' });
assert.equal(refused.statusCode, 429);
const retryAfter = Number(refused.headers['retry-after']);
assert.ok(
retryAfter > 60 && retryAfter <= 120,
`the ${attempt} refusal names OpenSky's cooldown (got ${retryAfter})`,
);
}
assert.equal(upstreamCalls, 1, 'the repeat was answered by the cooldown');
});
test('an error cached before the cooldown is not replayed as stale', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 1_800_000_000_000 });
let mode = 'missing';
stubFetch(t, async () =>
mode === 'missing'
? new Response('{}', { status: 404 })
: new Response('{}', {
status: 429,
headers: { 'x-rate-limit-retry-after-seconds': '600' },
}),
);
const track = install(trackBackfillProxies()).get('/api/flights/track');
assert.equal(
(await request(track, { url: '/?icao24=75e001' })).statusCode,
404,
);
t.mock.timers.tick(61_000); // the 404 has left its 60 s window
mode = 'cooling';
assert.equal(
(await request(track, { url: '/?icao24=75e002' })).statusCode,
429,
);
const later = await request(track, { url: '/?icao24=75e001' });
assert.equal(
later.statusCode,
429,
'the old 404 is not served as if it were current',
);
assert.ok(Number(later.headers['retry-after']) > 60);
});
test('a /states/all 429 does not block track backfill: separate OpenSky buckets', async (t) => {
let trackUpstreamCalls = 0;
stubFetch(t, async (url) => {
if (String(url).includes('states/all')) {
return new Response('{}', {
status: 429,
headers: { 'x-rate-limit-retry-after-seconds': '120' },
});
}
trackUpstreamCalls += 1;
return trackOk();
});
const states = install(openSkyProxy()).get('/api/flights');
await request(states, { url: '/' });
const track = install(trackBackfillProxies()).get('/api/flights/track');
const backfill = await request(track, { url: '/?icao24=7a1b2c' });
assert.equal(
backfill.statusCode,
200,
'the /tracks bucket still has credits, so the trail is fetched',
);
assert.equal(trackUpstreamCalls, 1);
});
-3
View File
@@ -1,11 +1,8 @@
import { createApplicationControls } from '../app/controls.js';
import { getStandaloneCatalog } from './catalog.js';
import { homeCountryView } from '../homeCountry.js';
export function createStandaloneControls(options) {
return createApplicationControls({
catalog: options?.catalog ?? getStandaloneCatalog(),
// The planet over the visitor's country; the title's logo goes back here.
startView: homeCountryView(),
...options,
});
}
-2
View File
@@ -1,10 +1,8 @@
import { startApplicationChrome } from '../app/startupChrome.js';
import { playOpeningIntro } from '../app/openingIntro.js';
import { initKeySetup } from '../keySetup.js';
export function startStandaloneChrome(options) {
return startApplicationChrome({
initializeSettings: initKeySetup,
playOpening: playOpeningIntro,
...options,
});
}
+1 -60
View File
@@ -10,7 +10,7 @@ const source = readFileSync(
.replace(/^import .*;\n/gm, '')
.replace('export function', 'function');
function fixture({ playOpening, hasShareState = false } = {}) {
function fixture() {
const timers = new Map();
const listeners = new Map();
const events = [];
@@ -44,10 +44,7 @@ function fixture({ playOpening, hasShareState = false } = {}) {
addEventListener: (type, listener) => listeners.set(type, listener),
removeEventListener: (type) => listeners.delete(type),
},
playOpening,
styleManager: {
hasShareState,
viewer: 'viewer',
initialRestorePromise: new Promise((resolve) => {
restored = resolve;
}),
@@ -127,59 +124,3 @@ test('shutdown during the cover transition cancels the listener and fallback', a
f.fire(900);
assert.deepEqual(f.events, ['hidden', 'settings:destroy']);
});
function openingStub(events) {
let land;
const calls = [];
const play = (options) => {
calls.push(options);
events.push('opening');
return {
done: new Promise((resolve) => {
land = resolve;
}),
cancel: () => events.push('opening:cancel'),
};
};
return { play, calls, land: () => land() };
}
test('a bare address plays the opening, and welcome waits for its end', async () => {
const events = [];
const opening = openingStub(events);
const f = fixture({ playOpening: opening.play });
f.events.push = (value) => events.push(value);
f.restored();
f.fire(1000);
await flush();
assert.deepEqual(events, ['opening']);
assert.equal(opening.calls[0].viewer, 'viewer');
f.fire(900);
assert.deepEqual(events, ['opening'], 'no fallback timer while it plays');
opening.land();
await flush();
assert.deepEqual(events, ['opening', 'welcome']);
await f.stop();
assert.ok(events.includes('opening:cancel'));
});
test('a shared view opens without the opening', async () => {
const events = [];
const opening = openingStub(events);
const f = fixture({ playOpening: opening.play, hasShareState: true });
f.restored();
f.fire(1000);
await flush();
assert.equal(opening.calls.length, 0);
assert.deepEqual(f.events, ['hidden']);
await f.stop();
});
test('without an opening to play the cover hides as before', async () => {
const f = fixture({ playOpening: () => null });
f.restored();
f.fire(1000);
await flush();
assert.deepEqual(f.events, ['hidden']);
await f.stop();
});
+5 -7
View File
@@ -31,6 +31,11 @@ export const getRecentImagery = defineTool({
requires: ['imagery'],
async run(args, { services, signal }) {
const area = await resolveArea(args.area, { services, signal });
if (area.west > area.east)
throw new ToolError(
'invalid_arguments',
'The area must not cross the antimeridian',
);
if (
Math.abs(area.south) > MAX_LATITUDE ||
Math.abs(area.north) > MAX_LATITUDE
@@ -50,13 +55,6 @@ export const getRecentImagery = defineTool({
east: area.east,
north: area.north,
};
// Worldview Snapshots rejects a west > east BBOX, so a dateline area can
// never produce the image this tool returns: refuse before searching.
if (box.west > box.east)
throw new ToolError(
'invalid_arguments',
'The area must not cross the antimeridian',
);
let latest;
try {
latest = await services.imagery.latest({ box, signal });
+1 -23
View File
@@ -82,30 +82,8 @@ test('overview fallback, empty results and invalid areas are reported', async ()
);
await assert.rejects(
none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }),
/too large for imagery/,
/antimeridian/,
);
const crossing = imagery({
candidate: {
product: 'S30',
day: '2026-10-01',
cloud: { min: 1, max: 2 },
coverage: 'full',
},
reason: 'clear',
errors: [],
});
const wrapped = composeCatalog({
tools: coreTools,
services: { imagery: crossing },
});
await assert.rejects(
wrapped.call('get_recent_imagery', {
area: { bbox: [179, 0, -179, 1] },
}),
/must not cross the antimeridian/,
);
assert.equal(crossing.snapshots.length, 0);
assert.equal(crossing.boxes.length, 0);
await assert.rejects(
none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }),
/±85° latitude/,
+4 -11
View File
@@ -48,20 +48,13 @@ export function initImageryBoxTool({
let lease = null;
let releaseCamera = null;
const dragBox = () => {
if (!anchor) return null;
const lo = Math.min(anchor.lon, corner.lon);
const hi = Math.max(anchor.lon, corner.lon);
// Corners more than half the globe apart are the short way round, over
// the dateline: west gets the larger longitude, east the smaller.
const crosses = hi - lo > 180;
return {
west: crosses ? hi : lo,
const dragBox = () =>
anchor && {
west: Math.min(anchor.lon, corner.lon),
south: Math.min(anchor.lat, corner.lat),
east: crosses ? lo : hi,
east: Math.max(anchor.lon, corner.lon),
north: Math.max(anchor.lat, corner.lat),
};
};
const preview = createPreview(viewer, dragBox);
const setPreview = (visible) => preview.setVisible(visible);
-38
View File
@@ -10,7 +10,6 @@ import {
IMAGERY_BOX_POINTER_OWNER,
initImageryBoxTool,
} from './imageryBoxTool.js';
import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js';
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
@@ -210,40 +209,3 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
assert.equal(f.tool.start(), false);
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
});
test('a drag across the dateline is the short box, not a box round the world', async () => {
const pickWorld = (_viewer, nx, ny) =>
ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny };
const f = fixture({ pickWorld });
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
assert.deepEqual(f.cancels, []);
assert.equal(f.boxes.length, 1);
const { west, east } = f.boxes[0];
assert.ok(west > east, `west ${west} is east of east ${east}`);
assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span');
await f.tool.destroy();
});
test('a drag whose short arc is still over the size limit is refused as too large', async () => {
const pickWorld = (_viewer, nx, ny) => ({
lon: nx < 0.5 ? 100 : -100,
lat: ny,
});
const refused = [];
const f = fixture({
pickWorld,
onCancel: (reason, message, box) => refused.push({ reason, message, box }),
});
f.tool.start();
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
assert.equal(f.boxes.length, 0);
const { reason, message, box } = refused.at(-1);
assert.equal(reason, 'too-large');
assert.deepEqual([box.west, box.east], [100, -100], 'the short arc');
assert.equal(lonSpanDeg(box.west, box.east), 160);
assert.equal(message, validateBox(box).message);
await f.tool.destroy();
});
+5 -27
View File
@@ -22,7 +22,6 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
import {
PRODUCTS,
hhmm,
nonCrossingBoxes,
wvsSnapshotUrl,
} from '../layers/recentImagery/model.js';
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
@@ -136,20 +135,6 @@ function coverageText(coverage) {
return t('unknown');
}
/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */
function shownCoverage(candidate, box) {
const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {};
const halves = nonCrossingBoxes(box).length;
if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial';
if (
status !== 'present' ||
!Array.isArray(availableBoxes) ||
availableBoxes.length >= halves
)
return candidate.coverage;
return 'unknown';
}
function cloudText(candidate) {
if (candidate.thumbnail?.status === 'empty') return t('no imagery');
if (!candidate.cloud) return t('cloud unknown');
@@ -531,9 +516,6 @@ export function createRecentImageryPanel({
function exportsView() {
const ab = snapshot.mode === 'ab';
const crossing = Boolean(
snapshot.box && snapshot.box.west > snapshot.box.east,
);
return [
{
id: 'export',
@@ -543,12 +525,10 @@ export function createRecentImageryPanel({
label: ab
? t('EXPORT {slot}', { slot: slotId.toUpperCase() })
: t('EXPORT'),
title: crossing
? t('Select one side of the dateline')
: ab
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
: t('Download the image as a PNG'),
disabled: crossing || !exportTarget(slotId) || exporting.has(slotId),
title: ab
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
: t('Download the image as a PNG'),
disabled: !exportTarget(slotId) || exporting.has(slotId),
reserved: slotId === 'b' ? !ab : undefined,
onClick: () => void exportImage(slotId),
})),
@@ -586,9 +566,7 @@ export function createRecentImageryPanel({
}),
);
times.push(
t('Coverage {coverage}', {
coverage: coverageText(shownCoverage(focus, snapshot.box)),
}),
t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }),
);
lines.push({ id: 'acquired', text: times.join(' · ') });
(focus.granules || []).forEach((granule, index) => {
-50
View File
@@ -5,11 +5,9 @@ import assert from 'node:assert/strict';
import { assertSameNode } from '../testSupport/domAssert.mjs';
import { readFileSync } from 'node:fs';
import { createRecentImageryPanel } from './recentImagery.js';
import { nonCrossingBoxes } from '../layers/recentImagery/model.js';
import { createRecentImageryLayer } from '../layers/recentImagery/index.js';
import {
BOX,
FIJI_BOX,
fakeCatalog,
fakeController,
fakeRenderer,
@@ -979,29 +977,6 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX
await settle();
assert.equal(await f.readout.exportImage('a'), true);
assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/);
// A dateline box is drawn on the map, but Worldview rejects a crossing BBOX.
const before = f.fetches.length;
f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 });
f.catalog.resolveLast();
await settle();
assert.notEqual(
f.byId('ri-notice-text').textContent,
'Select one side of the dateline',
'the drawn box is not a warning until an export is tried',
);
const crossingExport = f.byAction('export-a');
assert.equal(crossingExport.disabled, true, 'EXPORT is off up front');
assert.equal(crossingExport.title, 'Select one side of the dateline');
assert.equal(await f.readout.exportImage('a'), false);
assert.equal(
f.byId('ri-notice-text').textContent,
'Export failed · A snapshot cannot cross the dateline',
);
assert.equal(
f.fetches.length,
before,
'export does not request a crossing BBOX',
);
f.layer.setMode('ab');
assert.deepEqual(
[
@@ -1065,31 +1040,6 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to
assert.equal(article.dataset.open, 'false');
});
test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => {
const f = fixture();
f.layer.enable();
f.layer.setBox(FIJI_BOX);
f.catalog.resolveLast();
await settle();
assert.match(f.byId('ri-details').textContent, /Coverage full/);
const get = f.thumbnails.get;
const [west, east] = nonCrossingBoxes(FIJI_BOX);
f.thumbnails.get = (key) => ({
...get(key),
availableBoxes: [west],
emptyBoxes: [east],
});
f.thumbnails.probe(f.snap().focus.key, 'present');
assert.match(f.byId('ri-details').textContent, /Coverage partial/);
f.thumbnails.get = (key) => ({
...get(key),
availableBoxes: [west],
emptyBoxes: [],
});
f.thumbnails.probe(f.snap().focus.key, 'present');
assert.match(f.byId('ri-details').textContent, /Coverage unknown/);
});
test('the body scroll position survives renders even when DOM mutations reset it', async () => {
const f = fixture();
await f.ready();
+6 -13
View File
@@ -13,11 +13,11 @@ const REFUSALS = [
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
'That point cannot anchor a box', // layers/recentImagery/index.js
...[
{ west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap
{ west: 10, south: 80, east: 20, north: 89 },
{ west: 10, south: 10, east: 10, north: 20 },
{ west: 10, south: 10, east: 200, north: 20 },
{ west: Number.NaN, south: 10, east: 20, north: 20 },
{ west: 170, south: 10, east: -170, north: 20 }, // dateline
{ west: 10, south: 80, east: 20, north: 89 }, // polar
{ west: 10, south: 10, east: 10, north: 20 }, // degenerate
{ west: 10, south: 10, east: 200, north: 20 }, // longitude range
{ west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite
].map((box) => {
const result = validateBox(box);
assert.equal(result.ok, false);
@@ -27,14 +27,7 @@ const REFUSALS = [
test('en: refusals stay English', () => {
setLocale('en');
for (const text of REFUSALS) {
const shown = localizeNotice(text);
// Size refusals are rewritten with a non-breaking space before the unit.
const expected = / km wide/.test(text)
? text.replaceAll(' km', '\u00a0km')
: text;
assert.equal(shown, expected);
}
for (const text of REFUSALS) assert.equal(localizeNotice(text), text);
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
});
-29
View File
@@ -431,35 +431,6 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
}
}
/* The opening (src/app/openingIntro.js) sets these each frame. */
#loading-screen.opening {
background: color-mix(
in srgb,
var(--bg-dark) calc(var(--opening-veil, 1) * 100%),
transparent
);
}
#loading-screen.opening .loader-logo {
animation: none;
will-change: transform;
}
#loading-screen.opening .loader-logo svg {
overflow: visible;
}
#loading-screen.opening .loader-logo svg > path {
transform-box: fill-box;
transform-origin: center;
}
#loading-screen.opening h2,
#loading-screen.opening .loader-status {
animation: none;
opacity: var(--opening-text, 1);
}
.loader-content h2 {
font-family: var(--font-mono);
font-size: 18px;
+11 -11
View File
@@ -17,12 +17,7 @@
* @module voice/imageryActions
*/
import {
PRODUCTS,
boxCentre,
boxSideKm,
rankLatest,
} from '../layers/recentImagery/model.js';
import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js';
import {
displacedLayerResult,
watchExplicitLayerOff,
@@ -208,14 +203,19 @@ export async function findImagery(
`No area "${args.areaId}" on this page — call resolve_area again.`,
);
const [west, south, east, north] = record.bbox;
if (west > east)
return fail(
'DATELINE',
`${record.name} crosses the date line; the imagery box needs one side of it.`,
);
// 30 m pixels over a landmark-sized area show a handful of blobs: a small
// area gets the layer's own 10 km box around its centre instead.
// west > east is the short arc across the date line. The layer's helpers
// measure and centre it.
const { width, height } = boxSideKm({ west, south, east, north });
const small = width < 5 && height < 5;
const small =
(north - south) * 111 < 5 &&
(east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) <
5;
box = small
? { pin: boxCentre({ west, south, east, north }) }
? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } }
: { west, south, east, north };
areaName = record.name;
} else if (where === 'point') {
+4 -27
View File
@@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their
assert.equal(unknown.code, 'AREA_UNKNOWN');
});
test('a mixed antimeridian area is searched as its short-arc box', async () => {
test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => {
const square = (w, s, e, n) => [
[w, s],
[e, s],
@@ -251,7 +251,6 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
[178, 1],
[178, 0],
];
const layer = fakeLayer();
const store = createAreaStore();
const area = store.put({
geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]],
@@ -259,33 +258,11 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
source: 'osm',
});
assert.deepEqual(area.bbox, [178, 0, -174, 1]);
const result = await findImagery(deps(layer, { area }).value, {
const result = await findImagery(deps(fakeLayer(), { area }).value, {
areaId: area.areaId,
});
assert.equal(result.ok, true, 'the guard is lifted');
assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], {
west: 178,
south: 0,
east: -174,
north: 1,
});
});
test('a small area across the date line is pinned at its short-arc centre', async () => {
const layer = fakeLayer();
await findImagery(
deps(layer, {
area: {
areaId: 'd',
name: 'Dateline Islet',
bbox: [179.998, 0, -179.998, 0.01],
},
}).value,
{ areaId: 'd' },
);
const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt');
assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`);
assert.equal(lat, 0.005);
assert.equal(result.ok, false);
assert.equal(result.code, 'DATELINE');
});
test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => {