keyv 6.0.0-beta.4 → 6.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/dist/index.cjs CHANGED
@@ -65,6 +65,26 @@ function buildMethods(obj, names) {
65
65
  for (const name of names) methods[name] = obj ? resolveMethod(obj, name) : { ...noneMethod };
66
66
  return methods;
67
67
  }
68
+ /** The methods a full storage adapter implements. */
69
+ const keyvStorageRequiredMethods = [
70
+ "get",
71
+ "has",
72
+ "hasMany",
73
+ "set",
74
+ "setMany",
75
+ "delete",
76
+ "deleteMany",
77
+ "clear"
78
+ ];
79
+ /**
80
+ * Whether a detected store has every method of a full storage adapter, whether or not they are
81
+ * native `async` functions.
82
+ * @param capability - The result of {@link detectKeyvStorage}
83
+ * @returns `true` when all of the full storage adapter's methods exist
84
+ */
85
+ function hasKeyvStorageMethods(capability) {
86
+ return keyvStorageRequiredMethods.every((m) => capability.methods[m].exists);
87
+ }
68
88
  /**
69
89
  * Detect whether an object implements the full Keyv interface
70
90
  * @param obj - The object to check
@@ -136,16 +156,7 @@ function detectKeyvStorage(obj) {
136
156
  methods: buildMethods(null, keyvStorageMethodNames)
137
157
  };
138
158
  const methods = buildMethods(obj, keyvStorageMethodNames);
139
- if ([
140
- "get",
141
- "has",
142
- "hasMany",
143
- "set",
144
- "setMany",
145
- "delete",
146
- "deleteMany",
147
- "clear"
148
- ].every((k) => methods[k].exists && methods[k].methodType === "async")) return {
159
+ if (keyvStorageRequiredMethods.every((k) => methods[k].exists && methods[k].methodType === "async")) return {
149
160
  compatible: true,
150
161
  store: "keyvStorage",
151
162
  methods
@@ -373,7 +384,7 @@ function isDataExpired(data) {
373
384
  return typeof data.expires === "number" && Date.now() > data.expires;
374
385
  }
375
386
  /**
376
- * Calculate an absolute expiry timestamp from a TTL value.
387
+ * Calculate an absolute expiry timestamp from a TTL value, in whole milliseconds.
377
388
  * Returns `undefined` when `ttl` is absent, zero, negative, or non-finite
378
389
  * (meaning "no expiry").
379
390
  *
@@ -382,7 +393,19 @@ function isDataExpired(data) {
382
393
  */
383
394
  function calculateExpires(ttl) {
384
395
  if (typeof ttl !== "number" || ttl <= 0 || !Number.isFinite(ttl)) return;
385
- return Date.now() + ttl;
396
+ return toStoreExpires(Date.now() + ttl);
397
+ }
398
+ /**
399
+ * Convert an absolute expiry into the form stores accept: whole milliseconds, rounded up so an
400
+ * entry never expires early, or `undefined` (no expiry) when it is not a finite number. Stores
401
+ * such as PostgreSQL's `BIGINT` column and Redis's `PXAT` reject a fractional timestamp.
402
+ *
403
+ * @param expires - Absolute expiry timestamp (ms since epoch), or `undefined`
404
+ * @returns The expiry in whole milliseconds, or `undefined` for no expiry
405
+ */
406
+ function toStoreExpires(expires) {
407
+ if (typeof expires !== "number" || !Number.isFinite(expires)) return;
408
+ return Math.ceil(expires);
386
409
  }
387
410
  /**
388
411
  * Resolve a TTL value by falling back to a default when none is given,
@@ -411,6 +434,23 @@ function ttlFromExpires(expires) {
411
434
  return remaining > 0 ? remaining : void 0;
412
435
  }
413
436
  /**
437
+ * Calls a store's `has` once to see whether it returns a promise. A method that is not a native
438
+ * `async` function can still return one, such as an `async` method compiled to an older target.
439
+ * @param store - The store to check
440
+ * @returns `true` when `has` returned a promise
441
+ */
442
+ function returnsPromise(store) {
443
+ let result;
444
+ try {
445
+ result = store.has("keyv-probe");
446
+ } catch {
447
+ return false;
448
+ }
449
+ if (typeof result?.then !== "function") return false;
450
+ Promise.resolve(result).catch(() => {});
451
+ return true;
452
+ }
453
+ /**
414
454
  * Scan parallel `keys` and `data` arrays, nullify any expired entries in
415
455
  * `data`, and batch-delete the corresponding keys via `keyv.deleteMany()`.
416
456
  */
