geo-engine-node 2.0.0 → 2.1.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 CHANGED
@@ -5,55 +5,59 @@
5
5
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue.svg)](https://www.typescriptlang.org/)
6
6
  [![Tests](https://img.shields.io/badge/Tests-Vitest-green.svg)](https://vitest.dev/)
7
7
 
8
+ > *Read this in Spanish: [README.es.md](./README.es.md)*
9
+
8
10
  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.
11
+ Designed for **high performance**, strict type-safety, and 1:1 parity with the official Go SDK (`v2.1.0`). Seamlessly integrates into backend microservices, Serverless functions, and modern edge environments.
10
12
 
11
13
  ---
12
14
 
13
15
  ## ✨ Features
14
16
 
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).
17
+ - 📍 **Real-time Ingestion:** Sub-10ms telemetry coordinate dispatch via HTTP REST.
18
+ - 🗺️ **Advanced Spatial Module:** High-performance Point-in-Polygon spatial evaluation (single and general validation against all geofences).
19
+ - 👥 **Users Module:** Management of organization members, roles, and email invitations.
20
+ - 🛡️ **GeoIdentity Module:** Access rules (IP blacklists, geographic boundaries, Tor/datacenter blocking) assignable to users or to the entire organization.
21
+ - 🏗️ **Fluent Query Builder:** Fluent syntax `client.spatial.check(lat, lng).inGeofence(...)` for maximum readability.
22
+ - 🚧 **Geofence Management:** Dynamic creation and automatic normalization of PostGIS-backed GeoJSON polygons.
23
+ - 🔄 **Background AsyncIngester:** In-memory queue with auto-flush by batch size and time interval for high-throughput fleet and IoT ingestion.
24
+ - 🛡️ **Native Security:** Automatic HMAC-SHA256 signature generation (`X-Signature`), anti-replay timestamps, and JWT Bearer token support.
25
+ - 📦 **Dual Package (ESM & CommonJS):** Compatible with native `import` and `require()`, bundled with `tsup` and full `.d.ts` type definitions.
26
+ - ⚡ **Zero Runtime Dependencies:** Built on standard Node.js APIs (native `fetch`, `node:crypto`, `AbortController`). Compatible with Serverless and Edge runtimes (Cloudflare Workers, Next.js, Bun).
23
27
 
24
28
  ---
25
29
 
26
- ## 🚀 Instalación
30
+ ## 🚀 Installation
27
31
 
28
32
  ```bash
29
33
  npm install geo-engine-node
30
34
  ```
31
35
 
32
- O usando Yarn / PNPM / Bun:
36
+ Or using Yarn / PNPM / Bun:
33
37
 
34
38
  ```bash
35
39
  pnpm add geo-engine-node
36
- # o
40
+ # or
37
41
  bun add geo-engine-node
38
42
  ```
39
43
 
40
44
  ---
41
45
 
42
- ## ⚡ Inicio Rápido
46
+ ## ⚡ Quick Start
43
47
 
44
- ### TypeScript / ES Modules (Recomendado)
48
+ ### TypeScript / ES Modules (Recommended)
45
49
 
46
50
  ```ts
47
51
  import GeoEngine from 'geo-engine-node';
48
52
 
49
- // Inicializa con tu clave secreta de API
50
- const client = new GeoEngine('sk_live_123456');
53
+ // Initialize with your secret API key
54
+ const client = new GeoEngine('geo_live_123456');
51
55
 
52
56
  try {
53
57
  await client.sendLocation('truck-01', 19.4326, -99.1332);
54
- console.log('✅ Coordenada enviada con éxito');
58
+ console.log('✅ Coordinate sent successfully');
55
59
  } catch (error) {
56
- console.error('❌ Error al enviar ubicación:', error);
60
+ console.error('❌ Error sending location:', error);
57
61
  } finally {
58
62
  client.close();
59
63
  }
@@ -64,75 +68,75 @@ try {
64
68
  ```js
65
69
  const GeoEngine = require('geo-engine-node');
66
70
 
67
- const client = new GeoEngine('sk_live_123456');
71
+ const client = new GeoEngine('geo_live_123456');
68
72
 
69
73
  client.sendLocation('scooter-09', 19.4326, -99.1332)
70
- .then(() => console.log('Ubicación registrada'))
74
+ .then(() => console.log('Location registered'))
71
75
  .catch((err) => console.error(err));
72
76
  ```
73
77
 
74
78
  ---
75
79
 
76
- ## 🗺️ Módulo Spatial & Validación de Puntos
80
+ ## 🗺️ Spatial Module & Point Validation
77
81
 
78
- El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
82
+ The `client.spatial` module connects directly to the GeoEngine API service to evaluate spatial containment:
79
83
 
80
- ### Validación contra una Geocerca Individual
84
+ ### Single Geofence Validation
81
85
 
82
86
  ```ts
83
87
  import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
84
88
 
85
- const client = new GeoEngine('sk_live_123456');
89
+ const client = new GeoEngine('geo_live_123456');
86
90
 
87
91
  try {
88
92
  const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
89
93
 
90
94
  if (res.isInside()) {
91
- console.log(`✅ El dispositivo está dentro de ${res.geofenceName} (${res.geofenceId})`);
95
+ console.log(`✅ The device is inside ${res.geofenceName} (${res.geofenceId})`);
92
96
  } else {
93
- console.log('⚠️ El dispositivo está fuera de la geocerca');
97
+ console.log('⚠️ The device is outside the geofence');
94
98
  }
95
99
 
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)
100
+ console.log('Coordinates:', res.coordinates()); // [19.4326, -99.1332]
101
+ console.log('Formatted log:', res.toString()); // [INSIDE] geofence=geofence_123 (Downtown) at (19.432600, -99.133200)
98
102
  } catch (err) {
99
103
  if (err instanceof GeofenceNotFoundError) {
100
- console.warn('La geocerca solicitada no existe');
104
+ console.warn('The requested geofence does not exist');
101
105
  } else {
102
106
  throw err;
103
107
  }
104
108
  }
105
109
  ```
106
110
 
107
- ### Validación General (Contra Todas las Geocercas Activas)
111
+ ### General Validation (Against All Active Geofences)
108
112
 
109
113
  ```ts
110
114
  const res = await client.spatial.validateGeneral(19.4326, -99.1332);
111
115
 
112
116
  if (res.hasMatches()) {
113
- console.log(`Coincide con ${res.totalMatches} geocercas:`, res.geofenceNames());
117
+ console.log(`Matched ${res.totalMatches} geofences:`, res.geofenceNames());
114
118
 
115
- if (res.containsGeofence('CDMX Centro')) {
116
- console.log('El vehículo está en CDMX Centro');
119
+ if (res.containsGeofence('CDMX Downtown')) {
120
+ console.log('The vehicle is in CDMX Downtown');
117
121
  }
118
122
 
119
- const match = res.findMatch('CDMX Centro');
120
- console.log('ID encontrado:', match?.id);
123
+ const match = res.findMatch('CDMX Downtown');
124
+ console.log('Found ID:', match?.id);
121
125
  }
122
126
  ```
123
127
 
124
128
  ### Fluent Query Builder
125
129
 
126
- Para mayor legibilidad, puedes construir consultas fluidas:
130
+ For maximum readability, you can construct fluent queries:
127
131
 
128
132
  ```ts
129
- // Validación en geocerca específica
133
+ // Validation in a specific geofence
130
134
  const singleRes = await client.spatial
131
135
  .check(19.4326, -99.1332)
132
136
  .inGeofence('geofence_123')
133
137
  .execute();
134
138
 
135
- // Validación contra todas las geocercas
139
+ // Validation against all geofences
136
140
  const generalRes = await client.spatial
137
141
  .check(19.4326, -99.1332)
138
142
  .inAllGeofences()
@@ -141,96 +145,180 @@ const generalRes = await client.spatial
141
145
 
142
146
  ---
143
147
 
144
- ## 🚧 Creación de Geocercas (Polígonos PostGIS)
148
+ ## 👥 Users Module
149
+
150
+ The `client.users` module manages the members of the organization that owns the API key:
151
+
152
+ ```ts
153
+ import GeoEngine, { Roles, InvitationPendingError, LastAdminError } from 'geo-engine-node';
154
+
155
+ const client = new GeoEngine('geo_live_123456');
156
+
157
+ // List members and available roles
158
+ const users = await client.users.list();
159
+ const roles = await client.users.listRoles();
160
+ const user = await client.users.get('user_123');
161
+
162
+ // Invite a new member (GeoEngine sends the invitation email)
163
+ try {
164
+ const inv = await client.users.invite({
165
+ email: 'ana@acme.com',
166
+ role: Roles.Viewer,
167
+ lang: 'es', // 'es' (default) | 'en' | 'pt'
168
+ });
169
+ console.log('Invitation link:', inv.inviteUrl);
170
+ } catch (err) {
171
+ if (err instanceof InvitationPendingError) {
172
+ console.warn('There is already a pending invitation for this email');
173
+ } else {
174
+ throw err;
175
+ }
176
+ }
177
+
178
+ // Update a member's role or revoke their access
179
+ try {
180
+ await client.users.updateRole('user_123', Roles.Dispatcher);
181
+ await client.users.remove('user_123');
182
+ } catch (err) {
183
+ if (err instanceof LastAdminError) {
184
+ console.warn('The organization must retain at least one administrator');
185
+ } else {
186
+ throw err;
187
+ }
188
+ }
189
+ ```
190
+
191
+ ---
192
+
193
+ ## 🛡️ GeoIdentity Module
194
+
195
+ The `client.geoIdentity` module creates access rules and assigns them to a user or to the entire organization:
196
+
197
+ ```ts
198
+ import { polygonFromLatLng, RuleActions, SubjectTypes } from 'geo-engine-node';
199
+
200
+ const area = polygonFromLatLng([
201
+ [19.40, -99.20], [19.40, -99.10], [19.50, -99.10], // [lat, lng]
202
+ ]);
203
+
204
+ const rule = await client.geoIdentity.createRule({
205
+ name: 'CDMX Only',
206
+ action: RuleActions.Block,
207
+ blackIpList: ['203.0.113.0/24'],
208
+ blockTor: true,
209
+ geoLimit: area,
210
+ assignedSubjects: [{ subjectType: SubjectTypes.User, subjectId: 'user_123' }],
211
+ });
212
+
213
+ // Query, update, and delete
214
+ const rules = await client.geoIdentity.listRules({ isActive: true });
215
+ const detail = await client.geoIdentity.getRule(rule.id); // includes assignedSubjects
216
+ await client.geoIdentity.updateRule(rule.id, { isActive: false, geoLimit: null }); // null removes the geographic boundary
217
+ await client.geoIdentity.deleteRule(rule.id);
218
+
219
+ // Assign or unassign the rule
220
+ await client.geoIdentity.assignToUser(rule.id, 'user_456');
221
+ await client.geoIdentity.assignToOrganization(rule.id);
222
+ await client.geoIdentity.unassignFromUser(rule.id, 'user_456');
223
+
224
+ // Rules that apply to a user (direct, by role, or organization-wide)
225
+ const userRules = await client.geoIdentity.listUserRules('user_123');
226
+ ```
227
+
228
+ > A rule created without `assignedSubjects` applies to the entire organization. A rule must always retain at least one subject: removing the last subject throws `LastSubjectError` (deactivate or delete the rule instead).
229
+
230
+ ---
231
+
232
+ ## 🚧 Geofence Creation (PostGIS Polygons)
145
233
 
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:
234
+ Create spatial zones dynamically. The SDK validates the `[latitude, longitude]` format, automatically converts it to GeoJSON `[longitude, latitude]`, and ensures the polygon is closed:
147
235
 
148
236
  ```ts
149
- const coordenadasZona: [number, number][] = [
237
+ const zoneCoordinates: [number, number][] = [
150
238
  [19.4326, -99.1332],
151
239
  [19.4426, -99.1332],
152
240
  [19.4426, -99.1232],
153
241
  ];
154
242
 
155
243
  await client.createGeofence(
156
- 'Parque Logístico Norte',
157
- coordenadasZona,
158
- 'https://mi-api.com/webhooks/geocercas'
244
+ 'North Logistics Park',
245
+ zoneCoordinates,
246
+ 'https://my-api.com/webhooks/geofences'
159
247
  );
160
248
  ```
161
249
 
162
250
  ---
163
251
 
164
- ## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
252
+ ## 🔄 High-Throughput Async Batch Ingestion (`AsyncIngester`)
165
253
 
166
- Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
254
+ For high-volume fleet tracking or IoT telemetry, use the in-memory queue with auto-flush:
167
255
 
168
256
  ```ts
169
257
  import GeoEngine, { AsyncIngester } from 'geo-engine-node';
170
258
 
171
- const client = new GeoEngine('sk_live_123456');
259
+ const client = new GeoEngine('geo_live_123456');
172
260
 
173
- // Cola: buffer 5000 pings, flush cada 100 items o cada 500ms
261
+ // Queue: 5000 pings buffer, flush every 100 items or every 500ms
174
262
  const ingester = client.createAsyncIngester(5000, 100, 500);
175
263
 
176
264
  const ok = ingester.enqueue({
177
- deviceId: 'camion-45',
265
+ deviceId: 'truck-45',
178
266
  latitude: 19.4326,
179
267
  longitude: -99.1332,
180
268
  timestamp: Date.now(),
181
269
  });
182
270
 
183
271
  if (!ok) {
184
- console.warn('Buffer lleno o ingester detenido');
272
+ console.warn('Buffer queue full or ingester stopped');
185
273
  }
186
274
 
187
- // Al apagar el servicio, drena todos los elementos pendientes:
275
+ // On service shutdown, drain all pending items:
188
276
  await ingester.stop();
189
277
  client.close();
190
278
  ```
191
279
 
192
280
  ---
193
281
 
194
- ## 🔧 Configuración Avanzada
282
+ ## 🔧 Advanced Configuration
195
283
 
196
- Puedes configurar el cliente mediante el objeto de opciones:
284
+ You can configure the client using the options object:
197
285
 
198
286
  ```ts
199
- const client = new GeoEngine('sk_live_123456', {
287
+ const client = new GeoEngine('geo_live_123456', {
200
288
  environment: 'live', // 'live' | 'test'
201
- jwtToken: 'mi.jwt.token',
202
- timeout: 5000, // milisegundos
203
- maxRetries: 3, // reintentos con backoff exponencial ante 429/5xx
289
+ jwtToken: 'my.jwt.token',
290
+ timeout: 5000, // milliseconds
291
+ maxRetries: 3, // retries with exponential backoff on 429/5xx
204
292
  managementUrl: 'https://management.geoengine.dev',
205
293
  ingestUrl: 'https://ingest.geoengine.dev',
206
294
  apiServiceUrl: 'https://api.geoengine.dev',
207
- // O para pruebas locales/mock:
295
+ // Or for local/mock testing:
208
296
  // baseUrl: 'http://localhost:8080',
209
297
  });
210
298
  ```
211
299
 
212
- ### Opciones Disponibles
300
+ ### Available Options
213
301
 
214
- | Opción | Tipo | Descripción | Default |
302
+ | Option | Type | Description | Default |
215
303
  | :--- | :--- | :--- | :--- |
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` |
304
+ | `apiKey` | `string` | Secret authentication key | (required) |
305
+ | `environment` | `string` | Target (`'live'` or `'test'`) for the `X-Geo-Environment` header | `'live'` |
306
+ | `jwtToken` | `string` | Bearer token for authorized operations | `undefined` |
307
+ | `apiServiceUrl` | `string` | URL of the API service (Spatial, Users, and GeoIdentity) | `'https://api.geoengine.dev'` |
308
+ | `ingestUrl` | `string` | URL of the telemetry ingestion service | `'https://ingest.geoengine.dev'` |
309
+ | `managementUrl` | `string` | URL of the control plane and geofence service | `'https://management.geoengine.dev'` |
310
+ | `baseUrl` | `string` | Overrides ingest, management, and apiService endpoints together | `undefined` |
311
+ | `timeout` | `number` | Request timeout in ms (via `AbortController`) | `10000` |
312
+ | `maxRetries` | `number` | Retries with exponential backoff on transient errors | `2` |
313
+ | `batchSize` | `number` | Batch size for `AsyncIngester` | `100` |
314
+ | `flushInterval` | `number` | Flush interval for `AsyncIngester` in ms | `500` |
315
+ | `bufferSize` | `number` | Maximum queue capacity for `AsyncIngester` | `5000` |
228
316
 
229
317
  ---
230
318
 
231
- ## 🛡️ Jerarquía de Errores Tipados
319
+ ## 🛡️ Typed Error Hierarchy
232
320
 
233
- El SDK mapea todos los códigos de estado y respuestas en una jerarquía clara de clases de error:
321
+ The SDK maps all HTTP status codes and responses into a clean error class hierarchy:
234
322
 
235
323
  ```ts
236
324
  import {
@@ -251,30 +339,45 @@ try {
251
339
  await client.spatial.validatePoint('geo-x', lat, lng);
252
340
  } catch (error) {
253
341
  if (error instanceof GeofenceNotFoundError) {
254
- // 204 No Content o 404 Not Found
342
+ // 204 No Content or 404 Not Found
255
343
  } else if (error instanceof QuotaExceededError) {
256
- // 402 Payment Required o 429
344
+ // 402 Payment Required or 429
257
345
  } else if (error instanceof AuthenticationError) {
258
- // 401 Unauthorized o MISSING_API_KEY
346
+ // 401 Unauthorized or MISSING_API_KEY
259
347
  } else if (error instanceof TimeoutError) {
260
- // Tiempo de espera agotado
348
+ // Request timed out
261
349
  } else if (error instanceof ValidationError) {
262
- // Coordenada fuera de rango [-90,90] o parámetro inválido
350
+ // Coordinate out of range [-90,90] or invalid parameter
263
351
  }
264
352
  }
265
353
  ```
266
354
 
355
+ The Users and GeoIdentity modules throw `APIServiceError` (with `statusCode`, `code`, and `apiMessage`) or one of its subclasses:
356
+
357
+ | Error | API Code | When it occurs |
358
+ | :--- | :--- | :--- |
359
+ | `UserNotFoundError` | `USER_NOT_FOUND`, `USER_REVOKED` | User does not exist in the organization |
360
+ | `RuleNotFoundError` | `RULE_NOT_FOUND` | GeoIdentity rule does not exist |
361
+ | `UserAlreadyExistsError` | `USER_ALREADY_EXISTS` | Invited email already belongs to the organization |
362
+ | `InvitationPendingError` | `INVITATION_PENDING` | There is already a pending invitation for this email |
363
+ | `LastAdminError` | `LAST_ADMIN` | Operation would leave the organization without administrators |
364
+ | `LastSubjectError` | `LAST_SUBJECT` | Operation would leave the rule without assigned subjects |
365
+
366
+ Errors 401, 403, and 402 reuse `AuthenticationError`, `ForbiddenError`, and `QuotaExceededError`. Local validations throw `UserIDRequiredError`, `RuleIDRequiredError`, `RuleNameRequiredError`, `EmailRequiredError`, or `RoleRequiredError` without calling the API.
367
+
368
+ > In Users and GeoIdentity, only read requests (`GET`) are automatically retried on 429/5xx; write operations are never retried to prevent duplicate invitations or assignments.
369
+
267
370
  ---
268
371
 
269
- ## 🧪 Pruebas y Compilación
372
+ ## 🧪 Testing and Building
270
373
 
271
- Ejecuta la suite de pruebas unitarias e integración con Vitest:
374
+ Run the unit and integration test suite with Vitest:
272
375
 
273
376
  ```bash
274
377
  npm run test
275
378
  ```
276
379
 
277
- Para compilar las salidas CJS y ESM con tipos TypeScript:
380
+ To compile CJS and ESM outputs with TypeScript type definitions:
278
381
 
279
382
  ```bash
280
383
  npm run build
@@ -283,6 +386,6 @@ npm run typecheck
283
386
 
284
387
  ---
285
388
 
286
- ## 📄 Licencia
389
+ ## 📄 License
287
390
 
288
391
  MIT © Geo-Engine Team