mobs-ws 0.0.0-stage → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -2
  3. package/package.json +39 -4
  4. package/src/index.js +476 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MOBS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # mobs-ws
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official JavaScript client for the MOBS `/v1/ws/metar` WebSocket (protocol 4).
4
+
5
+ Requires Node 22+ (or a browser) and `mobs-ws` 0.17.0 for region and
6
+ platform subscriptions. There are no runtime dependencies. The client
7
+ uses the global `WebSocket` in the browser and in Node 22+. Snapshot
8
+ and resume are opt-in. The client applies `awc_confirmed` frames
9
+ last-wins per (`icao`, `versions`), handles `station_late`,
10
+ `station_recovered`, and `usage` (use `requestUsage()`), and ignores
11
+ unknown frame types. Late alerts are kept as the latest frame per
12
+ `outage_id` and cleared on `station_recovered`. More than one
13
+ `station_late` can arrive in the same outage. Snapshot frames are
14
+ marked `cached`; they are merged into `latest` and do not advance
15
+ `seq`.
16
+
17
+ A change-only `filter`, parsed `delta`, a US `state`, a `bbox`, and a
18
+ `platform` (`polymarket_com` or `polymarket_us`) are opt-in on a
19
+ mid-session `subscribe`, not on the handshake query. A region or
20
+ platform grant counts as one subscription; a socket may hold at most
21
+ 10 grants. `invalid_region`, `unknown_platform`, and `too_many_grants`
22
+ are stored on `lastError`. On reconnect, the client passes `since_seq`
23
+ and `boot_id` as before, and re-subscribes held grants. The first
24
+ state, first bounding box, and first platform can be replayed; any
25
+ extra grants of the same kind are restored by snapshot, not replay.
26
+
27
+ The API key is never embedded. Pass it to the constructor, or set
28
+ `MOBS_TOKEN` (Node). In the browser, pass the token in and the client
29
+ uses `?token=` because a page cannot set socket headers. A browser
30
+ `WebSocket` cannot see a handshake 401 or 403, so the client retries.
31
+
32
+ ```bash
33
+ npm install mobs-ws@0.17.0
34
+ export MOBS_TOKEN=$MOBS_TOKEN
35
+ ```
36
+
37
+ ```javascript
38
+ import { MetarClient } from "mobs-ws";
39
+
40
+ const client = new MetarClient({
41
+ airports: ["KNYC", "KLGA"],
42
+ token: process.env.MOBS_TOKEN, // or "YOUR_API_KEY"
43
+ snapshot: true,
44
+ resume: true,
45
+ platform: "polymarket_com",
46
+ onRecord: (rec) => console.log(rec.icao, rec.raw_metar, rec.awc_confirmed),
47
+ });
48
+
49
+ // Mid-session: client.subscribe([], {state: "NY"})
50
+ // or client.subscribe([], {bbox: {south:40.0,west:-75.0,north:41.5,east:-73.0}})
51
+ await client.runForever();
52
+ ```
53
+
54
+ MIT licensed. See [LICENSE](https://github.com/Mobs-ws/mobs-sdks/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "mobs-ws",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.17.0",
4
+ "description": "Official client for the MOBS /v1/ws/metar WebSocket (protocol 4).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test test/*.test.js"
18
+ },
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "keywords": [
23
+ "mobs",
24
+ "metar",
25
+ "websocket"
26
+ ],
27
+ "author": "MOBS <admin@mobs.ws>",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/mobs-ws/mobs-sdks.git",
31
+ "directory": "js"
32
+ },
33
+ "homepage": "https://github.com/mobs-ws/mobs-sdks#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/mobs-ws/mobs-sdks/issues"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ }
41
+ }
package/src/index.js ADDED
@@ -0,0 +1,476 @@
1
+ // Official client for MOBS /v1/ws/metar (protocol 4).
2
+ // Promoted from examples/ws_client.js and the WebSocket API page sample.
3
+ // No runtime dependencies: uses the global WebSocket (browser and Node 22+).
4
+ // The token comes only from the caller or the MOBS_TOKEN environment
5
+ // variable. It is never embedded.
6
+
7
+ export const DEFAULT_URL = "wss://mobs.ws/v1/ws/metar";
8
+ export const MAX_GRANTS = 10;
9
+ export const KNOWN_PLATFORMS = Object.freeze(["polymarket_com", "polymarket_us"]);
10
+ export const ERROR_CODES = Object.freeze([
11
+ "invalid_airports",
12
+ "bad_request",
13
+ "unknown_action",
14
+ "too_many_airports",
15
+ "invalid_region",
16
+ "unknown_platform",
17
+ "too_many_grants",
18
+ ]);
19
+ export const PING_EVERY_MS = 20000;
20
+ export const PONG_TIMEOUT_MS = 15000;
21
+ export const BACKOFF_START_MS = 1000;
22
+ export const BACKOFF_CAP_MS = 30000;
23
+ export const QUIET_OPEN_MS = 10000;
24
+
25
+ export function resolveToken(token) {
26
+ const env =
27
+ typeof process !== "undefined" && process.env && process.env.MOBS_TOKEN
28
+ ? process.env.MOBS_TOKEN
29
+ : "";
30
+ const value = token == null || token === "" ? env : token;
31
+ if (!value) {
32
+ throw new Error("pass a token or set MOBS_TOKEN");
33
+ }
34
+ return value;
35
+ }
36
+
37
+ export function shouldRetry(code) {
38
+ return code !== 4403;
39
+ }
40
+
41
+ export function nextBackoff(delay, rand = Math.random) {
42
+ const grown = Math.min(delay * 2, BACKOFF_CAP_MS);
43
+ return grown * (0.5 + rand());
44
+ }
45
+
46
+ function newerThan(incoming, held) {
47
+ if (incoming.versions !== held.versions) return true;
48
+ if (
49
+ incoming.icao !== held.icao ||
50
+ incoming.obs_time !== held.obs_time ||
51
+ incoming.raw_metar !== held.raw_metar
52
+ ) {
53
+ return true;
54
+ }
55
+ return incoming._live && !held._live;
56
+ }
57
+
58
+ export function mergeRecord(latest, record, live = false) {
59
+ const item = Object.assign({}, record, {_live: live});
60
+ const icao = item.icao;
61
+ if (!icao) return latest;
62
+ const held = latest[icao];
63
+ if (!held || newerThan(item, held)) latest[icao] = item;
64
+ return latest;
65
+ }
66
+
67
+ export function applyAwcConfirmed(latest, message) {
68
+ const icao = message.icao;
69
+ const versions = message.versions;
70
+ if (!icao || versions == null) return latest;
71
+ const held = latest[icao];
72
+ if (!held || held.versions !== versions) return latest;
73
+ held.awc_confirmed = true;
74
+ held.awc_confirmed_at = message.awc_confirmed_at;
75
+ return latest;
76
+ }
77
+
78
+ export function handshakeUrl(base, airports, {snapshot = true, sinceSeq = null, bootId = null} = {}) {
79
+ const url = new URL(base);
80
+ url.searchParams.set("airports", airports.join(","));
81
+ if (snapshot) url.searchParams.set("snapshot", "true");
82
+ if (sinceSeq != null && bootId) {
83
+ url.searchParams.set("since_seq", String(sinceSeq));
84
+ url.searchParams.set("boot_id", bootId);
85
+ }
86
+ return url.toString();
87
+ }
88
+
89
+ export function latestUrl(wsUrl, airports) {
90
+ const url = new URL(wsUrl);
91
+ url.protocol = url.protocol === "wss:" || url.protocol === "https:" ? "https:" : "http:";
92
+ url.pathname = "/v1/metar/latest";
93
+ url.search = new URLSearchParams({airports: airports.join(",")}).toString();
94
+ return url.toString();
95
+ }
96
+
97
+ export async function fetchLatest(wsUrl, token, airports) {
98
+ try {
99
+ const headers = token ? {Authorization: "Bearer " + token} : {};
100
+ const response = await fetch(latestUrl(wsUrl, airports), {headers});
101
+ if (!response.ok) return [];
102
+ const body = await response.json();
103
+ return body.data || [];
104
+ } catch {
105
+ return [];
106
+ }
107
+ }
108
+
109
+ function isBrowser() {
110
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
111
+ }
112
+
113
+ function openWebSocket(url, token) {
114
+ if (!isBrowser() && token) {
115
+ try {
116
+ return new WebSocket(url, {headers: {Authorization: "Bearer " + token}});
117
+ } catch {
118
+ // Fall through to the query form used in browsers.
119
+ }
120
+ }
121
+ const target = new URL(url);
122
+ if (token && !target.searchParams.has("token")) {
123
+ target.searchParams.set("token", token);
124
+ }
125
+ return new WebSocket(target.toString());
126
+ }
127
+
128
+ function outageKey(message) {
129
+ return (message && (message.outage_id || message.icao)) || "";
130
+ }
131
+
132
+ export class MetarClient {
133
+ constructor({
134
+ airports,
135
+ token,
136
+ url = DEFAULT_URL,
137
+ snapshot = true,
138
+ resume = true,
139
+ state = null,
140
+ bbox = null,
141
+ platform = null,
142
+ onRecord = null,
143
+ onFrame = null,
144
+ } = {}) {
145
+ this.url = url;
146
+ this.token = resolveToken(token);
147
+ this.airports = (airports || []).map((name) => String(name).toUpperCase());
148
+ this.snapshot = snapshot;
149
+ this.resume = resume;
150
+ this.onRecord = onRecord;
151
+ this.onFrame = onFrame;
152
+ this.latest = {};
153
+ this.bootId = null;
154
+ this.seq = null;
155
+ this._delay = BACKOFF_START_MS;
156
+ this._stopped = false;
157
+ this._ws = null;
158
+ this._sessionDone = null;
159
+ this.lastUsage = null;
160
+ this.lastLate = null;
161
+ this.lastRecovered = null;
162
+ this.lates = {};
163
+ this.lastError = null;
164
+ this.heldIcaos = this.airports.slice();
165
+ this.states = [];
166
+ this.bboxes = [];
167
+ this.platforms = [];
168
+ this._sessionOpen = false;
169
+ this._grantResumePending = false;
170
+ if (state) this.states.push(String(state).toUpperCase());
171
+ if (bbox) this.bboxes.push(Object.assign({}, bbox));
172
+ if (platform) this.platforms.push(String(platform).toLowerCase());
173
+ }
174
+
175
+ handshakeUrl() {
176
+ const useResume = this.resume && !this.hasGrants();
177
+ return handshakeUrl(this.url, this.airports, {
178
+ snapshot: this.hasGrants() ? false : this.snapshot,
179
+ sinceSeq: useResume ? this.seq : null,
180
+ bootId: useResume ? this.bootId : null,
181
+ });
182
+ }
183
+
184
+ hasGrants() {
185
+ return this.states.length > 0 || this.bboxes.length > 0 || this.platforms.length > 0;
186
+ }
187
+
188
+ handleFrame(message) {
189
+ const kind = message && message.type;
190
+ if (kind === "subscription_updated") {
191
+ if (message.boot_id) this.bootId = message.boot_id;
192
+ if (Array.isArray(message.icaos)) {
193
+ this.heldIcaos = message.icaos.map((item) => String(item).toUpperCase());
194
+ }
195
+ if (this._sessionOpen) this._rememberGrantsFrom(message);
196
+ else if (this.hasGrants()) this._grantResumePending = true;
197
+ this._sessionOpen = true;
198
+ // Do not take seq from subscription_updated: it is the server's
199
+ // current seq, and would skip replay frames not yet received.
200
+ } else if (kind === "error") {
201
+ this.lastError = message;
202
+ } else if (kind === "resume") {
203
+ return fetchLatest(this.url, this.token, this.heldIcaos.length ? this.heldIcaos : this.airports).then((rows) => {
204
+ for (const rec of rows) {
205
+ const before = this.latest[rec.icao];
206
+ mergeRecord(this.latest, rec, false);
207
+ this._emit(rec.icao, before);
208
+ }
209
+ if (this.onFrame) this.onFrame(message);
210
+ });
211
+ } else if (kind === "new_metar_arrived") {
212
+ const live = message.cached === false && message.replay === false;
213
+ const replayed = message.replay === true;
214
+ for (const rec of message.data || []) {
215
+ const before = this.latest[rec.icao];
216
+ mergeRecord(this.latest, rec, live);
217
+ this._emit(rec.icao, before);
218
+ }
219
+ if ((live || replayed) && message.seq != null) this._advanceSeq(message.seq);
220
+ } else if (kind === "awc_confirmed") {
221
+ if (message.seq != null) this._advanceSeq(message.seq);
222
+ const before = message.icao && this.latest[message.icao]
223
+ ? Object.assign({}, this.latest[message.icao])
224
+ : null;
225
+ applyAwcConfirmed(this.latest, message);
226
+ this._emit(message.icao, before);
227
+ } else if (kind === "station_late" || kind === "station_recovered" || kind === "usage") {
228
+ if (message.seq != null) this._advanceSeq(message.seq);
229
+ if (kind === "usage") this.lastUsage = message;
230
+ else if (kind === "station_late") {
231
+ this.lastLate = message;
232
+ this.lates[outageKey(message)] = message;
233
+ } else {
234
+ this.lastRecovered = message;
235
+ const key = outageKey(message);
236
+ delete this.lates[key];
237
+ if (this.lastLate && outageKey(this.lastLate) === key) this.lastLate = null;
238
+ }
239
+ }
240
+ if (this.onFrame) this.onFrame(message);
241
+ }
242
+
243
+ _advanceSeq(seq) {
244
+ if (this.seq == null || seq > this.seq) this.seq = seq;
245
+ }
246
+
247
+ _emit(icao, before) {
248
+ if (!icao || !this.onRecord) return;
249
+ const held = this.latest[icao];
250
+ if (held && held !== before && JSON.stringify(held) !== JSON.stringify(before)) {
251
+ this.onRecord(held);
252
+ }
253
+ }
254
+
255
+ requestUsage() {
256
+ const ws = this._ws;
257
+ if (ws && ws.readyState === 1) {
258
+ ws.send(JSON.stringify({action: "usage"}));
259
+ }
260
+ }
261
+
262
+ subscribeBody(icaos, fields = {}) {
263
+ const body = {action: "subscribe"};
264
+ if (icaos != null) body.icaos = icaos.map((item) => String(item).toUpperCase());
265
+ if (fields.state != null) body.state = String(fields.state).toUpperCase();
266
+ if (fields.bbox != null) body.bbox = Object.assign({}, fields.bbox);
267
+ if (fields.platform != null) body.platform = String(fields.platform).toLowerCase();
268
+ if (fields.since_seq != null && fields.boot_id) {
269
+ body.since_seq = fields.since_seq;
270
+ body.boot_id = fields.boot_id;
271
+ }
272
+ if (fields.snapshot != null) body.snapshot = Boolean(fields.snapshot);
273
+ for (const [key, value] of Object.entries(fields)) {
274
+ if (!["state", "bbox", "platform", "since_seq", "boot_id", "snapshot"].includes(key)) {
275
+ body[key] = value;
276
+ }
277
+ }
278
+ return body;
279
+ }
280
+
281
+ reconnectSubscribeBodies() {
282
+ const states = this.states.slice();
283
+ const bboxes = this.bboxes.slice();
284
+ const platforms = this.platforms.slice();
285
+ const first = this.subscribeBody(this.airports.length ? this.airports : null, {
286
+ state: states.length ? states.shift() : null,
287
+ bbox: bboxes.length ? bboxes.shift() : null,
288
+ platform: platforms.length ? platforms.shift() : null,
289
+ since_seq: this.resume ? this.seq : null,
290
+ boot_id: this.resume ? this.bootId : null,
291
+ snapshot: this.snapshot ? true : null,
292
+ });
293
+ const bodies = [first];
294
+ while (states.length || bboxes.length || platforms.length) {
295
+ bodies.push(this.subscribeBody(null, {
296
+ state: states.length ? states.shift() : null,
297
+ bbox: bboxes.length ? bboxes.shift() : null,
298
+ platform: platforms.length ? platforms.shift() : null,
299
+ snapshot: true,
300
+ }));
301
+ }
302
+ return bodies;
303
+ }
304
+
305
+ _rememberGrantsFrom(message) {
306
+ const regions = message.regions || [];
307
+ const platforms = message.platforms || [];
308
+ const states = [];
309
+ const bboxes = [];
310
+ for (const item of regions) {
311
+ const raw = String(item);
312
+ if (raw.toLowerCase().startsWith("state:")) states.push(raw.split(":").slice(1).join(":").toUpperCase());
313
+ else if (raw.toLowerCase().startsWith("bbox:")) {
314
+ const parts = raw.split(":").slice(1).join(":").split(",");
315
+ if (parts.length === 4) {
316
+ const nums = parts.map(Number);
317
+ if (nums.every((n) => Number.isFinite(n))) {
318
+ bboxes.push({south: nums[0], west: nums[1], north: nums[2], east: nums[3]});
319
+ }
320
+ }
321
+ }
322
+ }
323
+ this.states = states;
324
+ this.bboxes = bboxes;
325
+ this.platforms = platforms.map((name) => String(name).toLowerCase());
326
+ }
327
+
328
+ _rememberOutgoingGrants(body) {
329
+ if (body.state && !this.states.includes(body.state)) this.states.push(body.state);
330
+ if (body.bbox) this.bboxes.push(Object.assign({}, body.bbox));
331
+ if (body.platform && !this.platforms.includes(body.platform)) this.platforms.push(body.platform);
332
+ if (Array.isArray(body.icaos)) {
333
+ for (const item of body.icaos) {
334
+ const code = String(item).toUpperCase();
335
+ if (!this.airports.includes(code)) this.airports.push(code);
336
+ }
337
+ }
338
+ }
339
+
340
+ subscribe(icaos = [], fields = {}) {
341
+ const ws = this._ws;
342
+ if (!ws || ws.readyState !== 1) return;
343
+ const body = this.subscribeBody(icaos, fields);
344
+ this._rememberOutgoingGrants(body);
345
+ ws.send(JSON.stringify(body));
346
+ }
347
+
348
+ unsubscribe(icaos = null, fields = {}) {
349
+ const ws = this._ws;
350
+ if (!ws || ws.readyState !== 1) return;
351
+ const body = {action: "unsubscribe"};
352
+ if (icaos != null) body.icaos = icaos.map((item) => String(item).toUpperCase());
353
+ if (fields.state != null) body.state = String(fields.state).toUpperCase();
354
+ if (fields.bbox != null) body.bbox = Object.assign({}, fields.bbox);
355
+ if (fields.platform != null) body.platform = String(fields.platform).toLowerCase();
356
+ for (const [key, value] of Object.entries(fields)) {
357
+ if (!["state", "bbox", "platform"].includes(key)) body[key] = value;
358
+ }
359
+ ws.send(JSON.stringify(body));
360
+ }
361
+
362
+ _flushGrantResume() {
363
+ const ws = this._ws;
364
+ if (!this._grantResumePending || !ws || ws.readyState !== 1) return;
365
+ this._grantResumePending = false;
366
+ for (const body of this.reconnectSubscribeBodies()) {
367
+ ws.send(JSON.stringify(body));
368
+ }
369
+ }
370
+
371
+ stop() {
372
+ this._stopped = true;
373
+ if (this._stopTimer) this._stopTimer();
374
+ const ws = this._ws;
375
+ if (ws && (ws.readyState === 0 || ws.readyState === 1)) {
376
+ ws.close(1000, "client stop");
377
+ }
378
+ }
379
+
380
+ _session() {
381
+ return new Promise((resolve) => {
382
+ if (this._stopped) {
383
+ resolve(null);
384
+ return;
385
+ }
386
+ let openedAt = null;
387
+ let sawMessage = false;
388
+ let pingTimer = null;
389
+ let pongTimer = null;
390
+ let settled = false;
391
+ const finish = (code) => {
392
+ if (settled) return;
393
+ settled = true;
394
+ if (pingTimer) clearInterval(pingTimer);
395
+ if (pongTimer) clearTimeout(pongTimer);
396
+ this._ws = null;
397
+ if (sawMessage || (openedAt != null && Date.now() - openedAt >= QUIET_OPEN_MS)) {
398
+ this._delay = BACKOFF_START_MS;
399
+ }
400
+ resolve(code == null ? null : code);
401
+ };
402
+
403
+ let ws;
404
+ try {
405
+ ws = openWebSocket(this.handshakeUrl(), this.token);
406
+ } catch (err) {
407
+ finish(1006);
408
+ return;
409
+ }
410
+ this._ws = ws;
411
+ this._sessionOpen = false;
412
+ this._grantResumePending = false;
413
+
414
+ ws.addEventListener("open", () => {
415
+ openedAt = Date.now();
416
+ pingTimer = setInterval(() => {
417
+ if (ws.readyState !== 1) return;
418
+ ws.send(JSON.stringify({action: "ping"}));
419
+ if (pongTimer) clearTimeout(pongTimer);
420
+ pongTimer = setTimeout(() => {
421
+ try { ws.close(1001, "pong timeout"); } catch {}
422
+ }, PONG_TIMEOUT_MS);
423
+ }, PING_EVERY_MS);
424
+ });
425
+
426
+ ws.addEventListener("message", (event) => {
427
+ if (!sawMessage) {
428
+ sawMessage = true;
429
+ this._delay = BACKOFF_START_MS;
430
+ }
431
+ let message;
432
+ try {
433
+ message = JSON.parse(event.data);
434
+ } catch {
435
+ return;
436
+ }
437
+ if (message.type === "pong" && pongTimer) {
438
+ clearTimeout(pongTimer);
439
+ pongTimer = null;
440
+ }
441
+ const result = this.handleFrame(message);
442
+ if (result && typeof result.then === "function") result.then(() => this._flushGrantResume());
443
+ else this._flushGrantResume();
444
+ });
445
+
446
+ ws.addEventListener("close", (event) => {
447
+ finish(event && event.code != null ? event.code : 1006);
448
+ });
449
+
450
+ ws.addEventListener("error", () => {
451
+ // close follows; finish there so the code is accurate
452
+ });
453
+ });
454
+ }
455
+
456
+ async runForever() {
457
+ this._stopped = false;
458
+ while (!this._stopped) {
459
+ const code = await this._session();
460
+ if (this._stopped) return;
461
+ if (!shouldRetry(code)) return;
462
+ const wait = this._delay * (0.5 + Math.random());
463
+ this._delay = Math.min(this._delay * 2, BACKOFF_CAP_MS);
464
+ await new Promise((resolve) => {
465
+ const timer = setTimeout(resolve, wait);
466
+ this._stopTimer = () => {
467
+ clearTimeout(timer);
468
+ resolve();
469
+ };
470
+ });
471
+ this._stopTimer = null;
472
+ }
473
+ }
474
+ }
475
+
476
+ export { MetarClient as MetarExample };