@ingissa/navcore-mapbox 1.0.3 → 1.0.4

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.
@@ -0,0 +1,49 @@
1
+ import { DirectionsOptions, DirectionsProvider, Coordinate, DirectionsResult } from '@ingissa/navcore-core';
2
+
3
+ /**
4
+ * MapboxDirectionsProvider
5
+ *
6
+ * Implements DirectionsProvider using the Mapbox Directions API.
7
+ * Handles waypoint chunking internally for routes with >25 waypoints.
8
+ */
9
+
10
+ type MapboxProfile = 'driving' | 'driving-traffic' | 'cycling' | 'walking';
11
+ interface MapboxDirectionsConfig {
12
+ /** Mapbox access token */
13
+ accessToken: string;
14
+ /** Routing profile (default: 'driving') */
15
+ profile?: MapboxProfile;
16
+ /** API base URL (default: Mapbox production) */
17
+ baseUrl?: string;
18
+ /** Max waypoints per API call (default: 25, Mapbox limit) */
19
+ maxWaypointsPerChunk?: number;
20
+ /** Optional fetch implementation for tests, React Native, or custom runtimes */
21
+ fetchFn?: typeof fetch;
22
+ /** Request timeout in milliseconds. Set to 0 to disable. */
23
+ timeoutMs?: number;
24
+ }
25
+ type MapboxDirectionsOptions = Omit<DirectionsOptions, 'profile'> & {
26
+ profile?: MapboxProfile;
27
+ geometries?: 'geojson';
28
+ overview?: 'full' | 'simplified' | 'false';
29
+ };
30
+ declare class MapboxDirectionsProvider implements DirectionsProvider {
31
+ private readonly config;
32
+ constructor(config: MapboxDirectionsConfig);
33
+ /**
34
+ * Get a route through the given waypoints.
35
+ * Automatically chunks if waypoints exceed the Mapbox limit.
36
+ */
37
+ getRoute(waypoints: Coordinate[], options?: MapboxDirectionsOptions): Promise<DirectionsResult>;
38
+ /**
39
+ * Fetch a single route segment from the Mapbox API.
40
+ */
41
+ private fetchRoute;
42
+ /**
43
+ * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
44
+ */
45
+ private fetchChunkedRoute;
46
+ private fetchWithTimeout;
47
+ }
48
+
49
+ export { type MapboxDirectionsConfig, type MapboxDirectionsOptions, MapboxDirectionsProvider };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,49 @@
1
+ import { DirectionsOptions, DirectionsProvider, Coordinate, DirectionsResult } from '@ingissa/navcore-core';
2
+
1
3
  /**
2
- * @navcore/mapbox — Mapbox GL adapters
4
+ * MapboxDirectionsProvider
3
5
  *
4
- * Provides NavCoreRenderer and DirectionsProvider implementations
5
- * for Mapbox GL (via @rnmapbox/maps for React Native, or mapbox-gl for web).
6
+ * Implements DirectionsProvider using the Mapbox Directions API.
7
+ * Handles waypoint chunking internally for routes with >25 waypoints.
6
8
  */
