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/Readme.md CHANGED
@@ -3,136 +3,222 @@
3
3
  [![NPM Version](https://img.shields.io/npm/v/geo-engine-node?style=flat-square&color=blue)](https://www.npmjs.com/package/geo-engine-node)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue.svg)](https://www.typescriptlang.org/)
6
- [![Tests](https://img.shields.io/badge/Tests-Vitest-green.svg)](https://vitest.dev/)
6
+ [![Tests](https://img.shields.io/badge/Tests-Vitest%20%2B%20node%3Atest-green.svg)](https://vitest.dev/)
7
7
 
8
- Official idiomatic **Node.js & TypeScript** client for the **Geo-Engine** platform.
9
- Designed for **high performance**, strict type-safety, and parity 1:1 with the official Go SDK (`v2.0.3`). Seamlessly integrates into backend microservices, Serverless functions, and modern edge environments.
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
- - 📍 **Ingesta en tiempo real:** Envío sub-10ms de coordenadas de telemetría por HTTP REST.
16
- - 🗺️ **Módulo Spatial avanzado:** Evaluación espacial punto-en-polígono (Point-in-Polygon) de alto rendimiento (validación individual y general contra todas las geocercas).
17
- - 🏗️ **Fluent Query Builder:** Sintaxis fluida `client.spatial.check(lat, lng).inGeofence(...)` para máxima legibilidad.
18
- - 🚧 **Gestión de geocercas:** Creación dinámica y normalización automática de polígonos GeoJSON respaldados por PostGIS.
19
- - 🔄 **AsyncIngester en segundo plano:** Cola con auto-flush por tamaño de lote e intervalo de tiempo para alta ingesta en flotas e IoT.
20
- - 🛡️ **Seguridad nativa:** Generación automática de firmas HMAC-SHA256 (`X-Signature`), timestamp anti-replay y soporte para tokens JWT Bearer.
21
- - 📦 **Dual Package (ESM & CommonJS):** Compatible con `import` nativo y `require()`, empaquetado con `tsup` y definiciones de tipos `.d.ts`.
22
- - ⚡ **Zero dependencias en runtime:** Desarrollado sobre APIs estándar de Node.js (`fetch` nativo, `node:crypto`, `AbortController`). Compatible con Serverless y Edge (Cloudflare Workers, Next.js, Bun).
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
- ## 🚀 Instalación
31
+ ## 🚀 Installation
27
32
 
28
33
  ```bash
29
34
  npm install geo-engine-node
30
35
  ```
31
36
 
32
- O usando Yarn / PNPM / Bun:
37
+ Or using Yarn / PNPM / Bun:
33
38
 
34
39
  ```bash
35
40
  pnpm add geo-engine-node
36
- # o
41
+ # or
37
42
  bun add geo-engine-node
38
43
  ```
39
44
 
40
45
  ---
41
46
 
42
- ## ⚡ Inicio Rápido
47
+ ## ⚡ Quick Start
43
48
 
44
- ### TypeScript / ES Modules (Recomendado)
49
+ ### TypeScript / ES Modules (Recommended)
45
50
 
46
51
  ```ts
47
52
  import GeoEngine from 'geo-engine-node';
48
53
 
49
- // Inicializa con tu clave secreta de API
50
- const client = new GeoEngine('sk_live_123456');
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('✅ Coordenada enviada con éxito');
61
+ console.log('✅ Coordinate sent successfully');
55
62
  } catch (error) {
56
- console.error('❌ Error al enviar ubicación:', error);
63
+ console.error('❌ Error sending location:', error);
57
64
  } finally {
58
65
  client.close();
59
66
  }
60
67
  ```
61
68
 
62
- ### CommonJS (Legacy)
69
+ ### CommonJS
63
70
 
64
71
  ```js
65
72
  const GeoEngine = require('geo-engine-node');
66
73
 
67
- const client = new GeoEngine('sk_live_123456');
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('Ubicación registrada'))
79
+ .then(() => console.log('Location registered'))
71
80
  .catch((err) => console.error(err));
72
81
  ```
73
82
 
74
83
  ---
75
84
 
76
- ## 🗺️ Módulo Spatial & Validación de Puntos
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
- El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
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
- ### Validación contra una Geocerca Individual
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 client = new GeoEngine('sk_live_123456');
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(`✅ El dispositivo está dentro de ${res.geofenceName} (${res.geofenceId})`);
181
+ console.log(`✅ The device is inside ${res.geofenceName} (${res.geofenceId})`);
92
182
  } else {
93
- console.log('⚠️ El dispositivo está fuera de la geocerca');
183
+ console.log('⚠️ The device is outside the geofence');
94
184
  }
95
185
 
96
- console.log('Coordenadas:', res.coordinates()); // [19.4326, -99.1332]
97
- console.log('Log formateado:', res.toString()); // [INSIDE] geofence=geofence_123 (Centro) at (19.432600, -99.133200)
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('La geocerca solicitada no existe');
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
- ### Validación General (Contra Todas las Geocercas Activas)
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(`Coincide con ${res.totalMatches} geocercas:`, res.geofenceNames());
114
-
115
- if (res.containsGeofence('CDMX Centro')) {
116
- console.log('El vehículo está en CDMX Centro');
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 Centro');
120
- console.log('ID encontrado:', match?.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
- ## 🚧 Creación de Geocercas (Polígonos PostGIS)
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
- Crea zonas espaciales dinámicamente. El SDK valida el formato `[latitud, longitud]`, convierte automáticamente a GeoJSON `[longitud, latitud]` y asegura el cierre del polígono:
276
+ The `client.geoIdentity` module manages access rules and subject assignments:
147
277
 
148
278
  ```ts
149
- const coordenadasZona: [number, number][] = [
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
- 'Parque Logístico Norte',
157
- coordenadasZona,
158
- 'https://mi-api.com/webhooks/geocercas'
314
+ 'North Logistics Park',
315
+ zoneCoordinates,
316
+ 'https://my-api.com/webhooks/geofences'
159
317
  );
160
318
  ```
161
319
 
162
320
  ---
163
321
 
164
- ## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
322
+ ## 🔄 Async Batch Ingestion (`AsyncIngester`)
165
323
 
166
- Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
324
+ Queue telemetry pings in memory and dispatch them periodically (`sendLocation` per ping):
167
325
 
168
326
  ```ts
169
- import GeoEngine, { AsyncIngester } from 'geo-engine-node';
170
-
171
- const client = new GeoEngine('sk_live_123456');
327
+ import GeoEngine from 'geo-engine-node';
172
328
 
173
- // Cola: buffer 5000 pings, flush cada 100 items o cada 500ms
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: 'camion-45',
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 lleno o ingester detenido');
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
- ## 🔧 Configuración Avanzada
195
-
196
- Puedes configurar el cliente mediante el objeto de opciones:
351
+ ## 🔧 Advanced Configuration
197
352
 
198
353
  ```ts
199
- const client = new GeoEngine('sk_live_123456', {
200
- environment: 'live', // 'live' | 'test'
201
- jwtToken: 'mi.jwt.token',
202
- timeout: 5000, // milisegundos
203
- maxRetries: 3, // reintentos con backoff exponencial ante 429/5xx
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
- // O para pruebas locales/mock:
365
+ // Or for local/mock testing:
208
366
  // baseUrl: 'http://localhost:8080',
209
367
  });
210
368
  ```
211
369
 
212
- ### Opciones Disponibles
370
+ ### Available Options
213
371
 
214
- | Opción | Tipo | Descripción | Default |
372
+ | Option | Type | Description | Default |
215
373
  | :--- | :--- | :--- | :--- |
216
- | `apiKey` | `string` | Clave secreta de autenticación | (requerido) |
217
- | `environment` | `string` | Target (`'live'` o `'test'`) para header `X-Geo-Environment` | `'live'` |
218
- | `jwtToken` | `string` | Token Bearer para operaciones autorizadas | `undefined` |
219
- | `apiServiceUrl` | `string` | URL del servicio para consultas espaciales | `'https://api.geoengine.dev'` |
220
- | `ingestUrl` | `string` | URL del servicio de ingestión de telemetría | `'https://ingest.geoengine.dev'` |
221
- | `managementUrl` | `string` | URL del servicio de control y geocercas | `'https://management.geoengine.dev'` |
222
- | `baseUrl` | `string` | Sobrescribe ingest, management y apiService juntas | `undefined` |
223
- | `timeout` | `number` | Tiempo límite de espera en ms (vía `AbortController`) | `10000` |
224
- | `maxRetries` | `number` | Reintentos con backoff exponencial ante fallos transitorios | `2` |
225
- | `batchSize` | `number` | Tamaño de lote para `AsyncIngester` | `100` |
226
- | `flushInterval` | `number` | Intervalo de vaciado de `AsyncIngester` en ms | `500` |
227
- | `bufferSize` | `number` | Capacidad máxima de la cola de `AsyncIngester` | `5000` |
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
- ## 🛡️ Jerarquía de Errores Tipados
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
- El SDK mapea todos los códigos de estado y respuestas en una jerarquía clara de clases de error:
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 o 404 Not Found
414
+ // 204 No Content or 404 Not Found
255
415
  } else if (error instanceof QuotaExceededError) {
256
- // 402 Payment Required o 429
416
+ // 402 Payment Required or reason QUOTA_EXCEEDED
257
417
  } else if (error instanceof AuthenticationError) {
258
- // 401 Unauthorized o MISSING_API_KEY
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
- // Tiempo de espera agotado
422
+ // Request timed out
261
423
  } else if (error instanceof ValidationError) {
262
- // Coordenada fuera de rango [-90,90] o parámetro inválido
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
- ## 🧪 Pruebas y Compilación
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
- Ejecuta la suite de pruebas unitarias e integración con Vitest:
433
+ ---
272
434
 
273
- ```bash
274
- npm run test
275
- ```
435
+ ## 🧪 Testing and Building
276
436
 
277
- Para compilar las salidas CJS y ESM con tipos TypeScript:
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
- ## 📄 Licencia
447
+ ## 📄 License
287
448
 
288
449
  MIT © Geo-Engine Team