Show JTWC cyclones: western Pacific, Indian Ocean and Southern Hemisphere (#1891)

* Show JTWC warnings in Cyclone advisories

Cyclone advisories now also read the Joint Typhoon Warning Center (keyless,
public domain) for the western North Pacific, North Indian Ocean and Southern
Hemisphere, beside NHC and CPHC.

- server/providers/jtwc.js reads JTWC's warnings feed, each storm's JMV 3.0
  warning (.tcw) and its overlay (.kmz). /api/cyclones merges them with NHC's:
  one storm per id, NHC's advisory where NHC lists the storm. A failed JTWC
  read keeps its last storms, marked stale, and never hides NHC's.
- Storms carry an agency. A JTWC warning has no cone; its 34-knot wind danger
  area is drawn as its own dashed area and named for the selected storm.
- A JTWC storm's card notes that the regional centre's warning is official
  and that JTWC winds are 1-minute averages. Source and coverage wording names
  both agencies.
- Each storm is served while its own advisory is usable (12 hours for NHC,
  13 for JTWC).

* Keep one JTWC failure from affecting other storms or NHC

- A storm whose JTWC warning cannot be read or parsed is left out and the
  others are shown; the read fails only when every listed storm's does.
- JTWC is read under its own 8-second deadline. A failed or slow JTWC read
  keeps JTWC's last good storms and never delays, fails or stales the NHC
  answer.
- Danger-swath longitudes past ±180 (a ring crossing the antimeridian) are
  wrapped into -180..180 instead of dropping the ring.

* Add the changelog entry for JTWC cyclones
This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-11-20 21:48:15 -08:00
1 parent ae212e5b63
commit 5608b12a25
33 files changed
+1699 -201

No files matched your search

+97 -12
View File
@@ -1,4 +1,8 @@
import { readResponseTextCapped } from './common/http.js';
import {
readResponseBytesCapped,
readResponseTextCapped,
} from './common/http.js';
import { JTWC_USABLE_MS, readJtwcStorms } from './jtwc.js';
const STATUS_URL = 'https://www.nhc.noaa.gov/CurrentStorms.json';
const GIS =
@@ -7,7 +11,14 @@ const HOUR = 3600_000;
// Data, not UI copy: src/layers/cyclones/index.js keeps the same English in
// msg() and translates it when shown (likewise 'Cyclone data unavailable').
const COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
const SOURCE = 'NOAA NHC / CPHC · JTWC';
const ATTRIBUTION =
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center; Joint Typhoon Warning Center (U.S. Navy / U.S. Air Force)';
/** How long a storm's advisory stays usable after issuance, by agency. */
export function cycloneUsableMs(storm) {
return storm?.agency === 'jtwc' ? JTWC_USABLE_MS : 12 * HOUR;
}
const LAYERS = [
{ id: 5, cap: 512 * 1024, count: 500, kind: 'points' },
{ id: 6, cap: 512 * 1024, count: 32, kind: 'track' },
@@ -114,6 +125,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
const positionAt = iso(raw.lastUpdate, now);
return {
id: raw.id,
agency: 'nhc',
name: text(raw.name),
classification: text(raw.classification, 16),
basin: raw.id.slice(0, 2).toUpperCase(),
@@ -138,6 +150,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
});
}
@@ -262,8 +275,13 @@ export function cycloneProxy({
fetchImpl = fetch,
now = () => Date.now(),
timeoutMs = 12_000,
// JTWC's own deadline, inside NHC's: a slow JTWC never holds NHC's answer.
jtwcTimeoutMs = 8_000,
readJtwc = readJtwcStorms,
} = {}) {
let cache = null;
// JTWC's storms from its last good read, reused while a read fails.
let jtwcCache = null;
let operation = null;
let attemptedAt = -Infinity;
async function upstream(url, cap, signal) {
@@ -286,7 +304,64 @@ export function cycloneProxy({
signal.throwIfAborted();
return result;
}
// A JTWC product: text or bytes; null when JTWC has none posted (403/404).
async function jtwcRead(url, kind, signal) {
signal.throwIfAborted();
const response = await fetchImpl(url, {
signal,
redirect: 'error',
headers: { 'User-Agent': 'Gods Eye View (public JTWC warning context)' },
});
if (
kind === 'bytes' &&
(response.status === 403 || response.status === 404)
) {
await response.body?.cancel();
return null;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error('cyclone_upstream_unavailable');
}
return kind === 'bytes'
? readResponseBytesCapped(response, 4 * 1024 * 1024, signal)
: readResponseTextCapped(response, 256 * 1024, signal);
}
/**
* JTWC's storms, read under their own deadline. A read that fails or runs
* out of time gives JTWC's last good storms still usable, so it never fails,
* delays past its deadline or stales NHC's answer.
*/
async function jtwc(signal) {
const controller = new AbortController();
const abort = () => controller.abort();
signal.addEventListener('abort', abort, { once: true });
const timer = setTimeout(abort, jtwcTimeoutMs);
try {
const storms = await Promise.race([
readJtwc((url, kind) => jtwcRead(url, kind, controller.signal), now()),
new Promise((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(new Error('jtwc_timeout')),
{ once: true },
),
),
]);
jtwcCache = storms;
return storms;
} catch {
return (jtwcCache || []).filter(
(storm) => now() - Date.parse(storm.issuedAt) <= JTWC_USABLE_MS,
);
} finally {
clearTimeout(timer);
signal.removeEventListener('abort', abort);
}
}
async function refresh(signal) {
// JTWC is read beside NHC and never rejects.
const pendingJtwc = jtwc(signal);
let storms = parseCycloneStatus(
await upstream(STATUS_URL, 128 * 1024, signal),
now(),
@@ -323,6 +398,14 @@ export function cycloneProxy({
}));
}
}
// One storm per id: NHC's advisory where NHC lists the storm (a storm
// crossing 180° keeps its id), JTWC's elsewhere.
const fromJtwc = await pendingJtwc;
const listed = new Set(storms.map((storm) => storm.id));
storms = [
...storms,
...fromJtwc.filter((storm) => !listed.has(storm.id)),
].slice(0, 32);
signal.throwIfAborted();
cache = { storms, fetchedAt: now() };
return cache;
@@ -365,9 +448,8 @@ export function cycloneProxy({
function describe(value, stale = false) {
return {
schemaVersion: 1,
source: 'NOAA NHC / CPHC',
attribution:
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center',
source: SOURCE,
attribution: ATTRIBUTION,
coverage: COVERAGE,
fetchedAt: value?.fetchedAt ?? null,
stale: stale || !value,
@@ -402,13 +484,16 @@ export function cycloneProxy({
json(200, describe(await acquire(controller.signal)));
} catch (error) {
if (error.status === 429) return json(429, { error: 'cyclone_busy' });
const usable =
cache &&
now() - cache.fetchedAt <= 12 * HOUR &&
cache.storms.every(
(storm) => now() - Date.parse(storm.issuedAt) <= 12 * HOUR,
);
json(200, describe(usable ? cache : null, true));
// Each storm is served while its own advisory is usable.
const usable = cache &&
now() - cache.fetchedAt <= 12 * HOUR && {
...cache,
storms: cache.storms.filter(
(storm) =>
now() - Date.parse(storm.issuedAt) <= cycloneUsableMs(storm),
),
};
json(200, describe(usable || null, true));
}
} finally {
res.removeListener?.('close', close);
+459
View File
@@ -0,0 +1,459 @@
import { inflateRawSync } from 'node:zlib';
/**
* Joint Typhoon Warning Center (JTWC) warnings for the cyclone layer: the
* western North Pacific, North Indian Ocean and Southern Hemisphere, where
* NHC and CPHC issue none. Keyless; US government work.
*
* rss/jtwc.rss current warnings, product links in each item
* products/<prefix>.tcw JMV 3.0 warning data (position, forecast, text)
* products/<prefix>.kmz Google Earth overlay: the 34-knot danger swath
*
* JTWC publishes no schema for any of these. Each reader takes only what it
* recognises and throws on a product that lacks it. The danger swath is the
* swath of 34-knot winds widened by forecast track error; it is drawn as its
* own area (`dangerArea`), never as a cone of centre-track uncertainty.
*/
export const JTWC_ORIGIN = 'https://www.metoc.navy.mil';
export const JTWC_RSS_URL = `${JTWC_ORIGIN}/jtwc/rss/jtwc.rss`;
export const JTWC_PRODUCTS_URL = `${JTWC_ORIGIN}/jtwc/products`;
const WARNING_ITEMS = [
'NWPAC-NIO-WARNINGS',
'EPAC-CPAC-WARNINGS',
'SH-WARNINGS',
];
const NO_WARNINGS = 'No Current Tropical Cyclone Warnings';
const PREFIX = /^(?:wp|io|sh|ep|cp)\d{4}$/;
const HOUR = 3600_000;
/**
* A JTWC warning is usable for 13 hours after issuance: some storms are on
* 12-hourly warnings, and the next one posts shortly before its time.
*/
export const JTWC_USABLE_MS = 13 * HOUR;
const KML_MAX_BYTES = 4 * 1024 * 1024;
function invalid(what) {
return new Error(`invalid_jtwc_data: ${what}`);
}
/** Storm product prefixes (`sh0427`) the feed lists, in feed order. */
export function parseJtwcFeed(feed) {
if (typeof feed !== 'string' || !feed.includes('<rss')) throw invalid('feed');
const prefixes = [];
for (const guid of WARNING_ITEMS) {
const item = feed
.split('<item>')
.slice(1)
.map((part) => part.split('</item>')[0])
.find((part) => part.includes(`<guid>${guid}</guid>`));
if (!item) throw invalid(`feed item ${guid}`);
const found = [
...item.matchAll(
/\/jtwc\/products\/([a-z]{2}\d{4})(?:web\.txt|\.tcw|\.kmz)/g,
),
]
.map((match) => match[1])
.filter((prefix) => PREFIX.test(prefix));
if (!found.length && !item.includes(NO_WARNINGS))
throw invalid(`feed item ${guid}`);
for (const prefix of found)
if (!prefixes.includes(prefix)) prefixes.push(prefix);
}
return prefixes;
}
/** `sh0427` is ATCF `sh042027` (the season year). */
export function jtwcStormId(prefix) {
if (!PREFIX.test(prefix)) throw invalid('prefix');
return `${prefix.slice(0, 4)}20${prefix.slice(4)}`;
}
// JTWC's words for a storm, longest first, and their codes.
const KINDS = [
['SUPER TYPHOON', 'STY'],
['SUBTROPICAL STORM', 'SS'],
['SUBTROPICAL DEPRESSION', 'SD'],
['TROPICAL CYCLONE', 'TC'],
['TROPICAL STORM', 'TS'],
['TROPICAL DEPRESSION', 'TD'],
['TYPHOON', 'TY'],
['HURRICANE', 'HU'],
];
/** `115S` / `1642W` (tenths) or `11.6S` (degrees); south and west negative. */
function coordinate(word, tenths) {
const match = /^(\d+(?:\.\d+)?)([NSEW])$/.exec(word || '');
if (!match || (tenths && match[1].includes('.'))) return null;
const value = Number(match[1]) / (tenths ? 10 : 1);
const limit = 'NS'.includes(match[2]) ? 90 : 180;
if (!(value <= limit)) return null;
return 'SW'.includes(match[2]) ? -value : value;
}
function utc(year, month, day, hour, minute = 0) {
const at = Date.UTC(year, month - 1, day, hour, minute);
const date = new Date(at);
return date.getUTCDate() === day && date.getUTCHours() === hour ? at : NaN;
}
/** `ddhhmm` (optionally `Z`-suffixed) as the time nearest `near`. */
function nearest(dtg, near) {
const match = /^(\d\d)(\d\d)(\d\d)Z?[.,]?$/.exec(dtg || '');
if (!match) return NaN;
const base = new Date(near);
let best = NaN;
for (const offset of [-1, 0, 1]) {
const month = new Date(
Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + offset, 1),
);
const at = utc(
month.getUTCFullYear(),
month.getUTCMonth() + 1,
Number(match[1]),
Number(match[2]),
Number(match[3]),
);
if (
Number.isFinite(at) &&
(!Number.isFinite(best) || Math.abs(at - near) < Math.abs(best - near))
)
best = at;
}
return best;
}
const iso = (ms) => new Date(ms).toISOString();
function titleCase(name) {
return name
.toLowerCase()
.replace(
/(^|[\s-])([a-z])/g,
(_, gap, letter) => gap + letter.toUpperCase(),
);
}
/**
* One storm's warning (`.tcw`) as a cyclone-snapshot storm, its geometry
* pending until `withJtwcDangerArea` gives it the warning's danger swath.
* Throws on a warning without its header, hour 0 or subject.
*/
export function parseJtwcWarning(prefix, text) {
const id = jtwcStormId(prefix);
if (typeof text !== 'string') throw invalid('tcw');
const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, ''));
const dtg = lines[0]?.split(/\s+/)[2];
const headerAt = lines.findIndex((line) => /^\d{10}\s/.test(line));
if (headerAt < 0 || !dtg) throw invalid('tcw header');
const header = lines[headerAt].split(/\s+/);
const synopticAt = utc(
Number(header[0].slice(0, 4)),
Number(header[0].slice(4, 6)),
Number(header[0].slice(6, 8)),
Number(header[0].slice(8, 10)),
);
if (!Number.isFinite(synopticAt)) throw invalid('tcw synoptic time');
const number = header[1];
let at = 2;
const nameWords = [];
while (at < header.length && !/^\d+$/.test(header[at]))
nameWords.push(header[at++]);
const numbers = header.slice(at);
const warningMatch = /^0*(\d{1,3})$/.exec(numbers[0] || '');
if (!warningMatch || !number) throw invalid('tcw warning number');
const advisoryNumber = String(Number(warningMatch[1]));
const issuedAt = nearest(dtg, synopticAt);
if (!Number.isFinite(issuedAt)) throw invalid('tcw message time');
const direction = Number(numbers[2]);
const speed = Number(numbers[3]);
const forecast = [];
for (const line of lines.slice(headerAt + 1)) {
const words = line.trim().split(/\s+/);
const tau = /^T(\d{3})$/.exec(words[0]);
if (!tau) break;
const latitude = coordinate(words[1], true);
const longitude = coordinate(words[2], true);
const windKt = Number(words[3]);
if (latitude === null || longitude === null || !/^\d+$/.test(words[3]))
throw invalid('tcw forecast line');
forecast.push({
position: { longitude, latitude },
tauHours: Number(tau[1]),
windKt,
gustKt: null,
});
}
if (forecast[0]?.tauHours !== 0) throw invalid('tcw hour 0');
const subjectAt = lines.findIndex((line) => /^\s*SUBJ/.test(line));
if (subjectAt < 0) throw invalid('tcw subject');
const subject = lines[subjectAt]
.replace(/^\s*SUBJ[:/]?/, '')
.replace(/\/+$/, '')
.trim();
let end = lines.findIndex((line, i) => i > subjectAt && line.trim() === '//');
if (end < 0) end = lines.length;
const body = lines.slice(subjectAt, end);
let tau = null;
for (const line of body) {
const trimmed = line.trim();
const hours = /^(\d+) HRS, VALID AT:$/.exec(trimmed);
if (trimmed.startsWith('WARNING POSITION')) tau = 0;
else if (hours) tau = Number(hours[1]);
else {
const gust = /GUSTS (\d+) KT/.exec(trimmed);
const point = gust && forecast.find((p) => p.tauHours === tau);
if (point && point.gustKt === null) point.gustKt = Number(gust[1]);
}
}
const remarksAt = body.findIndex((line) => /^\s*REMARKS/.test(line));
const remarks = (remarksAt < 0 ? [] : body.slice(remarksAt))
.join(' ')
.replace(/\s+/g, ' ');
const issue = /(\d{6})Z POSITION NEAR (\d+\.\d)([NS]) (\d+\.\d)([EW])/.exec(
remarks,
);
const issueAt = issue ? nearest(issue[1], synopticAt) : NaN;
const pressure = /CENTRAL PRESSURE AT \d{6}Z IS (\d{3,4}) MB/.exec(remarks);
const kind = KINDS.find(([words]) => subject.includes(words));
const first = forecast[0];
const position =
issue && Number.isFinite(issueAt)
? {
longitude: coordinate(`${issue[4]}${issue[5]}`, false),
latitude: coordinate(`${issue[2]}${issue[3]}`, false),
}
: first.position;
if (position.longitude === null || position.latitude === null)
throw invalid('tcw position');
const basin = id.slice(0, 2);
const longitude = position.longitude;
const outlook =
basin === 'io' || (basin === 'sh' && longitude >= 0 && longitude < 135)
? 'abioweb.txt'
: basin === 'wp' || basin === 'sh'
? 'abpwweb.txt'
: null;
const pressureHpa = pressure ? Number(pressure[1]) : null;
const storm = {
id,
agency: 'jtwc',
name: nameWords.length ? titleCase(nameWords.join(' ')) : number,
classification: kind ? kind[1] : 'TC',
basin: basin.toUpperCase(),
position,
positionAt: iso(Number.isFinite(issueAt) ? issueAt : synopticAt),
advisoryNumber,
issuedAt: iso(issuedAt),
windKt: first.windKt <= 300 ? first.windKt : null,
pressureHpa:
pressureHpa !== null && pressureHpa >= 800 && pressureHpa <= 1100
? pressureHpa
: null,
movement: {
directionDegrees:
Number.isInteger(direction) && direction <= 360 ? direction : null,
speedKt: Number.isInteger(speed) && speed <= 200 ? speed : null,
},
advisoryUrl: `${JTWC_PRODUCTS_URL}/${prefix}web.txt`,
outlookUrl: outlook ? `${JTWC_PRODUCTS_URL}/${outlook}` : null,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
return { storm, forecast };
}
/**
* The storm with its forecast geometry, current only with the danger swath
* of its own warning number (JTWC posts the overlay before the text).
*/
export function withJtwcDangerArea({ storm, forecast }, overlay) {
if (
!overlay ||
overlay.advisoryNumber !== storm.advisoryNumber ||
!overlay.dangerArea ||
forecast.length < 2
)
return storm;
return {
...storm,
geometryStatus: 'current',
geometryAdvisoryNumber: storm.advisoryNumber,
forecastPoints: forecast.map((point) => ({
position: { ...point.position },
tauHours: point.tauHours,
windKt: point.windKt,
gustKt: point.gustKt,
})),
track: {
type: 'LineString',
coordinates: forecast.map((point) => [
point.position.longitude,
point.position.latitude,
]),
},
dangerArea: overlay.dangerArea,
};
}
/** The warning number and 34-knot danger swath of a warning's KML. */
export function parseJtwcKml(kml) {
if (typeof kml !== 'string') throw invalid('kml');
const number = /WARNING NR\s+0*(\d{1,3})\b/.exec(kml);
if (!number) throw invalid('kml warning number');
const polygons = [];
for (const part of kml.split('<Placemark').slice(1)) {
const placemark = part.split('</Placemark>')[0];
const name = /<name>([^<]*)<\/name>/.exec(placemark)?.[1] || '';
if (!/^\s*34 knot Danger Swath/i.test(name)) continue;
for (const polygonPart of placemark.split('<Polygon').slice(1)) {
const polygon = polygonPart.split('</Polygon>')[0];
const rings = [
...polygon.matchAll(/<coordinates>([\s\S]*?)<\/coordinates>/g),
]
.map((match) => ring(match[1]))
.filter(Boolean);
if (rings.length) polygons.push(rings);
}
}
return {
advisoryNumber: String(Number(number[1])),
dangerArea: !polygons.length
? null
: polygons.length === 1
? { type: 'Polygon', coordinates: polygons[0] }
: { type: 'MultiPolygon', coordinates: polygons },
};
}
/**
* `longitude` in -180..180 (180 stays 180). JTWC writes a ring crossing the
* antimeridian with longitudes past ±180 (`181.5`); wrapped, the ring crosses
* 180° as NHC's cones that cross it do.
*/
export function wrapJtwcLongitude(longitude) {
if (Math.abs(longitude) <= 180) return longitude;
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
// JTWC writes two decimals; this drops the float noise of the wrap.
return Math.round(wrapped * 1e6) / 1e6;
}
function ring(text) {
const points = [];
for (const tuple of text.trim().split(/\s+/)) {
const [lon, lat] = tuple.split(',').map(Number);
if (
!Number.isFinite(lon) ||
!Number.isFinite(lat) ||
Math.abs(lon) > 540 ||
Math.abs(lat) > 90
)
return null;
points.push([wrapJtwcLongitude(lon), lat]);
}
if (!points.length) return null;
const [a, b] = [points[0], points.at(-1)];
if (a[0] !== b[0] || a[1] !== b[1]) points.push([...a]);
return points.length >= 4 ? points : null;
}
/**
* The first `.kml` entry of a KMZ (a zip), from its central directory.
* Stored and deflated entries only.
*/
export function kmlFromKmz(bytes) {
const data = Buffer.from(bytes);
let end = -1;
for (let i = data.length - 22; i >= Math.max(0, data.length - 65_557); i--)
if (data.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw invalid('kmz');
const entries = data.readUInt16LE(end + 10);
let at = data.readUInt32LE(end + 16);
for (let n = 0; n < entries; n++) {
if (at + 46 > data.length || data.readUInt32LE(at) !== 0x02014b50)
throw invalid('kmz directory');
const method = data.readUInt16LE(at + 10);
const compressed = data.readUInt32LE(at + 20);
const size = data.readUInt32LE(at + 24);
const nameLength = data.readUInt16LE(at + 28);
const extra = data.readUInt16LE(at + 30);
const comment = data.readUInt16LE(at + 32);
const local = data.readUInt32LE(at + 42);
const name = data.toString('utf8', at + 46, at + 46 + nameLength);
at += 46 + nameLength + extra + comment;
if (!name.toLowerCase().endsWith('.kml')) continue;
if (size > KML_MAX_BYTES || data.readUInt32LE(local) !== 0x04034b50)
throw invalid('kmz entry');
const start =
local +
30 +
data.readUInt16LE(local + 26) +
data.readUInt16LE(local + 28);
const raw = data.subarray(start, start + compressed);
if (method === 0) return raw.toString('utf8');
if (method === 8)
return inflateRawSync(raw, { maxOutputLength: KML_MAX_BYTES }).toString(
'utf8',
);
throw invalid('kmz compression');
}
throw invalid('kmz holds no kml');
}
/**
* Every storm JTWC lists, through `read(url, kind)` (kind `text` or
* `bytes`). A feed that cannot be read throws. One storm never stops the
* others: a warning that cannot be read or parsed leaves that storm out,
* and only when every listed storm's fails does the read throw. An overlay
* that cannot be read leaves its storm's geometry `unavailable`, and one
* JTWC has not posted yet (`read` resolving null), or posted for another
* warning, leaves it `pending`.
*/
export async function readJtwcStorms(read, now = Date.now()) {
const prefixes = parseJtwcFeed(await read(JTWC_RSS_URL, 'text'));
// Each storm's warning and overlay are read at once, every storm alike.
const readStorm = async (prefix) => {
const [text, overlay] = await Promise.all([
read(`${JTWC_PRODUCTS_URL}/${prefix}.tcw`, 'text'),
read(`${JTWC_PRODUCTS_URL}/${prefix}.kmz`, 'bytes')
.then((bytes) =>
bytes === null ? null : parseJtwcKml(kmlFromKmz(bytes)),
)
.catch((error) => {
if (error?.name === 'AbortError') throw error;
return undefined;
}),
]);
if (text === null) throw invalid(`${prefix}.tcw missing`);
const warning = parseJtwcWarning(prefix, text);
const issued = Date.parse(warning.storm.issuedAt);
// A warning past its use, or dated far ahead of this clock, is left out.
if (now - issued > JTWC_USABLE_MS || issued - now > 90 * 60_000)
return null;
// An overlay that could not be read: the geometry is unavailable.
return overlay === undefined
? { ...warning.storm, geometryStatus: 'unavailable' }
: withJtwcDangerArea(warning, overlay);
};
const results = await Promise.allSettled(prefixes.map(readStorm));
const failed = results.filter((result) => result.status === 'rejected');
const aborted = failed.find((result) => result.reason?.name === 'AbortError');
if (aborted) throw aborted.reason;
if (failed.length && failed.length === results.length) throw failed[0].reason;
const storms = [];
for (const result of results) {
const storm = result.status === 'fulfilled' ? result.value : null;
if (storm && !storms.some((held) => held.id === storm.id))
storms.push(storm);
}
return storms;
}
+332
View File
@@ -0,0 +1,332 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deflateRawSync } from 'node:zlib';
import {
wrapJtwcLongitude,
JTWC_PRODUCTS_URL,
JTWC_RSS_URL,
jtwcStormId,
kmlFromKmz,
parseJtwcFeed,
parseJtwcKml,
parseJtwcWarning,
readJtwcStorms,
withJtwcDangerArea,
} from './jtwc.js';
// Tropical Cyclone 04P (Xavier), warning 15, as JTWC published it on
// 2026-11-21 (past fixes shortened).
const TCW = `WTPS51 PGTW 210300
WARNING ATCG MIL 04P SWP 261121015248
2026112100 04P XAVIER 015 01 245 04 SATL 020
T000 115S 1642W 045 R034 075 NE QD 105 SE QD 090 SW QD 050 NW QD
T012 120S 1652W 045 R034 075 NE QD 105 SE QD 090 SW QD 035 NW QD
T024 125S 1665W 040 R034 070 NE QD 100 SE QD 070 SW QD 020 NW QD
T072 130S 1708W 030
AMP
072HR DISSIPATED AS A SIGNIFICANT TROPICAL CYCLONE OVER WATER
SUBJ: TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
1. TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
01 ACTIVE TROPICAL CYCLONE IN SOUTHPAC
---
WARNING POSITION:
210000Z --- NEAR 11.5S 164.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
FORECASTS:
12 HRS, VALID AT:
211200Z --- 12.0S 165.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
24 HRS, VALID AT:
220000Z --- 12.5S 166.5W
MAX SUSTAINED WINDS - 040 KT, GUSTS 050 KT
---
72 HRS, VALID AT:
240000Z --- 13.0S 170.8W
MAX SUSTAINED WINDS - 030 KT, GUSTS 040 KT
---
REMARKS:
210300Z POSITION NEAR 11.6S 164.5W.
21NOV26. TROPICAL CYCLONE 04P (XAVIER), LOCATED APPROXIMATELY 416
NM EAST-NORTHEAST OF PAGO PAGO, HAS TRACKED WEST-SOUTHWESTWARD AT
04 KNOTS OVER THE PAST SIX HOURS.
MINIMUM CENTRAL PRESSURE AT 210000Z IS 995 MB. MAXIMUM
SIGNIFICANT WAVE HEIGHT AT 210000Z IS 19 FEET. NEXT WARNINGS AT
210900Z, 211500Z, 212100Z AND 220300Z.
//
0426112018 113S1638W 55
0426112100 115S1642W 45
NNNN
`;
const item = (guid, body) =>
`<item><title>${guid}</title><description><![CDATA[${body}]]></description><guid>${guid}</guid></item>`;
const NONE =
"<ul><li><font color='red'>No Current Tropical Cyclone Warnings.</font></li></ul>";
function feed(prefixes = ['sh0427']) {
const links = prefixes
.map(
(prefix) =>
`<li><a href='${JTWC_PRODUCTS_URL}/${prefix}web.txt'>TC Warning Text</a></li><li><a href='${JTWC_PRODUCTS_URL}/${prefix}.tcw'>JMV 3.0 Data</a></li>`,
)
.join('');
return `<?xml version="1.0"?><rss version="2.0"><channel>${item('NWPAC-NIO-WARNINGS', NONE)}${item('EPAC-CPAC-WARNINGS', NONE)}${item('SH-WARNINGS', prefixes.length ? links : NONE)}${item('TROPICAL-ADVISORIES', `<a href="${JTWC_PRODUCTS_URL}/abpwweb.txt">ABPW10</a>`)}</channel></rss>`;
}
const SWATH = [
[-164.02, -9.5],
[-163.0, -12.0],
[-171.0, -14.5],
[-170.0, -11.0],
];
function kml(number = 15) {
return `<kml><Document><Folder>
<Placemark><name>21/00Z (TROPICAL CYCLONE 04P (XAVIER) WARNING NR ${number} - 45 knots)</name>
<Point><coordinates>-164.2,-11.5,0</coordinates></Point></Placemark>
<Placemark><name>RADIUS OF 34 KT WINDS</name><Polygon><outerBoundaryIs><LinearRing><coordinates>-164.2,-10.25,0 -163,-11,0 -164.2,-12.5,0 -164.2,-10.25,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
<Placemark><name>34 knot Danger Swath</name><Polygon><outerBoundaryIs><LinearRing><coordinates>
${SWATH.map(([lon, lat]) => `${lon},${lat},0`).join(' ')}
</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
</Folder></Document></kml>`;
}
/** A zip holding `files` ({name: text}), deflated. */
function zip(files) {
const locals = [],
central = [];
let offset = 0;
for (const [name, text] of Object.entries(files)) {
const data = Buffer.from(text);
const packed = deflateRawSync(data);
const nameBytes = Buffer.from(name);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(8, 8);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0);
entry.writeUInt16LE(8, 10);
entry.writeUInt32LE(packed.length, 20);
entry.writeUInt32LE(data.length, 24);
entry.writeUInt16LE(nameBytes.length, 28);
entry.writeUInt32LE(offset, 42);
locals.push(local, nameBytes, packed);
central.push(entry, nameBytes);
offset += 30 + nameBytes.length + packed.length;
}
const directory = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(Object.keys(files).length, 8);
end.writeUInt16LE(Object.keys(files).length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return new Uint8Array(Buffer.concat([...locals, directory, end]));
}
const NOW = Date.UTC(2026, 10, 21, 3, 20);
test('the feed lists the storms of the warning items and refuses anything else', () => {
assert.deepEqual(parseJtwcFeed(feed()), ['sh0427']);
assert.deepEqual(parseJtwcFeed(feed([])), []);
assert.deepEqual(parseJtwcFeed(feed(['wp3026', 'sh0427', 'wp3026'])), [
'wp3026',
'sh0427',
]);
assert.throws(() => parseJtwcFeed('<html>blocked</html>'));
assert.throws(() =>
parseJtwcFeed(feed().replace('<guid>SH-WARNINGS', '<guid>OTHER')),
);
assert.throws(() => parseJtwcFeed(feed([]).replaceAll(NONE, '<ul></ul>')));
});
test('product prefixes are season-year ATCF ids', () => {
assert.equal(jtwcStormId('sh0427'), 'sh042027');
assert.equal(jtwcStormId('wp3026'), 'wp302026');
assert.throws(() => jtwcStormId('al0126'));
});
test('a warning reads as a pending JTWC storm with its forecast', () => {
const { storm, forecast } = parseJtwcWarning('sh0427', TCW);
assert.deepEqual(
{ ...storm },
{
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
// Where the storm was at issuance, from the remarks.
position: { longitude: -164.5, latitude: -11.6 },
positionAt: '2026-11-21T03:00:00.000Z',
advisoryNumber: '15',
issuedAt: '2026-11-21T03:00:00.000Z',
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
},
);
assert.deepEqual(
forecast.map((point) => [point.tauHours, point.windKt, point.gustKt]),
[
[0, 45, 55],
[12, 45, 55],
[24, 40, 50],
[72, 30, 40],
],
);
assert.deepEqual(forecast[0].position, { longitude: -164.2, latitude: -11.5 });
});
test('classes come from the subject; broken warnings throw', () => {
const typhoon = TCW.replace(
'SUBJ: TROPICAL CYCLONE 04P',
'SUBJ: SUPER TYPHOON 04P',
);
assert.equal(parseJtwcWarning('sh0427', typhoon).storm.classification, 'STY');
for (const broken of [
'',
'<html>Access Denied</html>',
TCW.replace(/^T000.*$/m, ''),
TCW.replace('SUBJ:', 'XXXX:'),
TCW.replace('T000 115S', 'T000 115X'),
])
assert.throws(() => parseJtwcWarning('sh0427', broken), /invalid_jtwc/);
});
test('the danger swath makes the geometry current only for its own warning', () => {
const warning = parseJtwcWarning('sh0427', TCW);
const overlay = parseJtwcKml(kml(15));
assert.equal(overlay.advisoryNumber, '15');
assert.deepEqual(overlay.dangerArea, {
type: 'Polygon',
coordinates: [[...SWATH, SWATH[0]]],
});
const storm = withJtwcDangerArea(warning, overlay);
assert.equal(storm.geometryStatus, 'current');
assert.equal(storm.geometryAdvisoryNumber, '15');
assert.equal(storm.cone, null);
assert.deepEqual(storm.track.coordinates[0], [-164.2, -11.5]);
assert.equal(storm.forecastPoints.length, 4);
assert.equal(
withJtwcDangerArea(warning, parseJtwcKml(kml(14))).geometryStatus,
'pending',
);
assert.equal(withJtwcDangerArea(warning, null).geometryStatus, 'pending');
assert.throws(() => parseJtwcKml('<kml></kml>'));
});
test('the KML is read out of the KMZ', () => {
assert.equal(
kmlFromKmz(zip({ 'images/logo.png': 'png', 'doc.kml': kml() })),
kml(),
);
assert.throws(() => kmlFromKmz(new Uint8Array([1, 2, 3])));
assert.throws(() => kmlFromKmz(zip({ 'logo.png': 'png' })));
});
function reader(answers) {
const calls = [];
const read = async (url, kind) => {
calls.push(url);
const answer = answers[url];
if (answer instanceof Error) throw answer;
if (answer === undefined) return null;
return kind === 'bytes' ? answer : String(answer);
};
return { read, calls };
}
test('every listed storm is read with its overlay; an unreadable overlay leaves its geometry unavailable', async () => {
const products = (prefix, kmz) => ({
[`${JTWC_PRODUCTS_URL}/${prefix}.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/${prefix}.kmz`]: kmz,
});
const good = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', zip({ 'doc.kml': kml() })),
});
const [storm] = await readJtwcStorms(good.read, NOW);
assert.equal(storm.geometryStatus, 'current');
assert.deepEqual(good.calls.sort(), [
`${JTWC_PRODUCTS_URL}/sh0427.kmz`,
`${JTWC_PRODUCTS_URL}/sh0427.tcw`,
JTWC_RSS_URL,
]);
const notPosted = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', undefined),
});
assert.equal(
(await readJtwcStorms(notPosted.read, NOW))[0].geometryStatus,
'pending',
);
const broken = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', new Uint8Array([1, 2, 3])),
});
assert.equal(
(await readJtwcStorms(broken.read, NOW))[0].geometryStatus,
'unavailable',
);
// A warning past 13 hours is left out; with every listed warning missing,
// the read fails.
assert.deepEqual(
await readJtwcStorms(good.read, NOW + 13 * 3600_000),
[],
);
const missing = reader({ [JTWC_RSS_URL]: feed() });
await assert.rejects(readJtwcStorms(missing.read, NOW), /invalid_jtwc/);
const down = reader({ [JTWC_RSS_URL]: new Error('down') });
await assert.rejects(readJtwcStorms(down.read, NOW), /down/);
});
test('one storm whose warning cannot be read or parsed never stops the others', async () => {
const { read } = reader({
[JTWC_RSS_URL]: feed(['wp3026', 'sh0427', 'io0126']),
[`${JTWC_PRODUCTS_URL}/wp3026.tcw`]: new Error('HTTP 500'),
[`${JTWC_PRODUCTS_URL}/io0126.tcw`]: '<html>Access Denied</html>',
[`${JTWC_PRODUCTS_URL}/sh0427.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/sh0427.kmz`]: zip({ 'doc.kml': kml() }),
});
const storms = await readJtwcStorms(read, NOW);
assert.deepEqual(
storms.map((storm) => [storm.id, storm.geometryStatus]),
[['sh042027', 'current']],
);
});
test('a danger swath crossing the antimeridian is kept, its longitudes wrapped', () => {
const crossing = kml().replace(
/<coordinates>\n[^<]*<\/coordinates>/,
'<coordinates>179.5,-15,0 181,-16,0 180.5,-18,0 179.5,-17,0</coordinates>',
);
assert.deepEqual(parseJtwcKml(crossing).dangerArea, {
type: 'Polygon',
coordinates: [
[
[179.5, -15],
[-179, -16],
[-179.5, -18],
[179.5, -17],
[179.5, -15],
],
],
});
assert.equal(wrapJtwcLongitude(-181.5), 178.5);
assert.equal(wrapJtwcLongitude(180), 180);
assert.equal(wrapJtwcLongitude(-164.2), -164.2);
});