keyv 6.0.0-rc.1 → 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
  */
@@ -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;
@@ -1328,18 +1414,19 @@ var Keyv = class Keyv extends hookified.Hookified {
1328
1414
  this._encryption = encryption;
1329
1415
  }
1330
1416
  /**
1331
- * 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.
1332
1419
  * @returns {string | undefined} The current namespace.
1333
1420
  */
1334
1421
  get namespace() {
1335
- return this._namespace;
1422
+ return this._namespace ?? this._store.namespace;
1336
1423
  }
1337
1424
  /**
1338
1425
  * Set the current namespace.
1339
1426
  * @param {string | undefined} namespace The namespace to set.
1340
1427
  */
1341
1428
  set namespace(namespace) {
1342
- this._namespace = namespace && this._sanitize.enabled ? this._sanitize.cleanNamespace(namespace) : namespace;
1429
+ this._namespace = namespace && this._sanitize.enabled ? this.cleanNamespace(namespace) : namespace;
1343
1430
  this._store.namespace = this._namespace;
1344
1431
  }
1345
1432
  /**
@@ -1372,22 +1459,6 @@ var Keyv = class Keyv extends hookified.Hookified {
1372
1459
  this._serialization = serialization === false ? void 0 : serialization;
1373
1460
  }
1374
1461
  /**
1375
- * Get the current throwOnErrors value. When enabled, all errors with throw. By default, errors
1376
- * will only throw if there are no listeners to the error event.
1377
- * @return {boolean} The current throwOnErrors value.
1378
- */
1379
- get throwOnErrors() {
1380
- return this.throwOnEmitError;
1381
- }
1382
- /**
1383
- * Set the current throwOnErrors value. When enabled, all errors will throw. By default, errors
1384
- * will only throw if there are no listeners to the error event.
1385
- * @param {boolean} value The throwOnErrors value to set.
1386
- */
1387
- set throwOnErrors(value) {
1388
- this.throwOnEmitError = value;
1389
- }
1390
- /**
1391
1462
  * Get the current sanitize adapter. Sanitization is disabled by default. To
1392
1463
  * enable it `sanitize.keys` or `sanitize.namespace` to true or set KeyvSanitizePatterns
1393
1464
  * to each.
@@ -1397,13 +1468,17 @@ var Keyv = class Keyv extends hookified.Hookified {
1397
1468
  return this._sanitize;
1398
1469
  }
1399
1470
  /**
1400
- * 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.
1401
1473
  * @param {KeyvSanitizeAdapter} value The sanitize adapter to use.
1402
1474
  */
1403
1475
  set sanitize(value) {
1404
1476
  this._sanitize = value;
1405
- /* v8 ignore next -- @preserve */
1406
- 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();
1407
1482
  }
1408
1483
  /**
1409
1484
  * Get the stats. This is just for this instance
@@ -1438,7 +1513,9 @@ var Keyv = class Keyv extends hookified.Hookified {
1438
1513
  * with the `async` keyword is not mis-bridged).
1439
1514
  * 2. If the store implements the full async storage interface (but doesn't declare `expires`),
1440
1515
  * treat it as a legacy relative-`ttl` adapter and wrap it in KeyvBridgeAdapter.
1441
- * 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.
1442
1519
  * 4. If the store has async get/set/delete/clear, wrap it in KeyvBridgeAdapter.
1443
1520
  * 5. Otherwise, emit an error and fall back to a default in-memory KeyvMemoryAdapter.
1444
1521
  *
@@ -1450,20 +1527,25 @@ var Keyv = class Keyv extends hookified.Hookified {
1450
1527
  if (store?.capabilities?.expires === true) return store;
1451
1528
  const cap = detectKeyvStorage(store);
1452
1529
  if (cap.store === "keyvStorage") return new KeyvBridgeAdapter(store);
1453
- 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
+ }
1454
1534
  if (cap.store === "asyncMap") return new KeyvBridgeAdapter(store);
1455
1535
  this.emit("error", /* @__PURE__ */ new Error("Could not use the provided storage adapter, falling back to KeyvMemoryAdapter with Map"));
