@tiducto/spider-sdk-typescript 0.7.0 → 1.1.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 (94) hide show
  1. package/README.md +1 -1
  2. package/dist/contract/routing/Leg.d.ts +3 -0
  3. package/dist/contract/routing/Leg.d.ts.map +1 -1
  4. package/dist/contract/routing/PlanConnectionStreamVariables.d.ts +5 -2
  5. package/dist/contract/routing/PlanConnectionStreamVariables.d.ts.map +1 -1
  6. package/dist/contract/routing/PlanConnectionVariables.d.ts +3 -0
  7. package/dist/contract/routing/PlanConnectionVariables.d.ts.map +1 -1
  8. package/dist/contract/routing/Reliability.d.ts +3 -0
  9. package/dist/contract/routing/Reliability.d.ts.map +1 -0
  10. package/dist/contract/routing/Reliability.js +2 -0
  11. package/dist/contract/routing/Reliability.js.map +1 -0
  12. package/dist/contract/routing/Route.d.ts +3 -0
  13. package/dist/contract/routing/Route.d.ts.map +1 -1
  14. package/dist/contract/routing/Stop.d.ts +2 -0
  15. package/dist/contract/routing/Stop.d.ts.map +1 -1
  16. package/dist/contract/routing/StopDeparturesData.d.ts +3 -3
  17. package/dist/contract/routing/StopDeparturesData.d.ts.map +1 -1
  18. package/dist/contract/routing/StopDeparturesRoute.d.ts +3 -0
  19. package/dist/contract/routing/StopDeparturesRoute.d.ts.map +1 -1
  20. package/dist/contract/routing/StopDeparturesStop.d.ts +1 -5
  21. package/dist/contract/routing/StopDeparturesStop.d.ts.map +1 -1
  22. package/dist/contract/routing/StopDeparturesStop2.d.ts +9 -0
  23. package/dist/contract/routing/StopDeparturesStop2.d.ts.map +1 -0
  24. package/dist/contract/routing/StopDeparturesStop2.js +2 -0
  25. package/dist/contract/routing/StopDeparturesStop2.js.map +1 -0
  26. package/dist/contract/routing/StopDeparturesStoptime.d.ts +16 -0
  27. package/dist/contract/routing/StopDeparturesStoptime.d.ts.map +1 -0
  28. package/dist/contract/routing/StopDeparturesStoptime.js +2 -0
  29. package/dist/contract/routing/StopDeparturesStoptime.js.map +1 -0
  30. package/dist/contract/routing/StopDeparturesTrip.d.ts +2 -0
  31. package/dist/contract/routing/StopDeparturesTrip.d.ts.map +1 -1
  32. package/dist/contract/routing/StopDeparturesVariables.d.ts +2 -2
  33. package/dist/contract/routing/StopDeparturesVariables.d.ts.map +1 -1
  34. package/dist/contract/routing/Stoptime.d.ts +6 -3
  35. package/dist/contract/routing/Stoptime.d.ts.map +1 -1
  36. package/dist/contract/routing/TripRoute.d.ts +3 -0
  37. package/dist/contract/routing/TripRoute.d.ts.map +1 -1
  38. package/dist/contract/routing/TripStop.d.ts +2 -0
  39. package/dist/contract/routing/TripStop.d.ts.map +1 -1
  40. package/dist/contract/routing/TripTrip.d.ts +4 -2
  41. package/dist/contract/routing/TripTrip.d.ts.map +1 -1
  42. package/dist/contract/routing/index.d.ts +3 -1
  43. package/dist/contract/routing/index.d.ts.map +1 -1
  44. package/dist/contract.d.ts +0 -1
  45. package/dist/contract.d.ts.map +1 -1
  46. package/dist/contract.js +0 -12
  47. package/dist/contract.js.map +1 -1
  48. package/dist/contractVersion.d.ts +1 -1
  49. package/dist/contractVersion.js +1 -1
  50. package/dist/enums.d.ts +13 -4
  51. package/dist/enums.d.ts.map +1 -1
  52. package/dist/enums.js +43 -24
  53. package/dist/enums.js.map +1 -1
  54. package/dist/errors.d.ts +30 -10
  55. package/dist/errors.d.ts.map +1 -1
  56. package/dist/errors.js +55 -18
  57. package/dist/errors.js.map +1 -1
  58. package/dist/http.d.ts +14 -0
  59. package/dist/http.d.ts.map +1 -1
  60. package/dist/http.js +18 -30
  61. package/dist/http.js.map +1 -1
  62. package/dist/index.d.ts +2 -3
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +0 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/location.d.ts +4 -0
  67. package/dist/location.d.ts.map +1 -1
  68. package/dist/location.js +4 -0
  69. package/dist/location.js.map +1 -1
  70. package/dist/persistedQueries.js +4 -4
  71. package/dist/realtime.d.ts +6 -2
  72. package/dist/realtime.d.ts.map +1 -1
  73. package/dist/realtime.js +21 -14
  74. package/dist/realtime.js.map +1 -1
  75. package/dist/routing.d.ts +103 -73
  76. package/dist/routing.d.ts.map +1 -1
  77. package/dist/routing.js +156 -145
  78. package/dist/routing.js.map +1 -1
  79. package/dist/sdk.d.ts +1 -1
  80. package/dist/sdkVersion.d.ts +1 -1
  81. package/dist/sdkVersion.js +1 -1
  82. package/dist/serviceDate.d.ts +6 -0
  83. package/dist/serviceDate.d.ts.map +1 -0
  84. package/dist/serviceDate.js +17 -0
  85. package/dist/serviceDate.js.map +1 -0
  86. package/dist/stops.d.ts +12 -1
  87. package/dist/stops.d.ts.map +1 -1
  88. package/dist/stops.js +15 -6
  89. package/dist/stops.js.map +1 -1
  90. package/package.json +1 -1
  91. package/dist/contract/routing/TripStoptime.d.ts +0 -13
  92. package/dist/contract/routing/TripStoptime.d.ts.map +0 -1
  93. package/dist/contract/routing/TripStoptime.js +0 -2
  94. package/dist/contract/routing/TripStoptime.js.map +0 -1
