@aeroswarm/client 0.0.0-stage → 0.1.11
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.
- package/README.md +473 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +683 -0
- package/dist/index.js.map +1 -0
- package/dist/react/index.d.ts +148 -0
- package/dist/react/index.js +1171 -0
- package/dist/react/index.js.map +1 -0
- package/dist/sdk/index.d.ts +582 -0
- package/dist/sdk/index.js +675 -0
- package/dist/sdk/index.js.map +1 -0
- package/package.json +60 -4
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
// src/sdk/websocket/index.ts
|
|
2
|
+
import { streamEnvelopeSchema, currentTrackSchema } from "@aeroswarm/core/validation";
|
|
3
|
+
var AeroWsClient = class {
|
|
4
|
+
constructor(url, token, maxReconnectDelay = 3e4, heartbeatTimeoutMs = 35e3) {
|
|
5
|
+
this.url = url;
|
|
6
|
+
this.token = token;
|
|
7
|
+
this.maxReconnectDelay = maxReconnectDelay;
|
|
8
|
+
this.heartbeatTimeoutMs = heartbeatTimeoutMs;
|
|
9
|
+
}
|
|
10
|
+
url;
|
|
11
|
+
token;
|
|
12
|
+
maxReconnectDelay;
|
|
13
|
+
heartbeatTimeoutMs;
|
|
14
|
+
ws = null;
|
|
15
|
+
attempt = 0;
|
|
16
|
+
stopped = false;
|
|
17
|
+
lastSubscribe = null;
|
|
18
|
+
callbacks = {};
|
|
19
|
+
lastSeq = -1;
|
|
20
|
+
lastHeartbeat = Date.now();
|
|
21
|
+
heartbeatTimer = null;
|
|
22
|
+
status = "idle";
|
|
23
|
+
connect(opts, callbacks) {
|
|
24
|
+
this.lastSubscribe = opts;
|
|
25
|
+
this.callbacks = callbacks;
|
|
26
|
+
this.stopped = false;
|
|
27
|
+
this._setStatus("connecting");
|
|
28
|
+
this._connect();
|
|
29
|
+
}
|
|
30
|
+
updateFilter(opts) {
|
|
31
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
32
|
+
this.ws.send(JSON.stringify({ type: "update-filter", ...opts }));
|
|
33
|
+
}
|
|
34
|
+
disconnect() {
|
|
35
|
+
this.stopped = true;
|
|
36
|
+
this._clearHeartbeatTimer();
|
|
37
|
+
this.ws?.close();
|
|
38
|
+
this.ws = null;
|
|
39
|
+
this._setStatus("offline");
|
|
40
|
+
}
|
|
41
|
+
getStatus() {
|
|
42
|
+
return this.status;
|
|
43
|
+
}
|
|
44
|
+
_setStatus(s) {
|
|
45
|
+
if (this.status === s) return;
|
|
46
|
+
this.status = s;
|
|
47
|
+
this.callbacks.onStatusChange?.(s);
|
|
48
|
+
}
|
|
49
|
+
_connect() {
|
|
50
|
+
const wsUrl = `${this.url}?token=${encodeURIComponent(this.token)}`;
|
|
51
|
+
try {
|
|
52
|
+
this.ws = new WebSocket(wsUrl);
|
|
53
|
+
this.ws.binaryType = "arraybuffer";
|
|
54
|
+
} catch {
|
|
55
|
+
this._scheduleReconnect();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
this.ws.onopen = () => {
|
|
59
|
+
this.attempt = 0;
|
|
60
|
+
this.lastSeq = -1;
|
|
61
|
+
this._setStatus("connected");
|
|
62
|
+
this._resetHeartbeatTimer();
|
|
63
|
+
if (this.lastSubscribe) {
|
|
64
|
+
this.ws.send(JSON.stringify({
|
|
65
|
+
type: "subscribe",
|
|
66
|
+
encoding: "json",
|
|
67
|
+
...this.lastSubscribe
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
this.ws.onmessage = (event) => {
|
|
72
|
+
this._handleRaw(event.data);
|
|
73
|
+
};
|
|
74
|
+
this.ws.onclose = () => {
|
|
75
|
+
this._clearHeartbeatTimer();
|
|
76
|
+
if (!this.stopped) {
|
|
77
|
+
this._setStatus("reconnecting");
|
|
78
|
+
this._scheduleReconnect();
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
this.ws.onerror = () => {
|
|
82
|
+
this.callbacks.onError?.({
|
|
83
|
+
code: "WS_ERROR",
|
|
84
|
+
message: "WebSocket connection error",
|
|
85
|
+
recoverable: true
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
_handleRaw(raw) {
|
|
90
|
+
this._resetHeartbeatTimer();
|
|
91
|
+
let parsed;
|
|
92
|
+
try {
|
|
93
|
+
const text = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
|
|
94
|
+
parsed = JSON.parse(text);
|
|
95
|
+
} catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
let msg;
|
|
99
|
+
const result = streamEnvelopeSchema.safeParse(parsed);
|
|
100
|
+
if (!result.success) {
|
|
101
|
+
const raw2 = parsed;
|
|
102
|
+
if (raw2["type"] === "snapshot" && Array.isArray(raw2["payload"]?.["tracks"])) {
|
|
103
|
+
const rawTracks = raw2["payload"]["tracks"];
|
|
104
|
+
const goodTracks = rawTracks.map((t) => currentTrackSchema.safeParse(t)).filter((r) => r.success).map((r) => r.data);
|
|
105
|
+
if (goodTracks.length > 0) this.callbacks.onSnapshot?.(goodTracks);
|
|
106
|
+
}
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
msg = result.data;
|
|
110
|
+
if (msg.seq <= this.lastSeq && this.lastSeq > 0) return;
|
|
111
|
+
if (msg.seq > this.lastSeq + 10 && this.lastSeq > 0) {
|
|
112
|
+
this._requestSnapshot();
|
|
113
|
+
}
|
|
114
|
+
this.lastSeq = msg.seq;
|
|
115
|
+
switch (msg.type) {
|
|
116
|
+
case "snapshot":
|
|
117
|
+
this.callbacks.onSnapshot?.(msg.payload.tracks);
|
|
118
|
+
break;
|
|
119
|
+
case "track.updated":
|
|
120
|
+
this.callbacks.onTrackUpdate?.(msg.payload.track);
|
|
121
|
+
break;
|
|
122
|
+
case "track.removed":
|
|
123
|
+
this.callbacks.onTrackRemoved?.(msg.payload);
|
|
124
|
+
break;
|
|
125
|
+
case "source.status":
|
|
126
|
+
this.callbacks.onSourceStatus?.(msg.payload);
|
|
127
|
+
break;
|
|
128
|
+
case "stream.heartbeat":
|
|
129
|
+
this.lastHeartbeat = Date.now();
|
|
130
|
+
break;
|
|
131
|
+
case "stream.degraded":
|
|
132
|
+
this._setStatus("degraded");
|
|
133
|
+
this.callbacks.onDegraded?.(msg.payload.reason);
|
|
134
|
+
break;
|
|
135
|
+
case "stream.error":
|
|
136
|
+
this.callbacks.onError?.({
|
|
137
|
+
code: msg.payload.code,
|
|
138
|
+
message: msg.payload.message ?? msg.payload.code,
|
|
139
|
+
recoverable: msg.payload.recoverable
|
|
140
|
+
});
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
_requestSnapshot() {
|
|
145
|
+
if (!this.lastSubscribe || !this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
146
|
+
this.ws.send(JSON.stringify({ type: "subscribe", ...this.lastSubscribe }));
|
|
147
|
+
}
|
|
148
|
+
_resetHeartbeatTimer() {
|
|
149
|
+
this._clearHeartbeatTimer();
|
|
150
|
+
this.heartbeatTimer = setInterval(() => {
|
|
151
|
+
if (Date.now() - this.lastHeartbeat > this.heartbeatTimeoutMs) {
|
|
152
|
+
this._setStatus("degraded");
|
|
153
|
+
this.callbacks.onDegraded?.("heartbeat_timeout");
|
|
154
|
+
}
|
|
155
|
+
}, this.heartbeatTimeoutMs / 2);
|
|
156
|
+
}
|
|
157
|
+
_clearHeartbeatTimer() {
|
|
158
|
+
if (this.heartbeatTimer) {
|
|
159
|
+
clearInterval(this.heartbeatTimer);
|
|
160
|
+
this.heartbeatTimer = null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
_scheduleReconnect() {
|
|
164
|
+
const delay = Math.min(1e3 * 2 ** this.attempt, this.maxReconnectDelay);
|
|
165
|
+
this.attempt++;
|
|
166
|
+
setTimeout(() => {
|
|
167
|
+
if (!this.stopped) this._connect();
|
|
168
|
+
}, delay);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// src/sdk/websocket/replay.ts
|
|
173
|
+
var toIso = (v) => v instanceof Date ? v.toISOString() : v;
|
|
174
|
+
var AeroReplayClient = class {
|
|
175
|
+
constructor(wsBase, token, wsPath = "/ws/tracks/replay") {
|
|
176
|
+
this.wsBase = wsBase;
|
|
177
|
+
this.token = token;
|
|
178
|
+
this.wsPath = wsPath;
|
|
179
|
+
}
|
|
180
|
+
wsBase;
|
|
181
|
+
token;
|
|
182
|
+
wsPath;
|
|
183
|
+
/** Open a replay stream. Returns a handle for transport control. */
|
|
184
|
+
stream(opts, callbacks) {
|
|
185
|
+
const params = new URLSearchParams({ token: this.token });
|
|
186
|
+
if (opts.airportId) params.set("airportId", opts.airportId);
|
|
187
|
+
if (opts.sessionId) params.set("sessionId", opts.sessionId);
|
|
188
|
+
const ws = new WebSocket(`${this.wsBase}${this.wsPath}?${params.toString()}`);
|
|
189
|
+
let sessionId = opts.sessionId ?? null;
|
|
190
|
+
let closedByUser = false;
|
|
191
|
+
ws.onopen = () => {
|
|
192
|
+
if (!opts.sessionId) {
|
|
193
|
+
ws.send(JSON.stringify({
|
|
194
|
+
type: "replay.start",
|
|
195
|
+
from: toIso(opts.from),
|
|
196
|
+
to: toIso(opts.to),
|
|
197
|
+
speed: opts.speed ?? 1
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
ws.onmessage = (ev) => {
|
|
202
|
+
let msg;
|
|
203
|
+
try {
|
|
204
|
+
msg = JSON.parse(String(ev.data));
|
|
205
|
+
} catch {
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const payload = msg.payload ?? {};
|
|
209
|
+
switch (msg.type) {
|
|
210
|
+
case "snapshot": {
|
|
211
|
+
if (typeof payload["sessionId"] === "string") sessionId = payload["sessionId"];
|
|
212
|
+
callbacks.onSnapshot?.(payload["tracks"] ?? [], sessionId ?? "");
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
case "track.updated":
|
|
216
|
+
callbacks.onTrackUpdate?.(payload["track"]);
|
|
217
|
+
break;
|
|
218
|
+
case "track.removed":
|
|
219
|
+
callbacks.onTrackRemoved?.({
|
|
220
|
+
trackId: String(payload["trackId"] ?? ""),
|
|
221
|
+
reason: String(payload["reason"] ?? "")
|
|
222
|
+
});
|
|
223
|
+
break;
|
|
224
|
+
case "replay.progress": {
|
|
225
|
+
const progress = payload;
|
|
226
|
+
sessionId = progress.sessionId ?? sessionId;
|
|
227
|
+
callbacks.onProgress?.(progress);
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
case "replay.done":
|
|
231
|
+
callbacks.onDone?.(String(payload["sessionId"] ?? sessionId ?? ""));
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
ws.onerror = () => {
|
|
236
|
+
if (!closedByUser) callbacks.onError?.(new Error("replay websocket error"));
|
|
237
|
+
};
|
|
238
|
+
ws.onclose = (ev) => {
|
|
239
|
+
if (!closedByUser && ev.code >= 4e3) {
|
|
240
|
+
callbacks.onError?.(new Error(`replay websocket closed: ${ev.reason || ev.code}`));
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const send = (body) => {
|
|
244
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(body));
|
|
245
|
+
};
|
|
246
|
+
return {
|
|
247
|
+
get sessionId() {
|
|
248
|
+
return sessionId;
|
|
249
|
+
},
|
|
250
|
+
pause: () => send({ type: "replay.pause" }),
|
|
251
|
+
resume: () => send({ type: "replay.resume" }),
|
|
252
|
+
seek: (at) => send({ type: "replay.seek", at: toIso(at) }),
|
|
253
|
+
stop: () => {
|
|
254
|
+
closedByUser = true;
|
|
255
|
+
send({ type: "replay.stop" });
|
|
256
|
+
try {
|
|
257
|
+
ws.close();
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// src/sdk/api/trpc.ts
|
|
266
|
+
import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
|
|
267
|
+
function createAeroTrpcClient(endpoint, token) {
|
|
268
|
+
const base = endpoint.replace(/\/$/, "");
|
|
269
|
+
return createTRPCProxyClient({
|
|
270
|
+
links: [
|
|
271
|
+
httpBatchLink({
|
|
272
|
+
url: `${base}/trpc`,
|
|
273
|
+
headers: () => ({ "x-aero-token": token }),
|
|
274
|
+
methodOverride: "POST"
|
|
275
|
+
})
|
|
276
|
+
]
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/sdk/api/rest.ts
|
|
281
|
+
var AeroRestClient = class {
|
|
282
|
+
constructor(endpoint, token) {
|
|
283
|
+
this.endpoint = endpoint;
|
|
284
|
+
this.token = token;
|
|
285
|
+
}
|
|
286
|
+
endpoint;
|
|
287
|
+
token;
|
|
288
|
+
async req(method, path, body) {
|
|
289
|
+
const res = await fetch(`${this.endpoint}${path}`, {
|
|
290
|
+
method,
|
|
291
|
+
headers: {
|
|
292
|
+
"Content-Type": "application/json",
|
|
293
|
+
"x-aero-token": this.token
|
|
294
|
+
},
|
|
295
|
+
body: body ? JSON.stringify(body) : void 0
|
|
296
|
+
});
|
|
297
|
+
if (!res.ok) throw new Error(`${method} ${path} \u2192 ${res.status}`);
|
|
298
|
+
return res.json();
|
|
299
|
+
}
|
|
300
|
+
createSource(body) {
|
|
301
|
+
return this.req("POST", "/v1/sources", body);
|
|
302
|
+
}
|
|
303
|
+
listSources() {
|
|
304
|
+
return this.req("GET", "/v1/sources");
|
|
305
|
+
}
|
|
306
|
+
deleteSource(id) {
|
|
307
|
+
return this.req("DELETE", `/v1/sources/${id}`);
|
|
308
|
+
}
|
|
309
|
+
createWebhook(body) {
|
|
310
|
+
return this.req("POST", "/v1/webhooks", body);
|
|
311
|
+
}
|
|
312
|
+
getTracksCurrent(params) {
|
|
313
|
+
const search = new URLSearchParams();
|
|
314
|
+
if (params?.bbox) search.set("bbox", params.bbox.join(","));
|
|
315
|
+
if (params?.minConfidence != null) search.set("minConfidence", String(params.minConfidence));
|
|
316
|
+
const qs = search.size ? `?${search.toString()}` : "";
|
|
317
|
+
return this.req("GET", `/v1/tracks/current${qs}`);
|
|
318
|
+
}
|
|
319
|
+
health() {
|
|
320
|
+
return this.req("GET", "/health");
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// src/sdk/api/graphql.ts
|
|
325
|
+
var AeroGraphQLClient = class {
|
|
326
|
+
constructor(endpoint, token) {
|
|
327
|
+
this.endpoint = endpoint;
|
|
328
|
+
this.token = token;
|
|
329
|
+
}
|
|
330
|
+
endpoint;
|
|
331
|
+
token;
|
|
332
|
+
async query(query, variables) {
|
|
333
|
+
const res = await fetch(`${this.endpoint}/graphql`, {
|
|
334
|
+
method: "POST",
|
|
335
|
+
headers: {
|
|
336
|
+
"Content-Type": "application/json",
|
|
337
|
+
"x-aero-token": this.token
|
|
338
|
+
},
|
|
339
|
+
body: JSON.stringify({ query, variables })
|
|
340
|
+
});
|
|
341
|
+
if (!res.ok) throw new Error(`GraphQL ${res.status}: ${await res.text().catch(() => "")}`);
|
|
342
|
+
const json = await res.json();
|
|
343
|
+
if (json.errors?.length) throw new Error(JSON.stringify(json.errors));
|
|
344
|
+
return json.data;
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
// src/sdk/cache/index.ts
|
|
349
|
+
import { isRenderableTrack } from "@aeroswarm/core/utils";
|
|
350
|
+
var TypedEmitter = class {
|
|
351
|
+
listeners = /* @__PURE__ */ new Map();
|
|
352
|
+
on(event, fn) {
|
|
353
|
+
if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
354
|
+
this.listeners.get(event).add(fn);
|
|
355
|
+
return () => this.listeners.get(event)?.delete(fn);
|
|
356
|
+
}
|
|
357
|
+
emit(event, payload) {
|
|
358
|
+
this.listeners.get(event)?.forEach((fn) => fn(payload));
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
var TrackCache = class extends TypedEmitter {
|
|
362
|
+
tracks = /* @__PURE__ */ new Map();
|
|
363
|
+
applyUpdate(track) {
|
|
364
|
+
if (track.status === "lost") {
|
|
365
|
+
this.tracks.delete(track.trackId);
|
|
366
|
+
this.emit("removed", { trackId: track.trackId });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const merged = { ...this.tracks.get(track.trackId), ...track };
|
|
370
|
+
this.tracks.set(track.trackId, merged);
|
|
371
|
+
this.emit("update", merged);
|
|
372
|
+
}
|
|
373
|
+
applyRemoved(ev) {
|
|
374
|
+
this.tracks.delete(ev.trackId);
|
|
375
|
+
this.emit("removed", ev);
|
|
376
|
+
}
|
|
377
|
+
applySnapshot(tracks) {
|
|
378
|
+
this.tracks.clear();
|
|
379
|
+
for (const t of tracks) {
|
|
380
|
+
if (isRenderableTrack(t)) this.tracks.set(t.trackId, t);
|
|
381
|
+
}
|
|
382
|
+
this.emit("snapshot", Array.from(this.tracks.values()));
|
|
383
|
+
}
|
|
384
|
+
getAll() {
|
|
385
|
+
return Array.from(this.tracks.values());
|
|
386
|
+
}
|
|
387
|
+
get(id) {
|
|
388
|
+
return this.tracks.get(id);
|
|
389
|
+
}
|
|
390
|
+
get size() {
|
|
391
|
+
return this.tracks.size;
|
|
392
|
+
}
|
|
393
|
+
clear() {
|
|
394
|
+
this.tracks.clear();
|
|
395
|
+
}
|
|
396
|
+
getRenderable() {
|
|
397
|
+
return this.getAll().filter(isRenderableTrack);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
// src/sdk/index.ts
|
|
402
|
+
var AeroSwarm = class _AeroSwarm {
|
|
403
|
+
constructor(opts) {
|
|
404
|
+
this.opts = opts;
|
|
405
|
+
this.trpc = createAeroTrpcClient(opts.endpoint, opts.token);
|
|
406
|
+
this.rest = new AeroRestClient(opts.endpoint, opts.token);
|
|
407
|
+
this.graphql = new AeroGraphQLClient(opts.endpoint, opts.token);
|
|
408
|
+
this.cache = new TrackCache();
|
|
409
|
+
const wsBase = (opts.wsEndpoint ?? opts.endpoint).replace(/^http/, "ws");
|
|
410
|
+
this.wsClient = new AeroWsClient(
|
|
411
|
+
`${wsBase}/ws/tracks/live`,
|
|
412
|
+
opts.token,
|
|
413
|
+
opts.maxReconnectDelay ?? 3e4
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
opts;
|
|
417
|
+
trpc;
|
|
418
|
+
rest;
|
|
419
|
+
graphql;
|
|
420
|
+
cache;
|
|
421
|
+
wsClient;
|
|
422
|
+
_status = "idle";
|
|
423
|
+
_lastUpdateAt = null;
|
|
424
|
+
_error = null;
|
|
425
|
+
_sourceStatus = {};
|
|
426
|
+
// ── Federated history resolution ──────────────────────────────────────
|
|
427
|
+
// An airport can serve its own replay/history through a backend mounting
|
|
428
|
+
// @aeroswarm/replay-server instead of AeroSwarm's own (see
|
|
429
|
+
// docs/development/federation/). `airports.list()`'s `historyEndpoint`
|
|
430
|
+
// field drives this automatically; every federatable call also accepts
|
|
431
|
+
// an explicit `endpoint` to bypass the registry entirely ("connect
|
|
432
|
+
// manual"). Priority: explicit endpoint > registry > AeroSwarm itself.
|
|
433
|
+
airportsCache = null;
|
|
434
|
+
static AIRPORTS_CACHE_TTL_MS = 6e4;
|
|
435
|
+
/** Resolves which base URL (if any) should serve a federated call.
|
|
436
|
+
* Returns null to mean "use AeroSwarm's own endpoint" — the normal,
|
|
437
|
+
* unfederated path, which is also what a lookup failure falls back to
|
|
438
|
+
* (a broken airports.list() call must never brick replay/history for
|
|
439
|
+
* everyone else). */
|
|
440
|
+
async resolveHistoryEndpoint(airportId, override) {
|
|
441
|
+
if (override) return override.replace(/\/$/, "");
|
|
442
|
+
if (!airportId) return null;
|
|
443
|
+
try {
|
|
444
|
+
const now = Date.now();
|
|
445
|
+
if (!this.airportsCache || now - this.airportsCache.fetchedAt > _AeroSwarm.AIRPORTS_CACHE_TTL_MS) {
|
|
446
|
+
const { airports } = await this.airports.list();
|
|
447
|
+
this.airportsCache = {
|
|
448
|
+
byId: new Map(airports.map((a) => [a.id, a.historyEndpoint])),
|
|
449
|
+
fetchedAt: now
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
const endpoint = this.airportsCache.byId.get(airportId) ?? null;
|
|
453
|
+
return endpoint ? endpoint.replace(/\/$/, "") : null;
|
|
454
|
+
} catch {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
async federatedFetch(base, path, query) {
|
|
459
|
+
const url = new URL(`${base}${path}`);
|
|
460
|
+
for (const [k, v] of Object.entries(query ?? {})) if (v !== void 0) url.searchParams.set(k, v);
|
|
461
|
+
const res = await fetch(url, { headers: { Authorization: `Bearer ${this.opts.token}` } });
|
|
462
|
+
if (!res.ok) throw new Error(`Federated request failed: ${res.status} ${res.statusText} (${url.pathname})`);
|
|
463
|
+
return res.json();
|
|
464
|
+
}
|
|
465
|
+
tracks = {
|
|
466
|
+
subscribe: (opts, callbacks) => {
|
|
467
|
+
this.wsClient.connect(
|
|
468
|
+
{ encoding: this.opts.encoding ?? "json", ...opts },
|
|
469
|
+
{
|
|
470
|
+
...callbacks,
|
|
471
|
+
onStatusChange: (s) => {
|
|
472
|
+
this._status = s;
|
|
473
|
+
callbacks.onStatusChange?.(s);
|
|
474
|
+
},
|
|
475
|
+
onSnapshot: (tracks) => {
|
|
476
|
+
this.cache.applySnapshot(tracks);
|
|
477
|
+
this._lastUpdateAt = Date.now();
|
|
478
|
+
callbacks.onSnapshot?.(tracks);
|
|
479
|
+
},
|
|
480
|
+
onTrackUpdate: (track) => {
|
|
481
|
+
this.cache.applyUpdate(track);
|
|
482
|
+
this._lastUpdateAt = Date.now();
|
|
483
|
+
callbacks.onTrackUpdate?.(track);
|
|
484
|
+
},
|
|
485
|
+
onTrackRemoved: (ev) => {
|
|
486
|
+
this.cache.applyRemoved(ev);
|
|
487
|
+
callbacks.onTrackRemoved?.(ev);
|
|
488
|
+
},
|
|
489
|
+
onSourceStatus: (ev) => {
|
|
490
|
+
this._sourceStatus[ev.sourceId] = ev.status;
|
|
491
|
+
callbacks.onSourceStatus?.(ev);
|
|
492
|
+
},
|
|
493
|
+
onError: (err) => {
|
|
494
|
+
this._error = err;
|
|
495
|
+
callbacks.onError?.(err);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
);
|
|
499
|
+
return () => this.wsClient.disconnect();
|
|
500
|
+
},
|
|
501
|
+
updateFilter: (opts) => this.wsClient.updateFilter(opts),
|
|
502
|
+
stream: (opts) => {
|
|
503
|
+
const queue = [];
|
|
504
|
+
let resolve = null;
|
|
505
|
+
let done = false;
|
|
506
|
+
this.wsClient.connect({ encoding: "json", ...opts }, {
|
|
507
|
+
onTrackUpdate: (t) => {
|
|
508
|
+
if (resolve) {
|
|
509
|
+
resolve({ value: t, done: false });
|
|
510
|
+
resolve = null;
|
|
511
|
+
} else queue.push(t);
|
|
512
|
+
},
|
|
513
|
+
onStatusChange: (s) => {
|
|
514
|
+
if (s === "offline") done = true;
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
return {
|
|
518
|
+
[Symbol.asyncIterator]: () => ({
|
|
519
|
+
next: () => {
|
|
520
|
+
if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
|
|
521
|
+
if (done) return Promise.resolve({ value: void 0, done: true });
|
|
522
|
+
return new Promise((r) => {
|
|
523
|
+
resolve = r;
|
|
524
|
+
});
|
|
525
|
+
},
|
|
526
|
+
return: async () => {
|
|
527
|
+
this.wsClient.disconnect();
|
|
528
|
+
return { value: void 0, done: true };
|
|
529
|
+
}
|
|
530
|
+
})
|
|
531
|
+
};
|
|
532
|
+
},
|
|
533
|
+
snapshot: (input) => this.trpc.tracks.snapshot.query(input ?? {}),
|
|
534
|
+
/** Persisted position history for one track. If the airport has a
|
|
535
|
+
* `historyEndpoint` (or `endpoint` is passed explicitly), this calls
|
|
536
|
+
* that backend's `@aeroswarm/replay-server` instead of AeroSwarm's
|
|
537
|
+
* own local database — see docs/development/federation/003-*.md. */
|
|
538
|
+
history: async (input) => {
|
|
539
|
+
const base = await this.resolveHistoryEndpoint(input.airportId, input.endpoint);
|
|
540
|
+
if (base) {
|
|
541
|
+
return this.federatedFetch(base, `/tracks/${encodeURIComponent(input.trackId)}/history`, {
|
|
542
|
+
limit: input.limit?.toString()
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
return this.trpc.tracks.history.query(input);
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
sources = {
|
|
549
|
+
/** Registers a source and returns its token, tied to `airportId` — a
|
|
550
|
+
* source is a sensor physically at one airport, so this is required.
|
|
551
|
+
* Anything that later authenticates with the returned token (WS
|
|
552
|
+
* live/replay, tRPC calls) is scoped to that airport automatically,
|
|
553
|
+
* with no need to keep passing `airportId` on every subsequent call.
|
|
554
|
+
* For access spanning multiple airports, use the viewer/dashboard
|
|
555
|
+
* token instead — it's never auto-scoped. */
|
|
556
|
+
create: (body) => this.rest.createSource(body),
|
|
557
|
+
health: (sourceId) => this.trpc.sources.health.query({ sourceId }),
|
|
558
|
+
list: (input) => this.trpc.sources.list.query(input ?? {}),
|
|
559
|
+
/** Reassigning `airportId` (including to `null` to clear it) re-caches
|
|
560
|
+
* the source's token immediately, so the new scoping takes effect
|
|
561
|
+
* without waiting out the token cache's TTL. */
|
|
562
|
+
update: (input) => this.trpc.sources.update.mutate(input),
|
|
563
|
+
delete: (id) => this.trpc.sources.delete.mutate({ id })
|
|
564
|
+
};
|
|
565
|
+
/** Airport registry (multi-airport tenancy). */
|
|
566
|
+
airports = {
|
|
567
|
+
list: () => this.trpc.airports.list.query(),
|
|
568
|
+
create: (input) => this.trpc.airports.create.mutate(input),
|
|
569
|
+
update: (input) => this.trpc.airports.update.mutate(input),
|
|
570
|
+
delete: (input) => this.trpc.airports.delete.mutate(input),
|
|
571
|
+
/** Surface geometry (runway/taxiway/apron GeoJSON) for the map. */
|
|
572
|
+
surface: (input) => this.trpc.airports.surface.query(input),
|
|
573
|
+
setSurface: (input) => this.trpc.airports.setSurface.mutate(input)
|
|
574
|
+
};
|
|
575
|
+
replay = {
|
|
576
|
+
/** Data-availability calendar: which days have recorded tracks.
|
|
577
|
+
* Use this to populate/validate replay date pickers — days not in
|
|
578
|
+
* the list have no data. Federates to the airport's own backend when
|
|
579
|
+
* it has a `historyEndpoint` (or `endpoint` is passed explicitly) —
|
|
580
|
+
* see docs/development/federation/003-*.md. */
|
|
581
|
+
days: async (input) => {
|
|
582
|
+
const base = await this.resolveHistoryEndpoint(input?.airportId, input?.endpoint);
|
|
583
|
+
if (base) {
|
|
584
|
+
return this.federatedFetch(base, "/replay/days", {
|
|
585
|
+
lookbackDays: input?.lookbackDays?.toString()
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
return this.trpc.replay.days.query(input ?? {});
|
|
589
|
+
},
|
|
590
|
+
range: async (input) => {
|
|
591
|
+
const base = await this.resolveHistoryEndpoint(input.airportId, input.endpoint);
|
|
592
|
+
if (base) {
|
|
593
|
+
const summary = await this.federatedFetch(
|
|
594
|
+
base,
|
|
595
|
+
"/replay/range",
|
|
596
|
+
{ from: input.from, to: input.to }
|
|
597
|
+
);
|
|
598
|
+
return { from: input.from, to: input.to, ...summary };
|
|
599
|
+
}
|
|
600
|
+
return this.trpc.replay.range.query(input);
|
|
601
|
+
},
|
|
602
|
+
// replay.window / replay.seek (bulk sample download for client-side
|
|
603
|
+
// interpolation) were removed — they were never part of the federation
|
|
604
|
+
// contract, and `replay.stream`'s server-paced WS (with server-side
|
|
605
|
+
// seek/re-snapshot) covers every use they had at a fraction of the
|
|
606
|
+
// payload. See docs/development/federation/005-*.md.
|
|
607
|
+
/** Server-paced WS playback: streams historical tracks at `speed`× in
|
|
608
|
+
* the same envelope format as the live stream. Returns a transport
|
|
609
|
+
* handle (pause/resume/seek/stop) — a Promise, since resolving which
|
|
610
|
+
* backend serves this airport (see docs/development/federation/003-*.md)
|
|
611
|
+
* is async. See `AeroReplayClient` for the raw wire protocol if you
|
|
612
|
+
* want to speak WS manually instead. */
|
|
613
|
+
stream: async (opts, callbacks) => {
|
|
614
|
+
const federatedBase = await this.resolveHistoryEndpoint(opts.airportId, opts.endpoint);
|
|
615
|
+
if (federatedBase) {
|
|
616
|
+
const wsBase2 = federatedBase.replace(/^http/, "ws");
|
|
617
|
+
const { airportId: _drop, ...rest } = opts;
|
|
618
|
+
return new AeroReplayClient(wsBase2, this.opts.token, "/replay").stream(rest, callbacks);
|
|
619
|
+
}
|
|
620
|
+
const wsBase = (this.opts.wsEndpoint ?? this.opts.endpoint).replace(/^http/, "ws");
|
|
621
|
+
return new AeroReplayClient(wsBase, this.opts.token).stream(opts, callbacks);
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
/** Movement analytics: takeoffs/landings per hour + peak hour, recorded
|
|
625
|
+
* by the pipeline's movement detector. */
|
|
626
|
+
analytics = {
|
|
627
|
+
movements: (input) => this.trpc.analytics.movements.query(input ?? {})
|
|
628
|
+
};
|
|
629
|
+
/** Route conformance: pre-defined ground routes + live track clearances.
|
|
630
|
+
* Assign a route to a track and the safety engine can detect when it
|
|
631
|
+
* strays beyond the route's corridor. */
|
|
632
|
+
routes = {
|
|
633
|
+
list: (input) => this.trpc.routes.list.query(input ?? {}),
|
|
634
|
+
create: (input) => this.trpc.routes.create.mutate(input),
|
|
635
|
+
delete: (input) => this.trpc.routes.delete.mutate(input),
|
|
636
|
+
assign: (input) => this.trpc.routes.assign.mutate(input),
|
|
637
|
+
unassign: (input) => this.trpc.routes.unassign.mutate(input),
|
|
638
|
+
assignments: () => this.trpc.routes.assignments.query()
|
|
639
|
+
};
|
|
640
|
+
webhooks = {
|
|
641
|
+
list: () => this.trpc.webhooks.list.query(),
|
|
642
|
+
create: (body) => this.trpc.webhooks.create.mutate(body),
|
|
643
|
+
delete: (input) => this.trpc.webhooks.delete.mutate(input)
|
|
644
|
+
};
|
|
645
|
+
system = {
|
|
646
|
+
stats: () => this.trpc.system.stats.query(),
|
|
647
|
+
infraHealth: () => this.trpc.system.infraHealth.query(),
|
|
648
|
+
ingestHistory: () => this.trpc.system.ingestHistory.query(),
|
|
649
|
+
getConfig: () => this.trpc.system.getConfig.query(),
|
|
650
|
+
setConfig: (input) => this.trpc.system.setConfig.mutate(input),
|
|
651
|
+
clearTable: (input) => this.trpc.system.clearTable.mutate(input)
|
|
652
|
+
};
|
|
653
|
+
getStatus() {
|
|
654
|
+
return this._status;
|
|
655
|
+
}
|
|
656
|
+
getLastUpdateAt() {
|
|
657
|
+
return this._lastUpdateAt;
|
|
658
|
+
}
|
|
659
|
+
getError() {
|
|
660
|
+
return this._error;
|
|
661
|
+
}
|
|
662
|
+
getSourceStatus() {
|
|
663
|
+
return { ...this._sourceStatus };
|
|
664
|
+
}
|
|
665
|
+
disconnect() {
|
|
666
|
+
this.wsClient.disconnect();
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
export {
|
|
670
|
+
AeroReplayClient,
|
|
671
|
+
AeroSwarm,
|
|
672
|
+
AeroWsClient,
|
|
673
|
+
TrackCache
|
|
674
|
+
};
|
|
675
|
+
//# sourceMappingURL=index.js.map
|