7
- export { MapboxDirectionsProvider } from './MapboxDirectionsProvider';
8
- export type { MapboxDirectionsConfig } from './MapboxDirectionsProvider';
9
- //# sourceMappingURL=index.d.ts.map
9
+
10
+ type MapboxProfile = 'driving' | 'driving-traffic' | 'cycling' | 'walking';
11
+ interface MapboxDirectionsConfig {
12
+ /** Mapbox access token */
13
+ accessToken: string;
14
+ /** Routing profile (default: 'driving') */
15
+ profile?: MapboxProfile;
16
+ /** API base URL (default: Mapbox production) */
17
+ baseUrl?: string;
18
+ /** Max waypoints per API call (default: 25, Mapbox limit) */
19
+ maxWaypointsPerChunk?: number;
20
+ /** Optional fetch implementation for tests, React Native, or custom runtimes */
21
+ fetchFn?: typeof fetch;
22
+ /** Request timeout in milliseconds. Set to 0 to disable. */
23
+ timeoutMs?: number;
24
+ }
25
+ type MapboxDirectionsOptions = Omit<DirectionsOptions, 'profile'> & {
26
+ profile?: MapboxProfile;
27
+ geometries?: 'geojson';
28
+ overview?: 'full' | 'simplified' | 'false';
29
+ };
30
+ declare class MapboxDirectionsProvider implements DirectionsProvider {
31
+ private readonly config;
32
+ constructor(config: MapboxDirectionsConfig);
33
+ /**
34
+ * Get a route through the given waypoints.
35
+ * Automatically chunks if waypoints exceed the Mapbox limit.
36
+ */
37
+ getRoute(waypoints: Coordinate[], options?: MapboxDirectionsOptions): Promise<DirectionsResult>;
38
+ /**
39
+ * Fetch a single route segment from the Mapbox API.
40
+ */
41
+ private fetchRoute;
42
+ /**
43
+ * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
44
+ */
45
+ private fetchChunkedRoute;
46
+ private fetchWithTimeout;
47
+ }
48
+
49
+ export { type MapboxDirectionsConfig, type MapboxDirectionsOptions, MapboxDirectionsProvider };
package/dist/index.js CHANGED
@@ -1,7 +1,146 @@
1
- /**
2
- * @navcore/mapbox — Mapbox GL adapters
3
- *
4
- * Provides NavCoreRenderer and DirectionsProvider implementations
5
- * for Mapbox GL (via @rnmapbox/maps for React Native, or mapbox-gl for web).
6
- */
7
- export { MapboxDirectionsProvider } from './MapboxDirectionsProvider';
1
+ 'use strict';
2
+
3
+ // src/MapboxDirectionsProvider.ts
4
+ var DEFAULT_BASE_URL = "https://api.mapbox.com/directions/v5/mapbox";
5
+ var MAX_WAYPOINTS = 25;
6
+ var DEFAULT_TIMEOUT_MS = 15e3;
7
+ var MapboxDirectionsProvider = class {
8
+ constructor(config) {
9
+ const fetchFn = config.fetchFn ?? globalThis.fetch?.bind(globalThis);
10
+ if (!fetchFn) {
11
+ throw new Error("[Mapbox] fetch is not available. Pass config.fetchFn in this runtime.");
12
+ }
13
+ this.config = {
14
+ accessToken: config.accessToken,
15
+ profile: config.profile ?? "driving",
16
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
17
+ maxWaypointsPerChunk: config.maxWaypointsPerChunk ?? MAX_WAYPOINTS,
18
+ fetchFn,
19
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS
20
+ };
21
+ }
22
+ /**
23
+ * Get a route through the given waypoints.
24
+ * Automatically chunks if waypoints exceed the Mapbox limit.
25
+ */
26
+ async getRoute(waypoints, options) {
27
+ if (waypoints.length < 2) {
28
+ throw new Error("At least 2 waypoints are required");
29
+ }
30
+ if (waypoints.length <= this.config.maxWaypointsPerChunk) {
31
+ return this.fetchRoute(waypoints, options);
32
+ }
33
+ return this.fetchChunkedRoute(waypoints, options);
34
+ }
35
+ /**
36
+ * Fetch a single route segment from the Mapbox API.
37
+ */
38
+ async fetchRoute(waypoints, options) {
39
+ const profile = options?.profile ?? this.config.profile;
40
+ const coords = waypoints.map((w) => `${w[0]},${w[1]}`).join(";");
41
+ const params = new URLSearchParams({
42
+ access_token: this.config.accessToken,
43
+ geometries: options?.geometries ?? "geojson",
44
+ overview: options?.overview ?? "full",
45
+ steps: String(options?.steps ?? true),
46
+ alternatives: String(options?.alternatives ?? false)
47
+ });
48
+ if (options?.language) {
49
+ params.set("language", options.language);
50
+ }
51
+ const url = `${this.config.baseUrl}/${profile}/${coords}?${params}`;
52
+ const response = await this.fetchWithTimeout(url);
53
+ if (!response.ok) {
54
+ const text = await response.text();
55
+ throw new Error(`[Mapbox] HTTP ${response.status}: ${text || response.statusText}`);
56
+ }
57
+ const data = await response.json();
58
+ if (!data.routes || data.routes.length === 0) {
59
+ throw new Error("No route found");
60
+ }
61
+ const route = data.routes[0];
62
+ return {
63
+ geometry: route.geometry.coordinates,
64
+ distance: route.distance,
65
+ duration: route.duration,
66
+ legs: route.legs.map((leg) => ({
67
+ distance: leg.distance,
68
+ duration: leg.duration,
69
+ steps: leg.steps?.map((step) => ({
70
+ distance: step.distance,
71
+ duration: step.duration,
72
+ geometry: step.geometry?.coordinates ?? [],
73
+ maneuver: {
74
+ type: step.maneuver?.type ?? "unknown",
75
+ modifier: step.maneuver?.modifier,
76
+ location: step.maneuver?.location ?? [0, 0],
77
+ bearingBefore: step.maneuver?.bearing_before ?? 0,
78
+ bearingAfter: step.maneuver?.bearing_after ?? 0,
79
+ instruction: step.maneuver?.instruction
80
+ },
81
+ name: step.name
82
+ }))
83
+ })),
84
+ raw: data
85
+ };
86
+ }
87
+ /**
88
+ * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
89
+ */
90
+ async fetchChunkedRoute(waypoints, options) {
91
+ const chunkSize = this.config.maxWaypointsPerChunk;
92
+ const step = chunkSize - 1;
93
+ const chunks = [];
94
+ for (let i = 0; i < waypoints.length; i += step) {
95
+ const chunk = waypoints.slice(i, i + chunkSize);
96
+ if (chunk.length < 2) break;
97
+ chunks.push(chunk);
98
+ if (i + chunkSize >= waypoints.length) break;
99
+ }
100
+ const results = await Promise.all(
101
+ chunks.map((chunk) => this.fetchRoute(chunk, options))
102
+ );
103
+ const stitchedGeometry = [];
104
+ let totalDistance = 0;
105
+ let totalDuration = 0;
106
+ const allLegs = [];
107
+ for (let i = 0; i < results.length; i++) {
108
+ const result = results[i];
109
+ const geom = result.geometry;
110
+ if (i === 0) {
111
+ stitchedGeometry.push(...geom);
112
+ } else {
113
+ stitchedGeometry.push(...geom.slice(1));
114
+ }
115
+ totalDistance += result.distance;
116
+ totalDuration += result.duration;
117
+ allLegs.push(...result.legs);
118
+ }
119
+ return {
120
+ geometry: stitchedGeometry,
121
+ distance: totalDistance,
122
+ duration: totalDuration,
123
+ legs: allLegs,
124
+ raw: results.map((r) => r.raw)
125
+ };
126
+ }
127
+ async fetchWithTimeout(url, init) {
128
+ if (this.config.timeoutMs <= 0 || typeof AbortController === "undefined") {
129
+ return this.config.fetchFn(url, init);
130
+ }
131
+ const controller = new AbortController();
132
+ const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs);
133
+ try {
134
+ return await this.config.fetchFn(url, { ...init, signal: controller.signal });
135
+ } catch (error) {
136
+ if (error.name === "AbortError") {
137
+ throw new Error(`[Mapbox] Request timed out after ${this.config.timeoutMs}ms`);
138
+ }
139
+ throw error;
140
+ } finally {
141
+ clearTimeout(timeout);
142
+ }
143
+ }
144
+ };
145
+
146
+ exports.MapboxDirectionsProvider = MapboxDirectionsProvider;
package/dist/index.mjs ADDED
@@ -0,0 +1,144 @@
1
+ // src/MapboxDirectionsProvider.ts
2
+ var DEFAULT_BASE_URL = "https://api.mapbox.com/directions/v5/mapbox";
3
+ var MAX_WAYPOINTS = 25;
4
+ var DEFAULT_TIMEOUT_MS = 15e3;
5
+ var MapboxDirectionsProvider = class {
6
+ constructor(config) {
7
+ const fetchFn = config.fetchFn ?? globalThis.fetch?.bind(globalThis);
8
+ if (!fetchFn) {
9
+ throw new Error("[Mapbox] fetch is not available. Pass config.fetchFn in this runtime.");
10
+ }
11
+ this.config = {
12
+ accessToken: config.accessToken,
13
+ profile: config.profile ?? "driving",
14
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
15
+ maxWaypointsPerChunk: config.maxWaypointsPerChunk ?? MAX_WAYPOINTS,
16
+ fetchFn,
17
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS
18
+ };
19
+ }
20
+ /**
21
+ * Get a route through the given waypoints.
22
+ * Automatically chunks if waypoints exceed the Mapbox limit.
23
+ */
24
+ async getRoute(waypoints, options) {
25
+ if (waypoints.length < 2) {
26
+ throw new Error("At least 2 waypoints are required");
27
+ }
28
+ if (waypoints.length <= this.config.maxWaypointsPerChunk) {
29
+ return this.fetchRoute(waypoints, options);
30
+ }
31
+ return this.fetchChunkedRoute(waypoints, options);
32
+ }
33
+ /**
34
+ * Fetch a single route segment from the Mapbox API.
35
+ */
36
+ async fetchRoute(waypoints, options) {
37
+ const profile = options?.profile ?? this.config.profile;
38
+ const coords = waypoints.map((w) => `${w[0]},${w[1]}`).join(";");
39
+ const params = new URLSearchParams({
40
+ access_token: this.config.accessToken,
41
+ geometries: options?.geometries ?? "geojson",
42
+ overview: options?.overview ?? "full",
43
+ steps: String(options?.steps ?? true),
44
+ alternatives: String(options?.alternatives ?? false)
45
+ });
46
+ if (options?.language) {
47
+ params.set("language", options.language);
48
+ }
49
+ const url = `${this.config.baseUrl}/${profile}/${coords}?${params}`;
50
+ const response = await this.fetchWithTimeout(url);
51
+ if (!response.ok) {
52
+ const text = await response.text();
53
+ throw new Error(`[Mapbox] HTTP ${response.status}: ${text || response.statusText}`);
54
+ }
55
+ const data = await response.json();
56
+ if (!data.routes || data.routes.length === 0) {
57
+ throw new Error("No route found");
58
+ }
59
+ const route = data.routes[0];
60
+ return {
61
+ geometry: route.geometry.coordinates,
62
+ distance: route.distance,
63
+ duration: route.duration,
64
+ legs: route.legs.map((leg) => ({
65
+ distance: leg.distance,
66
+ duration: leg.duration,
67
+ steps: leg.steps?.map((step) => ({
68
+ distance: step.distance,
69
+ duration: step.duration,
70
+ geometry: step.geometry?.coordinates ?? [],
71
+ maneuver: {
72
+ type: step.maneuver?.type ?? "unknown",
73
+ modifier: step.maneuver?.modifier,
74
+ location: step.maneuver?.location ?? [0, 0],
75
+ bearingBefore: step.maneuver?.bearing_before ?? 0,
76
+ bearingAfter: step.maneuver?.bearing_after ?? 0,
77
+ instruction: step.maneuver?.instruction
78
+ },
79
+ name: step.name
80
+ }))
81
+ })),
82
+ raw: data
83
+ };
84
+ }
85
+ /**
86
+ * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
87
+ */
88
+ async fetchChunkedRoute(waypoints, options) {
89
+ const chunkSize = this.config.maxWaypointsPerChunk;
90
+ const step = chunkSize - 1;
91
+ const chunks = [];
92
+ for (let i = 0; i < waypoints.length; i += step) {
93
+ const chunk = waypoints.slice(i, i + chunkSize);
94
+ if (chunk.length < 2) break;
95
+ chunks.push(chunk);
96
+ if (i + chunkSize >= waypoints.length) break;
97
+ }
98
+ const results = await Promise.all(
99
+ chunks.map((chunk) => this.fetchRoute(chunk, options))
100
+ );
101
+ const stitchedGeometry = [];
102
+ let totalDistance = 0;
103
+ let totalDuration = 0;
104
+ const allLegs = [];
105
+ for (let i = 0; i < results.length; i++) {
106
+ const result = results[i];
107
+ const geom = result.geometry;
108
+ if (i === 0) {
109
+ stitchedGeometry.push(...geom);
110
+ } else {
111
+ stitchedGeometry.push(...geom.slice(1));
112
+ }
113
+ totalDistance += result.distance;
114
+ totalDuration += result.duration;
115
+ allLegs.push(...result.legs);
116
+ }
117
+ return {
118
+ geometry: stitchedGeometry,
119
+ distance: totalDistance,
120
+ duration: totalDuration,
121
+ legs: allLegs,
122
+ raw: results.map((r) => r.raw)
123
+ };
124
+ }
125
+ async fetchWithTimeout(url, init) {
126
+ if (this.config.timeoutMs <= 0 || typeof AbortController === "undefined") {
127
+ return this.config.fetchFn(url, init);
128
+ }
129
+ const controller = new AbortController();
130
+ const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs);
131
+ try {
132
+ return await this.config.fetchFn(url, { ...init, signal: controller.signal });
133
+ } catch (error) {
134
+ if (error.name === "AbortError") {
135
+ throw new Error(`[Mapbox] Request timed out after ${this.config.timeoutMs}ms`);
136
+ }
137
+ throw error;
138
+ } finally {
139
+ clearTimeout(timeout);
140
+ }
141
+ }
142
+ };
143
+
144
+ export { MapboxDirectionsProvider };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ingissa/navcore-mapbox",
3
- "version": "1.0.3",
4
- "description": "Mapbox GL adapter for NavCore — renderer and directions provider.",
3
+ "version": "1.0.4",
4
+ "description": "Mapbox GL adapter for NavCore - renderer and directions provider.",
5
5
  "author": "Ingissa <8abnav@gmail.com>",