package/dist/routing.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import { failure, success } from "./result.js";
2
- import { DecodingError, SpiderContractMismatchError, TransportError, parseErrorEnvelope, toSpiderError } from "./errors.js";
3
- import { bikesAllowedFromWire, transitModeFromWire, wheelchairFromWire } from "./enums.js";
2
+ import { DecodingError, TransportError, badRequest, httpFailure, toSpiderError } from "./errors.js";
3
+ import { graphqlFailure } from "./http.js";
4
+ import { bikesAllowedFromWire, inputFieldFromWire, realtimeStateFromWire, routingErrorCodeFromWire, transitModeFromWire, wheelchairFromWire, } from "./enums.js";
4
5
  import { decodePolyline } from "./polyline.js";
6
+ import { invalidServiceDate, serviceDateOf } from "./serviceDate.js";
5
7
  import { DEPARTURES, PLAN, PLAN_STREAM, TRIP } from "./persistedQueries.js";
6
8
  const DEFAULT_SEARCH_WINDOW_MINUTES = 60;
7
- const DEFAULT_MAX_TRAVERSAL_MINUTES = 360;
8
- const DEFAULT_TARGET_RESULTS = 10;
9
- const DEFAULT_STREAM_TARGET_RESULTS = 5;
10
- const DEFAULT_MAX_WINDOW_MINUTES = 360;
11
- const DEFAULT_TIME_RANGE_SECONDS = 24 * 60 * 60;
12
- const INT_MAX = 2_147_483_647;
9
+ const DEFAULT_NUMBER_OF_DEPARTURES = 30;
10
+ const MAX_TIME_RANGE_SECONDS = 24 * 60 * 60;
11
+ // Fixed platform limits; the env-set ones (search window, result count, via count) are the server's to check.
12
+ const MIN_STREAM_WINDOW_MINUTES = 120;
13
+ const MAX_VIA_STOP_IDS = 10;
14
+ const MAX_VIA_WAIT_SECONDS = 24 * 60 * 60;
13
15
  // The OTP transit modes valid in a modes filter — the public TransitMode union also carries street/leg
14
16
  // values (WALK, BICYCLE, CAR, TRANSIT, UNKNOWN) that are not transit modes and must not reach the wire.
