@geolonia/geonicdb-sdk 0.3.0 → 0.5.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/geonicdb.mjs CHANGED
@@ -147,6 +147,8 @@ var RECONNECT_MAX_ATTEMPTS = 10;
147
147
  var RECONNECT_BASE_MS = 1e3;
148
148
  var RECONNECT_MAX_DELAY_MS = 3e4;
149
149
  var SUB_PROTOCOL = "access_token";
150
+ var SDK_CACHE_MAX_ENTRIES_DEFAULT = 1e3;
151
+ var SDK_POLL_INTERVAL_MS_DEFAULT = 5e3;
150
152
 
151
153
  // src/sdk/errors.ts
152
154
  var GeonicDBError = class extends Error {
@@ -223,6 +225,93 @@ function createErrorFromResponse(status, body, fallbackMessage) {
223
225
  }
224
226
  }
225
227
 
228
+ // src/sdk/cache.ts
229
+ var SdkCache = class {
230
+ constructor(maxEntries = SDK_CACHE_MAX_ENTRIES_DEFAULT) {
231
+ __publicField(this, "_store", /* @__PURE__ */ new Map());
232
+ __publicField(this, "_maxEntries");
233
+ if (!Number.isInteger(maxEntries) || maxEntries <= 0) {
234
+ throw new Error(`SdkCache maxEntries must be a positive integer, got ${String(maxEntries)}`);
235
+ }
236
+ this._maxEntries = maxEntries;
237
+ }
238
+ /** Build a stable cache key. Method is upper-cased so casing differences do not produce duplicate entries. */
239
+ static keyFor(method, path) {
240
+ return `${method.toUpperCase()}:${path}`;
241
+ }
242
+ /** Returns the entry and bumps it to most-recent position, or `undefined`. */
243
+ get(key) {
244
+ const entry = this._store.get(key);
245
+ if (!entry) return void 0;
246
+ this._store.delete(key);
247
+ this._store.set(key, entry);
248
+ return entry;
249
+ }
250
+ /** Insert or replace an entry. Evicts the LRU entry when over capacity. */
251
+ set(key, entry) {
252
+ if (this._store.has(key)) {
253
+ this._store.delete(key);
254
+ }
255
+ this._store.set(key, entry);
256
+ while (this._store.size > this._maxEntries) {
257
+ const oldest = this._store.keys().next().value;
258
+ if (oldest === void 0) break;
259
+ this._store.delete(oldest);
260
+ }
261
+ }
262
+ /** Delete a specific entry. Returns whether anything was removed. */
263
+ delete(key) {
264
+ return this._store.delete(key);
265
+ }
266
+ /**
267
+ * Delete every entry whose key matches a predicate. Returns the array of
268
+ * removed keys so callers can emit `cacheInvalidated` events.
269
+ */
270
+ deleteWhere(predicate) {
271
+ const removed = [];
272
+ for (const [key, entry] of this._store) {
273
+ if (predicate(key, entry)) {
274
+ this._store.delete(key);
275
+ removed.push(key);
276
+ }
277
+ }
278
+ return removed;
279
+ }
280
+ /** Drop everything. */
281
+ clear() {
282
+ this._store.clear();
283
+ }
284
+ /** Current entry count. Useful for tests / metrics. */
285
+ size() {
286
+ return this._store.size;
287
+ }
288
+ };
289
+ var HEADERS_TO_PERSIST = [
290
+ "content-type",
291
+ "etag",
292
+ "last-modified",
293
+ "cache-control",
294
+ "vary",
295
+ "link",
296
+ "ngsild-results-count",
297
+ "fiware-total-count",
298
+ "x-total-count",
299
+ "ngsild-next",
300
+ "fiware-next-token"
301
+ ];
302
+ function snapshotHeaders(headers) {
303
+ const out = {};
304
+ for (const name of HEADERS_TO_PERSIST) {
305
+ const value = headers.get(name);
306
+ if (value !== null) out[name] = value;
307
+ }
308
+ return out;
309
+ }
310
+ function isCacheableMethod(method) {
311
+ const upper = method.toUpperCase();
312
+ return upper === "GET" || upper === "HEAD";
313
+ }
314
+
226
315
  // src/sdk/auth.ts