@@ -425,7 +465,7 @@ async function deleteExpiredKeys(keys, data, keyv) {
425
465
  /**
426
466
  * Maps new hook names to their deprecated equivalents so both fire during migration.
427
467
  */
428
- const deprecatedHookAliases = new Map([
468
+ const deprecatedHookAliases = /* @__PURE__ */ new Map([
429
469
  ["before:set", "preSet"],
430
470
  ["after:set", "postSet"],
431
471
  ["before:get", "preGet"],
@@ -451,7 +491,7 @@ const deprecatedHookAliases = new Map([
451
491
  * Build the deprecated-hooks map used by Hookified to warn when old PRE_/POST_ hook names are registered.
452
492
  */
453
493
  function buildDeprecatedHooks() {
454
- return new Map([
494
+ return /* @__PURE__ */ new Map([
455
495
  ["preSet", "Use KeyvHooks.BEFORE_SET ('before:set') instead"],
456
496
  ["postSet", "Use KeyvHooks.AFTER_SET ('after:set') instead"],
457
497
  ["preGet", "Use KeyvHooks.BEFORE_GET ('before:get') instead"],
@@ -496,7 +536,7 @@ function buildDeprecatedHooks() {
496
536
  var KeyvBridgeAdapter = class extends hookified.Hookified {
497
537
  _store;
498
538
  _namespace;
499
- _keySeparator = ":";
539
+ _namespaceSeparator = "::";
500
540
  _capabilities;
501
541
  /**
502
542
  * Whether the wrapped store manages its own namespace (exposes a `namespace` property).
@@ -513,10 +553,11 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
513
553
  super({ throwOnHookError: false });
514
554
  this._store = store;
515
555
  this._capabilities = detectKeyvStorage(store);
516
- this._storeHandlesNamespace = this._capabilities.store === "keyvStorage" && "namespace" in store;
517
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
556
+ this._storeHandlesNamespace = hasKeyvStorageMethods(this._capabilities) && "namespace" in store;
557
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
518
558
  if (options?.namespace) this._namespace = options.namespace;
519
- if (this._storeHandlesNamespace) this._store.namespace = this._namespace;
559
+ if (this._storeHandlesNamespace) if (options?.namespace === void 0) this._namespace = this._store.namespace;
560
+ else this._store.namespace = this._namespace;
520
561
  if (typeof store.on === "function") store.on("error", (error) => this.emit("error", error));
521
562
  }
522
563
  /**
@@ -543,16 +584,16 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
543
584
  };
544
585
  }
545
586
  /**
546
- * Gets the current key separator used between namespace and key.
587
+ * Gets the separator between the namespace and the key. Defaults to `::`.
547
588
  */
548
- get keySeparator() {
549
- return this._keySeparator;
589
+ get namespaceSeparator() {
590
+ return this._namespaceSeparator;
550
591
  }
551
592
  /**
552
- * Sets the key separator used between namespace and key.
593
+ * Sets the separator between the namespace and the key.
553
594
  */
554
- set keySeparator(separator) {
555
- this._keySeparator = separator;
595
+ set namespaceSeparator(separator) {
596
+ this._namespaceSeparator = separator;
556
597
  }
557
598
  /**
558
599
  * Gets the current namespace.
@@ -576,7 +617,7 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
576
617
  */
577
618
  getKeyPrefix(key, namespace) {
578
619
  if (this._storeHandlesNamespace) return key;
579
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
620
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
580
621
  return key;
581
622
  }
582
623
  /**
@@ -585,9 +626,9 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
585
626
  * @returns An object containing the namespace (if present) and the original key
586
627
  */
587
628
  getKeyPrefixData(key) {
588
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
629
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
589
630
  namespace: this._namespace,
590
- key: key.slice(this._namespace.length + this._keySeparator.length)
631
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
591
632
  };
592
633
  return { key };
593
634
  }
@@ -667,25 +708,30 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
667
708
  * Stores multiple entries in the store at once.
668
709
  * Delegates to the store's native setMany if available, otherwise loops over set.
669
710
  * @param entries - Array of entries containing key, value, and optional absolute `expires`
711
+ * @returns One boolean per entry, `false` where the store reported that the write failed
670
712
  */
671
713
  async setMany(entries) {
672
714
  if (this._capabilities.methods.setMany.exists) {
673
715
  const now = Date.now();
674
716
  const isExpired = (entry) => typeof entry.expires === "number" && entry.expires <= now;
675
717
  const live = entries.filter((entry) => !isExpired(entry));
676
- if (live.length > 0) await this._store.setMany?.(live.map((entry) => ({
718
+ let liveResults;
719
+ if (live.length > 0) liveResults = await this._store.setMany?.(live.map((entry) => ({
677
720
  key: this.getKeyPrefix(entry.key, this._namespace),
678
721
  value: entry.value,
679
722
  ttl: ttlFromExpires(entry.expires)
680
723
  })));
681
724
  for (const entry of entries) if (isExpired(entry)) await this._store.delete(this.getKeyPrefix(entry.key, this._namespace));
682
- return entries.map(() => true);
725
+ let liveIndex = 0;
726
+ return entries.map((entry) => {
727
+ if (isExpired(entry)) return true;
728
+ const result = Array.isArray(liveResults) ? liveResults[liveIndex] : liveResults;
729
+ liveIndex++;
730
+ return result !== false;
731
+ });
683
732
  }
684
733
  const results = [];
685
- for (const entry of entries) {
686
- await this.set(entry.key, entry.value, entry.expires);
687
- results.push(true);
688
- }
734
+ for (const entry of entries) results.push(await this.set(entry.key, entry.value, entry.expires));
689
735
  return results;
690
736
  }
691
737
  /**
@@ -752,20 +798,20 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
752
798
  return results;
753
799
  }
754
800
  /**
755
- * Clears entries from the store. If a namespace is set and the store supports
756
- * iteration, only entries within that namespace are removed. Otherwise, the
757
- * entire store is cleared.
801
+ * Clears entries from the store. With no namespace, the whole store is cleared. With a
802
+ * namespace, only that namespace's entries are removed: a store that manages its own
803
+ * namespace clears them itself, and otherwise the bridge finds them with the store's
804
+ * `iterator()`. A store with neither can't tell namespaces apart, so this throws rather
805
+ * than call the store's `clear()` and delete every namespace's entries.
806
+ * @throws {Error} If a namespace is set and the store neither manages it nor has `iterator()`.
758
807
  */
759
808
  async clear() {
760
- if (this._namespace && this._storeHandlesNamespace) {
761
- await this._store.clear();
762
- return;
763
- }
764
- if (!this._namespace || !this._capabilities.methods.iterator.exists) {
809
+ if (!this._namespace || this._storeHandlesNamespace) {
765
810
  await this._store.clear();
766
811
  return;
767
812
  }
768
- const prefix = `${this._namespace}${this._keySeparator}`;
813
+ if (!this._capabilities.methods.iterator.exists) throw new Error(`Can't clear namespace "${this._namespace}": the store has no iterator() to find that namespace's keys, and its clear() would delete every namespace. Give the store an iterator(), or clear it without a namespace.`);
814
+ const prefix = `${this._namespace}${this._namespaceSeparator}`;
769
815
  const keysToDelete = [];
770
816
  /* v8 ignore next -- @preserve */
771
817
  for await (const entry of this._store.iterator?.(this._namespace) ?? []) {
@@ -782,7 +828,7 @@ var KeyvBridgeAdapter = class extends hookified.Hookified {
782
828
  async *iterator() {
783
829
  if (!this._capabilities.methods.iterator.exists) return;
784
830
  const namespace = this._namespace;
785
- const prefix = namespace && !this._storeHandlesNamespace ? `${namespace}${this._keySeparator}` : void 0;
831
+ const prefix = namespace && !this._storeHandlesNamespace ? `${namespace}${this._namespaceSeparator}` : void 0;
786
832
  /* v8 ignore next -- @preserve */
787
833
  for await (const entry of this._store.iterator?.(this._namespace) ?? []) {
788
834
  const [key, data] = Array.isArray(entry) ? entry : [entry];
@@ -838,7 +884,7 @@ function prepare(value) {
838
884
  if (Array.isArray(value)) return value.map((item) => prepare(item));
839
885
  if (typeof value === "object") {
840
886
  if (typeof value.toJSON === "function") return prepare(value.toJSON());
841
- const result = {};
887
+ const result = Object.create(null);
842
888
  for (const key of Object.keys(value)) if (value[key] !== void 0) result[key] = prepare(value[key]);
843
889
  return result;
844
890
  }
@@ -886,15 +932,50 @@ function buildPatterns(options) {
886
932
  return patterns.length > 0 ? patterns : void 0;
887
933
  }
888
934
  /**
889
- * Run all patterns against a string, stripping matched sequences.
935
+ * Run all patterns against a string, stripping matched sequences. Stripping one match can form
936
+ * another, as `..././` becomes `../`, so when a match remains, {@link stripRemaining} finishes
937
+ * the job.
890
938
  */
891
- function applyPatterns(value, patterns) {
939
+ function applyPatterns(value, patterns, options) {
892
940
  for (const pattern of patterns) {
893
941
  pattern.lastIndex = 0;
894
942
  value = value.replace(pattern, "");
895
943
  }
944
+ if (patterns.some((pattern) => value.search(pattern) !== -1)) return stripRemaining(value, options);
896
945
  return value;
897
946
  }
947
+ /**
948
+ * Strip the matches a single pass of {@link applyPatterns} left behind. It reads the string once,
949
+ * left to right, and drops a pattern as soon as its last character arrives, so a pattern formed by
950
+ * an earlier removal is caught without scanning the string again. The result contains no match.
951
+ */
952
+ function stripRemaining(value, options) {
953
+ const kept = [];
954
+ for (const char of value) {
955
+ const length = matchLength(kept, char, options);
956
+ if (length === 0) kept.push(char);
957
+ else kept.length -= length - 1;
958
+ }
959
+ return kept.join("");
960
+ }
961
+ const whitespace = /\s/;
962
+ /**
963
+ * The length of the pattern that `char` completes at the end of `kept`, counting `char` itself, or
964
+ * 0 when it completes none. `;`, `\0`, `\r` and `\n` need no check: the single pass before this
965
+ * removes every one of them, and removing characters never adds one back.
966
+ */
967
+ function matchLength(kept, char, options) {
968
+ const last = kept.length - 1;
969
+ if (options.sql && (char === "-" && kept[last] === "-" || char === "*" && kept[last] === "/")) return 2;
970
+ if (options.mongo && char === "$") {
971
+ if (kept.length === 0) return 1;
972
+ let start = kept.length;
973
+ while (start > 0 && whitespace.test(kept[start - 1])) start--;
974
+ if (kept[start - 1] === "{") return kept.length - start + 2;
975
+ }
976
+ if (options.path && (char === "/" || char === "\\") && kept[last] === "." && kept[last - 1] === ".") return 3;
977
+ return 0;
978
+ }
898
979
  const allOn = {
899
980
  escape: true,
900
981
  mongo: true,
@@ -963,7 +1044,7 @@ var KeyvSanitize = class {
963
1044
  this._cacheKeys.set(key, cached);
964
1045
  return cached;
965
1046
  }
966
- const result = applyPatterns(key, this._keyPatterns);
1047
+ const result = applyPatterns(key, this._keyPatterns, this._keys);
967
1048
  this._cacheKeys.set(key, result);
968
1049
  if (this._cacheKeys.size > this._cacheMax) {
969
1050
  const first = this._cacheKeys.keys().next().value;
@@ -989,7 +1070,7 @@ var KeyvSanitize = class {
989
1070
  this._cacheNamespaces.set(ns, cached);
990
1071
  return cached;
991
1072
  }
992
- const result = applyPatterns(ns, this._namespacePatterns);
1073
+ const result = applyPatterns(ns, this._namespacePatterns, this._namespace);
993
1074
  this._cacheNamespaces.set(ns, result);
994
1075
  if (this._cacheNamespaces.size > this._cacheMax) {
995
1076
  const first = this._cacheNamespaces.keys().next().value;
@@ -1135,10 +1216,10 @@ var KeyvStats = class {
1135
1216
  }
1136
1217
  /**
1137
1218
  * Build a composite key from a telemetry event.
1138
- * Format: "namespace:key" if namespace is present, otherwise just "key".
1219
+ * Format: "namespace::key" if namespace is present, otherwise just "key".
1139
1220
  */
1140
1221
  buildKeyEventName(event) {
1141
- if (event.namespace && event.key) return `${event.namespace}:${event.key}`;
1222
+ if (event.namespace && event.key) return `${event.namespace}::${event.key}`;
1142
1223
  return event.key ?? "";
1143
1224
  }
1144
1225
  /**
@@ -1221,6 +1302,12 @@ var KeyvStats = class {
1221
1302
  };
1222
1303
  //#endregion
1223
1304
  //#region src/keyv.ts
1305
+ /**
1306
+ * The namespace Keyv uses when sanitizing a namespace leaves nothing. An empty namespace would
1307
+ * turn namespacing off, mixing the instance's keys with unrelated ones and letting `clear()`
1308
+ * remove them.
1309
+ */
1310
+ const emptiedNamespace = "keyv-sanitized";
1224
1311
  var Keyv = class Keyv extends hookified.Hookified {
1225
1312
  /**
1226
1313
  * Keyv Constructor
@@ -1231,8 +1318,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1231
1318
  const mergedOptions = Keyv.resolveOptions(store, options);
1232
1319
  super({
1233
1320
  throwOnHookError: false,
1234
- throwOnEmptyListeners: true,
1235
- throwOnEmitError: mergedOptions.throwOnErrors ?? false
1321
+ throwOnEmptyListeners: true
1236
1322
  });
1237
1323
  this.deprecatedHooks = buildDeprecatedHooks();
1238
1324
  this._compression = mergedOptions.compression;
@@ -1243,7 +1329,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1243
1329
  this.initStats(mergedOptions);
1244
1330
  if (mergedOptions.store) this.setStore(mergedOptions.store);
1245
1331
  this.setTtl(mergedOptions.ttl);
1246
- this._checkExpired = mergedOptions.checkExpired ?? false;
1332
+ this._checkExpired = mergedOptions.checkExpired ?? true;
1247
1333
  }
1248
1334
  /**
1249
1335
  * Stats manager for tracking cache operation metrics (hits, misses, sets, deletes, errors).
@@ -1281,8 +1367,10 @@ var Keyv = class Keyv extends hookified.Hookified {
1281
1367
  _sanitize;
1282
1368
  /**
1283
1369
  * When true, Keyv checks expiry at its layer on get/getMany/has/hasMany.
1370
+ * Defaults to true so reads stay millisecond-precise even on adapters whose
1371
+ * native expiry is coarse or lazily swept (e.g. Memcached, DynamoDB).
1284
1372
  */
1285
- _checkExpired = false;
1373
+ _checkExpired = true;
1286
1374
  /**
1287
1375
  * Get the current storage adapter.
1288
1376
  * @returns {KeyvStorageAdapter} The current storage adapter.
@@ -1326,18 +1414,19 @@ var Keyv = class Keyv extends hookified.Hookified {
1326
1414
  this._encryption = encryption;
1327
1415
  }
1328
1416
  /**
1329
- * Get the current namespace.
1417
+ * Get the current namespace. When Keyv has no namespace of its own, this is the namespace
1418
+ * configured on the storage adapter.
1330
1419
  * @returns {string | undefined} The current namespace.
1331
1420
  */
1332
1421
  get namespace() {
1333
- return this._namespace;
1422
+ return this._namespace ?? this._store.namespace;
1334
1423
  }
1335
1424
  /**
1336
1425
  * Set the current namespace.
1337
1426
  * @param {string | undefined} namespace The namespace to set.
1338
1427
  */
1339
1428
  set namespace(namespace) {
1340
- this._namespace = namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(namespace) : namespace;
1429
+ this._namespace = namespace && this._sanitize.enabled ? this.cleanNamespace(namespace) : namespace;
1341
1430
  this._store.namespace = this._namespace;
1342
1431
  }
1343
1432
  /**
@@ -1370,22 +1459,6 @@ var Keyv = class Keyv extends hookified.Hookified {
1370
1459
  this._serialization = serialization === false ? void 0 : serialization;
1371
1460
  }
1372
1461
  /**
1373
- * Get the current throwOnErrors value. When enabled, all errors with throw. By default, errors
1374
- * will only throw if there are no listeners to the error event.
1375
- * @return {boolean} The current throwOnErrors value.
1376
- */
1377
- get throwOnErrors() {
1378
- return this.throwOnEmitError;
1379
- }
1380
- /**
1381
- * Set the current throwOnErrors value. When enabled, all errors will throw. By default, errors
1382
- * will only throw if there are no listeners to the error event.
1383
- * @param {boolean} value The throwOnErrors value to set.
1384
- */
1385
- set throwOnErrors(value) {
1386
- this.throwOnEmitError = value;
1387
- }
1388
- /**
1389
1462
  * Get the current sanitize adapter. Sanitization is disabled by default. To
1390
1463
  * enable it `sanitize.keys` or `sanitize.namespace` to true or set KeyvSanitizePatterns
1391
1464
  * to each.
@@ -1395,13 +1468,17 @@ var Keyv = class Keyv extends hookified.Hookified {
1395
1468
  return this._sanitize;
1396
1469
  }
1397
1470
  /**
1398
- * Set the sanitize adapter directly and will run sanitization on namespace.
1471
+ * Set the sanitize adapter directly and will run sanitization on namespace, including a
1472
+ * namespace kept from the storage adapter, and apply the result to the adapter.
1399
1473
  * @param {KeyvSanitizeAdapter} value The sanitize adapter to use.
1400
1474
  */
1401
1475
  set sanitize(value) {
1402
1476
  this._sanitize = value;
1403
- /* v8 ignore next -- @preserve */
1404
- this._namespace = this._namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(this._namespace) : this._namespace;
1477
+ if (this._namespace && this._sanitize.enabled) {
1478
+ this._namespace = this.cleanNamespace(this._namespace);
1479
+ this._store.namespace = this._namespace;
1480
+ }
1481
+ this.sanitizeStoreNamespace();
1405
1482
  }
1406
1483
  /**
1407
1484
  * Get the stats. This is just for this instance
@@ -1422,7 +1499,8 @@ var Keyv = class Keyv extends hookified.Hookified {
1422
1499
  }
1423
1500
  /**
1424
1501
  * Get whether Keyv checks expiry at its own layer on get/getMany/has/hasMany.
1425
- * When false (default), it trusts the storage adapter to handle expiry.
1502
+ * When true (default), expired entries are filtered (and deleted) by Keyv regardless of
1503
+ * the adapter. Set to false to trust the storage adapter to handle expiry on its own.
1426
1504
  * @returns {boolean} `true` if Keyv checks expiry at its layer.
1427
1505
  */
1428
1506
  get checkExpired() {
@@ -1435,7 +1513,9 @@ var Keyv = class Keyv extends hookified.Hookified {
1435
1513
  * with the `async` keyword is not mis-bridged).
1436
1514
  * 2. If the store implements the full async storage interface (but doesn't declare `expires`),
1437
1515
  * treat it as a legacy relative-`ttl` adapter and wrap it in KeyvBridgeAdapter.
1438
- * 3. If the store is map-like (synchronous get/set/delete/has), wrap it in KeyvMemoryAdapter.
1516
+ * 3. If the store is map-like (get/set/delete/has that aren't native `async` functions), wrap it
1517
+ * in KeyvMemoryAdapter. A store other than a Map is first asked once, through `has`, whether
1518
+ * it returns promises; if it does, wrap it in KeyvBridgeAdapter instead.
1439
1519
  * 4. If the store has async get/set/delete/clear, wrap it in KeyvBridgeAdapter.
1440
1520
  * 5. Otherwise, emit an error and fall back to a default in-memory KeyvMemoryAdapter.
1441
1521
  *
@@ -1447,20 +1527,25 @@ var Keyv = class Keyv extends hookified.Hookified {
1447
1527
  if (store?.capabilities?.expires === true) return store;
1448
1528
  const cap = detectKeyvStorage(store);
1449
1529
  if (cap.store === "keyvStorage") return new KeyvBridgeAdapter(store);
1450
- if (cap.store === "mapLike") return new KeyvMemoryAdapter(store);
1530
+ if (cap.store === "mapLike") {
1531
+ if (!(store instanceof Map) && returnsPromise(store)) return new KeyvBridgeAdapter(store);
1532
+ return new KeyvMemoryAdapter(store);
1533
+ }
1451
1534
  if (cap.store === "asyncMap") return new KeyvBridgeAdapter(store);
1452
1535
  this.emit("error", /* @__PURE__ */ new Error("Could not use the provided storage adapter, falling back to KeyvMemoryAdapter with Map"));
1453
1536
  return new KeyvMemoryAdapter(/* @__PURE__ */ new Map());
1454
1537
  }
1455
1538
  /**
1456
1539
  * Sets the storage adapter by resolving it via {@link resolveStore}, then wires up
1457
- * error forwarding and namespace propagation.
1540
+ * error forwarding and namespace propagation. Keyv's namespace, when set, is applied to the
1541
+ * adapter. Without one, the adapter keeps the namespace it was configured with.
1458
1542
  * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
1459
1543
  */
1460
1544
  setStore(store) {
1461
1545
  this._store = this.resolveStore(store);
1462
1546
  if (typeof this._store.on === "function") this._store.on("error", (error) => this.emit("error", error));
1463
- this._store.namespace = this._namespace;
1547
+ if (this._namespace !== void 0) this._store.namespace = this._namespace;
1548
+ else this.sanitizeStoreNamespace();
1464
1549
  }
1465
1550
  /**
1466
1551
  * Sets the TTL, treating zero and negative values as undefined (no TTL).
@@ -1484,6 +1569,11 @@ var Keyv = class Keyv extends hookified.Hookified {
1484
1569
  } catch (error) {
1485
1570
  this.emit("error", error);
1486
1571
  this.emitTelemetry("stat:error", key);
1572
+ await this.hookWithDeprecated("after:get", {
1573
+ key,
1574
+ value: void 0
1575
+ });
1576
+ return;
1487
1577
  }
1488
1578
  let data;
1489
1579
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
@@ -1516,6 +1606,23 @@ var Keyv = class Keyv extends hookified.Hookified {
1516
1606
  return Promise.all(keys.map(async (key) => this._store.get(key)));
1517
1607
  }
1518
1608
  /**
1609
+ * Runs a batch operation without the keys or entries whose key is empty, then returns its results
1610
+ * in the original order with `fallback` for each empty key. As with the single-key methods, an
1611
+ * empty key never reaches hooks, telemetry or the store.
1612
+ * @param items - the keys or entries of the batch
1613
+ * @param fallback - the result for an item whose key is empty
1614
+ * @param run - runs the batch operation on the items whose key is not empty
1615
+ * @returns one result per item, in the same order as `items`
1616
+ */
1617
+ async skipEmptyKeys(items, fallback, run) {
1618
+ const isEmpty = (item) => (typeof item === "string" ? item : item.key) === "";
1619
+ const kept = items.filter((item) => !isEmpty(item));
1620
+ if (kept.length === items.length) return run(items);
1621
+ const results = kept.length > 0 ? await run(kept) : [];
1622
+ let next = 0;
1623
+ return items.map((item) => isEmpty(item) ? fallback : results[next++]);
1624
+ }
1625
+ /**
1519
1626
  * Get many values for an array of keys.
1520
1627
  * @param {string[]} keys the keys to get
1521
1628
  * @returns {Promise<Array<Value | undefined>>} an array of values in the same order as the
@@ -1523,19 +1630,30 @@ var Keyv = class Keyv extends hookified.Hookified {
1523
1630
  */
1524
1631
  async getMany(keys) {
1525
1632
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1526
- await this.hookWithDeprecated("before:getMany", { keys });
1527
- const rawData = await this.storeGetMany(keys);
1528
- let deserialized;
1529
- if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1530
- else deserialized = await Promise.all(rawData.map(async (row) => {
1531
- if (row === void 0 || row === null) return;
1532
- return typeof row === "string" ? this.decode(row) : row;
1533
- }));
1534
- const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1535
- await this.hookWithDeprecated("after:getMany", result);
1536
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1537
- else this.emitTelemetry("stat:hit", keys[i]);
1538
- return result;
1633
+ return this.skipEmptyKeys(keys, void 0, async (keys) => {
1634
+ await this.hookWithDeprecated("before:getMany", { keys });
1635
+ let rawData;
1636
+ try {
1637
+ rawData = await this.storeGetMany(keys);
1638
+ } catch (error) {
1639
+ this.emit("error", error);
1640
+ this.emitTelemetry("stat:error", keys);
1641
+ const failed = keys.map(() => void 0);
1642
+ await this.hookWithDeprecated("after:getMany", failed);
1643
+ return failed;
1644
+ }
1645
+ let deserialized;
1646
+ if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1647
+ else deserialized = await Promise.all(rawData.map(async (row) => {
1648
+ if (row === void 0 || row === null) return;
1649
+ return typeof row === "string" ? this.decode(row) : row;
1650
+ }));
1651
+ const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1652
+ await this.hookWithDeprecated("after:getMany", result);
1653
+ for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1654
+ else this.emitTelemetry("stat:hit", keys[i]);
1655
+ return result;
1656
+ });
1539
1657
  }
1540
1658
  /**
1541
1659
  * Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
@@ -1547,7 +1665,18 @@ var Keyv = class Keyv extends hookified.Hookified {
1547
1665
  key = this._sanitize.enabled ? this._sanitize.cleanKey(key) : key;
1548
1666
  if (key === "") return;
1549
1667
  await this.hookWithDeprecated("before:getRaw", { key });
1550
- const rawData = await this._store.get(key);
1668
+ let rawData;
1669
+ try {
1670
+ rawData = await this._store.get(key);
1671
+ } catch (error) {
1672
+ this.emit("error", error);
1673
+ this.emitTelemetry("stat:error", key);
1674
+ await this.hookWithDeprecated("after:getRaw", {
1675
+ key,
1676
+ value: void 0
1677
+ });
1678
+ return;
1679
+ }
1551
1680
  let data;
1552
1681
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
1553
1682
  else data = rawData === void 0 || rawData === null ? void 0 : typeof rawData === "string" ? await this.decode(rawData) : rawData;
@@ -1574,29 +1703,43 @@ var Keyv = class Keyv extends hookified.Hookified {
1574
1703
  async getManyRaw(keys) {
1575
1704
  /* v8 ignore next -- @preserve */
1576
1705
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1577
- await this.hookWithDeprecated("before:getManyRaw", { keys });
1578
- if (keys.length === 0) {
1579
- const result = [];
1706
+ return this.skipEmptyKeys(keys, void 0, async (keys) => {
1707
+ await this.hookWithDeprecated("before:getManyRaw", { keys });
1708
+ if (keys.length === 0) {
1709
+ const result = [];
1710
+ await this.hookWithDeprecated("after:getManyRaw", {
1711
+ keys,
1712
+ values: result
1713
+ });
1714
+ return result;
1715
+ }
1716
+ let rawData;
1717
+ try {
1718
+ rawData = await this.storeGetMany(keys);
1719
+ } catch (error) {
1720
+ this.emit("error", error);
1721
+ this.emitTelemetry("stat:error", keys);
1722
+ const failed = keys.map(() => void 0);
1723
+ await this.hookWithDeprecated("after:getManyRaw", {
1724
+ keys,
1725
+ values: failed
1726
+ });
1727
+ return failed;
1728
+ }
1729
+ let result;
1730
+ if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1731
+ else result = await Promise.all(rawData.map(async (row) => {
1732
+ if (row === void 0 || row === null) return;
1733
+ return typeof row === "string" ? this.decode(row) : row;
1734
+ }));
1735
+ for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1736
+ else this.emitTelemetry("stat:hit", keys[i]);
1580
1737
  await this.hookWithDeprecated("after:getManyRaw", {
1581
1738
  keys,
1582
1739
  values: result
1583
1740
  });
1584
1741
  return result;
1585
- }
1586
- const rawData = await this.storeGetMany(keys);
1587
- let result;
1588
- if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1589
- else result = await Promise.all(rawData.map(async (row) => {
1590
- if (row === void 0 || row === null) return;
1591
- return typeof row === "string" ? this.decode(row) : row;
1592
- }));
1593
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1594
- else this.emitTelemetry("stat:hit", keys[i]);
1595
- await this.hookWithDeprecated("after:getManyRaw", {
1596
- keys,
1597
- values: result
1598
1742
  });
1599
- return result;
1600
1743
  }
1601
1744
  /**
1602
1745
  * Set an item to the store
@@ -1653,51 +1796,54 @@ var Keyv = class Keyv extends hookified.Hookified {
1653
1796
  ...e,
1654
1797
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1655
1798
  }));
1656
- const data = { entries };
1657
- await this.hookWithDeprecated("before:setMany", data);
1658
- entries = data.entries;
1659
- let results = [];
1660
- try {
1661
- const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1662
- ttl = resolveTtl(ttl, this._ttl);
1799
+ return this.skipEmptyKeys(entries, false, async (entries) => {
1800
+ const data = { entries };
1801
+ await this.hookWithDeprecated("before:setMany", data);
1802
+ entries = data.entries;
1803
+ let results = [];
1804
+ try {
1805
+ const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1806
+ ttl = resolveTtl(ttl, this._ttl);
1807
+ /* v8 ignore next -- @preserve */
1808
+ const expires = calculateExpires(ttl);
1809
+ /* v8 ignore next -- @preserve */
1810
+ if (typeof value === "symbol") {
1811
+ this.emit("error", "symbol cannot be serialized");
1812
+ this.emitTelemetry("stat:error", key);
1813
+ throw new Error("symbol cannot be serialized");
1814
+ }
1815
+ const formattedValue = {
1816
+ value,
1817
+ expires
1818
+ };
1819
+ return {
1820
+ key,
1821
+ value: await this.encode(formattedValue),
1822
+ expires
1823
+ };
1824
+ }));
1825
+ const storeResult = await this._store.setMany(serializedEntries);
1663
1826
  /* v8 ignore next -- @preserve */
1664
- const expires = calculateExpires(ttl);
1665
- /* v8 ignore next -- @preserve */
1666
- if (typeof value === "symbol") {
1667
- this.emit("error", "symbol cannot be serialized");
1668
- this.emitTelemetry("stat:error", key);
1669
- throw new Error("symbol cannot be serialized");
1670
- }
1671
- const formattedValue = {
1672
- value,
1673
- expires
1674
- };
1675
- return {
1676
- key,
1677
- value: await this.encode(formattedValue),
1678
- expires
1679
- };
1680
- }));
1681
- const storeResult = await this._store.setMany(serializedEntries);
1682
- /* v8 ignore next -- @preserve */
1683
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1684
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1685
- } catch (error) {
1686
- this.emit("error", error);
1687
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1688
- results = entries.map(() => false);
1689
- }
1690
- await this.hookWithDeprecated("after:setMany", {
1691
- entries,
1692
- values: results
1827
+ results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1828
+ this.emitTelemetry("stat:set", entries.map((e) => e.key));
1829
+ } catch (error) {
1830
+ this.emit("error", error);
1831
+ this.emitTelemetry("stat:error", entries.map((e) => e.key));
1832
+ results = entries.map(() => false);
1833
+ }
1834
+ await this.hookWithDeprecated("after:setMany", {
1835
+ entries,
1836
+ values: results
1837
+ });
1838
+ return results;
1693
1839
  });
1694
- return results;
1695
1840
  }
1696
1841
  /**
1697
1842
  * Set a raw value to the store without wrapping or serialization. This is the write-side counterpart to getRaw().
1698
1843
  * The value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1699
1844
  * set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`).
1700
- * The store-level TTL is derived automatically from `value.expires`.
1845
+ * The store-level expiry is derived automatically from `value.expires`, rounded up to a whole millisecond
1846
+ * (a non-finite `expires` means no store-level expiry).
1701
1847
  * @param {string} key the key to set
1702
1848
  * @param {KeyvValue<Value>} value the raw value envelope to store
1703
1849
  * @returns {Promise<boolean>} `true` if it was set successfully, `false` on failure.
@@ -1710,7 +1856,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1710
1856
  value
1711
1857
  };
1712
1858
  await this.hookWithDeprecated("before:setRaw", data);
1713
- const expires = data.value.expires;
1859
+ const expires = toStoreExpires(data.value.expires);
1714
1860
  const ttl = ttlFromExpires(expires);
1715
1861
  let result = true;
1716
1862
  try {
@@ -1733,7 +1879,8 @@ var Keyv = class Keyv extends hookified.Hookified {
1733
1879
  /**
1734
1880
  * Set many raw values to the store without wrapping or serialization. This is the write-side counterpart to getManyRaw().
1735
1881
  * Each entry's value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1736
- * set `expires` on each value directly. The store-level TTL is derived automatically from `value.expires`.
1882
+ * set `expires` on each value directly. The store-level expiry is derived automatically from `value.expires`,
1883
+ * rounded up to a whole millisecond (a non-finite `expires` means no store-level expiry).
1737
1884
  * @param {KeyvEntry<KeyvValue<Value>>[]} entries the raw entries to set
1738
1885
  * @returns {Promise<boolean[]>} an array of booleans, one per entry: `true` if set successfully, `false` on failure.
1739
1886
  */
@@ -1743,29 +1890,31 @@ var Keyv = class Keyv extends hookified.Hookified {
1743
1890
  /* v8 ignore next -- @preserve */
1744
1891
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1745
1892
  }));
1746
- let results = [];
1747
- await this.hookWithDeprecated("before:setManyRaw", { entries });
1748
- try {
1749
- const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1750
- return {
1751
- key,
1752
- value: await this.encode(value),
1753
- expires: value.expires
1754
- };
1755
- }));
1756
- const storeResult = await this._store.setMany(rawEntries);
1757
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1758
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1759
- } catch (error) {
1760
- this.emit("error", error);
1761
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1762
- results = entries.map(() => false);
1763
- }
1764
- await this.hookWithDeprecated("after:setManyRaw", {
1765
- entries,
1766
- results
1893
+ return this.skipEmptyKeys(entries, false, async (entries) => {
1894
+ let results = [];
1895
+ await this.hookWithDeprecated("before:setManyRaw", { entries });
1896
+ try {
1897
+ const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1898
+ return {
1899
+ key,
1900
+ value: await this.encode(value),
1901
+ expires: toStoreExpires(value.expires)
1902
+ };
1903
+ }));
1904
+ const storeResult = await this._store.setMany(rawEntries);
1905
+ results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1906
+ this.emitTelemetry("stat:set", entries.map((e) => e.key));
1907
+ } catch (error) {
1908
+ this.emit("error", error);
1909
+ this.emitTelemetry("stat:error", entries.map((e) => e.key));
1910
+ results = entries.map(() => false);
1911
+ }
1912
+ await this.hookWithDeprecated("after:setManyRaw", {
1913
+ entries,
1914
+ results
1915
+ });
1916
+ return results;
1767
1917
  });
1768
- return results;
1769
1918
  }
1770
1919
  async delete(key) {
1771
1920
  if (Array.isArray(key)) return this.deleteMany(key);
@@ -1795,26 +1944,28 @@ var Keyv = class Keyv extends hookified.Hookified {
1795
1944
  async deleteMany(keys) {
1796
1945
  /* v8 ignore next -- @preserve */
1797
1946
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1798
- await this.hookWithDeprecated("before:deleteMany", { keys });
1799
- await this.hookWithDeprecated("before:delete", { key: keys });
1800
- let results;
1801
- try {
1802
- results = await this._store.deleteMany(keys);
1803
- this.emitTelemetry("stat:delete", keys);
1804
- } catch (error) {
1805
- this.emit("error", error);
1806
- this.emitTelemetry("stat:error", keys);
1807
- results = keys.map(() => false);
1808
- }
1809
- await this.hookWithDeprecated("after:deleteMany", {
1810
- keys,
1811
- values: results
1812
- });
1813
- await this.hookWithDeprecated("after:delete", {
1814
- key: keys,
1815
- value: results
1947
+ return this.skipEmptyKeys(keys, false, async (keys) => {
1948
+ await this.hookWithDeprecated("before:deleteMany", { keys });
1949
+ await this.hookWithDeprecated("before:delete", { key: keys });
1950
+ let results;
1951
+ try {
1952
+ results = await this._store.deleteMany(keys);
1953
+ this.emitTelemetry("stat:delete", keys);
1954
+ } catch (error) {
1955
+ this.emit("error", error);
1956
+ this.emitTelemetry("stat:error", keys);
1957
+ results = keys.map(() => false);
1958
+ }
1959
+ await this.hookWithDeprecated("after:deleteMany", {
1960
+ keys,
1961
+ values: results
1962
+ });
1963
+ await this.hookWithDeprecated("after:delete", {
1964
+ key: keys,
1965
+ value: results
1966
+ });
1967
+ return results;
1816
1968
  });
1817
- return results;
1818
1969
  }
1819
1970
  async has(key) {
1820
1971
  if (Array.isArray(key)) return this.hasMany(key);
@@ -1847,39 +1998,42 @@ var Keyv = class Keyv extends hookified.Hookified {
1847
1998
  */
1848
1999
  async hasMany(keys) {
1849
2000
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1850
- await this.hookWithDeprecated("before:hasMany", { keys });
1851
- let results = [];
1852
- try {
1853
- if (this._checkExpired) {
1854
- const rawData = await this._store.getMany(keys);
1855
- results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
1856
- } else results = await this._store.hasMany(keys);
1857
- } catch (error) {
1858
- this.emit("error", error);
1859
- this.emitTelemetry("stat:error", keys);
1860
- results = keys.map(() => false);
1861
- }
1862
- await this.hookWithDeprecated("after:hasMany", {
1863
- keys,
1864
- values: results
2001
+ return this.skipEmptyKeys(keys, false, async (keys) => {
2002
+ await this.hookWithDeprecated("before:hasMany", { keys });
2003
+ let results = [];
2004
+ try {
2005
+ if (this._checkExpired) {
2006
+ const rawData = await this.storeGetMany(keys);
2007
+ results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
2008
+ } else results = await this._store.hasMany(keys);
2009
+ } catch (error) {
2010
+ this.emit("error", error);
2011
+ this.emitTelemetry("stat:error", keys);
2012
+ results = keys.map(() => false);
2013
+ }
2014
+ await this.hookWithDeprecated("after:hasMany", {
2015
+ keys,
2016
+ values: results
2017
+ });
2018
+ return results;
1865
2019
  });
1866
- return results;
1867
2020
  }
1868
2021
  /**
1869
- * Clear the store. If a namespace is set only entries in that namespace are removed.
2022
+ * Clear the store. If a namespace is set only entries in that namespace are removed. When the
2023
+ * store can't limit the removal to the namespace, nothing is removed and `error` is emitted.
1870
2024
  * Emits a `clear` event.
1871
2025
  * @returns {Promise<void>} resolves once the entries have been cleared.
1872
2026
  */
1873
2027
  async clear() {
1874
2028
  this.emit("clear");
1875
- await this.hook("before:clear", { namespace: this._namespace });
2029
+ await this.hook("before:clear", { namespace: this.namespace });
1876
2030
  try {
1877
2031
  await this._store.clear();
1878
2032
  } catch (error) {
1879
2033
  this.emit("error", error);
1880
2034
  this.emitTelemetry("stat:error");
1881
2035
  }
1882
- await this.hook("after:clear", { namespace: this._namespace });
2036
+ await this.hook("after:clear", { namespace: this.namespace });
1883
2037
  }
1884
2038
  /**
1885
2039
  * Will disconnect the store. This is only available if the store has a disconnect method
@@ -1887,13 +2041,13 @@ var Keyv = class Keyv extends hookified.Hookified {
1887
2041
  */
1888
2042
  async disconnect() {
1889
2043
  this.emit("disconnect");
1890
- await this.hook("before:disconnect", { namespace: this._namespace });
2044
+ await this.hook("before:disconnect", { namespace: this.namespace });
1891
2045
  try {
1892
2046
  if (this._store.disconnect) await this._store.disconnect();
1893
2047
  } catch (error) {
1894
2048
  this.emit("error", error);
1895
2049
  }
1896
- await this.hook("after:disconnect", { namespace: this._namespace });
2050
+ await this.hook("after:disconnect", { namespace: this.namespace });
1897
2051
  }
1898
2052
  /**
1899
2053
  * Iterate over all key-value pairs in the store. Automatically deserializes values,
@@ -1903,23 +2057,34 @@ var Keyv = class Keyv extends hookified.Hookified {
1903
2057
  async *iterator() {
1904
2058
  /* v8 ignore next 3 -- @preserve */
1905
2059
  if (this._store.iterator === void 0) return;
1906
- for await (const [key, raw] of this._store.iterator()) {
1907
- const data = await this.decode(raw);
1908
- if (this._checkExpired && data && isDataExpired(data)) {
1909
- await this.delete(key);
1910
- continue;
2060
+ try {
2061
+ for await (const [key, raw] of this._store.iterator()) {
2062
+ const data = await this.decode(raw);
2063
+ if (this._checkExpired && data && isDataExpired(data)) {
2064
+ await this.delete(key);
2065
+ continue;
2066
+ }
2067
+ yield [key, data?.value];
1911
2068
  }
1912
- yield [key, data?.value];
2069
+ } catch (error) {
2070
+ this.emit("error", error);
2071
+ this.emitTelemetry("stat:error");
1913
2072
  }
1914
2073
  }
1915
2074
  /**
1916
2075
  * Encodes a value for storage. Pipeline: serialize → compress → encrypt.
1917
- * If serialization is not configured, returns the data as-is.
2076
+ * If serialization is not configured, returns the data as-is, skipping compression. With an
2077
+ * encryption adapter set, it throws instead, since the value can't be encrypted and storing it
2078
+ * unencrypted would defeat the adapter.
1918
2079
  * @param {KeyvValue<T>} data The value envelope to encode.
1919
- * @returns {Promise<unknown>} The encoded value, or the original data on failure.
2080
+ * @returns {Promise<unknown>} The encoded value.
2081
+ * @throws {Error} If an encryption adapter is set while serialization is disabled.
1920
2082
  */
1921
2083
  async encode(data) {
1922
- if (!this._serialization) return data;
2084
+ if (!this._serialization) {
2085
+ if (this._encryption?.encrypt) throw new Error("Encryption needs serialization, which is disabled, so Keyv won't store the value unencrypted. Remove `serialization: false` or the encryption adapter.");
2086
+ return data;
2087
+ }
1923
2088
  let result = await this._serialization.stringify(data);
1924
2089
  if (this._compression?.compress) result = await this._compression.compress(result);
1925
2090
  if (this._encryption?.encrypt) result = await this._encryption.encrypt(result);
@@ -1990,7 +2155,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1990
2155
  if (key === void 0) {
1991
2156
  this.emit(event, {
1992
2157
  event: event.replace("stat:", ""),
1993
- namespace: this._namespace,
2158
+ namespace: this.namespace,
1994
2159
  timestamp: Date.now()
1995
2160
  });
1996
2161
  return;
@@ -1999,7 +2164,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1999
2164
  for (const k of keys) this.emit(event, {
2000
2165
  event: event.replace("stat:", ""),
2001
2166
  key: k,
2002
- namespace: this._namespace,
2167
+ namespace: this.namespace,
2003
2168
  timestamp: Date.now()
2004
2169
  });
2005
2170
  }
@@ -2043,7 +2208,20 @@ var Keyv = class Keyv extends hookified.Hookified {
2043
2208
  */
2044
2209
  initNamespace(namespace) {
2045
2210
  this._namespace = namespace;
2046
- if (this._namespace && this._sanitize.enabled) this._namespace = this._sanitize.cleanNamespace(this._namespace);
2211
+ if (this._namespace && this._sanitize.enabled) this._namespace = this.cleanNamespace(this._namespace);
2212
+ }
2213
+ /**
2214
+ * Sanitizes a namespace. When sanitizing leaves nothing, it returns {@link emptiedNamespace} so
2215
+ * the instance keeps a namespace of its own.
2216
+ */
2217
+ cleanNamespace(namespace) {
2218
+ return this._sanitize.cleanNamespace(namespace) || emptiedNamespace;
2219
+ }
2220
+ /**
2221
+ * Sanitizes the namespace kept from the storage adapter when Keyv has none of its own.
2222
+ */
2223
+ sanitizeStoreNamespace() {
2224
+ if (this._namespace === void 0 && this._store.namespace && this._sanitize.enabled) this._store.namespace = this.cleanNamespace(this._store.namespace);
2047
2225
  }
2048
2226
  };
2049
2227
  //#endregion
@@ -2062,14 +2240,14 @@ var Keyv = class Keyv extends hookified.Hookified {
2062
2240
  * // Using with a custom store
2063
2241
  * const customStore = new KeyvMemoryAdapter(myCustomMapLikeStore, {
2064
2242
  * namespace: 'tenant-123',
2065
- * keySeparator: ':'
2243
+ * namespaceSeparator: '::'
2066
2244
  * });
2067
2245
  * ```
2068
2246
  */
2069
2247
  var KeyvMemoryAdapter = class extends hookified.Hookified {
2070
2248
  _store;
2071
2249
  _namespace;
2072
- _keySeparator = ":";
2250
+ _namespaceSeparator = "::";
2073
2251
  _capabilities;
2074
2252
  /**
2075
2253
  * Creates a new KeyvMemoryAdapter instance.
@@ -2080,7 +2258,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2080
2258
  super({ throwOnHookError: false });
2081
2259
  this._store = store;
2082
2260
  this._capabilities = detectKeyvStorage(store);
2083
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
2261
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
2084
2262
  if (options?.namespace) this._namespace = options?.namespace;
2085
2263
  }
2086
2264
  /**
@@ -2106,16 +2284,16 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2106
2284
  this._store = store;
2107
2285
  }
2108
2286
  /**
2109
- * Gets the current key separator used between namespace and key.
2287
+ * Gets the separator between the namespace and the key. Defaults to `::`.
2110
2288
  */
2111
- get keySeparator() {
2112
- return this._keySeparator;
2289
+ get namespaceSeparator() {
2290
+ return this._namespaceSeparator;
2113
2291
  }
2114
2292
  /**
2115
- * Sets the key separator used between namespace and key.
2293
+ * Sets the separator between the namespace and the key.
2116
2294
  */
2117
- set keySeparator(separator) {
2118
- this._keySeparator = separator;
2295
+ set namespaceSeparator(separator) {
2296
+ this._namespaceSeparator = separator;
2119
2297
  }
2120
2298
  /**
2121
2299
  * Gets the current namespace.
@@ -2136,7 +2314,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2136
2314
  * @returns The prefixed key if namespace is provided, otherwise the original key
2137
2315
  */
2138
2316
  getKeyPrefix(key, namespace) {
2139
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
2317
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
2140
2318
  return key;
2141
2319
  }
2142
2320
  /**
@@ -2145,9 +2323,9 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2145
2323
  * @returns An object containing the namespace (if present) and the original key
2146
2324
  */
2147
2325
  getKeyPrefixData(key) {
2148
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
2326
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
2149
2327
  namespace: this._namespace,
2150
- key: key.slice(this._namespace.length + this._keySeparator.length)
2328
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
2151
2329
  };
2152
2330
  return { key };
2153
2331
  }
@@ -2210,16 +2388,19 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2210
2388
  return this._store.delete(keyPrefix);
2211
2389
  }
2212
2390
  /**
2213
- * Clears entries from the store. If a namespace is set, only entries
2214
- * within that namespace are removed. Otherwise, the entire store is cleared.
2215
- * NOTE: if there is no `keys()` then we just do a full clear.
2391
+ * Clears entries from the store. With no namespace, the whole store is cleared. With a
2392
+ * namespace, only that namespace's entries are removed, found through the store's `keys()`.
2393
+ * A store without `keys()` can't tell namespaces apart, so this throws rather than call the
2394
+ * store's `clear()` and delete every namespace's entries.
2395
+ * @throws {Error} If a namespace is set and the store has no `keys()`.
2216
2396
  */
2217
2397
  async clear() {
2218
- if (!this._namespace || typeof this._store.keys !== "function") {
2398
+ if (!this._namespace) {
2219
2399
  this._store.clear();
2220
2400
  return;
2221
2401
  }
2222
- const prefix = `${this._namespace}${this._keySeparator}`;
2402
+ if (typeof this._store.keys !== "function") throw new Error(`Can't clear namespace "${this._namespace}": the store has no keys() to find that namespace's keys, and its clear() would delete every namespace. Use a store with keys(), such as a Map, or clear it without a namespace.`);
2403
+ const prefix = `${this._namespace}${this._namespaceSeparator}`;
2223
2404
  const keysToDelete = [];
2224
2405
  for (const key of this._store.keys()) if (key.startsWith(prefix)) keysToDelete.push(key);
2225
2406
  for (const key of keysToDelete) this._store.delete(key);
@@ -2300,14 +2481,14 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2300
2481
  const namespace = this._namespace;
2301
2482
  for (const [key, raw] of this._store.entries()) {
2302
2483
  if (namespace) {
2303
- if (!key.startsWith(`${namespace}${this._keySeparator}`)) continue;
2484
+ if (!key.startsWith(`${namespace}${this._namespaceSeparator}`)) continue;
2304
2485
  }
2305
2486
  const entry = raw;
2306
2487
  if (entry?.expires !== void 0 && Date.now() > entry.expires) {
2307
2488
  this._store.delete(key);
2308
2489
  continue;
2309
2490
  }
2310
- yield [namespace ? key.slice(namespace.length + this._keySeparator.length) : key, entry?.value];
2491
+ yield [namespace ? key.slice(namespace.length + this._namespaceSeparator.length) : key, entry?.value];
2311
2492
  }
2312
2493
  }
2313
2494
  /**
@@ -2335,7 +2516,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2335
2516
  * // Create with namespace for multi-tenant scenarios
2336
2517
  * const tenantCache = createKeyv(new Map(), {
2337
2518
  * namespace: 'tenant-123',
2338
- * keySeparator: ':'
2519
+ * namespaceSeparator: '::'
2339
2520
  * });
2340
2521
  * ```
2341
2522
  */