skillfit 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (371) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/README.zh-CN.md +224 -0
  4. package/benches/README.md +172 -0
  5. package/benches/code-review/bench.json +57 -0
  6. package/benches/code-review/fixtures/explain-x1/.skillfit-mock.json +10 -0
  7. package/benches/code-review/fixtures/explain-x1/SPEC.md +16 -0
  8. package/benches/code-review/fixtures/explain-x1/src/compact.js +18 -0
  9. package/benches/code-review/fixtures/explain-x1/tests/compact.test.js +18 -0
  10. package/benches/code-review/fixtures/review-r1/.skillfit-mock.json +10 -0
  11. package/benches/code-review/fixtures/review-r1/CHANGES.diff +42 -0
  12. package/benches/code-review/fixtures/review-r1/SPEC.md +16 -0
  13. package/benches/code-review/fixtures/review-r1/src/errors.js +7 -0
  14. package/benches/code-review/fixtures/review-r1/src/money.js +3 -0
  15. package/benches/code-review/fixtures/review-r1/src/order.js +13 -0
  16. package/benches/code-review/fixtures/review-r1/tests/order.test.js +17 -0
  17. package/benches/code-review/fixtures/review-r2/.skillfit-mock.json +10 -0
  18. package/benches/code-review/fixtures/review-r2/CHANGES.diff +81 -0
  19. package/benches/code-review/fixtures/review-r2/SPEC.md +25 -0
  20. package/benches/code-review/fixtures/review-r2/src/errors.js +7 -0
  21. package/benches/code-review/fixtures/review-r2/src/invoice.js +9 -0
  22. package/benches/code-review/fixtures/review-r2/src/money.js +3 -0
  23. package/benches/code-review/fixtures/review-r2/tests/invoice.test.js +13 -0
  24. package/benches/code-review/fixtures/review-r3/.skillfit-mock.json +10 -0
  25. package/benches/code-review/fixtures/review-r3/CHANGES.diff +76 -0
  26. package/benches/code-review/fixtures/review-r3/SPEC.md +24 -0
  27. package/benches/code-review/fixtures/review-r3/src/errors.js +7 -0
  28. package/benches/code-review/fixtures/review-r3/src/money.js +3 -0
  29. package/benches/code-review/fixtures/review-r3/src/pricing.js +20 -0
  30. package/benches/code-review/fixtures/review-r3/tests/pricing.test.js +15 -0
  31. package/benches/code-review/fixtures/summarize-s1/.skillfit-mock.json +16 -0
  32. package/benches/code-review/fixtures/summarize-s1/CHANGES.diff +27 -0
  33. package/benches/code-review/fixtures/summarize-s1/SPEC.md +15 -0
  34. package/benches/code-review/fixtures/summarize-s1/src/discount.js +20 -0
  35. package/benches/code-review/fixtures/summarize-s1/src/errors.js +7 -0
  36. package/benches/code-review/fixtures/summarize-s1/src/money.js +7 -0
  37. package/benches/code-review/ground-truth/oracle-r1.mjs +21 -0
  38. package/benches/code-review/ground-truth/oracle-r2.mjs +21 -0
  39. package/benches/code-review/ground-truth/oracle-r3.mjs +20 -0
  40. package/benches/code-review/ground-truth/oracle-summarize-s1.mjs +21 -0
  41. package/benches/code-review/ground-truth/oracle-x1.mjs +18 -0
  42. package/benches/code-review/ground-truth/r1.md +22 -0
  43. package/benches/code-review/ground-truth/r2.md +21 -0
  44. package/benches/code-review/ground-truth/r3.md +18 -0
  45. package/benches/code-review/ground-truth/summarize-s1.md +26 -0
  46. package/benches/code-review/ground-truth/x1.md +7 -0
  47. package/benches/code-review/prompts/explain-x1.md +5 -0
  48. package/benches/code-review/prompts/explain-x1.trigger.md +5 -0
  49. package/benches/code-review/prompts/review-r1.md +7 -0
  50. package/benches/code-review/prompts/review-r1.trigger.md +7 -0
  51. package/benches/code-review/prompts/review-r2.md +7 -0
  52. package/benches/code-review/prompts/review-r2.trigger.md +7 -0
  53. package/benches/code-review/prompts/review-r3.md +7 -0
  54. package/benches/code-review/prompts/review-r3.trigger.md +7 -0
  55. package/benches/code-review/prompts/summarize-s1.md +9 -0
  56. package/benches/code-review/prompts/summarize-s1.trigger.md +9 -0
  57. package/benches/code-review/verifiers/explain-x1.mjs +30 -0
  58. package/benches/code-review/verifiers/review-r2.mjs +66 -0
  59. package/benches/code-review/verifiers/review-r3.mjs +60 -0
  60. package/benches/code-review/verifiers/seeded-bugs.mjs +74 -0
  61. package/benches/code-review/verifiers/summarize-s1.mjs +80 -0
  62. package/benches/contrib/README.md +42 -0
  63. package/benches/contrib/oss-lru-cache/README.md +24 -0
  64. package/benches/contrib/oss-lru-cache/bench.json +37 -0
  65. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/LICENSE +15 -0
  66. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/README.md +3 -0
  67. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/index.js +1044 -0
  68. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/package.json +11 -0
  69. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/runtime.mjs +22 -0
  70. package/benches/contrib/oss-lru-cache/fixtures/fetch-abort/test.mjs +11 -0
  71. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/LICENSE.md +55 -0
  72. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/README.md +3 -0
  73. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/package.json +11 -0
  74. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/runtime.mjs +22 -0
  75. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/diagnostics-channel-browser.ts +11 -0
  76. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/diagnostics-channel-cjs.cts +11 -0
  77. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/diagnostics-channel-esm.mts +29 -0
  78. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/diagnostics-channel-node.ts +7 -0
  79. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/diagnostics-channel.ts +6 -0
  80. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/index.ts +3148 -0
  81. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/src/perf.ts +17 -0
  82. package/benches/contrib/oss-lru-cache/fixtures/fetch-lifecycle/test.mjs +11 -0
  83. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/LICENSE +15 -0
  84. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/README.md +3 -0
  85. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/index.js +1028 -0
  86. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/package.json +11 -0
  87. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/runtime.mjs +22 -0
  88. package/benches/contrib/oss-lru-cache/fixtures/fetch-size/test.mjs +11 -0
  89. package/benches/contrib/oss-lru-cache/ground-truth/fetch-abort/LICENSE +15 -0
  90. package/benches/contrib/oss-lru-cache/ground-truth/fetch-abort/index.js +1053 -0
  91. package/benches/contrib/oss-lru-cache/ground-truth/fetch-abort.md +11 -0
  92. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/LICENSE.md +55 -0
  93. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/diagnostics-channel-browser.ts +11 -0
  94. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/diagnostics-channel-cjs.cts +11 -0
  95. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/diagnostics-channel-esm.mts +29 -0
  96. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/diagnostics-channel-node.ts +7 -0
  97. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/diagnostics-channel.ts +6 -0
  98. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/index.ts +3174 -0
  99. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle/src/perf.ts +17 -0
  100. package/benches/contrib/oss-lru-cache/ground-truth/fetch-lifecycle.md +11 -0
  101. package/benches/contrib/oss-lru-cache/ground-truth/fetch-size/LICENSE +15 -0
  102. package/benches/contrib/oss-lru-cache/ground-truth/fetch-size/index.js +1028 -0
  103. package/benches/contrib/oss-lru-cache/ground-truth/fetch-size.md +11 -0
  104. package/benches/contrib/oss-lru-cache/ground-truth/oracle-fetch-abort.mjs +8 -0
  105. package/benches/contrib/oss-lru-cache/ground-truth/oracle-fetch-lifecycle.mjs +7 -0
  106. package/benches/contrib/oss-lru-cache/ground-truth/oracle-fetch-size.mjs +7 -0
  107. package/benches/contrib/oss-lru-cache/ground-truth/oracle.mjs +9 -0
  108. package/benches/contrib/oss-lru-cache/prompts/fetch-abort.md +5 -0
  109. package/benches/contrib/oss-lru-cache/prompts/fetch-lifecycle.md +5 -0
  110. package/benches/contrib/oss-lru-cache/prompts/fetch-size.md +5 -0
  111. package/benches/contrib/oss-lru-cache/provenance.json +62 -0
  112. package/benches/contrib/oss-lru-cache/runtime.mjs +22 -0
  113. package/benches/contrib/oss-lru-cache/verifiers/cases.mjs +74 -0
  114. package/benches/contrib/oss-lru-cache/verifiers/fetch-abort.mjs +3 -0
  115. package/benches/contrib/oss-lru-cache/verifiers/fetch-lifecycle.mjs +3 -0
  116. package/benches/contrib/oss-lru-cache/verifiers/fetch-size.mjs +3 -0
  117. package/benches/contrib/oss-lru-cache/verifiers/probe.mjs +14 -0
  118. package/benches/contrib/oss-lru-cache/verifiers/shared.mjs +130 -0
  119. package/benches/contrib/oss-lru-cache/verifiers/test-reporter.mjs +29 -0
  120. package/benches/contrib/oss-mcp-use-utf8/LICENSE.upstream +21 -0
  121. package/benches/contrib/oss-mcp-use-utf8/README.md +56 -0
  122. package/benches/contrib/oss-mcp-use-utf8/bench.json +16 -0
  123. package/benches/contrib/oss-mcp-use-utf8/fixtures/view-utf8/LICENSE +21 -0
  124. package/benches/contrib/oss-mcp-use-utf8/fixtures/view-utf8/package.json +3 -0
  125. package/benches/contrib/oss-mcp-use-utf8/fixtures/view-utf8/src/ext-apps-bridge.js +3 -0
  126. package/benches/contrib/oss-mcp-use-utf8/fixtures/view-utf8/src/resolve-view-resource.ts +96 -0
  127. package/benches/contrib/oss-mcp-use-utf8/fixtures/view-utf8/test/basic.test.mjs +13 -0
  128. package/benches/contrib/oss-mcp-use-utf8/ground-truth/README.md +5 -0
  129. package/benches/contrib/oss-mcp-use-utf8/ground-truth/oracle-view-utf8.mjs +11 -0
  130. package/benches/contrib/oss-mcp-use-utf8/ground-truth/solutions/view-utf8/src/resolve-view-resource.ts +96 -0
  131. package/benches/contrib/oss-mcp-use-utf8/ground-truth/solutions/view-utf8/test/utf8.regression.test.mjs +14 -0
  132. package/benches/contrib/oss-mcp-use-utf8/prompts/view-utf8.md +8 -0
  133. package/benches/contrib/oss-mcp-use-utf8/verifiers/view-utf8.mjs +120 -0
  134. package/benches/contrib/waza-behavior/LICENSE.upstream +21 -0
  135. package/benches/contrib/waza-behavior/README.md +31 -0
  136. package/benches/contrib/waza-behavior/bench.json +10 -0
  137. package/benches/contrib/waza-behavior/fixtures/explicit-hold/README.md +1 -0
  138. package/benches/contrib/waza-behavior/fixtures/explicit-hold/notes.txt +1 -0
  139. package/benches/contrib/waza-behavior/fixtures/receipt-current/README.md +1 -0
  140. package/benches/contrib/waza-behavior/fixtures/receipt-current/docs/guide.md +2 -0
  141. package/benches/contrib/waza-behavior/fixtures/receipt-current/notes.txt +1 -0
  142. package/benches/contrib/waza-behavior/fixtures/receipt-current/scripts/check-links.mjs +16 -0
  143. package/benches/contrib/waza-behavior/fixtures/receipt-current/validation-receipt.json +10 -0
  144. package/benches/contrib/waza-behavior/fixtures/receipt-stale/README.md +1 -0
  145. package/benches/contrib/waza-behavior/fixtures/receipt-stale/docs/guide.md +3 -0
  146. package/benches/contrib/waza-behavior/fixtures/receipt-stale/notes.txt +1 -0
  147. package/benches/contrib/waza-behavior/fixtures/receipt-stale/scripts/check-links.mjs +16 -0
  148. package/benches/contrib/waza-behavior/fixtures/receipt-stale/validation-receipt.json +10 -0
  149. package/benches/contrib/waza-behavior/ground-truth/oracle.mjs +24 -0
  150. package/benches/contrib/waza-behavior/prompts/explicit-hold.md +1 -0
  151. package/benches/contrib/waza-behavior/prompts/receipt-current.md +1 -0
  152. package/benches/contrib/waza-behavior/prompts/receipt-stale.md +1 -0
  153. package/benches/contrib/waza-behavior/verifiers/behavior.mjs +59 -0
  154. package/benches/debugging/bench.json +93 -0
  155. package/benches/debugging/fixtures/async-queue/src/task-queue.mjs +50 -0
  156. package/benches/debugging/fixtures/async-queue/test/basic.test.mjs +18 -0
  157. package/benches/debugging/fixtures/chunked-decoder/src/frame-decoder.mjs +39 -0
  158. package/benches/debugging/fixtures/chunked-decoder/test/basic.test.mjs +17 -0
  159. package/benches/debugging/fixtures/debug-redaction/src/debug-redaction.mjs +33 -0
  160. package/benches/debugging/fixtures/debug-redaction/test/basic.test.mjs +26 -0
  161. package/benches/debugging/fixtures/document-queue/.skillfit-mock.json +16 -0
  162. package/benches/debugging/fixtures/document-queue/src/task-queue.mjs +52 -0
  163. package/benches/debugging/fixtures/document-queue/test/basic.test.mjs +23 -0
  164. package/benches/debugging/fixtures/explain-cache/.skillfit-mock.json +16 -0
  165. package/benches/debugging/fixtures/explain-cache/src/ttl-cache.mjs +31 -0
  166. package/benches/debugging/fixtures/explain-cache/test/basic.test.mjs +28 -0
  167. package/benches/debugging/fixtures/feat-slug/test/slug.test.mjs +15 -0
  168. package/benches/debugging/fixtures/range-parser/src/range-parser.mjs +9 -0
  169. package/benches/debugging/fixtures/range-parser/test/basic.test.mjs +8 -0
  170. package/benches/debugging/fixtures/ttl-cache/src/ttl-cache.mjs +30 -0
  171. package/benches/debugging/fixtures/ttl-cache/test/basic.test.mjs +11 -0
  172. package/benches/debugging/ground-truth/async-queue.md +81 -0
  173. package/benches/debugging/ground-truth/chunked-decoder.md +91 -0
  174. package/benches/debugging/ground-truth/debug-redaction.md +113 -0
  175. package/benches/debugging/ground-truth/document-queue.md +24 -0
  176. package/benches/debugging/ground-truth/explain-cache.md +22 -0
  177. package/benches/debugging/ground-truth/feat-slug.md +45 -0
  178. package/benches/debugging/ground-truth/oracle-async-queue.mjs +14 -0
  179. package/benches/debugging/ground-truth/oracle-chunked-decoder.mjs +14 -0
  180. package/benches/debugging/ground-truth/oracle-debug-redaction.mjs +30 -0
  181. package/benches/debugging/ground-truth/oracle-document-queue.mjs +27 -0
  182. package/benches/debugging/ground-truth/oracle-explain-cache.mjs +28 -0
  183. package/benches/debugging/ground-truth/oracle-feat-slug.mjs +13 -0
  184. package/benches/debugging/ground-truth/oracle-range-parser.mjs +14 -0
  185. package/benches/debugging/ground-truth/oracle-ttl-cache.mjs +14 -0
  186. package/benches/debugging/ground-truth/range-parser.md +121 -0
  187. package/benches/debugging/ground-truth/solutions/async-queue/src/task-queue.mjs +52 -0
  188. package/benches/debugging/ground-truth/solutions/chunked-decoder/src/frame-decoder.mjs +50 -0
  189. package/benches/debugging/ground-truth/solutions/debug-redaction/src/debug-redaction.mjs +27 -0
  190. package/benches/debugging/ground-truth/solutions/debug-redaction/test/debug-leak.regression.test.mjs +27 -0
  191. package/benches/debugging/ground-truth/solutions/feat-slug/src/slug.mjs +6 -0
  192. package/benches/debugging/ground-truth/solutions/range-parser/src/range-parser.mjs +34 -0
  193. package/benches/debugging/ground-truth/solutions/range-parser/test/basic.test.mjs +26 -0
  194. package/benches/debugging/ground-truth/solutions/ttl-cache/src/ttl-cache.mjs +31 -0
  195. package/benches/debugging/ground-truth/ttl-cache.md +69 -0
  196. package/benches/debugging/prompts/async-queue.md +13 -0
  197. package/benches/debugging/prompts/async-queue.trigger.md +13 -0
  198. package/benches/debugging/prompts/chunked-decoder.md +13 -0
  199. package/benches/debugging/prompts/chunked-decoder.trigger.md +13 -0
  200. package/benches/debugging/prompts/debug-redaction.md +23 -0
  201. package/benches/debugging/prompts/debug-redaction.trigger.md +23 -0
  202. package/benches/debugging/prompts/document-queue.md +10 -0
  203. package/benches/debugging/prompts/document-queue.trigger.md +10 -0
  204. package/benches/debugging/prompts/explain-cache.md +10 -0
  205. package/benches/debugging/prompts/explain-cache.trigger.md +10 -0
  206. package/benches/debugging/prompts/feat-slug.md +3 -0
  207. package/benches/debugging/prompts/feat-slug.trigger.md +5 -0
  208. package/benches/debugging/prompts/range-parser.md +15 -0
  209. package/benches/debugging/prompts/range-parser.trigger.md +15 -0
  210. package/benches/debugging/prompts/ttl-cache.md +18 -0
  211. package/benches/debugging/prompts/ttl-cache.trigger.md +18 -0
  212. package/benches/debugging/verifiers/async-queue.mjs +221 -0
  213. package/benches/debugging/verifiers/chunked-decoder.mjs +208 -0
  214. package/benches/debugging/verifiers/debug-redaction.mjs +283 -0
  215. package/benches/debugging/verifiers/document-queue.mjs +52 -0
  216. package/benches/debugging/verifiers/explain-cache.mjs +62 -0
  217. package/benches/debugging/verifiers/feat-slug.mjs +127 -0
  218. package/benches/debugging/verifiers/range-parser.mjs +146 -0
  219. package/benches/debugging/verifiers/ttl-cache.mjs +111 -0
  220. package/dist/agents.js +26 -0
  221. package/dist/cli.js +310 -0
  222. package/dist/cli.test.js +76 -0
  223. package/dist/commands/bench.js +1035 -0
  224. package/dist/commands/bench.test.js +1061 -0
  225. package/dist/commands/bundle.js +334 -0
  226. package/dist/commands/bundle.test.js +142 -0
  227. package/dist/commands/confirm.js +39 -0
  228. package/dist/commands/doctor.js +399 -0
  229. package/dist/commands/doctor.test.js +280 -0
  230. package/dist/commands/eval-report.js +485 -0
  231. package/dist/commands/eval-report.test.js +306 -0
  232. package/dist/commands/eval.js +391 -0
  233. package/dist/commands/eval.test.js +446 -0
  234. package/dist/commands/install.js +653 -0
  235. package/dist/commands/install.test.js +555 -0
  236. package/dist/commands/mcp.js +20 -0
  237. package/dist/commands/report.js +78 -0
  238. package/dist/commands/report.test.js +110 -0
  239. package/dist/commands/setup.js +95 -0
  240. package/dist/commands/setup.test.js +150 -0
  241. package/dist/commands/upstream.js +210 -0
  242. package/dist/commands/upstream.test.js +139 -0
  243. package/dist/docs.test.js +154 -0
  244. package/dist/frontmatter.js +53 -0
  245. package/dist/frontmatter.test.js +49 -0
  246. package/dist/harness/bench.js +134 -0
  247. package/dist/harness/bench.test.js +109 -0
  248. package/dist/harness/bundle.js +46 -0
  249. package/dist/harness/bundle.test.js +71 -0
  250. package/dist/harness/constants.js +2 -0
  251. package/dist/harness/executors/api.js +68 -0
  252. package/dist/harness/executors/api.test.js +75 -0
  253. package/dist/harness/executors/cli.js +348 -0
  254. package/dist/harness/executors/cli.test.js +402 -0
  255. package/dist/harness/executors/mock.js +34 -0
  256. package/dist/harness/executors/mock.test.js +43 -0
  257. package/dist/harness/experiment-session.js +345 -0
  258. package/dist/harness/experiment-session.test.js +223 -0
  259. package/dist/harness/hash.js +29 -0
  260. package/dist/harness/installed-skill.js +78 -0
  261. package/dist/harness/installed-skill.test.js +162 -0
  262. package/dist/harness/judge.js +108 -0
  263. package/dist/harness/judge.test.js +181 -0
  264. package/dist/harness/kill-tree.js +43 -0
  265. package/dist/harness/kimi-usage.js +94 -0
  266. package/dist/harness/kimi-usage.test.js +62 -0
  267. package/dist/harness/oss-lru-cache.test.js +79 -0
  268. package/dist/harness/oss-regression-witness.test.js +89 -0
  269. package/dist/harness/prompt.js +57 -0
  270. package/dist/harness/prompt.test.js +48 -0
  271. package/dist/harness/receipts.js +297 -0
  272. package/dist/harness/receipts.test.js +148 -0
  273. package/dist/harness/report.js +225 -0
  274. package/dist/harness/report.test.js +297 -0
  275. package/dist/harness/runner.js +629 -0
  276. package/dist/harness/runner.test.js +555 -0
  277. package/dist/harness/stats.js +93 -0
  278. package/dist/harness/stats.test.js +124 -0
  279. package/dist/harness/target.js +90 -0
  280. package/dist/harness/target.test.js +60 -0
  281. package/dist/harness/trigger.js +368 -0
  282. package/dist/harness/trigger.test.js +249 -0
  283. package/dist/harness/types.js +1 -0
  284. package/dist/harness/verifier-summary.js +59 -0
  285. package/dist/harness/verifier-summary.test.js +99 -0
  286. package/dist/harness/waza-behavior.test.js +139 -0
  287. package/dist/invocation.js +21 -0
  288. package/dist/matrix/agents.json +200 -0
  289. package/dist/matrix/agents.schema.json +152 -0
  290. package/dist/mcp/probe.js +317 -0
  291. package/dist/mcp/probe.test.js +87 -0
  292. package/dist/version.js +4 -0
  293. package/docs/assets/skillfit-flow.en.svg +47 -0
  294. package/docs/assets/skillfit-flow.zh-CN.svg +47 -0
  295. package/docs/assets/skillfit-mark.svg +9 -0
  296. package/docs/audit-2026-09-24-triage.md +231 -0
  297. package/docs/audit-2026-09-24.md +876 -0
  298. package/docs/bench-authoring.md +407 -0
  299. package/docs/codex-upstream-audit.md +41 -0
  300. package/docs/config-experiments.md +119 -0
  301. package/docs/examples/bench-check.yml +32 -0
  302. package/docs/examples/eval-manifest.synthetic.json +61 -0
  303. package/docs/experiment-workflow.md +15 -0
  304. package/docs/first-real-eval.md +90 -0
  305. package/docs/growth-roadmap-2026-10.md +100 -0
  306. package/docs/installed-skill-evaluation.md +77 -0
  307. package/docs/metrics.md +318 -0
  308. package/docs/oss-task-evaluation.md +139 -0
  309. package/docs/plans/2026-10-01-oss-task-evaluation.md +73 -0
  310. package/docs/plans/2026-10-09-experiment-workflow.md +18 -0
  311. package/docs/plans/2026-10-09-grader-calibration-audit.md +13 -0
  312. package/docs/plans/2026-10-09-waza-resource-evaluation.md +46 -0
  313. package/docs/portable-codex.md +31 -0
  314. package/docs/reproducible-offline-example.md +29 -0
  315. package/docs/selectable-codex.md +41 -0
  316. package/docs/sharing-results.md +53 -0
  317. package/evidence/2026-07-skill-baseline.md +34 -0
  318. package/evidence/2026-09-22-codex-trigger-capture.md +36 -0
  319. package/evidence/2026-09-bench-calibration.md +46 -0
  320. package/evidence/2026-09-debugging-bench-exploratory.md +55 -0
  321. package/evidence/2026-09-debugging-hardening.md +42 -0
  322. package/evidence/2026-09-ocr-vs-code-review.md +31 -0
  323. package/evidence/2026-09-trigger-snapshot-correction.md +48 -0
  324. package/evidence/2026-10-01-codex-diagnosing-bugs-pilot.md +58 -0
  325. package/evidence/2026-10-01-oss-case-selection.md +42 -0
  326. package/evidence/2026-10-01-oss-workspace-smoke.md +110 -0
  327. package/evidence/README.md +47 -0
  328. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/README.md +27 -0
  329. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/artifact-index.json +118 -0
  330. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/output.md +5 -0
  331. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/prompt.txt +14 -0
  332. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/result.json +65 -0
  333. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/verifier.txt +2 -0
  334. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/LICENSE +21 -0
  335. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/package.json +3 -0
  336. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/src/ext-apps-bridge.js +3 -0
  337. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/src/resolve-view-resource.ts +100 -0
  338. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/test/basic.test.mjs +13 -0
  339. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/baseline/workspace/test/resolve-view-resource.test.mjs +102 -0
  340. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/manifest.json +206 -0
  341. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/original-console.txt +44 -0
  342. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/report.md +67 -0
  343. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/output.md +5 -0
  344. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/prompt.txt +163 -0
  345. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/result.json +65 -0
  346. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/verifier.txt +2 -0
  347. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/LICENSE +21 -0
  348. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/package.json +3 -0
  349. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/src/ext-apps-bridge.js +3 -0
  350. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/src/resolve-view-resource.ts +100 -0
  351. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/test/basic.test.mjs +13 -0
  352. package/evidence/artifacts/2026-10-01-oss-workspace-smoke/treatment/workspace/test/resolve-view-resource.test.mjs +136 -0
  353. package/evidence/inputs/README.md +15 -0
  354. package/evidence/inputs/diagnosing-bugs/LICENSE +21 -0
  355. package/evidence/inputs/diagnosing-bugs/SKILL.md +138 -0
  356. package/evidence/inputs/diagnosing-bugs/agents/openai.yaml +3 -0
  357. package/evidence/inputs/diagnosing-bugs/scripts/hitl-loop.template.sh +44 -0
  358. package/evidence/plans/2026-10-01-oss-workspace-smoke.json +29 -0
  359. package/package.json +47 -4
  360. package/profiles/codex-curated/catalog.json +28 -0
  361. package/profiles/codex-curated/profile.json +282 -0
  362. package/profiles/codex-curated/rules/global.md +12 -0
  363. package/profiles/codex-curated/skills/autonomous-iteration/SKILL.md +75 -0
  364. package/profiles/codex-curated/skills/autonomous-iteration/agents/openai.yaml +4 -0
  365. package/profiles/codex-curated/skills/vibe-coding/SKILL.md +45 -0
  366. package/profiles/codex-curated/skills/vibe-coding/agents/openai.yaml +4 -0
  367. package/profiles/codex-upstream-sources.json +2980 -0
  368. package/profiles/recommended/profile.json +12 -0
  369. package/profiles/recommended/rules/core-workflow.md +41 -0
  370. package/profiles/recommended/skills/commit-message/SKILL.md +18 -0
  371. package/skills/skillfit/SKILL.md +60 -0