227
316
  var _AuthManager = class _AuthManager {
228
317
  constructor(baseUrl, apiKey, tenant, debug = false) {
@@ -240,6 +329,16 @@ var _AuthManager = class _AuthManager {
240
329
  __publicField(this, "_tokenPromise", null);
241
330
  /** Callback to emit tokenRefresh events. Set by GeonicDB class. */
242
331
  __publicField(this, "onTokenRefresh", null);
332
+ /**
333
+ * SDK-level cache (#991 Phase A). When set, cacheable GET requests are
334
+ * served via ETag/304 with automatic If-None-Match negotiation, and
335
+ * concurrent requests to the same path are deduplicated.
336
+ */
337
+ __publicField(this, "_cache", null);
338
+ /** Emitter for cacheHit / cacheMiss / cacheInvalidated events. */
339
+ __publicField(this, "_emitCacheEvent", null);
340
+ /** In-flight request map keyed by `${METHOD}:${path}` for request deduplication. */
341
+ __publicField(this, "_inFlight", /* @__PURE__ */ new Map());
243
342
  this._baseUrl = baseUrl;
244
343
  this._apiKey = apiKey;
245
344
  this._tenant = tenant;
@@ -255,6 +354,22 @@ var _AuthManager = class _AuthManager {
255
354
  _log(...args) {
256
355
  if (this._debug) console.log("[GeonicDB]", ...args);
257
356
  }
357
+ /** Wire an SdkCache instance (called by GeonicDB constructor when caching is enabled). */
358
+ setCache(cache) {
359
+ this._cache = cache;
360
+ }
361
+ /** Provide the cache event emitter (forwarded to the GeonicDB EventEmitter). */
362
+ setCacheEventEmitter(emitter) {
363
+ this._emitCacheEvent = emitter;
364
+ }
365
+ /** Expose the cache for invalidation (e.g. WebSocket entity events). */
366
+ getCache() {
367
+ return this._cache;
368
+ }
369
+ /** Emit a cache event if a listener is wired. */
370
+ emitCacheEvent(name, payload) {
371
+ this._emitCacheEvent?.(name, payload);
372
+ }
258
373
  /** Login with email and password (Bearer JWT). */
259
374
  async login(email, password) {
260
375
  this._log("login", email);
@@ -278,6 +393,7 @@ var _AuthManager = class _AuthManager {
278
393
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
279
394
  this._tokenType = "Bearer";
280
395
  this._refreshToken = data.refreshToken;
396
+ this._invalidateAuthScopedState();
281
397
  return data;
282
398
  }
283
399
  /**
@@ -292,6 +408,7 @@ var _AuthManager = class _AuthManager {
292
408
  this._tokenExpiry = opts.expiresIn != null ? Date.now() + (opts.expiresIn - 60) * 1e3 : Date.now() + DEFAULT_TOKEN_TTL_SEC * 1e3;
293
409
  this._refreshToken = opts.refreshToken || null;
294
410
  this._tokenPromise = null;
411
+ this._invalidateAuthScopedState();
295
412
  }
296
413
  /** Clear all credentials. */
297
414
  logout() {
@@ -299,6 +416,17 @@ var _AuthManager = class _AuthManager {
299
416
  this._tokenExpiry = 0;
300
417
  this._refreshToken = null;
301
418
  this._tokenPromise = null;
419
+ this._invalidateAuthScopedState();
420
+ }
421
+ /**
422
+ * Drop everything that may have been associated with the previous auth
423
+ * context. Called on `login()` (after token assignment), `setCredentials()`,
424
+ * and `logout()`. Without this, a cached body or in-flight Response from
425
+ * user A could be returned to user B after a credentials swap.
426
+ */
427
+ _invalidateAuthScopedState() {
428
+ this._cache?.clear();
429
+ this._inFlight.clear();
302
430
  }
303
431
  /** Ensure a valid token is available, refreshing or acquiring as needed. */
304
432
  async ensureToken() {
@@ -418,15 +546,89 @@ var _AuthManager = class _AuthManager {
418
546
  }
419
547
  /**
420
548
  * Make an authenticated HTTP request with automatic token refresh and DPoP.
549
+ *
550
+ * When the SDK cache is enabled and the request is cacheable
551
+ * (GET / HEAD without a body), this method:
552
+ * - Sends `If-None-Match` / `If-Modified-Since` derived from a previously
553
+ * cached entry, if any.
554
+ * - Returns the cached body wrapped in a synthesized `200` Response when
555
+ * the server replies `304 Not Modified`.
556
+ * - Persists fresh `200` responses (with their ETag/Last-Modified) into
557
+ * the cache.
558
+ * - Deduplicates concurrent in-flight requests to the same path.
421
559
  */
422
560
  async request(method, path, body) {
423
561
  this._log(method, path);
562
+ if (!this._cache || !isCacheableMethod(method) || body !== void 0) {
563
+ const token = await this.ensureToken();
564
+ const res = await this._doAuthenticatedRequest(method, path, body, token);
565
+ this._log(method, path, "\u2192", res.status);
566
+ return res;
567
+ }
568
+ const key = SdkCache.keyFor(method, path);
569
+ const inFlight = this._inFlight.get(key);
570
+ if (inFlight) {
571
+ return inFlight.then((res) => res.clone());
572
+ }
573
+ const promise = this._cachedRequest(method, path, key);
574
+ this._inFlight.set(key, promise);
575
+ try {
576
+ return await promise;
577
+ } finally {
578
+ this._inFlight.delete(key);
579
+ }
580
+ }
581
+ async _cachedRequest(method, path, key) {
582
+ const cache = this._cache;
583
+ if (!cache) {
584
+ const token2 = await this.ensureToken();
585
+ return this._doAuthenticatedRequest(method, path, void 0, token2);
586
+ }
587
+ const cached = cache.get(key);
588
+ const conditional = {};
589
+ if (cached?.etag) conditional["If-None-Match"] = cached.etag;
590
+ if (cached?.lastModified) conditional["If-Modified-Since"] = cached.lastModified;
424
591
  const token = await this.ensureToken();
425
- const res = await this._doAuthenticatedRequest(method, path, body, token);
592
+ const res = await this._doAuthenticatedRequest(method, path, void 0, token, 0, conditional);
426
593
  this._log(method, path, "\u2192", res.status);
594
+ if (res.status === 304 && cached) {
595
+ const refreshedHeaders = { ...cached.headers, ...snapshotHeaders(res.headers) };
596
+ const refreshedEtag = res.headers.get("etag") ?? cached.etag;
597
+ const refreshedLastModified = res.headers.get("last-modified") ?? cached.lastModified;
598
+ cache.set(key, {
599
+ ...cached,
600
+ etag: refreshedEtag,
601
+ lastModified: refreshedLastModified,
602
+ headers: refreshedHeaders,
603
+ cachedAt: Date.now()
604
+ });
605
+ this.emitCacheEvent("cacheHit", { key, path });
606
+ const body = typeof cached.data === "string" ? cached.data : JSON.stringify(cached.data);
607
+ return new Response(body, { status: 200, headers: refreshedHeaders });
608
+ }
609
+ if (res.status === 200) {
610
+ const etag = res.headers.get("etag") ?? void 0;
611
+ const lastModified = res.headers.get("last-modified") ?? void 0;
612
+ if (etag || lastModified) {
613
+ const text = await res.clone().text();
614
+ let data = text;
615
+ try {
616
+ data = JSON.parse(text);
617
+ } catch {
618
+ }
619
+ cache.set(key, {
620
+ etag,
621
+ lastModified,
622
+ data,
623
+ headers: snapshotHeaders(res.headers),
624
+ cachedAt: Date.now()
625
+ });
626
+ this.emitCacheEvent("cacheMiss", { key, path });
627
+ }
628
+ }
427
629
  return res;
428
630
  }
429
- async _doAuthenticatedRequest(method, path, body, token, retryCount = 0) {
631
+ async _doAuthenticatedRequest(method, path, body, token, retryCount = 0, extraHeaders = {}) {
430
632
  const url = this._baseUrl + path;
431
633
  const isDPoP = this._tokenType === "DPoP" && !!this._dpopKeyPair;
432
634
  const bodyStr = body !== void 0 ? JSON.stringify(body) : void 0;
@@ -442,7 +644,8 @@ var _AuthManager = class _AuthManager {
442
644
  const headers = {
443
645
  Authorization: (reqIsDPoP ? "DPoP " : "Bearer ") + reqToken,
444
646
  "Content-Type": "application/ld+json",
445
- Accept: "application/ld+json"
647
+ Accept: "application/ld+json",
648
+ ...extraHeaders
446
649
  };
447
650
  if (dpopProof) headers["DPoP"] = dpopProof;
448
651
  if (this._tenant) headers["Fiware-Service"] = this._tenant;
@@ -478,7 +681,7 @@ var _AuthManager = class _AuthManager {
478
681
  if (retryNonce) this._dpopNonce = retryNonce;
479
682
  const delay = parseInt(res.headers.get("Retry-After") || "1", 10) * 1e3;
480
683
  await new Promise((resolve) => setTimeout(resolve, delay));
481
- return this._doAuthenticatedRequest(method, path, body, currentToken, retryCount + 1);
684
+ return this._doAuthenticatedRequest(method, path, body, currentToken, retryCount + 1, extraHeaders);
482
685
  }
483
686
  return res;
484
687
  }
@@ -754,14 +957,37 @@ var GeonicDB = class extends EventEmitter {
754
957
  this.onTokenRefresh?.(creds);
755
958
  this.emit("tokenRefresh", creds);
756
959
  };
960
+ if (opts.cache !== false) {
961
+ const cache = new SdkCache(opts.cacheMaxEntries ?? SDK_CACHE_MAX_ENTRIES_DEFAULT);
962
+ this._auth.setCache(cache);
963
+ this._auth.setCacheEventEmitter((name, payload) => this.emit(name, payload));
964
+ }
757
965
  this._ws = new WebSocketManager(
758
966
  this._auth,
759
967
  baseUrl,
760
968
  tenant,
761
- (event, data) => this.emit(event, data),
969
+ (event, data) => {
970
+ this.emit(event, data);
971
+ },
762
972
  opts.wsEndpoint
763
973
  );
764
974
  }
975
+ /**
976
+ * Drop every cached response. Useful in tests and on manual auth changes.
977
+ *
978
+ * Emits a `cacheInvalidated` event for each removed entry so listeners can
979
+ * track explicit flushes (the WebSocket-driven auto-invalidation was removed
980
+ * in #1060 to preserve the ETag/304 revalidation path; `clearCache()` is now
981
+ * the only path that emits this event).
982
+ */
983
+ clearCache() {
984
+ const cache = this._auth.getCache();
985
+ if (!cache) return;
986
+ const removed = cache.deleteWhere(() => true);
987
+ for (const key of removed) {
988
+ this._auth.emitCacheEvent("cacheInvalidated", { key, path: key.split(":").slice(1).join(":") });
989
+ }
990
+ }
765
991
  // --- Authentication ---
766
992
  /** Login with email and password (Bearer JWT). */
767
993
  async login(email, password) {
@@ -804,25 +1030,82 @@ var GeonicDB = class extends EventEmitter {
804
1030
  }
805
1031
  /** Query entities with optional filters. */
806
1032
  async getEntities(params) {
807
- let qs = "";
808
- if (params) {
809
- const parts = [];
810
- if (params.type) parts.push("type=" + encodeURIComponent(params.type));
811
- if (params.limit != null) parts.push("limit=" + params.limit);
812
- if (params.offset != null) parts.push("offset=" + params.offset);
813
- if (params.q) parts.push("q=" + encodeURIComponent(params.q));
814
- if (parts.length) qs = "?" + parts.join("&");
815
- }
816
- const res = await this._auth.request(
817
- "GET",
818
- "/ngsi-ld/v1/entities" + qs
819
- );
1033
+ const res = await this._auth.request("GET", buildEntitiesPath(params));
820
1034
  if (!res.ok) {
821
1035
  const e = await res.json().catch(() => ({}));
822
1036
  throw createErrorFromResponse(res.status, e, "Query failed");
823
1037
  }
824
1038
  return await res.json();
825
1039
  }
1040
+ /**
1041
+ * Poll for entity list changes using ETag-based revalidation (#991 Phase A).
1042
+ *
1043
+ * The handle's `stop()` ends the loop. Each tick performs a normal
1044
+ * `getEntities()` call; the SDK's cache layer issues `If-None-Match`
1045
+ * automatically. The poll detects "no change" by comparing the previous
1046
+ * ETag with the response's ETag (the cache exposes the cached ETag on 304
1047
+ * replays as well, so the comparison stays valid in both 200 and 304
1048
+ * paths).
1049
+ *
1050
+ * @example
1051
+ * ```typescript
1052
+ * const handle = db.poll({ type: 'Room' }, {
1053
+ * interval: 5000,
1054
+ * onData: (rooms) => render(rooms),
1055
+ * onNoChange: () => {},
1056
+ * });
1057
+ * // ...later
1058
+ * handle.stop();
1059
+ * ```
1060
+ */
1061
+ poll(params, options) {
1062
+ const interval = options.interval ?? SDK_POLL_INTERVAL_MS_DEFAULT;
1063
+ if (!Number.isFinite(interval) || interval <= 0) {
1064
+ throw new Error(`poll interval must be a positive number (got ${String(interval)})`);
1065
+ }
1066
+ let stopped = false;
1067
+ let timer = null;
1068
+ let prevEtag;
1069
+ let prevPath;
1070
+ const buildPath = () => buildEntitiesPath(params);
1071
+ const tick = async () => {
1072
+ if (stopped) return;
1073
+ try {
1074
+ const path = prevPath ?? (prevPath = buildPath());
1075
+ const res = await this._auth.request("GET", path);
1076
+ if (stopped) return;
1077
+ const etag = res.headers.get("etag") ?? void 0;
1078
+ if (prevEtag !== void 0 && etag !== void 0 && prevEtag === etag) {
1079
+ options.onNoChange?.();
1080
+ } else {
1081
+ if (!res.ok) {
1082
+ throw createErrorFromResponse(res.status, {}, "Poll request failed");
1083
+ }
1084
+ const data = await res.json();
1085
+ prevEtag = etag;
1086
+ options.onData?.(data);
1087
+ }
1088
+ } catch (err) {
1089
+ options.onError?.(err);
1090
+ } finally {
1091
+ if (!stopped) {
1092
+ timer = setTimeout(() => {
1093
+ void tick();
1094
+ }, interval);
1095
+ }
1096
+ }
1097
+ };
1098
+ void tick();
1099
+ return {
1100
+ stop() {
1101
+ stopped = true;
1102
+ if (timer !== null) {
1103
+ clearTimeout(timer);
1104
+ timer = null;
1105
+ }
1106
+ }
1107
+ };
1108
+ }
826
1109
  /** Count entities matching the given filters. */
827
1110
  async count(params) {
828
1111
  const parts = ["count=true", "limit=0"];
@@ -1021,6 +1304,15 @@ var index_default = GeonicDB;
1021
1304
  if (typeof window !== "undefined") {
1022
1305
  window.GeonicDB = GeonicDB;
1023
1306
  }
1307
+ function buildEntitiesPath(params) {
1308
+ if (!params) return "/ngsi-ld/v1/entities";
1309
+ const parts = [];
1310
+ if (params.type) parts.push("type=" + encodeURIComponent(params.type));
1311
+ if (params.limit != null) parts.push("limit=" + params.limit);
1312
+ if (params.offset != null) parts.push("offset=" + params.offset);
1313
+ if (params.q) parts.push("q=" + encodeURIComponent(params.q));
1314
+ return parts.length > 0 ? "/ngsi-ld/v1/entities?" + parts.join("&") : "/ngsi-ld/v1/entities";
1315
+ }
1024
1316
  export {
1025
1317
  AuthenticationError,
1026
1318
  AuthorizationError,