@keq-request/cache 5.0.0-alpha.33 → 5.0.0-alpha.35

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.
Files changed (151) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/index.d.mts +354 -0
  3. package/dist/index.d.mts.map +1 -0
  4. package/dist/index.d.ts +352 -5
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1211 -1276
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +1183 -1251
  9. package/dist/index.mjs.map +1 -1
  10. package/package.json +9 -9
  11. package/tsdown.config.ts +12 -0
  12. package/dist/cache-entry/cache-entry.d.ts +0 -17
  13. package/dist/cache-entry/cache-entry.d.ts.map +0 -1
  14. package/dist/cache-entry/index.d.ts +0 -4
  15. package/dist/cache-entry/index.d.ts.map +0 -1
  16. package/dist/cache-entry/types/cache-entry-build-options.d.ts +0 -8
  17. package/dist/cache-entry/types/cache-entry-build-options.d.ts.map +0 -1
  18. package/dist/cache-entry/types/cache-entry-options.d.ts +0 -7
  19. package/dist/cache-entry/types/cache-entry-options.d.ts.map +0 -1
  20. package/dist/cache.d.ts +0 -44
  21. package/dist/cache.d.ts.map +0 -1
  22. package/dist/constants/eviction.enum.d.ts +0 -7
  23. package/dist/constants/eviction.enum.d.ts.map +0 -1
  24. package/dist/constants/index.d.ts +0 -5
  25. package/dist/constants/index.d.ts.map +0 -1
  26. package/dist/constants/max-expired-at.d.ts +0 -2
  27. package/dist/constants/max-expired-at.d.ts.map +0 -1
  28. package/dist/constants/size.enum.d.ts +0 -7
  29. package/dist/constants/size.enum.d.ts.map +0 -1
  30. package/dist/constants/strategy.enum.d.ts +0 -7
  31. package/dist/constants/strategy.enum.d.ts.map +0 -1
  32. package/dist/exceptions/cache-exception.d.ts +0 -5
  33. package/dist/exceptions/cache-exception.d.ts.map +0 -1
  34. package/dist/exceptions/index.d.ts +0 -2
  35. package/dist/exceptions/index.d.ts.map +0 -1
  36. package/dist/request-cache-handler/index.d.ts +0 -2
  37. package/dist/request-cache-handler/index.d.ts.map +0 -1
  38. package/dist/request-cache-handler/request-cache-handler.d.ts +0 -24
  39. package/dist/request-cache-handler/request-cache-handler.d.ts.map +0 -1
  40. package/dist/storage/index.d.ts +0 -6
  41. package/dist/storage/index.d.ts.map +0 -1
  42. package/dist/storage/indexed-db-storage/base-indexed-db-storage.d.ts +0 -22
  43. package/dist/storage/indexed-db-storage/base-indexed-db-storage.d.ts.map +0 -1
  44. package/dist/storage/indexed-db-storage/constants/default-table-name.d.ts +0 -2
  45. package/dist/storage/indexed-db-storage/constants/default-table-name.d.ts.map +0 -1
  46. package/dist/storage/indexed-db-storage/index.d.ts +0 -3
  47. package/dist/storage/indexed-db-storage/index.d.ts.map +0 -1
  48. package/dist/storage/indexed-db-storage/indexed-db-storage.d.ts +0 -12
  49. package/dist/storage/indexed-db-storage/indexed-db-storage.d.ts.map +0 -1
  50. package/dist/storage/indexed-db-storage/lfu-indexed-db-storage.d.ts +0 -11
  51. package/dist/storage/indexed-db-storage/lfu-indexed-db-storage.d.ts.map +0 -1
  52. package/dist/storage/indexed-db-storage/lru-indexed-db-storage.d.ts +0 -11
  53. package/dist/storage/indexed-db-storage/lru-indexed-db-storage.d.ts.map +0 -1
  54. package/dist/storage/indexed-db-storage/random-indexed-db-storage.d.ts +0 -11
  55. package/dist/storage/indexed-db-storage/random-indexed-db-storage.d.ts.map +0 -1
  56. package/dist/storage/indexed-db-storage/ttl-indexed-db-storage.d.ts +0 -11
  57. package/dist/storage/indexed-db-storage/ttl-indexed-db-storage.d.ts.map +0 -1
  58. package/dist/storage/indexed-db-storage/types/index.d.ts +0 -7
  59. package/dist/storage/indexed-db-storage/types/index.d.ts.map +0 -1
  60. package/dist/storage/indexed-db-storage/types/indexed-db-entry-metadata.d.ts +0 -12
  61. package/dist/storage/indexed-db-storage/types/indexed-db-entry-metadata.d.ts.map +0 -1
  62. package/dist/storage/indexed-db-storage/types/indexed-db-entry-response.d.ts +0 -8
  63. package/dist/storage/indexed-db-storage/types/indexed-db-entry-response.d.ts.map +0 -1
  64. package/dist/storage/indexed-db-storage/types/indexed-db-entry-visits.d.ts +0 -14
  65. package/dist/storage/indexed-db-storage/types/indexed-db-entry-visits.d.ts.map +0 -1
  66. package/dist/storage/indexed-db-storage/types/indexed-db-schema.d.ts +0 -29
  67. package/dist/storage/indexed-db-storage/types/indexed-db-schema.d.ts.map +0 -1
  68. package/dist/storage/indexed-db-storage/types/indexed-db-storage-options.d.ts +0 -14
  69. package/dist/storage/indexed-db-storage/types/indexed-db-storage-options.d.ts.map +0 -1
  70. package/dist/storage/indexed-db-storage/types/indexed-db-storage-size.d.ts +0 -13
  71. package/dist/storage/indexed-db-storage/types/indexed-db-storage-size.d.ts.map +0 -1
  72. package/dist/storage/internal-storage/internal-storage.d.ts +0 -16
  73. package/dist/storage/internal-storage/internal-storage.d.ts.map +0 -1
  74. package/dist/storage/internal-storage/types/events.d.ts +0 -16
  75. package/dist/storage/internal-storage/types/events.d.ts.map +0 -1
  76. package/dist/storage/internal-storage/types/storage-options.d.ts +0 -20
  77. package/dist/storage/internal-storage/types/storage-options.d.ts.map +0 -1
  78. package/dist/storage/keq-cache-storage.d.ts +0 -20
  79. package/dist/storage/keq-cache-storage.d.ts.map +0 -1
  80. package/dist/storage/memory-storage/base-memory-storage.d.ts +0 -31
  81. package/dist/storage/memory-storage/base-memory-storage.d.ts.map +0 -1
  82. package/dist/storage/memory-storage/index.d.ts +0 -3
  83. package/dist/storage/memory-storage/index.d.ts.map +0 -1
  84. package/dist/storage/memory-storage/lfu-memory-storage.d.ts +0 -11
  85. package/dist/storage/memory-storage/lfu-memory-storage.d.ts.map +0 -1
  86. package/dist/storage/memory-storage/lru-memory-storage.d.ts +0 -11
  87. package/dist/storage/memory-storage/lru-memory-storage.d.ts.map +0 -1
  88. package/dist/storage/memory-storage/memory-storage.d.ts +0 -13
  89. package/dist/storage/memory-storage/memory-storage.d.ts.map +0 -1
  90. package/dist/storage/memory-storage/random-memory-storage.d.ts +0 -11
  91. package/dist/storage/memory-storage/random-memory-storage.d.ts.map +0 -1
  92. package/dist/storage/memory-storage/ttl-memory-storage.d.ts +0 -11
  93. package/dist/storage/memory-storage/ttl-memory-storage.d.ts.map +0 -1
  94. package/dist/storage/memory-storage/types/index.d.ts +0 -3
  95. package/dist/storage/memory-storage/types/index.d.ts.map +0 -1
  96. package/dist/storage/memory-storage/types/memory-storage-options.d.ts +0 -9
  97. package/dist/storage/memory-storage/types/memory-storage-options.d.ts.map +0 -1
  98. package/dist/storage/memory-storage/types/memory-storage-size.d.ts +0 -13
  99. package/dist/storage/memory-storage/types/memory-storage-size.d.ts.map +0 -1
  100. package/dist/storage/memory-storage/utils/humanize-size.d.ts +0 -6
  101. package/dist/storage/memory-storage/utils/humanize-size.d.ts.map +0 -1
  102. package/dist/storage/memory-storage/utils/index.d.ts +0 -3
  103. package/dist/storage/memory-storage/utils/index.d.ts.map +0 -1
  104. package/dist/storage/memory-storage/utils/serialize-response-body.d.ts +0 -6
  105. package/dist/storage/memory-storage/utils/serialize-response-body.d.ts.map +0 -1
  106. package/dist/storage/multi-tier-storage/index.d.ts +0 -3
  107. package/dist/storage/multi-tier-storage/index.d.ts.map +0 -1
  108. package/dist/storage/multi-tier-storage/multi-tier-storage.d.ts +0 -36
  109. package/dist/storage/multi-tier-storage/multi-tier-storage.d.ts.map +0 -1
  110. package/dist/storage/multi-tier-storage/types/index.d.ts +0 -2
  111. package/dist/storage/multi-tier-storage/types/index.d.ts.map +0 -1
  112. package/dist/storage/multi-tier-storage/types/multi-tier-storage-options.d.ts +0 -5
  113. package/dist/storage/multi-tier-storage/types/multi-tier-storage-options.d.ts.map +0 -1
  114. package/dist/storage/tier-storage/index.d.ts +0 -3
  115. package/dist/storage/tier-storage/index.d.ts.map +0 -1
  116. package/dist/storage/tier-storage/tier-storage.d.ts +0 -15
  117. package/dist/storage/tier-storage/tier-storage.d.ts.map +0 -1
  118. package/dist/storage/tier-storage/types/index.d.ts +0 -2
  119. package/dist/storage/tier-storage/types/index.d.ts.map +0 -1
  120. package/dist/storage/tier-storage/types/tier-storage-options.d.ts +0 -21
  121. package/dist/storage/tier-storage/types/tier-storage-options.d.ts.map +0 -1
  122. package/dist/strategies/cache-first.d.ts +0 -3
  123. package/dist/strategies/cache-first.d.ts.map +0 -1
  124. package/dist/strategies/index.d.ts +0 -5
  125. package/dist/strategies/index.d.ts.map +0 -1
  126. package/dist/strategies/network-first.d.ts +0 -3
  127. package/dist/strategies/network-first.d.ts.map +0 -1
  128. package/dist/strategies/network-only.d.ts +0 -3
  129. package/dist/strategies/network-only.d.ts.map +0 -1
  130. package/dist/strategies/stale-while-revalidate.d.ts +0 -3
  131. package/dist/strategies/stale-while-revalidate.d.ts.map +0 -1
  132. package/dist/types/index.d.ts +0 -6
  133. package/dist/types/index.d.ts.map +0 -1
  134. package/dist/types/keq-cache-key.d.ts +0 -4
  135. package/dist/types/keq-cache-key.d.ts.map +0 -1
  136. package/dist/types/keq-cache-pattern.d.ts +0 -3
  137. package/dist/types/keq-cache-pattern.d.ts.map +0 -1
  138. package/dist/types/keq-cache-rule.d.ts +0 -6
  139. package/dist/types/keq-cache-rule.d.ts.map +0 -1
  140. package/dist/types/keq-cache-strategy.d.ts +0 -6
  141. package/dist/types/keq-cache-strategy.d.ts.map +0 -1
  142. package/dist/types/request-cache-options.d.ts +0 -45
  143. package/dist/types/request-cache-options.d.ts.map +0 -1
  144. package/dist/utils/get-response-bytes.d.ts +0 -2
  145. package/dist/utils/get-response-bytes.d.ts.map +0 -1
  146. package/dist/utils/index.d.ts +0 -4
  147. package/dist/utils/index.d.ts.map +0 -1
  148. package/dist/utils/logger.d.ts +0 -5
  149. package/dist/utils/logger.d.ts.map +0 -1
  150. package/dist/utils/random.d.ts +0 -2
  151. package/dist/utils/random.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,1336 +1,1271 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
9
  var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