@@ -0,0 +1,3148 @@
1
+ /**
2
+ * @module LRUCache
3
+ */
4
+
5
+ import { metrics, tracing } from './diagnostics-channel.js'
6
+ import { defaultPerf } from './perf.js'
7
+ import type { Perf } from './perf.js'
8
+ export type { Perf } from './perf.js'
9
+
10
+ const hasSubscribers = () =>
11
+ metrics.hasSubscribers || tracing.hasSubscribers
12
+
13
+ const warned = new Set<string>()
14
+
15
+ // either a function or a class
16
+ // oxlint-disable-next-line no-explicit-any
17
+ type ForC = ((...a: any[]) => any) | { new (...a: any[]): any }
18
+
19
+ /* c8 ignore start */
20
+ const PROCESS = (
21
+ typeof process === 'object' && !!process ?
22
+ process
23
+ : {}) as { [k: string]: unknown }
24
+ /* c8 ignore stop */
25
+
26
+ const emitWarning = (
27
+ msg: string,
28
+ type: string,
29
+ code: string,
30
+ fn: ForC,
31
+ ) => {
32
+ if (typeof PROCESS.emitWarning === 'function') {
33
+ PROCESS.emitWarning(msg, type, code, fn)
34
+ } else {
35
+ //oxlint-disable-next-line no-console
36
+ console.error(`[${code}] ${type}: ${msg}`)
37
+ }
38
+ }
39
+ const shouldWarn = (code: string) => !warned.has(code)
40
+
41
+ const TYPE = Symbol('type')
42
+ export type PosInt = number & { [TYPE]: 'Positive Integer' }
43
+ export type Index = number & { [TYPE]: 'LRUCache Index' }
44
+
45
+ const isPosInt = (n: unknown): n is PosInt =>
46
+ !!n && n === Math.floor(n as number) && n > 0 && isFinite(n)
47
+
48
+ export type UintArray = Uint8Array | Uint16Array | Uint32Array
49
+ export type NumberArray = UintArray | number[]
50
+
51
+ // This is a little bit ridiculous, tbh.
52
+ // The maximum array length is 2^32-1 or thereabouts on most JS impls.
53
+ // And well before that point, you're caching the entire world, I mean,
54
+ // that's ~32GB of just integers for the next/prev links, plus whatever
55
+ // else to hold that many keys and values. Just filling the memory with
56
+ // zeroes at init time is brutal when you get that big.
57
+ // But why not be complete?
58
+ // Maybe in the future, these limits will have expanded.
59
+ /* c8 ignore start */
60
+ const getUintArray = (max: number) =>
61
+ !isPosInt(max) ? null
62
+ : max <= Math.pow(2, 8) ? Uint8Array
63
+ : max <= Math.pow(2, 16) ? Uint16Array
64
+ : max <= Math.pow(2, 32) ? Uint32Array
65
+ : max <= Number.MAX_SAFE_INTEGER ? ZeroArray
66
+ : null
67
+ /* c8 ignore stop */
68
+
69
+ class ZeroArray extends Array<number> {
70
+ constructor(size: number) {
71
+ super(size)
72
+ this.fill(0)
73
+ }
74
+ }
75
+ export type { ZeroArray }
76
+ export type { Stack }
77
+
78
+ export type StackLike = Stack | Index[]
79
+ class Stack {
80
+ /* c8 ignore start - not sure why this is showing up uncovered?? */
81
+ heap: NumberArray
82
+ /* c8 ignore stop */
83
+ length: number
84
+ // private constructor
85
+ static #constructing: boolean = false
86
+ static create(max: number): StackLike {
87
+ const HeapCls = getUintArray(max)
88
+ if (!HeapCls) return []
89
+ Stack.#constructing = true
90
+ const s = new Stack(max, HeapCls)
91
+ Stack.#constructing = false
92
+ return s
93
+ }
94
+ constructor(max: number, HeapCls: { new (n: number): NumberArray }) {
95
+ /* c8 ignore start */
96
+ if (!Stack.#constructing) {
97
+ throw new TypeError('instantiate Stack using Stack.create(n)')
98
+ }
99
+ /* c8 ignore stop */
100
+ this.heap = new HeapCls(max)
101
+ this.length = 0
102
+ }
103
+ push(n: Index) {
104
+ this.heap[this.length++] = n
105
+ }
106
+ pop(): Index {
107
+ return this.heap[--this.length] as Index
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Promise representing an in-progress {@link LRUCache#fetch} call
113
+ */
114
+ export type BackgroundFetch<V> = Promise<V | undefined> & {
115
+ __returned: BackgroundFetch<V> | undefined
116
+ __abortController: AbortController
117
+ __staleWhileFetching: V | undefined
118
+ }
119
+
120
+ export type DisposeTask<K, V> = [
121
+ value: V,
122
+ key: K,
123
+ reason: LRUCache.DisposeReason,
124
+ ]
125
+
126
+ export namespace LRUCache {
127
+ /**
128
+ * An integer greater than 0, reflecting the calculated size of items
129
+ */
130
+ export type Size = number
131
+
132
+ /**
133
+ * Integer greater than 0, representing some number of milliseconds, or the
134
+ * time at which a TTL started counting from.
135
+ */
136
+ export type Milliseconds = number
137
+
138
+ /**
139
+ * An integer greater than 0, reflecting a number of items
140
+ */
141
+ export type Count = number
142
+
143
+ /**
144
+ * The reason why an item was removed from the cache, passed
145
+ * to the {@link Disposer} methods.
146
+ *
147
+ * - `evict`: The item was evicted because it is the least recently used,
148
+ * and the cache is full.
149
+ * - `set`: A new value was set, overwriting the old value being disposed.
150
+ * - `delete`: The item was explicitly deleted, either by calling
151
+ * {@link LRUCache#delete}, {@link LRUCache#clear}, or
152
+ * {@link LRUCache#set} with an undefined value.
153
+ * - `expire`: The item was removed due to exceeding its TTL.
154
+ * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned
155
+ * `undefined` or was aborted, causing the item to be deleted.
156
+ */
157
+ export type DisposeReason =
158
+ | 'evict'
159
+ | 'set'
160
+ | 'delete'
161
+ | 'expire'
162
+ | 'fetch'
163
+ /**
164
+ * A method called upon item removal, passed as the
165
+ * {@link OptionsBase.dispose} and/or
166
+ * {@link OptionsBase.disposeAfter} options.
167
+ */
168
+ export type Disposer<K, V> = (
169
+ value: V,
170
+ key: K,
171
+ reason: DisposeReason,
172
+ ) => void
173
+
174
+ /**
175
+ * The reason why an item was added to the cache, passed
176
+ * to the {@link Inserter} methods.
177
+ *
178
+ * - `add`: the item was not found in the cache, and was added
179
+ * - `update`: the item was in the cache, with the same value provided
180
+ * - `replace`: the item was in the cache, and replaced
181
+ */
182
+ export type InsertReason = 'add' | 'update' | 'replace'
183
+
184
+ /**
185
+ * A method called upon item insertion, passed as the
186
+ * {@link OptionsBase.insert}
187
+ */
188
+ export type Inserter<K, V> = (
189
+ value: V,
190
+ key: K,
191
+ reason: InsertReason,
192
+ ) => void
193
+
194
+ /**
195
+ * A function that returns the effective calculated size
196
+ * of an entry in the cache.
197
+ */
198
+ export type SizeCalculator<K, V> = (value: V, key: K) => Size
199
+
200
+ /**
201
+ * Options provided to the
202
+ * {@link OptionsBase.fetchMethod} function.
203
+ */
204
+ export interface FetcherOptions<K, V, FC = unknown> {
205
+ signal: AbortSignal
206
+ options: FetcherFetchOptions<K, V, FC>
207
+ /**
208
+ * Object provided in the {@link FetchOptions.context} option to
209
+ * {@link LRUCache#fetch}
210
+ */
211
+ context: FC
212
+ }
213
+
214
+ /**
215
+ * Occasionally, it may be useful to track the internal behavior of the
216
+ * cache, particularly for logging, debugging, or for behavior within the
217
+ * `fetchMethod`. To do this, you can pass a `status` object to the
218
+ * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},
219
+ * {@link LRUCache#memo}, and {@link LRUCache#has} methods.
220
+ *
221
+ * The `status` option should be a plain JavaScript object. The following
222
+ * fields will be set on it appropriately, depending on the situation.
223
+ *
224
+ * These objects are also the context objects passed to listeners on the
225
+ * `lru-cache:metrics` diagnostic channel, and the `lru-cache` tracing
226
+ * channels, in platforms that support them.
227
+ */
228
+ export interface Status<K, V> {
229
+ /**
230
+ * The operation being performed
231
+ */
232
+ op?: 'get' | 'set' | 'memo' | 'fetch' | 'delete' | 'has' | 'peek'
233
+ /**
234
+ * The status of a set() operation.
235
+ *
236
+ * - add: the item was not found in the cache, and was added
237
+ * - update: the item was in the cache, with the same value provided
238
+ * - replace: the item was in the cache, and replaced
239
+ * - miss: the item was not added to the cache for some reason
240
+ */
241
+ set?: 'add' | 'update' | 'replace' | 'miss' | 'deleted'
242
+
243
+ /**
244
+ * The status of a delete() operation.
245
+ */
246
+ delete?: LRUCache.DisposeReason
247
+
248
+ /**
249
+ * The result of a peek() operation
250
+ *
251
+ * - hit: the item was found and returned
252
+ * - stale: the item is in the cache, but past its ttl and not returned
253
+ * - miss: item not in the cache
254
+ */
255
+ peek?: 'hit' | 'miss' | 'stale'
256
+
257
+ /**
258
+ * The status of a memo() operation.
259
+ *
260
+ * - 'hit': the item was found in the cache and returned
261
+ * - 'miss': the `memoMethod` function was called
262
+ */
263
+ memo?: 'hit' | 'miss'
264
+
265
+ /**
266
+ * The `context` option provided to a memo or fetch operation
267
+ *
268
+ * In practice, of course, this will be the same type as the `FC`
269
+ * fetch context param used to instantiate the LRUCache, but the
270
+ * convolutions of threading that through would get quite complicated,
271
+ * and preclude forcing/forbidding the passing of a `context` param
272
+ * where it is/isn't expected, which is more valuable for error
273
+ * prevention.
274
+ */
275
+ context?: unknown
276
+
277
+ /**
278
+ * the ttl stored for the item, or undefined if ttls are not used.
279
+ */
280
+ ttl?: Milliseconds
281
+
282
+ /**
283
+ * the start time for the item, or undefined if ttls are not used.
284
+ */
285
+ start?: Milliseconds
286
+
287
+ /**
288
+ * The timestamp used for TTL calculation
289
+ */
290
+ now?: Milliseconds
291
+
292
+ /**
293
+ * the remaining ttl for the item, or undefined if ttls are not used.
294
+ */
295
+ remainingTTL?: Milliseconds
296
+
297
+ /**
298
+ * The calculated size for the item, if sizes are used.
299
+ */
300
+ entrySize?: Size
301
+
302
+ /**
303
+ * The total calculated size of the cache, if sizes are used.
304
+ */
305
+ totalCalculatedSize?: Size
306
+
307
+ /**
308
+ * A flag indicating that the item was not stored, due to exceeding the
309
+ * {@link OptionsBase.maxEntrySize}
310
+ */
311
+ maxEntrySizeExceeded?: true
312
+
313
+ /**
314
+ * The key that was set or retrieved
315
+ */
316
+ key?: K
317
+
318
+ /**
319
+ * The value that was set
320
+ */
321
+ value?: V
322
+
323
+ /**
324
+ * The old value, specified in the case of `set:'replace'`
325
+ */
326
+ oldValue?: V
327
+
328
+ /**
329
+ * The results of a {@link LRUCache#has} operation
330
+ *
331
+ * - hit: the item was found in the cache
332
+ * - stale: the item was found in the cache, but is stale
333
+ * - miss: the item was not found in the cache
334
+ */
335
+ has?: 'hit' | 'stale' | 'miss'
336
+
337
+ /**
338
+ * The status of a {@link LRUCache#fetch} operation.
339
+ * Note that this can change as the underlying fetch() moves through
340
+ * various states.
341
+ *
342
+ * - inflight: there is another fetch() for this key which is in process
343
+ * - get: there is no {@link OptionsBase.fetchMethod}, so
344
+ * {@link LRUCache#get} was called.
345
+ * - miss: the item is not in cache, and will be fetched.
346
+ * - hit: the item is in the cache, and was resolved immediately.
347
+ * - stale: the item is in the cache, but stale.
348
+ * - refresh: the item is in the cache, and not stale, but
349
+ * {@link FetchOptions.forceRefresh} was specified.
350
+ */
351
+ fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'
352
+
353
+ /**
354
+ * `forceRefresh` option was used for either a fetch or memo operation
355
+ */
356
+ forceRefresh?: boolean
357
+
358
+ /**
359
+ * The {@link OptionsBase.fetchMethod} was called
360
+ */
361
+ fetchDispatched?: true
362
+
363
+ /**
364
+ * The cached value was updated after a successful call to
365
+ * {@link OptionsBase.fetchMethod}
366
+ */
367
+ fetchUpdated?: true
368
+
369
+ /**
370
+ * The reason for a fetch() rejection. Either the error raised by the
371
+ * {@link OptionsBase.fetchMethod}, or the reason for an
372
+ * AbortSignal.
373
+ */
374
+ fetchError?: Error
375
+
376
+ /**
377
+ * The fetch received an abort signal
378
+ */
379
+ fetchAborted?: true
380
+
381
+ /**
382
+ * The abort signal received was ignored, and the fetch was allowed to
383
+ * continue in the background.
384
+ */
385
+ fetchAbortIgnored?: true
386
+
387
+ /**
388
+ * The fetchMethod promise resolved successfully
389
+ */
390
+ fetchResolved?: true
391
+
392
+ /**
393
+ * The fetchMethod promise was rejected
394
+ */
395
+ fetchRejected?: true
396
+
397
+ /**
398
+ * The status of a {@link LRUCache#get} operation.
399
+ *
400
+ * - fetching: The item is currently being fetched. If a previous value
401
+ * is present and allowed, that will be returned.
402
+ * - stale: The item is in the cache, and is stale. If it was returned,
403
+ * then the `returnedStale` flag will be set.
404
+ * - stale-fetching: The value is being fetched in the background, but is
405
+ * currently stale. If the stale value was returned, then the
406
+ * `returnedStale` flag will be set.
407
+ * - hit: the item is in the cache
408
+ * - miss: the item is not in the cache
409
+ */
410
+ get?: 'stale' | 'hit' | 'miss' | 'fetching' | 'stale-fetching'
411
+
412
+ /**
413
+ * A fetch or get operation returned a stale value.
414
+ */
415
+ returnedStale?: true
416
+
417
+ /**
418
+ * A tracingChannel trace was started for this operation
419
+ */
420
+ trace?: boolean
421
+ }
422
+
423
+ /**
424
+ * options which override the options set in the LRUCache constructor
425
+ * when calling {@link LRUCache#fetch}.
426
+ *
427
+ * This is the union of {@link GetOptions} and {@link SetOptions}, plus
428
+ * {@link OptionsBase.noDeleteOnFetchRejection},
429
+ * {@link OptionsBase.allowStaleOnFetchRejection},
430
+ * {@link FetchOptions.forceRefresh}, and
431
+ * {@link FetcherOptions.context}
432
+ *
433
+ * Any of these may be modified in the {@link OptionsBase.fetchMethod}
434
+ * function, but the {@link GetOptions} fields will of course have no
435
+ * effect, as the {@link LRUCache#get} call already happened by the time
436
+ * the fetchMethod is called.
437
+ */
438
+ export interface FetcherFetchOptions<K, V, FC = unknown> extends Pick<
439
+ OptionsBase<K, V, FC>,
440
+ | 'allowStale'
441
+ | 'updateAgeOnGet'
442
+ | 'noDeleteOnStaleGet'
443
+ | 'sizeCalculation'
444
+ | 'ttl'
445
+ | 'noDisposeOnSet'
446
+ | 'noUpdateTTL'
447
+ | 'noDeleteOnFetchRejection'
448
+ | 'allowStaleOnFetchRejection'
449
+ | 'ignoreFetchAbort'
450
+ | 'allowStaleOnFetchAbort'
451
+ > {
452
+ status?: Status<K, V>
453
+ size?: Size
454
+ }
455
+
456
+ /**
457
+ * Options that may be passed to the {@link LRUCache#fetch} method.
458
+ */
459
+ export interface FetchOptions<K, V, FC> extends FetcherFetchOptions<
460
+ K,
461
+ V,
462
+ FC
463
+ > {
464
+ /**
465
+ * Set to true to force a re-load of the existing data, even if it
466
+ * is not yet stale.
467
+ */
468
+ forceRefresh?: boolean
469
+ /**
470
+ * Context provided to the {@link OptionsBase.fetchMethod} as
471
+ * the {@link FetcherOptions.context} param.
472
+ *
473
+ * If the FC type is specified as unknown (the default),
474
+ * undefined or void, then this is optional. Otherwise, it will
475
+ * be required.
476
+ */
477
+ context?: FC
478
+ signal?: AbortSignal
479
+ status?: Status<K, V>
480
+ }
481
+ /**
482
+ * Options provided to {@link LRUCache#fetch} when the FC type is something
483
+ * other than `unknown`, `undefined`, or `void`
484
+ */
485
+ export interface FetchOptionsWithContext<K, V, FC> extends FetchOptions<
486
+ K,
487
+ V,
488
+ FC
489
+ > {
490
+ context: FC
491
+ }
492
+ /**
493
+ * Options provided to {@link LRUCache#fetch} when the FC type is
494
+ * `undefined` or `void`
495
+ */
496
+ export interface FetchOptionsNoContext<K, V> extends FetchOptions<
497
+ K,
498
+ V,
499
+ undefined
500
+ > {
501
+ context?: undefined
502
+ }
503
+
504
+ export interface MemoOptions<K, V, FC = unknown> extends Pick<
505
+ OptionsBase<K, V, FC>,
506
+ | 'allowStale'
507
+ | 'updateAgeOnGet'
508
+ | 'noDeleteOnStaleGet'
509
+ | 'sizeCalculation'
510
+ | 'ttl'
511
+ | 'noDisposeOnSet'
512
+ | 'noUpdateTTL'
513
+ | 'noDeleteOnFetchRejection'
514
+ | 'allowStaleOnFetchRejection'
515
+ | 'ignoreFetchAbort'
516
+ | 'allowStaleOnFetchAbort'
517
+ > {
518
+ /**
519
+ * Set to true to force a re-load of the existing data, even if it
520
+ * is not yet stale.
521
+ */
522
+ forceRefresh?: boolean
523
+ /**
524
+ * Context provided to the {@link OptionsBase.memoMethod} as
525
+ * the {@link MemoizerOptions.context} param.
526
+ *
527
+ * If the FC type is specified as unknown (the default),
528
+ * undefined or void, then this is optional. Otherwise, it will
529
+ * be required.
530
+ */
531
+ context?: FC
532
+ status?: Status<K, V>
533
+ }
534
+ /**
535
+ * Options provided to {@link LRUCache#memo} when the FC type is something
536
+ * other than `unknown`, `undefined`, or `void`
537
+ */
538
+ export interface MemoOptionsWithContext<K, V, FC> extends MemoOptions<
539
+ K,
540
+ V,
541
+ FC
542
+ > {
543
+ context: FC
544
+ }
545
+ /**
546
+ * Options provided to {@link LRUCache#memo} when the FC type is
547
+ * `undefined` or `void`
548
+ */
549
+ export interface MemoOptionsNoContext<K, V> extends MemoOptions<
550
+ K,
551
+ V,
552
+ undefined
553
+ > {
554
+ context?: undefined
555
+ }
556
+
557
+ /**
558
+ * Options provided to the
559
+ * {@link OptionsBase.memoMethod} function.
560
+ */
561
+ export interface MemoizerOptions<K, V, FC = unknown> {
562
+ options: MemoizerMemoOptions<K, V, FC>
563
+ /**
564
+ * Object provided in the {@link MemoOptions.context} option to
565
+ * {@link LRUCache#memo}
566
+ */
567
+ context: FC
568
+ }
569
+
570
+ /**
571
+ * options which override the options set in the LRUCache constructor
572
+ * when calling {@link LRUCache#memo}.
573
+ *
574
+ * This is the union of {@link GetOptions} and {@link SetOptions}, plus
575
+ * {@link MemoOptions.forceRefresh}, and
576
+ * {@link MemoOptions.context}
577
+ *
578
+ * Any of these may be modified in the {@link OptionsBase.memoMethod}
579
+ * function, but the {@link GetOptions} fields will of course have no
580
+ * effect, as the {@link LRUCache#get} call already happened by the time
581
+ * the memoMethod is called.
582
+ */
583
+ export interface MemoizerMemoOptions<K, V, FC = unknown> extends Pick<
584
+ OptionsBase<K, V, FC>,
585
+ | 'allowStale'
586
+ | 'updateAgeOnGet'
587
+ | 'noDeleteOnStaleGet'
588
+ | 'sizeCalculation'
589
+ | 'ttl'
590
+ | 'noDisposeOnSet'
591
+ | 'noUpdateTTL'
592
+ > {
593
+ status?: Status<K, V>
594
+ size?: Size
595
+ start?: Milliseconds
596
+ }
597
+
598
+ /**
599
+ * Options that may be passed to the {@link LRUCache#has} method.
600
+ */
601
+ export interface HasOptions<K, V, FC> extends Pick<
602
+ OptionsBase<K, V, FC>,
603
+ 'updateAgeOnHas'
604
+ > {
605
+ status?: Status<K, V>
606
+ }
607
+
608
+ /**
609
+ * Options that may be passed to the {@link LRUCache#get} method.
610
+ */
611
+ export interface GetOptions<K, V, FC> extends Pick<
612
+ OptionsBase<K, V, FC>,
613
+ 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'
614
+ > {
615
+ status?: Status<K, V>
616
+ }
617
+
618
+ /**
619
+ * Options that may be passed to the {@link LRUCache#peek} method.
620
+ */
621
+ export interface PeekOptions<K, V, FC> extends Pick<
622
+ OptionsBase<K, V, FC>,
623
+ 'allowStale'
624
+ > {
625
+ status?: Status<K, V>
626
+ }
627
+
628
+ /**
629
+ * Options that may be passed to the {@link LRUCache#set} method.
630
+ */
631
+ export interface SetOptions<K, V, FC> extends Pick<
632
+ OptionsBase<K, V, FC>,
633
+ 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'
634
+ > {
635
+ /**
636
+ * If size tracking is enabled, then setting an explicit size
637
+ * in the {@link LRUCache#set} call will prevent calling the
638
+ * {@link OptionsBase.sizeCalculation} function.
639
+ */
640
+ size?: Size
641
+ /**
642
+ * If TTL tracking is enabled, then setting an explicit start
643
+ * time in the {@link LRUCache#set} call will override the
644
+ * default time from `performance.now()` or `Date.now()`.
645
+ *
646
+ * Note that it must be a valid value for whichever time-tracking
647
+ * method is in use.
648
+ */
649
+ start?: Milliseconds
650
+ status?: Status<K, V>
651
+ }
652
+
653
+ /**
654
+ * The type signature for the {@link OptionsBase.fetchMethod} option.
655
+ */
656
+ export type Fetcher<K, V, FC = unknown> = (
657
+ key: K,
658
+ staleValue: V | undefined,
659
+ options: FetcherOptions<K, V, FC>,
660
+ ) => Promise<V | undefined | void> | V | undefined | void
661
+
662
+ /**
663
+ * the type signature for the {@link OptionsBase.memoMethod} option.
664
+ */
665
+ export type Memoizer<K, V, FC = unknown> = (
666
+ key: K,
667
+ staleValue: V | undefined,
668
+ options: MemoizerOptions<K, V, FC>,
669
+ ) => V
670
+
671
+ /**
672
+ * Options which may be passed to the {@link LRUCache} constructor.
673
+ *
674
+ * Most of these may be overridden in the various options that use
675
+ * them.
676
+ *
677
+ * Despite all being technically optional, the constructor requires that
678
+ * a cache is at minimum limited by one or more of {@link OptionsBase.max},
679
+ * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.
680
+ *
681
+ * If {@link OptionsBase.ttl} is used alone, then it is strongly advised
682
+ * (and in fact required by the type definitions here) that the cache
683
+ * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially
684
+ * unbounded storage.
685
+ *
686
+ * All options are also available on the {@link LRUCache} instance, making
687
+ * it safe to pass an LRUCache instance as the options argumemnt to
688
+ * make another empty cache of the same type.
689
+ *
690
+ * Some options are marked as read-only, because changing them after
691
+ * instantiation is not safe. Changing any of the other options will of
692
+ * course only have an effect on subsequent method calls.
693
+ */
694
+ export interface OptionsBase<K, V, FC> {
695
+ /**
696
+ * The maximum number of items to store in the cache before evicting
697
+ * old entries. This is read-only on the {@link LRUCache} instance,
698
+ * and may not be overridden.
699
+ *
700
+ * If set, then storage space will be pre-allocated at construction
701
+ * time, and the cache will perform significantly faster.
702
+ *
703
+ * Note that significantly fewer items may be stored, if
704
+ * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also
705
+ * set.
706
+ *
707
+ * **It is strongly recommended to set a `max` to prevent unbounded growth
708
+ * of the cache.**
709
+ */
710
+ max?: Count
711
+
712
+ /**
713
+ * Max time in milliseconds for items to live in cache before they are
714
+ * considered stale. Note that stale items are NOT preemptively removed by
715
+ * default, and MAY live in the cache, contributing to its LRU max, long
716
+ * after they have expired, unless {@link OptionsBase.ttlAutopurge} is
717
+ * set.
718
+ *
719
+ * If set to `0` (the default value), then that means "do not track
720
+ * TTL", not "expire immediately".
721
+ *
722
+ * Also, as this cache is optimized for LRU/MRU operations, some of
723
+ * the staleness/TTL checks will reduce performance, as they will incur
724
+ * overhead by deleting items.
725
+ *
726
+ * This is not primarily a TTL cache, and does not make strong TTL
727
+ * guarantees. There is no pre-emptive pruning of expired items, but you
728
+ * _may_ set a TTL on the cache, and it will treat expired items as missing
729
+ * when they are fetched, and delete them.
730
+ *
731
+ * Optional, but must be a non-negative integer in ms if specified.
732
+ *
733
+ * This may be overridden by passing an options object to `cache.set()`.
734
+ *
735
+ * At least one of `max`, `maxSize`, or `TTL` is required. This must be a
736
+ * positive integer if set.
737
+ *
738
+ * Even if ttl tracking is enabled, **it is strongly recommended to set a
739
+ * `max` to prevent unbounded growth of the cache.**
740
+ *
741
+ * If ttl tracking is enabled, and `max` and `maxSize` are not set,
742
+ * and `ttlAutopurge` is not set, then a warning will be emitted
743
+ * cautioning about the potential for unbounded memory consumption.
744
+ * (The TypeScript definitions will also discourage this.)
745
+ */
746
+ ttl?: Milliseconds
747
+
748
+ /**
749
+ * Minimum amount of time in ms in which to check for staleness.
750
+ * Defaults to 1, which means that the current time is checked
751
+ * at most once per millisecond.
752
+ *
753
+ * Set to 0 to check the current time every time staleness is tested.
754
+ * (This reduces performance, and is theoretically unnecessary.)
755
+ *
756
+ * Setting this to a higher value will improve performance somewhat
757
+ * while using ttl tracking, albeit at the expense of keeping stale
758
+ * items around a bit longer than their TTLs would indicate.
759
+ *
760
+ * @default 1
761
+ */
762
+ ttlResolution?: Milliseconds
763
+
764
+ /**
765
+ * Preemptively remove stale items from the cache.
766
+ *
767
+ * Note that this may *significantly* degrade performance, especially if
768
+ * the cache is storing a large number of items. It is almost always best
769
+ * to just leave the stale items in the cache, and let them fall out as new
770
+ * items are added.
771
+ *
772
+ * Note that this means that {@link OptionsBase.allowStale} is a bit
773
+ * pointless, as stale items will be deleted almost as soon as they
774
+ * expire.
775
+ *
776
+ * Use with caution!
777
+ */
778
+ ttlAutopurge?: boolean
779
+
780
+ /**
781
+ * When using time-expiring entries with `ttl`, setting this to `true` will
782
+ * make each item's age reset to 0 whenever it is retrieved from cache with
783
+ * {@link LRUCache#get}, causing it to not expire. (It can still fall out
784
+ * of cache based on recency of use, of course.)
785
+ *
786
+ * Has no effect if {@link OptionsBase.ttl} is not set.
787
+ *
788
+ * This may be overridden by passing an options object to `cache.get()`.
789
+ */
790
+ updateAgeOnGet?: boolean
791
+
792
+ /**
793
+ * When using time-expiring entries with `ttl`, setting this to `true` will
794
+ * make each item's age reset to 0 whenever its presence in the cache is
795
+ * checked with {@link LRUCache#has}, causing it to not expire. (It can
796
+ * still fall out of cache based on recency of use, of course.)
797
+ *
798
+ * Has no effect if {@link OptionsBase.ttl} is not set.
799
+ */
800
+ updateAgeOnHas?: boolean
801
+
802
+ /**
803
+ * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return
804
+ * stale data, if available.
805
+ *
806
+ * By default, if you set `ttl`, stale items will only be deleted from the
807
+ * cache when you `get(key)`. That is, it's not preemptively pruning items,
808
+ * unless {@link OptionsBase.ttlAutopurge} is set.
809
+ *
810
+ * If you set `allowStale:true`, it'll return the stale value *as well as*
811
+ * deleting it. If you don't set this, then it'll return `undefined` when
812
+ * you try to get a stale entry.
813
+ *
814
+ * Note that when a stale entry is fetched, _even if it is returned due to
815
+ * `allowStale` being set_, it is removed from the cache immediately. You
816
+ * can suppress this behavior by setting
817
+ * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in
818
+ * the options provided to {@link LRUCache#get}.
819
+ *
820
+ * This may be overridden by passing an options object to `cache.get()`.
821
+ * The `cache.has()` method will always return `false` for stale items.
822
+ *
823
+ * Only relevant if a ttl is set.
824
+ */
825
+ allowStale?: boolean
826
+
827
+ /**
828
+ * Function that is called on items when they are dropped from the
829
+ * cache, as `dispose(value, key, reason)`.
830
+ *
831
+ * This can be handy if you want to close file descriptors or do
832
+ * other cleanup tasks when items are no longer stored in the cache.
833
+ *
834
+ * **NOTE**: It is called _before_ the item has been fully removed
835
+ * from the cache, so if you want to put it right back in, you need
836
+ * to wait until the next tick. If you try to add it back in during
837
+ * the `dispose()` function call, it will break things in subtle and
838
+ * weird ways.
839
+ *
840
+ * Unlike several other options, this may _not_ be overridden by
841
+ * passing an option to `set()`, for performance reasons.
842
+ *
843
+ * The `reason` will be one of the following strings, corresponding
844
+ * to the reason for the item's deletion:
845
+ *
846
+ * - `evict` Item was evicted to make space for a new addition
847
+ * - `set` Item was overwritten by a new value
848
+ * - `expire` Item expired its TTL
849
+ * - `fetch` Item was deleted due to a failed or aborted fetch, or a
850
+ * fetchMethod returning `undefined.
851
+ * - `delete` Item was removed by explicit `cache.delete(key)`,
852
+ * `cache.clear()`, or `cache.set(key, undefined)`.
853
+ */
854
+ dispose?: Disposer<K, V>
855
+
856
+ /**
857
+ * Function that is called when new items are inserted into the cache,
858
+ * as `onInsert(value, key, reason)`.
859
+ *
860
+ * This can be useful if you need to perform actions when an item is
861
+ * added, such as logging or tracking insertions.
862
+ *
863
+ * Unlike some other options, this may _not_ be overridden by passing
864
+ * an option to `set()`, for performance and consistency reasons.
865
+ */
866
+ onInsert?: Inserter<K, V>
867
+
868
+ /**
869
+ * The same as {@link OptionsBase.dispose}, but called *after* the entry
870
+ * is completely removed and the cache is once again in a clean state.
871
+ *
872
+ * It is safe to add an item right back into the cache at this point.
873
+ * However, note that it is *very* easy to inadvertently create infinite
874
+ * recursion this way.
875
+ */
876
+ disposeAfter?: Disposer<K, V>
877
+
878
+ /**
879
+ * Set to true to suppress calling the
880
+ * {@link OptionsBase.dispose} function if the entry key is
881
+ * still accessible within the cache.
882
+ *
883
+ * This may be overridden by passing an options object to
884
+ * {@link LRUCache#set}.
885
+ *
886
+ * Only relevant if `dispose` or `disposeAfter` are set.
887
+ */
888
+ noDisposeOnSet?: boolean
889
+
890
+ /**
891
+ * Boolean flag to tell the cache to not update the TTL when setting a new
892
+ * value for an existing key (ie, when updating a value rather than
893
+ * inserting a new value). Note that the TTL value is _always_ set (if
894
+ * provided) when adding a new entry into the cache.
895
+ *
896
+ * Has no effect if a {@link OptionsBase.ttl} is not set.
897
+ *
898
+ * May be passed as an option to {@link LRUCache#set}.
899
+ */
900
+ noUpdateTTL?: boolean
901
+
902
+ /**
903
+ * Set to a positive integer to track the sizes of items added to the
904
+ * cache, and automatically evict items in order to stay below this size.
905
+ * Note that this may result in fewer than `max` items being stored.
906
+ *
907
+ * Attempting to add an item to the cache whose calculated size is greater
908
+ * that this amount will be a no-op. The item will not be cached, and no
909
+ * other items will be evicted.
910
+ *
911
+ * Optional, must be a positive integer if provided.
912
+ *
913
+ * Sets `maxEntrySize` to the same value, unless a different value is
914
+ * provided for `maxEntrySize`.
915
+ *
916
+ * At least one of `max`, `maxSize`, or `TTL` is required. This must be a
917
+ * positive integer if set.
918
+ *
919
+ * Even if size tracking is enabled, **it is strongly recommended to set a
920
+ * `max` to prevent unbounded growth of the cache.**
921
+ *
922
+ * Note also that size tracking can negatively impact performance,
923
+ * though for most cases, only minimally.
924
+ */
925
+ maxSize?: Size
926
+
927
+ /**
928
+ * The maximum allowed size for any single item in the cache.
929
+ *
930
+ * If a larger item is passed to {@link LRUCache#set} or returned by a
931
+ * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then
932
+ * it will not be stored in the cache.
933
+ *
934
+ * Attempting to add an item whose calculated size is greater than
935
+ * this amount will not cache the item or evict any old items, but
936
+ * WILL delete an existing value if one is already present.
937
+ *
938
+ * Optional, must be a positive integer if provided. Defaults to
939
+ * the value of `maxSize` if provided.
940
+ */
941
+ maxEntrySize?: Size
942
+
943
+ /**
944
+ * A function that returns a number indicating the item's size.
945
+ *
946
+ * Requires {@link OptionsBase.maxSize} to be set.
947
+ *
948
+ * If not provided, and {@link OptionsBase.maxSize} or
949
+ * {@link OptionsBase.maxEntrySize} are set, then all
950
+ * {@link LRUCache#set} calls **must** provide an explicit
951
+ * {@link SetOptions.size} or sizeCalculation param.
952
+ */
953
+ sizeCalculation?: SizeCalculator<K, V>
954
+
955
+ /**
956
+ * Method that provides the implementation for {@link LRUCache#fetch}
957
+ *
958
+ * ```ts
959
+ * fetchMethod(key, staleValue, { signal, options, context })
960
+ * ```
961
+ *
962
+ * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent
963
+ * to `Promise.resolve(cache.get(key))`.
964
+ *
965
+ * If at any time, `signal.aborted` is set to `true`, or if the
966
+ * `signal.onabort` method is called, or if it emits an `'abort'` event
967
+ * which you can listen to with `addEventListener`, then that means that
968
+ * the fetch should be abandoned. This may be passed along to async
969
+ * functions aware of AbortController/AbortSignal behavior.
970
+ *
971
+ * The `fetchMethod` should **only** return `undefined` or a Promise
972
+ * resolving to `undefined` if the AbortController signaled an `abort`
973
+ * event. In all other cases, it should return or resolve to a value
974
+ * suitable for adding to the cache.
975
+ *
976
+ * The `options` object is a union of the options that may be provided to
977
+ * `set()` and `get()`. If they are modified, then that will result in
978
+ * modifying the settings to `cache.set()` when the value is resolved, and
979
+ * in the case of
980
+ * {@link OptionsBase.noDeleteOnFetchRejection} and
981
+ * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of
982
+ * `fetchMethod` failures.
983
+ *
984
+ * For example, a DNS cache may update the TTL based on the value returned
985
+ * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.
986
+ */
987
+ fetchMethod?: Fetcher<K, V, FC>
988
+
989
+ /**
990
+ * Method that provides the implementation for {@link LRUCache#memo}
991
+ */
992
+ memoMethod?: Memoizer<K, V, FC>
993
+
994
+ /**
995
+ * Set to true to suppress the deletion of stale data when a
996
+ * {@link OptionsBase.fetchMethod} returns a rejected promise.
997
+ */
998
+ noDeleteOnFetchRejection?: boolean
999
+
1000
+ /**
1001
+ * Do not delete stale items when they are retrieved with
1002
+ * {@link LRUCache#get}.
1003
+ *
1004
+ * Note that the `get` return value will still be `undefined`
1005
+ * unless {@link OptionsBase.allowStale} is true.
1006
+ *
1007
+ * When using time-expiring entries with `ttl`, by default stale
1008
+ * items will be removed from the cache when the key is accessed
1009
+ * with `cache.get()`.
1010
+ *
1011
+ * Setting this option will cause stale items to remain in the cache, until
1012
+ * they are explicitly deleted with `cache.delete(key)`, or retrieved with
1013
+ * `noDeleteOnStaleGet` set to `false`.
1014
+ *
1015
+ * This may be overridden by passing an options object to `cache.get()`.
1016
+ *
1017
+ * Only relevant if a ttl is used.
1018
+ */
1019
+ noDeleteOnStaleGet?: boolean
1020
+
1021
+ /**
1022
+ * Set to true to allow returning stale data when a
1023
+ * {@link OptionsBase.fetchMethod} throws an error or returns a rejected
1024
+ * promise.
1025
+ *
1026
+ * This differs from using {@link OptionsBase.allowStale} in that stale
1027
+ * data will ONLY be returned in the case that the {@link LRUCache#fetch}
1028
+ * fails, not any other times.
1029
+ *
1030
+ * If a `fetchMethod` fails, and there is no stale value available, the
1031
+ * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are
1032
+ * suppressed.
1033
+ *
1034
+ * Implies `noDeleteOnFetchRejection`.
1035
+ *
1036
+ * This may be set in calls to `fetch()`, or defaulted on the constructor,
1037
+ * or overridden by modifying the options object in the `fetchMethod`.
1038
+ */
1039
+ allowStaleOnFetchRejection?: boolean
1040
+
1041
+ /**
1042
+ * Set to true to return a stale value from the cache when the
1043
+ * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches
1044
+ * an `'abort'` event, whether user-triggered, or due to internal cache
1045
+ * behavior.
1046
+ *
1047
+ * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying
1048
+ * {@link OptionsBase.fetchMethod} will still be considered canceled, and
1049
+ * any value it returns will be ignored and not cached.
1050
+ *
1051
+ * Caveat: since fetches are aborted when a new value is explicitly
1052
+ * set in the cache, this can lead to fetch returning a stale value,
1053
+ * since that was the fallback value _at the moment the `fetch()` was
1054
+ * initiated_, even though the new updated value is now present in
1055
+ * the cache.
1056
+ *
1057
+ * For example:
1058
+ *
1059
+ * ```ts
1060
+ * const cache = new LRUCache<string, any>({
1061
+ * ttl: 100,
1062
+ * fetchMethod: async (url, oldValue, { signal }) => {
1063
+ * const res = await fetch(url, { signal })
1064
+ * return await res.json()
1065
+ * }
1066
+ * })
1067
+ * cache.set('https://example.com/', { some: 'data' })
1068
+ * // 100ms go by...
1069
+ * const result = cache.fetch('https://example.com/')
1070
+ * cache.set('https://example.com/', { other: 'thing' })
1071
+ * console.log(await result) // { some: 'data' }
1072
+ * console.log(cache.get('https://example.com/')) // { other: 'thing' }
1073
+ * ```
1074
+ */
1075
+ allowStaleOnFetchAbort?: boolean
1076
+
1077
+ /**
1078
+ * Set to true to ignore the `abort` event emitted by the `AbortSignal`
1079
+ * object passed to {@link OptionsBase.fetchMethod}, and still cache the
1080
+ * resulting resolution value, as long as it is not `undefined`.
1081
+ *
1082
+ * When used on its own, this means aborted {@link LRUCache#fetch} calls
1083
+ * are not immediately resolved or rejected when they are aborted, and
1084
+ * instead take the full time to await.
1085
+ *
1086
+ * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted
1087
+ * {@link LRUCache#fetch} calls will resolve immediately to their stale
1088
+ * cached value or `undefined`, and will continue to process and eventually
1089
+ * update the cache when they resolve, as long as the resulting value is
1090
+ * not `undefined`, thus supporting a "return stale on timeout while
1091
+ * refreshing" mechanism by passing `AbortSignal.timeout(n)` as the signal.
1092
+ *
1093
+ * For example:
1094
+ *
1095
+ * ```ts
1096
+ * const c = new LRUCache({
1097
+ * ttl: 100,
1098
+ * ignoreFetchAbort: true,
1099
+ * allowStaleOnFetchAbort: true,
1100
+ * fetchMethod: async (key, oldValue, { signal }) => {
1101
+ * // note: do NOT pass the signal to fetch()!
1102
+ * // let's say this fetch can take a long time.
1103
+ * const res = await fetch(`https://slow-backend-server/${key}`)
1104
+ * return await res.json()
1105
+ * },
1106
+ * })
1107
+ *
1108
+ * // this will return the stale value after 100ms, while still
1109
+ * // updating in the background for next time.
1110
+ * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })
1111
+ * ```
1112
+ *
1113
+ * **Note**: regardless of this setting, an `abort` event _is still
1114
+ * emitted on the `AbortSignal` object_, so may result in invalid results
1115
+ * when passed to other underlying APIs that use AbortSignals.
1116
+ *
1117
+ * This may be overridden in the {@link OptionsBase.fetchMethod} or the
1118
+ * call to {@link LRUCache#fetch}.
1119
+ */
1120
+ ignoreFetchAbort?: boolean
1121
+
1122
+ /**
1123
+ * In some cases, you may want to swap out the performance/Date object
1124
+ * used for TTL tracking. This should almost certainly NOT be done in
1125
+ * production environments!
1126
+ *
1127
+ * This value defaults to `global.performance` if it has a `now()` method,
1128
+ * or the `global.Date` object otherwise.
1129
+ */
1130
+ perf?: Perf
1131
+ }
1132
+
1133
+ export interface OptionsMaxLimit<K, V, FC> extends OptionsBase<
1134
+ K,
1135
+ V,
1136
+ FC
1137
+ > {
1138
+ max: Count
1139
+ }
1140
+ export interface OptionsTTLLimit<K, V, FC> extends OptionsBase<
1141
+ K,
1142
+ V,
1143
+ FC
1144
+ > {
1145
+ ttl: Milliseconds
1146
+ ttlAutopurge: boolean
1147
+ }
1148
+ export interface OptionsSizeLimit<K, V, FC> extends OptionsBase<
1149
+ K,
1150
+ V,
1151
+ FC
1152
+ > {
1153
+ maxSize: Size
1154
+ }
1155
+
1156
+ /**
1157
+ * The valid safe options for the {@link LRUCache} constructor
1158
+ */
1159
+ export type Options<K, V, FC> =
1160
+ | OptionsMaxLimit<K, V, FC>
1161
+ | OptionsSizeLimit<K, V, FC>
1162
+ | OptionsTTLLimit<K, V, FC>
1163
+
1164
+ /**
1165
+ * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},
1166
+ * and returned by {@link LRUCache#info}.
1167
+ */
1168
+ export interface Entry<V> {
1169
+ value: V
1170
+ ttl?: Milliseconds
1171
+ size?: Size
1172
+ start?: Milliseconds
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * Default export, the thing you're using this module to get.
1178
+ *
1179
+ * The `K` and `V` types define the key and value types, respectively. The
1180
+ * optional `FC` type defines the type of the `context` object passed to
1181
+ * `cache.fetch()` and `cache.memo()`.
1182
+ *
1183
+ * Keys and values **must not** be `null` or `undefined`.
1184
+ *
1185
+ * All properties from the options object (with the exception of `max`,
1186
+ * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
1187
+ * added as normal public members. (The listed options are read-only getters.)
1188
+ *
1189
+ * Changing any of these will alter the defaults for subsequent method calls.
1190
+ */
1191
+ export class LRUCache<K extends {}, V extends {}, FC = unknown> {
1192
+ // options that cannot be changed without disaster
1193
+ readonly #max: LRUCache.Count
1194
+ readonly #maxSize: LRUCache.Size
1195
+ readonly #dispose?: LRUCache.Disposer<K, V>
1196
+ readonly #onInsert?: LRUCache.Inserter<K, V>
1197
+ readonly #disposeAfter?: LRUCache.Disposer<K, V>
1198
+ readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>
1199
+ readonly #memoMethod?: LRUCache.Memoizer<K, V, FC>
1200
+ readonly #perf: Perf
1201
+
1202
+ /**
1203
+ * {@link LRUCache.OptionsBase.perf}
1204
+ */
1205
+ get perf() {
1206
+ return this.#perf
1207
+ }
1208
+
1209
+ /**
1210
+ * {@link LRUCache.OptionsBase.ttl}
1211
+ */
1212
+ ttl: LRUCache.Milliseconds
1213
+
1214
+ /**
1215
+ * {@link LRUCache.OptionsBase.ttlResolution}
1216
+ */
1217
+ ttlResolution: LRUCache.Milliseconds
1218
+ /**
1219
+ * {@link LRUCache.OptionsBase.ttlAutopurge}
1220
+ */
1221
+ ttlAutopurge: boolean
1222
+ /**
1223
+ * {@link LRUCache.OptionsBase.updateAgeOnGet}
1224
+ */
1225
+ updateAgeOnGet: boolean
1226
+ /**
1227
+ * {@link LRUCache.OptionsBase.updateAgeOnHas}
1228
+ */
1229
+ updateAgeOnHas: boolean
1230
+ /**
1231
+ * {@link LRUCache.OptionsBase.allowStale}
1232
+ */
1233
+ allowStale: boolean
1234
+
1235
+ /**
1236
+ * {@link LRUCache.OptionsBase.noDisposeOnSet}
1237
+ */
1238
+ noDisposeOnSet: boolean
1239
+ /**
1240
+ * {@link LRUCache.OptionsBase.noUpdateTTL}
1241
+ */
1242
+ noUpdateTTL: boolean
1243
+ /**
1244
+ * {@link LRUCache.OptionsBase.maxEntrySize}
1245
+ */
1246
+ maxEntrySize: LRUCache.Size
1247
+ /**
1248
+ * {@link LRUCache.OptionsBase.sizeCalculation}
1249
+ */
1250
+ sizeCalculation?: LRUCache.SizeCalculator<K, V>
1251
+ /**
1252
+ * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
1253
+ */
1254
+ noDeleteOnFetchRejection: boolean
1255
+ /**
1256
+ * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
1257
+ */
1258
+ noDeleteOnStaleGet: boolean
1259
+ /**
1260
+ * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
1261
+ */
1262
+ allowStaleOnFetchAbort: boolean
1263
+ /**
1264
+ * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
1265
+ */
1266
+ allowStaleOnFetchRejection: boolean
1267
+ /**
1268
+ * {@link LRUCache.OptionsBase.ignoreFetchAbort}
1269
+ */
1270
+ ignoreFetchAbort: boolean
1271
+
1272
+ // computed properties
1273
+ #size: LRUCache.Count
1274
+ #calculatedSize: LRUCache.Size
1275
+ #keyMap: Map<K, Index>
1276
+ #keyList: (K | undefined)[]
1277
+ #valList: (V | BackgroundFetch<V> | undefined)[]
1278
+ #next: NumberArray
1279
+ #prev: NumberArray
1280
+ #head: Index
1281
+ #tail: Index
1282
+ #free: StackLike
1283
+ #disposed?: DisposeTask<K, V>[]
1284
+ #sizes?: ZeroArray
1285
+ #starts?: ZeroArray
1286
+ #ttls?: ZeroArray
1287
+ #autopurgeTimers?: (undefined | ReturnType<typeof setTimeout>)[]
1288
+
1289
+ #hasDispose: boolean
1290
+ #hasFetchMethod: boolean
1291
+ #hasDisposeAfter: boolean
1292
+ #hasOnInsert: boolean
1293
+
1294
+ /**
1295
+ * Do not call this method unless you need to inspect the
1296
+ * inner workings of the cache. If anything returned by this
1297
+ * object is modified in any way, strange breakage may occur.
1298
+ *
1299
+ * These fields are private for a reason!
1300
+ *
1301
+ * @internal
1302
+ */
1303
+ static unsafeExposeInternals<
1304
+ K extends {},
1305
+ V extends {},
1306
+ FC extends unknown = unknown,
1307
+ >(c: LRUCache<K, V, FC>) {
1308
+ return {
1309
+ // properties
1310
+ starts: c.#starts,
1311
+ ttls: c.#ttls,
1312
+ autopurgeTimers: c.#autopurgeTimers,
1313
+ sizes: c.#sizes,
1314
+ keyMap: c.#keyMap as Map<K, number>,
1315
+ keyList: c.#keyList,
1316
+ valList: c.#valList,
1317
+ next: c.#next,
1318
+ prev: c.#prev,
1319
+ get head() {
1320
+ return c.#head
1321
+ },
1322
+ get tail() {
1323
+ return c.#tail
1324
+ },
1325
+ free: c.#free,
1326
+ // methods
1327
+ isBackgroundFetch: (p: unknown) => c.#isBackgroundFetch(p),
1328
+ backgroundFetch: (
1329
+ k: K,
1330
+ index: number | undefined,
1331
+ options: LRUCache.FetchOptions<K, V, FC>,
1332
+ context: unknown,
1333
+ ): BackgroundFetch<V> =>
1334
+ c.#backgroundFetch(
1335
+ k,
1336
+ index as Index | undefined,
1337
+ options,
1338
+ context as FC,
1339
+ ),
1340
+ moveToTail: (index: number): void => c.#moveToTail(index as Index),
1341
+ indexes: (options?: { allowStale: boolean }) => c.#indexes(options),
1342
+ rindexes: (options?: { allowStale: boolean }) =>
1343
+ c.#rindexes(options),
1344
+ isStale: (index: number | undefined) => c.#isStale(index as Index),
1345
+ }
1346
+ }
1347
+
1348
+ // Protected read-only members
1349
+
1350
+ /**
1351
+ * {@link LRUCache.OptionsBase.max} (read-only)
1352
+ */
1353
+ get max(): LRUCache.Count {
1354
+ return this.#max
1355
+ }
1356
+ /**
1357
+ * {@link LRUCache.OptionsBase.maxSize} (read-only)
1358
+ */
1359
+ get maxSize(): LRUCache.Count {
1360
+ return this.#maxSize
1361
+ }
1362
+ /**
1363
+ * The total computed size of items in the cache (read-only)
1364
+ */
1365
+ get calculatedSize(): LRUCache.Size {
1366
+ return this.#calculatedSize
1367
+ }
1368
+ /**
1369
+ * The number of items stored in the cache (read-only)
1370
+ */
1371
+ get size(): LRUCache.Count {
1372
+ return this.#size
1373
+ }
1374
+ /**
1375
+ * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
1376
+ */
1377
+ get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {
1378
+ return this.#fetchMethod
1379
+ }
1380
+ get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined {
1381
+ return this.#memoMethod
1382
+ }
1383
+ /**
1384
+ * {@link LRUCache.OptionsBase.dispose} (read-only)
1385
+ */
1386
+ get dispose() {
1387
+ return this.#dispose
1388
+ }
1389
+ /**
1390
+ * {@link LRUCache.OptionsBase.onInsert} (read-only)
1391
+ */
1392
+ get onInsert() {
1393
+ return this.#onInsert
1394
+ }
1395
+ /**
1396
+ * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
1397
+ */
1398
+ get disposeAfter() {
1399
+ return this.#disposeAfter
1400
+ }
1401
+
1402
+ constructor(options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>) {
1403
+ const {
1404
+ max = 0,
1405
+ ttl,
1406
+ ttlResolution = 1,
1407
+ ttlAutopurge,
1408
+ updateAgeOnGet,
1409
+ updateAgeOnHas,
1410
+ allowStale,
1411
+ dispose,
1412
+ onInsert,
1413
+ disposeAfter,
1414
+ noDisposeOnSet,
1415
+ noUpdateTTL,
1416
+ maxSize = 0,
1417
+ maxEntrySize = 0,
1418
+ sizeCalculation,
1419
+ fetchMethod,
1420
+ memoMethod,
1421
+ noDeleteOnFetchRejection,
1422
+ noDeleteOnStaleGet,
1423
+ allowStaleOnFetchRejection,
1424
+ allowStaleOnFetchAbort,
1425
+ ignoreFetchAbort,
1426
+ perf,
1427
+ } = options
1428
+
1429
+ if (perf !== undefined) {
1430
+ if (typeof perf?.now !== 'function') {
1431
+ throw new TypeError(
1432
+ 'perf option must have a now() method if specified',
1433
+ )
1434
+ }
1435
+ }
1436
+
1437
+ this.#perf = perf ?? defaultPerf
1438
+
1439
+ if (max !== 0 && !isPosInt(max)) {
1440
+ throw new TypeError('max option must be a nonnegative integer')
1441
+ }
1442
+
1443
+ const UintArray = max ? getUintArray(max) : Array
1444
+ if (!UintArray) {
1445
+ throw new Error('invalid max value: ' + max)
1446
+ }
1447
+
1448
+ this.#max = max
1449
+ this.#maxSize = maxSize
1450
+ this.maxEntrySize = maxEntrySize || this.#maxSize
1451
+ this.sizeCalculation = sizeCalculation
1452
+ if (this.sizeCalculation) {
1453
+ if (!this.#maxSize && !this.maxEntrySize) {
1454
+ throw new TypeError(
1455
+ 'cannot set sizeCalculation without setting maxSize or maxEntrySize',
1456
+ )
1457
+ }
1458
+ if (typeof this.sizeCalculation !== 'function') {
1459
+ throw new TypeError('sizeCalculation set to non-function')
1460
+ }
1461
+ }
1462
+
1463
+ if (memoMethod !== undefined && typeof memoMethod !== 'function') {
1464
+ throw new TypeError('memoMethod must be a function if defined')
1465
+ }
1466
+ this.#memoMethod = memoMethod
1467
+
1468
+ if (fetchMethod !== undefined && typeof fetchMethod !== 'function') {
1469
+ throw new TypeError('fetchMethod must be a function if specified')
1470
+ }
1471
+ this.#fetchMethod = fetchMethod
1472
+ this.#hasFetchMethod = !!fetchMethod
1473
+
1474
+ this.#keyMap = new Map()
1475
+ this.#keyList = Array.from({ length: max }).fill(undefined) as (
1476
+ | K
1477
+ | undefined
1478
+ )[]
1479
+ this.#valList = Array.from({ length: max }).fill(undefined) as (
1480
+ | V
1481
+ | undefined
1482
+ )[]
1483
+ this.#next = new UintArray(max)
1484
+ this.#prev = new UintArray(max)
1485
+ this.#head = 0 as Index
1486
+ this.#tail = 0 as Index
1487
+ this.#free = Stack.create(max)
1488
+ this.#size = 0
1489
+ this.#calculatedSize = 0
1490
+
1491
+ if (typeof dispose === 'function') {
1492
+ this.#dispose = dispose
1493
+ }
1494
+ if (typeof onInsert === 'function') {
1495
+ this.#onInsert = onInsert
1496
+ }
1497
+ if (typeof disposeAfter === 'function') {
1498
+ this.#disposeAfter = disposeAfter
1499
+ this.#disposed = []
1500
+ } else {
1501
+ this.#disposeAfter = undefined
1502
+ this.#disposed = undefined
1503
+ }
1504
+ this.#hasDispose = !!this.#dispose
1505
+ this.#hasOnInsert = !!this.#onInsert
1506
+ this.#hasDisposeAfter = !!this.#disposeAfter
1507
+
1508
+ this.noDisposeOnSet = !!noDisposeOnSet
1509
+ this.noUpdateTTL = !!noUpdateTTL
1510
+ this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection
1511
+ this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection
1512
+ this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort
1513
+ this.ignoreFetchAbort = !!ignoreFetchAbort
1514
+
1515
+ // NB: maxEntrySize is set to maxSize if it's set
1516
+ if (this.maxEntrySize !== 0) {
1517
+ if (this.#maxSize !== 0) {
1518
+ if (!isPosInt(this.#maxSize)) {
1519
+ throw new TypeError(
1520
+ 'maxSize must be a positive integer if specified',
1521
+ )
1522
+ }
1523
+ }
1524
+ if (!isPosInt(this.maxEntrySize)) {
1525
+ throw new TypeError(
1526
+ 'maxEntrySize must be a positive integer if specified',
1527
+ )
1528
+ }
1529
+ this.#initializeSizeTracking()
1530
+ }
1531
+
1532
+ this.allowStale = !!allowStale
1533
+ this.noDeleteOnStaleGet = !!noDeleteOnStaleGet
1534
+ this.updateAgeOnGet = !!updateAgeOnGet
1535
+ this.updateAgeOnHas = !!updateAgeOnHas
1536
+ this.ttlResolution =
1537
+ isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1
1538
+ this.ttlAutopurge = !!ttlAutopurge
1539
+ this.ttl = ttl || 0
1540
+ if (this.ttl) {
1541
+ if (!isPosInt(this.ttl)) {
1542
+ throw new TypeError('ttl must be a positive integer if specified')
1543
+ }
1544
+ this.#initializeTTLTracking()
1545
+ }
1546
+
1547
+ // do not allow completely unbounded caches
1548
+ if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
1549
+ throw new TypeError(
1550
+ 'At least one of max, maxSize, or ttl is required',
1551
+ )
1552
+ }
1553
+ if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
1554
+ const code = 'LRU_CACHE_UNBOUNDED'
1555
+ if (shouldWarn(code)) {
1556
+ warned.add(code)
1557
+ const msg =
1558
+ 'TTL caching without ttlAutopurge, max, or maxSize can ' +
1559
+ 'result in unbounded memory consumption.'
1560
+ emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)
1561
+ }
1562
+ }
1563
+ }
1564
+
1565
+ /**
1566
+ * Return the number of ms left in the item's TTL. If item is not in cache,
1567
+ * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
1568
+ */
1569
+ getRemainingTTL(key: K) {
1570
+ return this.#keyMap.has(key) ? Infinity : 0
1571
+ }
1572
+
1573
+ #initializeTTLTracking() {
1574
+ const ttls = new ZeroArray(this.#max)
1575
+ const starts = new ZeroArray(this.#max)
1576
+ this.#ttls = ttls
1577
+ this.#starts = starts
1578
+ const purgeTimers =
1579
+ this.ttlAutopurge ?
1580
+ Array.from<undefined | ReturnType<typeof setTimeout>>({
1581
+ length: this.#max,
1582
+ })
1583
+ : undefined
1584
+ this.#autopurgeTimers = purgeTimers
1585
+
1586
+ this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
1587
+ starts[index] = ttl !== 0 ? start : 0
1588
+ ttls[index] = ttl
1589
+ setPurgetTimer(index, ttl)
1590
+ }
1591
+
1592
+ this.#updateItemAge = index => {
1593
+ starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0
1594
+ setPurgetTimer(index, ttls[index])
1595
+ }
1596
+
1597
+ // clear out the purge timer if we're setting TTL to 0, and
1598
+ // previously had a ttl purge timer running, so it doesn't
1599
+ // fire unnecessarily. Don't need to do this if we're not doing
1600
+ // autopurge.
1601
+ const setPurgetTimer =
1602
+ !this.ttlAutopurge ?
1603
+ () => {}
1604
+ : (index: Index, ttl?: number) => {
1605
+ if (purgeTimers?.[index]) {
1606
+ clearTimeout(purgeTimers[index])
1607
+ purgeTimers[index] = undefined
1608
+ }
1609
+ if (ttl && ttl !== 0 && purgeTimers) {
1610
+ const t = setTimeout(() => {
1611
+ if (this.#isStale(index)) {
1612
+ this.#delete(this.#keyList[index] as K, 'expire')
1613
+ }
1614
+ }, ttl + 1)
1615
+ // unref() not supported on all platforms
1616
+ /* c8 ignore start */
1617
+ if (t.unref) {
1618
+ t.unref()
1619
+ }
1620
+ /* c8 ignore stop */
1621
+ purgeTimers[index] = t
1622
+ }
1623
+ }
1624
+
1625
+ this.#statusTTL = (status, index) => {
1626
+ if (ttls[index]) {
1627
+ const ttl = ttls[index]
1628
+ const start = starts[index]
1629
+ /* c8 ignore start */
1630
+ if (!ttl || !start) {
1631
+ return
1632
+ }
1633
+ /* c8 ignore stop */
1634
+ status.ttl = ttl
1635
+ status.start = start
1636
+ status.now = cachedNow || getNow()
1637
+ const age = status.now - start
1638
+ status.remainingTTL = ttl - age
1639
+ }
1640
+ }
1641
+
1642
+ // debounce calls to perf.now() to 1s so we're not hitting
1643
+ // that costly call repeatedly.
1644
+ let cachedNow = 0
1645
+ const getNow = () => {
1646
+ const n = this.#perf.now()
1647
+ if (this.ttlResolution > 0) {
1648
+ cachedNow = n
1649
+ const t = setTimeout(() => (cachedNow = 0), this.ttlResolution)
1650
+ // not available on all platforms
1651
+ /* c8 ignore start */
1652
+ if (t.unref) {
1653
+ t.unref()
1654
+ }
1655
+ /* c8 ignore stop */
1656
+ }
1657
+ return n
1658
+ }
1659
+
1660
+ this.getRemainingTTL = key => {
1661
+ const index = this.#keyMap.get(key)
1662
+ if (index === undefined) {
1663
+ return 0
1664
+ }
1665
+ const ttl = ttls[index]
1666
+ const start = starts[index]
1667
+ if (!ttl || !start) {
1668
+ return Infinity
1669
+ }
1670
+ const age = (cachedNow || getNow()) - start
1671
+ return ttl - age
1672
+ }
1673
+
1674
+ this.#isStale = index => {
1675
+ const s = starts[index]
1676
+ const t = ttls[index]
1677
+ return !!t && !!s && (cachedNow || getNow()) - s > t
1678
+ }
1679
+ }
1680
+
1681
+ // conditionally set private methods related to TTL
1682
+ #updateItemAge: (index: Index) => void = () => {}
1683
+ #statusTTL: (status: LRUCache.Status<K, V>, index: Index) => void =
1684
+ () => {}
1685
+ #setItemTTL: (
1686
+ index: Index,
1687
+ ttl: LRUCache.Milliseconds,
1688
+ start?: LRUCache.Milliseconds,
1689
+ // ignore because we never call this if we're not already in TTL mode
1690
+ /* c8 ignore start */
1691
+ ) => void = () => {}
1692
+ /* c8 ignore stop */
1693
+
1694
+ #isStale: (index: Index) => boolean = () => false
1695
+
1696
+ #initializeSizeTracking() {
1697
+ const sizes = new ZeroArray(this.#max)
1698
+ this.#calculatedSize = 0
1699
+ this.#sizes = sizes
1700
+ this.#removeItemSize = index => {
1701
+ this.#calculatedSize -= sizes[index] as number
1702
+ sizes[index] = 0
1703
+ }
1704
+ this.#requireSize = (k, v, size, sizeCalculation) => {
1705
+ // provisionally accept background fetches.
1706
+ // actual value size will be checked when they return.
1707
+ if (this.#isBackgroundFetch(v)) {
1708
+ return 0
1709
+ }
1710
+ if (!isPosInt(size)) {
1711
+ if (sizeCalculation) {
1712
+ if (typeof sizeCalculation !== 'function') {
1713
+ throw new TypeError('sizeCalculation must be a function')
1714
+ }
1715
+ size = sizeCalculation(v, k)
1716
+ if (!isPosInt(size)) {
1717
+ throw new TypeError(
1718
+ 'sizeCalculation return invalid (expect positive integer)',
1719
+ )
1720
+ }
1721
+ } else {
1722
+ throw new TypeError(
1723
+ 'invalid size value (must be positive integer). ' +
1724
+ 'When maxSize or maxEntrySize is used, sizeCalculation ' +
1725
+ 'or size must be set.',
1726
+ )
1727
+ }
1728
+ }
1729
+ return size
1730
+ }
1731
+
1732
+ this.#addItemSize = (
1733
+ index: Index,
1734
+ size: LRUCache.Size,
1735
+ status?: LRUCache.Status<K, V>,
1736
+ ) => {
1737
+ sizes[index] = size
1738
+ if (this.#maxSize) {
1739
+ const maxSize = this.#maxSize - (sizes[index] as number)
1740
+ while (this.#calculatedSize > maxSize) {
1741
+ this.#evict(true)
1742
+ }
1743
+ }
1744
+ this.#calculatedSize += sizes[index] as number
1745
+ if (status) {
1746
+ status.entrySize = size
1747
+ status.totalCalculatedSize = this.#calculatedSize
1748
+ }
1749
+ }
1750
+ }
1751
+
1752
+ #removeItemSize: (index: Index) => void = _i => {}
1753
+
1754
+ #addItemSize: (
1755
+ index: Index,
1756
+ size: LRUCache.Size,
1757
+ status?: LRUCache.Status<K, V>,
1758
+ ) => void = (_i, _s, _st) => {}
1759
+
1760
+ #requireSize: (
1761
+ k: K,
1762
+ v: V | BackgroundFetch<V>,
1763
+ size?: LRUCache.Size,
1764
+ sizeCalculation?: LRUCache.SizeCalculator<K, V>,
1765
+ status?: LRUCache.Status<K, V>,
1766
+ ) => LRUCache.Size = (
1767
+ _k: K,
1768
+ _v: V | BackgroundFetch<V>,
1769
+ size?: LRUCache.Size,
1770
+ sizeCalculation?: LRUCache.SizeCalculator<K, V>,
1771
+ ) => {
1772
+ if (size || sizeCalculation) {
1773
+ throw new TypeError(
1774
+ 'cannot set size without setting maxSize or maxEntrySize on cache',
1775
+ )
1776
+ }
1777
+ return 0
1778
+ };
1779
+
1780
+ *#indexes({ allowStale = this.allowStale } = {}) {
1781
+ if (this.#size) {
1782
+ for (let i = this.#tail; this.#isValidIndex(i); ) {
1783
+ if (allowStale || !this.#isStale(i)) {
1784
+ yield i
1785
+ }
1786
+ if (i === this.#head) {
1787
+ break
1788
+ } else {
1789
+ i = this.#prev[i] as Index
1790
+ }
1791
+ }
1792
+ }
1793
+ }
1794
+
1795
+ *#rindexes({ allowStale = this.allowStale } = {}) {
1796
+ if (this.#size) {
1797
+ for (let i = this.#head; this.#isValidIndex(i); ) {
1798
+ if (allowStale || !this.#isStale(i)) {
1799
+ yield i
1800
+ }
1801
+ if (i === this.#tail) {
1802
+ break
1803
+ } else {
1804
+ i = this.#next[i] as Index
1805
+ }
1806
+ }
1807
+ }
1808
+ }
1809
+
1810
+ #isValidIndex(index: Index) {
1811
+ return (
1812
+ index !== undefined &&
1813
+ this.#keyMap.get(this.#keyList[index] as K) === index
1814
+ )
1815
+ }
1816
+
1817
+ /**
1818
+ * Return a generator yielding `[key, value]` pairs,
1819
+ * in order from most recently used to least recently used.
1820
+ */
1821
+ *entries() {
1822
+ for (const i of this.#indexes()) {
1823
+ if (
1824
+ this.#valList[i] !== undefined &&
1825
+ this.#keyList[i] !== undefined &&
1826
+ !this.#isBackgroundFetch(this.#valList[i])
1827
+ ) {
1828
+ yield [this.#keyList[i], this.#valList[i]] as [K, V]
1829
+ }
1830
+ }
1831
+ }
1832
+
1833
+ /**
1834
+ * Inverse order version of {@link LRUCache.entries}
1835
+ *
1836
+ * Return a generator yielding `[key, value]` pairs,
1837
+ * in order from least recently used to most recently used.
1838
+ */
1839
+ *rentries() {
1840
+ for (const i of this.#rindexes()) {
1841
+ if (
1842
+ this.#valList[i] !== undefined &&
1843
+ this.#keyList[i] !== undefined &&
1844
+ !this.#isBackgroundFetch(this.#valList[i])
1845
+ ) {
1846
+ yield [this.#keyList[i], this.#valList[i]]
1847
+ }
1848
+ }
1849
+ }
1850
+
1851
+ /**
1852
+ * Return a generator yielding the keys in the cache,
1853
+ * in order from most recently used to least recently used.
1854
+ */
1855
+ *keys() {
1856
+ for (const i of this.#indexes()) {
1857
+ const k = this.#keyList[i]
1858
+ if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
1859
+ yield k
1860
+ }
1861
+ }
1862
+ }
1863
+
1864
+ /**
1865
+ * Inverse order version of {@link LRUCache.keys}
1866
+ *
1867
+ * Return a generator yielding the keys in the cache,
1868
+ * in order from least recently used to most recently used.
1869
+ */
1870
+ *rkeys() {
1871
+ for (const i of this.#rindexes()) {
1872
+ const k = this.#keyList[i]
1873
+ if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
1874
+ yield k
1875
+ }
1876
+ }
1877
+ }
1878
+
1879
+ /**
1880
+ * Return a generator yielding the values in the cache,
1881
+ * in order from most recently used to least recently used.
1882
+ */
1883
+ *values() {
1884
+ for (const i of this.#indexes()) {
1885
+ const v = this.#valList[i]
1886
+ if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
1887
+ yield this.#valList[i] as V
1888
+ }
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * Inverse order version of {@link LRUCache.values}
1894
+ *
1895
+ * Return a generator yielding the values in the cache,
1896
+ * in order from least recently used to most recently used.
1897
+ */
1898
+ *rvalues() {
1899
+ for (const i of this.#rindexes()) {
1900
+ const v = this.#valList[i]
1901
+ if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {
1902
+ yield this.#valList[i]
1903
+ }
1904
+ }
1905
+ }
1906
+
1907
+ /**
1908
+ * Iterating over the cache itself yields the same results as
1909
+ * {@link LRUCache.entries}
1910
+ */
1911
+ [Symbol.iterator]() {
1912
+ return this.entries()
1913
+ }
1914
+
1915
+ /**
1916
+ * A String value that is used in the creation of the default string
1917
+ * description of an object. Called by the built-in method
1918
+ * `Object.prototype.toString`.
1919
+ */
1920
+ [Symbol.toStringTag] = 'LRUCache'
1921
+
1922
+ /**
1923
+ * Find a value for which the supplied fn method returns a truthy value,
1924
+ * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
1925
+ */
1926
+ find(
1927
+ fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean,
1928
+ getOptions: LRUCache.GetOptions<K, V, FC> = {},
1929
+ ) {
1930
+ for (const i of this.#indexes()) {
1931
+ const v = this.#valList[i]
1932
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
1933
+ if (value === undefined) continue
1934
+ if (fn(value, this.#keyList[i] as K, this)) {
1935
+ return this.#get(this.#keyList[i] as K, getOptions)
1936
+ }
1937
+ }
1938
+ }
1939
+
1940
+ /**
1941
+ * Call the supplied function on each item in the cache, in order from most
1942
+ * recently used to least recently used.
1943
+ *
1944
+ * `fn` is called as `fn(value, key, cache)`.
1945
+ *
1946
+ * If `thisp` is provided, function will be called in the `this`-context of
1947
+ * the provided object, or the cache if no `thisp` object is provided.
1948
+ *
1949
+ * Does not update age or recenty of use, or iterate over stale values.
1950
+ */
1951
+ forEach(
1952
+ fn: (v: V, k: K, self: LRUCache<K, V, FC>) => unknown,
1953
+ thisp: unknown = this,
1954
+ ) {
1955
+ for (const i of this.#indexes()) {
1956
+ const v = this.#valList[i]
1957
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
1958
+ if (value === undefined) continue
1959
+ fn.call(thisp, value, this.#keyList[i] as K, this)
1960
+ }
1961
+ }
1962
+
1963
+ /**
1964
+ * The same as {@link LRUCache.forEach} but items are iterated over in
1965
+ * reverse order. (ie, less recently used items are iterated over first.)
1966
+ */
1967
+ rforEach(
1968
+ fn: (v: V, k: K, self: LRUCache<K, V, FC>) => unknown,
1969
+ thisp: unknown = this,
1970
+ ) {
1971
+ for (const i of this.#rindexes()) {
1972
+ const v = this.#valList[i]
1973
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
1974
+ if (value === undefined) continue
1975
+ fn.call(thisp, value, this.#keyList[i] as K, this)
1976
+ }
1977
+ }
1978
+
1979
+ /**
1980
+ * Delete any stale entries. Returns true if anything was removed,
1981
+ * false otherwise.
1982
+ */
1983
+ purgeStale() {
1984
+ let deleted = false
1985
+ for (const i of this.#rindexes({ allowStale: true })) {
1986
+ if (this.#isStale(i)) {
1987
+ this.#delete(this.#keyList[i] as K, 'expire')
1988
+ deleted = true
1989
+ }
1990
+ }
1991
+ return deleted
1992
+ }
1993
+
1994
+ /**
1995
+ * Get the extended info about a given entry, to get its value, size, and
1996
+ * TTL info simultaneously. Returns `undefined` if the key is not present.
1997
+ *
1998
+ * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
1999
+ * serialization, the `start` value is always the current timestamp, and the
2000
+ * `ttl` is a calculated remaining time to live (negative if expired).
2001
+ *
2002
+ * Always returns stale values, if their info is found in the cache, so be
2003
+ * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
2004
+ * if relevant.
2005
+ */
2006
+ info(key: K): LRUCache.Entry<V> | undefined {
2007
+ const i = this.#keyMap.get(key)
2008
+ if (i === undefined) return undefined
2009
+ const v = this.#valList[i]
2010
+ /* c8 ignore start - this isn't tested for the info function,
2011
+ * but it's the same logic as found in other places. */
2012
+ const value: V | undefined =
2013
+ this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
2014
+ if (value === undefined) return undefined
2015
+ /* c8 ignore stop */
2016
+ const entry: LRUCache.Entry<V> = { value }
2017
+ if (this.#ttls && this.#starts) {
2018
+ const ttl = this.#ttls[i]
2019
+ const start = this.#starts[i]
2020
+ if (ttl && start) {
2021
+ const remain = ttl - (this.#perf.now() - start)
2022
+ entry.ttl = remain
2023
+ entry.start = Date.now()
2024
+ }
2025
+ }
2026
+ if (this.#sizes) {
2027
+ entry.size = this.#sizes[i]
2028
+ }
2029
+ return entry
2030
+ }
2031
+
2032
+ /**
2033
+ * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
2034
+ * passed to {@link LRUCache#load}.
2035
+ *
2036
+ * The `start` fields are calculated relative to a portable `Date.now()`
2037
+ * timestamp, even if `performance.now()` is available.
2038
+ *
2039
+ * Stale entries are always included in the `dump`, even if
2040
+ * {@link LRUCache.OptionsBase.allowStale} is false.
2041
+ *
2042
+ * Note: this returns an actual array, not a generator, so it can be more
2043
+ * easily passed around.
2044
+ */
2045
+ dump() {
2046
+ const arr: [K, LRUCache.Entry<V>][] = []
2047
+ for (const i of this.#indexes({ allowStale: true })) {
2048
+ const key = this.#keyList[i]
2049
+ const v = this.#valList[i]
2050
+ const value: V | undefined =
2051
+ this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
2052
+ if (value === undefined || key === undefined) continue
2053
+ const entry: LRUCache.Entry<V> = { value }
2054
+ if (this.#ttls && this.#starts) {
2055
+ entry.ttl = this.#ttls[i]
2056
+ // always dump the start relative to a portable timestamp
2057
+ // it's ok for this to be a bit slow, it's a rare operation.
2058
+ const age = this.#perf.now() - (this.#starts[i] as number)
2059
+ entry.start = Math.floor(Date.now() - age)
2060
+ }
2061
+ if (this.#sizes) {
2062
+ entry.size = this.#sizes[i]
2063
+ }
2064
+ arr.unshift([key, entry])
2065
+ }
2066
+ return arr
2067
+ }
2068
+
2069
+ /**
2070
+ * Reset the cache and load in the items in entries in the order listed.
2071
+ *
2072
+ * The shape of the resulting cache may be different if the same options are
2073
+ * not used in both caches.
2074
+ *
2075
+ * The `start` fields are assumed to be calculated relative to a portable
2076
+ * `Date.now()` timestamp, even if `performance.now()` is available.
2077
+ */
2078
+ load(arr: [K, LRUCache.Entry<V>][]) {
2079
+ this.clear()
2080
+ for (const [key, entry] of arr) {
2081
+ if (entry.start) {
2082
+ // entry.start is a portable timestamp, but we may be using
2083
+ // node's performance.now(), so calculate the offset, so that
2084
+ // we get the intended remaining TTL, no matter how long it's
2085
+ // been on ice.
2086
+ //
2087
+ // it's ok for this to be a bit slow, it's a rare operation.
2088
+ const age = Date.now() - entry.start
2089
+ entry.start = this.#perf.now() - age
2090
+ }
2091
+ this.#set(key, entry.value, entry)
2092
+ }
2093
+ }
2094
+
2095
+ /**
2096
+ * Add a value to the cache.
2097
+ *
2098
+ * Note: if `undefined` is specified as a value, this is an alias for
2099
+ * {@link LRUCache#delete}
2100
+ *
2101
+ * Fields on the {@link LRUCache.SetOptions} options param will override
2102
+ * their corresponding values in the constructor options for the scope
2103
+ * of this single `set()` operation.
2104
+ *
2105
+ * If `start` is provided, then that will set the effective start
2106
+ * time for the TTL calculation. Note that this must be a previous
2107
+ * value of `performance.now()` if supported, or a previous value of
2108
+ * `Date.now()` if not.
2109
+ *
2110
+ * Options object may also include `size`, which will prevent
2111
+ * calling the `sizeCalculation` function and just use the specified
2112
+ * number if it is a positive integer, and `noDisposeOnSet` which
2113
+ * will prevent calling a `dispose` function in the case of
2114
+ * overwrites.
2115
+ *
2116
+ * If the `size` (or return value of `sizeCalculation`) for a given
2117
+ * entry is greater than `maxEntrySize`, then the item will not be
2118
+ * added to the cache.
2119
+ *
2120
+ * Will update the recency of the entry.
2121
+ *
2122
+ * If the value is `undefined`, then this is an alias for
2123
+ * `cache.delete(key)`. `undefined` is never stored in the cache.
2124
+ */
2125
+ set(
2126
+ k: K,
2127
+ v: V | undefined,
2128
+ setOptions: LRUCache.SetOptions<K, V, FC> = {},
2129
+ ) {
2130
+ const { status = metrics.hasSubscribers ? {} : undefined } = setOptions
2131
+ setOptions.status = status
2132
+ if (status) {
2133
+ status.op = 'set'
2134
+ status.key = k
2135
+ if (v !== undefined) status.value = v
2136
+ }
2137
+ const result = this.#set(k, v, setOptions)
2138
+ if (status && metrics.hasSubscribers) {
2139
+ metrics.publish(status)
2140
+ }
2141
+ return result
2142
+ }
2143
+
2144
+ #set(
2145
+ k: K,
2146
+ v: V | BackgroundFetch<V> | undefined,
2147
+ setOptions: LRUCache.SetOptions<K, V, FC> = {},
2148
+ ) {
2149
+ const {
2150
+ ttl = this.ttl,
2151
+ start,
2152
+ noDisposeOnSet = this.noDisposeOnSet,
2153
+ sizeCalculation = this.sizeCalculation,
2154
+ status,
2155
+ } = setOptions
2156
+
2157
+ if (v === undefined) {
2158
+ if (status) status.set = 'deleted'
2159
+ this.delete(k)
2160
+ return this
2161
+ }
2162
+ let { noUpdateTTL = this.noUpdateTTL } = setOptions
2163
+
2164
+ if (status && !this.#isBackgroundFetch(v)) status.value = v
2165
+
2166
+ const size = this.#requireSize(
2167
+ k,
2168
+ v,
2169
+ setOptions.size || 0,
2170
+ sizeCalculation,
2171
+ status,
2172
+ )
2173
+ // if the item doesn't fit, don't do anything
2174
+ // NB: maxEntrySize set to maxSize by default
2175
+ if (this.maxEntrySize && size > this.maxEntrySize) {
2176
+ // have to delete, in case something is there already.
2177
+ this.#delete(k, 'set')
2178
+ if (status) {
2179
+ status.set = 'miss'
2180
+ status.maxEntrySizeExceeded = true
2181
+ }
2182
+ return this
2183
+ }
2184
+ let index = this.#size === 0 ? undefined : this.#keyMap.get(k)
2185
+ if (index === undefined) {
2186
+ // addition
2187
+ index = (
2188
+ this.#size === 0 ? this.#tail
2189
+ : this.#free.length !== 0 ? this.#free.pop()
2190
+ : this.#size === this.#max ? this.#evict(false)
2191
+ : this.#size) as Index
2192
+ this.#keyList[index] = k
2193
+ this.#valList[index] = v
2194
+ this.#keyMap.set(k, index)
2195
+ this.#next[this.#tail] = index
2196
+ this.#prev[index] = this.#tail
2197
+ this.#tail = index
2198
+ this.#size++
2199
+ this.#addItemSize(index, size, status)
2200
+ if (status) status.set = 'add'
2201
+ noUpdateTTL = false
2202
+ if (this.#hasOnInsert) {
2203
+ this.#onInsert?.(v as V, k, 'add')
2204
+ }
2205
+ } else {
2206
+ // update
2207
+ this.#moveToTail(index)
2208
+ const oldVal = this.#valList[index] as V | BackgroundFetch<V>
2209
+ if (v !== oldVal) {
2210
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
2211
+ oldVal.__abortController.abort(new Error('replaced'))
2212
+ const { __staleWhileFetching: s } = oldVal
2213
+ if (s !== undefined && !noDisposeOnSet) {
2214
+ if (this.#hasDispose) {
2215
+ this.#dispose?.(s as V, k, 'set')
2216
+ }
2217
+ if (this.#hasDisposeAfter) {
2218
+ this.#disposed?.push([s as V, k, 'set'])
2219
+ }
2220
+ }
2221
+ } else if (!noDisposeOnSet) {
2222
+ if (this.#hasDispose) {
2223
+ this.#dispose?.(oldVal as V, k, 'set')
2224
+ }
2225
+ if (this.#hasDisposeAfter) {
2226
+ this.#disposed?.push([oldVal as V, k, 'set'])
2227
+ }
2228
+ }
2229
+ this.#removeItemSize(index)
2230
+ this.#addItemSize(index, size, status)
2231
+ this.#valList[index] = v
2232
+ if (status) {
2233
+ status.set = 'replace'
2234
+ const oldValue =
2235
+ oldVal && this.#isBackgroundFetch(oldVal) ?
2236
+ oldVal.__staleWhileFetching
2237
+ : oldVal
2238
+ if (oldValue !== undefined) status.oldValue = oldValue
2239
+ }
2240
+ } else if (status) {
2241
+ status.set = 'update'
2242
+ }
2243
+
2244
+ if (this.#hasOnInsert) {
2245
+ this.onInsert?.(v as V, k, v === oldVal ? 'update' : 'replace')
2246
+ }
2247
+ }
2248
+ if (ttl !== 0 && !this.#ttls) {
2249
+ this.#initializeTTLTracking()
2250
+ }
2251
+ if (this.#ttls) {
2252
+ if (!noUpdateTTL) {
2253
+ this.#setItemTTL(index, ttl, start)
2254
+ }
2255
+ if (status) this.#statusTTL(status, index)
2256
+ }
2257
+ if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
2258
+ const dt = this.#disposed
2259
+ let task: DisposeTask<K, V> | undefined
2260
+ while ((task = dt?.shift())) {
2261
+ this.#disposeAfter?.(...task)
2262
+ }
2263
+ }
2264
+ return this
2265
+ }
2266
+
2267
+ /**
2268
+ * Evict the least recently used item, returning its value or
2269
+ * `undefined` if cache is empty.
2270
+ */
2271
+ pop(): V | undefined {
2272
+ try {
2273
+ while (this.#size) {
2274
+ const val = this.#valList[this.#head]
2275
+ this.#evict(true)
2276
+ if (this.#isBackgroundFetch(val)) {
2277
+ if (val.__staleWhileFetching) {
2278
+ return val.__staleWhileFetching
2279
+ }
2280
+ } else if (val !== undefined) {
2281
+ return val
2282
+ }
2283
+ }
2284
+ } finally {
2285
+ if (this.#hasDisposeAfter && this.#disposed) {
2286
+ const dt = this.#disposed
2287
+ let task: DisposeTask<K, V> | undefined
2288
+ while ((task = dt?.shift())) {
2289
+ this.#disposeAfter?.(...task)
2290
+ }
2291
+ }
2292
+ }
2293
+ }
2294
+
2295
+ #evict(free: boolean) {
2296
+ const head = this.#head
2297
+ const k = this.#keyList[head] as K
2298
+ const v = this.#valList[head] as V
2299
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
2300
+ v.__abortController.abort(new Error('evicted'))
2301
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
2302
+ if (this.#hasDispose) {
2303
+ this.#dispose?.(v, k, 'evict')
2304
+ }
2305
+ if (this.#hasDisposeAfter) {
2306
+ this.#disposed?.push([v, k, 'evict'])
2307
+ }
2308
+ }
2309
+ this.#removeItemSize(head)
2310
+ if (this.#autopurgeTimers?.[head]) {
2311
+ clearTimeout(this.#autopurgeTimers[head])
2312
+ this.#autopurgeTimers[head] = undefined
2313
+ }
2314
+ // if we aren't about to use the index, then null these out
2315
+ if (free) {
2316
+ this.#keyList[head] = undefined
2317
+ this.#valList[head] = undefined
2318
+ this.#free.push(head)
2319
+ }
2320
+ if (this.#size === 1) {
2321
+ this.#head = this.#tail = 0 as Index
2322
+ this.#free.length = 0
2323
+ } else {
2324
+ this.#head = this.#next[head] as Index
2325
+ }
2326
+ this.#keyMap.delete(k)
2327
+ this.#size--
2328
+ return head
2329
+ }
2330
+
2331
+ /**
2332
+ * Check if a key is in the cache, without updating the recency of use.
2333
+ * Will return false if the item is stale, even though it is technically
2334
+ * in the cache.
2335
+ *
2336
+ * Check if a key is in the cache, without updating the recency of
2337
+ * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
2338
+ * to `true` in either the options or the constructor.
2339
+ *
2340
+ * Will return `false` if the item is stale, even though it is technically in
2341
+ * the cache. The difference can be determined (if it matters) by using a
2342
+ * `status` argument, and inspecting the `has` field.
2343
+ *
2344
+ * Will not update item age unless
2345
+ * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
2346
+ */
2347
+ has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {
2348
+ const { status = metrics.hasSubscribers ? {} : undefined } = hasOptions
2349
+ hasOptions.status = status
2350
+ if (status) {
2351
+ status.op = 'has'
2352
+ status.key = k
2353
+ }
2354
+ const result = this.#has(k, hasOptions)
2355
+ if (metrics.hasSubscribers) metrics.publish(status)
2356
+ return result
2357
+ }
2358
+ #has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {
2359
+ const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions
2360
+ const index = this.#keyMap.get(k)
2361
+ if (index !== undefined) {
2362
+ const v = this.#valList[index]
2363
+ if (
2364
+ this.#isBackgroundFetch(v) &&
2365
+ v.__staleWhileFetching === undefined
2366
+ ) {
2367
+ return false
2368
+ }
2369
+ if (!this.#isStale(index)) {
2370
+ if (updateAgeOnHas) {
2371
+ this.#updateItemAge(index)
2372
+ }
2373
+ if (status) {
2374
+ status.has = 'hit'
2375
+ this.#statusTTL(status, index)
2376
+ }
2377
+ return true
2378
+ } else if (status) {
2379
+ status.has = 'stale'
2380
+ this.#statusTTL(status, index)
2381
+ }
2382
+ } else if (status) {
2383
+ status.has = 'miss'
2384
+ }
2385
+ return false
2386
+ }
2387
+
2388
+ /**
2389
+ * Like {@link LRUCache#get} but doesn't update recency or delete stale
2390
+ * items.
2391
+ *
2392
+ * Returns `undefined` if the item is stale, unless
2393
+ * {@link LRUCache.OptionsBase.allowStale} is set.
2394
+ */
2395
+ peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC> = {}) {
2396
+ const { status = hasSubscribers() ? {} : undefined } = peekOptions
2397
+ if (status) {
2398
+ status.op = 'peek'
2399
+ status.key = k
2400
+ }
2401
+ peekOptions.status = status
2402
+ const result = this.#peek(k, peekOptions)
2403
+ if (metrics.hasSubscribers) {
2404
+ metrics.publish(status)
2405
+ }
2406
+ return result
2407
+ }
2408
+ #peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC>) {
2409
+ const { status, allowStale = this.allowStale } = peekOptions
2410
+ const index = this.#keyMap.get(k)
2411
+ if (index === undefined || (!allowStale && this.#isStale(index))) {
2412
+ if (status) status.peek = index === undefined ? 'miss' : 'stale'
2413
+ return undefined
2414
+ }
2415
+ const v = this.#valList[index]
2416
+ const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v
2417
+ if (status) {
2418
+ if (val !== undefined) {
2419
+ status.peek = 'hit'
2420
+ status.value = val
2421
+ } else {
2422
+ status.peek = 'miss'
2423
+ }
2424
+ }
2425
+ return val
2426
+ }
2427
+
2428
+ #backgroundFetch(
2429
+ k: K,
2430
+ index: Index | undefined,
2431
+ options: LRUCache.FetchOptions<K, V, FC>,
2432
+ context: FC,
2433
+ ): BackgroundFetch<V> {
2434
+ const v = index === undefined ? undefined : this.#valList[index]
2435
+ if (this.#isBackgroundFetch(v)) {
2436
+ return v
2437
+ }
2438
+
2439
+ const ac = new AbortController()
2440
+ const { signal } = options
2441
+ // when/if our AC signals, then stop listening to theirs.
2442
+ signal?.addEventListener('abort', () => ac.abort(signal.reason), {
2443
+ signal: ac.signal,
2444
+ })
2445
+
2446
+ const fetchOpts = {
2447
+ signal: ac.signal,
2448
+ options,
2449
+ context,
2450
+ }
2451
+
2452
+ const cb = (v: V | undefined, updateCache = false): V | undefined => {
2453
+ const { aborted } = ac.signal
2454
+ const ignoreAbort = options.ignoreFetchAbort && v !== undefined
2455
+ const proceed =
2456
+ options.ignoreFetchAbort ||
2457
+ !!(options.allowStaleOnFetchAbort && v !== undefined)
2458
+ if (options.status) {
2459
+ if (aborted && !updateCache) {
2460
+ options.status.fetchAborted = true
2461
+ options.status.fetchError = ac.signal.reason
2462
+ if (ignoreAbort) options.status.fetchAbortIgnored = true
2463
+ } else {
2464
+ options.status.fetchResolved = true
2465
+ }
2466
+ }
2467
+ if (aborted && !ignoreAbort && !updateCache) {
2468
+ return fetchFail(ac.signal.reason, proceed)
2469
+ }
2470
+ // either we didn't abort, and are still here, or we did, and ignored
2471
+ const bf = p as BackgroundFetch<V>
2472
+ // if nothing else has been written there but we're set to update the
2473
+ // cache and ignore the abort, or if it's still pending on this specific
2474
+ // background request, then write it to the cache.
2475
+ const vl = this.#valList[index as Index]
2476
+ if (vl === p || (vl === undefined && ignoreAbort && updateCache)) {
2477
+ if (v === undefined) {
2478
+ if (bf.__staleWhileFetching !== undefined) {
2479
+ this.#valList[index as Index] = bf.__staleWhileFetching
2480
+ } else {
2481
+ this.#delete(k, 'fetch')
2482
+ }
2483
+ } else {
2484
+ if (options.status) options.status.fetchUpdated = true
2485
+ this.#set(k, v, fetchOpts.options)
2486
+ }
2487
+ }
2488
+ return v
2489
+ }
2490
+
2491
+ const eb = (er: unknown) => {
2492
+ if (options.status) {
2493
+ options.status.fetchRejected = true
2494
+ options.status.fetchError = er as Error
2495
+ }
2496
+ // do not pass go, do not collect $200
2497
+ return fetchFail(er, false)
2498
+ }
2499
+
2500
+ const fetchFail = (er: unknown, proceed: boolean): V | undefined => {
2501
+ const { aborted } = ac.signal
2502
+ const allowStaleAborted = aborted && options.allowStaleOnFetchAbort
2503
+ const allowStale =
2504
+ allowStaleAborted || options.allowStaleOnFetchRejection
2505
+ const noDelete = allowStale || options.noDeleteOnFetchRejection
2506
+ const bf = p as BackgroundFetch<V>
2507
+ if (this.#valList[index as Index] === p) {
2508
+ // if we allow stale on fetch rejections, then we need to ensure that
2509
+ // the stale value is not removed from the cache when the fetch fails.
2510
+ const del =
2511
+ !noDelete || (!proceed && bf.__staleWhileFetching === undefined)
2512
+ if (del) {
2513
+ this.#delete(k, 'fetch')
2514
+ } else if (!allowStaleAborted) {
2515
+ // still replace the *promise* with the stale value,
2516
+ // since we are done with the promise at this point.
2517
+ // leave it untouched if we're still waiting for an
2518
+ // aborted background fetch that hasn't yet returned.
2519
+ this.#valList[index as Index] = bf.__staleWhileFetching
2520
+ }
2521
+ }
2522
+ if (allowStale) {
2523
+ if (options.status && bf.__staleWhileFetching !== undefined) {
2524
+ options.status.returnedStale = true
2525
+ }
2526
+ return bf.__staleWhileFetching
2527
+ } else if (bf.__returned === bf) {
2528
+ throw er
2529
+ }
2530
+ }
2531
+
2532
+ const pcall = (
2533
+ res: (v: V | undefined) => void,
2534
+ rej: (e: unknown) => void,
2535
+ ) => {
2536
+ const fmp = this.#fetchMethod?.(k, v, fetchOpts)
2537
+ if (fmp && fmp instanceof Promise) {
2538
+ fmp.then(v => res(v === undefined ? undefined : v), rej)
2539
+ }
2540
+ // ignored, we go until we finish, regardless.
2541
+ // defer check until we are actually aborting,
2542
+ // so fetchMethod can override.
2543
+ ac.signal.addEventListener('abort', () => {
2544
+ if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
2545
+ res(undefined)
2546
+ // when it eventually resolves, update the cache.
2547
+ if (options.allowStaleOnFetchAbort) {
2548
+ res = v => cb(v, true)
2549
+ }
2550
+ }
2551
+ })
2552
+ }
2553
+
2554
+ if (options.status) options.status.fetchDispatched = true
2555
+ const p = new Promise(pcall).then(cb, eb)
2556
+ const bf: BackgroundFetch<V> = Object.assign(p, {
2557
+ __abortController: ac,
2558
+ __staleWhileFetching: v,
2559
+ __returned: undefined,
2560
+ })
2561
+
2562
+ if (index === undefined) {
2563
+ // internal, don't expose status.
2564
+ this.#set(k, bf, { ...fetchOpts.options, status: undefined })
2565
+ index = this.#keyMap.get(k)
2566
+ } else {
2567
+ this.#valList[index] = bf
2568
+ }
2569
+ return bf
2570
+ }
2571
+
2572
+ #isBackgroundFetch(p: unknown): p is BackgroundFetch<V> {
2573
+ if (!this.#hasFetchMethod) return false
2574
+ const b = p as BackgroundFetch<V>
2575
+ return (
2576
+ !!b &&
2577
+ b instanceof Promise &&
2578
+ b.hasOwnProperty('__staleWhileFetching') &&
2579
+ b.__abortController instanceof AbortController
2580
+ )
2581
+ }
2582
+
2583
+ /**
2584
+ * Make an asynchronous cached fetch using the
2585
+ * {@link LRUCache.OptionsBase.fetchMethod} function.
2586
+ *
2587
+ * If the value is in the cache and not stale, then the returned
2588
+ * Promise resolves to the value.
2589
+ *
2590
+ * If not in the cache, or beyond its TTL staleness, then
2591
+ * `fetchMethod(key, staleValue, { options, signal, context })` is
2592
+ * called, and the value returned will be added to the cache once
2593
+ * resolved.
2594
+ *
2595
+ * If called with `allowStale`, and an asynchronous fetch is
2596
+ * currently in progress to reload a stale value, then the former
2597
+ * stale value will be returned.
2598
+ *
2599
+ * If called with `forceRefresh`, then the cached item will be
2600
+ * re-fetched, even if it is not stale. However, if `allowStale` is also
2601
+ * set, then the old value will still be returned. This is useful
2602
+ * in cases where you want to force a reload of a cached value. If
2603
+ * a background fetch is already in progress, then `forceRefresh`
2604
+ * has no effect.
2605
+ *
2606
+ * If multiple fetches for the same key are issued, then they will all be
2607
+ * coalesced into a single call to fetchMethod.
2608
+ *
2609
+ * Note that this means that handling options such as
2610
+ * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},
2611
+ * {@link LRUCache.FetchOptions.signal},
2612
+ * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be
2613
+ * determined by the FIRST fetch() call for a given key.
2614
+ *
2615
+ * This is a known (fixable) shortcoming which will be addresed on when
2616
+ * someone complains about it, as the fix would involve added complexity and
2617
+ * may not be worth the costs for this edge case.
2618
+ *
2619
+ * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is
2620
+ * effectively an alias for `Promise.resolve(cache.get(key))`.
2621
+ *
2622
+ * When the fetch method resolves to a value, if the fetch has not
2623
+ * been aborted due to deletion, eviction, or being overwritten,
2624
+ * then it is added to the cache using the options provided.
2625
+ *
2626
+ * If the key is evicted or deleted before the `fetchMethod`
2627
+ * resolves, then the AbortSignal passed to the `fetchMethod` will
2628
+ * receive an `abort` event, and the promise returned by `fetch()`
2629
+ * will reject with the reason for the abort.
2630
+ *
2631
+ * If a `signal` is passed to the `fetch()` call, then aborting the
2632
+ * signal will abort the fetch and cause the `fetch()` promise to
2633
+ * reject with the reason provided.
2634
+ *
2635
+ * **Setting `context`**
2636
+ *
2637
+ * If an `FC` type is set to a type other than `unknown`, `void`, or
2638
+ * `undefined` in the {@link LRUCache} constructor, then all
2639
+ * calls to `cache.fetch()` _must_ provide a `context` option. If
2640
+ * set to `undefined` or `void`, then calls to fetch _must not_
2641
+ * provide a `context` option.
2642
+ *
2643
+ * The `context` param allows you to provide arbitrary data that
2644
+ * might be relevant in the course of fetching the data. It is only
2645
+ * relevant for the course of a single `fetch()` operation, and
2646
+ * discarded afterwards.
2647
+ *
2648
+ * **Note: `fetch()` calls are inflight-unique**
2649
+ *
2650
+ * If you call `fetch()` multiple times with the same key value,
2651
+ * then every call after the first will resolve on the same
2652
+ * promise<sup>1</sup>,
2653
+ * _even if they have different settings that would otherwise change
2654
+ * the behavior of the fetch_, such as `noDeleteOnFetchRejection`
2655
+ * or `ignoreFetchAbort`.
2656
+ *
2657
+ * In most cases, this is not a problem (in fact, only fetching
2658
+ * something once is what you probably want, if you're caching in
2659
+ * the first place). If you are changing the fetch() options
2660
+ * dramatically between runs, there's a good chance that you might
2661
+ * be trying to fit divergent semantics into a single object, and
2662
+ * would be better off with multiple cache instances.
2663
+ *
2664
+ * **1**: Ie, they're not the "same Promise", but they resolve at
2665
+ * the same time, because they're both waiting on the same
2666
+ * underlying fetchMethod response.
2667
+ */
2668
+
2669
+ fetch(
2670
+ k: K,
2671
+ fetchOptions: unknown extends FC ? LRUCache.FetchOptions<K, V, FC>
2672
+ : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V>
2673
+ : LRUCache.FetchOptionsWithContext<K, V, FC>,
2674
+ ): Promise<undefined | V>
2675
+
2676
+ // this overload not allowed if context is required
2677
+ fetch(
2678
+ k: unknown extends FC ? K
2679
+ : FC extends undefined | void ? K
2680
+ : never,
2681
+ fetchOptions?: unknown extends FC ? LRUCache.FetchOptions<K, V, FC>
2682
+ : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V>
2683
+ : never,
2684
+ ): Promise<undefined | V>
2685
+ fetch(
2686
+ k: K,
2687
+ fetchOptions: LRUCache.FetchOptions<K, V, FC> = {},
2688
+ ): Promise<undefined | V> {
2689
+ const ths = tracing.hasSubscribers
2690
+ const { status = hasSubscribers() ? {} : undefined } = fetchOptions
2691
+ fetchOptions.status = status
2692
+ if (status && fetchOptions.context) {
2693
+ status.context = fetchOptions.context
2694
+ }
2695
+ const p = this.#fetch(k, fetchOptions)
2696
+ if (status && ths) {
2697
+ status.trace = true
2698
+ tracing.tracePromise(() => p, status).catch(() => {})
2699
+ }
2700
+ return p
2701
+ }
2702
+
2703
+ async #fetch(
2704
+ k: K,
2705
+ fetchOptions: LRUCache.FetchOptions<K, V, FC> = {},
2706
+ ): Promise<undefined | V> {
2707
+ const {
2708
+ // get options
2709
+ allowStale = this.allowStale,
2710
+ updateAgeOnGet = this.updateAgeOnGet,
2711
+ noDeleteOnStaleGet = this.noDeleteOnStaleGet,
2712
+ // set options
2713
+ ttl = this.ttl,
2714
+ noDisposeOnSet = this.noDisposeOnSet,
2715
+ size = 0,
2716
+ sizeCalculation = this.sizeCalculation,
2717
+ noUpdateTTL = this.noUpdateTTL,
2718
+ // fetch exclusive options
2719
+ noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
2720
+ allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
2721
+ ignoreFetchAbort = this.ignoreFetchAbort,
2722
+ allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
2723
+ context,
2724
+ forceRefresh = false,
2725
+ status,
2726
+ signal,
2727
+ } = fetchOptions
2728
+ if (status) {
2729
+ status.op = 'fetch'
2730
+ status.key = k
2731
+ if (forceRefresh) status.forceRefresh = true
2732
+ }
2733
+
2734
+ if (!this.#hasFetchMethod) {
2735
+ if (status) status.fetch = 'get'
2736
+ return this.#get(k, {
2737
+ allowStale,
2738
+ updateAgeOnGet,
2739
+ noDeleteOnStaleGet,
2740
+ status,
2741
+ })
2742
+ }
2743
+
2744
+ const options = {
2745
+ allowStale,
2746
+ updateAgeOnGet,
2747
+ noDeleteOnStaleGet,
2748
+ ttl,
2749
+ noDisposeOnSet,
2750
+ size,
2751
+ sizeCalculation,
2752
+ noUpdateTTL,
2753
+ noDeleteOnFetchRejection,
2754
+ allowStaleOnFetchRejection,
2755
+ allowStaleOnFetchAbort,
2756
+ ignoreFetchAbort,
2757
+ status,
2758
+ signal,
2759
+ }
2760
+
2761
+ let index = this.#keyMap.get(k)
2762
+ if (index === undefined) {
2763
+ if (status) status.fetch = 'miss'
2764
+ const p = this.#backgroundFetch(k, index, options, context as FC)
2765
+ return (p.__returned = p)
2766
+ } else {
2767
+ // in cache, maybe already fetching
2768
+ const v = this.#valList[index]
2769
+ if (this.#isBackgroundFetch(v)) {
2770
+ const stale = allowStale && v.__staleWhileFetching !== undefined
2771
+ if (status) {
2772
+ status.fetch = 'inflight'
2773
+ if (stale) status.returnedStale = true
2774
+ }
2775
+ return stale ? v.__staleWhileFetching : (v.__returned = v)
2776
+ }
2777
+
2778
+ // if we force a refresh, that means do NOT serve the cached value,
2779
+ // unless we are already in the process of refreshing the cache.
2780
+ const isStale = this.#isStale(index)
2781
+ if (!forceRefresh && !isStale) {
2782
+ if (status) status.fetch = 'hit'
2783
+ this.#moveToTail(index)
2784
+ if (updateAgeOnGet) {
2785
+ this.#updateItemAge(index)
2786
+ }
2787
+ if (status) this.#statusTTL(status, index)
2788
+ return v
2789
+ }
2790
+
2791
+ // ok, it is stale or a forced refresh, and not already fetching.
2792
+ // refresh the cache.
2793
+ const p = this.#backgroundFetch(k, index, options, context as FC)
2794
+ const hasStale = p.__staleWhileFetching !== undefined
2795
+ const staleVal = hasStale && allowStale
2796
+ if (status) {
2797
+ status.fetch = isStale ? 'stale' : 'refresh'
2798
+ if (staleVal && isStale) status.returnedStale = true
2799
+ }
2800
+ return staleVal ? p.__staleWhileFetching : (p.__returned = p)
2801
+ }
2802
+ }
2803
+
2804
+ /**
2805
+ * In some cases, `cache.fetch()` may resolve to `undefined`, either because
2806
+ * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning
2807
+ * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or
2808
+ * because `ignoreFetchAbort` was specified (either to the constructor or
2809
+ * in the {@link LRUCache.FetchOptions}). Also, the
2810
+ * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making
2811
+ * the test even more complicated.
2812
+ *
2813
+ * Because inferring the cases where `undefined` might be returned are so
2814
+ * cumbersome, but testing for `undefined` can also be annoying, this method
2815
+ * can be used, which will reject if `this.fetch()` resolves to undefined.
2816
+ */
2817
+ forceFetch(
2818
+ k: K,
2819
+ fetchOptions: unknown extends FC ? LRUCache.FetchOptions<K, V, FC>
2820
+ : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V>
2821
+ : LRUCache.FetchOptionsWithContext<K, V, FC>,
2822
+ ): Promise<V>
2823
+ // this overload not allowed if context is required
2824
+ forceFetch(
2825
+ k: unknown extends FC ? K
2826
+ : FC extends undefined | void ? K
2827
+ : never,
2828
+ fetchOptions?: unknown extends FC ? LRUCache.FetchOptions<K, V, FC>
2829
+ : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V>
2830
+ : never,
2831
+ ): Promise<V>
2832
+ forceFetch(
2833
+ k: K,
2834
+ fetchOptions: LRUCache.FetchOptions<K, V, FC> = {},
2835
+ ): Promise<V> {
2836
+ const ths = tracing.hasSubscribers
2837
+ const { status = hasSubscribers() ? {} : undefined } = fetchOptions
2838
+ fetchOptions.status = status
2839
+ if (status && fetchOptions.context) {
2840
+ status.context = fetchOptions.context
2841
+ }
2842
+ const p = this.#forceFetch(k, fetchOptions)
2843
+ if (status && ths) {
2844
+ status.trace = true
2845
+ tracing.tracePromise(() => p, status).catch(() => {})
2846
+ }
2847
+ return p
2848
+ }
2849
+
2850
+ async #forceFetch(
2851
+ k: K,
2852
+ fetchOptions: LRUCache.FetchOptions<K, V, FC> = {},
2853
+ ) {
2854
+ const v = await this.#fetch(
2855
+ k,
2856
+ fetchOptions as unknown extends FC ? LRUCache.FetchOptions<K, V, FC>
2857
+ : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V>
2858
+ : LRUCache.FetchOptionsWithContext<K, V, FC>,
2859
+ )
2860
+ if (v === undefined) throw new Error('fetch() returned undefined')
2861
+ return v
2862
+ }
2863
+
2864
+ /**
2865
+ * If the key is found in the cache, then this is equivalent to
2866
+ * {@link LRUCache#get}. If not, in the cache, then calculate the value using
2867
+ * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.
2868
+ *
2869
+ * If an `FC` type is set to a type other than `unknown`, `void`, or
2870
+ * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`
2871
+ * _must_ provide a `context` option. If set to `undefined` or `void`, then
2872
+ * calls to memo _must not_ provide a `context` option.
2873
+ *
2874
+ * The `context` param allows you to provide arbitrary data that might be
2875
+ * relevant in the course of fetching the data. It is only relevant for the
2876
+ * course of a single `memo()` operation, and discarded afterwards.
2877
+ */
2878
+ memo(
2879
+ k: K,
2880
+ memoOptions: unknown extends FC ? LRUCache.MemoOptions<K, V, FC>
2881
+ : FC extends undefined | void ? LRUCache.MemoOptionsNoContext<K, V>
2882
+ : LRUCache.MemoOptionsWithContext<K, V, FC>,
2883
+ ): V
2884
+ // this overload not allowed if context is required
2885
+ memo(
2886
+ k: unknown extends FC ? K
2887
+ : FC extends undefined | void ? K
2888
+ : never,
2889
+ memoOptions?: unknown extends FC ? LRUCache.MemoOptions<K, V, FC>
2890
+ : FC extends undefined | void ? LRUCache.MemoOptionsNoContext<K, V>
2891
+ : never,
2892
+ ): V
2893
+ memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {
2894
+ const { status = metrics.hasSubscribers ? {} : undefined } =
2895
+ memoOptions
2896
+ memoOptions.status = status
2897
+ if (status) {
2898
+ status.op = 'memo'
2899
+ status.key = k
2900
+ if (memoOptions.context) {
2901
+ status.context = memoOptions.context
2902
+ }
2903
+ }
2904
+ const result = this.#memo(k, memoOptions)
2905
+ if (status) status.value = result
2906
+ if (metrics.hasSubscribers) metrics.publish(status)
2907
+ return result
2908
+ }
2909
+ #memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {
2910
+ const memoMethod = this.#memoMethod
2911
+ if (!memoMethod) {
2912
+ throw new Error('no memoMethod provided to constructor')
2913
+ }
2914
+ const { context, status, forceRefresh, ...options } = memoOptions
2915
+ if (status && forceRefresh) status.forceRefresh = true
2916
+ const v = this.#get(k, options)
2917
+ const refresh = forceRefresh || v === undefined
2918
+ if (status) {
2919
+ status.memo = refresh ? 'miss' : 'hit'
2920
+ if (!refresh) status.value = v
2921
+ }
2922
+ if (!refresh) return v
2923
+ const vv = memoMethod(k, v, {
2924
+ options,
2925
+ context,
2926
+ } as LRUCache.MemoizerOptions<K, V, FC>)
2927
+ if (status) status.value = vv
2928
+ this.#set(k, vv, options)
2929
+ return vv
2930
+ }
2931
+
2932
+ /**
2933
+ * Return a value from the cache. Will update the recency of the cache
2934
+ * entry found.
2935
+ *
2936
+ * If the key is not found, get() will return `undefined`.
2937
+ */
2938
+ get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {
2939
+ const { status = metrics.hasSubscribers ? {} : undefined } = getOptions
2940
+ getOptions.status = status
2941
+ if (status) {
2942
+ status.op = 'get'
2943
+ status.key = k
2944
+ }
2945
+ const result = this.#get(k, getOptions)
2946
+ if (status) {
2947
+ if (result !== undefined) status.value = result
2948
+ if (metrics.hasSubscribers) metrics.publish(status)
2949
+ }
2950
+ return result
2951
+ }
2952
+
2953
+ #get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {
2954
+ const {
2955
+ allowStale = this.allowStale,
2956
+ updateAgeOnGet = this.updateAgeOnGet,
2957
+ noDeleteOnStaleGet = this.noDeleteOnStaleGet,
2958
+ status,
2959
+ } = getOptions
2960
+ const index = this.#keyMap.get(k)
2961
+ if (index === undefined) {
2962
+ if (status) status.get = 'miss'
2963
+ return undefined
2964
+ }
2965
+ const value = this.#valList[index]
2966
+ const fetching = this.#isBackgroundFetch(value)
2967
+ if (status) this.#statusTTL(status, index)
2968
+ if (this.#isStale(index)) {
2969
+ // delete only if not an in-flight background fetch
2970
+ if (!fetching) {
2971
+ if (!noDeleteOnStaleGet) {
2972
+ this.#delete(k, 'expire')
2973
+ }
2974
+ if (status) status.get = 'stale'
2975
+ if (allowStale) {
2976
+ if (status) status.returnedStale = true
2977
+ return value
2978
+ }
2979
+ return undefined
2980
+ }
2981
+ if (status) status.get = 'stale-fetching'
2982
+ if (allowStale && value.__staleWhileFetching !== undefined) {
2983
+ if (status) status.returnedStale = true
2984
+ return value.__staleWhileFetching
2985
+ }
2986
+ return undefined
2987
+ }
2988
+ // not stale
2989
+ if (status) status.get = fetching ? 'fetching' : 'hit'
2990
+ // if we're currently fetching it, we don't actually have it yet
2991
+ // it's not stale, which means this isn't a staleWhileRefetching.
2992
+ // If it's not stale, and fetching, AND has a __staleWhileFetching
2993
+ // value, then that means the user fetched with {forceRefresh:true},
2994
+ // so it's safe to return that value.
2995
+ this.#moveToTail(index)
2996
+ if (updateAgeOnGet) {
2997
+ this.#updateItemAge(index)
2998
+ }
2999
+ return fetching ? value.__staleWhileFetching : value
3000
+ }
3001
+
3002
+ #connect(p: Index, n: Index) {
3003
+ this.#prev[n] = p
3004
+ this.#next[p] = n
3005
+ }
3006
+
3007
+ #moveToTail(index: Index): void {
3008
+ // if tail already, nothing to do
3009
+ // if head, move head to next[index]
3010
+ // else
3011
+ // move next[prev[index]] to next[index] (head has no prev)
3012
+ // move prev[next[index]] to prev[index]
3013
+ // prev[index] = tail
3014
+ // next[tail] = index
3015
+ // tail = index
3016
+ if (index !== this.#tail) {
3017
+ if (index === this.#head) {
3018
+ this.#head = this.#next[index] as Index
3019
+ } else {
3020
+ this.#connect(
3021
+ this.#prev[index] as Index,
3022
+ this.#next[index] as Index,
3023
+ )
3024
+ }
3025
+ this.#connect(this.#tail, index)
3026
+ this.#tail = index
3027
+ }
3028
+ }
3029
+
3030
+ /**
3031
+ * Deletes a key out of the cache.
3032
+ *
3033
+ * Returns true if the key was deleted, false otherwise.
3034
+ */
3035
+ delete(k: K) {
3036
+ return this.#delete(k, 'delete')
3037
+ }
3038
+
3039
+ #delete(k: K, reason: LRUCache.DisposeReason) {
3040
+ if (metrics.hasSubscribers) {
3041
+ metrics.publish({
3042
+ op: 'delete',
3043
+ delete: reason,
3044
+ key: k,
3045
+ })
3046
+ }
3047
+ let deleted = false
3048
+ if (this.#size !== 0) {
3049
+ const index = this.#keyMap.get(k)
3050
+ if (index !== undefined) {
3051
+ if (this.#autopurgeTimers?.[index]) {
3052
+ clearTimeout(this.#autopurgeTimers?.[index])
3053
+ this.#autopurgeTimers[index] = undefined
3054
+ }
3055
+ deleted = true
3056
+ if (this.#size === 1) {
3057
+ this.#clear(reason)
3058
+ } else {
3059
+ this.#removeItemSize(index)
3060
+ const v = this.#valList[index]
3061
+ if (this.#isBackgroundFetch(v)) {
3062
+ v.__abortController.abort(new Error('deleted'))
3063
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
3064
+ if (this.#hasDispose) {
3065
+ this.#dispose?.(v as V, k, reason)
3066
+ }
3067
+ if (this.#hasDisposeAfter) {
3068
+ this.#disposed?.push([v as V, k, reason])
3069
+ }
3070
+ }
3071
+ this.#keyMap.delete(k)
3072
+ this.#keyList[index] = undefined
3073
+ this.#valList[index] = undefined
3074
+ if (index === this.#tail) {
3075
+ this.#tail = this.#prev[index] as Index
3076
+ } else if (index === this.#head) {
3077
+ this.#head = this.#next[index] as Index
3078
+ } else {
3079
+ const pi = this.#prev[index] as number
3080
+ this.#next[pi] = this.#next[index] as number
3081
+ const ni = this.#next[index] as number
3082
+ this.#prev[ni] = this.#prev[index] as number
3083
+ }
3084
+ this.#size--
3085
+ this.#free.push(index)
3086
+ }
3087
+ }
3088
+ }
3089
+ if (this.#hasDisposeAfter && this.#disposed?.length) {
3090
+ const dt = this.#disposed
3091
+ let task: DisposeTask<K, V> | undefined
3092
+ while ((task = dt?.shift())) {
3093
+ this.#disposeAfter?.(...task)
3094
+ }
3095
+ }
3096
+ return deleted
3097
+ }
3098
+
3099
+ /**
3100
+ * Clear the cache entirely, throwing away all values.
3101
+ */
3102
+ clear() {
3103
+ return this.#clear('delete')
3104
+ }
3105
+ #clear(reason: LRUCache.DisposeReason) {
3106
+ for (const index of this.#rindexes({ allowStale: true })) {
3107
+ const v = this.#valList[index]
3108
+ if (this.#isBackgroundFetch(v)) {
3109
+ v.__abortController.abort(new Error('deleted'))
3110
+ } else {
3111
+ const k = this.#keyList[index]
3112
+ if (this.#hasDispose) {
3113
+ this.#dispose?.(v as V, k as K, reason)
3114
+ }
3115
+ if (this.#hasDisposeAfter) {
3116
+ this.#disposed?.push([v as V, k as K, reason])
3117
+ }
3118
+ }
3119
+ }
3120
+
3121
+ this.#keyMap.clear()
3122
+ this.#valList.fill(undefined)
3123
+ this.#keyList.fill(undefined)
3124
+ if (this.#ttls && this.#starts) {
3125
+ this.#ttls.fill(0)
3126
+ this.#starts.fill(0)
3127
+ for (const t of this.#autopurgeTimers ?? []) {
3128
+ if (t !== undefined) clearTimeout(t)
3129
+ }
3130
+ this.#autopurgeTimers?.fill(undefined)
3131
+ }
3132
+ if (this.#sizes) {
3133
+ this.#sizes.fill(0)
3134
+ }
3135
+ this.#head = 0 as Index
3136
+ this.#tail = 0 as Index
3137
+ this.#free.length = 0
3138
+ this.#calculatedSize = 0
3139
+ this.#size = 0
3140
+ if (this.#hasDisposeAfter && this.#disposed) {
3141
+ const dt = this.#disposed
3142
+ let task: DisposeTask<K, V> | undefined
3143
+ while ((task = dt?.shift())) {
3144
+ this.#disposeAfter?.(...task)
3145
+ }
3146
+ }
3147
+ }
3148
+ }