@prezly/theme-kit-core 10.10.0 → 10.11.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.
@@ -4,9 +4,38 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  var _exportNames = {
7
+ clearSharedMemoryCache: true,
8
+ configureSharedMemoryCache: true,
7
9
  createSharedMemoryCache: true,
10
+ DEFAULT_MAX_BYTES: true,
11
+ DEFAULT_MAX_RECORDS: true,
12
+ inspectSharedMemoryCache: true,
8
13
  createStackedCache: true
9
14
  };
15
+ Object.defineProperty(exports, "DEFAULT_MAX_BYTES", {
16
+ enumerable: true,
17
+ get: function get() {
18
+ return _memory.DEFAULT_MAX_BYTES;
19
+ }
20
+ });
21
+ Object.defineProperty(exports, "DEFAULT_MAX_RECORDS", {
22
+ enumerable: true,
23
+ get: function get() {
24
+ return _memory.DEFAULT_MAX_RECORDS;
25
+ }
26
+ });
27
+ Object.defineProperty(exports, "clearSharedMemoryCache", {
28
+ enumerable: true,
29
+ get: function get() {
30
+ return _memory.clearSharedMemoryCache;
31
+ }
32
+ });
33
+ Object.defineProperty(exports, "configureSharedMemoryCache", {
34
+ enumerable: true,
35
+ get: function get() {
36
+ return _memory.configureSharedMemoryCache;
37
+ }
38
+ });
10
39
  Object.defineProperty(exports, "createSharedMemoryCache", {
11
40
  enumerable: true,
12
41
  get: function get() {
@@ -19,6 +48,12 @@ Object.defineProperty(exports, "createStackedCache", {
19
48
  return _stacked.createStackedCache;
20
49
  }
21
50
  });
51
+ Object.defineProperty(exports, "inspectSharedMemoryCache", {
52
+ enumerable: true,
53
+ get: function get() {
54
+ return _memory.inspectSharedMemoryCache;
55
+ }
56
+ });
22
57
  var _type = require("./type.cjs");
23
58
  Object.keys(_type).forEach(function (key) {
24
59
  if (key === "default" || key === "__esModule") return;
@@ -1,3 +1,3 @@
1
1
  export * from './type';
2
- export { createSharedMemoryCache } from './memory';
2
+ export { clearSharedMemoryCache, configureSharedMemoryCache, createSharedMemoryCache, DEFAULT_MAX_BYTES, DEFAULT_MAX_RECORDS, inspectSharedMemoryCache, type MemoryCacheOptions, } from './memory';
3
3
  export { createStackedCache } from './stacked';
@@ -1,3 +1,3 @@
1
1
  export * from "./type.mjs";
2
- export { createSharedMemoryCache } from "./memory.mjs";
2
+ export { clearSharedMemoryCache, configureSharedMemoryCache, createSharedMemoryCache, DEFAULT_MAX_BYTES, DEFAULT_MAX_RECORDS, inspectSharedMemoryCache } from "./memory.mjs";
3
3
  export { createStackedCache } from "./stacked.mjs";
@@ -3,74 +3,147 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.RECORDS_LIMIT = void 0;
6
+ exports.RECORDS_LIMIT = exports.DEFAULT_MAX_RECORDS = exports.DEFAULT_MAX_BYTES = void 0;
7
+ exports.clearSharedMemoryCache = clearSharedMemoryCache;
8
+ exports.configureSharedMemoryCache = configureSharedMemoryCache;
7
9
  exports.createSharedMemoryCache = createSharedMemoryCache;
10
+ exports.inspectSharedMemoryCache = inspectSharedMemoryCache;
8
11
  var _telemetry = require("../telemetry.cjs");
9
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
10
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
11
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
12
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
13
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
14
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
15
- var RECORDS_LIMIT = exports.RECORDS_LIMIT = 10000;
16
- var GC_PROBABILITY = 1 / 100;
12
+ var DEFAULT_MAX_BYTES = exports.DEFAULT_MAX_BYTES = 128 * 1024 * 1024;
13
+ var DEFAULT_MAX_RECORDS = exports.DEFAULT_MAX_RECORDS = 20000;
14
+ /** @deprecated Use `DEFAULT_MAX_RECORDS`. */
15
+ var RECORDS_LIMIT = exports.RECORDS_LIMIT = DEFAULT_MAX_RECORDS;
16
+ /**
17
+ * One store per JavaScript runtime, shared by every namespace. `Map` keeps
18
+ * insertion order, so re-inserting an entry on read makes the first entry the
19
+ * least recently used one and eviction is a pop from the front: no sorting,
20
+ * no probability.
21
+ */
17
22
  var CACHE = new Map();
23
+ var totalBytes = 0;
24
+ var maxBytes = DEFAULT_MAX_BYTES;
25
+ var maxRecords = DEFAULT_MAX_RECORDS;
26
+
27
+ /** Sets the bounds of the shared store for the whole runtime. */
28
+ function configureSharedMemoryCache() {
29
+ var _options$maxBytes, _options$maxRecords;
30
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
31
+ for (var name of ['maxBytes', 'maxRecords']) {
32
+ var value = options[name];
33
+ if (value !== undefined && (!Number.isInteger(value) || value < 1)) {
34
+ throw new RangeError("The memory cache ".concat(name, " bound must be a positive integer."));
35
+ }
36
+ }
37
+ var nextMaxBytes = (_options$maxBytes = options.maxBytes) !== null && _options$maxBytes !== void 0 ? _options$maxBytes : DEFAULT_MAX_BYTES;
38
+ var nextMaxRecords = (_options$maxRecords = options.maxRecords) !== null && _options$maxRecords !== void 0 ? _options$maxRecords : DEFAULT_MAX_RECORDS;
39
+ if (nextMaxBytes === maxBytes && nextMaxRecords === maxRecords) return;
40
+ maxBytes = nextMaxBytes;
41
+ maxRecords = nextMaxRecords;
42
+ evict();
43
+ }
44
+
45
+ /** Empties the shared store. Intended for tests. */
46
+ function clearSharedMemoryCache() {
47
+ CACHE.clear();
48
+ totalBytes = 0;
49
+ }
50
+
51
+ /** Current occupancy of the shared store. */
52
+ function inspectSharedMemoryCache() {
53
+ return {
54
+ records: CACHE.size,
55
+ bytes: totalBytes,
56
+ maxBytes,
57
+ maxRecords
58
+ };
59
+ }
18
60
  function createSharedMemoryCache() {
19
61
  var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
62
+ var options = arguments.length > 1 ? arguments[1] : undefined;
63
+ if (options) configureSharedMemoryCache(options);
64
+ function read(key) {
65
+ var _entry$expires;
66
+ var fullKey = "".concat(prefix).concat(key);
67
+ var entry = CACHE.get(fullKey);
68
+ if (!entry) return undefined;
69
+ if (((_entry$expires = entry.expires) !== null && _entry$expires !== void 0 ? _entry$expires : Number.POSITIVE_INFINITY) <= Date.now()) {
70
+ remove(fullKey, entry);
71
+ return undefined;
72
+ }
73
+ // Most recently used entries live at the end of the map.
74
+ CACHE.delete(fullKey);
75
+ CACHE.set(fullKey, entry);
76
+ return entry;
77
+ }
78
+ function validate(key, latestVersion) {
79
+ var entry = read(key);
80
+ if (!entry) return undefined;
81
+ if (entry.version < latestVersion) {
82
+ remove("".concat(prefix).concat(key), entry);
83
+ return undefined;
84
+ }
85
+ return entry;
86
+ }
20
87
  return {
21
88
  get(key, latestVersion, onSource) {
22
- var _entry$expires;
23
- var entry = CACHE.get("".concat(prefix).concat(key));
24
- if (!entry) {
25
- return undefined;
26
- }
27
- if (entry.version < latestVersion || ((_entry$expires = entry.expires) !== null && _entry$expires !== void 0 ? _entry$expires : Number.POSITIVE_INFINITY) <= Date.now()) {
28
- CACHE.delete("".concat(prefix).concat(key));
29
- return undefined;
30
- }
31
- var value = entry.value,
32
- version = entry.version,
33
- expires = entry.expires;
34
- CACHE.set("".concat(prefix).concat(key), {
35
- value,
36
- version,
37
- expires,
38
- accessed: Date.now()
39
- });
40
- if (onSource && value !== undefined) (0, _telemetry.notify)(onSource, 'memory');
41
- return value;
89
+ var entry = validate(key, latestVersion);
90
+ if (!entry) return undefined;
91
+ if (onSource && entry.value !== undefined) (0, _telemetry.notify)(onSource, 'memory');
92
+ return entry.value;
93
+ },
94
+ lookup(key, latestVersion) {
95
+ var entry = validate(key, latestVersion);
96
+ if (!entry) return undefined;
97
+ return {
98
+ value: entry.value,
99
+ version: entry.version,
100
+ ttl: entry.expires === undefined ? undefined : Math.max(1, Math.ceil((entry.expires - Date.now()) / 1000)),
101
+ layer: 'memory'
102
+ };
42
103
  },
43
104
  set(key, value, version, options) {
105
+ var fullKey = "".concat(prefix).concat(key);
106
+ var previous = CACHE.get(fullKey);
107
+ // A late write (e.g. a refill that raced with a newer origin fetch)
108
+ // must not replace a newer entry with an older one.
109
+ if (previous && previous.version > version) return;
110
+ var bytes = estimateBytes(fullKey, value);
111
+ // One entry larger than the whole store would evict everything else
112
+ // and still not fit; skip it rather than flush every tenant.
113
+ if (bytes > maxBytes) return;
114
+ if (previous) remove(fullKey, previous);
44
115
  var entry = {
45
116
  value,
46
117
  version,
47
- accessed: Date.now(),
118
+ bytes,
48
119
  expires: (options === null || options === void 0 ? void 0 : options.ttl) === undefined ? undefined : Date.now() + options.ttl * 1000
49
120
  };
50
- CACHE.set("".concat(prefix).concat(key), entry);
51
- if (CACHE.size > RECORDS_LIMIT && Math.random() < GC_PROBABILITY) {
52
- gc();
53
- }
121
+ CACHE.set(fullKey, entry);
122
+ totalBytes += entry.bytes;
123
+ evict();
54
124
  },
55
125
  namespace(namespace) {
56
126
  return createSharedMemoryCache("".concat(prefix).concat(namespace, ":"));
57
127
  }
58
128
  };
59
129
  }
60
- function gc() {
61
- Array.from(CACHE.entries()).sort((_ref, _ref2) => {
62
- var _ref3 = _slicedToArray(_ref, 2),
63
- a = _ref3[1];
64
- var _ref4 = _slicedToArray(_ref2, 2),
65
- b = _ref4[1];
66
- return -cmp(a.accessed, b.accessed);
67
- }).slice(RECORDS_LIMIT).forEach(_ref5 => {
68
- var _ref6 = _slicedToArray(_ref5, 1),
69
- key = _ref6[0];
70
- CACHE.delete(key);
71
- });
130
+ function remove(fullKey, entry) {
131
+ if (CACHE.delete(fullKey)) totalBytes -= entry.bytes;
132
+ }
133
+
134
+ /** Drops least recently used entries until both bounds hold. */
135
+ function evict() {
136
+ while (CACHE.size > maxRecords || totalBytes > maxBytes) {
137
+ var oldest = CACHE.keys().next();
138
+ if (oldest.done) break;
139
+ remove(oldest.value, CACHE.get(oldest.value));
140
+ }
72
141
  }
73
- function cmp(a, b) {
74
- if (a === b) return 0;
75
- return a < b ? -1 : 1;
142
+ function estimateBytes(key, value) {
143
+ try {
144
+ var serialized = JSON.stringify(value);
145
+ return key.length + (serialized === undefined ? 0 : serialized.length);
146
+ } catch (_unused) {
147
+ return key.length;
148
+ }
76
149
  }
@@ -1,3 +1,23 @@
1
1
  import type { Cache } from './type';
2
- export declare const RECORDS_LIMIT = 10000;
3
- export declare function createSharedMemoryCache(prefix?: string): Cache;
2
+ export interface MemoryCacheOptions {
3
+ /** Upper bound on the estimated size of all stored values, in bytes. */
4
+ maxBytes?: number;
5
+ /** Upper bound on the number of stored entries. */
6
+ maxRecords?: number;
7
+ }
8
+ export declare const DEFAULT_MAX_BYTES: number;
9
+ export declare const DEFAULT_MAX_RECORDS = 20000;
10
+ /** @deprecated Use `DEFAULT_MAX_RECORDS`. */
11
+ export declare const RECORDS_LIMIT = 20000;
12
+ /** Sets the bounds of the shared store for the whole runtime. */
13
+ export declare function configureSharedMemoryCache(options?: MemoryCacheOptions): void;
14
+ /** Empties the shared store. Intended for tests. */
15
+ export declare function clearSharedMemoryCache(): void;
16
+ /** Current occupancy of the shared store. */
17
+ export declare function inspectSharedMemoryCache(): {
18
+ records: number;
19
+ bytes: number;
20
+ maxBytes: number;
21
+ maxRecords: number;
22
+ };
23
+ export declare function createSharedMemoryCache(prefix?: string, options?: MemoryCacheOptions): Cache;
@@ -1,69 +1,139 @@
1
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
1
  import { notify } from "../telemetry.mjs";
8
- export var RECORDS_LIMIT = 10000;
9
- var GC_PROBABILITY = 1 / 100;
2
+ export var DEFAULT_MAX_BYTES = 128 * 1024 * 1024;
3
+ export var DEFAULT_MAX_RECORDS = 20000;
4
+ /** @deprecated Use `DEFAULT_MAX_RECORDS`. */
5
+ export var RECORDS_LIMIT = DEFAULT_MAX_RECORDS;
6
+ /**
7
+ * One store per JavaScript runtime, shared by every namespace. `Map` keeps
8
+ * insertion order, so re-inserting an entry on read makes the first entry the
9
+ * least recently used one and eviction is a pop from the front: no sorting,
10
+ * no probability.
11
+ */
10
12
  var CACHE = new Map();
13
+ var totalBytes = 0;
14
+ var maxBytes = DEFAULT_MAX_BYTES;
15
+ var maxRecords = DEFAULT_MAX_RECORDS;
16
+
17
+ /** Sets the bounds of the shared store for the whole runtime. */
18
+ export function configureSharedMemoryCache() {
19
+ var _options$maxBytes, _options$maxRecords;
20
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
21
+ for (var name of ['maxBytes', 'maxRecords']) {
22
+ var value = options[name];
23
+ if (value !== undefined && (!Number.isInteger(value) || value < 1)) {
24
+ throw new RangeError("The memory cache ".concat(name, " bound must be a positive integer."));
25
+ }
26
+ }
27
+ var nextMaxBytes = (_options$maxBytes = options.maxBytes) !== null && _options$maxBytes !== void 0 ? _options$maxBytes : DEFAULT_MAX_BYTES;
28
+ var nextMaxRecords = (_options$maxRecords = options.maxRecords) !== null && _options$maxRecords !== void 0 ? _options$maxRecords : DEFAULT_MAX_RECORDS;
29
+ if (nextMaxBytes === maxBytes && nextMaxRecords === maxRecords) return;
30
+ maxBytes = nextMaxBytes;
31
+ maxRecords = nextMaxRecords;
32
+ evict();
33
+ }
34
+
35
+ /** Empties the shared store. Intended for tests. */
36
+ export function clearSharedMemoryCache() {
37
+ CACHE.clear();
38
+ totalBytes = 0;
39
+ }
40
+
41
+ /** Current occupancy of the shared store. */
42
+ export function inspectSharedMemoryCache() {
43
+ return {
44
+ records: CACHE.size,
45
+ bytes: totalBytes,
46
+ maxBytes,
47
+ maxRecords
48
+ };
49
+ }
11
50
  export function createSharedMemoryCache() {
12
51
  var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
52
+ var options = arguments.length > 1 ? arguments[1] : undefined;
53
+ if (options) configureSharedMemoryCache(options);
54
+ function read(key) {
55
+ var _entry$expires;
56
+ var fullKey = "".concat(prefix).concat(key);
57
+ var entry = CACHE.get(fullKey);
58
+ if (!entry) return undefined;
59
+ if (((_entry$expires = entry.expires) !== null && _entry$expires !== void 0 ? _entry$expires : Number.POSITIVE_INFINITY) <= Date.now()) {
60
+ remove(fullKey, entry);
61
+ return undefined;
62
+ }
63
+ // Most recently used entries live at the end of the map.
64
+ CACHE.delete(fullKey);
65
+ CACHE.set(fullKey, entry);
66
+ return entry;
67
+ }
68
+ function validate(key, latestVersion) {
69
+ var entry = read(key);
70
+ if (!entry) return undefined;
71
+ if (entry.version < latestVersion) {
72
+ remove("".concat(prefix).concat(key), entry);
73
+ return undefined;
74
+ }
75
+ return entry;
76
+ }
13
77
  return {
14
78
  get(key, latestVersion, onSource) {
15
- var _entry$expires;
16
- var entry = CACHE.get("".concat(prefix).concat(key));
17
- if (!entry) {
18
- return undefined;
19
- }
20
- if (entry.version < latestVersion || ((_entry$expires = entry.expires) !== null && _entry$expires !== void 0 ? _entry$expires : Number.POSITIVE_INFINITY) <= Date.now()) {
21
- CACHE.delete("".concat(prefix).concat(key));
22
- return undefined;
23
- }
24
- var value = entry.value,
25
- version = entry.version,
26
- expires = entry.expires;
27
- CACHE.set("".concat(prefix).concat(key), {
28
- value,
29
- version,
30
- expires,
31
- accessed: Date.now()
32
- });
33
- if (onSource && value !== undefined) notify(onSource, 'memory');
34
- return value;
79
+ var entry = validate(key, latestVersion);
80
+ if (!entry) return undefined;
81
+ if (onSource && entry.value !== undefined) notify(onSource, 'memory');
82
+ return entry.value;
83
+ },
84
+ lookup(key, latestVersion) {
85
+ var entry = validate(key, latestVersion);
86
+ if (!entry) return undefined;
87
+ return {
88
+ value: entry.value,
89
+ version: entry.version,
90
+ ttl: entry.expires === undefined ? undefined : Math.max(1, Math.ceil((entry.expires - Date.now()) / 1000)),
91
+ layer: 'memory'
92
+ };
35
93
  },
36
94
  set(key, value, version, options) {
95
+ var fullKey = "".concat(prefix).concat(key);
96
+ var previous = CACHE.get(fullKey);
97
+ // A late write (e.g. a refill that raced with a newer origin fetch)
98
+ // must not replace a newer entry with an older one.
99
+ if (previous && previous.version > version) return;
100
+ var bytes = estimateBytes(fullKey, value);
101
+ // One entry larger than the whole store would evict everything else
102
+ // and still not fit; skip it rather than flush every tenant.
103
+ if (bytes > maxBytes) return;
104
+ if (previous) remove(fullKey, previous);
37
105
  var entry = {
38
106
  value,
39
107
  version,
40
- accessed: Date.now(),
108
+ bytes,
41
109
  expires: (options === null || options === void 0 ? void 0 : options.ttl) === undefined ? undefined : Date.now() + options.ttl * 1000
42
110
  };
43
- CACHE.set("".concat(prefix).concat(key), entry);
44
- if (CACHE.size > RECORDS_LIMIT && Math.random() < GC_PROBABILITY) {
45
- gc();
46
- }
111
+ CACHE.set(fullKey, entry);
112
+ totalBytes += entry.bytes;
113
+ evict();
47
114
  },
48
115
  namespace(namespace) {
49
116
  return createSharedMemoryCache("".concat(prefix).concat(namespace, ":"));
50
117
  }
51
118
  };
52
119
  }
53
- function gc() {
54
- Array.from(CACHE.entries()).sort((_ref, _ref2) => {
55
- var _ref3 = _slicedToArray(_ref, 2),
56
- a = _ref3[1];
57
- var _ref4 = _slicedToArray(_ref2, 2),
58
- b = _ref4[1];
59
- return -cmp(a.accessed, b.accessed);
60
- }).slice(RECORDS_LIMIT).forEach(_ref5 => {
61
- var _ref6 = _slicedToArray(_ref5, 1),
62
- key = _ref6[0];
63
- CACHE.delete(key);
64
- });
120
+ function remove(fullKey, entry) {
121
+ if (CACHE.delete(fullKey)) totalBytes -= entry.bytes;
122
+ }
123
+
124
+ /** Drops least recently used entries until both bounds hold. */
125
+ function evict() {
126
+ while (CACHE.size > maxRecords || totalBytes > maxBytes) {
127
+ var oldest = CACHE.keys().next();
128
+ if (oldest.done) break;
129
+ remove(oldest.value, CACHE.get(oldest.value));
130
+ }
65
131
  }
66
- function cmp(a, b) {
67
- if (a === b) return 0;
68
- return a < b ? -1 : 1;
132
+ function estimateBytes(key, value) {
133
+ try {
134
+ var serialized = JSON.stringify(value);
135
+ return key.length + (serialized === undefined ? 0 : serialized.length);
136
+ } catch (_unused) {
137
+ return key.length;
138
+ }
69
139
  }
@@ -55,30 +55,112 @@ describe('createSharedMemoryCache', () => {
55
55
  expect(a.get('hello', 0)).toBe('world');
56
56
  expect(b.get('hello', 0)).toBe('universe');
57
57
  });
58
- it('should garbage-collect old cache records when threshold is reached (with a chance of 1/100)', () => {
59
- var cache = (0, _memory.createSharedMemoryCache)();
60
- for (var i = 0; i < _memory.RECORDS_LIMIT; i += 1) {
61
- cache.set("record-".concat(i), "value-".concat(i), 0);
62
- }
63
- for (var _i = 0; _i < _memory.RECORDS_LIMIT; _i += 1) {
64
- expect(cache.get("record-".concat(_i), 0)).toBe("value-".concat(_i));
65
- }
66
-
67
- // Write 10% more records, 10 times to trigger CG
68
- for (var repeat = 0; repeat < 100; repeat += 1) {
69
- for (var _i2 = _memory.RECORDS_LIMIT; _i2 < _memory.RECORDS_LIMIT * 1.1; _i2 += 1) {
70
- cache.set("record-".concat(_i2), "value-".concat(_i2), 0);
71
- }
58
+ it('evicts the least recently used entries once the record bound is reached', () => {
59
+ (0, _memory.clearSharedMemoryCache)();
60
+ (0, _memory.configureSharedMemoryCache)({
61
+ maxRecords: 3
62
+ });
63
+ try {
64
+ var cache = (0, _memory.createSharedMemoryCache)('lru:');
65
+ cache.set('a', 1, 0);
66
+ cache.set('b', 2, 0);
67
+ cache.set('c', 3, 0);
68
+ expect(cache.get('a', 0)).toBe(1); // a becomes most recently used
69
+ cache.set('d', 4, 0); // evicts b, the least recently used
70
+ expect(cache.get('b', 0)).toBeUndefined();
71
+ expect(cache.get('a', 0)).toBe(1);
72
+ expect(cache.get('c', 0)).toBe(3);
73
+ expect(cache.get('d', 0)).toBe(4);
74
+ expect((0, _memory.inspectSharedMemoryCache)().records).toBe(3);
75
+ } finally {
76
+ (0, _memory.configureSharedMemoryCache)();
77
+ (0, _memory.clearSharedMemoryCache)();
72
78
  }
73
-
74
- // the oldest part of the cache should be removed already
75
- for (var _i3 = 0; _i3 < _memory.RECORDS_LIMIT * 0.09; _i3 += 1) {
76
- expect(cache.get("record-".concat(_i3), 0)).toBeUndefined();
79
+ });
80
+ it('evicts by estimated bytes and accounts for overwrites and removals', () => {
81
+ (0, _memory.clearSharedMemoryCache)();
82
+ (0, _memory.configureSharedMemoryCache)({
83
+ maxBytes: 200
84
+ });
85
+ try {
86
+ var cache = (0, _memory.createSharedMemoryCache)('bytes:');
87
+ var big = 'x'.repeat(120);
88
+ cache.set('one', big, 0);
89
+ expect((0, _memory.inspectSharedMemoryCache)().bytes).toBeGreaterThan(120);
90
+ cache.set('two', big, 0); // two entries exceed 200 bytes: one is evicted
91
+ expect(cache.get('one', 0)).toBeUndefined();
92
+ expect(cache.get('two', 0)).toBe(big);
93
+ cache.set('two', 'tiny', 0); // overwrite releases the old size
94
+ expect((0, _memory.inspectSharedMemoryCache)().bytes).toBeLessThan(40);
95
+ expect(cache.get('two', 1)).toBeUndefined(); // version removal releases the rest
96
+ expect((0, _memory.inspectSharedMemoryCache)().bytes).toBe(0);
97
+ } finally {
98
+ (0, _memory.configureSharedMemoryCache)();
99
+ (0, _memory.clearSharedMemoryCache)();
77
100
  }
78
-
79
- // and the rest kept
80
- for (var _i4 = _memory.RECORDS_LIMIT * 0.11; _i4 < _memory.RECORDS_LIMIT * 1.1; _i4 += 1) {
81
- expect(cache.get("record-".concat(_i4), 0)).toBe("value-".concat(_i4));
101
+ });
102
+ it('keeps a newer entry when an older version is written late', () => {
103
+ var cache = (0, _memory.createSharedMemoryCache)('late:');
104
+ cache.set('key', 'new', 2);
105
+ cache.set('key', 'old', 1); // e.g. a refill that raced with an origin fetch
106
+ expect(cache.get('key', 2)).toBe('new');
107
+ cache.set('key', 'newer', 3);
108
+ expect(cache.get('key', 3)).toBe('newer');
109
+ });
110
+ it('skips an entry larger than the whole store instead of flushing it', () => {
111
+ (0, _memory.clearSharedMemoryCache)();
112
+ (0, _memory.configureSharedMemoryCache)({
113
+ maxBytes: 100
114
+ });
115
+ try {
116
+ var cache = (0, _memory.createSharedMemoryCache)('huge:');
117
+ cache.set('a', 'x'.repeat(30), 0);
118
+ cache.set('b', 'x'.repeat(30), 0);
119
+ cache.set('c', 'x'.repeat(500), 0);
120
+ expect(cache.get('c', 0)).toBeUndefined();
121
+ expect(cache.get('a', 0)).toBe('x'.repeat(30));
122
+ expect(cache.get('b', 0)).toBe('x'.repeat(30));
123
+ expect((0, _memory.inspectSharedMemoryCache)().records).toBe(2);
124
+ } finally {
125
+ (0, _memory.configureSharedMemoryCache)();
126
+ (0, _memory.clearSharedMemoryCache)();
82
127
  }
83
128
  });
129
+ it('rejects invalid bounds', () => {
130
+ expect(() => (0, _memory.configureSharedMemoryCache)({
131
+ maxRecords: 0
132
+ })).toThrow(RangeError);
133
+ expect(() => (0, _memory.configureSharedMemoryCache)({
134
+ maxBytes: 1.5
135
+ })).toThrow(RangeError);
136
+ (0, _memory.configureSharedMemoryCache)();
137
+ });
138
+ it('exposes version and remaining retention through lookup', () => {
139
+ var _cache$lookup, _cache$lookup2, _cache$lookup3, _cache$lookup4;
140
+ jest.useFakeTimers();
141
+ var cache = (0, _memory.createSharedMemoryCache)('lookup:');
142
+ cache.set('content', {
143
+ a: 1
144
+ }, 7);
145
+ cache.set('missing', null, 7, {
146
+ ttl: 30
147
+ });
148
+ expect((_cache$lookup = cache.lookup) === null || _cache$lookup === void 0 ? void 0 : _cache$lookup.call(cache, 'content', 7)).toEqual({
149
+ value: {
150
+ a: 1
151
+ },
152
+ version: 7,
153
+ ttl: undefined,
154
+ layer: 'memory'
155
+ });
156
+ jest.advanceTimersByTime(10000);
157
+ expect((_cache$lookup2 = cache.lookup) === null || _cache$lookup2 === void 0 ? void 0 : _cache$lookup2.call(cache, 'missing', 7)).toEqual({
158
+ value: null,
159
+ version: 7,
160
+ ttl: 20,
161
+ layer: 'memory'
162
+ });
163
+ expect((_cache$lookup3 = cache.lookup) === null || _cache$lookup3 === void 0 ? void 0 : _cache$lookup3.call(cache, 'content', 8)).toBeUndefined();
164
+ expect((_cache$lookup4 = cache.lookup) === null || _cache$lookup4 === void 0 ? void 0 : _cache$lookup4.call(cache, 'absent', 7)).toBeUndefined();
165
+ });
84
166
  });