1456
1536
  return new KeyvMemoryAdapter(/* @__PURE__ */ new Map());
1457
1537
  }
1458
1538
  /**
1459
1539
  * Sets the storage adapter by resolving it via {@link resolveStore}, then wires up
1460
- * 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.
1461
1542
  * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
1462
1543
  */
1463
1544
  setStore(store) {
1464
1545
  this._store = this.resolveStore(store);
1465
1546
  if (typeof this._store.on === "function") this._store.on("error", (error) => this.emit("error", error));
1466
- this._store.namespace = this._namespace;
1547
+ if (this._namespace !== void 0) this._store.namespace = this._namespace;
1548
+ else this.sanitizeStoreNamespace();
1467
1549
  }
1468
1550
  /**
1469
1551
  * Sets the TTL, treating zero and negative values as undefined (no TTL).
@@ -1487,6 +1569,11 @@ var Keyv = class Keyv extends hookified.Hookified {
1487
1569
  } catch (error) {
1488
1570
  this.emit("error", error);
1489
1571
  this.emitTelemetry("stat:error", key);
1572
+ await this.hookWithDeprecated("after:get", {
1573
+ key,
1574
+ value: void 0
1575
+ });
1576
+ return;
1490
1577
  }
1491
1578
  let data;
1492
1579
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
@@ -1519,6 +1606,23 @@ var Keyv = class Keyv extends hookified.Hookified {
1519
1606
  return Promise.all(keys.map(async (key) => this._store.get(key)));
1520
1607
  }
1521
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
+ /**
1522
1626
  * Get many values for an array of keys.
1523
1627
  * @param {string[]} keys the keys to get
1524
1628
  * @returns {Promise<Array<Value | undefined>>} an array of values in the same order as the
@@ -1526,19 +1630,30 @@ var Keyv = class Keyv extends hookified.Hookified {
1526
1630
  */
1527
1631
  async getMany(keys) {
1528
1632
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1529
- await this.hookWithDeprecated("before:getMany", { keys });
1530
- const rawData = await this.storeGetMany(keys);
1531
- let deserialized;
1532
- if (this._checkExpired) deserialized = await this.decodeWithExpire(keys, rawData);
1533
- else deserialized = await Promise.all(rawData.map(async (row) => {
1534
- if (row === void 0 || row === null) return;
1535
- return typeof row === "string" ? this.decode(row) : row;
1536
- }));
1537
- const result = deserialized.map((row) => row !== void 0 ? row.value : void 0);
1538
- await this.hookWithDeprecated("after:getMany", result);
1539
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1540
- else this.emitTelemetry("stat:hit", keys[i]);
1541
- 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
+ });
1542
1657
  }
1543
1658
  /**
1544
1659
  * Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
@@ -1550,7 +1665,18 @@ var Keyv = class Keyv extends hookified.Hookified {
1550
1665
  key = this._sanitize.enabled ? this._sanitize.cleanKey(key) : key;
1551
1666
  if (key === "") return;
1552
1667
  await this.hookWithDeprecated("before:getRaw", { key });
1553
- 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
+ }
1554
1680
  let data;
1555
1681
  if (this._checkExpired) [data] = await this.decodeWithExpire(key, rawData);
1556
1682
  else data = rawData === void 0 || rawData === null ? void 0 : typeof rawData === "string" ? await this.decode(rawData) : rawData;
@@ -1577,29 +1703,43 @@ var Keyv = class Keyv extends hookified.Hookified {
1577
1703
  async getManyRaw(keys) {
1578
1704
  /* v8 ignore next -- @preserve */
1579
1705
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1580
- await this.hookWithDeprecated("before:getManyRaw", { keys });
1581
- if (keys.length === 0) {
1582
- 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]);
1583
1737
  await this.hookWithDeprecated("after:getManyRaw", {
1584
1738
  keys,
1585
1739
  values: result
1586
1740
  });
1587
1741
  return result;
