-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
576 lines (503 loc) · 19 KB
/
Copy pathindex.ts
File metadata and controls
576 lines (503 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import { defaultEndpoints, subwayRouteColors } from "./src/defaults";
import { MissingBusTimeKeyError, StaticDataMissingError, UnknownRouteError, UnknownStopError } from "./src/errors";
import { decodeFeedMessage, type GtfsRealtimeFeed, type TranslatedString } from "./src/gtfs-realtime";
import { fetchArrayBuffer, fetchJson, urlWithParams } from "./src/http";
import { directionFromStopId, GTFSCache } from "./src/static-gtfs";
import type {
Alert,
AlertQuery,
Arrival,
BusArrivalQuery,
BusArrivalBoardQuery,
BusArrivalBoardStop,
BusRouteStopsQuery,
BusVehicleQuery,
Direction,
MTAEndpoints,
MTAOptions,
NearbyStop,
Route,
RouteCatalogEntry,
RouteStopsResponse,
RoutesListQuery,
Stop,
StopLookup,
StopsByIdsQuery,
StopsNearQuery,
SubwayArrivalQuery,
SubwayArrivalBoardQuery,
SubwayArrivalBoardStation,
SubwayDirectionQuery,
SubwayDirectionResolution,
SubwayRouteStationsQuery,
TransitMode,
Vehicle,
} from "./src/types";
export class MTA {
static: GTFSCache;
readonly subway: SubwayClient;
readonly bus: BusClient;
readonly alerts: AlertsClient;
readonly stops: StopsClient;
readonly routes: RoutesClient;
readonly fetch: typeof fetch;
readonly now: () => Date;
readonly apiKey?: string;
readonly apiBaseUrl: string;
readonly busTimeKey?: string;
readonly endpoints: MTAEndpoints;
readonly options: MTAOptions;
private readonly realtimeCache = new Map<string, { expiresAt: number; feed: GtfsRealtimeFeed }>();
private readonly realtimeCacheTtlMs: number;
constructor(options: MTAOptions = {}) {
this.options = options;
this.fetch = options.fetch ?? fetch;
this.now = options.now ?? (() => new Date());
this.apiKey = options.apiKey;
this.apiBaseUrl = options.apiBaseUrl ?? "https://www.mtaapi.dev";
this.busTimeKey = options.busTimeKey;
this.realtimeCacheTtlMs = options.realtimeCacheTtlMs ?? 15_000;
this.endpoints = {
...defaultEndpoints,
...options.endpoints,
subwayFeeds: {
...defaultEndpoints.subwayFeeds,
...options.endpoints?.subwayFeeds,
},
};
this.static = new GTFSCache(options.staticData, options.staticDataMode ?? "subway");
this.subway = new SubwayClient(this);
this.bus = new BusClient(this);
this.alerts = new AlertsClient(this);
this.stops = new StopsClient(this);
this.routes = new RoutesClient(this);
}
async ready() {
return this;
}
close() {
this.static.close();
}
async realtimeFeed(url: string) {
const now = this.now().getTime();
const cached = this.realtimeCache.get(url);
if (cached && cached.expiresAt > now) return cached.feed;
const feed = decodeFeedMessage(await fetchArrayBuffer(this.fetch, url));
if (this.realtimeCacheTtlMs > 0) {
this.realtimeCache.set(url, { feed, expiresAt: now + this.realtimeCacheTtlMs });
}
return feed;
}
hostedApiEnabled() {
return Boolean(this.apiKey);
}
async hostedJson<T>(path: string, query: object = {}): Promise<T> {
if (!this.apiKey) {
throw new Error("mta-js hosted API calls require an apiKey.");
}
const url = urlWithParams(
new URL(path, this.apiBaseUrl).toString(),
serializeHostedQuery(query),
);
return fetchJson(this.fetch, url, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
"x-api-key": this.apiKey,
},
}) as Promise<T>;
}
}
class SubwayClient {
constructor(private readonly mta: MTA) {}
async arrivals(query: SubwayArrivalQuery): Promise<Arrival[]> {
const normalizedQuery = normalizeSubwayArrivalQuery(query);
if (this.mta.hostedApiEnabled()) {
return this.mta.hostedJson<Arrival[]>("/api/v1/subway/arrivals", normalizedQuery);
}
await this.mta.ready();
const routeIds = normalizedQuery.route ? [normalizeRouteId(normalizedQuery.route)] : Object.keys(this.mta.endpoints.subwayFeeds);
const feeds = [...new Set(routeIds.map((route) => this.feedForRoute(route)))];
const stopIds = this.mta.static.getStopIdsForQuery(normalizedQuery.stopId);
if (this.mta.static.hasStaticData("subway") && !this.mta.static.getStopOrParent(normalizedQuery.stopId)) {
throw new UnknownStopError(normalizedQuery.stopId);
}
const arrivals: Arrival[] = [];
for (const feedUrl of feeds) {
const feed = await this.mta.realtimeFeed(feedUrl);
arrivals.push(...this.arrivalsFromFeed(feed, stopIds, normalizedQuery));
}
return arrivals
.sort((a, b) => Date.parse(a.arrivalTime) - Date.parse(b.arrivalTime))
.slice(0, query.limit ?? 20);
}
direction(query: SubwayDirectionQuery): Promise<SubwayDirectionResolution> {
return this.mta.hostedJson<SubwayDirectionResolution>("/api/v1/subway/direction", query);
}
arrivalBoard(query: SubwayArrivalBoardQuery): Promise<SubwayArrivalBoardStation[]> {
return this.mta.hostedJson<SubwayArrivalBoardStation[]>("/api/v1/subway/arrival-board", {
...query,
route: query.route ? normalizeRouteId(query.route) : undefined,
});
}
routeStations(query: SubwayRouteStationsQuery): Promise<RouteStopsResponse> {
return this.mta.hostedJson<RouteStopsResponse>(
`/api/v1/subway/routes/${encodeURIComponent(normalizeRouteId(query.route))}/stations`,
{
...query,
route: undefined,
direction: normalizeDirection(query.direction, query.route),
},
);
}
private feedForRoute(route: string) {
const feed = this.mta.endpoints.subwayFeeds[route];
if (!feed) throw new UnknownRouteError(route);
return feed;
}
private arrivalsFromFeed(
feed: GtfsRealtimeFeed,
stopIds: Set<string>,
query: SubwayArrivalQuery,
) {
const arrivals: Arrival[] = [];
const wantedDirection = normalizeDirection(query.direction);
const now = this.mta.now().getTime();
for (const entity of feed.entity) {
const tripUpdate = entity.tripUpdate;
if (!tripUpdate) continue;
const trip = tripUpdate.trip;
const routeId = normalizeRouteId(trip?.routeId ?? query.route ?? "");
if (query.route && routeId !== normalizeRouteId(query.route)) continue;
const staticTrip = trip?.tripId ? this.mta.static.getTrip(trip.tripId) : undefined;
const route = routeWithFallback(this.mta.static.getRoute(routeId), routeId);
for (const update of tripUpdate.stopTimeUpdate ?? []) {
const stopId = update.stopId;
if (!stopId || !stopIds.has(stopId)) continue;
if (update.scheduleRelationship === "SKIPPED" || update.scheduleRelationship === "NO_DATA") continue;
const direction = directionFromStopId(stopId);
if (wantedDirection && direction !== wantedDirection) continue;
const event = update.arrival ?? update.departure;
if (!event?.time) continue;
const stop = this.mta.static.getStopOrParent(stopId) ?? fallbackStop(query.stopId);
const headsign = staticTrip?.headsign ?? undefined;
arrivals.push({
mode: "subway",
route,
stop,
direction,
destination: headsign,
displayDirection: displayDirection(headsign, direction),
headsign,
arrivalTime: new Date(event.time * 1000).toISOString(),
departureTime: update.departure?.time ? new Date(update.departure.time * 1000).toISOString() : undefined,
minutes: Math.max(0, Math.round((event.time * 1000 - now) / 60_000)),
tripId: trip?.tripId,
realtime: true,
source: "mta-gtfs-rt",
raw: query.includeRaw ? entity : undefined,
});
}
}
return arrivals;
}
}
class BusClient {
constructor(private readonly mta: MTA) {}
async arrivals(query: BusArrivalQuery): Promise<Arrival[]> {
if (this.mta.hostedApiEnabled()) {
return this.mta.hostedJson<Arrival[]>("/api/v1/bus/arrivals", query);
}
await this.mta.ready();
const key = this.requireKey();
const body = await fetchJson(
this.mta.fetch,
urlWithParams(this.mta.endpoints.busStopMonitoring, {
key,
version: "2",
OperatorRef: "MTA",
MonitoringRef: query.stopId,
LineRef: query.route ? busLineRef(query.route) : undefined,
}),
);
const journeys = monitoredStopVisits(body);
const now = this.mta.now().getTime();
return journeys
.map((journey): Arrival | undefined => {
const mvj = journey.MonitoredVehicleJourney;
if (!mvj) return undefined;
const routeId = routeFromLineRef(mvj.LineRef ?? query.route ?? "");
const call = mvj.MonitoredCall ?? {};
const expected = call.ExpectedArrivalTime ?? call.AimedArrivalTime;
if (!expected) return undefined;
const stop = this.mta.static.getStop(String(call.StopPointRef ?? query.stopId)) ?? fallbackStop(query.stopId);
const headsign = stringOrUndefined(mvj.DestinationName);
return {
mode: "bus",
route: routeWithFallback(this.mta.static.getRoute(routeId), routeId),
stop,
direction: "unknown",
destination: headsign,
displayDirection: displayDirection(headsign, "unknown"),
headsign,
arrivalTime: new Date(expected).toISOString(),
minutes: Math.max(0, Math.round((Date.parse(expected) - now) / 60_000)),
tripId: stringOrUndefined(mvj.FramedVehicleJourneyRef?.DatedVehicleJourneyRef),
realtime: true,
source: "mta-bustime",
raw: query.includeRaw ? journey : undefined,
};
})
.filter((arrival): arrival is Arrival => Boolean(arrival))
.sort((a, b) => Date.parse(a.arrivalTime) - Date.parse(b.arrivalTime))
.slice(0, query.limit ?? 20);
}
async vehicles(query: BusVehicleQuery = {}): Promise<Vehicle[]> {
if (this.mta.hostedApiEnabled()) {
return this.mta.hostedJson<Vehicle[]>("/api/v1/bus/vehicles", query);
}
await this.mta.ready();
const key = this.requireKey();
const body = await fetchJson(
this.mta.fetch,
urlWithParams(this.mta.endpoints.busVehicleMonitoring, {
key,
version: "2",
OperatorRef: "MTA",
LineRef: query.route ? busLineRef(query.route) : undefined,
VehicleRef: query.vehicleId,
}),
);
return monitoredVehicleJourneys(body)
.map((mvj): Vehicle => {
const routeId = routeFromLineRef(mvj.LineRef ?? query.route ?? "");
const location = mvj.VehicleLocation ?? {};
const stopId = stringOrUndefined(mvj.MonitoredCall?.StopPointRef);
return {
mode: "bus",
route: routeWithFallback(this.mta.static.getRoute(routeId), routeId),
vehicleId: stringOrUndefined(mvj.VehicleRef),
tripId: stringOrUndefined(mvj.FramedVehicleJourneyRef?.DatedVehicleJourneyRef),
stop: stopId ? this.mta.static.getStop(stopId) ?? fallbackStop(stopId) : undefined,
lat: numberOrUndefined(location.Latitude),
lon: numberOrUndefined(location.Longitude),
bearing: numberOrUndefined(mvj.Bearing),
destinationName: stringOrUndefined(mvj.DestinationName),
recordedAt: mvj.RecordedAtTime ? new Date(mvj.RecordedAtTime).toISOString() : undefined,
source: "mta-bustime",
raw: query.includeRaw ? mvj : undefined,
};
})
.slice(0, query.limit ?? 50);
}
arrivalBoard(query: BusArrivalBoardQuery): Promise<BusArrivalBoardStop[]> {
return this.mta.hostedJson<BusArrivalBoardStop[]>("/api/v1/bus/arrival-board", query);
}
routeStops(query: BusRouteStopsQuery): Promise<RouteStopsResponse> {
return this.mta.hostedJson<RouteStopsResponse>(
`/api/v1/bus/routes/${encodeURIComponent(query.route)}/stops`,
{
...query,
route: undefined,
},
);
}
private requireKey() {
if (!this.mta.busTimeKey) throw new MissingBusTimeKeyError();
return this.mta.busTimeKey;
}
}
class AlertsClient {
constructor(private readonly mta: MTA) {}
async current(query: AlertQuery = {}): Promise<Alert[]> {
if (this.mta.hostedApiEnabled()) {
return this.mta.hostedJson<Alert[]>("/api/v1/alerts", query);
}
await this.mta.ready();
const feed = await this.mta.realtimeFeed(this.mta.endpoints.alerts);
const alerts: Alert[] = [];
for (const entity of feed.entity) {
if (!entity.alert) continue;
const informed = entity.alert.informedEntity ?? [];
const routeIds = [...new Set(informed.map((item) => item.routeId).filter((id): id is string => Boolean(id)))];
const stopIds = [...new Set(informed.map((item) => item.stopId).filter((id): id is string => Boolean(id)))];
const routes = routeIds.map((id) => routeWithFallback(this.mta.static.getRoute(id), id));
const stops = stopIds.map((id) => this.mta.static.getStopOrParent(id) ?? fallbackStop(id));
if (query.route && !routeIds.some((id) => normalizeRouteId(id) === normalizeRouteId(query.route!))) continue;
if (query.stopId && !stopIds.includes(query.stopId)) continue;
if (query.mode && !alertMatchesMode(query.mode, routes, stops, informed)) continue;
alerts.push({
id: entity.id,
mode: inferAlertMode(routes, stops, informed),
routes,
stops,
header: translatedText(entity.alert.headerText),
description: translatedText(entity.alert.descriptionText),
url: translatedText(entity.alert.url),
effect: entity.alert.effect,
activePeriods: (entity.alert.activePeriod ?? []).map((period) => ({
start: period.start ? new Date(period.start * 1000).toISOString() : undefined,
end: period.end ? new Date(period.end * 1000).toISOString() : undefined,
})),
source: "mta-gtfs-rt",
raw: query.includeRaw ? entity : undefined,
});
}
return alerts;
}
}
class StopsClient {
constructor(private readonly mta: MTA) {}
near(query: StopsNearQuery): Promise<NearbyStop[]> {
if (this.mta.hostedApiEnabled()) {
return this.mta.hostedJson<NearbyStop[]>("/api/v1/stops/near", query);
}
return this.mta.ready().then(() => {
if (!this.mta.static.hasStopData()) throw new StaticDataMissingError(query.modes?.[0] ?? "requested modes");
return this.mta.static.stopsNear(query);
});
}
byIds(query: StopsByIdsQuery): Promise<StopLookup[]> {
return this.mta.hostedJson<StopLookup[]>("/api/v1/stops", query);
}
}
class RoutesClient {
constructor(private readonly mta: MTA) {}
list(query: RoutesListQuery = {}): Promise<RouteCatalogEntry[]> {
return this.mta.hostedJson<RouteCatalogEntry[]>("/api/v1/routes", query);
}
}
function serializeHostedQuery(query: object) {
const params: Record<string, string | number | boolean | undefined> = {};
for (const [key, value] of Object.entries(query)) {
if (
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
params[key] = value;
continue;
}
if (Array.isArray(value)) {
params[key] = value.join(",");
}
}
return params;
}
function normalizeRouteId(route: string) {
return route.toUpperCase().trim();
}
function normalizeSubwayArrivalQuery(query: SubwayArrivalQuery): SubwayArrivalQuery {
const route = query.route ?? routeFromLStopId(query.stopId);
return {
...query,
route,
direction: normalizeDirection(query.direction, route),
};
}
function normalizeDirection(
direction: Direction | "uptown" | "downtown" | undefined,
route?: string,
): Direction | undefined {
if (!direction) return undefined;
if (direction === "uptown") return "north";
if (direction === "downtown") return "south";
if (route && normalizeRouteId(route) === "L") {
if (direction === "east") return "south";
if (direction === "west") return "north";
}
return direction;
}
function routeFromLStopId(stopId: string) {
return /^L\d{2}[NS]?$/.test(stopId.toUpperCase().trim()) ? "L" : undefined;
}
function displayDirection(headsign: string | undefined, direction: Direction) {
if (headsign) return `toward ${headsign}`;
if (direction === "unknown") return undefined;
return `${direction}bound`;
}
function routeWithFallback(route: Route | undefined, routeId: string): Route {
return (
route ?? {
id: routeId,
shortName: routeId,
color: subwayRouteColors[routeId] ? `#${subwayRouteColors[routeId]}` : undefined,
}
);
}
function fallbackStop(stopId: string): Stop {
return { id: stopId, name: stopId };
}
function busLineRef(route: string) {
const normalized = normalizeBusRouteId(route);
return normalized.includes("_") ? normalized : `MTA NYCT_${normalized}`;
}
function routeFromLineRef(lineRef: string) {
return String(lineRef).split("_").at(-1)?.toUpperCase() ?? String(lineRef).toUpperCase();
}
function normalizeBusRouteId(route: string) {
const normalized = route.toUpperCase().trim();
const aliases: Record<string, string> = {
M14A: "M14A-SBS",
M14D: "M14D-SBS",
M15: "M15-SBS",
M23: "M23-SBS",
M34: "M34-SBS",
M34A: "M34A-SBS",
M60: "M60-SBS",
M79: "M79-SBS",
M86: "M86-SBS",
};
return aliases[normalized] ?? normalized;
}
function stringOrUndefined(value: unknown) {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
function numberOrUndefined(value: unknown) {
if (value === undefined || value === null || value === "") return undefined;
const number = Number(value);
return Number.isFinite(number) ? number : undefined;
}
function translatedText(value: TranslatedString | undefined) {
return value?.translation?.find((translation) => !translation.language || translation.language === "en")?.text ??
value?.translation?.[0]?.text;
}
function monitoredStopVisits(body: unknown): any[] {
return (
(body as any)?.Siri?.ServiceDelivery?.StopMonitoringDelivery?.[0]?.MonitoredStopVisit ??
(body as any)?.Siri?.ServiceDelivery?.StopMonitoringDelivery?.MonitoredStopVisit ??
[]
);
}
function monitoredVehicleJourneys(body: unknown): any[] {
const visits =
(body as any)?.Siri?.ServiceDelivery?.VehicleMonitoringDelivery?.[0]?.VehicleActivity ??
(body as any)?.Siri?.ServiceDelivery?.VehicleMonitoringDelivery?.VehicleActivity ??
[];
return visits.map((visit: any) => visit.MonitoredVehicleJourney).filter(Boolean);
}
function inferAlertMode(
routes: Route[],
stops: Stop[],
informed: { routeType?: number }[],
): TransitMode | undefined {
if (stops.some((stop) => stop.mode)) return stops.find((stop) => stop.mode)?.mode;
if (informed.some((item) => item.routeType === 3)) return "bus";
if (informed.some((item) => item.routeType === 1)) return "subway";
if (routes.some((route) => route.type === 3)) return "bus";
if (routes.some((route) => route.type === 1 || route.id.length <= 2)) return "subway";
return undefined;
}
function alertMatchesMode(
mode: TransitMode,
routes: Route[],
stops: Stop[],
informed: { routeType?: number }[],
) {
return inferAlertMode(routes, stops, informed) === mode;
}
export { decodeFeedMessage, encodeFeedMessage } from "./src/gtfs-realtime";
export { GTFSCache } from "./src/static-gtfs";
export * from "./src/errors";
export type * from "./src/generated";
export type * from "./src/types";