15
17
  const WIRE_TRANSIT_MODES = new Set([
@@ -35,29 +37,53 @@ export class SpiderRouting {
35
37
  maxTransfers: options.maxTransfers,
36
38
  searchWindowMinutes: options.searchWindowMinutes ?? DEFAULT_SEARCH_WINDOW_MINUTES,
37
39
  wheelchairAccessible: options.wheelchairAccessible ?? false,
40
+ reliability: options.reliability,
38
41
  };
42
+ const invalid = invalidVia(request.via);
43
+ if (invalid != null)
44
+ return failure(invalid);
39
45
  return this.page(request);
40
46
  }
41
47
  /**
42
48
  * Streams itineraries over Server-Sent Events as the router sweeps the search window forward, emitting them
43
49
  * as they finalize instead of one batched page. Lazy and cancellable: iteration opens the request, and
44
- * `break`ing out of the `for await` cancels the underlying stream. Each `chunk` event carries itineraries
45
- * with realtime delays already on their legs; a `page` event then carries the continuation cursors and a
46
- * `done` event closes the stream (or a terminal `failure`). Never throws for transport/HTTP/server errors —
47
- * they surface as a `failure` event — except a contract-version mismatch, which throws like the batch calls.
50
+ * `break`ing out of the `for await` cancels the underlying stream. Each `result` event carries itineraries
51
+ * with realtime delays already on their legs; a terminal `done` event then carries the continuation
52
+ * {@link RoutePageInfo} and any `routingErrors` (or a terminal `failure`). Never throws — transport, HTTP and
53
+ * request errors surface as a `failure` event.
48
54
  *
49
- * `targetResults` is a soft floor the sweep aims to reach; `maxWindowMinutes` caps how far forward it
50
- * searches. To continue, re-call with the same inputs plus `after` = the last `page` event's `endCursor`
51
- * (or `before` = `startCursor` to walk earlier). For a single batched page instead, use {@link plan}.
55
+ * `targetResults` (a soft floor the sweep aims to reach) and `maxWindowMinutes` (how far it may search, at
56
+ * least 2 h) are required. This opens a fresh stream; to continue, call {@link planStreamNext} with
57
+ * `done.pageInfo.endCursor` (when `hasNextPage`) or {@link planStreamPrevious} with `done.pageInfo.startCursor`
58
+ * (when `hasPreviousPage`). For a single batched page instead, use {@link plan}.
52
59
  */
53
60
  async *planStream(options) {
61
+ yield* this.openPlanStream(options);
62
+ }
63
+ /**
64
+ * Continues a stream forward from a prior `done` event's `endCursor`. Takes the same options as
65
+ * {@link planStream} (so `targetResults` / `maxWindowMinutes` can vary per continuation) plus the raw cursor.
66
+ * Call only when the prior `done.pageInfo.hasNextPage` was true.
67
+ */
68
+ async *planStreamNext(options, after) {
69
+ yield* this.openPlanStream(options, { after });
70
+ }
71
+ /**
72
+ * Continues a stream backward from a prior `done` event's `startCursor`. Takes the same options as
73
+ * {@link planStream} plus the raw cursor. Call only when the prior `done.pageInfo.hasPreviousPage` was true.
74
+ */
75
+ async *planStreamPrevious(options, before) {
76
+ yield* this.openPlanStream(options, { before });
77
+ }
78
+ // Builds the SSE request variables from the public options plus an optional raw continuation cursor. Forward
79
+ // paging sets `after`, backward sets `before`; an initial stream sets neither.
80
+ streamVariables(options, cursor) {
54
81
  const time = options.arriveBy != null
55
82
  ? { kind: 'arriveBy', epochMs: toEpochMs(options.arriveBy) }
56
83
  : { kind: 'departAt', epochMs: toEpochMs(options.departAt ?? Date.now()) };
57
84
  const iso = new Date(time.epochMs).toISOString();
58
85
  const via = options.via ?? [];
59
- const maxWindowMinutes = Math.max(1, Math.floor(options.maxWindowMinutes ?? DEFAULT_MAX_WINDOW_MINUTES));
60
- const variables = {
86
+ return {
61
87
  dateTime: time.kind === 'departAt' ? { earliestDeparture: iso } : { latestArrival: iso },
62
88
  origin: locationToInput(options.origin),
63
89
  destination: locationToInput(options.destination),
@@ -67,50 +93,59 @@ export class SpiderRouting {
67
93
  maxTransfers: options.maxTransfers,
68
94
  wheelchairAccessible: options.wheelchairAccessible ?? false,
69
95
  }),
70
- targetResults: options.targetResults ?? DEFAULT_STREAM_TARGET_RESULTS,
71
- maxWindow: `PT${maxWindowMinutes}M`,
72
- before: options.before,
73
- after: options.after,
96
+ targetResults: options.targetResults,
97
+ maxWindow: `PT${Math.floor(options.maxWindowMinutes)}M`,
98
+ reliability: options.reliability,
99
+ before: cursor?.before,
100
+ after: cursor?.after,
74
101
  };
75
- yield* this.openPlanStream(variables);
76
102
  }
77
103
  // Opens the SSE `plan-stream` request and turns its `chunk`/`pageInfo`/`done`/`error` records into a
78
- // PlanStreamEvent stream. A non-2xx response, a transport error, or a decoding slip becomes a terminal
79
- // `failure` event rather than a throw (a contract mismatch still throws). Reading stops when the server
80
- // closes the stream or the consumer stops iterating (which cancels the reader → aborts the request).
81
- async *openPlanStream(variables) {
104
+ // PlanStreamEvent stream. Invalid options, a non-2xx response, a transport error, or a decoding slip becomes a
105
+ // terminal `failure` event rather than a throw. Reading stops when the server closes the stream or the
106
+ // consumer stops iterating (which cancels the reader → aborts the request).
107
+ async *openPlanStream(options, cursor) {
108
+ const invalid = invalidStreamOptions(options);
109
+ if (invalid != null) {
110
+ yield { type: 'failure', error: invalid };
111
+ return;
112
+ }
82
113
  let response;
83
114
  try {
84
- response = await this.transport.stream(PLAN_STREAM, variables);
115
+ response = await this.transport.stream(PLAN_STREAM, this.streamVariables(options, cursor));
85
116
  }
86
117
  catch (e) {
87
- if (e instanceof SpiderContractMismatchError)
88
- throw e;
89
- yield { kind: 'failure', error: toSpiderError(e) };
118
+ yield { type: 'failure', error: toSpiderError(e) };
90
119
  return;
91
120
  }
92
121
  if (!response.ok) {
93
- const text = await drainText(response);
94
- const env = parseErrorEnvelope(text);
95
- const detail = env.message ?? text.slice(0, 300);
96
- const err = new TransportError('http', `routing plan-stream -> ${response.status}: ${detail}`, response.status, env.code);
97
- yield { kind: 'failure', error: toSpiderError(err) };
122
+ yield { type: 'failure', error: toSpiderError(httpFailure('routing plan-stream', response.status, await drainText(response))) };
98
123
  return;
99
124
  }
100
125
  const body = response.body;
101
126
  if (body == null) {
102
- yield { kind: 'failure', error: toSpiderError(new TransportError('no_data', 'routing plan-stream returned no body')) };
127
+ yield { type: 'failure', error: toSpiderError(new TransportError('no_data', 'routing plan-stream returned no body')) };
103
128
  return;
104
129
  }
105
130
  const reader = body.getReader();
106
131
  const decoder = new TextDecoder();
107
132
  let buffer = '';
133
+ // The gateway answers some rejections (e.g. a missing required variable) with a 2xx GraphQL JSON body
134
+ // before any event, so a body that opens with `{` is read whole and mapped like a batch response.
135
+ let json = (response.headers.get('content-type') ?? '').includes('json') ? true : undefined;
108
136
  try {
109
137
  for (;;) {
110
138
  const { value, done } = await reader.read();
111
139
  if (done)
112
140
  break;
113
141
  buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, '\n');
142
+ if (json === undefined) {
143
+ const head = buffer.trimStart();
144
+ if (head !== '')
145
+ json = head.startsWith('{');
146
+ }
147
+ if (json !== false)
148
+ continue;
114
149
  // SSE records are separated by a blank line; parse every complete one and keep the remainder buffered.
115
150
  let boundary;
116
151
  while ((boundary = buffer.indexOf('\n\n')) !== -1) {
@@ -121,6 +156,10 @@ export class SpiderRouting {
121
156
  yield event;
122
157
  }
123
158
  }
159
+ if (json === true) {
160
+ yield { type: 'failure', error: streamErrorToSpiderError(buffer) };
161
+ return;
162
+ }
124
163
  // A trailing record the server didn't terminate with a blank line before closing.
125
164
  const record = parseSseFrame(buffer);
126
165
  const event = parsePlanStreamRecord(record.event, record.data);
@@ -128,7 +167,7 @@ export class SpiderRouting {
128
167
  yield event;
129
168
  }
130
169
  catch (e) {
131
- yield { kind: 'failure', error: toSpiderError(e) };
170
+ yield { type: 'failure', error: toSpiderError(e) };
132
171
  }
133
172
  finally {
134
173
  await reader.cancel().catch(() => { });
@@ -147,66 +186,19 @@ export class SpiderRouting {
147
186
  return this.page(requestOf(route), route.pageInfo.startCursor ?? undefined, undefined);
148
187
  }
149
188
  /**
150
- * Streams itineraries by stepping the search forward one search window at a time, until `targetResults`
151
- * itineraries have been collected or `maxTraversalMinutes` of time has been traversed. Each step pulls a
152
- * whole window in one search, so a busy window yields more — `targetResults` is a soft floor, the window
153
- * that reaches it is yielded whole. Lazy: `for await ... break` stops stepping and skips the remaining OTP
154
- * searches. Each yield is one step's `SpiderResult` (a terminal error ends the stream), matching the
155
- * non-throwing poll helpers.
156
- *
157
- * The step is `searchWindowMinutes` and it is fixed for the whole walk — OTP locks the window into the
158
- * paging cursor after the first search and ignores it thereafter, so a wider step means a wider
159
- * `searchWindowMinutes` here, not on a continuation.
189
+ * Upcoming departures from a stop or station: `numberOfDepartures` (default 30, up to the environment's
190
+ * limit) within `options.timeRangeSeconds` (default 24 h) from `options.startTime` (default now).
160
191
  */
161
- async *planUntil(options) {
162
- const { targetResults, maxTraversalMinutes, ...planOptions } = options;
163
- const target = targetResults ?? DEFAULT_TARGET_RESULTS;
164
- const steps = stepCount(maxTraversalMinutes ?? DEFAULT_MAX_TRAVERSAL_MINUTES, options.searchWindowMinutes ?? DEFAULT_SEARCH_WINDOW_MINUTES);
165
- const first = await this.plan(planOptions);
166
- yield first;
167
- if (!first.isSuccess)
168
- return;
169
- yield* this.stepFrom(first.data, 'forward', steps - 1, target, first.data.edges.length);
170
- }
171
- /** Streaming form of `planNext`: steps forward from `prev`, one (fixed) search window per step. */
172
- async *planNextUntil(prev, options) {
173
- const steps = stepCount(options?.maxTraversalMinutes ?? DEFAULT_MAX_TRAVERSAL_MINUTES, requestOf(prev).searchWindowMinutes);
174
- yield* this.stepFrom(prev, 'forward', steps, options?.targetResults ?? DEFAULT_TARGET_RESULTS, 0);
175
- }
176
- /** Streaming form of `planPrevious`: steps backward from `prev`, one (fixed) search window per step. */
177
- async *planPreviousUntil(prev, options) {
178
- const steps = stepCount(options?.maxTraversalMinutes ?? DEFAULT_MAX_TRAVERSAL_MINUTES, requestOf(prev).searchWindowMinutes);
179
- yield* this.stepFrom(prev, 'backward', steps, options?.targetResults ?? DEFAULT_TARGET_RESULTS, 0);
180
- }
181
- // Step from `start` one search window at a time, accumulating itinerary count. Stop at `targetResults`, when a
182
- // step has no next page, or on an error. `collectedSoFar` seeds the count (planUntil already yielded step 1).
183
- async *stepFrom(start, direction, remainingSteps, targetResults, collectedSoFar) {
184
- if (collectedSoFar >= targetResults)
185
- return;
186
- let prev = start;
187
- let collected = collectedSoFar;
188
- for (let i = 0; i < Math.max(0, remainingSteps); i++) {
189
- const res = direction === 'forward'
190
- ? await this.planNext(prev)
191
- : await this.planPrevious(prev);
192
- if (res === null)
193
- return;
194
- yield res;
195
- if (!res.isSuccess)
196
- return;
197
- collected += res.data.edges.length;
198
- if (collected >= targetResults)
199
- return;
200
- prev = res.data;
201
- }
202
- }
203
- async departures(stopId, numberOfDepartures = 30, options) {
192
+ async departures(stopId, numberOfDepartures = DEFAULT_NUMBER_OF_DEPARTURES, options) {
193
+ const timeRange = Math.floor(options?.timeRangeSeconds ?? MAX_TIME_RANGE_SECONDS);
194
+ if (!(timeRange > 0 && timeRange <= MAX_TIME_RANGE_SECONDS))
195
+ return failure(badRequest('timeRange'));
204
196
  try {
205
197
  const variables = {
206
198
  id: stopId,
207
199
  numberOfDepartures,
208
200
  startTime: options?.startTime != null ? Math.floor(toEpochMs(options.startTime) / 1000) : undefined,
209
- timeRange: clampSeconds(options?.timeRangeSeconds ?? DEFAULT_TIME_RANGE_SECONDS),
201
+ timeRange,
210
202
  };
211
203
  const data = await this.transport.graphql(DEPARTURES, variables);
212
204
  const stop = data.asStop ?? data.asStation;
@@ -216,12 +208,14 @@ export class SpiderRouting {
216
208
  return success(mapDepartures(stop));
217
209
  }
218
210
  catch (e) {
219
- if (e instanceof SpiderContractMismatchError)
220
- throw e;
221
211
  return failure(toSpiderError(e));
222
212
  }
223
213
  }
214
+ /** One trip on one service date (ISO `YYYY-MM-DD`, e.g. a {@link Departure.serviceDate}); undefined = today. */
224
215
  async trip(tripId, serviceDate) {
216
+ const invalid = serviceDate != null ? invalidServiceDate(serviceDate) : null;
217
+ if (invalid != null)
218
+ return failure(invalid);
225
219
  try {
226
220
  const variables = { id: tripId, serviceDate };
227
221
  const data = await this.transport.graphql(TRIP, variables);
@@ -232,8 +226,6 @@ export class SpiderRouting {
232
226
  return success(mapTrip(trip));
233
227
  }
234
228
  catch (e) {
235
- if (e instanceof SpiderContractMismatchError)
236
- throw e;
237
229
  return failure(toSpiderError(e));
238
230
  }
239
231
  }
@@ -242,8 +234,6 @@ export class SpiderRouting {
242
234
  return success(await this.fetchPlan(request, before, after));
243
235
  }
244
236
  catch (e) {
245
- if (e instanceof SpiderContractMismatchError)
246
- throw e;
247
237
  return failure(toSpiderError(e));
248
238
  }
249
239
  }
@@ -259,8 +249,8 @@ export class SpiderRouting {
259
249
  via: request.via.length > 0 ? request.via.map(viaToInput) : undefined,
260
250
  modes: modesInput(request.allowedTransitModes),
261
251
  preferences: preferencesInput(request),
262
- // Floor to a whole minute, min 1 — a sub-minute window returns almost nothing on OTP.
263
- searchWindow: `PT${Math.max(1, Math.floor(request.searchWindowMinutes))}M`,
252
+ searchWindow: `PT${Math.floor(request.searchWindowMinutes)}M`,
253
+ reliability: request.reliability,
264
254
  before,
265
255
  after,
266
256
  };
@@ -278,11 +268,7 @@ export class SpiderRouting {
278
268
  hasPreviousPage: plan.pageInfo.hasPreviousPage,
279
269
  searchWindowUsed: plan.pageInfo.searchWindowUsed ?? null,
280
270
  },
281
- routingErrors: plan.routingErrors.map((re) => ({
282
- code: re.code,
283
- description: re.description,
284
- inputField: re.inputField ?? null,
285
- })),
271
+ routingErrors: plan.routingErrors.map(mapRoutingError),
286
272
  searchDateTime: plan.searchDateTime ?? null,
287
273
  };
288
274
  return Object.assign({}, route, { [ROUTE_REQUEST]: request });
@@ -294,13 +280,23 @@ function requestOf(route) {
294
280
  function toEpochMs(value) {
295
281
  return typeof value === 'number' ? value : value.getTime();
296
282
  }
297
- function clampSeconds(seconds) {
298
- return Math.max(0, Math.min(Math.floor(seconds), INT_MAX));
283
+ function invalidStreamOptions(options) {
284
+ // Required by the type; a plain-JS caller can still omit it, and `PTNaNM` must never reach the wire.
285
+ if (options.maxWindowMinutes == null)
286
+ return badRequest('maxWindow', 'is required');
287
+ if (!(Math.floor(options.maxWindowMinutes) >= MIN_STREAM_WINDOW_MINUTES))
288
+ return badRequest('maxWindow');
289
+ return invalidVia(options.via ?? []);
299
290
  }
300
- // Each cursor step advances a full (fixed) search window, so the number of steps to traverse the total time
301
- // is a plain division by the step — no searchWindowUsed math.
302
- function stepCount(maxTraversalMinutes, stepMinutes) {
303
- return Math.max(1, Math.floor(maxTraversalMinutes / Math.max(1, stepMinutes)));
291
+ function invalidVia(via) {
292
+ for (const v of via) {
293
+ const valid = v.kind === 'passThrough'
294
+ ? v.stopIds.length >= 1 && v.stopIds.length <= MAX_VIA_STOP_IDS
295
+ : v.minimumWaitSeconds >= 0 && v.minimumWaitSeconds <= MAX_VIA_WAIT_SECONDS;
296
+ if (!valid)
297
+ return badRequest('via');
298
+ }
299
+ return null;
304
300
  }
305
301
  function locationToInput(location) {
306
302
  if (location.kind === 'stop') {
@@ -328,7 +324,7 @@ function viaToInput(via) {
328
324
  function modesInput(modes) {
329
325
  const transit = modes
330
326
  .filter((m) => WIRE_TRANSIT_MODES.has(m))
331
- .map((mode) => ({ mode }));
327
+ .map((mode) => ({ mode: mode }));
332
328
  return transit.length > 0 ? { transit: { transit } } : undefined;
333
329
  }
334
330
  function preferencesInput(request) {
@@ -358,23 +354,22 @@ function durationSecondsFromWire(raw) {
358
354
  }
359
355
  const SSE_DEFAULT_EVENT = 'message';
360
356
  // Parses one finished SSE record (its event name + accumulated data) into a PlanStreamEvent; returns null for
361
- // records the SDK doesn't surface (heartbeats, unknown events). A malformed payload becomes a terminal
362
- // `failure` rather than throwing. Exported so the wire-contract test exercises it directly.
357
+ // records the SDK doesn't surface (heartbeats, unknown events, the terminal `done` telemetry frame). A
358
+ // malformed payload becomes a terminal `failure` rather than throwing. Exported so the wire-contract test
359
+ // exercises it directly. A `chunk` frame → `result`; the `pageInfo` frame → terminal `done` (carrying the
360
+ // RoutePageInfo and routingErrors); the wire `done` telemetry frame just ends the stream and is dropped.
363
361
  export function parsePlanStreamRecord(event, data) {
364
362
  if (data.trim() === '')
365
363
  return null;
366
364
  switch (event) {
367
365
  case 'chunk':
368
366
  return decodeStreamRecord('chunk', data, (chunk) => ({
369
- kind: 'chunk',
370
- frontierSeconds: chunk.frontier ?? 0,
371
- found: chunk.found ?? 0,
372
- finalized: chunk.finalized ?? 0,
367
+ type: 'result',
373
368
  itineraries: (chunk.results ?? []).map(mapItinerary),
374
369
  }));
375
370
  case 'pageInfo':
376
371
  return decodeStreamRecord('pageInfo', data, (page) => ({
377
- kind: 'page',
372
+ type: 'done',
378
373
  pageInfo: {
379
374
  startCursor: page.startCursor ?? null,
380
375
  endCursor: page.endCursor ?? null,
@@ -382,27 +377,20 @@ export function parsePlanStreamRecord(event, data) {
382
377
  hasPreviousPage: page.hasPreviousPage ?? false,
383
378
  searchWindowUsed: page.searchWindowUsed ?? null,
384
379
  },
385
- }));
386
- case 'done':
387
- return decodeStreamRecord('done', data, (done) => ({
388
- kind: 'done',
389
- iterations: done.iterations ?? 0,
390
- windowSeconds: done.windowSeconds ?? 0,
391
- resultCount: done.resultCount ?? 0,
392
- stoppedBy: done.stoppedBy ?? 'unknown',
380
+ routingErrors: (page.routingErrors ?? []).map(mapRoutingError),
393
381
  }));
394
382
  case 'error':
395
- return { kind: 'failure', error: streamErrorToSpiderError(data) };
383
+ return { type: 'failure', error: streamErrorToSpiderError(data) };
396
384
  default:
397
385
  return null;
398
386
  }
399
387
  }
400
- function decodeStreamRecord(kind, data, map) {
388
+ function decodeStreamRecord(frame, data, map) {
401
389
  try {
402
390
  return map(JSON.parse(data));
403
391
  }
404
392
  catch (e) {
405
- return { kind: 'failure', error: toSpiderError(new DecodingError(`failed to decode plan-stream ${kind}`, e)) };
393
+ return { type: 'failure', error: toSpiderError(new DecodingError(`failed to decode plan-stream ${frame}`, e)) };
406
394
  }
407
395
  }
408
396
  // Splits one raw SSE record into its event name (default "message") and data (multiple `data:` lines joined
@@ -426,25 +414,20 @@ function parseSseFrame(record) {
426
414
  }
427
415
  return { event, data: data.join('\n') };
428
416
  }
429
- // A stream `error` record is the same GraphQL error envelope the batch path returns, so it maps through the
430
- // same taxonomy — a top-level BAD_REQUEST becomes a typed bad_request (with its field), anything else server.
417
+ // A stream `error` record (or a 2xx JSON body in place of the stream) is the same GraphQL error envelope the
418
+ // batch path returns, so it maps through the same taxonomy: a BAD_REQUEST becomes bad_request with its field.
431
419
  function streamErrorToSpiderError(data) {
432
420
  let env;
433
421
  try {
434
422
  env = JSON.parse(data);
435
423
  }
436
424
  catch {
437
- return toSpiderError(new TransportError('upstream', `plan-stream error: ${data.slice(0, 300)}`));
425
+ return toSpiderError(new TransportError('upstream', `routing plan-stream error: ${data.slice(0, 300)}`));
438
426
  }
439
- const errors = env.errors;
440
- if (errors != null && errors.length > 0) {
441
- const bad = errors.find((e) => e.extensions?.code === 'BAD_REQUEST');
442
- if (bad != null) {
443
- return toSpiderError(new TransportError('bad_request', bad.message, undefined, undefined, bad.extensions?.field));
444
- }
445
- return toSpiderError(new TransportError('upstream', `plan-stream errors: ${errors.map((e) => e.message).join(', ')}`));
427
+ if (env.errors != null && env.errors.length > 0) {
428
+ return toSpiderError(graphqlFailure('routing plan-stream', env.errors));
446
429
  }
447
- return toSpiderError(new TransportError('upstream', `plan-stream error: ${env.message ?? data.slice(0, 300)}`));
430
+ return toSpiderError(new TransportError('upstream', `routing plan-stream error: ${env.message ?? data.slice(0, 300)}`));
448
431
  }
449
432
  async function drainText(response) {
450
433
  try {
@@ -454,6 +437,9 @@ async function drainText(response) {
454
437
  return '';
455
438
  }
456
439
  }
440
+ function mapRoutingError(re) {
441
+ return { code: routingErrorCodeFromWire(re.code), description: re.description, inputField: inputFieldFromWire(re.inputField) };
442
+ }
457
443
  function mapItinerary(node) {
458
444
  return {
459
445
  start: node.start ?? null,
@@ -474,17 +460,28 @@ function mapLeg(leg) {
474
460
  endEstimated: leg.end.estimated?.time ?? null,
475
461
  startDelaySeconds: durationSecondsFromWire(leg.start.estimated?.delay),
476
462
  endDelaySeconds: durationSecondsFromWire(leg.end.estimated?.delay),
463
+ typicalArrivalDelaySeconds: leg.typicalArrivalDelay ?? null,
477
464
  isRealtime: leg.realTime ?? false,
478
- realtimeState: leg.realtimeState ?? null,
465
+ realtimeState: realtimeStateFromWire(leg.realtimeState),
479
466
  serviceDate: leg.serviceDate ?? null,
480
467
  fromName: leg.from.name ?? null,
481
468
  toName: leg.to.name ?? null,
469
+ fromGtfsId: leg.from.stop?.gtfsId ?? null,
470
+ toGtfsId: leg.to.stop?.gtfsId ?? null,
471
+ fromPlatformCode: leg.from.stop?.platformCode ?? null,
472
+ toPlatformCode: leg.to.stop?.platformCode ?? null,
473
+ fromZoneId: leg.from.stop?.zoneId ?? null,
474
+ toZoneId: leg.to.stop?.zoneId ?? null,
475
+ routeGtfsId: leg.route?.gtfsId ?? null,
482
476
  routeShortName: leg.route?.shortName ?? null,
483
477
  routeLongName: leg.route?.longName ?? null,
478
+ routeColor: leg.route?.color ?? null,
479
+ routeTextColor: leg.route?.textColor ?? null,
484
480
  headsign: leg.headsign ?? null,
485
481
  distanceMeters: leg.distance ?? null,
486
482
  durationSeconds: leg.duration ?? null,
487
483
  tripGtfsId: leg.trip?.gtfsId ?? null,
484
+ interlineWithPreviousLeg: leg.interlineWithPreviousLeg ?? false,
488
485
  bikesAllowed: bikesAllowedFromWire(leg.trip?.bikesAllowed),
489
486
  accessibilityScore: leg.accessibilityScore ?? null,
490
487
  fromWheelchair: wheelchairFromWire(leg.from.stop?.wheelchairBoarding),
@@ -493,31 +490,37 @@ function mapLeg(leg) {
493
490
  };
494
491
  }
495
492
  function mapDepartures(stop) {
496
- const stopName = stop.name.trim().toLowerCase();
497
493
  const out = [];
498
494
  for (const st of stop.stoptimesWithoutPatterns ?? []) {
499
495
  const serviceDay = st.serviceDay;
500
496
  const scheduledOffset = st.scheduledDeparture;
501
497
  if (serviceDay == null || scheduledOffset == null)
502
498
  continue;
503
- if (st.headsign != null && st.headsign.trim().toLowerCase() === stopName)
504
- continue;
505
499
  const route = st.trip?.route;
506
500
  out.push({
507
501
  scheduledTimeEpochMs: (serviceDay + scheduledOffset) * 1000,
508
502
  realtimeTimeEpochMs: st.realtimeDeparture != null ? (serviceDay + st.realtimeDeparture) * 1000 : null,
509
503
  isRealtime: st.realtime ?? false,
510
- realtimeState: st.realtimeState ?? null,
504
+ realtimeState: realtimeStateFromWire(st.realtimeState),
505
+ typicalDelaySeconds: st.typicalDelay ?? null,
511
506
  headsign: st.headsign ?? null,
512
507
  tripGtfsId: st.trip?.gtfsId ?? null,
508
+ serviceDate: serviceDateOf(serviceDay),
509
+ routeGtfsId: route?.gtfsId ?? null,
513
510
  routeShortName: route?.shortName ?? null,
514
511
  routeLongName: route?.longName ?? null,
512
+ routeColor: route?.color ?? null,
513
+ routeTextColor: route?.textColor ?? null,
515
514
  mode: transitModeFromWire(route?.mode),
515
+ stopGtfsId: st.stop?.gtfsId ?? null,
516
+ platformCode: st.stop?.platformCode ?? null,
517
+ wheelchairAccessible: wheelchairFromWire(st.trip?.wheelchairAccessible),
516
518
  });
517
519
  }
518
520
  return out;
519
521
  }
520
522
  function mapTrip(trip) {
523
+ const serviceDay = trip.stoptimesForDate?.find((st) => st.serviceDay != null)?.serviceDay;
521
524
  const stops = [];
522
525
  for (const st of trip.stoptimesForDate ?? []) {
523
526
  const s = st.stop;
@@ -535,17 +538,25 @@ function mapTrip(trip) {
535
538
  realtimeArrivalEpochMs: at(st.realtimeArrival),
536
539
  realtimeDepartureEpochMs: at(st.realtimeDeparture),
537
540
  isRealtime: st.realtime ?? false,
541
+ typicalDelaySeconds: st.typicalDelay ?? null,
538
542
  wheelchairBoarding: wheelchairFromWire(s.wheelchairBoarding),
543
+ platformCode: s.platformCode ?? null,
544
+ zoneId: s.zoneId ?? null,
539
545
  });
540
546
  }
541
547
  return {
542
548
  gtfsId: trip.gtfsId,
549
+ serviceDate: serviceDay != null ? serviceDateOf(serviceDay) : null,
550
+ routeGtfsId: trip.route.gtfsId ?? null,
543
551
  routeShortName: trip.route.shortName ?? null,
544
552
  routeLongName: trip.route.longName ?? null,
553
+ routeColor: trip.route.color ?? null,
554
+ routeTextColor: trip.route.textColor ?? null,
545
555
  mode: transitModeFromWire(trip.route.mode),
546
556
  headsign: trip.tripHeadsign ?? null,
547
557
  directionId: trip.directionId ?? null,
548
558
  bikesAllowed: bikesAllowedFromWire(trip.bikesAllowed),
559
+ wheelchairAccessible: wheelchairFromWire(trip.wheelchairAccessible),
549
560
  stops,
550
561
  geometry: trip.tripGeometry?.points ? decodePolyline(trip.tripGeometry.points) : [],
551
562
  };