1588
- }
1589
- const rawData = await this.storeGetMany(keys);
1590
- let result;
1591
- if (this._checkExpired) result = await this.decodeWithExpire(keys, rawData);
1592
- else result = await Promise.all(rawData.map(async (row) => {
1593
- if (row === void 0 || row === null) return;
1594
- return typeof row === "string" ? this.decode(row) : row;
1595
- }));
1596
- for (let i = 0; i < result.length; i++) if (result[i] === void 0) this.emitTelemetry("stat:miss", keys[i]);
1597
- else this.emitTelemetry("stat:hit", keys[i]);
1598
- await this.hookWithDeprecated("after:getManyRaw", {
1599
- keys,
1600
- values: result
1601
1742
  });
1602
- return result;
1603
1743
  }
1604
1744
  /**
1605
1745
  * Set an item to the store
@@ -1656,51 +1796,54 @@ var Keyv = class Keyv extends hookified.Hookified {
1656
1796
  ...e,
1657
1797
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1658
1798
  }));
1659
- const data = { entries };
1660
- await this.hookWithDeprecated("before:setMany", data);
1661
- entries = data.entries;
1662
- let results = [];
1663
- try {
1664
- const serializedEntries = await Promise.all(entries.map(async ({ key, value, ttl }) => {
1665
- 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);
1666
1826
  /* v8 ignore next -- @preserve */
1667
- const expires = calculateExpires(ttl);
1668
- /* v8 ignore next -- @preserve */
1669
- if (typeof value === "symbol") {
1670
- this.emit("error", "symbol cannot be serialized");
1671
- this.emitTelemetry("stat:error", key);
1672
- throw new Error("symbol cannot be serialized");
1673
- }
1674
- const formattedValue = {
1675
- value,
1676
- expires
1677
- };
1678
- return {
1679
- key,
1680
- value: await this.encode(formattedValue),
1681
- expires
1682
- };
1683
- }));
1684
- const storeResult = await this._store.setMany(serializedEntries);
1685
- /* v8 ignore next -- @preserve */
1686
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1687
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1688
- } catch (error) {
1689
- this.emit("error", error);
1690
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1691
- results = entries.map(() => false);
1692
- }
1693
- await this.hookWithDeprecated("after:setMany", {
1694
- entries,
1695
- 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;
1696
1839
  });
1697
- return results;
1698
1840
  }
1699
1841
  /**
1700
1842
  * Set a raw value to the store without wrapping or serialization. This is the write-side counterpart to getRaw().
1701
1843
  * The value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1702
1844
  * set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`).
1703
- * 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).
1704
1847
  * @param {string} key the key to set
1705
1848
  * @param {KeyvValue<Value>} value the raw value envelope to store
1706
1849
  * @returns {Promise<boolean>} `true` if it was set successfully, `false` on failure.
@@ -1713,7 +1856,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1713
1856
  value
1714
1857
  };
1715
1858
  await this.hookWithDeprecated("before:setRaw", data);
1716
- const expires = data.value.expires;
1859
+ const expires = toStoreExpires(data.value.expires);
1717
1860
  const ttl = ttlFromExpires(expires);
1718
1861
  let result = true;
1719
1862
  try {
@@ -1736,7 +1879,8 @@ var Keyv = class Keyv extends hookified.Hookified {
1736
1879
  /**
1737
1880
  * Set many raw values to the store without wrapping or serialization. This is the write-side counterpart to getManyRaw().
1738
1881
  * Each entry's value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1739
- * 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).
1740
1884
  * @param {KeyvEntry<KeyvValue<Value>>[]} entries the raw entries to set
1741
1885
  * @returns {Promise<boolean[]>} an array of booleans, one per entry: `true` if set successfully, `false` on failure.
1742
1886
  */
@@ -1746,29 +1890,31 @@ var Keyv = class Keyv extends hookified.Hookified {
1746
1890
  /* v8 ignore next -- @preserve */
1747
1891
  key: this._sanitize.enabled ? this._sanitize.cleanKey(e.key) : e.key
1748
1892
  }));