6
6
  "license": "Commercial",
7
7
  "homepage": "https://navcore-web.vercel.app/",
@@ -17,28 +17,33 @@
17
17
  "types": "dist/index.d.ts",
18
18
  "exports": {
19
19
  ".": {
20
+ "types": "./dist/index.d.ts",
20
21
  "import": "./dist/index.mjs",
21
- "require": "./dist/index.js",
22
- "types": "./dist/index.d.ts"
22
+ "require": "./dist/index.js"
23
23
  }
24
24
  },
25
- "files": ["dist"],
25
+ "files": [
26
+ "dist"
27
+ ],
26
28
  "sideEffects": false,
27
29
  "publishConfig": {
28
30
  "access": "public"
29
31
  },
30
- "engines": { "node": ">=18" },
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
31
35
  "scripts": {
32
- "build": "tsc -p tsconfig.build.json",
36
+ "build": "tsup",
33
37
  "lint": "tsc --noEmit",
34
38
  "prepublishOnly": "npm run build"
35
39
  },
36
40
  "peerDependencies": {
37
- "@ingissa/navcore-core": "^1.0.3",
41
+ "@ingissa/navcore-core": "^1.0.4",
38
42
  "@rnmapbox/maps": ">=10.0.0"
39
43
  },
40
44
  "peerDependenciesMeta": {
41
- "@rnmapbox/maps": { "optional": true }
42
- },
43
- "dependencies": {}
45
+ "@rnmapbox/maps": {
46
+ "optional": true
47
+ }
48
+ }
44
49
  }
