@wemap/routers 12.8.9 → 12.8.10

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/index.ts CHANGED
@@ -31,6 +31,7 @@ export { default as CustomGraphMapTester, type Report as CustomGraphMapTesterRep
31
31
  export { default as OsrmRemoteRouter } from './src/remote/osrm/OsrmRemoteRouter.js';
32
32
  export { default as OtpRemoteRouter } from './src/remote/otp/OtpRemoteRouter.js';
33
33
  export { default as CitywayRemoteRouter } from './src/remote/cityway/CitywayRemoteRouter.js';
34
+ export { default as NavitiaRemoteRouter } from './src/remote/navitia/NavitiaRemoteRouter.js';
34
35
  export { default as DeutscheBahnRemoteRouter } from './src/remote/deutsche-bahn/DeutscheBahnRemoteRouter.js';
35
36
  export { default as IdfmRemoteRouter } from './src/remote/idfm/IdfmRemoteRouter.js';
36
37
  export { default as GeoveloRemoteRouter } from './src/remote/geovelo/GeoveloRemoteRouter.js';
package/package.json CHANGED
@@ -12,7 +12,7 @@
12
12
  "directory": "packages/routers"
13
13
  },
14
14
  "name": "@wemap/routers",
15
- "version": "12.8.9",
15
+ "version": "12.8.10",
16
16
  "bugs": {
17
17
  "url": "https://github.com/wemap/wemap-modules-js/issues"
18
18
  },
@@ -52,5 +52,5 @@
52
52
  },
53
53
  "./helpers/*": "./helpers/*"
54
54
  },
55
- "gitHead": "653f93f7efb8585735ea406aac1ca96f89b4ee12"
55
+ "gitHead": "a9ac02840374bc97ddf8322f4f35d737ff49a379"
56
56
  }
@@ -42,6 +42,10 @@ export class RemoteRoutingError extends RoutingError {
42
42
  return new RemoteRoutingError(StatusCode.NOT_FOUND, routerName, `Cannot found an itinerary with ${routerName}. Details: ${details}`)
43
43
  }
44
44
 
45
+ static missingApiKey(routerName: string, details?: string) {
46
+ return new RemoteRoutingError(StatusCode.UNAUTHENTICATED, routerName, `API key is missing for ${routerName}. Details: ${details}`)
47
+ }
48
+
45
49
  static unreachableServer(routerName: string, url: string) {
46
50
  return new RemoteRoutingError(StatusCode.NOT_FOUND, routerName, `Remote router server ${routerName} is unreachable. URL: ${url}`)
47
51
  }
package/src/StatusCode.ts CHANGED
@@ -7,5 +7,6 @@ export enum StatusCode {
7
7
  NOT_FOUND = 5,
8
8
  UNIMPLEMENTED = 12,
9
9
  INTERNAL = 13,
10
- UNAVAILABLE = 14
10
+ UNAVAILABLE = 14,
11
+ UNAUTHENTICATED = 16
11
12
  }
@@ -1,5 +1,6 @@
1
1
  import RemoteRouter from './RemoteRouter.js';
2
2
  import CitywayRemoteRouter from './cityway/CitywayRemoteRouter.js';
3
+ import NavitiaRemoteRouter from './navitia/NavitiaRemoteRouter.js';
3
4
  import DeutscheBahnRemoteRouter from './deutsche-bahn/DeutscheBahnRemoteRouter.js';
4
5
  import IdfmRemoteRouter from './idfm/IdfmRemoteRouter.js';
5
6
  import OsrmRemoteRouter from './osrm/OsrmRemoteRouter.js';
@@ -10,6 +11,7 @@ import { RemoteRoutingError } from '../RoutingError.js';
10
11
 
