@geolonia/geonicdb-sdk 0.27.1 → 0.28.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
@@ -52,12 +52,93 @@ var SDK_POLL_INTERVAL_MS_DEFAULT = 5e3;
52
52
  var DPOP_IDB_NAME = "geonicdb-sdk";
53
53
  var DPOP_IDB_STORE = "dpop-sessions";
54
54
  var DPOP_IDB_VERSION = 1;
55
+ var SDK_IDB_OPERATION_TIMEOUT_MS = 3e3;
55
56
  var SDK_CACHE_IDB_NAME = "geonicdb-sdk-cache";
56
57
  var SDK_CACHE_IDB_STORE = "responses";
57
58
  var SDK_CACHE_IDB_VERSION = 1;
58
59
  var WEBPUSH_VAPID_KEY_PATH = "/.well-known/webpush-vapid-key";
59
60
  var WEBPUSH_SUBSCRIPTION_ID_STORAGE_PREFIX = "geonicdb:webpush:subscriptionId";
60
61
 
62
+ // src/sdk/idb-timeout.ts
63
+ var IdbTimeoutError = class extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = "IdbTimeoutError";
67
+ }
68
+ };
69
+ function withIdbTimeout(promise, options) {
70
+ return new Promise((resolve, reject) => {
71
+ let settled = false;
72
+ const timer = setTimeout(() => {
73
+ if (settled) return;
74
+ settled = true;
75
+ try {
76
+ options.onTimeout?.();
77
+ } catch {
78
+ }
79
+ reject(new IdbTimeoutError(`IndexedDB ${options.operation} timed out`));
80
+ }, options.timeoutMs);
81
+ promise.then(
82
+ (value) => {
83
+ if (settled) return;
84
+ settled = true;
85
+ clearTimeout(timer);
86
+ resolve(value);
87
+ },
88
+ (err) => {
89
+ if (settled) return;
90
+ settled = true;
91
+ clearTimeout(timer);
92
+ reject(err instanceof Error ? err : new Error(String(err)));
93
+ }
94
+ );
95
+ });
96
+ }
97
+ function openIndexedDbWithTimeout(options) {
98
+ return new Promise((resolve, reject) => {
99
+ let settled = false;
100
+ const timer = setTimeout(() => {
101
+ if (settled) return;
102
+ settled = true;
103
+ reject(new IdbTimeoutError("IndexedDB open timed out"));
104
+ }, options.timeoutMs);
105
+ let req;
106
+ try {
107
+ req = globalThis.indexedDB.open(options.name, options.version);
108
+ } catch (err) {
109
+ if (settled) return;
110
+ settled = true;
111
+ clearTimeout(timer);
112
+ reject(err instanceof Error ? err : new Error(String(err)));
113
+ return;
114
+ }
115
+ req.onupgradeneeded = () => {
116
+ options.onUpgradeNeeded?.(req);
117
+ };
118
+ req.onsuccess = () => {
119
+ if (settled) {
120
+ req.result?.close?.();
121
+ return;
122
+ }
123
+ settled = true;
124
+ clearTimeout(timer);
125
+ resolve(req.result);
126
+ };
127
+ req.onerror = () => {
128
+ if (settled) return;
129
+ settled = true;
130
+ clearTimeout(timer);
131
+ reject(req.error ?? new Error("IndexedDB open failed"));
132
+ };
133
+ req.onblocked = () => {
134
+ if (settled) return;
135
+ settled = true;
136
+ clearTimeout(timer);
137
+ reject(req.error ?? new Error("IndexedDB open blocked"));
138
+ };
139
+ });
140
+ }
141
+
61
142
  // src/sdk/dpop.ts
62
143
  var dpopSupported = typeof crypto !== "undefined" && !!crypto.subtle && !!crypto.subtle.generateKey;
63
144
  var dpopPersistenceSupported = typeof globalThis.indexedDB !== "undefined" && typeof structuredClone !== "undefined";
@@ -118,40 +199,52 @@ async function createDPoPProof(keyPair, htm, htu, accessToken, nonce) {
118
199
  return signingInput + "." + b64url(new Uint8Array(sigBuf));
119
200
  }
