geo-engine-node 1.1.3 → 2.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 CHANGED
@@ -1,21 +1,25 @@
1
- # 📦 Geo-Engine Node.js SDK
1
+ # 📦 Geo-Engine Node.js & TypeScript SDK
2
2
 
3
- ![NPM Version](https://img.shields.io/npm/v/geo-engine-node?style=flat-square&color=blue)
4
- ![License](https://img.shields.io/npm/l/geo-engine-node?style=flat-square)
5
- ![Types](https://img.shields.io/npm/types/geo-engine-node?style=flat-square)
6
- ![Size](https://img.shields.io/bundlephobia/minzip/geo-engine-node?style=flat-square)
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
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
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/)
7
7
 
8
- Cliente oficial de alto rendimiento para interactuar con la plataforma **Geo-Engine**.
9
- Procesa ubicaciones en tiempo real, detecta cruces de geocercas y dispara webhooks en milisegundos.
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.
10
10
 
11
11
  ---
12
12
 
13
- ## ✨ Características
13
+ ## ✨ Features
14
14
 
15
- - 🚀 **Rendimiento:** Diseñado para manejar alta ingestión de datos.
16
- - 🛡️ **Type-Safe:** Incluye definiciones TypeScript (`.d.ts`) nativas.
17
- - 📦 **Híbrido:** Funciona con `require` (CommonJS) y `import` (ES Modules).
18
- - ⚡ **Ligero:** Cero dependencias pesadas.
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
23
 
20
24
  ---
21
25
 
@@ -23,105 +27,258 @@ Procesa ubicaciones en tiempo real, detecta cruces de geocercas y dispara webhoo
23
27
 
24
28
  ```bash
25
29
  npm install geo-engine-node
26
- ````
30
+ ```
31
+
32
+ O usando Yarn / PNPM / Bun:
33
+
34
+ ```bash
35
+ pnpm add geo-engine-node
36
+ # o
37
+ bun add geo-engine-node
38
+ ```
27
39
 
28
40
  ---
29
41
 
30
42
  ## ⚡ Inicio Rápido
31
43
 
32
- Geo-Engine soporta tanto sintaxis moderna como clásica.
33
-
34
- ### Opción A: ES Modules (Recomendado)
44
+ ### TypeScript / ES Modules (Recomendado)
35
45
 
36
- ```js
46
+ ```ts
37
47
  import GeoEngine from 'geo-engine-node';
38
48
 
39
- // Inicializa con tu API Key
40
- const geo = new GeoEngine('sk_test_12345abcdef');
49
+ // Inicializa con tu clave secreta de API
50
+ const client = new GeoEngine('sk_live_123456');
41
51
 
42
- // Envía una coordenada (ID, Latitud, Longitud)
43
52
  try {
44
- const res = await geo.sendLocation('camion-01', 19.4326, -99.1332);
45
- console.log('✅ Ubicación procesada:', res);
46
- } catch (err) {
47
- console.error('❌ Error:', err.message);
53
+ await client.sendLocation('truck-01', 19.4326, -99.1332);
54
+ console.log('✅ Coordenada enviada con éxito');
55
+ } catch (error) {
56
+ console.error('❌ Error al enviar ubicación:', error);
57
+ } finally {
58
+ client.close();
48
59
  }
49
60
  ```
50
61
 
51
- ### Opción B: CommonJS (Legacy)
62
+ ### CommonJS (Legacy)
52
63
 
53
64
  ```js
54
65
  const GeoEngine = require('geo-engine-node');
55
66
 
56
- const geo = new GeoEngine('sk_test_...');
67
+ const client = new GeoEngine('sk_live_123456');
68
+
69
+ client.sendLocation('scooter-09', 19.4326, -99.1332)
70
+ .then(() => console.log('Ubicación registrada'))
71
+ .catch((err) => console.error(err));
57
72
  ```
58
73
 
59
74
  ---
60
75
 
61
- ## 📚 Referencia de la API
76
+ ## 🗺️ Módulo Spatial & Validación de Puntos
62
77
 
63
- ### `new GeoEngine(apiKey, [options])`
78
+ El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
64
79
 
65
- Crea una nueva instancia del cliente.
80
+ ### Validación contra una Geocerca Individual
66
81
 
67
- **Parámetros:**
82
+ ```ts
83
+ import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
68
84
 
69
- * `apiKey` (`string`): Tu clave secreta de API.
70
- * `options` (`object`, opcional):
85
+ const client = new GeoEngine('sk_live_123456');
71
86
 
72
- * `timeout`: Tiempo de espera en ms (default: `10000`)
73
- * `ingestUrl`: URL personalizada (útil para proxies o testing)
74
- * `managementUrl`: URL del servicio de administración
87
+ try {
88
+ const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
75
89
 
76
- ---
90
+ if (res.isInside()) {
91
+ console.log(`✅ El dispositivo está dentro de ${res.geofenceName} (${res.geofenceId})`);
92
+ } else {
93
+ console.log('⚠️ El dispositivo está fuera de la geocerca');
94
+ }
95
+
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)
98
+ } catch (err) {
99
+ if (err instanceof GeofenceNotFoundError) {
100
+ console.warn('La geocerca solicitada no existe');
101
+ } else {
102
+ throw err;
103
+ }
104
+ }
105
+ ```
77
106
 
78
- ### `geo.sendLocation(deviceId, lat, lng)`
107
+ ### Validación General (Contra Todas las Geocercas Activas)
79
108
 
80
- Envía un punto de rastreo al motor de ingestión.
81
- El sistema evaluará automáticamente las reglas espaciales.
109
+ ```ts
110
+ const res = await client.spatial.validateGeneral(19.4326, -99.1332);
82
111
 
83
- **Parámetros:**
112
+ 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');
117
+ }
84
118
 
85
- * `deviceId` (`string`): ID único (placa, UUID, etc).
86
- * `lat` (`number`): Latitud decimal (Ej: `19.43`)
87
- * `lng` (`number`): Longitud decimal (Ej: `-99.13`)
119
+ const match = res.findMatch('CDMX Centro');
120
+ console.log('ID encontrado:', match?.id);
121
+ }
122
+ ```
88
123
 
89
- ---
124
+ ### Fluent Query Builder
90
125
 
91
- ### `geo.createGeofence(name, coordinates, webhookUrl)`
126
+ Para mayor legibilidad, puedes construir consultas fluidas:
92
127
 
93
- Crea dinámicamente una zona de monitoreo.
94
- Geo-Engine enviará un `POST` a tu webhook cuando un activo entre o salga.
128
+ ```ts
129
+ // Validación en geocerca específica
130
+ const singleRes = await client.spatial
131
+ .check(19.4326, -99.1332)
132
+ .inGeofence('geofence_123')
133
+ .execute();
95
134
 