20
18
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
31
-
32
- // src/index.ts
33
- var index_exports = {};
34
- __export(index_exports, {
35
- Eviction: () => Eviction,
36
- IndexedDBStorage: () => IndexedDBStorage,
37
- KeqCacheStorage: () => KeqCacheStorage,
38
- MemoryStorage: () => MemoryStorage,
39
- MultiTierStorage: () => MultiTierStorage,
40
- Size: () => Size,
41
- Strategy: () => Strategy,
42
- TierStorage: () => TierStorage,
43
- cache: () => cache
44
- });
45
- module.exports = __toCommonJS(index_exports);
46
-
47
- // src/cache.ts
48
- var R2 = __toESM(require("ramda"));
49
- var fastq = __toESM(require("fastq"));
50
-
51
- // src/request-cache-handler/request-cache-handler.ts
52
- var R = __toESM(require("ramda"));
53
-
54
- // src/exceptions/cache-exception.ts
55
- var import_keq = require("keq");
56
- var CacheException = class extends import_keq.Exception {
57
- constructor(message) {
58
- super("[@keq-request/cache] ".concat(message));
59
- }
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let ramda = require("ramda");
25
+ ramda = __toESM(ramda);
26
+ let fastq = require("fastq");
27
+ fastq = __toESM(fastq);
28
+ let keq = require("keq");
29
+ let dayjs = require("dayjs");
30
+ dayjs = __toESM(dayjs);
31
+ let idb = require("idb");
32
+ //#region src/exceptions/cache-exception.ts
33
+ var CacheException = class extends keq.Exception {
34
+ constructor(message) {
35
+ super(`[@keq-request/cache] ${message}`);
36
+ }
60
37
  };
61
-
62
- // src/cache-entry/cache-entry.ts
63
- var import_keq2 = require("keq");
64
-
65
- // src/utils/get-response-bytes.ts
38
+ //#endregion
39
+ //#region src/utils/get-response-bytes.ts
66
40
  async function getResponseBytes(response) {
67
- const contentLength = response.headers.get("content-length");
68
- if (contentLength) {
69
- return parseInt(contentLength);
70
- }
71
- const arrayBuffer = await response.clone().arrayBuffer();
72
- return arrayBuffer.byteLength;
41
+ const contentLength = response.headers.get("content-length");
42
+ if (contentLength) return parseInt(contentLength);
43
+ return (await response.clone().arrayBuffer()).byteLength;
73
44
  }
74
-
75
- // src/constants/max-expired-at.ts
76
- var MAX_EXPIRED_AT = /* @__PURE__ */ new Date(864e13);
77
-
78
- // src/constants/eviction.enum.ts
79
- var Eviction = /* @__PURE__ */ ((Eviction2) => {
80
- Eviction2["LRU"] = "lru";
81
- Eviction2["LFU"] = "lfu";
82
- Eviction2["RANDOM"] = "random";
83
- Eviction2["TTL"] = "ttl";
84
- return Eviction2;
85
- })(Eviction || {});
86
-
87
- // src/constants/size.enum.ts
88
- var Size = /* @__PURE__ */ ((Size2) => {
89
- Size2[Size2["B"] = 1] = "B";
90
- Size2[Size2["KB"] = 1024] = "KB";
91
- Size2[Size2["MB"] = 1048576] = "MB";
92
- Size2[Size2["GB"] = 1073741824] = "GB";
93
- return Size2;
94
- })(Size || {});
95
-
96
- // src/utils/logger.ts
45
+ //#endregion
46
+ //#region src/constants/max-expired-at.ts
47
+ const MAX_EXPIRED_AT = /* @__PURE__ */ new Date(864e13);
48
+ //#endregion
49
+ //#region src/constants/eviction.enum.ts
50
+ let Eviction = /* @__PURE__ */ function(Eviction) {
51
+ Eviction["LRU"] = "lru";
52
+ Eviction["LFU"] = "lfu";
53
+ Eviction["RANDOM"] = "random";
54
+ Eviction["TTL"] = "ttl";
55
+ return Eviction;
56
+ }({});
57
+ //#endregion
58
+ //#region src/constants/size.enum.ts
59
+ let Size = /* @__PURE__ */ function(Size) {
60
+ Size[Size["B"] = 1] = "B";
61
+ Size[Size["KB"] = 1024] = "KB";
62
+ Size[Size["MB"] = 1048576] = "MB";
63
+ Size[Size["GB"] = 1073741824] = "GB";
64
+ return Size;
65
+ }({});
66
+ //#endregion
67
+ //#region src/utils/logger.ts
97
68
  var Logger = class {
98
- static debug(...args) {
99
- console.debug("[@keq-request/cache] [DEBUG] ", ...args);
100
- }
101
- static error(...args) {
102
- console.error("[@keq-request/cache] [ERROR] ", ...args);
103
- }
69
+ static debug(...args) {
70
+ console.debug("[@keq-request/cache] [DEBUG] ", ...args);
71
+ }
72
+ static error(...args) {
73
+ console.error("[@keq-request/cache] [ERROR] ", ...args);
74
+ }
104
75
  };
105
-
106
- // src/utils/random.ts
76
+ //#endregion
77
+ //#region src/utils/random.ts
107
78
  function random(min, max) {
108
- return Math.floor(Math.random() * (max - min)) + min;
79
+ return Math.floor(Math.random() * (max - min)) + min;
109
80
  }
110
-
111
- // src/strategies/cache-first.ts
112
- var cacheFirst = async function cacheFirst2(handler, context, next) {
113
- const [cacheKey, cacheValue] = await handler.getCache();
114
- if (handler.options.debug) {
115
- Logger.debug([
116
- "",
117
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
118
- "Strategy: Cache First",
119
- "Cache Key: ".concat(cacheKey),
120
- "Cache Status: ".concat(cacheValue ? "HIT" : "MISS")
121
- ].join("\n"));
122
- }
123
- if (cacheValue) {
124
- context.emitter.emit("cache:hit", { key: cacheKey, response: cacheValue.response, context });
125
- context.res = cacheValue.response;
126
- return;
127
- }
128
- context.emitter.emit("cache:miss", { key: cacheKey, context });
129
- await next();
130
- const [, entry] = await handler.setCache(context);
131
- if (handler.options.debug) {
132
- Logger.debug([
133
- "",
134
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
135
- "Strategy: Cache First",
136
- "Cache Key: ".concat(cacheKey),
137
- "ACTIONS: ".concat(entry ? "UPDATED" : "EXCLUDED")
138
- ].join("\n"));
139
- }
140
- if (entry) {
141
- context.emitter.emit("cache:update", {
142
- key: entry.key,
143
- oldResponse: void 0,
144
- newResponse: entry.response,
145
- context
146
- });
147
- }
81
+ //#endregion
82
+ //#region src/strategies/cache-first.ts
83
+ const cacheFirst = async function cacheFirst(handler, context, next) {
84
+ const [cacheKey, cacheValue] = await handler.getCache();
85
+ if (handler.options.debug) Logger.debug([
86
+ "",
87
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
88
+ "Strategy: Cache First",
89
+ `Cache Key: ${cacheKey}`,
90
+ `Cache Status: ${cacheValue ? "HIT" : "MISS"}`
91
+ ].join("\n"));
92
+ if (cacheValue) {
93
+ context.emitter.emit("cache:hit", {
94
+ key: cacheKey,
95
+ response: cacheValue.response,
96
+ context
97
+ });
98
+ context.res = cacheValue.response;
99
+ return;
100
+ }
101
+ context.emitter.emit("cache:miss", {
102
+ key: cacheKey,
103
+ context
104
+ });
105
+ await next();
106
+ const [, entry] = await handler.setCache(context);
107
+ if (handler.options.debug) Logger.debug([
108
+ "",
109
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
110
+ "Strategy: Cache First",
111
+ `Cache Key: ${cacheKey}`,
112
+ `ACTIONS: ${entry ? "UPDATED" : "EXCLUDED"}`
113
+ ].join("\n"));
114
+ if (entry) context.emitter.emit("cache:update", {
115
+ key: entry.key,
116
+ oldResponse: void 0,
117
+ newResponse: entry.response,
118
+ context
119
+ });
148
120
  };
149
-
150
- // src/strategies/network-first.ts
151
- var networkFirst = async function networkFirst2(handler, context, next) {
152
- try {
153
- await next();
154
- const [cacheKey, cache2] = await handler.getCache();
155
- const [, entry] = await handler.setCache(context);
156
- if (handler.options.debug) {
157
- Logger.debug([
158
- "",
159
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
160
- "Strategy: Network First",
161
- "Cache Key: ".concat(cacheKey),
162
- "ACTIONS: ".concat(entry ? "UPDATED" : "EXCLUDED")
163
- ].join("\n"));
164
- }
165
- if (entry) {
166
- context.emitter.emit("cache:update", {
167
- key: entry.key,
168
- oldResponse: cache2 == null ? void 0 : cache2.response,
169
- newResponse: entry.response,
170
- context
171
- });
172
- }
173
- } catch (err) {
174
- const [cacheKey, cache2] = await handler.getCache();
175
- if (handler.options.debug) {
176
- Logger.debug([
177
- "",
178
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
179
- "Strategy: Network First",
180
- "Cache Key: ".concat(cacheKey),
181
- "Cache Status: ".concat(cache2 ? "HIT" : "MISS")
182
- ].join("\n"));
183
- }
184
- if (!cache2) {
185
- context.emitter.emit("cache:miss", { key: cacheKey, context });
186
- throw err;
187
- }
188
- context.emitter.emit("cache:hit", { key: cacheKey, response: cache2.response, context });
189
- context.res = cache2.response;
190
- }
121
+ //#endregion
122
+ //#region src/strategies/network-first.ts
123
+ const networkFirst = async function networkFirst(handler, context, next) {
124
+ try {
125
+ await next();
126
+ const [cacheKey, cache] = await handler.getCache();
127
+ const [, entry] = await handler.setCache(context);
128
+ if (handler.options.debug) Logger.debug([
129
+ "",
130
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
131
+ "Strategy: Network First",
132
+ `Cache Key: ${cacheKey}`,
133
+ `ACTIONS: ${entry ? "UPDATED" : "EXCLUDED"}`
134
+ ].join("\n"));
135
+ if (entry) context.emitter.emit("cache:update", {
136
+ key: entry.key,
137
+ oldResponse: cache?.response,
138
+ newResponse: entry.response,
139
+ context
140
+ });
141
+ } catch (err) {
142
+ const [cacheKey, cache] = await handler.getCache();
143
+ if (handler.options.debug) Logger.debug([
144
+ "",
145
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
146
+ "Strategy: Network First",
147
+ `Cache Key: ${cacheKey}`,
148
+ `Cache Status: ${cache ? "HIT" : "MISS"}`
149
+ ].join("\n"));
150
+ if (!cache) {
151
+ context.emitter.emit("cache:miss", {
152
+ key: cacheKey,
153
+ context
154
+ });
155
+ throw err;
156
+ }
157
+ context.emitter.emit("cache:hit", {
158
+ key: cacheKey,
159
+ response: cache.response,
160
+ context
161
+ });
162
+ context.res = cache.response;
163
+ }
191
164
  };
192
-
193
- // src/strategies/network-only.ts
194
- var networkOnly = async function(handler, context, next) {
195
- await next();
165
+ //#endregion
166
+ //#region src/strategies/network-only.ts
167
+ const networkOnly = async function(handler, context, next) {
168
+ await next();
196
169
  };
197
-
198
- // src/strategies/stale-while-revalidate.ts
199
- var staleWhileRevalidate = async function(handler, context, next) {
200
- const [cacheKey, cache2] = await handler.getCache();
201
- if (handler.options.debug) {
202
- Logger.debug([
203
- "",
204
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
205
- "Strategy: Stale While Revalidate",
206
- "Cache Key: ".concat(cacheKey),
207
- "Cache Status: ".concat(cache2 ? "HIT" : "MISS")
208
- ].join("\n"));
209
- }
210
- if (cache2) {
211
- context.emitter.emit("cache:hit", { key: cacheKey, response: cache2.response, context });
212
- } else {
213
- context.emitter.emit("cache:miss", { key: cacheKey, context });
214
- }
215
- if (cache2) {
216
- const orchestrator = context.orchestration.fork();
217
- context.res = cache2.response;
218
- setTimeout(async () => {
219
- try {
220
- await orchestrator.execute();
221
- const context2 = orchestrator.context;
222
- const [cacheKey2, entry] = await handler.setCache(context2);
223
- if (handler.options.debug) {
224
- Logger.debug([
225
- "",
226
- "Request: ".concat(context2.request.method.toUpperCase(), " ").concat(context2.request.__url__.href),
227
- "Strategy: Stale While Revalidate",
228
- "Cache Key: ".concat(cacheKey2),
229
- "ACTIONS: ".concat(entry ? "UPDATED" : "EXCLUDED")
230
- ].join("\n"));
231
- }
232
- if (entry) {
233
- context2.emitter.emit("cache:update", {
234
- key: cacheKey2,
235
- oldResponse: cache2.response,
236
- newResponse: entry.response,
237
- context: context2
238
- });
239
- }
240
- } catch (err) {
241
- }
242
- }, 1);
243
- } else {
244
- await next();
245
- const [cacheKey2, entry] = await handler.setCache(context);
246
- if (handler.options.debug) {
247
- Logger.debug([
248
- "",
249
- "Request: ".concat(context.request.method.toUpperCase(), " ").concat(context.request.__url__.href),
250
- "Strategy: Stale While Revalidate",
251
- "Cache Key: ".concat(cacheKey2),
252
- "ACTIONS: ".concat(entry ? "UPDATED" : "EXCLUDED")
253
- ].join("\n"));
254
- }
255
- if (entry) {
256
- context.emitter.emit("cache:update", {
257
- key: cacheKey2,
258
- oldResponse: void 0,
259
- newResponse: entry.response,
260
- context
261
- });
262
- }
263
- }
170
+ //#endregion
171
+ //#region src/strategies/stale-while-revalidate.ts
172
+ const staleWhileRevalidate = async function(handler, context, next) {
173
+ const [cacheKey, cache] = await handler.getCache();
174
+ if (handler.options.debug) Logger.debug([
175
+ "",
176
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
177
+ "Strategy: Stale While Revalidate",
178
+ `Cache Key: ${cacheKey}`,
179
+ `Cache Status: ${cache ? "HIT" : "MISS"}`
180
+ ].join("\n"));
181
+ if (cache) context.emitter.emit("cache:hit", {
182
+ key: cacheKey,
183
+ response: cache.response,
184
+ context
185
+ });
186
+ else context.emitter.emit("cache:miss", {
187
+ key: cacheKey,
188
+ context
189
+ });
190
+ if (cache) {
191
+ const orchestrator = context.orchestration.fork();
192
+ context.res = cache.response;
193
+ setTimeout(async () => {
194
+ try {
195
+ await orchestrator.execute();
196
+ const context = orchestrator.context;
197
+ const [cacheKey, entry] = await handler.setCache(context);
198
+ if (handler.options.debug) Logger.debug([
199
+ "",
200
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
201
+ "Strategy: Stale While Revalidate",
202
+ `Cache Key: ${cacheKey}`,
203
+ `ACTIONS: ${entry ? "UPDATED" : "EXCLUDED"}`
204
+ ].join("\n"));
205
+ if (entry) context.emitter.emit("cache:update", {
206
+ key: cacheKey,
207
+ oldResponse: cache.response,
208
+ newResponse: entry.response,
209
+ context
210
+ });
211
+ } catch (err) {}
212
+ }, 1);
213
+ } else {
214
+ await next();
215
+ const [cacheKey, entry] = await handler.setCache(context);
216
+ if (handler.options.debug) Logger.debug([
217
+ "",
218
+ `Request: ${context.request.method.toUpperCase()} ${context.request.__url__.href}`,
219
+ "Strategy: Stale While Revalidate",
220
+ `Cache Key: ${cacheKey}`,
221
+ `ACTIONS: ${entry ? "UPDATED" : "EXCLUDED"}`
222
+ ].join("\n"));
223
+ if (entry) context.emitter.emit("cache:update", {
224
+ key: cacheKey,
225
+ oldResponse: void 0,
226
+ newResponse: entry.response,
227
+ context
228
+ });
229
+ }
264
230
  };
265
-
266
- // src/constants/strategy.enum.ts
267
- var Strategy = {
268
- STALE_WHILE_REVALIDATE: staleWhileRevalidate,
269
- NETWORK_FIRST: networkFirst,
270
- NETWORK_ONLY: networkOnly,
271
- CACHE_FIRST: cacheFirst
231
+ //#endregion
232
+ //#region src/constants/strategy.enum.ts
233
+ const Strategy = {
234
+ STALE_WHILE_REVALIDATE: staleWhileRevalidate,
235
+ NETWORK_FIRST: networkFirst,
236
+ NETWORK_ONLY: networkOnly,
237
+ CACHE_FIRST: cacheFirst
272
238
  };
273
-
274
- // src/cache-entry/cache-entry.ts
275
- var CacheEntry = class _CacheEntry {
276
- constructor(options) {
277
- __publicField(this, "key");
278
- __publicField(this, "response");
279
- /**
280
- * @en bytes
281
- * @zh 字节数
282
- */
283
- __publicField(this, "size");
284
- __publicField(this, "expiredAt");
285
- var _a;
286
- this.key = options.key;
287
- this.response = (0, import_keq2.createProxyResponse)(options.response);
288
- this.size = options.size;
289
- this.expiredAt = (_a = options.expiredAt) != null ? _a : MAX_EXPIRED_AT;
290
- }
291
- static async build(options) {
292
- var _a;
293
- const expiredAt = "expiredAt" in options ? options.expiredAt : "ttl" in options && typeof options.ttl === "number" && options.ttl > 0 ? new Date(Date.now() + options.ttl * 1e3) : MAX_EXPIRED_AT;
294
- const response = options.response.clone();
295
- return new _CacheEntry({
296
- key: options.key,
297
- response,
298
- size: (_a = options.size) != null ? _a : await getResponseBytes(response),
299
- expiredAt
300
- });
301
- }
302
- clone() {
303
- return new _CacheEntry({
304
- key: this.key,
305
- response: this.response.clone(),
306
- size: this.size,
307
- expiredAt: this.expiredAt
308
- });
309
- }
310
- assignResponseHeaders(headers) {
311
- this.response = new Response(this.response.body, {
312
- status: this.response.status,
313
- statusText: this.response.statusText,
314
- headers
315
- });
316
- }
239
+ //#endregion
240
+ //#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
241
+ function _typeof(o) {
242
+ "@babel/helpers - typeof";
243
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
244
+ return typeof o;
245
+ } : function(o) {
246
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
247
+ }, _typeof(o);
248
+ }
249
+ //#endregion
250
+ //#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
251
+ function toPrimitive(t, r) {
252
+ if ("object" != _typeof(t) || !t) return t;
253
+ var e = t[Symbol.toPrimitive];
254
+ if (void 0 !== e) {
255
+ var i = e.call(t, r || "default");
256
+ if ("object" != _typeof(i)) return i;
257
+ throw new TypeError("@@toPrimitive must return a primitive value.");
258
+ }
259
+ return ("string" === r ? String : Number)(t);
260
+ }
261
+ //#endregion
262
+ //#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
263
+ function toPropertyKey(t) {
264
+ var i = toPrimitive(t, "string");
265
+ return "symbol" == _typeof(i) ? i : i + "";
266
+ }
267
+ //#endregion
268
+ //#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
269
+ function _defineProperty(e, r, t) {
270
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
271
+ value: t,
272
+ enumerable: !0,
273
+ configurable: !0,
274
+ writable: !0
275
+ }) : e[r] = t, e;
276
+ }
277
+ //#endregion
278
+ //#region src/cache-entry/cache-entry.ts
279
+ var CacheEntry = class CacheEntry {
280
+ constructor(options) {
281
+ _defineProperty(this, "key", void 0);
282
+ _defineProperty(this, "response", void 0);
283
+ _defineProperty(
284
+ this,
285
+ /**
286
+ * @en bytes
287
+ * @zh 字节数
288
+ */
289
+ "size",
290
+ void 0
291
+ );
292
+ _defineProperty(this, "expiredAt", void 0);
293
+ this.key = options.key;
294
+ this.response = (0, keq.createProxyResponse)(options.response);
295
+ this.size = options.size;
296
+ this.expiredAt = options.expiredAt ?? MAX_EXPIRED_AT;
297
+ }
298
+ static async build(options) {
299
+ const expiredAt = "expiredAt" in options ? options.expiredAt : "ttl" in options && typeof options.ttl === "number" && options.ttl > 0 ? new Date(Date.now() + options.ttl * 1e3) : MAX_EXPIRED_AT;
300
+ const response = options.response.clone();
301
+ return new CacheEntry({
302
+ key: options.key,
303
+ response,
304
+ size: options.size ?? await getResponseBytes(response),
305
+ expiredAt
306
+ });
307
+ }
308
+ clone() {
309
+ return new CacheEntry({
310
+ key: this.key,
311
+ response: this.response.clone(),
312
+ size: this.size,
313
+ expiredAt: this.expiredAt
314
+ });
315
+ }
316
+ assignResponseHeaders(headers) {
317
+ this.response = new Response(this.response.body, {
318
+ status: this.response.status,
319
+ statusText: this.response.statusText,
320
+ headers
321
+ });
322
+ }
317
323
  };
318
-
319
- // src/request-cache-handler/request-cache-handler.ts
324
+ //#endregion
325
+ //#region src/request-cache-handler/request-cache-handler.ts
320
326
  var RequestCacheHandler = class {
321
- constructor(cacheKey, storage, options) {
322
- this.cacheKey = cacheKey;
323
- this.storage = storage;
324
- this.options = options;
325
- }
326
- /**
327
- * Resolve cache key for request context
328
- */
329
- static resolveRequestCacheKey(context, options) {
330
- if (typeof options.key === "string") return options.key;
331
- else if (typeof options.key === "function") return options.key(context);
332
- else if (R.isNil(options.key) && context.locationId) return context.locationId;
333
- else throw new CacheException("Cannot resolve cache key");
334
- }
335
- /**
336
- * Get cache from storage
337
- */
338
- async getCache() {
339
- const key = this.cacheKey;
340
- if (this.options.serverTiming) {
341
- const startAt = /* @__PURE__ */ new Date();
342
- const entry = await this.storage.get(key);
343
- if (entry) {
344
- const dur = (/* @__PURE__ */ new Date()).getTime() - startAt.getTime();
345
- const HeadersWithServerTiming = new Headers(entry.response.headers);
346
- HeadersWithServerTiming.set("Server-Timing", "keq-cache; dur=".concat(dur, '; desc="HIT"'));
347
- entry.assignResponseHeaders(HeadersWithServerTiming);
348
- }
349
- return [key, entry];
350
- }
351
- return [key, await this.storage.get(key)];
352
- }
353
- /**
354
- * Store response that in context to storage
355
- */
356
- async setCache(context) {
357
- const options = this.options;
358
- const key = this.cacheKey;
359
- if (!context.response) return [key, void 0];
360
- if (options.exclude && await options.exclude(context.response)) return [key, void 0];
361
- const entry = await CacheEntry.build({
362
- key,
363
- response: context.response,
364
- ttl: options.ttl
365
- });
366
- void this.storage.set(entry);
367
- return [key, entry];
368
- }
327
+ constructor(cacheKey, storage, options) {
328
+ this.cacheKey = cacheKey;
329
+ this.storage = storage;
330
+ this.options = options;
331
+ }
332
+ /**
333
+ * Resolve cache key for request context
334
+ */
335
+ static resolveRequestCacheKey(context, options) {
336
+ if (typeof options.key === "string") return options.key;
337
+ else if (typeof options.key === "function") return options.key(context);
338
+ else if (ramda.isNil(options.key) && context.locationId) return context.locationId;
339
+ else throw new CacheException("Cannot resolve cache key");
340
+ }
341
+ /**
342
+ * Get cache from storage
343
+ */
344
+ async getCache() {
345
+ const key = this.cacheKey;
346
+ if (this.options.serverTiming) {
347
+ const startAt = /* @__PURE__ */ new Date();
348
+ const entry = await this.storage.get(key);
349
+ if (entry) {
350
+ const dur = (/* @__PURE__ */ new Date()).getTime() - startAt.getTime();
351
+ const HeadersWithServerTiming = new Headers(entry.response.headers);
352
+ HeadersWithServerTiming.set("Server-Timing", `keq-cache; dur=${dur}; desc="HIT"`);
353
+ entry.assignResponseHeaders(HeadersWithServerTiming);
354
+ }
355
+ return [key, entry];
356
+ }
357
+ return [key, await this.storage.get(key)];
358
+ }
359
+ /**
360
+ * Store response that in context to storage
361
+ */
362
+ async setCache(context) {
363
+ const options = this.options;
364
+ const key = this.cacheKey;
365
+ if (!context.response) return [key, void 0];
366
+ if (options.exclude && await options.exclude(context.response)) return [key, void 0];
367
+ const entry = await CacheEntry.build({
368
+ key,
369
+ response: context.response,
370
+ ttl: options.ttl
371
+ });
372
+ this.storage.set(entry);
373
+ return [key, entry];
374
+ }
369
375
  };
370
-
371
- // src/cache.ts
376
+ //#endregion
377
+ //#region src/cache.ts
372
378
  function cache(options) {
373
- const storage = options.storage;
374
- const rules = (options == null ? void 0 : options.rules) || [];
375
- return async function cache2(ctx, next) {
376
- if (ctx.options.cache === false) {
377
- await next();
378
- return;
379
- }
380
- let requestCacheOptions = ctx.options.cache;
381
- const rule = rules.find((rule2) => {
382
- if (rule2.pattern === void 0 || rule2.pattern === true) return true;
383
- if (typeof rule2.pattern === "function") return rule2.pattern(ctx);
384
- return rule2.pattern.test(ctx.request.__url__.href);
385
- });
386
- if (rule) requestCacheOptions = R2.mergeRight(rule, requestCacheOptions || {});
387
- if (!requestCacheOptions || R2.isEmpty(requestCacheOptions)) {
388
- await next();
389
- return;
390
- }
391
- if (!requestCacheOptions.key) requestCacheOptions.key = options.keyFactory;
392
- if (!ctx.locationId && !requestCacheOptions.key) {
393
- console.warn("[@keq/cache] Warning: Cannot resolve Cache Key. Cache is skipped.");
394
- await next();
395
- return;
396
- }
397
- if (requestCacheOptions.serverTiming === void 0 && options.serverTiming !== void 0) {
398
- requestCacheOptions.serverTiming = options.serverTiming;
399
- }
400
- const cacheKey = RequestCacheHandler.resolveRequestCacheKey(ctx, requestCacheOptions);
401
- const handler = new RequestCacheHandler(cacheKey, storage, requestCacheOptions);
402
- const strategy = requestCacheOptions.strategy;
403
- if (requestCacheOptions.concurrent) {
404
- await strategy(handler, ctx, next);
405
- } else {
406
- if (!ctx.global.core) ctx.global.core = {};
407
- if (!ctx.global.core.cache) ctx.global.core.cache = {};
408
- if (!ctx.global.core.cache[cacheKey]) {
409
- ctx.global.core.cache[cacheKey] = fastq.promise(async ({ next: next2 }) => {
410
- await next2();
411
- }, 1);
412
- }
413
- const queue = ctx.global.core.cache[cacheKey];
414
- await queue.push({
415
- next: async () => {
416
- await strategy(handler, ctx, next);
417
- }
418
- });
419
- }
420
- };
379
+ const storage = options.storage;
380
+ const rules = options?.rules || [];
381
+ return async function cache(ctx, next) {
382
+ if (ctx.options.cache === false) {
383
+ await next();
384
+ return;
385
+ }
386
+ let requestCacheOptions = ctx.options.cache;
387
+ const rule = rules.find((rule) => {
388
+ if (rule.pattern === void 0 || rule.pattern === true) return true;
389
+ if (typeof rule.pattern === "function") return rule.pattern(ctx);
390
+ return rule.pattern.test(ctx.request.__url__.href);
391
+ });
392
+ if (rule) requestCacheOptions = ramda.mergeRight(rule, requestCacheOptions || {});
393
+ if (!requestCacheOptions || ramda.isEmpty(requestCacheOptions)) {
394
+ await next();
395
+ return;
396
+ }
397
+ if (!requestCacheOptions.key) requestCacheOptions.key = options.keyFactory;
398
+ if (!ctx.locationId && !requestCacheOptions.key) {
399
+ console.warn("[@keq/cache] Warning: Cannot resolve Cache Key. Cache is skipped.");
400
+ await next();
401
+ return;
402
+ }
403
+ if (requestCacheOptions.serverTiming === void 0 && options.serverTiming !== void 0) requestCacheOptions.serverTiming = options.serverTiming;
404
+ const cacheKey = RequestCacheHandler.resolveRequestCacheKey(ctx, requestCacheOptions);
405
+ const handler = new RequestCacheHandler(cacheKey, storage, requestCacheOptions);
406
+ const strategy = requestCacheOptions.strategy;
407
+ if (requestCacheOptions.concurrent) await strategy(handler, ctx, next);
408
+ else {
409
+ if (!ctx.global.core) ctx.global.core = {};
410
+ if (!ctx.global.core.cache) ctx.global.core.cache = {};
411
+ if (!ctx.global.core.cache[cacheKey]) ctx.global.core.cache[cacheKey] = fastq.promise(async ({ next }) => {
412
+ await next();
413
+ }, 1);
414
+ await ctx.global.core.cache[cacheKey].push({ next: async () => {
415
+ await strategy(handler, ctx, next);
416
+ } });
417
+ }
418
+ };
421
419
  }
422
-
423
- // src/storage/memory-storage/ttl-memory-storage.ts
424
- var import_dayjs2 = __toESM(require("dayjs"));
425
- var R4 = __toESM(require("ramda"));
426
-
427
- // src/storage/memory-storage/base-memory-storage.ts
428
- var import_dayjs = __toESM(require("dayjs"));
429
- var R3 = __toESM(require("ramda"));
430
-
431
- // src/storage/keq-cache-storage.ts
432
- var KeqCacheStorage = class {
433
- };
434
-
435
- // src/storage/internal-storage/internal-storage.ts
420
+ //#endregion
421
+ //#region src/storage/keq-cache-storage.ts
422
+ var KeqCacheStorage = class {};
423
+ //#endregion
424
+ //#region src/storage/internal-storage/internal-storage.ts
436
425
  var InternalStorage = class extends KeqCacheStorage {
437
- constructor(options) {
438
- var _a;
439
- super();
440
- __publicField(this, "__id__", Math.random().toString(36).slice(2));
441
- __publicField(this, "__size__");
442
- __publicField(this, "__debug__");
443
- __publicField(this, "__onCacheGet__");
444
- __publicField(this, "__onCacheSet__");
445
- __publicField(this, "__onCacheRemove__");
446
- __publicField(this, "__onCacheEvict__");
447
- __publicField(this, "__onCacheExpired__");
448
- if ((options == null ? void 0 : options.size) && (typeof (options == null ? void 0 : options.size) !== "number" || options.size <= 0)) {
449
- throw new CacheException("Invalid size: ".concat(String(options == null ? void 0 : options.size)));
450
- }
451
- this.__size__ = (_a = options == null ? void 0 : options.size) != null ? _a : Infinity;
452
- this.__debug__ = !!(options == null ? void 0 : options.debug);
453
- this.__onCacheGet__ = options == null ? void 0 : options.onCacheGet;
454
- this.__onCacheSet__ = options == null ? void 0 : options.onCacheSet;
455
- this.__onCacheRemove__ = options == null ? void 0 : options.onCacheRemove;
456
- this.__onCacheEvict__ = options == null ? void 0 : options.onCacheEvict;
457
- this.debug((log) => log("Storage Created: ", this));
458
- }
459
- debug(fn) {
460
- if (this.__debug__) {
461
- fn((...args) => {
462
- Logger.debug("[Storage(".concat(this.__id__, ")]"), ...args);
463
- });
464
- }
465
- }
426
+ constructor(options) {
427
+ super();
428
+ _defineProperty(this, "__id__", Math.random().toString(36).slice(2));
429
+ _defineProperty(this, "__size__", void 0);
430
+ _defineProperty(this, "__debug__", void 0);
431
+ _defineProperty(this, "__onCacheGet__", void 0);
432
+ _defineProperty(this, "__onCacheSet__", void 0);
433
+ _defineProperty(this, "__onCacheRemove__", void 0);
434
+ _defineProperty(this, "__onCacheEvict__", void 0);
435
+ _defineProperty(this, "__onCacheExpired__", void 0);
436
+ if (options?.size && (typeof options?.size !== "number" || options.size <= 0)) throw new CacheException(`Invalid size: ${String(options?.size)}`);
437
+ this.__size__ = options?.size ?? Infinity;
438
+ this.__debug__ = !!options?.debug;
439
+ this.__onCacheGet__ = options?.onCacheGet;
440
+ this.__onCacheSet__ = options?.onCacheSet;
441
+ this.__onCacheRemove__ = options?.onCacheRemove;
442
+ this.__onCacheEvict__ = options?.onCacheEvict;
443
+ this.debug((log) => log("Storage Created: ", this));
444
+ }
445
+ debug(fn) {
446
+ if (this.__debug__) fn((...args) => {
447
+ Logger.debug(`[Storage(${this.__id__})]`, ...args);
448
+ });
449
+ }
466
450
  };
467
-
468
- // src/storage/memory-storage/utils/humanize-size.ts
451
+ //#endregion
452
+ //#region src/storage/memory-storage/utils/humanize-size.ts
453
+ /**
454
+ * @en Humanize size in bytes to KB, MB, GB
455
+ * @zh 将字节数转换为 KB、MB、GB 等易读格式
456
+ */
469
457
  function humanizeSize(size) {
470
- if (size < 1024) return "".concat(size, " B");
471
- if (size < 1024 * 1024) return "".concat((size / 1024).toFixed(2), " KB");
472
- if (size < 1024 * 1024 * 1024) return "".concat((size / (1024 * 1024)).toFixed(2), " MB");
473
- return "".concat((size / (1024 * 1024 * 1024)).toFixed(2), " GB");
458
+ if (size < 1024) return `${size} B`;
459
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
460
+ if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
461
+ return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
474
462
  }
475
-
476
- // src/storage/memory-storage/utils/serialize-response-body.ts
463
+ //#endregion
464
+ //#region src/storage/memory-storage/utils/serialize-response-body.ts
465
+ /**
466
+ * @en Serialize the response body based on content-type
467
+ * @zh 根据 content-type 序列化响应体
468
+ */
477
469
  async function serializeResponseBody(response) {
478
- var _a;
479
- const contentType = (_a = response.headers.get("content-type")) != null ? _a : "";
480
- try {
481
- if (contentType.includes("application/json")) {
482
- const json = await response.json();
483
- return JSON.stringify(json);
484
- }
485
- if (contentType.includes("text/") || contentType.includes("application/xml") || contentType.includes("application/javascript")) {
486
- return await response.text();
487
- }
488
- return "[Binary or unsupported content]";
489
- } catch {
490
- return "[Unable to serialize]";
491
- }
470
+ const contentType = response.headers.get("content-type") ?? "";
471
+ try {
472
+ if (contentType.includes("application/json")) {
473
+ const json = await response.json();
474
+ return JSON.stringify(json);
475
+ }
476
+ if (contentType.includes("text/") || contentType.includes("application/xml") || contentType.includes("application/javascript")) return await response.text();
477
+ return "[Binary or unsupported content]";
478
+ } catch {
479
+ return "[Unable to serialize]";
480
+ }
492
481
  }
493
-
494
- // src/storage/memory-storage/base-memory-storage.ts
482
+ //#endregion
483
+ //#region src/storage/memory-storage/base-memory-storage.ts
495
484
  var BaseMemoryStorage = class extends InternalStorage {
496
- constructor() {
497
- super(...arguments);
498
- __publicField(this, "storage", /* @__PURE__ */ new Map());
499
- __publicField(this, "visitTimeRecords", /* @__PURE__ */ new Map());
500
- __publicField(this, "visitCountRecords", /* @__PURE__ */ new Map());
501
- __publicField(this, "lastEvictExpiredTime", (0, import_dayjs.default)());
502
- }
503
- get size() {
504
- const used = R3.sum(R3.pluck("size", [...this.storage.values()]));
505
- const free = this.__size__ > used ? this.__size__ - used : 0;
506
- return {
507
- used,
508
- free
509
- };
510
- }
511
- get(key) {
512
- var _a;
513
- this.evictExpired();
514
- const entry = this.storage.get(key);
515
- this.visitCountRecords.set(key, ((_a = this.visitCountRecords.get(key)) != null ? _a : 0) + 1);
516
- this.visitTimeRecords.set(key, /* @__PURE__ */ new Date());
517
- if (!entry) this.debug((log) => log("Entry(".concat(key, ") Not Found")));
518
- else this.debug((log) => log("Entry(".concat(key, ") Found: "), entry));
519
- return entry == null ? void 0 : entry.clone();
520
- }
521
- set(value) {
522
- var _a;
523
- if (!this.evict(value.size)) {
524
- this.debug((log) => log("Storage Size Not Enough: ", this.size.free, " < ", value.size));
525
- return;
526
- }
527
- this.storage.set(value.key, value);
528
- this.visitTimeRecords.set(value.key, /* @__PURE__ */ new Date());
529
- this.visitCountRecords.set(value.key, (_a = this.visitCountRecords.get(value.key)) != null ? _a : 0);
530
- this.debug((log) => log("Entry Added: ", value));
531
- this.debug((log) => log("Storage Size: ", this.size));
532
- }
533
- __remove__(keys) {
534
- for (const key of keys) {
535
- const entry = this.storage.get(key);
536
- if (!entry) return;
537
- this.storage.delete(key);
538
- this.visitCountRecords.delete(key);
539
- this.visitTimeRecords.delete(key);
540
- this.debug((log) => log("Entry Removed: ", entry));
541
- this.debug((log) => log("Storage Size: ", this.size));
542
- }
543
- }
544
- remove(key) {
545
- this.__remove__([key]);
546
- }
547
- /**
548
- * @zh 清除过期的缓存
549
- */
550
- evictExpired() {
551
- var _a;
552
- const now = (0, import_dayjs.default)();
553
- if (now.diff(this.lastEvictExpiredTime, "second") < 1) return;
554
- const keys = [];
555
- for (const [key, entry] of this.storage.entries()) {
556
- if (entry.expiredAt && now.isAfter(entry.expiredAt)) {
557
- keys.push(key);
558
- }
559
- }
560
- this.__remove__(keys);
561
- (_a = this.__onCacheExpired__) == null ? void 0 : _a.call(this, { keys });
562
- }
563
- /**
564
- * @en Evict the storage to make sure the size is enough
565
- * @zh 清除缓存以确保有足够的空间
566
- *
567
- * @return {boolean} - is evicted successfully
568
- */
569
- evict(expectSize) {
570
- this.evictExpired();
571
- const size = this.size;
572
- return size.free >= expectSize;
573
- }
574
- /**
575
- * @en Print all cached data using console.table for debugging
576
- * @zh 使用 console.table 打印所有缓存数据,用于调试
577
- */
578
- async print() {
579
- if (this.storage.size === 0) {
580
- console.log("MemoryStorage is empty");
581
- return;
582
- }
583
- const entries = await Promise.all(
584
- [...this.storage.entries()].map(async ([key, entry]) => {
585
- var _a, _b, _c;
586
- const body = await serializeResponseBody(entry.response.clone());
587
- return {
588
- key,
589
- size: humanizeSize(entry.size),
590
- "Expired Time": entry.expiredAt.getTime() >= MAX_EXPIRED_AT.getTime() ? "-" : entry.expiredAt.toISOString(),
591
- "Visit Count": (_a = this.visitCountRecords.get(key)) != null ? _a : 0,
592
- "Last Visit Time": (_c = (_b = this.visitTimeRecords.get(key)) == null ? void 0 : _b.toISOString()) != null ? _c : "-",
593
- "Response Status": entry.response.status,
594
- "Response URL": entry.response.url,
595
- "Response Body": body
596
- };
597
- })
598
- );
599
- console.table(entries);
600
- }
485
+ constructor(..._args) {
486
+ super(..._args);
487
+ _defineProperty(this, "storage", /* @__PURE__ */ new Map());
488
+ _defineProperty(this, "visitTimeRecords", /* @__PURE__ */ new Map());
489
+ _defineProperty(this, "visitCountRecords", /* @__PURE__ */ new Map());
490
+ _defineProperty(this, "lastEvictExpiredTime", (0, dayjs.default)());
491
+ }
492
+ get size() {
493
+ const used = ramda.sum(ramda.pluck("size", [...this.storage.values()]));
494
+ return {
495
+ used,
496
+ free: this.__size__ > used ? this.__size__ - used : 0
497
+ };
498
+ }
499
+ get(key) {
500
+ this.evictExpired();
501
+ const entry = this.storage.get(key);
502
+ this.visitCountRecords.set(key, (this.visitCountRecords.get(key) ?? 0) + 1);
503
+ this.visitTimeRecords.set(key, /* @__PURE__ */ new Date());
504
+ if (!entry) this.debug((log) => log(`Entry(${key}) Not Found`));
505
+ else this.debug((log) => log(`Entry(${key}) Found: `, entry));
506
+ return entry?.clone();
507
+ }
508
+ set(value) {
509
+ if (!this.evict(value.size)) {
510
+ this.debug((log) => log("Storage Size Not Enough: ", this.size.free, " < ", value.size));
511
+ return;
512
+ }
513
+ this.storage.set(value.key, value);
514
+ this.visitTimeRecords.set(value.key, /* @__PURE__ */ new Date());
515
+ this.visitCountRecords.set(value.key, this.visitCountRecords.get(value.key) ?? 0);
516
+ this.debug((log) => log("Entry Added: ", value));
517
+ this.debug((log) => log("Storage Size: ", this.size));
518
+ }
519
+ __remove__(keys) {
520
+ for (const key of keys) {
521
+ const entry = this.storage.get(key);
522
+ if (!entry) return;
523
+ this.storage.delete(key);
524
+ this.visitCountRecords.delete(key);
525
+ this.visitTimeRecords.delete(key);
526
+ this.debug((log) => log("Entry Removed: ", entry));
527
+ this.debug((log) => log("Storage Size: ", this.size));
528
+ }
529
+ }
530
+ remove(key) {
531
+ this.__remove__([key]);
532
+ }
533
+ /**
534
+ * @zh 清除过期的缓存
535
+ */
536
+ evictExpired() {
537
+ const now = (0, dayjs.default)();
538
+ if (now.diff(this.lastEvictExpiredTime, "second") < 1) return;
539
+ const keys = [];
540
+ for (const [key, entry] of this.storage.entries()) if (entry.expiredAt && now.isAfter(entry.expiredAt)) keys.push(key);
541
+ this.__remove__(keys);
542
+ this.__onCacheExpired__?.({ keys });
543
+ }
544
+ /**
545
+ * @en Evict the storage to make sure the size is enough
546
+ * @zh 清除缓存以确保有足够的空间
547
+ *
548
+ * @return {boolean} - is evicted successfully
549
+ */
550
+ evict(expectSize) {
551
+ this.evictExpired();
552
+ return this.size.free >= expectSize;
553
+ }
554
+ /**
555
+ * @en Print all cached data using console.table for debugging
556
+ * @zh 使用 console.table 打印所有缓存数据,用于调试
557
+ */
558
+ async print() {
559
+ if (this.storage.size === 0) {
560
+ console.log("MemoryStorage is empty");
561
+ return;
562
+ }
563
+ const entries = await Promise.all([...this.storage.entries()].map(async ([key, entry]) => {
564
+ const body = await serializeResponseBody(entry.response.clone());
565
+ return {
566
+ key,
567
+ size: humanizeSize(entry.size),
568
+ "Expired Time": entry.expiredAt.getTime() >= MAX_EXPIRED_AT.getTime() ? "-" : entry.expiredAt.toISOString(),
569
+ "Visit Count": this.visitCountRecords.get(key) ?? 0,
570
+ "Last Visit Time": this.visitTimeRecords.get(key)?.toISOString() ?? "-",
571
+ "Response Status": entry.response.status,
572
+ "Response URL": entry.response.url,
573
+ "Response Body": body
574
+ };
575
+ }));
576
+ console.table(entries);
577
+ }
601
578
  };
602
-
603
- // src/storage/memory-storage/ttl-memory-storage.ts
579
+ //#endregion
580
+ //#region src/storage/memory-storage/ttl-memory-storage.ts
604
581
  var TTLMemoryStorage = class extends BaseMemoryStorage {
605
- constructor(options) {
606
- super(options);
607
- }
608
- get(key) {
609
- var _a;
610
- const entry = super.get(key);
611
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
612
- return entry;
613
- }
614
- set(value) {
615
- var _a;
616
- super.set(value);
617
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
618
- }
619
- remove(key) {
620
- var _a;
621
- super.remove(key);
622
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
623
- }
624
- evict(expectSize) {
625
- var _a;
626
- if (expectSize > this.__size__) {
627
- this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
628
- return false;
629
- }
630
- this.evictExpired();
631
- let deficitSize = expectSize - this.size.free;
632
- if (deficitSize <= 0) return true;
633
- const entries = [...this.storage.values()].sort((a, b) => {
634
- const aExpiredAt = (0, import_dayjs2.default)(a.expiredAt);
635
- const bExpiredAt = (0, import_dayjs2.default)(b.expiredAt);
636
- return aExpiredAt.isBefore(bExpiredAt) ? 1 : -1;
637
- });
638
- if (R4.sum(R4.pluck("size", entries)) < deficitSize) {
639
- this.debug((log) => log("Storage Size Not Enough: ", this.size.free, " < ", deficitSize));
640
- return false;
641
- }
642
- const keys = [];
643
- while (deficitSize > 0 && entries.length) {
644
- const entry = entries.pop();
645
- deficitSize -= entry.size;
646
- keys.push(entry.key);
647
- }
648
- this.__remove__(keys);
649
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
650
- return true;
651
- }
582
+ constructor(options) {
583
+ super(options);
584
+ }
585
+ get(key) {
586
+ const entry = super.get(key);
587
+ this.__onCacheGet__?.({ key });
588
+ return entry;
589
+ }
590
+ set(value) {
591
+ super.set(value);
592
+ this.__onCacheSet__?.({ key: value.key });
593
+ }
594
+ remove(key) {
595
+ super.remove(key);
596
+ this.__onCacheRemove__?.({ key });
597
+ }
598
+ evict(expectSize) {
599
+ if (expectSize > this.__size__) {
600
+ this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
601
+ return false;
602
+ }
603
+ this.evictExpired();
604
+ let deficitSize = expectSize - this.size.free;
605
+ if (deficitSize <= 0) return true;
606
+ const entries = [...this.storage.values()].sort((a, b) => {
607
+ const aExpiredAt = (0, dayjs.default)(a.expiredAt);
608
+ const bExpiredAt = (0, dayjs.default)(b.expiredAt);
609
+ return aExpiredAt.isBefore(bExpiredAt) ? 1 : -1;
610
+ });
611
+ if (ramda.sum(ramda.pluck("size", entries)) < deficitSize) {
612
+ this.debug((log) => log("Storage Size Not Enough: ", this.size.free, " < ", deficitSize));
613
+ return false;
614
+ }
615
+ const keys = [];
616
+ while (deficitSize > 0 && entries.length) {
617
+ const entry = entries.pop();
618
+ deficitSize -= entry.size;
619
+ keys.push(entry.key);
620
+ }
621
+ this.__remove__(keys);
622
+ this.__onCacheEvict__?.({ keys });
623
+ return true;
624
+ }
652
625
  };
653
-
654
- // src/storage/memory-storage/random-memory-storage.ts
626
+ //#endregion
627
+ //#region src/storage/memory-storage/random-memory-storage.ts
655
628
  var RandomMemoryStorage = class extends BaseMemoryStorage {
656
- constructor(options) {
657
- super(options);
658
- }
659
- get(key) {
660
- var _a;
661
- const entry = super.get(key);
662
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
663
- return entry;
664
- }
665
- set(value) {
666
- var _a;
667
- super.set(value);
668
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
669
- }
670
- remove(key) {
671
- var _a;
672
- super.remove(key);
673
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
674
- }
675
- evict(expectSize) {
676
- var _a;
677
- if (expectSize > this.__size__) {
678
- this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
679
- return false;
680
- }
681
- this.evictExpired();
682
- let deficitSize = expectSize - this.size.free;
683
- if (deficitSize <= 0) return true;
684
- const entries = [...this.storage.values()];
685
- const keys = [];
686
- while (deficitSize > 0 && entries.length) {
687
- const index = random(0, entries.length - 1);
688
- const entry = entries[index];
689
- deficitSize -= entry.size;
690
- entries.splice(index, 1);
691
- keys.push(entry.key);
692
- }
693
- this.__remove__(keys);
694
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
695
- return true;
696
- }
629
+ constructor(options) {
630
+ super(options);
631
+ }
632
+ get(key) {
633
+ const entry = super.get(key);
634
+ this.__onCacheGet__?.({ key });
635
+ return entry;
636
+ }
637
+ set(value) {
638
+ super.set(value);
639
+ this.__onCacheSet__?.({ key: value.key });
640
+ }
641
+ remove(key) {
642
+ super.remove(key);
643
+ this.__onCacheRemove__?.({ key });
644
+ }
645
+ evict(expectSize) {
646
+ if (expectSize > this.__size__) {
647
+ this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
648
+ return false;
649
+ }
650
+ this.evictExpired();
651
+ let deficitSize = expectSize - this.size.free;
652
+ if (deficitSize <= 0) return true;
653
+ const entries = [...this.storage.values()];
654
+ const keys = [];
655
+ while (deficitSize > 0 && entries.length) {
656
+ const index = random(0, entries.length - 1);
657
+ const entry = entries[index];
658
+ deficitSize -= entry.size;
659
+ entries.splice(index, 1);
660
+ keys.push(entry.key);
661
+ }
662
+ this.__remove__(keys);
663
+ this.__onCacheEvict__?.({ keys });
664
+ return true;
665
+ }
697
666
  };
698
-
699
- // src/storage/memory-storage/lru-memory-storage.ts
700
- var import_dayjs3 = __toESM(require("dayjs"));
667
+ //#endregion
668
+ //#region src/storage/memory-storage/lru-memory-storage.ts
701
669
  var LRUMemoryStorage = class extends BaseMemoryStorage {
702
- constructor(options) {
703
- super(options);
704
- }
705
- get(key) {
706
- var _a;
707
- const entry = super.get(key);
708
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
709
- return entry;
710
- }
711
- set(value) {
712
- var _a;
713
- super.set(value);
714
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
715
- }
716
- remove(key) {
717
- var _a;
718
- super.remove(key);
719
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
720
- }
721
- evict(expectSize) {
722
- var _a;
723
- if (expectSize > this.__size__) {
724
- this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
725
- return false;
726
- }
727
- this.evictExpired();
728
- let deficitSize = expectSize - this.size.free;
729
- if (deficitSize <= 0) return true;
730
- const entries = [...this.storage.values()].sort((a, b) => {
731
- const aVisitAt = this.visitTimeRecords.get(a.key);
732
- const bVisitAt = this.visitTimeRecords.get(b.key);
733
- if (aVisitAt === bVisitAt) return 0;
734
- if (!aVisitAt) return 1;
735
- if (!bVisitAt) return -1;
736
- return (0, import_dayjs3.default)(aVisitAt).isBefore((0, import_dayjs3.default)(bVisitAt)) ? 1 : -1;
737
- });
738
- const keys = [];
739
- while (deficitSize > 0 && entries.length) {
740
- const entry = entries.pop();
741
- deficitSize -= entry.size;
742
- keys.push(entry.key);
743
- }
744
- this.__remove__(keys);
745
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
746
- return true;
747
- }
670
+ constructor(options) {
671
+ super(options);
672
+ }
673
+ get(key) {
674
+ const entry = super.get(key);
675
+ this.__onCacheGet__?.({ key });
676
+ return entry;
677
+ }
678
+ set(value) {
679
+ super.set(value);
680
+ this.__onCacheSet__?.({ key: value.key });
681
+ }
682
+ remove(key) {
683
+ super.remove(key);
684
+ this.__onCacheRemove__?.({ key });
685
+ }
686
+ evict(expectSize) {
687
+ if (expectSize > this.__size__) {
688
+ this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
689
+ return false;
690
+ }
691
+ this.evictExpired();
692
+ let deficitSize = expectSize - this.size.free;
693
+ if (deficitSize <= 0) return true;
694
+ const entries = [...this.storage.values()].sort((a, b) => {
695
+ const aVisitAt = this.visitTimeRecords.get(a.key);
696
+ const bVisitAt = this.visitTimeRecords.get(b.key);
697
+ if (aVisitAt === bVisitAt) return 0;
698
+ if (!aVisitAt) return 1;
699
+ if (!bVisitAt) return -1;
700
+ return (0, dayjs.default)(aVisitAt).isBefore((0, dayjs.default)(bVisitAt)) ? 1 : -1;
701
+ });
702
+ const keys = [];
703
+ while (deficitSize > 0 && entries.length) {
704
+ const entry = entries.pop();
705
+ deficitSize -= entry.size;
706
+ keys.push(entry.key);
707
+ }
708
+ this.__remove__(keys);
709
+ this.__onCacheEvict__?.({ keys });
710
+ return true;
711
+ }
748
712
  };
749
-
750
- // src/storage/memory-storage/lfu-memory-storage.ts
713
+ //#endregion
714
+ //#region src/storage/memory-storage/lfu-memory-storage.ts
751
715
  var LFUMemoryStorage = class extends BaseMemoryStorage {
752
- constructor(options) {
753
- super(options);
754
- }
755
- get(key) {
756
- var _a;
757
- const entry = super.get(key);
758
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
759
- return entry;
760
- }
761
- set(value) {
762
- var _a;
763
- super.set(value);
764
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
765
- }
766
- remove(key) {
767
- var _a;
768
- super.remove(key);
769
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
770
- }
771
- evict(expectSize) {
772
- var _a;
773
- if (expectSize > this.__size__) {
774
- this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
775
- return false;
776
- }
777
- this.evictExpired();
778
- let deficitSize = expectSize - this.size.free;
779
- if (deficitSize <= 0) return true;
780
- const entries = [...this.storage.values()].sort((a, b) => {
781
- const aVisitCount = this.visitCountRecords.get(a.key) || 0;
782
- const bVisitCount = this.visitCountRecords.get(b.key) || 0;
783
- return bVisitCount - aVisitCount;
784
- });
785
- const keys = [];
786
- while (deficitSize > 0 && entries.length) {
787
- const entry = entries.pop();
788
- deficitSize -= entry.size;
789
- keys.push(entry.key);
790
- }
791
- this.__remove__(keys);
792
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
793
- return true;
794
- }
716
+ constructor(options) {
717
+ super(options);
718
+ }
719
+ get(key) {
720
+ const entry = super.get(key);
721
+ this.__onCacheGet__?.({ key });
722
+ return entry;
723
+ }
724
+ set(value) {
725
+ super.set(value);
726
+ this.__onCacheSet__?.({ key: value.key });
727
+ }
728
+ remove(key) {
729
+ super.remove(key);
730
+ this.__onCacheRemove__?.({ key });
731
+ }
732
+ evict(expectSize) {
733
+ if (expectSize > this.__size__) {
734
+ this.debug((log) => log("Storage Size Not Enough: ", this.__size__, " < ", expectSize));
735
+ return false;
736
+ }
737
+ this.evictExpired();
738
+ let deficitSize = expectSize - this.size.free;
739
+ if (deficitSize <= 0) return true;
740
+ const entries = [...this.storage.values()].sort((a, b) => {
741
+ const aVisitCount = this.visitCountRecords.get(a.key) || 0;
742
+ return (this.visitCountRecords.get(b.key) || 0) - aVisitCount;
743
+ });
744
+ const keys = [];
745
+ while (deficitSize > 0 && entries.length) {
746
+ const entry = entries.pop();
747
+ deficitSize -= entry.size;
748
+ keys.push(entry.key);
749
+ }
750
+ this.__remove__(keys);
751
+ this.__onCacheEvict__?.({ keys });
752
+ return true;
753
+ }
795
754
  };
796
-
797
- // src/storage/memory-storage/memory-storage.ts
755
+ //#endregion
756
+ //#region src/storage/memory-storage/memory-storage.ts
798
757
  var MemoryStorage = class extends KeqCacheStorage {
799
- constructor(options) {
800
- super();
801
- __publicField(this, "storage");
802
- const eviction = (options == null ? void 0 : options.eviction) || "lru" /* LRU */;
803
- if (eviction === "ttl" /* TTL */) {
804
- this.storage = new TTLMemoryStorage(options);
805
- } else if (eviction === "random" /* RANDOM */) {
806
- this.storage = new RandomMemoryStorage(options);
807
- } else if (eviction === "lru" /* LRU */) {
808
- this.storage = new LRUMemoryStorage(options);
809
- } else if (eviction === "lfu" /* LFU */) {
810
- this.storage = new LFUMemoryStorage(options);
811
- } else {
812
- throw new TypeError("Invalid eviction: ".concat(String(eviction)));
813
- }
814
- }
815
- set(entry) {
816
- return this.storage.set(entry);
817
- }
818
- get(key) {
819
- return this.storage.get(key);
820
- }
821
- remove(key) {
822
- return this.storage.remove(key);
823
- }
824
- async print() {
825
- return this.storage.print();
826
- }
758
+ constructor(options) {
759
+ super();
760
+ _defineProperty(this, "storage", void 0);
761
+ const eviction = options?.eviction || "lru";
762
+ if (eviction === "ttl") this.storage = new TTLMemoryStorage(options);
763
+ else if (eviction === "random") this.storage = new RandomMemoryStorage(options);
764
+ else if (eviction === "lru") this.storage = new LRUMemoryStorage(options);
765
+ else if (eviction === "lfu") this.storage = new LFUMemoryStorage(options);
766
+ else throw new TypeError(`Invalid eviction: ${String(eviction)}`);
767
+ }
768
+ set(entry) {
769
+ return this.storage.set(entry);
770
+ }
771
+ get(key) {
772
+ return this.storage.get(key);
773
+ }
774
+ remove(key) {
775
+ return this.storage.remove(key);
776
+ }
777
+ async print() {
778
+ return this.storage.print();
779
+ }
827
780
  };
828
-
829
- // src/storage/indexed-db-storage/random-indexed-db-storage.ts
830
- var R6 = __toESM(require("ramda"));
831
-
832
- // src/storage/indexed-db-storage/base-indexed-db-storage.ts
833
- var R5 = __toESM(require("ramda"));
834
- var import_dayjs4 = __toESM(require("dayjs"));
835
- var import_idb = require("idb");
836
-
837
- // src/storage/indexed-db-storage/constants/default-table-name.ts
838
- var DEFAULT_TABLE_NAME = "keq_cache_indexed_db_storage";
839
-
840
- // src/storage/indexed-db-storage/base-indexed-db-storage.ts
781
+ //#endregion
782
+ //#region src/storage/indexed-db-storage/constants/default-table-name.ts
783
+ const DEFAULT_TABLE_NAME = "keq_cache_indexed_db_storage";
784
+ //#endregion
785
+ //#region src/storage/indexed-db-storage/base-indexed-db-storage.ts
841
786
  var BaseIndexedDBStorage = class extends InternalStorage {
842
- constructor(options) {
843
- super(options);
844
- __publicField(this, "tableName", DEFAULT_TABLE_NAME);
845
- __publicField(this, "db");
846
- __publicField(this, "lastEvictExpiredTime", (0, import_dayjs4.default)(0));
847
- if ((options == null ? void 0 : options.tableName) === DEFAULT_TABLE_NAME) {
848
- throw new CacheException('IndexedDBStorage name cannot be "'.concat(DEFAULT_TABLE_NAME, '"'));
849
- }
850
- this.tableName = (options == null ? void 0 : options.tableName) || DEFAULT_TABLE_NAME;
851
- }
852
- async openDB() {
853
- if (this.db) return this.db;
854
- const tableName = this.tableName;
855
- const db = await (0, import_idb.openDB)(tableName, 2, {
856
- upgrade(db2) {
857
- if (!db2.objectStoreNames.contains("metadata")) {
858
- const entriesStore = db2.createObjectStore("metadata", { keyPath: "key" });
859
- entriesStore.createIndex("expiredAt", "expiredAt");
860
- }
861
- if (!db2.objectStoreNames.contains("response")) {
862
- const responsesStore = db2.createObjectStore("response", { keyPath: "key" });
863
- responsesStore.createIndex("responseStatus", "responseStatus");
864
- }
865
- if (!db2.objectStoreNames.contains("visits")) {
866
- const visitsStore = db2.createObjectStore("visits", { keyPath: "key" });
867
- visitsStore.createIndex("visitCount", "visitCount");
868
- visitsStore.createIndex("lastVisitedAt", "lastVisitedAt");
869
- }
870
- },
871
- blocked() {
872
- Logger.error("[@keq-request/cache] IndexedDB Table ".concat(tableName, " is blocked"));
873
- },
874
- blocking() {
875
- Logger.error("[@keq-request/cache] IndexedDB Table ".concat(tableName, " is blocking"));
876
- },
877
- terminated() {
878
- Logger.error("[@keq-request/cache] IndexedDB Table ".concat(tableName, " is terminated"));
879
- }
880
- });
881
- this.db = db;
882
- return db;
883
- }
884
- async getSize() {
885
- const db = await this.openDB();
886
- const items = await db.getAll("metadata");
887
- const used = R5.sum(items.map((entry) => entry.size));
888
- const free = this.__size__ - used;
889
- return { used, free };
890
- }
891
- async get(key) {
892
- await this.evictExpired();
893
- try {
894
- const db = await this.openDB();
895
- const dbMetadata = await db.get("metadata", key);
896
- const dbResponse = await db.get("response", key);
897
- const dbVisits = await db.get("visits", key);
898
- if (!dbMetadata || !dbResponse) return;
899
- await db.put("visits", {
900
- key: dbMetadata.key,
901
- visitCount: dbVisits ? dbVisits.visitCount + 1 : 1,
902
- lastVisitedAt: /* @__PURE__ */ new Date()
903
- });
904
- const response = new Response(dbResponse.responseBody, {
905
- status: dbResponse.responseStatus,
906
- headers: new Headers(dbResponse.responseHeaders),
907
- statusText: dbResponse.responseStatusText
908
- });
909
- return await CacheEntry.build({
910
- key: dbMetadata.key,
911
- expiredAt: dbMetadata.expiredAt,
912
- response,
913
- size: dbMetadata.size
914
- });
915
- } catch (error) {
916
- return;
917
- }
918
- }
919
- async set(entry) {
920
- try {
921
- if (!await this.evict(entry.size)) {
922
- const size = await this.getSize();
923
- this.debug((log) => log("Storage Size Not Enough: ".concat(size.free, " < ").concat(entry.size)));
924
- return;
925
- }
926
- const dbMetadata = {
927
- key: entry.key,
928
- size: entry.size,
929
- expiredAt: entry.expiredAt,
930
- visitedAt: /* @__PURE__ */ new Date(),
931
- visitCount: 0
932
- };
933
- const response = entry.response.clone();
934
- const dbResponse = {
935
- key: entry.key,
936
- responseBody: await response.arrayBuffer(),
937
- responseHeaders: [...response.headers.entries()],
938
- responseStatus: response.status,
939
- responseStatusText: response.statusText
940
- };
941
- const db = await this.openDB();
942
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
943
- const metadataStore = tx.objectStore("metadata");
944
- const responseStore = tx.objectStore("response");
945
- const visitsStore = tx.objectStore("visits");
946
- const dbVisits = await visitsStore.get(entry.key) || {
947
- key: entry.key,
948
- visitCount: 0,
949
- lastVisitedAt: /* @__PURE__ */ new Date()
950
- };
951
- await Promise.all([
952
- metadataStore.put(dbMetadata),
953
- responseStore.put(dbResponse),
954
- visitsStore.put(dbVisits)
955
- ]);
956
- await tx.done;
957
- } catch (error) {
958
- return;
959
- }
960
- }
961
- async __remove__(tx, keys) {
962
- await Promise.all(
963
- R5.unnest(
964
- keys.map((key) => [
965
- tx.objectStore("metadata").delete(key),
966
- tx.objectStore("response").delete(key),
967
- tx.objectStore("visits").delete(key)
968
- ])
969
- )
970
- );
971
- }
972
- async remove(key) {
973
- try {
974
- const db = await this.openDB();
975
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
976
- await this.__remove__(tx, [key]);
977
- await tx.done;
978
- } catch (error) {
979
- return;
980
- }
981
- }
982
- /**
983
- * @zh 清除过期的缓存
984
- */
985
- async evictExpired() {
986
- var _a;
987
- const now = (0, import_dayjs4.default)();
988
- if (now.diff(this.lastEvictExpiredTime, "second") < 1) return;
989
- this.lastEvictExpiredTime = now;
990
- try {
991
- const db = await this.openDB();
992
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
993
- const metadataStore = tx.objectStore("metadata");
994
- let cursor = await metadataStore.index("expiredAt").openCursor(IDBKeyRange.upperBound(now.toDate()));
995
- const expiredKeys = [];
996
- while (cursor) {
997
- if ((0, import_dayjs4.default)(cursor.value.expiredAt).isBefore(now)) {
998
- expiredKeys.push(cursor.value.key);
999
- cursor = await cursor.continue();
1000
- } else {
1001
- break;
1002
- }
1003
- }
1004
- await this.__remove__(tx, expiredKeys);
1005
- await tx.done;
1006
- (_a = this.__onCacheExpired__) == null ? void 0 : _a.call(this, { keys: expiredKeys });
1007
- } catch (error) {
1008
- return;
1009
- }
1010
- }
787
+ constructor(options) {
788
+ super(options);
789
+ _defineProperty(this, "tableName", DEFAULT_TABLE_NAME);
790
+ _defineProperty(this, "db", void 0);
791
+ _defineProperty(this, "lastEvictExpiredTime", (0, dayjs.default)(0));
792
+ if (options?.tableName === "keq_cache_indexed_db_storage") throw new CacheException(`IndexedDBStorage name cannot be "${DEFAULT_TABLE_NAME}"`);
793
+ this.tableName = options?.tableName || "keq_cache_indexed_db_storage";
794
+ }
795
+ async openDB() {
796
+ if (this.db) return this.db;
797
+ const tableName = this.tableName;
798
+ const db = await (0, idb.openDB)(tableName, 2, {
799
+ upgrade(db) {
800
+ if (!db.objectStoreNames.contains("metadata")) db.createObjectStore("metadata", { keyPath: "key" }).createIndex("expiredAt", "expiredAt");
801
+ if (!db.objectStoreNames.contains("response")) db.createObjectStore("response", { keyPath: "key" }).createIndex("responseStatus", "responseStatus");
802
+ if (!db.objectStoreNames.contains("visits")) {
803
+ const visitsStore = db.createObjectStore("visits", { keyPath: "key" });
804
+ visitsStore.createIndex("visitCount", "visitCount");
805
+ visitsStore.createIndex("lastVisitedAt", "lastVisitedAt");
806
+ }
807
+ },
808
+ blocked() {
809
+ Logger.error(`[@keq-request/cache] IndexedDB Table ${tableName} is blocked`);
810
+ },
811
+ blocking() {
812
+ Logger.error(`[@keq-request/cache] IndexedDB Table ${tableName} is blocking`);
813
+ },
814
+ terminated() {
815
+ Logger.error(`[@keq-request/cache] IndexedDB Table ${tableName} is terminated`);
816
+ }
817
+ });
818
+ this.db = db;
819
+ return db;
820
+ }
821
+ async getSize() {
822
+ const items = await (await this.openDB()).getAll("metadata");
823
+ const used = ramda.sum(items.map((entry) => entry.size));
824
+ return {
825
+ used,
826
+ free: this.__size__ - used
827
+ };
828
+ }
829
+ async get(key) {
830
+ await this.evictExpired();
831
+ try {
832
+ const db = await this.openDB();
833
+ const dbMetadata = await db.get("metadata", key);
834
+ const dbResponse = await db.get("response", key);
835
+ const dbVisits = await db.get("visits", key);
836
+ if (!dbMetadata || !dbResponse) return;
837
+ await db.put("visits", {
838
+ key: dbMetadata.key,
839
+ visitCount: dbVisits ? dbVisits.visitCount + 1 : 1,
840
+ lastVisitedAt: /* @__PURE__ */ new Date()
841
+ });
842
+ const response = new Response(dbResponse.responseBody, {
843
+ status: dbResponse.responseStatus,
844
+ headers: new Headers(dbResponse.responseHeaders),
845
+ statusText: dbResponse.responseStatusText
846
+ });
847
+ return await CacheEntry.build({
848
+ key: dbMetadata.key,
849
+ expiredAt: dbMetadata.expiredAt,
850
+ response,
851
+ size: dbMetadata.size
852
+ });
853
+ } catch (error) {
854
+ return;
855
+ }
856
+ }
857
+ async set(entry) {
858
+ try {
859
+ if (!await this.evict(entry.size)) {
860
+ const size = await this.getSize();
861
+ this.debug((log) => log(`Storage Size Not Enough: ${size.free} < ${entry.size}`));
862
+ return;
863
+ }
864
+ const dbMetadata = {
865
+ key: entry.key,
866
+ size: entry.size,
867
+ expiredAt: entry.expiredAt,
868
+ visitedAt: /* @__PURE__ */ new Date(),
869
+ visitCount: 0
870
+ };
871
+ const response = entry.response.clone();
872
+ const dbResponse = {
873
+ key: entry.key,
874
+ responseBody: await response.arrayBuffer(),
875
+ responseHeaders: [...response.headers.entries()],
876
+ responseStatus: response.status,
877
+ responseStatusText: response.statusText
878
+ };
879
+ const tx = (await this.openDB()).transaction([
880
+ "metadata",
881
+ "response",
882
+ "visits"
883
+ ], "readwrite");
884
+ const metadataStore = tx.objectStore("metadata");
885
+ const responseStore = tx.objectStore("response");
886
+ const visitsStore = tx.objectStore("visits");
887
+ const dbVisits = await visitsStore.get(entry.key) || {
888
+ key: entry.key,
889
+ visitCount: 0,
890
+ lastVisitedAt: /* @__PURE__ */ new Date()
891
+ };
892
+ await Promise.all([
893
+ metadataStore.put(dbMetadata),
894
+ responseStore.put(dbResponse),
895
+ visitsStore.put(dbVisits)
896
+ ]);
897
+ await tx.done;
898
+ } catch (error) {
899
+ return;
900
+ }
901
+ }
902
+ async __remove__(tx, keys) {
903
+ await Promise.all(ramda.unnest(keys.map((key) => [
904
+ tx.objectStore("metadata").delete(key),
905
+ tx.objectStore("response").delete(key),
906
+ tx.objectStore("visits").delete(key)
907
+ ])));
908
+ }
909
+ async remove(key) {
910
+ try {
911
+ const tx = (await this.openDB()).transaction([
912
+ "metadata",
913
+ "response",
914
+ "visits"
915
+ ], "readwrite");
916
+ await this.__remove__(tx, [key]);
917
+ await tx.done;
918
+ } catch (error) {
919
+ return;
920
+ }
921
+ }
922
+ /**
923
+ * @zh 清除过期的缓存
924
+ */
925
+ async evictExpired() {
926
+ const now = (0, dayjs.default)();
927
+ if (now.diff(this.lastEvictExpiredTime, "second") < 1) return;
928
+ this.lastEvictExpiredTime = now;
929
+ try {
930
+ const tx = (await this.openDB()).transaction([
931
+ "metadata",
932
+ "response",
933
+ "visits"
934
+ ], "readwrite");
935
+ let cursor = await tx.objectStore("metadata").index("expiredAt").openCursor(IDBKeyRange.upperBound(now.toDate()));
936
+ const expiredKeys = [];
937
+ while (cursor) if ((0, dayjs.default)(cursor.value.expiredAt).isBefore(now)) {
938
+ expiredKeys.push(cursor.value.key);
939
+ cursor = await cursor.continue();
940
+ } else break;
941
+ await this.__remove__(tx, expiredKeys);
942
+ await tx.done;
943
+ this.__onCacheExpired__?.({ keys: expiredKeys });
944
+ } catch (error) {
945
+ return;
946
+ }
947
+ }
1011
948
  };
1012
-
1013
- // src/storage/indexed-db-storage/random-indexed-db-storage.ts
949
+ //#endregion
950
+ //#region src/storage/indexed-db-storage/random-indexed-db-storage.ts
1014
951
  var RandomIndexedDBStorage = class extends BaseIndexedDBStorage {
1015
- constructor(options) {
1016
- super(options);
1017
- }
1018
- async get(key) {
1019
- var _a;
1020
- const entry = await super.get(key);
1021
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
1022
- return entry;
1023
- }
1024
- async set(value) {
1025
- var _a;
1026
- await super.set(value);
1027
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
1028
- }
1029
- async remove(key) {
1030
- var _a;
1031
- await super.remove(key);
1032
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
1033
- }
1034
- async evict(expectSize) {
1035
- var _a;
1036
- await this.evictExpired();
1037
- const size = await this.getSize();
1038
- let deficitSize = expectSize - size.free;
1039
- if (deficitSize <= 0) return true;
1040
- const db = await this.openDB();
1041
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
1042
- const metadataStore = tx.objectStore("metadata");
1043
- const metadatas = await metadataStore.getAll();
1044
- const totalSize = R6.sum(metadatas.map((m) => m.size));
1045
- if (totalSize < deficitSize) {
1046
- this.debug((log) => log("Storage Size Not Enough, deficit size: ".concat(deficitSize - totalSize)));
1047
- tx.abort();
1048
- return false;
1049
- }
1050
- const keys = [];
1051
- while (deficitSize > 0 && metadatas.length) {
1052
- const index = random(0, metadatas.length - 1);
1053
- const metadata = metadatas[index];
1054
- deficitSize -= metadata.size;
1055
- keys.push(metadata.key);
1056
- metadatas.splice(index, 1);
1057
- }
1058
- await this.__remove__(tx, keys);
1059
- await tx.done;
1060
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
1061
- return true;
1062
- }
952
+ constructor(options) {
953
+ super(options);
954
+ }
955
+ async get(key) {
956
+ const entry = await super.get(key);
957
+ this.__onCacheGet__?.({ key });
958
+ return entry;
959
+ }
960
+ async set(value) {
961
+ await super.set(value);
962
+ this.__onCacheSet__?.({ key: value.key });
963
+ }
964
+ async remove(key) {
965
+ await super.remove(key);
966
+ this.__onCacheRemove__?.({ key });
967
+ }
968
+ async evict(expectSize) {
969
+ await this.evictExpired();
970
+ let deficitSize = expectSize - (await this.getSize()).free;
971
+ if (deficitSize <= 0) return true;
972
+ const tx = (await this.openDB()).transaction([
973
+ "metadata",
974
+ "response",
975
+ "visits"
976
+ ], "readwrite");
977
+ const metadatas = await tx.objectStore("metadata").getAll();
978
+ const totalSize = ramda.sum(metadatas.map((m) => m.size));
979
+ if (totalSize < deficitSize) {
980
+ this.debug((log) => log(`Storage Size Not Enough, deficit size: ${deficitSize - totalSize}`));
981
+ tx.abort();
982
+ return false;
983
+ }
984
+ const keys = [];
985
+ while (deficitSize > 0 && metadatas.length) {
986
+ const index = random(0, metadatas.length - 1);
987
+ const metadata = metadatas[index];
988
+ deficitSize -= metadata.size;
989
+ keys.push(metadata.key);
990
+ metadatas.splice(index, 1);
991
+ }
992
+ await this.__remove__(tx, keys);
993
+ await tx.done;
994
+ this.__onCacheEvict__?.({ keys });
995
+ return true;
996
+ }
1063
997
  };
1064
-
1065
- // src/storage/indexed-db-storage/lfu-indexed-db-storage.ts
998
+ //#endregion
999
+ //#region src/storage/indexed-db-storage/lfu-indexed-db-storage.ts
1066
1000
  var LFUIndexedDBStorage = class extends BaseIndexedDBStorage {
1067
- constructor(options) {
1068
- super(options);
1069
- }
1070
- async get(key) {
1071
- var _a;
1072
- const entry = await super.get(key);
1073
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
1074
- return entry;
1075
- }
1076
- async set(value) {
1077
- var _a;
1078
- await super.set(value);
1079
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
1080
- }
1081
- async remove(key) {
1082
- var _a;
1083
- await super.remove(key);
1084
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
1085
- }
1086
- async evict(expectSize) {
1087
- var _a;
1088
- await this.evictExpired();
1089
- const size = await this.getSize();
1090
- let deficitSize = expectSize - size.free;
1091
- if (deficitSize <= 0) return true;
1092
- const db = await this.openDB();
1093
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
1094
- const metadataStore = tx.objectStore("metadata");
1095
- const visitsStore = tx.objectStore("visits");
1096
- let cursor = await visitsStore.index("visitCount").openCursor();
1097
- const keys = [];
1098
- while (deficitSize > 0 && cursor) {
1099
- const metadata = await metadataStore.get(cursor.value.key);
1100
- if (!metadata) {
1101
- await cursor.delete();
1102
- cursor = await cursor.continue();
1103
- continue;
1104
- }
1105
- deficitSize -= metadata.size;
1106
- keys.push(cursor.value.key);
1107
- cursor = await cursor.continue();
1108
- }
1109
- if (deficitSize > 0) {
1110
- this.debug((log) => log("Storage Size Not Enough, deficit size: ".concat(deficitSize)));
1111
- tx.abort();
1112
- return false;
1113
- }
1114
- await this.__remove__(tx, keys);
1115
- await tx.done;
1116
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
1117
- return true;
1118
- }
1001
+ constructor(options) {
1002
+ super(options);
1003
+ }
1004
+ async get(key) {
1005
+ const entry = await super.get(key);
1006
+ this.__onCacheGet__?.({ key });
1007
+ return entry;
1008
+ }
1009
+ async set(value) {
1010
+ await super.set(value);
1011
+ this.__onCacheSet__?.({ key: value.key });
1012
+ }
1013
+ async remove(key) {
1014
+ await super.remove(key);
1015
+ this.__onCacheRemove__?.({ key });
1016
+ }
1017
+ async evict(expectSize) {
1018
+ await this.evictExpired();
1019
+ let deficitSize = expectSize - (await this.getSize()).free;
1020
+ if (deficitSize <= 0) return true;
1021
+ const tx = (await this.openDB()).transaction([
1022
+ "metadata",
1023
+ "response",
1024
+ "visits"
1025
+ ], "readwrite");
1026
+ const metadataStore = tx.objectStore("metadata");
1027
+ let cursor = await tx.objectStore("visits").index("visitCount").openCursor();
1028
+ const keys = [];
1029
+ while (deficitSize > 0 && cursor) {
1030
+ const metadata = await metadataStore.get(cursor.value.key);
1031
+ if (!metadata) {
1032
+ await cursor.delete();
1033
+ cursor = await cursor.continue();
1034
+ continue;
1035
+ }
1036
+ deficitSize -= metadata.size;
1037
+ keys.push(cursor.value.key);
1038
+ cursor = await cursor.continue();
1039
+ }
1040
+ if (deficitSize > 0) {
1041
+ this.debug((log) => log(`Storage Size Not Enough, deficit size: ${deficitSize}`));
1042
+ tx.abort();
1043
+ return false;
1044
+ }
1045
+ await this.__remove__(tx, keys);
1046
+ await tx.done;
1047
+ this.__onCacheEvict__?.({ keys });
1048
+ return true;
1049
+ }
1119
1050
  };
1120
-
1121
- // src/storage/indexed-db-storage/lru-indexed-db-storage.ts
1051
+ //#endregion
1052
+ //#region src/storage/indexed-db-storage/lru-indexed-db-storage.ts
1122
1053
  var LRUIndexedDBStorage = class extends BaseIndexedDBStorage {
1123
- constructor(options) {
1124
- super(options);
1125
- }
1126
- async get(key) {
1127
- var _a;
1128
- const entry = await super.get(key);
1129
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
1130
- return entry;
1131
- }
1132
- async set(value) {
1133
- var _a;
1134
- await super.set(value);
1135
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
1136
- }
1137
- async remove(key) {
1138
- var _a;
1139
- await super.remove(key);
1140
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
1141
- }
1142
- async evict(expectSize) {
1143
- var _a;
1144
- await this.evictExpired();
1145
- const size = await this.getSize();
1146
- let deficitSize = expectSize - size.free;
1147
- if (deficitSize <= 0) return true;
1148
- const db = await this.openDB();
1149
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
1150
- const metadataStore = tx.objectStore("metadata");
1151
- const visitsStore = tx.objectStore("visits");
1152
- const keys = [];
1153
- let cursor = await visitsStore.index("lastVisitedAt").openCursor();
1154
- while (deficitSize > 0 && cursor) {
1155
- const metadata = await metadataStore.get(cursor.value.key);
1156
- if (!metadata) {
1157
- await cursor.delete();
1158
- cursor = await cursor.continue();
1159
- continue;
1160
- }
1161
- deficitSize -= metadata.size;
1162
- keys.push(cursor.value.key);
1163
- cursor = await cursor.continue();
1164
- }
1165
- if (deficitSize > 0) {
1166
- this.debug((log) => log("Storage Size Not Enough, deficit size: ".concat(deficitSize)));
1167
- tx.abort();
1168
- return false;
1169
- }
1170
- await this.__remove__(tx, keys);
1171
- await tx.done;
1172
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
1173
- return true;
1174
- }
1054
+ constructor(options) {
1055
+ super(options);
1056
+ }
1057
+ async get(key) {
1058
+ const entry = await super.get(key);
1059
+ this.__onCacheGet__?.({ key });
1060
+ return entry;
1061
+ }
1062
+ async set(value) {
1063
+ await super.set(value);
1064
+ this.__onCacheSet__?.({ key: value.key });
1065
+ }
1066
+ async remove(key) {
1067
+ await super.remove(key);
1068
+ this.__onCacheRemove__?.({ key });
1069
+ }
1070
+ async evict(expectSize) {
1071
+ await this.evictExpired();
1072
+ let deficitSize = expectSize - (await this.getSize()).free;
1073
+ if (deficitSize <= 0) return true;
1074
+ const tx = (await this.openDB()).transaction([
1075
+ "metadata",
1076
+ "response",
1077
+ "visits"
1078
+ ], "readwrite");
1079
+ const metadataStore = tx.objectStore("metadata");
1080
+ const visitsStore = tx.objectStore("visits");
1081
+ const keys = [];
1082
+ let cursor = await visitsStore.index("lastVisitedAt").openCursor();
1083
+ while (deficitSize > 0 && cursor) {
1084
+ const metadata = await metadataStore.get(cursor.value.key);
1085
+ if (!metadata) {
1086
+ await cursor.delete();
1087
+ cursor = await cursor.continue();
1088
+ continue;
1089
+ }
1090
+ deficitSize -= metadata.size;
1091
+ keys.push(cursor.value.key);
1092
+ cursor = await cursor.continue();
1093
+ }
1094
+ if (deficitSize > 0) {
1095
+ this.debug((log) => log(`Storage Size Not Enough, deficit size: ${deficitSize}`));
1096
+ tx.abort();
1097
+ return false;
1098
+ }
1099
+ await this.__remove__(tx, keys);
1100
+ await tx.done;
1101
+ this.__onCacheEvict__?.({ keys });
1102
+ return true;
1103
+ }
1175
1104
  };
1176
-
1177
- // src/storage/indexed-db-storage/ttl-indexed-db-storage.ts
1105
+ //#endregion
1106
+ //#region src/storage/indexed-db-storage/ttl-indexed-db-storage.ts
1178
1107
  var TTLIndexedDBStorage = class extends BaseIndexedDBStorage {
1179
- constructor(options) {
1180
- super(options);
1181
- }
1182
- async get(key) {
1183
- var _a;
1184
- const entry = await super.get(key);
1185
- (_a = this.__onCacheGet__) == null ? void 0 : _a.call(this, { key });
1186
- return entry;
1187
- }
1188
- async set(value) {
1189
- var _a;
1190
- await super.set(value);
1191
- (_a = this.__onCacheSet__) == null ? void 0 : _a.call(this, { key: value.key });
1192
- }
1193
- async remove(key) {
1194
- var _a;
1195
- await super.remove(key);
1196
- (_a = this.__onCacheRemove__) == null ? void 0 : _a.call(this, { key });
1197
- }
1198
- async evict(expectSize) {
1199
- var _a;
1200
- await this.evictExpired();
1201
- const size = await this.getSize();
1202
- let deficitSize = expectSize - size.free;
1203
- if (deficitSize <= 0) return true;
1204
- const db = await this.openDB();
1205
- const tx = db.transaction(["metadata", "response", "visits"], "readwrite");
1206
- const metadataStore = tx.objectStore("metadata");
1207
- const keys = [];
1208
- let cursor = await metadataStore.index("expiredAt").openCursor();
1209
- while (deficitSize > 0 && cursor) {
1210
- const metadata = await metadataStore.get(cursor.value.key);
1211
- if (!metadata) {
1212
- await cursor.delete();
1213
- cursor = await cursor.continue();
1214
- continue;
1215
- }
1216
- deficitSize -= metadata.size;
1217
- keys.push(cursor.value.key);
1218
- cursor = await cursor.continue();
1219
- }
1220
- if (deficitSize > 0) {
1221
- this.debug((log) => log("Storage Size Not Enough, deficit size: ".concat(deficitSize)));
1222
- tx.abort();
1223
- return false;
1224
- }
1225
- await this.__remove__(tx, keys);
1226
- await tx.done;
1227
- (_a = this.__onCacheEvict__) == null ? void 0 : _a.call(this, { keys });
1228
- return true;
1229
- }
1108
+ constructor(options) {
1109
+ super(options);
1110
+ }
1111
+ async get(key) {
1112
+ const entry = await super.get(key);
1113
+ this.__onCacheGet__?.({ key });
1114
+ return entry;
1115
+ }
1116
+ async set(value) {
1117
+ await super.set(value);
1118
+ this.__onCacheSet__?.({ key: value.key });
1119
+ }
1120
+ async remove(key) {
1121
+ await super.remove(key);
1122
+ this.__onCacheRemove__?.({ key });
1123
+ }
1124
+ async evict(expectSize) {
1125
+ await this.evictExpired();
1126
+ let deficitSize = expectSize - (await this.getSize()).free;
1127
+ if (deficitSize <= 0) return true;
1128
+ const tx = (await this.openDB()).transaction([
1129
+ "metadata",
1130
+ "response",
1131
+ "visits"
1132
+ ], "readwrite");
1133
+ const metadataStore = tx.objectStore("metadata");
1134
+ const keys = [];
1135
+ let cursor = await metadataStore.index("expiredAt").openCursor();
1136
+ while (deficitSize > 0 && cursor) {
1137
+ const metadata = await metadataStore.get(cursor.value.key);
1138
+ if (!metadata) {
1139
+ await cursor.delete();
1140
+ cursor = await cursor.continue();
1141
+ continue;
1142
+ }
1143
+ deficitSize -= metadata.size;
1144
+ keys.push(cursor.value.key);
1145
+ cursor = await cursor.continue();
1146
+ }
1147
+ if (deficitSize > 0) {
1148
+ this.debug((log) => log(`Storage Size Not Enough, deficit size: ${deficitSize}`));
1149
+ tx.abort();
1150
+ return false;
1151
+ }
1152
+ await this.__remove__(tx, keys);
1153
+ await tx.done;
1154
+ this.__onCacheEvict__?.({ keys });
1155
+ return true;
1156
+ }
1230
1157
  };
1231
-
1232
- // src/storage/indexed-db-storage/indexed-db-storage.ts
1158
+ //#endregion
1159
+ //#region src/storage/indexed-db-storage/indexed-db-storage.ts
1233
1160
  var IndexedDBStorage = class extends KeqCacheStorage {
1234
- constructor(options) {
1235
- super();
1236
- __publicField(this, "storage");
1237
- const eviction = (options == null ? void 0 : options.eviction) || "lru" /* LRU */;
1238
- if (eviction === "random" /* RANDOM */) {
1239
- this.storage = new RandomIndexedDBStorage(options);
1240
- } else if (eviction === "lfu" /* LFU */) {
1241
- this.storage = new LFUIndexedDBStorage(options);
1242
- } else if (eviction === "lru" /* LRU */) {
1243
- this.storage = new LRUIndexedDBStorage(options);
1244
- } else if (eviction === "ttl" /* TTL */) {
1245
- this.storage = new TTLIndexedDBStorage(options);
1246
- } else {
1247
- throw new CacheException("Not Supported Eviction: ".concat(String(options == null ? void 0 : options.eviction)));
1248
- }
1249
- }
1250
- set(entry) {
1251
- return this.storage.set(entry);
1252
- }
1253
- get(key) {
1254
- return this.storage.get(key);
1255
- }
1256
- remove(key) {
1257
- return this.storage.remove(key);
1258
- }
1161
+ constructor(options) {
1162
+ super();
1163
+ _defineProperty(this, "storage", void 0);
1164
+ const eviction = options?.eviction || "lru";
1165
+ if (eviction === "random") this.storage = new RandomIndexedDBStorage(options);
1166
+ else if (eviction === "lfu") this.storage = new LFUIndexedDBStorage(options);
1167
+ else if (eviction === "lru") this.storage = new LRUIndexedDBStorage(options);
1168
+ else if (eviction === "ttl") this.storage = new TTLIndexedDBStorage(options);
1169
+ else throw new CacheException(`Not Supported Eviction: ${String(options?.eviction)}`);
1170
+ }
1171
+ set(entry) {
1172
+ return this.storage.set(entry);
1173
+ }
1174
+ get(key) {
1175
+ return this.storage.get(key);
1176
+ }
1177
+ remove(key) {
1178
+ return this.storage.remove(key);
1179
+ }
1259
1180
  };
1260
-
1261
- // src/storage/multi-tier-storage/multi-tier-storage.ts
1181
+ //#endregion
1182
+ //#region src/storage/multi-tier-storage/multi-tier-storage.ts
1183
+ /**
1184
+ * @en Multi-tier cache storage that manages multiple KeqCacheStorage instances in tiers
1185
+ * @zh 多层缓存存储,管理多个分层的 KeqCacheStorage 实例
1186
+ */
1262
1187
  var MultiTierStorage = class extends KeqCacheStorage {
1263
- /**
1264
- * @param storages Array of storage instances ordered by performance (fastest first)
1265
- * @zh 按性价比排序的存储实例数组,排在前面的成本低,排在后面的成本高
1266
- */
1267
- constructor(options) {
1268
- super();
1269
- __publicField(this, "storages");
1270
- if (!options.tiers || options.tiers.length === 0) {
1271
- throw new Error("At least one storage instance is required");
1272
- }
1273
- this.storages = [...options.tiers];
1274
- }
1275
- /**
1276
- * @en Get cache entry, searching from lowest to highest tier
1277
- * @zh 获取缓存条目,从最底层到高层依次搜索
1278
- */
1279
- async get(key) {
1280
- for (let i = 0; i < this.storages.length; i++) {
1281
- const storage = this.storages[i];
1282
- const entry = await storage.get(key);
1283
- if (entry) {
1284
- if (i > 0) {
1285
- await this.syncToLowerTiers(entry, i);
1286
- }
1287
- return entry;
1288
- }
1289
- }
1290
- return void 0;
1291
- }
1292
- /**
1293
- * @en Set cache entry to all tiers concurrently
1294
- * @zh 并发写入所有层的缓存
1295
- */
1296
- async set(entry) {
1297
- const promises = this.storages.map(async (storage) => storage.set(entry));
1298
- await Promise.all(promises);
1299
- }
1300
- /**
1301
- * @en Remove cache entry from all tiers
1302
- * @zh 从所有层删除缓存条目
1303
- */
1304
- async remove(key) {
1305
- const promises = this.storages.map(async (storage) => storage.remove(key));
1306
- await Promise.all(promises);
1307
- }
1308
- /**
1309
- * @en Sync cache entry to all lower tiers (tiers with index < currentTierIndex)
1310
- * @zh 将缓存条目同步到所有低层存储(索引小于当前层的存储)
1311
- */
1312
- async syncToLowerTiers(entry, currentTierIndex) {
1313
- const lowerTierStorages = this.storages.slice(0, currentTierIndex);
1314
- if (lowerTierStorages.length === 0) {
1315
- return;
1316
- }
1317
- const promises = lowerTierStorages.map(async (storage) => storage.set(entry.clone()));
1318
- try {
1319
- await Promise.all(promises);
1320
- } catch (error) {
1321
- console.warn("Failed to sync cache entry to lower tiers:", error);
1322
- }
1323
- }
1188
+ /**
1189
+ * @param storages Array of storage instances ordered by performance (fastest first)
1190
+ * @zh 按性价比排序的存储实例数组,排在前面的成本低,排在后面的成本高
1191
+ */
1192
+ constructor(options) {
1193
+ super();
1194
+ _defineProperty(this, "storages", void 0);
1195
+ if (!options.tiers || options.tiers.length === 0) throw new Error("At least one storage instance is required");
1196
+ this.storages = [...options.tiers];
1197
+ }
1198
+ /**
1199
+ * @en Get cache entry, searching from lowest to highest tier
1200
+ * @zh 获取缓存条目,从最底层到高层依次搜索
1201
+ */
1202
+ async get(key) {
1203
+ for (let i = 0; i < this.storages.length; i++) {
1204
+ const entry = await this.storages[i].get(key);
1205
+ if (entry) {
1206
+ if (i > 0) await this.syncToLowerTiers(entry, i);
1207
+ return entry;
1208
+ }
1209
+ }
1210
+ }
1211
+ /**
1212
+ * @en Set cache entry to all tiers concurrently
1213
+ * @zh 并发写入所有层的缓存
1214
+ */
1215
+ async set(entry) {
1216
+ const promises = this.storages.map(async (storage) => storage.set(entry));
1217
+ await Promise.all(promises);
1218
+ }
1219
+ /**
1220
+ * @en Remove cache entry from all tiers
1221
+ * @zh 从所有层删除缓存条目
1222
+ */
1223
+ async remove(key) {
1224
+ const promises = this.storages.map(async (storage) => storage.remove(key));
1225
+ await Promise.all(promises);
1226
+ }
1227
+ /**
1228
+ * @en Sync cache entry to all lower tiers (tiers with index < currentTierIndex)
1229
+ * @zh 将缓存条目同步到所有低层存储(索引小于当前层的存储)
1230
+ */
1231
+ async syncToLowerTiers(entry, currentTierIndex) {
1232
+ const lowerTierStorages = this.storages.slice(0, currentTierIndex);
1233
+ if (lowerTierStorages.length === 0) return;
1234
+ const promises = lowerTierStorages.map(async (storage) => storage.set(entry.clone()));
1235
+ try {
1236
+ await Promise.all(promises);
1237
+ } catch (error) {
1238
+ console.warn("Failed to sync cache entry to lower tiers:", error);
1239
+ }
1240
+ }
1324
1241
  };
1325
-
1326
- // src/storage/tier-storage/tier-storage.ts
1242
+ //#endregion
1243
+ //#region src/storage/tier-storage/tier-storage.ts
1244
+ /**
1245
+ * @en Two-tier cache storage that combines MemoryStorage (L1) and IndexedDBStorage (L2)
1246
+ * @zh 二级缓存存储,结合了MemoryStorage(一级)和IndexedDBStorage(二级)
1247
+ *
1248
+ * This is a convenience wrapper around MultiTierStorage that provides:
1249
+ * - Fast in-memory cache (L1)
1250
+ * - Persistent IndexedDB cache (L2)
1251
+ * - Simplified configuration options
1252
+ */
1327
1253
  var TierStorage = class extends MultiTierStorage {
1328
- constructor(options) {
1329
- const memoryStorage = (options == null ? void 0 : options.memory) instanceof MemoryStorage ? options.memory : new MemoryStorage(options == null ? void 0 : options.memory);
1330
- const indexedDBStorage = (options == null ? void 0 : options.indexedDB) instanceof IndexedDBStorage ? options.indexedDB : new IndexedDBStorage(options == null ? void 0 : options.indexedDB);
1331
- super({
1332
- tiers: [memoryStorage, indexedDBStorage]
1333
- });
1334
- }
1254
+ constructor(options) {
1255
+ const memoryStorage = options?.memory instanceof MemoryStorage ? options.memory : new MemoryStorage(options?.memory);
1256
+ const indexedDBStorage = options?.indexedDB instanceof IndexedDBStorage ? options.indexedDB : new IndexedDBStorage(options?.indexedDB);
1257
+ super({ tiers: [memoryStorage, indexedDBStorage] });
1258
+ }
1335
1259
  };
1260
+ //#endregion
1261
+ exports.Eviction = Eviction;
1262
+ exports.IndexedDBStorage = IndexedDBStorage;
1263
+ exports.KeqCacheStorage = KeqCacheStorage;
1264
+ exports.MemoryStorage = MemoryStorage;
1265
+ exports.MultiTierStorage = MultiTierStorage;
1266
+ exports.Size = Size;
1267
+ exports.Strategy = Strategy;
1268
+ exports.TierStorage = TierStorage;
1269
+ exports.cache = cache;
1270
+
1336
1271
  //# sourceMappingURL=index.js.map