geo-engine-node 1.1.2 → 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 +220 -67
- package/dist/index.cjs +924 -64
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +631 -101
- package/dist/index.d.ts +631 -101
- package/dist/index.js +889 -64
- package/dist/index.js.map +1 -0
- package/package.json +20 -9
- package/index.js +0 -110
package/Readme.md
CHANGED
|
@@ -1,10 +1,25 @@
|
|
|
1
|
+
# 📦 Geo-Engine Node.js & TypeScript SDK
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/geo-engine-node)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
[](https://vitest.dev/)
|
|
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.
|
|
1
10
|
|
|
2
11
|
---
|
|
3
12
|
|
|
4
|
-
|
|
13
|
+
## ✨ Features
|
|
5
14
|
|
|
6
|
-
|
|
7
|
-
|
|
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).
|
|
8
23
|
|
|
9
24
|
---
|
|
10
25
|
|
|
@@ -14,116 +29,256 @@ Permite enviar ubicaciones en tiempo real y gestionar **geocercas** desde tus ap
|
|
|
14
29
|
npm install geo-engine-node
|
|
15
30
|
```
|
|
16
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
|
+
```
|
|
39
|
+
|
|
17
40
|
---
|
|
18
41
|
|
|
19
42
|
## ⚡ Inicio Rápido
|
|
20
43
|
|
|
21
|
-
|
|
44
|
+
### TypeScript / ES Modules (Recomendado)
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import GeoEngine from 'geo-engine-node';
|
|
48
|
+
|
|
49
|
+
// Inicializa con tu clave secreta de API
|
|
50
|
+
const client = new GeoEngine('sk_live_123456');
|
|
51
|
+
|
|
52
|
+
try {
|
|
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();
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### CommonJS (Legacy)
|
|
22
63
|
|
|
23
64
|
```js
|
|
24
65
|
const GeoEngine = require('geo-engine-node');
|
|
25
66
|
|
|
26
|
-
|
|
27
|
-
const geo = new GeoEngine('sk_test_12345abcdef');
|
|
67
|
+
const client = new GeoEngine('sk_live_123456');
|
|
28
68
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
.
|
|
32
|
-
.catch(err => console.error('❌ Error:', err.message));
|
|
69
|
+
client.sendLocation('scooter-09', 19.4326, -99.1332)
|
|
70
|
+
.then(() => console.log('Ubicación registrada'))
|
|
71
|
+
.catch((err) => console.error(err));
|
|
33
72
|
```
|
|
34
73
|
|
|
35
74
|
---
|
|
36
75
|
|
|
37
|
-
##
|
|
76
|
+
## 🗺️ Módulo Spatial & Validación de Puntos
|
|
38
77
|
|
|
39
|
-
|
|
78
|
+
El módulo `client.spatial` conecta directamente con el servicio de API de GeoEngine para evaluar contención espacial:
|
|
40
79
|
|
|
41
|
-
|
|
80
|
+
### Validación contra una Geocerca Individual
|
|
42
81
|
|
|
43
|
-
|
|
82
|
+
```ts
|
|
83
|
+
import GeoEngine, { GeofenceNotFoundError } from 'geo-engine-node';
|
|
44
84
|
|
|
45
|
-
|
|
46
|
-
* `options` (`object`, opcional):
|
|
85
|
+
const client = new GeoEngine('sk_live_123456');
|
|
47
86
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
87
|
+
try {
|
|
88
|
+
const res = await client.spatial.validatePoint('geofence_123', 19.4326, -99.1332);
|
|
89
|
+
|
|
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
|
+
```
|
|
51
106
|
|
|
52
|
-
|
|
107
|
+
### Validación General (Contra Todas las Geocercas Activas)
|
|
53
108
|
|
|
54
|
-
|
|
109
|
+
```ts
|
|
110
|
+
const res = await client.spatial.validateGeneral(19.4326, -99.1332);
|
|
55
111
|
|
|
56
|
-
|
|
57
|
-
|
|
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
|
+
}
|
|
58
118
|
|
|
59
|
-
|
|
119
|
+
const match = res.findMatch('CDMX Centro');
|
|
120
|
+
console.log('ID encontrado:', match?.id);
|
|
121
|
+
}
|
|
122
|
+
```
|
|
60
123
|
|
|
61
|
-
|
|
62
|
-
* `lat` (`number`): Latitud decimal.
|
|
63
|
-
* `lng` (`number`): Longitud decimal.
|
|
124
|
+
### Fluent Query Builder
|
|
64
125
|
|
|
65
|
-
|
|
66
|
-
`Promise<Object>` con el estado de la cola (`queued`).
|
|
126
|
+
Para mayor legibilidad, puedes construir consultas fluidas:
|
|
67
127
|
|
|
68
|
-
|
|
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();
|
|
69
134
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
135
|
+
// Validación contra todas las geocercas
|
|
136
|
+
const generalRes = await client.spatial
|
|
137
|
+
.check(19.4326, -99.1332)
|
|
138
|
+
.inAllGeofences()
|
|
139
|
+
.execute();
|
|
140
|
+
```
|
|
73
141
|
|
|
74
|
-
|
|
142
|
+
---
|
|
75
143
|
|
|
76
|
-
|
|
77
|
-
* `coordinates` (`Array<Array<number>>`):
|
|
78
|
-
Lista de puntos que forman el polígono
|
|
79
|
-
`[[lat, lng], [lat, lng], ...]`
|
|
80
|
-
*(El SDK se encarga de cerrar el polígono si es necesario).*
|
|
81
|
-
* `webhookUrl` (`string`):
|
|
82
|
-
URL donde Geo-Engine enviará una petición **POST** cuando un dispositivo entre en esta zona.
|
|
144
|
+
## 🚧 Creación de Geocercas (Polígonos PostGIS)
|
|
83
145
|
|
|
84
|
-
|
|
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:
|
|
85
147
|
|
|
86
|
-
```
|
|
87
|
-
const
|
|
88
|
-
[19.
|
|
89
|
-
[19.
|
|
90
|
-
[19.
|
|
91
|
-
[19.42, -99.15]
|
|
148
|
+
```ts
|
|
149
|
+
const coordenadasZona: [number, number][] = [
|
|
150
|
+
[19.4326, -99.1332],
|
|
151
|
+
[19.4426, -99.1332],
|
|
152
|
+
[19.4426, -99.1232],
|
|
92
153
|
];
|
|
93
154
|
|
|
94
|
-
await
|
|
95
|
-
'
|
|
96
|
-
|
|
97
|
-
'https://mi-api.com/
|
|
155
|
+
await client.createGeofence(
|
|
156
|
+
'Parque Logístico Norte',
|
|
157
|
+
coordenadasZona,
|
|
158
|
+
'https://mi-api.com/webhooks/geocercas'
|
|
98
159
|
);
|
|
99
160
|
```
|
|
100
161
|
|
|
101
162
|
---
|
|
102
163
|
|
|
103
|
-
##
|
|
164
|
+
## 🔄 Ingesta Asíncrona en Lotes (`AsyncIngester`)
|
|
104
165
|
|
|
105
|
-
|
|
166
|
+
Para telemetría masiva de flotas de vehículos o dispositivos IoT, utiliza la cola en memoria con auto-flush:
|
|
167
|
+
|
|
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(),
|
|
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';
|
|
106
249
|
|
|
107
|
-
```js
|
|
108
250
|
try {
|
|
109
|
-
await
|
|
251
|
+
await client.spatial.validatePoint('geo-x', lat, lng);
|
|
110
252
|
} catch (error) {
|
|
111
|
-
|
|
112
|
-
|
|
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
|
+
}
|
|
113
264
|
}
|
|
114
265
|
```
|
|
115
266
|
|
|
116
267
|
---
|
|
117
268
|
|
|
118
|
-
## 🧪
|
|
269
|
+
## 🧪 Pruebas y Compilación
|
|
119
270
|
|
|
120
|
-
|
|
271
|
+
Ejecuta la suite de pruebas unitarias e integración con Vitest:
|
|
121
272
|
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
|
127
282
|
```
|
|
128
283
|
|
|
129
284
|
---
|
|
@@ -131,5 +286,3 @@ const geo = new GeoEngine('mi-clave-local', {
|
|
|
131
286
|
## 📄 Licencia
|
|
132
287
|
|
|
133
288
|
MIT © Geo-Engine Team
|
|
134
|
-
|
|
135
|
-
---
|