96
- **Ejemplo:**
135
+ // Validación contra todas las geocercas
136
+ const generalRes = await client.spatial
137
+ .check(19.4326, -99.1332)
138
+ .inAllGeofences()
139
+ .execute();
140
+ ```
97
141
 
98
- ```js
99
- // Definir polígono: Array de [Lat, Lng]
100
- const zona = [
101
- [19.42, -99.16],
102
- [19.41, -99.16],
103
- [19.41, -99.15],
104
- [19.42, -99.15]
142
+ ---
143
+
144
+ ## 🚧 Creación de Geocercas (Polígonos PostGIS)
145
+
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:
147
+
148
+ ```ts
149
+ const coordenadasZona: [number, number][] = [
150
+ [19.4326, -99.1332],
151
+ [19.4426, -99.1332],
152
+ [19.4426, -99.1232],
105
153
  ];
106
154
 
107
- await geo.createGeofence(
108
- 'Almacén Central',
109
- zona,
110
- 'https://mi-api.com/webhooks/geofence-alert'
155
+ await client.createGeofence(
156
+ 'Parque Logístico Norte',
157
+ coordenadasZona,
158
+ 'https://mi-api.com/webhooks/geocercas'
111
159
  );
112
160
  ```
113
161
 
114
162
  ---
115
163
 
116
- ## 🧪 Desarrollo Local
164
+ ## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
117
165
 
118
- Ideal para probar con tu propia instancia de Geo-Engine corriendo en Docker o Localhost.
166
+ Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
119
167
 
120
- ```js
121
- const geo = new GeoEngine('local-key', {
122
- ingestUrl: 'http://localhost:8080',
123
- managementUrl: 'http://localhost:8081'
168
+ ```ts
169
+ import GeoEngine, { AsyncIngester } from 'geo-engine-node';
170
+
171
+ const client = new GeoEngine('sk_live_123456');
172
+
173
+ // Cola: buffer 5000 pings, flush cada 100 items o cada 500ms
174
+ const ingester = client.createAsyncIngester(5000, 100, 500);
175
+
176
+ const ok = ingester.enqueue({
177
+ deviceId: 'camion-45',
178
+ latitude: 19.4326,
179
+ longitude: -99.1332,
180
+ timestamp: Date.now(),
124
181
  });
182
+
183
+ if (!ok) {
184
+ console.warn('Buffer lleno o ingester detenido');
185
+ }
186
+
187
+ // Al apagar el servicio, drena todos los elementos pendientes:
188
+ await ingester.stop();
189
+ client.close();
190
+ ```
191
+
192
+ ---
193
+
194
+ ## 🔧 Configuración Avanzada
195
+
196
+ Puedes configurar el cliente mediante el objeto de opciones:
197
+
198
+ ```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
204
+ managementUrl: 'https://management.geoengine.dev',
205
+ ingestUrl: 'https://ingest.geoengine.dev',
206
+ apiServiceUrl: 'https://api.geoengine.dev',
207
+ // O para pruebas locales/mock:
208
+ // baseUrl: 'http://localhost:8080',
209
+ });
210
+ ```
211
+
212
+ ### Opciones Disponibles
213
+
214
+ | Opción | Tipo | Descripción | Default |
215
+ | :--- | :--- | :--- | :--- |
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` |
228
+
229
+ ---
230
+
231
+ ## 🛡️ Jerarquía de Errores Tipados
232
+
233
+ El SDK mapea todos los códigos de estado y respuestas en una jerarquía clara de clases de error:
234
+
235
+ ```ts
236
+ import {
237
+ GeoEngineError,
238
+ ValidationError,
239
+ InvalidLatitudeError,
240
+ InvalidLongitudeError,
241
+ DeviceIDRequiredError,
242
+ GeofenceNotFoundError,
243
+ QuotaExceededError,
244
+ AuthenticationError,
245
+ ForbiddenError,
246
+ TimeoutError,
247
+ SpatialAPIError,
248
+ } from 'geo-engine-node';
249
+
250
+ try {
251
+ await client.spatial.validatePoint('geo-x', lat, lng);
252
+ } catch (error) {
253
+ if (error instanceof GeofenceNotFoundError) {
254
+ // 204 No Content o 404 Not Found
255
+ } else if (error instanceof QuotaExceededError) {
256
+ // 402 Payment Required o 429
257
+ } else if (error instanceof AuthenticationError) {
258
+ // 401 Unauthorized o MISSING_API_KEY
259
+ } else if (error instanceof TimeoutError) {
260
+ // Tiempo de espera agotado
261
+ } else if (error instanceof ValidationError) {
262
+ // Coordenada fuera de rango [-90,90] o parámetro inválido
263
+ }
264
+ }
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 🧪 Pruebas y Compilación
270
+
271
+ Ejecuta la suite de pruebas unitarias e integración con Vitest:
272
+
273
+ ```bash
274
+ npm run test
275
+ ```
276
+
277
+ Para compilar las salidas CJS y ESM con tipos TypeScript:
278
+
279
+ ```bash
280
+ npm run build
281
+ npm run typecheck
125
282
  ```
126
283
 
127
284
  ---
@@ -129,4 +286,3 @@ const geo = new GeoEngine('local-key', {
129
286
  ## 📄 Licencia
130
287
 
131
288
  MIT © Geo-Engine Team
132
-