geo-engine-node 2.0.0 → 3.0.0-rc.1
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/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.es.md +397 -0
- package/Readme.md +261 -100
- package/dist/chunk-425YTEGY.js +1231 -0
- package/dist/chunk-425YTEGY.js.map +1 -0
- package/dist/chunk-A6RGK4MA.cjs +1231 -0
- package/dist/chunk-A6RGK4MA.cjs.map +1 -0
- package/dist/errors-C5S_d0Ca.d.cts +473 -0
- package/dist/errors-C5S_d0Ca.d.ts +473 -0
- package/dist/identity.cjs +196 -0
- package/dist/identity.cjs.map +1 -0
- package/dist/identity.d.cts +10 -0
- package/dist/identity.d.ts +10 -0
- package/dist/identity.js +196 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.cjs +465 -455
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +275 -134
- package/dist/index.d.ts +275 -134
- package/dist/index.js +375 -310
- package/dist/index.js.map +1 -1
- package/package.json +38 -9
package/Readme.md
CHANGED
|
@@ -3,136 +3,222 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/geo-engine-node)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
[](https://www.typescriptlang.org/)
|
|
6
|
-
[](https://vitest.dev/)
|
|
6
|
+
[](https://vitest.dev/)
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
> *Read this in Spanish: [README.es.md](./README.es.md)*
|
|
9
|
+
|
|
10
|
+
Official **Node.js & TypeScript** client for the **Geo-Engine** platform (`v3.0.0-rc.1`).
|
|
11
|
+
|
|
12
|
+
> ⚠️ **Release candidate / experimental:** `v3.0.0-rc.1` is published under the `next` dist-tag (`npm install geo-engine-node@next`). The GeoIdentity module (`client.identity`, `geo-engine-node/identity`) is **experimental**: its API contract (`/v1/evaluate`) is still a **draft** and it is **not recommended for production**. This is a major release with breaking changes; see [CHANGELOG.md](./CHANGELOG.md) for migration notes.
|
|
13
|
+
Designed for strict TypeScript safety, zero runtime dependencies, and server-side integration in Node.js `>=20`.
|
|
10
14
|
|
|
11
15
|
---
|
|
12
16
|
|
|
13
17
|
## ✨ Features
|
|
14
18
|
|
|
15
|
-
- 📍 **
|
|
16
|
-
- 🗺️ **
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
|
|
19
|
+
- 📍 **Telemetry Ingestion:** HTTP REST location dispatch (`sendLocation`) and background `AsyncIngester`.
|
|
20
|
+
- 🗺️ **Spatial Module:** Point-in-polygon evaluation (single geofence and general validation against all active geofences) plus fluent query builder `client.spatial.check(lat, lng)`.
|
|
21
|
+
- 👥 **Users Module:** Management of organization members, roles, and email invitations (`client.users`).
|
|
22
|
+
- 🛡️ **GeoIdentity Rules & Runtime Evaluation:** Rule CRUD (`client.geoIdentity`) and server-only access decision evaluation via `client.identity.evaluate(...)` and `geo-engine-node/identity` (`identityGuard`).
|
|
23
|
+
- 🚧 **Geofence Management:** Creation and automatic normalization of PostGIS-backed GeoJSON polygons (`createGeofence`).
|
|
24
|
+
- 📦 **Dual Package (ESM & CommonJS):** Compatible with native `import` and `require()`, bundled with `tsup` and `.d.ts` / `.d.cts` type definitions.
|
|
25
|
+
- ⚡ **Zero Runtime Dependencies:** Built on standard Node.js APIs (`fetch`, `node:crypto`, `node:timers`, `AbortController`) for Node.js `>=20` server runtimes.
|
|
26
|
+
|
|
27
|
+
> **Runtime Note:** The SDK imports `node:crypto` and `node:timers` and is intended for **Node.js server runtimes** (edge runtimes without Node compatibility are not supported). The secret `apiKey` is stored in a private `#` field and is omitted from `client.options`, `JSON.stringify`, and `util.inspect`.
|
|
23
28
|
|
|
24
29
|
---
|
|
25
30
|
|
|
26
|
-
## 🚀
|
|
31
|
+
## 🚀 Installation
|
|
27
32
|
|
|
28
33
|
```bash
|
|
29
34
|
npm install geo-engine-node
|
|
30
35
|
```
|
|
31
36
|
|
|
32
|
-
|
|
37
|
+
Or using Yarn / PNPM / Bun:
|
|
33
38
|
|
|
34
39
|
```bash
|
|
35
40
|
pnpm add geo-engine-node
|
|
36
|
-
#
|
|
41
|
+
# or
|
|
37
42
|
bun add geo-engine-node
|
|
38
43
|
```
|
|
39
44
|
|
|
40
45
|
---
|
|
41
46
|
|
|
42
|
-
## ⚡
|
|
47
|
+
## ⚡ Quick Start
|
|
43
48
|
|
|
44
|
-
### TypeScript / ES Modules (
|
|
49
|
+
### TypeScript / ES Modules (Recommended)
|
|
45
50
|
|
|
46
51
|
```ts
|
|
47
52
|
import GeoEngine from 'geo-engine-node';
|
|
48
53
|
|
|
49
|
-
//
|
|
50
|
-
const
|
|
54
|
+
// Initialize with your secret API key
|
|
55
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
56
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
57
|
+
const client = new GeoEngine(apiKey);
|
|
51
58
|
|
|
52
59
|
try {
|
|
53
60
|
await client.sendLocation('truck-01', 19.4326, -99.1332);
|
|
54
|
-
console.log('✅
|
|
61
|
+
console.log('✅ Coordinate sent successfully');
|
|
55
62
|
} catch (error) {
|
|
56
|
-
console.error('❌ Error
|
|
63
|
+
console.error('❌ Error sending location:', error);
|
|
57
64
|
} finally {
|
|
58
65
|
client.close();
|
|
59
66
|
}
|
|
60
67
|
```
|
|
61
68
|
|
|
62
|
-
### CommonJS
|
|
69
|
+
### CommonJS
|
|
63
70
|
|
|
64
71
|
```js
|
|
65
72
|
const GeoEngine = require('geo-engine-node');
|
|
66
73
|
|
|
67
|
-
const
|
|
74
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
75
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
76
|
+
const client = new GeoEngine(apiKey);
|
|
68
77
|
|
|
69
78
|
client.sendLocation('scooter-09', 19.4326, -99.1332)
|
|
70
|
-
.then(() => console.log('
|
|
79
|
+
.then(() => console.log('Location registered'))
|
|
71
80
|
.catch((err) => console.error(err));
|
|
72
81
|
```
|
|
73
82
|
|
|
74
83
|
---
|
|
75
84
|
|
|
76
|
-
##
|
|
85
|
+
## 🛡️ GeoIdentity Runtime Evaluation (`/v1/evaluate` & `identityGuard`)
|
|
86
|
+
|
|
87
|
+
> [!IMPORTANT]
|
|
88
|
+
> **Server-only & Secret API Key:** `POST /v1/evaluate` authenticates strictly with `Authorization: Bearer <secret_api_key>` and does **not** allow browser CORS requests. Never expose your API key or import `geo-engine-node/identity` in browser code (loading it when `window` is defined throws immediately).
|
|
89
|
+
|
|
90
|
+
### Direct Evaluation (`client.identity.evaluate`)
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import GeoEngine from 'geo-engine-node';
|
|
94
|
+
import { IdentityTransientError, IdentityIntegrationError, isTransient } from 'geo-engine-node/identity';
|
|
95
|
+
|
|
96
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
97
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
98
|
+
const client = new GeoEngine(apiKey);
|
|
77
99
|
|
|
78
|
-
|
|
100
|
+
try {
|
|
101
|
+
const decision = await client.identity.evaluate({
|
|
102
|
+
scope: 'login',
|
|
103
|
+
subject: { user_id: 'user_2abc123', roles: ['admin'], device_id: 'dev_9f8e7d' },
|
|
104
|
+
context: {
|
|
105
|
+
ip: '203.0.113.42',
|
|
106
|
+
location: { lat: 28.6353, lng: -106.0889, accuracy_m: 25, source: 'device' },
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
if (decision.decision === 'BLOCK') {
|
|
111
|
+
// Handle block
|
|
112
|
+
} else if (decision.decision === 'CHALLENGE') {
|
|
113
|
+
// Prompt step-up verification (e.g. decision.challenge?.hint)
|
|
114
|
+
}
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (isTransient(err)) {
|
|
117
|
+
// Network, timeout, 5xx, or 429 after 500ms deadline / single retry
|
|
118
|
+
} else if (err instanceof IdentityIntegrationError) {
|
|
119
|
+
// 400, 401, edge 403, 404, 422, or malformed response (do NOT fail open)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
79
123
|
|
|
80
|
-
###
|
|
124
|
+
### Express / Connect Middleware (`identityGuard`)
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import GeoEngine from 'geo-engine-node';
|
|
128
|
+
import { identityGuard } from 'geo-engine-node/identity';
|
|
129
|
+
|
|
130
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
131
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
132
|
+
const client = new GeoEngine(apiKey);
|
|
133
|
+
|
|
134
|
+
app.post(
|
|
135
|
+
'/login',
|
|
136
|
+
identityGuard({
|
|
137
|
+
client,
|
|
138
|
+
scope: 'login',
|
|
139
|
+
failOpen: false, // REQUIRED: true allows on transient error, false blocks (403)
|
|
140
|
+
getSubject: (req) => ({ user_id: req.body.userId, device_id: req.headers['x-device-id'] as string }),
|
|
141
|
+
getContext: (req) => ({
|
|
142
|
+
ip: req.ip,
|
|
143
|
+
location: req.body.location, // If omitted and scope has geo rules, engine may block with `location_missing`
|
|
144
|
+
}),
|
|
145
|
+
onChallenge: async (decision, _req, res) => {
|
|
146
|
+
res.status(403).json({ error: 'challenge_required', hint: decision.challenge?.hint ?? 'step_up' });
|
|
147
|
+
},
|
|
148
|
+
onIntegrationError: (err) => {
|
|
149
|
+
console.error('GeoIdentity integration error:', err);
|
|
150
|
+
},
|
|
151
|
+
}),
|
|
152
|
+
loginHandler
|
|
153
|
+
);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
- **`failOpen` (mandatory, no default):** applies **only** to transient errors (`timeout`, `network`, `server_error`, `rate_limited`) and unknown `decision` values (`unknown_decision`). When triggered, `onDecision` receives a synthetic `FallbackDecision` with `fallback: true`, `fallback_reason`, and `meta.source = 'sdk_fallback'`.
|
|
157
|
+
- **Integration errors never fail open:** `400`, `401`, `403` (including non-JSON edge `403`), `404`, `422`, local invalid inputs, or unexpected payloads throw `IdentityIntegrationError`, invoke `onIntegrationError`, and return HTTP `500` (`{ error: 'internal_error' }`).
|
|
158
|
+
- **`CHALLENGE`:** invokes `onChallenge` if provided; if omitted, responds `403` with `{ error: 'challenge_required', hint: 'step_up' }` and never falls through to `next()`.
|
|
159
|
+
- **`context.location`:** when the scope evaluates geographic conditions and `location` is absent, `/v1/evaluate` returns HTTP `200` with the `location_missing` signal (which may result in `BLOCK` as a normal policy decision, not an error).
|
|
160
|
+
- **Deadline & retries:** `evaluate` enforces a `500 ms` total deadline by default (`identityTimeoutMs` or per-call `timeoutMs`) with at most 1 jittered retry on transient failures (honoring `Retry-After` if it fits in the remaining budget), reusing the same `X-Request-Id`.
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
## 🗺️ Spatial Module & Point Validation
|
|
165
|
+
|
|
166
|
+
The `client.spatial` module connects to the GeoEngine API service to evaluate spatial containment:
|
|
167
|
+
|
|
168
|
+
### Single Geofence Validation
|
|
81
169
|
|
|
82
170
|
```ts
|
|
83
171
|
import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
|
|
84
172
|
|
|
85
|
-
const
|
|
173
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
174
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
175
|
+
const client = new GeoEngine(apiKey);
|
|
86
176
|
|
|
87
177
|
try {
|
|
88
178
|
const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
|
|
89
179
|
|
|
90
180
|
if (res.isInside()) {
|
|
91
|
-
console.log(`✅
|
|
181
|
+
console.log(`✅ The device is inside ${res.geofenceName} (${res.geofenceId})`);
|
|
92
182
|
} else {
|
|
93
|
-
console.log('⚠️
|
|
183
|
+
console.log('⚠️ The device is outside the geofence');
|
|
94
184
|
}
|
|
95
185
|
|
|
96
|
-
console.log('
|
|
97
|
-
console.log('
|
|
186
|
+
console.log('Coordinates:', res.coordinates()); // [19.4326, -99.1332]
|
|
187
|
+
console.log('Formatted log:', res.toString()); // [INSIDE] geofence=geofence_123 (Downtown) at (19.432600, -99.133200)
|
|
98
188
|
} catch (err) {
|
|
99
189
|
if (err instanceof GeofenceNotFoundError) {
|
|
100
|
-
console.warn('
|
|
190
|
+
console.warn('The requested geofence does not exist');
|
|
101
191
|
} else {
|
|
102
192
|
throw err;
|
|
103
193
|
}
|
|
104
194
|
}
|
|
105
195
|
```
|
|
106
196
|
|
|
107
|
-
###
|
|
197
|
+
### General Validation (Against All Active Geofences)
|
|
108
198
|
|
|
109
199
|
```ts
|
|
110
200
|
const res = await client.spatial.validateGeneral(19.4326, -99.1332);
|
|
111
201
|
|
|
112
202
|
if (res.hasMatches()) {
|
|
113
|
-
console.log(`
|
|
114
|
-
|
|
115
|
-
if (res.containsGeofence('CDMX
|
|
116
|
-
console.log('
|
|
203
|
+
console.log(`Matched ${res.totalMatches} geofences:`, res.geofenceNames());
|
|
204
|
+
|
|
205
|
+
if (res.containsGeofence('CDMX Downtown')) {
|
|
206
|
+
console.log('The vehicle is in CDMX Downtown');
|
|
117
207
|
}
|
|
118
208
|
|
|
119
|
-
const match = res.findMatch('CDMX
|
|
120
|
-
console.log('ID
|
|
209
|
+
const match = res.findMatch('CDMX Downtown');
|
|
210
|
+
console.log('Found ID:', match?.id);
|
|
121
211
|
}
|
|
122
212
|
```
|
|
123
213
|
|
|
124
214
|
### Fluent Query Builder
|
|
125
215
|
|
|
126
|
-
Para mayor legibilidad, puedes construir consultas fluidas:
|
|
127
|
-
|
|
128
216
|
```ts
|
|
129
|
-
// Validación en geocerca específica
|
|
130
217
|
const singleRes = await client.spatial
|
|
131
218
|
.check(19.4326, -99.1332)
|
|
132
219
|
.inGeofence('geofence_123')
|
|
133
220
|
.execute();
|
|
134
221
|
|
|
135
|
-
// Validación contra todas las geocercas
|
|
136
222
|
const generalRes = await client.spatial
|
|
137
223
|
.check(19.4326, -99.1332)
|
|
138
224
|
.inAllGeofences()
|
|
@@ -141,104 +227,178 @@ const generalRes = await client.spatial
|
|
|
141
227
|
|
|
142
228
|
---
|
|
143
229
|
|
|
144
|
-
##
|
|
230
|
+
## 👥 Users Module
|
|
231
|
+
|
|
232
|
+
The `client.users` module manages the members of the organization that owns the API key:
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
|
|
236
|
+
|
|
237
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
238
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
239
|
+
const client = new GeoEngine(apiKey);
|
|
240
|
+
|
|
241
|
+
const users = await client.users.list();
|
|
242
|
+
const roles = await client.users.listRoles();
|
|
243
|
+
const user = await client.users.get('user_123');
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const inv = await client.users.invite({
|
|
247
|
+
email: 'ana@acme.com',
|
|
248
|
+
role: Roles.Viewer,
|
|
249
|
+
lang: 'es', // 'es' (default) | 'en' | 'pt'
|
|
250
|
+
});
|
|
251
|
+
console.log('Invitation link:', inv.inviteUrl);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
if (err instanceof InvitationPendingError) {
|
|
254
|
+
console.warn('There is already a pending invitation for this email');
|
|
255
|
+
} else {
|
|
256
|
+
throw err;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
try {
|
|
261
|
+
await client.users.updateRole('user_123', Roles.Dispatcher);
|
|
262
|
+
await client.users.remove('user_123');
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if (err instanceof LastAdminError) {
|
|
265
|
+
console.warn('The organization must retain at least one administrator');
|
|
266
|
+
} else {
|
|
267
|
+
throw err;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## 🛡️ GeoIdentity Rules Management (`client.geoIdentity`)
|
|
145
275
|
|
|
146
|
-
|
|
276
|
+
The `client.geoIdentity` module manages access rules and subject assignments:
|
|
147
277
|
|
|
148
278
|
```ts
|
|
149
|
-
|
|
279
|
+
import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
|
|
280
|
+
|
|
281
|
+
const area = polygonFromLatLng([
|
|
282
|
+
[19.40, -99.20], [19.40, -99.10], [19.50, -99.10], // [lat, lng]
|
|
283
|
+
]);
|
|
284
|
+
|
|
285
|
+
const rule = await client.geoIdentity.createRule({
|
|
286
|
+
name: 'CDMX Only',
|
|
287
|
+
action: RuleActions.Block,
|
|
288
|
+
blackIpList: ['203.0.113.0/24'],
|
|
289
|
+
blockTor: true,
|
|
290
|
+
geoLimit: area,
|
|
291
|
+
assignedSubjects: [{ subjectType: SubjectTypes.User, subjectId: 'user_123' }],
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
const rules = await client.geoIdentity.listRules({ isActive: true });
|
|
295
|
+
const detail = await client.geoIdentity.getRule(rule.id);
|
|
296
|
+
await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null });
|
|
297
|
+
await client.geoIdentity.deleteRule(rule.id);
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## 🚧 Geofence Creation (PostGIS Polygons)
|
|
303
|
+
|
|
304
|
+
Create spatial zones dynamically. The SDK validates `[latitude, longitude]`, converts to GeoJSON `[longitude, latitude]`, and ensures the polygon ring is closed:
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
const zoneCoordinates: [number, number][] = [
|
|
150
308
|
[19.4326, -99.1332],
|
|
151
309
|
[19.4426, -99.1332],
|
|
152
310
|
[19.4426, -99.1232],
|
|
153
311
|
];
|
|
154
312
|
|
|
155
313
|
await client.createGeofence(
|
|
156
|
-
'
|
|
157
|
-
|
|
158
|
-
'https://
|
|
314
|
+
'North Logistics Park',
|
|
315
|
+
zoneCoordinates,
|
|
316
|
+
'https://my-api.com/webhooks/geofences'
|
|
159
317
|
);
|
|
160
318
|
```
|
|
161
319
|
|
|
162
320
|
---
|
|
163
321
|
|
|
164
|
-
## 🔄
|
|
322
|
+
## 🔄 Async Batch Ingestion (`AsyncIngester`)
|
|
165
323
|
|
|
166
|
-
|
|
324
|
+
Queue telemetry pings in memory and dispatch them periodically (`sendLocation` per ping):
|
|
167
325
|
|
|
168
326
|
```ts
|
|
169
|
-
import GeoEngine
|
|
170
|
-
|
|
171
|
-
const client = new GeoEngine('sk_live_123456');
|
|
327
|
+
import GeoEngine from 'geo-engine-node';
|
|
172
328
|
|
|
173
|
-
|
|
329
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
330
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
331
|
+
const client = new GeoEngine(apiKey);
|
|
174
332
|
const ingester = client.createAsyncIngester(5000, 100, 500);
|
|
175
333
|
|
|
176
334
|
const ok = ingester.enqueue({
|
|
177
|
-
deviceId: '
|
|
335
|
+
deviceId: 'truck-45',
|
|
178
336
|
latitude: 19.4326,
|
|
179
337
|
longitude: -99.1332,
|
|
180
338
|
timestamp: Date.now(),
|
|
181
339
|
});
|
|
182
340
|
|
|
183
341
|
if (!ok) {
|
|
184
|
-
console.warn('Buffer
|
|
342
|
+
console.warn('Buffer queue full or ingester stopped');
|
|
185
343
|
}
|
|
186
344
|
|
|
187
|
-
// Al apagar el servicio, drena todos los elementos pendientes:
|
|
188
345
|
await ingester.stop();
|
|
189
346
|
client.close();
|
|
190
347
|
```
|
|
191
348
|
|
|
192
349
|
---
|
|
193
350
|
|
|
194
|
-
## 🔧
|
|
195
|
-
|
|
196
|
-
Puedes configurar el cliente mediante el objeto de opciones:
|
|
351
|
+
## 🔧 Advanced Configuration
|
|
197
352
|
|
|
198
353
|
```ts
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
354
|
+
const apiKey = process.env.GEOENGINE_API_KEY;
|
|
355
|
+
if (!apiKey) throw new Error('GEOENGINE_API_KEY is not set');
|
|
356
|
+
const client = new GeoEngine(apiKey, {
|
|
357
|
+
environment: 'live', // 'live' | 'test' (sent as X-Geo-Environment on legacy routes)
|
|
358
|
+
jwtToken: 'my.jwt.token',
|
|
359
|
+
timeout: 5000, // legacy routes timeout in ms
|
|
360
|
+
identityTimeoutMs: 500, // total deadline for client.identity.evaluate in ms
|
|
361
|
+
maxRetries: 2, // legacy routes retry count
|
|
204
362
|
managementUrl: 'https://management.geoengine.dev',
|
|
205
363
|
ingestUrl: 'https://ingest.geoengine.dev',
|
|
206
364
|
apiServiceUrl: 'https://api.geoengine.dev',
|
|
207
|
-
//
|
|
365
|
+
// Or for local/mock testing:
|
|
208
366
|
// baseUrl: 'http://localhost:8080',
|
|
209
367
|
});
|
|
210
368
|
```
|
|
211
369
|
|
|
212
|
-
###
|
|
370
|
+
### Available Options
|
|
213
371
|
|
|
214
|
-
|
|
|
372
|
+
| Option | Type | Description | Default |
|
|
215
373
|
| :--- | :--- | :--- | :--- |
|
|
216
|
-
| `apiKey` | `string` |
|
|
217
|
-
| `environment` | `string` | Target (`'live'`
|
|
218
|
-
| `jwtToken` | `string` |
|
|
219
|
-
| `apiServiceUrl` | `string` | URL
|
|
220
|
-
| `ingestUrl` | `string` | URL
|
|
221
|
-
| `managementUrl` | `string` | URL
|
|
222
|
-
| `baseUrl` | `string` |
|
|
223
|
-
| `timeout` | `number` |
|
|
224
|
-
| `
|
|
225
|
-
| `
|
|
226
|
-
| `
|
|
227
|
-
| `
|
|
374
|
+
| `apiKey` | `string` | Secret authentication key (stored privately; not exposed on `client.options`) | (required) |
|
|
375
|
+
| `environment` | `string` | Target (`'live'` or `'test'`) sent in `X-Geo-Environment` on legacy routes | `'live'` |
|
|
376
|
+
| `jwtToken` | `string` | Optional Bearer token sent on legacy routes | `undefined` |
|
|
377
|
+
| `apiServiceUrl` | `string` | URL of the API service (Spatial, Users, GeoIdentity, `/v1/evaluate`) | `'https://api.geoengine.dev'` |
|
|
378
|
+
| `ingestUrl` | `string` | URL of the telemetry ingestion service | `'https://ingest.geoengine.dev'` |
|
|
379
|
+
| `managementUrl` | `string` | URL of the control plane and geofence service | `'https://management.geoengine.dev'` |
|
|
380
|
+
| `baseUrl` | `string` | Overrides ingest, management, and apiService endpoints together. Must be `https` (plain `http` only for `localhost`, `127.0.0.1` or `::1`); otherwise the constructor throws a `ValidationError`. Redirects are never followed. | `undefined` |
|
|
381
|
+
| `timeout` | `number` | Legacy request timeout in ms (via `AbortController`) | `10000` |
|
|
382
|
+
| `identityTimeoutMs` | `number` | Total deadline in ms for `client.identity.evaluate` (including retry) | `500` |
|
|
383
|
+
| `maxRetries` | `number` | Exponential backoff retries (`429`, `5xx`, network) on legacy routes (`GET`-only for `users`/`geoIdentity`) | `2` |
|
|
384
|
+
| `batchSize` | `number` | Batch size for `AsyncIngester` | `100` |
|
|
385
|
+
| `flushInterval` | `number` | Flush interval for `AsyncIngester` in ms | `500` |
|
|
386
|
+
| `bufferSize` | `number` | Maximum queue capacity for `AsyncIngester` | `5000` |
|
|
387
|
+
|
|
388
|
+
> **Legacy vs `/v1/evaluate` Authentication:** Legacy routes send `X-API-Key`, `X-Geo-Environment`, `X-Request-Time`, and `X-Signature` (HMAC-SHA256 of the timestamp using `apiKey`, plus `Authorization: Bearer` if `jwtToken` is set). `/v1/evaluate` sends **only** `Authorization: Bearer <apiKey>` and `X-Request-Id`.
|
|
228
389
|
|
|
229
390
|
---
|
|
230
391
|
|
|
231
|
-
## 🛡️
|
|
392
|
+
## 🛡️ Typed Error Hierarchy
|
|
393
|
+
|
|
394
|
+
> `err.code` is the stable contract between formats: the ESM and CJS builds each ship their own error classes (so `instanceof` does not work across formats), but `code` values are identical.
|
|
232
395
|
|
|
233
|
-
|
|
396
|
+
Legacy and Spatial routes map HTTP status codes as follows:
|
|
234
397
|
|
|
235
398
|
```ts
|
|
236
399
|
import {
|
|
237
400
|
GeoEngineError,
|
|
238
401
|
ValidationError,
|
|
239
|
-
InvalidLatitudeError,
|
|
240
|
-
InvalidLongitudeError,
|
|
241
|
-
DeviceIDRequiredError,
|
|
242
402
|
GeofenceNotFoundError,
|
|
243
403
|
QuotaExceededError,
|
|
244
404
|
AuthenticationError,
|
|
@@ -251,38 +411,39 @@ try {
|
|
|
251
411
|
await client.spatial.validatePoint('geo-x', lat, lng);
|
|
252
412
|
} catch (error) {
|
|
253
413
|
if (error instanceof GeofenceNotFoundError) {
|
|
254
|
-
// 204 No Content
|
|
414
|
+
// 204 No Content or 404 Not Found
|
|
255
415
|
} else if (error instanceof QuotaExceededError) {
|
|
256
|
-
// 402 Payment Required
|
|
416
|
+
// 402 Payment Required or reason QUOTA_EXCEEDED
|
|
257
417
|
} else if (error instanceof AuthenticationError) {
|
|
258
|
-
// 401 Unauthorized
|
|
418
|
+
// 401 Unauthorized, MISSING_API_KEY, or MISSING_ORGANIZATION
|
|
419
|
+
} else if (error instanceof ForbiddenError) {
|
|
420
|
+
// 403 Forbidden
|
|
259
421
|
} else if (error instanceof TimeoutError) {
|
|
260
|
-
//
|
|
422
|
+
// Request timed out
|
|
261
423
|
} else if (error instanceof ValidationError) {
|
|
262
|
-
//
|
|
424
|
+
// Local validation failure (e.g. out-of-range coordinates or missing ID)
|
|
263
425
|
}
|
|
264
426
|
}
|
|
265
427
|
```
|
|
266
428
|
|
|
267
|
-
|
|
429
|
+
Users and GeoIdentity rule CRUD endpoints throw `APIServiceError` subclasses (`UserNotFoundError`, `RuleNotFoundError`, `UserAlreadyExistsError`, `InvitationPendingError`, `LastAdminError`, `LastSubjectError`) and only retry `GET` requests.
|
|
268
430
|
|
|
269
|
-
|
|
431
|
+
GeoIdentity `/v1/evaluate` throws `IdentityTransientError` (network, timeout, `5xx`, `429`) or `IdentityIntegrationError` (`400`, `401`, `403` including edge `403`, `404`, `422`, invalid payload/config), exporting `isTransient(err)`.
|
|
270
432
|
|
|
271
|
-
|
|
433
|
+
---
|
|
272
434
|
|
|
273
|
-
|
|
274
|
-
npm run test
|
|
275
|
-
```
|
|
435
|
+
## 🧪 Testing and Building
|
|
276
436
|
|
|
277
|
-
|
|
437
|
+
All tests run locally against simulated `node:http` servers (no live network required):
|
|
278
438
|
|
|
279
439
|
```bash
|
|
280
|
-
npm run build
|
|
281
440
|
npm run typecheck
|
|
441
|
+
npm run build
|
|
442
|
+
npm test
|
|
282
443
|
```
|
|
283
444
|
|
|
284
445
|
---
|
|
285
446
|
|
|
286
|
-
## 📄
|
|
447
|
+
## 📄 License
|
|
287
448
|
|
|
288
449
|
MIT © Geo-Engine Team
|