mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-22 19:22:18 +00:00
Merge branch 'main' into sameh/photo-without-credit
This commit is contained in:
110 files changed
+18080
-148
No files matched your search
@@ -325,3 +325,30 @@ GEMINI_CHAT_MODEL=gemini-3.5-flash-lite
|
||||
# Each reserves up to 40 stations within the existing 750-station directory.
|
||||
# Restart after changing. Leave blank for the existing global selection.
|
||||
# RADIO_PRIORITY_COUNTRIES=IN,PL
|
||||
|
||||
# Optional: a news server for the News layer (its /api/news/hotspots, /feed
|
||||
# and /outline routes), such as https://news.example. The local server
|
||||
# forwards only the layer's own GET requests there, with a 15 s timeout. Set,
|
||||
# it wins over the settings below. SERVER-SIDE ONLY.
|
||||
# GEV_NEWS_ORIGIN=
|
||||
#
|
||||
# Without a news server Core reads the News layer itself. SERVER-SIDE ONLY.
|
||||
# Conflicts need no key: the last 24 h of GDELT events (its 15-minute export
|
||||
# files, about 100 KB each, about 10 MB a day; violence only, one report per
|
||||
# story at GDELT's place for it), titled from GDELT's GKG files (about 6 MB
|
||||
# each, about 23 MB an hour: the newest 3 h are read at start, then each new
|
||||
# one). Optional: Liveuamap's mapped reports beside them (paid API,
|
||||
# https://liveuamap.com/promo/api), read once every 5 minutes.
|
||||
# LIVEUAMAP_API_KEY=
|
||||
# Local: the day's news from the outlets of the country in view (free plan
|
||||
# of 50 points a day, https://worldnewsapi.com/console/), read once per
|
||||
# country every 30 minutes, about 1.5 points a read. Without it Local says
|
||||
# "key required". Each country's news is kept in memory for at most 1 hour.
|
||||
# World News API's terms (https://worldnewsapi.com/terms/) allow caching
|
||||
# only with its prior written permission: get that before setting the key.
|
||||
# The app's Data attribution popover credits World News API with a link.
|
||||
# WORLDNEWSAPI_KEY=
|
||||
# The most World News API reads a day (default 30, about 45 points, inside
|
||||
# the free plan). After that Local says the daily limit is reached.
|
||||
# Raise it on a paid plan.
|
||||
# WORLDNEWSAPI_DAILY_READS=30
|
||||
@@ -40,6 +40,12 @@ How to read this:
|
||||
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
|
||||
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
|
||||
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
|
||||
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
|
||||
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
|
||||
| **Liveuamap** (`a.liveuamap.com/api`, `LIVEUAMAP_API_KEY`, optional, paid; used only without a news server) | News layer, Conflicts, beside GDELT: Liveuamap's worldwide mapped items of the last 24 h (`a=mpts`), read server-side every 5 minutes; categories and severity are read from the headline by bundled rules | Liveuamap API terms of the operator's own subscription. Headlines, places and links only; item pictures and clips are hotlinked from Liveuamap, never stored | "Liveuamap" with a link in the Data attribution popover once its items show; "Liveuamap" and the item's Liveuamap link on every card |
|
||||
| **World News API** (`api.worldnewsapi.com/search-news`, `WORLDNEWSAPI_KEY`, optional; used only without a news server) | News layer, Local: the last 24 h of news by the source country at the view centre (country from the bundled Natural Earth admin-0 pack; none in a disputed area), read server-side once per country every 30 minutes, about 1.5 points a read, kept in memory for at most 1 hour and then deleted (a read that fails is served from that copy only within the hour); at most `WORLDNEWSAPI_DAILY_READS` reads a day (default 30), after which Local says the daily limit is reached. Each story keeps World News API's own category (politics, business, else other) with no severity of its own; sport, entertainment, lifestyle and travel left out | [World News API terms](https://worldnewsapi.com/terms/) of the operator's own plan. The terms allow caching only with World News API's prior written permission, and then for at most 1 hour: getting that permission before setting the key is the operator's responsibility. Titles and links only; article text and summaries are not kept or shown; pictures are hotlinked from the publisher | The "World News API" link to worldnewsapi.com, always in the Data attribution popover (a credit; the terms require a backlink only of invited free plans); "via World News API", the publisher's domain and the article link on every card |
|
||||
| **EMODnet Human Activities — Ship wrecks** (`ows.emodnet-humanactivities.eu/wfs`, layer `emodnet:heritageshipwrecks`) | Shipwrecks layer: about 7,000 wrecks in European waters (name, sinking year and text, vessel type, least depth and its quality, position accuracy, period, cargo, protected status). Keyless WFS GeoJSON, fetched by `/api/shipwrecks` once a day; rows sourced from wrecksite.eu are skipped, and free text that refers to a person by a title or role is dropped by a keyword filter (a bare name can still pass) | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) (EMODnet catalogue record `e965088b-a265-4517-84df-c49b156af8a7`; data originator AND-International, compiled from SHOM, National Monuments Service, Historic England and the Oxford Roman Economy Project); fetched at runtime, not stored in this repository | "Shipwrecks (Europe): EMODnet Human Activities (data originator AND-International, …), CC BY 4.0" — shown in-app |
|
||||
| **Wikidata — shipwrecks** (`query.wikidata.org/sparql`) | Shipwrecks layer: shipwreck items (Q852190) with a coordinate and at least one Wikipedia article, plus sinking events (Q906512, where the death toll lives): name, ship type, sinking date with its precision, deaths and survivors (counts only), description and article link. Keyless, fetched by `/api/shipwrecks` once a day | [CC0](https://creativecommons.org/publicdomain/zero/1.0/); fetched at runtime | "Shipwrecks (worldwide): Wikidata (CC0)" — shown in-app |
|
||||
| **InciWeb** (inciweb.wildfire.gov) | Per-incident "InciWeb ↗" card links to official incident pages (narratives, evacuation/closure notices) | U.S. government public incident information. Links are matched best-effort by incident name and state, with incident page origin and update times checked on selection. Same-origin `/api/fire-perimeters/inciweb` routes cache the catalog for 1 hour and publication metadata for 30 minutes; linked pages remain InciWeb content | "Incident information: InciWeb (inciweb.wildfire.gov)" |
|
||||
| **FAA Special Use Airspace** (`services6.arcgis.com` FeatureServer `Special_Use_Airspace`) | Prohibited & Restricted Airspace layer: US prohibited (P) and restricted (R) special-use airspace polygons (not the UAS Facility Map or UAS flight restrictions), altitude limits from the `*_VAL`/`*_UOM`/`*_CODE` fields, times of use, and controlling agency | U.S. public domain (FAA aeronautical data published through the [FAA AIS Open Data portal](https://adds-faa.opendata.arcgis.com/)); fetched keyless through `/api/drone-airspace` (1-hour server cache). Informational only — not a substitute for official UAS flight-planning tools | "Prohibited & restricted airspace: FAA Special Use Airspace" |
|
||||
| **iNaturalist API** (`api.inaturalist.org/v2/observations`, `/v1/grid/{z}/{x}/{y}.grid.json`) | Wildlife Sightings layer: verifiable wildlife observed within the last 48 h (whales 7 d), by observation time, in the current view, with taxon, observation time, quality grade and eligible photo | Per-record licences; observations default CC BY-NC. Photos CC0/BY/BY-SA/BY-NC/BY-NC-SA shown; ND and all-rights-reserved photos link-only. Keyless via `/api/inaturalist/observations` (5-min cache; global sample 10 min; stale ≤ 1 h; 60 requests/min and 8,000/day upstream caps). **NonCommercial content:** commercial redistributors must filter to CC0/BY/BY-SA or remove the layer. No AI training on this content | "Wildlife sightings: iNaturalist contributors (licences per record; photos credited on each card)" |
|
||||
@@ -270,6 +276,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p
|
||||
| **Natural Earth physical regions** (1,046 land + 292 marine named polygons) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **DataSF Analysis Neighborhoods** (41 SF neighborhood polygons) | `neighborhoods/` | **PDDL 1.0** (public domain) | ✅ (no restrictions) | "City & County of San Francisco — DataSF" (courtesy — not legally required) |
|
||||
| **Natural Earth countries, states and provinces** (260 admin-0/map units + 4,587 admin-1 polygons) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Natural Earth disputed areas** (11 of the source's 99 features, hand-picked; [list](src/data/local_data/natural_earth/README.md#disputed-areas-disputed_areasjson)) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **Natural Earth populated places** (7,342 points: name, position, rank) | `natural_earth/` | **Public domain** | ✅ (no restrictions) | "Made with Natural Earth" (courtesy credit — not legally required) |
|
||||
| **US Census Bureau counties** (3,235 county polygons) | `us_census_counties/` | **Public domain** | ✅ (no restrictions) | "U.S. Census Bureau" (courtesy — not legally required) |
|
||||
| **US Census Bureau places** (32,629 city, town and CDP polygons) | `us_census_places/` | **Public domain** | ✅ (no restrictions) | "U.S. Census Bureau" (courtesy — not legally required) |
|
||||
|
||||
@@ -212,7 +212,7 @@ Keep the `env`: bash treats `UID` as read-only, so a plain `UID=1026` in front o
|
||||
|
||||
On SELinux hosts (Fedora, RHEL), compose mounts the checkout with `:z` so the container may read it; Docker may relabel the checkout for container access, which can take a moment on a large checkout. Without that, the start fails with `Cannot find module '/app/scripts/docker-start.mjs'`.
|
||||
|
||||
Behind a reverse proxy, put your keys in `.env` or pass them as environment variables - Provider Settings refuses proxied requests on purpose - and add the hostname you serve it on, for example `GEV_ALLOWED_HOSTS=globe.example.lan` (see [Sharing an instance](#-sharing-an-instance)). The map routes compare the browser's `Origin` with the `Host` the server sees, so the proxy must pass the original `Host` and, when it terminates TLS, `X-Forwarded-Proto`. Caddy does both by default; for nginx add `proxy_set_header Host $http_host;`, `proxy_set_header X-Forwarded-Proto $scheme;` and `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`. On an install outside Docker, that forwarding header also rate-limits the proxy's users apart from your own browser. Under the default Docker bridge network every client on the host, your browser included, reaches the container from its gateway address and shares one Overpass bucket.
|
||||
Behind a reverse proxy, put your keys in `.env` or pass them as environment variables - Provider Settings and the News layer refuse proxied requests on purpose - and add the hostname you serve it on, for example `GEV_ALLOWED_HOSTS=globe.example.lan` (see [Sharing an instance](#-sharing-an-instance)). The map routes compare the browser's `Origin` with the `Host` the server sees, so the proxy must pass the original `Host` and, when it terminates TLS, `X-Forwarded-Proto`. Caddy does both by default; for nginx add `proxy_set_header Host $http_host;`, `proxy_set_header X-Forwarded-Proto $scheme;` and `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`. On an install outside Docker, that forwarding header also rate-limits the proxy's users apart from your own browser. Under the default Docker bridge network every client on the host, your browser included, reaches the container from its gateway address and shares one Overpass bucket.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -236,8 +236,8 @@ the container.
|
||||
|
||||
### Path 4 — GitHub Codespaces (cloud, no local install)
|
||||
|
||||
Codespaces requires a GitHub account. Overpass queries and OpenAI voice token
|
||||
requests return HTTP 403 through its forwarded HTTPS URL, even with API keys
|
||||
Codespaces requires a GitHub account. Overpass queries, the News layer and OpenAI
|
||||
voice token requests return HTTP 403 through its forwarded HTTPS URL, even with API keys
|
||||
in `.env` and `GEV_ALLOWED_HOSTS` configured. Use a local setup for these features.
|
||||
|
||||
The codespace runs the dev server in a cloud workspace, so Node and the dependencies
|
||||
@@ -426,7 +426,7 @@ _Ask for radio near anywhere and the globe starts broadcasting — every station
|
||||
|
||||
## 🛰️ What's on the Globe
|
||||
|
||||
Twenty-two layers and map sources. **Twenty have a keyless path.** Some offer additional capabilities with a provider key. (🟢 no key · 🟡 free key · 🔴 metered.)
|
||||
Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some offer additional capabilities with a provider key. (🟢 no key · 🟡 free key · 🔴 metered.)
|
||||
|
||||
| Layer | What you get | Source | Auth |
|
||||
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- |
|
||||
@@ -438,6 +438,7 @@ Twenty-two layers and map sources. **Twenty have a keyless path.** Some offer ad
|
||||
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
|
||||
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
|
||||
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
|
||||
| 📰 **News** | The last 24 hours of news in the right-rail **NEWS** panel, narrowed to 12, 6, 3 or 1 hours, with picture cards and clips. **Conflicts**: physical violence worldwide from GDELT's event files, one report per story at GDELT's place for it, plus Liveuamap's mapped items with a key. **Local**: the news of the country at the view centre, its outline and name on the globe; a disputed area of the bundled list, or a territory without a country code, is named as itself. Places and categories are machine-coded and can be wrong | GDELT · Liveuamap · World News API, or your own news server | 🟢 Conflicts · 🟡 Local (World News API) · 🔴 Liveuamap items |
|
||||
| ◍ **Air quality** | Live AQHI on the published 1–10+ health-risk scale, with a Weather-panel card showing the band legend and the highest readings in view. **Canada only** — ECCC is the first registered provider | ECCC MSC GeoMet | 🟢 |
|
||||
| 🚗 **Traffic** | Simulated vehicles on OSM roads. With TomTom, live flow speeds drive the simulation and congestion colors below ~8 km; individual vehicle positions are not live observations | TomTom + OSM | 🟢 simulation · 🟡 live flow speeds |
|
||||
| 📹 **CCTV Mesh** | up to 7,350 camera locations (4,000 shared round-robin slots, plus room for 1,120 Québec and 2,230 World image cameras) projected _into_ the 3D space — Austin · Texas (TxDOT) · California (Caltrans) · London (TfL) · Ontario (511, free developer key) · Ottawa (City of Ottawa, free access certificate) · Finland (Fintraffic) · British Columbia (DriveBC) · Estonia (Tallinn, Tarktee) · Delaware (DelDOT live video) · New South Wales (Live Traffic NSW) · Calgary · Norway (Statens vegvesen) · Toronto · King County (WA) · Washington (WSDOT) · Catalonia (Servei Català de Trànsit) · Iceland (Vegagerðin) · Hong Kong (Transport Department) · Taiwan (Freeway Bureau, MOTC) · Québec (MTQ locations with Québec 511 links, Montréal locations, regional webcams) · Oregon (TripCheck) · Japan (MLIT river cameras) · Italy (A22 Brennero motorway), plus opt-in New York City (NYC DOT TMC, needs your own NYC DOT agreement), opt-in Lithuania (Via Lietuva / Eismoinfo, photo licence unconfirmed), opt-in Québec 511 in-browser video (embedding terms unconfirmed), opt-in Florida (FL511, individual personal use only; other use needs FDOT's written consent) and opt-in Houston (TranStar, enable only with TxDOT's written permission per TranStar's Content Usage terms). Positions are published or attributed; poses are estimated priors **you calibrate by dragging a gizmo on the camera itself** | City APIs | 🟢 |
|
||||
@@ -567,12 +568,14 @@ and configuration details.
|
||||
|
||||
No key needed for Wind, Rain radar, Satellite clouds, Lightning density,
|
||||
Cyclone advisories, Mapped ALPR Cameras, Transit, Directions, Delaware live
|
||||
video, and coordinate or bundled-place search. A layer row waiting on a key
|
||||
video, the News layer's Conflicts section, and coordinate or bundled-place
|
||||
search. A layer row waiting on a key
|
||||
names it.
|
||||
|
||||
### Choose the capabilities you want
|
||||
|
||||
Seven keys. Five have a free tier, and the two 🔴 ones are metered:
|
||||
Nine keys. Six have a free tier. Of the three 🔴 ones, Google Maps and OpenAI are
|
||||
metered and Liveuamap is a paid subscription:
|
||||
|
||||
| | Key | Why | Get it |
|
||||
| --- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
@@ -583,6 +586,8 @@ Seven keys. Five have a free tier, and the two 🔴 ones are metered:
|
||||
| 🟡 | **NASA FIRMS** | 🔥 Live active fires | [firms.modaps.eosdis.nasa.gov](https://firms.modaps.eosdis.nasa.gov/api/map_key/) — free |
|
||||
| 🟡 | **TomTom** | 🚦 Live flow speeds and congestion colors for the simulated traffic layer | [my.tomtom.com](https://my.tomtom.com/keys) — free tier available |
|
||||
| 🟡 | **Mapillary** | 📷 Street Level coverage and photos. A public client token by design (see SECURITY.md) | [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers) — register an app, copy its Client Token |
|
||||
| 🟡 | **World News API** | 📰 News layer, Local: the news of the country in view. The free plan allows 50 points a day; `WORLDNEWSAPI_DAILY_READS` (default 30) keeps Core inside it. Core keeps each country's news for up to 1 hour, and World News API's [terms](https://worldnewsapi.com/terms/) allow caching only with its prior written permission, which is yours to get. The Data attribution popover credits it with a link | [worldnewsapi.com/console](https://worldnewsapi.com/console/) — free plan |
|
||||
| 🔴 | **Liveuamap** | 📰 News layer, Conflicts: Liveuamap's mapped items beside GDELT's reports (🟢 Conflicts works without) | [liveuamap.com/promo/api](https://liveuamap.com/promo/api) — paid API |
|
||||
|
||||

|
||||
|
||||
@@ -656,8 +661,8 @@ Honest numbers, roughly, as of mid-2026 — always check the provider pricing pa
|
||||
|
||||
| | Cost reality |
|
||||
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **🟢 Most layers** | **$0, no signup.** OpenSky anon, USGS, CelesTrak, adsb.lol, city CCTV, Radio Browser, GBFS, Launch Library 2, transit feeds, OSRM routing, NOAA and ECMWF weather, OpenStreetMap ALPR mapping, bundled datasets. |
|
||||
| **🟡 The free-key tier** | **$0 with a signup.** AISStream, FIRMS, TomTom, OpenSky, plus Cesium ion for eligible personal/non-commercial use. Provider quotas and eligibility still apply. |
|
||||
| **🟢 Most layers** | **$0, no signup.** OpenSky anon, USGS, CelesTrak, adsb.lol, city CCTV, Radio Browser, GBFS, Launch Library 2, transit feeds, OSRM routing, NOAA and ECMWF weather, OpenStreetMap ALPR mapping, GDELT news events, bundled datasets. |
|
||||
| **🟡 The free-key tier** | **$0 with a signup.** AISStream, FIRMS, TomTom, OpenSky, World News API, plus Cesium ion for eligible personal/non-commercial use. Provider quotas and eligibility still apply. |
|
||||
| **🗺️ Google 3D tiles** | **Free through an eligible Cesium ion Community account within its quota; metered through a direct Google key.** Use the direct route for Google place search or commercial deployment, verify current provider terms, and set budget alerts where billing is enabled. |
|
||||
| **🔴 OpenAI voice** | API-key sessions keep the live spend readout, STD/MINI model toggle, $2 warning, and **$5 hard cap**. ChatGPT OAuth is an explicit choice in Provider Settings. Its usage is tracked without an API-dollar estimate or spend cap. The voice context window stays deliberately short. |
|
||||
|
||||
|
||||
+1
-1
@@ -82,7 +82,7 @@ The data proxies under `server/providers/` are written so the browser cannot tur
|
||||
- **Sanitized errors** — internal error details are not echoed back to clients.
|
||||
- **Coalesced OAuth refresh** and cached successful responses only (OpenSky).
|
||||
- **Redacted debug logging.** The voice debug log (`.gev-logs/`, gitignored) strips API keys, bearer tokens, client secrets, and image data URLs before writing.
|
||||
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, and `/api/tomtom/*`, backed by its persistent daily tile budget) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control. The keyless map routes (`/api/terrain/heights`, `/api/drone-airspace`, `/api/inaturalist/observations`, `/api/acartia/sightings`, `/api/overpass` and voice place search's `/api/osm/features`, which spends the same operator Overpass) use the same cross-site checks, minus the forwarding-header refusal: they guard only per-client quotas and caches, not a key or a bill, and the map and voice need them to work behind a reverse proxy. `/api/overpass` also admits at most 300 POSTs a minute per peer (IPv6 peers keyed by /64) and 900 a minute across all remote peers before it reads a body. A direct loopback request — a loopback socket with none of the forwarding headers `hasProxySignals` checks (`Forwarded`, `Via`, `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Port`, `X-Forwarded-Proto`, `X-Real-IP`, `CF-Connecting-IP`, `CF-Ray`) — draws on its own per-peer admission window, so remote peers cannot exhaust the owner's admission. A reverse proxy on the same machine must add at least one of those headers (Caddy and Cloudflare do by default; nginx needs `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`, plus `proxy_set_header Host $http_host;` and `proxy_set_header X-Forwarded-Proto $scheme;` so the `Origin` check matches), or its traffic is indistinguishable from the owner's and shares the owner's window. With one, its requests are then counted as remote, in one bucket per proxy socket — the forwarded client address is never trusted as identity — so all users behind one proxy share 300/min. The isolation needs a loopback socket: under the default Docker bridge network every host-side client, the owner included, arrives from the container gateway and is one remote peer. **Limit:** this isolates admission only. The upstream budget (90 requests/min per client key, 300/min across all clients) is shared, so once remote traffic has used the global upstream budget, an owner request that misses the cache can still get `429`, or `503` when remote misses hold every upstream concurrency slot; cache hits are unaffected. The CCTV routes (`/api/cctv/*`) use the same keyless checks; their one key-bearing step, the Street View fallback, is skipped for any request with forwarding headers.
|
||||
- **Cross-site gate on cost/log endpoints.** The cost-bearing (`/api/realtime/token`, `/api/openai/hud-summary`, `/api/google/nearby-places`, `/api/google/text-search`), quota-bearing (`/api/mapillary/*`, with a per-IP limit on tiles, `/api/tomtom/*`, backed by its persistent daily tile budget, and `/api/news/*`, which spends the World News API daily reads, Liveuamap reads and GDELT downloads) and log (`/api/realtime/debug-log`) endpoints refuse cross-site browser requests: a foreign or opaque `Origin`, a `Sec-Fetch-Site` other than `same-origin`/`none` (this is what blocks an `<img>`/navigation that carries no `Origin`), or any reverse-proxy/CDN forwarding header returns `403`. Non-browser loopback tools (the repo QA harnesses POST the token endpoint with no `Origin`) and the explicit `HOST=0.0.0.0` LAN opt-in keep working — the gate deliberately does not require a loopback remote address; that stricter requirement belongs only to the credential panel (`admitKeySetupRequest`). The Host check (`allowedHosts`, applied by `hostCheckPlugin` ahead of every route, since Vite's own check runs only after plugin middleware) rejects a rebinding `Host` before any handler runs, in every mode, and the gate is defense in depth behind it: the LAN opt-in keeps that check and accepts only IP addresses, `localhost` and names listed in `GEV_ALLOWED_HOSTS`. **Limit:** a name you list there is trusted like the app's own address, so list only names you control. The keyless map routes (`/api/terrain/heights`, `/api/drone-airspace`, `/api/inaturalist/observations`, `/api/acartia/sightings`, `/api/overpass` and voice place search's `/api/osm/features`, which spends the same operator Overpass) use the same cross-site checks, minus the forwarding-header refusal: they guard only per-client quotas and caches, not a key or a bill, and the map and voice need them to work behind a reverse proxy. `/api/overpass` also admits at most 300 POSTs a minute per peer (IPv6 peers keyed by /64) and 900 a minute across all remote peers before it reads a body. A direct loopback request — a loopback socket with none of the forwarding headers `hasProxySignals` checks (`Forwarded`, `Via`, `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Port`, `X-Forwarded-Proto`, `X-Real-IP`, `CF-Connecting-IP`, `CF-Ray`) — draws on its own per-peer admission window, so remote peers cannot exhaust the owner's admission. A reverse proxy on the same machine must add at least one of those headers (Caddy and Cloudflare do by default; nginx needs `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`, plus `proxy_set_header Host $http_host;` and `proxy_set_header X-Forwarded-Proto $scheme;` so the `Origin` check matches), or its traffic is indistinguishable from the owner's and shares the owner's window. With one, its requests are then counted as remote, in one bucket per proxy socket — the forwarded client address is never trusted as identity — so all users behind one proxy share 300/min. The isolation needs a loopback socket: under the default Docker bridge network every host-side client, the owner included, arrives from the container gateway and is one remote peer. **Limit:** this isolates admission only. The upstream budget (90 requests/min per client key, 300/min across all clients) is shared, so once remote traffic has used the global upstream budget, an owner request that misses the cache can still get `429`, or `503` when remote misses hold every upstream concurrency slot; cache hits are unaffected. The CCTV routes (`/api/cctv/*`) use the same keyless checks; their one key-bearing step, the Street View fallback, is skipped for any request with forwarding headers.
|
||||
- **Full Content-Security-Policy.** The dev and preview servers send a real CSP (`script-src 'self' 'unsafe-eval' blob:` plus the YouTube, Facebook and X scripts the Nepal event's embedded media loads and the Maps JavaScript API that Street View runs on, with a matching `frame-src` for their players and posts: no inline script and no other script origin; `blob:` covers the object URLs Cesium's bundled workers bootstrap through in the built app), alongside the existing `X-Frame-Options: DENY` and `frame-ancestors 'none'`. `'unsafe-eval'` stays because Knockout, bundled inside Cesium's widgets package, resolves the global object with `eval` at load time and the globe does not initialize without it; styles permit `'unsafe-inline'` and Google Fonts because Vite's dev client injects `<style>` elements.
|
||||
|
||||
Allowing `maps.googleapis.com` in `script-src` also trusts its JSONP endpoints, which can bypass the script allowlist if an HTML-injection bug exists; this is an accepted limitation of loading the Maps JavaScript API, alongside the existing `'unsafe-eval'` allowance.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
- New Shipwrecks layer (Events): about 8,000 wrecks from EMODnet (CC BY 4.0)
|
||||
and Wikidata (CC0). Each has a card with deaths, date, vessel, cause, depth,
|
||||
position quality and a source link. Markers grow with the death toll, and
|
||||
a start and end year picker filters by period (IMBrandao, #1583).
|
||||
@@ -0,0 +1,29 @@
|
||||
- Add the News layer (Events ▸ News) and its right-rail NEWS panel: the last
|
||||
24 hours of news, narrowed in the panel to the last 12, 6, 3 or 1 hours with
|
||||
the hotspot counts read for that window. Markers are coloured by severity
|
||||
only, with hotspot beacons, outlines with disputed areas, picture cards for
|
||||
major events and a continuous feed whose cards fly the globe to the event.
|
||||
An open card plays the post's clip on request. The panel has two sections.
|
||||
Conflicts lists the hotspots' news. Local, below 3,000 km, lists every
|
||||
report in the area at the view centre, newest first, names and outlines that area on the
|
||||
globe, and shows those reports on the map instead while it is chosen; a
|
||||
disputed area is named as itself and read from no country's outlets. Set
|
||||
`GEV_NEWS_ORIGIN` to a news server and the local server forwards the
|
||||
layer's three read routes there. Unset, Core answers them itself:
|
||||
Conflicts from the last 24 hours of GDELT 2.0 event exports with no key
|
||||
(physical violence only, one report per story at GDELT's place for it,
|
||||
titled from GDELT's GKG files for the newest 3 hours), plus Liveuamap's
|
||||
mapped items with `LIVEUAMAP_API_KEY`; Local from World News API with
|
||||
`WORLDNEWSAPI_KEY`, at most `WORLDNEWSAPI_DAILY_READS` reads a day
|
||||
(default 30), each country's news kept for at most 1 hour. The routes
|
||||
refuse cross-site and proxied requests. A section says when its key is
|
||||
required, refused or out of its daily allowance. The Data attribution popover credits the GDELT
|
||||
Project, World News API and, once its items show, Liveuamap
|
||||
(Denis Groshev, @ZloyS, #1593).
|
||||
- Cockpit Regional News holds its list to the last 24 hours, newest first, on
|
||||
the server and in the client, and labels its four states apart: fresh
|
||||
results with no banner and a `LAST 24 H` footer, earlier results kept after
|
||||
a failed refresh near the same place as `CACHED · REFRESH FAILED`, `NO NEWS IN THE LAST 24 H`,
|
||||
and `REGIONAL NEWS UNAVAILABLE`. The banner is now really hidden over a
|
||||
populated list, and the footer no longer reverts to a static `RECENT` on a
|
||||
page change (Denis Groshev, @ZloyS, #1593).
|
||||
+61
-6
@@ -167,6 +167,49 @@ across the antimeridian, so they cannot use the strict ±180 check as-is, and
|
||||
`src/sources/adsbRecords.js` and `server/providers/common/geo.js` keep their own
|
||||
implementations.
|
||||
|
||||
## Shipwrecks — EMODnet and Wikidata
|
||||
|
||||
The Events group includes **Shipwrecks** (`shipwrecks`, share-link token `01`),
|
||||
off by default. `/api/shipwrecks` downloads EMODnet Human Activities'
|
||||
`emodnet:heritageshipwrecks` WFS layer (about 7,000 wrecks in European waters
|
||||
compiled from SHOM, Ireland's National Monuments Service, Historic England and
|
||||
the Oxford Roman Economy Project; CC BY 4.0) and a Wikidata SPARQL query for
|
||||
shipwreck items with a coordinate and at least one Wikipedia article (about
|
||||
1,450 worldwide; CC0). A source that answered well is asked again after 24 hours;
|
||||
one that failed is asked again after 15 minutes. Each source keeps its own last
|
||||
good records: a source that fails, answers with nothing usable, or answers with
|
||||
less than half of its last good set keeps serving its earlier records as stale
|
||||
for up to seven days, and never removes the other source's wrecks. When the
|
||||
page cannot refresh, the wrecks it shows are marked stale, and it removes them
|
||||
once even the newest source is past seven days, counted from the ages the
|
||||
proxy reported (so the page and server clocks are never compared; a wreck
|
||||
both sources list is one record, so nothing is removed per source). EMODnet rows the portal took from
|
||||
wrecksite.eu are skipped (that site is not openly licensed). A Wikidata wreck
|
||||
with the same name within 3 km of an EMODnet wreck is merged into one record
|
||||
that keeps the article link and takes EMODnet's year, sinking text, depth and
|
||||
position accuracy. Only ship columns are read: EMODnet's long histories
|
||||
(`ship_char`, `obj_desc`) are not. Sinking, cargo and description text that
|
||||
refers to a person by a title or role (Mr, captain, master, owner, crew,
|
||||
"reported by", …) is dropped whole by a keyword filter; a bare name with no
|
||||
such word can still pass. Deaths appear only as a Wikidata count.
|
||||
|
||||
The globe draws a round marker with a hull and mast per wreck, all in one
|
||||
billboard collection, ground-clamped with the depth test off and the horizon
|
||||
cull GhostMaps uses, sized by deaths (a bigger toll draws on top) and coloured
|
||||
by era (a legend under the row): before 1900 (ancient wrecks dated only by
|
||||
period count here), 1900–1945, after 1945, and date unknown. A period filter
|
||||
under the row picks a start year and an end year side by side (two pickers
|
||||
over the years that have a wreck; a reversed pair is stored swapped); undated
|
||||
wrecks show only when every year is selected. The filter is session-only (not
|
||||
in the share link). Clicking a marker opens a `stateless` card: deaths and
|
||||
survivors first, then the sinking date or year (or the archaeological dating)
|
||||
and waters, vessel type, what happened, least depth and its quality, how well
|
||||
the position is known, period notes or the Wikidata description, cargo or
|
||||
finds, protected status and source.
|
||||
Clicking the card opens the Wikipedia article (else the Wikidata item), the
|
||||
wreck's own web page when EMODnet lists one, else EMODnet's portal. Voice does
|
||||
not toggle this layer yet (prompt budget, as for the airspace layer).
|
||||
|
||||
## Wildlife Sightings — iNaturalist and Acartia
|
||||
|
||||
**Wildlife Sightings** (`wildlife-sightings`, share-link token `9`) is off by
|
||||
@@ -2494,8 +2537,9 @@ Overpass query validation, geometry simplification, disk caching and upstream
|
||||
transport now have separate modules; military-installation search reuses that
|
||||
transport. Regional briefing combines separate place, news and weather sources,
|
||||
while weather effects uses only the weather source.
|
||||
GDELT compact dates that do not name a real calendar instant keep the article
|
||||
with an unknown publication time. Existing process-scoped
|
||||
GDELT compact dates that do not name a real calendar instant normalize to an
|
||||
unknown publication time, and the 24-hour regional-news window then drops the
|
||||
article. Existing process-scoped
|
||||
caches, rate limits, stale fallbacks and route ordering are preserved.
|
||||
|
||||
Local voice has separate HUD-summary, debug-log and Realtime-token handlers,
|
||||
@@ -4714,7 +4758,7 @@ Shipped locales: **en** (source and fallback), **ar**, **de**, **es**, **fr**, *
|
||||
select `zh-Hant`. Explicit `Hans` selects `zh-CN` regardless of region. `?lang=` is not stored, and share links drop
|
||||
it, so a recipient keeps their own language. The globe picker in the
|
||||
bottom-right corner (bottom-left in Arabic and Hebrew)
|
||||
(`src/ui/localePicker.js`) stores the choice, drops
|
||||
(`src/ui/localePicker.js`) stores the choice, drops
|
||||
`?lang=` (keeps it only when storage is blocked) and switches in place:
|
||||
views re-render, code that published translated text words it again through
|
||||
`onLocaleChange`, and `<html lang>`/`dir` and the page's `data-i18n` markup
|
||||
@@ -4777,7 +4821,7 @@ requests use Play; a qualified Play-shaped tool call is normalized to Select so
|
||||
its criteria cannot be silently ignored.
|
||||
|
||||
| Layer | Source | File | Proxy | Update Interval |
|
||||
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Live Flights ✈️ | OpenSky Network; bounded adsb.lol regional fallback | `src/data/flights.js` | `/api/flights` (OAuth + fallback) | 30s |
|
||||
| Military Flights 🎖️ | adsb.lol /v2/mil | `src/data/militaryFlights.js` | `/api/military` | 15s |
|
||||
| Live AIS Vessels 🚢 | AISStream websocket | `src/data/aisLiveVessels.js` | `/api/vessels` | 60s (+800ms visibility pass) |
|
||||
@@ -4804,6 +4848,8 @@ its criteria cannot be silently ignored.
|
||||
| Ski Pistes ⛷ (`ski-pistes`) | OpenSnowMap piste raster tiles (keyless; CC BY-SA tiles, OSM data ODbL; no bulk download) | `src/data/osmOverlays.js` | — (browser-direct tiles) | on view (Cesium tile requests; no polling) |
|
||||
| Fire Perimeters 🔥 | NIFC WFIGS current interagency perimeters (keyless, paged past the 2000-record cap); InciWeb catalog + incident page origin and update time checks for verified incident-page links | `src/layers/perimeters/` via `src/app/layers/perimeters.js` | `/api/fire-perimeters` + `/api/fire-perimeters/inciweb/*` | 5 min (server caches: catalog 1 h; publication 30 min) |
|
||||
| Prohibited & Restricted Airspace 🚫 | FAA Special Use Airspace prohibited (P) and restricted (R) zones (keyless FeatureServer, simplified geometry) | `src/layers/droneAirspace/` via `src/app/layers/droneAirspace.js` | `/api/drone-airspace` | 1 h (server cache 1 h; stale-on-error) |
|
||||
| Shipwrecks ⚓ (`shipwrecks`) | EMODnet Human Activities heritage shipwrecks (European waters, keyless WFS, CC BY 4.0) and Wikidata (notable wrecks worldwide, keyless, CC0) | `src/layers/shipwrecks/` via `src/app/layers/shipwrecks.js` | `/api/shipwrecks` | 6 h page check; server refresh once a day (stale-on-error up to 7 days) |
|
||||
| News ◆ (`news`) | The last 24 h of reports in two sections, Conflicts and Local, with hotspots, outlines and disputed areas: from a news server (`GEV_NEWS_ORIGIN`), else Core's own reading of GDELT 2.0 events (no key), Liveuamap (`LIVEUAMAP_API_KEY`) and World News API (`WORLDNEWSAPI_KEY`) | `src/layers/news/` via `src/app/layers/news.js`; panel `src/ui/newsPanel.js`, `src/ui/news/`; server `server/providers/news.js`, `server/providers/news/` | `/api/news/hotspots`, `/api/news/feed`, `/api/news/outline` (forwarded to `GEV_NEWS_ORIGIN` when set, else answered by Core) | 2 min map refresh; Local re-read when the camera settles 0.8 s in a new half-degree cell below 3,000 km |
|
||||
| Wildlife Sightings 🦉 | iNaturalist wildlife observed within 48 h (whales 7 d), per view; Acartia Salish Sea marine mammal coverage (keyless) | `src/layers/wildlifeSightings/` via `src/app/layers/wildlifeSightings.js` | `/api/inaturalist/observations`, `/api/inaturalist/grid`, `/api/acartia/sightings` | camera moveEnd (600 ms debounce; enable settles 300 ms) + 5 min (observations 5 / 10 min; tiles 15 min; stale ≤ 1 h / 24 h) |
|
||||
|
||||
GNSS Integrity samples a 250 nm circle around the Earth point under the screen
|
||||
@@ -6459,6 +6505,15 @@ request viewbox and continues searching without that geographic preference.
|
||||
- Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`.
|
||||
- The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`.
|
||||
|
||||
### News (November 2026)
|
||||
|
||||
- **What it shows.** Events ▸ **News**: the last 24 hours only, or the fewer hours a server names. Zoomed out, one beacon per hotspot with its count for the window and its trend, and a breathing beacon per developing situation (still under reduced motion). Below 2,500 km (7,500 km with a hotspot chosen), the hotspot outlines with disputed areas dotted and named, and every placed report as a ground-clamped marker: fill is severity (0 grey no physical event, 1 yellow minor, 2 orange significant, 3 red major), the icon is the category, the rim is attestation (solid confirmed, dashed claim, thin single), size grows with sources and the marker fades over the day. Colour never marks a side. Up to ten picture cards (physical events with two or more sources, major or pressing) stand over their markers without overlapping. A selected report's card reads "Source: host ↗" and opens the article.
|
||||
- **Panel.** The right-rail NEWS panel (`src/ui/newsPanel.js`, `src/ui/news/`) has a time window at the top (the server's 24 h, or 12, 6, 3 or 1 h; the hotspot counts are read for the chosen window) and two sections. **Conflicts**: hotspot chips with counts, a severity floor (significant and above by default), a category filter, the chosen event, and a continuous feed, newest first. **Local**, while the camera is below 3,000 km: every report in the area at the view centre, newest first, named at the top ("News from …") and outlined on the globe, which then shows those reports instead of the hotspots' news; at sea, reports within 500 km. A disputed area of the bundled list (11, see `src/data/local_data/natural_earth/README.md`), or a territory Natural Earth gives no country code (Somaliland, Northern Cyprus and others), is named as itself and read from no country's outlets; elsewhere Natural Earth's default country lines apply. Each card shows the publisher's picture when the event has one (hotlinked, no referrer, publisher credited), the headline (a model's English headline marked as such), a mono meta line (severity marker, category, place, sources, age), who reported it, attestation and media chips, and the service it came through ("via GDELT Project"). Open, a card plays the post's clip on request. A click flies the camera straight down from 150 km and selects the report.
|
||||
- **Notices.** A section whose key the server lacks says "{provider} key required" and names the variable; a refused key says "{provider} refused its key"; a spent daily allowance says "{provider} limit reached for today". The other section keeps working.
|
||||
- **Source.** `sources.news` (`createNewsSource`, export `./layers/news/source`) reads same-origin `/api/news/*` with a 15 s timeout, a 4 MiB cap and record-by-record validation; `newsQueryAllowed` lets a host admit exactly the client's requests. Core's local server (`server/providers/news.js`) forwards only those GET requests to `GEV_NEWS_ORIGIN` when it is set.
|
||||
- **Built-in backend.** With `GEV_NEWS_ORIGIN` unset, Core answers the same routes itself (`server/providers/news/keyed.js`). **Conflicts** needs no key: the last 24 h of GDELT 2.0 event exports (15-minute files on `data.gdeltproject.org`, about 100 KB each), physical violence only (CAMEO roots 18–20), one report per story with copies of one agency story merged, placed at GDELT's location for it (a town the article's words name beats a bare country). Titles are the article's page title from GDELT's GKG export of the same quarter hour (about 6 MB each) for the newest 3 h, else the words of the article's address; GDELT's actor coding is never shown. With `LIVEUAMAP_API_KEY`, Liveuamap's mapped items stand beside GDELT's. **Local** reads World News API (`WORLDNEWSAPI_KEY`) by the source country at the view centre, once per country every 30 minutes (about 1.5 points a read, at most `WORLDNEWSAPI_DAILY_READS` reads a day, default 30), plus the Conflicts reports placed inside the area. A country's own stories keep World News API's category (politics, business, else other) and no severity: the rules read fighting and crises, and everyday headlines mislead them. Areas come from the bundled Natural Earth countries and disputed areas (`server/providers/news/areas.js`). Conflicts' categories, relevance and severity are bundled rules (`categorize.js`); a news server may replace them. A read with nothing current to serve (GDELT's, Liveuamap's or a country's) is waited for at most 10 s, under the client's 15 s timeout, and goes on past that for the next refresh. Meanwhile GDELT serves the exports read so far and Conflicts serves GDELT without Liveuamap; Local in a country answers unavailable (502) until its outlets' read lands, and serves them without the Conflicts reports while those are missing. A section left with nothing answers unavailable, and a refused key stays refused. A country's World News API news is kept for at most 1 hour and then deleted; a request that never reached World News API is not counted against the day's reads. A story with neither a page title nor words in its address is minor (GDELT's code alone), so it is not listed under Conflicts, and the hotspot counts leave minor reports out. The routes sit behind the cross-site gate for key-spending routes (`sameSiteGated`), a request line that is no URL answers 400, and a news server's 503 key states (`no_key`, `key_rejected`, `key_quota`) and `news_not_configured` are relayed as they are.
|
||||
- **State.** Share/restore token `00`, enabled-only. Voice is off for this layer (`VOICE_OFF_LAYERS`).
|
||||
|
||||
### S2 GhostMaps (October 2026)
|
||||
|
||||
- **What it shows.** Events ▸ **S2 GhostMaps** draws the current edition of S2 Underground's KMZ intel products from `github.com/s2underground/GhostMaps`. The products are the Common Intelligence Picture and the 30-day kinetic pull (both on by default), the Border Crisis Map, the Iran Common Intelligence Picture, Iran Kinetic Events, Yemen FLOT, and **Latest Drop**: the newest dated incident file outside those series, `0_Archive`, `Basedata` and `Reference Material`. Each product has a chip in the row. The chip choice is kept in `localStorage` (`gev.ghostmaps.products`) and falls back to the defaults when storage is blocked.
|
||||
@@ -6716,11 +6771,11 @@ apply to `public/` assets or built-preview serving.
|
||||
The ship bridge and the orbital view have their own own-layer gates
|
||||
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
|
||||
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
|
||||
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical and Cyber layouts), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Empty news matches and unavailable news use compact text states rather than reserving an empty media frame; partial local data remains explicit. Article links open their original publisher, and no headline is treated as verified risk intelligence. On desktop both cockpit rails use the same width and share a bottom-aligned safe baseline in opposite corners above the peripheral MGRS/GSD/time telemetry, leaving bothLine truncated
|
||||
- **Aircraft cockpit view:** selecting a commercial or military aircraft reveals a `COCKPIT` action once that aircraft's own layer is on; Contacts is not required. The action shows in Contacts (`#cockpit-entry`) and under the Intel HUD's bottom-right readout (`#cockpit-entry-readout`, with the HUD on, in its Tactical and Cyber layouts), so entry needs no Contacts panel. Turning off the ridden aircraft's layer ends the view (the layer clears its tracking). When an air feed the surrounding picture uses is off, the Cockpit says so instead of blocking: Live Signals leads with `MILITARY FEED OFF · PARTIAL PICTURE` or `FLIGHTS FEED OFF · PARTIAL PICTURE`, and the Contact card shows that line in place of its inputs status, so a partial picture is never presented as complete. `control_cockpit` refuses entry with `entryBlockedReason` `contacts-starting` (a Context change in flight), `subject-layer-off` (the aircraft's layer, or with none tracked any aircraft layer, is off) or `no-tracked-aircraft`. Cockpit mode temporarily releases Cesium's orbit-follow transform and drives a first-person camera from the tracked aircraft's existing smoothed display position and course. Its concave helmet-visor HUD shows callsign, UTC time, coordinates, curved roll/pitch guides, and a seven-division heading tape. Ambient commercial and military AIR contacts use a Cockpit near/far band selected by the shared Display 3D mode: Proximity admits at 150 km and retains to 185 km; All admits at 400 km and retains to 450 km. The shared 3D toggle now applies in Cockpit: Off keeps in-range contacts as rotating 2D aircraft silhouettes, while On lets a ready admitted glTF take over without a drawing gap. The Cockpit model cap remains 60 and can only lower the map budget; in-range contacts that are capped or still loading remain 2D silhouettes instead of degrading to out-of-range dots. Contacts outside the selected band use small rotation-free cyan-white pips for civilian aircraft and amber pips for military. The pilot's own airframe is not drawn in first person, and exiting clears the Cockpit band and restores normal map silhouettes/models. The normal left accordion remains available for Layers and Authoring and keeps the same 26vh HUD-aligned anchor used in map mode, independent of whether the bottom-left Contact card is expanded or collapsed; the right-rail CCTV and Context chooser are hidden to avoid duplicating or overlapping the cockpit presentation. When the intelligence HUD is enabled, its classification, scene summary, collection/orbit metadata, coordinates, and imaging-status text remain visible as reduced peripheral cockpit telemetry; the optical center and flight instruments stay clear, and turning the HUD off still hides it. Ground speed, exact heading, and rendered altitude form one compact lower-center instrument cluster, keeping the horizon and peripheral view open. A second live altitude tape hugs the inside-right visor rim: its rail and nine moving ticks are derived from the same responsive keyhole radius, remain 20 px inside the circular edge even on wide displays, fade deeply at both vertical ends, and move continuously behind a fixed current-altitude pointer; its interval tightens automatically near the surface and it is suppressed on narrow screens. Cockpit mode also has a weather-backed transparent volumetric-cloud pass derived from the supplied FBM/domain-warped R&D shader. It renders at no more than 520×320, uses 24 ray steps/three FBM octaves at 12 FPS, is clipped to the visor, fails clear when Open-Meteo is unavailable, and stops its animation completely on cockpit exit. It does not restore the prior CPU weather canvases, precipitation, scene fog, or any map-mode effect. When Contacts is active for the tracked aircraft, the compact `CONTACT` rail adds the 250 km subject window, four cohort counts, nearest observed/mapped example with relative bearing and distance, freshness, explicit uncertainty, and Previous and Next controls plus its own collapse control. The mirrored right rail is a three-page **cockpit briefing carousel**: source-backed live signals, location-matched regional headlines, and physical-region/current-weather context from bundled Natural Earth polygons and Open-Meteo. It is manual-first: Previous, Next, and direct page controls are always available, and the visible `CYCLE OFF` / `CYCLE ON` control starts or stops the nine-second page cycle. The cycle pauses on hover or keyboard focus and stops while collapsed, hidden, or outside cockpit mode; live signal data continues refreshing either way. Regional News holds its list to the last 24 hours (`newsWindowHours` in the brief; the client drops anything older or undated even if a server sends it) and shows four distinct states: fresh results with no banner and a `{SOURCE} · LAST 24 H` footer; earlier results kept after a failed refresh under `CACHED · REFRESH FAILED` with the cached age in the footer; `NO NEWS IN THE LAST 24 H` when a source answered wiLine truncated
|
||||
- **Cockpit left-panel clearance:** the Cockpit Contact card and peripheral HUD participate in the adaptive left accordion's live obstacle measurements, including live viewport-height changes. Expanding Layers or Authoring keeps the active panel in the available upper-left corridor with internal scrolling; it does not cover the Contact card, lower Cockpit controls, or Cesium credit line. Outside Cockpit the hidden card does not alter the normal corridor.
|
||||
- **Cockpit Context scope:** the 250 km radius applies to the air/sea proximity cohorts. Installation counts come only from the currently loaded viewport and are labeled `CURRENT VIEWPORT ONLY` in the cockpit as well as the normal Context panel; neither surface presents them as a complete 250 km installation survey.
|
||||
- **Cockpit camera anchor:** first-person mode does not write feed-boundary corrections directly into the camera. A cockpit-only inertial anchor advances from the selected aircraft's displayed course and speed, then converges toward the authoritative delayed track with correction capped below forward motion. The displayed kinematics are derived from the same consecutive fix segment as the rendered position, with raw feed speed/course used only as fallback; a transient zero/missing feed speed therefore cannot freeze a visibly moving aircraft after layer enable or a map/cockpit handoff. Rendered altitude continues to come from that interpolated track position. Late ADS-B fixes and short render stalls can remove drift without accelerating or reversing the view. Camera placement runs before scene update/culling at a bounded 20 Hz so a moving cockpit does not force Photoreal 3D Tiles to retraverse on every display frame; textual instruments update at 10 Hz and context/layout work at 4 Hz. Every far Cockpit contact pip shares one stable Cesium texture-atlas entry and skips unused screen-projected course calculations, while only in-range 2D aircraft silhouettes pay the screen-projected rotation cost; ambient glTF collections are hidden/retained rather than synchronously destroyed at cockpit entry, and context rails lay out only on explicit content/state changes and viewport resize. The deliberate 15/30-second layer interpolation delays and per-Cesium-frame position caches remain unchanged.
|
||||
- **Cockpit route, vision, and view controls:** visible on-screen `COCKPIT`, `RESET`, and `EXIT COCKPIT` controls are the way in and out; Cockpit claims no `C` shortcut, so `C` keeps toggling CCTV, also inside a first-person view. RESET uses the same canonical globe route as the map and voice actions, exits Cockpit, and releases its camera ownership rather than exposing the hidden map-style top action. When the tracked commercial flight has a plausible ADSBDB route, the top of the right briefing rail shows a compact `FROM → TO` airport strip and the visor shows a centered estimated-destination chevron with its relative bearing; its destination label rounds to whole degrees in 000–359, wrapping rounded north to 000° while the chevron continues to use the relative bearing independently of label rounding; absent or implausible route data hides the strip and cue rather than guessing. The cockpit-local vision control is an interactive `PREV / CURRENT / NEXT` carousel over `NORMAL`, `CRT`, `NVG`, `FLIR`, `ANIME`, and `NOIR`; its previous/next actions wrap, and activating the current value advances to the next style. Cockpit enters on the active map preset, so a Cyber FLIR map opens Cockpit on FLIR while Normal remains a distinct option instead of producing a second FLIR entry. Cockpit choices temporarily activate the existing Cesium post-process stages, while exiting Cockpit through either EXIT or RESET restores the pre-entry map style. The regional-news page uses a free Google News RSS locality query first, with the existing GDELT query retained only as a fail-soft fallback; linked headlines remain reporting, not verified incidents or risk intelligence.
|
||||
- **Cockpit route, vision, and view controls:** visible on-screen `COCKPIT`, `RESET`, and `EXIT COCKPIT` controls are the way in and out; Cockpit claims no `C` shortcut, so `C` keeps toggling CCTV, also inside a first-person view. RESET uses the same canonical globe route as the map and voice actions, exits Cockpit, and releases its camera ownership rather than exposing the hidden map-style top action. When the tracked commercial flight has a plausible ADSBDB route, the top of the right briefing rail shows a compact `FROM → TO` airport strip and the visor shows a centered estimated-destination chevron with its relative bearing; its destination label rounds to whole degrees in 000–359, wrapping rounded north to 000° while the chevron continues to use the relative bearing independently of label rounding; absent or implausible route data hides the strip and cue rather than guessing. The cockpit-local vision control is an interactive `PREV / CURRENT / NEXT` carousel over `NORMAL`, `CRT`, `NVG`, `FLIR`, `ANIME`, and `NOIR`; its previous/next actions wrap, and activating the current value advances to the next style. Cockpit enters on the active map preset, so a Cyber FLIR map opens Cockpit on FLIR while Normal remains a distinct option instead of producing a second FLIR entry. Cockpit choices temporarily activate the existing Cesium post-process stages, while exiting Cockpit through either EXIT or RESET restores the pre-entry map style. The regional-news page uses a free Google News RSS locality query for the last day (`when:1d`) first, with the existing GDELT query (24 h timespan) retained only as a fail-soft fallback; both keep only articles published in the last 24 hours, newest first; linked headlines remain reporting, not verified incidents or risk intelligence.
|
||||
- Cockpit wind-direction labels wrap after rounding to whole degrees, so a direction of 359.5° displays as `N · 0°` rather than `N · 360°`.
|
||||
- The transit, ALPR, vessel, CCTV, Local ADS-B, flight and military context, awareness, Cockpit and Street Level heading readouts, and the query tools' vessel `course_deg` and `heading_deg`, aircraft `course_deg`, transit `bearing_deg`, camera `heading_deg` and satellite `rise_azimuth_deg` and `azimuth_deg`, round through `roundHeadingDegrees` in `src/data/headingDegrees.js` (whole degrees 0–359, `null` when not finite, so each caller keeps its own placeholder); `normalizeHeading` lives there too and `cockpitMath.js` re-exports it. The Cockpit's `TRACK ACQUIRED` signal uses `formatHeadingReadout`, so a 359.6° track reads `COURSE 000°`.
|
||||
- **Cockpit missing observations:** missing local weather observations remain unknown rather than being converted to zero or clear skies, in the briefing and in the cloud effects; a missing temperature drops the whole local weather record, including its wind and condition.
|
||||
|
||||
+44
-1
@@ -1,6 +1,6 @@
|
||||
# KNOWN ISSUES
|
||||
|
||||
Updated: September 22, 2026
|
||||
Updated: November 5, 2026
|
||||
|
||||
This file tracks active runtime issues only.
|
||||
|
||||
@@ -145,6 +145,49 @@ Status: Open (limits)
|
||||
|
||||
---
|
||||
|
||||
### News layer without a news server
|
||||
Status: Open (limits)
|
||||
|
||||
- GDELT's places and categories are machine-coded and approximate. A report can
|
||||
be placed in the wrong town of the same name, or at a country an article only
|
||||
names as a nationality ("Syrian refugees" placed in Syria).
|
||||
- Copies of one agency story are merged, but the same event under different
|
||||
wording stays as separate reports.
|
||||
- Only the 11 disputed areas in the bundled list
|
||||
(`src/data/local_data/natural_earth/README.md`) and the territories Natural
|
||||
Earth gives no country code (Somaliland, Northern Cyprus, Siachen Glacier,
|
||||
the Spratly Islands and a few more) are named as themselves; everywhere else
|
||||
Natural Earth's default country lines apply, so a place in Western Sahara,
|
||||
for example, is named with the country those lines put it in. GDELT places a whole city at one point: Jerusalem's falls
|
||||
inside East Jerusalem, so it is named "Jerusalem" alone.
|
||||
- A country's own stories in Local keep World News API's category (politics as
|
||||
political, business as economy, else other) and carry no severity; fighting
|
||||
there shows through the Conflicts reports placed in the area.
|
||||
- When World News API takes 10 to 20 s to answer a country's first read, Local
|
||||
reads unavailable until it is asked again (the next refresh, every 2 minutes
|
||||
while the tab is shown, or the camera settling in another half-degree cell,
|
||||
or a section switch), which is served from that read. A read over 20 s fails
|
||||
and is tried again with the first ask a minute or more later.
|
||||
- Local needs a World News API key. Its free plan allows 50 points a day; Core
|
||||
stops at `WORLDNEWSAPI_DAILY_READS` reads (default 30) and Local then says the
|
||||
daily limit is reached. A request that never reached World News API (offline)
|
||||
is not counted; any answer from it is, a failing one too, and so is a
|
||||
request that timed out.
|
||||
- A country's news is kept for at most 1 hour (World News API's terms, which
|
||||
also ask the operator for its written permission to cache at all). While
|
||||
World News API cannot be read, Local in that country therefore reads
|
||||
unavailable from an hour after its last good read.
|
||||
- A story GDELT codes as violence whose address has no words, and whose page
|
||||
title is not in yet (titles are read for the newest 3 hours only), is not
|
||||
listed under Conflicts or counted in its hotspot: GDELT's coding alone is
|
||||
wrong too often. It still shows in Local for its area, as "… reported in
|
||||
<place>".
|
||||
- `/api/news/*` refuses cross-site browser requests and requests carrying
|
||||
reverse-proxy forwarding headers, like the other key-spending routes
|
||||
(SECURITY.md): behind a reverse proxy the News layer reads unavailable.
|
||||
|
||||
---
|
||||
|
||||
## Closed / Intentional (for clarity)
|
||||
|
||||
### Proxy SSRF and error-surface hardening gaps
|
||||
|
||||
@@ -138,6 +138,9 @@
|
||||
"./server/providers/regional": {
|
||||
"node": "./server/providers/regional.js"
|
||||
},
|
||||
"./server/providers/news": {
|
||||
"node": "./server/providers/news.js"
|
||||
},
|
||||
"./server/providers/openai": {
|
||||
"node": "./server/providers/openai.js"
|
||||
},
|
||||
@@ -261,6 +264,7 @@
|
||||
"./layers/gnss/source": "./src/layers/gnss/source.js",
|
||||
"./layers/ghostmaps/source": "./src/layers/ghostMaps/source.js",
|
||||
"./layers/drone-airspace/source": "./src/layers/droneAirspace/source.js",
|
||||
"./layers/news/source": "./src/layers/news/source.js",
|
||||
"./layers/firms/source": "./src/layers/firms/source.js",
|
||||
"./layers/installations/source": "./src/layers/installations/source.js",
|
||||
"./layers/launches/source": "./src/layers/launches/source.js",
|
||||
|
||||
@@ -1230,6 +1230,7 @@
|
||||
"src/data/firmsIntensity.js",
|
||||
"src/data/firmsIntensity.test.mjs",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
"src/ui/layerPanel/RowRange.vue",
|
||||
"src/ui/layerPanel/RowSlider.vue",
|
||||
"src/sources/phaseTiming.test.mjs",
|
||||
"scripts/build-census-places.mjs",
|
||||
@@ -1284,6 +1285,13 @@
|
||||
"src/voice/panelLayout.js",
|
||||
"src/voice/textChat.js",
|
||||
"src/voice/textProtocol.js",
|
||||
"src/layers/shipwrecks/records.test.mjs",
|
||||
"src/layers/shipwrecks/cards.test.mjs",
|
||||
"src/layers/shipwrecks/eras.test.mjs",
|
||||
"src/layers/shipwrecks/period.test.mjs",
|
||||
"src/layers/shipwrecks/index.test.mjs",
|
||||
"src/layers/shipwrecks/source.test.mjs",
|
||||
"src/data/shipwrecksProxy.test.mjs",
|
||||
"src/app/sourceComposition.js",
|
||||
"src/app/sourceComposition.test.mjs",
|
||||
"src/data/dataCredits.js",
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"src/ui/views/panels/CockpitSignalList.vue",
|
||||
"src/ui/views/panels/CockpitUtilityControls.vue",
|
||||
"src/ui/cockpitBriefPages.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/ui/cockpitContextState.js",
|
||||
"src/ui/cockpitInstrumentState.js",
|
||||
"src/ui/cockpitRollingValue.js",
|
||||
@@ -508,6 +509,7 @@
|
||||
"server/providers/regional/weather-effects.js",
|
||||
"server/providers/regional/weather.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/geoDistance.js",
|
||||
"src/nominatimGeocode.js",
|
||||
"src/sources/httpBody.js",
|
||||
@@ -530,6 +532,32 @@
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
"news-provider": {
|
||||
"runtime": "node",
|
||||
"exports": ["./server/providers/news"],
|
||||
"modules": [
|
||||
"server/providers/news.js",
|
||||
"server/providers/news/keyed.js",
|
||||
"server/providers/news/categorize.js",
|
||||
"server/providers/news/areas.js",
|
||||
"server/providers/news/gdeltEvents.js",
|
||||
"server/providers/news/upstream.js",
|
||||
"server/providers/common/http.js",
|
||||
"server/providers/common/same-site.js",
|
||||
"src/data/adminBoundaries.js",
|
||||
"src/data/bundledJson.js",
|
||||
"src/data/retryableLoad.js",
|
||||
"src/data/local_data/natural_earth/countries.json",
|
||||
"src/data/local_data/natural_earth/disputed_areas.json",
|
||||
"src/layers/news/source.js",
|
||||
"src/layers/news/records.js",
|
||||
"src/localRequestGate.mjs",
|
||||
"src/sources/httpBody.js",
|
||||
"src/sources/capability.js",
|
||||
"src/i18n/marker.js"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
"openai-provider": {
|
||||
"runtime": "node",
|
||||
"exports": ["./server/providers/openai"],
|
||||
@@ -608,6 +636,7 @@
|
||||
"src/search/nominatim.js",
|
||||
"src/nominatimGeocode.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/geoDistance.js",
|
||||
"src/data/naturalEarthRegions.js",
|
||||
"src/data/bundledJson.js",
|
||||
@@ -733,6 +762,7 @@
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/layerPanel/RowText.vue",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
"src/ui/layerPanel/RowRange.vue",
|
||||
"src/ui/layerPanel/RowSlider.vue",
|
||||
"src/ui/railTimeline.js",
|
||||
"src/ui/clearLayersControl.js",
|
||||
@@ -769,6 +799,11 @@
|
||||
"src/ui/rail/RailTimeline.vue",
|
||||
"src/ui/rail/rangeValue.js",
|
||||
"src/ui/weather/WeatherReadout.vue",
|
||||
"src/ui/newsPanel.js",
|
||||
"src/ui/news/NewsFeed.vue",
|
||||
"src/ui/news/NewsCard.vue",
|
||||
"src/ui/kit/UiEmpty.vue",
|
||||
"src/ui/kit/UiSelect.js",
|
||||
"src/ui/kit/UiButton.vue",
|
||||
"src/ui/kit/UiBadge.vue",
|
||||
"src/ui/rail/fieldValue.js",
|
||||
@@ -914,6 +949,7 @@
|
||||
"src/ui/cockpit.js",
|
||||
"src/ui/cockpitBriefing.js",
|
||||
"src/ui/cockpitBriefPages.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/ui/cockpitContextState.js",
|
||||
"src/ui/cockpitInstrumentState.js",
|
||||
"src/ui/cockpitRollingValue.js",
|
||||
@@ -1075,6 +1111,7 @@
|
||||
"src/ui/cockpit.js",
|
||||
"src/ui/cockpitBriefing.js",
|
||||
"src/ui/cockpitBriefPages.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/ui/cockpitContextState.js",
|
||||
"src/ui/cockpitInstrumentState.js",
|
||||
"src/ui/cockpitRollingValue.js",
|
||||
@@ -1126,6 +1163,7 @@
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/layerPanel/RowText.vue",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
"src/ui/layerPanel/RowRange.vue",
|
||||
"src/ui/layerPanel/RowSlider.vue",
|
||||
"src/ui/railTimeline.js",
|
||||
"src/ui/layers.js",
|
||||
@@ -1224,6 +1262,11 @@
|
||||
"src/ui/rail/RailTimeline.vue",
|
||||
"src/ui/rail/rangeValue.js",
|
||||
"src/ui/weather/WeatherReadout.vue",
|
||||
"src/ui/newsPanel.js",
|
||||
"src/ui/news/NewsFeed.vue",
|
||||
"src/ui/news/NewsCard.vue",
|
||||
"src/ui/kit/UiEmpty.vue",
|
||||
"src/ui/kit/UiSelect.js",
|
||||
"src/ui/stores/streetLevel.js",
|
||||
"src/ui/stores/cctv.js",
|
||||
"src/ui/stores/radio.js",
|
||||
@@ -1294,6 +1337,7 @@
|
||||
"src/ui/styles/first-run.css",
|
||||
"src/ui/styles/provider-settings.css",
|
||||
"src/ui/styles/weather.css",
|
||||
"src/ui/styles/news.css",
|
||||
"src/ui/styles/recent-imagery.css"
|
||||
],
|
||||
"external": []
|
||||
@@ -2955,6 +2999,7 @@
|
||||
"src/ui/cockpit.js",
|
||||
"src/ui/cockpitBriefing.js",
|
||||
"src/ui/cockpitBriefPages.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/ui/cockpitContextState.js",
|
||||
"src/ui/cockpitInstrumentState.js",
|
||||
"src/ui/cockpitRollingValue.js",
|
||||
@@ -3001,6 +3046,7 @@
|
||||
"src/ui/rail/focusSafeChildren.js",
|
||||
"src/ui/layerPanel/RowText.vue",
|
||||
"src/ui/layerPanel/RowSwitch.vue",
|
||||
"src/ui/layerPanel/RowRange.vue",
|
||||
"src/ui/layerPanel/RowSlider.vue",
|
||||
"src/ui/railTimeline.js",
|
||||
"src/ui/layers.js",
|
||||
@@ -3130,11 +3176,25 @@
|
||||
"src/layers/ghostMaps/records.js",
|
||||
"src/layers/ghostMaps/kml.js",
|
||||
"src/layers/ghostMaps/source.js",
|
||||
"src/app/layers/shipwrecks.js",
|
||||
"src/layers/shipwrecks/index.js",
|
||||
"src/layers/shipwrecks/source.js",
|
||||
"src/layers/shipwrecks/records.js",
|
||||
"src/layers/shipwrecks/cards.js",
|
||||
"src/layers/shipwrecks/eras.js",
|
||||
"src/layers/shipwrecks/period.js",
|
||||
"src/app/layers/droneAirspace.js",
|
||||
"src/layers/droneAirspace/index.js",
|
||||
"src/layers/droneAirspace/source.js",
|
||||
"src/layers/droneAirspace/records.js",
|
||||
"src/layers/droneAirspace/cards.js",
|
||||
"src/app/layers/news.js",
|
||||
"src/layers/news/index.js",
|
||||
"src/layers/news/model.js",
|
||||
"src/layers/news/records.js",
|
||||
"src/layers/news/source.js",
|
||||
"src/layers/news/sprites.js",
|
||||
"src/layers/news/cards.js",
|
||||
"src/layers/cctv/sourcePolicy.js",
|
||||
"src/sources/reference.js",
|
||||
"src/search/nominatim.js",
|
||||
@@ -3388,6 +3448,10 @@
|
||||
"src/ui/rail/RailTimeline.vue",
|
||||
"src/ui/rail/rangeValue.js",
|
||||
"src/ui/weather/WeatherReadout.vue",
|
||||
"src/ui/newsPanel.js",
|
||||
"src/ui/news/NewsFeed.vue",
|
||||
"src/ui/news/NewsCard.vue",
|
||||
"src/ui/kit/UiSelect.js",
|
||||
"src/ui/recentImagery/RecentImageryCard.vue",
|
||||
"src/ui/recentImagery/RecentImageryReadout.vue",
|
||||
"src/ui/stores/streetLevel.js",
|
||||
@@ -3928,15 +3992,30 @@
|
||||
"src/layers/ghostMaps/records.js",
|
||||
"src/layers/ghostMaps/kml.js",
|
||||
"src/layers/ghostMaps/source.js",
|
||||
"src/app/layers/shipwrecks.js",
|
||||
"src/layers/shipwrecks/index.js",
|
||||
"src/layers/shipwrecks/source.js",
|
||||
"src/layers/shipwrecks/records.js",
|
||||
"src/layers/shipwrecks/cards.js",
|
||||
"src/layers/shipwrecks/eras.js",
|
||||
"src/layers/shipwrecks/period.js",
|
||||
"src/app/layers/droneAirspace.js",
|
||||
"src/layers/droneAirspace/index.js",
|
||||
"src/layers/droneAirspace/source.js",
|
||||
"src/layers/droneAirspace/records.js",
|
||||
"src/layers/droneAirspace/cards.js",
|
||||
"src/app/layers/news.js",
|
||||
"src/layers/news/index.js",
|
||||
"src/layers/news/model.js",
|
||||
"src/layers/news/records.js",
|
||||
"src/layers/news/source.js",
|
||||
"src/layers/news/sprites.js",
|
||||
"src/layers/news/cards.js",
|
||||
"src/layers/cctv/sourcePolicy.js",
|
||||
"src/search/nominatim.js",
|
||||
"src/nominatimGeocode.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/i18n/marker.js",
|
||||
"src/sources/nominatim.js",
|
||||
@@ -4211,6 +4290,7 @@
|
||||
"src/search/nominatim.js",
|
||||
"src/nominatimGeocode.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/i18n/marker.js",
|
||||
"src/sources/nominatim.js",
|
||||
@@ -4522,7 +4602,11 @@
|
||||
},
|
||||
"regional-source": {
|
||||
"exports": ["./sources/regional"],
|
||||
"modules": ["src/data/regionalModel.js", "src/geoDistance.js"],
|
||||
"modules": [
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/geoDistance.js"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
"voice-action-schemas": {
|
||||
@@ -4732,6 +4816,7 @@
|
||||
"src/search/google.js",
|
||||
"src/search/geospatial.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/geoDistance.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/i18n/marker.js",
|
||||
@@ -4756,6 +4841,7 @@
|
||||
"src/nominatimGeocode.js",
|
||||
"src/search/geospatial.js",
|
||||
"src/data/regionalModel.js",
|
||||
"src/data/regionalNewsWindow.js",
|
||||
"src/geoDistance.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/i18n/marker.js"
|
||||
@@ -5106,6 +5192,17 @@
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
"news-source": {
|
||||
"exports": ["./layers/news/source"],
|
||||
"modules": [
|
||||
"src/layers/news/source.js",
|
||||
"src/layers/news/records.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/sources/capability.js",
|
||||
"src/i18n/marker.js"
|
||||
],
|
||||
"external": []
|
||||
},
|
||||
"perimeters-source": {
|
||||
"exports": ["./layers/perimeters/source"],
|
||||
"modules": [
|
||||
|
||||
@@ -28,7 +28,9 @@ import { weatherProxy } from './weather.js';
|
||||
import { firePerimetersProxy } from './firePerimeters.js';
|
||||
import { gnssIntegrityProxy } from './gnssIntegrity.js';
|
||||
import { ghostMapsProxy } from './ghostMaps.js';
|
||||
import { shipwrecksProxy } from './shipwrecks.js';
|
||||
import { droneAirspaceProxy } from './droneAirspace.js';
|
||||
import { newsProxy } from './news.js';
|
||||
import { inaturalistProxy } from './inaturalist/observations.js';
|
||||
import { acartiaProxy } from './acartia.js';
|
||||
import { cycloneProxy } from './cyclones.js';
|
||||
@@ -82,7 +84,9 @@ function localProviderPlugins({
|
||||
firePerimetersProxy(),
|
||||
gnssIntegrityProxy(),
|
||||
ghostMapsProxy(),
|
||||
shipwrecksProxy(),
|
||||
droneAirspaceProxy(),
|
||||
newsProxy(),
|
||||
inaturalistProxy(),
|
||||
acartiaProxy(),
|
||||
keySetupEndpoint(),
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { newsQueryAllowed } from '../../src/layers/news/source.js';
|
||||
import { readResponseTextCapped } from './common/http.js';
|
||||
import { sameSiteGated } from './common/same-site.js';
|
||||
import { createKeyedNews } from './news/keyed.js';
|
||||
|
||||
// News (/api/news/*). With GEV_NEWS_ORIGIN set (a news server such as
|
||||
// https://news.example), this forwards exactly the GET requests the news
|
||||
// layer sends there and relays the JSON. Without it (or with a value that
|
||||
// is no plain origin, warned of once), Core answers the same routes itself
|
||||
// (news/keyed.js): Conflicts from GDELT's event exports with no key, and
|
||||
// Liveuamap's items beside them with LIVEUAMAP_API_KEY; Local from World
|
||||
// News API, "key required" while WORLDNEWSAPI_KEY is unset. A host that
|
||||
// serves news only from its own server mounts it with `builtIn: false`.
|
||||
|
||||
const TIMEOUT_MS = 15_000;
|
||||
const MAX_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The configured news server's origin, or null: http(s) only, no
|
||||
* credentials, query or fragment; a path is ignored.
|
||||
* @param {string|undefined} raw
|
||||
*/
|
||||
export function newsOrigin(raw = process.env.GEV_NEWS_ORIGIN) {
|
||||
const text = String(raw ?? '').trim();
|
||||
if (!text) return null;
|
||||
try {
|
||||
const url = new URL(text);
|
||||
if (
|
||||
!['http:', 'https:'].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash
|
||||
)
|
||||
return null;
|
||||
return url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Text for the log: no address (a key may ride in one), one short line. */
|
||||
const logText = (error) =>
|
||||
`${error?.name || 'Error'}: ${String(error?.message ?? '')}`
|
||||
.replace(/[a-z][a-z0-9+.-]*:\/\/\S*/gi, '<url>')
|
||||
.replace(/\s+/g, ' ')
|
||||
.slice(0, 200);
|
||||
|
||||
/** GEV_NEWS_ORIGIN as newsOrigin reads it; a value it refuses is warned of once. */
|
||||
function configuredOrigin(env, log) {
|
||||
let warned = null;
|
||||
return () => {
|
||||
const raw = String(env().GEV_NEWS_ORIGIN ?? '').trim();
|
||||
const base = newsOrigin(raw);
|
||||
if (!base && raw && warned !== raw) {
|
||||
warned = raw;
|
||||
// Not the value: it may carry credentials.
|
||||
log(
|
||||
'[news] GEV_NEWS_ORIGIN is not a plain http(s) origin; answering with the built-in news backend',
|
||||
);
|
||||
}
|
||||
return base;
|
||||
};
|
||||
}
|
||||
|
||||
/** A 503's known key or configuration state, rebuilt from its fields; else null. */
|
||||
async function upstreamState(upstream) {
|
||||
let body = null;
|
||||
try {
|
||||
body = JSON.parse(await readResponseTextCapped(upstream, 16 * 1024));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (body?.error === 'news_not_configured')
|
||||
return { error: body.error, unavailable: true, retryable: false };
|
||||
if (
|
||||
['no_key', 'key_rejected', 'key_quota'].includes(body?.error) &&
|
||||
typeof body.key === 'string' &&
|
||||
/^[a-z][a-z0-9-]{0,31}$/.test(body.key)
|
||||
)
|
||||
return { error: body.error, key: body.key };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A thin, validated GET proxy for the news layer's three read routes, or
|
||||
* their keyed answers without a news server. A host that serves news only
|
||||
* from its own server passes `builtIn: false`: without GEV_NEWS_ORIGIN the
|
||||
* routes then answer "not configured" and Core reads nothing itself.
|
||||
* @param {{env?: () => object, log?: (message: string) => void, origin?: () => string|null, fetchImpl?: typeof fetch, timeoutMs?: number, builtIn?: boolean, keyed?: {answer: (path: string, params: URLSearchParams) => Promise<{status: number, body: object}>}|null}} [options]
|
||||
*/
|
||||
export function newsProxy({
|
||||
env = () => process.env,
|
||||
log = (message) => console.warn(message),
|
||||
origin = configuredOrigin(env, log),
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
timeoutMs = TIMEOUT_MS,
|
||||
builtIn = true,
|
||||
keyed = builtIn ? createKeyedNews({ env, fetchImpl, log }) : null,
|
||||
} = {}) {
|
||||
const json = (res, status, value) => {
|
||||
if (res.destroyed) return;
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-store',
|
||||
...(status === 405 ? { Allow: 'GET' } : {}),
|
||||
});
|
||||
res.end(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
};
|
||||
|
||||
async function handler(req, res) {
|
||||
if (req.method !== 'GET')
|
||||
return json(res, 405, { error: 'method_not_allowed' });
|
||||
let local, target;
|
||||
try {
|
||||
// `//[` and the like are no URL: a 400, not an unhandled rejection.
|
||||
local = new URL(req.url || '/', 'http://local');
|
||||
target = new URL(
|
||||
`/api/news${local.pathname}${local.search}`,
|
||||
'http://local',
|
||||
);
|
||||
} catch {
|
||||
return json(res, 400, { error: 'invalid_news_request' });
|
||||
}
|
||||
if (!newsQueryAllowed(target))
|
||||
return json(res, 400, { error: 'invalid_news_request' });
|
||||
const base = origin();
|
||||
if (!base) {
|
||||
if (!keyed)
|
||||
return json(res, 503, {
|
||||
error: 'news_not_configured',
|
||||
unavailable: true,
|
||||
retryable: false,
|
||||
});
|
||||
try {
|
||||
const { status, body } = await keyed.answer(
|
||||
local.pathname,
|
||||
target.searchParams,
|
||||
);
|
||||
return json(res, status, body);
|
||||
} catch (error) {
|
||||
log(`[news] built-in news answer failed: ${logText(error)}`);
|
||||
return json(res, 502, { error: 'news_unavailable' });
|
||||
}
|
||||
}
|
||||
try {
|
||||
const upstream = await fetchImpl(
|
||||
new URL(`${target.pathname}${target.search}`, base),
|
||||
{
|
||||
headers: { Accept: 'application/json' },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
},
|
||||
);
|
||||
if (upstream.status === 503) {
|
||||
// The news server's own key and configuration states reach the
|
||||
// panel as they are, so it can say which key is missing.
|
||||
const state = await upstreamState(upstream);
|
||||
if (state) return json(res, 503, state);
|
||||
}
|
||||
if (!upstream.ok) {
|
||||
await upstream.body?.cancel().catch(() => {});
|
||||
return json(res, 502, {
|
||||
error: 'news_upstream_error',
|
||||
status: upstream.status,
|
||||
});
|
||||
}
|
||||
const text = await readResponseTextCapped(upstream, MAX_BYTES);
|
||||
// Relayed only as JSON; the browser validates every record.
|
||||
JSON.parse(text);
|
||||
return json(res, 200, text);
|
||||
} catch (error) {
|
||||
return json(res, error?.name === 'TimeoutError' ? 504 : 502, {
|
||||
error: 'news_unavailable',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The routes spend keys and upstream reads: no other site's page, and no
|
||||
// proxied request, may drive them (SECURITY.md, cross-site gate).
|
||||
const gated = sameSiteGated(handler);
|
||||
return {
|
||||
name: 'news',
|
||||
configureServer({ middlewares }) {
|
||||
middlewares.use('/api/news', gated);
|
||||
},
|
||||
configurePreviewServer({ middlewares }) {
|
||||
middlewares.use('/api/news', gated);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { newsOrigin, newsProxy } from './news.js';
|
||||
import { createKeyedNews } from './news/keyed.js';
|
||||
|
||||
/** Mount the proxy on a fake middleware stack and call it like Connect does. */
|
||||
function mount(options) {
|
||||
let handler = null;
|
||||
newsProxy(options).configureServer({
|
||||
middlewares: {
|
||||
use(prefix, fn) {
|
||||
assert.equal(prefix, '/api/news');
|
||||
handler = fn;
|
||||
},
|
||||
},
|
||||
});
|
||||
return async (url, method = 'GET', headers = {}) => {
|
||||
const res = {
|
||||
destroyed: false,
|
||||
status: 0,
|
||||
headers: {},
|
||||
body: '',
|
||||
writeHead(status, headers) {
|
||||
this.status = status;
|
||||
this.headers = headers;
|
||||
},
|
||||
setHeader(name, value) {
|
||||
this.headers[name] = value;
|
||||
},
|
||||
end(body) {
|
||||
if (this.statusCode) this.status = this.statusCode;
|
||||
this.body = body;
|
||||
},
|
||||
};
|
||||
await handler({ url, method, headers }, res);
|
||||
return { ...res, json: res.body ? JSON.parse(res.body) : null };
|
||||
};
|
||||
}
|
||||
|
||||
test('the origin must be a plain http(s) origin', () => {
|
||||
assert.equal(
|
||||
newsOrigin('http://news.example:8080'),
|
||||
'http://news.example:8080',
|
||||
);
|
||||
assert.equal(
|
||||
newsOrigin('https://news.example/base/'),
|
||||
'https://news.example',
|
||||
);
|
||||
for (const bad of [
|
||||
undefined,
|
||||
'',
|
||||
' ',
|
||||
'ftp://x',
|
||||
'http://u:p@x',
|
||||
'http://x/?a=1',
|
||||
'http://x/#f',
|
||||
'not a url',
|
||||
])
|
||||
assert.equal(newsOrigin(bad), null, String(bad));
|
||||
});
|
||||
|
||||
test('without GEV_NEWS_ORIGIN Core answers itself: Conflicts from GDELT, Local saying it needs its key', async () => {
|
||||
const hosts = [];
|
||||
const fetchImpl = async (url) => {
|
||||
hosts.push(new URL(String(url)).host);
|
||||
throw new Error('offline');
|
||||
};
|
||||
const call = mount({
|
||||
origin: () => null,
|
||||
fetchImpl,
|
||||
keyed: createKeyedNews({ env: () => ({}), fetchImpl, log: () => {} }),
|
||||
});
|
||||
// GDELT's exports need no key; offline, the read fails like any upstream.
|
||||
const hotspots = await call('/hotspots');
|
||||
assert.equal(hotspots.status, 502);
|
||||
assert.deepEqual(hotspots.json, { error: 'news_upstream_error' });
|
||||
const local = await call('/feed?hotspot=all&at=31.95,35.93');
|
||||
assert.equal(local.status, 503);
|
||||
assert.deepEqual(local.json, { error: 'no_key', key: 'worldnewsapi' });
|
||||
// The area is read from the bundled countries, with no key.
|
||||
const area = await call('/outline?at=31.95,35.93&v=4');
|
||||
assert.equal(area.status, 200);
|
||||
assert.equal(area.json.area.name, 'Jordan');
|
||||
// The client's allowlist still holds.
|
||||
assert.equal((await call('/feed?side=UA')).status, 400);
|
||||
assert.ok(hosts.length > 0);
|
||||
assert.ok(hosts.every((host) => host === 'data.gdeltproject.org'));
|
||||
});
|
||||
|
||||
test('forwards only the client routes, by GET, and relays the JSON', async () => {
|
||||
const calls = [];
|
||||
const call = mount({
|
||||
origin: () => 'https://news.example',
|
||||
fetchImpl: async (url, init) => {
|
||||
calls.push({ url: String(url), init });
|
||||
return new Response('{"reports":[],"nextBefore":null}', { status: 200 });
|
||||
},
|
||||
});
|
||||
const ok = await call('/feed?hotspot=all&limit=60&today=1&events=1');
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual(ok.json, { reports: [], nextBefore: null });
|
||||
assert.equal(ok.headers['Cache-Control'], 'no-store');
|
||||
assert.equal(
|
||||
calls[0].url,
|
||||
'https://news.example/api/news/feed?hotspot=all&limit=60&today=1&events=1',
|
||||
);
|
||||
assert.equal(calls[0].init.redirect, 'error');
|
||||
assert.ok(calls[0].init.signal instanceof AbortSignal);
|
||||
|
||||
for (const url of [
|
||||
'/air-alerts',
|
||||
'/feed?side=UA',
|
||||
'/feed?limit=9999',
|
||||
'/../admin',
|
||||
'/hotspots?x=1',
|
||||
]) {
|
||||
const refused = await call(url);
|
||||
assert.equal(refused.status, 400, url);
|
||||
}
|
||||
const post = await call('/hotspots', 'POST');
|
||||
assert.equal(post.status, 405);
|
||||
assert.equal(post.headers.Allow, 'GET');
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test('upstream failures, bad JSON and timeouts become bounded errors', async () => {
|
||||
const failing = mount({
|
||||
origin: () => 'https://news.example',
|
||||
fetchImpl: async () => new Response('down', { status: 500 }),
|
||||
});
|
||||
const down = await failing('/hotspots');
|
||||
assert.equal(down.status, 502);
|
||||
assert.deepEqual(down.json, { error: 'news_upstream_error', status: 500 });
|
||||
|
||||
const garbled = mount({
|
||||
origin: () => 'https://news.example',
|
||||
fetchImpl: async () => new Response('<html>', { status: 200 }),
|
||||
});
|
||||
assert.equal((await garbled('/hotspots')).status, 502);
|
||||
|
||||
const slow = mount({
|
||||
origin: () => 'https://news.example',
|
||||
timeoutMs: 10,
|
||||
// AbortSignal.timeout does not hold the event loop open: the hanging
|
||||
// fetch does, until its signal aborts, so the run cannot end before it.
|
||||
fetchImpl: (_url, { signal }) =>
|
||||
new Promise((_, reject) => {
|
||||
const alive = setTimeout(() => {}, 60_000);
|
||||
signal.addEventListener('abort', () => {
|
||||
clearTimeout(alive);
|
||||
reject(signal.reason);
|
||||
});
|
||||
}),
|
||||
});
|
||||
const timedOut = await slow('/hotspots');
|
||||
assert.equal(timedOut.status, 504);
|
||||
assert.deepEqual(timedOut.json, { error: 'news_unavailable' });
|
||||
});
|
||||
|
||||
test('a GEV_NEWS_ORIGIN that is no plain origin is warned of once, and Core answers itself', async () => {
|
||||
const logs = [];
|
||||
const asked = [];
|
||||
const call = mount({
|
||||
env: () => ({ GEV_NEWS_ORIGIN: 'https://user:[email protected]' }),
|
||||
log: (line) => logs.push(line),
|
||||
fetchImpl: async () => assert.fail('nothing is forwarded'),
|
||||
keyed: {
|
||||
answer: async (path) => {
|
||||
asked.push(path);
|
||||
return { status: 200, body: { reports: [], nextBefore: null } };
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal((await call('/feed?hotspot=all')).status, 200);
|
||||
assert.equal((await call('/feed?hotspot=all')).status, 200);
|
||||
assert.deepEqual(asked, ['/feed', '/feed']);
|
||||
assert.equal(logs.length, 1);
|
||||
assert.doesNotMatch(logs[0], /secret|news\.example/);
|
||||
});
|
||||
|
||||
test('a built-in answer that throws is a 502, logged in one line without addresses', async () => {
|
||||
const logs = [];
|
||||
const call = mount({
|
||||
env: () => ({}),
|
||||
log: (line) => logs.push(line),
|
||||
keyed: {
|
||||
answer: async () => {
|
||||
throw new TypeError('bad https://api.example/?key=abc\nmore');
|
||||
},
|
||||
},
|
||||
});
|
||||
const failed = await call('/hotspots');
|
||||
assert.equal(failed.status, 502);
|
||||
assert.deepEqual(failed.json, { error: 'news_unavailable' });
|
||||
assert.equal(logs.length, 1);
|
||||
assert.match(logs[0], /TypeError/);
|
||||
assert.doesNotMatch(logs[0], /key=abc|\n/);
|
||||
});
|
||||
|
||||
test('a host that serves news only from its own server turns the built-in backend off', async () => {
|
||||
let fetches = 0;
|
||||
const call = mount({
|
||||
origin: () => null,
|
||||
builtIn: false,
|
||||
fetchImpl: async () => {
|
||||
fetches++;
|
||||
throw new Error('unexpected');
|
||||
},
|
||||
});
|
||||
for (const url of [
|
||||
'/hotspots',
|
||||
'/feed?hotspot=all',
|
||||
'/outline?at=31.95,35.93&v=4',
|
||||
]) {
|
||||
const answer = await call(url);
|
||||
assert.equal(answer.status, 503, url);
|
||||
assert.deepEqual(answer.json, {
|
||||
error: 'news_not_configured',
|
||||
unavailable: true,
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
assert.equal(fetches, 0);
|
||||
});
|
||||
|
||||
test('a request line that is no URL is a 400, not a crash', async () => {
|
||||
const call = mount({
|
||||
origin: () => null,
|
||||
keyed: { answer: async () => assert.fail('nothing is answered') },
|
||||
});
|
||||
// `GET /api/news//[`: Connect strips the mount prefix and leaves `//[`.
|
||||
const bad = await call('//[');
|
||||
assert.equal(bad.status, 400);
|
||||
assert.deepEqual(bad.json, { error: 'invalid_news_request' });
|
||||
});
|
||||
|
||||
test('cross-site and proxied requests are refused before anything is read', async () => {
|
||||
let answered = 0;
|
||||
const call = mount({
|
||||
origin: () => null,
|
||||
keyed: {
|
||||
answer: async () => {
|
||||
answered++;
|
||||
return { status: 200, body: { reports: [], nextBefore: null } };
|
||||
},
|
||||
},
|
||||
});
|
||||
const host = 'localhost:5173';
|
||||
for (const headers of [
|
||||
{ host, origin: 'https://evil.example' },
|
||||
{ host, origin: 'null' },
|
||||
{ host, 'sec-fetch-site': 'cross-site' },
|
||||
{ host, 'x-forwarded-for': '203.0.113.9' },
|
||||
]) {
|
||||
const refused = await call('/feed?hotspot=all', 'GET', headers);
|
||||
assert.equal(refused.status, 403, JSON.stringify(headers));
|
||||
}
|
||||
assert.equal(answered, 0);
|
||||
for (const headers of [
|
||||
{ host },
|
||||
{ host, origin: `http://${host}`, 'sec-fetch-site': 'same-origin' },
|
||||
]) {
|
||||
const passed = await call('/feed?hotspot=all', 'GET', headers);
|
||||
assert.equal(passed.status, 200, JSON.stringify(headers));
|
||||
}
|
||||
assert.equal(answered, 2);
|
||||
});
|
||||
|
||||
test("a news server's key and configuration states are relayed as they are", async () => {
|
||||
for (const body of [
|
||||
{ error: 'no_key', key: 'worldnewsapi' },
|
||||
{ error: 'key_rejected', key: 'worldnewsapi' },
|
||||
{ error: 'key_quota', key: 'worldnewsapi' },
|
||||
{ error: 'news_not_configured', unavailable: true, retryable: false },
|
||||
]) {
|
||||
const call = mount({
|
||||
origin: () => 'https://news.example',
|
||||
fetchImpl: async () =>
|
||||
new Response(JSON.stringify(body), { status: 503 }),
|
||||
});
|
||||
const relayed = await call('/feed?hotspot=all&at=31.95,35.93');
|
||||
assert.equal(relayed.status, 503, body.error);
|
||||
assert.deepEqual(relayed.json, body);
|
||||
}
|
||||
// Any other 503 stays a bounded upstream error.
|
||||
const other = mount({
|
||||
origin: () => 'https://news.example',
|
||||
fetchImpl: async () =>
|
||||
new Response('{"error":"maintenance","detail":"x"}', { status: 503 }),
|
||||
});
|
||||
const down = await other('/hotspots');
|
||||
assert.equal(down.status, 502);
|
||||
assert.deepEqual(down.json, { error: 'news_upstream_error', status: 503 });
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
// Areas for the News layer, from the bundled Natural Earth packs (public
|
||||
// domain): the disputed area or else the country at a point, its outline in
|
||||
// the /api/news/outline form, and a point inside a country to pin its
|
||||
// national news at. A disputed area is checked first and named as itself,
|
||||
// so no one country's name stands for it; so is a territory the countries
|
||||
// pack gives no code (Somaliland), rather than read as sea. Read once, on
|
||||
// first use.
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
import {
|
||||
containsAnchor,
|
||||
geometryOf,
|
||||
pointInRing,
|
||||
} from '../../../src/data/adminBoundaries.js';
|
||||
|
||||
const PACKS = '../../../src/data/local_data/natural_earth/';
|
||||
const PACK = new URL(`${PACKS}countries.json`, import.meta.url);
|
||||
const DISPUTED = new URL(`${PACKS}disputed_areas.json`, import.meta.url);
|
||||
const ISO2 = /^[A-Z]{2}$/;
|
||||
|
||||
let countries = null;
|
||||
let territories = [];
|
||||
|
||||
/**
|
||||
* One entry per ISO code: its name and every Country part's geometry. The
|
||||
* Country features without a code ("-99": Somaliland, Northern Cyprus,
|
||||
* sovereign base areas, no man's lands) are kept apart as territories.
|
||||
*/
|
||||
function loadCountries(read = () => JSON.parse(readFileSync(PACK, 'utf8'))) {
|
||||
if (countries) return countries;
|
||||
const pack = read();
|
||||
const decimals = pack.meta?.decimals ?? 3;
|
||||
const byCode = new Map();
|
||||
const codeless = [];
|
||||
for (const feature of pack.features || []) {
|
||||
// The constituent countries of the United Kingdom repeat its part.
|
||||
if (feature.type !== 'Country') continue;
|
||||
if (!ISO2.test(feature.iso2 || '')) {
|
||||
if (feature.name)
|
||||
codeless.push({ name: feature.name, feature, decimals });
|
||||
continue;
|
||||
}
|
||||
const entry = byCode.get(feature.iso2) || {
|
||||
code: feature.iso2,
|
||||
name: null,
|
||||
size: 0,
|
||||
parts: [],
|
||||
};
|
||||
entry.parts.push({ feature, decimals });
|
||||
// Named after its largest feature: Kazakhstan, not the Baikonur lease.
|
||||
const size = JSON.stringify(feature.polygons).length;
|
||||
if (size > entry.size) {
|
||||
entry.name = feature.name;
|
||||
entry.size = size;
|
||||
}
|
||||
byCode.set(feature.iso2, entry);
|
||||
}
|
||||
countries = byCode;
|
||||
territories = codeless;
|
||||
return countries;
|
||||
}
|
||||
|
||||
/** Test seam: read another pack (or the bundled one again). */
|
||||
export function resetCountries(read) {
|
||||
countries = null;
|
||||
if (read) loadCountries(read);
|
||||
}
|
||||
|
||||
const geometries = (entry) => entry.parts.map((part) => geometryOf(part));
|
||||
|
||||
let disputed = null;
|
||||
const slug = (name) =>
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
|
||||
/** The disputed areas: `{key, name, kind, heldBy, claimedBy, rings}`. */
|
||||
function loadDisputed() {
|
||||
if (disputed) return disputed;
|
||||
const pack = JSON.parse(readFileSync(DISPUTED, 'utf8'));
|
||||
disputed = (pack.areas || []).map((area) => ({
|
||||
key: `disputed-${slug(area.name)}`,
|
||||
name: area.name,
|
||||
kind: area.kind,
|
||||
heldBy: area.heldBy ?? null,
|
||||
claimedBy: area.claimedBy ?? null,
|
||||
rings: area.rings,
|
||||
}));
|
||||
return disputed;
|
||||
}
|
||||
|
||||
/** The disputed area at a point, or null. */
|
||||
export function disputedAt(lat, lon) {
|
||||
return (
|
||||
loadDisputed().find((area) =>
|
||||
area.rings.some((ring) => pointInRing(ring, lat, lon)),
|
||||
) || null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The area a point is in, as the News layer names it: a disputed area, or
|
||||
* a territory without a code, as itself (`kind: 'disputed'`, `code` null),
|
||||
* else its country (`kind: 'country'`, with `country` the countryAt
|
||||
* entry); null at sea.
|
||||
*/
|
||||
export function areaAt(lat, lon) {
|
||||
const area = disputedAt(lat, lon);
|
||||
if (area)
|
||||
return {
|
||||
...area,
|
||||
kind: 'disputed',
|
||||
held: area.kind,
|
||||
code: null,
|
||||
polygons: area.rings.map((outer) => ({ outer, holes: [] })),
|
||||
};
|
||||
const country = countryAt(lat, lon);
|
||||
if (country)
|
||||
return {
|
||||
key: country.code,
|
||||
name: country.name,
|
||||
kind: 'country',
|
||||
code: country.code,
|
||||
country,
|
||||
};
|
||||
const territory = territoryAt(lat, lon);
|
||||
return territory
|
||||
? {
|
||||
key: `disputed-${slug(territory.name)}`,
|
||||
name: territory.name,
|
||||
kind: 'disputed',
|
||||
held: null,
|
||||
code: null,
|
||||
polygons: geometryOf(territory).polygons.map(([outer, ...holes]) => ({
|
||||
outer,
|
||||
holes,
|
||||
})),
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Whether a point lies in a geometry (geometryOf), across the antimeridian. */
|
||||
function inGeometry(geometry, lat, lon) {
|
||||
const [west, south, east, north] = geometry.bbox;
|
||||
const x = lon - 360 * Math.round((lon - (west + east) / 2) / 360);
|
||||
if (x < west || x > east || lat < south || lat > north) return false;
|
||||
return containsAnchor(geometry.polygons, lat, lon);
|
||||
}
|
||||
|
||||
/** The country at a point, or null at sea or in a territory without a code. */
|
||||
export function countryAt(lat, lon) {
|
||||
for (const entry of loadCountries().values())
|
||||
for (const geometry of geometries(entry))
|
||||
if (inGeometry(geometry, lat, lon)) return entry;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The territory without a code at a point (Somaliland), or null. */
|
||||
function territoryAt(lat, lon) {
|
||||
loadCountries();
|
||||
return (
|
||||
territories.find((part) => inGeometry(geometryOf(part), lat, lon)) || null
|
||||
);
|
||||
}
|
||||
|
||||
/** A country by its ISO code, or null. */
|
||||
export const countryByCode = (code) => loadCountries().get(code) || null;
|
||||
|
||||
/**
|
||||
* A country's outline as /api/news/outline answers it (`{outer, holes}`),
|
||||
* the disputed areas inside it left out as holes (Russia's without Crimea).
|
||||
*/
|
||||
export function countryPolygons(entry) {
|
||||
const areas = loadDisputed();
|
||||
return geometries(entry).flatMap((geometry) =>
|
||||
geometry.polygons.map(([outer, ...holes]) => ({
|
||||
outer,
|
||||
holes: [
|
||||
...holes,
|
||||
...areas
|
||||
.flatMap((area) => area.rings)
|
||||
// By a point inside it: its corners lie on the neighbours' borders.
|
||||
.filter((ring) => {
|
||||
const inside = ringInterior(ring);
|
||||
return inside && pointInRing(outer, inside.lat, inside.lon);
|
||||
}),
|
||||
],
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A point inside the country's largest part, for news placed in the country
|
||||
* alone: its label point when that lies inside, else the middle of the
|
||||
* widest span across the part at its middle latitude.
|
||||
*/
|
||||
export function countryAnchor(entry) {
|
||||
const largest = geometries(entry).sort((a, b) => b.areaKm2 - a.areaKm2)[0];
|
||||
const { label, polygons, bbox } = largest;
|
||||
if (containsAnchor(polygons, label.lat, label.lon)) return label;
|
||||
const [outer] = polygons.reduce((a, b) =>
|
||||
b[0].length > a[0].length ? b : a,
|
||||
);
|
||||
return ringInterior(outer, (bbox[1] + bbox[3]) / 2) || label;
|
||||
}
|
||||
|
||||
/**
|
||||
* A point inside a ring: the middle of its widest span at `lat` (its middle
|
||||
* latitude by default); null when the ring is not crossed there.
|
||||
*/
|
||||
function ringInterior(outer, lat = middleLat(outer)) {
|
||||
const crossings = [];
|
||||
for (let i = 0, j = outer.length - 1; i < outer.length; j = i++) {
|
||||
const [x1, y1] = outer[j];
|
||||
const [x2, y2] = outer[i];
|
||||
if (y1 > lat !== y2 > lat)
|
||||
crossings.push(x1 + ((lat - y1) * (x2 - x1)) / (y2 - y1));
|
||||
}
|
||||
crossings.sort((a, b) => a - b);
|
||||
let best = null;
|
||||
for (let i = 0; i + 1 < crossings.length; i += 2)
|
||||
if (!best || crossings[i + 1] - crossings[i] > best[1] - best[0])
|
||||
best = [crossings[i], crossings[i + 1]];
|
||||
return best ? { lat, lon: (best[0] + best[1]) / 2 } : null;
|
||||
}
|
||||
|
||||
const middleLat = (ring) => {
|
||||
const lats = ring.map(([, y]) => y);
|
||||
return (Math.min(...lats) + Math.max(...lats)) / 2;
|
||||
};
|
||||
@@ -0,0 +1,872 @@
|
||||
// Rule-based report categories, relevance and severity: the News layer's
|
||||
// base reading, shared by every news server. Multilingual stems (en, uk, ru,
|
||||
// ar, he and more) matched at a word start on normalised text; a trailing `$`
|
||||
// makes a stem whole-word. A title hit counts double. Ties go to the earlier
|
||||
// category in CATEGORY_ORDER, which runs from most to least specific.
|
||||
//
|
||||
// A news server may replace these readings with its own; the rules stay
|
||||
// as the fallback.
|
||||
|
||||
/** Text as the rules match it: folded case, one apostrophe, no vowel marks. */
|
||||
function normaliseForMatch(text) {
|
||||
return String(text || '')
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/ё/g, 'е')
|
||||
.replace(/[’ʼ`´]/g, "'")
|
||||
.replace(/[ً-ٰٟ֑-ׇ]/g, '')
|
||||
.replace(/[أإآ]/g, 'ا');
|
||||
}
|
||||
|
||||
export const CATEGORY_ORDER = Object.freeze([
|
||||
'strike',
|
||||
'alert',
|
||||
'air-defence',
|
||||
'ground',
|
||||
'casualties',
|
||||
'humanitarian',
|
||||
'infrastructure',
|
||||
'disaster',
|
||||
'protest',
|
||||
'political',
|
||||
// Business and trade: the rules' reading, or World News API's business.
|
||||
'economy',
|
||||
]);
|
||||
|
||||
// [stem, weight]; weight defaults to 1.
|
||||
const RULES = {
|
||||
strike: [
|
||||
'strike',
|
||||
'airstrike',
|
||||
'air strike',
|
||||
'missile',
|
||||
'rocket',
|
||||
'drone',
|
||||
'shelling',
|
||||
'shelled',
|
||||
'bomb',
|
||||
'explosion',
|
||||
'blast',
|
||||
'artillery',
|
||||
'shahed',
|
||||
['attack', 0.5],
|
||||
'удар',
|
||||
'ракет',
|
||||
'дрон',
|
||||
'бпла',
|
||||
'обстріл',
|
||||
'обстрел',
|
||||
'вибух',
|
||||
'взрыв',
|
||||
'шахед',
|
||||
'бомб',
|
||||
['атак', 0.5],
|
||||
'غارة',
|
||||
'غارات',
|
||||
'قصف',
|
||||
'صاروخ',
|
||||
'صواريخ',
|
||||
'مسيرة',
|
||||
'انفجار',
|
||||
['استهداف', 0.7],
|
||||
['هجوم', 0.5],
|
||||
'תקיפה',
|
||||
'טיל',
|
||||
'רקט',
|
||||
'כטב"מ',
|
||||
'פיצוץ',
|
||||
'הפצצ',
|
||||
],
|
||||
'air-defence': [
|
||||
'air defen',
|
||||
'intercept',
|
||||
'shot down',
|
||||
'downed',
|
||||
'air raid',
|
||||
'ппо',
|
||||
'збит',
|
||||
'сбит',
|
||||
'перехоп',
|
||||
'перехват',
|
||||
'повітряна тривога',
|
||||
'воздушная тревога',
|
||||
'الدفاع الجوي',
|
||||
'اعتراض',
|
||||
'יירוט',
|
||||
'יורט',
|
||||
'כיפת ברזל',
|
||||
'אזעק',
|
||||
],
|
||||
ground: [
|
||||
'advance$',
|
||||
'advances$',
|
||||
'advancing',
|
||||
'offensive',
|
||||
'captur',
|
||||
'liberat',
|
||||
'assault',
|
||||
'clash',
|
||||
'fighting',
|
||||
'counteroffensive',
|
||||
'frontline',
|
||||
'front line',
|
||||
'battle',
|
||||
'encircl',
|
||||
['troops', 0.5],
|
||||
'наступ',
|
||||
'штурм',
|
||||
'звільн',
|
||||
'освобо',
|
||||
'бої$',
|
||||
'бои$',
|
||||
'контрнаступ',
|
||||
'захоп',
|
||||
'захват',
|
||||
'оточ',
|
||||
'окруж',
|
||||
'продвиж',
|
||||
'просуван',
|
||||
'اشتباك',
|
||||
'معارك',
|
||||
'تقدم',
|
||||
'سيطر',
|
||||
'اقتحام',
|
||||
'توغل',
|
||||
'לחימה',
|
||||
'קרב',
|
||||
'פשיט',
|
||||
'תמרון',
|
||||
],
|
||||
casualties: [
|
||||
'killed',
|
||||
'dead$',
|
||||
'deaths',
|
||||
'wounded',
|
||||
'injured',
|
||||
'casualt',
|
||||
'death toll',
|
||||
'загин',
|
||||
'поранен',
|
||||
'жертв',
|
||||
'вбит',
|
||||
'погиб',
|
||||
'ранен',
|
||||
'убит',
|
||||
'قتلى',
|
||||
'شهداء',
|
||||
'شهيد',
|
||||
'جرحى',
|
||||
'مقتل',
|
||||
'اصاب',
|
||||
'הרוג',
|
||||
'נהרג',
|
||||
'פצוע',
|
||||
'נפצע',
|
||||
],
|
||||
humanitarian: [
|
||||
'evacuat',
|
||||
'aid$',
|
||||
'refugee',
|
||||
'displac',
|
||||
'humanitarian',
|
||||
'famine',
|
||||
'hunger',
|
||||
'convoy',
|
||||
'shelter',
|
||||
'евакуац',
|
||||
'эвакуац',
|
||||
'гуманітар',
|
||||
'гуманитар',
|
||||
'біженц',
|
||||
'беженц',
|
||||
'انسانية',
|
||||
'نازح',
|
||||
'نزوح',
|
||||
'مساعدات',
|
||||
'اجلاء',
|
||||
'مجاعة',
|
||||
'הומניטרי',
|
||||
'פינוי',
|
||||
'סיוע',
|
||||
],
|
||||
infrastructure: [
|
||||
'power outage',
|
||||
'blackout',
|
||||
'electricity',
|
||||
'energy',
|
||||
'grid$',
|
||||
'substation',
|
||||
'water supply',
|
||||
'bridge',
|
||||
'railway',
|
||||
'refinery',
|
||||
'port$',
|
||||
'dam$',
|
||||
'power plant',
|
||||
'енерг',
|
||||
'энерг',
|
||||
'знеструм',
|
||||
'обесточ',
|
||||
'підстанц',
|
||||
'подстанц',
|
||||
'залізниц',
|
||||
'железн',
|
||||
'нпз',
|
||||
'الكهرباء',
|
||||
'محطة',
|
||||
'مياه',
|
||||
'جسر',
|
||||
'חשמל',
|
||||
'תשתית',
|
||||
],
|
||||
disaster: [
|
||||
'earthquake',
|
||||
'flood',
|
||||
'wildfire',
|
||||
'landslide',
|
||||
'cyclone',
|
||||
'hurricane',
|
||||
'typhoon',
|
||||
'tsunami',
|
||||
'eruption',
|
||||
'glof$',
|
||||
'glacial lake',
|
||||
'storm$',
|
||||
'lightning',
|
||||
'землетрус',
|
||||
'землетрясен',
|
||||
'повін',
|
||||
'паводк',
|
||||
'наводнен',
|
||||
'زلزال',
|
||||
'فيضان',
|
||||
'سيول',
|
||||
'רעידת אדמה',
|
||||
'שיטפון',
|
||||
],
|
||||
protest: [
|
||||
'protest',
|
||||
'demonstrat',
|
||||
'rally$',
|
||||
'rallies',
|
||||
'riot',
|
||||
// Not a bare "протест": "протестировал" is "tested".
|
||||
'протест$',
|
||||
'протеста',
|
||||
'протесту',
|
||||
'протестом',
|
||||
'протесте$',
|
||||
'протесты',
|
||||
'протестов',
|
||||
'протестн',
|
||||
'протестую',
|
||||
'протестова',
|
||||
'мітинг',
|
||||
'митинг',
|
||||
'احتجاج',
|
||||
'مظاهر',
|
||||
'تظاهر',
|
||||
'הפגנ',
|
||||
'מחאה',
|
||||
],
|
||||
political: [
|
||||
'talks$',
|
||||
'negotiat',
|
||||
'sanction',
|
||||
'summit',
|
||||
'ceasefire',
|
||||
'truce',
|
||||
'peace',
|
||||
'election',
|
||||
'parliament',
|
||||
['president', 0.5],
|
||||
['minister', 0.5],
|
||||
['statement', 0.5],
|
||||
// A state visit ("Emir of Qatar arrives in Amman").
|
||||
['visit', 0.5],
|
||||
['delegation', 0.5],
|
||||
['agreement', 0.5],
|
||||
'memorandum',
|
||||
'diplomat',
|
||||
'bilateral',
|
||||
'ambassador',
|
||||
['визит', 0.5],
|
||||
['делегац', 0.5],
|
||||
'дипломат',
|
||||
'переговор',
|
||||
'санкц',
|
||||
'перемир',
|
||||
'вибори',
|
||||
'выборы',
|
||||
['президент', 0.5],
|
||||
['міністр', 0.5],
|
||||
['министр', 0.5],
|
||||
'مفاوضات',
|
||||
'عقوبات',
|
||||
'هدنة',
|
||||
'وقف اطلاق النار',
|
||||
['وزير', 0.5],
|
||||
['رئيس', 0.5],
|
||||
'משא ומתן',
|
||||
'הפסקת אש',
|
||||
'סנקצי',
|
||||
['ראש הממשלה', 0.5],
|
||||
],
|
||||
// Elections and party politics ("How Gina Hinojosa Captured Texas" is a
|
||||
// governor's race, not a battle). They count toward political only when
|
||||
// nothing physical happened (categorizeText): a strike in an election week
|
||||
// is still a strike.
|
||||
election: [
|
||||
'midterm',
|
||||
'electoral',
|
||||
'elect$',
|
||||
'ballot',
|
||||
'voter',
|
||||
'vote$',
|
||||
'votes$',
|
||||
'voting',
|
||||
'polls$',
|
||||
'candidate',
|
||||
'senate race',
|
||||
'referendum',
|
||||
'inaugurat',
|
||||
// Plurals only: "Democratic Republic of Congo", "Republican Guard".
|
||||
'democrats$',
|
||||
'republicans$',
|
||||
'gop$',
|
||||
'избира',
|
||||
'голосован',
|
||||
'виборц',
|
||||
'голосуван',
|
||||
'انتخاب',
|
||||
'בחירות',
|
||||
],
|
||||
};
|
||||
|
||||
// Business, trade, industry and energy, counted only when nothing physical
|
||||
// happened (categorizeText): an oil depot struck is a strike. English,
|
||||
// Russian, Ukrainian, Turkish and the European stems.
|
||||
RULES.economy = [
|
||||
'econom',
|
||||
'gdp$',
|
||||
'inflation',
|
||||
'investment',
|
||||
'investor',
|
||||
'export',
|
||||
'imports$',
|
||||
'import$',
|
||||
'tariff',
|
||||
'trade deal',
|
||||
'trade turnover',
|
||||
'central bank',
|
||||
'stock market',
|
||||
'budget',
|
||||
'oil and gas',
|
||||
'oilfield',
|
||||
'oil field',
|
||||
'gas field',
|
||||
'exploration',
|
||||
'drilling',
|
||||
'mining',
|
||||
'industr',
|
||||
'manufactur',
|
||||
'business',
|
||||
'company',
|
||||
'companies',
|
||||
'revenue',
|
||||
'profit',
|
||||
'merger',
|
||||
'tourism',
|
||||
'agricultur',
|
||||
'harvest',
|
||||
'экономи',
|
||||
'инвест',
|
||||
'экспорт',
|
||||
'импорт',
|
||||
'инфляц',
|
||||
'ввп$',
|
||||
'бюджет',
|
||||
'промышлен',
|
||||
'бизнес',
|
||||
'компани',
|
||||
'товарооборот',
|
||||
'економі',
|
||||
'інвест',
|
||||
'експорт',
|
||||
'промисло',
|
||||
'ekonomi',
|
||||
'yatırım',
|
||||
'ihracat',
|
||||
'ithalat',
|
||||
'enflasyon',
|
||||
'sanayi',
|
||||
'şirket',
|
||||
'wirtschaft',
|
||||
'konjunktur',
|
||||
'unternehm',
|
||||
'inversi',
|
||||
'investiss',
|
||||
'investiment',
|
||||
'empresa',
|
||||
'entreprise',
|
||||
'impresa',
|
||||
];
|
||||
|
||||
// Attack words beyond PHYSICAL's harm, which keep a report off economy.
|
||||
const ATTACK = new RegExp(
|
||||
String.raw`(?<![\p{L}])(?:attack|assault|target|hit(?![\p{L}])|fire|plot|war(?![\p{L}])|wartime|атак|удар|пораж|пожар|обстр|війн|войн|هجوم|استهداف|حرب|מתקפ|ataque|attaque|attacco|angriff|saldır)`,
|
||||
'u',
|
||||
);
|
||||
|
||||
function escapeRegex(text) {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
// Spanish, French, Portuguese, Italian and German stems, for outlets that
|
||||
// report in their own language (a train crash in Spain, in Spanish).
|
||||
const EUROPEAN = {
|
||||
strike: [
|
||||
'bombarde',
|
||||
'misil',
|
||||
'míssil',
|
||||
'dron$',
|
||||
'explosión',
|
||||
'explosão',
|
||||
'esplosi',
|
||||
'ataque',
|
||||
'attaque',
|
||||
'attacco',
|
||||
'angriff',
|
||||
'rakete',
|
||||
'luftangriff',
|
||||
],
|
||||
'air-defence': ['antiaére', 'défense aérienne', 'flugabwehr', 'abatid'],
|
||||
ground: [
|
||||
'combate',
|
||||
'combats',
|
||||
'enfrentamiento',
|
||||
'affrontement',
|
||||
'scontri',
|
||||
'gefecht',
|
||||
],
|
||||
casualties: [
|
||||
'muert',
|
||||
'fallecid',
|
||||
'herid',
|
||||
'morts$',
|
||||
'tué',
|
||||
'blessé',
|
||||
'morti',
|
||||
'ferit',
|
||||
'mortos',
|
||||
'ferido',
|
||||
'muere',
|
||||
'mueren',
|
||||
'fallece',
|
||||
'meurt',
|
||||
'morre',
|
||||
'tote$',
|
||||
'verletzt',
|
||||
'víctimas',
|
||||
'victimes',
|
||||
'vittime',
|
||||
],
|
||||
humanitarian: [
|
||||
'evacua',
|
||||
'évacu',
|
||||
'refugiad',
|
||||
'réfugi',
|
||||
'flüchtling',
|
||||
'desplazad',
|
||||
],
|
||||
infrastructure: [
|
||||
'apagón',
|
||||
'panne',
|
||||
'blackout',
|
||||
'descarril',
|
||||
'déraill',
|
||||
'deragliament',
|
||||
'entgleis',
|
||||
'accidente',
|
||||
'accident',
|
||||
'incidente',
|
||||
'choque',
|
||||
'collision',
|
||||
'collisione',
|
||||
'zusammenstoß',
|
||||
'incendio',
|
||||
'incendie',
|
||||
],
|
||||
disaster: [
|
||||
'terremoto',
|
||||
'séisme',
|
||||
'tremblement',
|
||||
'erdbeben',
|
||||
'inundaci',
|
||||
'inondation',
|
||||
'alluvion',
|
||||
'überschwemm',
|
||||
'huracán',
|
||||
'ouragan',
|
||||
'uragano',
|
||||
'tormenta',
|
||||
'tempête',
|
||||
'tempesta',
|
||||
'sturm',
|
||||
'cicl',
|
||||
'erupci',
|
||||
'éruption',
|
||||
'eruzione',
|
||||
],
|
||||
protest: [
|
||||
'protesta',
|
||||
'manifesta',
|
||||
'disturbio',
|
||||
'émeute',
|
||||
'huelga',
|
||||
'grève',
|
||||
'sciopero',
|
||||
'streik',
|
||||
'demonstration',
|
||||
],
|
||||
};
|
||||
for (const [category, stems] of Object.entries(EUROPEAN))
|
||||
RULES[category] = [...(RULES[category] || []), ...stems];
|
||||
|
||||
const COMPILED = Object.entries(RULES).map(([category, stems]) => ({
|
||||
category,
|
||||
rules: stems.map((entry) => {
|
||||
const [stem, weight = 1] = Array.isArray(entry) ? entry : [entry];
|
||||
const whole = stem.endsWith('$');
|
||||
const body = escapeRegex(
|
||||
normaliseForMatch(whole ? stem.slice(0, -1) : stem),
|
||||
).replace(/\s+/g, '\\s+');
|
||||
const arabic = /\p{Script=Arabic}/u.test(stem) ? '(?:[وفبلك]?(?:ال)?)' : '';
|
||||
const hebrew = /\p{Script=Hebrew}/u.test(stem) ? '(?:[ובלמהשכ]{0,2})' : '';
|
||||
return {
|
||||
weight,
|
||||
regex: new RegExp(
|
||||
`(?<![\\p{L}\\p{N}])${arabic}${hebrew}${body}${whole ? '(?![\\p{L}\\p{N}])' : ''}`,
|
||||
'u',
|
||||
),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
const EVENT_CATEGORIES = new Set([
|
||||
'strike',
|
||||
'air-defence',
|
||||
'ground',
|
||||
'casualties',
|
||||
'disaster',
|
||||
]);
|
||||
// Words that tie a report to armed conflict or crisis, whatever its category
|
||||
// (en, fr, ru, uk, ar, he, es).
|
||||
const CONFLICT_TERMS = new RegExp(
|
||||
[
|
||||
'war',
|
||||
'army',
|
||||
'military',
|
||||
'militar',
|
||||
'troops',
|
||||
'soldier',
|
||||
'militant',
|
||||
'jihad',
|
||||
'terror',
|
||||
'insurg',
|
||||
'rebel',
|
||||
'ceasefire',
|
||||
'truce',
|
||||
'hostage',
|
||||
'sanction',
|
||||
'shell',
|
||||
'drone',
|
||||
'missile',
|
||||
'airstrike',
|
||||
'frappe',
|
||||
'armée',
|
||||
'soldat',
|
||||
'djihad',
|
||||
'fama',
|
||||
'jnim',
|
||||
'houthi',
|
||||
'hezbollah',
|
||||
'hamas',
|
||||
'irgc',
|
||||
'rsf',
|
||||
'wagner',
|
||||
'africa corps',
|
||||
'войн',
|
||||
'війн',
|
||||
'армі',
|
||||
'арми',
|
||||
'всу',
|
||||
'зсу',
|
||||
'бпла',
|
||||
'обстр',
|
||||
'фронт',
|
||||
'حرب',
|
||||
'الجيش',
|
||||
'هجوم',
|
||||
'قصف',
|
||||
'الحوثي',
|
||||
'مسلح',
|
||||
'מלחמה',
|
||||
'צה"ל',
|
||||
'guerra',
|
||||
'ejército',
|
||||
// Violence, coercion and their aftermath.
|
||||
'massacre',
|
||||
'atrocit',
|
||||
'genocide',
|
||||
'arms',
|
||||
'weapon',
|
||||
'detain',
|
||||
'abduct',
|
||||
'kidnap',
|
||||
'air raid',
|
||||
'alert',
|
||||
'jamming',
|
||||
'тривог',
|
||||
'тревог',
|
||||
'відбій',
|
||||
'отбой',
|
||||
'occupied',
|
||||
'occupation',
|
||||
'territor',
|
||||
'convoy',
|
||||
'demining',
|
||||
'forces',
|
||||
'raid',
|
||||
'conflict',
|
||||
'putin',
|
||||
'zelensk',
|
||||
'окуп',
|
||||
'оккуп',
|
||||
// Diplomacy and strategic stakes of the conflict.
|
||||
'ambassador',
|
||||
'mediat',
|
||||
'election',
|
||||
'talks',
|
||||
'negotiat',
|
||||
'envoy',
|
||||
'diplomat',
|
||||
'foreign minister',
|
||||
'condemn',
|
||||
'nuclear',
|
||||
'hormuz',
|
||||
'blockade',
|
||||
'négociation',
|
||||
'переговор',
|
||||
'перемир',
|
||||
'مفاوضات',
|
||||
'هدنة',
|
||||
]
|
||||
// Short words are whole words ("war" is not "warning" or "Warsaw").
|
||||
.map((w) => `(?<![\\p{L}])${w}${w.length < 5 ? '(?![\\p{L}])' : ''}`)
|
||||
.join('|'),
|
||||
'iu',
|
||||
);
|
||||
|
||||
/**
|
||||
* How much a report matters to its hotspot, by rule: `core` for a physical conflict or crisis event, `related` for
|
||||
* news tied to the conflict (by wording, or because the source covers
|
||||
* nothing else), `minor` for the rest of what a broad outlet publishes
|
||||
* (prices, sport, health, culture).
|
||||
*/
|
||||
const termPatterns = new Map();
|
||||
/** A word-start pattern for a hotspot term ("pow" must not match "power"). */
|
||||
function termPattern(term) {
|
||||
if (!termPatterns.has(term))
|
||||
termPatterns.set(
|
||||
term,
|
||||
new RegExp(
|
||||
// Short terms are whole words ("pow" is not "power"); longer ones are
|
||||
// stems ("mobiliz" → mobilized, mobilization).
|
||||
`(?<![\\p{L}])${normaliseForMatch(term).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}${term.length < 5 ? '(?![\\p{L}])' : ''}`,
|
||||
'u',
|
||||
),
|
||||
);
|
||||
return termPatterns.get(term);
|
||||
}
|
||||
|
||||
export function relevanceOf({
|
||||
category,
|
||||
tags = [],
|
||||
title = '',
|
||||
summary = '',
|
||||
dedicated = false,
|
||||
relatedTerms = [],
|
||||
floor = 'minor',
|
||||
}) {
|
||||
const text = normaliseForMatch(`${title} ${summary}`);
|
||||
// A hotspot's own vocabulary counts as conflict wording there (Iran:
|
||||
// "Qalibaf", "IAEA"; Israel: "settler"; Ukraine: "prisoner exchange").
|
||||
const conflict =
|
||||
CONFLICT_TERMS.test(text) ||
|
||||
relatedTerms.some((term) => termPattern(term).test(text));
|
||||
// Any event reading counts, even when another category wins the title
|
||||
// ("the accident toll rises to 74": infrastructure first, casualties too).
|
||||
if (
|
||||
EVENT_CATEGORIES.has(category) ||
|
||||
tags.some((tag) => EVENT_CATEGORIES.has(tag))
|
||||
)
|
||||
return 'core';
|
||||
if (conflict && ['humanitarian', 'infrastructure'].includes(category))
|
||||
return 'core';
|
||||
if (conflict || dedicated || category === 'humanitarian') return 'related';
|
||||
return floor;
|
||||
}
|
||||
|
||||
// Alerts: air-raid alerts and reports of drones or missiles on their way
|
||||
// ("Реактивний БпЛА курсом на Полтаву", "КАБи на Донеччину", "drone heading
|
||||
// for Kyiv", "➡️"). Something is in the air; nothing has hit yet. Most of an
|
||||
// air force's channel is these, and as "strikes" they would merge into real
|
||||
// strike events and inflate them.
|
||||
// A direction counts only after a weapon ("БпЛА … з півдня"), so a convoy
|
||||
// leaving "in the direction of Oleshky" is not an alert.
|
||||
const WEAPON =
|
||||
'(?:бпла|дрон|шахед|герань|ракет|каб|балістик|крилат|боєприпас|боеприпас|uav|drone|missile|shahed|ballistic|cruise|munition)';
|
||||
const DIRECTION =
|
||||
'(?:курсом на|у напрямку|в напрямку|в направлении|у бік|в сторону|повз |з (?:північ|півден|схід|сход|захід|заход)|с (?:север|юг|восток|запад)|на |над |heading |on course|toward)';
|
||||
const ALERT = new RegExp(
|
||||
`${WEAPON}[^.!?]{0,40}${DIRECTION}|^[^\\p{L}]*курсом на|тривог|тревог|загроза застосування|угроза применения|air[- ]raid|threat of (?:missile|drone|ballistic|uav)|[➡⬅⬆⬇↗↘↙↖]`,
|
||||
'u',
|
||||
);
|
||||
// Wording that something did hit: then it is a strike (or air defence), not an alert.
|
||||
const IMPACT =
|
||||
/влуч|вибух|уражен|пошкодж|загин|поранен|зруйн|пожеж|атак|удар по|збит|знищ|попадан|взрыв|поражен|поврежд|погиб|ранен|разруш|сбит|уничтож|\bhit\b|\bhits\b|struck|explosion|blast|killed|injur|wounded|damage|destroy|fire\b|shot down|intercept|attack/u;
|
||||
|
||||
/** Whether a report's title is an alert: a threat on its way, nothing hit yet. */
|
||||
function isAlertText(title = '', summary = '') {
|
||||
const t = normaliseForMatch(`${title} ${summary}`.slice(0, 400));
|
||||
return ALERT.test(t) && !IMPACT.test(t);
|
||||
}
|
||||
|
||||
// "Hit" or "struck" says nothing on its own: what hit decides (a missile is a
|
||||
// strike, a flood or lightning a disaster), and those words score by
|
||||
// themselves. A few phrases use a category's word for another thing.
|
||||
const PHRASES = [
|
||||
[/storm shadow/gu, 'missile'],
|
||||
[/lightning strikes?/gu, 'lightning'],
|
||||
[
|
||||
/(?:general|hunger|labou?r|workers?|nationwide|national|transport|rail|teachers?|doctors?|nurses?) strikes?|on strike|strike action/gu,
|
||||
'protest',
|
||||
],
|
||||
];
|
||||
const rephrase = (text) =>
|
||||
PHRASES.reduce((out, [re, word]) => out.replace(re, word), text);
|
||||
|
||||
// An election story borrows the words of war and disaster ("‘An Earthquake’:
|
||||
// A Democratic Rout", "captured Texas", "a bloodbath for Republicans"). With
|
||||
// election wording and nothing physical (no weapon, no one hurt, no quake's
|
||||
// magnitude), the event categories give way to political.
|
||||
const ELECTION =
|
||||
/(?<![\p{L}])(?:election|midterm|electoral|ballot|voters?(?![\p{L}])|votes?(?![\p{L}])|voting|polls(?![\p{L}])|senate race|referendum|democrats|republicans|gop(?![\p{L}])|[\p{L}]+-elect(?![\p{L}])|выбор|избира|вибор|голосув|голосов|انتخاب|בחירות)/u;
|
||||
const PHYSICAL =
|
||||
/(?<![\p{L}])(?:kill|dead(?![\p{L}])|fighting|clash|air ?strike|strikes?(?![\p{L}])|struck|destroy|downed|ablaze|on fire|catch(?:es)? fire|caught fire|naval mine|landmine|shot down|sunk|sank|deaths?|injur|wounded|casualt|troops|soldier|missile|drone|rocket|shell(?:ing|ed)|artiller|explosi|blast|bomb|gunfire|shot(?![\p{L}])|shooting|magnitude|richter|tremor|evacuat|flood(?:ed|ing|waters)|убит|погиб|ранен|ракет|дрон|обстрел|загин|поранен|обстріл|قتل|جرح|صاروخ|הרג|פצוע|טיל)/u;
|
||||
/** The categories of a physical event (an alert is a threat, not yet one). */
|
||||
const EVENT_KINDS = new Set([
|
||||
'strike',
|
||||
'air-defence',
|
||||
'ground',
|
||||
'casualties',
|
||||
'disaster',
|
||||
'infrastructure',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Categorise a report from its title and summary.
|
||||
* @returns {{category: string, tags: string[]}}
|
||||
*/
|
||||
export function categorizeText({ title = '', summary = '' } = {}) {
|
||||
if (isAlertText(title)) return { category: 'alert', tags: ['alert'] };
|
||||
const t = rephrase(normaliseForMatch(title));
|
||||
const s = rephrase(normaliseForMatch(summary));
|
||||
const scores = new Map();
|
||||
for (const { category, rules } of COMPILED) {
|
||||
let score = 0;
|
||||
for (const { regex, weight } of rules) {
|
||||
if (regex.test(t)) score += 2 * weight;
|
||||
else if (regex.test(s)) score += weight;
|
||||
}
|
||||
if (score > 0) scores.set(category, score);
|
||||
}
|
||||
const all = `${t} ${s}`;
|
||||
const election = scores.get('election') || 0;
|
||||
scores.delete('election');
|
||||
const physical = PHYSICAL.test(all);
|
||||
// Business words and no harm or attack: "advance exploration" is no
|
||||
// front-line advance; "attack an industrial facility" stays a strike.
|
||||
if (physical || ATTACK.test(all)) scores.delete('economy');
|
||||
else if (scores.has('economy'))
|
||||
for (const kind of EVENT_KINDS) scores.delete(kind);
|
||||
if (!physical) {
|
||||
if (election)
|
||||
scores.set('political', (scores.get('political') || 0) + election);
|
||||
if (ELECTION.test(all)) {
|
||||
for (const kind of EVENT_KINDS) scores.delete(kind);
|
||||
scores.set('political', Math.max(scores.get('political') || 0, 1));
|
||||
}
|
||||
}
|
||||
if (!scores.size) return { category: 'other', tags: [] };
|
||||
const ranked = CATEGORY_ORDER.filter((c) => scores.has(c)).sort(
|
||||
(a, b) => scores.get(b) - scores.get(a),
|
||||
);
|
||||
return { category: ranked[0], tags: ranked };
|
||||
}
|
||||
|
||||
// Severity by rule, for reports without a severity of their own (0 none,
|
||||
// 1 minor incident, 2 significant: deaths, injuries or real damage, 3 major:
|
||||
// mass casualties). Wording in en, uk, ru, ar, he, es, fr, de.
|
||||
const SEVERITY_EVENTS = new Set([...EVENT_CATEGORIES, 'infrastructure']);
|
||||
const MAJOR_HARM =
|
||||
/mass casualt|massacre|dozens (?:of \p{L}+ )?(?:killed|dead)|hundreds (?:of \p{L}+ )?(?:killed|dead)|масов\p{L}* (?:жертв|загибел|гибел)|десятки (?:загибл|погибш|убит|вбит|людей загин|человек погиб)|مجزرة|عشرات (?:القتلى|الشهداء)|טבח/u;
|
||||
const HARM_WORDS =
|
||||
'kill|dead|died|death|injur|wound|casualt|загин|загибл|погиб|убит|вбит|поранен|ранен|постражд|пострадал|травм|قتل|قتيل|شهيد|شهداء|جرح|جريح|إصاب|اصاب|נהרג|הרוג|פצוע|muert|herid|tué|mort|bless|getötet|tote|verletz';
|
||||
const HARM = new RegExp(String.raw`(?<![\p{L}])(?:${HARM_WORDS})`, 'u');
|
||||
// "No casualties", "без жертв": the harm word is there, the harm is not.
|
||||
const NO_HARM =
|
||||
/(?:no|without|zero) (?:casualt|injur|deaths|victims|one (?:was )?(?:hurt|injured))|без (?:жертв|постраждал|пострадавш|загибл|погибш)|не постраждал|не пострадал|لا (?:إصابات|اصابات)|אין נפגעים|sin (?:víctimas|heridos)|sans (?:victime|blessé)/u;
|
||||
const DAMAGE =
|
||||
/destroy|damag|ablaze|on fire|fire broke|explosion|collapse|зруйн|разруш|пошкодж|поврежд|пожеж|пожар|вибух|взрыв|دمار|تدمير|انفجار|حريق|הרס|פיצוץ|שריפה|destru|incendi|explos|zerstör/u;
|
||||
// An age ("a 71-year-old woman", "71-річна", "71-летний") is not a count.
|
||||
const NUMBER = String.raw`(\d{1,3}(?:[,.\s]\d{3})+|\d{1,5})(?![\d,.]*[-\s]*(?:year|yr|річн|рок|летн|год))`;
|
||||
const COUNTS = [
|
||||
// "14 killed", "three people dead" is left to the words; "14 civilians dead".
|
||||
new RegExp(String.raw`${NUMBER}\s+(?:\p{L}+\s+){0,2}(?:${HARM_WORDS})`, 'gu'),
|
||||
// "killing 14", "death toll rises to 74", "kills at least 20".
|
||||
new RegExp(
|
||||
String.raw`(?:kill\p{L}*|toll\p{L}*(?:\s+\p{L}+){0,3}|загинул\p{L}*|погибл\p{L}*|жертв\p{L}*)\s+(?:at least\s+|не менее\s+|щонайменше\s+|до\s+|to\s+)?${NUMBER}`,
|
||||
'gu',
|
||||
),
|
||||
];
|
||||
|
||||
function largestCount(text) {
|
||||
let most = 0;
|
||||
for (const pattern of COUNTS)
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
const n = Number(match[1].replace(/[,.\s]/g, ''));
|
||||
// A year ("since 2022 killed…") is not a toll.
|
||||
if (n < 1900 || n > 2100) most = Math.max(most, n);
|
||||
}
|
||||
return most;
|
||||
}
|
||||
|
||||
/** A report's severity by rule, 0–3. */
|
||||
export function severityByRules({
|
||||
category,
|
||||
tags = [],
|
||||
title = '',
|
||||
summary = '',
|
||||
}) {
|
||||
const text = normaliseForMatch(`${title} ${summary}`);
|
||||
const harmed = HARM.test(text) && !NO_HARM.test(text);
|
||||
if (MAJOR_HARM.test(text) || (harmed && largestCount(text) >= 10)) return 3;
|
||||
const event =
|
||||
SEVERITY_EVENTS.has(category) ||
|
||||
tags.some((tag) => SEVERITY_EVENTS.has(tag));
|
||||
if (harmed && (event || category === 'humanitarian')) return 2;
|
||||
if (event && DAMAGE.test(text)) return 2;
|
||||
return event ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
// GDELT 2.0 events for the Conflicts section, from the 15-minute export
|
||||
// files (data.gdeltproject.org, plain downloads; no key, and not the
|
||||
// rate-limited search API). Each export is one zipped tab-separated table of
|
||||
// machine-coded events, each placed by GDELT with a point and a place type.
|
||||
//
|
||||
// A story counts when GDELT coded physical violence in it (CAMEO roots 18
|
||||
// assault, 19 fight, 20 mass violence); its place is read from all its
|
||||
// placed events (choosePlace). GDELT's actor fields are machine-coded and
|
||||
// often wrong, so no report says who did what: a report is the story (its
|
||||
// article, and the copies other outlets ran under the same address words).
|
||||
// The events carry no headline: a story's title is its page title from the
|
||||
// GKG export of the same quarter hour (read for the newest hours only, it
|
||||
// runs to 6 MB), else the words of its address. All of it is rules over
|
||||
// GDELT's own fields; nothing reads the articles.
|
||||
|
||||
import { promisify } from 'node:util';
|
||||
import { inflateRaw } from 'node:zlib';
|
||||
|
||||
import { readResponseBytesCapped } from '../common/http.js';
|
||||
import { categorizeText, relevanceOf, severityByRules } from './categorize.js';
|
||||
import { UpstreamError, unescapeHtml, webLink } from './upstream.js';
|
||||
|
||||
const EXPORTS_URL = 'https://data.gdeltproject.org/gdeltv2/';
|
||||
const STEP_MS = 15 * 60_000;
|
||||
// An events export runs to about 100 KB zipped and 500 KB unzipped; a GKG
|
||||
// export to about 6 MB and 18 MB. Unzipped off the main thread.
|
||||
const MAX_ZIP_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_TABLE_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_GKG_ZIP_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_GKG_TABLE_BYTES = 32 * 1024 * 1024;
|
||||
const inflate = promisify(inflateRaw);
|
||||
// The most words an address's words make a title of.
|
||||
const MAX_ADDRESS_WORDS = 24;
|
||||
const TIMEOUT_MS = 30_000;
|
||||
const MAX_PLACES = 3;
|
||||
|
||||
// Columns of the 2.0 events table (61).
|
||||
const COL = {
|
||||
id: 0,
|
||||
eventCode: 26,
|
||||
rootCode: 28,
|
||||
quadClass: 29,
|
||||
mentions: 31,
|
||||
geoType: 51,
|
||||
place: 52,
|
||||
lat: 56,
|
||||
lon: 57,
|
||||
added: 59,
|
||||
url: 60,
|
||||
};
|
||||
|
||||
// CAMEO event codes as the News layer's categories, and as words for an
|
||||
// article whose address carries none of its own.
|
||||
const EVENTS = [
|
||||
// Aerial weapons, artillery and tanks, bombings.
|
||||
[/^19[45]|^183/, 'strike', 'Strike reported'],
|
||||
[/^186|^185/, 'casualties', 'Killing reported'],
|
||||
[/^181/, 'humanitarian', 'Abduction reported'],
|
||||
[/^20/, 'casualties', 'Mass violence reported'],
|
||||
[/^19/, 'ground', 'Fighting reported'],
|
||||
[/^18/, 'other', 'Violence reported'],
|
||||
];
|
||||
const eventKind = (code) =>
|
||||
EVENTS.find(([pattern]) => pattern.test(code)) || EVENTS.at(-1);
|
||||
|
||||
// GDELT's place types: 1 country, 2 US state, 3 US city, 4 world city,
|
||||
// 5 world state.
|
||||
const PRECISION = {
|
||||
1: 'country',
|
||||
2: 'region',
|
||||
3: 'city',
|
||||
4: 'city',
|
||||
5: 'region',
|
||||
};
|
||||
|
||||
/** The export holding the events GDELT added in the 15 minutes before `ms`. */
|
||||
export function exportUrl(ms) {
|
||||
const at = new Date(Math.floor(ms / STEP_MS) * STEP_MS);
|
||||
const stamp = at.toISOString().replace(/[-:T]/g, '').slice(0, 14);
|
||||
return `${EXPORTS_URL}${stamp}.export.CSV.zip`;
|
||||
}
|
||||
|
||||
/** An events export's quarter hour (ms), from its name, or NaN. */
|
||||
export function exportAt(url) {
|
||||
const match = /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)00\.export\.CSV\.zip$/.exec(
|
||||
url,
|
||||
);
|
||||
return match
|
||||
? Date.UTC(match[1], match[2] - 1, match[3], match[4], match[5])
|
||||
: NaN;
|
||||
}
|
||||
|
||||
const LASTUPDATE_URL = `${EXPORTS_URL}lastupdate.txt`;
|
||||
|
||||
/**
|
||||
* The time of the newest events export GDELT lists as published, in ms, or
|
||||
* null when its list cannot be read. Asking for one not listed yet would
|
||||
* be answered 404, and GDELT's CDN keeps that 404 for an hour.
|
||||
*/
|
||||
export async function fetchLatestExport({ fetchImpl, signal } = {}) {
|
||||
try {
|
||||
const response = await fetchImpl(LASTUPDATE_URL, {
|
||||
redirect: 'error',
|
||||
signal: signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)])
|
||||
: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
return null;
|
||||
}
|
||||
const text = new TextDecoder().decode(
|
||||
await readResponseBytesCapped(response, 16 * 1024, signal),
|
||||
);
|
||||
const at = exportAt(
|
||||
/\S+\.export\.CSV\.zip/.exec(text)?.[0].replace(/^http:/, 'https:') || '',
|
||||
);
|
||||
return Number.isFinite(at) ? at : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The GKG export of the same quarter hour as an events export. */
|
||||
export const gkgUrl = (eventsUrl) =>
|
||||
eventsUrl.replace(/\.export\.CSV\.zip$/, '.gkg.csv.zip');
|
||||
|
||||
/** The day's exports up to `now`, newest first. */
|
||||
export function exportsOfDay(now, hours = 24) {
|
||||
const urls = [];
|
||||
const last = Math.floor(now / STEP_MS) * STEP_MS;
|
||||
for (let ms = last; ms > now - hours * 3_600_000; ms -= STEP_MS)
|
||||
urls.push(exportUrl(ms));
|
||||
return urls;
|
||||
}
|
||||
|
||||
/** The one table inside an export's zip, as text, up to `maxBytes`. */
|
||||
export async function unzipExport(bytes, maxBytes = MAX_TABLE_BYTES) {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const fail = () => {
|
||||
throw new UpstreamError('GDELT export unreadable', { unreadable: true });
|
||||
};
|
||||
if (bytes.length < 30 || view.getUint32(0, true) !== 0x04034b50) fail();
|
||||
// The central directory has the sizes; a local header may leave them 0.
|
||||
let eocd = -1;
|
||||
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 0x10015); i--)
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocd = i;
|
||||
break;
|
||||
}
|
||||
if (eocd < 0) fail();
|
||||
const dir = view.getUint32(eocd + 16, true);
|
||||
if (dir + 46 > bytes.length || view.getUint32(dir, true) !== 0x02014b50)
|
||||
fail();
|
||||
const method = view.getUint16(dir + 10, true);
|
||||
const compressed = view.getUint32(dir + 20, true);
|
||||
const local = view.getUint32(dir + 42, true);
|
||||
if (local + 30 > bytes.length || view.getUint32(local, true) !== 0x04034b50)
|
||||
fail();
|
||||
const start =
|
||||
local +
|
||||
30 +
|
||||
view.getUint16(local + 26, true) +
|
||||
view.getUint16(local + 28, true);
|
||||
if (start + compressed > bytes.length) fail();
|
||||
const data = bytes.subarray(start, start + compressed);
|
||||
try {
|
||||
if (method === 0 && data.length > maxBytes) fail();
|
||||
const table =
|
||||
method === 0
|
||||
? data
|
||||
: method === 8
|
||||
? await inflate(data, { maxOutputLength: maxBytes })
|
||||
: fail();
|
||||
return new TextDecoder().decode(table);
|
||||
} catch (error) {
|
||||
if (error instanceof UpstreamError) throw error;
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An article's address as the reports carry it: https, an http one
|
||||
* upgraded (GDELT keeps the address as it found it), else null.
|
||||
*/
|
||||
export const articleLink = (value) =>
|
||||
webLink(value) || webLink(String(value ?? '').replace(/^http:/, 'https:'));
|
||||
|
||||
/**
|
||||
* The placed events of an export's table, of the stories with physical
|
||||
* violence in them: those events, and every other placed event of the same
|
||||
* stories (they help place it).
|
||||
*/
|
||||
export function parseEvents(table) {
|
||||
const all = [];
|
||||
for (const line of table.split('\n')) {
|
||||
const f = line.split('\t');
|
||||
if (f.length < 61) continue;
|
||||
const violent =
|
||||
f[COL.quadClass] === '4' && ['18', '19', '20'].includes(f[COL.rootCode]);
|
||||
const precision = PRECISION[f[COL.geoType]];
|
||||
const lat = Number(f[COL.lat]);
|
||||
const lon = Number(f[COL.lon]);
|
||||
const url = articleLink(f[COL.url]);
|
||||
const added = /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/.exec(f[COL.added]);
|
||||
if (
|
||||
!precision ||
|
||||
!f[COL.lat] ||
|
||||
!f[COL.lon] ||
|
||||
!Number.isFinite(lat) ||
|
||||
!Number.isFinite(lon) ||
|
||||
Math.abs(lat) > 90 ||
|
||||
Math.abs(lon) > 180 ||
|
||||
(lat === 0 && lon === 0) ||
|
||||
!url ||
|
||||
!added
|
||||
)
|
||||
continue;
|
||||
all.push({
|
||||
id: f[COL.id],
|
||||
code: f[COL.eventCode],
|
||||
violent,
|
||||
lat,
|
||||
lon,
|
||||
place: f[COL.place].trim() || null,
|
||||
precision,
|
||||
mentions: Math.max(1, Number(f[COL.mentions]) || 1),
|
||||
addedAt: `${added[1]}-${added[2]}-${added[3]}T${added[4]}:${added[5]}:${added[6]}.000Z`,
|
||||
url,
|
||||
});
|
||||
}
|
||||
const stories = new Set(all.filter((e) => e.violent).map(storyKey));
|
||||
return all.filter((e) => stories.has(storyKey(e)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The words of an article's address, when it is written in them
|
||||
* ("three-children-die-in-peshawar-cylinder-exp"), as a sentence; else null.
|
||||
*/
|
||||
export function addressWords(url) {
|
||||
let path;
|
||||
try {
|
||||
path = decodeURIComponent(new URL(url).pathname);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const segment = path
|
||||
.split('/')
|
||||
.map((part) => part.replace(/\.(?:s?html?|php|aspx?)$/i, ''))
|
||||
.filter((part) => /[-_]/.test(part))
|
||||
.sort((a, b) => b.length - a.length)[0];
|
||||
if (!segment) return null;
|
||||
const words = segment.split(/[-_]+/).filter(Boolean);
|
||||
const lettered = words.filter((word) => /^\p{L}+$/u.test(word));
|
||||
if (lettered.length < 4 || lettered.length < 0.7 * words.length) return null;
|
||||
// Numbers stay ("killed nearly 500"); an id does not: a word of letters
|
||||
// and digits, five digits or more, or four or more at either end.
|
||||
const kept = words.filter(
|
||||
(word, i) =>
|
||||
/^\p{L}+$/u.test(word) ||
|
||||
(/^\d{1,4}$/.test(word) &&
|
||||
!(word.length === 4 && (i === 0 || i === words.length - 1))),
|
||||
);
|
||||
const text = kept.slice(0, MAX_ADDRESS_WORDS).join(' ').toLowerCase();
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Address words with the places the story is at written as names
|
||||
* ("killed in amman" → "killed in Amman"), and "u s" as "US".
|
||||
*/
|
||||
export function withNames(words, places) {
|
||||
let text = words.replace(/(?<![\p{L}])u s(?![\p{L}])/gu, 'US');
|
||||
const names = new Set(
|
||||
places.flatMap((place) =>
|
||||
String(place.place ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.replace(/\(.*?\)/g, '').trim())
|
||||
.filter((part) => part.length > 2 && !/\(general\)/.test(part)),
|
||||
),
|
||||
);
|
||||
for (const name of names) {
|
||||
const pattern = new RegExp(
|
||||
`(?<![\\p{L}])${name.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}])`,
|
||||
'gu',
|
||||
);
|
||||
text = text.replace(pattern, name);
|
||||
}
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
// A page title's site part: " | The Daily Example", " - Wire Service".
|
||||
const SITE_PART = /\s+[|–—-]\s+([^|–—-]{2,60})$/u;
|
||||
|
||||
/**
|
||||
* A page title as a headline: entities decoded, the site's name after a
|
||||
* bar or dash taken off (when the headline before it is still one), or
|
||||
* null when it is too short to be one.
|
||||
*/
|
||||
export function cleanTitle(raw) {
|
||||
// An agency's tag set on with a bare hyphen ("…attack-Newswire", "…-X").
|
||||
let title = unescapeHtml(raw).replace(
|
||||
// After a word in lower case: "Jean-Pierre" keeps its name.
|
||||
/(?<=(?:^|\s)\p{Ll}\p{L}*|[\p{N}'")])-\p{Lu}\p{L}{0,15}$/u,
|
||||
'',
|
||||
);
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const match = SITE_PART.exec(title);
|
||||
if (!match) break;
|
||||
const rest = title.slice(0, match.index);
|
||||
if (rest.split(/\s+/).length < 4 || match[1].split(/\s+/).length > 6) break;
|
||||
title = rest;
|
||||
}
|
||||
title = title.trim().slice(0, 300);
|
||||
return title.length >= 12 && title.split(/\s+/).length >= 3 ? title : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GKG page titles by article address (as articleLink writes it), for the
|
||||
* addresses in `wanted`.
|
||||
*/
|
||||
export function parseTitles(table, wanted) {
|
||||
const titles = new Map();
|
||||
for (const line of table.split('\n')) {
|
||||
const f = line.split('\t');
|
||||
const url = f[4] && articleLink(f[4]);
|
||||
if (!url || !wanted.has(url)) continue;
|
||||
const match = /<PAGE_TITLE>(.*?)<\/PAGE_TITLE>/s.exec(f.at(-1) || '');
|
||||
const title = match && cleanTitle(match[1]);
|
||||
if (title) titles.set(url, title);
|
||||
}
|
||||
return titles;
|
||||
}
|
||||
|
||||
/**
|
||||
* The story an event belongs to: its article's address words, which the
|
||||
* copies other outlets run share (an agency story), else its address.
|
||||
*/
|
||||
export function storyKey(event) {
|
||||
return addressWords(event.url)?.toLowerCase() || event.url;
|
||||
}
|
||||
|
||||
const PLACE_WORD = (name) =>
|
||||
new RegExp(
|
||||
`(?<![\\p{L}])${name.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}s?(?![\\p{L}])`,
|
||||
'u',
|
||||
);
|
||||
/** Whether the words name a place's town or its country ("jordans" too). */
|
||||
function namedIn(words, place) {
|
||||
if (!words || !place) return false;
|
||||
const parts = place
|
||||
.split(',')
|
||||
.map((part) => part.replace(/\(.*?\)/g, '').trim())
|
||||
.filter((part) => part.length > 2);
|
||||
return [parts[0], parts.at(-1)].some(
|
||||
(part) => part && PLACE_WORD(part).test(words.toLowerCase()),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A story's places, best first, from all its placed events. GDELT places
|
||||
* an event at a bare country when the text only names a nationality ("a
|
||||
* Sri Lankan embassy", an Australian outlet's own country), so a town or
|
||||
* region wins over a country; of those, the ones the article's own words
|
||||
* name; then the most mentioned.
|
||||
*/
|
||||
export function choosePlaces(events, words) {
|
||||
const byPlace = new Map();
|
||||
for (const event of events) {
|
||||
const key = `${event.lat},${event.lon}`;
|
||||
const place = byPlace.get(key) || { ...event, mentions: 0 };
|
||||
place.mentions += event.mentions;
|
||||
byPlace.set(key, place);
|
||||
}
|
||||
let places = [...byPlace.values()];
|
||||
const specific = places.filter((p) => p.precision !== 'country');
|
||||
if (specific.length) places = specific;
|
||||
const named = places.filter((p) => namedIn(words, p.place));
|
||||
if (named.length) places = named;
|
||||
return places.sort((a, b) => b.mentions - a.mentions).slice(0, MAX_PLACES);
|
||||
}
|
||||
|
||||
// The earlier of two events: by the time GDELT added it, then by its id.
|
||||
const earlier = (a, b) =>
|
||||
b.addedAt < a.addedAt ||
|
||||
(b.addedAt === a.addedAt && Number(b.id) < Number(a.id))
|
||||
? b
|
||||
: a;
|
||||
|
||||
/**
|
||||
* One report per story (storyKey), its address and id the first copy's (an
|
||||
* export adding a more-mentioned event keeps both), placed by choosePlaces,
|
||||
* titled by a copy's page title (`titleOf`), else its address words, else
|
||||
* its violent event.
|
||||
*/
|
||||
export function eventReports(events, { titleOf = () => null } = {}) {
|
||||
const stories = new Map();
|
||||
for (const event of events) {
|
||||
const key = storyKey(event);
|
||||
const list = stories.get(key) || [];
|
||||
list.push(event);
|
||||
stories.set(key, list);
|
||||
}
|
||||
const reports = [];
|
||||
for (const list of stories.values()) {
|
||||
const violent = list
|
||||
.filter((e) => e.violent !== false)
|
||||
.sort(
|
||||
(a, b) => b.mentions - a.mentions || a.addedAt.localeCompare(b.addedAt),
|
||||
);
|
||||
if (!violent.length) continue;
|
||||
const [lead] = violent;
|
||||
const first = list.reduce(earlier);
|
||||
const { url } = first;
|
||||
const address = addressWords(url);
|
||||
const places = choosePlaces(list, address);
|
||||
const [, eventCategory, words] = eventKind(lead.code);
|
||||
const page = [url, ...list.map((e) => e.url)]
|
||||
.map((copy) => titleOf(copy))
|
||||
.find(Boolean);
|
||||
const own = page || (address ? withNames(address, places) : null);
|
||||
const title = own || eventTitle(words, places[0].place);
|
||||
// The article's words decide whether it is conflict, as any headline's
|
||||
// would: GDELT codes an election story as "fighting" too. GDELT's code
|
||||
// names the kind only where the words read as conflict without naming
|
||||
// one. A story with no words at all has GDELT's code alone to go by,
|
||||
// which is not enough to list it under Conflicts: it is minor (kept
|
||||
// for Local) until a page title comes in.
|
||||
const read = own ? categorizeText({ title: own }) : null;
|
||||
const tags = read?.tags || [];
|
||||
const relevance = read
|
||||
? relevanceOf({ category: read.category, tags, title: own })
|
||||
: 'minor';
|
||||
const category = !read
|
||||
? eventCategory
|
||||
: read.category !== 'other'
|
||||
? read.category
|
||||
: relevance === 'minor'
|
||||
? 'other'
|
||||
: eventCategory;
|
||||
const publisher = new URL(url).hostname.replace(/^www\./, '');
|
||||
const geo = ({ lat, lon, place, precision }) => ({
|
||||
lat,
|
||||
lon,
|
||||
place,
|
||||
precision,
|
||||
confidence: precision === 'city' ? 0.6 : 0.3,
|
||||
mappable: true,
|
||||
method: 'source',
|
||||
});
|
||||
reports.push({
|
||||
id: `gdelt-${first.id}`,
|
||||
title,
|
||||
url,
|
||||
publisher,
|
||||
source: { name: publisher, attribution: 'GDELT Project' },
|
||||
kind: 'gdelt',
|
||||
side: 'unknown',
|
||||
category,
|
||||
relevance,
|
||||
severity: Math.max(
|
||||
1,
|
||||
severityByRules({ category, tags, title: own || '' }),
|
||||
),
|
||||
severityBy: 'rules',
|
||||
publishedAt: first.addedAt,
|
||||
geo: geo(places[0]),
|
||||
locations: places.slice(1).map(geo),
|
||||
media: [],
|
||||
mentions: list.reduce((sum, e) => sum + e.mentions, 0),
|
||||
copies: new Set(list.map((e) => e.url)).size,
|
||||
// A title of the event's words and its place, when the address had
|
||||
// none: a renamed place renames it (eventTitle).
|
||||
...(own ? {} : { eventWords: words }),
|
||||
titled: page ? 'page' : own ? 'address' : 'event',
|
||||
});
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
|
||||
/** The title of a report without address words, at its (renamed) place. */
|
||||
export const eventTitle = (words, place) =>
|
||||
place ? `${words} in ${place}` : words;
|
||||
|
||||
/**
|
||||
* One export's table, or null while GDELT has not published it (GDELT
|
||||
* lists the newest in lastupdate.txt; see fetchLatestExport).
|
||||
*/
|
||||
async function fetchTable(url, { fetchImpl, signal, maxBytes, tableBytes }) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
redirect: 'error',
|
||||
signal: signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)])
|
||||
: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch {
|
||||
throw new UpstreamError('GDELT exports unreachable');
|
||||
}
|
||||
if (response.status === 404) {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
throw new UpstreamError(`GDELT exports answered ${response.status}`, {
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
let bytes;
|
||||
try {
|
||||
bytes = await readResponseBytesCapped(response, maxBytes, signal);
|
||||
} catch (error) {
|
||||
// Over the cap stays over it; a read cut short may succeed again.
|
||||
throw new UpstreamError('GDELT export unreadable', {
|
||||
unreadable: error?.code === 'RESPONSE_TOO_LARGE',
|
||||
});
|
||||
}
|
||||
return unzipExport(bytes, tableBytes);
|
||||
}
|
||||
|
||||
/** One events export's events, or null while it is not published yet. */
|
||||
export async function fetchExport(url, { fetchImpl, signal } = {}) {
|
||||
const table = await fetchTable(url, {
|
||||
fetchImpl,
|
||||
signal,
|
||||
maxBytes: MAX_ZIP_BYTES,
|
||||
tableBytes: MAX_TABLE_BYTES,
|
||||
});
|
||||
return table === null ? null : parseEvents(table);
|
||||
}
|
||||
|
||||
/**
|
||||
* The page titles a GKG export holds for the addresses in `wanted`, or null
|
||||
* while it is not published yet.
|
||||
*/
|
||||
export async function fetchTitles(url, wanted, { fetchImpl, signal } = {}) {
|
||||
const table = await fetchTable(url, {
|
||||
fetchImpl,
|
||||
signal,
|
||||
maxBytes: MAX_GKG_ZIP_BYTES,
|
||||
tableBytes: MAX_GKG_TABLE_BYTES,
|
||||
});
|
||||
return table === null ? null : parseTitles(table, wanted);
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
addressWords,
|
||||
cleanTitle,
|
||||
gkgUrl,
|
||||
parseTitles,
|
||||
withNames,
|
||||
eventReports,
|
||||
exportsOfDay,
|
||||
exportUrl,
|
||||
fetchExport,
|
||||
parseEvents,
|
||||
unzipExport,
|
||||
} from './gdeltEvents.js';
|
||||
import { eventRow, gkgRow, zipTable } from './gdeltFixtures.mjs';
|
||||
|
||||
const ARTICLE =
|
||||
'https://www.wire.example/rubric-ato/3912-russian-drones-attack-kharkiv-overnight-three-killed.html';
|
||||
|
||||
test('the day is 96 exports, one each quarter hour, newest first', () => {
|
||||
const now = Date.parse('2026-11-05T15:07:30Z');
|
||||
assert.equal(
|
||||
exportUrl(now),
|
||||
'https://data.gdeltproject.org/gdeltv2/20261105150000.export.CSV.zip',
|
||||
);
|
||||
const day = exportsOfDay(now);
|
||||
assert.equal(day.length, 96);
|
||||
assert.equal(
|
||||
day[1],
|
||||
'https://data.gdeltproject.org/gdeltv2/20261105144500.export.CSV.zip',
|
||||
);
|
||||
assert.equal(
|
||||
day.at(-1),
|
||||
'https://data.gdeltproject.org/gdeltv2/20261104151500.export.CSV.zip',
|
||||
);
|
||||
});
|
||||
|
||||
test('a story with physical violence is kept with all its placed events', () => {
|
||||
const rows = [
|
||||
eventRow({ id: 1, code: '195', url: ARTICLE }),
|
||||
eventRow({ id: 2, code: '183', url: ARTICLE }),
|
||||
eventRow({ id: 3, code: '2001', url: ARTICLE }),
|
||||
// Not physical, but of the same story: kept to place it by.
|
||||
eventRow({ id: 4, code: '150', url: ARTICLE }),
|
||||
eventRow({ id: 7, code: '190', quad: '3', url: ARTICLE }),
|
||||
// A story with no violence in it is left out.
|
||||
eventRow({
|
||||
id: 5,
|
||||
code: '163',
|
||||
url: 'https://x.example/talks-resume-in-geneva-today-officials',
|
||||
}),
|
||||
eventRow({
|
||||
id: 6,
|
||||
code: '173',
|
||||
url: 'https://x.example/talks-resume-in-geneva-today-officials',
|
||||
}),
|
||||
// Unplaced, at 0,0, or without a link.
|
||||
eventRow({ id: 8, geoType: '0', url: ARTICLE }),
|
||||
eventRow({ id: 9, lat: 0, lon: 0, url: ARTICLE }),
|
||||
eventRow({ id: 10, url: 'javascript:alert(1)' }),
|
||||
'short\trow',
|
||||
];
|
||||
const events = parseEvents(rows.join('\n'));
|
||||
assert.deepEqual(
|
||||
events.map((e) => [e.id, e.violent]),
|
||||
[
|
||||
['1', true],
|
||||
['2', true],
|
||||
['3', true],
|
||||
['4', false],
|
||||
['7', false],
|
||||
],
|
||||
);
|
||||
assert.equal(events[0].precision, 'city');
|
||||
assert.equal(events[0].addedAt, '2026-11-05T11:45:00.000Z');
|
||||
});
|
||||
|
||||
test("an article is one report, at its most-mentioned event, in its address's words", () => {
|
||||
const events = parseEvents(
|
||||
[
|
||||
eventRow({ id: 11, code: '195', mentions: 2, url: ARTICLE }),
|
||||
eventRow({
|
||||
id: 12,
|
||||
code: '190',
|
||||
mentions: 9,
|
||||
url: ARTICLE,
|
||||
place: "Kupiansk, Kharkivs'ka Oblast', Ukraine",
|
||||
lat: 49.71,
|
||||
lon: 37.61,
|
||||
}),
|
||||
eventRow({
|
||||
id: 13,
|
||||
code: '190',
|
||||
geoType: '1',
|
||||
place: 'Ukraine',
|
||||
lat: 49,
|
||||
lon: 32,
|
||||
url: 'https://example.com/a/b/12345',
|
||||
}),
|
||||
].join('\n'),
|
||||
);
|
||||
const [drones, bare] = eventReports(events);
|
||||
// The story's first event (by time, then id) names it.
|
||||
assert.equal(drones.id, 'gdelt-11');
|
||||
// Its address words, with the place it is at written as a name.
|
||||
assert.equal(
|
||||
drones.title,
|
||||
'Russian drones attack Kharkiv overnight three killed',
|
||||
);
|
||||
// Kupiansk has more mentions; the article's own words name Kharkiv.
|
||||
assert.equal(drones.geo.place, "Kharkiv, Kharkivs'ka Oblast', Ukraine");
|
||||
assert.equal(drones.geo.precision, 'city');
|
||||
assert.equal(drones.locations.length, 0, 'Kupiansk is not named');
|
||||
assert.equal(drones.category, 'strike');
|
||||
assert.equal(drones.relevance, 'core');
|
||||
assert.equal(drones.severity, 2);
|
||||
assert.equal(drones.publisher, 'wire.example');
|
||||
assert.equal(drones.source.attribution, 'GDELT Project');
|
||||
assert.equal(drones.side, 'unknown', 'no actor is said');
|
||||
// No words in the address: GDELT's coding alone, so minor (not listed
|
||||
// under Conflicts), at least severity 1.
|
||||
assert.equal(bare.title, 'Fighting reported in Ukraine');
|
||||
assert.equal(bare.category, 'ground');
|
||||
assert.equal(bare.relevance, 'minor');
|
||||
assert.equal(bare.severity, 1);
|
||||
assert.equal(bare.geo.precision, 'country');
|
||||
});
|
||||
|
||||
test('an article GDELT codes as fighting whose words say otherwise stays out of Conflicts', () => {
|
||||
const [report] = eventReports(
|
||||
parseEvents(
|
||||
eventRow({
|
||||
url: 'https://news.example.com/2026/11/05/city-council-approves-new-budget-for-schools',
|
||||
id: 20,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(report.relevance, 'minor');
|
||||
});
|
||||
|
||||
test('address words need four lettered words, most of the address', () => {
|
||||
assert.equal(addressWords('https://x.example/news/1234567'), null);
|
||||
assert.equal(addressWords('https://x.example/a/lueop1pzfi'), null);
|
||||
assert.equal(
|
||||
addressWords('https://x.example/2026/11/05/a-b-1-2-3-4-5'),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
addressWords(
|
||||
'https://x.example/story/2638789/three-children-die-in-peshawar.html',
|
||||
),
|
||||
'Three children die in peshawar',
|
||||
);
|
||||
});
|
||||
|
||||
test('an export is unzipped and read; one not published yet is null', async () => {
|
||||
const zip = zipTable(eventRow({ id: 30, code: '193', url: ARTICLE }));
|
||||
assert.deepEqual(
|
||||
parseEvents(await unzipExport(zip)).map((e) => e.id),
|
||||
['30'],
|
||||
);
|
||||
const served = await fetchExport('https://data.gdeltproject.org/x.zip', {
|
||||
fetchImpl: async () => new Response(zip, { status: 200 }),
|
||||
});
|
||||
assert.deepEqual(
|
||||
served.map((e) => e.id),
|
||||
['30'],
|
||||
);
|
||||
const later = await fetchExport('https://data.gdeltproject.org/y.zip', {
|
||||
fetchImpl: async () => new Response('not found', { status: 404 }),
|
||||
});
|
||||
assert.equal(later, null);
|
||||
await assert.rejects(
|
||||
fetchExport('https://data.gdeltproject.org/z.zip', {
|
||||
fetchImpl: async () => new Response('busy', { status: 503 }),
|
||||
}),
|
||||
{ name: 'UpstreamError' },
|
||||
);
|
||||
await assert.rejects(unzipExport(new Uint8Array([1, 2, 3])), {
|
||||
name: 'UpstreamError',
|
||||
});
|
||||
});
|
||||
|
||||
test("a nationality is no place: a town the article's words name wins over a bare country", () => {
|
||||
const url =
|
||||
'https://www.sun.example/world/2026/11/05/security-officer-attacked-and-killed-near-sri-lankan-embassy-in-jordans-capital';
|
||||
const amman = { place: 'Amman, (JO11), Jordan', lat: 31.95, lon: 35.9333 };
|
||||
const cairo = { place: 'Cairo, Al Qahirah, Egypt', lat: 30.05, lon: 31.25 };
|
||||
const [report] = eventReports(
|
||||
parseEvents(
|
||||
[
|
||||
// "Sri Lankan embassy": GDELT's most-mentioned place, a bare country.
|
||||
eventRow({
|
||||
id: 1,
|
||||
mentions: 12,
|
||||
geoType: '1',
|
||||
place: 'Sri Lanka',
|
||||
lat: 7,
|
||||
lon: 81,
|
||||
url,
|
||||
}),
|
||||
eventRow({ id: 2, mentions: 6, ...cairo, url }),
|
||||
eventRow({ id: 3, mentions: 4, ...amman, url }),
|
||||
eventRow({ id: 4, mentions: 2, ...amman, url }),
|
||||
].join('\n'),
|
||||
),
|
||||
);
|
||||
assert.equal(report.geo.place, 'Amman, (JO11), Jordan');
|
||||
assert.equal(report.geo.precision, 'city');
|
||||
});
|
||||
|
||||
test('an agency story run by several outlets is one report, placed by all their events', () => {
|
||||
const words = 'jordan-security-officer-killed-near-sri-lanka-embassy';
|
||||
const times = `https://www.times.example/story/9386807/${words}/`;
|
||||
const chronicle = `https://www.chronicle.example/story/9386807/${words}/`;
|
||||
const reports = eventReports(
|
||||
parseEvents(
|
||||
[
|
||||
// The outlet's own country, at country level, on its violent events.
|
||||
eventRow({
|
||||
id: 1,
|
||||
mentions: 6,
|
||||
geoType: '1',
|
||||
place: 'Australia',
|
||||
lat: -25,
|
||||
lon: 135,
|
||||
url: times,
|
||||
added: '20261105141500',
|
||||
}),
|
||||
// Its other events are placed in Jordan.
|
||||
eventRow({
|
||||
id: 2,
|
||||
code: '120',
|
||||
quad: '3',
|
||||
mentions: 8,
|
||||
place: 'Karak, Jordan (general), Jordan',
|
||||
lat: 31.18,
|
||||
lon: 35.7,
|
||||
url: times,
|
||||
added: '20261105141500',
|
||||
}),
|
||||
eventRow({
|
||||
id: 3,
|
||||
mentions: 4,
|
||||
geoType: '1',
|
||||
place: 'Syria',
|
||||
lat: 35,
|
||||
lon: 38,
|
||||
url: chronicle,
|
||||
added: '20261105151500',
|
||||
}),
|
||||
].join('\n'),
|
||||
),
|
||||
);
|
||||
assert.equal(reports.length, 1);
|
||||
const [story] = reports;
|
||||
assert.equal(story.copies, 2);
|
||||
assert.equal(story.url, times, 'the first copy');
|
||||
assert.equal(story.publishedAt, '2026-11-05T14:15:00.000Z');
|
||||
assert.equal(story.geo.place, 'Karak, Jordan (general), Jordan');
|
||||
});
|
||||
|
||||
test("a story's title is a copy's page title from the GKG export", () => {
|
||||
const titles = parseTitles(
|
||||
[
|
||||
gkgRow(
|
||||
ARTICLE,
|
||||
'Russian drones attack Kharkiv overnight, three killed | Wire',
|
||||
),
|
||||
gkgRow('https://elsewhere.example/a', 'Not one of ours, not kept here'),
|
||||
].join('\n'),
|
||||
new Set([ARTICLE]),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...titles],
|
||||
[[ARTICLE, 'Russian drones attack Kharkiv overnight, three killed']],
|
||||
);
|
||||
const [report] = eventReports(
|
||||
parseEvents(eventRow({ id: 1, url: ARTICLE })),
|
||||
{
|
||||
titleOf: (url) => titles.get(url) || null,
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
report.title,
|
||||
'Russian drones attack Kharkiv overnight, three killed',
|
||||
);
|
||||
assert.equal(report.titled, 'page');
|
||||
assert.equal(
|
||||
gkgUrl(
|
||||
'https://data.gdeltproject.org/gdeltv2/20261105141500.export.CSV.zip',
|
||||
),
|
||||
'https://data.gdeltproject.org/gdeltv2/20261105141500.gkg.csv.zip',
|
||||
);
|
||||
});
|
||||
|
||||
test('a page title loses its site name, keeps its words, and must be a headline', () => {
|
||||
assert.equal(
|
||||
cleanTitle(
|
||||
'Yemen's president sacks ministers | Yemen | The Daily Example',
|
||||
),
|
||||
"Yemen's president sacks ministers",
|
||||
);
|
||||
assert.equal(
|
||||
cleanTitle('Strike in Kharkiv - live updates - Wire Service'),
|
||||
'Strike in Kharkiv - live updates',
|
||||
);
|
||||
// Too little before the dash: the dash is part of the headline.
|
||||
assert.equal(cleanTitle('Iran - Wire Service'), 'Iran - Wire Service');
|
||||
assert.equal(cleanTitle('Home'), null);
|
||||
assert.equal(
|
||||
cleanTitle('Jordanian security officer killed in stabbing attack-Newswire'),
|
||||
'Jordanian security officer killed in stabbing attack',
|
||||
);
|
||||
assert.equal(
|
||||
cleanTitle('Five killed in Gaza, sources say-X'),
|
||||
'Five killed in Gaza, sources say',
|
||||
);
|
||||
// A hyphenated name is no tag.
|
||||
assert.equal(
|
||||
cleanTitle('Talks resume with Jean-Pierre'),
|
||||
'Talks resume with Jean-Pierre',
|
||||
);
|
||||
});
|
||||
|
||||
test('address words keep their numbers and name the places the story is at', () => {
|
||||
const words = addressWords(
|
||||
'https://x.example/2026/11/05/jordan-says-u-s-envoy-met-officials-in-amman-after-500-killed',
|
||||
);
|
||||
assert.equal(
|
||||
words,
|
||||
'Jordan says u s envoy met officials in amman after 500 killed',
|
||||
);
|
||||
assert.equal(
|
||||
withNames(words, [{ place: 'Amman, (JO11), Jordan' }]),
|
||||
'Jordan says US envoy met officials in Amman after 500 killed',
|
||||
);
|
||||
});
|
||||
|
||||
test("a story's id is its first event's: a later, more-mentioned event keeps it", () => {
|
||||
const first = eventRow({ id: 40, mentions: 1, url: ARTICLE });
|
||||
const [before] = eventReports(parseEvents(first));
|
||||
const [after] = eventReports(
|
||||
parseEvents(
|
||||
[
|
||||
first,
|
||||
eventRow({
|
||||
id: 41,
|
||||
code: '195',
|
||||
mentions: 30,
|
||||
url: ARTICLE,
|
||||
added: '20261105120000',
|
||||
}),
|
||||
].join('\n'),
|
||||
),
|
||||
);
|
||||
assert.equal(before.id, 'gdelt-40');
|
||||
assert.equal(after.id, 'gdelt-40');
|
||||
assert.equal(after.mentions, 31);
|
||||
});
|
||||
|
||||
test('words that read as no conflict leave GDELT no kind to name', () => {
|
||||
const [report] = eventReports(
|
||||
parseEvents(
|
||||
eventRow({
|
||||
id: 42,
|
||||
code: '195',
|
||||
url: 'https://x.example/2026/11/05/local-bakery-celebrates-fifty-years-of-baking',
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(report.relevance, 'minor');
|
||||
assert.equal(report.category, 'other');
|
||||
});
|
||||
|
||||
test('a GKG address written with http is the https one the events carry', () => {
|
||||
const plain = ARTICLE.replace('https:', 'http:');
|
||||
const [event] = parseEvents(eventRow({ id: 43, url: plain }));
|
||||
assert.equal(event.url, ARTICLE);
|
||||
const titles = parseTitles(
|
||||
gkgRow(plain, 'Russian drones attack Kharkiv overnight, three killed'),
|
||||
new Set([event.url]),
|
||||
);
|
||||
assert.equal(
|
||||
titles.get(ARTICLE),
|
||||
'Russian drones attack Kharkiv overnight, three killed',
|
||||
);
|
||||
});
|
||||
|
||||
test('a corrupt or oversized export is an UpstreamError, never a RangeError', async () => {
|
||||
const zip = zipTable(eventRow({ id: 44, url: ARTICLE }));
|
||||
const view = new DataView(zip.buffer);
|
||||
// The central directory's local header offset, pointing past the end.
|
||||
const dir = view.getUint32(zip.length - 22 + 16, true);
|
||||
const far = zip.slice();
|
||||
new DataView(far.buffer).setUint32(dir + 42, zip.length - 10, true);
|
||||
await assert.rejects(unzipExport(far), { name: 'UpstreamError' });
|
||||
// The end record cut short.
|
||||
await assert.rejects(unzipExport(zip.subarray(0, zip.length - 30)), {
|
||||
name: 'UpstreamError',
|
||||
});
|
||||
// Unzipped past the table's cap.
|
||||
await assert.rejects(unzipExport(zip, 16), { name: 'UpstreamError' });
|
||||
assert.equal((await unzipExport(zip)).length > 16, true);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
// Test fixtures: GDELT 2.0 export rows and their zip, as the export files
|
||||
// carry them (61 tab-separated columns, one zipped table).
|
||||
import { deflateRawSync } from 'node:zlib';
|
||||
|
||||
/** One events row; only the columns the reader looks at are filled. */
|
||||
export function eventRow({
|
||||
id,
|
||||
code = '190',
|
||||
quad = '4',
|
||||
mentions = 1,
|
||||
geoType = '4',
|
||||
place = "Kharkiv, Kharkivs'ka Oblast', Ukraine",
|
||||
lat = 49.9935,
|
||||
lon = 36.2304,
|
||||
added = '20261105114500',
|
||||
url,
|
||||
}) {
|
||||
const f = new Array(61).fill('');
|
||||
f[0] = String(id);
|
||||
f[26] = code;
|
||||
f[28] = code.slice(0, 2);
|
||||
f[29] = quad;
|
||||
f[31] = String(mentions);
|
||||
f[51] = geoType;
|
||||
f[52] = place;
|
||||
f[56] = String(lat);
|
||||
f[57] = String(lon);
|
||||
f[59] = added;
|
||||
f[60] = url;
|
||||
return f.join('\t');
|
||||
}
|
||||
|
||||
/** One GKG 2.1 row: an article's address and its page title (27 columns). */
|
||||
export function gkgRow(url, title) {
|
||||
const f = new Array(27).fill('');
|
||||
f[4] = url;
|
||||
f[26] = `<PAGE_PRECISEPUBTIMESTAMP>20261105114500</PAGE_PRECISEPUBTIMESTAMP><PAGE_TITLE>${title}</PAGE_TITLE>`;
|
||||
return f.join('\t');
|
||||
}
|
||||
|
||||
/** A single-entry zip of `text`, deflated, sizes in the central directory. */
|
||||
export function zipTable(text, name = 'table.export.CSV') {
|
||||
const data = Buffer.from(text, 'utf8');
|
||||
const packed = deflateRawSync(data);
|
||||
const nameBytes = Buffer.from(name);
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x08, 6); // sizes follow the data (left 0 here)
|
||||
local.writeUInt16LE(8, 8);
|
||||
local.writeUInt16LE(nameBytes.length, 26);
|
||||
const dir = Buffer.alloc(46);
|
||||
dir.writeUInt32LE(0x02014b50, 0);
|
||||
dir.writeUInt16LE(20, 4);
|
||||
dir.writeUInt16LE(20, 6);
|
||||
dir.writeUInt16LE(0x08, 8);
|
||||
dir.writeUInt16LE(8, 10);
|
||||
dir.writeUInt32LE(packed.length, 20);
|
||||
dir.writeUInt32LE(data.length, 24);
|
||||
dir.writeUInt16LE(nameBytes.length, 28);
|
||||
dir.writeUInt32LE(0, 42);
|
||||
const dirAt = local.length + nameBytes.length + packed.length;
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(1, 8);
|
||||
end.writeUInt16LE(1, 10);
|
||||
end.writeUInt32LE(dir.length + nameBytes.length, 12);
|
||||
end.writeUInt32LE(dirAt, 16);
|
||||
return new Uint8Array(
|
||||
Buffer.concat([local, nameBytes, packed, dir, nameBytes, end]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,909 @@
|
||||
// The News layer's routes answered by Core itself, when no news server is
|
||||
// configured (GEV_NEWS_ORIGIN). Conflicts: the day's GDELT events (no key;
|
||||
// gdeltEvents.js), one report per article at GDELT's place for it, and with
|
||||
// LIVEUAMAP_API_KEY Liveuamap's mapped items too. Local: World News API
|
||||
// (WORLDNEWSAPI_KEY) by the country at the view centre; without its key the
|
||||
// section answers 503 {error: 'no_key', key} and reads nothing, and past
|
||||
// its day's reads (WORLDNEWSAPI_DAILY_READS) 503 {error: 'key_quota', key}.
|
||||
// Conflicts' categories, relevance and severity are the shared rules
|
||||
// (categorize.js); a country's own news keeps World News API's category.
|
||||
// A news server may replace these readings with its own.
|
||||
//
|
||||
// A read that has something to serve is not waited for: what was read is
|
||||
// served while it is read again. A section that cannot be read answers 502,
|
||||
// never an empty list.
|
||||
//
|
||||
// The answers are the same /api/news contract a news server serves
|
||||
// (src/layers/news/records.js reads both).
|
||||
|
||||
import {
|
||||
CATEGORY_ORDER,
|
||||
categorizeText,
|
||||
relevanceOf,
|
||||
severityByRules,
|
||||
} from './categorize.js';
|
||||
import {
|
||||
areaAt,
|
||||
countryAnchor,
|
||||
countryByCode,
|
||||
countryPolygons,
|
||||
} from './areas.js';
|
||||
import {
|
||||
eventReports,
|
||||
fetchLatestExport,
|
||||
eventTitle,
|
||||
exportAt,
|
||||
exportsOfDay,
|
||||
fetchExport,
|
||||
fetchTitles,
|
||||
gkgUrl,
|
||||
storyKey,
|
||||
} from './gdeltEvents.js';
|
||||
import { fetchLiveuamap, fetchWorldNews, UpstreamError } from './upstream.js';
|
||||
|
||||
/** The keys each section reads with, by the key registry's id. */
|
||||
export const NEWS_KEYS = Object.freeze({
|
||||
liveuamap: 'LIVEUAMAP_API_KEY',
|
||||
worldnewsapi: 'WORLDNEWSAPI_KEY',
|
||||
});
|
||||
|
||||
/** The one hotspot: the world, its reports drawn as markers at every zoom. */
|
||||
export const WORLDWIDE_HOTSPOT = 'worldwide';
|
||||
const HOUR_MS = 3_600_000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
// GDELT publishes an export every 15 minutes and lists the newest in
|
||||
// lastupdate.txt: the day's missing ones up to it are read every 5 minutes,
|
||||
// newest first, a dozen a read (the first day's 96 fill in over the next
|
||||
// reads, a few seconds apart, while each reads something new). One listed
|
||||
// but missing (404) an hour and a half after its time is taken as never
|
||||
// published; one that fails GDELT_EXPORT_TRIES times (a try a round), or
|
||||
// cannot be read at all, is given up on, so one bad file never holds the
|
||||
// rest back. Only while GDELT itself answers is a file given up on. The first
|
||||
// answer waits at most FIRST_ANSWER_MS for the first exports.
|
||||
const GDELT_FRESH_MS = 5 * 60_000;
|
||||
const GDELT_EXPORTS_PER_READ = 12;
|
||||
const GDELT_PARALLEL = 4;
|
||||
const GDELT_NEXT_MS = 2_000;
|
||||
const GDELT_GONE_MS = 90 * 60_000;
|
||||
const GDELT_EXPORT_TRIES = 3;
|
||||
const MAX_GDELT_REPORTS = 5000;
|
||||
// Events kept of one story, to place it by.
|
||||
const MAX_STORY_EVENTS = 200;
|
||||
// Page titles are read from the GKG exports of the newest three hours: one
|
||||
// runs to 6 MB, so the day's 96 are not fetched. A file that fails is tried
|
||||
// with the next reads, a few times.
|
||||
const GDELT_TITLED_EXPORTS = 12;
|
||||
const GKG_TRIES = 3;
|
||||
const LIVE_FRESH_MS = 5 * 60_000;
|
||||
const COUNTRY_FRESH_MS = 30 * 60_000;
|
||||
// A failed read is not tried again for a minute; what was read before is
|
||||
// served meanwhile, up to these ages (GDELT's: since an export last came in).
|
||||
const RETRY_MS = 60_000;
|
||||
// A read with nothing to serve yet is waited for at most this long, well under
|
||||
// the browser's own 15 s: it goes on, and the next ask is served from it.
|
||||
const FIRST_ANSWER_MS = 10_000;
|
||||
const GDELT_STALE_MS = 2 * HOUR_MS;
|
||||
const LIVE_STALE_MS = HOUR_MS;
|
||||
// World News API's terms allow a cache of at most an hour, deleted after:
|
||||
// a country's news is kept no longer, served or not (dropExpiredCountries).
|
||||
const COUNTRY_STALE_MS = HOUR_MS;
|
||||
const MAX_COUNTRIES = 64;
|
||||
// World News API reads a UTC day, across all countries: each is about 1.5
|
||||
// of the free plan's 50 daily points.
|
||||
const DEFAULT_DAILY_READS = 30;
|
||||
const DEFAULT_LIMIT = 50;
|
||||
const EMPTY_OUTLINE = Object.freeze({
|
||||
polygons: [],
|
||||
borders: [],
|
||||
disputed: [],
|
||||
area: null,
|
||||
});
|
||||
// A country's own news keeps World News API's category: the rules read
|
||||
// fighting and crises, and in everyday news their words mislead ("advances
|
||||
// in the rankings" is no ground fighting). Fighting in the country reaches
|
||||
// Local as the Conflicts reports placed there.
|
||||
const WORLD_NEWS_CATEGORY = { politics: 'political', business: 'economy' };
|
||||
|
||||
const list = (value) =>
|
||||
value ? new Set(value.split(',').filter(Boolean)) : null;
|
||||
|
||||
/** The rules' reading of a Conflicts headline: category, relevance, severity. */
|
||||
function readTitle(title) {
|
||||
const read = categorizeText({ title });
|
||||
const { category } = read;
|
||||
return {
|
||||
category,
|
||||
relevance: relevanceOf({
|
||||
category,
|
||||
tags: read.tags,
|
||||
title,
|
||||
dedicated: true,
|
||||
}),
|
||||
severity: severityByRules({ category, tags: read.tags, title }),
|
||||
};
|
||||
}
|
||||
|
||||
/** A one-report event carrying the report's picture, for its card. */
|
||||
function pictureEvent(id, report, image, video, publisher) {
|
||||
return {
|
||||
id,
|
||||
status: 'single',
|
||||
size: 1,
|
||||
reports: 1,
|
||||
severity: report.severity,
|
||||
firstAt: report.publishedAt,
|
||||
lastAt: report.publishedAt,
|
||||
sides: [],
|
||||
image: { url: image, publisher, ...(video ? { video } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
const media = ({ image, video }) =>
|
||||
video ? ['video'] : image ? ['photo'] : [];
|
||||
|
||||
/** A Liveuamap item as a report of the Conflicts section. */
|
||||
export function liveuamapReport(item) {
|
||||
const id = `lum-${item.id}`;
|
||||
const report = {
|
||||
id,
|
||||
hotspotId: WORLDWIDE_HOTSPOT,
|
||||
hotspotIds: [WORLDWIDE_HOTSPOT],
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
publisher: 'Liveuamap',
|
||||
source: { name: 'Liveuamap' },
|
||||
kind: 'liveuamap',
|
||||
side: 'unknown',
|
||||
// A conflict map: everything it posts is at least related.
|
||||
...readTitle(item.title),
|
||||
severityBy: 'rules',
|
||||
publishedAt: item.publishedAt,
|
||||
geo: {
|
||||
lat: item.lat,
|
||||
lon: item.lon,
|
||||
place: item.place,
|
||||
precision: 'city',
|
||||
confidence: 1,
|
||||
mappable: true,
|
||||
method: 'source',
|
||||
},
|
||||
media: media(item),
|
||||
};
|
||||
if (item.image)
|
||||
report.event = pictureEvent(
|
||||
id,
|
||||
report,
|
||||
item.image,
|
||||
item.video,
|
||||
'Liveuamap',
|
||||
);
|
||||
return report;
|
||||
}
|
||||
|
||||
/**
|
||||
* A GDELT place named by its town and the area Natural Earth has there (a
|
||||
* disputed area as itself, else the country): GDELT's own names follow old
|
||||
* FIPS regions ("Bureij, Yerushalayim, Israel" for a camp in Gaza, "Abuja,
|
||||
* …, Niger" for Nigeria's capital). Its point stays. A town a disputed
|
||||
* area is named after ("Jerusalem" in East Jerusalem) lies on both sides
|
||||
* of its line: GDELT puts the whole city at one point, so it is named as
|
||||
* the town alone.
|
||||
*/
|
||||
export function gdeltPlace(geo) {
|
||||
const area = areaAt(geo.lat, geo.lon);
|
||||
const town = String(geo.place ?? '')
|
||||
.split(',')[0]
|
||||
.trim();
|
||||
const straddles =
|
||||
area?.kind === 'disputed' &&
|
||||
town &&
|
||||
area.name.toLowerCase().includes(town.toLowerCase());
|
||||
const place =
|
||||
geo.precision === 'country' && area?.kind === 'country'
|
||||
? area.name
|
||||
: straddles
|
||||
? town
|
||||
: [town, area?.name].filter(Boolean).join(', ');
|
||||
return { ...geo, place: place || null };
|
||||
}
|
||||
|
||||
/**
|
||||
* A World News API article as a report of the Local section: placed in its
|
||||
* publisher's country alone, at a point inside it.
|
||||
*/
|
||||
export function worldNewsReport(article, country) {
|
||||
const id = `wna-${article.id}`;
|
||||
const anchor = countryAnchor(country);
|
||||
const report = {
|
||||
id,
|
||||
hotspotId: null,
|
||||
hotspotIds: [],
|
||||
title: article.title,
|
||||
url: article.url,
|
||||
publisher: article.publisher,
|
||||
// World News API's free plan asks to be credited where its news shows.
|
||||
source: { name: article.publisher, attribution: 'World News API' },
|
||||
kind: 'worldnewsapi',
|
||||
side: 'unknown',
|
||||
category: WORLD_NEWS_CATEGORY[article.category] || 'other',
|
||||
// Local news: what the country's own outlets publish, with no severity
|
||||
// of its own.
|
||||
relevance: 'minor',
|
||||
publishedAt: article.publishedAt,
|
||||
geo: {
|
||||
lat: anchor.lat,
|
||||
lon: anchor.lon,
|
||||
place: country.name,
|
||||
precision: 'country',
|
||||
confidence: 1,
|
||||
mappable: true,
|
||||
method: 'source',
|
||||
},
|
||||
media: media(article),
|
||||
};
|
||||
if (article.image)
|
||||
report.event = pictureEvent(
|
||||
id,
|
||||
report,
|
||||
article.image,
|
||||
article.video,
|
||||
article.publisher,
|
||||
);
|
||||
return report;
|
||||
}
|
||||
|
||||
const AT = /^(-?\d{1,2}(?:\.\d{1,2})?),(-?\d{1,3}(?:\.\d{1,2})?)$/;
|
||||
function point(value) {
|
||||
const match = AT.exec(String(value ?? ''));
|
||||
if (!match) return null;
|
||||
const [lat, lon] = [Number(match[1]), Number(match[2])];
|
||||
return Math.abs(lat) <= 90 && Math.abs(lon) <= 180 ? { lat, lon } : null;
|
||||
}
|
||||
|
||||
const noKey = (key) => ({ status: 503, body: { error: 'no_key', key } });
|
||||
const rejectedKey = (key) => ({
|
||||
status: 503,
|
||||
body: { error: 'key_rejected', key },
|
||||
});
|
||||
const spentKey = (key) => ({ status: 503, body: { error: 'key_quota', key } });
|
||||
|
||||
/**
|
||||
* The keyed news routes. `answer(path, params)` resolves to `{status, body}`
|
||||
* for `/hotspots`, `/feed` and `/outline`, whose queries the proxy has
|
||||
* already checked against the client's allowlist. `later(run, ms)` runs
|
||||
* the next GDELT read of a day still filling in (an unref'd timer).
|
||||
* `firstAnswerMs` bounds the wait for a read with nothing to serve yet.
|
||||
* @param {{env?: () => object, fetchImpl?: typeof fetch, now?: () => number, log?: (message: string) => void, later?: (run: () => void, ms: number) => void, firstAnswerMs?: number}} [options]
|
||||
*/
|
||||
export function createKeyedNews({
|
||||
env = () => process.env,
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
now = () => Date.now(),
|
||||
log = (message) => console.warn(message),
|
||||
later = (run, ms) => setTimeout(run, ms).unref(),
|
||||
firstAnswerMs = FIRST_ANSWER_MS,
|
||||
} = {}) {
|
||||
const keyOf = (id) => String(env()[NEWS_KEYS[id]] ?? '').trim();
|
||||
const inFlight = new Map();
|
||||
// GDELT's stories of the last day (their events and report, by
|
||||
// storyKey), and the exports read.
|
||||
const gdelt = {
|
||||
stories: new Map(),
|
||||
reports: new Map(),
|
||||
// Page titles by article address, of the stories kept.
|
||||
titles: new Map(),
|
||||
read: new Set(),
|
||||
// Exports still missing well after their time: not looked for again.
|
||||
gone: new Set(),
|
||||
// Failed reads of each export not read yet: `{tries, at}`.
|
||||
failures: new Map(),
|
||||
// Exports read among the newest whose GKG titles are not in yet, with
|
||||
// the tries made: `{tries, triedAt}`.
|
||||
untitled: new Map(),
|
||||
titling: null,
|
||||
// When a read last brought an export in.
|
||||
readAt: null,
|
||||
checkedAt: null,
|
||||
failedAt: null,
|
||||
};
|
||||
const live = new Map();
|
||||
const countries = new Map();
|
||||
// The keys refused so far, by section: logged once each.
|
||||
const refused = new Set();
|
||||
// World News API reads of the UTC day; `spent` once it answered 402.
|
||||
const budget = { day: null, reads: 0, spent: false, logged: false };
|
||||
// The areas (disputed area or country) of a placed Conflicts report's
|
||||
// pins, its first and the others, looked up once.
|
||||
const reportAreas = new WeakMap();
|
||||
const areasOf = (report) => {
|
||||
if (!reportAreas.has(report))
|
||||
reportAreas.set(
|
||||
report,
|
||||
new Set(
|
||||
[report.geo, ...(report.locations || [])]
|
||||
.filter(Boolean)
|
||||
.map((pin) => areaAt(pin.lat, pin.lon)?.key),
|
||||
),
|
||||
);
|
||||
return reportAreas.get(report);
|
||||
};
|
||||
|
||||
/** A failed read in the log: a refused key once, never the key itself. */
|
||||
function logFailure(section, what, key, error) {
|
||||
// The day's reads spent: said once, by spendRead.
|
||||
if (error.quota && error.status === null) return;
|
||||
if (error.rejected) {
|
||||
const id = `${section}\0${key}`;
|
||||
if (refused.has(id)) return;
|
||||
refused.add(id);
|
||||
log(
|
||||
`[news] ${NEWS_KEYS[section]} was refused (${error.status})${section === 'liveuamap' ? "; Conflicts are GDELT's alone" : ''}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
log(`[news] ${what} read failed: ${error.message}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A cached read (`{key, value, readAt, failedAt, error}`, kept in `store`
|
||||
* under `id`): served as it is within `freshMs`; past that read again,
|
||||
* and served meanwhile up to `staleMs`, so only a read with nothing to
|
||||
* serve is waited for. One read at a time per key; a failed read is tried
|
||||
* again after RETRY_MS. A new key drops what the old one read.
|
||||
*/
|
||||
async function cached(
|
||||
store,
|
||||
id,
|
||||
{ section, key, freshMs, staleMs, read, what },
|
||||
) {
|
||||
const at = now();
|
||||
const stored = store.get(id);
|
||||
const prior = stored?.key === key ? stored : { key };
|
||||
if (prior.value && at - prior.readAt < freshMs) return prior;
|
||||
if (prior.failedAt && at - prior.failedAt < RETRY_MS) return prior;
|
||||
const flight = `${id}\0${key}`;
|
||||
if (!inFlight.has(flight))
|
||||
inFlight.set(
|
||||
flight,
|
||||
read(key)
|
||||
.then(
|
||||
(value) => ({ key, value, readAt: now() }),
|
||||
(error) => {
|
||||
logFailure(section, what, key, error);
|
||||
// What is held now: news deleted meanwhile stays deleted.
|
||||
const held = store.get(id);
|
||||
return {
|
||||
...(held?.key === key ? held : { key }),
|
||||
failedAt: now(),
|
||||
error,
|
||||
};
|
||||
},
|
||||
)
|
||||
.then((entry) => {
|
||||
// A read with a key replaced meanwhile is dropped.
|
||||
if (keyOf(section) === key) keep(store, id, entry);
|
||||
return entry;
|
||||
})
|
||||
.finally(() => inFlight.delete(flight)),
|
||||
);
|
||||
if (prior.value && at - prior.readAt < staleMs) return prior;
|
||||
// Meanwhile a refused key stays refused; an older failure is not this one.
|
||||
return firstAnswer(inFlight.get(flight), {
|
||||
...prior,
|
||||
error: prior.error?.rejected ? prior.error : null,
|
||||
});
|
||||
}
|
||||
|
||||
/** An entry stored as the most recently used (the countries are capped). */
|
||||
function keep(store, id, entry) {
|
||||
store.delete(id);
|
||||
store.set(id, entry);
|
||||
while (store.size > MAX_COUNTRIES) store.delete(store.keys().next().value);
|
||||
}
|
||||
|
||||
/** `read`, waited for at most firstAnswerMs; then `fallback`, as it goes on. */
|
||||
async function firstAnswer(read, fallback) {
|
||||
let timer;
|
||||
try {
|
||||
return await Promise.race([
|
||||
read,
|
||||
new Promise((resolve) => {
|
||||
timer = setTimeout(() => resolve(fallback), firstAnswerMs);
|
||||
timer.unref?.();
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** An entry's reports while they may be served, else why there are none. */
|
||||
function served(entry, staleMs, id) {
|
||||
if (entry.value && now() - entry.readAt < staleMs)
|
||||
return { reports: entry.value, readAt: entry.readAt };
|
||||
if (entry.error?.rejected) return { rejected: id };
|
||||
if (entry.error?.quota) return { quota: id };
|
||||
return { failed: true };
|
||||
}
|
||||
|
||||
async function liveuamapReports() {
|
||||
const key = keyOf('liveuamap');
|
||||
if (!key) return { missing: 'liveuamap' };
|
||||
const entry = await cached(live, 'liveuamap', {
|
||||
section: 'liveuamap',
|
||||
key,
|
||||
freshMs: LIVE_FRESH_MS,
|
||||
staleMs: LIVE_STALE_MS,
|
||||
what: 'liveuamap',
|
||||
read: async (k) =>
|
||||
(await fetchLiveuamap({ key: k, fetchImpl, now: now() }))
|
||||
.map(liveuamapReport)
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt)),
|
||||
});
|
||||
return served(entry, LIVE_STALE_MS, 'liveuamap');
|
||||
}
|
||||
|
||||
/**
|
||||
* A story placed (again) from all its events and the titles in: an
|
||||
* agency story run by several outlets is one report.
|
||||
*/
|
||||
function placeStory(key) {
|
||||
const [report] = eventReports(gdelt.stories.get(key), {
|
||||
titleOf: (url) => gdelt.titles.get(url) || null,
|
||||
});
|
||||
if (!report) return;
|
||||
const { eventWords, ...rest } = report;
|
||||
const geo = gdeltPlace(report.geo);
|
||||
gdelt.reports.set(key, {
|
||||
...rest,
|
||||
...(eventWords ? { title: eventTitle(eventWords, geo.place) } : {}),
|
||||
hotspotId: WORLDWIDE_HOTSPOT,
|
||||
hotspotIds: [WORLDWIDE_HOTSPOT],
|
||||
geo,
|
||||
locations: report.locations.map(gdeltPlace),
|
||||
});
|
||||
}
|
||||
|
||||
/** An export's events into their stories, each placed again. */
|
||||
function addEvents(events) {
|
||||
const changed = new Set();
|
||||
for (const event of events) {
|
||||
const key = storyKey(event);
|
||||
const list = gdelt.stories.get(key) || [];
|
||||
if (list.length < MAX_STORY_EVENTS) list.push(event);
|
||||
gdelt.stories.set(key, list);
|
||||
changed.add(key);
|
||||
}
|
||||
for (const key of changed) placeStory(key);
|
||||
}
|
||||
|
||||
/** The stories a GKG export titled, re-titled. */
|
||||
function addTitles(titles) {
|
||||
for (const [key, list] of gdelt.stories) {
|
||||
const titled = list.filter((event) => titles.has(event.url));
|
||||
if (!titled.length) continue;
|
||||
for (const { url } of titled) gdelt.titles.set(url, titles.get(url));
|
||||
placeStory(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The page titles of the newest exports read, from their GKG exports one
|
||||
* at a time (each runs to 18 MB unzipped), in the background: no answer
|
||||
* waits for them, and a story is re-titled as its title comes in. A file
|
||||
* that fails or is not up yet only leaves address words: it is tried
|
||||
* again with a later read while among the newest, up to GKG_TRIES times.
|
||||
*/
|
||||
function readTitles() {
|
||||
gdelt.titling ??= (async () => {
|
||||
let failed = null;
|
||||
for (const [url, tried] of [...gdelt.untitled]) {
|
||||
if (!gdelt.untitled.has(url)) continue;
|
||||
if (tried.triedAt !== null && now() - tried.triedAt < GDELT_FRESH_MS)
|
||||
continue;
|
||||
tried.tries += 1;
|
||||
tried.triedAt = now();
|
||||
const wanted = new Set();
|
||||
for (const list of gdelt.stories.values())
|
||||
for (const event of list) wanted.add(event.url);
|
||||
let titles = null;
|
||||
try {
|
||||
titles = await fetchTitles(gkgUrl(url), wanted, { fetchImpl });
|
||||
} catch (error) {
|
||||
failed ??= error;
|
||||
}
|
||||
if (titles || tried.tries >= GKG_TRIES) gdelt.untitled.delete(url);
|
||||
if (titles?.size) addTitles(titles);
|
||||
}
|
||||
if (failed) log(`[news] gdelt titles read failed: ${failed.message}`);
|
||||
})()
|
||||
.catch((error) => log(`[news] gdelt titles failed: ${error.message}`))
|
||||
.finally(() => {
|
||||
gdelt.titling = null;
|
||||
});
|
||||
return gdelt.titling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Up to a dozen of the day's exports not read yet, newest first; whether
|
||||
* to carry on at once (the round brought one in, and more are missing).
|
||||
* One not up yet is looked for again; one still missing GDELT_GONE_MS
|
||||
* after its time is not.
|
||||
*/
|
||||
async function readExports() {
|
||||
const at = now();
|
||||
const day = exportsOfDay(at);
|
||||
// Up to the newest GDELT lists; all of the day when its list fails.
|
||||
const latest = await fetchLatestExport({ fetchImpl });
|
||||
const listed = (url) => latest === null || exportAt(url) <= latest;
|
||||
const newest = new Set(day.slice(0, GDELT_TITLED_EXPORTS));
|
||||
const wanted = (url) =>
|
||||
listed(url) && !gdelt.read.has(url) && !gdelt.gone.has(url);
|
||||
const missing = day.filter(wanted).slice(0, GDELT_EXPORTS_PER_READ);
|
||||
let failed = null;
|
||||
let added = 0;
|
||||
const failing = [];
|
||||
const unreadable = [];
|
||||
const unpublished = [];
|
||||
for (let i = 0; i < missing.length; i += GDELT_PARALLEL)
|
||||
await Promise.all(
|
||||
missing.slice(i, i + GDELT_PARALLEL).map(async (url) => {
|
||||
let events;
|
||||
try {
|
||||
events = await fetchExport(url, { fetchImpl });
|
||||
} catch (error) {
|
||||
failed = error;
|
||||
(error.unreadable ? unreadable : failing).push(url);
|
||||
return;
|
||||
}
|
||||
if (!events) {
|
||||
if (at - exportAt(url) >= GDELT_GONE_MS) unpublished.push(url);
|
||||
return;
|
||||
}
|
||||
// The events count now; the titles follow (readTitles).
|
||||
gdelt.read.add(url);
|
||||
gdelt.failures.delete(url);
|
||||
added += 1;
|
||||
gdelt.readAt = now();
|
||||
addEvents(events);
|
||||
if (newest.has(url))
|
||||
gdelt.untitled.set(url, { tries: 0, triedAt: null });
|
||||
}),
|
||||
);
|
||||
if (failed) log(`[news] gdelt read failed: ${failed.message}`);
|
||||
// A file is blamed only while GDELT itself answers (its list read, or
|
||||
// another export of the round read): then a 404 long after its time is
|
||||
// never published, an unreadable file stays so, and a failing one gets a
|
||||
// few tries, one a GDELT_FRESH_MS. With GDELT down, no file is blamed.
|
||||
const answering = added > 0 || latest !== null;
|
||||
if (answering)
|
||||
for (const url of [...unpublished, ...unreadable]) gdelt.gone.add(url);
|
||||
if (added)
|
||||
for (const url of failing) {
|
||||
const prior = gdelt.failures.get(url);
|
||||
if (prior && now() - prior.at < GDELT_FRESH_MS) continue;
|
||||
const tries = (prior?.tries || 0) + 1;
|
||||
gdelt.failures.set(url, { tries, at: now() });
|
||||
if (tries >= GDELT_EXPORT_TRIES) gdelt.gone.add(url);
|
||||
}
|
||||
// Nothing read and a failure: tried again after RETRY_MS, not after
|
||||
// GDELT_FRESH_MS. Something read: the round counts.
|
||||
if (failed && !added) gdelt.failedAt = now();
|
||||
else {
|
||||
gdelt.checkedAt = now();
|
||||
gdelt.failedAt = null;
|
||||
}
|
||||
// Only the day is kept, and titled while among the newest.
|
||||
const kept = new Set(day);
|
||||
for (const set of [gdelt.read, gdelt.gone])
|
||||
for (const url of set) if (!kept.has(url)) set.delete(url);
|
||||
for (const url of gdelt.failures.keys())
|
||||
if (!kept.has(url)) gdelt.failures.delete(url);
|
||||
for (const url of gdelt.untitled.keys())
|
||||
if (!newest.has(url)) gdelt.untitled.delete(url);
|
||||
return (
|
||||
added > 0 && missing.length === GDELT_EXPORTS_PER_READ && day.some(wanted)
|
||||
);
|
||||
}
|
||||
|
||||
/** GDELT's reports of the last day, newest first, or `{failed}`. */
|
||||
async function gdeltReports() {
|
||||
const at = now();
|
||||
const fresh = gdelt.checkedAt && at - gdelt.checkedAt < GDELT_FRESH_MS;
|
||||
const resting = gdelt.failedAt && at - gdelt.failedAt < RETRY_MS;
|
||||
if (!fresh && !resting && !inFlight.has('gdelt')) {
|
||||
const round = readExports()
|
||||
.then(
|
||||
(more) => {
|
||||
// More of the day to fill in: carry on shortly, without holding
|
||||
// the answer.
|
||||
if (!more) return;
|
||||
gdelt.checkedAt = null;
|
||||
later(() => void gdeltReports(), GDELT_NEXT_MS);
|
||||
},
|
||||
(error) => {
|
||||
log(`[news] gdelt read failed: ${error.message}`);
|
||||
gdelt.failedAt = now();
|
||||
},
|
||||
)
|
||||
.finally(() => {
|
||||
inFlight.delete('gdelt');
|
||||
void readTitles();
|
||||
});
|
||||
inFlight.set('gdelt', round);
|
||||
}
|
||||
// Only a read with nothing (recent) to serve is waited for: the
|
||||
// newest exports' events, not their titles.
|
||||
const current = () =>
|
||||
gdelt.readAt !== null && now() - gdelt.readAt < GDELT_STALE_MS;
|
||||
// A slow GDELT must not outlast the browser's own timeout: what has come
|
||||
// in by then is served.
|
||||
if (!current() && inFlight.has('gdelt'))
|
||||
await firstAnswer(inFlight.get('gdelt'));
|
||||
if (!current()) return { failed: true };
|
||||
const dayAgo = new Date(now() - DAY_MS).toISOString();
|
||||
const reports = [...gdelt.reports.values()]
|
||||
.filter((r) => r.publishedAt >= dayAgo)
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
|
||||
.slice(0, MAX_GDELT_REPORTS);
|
||||
if (reports.length !== gdelt.reports.size) {
|
||||
const kept = new Set(reports);
|
||||
for (const [key, report] of gdelt.reports)
|
||||
if (!kept.has(report)) {
|
||||
for (const event of gdelt.stories.get(key) || [])
|
||||
gdelt.titles.delete(event.url);
|
||||
gdelt.reports.delete(key);
|
||||
gdelt.stories.delete(key);
|
||||
}
|
||||
}
|
||||
return { reports, readAt: gdelt.readAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* The Conflicts section's reports: GDELT's, with Liveuamap's when its key
|
||||
* is set. Liveuamap failing (or refusing its key) leaves GDELT's.
|
||||
*/
|
||||
async function conflictReports() {
|
||||
const [articles, items] = await Promise.all([
|
||||
gdeltReports(),
|
||||
keyOf('liveuamap') ? liveuamapReports() : {},
|
||||
]);
|
||||
if (!articles.reports && !items.reports) return { failed: true };
|
||||
return {
|
||||
reports: [...(articles.reports || []), ...(items.reports || [])].sort(
|
||||
(a, b) => b.publishedAt.localeCompare(a.publishedAt),
|
||||
),
|
||||
readAt: Math.max(articles.readAt || 0, items.readAt || 0),
|
||||
};
|
||||
}
|
||||
|
||||
const dailyReads = () => {
|
||||
const raw = String(env().WORLDNEWSAPI_DAILY_READS ?? '').trim();
|
||||
const reads = raw ? Number(raw) : NaN;
|
||||
return Number.isInteger(reads) && reads >= 0 ? reads : DEFAULT_DAILY_READS;
|
||||
};
|
||||
|
||||
/** Whether a World News API read is left today (UTC); counts it if so. */
|
||||
function spendRead() {
|
||||
const day = new Date(now()).toISOString().slice(0, 10);
|
||||
if (budget.day !== day)
|
||||
Object.assign(budget, { day, reads: 0, spent: false, logged: false });
|
||||
if (!budget.spent && budget.reads < dailyReads()) {
|
||||
budget.reads += 1;
|
||||
return true;
|
||||
}
|
||||
if (!budget.logged)
|
||||
log(
|
||||
"[news] World News API's reads for today are spent; Local reads again after 00:00 UTC",
|
||||
);
|
||||
budget.logged = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** World News API's news an hour old is deleted, as its terms ask. */
|
||||
function dropExpiredCountries() {
|
||||
for (const [code, entry] of countries)
|
||||
if (entry.value && now() - entry.readAt >= COUNTRY_STALE_MS) {
|
||||
const { value, readAt, ...rest } = entry;
|
||||
countries.set(code, rest);
|
||||
}
|
||||
}
|
||||
|
||||
async function countryReports(country) {
|
||||
const key = keyOf('worldnewsapi');
|
||||
if (!key) return { missing: 'worldnewsapi' };
|
||||
const stored = countries.get(country.code);
|
||||
if (stored) keep(countries, country.code, stored);
|
||||
const entry = await cached(countries, country.code, {
|
||||
section: 'worldnewsapi',
|
||||
key,
|
||||
freshMs: COUNTRY_FRESH_MS,
|
||||
staleMs: COUNTRY_STALE_MS,
|
||||
what: `worldnewsapi:${country.code}`,
|
||||
read: async (k) => {
|
||||
// Not asked: no status, unlike an answer.
|
||||
if (!spendRead())
|
||||
throw new UpstreamError("World News API's reads for today spent", {
|
||||
quota: true,
|
||||
});
|
||||
const { day } = budget;
|
||||
try {
|
||||
const reports = (
|
||||
await fetchWorldNews({
|
||||
key: k,
|
||||
country: country.code,
|
||||
fetchImpl,
|
||||
now: now(),
|
||||
})
|
||||
).map((article) => worldNewsReport(article, country));
|
||||
// Deleted an hour on, whether or not anything is asked then.
|
||||
setTimeout(dropExpiredCountries, COUNTRY_STALE_MS + 1000).unref?.();
|
||||
return reports;
|
||||
} catch (error) {
|
||||
// Out of points: nothing more is asked today.
|
||||
if (error.status === 402) budget.spent = true;
|
||||
// Never reached (offline): no read of the day it was counted in.
|
||||
if (error.unreached && budget.day === day && budget.reads > 0)
|
||||
budget.reads -= 1;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
return served(entry, COUNTRY_STALE_MS, 'worldnewsapi');
|
||||
}
|
||||
|
||||
const refusal = (read) =>
|
||||
read.missing
|
||||
? noKey(read.missing)
|
||||
: read.rejected
|
||||
? rejectedKey(read.rejected)
|
||||
: read.quota
|
||||
? spentKey(read.quota)
|
||||
: read.failed
|
||||
? { status: 502, body: { error: 'news_upstream_error' } }
|
||||
: null;
|
||||
|
||||
async function hotspots(params) {
|
||||
const read = await conflictReports();
|
||||
const refused = refusal(read);
|
||||
if (refused) return refused;
|
||||
const hours = Number(params.get('hours')) || 24;
|
||||
const since = new Date(now() - hours * HOUR_MS).toISOString();
|
||||
// The reports Conflicts lists: a minor one is in no count.
|
||||
const shown = read.reports.filter(
|
||||
(r) => r.publishedAt >= since && r.relevance !== 'minor',
|
||||
);
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
hotspots: [
|
||||
{
|
||||
id: WORLDWIDE_HOTSPOT,
|
||||
name: 'Worldwide',
|
||||
kind: 'conflict',
|
||||
catchAll: true,
|
||||
bbox: [-180, -90, 180, 90],
|
||||
parties: [],
|
||||
developing: [],
|
||||
counts: {
|
||||
last24h: shown.length,
|
||||
mapped24h: shown.filter((r) => r.geo).length,
|
||||
prev24h: null,
|
||||
},
|
||||
latestAt: shown[0]?.publishedAt ?? null,
|
||||
},
|
||||
],
|
||||
categories: CATEGORY_ORDER,
|
||||
ingest: { lastRunAt: new Date(read.readAt).toISOString() },
|
||||
windowHours: hours,
|
||||
maxWindowHours: 24,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Reports filtered, newest first, and paged by `before`. */
|
||||
function page(reports, params) {
|
||||
const since = params.get('since');
|
||||
const before = params.get('before');
|
||||
const dayAgo = new Date(now() - DAY_MS).toISOString();
|
||||
const categories = list(params.get('category'));
|
||||
const relevance = list(params.get('relevance'));
|
||||
const hotspot = params.get('hotspot');
|
||||
const limit = Number(params.get('limit')) || DEFAULT_LIMIT;
|
||||
const kept = reports.filter(
|
||||
(r) =>
|
||||
(!hotspot || hotspot === 'all' || r.hotspotIds.includes(hotspot)) &&
|
||||
(!since || r.publishedAt >= since) &&
|
||||
(!before || r.publishedAt < before) &&
|
||||
(!params.has('today') || r.publishedAt >= dayAgo) &&
|
||||
(!params.has('geo') || r.geo) &&
|
||||
(!categories || categories.has(r.category)) &&
|
||||
(!relevance || relevance.has(r.relevance)),
|
||||
);
|
||||
const shown = kept.slice(0, limit);
|
||||
// A page ends between two times: the next asks for those `before` the
|
||||
// last, and a GDELT export's reports all share its quarter hour.
|
||||
while (
|
||||
shown.length < kept.length &&
|
||||
kept[shown.length].publishedAt === shown.at(-1).publishedAt
|
||||
)
|
||||
shown.push(kept[shown.length]);
|
||||
const events = params.has('events');
|
||||
return {
|
||||
reports: events ? shown : shown.map(({ event, ...report }) => report),
|
||||
nextBefore: kept.length > shown.length ? shown.at(-1).publishedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function feed(params) {
|
||||
const at = params.has('at') ? point(params.get('at')) : null;
|
||||
const area = at ? areaAt(at.lat, at.lon) : null;
|
||||
if (!area) {
|
||||
// Conflicts, or Local at sea (by distance, in the browser).
|
||||
const read = await conflictReports();
|
||||
return refusal(read) || { status: 200, body: page(read.reports, params) };
|
||||
}
|
||||
// Local in a country: its own outlets, with the Conflicts reports
|
||||
// placed inside it (those failing leave the outlets'). In a disputed
|
||||
// area no country's outlets speak for it: the Conflicts reports there
|
||||
// alone, so their failing is the answer's.
|
||||
const country = area.kind === 'country';
|
||||
const [national, conflicts] = await Promise.all([
|
||||
country ? countryReports(area.country) : { reports: [] },
|
||||
conflictReports(),
|
||||
]);
|
||||
const refused = refusal(national) || (!country && refusal(conflicts));
|
||||
if (refused) return refused;
|
||||
const inside = (conflicts.reports || []).filter((r) =>
|
||||
areasOf(r).has(area.key),
|
||||
);
|
||||
const reports = [...national.reports, ...inside].sort((a, b) =>
|
||||
b.publishedAt.localeCompare(a.publishedAt),
|
||||
);
|
||||
return { status: 200, body: page(reports, params) };
|
||||
}
|
||||
|
||||
function outline(params) {
|
||||
if (params.has('at')) {
|
||||
const at = point(params.get('at'));
|
||||
const area = at ? areaAt(at.lat, at.lon) : null;
|
||||
if (!area) return { status: 200, body: EMPTY_OUTLINE };
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
...EMPTY_OUTLINE,
|
||||
polygons:
|
||||
area.kind === 'country'
|
||||
? countryPolygons(area.country)
|
||||
: area.polygons,
|
||||
area: {
|
||||
key: area.key,
|
||||
name: area.name,
|
||||
kind: area.kind,
|
||||
country: area.code,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
// A developing situation's country; the world has no outline.
|
||||
const country = countryByCode(
|
||||
String(params.get('country') ?? '').slice(0, 2),
|
||||
);
|
||||
return {
|
||||
status: 200,
|
||||
body: country
|
||||
? { ...EMPTY_OUTLINE, polygons: countryPolygons(country) }
|
||||
: EMPTY_OUTLINE,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
async answer(path, params) {
|
||||
dropExpiredCountries();
|
||||
if (path === '/hotspots') return hotspots(params);
|
||||
if (path === '/feed') return feed(params);
|
||||
if (path === '/outline') return outline(params);
|
||||
return { status: 404, body: { error: 'not_found' } };
|
||||
},
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,283 @@
|
||||
// The keyed news APIs Core reads itself when no news server is configured:
|
||||
// Liveuamap's worldwide feed (`a=mpts`) beside GDELT's events in the
|
||||
// Conflicts section (gdeltEvents.js), World News API's search by source
|
||||
// country for Local. Each key stays on the server: Liveuamap's rides in the query, so
|
||||
// neither a URL nor an error body is ever logged or relayed.
|
||||
|
||||
import { readResponseTextCapped } from '../common/http.js';
|
||||
|
||||
const LIVEUAMAP_URL = 'https://a.liveuamap.com/api';
|
||||
const WORLD_NEWS_URL = 'https://api.worldnewsapi.com/search-news';
|
||||
// 100 Liveuamap items run to about 500 KB.
|
||||
const LIVEUAMAP_COUNT = 500;
|
||||
const LIVEUAMAP_MAX_BYTES = 16 * 1024 * 1024;
|
||||
// One search per country: a point, and a hundredth of one per article, so
|
||||
// about 1.5 points a read (the free plan has 50 points a day).
|
||||
const WORLD_NEWS_ARTICLES = 50;
|
||||
const WORLD_NEWS_MAX_BYTES = 8 * 1024 * 1024;
|
||||
// World News API's categories that are not the news of the day. Its
|
||||
// `categories` filter is not asked for: it classifies few articles outside
|
||||
// English, so it would drop most of a country's own outlets; an article it
|
||||
// left unclassified is kept.
|
||||
export const WORLD_NEWS_LEFT_OUT = Object.freeze(
|
||||
new Set(['sports', 'entertainment', 'lifestyle', 'travel']),
|
||||
);
|
||||
const DAY_MS = 86_400_000;
|
||||
const TIMEOUT_MS = 20_000;
|
||||
|
||||
const ENTITIES = {
|
||||
amp: '&',
|
||||
quot: '"',
|
||||
apos: "'",
|
||||
lt: '<',
|
||||
gt: '>',
|
||||
nbsp: ' ',
|
||||
};
|
||||
|
||||
/** Text with HTML entities decoded and whitespace collapsed, or ''. */
|
||||
export function unescapeHtml(value) {
|
||||
return String(value ?? '')
|
||||
.replace(
|
||||
/&(?:#(\d{1,7})|#x([0-9a-f]{1,6})|([a-z]{2,6}));/gi,
|
||||
(all, dec, hex, name) => {
|
||||
if (name) return ENTITIES[name.toLowerCase()] ?? all;
|
||||
const code = dec ? Number(dec) : parseInt(hex, 16);
|
||||
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : all;
|
||||
},
|
||||
)
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** An https URL without credentials, or null. */
|
||||
export function webLink(value) {
|
||||
try {
|
||||
const url = new URL(String(value ?? '').trim());
|
||||
return url.protocol === 'https:' && !url.username && !url.password
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A clip a browser plays itself (an https MP4 or WebM file), or null. */
|
||||
export function playableVideo(value) {
|
||||
const url = webLink(value);
|
||||
return url && /\.(?:mp4|m4v|webm)$/i.test(new URL(url).pathname) ? url : null;
|
||||
}
|
||||
|
||||
const finiteNumber = (value) => {
|
||||
const number = typeof value === 'string' ? Number(value.trim()) : value;
|
||||
return typeof number === 'number' && Number.isFinite(number) ? number : null;
|
||||
};
|
||||
|
||||
/** Why an upstream could not be read; never carries its URL or body. */
|
||||
export class UpstreamError extends Error {
|
||||
constructor(
|
||||
message,
|
||||
{
|
||||
status = null,
|
||||
rejected = false,
|
||||
quota = false,
|
||||
unreadable = false,
|
||||
unreached = false,
|
||||
} = {},
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'UpstreamError';
|
||||
this.status = status;
|
||||
// The key was refused (401 or 403): the operator's to fix.
|
||||
this.rejected = rejected;
|
||||
// The key's allowance is spent (402, or the day's reads): it answers
|
||||
// again later. A 429 is a per-second limit, not this.
|
||||
this.quota = quota;
|
||||
// The answer itself cannot be read (corrupt, or over a size cap): asking
|
||||
// again gets the same.
|
||||
this.unreadable = unreadable;
|
||||
// The request got no answer at all (offline, timed out).
|
||||
this.unreached = unreached;
|
||||
}
|
||||
}
|
||||
|
||||
async function getText(
|
||||
fetchImpl,
|
||||
url,
|
||||
{ headers = {}, maxBytes, signal, what },
|
||||
) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
headers: { Accept: 'application/json', ...headers },
|
||||
redirect: 'error',
|
||||
signal: signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)])
|
||||
: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (cause) {
|
||||
// A request that timed out may have been read; one refused was not.
|
||||
const timedOut = cause?.name === 'TimeoutError';
|
||||
throw new UpstreamError(
|
||||
timedOut ? `${what} timed out` : `${what} unreachable`,
|
||||
{ unreached: !timedOut },
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
throw new UpstreamError(`${what} answered ${response.status}`, {
|
||||
status: response.status,
|
||||
rejected: response.status === 401 || response.status === 403,
|
||||
quota: response.status === 402,
|
||||
});
|
||||
}
|
||||
try {
|
||||
return await readResponseTextCapped(response, maxBytes, signal);
|
||||
} catch {
|
||||
throw new UpstreamError(`${what} answer unreadable`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJson(text, what) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
// Not the parser's message: an error answer may echo the request.
|
||||
throw new UpstreamError(`${what} answer unreadable`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Liveuamap's items with a headline, a point and a page:
|
||||
* `{id, title, lat, lon, place, publishedAt, url, image, video}`.
|
||||
*/
|
||||
export function parseLiveuamap(payload) {
|
||||
if (!Array.isArray(payload?.venues))
|
||||
throw new UpstreamError('Liveuamap answer unreadable');
|
||||
const items = [];
|
||||
for (const venue of payload.venues) {
|
||||
const id = finiteNumber(venue?.id);
|
||||
const title = unescapeHtml(venue?.name);
|
||||
const lat = finiteNumber(venue?.lat);
|
||||
const lon = finiteNumber(venue?.lng);
|
||||
const seconds = finiteNumber(venue?.timestamp);
|
||||
const url = webLink(venue?.link);
|
||||
if (
|
||||
id === null ||
|
||||
!title ||
|
||||
lat === null ||
|
||||
lon === null ||
|
||||
Math.abs(lat) > 90 ||
|
||||
Math.abs(lon) > 180 ||
|
||||
(lat === 0 && lon === 0) ||
|
||||
seconds === null ||
|
||||
!url
|
||||
)
|
||||
continue;
|
||||
items.push({
|
||||
id: Math.trunc(id),
|
||||
title,
|
||||
lat,
|
||||
lon,
|
||||
place: unescapeHtml(venue.location) || null,
|
||||
publishedAt: new Date(seconds * 1000).toISOString(),
|
||||
url,
|
||||
image: webLink(venue.img_share),
|
||||
video: playableVideo(venue.video),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The worldwide feed of the last day, as of `now`. */
|
||||
export async function fetchLiveuamap({ key, fetchImpl, now, signal }) {
|
||||
const url = new URL(LIVEUAMAP_URL);
|
||||
url.search = new URLSearchParams({
|
||||
a: 'mpts',
|
||||
resid: '1',
|
||||
time: String(Math.floor((now - DAY_MS) / 1000)),
|
||||
count: String(LIVEUAMAP_COUNT),
|
||||
key,
|
||||
}).toString();
|
||||
const text = await getText(fetchImpl, url, {
|
||||
maxBytes: LIVEUAMAP_MAX_BYTES,
|
||||
signal,
|
||||
what: 'Liveuamap',
|
||||
});
|
||||
return parseLiveuamap(parseJson(text, 'Liveuamap'));
|
||||
}
|
||||
|
||||
// World News API writes times as "2026-10-30 01:31:00", in UTC.
|
||||
const worldNewsTime = (ms) =>
|
||||
new Date(ms).toISOString().slice(0, 19).replace('T', ' ');
|
||||
function worldNewsDate(value) {
|
||||
const match = /^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)$/.exec(
|
||||
String(value ?? ''),
|
||||
);
|
||||
const ms = match ? Date.parse(`${match[1]}T${match[2]}Z`) : NaN;
|
||||
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A search's articles with a title, a link and a time, one per title (the
|
||||
* same story from several outlets is one), sport and entertainment left
|
||||
* out, newest first:
|
||||
* `{id, title, url, publisher, language, category, publishedAt, image, video}`.
|
||||
*/
|
||||
export function parseWorldNews(payload) {
|
||||
if (!Array.isArray(payload?.news))
|
||||
throw new UpstreamError('World News API answer unreadable');
|
||||
const seen = new Set();
|
||||
const articles = [];
|
||||
for (const article of payload.news) {
|
||||
const id = finiteNumber(article?.id);
|
||||
const title = unescapeHtml(article?.title);
|
||||
const url = webLink(article?.url);
|
||||
const publishedAt = worldNewsDate(article?.publish_date);
|
||||
const category =
|
||||
typeof article?.category === 'string'
|
||||
? article.category.toLowerCase()
|
||||
: null;
|
||||
if (id === null || !title || !url || !publishedAt) continue;
|
||||
if (WORLD_NEWS_LEFT_OUT.has(category)) continue;
|
||||
const same = title.toLowerCase();
|
||||
if (seen.has(same)) continue;
|
||||
seen.add(same);
|
||||
articles.push({
|
||||
id: Math.trunc(id),
|
||||
title,
|
||||
url,
|
||||
publisher: new URL(url).hostname.replace(/^www\./, ''),
|
||||
language:
|
||||
typeof article.language === 'string' &&
|
||||
/^[a-z]{2}$/i.test(article.language)
|
||||
? article.language.toLowerCase()
|
||||
: null,
|
||||
category,
|
||||
publishedAt,
|
||||
image: webLink(article.image),
|
||||
video: playableVideo(article.video),
|
||||
});
|
||||
}
|
||||
return articles.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt));
|
||||
}
|
||||
|
||||
/** A country's everyday news of the last day, as of `now`. */
|
||||
export async function fetchWorldNews({ key, country, fetchImpl, now, signal }) {
|
||||
const url = new URL(WORLD_NEWS_URL);
|
||||
url.search = new URLSearchParams({
|
||||
'source-country': country.toLowerCase(),
|
||||
// Both ends: sorted by time with neither, a search is cut to 31 days.
|
||||
'earliest-publish-date': worldNewsTime(now - DAY_MS),
|
||||
'latest-publish-date': worldNewsTime(now),
|
||||
sort: 'publish-time',
|
||||
'sort-direction': 'DESC',
|
||||
number: String(WORLD_NEWS_ARTICLES),
|
||||
}).toString();
|
||||
const text = await getText(fetchImpl, url, {
|
||||
headers: { 'x-api-key': key },
|
||||
maxBytes: WORLD_NEWS_MAX_BYTES,
|
||||
signal,
|
||||
what: 'World News API',
|
||||
});
|
||||
return parseWorldNews(parseJson(text, 'World News API'));
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { fetchRegionalPlace } from './place.js';
|
||||
import { fetchRegionalWeather } from './weather.js';
|
||||
import { fetchRegionalNews } from './news.js';
|
||||
import { validRegionalPoint } from './query.js';
|
||||
import { REGIONAL_NEWS_WINDOW_HOURS } from '../../../src/data/regionalModel.js';
|
||||
import { coalesceProxyRequest } from '../common/http.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -50,10 +51,11 @@ function regionalBriefProxy({ placeProvider = fetchRegionalPlace } = {}) {
|
||||
if (!regionalBriefHasAnySource({ place, weather, news })) {
|
||||
throw new Error('All regional briefing sources unavailable');
|
||||
}
|
||||
const retrievedAt = new Date().toISOString();
|
||||
const payload = {
|
||||
status:
|
||||
place && weather && news.status !== 'unavailable' ? 'ready' : 'partial',
|
||||
retrievedAt: new Date().toISOString(),
|
||||
retrievedAt,
|
||||
coordinates: point,
|
||||
place,
|
||||
placeStatus: place ? 'ready' : 'unavailable',
|
||||
@@ -62,6 +64,9 @@ function regionalBriefProxy({ placeProvider = fetchRegionalPlace } = {}) {
|
||||
newsStatus: news.status,
|
||||
newsQuery: news.query,
|
||||
newsSource: news.source,
|
||||
newsWindowHours: REGIONAL_NEWS_WINDOW_HOURS,
|
||||
// A cached or stale answer keeps this, so the client can show its age.
|
||||
newsFetchedAt: retrievedAt,
|
||||
articles: news.articles,
|
||||
};
|
||||
_regionalBriefCache.set(key, { payload, cachedAt: Date.now() });
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { fetchRegionalText, fetchRegionalJson } from './http.js';
|
||||
import { normalizeRegionalArticles } from '../../../src/data/regionalModel.js';
|
||||
import {
|
||||
REGIONAL_NEWS_WINDOW_HOURS,
|
||||
googleNewsWindowOperator,
|
||||
normalizeRegionalArticles,
|
||||
recentRegionalArticles,
|
||||
} from '../../../src/data/regionalModel.js';
|
||||
|
||||
function decodeRssText(value) {
|
||||
return String(value || '')
|
||||
@@ -22,7 +27,10 @@ function rssTag(block, tag) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeRssArticles(xml, limit = 5) {
|
||||
// Feed items read before the window filter; Google returns about 100.
|
||||
const RSS_ITEM_CAP = 100;
|
||||
|
||||
function normalizeRssArticles(xml, limit = RSS_ITEM_CAP) {
|
||||
const seen = new Set();
|
||||
const articles = [];
|
||||
for (const match of String(xml || '').matchAll(
|
||||
@@ -57,12 +65,27 @@ function normalizeRssArticles(xml, limit = 5) {
|
||||
return articles;
|
||||
}
|
||||
|
||||
async function fetchRegionalNews(place) {
|
||||
/**
|
||||
* Headlines for a place from the last REGIONAL_NEWS_WINDOW_HOURS, newest
|
||||
* first: Google News RSS, then GDELT when RSS fails or has nothing recent.
|
||||
* `empty` means a source answered with nothing in the window; `unavailable`
|
||||
* means there was no place or no source answered.
|
||||
* @param {{locality?: string, region?: string, country?: string}|null} place
|
||||
* @param {{now?: () => number}} [options]
|
||||
*/
|
||||
async function fetchRegionalNews(place, { now = Date.now } = {}) {
|
||||
const query = place?.locality || place?.region || place?.country;
|
||||
if (!query)
|
||||
return { status: 'unavailable', query: null, articles: [], source: null };
|
||||
const recent = (articles) =>
|
||||
recentRegionalArticles(articles, {
|
||||
now: now(),
|
||||
windowHours: REGIONAL_NEWS_WINDOW_HOURS,
|
||||
limit: 5,
|
||||
});
|
||||
let answered = false;
|
||||
const rssParams = new URLSearchParams({
|
||||
q: String(query).replace(/["\\]/g, ' ').trim(),
|
||||
q: `${String(query).replace(/["\\]/g, ' ').trim()} ${googleNewsWindowOperator()}`,
|
||||
hl: 'en-US',
|
||||
gl: 'US',
|
||||
ceid: 'US:en',
|
||||
@@ -75,7 +98,8 @@ async function fetchRegionalNews(place) {
|
||||
timeoutMs: 12_000,
|
||||
},
|
||||
);
|
||||
const articles = normalizeRssArticles(xml, 5);
|
||||
answered = true;
|
||||
const articles = recent(normalizeRssArticles(xml));
|
||||
if (articles.length)
|
||||
return { status: 'ready', query, articles, source: 'Google News RSS' };
|
||||
} catch {
|
||||
@@ -87,7 +111,7 @@ async function fetchRegionalNews(place) {
|
||||
format: 'json',
|
||||
maxrecords: '5',
|
||||
sort: 'datedesc',
|
||||
timespan: '48h',
|
||||
timespan: `${REGIONAL_NEWS_WINDOW_HOURS}h`,
|
||||
});
|
||||
try {
|
||||
const payload = await fetchRegionalJson(
|
||||
@@ -97,7 +121,7 @@ async function fetchRegionalNews(place) {
|
||||
timeoutMs: 12_000,
|
||||
},
|
||||
);
|
||||
const articles = normalizeRegionalArticles(payload, 5);
|
||||
const articles = recent(normalizeRegionalArticles(payload, 5));
|
||||
return {
|
||||
status: articles.length ? 'ready' : 'empty',
|
||||
query,
|
||||
@@ -105,7 +129,10 @@ async function fetchRegionalNews(place) {
|
||||
source: 'GDELT fallback',
|
||||
};
|
||||
} catch {
|
||||
return { status: 'unavailable', query, articles: [], source: null };
|
||||
// An RSS answer with nothing recent is still a true empty result.
|
||||
return answered
|
||||
? { status: 'empty', query, articles: [], source: 'Google News RSS' }
|
||||
: { status: 'unavailable', query, articles: [], source: null };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import {
|
||||
EMODNET_WFS_URL,
|
||||
WIKIDATA_QUERY,
|
||||
mergeShipwreckRecords,
|
||||
normalizeEmodnetFeatures,
|
||||
normalizeWikidataResults,
|
||||
} from '../../src/layers/shipwrecks/records.js';
|
||||
import { coalesceProxyRequest, readResponseJsonCapped } from './common/http.js';
|
||||
import { clientKey, makeRateLimiter } from './common/rate-limit.js';
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
/** EMODnet republishes the wreck layer about once a year; Wikidata daily at most. */
|
||||
const REFRESH_MS = 24 * 60 * 60 * 1000;
|
||||
/** A source's last good records keep being served this long, marked stale. */
|
||||
const STALE_MAX_MS = 7 * REFRESH_MS;
|
||||
/** After a source fails, it is not asked again for this long. */
|
||||
const RETRY_MS = 15 * 60 * 1000;
|
||||
/** A refresh with fewer than this share of the last good records is refused. */
|
||||
const MIN_KEEP_RATIO = 0.5;
|
||||
// Only the columns the card uses; ship_char/obj_desc histories can name people
|
||||
// and are not read beyond a short vessel type.
|
||||
const EMODNET_PROPERTIES = [
|
||||
'source_id',
|
||||
'country',
|
||||
'name',
|
||||
'least_depth',
|
||||
'depth_prec',
|
||||
'loc_prec',
|
||||
'sink_context',
|
||||
'sink_yr',
|
||||
'dating',
|
||||
'period',
|
||||
'statutory',
|
||||
'ship_char',
|
||||
'obj_type',
|
||||
'artefacts',
|
||||
'source_inf',
|
||||
'website1',
|
||||
'point_info',
|
||||
'the_geom',
|
||||
].join(',');
|
||||
const EMODNET_URL = `${EMODNET_WFS_URL}&propertyName=${EMODNET_PROPERTIES}`;
|
||||
const WIKIDATA_URL =
|
||||
'https://query.wikidata.org/sparql?format=json&query=' +
|
||||
encodeURIComponent(WIKIDATA_QUERY);
|
||||
// Wikimedia asks automated clients to name themselves.
|
||||
const USER_AGENT =
|
||||
"God's Eye View shipwrecks layer (https://github.com/bilawalsidhu/gods-eye-view)";
|
||||
|
||||
/** Fixed-origin, cached EMODnet + Wikidata shipwreck snapshot for dev and preview. */
|
||||
export function shipwrecksProxy({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
now = () => Date.now(),
|
||||
} = {}) {
|
||||
// Each source keeps its last good records on its own, so one failing (or
|
||||
// answering with nothing usable) never removes the other's wrecks or its
|
||||
// own earlier ones. `retryAt` holds a failed source back for RETRY_MS.
|
||||
const sources = {
|
||||
emodnet: { load: fetchEmodnet, good: null, retryAt: 0 },
|
||||
wikidata: { load: fetchWikidata, good: null, retryAt: 0 },
|
||||
};
|
||||
let snapshot = null;
|
||||
const inFlight = new Map();
|
||||
const allow = makeRateLimiter({ windowMs: 60_000, max: 30, globalMax: 600 });
|
||||
|
||||
async function upstreamJson(url, maxBytes) {
|
||||
const signal = AbortSignal.timeout(90_000);
|
||||
const response = await fetchImpl(url, {
|
||||
signal,
|
||||
redirect: 'error',
|
||||
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new Error('upstream_unavailable');
|
||||
}
|
||||
return readResponseJsonCapped(response, maxBytes, signal);
|
||||
}
|
||||
|
||||
async function fetchEmodnet() {
|
||||
const records = normalizeEmodnetFeatures(
|
||||
await upstreamJson(EMODNET_URL, 32 * MIB),
|
||||
);
|
||||
if (!records.length) throw new Error('invalid_emodnet_layer');
|
||||
return records;
|
||||
}
|
||||
|
||||
async function fetchWikidata() {
|
||||
const payload = await upstreamJson(WIKIDATA_URL, 16 * MIB);
|
||||
if (!Array.isArray(payload?.results?.bindings))
|
||||
throw new Error('invalid_wikidata_results');
|
||||
const records = normalizeWikidataResults(payload);
|
||||
// Wikidata lists over a thousand wrecks; none at all is a broken answer.
|
||||
if (!records.length) throw new Error('invalid_wikidata_results');
|
||||
return records;
|
||||
}
|
||||
|
||||
const fresh = (state, at) =>
|
||||
state.good !== null && at - state.good.fetchedAt < REFRESH_MS;
|
||||
const usable = (state, at) =>
|
||||
state.good !== null && at - state.good.fetchedAt <= STALE_MAX_MS;
|
||||
const due = (state, at) => !fresh(state, at) && at >= state.retryAt;
|
||||
|
||||
/** Refresh the sources that are due; failures keep their last good records. */
|
||||
async function refresh() {
|
||||
const at = now();
|
||||
const names = Object.keys(sources).filter((name) => due(sources[name], at));
|
||||
const results = await Promise.allSettled(
|
||||
names.map((name) => sources[name].load()),
|
||||
);
|
||||
const done = now();
|
||||
results.forEach((result, i) => {
|
||||
const state = sources[names[i]];
|
||||
// A valid answer far smaller than the last good set (a truncated or
|
||||
// half-built upstream) is a failure too, until the old set expires.
|
||||
const shrunk =
|
||||
result.status === 'fulfilled' &&
|
||||
usable(state, done) &&
|
||||
result.value.length < state.good.records.length * MIN_KEEP_RATIO;
|
||||
if (result.status === 'fulfilled' && !shrunk)
|
||||
state.good = { records: result.value, fetchedAt: done };
|
||||
else state.retryAt = done + RETRY_MS;
|
||||
if (shrunk)
|
||||
console.warn(
|
||||
`[shipwrecks] ${names[i]} refresh refused: ${result.value.length} ` +
|
||||
`records against ${state.good.records.length} last good`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** The served snapshot: every source with usable records, merged once. */
|
||||
function compose(at) {
|
||||
const sourceFlags = {};
|
||||
// How old each source's records are, on this clock, so the page can
|
||||
// expire them by its own clock without comparing the two.
|
||||
const ages = {};
|
||||
let stale = false;
|
||||
let fetchedAt = null;
|
||||
for (const [name, state] of Object.entries(sources)) {
|
||||
sourceFlags[name] = usable(state, at);
|
||||
ages[name] = sourceFlags[name] ? at - state.good.fetchedAt : null;
|
||||
if (!sourceFlags[name]) continue;
|
||||
if (!fresh(state, at)) stale = true;
|
||||
fetchedAt = Math.min(fetchedAt ?? Infinity, state.good.fetchedAt);
|
||||
}
|
||||
if (!sourceFlags.emodnet && !sourceFlags.wikidata) return null;
|
||||
const key = `${sourceFlags.emodnet && sources.emodnet.good.fetchedAt}:${
|
||||
sourceFlags.wikidata && sources.wikidata.good.fetchedAt
|
||||
}`;
|
||||
if (snapshot?.key !== key) {
|
||||
// The merge writes EMODnet facts into Wikidata records: work on copies
|
||||
// so a source's kept records stay as fetched.
|
||||
const copy = (name) =>
|
||||
sourceFlags[name]
|
||||
? sources[name].good.records.map((record) => ({ ...record }))
|
||||
: [];
|
||||
snapshot = {
|
||||
key,
|
||||
records: mergeShipwreckRecords(copy('emodnet'), copy('wikidata')),
|
||||
};
|
||||
}
|
||||
return {
|
||||
value: {
|
||||
fetchedAt,
|
||||
version: key,
|
||||
sources: sourceFlags,
|
||||
ages,
|
||||
maxAgeMs: STALE_MAX_MS,
|
||||
records: snapshot.records,
|
||||
},
|
||||
stale,
|
||||
};
|
||||
}
|
||||
|
||||
async function acquire() {
|
||||
const at = now();
|
||||
if (Object.values(sources).some((state) => due(state, at)))
|
||||
await coalesceProxyRequest(inFlight, 'refresh', refresh).promise;
|
||||
const composed = compose(now());
|
||||
if (!composed) throw new Error('shipwrecks_unavailable');
|
||||
return composed;
|
||||
}
|
||||
|
||||
async function handler(req, res) {
|
||||
const json = (status, value, stale = false) => {
|
||||
if (res.destroyed) return;
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-store',
|
||||
...(status === 405 ? { Allow: 'GET' } : {}),
|
||||
...(status === 429 ? { 'Retry-After': '60' } : {}),
|
||||
...(stale ? { 'X-Data-Stale': 'true' } : {}),
|
||||
});
|
||||
res.end(JSON.stringify(value));
|
||||
};
|
||||
if (req.method !== 'GET') return json(405, { error: 'method_not_allowed' });
|
||||
const path = (req.url || '/').split('?')[0];
|
||||
if (path !== '/' && path !== '')
|
||||
return json(404, { error: 'unknown_route' });
|
||||
if (!allow(clientKey(req))) return json(429, { error: 'rate_limited' });
|
||||
try {
|
||||
const { value, stale } = await acquire();
|
||||
json(200, stale ? { ...value, stale: true } : value, stale);
|
||||
} catch {
|
||||
json(502, { error: 'shipwrecks_unavailable' });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: 'shipwrecks',
|
||||
configureServer({ middlewares }) {
|
||||
middlewares.use('/api/shipwrecks', handler);
|
||||
},
|
||||
configurePreviewServer({ middlewares }) {
|
||||
middlewares.use('/api/shipwrecks', handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -30,7 +30,9 @@ import { createApplicationAirQuality } from './layers/airQuality.js';
|
||||
import { createApplicationFirePerimeters } from './layers/perimeters.js';
|
||||
import { createApplicationGnssIntegrity } from './layers/gnss.js';
|
||||
import { createApplicationGhostMaps } from './layers/ghostMaps.js';
|
||||
import { createApplicationShipwrecks } from './layers/shipwrecks.js';
|
||||
import { createApplicationDroneAirspace } from './layers/droneAirspace.js';
|
||||
import { createApplicationNews } from './layers/news.js';
|
||||
import { createApplicationWildlifeSightings } from './layers/wildlifeSightings.js';
|
||||
import { createApplicationCables } from './layers/submarineCables.js';
|
||||
import { createOsmOverlayLayers } from '../data/osmOverlays.js';
|
||||
@@ -136,9 +138,11 @@ export function createApplicationCatalog({
|
||||
windowMs: sources['gnss-integrity'].windowMs,
|
||||
}),
|
||||
createApplicationGhostMaps({ source: sources['s2-ghostmaps'] }),
|
||||
createApplicationShipwrecks({ source: sources.shipwrecks }),
|
||||
createApplicationDroneAirspace({
|
||||
source: sources['drone-airspace'],
|
||||
}),
|
||||
createApplicationNews({ source: sources.news }),
|
||||
createApplicationWildlifeSightings({
|
||||
source: sources['wildlife-sightings'],
|
||||
groundFloor: surface.groundFloor,
|
||||
|
||||
@@ -40,7 +40,7 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
signal: b.signal,
|
||||
surface: fixtureSurface(b.signal),
|
||||
});
|
||||
assert.equal(first.layers.length, 38);
|
||||
assert.equal(first.layers.length, 40);
|
||||
assert.ok(first.get('local-adsb'), 'Local ADS-B is registered');
|
||||
assert.deepEqual(
|
||||
first.metadata.find(({ id }) => id === 'osm-places'),
|
||||
@@ -68,6 +68,7 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
assert.ok(first.get('gnss-integrity'));
|
||||
assert.ok(first.get('s2-ghostmaps'));
|
||||
assert.ok(first.get('drone-airspace'));
|
||||
assert.ok(first.get('news'));
|
||||
assert.ok(first.get('transit'));
|
||||
const order = first.layers.map(({ id }) => id);
|
||||
assert.deepEqual(
|
||||
@@ -161,7 +162,7 @@ test('Mapillary can be omitted or replaced without changing catalog membership',
|
||||
surface: fixtureSurface(lifetime.signal),
|
||||
};
|
||||
const catalog = createApplicationCatalog(options);
|
||||
assert.equal(catalog.layers.length, 38);
|
||||
assert.equal(catalog.layers.length, 40);
|
||||
assert.deepEqual(catalog.get('street-level').providerIds, []);
|
||||
assert.equal(
|
||||
catalogControlServices(catalog).streetLevelLayer,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createNewsLayer } from '../../layers/news/index.js';
|
||||
import { overlayHost } from './overlayHost.js';
|
||||
/** Wire the news layer to the application overlay host. */
|
||||
export function createApplicationNews(options) {
|
||||
return createNewsLayer({ overlayHost, ...options });
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createShipwrecksLayer } from '../../layers/shipwrecks/index.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
|
||||
/** Wire the EMODnet + Wikidata shipwrecks layer into the application catalog. */
|
||||
export function createApplicationShipwrecks(options) {
|
||||
return createShipwrecksLayer({
|
||||
overlayHost: {
|
||||
setEntries: overlays.setOverlayEntries,
|
||||
setVisible: overlays.setOverlaySourceVisible,
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
|
||||
screenSpaceEventHandlerFactory: (viewer) =>
|
||||
new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas),
|
||||
picking,
|
||||
pointer: { isPointerFree },
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -49,7 +49,9 @@ export const CATALOG_SOURCE_CONTRACTS = Object.freeze({
|
||||
'air-quality': contract(['air-quality'], ['getSnapshot']),
|
||||
'gnss-integrity': contract(['gnss-integrity'], ['getSnapshot']),
|
||||
's2-ghostmaps': contract(['s2-ghostmaps'], ['getCatalog', 'getFile']),
|
||||
shipwrecks: contract(['shipwrecks'], ['getSnapshot']),
|
||||
'drone-airspace': contract(['drone-airspace'], ['getSnapshot']),
|
||||
news: contract(['news'], ['getHotspots', 'getFeed', 'getOutline']),
|
||||
'wildlife-sightings': contract(['wildlife-sightings'], ['getSnapshot']),
|
||||
cables: contract(['telegeography-submarine-cables'], ['fetch']),
|
||||
transit: contract(['transit'], ['requestSnapshot', 'getHistory']),
|
||||
|
||||
@@ -37,7 +37,7 @@ test('every acquisition source can be omitted without losing catalog membership'
|
||||
|
||||
test('all acquisition sources may be absent, and enable fails before initializing or fetching', async (t) => {
|
||||
const actual = catalog({}, t);
|
||||
assert.equal(actual.layers.length, 38);
|
||||
assert.equal(actual.layers.length, 40);
|
||||
const manager = new LayerLifecycle(
|
||||
{},
|
||||
{ getSourceAvailability: actual.getSourceAvailability },
|
||||
@@ -150,6 +150,35 @@ test('GhostMaps obeys source omission, replacement and explicit removal', async
|
||||
assert.equal(fetches, 0);
|
||||
});
|
||||
|
||||
test('News is unavailable without a source and the standalone default reads only same-origin /api/news', async (t) => {
|
||||
const missing = catalog({}, t);
|
||||
assert.equal(missing.getSourceAvailability('news')?.available, false);
|
||||
const manager = new LayerLifecycle(
|
||||
{},
|
||||
{ getSourceAvailability: missing.getSourceAvailability },
|
||||
);
|
||||
manager.register(missing.get('news'));
|
||||
assert.equal(await manager.setEnabled('news', true), false);
|
||||
assert.equal(manager.layers.get('news').initialized, false);
|
||||
assert.equal(createStandaloneLayerSources({ news: null }).news, null);
|
||||
|
||||
const urls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
urls.push(url);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: 'news_not_configured',
|
||||
unavailable: true,
|
||||
retryable: false,
|
||||
}),
|
||||
{ status: 503 },
|
||||
);
|
||||
});
|
||||
const standalone = createStandaloneLayerSources().news;
|
||||
await assert.rejects(standalone.getHotspots(), { unavailable: true });
|
||||
assert.deepEqual(urls, ['/api/news/hotspots']);
|
||||
});
|
||||
|
||||
test('empty Street Level uses the shared unavailable lifecycle without initialization', async (t) => {
|
||||
const actual = catalog({}, t);
|
||||
const manager = new LayerLifecycle(
|
||||
|
||||
@@ -573,6 +573,38 @@ export const DATA_CREDITS = [
|
||||
'licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a>. ' +
|
||||
'Shown as published; reports are S2 assessments, not verified fact.',
|
||||
},
|
||||
{
|
||||
key: 'news',
|
||||
html:
|
||||
'News: every report is credited to its own publisher and links to the original article; ' +
|
||||
'pictures are the publishers’ own, shown from their sites with the publisher named. ' +
|
||||
'Places, categories, severity and English headlines are derived automatically, by ' +
|
||||
'bundled rules, the news provider or the configured news server, and can be wrong.',
|
||||
},
|
||||
{
|
||||
// GDELT's terms ask for a citation and a link.
|
||||
key: 'gdelt-news',
|
||||
html:
|
||||
'News, Conflicts without a news server: events and page titles from the ' +
|
||||
'<a href="https://www.gdeltproject.org/" target="_blank" rel="noopener">GDELT Project</a> ' +
|
||||
'(GDELT 2.0 events and GKG; places and categories are machine-coded)',
|
||||
},
|
||||
{
|
||||
// World News API's free plan asks for a visible "World News API" link to
|
||||
// its site; always listed, so a free-plan key is never shown without it.
|
||||
key: 'worldnewsapi',
|
||||
html:
|
||||
'News, Local without a news server: headlines from ' +
|
||||
'<a href="https://worldnewsapi.com/" target="_blank" rel="noopener">World News API</a>',
|
||||
},
|
||||
{
|
||||
key: 'shipwrecks',
|
||||
html:
|
||||
'Shipwrecks (Europe): <a href="https://emodnet.ec.europa.eu/en/human-activities" target="_blank" rel="noopener">EMODnet Human Activities</a> ' +
|
||||
'(data originator AND-International, compiled from SHOM, Ireland’s National Monuments Service, Historic England and the Oxford Roman Economy Project), ' +
|
||||
'licensed under <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>' +
|
||||
' · Shipwrecks (worldwide): <a href="https://www.wikidata.org/" target="_blank" rel="noopener">Wikidata</a> (CC0)',
|
||||
},
|
||||
{
|
||||
key: 'drivebc-cctv',
|
||||
html:
|
||||
@@ -639,6 +671,15 @@ export const TOMTOM_CREDIT = {
|
||||
'<a href="https://www.tomtom.com" target="_blank" rel="noopener">TomTom</a>',
|
||||
};
|
||||
|
||||
/** Registered when the News layer shows a Liveuamap report (only with
|
||||
* LIVEUAMAP_API_KEY set and no news server). */
|
||||
export const LIVEUAMAP_CREDIT = {
|
||||
key: 'liveuamap',
|
||||
html:
|
||||
'News, Conflicts: mapped reports from ' +
|
||||
'<a href="https://liveuamap.com/" target="_blank" rel="noopener">Liveuamap</a>',
|
||||
};
|
||||
|
||||
/** Registered when the first Natural Earth region or state/province outline
|
||||
* resolves (public domain — no attribution required; credited as a courtesy). */
|
||||
export const NATURAL_EARTH_CREDIT = {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DATA_CREDITS,
|
||||
LIVEUAMAP_CREDIT,
|
||||
NYC_DOT_DISCLAIMER,
|
||||
transitFeedCredit,
|
||||
} from './dataCredits.js';
|
||||
@@ -189,6 +190,26 @@ test('every Street Level imagery source is in the attribution lightbox', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('the News layer credits its built-in sources', () => {
|
||||
const credit = (key) => DATA_CREDITS.find((entry) => entry.key === key);
|
||||
// GDELT's terms ask for a citation and a link.
|
||||
assert.match(
|
||||
credit('gdelt-news').html,
|
||||
/href="https:\/\/www\.gdeltproject\.org\/"[^>]*>GDELT Project</,
|
||||
);
|
||||
// World News API's free plan asks for this exact link.
|
||||
assert.match(
|
||||
credit('worldnewsapi').html,
|
||||
/<a href="https:\/\/worldnewsapi\.com\/"[^>]*>World News API<\/a>/,
|
||||
);
|
||||
assert.match(LIVEUAMAP_CREDIT.html, />Liveuamap</);
|
||||
assert.ok(
|
||||
!DATA_CREDITS.some((entry) => entry.key === LIVEUAMAP_CREDIT.key),
|
||||
'Liveuamap is credited only once its key is in use',
|
||||
);
|
||||
assert.doesNotMatch(credit('news').html, /No single provider/);
|
||||
});
|
||||
|
||||
test('the PR #1506 camera packs are credited with their sources and terms', () => {
|
||||
const html = (key) => DATA_CREDITS.find((entry) => entry.key === key)?.html;
|
||||
assert.match(html('ottawa-cctv') || '', /traffic\.ottawa\.ca/);
|
||||
|
||||
@@ -693,6 +693,7 @@ export const LAYER_STATE_REGISTRY = Object.freeze([
|
||||
token: 'i',
|
||||
disposition: 'enabled-only',
|
||||
}),
|
||||
Object.freeze({ id: 'news', token: '00', disposition: 'enabled-only' }),
|
||||
Object.freeze({
|
||||
id: 'radio',
|
||||
token: 'r',
|
||||
@@ -722,6 +723,7 @@ export const LAYER_STATE_REGISTRY = Object.freeze([
|
||||
optionOwner: 'satellites',
|
||||
}),
|
||||
Object.freeze({ id: 'sea-marks', token: '6', disposition: 'enabled-only' }),
|
||||
Object.freeze({ id: 'shipwrecks', token: '01', disposition: 'enabled-only' }),
|
||||
Object.freeze({ id: 'ski-pistes', token: '7', disposition: 'enabled-only' }),
|
||||
Object.freeze({
|
||||
id: 'street-level',
|
||||
|
||||
@@ -203,8 +203,8 @@ function encode(state) {
|
||||
|
||||
test('production registry is exact, canonical, and rejects incomplete contracts', async () => {
|
||||
assert.equal(validateLayerStateRegistry(), true);
|
||||
assert.equal(REGISTERED_LAYER_IDS.length, 36);
|
||||
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 36);
|
||||
assert.equal(REGISTERED_LAYER_IDS.length, 38);
|
||||
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 38);
|
||||
assert.ok(REGISTERED_LAYER_IDS.includes('transit'));
|
||||
assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort());
|
||||
assert.deepEqual(LEGACY_LAYER_STATE_TOKENS, {
|
||||
@@ -243,17 +243,23 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
for (const [id, token] of Object.entries(LEGACY_LAYER_STATE_TOKENS)) {
|
||||
assert.equal(LAYER_STATE_TOKEN_RESERVATIONS[id], token);
|
||||
}
|
||||
assert.equal(nextLayerStateToken(), '00');
|
||||
// News holds 00 and Shipwrecks 01, the first pairs: the next token is 02.
|
||||
assert.equal(nextLayerStateToken(), '02');
|
||||
// The allocation rules below read the ledger before either took a pair.
|
||||
const beforeNews = { ...LAYER_STATE_TOKEN_RESERVATIONS };
|
||||
delete beforeNews.news;
|
||||
delete beforeNews.shipwrecks;
|
||||
assert.equal(nextLayerStateToken(beforeNews), '00');
|
||||
assert.equal(
|
||||
nextLayerStateToken({
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
...beforeNews,
|
||||
alpha: '9',
|
||||
bravo: '00',
|
||||
}),
|
||||
'01',
|
||||
);
|
||||
const digitsExhausted = {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
...beforeNews,
|
||||
...Object.fromEntries([...'9'].map((digit) => [`prior-${digit}`, digit])),
|
||||
};
|
||||
assert.equal(nextLayerStateToken(digitsExhausted), '00');
|
||||
@@ -304,8 +310,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
validateLayerStateAllocations(beforeNews, {
|
||||
...beforeNews,
|
||||
future: '00',
|
||||
next: '01',
|
||||
}),
|
||||
@@ -313,8 +319,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
validateLayerStateAllocations(beforeNews, {
|
||||
...beforeNews,
|
||||
future: '01',
|
||||
}),
|
||||
/next free token 00/,
|
||||
@@ -341,8 +347,8 @@ test('production registry is exact, canonical, and rejects incomplete contracts'
|
||||
assert.throws(
|
||||
() =>
|
||||
validateLayerStateAllocations(
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9' },
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '9', competing: '9' },
|
||||
{ ...beforeNews, merged: '9' },
|
||||
{ ...beforeNews, merged: '9', competing: '9' },
|
||||
),
|
||||
/next free token 00/,
|
||||
);
|
||||
@@ -500,7 +506,7 @@ test('unknown enabled-layer tokens reject the payload instead of becoming an emp
|
||||
});
|
||||
|
||||
test('malformed enabled-layer lists reject the entire payload', () => {
|
||||
for (const value of ['.c', 'c.', 'c..e', 'c.c', '00', 'c.00']) {
|
||||
for (const value of ['.c', 'c.', 'c..e', 'c.c', 'zz', 'c.zz']) {
|
||||
assert.equal(
|
||||
decodeLayerStateParams(new URLSearchParams(`v=2&l=${value}`)),
|
||||
null,
|
||||
|
||||
@@ -97,8 +97,10 @@ function withPublishedBase(
|
||||
}
|
||||
}
|
||||
|
||||
const preWildlifeRows = reservationRows.filter(
|
||||
([id]) => id !== 'wildlife-sightings',
|
||||
// The ledger before Wildlife Sightings took the last digit and News and
|
||||
// Shipwrecks the first pairs, for the allocation rules written against it.
|
||||
const beforeLastDigitRows = reservationRows.filter(
|
||||
([id]) => !['wildlife-sightings', 'news', 'shipwrecks'].includes(id),
|
||||
);
|
||||
|
||||
function writeCodecFixture(cwd, rows, entries) {
|
||||
@@ -115,6 +117,16 @@ function writeCodecFixture(cwd, rows, entries) {
|
||||
/ Object\.freeze\(\{\s*id: 'wildlife-sightings',[\s\S]*?\}\),\n/,
|
||||
'',
|
||||
);
|
||||
if (!rows.some(([id]) => id === 'news'))
|
||||
source = source.replace(
|
||||
/ Object\.freeze\(\{\s*id: 'news',[\s\S]*?\}\),\n/,
|
||||
'',
|
||||
);
|
||||
if (!rows.some(([id]) => id === 'shipwrecks'))
|
||||
source = source.replace(
|
||||
/ Object\.freeze\(\{\s*id: 'shipwrecks',[\s\S]*?\}\),\n/,
|
||||
'',
|
||||
);
|
||||
const registryEnd = ']);\n\nexport const REGISTERED_LAYER_IDS';
|
||||
assert.equal(source.split(registryEnd).length, 2);
|
||||
const additions = entries
|
||||
@@ -138,7 +150,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
{ ...parseLayerStateTokenReservations(reservationRows) },
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS },
|
||||
);
|
||||
assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 36);
|
||||
assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 38);
|
||||
assert.deepEqual(
|
||||
{ ...LAYER_STATE_TOKEN_RESERVATIONS },
|
||||
{
|
||||
@@ -151,6 +163,8 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
'ski-pistes': '7',
|
||||
'drone-airspace': '8',
|
||||
'wildlife-sightings': '9',
|
||||
news: '00',
|
||||
shipwrecks: '01',
|
||||
},
|
||||
);
|
||||
assert.throws(
|
||||
@@ -176,9 +190,9 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
/Duplicate layer-state token reservation/,
|
||||
);
|
||||
assert.equal(
|
||||
parseLayerStateTokenReservations([...reservationRows, ['future', '00']])
|
||||
parseLayerStateTokenReservations([...reservationRows, ['future', '02']])
|
||||
.future,
|
||||
'00',
|
||||
'02',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
@@ -196,7 +210,7 @@ test('reservation ledger is complete, pinned, and rejects duplicate or malformed
|
||||
|
||||
test('published retired digits and competing PRs advance the merge-time allocation', () => {
|
||||
withPublishedBase(
|
||||
{ rows: [...preWildlifeRows, ['retired-layer', '9']] },
|
||||
{ rows: [...beforeLastDigitRows, ['retired-layer', '9']] },
|
||||
(cwd) => {
|
||||
const published = readPublishedLayerStateReservations('HEAD', cwd);
|
||||
assert.equal(nextLayerStateToken(published), '00');
|
||||
@@ -228,7 +242,9 @@ test('published retired digits and competing PRs advance the merge-time allocati
|
||||
});
|
||||
|
||||
test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () => {
|
||||
withPublishedBase({ rows: [...preWildlifeRows, ['pr-a', '9']] }, (cwd) => {
|
||||
withPublishedBase(
|
||||
{ rows: [...beforeLastDigitRows, ['pr-a', '9']] },
|
||||
(cwd) => {
|
||||
mkdirSync(path.join(cwd, 'scripts'));
|
||||
const fixtureChecker = path.join(
|
||||
cwd,
|
||||
@@ -249,7 +265,7 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () =
|
||||
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...preWildlifeRows, ['pr-b', '9']],
|
||||
[...beforeLastDigitRows, ['pr-b', '9']],
|
||||
[{ id: 'pr-b', token: '9' }],
|
||||
);
|
||||
const beforeRebase = runCheck();
|
||||
@@ -258,7 +274,7 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () =
|
||||
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...preWildlifeRows, ['pr-a', '9'], ['pr-b', '9']],
|
||||
[...beforeLastDigitRows, ['pr-a', '9'], ['pr-b', '9']],
|
||||
[
|
||||
{ id: 'pr-a', token: '9' },
|
||||
{ id: 'pr-b', token: '9' },
|
||||
@@ -266,11 +282,14 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () =
|
||||
);
|
||||
const staleRebase = runCheck();
|
||||
assert.equal(staleRebase.status, 1);
|
||||
assert.match(staleRebase.stderr, /Duplicate layer-state token reservation/);
|
||||
assert.match(
|
||||
staleRebase.stderr,
|
||||
/Duplicate layer-state token reservation/,
|
||||
);
|
||||
|
||||
const published = readPublishedLayerStateReservations('HEAD', cwd);
|
||||
assert.equal(nextLayerStateToken(published), '00');
|
||||
const validBaselineRows = [...preWildlifeRows, ['pr-a', '9']];
|
||||
const validBaselineRows = [...beforeLastDigitRows, ['pr-a', '9']];
|
||||
writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '9' }]);
|
||||
const helper = spawnSync(
|
||||
process.execPath,
|
||||
@@ -286,7 +305,7 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () =
|
||||
);
|
||||
writeCodecFixture(
|
||||
cwd,
|
||||
[...preWildlifeRows, ['pr-a', '9'], ['pr-b', '00']],
|
||||
[...beforeLastDigitRows, ['pr-a', '9'], ['pr-b', '00']],
|
||||
[
|
||||
{ id: 'pr-a', token: '9' },
|
||||
{ id: 'pr-b', token: '00' },
|
||||
@@ -295,13 +314,14 @@ test('PR B manually replaces provisional 9 with 00 after PR A publishes 9', () =
|
||||
const corrected = runCheck();
|
||||
assert.equal(corrected.status, 0, corrected.stderr);
|
||||
assert.match(corrected.stdout, /36 published, 1 new/);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('allocation batches cross the last digit and base-36 pair boundaries in order', () => {
|
||||
const digitRows = [...'9'].map((digit) => [`retired-${digit}`, digit]);
|
||||
const allDigits = parseLayerStateTokenReservations([
|
||||
...preWildlifeRows,
|
||||
...beforeLastDigitRows,
|
||||
...digitRows,
|
||||
]);
|
||||
const beforeNine = { ...allDigits };
|
||||
@@ -360,7 +380,7 @@ test('an isolated valid two-character fixture round-trips an l field beyond the
|
||||
token,
|
||||
}));
|
||||
const fixtureRows = [
|
||||
...preWildlifeRows,
|
||||
...beforeLastDigitRows,
|
||||
...priorDigits,
|
||||
...fixtureLayers.map(({ id, token }) => [id, token]),
|
||||
];
|
||||
@@ -369,13 +389,16 @@ test('an isolated valid two-character fixture round-trips an l field beyond the
|
||||
assert.equal(codec.validateLayerStateRegistry(), true);
|
||||
assert.equal(
|
||||
nextLayerStateToken(
|
||||
parseLayerStateTokenReservations([...preWildlifeRows, ...priorDigits]),
|
||||
parseLayerStateTokenReservations([
|
||||
...beforeLastDigitRows,
|
||||
...priorDigits,
|
||||
]),
|
||||
),
|
||||
'00',
|
||||
);
|
||||
assert.equal(
|
||||
validateLayerStateAllocations(
|
||||
parseLayerStateTokenReservations(preWildlifeRows),
|
||||
parseLayerStateTokenReservations(beforeLastDigitRows),
|
||||
codec.LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
),
|
||||
true,
|
||||
@@ -400,19 +423,19 @@ test('an isolated valid two-character fixture round-trips an l field beyond the
|
||||
test('checker reads a complete future base ledger and rejects retired-token reuse', () => {
|
||||
withPublishedBase(
|
||||
{
|
||||
rows: [...reservationRows, ['retired-layer', '00']],
|
||||
rows: [...reservationRows, ['retired-layer', '02']],
|
||||
source:
|
||||
'export const LAYER_STATE_TOKEN_RESERVATIONS = Object.freeze({ ["retired-layer"]: "00" });\n',
|
||||
'export const LAYER_STATE_TOKEN_RESERVATIONS = Object.freeze({ ["retired-layer"]: "02" });\n',
|
||||
},
|
||||
(cwd) => {
|
||||
const published = readPublishedLayerStateReservations('HEAD', cwd);
|
||||
assert.equal(Object.keys(published).length, 37);
|
||||
assert.equal(published['retired-layer'], '00');
|
||||
assert.equal(Object.keys(published).length, 39);
|
||||
assert.equal(published['retired-layer'], '02');
|
||||
assert.throws(
|
||||
() =>
|
||||
validateLayerStateAllocations(published, {
|
||||
...LAYER_STATE_TOKEN_RESERVATIONS,
|
||||
newcomer: '00',
|
||||
newcomer: '02',
|
||||
}),
|
||||
/changed or removed/,
|
||||
);
|
||||
|
||||
@@ -18,12 +18,14 @@
|
||||
["military", "m"],
|
||||
["military-awareness", "g"],
|
||||
["military-installations", "i"],
|
||||
["news", "00"],
|
||||
["radio", "r"],
|
||||
["recent-imagery", "1"],
|
||||
["rocket-launches", "x"],
|
||||
["s2-ghostmaps", "5"],
|
||||
["satellites", "s"],
|
||||
["sea-marks", "6"],
|
||||
["shipwrecks", "01"],
|
||||
["ski-pistes", "7"],
|
||||
["street-level", "0"],
|
||||
["telegeography-submarine-cables", "u"],
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
# Natural Earth packs
|
||||
|
||||
Offline named-region polygons for the voice-annotation resolver
|
||||
(`src/data/naturalEarthRegions.js`) — "outline the Alps" resolves to the real
|
||||
range geometry with no network dependency.
|
||||
Offline polygons with no network dependency. The voice-annotation resolver
|
||||
(`src/data/naturalEarthRegions.js`) reads the named regions, so "outline the
|
||||
Alps" resolves to the real range geometry; area annotations read the
|
||||
countries, states and provinces (`src/data/adminBoundaries.js`); and the News
|
||||
layer reads the countries and the disputed areas
|
||||
(`server/providers/news/areas.js`).
|
||||
|
||||
| File | Source dataset | Features |
|
||||
|------|----------------|----------|
|
||||
@@ -10,6 +13,7 @@ range geometry with no network dependency.
|
||||
| `marine.json` | `ne_10m_geography_marine_polys` (seas, gulfs, straits, bays, …) | 292 named |
|
||||
| `countries.json` | `ne_10m_admin_0_countries` (countries) | 256 |
|
||||
| `states_provinces.json` | `ne_10m_admin_1_states_provinces` (states, provinces and other first-level units) | 4,587 named |
|
||||
| `disputed_areas.json` | `ne_10m_admin_0_disputed_areas` (disputed, breakaway and UN-patrolled areas; a hand-picked set, see below) | 11 of 99 |
|
||||
| `populated_places.json` | `ne_10m_populated_places_simple` (cities and towns, as points) | 7,342 |
|
||||
|
||||
**Source:** Natural Earth 10m physical vectors, via the canonical
|
||||
@@ -105,6 +109,44 @@ Includes England, Scotland, Wales and Northern Ireland from
|
||||
`57da82be755f4afccd8f3b14251bb2752f5df1395f47d2d86f817470c4a48862`).
|
||||
Result: 945,843 bytes; 260 features, 2,088 parts, 122,788 vertices.
|
||||
|
||||
## Disputed areas (`disputed_areas.json`)
|
||||
|
||||
The News layer's areas that no one country's name may stand for
|
||||
(`server/providers/news/areas.js`): a place inside one is named with the
|
||||
area ("Crimea"), and Local there reads no country's outlets.
|
||||
|
||||
**Source:** `geojson/ne_10m_admin_0_disputed_areas.geojson` at the same pinned
|
||||
commit (SHA-256
|
||||
`9cafef8b7dfb6b164dc58f218f981f4ace9f716f6c03795d4c62d1ac9f3d50f5`), fetched
|
||||
2026-11-05. Public domain, as above.
|
||||
|
||||
**Selection:** a hand-picked 11 of the source's 99 features. No rule picks
|
||||
them; this is the list:
|
||||
|
||||
| Area | Natural Earth's note (`NOTE_BRK`) |
|
||||
|------|-----------------------------------|
|
||||
| Golan Heights | Admin. By Israel; Claimed by Syria |
|
||||
| UNDOF Zone | UN Patrolled Zone in Syria |
|
||||
| Transnistria | Self admin.; Claimed by Moldova |
|
||||
| Abyei | Admin. by Sudan; Claimed by South Sudan |
|
||||
| Crimea | Admin. by Russia; Claimed by Ukraine |
|
||||
| Shebaa Farms | Admin. By Israel; Claimed by Lebanon |
|
||||
| Bir Tawil | Between Egypt and Sudan |
|
||||
| Halayib Triangle | Admin. by Egypt; Claimed by Sudan |
|
||||
| East Jerusalem | Admin. By Israel; Claimed by Palestine |
|
||||
| Abu Musa I. | Admin. by Iran; Claimed by UAE |
|
||||
| Doumera Island | Admin. By Eritrea; Claimed by Djibouti |
|
||||
|
||||
The source names three of these by a country ("Moldova", "Sudan", "Iran");
|
||||
the pack names them as the area. The 2014 Donetsk and Luhansk lines are left
|
||||
out as out of date. Every other feature is left out too, so a place there is
|
||||
named by its country in `countries.json`.
|
||||
|
||||
**Curation:** `kind` (`held`, `self`, `un`, `unclaimed`), `heldBy` and
|
||||
`claimedBy` are read from `NOTE_BRK`, and `note` keeps it as published. Every
|
||||
part is kept; each ring is Douglas-Peucker simplified at 0.003°, coordinates
|
||||
are rounded to 3 decimals and rings are stored open. Provenance is in the
|
||||
pack's `meta`. Result: 14,504 bytes.
|
||||
## Populated places (`populated_places.json`)
|
||||
|
||||
The orbital view's "near <city>" (`src/data/placeBelow.js`): from 8x it
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"meta":{"title":"Natural Earth admin-0 disputed areas, for the News layer","source":"ne_10m_admin_0_disputed_areas","url":"https://raw.githubusercontent.com/nvkelso/natural-earth-vector/ca96624a56bd078437bca8184e78163e5039ad19/geojson/ne_10m_admin_0_disputed_areas.geojson","sha256":"9cafef8b7dfb6b164dc58f218f981f4ace9f716f6c03795d4c62d1ac9f3d50f5","fetched":"2026-11-05","license":"Public domain (https://www.naturalearthdata.com/about/terms-of-use/)","curation":"A hand-picked 11 of the source's 99 features: Golan Heights, UNDOF Zone, Transnistria, Abyei, Crimea, Shebaa Farms, Bir Tawil, Halayib Triangle, East Jerusalem, Abu Musa I. and Doumera Island. The source names three of them by a country (Moldova, Sudan, Iran); they are named here as the area. kind, heldBy and claimedBy are read from NOTE_BRK; note is NOTE_BRK as published. The 2014 Donetsk and Luhansk lines are left out as out of date. Every part kept; each ring Douglas-Peucker simplified at 0.003 degrees, coordinates rounded to 3 decimals, rings stored open."},"areas":[{"name":"Golan Heights","kind":"held","heldBy":"IL","claimedBy":"SY","note":"Admin. By Israel; Claimed by Syria","rings":[[[35.821,33.407],[35.81,33.36],[35.786,33.343],[35.764,33.334],[35.802,33.312],[35.769,33.273],[35.804,33.248],[35.808,33.202],[35.83,33.19],[35.833,33.161],[35.811,33.127],[35.811,33.112],[35.849,33.099],[35.846,33.085],[35.859,32.99],[35.888,32.945],[35.85,32.896],[35.838,32.866],[35.842,32.854],[35.834,32.828],[35.784,32.778],[35.758,32.744],[35.74,32.741],[35.685,32.711],[35.636,32.679],[35.612,32.682],[35.595,32.707],[35.6,32.717],[35.634,32.752],[35.635,32.769],[35.641,32.772],[35.635,32.794],[35.641,32.82],[35.638,32.832],[35.641,32.865],[35.638,32.875],[35.602,32.909],[35.615,32.921],[35.62,32.984],[35.588,33.018],[35.621,33.05],[35.634,33.052],[35.637,33.077],[35.656,33.125],[35.672,33.15],[35.661,33.213],[35.66,33.236],[35.666,33.247],[35.635,33.249],[35.608,33.239],[35.605,33.244],[35.618,33.256],[35.62,33.27],[35.631,33.275],[35.654,33.262],[35.712,33.307],[35.718,33.317],[35.716,33.327],[35.744,33.331],[35.769,33.343],[35.786,33.358],[35.806,33.391]]]},{"name":"UNDOF Zone","kind":"un","note":"UN Patrolled Zone in Syria","rings":[[[35.758,32.744],[35.784,32.778],[35.834,32.828],[35.842,32.854],[35.838,32.866],[35.85,32.896],[35.888,32.945],[35.859,32.99],[35.846,33.085],[35.849,33.099],[35.811,33.112],[35.811,33.127],[35.833,33.161],[35.83,33.19],[35.808,33.202],[35.804,33.248],[35.769,33.273],[35.802,33.312],[35.764,33.334],[35.786,33.343],[35.81,33.36],[35.821,33.407],[35.87,33.431],[35.873,33.416],[35.87,33.407],[35.845,33.389],[35.83,33.365],[35.83,33.351],[35.843,33.322],[35.845,33.304],[35.84,33.295],[35.819,33.284],[35.82,33.281],[35.851,33.276],[35.866,33.226],[35.889,33.199],[35.882,33.189],[35.885,33.179],[35.9,33.18],[35.911,33.166],[35.911,33.135],[35.892,33.124],[35.897,33.117],[35.903,33.117],[35.903,33.11],[35.868,33.107],[35.865,33.082],[35.877,32.993],[35.898,32.986],[35.924,32.968],[35.912,32.947],[35.89,32.929],[35.861,32.88],[35.843,32.822],[35.815,32.787],[35.791,32.774],[35.77,32.748],[35.764,32.747]]]},{"name":"Transnistria","kind":"self","claimedBy":"MD","note":"Self admin.; Claimed by Moldova","rings":[[[29.899,46.553],[29.868,46.58],[29.84,46.582],[29.831,46.588],[29.824,46.601],[29.776,46.58],[29.728,46.594],[29.748,46.617],[29.776,46.629],[29.759,46.658],[29.749,46.665],[29.728,46.67],[29.703,46.665],[29.696,46.676],[29.667,46.676],[29.69,46.707],[29.698,46.728],[29.665,46.801],[29.652,46.813],[29.62,46.815],[29.611,46.827],[29.619,46.832],[29.615,46.841],[29.59,46.824],[29.563,46.787],[29.549,46.793],[29.543,46.793],[29.531,46.783],[29.512,46.787],[29.498,46.801],[29.502,46.821],[29.495,46.828],[29.494,46.862],[29.477,46.889],[29.471,46.941],[29.46,46.953],[29.436,46.957],[29.376,46.935],[29.35,46.937],[29.316,46.958],[29.296,46.992],[29.325,46.988],[29.371,47.003],[29.378,47.012],[29.374,47.011],[29.364,47.033],[29.381,47.029],[29.383,47.042],[29.378,47.071],[29.372,47.078],[29.33,47.108],[29.296,47.122],[29.291,47.14],[29.237,47.162],[29.227,47.149],[29.221,47.149],[29.213,47.158],[29.188,47.162],[29.179,47.156],[29.18,47.145],[29.194,47.124],[29.19,47.111],[29.157,47.113],[29.148,47.096],[29.125,47.074],[29.099,47.092],[29.07,47.101],[29.095,47.135],[29.112,47.15],[29.145,47.163],[29.164,47.192],[29.179,47.197],[29.164,47.231],[29.094,47.31],[29.08,47.332],[29.079,47.348],[29.089,47.351],[29.123,47.329],[29.14,47.329],[29.154,47.336],[29.165,47.348],[29.139,47.376],[29.083,47.406],[29.091,47.437],[29.108,47.454],[29.111,47.464],[29.104,47.478],[29.093,47.487],[29.049,47.506],[29.034,47.518],[29.025,47.533],[29.016,47.582],[28.993,47.605],[28.987,47.622],[28.996,47.651],[28.988,47.661],[28.981,47.687],[28.976,47.743],[28.981,47.765],[29.018,47.827],[29.019,47.853],[28.981,47.875],[28.861,47.899],[28.829,47.917],[28.831,47.941],[28.813,47.965],[28.785,47.983],[28.754,47.979],[28.719,47.999],[28.698,48.022],[28.682,48.031]Line truncated
|
||||
@@ -1,7 +1,11 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
REGIONAL_NEWS_WINDOW_HOURS,
|
||||
googleNewsWindowOperator,
|
||||
normalizeRegionalArticles,
|
||||
recentRegionalArticles,
|
||||
regionalNewsWindowHours,
|
||||
normalizeRegionalPlace,
|
||||
normalizeRegionalWeather,
|
||||
regionalDistanceM,
|
||||
@@ -61,3 +65,37 @@ test('regional distance handles nearby movement and missing positions', () => {
|
||||
assert.ok(distance > 11000 && distance < 11200);
|
||||
assert.equal(regionalDistanceM(null, null), Infinity);
|
||||
});
|
||||
|
||||
test('regional news is held to one 24-hour window, newest first, undated dropped', () => {
|
||||
assert.equal(REGIONAL_NEWS_WINDOW_HOURS, 24);
|
||||
assert.equal(googleNewsWindowOperator(), 'when:1d');
|
||||
assert.equal(googleNewsWindowOperator(6), 'when:6h');
|
||||
assert.equal(regionalNewsWindowHours('12'), 12);
|
||||
assert.equal(regionalNewsWindowHours(0), 24);
|
||||
assert.equal(regionalNewsWindowHours(undefined), 24);
|
||||
const now = Date.parse('2026-11-04T12:00:00Z');
|
||||
const at = (hours) => new Date(now - hours * 3_600_000).toISOString();
|
||||
const rows = [
|
||||
{ title: 'a', publishedAt: at(23) },
|
||||
{ title: 'stale', publishedAt: at(25) },
|
||||
{ title: 'undated', publishedAt: null },
|
||||
{ title: 'garbled', publishedAt: 'not a date' },
|
||||
{ title: 'b', publishedAt: at(1) },
|
||||
{ title: 'future', publishedAt: at(-2) },
|
||||
{ title: 'c', publishedAt: at(5) },
|
||||
];
|
||||
assert.deepEqual(
|
||||
recentRegionalArticles(rows, { now }).map((row) => row.title),
|
||||
['b', 'c', 'a'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
recentRegionalArticles(rows, { now, limit: 2 }).map((row) => row.title),
|
||||
['b', 'c'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
recentRegionalArticles(rows, { now, windowHours: 4 }).map((row) => row.title),
|
||||
['b'],
|
||||
);
|
||||
assert.deepEqual(recentRegionalArticles([], { now }), []);
|
||||
assert.deepEqual(recentRegionalArticles(undefined, { now }), []);
|
||||
});
|
||||
@@ -55,6 +55,13 @@ export function normalizeRegionalPlace(payload) {
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
REGIONAL_NEWS_WINDOW_HOURS,
|
||||
googleNewsWindowOperator,
|
||||
recentRegionalArticles,
|
||||
regionalNewsWindowHours,
|
||||
} from './regionalNewsWindow.js';
|
||||
|
||||
/** Normalize and deduplicate GDELT ArticleList output without trusting article HTML. */
|
||||
export function normalizeRegionalArticles(payload, limit = MAX_ARTICLES) {
|
||||
const rows = Array.isArray(payload?.articles) ? payload.articles : [];
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/** The regional-news freshness window, shared by the servers and the Cockpit. */
|
||||
|
||||
/** At most this many articles answer a regional brief. */
|
||||
export const REGIONAL_NEWS_ROWS = 5;
|
||||
|
||||
/**
|
||||
* The regional-news freshness window, in hours. The servers ask upstream for
|
||||
* this window, drop anything older and report it as `newsWindowHours`; the
|
||||
* Cockpit labels its list with it.
|
||||
*/
|
||||
export const REGIONAL_NEWS_WINDOW_HOURS = 24;
|
||||
|
||||
// A publish time this far ahead of the clock is skew, not a future story.
|
||||
const REGIONAL_NEWS_CLOCK_SKEW_MS = 15 * 60_000;
|
||||
|
||||
/**
|
||||
* A served window in hours, or the default when it is missing or out of range.
|
||||
* @param {unknown} value
|
||||
* @returns {number}
|
||||
*/
|
||||
export function regionalNewsWindowHours(value) {
|
||||
const hours = Number(value);
|
||||
return Number.isInteger(hours) && hours >= 1 && hours <= 168
|
||||
? hours
|
||||
: REGIONAL_NEWS_WINDOW_HOURS;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Google News search operator asking for the window: `when:1d` for 24 h.
|
||||
* @param {number} [hours]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function googleNewsWindowOperator(hours = REGIONAL_NEWS_WINDOW_HOURS) {
|
||||
const span = regionalNewsWindowHours(hours);
|
||||
return span % 24 === 0 ? `when:${span / 24}d` : `when:${span}h`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The articles published inside the window, newest first, at most `limit`.
|
||||
* An article without a parseable publish time is dropped: nothing shows it is
|
||||
* recent. One dated more than 15 minutes ahead of `now` is dropped too.
|
||||
* @param {Array<{publishedAt?: string|null}>} articles
|
||||
* @param {{now?: number, windowHours?: number, limit?: number}} [options]
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function recentRegionalArticles(
|
||||
articles,
|
||||
{
|
||||
now = Date.now(),
|
||||
windowHours = REGIONAL_NEWS_WINDOW_HOURS,
|
||||
limit = REGIONAL_NEWS_ROWS,
|
||||
} = {},
|
||||
) {
|
||||
const oldest = now - regionalNewsWindowHours(windowHours) * 3_600_000;
|
||||
return (Array.isArray(articles) ? articles : [])
|
||||
.map((article) => ({ article, at: Date.parse(article?.publishedAt) }))
|
||||
.filter(
|
||||
({ at }) =>
|
||||
Number.isFinite(at) &&
|
||||
at >= oldest &&
|
||||
at <= now + REGIONAL_NEWS_CLOCK_SKEW_MS,
|
||||
)
|
||||
.sort((a, b) => b.at - a.at)
|
||||
.slice(0, Math.max(0, limit))
|
||||
.map(({ article }) => article);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import createViteConfig, {
|
||||
validMilitaryInstallationBox,
|
||||
validRegionalPoint,
|
||||
} from '../../vite.config.js';
|
||||
import { fetchRegionalNews } from '../../server/providers/regional/news.js';
|
||||
|
||||
test('missing Google place context is a quiet keyless capability, not a 503', () => {
|
||||
assert.deepEqual(keylessGooglePlacesResponse(undefined), {
|
||||
@@ -113,3 +114,50 @@ test('regional brief treats an all-source outage as total failure', () => {
|
||||
news: { status: 'unavailable' },
|
||||
}), true);
|
||||
});
|
||||
|
||||
test('local regional news asks for the last day, drops old and undated items, newest first', async (t) => {
|
||||
const realFetch = globalThis.fetch;
|
||||
t.after(() => { globalThis.fetch = realFetch; });
|
||||
const urls = [];
|
||||
let rss;
|
||||
let gdelt;
|
||||
globalThis.fetch = async (url) => {
|
||||
urls.push(new URL(String(url)));
|
||||
const answer = String(url).includes('news.google') ? rss : gdelt;
|
||||
return typeof answer === 'function' ? answer() : answer.clone();
|
||||
};
|
||||
const at = (hours) => new Date(Date.now() - hours * 3_600_000).toUTCString();
|
||||
const item = (title, date) =>
|
||||
`<item><title>${title}</title><link>https://news.example/${title}</link>${date ? `<pubDate>${date}</pubDate>` : ''}</item>`;
|
||||
rss = new Response(`<rss><channel>${[
|
||||
item('old', at(4 * 24)),
|
||||
item('undated', null),
|
||||
item('day', at(20)),
|
||||
item('hour', at(1)),
|
||||
].join('')}</channel></rss>`);
|
||||
const place = { locality: 'Austin' };
|
||||
const ready = await fetchRegionalNews(place);
|
||||
assert.equal(urls[0].searchParams.get('q'), 'Austin when:1d');
|
||||
assert.equal(ready.status, 'ready');
|
||||
assert.deepEqual(ready.articles.map((row) => row.title), ['hour', 'day']);
|
||||
|
||||
// Nothing recent in RSS: GDELT is asked for the same 24 h window.
|
||||
rss = new Response(`<rss><channel>${item('old', at(30))}</channel></rss>`);
|
||||
gdelt = Response.json({ articles: [] });
|
||||
urls.length = 0;
|
||||
const empty = await fetchRegionalNews(place);
|
||||
assert.equal(urls[1].searchParams.get('timespan'), '24h');
|
||||
assert.deepEqual(empty, { status: 'empty', query: 'Austin', articles: [], source: 'GDELT fallback' });
|
||||
|
||||
// RSS answered with nothing recent and GDELT failed: still a true empty.
|
||||
rss = new Response('<rss><channel></channel></rss>');
|
||||
gdelt = () => Promise.reject(new TypeError('network'));
|
||||
assert.equal((await fetchRegionalNews(place)).status, 'empty');
|
||||
|
||||
// Neither source answered, or no place: unavailable.
|
||||
rss = () => Promise.resolve(new Response('busy', { status: 503 }));
|
||||
const failed = await fetchRegionalNews(place);
|
||||
assert.equal(failed.status, 'unavailable');
|
||||
assert.deepEqual(failed.articles, []);
|
||||
assert.equal((await fetchRegionalNews(null)).status, 'unavailable');
|
||||
});
|
||||
@@ -0,0 +1,332 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { shipwrecksProxy } from '../../server/providers/shipwrecks.js';
|
||||
|
||||
const EMODNET = {
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
id: 'heritageshipwrecks.1',
|
||||
geometry: { type: 'Point', coordinates: [-0.92, 50.74] },
|
||||
properties: { name: 'HMS/m A1', sink_yr: '1911', country: 'UK' },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const WIKIDATA = {
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: { value: 'http://www.wikidata.org/entity/Q25173' },
|
||||
itemLabel: { value: 'Titanic' },
|
||||
coord: { value: 'Point(-49.9469 41.7325)' },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Upstream fake. Each source answers 'ok', 'down' (HTTP 503) or 'malformed'
|
||||
* (HTTP 200 with a body that is not that source's data); change `state` to
|
||||
* switch between requests.
|
||||
*/
|
||||
function fakeFetch({ wikidataFails = false, emodnetFails = false } = {}) {
|
||||
const calls = [];
|
||||
const state = {
|
||||
emodnet: emodnetFails ? 'down' : 'ok',
|
||||
wikidata: wikidataFails ? 'down' : 'ok',
|
||||
};
|
||||
const fetchImpl = async (url, options) => {
|
||||
calls.push({ url: String(url), options });
|
||||
const href = String(url);
|
||||
const name = href.includes('query.wikidata.org')
|
||||
? 'wikidata'
|
||||
: href.includes('ows.emodnet-humanactivities.eu')
|
||||
? 'emodnet'
|
||||
: null;
|
||||
if (!name) return new Response('', { status: 404 });
|
||||
if (state[name] === 'down') return new Response('', { status: 503 });
|
||||
if (state[name] === 'malformed') return Response.json({});
|
||||
return Response.json(name === 'wikidata' ? WIKIDATA : EMODNET);
|
||||
};
|
||||
const callsTo = (name) =>
|
||||
calls.filter(({ url }) =>
|
||||
url.includes(
|
||||
name === 'wikidata'
|
||||
? 'query.wikidata.org'
|
||||
: 'ows.emodnet-humanactivities',
|
||||
),
|
||||
).length;
|
||||
return { fetchImpl, calls, state, callsTo };
|
||||
}
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
function handlerOf(plugin) {
|
||||
let handler;
|
||||
plugin.configureServer({
|
||||
middlewares: { use: (_path, fn) => (handler = fn) },
|
||||
});
|
||||
return handler;
|
||||
}
|
||||
|
||||
function request(handler, { method = 'GET', url = '/' } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const res = {
|
||||
destroyed: false,
|
||||
writeHead(status, headers) {
|
||||
this.status = status;
|
||||
this.headers = headers;
|
||||
},
|
||||
end(body) {
|
||||
resolve({
|
||||
status: this.status,
|
||||
headers: this.headers,
|
||||
body: JSON.parse(body),
|
||||
});
|
||||
},
|
||||
};
|
||||
handler(
|
||||
{ method, url, headers: {}, socket: { remoteAddress: '127.0.0.1' } },
|
||||
res,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('serves one cached snapshot from fixed upstreams', async () => {
|
||||
const { fetchImpl, calls } = fakeFetch();
|
||||
const handler = handlerOf(shipwrecksProxy({ fetchImpl }));
|
||||
const first = await request(handler);
|
||||
assert.equal(first.status, 200);
|
||||
assert.equal(first.body.records.length, 2);
|
||||
const a1 = first.body.records.find((record) => record.name === 'HMS/m A1');
|
||||
assert.equal(a1.year, 1911);
|
||||
assert.deepEqual(first.body.sources, { emodnet: true, wikidata: true });
|
||||
for (const { url } of calls)
|
||||
assert.match(
|
||||
url,
|
||||
/^https:\/\/(ows\.emodnet-humanactivities\.eu\/wfs\?|query\.wikidata\.org\/sparql\?)/,
|
||||
);
|
||||
const count = calls.length;
|
||||
await request(handler);
|
||||
assert.equal(calls.length, count, 'second request is served from cache');
|
||||
});
|
||||
|
||||
test('one failing source still serves the other; both failing is a 502', async () => {
|
||||
const partial = handlerOf(
|
||||
shipwrecksProxy({
|
||||
fetchImpl: fakeFetch({ wikidataFails: true }).fetchImpl,
|
||||
}),
|
||||
);
|
||||
const ok = await request(partial);
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual(ok.body.sources, { emodnet: true, wikidata: false });
|
||||
|
||||
const down = handlerOf(
|
||||
shipwrecksProxy({
|
||||
fetchImpl: fakeFetch({ wikidataFails: true, emodnetFails: true })
|
||||
.fetchImpl,
|
||||
}),
|
||||
);
|
||||
assert.equal((await request(down)).status, 502);
|
||||
});
|
||||
|
||||
test('a failed refresh serves the last snapshot as stale', async () => {
|
||||
let clock = 0;
|
||||
let fail = false;
|
||||
const { fetchImpl: good } = fakeFetch();
|
||||
const { fetchImpl: bad } = fakeFetch({
|
||||
wikidataFails: true,
|
||||
emodnetFails: true,
|
||||
});
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({
|
||||
fetchImpl: (...args) => (fail ? bad : good)(...args),
|
||||
now: () => clock,
|
||||
}),
|
||||
);
|
||||
await request(handler);
|
||||
fail = true;
|
||||
clock = 25 * 60 * 60 * 1000;
|
||||
const stale = await request(handler);
|
||||
assert.equal(stale.status, 200);
|
||||
assert.equal(stale.body.stale, true);
|
||||
assert.equal(stale.headers['X-Data-Stale'], 'true');
|
||||
});
|
||||
|
||||
test('rejects other methods and routes', async () => {
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: fakeFetch().fetchImpl }),
|
||||
);
|
||||
assert.equal((await request(handler, { method: 'POST' })).status, 405);
|
||||
assert.equal((await request(handler, { url: '/x' })).status, 404);
|
||||
});
|
||||
|
||||
test("a refresh that gets nothing usable keeps every source's last good wrecks", async () => {
|
||||
let clock = 0;
|
||||
const upstream = fakeFetch();
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: upstream.fetchImpl, now: () => clock }),
|
||||
);
|
||||
const first = await request(handler);
|
||||
assert.equal(first.body.records.length, 2);
|
||||
// A day later EMODnet is down and Wikidata answers 200 with no results.
|
||||
upstream.state.emodnet = 'down';
|
||||
upstream.state.wikidata = 'malformed';
|
||||
clock = 25 * HOUR;
|
||||
const later = await request(handler);
|
||||
assert.equal(later.status, 200);
|
||||
assert.equal(later.body.records.length, 2, 'no wreck is lost');
|
||||
assert.deepEqual(later.body.sources, { emodnet: true, wikidata: true });
|
||||
assert.equal(later.body.stale, true);
|
||||
assert.equal(later.body.fetchedAt, 0, 'the age of the oldest data served');
|
||||
});
|
||||
|
||||
test('one source failing keeps its own last records while the other refreshes', async () => {
|
||||
let clock = 0;
|
||||
const upstream = fakeFetch();
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: upstream.fetchImpl, now: () => clock }),
|
||||
);
|
||||
const first = await request(handler);
|
||||
assert.equal((await request(handler)).body.version, first.body.version);
|
||||
upstream.state.wikidata = 'down';
|
||||
clock = 25 * HOUR;
|
||||
const later = await request(handler);
|
||||
assert.notEqual(later.body.version, first.body.version, 'new EMODnet data');
|
||||
assert.equal(later.body.records.length, 2);
|
||||
assert.deepEqual(later.body.sources, { emodnet: true, wikidata: true });
|
||||
assert.equal(later.body.stale, true);
|
||||
assert.equal(upstream.callsTo('emodnet'), 2, 'EMODnet was refreshed');
|
||||
assert.deepEqual(later.body.ages, { emodnet: 0, wikidata: 25 * HOUR });
|
||||
assert.equal(later.body.maxAgeMs, 7 * 24 * HOUR);
|
||||
});
|
||||
|
||||
test('a failed source waits before it is asked again', async () => {
|
||||
let clock = 0;
|
||||
const upstream = fakeFetch();
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: upstream.fetchImpl, now: () => clock }),
|
||||
);
|
||||
await request(handler);
|
||||
upstream.state.emodnet = 'down';
|
||||
upstream.state.wikidata = 'down';
|
||||
clock = 25 * HOUR;
|
||||
await request(handler);
|
||||
const asked = upstream.calls.length;
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
clock += 60 * 1000;
|
||||
const res = await request(handler);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.stale, true);
|
||||
}
|
||||
assert.equal(upstream.calls.length, asked, 'no upstream call while waiting');
|
||||
clock = 25 * HOUR + 16 * 60 * 1000;
|
||||
upstream.state.emodnet = 'ok';
|
||||
upstream.state.wikidata = 'ok';
|
||||
const back = await request(handler);
|
||||
assert.equal(
|
||||
upstream.calls.length,
|
||||
asked + 2,
|
||||
'both are retried after the wait',
|
||||
);
|
||||
assert.equal(back.body.stale, undefined);
|
||||
});
|
||||
|
||||
test('with no data yet, failures are retried only after the wait', async () => {
|
||||
let clock = 0;
|
||||
const upstream = fakeFetch({ emodnetFails: true, wikidataFails: true });
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: upstream.fetchImpl, now: () => clock }),
|
||||
);
|
||||
assert.equal((await request(handler)).status, 502);
|
||||
const asked = upstream.calls.length;
|
||||
clock += 5 * 60 * 1000;
|
||||
assert.equal((await request(handler)).status, 502);
|
||||
assert.equal(upstream.calls.length, asked);
|
||||
clock += 11 * 60 * 1000;
|
||||
assert.equal((await request(handler)).status, 502);
|
||||
assert.equal(upstream.calls.length, asked * 2);
|
||||
});
|
||||
|
||||
test('a source older than seven days is no longer served', async () => {
|
||||
let clock = 0;
|
||||
const upstream = fakeFetch();
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({ fetchImpl: upstream.fetchImpl, now: () => clock }),
|
||||
);
|
||||
await request(handler);
|
||||
upstream.state.emodnet = 'down';
|
||||
upstream.state.wikidata = 'down';
|
||||
clock = 7 * 24 * HOUR;
|
||||
assert.equal((await request(handler)).status, 200, 'seven days is served');
|
||||
clock = 7 * 24 * HOUR + 16 * 60 * 1000;
|
||||
assert.equal((await request(handler)).status, 502, 'older is dropped');
|
||||
});
|
||||
|
||||
test('an upstream body over its cap is a failed source, read only to the cap', async () => {
|
||||
const MIB = 1024 * 1024;
|
||||
const chunk = new Uint8Array(MIB).fill(0x20);
|
||||
let sent = 0;
|
||||
let cancelled = false;
|
||||
const endless = () =>
|
||||
new ReadableStream({
|
||||
pull(controller) {
|
||||
sent += chunk.byteLength;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({
|
||||
fetchImpl: async (url) =>
|
||||
String(url).includes('query.wikidata.org')
|
||||
? Response.json(WIKIDATA)
|
||||
: new Response(endless()),
|
||||
}),
|
||||
);
|
||||
const res = await request(handler);
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body.sources, { emodnet: false, wikidata: true });
|
||||
assert.ok(cancelled, 'the oversized body is cancelled');
|
||||
assert.ok(sent <= 34 * MIB, `read ${sent / MIB} MiB of a 32 MiB cap`);
|
||||
});
|
||||
|
||||
test('a refresh far smaller than the last good set is refused until it expires', async () => {
|
||||
let clock = 0;
|
||||
const many = {
|
||||
results: {
|
||||
bindings: Array.from({ length: 10 }, (_, i) => ({
|
||||
item: { value: `http://www.wikidata.org/entity/Q${100 + i}` },
|
||||
itemLabel: { value: `Wreck ${i}` },
|
||||
coord: { value: `Point(${i} 40)` },
|
||||
})),
|
||||
},
|
||||
};
|
||||
let wikidata = many;
|
||||
const handler = handlerOf(
|
||||
shipwrecksProxy({
|
||||
fetchImpl: async (url) =>
|
||||
Response.json(
|
||||
String(url).includes('query.wikidata.org') ? wikidata : EMODNET,
|
||||
),
|
||||
now: () => clock,
|
||||
}),
|
||||
);
|
||||
assert.equal((await request(handler)).body.records.length, 11);
|
||||
wikidata = WIKIDATA;
|
||||
clock = 25 * HOUR;
|
||||
const refused = await request(handler);
|
||||
assert.equal(refused.body.records.length, 11, 'one wreck is not ten');
|
||||
assert.equal(refused.body.stale, true);
|
||||
clock = 8 * 24 * HOUR;
|
||||
const accepted = await request(handler);
|
||||
assert.equal(
|
||||
accepted.body.records.length,
|
||||
2,
|
||||
'taken once the old set expired',
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Bottom-to-top order for near-plane-clamped contact sprite collections. */
|
||||
export const SPRITE_LAYER_ORDER = Object.freeze([
|
||||
'shipwrecks',
|
||||
'cctv',
|
||||
'firms',
|
||||
'wildlife-sightings',
|
||||
|
||||
+159
-3
@@ -1,4 +1,103 @@
|
||||
{
|
||||
"News feed unavailable": "موجز الأخبار غير متاح",
|
||||
"Developing: {name}": "تطورات: {name}",
|
||||
"{count} events today": {
|
||||
"zero": "{count} حدث اليوم",
|
||||
"one": "حدث واحد اليوم ({count})",
|
||||
"two": "حدثان اليوم ({count})",
|
||||
"few": "{count} أحداث اليوم",
|
||||
"many": "{count} حدثًا اليوم",
|
||||
"other": "{count} حدث اليوم"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"zero": "{count} تقرير اليوم",
|
||||
"one": "تقرير واحد اليوم ({count})",
|
||||
"two": "تقريران اليوم ({count})",
|
||||
"few": "{count} تقارير اليوم",
|
||||
"many": "{count} تقريرًا اليوم",
|
||||
"other": "{count} تقرير اليوم"
|
||||
},
|
||||
"Disputed: {name}": "منطقة متنازع عليها: {name}",
|
||||
"Video": "فيديو",
|
||||
"Photos": "صور",
|
||||
"Claimed by {who}": "ادعاء: {who}",
|
||||
"Claimed": "ادعاء",
|
||||
"Not yet confirmed by others": "لم يؤكده آخرون بعد",
|
||||
"Reported by {side} sources": "أوردته مصادر {side}",
|
||||
"Reported by {sides}": "أوردته {sides}",
|
||||
"{side} sources": "مصادر {side}",
|
||||
"Official": "رسمي",
|
||||
"Reported by both sides": "أورده الطرفان",
|
||||
"Independently reported": "أُبلغ عنه بشكل مستقل",
|
||||
"Single source": "مصدر واحد",
|
||||
"International": "دولية",
|
||||
"Independent": "مستقلة",
|
||||
"Unattributed": "غير منسوب",
|
||||
"Outside party": "طرف خارجي",
|
||||
"Ukraine–Russia": "أوكرانيا–روسيا",
|
||||
"Israel–Gaza–Lebanon": "إسرائيل–غزة–لبنان",
|
||||
"Iran–Hormuz": "إيران–هرمز",
|
||||
"Yemen–Red Sea": "اليمن–البحر الأحمر",
|
||||
"Sudan": "السودان",
|
||||
"Sahel": "الساحل",
|
||||
"Elsewhere": "أماكن أخرى",
|
||||
"Strike": "ضربة",
|
||||
"Alert": "إنذار",
|
||||
"Air defence": "دفاع جوي",
|
||||
"Ground fighting": "قتال بري",
|
||||
"Casualties": "إصابات",
|
||||
"Humanitarian": "إنساني",
|
||||
"Disaster": "كارثة",
|
||||
"Protest": "احتجاج",
|
||||
"Political": "سياسي",
|
||||
"No physical event": "لا حدث ميداني",
|
||||
"Minor incident": "حادث بسيط",
|
||||
"Significant": "كبير",
|
||||
"Major": "جسيم",
|
||||
"age|now": "الآن",
|
||||
"{minutes} min": "{minutes} د",
|
||||
"{hours} h": "{hours} س",
|
||||
"{count} sources": {
|
||||
"zero": "{count} مصدر",
|
||||
"one": "مصدر واحد ({count})",
|
||||
"two": "مصدران ({count})",
|
||||
"few": "{count} مصادر",
|
||||
"many": "{count} مصدرًا",
|
||||
"other": "{count} مصدر"
|
||||
},
|
||||
"News feed not configured on this server": "موجز الأخبار غير مهيأ على هذا الخادم",
|
||||
"Malformed news hotspots response": "استجابة بؤر الأخبار غير صالحة",
|
||||
"Malformed news feed response": "استجابة موجز الأخبار غير صالحة",
|
||||
"{place} (placed by model)": "{place} (حدده النموذج)",
|
||||
"English headline by the model": "عنوان إنجليزي من النموذج",
|
||||
"Not placed on the map": "غير موضوع على الخريطة",
|
||||
"Close": "إغلاق",
|
||||
"Any severity": "أي درجة خطورة",
|
||||
"{severity} and above": "{severity} فأعلى",
|
||||
"{severity} only": "{severity} فقط",
|
||||
"All categories": "كل الفئات",
|
||||
"Reading the news…": "جارٍ قراءة الأخبار…",
|
||||
"News, last {hours} hours": "الأخبار، آخر {hours} ساعة",
|
||||
"Last {hours} h": "آخر {hours} ساعة",
|
||||
"Time window": "الفترة الزمنية",
|
||||
"Conflicts": "النزاعات",
|
||||
"Local": "محلي",
|
||||
"News sections": "أقسام الأخبار",
|
||||
"Zoom in to see local news": "قرّب الخريطة لرؤية الأخبار المحلية",
|
||||
"Hotspots": "بؤر ساخنة",
|
||||
"Severity": "الخطورة",
|
||||
"Category": "الفئة",
|
||||
"Nothing reported near here in the last {hours} h": "لم يُبلَّغ عن شيء قريب من هنا في آخر {hours} ساعة",
|
||||
"Latest news": "آخر الأخبار",
|
||||
"No news matches these filters in the last {hours} h": "لا أخبار تطابق هذه المرشحات في آخر {hours} ساعة",
|
||||
"Load older news": "تحميل أخبار أقدم",
|
||||
"How to read the map": "كيف تقرأ الخريطة",
|
||||
"Colour: severity · icon: type of event": "اللون: الخطورة · الرمز: نوع الحدث",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "إطار متصل: أورده الطرفان أو مصدر مستقل. إطار متقطع: ادعاء. إطار رفيع: مصدر واحد، أو إعلام أحد الطرفين.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "أكبر: مصادر أكثر · أبهت: أقدم. بطاقة بصورة: حدث جسيم أو متسارع من مصدرين أو أكثر.",
|
||||
"Side labels describe the source, not whether a report is true.": "تصف تسميات الأطراف المصدر، لا صحة التقرير.",
|
||||
"Exit cockpit to fly to a news report": "اخرج من القمرة للانتقال إلى خبر",
|
||||
"News items in the feed": "عدد الأخبار في الموجز",
|
||||
"NO PLACE LEFT BEHIND": "لا مكان يُترك خلفنا",
|
||||
"Initializing photorealistic world...": "جارٍ تهيئة العالم الواقعي…",
|
||||
"Configuring viewer...": "جارٍ إعداد العارض…",
|
||||
@@ -437,11 +536,12 @@
|
||||
"PLACE / CONDITIONS / POSITION": "المكان / الأحوال / الموضع",
|
||||
"POSITION UNAVAILABLE": "الموضع غير متاح",
|
||||
"REGIONAL NEWS UNAVAILABLE": "الأخبار الإقليمية غير متاحة",
|
||||
"CACHED · REFRESH FAILED": "مخزنة · فشل التحديث",
|
||||
"REGION UNAVAILABLE": "المنطقة غير متاحة",
|
||||
"NO RECENT LOCATION MATCHES": "لا توجد تقارير حديثة مطابقة للموقع",
|
||||
"NO NEWS IN THE LAST {hours} H": "لا أخبار خلال آخر {hours} س",
|
||||
"SOURCE": "المصدر",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{source} · LOCATION QUERY": "{source} · استعلام الموقع",
|
||||
"{source} · CACHED {age}": "{source} · مخزنة {age}",
|
||||
"TIME UNKNOWN": "الوقت غير معروف",
|
||||
"{count}M AGO": "قبل {count} د",
|
||||
"{count}H AGO": "قبل {count} س",
|
||||
@@ -2286,7 +2386,7 @@
|
||||
"ADS-B PRIORITY · {status}": "أولوية ADS-B · {status}",
|
||||
"ADS-B EMERGENCY · {status}": "طوارئ ADS-B · {status}",
|
||||
"{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · استعلام الموقع · حديث",
|
||||
"{source} · LAST {hours} H": "{source} · آخر {hours} س",
|
||||
"Rendered globe frames per second · toggle with `": "إطارات الكرة الأرضية المعروضة في الثانية · بدّل بالمفتاح `",
|
||||
"Ground heights could not be refreshed. Try the file again when the map has loaded.": "تعذّر تحديث ارتفاعات الأرض. أعد استيراد الملف بعد تحميل الخريطة.",
|
||||
"{count} map objects": {
|
||||
@@ -3513,6 +3613,62 @@
|
||||
"Prohibited": "محظور",
|
||||
"Restricted": "مقيّد",
|
||||
"Prohibited & Restricted Airspace": "المجال الجوي المحظور والمقيّد",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "آخر 24 ساعة من الأخبار. يرتبط كل تقرير بناشره؛ تُستخرج الأماكن والفئات من النص والبيانات تلقائيًا وقد تكون خاطئة. تصف تسميات الأطراف، حيث تظهر، المصدر لا صحة التقرير.",
|
||||
"Economy": "اقتصاد",
|
||||
"News from {area}": "أخبار: {area}",
|
||||
"Within {km} km of the view centre": "ضمن {km} كم من مركز العرض",
|
||||
"{region}, {country}": "{region}، {country}",
|
||||
"via {source}": "عبر {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "المحلي في طبقة الأخبار: أخبار اليوم من وسائل إعلام البلد المعروض",
|
||||
"{provider} refused its key": "رفض {provider} مفتاحه",
|
||||
"Check {envVars} in Provider Settings": "تحقق من {envVars} في «إعدادات المزوّدين»",
|
||||
"{provider} key required": "مفتاح {provider} مطلوب",
|
||||
"{provider} limit reached for today": "بلغ {provider} حدّه لهذا اليوم",
|
||||
"News resumes tomorrow, or with a paid plan": "تُستأنف الأخبار غدًا، أو مع خطة مدفوعة",
|
||||
"News key required": "مفتاح الأخبار مطلوب",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "نقاط نزاع دقيقة في طبقة الأخبار، إلى جانب مقالات GDELT",
|
||||
"Worldwide": "العالم",
|
||||
"Shipwrecks": "حطام السفن",
|
||||
"Before 1900": "قبل 1900",
|
||||
"After 1945": "بعد 1945",
|
||||
"Date unknown": "التاريخ غير معروف",
|
||||
"Position: centre of the protected area": "الموقع: مركز المنطقة المحمية",
|
||||
"Position approximate (within about {km} km)": "الموقع تقريبي (في حدود {km} كم تقريبًا)",
|
||||
"Position surveyed (within about {m} m)": "الموقع مُسَح (في حدود {m} م تقريبًا)",
|
||||
"Vessel: {value}": "السفينة: {value}",
|
||||
"What happened: {value}": "ما حدث: {value}",
|
||||
"Depth: {m} m ({quality})": "العمق: {m} م ({quality})",
|
||||
"Depth: {m} m": "العمق: {m} م",
|
||||
"Notes: {value}": "ملاحظات: {value}",
|
||||
"Cargo or finds: {value}": "الحمولة أو المكتشفات: {value}",
|
||||
"Protected wreck": "حطام محمي",
|
||||
"Source: {value}": "المصدر: {value}",
|
||||
"Click the card to open EMODnet ↗": "انقر على البطاقة لفتح EMODnet ↗",
|
||||
"Click the card to open the source ↗": "انقر على البطاقة لفتح المصدر ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "ويكي بيانات غير متاحة؛ يُعرض EMODnet فقط",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet غير متاح؛ تُعرض ويكي بيانات فقط",
|
||||
"Shipwrecks unavailable": "بيانات حطام السفن غير متاحة",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (المياه الأوروبية) · ويكي بيانات (العالم)",
|
||||
"{count} wrecks": {
|
||||
"zero": "لا حطام ({count})",
|
||||
"one": "حطام واحد ({count})",
|
||||
"two": "حطامان ({count})",
|
||||
"few": "{count} حطامات",
|
||||
"many": "{count} حطامًا",
|
||||
"other": "{count} حطام"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "غرق سفينة",
|
||||
"Fatalities: {count}": "الوفيات: {count}",
|
||||
"Survivors: {count}": "الناجون: {count}",
|
||||
"Click the card to open the article ↗": "انقر على البطاقة لفتح المقالة ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "يأتي حطام السفن التراثي الأوروبي من EMODnet Human Activities، ويأتي الحطام البارز في العالم من ويكي بيانات. يبيّن اللون متى غرقت السفينة، ويكبر حجم العلامة مع عدد الوفيات. انقر على علامة لعرض بطاقتها.",
|
||||
"All years": "كل السنوات",
|
||||
"Period": "الفترة",
|
||||
"From": "من",
|
||||
"To": "إلى",
|
||||
"First year of the shipwreck period": "السنة الأولى من فترة الغرق",
|
||||
"Last year of the shipwreck period": "السنة الأخيرة من فترة الغرق",
|
||||
"SIGHTING": "مشاهدة",
|
||||
"Show {name} sighting": "إظهار مشاهدة {name}",
|
||||
"seen {age} ago": "شوهد قبل {age}",
|
||||
|
||||
+143
-3
@@ -1,4 +1,91 @@
|
||||
{
|
||||
"News feed unavailable": "Nachrichtenfeed nicht verfügbar",
|
||||
"Developing: {name}": "In Entwicklung: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} Ereignis heute",
|
||||
"other": "{count} Ereignisse heute"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} Meldung heute",
|
||||
"other": "{count} Meldungen heute"
|
||||
},
|
||||
"Disputed: {name}": "Umstritten: {name}",
|
||||
"Video": "Video",
|
||||
"Photos": "Fotos",
|
||||
"Claimed by {who}": "Behauptet von {who}",
|
||||
"Claimed": "Behauptung",
|
||||
"Not yet confirmed by others": "Noch nicht von anderen bestätigt",
|
||||
"Reported by {side} sources": "Gemeldet von Quellen aus {side}",
|
||||
"Reported by {sides}": "Gemeldet von {sides}",
|
||||
"{side} sources": "Quellen aus {side}",
|
||||
"Official": "Offiziell",
|
||||
"Reported by both sides": "Von beiden Seiten gemeldet",
|
||||
"Independently reported": "Unabhängig gemeldet",
|
||||
"Single source": "Einzelne Quelle",
|
||||
"International": "International",
|
||||
"Independent": "Unabhängig",
|
||||
"Unattributed": "Ohne Zuordnung",
|
||||
"Outside party": "Außenstehende Partei",
|
||||
"Ukraine–Russia": "Ukraine–Russland",
|
||||
"Israel–Gaza–Lebanon": "Israel–Gaza–Libanon",
|
||||
"Iran–Hormuz": "Iran–Hormus",
|
||||
"Yemen–Red Sea": "Jemen–Rotes Meer",
|
||||
"Sudan": "Sudan",
|
||||
"Sahel": "Sahel",
|
||||
"Elsewhere": "Anderswo",
|
||||
"Strike": "Angriff",
|
||||
"Alert": "Warnung",
|
||||
"Air defence": "Luftabwehr",
|
||||
"Ground fighting": "Bodenkämpfe",
|
||||
"Casualties": "Opfer",
|
||||
"Humanitarian": "Humanitär",
|
||||
"Disaster": "Katastrophe",
|
||||
"Protest": "Protest",
|
||||
"Political": "Politik",
|
||||
"No physical event": "Kein physisches Ereignis",
|
||||
"Minor incident": "Kleiner Vorfall",
|
||||
"Significant": "Erheblich",
|
||||
"Major": "Schwer",
|
||||
"age|now": "jetzt",
|
||||
"{minutes} min": "{minutes} Min.",
|
||||
"{hours} h": "{hours} Std.",
|
||||
"{count} sources": {
|
||||
"one": "{count} Quelle",
|
||||
"other": "{count} Quellen"
|
||||
},
|
||||
"News feed not configured on this server": "Nachrichtenfeed auf diesem Server nicht eingerichtet",
|
||||
"Malformed news hotspots response": "Fehlerhafte Antwort zu Nachrichten-Brennpunkten",
|
||||
"Malformed news feed response": "Fehlerhafte Antwort des Nachrichtenfeeds",
|
||||
"{place} (placed by model)": "{place} (vom Modell verortet)",
|
||||
"English headline by the model": "Englische Schlagzeile vom Modell",
|
||||
"Not placed on the map": "Nicht auf der Karte verortet",
|
||||
"Close": "Schließen",
|
||||
"Any severity": "Jeder Schweregrad",
|
||||
"{severity} and above": "{severity} und höher",
|
||||
"{severity} only": "Nur {severity}",
|
||||
"All categories": "Alle Kategorien",
|
||||
"Reading the news…": "Nachrichten werden gelesen…",
|
||||
"News, last {hours} hours": "Nachrichten der letzten {hours} Stunden",
|
||||
"Last {hours} h": "Letzte {hours} Std.",
|
||||
"Time window": "Zeitraum",
|
||||
"Conflicts": "Konflikte",
|
||||
"Local": "Lokal",
|
||||
"News sections": "Nachrichtenbereiche",
|
||||
"Zoom in to see local news": "Hineinzoomen, um lokale Nachrichten zu sehen",
|
||||
"Hotspots": "Brennpunkte",
|
||||
"Severity": "Schweregrad",
|
||||
"Category": "Kategorie",
|
||||
"Nothing reported near here in the last {hours} h": "In den letzten {hours} h nichts in der Nähe gemeldet",
|
||||
"Latest news": "Neueste Nachrichten",
|
||||
"No news matches these filters in the last {hours} h": "Keine Nachrichten der letzten {hours} h passen zu diesen Filtern",
|
||||
"Load older news": "Ältere Nachrichten laden",
|
||||
"How to read the map": "So liest man die Karte",
|
||||
"Colour: severity · icon: type of event": "Farbe: Schweregrad · Symbol: Art des Ereignisses",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Durchgehender Rand: von beiden Seiten oder unabhängig gemeldet. Gestrichelter Rand: eine Behauptung. Dünner Rand: eine Quelle oder die eigene Presse einer Seite.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Größer: mehr Quellen · blasser: älter. Bildkarte: ein schweres oder schnell wachsendes Ereignis mit zwei oder mehr Quellen.",
|
||||
"Side labels describe the source, not whether a report is true.": "Seitenangaben beschreiben die Quelle, nicht ob eine Meldung stimmt.",
|
||||
"Exit cockpit to fly to a news report": "Cockpit verlassen, um zu einer Meldung zu fliegen",
|
||||
"News items in the feed": "Meldungen im Feed",
|
||||
"Flying to Austin, TX...": "Flug nach Austin, TX...",
|
||||
"Restoring shared view...": "Geteilte Ansicht wird wiederhergestellt...",
|
||||
"Configuring viewer...": "Viewer wird konfiguriert...",
|
||||
@@ -433,13 +520,14 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Briefing-Seiten automatisch alle 9 Sekunden wechseln (Signale → News → Lokal). Pausiert, solange sich der Mauszeiger über dem Bereich befindet oder dieser den Fokus hat. Live-Signaldaten werden in beiden Fällen laufend aktualisiert.",
|
||||
"ACQUIRING REGIONAL NEWS": "REGIONALE NEWS WERDEN ERFASST",
|
||||
"REGIONAL NEWS UNAVAILABLE": "REGIONALE NEWS NICHT VERFÜGBAR",
|
||||
"CACHED · REFRESH FAILED": "CACHE · AKTUALISIERUNG FEHLGESCHLAGEN",
|
||||
"RESOLVING REGION": "REGION WIRD ERMITTELT",
|
||||
"REGION UNAVAILABLE": "REGION NICHT VERFÜGBAR",
|
||||
"NO RECENT LOCATION MATCHES": "KEINE AKTUELLEN ORTSTREFFER",
|
||||
"NO NEWS IN THE LAST {hours} H": "KEINE NEWS IN DEN LETZTEN {hours} H",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"CLOUD {pct}%": "WOLKEN {pct} %",
|
||||
"CLOUD UNKNOWN": "WOLKEN UNBEKANNT",
|
||||
"{source} · LOCATION QUERY": "{source} · ORTSABFRAGE",
|
||||
"{source} · CACHED {age}": "{source} · CACHE {age}",
|
||||
"REGIONAL NEWS": "REGIONALE NEWS",
|
||||
"CONTEXT STANDBY": "KONTEXT STANDBY",
|
||||
"ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "GLOBALEN KONTEXT FÜR NÄHE-PINGS AKTIVIEREN",
|
||||
@@ -2182,7 +2270,7 @@
|
||||
"ADS-B PRIORITY · {status}": "ADS-B-PRIORITÄT · {status}",
|
||||
"ADS-B EMERGENCY · {status}": "ADS-B-NOTFALL · {status}",
|
||||
"{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · ORTSABFRAGE · AKTUELL",
|
||||
"{source} · LAST {hours} H": "{source} · LETZTE {hours} H",
|
||||
"Rendered globe frames per second · toggle with `": "Gerenderte Globus-Frames pro Sekunde · umschalten mit `",
|
||||
"Ground heights could not be refreshed. Try the file again when the map has loaded.": "Geländehöhen konnten nicht aktualisiert werden. Die Datei erneut laden, wenn die Karte geladen ist.",
|
||||
"{count} map objects": {
|
||||
@@ -3205,6 +3293,58 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Zu viele Chat-Anfragen. In {seconds} s erneut versuchen.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "Der Anbieter hat den Zugriff für diesen Schlüssel verweigert. Projekt, Region oder Berechtigungen des Schlüssels prüfen.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Das Anbieterkonto hat kein Guthaben mehr. Die Abrechnung prüfen oder in den Einstellungen einen anderen KI-Anbieter wählen.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Letzte 24 h Nachrichten. Jede Meldung verlinkt auf ihren Herausgeber; Orte und Kategorien werden automatisch aus Text und Daten gelesen und können falsch sein. Seitenangaben, wo vorhanden, beschreiben die Quelle, nicht ob eine Meldung stimmt.",
|
||||
"Economy": "Wirtschaft",
|
||||
"News from {area}": "Nachrichten: {area}",
|
||||
"Within {km} km of the view centre": "Im Umkreis von {km} km um die Bildmitte",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "über {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Lokal in der Nachrichtenebene: die Nachrichten des Tages aus den Medien des Landes im Blick",
|
||||
"{provider} refused its key": "{provider} hat den Schlüssel abgelehnt",
|
||||
"Check {envVars} in Provider Settings": "{envVars} in den Anbieter-Einstellungen prüfen",
|
||||
"{provider} key required": "{provider}-Schlüssel erforderlich",
|
||||
"{provider} limit reached for today": "{provider}: Tageslimit erreicht",
|
||||
"News resumes tomorrow, or with a paid plan": "Nachrichten gibt es morgen wieder, oder mit einem kostenpflichtigen Tarif",
|
||||
"News key required": "Nachrichtenschlüssel erforderlich",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Genaue Konfliktpunkte in der Nachrichtenebene, neben den Artikeln von GDELT",
|
||||
"Worldwide": "Weltweit",
|
||||
"Shipwrecks": "Schiffswracks",
|
||||
"Before 1900": "Vor 1900",
|
||||
"After 1945": "Nach 1945",
|
||||
"Date unknown": "Datum unbekannt",
|
||||
"Position: centre of the protected area": "Position: Mitte des Schutzgebiets",
|
||||
"Position approximate (within about {km} km)": "Position ungefähr (auf etwa {km} km genau)",
|
||||
"Position surveyed (within about {m} m)": "Position vermessen (auf etwa {m} m genau)",
|
||||
"Vessel: {value}": "Schiff: {value}",
|
||||
"What happened: {value}": "Was geschah: {value}",
|
||||
"Depth: {m} m ({quality})": "Tiefe: {m} m ({quality})",
|
||||
"Depth: {m} m": "Tiefe: {m} m",
|
||||
"Notes: {value}": "Hinweise: {value}",
|
||||
"Cargo or finds: {value}": "Ladung oder Funde: {value}",
|
||||
"Protected wreck": "Geschütztes Wrack",
|
||||
"Source: {value}": "Quelle: {value}",
|
||||
"Click the card to open EMODnet ↗": "Karte anklicken, um EMODnet zu öffnen ↗",
|
||||
"Click the card to open the source ↗": "Karte anklicken, um die Quelle zu öffnen ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata nicht verfügbar; nur EMODnet wird angezeigt",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet nicht verfügbar; nur Wikidata wird angezeigt",
|
||||
"Shipwrecks unavailable": "Schiffswracks nicht verfügbar",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (europäische Gewässer) · Wikidata (weltweit)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} Wrack",
|
||||
"other": "{count} Wracks"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Schiffbruch",
|
||||
"Fatalities: {count}": "Todesopfer: {count}",
|
||||
"Survivors: {count}": "Überlebende: {count}",
|
||||
"Click the card to open the article ↗": "Karte anklicken, um den Artikel zu öffnen ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Europäische Kulturerbe-Wracks stammen von EMODnet Human Activities, bekannte Wracks weltweit von Wikidata. Die Farbe zeigt, wann das Schiff sank; die Markierung wächst mit der Zahl der Todesopfer. Klicke auf eine Markierung für ihre Karte.",
|
||||
"All years": "Alle Jahre",
|
||||
"Period": "Zeitraum",
|
||||
"From": "Von",
|
||||
"To": "Bis",
|
||||
"First year of the shipwreck period": "Erstes Jahr des Schiffbruch-Zeitraums",
|
||||
"Last year of the shipwreck period": "Letztes Jahr des Schiffbruch-Zeitraums",
|
||||
"SIGHTING": "BEOBACHTUNG",
|
||||
"Show {name} sighting": "Beobachtung von {name} anzeigen",
|
||||
"seen {age} ago": "vor {age} gesichtet",
|
||||
|
||||
+147
-3
@@ -1,4 +1,94 @@
|
||||
{
|
||||
"News feed unavailable": "Noticias no disponibles",
|
||||
"Developing: {name}": "En desarrollo: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} suceso hoy",
|
||||
"many": "{count} sucesos hoy",
|
||||
"other": "{count} sucesos hoy"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} noticia hoy",
|
||||
"many": "{count} noticias hoy",
|
||||
"other": "{count} noticias hoy"
|
||||
},
|
||||
"Disputed: {name}": "En disputa: {name}",
|
||||
"Video": "Vídeo",
|
||||
"Photos": "Fotos",
|
||||
"Claimed by {who}": "Según {who}",
|
||||
"Claimed": "Afirmación",
|
||||
"Not yet confirmed by others": "Aún sin confirmar por otros",
|
||||
"Reported by {side} sources": "Informado por fuentes de {side}",
|
||||
"Reported by {sides}": "Informado por {sides}",
|
||||
"{side} sources": "fuentes de {side}",
|
||||
"Official": "Oficial",
|
||||
"Reported by both sides": "Informado por ambos bandos",
|
||||
"Independently reported": "Informado de forma independiente",
|
||||
"Single source": "Fuente única",
|
||||
"International": "Internacional",
|
||||
"Independent": "Independiente",
|
||||
"Unattributed": "Sin atribuir",
|
||||
"Outside party": "Parte externa",
|
||||
"Ukraine–Russia": "Ucrania–Rusia",
|
||||
"Israel–Gaza–Lebanon": "Israel–Gaza–Líbano",
|
||||
"Iran–Hormuz": "Irán–Ormuz",
|
||||
"Yemen–Red Sea": "Yemen–Mar Rojo",
|
||||
"Sudan": "Sudán",
|
||||
"Sahel": "Sahel",
|
||||
"Elsewhere": "En otros lugares",
|
||||
"Strike": "Ataque",
|
||||
"Alert": "Alerta",
|
||||
"Air defence": "Defensa aérea",
|
||||
"Ground fighting": "Combates terrestres",
|
||||
"Casualties": "Víctimas",
|
||||
"Humanitarian": "Humanitario",
|
||||
"Disaster": "Catástrofe",
|
||||
"Protest": "Protesta",
|
||||
"Political": "Político",
|
||||
"No physical event": "Sin hecho físico",
|
||||
"Minor incident": "Incidente menor",
|
||||
"Significant": "Significativo",
|
||||
"Major": "Grave",
|
||||
"age|now": "ahora",
|
||||
"{minutes} min": "{minutes} min",
|
||||
"{hours} h": "{hours} h",
|
||||
"{count} sources": {
|
||||
"one": "{count} fuente",
|
||||
"many": "{count} fuentes",
|
||||
"other": "{count} fuentes"
|
||||
},
|
||||
"News feed not configured on this server": "Noticias no configuradas en este servidor",
|
||||
"Malformed news hotspots response": "Respuesta de focos de noticias mal formada",
|
||||
"Malformed news feed response": "Respuesta de noticias mal formada",
|
||||
"{place} (placed by model)": "{place} (ubicado por el modelo)",
|
||||
"English headline by the model": "Titular en inglés del modelo",
|
||||
"Not placed on the map": "Sin ubicar en el mapa",
|
||||
"Close": "Cerrar",
|
||||
"Any severity": "Cualquier gravedad",
|
||||
"{severity} and above": "{severity} o más",
|
||||
"{severity} only": "Solo {severity}",
|
||||
"All categories": "Todas las categorías",
|
||||
"Reading the news…": "Leyendo las noticias…",
|
||||
"News, last {hours} hours": "Noticias de las últimas {hours} horas",
|
||||
"Last {hours} h": "Últimas {hours} h",
|
||||
"Time window": "Periodo",
|
||||
"Conflicts": "Conflictos",
|
||||
"Local": "Local",
|
||||
"News sections": "Secciones de noticias",
|
||||
"Zoom in to see local news": "Acerca el mapa para ver noticias locales",
|
||||
"Hotspots": "Focos",
|
||||
"Severity": "Gravedad",
|
||||
"Category": "Categoría",
|
||||
"Nothing reported near here in the last {hours} h": "Nada informado cerca de aquí en las últimas {hours} h",
|
||||
"Latest news": "Últimas noticias",
|
||||
"No news matches these filters in the last {hours} h": "Ninguna noticia de las últimas {hours} h coincide con estos filtros",
|
||||
"Load older news": "Cargar noticias anteriores",
|
||||
"How to read the map": "Cómo leer el mapa",
|
||||
"Colour: severity · icon: type of event": "Color: gravedad · icono: tipo de suceso",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Borde continuo: informado por ambos bandos o de forma independiente. Borde discontinuo: una afirmación. Borde fino: una fuente, o la prensa de un bando.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Más grande: más fuentes · más tenue: más antiguo. Tarjeta con imagen: un suceso grave o en rápido crecimiento con dos o más fuentes.",
|
||||
"Side labels describe the source, not whether a report is true.": "Las etiquetas de bando describen la fuente, no si la noticia es cierta.",
|
||||
"Exit cockpit to fly to a news report": "Sal de la cabina para volar a una noticia",
|
||||
"News items in the feed": "Noticias en la lista",
|
||||
"NO PLACE LEFT BEHIND": "NINGÚN RINCÓN SIN VIGILAR",
|
||||
"Initializing photorealistic world...": "Inicializando el mundo fotorrealista...",
|
||||
"Configuring viewer...": "Configurando el visor...",
|
||||
@@ -320,11 +410,12 @@
|
||||
"PLACE / CONDITIONS / POSITION": "LUGAR / CLIMA / POSICIÓN",
|
||||
"POSITION UNAVAILABLE": "POSICIÓN NO DISPONIBLE",
|
||||
"REGIONAL NEWS UNAVAILABLE": "NOTICIAS DE ZONA NO DISPONIBLES",
|
||||
"CACHED · REFRESH FAILED": "EN CACHÉ · ERROR AL ACTUALIZAR",
|
||||
"REGION UNAVAILABLE": "REGIÓN NO DISPONIBLE",
|
||||
"NO RECENT LOCATION MATCHES": "SIN COINCIDENCIAS RECIENTES DE UBICACIÓN",
|
||||
"NO NEWS IN THE LAST {hours} H": "SIN NOTICIAS EN LAS ÚLTIMAS {hours} H",
|
||||
"SOURCE": "FUENTE",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{source} · LOCATION QUERY": "{source} · CONSULTA POR UBICACIÓN",
|
||||
"{source} · CACHED {age}": "{source} · EN CACHÉ {age}",
|
||||
"TIME UNKNOWN": "HORA DESCONOCIDA",
|
||||
"{count}M AGO": "HACE {count} MIN",
|
||||
"{count}H AGO": "HACE {count} H",
|
||||
@@ -2008,7 +2099,7 @@
|
||||
"MILITARY FEED OFF · PARTIAL PICTURE": "FUENTE MILITAR DESACTIVADA · PANORAMA PARCIAL",
|
||||
"FLIGHTS FEED OFF · PARTIAL PICTURE": "FUENTE DE VUELOS DESACTIVADA · PANORAMA PARCIAL",
|
||||
"NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR": "AERONAVES CERCANAS INCOMPLETAS · NO IMPLICA TODO DESPEJADO",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR UBICACIÓN · RECIENTE",
|
||||
"{source} · LAST {hours} H": "{source} · ÚLTIMAS {hours} H",
|
||||
"ft": "ft",
|
||||
"kts": "kn",
|
||||
"PAUSE": "PAUSA",
|
||||
@@ -3282,6 +3373,59 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Demasiadas solicitudes de chat. Vuelve a intentarlo en {seconds} s.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "El proveedor denegó el acceso a esta clave. Revisa el proyecto, la región o los permisos de la clave.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "La cuenta del proveedor no tiene crédito. Revisa la facturación o elige otro proveedor de IA en Ajustes.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Últimas 24 h de noticias. Cada noticia enlaza a su medio; los lugares y categorías se leen del texto y los datos automáticamente y pueden ser erróneos. Las etiquetas de bando, donde aparecen, describen la fuente, no si la noticia es cierta.",
|
||||
"Economy": "Economía",
|
||||
"News from {area}": "Noticias: {area}",
|
||||
"Within {km} km of the view centre": "A menos de {km} km del centro de la vista",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "vía {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Local en la capa de noticias: las noticias del día de los medios del país a la vista",
|
||||
"{provider} refused its key": "{provider} rechazó su clave",
|
||||
"Check {envVars} in Provider Settings": "Revisa {envVars} en Ajustes de proveedores",
|
||||
"{provider} key required": "Se necesita una clave de {provider}",
|
||||
"{provider} limit reached for today": "{provider} alcanzó su límite de hoy",
|
||||
"News resumes tomorrow, or with a paid plan": "Las noticias vuelven mañana, o con un plan de pago",
|
||||
"News key required": "Se necesita una clave de noticias",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Puntos de conflicto precisos en la capa de noticias, junto a los artículos de GDELT",
|
||||
"Worldwide": "Mundial",
|
||||
"Shipwrecks": "Naufragios",
|
||||
"Before 1900": "Antes de 1900",
|
||||
"After 1945": "Después de 1945",
|
||||
"Date unknown": "Fecha desconocida",
|
||||
"Position: centre of the protected area": "Posición: centro de la zona protegida",
|
||||
"Position approximate (within about {km} km)": "Posición aproximada (margen de unos {km} km)",
|
||||
"Position surveyed (within about {m} m)": "Posición levantada (margen de unos {m} m)",
|
||||
"Vessel: {value}": "Embarcación: {value}",
|
||||
"What happened: {value}": "Qué ocurrió: {value}",
|
||||
"Depth: {m} m ({quality})": "Profundidad: {m} m ({quality})",
|
||||
"Depth: {m} m": "Profundidad: {m} m",
|
||||
"Notes: {value}": "Notas: {value}",
|
||||
"Cargo or finds: {value}": "Carga o hallazgos: {value}",
|
||||
"Protected wreck": "Pecio protegido",
|
||||
"Source: {value}": "Fuente: {value}",
|
||||
"Click the card to open EMODnet ↗": "Haz clic en la ficha para abrir EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Haz clic en la ficha para abrir la fuente ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata no disponible; solo se muestra EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet no disponible; solo se muestra Wikidata",
|
||||
"Shipwrecks unavailable": "Naufragios no disponibles",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (aguas europeas) · Wikidata (todo el mundo)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} naufragio",
|
||||
"many": "{count} de naufragios",
|
||||
"other": "{count} naufragios"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Naufragio",
|
||||
"Fatalities: {count}": "Fallecidos: {count}",
|
||||
"Survivors: {count}": "Supervivientes: {count}",
|
||||
"Click the card to open the article ↗": "Haz clic en la ficha para abrir el artículo ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Los pecios históricos europeos proceden de EMODnet Human Activities; los naufragios notables de todo el mundo, de Wikidata. El color indica cuándo se hundió el barco; el marcador crece con el número de muertos. Haz clic en un marcador para ver su ficha.",
|
||||
"All years": "Todos los años",
|
||||
"Period": "Periodo",
|
||||
"From": "Desde",
|
||||
"To": "Hasta",
|
||||
"First year of the shipwreck period": "Primer año del periodo de naufragios",
|
||||
"Last year of the shipwreck period": "Último año del periodo de naufragios",
|
||||
"SIGHTING": "AVISTAMIENTO",
|
||||
"Show {name} sighting": "Mostrar avistamiento de {name}",
|
||||
"seen {age} ago": "visto hace {age}",
|
||||
|
||||
+147
-3
@@ -1,4 +1,94 @@
|
||||
{
|
||||
"News feed unavailable": "Fil d’actualités indisponible",
|
||||
"Developing: {name}": "En cours : {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} événement aujourd’hui",
|
||||
"many": "{count} événements aujourd’hui",
|
||||
"other": "{count} événements aujourd’hui"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} article aujourd’hui",
|
||||
"many": "{count} articles aujourd’hui",
|
||||
"other": "{count} articles aujourd’hui"
|
||||
},
|
||||
"Disputed: {name}": "Contesté : {name}",
|
||||
"Video": "Vidéo",
|
||||
"Photos": "Photos",
|
||||
"Claimed by {who}": "Selon {who}",
|
||||
"Claimed": "Affirmation",
|
||||
"Not yet confirmed by others": "Pas encore confirmé par d’autres",
|
||||
"Reported by {side} sources": "Rapporté par des sources {side}",
|
||||
"Reported by {sides}": "Rapporté par {sides}",
|
||||
"{side} sources": "sources {side}",
|
||||
"Official": "Officiel",
|
||||
"Reported by both sides": "Rapporté par les deux camps",
|
||||
"Independently reported": "Rapporté de façon indépendante",
|
||||
"Single source": "Source unique",
|
||||
"International": "Internationale",
|
||||
"Independent": "Indépendante",
|
||||
"Unattributed": "Non attribué",
|
||||
"Outside party": "Partie extérieure",
|
||||
"Ukraine–Russia": "Ukraine–Russie",
|
||||
"Israel–Gaza–Lebanon": "Israël–Gaza–Liban",
|
||||
"Iran–Hormuz": "Iran–Ormuz",
|
||||
"Yemen–Red Sea": "Yémen–mer Rouge",
|
||||
"Sudan": "Soudan",
|
||||
"Sahel": "Sahel",
|
||||
"Elsewhere": "Ailleurs",
|
||||
"Strike": "Frappe",
|
||||
"Alert": "Alerte",
|
||||
"Air defence": "Défense aérienne",
|
||||
"Ground fighting": "Combats au sol",
|
||||
"Casualties": "Victimes",
|
||||
"Humanitarian": "Humanitaire",
|
||||
"Disaster": "Catastrophe",
|
||||
"Protest": "Manifestation",
|
||||
"Political": "Politique",
|
||||
"No physical event": "Aucun événement physique",
|
||||
"Minor incident": "Incident mineur",
|
||||
"Significant": "Important",
|
||||
"Major": "Majeur",
|
||||
"age|now": "maintenant",
|
||||
"{minutes} min": "{minutes} min",
|
||||
"{hours} h": "{hours} h",
|
||||
"{count} sources": {
|
||||
"one": "{count} source",
|
||||
"many": "{count} sources",
|
||||
"other": "{count} sources"
|
||||
},
|
||||
"News feed not configured on this server": "Fil d’actualités non configuré sur ce serveur",
|
||||
"Malformed news hotspots response": "Réponse des foyers d’actualité mal formée",
|
||||
"Malformed news feed response": "Réponse du fil d’actualités mal formée",
|
||||
"{place} (placed by model)": "{place} (placé par le modèle)",
|
||||
"English headline by the model": "Titre anglais du modèle",
|
||||
"Not placed on the map": "Non placé sur la carte",
|
||||
"Close": "Fermer",
|
||||
"Any severity": "Toute gravité",
|
||||
"{severity} and above": "{severity} et plus",
|
||||
"{severity} only": "{severity} uniquement",
|
||||
"All categories": "Toutes les catégories",
|
||||
"Reading the news…": "Lecture des actualités…",
|
||||
"News, last {hours} hours": "Actualités des dernières {hours} heures",
|
||||
"Last {hours} h": "Dernières {hours} h",
|
||||
"Time window": "Période",
|
||||
"Conflicts": "Conflits",
|
||||
"Local": "Local",
|
||||
"News sections": "Rubriques d’actualité",
|
||||
"Zoom in to see local news": "Zoomez pour voir l’actualité locale",
|
||||
"Hotspots": "Foyers",
|
||||
"Severity": "Gravité",
|
||||
"Category": "Catégorie",
|
||||
"Nothing reported near here in the last {hours} h": "Rien de signalé près d’ici ces dernières {hours} h",
|
||||
"Latest news": "Dernières actualités",
|
||||
"No news matches these filters in the last {hours} h": "Aucune actualité des dernières {hours} h ne correspond à ces filtres",
|
||||
"Load older news": "Charger des actualités plus anciennes",
|
||||
"How to read the map": "Comment lire la carte",
|
||||
"Colour: severity · icon: type of event": "Couleur : gravité · icône : type d’événement",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Bord plein : rapporté par les deux camps ou de façon indépendante. Bord en tirets : une affirmation. Bord fin : une source, ou la presse d’un camp.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Plus grand : plus de sources · plus pâle : plus ancien. Carte illustrée : un événement majeur ou en forte croissance, avec au moins deux sources.",
|
||||
"Side labels describe the source, not whether a report is true.": "Les étiquettes de camp décrivent la source, pas la véracité de l’article.",
|
||||
"Exit cockpit to fly to a news report": "Quittez le cockpit pour aller à un article",
|
||||
"News items in the feed": "Articles dans le fil",
|
||||
"Pick a shape, then click the map.": "Choisissez une forme, puis cliquez sur la carte.",
|
||||
"Enter to place the pin, Esc to cancel.": "Enter pour poser l'épingle, Esc pour annuler.",
|
||||
"Click where the pin goes.": "Cliquez à l'endroit où poser l'épingle.",
|
||||
@@ -1691,14 +1781,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Faire défiler automatiquement les pages du briefing toutes les 9 secondes (Signaux → Actus → Local). Pause pendant le survol ou quand le panneau a le focus. Les signaux en direct s'actualisent en continu dans les deux cas.",
|
||||
"ACQUIRING REGIONAL NEWS": "ACQUISITION DES ACTUS RÉGIONALES",
|
||||
"REGIONAL NEWS UNAVAILABLE": "ACTUS RÉGIONALES INDISPONIBLES",
|
||||
"CACHED · REFRESH FAILED": "EN CACHE · ÉCHEC DE L’ACTUALISATION",
|
||||
"RESOLVING REGION": "IDENTIFICATION DE LA RÉGION",
|
||||
"REGION UNAVAILABLE": "RÉGION INDISPONIBLE",
|
||||
"NO RECENT LOCATION MATCHES": "AUCUNE ACTU RÉCENTE POUR CE LIEU",
|
||||
"NO NEWS IN THE LAST {hours} H": "AUCUNE ACTU CES {hours} DERNIÈRES H",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} KM/H",
|
||||
"CLOUD {pct}%": "NÉBULOSITÉ {pct} %",
|
||||
"CLOUD UNKNOWN": "NÉBULOSITÉ INCONNUE",
|
||||
"{source} · LOCATION QUERY": "{source} · REQUÊTE DE LIEU",
|
||||
"{source} · CACHED {age}": "{source} · EN CACHE {age}",
|
||||
"REGIONAL NEWS": "ACTUS RÉGIONALES",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · AIR/MER {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALLATIONS : {coverage}",
|
||||
@@ -1764,7 +1855,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "PINGS OBSERVÉS / CARTOGRAPHIÉS",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "ÉVÉNEMENTS SOURCÉS · AUCUNE ACTU SYNTHÉTIQUE",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "DERNIÈRES ACTUS LIÉES AU LIEU",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · REQUÊTE DE LIEU · RÉCENT",
|
||||
"{source} · LAST {hours} H": "{source} · {hours} DERNIÈRES H",
|
||||
"LOCAL INFO": "INFOS LOCALES",
|
||||
"PLACE / CONDITIONS / POSITION": "LIEU / CONDITIONS / POSITION",
|
||||
"TIME UNKNOWN": "HEURE INCONNUE",
|
||||
@@ -3282,6 +3373,59 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Trop de requêtes de discussion. Réessayez dans {seconds} s.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "Le fournisseur a refusé l'accès pour cette clé. Vérifiez le projet, la région ou les autorisations de la clé.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "Le compte du fournisseur n'a plus de crédit. Vérifiez la facturation ou choisissez un autre fournisseur d'IA dans les paramètres.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Dernières 24 h d’actualité. Chaque article renvoie à son éditeur ; lieux et catégories sont lus automatiquement dans le texte et les données et peuvent être faux. Les étiquettes de camp, là où elles figurent, décrivent la source, pas la véracité de l’article.",
|
||||
"Economy": "Économie",
|
||||
"News from {area}": "Actualités : {area}",
|
||||
"Within {km} km of the view centre": "À moins de {km} km du centre de la vue",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "via {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Local dans la couche Actualités : l’actualité du jour des médias du pays affiché",
|
||||
"{provider} refused its key": "{provider} a refusé sa clé",
|
||||
"Check {envVars} in Provider Settings": "Vérifiez {envVars} dans les paramètres des fournisseurs",
|
||||
"{provider} key required": "Clé {provider} requise",
|
||||
"{provider} limit reached for today": "{provider} a atteint sa limite du jour",
|
||||
"News resumes tomorrow, or with a paid plan": "Les actualités reprennent demain, ou avec une offre payante",
|
||||
"News key required": "Clé d’actualités requise",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Points de conflit précis dans la couche Actualités, à côté des articles de GDELT",
|
||||
"Worldwide": "Monde entier",
|
||||
"Shipwrecks": "Épaves",
|
||||
"Before 1900": "Avant 1900",
|
||||
"After 1945": "Après 1945",
|
||||
"Date unknown": "Date inconnue",
|
||||
"Position: centre of the protected area": "Position : centre de la zone protégée",
|
||||
"Position approximate (within about {km} km)": "Position approximative (à environ {km} km près)",
|
||||
"Position surveyed (within about {m} m)": "Position relevée (à environ {m} m près)",
|
||||
"Vessel: {value}": "Navire : {value}",
|
||||
"What happened: {value}": "Ce qui s'est passé : {value}",
|
||||
"Depth: {m} m ({quality})": "Profondeur : {m} m ({quality})",
|
||||
"Depth: {m} m": "Profondeur : {m} m",
|
||||
"Notes: {value}": "Notes : {value}",
|
||||
"Cargo or finds: {value}": "Cargaison ou découvertes : {value}",
|
||||
"Protected wreck": "Épave protégée",
|
||||
"Source: {value}": "Source : {value}",
|
||||
"Click the card to open EMODnet ↗": "Cliquez sur la fiche pour ouvrir EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Cliquez sur la fiche pour ouvrir la source ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata indisponible ; seul EMODnet est affiché",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet indisponible ; seul Wikidata est affiché",
|
||||
"Shipwrecks unavailable": "Épaves indisponibles",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (eaux européennes) · Wikidata (monde)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} épave",
|
||||
"many": "{count} d'épaves",
|
||||
"other": "{count} épaves"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Naufrage",
|
||||
"Fatalities: {count}": "Morts : {count}",
|
||||
"Survivors: {count}": "Survivants : {count}",
|
||||
"Click the card to open the article ↗": "Cliquez sur la fiche pour ouvrir l'article ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Les épaves patrimoniales européennes viennent d'EMODnet Human Activities ; les épaves notables du monde entier viennent de Wikidata. La couleur indique quand le navire a coulé ; le repère grossit avec le nombre de morts. Cliquez sur un repère pour voir sa fiche.",
|
||||
"All years": "Toutes les années",
|
||||
"Period": "Période",
|
||||
"From": "Du",
|
||||
"To": "Au",
|
||||
"First year of the shipwreck period": "Première année de la période des naufrages",
|
||||
"Last year of the shipwreck period": "Dernière année de la période des naufrages",
|
||||
"SIGHTING": "OBSERVATION",
|
||||
"Show {name} sighting": "Afficher l'observation : {name}",
|
||||
"seen {age} ago": "vu il y a {age}",
|
||||
|
||||
+148
-4
@@ -1644,7 +1644,6 @@
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "אירועים נתמכי מקור · ללא חדשות סינתטיות",
|
||||
"REGIONAL NEWS": "חדשות אזוריות",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "הדיווחים תואמי המיקום האחרונים",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · שאילתת מיקום · אחרונים",
|
||||
"LOCAL INFO": "מידע מקומי",
|
||||
"PLACE / CONDITIONS / POSITION": "מקום / מצב / עמדה",
|
||||
"Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.": "הפסק את מחזור העמודים האוטומטי. הקודם, הבא והלשוניות אותות/חדשות/מקומי נשארים זמינים.",
|
||||
@@ -1667,12 +1666,10 @@
|
||||
"CYCLE ON": "מחזור פעיל",
|
||||
"REGIONAL NEWS UNAVAILABLE": "חדשות אזוריות אינן זמינות",
|
||||
"REGION UNAVAILABLE": "אזור אינו זמין",
|
||||
"NO RECENT LOCATION MATCHES": "אין התאמות מיקום אחרונות",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} קמ\"ש",
|
||||
"CLOUD {pct}%": "עננות {pct}%",
|
||||
"CLOUD UNKNOWN": "עננות לא ידועה",
|
||||
"{source} · LOCATION QUERY": "{source} · שאילתת מיקום",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · חלון אוויר/ים {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · מתקנים {coverage}",
|
||||
"MILITARY FEED OFF · PARTIAL PICTURE": "פיד צבאי כבוי · תמונה חלקית",
|
||||
@@ -3391,5 +3388,152 @@
|
||||
"one": "אין עדיין שיתוף אופניים כאן · {n} מערכת זמינה",
|
||||
"two": "אין עדיין שיתוף אופניים כאן · {n} מערכות זמינות",
|
||||
"other": "אין עדיין שיתוף אופניים כאן · {n} מערכות זמינות"
|
||||
}
|
||||
},
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "נקודות עימות מדויקות בשכבת החדשות, לצד הכתבות של GDELT",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "מקומי בשכבת החדשות: חדשות היום מכלי התקשורת של המדינה שבתצוגה",
|
||||
"News feed unavailable": "פיד החדשות אינו זמין",
|
||||
"{provider} limit reached for today": "המכסה היומית של {provider} נוצלה",
|
||||
"News resumes tomorrow, or with a paid plan": "החדשות יחזרו מחר, או עם תוכנית בתשלום",
|
||||
"{provider} refused its key": "{provider} דחה את המפתח",
|
||||
"Check {envVars} in Provider Settings": "בדקו את {envVars} בהגדרות הספקים",
|
||||
"{provider} key required": "נדרש מפתח של {provider}",
|
||||
"Developing: {name}": "מתפתח: {name}",
|
||||
"{count} events today": {
|
||||
"one": "אירוע {count} היום",
|
||||
"two": "{count} אירועים היום",
|
||||
"other": "{count} אירועים היום"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "דיווח {count} היום",
|
||||
"two": "{count} דיווחים היום",
|
||||
"other": "{count} דיווחים היום"
|
||||
},
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "חדשות 24 השעות האחרונות. כל דיווח מקשר למפרסם שלו; מקומות וקטגוריות נקראים אוטומטית מהטקסט ומהנתונים ועלולים להיות שגויים. תוויות הצד, כשהן מוצגות, מתארות את המקור ולא אם הדיווח נכון.",
|
||||
"Disputed: {name}": "שטח במחלוקת: {name}",
|
||||
"via {source}": "דרך {source}",
|
||||
"Video": "וידאו",
|
||||
"Photos": "תמונות",
|
||||
"Claimed by {who}": "נטען על ידי {who}",
|
||||
"Claimed": "נטען",
|
||||
"Not yet confirmed by others": "טרם אושר על ידי אחרים",
|
||||
"Reported by {side} sources": "דווח על ידי מקורות {side}",
|
||||
"Reported by {sides}": "דווח על ידי {sides}",
|
||||
"{side} sources": "מקורות {side}",
|
||||
"Official": "רשמי",
|
||||
"Reported by both sides": "דווח על ידי שני הצדדים",
|
||||
"Independently reported": "דווח באופן עצמאי",
|
||||
"Single source": "מקור יחיד",
|
||||
"International": "בינלאומי",
|
||||
"Independent": "עצמאי",
|
||||
"Unattributed": "ללא ייחוס",
|
||||
"Outside party": "צד חיצוני",
|
||||
"Ukraine–Russia": "אוקראינה–רוסיה",
|
||||
"Israel–Gaza–Lebanon": "ישראל–עזה–לבנון",
|
||||
"Iran–Hormuz": "איראן–הורמוז",
|
||||
"Yemen–Red Sea": "תימן–הים האדום",
|
||||
"Sudan": "סודאן",
|
||||
"Sahel": "סאהל",
|
||||
"Elsewhere": "במקומות אחרים",
|
||||
"Worldwide": "כל העולם",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"Strike": "תקיפה",
|
||||
"Alert": "התרעה",
|
||||
"Air defence": "הגנה אווירית",
|
||||
"Ground fighting": "לחימה קרקעית",
|
||||
"Casualties": "נפגעים",
|
||||
"Humanitarian": "הומניטרי",
|
||||
"Disaster": "אסון",
|
||||
"Protest": "מחאה",
|
||||
"Political": "פוליטי",
|
||||
"Economy": "כלכלה",
|
||||
"No physical event": "ללא אירוע פיזי",
|
||||
"Minor incident": "תקרית קלה",
|
||||
"Significant": "משמעותי",
|
||||
"Major": "חמור",
|
||||
"age|now": "עכשיו",
|
||||
"{minutes} min": "{minutes} דק׳",
|
||||
"{hours} h": "{hours} שע׳",
|
||||
"{count} sources": {
|
||||
"one": "מקור {count}",
|
||||
"two": "{count} מקורות",
|
||||
"other": "{count} מקורות"
|
||||
},
|
||||
"News key required": "נדרש מפתח חדשות",
|
||||
"News feed not configured on this server": "פיד החדשות אינו מוגדר בשרת זה",
|
||||
"Malformed news hotspots response": "תגובת מוקדי החדשות פגומה",
|
||||
"Malformed news feed response": "תגובת פיד החדשות פגומה",
|
||||
"Exit cockpit to fly to a news report": "צאו מתא הטייס כדי לטוס אל דיווח חדשותי",
|
||||
"{source} · LAST {hours} H": "{source} · {hours} השעות האחרונות",
|
||||
"CACHED · REFRESH FAILED": "מהמטמון · הרענון נכשל",
|
||||
"{source} · CACHED {age}": "{source} · מהמטמון {age}",
|
||||
"NO NEWS IN THE LAST {hours} H": "אין חדשות ב־{hours} השעות האחרונות",
|
||||
"{place} (placed by model)": "{place} (מוקם על ידי המודל)",
|
||||
"English headline by the model": "כותרת באנגלית מאת המודל",
|
||||
"Not placed on the map": "לא מוקם על המפה",
|
||||
"Close": "סגירה",
|
||||
"Conflicts": "עימותים",
|
||||
"Local": "מקומי",
|
||||
"Any severity": "כל חומרה",
|
||||
"{severity} and above": "{severity} ומעלה",
|
||||
"{severity} only": "{severity} בלבד",
|
||||
"All categories": "כל הקטגוריות",
|
||||
"Last {hours} h": "{hours} שע׳ אחרונות",
|
||||
"News from {area}": "חדשות מ{area}",
|
||||
"Within {km} km of the view centre": "בטווח {km} ק״מ ממרכז התצוגה",
|
||||
"Reading the news…": "קורא את החדשות…",
|
||||
"News, last {hours} hours": "חדשות, {hours} השעות האחרונות",
|
||||
"Time window": "חלון זמן",
|
||||
"News sections": "מדורי חדשות",
|
||||
"Hotspots": "מוקדים",
|
||||
"Severity": "חומרה",
|
||||
"Category": "קטגוריה",
|
||||
"Zoom in to see local news": "התקרבו כדי לראות חדשות מקומיות",
|
||||
"Nothing reported near here in the last {hours} h": "לא דווח דבר בסביבה ב־{hours} השעות האחרונות",
|
||||
"Latest news": "חדשות אחרונות",
|
||||
"No news matches these filters in the last {hours} h": "אין חדשות התואמות למסננים אלה ב־{hours} השעות האחרונות",
|
||||
"Load older news": "טעינת חדשות ישנות יותר",
|
||||
"How to read the map": "איך לקרוא את המפה",
|
||||
"Colour: severity · icon: type of event": "צבע: חומרה · סמל: סוג האירוע",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "מסגרת מלאה: דווח על ידי שני הצדדים או באופן עצמאי. מסגרת מקווקוות: טענה. מסגרת דקה: מקור יחיד, או התקשורת של אחד הצדדים.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "גדול יותר: יותר מקורות · דהוי יותר: ישן יותר. כרטיס תמונה: אירוע חמור או מתפתח במהירות עם שני מקורות או יותר.",
|
||||
"Side labels describe the source, not whether a report is true.": "תוויות הצד מתארות את המקור, לא אם הדיווח נכון.",
|
||||
"News items in the feed": "פריטי חדשות בפיד",
|
||||
"Shipwrecks": "ספינות טרופות",
|
||||
"Before 1900": "לפני 1900",
|
||||
"1900–1945": "1900–1945",
|
||||
"After 1945": "אחרי 1945",
|
||||
"Date unknown": "תאריך לא ידוע",
|
||||
"Position: centre of the protected area": "מיקום: מרכז השטח המוגן",
|
||||
"Position approximate (within about {km} km)": "מיקום משוער (בטווח של כ־{km} ק״מ)",
|
||||
"Position surveyed (within about {m} m)": "מיקום שנמדד (בטווח של כ־{m} מ׳)",
|
||||
"Shipwreck": "ספינה טרופה",
|
||||
"Fatalities: {count}": "הרוגים: {count}",
|
||||
"Survivors: {count}": "ניצולים: {count}",
|
||||
"Vessel: {value}": "כלי שיט: {value}",
|
||||
"What happened: {value}": "מה קרה: {value}",
|
||||
"Depth: {m} m ({quality})": "עומק: {m} מ׳ ({quality})",
|
||||
"Depth: {m} m": "עומק: {m} מ׳",
|
||||
"Notes: {value}": "הערות: {value}",
|
||||
"Cargo or finds: {value}": "מטען או ממצאים: {value}",
|
||||
"Protected wreck": "ספינה טרופה מוגנת",
|
||||
"Source: {value}": "מקור: {value}",
|
||||
"Click the card to open EMODnet ↗": "לחץ על הכרטיס כדי לפתוח את EMODnet ↗",
|
||||
"Click the card to open the article ↗": "לחץ על הכרטיס כדי לפתוח את הערך ↗",
|
||||
"Click the card to open the source ↗": "לחץ על הכרטיס כדי לפתוח את המקור ↗",
|
||||
"All years": "כל השנים",
|
||||
"Period": "תקופה",
|
||||
"From": "מ־",
|
||||
"First year of the shipwreck period": "השנה הראשונה בתקופת הטביעות",
|
||||
"To": "עד",
|
||||
"Last year of the shipwreck period": "השנה האחרונה בתקופת הטביעות",
|
||||
"Wikidata unavailable; showing EMODnet only": "ויקינתונים אינו זמין; מוצג EMODnet בלבד",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet אינו זמין; מוצג ויקינתונים בלבד",
|
||||
"Shipwrecks unavailable": "ספינות טרופות לא זמינות",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} ספינה טרופה",
|
||||
"two": "{count} ספינות טרופות",
|
||||
"other": "{count} ספינות טרופות"
|
||||
},
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (מימי אירופה) · ויקינתונים (כל העולם)",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "ספינות טרופות אירופיות בעלות ערך מורשת מגיעות מ־EMODnet Human Activities; ספינות טרופות בולטות מכל העולם מגיעות מוויקינתונים. הצבע מראה מתי הספינה טבעה; הסמן גדל ככל שמספר ההרוגים עולה. לחץ על סמן כדי לפתוח את הכרטיס שלו."
|
||||
}
|
||||
+147
-3
@@ -1,4 +1,94 @@
|
||||
{
|
||||
"News feed unavailable": "Feed delle notizie non disponibile",
|
||||
"Developing: {name}": "In sviluppo: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} evento oggi",
|
||||
"many": "{count} eventi oggi",
|
||||
"other": "{count} eventi oggi"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} notizia oggi",
|
||||
"many": "{count} notizie oggi",
|
||||
"other": "{count} notizie oggi"
|
||||
},
|
||||
"Disputed: {name}": "Conteso: {name}",
|
||||
"Video": "Video",
|
||||
"Photos": "Foto",
|
||||
"Claimed by {who}": "Secondo {who}",
|
||||
"Claimed": "Affermazione",
|
||||
"Not yet confirmed by others": "Non ancora confermato da altri",
|
||||
"Reported by {side} sources": "Riportato da fonti {side}",
|
||||
"Reported by {sides}": "Riportato da {sides}",
|
||||
"{side} sources": "fonti {side}",
|
||||
"Official": "Ufficiale",
|
||||
"Reported by both sides": "Riportato da entrambe le parti",
|
||||
"Independently reported": "Riportato in modo indipendente",
|
||||
"Single source": "Fonte unica",
|
||||
"International": "Internazionale",
|
||||
"Independent": "Indipendente",
|
||||
"Unattributed": "Non attribuito",
|
||||
"Outside party": "Parte esterna",
|
||||
"Ukraine–Russia": "Ucraina–Russia",
|
||||
"Israel–Gaza–Lebanon": "Israele–Gaza–Libano",
|
||||
"Iran–Hormuz": "Iran–Hormuz",
|
||||
"Yemen–Red Sea": "Yemen–Mar Rosso",
|
||||
"Sudan": "Sudan",
|
||||
"Sahel": "Sahel",
|
||||
"Elsewhere": "Altrove",
|
||||
"Strike": "Attacco",
|
||||
"Alert": "Allerta",
|
||||
"Air defence": "Difesa aerea",
|
||||
"Ground fighting": "Combattimenti a terra",
|
||||
"Casualties": "Vittime",
|
||||
"Humanitarian": "Umanitario",
|
||||
"Disaster": "Disastro",
|
||||
"Protest": "Protesta",
|
||||
"Political": "Politica",
|
||||
"No physical event": "Nessun evento fisico",
|
||||
"Minor incident": "Incidente minore",
|
||||
"Significant": "Rilevante",
|
||||
"Major": "Grave",
|
||||
"age|now": "ora",
|
||||
"{minutes} min": "{minutes} min",
|
||||
"{hours} h": "{hours} h",
|
||||
"{count} sources": {
|
||||
"one": "{count} fonte",
|
||||
"many": "{count} fonti",
|
||||
"other": "{count} fonti"
|
||||
},
|
||||
"News feed not configured on this server": "Feed delle notizie non configurato su questo server",
|
||||
"Malformed news hotspots response": "Risposta dei focolai di notizie non valida",
|
||||
"Malformed news feed response": "Risposta del feed delle notizie non valida",
|
||||
"{place} (placed by model)": "{place} (collocato dal modello)",
|
||||
"English headline by the model": "Titolo inglese del modello",
|
||||
"Not placed on the map": "Non collocato sulla mappa",
|
||||
"Close": "Chiudi",
|
||||
"Any severity": "Qualsiasi gravità",
|
||||
"{severity} and above": "{severity} e oltre",
|
||||
"{severity} only": "Solo {severity}",
|
||||
"All categories": "Tutte le categorie",
|
||||
"Reading the news…": "Lettura delle notizie…",
|
||||
"News, last {hours} hours": "Notizie delle ultime {hours} ore",
|
||||
"Last {hours} h": "Ultime {hours} h",
|
||||
"Time window": "Periodo",
|
||||
"Conflicts": "Conflitti",
|
||||
"Local": "Locale",
|
||||
"News sections": "Sezioni notizie",
|
||||
"Zoom in to see local news": "Ingrandisci per vedere le notizie locali",
|
||||
"Hotspots": "Focolai",
|
||||
"Severity": "Gravità",
|
||||
"Category": "Categoria",
|
||||
"Nothing reported near here in the last {hours} h": "Nulla segnalato qui vicino nelle ultime {hours} h",
|
||||
"Latest news": "Ultime notizie",
|
||||
"No news matches these filters in the last {hours} h": "Nessuna notizia delle ultime {hours} h corrisponde a questi filtri",
|
||||
"Load older news": "Carica notizie precedenti",
|
||||
"How to read the map": "Come leggere la mappa",
|
||||
"Colour: severity · icon: type of event": "Colore: gravità · icona: tipo di evento",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Bordo pieno: riportato da entrambe le parti o in modo indipendente. Bordo tratteggiato: un’affermazione. Bordo sottile: una fonte, o la stampa di una parte.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Più grande: più fonti · più tenue: più vecchio. Scheda con immagine: un evento grave o in rapida crescita con due o più fonti.",
|
||||
"Side labels describe the source, not whether a report is true.": "Le etichette di parte descrivono la fonte, non se la notizia è vera.",
|
||||
"Exit cockpit to fly to a news report": "Esci dalla cabina per volare a una notizia",
|
||||
"News items in the feed": "Notizie nel feed",
|
||||
"Pick a shape, then click the map.": "Scegli una forma, poi fai clic sulla mappa.",
|
||||
"Enter to place the pin, Esc to cancel.": "Premi Enter per posizionare il segnaposto, Esc per annullare.",
|
||||
"Click where the pin goes.": "Fai clic dove va il segnaposto.",
|
||||
@@ -1691,14 +1781,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Scorri automaticamente le pagine del briefing ogni 9 secondi (Segnali → Notizie → Locale). Lo scorrimento si interrompe quando passi sul pannello o lo selezioni. I dati dei segnali live si aggiornano comunque di continuo.",
|
||||
"ACQUIRING REGIONAL NEWS": "ACQUISIZIONE NOTIZIE REGIONALI",
|
||||
"REGIONAL NEWS UNAVAILABLE": "NOTIZIE REGIONALI NON DISPONIBILI",
|
||||
"CACHED · REFRESH FAILED": "IN CACHE · AGGIORNAMENTO NON RIUSCITO",
|
||||
"RESOLVING REGION": "IDENTIFICAZIONE REGIONE",
|
||||
"REGION UNAVAILABLE": "REGIONE NON DISPONIBILE",
|
||||
"NO RECENT LOCATION MATCHES": "NESSUNA CORRISPONDENZA RECENTE PER POSIZIONE",
|
||||
"NO NEWS IN THE LAST {hours} H": "NESSUNA NOTIZIA NELLE ULTIME {hours} H",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} KM/H",
|
||||
"CLOUD {pct}%": "NUVOLE {pct}%",
|
||||
"CLOUD UNKNOWN": "NUVOLE N/D",
|
||||
"{source} · LOCATION QUERY": "{source} · QUERY PER POSIZIONE",
|
||||
"{source} · CACHED {age}": "{source} · IN CACHE {age}",
|
||||
"REGIONAL NEWS": "NOTIZIE REGIONALI",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · ARIA/MARE {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · SITI {coverage}",
|
||||
@@ -1764,7 +1855,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "PING OSSERVATI / MAPPATI",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTI DA FONTI · NESSUNA NOTIZIA SINTETICA",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "ULTIME NOTIZIE PER POSIZIONE",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · QUERY PER POSIZIONE · RECENTI",
|
||||
"{source} · LAST {hours} H": "{source} · ULTIME {hours} H",
|
||||
"LOCAL INFO": "INFO LOCALI",
|
||||
"PLACE / CONDITIONS / POSITION": "LUOGO / CONDIZIONI / POSIZIONE",
|
||||
"TIME UNKNOWN": "ORA SCONOSCIUTA",
|
||||
@@ -3282,6 +3373,59 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Troppe richieste di chat. Riprova tra {seconds} s.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "Il provider ha negato l'accesso per questa chiave. Controlla progetto, regione o autorizzazioni della chiave.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "L'account del provider ha esaurito il credito. Controlla la fatturazione o scegli un altro provider IA in Impostazioni.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Ultime 24 h di notizie. Ogni notizia rimanda al suo editore; luoghi e categorie sono letti automaticamente dal testo e dai dati e possono essere errati. Le etichette di parte, dove presenti, descrivono la fonte, non se la notizia è vera.",
|
||||
"Economy": "Economia",
|
||||
"News from {area}": "Notizie: {area}",
|
||||
"Within {km} km of the view centre": "Entro {km} km dal centro della vista",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "tramite {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Locale nel livello Notizie: le notizie del giorno dalle testate del paese inquadrato",
|
||||
"{provider} refused its key": "{provider} ha rifiutato la chiave",
|
||||
"Check {envVars} in Provider Settings": "Controlla {envVars} in Impostazioni provider",
|
||||
"{provider} key required": "Chiave {provider} richiesta",
|
||||
"{provider} limit reached for today": "{provider} ha raggiunto il limite di oggi",
|
||||
"News resumes tomorrow, or with a paid plan": "Le notizie riprendono domani, o con un piano a pagamento",
|
||||
"News key required": "Chiave per le notizie richiesta",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Punti di conflitto precisi nel livello Notizie, accanto agli articoli di GDELT",
|
||||
"Worldwide": "Mondo",
|
||||
"Shipwrecks": "Relitti",
|
||||
"Before 1900": "Prima del 1900",
|
||||
"After 1945": "Dopo il 1945",
|
||||
"Date unknown": "Data sconosciuta",
|
||||
"Position: centre of the protected area": "Posizione: centro dell'area protetta",
|
||||
"Position approximate (within about {km} km)": "Posizione approssimativa (entro circa {km} km)",
|
||||
"Position surveyed (within about {m} m)": "Posizione rilevata (entro circa {m} m)",
|
||||
"Vessel: {value}": "Imbarcazione: {value}",
|
||||
"What happened: {value}": "Cosa è successo: {value}",
|
||||
"Depth: {m} m ({quality})": "Profondità: {m} m ({quality})",
|
||||
"Depth: {m} m": "Profondità: {m} m",
|
||||
"Notes: {value}": "Note: {value}",
|
||||
"Cargo or finds: {value}": "Carico o reperti: {value}",
|
||||
"Protected wreck": "Relitto protetto",
|
||||
"Source: {value}": "Fonte: {value}",
|
||||
"Click the card to open EMODnet ↗": "Fai clic sulla scheda per aprire EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Fai clic sulla scheda per aprire la fonte ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata non disponibile; solo EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet non disponibile; solo Wikidata",
|
||||
"Shipwrecks unavailable": "Relitti non disponibili",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (acque europee) · Wikidata (mondo)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} relitto",
|
||||
"many": "{count} di relitti",
|
||||
"other": "{count} relitti"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Naufragio",
|
||||
"Fatalities: {count}": "Vittime: {count}",
|
||||
"Survivors: {count}": "Sopravvissuti: {count}",
|
||||
"Click the card to open the article ↗": "Fai clic sulla scheda per aprire l'articolo ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "I relitti storici europei provengono da EMODnet Human Activities; i relitti noti di tutto il mondo da Wikidata. Il colore indica quando la nave è affondata; l'indicatore cresce con il numero di vittime. Fai clic su un indicatore per la sua scheda.",
|
||||
"All years": "Tutti gli anni",
|
||||
"Period": "Periodo",
|
||||
"From": "Dal",
|
||||
"To": "Al",
|
||||
"First year of the shipwreck period": "Primo anno del periodo dei naufragi",
|
||||
"Last year of the shipwreck period": "Ultimo anno del periodo dei naufragi",
|
||||
"SIGHTING": "AVVISTAMENTO",
|
||||
"Show {name} sighting": "Mostra avvistamento di {name}",
|
||||
"seen {age} ago": "avvistato {age} fa",
|
||||
|
||||
+139
-3
@@ -1,4 +1,88 @@
|
||||
{
|
||||
"News feed unavailable": "ニュースフィードを利用できません",
|
||||
"Developing: {name}": "進行中: {name}",
|
||||
"{count} events today": {
|
||||
"other": "本日の出来事 {count}件"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"other": "本日の報道 {count}件"
|
||||
},
|
||||
"Disputed: {name}": "係争地: {name}",
|
||||
"Video": "動画",
|
||||
"Photos": "写真",
|
||||
"Claimed by {who}": "{who}の主張",
|
||||
"Claimed": "主張",
|
||||
"Not yet confirmed by others": "他からの確認はまだない",
|
||||
"Reported by {side} sources": "{side}側の情報源が報道",
|
||||
"Reported by {sides}": "報道: {sides}",
|
||||
"{side} sources": "{side}側の情報源",
|
||||
"Official": "公式",
|
||||
"Reported by both sides": "双方が報道",
|
||||
"Independently reported": "独立した報道あり",
|
||||
"Single source": "単一の情報源",
|
||||
"International": "国際",
|
||||
"Independent": "独立系",
|
||||
"Unattributed": "出所不明",
|
||||
"Outside party": "第三者",
|
||||
"Ukraine–Russia": "ウクライナ–ロシア",
|
||||
"Israel–Gaza–Lebanon": "イスラエル–ガザ–レバノン",
|
||||
"Iran–Hormuz": "イラン–ホルムズ",
|
||||
"Yemen–Red Sea": "イエメン–紅海",
|
||||
"Sudan": "スーダン",
|
||||
"Sahel": "サヘル",
|
||||
"Elsewhere": "その他の地域",
|
||||
"Strike": "攻撃",
|
||||
"Alert": "警報",
|
||||
"Air defence": "防空",
|
||||
"Ground fighting": "地上戦",
|
||||
"Casualties": "死傷者",
|
||||
"Humanitarian": "人道",
|
||||
"Disaster": "災害",
|
||||
"Protest": "抗議",
|
||||
"Political": "政治",
|
||||
"No physical event": "物理的な事象なし",
|
||||
"Minor incident": "小規模な事案",
|
||||
"Significant": "重大",
|
||||
"Major": "深刻",
|
||||
"age|now": "今",
|
||||
"{minutes} min": "{minutes}分",
|
||||
"{hours} h": "{hours}時間",
|
||||
"{count} sources": {
|
||||
"other": "情報源 {count}件"
|
||||
},
|
||||
"News feed not configured on this server": "このサーバーではニュースフィードが設定されていません",
|
||||
"Malformed news hotspots response": "ニュースのホットスポット応答の形式が不正です",
|
||||
"Malformed news feed response": "ニュースフィードの応答の形式が不正です",
|
||||
"{place} (placed by model)": "{place}(モデルが推定)",
|
||||
"English headline by the model": "モデルによる英語の見出し",
|
||||
"Not placed on the map": "地図上に配置されていません",
|
||||
"Close": "閉じる",
|
||||
"Any severity": "すべての深刻度",
|
||||
"{severity} and above": "{severity}以上",
|
||||
"{severity} only": "{severity}のみ",
|
||||
"All categories": "すべてのカテゴリ",
|
||||
"Reading the news…": "ニュースを読み込み中…",
|
||||
"News, last {hours} hours": "直近{hours}時間のニュース",
|
||||
"Last {hours} h": "直近{hours}時間",
|
||||
"Time window": "期間",
|
||||
"Conflicts": "紛争",
|
||||
"Local": "ローカル",
|
||||
"News sections": "ニュースの区分",
|
||||
"Zoom in to see local news": "拡大するとローカルニュースが表示されます",
|
||||
"Hotspots": "ホットスポット",
|
||||
"Severity": "深刻度",
|
||||
"Category": "カテゴリ",
|
||||
"Nothing reported near here in the last {hours} h": "直近{hours}時間、この付近の報道はありません",
|
||||
"Latest news": "最新ニュース",
|
||||
"No news matches these filters in the last {hours} h": "直近{hours}時間で条件に合うニュースはありません",
|
||||
"Load older news": "以前のニュースを読み込む",
|
||||
"How to read the map": "地図の見方",
|
||||
"Colour: severity · icon: type of event": "色: 深刻度 · アイコン: 出来事の種類",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "実線の縁: 双方または独立した情報源が報道。破線の縁: 主張。細い縁: 単一の情報源、または一方の陣営のメディア。",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "大きい: 情報源が多い · 薄い: 古い。画像カード: 情報源が2件以上ある深刻な、または急拡大中の出来事。",
|
||||
"Side labels describe the source, not whether a report is true.": "陣営ラベルは情報源を示すもので、報道の真偽ではありません。",
|
||||
"Exit cockpit to fly to a news report": "ニュースへ移動するにはコックピットを終了してください",
|
||||
"News items in the feed": "フィード内のニュース数",
|
||||
"Pick a shape, then click the map.": "図形を選んでから、地図をクリックしてください。",
|
||||
"Enter to place the pin, Esc to cancel.": "Enterでピンを配置、Escでキャンセル。",
|
||||
"Click where the pin goes.": "ピンを置く場所をクリックしてください。",
|
||||
@@ -1643,14 +1727,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "9秒ごとにブリーフィングページを自動で切り替えます(シグナル → ニュース → ローカル)。パネルにカーソルを合わせるかフォーカスしている間は一時停止します。ライブシグナルのデータは、どちらの場合も継続的に更新されます。",
|
||||
"ACQUIRING REGIONAL NEWS": "地域ニュースを取得中",
|
||||
"REGIONAL NEWS UNAVAILABLE": "地域ニュースを取得できません",
|
||||
"CACHED · REFRESH FAILED": "キャッシュ · 更新失敗",
|
||||
"RESOLVING REGION": "地域を特定中",
|
||||
"REGION UNAVAILABLE": "地域を取得できません",
|
||||
"NO RECENT LOCATION MATCHES": "この地域の最近のニュースなし",
|
||||
"NO NEWS IN THE LAST {hours} H": "過去{hours}時間のニュースなし",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} km/h",
|
||||
"CLOUD {pct}%": "雲量 {pct}%",
|
||||
"CLOUD UNKNOWN": "雲量不明",
|
||||
"{source} · LOCATION QUERY": "{source} · 位置クエリ",
|
||||
"{source} · CACHED {age}": "{source} · キャッシュ {age}",
|
||||
"REGIONAL NEWS": "地域ニュース",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · 航空機/船舶の範囲 {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · 施設 {coverage}",
|
||||
@@ -1714,7 +1799,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "観測 / マップ済みピング",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "出典付きイベントのみ · 合成ニュースなし",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "位置に一致する最新の報道",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · 位置クエリ · 最近",
|
||||
"{source} · LAST {hours} H": "{source} · 過去{hours}時間",
|
||||
"LOCAL INFO": "ローカル情報",
|
||||
"PLACE / CONDITIONS / POSITION": "場所 / 天候 / 位置",
|
||||
"TIME UNKNOWN": "時刻不明",
|
||||
@@ -3128,6 +3213,57 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "チャットのリクエストが多すぎます。{seconds}秒後にもう一度お試しください。",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "プロバイダーがこのキーでのアクセスを拒否しました。キーのプロジェクト、リージョン、権限を確認してください。",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "プロバイダーアカウントのクレジットが不足しています。課金状況を確認するか、設定で別のAIプロバイダーを選んでください。",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "直近24時間のニュース。各報道は発信元にリンクします。場所とカテゴリは本文とデータから自動で読み取るため誤りがあり得ます。陣営ラベルは、表示される場合、情報源を示すもので、報道の真偽ではありません。",
|
||||
"Economy": "経済",
|
||||
"News from {area}": "{area}のニュース",
|
||||
"Within {km} km of the view centre": "表示中心から{km} km以内",
|
||||
"{region}, {country}": "{country}・{region}",
|
||||
"via {source}": "{source}経由",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "ニュースレイヤーのローカル:表示中の国のメディアによる今日のニュース",
|
||||
"{provider} refused its key": "{provider}がキーを拒否しました",
|
||||
"Check {envVars} in Provider Settings": "プロバイダー設定で{envVars}を確認してください",
|
||||
"{provider} key required": "{provider}のキーが必要です",
|
||||
"{provider} limit reached for today": "{provider}の本日の上限に達しました",
|
||||
"News resumes tomorrow, or with a paid plan": "ニュースは明日、または有料プランで再開します",
|
||||
"News key required": "ニュースのキーが必要です",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "ニュースレイヤーの正確な紛争地点(GDELTの記事に加えて)",
|
||||
"Worldwide": "世界",
|
||||
"Shipwrecks": "難破船",
|
||||
"Before 1900": "1900年以前",
|
||||
"After 1945": "1945年以降",
|
||||
"Date unknown": "日付不明",
|
||||
"Position: centre of the protected area": "位置: 保護区域の中心",
|
||||
"Position approximate (within about {km} km)": "おおよその位置(誤差約{km} km)",
|
||||
"Position surveyed (within about {m} m)": "測量された位置(誤差約{m} m)",
|
||||
"Vessel: {value}": "船種: {value}",
|
||||
"What happened: {value}": "経緯: {value}",
|
||||
"Depth: {m} m ({quality})": "水深: {m} m({quality})",
|
||||
"Depth: {m} m": "水深: {m} m",
|
||||
"Notes: {value}": "備考: {value}",
|
||||
"Cargo or finds: {value}": "積荷・遺物: {value}",
|
||||
"Protected wreck": "保護対象の難破船",
|
||||
"Source: {value}": "出典: {value}",
|
||||
"Click the card to open EMODnet ↗": "カードをクリックしてEMODnetを開く ↗",
|
||||
"Click the card to open the source ↗": "カードをクリックして出典を開く ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidataを利用できません。EMODnetのみ表示しています",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnetを利用できません。Wikidataのみ表示しています",
|
||||
"Shipwrecks unavailable": "難破船データを利用できません",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(欧州海域)· Wikidata(世界)",
|
||||
"{count} wrecks": {
|
||||
"other": "難破船 {count}件"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "難破",
|
||||
"Fatalities: {count}": "死者: {count}",
|
||||
"Survivors: {count}": "生存者: {count}",
|
||||
"Click the card to open the article ↗": "カードをクリックして記事を開く ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧州の歴史的な難破船はEMODnet Human Activities、世界の著名な難破船はWikidataによります。色は沈没した時期を示し、マーカーは死者数に応じて大きくなります。マーカーをクリックするとカードが開きます。",
|
||||
"All years": "全期間",
|
||||
"Period": "期間",
|
||||
"From": "開始",
|
||||
"To": "終了",
|
||||
"First year of the shipwreck period": "難破の期間の開始年",
|
||||
"Last year of the shipwreck period": "難破の期間の終了年",
|
||||
"SIGHTING": "目撃情報",
|
||||
"Show {name} sighting": "{name}の目撃情報を表示",
|
||||
"seen {age} ago": "{age}前に目撃",
|
||||
|
||||
+147
-3
@@ -1,4 +1,94 @@
|
||||
{
|
||||
"News feed unavailable": "Feed de notícias indisponível",
|
||||
"Developing: {name}": "Em desenvolvimento: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} evento hoje",
|
||||
"many": "{count} eventos hoje",
|
||||
"other": "{count} eventos hoje"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} notícia hoje",
|
||||
"many": "{count} notícias hoje",
|
||||
"other": "{count} notícias hoje"
|
||||
},
|
||||
"Disputed: {name}": "Em disputa: {name}",
|
||||
"Video": "Vídeo",
|
||||
"Photos": "Fotos",
|
||||
"Claimed by {who}": "Segundo {who}",
|
||||
"Claimed": "Alegação",
|
||||
"Not yet confirmed by others": "Ainda não confirmado por outros",
|
||||
"Reported by {side} sources": "Noticiado por fontes de {side}",
|
||||
"Reported by {sides}": "Noticiado por {sides}",
|
||||
"{side} sources": "fontes de {side}",
|
||||
"Official": "Oficial",
|
||||
"Reported by both sides": "Noticiado por ambos os lados",
|
||||
"Independently reported": "Noticiado de forma independente",
|
||||
"Single source": "Fonte única",
|
||||
"International": "Internacional",
|
||||
"Independent": "Independente",
|
||||
"Unattributed": "Sem atribuição",
|
||||
"Outside party": "Parte externa",
|
||||
"Ukraine–Russia": "Ucrânia–Rússia",
|
||||
"Israel–Gaza–Lebanon": "Israel–Gaza–Líbano",
|
||||
"Iran–Hormuz": "Irã–Ormuz",
|
||||
"Yemen–Red Sea": "Iêmen–Mar Vermelho",
|
||||
"Sudan": "Sudão",
|
||||
"Sahel": "Sahel",
|
||||
"Elsewhere": "Outros lugares",
|
||||
"Strike": "Ataque",
|
||||
"Alert": "Alerta",
|
||||
"Air defence": "Defesa aérea",
|
||||
"Ground fighting": "Combates terrestres",
|
||||
"Casualties": "Vítimas",
|
||||
"Humanitarian": "Humanitário",
|
||||
"Disaster": "Desastre",
|
||||
"Protest": "Protesto",
|
||||
"Political": "Político",
|
||||
"No physical event": "Sem evento físico",
|
||||
"Minor incident": "Incidente menor",
|
||||
"Significant": "Significativo",
|
||||
"Major": "Grave",
|
||||
"age|now": "agora",
|
||||
"{minutes} min": "{minutes} min",
|
||||
"{hours} h": "{hours} h",
|
||||
"{count} sources": {
|
||||
"one": "{count} fonte",
|
||||
"many": "{count} fontes",
|
||||
"other": "{count} fontes"
|
||||
},
|
||||
"News feed not configured on this server": "Feed de notícias não configurado neste servidor",
|
||||
"Malformed news hotspots response": "Resposta de focos de notícias malformada",
|
||||
"Malformed news feed response": "Resposta do feed de notícias malformada",
|
||||
"{place} (placed by model)": "{place} (localizado pelo modelo)",
|
||||
"English headline by the model": "Manchete em inglês do modelo",
|
||||
"Not placed on the map": "Não localizado no mapa",
|
||||
"Close": "Fechar",
|
||||
"Any severity": "Qualquer gravidade",
|
||||
"{severity} and above": "{severity} ou mais",
|
||||
"{severity} only": "Apenas {severity}",
|
||||
"All categories": "Todas as categorias",
|
||||
"Reading the news…": "Lendo as notícias…",
|
||||
"News, last {hours} hours": "Notícias das últimas {hours} horas",
|
||||
"Last {hours} h": "Últimas {hours} h",
|
||||
"Time window": "Período",
|
||||
"Conflicts": "Conflitos",
|
||||
"Local": "Local",
|
||||
"News sections": "Secções de notícias",
|
||||
"Zoom in to see local news": "Aproxime para ver notícias locais",
|
||||
"Hotspots": "Focos",
|
||||
"Severity": "Gravidade",
|
||||
"Category": "Categoria",
|
||||
"Nothing reported near here in the last {hours} h": "Nada noticiado aqui perto nas últimas {hours} h",
|
||||
"Latest news": "Últimas notícias",
|
||||
"No news matches these filters in the last {hours} h": "Nenhuma notícia das últimas {hours} h corresponde a estes filtros",
|
||||
"Load older news": "Carregar notícias anteriores",
|
||||
"How to read the map": "Como ler o mapa",
|
||||
"Colour: severity · icon: type of event": "Cor: gravidade · ícone: tipo de evento",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Borda contínua: noticiado por ambos os lados ou de forma independente. Borda tracejada: uma alegação. Borda fina: uma fonte, ou a imprensa de um lado.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Maior: mais fontes · mais tênue: mais antigo. Cartão com imagem: um evento grave ou em rápido crescimento com duas ou mais fontes.",
|
||||
"Side labels describe the source, not whether a report is true.": "Os rótulos de lado descrevem a fonte, não se a notícia é verdadeira.",
|
||||
"Exit cockpit to fly to a news report": "Saia da cabine para voar até uma notícia",
|
||||
"News items in the feed": "Notícias no feed",
|
||||
"Pick a shape, then click the map.": "Escolha uma forma e clique no mapa.",
|
||||
"Enter to place the pin, Esc to cancel.": "Enter para colocar o marcador, Esc para cancelar.",
|
||||
"Click where the pin goes.": "Clique onde o marcador deve ficar.",
|
||||
@@ -1691,14 +1781,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Alternar as páginas do briefing automaticamente a cada 9 segundos (Sinais → Notícias → Local). A alternância pausa enquanto você passa o mouse ou foca o painel. Os dados de sinais ao vivo continuam sendo atualizados de qualquer forma.",
|
||||
"ACQUIRING REGIONAL NEWS": "OBTENDO NOTÍCIAS DA ÁREA",
|
||||
"REGIONAL NEWS UNAVAILABLE": "NOTÍCIAS DA ÁREA INDISPONÍVEIS",
|
||||
"CACHED · REFRESH FAILED": "EM CACHE · FALHA AO ATUALIZAR",
|
||||
"RESOLVING REGION": "IDENTIFICANDO REGIÃO",
|
||||
"REGION UNAVAILABLE": "REGIÃO INDISPONÍVEL",
|
||||
"NO RECENT LOCATION MATCHES": "NENHUMA CORRESPONDÊNCIA RECENTE COM O LOCAL",
|
||||
"NO NEWS IN THE LAST {hours} H": "SEM NOTÍCIAS NAS ÚLTIMAS {hours} H",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} KM/H",
|
||||
"CLOUD {pct}%": "NUVENS {pct}%",
|
||||
"CLOUD UNKNOWN": "NEBULOSIDADE DESCONHECIDA",
|
||||
"{source} · LOCATION QUERY": "{source} · CONSULTA POR LOCAL",
|
||||
"{source} · CACHED {age}": "{source} · EM CACHE {age}",
|
||||
"REGIONAL NEWS": "NOTÍCIAS DA ÁREA",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · AR/MAR {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALAÇÕES: {coverage}",
|
||||
@@ -1764,7 +1855,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "PINGS OBSERVADOS / MAPEADOS",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTOS COM FONTE · SEM NOTÍCIAS SINTÉTICAS",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "ÚLTIMAS NOTÍCIAS DO LOCAL",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR LOCAL · RECENTE",
|
||||
"{source} · LAST {hours} H": "{source} · ÚLTIMAS {hours} H",
|
||||
"LOCAL INFO": "INFO LOCAL",
|
||||
"PLACE / CONDITIONS / POSITION": "LUGAR / CONDIÇÕES / POSIÇÃO",
|
||||
"TIME UNKNOWN": "HORA DESCONHECIDA",
|
||||
@@ -3282,6 +3373,59 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Chat: limite de requisições atingido. Tente novamente em {seconds} s.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "O provedor negou o acesso para esta chave. Verifique o projeto, a região ou as permissões da chave.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "A conta do provedor está sem crédito. Verifique o faturamento ou escolha outro provedor de IA em \"Configurações\".",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Últimas 24 h de notícias. Cada notícia leva ao seu editor; locais e categorias são lidos do texto e dos dados automaticamente e podem estar errados. Os rótulos de lado, quando exibidos, descrevem a fonte, não se a notícia é verdadeira.",
|
||||
"Economy": "Economia",
|
||||
"News from {area}": "Notícias: {area}",
|
||||
"Within {km} km of the view centre": "Até {km} km do centro da vista",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "via {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Local na camada de notícias: as notícias do dia dos veículos do país em vista",
|
||||
"{provider} refused its key": "{provider} recusou a chave",
|
||||
"Check {envVars} in Provider Settings": "Verifique {envVars} em \"Configurações de provedores\"",
|
||||
"{provider} key required": "Chave do {provider} necessária",
|
||||
"{provider} limit reached for today": "{provider} atingiu o limite de hoje",
|
||||
"News resumes tomorrow, or with a paid plan": "As notícias voltam amanhã, ou com um plano pago",
|
||||
"News key required": "Chave de notícias necessária",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Pontos de conflito precisos na camada de notícias, ao lado dos artigos do GDELT",
|
||||
"Worldwide": "Mundo",
|
||||
"Shipwrecks": "Naufrágios",
|
||||
"Before 1900": "Antes de 1900",
|
||||
"After 1945": "Depois de 1945",
|
||||
"Date unknown": "Data desconhecida",
|
||||
"Position: centre of the protected area": "Posição: centro da área protegida",
|
||||
"Position approximate (within about {km} km)": "Posição aproximada (margem de cerca de {km} km)",
|
||||
"Position surveyed (within about {m} m)": "Posição levantada (margem de cerca de {m} m)",
|
||||
"Vessel: {value}": "Embarcação: {value}",
|
||||
"What happened: {value}": "O que aconteceu: {value}",
|
||||
"Depth: {m} m ({quality})": "Profundidade: {m} m ({quality})",
|
||||
"Depth: {m} m": "Profundidade: {m} m",
|
||||
"Notes: {value}": "Notas: {value}",
|
||||
"Cargo or finds: {value}": "Carga ou achados: {value}",
|
||||
"Protected wreck": "Naufrágio protegido",
|
||||
"Source: {value}": "Fonte: {value}",
|
||||
"Click the card to open EMODnet ↗": "Clique na ficha para abrir o EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Clique na ficha para abrir a fonte ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata indisponível; mostrando só o EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet indisponível; mostrando só o Wikidata",
|
||||
"Shipwrecks unavailable": "Naufrágios indisponíveis",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (águas europeias) · Wikidata (mundo)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} naufrágio",
|
||||
"many": "{count} de naufrágios",
|
||||
"other": "{count} naufrágios"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Naufrágio",
|
||||
"Fatalities: {count}": "Mortos: {count}",
|
||||
"Survivors: {count}": "Sobreviventes: {count}",
|
||||
"Click the card to open the article ↗": "Clique na ficha para abrir o artigo ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Os naufrágios históricos europeus vêm do EMODnet Human Activities; os naufrágios notáveis do mundo vêm do Wikidata. A cor mostra quando o navio afundou; o marcador cresce com o número de mortos. Clique num marcador para ver a ficha.",
|
||||
"All years": "Todos os anos",
|
||||
"Period": "Período",
|
||||
"From": "Início",
|
||||
"To": "Fim",
|
||||
"First year of the shipwreck period": "Primeiro ano do período dos naufrágios",
|
||||
"Last year of the shipwreck period": "Último ano do período dos naufrágios",
|
||||
"SIGHTING": "AVISTAMENTO",
|
||||
"Show {name} sighting": "Mostrar avistamento de {name}",
|
||||
"seen {age} ago": "visto há {age}",
|
||||
|
||||
+151
-3
@@ -1,4 +1,97 @@
|
||||
{
|
||||
"News feed unavailable": "Лента новостей недоступна",
|
||||
"Developing: {name}": "Развивается: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} событие сегодня",
|
||||
"few": "{count} события сегодня",
|
||||
"many": "{count} событий сегодня",
|
||||
"other": "{count} события сегодня"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} сообщение сегодня",
|
||||
"few": "{count} сообщения сегодня",
|
||||
"many": "{count} сообщений сегодня",
|
||||
"other": "{count} сообщения сегодня"
|
||||
},
|
||||
"Disputed: {name}": "Спорная территория: {name}",
|
||||
"Video": "Видео",
|
||||
"Photos": "Фото",
|
||||
"Claimed by {who}": "Заявление: {who}",
|
||||
"Claimed": "Заявление",
|
||||
"Not yet confirmed by others": "Пока не подтверждено другими",
|
||||
"Reported by {side} sources": "Сообщают источники {side}",
|
||||
"Reported by {sides}": "Сообщают: {sides}",
|
||||
"{side} sources": "источники {side}",
|
||||
"Official": "Официально",
|
||||
"Reported by both sides": "Сообщают обе стороны",
|
||||
"Independently reported": "Подтверждено независимыми источниками",
|
||||
"Single source": "Один источник",
|
||||
"International": "Международные",
|
||||
"Independent": "Независимые",
|
||||
"Unattributed": "Без атрибуции",
|
||||
"Outside party": "Внешняя сторона",
|
||||
"Ukraine–Russia": "Украина–Россия",
|
||||
"Israel–Gaza–Lebanon": "Израиль–Газа–Ливан",
|
||||
"Iran–Hormuz": "Иран–Ормуз",
|
||||
"Yemen–Red Sea": "Йемен–Красное море",
|
||||
"Sudan": "Судан",
|
||||
"Sahel": "Сахель",
|
||||
"Elsewhere": "Другие места",
|
||||
"Strike": "Удар",
|
||||
"Alert": "Тревога",
|
||||
"Air defence": "ПВО",
|
||||
"Ground fighting": "Наземные бои",
|
||||
"Casualties": "Жертвы",
|
||||
"Humanitarian": "Гуманитарное",
|
||||
"Disaster": "Бедствие",
|
||||
"Protest": "Протест",
|
||||
"Political": "Политика",
|
||||
"No physical event": "Без физического события",
|
||||
"Minor incident": "Незначительный инцидент",
|
||||
"Significant": "Значительный",
|
||||
"Major": "Крупный",
|
||||
"age|now": "сейчас",
|
||||
"{minutes} min": "{minutes} мин",
|
||||
"{hours} h": "{hours} ч",
|
||||
"{count} sources": {
|
||||
"one": "{count} источник",
|
||||
"few": "{count} источника",
|
||||
"many": "{count} источников",
|
||||
"other": "{count} источника"
|
||||
},
|
||||
"News feed not configured on this server": "Лента новостей не настроена на этом сервере",
|
||||
"Malformed news hotspots response": "Некорректный ответ горячих точек новостей",
|
||||
"Malformed news feed response": "Некорректный ответ ленты новостей",
|
||||
"{place} (placed by model)": "{place} (место определила модель)",
|
||||
"English headline by the model": "Английский заголовок от модели",
|
||||
"Not placed on the map": "Не отмечено на карте",
|
||||
"Close": "Закрыть",
|
||||
"Any severity": "Любая тяжесть",
|
||||
"{severity} and above": "{severity} и выше",
|
||||
"{severity} only": "Только {severity}",
|
||||
"All categories": "Все категории",
|
||||
"Reading the news…": "Читаем новости…",
|
||||
"News, last {hours} hours": "Новости за последние {hours} ч",
|
||||
"Last {hours} h": "За {hours} ч",
|
||||
"Time window": "Период",
|
||||
"Conflicts": "Конфликты",
|
||||
"Local": "Местные",
|
||||
"News sections": "Разделы новостей",
|
||||
"Zoom in to see local news": "Приблизьте карту, чтобы увидеть местные новости",
|
||||
"Hotspots": "Горячие точки",
|
||||
"Severity": "Тяжесть",
|
||||
"Category": "Категория",
|
||||
"Nothing reported near here in the last {hours} h": "За последние {hours} ч поблизости ничего не сообщалось",
|
||||
"Latest news": "Последние новости",
|
||||
"No news matches these filters in the last {hours} h": "За последние {hours} ч нет новостей по этим фильтрам",
|
||||
"Load older news": "Загрузить более ранние новости",
|
||||
"How to read the map": "Как читать карту",
|
||||
"Colour: severity · icon: type of event": "Цвет: тяжесть · значок: тип события",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Сплошной обод: сообщают обе стороны или независимые источники. Пунктирный обод: заявление. Тонкий обод: один источник или пресса одной стороны.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Крупнее: больше источников · бледнее: старше. Карточка с фото: крупное или быстро растущее событие от двух и более источников.",
|
||||
"Side labels describe the source, not whether a report is true.": "Метки сторон описывают источник, а не достоверность сообщения.",
|
||||
"Exit cockpit to fly to a news report": "Выйдите из кабины, чтобы перелететь к сообщению",
|
||||
"News items in the feed": "Новостей в ленте",
|
||||
"Flying to Austin, TX...": "Перелёт в Остин, Техас...",
|
||||
"Restoring shared view...": "Восстановление общего вида...",
|
||||
"Initializing systems...": "Инициализация систем...",
|
||||
@@ -400,10 +493,11 @@
|
||||
"OVERCAST": "ПАСМУРНО",
|
||||
"ACQUIRING REGIONAL NEWS": "ЗАГРУЗКА РЕГИОНАЛЬНЫХ НОВОСТЕЙ",
|
||||
"REGIONAL NEWS UNAVAILABLE": "РЕГИОНАЛЬНЫЕ НОВОСТИ НЕДОСТУПНЫ",
|
||||
"CACHED · REFRESH FAILED": "КЭШ · ОБНОВЛЕНИЕ НЕ УДАЛОСЬ",
|
||||
"RESOLVING REGION": "ОПРЕДЕЛЕНИЕ РЕГИОНА",
|
||||
"REGION UNAVAILABLE": "РЕГИОН НЕДОСТУПЕН",
|
||||
"FOG": "ТУМАН",
|
||||
"NO RECENT LOCATION MATCHES": "НЕТ СВЕЖИХ СОВПАДЕНИЙ ПО МЕСТУ",
|
||||
"NO NEWS IN THE LAST {hours} H": "НЕТ НОВОСТЕЙ ЗА {hours} Ч",
|
||||
"DRIZZLE": "МОРОСЬ",
|
||||
"RAIN": "ДОЖДЬ",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
@@ -415,7 +509,7 @@
|
||||
"CLOUD {pct}%": "ОБЛАЧНОСТЬ {pct}%",
|
||||
"CLOUD UNKNOWN": "ОБЛАЧНОСТЬ НЕИЗВЕСТНА",
|
||||
"MIXED CONDITIONS": "СМЕШАННЫЕ УСЛОВИЯ",
|
||||
"{source} · LOCATION QUERY": "{source} · ЗАПРОС ПО МЕСТУ",
|
||||
"{source} · CACHED {age}": "{source} · КЭШ {age}",
|
||||
"REGIONAL NEWS": "НОВОСТИ РЕГИОНА",
|
||||
"CYCLE ON": "АВТО: ВКЛ",
|
||||
"CYCLE OFF": "АВТО: ВЫКЛ",
|
||||
@@ -2042,7 +2136,7 @@
|
||||
"MILITARY FEED OFF · PARTIAL PICTURE": "ВОЕННЫЙ ПОТОК ВЫКЛ · КАРТИНА НЕПОЛНАЯ",
|
||||
"FLIGHTS FEED OFF · PARTIAL PICTURE": "ПОТОК РЕЙСОВ ВЫКЛ · КАРТИНА НЕПОЛНАЯ",
|
||||
"NEARBY AIRCRAFT INCOMPLETE · NOT AN ALL-CLEAR": "БЛИЖНИЕ ВОЗДУШНЫЕ СУДА: ДАННЫЕ НЕПОЛНЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · ЗАПРОС ПО МЕСТУ · НЕДАВНИЕ",
|
||||
"{source} · LAST {hours} H": "{source} · ЗА {hours} Ч",
|
||||
"ft": "фт",
|
||||
"kts": "уз",
|
||||
"PAUSE": "ПАУЗА",
|
||||
@@ -3359,6 +3453,60 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Слишком много запросов в чате. Повторите попытку через {seconds} с.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "Провайдер отказал этому ключу в доступе. Проверьте проект, регион или разрешения ключа.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашем счёте у провайдера закончились средства. Проверьте оплату или выберите другого провайдера ИИ в настройках.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Новости за последние 24 ч. Каждое сообщение ведёт к своему изданию; места и категории определяются по тексту и данным автоматически и могут быть ошибочны. Метки сторон, где они есть, описывают источник, а не достоверность сообщения.",
|
||||
"Economy": "Экономика",
|
||||
"News from {area}": "Новости: {area}",
|
||||
"Within {km} km of the view centre": "В радиусе {km} км от центра карты",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "через {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Местное в слое новостей: новости дня от СМИ страны в кадре",
|
||||
"{provider} refused its key": "{provider} отклонил ключ",
|
||||
"Check {envVars} in Provider Settings": "Проверьте {envVars} в «Настройках провайдеров»",
|
||||
"{provider} key required": "Нужен ключ {provider}",
|
||||
"{provider} limit reached for today": "{provider}: дневной лимит исчерпан",
|
||||
"News resumes tomorrow, or with a paid plan": "Новости вернутся завтра или с платным тарифом",
|
||||
"News key required": "Нужен ключ новостей",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Точные точки конфликтов в слое новостей, вдобавок к статьям GDELT",
|
||||
"Worldwide": "Весь мир",
|
||||
"Shipwrecks": "Кораблекрушения",
|
||||
"Before 1900": "До 1900",
|
||||
"After 1945": "После 1945",
|
||||
"Date unknown": "Дата неизвестна",
|
||||
"Position: centre of the protected area": "Положение: центр охраняемой зоны",
|
||||
"Position approximate (within about {km} km)": "Положение приблизительное (точность около {km} км)",
|
||||
"Position surveyed (within about {m} m)": "Положение измерено (точность около {m} м)",
|
||||
"Vessel: {value}": "Судно: {value}",
|
||||
"What happened: {value}": "Что произошло: {value}",
|
||||
"Depth: {m} m ({quality})": "Глубина: {m} м ({quality})",
|
||||
"Depth: {m} m": "Глубина: {m} м",
|
||||
"Notes: {value}": "Примечания: {value}",
|
||||
"Cargo or finds: {value}": "Груз или находки: {value}",
|
||||
"Protected wreck": "Охраняемый объект",
|
||||
"Source: {value}": "Источник: {value}",
|
||||
"Click the card to open EMODnet ↗": "Нажмите на карточку, чтобы открыть EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Нажмите на карточку, чтобы открыть источник ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показан только EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet недоступен; показана только Wikidata",
|
||||
"Shipwrecks unavailable": "Данные о кораблекрушениях недоступны",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (воды Европы) · Wikidata (весь мир)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} затонувшее судно",
|
||||
"few": "{count} затонувших судна",
|
||||
"many": "{count} затонувших судов",
|
||||
"other": "{count} затонувшего судна"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Кораблекрушение",
|
||||
"Fatalities: {count}": "Погибших: {count}",
|
||||
"Survivors: {count}": "Выживших: {count}",
|
||||
"Click the card to open the article ↗": "Нажмите на карточку, чтобы открыть статью ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Исторические затонувшие суда Европы — из EMODnet Human Activities, известные кораблекрушения по всему миру — из Wikidata. Цвет показывает, когда судно затонуло; маркер растёт с числом погибших. Нажмите на маркер, чтобы открыть карточку.",
|
||||
"All years": "Все годы",
|
||||
"Period": "Период",
|
||||
"From": "С",
|
||||
"To": "По",
|
||||
"First year of the shipwreck period": "Первый год периода кораблекрушений",
|
||||
"Last year of the shipwreck period": "Последний год периода кораблекрушений",
|
||||
"SIGHTING": "НАБЛЮДЕНИЕ",
|
||||
"Show {name} sighting": "Показать наблюдение: {name}",
|
||||
"seen {age} ago": "замечено {age} назад",
|
||||
|
||||
+151
-3
@@ -1,4 +1,97 @@
|
||||
{
|
||||
"News feed unavailable": "Стрічка новин недоступна",
|
||||
"Developing: {name}": "Розвивається: {name}",
|
||||
"{count} events today": {
|
||||
"one": "{count} подія сьогодні",
|
||||
"few": "{count} події сьогодні",
|
||||
"many": "{count} подій сьогодні",
|
||||
"other": "{count} події сьогодні"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"one": "{count} повідомлення сьогодні",
|
||||
"few": "{count} повідомлення сьогодні",
|
||||
"many": "{count} повідомлень сьогодні",
|
||||
"other": "{count} повідомлення сьогодні"
|
||||
},
|
||||
"Disputed: {name}": "Спірна територія: {name}",
|
||||
"Video": "Відео",
|
||||
"Photos": "Фото",
|
||||
"Claimed by {who}": "Заява: {who}",
|
||||
"Claimed": "Заява",
|
||||
"Not yet confirmed by others": "Поки не підтверджено іншими",
|
||||
"Reported by {side} sources": "Повідомляють джерела {side}",
|
||||
"Reported by {sides}": "Повідомляють: {sides}",
|
||||
"{side} sources": "джерела {side}",
|
||||
"Official": "Офіційно",
|
||||
"Reported by both sides": "Повідомляють обидві сторони",
|
||||
"Independently reported": "Підтверджено незалежними джерелами",
|
||||
"Single source": "Одне джерело",
|
||||
"International": "Міжнародні",
|
||||
"Independent": "Незалежні",
|
||||
"Unattributed": "Без атрибуції",
|
||||
"Outside party": "Зовнішня сторона",
|
||||
"Ukraine–Russia": "Україна–Росія",
|
||||
"Israel–Gaza–Lebanon": "Ізраїль–Газа–Ліван",
|
||||
"Iran–Hormuz": "Іран–Ормуз",
|
||||
"Yemen–Red Sea": "Ємен–Червоне море",
|
||||
"Sudan": "Судан",
|
||||
"Sahel": "Сахель",
|
||||
"Elsewhere": "Інші місця",
|
||||
"Strike": "Удар",
|
||||
"Alert": "Тривога",
|
||||
"Air defence": "ППО",
|
||||
"Ground fighting": "Наземні бої",
|
||||
"Casualties": "Жертви",
|
||||
"Humanitarian": "Гуманітарне",
|
||||
"Disaster": "Лихо",
|
||||
"Protest": "Протест",
|
||||
"Political": "Політика",
|
||||
"No physical event": "Без фізичної події",
|
||||
"Minor incident": "Незначний інцидент",
|
||||
"Significant": "Значний",
|
||||
"Major": "Великий",
|
||||
"age|now": "зараз",
|
||||
"{minutes} min": "{minutes} хв",
|
||||
"{hours} h": "{hours} год",
|
||||
"{count} sources": {
|
||||
"one": "{count} джерело",
|
||||
"few": "{count} джерела",
|
||||
"many": "{count} джерел",
|
||||
"other": "{count} джерела"
|
||||
},
|
||||
"News feed not configured on this server": "Стрічку новин не налаштовано на цьому сервері",
|
||||
"Malformed news hotspots response": "Некоректна відповідь гарячих точок новин",
|
||||
"Malformed news feed response": "Некоректна відповідь стрічки новин",
|
||||
"{place} (placed by model)": "{place} (місце визначила модель)",
|
||||
"English headline by the model": "Англійський заголовок від моделі",
|
||||
"Not placed on the map": "Не позначено на мапі",
|
||||
"Close": "Закрити",
|
||||
"Any severity": "Будь-яка тяжкість",
|
||||
"{severity} and above": "{severity} і вище",
|
||||
"{severity} only": "Лише {severity}",
|
||||
"All categories": "Усі категорії",
|
||||
"Reading the news…": "Читаємо новини…",
|
||||
"News, last {hours} hours": "Новини за останні {hours} год",
|
||||
"Last {hours} h": "За {hours} год",
|
||||
"Time window": "Період",
|
||||
"Conflicts": "Конфлікти",
|
||||
"Local": "Місцеві",
|
||||
"News sections": "Розділи новин",
|
||||
"Zoom in to see local news": "Наблизьте мапу, щоб побачити місцеві новини",
|
||||
"Hotspots": "Гарячі точки",
|
||||
"Severity": "Тяжкість",
|
||||
"Category": "Категорія",
|
||||
"Nothing reported near here in the last {hours} h": "За останні {hours} год поблизу нічого не повідомлялося",
|
||||
"Latest news": "Останні новини",
|
||||
"No news matches these filters in the last {hours} h": "За останні {hours} год немає новин за цими фільтрами",
|
||||
"Load older news": "Завантажити давніші новини",
|
||||
"How to read the map": "Як читати мапу",
|
||||
"Colour: severity · icon: type of event": "Колір: тяжкість · значок: тип події",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "Суцільний обідок: повідомляють обидві сторони або незалежні джерела. Пунктирний обідок: заява. Тонкий обідок: одне джерело або преса однієї сторони.",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "Більше: більше джерел · блідіше: давніше. Картка з фото: велика або швидко зростаюча подія з двох і більше джерел.",
|
||||
"Side labels describe the source, not whether a report is true.": "Позначки сторін описують джерело, а не правдивість повідомлення.",
|
||||
"Exit cockpit to fly to a news report": "Вийдіть із кабіни, щоб перелетіти до повідомлення",
|
||||
"News items in the feed": "Новин у стрічці",
|
||||
"Pick a shape, then click the map.": "Виберіть фігуру й клацніть на карті.",
|
||||
"Enter to place the pin, Esc to cancel.": "Enter — поставити мітку, Esc — скасувати.",
|
||||
"Click where the pin goes.": "Клацніть там, де має бути мітка.",
|
||||
@@ -1714,14 +1807,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Автоматично гортає сторінки брифінгу кожні 9 секунд (Сигнали → Новини → Місцеві дані). Пауза, доки ви наводите вказівник на панель або вона у фокусі. Дані сигналів у реальному часі однаково оновлюються безперервно.",
|
||||
"ACQUIRING REGIONAL NEWS": "ОТРИМАННЯ РЕГІОНАЛЬНИХ НОВИН",
|
||||
"REGIONAL NEWS UNAVAILABLE": "РЕГІОНАЛЬНІ НОВИНИ НЕДОСТУПНІ",
|
||||
"CACHED · REFRESH FAILED": "КЕШ · ОНОВЛЕННЯ НЕ ВДАЛОСЯ",
|
||||
"RESOLVING REGION": "ВИЗНАЧЕННЯ РЕГІОНУ",
|
||||
"REGION UNAVAILABLE": "РЕГІОН НЕДОСТУПНИЙ",
|
||||
"NO RECENT LOCATION MATCHES": "НЕМАЄ СВІЖИХ ЗБІГІВ ЗА РОЗТАШУВАННЯМ",
|
||||
"NO NEWS IN THE LAST {hours} H": "НЕМАЄ НОВИН ЗА {hours} ГОД",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} КМ/ГОД",
|
||||
"CLOUD {pct}%": "ХМАРНІСТЬ {pct}%",
|
||||
"CLOUD UNKNOWN": "ХМАРНІСТЬ НЕВІДОМА",
|
||||
"{source} · LOCATION QUERY": "{source} · ЗАПИТ ЗА РОЗТАШУВАННЯМ",
|
||||
"{source} · CACHED {age}": "{source} · КЕШ {age}",
|
||||
"REGIONAL NEWS": "РЕГІОНАЛЬНІ НОВИНИ",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · РЕЙСИ / СУДНА · РАДІУС {radius}",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · ОБʼЄКТИ: {coverage}",
|
||||
@@ -1788,7 +1882,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "СПОСТЕРЕЖЕНІ / НАНЕСЕНІ КОНТАКТИ",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "ПОДІЇ ПІДТВЕРДЖЕНІ ДЖЕРЕЛАМИ · БЕЗ ІМІТОВАНИХ НОВИН",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "ОСТАННІ ПУБЛІКАЦІЇ ЗА РОЗТАШУВАННЯМ",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · ЗАПИТ ЗА РОЗТАШУВАННЯМ · НЕЩОДАВНІ",
|
||||
"{source} · LAST {hours} H": "{source} · ЗА {hours} ГОД",
|
||||
"LOCAL INFO": "МІСЦЕВІ ДАНІ",
|
||||
"PLACE / CONDITIONS / POSITION": "МІСЦЕ / УМОВИ / ПОЗИЦІЯ",
|
||||
"TIME UNKNOWN": "ЧАС НЕВІДОМИЙ",
|
||||
@@ -3359,6 +3453,60 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "Забагато запитів до чату. Спробуйте ще раз через {seconds} с.",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "Постачальник відмовив цьому ключу в доступі. Перевірте проєкт, регіон або дозволи ключа.",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "На вашому рахунку в постачальника закінчилися кошти. Перевірте оплату або виберіть іншого постачальника ШІ в налаштуваннях.",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "Новини за останні 24 год. Кожне повідомлення веде до свого видання; місця й категорії визначаються з тексту й даних автоматично і можуть бути хибними. Позначки сторін, де вони є, описують джерело, а не правдивість повідомлення.",
|
||||
"Economy": "Економіка",
|
||||
"News from {area}": "Новини: {area}",
|
||||
"Within {km} km of the view centre": "У радіусі {km} км від центру мапи",
|
||||
"{region}, {country}": "{region}, {country}",
|
||||
"via {source}": "через {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "Місцеве в шарі новин: новини дня від медіа країни в кадрі",
|
||||
"{provider} refused its key": "{provider} відхилив ключ",
|
||||
"Check {envVars} in Provider Settings": "Перевірте {envVars} у «Налаштуваннях постачальників»",
|
||||
"{provider} key required": "Потрібен ключ {provider}",
|
||||
"{provider} limit reached for today": "{provider}: денний ліміт вичерпано",
|
||||
"News resumes tomorrow, or with a paid plan": "Новини повернуться завтра або з платним тарифом",
|
||||
"News key required": "Потрібен ключ новин",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "Точні точки конфліктів у шарі новин, на додачу до статей GDELT",
|
||||
"Worldwide": "Увесь світ",
|
||||
"Shipwrecks": "Корабельні аварії",
|
||||
"Before 1900": "До 1900",
|
||||
"After 1945": "Після 1945",
|
||||
"Date unknown": "Дата невідома",
|
||||
"Position: centre of the protected area": "Положення: центр охоронної зони",
|
||||
"Position approximate (within about {km} km)": "Положення приблизне (точність близько {km} км)",
|
||||
"Position surveyed (within about {m} m)": "Положення виміряно (точність близько {m} м)",
|
||||
"Vessel: {value}": "Судно: {value}",
|
||||
"What happened: {value}": "Що сталося: {value}",
|
||||
"Depth: {m} m ({quality})": "Глибина: {m} м ({quality})",
|
||||
"Depth: {m} m": "Глибина: {m} м",
|
||||
"Notes: {value}": "Примітки: {value}",
|
||||
"Cargo or finds: {value}": "Вантаж або знахідки: {value}",
|
||||
"Protected wreck": "Охоронюваний об'єкт",
|
||||
"Source: {value}": "Джерело: {value}",
|
||||
"Click the card to open EMODnet ↗": "Натисніть картку, щоб відкрити EMODnet ↗",
|
||||
"Click the card to open the source ↗": "Натисніть картку, щоб відкрити джерело ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показано лише EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet недоступний; показано лише Wikidata",
|
||||
"Shipwrecks unavailable": "Дані про корабельні аварії недоступні",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet (води Європи) · Wikidata (увесь світ)",
|
||||
"{count} wrecks": {
|
||||
"one": "{count} затонуле судно",
|
||||
"few": "{count} затонулі судна",
|
||||
"many": "{count} затонулих суден",
|
||||
"other": "{count} затонулого судна"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "Корабельна аварія",
|
||||
"Fatalities: {count}": "Загиблих: {count}",
|
||||
"Survivors: {count}": "Тих, хто вижив: {count}",
|
||||
"Click the card to open the article ↗": "Натисніть картку, щоб відкрити статтю ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "Історичні затонулі судна Європи — з EMODnet Human Activities, відомі корабельні аварії світу — з Wikidata. Колір показує, коли судно затонуло; маркер збільшується з кількістю загиблих. Натисніть маркер, щоб відкрити картку.",
|
||||
"All years": "Усі роки",
|
||||
"Period": "Період",
|
||||
"From": "З",
|
||||
"To": "По",
|
||||
"First year of the shipwreck period": "Перший рік періоду корабельних аварій",
|
||||
"Last year of the shipwreck period": "Останній рік періоду корабельних аварій",
|
||||
"SIGHTING": "СПОСТЕРЕЖЕННЯ",
|
||||
"Show {name} sighting": "Показати спостереження: {name}",
|
||||
"seen {age} ago": "помічено {age} тому",
|
||||
|
||||
+139
-3
@@ -1,4 +1,88 @@
|
||||
{
|
||||
"News feed unavailable": "新闻源不可用",
|
||||
"Developing: {name}": "事态发展:{name}",
|
||||
"{count} events today": {
|
||||
"other": "今日 {count} 起事件"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"other": "今日 {count} 条报道"
|
||||
},
|
||||
"Disputed: {name}": "争议地区:{name}",
|
||||
"Video": "视频",
|
||||
"Photos": "照片",
|
||||
"Claimed by {who}": "{who}声称",
|
||||
"Claimed": "声称",
|
||||
"Not yet confirmed by others": "尚未获他方证实",
|
||||
"Reported by {side} sources": "{side}方来源报道",
|
||||
"Reported by {sides}": "报道来源:{sides}",
|
||||
"{side} sources": "{side}方来源",
|
||||
"Official": "官方",
|
||||
"Reported by both sides": "双方均有报道",
|
||||
"Independently reported": "有独立来源报道",
|
||||
"Single source": "单一来源",
|
||||
"International": "国际",
|
||||
"Independent": "独立",
|
||||
"Unattributed": "未注明来源",
|
||||
"Outside party": "外部方",
|
||||
"Ukraine–Russia": "乌克兰–俄罗斯",
|
||||
"Israel–Gaza–Lebanon": "以色列–加沙–黎巴嫩",
|
||||
"Iran–Hormuz": "伊朗–霍尔木兹",
|
||||
"Yemen–Red Sea": "也门–红海",
|
||||
"Sudan": "苏丹",
|
||||
"Sahel": "萨赫勒",
|
||||
"Elsewhere": "其他地区",
|
||||
"Strike": "打击",
|
||||
"Alert": "警报",
|
||||
"Air defence": "防空",
|
||||
"Ground fighting": "地面战斗",
|
||||
"Casualties": "伤亡",
|
||||
"Humanitarian": "人道",
|
||||
"Disaster": "灾害",
|
||||
"Protest": "抗议",
|
||||
"Political": "政治",
|
||||
"No physical event": "无实际事件",
|
||||
"Minor incident": "轻微事件",
|
||||
"Significant": "重大",
|
||||
"Major": "严重",
|
||||
"age|now": "刚刚",
|
||||
"{minutes} min": "{minutes} 分钟",
|
||||
"{hours} h": "{hours} 小时",
|
||||
"{count} sources": {
|
||||
"other": "{count} 个来源"
|
||||
},
|
||||
"News feed not configured on this server": "此服务器未配置新闻源",
|
||||
"Malformed news hotspots response": "新闻热点响应格式错误",
|
||||
"Malformed news feed response": "新闻源响应格式错误",
|
||||
"{place} (placed by model)": "{place}(由模型定位)",
|
||||
"English headline by the model": "模型生成的英文标题",
|
||||
"Not placed on the map": "未在地图上标出",
|
||||
"Close": "关闭",
|
||||
"Any severity": "任意严重程度",
|
||||
"{severity} and above": "{severity}及以上",
|
||||
"{severity} only": "仅{severity}",
|
||||
"All categories": "所有类别",
|
||||
"Reading the news…": "正在读取新闻…",
|
||||
"News, last {hours} hours": "最近 {hours} 小时的新闻",
|
||||
"Last {hours} h": "最近 {hours} 小时",
|
||||
"Time window": "时间范围",
|
||||
"Conflicts": "冲突",
|
||||
"Local": "本地",
|
||||
"News sections": "新闻分区",
|
||||
"Zoom in to see local news": "放大地图以查看本地新闻",
|
||||
"Hotspots": "热点",
|
||||
"Severity": "严重程度",
|
||||
"Category": "类别",
|
||||
"Nothing reported near here in the last {hours} h": "最近 {hours} 小时附近无报道",
|
||||
"Latest news": "最新新闻",
|
||||
"No news matches these filters in the last {hours} h": "最近 {hours} 小时没有符合这些筛选条件的新闻",
|
||||
"Load older news": "加载更早的新闻",
|
||||
"How to read the map": "如何解读地图",
|
||||
"Colour: severity · icon: type of event": "颜色:严重程度 · 图标:事件类型",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "实线边框:双方或独立来源均有报道。虚线边框:一方声称。细边框:单一来源,或一方自身的媒体。",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "越大:来源越多 · 越淡:越早。图片卡片:有两个或以上来源的严重或快速发展的事件。",
|
||||
"Side labels describe the source, not whether a report is true.": "阵营标签描述的是来源,而非报道是否属实。",
|
||||
"Exit cockpit to fly to a news report": "退出驾驶舱以飞往新闻报道",
|
||||
"News items in the feed": "列表中的新闻数",
|
||||
"Pick a shape, then click the map.": "先选择形状,再在地图上点击。",
|
||||
"Enter to place the pin, Esc to cancel.": "按 Enter 放置图钉,按 Esc 取消。",
|
||||
"Click where the pin goes.": "点击图钉的放置位置。",
|
||||
@@ -1619,14 +1703,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "每 9 秒自动轮换简报页面(信号 → 新闻 → 本地)。悬停或聚焦面板时暂停。无论是否轮换,实时信号数据都会持续刷新。",
|
||||
"ACQUIRING REGIONAL NEWS": "正在获取地区新闻",
|
||||
"REGIONAL NEWS UNAVAILABLE": "地区新闻不可用",
|
||||
"CACHED · REFRESH FAILED": "缓存 · 刷新失败",
|
||||
"RESOLVING REGION": "正在解析区域",
|
||||
"REGION UNAVAILABLE": "区域不可用",
|
||||
"NO RECENT LOCATION MATCHES": "暂无近期位置匹配结果",
|
||||
"NO NEWS IN THE LAST {hours} H": "过去 {hours} 小时无新闻",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} km/h",
|
||||
"CLOUD {pct}%": "云量 {pct}%",
|
||||
"CLOUD UNKNOWN": "云量未知",
|
||||
"{source} · LOCATION QUERY": "{source} · 位置查询",
|
||||
"{source} · CACHED {age}": "{source} · 缓存 {age}",
|
||||
"REGIONAL NEWS": "地区新闻",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · {radius} 空/海监视窗口",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · 设施 {coverage}",
|
||||
@@ -1690,7 +1775,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "观测 / 地图标注目标",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "来源可查的事件 · 无合成新闻",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "当前地区最新报道",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · 位置查询 · 近期",
|
||||
"{source} · LAST {hours} H": "{source} · 过去 {hours} 小时",
|
||||
"LOCAL INFO": "本地信息",
|
||||
"PLACE / CONDITIONS / POSITION": "地点 / 状况 / 位置",
|
||||
"TIME UNKNOWN": "时间未知",
|
||||
@@ -3128,6 +3213,57 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "聊天请求过多。请在 {seconds} 秒后重试。",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "服务商拒绝了此密钥的访问请求。请检查该密钥所属的项目、区域或权限。",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服务商账户余额不足。请检查账户的计费信息,或在设置中选择其他 AI 服务商。",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "最近 24 小时的新闻。每条报道都链接到其发布者;地点和类别由文本和数据自动读取,可能有误。阵营标签(如有显示)描述的是来源,而非报道是否属实。",
|
||||
"Economy": "经济",
|
||||
"News from {area}": "{area}新闻",
|
||||
"Within {km} km of the view centre": "视图中心 {km} 公里范围内",
|
||||
"{region}, {country}": "{country}{region}",
|
||||
"via {source}": "来自 {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "新闻图层的本地:视野中国家的媒体当天的新闻",
|
||||
"{provider} refused its key": "{provider} 拒绝了密钥",
|
||||
"Check {envVars} in Provider Settings": "请在服务商设置中检查 {envVars}",
|
||||
"{provider} key required": "需要 {provider} 密钥",
|
||||
"{provider} limit reached for today": "{provider} 已达今日上限",
|
||||
"News resumes tomorrow, or with a paid plan": "新闻将于明天恢复,或升级付费套餐",
|
||||
"News key required": "需要新闻密钥",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "新闻图层中精确的冲突地点,与 GDELT 的文章并列",
|
||||
"Worldwide": "全球",
|
||||
"Shipwrecks": "沉船",
|
||||
"Before 1900": "1900年以前",
|
||||
"After 1945": "1945年以后",
|
||||
"Date unknown": "日期不详",
|
||||
"Position: centre of the protected area": "位置:保护区中心",
|
||||
"Position approximate (within about {km} km)": "大致位置(误差约 {km} 公里)",
|
||||
"Position surveyed (within about {m} m)": "实测位置(误差约 {m} 米)",
|
||||
"Vessel: {value}": "船只:{value}",
|
||||
"What happened: {value}": "经过:{value}",
|
||||
"Depth: {m} m ({quality})": "深度:{m} 米({quality})",
|
||||
"Depth: {m} m": "深度:{m} 米",
|
||||
"Notes: {value}": "备注:{value}",
|
||||
"Cargo or finds: {value}": "货物或出水文物:{value}",
|
||||
"Protected wreck": "受保护沉船",
|
||||
"Source: {value}": "来源:{value}",
|
||||
"Click the card to open EMODnet ↗": "点击卡片打开 EMODnet ↗",
|
||||
"Click the card to open the source ↗": "点击卡片打开来源 ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;仅显示 EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;仅显示 Wikidata",
|
||||
"Shipwrecks unavailable": "沉船数据不可用",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(欧洲海域)· Wikidata(全球)",
|
||||
"{count} wrecks": {
|
||||
"other": "{count} 艘沉船"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "沉船",
|
||||
"Fatalities: {count}": "遇难:{count}",
|
||||
"Survivors: {count}": "幸存者:{count}",
|
||||
"Click the card to open the article ↗": "点击卡片打开文章 ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "欧洲历史沉船来自 EMODnet Human Activities;全球知名沉船来自 Wikidata。颜色表示船只沉没的时期,标记大小随遇难人数增加。点击标记查看卡片。",
|
||||
"All years": "所有年份",
|
||||
"Period": "时段",
|
||||
"From": "起",
|
||||
"To": "止",
|
||||
"First year of the shipwreck period": "沉船时段的起始年份",
|
||||
"Last year of the shipwreck period": "沉船时段的结束年份",
|
||||
"SIGHTING": "目击",
|
||||
"Show {name} sighting": "显示{name}目击",
|
||||
"seen {age} ago": "{age}前目击",
|
||||
|
||||
@@ -1,4 +1,88 @@
|
||||
{
|
||||
"News feed unavailable": "新聞來源無法使用",
|
||||
"Developing: {name}": "事態發展:{name}",
|
||||
"{count} events today": {
|
||||
"other": "今日 {count} 起事件"
|
||||
},
|
||||
"{count} reports today": {
|
||||
"other": "今日 {count} 則報導"
|
||||
},
|
||||
"Disputed: {name}": "爭議地區:{name}",
|
||||
"Video": "影片",
|
||||
"Photos": "照片",
|
||||
"Claimed by {who}": "{who}聲稱",
|
||||
"Claimed": "聲稱",
|
||||
"Not yet confirmed by others": "尚未獲他方證實",
|
||||
"Reported by {side} sources": "{side}方來源報導",
|
||||
"Reported by {sides}": "報導來源:{sides}",
|
||||
"{side} sources": "{side}方來源",
|
||||
"Official": "官方",
|
||||
"Reported by both sides": "雙方均有報導",
|
||||
"Independently reported": "有獨立來源報導",
|
||||
"Single source": "單一來源",
|
||||
"International": "國際",
|
||||
"Independent": "獨立",
|
||||
"Unattributed": "未註明來源",
|
||||
"Outside party": "外部方",
|
||||
"Ukraine–Russia": "烏克蘭–俄羅斯",
|
||||
"Israel–Gaza–Lebanon": "以色列–加薩–黎巴嫩",
|
||||
"Iran–Hormuz": "伊朗–荷莫茲",
|
||||
"Yemen–Red Sea": "葉門–紅海",
|
||||
"Sudan": "蘇丹",
|
||||
"Sahel": "薩赫爾",
|
||||
"Elsewhere": "其他地區",
|
||||
"Strike": "打擊",
|
||||
"Alert": "警報",
|
||||
"Air defence": "防空",
|
||||
"Ground fighting": "地面戰鬥",
|
||||
"Casualties": "傷亡",
|
||||
"Humanitarian": "人道",
|
||||
"Disaster": "災害",
|
||||
"Protest": "抗議",
|
||||
"Political": "政治",
|
||||
"No physical event": "無實際事件",
|
||||
"Minor incident": "輕微事件",
|
||||
"Significant": "重大",
|
||||
"Major": "嚴重",
|
||||
"age|now": "剛剛",
|
||||
"{minutes} min": "{minutes} 分鐘",
|
||||
"{hours} h": "{hours} 小時",
|
||||
"{count} sources": {
|
||||
"other": "{count} 個來源"
|
||||
},
|
||||
"News feed not configured on this server": "此伺服器未設定新聞來源",
|
||||
"Malformed news hotspots response": "新聞熱點回應格式錯誤",
|
||||
"Malformed news feed response": "新聞來源回應格式錯誤",
|
||||
"{place} (placed by model)": "{place}(由模型定位)",
|
||||
"English headline by the model": "模型產生的英文標題",
|
||||
"Not placed on the map": "未在地圖上標出",
|
||||
"Close": "關閉",
|
||||
"Any severity": "任意嚴重程度",
|
||||
"{severity} and above": "{severity}及以上",
|
||||
"{severity} only": "僅{severity}",
|
||||
"All categories": "所有類別",
|
||||
"Reading the news…": "正在讀取新聞…",
|
||||
"News, last {hours} hours": "最近 {hours} 小時的新聞",
|
||||
"Last {hours} h": "最近 {hours} 小時",
|
||||
"Time window": "時間範圍",
|
||||
"Conflicts": "衝突",
|
||||
"Local": "本地",
|
||||
"News sections": "新聞分區",
|
||||
"Zoom in to see local news": "放大地圖以查看本地新聞",
|
||||
"Hotspots": "熱點",
|
||||
"Severity": "嚴重程度",
|
||||
"Category": "類別",
|
||||
"Nothing reported near here in the last {hours} h": "最近 {hours} 小時附近無報導",
|
||||
"Latest news": "最新新聞",
|
||||
"No news matches these filters in the last {hours} h": "最近 {hours} 小時沒有符合這些篩選條件的新聞",
|
||||
"Load older news": "載入更早的新聞",
|
||||
"How to read the map": "如何解讀地圖",
|
||||
"Colour: severity · icon: type of event": "顏色:嚴重程度 · 圖示:事件類型",
|
||||
"Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.": "實線邊框:雙方或獨立來源均有報導。虛線邊框:一方聲稱。細邊框:單一來源,或一方自身的媒體。",
|
||||
"Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.": "越大:來源越多 · 越淡:越早。圖片卡片:有兩個或以上來源的嚴重或快速發展的事件。",
|
||||
"Side labels describe the source, not whether a report is true.": "陣營標籤描述的是來源,而非報導是否屬實。",
|
||||
"Exit cockpit to fly to a news report": "退出駕駛艙以飛往新聞報導",
|
||||
"News items in the feed": "列表中的新聞數",
|
||||
"Pick a shape, then click the map.": "先選擇形狀,再在地圖上點擊。",
|
||||
"Enter to place the pin, Esc to cancel.": "按 Enter 放置圖釘,按 Esc 取消。",
|
||||
"Click where the pin goes.": "點擊圖釘的放置位置。",
|
||||
@@ -1609,14 +1693,15 @@
|
||||
"Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "每 9 秒自動輪換簡報頁面(信號 → 新聞 → 本地)。懸停或聚焦面板時暫停。無論是否輪換,實時信號數據都會持續刷新。",
|
||||
"ACQUIRING REGIONAL NEWS": "正在獲取地區新聞",
|
||||
"REGIONAL NEWS UNAVAILABLE": "地區新聞不可用",
|
||||
"CACHED · REFRESH FAILED": "快取 · 重新整理失敗",
|
||||
"RESOLVING REGION": "正在解析區域",
|
||||
"REGION UNAVAILABLE": "區域不可用",
|
||||
"NO RECENT LOCATION MATCHES": "暫無近期位置匹配結果",
|
||||
"NO NEWS IN THE LAST {hours} H": "過去 {hours} 小時無新聞",
|
||||
"{domain} · {age}": "{domain} · {age}",
|
||||
"{value} KM/H": "{value} km/h",
|
||||
"CLOUD {pct}%": "雲量 {pct}%",
|
||||
"CLOUD UNKNOWN": "雲量未知",
|
||||
"{source} · LOCATION QUERY": "{source} · 位置查詢",
|
||||
"{source} · CACHED {age}": "{source} · 快取 {age}",
|
||||
"REGIONAL NEWS": "地區新聞",
|
||||
"{label} · {radius} AIR/SEA WINDOW": "{label} · {radius} 空/海監視窗口",
|
||||
"{scope} · INSTALLATIONS {coverage}": "{scope} · 設施 {coverage}",
|
||||
@@ -1680,7 +1765,7 @@
|
||||
"OBSERVED / MAPPED PINGS": "觀測 / 地圖標註目標",
|
||||
"SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "來源可查的事件 · 無合成新聞",
|
||||
"LATEST LOCATION-MATCHED REPORTING": "當前地區最新報道",
|
||||
"{source} · LOCATION QUERY · RECENT": "{source} · 位置查詢 · 近期",
|
||||
"{source} · LAST {hours} H": "{source} · 過去 {hours} 小時",
|
||||
"LOCAL INFO": "本地信息",
|
||||
"PLACE / CONDITIONS / POSITION": "地點 / 狀況 / 位置",
|
||||
"TIME UNKNOWN": "時間未知",
|
||||
@@ -3128,6 +3213,57 @@
|
||||
"Too many chat requests. Try again in {seconds} s.": "聊天請求過多。請在 {seconds} 秒後重試。",
|
||||
"The provider refused access for this key. Check the key's project, region or permissions.": "服務商拒絕了此密鑰的訪問請求。請檢查該密鑰所屬的項目、區域或權限。",
|
||||
"The provider account is out of credit. Check its billing, or choose another AI Provider in Settings.": "服務商賬戶餘額不足。請檢查賬戶的計費信息,或在設置中選擇其他 AI 服務商。",
|
||||
"Last 24 h of news. Each report links to its publisher; places and categories are read from the text and data automatically and can be wrong. Side labels, where shown, describe the source, not whether a report is true.": "最近 24 小時的新聞。每則報導都連結至其發布者;地點與類別由文字與資料自動判讀,可能有誤。陣營標籤(如有顯示)描述的是來源,而非報導是否屬實。",
|
||||
"Economy": "經濟",
|
||||
"News from {area}": "{area}新聞",
|
||||
"Within {km} km of the view centre": "視圖中心 {km} 公里範圍內",
|
||||
"{region}, {country}": "{country}{region}",
|
||||
"via {source}": "來自 {source}",
|
||||
"Local in the News layer: the day’s news from the outlets of the country in view": "新聞圖層的本地:視野中國家的媒體當天的新聞",
|
||||
"{provider} refused its key": "{provider} 拒絕了金鑰",
|
||||
"Check {envVars} in Provider Settings": "請在服務商設置中檢查 {envVars}",
|
||||
"{provider} key required": "需要 {provider} 金鑰",
|
||||
"{provider} limit reached for today": "{provider} 已達今日上限",
|
||||
"News resumes tomorrow, or with a paid plan": "新聞將於明天恢復,或升級付費方案",
|
||||
"News key required": "需要新聞金鑰",
|
||||
"Precise conflict points in the News layer, beside GDELT’s articles": "新聞圖層中精確的衝突地點,與 GDELT 的文章並列",
|
||||
"Worldwide": "全球",
|
||||
"Shipwrecks": "沉船",
|
||||
"Before 1900": "1900年以前",
|
||||
"After 1945": "1945年以後",
|
||||
"Date unknown": "日期不詳",
|
||||
"Position: centre of the protected area": "位置:保護區中心",
|
||||
"Position approximate (within about {km} km)": "大致位置(誤差約 {km} 公里)",
|
||||
"Position surveyed (within about {m} m)": "實測位置(誤差約 {m} 公尺)",
|
||||
"Vessel: {value}": "船隻:{value}",
|
||||
"What happened: {value}": "經過:{value}",
|
||||
"Depth: {m} m ({quality})": "深度:{m} 公尺({quality})",
|
||||
"Depth: {m} m": "深度:{m} 公尺",
|
||||
"Notes: {value}": "備註:{value}",
|
||||
"Cargo or finds: {value}": "貨物或出水文物:{value}",
|
||||
"Protected wreck": "受保護沉船",
|
||||
"Source: {value}": "來源:{value}",
|
||||
"Click the card to open EMODnet ↗": "點擊卡片開啟 EMODnet ↗",
|
||||
"Click the card to open the source ↗": "點擊卡片開啟來源 ↗",
|
||||
"Wikidata unavailable; showing EMODnet only": "Wikidata 無法使用;僅顯示 EMODnet",
|
||||
"EMODnet unavailable; showing Wikidata only": "EMODnet 無法使用;僅顯示 Wikidata",
|
||||
"Shipwrecks unavailable": "沉船資料無法使用",
|
||||
"EMODnet (European waters) · Wikidata (worldwide)": "EMODnet(歐洲海域)· Wikidata(全球)",
|
||||
"{count} wrecks": {
|
||||
"other": "{count} 艘沉船"
|
||||
},
|
||||
"1900–1945": "1900–1945",
|
||||
"Shipwreck": "沉船",
|
||||
"Fatalities: {count}": "罹難:{count}",
|
||||
"Survivors: {count}": "倖存者:{count}",
|
||||
"Click the card to open the article ↗": "點擊卡片開啟文章 ↗",
|
||||
"European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.": "歐洲歷史沉船來自 EMODnet Human Activities;全球知名沉船來自 Wikidata。顏色表示船隻沉沒的時期,標記大小隨罹難人數增加。點擊標記查看卡片。",
|
||||
"All years": "所有年份",
|
||||
"Period": "時段",
|
||||
"From": "起",
|
||||
"To": "迄",
|
||||
"First year of the shipwreck period": "沉船時段的起始年份",
|
||||
"Last year of the shipwreck period": "沉船時段的結束年份",
|
||||
"SIGHTING": "目擊",
|
||||
"Show {name} sighting": "顯示{name}目擊",
|
||||
"seen {age} ago": "{age}前目擊",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"ar": [
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -47,6 +48,7 @@
|
||||
],
|
||||
"de": [
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -99,6 +101,7 @@
|
||||
"House",
|
||||
"Hybrid",
|
||||
"Indie",
|
||||
"International",
|
||||
"Ironbow",
|
||||
"Jazz",
|
||||
"LIVE",
|
||||
@@ -145,6 +148,7 @@
|
||||
"Pin",
|
||||
"Plan",
|
||||
"Pop",
|
||||
"Protest",
|
||||
"Punk",
|
||||
"RADAR · {units}",
|
||||
"RADIO",
|
||||
@@ -172,6 +176,7 @@
|
||||
"STD",
|
||||
"SW",
|
||||
"SYNC",
|
||||
"Sahel",
|
||||
"San Francisco",
|
||||
"Scanlines",
|
||||
"Scope",
|
||||
@@ -180,6 +185,7 @@
|
||||
"Soul",
|
||||
"Station",
|
||||
"Station {id}",
|
||||
"Sudan",
|
||||
"T minus {seconds}",
|
||||
"TAGS · {tags}",
|
||||
"TANKER",
|
||||
@@ -192,6 +198,7 @@
|
||||
"Turboprop",
|
||||
"UPSTREAM",
|
||||
"Upstream HTTP {status}",
|
||||
"Video",
|
||||
"Vignette",
|
||||
"WHOT/BHOT",
|
||||
"WIND",
|
||||
@@ -217,6 +224,7 @@
|
||||
"view band|GLOBAL",
|
||||
"{city} CCTV",
|
||||
"{county} County",
|
||||
"{region}, {country}",
|
||||
"{direction} {angle}°",
|
||||
"{direction} · {elevation}",
|
||||
"{division}, {country}",
|
||||
@@ -235,6 +243,7 @@
|
||||
"es": [
|
||||
"1 min/s",
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -286,6 +295,7 @@
|
||||
"Jazz",
|
||||
"LOCAL",
|
||||
"Landsat 8/9",
|
||||
"Local",
|
||||
"MIC",
|
||||
"MIL",
|
||||
"MINI",
|
||||
@@ -329,6 +339,7 @@
|
||||
"STARLINK ···",
|
||||
"STARLINK ✕",
|
||||
"STD",
|
||||
"Sahel",
|
||||
"San Francisco",
|
||||
"Sector",
|
||||
"Sonar",
|
||||
@@ -362,10 +373,13 @@
|
||||
"panel",
|
||||
"view band|GLOBAL",
|
||||
"voice|ERROR",
|
||||
"{hours} h",
|
||||
"{minutes} min",
|
||||
"{direction} {angle}°",
|
||||
"{direction} · {elevation}",
|
||||
"{division}, {country}",
|
||||
"{rate} msg/s",
|
||||
"{region}, {country}",
|
||||
"{speed} kn",
|
||||
"{type} SPD: {speed} HDG: {heading}",
|
||||
"{value} KM",
|
||||
@@ -386,6 +400,7 @@
|
||||
"fr": [
|
||||
"1 min/s",
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"ALTITUDE",
|
||||
"ALTITUDE · FT",
|
||||
@@ -462,6 +477,7 @@
|
||||
"LOCAL",
|
||||
"Landsat 8/9",
|
||||
"Landsat 8/9 via HLS",
|
||||
"Local",
|
||||
"Los Angeles",
|
||||
"MIC",
|
||||
"MIL",
|
||||
@@ -497,6 +513,7 @@
|
||||
"PROPAGATION",
|
||||
"Paris",
|
||||
"Pause",
|
||||
"Photos",
|
||||
"Plan",
|
||||
"Pop",
|
||||
"Punk",
|
||||
@@ -523,6 +540,7 @@
|
||||
"STATION",
|
||||
"STATIONS",
|
||||
"STD",
|
||||
"Sahel",
|
||||
"San Francisco",
|
||||
"Satellites",
|
||||
"Saturation",
|
||||
@@ -567,17 +585,22 @@
|
||||
"satellite",
|
||||
"standard",
|
||||
"station",
|
||||
"via {source}",
|
||||
"voice|OFF",
|
||||
"{count} CONTACTS",
|
||||
"{count} MSGS",
|
||||
"{count} SOURCES",
|
||||
"{count} messages",
|
||||
"{count} sources",
|
||||
"{hours} h",
|
||||
"{minutes} min",
|
||||
"{direction} {angle}°",
|
||||
"{direction} · {elevation}",
|
||||
"{division}, {country}",
|
||||
"{n} cyclones",
|
||||
"{n} satellites",
|
||||
"{rate} msg/s",
|
||||
"{region}, {country}",
|
||||
"{value} KM",
|
||||
"{value} KM/H",
|
||||
"{value} KM/S",
|
||||
@@ -592,6 +615,7 @@
|
||||
"it": [
|
||||
"1 min/s",
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AFRICA",
|
||||
"AIS: --",
|
||||
@@ -651,6 +675,7 @@
|
||||
"Hip-Hop",
|
||||
"House",
|
||||
"Indie",
|
||||
"Iran–Hormuz",
|
||||
"Ironbow",
|
||||
"Jazz",
|
||||
"KTS",
|
||||
@@ -709,11 +734,13 @@
|
||||
"STD",
|
||||
"STOP",
|
||||
"SYNC",
|
||||
"Sahel",
|
||||
"San Francisco",
|
||||
"Scope",
|
||||
"Sentinel-2",
|
||||
"Sonar",
|
||||
"Soul",
|
||||
"Sudan",
|
||||
"TELECOM",
|
||||
"TEMP",
|
||||
"TIMEOUT",
|
||||
@@ -732,6 +759,7 @@
|
||||
"VIEWSHED ON",
|
||||
"VOLUME",
|
||||
"VS",
|
||||
"Video",
|
||||
"WHOT/BHOT",
|
||||
"Washington DC",
|
||||
"World",
|
||||
@@ -757,10 +785,13 @@
|
||||
"{count} MSGS",
|
||||
"{count} feeds live",
|
||||
"{count} scenes",
|
||||
"{hours} h",
|
||||
"{minutes} min",
|
||||
"{direction} {angle}°",
|
||||
"{direction} · {elevation}",
|
||||
"{division}, {country}",
|
||||
"{rate} msg/s",
|
||||
"{region}, {country}",
|
||||
"{scene} / {pack}: {status}. File: {path}. {attribution} · {license}",
|
||||
"{source} HTTP {status}",
|
||||
"{speed} kn",
|
||||
@@ -783,6 +814,7 @@
|
||||
],
|
||||
"ja": [
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -846,6 +878,7 @@
|
||||
"pt": [
|
||||
"1 min/s",
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -901,6 +934,7 @@
|
||||
"Landsat 8/9",
|
||||
"Landsat 8/9 via HLS",
|
||||
"Layout",
|
||||
"Local",
|
||||
"Los Angeles",
|
||||
"MIC",
|
||||
"MIL",
|
||||
@@ -943,6 +977,7 @@
|
||||
"STARLINK ✕",
|
||||
"STATUS",
|
||||
"STATUS · ",
|
||||
"Sahel",
|
||||
"Sentinel-2",
|
||||
"Sentinel-2 via HLS",
|
||||
"Sonar",
|
||||
@@ -975,11 +1010,15 @@
|
||||
"mini",
|
||||
"mph",
|
||||
"nominal",
|
||||
"via {source}",
|
||||
"view band|GLOBAL",
|
||||
"{hours} h",
|
||||
"{minutes} min",
|
||||
"{direction} {angle}°",
|
||||
"{direction} · {elevation}",
|
||||
"{division}, {country}",
|
||||
"{rate} msg/s",
|
||||
"{region}, {country}",
|
||||
"{type} SPD: {speed} HDG: {heading}",
|
||||
"{value} KM",
|
||||
"{value} KM/H",
|
||||
@@ -995,6 +1034,7 @@
|
||||
"iNaturalist"
|
||||
],
|
||||
"ru": [
|
||||
"1900–1945",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
"Acartia",
|
||||
@@ -1018,6 +1058,7 @@
|
||||
"TLE",
|
||||
"VS",
|
||||
"WHOT/BHOT",
|
||||
"{region}, {country}",
|
||||
"acartia.io ↗",
|
||||
"iNaturalist",
|
||||
"iNaturalist ↗",
|
||||
@@ -1026,6 +1067,7 @@
|
||||
"{division}, {country}"
|
||||
],
|
||||
"uk": [
|
||||
"1900–1945",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
"Acartia",
|
||||
@@ -1044,6 +1086,7 @@
|
||||
"STARLINK ✕",
|
||||
"TLE",
|
||||
"WHOT/BHOT",
|
||||
"{region}, {country}",
|
||||
"acartia.io ↗",
|
||||
"iNaturalist",
|
||||
"iNaturalist ↗",
|
||||
@@ -1053,6 +1096,7 @@
|
||||
],
|
||||
"zh-CN": [
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
@@ -1123,6 +1167,7 @@
|
||||
],
|
||||
"zh-Hant": [
|
||||
"1090 MHz",
|
||||
"1900–1945",
|
||||
"978 MHz UAT",
|
||||
"AIS: --",
|
||||
"AIS: {name}",
|
||||
|
||||
@@ -89,6 +89,26 @@ export const KEY_SETUP_KEYS = Object.freeze([
|
||||
envVars: Object.freeze(['FIRMS_MAP_KEY']),
|
||||
tier: 'free',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'liveuamap',
|
||||
title: 'LIVEUAMAP', // i18n-ignore: provider product name
|
||||
unlocks: msg(
|
||||
'Precise conflict points in the News layer, beside GDELT’s articles',
|
||||
),
|
||||
getUrl: 'https://liveuamap.com/promo/api',
|
||||
envVars: Object.freeze(['LIVEUAMAP_API_KEY']),
|
||||
tier: 'metered',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'worldnewsapi',
|
||||
title: 'WORLD NEWS API', // i18n-ignore: provider product name
|
||||
unlocks: msg(
|
||||
'Local in the News layer: the day’s news from the outlets of the country in view',
|
||||
),
|
||||
getUrl: 'https://worldnewsapi.com/console/',
|
||||
envVars: Object.freeze(['WORLDNEWSAPI_KEY']),
|
||||
tier: 'free',
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'tomtom',
|
||||
title: 'TOMTOM', // i18n-ignore: provider product name
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
// Event cards on the globe: a picture, the headline in two lines, and "age ·
|
||||
// sources · sides", with the severity colour down the left edge and the
|
||||
// event's marker as a badge on the picture. Painted on a canvas and handed to
|
||||
// the world overlay as a thumbnail entry, so the overlay places them, keeps
|
||||
// them apart and draws their leader to the marker, as it does CCTV cards.
|
||||
//
|
||||
// The picture is the publisher's own (hotlinked, never copied, credited on
|
||||
// the card); until it loads, or without one, the card shows a tile in the
|
||||
// severity colour with the category icon.
|
||||
|
||||
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
|
||||
import { NEWS_SEVERITY } from './model.js';
|
||||
import { paintMarker } from './sprites.js';
|
||||
|
||||
/** Card size in CSS pixels. */
|
||||
export const CARD_W = 168;
|
||||
export const CARD_H = 136;
|
||||
const PAD = 4;
|
||||
const PIC_H = 84;
|
||||
const EDGE = 3;
|
||||
const SCALE = 2; // canvas pixels per CSS pixel
|
||||
const TITLE_FONT = '600 11px Inter, "Noto Sans Arabic", system-ui, sans-serif';
|
||||
const META_FONT = '9px "JetBrains Mono", "Noto Sans Arabic", monospace';
|
||||
const CREDIT_FONT = '8px Inter, "Noto Sans Arabic", system-ui, sans-serif';
|
||||
// The map shows about ten cards plus the clicked one; a few more stay ready
|
||||
// for a pan back. The least recently drawn card goes, and its picture with it.
|
||||
export const MAX_CARDS = 24;
|
||||
|
||||
const pictures = new Map(); // url → {image, state: 'loading'|'ok'|'failed', waiters}
|
||||
const cards = new Map(); // event id → {canvas, key, view, look, pic}, oldest first
|
||||
|
||||
/** Forget a picture no kept card shows any more. */
|
||||
function releasePicture(url) {
|
||||
if (!url || [...cards.values()].some((card) => card.view.image === url))
|
||||
return;
|
||||
const entry = pictures.get(url);
|
||||
if (!entry) return;
|
||||
entry.waiters.clear();
|
||||
entry.image.onload = entry.image.onerror = null;
|
||||
pictures.delete(url);
|
||||
}
|
||||
|
||||
function picture(url, onLoad) {
|
||||
let entry = pictures.get(url);
|
||||
if (!entry) {
|
||||
const image = new Image();
|
||||
// No referrer: the publisher sees a plain image request, as from a link preview.
|
||||
image.referrerPolicy = 'no-referrer';
|
||||
image.decoding = 'async';
|
||||
entry = { image, state: 'loading', waiters: new Set() };
|
||||
pictures.set(url, entry);
|
||||
image.onload = () => {
|
||||
entry.state = 'ok';
|
||||
for (const done of entry.waiters) done();
|
||||
entry.waiters.clear();
|
||||
};
|
||||
image.onerror = () => {
|
||||
entry.state = 'failed';
|
||||
entry.waiters.clear();
|
||||
};
|
||||
image.src = url;
|
||||
}
|
||||
if (entry.state === 'loading' && onLoad) entry.waiters.add(onLoad);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function roundRect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/** `text` in at most `lines` lines of `width`, the last cut with an ellipsis. */
|
||||
export function wrapLines(ctx, text, width, lines) {
|
||||
const words = String(text || '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
const out = [];
|
||||
let line = '';
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
const next = line ? `${line} ${words[i]}` : words[i];
|
||||
if (ctx.measureText(next).width <= width || !line) {
|
||||
line = next;
|
||||
continue;
|
||||
}
|
||||
out.push(line);
|
||||
line = words[i];
|
||||
if (out.length === lines - 1) {
|
||||
line = words.slice(i).join(' ');
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (line) out.push(line);
|
||||
const last = out.length - 1;
|
||||
if (last >= 0 && ctx.measureText(out[last]).width > width) {
|
||||
let cut = out[last];
|
||||
while (cut && ctx.measureText(`${cut}…`).width > width)
|
||||
cut = cut.slice(0, -1);
|
||||
out[last] = `${cut.trimEnd()}…`;
|
||||
}
|
||||
return out.slice(0, lines);
|
||||
}
|
||||
|
||||
/** Cover-fit an image into a box. */
|
||||
function drawCover(ctx, image, x, y, w, h) {
|
||||
const iw = image.naturalWidth || image.width;
|
||||
const ih = image.naturalHeight || image.height;
|
||||
if (!iw || !ih) return;
|
||||
const s = Math.max(w / iw, h / ih);
|
||||
const sw = w / s;
|
||||
const sh = h / s;
|
||||
ctx.drawImage(image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, x, y, w, h);
|
||||
}
|
||||
|
||||
function paint(canvas, view, look, pic) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0);
|
||||
ctx.clearRect(0, 0, CARD_W, CARD_H);
|
||||
const color = (NEWS_SEVERITY[look.severity] || NEWS_SEVERITY[0]).color;
|
||||
|
||||
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.selectedBackground;
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = WORLD_OVERLAY_STYLE.border;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
// Severity down the left edge.
|
||||
ctx.save();
|
||||
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
|
||||
ctx.clip();
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(0, 0, EDGE, CARD_H);
|
||||
ctx.restore();
|
||||
|
||||
const px = PAD + EDGE;
|
||||
const pw = CARD_W - px - PAD;
|
||||
ctx.save();
|
||||
roundRect(ctx, px, PAD, pw, PIC_H, 3);
|
||||
ctx.clip();
|
||||
if (pic?.state === 'ok') {
|
||||
try {
|
||||
drawCover(ctx, pic.image, px, PAD, pw, PIC_H);
|
||||
} catch {
|
||||
pic.state = 'failed';
|
||||
}
|
||||
}
|
||||
if (pic?.state !== 'ok') {
|
||||
// No picture: a plain glass tile with the event's marker.
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.background;
|
||||
ctx.fillRect(px, PAD, pw, PIC_H);
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.04)';
|
||||
ctx.fillRect(px, PAD, pw, PIC_H);
|
||||
paintMarker(ctx, look, px + pw / 2, PAD + PIC_H / 2, 34);
|
||||
}
|
||||
ctx.restore();
|
||||
// The event's marker as a badge, so the card reads with the map.
|
||||
if (pic?.state === 'ok') paintMarker(ctx, look, px + 13, PAD + 13, 18);
|
||||
// The picture's publisher, always named on it.
|
||||
if (pic?.state === 'ok' && view.credit) {
|
||||
ctx.font = CREDIT_FONT;
|
||||
const w = Math.min(pw - 30, ctx.measureText(view.credit).width + 8);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
|
||||
ctx.fillRect(px + pw - w, PAD + PIC_H - 12, w, 12);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(
|
||||
wrapLines(ctx, view.credit, w - 8, 1)[0] || '',
|
||||
px + pw - w + 4,
|
||||
PAD + PIC_H - 6,
|
||||
);
|
||||
}
|
||||
|
||||
ctx.textBaseline = 'alphabetic';
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
|
||||
ctx.font = TITLE_FONT;
|
||||
wrapLines(ctx, view.title, pw, 2).forEach((line, i) =>
|
||||
ctx.fillText(line, px, PAD + PIC_H + 14 + i * 13),
|
||||
);
|
||||
ctx.fillStyle = WORLD_OVERLAY_STYLE.detail;
|
||||
ctx.font = META_FONT;
|
||||
ctx.fillText(wrapLines(ctx, view.meta, pw, 1)[0] || '', px, CARD_H - PAD - 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* The canvas of an event's card, one per event: a change in what it shows
|
||||
* (the age in its meta line ticks by the minute) repaints the same canvas.
|
||||
* `onChange` runs when its picture arrives and the canvas has been repainted
|
||||
* (ask the scene for a frame).
|
||||
* @returns {HTMLCanvasElement|null} null where there is no canvas
|
||||
*/
|
||||
export function eventCard(id, view, look, onChange) {
|
||||
const key = `${look.severity}|${look.category}|${look.rim}|${view.image || ''}|${view.credit || ''}|${view.title}|${view.meta}`;
|
||||
let card = cards.get(id);
|
||||
if (card) {
|
||||
// Most recently drawn last.
|
||||
cards.delete(id);
|
||||
cards.set(id, card);
|
||||
if (card.key === key) return card.canvas;
|
||||
} else {
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
if (
|
||||
!canvas?.getContext?.('2d') ||
|
||||
typeof globalThis.Path2D !== 'function' ||
|
||||
typeof globalThis.Image !== 'function'
|
||||
)
|
||||
return null;
|
||||
canvas.width = CARD_W * SCALE;
|
||||
canvas.height = CARD_H * SCALE;
|
||||
card = { canvas, key: null, view: {}, look, pic: null };
|
||||
cards.set(id, card);
|
||||
while (cards.size > MAX_CARDS) {
|
||||
const [oldest, gone] = cards.entries().next().value;
|
||||
cards.delete(oldest);
|
||||
releasePicture(gone.view.image);
|
||||
}
|
||||
}
|
||||
const previous = card.view.image;
|
||||
card.key = key;
|
||||
card.view = view;
|
||||
card.look = look;
|
||||
const shown = card;
|
||||
card.pic = view.image
|
||||
? picture(view.image, () => {
|
||||
if (cards.get(id) !== shown || shown.view.image !== view.image) return;
|
||||
paint(shown.canvas, shown.view, shown.look, shown.pic);
|
||||
onChange?.();
|
||||
})
|
||||
: null;
|
||||
if (previous && previous !== view.image) releasePicture(previous);
|
||||
paint(card.canvas, view, look, card.pic);
|
||||
return card.canvas;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAX_CARDS, eventCard } from './cards.js';
|
||||
|
||||
const look = { severity: 3, category: 'strike', rim: 'confirmed', size: 20 };
|
||||
const view = (extra = {}) => ({
|
||||
title: 'Strike on Kharkiv',
|
||||
meta: '10 min · 6 sources · UA, RU',
|
||||
image: 'https://a.test/p.jpg',
|
||||
credit: 'A',
|
||||
...extra,
|
||||
});
|
||||
|
||||
// Node has no canvas: a 2D context that accepts every call, and an Image that
|
||||
// records what was asked for.
|
||||
function fakeBrowser(t) {
|
||||
const saved = {
|
||||
document: globalThis.document,
|
||||
Path2D: globalThis.Path2D,
|
||||
Image: globalThis.Image,
|
||||
};
|
||||
const images = [];
|
||||
const ctx = new Proxy(
|
||||
{},
|
||||
{
|
||||
get: (_target, name) =>
|
||||
name === 'measureText'
|
||||
? (text) => ({ width: String(text).length * 5 })
|
||||
: name === 'createLinearGradient'
|
||||
? () => ({ addColorStop() {} })
|
||||
: () => {},
|
||||
set: () => true,
|
||||
},
|
||||
);
|
||||
let canvases = 0;
|
||||
globalThis.document = {
|
||||
createElement: () => {
|
||||
canvases++;
|
||||
return { getContext: () => ctx };
|
||||
},
|
||||
};
|
||||
globalThis.Path2D = class {};
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
images.push(this);
|
||||
}
|
||||
};
|
||||
t.after(() => {
|
||||
for (const [name, value] of Object.entries(saved))
|
||||
if (value === undefined) delete globalThis[name];
|
||||
else globalThis[name] = value;
|
||||
});
|
||||
return { images, canvases: () => canvases };
|
||||
}
|
||||
|
||||
test('a card keeps one canvas per event while its age ticks', (t) => {
|
||||
const browser = fakeBrowser(t);
|
||||
const first = eventCard('ev-a', view(), look);
|
||||
assert.ok(first);
|
||||
// The meta line's minute-level age changes: the same canvas, repainted.
|
||||
const later = eventCard('ev-a', view({ meta: '11 min · 6 sources' }), look);
|
||||
assert.equal(later, first);
|
||||
assert.equal(browser.canvases(), 1);
|
||||
// One picture request for the event, however often it is drawn.
|
||||
assert.equal(browser.images.length, 1);
|
||||
// Its picture arriving repaints and asks for a frame once; a card with no
|
||||
// picture never does.
|
||||
let frames = 0;
|
||||
const pictured = eventCard(
|
||||
'ev-b',
|
||||
view({ image: 'https://b.test/p.jpg' }),
|
||||
look,
|
||||
() => frames++,
|
||||
);
|
||||
assert.ok(pictured);
|
||||
browser.images.at(-1).onload();
|
||||
assert.equal(frames, 1);
|
||||
assert.ok(eventCard('ev-c', view({ image: null }), look));
|
||||
});
|
||||
|
||||
test('the card cache is bounded and evicts pictures with their cards', (t) => {
|
||||
const browser = fakeBrowser(t);
|
||||
const kept = eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look);
|
||||
for (let i = 0; i < MAX_CARDS * 3; i++) {
|
||||
eventCard(`ev-${i}`, view({ image: `https://p.test/${i}.jpg` }), look);
|
||||
// A card drawn every frame stays: the least recently drawn goes first.
|
||||
assert.equal(
|
||||
eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look),
|
||||
kept,
|
||||
);
|
||||
}
|
||||
const requested = browser.images.length;
|
||||
// The first event was evicted with its picture: drawing it again paints a
|
||||
// new canvas and asks for the picture anew.
|
||||
const again = eventCard(
|
||||
'ev-0',
|
||||
view({ image: 'https://p.test/0.jpg' }),
|
||||
look,
|
||||
);
|
||||
assert.ok(again);
|
||||
assert.equal(browser.images.length, requested + 1);
|
||||
// Evicted pictures are let go: their load handlers are cleared.
|
||||
assert.equal(browser.images[1].onload, null);
|
||||
// The recent ones are still cached.
|
||||
const recent = MAX_CARDS * 3 - 1;
|
||||
eventCard(
|
||||
`ev-${recent}`,
|
||||
view({ image: `https://p.test/${recent}.jpg` }),
|
||||
look,
|
||||
);
|
||||
assert.equal(browser.images.length, requested + 1);
|
||||
});
|
||||
|
||||
test('without a canvas no card is made and nothing is cached', (t) => {
|
||||
fakeBrowser(t);
|
||||
globalThis.document = { createElement: () => ({ getContext: () => null }) };
|
||||
assert.equal(eventCard('none', view(), look), null);
|
||||
globalThis.document = undefined;
|
||||
assert.equal(eventCard('none', view(), look), null);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,826 @@
|
||||
// Pure presentation model for the news layer: severity, category glyphs,
|
||||
// attestation, marker looks and placement, the feed's filters and paging, and
|
||||
// the event cards the News panel and the globe show. No Cesium, no DOM.
|
||||
|
||||
import { getLocale, msg, t, tn } from '../../i18n/index.js';
|
||||
|
||||
export const NEWS_LAYER_ID = 'news';
|
||||
export const NEWS_OVERLAY_SOURCE_ID = 'news';
|
||||
export const NEWS_PICK_PREFIX = 'news:';
|
||||
export const NEWS_FEED_PAGE = 60;
|
||||
export const NEWS_MAP_LIMIT = 500;
|
||||
/** News is real time only: nothing older than a day is shown anywhere. */
|
||||
export const NEWS_WINDOW_MS = 24 * 3_600_000;
|
||||
|
||||
/**
|
||||
* The window a server serves, in ms: its `windowHours` (a whole number of
|
||||
* hours up to 24; a host may serve fewer), else the full day.
|
||||
*/
|
||||
export function newsWindowMs(hours) {
|
||||
return Number.isInteger(hours) && hours >= 1 && hours <= 24
|
||||
? hours * 3_600_000
|
||||
: NEWS_WINDOW_MS;
|
||||
}
|
||||
|
||||
/** The windows the News panel offers, longest first. */
|
||||
export const NEWS_WINDOW_CHOICES = Object.freeze([24, 12, 6, 3, 1]);
|
||||
|
||||
/**
|
||||
* The windows offered under a server's own window of `maxHours`: that window
|
||||
* itself, then each shorter choice.
|
||||
*/
|
||||
export function newsWindowChoices(maxHours) {
|
||||
const cap = newsWindowMs(maxHours) / 3_600_000;
|
||||
return [cap, ...NEWS_WINDOW_CHOICES.filter((hours) => hours < cap)];
|
||||
}
|
||||
// A publish time this far ahead of the clock is skew, not a future story
|
||||
// (as data/regionalNewsWindow.js).
|
||||
const NEWS_CLOCK_SKEW_MS = 15 * 60_000;
|
||||
/** At most this many reports are kept in the feed list, newest first. */
|
||||
export const NEWS_FEED_MAX = 600;
|
||||
// Above this camera height the layer shows one beacon per hotspot; below it
|
||||
// (or once a hotspot is chosen) the outlines and individual reports.
|
||||
export const NEWS_DETAIL_MAX_HEIGHT_M = 2_500_000;
|
||||
// "In view": reports near the view centre, only once the camera is low enough
|
||||
// for "here" to mean a region, read again when it settles in a new cell.
|
||||
// Near is inside the area the server names there (a country, a large
|
||||
// country's state, a disputed area), else, at sea, within the radius.
|
||||
export const NEWS_IN_VIEW_MAX_HEIGHT_M = 3_000_000;
|
||||
export const NEWS_IN_VIEW_RADIUS_KM = 500;
|
||||
export const NEWS_IN_VIEW_LIMIT = 12;
|
||||
/** The Local section lists at most this many reports near the view centre. */
|
||||
export const NEWS_LOCAL_LIMIT = 40;
|
||||
/**
|
||||
* The News panel's sections: Conflicts (the hotspots' significant news, on the
|
||||
* map whenever the layer is on) and Local (everything near the view centre,
|
||||
* on the map while the section is chosen).
|
||||
*/
|
||||
export const NEWS_SECTIONS = Object.freeze(['conflicts', 'local']);
|
||||
export const NEWS_SETTLE_MS = 800;
|
||||
export const NEWS_CELL_DEG = 0.5;
|
||||
/** A feed card's click flies the camera to this height over the event. */
|
||||
export const NEWS_FOCUS_HEIGHT_M = 150_000;
|
||||
// Minor news (a broad outlet's prices, sport, health) is left out unless asked for.
|
||||
export const NEWS_RELEVANT = 'core,related';
|
||||
|
||||
const SOURCE_LABEL = msg('Source');
|
||||
const DISPUTED = msg('Disputed: {name}');
|
||||
const VIA = msg('via {source}');
|
||||
const MEDIA_LABELS = { video: msg('Video'), photo: msg('Photos') };
|
||||
const CLAIMED_BY = msg('Claimed by {who}');
|
||||
const CLAIMED = msg('Claimed');
|
||||
const UNCONFIRMED = msg('Not yet confirmed by others');
|
||||
const REPORTED_BY_SIDE = msg('Reported by {side} sources');
|
||||
const REPORTED_BY_SIDES = msg('Reported by {sides}');
|
||||
const SIDE_SOURCES = msg('{side} sources');
|
||||
const OFFICIAL = msg('Official');
|
||||
const OFFICIAL_AFFILIATIONS = new Set(['military', 'state']);
|
||||
const ATTESTATION = {
|
||||
'both-sides': msg('Reported by both sides'),
|
||||
independent: msg('Independently reported'),
|
||||
single: msg('Single source'),
|
||||
};
|
||||
const NEUTRAL_SIDES = Object.freeze({
|
||||
intl: msg('International'),
|
||||
independent: msg('Independent'),
|
||||
unknown: msg('Unattributed'),
|
||||
external: msg('Outside party'),
|
||||
});
|
||||
|
||||
/**
|
||||
* Short chip names for the curated hotspots; the API's own English name is
|
||||
* the fallback for any other.
|
||||
*/
|
||||
export const NEWS_HOTSPOT_LABELS = Object.freeze({
|
||||
'ua-ru-war': msg('Ukraine–Russia'),
|
||||
'israel-gaza-lebanon': msg('Israel–Gaza–Lebanon'),
|
||||
'iran-hormuz': msg('Iran–Hormuz'),
|
||||
yemen: msg('Yemen–Red Sea'),
|
||||
'sudan-war': msg('Sudan'),
|
||||
sahel: msg('Sahel'),
|
||||
elsewhere: msg('Elsewhere'),
|
||||
// Core's own news (no news server): the world is one hotspot.
|
||||
worldwide: msg('Worldwide'),
|
||||
});
|
||||
|
||||
/** A hotspot's chip label in the interface language. */
|
||||
export function hotspotLabel(hotspot) {
|
||||
const key = NEWS_HOTSPOT_LABELS[hotspot?.id];
|
||||
if (key) return t(key);
|
||||
return hotspot?.catchAll ? t(NEWS_HOTSPOT_LABELS.elsewhere) : hotspot?.name;
|
||||
}
|
||||
|
||||
/** A country's name in the interface language, from its ISO code. */
|
||||
export function countryName(code) {
|
||||
if (!code) return '';
|
||||
try {
|
||||
return (
|
||||
new Intl.DisplayNames([getLocale(), 'en'], { type: 'region' }).of(code) ||
|
||||
code
|
||||
);
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
const AREA_IN_COUNTRY = msg('{region}, {country}');
|
||||
|
||||
/**
|
||||
* The Local section's area in the interface language: a country by its code,
|
||||
* a state with its country, a disputed area by its own name only.
|
||||
*/
|
||||
export function areaLabel(area) {
|
||||
if (!area) return '';
|
||||
if (area.kind === 'disputed' || !area.country) return area.name;
|
||||
if (area.kind === 'country') return countryName(area.country);
|
||||
return t(AREA_IN_COUNTRY, {
|
||||
region: area.name,
|
||||
country: countryName(area.country),
|
||||
});
|
||||
}
|
||||
|
||||
/** Label for a disputed area on the map: its name, marked as disputed. */
|
||||
export const disputedLabel = (area) => t(DISPUTED, { name: area.name });
|
||||
|
||||
// A category is told by its icon (a 16-unit SVG path, filled or stroked). On
|
||||
// the map and in the feed colour is severity (NEWS_SEVERITY), never the type
|
||||
// of event or a side.
|
||||
export const NEWS_CATEGORIES = Object.freeze({
|
||||
strike: {
|
||||
label: msg('Strike'),
|
||||
icon: 'M8 0.8 L9.6 5.2 L14.2 3.6 L11.2 7.6 L15.2 10.6 L10.3 10.6 L8 15.2 L5.7 10.6 L0.8 10.6 L4.8 7.6 L1.8 3.6 L6.4 5.2 Z',
|
||||
solid: true,
|
||||
},
|
||||
// A threat on its way (a drone's course, an air-raid alert): nothing has
|
||||
// hit yet. Not a physical event, so never a picture card.
|
||||
alert: {
|
||||
label: msg('Alert'),
|
||||
icon: 'M1.5 8 H11.5 M8 4.5 L11.5 8 L8 11.5 M14.5 3.5 V12.5',
|
||||
},
|
||||
'air-defence': {
|
||||
label: msg('Air defence'),
|
||||
icon: 'M8 1.5 L13.5 3.5 V8 C13.5 11.3 10.8 13.4 8 14.6 C5.2 13.4 2.5 11.3 2.5 8 V3.5 Z M8 4.5 V11',
|
||||
},
|
||||
ground: {
|
||||
label: msg('Ground fighting'),
|
||||
icon: 'M3 13 L12 4 M8.5 3.5 H12.5 V7.5 M13 13 L4 4 M3.5 7.5 V3.5 H7.5',
|
||||
},
|
||||
casualties: {
|
||||
label: msg('Casualties'),
|
||||
icon: 'M6.2 2 H9.8 V6.2 H14 V9.8 H9.8 V14 H6.2 V9.8 H2 V6.2 H6.2 Z',
|
||||
solid: true,
|
||||
},
|
||||
humanitarian: {
|
||||
label: msg('Humanitarian'),
|
||||
icon: 'M8 2.5 L14.5 13.5 H1.5 Z M8 2.5 V13.5',
|
||||
},
|
||||
infrastructure: {
|
||||
label: msg('Infrastructure'),
|
||||
icon: 'M9.2 1 L3.2 9 H7.6 L6.6 15 L12.8 6.8 H8.4 Z',
|
||||
solid: true,
|
||||
},
|
||||
disaster: {
|
||||
label: msg('Disaster'),
|
||||
icon: 'M1.5 6.5 C3.5 4.5 5.5 4.5 7.5 6.5 S11.5 8.5 14.5 6.5 M1.5 10.5 C3.5 8.5 5.5 8.5 7.5 10.5 S11.5 12.5 14.5 10.5',
|
||||
},
|
||||
protest: {
|
||||
label: msg('Protest'),
|
||||
icon: 'M2.5 6.2 V9.8 H5 L12.5 13.2 V2.8 L5 6.2 Z',
|
||||
},
|
||||
political: {
|
||||
label: msg('Political'),
|
||||
icon: 'M2 14 H14 M2.5 5.5 H13.5 M8 1.8 L14 4.8 H2 Z M4.2 6.5 V12 M8 6.5 V12 M11.8 6.5 V12',
|
||||
},
|
||||
// Business, trade and industry: a national feed's news in Local.
|
||||
economy: {
|
||||
label: msg('Economy'),
|
||||
icon: 'M2 13.5 H14 M2.5 11 L6 7.5 L8.5 9.5 L13.5 4.5 M10.5 4.5 H13.5 V7.5',
|
||||
},
|
||||
other: {
|
||||
label: msg('Other'),
|
||||
icon: 'M8 4.5 A3.5 3.5 0 1 0 8.01 4.5 Z',
|
||||
solid: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Severity 0–3, in colours GEV already uses: its dim and primary text, the
|
||||
// military layers' amber and the Cockpit's emergency red. They are drawn on
|
||||
// a dark disc, so from minor up lightness falls as severity rises and the
|
||||
// ramp still reads under colour blindness and in greyscale.
|
||||
export const NEWS_SEVERITY = Object.freeze([
|
||||
{ label: msg('No physical event'), color: '#7c878d' },
|
||||
{ label: msg('Minor incident'), color: '#e8eaed' },
|
||||
{ label: msg('Significant'), color: '#ffb800' },
|
||||
{ label: msg('Major'), color: '#ff4444' },
|
||||
]);
|
||||
/** The feed's default floor: significant and major events. */
|
||||
export const NEWS_DEFAULT_MIN_SEVERITY = 2;
|
||||
const PHYSICAL = new Set([
|
||||
'strike',
|
||||
'air-defence',
|
||||
'ground',
|
||||
'casualties',
|
||||
'infrastructure',
|
||||
'disaster',
|
||||
]);
|
||||
|
||||
export const categoryStyle = (category) =>
|
||||
NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
|
||||
export const categoryLabel = (category) => t(categoryStyle(category).label);
|
||||
/** Party codes (UA, RU, IL…) are shown as-is; neutral sides are translated. */
|
||||
export const sideLabel = (side) =>
|
||||
Object.hasOwn(NEUTRAL_SIDES, side) ? t(NEUTRAL_SIDES[side]) : side;
|
||||
|
||||
/**
|
||||
* A report's severity, 0–3: the server's (the local model's reading, else
|
||||
* its rules, raised to its event's), or a fallback from the category.
|
||||
*/
|
||||
export function reportSeverity(report) {
|
||||
const own = Number.isInteger(report?.severity) ? report.severity : null;
|
||||
const event = Number.isInteger(report?.event?.severity)
|
||||
? report.event.severity
|
||||
: null;
|
||||
if (own === null && event === null)
|
||||
return PHYSICAL.has(report?.category) ? 1 : 0;
|
||||
return Math.max(own ?? 0, event ?? 0);
|
||||
}
|
||||
export const severityStyle = (report) => NEWS_SEVERITY[reportSeverity(report)];
|
||||
export const severityLabel = (report) => t(severityStyle(report).label);
|
||||
|
||||
/** When a report (or its event) was last heard of, in ms; NaN when unknown. */
|
||||
const lastHeard = (report) =>
|
||||
Date.parse(report?.event?.lastAt || report?.publishedAt || '');
|
||||
|
||||
/**
|
||||
* Whether a time is inside the window (the last 24 hours unless the server
|
||||
* serves fewer; the only news shown); one more than 15 minutes ahead of the
|
||||
* clock is not.
|
||||
*/
|
||||
function inWindow(value, now, windowMs = NEWS_WINDOW_MS) {
|
||||
const at = Date.parse(value || '');
|
||||
return (
|
||||
Number.isFinite(at) &&
|
||||
now - at <= windowMs &&
|
||||
at - now <= NEWS_CLOCK_SKEW_MS
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a report is inside the window (the only news shown). */
|
||||
export function withinNewsWindow(
|
||||
report,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return inWindow(report?.publishedAt, now, windowMs);
|
||||
}
|
||||
|
||||
/** The event's one-report-per-side list, inside the last 24 hours only. */
|
||||
const recentSides = (report, now) =>
|
||||
(report?.event?.sides || []).filter((s) => inWindow(s.publishedAt, now));
|
||||
|
||||
/**
|
||||
* How a report or its event is attested, as a chip: `claimed` (someone's
|
||||
* claim, named where known), `confirmed` (both sides, or an independent
|
||||
* source), `side` (one party's own press), `single` (one report), or null.
|
||||
*/
|
||||
export function attestation(report) {
|
||||
const event = report?.event;
|
||||
const status = event?.status || (report?.claim ? 'claimed' : null);
|
||||
if (status === 'claimed') {
|
||||
const who = event?.claimedBy || report?.claim?.by;
|
||||
return {
|
||||
kind: 'claimed',
|
||||
label: who ? t(CLAIMED_BY, { who }) : t(CLAIMED),
|
||||
};
|
||||
}
|
||||
if (status === 'both-sides' || status === 'independent')
|
||||
return { kind: 'confirmed', label: t(ATTESTATION[status]) };
|
||||
if (status === 'side' && event.reportedSide)
|
||||
return {
|
||||
kind: 'side',
|
||||
label: t(REPORTED_BY_SIDE, { side: sideLabel(event.reportedSide) }),
|
||||
};
|
||||
if (status === 'single')
|
||||
return { kind: 'single', label: t(ATTESTATION.single) };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The attestation chip under a report. An official channel's own post is
|
||||
* already marked Official: "Claimed by" itself would read as doubt about an
|
||||
* alert. It says only that nobody else has reported it yet, and nothing for
|
||||
* an alert, which is the channel's own notice.
|
||||
*/
|
||||
function ownClaimChip(report) {
|
||||
const chip = attestation(report);
|
||||
if (
|
||||
chip?.kind !== 'claimed' ||
|
||||
!OFFICIAL_AFFILIATIONS.has(report.affiliation)
|
||||
)
|
||||
return chip;
|
||||
const who = report.event?.claimedBy || report.claim?.by;
|
||||
if (who && who !== report.sourceName && who !== report.publisher) return chip;
|
||||
return report.category === 'alert'
|
||||
? null
|
||||
: { kind: 'claimed', label: t(UNCONFIRMED) };
|
||||
}
|
||||
|
||||
// The map card is a label, not a reader: long headlines are cut.
|
||||
export const NEWS_CARD_TITLE_MAX = 90;
|
||||
|
||||
/** A headline cut at a word to fit `max` characters. */
|
||||
export function shortTitle(title, max = NEWS_CARD_TITLE_MAX) {
|
||||
const text = String(title || '');
|
||||
if (text.length <= max) return text;
|
||||
const cut = text.slice(0, max - 1);
|
||||
const word = cut.lastIndexOf(' ');
|
||||
return `${word > max * 0.6 ? cut.slice(0, word) : cut}…`;
|
||||
}
|
||||
|
||||
/** The media a post carries ("Video", "Photos"), translated. */
|
||||
export function mediaLabels(report) {
|
||||
return (report?.media || [])
|
||||
.map((m) => (MEDIA_LABELS[m] ? t(MEDIA_LABELS[m]) : ''))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* How long ago, in few words: "now" under a minute, "N min" under an hour,
|
||||
* "N h" under a day. Older is never shown; it reads
|
||||
* "24 h".
|
||||
*/
|
||||
export function ageWords(at, now = Date.now()) {
|
||||
const minutes = Math.max(0, Math.floor((now - Date.parse(at)) / 60_000));
|
||||
if (!Number.isFinite(minutes)) return '';
|
||||
if (minutes < 1) return t('now', { context: 'age' });
|
||||
if (minutes < 60) return t('{minutes} min', { minutes });
|
||||
return t('{hours} h', { hours: Math.min(24, Math.floor(minutes / 60)) });
|
||||
}
|
||||
|
||||
/**
|
||||
* How a report's marker looks: colour = severity, icon = category, rim =
|
||||
* attestation (`confirmed` solid, `claimed` dashed, else thin), size =
|
||||
* sources, opacity = age (fading to 45 % over a day).
|
||||
*/
|
||||
export function markerStyle(report, now = Date.now()) {
|
||||
const kind = attestation(report)?.kind;
|
||||
const at = lastHeard(report);
|
||||
const hours = Number.isFinite(at) ? Math.max(0, (now - at) / 3_600_000) : 0;
|
||||
return {
|
||||
category: Object.hasOwn(NEWS_CATEGORIES, report?.category)
|
||||
? report.category
|
||||
: 'other',
|
||||
severity: reportSeverity(report),
|
||||
rim: kind === 'confirmed' || kind === 'claimed' ? kind : 'thin',
|
||||
size: eventPixelSize(report?.event?.size),
|
||||
alpha: Math.max(0.45, 1 - (0.55 * Math.min(hours, 24)) / 24),
|
||||
};
|
||||
}
|
||||
|
||||
function hash(text) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
h ^= text.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trend glyph for a hotspot: ▲/▼ when the last 24 h differ from the 24 h
|
||||
* before by more than a fifth, nothing when flat or without a prior day.
|
||||
*/
|
||||
export function hotspotTrend(last24h, prev24h) {
|
||||
if (!(prev24h > 0)) return '';
|
||||
if (last24h > prev24h * 1.2) return '▲';
|
||||
if (last24h < prev24h * 0.8) return '▼';
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Beacon size in pixels: grows with the square root of daily activity. */
|
||||
export const beaconPixelSize = (last24h) =>
|
||||
Math.round(Math.min(26, 10 + Math.sqrt(Math.max(0, last24h)) * 1.4));
|
||||
|
||||
/** Marker size for an event: grows with the number of distinct sources. */
|
||||
export function eventPixelSize(sources = 1) {
|
||||
return Math.round(
|
||||
// No smaller than 24: the category icon is half the disc and unreadable
|
||||
// below that.
|
||||
Math.min(36, 24 + 3 * Math.log2(Math.max(1, Number(sources) || 1))),
|
||||
);
|
||||
}
|
||||
|
||||
// An event several sources report within the last few hours gets a halo.
|
||||
export const NEWS_PRESSING_SOURCES = 5;
|
||||
const PRESSING_MS = 3 * 3_600_000;
|
||||
|
||||
/** Whether an event is fresh and widely reported, or fresh and major. */
|
||||
export function isPressing(report, now = Date.now()) {
|
||||
const event = report?.event;
|
||||
const fresh = now - lastHeard(report) <= PRESSING_MS;
|
||||
return Boolean(
|
||||
fresh &&
|
||||
((event && event.size >= NEWS_PRESSING_SOURCES) ||
|
||||
reportSeverity(report) === 3),
|
||||
);
|
||||
}
|
||||
|
||||
// The big events stand as picture cards over their marker: several
|
||||
// sources, and major or pressing.
|
||||
export const NEWS_CARD_LIMIT = 10;
|
||||
export const NEWS_CARD_MIN_SOURCES = 2;
|
||||
|
||||
/** Whether an event gets a card on the map: physical events only, not statements. */
|
||||
export function isCardEvent(report, now = Date.now()) {
|
||||
return Boolean(
|
||||
report?.event?.size >= NEWS_CARD_MIN_SOURCES &&
|
||||
PHYSICAL.has(report.category) &&
|
||||
(reportSeverity(report) === 3 || isPressing(report, now)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The card events among `reports`, most severe, most reported and newest first. */
|
||||
export function cardEvents(reports, now = Date.now(), limit = NEWS_CARD_LIMIT) {
|
||||
return reports
|
||||
.filter((r) => r.pins?.length && isCardEvent(r, now))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
reportSeverity(b) - reportSeverity(a) ||
|
||||
b.event.size - a.event.size ||
|
||||
(b.event.lastAt || '').localeCompare(a.event.lastAt || ''),
|
||||
)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/** The distinct sides an event was reported by in the last day, lead first. */
|
||||
function eventSides(report, now) {
|
||||
const sides = recentSides(report, now).map((s) => s.side);
|
||||
return [...new Set(sides.length ? sides : [report?.side].filter(Boolean))];
|
||||
}
|
||||
|
||||
/**
|
||||
* "Reported by UA sources · RU sources", or '' when no side is known; an
|
||||
* unattributed side is left out.
|
||||
*/
|
||||
export function sidesLine(report, now = Date.now()) {
|
||||
const sides = eventSides(report, now).filter((side) => side !== 'unknown');
|
||||
if (!sides.length) return '';
|
||||
if (sides.length === 1)
|
||||
return t(REPORTED_BY_SIDE, { side: sideLabel(sides[0]) });
|
||||
return t(REPORTED_BY_SIDES, {
|
||||
sides: sides
|
||||
.map((side) => t(SIDE_SOURCES, { side: sideLabel(side) }))
|
||||
.join(' · '),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The event's picture, the publisher named, and its clip when it has one. The
|
||||
* panel shows it for any event; the globe's picture cards are for events of
|
||||
* two or more sources (isCardEvent).
|
||||
*/
|
||||
export function eventPicture(report) {
|
||||
const image = report?.event?.image;
|
||||
if (!image) return null;
|
||||
return {
|
||||
url: image.url,
|
||||
credit: image.publisher || '',
|
||||
...(image.video ? { video: image.video } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** What an event's picture card on the globe shows. */
|
||||
export function cardView(report, now = Date.now()) {
|
||||
const event = report.event;
|
||||
const sides = eventSides(report, now).map(sideLabel);
|
||||
// A globe card's picture needs two or more sources, as the card does.
|
||||
const picture =
|
||||
report?.event?.size >= NEWS_CARD_MIN_SOURCES ? eventPicture(report) : null;
|
||||
return {
|
||||
title: report.titleEn || report.title,
|
||||
meta: [
|
||||
ageWords(event?.lastAt || report.publishedAt, now),
|
||||
tn(event?.size || 1, '{count} source', '{count} sources'),
|
||||
sides.slice(0, 3).join(', ') + (sides.length > 3 ? '…' : ''),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
image: picture?.url || null,
|
||||
credit: picture?.credit || '',
|
||||
};
|
||||
}
|
||||
|
||||
/** "Source: host ↗" line for a report's card; the card opens the article. */
|
||||
export function sourceLinkLabel(url) {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(url).hostname.replace(/^www\./, '');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
return `${t(SOURCE_LABEL)}: ${host} ↗`;
|
||||
}
|
||||
|
||||
/**
|
||||
* "via GDELT Project": the service a report was read through, which asks to
|
||||
* be credited where its reports show; '' when the server names none.
|
||||
*/
|
||||
export function attributionLabel(report) {
|
||||
return report?.attribution ? t(VIA, { source: report.attribution }) : '';
|
||||
}
|
||||
|
||||
/** The places a report is pinned at, joined, or null. */
|
||||
function placeLine(report) {
|
||||
return (
|
||||
(report.pins?.length ? report.pins : [report.geo])
|
||||
.map((p) => p?.place)
|
||||
.filter(Boolean)
|
||||
.join(' · ') || null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One event card in the News panel: picture,
|
||||
* headline, a mono meta line (severity, category, place, sources, age, the
|
||||
* service it came through), the sides line, then attestation and media chips. Labels and colours are
|
||||
* resolved here so the panel imports no layer code.
|
||||
*/
|
||||
export function feedCardView(report, now = Date.now()) {
|
||||
const severity = reportSeverity(report);
|
||||
const style = categoryStyle(report.category);
|
||||
const size = report.event?.size || 1;
|
||||
const translated = Boolean(report.titleEn && report.titleEn !== report.title);
|
||||
return {
|
||||
id: report.id,
|
||||
url: report.url,
|
||||
title: translated ? report.titleEn : report.title,
|
||||
// The local model's English headline over a post in another language:
|
||||
// the original stays beside it.
|
||||
original: translated ? report.title : null,
|
||||
snippet: report.snippet,
|
||||
severity,
|
||||
severityLabel: t(NEWS_SEVERITY[severity].label),
|
||||
color: NEWS_SEVERITY[severity].color,
|
||||
icon: style.icon,
|
||||
solid: Boolean(style.solid),
|
||||
category: categoryLabel(report.category),
|
||||
place: placeLine(report),
|
||||
placedByModel: Boolean(report.geo?.byModel),
|
||||
mappable: Boolean(report.pins?.length),
|
||||
sources: tn(size, '{count} source', '{count} sources'),
|
||||
age: ageWords(report.event?.lastAt || report.publishedAt, now),
|
||||
publisher: report.publisher,
|
||||
via: attributionLabel(report),
|
||||
sides: sidesLine(report, now),
|
||||
sourceLink: sourceLinkLabel(report.url),
|
||||
picture: eventPicture(report),
|
||||
chips: [
|
||||
// An official channel speaking for itself (a ministry, the armed
|
||||
// forces, a press service), not an outlet that quotes one.
|
||||
OFFICIAL_AFFILIATIONS.has(report.affiliation)
|
||||
? { kind: 'official', label: t(OFFICIAL) }
|
||||
: null,
|
||||
ownClaimChip(report),
|
||||
...mediaLabels(report).map((label) => ({ kind: 'media', label })),
|
||||
].filter(Boolean),
|
||||
// The event's first report from each other side, under the lead.
|
||||
others: recentSides(report, now)
|
||||
.slice(1)
|
||||
.map((s) => ({
|
||||
side: sideLabel(s.side),
|
||||
publisher: s.publisher,
|
||||
title: s.title,
|
||||
url: s.url,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a report is placed no closer than a country: it has no spot of its
|
||||
* own on the map.
|
||||
*/
|
||||
export const countryOnly = (report) =>
|
||||
report.pins?.length > 0 &&
|
||||
report.pins.every((pin) => pin.precision === 'country');
|
||||
|
||||
/**
|
||||
* Country-only reports as one group per country, in the order met:
|
||||
* `{key, place, lat, lon, count}`. They are drawn as one badge with a count,
|
||||
* not as markers piled on the country's centre.
|
||||
*/
|
||||
export function countryGroups(reports) {
|
||||
const groups = new Map();
|
||||
for (const report of reports) {
|
||||
if (!countryOnly(report)) continue;
|
||||
const { lat, lon, place } = report.pins[0];
|
||||
const key = place || `${lat.toFixed(1)},${lon.toFixed(1)}`;
|
||||
const group = groups.get(key);
|
||||
if (group) group.count += 1;
|
||||
else groups.set(key, { key, place: place || '', lat, lon, count: 1 });
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Marker position for a report. Many reports name the same city and would
|
||||
* stack on one centroid, so each is spread on a small deterministic ring
|
||||
* (about 1.5 km for a place, 6 km for a region, 28 km for a country) to stay
|
||||
* individually clickable. The spread is display-only; cards show the place.
|
||||
*/
|
||||
export function reportMarkerPosition(report, pin = 0) {
|
||||
const { lat, lon, precision } = report.pins?.[pin] || report.geo;
|
||||
const h = hash(pin ? `${report.id}~${pin}` : report.id);
|
||||
const angle = ((h % 3600) / 3600) * 2 * Math.PI;
|
||||
const radiusDeg =
|
||||
(precision === 'country' ? 0.25 : precision === 'region' ? 0.055 : 0.014) *
|
||||
(0.35 + ((h >>> 12) % 65) / 100);
|
||||
return {
|
||||
lat: lat + radiusDeg * Math.sin(angle),
|
||||
lon: lon + (radiusDeg * Math.cos(angle)) / Math.cos((lat * Math.PI) / 180),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a page into the feed, newest first, one row per report id, keeping
|
||||
* only the window and at most `max` rows (a long session does not grow
|
||||
* the list). `mode` 'head' refreshes the top and keeps the older cursor;
|
||||
* 'append' adds an older page and takes its cursor; 'replace' starts over.
|
||||
* A head page that has older pages behind it and shares no row with the list
|
||||
* left a gap (more than a page arrived since), so it starts over too.
|
||||
*/
|
||||
export function mergeFeedPage(
|
||||
feed,
|
||||
page,
|
||||
mode,
|
||||
now = Date.now(),
|
||||
max = NEWS_FEED_MAX,
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
const byId = new Map();
|
||||
if (mode === 'head' && page.nextBefore && feed.items.length) {
|
||||
const held = new Set(feed.items.map((item) => item.id));
|
||||
if (!page.reports.some((item) => held.has(item.id))) mode = 'replace';
|
||||
}
|
||||
const items =
|
||||
mode === 'replace'
|
||||
? page.reports
|
||||
: mode === 'append'
|
||||
? [...feed.items, ...page.reports]
|
||||
: [...page.reports, ...feed.items];
|
||||
for (const item of items)
|
||||
if (!byId.has(item.id) && withinNewsWindow(item, now, windowMs))
|
||||
byId.set(item.id, item);
|
||||
return {
|
||||
items: [...byId.values()]
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
|
||||
.slice(0, max),
|
||||
nextBefore:
|
||||
mode === 'head' && feed.items.length ? feed.nextBefore : page.nextBefore,
|
||||
};
|
||||
}
|
||||
|
||||
/** Normalised filters; anything unknown falls back to its default. */
|
||||
export function normalizeFilters(next = {}, hotspots = [], previous = {}) {
|
||||
const merged = { ...previous, ...next };
|
||||
const hotspot = hotspots.some((h) => h.id === merged.hotspot)
|
||||
? merged.hotspot
|
||||
: 'all';
|
||||
const category = Object.hasOwn(NEWS_CATEGORIES, merged.category)
|
||||
? merged.category
|
||||
: 'all';
|
||||
const minSeverity =
|
||||
Number.isInteger(merged.minSeverity) &&
|
||||
merged.minSeverity >= 0 &&
|
||||
merged.minSeverity <= 3
|
||||
? merged.minSeverity
|
||||
: NEWS_DEFAULT_MIN_SEVERITY;
|
||||
return {
|
||||
hotspot,
|
||||
category,
|
||||
minSeverity,
|
||||
section: NEWS_SECTIONS.includes(merged.section)
|
||||
? merged.section
|
||||
: 'conflicts',
|
||||
// A shorter window than the server's; null shows all it serves.
|
||||
hours: NEWS_WINDOW_CHOICES.includes(merged.hours) ? merged.hours : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a report passes the filters the server does not apply. */
|
||||
export function passesFilters(
|
||||
report,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return (
|
||||
withinNewsWindow(report, now, windowMs) &&
|
||||
reportSeverity(report) >= filters.minSeverity
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a report belongs on the map under the current filters. */
|
||||
export function visibleOnMap(
|
||||
report,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
) {
|
||||
return (
|
||||
(filters.hotspot === 'all' ||
|
||||
(report.hotspotIds || [report.hotspotId]).includes(filters.hotspot)) &&
|
||||
(filters.category === 'all' || report.category === filters.category) &&
|
||||
passesFilters(report, filters, now, windowMs)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The filters Local applies: every hotspot and every severity, near the view
|
||||
* centre; the category and the window still hold.
|
||||
*/
|
||||
export const localFilters = (filters) => ({
|
||||
...filters,
|
||||
hotspot: 'all',
|
||||
minSeverity: 0,
|
||||
});
|
||||
|
||||
/** API query for the Conflicts feed under the current filters: the window only. */
|
||||
export function feedQueryFor(filters, extra = {}) {
|
||||
return {
|
||||
events: true,
|
||||
today: true,
|
||||
relevance: NEWS_RELEVANT,
|
||||
hotspot: filters.hotspot,
|
||||
category: filters.category === 'all' ? '' : filters.category,
|
||||
limit: NEWS_FEED_PAGE,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
/** The half-degree cell a point lies in, as a key. */
|
||||
export function viewCell({ lat, lon }) {
|
||||
return `${Math.floor(lat / NEWS_CELL_DEG)}:${Math.floor(lon / NEWS_CELL_DEG)}`;
|
||||
}
|
||||
|
||||
/** Great-circle distance in kilometres. */
|
||||
export function distanceKm(a, b) {
|
||||
const rad = Math.PI / 180;
|
||||
const dLat = (b.lat - a.lat) * rad;
|
||||
const dLon = (b.lon - a.lon) * rad;
|
||||
const s =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
|
||||
return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(s)));
|
||||
}
|
||||
|
||||
function inRing(ring, { lat, lon }) {
|
||||
let inside = false;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
const [xi, yi] = ring[i];
|
||||
const [xj, yj] = ring[j];
|
||||
if (
|
||||
yi > lat !== yj > lat &&
|
||||
lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi
|
||||
)
|
||||
inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Whether a point lies in an outline's polygons (`{outer, holes}`). */
|
||||
export function inPolygons(polygons, point) {
|
||||
return polygons.some(
|
||||
({ outer, holes }) =>
|
||||
inRing(outer, point) && !holes.some((hole) => inRing(hole, point)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reports near `centre` that pass the filters, newest first: any pin
|
||||
* inside `area` (outline polygons), or without one within
|
||||
* NEWS_IN_VIEW_RADIUS_KM. Newest, not most severe: an area's own news often
|
||||
* carries no severity, and the area's fighting would otherwise crowd it out.
|
||||
*/
|
||||
export function reportsInView(
|
||||
reports,
|
||||
centre,
|
||||
filters,
|
||||
now = Date.now(),
|
||||
limit = NEWS_IN_VIEW_LIMIT,
|
||||
windowMs = NEWS_WINDOW_MS,
|
||||
area = null,
|
||||
) {
|
||||
if (!centre) return [];
|
||||
const near = area?.length
|
||||
? (pin) => inPolygons(area, pin)
|
||||
: (pin) => distanceKm(pin, centre) <= NEWS_IN_VIEW_RADIUS_KM;
|
||||
return reports
|
||||
.filter(
|
||||
(r) =>
|
||||
passesFilters(r, filters, now, windowMs) &&
|
||||
(filters.category === 'all' || r.category === filters.category) &&
|
||||
r.pins?.some(near),
|
||||
)
|
||||
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
normalizeFeedPayload,
|
||||
normalizeHotspotsPayload,
|
||||
normalizeOutlinePayload,
|
||||
} from './records.js';
|
||||
import {
|
||||
NEWS_IN_VIEW_RADIUS_KM,
|
||||
ageWords,
|
||||
areaLabel,
|
||||
beaconPixelSize,
|
||||
cardEvents,
|
||||
cardView,
|
||||
distanceKm,
|
||||
eventPixelSize,
|
||||
feedCardView,
|
||||
feedQueryFor,
|
||||
hotspotLabel,
|
||||
hotspotTrend,
|
||||
inPolygons,
|
||||
isPressing,
|
||||
markerStyle,
|
||||
mergeFeedPage,
|
||||
newsWindowChoices,
|
||||
newsWindowMs,
|
||||
normalizeFilters,
|
||||
passesFilters,
|
||||
reportMarkerPosition,
|
||||
reportSeverity,
|
||||
reportsInView,
|
||||
sidesLine,
|
||||
sourceLinkLabel,
|
||||
viewCell,
|
||||
visibleOnMap,
|
||||
withinNewsWindow,
|
||||
} from './model.js';
|
||||
import { newsFeedQuery } from './source.js';
|
||||
|
||||
const NOW = Date.parse('2026-10-28T10:00:00Z');
|
||||
const report = (id, publishedAt, extra = {}) => ({
|
||||
id,
|
||||
title: `Report ${id}`,
|
||||
url: `https://example.com/${id}`,
|
||||
publishedAt,
|
||||
publisher: 'Example',
|
||||
side: 'UA',
|
||||
category: 'strike',
|
||||
hotspotIds: ['ua'],
|
||||
geo: {
|
||||
lat: 50,
|
||||
lon: 36,
|
||||
place: 'Kharkiv',
|
||||
precision: 'city',
|
||||
mappable: true,
|
||||
},
|
||||
pins: [
|
||||
{ lat: 50, lon: 36, place: 'Kharkiv', precision: 'city', mappable: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
const event = (extra = {}) => ({
|
||||
status: 'both-sides',
|
||||
size: 6,
|
||||
severity: 3,
|
||||
lastAt: '2026-10-28T09:30:00Z',
|
||||
sides: [
|
||||
{
|
||||
side: 'UA',
|
||||
title: 'a',
|
||||
url: 'https://a.test/',
|
||||
publisher: 'A',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'b',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-28T09:20:00Z',
|
||||
},
|
||||
],
|
||||
image: { url: 'https://a.test/p.jpg', publisher: 'A' },
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('payloads are validated record by record; empty and malformed payloads', () => {
|
||||
const hotspots = normalizeHotspotsPayload({
|
||||
hotspots: [
|
||||
{
|
||||
id: 'ua',
|
||||
name: 'UA',
|
||||
bbox: [22, 44, 42, 56],
|
||||
parties: ['UA', 'RU', '<x>'],
|
||||
counts: { last24h: 3 },
|
||||
},
|
||||
{ id: 'bad', name: 'Bad', bbox: [42, 44, 22, 56] },
|
||||
{ id: '../x', name: 'Bad id', bbox: [22, 44, 42, 56] },
|
||||
],
|
||||
ingest: { lastRunAt: '2026-10-28T10:00:00Z' },
|
||||
});
|
||||
assert.deepEqual(
|
||||
hotspots.hotspots.map((h) => [h.id, h.parties, h.last24h]),
|
||||
[['ua', ['UA', 'RU'], 3]],
|
||||
);
|
||||
assert.equal(hotspots.lastRunAt, '2026-10-28T10:00:00.000Z');
|
||||
assert.equal(normalizeHotspotsPayload({}), null);
|
||||
assert.equal(normalizeHotspotsPayload(null), null);
|
||||
assert.deepEqual(normalizeHotspotsPayload({ hotspots: [] }).hotspots, []);
|
||||
|
||||
const feed = normalizeFeedPayload({
|
||||
reports: [
|
||||
{
|
||||
id: 'r_1',
|
||||
title: ' Strike on Kharkiv ',
|
||||
url: 'https://x.test/a',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
geo: { lat: 50, lon: 36, mappable: true },
|
||||
media: ['video', 'video', 'audio'],
|
||||
event: { size: 3, image: { url: 'http://x.test/p.jpg' } },
|
||||
},
|
||||
{
|
||||
id: 'r_2',
|
||||
title: 'Bad link',
|
||||
url: 'javascript:alert(1)',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'r_3',
|
||||
title: 'Bad geo',
|
||||
url: 'https://user:[email protected]/c',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'r_4',
|
||||
title: 'Off the globe',
|
||||
url: 'https://x.test/d',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
geo: { lat: 200, lon: 36 },
|
||||
},
|
||||
],
|
||||
nextBefore: '2026-10-28T08:00:00Z',
|
||||
});
|
||||
assert.deepEqual(
|
||||
feed.reports.map((r) => [r.id, r.title, Boolean(r.geo), r.pins.length]),
|
||||
[
|
||||
['r_1', 'Strike on Kharkiv', true, 1],
|
||||
['r_4', 'Off the globe', false, 0],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(feed.reports[0].media, ['video']);
|
||||
// A picture must be HTTPS on the publisher's site.
|
||||
assert.equal(feed.reports[0].event.image, null);
|
||||
assert.equal(feed.nextBefore, '2026-10-28T08:00:00.000Z');
|
||||
assert.equal(normalizeFeedPayload({ reports: 'x' }), null);
|
||||
assert.deepEqual(normalizeFeedPayload({ reports: [] }), {
|
||||
reports: [],
|
||||
nextBefore: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("an event's clip is kept only as an HTTPS file a browser plays itself", () => {
|
||||
const clip = (video) =>
|
||||
normalizeFeedPayload({
|
||||
reports: [
|
||||
{
|
||||
id: 'r',
|
||||
title: 'T',
|
||||
url: 'https://x.test/r',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
event: {
|
||||
size: 1,
|
||||
image: { url: 'https://cdn.test/p.jpg', publisher: 'P', video },
|
||||
},
|
||||
},
|
||||
],
|
||||
}).reports[0].event.image.video;
|
||||
assert.equal(
|
||||
clip('https://cdn.test/v.mp4?token=a'),
|
||||
'https://cdn.test/v.mp4?token=a',
|
||||
);
|
||||
assert.equal(clip('https://cdn.test/v.webm'), 'https://cdn.test/v.webm');
|
||||
assert.equal(clip('http://cdn.test/v.mp4'), undefined);
|
||||
assert.equal(clip('https://cdn.test/v.m3u8'), undefined);
|
||||
assert.equal(clip(undefined), undefined);
|
||||
});
|
||||
|
||||
test('outlines keep valid rings, borders and named disputed areas', () => {
|
||||
const ring = [
|
||||
[30, 45],
|
||||
[31, 45],
|
||||
[31, 46],
|
||||
];
|
||||
const outline = normalizeOutlinePayload({
|
||||
polygons: [{ outer: ring, holes: [[[0, 0]]] }, { outer: [[1, 2]] }],
|
||||
borders: [ring, 'x'],
|
||||
disputed: [
|
||||
{
|
||||
name: 'Crimea',
|
||||
kind: 'held',
|
||||
heldBy: 'RU',
|
||||
claimedBy: 'UA',
|
||||
rings: [ring],
|
||||
},
|
||||
{ name: 'No rings', rings: [] },
|
||||
{ name: 'Odd kind', kind: 'zzz', heldBy: 'nope', rings: [ring] },
|
||||
],
|
||||
});
|
||||
assert.equal(outline.polygons.length, 1);
|
||||
assert.deepEqual(outline.polygons[0].holes, []);
|
||||
assert.equal(outline.borders.length, 1);
|
||||
assert.deepEqual(
|
||||
outline.disputed.map((d) => [d.name, d.kind, d.heldBy]),
|
||||
[
|
||||
['Crimea', 'held', 'RU'],
|
||||
['Odd kind', 'held', null],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(normalizeOutlinePayload(null), {
|
||||
polygons: [],
|
||||
borders: [],
|
||||
disputed: [],
|
||||
area: null,
|
||||
});
|
||||
// Indonesia's 208 islands are all kept.
|
||||
const islands = Array.from({ length: 208 }, () => ({ outer: ring }));
|
||||
assert.equal(
|
||||
normalizeOutlinePayload({ polygons: islands }).polygons.length,
|
||||
208,
|
||||
);
|
||||
});
|
||||
|
||||
test('a point outline names its area, and Local keeps to it', () => {
|
||||
const box = [
|
||||
[35, 48],
|
||||
[37, 48],
|
||||
[37, 50.5],
|
||||
[35, 50.5],
|
||||
];
|
||||
const { area, polygons } = normalizeOutlinePayload({
|
||||
area: { key: 'US-TX', name: 'Texas', kind: 'region', country: 'US' },
|
||||
polygons: [{ outer: box, holes: [] }],
|
||||
});
|
||||
assert.deepEqual(area, {
|
||||
key: 'US-TX',
|
||||
name: 'Texas',
|
||||
kind: 'region',
|
||||
country: 'US',
|
||||
});
|
||||
assert.equal(areaLabel(area), 'Texas, United States');
|
||||
assert.equal(
|
||||
areaLabel({ ...area, kind: 'country', country: 'UA' }),
|
||||
'Ukraine',
|
||||
);
|
||||
// A disputed area is named as itself, never as either side's.
|
||||
assert.equal(
|
||||
areaLabel({ key: 'disputed:Crimea', name: 'Crimea', kind: 'disputed' }),
|
||||
'Crimea',
|
||||
);
|
||||
assert.equal(normalizeOutlinePayload({ area: { key: 'X' } }).area, null);
|
||||
const at = (id, lat, lon) =>
|
||||
report(id, '2026-10-28T09:00:00Z', {
|
||||
pins: [{ lat, lon, mappable: true }],
|
||||
});
|
||||
const reports = [at('inside', 50, 36), at('beyond', 49, 39)];
|
||||
const filters = normalizeFilters({ minSeverity: 0 });
|
||||
const centre = { lat: 49, lon: 36 };
|
||||
const now = Date.parse('2026-10-28T10:00:00Z');
|
||||
const ids = (area) =>
|
||||
reportsInView(reports, centre, filters, now, 10, undefined, area).map(
|
||||
(r) => r.id,
|
||||
);
|
||||
// Within 500 km both; inside the area only the one.
|
||||
assert.deepEqual(ids(null), ['inside', 'beyond']);
|
||||
assert.deepEqual(ids(polygons), ['inside']);
|
||||
assert.ok(inPolygons(polygons, { lat: 49, lon: 36 }));
|
||||
assert.ok(!inPolygons([{ outer: box, holes: [box] }], { lat: 49, lon: 36 }));
|
||||
});
|
||||
|
||||
test('feed pages merge newest first without duplicates', () => {
|
||||
const a = report('a', '2026-10-28T10:00:00Z');
|
||||
const b = report('b', '2026-10-28T09:00:00Z');
|
||||
const c = report('c', '2026-10-28T08:00:00Z');
|
||||
let feed = mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: [a, b], nextBefore: 'B' },
|
||||
'replace',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['a', 'b'], 'B'],
|
||||
);
|
||||
feed = mergeFeedPage(
|
||||
feed,
|
||||
{ reports: [b, c], nextBefore: null },
|
||||
'append',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['a', 'b', 'c'], null],
|
||||
);
|
||||
const newer = report('n', '2026-10-28T11:00:00Z');
|
||||
feed = mergeFeedPage(
|
||||
{ ...feed, nextBefore: 'C' },
|
||||
{ reports: [newer, a], nextBefore: 'X' },
|
||||
'head',
|
||||
NOW + 3_600_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['n', 'a', 'b', 'c'], 'C'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
mergeFeedPage({ items: [] }, { reports: [], nextBefore: null }, 'replace'),
|
||||
{ items: [], nextBefore: null },
|
||||
);
|
||||
});
|
||||
|
||||
test('a head page that does not reach the rows held starts the list over', () => {
|
||||
const held = report('h', '2026-10-28T06:00:00Z');
|
||||
const fresh = report('n', '2026-10-28T09:30:00Z');
|
||||
// More than a page arrived since the last refresh (a suspended tab): the
|
||||
// reports between this page and the rows held are behind its cursor.
|
||||
const feed = mergeFeedPage(
|
||||
{ items: [held], nextBefore: 'OLD' },
|
||||
{ reports: [fresh], nextBefore: 'NEW' },
|
||||
'head',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[feed.items.map((r) => r.id), feed.nextBefore],
|
||||
[['n'], 'NEW'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the feed list keeps only the last 24 hours and at most its cap', () => {
|
||||
const fresh = report('f', '2026-10-28T09:00:00Z');
|
||||
const stale = report('s', '2026-10-27T09:00:00Z');
|
||||
const ahead = report('x', '2026-10-28T11:00:00Z');
|
||||
// A long session: yesterday's rows already held fall out on the next merge.
|
||||
const feed = mergeFeedPage(
|
||||
{ items: [stale], nextBefore: 'S' },
|
||||
{ reports: [fresh, ahead], nextBefore: 'F' },
|
||||
'head',
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(
|
||||
feed.items.map((r) => r.id),
|
||||
['f'],
|
||||
);
|
||||
const many = Array.from({ length: 30 }, (_, i) =>
|
||||
report(`r${i}`, new Date(NOW - (i + 1) * 60_000).toISOString()),
|
||||
);
|
||||
const capped = mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: many, nextBefore: null },
|
||||
'replace',
|
||||
NOW,
|
||||
10,
|
||||
);
|
||||
assert.equal(capped.items.length, 10);
|
||||
assert.equal(capped.items[0].id, 'r0');
|
||||
assert.equal(capped.items.at(-1).id, 'r9');
|
||||
// Everything outside the window: an empty list, not an error.
|
||||
assert.deepEqual(
|
||||
mergeFeedPage(
|
||||
{ items: [] },
|
||||
{ reports: [stale], nextBefore: null },
|
||||
'replace',
|
||||
NOW,
|
||||
).items,
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('filters default to significant news and map to a last-24-hours query', () => {
|
||||
const hotspots = [{ id: 'ua' }, { id: 'me' }];
|
||||
const filters = normalizeFilters(
|
||||
{ hotspot: 'ua', category: 'nope', minSeverity: 9 },
|
||||
hotspots,
|
||||
);
|
||||
assert.deepEqual(filters, {
|
||||
hotspot: 'ua',
|
||||
category: 'all',
|
||||
minSeverity: 2,
|
||||
section: 'conflicts',
|
||||
hours: null,
|
||||
});
|
||||
assert.equal(
|
||||
normalizeFilters({ section: 'local' }, hotspots).section,
|
||||
'local',
|
||||
);
|
||||
assert.equal(
|
||||
normalizeFilters({ section: 'nope' }, hotspots).section,
|
||||
'conflicts',
|
||||
);
|
||||
assert.equal(normalizeFilters({ hours: 6 }, hotspots).hours, 6);
|
||||
assert.equal(normalizeFilters({ hours: 5 }, hotspots).hours, null);
|
||||
assert.equal(normalizeFilters({ minSeverity: 0 }, hotspots).minSeverity, 0);
|
||||
assert.equal(normalizeFilters({ hotspot: 'gone' }, hotspots).hotspot, 'all');
|
||||
assert.equal(
|
||||
newsFeedQuery(
|
||||
feedQueryFor(filters, { before: '2026-10-28T08:00:00.000Z' }),
|
||||
),
|
||||
'hotspot=ua&before=2026-10-28T08%3A00%3A00.000Z&limit=60&relevance=core%2Crelated&today=1&events=1',
|
||||
);
|
||||
// The Conflicts feed reads the same whichever section is chosen.
|
||||
assert.equal(
|
||||
newsFeedQuery(feedQueryFor({ ...filters, section: 'local' })),
|
||||
newsFeedQuery(feedQueryFor(filters)),
|
||||
);
|
||||
});
|
||||
|
||||
test('only the last 24 hours pass, and the severity floor applies', () => {
|
||||
const filters = normalizeFilters();
|
||||
const fresh = report('f', '2026-10-28T09:00:00Z', { severity: 2 });
|
||||
const minor = report('m', '2026-10-28T09:00:00Z', { severity: 1 });
|
||||
const old = report('o', '2026-10-27T09:00:00Z', { severity: 3 });
|
||||
assert.equal(withinNewsWindow(fresh, NOW), true);
|
||||
assert.equal(withinNewsWindow(old, NOW), false);
|
||||
assert.equal(withinNewsWindow({ publishedAt: 'x' }, NOW), false);
|
||||
// Clock skew up to 15 min ahead passes; further ahead is not news yet.
|
||||
const skew = report('k', '2026-10-28T10:14:00Z');
|
||||
const future = report('z', '2026-10-28T10:16:00Z');
|
||||
assert.equal(withinNewsWindow(skew, NOW), true);
|
||||
assert.equal(withinNewsWindow(future, NOW), false);
|
||||
assert.deepEqual(
|
||||
[fresh, minor, old]
|
||||
.filter((r) => passesFilters(r, filters, NOW))
|
||||
.map((r) => r.id),
|
||||
['f'],
|
||||
);
|
||||
assert.equal(visibleOnMap(minor, { ...filters, minSeverity: 0 }, NOW), true);
|
||||
assert.equal(visibleOnMap(fresh, { ...filters, hotspot: 'me' }, NOW), false);
|
||||
});
|
||||
|
||||
test('ageWords says now, minutes or hours', () => {
|
||||
assert.equal(ageWords('2026-10-28T09:59:30Z', NOW), 'now');
|
||||
assert.equal(ageWords('2026-10-28T09:55:00Z', NOW), '5 min');
|
||||
assert.equal(ageWords('2026-10-28T07:10:00Z', NOW), '2 h');
|
||||
assert.equal(ageWords('2026-10-26T07:10:00Z', NOW), '24 h');
|
||||
assert.equal(ageWords('not a date', NOW), '');
|
||||
});
|
||||
|
||||
test('markers spread deterministically near their place; source link line', () => {
|
||||
const r = report('r_spread', '2026-10-28T10:00:00Z');
|
||||
const p1 = reportMarkerPosition(r);
|
||||
assert.deepEqual(reportMarkerPosition(r), p1);
|
||||
assert.ok(Math.abs(p1.lat - 50) < 0.02 && Math.abs(p1.lon - 36) < 0.04);
|
||||
assert.notDeepEqual(
|
||||
reportMarkerPosition(report('r_other', r.publishedAt)),
|
||||
p1,
|
||||
);
|
||||
assert.equal(
|
||||
sourceLinkLabel('https://www.reliefweb.int/report/x'),
|
||||
'Source: reliefweb.int ↗',
|
||||
);
|
||||
assert.equal(sourceLinkLabel('not a url'), '');
|
||||
});
|
||||
|
||||
test('beacons carry a focus, a size by activity and a trend only against a prior day', () => {
|
||||
const { hotspots } = normalizeHotspotsPayload({
|
||||
hotspots: [
|
||||
{
|
||||
id: 'a',
|
||||
name: 'A',
|
||||
bbox: [20, 40, 40, 50],
|
||||
focus: { lat: 45, lon: 30 },
|
||||
counts: { last24h: 120, prev24h: 80 },
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
name: 'B',
|
||||
bbox: [20, 40, 40, 50],
|
||||
focus: { lat: 80, lon: 30 },
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
hotspots.map((h) => h.focus),
|
||||
[
|
||||
{ lat: 45, lon: 30 },
|
||||
{ lat: 45, lon: 30 },
|
||||
],
|
||||
);
|
||||
assert.equal(hotspotTrend(120, 80), '▲');
|
||||
assert.equal(hotspotTrend(50, 80), '▼');
|
||||
assert.equal(hotspotTrend(85, 80), '');
|
||||
assert.equal(hotspotTrend(40, 0), '');
|
||||
assert.equal(beaconPixelSize(0), 10);
|
||||
assert.equal(beaconPixelSize(10_000), 26);
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'ua-ru-war', name: 'Russia–Ukraine war' }),
|
||||
'Ukraine–Russia',
|
||||
);
|
||||
assert.equal(hotspotLabel({ id: 'new-one', name: 'New one' }), 'New one');
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'x', name: 'X', catchAll: true }),
|
||||
'Elsewhere',
|
||||
);
|
||||
assert.equal(
|
||||
hotspotLabel({ id: 'worldwide', name: 'Worldwide', catchAll: true }),
|
||||
'Worldwide',
|
||||
);
|
||||
});
|
||||
|
||||
test('marker style: severity fill, attestation rim, size by sources, fading with age', () => {
|
||||
const r = report('r_style', '2026-10-28T10:00:00Z', {
|
||||
severity: 2,
|
||||
event: event({
|
||||
status: 'claimed',
|
||||
size: 4,
|
||||
lastAt: '2026-10-28T10:00:00Z',
|
||||
}),
|
||||
});
|
||||
const fresh = markerStyle(r, NOW);
|
||||
assert.equal(fresh.severity, 3); // the event's, when higher than the report's
|
||||
assert.equal(fresh.rim, 'claimed');
|
||||
assert.equal(fresh.size, eventPixelSize(4));
|
||||
// The icon is half the disc: no marker is too small to read it.
|
||||
assert.equal(eventPixelSize(1), 24);
|
||||
assert.equal(eventPixelSize(1000), 36);
|
||||
assert.equal(fresh.alpha, 1);
|
||||
assert.equal(markerStyle(r, NOW + 48 * 3_600_000).alpha, 0.45);
|
||||
assert.equal(reportSeverity({ category: 'political' }), 0);
|
||||
assert.equal(reportSeverity({ category: 'strike' }), 1);
|
||||
});
|
||||
|
||||
test('picture cards: physical, two or more sources, major or pressing, at most ten', () => {
|
||||
const big = report('big', '2026-10-28T09:30:00Z', { event: event() });
|
||||
const statement = report('st', '2026-10-28T09:30:00Z', {
|
||||
category: 'political',
|
||||
event: event(),
|
||||
});
|
||||
const lone = report('lone', '2026-10-28T09:30:00Z', {
|
||||
event: event({ size: 1 }),
|
||||
});
|
||||
const stale = report('stale', '2026-10-28T01:00:00Z', {
|
||||
event: event({ severity: 2, lastAt: '2026-10-28T01:00:00Z' }),
|
||||
});
|
||||
assert.equal(isPressing(big, NOW), true);
|
||||
assert.deepEqual(
|
||||
cardEvents([statement, lone, stale, big], NOW).map((r) => r.id),
|
||||
['big'],
|
||||
);
|
||||
const many = Array.from({ length: 14 }, (_, i) =>
|
||||
report(`m${i}`, '2026-10-28T09:30:00Z', { event: event() }),
|
||||
);
|
||||
assert.equal(cardEvents(many, NOW).length, 10);
|
||||
const view = cardView(big, NOW);
|
||||
assert.equal(view.image, 'https://a.test/p.jpg');
|
||||
assert.equal(view.credit, 'A');
|
||||
assert.equal(view.meta, '30 min · 6 sources · UA, RU');
|
||||
assert.equal(cardView(lone, NOW).image, null);
|
||||
});
|
||||
|
||||
test('feed cards: headline, meta parts, sides and chips', () => {
|
||||
const r = report('fc', '2026-10-28T09:00:00Z', {
|
||||
title: 'Удар по Харкову',
|
||||
titleEn: 'Strike on Kharkiv',
|
||||
affiliation: 'military',
|
||||
media: ['video', 'photo'],
|
||||
geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true, byModel: true },
|
||||
event: event({ lastAt: '2026-10-28T09:50:00Z' }),
|
||||
});
|
||||
const view = feedCardView(r, NOW);
|
||||
assert.equal(view.title, 'Strike on Kharkiv');
|
||||
assert.equal(view.original, 'Удар по Харкову');
|
||||
assert.equal(view.placedByModel, true);
|
||||
assert.equal(view.severityLabel, 'Major');
|
||||
assert.equal(view.color, '#ff4444');
|
||||
assert.equal(view.category, 'Strike');
|
||||
assert.equal(view.place, 'Kharkiv');
|
||||
assert.equal(view.sources, '6 sources');
|
||||
assert.equal(view.age, '10 min');
|
||||
assert.equal(view.sides, 'Reported by UA sources · RU sources');
|
||||
assert.deepEqual(view.picture, { url: 'https://a.test/p.jpg', credit: 'A' });
|
||||
assert.deepEqual(
|
||||
view.chips.map((c) => [c.kind, c.label]),
|
||||
[
|
||||
['official', 'Official'],
|
||||
['confirmed', 'Reported by both sides'],
|
||||
['media', 'Video'],
|
||||
['media', 'Photos'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
view.others.map((o) => o.side),
|
||||
['RU'],
|
||||
);
|
||||
// A lone report: its own side, no picture, one source.
|
||||
const single = feedCardView(report('s', '2026-10-28T09:00:00Z'), NOW);
|
||||
assert.equal(single.sides, 'Reported by UA sources');
|
||||
assert.equal(single.picture, null);
|
||||
// A one-source event (a Telegram post) shows its picture and its clip in
|
||||
// the panel, though the globe's picture cards need two sources.
|
||||
const post = report('p', '2026-10-28T09:00:00Z', {
|
||||
event: {
|
||||
size: 1,
|
||||
sides: [],
|
||||
image: {
|
||||
url: 'https://cdn4.telesco.pe/file/v.jpg',
|
||||
publisher: 'Channel',
|
||||
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(feedCardView(post, NOW).picture, {
|
||||
url: 'https://cdn4.telesco.pe/file/v.jpg',
|
||||
credit: 'Channel',
|
||||
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
});
|
||||
assert.equal(single.original, null);
|
||||
assert.equal(sidesLine({ side: 'unknown' }), '');
|
||||
});
|
||||
|
||||
test('event sides older than a day are left out of the card and its sides line', () => {
|
||||
const r = report('w', '2026-10-28T09:00:00Z', {
|
||||
event: event({
|
||||
sides: [
|
||||
{
|
||||
side: 'UA',
|
||||
title: 'a',
|
||||
url: 'https://a.test/',
|
||||
publisher: 'A',
|
||||
publishedAt: '2026-10-28T08:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'old',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-26T08:00:00Z',
|
||||
},
|
||||
{
|
||||
side: 'unknown',
|
||||
title: 'c',
|
||||
url: 'https://c.test/',
|
||||
publisher: 'C',
|
||||
publishedAt: '2026-10-28T09:10:00Z',
|
||||
},
|
||||
// No date: nothing shows it is recent.
|
||||
{ side: 'IL', title: 'd', url: 'https://d.test/', publisher: 'D' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const view = feedCardView(r, NOW);
|
||||
assert.deepEqual(
|
||||
view.others.map((o) => [o.side, o.title]),
|
||||
[['Unattributed', 'c']],
|
||||
);
|
||||
// The unattributed side is not named in the sides line.
|
||||
assert.equal(view.sides, 'Reported by UA sources');
|
||||
assert.equal(cardView(r, NOW).meta, '30 min · 6 sources · UA, Unattributed');
|
||||
// All sides outside the window: no others, the report's own side remains.
|
||||
const stale = report('v', '2026-10-28T09:00:00Z', {
|
||||
event: event({
|
||||
sides: [
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'old',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-26T08:00:00Z',
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
assert.deepEqual(feedCardView(stale, NOW).others, []);
|
||||
assert.equal(feedCardView(stale, NOW).sides, 'Reported by UA sources');
|
||||
});
|
||||
|
||||
test('in view: half-degree cells and reports within 500 km of the centre', () => {
|
||||
assert.equal(viewCell({ lat: 50.2, lon: 36.7 }), '100:73');
|
||||
assert.equal(viewCell({ lat: 50.4, lon: 36.9 }), '100:73');
|
||||
assert.notEqual(viewCell({ lat: 50.6, lon: 36.7 }), '100:73');
|
||||
assert.ok(
|
||||
Math.abs(distanceKm({ lat: 0, lon: 0 }, { lat: 0, lon: 1 }) - 111.2) < 0.5,
|
||||
);
|
||||
const filters = normalizeFilters({ minSeverity: 0 });
|
||||
const near = report('near', '2026-10-28T09:00:00Z', { severity: 1 });
|
||||
const major = report('major', '2026-10-28T08:00:00Z', { severity: 3 });
|
||||
const far = report('far', '2026-10-28T09:00:00Z', {
|
||||
pins: [{ lat: 31.5, lon: 34.4, place: 'Gaza', mappable: true }],
|
||||
});
|
||||
const old = report('old', '2026-10-27T08:00:00Z');
|
||||
const centre = { lat: 49, lon: 36 };
|
||||
assert.ok(distanceKm(centre, far.pins[0]) > NEWS_IN_VIEW_RADIUS_KM);
|
||||
assert.deepEqual(
|
||||
reportsInView([near, far, old, major], centre, filters, NOW).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
['near', 'major'],
|
||||
);
|
||||
assert.deepEqual(reportsInView([near], null, filters, NOW), []);
|
||||
assert.deepEqual(reportsInView([], centre, filters, NOW), []);
|
||||
});
|
||||
|
||||
test('a server may serve fewer hours than the day, never more', () => {
|
||||
assert.equal(newsWindowMs(12), 12 * 3_600_000);
|
||||
assert.equal(newsWindowMs(24), 24 * 3_600_000);
|
||||
for (const bad of [0, 25, 12.5, '12', null, undefined])
|
||||
assert.equal(newsWindowMs(bad), 24 * 3_600_000);
|
||||
const page = {
|
||||
reports: [
|
||||
report('fresh', '2026-10-28T02:00:00Z'),
|
||||
report('old', '2026-10-27T20:00:00Z'),
|
||||
],
|
||||
nextBefore: null,
|
||||
};
|
||||
const empty = { items: [], nextBefore: null };
|
||||
const ids = (windowMs) =>
|
||||
mergeFeedPage(empty, page, 'replace', NOW, undefined, windowMs).items.map(
|
||||
(r) => r.id,
|
||||
);
|
||||
assert.deepEqual(ids(newsWindowMs(12)), ['fresh']);
|
||||
assert.deepEqual(ids(newsWindowMs(24)), ['fresh', 'old']);
|
||||
});
|
||||
|
||||
test('the hotspots answer carries the window it was counted over', () => {
|
||||
const base = {
|
||||
hotspots: [],
|
||||
ingest: { lastRunAt: '2026-10-28T09:00:00Z' },
|
||||
};
|
||||
assert.equal(
|
||||
normalizeHotspotsPayload({ ...base, windowHours: 12 }).windowHours,
|
||||
12,
|
||||
);
|
||||
assert.equal(normalizeHotspotsPayload(base).windowHours, null);
|
||||
assert.equal(
|
||||
normalizeHotspotsPayload({ ...base, windowHours: 48 }).windowHours,
|
||||
null,
|
||||
);
|
||||
const shorter = normalizeHotspotsPayload({
|
||||
...base,
|
||||
windowHours: 3,
|
||||
maxWindowHours: 12,
|
||||
});
|
||||
assert.deepEqual([shorter.windowHours, shorter.maxWindowHours], [3, 12]);
|
||||
assert.equal(normalizeHotspotsPayload(base).maxWindowHours, null);
|
||||
});
|
||||
|
||||
test('the window choices stop at the window the server serves', () => {
|
||||
assert.deepEqual(newsWindowChoices(24), [24, 12, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(12), [12, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(8), [8, 6, 3, 1]);
|
||||
assert.deepEqual(newsWindowChoices(1), [1]);
|
||||
assert.deepEqual(newsWindowChoices(null), [24, 12, 6, 3, 1]);
|
||||
});
|
||||
|
||||
test('a checked severity keeps saying who set it', () => {
|
||||
const page = normalizeFeedPayload({
|
||||
reports: ['label', 'model', 'guess'].map((by, i) => ({
|
||||
...report(`r${i}`, '2026-10-28T09:00:00Z'),
|
||||
severity: 2,
|
||||
severityBy: by,
|
||||
})),
|
||||
});
|
||||
assert.deepEqual(
|
||||
page.reports.map((r) => r.severityBy),
|
||||
['label', 'model', 'rules'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
// Validate /api/news payloads before they reach the scene or the DOM. Every
|
||||
// string is bounded, every URL is http(s), every position is finite; a record
|
||||
// that fails is dropped, a payload that fails is rejected whole. A portable
|
||||
// export (layers/news/source): no i18n here.
|
||||
|
||||
const CATEGORY = /^[a-z][a-z-]{1,31}$/;
|
||||
const CODE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
|
||||
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
||||
const EVENT_STATUSES = Object.freeze([
|
||||
'both-sides',
|
||||
'independent',
|
||||
'claimed',
|
||||
'reported',
|
||||
'side',
|
||||
'single',
|
||||
]);
|
||||
|
||||
const text = (value, max) =>
|
||||
typeof value === 'string' && value.trim()
|
||||
? value.replace(/\s+/g, ' ').trim().slice(0, max)
|
||||
: null;
|
||||
const finite = (value, min, max) =>
|
||||
Number.isFinite(value) && value >= min && value <= max ? value : null;
|
||||
const iso = (value) => {
|
||||
const ms = Date.parse(value);
|
||||
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
||||
};
|
||||
const code = (value) =>
|
||||
typeof value === 'string' && CODE.test(value) ? value : null;
|
||||
const severity = (value) =>
|
||||
Number.isInteger(value) && value >= 0 && value <= 3 ? value : null;
|
||||
|
||||
/** An http(s) URL without credentials, as its normalised href, or null. */
|
||||
export function httpUrl(value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return ['http:', 'https:'].includes(url.protocol) &&
|
||||
!url.username &&
|
||||
!url.password
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBbox(bbox) {
|
||||
if (!Array.isArray(bbox) || bbox.length !== 4) return null;
|
||||
const [west, south, east, north] = bbox;
|
||||
if (
|
||||
finite(west, -180, 180) === null ||
|
||||
finite(east, -180, 180) === null ||
|
||||
finite(south, -90, 90) === null ||
|
||||
finite(north, -90, 90) === null ||
|
||||
west >= east ||
|
||||
south >= north
|
||||
)
|
||||
return null;
|
||||
return [west, south, east, north];
|
||||
}
|
||||
|
||||
/** Beacon position: the curated focus point, else the bbox centre. */
|
||||
function normalizeFocus(focus, [west, south, east, north]) {
|
||||
const lat = finite(focus?.lat, south, north);
|
||||
const lon = finite(focus?.lon, west, east);
|
||||
return lat !== null && lon !== null
|
||||
? { lat, lon }
|
||||
: { lat: (south + north) / 2, lon: (west + east) / 2 };
|
||||
}
|
||||
|
||||
function normalizeDeveloping(items) {
|
||||
const out = [];
|
||||
for (const raw of Array.isArray(items) ? items.slice(0, 16) : []) {
|
||||
const lat = finite(raw?.focus?.lat, -90, 90);
|
||||
const lon = finite(raw?.focus?.lon, -180, 180);
|
||||
const country =
|
||||
typeof raw?.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
|
||||
? raw.country
|
||||
: null;
|
||||
if (lat === null || lon === null || !country) continue;
|
||||
// A state where the catch-all flags states ("US-FL"), else the country.
|
||||
const area =
|
||||
typeof raw.area === 'string' && /^[A-Z]{2}-[A-Z0-9]{1,3}$/.test(raw.area)
|
||||
? raw.area
|
||||
: null;
|
||||
out.push({
|
||||
country,
|
||||
key: area || country,
|
||||
name: text(raw.name, 80) || country,
|
||||
events: Math.max(0, Math.floor(Number(raw.events) || 0)),
|
||||
reports: Math.max(0, Math.floor(Number(raw.reports) || 0)),
|
||||
focus: { lat, lon },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const hoursOrNull = (hours) =>
|
||||
Number.isInteger(hours) && hours >= 1 && hours <= 24 ? hours : null;
|
||||
|
||||
/**
|
||||
* `/api/news/hotspots` → `{hotspots, categories, lastRunAt, windowHours,
|
||||
* maxWindowHours}`, or null when the payload has no hotspot list.
|
||||
* `windowHours` is the window the counts cover and `maxWindowHours` the
|
||||
* longest the server serves this reader; each is null when the server names
|
||||
* none.
|
||||
*/
|
||||
export function normalizeHotspotsPayload(payload) {
|
||||
if (!Array.isArray(payload?.hotspots)) return null;
|
||||
const hotspots = [];
|
||||
for (const raw of payload.hotspots.slice(0, 64)) {
|
||||
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
|
||||
const name = text(raw?.name, 80);
|
||||
const bbox = normalizeBbox(raw?.bbox);
|
||||
if (!id || !name || !bbox) continue;
|
||||
const counts = raw.counts || {};
|
||||
hotspots.push({
|
||||
id,
|
||||
name,
|
||||
kind: text(raw.kind, 16) || 'conflict',
|
||||
catchAll: raw.catchAll === true,
|
||||
developing: normalizeDeveloping(raw.developing),
|
||||
bbox,
|
||||
parties: Array.isArray(raw.parties)
|
||||
? raw.parties.filter((p) => code(p))
|
||||
: [],
|
||||
last24h: Math.max(0, Math.floor(Number(counts.last24h) || 0)),
|
||||
mapped24h: Math.max(0, Math.floor(Number(counts.mapped24h) || 0)),
|
||||
prev24h: Number.isFinite(counts.prev24h)
|
||||
? Math.max(0, Math.floor(counts.prev24h))
|
||||
: null,
|
||||
focus: normalizeFocus(raw.focus, bbox),
|
||||
latestAt: iso(raw.latestAt),
|
||||
});
|
||||
}
|
||||
return {
|
||||
hotspots,
|
||||
categories: Array.isArray(payload.categories)
|
||||
? payload.categories.filter(
|
||||
(c) => typeof c === 'string' && CATEGORY.test(c),
|
||||
)
|
||||
: [],
|
||||
lastRunAt: iso(payload.ingest?.lastRunAt),
|
||||
windowHours: hoursOrNull(payload.windowHours),
|
||||
maxWindowHours: hoursOrNull(payload.maxWindowHours),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeGeo(geo) {
|
||||
if (!geo || typeof geo !== 'object') return null;
|
||||
const lat = finite(geo.lat, -90, 90);
|
||||
const lon = finite(geo.lon, -180, 180);
|
||||
if (lat === null || lon === null) return null;
|
||||
return {
|
||||
lat,
|
||||
lon,
|
||||
place: text(geo.place, 80),
|
||||
precision: text(geo.precision, 16) || 'city',
|
||||
confidence: finite(geo.confidence, 0, 1) ?? 0,
|
||||
mappable: geo.mappable === true,
|
||||
byModel: geo.method === 'llm',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The event's picture: an HTTPS URL on the publisher's site, and whose it is;
|
||||
* with the post's own clip when it has one a browser plays itself (an HTTPS
|
||||
* MP4 or WebM file), the picture then its poster.
|
||||
*/
|
||||
function eventImage(image) {
|
||||
const url = httpUrl(image?.url);
|
||||
if (!url?.startsWith('https://')) return null;
|
||||
const video = httpUrl(image.video);
|
||||
const playable =
|
||||
video?.startsWith('https://') &&
|
||||
/\.(?:mp4|m4v|webm)$/i.test(new URL(video).pathname);
|
||||
return {
|
||||
url,
|
||||
publisher: text(image.publisher, 80) || '',
|
||||
...(playable ? { video } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** An event summary from `/feed?events=1`: size and one report per side. */
|
||||
function normalizeEvent(event) {
|
||||
if (!event || typeof event !== 'object') return null;
|
||||
const count = (value) => Math.max(1, Math.floor(Number(value) || 1));
|
||||
const sides = [];
|
||||
for (const side of Array.isArray(event.sides)
|
||||
? event.sides.slice(0, 8)
|
||||
: []) {
|
||||
const url = httpUrl(side?.url);
|
||||
const title = text(side?.title, 300);
|
||||
if (!url || !title) continue;
|
||||
sides.push({
|
||||
side: code(side.side) || 'unknown',
|
||||
title,
|
||||
url,
|
||||
publisher: text(side.publisher, 80) || '',
|
||||
publishedAt: iso(side.publishedAt),
|
||||
});
|
||||
}
|
||||
return {
|
||||
id: typeof event.id === 'string' && ID.test(event.id) ? event.id : null,
|
||||
status: EVENT_STATUSES.includes(event.status) ? event.status : null,
|
||||
claimedBy: text(event.claimedBy, 80),
|
||||
reportedSide: code(event.reportedSide),
|
||||
size: count(event.size),
|
||||
reports: count(event.reports),
|
||||
severity: severity(event.severity),
|
||||
firstAt: iso(event.firstAt),
|
||||
lastAt: iso(event.lastAt),
|
||||
sides,
|
||||
image: eventImage(event.image),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeReport(raw) {
|
||||
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
|
||||
const title = text(raw?.title, 300);
|
||||
const url = httpUrl(raw?.url);
|
||||
const publishedAt = iso(raw?.publishedAt);
|
||||
if (!id || !title || !url || !publishedAt) return null;
|
||||
const source = raw.source || {};
|
||||
const geo = normalizeGeo(raw.geo);
|
||||
// Map positions: the report's own place plus any other hotspot its title
|
||||
// names (a roundup is pinned in each).
|
||||
const pins = [];
|
||||
for (const place of [
|
||||
geo,
|
||||
...(Array.isArray(raw.locations)
|
||||
? raw.locations.slice(0, 8).map(normalizeGeo)
|
||||
: []),
|
||||
])
|
||||
if (
|
||||
place?.mappable &&
|
||||
!pins.some((p) => p.lat === place.lat && p.lon === place.lon)
|
||||
)
|
||||
pins.push(place);
|
||||
const hotspotId = typeof raw.hotspotId === 'string' ? raw.hotspotId : null;
|
||||
return {
|
||||
id,
|
||||
hotspotId,
|
||||
hotspotIds: Array.isArray(raw.hotspotIds)
|
||||
? raw.hotspotIds.filter((h) => typeof h === 'string').slice(0, 8)
|
||||
: [hotspotId].filter(Boolean),
|
||||
title,
|
||||
url,
|
||||
snippet: text(raw.snippet, 400),
|
||||
publisher: text(raw.publisher, 80) || text(source.name, 80) || '',
|
||||
sourceName: text(source.name, 80) || text(raw.publisher, 80) || '',
|
||||
kind: text(raw.kind, 16) || 'rss',
|
||||
side: code(raw.side) || 'unknown',
|
||||
affiliation: text(raw.affiliation, 32),
|
||||
attribution: text(source.attribution, 120),
|
||||
category:
|
||||
typeof raw.category === 'string' && CATEGORY.test(raw.category)
|
||||
? raw.category
|
||||
: 'other',
|
||||
publishedAt,
|
||||
geo,
|
||||
pins,
|
||||
event: normalizeEvent(raw.event),
|
||||
titleEn: text(raw.titleEn, 200),
|
||||
relevance: ['core', 'related', 'minor'].includes(raw.relevance)
|
||||
? raw.relevance
|
||||
: 'related',
|
||||
severity: severity(raw.severity),
|
||||
severityBy: ['model', 'label'].includes(raw.severityBy)
|
||||
? raw.severityBy
|
||||
: 'rules',
|
||||
claim:
|
||||
raw.claim && typeof raw.claim === 'object'
|
||||
? { by: text(raw.claim.by, 80) }
|
||||
: null,
|
||||
media: Array.isArray(raw.media)
|
||||
? [...new Set(raw.media.filter((m) => m === 'video' || m === 'photo'))]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRing(ring) {
|
||||
if (!Array.isArray(ring) || ring.length < 3) return null;
|
||||
const points = [];
|
||||
for (const point of ring.slice(0, 20_000)) {
|
||||
const lon = finite(point?.[0], -180, 180);
|
||||
const lat = finite(point?.[1], -90, 90);
|
||||
if (lon !== null && lat !== null) points.push([lon, lat]);
|
||||
}
|
||||
return points.length >= 3 ? points : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `/api/news/outline` → `{polygons, borders, disputed, area}`: the dissolved
|
||||
* extent (`{outer, holes}`), the national borders inside it (rings), its
|
||||
* disputed areas and, answering a point, the area named there (else null),
|
||||
* invalid parts dropped.
|
||||
*/
|
||||
export function normalizeOutlinePayload(payload) {
|
||||
const polygons = [];
|
||||
// Above every country's island count (Indonesia's is 208): an outline cut
|
||||
// short leaves islands outside the area, read again on each settle there.
|
||||
for (const raw of Array.isArray(payload?.polygons)
|
||||
? payload.polygons.slice(0, 300)
|
||||
: []) {
|
||||
const outer = normalizeRing(raw?.outer);
|
||||
if (!outer) continue;
|
||||
const holes = (Array.isArray(raw.holes) ? raw.holes.slice(0, 200) : [])
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
polygons.push({ outer, holes });
|
||||
}
|
||||
const borders = (
|
||||
Array.isArray(payload?.borders) ? payload.borders.slice(0, 50) : []
|
||||
)
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
const KINDS = ['held', 'self', 'un', 'unclaimed'];
|
||||
const country = (value) =>
|
||||
typeof value === 'string' && /^[A-Z]{2}$/.test(value) ? value : null;
|
||||
const disputed = [];
|
||||
for (const raw of Array.isArray(payload?.disputed)
|
||||
? payload.disputed.slice(0, 30)
|
||||
: []) {
|
||||
const rings = (Array.isArray(raw?.rings) ? raw.rings.slice(0, 20) : [])
|
||||
.map(normalizeRing)
|
||||
.filter(Boolean);
|
||||
const name = text(raw?.name, 60);
|
||||
if (!rings.length || !name) continue;
|
||||
disputed.push({
|
||||
name,
|
||||
kind: KINDS.includes(raw.kind) ? raw.kind : 'held',
|
||||
heldBy: country(raw.heldBy),
|
||||
claimedBy: country(raw.claimedBy),
|
||||
rings,
|
||||
});
|
||||
}
|
||||
return { polygons, borders, disputed, area: outlineArea(payload?.area) };
|
||||
}
|
||||
|
||||
const AREA_KINDS = ['country', 'region', 'disputed'];
|
||||
function outlineArea(raw) {
|
||||
const key = text(raw?.key, 80);
|
||||
const name = text(raw?.name, 80);
|
||||
if (!key || !name) return null;
|
||||
return {
|
||||
key,
|
||||
name,
|
||||
kind: AREA_KINDS.includes(raw.kind) ? raw.kind : 'country',
|
||||
country:
|
||||
typeof raw.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
|
||||
? raw.country
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** `/api/news/feed` → `{reports, nextBefore}`, or null without a report list. */
|
||||
export function normalizeFeedPayload(payload) {
|
||||
if (!Array.isArray(payload?.reports)) return null;
|
||||
const reports = [];
|
||||
for (const raw of payload.reports.slice(0, 500)) {
|
||||
const report = normalizeReport(raw);
|
||||
if (report) reports.push(report);
|
||||
}
|
||||
return { reports, nextBefore: iso(payload.nextBefore) };
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { isUnavailableCapability } from '../../sources/capability.js';
|
||||
import {
|
||||
normalizeFeedPayload,
|
||||
normalizeHotspotsPayload,
|
||||
normalizeOutlinePayload,
|
||||
} from './records.js';
|
||||
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the layer shows them translated.
|
||||
const msg = (text) => text;
|
||||
|
||||
const MAX_BYTES = 4 * 1024 * 1024;
|
||||
const BASE_PATH = '/api/news';
|
||||
// The outline geometry version the client draws (disputed areas included).
|
||||
const OUTLINE_VERSION = '4';
|
||||
|
||||
/** The three read routes the news layer calls, for a host's path allowlist. */
|
||||
export const NEWS_API_PATHS = Object.freeze([
|
||||
`${BASE_PATH}/hotspots`,
|
||||
`${BASE_PATH}/feed`,
|
||||
`${BASE_PATH}/outline`,
|
||||
]);
|
||||
|
||||
const FEED_KEYS = Object.freeze([
|
||||
'hotspot',
|
||||
'before',
|
||||
'since',
|
||||
'limit',
|
||||
'category',
|
||||
'relevance',
|
||||
'at',
|
||||
]);
|
||||
const FLAG_KEYS = Object.freeze(['geo', 'today', 'events']);
|
||||
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
|
||||
const LIST = /^[a-z][a-z,-]{0,127}$/;
|
||||
// A point to two decimals (~1 km), as areaPoint writes it.
|
||||
const AT = /^-?\d{1,2}(?:\.\d{1,2})?,-?\d{1,3}(?:\.\d{1,2})?$/;
|
||||
// A coordinate to two decimals, without trailing zeros ("50.4", "-97.74").
|
||||
const areaPoint = (value) => String(Math.round(value * 100) / 100);
|
||||
const FEED_VALUE = {
|
||||
hotspot: (v) => /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(v),
|
||||
before: (v) => ISO.test(v),
|
||||
since: (v) => ISO.test(v),
|
||||
limit: (v) => /^\d{1,3}$/.test(v) && Number(v) >= 1 && Number(v) <= 500,
|
||||
category: (v) => LIST.test(v),
|
||||
relevance: (v) => LIST.test(v),
|
||||
at: (v) => AT.test(v),
|
||||
};
|
||||
|
||||
/**
|
||||
* Feed query string from a plain object; unknown keys and empty values are
|
||||
* dropped. `at` is a point (`{lat, lon}`), the Local section's area there.
|
||||
*/
|
||||
export function newsFeedQuery(query = {}) {
|
||||
const params = new URLSearchParams();
|
||||
for (const key of FEED_KEYS) {
|
||||
const value =
|
||||
key === 'at' && query.at
|
||||
? `${areaPoint(query.at.lat)},${areaPoint(query.at.lon)}`
|
||||
: query[key];
|
||||
if (value !== undefined && value !== null && value !== '')
|
||||
params.set(key, String(value));
|
||||
}
|
||||
for (const key of FLAG_KEYS) if (query[key]) params.set(key, '1');
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request URL is one this client sends: a known route, known keys
|
||||
* only, each value in its form. A host proxying the routes can admit exactly
|
||||
* these and refuse the rest.
|
||||
* @param {URL} url
|
||||
*/
|
||||
export function newsQueryAllowed(url) {
|
||||
const params = [...url.searchParams];
|
||||
if (new Set(params.map(([key]) => key)).size !== params.length) return false;
|
||||
if (url.pathname === `${BASE_PATH}/hotspots`)
|
||||
return (
|
||||
params.length === 0 ||
|
||||
(params.length === 1 &&
|
||||
params[0][0] === 'hours' &&
|
||||
/^\d{1,2}$/.test(params[0][1]) &&
|
||||
Number(params[0][1]) >= 1 &&
|
||||
Number(params[0][1]) <= 24)
|
||||
);
|
||||
if (url.pathname === `${BASE_PATH}/outline`) {
|
||||
const keys = params.map(([key]) => key).sort();
|
||||
const value = url.searchParams;
|
||||
return (
|
||||
params.length === 2 &&
|
||||
keys[1] === 'v' &&
|
||||
value.get('v') === OUTLINE_VERSION &&
|
||||
((keys[0] === 'hotspot' && FEED_VALUE.hotspot(value.get('hotspot'))) ||
|
||||
(keys[0] === 'country' &&
|
||||
/^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/.test(value.get('country'))) ||
|
||||
(keys[0] === 'at' && AT.test(value.get('at'))))
|
||||
);
|
||||
}
|
||||
if (url.pathname !== `${BASE_PATH}/feed`) return false;
|
||||
return params.every(([key, value]) =>
|
||||
FLAG_KEYS.includes(key)
|
||||
? value === '1'
|
||||
: Object.hasOwn(FEED_VALUE, key) && FEED_VALUE[key](value),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed read: a server without the news routes is a permanent miss; one
|
||||
* that reads a section from a key it lacks (503 `no_key`, `key_rejected` or,
|
||||
* its allowance for the day spent, `key_quota`, naming the key registry's id)
|
||||
* says which, and is asked again later.
|
||||
*/
|
||||
async function responseError(response) {
|
||||
let body = null;
|
||||
try {
|
||||
body = await readResponseJsonCapped(response, 16 * 1024);
|
||||
} catch {
|
||||
await response.body?.cancel?.().catch?.(() => {});
|
||||
}
|
||||
if (
|
||||
response.status === 503 &&
|
||||
['no_key', 'key_rejected', 'key_quota'].includes(body?.error) &&
|
||||
typeof body.key === 'string' &&
|
||||
/^[a-z][a-z0-9-]{0,31}$/.test(body.key)
|
||||
)
|
||||
return Object.assign(new Error(msg('News key required')), {
|
||||
status: 503,
|
||||
code: body.error,
|
||||
keyRequired: true,
|
||||
keyRejected: body.error === 'key_rejected',
|
||||
keyQuota: body.error === 'key_quota',
|
||||
keyId: body.key,
|
||||
unavailable: false,
|
||||
retryable: true,
|
||||
});
|
||||
const unavailable =
|
||||
response.status === 404 ||
|
||||
(response.status === 503 && isUnavailableCapability(body));
|
||||
return Object.assign(
|
||||
new Error(
|
||||
unavailable
|
||||
? msg('News feed not configured on this server')
|
||||
: msg('News feed unavailable'),
|
||||
),
|
||||
{
|
||||
status: response.status,
|
||||
code: unavailable ? 'unavailable' : 'http',
|
||||
unavailable,
|
||||
retryable: !unavailable,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Read hotspots, reports and outlines from the server's /api/news routes. */
|
||||
export function createNewsSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
timeoutMs = 15_000,
|
||||
} = {}) {
|
||||
async function get(path, { signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const timeout = AbortSignal.timeout(timeoutMs);
|
||||
const request = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
||||
try {
|
||||
const response = await fetchImpl(`${BASE_PATH}${path}`, {
|
||||
signal: request,
|
||||
cache: 'no-store',
|
||||
redirect: 'error',
|
||||
});
|
||||
if (!response.ok) throw await responseError(response);
|
||||
return await readResponseJsonCapped(response, MAX_BYTES, request);
|
||||
} catch (cause) {
|
||||
// Out of time the feed reads unavailable, not the browser's own words
|
||||
// ("signal timed out"); the caller's own abort stays an abort.
|
||||
if (timeout.aborted && !signal?.aborted)
|
||||
throw Object.assign(new Error(msg('News feed unavailable')), {
|
||||
code: 'timeout',
|
||||
unavailable: false,
|
||||
retryable: true,
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
return {
|
||||
// `hours` asks for counts over a shorter window than the server's own.
|
||||
async getHotspots({ signal, hours } = {}) {
|
||||
const payload = normalizeHotspotsPayload(
|
||||
await get(hours ? `/hotspots?hours=${hours}` : '/hotspots', {
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
if (!payload) throw new Error(msg('Malformed news hotspots response'));
|
||||
return payload;
|
||||
},
|
||||
async getOutline(hotspotId, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?hotspot=${encodeURIComponent(hotspotId)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
async getCountryOutline(country, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?country=${encodeURIComponent(country)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
// The area the Local section reads at a point, with its outline.
|
||||
async getAreaOutline({ lat, lon }, { signal } = {}) {
|
||||
return normalizeOutlinePayload(
|
||||
await get(
|
||||
`/outline?at=${areaPoint(lat)},${areaPoint(lon)}&v=${OUTLINE_VERSION}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
},
|
||||
async getFeed(query = {}, { signal } = {}) {
|
||||
const payload = normalizeFeedPayload(
|
||||
await get(`/feed?${newsFeedQuery(query)}`, { signal }),
|
||||
);
|
||||
if (!payload) throw new Error(msg('Malformed news feed response'));
|
||||
return payload;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
NEWS_API_PATHS,
|
||||
createNewsSource,
|
||||
newsFeedQuery,
|
||||
newsQueryAllowed,
|
||||
} from './source.js';
|
||||
|
||||
const json = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
function recorder(respond) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
fetchImpl: async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
return respond(url, init);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('reads validated hotspots, feed and outlines from the same-origin routes', async () => {
|
||||
const { calls, fetchImpl } = recorder((url) => {
|
||||
if (url.startsWith('/api/news/hotspots'))
|
||||
return json({
|
||||
hotspots: [{ id: 'ua', name: 'UA', bbox: [22, 44, 42, 56] }],
|
||||
});
|
||||
if (url.startsWith('/api/news/feed'))
|
||||
return json({
|
||||
reports: [
|
||||
{
|
||||
id: 'r1',
|
||||
title: 'T',
|
||||
url: 'https://x.test/',
|
||||
publishedAt: '2026-10-28T09:00:00Z',
|
||||
},
|
||||
],
|
||||
nextBefore: null,
|
||||
});
|
||||
return json({ polygons: [], borders: [], disputed: [] });
|
||||
});
|
||||
const source = createNewsSource({ fetchImpl });
|
||||
assert.equal((await source.getHotspots()).hotspots[0].id, 'ua');
|
||||
assert.equal(
|
||||
(await source.getFeed({ hotspot: 'all', today: true, limit: 60 }))
|
||||
.reports[0].id,
|
||||
'r1',
|
||||
);
|
||||
assert.deepEqual((await source.getOutline('ua')).polygons, []);
|
||||
await source.getCountryOutline('SD');
|
||||
await source.getHotspots({ hours: 6 });
|
||||
await source.getAreaOutline({ lat: 30.26666, lon: -97.7 });
|
||||
await source.getFeed({ hotspot: 'all', at: { lat: 30.26666, lon: -97.7 } });
|
||||
assert.deepEqual(
|
||||
calls.map((c) => c.url),
|
||||
[
|
||||
'/api/news/hotspots',
|
||||
'/api/news/feed?hotspot=all&limit=60&today=1',
|
||||
'/api/news/outline?hotspot=ua&v=4',
|
||||
'/api/news/outline?country=SD&v=4',
|
||||
'/api/news/hotspots?hours=6',
|
||||
'/api/news/outline?at=30.27,-97.7&v=4',
|
||||
'/api/news/feed?hotspot=all&at=30.27%2C-97.7',
|
||||
],
|
||||
);
|
||||
for (const { url, init } of calls) {
|
||||
assert.equal(init.redirect, 'error');
|
||||
assert.equal(init.cache, 'no-store');
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
// Every URL the client sends is one a host's allowlist admits.
|
||||
assert.equal(newsQueryAllowed(new URL(url, 'http://h')), true, url);
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed, failed and unconfigured reads reject; a server without news is a permanent miss', async () => {
|
||||
const malformed = createNewsSource({ fetchImpl: async () => json({}) });
|
||||
await assert.rejects(malformed.getHotspots(), /Malformed news hotspots/);
|
||||
await assert.rejects(malformed.getFeed(), /Malformed news feed/);
|
||||
|
||||
const down = createNewsSource({
|
||||
fetchImpl: async () => json({ error: 'upstream' }, 502),
|
||||
});
|
||||
await assert.rejects(down.getHotspots(), (error) => {
|
||||
assert.equal(error.message, 'News feed unavailable');
|
||||
assert.equal(error.retryable, true);
|
||||
assert.equal(error.unavailable, false);
|
||||
return true;
|
||||
});
|
||||
|
||||
const unconfigured = createNewsSource({
|
||||
fetchImpl: async () =>
|
||||
json(
|
||||
{ error: 'news_not_configured', unavailable: true, retryable: false },
|
||||
503,
|
||||
),
|
||||
});
|
||||
await assert.rejects(unconfigured.getHotspots(), (error) => {
|
||||
assert.equal(error.message, 'News feed not configured on this server');
|
||||
assert.equal(error.code, 'unavailable');
|
||||
assert.equal(error.unavailable, true);
|
||||
assert.equal(error.retryable, false);
|
||||
return true;
|
||||
});
|
||||
const missing = createNewsSource({
|
||||
fetchImpl: async () => new Response('Not found', { status: 404 }),
|
||||
});
|
||||
await assert.rejects(missing.getFeed(), { unavailable: true });
|
||||
const broken = createNewsSource({
|
||||
fetchImpl: async () => new Response('{', { status: 200 }),
|
||||
});
|
||||
await assert.rejects(broken.getHotspots(), SyntaxError);
|
||||
});
|
||||
|
||||
test('a section read from a key the server lacks names the key and is asked again', async () => {
|
||||
const answer = (body) =>
|
||||
createNewsSource({
|
||||
fetchImpl: async () =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
});
|
||||
await assert.rejects(
|
||||
answer({ error: 'no_key', key: 'liveuamap' }).getHotspots(),
|
||||
(error) => {
|
||||
assert.equal(error.keyRequired, true);
|
||||
assert.equal(error.keyRejected, false);
|
||||
assert.equal(error.keyId, 'liveuamap');
|
||||
assert.equal(error.unavailable, false);
|
||||
assert.equal(error.retryable, true);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
await assert.rejects(
|
||||
answer({ error: 'key_rejected', key: 'worldnewsapi' }).getFeed({
|
||||
at: { lat: 51.13, lon: 71.43 },
|
||||
}),
|
||||
{ keyRequired: true, keyRejected: true, keyId: 'worldnewsapi' },
|
||||
);
|
||||
// The day's allowance spent: still the key's matter, back tomorrow.
|
||||
await assert.rejects(
|
||||
answer({ error: 'key_quota', key: 'worldnewsapi' }).getFeed(),
|
||||
{
|
||||
keyRequired: true,
|
||||
keyRejected: false,
|
||||
keyQuota: true,
|
||||
keyId: 'worldnewsapi',
|
||||
unavailable: false,
|
||||
},
|
||||
);
|
||||
// A key name not in the registry's form is an ordinary failure.
|
||||
await assert.rejects(
|
||||
answer({ error: 'no_key', key: '<script>' }).getHotspots(),
|
||||
(error) => error.keyRequired === undefined && error.code === 'http',
|
||||
);
|
||||
});
|
||||
|
||||
test('reads time out and follow the caller signal', async () => {
|
||||
// AbortSignal.timeout does not hold the event loop open: the hanging fetch
|
||||
// does, until its signal aborts, so the run cannot end before it.
|
||||
const hang = (_url, { signal }) =>
|
||||
new Promise((_, reject) => {
|
||||
const alive = setTimeout(() => {}, 60_000);
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(alive);
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
const slow = createNewsSource({ fetchImpl: hang, timeoutMs: 20 });
|
||||
// Out of time it reads unavailable, in the app's words, as retryable.
|
||||
await assert.rejects(slow.getHotspots(), {
|
||||
message: 'News feed unavailable',
|
||||
code: 'timeout',
|
||||
retryable: true,
|
||||
});
|
||||
// The caller's abort stays its own, even once the time is up too.
|
||||
const late = (_url, { signal }) =>
|
||||
new Promise((_, reject) => {
|
||||
setTimeout(() => reject(signal.reason), 40);
|
||||
});
|
||||
const leaving = new AbortController();
|
||||
const gone = createNewsSource({ fetchImpl: late, timeoutMs: 20 }).getFeed(
|
||||
{},
|
||||
{ signal: leaving.signal },
|
||||
);
|
||||
leaving.abort(new Error('gone'));
|
||||
await assert.rejects(gone, /gone/);
|
||||
const caller = new AbortController();
|
||||
const pending = createNewsSource({ fetchImpl: hang }).getFeed(
|
||||
{},
|
||||
{ signal: caller.signal },
|
||||
);
|
||||
caller.abort(new Error('gone'));
|
||||
await assert.rejects(pending, /gone/);
|
||||
await assert.rejects(
|
||||
createNewsSource({ fetchImpl: hang }).getHotspots({
|
||||
signal: AbortSignal.abort(new Error('already')),
|
||||
}),
|
||||
/already/,
|
||||
);
|
||||
});
|
||||
|
||||
test('the host allowlist admits the client routes and refuses anything else', () => {
|
||||
const allowed = (path) => newsQueryAllowed(new URL(path, 'http://h'));
|
||||
assert.deepEqual(NEWS_API_PATHS, [
|
||||
'/api/news/hotspots',
|
||||
'/api/news/feed',
|
||||
'/api/news/outline',
|
||||
]);
|
||||
assert.equal(
|
||||
allowed(
|
||||
`/api/news/feed?${newsFeedQuery({ hotspot: 'ua-ru-war', before: '2026-10-28T08:00:00.000Z', limit: 500, category: 'strike', relevance: 'core,related', geo: true, today: true, events: true })}`,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(allowed('/api/news/hotspots?hours=6'), true);
|
||||
for (const path of [
|
||||
'/api/news/hotspots?hours=0',
|
||||
'/api/news/hotspots?hours=25',
|
||||
'/api/news/hotspots?hours=6&hours=3',
|
||||
'/api/news/hotspots?hours=6&x=1',
|
||||
'/api/news/hotspots?x=1',
|
||||
'/api/news/feed?limit=501',
|
||||
'/api/news/feed?limit=0',
|
||||
'/api/news/feed?hotspot=all&hotspot=ua',
|
||||
'/api/news/feed?since=yesterday',
|
||||
'/api/news/feed?geo=yes',
|
||||
'/api/news/feed?side=UA',
|
||||
'/api/news/air-alerts',
|
||||
'/api/news/outline?hotspot=ua',
|
||||
'/api/news/outline?hotspot=ua&v=2',
|
||||
'/api/news/outline?country=ukraine&v=4',
|
||||
'/api/news/outline?at=30.267,-97.7&v=4',
|
||||
'/api/news/outline?at=30.27&v=4',
|
||||
'/api/news/outline?at=30.27,-97.7&country=US&v=4',
|
||||
'/api/news/feed?at=30.267,-97.7',
|
||||
])
|
||||
assert.equal(allowed(path), false, path);
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
// Marker sprites for news reports: a dark disc with the category's icon and
|
||||
// a rim in the severity colour, the rim's form telling attestation. Drawn once per look
|
||||
// on a canvas and handed to Cesium as a data URL, so its texture atlas keeps
|
||||
// one copy per look however often the layer re-renders.
|
||||
|
||||
import { NEWS_CATEGORIES, NEWS_SEVERITY } from './model.js';
|
||||
|
||||
const CANVAS = 64;
|
||||
const BODY = 52; // disc diameter inside the canvas; the rest is rim and ring
|
||||
const INK = 'rgba(10, 10, 15, 0.92)';
|
||||
const SELECTED = '#00d4ff';
|
||||
const COUNT_INK = '#e8eaed';
|
||||
|
||||
/** Canvas pixels per marker pixel: the billboard is drawn at this ratio. */
|
||||
export const SPRITE_SCALE = CANVAS / BODY;
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
/**
|
||||
* Paint one marker look centred at (cx, cy) with a disc of `body` pixels: the
|
||||
* sprites and the event cards' badges draw the same thing.
|
||||
*/
|
||||
export function paintMarker(ctx, { category, severity, rim }, cx, cy, body) {
|
||||
const k = body / BODY; // the strokes below are tuned for the 52 px body
|
||||
const r = body / 2;
|
||||
// A dark edge keeps the lightest fills apart from bright ground.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r + 1.5 * k, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
|
||||
ctx.fill();
|
||||
// GEV's dark glass disc, as its HUD buttons are; severity colours the rim
|
||||
// and the icon rather than filling the disc.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = INK;
|
||||
ctx.fill();
|
||||
const color = (NEWS_SEVERITY[severity] || NEWS_SEVERITY[0]).color;
|
||||
|
||||
// Attestation is the rim's form, never its colour.
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r - 3 * k, 0, 2 * Math.PI);
|
||||
ctx.setLineDash(rim === 'claimed' ? [7 * k, 5 * k] : []);
|
||||
ctx.lineWidth = (rim === 'thin' ? 2.5 : 6) * k;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
|
||||
const style = NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
|
||||
const icon = body * 0.5;
|
||||
ctx.save();
|
||||
ctx.translate(cx - icon / 2, cy - icon / 2);
|
||||
ctx.scale(icon / 16, icon / 16);
|
||||
const path = new Path2D(style.icon);
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.lineWidth = 1.7;
|
||||
ctx.strokeStyle = color;
|
||||
if (style.solid) {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill(path);
|
||||
} else ctx.stroke(path);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Data URL of the sprite for a look, or null where there is no canvas (the
|
||||
* layer then falls back to a plain point).
|
||||
* @param {{category: string, severity: number, rim: 'confirmed'|'claimed'|'thin', selected?: boolean}} look
|
||||
*/
|
||||
export function markerSprite({ category, severity, rim, selected = false }) {
|
||||
const key = `${category}|${severity}|${rim}|${selected ? 1 : 0}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
const ctx = canvas?.getContext?.('2d');
|
||||
if (!ctx || typeof globalThis.Path2D !== 'function') return null;
|
||||
canvas.width = canvas.height = CANVAS;
|
||||
const c = CANVAS / 2;
|
||||
paintMarker(ctx, { category, severity, rim }, c, c, BODY);
|
||||
if (selected) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, CANVAS / 2 - 2, 0, 2 * Math.PI);
|
||||
ctx.lineWidth = 3.5;
|
||||
ctx.strokeStyle = SELECTED;
|
||||
ctx.stroke();
|
||||
}
|
||||
const url = canvas.toDataURL('image/png');
|
||||
cache.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data URL of a country badge: the dark disc with a light rim and the number
|
||||
* of reports it stands for, drawn at the pixels it is shown at so the digits
|
||||
* stay sharp. Null where there is no canvas.
|
||||
* @param {number} count Reports the badge stands for.
|
||||
* @param {number} pixels The disc's diameter in drawn pixels.
|
||||
*/
|
||||
export function countSprite(count, pixels) {
|
||||
const body = Math.max(1, Math.round(pixels));
|
||||
const text = count > 99 ? '99+' : String(count);
|
||||
const key = `count|${text}|${body}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const canvas = globalThis.document?.createElement?.('canvas');
|
||||
const ctx = canvas?.getContext?.('2d');
|
||||
if (!ctx) return null;
|
||||
const k = body / BODY;
|
||||
canvas.width = canvas.height = Math.round(CANVAS * k);
|
||||
const c = canvas.width / 2;
|
||||
const r = body / 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r + 1.5 * k, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r, 0, 2 * Math.PI);
|
||||
ctx.fillStyle = INK;
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(c, c, r - 2 * k, 0, 2 * Math.PI);
|
||||
ctx.lineWidth = 3 * k;
|
||||
ctx.strokeStyle = COUNT_INK;
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = COUNT_INK;
|
||||
ctx.font = `600 ${Math.round(body * (text.length > 2 ? 0.34 : 0.44))}px ui-monospace, Menlo, monospace`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(text, c, c + k);
|
||||
const url = canvas.toDataURL('image/png');
|
||||
cache.set(key, url);
|
||||
return url;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { formatDate, formatNumber, msg, t } from '../../i18n/index.js';
|
||||
import { EMODNET_PAGE_URL } from './records.js';
|
||||
|
||||
export const ERA_LABELS = Object.freeze({
|
||||
'before-1900': msg('Before 1900'),
|
||||
'1900-1945': msg('1900–1945'),
|
||||
'after-1945': msg('After 1945'),
|
||||
undated: msg('Date unknown'),
|
||||
});
|
||||
|
||||
export const ERA_COLORS = Object.freeze({
|
||||
'before-1900': '#c79a5b',
|
||||
'1900-1945': '#ff6b5e',
|
||||
'after-1945': '#4fc3f7',
|
||||
undated: '#9aa7b4',
|
||||
});
|
||||
|
||||
function formatDay(date) {
|
||||
const match = /^(-?\d{4})-(\d{2})-(\d{2})$/.exec(date || '');
|
||||
if (!match) return '';
|
||||
return formatDate(
|
||||
Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])),
|
||||
{ day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' },
|
||||
);
|
||||
}
|
||||
|
||||
function meters(value) {
|
||||
return formatNumber(value, {
|
||||
maximumFractionDigits: value < 10 ? 1 : 0,
|
||||
});
|
||||
}
|
||||
|
||||
/** How well the position is known, as one card line (or null). */
|
||||
export function positionLine(record) {
|
||||
if (record.positionNote) return t('Position: centre of the protected area');
|
||||
const accuracy = record.positionAccuracy;
|
||||
if (!Number.isFinite(accuracy)) return null;
|
||||
// 1852 m is EMODnet's "within a nautical mile" for old, reported positions.
|
||||
if (accuracy >= 1000)
|
||||
return t('Position approximate (within about {km} km)', {
|
||||
km: formatNumber(accuracy / 1000, { maximumFractionDigits: 1 }),
|
||||
});
|
||||
return t('Position surveyed (within about {m} m)', { m: meters(accuracy) });
|
||||
}
|
||||
|
||||
/**
|
||||
* The link a click on the card opens: the Wikipedia (or Wikidata) page, the
|
||||
* wreck's own page when EMODnet lists one, else EMODnet's portal.
|
||||
* @param {object} record
|
||||
* @returns {string}
|
||||
*/
|
||||
export function cardLink(record) {
|
||||
return record?.url || EMODNET_PAGE_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Title and detail lines for one wreck card: deaths first, then when and
|
||||
* where, then the ship facts. Victims appear as a count only; free text that
|
||||
* refers to a person by a title or role is dropped by a keyword filter (see
|
||||
* records.js), which a bare name can still pass.
|
||||
* @param {object} record A normalized shipwreck record.
|
||||
* @returns {{title: string, details: string[], link: string}}
|
||||
*/
|
||||
export function describeShipwreck(record) {
|
||||
const titleParts = [t('Shipwreck')];
|
||||
if (record.name) titleParts.push(record.name);
|
||||
const details = [];
|
||||
// Deaths first, right under the title: the fact readers look for.
|
||||
const toll = [];
|
||||
if (Number.isFinite(record.casualties))
|
||||
toll.push(
|
||||
t('Fatalities: {count}', { count: formatNumber(record.casualties) }),
|
||||
);
|
||||
if (record.survivors)
|
||||
toll.push(
|
||||
t('Survivors: {count}', { count: formatNumber(record.survivors) }),
|
||||
);
|
||||
if (toll.length) details.push(toll.join(' · '));
|
||||
const when =
|
||||
formatDay(record.date) ||
|
||||
(Number.isInteger(record.year) ? String(record.year) : '') ||
|
||||
record.dating ||
|
||||
'';
|
||||
const where = [when, record.country].filter(Boolean);
|
||||
if (where.length) details.push(where.join(' · '));
|
||||
if (record.vesselType)
|
||||
details.push(t('Vessel: {value}', { value: record.vesselType }));
|
||||
if (record.cause)
|
||||
details.push(t('What happened: {value}', { value: record.cause }));
|
||||
if (Number.isFinite(record.depth))
|
||||
details.push(
|
||||
record.depthQuality
|
||||
? t('Depth: {m} m ({quality})', {
|
||||
m: meters(record.depth),
|
||||
quality: record.depthQuality,
|
||||
})
|
||||
: t('Depth: {m} m', { m: meters(record.depth) }),
|
||||
);
|
||||
const position = positionLine(record);
|
||||
if (position) details.push(position);
|
||||
if (record.notes) details.push(t('Notes: {value}', { value: record.notes }));
|
||||
if (record.cargo)
|
||||
details.push(t('Cargo or finds: {value}', { value: record.cargo }));
|
||||
if (record.protected) details.push(t('Protected wreck'));
|
||||
const sources =
|
||||
record.source === 'wikidata'
|
||||
? record.alsoIn === 'emodnet'
|
||||
? 'Wikidata · EMODnet'
|
||||
: 'Wikidata'
|
||||
: record.originator
|
||||
? `EMODnet (${record.originator})`
|
||||
: 'EMODnet';
|
||||
details.push(t('Source: {value}', { value: sources }));
|
||||
const link = cardLink(record);
|
||||
details.push(
|
||||
link === EMODNET_PAGE_URL
|
||||
? t('Click the card to open EMODnet ↗')
|
||||
: link.includes('.wikipedia.org/')
|
||||
? t('Click the card to open the article ↗')
|
||||
: t('Click the card to open the source ↗'),
|
||||
);
|
||||
return { title: titleParts.join(' · '), details, link };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { describeShipwreck, positionLine } from './cards.js';
|
||||
import { EMODNET_PAGE_URL } from './records.js';
|
||||
|
||||
test('a Wikidata card shows the ship facts and links its article', () => {
|
||||
const card = describeShipwreck({
|
||||
source: 'wikidata',
|
||||
alsoIn: 'emodnet',
|
||||
name: 'HMS Havant',
|
||||
vesselType: 'destroyer',
|
||||
date: '1940-06-01',
|
||||
year: 1940,
|
||||
cause: 'Was sunk on 06/01/1940 by the German air force',
|
||||
casualties: 8,
|
||||
survivors: 120,
|
||||
depth: 14.72,
|
||||
depthQuality: 'Least depth known',
|
||||
positionAccuracy: 3.1,
|
||||
notes: '1939 G and H-class destroyer',
|
||||
country: 'France',
|
||||
url: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)',
|
||||
});
|
||||
assert.equal(card.title, 'Shipwreck · HMS Havant');
|
||||
assert.equal(card.link, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
|
||||
const text = card.details.join('\n');
|
||||
assert.equal(card.details[0], 'Fatalities: 8 · Survivors: 120');
|
||||
assert.match(card.details[1], /1940 · France$/);
|
||||
assert.match(text, /Vessel: destroyer/);
|
||||
assert.match(text, /What happened: Was sunk/);
|
||||
assert.match(text, /Depth: 15 m \(Least depth known\)/);
|
||||
assert.match(text, /Position surveyed \(within about 3\.1 m\)/);
|
||||
assert.match(text, /Source: Wikidata · EMODnet/);
|
||||
assert.match(text, /open the article/);
|
||||
});
|
||||
|
||||
test('an EMODnet card without a page links the portal', () => {
|
||||
const card = describeShipwreck({
|
||||
source: 'emodnet',
|
||||
name: null,
|
||||
year: null,
|
||||
dating: 'C1st AD',
|
||||
originator: 'The Oxford Roman Economy Project',
|
||||
protected: true,
|
||||
url: null,
|
||||
});
|
||||
assert.equal(card.title, 'Shipwreck');
|
||||
assert.equal(card.link, EMODNET_PAGE_URL);
|
||||
const text = card.details.join('\n');
|
||||
assert.equal(card.details[0], 'C1st AD');
|
||||
assert.match(text, /Protected wreck/);
|
||||
assert.match(text, /EMODnet \(The Oxford Roman Economy Project\)/);
|
||||
assert.match(text, /open EMODnet/);
|
||||
});
|
||||
|
||||
test('position lines read the accuracy', () => {
|
||||
assert.equal(positionLine({}), null);
|
||||
assert.match(positionLine({ positionAccuracy: 1852 }), /about 1\.9 km/);
|
||||
assert.match(
|
||||
positionLine({ positionNote: 'x' }),
|
||||
/centre of the protected area/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Era chips, oldest first; a wreck with no known year sits in its own chip. */
|
||||
export const SHIPWRECK_ERAS = Object.freeze([
|
||||
'before-1900',
|
||||
'1900-1945',
|
||||
'after-1945',
|
||||
'undated',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The era a wreck belongs to. Ancient wrecks dated only by period
|
||||
* ("Roman Imperial", "C1st AD") count as before 1900.
|
||||
* @param {{year?: number|null, ancient?: boolean}} record
|
||||
* @returns {string}
|
||||
*/
|
||||
export function eraOf(record) {
|
||||
const year = Number.isInteger(record?.year) ? record.year : null;
|
||||
if (year === null) return record?.ancient ? 'before-1900' : 'undated';
|
||||
if (year < 1900) return 'before-1900';
|
||||
if (year <= 1945) return '1900-1945';
|
||||
return 'after-1945';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { eraOf } from './eras.js';
|
||||
|
||||
test('each wreck falls in one era', () => {
|
||||
assert.equal(eraOf({ year: 1588 }), 'before-1900');
|
||||
assert.equal(eraOf({ year: null, ancient: true }), 'before-1900');
|
||||
assert.equal(eraOf({ year: 1900 }), '1900-1945');
|
||||
assert.equal(eraOf({ year: 1945 }), '1900-1945');
|
||||
assert.equal(eraOf({ year: 1946 }), 'after-1945');
|
||||
assert.equal(eraOf({ year: null }), 'undated');
|
||||
assert.equal(eraOf(null), 'undated');
|
||||
});
|
||||
@@ -0,0 +1,528 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { formatNumber, msg, t, tn } from '../../i18n/index.js';
|
||||
import {
|
||||
registerSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
unregisterSpriteCollection,
|
||||
} from '../../data/spriteOrder.js';
|
||||
import { createHorizonCull } from '../streetLevel/view.js';
|
||||
import { ERA_COLORS, ERA_LABELS, describeShipwreck } from './cards.js';
|
||||
import { SHIPWRECK_ERAS, eraOf } from './eras.js';
|
||||
import {
|
||||
inPeriod,
|
||||
normalizePeriod,
|
||||
periodRange,
|
||||
yearExtent,
|
||||
} from './period.js';
|
||||
export * from './records.js';
|
||||
export * from './cards.js';
|
||||
export * from './eras.js';
|
||||
export * from './period.js';
|
||||
export { createShipwrecksSource } from './source.js';
|
||||
|
||||
export const SHIPWRECKS_LAYER_ID = 'shipwrecks';
|
||||
export const SHIPWRECKS_OVERLAY_SOURCE_ID = 'shipwrecks';
|
||||
const PICK_PREFIX = 'shipwreck:';
|
||||
const CARD_HOST_OPTIONS = Object.freeze({
|
||||
cohortLimit: 1,
|
||||
collisionCapacity: 1,
|
||||
moving: false,
|
||||
});
|
||||
const MAX_CARD_LINES = 14;
|
||||
/** Wrecks not refreshed for this long leave the map (the proxy's own limit). */
|
||||
const MAX_SHOWN_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* When the shown wrecks leave the map if the page cannot refresh, on this
|
||||
* page's clock: the age the proxy reports (its own clock) is subtracted from
|
||||
* the limit, so the two clocks are never compared, and the newest source
|
||||
* decides. A wreck both sources list is one merged record, so the snapshot
|
||||
* goes as a whole, not per source. With no age reported, the snapshot counts
|
||||
* as fresh when it arrives.
|
||||
*/
|
||||
export function snapshotDeadline(snapshot, at) {
|
||||
const limit = snapshot.maxAgeMs ?? MAX_SHOWN_AGE_MS;
|
||||
const ages = ['emodnet', 'wikidata']
|
||||
.filter((name) => snapshot.sources?.[name] !== false)
|
||||
.map((name) => snapshot.ages?.[name] ?? 0);
|
||||
const newest = ages.length ? Math.min(...ages) : 0;
|
||||
return at + limit - newest;
|
||||
}
|
||||
/**
|
||||
* Marker size in pixels: grows with the death toll, from 16 px (no deaths known) to 36 px (about a thousand or more).
|
||||
*/
|
||||
export function markerPixelSize(casualties) {
|
||||
const n = Number.isFinite(casualties) && casualties > 0 ? casualties : 0;
|
||||
return Math.round(16 + Math.min(20, Math.log2(1 + n) * 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* A round marker in the era's colour with a sinking hull and mast in the
|
||||
* middle, as an SVG data URL. It is rasterized at 144 px, four times the
|
||||
* largest marker, so big markers stay sharp on high-density screens.
|
||||
* @param {string} color CSS colour.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function wreckMarkerImage(color) {
|
||||
const svg =
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="144" height="144" viewBox="0 0 36 36">` +
|
||||
`<circle cx="18" cy="18" r="16" fill="${color}" stroke="#ffffff" stroke-width="2"/>` +
|
||||
`<path d="M8 21h20l-3.5 5h-13z" fill="#0b1420"/>` +
|
||||
`<path d="M17 8v12M17 9l6 7h-6" fill="none" stroke="#0b1420" stroke-width="2.2" stroke-linejoin="round"/>` +
|
||||
`</svg>`;
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shipwrecks: EMODnet's European heritage wrecks and Wikidata's notable
|
||||
* wrecks worldwide, one marker each, with a card and era chips.
|
||||
*/
|
||||
export function createShipwrecksLayer({
|
||||
source,
|
||||
overlayHost = null,
|
||||
screenSpaceEventHandlerFactory = null,
|
||||
picking = null,
|
||||
pointer = null,
|
||||
openExternal = null,
|
||||
now = () => Date.now(),
|
||||
// One collection for every wreck marker (thousands of them): far cheaper to
|
||||
// draw and rebuild than an entity each. Tests pass a fake.
|
||||
createMarkers = (scene) =>
|
||||
new Cesium.BillboardCollection({
|
||||
scene,
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
}),
|
||||
} = {}) {
|
||||
if (typeof source?.getSnapshot !== 'function')
|
||||
throw new TypeError('Shipwrecks require a snapshot source');
|
||||
let _viewer = null;
|
||||
let _enabled = false;
|
||||
let _markers = null;
|
||||
let _request = null;
|
||||
let _records = new Map();
|
||||
let _pins = [];
|
||||
let _snapshot = null;
|
||||
let _deadline = null;
|
||||
let _lastError = null;
|
||||
let _clickHandler = null;
|
||||
let _rowListener = null;
|
||||
let _selectedId = null;
|
||||
let _selectedCardId = null;
|
||||
let _selectedLink = null;
|
||||
let _period = { from: null, to: null };
|
||||
let _extent = null;
|
||||
let _range = null;
|
||||
const _images = Object.fromEntries(
|
||||
SHIPWRECK_ERAS.map((era) => [era, wreckMarkerImage(ERA_COLORS[era])]),
|
||||
);
|
||||
|
||||
const render = () => _viewer?.scene?.requestRender?.();
|
||||
const notifyRow = () => _rowListener?.();
|
||||
const canSelect = () =>
|
||||
overlayHost && screenSpaceEventHandlerFactory && picking;
|
||||
// Markers skip the depth test so terrain does not swallow them; the
|
||||
// horizon cull hides the far side of the planet instead.
|
||||
const _horizon = createHorizonCull({
|
||||
getViewer: () => _viewer,
|
||||
items: () => _pins,
|
||||
onChange: render,
|
||||
});
|
||||
|
||||
/** Shown: its year is inside the period (undated ones only for all years). */
|
||||
function visible(record) {
|
||||
return Boolean(record) && inPeriod(record, _range);
|
||||
}
|
||||
|
||||
function applyPin(pin) {
|
||||
const show = pin.inFront && visible(pin.record);
|
||||
if (pin.billboard.show !== show) pin.billboard.show = show;
|
||||
}
|
||||
|
||||
/** Re-apply the period to every marker and the open card. */
|
||||
function applyFilter() {
|
||||
for (const pin of _pins) applyPin(pin);
|
||||
if (_selectedId && !visible(_records.get(_selectedId))) clearSelection();
|
||||
notifyRow();
|
||||
render();
|
||||
}
|
||||
|
||||
function rebuild(records) {
|
||||
_records = new Map(records.map((record) => [record.id, record]));
|
||||
_extent = yearExtent(records);
|
||||
_range = periodRange(_period, _extent);
|
||||
_pins = [];
|
||||
if (!_markers) return;
|
||||
_markers.removeAll();
|
||||
// Within one collection later markers draw on top: add by rising death
|
||||
// toll so a bigger toll covers smaller neighbours.
|
||||
const ordered = [...records].sort(
|
||||
(a, b) => (a.casualties || 0) - (b.casualties || 0),
|
||||
);
|
||||
for (const record of ordered) {
|
||||
const position = Cesium.Cartesian3.fromDegrees(record.lon, record.lat);
|
||||
const size = markerPixelSize(record.casualties);
|
||||
const billboard = _markers.add({
|
||||
id: `${PICK_PREFIX}${record.id}`,
|
||||
position,
|
||||
image: _images[eraOf(record)],
|
||||
width: size,
|
||||
height: size,
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
const pin = {
|
||||
billboard,
|
||||
record,
|
||||
position,
|
||||
inFront: true,
|
||||
get show() {
|
||||
return this.inFront;
|
||||
},
|
||||
set show(value) {
|
||||
this.inFront = value;
|
||||
applyPin(this);
|
||||
},
|
||||
};
|
||||
applyPin(pin);
|
||||
_pins.push(pin);
|
||||
}
|
||||
_horizon.update();
|
||||
if (_selectedId && !_records.has(_selectedId)) clearSelection();
|
||||
else if (_selectedId) publishCard();
|
||||
render();
|
||||
}
|
||||
|
||||
// ---- selection card ----------------------------------------------------
|
||||
function publishCard() {
|
||||
if (!canSelect()) return;
|
||||
const record = _selectedId ? _records.get(_selectedId) : null;
|
||||
if (!visible(record)) {
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
const { title, details, link } = describeShipwreck(record);
|
||||
_selectedLink = link && openExternal ? link : null;
|
||||
const card = {
|
||||
id: `shipwreck-card:${record.id}`,
|
||||
selected: true,
|
||||
interactive: Boolean(_selectedLink),
|
||||
title,
|
||||
details: details.slice(0, MAX_CARD_LINES),
|
||||
accent: ERA_COLORS[eraOf(record)],
|
||||
priority: Number.MAX_SAFE_INTEGER,
|
||||
gapPx: 15,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
stateless: true,
|
||||
horizonCull: true,
|
||||
position: Cesium.Cartesian3.fromDegrees(record.lon, record.lat),
|
||||
};
|
||||
if (card.interactive) {
|
||||
const target = _selectedLink;
|
||||
card.accessibilityLabel = t('Open the source for {title}', { title });
|
||||
card.activate = () => {
|
||||
openExternal(target);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
_selectedCardId = card.id;
|
||||
overlayHost.setEntries(
|
||||
SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
[card],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
overlayHost.setVisible?.(SHIPWRECKS_OVERLAY_SOURCE_ID, true);
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
_selectedId = null;
|
||||
_selectedCardId = null;
|
||||
_selectedLink = null;
|
||||
overlayHost?.setEntries(
|
||||
SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
function pickedRecordId(picked) {
|
||||
const pickId = picking.resolvePickId(picked);
|
||||
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
|
||||
return null;
|
||||
const id = pickId.slice(PICK_PREFIX.length);
|
||||
return _records.has(id) ? id : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
if (!canSelect() || _clickHandler || !_viewer) return;
|
||||
picking.registerPickOwner?.(
|
||||
SHIPWRECKS_LAYER_ID,
|
||||
(pickedId) =>
|
||||
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
|
||||
);
|
||||
_clickHandler = screenSpaceEventHandlerFactory(_viewer);
|
||||
_clickHandler.setInputAction((click) => {
|
||||
if (pointer && !pointer.isPointerFree()) return;
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
click.position?.x,
|
||||
click.position?.y,
|
||||
{ sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink) openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = _viewer.scene.pick(click.position);
|
||||
const id = picked ? pickedRecordId(picked) : null;
|
||||
if (id) {
|
||||
_selectedId = id;
|
||||
publishCard();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (picked) {
|
||||
const pickId = picking.resolvePickId(picked);
|
||||
if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId))
|
||||
return;
|
||||
}
|
||||
if (_selectedId) {
|
||||
clearSelection();
|
||||
render();
|
||||
}
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickHandler?.destroy();
|
||||
_clickHandler = null;
|
||||
picking?.unregisterPickOwner?.(SHIPWRECKS_LAYER_ID);
|
||||
}
|
||||
|
||||
/** Wrecks shown per era, in one pass over the records. */
|
||||
function eraCounts() {
|
||||
const counts = Object.fromEntries(SHIPWRECK_ERAS.map((era) => [era, 0]));
|
||||
for (const record of _records.values())
|
||||
if (inPeriod(record, _range)) counts[eraOf(record)]++;
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** The years that have a dated wreck, plus `extra` ones, newest first. */
|
||||
function yearsInData(extra = []) {
|
||||
const years = new Set(extra);
|
||||
for (const record of _records.values())
|
||||
if (Number.isInteger(record.year)) years.add(record.year);
|
||||
return [...years].sort((a, b) => b - a);
|
||||
}
|
||||
|
||||
/** The start and end year pickers, side by side. */
|
||||
function periodControls() {
|
||||
if (!_extent || _extent.min === _extent.max) return {};
|
||||
const range = periodRange(_period, _extent);
|
||||
const valueText = range.all
|
||||
? t('All years')
|
||||
: range.from === range.to
|
||||
? String(range.from)
|
||||
: `${range.from}–${range.to}`;
|
||||
// Only years with a wreck: a picker of every year since the oldest
|
||||
// dated wreck would run to well over a thousand entries.
|
||||
// The chosen ends stay listed even when no wreck sank that year.
|
||||
const options = yearsInData([range.from, range.to]).map((year) => ({
|
||||
value: year,
|
||||
label: String(year),
|
||||
}));
|
||||
return {
|
||||
range: {
|
||||
id: 'period',
|
||||
label: t('Period'),
|
||||
valueText,
|
||||
from: {
|
||||
label: t('From'),
|
||||
ariaLabel: t('First year of the shipwreck period'),
|
||||
value: range.from,
|
||||
},
|
||||
to: {
|
||||
label: t('To'),
|
||||
ariaLabel: t('Last year of the shipwreck period'),
|
||||
value: range.to,
|
||||
},
|
||||
options,
|
||||
params: (end, value) => ({ [end]: Number(value) }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const layer = {
|
||||
id: SHIPWRECKS_LAYER_ID,
|
||||
name: 'Shipwrecks',
|
||||
icon: '⚓',
|
||||
source: 'EMODnet · Wikidata',
|
||||
// The proxy refreshes once a day; this only notices a new snapshot.
|
||||
updateInterval: 6 * 60 * 60 * 1000,
|
||||
|
||||
init(viewer) {
|
||||
if (_viewer) throw new Error('Shipwrecks layer is already initialized');
|
||||
_viewer = viewer;
|
||||
_markers = createMarkers(viewer.scene);
|
||||
_markers.show = false;
|
||||
viewer.scene.primitives.add(_markers);
|
||||
registerSpriteCollection(SHIPWRECKS_LAYER_ID, _markers);
|
||||
},
|
||||
|
||||
enable() {
|
||||
_enabled = true;
|
||||
if (_markers) _markers.show = true;
|
||||
restoreSpriteOrder(_viewer);
|
||||
installClickHandler();
|
||||
if (_pins.length) _horizon.update();
|
||||
},
|
||||
|
||||
disable() {
|
||||
_enabled = false;
|
||||
_request?.abort();
|
||||
_request = null;
|
||||
if (_markers) _markers.show = false;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_horizon.stop();
|
||||
render();
|
||||
},
|
||||
|
||||
async update() {
|
||||
if (!_enabled || !_markers) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
try {
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
// The page checks every 6 h; the proxy refreshes once a day. Only a
|
||||
// new snapshot rebuilds the markers.
|
||||
const unchanged =
|
||||
typeof snapshot.version === 'string' &&
|
||||
snapshot.version === _snapshot?.version &&
|
||||
_pins.length > 0;
|
||||
_snapshot = snapshot;
|
||||
_deadline = snapshotDeadline(snapshot, now());
|
||||
_lastError =
|
||||
snapshot.sources.emodnet && snapshot.sources.wikidata
|
||||
? null
|
||||
: snapshot.sources.emodnet
|
||||
? msg('Wikidata unavailable; showing EMODnet only')
|
||||
: msg('EMODnet unavailable; showing Wikidata only');
|
||||
if (!unchanged) rebuild(snapshot.records);
|
||||
notifyRow();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
console.warn('[Data:Shipwrecks] Fetch error:', error);
|
||||
_lastError = error?.message || msg('Shipwrecks unavailable');
|
||||
// What is on the map was not refreshed: say so, and drop it once
|
||||
// even its newest source is older than the proxy would serve.
|
||||
if (_snapshot) {
|
||||
if (now() >= _deadline) {
|
||||
_snapshot = null;
|
||||
_deadline = null;
|
||||
rebuild([]);
|
||||
} else _snapshot = { ..._snapshot, stale: true };
|
||||
}
|
||||
notifyRow();
|
||||
return false;
|
||||
} finally {
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
|
||||
destroy(viewer = _viewer) {
|
||||
layer.disable();
|
||||
if (_markers) {
|
||||
unregisterSpriteCollection(SHIPWRECKS_LAYER_ID, _markers);
|
||||
const primitives = viewer?.scene?.primitives;
|
||||
if (primitives && !primitives.isDestroyed?.())
|
||||
primitives.remove(_markers);
|
||||
_markers = null;
|
||||
}
|
||||
_records = new Map();
|
||||
_pins = [];
|
||||
_snapshot = null;
|
||||
_deadline = null;
|
||||
_viewer = null;
|
||||
_rowListener = null;
|
||||
},
|
||||
|
||||
/** The period filter: `from` and `to` are years (null = oldest / latest in the data). */
|
||||
getParams() {
|
||||
return { ..._period };
|
||||
},
|
||||
|
||||
setParams(params = {}) {
|
||||
const next = normalizePeriod(params, _period);
|
||||
if (next.from === _period.from && next.to === _period.to) return true;
|
||||
_period = next;
|
||||
_range = periodRange(_period, _extent);
|
||||
applyFilter();
|
||||
return true;
|
||||
},
|
||||
|
||||
setRowControlsListener(listener) {
|
||||
_rowListener = listener;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
const counts = eraCounts();
|
||||
return {
|
||||
chips: [],
|
||||
...periodControls(),
|
||||
// The colours are a legend: when the ship sank.
|
||||
legend: SHIPWRECK_ERAS.map((era) => ({
|
||||
label: t(ERA_LABELS[era]),
|
||||
count: counts[era],
|
||||
color: ERA_COLORS[era],
|
||||
blurb: tn(counts[era], '{count} wreck', '{count} wrecks', {
|
||||
count: formatNumber(counts[era]),
|
||||
}),
|
||||
})),
|
||||
info: t('EMODnet (European waters) · Wikidata (worldwide)'),
|
||||
infoTitle: t(
|
||||
'European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.',
|
||||
),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
let shown = 0;
|
||||
for (const record of _records.values()) if (visible(record)) shown++;
|
||||
return {
|
||||
count: shown,
|
||||
lastUpdate: _snapshot?.fetchedAt ?? null,
|
||||
stale: _snapshot?.stale === true,
|
||||
error: _lastError,
|
||||
};
|
||||
},
|
||||
|
||||
/** Loaded records as plain JSON-safe objects, for tools and QA. */
|
||||
getAnalystRecords(maxCount = 2000) {
|
||||
if (!_enabled) return [];
|
||||
const out = [];
|
||||
for (const record of _records.values()) {
|
||||
if (out.length >= maxCount) break;
|
||||
if (!visible(record)) continue;
|
||||
out.push({
|
||||
id: record.id,
|
||||
source: record.source,
|
||||
name: record.name,
|
||||
vesselType: record.vesselType,
|
||||
year: record.year,
|
||||
era: eraOf(record),
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
depth: record.depth,
|
||||
casualties: record.casualties,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
return layer;
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import {
|
||||
createShipwrecksLayer,
|
||||
markerPixelSize,
|
||||
snapshotDeadline,
|
||||
} from './index.js';
|
||||
|
||||
const wreck = (id, extra = {}) => ({
|
||||
id,
|
||||
source: 'wikidata',
|
||||
name: id,
|
||||
lat: 50,
|
||||
lon: -1,
|
||||
year: 1912,
|
||||
date: null,
|
||||
casualties: null,
|
||||
...extra,
|
||||
});
|
||||
|
||||
const snapshot = (records, version = 'v1') => ({
|
||||
records,
|
||||
fetchedAt: 1,
|
||||
stale: false,
|
||||
version,
|
||||
sources: { emodnet: true, wikidata: true },
|
||||
});
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
/** A fake billboard collection that records what the layer adds. */
|
||||
function fakeMarkers() {
|
||||
const collection = {
|
||||
show: true,
|
||||
billboards: [],
|
||||
rebuilds: 0,
|
||||
add(options) {
|
||||
const billboard = { show: true, ...options };
|
||||
collection.billboards.push(billboard);
|
||||
return billboard;
|
||||
},
|
||||
removeAll() {
|
||||
collection.rebuilds++;
|
||||
collection.billboards = [];
|
||||
},
|
||||
};
|
||||
return collection;
|
||||
}
|
||||
|
||||
function harness({ snapshots, now = () => 1 } = {}) {
|
||||
const markers = fakeMarkers();
|
||||
const primitives = [];
|
||||
const cards = [];
|
||||
const handlers = [];
|
||||
const opened = [];
|
||||
let pickResult = null;
|
||||
const viewer = {
|
||||
camera: { positionWC: Cesium.Cartesian3.fromDegrees(-1, 50, 2e6) },
|
||||
scene: {
|
||||
canvas: {},
|
||||
requestRender() {},
|
||||
pick: () => pickResult,
|
||||
preRender: { addEventListener: () => () => {} },
|
||||
primitives: {
|
||||
add: (primitive) => primitives.push(primitive),
|
||||
remove: (primitive) =>
|
||||
primitives.splice(primitives.indexOf(primitive), 1),
|
||||
raiseToTop() {},
|
||||
contains: (primitive) => primitives.includes(primitive),
|
||||
},
|
||||
},
|
||||
};
|
||||
const queue = [...(snapshots || [])];
|
||||
const requests = [];
|
||||
const layer = createShipwrecksLayer({
|
||||
source: {
|
||||
getSnapshot({ signal }) {
|
||||
requests.push(signal);
|
||||
const next = queue.shift();
|
||||
if (next instanceof Error) return Promise.reject(next);
|
||||
return next instanceof Promise ? next : Promise.resolve(next);
|
||||
},
|
||||
},
|
||||
createMarkers: () => markers,
|
||||
overlayHost: {
|
||||
setEntries: (_source, entries) => cards.push(entries),
|
||||
setVisible() {},
|
||||
hitTest: () => null,
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => {
|
||||
const handler = {
|
||||
setInputAction(callback) {
|
||||
handler.click = callback;
|
||||
},
|
||||
destroy() {
|
||||
handler.destroyed = true;
|
||||
},
|
||||
};
|
||||
handlers.push(handler);
|
||||
return handler;
|
||||
},
|
||||
picking,
|
||||
pointer: { isPointerFree: () => true },
|
||||
openExternal: (url) => opened.push(url),
|
||||
now: () => now(),
|
||||
});
|
||||
layer.init(viewer);
|
||||
return {
|
||||
layer,
|
||||
markers,
|
||||
primitives,
|
||||
cards,
|
||||
handlers,
|
||||
requests,
|
||||
opened,
|
||||
pick(id) {
|
||||
pickResult = id ? { id: `shipwreck:${id}` } : null;
|
||||
},
|
||||
lastCard: () => cards.at(-1),
|
||||
};
|
||||
}
|
||||
|
||||
test('markers live in one collection, shown only while the layer is on', async () => {
|
||||
const h = harness({ snapshots: [snapshot([wreck('a'), wreck('b')])] });
|
||||
assert.deepEqual(h.primitives, [h.markers]);
|
||||
assert.equal(h.markers.show, false);
|
||||
h.layer.enable();
|
||||
assert.equal(h.markers.show, true);
|
||||
assert.equal(await h.layer.update(), true);
|
||||
assert.equal(h.markers.billboards.length, 2);
|
||||
assert.equal(h.layer.getStats().count, 2);
|
||||
h.layer.disable();
|
||||
assert.equal(h.markers.show, false);
|
||||
assert.equal(h.handlers[0].destroyed, true);
|
||||
h.layer.destroy();
|
||||
assert.deepEqual(h.primitives, [], 'the collection leaves the scene');
|
||||
});
|
||||
|
||||
test('markers sit on the wreck: no eye offset, bigger toll drawn last', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([
|
||||
wreck('big', { casualties: 1500 }),
|
||||
wreck('none'),
|
||||
wreck('small', { casualties: 3 }),
|
||||
]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
const ids = h.markers.billboards.map((billboard) => billboard.id);
|
||||
assert.deepEqual(ids, ['shipwreck:none', 'shipwreck:small', 'shipwreck:big']);
|
||||
for (const billboard of h.markers.billboards)
|
||||
assert.equal(billboard.eyeOffset, undefined);
|
||||
assert.equal(h.markers.billboards[2].width, markerPixelSize(1500));
|
||||
});
|
||||
|
||||
test('an unchanged snapshot does not rebuild the markers', async () => {
|
||||
const records = [wreck('a')];
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot(records, 'v1'),
|
||||
snapshot(records, 'v1'),
|
||||
snapshot([wreck('a'), wreck('b')], 'v2'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.rebuilds, 1);
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.rebuilds, 2);
|
||||
assert.equal(h.markers.billboards.length, 2);
|
||||
});
|
||||
|
||||
test('a response that arrives after the layer is turned off is ignored', async () => {
|
||||
const late = deferred();
|
||||
const h = harness({ snapshots: [late.promise] });
|
||||
h.layer.enable();
|
||||
const pending = h.layer.update();
|
||||
h.layer.disable();
|
||||
assert.equal(h.requests[0].aborted, true);
|
||||
late.resolve(snapshot([wreck('a')]));
|
||||
assert.equal(await pending, false);
|
||||
assert.equal(h.markers.billboards.length, 0);
|
||||
});
|
||||
|
||||
test('a click opens the card; a period that excludes the wreck closes it', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([wreck('old', { year: 1850 }), wreck('new', { year: 1990 })]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
h.pick('old');
|
||||
h.handlers[0].click({ position: { x: 1, y: 1 } });
|
||||
const [card] = h.lastCard();
|
||||
assert.equal(card.id, 'shipwreck-card:old');
|
||||
h.layer.setParams({ from: 1900, to: 1990 });
|
||||
assert.deepEqual(h.lastCard(), [], 'the hidden wreck loses its card');
|
||||
const shown = h.markers.billboards.filter((billboard) => billboard.show);
|
||||
assert.deepEqual(
|
||||
shown.map((billboard) => billboard.id),
|
||||
['shipwreck:new'],
|
||||
);
|
||||
assert.equal(h.layer.getStats().count, 1);
|
||||
});
|
||||
|
||||
test('the year pickers list only years with a wreck, and each era is counted', async () => {
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
snapshot([
|
||||
wreck('a', { year: 300 }),
|
||||
wreck('b', { year: 1912 }),
|
||||
wreck('c', { year: 1912 }),
|
||||
wreck('d', { year: 1990 }),
|
||||
wreck('e', { year: null }),
|
||||
]),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
let controls = h.layer.getRowControls();
|
||||
assert.deepEqual(
|
||||
controls.range.options.map((option) => option.value),
|
||||
[1990, 1912, 300],
|
||||
);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((era) => era.count),
|
||||
[1, 2, 1, 1],
|
||||
);
|
||||
h.layer.setParams({ from: 1900, to: 1950 });
|
||||
controls = h.layer.getRowControls();
|
||||
assert.deepEqual(
|
||||
controls.range.options.map((option) => option.value),
|
||||
[1990, 1950, 1912, 1900, 300],
|
||||
'the chosen ends are listed too',
|
||||
);
|
||||
assert.deepEqual(
|
||||
controls.legend.map((era) => era.count),
|
||||
[0, 2, 0, 0],
|
||||
);
|
||||
});
|
||||
|
||||
test('a source without a version rebuilds on every new snapshot', async () => {
|
||||
const bare = (records) => {
|
||||
const value = snapshot(records);
|
||||
delete value.version;
|
||||
return value;
|
||||
};
|
||||
const h = harness({
|
||||
snapshots: [
|
||||
bare([wreck('a')]),
|
||||
bare([wreck('a'), wreck('b')]),
|
||||
{ ...snapshot([wreck('a')]), version: null },
|
||||
{ ...snapshot([wreck('a'), wreck('b'), wreck('c')]), version: null },
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
for (const expected of [1, 2, 1, 3]) {
|
||||
await h.layer.update();
|
||||
assert.equal(h.markers.billboards.length, expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed refresh marks the shown wrecks stale, and clears them after seven days', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
let clock = 1;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
snapshot([wreck('a')]),
|
||||
new Error('Shipwrecks unavailable (HTTP 502)'),
|
||||
new Error('Shipwrecks unavailable (HTTP 502)'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().stale, false);
|
||||
clock = 1 + 2 * DAY;
|
||||
assert.equal(await h.layer.update(), false);
|
||||
assert.equal(h.layer.getStats().stale, true);
|
||||
assert.equal(h.layer.getStats().count, 1, 'still shown, as stale');
|
||||
clock = 1 + 8 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().count, 0, 'expired wrecks leave the map');
|
||||
assert.equal(h.markers.billboards.length, 0);
|
||||
});
|
||||
|
||||
test('expiry runs on the page clock and keeps every wreck until the newest source is too old', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const down = () => new Error('Shipwrecks unavailable (HTTP 502)');
|
||||
// The page clock is far from the proxy's fetchedAt: only reported ages count.
|
||||
let clock = 5e12;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
{
|
||||
...snapshot([
|
||||
wreck('fresh', { source: 'emodnet' }),
|
||||
wreck('merged', { source: 'wikidata', alsoIn: 'emodnet' }),
|
||||
]),
|
||||
fetchedAt: 1,
|
||||
ages: { emodnet: 0, wikidata: 6.5 * DAY },
|
||||
maxAgeMs: 7 * DAY,
|
||||
},
|
||||
down(),
|
||||
down(),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
clock += 1 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(
|
||||
h.layer.getStats().count,
|
||||
2,
|
||||
'nothing leaves while EMODnet is in date',
|
||||
);
|
||||
assert.equal(h.layer.getStats().stale, true);
|
||||
clock += 6.5 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(
|
||||
h.layer.getStats().count,
|
||||
0,
|
||||
'all leave once the newest is too old',
|
||||
);
|
||||
});
|
||||
|
||||
test('a snapshot with no timestamp or ages still expires seven days after it arrived', async () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
let clock = 100;
|
||||
const h = harness({
|
||||
now: () => clock,
|
||||
snapshots: [
|
||||
{ ...snapshot([wreck('a')]), fetchedAt: null },
|
||||
new Error('down'),
|
||||
],
|
||||
});
|
||||
h.layer.enable();
|
||||
await h.layer.update();
|
||||
clock += 8 * DAY;
|
||||
await h.layer.update();
|
||||
assert.equal(h.layer.getStats().count, 0);
|
||||
});
|
||||
|
||||
test('the page deadline subtracts the newest available source age from the limit', () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const both = { emodnet: true, wikidata: true };
|
||||
assert.equal(
|
||||
snapshotDeadline(
|
||||
{
|
||||
sources: both,
|
||||
ages: { emodnet: 2 * DAY, wikidata: 6.5 * DAY },
|
||||
maxAgeMs: 5 * DAY,
|
||||
},
|
||||
100,
|
||||
),
|
||||
100 + 3 * DAY,
|
||||
);
|
||||
assert.equal(
|
||||
snapshotDeadline(
|
||||
{
|
||||
sources: { emodnet: false, wikidata: true },
|
||||
ages: { emodnet: null, wikidata: 4 * DAY },
|
||||
maxAgeMs: 5 * DAY,
|
||||
},
|
||||
0,
|
||||
),
|
||||
1 * DAY,
|
||||
'an unavailable source does not count',
|
||||
);
|
||||
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* The sinking year, or null when it is unknown (ancient wrecks dated only by
|
||||
* period, "C1st AD", have none).
|
||||
*/
|
||||
export function recordYear(record) {
|
||||
return Number.isInteger(record?.year) ? record.year : null;
|
||||
}
|
||||
|
||||
/** First and last year present in the records (null when none is dated). */
|
||||
export function yearExtent(records) {
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (const record of records) {
|
||||
const year = recordYear(record);
|
||||
if (year === null) continue;
|
||||
if (year < min) min = year;
|
||||
if (year > max) max = year;
|
||||
}
|
||||
return Number.isFinite(min) ? { min, max } : null;
|
||||
}
|
||||
|
||||
function yearParam(value) {
|
||||
if (value === null) return null;
|
||||
const year =
|
||||
typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value;
|
||||
return Number.isInteger(year) && Math.abs(year) < 10000 ? year : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a (partial) period request into the current one. `from: null` means
|
||||
* the first year in the data and `to: null` the latest; an invalid year keeps
|
||||
* the current one, and a start after the end is stored as the reverse.
|
||||
* @param {{from?: number|string|null, to?: number|string|null}} params
|
||||
* @param {{from: number|null, to: number|null}} current
|
||||
* @returns {{from: number|null, to: number|null}}
|
||||
*/
|
||||
export function normalizePeriod(
|
||||
params = {},
|
||||
current = { from: null, to: null },
|
||||
) {
|
||||
const next = { ...current };
|
||||
for (const end of ['from', 'to']) {
|
||||
if (!(end in params)) continue;
|
||||
const year = yearParam(params[end]);
|
||||
if (year !== undefined) next[end] = year;
|
||||
}
|
||||
// Stored in the order it is shown, so a later edit to one end (the picker
|
||||
// sends only that end) changes the end the reader picked, not the other.
|
||||
if (Number.isInteger(next.from) && Number.isInteger(next.to))
|
||||
if (next.from > next.to) [next.from, next.to] = [next.to, next.from];
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The inclusive year range a period covers over the data's extent. Years are
|
||||
* clamped to the data, and a start after the end is read as the reverse.
|
||||
* @returns {{from: number, to: number, all: boolean}|null}
|
||||
*/
|
||||
export function periodRange(period, extent) {
|
||||
if (!extent) return null;
|
||||
const clamp = (year, fallback) =>
|
||||
Math.min(extent.max, Math.max(extent.min, year ?? fallback));
|
||||
const start = clamp(period.from, extent.min);
|
||||
const end = clamp(period.to, extent.max);
|
||||
const from = Math.min(start, end);
|
||||
const to = Math.max(start, end);
|
||||
return { from, to, all: from === extent.min && to === extent.max };
|
||||
}
|
||||
|
||||
/** Whether a record falls in the range; undated records only when all years show. */
|
||||
export function inPeriod(record, range) {
|
||||
if (!range || range.all) return true;
|
||||
const year = recordYear(record);
|
||||
return year !== null && year >= range.from && year <= range.to;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
inPeriod,
|
||||
normalizePeriod,
|
||||
periodRange,
|
||||
recordYear,
|
||||
yearExtent,
|
||||
} from './period.js';
|
||||
|
||||
const RECORDS = [
|
||||
{ year: 1588 },
|
||||
{ year: 1912 },
|
||||
{ year: 2012 },
|
||||
{ year: null, ancient: true },
|
||||
];
|
||||
|
||||
test('years come from the record; the extent ignores undated wrecks', () => {
|
||||
assert.equal(recordYear(RECORDS[1]), 1912);
|
||||
assert.equal(recordYear(RECORDS[3]), null);
|
||||
assert.deepEqual(yearExtent(RECORDS), { min: 1588, max: 2012 });
|
||||
assert.equal(yearExtent([{ year: null }]), null);
|
||||
});
|
||||
|
||||
test('all years show every wreck; a narrower period hides undated ones', () => {
|
||||
const extent = yearExtent(RECORDS);
|
||||
const all = periodRange({ from: null, to: null }, extent);
|
||||
assert.deepEqual(all, { from: 1588, to: 2012, all: true });
|
||||
assert.ok(RECORDS.every((record) => inPeriod(record, all)));
|
||||
const wars = periodRange(normalizePeriod({ from: '1914', to: 1945 }), extent);
|
||||
assert.deepEqual(
|
||||
RECORDS.map((record) => inPeriod(record, wars)),
|
||||
[false, false, false, false],
|
||||
);
|
||||
const reversed = periodRange({ from: 1950, to: 1900 }, extent);
|
||||
assert.deepEqual(reversed, { from: 1900, to: 1950, all: false });
|
||||
assert.equal(inPeriod(RECORDS[1], reversed), true);
|
||||
});
|
||||
|
||||
test('a reversed period is stored as shown, so editing one end keeps the other', () => {
|
||||
const reversed = normalizePeriod({ from: 1950, to: 1900 });
|
||||
assert.deepEqual(reversed, { from: 1900, to: 1950 });
|
||||
// The picker shows 1900–1950; the reader changes "From" to 1920.
|
||||
assert.deepEqual(normalizePeriod({ from: 1920 }, reversed), {
|
||||
from: 1920,
|
||||
to: 1950,
|
||||
});
|
||||
// Moving "From" past "To" reads as the reverse, never an empty range.
|
||||
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: 1900, to: 1950 }), {
|
||||
from: 1950,
|
||||
to: 1960,
|
||||
});
|
||||
// One open end stays open.
|
||||
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: null, to: null }), {
|
||||
from: 1960,
|
||||
to: null,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,455 @@
|
||||
// Shared by the server proxy (server/providers/shipwrecks.js) and the browser
|
||||
// layer, so it must not load the i18n catalogs: values stay data.
|
||||
|
||||
/** EMODnet Human Activities "Cultural Heritage – Ship wrecks" (CC BY 4.0). */
|
||||
export const EMODNET_WFS_URL =
|
||||
'https://ows.emodnet-humanactivities.eu/wfs?service=WFS&request=GetFeature' +
|
||||
'&version=2.0.0&typeNames=emodnet:heritageshipwrecks' +
|
||||
'&outputFormat=application/json&srsName=EPSG:4326';
|
||||
/** Landing page shown when an EMODnet wreck has no web page of its own. */
|
||||
export const EMODNET_PAGE_URL =
|
||||
'https://emodnet.ec.europa.eu/en/human-activities';
|
||||
|
||||
export const SHIPWRECK_SOURCES = Object.freeze(['emodnet', 'wikidata']);
|
||||
|
||||
/**
|
||||
* Wikidata (CC0): shipwreck items that have at least one Wikipedia article,
|
||||
* so the worldwide set stays to notable wrecks and skips bulk register
|
||||
* imports, plus sinking events ("sinking of the RMS Titanic"), which are where
|
||||
* Wikidata keeps the death toll. Dates, the end of service (P576) included,
|
||||
* come with their precision so a month-precise date is not shown as the 1st.
|
||||
* Only ship and event facts are read: no items about people.
|
||||
*/
|
||||
export const WIKIDATA_QUERY = `SELECT ?item ?itemLabel ?itemDescription ?coord ?sunk ?sunkPrecision ?end ?endPrecision ?deaths ?survivors ?typeLabel ?enwiki ?event WHERE {
|
||||
{
|
||||
?item wdt:P31/wdt:P279* wd:Q852190 ; wdt:P625 ?coord ; wikibase:sitelinks ?links .
|
||||
FILTER(?links > 0)
|
||||
OPTIONAL { ?item p:P793 ?wreck . ?wreck ps:P793 wd:Q906512 ; pqv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
|
||||
OPTIONAL { ?item p:P576 [ a wikibase:BestRank ; psv:P576 [ wikibase:timeValue ?end ; wikibase:timePrecision ?endPrecision ] ] }
|
||||
OPTIONAL { ?item wdt:P31 ?type . FILTER(?type != wd:Q852190) }
|
||||
} UNION {
|
||||
?item wdt:P31/wdt:P279* wd:Q906512 ; wdt:P625 ?coord .
|
||||
BIND("event" AS ?event)
|
||||
OPTIONAL { ?item p:P585/psv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
|
||||
OPTIONAL { ?item wdt:P1561 ?survivors }
|
||||
}
|
||||
OPTIONAL { ?item wdt:P1120 ?deaths }
|
||||
OPTIONAL { ?enwiki schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> }
|
||||
SERVICE wikibase:label { bd:serviceParam wikibase:language "en,mul,fr,de,es,it,pt,ru,uk,ja,zh,ar". }
|
||||
}`;
|
||||
|
||||
const MAX_TEXT = 160;
|
||||
const MAX_NOTE = 260;
|
||||
/** Same name within this distance: one wreck seen by both sources. */
|
||||
const SAME_WRECK_KM = 3;
|
||||
|
||||
// Free text sometimes names people (owners, masters, divers who reported a
|
||||
// wreck). The layer is about ships, so text that refers to a person by a title
|
||||
// or role is dropped whole. This is a keyword filter: a bare name with none of
|
||||
// these words still passes.
|
||||
const PERSON_TEXT =
|
||||
/\b(mr|mrs|ms|dr|capt|captain|master|skipper|owner|owned|crew|body|bodies|drowned|reported by|according to)\b/i;
|
||||
|
||||
/** EMODnet writes "n/a" or nothing where a value is unknown. */
|
||||
function clean(value, max = MAX_TEXT) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value
|
||||
.replace(/[\u0000-\u001f<>]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!text || /^(n\/a|null|unknown|none|-)$/i.test(text)) return null;
|
||||
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
|
||||
}
|
||||
|
||||
/** Free text with none of the person keywords in it, or null. */
|
||||
function impersonalText(value, max) {
|
||||
const text = clean(value, max);
|
||||
return text && !PERSON_TEXT.test(text) ? text : null;
|
||||
}
|
||||
|
||||
function positiveNumber(value, max) {
|
||||
const n = typeof value === 'number' ? value : Number(value);
|
||||
return Number.isFinite(n) && n > 0 && n <= max ? n : null;
|
||||
}
|
||||
|
||||
function count(value) {
|
||||
const text = String(value ?? '').replace(/\.0+$/, '');
|
||||
if (!/^\d{1,6}$/.test(text)) return null;
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
/** A sinking year from "1917", "1917-1918" or "c. 1917"; null otherwise. */
|
||||
export function parseYear(value, maxYear = new Date().getUTCFullYear()) {
|
||||
const match = /(?:^|\D)(\d{3,4})(?:\D|$)/.exec(String(value ?? ''));
|
||||
if (!match) return null;
|
||||
const year = Number(match[1]);
|
||||
return year >= 100 && year <= maxYear ? year : null;
|
||||
}
|
||||
|
||||
function validPoint(lat, lon) {
|
||||
return (
|
||||
Number.isFinite(lat) &&
|
||||
Number.isFinite(lon) &&
|
||||
Math.abs(lat) <= 90 &&
|
||||
Math.abs(lon) <= 180 &&
|
||||
!(lat === 0 && lon === 0)
|
||||
);
|
||||
}
|
||||
|
||||
function httpUrl(value) {
|
||||
const text = clean(value, 400);
|
||||
if (!text) return null;
|
||||
try {
|
||||
const url = new URL(text);
|
||||
return url.protocol === 'https:' || url.protocol === 'http:'
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a provenance or link value points at wrecksite.eu, in any form. */
|
||||
function fromWrecksite(value) {
|
||||
return typeof value === 'string' && /wrecksite/i.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize EMODnet's shipwreck GeoJSON. Records the portal took from
|
||||
* wrecksite.eu, named in the provenance or linked as the record's page, are
|
||||
* skipped: that site's data is not openly licensed.
|
||||
* @param {object} payload WFS GeoJSON FeatureCollection.
|
||||
* @returns {object[]} Shipwreck records.
|
||||
*/
|
||||
export function normalizeEmodnetFeatures(payload) {
|
||||
const features = payload?.features;
|
||||
if (!Array.isArray(features)) return [];
|
||||
const out = [];
|
||||
const ids = new Set();
|
||||
for (const feature of features) {
|
||||
const p = feature?.properties || {};
|
||||
const coords = feature?.geometry?.coordinates;
|
||||
if (feature?.geometry?.type !== 'Point' || !Array.isArray(coords)) continue;
|
||||
const lon = Number(coords[0]);
|
||||
const lat = Number(coords[1]);
|
||||
if (!validPoint(lat, lon)) continue;
|
||||
// Checked on the raw values: the shown origin is cut to 80 characters,
|
||||
// and a long provenance list can name wrecksite.eu after the cut.
|
||||
if (fromWrecksite(p.source_inf) || fromWrecksite(p.website1)) continue;
|
||||
const origin = clean(p.source_inf, 80);
|
||||
const key = clean(String(feature.id ?? p.source_id ?? ''), 80);
|
||||
if (!key) continue;
|
||||
const id = `emodnet:${key}`;
|
||||
if (ids.has(id)) continue;
|
||||
ids.add(id);
|
||||
const year = parseYear(p.sink_yr);
|
||||
const dating = clean(p.dating, 60);
|
||||
const period = clean(p.period, 60);
|
||||
const vesselType =
|
||||
clean(p.obj_type, 60) ||
|
||||
(() => {
|
||||
// ship_char is sometimes a short type ("Trawler"), sometimes a long
|
||||
// history that can name people; only the short form is a type.
|
||||
const text = clean(p.ship_char, 40);
|
||||
return text && !/\d/.test(text) && !PERSON_TEXT.test(text)
|
||||
? text
|
||||
: null;
|
||||
})();
|
||||
out.push({
|
||||
id,
|
||||
source: 'emodnet',
|
||||
lat,
|
||||
lon,
|
||||
name: clean(p.name, 100),
|
||||
vesselType,
|
||||
year,
|
||||
date: null,
|
||||
dating: year ? null : dating,
|
||||
ancient: !year && Boolean(period || dating),
|
||||
cause: impersonalText(p.sink_context, MAX_NOTE),
|
||||
notes: period && dating ? `${period} (${dating})` : period,
|
||||
cargo: impersonalText(p.artefacts, 120),
|
||||
protected: /protected/i.test(p.statutory || ''),
|
||||
depth: positiveNumber(p.least_depth, 11000),
|
||||
depthQuality: clean(p.depth_prec, 80),
|
||||
positionAccuracy: positiveNumber(p.loc_prec, 100000),
|
||||
positionNote: /centroid/i.test(p.point_info || '')
|
||||
? 'Centre of the protected area'
|
||||
: null,
|
||||
casualties: null,
|
||||
survivors: null,
|
||||
country: clean(p.country, 60),
|
||||
originator: origin,
|
||||
url: httpUrl(p.website1),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function wikiUrl(value) {
|
||||
const url = httpUrl(value);
|
||||
return url && /^https:\/\/[a-z]{2,3}\.wikipedia\.org\/wiki\//.test(url)
|
||||
? url
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Wikidata time as a day ("1912-04-15") when it is day-precise, else as a
|
||||
* year only: a month- or year-precise value reads back as the 1st. A year
|
||||
* before AD 100 ("-0299", 300 BC) has no place on the year picker, so it is
|
||||
* kept as ancient with its year as text, like EMODnet's period-dated wrecks.
|
||||
* @returns {{date: string|null, year: number|null, dating: string|null}}
|
||||
*/
|
||||
function wikidataTime(value, precision) {
|
||||
const none = { date: null, year: null, dating: null };
|
||||
const match = /^([+-]?)(\d{4,})-(\d{2})-(\d{2})T/.exec(value || '');
|
||||
if (!match) return none;
|
||||
// A value without a precision is only trusted to the year.
|
||||
const p = precision == null ? 9 : Number(precision);
|
||||
// 11 = day; 10 = month; 9 = year; below 9 is a decade or coarser.
|
||||
if (!Number.isFinite(p) || p < 9) return none;
|
||||
const signed = Number(`${match[1] === '-' ? '-' : ''}${match[2]}`);
|
||||
if (signed < 100) {
|
||||
// The query service writes XSD 1.1 years: 0000 is 1 BC, -0299 is 300 BC.
|
||||
const dating = signed <= 0 ? `${1 - signed} BC` : `AD ${signed}`;
|
||||
return { date: null, year: null, dating };
|
||||
}
|
||||
const year = parseYear(String(signed));
|
||||
if (year === null) return none;
|
||||
if (p >= 11)
|
||||
return { date: `${match[2]}-${match[3]}-${match[4]}`, year, dating: null };
|
||||
return { date: null, year, dating: null };
|
||||
}
|
||||
|
||||
/** Whether a record (or a parsed time) says when the ship sank. */
|
||||
function hasWhen(when) {
|
||||
return Boolean(when.date || Number.isInteger(when.year) || when.dating);
|
||||
}
|
||||
|
||||
/** Copy when a ship sank from one record (or parsed time) to another. */
|
||||
function takeWhen(target, from) {
|
||||
target.date = from.date ?? null;
|
||||
target.year = from.year ?? null;
|
||||
target.dating = from.dating ?? null;
|
||||
target.ancient = Boolean(from.dating) || Boolean(from.ancient);
|
||||
}
|
||||
|
||||
/** "sinking of the RMS Titanic" → "Sinking of the RMS Titanic". */
|
||||
function sentenceCase(text) {
|
||||
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize Wikidata SPARQL results to shipwreck records (one per item).
|
||||
* Sinking events are folded into the ship they sank when both are listed.
|
||||
* @param {object} payload SPARQL JSON results.
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function normalizeWikidataResults(payload) {
|
||||
const bindings = payload?.results?.bindings;
|
||||
if (!Array.isArray(bindings)) return [];
|
||||
const byItem = new Map();
|
||||
for (const binding of bindings) {
|
||||
const value = (key) => binding?.[key]?.value;
|
||||
const qid = /\/entity\/(Q\d{1,12})$/.exec(value('item') || '')?.[1];
|
||||
if (!qid) continue;
|
||||
const sunk = wikidataTime(value('sunk'), value('sunkPrecision'));
|
||||
const ended = wikidataTime(value('end'), value('endPrecision'));
|
||||
const known = byItem.get(qid);
|
||||
if (known) {
|
||||
// Extra rows only add what the first one lacked.
|
||||
known.vesselType ||= clean(value('typeLabel'), 60);
|
||||
if (!hasWhen(known)) takeWhen(known, hasWhen(sunk) ? sunk : ended);
|
||||
known.casualties ??= count(value('deaths'));
|
||||
known.survivors ??= count(value('survivors'));
|
||||
continue;
|
||||
}
|
||||
const point = /^Point\(([-\d.eE]+) ([-\d.eE]+)\)$/.exec(
|
||||
value('coord') || '',
|
||||
);
|
||||
const lon = point ? Number(point[1]) : NaN;
|
||||
const lat = point ? Number(point[2]) : NaN;
|
||||
if (!validPoint(lat, lon)) continue;
|
||||
const name = clean(value('itemLabel'), 100);
|
||||
const event = value('event') === 'event';
|
||||
const when = hasWhen(sunk) ? sunk : ended;
|
||||
byItem.set(qid, {
|
||||
id: `wikidata:${qid}`,
|
||||
source: 'wikidata',
|
||||
event,
|
||||
lat,
|
||||
lon,
|
||||
// An unlabelled item reads back as its own Q-id; that is no name.
|
||||
name: name && name !== qid ? (event ? sentenceCase(name) : name) : null,
|
||||
vesselType: event ? null : clean(value('typeLabel'), 60),
|
||||
year: when.year,
|
||||
date: when.date,
|
||||
dating: when.dating,
|
||||
ancient: Boolean(when.dating),
|
||||
cause: null,
|
||||
notes: impersonalText(value('itemDescription'), MAX_TEXT),
|
||||
cargo: null,
|
||||
protected: false,
|
||||
depth: null,
|
||||
depthQuality: null,
|
||||
positionAccuracy: null,
|
||||
positionNote: null,
|
||||
casualties: count(value('deaths')),
|
||||
survivors: count(value('survivors')),
|
||||
country: null,
|
||||
originator: null,
|
||||
url:
|
||||
// English Wikipedia, else the Wikidata item, which links the
|
||||
// article in every language that has one.
|
||||
wikiUrl(value('enwiki')) || `https://www.wikidata.org/wiki/${qid}`,
|
||||
});
|
||||
}
|
||||
return foldSinkingEvents([...byItem.values()]);
|
||||
}
|
||||
|
||||
/** An event this far from a listed ship whose name it contains is that ship's sinking. */
|
||||
const SAME_SINKING_KM = 50;
|
||||
|
||||
/**
|
||||
* "Sinking of the RMS Titanic" near the RMS Titanic wreck is one marker: the
|
||||
* ship keeps its article and takes the event's date, deaths and survivors.
|
||||
*/
|
||||
function foldSinkingEvents(records) {
|
||||
// Wikidata sometimes has both the ship and its wreck as items at one spot
|
||||
// ("Titanic", "wreck of the RMS Titanic"): keep the ship, one marker.
|
||||
const isWreckItem = (record) => (/^wreck\b/i.test(record.name || '') ? 1 : 0);
|
||||
const ships = [];
|
||||
const candidates = records
|
||||
.filter((record) => !record.event)
|
||||
.sort((a, b) => isWreckItem(a) - isWreckItem(b));
|
||||
for (const record of candidates) {
|
||||
const key = nameKey(record.name);
|
||||
const twin =
|
||||
key &&
|
||||
ships.find(
|
||||
(ship) =>
|
||||
nameKey(ship.name) === key &&
|
||||
distanceKm(ship, record) <= SAME_WRECK_KM,
|
||||
);
|
||||
if (!twin) {
|
||||
ships.push(record);
|
||||
continue;
|
||||
}
|
||||
twin.vesselType ||= record.vesselType;
|
||||
if (!hasWhen(twin)) takeWhen(twin, record);
|
||||
twin.casualties ??= record.casualties;
|
||||
twin.survivors ??= record.survivors;
|
||||
}
|
||||
const out = [...ships];
|
||||
for (const event of records.filter((record) => record.event)) {
|
||||
const eventKey = ` ${nameKey(event.name)} `;
|
||||
const ship = ships.find((candidate) => {
|
||||
const key = nameKey(candidate.name);
|
||||
return (
|
||||
key.length >= 3 &&
|
||||
eventKey.includes(` ${key} `) &&
|
||||
distanceKm(candidate, event) <= SAME_SINKING_KM
|
||||
);
|
||||
});
|
||||
if (!ship) {
|
||||
out.push(event);
|
||||
continue;
|
||||
}
|
||||
if (!hasWhen(ship)) {
|
||||
takeWhen(ship, event);
|
||||
} else if (!ship.date && event.date && event.year === ship.year) {
|
||||
ship.date = event.date;
|
||||
}
|
||||
ship.casualties ??= event.casualties;
|
||||
ship.survivors ??= event.survivors;
|
||||
}
|
||||
for (const record of out) delete record.event;
|
||||
return out;
|
||||
}
|
||||
|
||||
function nameKey(name) {
|
||||
return String(name || '')
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/\([^)]*\)/g, ' ')
|
||||
.replace(/\b(wreck|sinking|loss|disaster|of)\b/g, ' ')
|
||||
.replace(
|
||||
/\b(hms|hmt|hmhs|hmas|sms|ss|ms|mv|rms|uss|hm|s\/s|m\/v|the)\b/g,
|
||||
' ',
|
||||
)
|
||||
.replace(/[^a-z0-9]+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function distanceKm(a, b) {
|
||||
const rad = Math.PI / 180;
|
||||
const dLat = (b.lat - a.lat) * rad;
|
||||
const dLon = (b.lon - a.lon) * rad;
|
||||
const h =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
|
||||
return 12742 * Math.asin(Math.min(1, Math.sqrt(h)));
|
||||
}
|
||||
|
||||
/**
|
||||
* One list from both sources. A wreck in both (same name, a few km apart)
|
||||
* keeps the Wikidata record, which links an article, and takes EMODnet's
|
||||
* survey facts (depth, sinking text, year) that Wikidata lacks.
|
||||
*/
|
||||
export function mergeShipwreckRecords(emodnet = [], wikidata = []) {
|
||||
const byName = new Map();
|
||||
for (const record of wikidata) {
|
||||
const key = nameKey(record.name);
|
||||
if (!key) continue;
|
||||
if (!byName.has(key)) byName.set(key, []);
|
||||
byName.get(key).push(record);
|
||||
}
|
||||
const kept = [];
|
||||
for (const record of emodnet) {
|
||||
const twin = (byName.get(nameKey(record.name)) || []).find(
|
||||
(candidate) => distanceKm(candidate, record) <= SAME_WRECK_KM,
|
||||
);
|
||||
if (!twin) {
|
||||
kept.push(record);
|
||||
continue;
|
||||
}
|
||||
if (!hasWhen(twin)) takeWhen(twin, record);
|
||||
twin.vesselType ||= record.vesselType;
|
||||
twin.cause ||= record.cause;
|
||||
twin.depth ??= record.depth;
|
||||
twin.depthQuality ||= record.depthQuality;
|
||||
twin.positionAccuracy ??= record.positionAccuracy;
|
||||
twin.country ||= record.country;
|
||||
twin.protected ||= record.protected;
|
||||
twin.alsoIn = 'emodnet';
|
||||
}
|
||||
return [...wikidata, ...kept];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the proxy's snapshot in the browser.
|
||||
* @returns {object[]|null} Records, or null when the payload is malformed.
|
||||
*/
|
||||
export function normalizeShipwreckSnapshot(payload) {
|
||||
if (!Array.isArray(payload?.records)) return null;
|
||||
const rows = [];
|
||||
const ids = new Set();
|
||||
for (const record of payload.records) {
|
||||
if (
|
||||
!record ||
|
||||
typeof record.id !== 'string' ||
|
||||
ids.has(record.id) ||
|
||||
!SHIPWRECK_SOURCES.includes(record.source) ||
|
||||
!validPoint(record.lat, record.lon)
|
||||
)
|
||||
continue;
|
||||
ids.add(record.id);
|
||||
rows.push({
|
||||
...record,
|
||||
year: Number.isInteger(record.year) ? record.year : null,
|
||||
url: httpUrl(record.url),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
mergeShipwreckRecords,
|
||||
normalizeEmodnetFeatures,
|
||||
normalizeShipwreckSnapshot,
|
||||
normalizeWikidataResults,
|
||||
parseYear,
|
||||
WIKIDATA_QUERY,
|
||||
} from './records.js';
|
||||
|
||||
function feature(id, properties, coordinates = [-4.35, 54.13]) {
|
||||
return {
|
||||
type: 'Feature',
|
||||
id,
|
||||
geometry: { type: 'Point', coordinates },
|
||||
properties,
|
||||
};
|
||||
}
|
||||
|
||||
test('EMODnet wrecks keep ship facts and drop text that names people', () => {
|
||||
const [wreck, roman] = normalizeEmodnetFeatures({
|
||||
features: [
|
||||
feature('w.1', {
|
||||
name: 'MAINA-NUI',
|
||||
sink_yr: '1987',
|
||||
sink_context: 'Sank on 07/02/1987',
|
||||
obj_type: 'Pusher or tug',
|
||||
least_depth: 12.5,
|
||||
depth_prec: 'Least depth known',
|
||||
loc_prec: 50,
|
||||
country: 'France',
|
||||
source_inf: 'SHOM',
|
||||
statutory: 'n/a',
|
||||
website1: 'n/a',
|
||||
}),
|
||||
feature('w.2', {
|
||||
name: 'Lerici',
|
||||
sink_yr: '',
|
||||
dating: 'C1st-2nd AD',
|
||||
period: 'Roman Imperial',
|
||||
artefacts: 'Marble, Columns',
|
||||
obj_type: 'n/a',
|
||||
ship_char: 'Owned by J. Smith, master was A. Jones',
|
||||
sink_context: 'Wrecked here, reported by Mr Smith',
|
||||
}),
|
||||
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
|
||||
feature('w.4', { name: 'Null island' }, [0, 0]),
|
||||
],
|
||||
});
|
||||
const ids = normalizeEmodnetFeatures({
|
||||
features: [
|
||||
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
|
||||
feature('w.5', {
|
||||
source_inf: `${'SHOM; '.repeat(20)}wrecksite.eu`,
|
||||
}),
|
||||
feature('w.6', { website1: 'https://www.wrecksite.eu/wreck.aspx?1' }),
|
||||
feature('w.7', { website1: 'wrecksite.eu/wreck/1' }),
|
||||
feature('w.8', { name: 'Kept', source_inf: 'SHOM' }),
|
||||
],
|
||||
}).map((record) => record.id);
|
||||
assert.deepEqual(ids, ['emodnet:w.8'], 'wrecksite.eu rows are all skipped');
|
||||
assert.equal(wreck.id, 'emodnet:w.1');
|
||||
assert.equal(wreck.year, 1987);
|
||||
assert.equal(wreck.vesselType, 'Pusher or tug');
|
||||
assert.equal(wreck.cause, 'Sank on 07/02/1987');
|
||||
assert.equal(wreck.depth, 12.5);
|
||||
assert.equal(wreck.positionAccuracy, 50);
|
||||
assert.equal(wreck.url, null);
|
||||
assert.equal(roman.year, null);
|
||||
assert.equal(roman.ancient, true);
|
||||
assert.equal(roman.dating, 'C1st-2nd AD');
|
||||
assert.equal(roman.notes, 'Roman Imperial (C1st-2nd AD)');
|
||||
assert.equal(roman.cargo, 'Marble, Columns');
|
||||
assert.equal(roman.vesselType, null, 'a history naming people is no type');
|
||||
assert.equal(roman.cause, null, 'text naming a person is dropped');
|
||||
});
|
||||
|
||||
test('Wikidata rows fold into one record per item', () => {
|
||||
const item = 'http://www.wikidata.org/entity/Q1471525';
|
||||
const records = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: { value: item },
|
||||
itemLabel: { value: 'HMS Havant' },
|
||||
itemDescription: { value: '1939 G and H-class destroyer' },
|
||||
coord: { value: 'Point(2.26 51.13)' },
|
||||
sunk: { value: '1940-06-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
enwiki: { value: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)' },
|
||||
},
|
||||
{
|
||||
item: { value: item },
|
||||
typeLabel: { value: 'destroyer' },
|
||||
deaths: { value: '8' },
|
||||
coord: { value: 'Point(2.26 51.13)' },
|
||||
},
|
||||
{
|
||||
item: { value: 'http://www.wikidata.org/entity/Q9' },
|
||||
itemLabel: { value: 'Q9' },
|
||||
coord: { value: 'Point(10 10)' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(records.length, 2);
|
||||
const [havant, unnamed] = records;
|
||||
assert.equal(havant.date, '1940-06-01');
|
||||
assert.equal(havant.year, 1940);
|
||||
assert.equal(havant.vesselType, 'destroyer');
|
||||
assert.equal(havant.casualties, 8);
|
||||
assert.equal(havant.url, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
|
||||
assert.equal(unnamed.name, null);
|
||||
assert.equal(unnamed.url, 'https://www.wikidata.org/wiki/Q9');
|
||||
});
|
||||
|
||||
test('a wreck in both sources keeps Wikidata and takes EMODnet survey facts', () => {
|
||||
const wikidata = [
|
||||
{
|
||||
id: 'wikidata:Q1',
|
||||
source: 'wikidata',
|
||||
name: 'HMS Havant',
|
||||
lat: 51.13,
|
||||
lon: 2.26,
|
||||
year: null,
|
||||
depth: null,
|
||||
},
|
||||
];
|
||||
const emodnet = [
|
||||
{
|
||||
id: 'emodnet:a',
|
||||
source: 'emodnet',
|
||||
name: 'Havant (HMS)',
|
||||
lat: 51.131,
|
||||
lon: 2.262,
|
||||
year: 1940,
|
||||
depth: 14.7,
|
||||
},
|
||||
{
|
||||
id: 'emodnet:b',
|
||||
source: 'emodnet',
|
||||
name: 'HMS Havant',
|
||||
lat: 45,
|
||||
lon: -10,
|
||||
year: 1950,
|
||||
},
|
||||
];
|
||||
const merged = mergeShipwreckRecords(emodnet, wikidata);
|
||||
assert.deepEqual(
|
||||
merged.map((record) => record.id),
|
||||
['wikidata:Q1', 'emodnet:b'],
|
||||
);
|
||||
assert.equal(merged[0].year, 1940);
|
||||
assert.equal(merged[0].depth, 14.7);
|
||||
assert.equal(merged[0].alsoIn, 'emodnet');
|
||||
});
|
||||
|
||||
test('years and snapshots are validated', () => {
|
||||
assert.equal(parseYear('1917-1918'), 1917);
|
||||
assert.equal(parseYear('c. 1588'), 1588);
|
||||
assert.equal(parseYear(''), null);
|
||||
assert.equal(parseYear('3000'), null);
|
||||
assert.equal(normalizeShipwreckSnapshot({}), null);
|
||||
const rows = normalizeShipwreckSnapshot({
|
||||
records: [
|
||||
{ id: 'a', source: 'emodnet', lat: 1, lon: 2, url: 'javascript:x' },
|
||||
{ id: 'a', source: 'emodnet', lat: 1, lon: 2 },
|
||||
{ id: 'b', source: 'other', lat: 1, lon: 2 },
|
||||
{ id: 'c', source: 'wikidata', lat: 91, lon: 2 },
|
||||
],
|
||||
});
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].url, null);
|
||||
});
|
||||
|
||||
test('a sinking event folds into its ship; month-precise dates keep the year only', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const records = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q25173'),
|
||||
itemLabel: { value: 'Titanic' },
|
||||
coord: { value: 'Point(-49.9469 41.7325)' },
|
||||
},
|
||||
{
|
||||
item: entity('Q3018259'),
|
||||
itemLabel: { value: 'wreck of the RMS Titanic' },
|
||||
coord: { value: 'Point(-49.9469 41.7325)' },
|
||||
},
|
||||
{
|
||||
item: entity('Q2577588'),
|
||||
itemLabel: { value: 'sinking of the RMS Titanic' },
|
||||
coord: { value: 'Point(-49.9458 41.7319)' },
|
||||
event: { value: 'event' },
|
||||
sunk: { value: '1912-04-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '10' },
|
||||
deaths: { value: '1501' },
|
||||
survivors: { value: '712' },
|
||||
},
|
||||
{
|
||||
item: entity('Q1245004'),
|
||||
itemLabel: { value: 'Costa Concordia disaster' },
|
||||
coord: { value: 'Point(10.92 42.37)' },
|
||||
event: { value: 'event' },
|
||||
sunk: { value: '2012-01-13T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
deaths: { value: '32' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
records.map((record) => record.id),
|
||||
['wikidata:Q25173', 'wikidata:Q1245004'],
|
||||
);
|
||||
const [titanic, concordia] = records;
|
||||
assert.equal(titanic.date, null);
|
||||
assert.equal(titanic.year, 1912);
|
||||
assert.equal(titanic.casualties, 1501);
|
||||
assert.equal(titanic.survivors, 712);
|
||||
assert.equal(concordia.name, 'Costa Concordia disaster');
|
||||
assert.equal(concordia.date, '2012-01-13');
|
||||
assert.equal('event' in concordia, false);
|
||||
});
|
||||
|
||||
test('a date before AD 100 is kept as ancient text, never read as an AD year', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const [bc, earlyAd, roman] = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q1'),
|
||||
itemLabel: { value: 'Antikythera wreck' },
|
||||
coord: { value: 'Point(23.3 35.9)' },
|
||||
sunk: { value: '-0299-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '11' },
|
||||
},
|
||||
{
|
||||
item: entity('Q2'),
|
||||
itemLabel: { value: 'Early wreck' },
|
||||
coord: { value: 'Point(12 40)' },
|
||||
sunk: { value: '0050-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '9' },
|
||||
},
|
||||
{
|
||||
item: entity('Q3'),
|
||||
itemLabel: { value: 'Roman wreck' },
|
||||
coord: { value: 'Point(13 41)' },
|
||||
sunk: { value: '0300-01-01T00:00:00Z' },
|
||||
sunkPrecision: { value: '9' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(bc.year, null, '300 BC is not the year 300');
|
||||
assert.equal(bc.date, null, 'no day for a BC date');
|
||||
assert.equal(bc.dating, '300 BC');
|
||||
assert.equal(bc.ancient, true);
|
||||
assert.equal(earlyAd.year, null);
|
||||
assert.equal(earlyAd.dating, 'AD 50');
|
||||
assert.equal(earlyAd.ancient, true);
|
||||
assert.equal(roman.year, 300);
|
||||
assert.equal(roman.dating, null);
|
||||
});
|
||||
|
||||
test('an end-of-service date keeps its precision: a year-only one is no day', () => {
|
||||
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
|
||||
const [yearOnly, dayPrecise, unknown] = normalizeWikidataResults({
|
||||
results: {
|
||||
bindings: [
|
||||
{
|
||||
item: entity('Q11'),
|
||||
itemLabel: { value: 'Year only' },
|
||||
coord: { value: 'Point(1 50)' },
|
||||
end: { value: '1917-01-01T00:00:00Z' },
|
||||
endPrecision: { value: '9' },
|
||||
},
|
||||
{
|
||||
item: entity('Q12'),
|
||||
itemLabel: { value: 'Day precise' },
|
||||
coord: { value: 'Point(2 50)' },
|
||||
end: { value: '1917-03-04T00:00:00Z' },
|
||||
endPrecision: { value: '11' },
|
||||
},
|
||||
{
|
||||
item: entity('Q13'),
|
||||
itemLabel: { value: 'No precision' },
|
||||
coord: { value: 'Point(3 50)' },
|
||||
end: { value: '1917-01-01T00:00:00Z' },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(yearOnly.date, null, 'not shown as 1 Jan 1917');
|
||||
assert.equal(yearOnly.year, 1917);
|
||||
assert.equal(dayPrecise.date, '1917-03-04');
|
||||
assert.equal(unknown.date, null, 'an unknown precision is a year only');
|
||||
assert.equal(unknown.year, 1917);
|
||||
});
|
||||
|
||||
test('the query reads the end of service with its precision', () => {
|
||||
assert.match(
|
||||
WIKIDATA_QUERY,
|
||||
/psv:P576 \[ wikibase:timeValue \?end ; wikibase:timePrecision \?endPrecision \]/,
|
||||
);
|
||||
assert.doesNotMatch(WIKIDATA_QUERY, /wdt:P576/);
|
||||
});
|
||||
|
||||
test('labels and links do not default to one other language', () => {
|
||||
assert.doesNotMatch(WIKIDATA_QUERY, /ptwiki|pt\.wikipedia/);
|
||||
assert.match(WIKIDATA_QUERY, /wikibase:language "en,mul,/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { normalizeShipwreckSnapshot } from './records.js';
|
||||
|
||||
const age = (value) => (Number.isFinite(value) && value >= 0 ? value : null);
|
||||
|
||||
/** Same-origin source for the proxy's EMODnet + Wikidata shipwreck snapshot. */
|
||||
export function createShipwrecksSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
return {
|
||||
async getSnapshot({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/shipwrecks', { signal });
|
||||
if (!response.ok)
|
||||
throw new Error(`Shipwrecks unavailable (HTTP ${response.status})`);
|
||||
const payload = await readResponseJsonCapped(
|
||||
response,
|
||||
16 * 1024 * 1024,
|
||||
signal,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
const records = normalizeShipwreckSnapshot(payload);
|
||||
if (!records) throw new Error('Malformed shipwrecks response');
|
||||
return {
|
||||
records,
|
||||
fetchedAt: Number.isFinite(payload.fetchedAt)
|
||||
? payload.fetchedAt
|
||||
: null,
|
||||
stale: payload.stale === true,
|
||||
// Changes whenever either source's data does; null from an older proxy.
|
||||
version: typeof payload.version === 'string' ? payload.version : null,
|
||||
// Each source's age on the proxy's clock (null when unknown).
|
||||
ages: {
|
||||
emodnet: age(payload.ages?.emodnet),
|
||||
wikidata: age(payload.ages?.wikidata),
|
||||
},
|
||||
maxAgeMs: age(payload.maxAgeMs),
|
||||
sources: {
|
||||
emodnet: payload.sources?.emodnet !== false,
|
||||
wikidata: payload.sources?.wikidata !== false,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createShipwrecksSource } from './source.js';
|
||||
|
||||
const respond = (payload) =>
|
||||
createShipwrecksSource({ fetchImpl: async () => Response.json(payload) });
|
||||
|
||||
test('the snapshot keeps valid source ages and drops malformed ones', async () => {
|
||||
const record = { id: 'a', source: 'emodnet', lat: 50, lon: -1 };
|
||||
const good = await respond({
|
||||
records: [record],
|
||||
version: 'v',
|
||||
ages: { emodnet: 0, wikidata: 3600 },
|
||||
maxAgeMs: 604800000,
|
||||
}).getSnapshot();
|
||||
assert.deepEqual(good.ages, { emodnet: 0, wikidata: 3600 });
|
||||
assert.equal(good.maxAgeMs, 604800000);
|
||||
assert.equal(good.version, 'v');
|
||||
const bad = await respond({
|
||||
records: [record],
|
||||
ages: { emodnet: -5, wikidata: 'x' },
|
||||
maxAgeMs: Number.NaN,
|
||||
}).getSnapshot();
|
||||
assert.deepEqual(bad.ages, { emodnet: null, wikidata: null });
|
||||
assert.equal(bad.maxAgeMs, null);
|
||||
assert.equal(bad.version, null);
|
||||
});
|
||||
@@ -33,6 +33,8 @@ const COCKPIT_REFUSALS = Object.freeze({
|
||||
// «View coverage» button); the cyclone layer flies to the selected storm.
|
||||
weather: msg('Exit cockpit to view weather coverage'),
|
||||
cyclone: msg('Exit cockpit to fly to a cyclone'),
|
||||
// The News panel's cards and the news layer's hotspots fly to the event.
|
||||
news: msg('Exit cockpit to fly to a news report'),
|
||||
// Voice track_entity (TRACKABLE_FAMILIES kinds in gevActions.js) and
|
||||
// frame_overhead, which frames the contacts around the current view.
|
||||
aircraft: msg('Exit cockpit to fly to an aircraft'),
|
||||
|
||||
@@ -136,6 +136,7 @@ test('weather layers name their destination in the Cockpit refusal', () => {
|
||||
const expected = {
|
||||
weather: 'Exit cockpit to view weather coverage',
|
||||
cyclone: 'Exit cockpit to fly to a cyclone',
|
||||
news: 'Exit cockpit to fly to a news report',
|
||||
};
|
||||
for (const [noun, text] of Object.entries(expected)) {
|
||||
const s = spy();
|
||||
|
||||
@@ -20,6 +20,8 @@ import { createCycloneSource } from '../layers/cyclones/source.js';
|
||||
import { createWindSource } from '../layers/wind/source.js';
|
||||
import { createFirmsSource } from '../layers/firms/source.js';
|
||||
import { createGhostMapsSource } from '../layers/ghostMaps/source.js';
|
||||
import { createNewsSource } from '../layers/news/source.js';
|
||||
import { createShipwrecksSource } from '../layers/shipwrecks/source.js';
|
||||
import { createMapillarySource } from '../layers/streetLevel/providers/mapillary/source.js';
|
||||
import { createReferenceSources } from '../sources/reference.js';
|
||||
export { createReferenceSources as createStandaloneReferenceSources } from '../sources/reference.js';
|
||||
@@ -60,6 +62,11 @@ export function createStandaloneLayerSources(
|
||||
alpr: createAlprTileSource(),
|
||||
firms: createFirmsSource(),
|
||||
's2-ghostmaps': createGhostMapsSource(),
|
||||
// Same-origin /api/news: the local server proxies GEV_NEWS_ORIGIN and,
|
||||
// without it, answers "not configured", which the layer shows as
|
||||
// unavailable without retrying.
|
||||
news: createNewsSource(),
|
||||
shipwrecks: createShipwrecksSource(),
|
||||
wind: createWindSource(),
|
||||
weather: createWeatherSource(),
|
||||
cyclones: createCycloneSource(),
|
||||
|
||||
@@ -695,7 +695,7 @@ test('public transit documentation uses courtesy attribution and the approved gr
|
||||
);
|
||||
assert.ok(
|
||||
readme.includes(
|
||||
'Twenty-two layers and map sources. **Twenty have a keyless path.**',
|
||||
'Twenty-three layers and map sources. **Twenty-one have a keyless path.**',
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
|
||||
@@ -1,9 +1,29 @@
|
||||
/**
|
||||
* The Cockpit briefing's pages and the state it starts in. It needs only the
|
||||
* i18n module, so the controller and the view can both read it.
|
||||
* i18n module and the regional-news window, so the controller and the view
|
||||
* can both read it.
|
||||
*/
|
||||
import { REGIONAL_NEWS_WINDOW_HOURS } from '../data/regionalNewsWindow.js';
|
||||
import { msg, t } from '../i18n/index.js';
|
||||
|
||||
// i18n-ignore: provider name
|
||||
/** The news feed named before any briefing has answered. */
|
||||
export const DEFAULT_NEWS_SOURCE = 'GOOGLE NEWS RSS';
|
||||
|
||||
/**
|
||||
* The Regional News footer for a fresh, empty or unavailable list: the feed
|
||||
* and the window its articles are held to.
|
||||
* @param {string} [source]
|
||||
* @param {number} [hours]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function newsWindowFooter(
|
||||
source = DEFAULT_NEWS_SOURCE,
|
||||
hours = REGIONAL_NEWS_WINDOW_HOURS,
|
||||
) {
|
||||
return t('{source} · LAST {hours} H', { source, hours });
|
||||
}
|
||||
|
||||
export const COCKPIT_BRIEF_PAGES = [
|
||||
{
|
||||
id: 'signals',
|
||||
@@ -15,8 +35,7 @@ export const COCKPIT_BRIEF_PAGES = [
|
||||
id: 'news',
|
||||
kickerKey: msg('REGIONAL NEWS'),
|
||||
subtitleKey: msg('LATEST LOCATION-MATCHED REPORTING'),
|
||||
sourceKey: msg('{source} · LOCATION QUERY · RECENT'),
|
||||
sourceName: 'GOOGLE NEWS RSS', // i18n-ignore: provider name
|
||||
// The news footer comes from the news state (`news.footer`), not here.
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
@@ -60,6 +79,7 @@ export function createBriefState() {
|
||||
statusHidden: false,
|
||||
state: null,
|
||||
status: t('ACQUIRING REGIONAL NEWS'),
|
||||
footer: newsWindowFooter(),
|
||||
articles: [],
|
||||
},
|
||||
local: {
|
||||
|
||||
+110
-18
@@ -12,7 +12,14 @@ import {
|
||||
COCKPIT_BRIEF_PAGES,
|
||||
CYCLE_HELP_KEYS,
|
||||
createBriefState,
|
||||
newsWindowFooter,
|
||||
} from './cockpitBriefPages.js';
|
||||
import {
|
||||
recentRegionalArticles,
|
||||
regionalNewsWindowHours,
|
||||
} from '../data/regionalNewsWindow.js';
|
||||
|
||||
const NEWS_ROWS = 4;
|
||||
|
||||
// regionalModel.weatherCodeLabel is shared with node code and returns
|
||||
// English; translate it here.
|
||||
@@ -52,8 +59,12 @@ export function showBriefPage(index, { manual = false } = {}) {
|
||||
kicker: t(page.kickerKey),
|
||||
subtitle: t(page.subtitleKey),
|
||||
position: `${this.briefPageIndex + 1} / ${count}`,
|
||||
source: page.sourceKey
|
||||
? t(page.sourceKey, { source: page.sourceName })
|
||||
// The news footer follows the news state, so it survives page changes.
|
||||
source:
|
||||
page.id === 'news'
|
||||
? this.brief.news.footer
|
||||
: page.sourceKey
|
||||
? t(page.sourceKey)
|
||||
: page.source,
|
||||
});
|
||||
this.publishBriefView();
|
||||
@@ -176,6 +187,13 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
)
|
||||
return;
|
||||
|
||||
// The brief held stands in after a failed refresh only near where its news
|
||||
// was read; past the refresh distance it is another place's.
|
||||
const previous =
|
||||
this.services.regionalDistanceM(this.regionalBriefPoint, point) <
|
||||
COCKPIT_REGIONAL_REFRESH_DISTANCE_M
|
||||
? this.regionalBrief
|
||||
: null;
|
||||
this.regionalBriefAnchor = point;
|
||||
this.regionalBriefFetchedAt = Date.now();
|
||||
const controller = new AbortController();
|
||||
@@ -193,8 +211,9 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
subjectId !== this.regionalBriefSubjectId
|
||||
)
|
||||
return;
|
||||
this.regionalBrief = payload;
|
||||
this.renderRegionalBrief(payload, info);
|
||||
this.regionalBrief = withCachedNews(payload, previous);
|
||||
if (this.regionalBrief === payload) this.regionalBriefPoint = point;
|
||||
this.renderRegionalBrief(this.regionalBrief, info);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (
|
||||
@@ -203,8 +222,15 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
requestToken === this.regionalBriefRequestToken &&
|
||||
subjectId === this.regionalBriefSubjectId
|
||||
) {
|
||||
if (previous) {
|
||||
this.regionalBrief = cachedNews(previous, previous);
|
||||
this.renderRegionalBrief(this.regionalBrief, info);
|
||||
} else {
|
||||
// Another place's brief: not to come back with a language change.
|
||||
this.regionalBrief = null;
|
||||
this.renderRegionalBriefStatus('unavailable', info);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.regionalBriefAbort === controller)
|
||||
@@ -212,6 +238,75 @@ export function maybeRefreshRegionalBrief(info) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A brief whose news comes from `previous` after a refresh that brought none:
|
||||
* the earlier articles stay, marked `cached` so they are labelled as such.
|
||||
* @param {object} payload The brief to keep everything else from.
|
||||
* @param {object} previous The last brief rendered for this subject.
|
||||
*/
|
||||
function cachedNews(payload, previous) {
|
||||
return {
|
||||
...payload,
|
||||
newsStatus: 'cached',
|
||||
newsSource: previous.newsSource,
|
||||
newsWindowHours: previous.newsWindowHours,
|
||||
newsFetchedAt: previous.newsFetchedAt ?? previous.retrievedAt ?? null,
|
||||
articles: previous.articles,
|
||||
};
|
||||
}
|
||||
|
||||
// A refresh whose news read failed keeps the articles from before it.
|
||||
function withCachedNews(payload, previous) {
|
||||
return previous && payload?.newsStatus === 'unavailable'
|
||||
? cachedNews(payload, previous)
|
||||
: payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Regional News state a brief presents. `ready` and `cached` have rows
|
||||
* inside the window; `cached` is a refresh that failed (a client-side failure,
|
||||
* or the local proxy's `stale` answer). `empty` is a source that answered with
|
||||
* nothing in the window; anything else is `unavailable`.
|
||||
* @returns {{state: string, status: string, footer: string, articles: object[]}}
|
||||
*/
|
||||
function regionalNewsView(payload) {
|
||||
const hours = regionalNewsWindowHours(payload?.newsWindowHours);
|
||||
// Old caches and the local path are held to the window here too.
|
||||
const articles = recentRegionalArticles(payload?.articles, {
|
||||
windowHours: hours,
|
||||
limit: NEWS_ROWS,
|
||||
});
|
||||
const source = String(
|
||||
payload?.newsSource || t('REGIONAL NEWS'),
|
||||
).toUpperCase();
|
||||
const refreshFailed =
|
||||
payload?.newsStatus === 'cached' || payload?.status === 'stale';
|
||||
if (articles.length && refreshFailed)
|
||||
return {
|
||||
state: 'cached',
|
||||
status: t('CACHED · REFRESH FAILED'),
|
||||
footer: t('{source} · CACHED {age}', {
|
||||
source,
|
||||
age: formatCockpitBriefAge(
|
||||
payload?.newsFetchedAt ?? payload?.retrievedAt,
|
||||
),
|
||||
}),
|
||||
articles,
|
||||
};
|
||||
const answered =
|
||||
!refreshFailed && ['ready', 'empty'].includes(payload?.newsStatus);
|
||||
return {
|
||||
state: articles.length ? 'ready' : answered ? 'empty' : 'unavailable',
|
||||
status: articles.length
|
||||
? ''
|
||||
: answered
|
||||
? t('NO NEWS IN THE LAST {hours} H', { hours })
|
||||
: t('REGIONAL NEWS UNAVAILABLE'),
|
||||
footer: newsWindowFooter(source, hours),
|
||||
articles,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderRegionalBriefStatus(status, info) {
|
||||
const { news, local } = this.brief;
|
||||
news.statusHidden = false;
|
||||
@@ -220,7 +315,10 @@ export function renderRegionalBriefStatus(status, info) {
|
||||
status === 'loading'
|
||||
? t('ACQUIRING REGIONAL NEWS')
|
||||
: t('REGIONAL NEWS UNAVAILABLE');
|
||||
if (status === 'unavailable') news.articles = [];
|
||||
news.footer = newsWindowFooter();
|
||||
// Only called with no brief for this subject: any rows are another's.
|
||||
news.articles = [];
|
||||
if (this.briefPageIndex === 1) this.brief.source = news.footer;
|
||||
if (status === 'loading') local.place = t('RESOLVING REGION');
|
||||
if (status === 'unavailable') local.place = t('REGION UNAVAILABLE');
|
||||
local.coordinates = localCoordinates(info);
|
||||
@@ -228,7 +326,7 @@ export function renderRegionalBriefStatus(status, info) {
|
||||
}
|
||||
|
||||
export function renderRegionalBrief(payload, info) {
|
||||
const articles = Array.isArray(payload?.articles) ? payload.articles : [];
|
||||
const { state, status, footer, articles } = regionalNewsView(payload);
|
||||
const seen = new Map();
|
||||
const storyKey = (url) => {
|
||||
const count = seen.get(url) ?? 0;
|
||||
@@ -241,13 +339,11 @@ export function renderRegionalBrief(payload, info) {
|
||||
const placeLabel =
|
||||
payload?.place?.label || payload?.place?.country || t('REGION UNAVAILABLE');
|
||||
this.brief.news = {
|
||||
statusHidden: articles.length > 0,
|
||||
state: payload?.newsStatus || 'unavailable',
|
||||
status:
|
||||
payload?.newsStatus === 'empty'
|
||||
? t('NO RECENT LOCATION MATCHES')
|
||||
: t('REGIONAL NEWS UNAVAILABLE'),
|
||||
articles: articles.slice(0, 4).map((article) => ({
|
||||
statusHidden: state === 'ready',
|
||||
state,
|
||||
status,
|
||||
footer,
|
||||
articles: articles.map((article) => ({
|
||||
// A row keeps its node, and so its focus, only for the same story.
|
||||
key: storyKey(article.url),
|
||||
url: article.url,
|
||||
@@ -281,11 +377,7 @@ export function renderRegionalBrief(payload, info) {
|
||||
: '—',
|
||||
};
|
||||
this.brief.regionalStatus = payload?.status || 'partial';
|
||||
if (this.briefPageIndex === 1) {
|
||||
this.brief.source = t('{source} · LOCATION QUERY', {
|
||||
source: String(payload?.newsSource || t('REGIONAL NEWS')).toUpperCase(),
|
||||
});
|
||||
}
|
||||
if (this.briefPageIndex === 1) this.brief.source = footer;
|
||||
this.publishBriefView();
|
||||
this.scheduleContextLayout();
|
||||
}
|
||||
+360
-17
@@ -3,11 +3,14 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createPinia } from 'pinia';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { createBriefState } from './cockpitBriefPages.js';
|
||||
import {
|
||||
maybeRefreshRegionalBrief,
|
||||
publishBriefView,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
@@ -88,10 +91,7 @@ test('pages, the cycle toggle and the source follow the controller', async (t) =
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-kicker'), 'REGIONAL NEWS');
|
||||
assert.equal(text('#cockpit-brief-position'), '2 / 3');
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
|
||||
);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
assert.deepEqual(visiblePages(), ['news']);
|
||||
assert.deepEqual(current(), ['false', 'true', 'false']);
|
||||
assert.equal($('#cockpit-signal-stream').dataset.briefPage, 'news');
|
||||
@@ -129,7 +129,8 @@ test('regional news and local conditions render what the region returned', async
|
||||
url: `https://example.com/${index}`,
|
||||
title: `Story ${index}`,
|
||||
domain: 'example.com',
|
||||
publishedAt: new Date().toISOString(),
|
||||
// Newest first is the shown order, so Story 0 is the newest.
|
||||
publishedAt: new Date(Date.now() - index * 60_000).toISOString(),
|
||||
})),
|
||||
weather: {
|
||||
temperatureC: 21.6,
|
||||
@@ -159,7 +160,7 @@ test('regional news and local conditions render what the region returned', async
|
||||
assert.equal(text('#cockpit-local-condition'), 'RAIN');
|
||||
assert.equal(text('#cockpit-local-cloud'), 'CLOUD 40%');
|
||||
assert.equal(text('#cockpit-local-precipitation'), '1.3');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
assert.equal($('#cockpit-signal-stream').dataset.regionalStatus, 'ok');
|
||||
renderRegionalBriefStatus.call(owner, 'unavailable', {});
|
||||
await nextTick();
|
||||
@@ -210,26 +211,293 @@ test('a refreshed news list keeps a focused story on its own link', async (t) =>
|
||||
assert.equal($('#cockpit-news-list').textContent.includes('Story y'), true);
|
||||
});
|
||||
|
||||
test('the news source names the feed only while it is current on page 2', async (t) => {
|
||||
// This contract changed on purpose: the footer used to fall back to a
|
||||
// static "· RECENT" on every page change, which promised nothing. It now
|
||||
// follows the news state and names the window it holds articles to.
|
||||
test('the news footer follows the news state across page changes, not a static RECENT', async (t) => {
|
||||
const { text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'wire',
|
||||
newsWindowHours: 24,
|
||||
articles: [story('a')],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LOCATION QUERY');
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
showBriefPage.call(owner, 2);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 24 H');
|
||||
showBriefPage.call(owner, 0);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'wire',
|
||||
newsWindowHours: 12,
|
||||
articles: [story('a')],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
// Off page 2 the footer is the current page's.
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
|
||||
);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(text('#cockpit-brief-source'), 'WIRE · LAST 12 H');
|
||||
});
|
||||
|
||||
test('the news banner is hidden by the stylesheet, not only by the attribute', async (t) => {
|
||||
// happy-dom applies no author CSS by itself, so `hidden` alone proves
|
||||
// nothing: `.cockpit-brief-status { display: grid }` used to beat it.
|
||||
const css = readFileSync(
|
||||
fileURLToPath(new URL('./styles/cockpit.css', import.meta.url)),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/\.cockpit-brief-status\[hidden\]\s*\{\s*display:\s*none;?\s*\}/,
|
||||
);
|
||||
const { $, owner } = fixture(t);
|
||||
const style = document.head.appendChild(document.createElement('style'));
|
||||
t.after(() => style.remove());
|
||||
style.textContent = css;
|
||||
showBriefPage.call(owner, 1);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ newsStatus: 'ready', articles: [story('a')] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
const banner = $('#cockpit-news-status');
|
||||
assert.equal(banner.hidden, true);
|
||||
assert.equal(getComputedStyle(banner).display, 'none');
|
||||
renderRegionalBrief.call(owner, { newsStatus: 'empty', articles: [] }, INFO);
|
||||
await nextTick();
|
||||
assert.equal(getComputedStyle(banner).display, 'grid');
|
||||
});
|
||||
|
||||
const hoursAgo = (hours) =>
|
||||
new Date(Date.now() - hours * 3_600_000).toISOString();
|
||||
|
||||
test('ready, cached, empty and unavailable each label the news differently', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
const rows = () =>
|
||||
[...document.querySelectorAll('#cockpit-news-list strong')].map(
|
||||
(row) => row.textContent,
|
||||
);
|
||||
const banner = () => ({
|
||||
hidden: $('#cockpit-news-status').hidden,
|
||||
state: $('#cockpit-news-status').dataset.state,
|
||||
text: text('#cockpit-news-status'),
|
||||
});
|
||||
const ready = {
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: hoursAgo(0.5),
|
||||
articles: [story('a'), story('b')],
|
||||
};
|
||||
renderRegionalBrief.call(owner, ready, INFO);
|
||||
await nextTick();
|
||||
assert.equal(banner().hidden, true);
|
||||
assert.equal(banner().state, 'ready');
|
||||
assert.deepEqual(rows(), ['Story a', 'Story b']);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
|
||||
// The local proxy's stale answer is a refresh that failed.
|
||||
renderRegionalBrief.call(owner, { ...ready, status: 'stale' }, INFO);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'cached',
|
||||
text: 'CACHED · REFRESH FAILED',
|
||||
});
|
||||
assert.deepEqual(rows(), ['Story a', 'Story b']);
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · CACHED 30M AGO',
|
||||
);
|
||||
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
...ready,
|
||||
newsStatus: 'empty',
|
||||
newsSource: 'Google News RSS',
|
||||
articles: [],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'empty',
|
||||
text: 'NO NEWS IN THE LAST 24 H',
|
||||
});
|
||||
assert.deepEqual(rows(), []);
|
||||
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ ...ready, newsStatus: 'unavailable', newsSource: null, articles: [] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(banner(), {
|
||||
hidden: false,
|
||||
state: 'unavailable',
|
||||
text: 'REGIONAL NEWS UNAVAILABLE',
|
||||
});
|
||||
assert.deepEqual(rows(), []);
|
||||
});
|
||||
|
||||
test('articles outside the window are dropped even when a server sends them', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
showBriefPage.call(owner, 1);
|
||||
const dated = (id, publishedAt) => ({ ...story(id), publishedAt });
|
||||
// The reported case: 4, 104, 215 and 165 days old under "RECENT".
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{
|
||||
newsStatus: 'ready',
|
||||
articles: [
|
||||
dated('old', hoursAgo(4 * 24)),
|
||||
dated('older', hoursAgo(104 * 24)),
|
||||
dated('undated', null),
|
||||
dated('one', hoursAgo(20)),
|
||||
dated('two', hoursAgo(2)),
|
||||
],
|
||||
},
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.deepEqual(
|
||||
[...document.querySelectorAll('#cockpit-news-list strong')].map(
|
||||
(row) => row.textContent,
|
||||
),
|
||||
['Story two', 'Story one'],
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').hidden, true);
|
||||
renderRegionalBrief.call(
|
||||
owner,
|
||||
{ newsStatus: 'ready', articles: [dated('old', hoursAgo(25))] },
|
||||
INFO,
|
||||
);
|
||||
await nextTick();
|
||||
assert.equal(document.querySelectorAll('#cockpit-news-list li').length, 0);
|
||||
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
|
||||
});
|
||||
|
||||
test('a failed refresh keeps the earlier articles as cached, and clears only when there are none', async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
const answers = [];
|
||||
Object.assign(owner, {
|
||||
active: true,
|
||||
regionalBriefSubjectId: null,
|
||||
regionalBriefAbort: null,
|
||||
regionalBriefRequestToken: 0,
|
||||
regionalBriefFetchedAt: 0,
|
||||
regionalBrief: null,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
});
|
||||
owner.services = {
|
||||
...owner.services,
|
||||
regionalDistanceM: () => 0,
|
||||
fetchRegionalBrief: () => answers.shift()(),
|
||||
};
|
||||
const refresh = async (answer, info = { ...INFO, icao24: 'abc123' }) => {
|
||||
answers.push(answer);
|
||||
owner.regionalBriefFetchedAt = 0;
|
||||
maybeRefreshRegionalBrief.call(owner, info);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
};
|
||||
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
|
||||
showBriefPage.call(owner, 1);
|
||||
|
||||
// No earlier brief: an error clears and says unavailable.
|
||||
await refresh(() => Promise.reject(new Error('503')));
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
|
||||
assert.equal(rows(), 0);
|
||||
|
||||
const fetchedAt = hoursAgo(1);
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: fetchedAt,
|
||||
articles: [story('a'), story('b')],
|
||||
}),
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').hidden, true);
|
||||
assert.equal(rows(), 2);
|
||||
|
||||
// A network failure keeps the rows and says so, with their age.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')));
|
||||
assert.equal($('#cockpit-news-status').hidden, false);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · CACHED 1H AGO',
|
||||
);
|
||||
showBriefPage.call(owner, 2);
|
||||
showBriefPage.call(owner, 1);
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'GOOGLE NEWS RSS · LOCATION QUERY · RECENT',
|
||||
'GOOGLE NEWS RSS · CACHED 1H AGO',
|
||||
);
|
||||
showBriefPage.call(owner, 0);
|
||||
renderRegionalBrief.call(owner, { newsSource: 'wire', articles: [] }, INFO);
|
||||
await nextTick();
|
||||
assert.equal(
|
||||
text('#cockpit-brief-source'),
|
||||
'SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS',
|
||||
|
||||
// So does a brief whose news read failed while weather answered.
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'partial',
|
||||
newsStatus: 'unavailable',
|
||||
articles: [],
|
||||
}),
|
||||
);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
|
||||
// A successful refresh clears the cached label; a true empty clears rows.
|
||||
await refresh(() =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'empty',
|
||||
newsSource: 'Google News RSS',
|
||||
articles: [],
|
||||
}),
|
||||
);
|
||||
assert.equal(text('#cockpit-news-status'), 'NO NEWS IN THE LAST 24 H');
|
||||
assert.equal(rows(), 0);
|
||||
assert.equal(text('#cockpit-brief-source'), 'GOOGLE NEWS RSS · LAST 24 H');
|
||||
|
||||
// Another aircraft never inherits the last one's rows.
|
||||
await refresh(() =>
|
||||
Promise.resolve({ newsStatus: 'ready', articles: [story('c')] }),
|
||||
);
|
||||
assert.equal(rows(), 1);
|
||||
await refresh(() => Promise.reject(new Error('503')), {
|
||||
...INFO,
|
||||
icao24: 'def456',
|
||||
});
|
||||
assert.equal(text('#cockpit-news-status'), 'REGIONAL NEWS UNAVAILABLE');
|
||||
assert.equal(rows(), 0);
|
||||
});
|
||||
|
||||
test('an unchanged position publishes nothing new', (t) => {
|
||||
@@ -278,7 +546,10 @@ test('the card and its toggle render the collapse the controller presents', asyn
|
||||
await nextTick();
|
||||
assert.equal(card.dataset.collapsed, 'true');
|
||||
assert.equal(toggle.getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(toggle.getAttribute('aria-label'), 'Expand cockpit briefing panel');
|
||||
assert.equal(
|
||||
toggle.getAttribute('aria-label'),
|
||||
'Expand cockpit briefing panel',
|
||||
);
|
||||
assert.equal(toggle.title, 'Expand briefing panel');
|
||||
assert.equal(toggle.textContent.trim(), 'right_panel_open');
|
||||
assert.equal(owner.signalUserCollapsed, true);
|
||||
@@ -287,3 +558,75 @@ test('the card and its toggle render the collapse the controller presents', asyn
|
||||
assert.equal(card.dataset.collapsed, 'false');
|
||||
assert.equal(toggle.textContent.trim(), 'right_panel_close');
|
||||
});
|
||||
|
||||
test("a refresh that fails after a move never shows the last location's brief as current", async (t) => {
|
||||
const { $, text, owner } = fixture(t);
|
||||
const answers = [];
|
||||
Object.assign(owner, {
|
||||
active: true,
|
||||
regionalBriefSubjectId: null,
|
||||
regionalBriefAbort: null,
|
||||
regionalBriefRequestToken: 0,
|
||||
regionalBriefFetchedAt: 0,
|
||||
regionalBrief: null,
|
||||
renderRegionalBrief,
|
||||
renderRegionalBriefStatus,
|
||||
});
|
||||
owner.services = {
|
||||
...owner.services,
|
||||
// One degree of latitude stands for a move past the refresh distance.
|
||||
regionalDistanceM: (from, to) =>
|
||||
from ? Math.abs(from.latitude - to.latitude) * 111_000 : Infinity,
|
||||
fetchRegionalBrief: () => answers.shift()(),
|
||||
};
|
||||
const refresh = async (answer, latitude) => {
|
||||
answers.push(answer);
|
||||
owner.regionalBriefFetchedAt = 0;
|
||||
maybeRefreshRegionalBrief.call(owner, {
|
||||
...INFO,
|
||||
icao24: 'abc123',
|
||||
latitude,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
};
|
||||
const rows = () => document.querySelectorAll('#cockpit-news-list li').length;
|
||||
const here = () =>
|
||||
Promise.resolve({
|
||||
status: 'ready',
|
||||
newsStatus: 'ready',
|
||||
newsSource: 'Google News RSS',
|
||||
newsWindowHours: 24,
|
||||
newsFetchedAt: hoursAgo(1),
|
||||
articles: [story('a'), story('b')],
|
||||
});
|
||||
showBriefPage.call(owner, 1);
|
||||
|
||||
await refresh(here, 40);
|
||||
assert.equal(rows(), 2);
|
||||
// The same place: a failed refresh keeps the rows as cached.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 40);
|
||||
assert.equal(text('#cockpit-news-status'), 'CACHED · REFRESH FAILED');
|
||||
assert.equal(rows(), 2);
|
||||
// Elsewhere: the brief is unavailable, as it was before there was a cache.
|
||||
await refresh(() => Promise.reject(new TypeError('Failed to fetch')), 45);
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(rows(), 0);
|
||||
// Nor is it held, for a language change to show again.
|
||||
assert.equal(owner.regionalBrief, null);
|
||||
|
||||
// Nor does a brief there whose news read failed borrow the last place's rows.
|
||||
await refresh(here, 40);
|
||||
assert.equal(rows(), 2);
|
||||
await refresh(
|
||||
() =>
|
||||
Promise.resolve({
|
||||
status: 'partial',
|
||||
newsStatus: 'unavailable',
|
||||
articles: [],
|
||||
}),
|
||||
45,
|
||||
);
|
||||
assert.equal($('#cockpit-news-status').dataset.state, 'unavailable');
|
||||
assert.equal(rows(), 0);
|
||||
});
|
||||
@@ -147,6 +147,15 @@ export class LayerBindings {
|
||||
fires.attachShellServices({ imageryHost: this.services.imageryHost });
|
||||
this._weatherShellModules.push(fires);
|
||||
}
|
||||
// News flies to a chosen report or hotspot through the same release.
|
||||
const news = this._dataManager?.layers?.get('news')?.module;
|
||||
if (typeof news?.attachShellServices === 'function') {
|
||||
news.attachShellServices({
|
||||
runNavigation: (navigate) =>
|
||||
this.runImmediateNavigation('news', navigate),
|
||||
});
|
||||
this._weatherShellModules.push(news);
|
||||
}
|
||||
}
|
||||
|
||||
_persistAwarenessSelection(event, cleared = false) {
|
||||
|
||||
@@ -38,6 +38,8 @@ export const LAYER_NAME_KEYS = Object.freeze({
|
||||
'drone-airspace': msg('Prohibited & Restricted Airspace'),
|
||||
'wildlife-sightings': msg('Wildlife Sightings'),
|
||||
's2-ghostmaps': msg('S2 GhostMaps'),
|
||||
news: msg('News'),
|
||||
shipwrecks: msg('Shipwrecks'),
|
||||
wind: msg('Wind'),
|
||||
'weather-radar': msg('Rain radar'),
|
||||
'weather-satellite': msg('Satellite clouds'),
|
||||
|
||||
+42
-2
@@ -11,6 +11,7 @@ import {
|
||||
} from './layerNames.js';
|
||||
export { localizeLayerName } from './layerNames.js';
|
||||
import { createWeatherPanel } from './weatherPanel.js';
|
||||
import { createNewsPanel } from './newsPanel.js';
|
||||
import {
|
||||
translateFeedError,
|
||||
translateStatusLine,
|
||||
@@ -81,6 +82,8 @@ const PANEL_GROUPS = [
|
||||
'fire-perimeters',
|
||||
'gnss-integrity',
|
||||
's2-ghostmaps',
|
||||
'shipwrecks',
|
||||
'news',
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -317,6 +320,11 @@ export class LayerPanel {
|
||||
container?.ownerDocument?.getElementById?.('weather-panel-body'),
|
||||
setLayerParams: this.setLayerParams,
|
||||
});
|
||||
this._newsPanel?.destroy();
|
||||
this._newsPanel = createNewsPanel({
|
||||
container: container?.ownerDocument?.getElementById?.('news-panel-body'),
|
||||
setLayerParams: this.setLayerParams,
|
||||
});
|
||||
this._mountRecentImagery();
|
||||
this._renderToggles();
|
||||
}
|
||||
@@ -352,6 +360,8 @@ export class LayerPanel {
|
||||
this._releaseBindings();
|
||||
this._weatherPanel?.destroy();
|
||||
this._weatherPanel = null;
|
||||
this._newsPanel?.destroy();
|
||||
this._newsPanel = null;
|
||||
this._recentImageryPanel?.destroy();
|
||||
this._recentImageryPanel = null;
|
||||
this._recentImageryFactory = null;
|
||||
@@ -416,10 +426,12 @@ export class LayerPanel {
|
||||
onLocaleChange(() => {
|
||||
this._paint();
|
||||
this._refreshWeatherPanel();
|
||||
this._refreshNewsPanel();
|
||||
}),
|
||||
);
|
||||
this._paint();
|
||||
this._refreshWeatherPanel();
|
||||
this._refreshNewsPanel();
|
||||
}
|
||||
|
||||
/** Present every row from the layers' current state and render them. */
|
||||
@@ -451,6 +463,8 @@ export class LayerPanel {
|
||||
this._selectListItem(layerId, itemId, generation),
|
||||
onSlider: (layerId, sliderId, value) =>
|
||||
this._moveSlider(layerId, sliderId, value, generation),
|
||||
onRange: (layerId, rangeId, end, value) =>
|
||||
this._pickRangeEnd(layerId, rangeId, end, value, generation),
|
||||
}),
|
||||
id === null ? this._toggleContainer : this._groupContainers.get(id),
|
||||
);
|
||||
@@ -480,7 +494,7 @@ export class LayerPanel {
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer's row chips, one-of-many switch, slider, color legend, info line
|
||||
* A layer's row chips, one-of-many switch, slider, start/end pickers, color legend, info line
|
||||
* and ordered list. The block
|
||||
* is hidden while the layer is off (or while a dependency owner has
|
||||
* surrendered it), so a quiet row stays quiet. Chips and list items are
|
||||
@@ -507,6 +521,7 @@ export class LayerPanel {
|
||||
const infoText = controls?.info ? String(controls.info) : '';
|
||||
const segmented = controls?.segmented || null;
|
||||
const slider = controls?.slider || null;
|
||||
const range = controls?.range || null;
|
||||
// The info line, once shown, stays in place and hides when empty.
|
||||
if (infoText) row.info = true;
|
||||
return {
|
||||
@@ -515,10 +530,12 @@ export class LayerPanel {
|
||||
legend.length === 0 &&
|
||||
!infoText &&
|
||||
!segmented &&
|
||||
!slider,
|
||||
!slider &&
|
||||
!range,
|
||||
chips,
|
||||
segmented,
|
||||
slider,
|
||||
range,
|
||||
legend,
|
||||
info: row.info
|
||||
? { text: infoText, title: controls?.infoTitle || '' }
|
||||
@@ -583,6 +600,20 @@ export class LayerPanel {
|
||||
this.setLayerParams(id, slider.params(value), { origin: 'user' });
|
||||
}
|
||||
|
||||
_pickRangeEnd(id, rangeId, end, value, generation = this._generation) {
|
||||
if (this._destroyed || this._generation !== generation) return;
|
||||
const range = this._rowControlsFor(id)?.range;
|
||||
if (
|
||||
!range ||
|
||||
range.id !== rangeId ||
|
||||
(end !== 'from' && end !== 'to') ||
|
||||
typeof range.params !== 'function' ||
|
||||
!this.isEnabled(id)
|
||||
)
|
||||
return;
|
||||
this.setLayerParams(id, range.params(end, value), { origin: 'user' });
|
||||
}
|
||||
|
||||
_selectListItem(id, itemId, generation = this._generation) {
|
||||
if (this._destroyed || this._generation !== generation) return;
|
||||
const item = this._rowControlsFor(id)?.list?.items?.find(
|
||||
@@ -648,6 +679,15 @@ export class LayerPanel {
|
||||
}
|
||||
this._paint();
|
||||
this._refreshWeatherPanel();
|
||||
this._refreshNewsPanel();
|
||||
}
|
||||
|
||||
/** Feed the News rail panel the view the news layer publishes while on. */
|
||||
_refreshNewsPanel() {
|
||||
const layer = this.getAll().find(({ id }) => id === 'news');
|
||||
this._newsPanel?.update(
|
||||
layer?.enabled ? this._rowControlsFor(layer.id)?.feed || null : null,
|
||||
);
|
||||
}
|
||||
|
||||
_buildMetaText(layer) {
|
||||
|
||||
@@ -50,7 +50,8 @@ test('Wildlife follows Events and precedes Weather', () => {
|
||||
);
|
||||
const wildlife = order.findIndex(({ id }) => id === 'wildlife-sightings');
|
||||
assert.equal(order[wildlife].label, 'Wildlife');
|
||||
assert.equal(order[wildlife - 1].id, 's2-ghostmaps');
|
||||
// News is the last of Events.
|
||||
assert.equal(order[wildlife - 1].id, 'news');
|
||||
assert.equal(order[wildlife + 1].id, 'air-quality');
|
||||
assert.equal(order.filter(({ id }) => id === 'wildlife-sightings').length, 1);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup>
|
||||
import RailChips from '../rail/RailChips.vue';
|
||||
import RailRowList from '../rail/RailRowList.vue';
|
||||
import RowRange from './RowRange.vue';
|
||||
import RowSlider from './RowSlider.vue';
|
||||
import RowSwitch from './RowSwitch.vue';
|
||||
import RowText from './RowText.vue';
|
||||
@@ -15,6 +16,7 @@ defineProps({
|
||||
onChip: { type: Function, default: () => {} },
|
||||
onListItem: { type: Function, default: () => {} },
|
||||
onSlider: { type: Function, default: () => {} },
|
||||
onRange: { type: Function, default: () => {} },
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -68,6 +70,13 @@ defineProps({
|
||||
:on-input="
|
||||
(value) => onSlider(item.id, item.controls.slider.id, value)
|
||||
"
|
||||
/><RowRange
|
||||
v-if="item.controls.range"
|
||||
:range="item.controls.range"
|
||||
:on-select="
|
||||
(end, value) =>
|
||||
onRange(item.id, item.controls.range.id, end, value)
|
||||
"
|
||||
/><span
|
||||
v-for="(entry, index) in item.controls.legend"
|
||||
:key="index"
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<script setup>
|
||||
// A row's start and end pickers on one line (e.g. the Shipwrecks period).
|
||||
// Both ends share one option list; `onSelect` reports which end moved
|
||||
// ('from' or 'to') and the chosen option value.
|
||||
defineProps({
|
||||
range: { type: Object, required: true },
|
||||
onSelect: { type: Function, default: () => {} },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="data-toggle-range" :data-range-id="range.id"
|
||||
><div class="data-toggle-slider-head"
|
||||
><span class="data-toggle-slider-label">{{ range.label }}</span
|
||||
><span class="data-toggle-slider-value gev-slider-value">{{
|
||||
range.valueText
|
||||
}}</span></div
|
||||
><div class="data-toggle-range-ends"
|
||||
><label
|
||||
v-for="end in ['from', 'to']"
|
||||
:key="end"
|
||||
class="data-toggle-range-end"
|
||||
><span class="data-toggle-range-caption">{{ range[end].label }}</span
|
||||
><select
|
||||
class="data-toggle-range-select"
|
||||
:data-range-end="end"
|
||||
:aria-label="range[end].ariaLabel || undefined"
|
||||
:value="String(range[end].value)"
|
||||
@change="onSelect(end, $event.target.value)"
|
||||
><option
|
||||
v-for="option in range.options"
|
||||
:key="option.value"
|
||||
:value="String(option.value)"
|
||||
>{{ option.label }}</option
|
||||
></select
|
||||
></label
|
||||
></div
|
||||
></div
|
||||
>
|
||||
</template>
|
||||
@@ -159,3 +159,62 @@ test('a row switch and slider render their markup and report choices', () => {
|
||||
assert.equal(segments[1].classList.contains('active'), true);
|
||||
render(null, container);
|
||||
});
|
||||
|
||||
test('a row range renders start and end pickers and reports which end moved', () => {
|
||||
document.body.replaceChildren();
|
||||
const container = document.body.appendChild(document.createElement('div'));
|
||||
const picks = [];
|
||||
const item = {
|
||||
...row(false),
|
||||
key: 'shipwrecks',
|
||||
id: 'shipwrecks',
|
||||
controls: {
|
||||
hidden: false,
|
||||
chips: [],
|
||||
segmented: null,
|
||||
slider: null,
|
||||
range: {
|
||||
id: 'period',
|
||||
label: 'Period',
|
||||
valueText: '2010–2024',
|
||||
from: { label: 'From', ariaLabel: 'First year', value: 2010 },
|
||||
to: { label: 'To', ariaLabel: 'Last year', value: 2024 },
|
||||
options: [2024, 2010, 2007].map((year) => ({
|
||||
value: year,
|
||||
label: String(year),
|
||||
})),
|
||||
},
|
||||
legend: [],
|
||||
info: null,
|
||||
list: null,
|
||||
},
|
||||
};
|
||||
render(
|
||||
h(LayerRows, {
|
||||
items: [item],
|
||||
onRange: (id, rangeId, end, value) =>
|
||||
picks.push([id, rangeId, end, value]),
|
||||
}),
|
||||
container,
|
||||
);
|
||||
const block = container.querySelector('.data-toggle-range');
|
||||
assert.equal(block.dataset.rangeId, 'period');
|
||||
assert.equal(
|
||||
block.querySelector('.data-toggle-slider-value').textContent,
|
||||
'2010–2024',
|
||||
);
|
||||
const [from, to] = block.querySelectorAll('select.data-toggle-range-select');
|
||||
assert.equal(from.getAttribute('aria-label'), 'First year');
|
||||
assert.equal(from.value, '2010');
|
||||
assert.equal(to.value, '2024');
|
||||
assert.deepEqual(
|
||||
[...block.querySelectorAll('.data-toggle-range-caption')].map(
|
||||
(caption) => caption.textContent,
|
||||
),
|
||||
['From', 'To'],
|
||||
);
|
||||
to.value = '2007';
|
||||
to.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
assert.deepEqual(picks, [['shipwrecks', 'period', 'to', '2007']]);
|
||||
render(null, container);
|
||||
});
|
||||
@@ -977,3 +977,20 @@ test('a slow downward pull is claimed before Android native scroll takes ownersh
|
||||
assert.equal(shell.getSheet(), null);
|
||||
shell.destroy();
|
||||
});
|
||||
|
||||
test('on phones the News panel shows in the Context sheet only, like Weather', () => {
|
||||
const css = readFileSync(
|
||||
new URL('./styles/mobile-shell.css', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
// Hidden by id: the rail's own `#news-panel:not(.collapsed)` rule outranks
|
||||
// the generic `#right-context-rail > *` hiding rule.
|
||||
assert.match(
|
||||
css,
|
||||
/body\.mobile-shell #right-context-rail > #news-panel,\n[^{}]*\{\s*display: none;/,
|
||||
);
|
||||
assert.match(
|
||||
css,
|
||||
/body\.mobile-shell\[data-mobile-sheet='context'\]\s+#right-context-rail\s+> #news-panel:not\(\[hidden\]\),/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import UiButton from '../kit/UiButton.vue';
|
||||
|
||||
// One event in the News panel: the publisher's
|
||||
// picture when the event has one, the headline, a mono meta line (severity
|
||||
// marker, category, place, sources, age), who reported it, its attestation
|
||||
// and media chips, and the service it came through ("via …"), which some ask
|
||||
// to be credited wherever their reports show. A click chooses it (the layer
|
||||
// flies there and opens its card on the globe); open, it plays the post's
|
||||
// clip when it has one (on request, with sound and controls), and shows the
|
||||
// summary, the other sides' reports and the link to the original article.
|
||||
// The layer computes every value shown (feedCardView in
|
||||
// src/layers/news/model.js).
|
||||
const props = defineProps({
|
||||
item: { type: Object, required: true },
|
||||
open: { type: Boolean, default: false },
|
||||
onChoose: { type: Function, default: () => {} },
|
||||
onClear: { type: Function, default: () => {} },
|
||||
});
|
||||
|
||||
// A picture the publisher no longer serves leaves the card without one.
|
||||
const pictureFailed = ref(false);
|
||||
const dropPicture = () => {
|
||||
pictureFailed.value = true;
|
||||
};
|
||||
// So does a clip whose signed link has expired.
|
||||
const clipFailed = ref(false);
|
||||
const dropClip = () => {
|
||||
clipFailed.value = true;
|
||||
};
|
||||
watch(
|
||||
() => props.item.picture?.url,
|
||||
() => {
|
||||
pictureFailed.value = false;
|
||||
clipFailed.value = false;
|
||||
},
|
||||
);
|
||||
const meta = () =>
|
||||
[
|
||||
props.item.category,
|
||||
props.item.place &&
|
||||
(props.item.placedByModel
|
||||
? t('{place} (placed by model)', { place: props.item.place })
|
||||
: props.item.place),
|
||||
props.item.sources,
|
||||
props.item.age,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="news-card"
|
||||
:class="{ 'is-open': open, 'is-unmapped': !item.mappable }"
|
||||
:data-report-id="item.id"
|
||||
:style="{ '--news-color': item.color }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="news-card__main ui-focus"
|
||||
:aria-expanded="open ? 'true' : 'false'"
|
||||
@click="onChoose(item)"
|
||||
>
|
||||
<span v-if="item.picture && !pictureFailed" class="news-card__thumb"
|
||||
><img
|
||||
:src="item.picture.url"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
referrerpolicy="no-referrer"
|
||||
v-on="{ error: dropPicture }"
|
||||
/><span
|
||||
v-if="item.picture.video && !clipFailed"
|
||||
class="news-card__play"
|
||||
role="img"
|
||||
:aria-label="t('Video')"
|
||||
>▶</span
|
||||
><span v-if="item.picture.credit" class="news-card__credit">{{
|
||||
item.picture.credit
|
||||
}}</span></span
|
||||
>
|
||||
<span class="news-card__title">{{ item.title }}</span>
|
||||
<span v-if="item.original" class="news-card__note">{{
|
||||
t('English headline by the model')
|
||||
}}</span>
|
||||
<span class="news-card__meta ui-mono"
|
||||
><span
|
||||
class="news-card__marker"
|
||||
:class="{ solid: item.solid }"
|
||||
role="img"
|
||||
:aria-label="item.severityLabel"
|
||||
:title="item.severityLabel"
|
||||
><svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path :d="item.icon" /></svg></span
|
||||
><span v-if="item.severity >= 2" class="news-card__severity">{{
|
||||
item.severityLabel
|
||||
}}</span
|
||||
>{{ item.severity >= 2 ? ` · ${meta()}` : meta() }}</span
|
||||
>
|
||||
<span v-if="item.sides" class="news-card__sides">{{ item.sides }}</span>
|
||||
<span v-if="item.chips.length" class="news-card__chips"
|
||||
><span
|
||||
v-for="chip in item.chips"
|
||||
:key="`${chip.kind}:${chip.label}`"
|
||||
class="news-chip"
|
||||
:class="`news-chip--${chip.kind}`"
|
||||
>{{ chip.label }}</span
|
||||
></span
|
||||
>
|
||||
<span v-if="item.via" class="news-card__via ui-mono">{{ item.via }}</span>
|
||||
</button>
|
||||
<div v-if="open" class="news-card__open">
|
||||
<video
|
||||
v-if="item.picture?.video && !clipFailed"
|
||||
class="news-card__clip"
|
||||
:src="item.picture.video"
|
||||
:poster="pictureFailed ? undefined : item.picture.url"
|
||||
controls
|
||||
playsinline
|
||||
preload="none"
|
||||
referrerpolicy="no-referrer"
|
||||
v-on="{ error: dropClip }"
|
||||
></video>
|
||||
<p v-if="item.original" class="news-card__original">{{
|
||||
item.original
|
||||
}}</p>
|
||||
<p v-if="item.snippet" class="news-card__snippet">{{ item.snippet }}</p>
|
||||
<p v-if="!item.mappable" class="news-card__note">
|
||||
{{ t('Not placed on the map') }}
|
||||
</p>
|
||||
<ul v-if="item.others.length" class="news-card__others">
|
||||
<li v-for="other in item.others" :key="other.url">
|
||||
<span class="news-card__side ui-mono">{{ other.side }}</span
|
||||
><a :href="other.url" target="_blank" rel="noopener noreferrer"
|
||||
>{{ other.publisher }}: {{ other.title }}</a
|
||||
>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="news-card__actions">
|
||||
<a
|
||||
class="news-card__link"
|
||||
:href="item.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ item.sourceLink }}</a
|
||||
>
|
||||
<UiButton
|
||||
class="data-toggle-chip news-card__clear"
|
||||
type="button"
|
||||
@click="onClear()"
|
||||
>{{ t('Close') }}</UiButton
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,294 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import UiButton from '../kit/UiButton.vue';
|
||||
import UiEmpty from '../kit/UiEmpty.vue';
|
||||
import UiSelect from '../kit/UiSelect.js';
|
||||
import RailChips from '../rail/RailChips.vue';
|
||||
import NewsCard from './NewsCard.vue';
|
||||
|
||||
// The News panel: the window the server serves only (the last 24 hours, or
|
||||
// fewer where the host serves less), or a shorter one chosen at the
|
||||
// top (24/12/6/3/1 h), and two sections. Conflicts: hotspot chips, the
|
||||
// severity floor, the chosen event and a continuous feed, newest first.
|
||||
// Local: every report in the area at the view centre (its country, a large
|
||||
// country's state; within a radius at sea) while the camera is low, named at
|
||||
// the top, which the map then shows, outlined, instead of the hotspots' news.
|
||||
// A section read from a key the server lacks (or whose allowance for the day
|
||||
// is spent) says which key instead. It
|
||||
// renders the `feed` view the news layer publishes and acts only through
|
||||
// `onParams`.
|
||||
const props = defineProps({
|
||||
view: { type: Object, default: null },
|
||||
onParams: { type: Function, default: () => {} },
|
||||
});
|
||||
|
||||
const filters = computed(() => props.view?.filters ?? {});
|
||||
const local = computed(() => filters.value.section === 'local');
|
||||
const sections = computed(() =>
|
||||
[
|
||||
{ id: 'conflicts', label: t('Conflicts') },
|
||||
{ id: 'local', label: t('Local') },
|
||||
].map((chip) => ({
|
||||
...chip,
|
||||
active: (filters.value.section ?? 'conflicts') === chip.id,
|
||||
})),
|
||||
);
|
||||
const chips = computed(() =>
|
||||
(props.view?.hotspots ?? []).map((chip) => ({
|
||||
id: chip.id,
|
||||
label: `${chip.label} ${chip.count}`,
|
||||
active: chip.active,
|
||||
title: chip.label,
|
||||
})),
|
||||
);
|
||||
const severityOptions = computed(() => {
|
||||
const levels = props.view?.severities ?? [];
|
||||
return [
|
||||
{ value: '0', label: t('Any severity') },
|
||||
...levels.slice(1, 3).map((level) => ({
|
||||
value: String(level.value),
|
||||
label: t('{severity} and above', { severity: level.label }),
|
||||
})),
|
||||
...levels.slice(3).map((level) => ({
|
||||
value: String(level.value),
|
||||
label: t('{severity} only', { severity: level.label }),
|
||||
})),
|
||||
];
|
||||
});
|
||||
const categoryOptions = computed(() => [
|
||||
{ value: 'all', label: t('All categories') },
|
||||
...(props.view?.categories ?? []),
|
||||
]);
|
||||
const windowOptions = computed(() =>
|
||||
(props.view?.windowChoices ?? []).map((hours) => ({
|
||||
value: String(hours),
|
||||
label: t('Last {hours} h', { hours }),
|
||||
})),
|
||||
);
|
||||
// The longest choice is the server's whole window, kept as no choice.
|
||||
const chooseWindow = (hours) =>
|
||||
setFilter('hours', hours === props.view?.windowChoices?.[0] ? null : hours);
|
||||
const selectedId = computed(() => props.view?.selected?.id ?? null);
|
||||
// The chosen event leads the panel unless the feed already shows it open.
|
||||
const selectedApart = computed(() => {
|
||||
const chosen = props.view?.selected;
|
||||
if (!chosen) return null;
|
||||
const listed = local.value
|
||||
? props.view.inView.items.some((item) => item.id === chosen.id)
|
||||
: props.view.items.some((item) => item.id === chosen.id);
|
||||
return listed ? null : chosen;
|
||||
});
|
||||
// What Local reads: the area named, else the radius; neither while the
|
||||
// first area is being named, so the radius does not flash before it.
|
||||
const areaHead = computed(() => {
|
||||
const inView = props.view?.inView;
|
||||
if (!inView?.active) return '';
|
||||
if (inView.area) return t('News from {area}', { area: inView.area });
|
||||
if (inView.areaLoading) return '';
|
||||
return t('Within {km} km of the view centre', { km: inView.radiusKm });
|
||||
});
|
||||
const status = computed(() => {
|
||||
const view = props.view;
|
||||
if (!view) return '';
|
||||
if (view.error) return view.error;
|
||||
if (view.loading && !view.items.length) return t('Reading the news…');
|
||||
return '';
|
||||
});
|
||||
|
||||
const setFilter = (name, value) =>
|
||||
props.onParams({ filters: { [name]: value } });
|
||||
function choose(item) {
|
||||
if (item.id === selectedId.value) props.onParams({ clear: true });
|
||||
else props.onParams({ reportId: item.id, focus: true });
|
||||
}
|
||||
const clear = () => props.onParams({ clear: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="view"
|
||||
class="news-readout"
|
||||
:aria-label="t('News, last {hours} hours', { hours: view.windowHours })"
|
||||
>
|
||||
<UiSelect
|
||||
v-if="windowOptions.length > 1"
|
||||
class="gev-field news-filter news-readout__window-choice"
|
||||
:aria-label="t('Time window')"
|
||||
:model-value="String(view.windowHours)"
|
||||
:options="windowOptions"
|
||||
@update:model-value="chooseWindow(Number($event))"
|
||||
/>
|
||||
<p v-else class="news-readout__window ui-mono">{{
|
||||
t('Last {hours} h', { hours: view.windowHours })
|
||||
}}</p>
|
||||
<div
|
||||
class="news-readout__sections"
|
||||
role="group"
|
||||
:aria-label="t('News sections')"
|
||||
>
|
||||
<RailChips
|
||||
:chips="sections"
|
||||
:on-select="(chip) => setFilter('section', chip.id)"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="!local"
|
||||
class="news-readout__chips"
|
||||
role="group"
|
||||
:aria-label="t('Hotspots')"
|
||||
>
|
||||
<RailChips
|
||||
:chips="chips"
|
||||
:on-select="(chip) => setFilter('hotspot', chip.id)"
|
||||
/>
|
||||
</div>
|
||||
<div class="news-readout__filters">
|
||||
<UiSelect
|
||||
v-if="!local"
|
||||
class="gev-field news-filter"
|
||||
:aria-label="t('Severity')"
|
||||
:model-value="String(filters.minSeverity ?? 2)"
|
||||
:options="severityOptions"
|
||||
@update:model-value="setFilter('minSeverity', Number($event))"
|
||||
/>
|
||||
<UiSelect
|
||||
class="gev-field news-filter"
|
||||
:aria-label="t('Category')"
|
||||
:model-value="filters.category ?? 'all'"
|
||||
:options="categoryOptions"
|
||||
@update:model-value="setFilter('category', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<NewsCard
|
||||
v-if="selectedApart"
|
||||
class="news-readout__selected"
|
||||
:item="selectedApart"
|
||||
open
|
||||
:on-choose="choose"
|
||||
:on-clear="clear"
|
||||
/>
|
||||
|
||||
<section
|
||||
v-if="local"
|
||||
class="news-readout__section"
|
||||
:aria-label="t('Local')"
|
||||
>
|
||||
<p v-if="areaHead" class="news-readout__head news-readout__area ui-mono">
|
||||
{{ areaHead }}
|
||||
</p>
|
||||
<UiEmpty
|
||||
v-if="!view.inView.active"
|
||||
class="news-readout__empty"
|
||||
:title="t('Zoom in to see local news')"
|
||||
/>
|
||||
<UiEmpty
|
||||
v-else-if="view.inView.key"
|
||||
class="news-readout__empty"
|
||||
:title="view.inView.key.title"
|
||||
:hint="view.inView.key.hint"
|
||||
/>
|
||||
<p v-else-if="view.inView.error" class="news-readout__status">
|
||||
{{ view.inView.error }}
|
||||
</p>
|
||||
<UiEmpty
|
||||
v-else-if="!view.inView.items.length && !view.inView.loading"
|
||||
class="news-readout__empty"
|
||||
:title="
|
||||
t('Nothing reported near here in the last {hours} h', {
|
||||
hours: view.windowHours,
|
||||
})
|
||||
"
|
||||
/>
|
||||
<ol
|
||||
v-else
|
||||
class="news-readout__list"
|
||||
:class="{ 'is-stale': view.inView.loading }"
|
||||
:aria-busy="view.inView.loading ? 'true' : 'false'"
|
||||
>
|
||||
<li v-for="item in view.inView.items" :key="item.id">
|
||||
<NewsCard
|
||||
:item="item"
|
||||
:open="item.id === selectedId"
|
||||
:on-choose="choose"
|
||||
:on-clear="clear"
|
||||
/>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else
|
||||
class="news-readout__section"
|
||||
:aria-label="t('Latest news')"
|
||||
>
|
||||
<h3 class="news-readout__head ui-mono">{{ t('Latest') }}</h3>
|
||||
<UiEmpty
|
||||
v-if="view.key"
|
||||
class="news-readout__empty"
|
||||
:title="view.key.title"
|
||||
:hint="view.key.hint"
|
||||
/>
|
||||
<ol
|
||||
v-else-if="view.items.length"
|
||||
class="news-readout__list news-readout__feed"
|
||||
>
|
||||
<li v-for="item in view.items" :key="item.id">
|
||||
<NewsCard
|
||||
:item="item"
|
||||
:open="item.id === selectedId"
|
||||
:on-choose="choose"
|
||||
:on-clear="clear"
|
||||
/>
|
||||
</li>
|
||||
</ol>
|
||||
<UiEmpty
|
||||
v-else-if="!view.loading && !view.error"
|
||||
class="news-readout__empty"
|
||||
:title="
|
||||
t('No news matches these filters in the last {hours} h', {
|
||||
hours: view.windowHours,
|
||||
})
|
||||
"
|
||||
/>
|
||||
<div class="news-readout__footer">
|
||||
<span class="news-readout__status" role="status">{{ status }}</span>
|
||||
<UiButton
|
||||
v-if="view.hasMore && !view.loading"
|
||||
class="data-toggle-chip"
|
||||
type="button"
|
||||
@click="onParams({ loadMore: true })"
|
||||
>{{ t('Load older news') }}</UiButton
|
||||
>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<details class="news-legend">
|
||||
<summary>{{ t('How to read the map') }}</summary>
|
||||
<p>{{ t('Colour: severity · icon: type of event') }}</p>
|
||||
<ul class="news-legend__severity">
|
||||
<li
|
||||
v-for="level in view.severities"
|
||||
:key="level.value"
|
||||
:style="{ '--news-color': level.color }"
|
||||
>
|
||||
{{ level.label }}
|
||||
</li>
|
||||
</ul>
|
||||
<p>{{
|
||||
t(
|
||||
'Solid rim: reported by both sides or independently. Dashed rim: a claim. Thin rim: one source, or one side’s own press.',
|
||||
)
|
||||
}}</p>
|
||||
<p>{{
|
||||
t(
|
||||
'Larger: more sources · fainter: older. Picture card: a major or fast-growing event with two or more sources.',
|
||||
)
|
||||
}}</p>
|
||||
<p>{{
|
||||
t('Side labels describe the source, not whether a report is true.')
|
||||
}}</p>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,89 @@
|
||||
import { h, render as renderVue } from 'vue';
|
||||
import NewsFeed from './news/NewsFeed.vue';
|
||||
|
||||
const LAYER_ID = 'news';
|
||||
const LOAD_MORE_MARGIN_PX = 160;
|
||||
// Remounting must not reopen a panel the reader already collapsed.
|
||||
const appearedPanels = new WeakSet();
|
||||
const set = (node, key, value) => {
|
||||
if (node[key] !== value) node[key] = value;
|
||||
};
|
||||
|
||||
/**
|
||||
* The News rail panel (`#news-panel`): it renders the `feed` view the news
|
||||
* layer publishes through its row controls, shows itself only while the
|
||||
* layer is on, and acts only through setLayerParams. Near the bottom of its
|
||||
* scroller it asks for the next older page, once per page; other filters or a
|
||||
* failed read let it ask again.
|
||||
*/
|
||||
export function createNewsPanel({ container, setLayerParams = () => {} } = {}) {
|
||||
const document = container?.ownerDocument;
|
||||
if (!document?.createElement) return null;
|
||||
const panel = container.closest?.('#news-panel');
|
||||
const count = panel?.querySelector('#news-panel-count');
|
||||
const onParams = (params) =>
|
||||
setLayerParams(LAYER_ID, params, { origin: 'user' });
|
||||
let view = null;
|
||||
let destroyed = false;
|
||||
let requestedAt = -1;
|
||||
let shownFilters = '';
|
||||
|
||||
function render() {
|
||||
if (destroyed) return;
|
||||
renderVue(h(NewsFeed, { view, onParams }), container);
|
||||
const hidden = !view;
|
||||
if (panel) set(panel, 'hidden', hidden);
|
||||
// The count is the shown section's: Local's list, else the feed.
|
||||
const shown =
|
||||
view?.filters?.section === 'local' ? view.inView?.items : view?.items;
|
||||
if (count) set(count, 'textContent', String(shown?.length ?? 0));
|
||||
if (!hidden && panel && !appearedPanels.has(panel)) {
|
||||
appearedPanels.add(panel);
|
||||
// First appearance opens the panel unless a stored or shared collapse
|
||||
// choice exists (marked by the panel chrome when it restored the state).
|
||||
const preference = panel.dataset?.collapsedPreference;
|
||||
if (
|
||||
panel.classList?.contains('collapsed') &&
|
||||
(preference === undefined || preference === 'default')
|
||||
)
|
||||
panel.querySelector('[data-collapse-target="news-panel"]')?.click();
|
||||
}
|
||||
}
|
||||
|
||||
const onScroll = () => {
|
||||
if (!view?.hasMore || view.loading) return;
|
||||
const remaining =
|
||||
container.scrollHeight - container.scrollTop - container.clientHeight;
|
||||
if (remaining > LOAD_MORE_MARGIN_PX) return;
|
||||
if (requestedAt === view.items.length) return;
|
||||
requestedAt = view.items.length;
|
||||
onParams({ loadMore: true });
|
||||
};
|
||||
container.addEventListener?.('scroll', onScroll, { passive: true });
|
||||
|
||||
return {
|
||||
/** Show the layer's feed view, or hide the panel with null. */
|
||||
update(next) {
|
||||
const filters = JSON.stringify(next?.filters ?? null);
|
||||
// A new list (other filters or hotspot), or a read that failed, may stop
|
||||
// at the same length as the last request: let the next scroll ask.
|
||||
// A list started over is shorter than the one the last request saw.
|
||||
if (
|
||||
filters !== shownFilters ||
|
||||
(next?.error && !view?.error) ||
|
||||
(next?.items?.length ?? 0) < requestedAt
|
||||
)
|
||||
requestedAt = -1;
|
||||
shownFilters = filters;
|
||||
view = next || null;
|
||||
render();
|
||||
},
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
container.removeEventListener?.('scroll', onScroll);
|
||||
renderVue(null, container);
|
||||
if (panel) set(panel, 'hidden', true);
|
||||
if (count) set(count, 'textContent', '0');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createNewsPanel } from './newsPanel.js';
|
||||
import {
|
||||
NEWS_CATEGORIES,
|
||||
NEWS_SEVERITY,
|
||||
categoryLabel,
|
||||
feedCardView,
|
||||
normalizeFilters,
|
||||
} from '../layers/news/model.js';
|
||||
|
||||
const NOW = Date.parse('2026-10-28T10:00:00Z');
|
||||
const report = (id, extra = {}) => ({
|
||||
id,
|
||||
title: `Report ${id}`,
|
||||
url: `https://www.example.com/${id}`,
|
||||
publishedAt: '2026-10-28T09:00:00.000Z',
|
||||
publisher: 'Example',
|
||||
side: 'UA',
|
||||
category: 'strike',
|
||||
severity: 2,
|
||||
geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true },
|
||||
pins: [{ lat: 50, lon: 36, place: 'Kharkiv', mappable: true }],
|
||||
event: null,
|
||||
media: [],
|
||||
...extra,
|
||||
});
|
||||
const big = report('big', {
|
||||
severity: 3,
|
||||
titleEn: 'Strike on Kharkiv',
|
||||
title: 'Удар по Харкову',
|
||||
media: ['video'],
|
||||
event: {
|
||||
size: 4,
|
||||
severity: 3,
|
||||
status: 'both-sides',
|
||||
lastAt: '2026-10-28T09:50:00.000Z',
|
||||
sides: [
|
||||
{
|
||||
side: 'UA',
|
||||
title: 'a',
|
||||
url: 'https://a.test/',
|
||||
publisher: 'A',
|
||||
publishedAt: '2026-10-28T09:00:00.000Z',
|
||||
},
|
||||
{
|
||||
side: 'RU',
|
||||
title: 'b',
|
||||
url: 'https://b.test/',
|
||||
publisher: 'B',
|
||||
publishedAt: '2026-10-28T09:40:00.000Z',
|
||||
},
|
||||
],
|
||||
image: { url: 'https://a.test/p.jpg', publisher: 'A' },
|
||||
},
|
||||
});
|
||||
|
||||
function view(extra = {}) {
|
||||
return {
|
||||
filters: normalizeFilters(),
|
||||
hotspots: [
|
||||
{ id: 'all', label: 'All', count: 7, active: true },
|
||||
{ id: 'ua-ru-war', label: 'Ukraine–Russia', count: 7, active: false },
|
||||
],
|
||||
categories: Object.keys(NEWS_CATEGORIES).map((id) => ({
|
||||
value: id,
|
||||
label: categoryLabel(id),
|
||||
})),
|
||||
severities: NEWS_SEVERITY.map((level, index) => ({
|
||||
value: index,
|
||||
label: level.label,
|
||||
color: level.color,
|
||||
})),
|
||||
items: [feedCardView(big, NOW), feedCardView(report('lone'), NOW)],
|
||||
inView: { active: false, loading: false, error: null, items: [] },
|
||||
selected: null,
|
||||
hasMore: true,
|
||||
windowHours: 24,
|
||||
loading: false,
|
||||
error: null,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
document.body.innerHTML = `
|
||||
<div id="news-panel" class="collapsed" hidden>
|
||||
<span id="news-panel-count">0</span>
|
||||
<button data-collapse-target="news-panel"></button>
|
||||
<div id="news-panel-body"></div>
|
||||
</div>`;
|
||||
const panel = document.getElementById('news-panel');
|
||||
let opened = 0;
|
||||
panel
|
||||
.querySelector('[data-collapse-target]')
|
||||
.addEventListener('click', () => {
|
||||
opened++;
|
||||
panel.classList.remove('collapsed');
|
||||
});
|
||||
const calls = [];
|
||||
const news = createNewsPanel({
|
||||
container: document.getElementById('news-panel-body'),
|
||||
setLayerParams: (id, params, options) => calls.push([id, params, options]),
|
||||
});
|
||||
return { news, panel, calls, opened: () => opened };
|
||||
}
|
||||
|
||||
test('the panel shows the last 24 h as event cards and opens once', () => {
|
||||
const { news, panel, opened } = fixture();
|
||||
news.update(null);
|
||||
assert.equal(panel.hidden, true);
|
||||
news.update(view());
|
||||
assert.equal(panel.hidden, false);
|
||||
assert.equal(opened(), 1);
|
||||
assert.equal(document.getElementById('news-panel-count').textContent, '2');
|
||||
assert.equal(
|
||||
panel.querySelector('.news-readout__window').textContent,
|
||||
'Last 24 h',
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...panel.querySelectorAll('.news-readout__chips [data-chip-id]')].map(
|
||||
(chip) => chip.textContent,
|
||||
),
|
||||
['All 7', 'Ukraine–Russia 7'],
|
||||
);
|
||||
const [first, second] = panel.querySelectorAll(
|
||||
'.news-readout__feed .news-card',
|
||||
);
|
||||
assert.equal(
|
||||
first.querySelector('.news-card__title').textContent,
|
||||
'Strike on Kharkiv',
|
||||
);
|
||||
assert.equal(
|
||||
first.querySelector('.news-card__note').textContent,
|
||||
'English headline by the model',
|
||||
);
|
||||
assert.equal(
|
||||
first.querySelector('.news-card__meta').textContent,
|
||||
'Major · Strike · Kharkiv · 4 sources · 10 min',
|
||||
);
|
||||
assert.equal(
|
||||
first.querySelector('.news-card__marker').getAttribute('aria-label'),
|
||||
'Major',
|
||||
);
|
||||
assert.equal(
|
||||
first.querySelector('.news-card__sides').textContent,
|
||||
'Reported by UA sources · RU sources',
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...first.querySelectorAll('.news-chip')].map((c) => c.textContent),
|
||||
['Reported by both sides', 'Video'],
|
||||
);
|
||||
const img = first.querySelector('.news-card__thumb img');
|
||||
assert.equal(img.getAttribute('src'), 'https://a.test/p.jpg');
|
||||
assert.equal(img.getAttribute('referrerpolicy'), 'no-referrer');
|
||||
assert.equal(first.querySelector('.news-card__credit').textContent, 'A');
|
||||
// A lone report has no picture.
|
||||
assert.equal(second.querySelector('.news-card__thumb'), null);
|
||||
// A later update does not reopen a panel the reader collapsed.
|
||||
panel.classList.add('collapsed');
|
||||
news.update(view());
|
||||
assert.equal(opened(), 1);
|
||||
news.destroy();
|
||||
assert.equal(panel.hidden, true);
|
||||
});
|
||||
|
||||
test('a card click flies there; open, it links the source and closes', () => {
|
||||
const { news, panel, calls } = fixture();
|
||||
news.update(view());
|
||||
panel.querySelector('.news-card__main').click();
|
||||
assert.deepEqual(calls.at(-1), [
|
||||
'news',
|
||||
{ reportId: 'big', focus: true },
|
||||
{ origin: 'user' },
|
||||
]);
|
||||
news.update(view({ selected: feedCardView(big, NOW) }));
|
||||
const open = panel.querySelector('.news-card.is-open');
|
||||
const link = open.querySelector('.news-card__link');
|
||||
assert.equal(link.textContent, 'Source: example.com ↗');
|
||||
assert.equal(link.getAttribute('href'), 'https://www.example.com/big');
|
||||
assert.equal(link.getAttribute('rel'), 'noopener noreferrer');
|
||||
assert.equal(
|
||||
open.querySelector('.news-card__original').textContent,
|
||||
'Удар по Харкову',
|
||||
);
|
||||
open.querySelector('.news-card__main').click();
|
||||
assert.deepEqual(calls.at(-1)[1], { clear: true });
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('filters, the Local section and empty or failed reads', () => {
|
||||
const { news, panel, calls } = fixture();
|
||||
news.update(view());
|
||||
assert.equal(panel.querySelector('[aria-label="Local"]'), null);
|
||||
assert.equal(panel.querySelector('.news-toggle'), null);
|
||||
const severity = panel.querySelector('select[aria-label="Severity"]');
|
||||
assert.equal(severity.value, '2');
|
||||
severity.value = '3';
|
||||
severity.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(calls.at(-1)[1], { filters: { minSeverity: 3 } });
|
||||
panel.querySelector('[data-chip-id="ua-ru-war"]').click();
|
||||
assert.deepEqual(calls.at(-1)[1], { filters: { hotspot: 'ua-ru-war' } });
|
||||
panel.querySelector('[data-chip-id="local"]').click();
|
||||
assert.deepEqual(calls.at(-1)[1], { filters: { section: 'local' } });
|
||||
|
||||
news.update(
|
||||
view({
|
||||
items: [],
|
||||
hasMore: false,
|
||||
}),
|
||||
);
|
||||
assert.match(
|
||||
panel.textContent,
|
||||
/No news matches these filters in the last 24 h/,
|
||||
);
|
||||
assert.equal(panel.querySelector('.news-readout__footer button'), null);
|
||||
|
||||
// Local: no hotspot chips or severity floor, and its own empty states.
|
||||
const localView = (inView) =>
|
||||
view({
|
||||
filters: normalizeFilters({ section: 'local' }),
|
||||
inView: { loading: false, error: null, items: [], ...inView },
|
||||
});
|
||||
news.update(localView({ active: false }));
|
||||
const section = panel.querySelector('[aria-label="Local"]');
|
||||
assert.match(section.textContent, /Zoom in to see local news/);
|
||||
assert.equal(panel.querySelector('[data-chip-id="ua-ru-war"]'), null);
|
||||
assert.equal(panel.querySelector('select[aria-label="Severity"]'), null);
|
||||
assert.equal(panel.querySelector('[aria-label="Latest news"]'), null);
|
||||
assert.equal(document.getElementById('news-panel-count').textContent, '0');
|
||||
news.update(
|
||||
localView({ active: true, items: [feedCardView(report('near'), NOW)] }),
|
||||
);
|
||||
assert.equal(document.getElementById('news-panel-count').textContent, '1');
|
||||
news.update(localView({ active: true }));
|
||||
assert.match(
|
||||
panel.querySelector('[aria-label="Local"]').textContent,
|
||||
/Nothing reported near here in the last 24 h/,
|
||||
);
|
||||
news.update(view());
|
||||
|
||||
news.update(
|
||||
view({ items: [], error: 'News feed unavailable', hasMore: false }),
|
||||
);
|
||||
assert.equal(
|
||||
panel.querySelector('.news-readout__status').textContent,
|
||||
'News feed unavailable',
|
||||
);
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('each section says which key it lacks; Local names the area it reads', () => {
|
||||
const { news, panel } = fixture();
|
||||
const key = {
|
||||
title: 'Liveuamap key required',
|
||||
hint: 'Needs LIVEUAMAP_API_KEY — add it in Provider Settings',
|
||||
};
|
||||
news.update(view({ key, items: [], hasMore: false }));
|
||||
const latest = panel.querySelector('[aria-label="Latest news"]');
|
||||
assert.match(latest.textContent, /Liveuamap key required/);
|
||||
assert.match(latest.textContent, /Needs LIVEUAMAP_API_KEY/);
|
||||
assert.doesNotMatch(latest.textContent, /No news matches/);
|
||||
|
||||
const localView = (inView) =>
|
||||
view({
|
||||
filters: normalizeFilters({ section: 'local' }),
|
||||
inView: {
|
||||
active: true,
|
||||
loading: false,
|
||||
error: null,
|
||||
items: [],
|
||||
radiusKm: 500,
|
||||
...inView,
|
||||
},
|
||||
});
|
||||
const section = () => panel.querySelector('[aria-label="Local"]');
|
||||
const heading = () => section().querySelector('.news-readout__area');
|
||||
news.update(
|
||||
localView({
|
||||
key: {
|
||||
title: 'World News API limit reached for today',
|
||||
hint: 'News resumes tomorrow, or with a paid plan',
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.match(section().textContent, /World News API limit reached for today/);
|
||||
assert.match(section().textContent, /News resumes tomorrow/);
|
||||
assert.doesNotMatch(section().textContent, /Nothing reported near here/);
|
||||
|
||||
// The area named, else the radius at sea.
|
||||
news.update(localView({ area: 'Ukraine' }));
|
||||
assert.equal(heading().textContent.trim(), 'News from Ukraine');
|
||||
news.update(localView({ area: null }));
|
||||
assert.equal(
|
||||
heading().textContent.trim(),
|
||||
'Within 500 km of the view centre',
|
||||
);
|
||||
// While the first area is named, neither: the radius does not flash.
|
||||
news.update(localView({ area: null, areaLoading: true, loading: true }));
|
||||
assert.equal(heading(), null);
|
||||
// A new area on the way keeps the one shown.
|
||||
news.update(localView({ area: 'Ukraine', areaLoading: true, loading: true }));
|
||||
assert.equal(heading().textContent.trim(), 'News from Ukraine');
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('a card credits the service its report came through', () => {
|
||||
const { news, panel } = fixture();
|
||||
news.update(
|
||||
view({
|
||||
items: [
|
||||
feedCardView(report('gdelt', { attribution: 'GDELT Project' }), NOW),
|
||||
feedCardView(report('own'), NOW),
|
||||
],
|
||||
}),
|
||||
);
|
||||
const [credited, own] = panel.querySelectorAll('.news-card');
|
||||
assert.equal(
|
||||
credited.querySelector('.news-card__via').textContent,
|
||||
'via GDELT Project',
|
||||
);
|
||||
assert.equal(own.querySelector('.news-card__via'), null);
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('scrolling to the end asks once per page, again after a filter change or a failed read', () => {
|
||||
const { news, calls } = fixture();
|
||||
const body = document.getElementById('news-panel-body');
|
||||
// A scroller at its bottom.
|
||||
Object.defineProperty(body, 'scrollHeight', {
|
||||
value: 1000,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(body, 'clientHeight', {
|
||||
value: 400,
|
||||
configurable: true,
|
||||
});
|
||||
body.scrollTop = 600;
|
||||
const loadMores = () => calls.filter(([, p]) => p.loadMore === true).length;
|
||||
const scroll = () => body.dispatchEvent(new Event('scroll'));
|
||||
news.update(view());
|
||||
scroll();
|
||||
scroll();
|
||||
assert.equal(loadMores(), 1);
|
||||
// The page came back with nothing new (as many items): no second request.
|
||||
news.update(view());
|
||||
scroll();
|
||||
assert.equal(loadMores(), 1);
|
||||
// Another hotspot, the same number of rows: the new list can be read on.
|
||||
const hotspot = normalizeFilters({ hotspot: 'ua-ru-war' }, [
|
||||
{ id: 'ua-ru-war' },
|
||||
]);
|
||||
news.update(view({ filters: hotspot }));
|
||||
scroll();
|
||||
assert.equal(loadMores(), 2);
|
||||
// The read fails: the next scroll tries again.
|
||||
news.update(view({ filters: hotspot, error: 'News feed unavailable' }));
|
||||
scroll();
|
||||
assert.equal(loadMores(), 3);
|
||||
// While loading, or with no older page, nothing is asked.
|
||||
news.update(view({ filters: hotspot, loading: true }));
|
||||
scroll();
|
||||
news.update(view({ filters: hotspot, hasMore: false }));
|
||||
scroll();
|
||||
assert.equal(loadMores(), 3);
|
||||
news.destroy();
|
||||
});
|
||||
|
||||
test('the window choice offers shorter windows; the longest is the server window', () => {
|
||||
const { news, panel, calls } = fixture();
|
||||
news.update(view({ windowHours: 12, windowChoices: [12, 6, 3, 1] }));
|
||||
assert.equal(panel.querySelector('.news-readout__window'), null);
|
||||
const choice = panel.querySelector('select[aria-label="Time window"]');
|
||||
assert.deepEqual(
|
||||
[...choice.options].map((option) => option.textContent),
|
||||
['Last 12 h', 'Last 6 h', 'Last 3 h', 'Last 1 h'],
|
||||
);
|
||||
assert.equal(choice.value, '12');
|
||||
choice.value = '3';
|
||||
choice.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(calls.at(-1)[1], { filters: { hours: 3 } });
|
||||
choice.value = '12';
|
||||
choice.dispatchEvent(new Event('change'));
|
||||
assert.deepEqual(calls.at(-1)[1], { filters: { hours: null } });
|
||||
});
|
||||
|
||||
test('the panel names the window the server serves', () => {
|
||||
const { news, panel } = fixture();
|
||||
news.update(view({ windowHours: 12 }));
|
||||
assert.equal(
|
||||
panel.querySelector('.news-readout__window').textContent,
|
||||
'Last 12 h',
|
||||
);
|
||||
});
|
||||
|
||||
test('a clip waits behind its picture and plays, on request, in the open card', () => {
|
||||
const { news, panel } = fixture();
|
||||
const clipped = report('clip', {
|
||||
event: {
|
||||
size: 1,
|
||||
sides: [],
|
||||
image: {
|
||||
url: 'https://cdn4.telesco.pe/file/v.jpg',
|
||||
publisher: 'Channel',
|
||||
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
},
|
||||
},
|
||||
});
|
||||
news.update(view({ items: [feedCardView(clipped, NOW)] }));
|
||||
const card = panel.querySelector('.news-card');
|
||||
assert.equal(card.querySelector('.news-card__play').textContent, '▶');
|
||||
assert.equal(card.querySelector('video'), null);
|
||||
news.update(
|
||||
view({
|
||||
items: [feedCardView(clipped, NOW)],
|
||||
selected: feedCardView(clipped, NOW),
|
||||
}),
|
||||
);
|
||||
const video = panel.querySelector('.news-card.is-open video');
|
||||
assert.equal(
|
||||
video.getAttribute('src'),
|
||||
'https://cdn4.telesco.pe/file/v.mp4?token=x',
|
||||
);
|
||||
assert.equal(
|
||||
video.getAttribute('poster'),
|
||||
'https://cdn4.telesco.pe/file/v.jpg',
|
||||
);
|
||||
assert.equal(video.getAttribute('preload'), 'none');
|
||||
assert.ok(video.hasAttribute('controls'));
|
||||
// An expired link leaves the card without the clip.
|
||||
video.dispatchEvent(new Event('error'));
|
||||
news.update(
|
||||
view({
|
||||
items: [feedCardView(clipped, NOW)],
|
||||
selected: feedCardView(clipped, NOW),
|
||||
}),
|
||||
);
|
||||
assert.equal(panel.querySelector('.news-card.is-open video'), null);
|
||||
news.destroy();
|
||||
});
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user