11
12
  const remoteRouters = [
12
13
  CitywayRemoteRouter,
14
+ NavitiaRemoteRouter,
13
15
  DeutscheBahnRemoteRouter,
14
16
  IdfmRemoteRouter,
15
17
  OsrmRemoteRouter,
@@ -15,7 +15,7 @@ const { expect } = chai;
15
15
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
16
  const assetsPath = path.resolve(__dirname, '../../../assets');
17
17
 
18
- describe.only('GeoveloRouter - parseResponse', () => {
18
+ describe('GeoveloRouter - parseResponse', () => {
19
19
 
20
20
  it('Itineraries - 1', () => {
21
21
 
@@ -0,0 +1,116 @@
1
+ /* eslint-disable max-statements */
2
+ import chai from 'chai';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ import { Coordinates } from '@wemap/geo';
8
+
9
+ import NavitiaRemoteRouter from './NavitiaRemoteRouter.js';
10
+ import { verifyStepsCoherence } from '../../model/Itinerary.spec.js';
11
+ import { areTransitAndTravelModeConsistent } from '../../model/TransitMode.js';
12
+
13
+ const { expect } = chai;
14
+
15
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
+ const assetsPath = path.resolve(__dirname, '../../../assets');
17
+
18
+ describe('NavitiaRouter - parseResponse', () => {
19
+
20
+ it('Itineraries - 1', () => {
21
+
22
+ const filePath = path.resolve(assetsPath, 'itinerary-lemans-navitia.json');
23
+ const fileString = fs.readFileSync(filePath, 'utf8');
24
+ const json = JSON.parse(fileString);
25
+
26
+ const itineraries = NavitiaRemoteRouter.parseResponse(json);
27
+ itineraries.forEach(verifyStepsCoherence);
28
+
29
+ expect(itineraries.length).equal(5);
30
+
31
+ const itinerary1 = itineraries[0];
32
+ expect(itinerary1.origin.equals(new Coordinates(48.007274, 0.187574))).true;
33
+ expect(itinerary1.destination.equals(new Coordinates(48.005228, 0.205664))).true;
34
+ expect(itinerary1.distance).to.be.closeTo(1710, 1);
35
+ expect(itinerary1.duration).equal(1140);
36
+ expect(itinerary1.transitMode).equal('TRAM');
37
+ // Do not work because of the input time format
38
+ expect(itinerary1.startTime).equal(1722854691000);
39
+ expect(itinerary1.endTime).equal(1722855831000);
40
+ expect(itinerary1.legs.length).equal(3);
41
+
42
+ expect(areTransitAndTravelModeConsistent(itinerary1.transitMode, 'TRANSIT')).is.true;
43
+
44
+ const itinerary1leg1 = itinerary1.legs[0];
45
+ // Do not work because of the input time format
46
+ expect(itinerary1leg1.startTime).equal(1722854691000);
47
+ expect(itinerary1leg1.endTime).equal(1722854885000);
48
+ expect(itinerary1leg1.distance).to.be.closeTo(224, 1);
49
+ expect(itinerary1leg1.transitMode).equal('WALK');
50
+ expect(itinerary1leg1.transportInfo).is.null;
51
+ expect(itinerary1leg1.start.name).equal('33 Rue Saint-Pavin des Champs (Le Mans)');
52
+ expect(itinerary1leg1.start.coords.distanceTo(new Coordinates(48.007274, 0.187574))).to.be.closeTo(0, 1);
53
+ expect(itinerary1leg1.end.name).equal('Lafayette (Le Mans)');
54
+ expect(itinerary1leg1.end.coords.distanceTo(new Coordinates(48.006794, 0.190226))).to.be.closeTo(0, 1);
55
+
56
+ const itinerary1leg2 = itinerary1.legs[1];
57
+ expect(itinerary1leg2.transitMode).equal('TRAM');
58
+ expect(itinerary1leg2.transportInfo).is.not.null;
59
+ expect(itinerary1leg2.transportInfo?.name).equal('T1');
60
+ expect(itinerary1leg2.transportInfo?.routeColor).equal('E5261D');
61
+ expect(itinerary1leg2.transportInfo?.routeTextColor).equal('FFFFFF');
62
+ expect(itinerary1leg2.transportInfo?.directionName).equal('Antarès - Stade Marie Marvingt (Le Mans)');
63
+ });
64
+
65
+ it('Itineraries - 2', () => {
66
+
67
+ const filePath = path.resolve(assetsPath, 'itinerary-lemans-navitia.json');
68
+ const fileString = fs.readFileSync(filePath, 'utf8');
69
+ const json = JSON.parse(fileString);
70
+
71
+ const itineraries = NavitiaRemoteRouter.parseResponse(json);
72
+ itineraries.forEach(verifyStepsCoherence);
73
+
74
+
75
+ const itinerary2 = itineraries[1];
76
+ expect(itinerary2.origin.equals(new Coordinates(48.007274, 0.187574))).true;
77
+ expect(itinerary2.destination.equals(new Coordinates(48.005228, 0.205664))).true;
78
+ expect(itinerary2.distance).to.be.closeTo(1995, 1);
79
+ expect(itinerary2.duration).equal(1452);
80
+ expect(itinerary2.transitMode).equal('MULTI');
81
+ // Do not work because of the input time format
82
+ expect(itinerary2.startTime).equal(1722854691000);
83
+ expect(itinerary2.endTime).equal(1722856143000);
84
+ expect(itinerary2.legs.length).equal(4);
85
+
86
+ expect(areTransitAndTravelModeConsistent(itinerary2.transitMode, 'TRANSIT')).is.true;
87
+
88
+ const itinerary2leg1 = itinerary2.legs[0];
89
+ // Do not work because of the input time format
90
+ expect(itinerary2leg1.startTime).equal(1722854691000);
91
+ expect(itinerary2leg1.endTime).equal(1722854885000);
92
+ expect(itinerary2leg1.distance).to.be.closeTo(224, 1);
93
+ expect(itinerary2leg1.transitMode).equal('WALK');
94
+ expect(itinerary2leg1.transportInfo).is.null;
95
+ expect(itinerary2leg1.start.name).equal('33 Rue Saint-Pavin des Champs (Le Mans)');
96
+ expect(itinerary2leg1.start.coords.distanceTo(new Coordinates(48.007274, 0.187574))).to.be.closeTo(0, 1);
97
+ expect(itinerary2leg1.end.name).equal('Lafayette (Le Mans)');
98
+ expect(itinerary2leg1.end.coords.distanceTo(new Coordinates(48.006794, 0.190226))).to.be.closeTo(0, 1);
99
+
100
+ const itinerary2leg2 = itinerary2.legs[1];
101
+ expect(itinerary2leg2.transitMode).equal('TRAM');
102
+ expect(itinerary2leg2.transportInfo).is.not.null;
103
+ expect(itinerary2leg2.transportInfo?.name).equal('T1');
104
+ expect(itinerary2leg2.transportInfo?.routeColor).equal('E5261D');
105
+ expect(itinerary2leg2.transportInfo?.routeTextColor).equal('FFFFFF');
106
+ expect(itinerary2leg2.transportInfo?.directionName).equal('Antarès - Stade Marie Marvingt (Le Mans)');
107
+
108
+ const itinerary2leg3 = itinerary2.legs[2];
109
+ expect(itinerary2leg3.transitMode).equal('BUS');
110
+ expect(itinerary2leg3.transportInfo).is.not.null;
111
+ expect(itinerary2leg3.transportInfo?.name).equal('6');
112
+ expect(itinerary2leg3.transportInfo?.routeColor).equal('C3057F');
113
+ expect(itinerary2leg3.transportInfo?.routeTextColor).equal('FFFFFF');
114
+ expect(itinerary2leg3.transportInfo?.directionName).equal('St-Martin (Le Mans)');
115
+ });
116
+ });
@@ -0,0 +1,445 @@
1
+ import { Coordinates, Utils as GeoUtils } from '@wemap/geo';
2
+ import Logger from '@wemap/logger';
3
+
4
+ import RemoteRouter from '../RemoteRouter.js';
5
+ import Itinerary from '../../model/Itinerary.js';
6
+ import Leg, { TransportInfo } from '../../model/Leg.js';
7
+ import { dateWithTimeZone } from '../RemoteRouterUtils.js';
8
+ import { TransitMode, areTransitAndTravelModeConsistent } from '../../model/TransitMode.js';
9
+ import StepsBuilder from '../../model/StepsBuilder.js';
10
+ import { type MinStepInfo } from '../../model/Step.js';
11
+ import { type RouterRequest } from '../../model/RouterRequest.js';
12
+ import { RemoteRoutingError } from '../../RoutingError.js';
13
+ import { NavitiaJson, NavitiaCoordinates, NavitiaSection, NavitiaIntermediateStep } from './types';
14
+
15
+ /**
16
+ * List of all modes supported by the API
17
+ * http://doc.navitia.io/#physical-mode
18
+ */
19
+
20
+ const transitModeCorrespondance = new Map<string, TransitMode>();
21
+ transitModeCorrespondance.set('Air', 'AIRPLANE');
22
+ transitModeCorrespondance.set('Boat', 'BOAT');
23
+ transitModeCorrespondance.set('Bus', 'BUS');
24
+ transitModeCorrespondance.set('BusRapidTransit', 'BUS');
25
+ transitModeCorrespondance.set('Coach', 'BUS');
26
+ transitModeCorrespondance.set('Ferry', 'FERRY');
27
+ transitModeCorrespondance.set('Funicular', 'FUNICULAR');
28
+ transitModeCorrespondance.set('LocalTrain', 'TRAIN');
29
+ transitModeCorrespondance.set('LongDistanceTrain', 'TRAIN');
30
+ transitModeCorrespondance.set('Metro', 'METRO');
31
+ transitModeCorrespondance.set('Métro', 'METRO');
32
+ transitModeCorrespondance.set('RailShuttle', 'TRAIN');
33
+ transitModeCorrespondance.set('RapidTransit', 'BUS');
34
+ transitModeCorrespondance.set('Shuttle', 'BUS');
35
+ transitModeCorrespondance.set('SuspendedCableCar', 'FUNICULAR');
36
+ transitModeCorrespondance.set('Taxi', 'TAXI');
37
+ transitModeCorrespondance.set('Train', 'TRAIN');
38
+ transitModeCorrespondance.set('RER', 'TRAIN');
39
+ transitModeCorrespondance.set('Tramway', 'TRAM');
40
+ transitModeCorrespondance.set('walking', 'WALK');
41
+ transitModeCorrespondance.set('bike', 'BIKE');
42
+
43
+ /**
44
+ * List of transports modes
45
+ */
46
+ const TRANSPORT_IDS = [
47
+ 'physical_mode:Air',
48
+ 'physical_mode:Boat',
49
+ 'physical_mode:Bus',
50
+ 'physical_mode:BusRapidTransit',
51
+ 'physical_mode:Coach',
52
+ 'physical_mode:Ferry',
53
+ 'physical_mode:Funicular',
54
+ 'physical_mode:LocalTrain',
55
+ 'physical_mode:LongDistanceTrain',
56
+ 'physical_mode:Metro',
57
+ 'physical_mode:RailShuttle',
58
+ 'physical_mode:RapidTransit',
59
+ 'physical_mode:Shuttle',
60
+ 'physical_mode:SuspendedCableCar',
61
+ 'physical_mode:Taxi',
62
+ 'physical_mode:Train',
63
+ 'physical_mode:Tramway'
64
+ ];
65
+
66
+ function jsonToCoordinates(json: NavitiaCoordinates) {
67
+ return new Coordinates(Number(json.lat), Number(json.lon));
68
+ }
69
+
70
+ function last<T>(array: T[]) {
71
+ return array[array.length - 1];
72
+ }
73
+
74
+ /**
75
+ * stringDate (e.g. 20211117T104516)
76
+ */
77
+ function dateStringToTimestamp(stringDate: string, timeZone: string) {
78
+ const yearStr = stringDate.substr(0, 4);
79
+ const monthStr = stringDate.substr(4, 2);
80
+ const dayStr = stringDate.substr(6, 2);
81
+ const hoursStr = stringDate.substr(9, 2);
82
+ const minutesStr = stringDate.substr(11, 2);
83
+ const secondsStr = stringDate.substr(13, 2);
84
+
85
+ return dateWithTimeZone(
86
+ Number(yearStr),
87
+ Number(monthStr) - 1,
88
+ Number(dayStr),
89
+ Number(hoursStr),
90
+ Number(minutesStr),
91
+ Number(secondsStr),
92
+ timeZone
93
+ ).getTime();
94
+ }
95
+
96
+ // The api key should be defined in the routingurl as api_key=XXXXXXXX
97
+
98
+ /**
99
+ * Singleton.
100
+ */
101
+ class NavitiaRemoteRouter extends RemoteRouter {
102
+
103
+ get rname() { return 'navitia' as const; }
104
+
105
+ async getItineraries(endpointUrl: string, routerRequest: RouterRequest) {
106
+ const url = this.getURL(endpointUrl, routerRequest);
107
+
108
+ // The api key should be defined in the routingurl as api_key=XXXXXXXX
109
+ const api_key = url.searchParams.get('api_key');
110
+ if (!api_key) {
111
+ throw RemoteRoutingError.missingApiKey(this.rname);
112
+ }
113
+
114
+ const res = await (fetch(url, {
115
+ method: 'GET',
116
+ headers: {
117
+ 'Authorization': api_key,
118
+ }
119
+ }).catch(() => {
120
+ throw RemoteRoutingError.unreachableServer(this.rname, url.toString());
121
+ }));
122
+
123
+
124
+ const jsonResponse: NavitiaJson = await res.json().catch(() => {
125
+ throw RemoteRoutingError.responseNotParsing(this.rname, url.toString());
126
+ });
127
+
128
+ // When Navitia failed to calculate an itinerary (ie. start or end
129
+ // point is far from network), it respond a 404 with an error message
130
+ // or a 200 with an error message
131
+ if (jsonResponse && jsonResponse.error) {
132
+ throw RemoteRoutingError.notFound(this.rname, jsonResponse.error.message);
133
+ }
134
+
135
+ const itineraries = this.parseResponse(jsonResponse);
136
+
137
+ const sameModeFound = itineraries.some((itinerary) => areTransitAndTravelModeConsistent(itinerary.transitMode, routerRequest.travelMode));
138
+
139
+ if (!sameModeFound) {
140
+ throw RemoteRoutingError.notFound(
141
+ this.rname,
142
+ 'Selected mode of transport was not found for this itinerary.'
143
+ )
144
+ }
145
+
146
+ return itineraries;
147
+ }
148
+
149
+ getURL(endpointUrl: string, routerRequest: RouterRequest) {
150
+ const { origin, destination, waypoints, travelMode } = routerRequest;
151
+
152
+ if ((waypoints || []).length > 0) {
153
+ Logger.warn(`${this.rname} router uses only the first 2 waypoints (asked ${waypoints?.length})`);
154
+ }
155
+
156
+ const url = new URL(endpointUrl);
157
+
158
+ const coreParams = new URLSearchParams();
159
+ coreParams.set('from', `${origin.longitude};${origin.latitude}`);
160
+ coreParams.set('to', `${destination.longitude};${destination.latitude}`);
161
+ coreParams.set('data_freshness', 'realtime');
162
+
163
+ if (routerRequest.itineraryModifiers?.avoidStairs) {
164
+ coreParams.set('wheelchair', 'true')
165
+ }
166
+
167
+ let queryParams: URLSearchParams = new URLSearchParams();
168
+ switch (travelMode) {
169
+ case 'WALK':
170
+ queryParams = this.getWalkingQuery();
171
+ break;
172
+ case 'BIKE':
173
+ queryParams = this.getBikeQuery();
174
+ break;
175
+ case 'CAR':
176
+ queryParams = this.getCarQuery();
177
+ break;
178
+ default:
179
+ break;
180
+ }
181
+
182
+ [coreParams, queryParams].map(params => {
183
+ for (const pair of params.entries()) {
184
+ url.searchParams.append(pair[0], pair[1]);
185
+ }
186
+ });
187
+
188
+ return url;
189
+ }
190
+
191
+ getCarQuery() {
192
+ const urlSearchParams = new URLSearchParams();
193
+
194
+ TRANSPORT_IDS.forEach((id) => {
195
+ urlSearchParams.append('forbidden_uris[]', id);
196
+ });
197
+
198
+ urlSearchParams.append('first_section_mode[]', 'walking');
199
+ urlSearchParams.append('first_section_mode[]', 'car');
200
+ urlSearchParams.append('last_section_mode[]', 'walking');
201
+ urlSearchParams.append('last_section_mode[]', 'car');
202
+
203
+ return urlSearchParams;
204
+ }
205
+
206
+ getWalkingQuery() {
207
+ const urlSearchParams = new URLSearchParams();
208
+
209
+ TRANSPORT_IDS.forEach((id) => {
210
+ urlSearchParams.append('forbidden_uris[]', id);
211
+ });
212
+
213
+ urlSearchParams.append('first_section_mode[]', 'walking');
214
+ urlSearchParams.append('last_section_mode[]', 'walking');
215
+
216
+ return urlSearchParams;
217
+ }
218
+
219
+ getBikeQuery() {
220
+ const urlSearchParams = new URLSearchParams();
221
+
222
+ TRANSPORT_IDS.forEach((id) => {
223
+ urlSearchParams.append('forbidden_uris[]', id);
224
+ });
225
+
226
+ urlSearchParams.append('first_section_mode[]', 'bike');
227
+ urlSearchParams.append('last_section_mode[]', 'bike');
228
+
229
+ return urlSearchParams;
230
+ }
231
+
232
+
233
+ getSectionCoords(section: NavitiaSection) {
234
+ let from: NavitiaCoordinates | undefined;
235
+ let to: NavitiaCoordinates | undefined;
236
+
237
+ if ('stop_point' in section.from) {
238
+ from = section.from.stop_point.coord;
239
+ } else if ('address' in section.from) {
240
+ from = section.from.address.coord;
241
+ } else {
242
+ from = section.from.poi.coord;
243
+ }
244
+
245
+ if ('stop_point' in section.to) {
246
+ to = section.to.stop_point.coord;
247
+ } else if ('address' in section.to) {
248
+ to = section.to.address.coord;
249
+ } else {
250
+ to = section.to.poi.coord;
251
+ }
252
+
253
+ return {
254
+ from: jsonToCoordinates(from),
255
+ to: jsonToCoordinates(to)
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Since the navitia API does not provide coords for each step, we need to compute them
261
+ * We trim the coordinates of the leg with the distance of each step and keep the last result as the coords of the step
262
+ * @param {Leg} leg
263
+ */
264
+ findStepsCoord(legCoords: Coordinates[], steps: NavitiaIntermediateStep[]) {
265
+ const coords = legCoords;
266
+
267
+ const duplicatedCoords = [...coords];
268
+ let previousStep = steps[0];
269
+ let accumulatedIndex = 0;
270
+ const outputSteps = [];
271
+
272
+ for (const [idx, step] of steps.entries()) {
273
+ let newCoords: Coordinates;
274
+
275
+ let _idCoordsInLeg;
276
+
277
+ if (idx === 0) {
278
+ _idCoordsInLeg = 0;
279
+ newCoords = coords[0];
280
+ } else if (idx === steps.length - 1) {
281
+ _idCoordsInLeg = coords.length - 1;
282
+ newCoords = last(coords);
283
+ } else if (duplicatedCoords.length === 1) {
284
+ accumulatedIndex++;
285
+
286
+ _idCoordsInLeg = accumulatedIndex;
287
+
288
+ newCoords = duplicatedCoords[0];
289
+
290
+ coords[_idCoordsInLeg] = newCoords;
291
+ } else {
292
+ const result = GeoUtils.trimRoute(duplicatedCoords, duplicatedCoords[0], previousStep.distance);
293
+ accumulatedIndex += result.length - 1;
294
+
295
+ duplicatedCoords.splice(0, result.length - 1);
296
+
297
+ _idCoordsInLeg = accumulatedIndex;
298
+
299
+ newCoords = last(result);
300
+
301
+ coords[_idCoordsInLeg] = newCoords;
302
+ }
303
+
304
+ outputSteps.push({
305
+ ...step,
306
+ coords: newCoords
307
+ });
308
+
309
+ previousStep = step;
310
+ }
311
+
312
+ return outputSteps;
313
+ }
314
+
315
+ findStepCoords(step: NavitiaSection['path'][number], section: NavitiaSection) {
316
+ if ('instruction_start_coordinate' in step) {
317
+ return jsonToCoordinates(step.instruction_start_coordinate);
318
+ }
319
+
320
+ const via = section.vias?.find(via => via.id === step.via_uri);
321
+ if (via) {
322
+ return jsonToCoordinates(via.access_point.coord);
323
+ }
324
+ }
325
+
326
+ parseResponse(json: NavitiaJson) {
327
+
328
+ if (!json || !json.journeys) {
329
+ throw RemoteRoutingError.notFound(this.rname, json.error?.message);
330
+ }
331
+
332
+ const itineraries = [];
333
+
334
+ const timeZone = json.context.timezone;
335
+
336
+ for (const jsonItinerary of json.journeys) {
337
+
338
+ const legs = [];
339
+
340
+ for (const jsonSection of jsonItinerary.sections) {
341
+
342
+ if (jsonSection.type === 'waiting' || jsonSection.type === 'transfer') {
343
+ continue;
344
+ }
345
+
346
+ const { from: startSection, to: endSection } = this.getSectionCoords(jsonSection);
347
+
348
+ // A section can have multiple same coordinates, we need to remove them
349
+ let existingCoords: string[] = [];
350
+ const legCoords = jsonSection.geojson.coordinates.reduce((acc, [lon, lat]) => {
351
+ if (!existingCoords.includes(`${lon}-${lat}`)) {
352
+ existingCoords = existingCoords.concat(`${lon}-${lat}`);
353
+ acc.push(new Coordinates(lat, lon));
354
+ }
355
+ return acc;
356
+ }, [] as Coordinates[]);
357
+
358
+ const stepsBuilder = new StepsBuilder().setStart(startSection).setEnd(endSection).setPathCoords(legCoords);
359
+ let transportInfo: TransportInfo | undefined;
360
+ let transitMode = transitModeCorrespondance.get(jsonSection.mode) as TransitMode;
361
+
362
+ if (jsonSection.path) {
363
+ const useNavitiaSteps = jsonSection.path.every(step => 'instruction_start_coordinate' in step || step.via_uri);
364
+ const navitiaIntermediateSteps = [];
365
+
366
+ for (const jsonPathLink of jsonSection.path) {
367
+ let coords: Coordinates;
368
+ if (useNavitiaSteps) {
369
+ coords = this.findStepCoords(jsonPathLink, jsonSection)!;
370
+
371
+ const intermediateStep = {
372
+ name: jsonPathLink.name,
373
+ distance: jsonPathLink.length,
374
+ coords
375
+ };
376
+
377
+ stepsBuilder.addStepInfo(intermediateStep);
378
+ } else {
379
+ navitiaIntermediateSteps.push({
380
+ name: jsonPathLink.name,
381
+ distance: jsonPathLink.length,
382
+ });
383
+ }
384
+ }
385
+
386
+ if (!useNavitiaSteps) {
387
+ stepsBuilder.setStepsInfo(this.findStepsCoord(legCoords, navitiaIntermediateSteps));
388
+ }
389
+ }
390
+
391
+ if (jsonSection.type === 'public_transport') {
392
+ transportInfo = {
393
+ name: jsonSection.display_informations.code,
394
+ routeColor: jsonSection.display_informations.color,
395
+ routeTextColor: jsonSection.display_informations.text_color,
396
+ directionName: jsonSection.display_informations.direction
397
+ };
398
+
399
+ transitMode = transitModeCorrespondance.get(jsonSection.display_informations.physical_mode) as TransitMode;
400
+
401
+ const legStep: MinStepInfo = {
402
+ coords: legCoords[0],
403
+ name: transportInfo.directionName,
404
+ distance: jsonSection.geojson.properties[0].length
405
+ };
406
+ stepsBuilder.setStepsInfo([legStep]);
407
+ }
408
+
409
+ const leg = new Leg({
410
+ transitMode,
411
+ duration: jsonSection.duration,
412
+ startTime: dateStringToTimestamp(jsonSection.departure_date_time, timeZone),
413
+ endTime: dateStringToTimestamp(jsonSection.arrival_date_time, timeZone),
414
+ start: {
415
+ name: jsonSection.from.name,
416
+ coords: startSection
417
+ },
418
+ end: {
419
+ name: jsonSection.to.name,
420
+ coords: endSection
421
+ },
422
+ coords: legCoords,
423
+ transportInfo,
424
+ steps: stepsBuilder.build()
425
+ });
426
+ legs.push(leg);
427
+ }
428
+
429
+ const itinerary = new Itinerary({
430
+ duration: jsonItinerary.duration,
431
+ startTime: dateStringToTimestamp(jsonItinerary.departure_date_time, timeZone),
432
+ endTime: dateStringToTimestamp(jsonItinerary.arrival_date_time, timeZone),
433
+ origin: this.getSectionCoords(jsonItinerary.sections[0]).from,
434
+ destination: this.getSectionCoords(last(jsonItinerary.sections)).to,
435
+ legs
436
+ });
437
+
438
+ itineraries.push(itinerary);
439
+ }
440
+
441
+ return itineraries;
442
+ }
443
+ }
444
+
445
+ export default new NavitiaRemoteRouter();