@@ -1,68 +0,0 @@
1
- /**
2
- * MapboxDirectionsProvider
3
- *
4
- * Implements DirectionsProvider using the Mapbox Directions API.
5
- * Handles waypoint chunking internally for routes with >25 waypoints.
6
- */
7
- type Coordinate = [number, number];
8
- export interface MapboxDirectionsConfig {
9
- /** Mapbox access token */
10
- accessToken: string;
11
- /** Routing profile (default: 'driving') */
12
- profile?: 'driving' | 'driving-traffic' | 'cycling' | 'walking';
13
- /** API base URL (default: Mapbox production) */
14
- baseUrl?: string;
15
- /** Max waypoints per API call (default: 25, Mapbox limit) */
16
- maxWaypointsPerChunk?: number;
17
- }
18
- interface RouteResult {
19
- geometry: Coordinate[];
20
- distance: number;
21
- duration: number;
22
- legs: Array<{
23
- distance: number;
24
- duration: number;
25
- steps?: Array<{
26
- distance: number;
27
- duration: number;
28
- geometry: Coordinate[];
29
- maneuver: {
30
- type: string;
31
- modifier?: string;
32
- location: Coordinate;
33
- bearing_before: number;
34
- bearing_after: number;
35
- instruction?: string;
36
- };
37
- name?: string;
38
- }>;
39
- }>;
40
- raw?: unknown;
41
- }
42
- interface RouteOptions {
43
- profile?: string;
44
- alternatives?: boolean;
45
- steps?: boolean;
46
- geometries?: string;
47
- overview?: string;
48
- language?: string;
49
- }
50
- export declare class MapboxDirectionsProvider {
51
- private readonly config;
52
- constructor(config: MapboxDirectionsConfig);
53
- /**
54
- * Get a route through the given waypoints.
55
- * Automatically chunks if waypoints exceed the Mapbox limit.
56
- */
57
- getRoute(waypoints: Coordinate[], options?: RouteOptions): Promise<RouteResult>;
58
- /**
59
- * Fetch a single route segment from the Mapbox API.
60
- */
61
- private fetchRoute;
62
- /**
63
- * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
64
- */
65
- private fetchChunkedRoute;
66
- }
67
- export {};
68
- //# sourceMappingURL=MapboxDirectionsProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MapboxDirectionsProvider.d.ts","sourceRoot":"","sources":["../src/MapboxDirectionsProvider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,KAAK,UAAU,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEnC,MAAM,WAAW,sBAAsB;IACrC,0BAA0B;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,2CAA2C;IAC3C,OAAO,CAAC,EAAE,SAAS,GAAG,iBAAiB,GAAG,SAAS,GAAG,SAAS,CAAC;IAChE,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6DAA6D;IAC7D,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,UAAU,WAAW;IACnB,QAAQ,EAAE,UAAU,EAAE,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,KAAK,CAAC;QACV,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,EAAE,MAAM,CAAC;QACjB,KAAK,CAAC,EAAE,KAAK,CAAC;YACZ,QAAQ,EAAE,MAAM,CAAC;YACjB,QAAQ,EAAE,MAAM,CAAC;YACjB,QAAQ,EAAE,UAAU,EAAE,CAAC;YACvB,QAAQ,EAAE;gBACR,IAAI,EAAE,MAAM,CAAC;gBACb,QAAQ,CAAC,EAAE,MAAM,CAAC;gBAClB,QAAQ,EAAE,UAAU,CAAC;gBACrB,cAAc,EAAE,MAAM,CAAC;gBACvB,aAAa,EAAE,MAAM,CAAC;gBACtB,WAAW,CAAC,EAAE,MAAM,CAAC;aACtB,CAAC;YACF,IAAI,CAAC,EAAE,MAAM,CAAC;SACf,CAAC,CAAC;KACJ,CAAC,CAAC;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED,UAAU,YAAY;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAKD,qBAAa,wBAAwB;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;gBAE9C,MAAM,EAAE,sBAAsB;IAS1C;;;OAGG;IACG,QAAQ,CAAC,SAAS,EAAE,UAAU,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC;IAcrF;;OAEG;YACW,UAAU;IAyDxB;;OAEG;YACW,iBAAiB;CA+ChC"}
@@ -1,128 +0,0 @@
1
- /**
2
- * MapboxDirectionsProvider
3
- *
4
- * Implements DirectionsProvider using the Mapbox Directions API.
5
- * Handles waypoint chunking internally for routes with >25 waypoints.
6
- */
7
- const DEFAULT_BASE_URL = 'https://api.mapbox.com/directions/v5/mapbox';
8
- const MAX_WAYPOINTS = 25;
9
- export class MapboxDirectionsProvider {
10
- constructor(config) {
11
- this.config = {
12
- accessToken: config.accessToken,
13
- profile: config.profile ?? 'driving',
14
- baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
15
- maxWaypointsPerChunk: config.maxWaypointsPerChunk ?? MAX_WAYPOINTS,
16
- };
17
- }
18
- /**
19
- * Get a route through the given waypoints.
20
- * Automatically chunks if waypoints exceed the Mapbox limit.
21
- */
22
- async getRoute(waypoints, options) {
23
- if (waypoints.length < 2) {
24
- throw new Error('At least 2 waypoints are required');
25
- }
26
- // If within limit, single request
27
- if (waypoints.length <= this.config.maxWaypointsPerChunk) {
28
- return this.fetchRoute(waypoints, options);
29
- }
30
- // Otherwise chunk with OVERLAP_1 strategy
31
- return this.fetchChunkedRoute(waypoints, options);
32
- }
33
- /**
34
- * Fetch a single route segment from the Mapbox API.
35
- */
36
- async fetchRoute(waypoints, options) {
37
- const profile = options?.profile ?? this.config.profile;
38
- const coords = waypoints.map(w => `${w[0]},${w[1]}`).join(';');
39
- const params = new URLSearchParams({
40
- access_token: this.config.accessToken,
41
- geometries: options?.geometries ?? 'geojson',
42
- overview: options?.overview ?? 'full',
43
- steps: String(options?.steps ?? true),
44
- alternatives: String(options?.alternatives ?? false),
45
- });
46
- if (options?.language) {
47
- params.set('language', options.language);
48
- }
49
- const url = `${this.config.baseUrl}/${profile}/${coords}?${params}`;
50
- const response = await fetch(url);
51
- if (!response.ok) {
52
- throw new Error(`Mapbox API error: ${response.status} ${response.statusText}`);
53
- }
54
- const data = await response.json();
55
- if (!data.routes || data.routes.length === 0) {
56
- throw new Error('No route found');
57
- }
58
- const route = data.routes[0];
59
- return {
60
- geometry: route.geometry.coordinates,
61
- distance: route.distance,
62
- duration: route.duration,
63
- legs: route.legs.map((leg) => ({
64
- distance: leg.distance,
65
- duration: leg.duration,
66
- steps: leg.steps?.map((step) => ({
67
- distance: step.distance,
68
- duration: step.duration,
69
- geometry: step.geometry?.coordinates ?? [],
70
- maneuver: {
71
- type: step.maneuver?.type ?? 'unknown',
72
- modifier: step.maneuver?.modifier,
73
- location: step.maneuver?.location ?? [0, 0],
74
- bearing_before: step.maneuver?.bearing_before ?? 0,
75
- bearing_after: step.maneuver?.bearing_after ?? 0,
76
- instruction: step.maneuver?.instruction,
77
- },
78
- name: step.name,
79
- })),
80
- })),
81
- raw: data,
82
- };
83
- }
84
- /**
85
- * Fetch multi-segment route, stitching chunks with OVERLAP_1 strategy.
86
- */
87
- async fetchChunkedRoute(waypoints, options) {
88
- const chunkSize = this.config.maxWaypointsPerChunk;
89
- const step = chunkSize - 1; // OVERLAP_1
90
- const chunks = [];
91
- for (let i = 0; i < waypoints.length; i += step) {
92
- const chunk = waypoints.slice(i, i + chunkSize);
93
- if (chunk.length < 2)
94
- break;
95
- chunks.push(chunk);
96
- if (i + chunkSize >= waypoints.length)
97
- break;
98
- }
99
- // Fetch all chunks in parallel
100
- const results = await Promise.all(chunks.map(chunk => this.fetchRoute(chunk, options)));
101
- // Stitch geometries — drop first point of subsequent chunks (it's the overlap)
102
- const stitchedGeometry = [];
103
- let totalDistance = 0;
104
- let totalDuration = 0;
105
- const allLegs = [];
106
- for (let i = 0; i < results.length; i++) {
107
- const result = results[i];
108
- const geom = result.geometry;
109
- if (i === 0) {
110
- stitchedGeometry.push(...geom);
111
- }
112
- else {
113
- // Skip first point (overlap with previous chunk's last point)
114
- stitchedGeometry.push(...geom.slice(1));
115
- }
116
- totalDistance += result.distance;
117
- totalDuration += result.duration;
118
- allLegs.push(...result.legs);
119
- }
120
- return {
121
- geometry: stitchedGeometry,
122
- distance: totalDistance,
123
- duration: totalDuration,
124
- legs: allLegs,
125
- raw: results.map(r => r.raw),
126
- };
127
- }
128
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,YAAY,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC"}