hg-map-sdk 0.0.0-stage → 1.0.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.
- package/README.md +128 -2
- package/index.d.ts +279 -0
- package/index.js +4 -0
- package/package.json +32 -4
- package/src/client.js +116 -0
- package/src/errors.js +33 -0
- package/src/mapClient.js +106 -0
package/README.md
CHANGED
|
@@ -1,3 +1,129 @@
|
|
|
1
|
-
#
|
|
1
|
+
# hg-map-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Client for Mummy's Dabba **map-service** (`mesh-service/map-osrm`): road routing and ETAs, trip
|
|
4
|
+
optimization, geocoding (address ⇄ lat/lng, search-as-you-type) and India PIN codes.
|
|
5
|
+
|
|
6
|
+
Answers are in our own format whatever map provider runs behind the service (OSRM / Photon /
|
|
7
|
+
Nominatim today; Google, Ola Maps or Mappls later). Code that uses this SDK never changes when the
|
|
8
|
+
provider does:
|
|
9
|
+
- points are `{ lat, lng }`
|
|
10
|
+
- distances are metres
|
|
11
|
+
- durations are seconds
|
|
12
|
+
|
|
13
|
+
Node 18+, no dependencies, TypeScript types included.
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
1. Give your service its own key on map-service:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
cd mesh-service/map-osrm/map-service
|
|
21
|
+
npm run clients -- create user-backend # prints the key once
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
2. Add it to your service's env:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
MAP_SERVICE_URL=http://map-service:4120/api/v1/maps
|
|
28
|
+
MAP_SERVICE_API_KEY=mk_…
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
3. Create one client per process and reuse it:
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
const { createMapClient, MapServiceError } = require("hg-map-sdk");
|
|
35
|
+
|
|
36
|
+
const map = createMapClient({
|
|
37
|
+
baseUrl: process.env.MAP_SERVICE_URL,
|
|
38
|
+
apiKey: process.env.MAP_SERVICE_API_KEY,
|
|
39
|
+
// timeoutMs: 8000, retries: 1
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Methods
|
|
44
|
+
|
|
45
|
+
| Method | Returns |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `eta({ from, to, profile?, departAt? })` | `{ distance_m, duration_s, eta }` |
|
|
48
|
+
| `route({ points, profile?, geometry?, alternatives? })` | Distance, time, legs, GeoJSON line |
|
|
49
|
+
| `matrix({ sources, destinations?, profile? })` | `durations[][]`, `distances[][]` (null = unreachable) |
|
|
50
|
+
| `nearest({ point, profile? })` | The point snapped to the nearest road |
|
|
51
|
+
| `optimizeTrip({ start, end?, stops, profile?, departAt?, geometry? })` | Stops in visit order with ETAs |
|
|
52
|
+
| `reverse({ point, language? })` | `{ place, provider, cache }`: the address at a GPS point |
|
|
53
|
+
| `search({ query, near?, limit?, language? })` | `{ results, provider, cache }` |
|
|
54
|
+
| `autocomplete({ query, near?, limit?, language? })` | Suggestions while the user types |
|
|
55
|
+
| `pincode(pin, { geometry? })` | Official PIN details (+ boundary GeoJSON) |
|
|
56
|
+
| `locatePincode({ point })` | Which PIN a point is in |
|
|
57
|
+
| `pincodesWithin({ center, radiusM })` | Every PIN a radius reaches, with `share_inside` |
|
|
58
|
+
| `clientConfig()` | What an app's map should draw (tiles provider, renderer, style URL) |
|
|
59
|
+
| `health()` | `{ status: "OK" \| "DEGRADED", … }`, without throwing on DEGRADED |
|
|
60
|
+
|
|
61
|
+
Profiles: `bike` (default, scooter or motorcycle) and `bicycle`.
|
|
62
|
+
|
|
63
|
+
`place.components.pincode` always comes from the **official India Post boundaries**, not the map
|
|
64
|
+
provider. PIN data is under the Government Open Data Licence – India. Show the `attribution` string
|
|
65
|
+
from the PIN-code answers wherever you display that data.
|
|
66
|
+
|
|
67
|
+
## Examples
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
// Is this customer within 10 km (by road) of the kitchen?
|
|
71
|
+
const { distance_m } = await map.eta({ from: kitchen, to: customer });
|
|
72
|
+
const serviceable = distance_m <= 10000;
|
|
73
|
+
|
|
74
|
+
// GPS at app start → city + PIN
|
|
75
|
+
const { place } = await map.reverse({ point: { lat: 26.4842, lng: 80.311 } });
|
|
76
|
+
// place.components → { city: "Kanpur", pincode: "208002", … }
|
|
77
|
+
|
|
78
|
+
// Which PINs to offer home delivery in
|
|
79
|
+
const { pincodes } = await map.pincodesWithin({ center: kitchen, radiusM: 10000 });
|
|
80
|
+
const mostlyInside = pincodes.filter((p) => p.share_inside >= 0.5).map((p) => p.pincode);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Errors
|
|
84
|
+
|
|
85
|
+
Every failure is a `MapServiceError` with:
|
|
86
|
+
- `code`: map-service's own code, or `NETWORK_ERROR` / `TIMEOUT`
|
|
87
|
+
- `status`: the HTTP status, or `null` if map-service wasn't reached
|
|
88
|
+
- `details`
|
|
89
|
+
- `retryAfterS`
|
|
90
|
+
- `retryable`
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
try {
|
|
94
|
+
await map.eta({ from, to });
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (err instanceof MapServiceError && err.code === "POINT_OUTSIDE_COVERAGE") {
|
|
97
|
+
// address outside the map region we serve
|
|
98
|
+
}
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
| `code` | Meaning |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `INVALID_API_KEY` (401) | Missing, unknown or revoked key |
|
|
106
|
+
| `RATE_LIMITED` (429) | This service is over its per-minute limit |
|
|
107
|
+
| `POINT_OUTSIDE_COVERAGE` / `NO_ROUTE` (422) | Not reachable by road in the loaded map |
|
|
108
|
+
| `PINCODE_NOT_FOUND` (404) | No such PIN |
|
|
109
|
+
| `INVALID_*` (400) | Bad input; `details` says which field |
|
|
110
|
+
| `PROVIDER_UNAVAILABLE` / `GEOCODING_UNAVAILABLE` (503) | Engine down / no geocoder configured |
|
|
111
|
+
| `NETWORK_ERROR`, `TIMEOUT` | map-service not reachable or too slow |
|
|
112
|
+
|
|
113
|
+
**Retries:** network errors, timeouts and 5xx are retried `retries` times (default 1), with
|
|
114
|
+
backoff. This is safe because every map-service endpoint only reads. A `429` is retried only when
|
|
115
|
+
`Retry-After` is at most `maxRetryAfterS` (2 s); otherwise it is thrown at once. 4xx errors are
|
|
116
|
+
never retried.
|
|
117
|
+
|
|
118
|
+
## Develop
|
|
119
|
+
|
|
120
|
+
The SDK lives in the map-service repo (`sdk/`), next to the API it calls, so an API change
|
|
121
|
+
and its SDK change land in one PR. Only this folder is published; the `files` list in
|
|
122
|
+
`package.json` limits the package to `index.js`, `index.d.ts`, `src/` and this README.
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
cd sdk
|
|
126
|
+
npm test # against a fake map-service; no engines needed
|
|
127
|
+
npm pack --dry-run # shows exactly what would be published
|
|
128
|
+
npm publish # from sdk/ only, after bumping `version` (npm account: satyamsonker1010)
|
|
129
|
+
```
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Types for hg-map-sdk — client for Mummy's Dabba map-service (/api/v1/maps).
|
|
2
|
+
// Points are { lat, lng }; distances are metres; durations are seconds.
|
|
3
|
+
|
|
4
|
+
export interface LatLng {
|
|
5
|
+
lat: number;
|
|
6
|
+
lng: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface MapClientOptions {
|
|
10
|
+
/** e.g. "http://map-service:4120/api/v1/maps" */
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
/** This service's own key (map-service: npm run clients -- create <name>). */
|
|
13
|
+
apiKey: string;
|
|
14
|
+
/** Per attempt. Default 8000. */
|
|
15
|
+
timeoutMs?: number;
|
|
16
|
+
/** Extra attempts on network errors, timeouts, 5xx and short 429s. Default 1. */
|
|
17
|
+
retries?: number;
|
|
18
|
+
/** First backoff; doubles each retry. Default 200. */
|
|
19
|
+
retryDelayMs?: number;
|
|
20
|
+
/** A 429 is retried only if Retry-After is at most this. Default 2. */
|
|
21
|
+
maxRetryAfterS?: number;
|
|
22
|
+
/** Custom fetch (tests, proxies). Default: global fetch (Node 18+). */
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
userAgent?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type ErrorCode =
|
|
28
|
+
| "NETWORK_ERROR"
|
|
29
|
+
| "TIMEOUT"
|
|
30
|
+
| "INVALID_API_KEY"
|
|
31
|
+
| "RATE_LIMITED"
|
|
32
|
+
| "INVALID_POINT"
|
|
33
|
+
| "INVALID_POINTS"
|
|
34
|
+
| "INVALID_STOPS"
|
|
35
|
+
| "INVALID_PROFILE"
|
|
36
|
+
| "INVALID_DEPART_AT"
|
|
37
|
+
| "INVALID_PRECEDENCE"
|
|
38
|
+
| "INVALID_QUERY"
|
|
39
|
+
| "INVALID_LIMIT"
|
|
40
|
+
| "INVALID_LANGUAGE"
|
|
41
|
+
| "INVALID_PINCODE"
|
|
42
|
+
| "INVALID_RADIUS"
|
|
43
|
+
| "PROFILE_UNAVAILABLE"
|
|
44
|
+
| "POINT_OUTSIDE_COVERAGE"
|
|
45
|
+
| "NO_ROUTE"
|
|
46
|
+
| "PINCODE_NOT_FOUND"
|
|
47
|
+
| "PINCODES_UNAVAILABLE"
|
|
48
|
+
| "GEOCODING_UNAVAILABLE"
|
|
49
|
+
| "PROVIDER_UNAVAILABLE"
|
|
50
|
+
| "PROVIDER_REJECTED"
|
|
51
|
+
| (string & {});
|
|
52
|
+
|
|
53
|
+
export class MapServiceError extends Error {
|
|
54
|
+
name: "MapServiceError";
|
|
55
|
+
code: ErrorCode;
|
|
56
|
+
/** HTTP status, null when map-service wasn't reached. */
|
|
57
|
+
status: number | null;
|
|
58
|
+
details: unknown;
|
|
59
|
+
retryAfterS: number | null;
|
|
60
|
+
/** Network error, timeout, 5xx or 429. */
|
|
61
|
+
readonly retryable: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── Routing ────────────────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
export interface LineString {
|
|
67
|
+
type: "LineString";
|
|
68
|
+
coordinates: [number, number][];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface Leg {
|
|
72
|
+
distance_m: number;
|
|
73
|
+
duration_s: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface EtaResult {
|
|
77
|
+
profile: string;
|
|
78
|
+
distance_m: number;
|
|
79
|
+
duration_s: number;
|
|
80
|
+
/** ISO time, when departAt was given. */
|
|
81
|
+
eta: string | null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface RouteResult {
|
|
85
|
+
profile: string;
|
|
86
|
+
distance_m: number;
|
|
87
|
+
duration_s: number;
|
|
88
|
+
legs: Leg[];
|
|
89
|
+
geometry: LineString | null;
|
|
90
|
+
alternatives?: Omit<RouteResult, "profile" | "alternatives">[];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface MatrixResult {
|
|
94
|
+
profile: string;
|
|
95
|
+
/** [source][destination]; null = unreachable */
|
|
96
|
+
durations: (number | null)[][];
|
|
97
|
+
distances: (number | null)[][];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface NearestResult extends LatLng {
|
|
101
|
+
profile: string;
|
|
102
|
+
distance_m: number;
|
|
103
|
+
name: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface TripStop extends LatLng {
|
|
107
|
+
id: string | number;
|
|
108
|
+
/** This stop must come after the stop with this id (e.g. a drop after its kitchen). */
|
|
109
|
+
after?: string | number | null;
|
|
110
|
+
serviceTimeS?: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface TripResult {
|
|
114
|
+
profile: string;
|
|
115
|
+
total_distance_m: number;
|
|
116
|
+
total_travel_s: number;
|
|
117
|
+
total_service_s: number;
|
|
118
|
+
total_duration_s: number;
|
|
119
|
+
depart_at: string | null;
|
|
120
|
+
finish_at: string | null;
|
|
121
|
+
start: LatLng;
|
|
122
|
+
stops: (LatLng & {
|
|
123
|
+
sequence: number;
|
|
124
|
+
id: string;
|
|
125
|
+
after: string | null;
|
|
126
|
+
leg_distance_m: number;
|
|
127
|
+
leg_duration_s: number;
|
|
128
|
+
service_time_s: number;
|
|
129
|
+
arrival_offset_s: number;
|
|
130
|
+
departure_offset_s: number;
|
|
131
|
+
eta: string | null;
|
|
132
|
+
})[];
|
|
133
|
+
end: (LatLng & { leg_distance_m: number; leg_duration_s: number; arrival_offset_s: number; eta: string | null }) | null;
|
|
134
|
+
geometry: LineString | null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── Geocoding ──────────────────────────────────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
export interface AddressComponents {
|
|
140
|
+
house_number: string | null;
|
|
141
|
+
road: string | null;
|
|
142
|
+
/** mohalla / neighbourhood */
|
|
143
|
+
locality: string | null;
|
|
144
|
+
city: string | null;
|
|
145
|
+
district: string | null;
|
|
146
|
+
state: string | null;
|
|
147
|
+
/** 6 digits, from the official India Post boundaries */
|
|
148
|
+
pincode: string | null;
|
|
149
|
+
country: string | null;
|
|
150
|
+
country_code: string | null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface Place extends LatLng {
|
|
154
|
+
provider: string;
|
|
155
|
+
provider_place_id: string | null;
|
|
156
|
+
name: string | null;
|
|
157
|
+
formatted_address: string;
|
|
158
|
+
components: AddressComponents;
|
|
159
|
+
precision: "house" | "street" | "locality" | "pincode" | "city" | "region" | "unknown";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Where the answer came from: our saved data, or null when a provider answered just now. */
|
|
163
|
+
export type CacheSource = "redis" | "db" | null;
|
|
164
|
+
|
|
165
|
+
export interface ReverseResult {
|
|
166
|
+
place: Place | null;
|
|
167
|
+
provider: string | null;
|
|
168
|
+
cache: CacheSource;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export interface SearchResult {
|
|
172
|
+
results: Place[];
|
|
173
|
+
provider: string | null;
|
|
174
|
+
cache: CacheSource;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface SearchOptions {
|
|
178
|
+
query: string;
|
|
179
|
+
/** Prefer results around this point. */
|
|
180
|
+
near?: LatLng;
|
|
181
|
+
limit?: number;
|
|
182
|
+
/** "en", "hi" … */
|
|
183
|
+
language?: string;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── PIN codes ──────────────────────────────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
export interface Pincode {
|
|
189
|
+
pincode: string;
|
|
190
|
+
office_name: string | null;
|
|
191
|
+
division: string | null;
|
|
192
|
+
region: string | null;
|
|
193
|
+
circle: string | null;
|
|
194
|
+
center: LatLng;
|
|
195
|
+
/** [minLng, minLat, maxLng, maxLat] */
|
|
196
|
+
bbox: [number, number, number, number];
|
|
197
|
+
area_km2: number;
|
|
198
|
+
source_version: string;
|
|
199
|
+
/** GeoJSON, only with { geometry: true } */
|
|
200
|
+
boundary?: { type: "MultiPolygon"; coordinates: number[][][][] };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface PincodeDetails extends Pincode {
|
|
204
|
+
/** Licence condition (GODL-India): show it wherever the data is shown. */
|
|
205
|
+
attribution: string;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export interface LocatePincodeResult {
|
|
209
|
+
pincode: Pincode | null;
|
|
210
|
+
match: "inside" | "nearest" | null;
|
|
211
|
+
distance_m: number | null;
|
|
212
|
+
attribution: string;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface PincodesWithinResult {
|
|
216
|
+
center: LatLng;
|
|
217
|
+
radius_m: number;
|
|
218
|
+
count: number;
|
|
219
|
+
pincodes: (Pincode & { distance_m: number; center_distance_m: number; share_inside: number })[];
|
|
220
|
+
attribution: string;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── Service ────────────────────────────────────────────────────────────────────
|
|
224
|
+
|
|
225
|
+
export interface ClientConfig {
|
|
226
|
+
renderer: "maplibre" | "google";
|
|
227
|
+
styleUrl: string | null;
|
|
228
|
+
attribution: string;
|
|
229
|
+
tiles: {
|
|
230
|
+
provider: string;
|
|
231
|
+
renderer: "maplibre" | "google";
|
|
232
|
+
styleUrl: string | null;
|
|
233
|
+
attribution: string;
|
|
234
|
+
apiKey: string | null;
|
|
235
|
+
};
|
|
236
|
+
providers: { routing: string; geocoding: string[]; tiles: string };
|
|
237
|
+
routingProvider: string;
|
|
238
|
+
profiles: string[];
|
|
239
|
+
defaultProfile: string;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export interface HealthResult {
|
|
243
|
+
status: "OK" | "DEGRADED";
|
|
244
|
+
service: string;
|
|
245
|
+
env: string;
|
|
246
|
+
capabilities: Record<string, unknown>;
|
|
247
|
+
storage?: { db: string; redis: string };
|
|
248
|
+
[key: string]: unknown;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export class MapClient {
|
|
252
|
+
constructor(options: MapClientOptions);
|
|
253
|
+
|
|
254
|
+
eta(args: { from: LatLng; to: LatLng; profile?: string; departAt?: Date | string }): Promise<EtaResult>;
|
|
255
|
+
route(args: { points: LatLng[]; profile?: string; geometry?: boolean; alternatives?: number }): Promise<RouteResult>;
|
|
256
|
+
matrix(args: { sources: LatLng[]; destinations?: LatLng[]; profile?: string }): Promise<MatrixResult>;
|
|
257
|
+
nearest(args: { point: LatLng; profile?: string }): Promise<NearestResult>;
|
|
258
|
+
optimizeTrip(args: {
|
|
259
|
+
start: LatLng;
|
|
260
|
+
end?: LatLng;
|
|
261
|
+
stops: TripStop[];
|
|
262
|
+
profile?: string;
|
|
263
|
+
departAt?: Date | string;
|
|
264
|
+
geometry?: boolean;
|
|
265
|
+
}): Promise<TripResult>;
|
|
266
|
+
|
|
267
|
+
reverse(args: { point: LatLng; language?: string }): Promise<ReverseResult>;
|
|
268
|
+
search(args: SearchOptions): Promise<SearchResult>;
|
|
269
|
+
autocomplete(args: SearchOptions): Promise<SearchResult>;
|
|
270
|
+
|
|
271
|
+
pincode(pincode: string | number, options?: { geometry?: boolean }): Promise<PincodeDetails>;
|
|
272
|
+
locatePincode(args: { point: LatLng }): Promise<LocatePincodeResult>;
|
|
273
|
+
pincodesWithin(args: { center: LatLng; radiusM: number }): Promise<PincodesWithinResult>;
|
|
274
|
+
|
|
275
|
+
clientConfig(): Promise<ClientConfig>;
|
|
276
|
+
health(): Promise<HealthResult>;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function createMapClient(options: MapClientOptions): MapClient;
|
package/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hg-map-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Client for Mummy's Dabba map-service: routing, ETA, trip optimization, geocoding and India PIN codes \u2014 provider-independent",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"types": "index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"index.js",
|
|
9
|
+
"index.d.ts",
|
|
10
|
+
"src/",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test test/"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18.0.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/satyamsonker1010/mummys-dabba-map-service.git",
|
|
22
|
+
"directory": "sdk"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/satyamsonker1010/mummys-dabba-map-service/tree/development/sdk#readme",
|
|
25
|
+
"keywords": [
|
|
26
|
+
"maps",
|
|
27
|
+
"routing",
|
|
28
|
+
"geocoding",
|
|
29
|
+
"pincode",
|
|
30
|
+
"osrm"
|
|
31
|
+
],
|
|
32
|
+
"author": "Satyam Sonker",
|
|
33
|
+
"license": "ISC"
|
|
34
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const { MapServiceError } = require("./errors");
|
|
2
|
+
|
|
3
|
+
const DEFAULTS = {
|
|
4
|
+
timeoutMs: 8000,
|
|
5
|
+
// Every map-service endpoint only reads, so retrying is always safe.
|
|
6
|
+
retries: 1,
|
|
7
|
+
retryDelayMs: 200,
|
|
8
|
+
// A 429 is retried only if map-service asks us to wait at most this long.
|
|
9
|
+
maxRetryAfterS: 2,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Low-level HTTP: base URL + key, timeout, retries, and turning map-service's
|
|
16
|
+
* `{ success, message, data, code, errors }` envelope into data or a MapServiceError.
|
|
17
|
+
*/
|
|
18
|
+
class HttpClient {
|
|
19
|
+
/**
|
|
20
|
+
* @param {{ baseUrl: string, apiKey: string, timeoutMs?: number, retries?: number,
|
|
21
|
+
* retryDelayMs?: number, maxRetryAfterS?: number, fetch?: typeof fetch, userAgent?: string }} options
|
|
22
|
+
*/
|
|
23
|
+
constructor(options) {
|
|
24
|
+
if (!options || typeof options.baseUrl !== "string" || !options.baseUrl) {
|
|
25
|
+
throw new TypeError("hg-map-sdk: baseUrl is required, e.g. http://map-service:4120/api/v1/maps");
|
|
26
|
+
}
|
|
27
|
+
if (typeof options.apiKey !== "string" || !options.apiKey) {
|
|
28
|
+
throw new TypeError("hg-map-sdk: apiKey is required (this service's own key: npm run clients -- create <name>)");
|
|
29
|
+
}
|
|
30
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
31
|
+
this.apiKey = options.apiKey;
|
|
32
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULTS.timeoutMs;
|
|
33
|
+
this.retries = Math.max(0, options.retries ?? DEFAULTS.retries);
|
|
34
|
+
this.retryDelayMs = options.retryDelayMs ?? DEFAULTS.retryDelayMs;
|
|
35
|
+
this.maxRetryAfterS = options.maxRetryAfterS ?? DEFAULTS.maxRetryAfterS;
|
|
36
|
+
this.fetch = options.fetch || globalThis.fetch;
|
|
37
|
+
this.userAgent = options.userAgent || "hg-map-sdk";
|
|
38
|
+
if (typeof this.fetch !== "function") {
|
|
39
|
+
throw new TypeError("hg-map-sdk: no fetch available — use Node 18+ or pass options.fetch");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `accept`: extra HTTP statuses whose body is still a normal answer (e.g. /health's 503). */
|
|
44
|
+
async once(method, path, body, { accept = [] } = {}) {
|
|
45
|
+
const controller = new AbortController();
|
|
46
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
47
|
+
let res;
|
|
48
|
+
try {
|
|
49
|
+
res = await this.fetch(`${this.baseUrl}${path}`, {
|
|
50
|
+
method,
|
|
51
|
+
headers: {
|
|
52
|
+
"X-Map-Service-Api-Key": this.apiKey,
|
|
53
|
+
"User-Agent": this.userAgent,
|
|
54
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
55
|
+
},
|
|
56
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
57
|
+
signal: controller.signal,
|
|
58
|
+
});
|
|
59
|
+
} catch (err) {
|
|
60
|
+
if (err.name === "AbortError") {
|
|
61
|
+
throw new MapServiceError(`map-service did not answer within ${this.timeoutMs} ms (${method} ${path})`, {
|
|
62
|
+
code: "TIMEOUT",
|
|
63
|
+
cause: err,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
throw new MapServiceError(`map-service not reachable (${method} ${path}): ${err.message}`, {
|
|
67
|
+
code: "NETWORK_ERROR",
|
|
68
|
+
cause: err,
|
|
69
|
+
});
|
|
70
|
+
} finally {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let payload = null;
|
|
75
|
+
try {
|
|
76
|
+
payload = await res.json();
|
|
77
|
+
} catch {
|
|
78
|
+
// not JSON (proxy error page …) — handled below
|
|
79
|
+
}
|
|
80
|
+
if ((res.ok || accept.includes(res.status)) && payload && payload.success !== false) return payload.data;
|
|
81
|
+
|
|
82
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
83
|
+
throw new MapServiceError(payload?.message || `map-service answered HTTP ${res.status}`, {
|
|
84
|
+
code: payload?.code || (res.status === 429 ? "RATE_LIMITED" : `HTTP_${res.status}`),
|
|
85
|
+
status: res.status,
|
|
86
|
+
details: payload?.errors ?? null,
|
|
87
|
+
retryAfterS: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : null,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** One request with retries on network errors, timeouts, 5xx and short 429s. */
|
|
92
|
+
async request(method, path, body, { accept = [], retries = this.retries } = {}) {
|
|
93
|
+
let attempt = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
try {
|
|
96
|
+
return await this.once(method, path, body, { accept });
|
|
97
|
+
} catch (err) {
|
|
98
|
+
if (!(err instanceof MapServiceError) || !err.retryable || attempt >= retries) throw err;
|
|
99
|
+
if (err.status === 429 && (err.retryAfterS == null || err.retryAfterS > this.maxRetryAfterS)) throw err;
|
|
100
|
+
attempt += 1;
|
|
101
|
+
const waitMs = err.status === 429 ? err.retryAfterS * 1000 : this.retryDelayMs * 2 ** (attempt - 1);
|
|
102
|
+
await sleep(waitMs);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get(path) {
|
|
108
|
+
return this.request("GET", path);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
post(path, body) {
|
|
112
|
+
return this.request("POST", path, body);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
module.exports = { HttpClient, DEFAULTS };
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every failure from map-service (or reaching it) is a MapServiceError, so callers branch on
|
|
3
|
+
* `code` — the same codes map-service documents (NO_ROUTE, POINT_OUTSIDE_COVERAGE,
|
|
4
|
+
* INVALID_API_KEY, RATE_LIMITED, PINCODE_NOT_FOUND …) plus two of the SDK's own:
|
|
5
|
+
* NETWORK_ERROR — map-service not reachable
|
|
6
|
+
* TIMEOUT — no answer within timeoutMs
|
|
7
|
+
*/
|
|
8
|
+
class MapServiceError extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* @param {string} message
|
|
11
|
+
* @param {{ code?: string, status?: number|null, details?: any, retryAfterS?: number|null, cause?: Error }} [info]
|
|
12
|
+
*/
|
|
13
|
+
constructor(message, { code = "MAP_SERVICE_ERROR", status = null, details = null, retryAfterS = null, cause } = {}) {
|
|
14
|
+
super(message, cause ? { cause } : undefined);
|
|
15
|
+
this.name = "MapServiceError";
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.details = details;
|
|
19
|
+
this.retryAfterS = retryAfterS;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** True for failures worth retrying later (map-service down/slow, or rate-limited). */
|
|
23
|
+
get retryable() {
|
|
24
|
+
return (
|
|
25
|
+
this.code === "NETWORK_ERROR" ||
|
|
26
|
+
this.code === "TIMEOUT" ||
|
|
27
|
+
this.status === 429 ||
|
|
28
|
+
(this.status != null && this.status >= 500)
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { MapServiceError };
|
package/src/mapClient.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const { HttpClient } = require("./client");
|
|
2
|
+
|
|
3
|
+
/** Drops undefined keys so map-service applies its own defaults. */
|
|
4
|
+
const clean = (obj) => Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One method per map-service endpoint. Points are always `{ lat, lng }`, distances metres,
|
|
8
|
+
* durations seconds — whatever map provider runs behind the service (OSRM, Google, Ola …),
|
|
9
|
+
* so code using this SDK never changes when the provider does.
|
|
10
|
+
*/
|
|
11
|
+
class MapClient {
|
|
12
|
+
/** @param {ConstructorParameters<typeof HttpClient>[0]} options */
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.http = new HttpClient(options);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// ── Routing ──────────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
/** A→B road distance + time (+ absolute `eta` when departAt is given). */
|
|
20
|
+
eta({ from, to, profile, departAt }) {
|
|
21
|
+
return this.http.post("/eta", clean({ from, to, profile, departAt: toIso(departAt) }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Road route through `points` in order, with a GeoJSON line for drawing. */
|
|
25
|
+
route({ points, profile, geometry, alternatives }) {
|
|
26
|
+
return this.http.post("/route", clean({ points, profile, geometry, alternatives }));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Travel times/distances from every source to every destination (omit destinations → all-to-all). */
|
|
30
|
+
matrix({ sources, destinations, profile }) {
|
|
31
|
+
return this.http.post("/matrix", clean({ sources, destinations, profile }));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Snap a noisy GPS point to the nearest road. */
|
|
35
|
+
nearest({ point, profile }) {
|
|
36
|
+
return this.http.post("/nearest", clean({ point, profile }));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Order a multi-stop delivery run and get per-stop ETAs. */
|
|
40
|
+
optimizeTrip({ start, end, stops, profile, departAt, geometry }) {
|
|
41
|
+
return this.http.post("/trip/optimize", clean({ start, end, stops, profile, departAt: toIso(departAt), geometry }));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ── Geocoding ────────────────────────────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/** Lat/lng → the address there: `{ place, provider, cache }` (place null when nothing is there). */
|
|
47
|
+
reverse({ point, language }) {
|
|
48
|
+
return this.http.post("/geocode/reverse", clean({ point, language }));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Address text → places, best first: `{ results, provider, cache }`. */
|
|
52
|
+
search({ query, near, limit, language }) {
|
|
53
|
+
return this.http.post("/geocode/search", clean({ query, near, limit, language }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Suggestions while the user types: `{ results, provider, cache }`. */
|
|
57
|
+
autocomplete({ query, near, limit, language }) {
|
|
58
|
+
return this.http.post("/geocode/autocomplete", clean({ query, near, limit, language }));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ── PIN codes (official India Post boundaries) ───────────────────────────────
|
|
62
|
+
|
|
63
|
+
/** One PIN code's details (boundary GeoJSON too when geometry is true). */
|
|
64
|
+
pincode(pincode, { geometry = false } = {}) {
|
|
65
|
+
const pin = String(pincode).replace(/\s+/g, "");
|
|
66
|
+
return this.http.get(`/pincodes/${encodeURIComponent(pin)}${geometry ? "?geometry=true" : ""}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Which PIN is this point in: `{ pincode, match: "inside"|"nearest"|null, distance_m }`. */
|
|
70
|
+
locatePincode({ point }) {
|
|
71
|
+
return this.http.post("/pincodes/locate", { point });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Every PIN a radius reaches (e.g. a kitchen's 10 km), nearest first, with share_inside. */
|
|
75
|
+
pincodesWithin({ center, radiusM }) {
|
|
76
|
+
return this.http.post("/pincodes/within", { center, radius_m: radiusM });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ── Service ──────────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
/** What an app's map wrapper should draw (tiles provider, renderer, style URL, attribution). */
|
|
82
|
+
clientConfig() {
|
|
83
|
+
return this.http.get("/client-config");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* map-service health: `{ status: "OK"|"DEGRADED", capabilities, storage … }`. A DEGRADED
|
|
88
|
+
* service answers 503 with the same body, which is returned (not thrown); no retries, so a
|
|
89
|
+
* health check reports what it sees right now.
|
|
90
|
+
*/
|
|
91
|
+
health() {
|
|
92
|
+
return this.http.request("GET", "/health", undefined, { accept: [503], retries: 0 });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const toIso = (d) => (d instanceof Date ? d.toISOString() : d);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @example
|
|
100
|
+
* const { createMapClient } = require("hg-map-sdk");
|
|
101
|
+
* const map = createMapClient({ baseUrl: process.env.MAP_SERVICE_URL, apiKey: process.env.MAP_SERVICE_API_KEY });
|
|
102
|
+
* const { distance_m, duration_s } = await map.eta({ from: kitchen, to: customer });
|
|
103
|
+
*/
|
|
104
|
+
const createMapClient = (options) => new MapClient(options);
|
|
105
|
+
|
|
106
|
+
module.exports = { MapClient, createMapClient };
|