120
201
  function openSessionDB() {
121
- return new Promise((resolve, reject) => {
122
- const req = globalThis.indexedDB.open(DPOP_IDB_NAME, DPOP_IDB_VERSION);
123
- req.onupgradeneeded = () => {
202
+ return openIndexedDbWithTimeout({
203
+ name: DPOP_IDB_NAME,
204
+ version: DPOP_IDB_VERSION,
205
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
206
+ onUpgradeNeeded: (req) => {
124
207
  const db = req.result;
125
208
  if (!db.objectStoreNames.contains(DPOP_IDB_STORE)) {
126
209
  db.createObjectStore(DPOP_IDB_STORE);
127
210
  }
128
- };
129
- req.onsuccess = () => {
130
- resolve(req.result);
131
- };
132
- req.onerror = () => {
133
- reject(req.error ?? new Error("IndexedDB open failed"));
134
- };
211
+ }
135
212
  });
136
213
  }
137
- async function saveDPoPSession(session) {
214
+ async function saveDPoPSession(session, checkValid) {
138
215
  if (!dpopPersistenceSupported) return false;
139
216
  let db = null;
140
217
  try {
141
218
  db = await openSessionDB();
142
- await new Promise((resolve, reject) => {
143
- const tx = db.transaction(DPOP_IDB_STORE, "readwrite");
144
- tx.objectStore(DPOP_IDB_STORE).put(session, session.tenant);
145
- tx.oncomplete = () => {
146
- resolve();
147
- };
148
- tx.onerror = () => {
149
- reject(tx.error ?? new Error("IndexedDB put failed"));
150
- };
151
- tx.onabort = () => {
152
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
153
- };
154
- });
219
+ if (checkValid && !checkValid()) {
220
+ return false;
221
+ }
222
+ let tx = null;
223
+ await withIdbTimeout(
224
+ new Promise((resolve, reject) => {
225
+ tx = db.transaction(DPOP_IDB_STORE, "readwrite");
226
+ tx.objectStore(DPOP_IDB_STORE).put(session, session.tenant);
227
+ tx.oncomplete = () => {
228
+ resolve();
229
+ };
230
+ tx.onerror = () => {
231
+ reject(tx.error ?? new Error("IndexedDB put failed"));
232
+ };
233
+ tx.onabort = () => {
234
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
235
+ };
236
+ }),
237
+ {
238
+ operation: "put",
239
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
240
+ onTimeout: () => {
241
+ try {
242
+ tx?.abort?.();
243
+ } catch {
244
+ }
245
+ }
246
+ }
247
+ );
155
248
  return true;
156
249
  } catch {
157
250
  return false;
@@ -164,16 +257,29 @@ async function loadDPoPSession(tenant) {
164
257
  let db = null;
165
258
  try {
166
259
  db = await openSessionDB();
167
- const data = await new Promise((resolve, reject) => {
168
- const tx = db.transaction(DPOP_IDB_STORE, "readonly");
169
- const req = tx.objectStore(DPOP_IDB_STORE).get(tenant);
170
- req.onsuccess = () => {
171
- resolve(req.result);
172
- };
173
- req.onerror = () => {
174
- reject(req.error ?? new Error("IndexedDB get failed"));
175
- };
176
- });
260
+ let tx = null;
261
+ const data = await withIdbTimeout(
262
+ new Promise((resolve, reject) => {
263
+ tx = db.transaction(DPOP_IDB_STORE, "readonly");
264
+ const req = tx.objectStore(DPOP_IDB_STORE).get(tenant);
265
+ req.onsuccess = () => {
266
+ resolve(req.result);
267
+ };
268
+ req.onerror = () => {
269
+ reject(req.error ?? new Error("IndexedDB get failed"));
270
+ };
271
+ }),
272
+ {
273
+ operation: "get",
274
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
275
+ onTimeout: () => {
276
+ try {
277
+ tx?.abort?.();
278
+ } catch {
279
+ }
280
+ }
281
+ }
282
+ );
177
283
  return validatePersistedSession(data);
178
284
  } catch {
179
285
  return null;
@@ -186,19 +292,81 @@ async function clearDPoPSession(tenant) {
186
292
  let db = null;
187
293
  try {
188
294
  db = await openSessionDB();
189
- await new Promise((resolve, reject) => {
190
- const tx = db.transaction(DPOP_IDB_STORE, "readwrite");
191
- tx.objectStore(DPOP_IDB_STORE).delete(tenant);
192
- tx.oncomplete = () => {
193
- resolve();
194
- };
195
- tx.onerror = () => {
196
- reject(tx.error ?? new Error("IndexedDB delete failed"));
197
- };
198
- tx.onabort = () => {
199
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
200
- };
201
- });
295
+ let tx = null;
296
+ await withIdbTimeout(
297
+ new Promise((resolve, reject) => {
298
+ tx = db.transaction(DPOP_IDB_STORE, "readwrite");
299
+ tx.objectStore(DPOP_IDB_STORE).delete(tenant);
300
+ tx.oncomplete = () => {
301
+ resolve();
302
+ };
303
+ tx.onerror = () => {
304
+ reject(tx.error ?? new Error("IndexedDB delete failed"));
305
+ };
306
+ tx.onabort = () => {
307
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
308
+ };
309
+ }),
310
+ {
311
+ operation: "delete",
312
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
313
+ onTimeout: () => {
314
+ try {
315
+ tx?.abort?.();
316
+ } catch {
317
+ }
318
+ }
319
+ }
320
+ );
321
+ } catch {
322
+ } finally {
323
+ db?.close();
324
+ }
325
+ }
326
+ async function clearDPoPSessionUpToRevision(tenant, maxPersistRevision) {
327
+ if (!dpopPersistenceSupported) return;
328
+ let db = null;
329
+ try {
330
+ db = await openSessionDB();
331
+ let tx = null;
332
+ await withIdbTimeout(
333
+ new Promise((resolve, reject) => {
334
+ tx = db.transaction(DPOP_IDB_STORE, "readwrite");
335
+ const store = tx.objectStore(DPOP_IDB_STORE);
336
+ const req = store.get(tenant);
337
+ req.onsuccess = () => {
338
+ const current = validatePersistedSession(req.result);
339
+ const revision = current?.persistRevision;
340
+ const isLegacy = typeof revision !== "number";
341
+ const isOlderOrEqual = typeof revision === "number" && revision <= maxPersistRevision;
342
+ if (!current || isLegacy || isOlderOrEqual) {
343
+ store.delete(tenant);
344
+ }
345
+ };
346
+ req.onerror = () => {
347
+ reject(req.error ?? new Error("IndexedDB get failed"));
348
+ };
349
+ tx.oncomplete = () => {
350
+ resolve();
351
+ };
352
+ tx.onerror = () => {
353
+ reject(tx.error ?? new Error("IndexedDB delete failed"));
354
+ };
355
+ tx.onabort = () => {
356
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
357
+ };
358
+ }),
359
+ {
360
+ operation: "conditional delete",
361
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
362
+ onTimeout: () => {
363
+ try {
364
+ tx?.abort?.();
365
+ } catch {
366
+ }
367
+ }
368
+ }
369
+ );
202
370
  } catch {
203
371
  } finally {
204
372
  db?.close();
@@ -208,7 +376,7 @@ function validatePersistedSession(data) {
208
376
  if (!data || typeof data !== "object") return null;
209
377
  const s = data;
210
378
  const kp = s.keyPair;
211
- if (typeof s.tenant !== "string" || typeof s.accessToken !== "string" || typeof s.refreshToken !== "string" || typeof s.expiresAt !== "number" || !kp || !kp.privateKey || !kp.publicJwk) {
379
+ if (typeof s.tenant !== "string" || typeof s.accessToken !== "string" || typeof s.refreshToken !== "string" || typeof s.expiresAt !== "number" || s.persistRevision !== void 0 && typeof s.persistRevision !== "number" || !kp || !kp.privateKey || !kp.publicJwk) {
212
380
  return null;
213
381
  }
214
382
  return data;
@@ -423,11 +591,15 @@ var SdkCache = class {
423
591
  * best-effort) and does not stall the chain. Returns the tail so callers that
424
592
  * need ordering (`clearPersisted`) can await it.
425
593
  */
426
- _enqueuePersist(op) {
594
+ _enqueuePersist(op, options) {
427
595
  const persistence = this._persistence;
428
596
  if (!persistence) return this._persistQueue;
429
597
  const scope = this._scope;
430
- this._persistQueue = this._persistQueue.catch(() => void 0).then(() => op(persistence, scope)).catch(() => void 0);
598
+ const next = this._persistQueue.catch(() => void 0).then(() => op(persistence, scope));
599
+ this._persistQueue = next.catch(() => void 0);
600
+ if (options?.propagateError) {
601
+ return next;
602
+ }
431
603
  return this._persistQueue;
432
604
  }
433
605
  /**
@@ -449,10 +621,21 @@ var SdkCache = class {
449
621
  this._store.delete(oldest);
450
622
  }
451
623
  }
452
- /** Drop every persisted entry for the current scope (auth change / flush). */
624
+ /**
625
+ * Drop every persisted entry for the current scope (auth change / flush).
626
+ * Returns false when the persistence backend failed to clear.
627
+ */
453
628
  async clearPersisted() {
454
- if (!this._persistence) return;
455
- await this._enqueuePersist((persistence, scope) => persistence.clearScope(scope));
629
+ if (!this._persistence) return true;
630
+ try {
631
+ await this._enqueuePersist(
632
+ (persistence, scope) => persistence.clearScope(scope),
633
+ { propagateError: true }
634
+ );
635
+ return true;
636
+ } catch {
637
+ return false;
638
+ }
456
639
  }
457
640
  /** Build a stable cache key. Method is upper-cased so casing differences do not produce duplicate entries. */
458
641
  static keyFor(method, path) {
@@ -654,6 +837,8 @@ var _AuthManager = class _AuthManager {
654
837
  __publicField(this, "_dpopKeyPair", null);
655
838
  __publicField(this, "_dpopReady", null);
656
839
  __publicField(this, "_dpopNonce", null);
840
+ /** Monotonic sequence used to guard delayed persisted-session cleanup. */
841
+ __publicField(this, "_persistRevision", 0);
657
842
  /**
658
843
  * When true, every DPoP token mutation (login bind, refresh) is mirrored to
659
844
  * IndexedDB so the session survives a page reload (#1230). Toggled by
@@ -753,8 +938,19 @@ var _AuthManager = class _AuthManager {
753
938
  */
754
939
  async _enablePersistentCache(clearFirst) {
755
940
  if (!this._cache) return;
941
+ const generation = this._credentialGeneration;
756
942
  this._cache.setScope(this._cacheScope());
757
- if (clearFirst) await this._cache.clearPersisted();
943
+ if (clearFirst) {
944
+ const cleared = await this._cache.clearPersisted();
945
+ if (generation !== this._credentialGeneration || !this._rememberSession) {
946
+ return;
947
+ }
948
+ if (!cleared) {
949
+ this._cache.setPersistEnabled(false);
950
+ this._log("Persistent cache clear failed; keeping persistence disabled for this session");
951
+ return;
952
+ }
953
+ }
758
954
  this._cache.setPersistEnabled(true);
759
955
  }
760
956
  /**
@@ -857,6 +1053,7 @@ var _AuthManager = class _AuthManager {
857
1053
  this._assertCredentialGeneration(generation, "login");
858
1054
  if (this._rememberSession) {
859
1055
  await this._persistDpopSession();
1056
+ this._assertCredentialGeneration(generation, "login");
860
1057
  await this._enablePersistentCache(true);
861
1058
  } else {
862
1059
  this._disablePersistentCache();
@@ -1040,6 +1237,7 @@ var _AuthManager = class _AuthManager {
1040
1237
  this._dpopNonce = null;
1041
1238
  this._rememberSession = true;
1042
1239
  this._email = persisted.email ?? null;
1240
+ this._persistRevision = Math.max(this._persistRevision, persisted.persistRevision ?? 0);
1043
1241
  this._tokenPromise = null;
1044
1242
  this._invalidateAuthScopedState();
1045
1243
  await this._enablePersistentCache(false);
@@ -1065,15 +1263,35 @@ var _AuthManager = class _AuthManager {
1065
1263
  if (!this._rememberSession || !this._tenant || !this._dpopKeyPair || !this._token || !this._refreshToken) {
1066
1264
  return;
1067
1265
  }
1068
- const ok = await saveDPoPSession({
1266
+ const generation = this._credentialGeneration;
1267
+ if (this._persistRevision === 0) {
1268
+ const existing = await loadDPoPSession(this._tenant);
1269
+ if (generation !== this._credentialGeneration || !this._rememberSession) {
1270
+ return;
1271
+ }
1272
+ this._persistRevision = Math.max(0, existing?.persistRevision ?? 0);
1273
+ }
1274
+ const expectedPersistedSession = {
1069
1275
  tenant: this._tenant,
1070
1276
  accessToken: this._token,
1071
1277
  refreshToken: this._refreshToken,
1072
1278
  expiresAt: this._tokenExpiry,
1073
- email: this._email ?? void 0,
1279
+ email: this._email ?? void 0
1280
+ };
1281
+ const persistRevision = ++this._persistRevision;
1282
+ const ok = await saveDPoPSession({
1283
+ tenant: expectedPersistedSession.tenant,
1284
+ accessToken: expectedPersistedSession.accessToken,
1285
+ refreshToken: expectedPersistedSession.refreshToken,
1286
+ expiresAt: expectedPersistedSession.expiresAt,
1287
+ email: expectedPersistedSession.email,
1288
+ persistRevision,
1074
1289
  keyPair: this._dpopKeyPair
1075
- });
1076
- if (!ok) this._log("DPoP session persistence failed (IndexedDB unavailable?)");
1290
+ }, () => generation === this._credentialGeneration && this._rememberSession);
1291
+ if (!ok) {
1292
+ void clearDPoPSessionUpToRevision(expectedPersistedSession.tenant, persistRevision);
1293
+ this._log("DPoP session persistence failed (IndexedDB unavailable?)");
1294
+ }
1077
1295
  }
1078
1296
  /**
1079
1297
  * Drop everything that may have been associated with the previous auth
@@ -1724,126 +1942,194 @@ var cachePersistenceSupported = typeof globalThis.indexedDB !== "undefined" && t
1724
1942
  var SCOPE_SEP = "\0";
1725
1943
  var SCOPE_RANGE_END = "\uFFFF";
1726
1944
  function openCacheDB() {
1727
- return new Promise((resolve, reject) => {
1728
- const req = globalThis.indexedDB.open(
1729
- SDK_CACHE_IDB_NAME,
1730
- SDK_CACHE_IDB_VERSION
1731
- );
1732
- req.onupgradeneeded = () => {
1945
+ return openIndexedDbWithTimeout({
1946
+ name: SDK_CACHE_IDB_NAME,
1947
+ version: SDK_CACHE_IDB_VERSION,
1948
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
1949
+ onUpgradeNeeded: (req) => {
1733
1950
  const db = req.result;
1734
1951
  if (!db.objectStoreNames.contains(SDK_CACHE_IDB_STORE)) {
1735
1952
  db.createObjectStore(SDK_CACHE_IDB_STORE, { keyPath: "id" });
1736
1953
  }
1737
- };
1738
- req.onsuccess = () => {
1739
- resolve(req.result);
1740
- };
1741
- req.onerror = () => {
1742
- reject(req.error ?? new Error("IndexedDB open failed"));
1743
- };
1744
- req.onblocked = () => {
1745
- reject(req.error ?? new Error("IndexedDB open blocked"));
1746
- };
1954
+ }
1747
1955
  });
1748
1956
  }
1749
1957
  function recordId(scope, key) {
1750
1958
  return scope + SCOPE_SEP + key;
1751
1959
  }
1752
1960
  var IdbCachePersistence = class {
1961
+ constructor() {
1962
+ /**
1963
+ * Circuit breaker for repeated IDB timeout failures (#3898). Once a timeout
1964
+ * is observed, subsequent operations fail fast instead of spending another
1965
+ * timeout window per queued op.
1966
+ */
1967
+ __publicField(this, "_timeoutCircuitOpen", false);
1968
+ }
1969
+ _tripTimeoutCircuit(error) {
1970
+ if (error instanceof IdbTimeoutError) {
1971
+ this._timeoutCircuitOpen = true;
1972
+ }
1973
+ }
1974
+ _assertCircuitClosed() {
1975
+ if (!this._timeoutCircuitOpen) return;
1976
+ throw new Error("IndexedDB persistence circuit is open");
1977
+ }
1753
1978
  async loadScope(scope, limit) {
1979
+ if (this._timeoutCircuitOpen) return [];
1754
1980
  let db = null;
1755
1981
  try {
1756
1982
  db = await openCacheDB();
1757
- const records = await new Promise((resolve, reject) => {
1758
- const tx = db.transaction(SDK_CACHE_IDB_STORE, "readonly");
1759
- const range = globalThis.IDBKeyRange.bound(
1760
- scope + SCOPE_SEP,
1761
- scope + SCOPE_SEP + SCOPE_RANGE_END
1762
- );
1763
- const req = tx.objectStore(SDK_CACHE_IDB_STORE).getAll(range);
1764
- req.onsuccess = () => {
1765
- resolve(req.result ?? []);
1766
- };
1767
- req.onerror = () => {
1768
- reject(req.error ?? new Error("IndexedDB getAll failed"));
1769
- };
1770
- });
1983
+ let tx = null;
1984
+ const records = await withIdbTimeout(
1985
+ new Promise((resolve, reject) => {
1986
+ tx = db.transaction(SDK_CACHE_IDB_STORE, "readonly");
1987
+ const range = globalThis.IDBKeyRange.bound(
1988
+ scope + SCOPE_SEP,
1989
+ scope + SCOPE_SEP + SCOPE_RANGE_END
1990
+ );
1991
+ const req = tx.objectStore(SDK_CACHE_IDB_STORE).getAll(range);
1992
+ req.onsuccess = () => {
1993
+ resolve(req.result ?? []);
1994
+ };
1995
+ req.onerror = () => {
1996
+ reject(req.error ?? new Error("IndexedDB getAll failed"));
1997
+ };
1998
+ }),
1999
+ {
2000
+ operation: "getAll",
2001
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
2002
+ onTimeout: () => {
2003
+ try {
2004
+ tx?.abort?.();
2005
+ } catch {
2006
+ }
2007
+ }
2008
+ }
2009
+ );
1771
2010
  return records.filter((r) => r && r.scope === scope && typeof r.key === "string" && r.entry).sort((a, b) => (a.entry.cachedAt ?? 0) - (b.entry.cachedAt ?? 0)).slice(-limit).map((r) => ({ key: r.key, entry: r.entry }));
1772
- } catch {
2011
+ } catch (err) {
2012
+ this._tripTimeoutCircuit(err);
1773
2013
  return [];
1774
2014
  } finally {
1775
2015
  db?.close();
1776
2016
  }
1777
2017
  }
1778
2018
  async put(scope, key, entry) {
2019
+ if (this._timeoutCircuitOpen) return;
1779
2020
  let db = null;
1780
2021
  try {
1781
2022
  db = await openCacheDB();
1782
- await new Promise((resolve, reject) => {
1783
- const tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
1784
- const record = { id: recordId(scope, key), scope, key, entry };
1785
- tx.objectStore(SDK_CACHE_IDB_STORE).put(record);
1786
- tx.oncomplete = () => {
1787
- resolve();
1788
- };
1789
- tx.onerror = () => {
1790
- reject(tx.error ?? new Error("IndexedDB put failed"));
1791
- };
1792
- tx.onabort = () => {
1793
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
1794
- };
1795
- });
1796
- } catch {
2023
+ let tx = null;
2024
+ await withIdbTimeout(
2025
+ new Promise((resolve, reject) => {
2026
+ tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
2027
+ const record = { id: recordId(scope, key), scope, key, entry };
2028
+ tx.objectStore(SDK_CACHE_IDB_STORE).put(record);
2029
+ tx.oncomplete = () => {
2030
+ resolve();
2031
+ };
2032
+ tx.onerror = () => {
2033
+ reject(tx.error ?? new Error("IndexedDB put failed"));
2034
+ };
2035
+ tx.onabort = () => {
2036
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
2037
+ };
2038
+ }),
2039
+ {
2040
+ operation: "put",
2041
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
2042
+ onTimeout: () => {
2043
+ try {
2044
+ tx?.abort?.();
2045
+ } catch {
2046
+ }
2047
+ }
2048
+ }
2049
+ );
2050
+ } catch (err) {
2051
+ this._tripTimeoutCircuit(err);
1797
2052
  } finally {
1798
2053
  db?.close();
1799
2054
  }
1800
2055
  }
1801
2056
  async remove(scope, keys) {
1802
2057
  if (keys.length === 0) return;
2058
+ if (this._timeoutCircuitOpen) return;
1803
2059
  let db = null;
1804
2060
  try {
1805
2061
  db = await openCacheDB();
1806
- await new Promise((resolve, reject) => {
1807
- const tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
1808
- const store = tx.objectStore(SDK_CACHE_IDB_STORE);
1809
- for (const key of keys) store.delete(recordId(scope, key));
1810
- tx.oncomplete = () => {
1811
- resolve();
1812
- };
1813
- tx.onerror = () => {
1814
- reject(tx.error ?? new Error("IndexedDB delete failed"));
1815
- };
1816
- tx.onabort = () => {
1817
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
1818
- };
1819
- });
1820
- } catch {
2062
+ let tx = null;
2063
+ await withIdbTimeout(
2064
+ new Promise((resolve, reject) => {
2065
+ tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
2066
+ const store = tx.objectStore(SDK_CACHE_IDB_STORE);
2067
+ for (const key of keys) store.delete(recordId(scope, key));
2068
+ tx.oncomplete = () => {
2069
+ resolve();
2070
+ };
2071
+ tx.onerror = () => {
2072
+ reject(tx.error ?? new Error("IndexedDB delete failed"));
2073
+ };
2074
+ tx.onabort = () => {
2075
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
2076
+ };
2077
+ }),
2078
+ {
2079
+ operation: "delete",
2080
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
2081
+ onTimeout: () => {
2082
+ try {
2083
+ tx?.abort?.();
2084
+ } catch {
2085
+ }
2086
+ }
2087
+ }
2088
+ );
2089
+ } catch (err) {
2090
+ this._tripTimeoutCircuit(err);
1821
2091
  } finally {
1822
2092
  db?.close();
1823
2093
  }
1824
2094
  }
1825
2095
  async clearScope(scope) {
2096
+ this._assertCircuitClosed();
1826
2097
  let db = null;
1827
2098
  try {
1828
2099
  db = await openCacheDB();
1829
- await new Promise((resolve, reject) => {
1830
- const tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
1831
- const range = globalThis.IDBKeyRange.bound(
1832
- scope + SCOPE_SEP,
1833
- scope + SCOPE_SEP + SCOPE_RANGE_END
1834
- );
1835
- tx.objectStore(SDK_CACHE_IDB_STORE).delete(range);
1836
- tx.oncomplete = () => {
1837
- resolve();
1838
- };
1839
- tx.onerror = () => {
1840
- reject(tx.error ?? new Error("IndexedDB clear failed"));
1841
- };
1842
- tx.onabort = () => {
1843
- reject(tx.error ?? new Error("IndexedDB transaction aborted"));
1844
- };
1845
- });
1846
- } catch {
2100
+ let tx = null;
2101
+ await withIdbTimeout(
2102
+ new Promise((resolve, reject) => {
2103
+ tx = db.transaction(SDK_CACHE_IDB_STORE, "readwrite");
2104
+ const range = globalThis.IDBKeyRange.bound(
2105
+ scope + SCOPE_SEP,
2106
+ scope + SCOPE_SEP + SCOPE_RANGE_END
2107
+ );
2108
+ tx.objectStore(SDK_CACHE_IDB_STORE).delete(range);
2109
+ tx.oncomplete = () => {
2110
+ resolve();
2111
+ };
2112
+ tx.onerror = () => {
2113
+ reject(tx.error ?? new Error("IndexedDB clear failed"));
2114
+ };
2115
+ tx.onabort = () => {
2116
+ reject(tx.error ?? new Error("IndexedDB transaction aborted"));
2117
+ };
2118
+ }),
2119
+ {
2120
+ operation: "clear",
2121
+ timeoutMs: SDK_IDB_OPERATION_TIMEOUT_MS,
2122
+ onTimeout: () => {
2123
+ try {
2124
+ tx?.abort?.();
2125
+ } catch {
2126
+ }
2127
+ }
2128
+ }
2129
+ );
2130
+ } catch (err) {
2131
+ this._tripTimeoutCircuit(err);
2132
+ throw err instanceof Error ? err : new Error(String(err));
1847
2133
  } finally {
1848
2134
  db?.close();
1849
2135
  }