1749
- let results = [];
1750
- await this.hookWithDeprecated("before:setManyRaw", { entries });
1751
- try {
1752
- const rawEntries = await Promise.all(entries.map(async ({ key, value }) => {
1753
- return {
1754
- key,
1755
- value: await this.encode(value),
1756
- expires: value.expires
1757
- };
1758
- }));
1759
- const storeResult = await this._store.setMany(rawEntries);
1760
- results = Array.isArray(storeResult) ? storeResult : entries.map(() => true);
1761
- this.emitTelemetry("stat:set", entries.map((e) => e.key));
1762
- } catch (error) {
1763
- this.emit("error", error);
1764
- this.emitTelemetry("stat:error", entries.map((e) => e.key));
1765
- results = entries.map(() => false);
1766
- }
1767
- await this.hookWithDeprecated("after:setManyRaw", {
1768
- entries,
1769
- 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;
1770
1917
  });
1771
- return results;
1772
1918
  }
1773
1919
  async delete(key) {
1774
1920
  if (Array.isArray(key)) return this.deleteMany(key);
@@ -1798,26 +1944,28 @@ var Keyv = class Keyv extends hookified.Hookified {
1798
1944
  async deleteMany(keys) {
1799
1945
  /* v8 ignore next -- @preserve */
1800
1946
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1801
- await this.hookWithDeprecated("before:deleteMany", { keys });
1802
- await this.hookWithDeprecated("before:delete", { key: keys });
1803
- let results;
1804
- try {
1805
- results = await this._store.deleteMany(keys);
1806
- this.emitTelemetry("stat:delete", keys);
1807
- } catch (error) {
1808
- this.emit("error", error);
1809
- this.emitTelemetry("stat:error", keys);
1810
- results = keys.map(() => false);
1811
- }
1812
- await this.hookWithDeprecated("after:deleteMany", {
1813
- keys,
1814
- values: results
1815
- });
1816
- await this.hookWithDeprecated("after:delete", {
1817
- key: keys,
1818
- 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;
1819
1968
  });
1820
- return results;
1821
1969
  }
1822
1970
  async has(key) {
1823
1971
  if (Array.isArray(key)) return this.hasMany(key);
@@ -1850,39 +1998,42 @@ var Keyv = class Keyv extends hookified.Hookified {
1850
1998
  */
1851
1999
  async hasMany(keys) {
1852
2000
  keys = this._sanitize.enabled ? this._sanitize.cleanKeys(keys) : keys;
1853
- await this.hookWithDeprecated("before:hasMany", { keys });
1854
- let results = [];
1855
- try {
1856
- if (this._checkExpired) {
1857
- const rawData = await this.storeGetMany(keys);
1858
- results = (await this.decodeWithExpire(keys, rawData)).map((row) => row !== void 0);
1859
- } else results = await this._store.hasMany(keys);
1860
- } catch (error) {
1861
- this.emit("error", error);
1862
- this.emitTelemetry("stat:error", keys);
1863
- results = keys.map(() => false);
1864
- }
1865
- await this.hookWithDeprecated("after:hasMany", {
1866
- keys,
1867
- 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;
1868
2019
  });
1869
- return results;
1870
2020
  }
1871
2021
  /**
1872
- * 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.
1873
2024
  * Emits a `clear` event.
1874
2025
  * @returns {Promise<void>} resolves once the entries have been cleared.
1875
2026
  */
1876
2027
  async clear() {
1877
2028
  this.emit("clear");
1878
- await this.hook("before:clear", { namespace: this._namespace });
2029
+ await this.hook("before:clear", { namespace: this.namespace });
1879
2030
  try {
1880
2031
  await this._store.clear();
1881
2032
  } catch (error) {
1882
2033
  this.emit("error", error);
1883
2034
  this.emitTelemetry("stat:error");
1884
2035
  }
1885
- await this.hook("after:clear", { namespace: this._namespace });
2036
+ await this.hook("after:clear", { namespace: this.namespace });
1886
2037
  }
1887
2038
  /**
1888
2039
  * Will disconnect the store. This is only available if the store has a disconnect method
@@ -1890,13 +2041,13 @@ var Keyv = class Keyv extends hookified.Hookified {
1890
2041
  */
1891
2042
  async disconnect() {
1892
2043
  this.emit("disconnect");
1893
- await this.hook("before:disconnect", { namespace: this._namespace });
2044
+ await this.hook("before:disconnect", { namespace: this.namespace });
1894
2045
  try {
1895
2046
  if (this._store.disconnect) await this._store.disconnect();
1896
2047
  } catch (error) {
1897
2048
  this.emit("error", error);
1898
2049
  }
1899
- await this.hook("after:disconnect", { namespace: this._namespace });
2050
+ await this.hook("after:disconnect", { namespace: this.namespace });
1900
2051
  }
1901
2052
  /**
1902
2053
  * Iterate over all key-value pairs in the store. Automatically deserializes values,
@@ -1906,23 +2057,34 @@ var Keyv = class Keyv extends hookified.Hookified {
1906
2057
  async *iterator() {
1907
2058
  /* v8 ignore next 3 -- @preserve */
1908
2059
  if (this._store.iterator === void 0) return;
1909
- for await (const [key, raw] of this._store.iterator()) {
1910
- const data = await this.decode(raw);
1911
- if (this._checkExpired && data && isDataExpired(data)) {
1912
- await this.delete(key);
1913
- 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];
1914
2068
  }
1915
- yield [key, data?.value];
2069
+ } catch (error) {
2070
+ this.emit("error", error);
2071
+ this.emitTelemetry("stat:error");
1916
2072
  }
1917
2073
  }
1918
2074
  /**
1919
2075
  * Encodes a value for storage. Pipeline: serialize → compress → encrypt.
1920
- * 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.
1921
2079
  * @param {KeyvValue<T>} data The value envelope to encode.
1922
- * @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.
1923
2082
  */
1924
2083
  async encode(data) {
1925
- 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
+ }
1926
2088
  let result = await this._serialization.stringify(data);
1927
2089
  if (this._compression?.compress) result = await this._compression.compress(result);
1928
2090
  if (this._encryption?.encrypt) result = await this._encryption.encrypt(result);
@@ -1993,7 +2155,7 @@ var Keyv = class Keyv extends hookified.Hookified {
1993
2155
  if (key === void 0) {
1994
2156
  this.emit(event, {
1995
2157
  event: event.replace("stat:", ""),
1996
- namespace: this._namespace,
2158
+ namespace: this.namespace,
1997
2159
  timestamp: Date.now()
1998
2160
  });
1999
2161
  return;
@@ -2002,7 +2164,7 @@ var Keyv = class Keyv extends hookified.Hookified {
2002
2164
  for (const k of keys) this.emit(event, {
2003
2165
  event: event.replace("stat:", ""),
2004
2166
  key: k,
2005
- namespace: this._namespace,
2167
+ namespace: this.namespace,
2006
2168
  timestamp: Date.now()
2007
2169
  });
2008
2170
  }
@@ -2046,7 +2208,20 @@ var Keyv = class Keyv extends hookified.Hookified {
2046
2208
  */
2047
2209
  initNamespace(namespace) {
2048
2210
  this._namespace = namespace;
2049
- 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);
2050
2225
  }
2051
2226
  };
2052
2227
  //#endregion
@@ -2065,14 +2240,14 @@ var Keyv = class Keyv extends hookified.Hookified {
2065
2240
  * // Using with a custom store
2066
2241
  * const customStore = new KeyvMemoryAdapter(myCustomMapLikeStore, {
2067
2242
  * namespace: 'tenant-123',
2068
- * keySeparator: ':'
2243
+ * namespaceSeparator: '::'
2069
2244
  * });
2070
2245
  * ```
2071
2246
  */
2072
2247
  var KeyvMemoryAdapter = class extends hookified.Hookified {
2073
2248
  _store;
2074
2249
  _namespace;
2075
- _keySeparator = ":";
2250
+ _namespaceSeparator = "::";
2076
2251
  _capabilities;
2077
2252
  /**
2078
2253
  * Creates a new KeyvMemoryAdapter instance.
@@ -2083,7 +2258,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2083
2258
  super({ throwOnHookError: false });
2084
2259
  this._store = store;
2085
2260
  this._capabilities = detectKeyvStorage(store);
2086
- if (options?.keySeparator) this._keySeparator = options.keySeparator;
2261
+ if (options?.namespaceSeparator !== void 0) this._namespaceSeparator = options.namespaceSeparator;
2087
2262
  if (options?.namespace) this._namespace = options?.namespace;
2088
2263
  }
2089
2264
  /**
@@ -2109,16 +2284,16 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2109
2284
  this._store = store;
2110
2285
  }
2111
2286
  /**
2112
- * Gets the current key separator used between namespace and key.
2287
+ * Gets the separator between the namespace and the key. Defaults to `::`.
2113
2288
  */
2114
- get keySeparator() {
2115
- return this._keySeparator;
2289
+ get namespaceSeparator() {
2290
+ return this._namespaceSeparator;
2116
2291
  }
2117
2292
  /**
2118
- * Sets the key separator used between namespace and key.
2293
+ * Sets the separator between the namespace and the key.
2119
2294
  */
2120
- set keySeparator(separator) {
2121
- this._keySeparator = separator;
2295
+ set namespaceSeparator(separator) {
2296
+ this._namespaceSeparator = separator;
2122
2297
  }
2123
2298
  /**
2124
2299
  * Gets the current namespace.
@@ -2139,7 +2314,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2139
2314
  * @returns The prefixed key if namespace is provided, otherwise the original key
2140
2315
  */
2141
2316
  getKeyPrefix(key, namespace) {
2142
- if (namespace) return `${namespace}${this._keySeparator}${key}`;
2317
+ if (namespace) return `${namespace}${this._namespaceSeparator}${key}`;
2143
2318
  return key;
2144
2319
  }
2145
2320
  /**
@@ -2148,9 +2323,9 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2148
2323
  * @returns An object containing the namespace (if present) and the original key
2149
2324
  */
2150
2325
  getKeyPrefixData(key) {
2151
- if (this._namespace && key.startsWith(`${this._namespace}${this._keySeparator}`)) return {
2326
+ if (this._namespace && key.startsWith(`${this._namespace}${this._namespaceSeparator}`)) return {
2152
2327
  namespace: this._namespace,
2153
- key: key.slice(this._namespace.length + this._keySeparator.length)
2328
+ key: key.slice(this._namespace.length + this._namespaceSeparator.length)
2154
2329
  };
2155
2330
  return { key };
2156
2331
  }
@@ -2213,16 +2388,19 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2213
2388
  return this._store.delete(keyPrefix);
2214
2389
  }
2215
2390
  /**
2216
- * Clears entries from the store. If a namespace is set, only entries
2217
- * within that namespace are removed. Otherwise, the entire store is cleared.
2218
- * 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()`.
2219
2396
  */
2220
2397
  async clear() {
2221
- if (!this._namespace || typeof this._store.keys !== "function") {
2398
+ if (!this._namespace) {
2222
2399
  this._store.clear();
2223
2400
  return;
2224
2401
  }
2225
- 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}`;
2226
2404
  const keysToDelete = [];
2227
2405
  for (const key of this._store.keys()) if (key.startsWith(prefix)) keysToDelete.push(key);
2228
2406
  for (const key of keysToDelete) this._store.delete(key);
@@ -2303,14 +2481,14 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2303
2481
  const namespace = this._namespace;
2304
2482
  for (const [key, raw] of this._store.entries()) {
2305
2483
  if (namespace) {
2306
- if (!key.startsWith(`${namespace}${this._keySeparator}`)) continue;
2484
+ if (!key.startsWith(`${namespace}${this._namespaceSeparator}`)) continue;
2307
2485
  }
2308
2486
  const entry = raw;
2309
2487
  if (entry?.expires !== void 0 && Date.now() > entry.expires) {
2310
2488
  this._store.delete(key);
2311
2489
  continue;
2312
2490
  }
2313
- 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];
2314
2492
  }
2315
2493
  }
2316
2494
  /**
@@ -2338,7 +2516,7 @@ var KeyvMemoryAdapter = class extends hookified.Hookified {
2338
2516
  * // Create with namespace for multi-tenant scenarios
2339
2517
  * const tenantCache = createKeyv(new Map(), {
2340
2518
  * namespace: 'tenant-123',
2341
- * keySeparator: ':'
2519
+ * namespaceSeparator: '::'
2342
2520
  * });
2343
2521
  * ```
2344
2522
  */