@sentio/sdk 2.57.12-rc.j → 2.57.13-rc.1

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 (250) hide show
  1. package/lib/core/template.d.ts +1 -5
  2. package/lib/core/template.d.ts.map +1 -1
  3. package/lib/core/template.js +1 -4
  4. package/lib/core/template.js.map +1 -1
  5. package/lib/store/store.d.ts +2 -2
  6. package/lib/store/store.d.ts.map +1 -1
  7. package/lib/store/store.js.map +1 -1
  8. package/package.json +3 -3
  9. package/src/core/template.ts +1 -6
  10. package/src/store/store.ts +2 -3
  11. package/lib/chunk-2F2KNF4Z.js +0 -71905
  12. package/lib/chunk-2F2KNF4Z.js.map +0 -1
  13. package/lib/chunk-43HP4DQZ.js +0 -47
  14. package/lib/chunk-43HP4DQZ.js.map +0 -1
  15. package/lib/chunk-4HPFNKDX.js +0 -6763
  16. package/lib/chunk-4HPFNKDX.js.map +0 -1
  17. package/lib/chunk-4OCWUYSJ.js +0 -898
  18. package/lib/chunk-4OCWUYSJ.js.map +0 -1
  19. package/lib/chunk-6UVWNOIX.js +0 -4207
  20. package/lib/chunk-6UVWNOIX.js.map +0 -1
  21. package/lib/chunk-73SHERGU.js +0 -23970
  22. package/lib/chunk-73SHERGU.js.map +0 -1
  23. package/lib/chunk-742S42NO.js +0 -1323
  24. package/lib/chunk-742S42NO.js.map +0 -1
  25. package/lib/chunk-7ECRTQD7.js +0 -26757
  26. package/lib/chunk-7ECRTQD7.js.map +0 -1
  27. package/lib/chunk-7IDGS56O.js +0 -5058
  28. package/lib/chunk-7IDGS56O.js.map +0 -1
  29. package/lib/chunk-7S6WQ4RL.js +0 -1069
  30. package/lib/chunk-7S6WQ4RL.js.map +0 -1
  31. package/lib/chunk-AZFMPZRN.js +0 -3613
  32. package/lib/chunk-AZFMPZRN.js.map +0 -1
  33. package/lib/chunk-BZCXYTDE.js +0 -1333
  34. package/lib/chunk-BZCXYTDE.js.map +0 -1
  35. package/lib/chunk-E2DS6WZF.js +0 -1690
  36. package/lib/chunk-E2DS6WZF.js.map +0 -1
  37. package/lib/chunk-GE6BRIGS.js +0 -1721
  38. package/lib/chunk-GE6BRIGS.js.map +0 -1
  39. package/lib/chunk-J3I3VNTV.js +0 -767
  40. package/lib/chunk-J3I3VNTV.js.map +0 -1
  41. package/lib/chunk-J3QOJ2RV.js +0 -661
  42. package/lib/chunk-J3QOJ2RV.js.map +0 -1
  43. package/lib/chunk-J5UEW4B7.js +0 -1351
  44. package/lib/chunk-J5UEW4B7.js.map +0 -1
  45. package/lib/chunk-LPSNAS2G.js +0 -460
  46. package/lib/chunk-LPSNAS2G.js.map +0 -1
  47. package/lib/chunk-LR232ZJV.js +0 -2593
  48. package/lib/chunk-LR232ZJV.js.map +0 -1
  49. package/lib/chunk-N36N7RXJ.js +0 -653
  50. package/lib/chunk-N36N7RXJ.js.map +0 -1
  51. package/lib/chunk-OJG2VJ5T.js +0 -7063
  52. package/lib/chunk-OJG2VJ5T.js.map +0 -1
  53. package/lib/chunk-ONBEMKI5.js +0 -323
  54. package/lib/chunk-ONBEMKI5.js.map +0 -1
  55. package/lib/chunk-PVX2LIM5.js +0 -205
  56. package/lib/chunk-PVX2LIM5.js.map +0 -1
  57. package/lib/chunk-R7PMHHKJ.js +0 -52
  58. package/lib/chunk-R7PMHHKJ.js.map +0 -1
  59. package/lib/chunk-RMT2JEWA.js +0 -7740
  60. package/lib/chunk-RMT2JEWA.js.map +0 -1
  61. package/lib/chunk-S6MJ3KIL.js +0 -27798
  62. package/lib/chunk-S6MJ3KIL.js.map +0 -1
  63. package/lib/chunk-UEFVZL4I.js +0 -199
  64. package/lib/chunk-UEFVZL4I.js.map +0 -1
  65. package/lib/chunk-UIBPOKNT.js +0 -945
  66. package/lib/chunk-UIBPOKNT.js.map +0 -1
  67. package/lib/chunk-ZR7UHHH2.js +0 -5
  68. package/lib/chunk-ZR7UHHH2.js.map +0 -1
  69. package/lib/multipart-parser-SQIYSR67.js +0 -368
  70. package/lib/multipart-parser-SQIYSR67.js.map +0 -1
  71. package/src/aptos/builtin/0x1.d.ts +0 -6451
  72. package/src/aptos/builtin/0x1.d.ts.map +0 -1
  73. package/src/aptos/builtin/0x1.js +0 -7138
  74. package/src/aptos/builtin/0x1.js.map +0 -1
  75. package/src/aptos/builtin/0x3.d.ts +0 -1122
  76. package/src/aptos/builtin/0x3.d.ts.map +0 -1
  77. package/src/aptos/builtin/0x3.js +0 -937
  78. package/src/aptos/builtin/0x3.js.map +0 -1
  79. package/src/aptos/builtin/0x4.d.ts +0 -551
  80. package/src/aptos/builtin/0x4.d.ts.map +0 -1
  81. package/src/aptos/builtin/0x4.js +0 -529
  82. package/src/aptos/builtin/0x4.js.map +0 -1
  83. package/src/aptos/builtin/index.d.ts +0 -4
  84. package/src/aptos/builtin/index.d.ts.map +0 -1
  85. package/src/aptos/builtin/index.js +0 -7
  86. package/src/aptos/builtin/index.js.map +0 -1
  87. package/src/eth/builtin/eacaggregatorproxy.d.ts +0 -5
  88. package/src/eth/builtin/eacaggregatorproxy.d.ts.map +0 -1
  89. package/src/eth/builtin/eacaggregatorproxy.js +0 -8
  90. package/src/eth/builtin/eacaggregatorproxy.js.map +0 -1
  91. package/src/eth/builtin/erc1155.d.ts +0 -5
  92. package/src/eth/builtin/erc1155.d.ts.map +0 -1
  93. package/src/eth/builtin/erc1155.js +0 -8
  94. package/src/eth/builtin/erc1155.js.map +0 -1
  95. package/src/eth/builtin/erc20.d.ts +0 -5
  96. package/src/eth/builtin/erc20.d.ts.map +0 -1
  97. package/src/eth/builtin/erc20.js +0 -8
  98. package/src/eth/builtin/erc20.js.map +0 -1
  99. package/src/eth/builtin/erc20bytes.d.ts +0 -5
  100. package/src/eth/builtin/erc20bytes.d.ts.map +0 -1
  101. package/src/eth/builtin/erc20bytes.js +0 -8
  102. package/src/eth/builtin/erc20bytes.js.map +0 -1
  103. package/src/eth/builtin/erc721.d.ts +0 -5
  104. package/src/eth/builtin/erc721.d.ts.map +0 -1
  105. package/src/eth/builtin/erc721.js +0 -8
  106. package/src/eth/builtin/erc721.js.map +0 -1
  107. package/src/eth/builtin/index.d.ts +0 -13
  108. package/src/eth/builtin/index.d.ts.map +0 -1
  109. package/src/eth/builtin/index.js +0 -16
  110. package/src/eth/builtin/index.js.map +0 -1
  111. package/src/eth/builtin/internal/EACAggregatorProxy.d.ts +0 -50
  112. package/src/eth/builtin/internal/EACAggregatorProxy.d.ts.map +0 -1
  113. package/src/eth/builtin/internal/EACAggregatorProxy.js +0 -2
  114. package/src/eth/builtin/internal/EACAggregatorProxy.js.map +0 -1
  115. package/src/eth/builtin/internal/ERC1155.d.ts +0 -57
  116. package/src/eth/builtin/internal/ERC1155.d.ts.map +0 -1
  117. package/src/eth/builtin/internal/ERC1155.js +0 -2
  118. package/src/eth/builtin/internal/ERC1155.js.map +0 -1
  119. package/src/eth/builtin/internal/ERC20.d.ts +0 -41
  120. package/src/eth/builtin/internal/ERC20.d.ts.map +0 -1
  121. package/src/eth/builtin/internal/ERC20.js +0 -2
  122. package/src/eth/builtin/internal/ERC20.js.map +0 -1
  123. package/src/eth/builtin/internal/ERC20Bytes.d.ts +0 -32
  124. package/src/eth/builtin/internal/ERC20Bytes.d.ts.map +0 -1
  125. package/src/eth/builtin/internal/ERC20Bytes.js +0 -2
  126. package/src/eth/builtin/internal/ERC20Bytes.js.map +0 -1
  127. package/src/eth/builtin/internal/ERC721.d.ts +0 -43
  128. package/src/eth/builtin/internal/ERC721.d.ts.map +0 -1
  129. package/src/eth/builtin/internal/ERC721.js +0 -2
  130. package/src/eth/builtin/internal/ERC721.js.map +0 -1
  131. package/src/eth/builtin/internal/WETH9.d.ts +0 -47
  132. package/src/eth/builtin/internal/WETH9.d.ts.map +0 -1
  133. package/src/eth/builtin/internal/WETH9.js +0 -2
  134. package/src/eth/builtin/internal/WETH9.js.map +0 -1
  135. package/src/eth/builtin/internal/common.d.ts +0 -3
  136. package/src/eth/builtin/internal/common.d.ts.map +0 -1
  137. package/src/eth/builtin/internal/common.js +0 -8
  138. package/src/eth/builtin/internal/common.js.map +0 -1
  139. package/src/eth/builtin/internal/eacaggregatorproxy-processor.d.ts +0 -373
  140. package/src/eth/builtin/internal/eacaggregatorproxy-processor.d.ts.map +0 -1
  141. package/src/eth/builtin/internal/eacaggregatorproxy-processor.js +0 -1355
  142. package/src/eth/builtin/internal/eacaggregatorproxy-processor.js.map +0 -1
  143. package/src/eth/builtin/internal/eacaggregatorproxy-test-utils.d.ts +0 -7
  144. package/src/eth/builtin/internal/eacaggregatorproxy-test-utils.d.ts.map +0 -1
  145. package/src/eth/builtin/internal/eacaggregatorproxy-test-utils.js +0 -55
  146. package/src/eth/builtin/internal/eacaggregatorproxy-test-utils.js.map +0 -1
  147. package/src/eth/builtin/internal/erc1155-processor.d.ts +0 -173
  148. package/src/eth/builtin/internal/erc1155-processor.d.ts.map +0 -1
  149. package/src/eth/builtin/internal/erc1155-processor.js +0 -596
  150. package/src/eth/builtin/internal/erc1155-processor.js.map +0 -1
  151. package/src/eth/builtin/internal/erc1155-test-utils.d.ts +0 -7
  152. package/src/eth/builtin/internal/erc1155-test-utils.d.ts.map +0 -1
  153. package/src/eth/builtin/internal/erc1155-test-utils.js +0 -55
  154. package/src/eth/builtin/internal/erc1155-test-utils.js.map +0 -1
  155. package/src/eth/builtin/internal/erc20-processor.d.ts +0 -244
  156. package/src/eth/builtin/internal/erc20-processor.d.ts.map +0 -1
  157. package/src/eth/builtin/internal/erc20-processor.js +0 -1109
  158. package/src/eth/builtin/internal/erc20-processor.js.map +0 -1
  159. package/src/eth/builtin/internal/erc20-test-utils.d.ts +0 -6
  160. package/src/eth/builtin/internal/erc20-test-utils.d.ts.map +0 -1
  161. package/src/eth/builtin/internal/erc20-test-utils.js +0 -44
  162. package/src/eth/builtin/internal/erc20-test-utils.js.map +0 -1
  163. package/src/eth/builtin/internal/erc20bytes-processor.d.ts +0 -144
  164. package/src/eth/builtin/internal/erc20bytes-processor.d.ts.map +0 -1
  165. package/src/eth/builtin/internal/erc20bytes-processor.js +0 -594
  166. package/src/eth/builtin/internal/erc20bytes-processor.js.map +0 -1
  167. package/src/eth/builtin/internal/erc20bytes-test-utils.d.ts +0 -5
  168. package/src/eth/builtin/internal/erc20bytes-test-utils.d.ts.map +0 -1
  169. package/src/eth/builtin/internal/erc20bytes-test-utils.js +0 -33
  170. package/src/eth/builtin/internal/erc20bytes-test-utils.js.map +0 -1
  171. package/src/eth/builtin/internal/erc721-processor.d.ts +0 -215
  172. package/src/eth/builtin/internal/erc721-processor.d.ts.map +0 -1
  173. package/src/eth/builtin/internal/erc721-processor.js +0 -895
  174. package/src/eth/builtin/internal/erc721-processor.js.map +0 -1
  175. package/src/eth/builtin/internal/erc721-test-utils.d.ts +0 -6
  176. package/src/eth/builtin/internal/erc721-test-utils.d.ts.map +0 -1
  177. package/src/eth/builtin/internal/erc721-test-utils.js +0 -44
  178. package/src/eth/builtin/internal/erc721-test-utils.js.map +0 -1
  179. package/src/eth/builtin/internal/factories/EACAggregatorProxy__factory.d.ts +0 -400
  180. package/src/eth/builtin/internal/factories/EACAggregatorProxy__factory.d.ts.map +0 -1
  181. package/src/eth/builtin/internal/factories/EACAggregatorProxy__factory.js +0 -524
  182. package/src/eth/builtin/internal/factories/EACAggregatorProxy__factory.js.map +0 -1
  183. package/src/eth/builtin/internal/factories/ERC1155__factory.d.ts +0 -251
  184. package/src/eth/builtin/internal/factories/ERC1155__factory.d.ts.map +0 -1
  185. package/src/eth/builtin/internal/factories/ERC1155__factory.js +0 -329
  186. package/src/eth/builtin/internal/factories/ERC1155__factory.js.map +0 -1
  187. package/src/eth/builtin/internal/factories/ERC20Bytes__factory.d.ts +0 -185
  188. package/src/eth/builtin/internal/factories/ERC20Bytes__factory.d.ts.map +0 -1
  189. package/src/eth/builtin/internal/factories/ERC20Bytes__factory.js +0 -251
  190. package/src/eth/builtin/internal/factories/ERC20Bytes__factory.js.map +0 -1
  191. package/src/eth/builtin/internal/factories/ERC20__factory.d.ts +0 -303
  192. package/src/eth/builtin/internal/factories/ERC20__factory.d.ts.map +0 -1
  193. package/src/eth/builtin/internal/factories/ERC20__factory.js +0 -401
  194. package/src/eth/builtin/internal/factories/ERC20__factory.js.map +0 -1
  195. package/src/eth/builtin/internal/factories/ERC721__factory.d.ts +0 -273
  196. package/src/eth/builtin/internal/factories/ERC721__factory.d.ts.map +0 -1
  197. package/src/eth/builtin/internal/factories/ERC721__factory.js +0 -361
  198. package/src/eth/builtin/internal/factories/ERC721__factory.js.map +0 -1
  199. package/src/eth/builtin/internal/factories/WETH9__factory.d.ts +0 -220
  200. package/src/eth/builtin/internal/factories/WETH9__factory.d.ts.map +0 -1
  201. package/src/eth/builtin/internal/factories/WETH9__factory.js +0 -294
  202. package/src/eth/builtin/internal/factories/WETH9__factory.js.map +0 -1
  203. package/src/eth/builtin/internal/factories/index.d.ts +0 -7
  204. package/src/eth/builtin/internal/factories/index.d.ts.map +0 -1
  205. package/src/eth/builtin/internal/factories/index.js +0 -10
  206. package/src/eth/builtin/internal/factories/index.js.map +0 -1
  207. package/src/eth/builtin/internal/index.d.ts +0 -14
  208. package/src/eth/builtin/internal/index.d.ts.map +0 -1
  209. package/src/eth/builtin/internal/index.js +0 -8
  210. package/src/eth/builtin/internal/index.js.map +0 -1
  211. package/src/eth/builtin/internal/weth9-processor.d.ts +0 -172
  212. package/src/eth/builtin/internal/weth9-processor.d.ts.map +0 -1
  213. package/src/eth/builtin/internal/weth9-processor.js +0 -729
  214. package/src/eth/builtin/internal/weth9-processor.js.map +0 -1
  215. package/src/eth/builtin/internal/weth9-test-utils.d.ts +0 -7
  216. package/src/eth/builtin/internal/weth9-test-utils.d.ts.map +0 -1
  217. package/src/eth/builtin/internal/weth9-test-utils.js +0 -55
  218. package/src/eth/builtin/internal/weth9-test-utils.js.map +0 -1
  219. package/src/eth/builtin/weth9.d.ts +0 -5
  220. package/src/eth/builtin/weth9.d.ts.map +0 -1
  221. package/src/eth/builtin/weth9.js +0 -8
  222. package/src/eth/builtin/weth9.js.map +0 -1
  223. package/src/solana/builtin/index.d.ts +0 -2
  224. package/src/solana/builtin/index.d.ts.map +0 -1
  225. package/src/solana/builtin/index.js +0 -2
  226. package/src/solana/builtin/index.js.map +0 -1
  227. package/src/solana/builtin/spl-token-processor.d.ts +0 -40
  228. package/src/solana/builtin/spl-token-processor.d.ts.map +0 -1
  229. package/src/solana/builtin/spl-token-processor.js +0 -254
  230. package/src/solana/builtin/spl-token-processor.js.map +0 -1
  231. package/src/solana/builtin/types.d.ts +0 -428
  232. package/src/solana/builtin/types.d.ts.map +0 -1
  233. package/src/solana/builtin/types.js +0 -201
  234. package/src/solana/builtin/types.js.map +0 -1
  235. package/src/sui/builtin/0x1.d.ts +0 -114
  236. package/src/sui/builtin/0x1.d.ts.map +0 -1
  237. package/src/sui/builtin/0x1.js +0 -159
  238. package/src/sui/builtin/0x1.js.map +0 -1
  239. package/src/sui/builtin/0x2.d.ts +0 -1250
  240. package/src/sui/builtin/0x2.d.ts.map +0 -1
  241. package/src/sui/builtin/0x2.js +0 -1511
  242. package/src/sui/builtin/0x2.js.map +0 -1
  243. package/src/sui/builtin/0x3.d.ts +0 -774
  244. package/src/sui/builtin/0x3.d.ts.map +0 -1
  245. package/src/sui/builtin/0x3.js +0 -720
  246. package/src/sui/builtin/0x3.js.map +0 -1
  247. package/src/sui/builtin/index.d.ts +0 -4
  248. package/src/sui/builtin/index.d.ts.map +0 -1
  249. package/src/sui/builtin/index.js +0 -7
  250. package/src/sui/builtin/index.js.map +0 -1
@@ -1,3613 +0,0 @@
1
- import { createRequire as createRequireSdkShim } from 'module'; const require = createRequireSdkShim(import.meta.url);
2
- import {
3
- getERC20BytesContract
4
- } from "./chunk-J3QOJ2RV.js";
5
- import {
6
- getEACAggregatorProxyContract
7
- } from "./chunk-BZCXYTDE.js";
8
- import {
9
- EthChainId,
10
- SimpleEthersError,
11
- getERC20Contract
12
- } from "./chunk-OJG2VJ5T.js";
13
- import {
14
- decodeBytes32String
15
- } from "./chunk-RMT2JEWA.js";
16
- import {
17
- BaseContext,
18
- scaleDown
19
- } from "./chunk-2F2KNF4Z.js";
20
- import {
21
- __export,
22
- __name
23
- } from "./chunk-R7PMHHKJ.js";
24
-
25
- // src/utils/block.ts
26
- async function getBlockSafely(provider, blockNumber) {
27
- const block = await provider.getBlock(blockNumber);
28
- if (!block) {
29
- throw new Error(`Block ${blockNumber} not found.`);
30
- }
31
- return block;
32
- }
33
- __name(getBlockSafely, "getBlockSafely");
34
- async function estimateBlockNumberAtDate(provider, targetDate, startBlock) {
35
- const targetTimestamp = Math.floor(targetDate.getTime() / 1e3);
36
- const latestBlock = await getBlockSafely(provider, "latest");
37
- const earliestBlockNumber = startBlock !== void 0 ? startBlock : 0;
38
- const earliestBlock = await getBlockSafely(provider, earliestBlockNumber);
39
- let low = earliestBlock.number;
40
- let high = latestBlock.number;
41
- while (low <= high) {
42
- const mid = Math.floor((low + high) / 2);
43
- const midBlock = await getBlockSafely(provider, mid);
44
- if (midBlock.timestamp === targetTimestamp) {
45
- return midBlock.number;
46
- } else if (midBlock.timestamp < targetTimestamp) {
47
- low = mid + 1;
48
- } else {
49
- high = mid - 1;
50
- }
51
- }
52
- const closestBlock = await getBlockSafely(provider, high);
53
- return closestBlock.number;
54
- }
55
- __name(estimateBlockNumberAtDate, "estimateBlockNumberAtDate");
56
- import("node:process").then((p) => p.stdout.write(""));
57
-
58
- // src/utils/conversion.ts
59
- function bytesToBigInt(bytes) {
60
- let intValue = BigInt(0);
61
- for (let i = 0; i < bytes.length; i++) {
62
- intValue = intValue * BigInt(256) + BigInt(bytes[i]);
63
- }
64
- return intValue;
65
- }
66
- __name(bytesToBigInt, "bytesToBigInt");
67
- import("node:process").then((p) => p.stdout.write(""));
68
-
69
- // src/utils/token.ts
70
- var token_exports = {};
71
- __export(token_exports, {
72
- NATIVE_ETH: () => NATIVE_ETH,
73
- getER20NormalizedAmount: () => getER20NormalizedAmount,
74
- getERC20TokenInfo: () => getERC20TokenInfo
75
- });
76
-
77
- // ../../node_modules/.pnpm/lru-cache@11.0.0/node_modules/lru-cache/dist/esm/index.js
78
- var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
79
- var warned = /* @__PURE__ */ new Set();
80
- var PROCESS = typeof process === "object" && !!process ? process : {};
81
- var emitWarning = /* @__PURE__ */ __name((msg, type, code, fn) => {
82
- typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
83
- }, "emitWarning");
84
- var AC = globalThis.AbortController;
85
- var AS = globalThis.AbortSignal;
86
- if (typeof AC === "undefined") {
87
- AS = class AbortSignal {
88
- static {
89
- __name(this, "AbortSignal");
90
- }
91
- onabort;
92
- _onabort = [];
93
- reason;
94
- aborted = false;
95
- addEventListener(_, fn) {
96
- this._onabort.push(fn);
97
- }
98
- };
99
- AC = class AbortController {
100
- static {
101
- __name(this, "AbortController");
102
- }
103
- constructor() {
104
- warnACPolyfill();
105
- }
106
- signal = new AS();
107
- abort(reason) {
108
- if (this.signal.aborted)
109
- return;
110
- this.signal.reason = reason;
111
- this.signal.aborted = true;
112
- for (const fn of this.signal._onabort) {
113
- fn(reason);
114
- }
115
- this.signal.onabort?.(reason);
116
- }
117
- };
118
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
119
- const warnACPolyfill = /* @__PURE__ */ __name(() => {
120
- if (!printACPolyfillWarning)
121
- return;
122
- printACPolyfillWarning = false;
123
- emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
124
- }, "warnACPolyfill");
125
- }
126
- var shouldWarn = /* @__PURE__ */ __name((code) => !warned.has(code), "shouldWarn");
127
- var TYPE = Symbol("type");
128
- var isPosInt = /* @__PURE__ */ __name((n) => n && n === Math.floor(n) && n > 0 && isFinite(n), "isPosInt");
129
- var getUintArray = /* @__PURE__ */ __name((max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null, "getUintArray");
130
- var ZeroArray = class extends Array {
131
- static {
132
- __name(this, "ZeroArray");
133
- }
134
- constructor(size) {
135
- super(size);
136
- this.fill(0);
137
- }
138
- };
139
- var Stack = class _Stack {
140
- static {
141
- __name(this, "Stack");
142
- }
143
- heap;
144
- length;
145
- // private constructor
146
- static #constructing = false;
147
- static create(max) {
148
- const HeapCls = getUintArray(max);
149
- if (!HeapCls)
150
- return [];
151
- _Stack.#constructing = true;
152
- const s = new _Stack(max, HeapCls);
153
- _Stack.#constructing = false;
154
- return s;
155
- }
156
- constructor(max, HeapCls) {
157
- if (!_Stack.#constructing) {
158
- throw new TypeError("instantiate Stack using Stack.create(n)");
159
- }
160
- this.heap = new HeapCls(max);
161
- this.length = 0;
162
- }
163
- push(n) {
164
- this.heap[this.length++] = n;
165
- }
166
- pop() {
167
- return this.heap[--this.length];
168
- }
169
- };
170
- var LRUCache = class _LRUCache {
171
- static {
172
- __name(this, "LRUCache");
173
- }
174
- // options that cannot be changed without disaster
175
- #max;
176
- #maxSize;
177
- #dispose;
178
- #disposeAfter;
179
- #fetchMethod;
180
- #memoMethod;
181
- /**
182
- * {@link LRUCache.OptionsBase.ttl}
183
- */
184
- ttl;
185
- /**
186
- * {@link LRUCache.OptionsBase.ttlResolution}
187
- */
188
- ttlResolution;
189
- /**
190
- * {@link LRUCache.OptionsBase.ttlAutopurge}
191
- */
192
- ttlAutopurge;
193
- /**
194
- * {@link LRUCache.OptionsBase.updateAgeOnGet}
195
- */
196
- updateAgeOnGet;
197
- /**
198
- * {@link LRUCache.OptionsBase.updateAgeOnHas}
199
- */
200
- updateAgeOnHas;
201
- /**
202
- * {@link LRUCache.OptionsBase.allowStale}
203
- */
204
- allowStale;
205
- /**
206
- * {@link LRUCache.OptionsBase.noDisposeOnSet}
207
- */
208
- noDisposeOnSet;
209
- /**
210
- * {@link LRUCache.OptionsBase.noUpdateTTL}
211
- */
212
- noUpdateTTL;
213
- /**
214
- * {@link LRUCache.OptionsBase.maxEntrySize}
215
- */
216
- maxEntrySize;
217
- /**
218
- * {@link LRUCache.OptionsBase.sizeCalculation}
219
- */
220
- sizeCalculation;
221
- /**
222
- * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
223
- */
224
- noDeleteOnFetchRejection;
225
- /**
226
- * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
227
- */
228
- noDeleteOnStaleGet;
229
- /**
230
- * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
231
- */
232
- allowStaleOnFetchAbort;
233
- /**
234
- * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
235
- */
236
- allowStaleOnFetchRejection;
237
- /**
238
- * {@link LRUCache.OptionsBase.ignoreFetchAbort}
239
- */
240
- ignoreFetchAbort;
241
- // computed properties
242
- #size;
243
- #calculatedSize;
244
- #keyMap;
245
- #keyList;
246
- #valList;
247
- #next;
248
- #prev;
249
- #head;
250
- #tail;
251
- #free;
252
- #disposed;
253
- #sizes;
254
- #starts;
255
- #ttls;
256
- #hasDispose;
257
- #hasFetchMethod;
258
- #hasDisposeAfter;
259
- /**
260
- * Do not call this method unless you need to inspect the
261
- * inner workings of the cache. If anything returned by this
262
- * object is modified in any way, strange breakage may occur.
263
- *
264
- * These fields are private for a reason!
265
- *
266
- * @internal
267
- */
268
- static unsafeExposeInternals(c) {
269
- return {
270
- // properties
271
- starts: c.#starts,
272
- ttls: c.#ttls,
273
- sizes: c.#sizes,
274
- keyMap: c.#keyMap,
275
- keyList: c.#keyList,
276
- valList: c.#valList,
277
- next: c.#next,
278
- prev: c.#prev,
279
- get head() {
280
- return c.#head;
281
- },
282
- get tail() {
283
- return c.#tail;
284
- },
285
- free: c.#free,
286
- // methods
287
- isBackgroundFetch: /* @__PURE__ */ __name((p) => c.#isBackgroundFetch(p), "isBackgroundFetch"),
288
- backgroundFetch: /* @__PURE__ */ __name((k, index, options, context) => c.#backgroundFetch(k, index, options, context), "backgroundFetch"),
289
- moveToTail: /* @__PURE__ */ __name((index) => c.#moveToTail(index), "moveToTail"),
290
- indexes: /* @__PURE__ */ __name((options) => c.#indexes(options), "indexes"),
291
- rindexes: /* @__PURE__ */ __name((options) => c.#rindexes(options), "rindexes"),
292
- isStale: /* @__PURE__ */ __name((index) => c.#isStale(index), "isStale")
293
- };
294
- }
295
- // Protected read-only members
296
- /**
297
- * {@link LRUCache.OptionsBase.max} (read-only)
298
- */
299
- get max() {
300
- return this.#max;
301
- }
302
- /**
303
- * {@link LRUCache.OptionsBase.maxSize} (read-only)
304
- */
305
- get maxSize() {
306
- return this.#maxSize;
307
- }
308
- /**
309
- * The total computed size of items in the cache (read-only)
310
- */
311
- get calculatedSize() {
312
- return this.#calculatedSize;
313
- }
314
- /**
315
- * The number of items stored in the cache (read-only)
316
- */
317
- get size() {
318
- return this.#size;
319
- }
320
- /**
321
- * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
322
- */
323
- get fetchMethod() {
324
- return this.#fetchMethod;
325
- }
326
- get memoMethod() {
327
- return this.#memoMethod;
328
- }
329
- /**
330
- * {@link LRUCache.OptionsBase.dispose} (read-only)
331
- */
332
- get dispose() {
333
- return this.#dispose;
334
- }
335
- /**
336
- * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
337
- */
338
- get disposeAfter() {
339
- return this.#disposeAfter;
340
- }
341
- constructor(options) {
342
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
343
- if (max !== 0 && !isPosInt(max)) {
344
- throw new TypeError("max option must be a nonnegative integer");
345
- }
346
- const UintArray = max ? getUintArray(max) : Array;
347
- if (!UintArray) {
348
- throw new Error("invalid max value: " + max);
349
- }
350
- this.#max = max;
351
- this.#maxSize = maxSize;
352
- this.maxEntrySize = maxEntrySize || this.#maxSize;
353
- this.sizeCalculation = sizeCalculation;
354
- if (this.sizeCalculation) {
355
- if (!this.#maxSize && !this.maxEntrySize) {
356
- throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
357
- }
358
- if (typeof this.sizeCalculation !== "function") {
359
- throw new TypeError("sizeCalculation set to non-function");
360
- }
361
- }
362
- if (memoMethod !== void 0 && typeof memoMethod !== "function") {
363
- throw new TypeError("memoMethod must be a function if defined");
364
- }
365
- this.#memoMethod = memoMethod;
366
- if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
367
- throw new TypeError("fetchMethod must be a function if specified");
368
- }
369
- this.#fetchMethod = fetchMethod;
370
- this.#hasFetchMethod = !!fetchMethod;
371
- this.#keyMap = /* @__PURE__ */ new Map();
372
- this.#keyList = new Array(max).fill(void 0);
373
- this.#valList = new Array(max).fill(void 0);
374
- this.#next = new UintArray(max);
375
- this.#prev = new UintArray(max);
376
- this.#head = 0;
377
- this.#tail = 0;
378
- this.#free = Stack.create(max);
379
- this.#size = 0;
380
- this.#calculatedSize = 0;
381
- if (typeof dispose === "function") {
382
- this.#dispose = dispose;
383
- }
384
- if (typeof disposeAfter === "function") {
385
- this.#disposeAfter = disposeAfter;
386
- this.#disposed = [];
387
- } else {
388
- this.#disposeAfter = void 0;
389
- this.#disposed = void 0;
390
- }
391
- this.#hasDispose = !!this.#dispose;
392
- this.#hasDisposeAfter = !!this.#disposeAfter;
393
- this.noDisposeOnSet = !!noDisposeOnSet;
394
- this.noUpdateTTL = !!noUpdateTTL;
395
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
396
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
397
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
398
- this.ignoreFetchAbort = !!ignoreFetchAbort;
399
- if (this.maxEntrySize !== 0) {
400
- if (this.#maxSize !== 0) {
401
- if (!isPosInt(this.#maxSize)) {
402
- throw new TypeError("maxSize must be a positive integer if specified");
403
- }
404
- }
405
- if (!isPosInt(this.maxEntrySize)) {
406
- throw new TypeError("maxEntrySize must be a positive integer if specified");
407
- }
408
- this.#initializeSizeTracking();
409
- }
410
- this.allowStale = !!allowStale;
411
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
412
- this.updateAgeOnGet = !!updateAgeOnGet;
413
- this.updateAgeOnHas = !!updateAgeOnHas;
414
- this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
415
- this.ttlAutopurge = !!ttlAutopurge;
416
- this.ttl = ttl || 0;
417
- if (this.ttl) {
418
- if (!isPosInt(this.ttl)) {
419
- throw new TypeError("ttl must be a positive integer if specified");
420
- }
421
- this.#initializeTTLTracking();
422
- }
423
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
424
- throw new TypeError("At least one of max, maxSize, or ttl is required");
425
- }
426
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
427
- const code = "LRU_CACHE_UNBOUNDED";
428
- if (shouldWarn(code)) {
429
- warned.add(code);
430
- const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
431
- emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
432
- }
433
- }
434
- }
435
- /**
436
- * Return the number of ms left in the item's TTL. If item is not in cache,
437
- * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
438
- */
439
- getRemainingTTL(key) {
440
- return this.#keyMap.has(key) ? Infinity : 0;
441
- }
442
- #initializeTTLTracking() {
443
- const ttls = new ZeroArray(this.#max);
444
- const starts = new ZeroArray(this.#max);
445
- this.#ttls = ttls;
446
- this.#starts = starts;
447
- this.#setItemTTL = (index, ttl, start = perf.now()) => {
448
- starts[index] = ttl !== 0 ? start : 0;
449
- ttls[index] = ttl;
450
- if (ttl !== 0 && this.ttlAutopurge) {
451
- const t = setTimeout(() => {
452
- if (this.#isStale(index)) {
453
- this.#delete(this.#keyList[index], "expire");
454
- }
455
- }, ttl + 1);
456
- if (t.unref) {
457
- t.unref();
458
- }
459
- }
460
- };
461
- this.#updateItemAge = (index) => {
462
- starts[index] = ttls[index] !== 0 ? perf.now() : 0;
463
- };
464
- this.#statusTTL = (status, index) => {
465
- if (ttls[index]) {
466
- const ttl = ttls[index];
467
- const start = starts[index];
468
- if (!ttl || !start)
469
- return;
470
- status.ttl = ttl;
471
- status.start = start;
472
- status.now = cachedNow || getNow();
473
- const age = status.now - start;
474
- status.remainingTTL = ttl - age;
475
- }
476
- };
477
- let cachedNow = 0;
478
- const getNow = /* @__PURE__ */ __name(() => {
479
- const n = perf.now();
480
- if (this.ttlResolution > 0) {
481
- cachedNow = n;
482
- const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
483
- if (t.unref) {
484
- t.unref();
485
- }
486
- }
487
- return n;
488
- }, "getNow");
489
- this.getRemainingTTL = (key) => {
490
- const index = this.#keyMap.get(key);
491
- if (index === void 0) {
492
- return 0;
493
- }
494
- const ttl = ttls[index];
495
- const start = starts[index];
496
- if (!ttl || !start) {
497
- return Infinity;
498
- }
499
- const age = (cachedNow || getNow()) - start;
500
- return ttl - age;
501
- };
502
- this.#isStale = (index) => {
503
- const s = starts[index];
504
- const t = ttls[index];
505
- return !!t && !!s && (cachedNow || getNow()) - s > t;
506
- };
507
- }
508
- // conditionally set private methods related to TTL
509
- #updateItemAge = /* @__PURE__ */ __name(() => {
510
- }, "#updateItemAge");
511
- #statusTTL = /* @__PURE__ */ __name(() => {
512
- }, "#statusTTL");
513
- #setItemTTL = /* @__PURE__ */ __name(() => {
514
- }, "#setItemTTL");
515
- /* c8 ignore stop */
516
- #isStale = /* @__PURE__ */ __name(() => false, "#isStale");
517
- #initializeSizeTracking() {
518
- const sizes = new ZeroArray(this.#max);
519
- this.#calculatedSize = 0;
520
- this.#sizes = sizes;
521
- this.#removeItemSize = (index) => {
522
- this.#calculatedSize -= sizes[index];
523
- sizes[index] = 0;
524
- };
525
- this.#requireSize = (k, v, size, sizeCalculation) => {
526
- if (this.#isBackgroundFetch(v)) {
527
- return 0;
528
- }
529
- if (!isPosInt(size)) {
530
- if (sizeCalculation) {
531
- if (typeof sizeCalculation !== "function") {
532
- throw new TypeError("sizeCalculation must be a function");
533
- }
534
- size = sizeCalculation(v, k);
535
- if (!isPosInt(size)) {
536
- throw new TypeError("sizeCalculation return invalid (expect positive integer)");
537
- }
538
- } else {
539
- throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
540
- }
541
- }
542
- return size;
543
- };
544
- this.#addItemSize = (index, size, status) => {
545
- sizes[index] = size;
546
- if (this.#maxSize) {
547
- const maxSize = this.#maxSize - sizes[index];
548
- while (this.#calculatedSize > maxSize) {
549
- this.#evict(true);
550
- }
551
- }
552
- this.#calculatedSize += sizes[index];
553
- if (status) {
554
- status.entrySize = size;
555
- status.totalCalculatedSize = this.#calculatedSize;
556
- }
557
- };
558
- }
559
- #removeItemSize = /* @__PURE__ */ __name((_i) => {
560
- }, "#removeItemSize");
561
- #addItemSize = /* @__PURE__ */ __name((_i, _s, _st) => {
562
- }, "#addItemSize");
563
- #requireSize = /* @__PURE__ */ __name((_k, _v, size, sizeCalculation) => {
564
- if (size || sizeCalculation) {
565
- throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
566
- }
567
- return 0;
568
- }, "#requireSize");
569
- *#indexes({ allowStale = this.allowStale } = {}) {
570
- if (this.#size) {
571
- for (let i = this.#tail; true; ) {
572
- if (!this.#isValidIndex(i)) {
573
- break;
574
- }
575
- if (allowStale || !this.#isStale(i)) {
576
- yield i;
577
- }
578
- if (i === this.#head) {
579
- break;
580
- } else {
581
- i = this.#prev[i];
582
- }
583
- }
584
- }
585
- }
586
- *#rindexes({ allowStale = this.allowStale } = {}) {
587
- if (this.#size) {
588
- for (let i = this.#head; true; ) {
589
- if (!this.#isValidIndex(i)) {
590
- break;
591
- }
592
- if (allowStale || !this.#isStale(i)) {
593
- yield i;
594
- }
595
- if (i === this.#tail) {
596
- break;
597
- } else {
598
- i = this.#next[i];
599
- }
600
- }
601
- }
602
- }
603
- #isValidIndex(index) {
604
- return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
605
- }
606
- /**
607
- * Return a generator yielding `[key, value]` pairs,
608
- * in order from most recently used to least recently used.
609
- */
610
- *entries() {
611
- for (const i of this.#indexes()) {
612
- if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
613
- yield [this.#keyList[i], this.#valList[i]];
614
- }
615
- }
616
- }
617
- /**
618
- * Inverse order version of {@link LRUCache.entries}
619
- *
620
- * Return a generator yielding `[key, value]` pairs,
621
- * in order from least recently used to most recently used.
622
- */
623
- *rentries() {
624
- for (const i of this.#rindexes()) {
625
- if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
626
- yield [this.#keyList[i], this.#valList[i]];
627
- }
628
- }
629
- }
630
- /**
631
- * Return a generator yielding the keys in the cache,
632
- * in order from most recently used to least recently used.
633
- */
634
- *keys() {
635
- for (const i of this.#indexes()) {
636
- const k = this.#keyList[i];
637
- if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
638
- yield k;
639
- }
640
- }
641
- }
642
- /**
643
- * Inverse order version of {@link LRUCache.keys}
644
- *
645
- * Return a generator yielding the keys in the cache,
646
- * in order from least recently used to most recently used.
647
- */
648
- *rkeys() {
649
- for (const i of this.#rindexes()) {
650
- const k = this.#keyList[i];
651
- if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
652
- yield k;
653
- }
654
- }
655
- }
656
- /**
657
- * Return a generator yielding the values in the cache,
658
- * in order from most recently used to least recently used.
659
- */
660
- *values() {
661
- for (const i of this.#indexes()) {
662
- const v = this.#valList[i];
663
- if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
664
- yield this.#valList[i];
665
- }
666
- }
667
- }
668
- /**
669
- * Inverse order version of {@link LRUCache.values}
670
- *
671
- * Return a generator yielding the values in the cache,
672
- * in order from least recently used to most recently used.
673
- */
674
- *rvalues() {
675
- for (const i of this.#rindexes()) {
676
- const v = this.#valList[i];
677
- if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
678
- yield this.#valList[i];
679
- }
680
- }
681
- }
682
- /**
683
- * Iterating over the cache itself yields the same results as
684
- * {@link LRUCache.entries}
685
- */
686
- [Symbol.iterator]() {
687
- return this.entries();
688
- }
689
- /**
690
- * A String value that is used in the creation of the default string
691
- * description of an object. Called by the built-in method
692
- * `Object.prototype.toString`.
693
- */
694
- [Symbol.toStringTag] = "LRUCache";
695
- /**
696
- * Find a value for which the supplied fn method returns a truthy value,
697
- * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
698
- */
699
- find(fn, getOptions = {}) {
700
- for (const i of this.#indexes()) {
701
- const v = this.#valList[i];
702
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
703
- if (value === void 0)
704
- continue;
705
- if (fn(value, this.#keyList[i], this)) {
706
- return this.get(this.#keyList[i], getOptions);
707
- }
708
- }
709
- }
710
- /**
711
- * Call the supplied function on each item in the cache, in order from most
712
- * recently used to least recently used.
713
- *
714
- * `fn` is called as `fn(value, key, cache)`.
715
- *
716
- * If `thisp` is provided, function will be called in the `this`-context of
717
- * the provided object, or the cache if no `thisp` object is provided.
718
- *
719
- * Does not update age or recenty of use, or iterate over stale values.
720
- */
721
- forEach(fn, thisp = this) {
722
- for (const i of this.#indexes()) {
723
- const v = this.#valList[i];
724
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
725
- if (value === void 0)
726
- continue;
727
- fn.call(thisp, value, this.#keyList[i], this);
728
- }
729
- }
730
- /**
731
- * The same as {@link LRUCache.forEach} but items are iterated over in
732
- * reverse order. (ie, less recently used items are iterated over first.)
733
- */
734
- rforEach(fn, thisp = this) {
735
- for (const i of this.#rindexes()) {
736
- const v = this.#valList[i];
737
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
738
- if (value === void 0)
739
- continue;
740
- fn.call(thisp, value, this.#keyList[i], this);
741
- }
742
- }
743
- /**
744
- * Delete any stale entries. Returns true if anything was removed,
745
- * false otherwise.
746
- */
747
- purgeStale() {
748
- let deleted = false;
749
- for (const i of this.#rindexes({ allowStale: true })) {
750
- if (this.#isStale(i)) {
751
- this.#delete(this.#keyList[i], "expire");
752
- deleted = true;
753
- }
754
- }
755
- return deleted;
756
- }
757
- /**
758
- * Get the extended info about a given entry, to get its value, size, and
759
- * TTL info simultaneously. Returns `undefined` if the key is not present.
760
- *
761
- * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
762
- * serialization, the `start` value is always the current timestamp, and the
763
- * `ttl` is a calculated remaining time to live (negative if expired).
764
- *
765
- * Always returns stale values, if their info is found in the cache, so be
766
- * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
767
- * if relevant.
768
- */
769
- info(key) {
770
- const i = this.#keyMap.get(key);
771
- if (i === void 0)
772
- return void 0;
773
- const v = this.#valList[i];
774
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
775
- if (value === void 0)
776
- return void 0;
777
- const entry = { value };
778
- if (this.#ttls && this.#starts) {
779
- const ttl = this.#ttls[i];
780
- const start = this.#starts[i];
781
- if (ttl && start) {
782
- const remain = ttl - (perf.now() - start);
783
- entry.ttl = remain;
784
- entry.start = Date.now();
785
- }
786
- }
787
- if (this.#sizes) {
788
- entry.size = this.#sizes[i];
789
- }
790
- return entry;
791
- }
792
- /**
793
- * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
794
- * passed to {@link LRLUCache#load}.
795
- *
796
- * The `start` fields are calculated relative to a portable `Date.now()`
797
- * timestamp, even if `performance.now()` is available.
798
- *
799
- * Stale entries are always included in the `dump`, even if
800
- * {@link LRUCache.OptionsBase.allowStale} is false.
801
- *
802
- * Note: this returns an actual array, not a generator, so it can be more
803
- * easily passed around.
804
- */
805
- dump() {
806
- const arr = [];
807
- for (const i of this.#indexes({ allowStale: true })) {
808
- const key = this.#keyList[i];
809
- const v = this.#valList[i];
810
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
811
- if (value === void 0 || key === void 0)
812
- continue;
813
- const entry = { value };
814
- if (this.#ttls && this.#starts) {
815
- entry.ttl = this.#ttls[i];
816
- const age = perf.now() - this.#starts[i];
817
- entry.start = Math.floor(Date.now() - age);
818
- }
819
- if (this.#sizes) {
820
- entry.size = this.#sizes[i];
821
- }
822
- arr.unshift([key, entry]);
823
- }
824
- return arr;
825
- }
826
- /**
827
- * Reset the cache and load in the items in entries in the order listed.
828
- *
829
- * The shape of the resulting cache may be different if the same options are
830
- * not used in both caches.
831
- *
832
- * The `start` fields are assumed to be calculated relative to a portable
833
- * `Date.now()` timestamp, even if `performance.now()` is available.
834
- */
835
- load(arr) {
836
- this.clear();
837
- for (const [key, entry] of arr) {
838
- if (entry.start) {
839
- const age = Date.now() - entry.start;
840
- entry.start = perf.now() - age;
841
- }
842
- this.set(key, entry.value, entry);
843
- }
844
- }
845
- /**
846
- * Add a value to the cache.
847
- *
848
- * Note: if `undefined` is specified as a value, this is an alias for
849
- * {@link LRUCache#delete}
850
- *
851
- * Fields on the {@link LRUCache.SetOptions} options param will override
852
- * their corresponding values in the constructor options for the scope
853
- * of this single `set()` operation.
854
- *
855
- * If `start` is provided, then that will set the effective start
856
- * time for the TTL calculation. Note that this must be a previous
857
- * value of `performance.now()` if supported, or a previous value of
858
- * `Date.now()` if not.
859
- *
860
- * Options object may also include `size`, which will prevent
861
- * calling the `sizeCalculation` function and just use the specified
862
- * number if it is a positive integer, and `noDisposeOnSet` which
863
- * will prevent calling a `dispose` function in the case of
864
- * overwrites.
865
- *
866
- * If the `size` (or return value of `sizeCalculation`) for a given
867
- * entry is greater than `maxEntrySize`, then the item will not be
868
- * added to the cache.
869
- *
870
- * Will update the recency of the entry.
871
- *
872
- * If the value is `undefined`, then this is an alias for
873
- * `cache.delete(key)`. `undefined` is never stored in the cache.
874
- */
875
- set(k, v, setOptions = {}) {
876
- if (v === void 0) {
877
- this.delete(k);
878
- return this;
879
- }
880
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
881
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
882
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
883
- if (this.maxEntrySize && size > this.maxEntrySize) {
884
- if (status) {
885
- status.set = "miss";
886
- status.maxEntrySizeExceeded = true;
887
- }
888
- this.#delete(k, "set");
889
- return this;
890
- }
891
- let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
892
- if (index === void 0) {
893
- index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
894
- this.#keyList[index] = k;
895
- this.#valList[index] = v;
896
- this.#keyMap.set(k, index);
897
- this.#next[this.#tail] = index;
898
- this.#prev[index] = this.#tail;
899
- this.#tail = index;
900
- this.#size++;
901
- this.#addItemSize(index, size, status);
902
- if (status)
903
- status.set = "add";
904
- noUpdateTTL = false;
905
- } else {
906
- this.#moveToTail(index);
907
- const oldVal = this.#valList[index];
908
- if (v !== oldVal) {
909
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
910
- oldVal.__abortController.abort(new Error("replaced"));
911
- const { __staleWhileFetching: s } = oldVal;
912
- if (s !== void 0 && !noDisposeOnSet) {
913
- if (this.#hasDispose) {
914
- this.#dispose?.(s, k, "set");
915
- }
916
- if (this.#hasDisposeAfter) {
917
- this.#disposed?.push([s, k, "set"]);
918
- }
919
- }
920
- } else if (!noDisposeOnSet) {
921
- if (this.#hasDispose) {
922
- this.#dispose?.(oldVal, k, "set");
923
- }
924
- if (this.#hasDisposeAfter) {
925
- this.#disposed?.push([oldVal, k, "set"]);
926
- }
927
- }
928
- this.#removeItemSize(index);
929
- this.#addItemSize(index, size, status);
930
- this.#valList[index] = v;
931
- if (status) {
932
- status.set = "replace";
933
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
934
- if (oldValue !== void 0)
935
- status.oldValue = oldValue;
936
- }
937
- } else if (status) {
938
- status.set = "update";
939
- }
940
- }
941
- if (ttl !== 0 && !this.#ttls) {
942
- this.#initializeTTLTracking();
943
- }
944
- if (this.#ttls) {
945
- if (!noUpdateTTL) {
946
- this.#setItemTTL(index, ttl, start);
947
- }
948
- if (status)
949
- this.#statusTTL(status, index);
950
- }
951
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
952
- const dt = this.#disposed;
953
- let task;
954
- while (task = dt?.shift()) {
955
- this.#disposeAfter?.(...task);
956
- }
957
- }
958
- return this;
959
- }
960
- /**
961
- * Evict the least recently used item, returning its value or
962
- * `undefined` if cache is empty.
963
- */
964
- pop() {
965
- try {
966
- while (this.#size) {
967
- const val = this.#valList[this.#head];
968
- this.#evict(true);
969
- if (this.#isBackgroundFetch(val)) {
970
- if (val.__staleWhileFetching) {
971
- return val.__staleWhileFetching;
972
- }
973
- } else if (val !== void 0) {
974
- return val;
975
- }
976
- }
977
- } finally {
978
- if (this.#hasDisposeAfter && this.#disposed) {
979
- const dt = this.#disposed;
980
- let task;
981
- while (task = dt?.shift()) {
982
- this.#disposeAfter?.(...task);
983
- }
984
- }
985
- }
986
- }
987
- #evict(free) {
988
- const head = this.#head;
989
- const k = this.#keyList[head];
990
- const v = this.#valList[head];
991
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
992
- v.__abortController.abort(new Error("evicted"));
993
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
994
- if (this.#hasDispose) {
995
- this.#dispose?.(v, k, "evict");
996
- }
997
- if (this.#hasDisposeAfter) {
998
- this.#disposed?.push([v, k, "evict"]);
999
- }
1000
- }
1001
- this.#removeItemSize(head);
1002
- if (free) {
1003
- this.#keyList[head] = void 0;
1004
- this.#valList[head] = void 0;
1005
- this.#free.push(head);
1006
- }
1007
- if (this.#size === 1) {
1008
- this.#head = this.#tail = 0;
1009
- this.#free.length = 0;
1010
- } else {
1011
- this.#head = this.#next[head];
1012
- }
1013
- this.#keyMap.delete(k);
1014
- this.#size--;
1015
- return head;
1016
- }
1017
- /**
1018
- * Check if a key is in the cache, without updating the recency of use.
1019
- * Will return false if the item is stale, even though it is technically
1020
- * in the cache.
1021
- *
1022
- * Check if a key is in the cache, without updating the recency of
1023
- * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
1024
- * to `true` in either the options or the constructor.
1025
- *
1026
- * Will return `false` if the item is stale, even though it is technically in
1027
- * the cache. The difference can be determined (if it matters) by using a
1028
- * `status` argument, and inspecting the `has` field.
1029
- *
1030
- * Will not update item age unless
1031
- * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
1032
- */
1033
- has(k, hasOptions = {}) {
1034
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
1035
- const index = this.#keyMap.get(k);
1036
- if (index !== void 0) {
1037
- const v = this.#valList[index];
1038
- if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
1039
- return false;
1040
- }
1041
- if (!this.#isStale(index)) {
1042
- if (updateAgeOnHas) {
1043
- this.#updateItemAge(index);
1044
- }
1045
- if (status) {
1046
- status.has = "hit";
1047
- this.#statusTTL(status, index);
1048
- }
1049
- return true;
1050
- } else if (status) {
1051
- status.has = "stale";
1052
- this.#statusTTL(status, index);
1053
- }
1054
- } else if (status) {
1055
- status.has = "miss";
1056
- }
1057
- return false;
1058
- }
1059
- /**
1060
- * Like {@link LRUCache#get} but doesn't update recency or delete stale
1061
- * items.
1062
- *
1063
- * Returns `undefined` if the item is stale, unless
1064
- * {@link LRUCache.OptionsBase.allowStale} is set.
1065
- */
1066
- peek(k, peekOptions = {}) {
1067
- const { allowStale = this.allowStale } = peekOptions;
1068
- const index = this.#keyMap.get(k);
1069
- if (index === void 0 || !allowStale && this.#isStale(index)) {
1070
- return;
1071
- }
1072
- const v = this.#valList[index];
1073
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
1074
- }
1075
- #backgroundFetch(k, index, options, context) {
1076
- const v = index === void 0 ? void 0 : this.#valList[index];
1077
- if (this.#isBackgroundFetch(v)) {
1078
- return v;
1079
- }
1080
- const ac = new AC();
1081
- const { signal } = options;
1082
- signal?.addEventListener("abort", () => ac.abort(signal.reason), {
1083
- signal: ac.signal
1084
- });
1085
- const fetchOpts = {
1086
- signal: ac.signal,
1087
- options,
1088
- context
1089
- };
1090
- const cb = /* @__PURE__ */ __name((v2, updateCache = false) => {
1091
- const { aborted } = ac.signal;
1092
- const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
1093
- if (options.status) {
1094
- if (aborted && !updateCache) {
1095
- options.status.fetchAborted = true;
1096
- options.status.fetchError = ac.signal.reason;
1097
- if (ignoreAbort)
1098
- options.status.fetchAbortIgnored = true;
1099
- } else {
1100
- options.status.fetchResolved = true;
1101
- }
1102
- }
1103
- if (aborted && !ignoreAbort && !updateCache) {
1104
- return fetchFail(ac.signal.reason);
1105
- }
1106
- const bf2 = p;
1107
- if (this.#valList[index] === p) {
1108
- if (v2 === void 0) {
1109
- if (bf2.__staleWhileFetching) {
1110
- this.#valList[index] = bf2.__staleWhileFetching;
1111
- } else {
1112
- this.#delete(k, "fetch");
1113
- }
1114
- } else {
1115
- if (options.status)
1116
- options.status.fetchUpdated = true;
1117
- this.set(k, v2, fetchOpts.options);
1118
- }
1119
- }
1120
- return v2;
1121
- }, "cb");
1122
- const eb = /* @__PURE__ */ __name((er) => {
1123
- if (options.status) {
1124
- options.status.fetchRejected = true;
1125
- options.status.fetchError = er;
1126
- }
1127
- return fetchFail(er);
1128
- }, "eb");
1129
- const fetchFail = /* @__PURE__ */ __name((er) => {
1130
- const { aborted } = ac.signal;
1131
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
1132
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
1133
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
1134
- const bf2 = p;
1135
- if (this.#valList[index] === p) {
1136
- const del = !noDelete || bf2.__staleWhileFetching === void 0;
1137
- if (del) {
1138
- this.#delete(k, "fetch");
1139
- } else if (!allowStaleAborted) {
1140
- this.#valList[index] = bf2.__staleWhileFetching;
1141
- }
1142
- }
1143
- if (allowStale) {
1144
- if (options.status && bf2.__staleWhileFetching !== void 0) {
1145
- options.status.returnedStale = true;
1146
- }
1147
- return bf2.__staleWhileFetching;
1148
- } else if (bf2.__returned === bf2) {
1149
- throw er;
1150
- }
1151
- }, "fetchFail");
1152
- const pcall = /* @__PURE__ */ __name((res, rej) => {
1153
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
1154
- if (fmp && fmp instanceof Promise) {
1155
- fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
1156
- }
1157
- ac.signal.addEventListener("abort", () => {
1158
- if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
1159
- res(void 0);
1160
- if (options.allowStaleOnFetchAbort) {
1161
- res = /* @__PURE__ */ __name((v2) => cb(v2, true), "res");
1162
- }
1163
- }
1164
- });
1165
- }, "pcall");
1166
- if (options.status)
1167
- options.status.fetchDispatched = true;
1168
- const p = new Promise(pcall).then(cb, eb);
1169
- const bf = Object.assign(p, {
1170
- __abortController: ac,
1171
- __staleWhileFetching: v,
1172
- __returned: void 0
1173
- });
1174
- if (index === void 0) {
1175
- this.set(k, bf, { ...fetchOpts.options, status: void 0 });
1176
- index = this.#keyMap.get(k);
1177
- } else {
1178
- this.#valList[index] = bf;
1179
- }
1180
- return bf;
1181
- }
1182
- #isBackgroundFetch(p) {
1183
- if (!this.#hasFetchMethod)
1184
- return false;
1185
- const b = p;
1186
- return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
1187
- }
1188
- async fetch(k, fetchOptions = {}) {
1189
- const {
1190
- // get options
1191
- allowStale = this.allowStale,
1192
- updateAgeOnGet = this.updateAgeOnGet,
1193
- noDeleteOnStaleGet = this.noDeleteOnStaleGet,
1194
- // set options
1195
- ttl = this.ttl,
1196
- noDisposeOnSet = this.noDisposeOnSet,
1197
- size = 0,
1198
- sizeCalculation = this.sizeCalculation,
1199
- noUpdateTTL = this.noUpdateTTL,
1200
- // fetch exclusive options
1201
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
1202
- allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
1203
- ignoreFetchAbort = this.ignoreFetchAbort,
1204
- allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
1205
- context,
1206
- forceRefresh = false,
1207
- status,
1208
- signal
1209
- } = fetchOptions;
1210
- if (!this.#hasFetchMethod) {
1211
- if (status)
1212
- status.fetch = "get";
1213
- return this.get(k, {
1214
- allowStale,
1215
- updateAgeOnGet,
1216
- noDeleteOnStaleGet,
1217
- status
1218
- });
1219
- }
1220
- const options = {
1221
- allowStale,
1222
- updateAgeOnGet,
1223
- noDeleteOnStaleGet,
1224
- ttl,
1225
- noDisposeOnSet,
1226
- size,
1227
- sizeCalculation,
1228
- noUpdateTTL,
1229
- noDeleteOnFetchRejection,
1230
- allowStaleOnFetchRejection,
1231
- allowStaleOnFetchAbort,
1232
- ignoreFetchAbort,
1233
- status,
1234
- signal
1235
- };
1236
- let index = this.#keyMap.get(k);
1237
- if (index === void 0) {
1238
- if (status)
1239
- status.fetch = "miss";
1240
- const p = this.#backgroundFetch(k, index, options, context);
1241
- return p.__returned = p;
1242
- } else {
1243
- const v = this.#valList[index];
1244
- if (this.#isBackgroundFetch(v)) {
1245
- const stale = allowStale && v.__staleWhileFetching !== void 0;
1246
- if (status) {
1247
- status.fetch = "inflight";
1248
- if (stale)
1249
- status.returnedStale = true;
1250
- }
1251
- return stale ? v.__staleWhileFetching : v.__returned = v;
1252
- }
1253
- const isStale = this.#isStale(index);
1254
- if (!forceRefresh && !isStale) {
1255
- if (status)
1256
- status.fetch = "hit";
1257
- this.#moveToTail(index);
1258
- if (updateAgeOnGet) {
1259
- this.#updateItemAge(index);
1260
- }
1261
- if (status)
1262
- this.#statusTTL(status, index);
1263
- return v;
1264
- }
1265
- const p = this.#backgroundFetch(k, index, options, context);
1266
- const hasStale = p.__staleWhileFetching !== void 0;
1267
- const staleVal = hasStale && allowStale;
1268
- if (status) {
1269
- status.fetch = isStale ? "stale" : "refresh";
1270
- if (staleVal && isStale)
1271
- status.returnedStale = true;
1272
- }
1273
- return staleVal ? p.__staleWhileFetching : p.__returned = p;
1274
- }
1275
- }
1276
- async forceFetch(k, fetchOptions = {}) {
1277
- const v = await this.fetch(k, fetchOptions);
1278
- if (v === void 0)
1279
- throw new Error("fetch() returned undefined");
1280
- return v;
1281
- }
1282
- memo(k, memoOptions = {}) {
1283
- const memoMethod = this.#memoMethod;
1284
- if (!memoMethod) {
1285
- throw new Error("no memoMethod provided to constructor");
1286
- }
1287
- const { context, forceRefresh, ...options } = memoOptions;
1288
- const v = this.get(k, options);
1289
- if (!forceRefresh && v !== void 0)
1290
- return v;
1291
- const vv = memoMethod(k, v, {
1292
- options,
1293
- context
1294
- });
1295
- this.set(k, vv, options);
1296
- return vv;
1297
- }
1298
- /**
1299
- * Return a value from the cache. Will update the recency of the cache
1300
- * entry found.
1301
- *
1302
- * If the key is not found, get() will return `undefined`.
1303
- */
1304
- get(k, getOptions = {}) {
1305
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
1306
- const index = this.#keyMap.get(k);
1307
- if (index !== void 0) {
1308
- const value = this.#valList[index];
1309
- const fetching = this.#isBackgroundFetch(value);
1310
- if (status)
1311
- this.#statusTTL(status, index);
1312
- if (this.#isStale(index)) {
1313
- if (status)
1314
- status.get = "stale";
1315
- if (!fetching) {
1316
- if (!noDeleteOnStaleGet) {
1317
- this.#delete(k, "expire");
1318
- }
1319
- if (status && allowStale)
1320
- status.returnedStale = true;
1321
- return allowStale ? value : void 0;
1322
- } else {
1323
- if (status && allowStale && value.__staleWhileFetching !== void 0) {
1324
- status.returnedStale = true;
1325
- }
1326
- return allowStale ? value.__staleWhileFetching : void 0;
1327
- }
1328
- } else {
1329
- if (status)
1330
- status.get = "hit";
1331
- if (fetching) {
1332
- return value.__staleWhileFetching;
1333
- }
1334
- this.#moveToTail(index);
1335
- if (updateAgeOnGet) {
1336
- this.#updateItemAge(index);
1337
- }
1338
- return value;
1339
- }
1340
- } else if (status) {
1341
- status.get = "miss";
1342
- }
1343
- }
1344
- #connect(p, n) {
1345
- this.#prev[n] = p;
1346
- this.#next[p] = n;
1347
- }
1348
- #moveToTail(index) {
1349
- if (index !== this.#tail) {
1350
- if (index === this.#head) {
1351
- this.#head = this.#next[index];
1352
- } else {
1353
- this.#connect(this.#prev[index], this.#next[index]);
1354
- }
1355
- this.#connect(this.#tail, index);
1356
- this.#tail = index;
1357
- }
1358
- }
1359
- /**
1360
- * Deletes a key out of the cache.
1361
- *
1362
- * Returns true if the key was deleted, false otherwise.
1363
- */
1364
- delete(k) {
1365
- return this.#delete(k, "delete");
1366
- }
1367
- #delete(k, reason) {
1368
- let deleted = false;
1369
- if (this.#size !== 0) {
1370
- const index = this.#keyMap.get(k);
1371
- if (index !== void 0) {
1372
- deleted = true;
1373
- if (this.#size === 1) {
1374
- this.#clear(reason);
1375
- } else {
1376
- this.#removeItemSize(index);
1377
- const v = this.#valList[index];
1378
- if (this.#isBackgroundFetch(v)) {
1379
- v.__abortController.abort(new Error("deleted"));
1380
- } else if (this.#hasDispose || this.#hasDisposeAfter) {
1381
- if (this.#hasDispose) {
1382
- this.#dispose?.(v, k, reason);
1383
- }
1384
- if (this.#hasDisposeAfter) {
1385
- this.#disposed?.push([v, k, reason]);
1386
- }
1387
- }
1388
- this.#keyMap.delete(k);
1389
- this.#keyList[index] = void 0;
1390
- this.#valList[index] = void 0;
1391
- if (index === this.#tail) {
1392
- this.#tail = this.#prev[index];
1393
- } else if (index === this.#head) {
1394
- this.#head = this.#next[index];
1395
- } else {
1396
- const pi = this.#prev[index];
1397
- this.#next[pi] = this.#next[index];
1398
- const ni = this.#next[index];
1399
- this.#prev[ni] = this.#prev[index];
1400
- }
1401
- this.#size--;
1402
- this.#free.push(index);
1403
- }
1404
- }
1405
- }
1406
- if (this.#hasDisposeAfter && this.#disposed?.length) {
1407
- const dt = this.#disposed;
1408
- let task;
1409
- while (task = dt?.shift()) {
1410
- this.#disposeAfter?.(...task);
1411
- }
1412
- }
1413
- return deleted;
1414
- }
1415
- /**
1416
- * Clear the cache entirely, throwing away all values.
1417
- */
1418
- clear() {
1419
- return this.#clear("delete");
1420
- }
1421
- #clear(reason) {
1422
- for (const index of this.#rindexes({ allowStale: true })) {
1423
- const v = this.#valList[index];
1424
- if (this.#isBackgroundFetch(v)) {
1425
- v.__abortController.abort(new Error("deleted"));
1426
- } else {
1427
- const k = this.#keyList[index];
1428
- if (this.#hasDispose) {
1429
- this.#dispose?.(v, k, reason);
1430
- }
1431
- if (this.#hasDisposeAfter) {
1432
- this.#disposed?.push([v, k, reason]);
1433
- }
1434
- }
1435
- }
1436
- this.#keyMap.clear();
1437
- this.#valList.fill(void 0);
1438
- this.#keyList.fill(void 0);
1439
- if (this.#ttls && this.#starts) {
1440
- this.#ttls.fill(0);
1441
- this.#starts.fill(0);
1442
- }
1443
- if (this.#sizes) {
1444
- this.#sizes.fill(0);
1445
- }
1446
- this.#head = 0;
1447
- this.#tail = 0;
1448
- this.#free.length = 0;
1449
- this.#calculatedSize = 0;
1450
- this.#size = 0;
1451
- if (this.#hasDisposeAfter && this.#disposed) {
1452
- const dt = this.#disposed;
1453
- let task;
1454
- while (task = dt?.shift()) {
1455
- this.#disposeAfter?.(...task);
1456
- }
1457
- }
1458
- }
1459
- };
1460
-
1461
- // src/utils/token.ts
1462
- var NATIVE_ETH = {
1463
- symbol: "ETH",
1464
- decimal: 18,
1465
- name: "Native ETH"
1466
- };
1467
- var TOKEN_INFOS = new LRUCache({
1468
- max: 1e4,
1469
- ttl: 1e3 * 60 * 60
1470
- // 1 hour
1471
- });
1472
- async function getTokenInfoPromise(symbol, name, decimal) {
1473
- return {
1474
- symbol: await symbol,
1475
- name: await name,
1476
- decimal: Number(await decimal)
1477
- };
1478
- }
1479
- __name(getTokenInfoPromise, "getTokenInfoPromise");
1480
- async function getERC20TokenInfo(contextOrNetworkish, tokenAddress) {
1481
- let chainId;
1482
- if (contextOrNetworkish instanceof BaseContext) {
1483
- chainId = contextOrNetworkish.getChainId();
1484
- } else {
1485
- chainId = contextOrNetworkish || EthChainId.ETHEREUM;
1486
- }
1487
- const key = chainId + tokenAddress;
1488
- const res = TOKEN_INFOS.get(key);
1489
- if (res) {
1490
- return res;
1491
- }
1492
- const contract = getERC20Contract(chainId, tokenAddress);
1493
- const bytesContract = getERC20BytesContract(chainId, tokenAddress);
1494
- let name = "";
1495
- try {
1496
- name = await contract.name();
1497
- } catch (e) {
1498
- name = decodeBytes32String(await bytesContract.name());
1499
- }
1500
- let symbol = "";
1501
- try {
1502
- symbol = await contract.symbol();
1503
- } catch (e) {
1504
- symbol = decodeBytes32String(await bytesContract.symbol());
1505
- }
1506
- const decimal = await contract.decimals();
1507
- const info = getTokenInfoPromise(symbol, name, decimal);
1508
- TOKEN_INFOS.set(key, info);
1509
- return info;
1510
- }
1511
- __name(getERC20TokenInfo, "getERC20TokenInfo");
1512
- async function getER20NormalizedAmount(contextOrNetworkish, tokenAddress, amount) {
1513
- const tokenInfo = await getERC20TokenInfo(contextOrNetworkish, tokenAddress);
1514
- return scaleDown(amount, tokenInfo.decimal);
1515
- }
1516
- __name(getER20NormalizedAmount, "getER20NormalizedAmount");
1517
- import("node:process").then((p) => p.stdout.write(""));
1518
-
1519
- // src/utils/dex-price.ts
1520
- import fs from "fs";
1521
-
1522
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/api/CsvError.js
1523
- var CsvError = class _CsvError extends Error {
1524
- static {
1525
- __name(this, "CsvError");
1526
- }
1527
- constructor(code, message, options, ...contexts) {
1528
- if (Array.isArray(message)) message = message.join(" ").trim();
1529
- super(message);
1530
- if (Error.captureStackTrace !== void 0) {
1531
- Error.captureStackTrace(this, _CsvError);
1532
- }
1533
- this.code = code;
1534
- for (const context of contexts) {
1535
- for (const key in context) {
1536
- const value = context[key];
1537
- this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
1538
- }
1539
- }
1540
- }
1541
- };
1542
-
1543
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/utils/is_object.js
1544
- var is_object = /* @__PURE__ */ __name(function(obj) {
1545
- return typeof obj === "object" && obj !== null && !Array.isArray(obj);
1546
- }, "is_object");
1547
-
1548
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/api/normalize_columns_array.js
1549
- var normalize_columns_array = /* @__PURE__ */ __name(function(columns) {
1550
- const normalizedColumns = [];
1551
- for (let i = 0, l = columns.length; i < l; i++) {
1552
- const column = columns[i];
1553
- if (column === void 0 || column === null || column === false) {
1554
- normalizedColumns[i] = { disabled: true };
1555
- } else if (typeof column === "string") {
1556
- normalizedColumns[i] = { name: column };
1557
- } else if (is_object(column)) {
1558
- if (typeof column.name !== "string") {
1559
- throw new CsvError("CSV_OPTION_COLUMNS_MISSING_NAME", [
1560
- "Option columns missing name:",
1561
- `property "name" is required at position ${i}`,
1562
- "when column is an object literal"
1563
- ]);
1564
- }
1565
- normalizedColumns[i] = column;
1566
- } else {
1567
- throw new CsvError("CSV_INVALID_COLUMN_DEFINITION", [
1568
- "Invalid column definition:",
1569
- "expect a string or a literal object,",
1570
- `got ${JSON.stringify(column)} at position ${i}`
1571
- ]);
1572
- }
1573
- }
1574
- return normalizedColumns;
1575
- }, "normalize_columns_array");
1576
-
1577
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/utils/ResizeableBuffer.js
1578
- var ResizeableBuffer = class {
1579
- static {
1580
- __name(this, "ResizeableBuffer");
1581
- }
1582
- constructor(size = 100) {
1583
- this.size = size;
1584
- this.length = 0;
1585
- this.buf = Buffer.allocUnsafe(size);
1586
- }
1587
- prepend(val) {
1588
- if (Buffer.isBuffer(val)) {
1589
- const length = this.length + val.length;
1590
- if (length >= this.size) {
1591
- this.resize();
1592
- if (length >= this.size) {
1593
- throw Error("INVALID_BUFFER_STATE");
1594
- }
1595
- }
1596
- const buf = this.buf;
1597
- this.buf = Buffer.allocUnsafe(this.size);
1598
- val.copy(this.buf, 0);
1599
- buf.copy(this.buf, val.length);
1600
- this.length += val.length;
1601
- } else {
1602
- const length = this.length++;
1603
- if (length === this.size) {
1604
- this.resize();
1605
- }
1606
- const buf = this.clone();
1607
- this.buf[0] = val;
1608
- buf.copy(this.buf, 1, 0, length);
1609
- }
1610
- }
1611
- append(val) {
1612
- const length = this.length++;
1613
- if (length === this.size) {
1614
- this.resize();
1615
- }
1616
- this.buf[length] = val;
1617
- }
1618
- clone() {
1619
- return Buffer.from(this.buf.slice(0, this.length));
1620
- }
1621
- resize() {
1622
- const length = this.length;
1623
- this.size = this.size * 2;
1624
- const buf = Buffer.allocUnsafe(this.size);
1625
- this.buf.copy(buf, 0, 0, length);
1626
- this.buf = buf;
1627
- }
1628
- toString(encoding) {
1629
- if (encoding) {
1630
- return this.buf.slice(0, this.length).toString(encoding);
1631
- } else {
1632
- return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
1633
- }
1634
- }
1635
- toJSON() {
1636
- return this.toString("utf8");
1637
- }
1638
- reset() {
1639
- this.length = 0;
1640
- }
1641
- };
1642
- var ResizeableBuffer_default = ResizeableBuffer;
1643
-
1644
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/api/init_state.js
1645
- var np = 12;
1646
- var cr = 13;
1647
- var nl = 10;
1648
- var space = 32;
1649
- var tab = 9;
1650
- var init_state = /* @__PURE__ */ __name(function(options) {
1651
- return {
1652
- bomSkipped: false,
1653
- bufBytesStart: 0,
1654
- castField: options.cast_function,
1655
- commenting: false,
1656
- // Current error encountered by a record
1657
- error: void 0,
1658
- enabled: options.from_line === 1,
1659
- escaping: false,
1660
- escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
1661
- // columns can be `false`, `true`, `Array`
1662
- expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : void 0,
1663
- field: new ResizeableBuffer_default(20),
1664
- firstLineToHeaders: options.cast_first_line_to_header,
1665
- needMoreDataSize: Math.max(
1666
- // Skip if the remaining buffer smaller than comment
1667
- options.comment !== null ? options.comment.length : 0,
1668
- ...options.delimiter.map((delimiter) => delimiter.length),
1669
- // Skip if the remaining buffer can be escape sequence
1670
- options.quote !== null ? options.quote.length : 0
1671
- ),
1672
- previousBuf: void 0,
1673
- quoting: false,
1674
- stop: false,
1675
- rawBuffer: new ResizeableBuffer_default(100),
1676
- record: [],
1677
- recordHasError: false,
1678
- record_length: 0,
1679
- recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
1680
- trimChars: [Buffer.from(" ", options.encoding)[0], Buffer.from(" ", options.encoding)[0]],
1681
- wasQuoting: false,
1682
- wasRowDelimiter: false,
1683
- timchars: [
1684
- Buffer.from(Buffer.from([cr], "utf8").toString(), options.encoding),
1685
- Buffer.from(Buffer.from([nl], "utf8").toString(), options.encoding),
1686
- Buffer.from(Buffer.from([np], "utf8").toString(), options.encoding),
1687
- Buffer.from(Buffer.from([space], "utf8").toString(), options.encoding),
1688
- Buffer.from(Buffer.from([tab], "utf8").toString(), options.encoding)
1689
- ]
1690
- };
1691
- }, "init_state");
1692
-
1693
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/utils/underscore.js
1694
- var underscore = /* @__PURE__ */ __name(function(str) {
1695
- return str.replace(/([A-Z])/g, function(_, match) {
1696
- return "_" + match.toLowerCase();
1697
- });
1698
- }, "underscore");
1699
-
1700
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/api/normalize_options.js
1701
- var normalize_options = /* @__PURE__ */ __name(function(opts) {
1702
- const options = {};
1703
- for (const opt in opts) {
1704
- options[underscore(opt)] = opts[opt];
1705
- }
1706
- if (options.encoding === void 0 || options.encoding === true) {
1707
- options.encoding = "utf8";
1708
- } else if (options.encoding === null || options.encoding === false) {
1709
- options.encoding = null;
1710
- } else if (typeof options.encoding !== "string" && options.encoding !== null) {
1711
- throw new CsvError("CSV_INVALID_OPTION_ENCODING", [
1712
- "Invalid option encoding:",
1713
- "encoding must be a string or null to return a buffer,",
1714
- `got ${JSON.stringify(options.encoding)}`
1715
- ], options);
1716
- }
1717
- if (options.bom === void 0 || options.bom === null || options.bom === false) {
1718
- options.bom = false;
1719
- } else if (options.bom !== true) {
1720
- throw new CsvError("CSV_INVALID_OPTION_BOM", [
1721
- "Invalid option bom:",
1722
- "bom must be true,",
1723
- `got ${JSON.stringify(options.bom)}`
1724
- ], options);
1725
- }
1726
- options.cast_function = null;
1727
- if (options.cast === void 0 || options.cast === null || options.cast === false || options.cast === "") {
1728
- options.cast = void 0;
1729
- } else if (typeof options.cast === "function") {
1730
- options.cast_function = options.cast;
1731
- options.cast = true;
1732
- } else if (options.cast !== true) {
1733
- throw new CsvError("CSV_INVALID_OPTION_CAST", [
1734
- "Invalid option cast:",
1735
- "cast must be true or a function,",
1736
- `got ${JSON.stringify(options.cast)}`
1737
- ], options);
1738
- }
1739
- if (options.cast_date === void 0 || options.cast_date === null || options.cast_date === false || options.cast_date === "") {
1740
- options.cast_date = false;
1741
- } else if (options.cast_date === true) {
1742
- options.cast_date = function(value) {
1743
- const date = Date.parse(value);
1744
- return !isNaN(date) ? new Date(date) : value;
1745
- };
1746
- } else if (typeof options.cast_date !== "function") {
1747
- throw new CsvError("CSV_INVALID_OPTION_CAST_DATE", [
1748
- "Invalid option cast_date:",
1749
- "cast_date must be true or a function,",
1750
- `got ${JSON.stringify(options.cast_date)}`
1751
- ], options);
1752
- }
1753
- options.cast_first_line_to_header = null;
1754
- if (options.columns === true) {
1755
- options.cast_first_line_to_header = void 0;
1756
- } else if (typeof options.columns === "function") {
1757
- options.cast_first_line_to_header = options.columns;
1758
- options.columns = true;
1759
- } else if (Array.isArray(options.columns)) {
1760
- options.columns = normalize_columns_array(options.columns);
1761
- } else if (options.columns === void 0 || options.columns === null || options.columns === false) {
1762
- options.columns = false;
1763
- } else {
1764
- throw new CsvError("CSV_INVALID_OPTION_COLUMNS", [
1765
- "Invalid option columns:",
1766
- "expect an array, a function or true,",
1767
- `got ${JSON.stringify(options.columns)}`
1768
- ], options);
1769
- }
1770
- if (options.group_columns_by_name === void 0 || options.group_columns_by_name === null || options.group_columns_by_name === false) {
1771
- options.group_columns_by_name = false;
1772
- } else if (options.group_columns_by_name !== true) {
1773
- throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
1774
- "Invalid option group_columns_by_name:",
1775
- "expect an boolean,",
1776
- `got ${JSON.stringify(options.group_columns_by_name)}`
1777
- ], options);
1778
- } else if (options.columns === false) {
1779
- throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
1780
- "Invalid option group_columns_by_name:",
1781
- "the `columns` mode must be activated."
1782
- ], options);
1783
- }
1784
- if (options.comment === void 0 || options.comment === null || options.comment === false || options.comment === "") {
1785
- options.comment = null;
1786
- } else {
1787
- if (typeof options.comment === "string") {
1788
- options.comment = Buffer.from(options.comment, options.encoding);
1789
- }
1790
- if (!Buffer.isBuffer(options.comment)) {
1791
- throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
1792
- "Invalid option comment:",
1793
- "comment must be a buffer or a string,",
1794
- `got ${JSON.stringify(options.comment)}`
1795
- ], options);
1796
- }
1797
- }
1798
- if (options.comment_no_infix === void 0 || options.comment_no_infix === null || options.comment_no_infix === false) {
1799
- options.comment_no_infix = false;
1800
- } else if (options.comment_no_infix !== true) {
1801
- throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
1802
- "Invalid option comment_no_infix:",
1803
- "value must be a boolean,",
1804
- `got ${JSON.stringify(options.comment_no_infix)}`
1805
- ], options);
1806
- }
1807
- const delimiter_json = JSON.stringify(options.delimiter);
1808
- if (!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
1809
- if (options.delimiter.length === 0) {
1810
- throw new CsvError("CSV_INVALID_OPTION_DELIMITER", [
1811
- "Invalid option delimiter:",
1812
- "delimiter must be a non empty string or buffer or array of string|buffer,",
1813
- `got ${delimiter_json}`
1814
- ], options);
1815
- }
1816
- options.delimiter = options.delimiter.map(function(delimiter) {
1817
- if (delimiter === void 0 || delimiter === null || delimiter === false) {
1818
- return Buffer.from(",", options.encoding);
1819
- }
1820
- if (typeof delimiter === "string") {
1821
- delimiter = Buffer.from(delimiter, options.encoding);
1822
- }
1823
- if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) {
1824
- throw new CsvError("CSV_INVALID_OPTION_DELIMITER", [
1825
- "Invalid option delimiter:",
1826
- "delimiter must be a non empty string or buffer or array of string|buffer,",
1827
- `got ${delimiter_json}`
1828
- ], options);
1829
- }
1830
- return delimiter;
1831
- });
1832
- if (options.escape === void 0 || options.escape === true) {
1833
- options.escape = Buffer.from('"', options.encoding);
1834
- } else if (typeof options.escape === "string") {
1835
- options.escape = Buffer.from(options.escape, options.encoding);
1836
- } else if (options.escape === null || options.escape === false) {
1837
- options.escape = null;
1838
- }
1839
- if (options.escape !== null) {
1840
- if (!Buffer.isBuffer(options.escape)) {
1841
- throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
1842
- }
1843
- }
1844
- if (options.from === void 0 || options.from === null) {
1845
- options.from = 1;
1846
- } else {
1847
- if (typeof options.from === "string" && /\d+/.test(options.from)) {
1848
- options.from = parseInt(options.from);
1849
- }
1850
- if (Number.isInteger(options.from)) {
1851
- if (options.from < 0) {
1852
- throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
1853
- }
1854
- } else {
1855
- throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
1856
- }
1857
- }
1858
- if (options.from_line === void 0 || options.from_line === null) {
1859
- options.from_line = 1;
1860
- } else {
1861
- if (typeof options.from_line === "string" && /\d+/.test(options.from_line)) {
1862
- options.from_line = parseInt(options.from_line);
1863
- }
1864
- if (Number.isInteger(options.from_line)) {
1865
- if (options.from_line <= 0) {
1866
- throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
1867
- }
1868
- } else {
1869
- throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
1870
- }
1871
- }
1872
- if (options.ignore_last_delimiters === void 0 || options.ignore_last_delimiters === null) {
1873
- options.ignore_last_delimiters = false;
1874
- } else if (typeof options.ignore_last_delimiters === "number") {
1875
- options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
1876
- if (options.ignore_last_delimiters === 0) {
1877
- options.ignore_last_delimiters = false;
1878
- }
1879
- } else if (typeof options.ignore_last_delimiters !== "boolean") {
1880
- throw new CsvError("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS", [
1881
- "Invalid option `ignore_last_delimiters`:",
1882
- "the value must be a boolean value or an integer,",
1883
- `got ${JSON.stringify(options.ignore_last_delimiters)}`
1884
- ], options);
1885
- }
1886
- if (options.ignore_last_delimiters === true && options.columns === false) {
1887
- throw new CsvError("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS", [
1888
- "The option `ignore_last_delimiters`",
1889
- "requires the activation of the `columns` option"
1890
- ], options);
1891
- }
1892
- if (options.info === void 0 || options.info === null || options.info === false) {
1893
- options.info = false;
1894
- } else if (options.info !== true) {
1895
- throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
1896
- }
1897
- if (options.max_record_size === void 0 || options.max_record_size === null || options.max_record_size === false) {
1898
- options.max_record_size = 0;
1899
- } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {
1900
- } else if (typeof options.max_record_size === "string" && /\d+/.test(options.max_record_size)) {
1901
- options.max_record_size = parseInt(options.max_record_size);
1902
- } else {
1903
- throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
1904
- }
1905
- if (options.objname === void 0 || options.objname === null || options.objname === false) {
1906
- options.objname = void 0;
1907
- } else if (Buffer.isBuffer(options.objname)) {
1908
- if (options.objname.length === 0) {
1909
- throw new Error(`Invalid Option: objname must be a non empty buffer`);
1910
- }
1911
- if (options.encoding === null) {
1912
- } else {
1913
- options.objname = options.objname.toString(options.encoding);
1914
- }
1915
- } else if (typeof options.objname === "string") {
1916
- if (options.objname.length === 0) {
1917
- throw new Error(`Invalid Option: objname must be a non empty string`);
1918
- }
1919
- } else if (typeof options.objname === "number") {
1920
- } else {
1921
- throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
1922
- }
1923
- if (options.objname !== void 0) {
1924
- if (typeof options.objname === "number") {
1925
- if (options.columns !== false) {
1926
- throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field");
1927
- }
1928
- } else {
1929
- if (options.columns === false) {
1930
- throw Error("Invalid Option: objname field must be combined with columns or be defined as an index");
1931
- }
1932
- }
1933
- }
1934
- if (options.on_record === void 0 || options.on_record === null) {
1935
- options.on_record = void 0;
1936
- } else if (typeof options.on_record !== "function") {
1937
- throw new CsvError("CSV_INVALID_OPTION_ON_RECORD", [
1938
- "Invalid option `on_record`:",
1939
- "expect a function,",
1940
- `got ${JSON.stringify(options.on_record)}`
1941
- ], options);
1942
- }
1943
- if (options.on_skip !== void 0 && options.on_skip !== null && typeof options.on_skip !== "function") {
1944
- throw new Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(options.on_skip)}`);
1945
- }
1946
- if (options.quote === null || options.quote === false || options.quote === "") {
1947
- options.quote = null;
1948
- } else {
1949
- if (options.quote === void 0 || options.quote === true) {
1950
- options.quote = Buffer.from('"', options.encoding);
1951
- } else if (typeof options.quote === "string") {
1952
- options.quote = Buffer.from(options.quote, options.encoding);
1953
- }
1954
- if (!Buffer.isBuffer(options.quote)) {
1955
- throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
1956
- }
1957
- }
1958
- if (options.raw === void 0 || options.raw === null || options.raw === false) {
1959
- options.raw = false;
1960
- } else if (options.raw !== true) {
1961
- throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
1962
- }
1963
- if (options.record_delimiter === void 0) {
1964
- options.record_delimiter = [];
1965
- } else if (typeof options.record_delimiter === "string" || Buffer.isBuffer(options.record_delimiter)) {
1966
- if (options.record_delimiter.length === 0) {
1967
- throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
1968
- "Invalid option `record_delimiter`:",
1969
- "value must be a non empty string or buffer,",
1970
- `got ${JSON.stringify(options.record_delimiter)}`
1971
- ], options);
1972
- }
1973
- options.record_delimiter = [options.record_delimiter];
1974
- } else if (!Array.isArray(options.record_delimiter)) {
1975
- throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
1976
- "Invalid option `record_delimiter`:",
1977
- "value must be a string, a buffer or array of string|buffer,",
1978
- `got ${JSON.stringify(options.record_delimiter)}`
1979
- ], options);
1980
- }
1981
- options.record_delimiter = options.record_delimiter.map(function(rd, i) {
1982
- if (typeof rd !== "string" && !Buffer.isBuffer(rd)) {
1983
- throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
1984
- "Invalid option `record_delimiter`:",
1985
- "value must be a string, a buffer or array of string|buffer",
1986
- `at index ${i},`,
1987
- `got ${JSON.stringify(rd)}`
1988
- ], options);
1989
- } else if (rd.length === 0) {
1990
- throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
1991
- "Invalid option `record_delimiter`:",
1992
- "value must be a non empty string or buffer",
1993
- `at index ${i},`,
1994
- `got ${JSON.stringify(rd)}`
1995
- ], options);
1996
- }
1997
- if (typeof rd === "string") {
1998
- rd = Buffer.from(rd, options.encoding);
1999
- }
2000
- return rd;
2001
- });
2002
- if (typeof options.relax_column_count === "boolean") {
2003
- } else if (options.relax_column_count === void 0 || options.relax_column_count === null) {
2004
- options.relax_column_count = false;
2005
- } else {
2006
- throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
2007
- }
2008
- if (typeof options.relax_column_count_less === "boolean") {
2009
- } else if (options.relax_column_count_less === void 0 || options.relax_column_count_less === null) {
2010
- options.relax_column_count_less = false;
2011
- } else {
2012
- throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
2013
- }
2014
- if (typeof options.relax_column_count_more === "boolean") {
2015
- } else if (options.relax_column_count_more === void 0 || options.relax_column_count_more === null) {
2016
- options.relax_column_count_more = false;
2017
- } else {
2018
- throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
2019
- }
2020
- if (typeof options.relax_quotes === "boolean") {
2021
- } else if (options.relax_quotes === void 0 || options.relax_quotes === null) {
2022
- options.relax_quotes = false;
2023
- } else {
2024
- throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
2025
- }
2026
- if (typeof options.skip_empty_lines === "boolean") {
2027
- } else if (options.skip_empty_lines === void 0 || options.skip_empty_lines === null) {
2028
- options.skip_empty_lines = false;
2029
- } else {
2030
- throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
2031
- }
2032
- if (typeof options.skip_records_with_empty_values === "boolean") {
2033
- } else if (options.skip_records_with_empty_values === void 0 || options.skip_records_with_empty_values === null) {
2034
- options.skip_records_with_empty_values = false;
2035
- } else {
2036
- throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
2037
- }
2038
- if (typeof options.skip_records_with_error === "boolean") {
2039
- } else if (options.skip_records_with_error === void 0 || options.skip_records_with_error === null) {
2040
- options.skip_records_with_error = false;
2041
- } else {
2042
- throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
2043
- }
2044
- if (options.rtrim === void 0 || options.rtrim === null || options.rtrim === false) {
2045
- options.rtrim = false;
2046
- } else if (options.rtrim !== true) {
2047
- throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
2048
- }
2049
- if (options.ltrim === void 0 || options.ltrim === null || options.ltrim === false) {
2050
- options.ltrim = false;
2051
- } else if (options.ltrim !== true) {
2052
- throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
2053
- }
2054
- if (options.trim === void 0 || options.trim === null || options.trim === false) {
2055
- options.trim = false;
2056
- } else if (options.trim !== true) {
2057
- throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
2058
- }
2059
- if (options.trim === true && opts.ltrim !== false) {
2060
- options.ltrim = true;
2061
- } else if (options.ltrim !== true) {
2062
- options.ltrim = false;
2063
- }
2064
- if (options.trim === true && opts.rtrim !== false) {
2065
- options.rtrim = true;
2066
- } else if (options.rtrim !== true) {
2067
- options.rtrim = false;
2068
- }
2069
- if (options.to === void 0 || options.to === null) {
2070
- options.to = -1;
2071
- } else {
2072
- if (typeof options.to === "string" && /\d+/.test(options.to)) {
2073
- options.to = parseInt(options.to);
2074
- }
2075
- if (Number.isInteger(options.to)) {
2076
- if (options.to <= 0) {
2077
- throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
2078
- }
2079
- } else {
2080
- throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
2081
- }
2082
- }
2083
- if (options.to_line === void 0 || options.to_line === null) {
2084
- options.to_line = -1;
2085
- } else {
2086
- if (typeof options.to_line === "string" && /\d+/.test(options.to_line)) {
2087
- options.to_line = parseInt(options.to_line);
2088
- }
2089
- if (Number.isInteger(options.to_line)) {
2090
- if (options.to_line <= 0) {
2091
- throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
2092
- }
2093
- } else {
2094
- throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
2095
- }
2096
- }
2097
- return options;
2098
- }, "normalize_options");
2099
-
2100
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/api/index.js
2101
- var isRecordEmpty = /* @__PURE__ */ __name(function(record) {
2102
- return record.every((field) => field == null || field.toString && field.toString().trim() === "");
2103
- }, "isRecordEmpty");
2104
- var cr2 = 13;
2105
- var nl2 = 10;
2106
- var boms = {
2107
- // Note, the following are equals:
2108
- // Buffer.from("\ufeff")
2109
- // Buffer.from([239, 187, 191])
2110
- // Buffer.from('EFBBBF', 'hex')
2111
- "utf8": Buffer.from([239, 187, 191]),
2112
- // Note, the following are equals:
2113
- // Buffer.from "\ufeff", 'utf16le
2114
- // Buffer.from([255, 254])
2115
- "utf16le": Buffer.from([255, 254])
2116
- };
2117
- var transform = /* @__PURE__ */ __name(function(original_options = {}) {
2118
- const info = {
2119
- bytes: 0,
2120
- comment_lines: 0,
2121
- empty_lines: 0,
2122
- invalid_field_length: 0,
2123
- lines: 1,
2124
- records: 0
2125
- };
2126
- const options = normalize_options(original_options);
2127
- return {
2128
- info,
2129
- original_options,
2130
- options,
2131
- state: init_state(options),
2132
- __needMoreData: /* @__PURE__ */ __name(function(i, bufLen, end) {
2133
- if (end) return false;
2134
- const { encoding, escape, quote } = this.options;
2135
- const { quoting, needMoreDataSize, recordDelimiterMaxLength } = this.state;
2136
- const numOfCharLeft = bufLen - i - 1;
2137
- const requiredLength = Math.max(
2138
- needMoreDataSize,
2139
- // Skip if the remaining buffer smaller than record delimiter
2140
- // If "record_delimiter" is yet to be discovered:
2141
- // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
2142
- // 2. We set the length to windows line ending in the current encoding
2143
- // Note, that encoding is known from user or bom discovery at that point
2144
- // recordDelimiterMaxLength,
2145
- recordDelimiterMaxLength === 0 ? Buffer.from("\r\n", encoding).length : recordDelimiterMaxLength,
2146
- // Skip if remaining buffer can be an escaped quote
2147
- quoting ? (escape === null ? 0 : escape.length) + quote.length : 0,
2148
- // Skip if remaining buffer can be record delimiter following the closing quote
2149
- quoting ? quote.length + recordDelimiterMaxLength : 0
2150
- );
2151
- return numOfCharLeft < requiredLength;
2152
- }, "__needMoreData"),
2153
- // Central parser implementation
2154
- parse: /* @__PURE__ */ __name(function(nextBuf, end, push, close) {
2155
- const { bom, comment_no_infix, encoding, from_line, ltrim, max_record_size, raw, relax_quotes, rtrim, skip_empty_lines, to, to_line } = this.options;
2156
- let { comment, escape, quote, record_delimiter } = this.options;
2157
- const { bomSkipped, previousBuf, rawBuffer, escapeIsQuote } = this.state;
2158
- let buf;
2159
- if (previousBuf === void 0) {
2160
- if (nextBuf === void 0) {
2161
- close();
2162
- return;
2163
- } else {
2164
- buf = nextBuf;
2165
- }
2166
- } else if (previousBuf !== void 0 && nextBuf === void 0) {
2167
- buf = previousBuf;
2168
- } else {
2169
- buf = Buffer.concat([previousBuf, nextBuf]);
2170
- }
2171
- if (bomSkipped === false) {
2172
- if (bom === false) {
2173
- this.state.bomSkipped = true;
2174
- } else if (buf.length < 3) {
2175
- if (end === false) {
2176
- this.state.previousBuf = buf;
2177
- return;
2178
- }
2179
- } else {
2180
- for (const encoding2 in boms) {
2181
- if (boms[encoding2].compare(buf, 0, boms[encoding2].length) === 0) {
2182
- const bomLength = boms[encoding2].length;
2183
- this.state.bufBytesStart += bomLength;
2184
- buf = buf.slice(bomLength);
2185
- this.options = normalize_options({ ...this.original_options, encoding: encoding2 });
2186
- ({ comment, escape, quote } = this.options);
2187
- break;
2188
- }
2189
- }
2190
- this.state.bomSkipped = true;
2191
- }
2192
- }
2193
- const bufLen = buf.length;
2194
- let pos;
2195
- for (pos = 0; pos < bufLen; pos++) {
2196
- if (this.__needMoreData(pos, bufLen, end)) {
2197
- break;
2198
- }
2199
- if (this.state.wasRowDelimiter === true) {
2200
- this.info.lines++;
2201
- this.state.wasRowDelimiter = false;
2202
- }
2203
- if (to_line !== -1 && this.info.lines > to_line) {
2204
- this.state.stop = true;
2205
- close();
2206
- return;
2207
- }
2208
- if (this.state.quoting === false && record_delimiter.length === 0) {
2209
- const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
2210
- if (record_delimiterCount) {
2211
- record_delimiter = this.options.record_delimiter;
2212
- }
2213
- }
2214
- const chr = buf[pos];
2215
- if (raw === true) {
2216
- rawBuffer.append(chr);
2217
- }
2218
- if ((chr === cr2 || chr === nl2) && this.state.wasRowDelimiter === false) {
2219
- this.state.wasRowDelimiter = true;
2220
- }
2221
- if (this.state.escaping === true) {
2222
- this.state.escaping = false;
2223
- } else {
2224
- if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) {
2225
- if (escapeIsQuote) {
2226
- if (this.__isQuote(buf, pos + escape.length)) {
2227
- this.state.escaping = true;
2228
- pos += escape.length - 1;
2229
- continue;
2230
- }
2231
- } else {
2232
- this.state.escaping = true;
2233
- pos += escape.length - 1;
2234
- continue;
2235
- }
2236
- }
2237
- if (this.state.commenting === false && this.__isQuote(buf, pos)) {
2238
- if (this.state.quoting === true) {
2239
- const nextChr = buf[pos + quote.length];
2240
- const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote.length);
2241
- const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr);
2242
- const isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr);
2243
- const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length);
2244
- if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) {
2245
- pos += escape.length - 1;
2246
- } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) {
2247
- this.state.quoting = false;
2248
- this.state.wasQuoting = true;
2249
- pos += quote.length - 1;
2250
- continue;
2251
- } else if (relax_quotes === false) {
2252
- const err = this.__error(
2253
- new CsvError("CSV_INVALID_CLOSING_QUOTE", [
2254
- "Invalid Closing Quote:",
2255
- `got "${String.fromCharCode(nextChr)}"`,
2256
- `at line ${this.info.lines}`,
2257
- "instead of delimiter, record delimiter, trimable character",
2258
- "(if activated) or comment"
2259
- ], this.options, this.__infoField())
2260
- );
2261
- if (err !== void 0) return err;
2262
- } else {
2263
- this.state.quoting = false;
2264
- this.state.wasQuoting = true;
2265
- this.state.field.prepend(quote);
2266
- pos += quote.length - 1;
2267
- }
2268
- } else {
2269
- if (this.state.field.length !== 0) {
2270
- if (relax_quotes === false) {
2271
- const info2 = this.__infoField();
2272
- const bom2 = Object.keys(boms).map((b) => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
2273
- const err = this.__error(
2274
- new CsvError("INVALID_OPENING_QUOTE", [
2275
- "Invalid Opening Quote:",
2276
- `a quote is found on field ${JSON.stringify(info2.column)} at line ${info2.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
2277
- bom2 ? `(${bom2} bom)` : void 0
2278
- ], this.options, info2, {
2279
- field: this.state.field
2280
- })
2281
- );
2282
- if (err !== void 0) return err;
2283
- }
2284
- } else {
2285
- this.state.quoting = true;
2286
- pos += quote.length - 1;
2287
- continue;
2288
- }
2289
- }
2290
- }
2291
- if (this.state.quoting === false) {
2292
- const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
2293
- if (recordDelimiterLength !== 0) {
2294
- const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
2295
- if (skipCommentLine) {
2296
- this.info.comment_lines++;
2297
- } else {
2298
- if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) {
2299
- this.state.enabled = true;
2300
- this.__resetField();
2301
- this.__resetRecord();
2302
- pos += recordDelimiterLength - 1;
2303
- continue;
2304
- }
2305
- if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) {
2306
- this.info.empty_lines++;
2307
- pos += recordDelimiterLength - 1;
2308
- continue;
2309
- }
2310
- this.info.bytes = this.state.bufBytesStart + pos;
2311
- const errField = this.__onField();
2312
- if (errField !== void 0) return errField;
2313
- this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
2314
- const errRecord = this.__onRecord(push);
2315
- if (errRecord !== void 0) return errRecord;
2316
- if (to !== -1 && this.info.records >= to) {
2317
- this.state.stop = true;
2318
- close();
2319
- return;
2320
- }
2321
- }
2322
- this.state.commenting = false;
2323
- pos += recordDelimiterLength - 1;
2324
- continue;
2325
- }
2326
- if (this.state.commenting) {
2327
- continue;
2328
- }
2329
- if (comment !== null && (comment_no_infix === false || this.state.record.length === 0 && this.state.field.length === 0)) {
2330
- const commentCount = this.__compareBytes(comment, buf, pos, chr);
2331
- if (commentCount !== 0) {
2332
- this.state.commenting = true;
2333
- continue;
2334
- }
2335
- }
2336
- const delimiterLength = this.__isDelimiter(buf, pos, chr);
2337
- if (delimiterLength !== 0) {
2338
- this.info.bytes = this.state.bufBytesStart + pos;
2339
- const errField = this.__onField();
2340
- if (errField !== void 0) return errField;
2341
- pos += delimiterLength - 1;
2342
- continue;
2343
- }
2344
- }
2345
- }
2346
- if (this.state.commenting === false) {
2347
- if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) {
2348
- return this.__error(
2349
- new CsvError("CSV_MAX_RECORD_SIZE", [
2350
- "Max Record Size:",
2351
- "record exceed the maximum number of tolerated bytes",
2352
- `of ${max_record_size}`,
2353
- `at line ${this.info.lines}`
2354
- ], this.options, this.__infoField())
2355
- );
2356
- }
2357
- }
2358
- const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
2359
- const rappend = rtrim === false || this.state.wasQuoting === false;
2360
- if (lappend === true && rappend === true) {
2361
- this.state.field.append(chr);
2362
- } else if (rtrim === true && !this.__isCharTrimable(buf, pos)) {
2363
- return this.__error(
2364
- new CsvError("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE", [
2365
- "Invalid Closing Quote:",
2366
- "found non trimable byte after quote",
2367
- `at line ${this.info.lines}`
2368
- ], this.options, this.__infoField())
2369
- );
2370
- } else {
2371
- if (lappend === false) {
2372
- pos += this.__isCharTrimable(buf, pos) - 1;
2373
- }
2374
- continue;
2375
- }
2376
- }
2377
- if (end === true) {
2378
- if (this.state.quoting === true) {
2379
- const err = this.__error(
2380
- new CsvError("CSV_QUOTE_NOT_CLOSED", [
2381
- "Quote Not Closed:",
2382
- `the parsing is finished with an opening quote at line ${this.info.lines}`
2383
- ], this.options, this.__infoField())
2384
- );
2385
- if (err !== void 0) return err;
2386
- } else {
2387
- if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) {
2388
- this.info.bytes = this.state.bufBytesStart + pos;
2389
- const errField = this.__onField();
2390
- if (errField !== void 0) return errField;
2391
- const errRecord = this.__onRecord(push);
2392
- if (errRecord !== void 0) return errRecord;
2393
- } else if (this.state.wasRowDelimiter === true) {
2394
- this.info.empty_lines++;
2395
- } else if (this.state.commenting === true) {
2396
- this.info.comment_lines++;
2397
- }
2398
- }
2399
- } else {
2400
- this.state.bufBytesStart += pos;
2401
- this.state.previousBuf = buf.slice(pos);
2402
- }
2403
- if (this.state.wasRowDelimiter === true) {
2404
- this.info.lines++;
2405
- this.state.wasRowDelimiter = false;
2406
- }
2407
- }, "parse"),
2408
- __onRecord: /* @__PURE__ */ __name(function(push) {
2409
- const { columns, group_columns_by_name, encoding, info: info2, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values } = this.options;
2410
- const { enabled, record } = this.state;
2411
- if (enabled === false) {
2412
- return this.__resetRecord();
2413
- }
2414
- const recordLength = record.length;
2415
- if (columns === true) {
2416
- if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
2417
- this.__resetRecord();
2418
- return;
2419
- }
2420
- return this.__firstLineToColumns(record);
2421
- }
2422
- if (columns === false && this.info.records === 0) {
2423
- this.state.expectedRecordLength = recordLength;
2424
- }
2425
- if (recordLength !== this.state.expectedRecordLength) {
2426
- const err = columns === false ? new CsvError("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH", [
2427
- "Invalid Record Length:",
2428
- `expect ${this.state.expectedRecordLength},`,
2429
- `got ${recordLength} on line ${this.info.lines}`
2430
- ], this.options, this.__infoField(), {
2431
- record
2432
- }) : new CsvError("CSV_RECORD_INCONSISTENT_COLUMNS", [
2433
- "Invalid Record Length:",
2434
- `columns length is ${columns.length},`,
2435
- // rename columns
2436
- `got ${recordLength} on line ${this.info.lines}`
2437
- ], this.options, this.__infoField(), {
2438
- record
2439
- });
2440
- if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) {
2441
- this.info.invalid_field_length++;
2442
- this.state.error = err;
2443
- } else {
2444
- const finalErr = this.__error(err);
2445
- if (finalErr) return finalErr;
2446
- }
2447
- }
2448
- if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
2449
- this.__resetRecord();
2450
- return;
2451
- }
2452
- if (this.state.recordHasError === true) {
2453
- this.__resetRecord();
2454
- this.state.recordHasError = false;
2455
- return;
2456
- }
2457
- this.info.records++;
2458
- if (from === 1 || this.info.records >= from) {
2459
- const { objname } = this.options;
2460
- if (columns !== false) {
2461
- const obj = {};
2462
- for (let i = 0, l = record.length; i < l; i++) {
2463
- if (columns[i] === void 0 || columns[i].disabled) continue;
2464
- if (group_columns_by_name === true && obj[columns[i].name] !== void 0) {
2465
- if (Array.isArray(obj[columns[i].name])) {
2466
- obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
2467
- } else {
2468
- obj[columns[i].name] = [obj[columns[i].name], record[i]];
2469
- }
2470
- } else {
2471
- obj[columns[i].name] = record[i];
2472
- }
2473
- }
2474
- if (raw === true || info2 === true) {
2475
- const extRecord = Object.assign(
2476
- { record: obj },
2477
- raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {},
2478
- info2 === true ? { info: this.__infoRecord() } : {}
2479
- );
2480
- const err = this.__push(
2481
- objname === void 0 ? extRecord : [obj[objname], extRecord],
2482
- push
2483
- );
2484
- if (err) {
2485
- return err;
2486
- }
2487
- } else {
2488
- const err = this.__push(
2489
- objname === void 0 ? obj : [obj[objname], obj],
2490
- push
2491
- );
2492
- if (err) {
2493
- return err;
2494
- }
2495
- }
2496
- } else {
2497
- if (raw === true || info2 === true) {
2498
- const extRecord = Object.assign(
2499
- { record },
2500
- raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {},
2501
- info2 === true ? { info: this.__infoRecord() } : {}
2502
- );
2503
- const err = this.__push(
2504
- objname === void 0 ? extRecord : [record[objname], extRecord],
2505
- push
2506
- );
2507
- if (err) {
2508
- return err;
2509
- }
2510
- } else {
2511
- const err = this.__push(
2512
- objname === void 0 ? record : [record[objname], record],
2513
- push
2514
- );
2515
- if (err) {
2516
- return err;
2517
- }
2518
- }
2519
- }
2520
- }
2521
- this.__resetRecord();
2522
- }, "__onRecord"),
2523
- __firstLineToColumns: /* @__PURE__ */ __name(function(record) {
2524
- const { firstLineToHeaders } = this.state;
2525
- try {
2526
- const headers = firstLineToHeaders === void 0 ? record : firstLineToHeaders.call(null, record);
2527
- if (!Array.isArray(headers)) {
2528
- return this.__error(
2529
- new CsvError("CSV_INVALID_COLUMN_MAPPING", [
2530
- "Invalid Column Mapping:",
2531
- "expect an array from column function,",
2532
- `got ${JSON.stringify(headers)}`
2533
- ], this.options, this.__infoField(), {
2534
- headers
2535
- })
2536
- );
2537
- }
2538
- const normalizedHeaders = normalize_columns_array(headers);
2539
- this.state.expectedRecordLength = normalizedHeaders.length;
2540
- this.options.columns = normalizedHeaders;
2541
- this.__resetRecord();
2542
- return;
2543
- } catch (err) {
2544
- return err;
2545
- }
2546
- }, "__firstLineToColumns"),
2547
- __resetRecord: /* @__PURE__ */ __name(function() {
2548
- if (this.options.raw === true) {
2549
- this.state.rawBuffer.reset();
2550
- }
2551
- this.state.error = void 0;
2552
- this.state.record = [];
2553
- this.state.record_length = 0;
2554
- }, "__resetRecord"),
2555
- __onField: /* @__PURE__ */ __name(function() {
2556
- const { cast, encoding, rtrim, max_record_size } = this.options;
2557
- const { enabled, wasQuoting } = this.state;
2558
- if (enabled === false) {
2559
- return this.__resetField();
2560
- }
2561
- let field = this.state.field.toString(encoding);
2562
- if (rtrim === true && wasQuoting === false) {
2563
- field = field.trimRight();
2564
- }
2565
- if (cast === true) {
2566
- const [err, f] = this.__cast(field);
2567
- if (err !== void 0) return err;
2568
- field = f;
2569
- }
2570
- this.state.record.push(field);
2571
- if (max_record_size !== 0 && typeof field === "string") {
2572
- this.state.record_length += field.length;
2573
- }
2574
- this.__resetField();
2575
- }, "__onField"),
2576
- __resetField: /* @__PURE__ */ __name(function() {
2577
- this.state.field.reset();
2578
- this.state.wasQuoting = false;
2579
- }, "__resetField"),
2580
- __push: /* @__PURE__ */ __name(function(record, push) {
2581
- const { on_record } = this.options;
2582
- if (on_record !== void 0) {
2583
- const info2 = this.__infoRecord();
2584
- try {
2585
- record = on_record.call(null, record, info2);
2586
- } catch (err) {
2587
- return err;
2588
- }
2589
- if (record === void 0 || record === null) {
2590
- return;
2591
- }
2592
- }
2593
- push(record);
2594
- }, "__push"),
2595
- // Return a tuple with the error and the casted value
2596
- __cast: /* @__PURE__ */ __name(function(field) {
2597
- const { columns, relax_column_count } = this.options;
2598
- const isColumns = Array.isArray(columns);
2599
- if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) {
2600
- return [void 0, void 0];
2601
- }
2602
- if (this.state.castField !== null) {
2603
- try {
2604
- const info2 = this.__infoField();
2605
- return [void 0, this.state.castField.call(null, field, info2)];
2606
- } catch (err) {
2607
- return [err];
2608
- }
2609
- }
2610
- if (this.__isFloat(field)) {
2611
- return [void 0, parseFloat(field)];
2612
- } else if (this.options.cast_date !== false) {
2613
- const info2 = this.__infoField();
2614
- return [void 0, this.options.cast_date.call(null, field, info2)];
2615
- }
2616
- return [void 0, field];
2617
- }, "__cast"),
2618
- // Helper to test if a character is a space or a line delimiter
2619
- __isCharTrimable: /* @__PURE__ */ __name(function(buf, pos) {
2620
- const isTrim = /* @__PURE__ */ __name((buf2, pos2) => {
2621
- const { timchars } = this.state;
2622
- loop1: for (let i = 0; i < timchars.length; i++) {
2623
- const timchar = timchars[i];
2624
- for (let j = 0; j < timchar.length; j++) {
2625
- if (timchar[j] !== buf2[pos2 + j]) continue loop1;
2626
- }
2627
- return timchar.length;
2628
- }
2629
- return 0;
2630
- }, "isTrim");
2631
- return isTrim(buf, pos);
2632
- }, "__isCharTrimable"),
2633
- // Keep it in case we implement the `cast_int` option
2634
- // __isInt(value){
2635
- // // return Number.isInteger(parseInt(value))
2636
- // // return !isNaN( parseInt( obj ) );
2637
- // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
2638
- // }
2639
- __isFloat: /* @__PURE__ */ __name(function(value) {
2640
- return value - parseFloat(value) + 1 >= 0;
2641
- }, "__isFloat"),
2642
- __compareBytes: /* @__PURE__ */ __name(function(sourceBuf, targetBuf, targetPos, firstByte) {
2643
- if (sourceBuf[0] !== firstByte) return 0;
2644
- const sourceLength = sourceBuf.length;
2645
- for (let i = 1; i < sourceLength; i++) {
2646
- if (sourceBuf[i] !== targetBuf[targetPos + i]) return 0;
2647
- }
2648
- return sourceLength;
2649
- }, "__compareBytes"),
2650
- __isDelimiter: /* @__PURE__ */ __name(function(buf, pos, chr) {
2651
- const { delimiter, ignore_last_delimiters } = this.options;
2652
- if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) {
2653
- return 0;
2654
- } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === "number" && this.state.record.length === ignore_last_delimiters - 1) {
2655
- return 0;
2656
- }
2657
- loop1: for (let i = 0; i < delimiter.length; i++) {
2658
- const del = delimiter[i];
2659
- if (del[0] === chr) {
2660
- for (let j = 1; j < del.length; j++) {
2661
- if (del[j] !== buf[pos + j]) continue loop1;
2662
- }
2663
- return del.length;
2664
- }
2665
- }
2666
- return 0;
2667
- }, "__isDelimiter"),
2668
- __isRecordDelimiter: /* @__PURE__ */ __name(function(chr, buf, pos) {
2669
- const { record_delimiter } = this.options;
2670
- const recordDelimiterLength = record_delimiter.length;
2671
- loop1: for (let i = 0; i < recordDelimiterLength; i++) {
2672
- const rd = record_delimiter[i];
2673
- const rdLength = rd.length;
2674
- if (rd[0] !== chr) {
2675
- continue;
2676
- }
2677
- for (let j = 1; j < rdLength; j++) {
2678
- if (rd[j] !== buf[pos + j]) {
2679
- continue loop1;
2680
- }
2681
- }
2682
- return rd.length;
2683
- }
2684
- return 0;
2685
- }, "__isRecordDelimiter"),
2686
- __isEscape: /* @__PURE__ */ __name(function(buf, pos, chr) {
2687
- const { escape } = this.options;
2688
- if (escape === null) return false;
2689
- const l = escape.length;
2690
- if (escape[0] === chr) {
2691
- for (let i = 0; i < l; i++) {
2692
- if (escape[i] !== buf[pos + i]) {
2693
- return false;
2694
- }
2695
- }
2696
- return true;
2697
- }
2698
- return false;
2699
- }, "__isEscape"),
2700
- __isQuote: /* @__PURE__ */ __name(function(buf, pos) {
2701
- const { quote } = this.options;
2702
- if (quote === null) return false;
2703
- const l = quote.length;
2704
- for (let i = 0; i < l; i++) {
2705
- if (quote[i] !== buf[pos + i]) {
2706
- return false;
2707
- }
2708
- }
2709
- return true;
2710
- }, "__isQuote"),
2711
- __autoDiscoverRecordDelimiter: /* @__PURE__ */ __name(function(buf, pos) {
2712
- const { encoding } = this.options;
2713
- const rds = [
2714
- // Important, the windows line ending must be before mac os 9
2715
- Buffer.from("\r\n", encoding),
2716
- Buffer.from("\n", encoding),
2717
- Buffer.from("\r", encoding)
2718
- ];
2719
- loop: for (let i = 0; i < rds.length; i++) {
2720
- const l = rds[i].length;
2721
- for (let j = 0; j < l; j++) {
2722
- if (rds[i][j] !== buf[pos + j]) {
2723
- continue loop;
2724
- }
2725
- }
2726
- this.options.record_delimiter.push(rds[i]);
2727
- this.state.recordDelimiterMaxLength = rds[i].length;
2728
- return rds[i].length;
2729
- }
2730
- return 0;
2731
- }, "__autoDiscoverRecordDelimiter"),
2732
- __error: /* @__PURE__ */ __name(function(msg) {
2733
- const { encoding, raw, skip_records_with_error } = this.options;
2734
- const err = typeof msg === "string" ? new Error(msg) : msg;
2735
- if (skip_records_with_error) {
2736
- this.state.recordHasError = true;
2737
- if (this.options.on_skip !== void 0) {
2738
- this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : void 0);
2739
- }
2740
- return void 0;
2741
- } else {
2742
- return err;
2743
- }
2744
- }, "__error"),
2745
- __infoDataSet: /* @__PURE__ */ __name(function() {
2746
- return {
2747
- ...this.info,
2748
- columns: this.options.columns
2749
- };
2750
- }, "__infoDataSet"),
2751
- __infoRecord: /* @__PURE__ */ __name(function() {
2752
- const { columns, raw, encoding } = this.options;
2753
- return {
2754
- ...this.__infoDataSet(),
2755
- error: this.state.error,
2756
- header: columns === true,
2757
- index: this.state.record.length,
2758
- raw: raw ? this.state.rawBuffer.toString(encoding) : void 0
2759
- };
2760
- }, "__infoRecord"),
2761
- __infoField: /* @__PURE__ */ __name(function() {
2762
- const { columns } = this.options;
2763
- const isColumns = Array.isArray(columns);
2764
- return {
2765
- ...this.__infoRecord(),
2766
- column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length,
2767
- quoting: this.state.wasQuoting
2768
- };
2769
- }, "__infoField")
2770
- };
2771
- }, "transform");
2772
-
2773
- // ../../node_modules/.pnpm/csv-parse@5.5.6/node_modules/csv-parse/lib/sync.js
2774
- var parse = /* @__PURE__ */ __name(function(data, opts = {}) {
2775
- if (typeof data === "string") {
2776
- data = Buffer.from(data);
2777
- }
2778
- const records = opts && opts.objname ? {} : [];
2779
- const parser = transform(opts);
2780
- const push = /* @__PURE__ */ __name((record) => {
2781
- if (parser.options.objname === void 0)
2782
- records.push(record);
2783
- else {
2784
- records[record[0]] = record[1];
2785
- }
2786
- }, "push");
2787
- const close = /* @__PURE__ */ __name(() => {
2788
- }, "close");
2789
- const err1 = parser.parse(data, false, push, close);
2790
- if (err1 !== void 0) throw err1;
2791
- const err2 = parser.parse(void 0, true, push, close);
2792
- if (err2 !== void 0) throw err2;
2793
- return records;
2794
- }, "parse");
2795
-
2796
- // src/utils/dex-price.ts
2797
- import { EthChainId as EthChainId2 } from "@sentio/chain";
2798
- import { createRequire } from "module";
2799
- import path from "path";
2800
- var PriceUnit = /* @__PURE__ */ ((PriceUnit2) => {
2801
- PriceUnit2[PriceUnit2["USD"] = 0] = "USD";
2802
- PriceUnit2[PriceUnit2["ETH"] = 1] = "ETH";
2803
- PriceUnit2[PriceUnit2["BTC"] = 2] = "BTC";
2804
- return PriceUnit2;
2805
- })(PriceUnit || {});
2806
- function getPackageRoot(pkgId) {
2807
- const require2 = createRequire(import.meta.url);
2808
- const m = require2.resolve(pkgId);
2809
- let dir = path.dirname(m);
2810
- while (!fs.existsSync(path.join(dir, "package.json"))) {
2811
- dir = path.dirname(dir);
2812
- }
2813
- return dir;
2814
- }
2815
- __name(getPackageRoot, "getPackageRoot");
2816
- var DexPrice = class {
2817
- static {
2818
- __name(this, "DexPrice");
2819
- }
2820
- USD_ORACLE_MAP = /* @__PURE__ */ new Map();
2821
- ETH_ORACLE_MAP = /* @__PURE__ */ new Map();
2822
- BTC_ORACLE_MAP = /* @__PURE__ */ new Map();
2823
- ASSETS_INFOS = /* @__PURE__ */ new Map();
2824
- chainId;
2825
- constructor(csvFileName, chainId) {
2826
- this.chainId = chainId;
2827
- const packageRoot = getPackageRoot("@sentio/sdk");
2828
- const csvFilePath = path.join(packageRoot, "assets", csvFileName);
2829
- const fileContent = fs.readFileSync(csvFilePath, { encoding: "utf-8" });
2830
- const headers = ["Pair", "Asset", "Type", "Address"];
2831
- const records = parse(fileContent, {
2832
- delimiter: ",",
2833
- columns: headers,
2834
- skip_empty_lines: true
2835
- });
2836
- for (const record of records) {
2837
- const pair = record.Pair.split("/");
2838
- const asset = pair[0].trim().toLowerCase();
2839
- const target = pair[1].trim().toLowerCase();
2840
- const address = record.Address.toLowerCase();
2841
- if (target === "usd") {
2842
- this.USD_ORACLE_MAP.set(asset, address);
2843
- } else if (target === "eth") {
2844
- this.ETH_ORACLE_MAP.set(asset, address);
2845
- } else if (target == "btc") {
2846
- this.BTC_ORACLE_MAP.set(asset, address);
2847
- } else {
2848
- console.error("wrong asset record:" + JSON.stringify(record));
2849
- }
2850
- }
2851
- }
2852
- // asset: symbol of the asset
2853
- // unit: usd, eth or btc
2854
- // blockTag: blockNumber of block symbol like "latest"
2855
- // returns the asset price,
2856
- // throw exception if calling to price feed failed, e.g. due to a invalid block number
2857
- async getPrice(asset, blockTag = "latest", unit = 0 /* USD */) {
2858
- let oracleMap = this.USD_ORACLE_MAP;
2859
- switch (unit) {
2860
- case 1 /* ETH */:
2861
- oracleMap = this.ETH_ORACLE_MAP;
2862
- break;
2863
- case 2 /* BTC */:
2864
- oracleMap = this.BTC_ORACLE_MAP;
2865
- break;
2866
- default:
2867
- }
2868
- asset = asset.trim().toLowerCase();
2869
- const addr = oracleMap.get(asset);
2870
- if (!addr) {
2871
- return {
2872
- error: "No price feed found for asset"
2873
- };
2874
- }
2875
- const contract = getEACAggregatorProxyContract(this.chainId, addr);
2876
- try {
2877
- const price = await contract.latestAnswer({
2878
- blockTag
2879
- });
2880
- let decimal = this.ASSETS_INFOS.get(asset);
2881
- if (!decimal) {
2882
- decimal = Number(await contract.decimals());
2883
- this.ASSETS_INFOS.set(asset, decimal);
2884
- }
2885
- return {
2886
- price: scaleDown(price, decimal).toNumber()
2887
- };
2888
- } catch (e) {
2889
- return {
2890
- error: "Price query error for " + asset + " failed at " + addr + " at chain " + this.chainId + ". Details: " + e.toString()
2891
- };
2892
- }
2893
- }
2894
- };
2895
- var EthereumDexPrice = new DexPrice("chainlink-oracles.csv", EthChainId2.ETHEREUM);
2896
- var SepoliaDexPrice = new DexPrice("chainlink-oracles-sepolia.csv", EthChainId2.SEPOLIA);
2897
- import("node:process").then((p) => p.stdout.write(""));
2898
-
2899
- // src/utils/price.ts
2900
- import { Endpoints, processMetrics } from "@sentio/runtime";
2901
-
2902
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/runtime.js
2903
- var BASE_PATH = "https://app.sentio.xyz".replace(/\/+$/, "");
2904
- var Configuration = class {
2905
- static {
2906
- __name(this, "Configuration");
2907
- }
2908
- configuration;
2909
- constructor(configuration = {}) {
2910
- this.configuration = configuration;
2911
- }
2912
- set config(configuration) {
2913
- this.configuration = configuration;
2914
- }
2915
- get basePath() {
2916
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
2917
- }
2918
- get fetchApi() {
2919
- return this.configuration.fetchApi;
2920
- }
2921
- get middleware() {
2922
- return this.configuration.middleware || [];
2923
- }
2924
- get queryParamsStringify() {
2925
- return this.configuration.queryParamsStringify || querystring;
2926
- }
2927
- get username() {
2928
- return this.configuration.username;
2929
- }
2930
- get password() {
2931
- return this.configuration.password;
2932
- }
2933
- get apiKey() {
2934
- const apiKey = this.configuration.apiKey;
2935
- if (apiKey) {
2936
- return typeof apiKey === "function" ? apiKey : () => apiKey;
2937
- }
2938
- return void 0;
2939
- }
2940
- get accessToken() {
2941
- const accessToken = this.configuration.accessToken;
2942
- if (accessToken) {
2943
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
2944
- }
2945
- return void 0;
2946
- }
2947
- get headers() {
2948
- return this.configuration.headers;
2949
- }
2950
- get credentials() {
2951
- return this.configuration.credentials;
2952
- }
2953
- };
2954
- var DefaultConfig = new Configuration();
2955
- var BaseAPI = class _BaseAPI {
2956
- static {
2957
- __name(this, "BaseAPI");
2958
- }
2959
- configuration;
2960
- static jsonRegex = new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$", "i");
2961
- middleware;
2962
- constructor(configuration = DefaultConfig) {
2963
- this.configuration = configuration;
2964
- this.middleware = configuration.middleware;
2965
- }
2966
- withMiddleware(...middlewares) {
2967
- const next = this.clone();
2968
- next.middleware = next.middleware.concat(...middlewares);
2969
- return next;
2970
- }
2971
- withPreMiddleware(...preMiddlewares) {
2972
- const middlewares = preMiddlewares.map((pre) => ({ pre }));
2973
- return this.withMiddleware(...middlewares);
2974
- }
2975
- withPostMiddleware(...postMiddlewares) {
2976
- const middlewares = postMiddlewares.map((post) => ({ post }));
2977
- return this.withMiddleware(...middlewares);
2978
- }
2979
- /**
2980
- * Check if the given MIME is a JSON MIME.
2981
- * JSON MIME examples:
2982
- * application/json
2983
- * application/json; charset=UTF8
2984
- * APPLICATION/JSON
2985
- * application/vnd.company+json
2986
- * @param mime - MIME (Multipurpose Internet Mail Extensions)
2987
- * @return True if the given MIME is JSON, false otherwise.
2988
- */
2989
- isJsonMime(mime) {
2990
- if (!mime) {
2991
- return false;
2992
- }
2993
- return _BaseAPI.jsonRegex.test(mime);
2994
- }
2995
- async request(context, initOverrides) {
2996
- const { url, init } = await this.createFetchParams(context, initOverrides);
2997
- const response = await this.fetchApi(url, init);
2998
- if (response && (response.status >= 200 && response.status < 300)) {
2999
- return response;
3000
- }
3001
- throw new ResponseError(response, "Response returned an error code");
3002
- }
3003
- async createFetchParams(context, initOverrides) {
3004
- let url = this.configuration.basePath + context.path;
3005
- if (context.query !== void 0 && Object.keys(context.query).length !== 0) {
3006
- url += "?" + this.configuration.queryParamsStringify(context.query);
3007
- }
3008
- const headers = Object.assign({}, this.configuration.headers, context.headers);
3009
- Object.keys(headers).forEach((key) => headers[key] === void 0 ? delete headers[key] : {});
3010
- const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
3011
- const initParams = {
3012
- method: context.method,
3013
- headers,
3014
- body: context.body,
3015
- credentials: this.configuration.credentials
3016
- };
3017
- const overriddenInit = {
3018
- ...initParams,
3019
- ...await initOverrideFn({
3020
- init: initParams,
3021
- context
3022
- })
3023
- };
3024
- let body;
3025
- if (isFormData(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob(overriddenInit.body)) {
3026
- body = overriddenInit.body;
3027
- } else if (this.isJsonMime(headers["Content-Type"])) {
3028
- body = JSON.stringify(overriddenInit.body);
3029
- } else {
3030
- body = overriddenInit.body;
3031
- }
3032
- const init = {
3033
- ...overriddenInit,
3034
- body
3035
- };
3036
- return { url, init };
3037
- }
3038
- fetchApi = /* @__PURE__ */ __name(async (url, init) => {
3039
- let fetchParams = { url, init };
3040
- for (const middleware of this.middleware) {
3041
- if (middleware.pre) {
3042
- fetchParams = await middleware.pre({
3043
- fetch: this.fetchApi,
3044
- ...fetchParams
3045
- }) || fetchParams;
3046
- }
3047
- }
3048
- let response = void 0;
3049
- try {
3050
- response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
3051
- } catch (e) {
3052
- for (const middleware of this.middleware) {
3053
- if (middleware.onError) {
3054
- response = await middleware.onError({
3055
- fetch: this.fetchApi,
3056
- url: fetchParams.url,
3057
- init: fetchParams.init,
3058
- error: e,
3059
- response: response ? response.clone() : void 0
3060
- }) || response;
3061
- }
3062
- }
3063
- if (response === void 0) {
3064
- if (e instanceof Error) {
3065
- throw new FetchError(e, "The request failed and the interceptors did not return an alternative response");
3066
- } else {
3067
- throw e;
3068
- }
3069
- }
3070
- }
3071
- for (const middleware of this.middleware) {
3072
- if (middleware.post) {
3073
- response = await middleware.post({
3074
- fetch: this.fetchApi,
3075
- url: fetchParams.url,
3076
- init: fetchParams.init,
3077
- response: response.clone()
3078
- }) || response;
3079
- }
3080
- }
3081
- return response;
3082
- }, "fetchApi");
3083
- /**
3084
- * Create a shallow clone of `this` by constructing a new instance
3085
- * and then shallow cloning data members.
3086
- */
3087
- clone() {
3088
- const constructor = this.constructor;
3089
- const next = new constructor(this.configuration);
3090
- next.middleware = this.middleware.slice();
3091
- return next;
3092
- }
3093
- };
3094
- function isBlob(value) {
3095
- return typeof Blob !== "undefined" && value instanceof Blob;
3096
- }
3097
- __name(isBlob, "isBlob");
3098
- function isFormData(value) {
3099
- return typeof FormData !== "undefined" && value instanceof FormData;
3100
- }
3101
- __name(isFormData, "isFormData");
3102
- var ResponseError = class extends Error {
3103
- static {
3104
- __name(this, "ResponseError");
3105
- }
3106
- response;
3107
- name = "ResponseError";
3108
- constructor(response, msg) {
3109
- super(msg);
3110
- this.response = response;
3111
- }
3112
- };
3113
- var FetchError = class extends Error {
3114
- static {
3115
- __name(this, "FetchError");
3116
- }
3117
- cause;
3118
- name = "FetchError";
3119
- constructor(cause, msg) {
3120
- super(msg);
3121
- this.cause = cause;
3122
- }
3123
- };
3124
- function querystring(params, prefix = "") {
3125
- return Object.keys(params).map((key) => querystringSingleKey(key, params[key], prefix)).filter((part) => part.length > 0).join("&");
3126
- }
3127
- __name(querystring, "querystring");
3128
- function querystringSingleKey(key, value, keyPrefix = "") {
3129
- const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
3130
- if (value instanceof Array) {
3131
- const multiValue = value.map((singleValue) => encodeURIComponent(String(singleValue))).join(`&${encodeURIComponent(fullKey)}=`);
3132
- return `${encodeURIComponent(fullKey)}=${multiValue}`;
3133
- }
3134
- if (value instanceof Set) {
3135
- const valueAsArray = Array.from(value);
3136
- return querystringSingleKey(key, valueAsArray, keyPrefix);
3137
- }
3138
- if (value instanceof Date) {
3139
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
3140
- }
3141
- if (value instanceof Object) {
3142
- return querystring(value, fullKey);
3143
- }
3144
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
3145
- }
3146
- __name(querystringSingleKey, "querystringSingleKey");
3147
- function mapValues(data, fn) {
3148
- return Object.keys(data).reduce((acc, key) => ({ ...acc, [key]: fn(data[key]) }), {});
3149
- }
3150
- __name(mapValues, "mapValues");
3151
- var JSONApiResponse = class {
3152
- static {
3153
- __name(this, "JSONApiResponse");
3154
- }
3155
- raw;
3156
- transformer;
3157
- constructor(raw, transformer = (jsonValue) => jsonValue) {
3158
- this.raw = raw;
3159
- this.transformer = transformer;
3160
- }
3161
- async value() {
3162
- return this.transformer(await this.raw.json());
3163
- }
3164
- };
3165
-
3166
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceGetPriceResponse.js
3167
- function PriceServiceGetPriceResponseFromJSON(json) {
3168
- return PriceServiceGetPriceResponseFromJSONTyped(json, false);
3169
- }
3170
- __name(PriceServiceGetPriceResponseFromJSON, "PriceServiceGetPriceResponseFromJSON");
3171
- function PriceServiceGetPriceResponseFromJSONTyped(json, ignoreDiscriminator) {
3172
- if (json == null) {
3173
- return json;
3174
- }
3175
- return {
3176
- "price": json["price"] == null ? void 0 : json["price"],
3177
- "timestamp": json["timestamp"] == null ? void 0 : new Date(json["timestamp"])
3178
- };
3179
- }
3180
- __name(PriceServiceGetPriceResponseFromJSONTyped, "PriceServiceGetPriceResponseFromJSONTyped");
3181
-
3182
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceBatchGetPricesResponseCoinPricePrice.js
3183
- function PriceServiceBatchGetPricesResponseCoinPricePriceFromJSON(json) {
3184
- return PriceServiceBatchGetPricesResponseCoinPricePriceFromJSONTyped(json, false);
3185
- }
3186
- __name(PriceServiceBatchGetPricesResponseCoinPricePriceFromJSON, "PriceServiceBatchGetPricesResponseCoinPricePriceFromJSON");
3187
- function PriceServiceBatchGetPricesResponseCoinPricePriceFromJSONTyped(json, ignoreDiscriminator) {
3188
- if (json == null) {
3189
- return json;
3190
- }
3191
- return {
3192
- "results": json["results"] == null ? void 0 : json["results"].map(PriceServiceGetPriceResponseFromJSON)
3193
- };
3194
- }
3195
- __name(PriceServiceBatchGetPricesResponseCoinPricePriceFromJSONTyped, "PriceServiceBatchGetPricesResponseCoinPricePriceFromJSONTyped");
3196
-
3197
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceCoinIDAddressIdentifier.js
3198
- function PriceServiceCoinIDAddressIdentifierFromJSON(json) {
3199
- return PriceServiceCoinIDAddressIdentifierFromJSONTyped(json, false);
3200
- }
3201
- __name(PriceServiceCoinIDAddressIdentifierFromJSON, "PriceServiceCoinIDAddressIdentifierFromJSON");
3202
- function PriceServiceCoinIDAddressIdentifierFromJSONTyped(json, ignoreDiscriminator) {
3203
- if (json == null) {
3204
- return json;
3205
- }
3206
- return {
3207
- "address": json["address"] == null ? void 0 : json["address"],
3208
- "chain": json["chain"] == null ? void 0 : json["chain"]
3209
- };
3210
- }
3211
- __name(PriceServiceCoinIDAddressIdentifierFromJSONTyped, "PriceServiceCoinIDAddressIdentifierFromJSONTyped");
3212
-
3213
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceCoinID.js
3214
- function PriceServiceCoinIDFromJSON(json) {
3215
- return PriceServiceCoinIDFromJSONTyped(json, false);
3216
- }
3217
- __name(PriceServiceCoinIDFromJSON, "PriceServiceCoinIDFromJSON");
3218
- function PriceServiceCoinIDFromJSONTyped(json, ignoreDiscriminator) {
3219
- if (json == null) {
3220
- return json;
3221
- }
3222
- return {
3223
- "symbol": json["symbol"] == null ? void 0 : json["symbol"],
3224
- "address": json["address"] == null ? void 0 : PriceServiceCoinIDAddressIdentifierFromJSON(json["address"])
3225
- };
3226
- }
3227
- __name(PriceServiceCoinIDFromJSONTyped, "PriceServiceCoinIDFromJSONTyped");
3228
-
3229
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceBatchGetPricesResponseCoinPrice.js
3230
- function PriceServiceBatchGetPricesResponseCoinPriceFromJSON(json) {
3231
- return PriceServiceBatchGetPricesResponseCoinPriceFromJSONTyped(json, false);
3232
- }
3233
- __name(PriceServiceBatchGetPricesResponseCoinPriceFromJSON, "PriceServiceBatchGetPricesResponseCoinPriceFromJSON");
3234
- function PriceServiceBatchGetPricesResponseCoinPriceFromJSONTyped(json, ignoreDiscriminator) {
3235
- if (json == null) {
3236
- return json;
3237
- }
3238
- return {
3239
- "coinId": json["coinId"] == null ? void 0 : PriceServiceCoinIDFromJSON(json["coinId"]),
3240
- "price": json["price"] == null ? void 0 : PriceServiceBatchGetPricesResponseCoinPricePriceFromJSON(json["price"]),
3241
- "error": json["error"] == null ? void 0 : json["error"]
3242
- };
3243
- }
3244
- __name(PriceServiceBatchGetPricesResponseCoinPriceFromJSONTyped, "PriceServiceBatchGetPricesResponseCoinPriceFromJSONTyped");
3245
-
3246
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceBatchGetPricesResponse.js
3247
- function PriceServiceBatchGetPricesResponseFromJSON(json) {
3248
- return PriceServiceBatchGetPricesResponseFromJSONTyped(json, false);
3249
- }
3250
- __name(PriceServiceBatchGetPricesResponseFromJSON, "PriceServiceBatchGetPricesResponseFromJSON");
3251
- function PriceServiceBatchGetPricesResponseFromJSONTyped(json, ignoreDiscriminator) {
3252
- if (json == null) {
3253
- return json;
3254
- }
3255
- return {
3256
- "prices": json["prices"] == null ? void 0 : json["prices"].map(PriceServiceBatchGetPricesResponseCoinPriceFromJSON)
3257
- };
3258
- }
3259
- __name(PriceServiceBatchGetPricesResponseFromJSONTyped, "PriceServiceBatchGetPricesResponseFromJSONTyped");
3260
-
3261
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceCheckLatestPriceResponseCoinPrice.js
3262
- function PriceServiceCheckLatestPriceResponseCoinPriceFromJSON(json) {
3263
- return PriceServiceCheckLatestPriceResponseCoinPriceFromJSONTyped(json, false);
3264
- }
3265
- __name(PriceServiceCheckLatestPriceResponseCoinPriceFromJSON, "PriceServiceCheckLatestPriceResponseCoinPriceFromJSON");
3266
- function PriceServiceCheckLatestPriceResponseCoinPriceFromJSONTyped(json, ignoreDiscriminator) {
3267
- if (json == null) {
3268
- return json;
3269
- }
3270
- return {
3271
- "coinId": json["coinId"] == null ? void 0 : PriceServiceCoinIDFromJSON(json["coinId"]),
3272
- "price": json["price"] == null ? void 0 : json["price"],
3273
- "timestamp": json["timestamp"] == null ? void 0 : new Date(json["timestamp"])
3274
- };
3275
- }
3276
- __name(PriceServiceCheckLatestPriceResponseCoinPriceFromJSONTyped, "PriceServiceCheckLatestPriceResponseCoinPriceFromJSONTyped");
3277
-
3278
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceCheckLatestPriceResponse.js
3279
- function PriceServiceCheckLatestPriceResponseFromJSON(json) {
3280
- return PriceServiceCheckLatestPriceResponseFromJSONTyped(json, false);
3281
- }
3282
- __name(PriceServiceCheckLatestPriceResponseFromJSON, "PriceServiceCheckLatestPriceResponseFromJSON");
3283
- function PriceServiceCheckLatestPriceResponseFromJSONTyped(json, ignoreDiscriminator) {
3284
- if (json == null) {
3285
- return json;
3286
- }
3287
- return {
3288
- "prices": json["prices"] == null ? void 0 : json["prices"].map(PriceServiceCheckLatestPriceResponseCoinPriceFromJSON),
3289
- "latestPrice": json["latestPrice"] == null ? void 0 : PriceServiceCheckLatestPriceResponseCoinPriceFromJSON(json["latestPrice"])
3290
- };
3291
- }
3292
- __name(PriceServiceCheckLatestPriceResponseFromJSONTyped, "PriceServiceCheckLatestPriceResponseFromJSONTyped");
3293
-
3294
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/models/PriceServiceListCoinsResponse.js
3295
- function PriceServiceListCoinsResponseFromJSON(json) {
3296
- return PriceServiceListCoinsResponseFromJSONTyped(json, false);
3297
- }
3298
- __name(PriceServiceListCoinsResponseFromJSON, "PriceServiceListCoinsResponseFromJSON");
3299
- function PriceServiceListCoinsResponseFromJSONTyped(json, ignoreDiscriminator) {
3300
- if (json == null) {
3301
- return json;
3302
- }
3303
- return {
3304
- "coins": json["coins"] == null ? void 0 : json["coins"].map(PriceServiceCoinIDFromJSON),
3305
- "coinAddressesInChain": json["coinAddressesInChain"] == null ? void 0 : mapValues(json["coinAddressesInChain"], PriceServiceCoinIDFromJSON)
3306
- };
3307
- }
3308
- __name(PriceServiceListCoinsResponseFromJSONTyped, "PriceServiceListCoinsResponseFromJSONTyped");
3309
-
3310
- // ../../node_modules/.pnpm/@sentio+api@1.0.2-rc.11/node_modules/@sentio/api/dist/src/apis/PriceApi.js
3311
- var PriceApi = class extends BaseAPI {
3312
- static {
3313
- __name(this, "PriceApi");
3314
- }
3315
- /**
3316
- * Batch get prices
3317
- */
3318
- async batchGetPricesRaw(requestParameters, initOverrides) {
3319
- const queryParameters = {};
3320
- if (requestParameters["timestamps"] != null) {
3321
- queryParameters["timestamps"] = requestParameters["timestamps"];
3322
- }
3323
- const headerParameters = {};
3324
- if (this.configuration && this.configuration.apiKey) {
3325
- headerParameters["api-key"] = await this.configuration.apiKey("api-key");
3326
- }
3327
- const response = await this.request({
3328
- path: `/api/v1/prices/batch`,
3329
- method: "GET",
3330
- headers: headerParameters,
3331
- query: queryParameters
3332
- }, initOverrides);
3333
- return new JSONApiResponse(response, (jsonValue) => PriceServiceBatchGetPricesResponseFromJSON(jsonValue));
3334
- }
3335
- /**
3336
- * Batch get prices
3337
- */
3338
- async batchGetPrices(requestParameters = {}, initOverrides) {
3339
- const response = await this.batchGetPricesRaw(requestParameters, initOverrides);
3340
- return await response.value();
3341
- }
3342
- /**
3343
- * Check latest price
3344
- */
3345
- async checkLatestPriceRaw(initOverrides) {
3346
- const queryParameters = {};
3347
- const headerParameters = {};
3348
- if (this.configuration && this.configuration.apiKey) {
3349
- headerParameters["api-key"] = await this.configuration.apiKey("api-key");
3350
- }
3351
- const response = await this.request({
3352
- path: `/api/v1/prices/check_latest`,
3353
- method: "GET",
3354
- headers: headerParameters,
3355
- query: queryParameters
3356
- }, initOverrides);
3357
- return new JSONApiResponse(response, (jsonValue) => PriceServiceCheckLatestPriceResponseFromJSON(jsonValue));
3358
- }
3359
- /**
3360
- * Check latest price
3361
- */
3362
- async checkLatestPrice(initOverrides) {
3363
- const response = await this.checkLatestPriceRaw(initOverrides);
3364
- return await response.value();
3365
- }
3366
- /**
3367
- * GetPrice returns the price of a given coin identifier, in a best effort way. If we do not have any price data for the given coin, we will return NOT_FOUND error. If we have at least one price data for the given coin, we will return it with the actual timestamp. Client is responsible for checking the timestamp and decide whether to use the price or not.
3368
- * Get price
3369
- */
3370
- async getPriceRaw(requestParameters, initOverrides) {
3371
- const queryParameters = {};
3372
- if (requestParameters["timestamp"] != null) {
3373
- queryParameters["timestamp"] = requestParameters["timestamp"].toISOString();
3374
- }
3375
- if (requestParameters["coinIdSymbol"] != null) {
3376
- queryParameters["coinId.symbol"] = requestParameters["coinIdSymbol"];
3377
- }
3378
- if (requestParameters["coinIdAddressAddress"] != null) {
3379
- queryParameters["coinId.address.address"] = requestParameters["coinIdAddressAddress"];
3380
- }
3381
- if (requestParameters["coinIdAddressChain"] != null) {
3382
- queryParameters["coinId.address.chain"] = requestParameters["coinIdAddressChain"];
3383
- }
3384
- if (requestParameters["source"] != null) {
3385
- queryParameters["source"] = requestParameters["source"];
3386
- }
3387
- const headerParameters = {};
3388
- if (this.configuration && this.configuration.apiKey) {
3389
- headerParameters["api-key"] = await this.configuration.apiKey("api-key");
3390
- }
3391
- const response = await this.request({
3392
- path: `/api/v1/prices`,
3393
- method: "GET",
3394
- headers: headerParameters,
3395
- query: queryParameters
3396
- }, initOverrides);
3397
- return new JSONApiResponse(response, (jsonValue) => PriceServiceGetPriceResponseFromJSON(jsonValue));
3398
- }
3399
- /**
3400
- * GetPrice returns the price of a given coin identifier, in a best effort way. If we do not have any price data for the given coin, we will return NOT_FOUND error. If we have at least one price data for the given coin, we will return it with the actual timestamp. Client is responsible for checking the timestamp and decide whether to use the price or not.
3401
- * Get price
3402
- */
3403
- async getPrice(requestParameters = {}, initOverrides) {
3404
- const response = await this.getPriceRaw(requestParameters, initOverrides);
3405
- return await response.value();
3406
- }
3407
- /**
3408
- * List coins
3409
- */
3410
- async priceListCoinsRaw(requestParameters, initOverrides) {
3411
- const queryParameters = {};
3412
- if (requestParameters["limit"] != null) {
3413
- queryParameters["limit"] = requestParameters["limit"];
3414
- }
3415
- if (requestParameters["offset"] != null) {
3416
- queryParameters["offset"] = requestParameters["offset"];
3417
- }
3418
- if (requestParameters["searchQuery"] != null) {
3419
- queryParameters["searchQuery"] = requestParameters["searchQuery"];
3420
- }
3421
- if (requestParameters["chain"] != null) {
3422
- queryParameters["chain"] = requestParameters["chain"];
3423
- }
3424
- const headerParameters = {};
3425
- if (this.configuration && this.configuration.apiKey) {
3426
- headerParameters["api-key"] = await this.configuration.apiKey("api-key");
3427
- }
3428
- const response = await this.request({
3429
- path: `/api/v1/prices/coins`,
3430
- method: "GET",
3431
- headers: headerParameters,
3432
- query: queryParameters
3433
- }, initOverrides);
3434
- return new JSONApiResponse(response, (jsonValue) => PriceServiceListCoinsResponseFromJSON(jsonValue));
3435
- }
3436
- /**
3437
- * List coins
3438
- */
3439
- async priceListCoins(requestParameters = {}, initOverrides) {
3440
- const response = await this.priceListCoinsRaw(requestParameters, initOverrides);
3441
- return await response.value();
3442
- }
3443
- };
3444
-
3445
- // src/utils/price.ts
3446
- import path2 from "path";
3447
- import fs2 from "fs";
3448
- import os from "os";
3449
- function getApiKey() {
3450
- try {
3451
- const content = fs2.readFileSync(path2.join(os.homedir(), ".sentio", "config.json"), "utf8");
3452
- const config = JSON.parse(content);
3453
- return config["https://app.sentio.xyz"]?.api_keys;
3454
- } catch (e) {
3455
- }
3456
- }
3457
- __name(getApiKey, "getApiKey");
3458
- function getPriceClient(basePath = Endpoints.INSTANCE.priceFeedAPI) {
3459
- if (!basePath.startsWith("http")) {
3460
- basePath = "http://" + basePath;
3461
- }
3462
- if (basePath.endsWith("/")) {
3463
- basePath = basePath.slice(0, -1);
3464
- }
3465
- const config = new Configuration({
3466
- basePath,
3467
- apiKey: getApiKey()
3468
- });
3469
- const api = new PriceApi(config);
3470
- return api;
3471
- }
3472
- __name(getPriceClient, "getPriceClient");
3473
- var priceMap = new LRUCache({
3474
- max: 1e5,
3475
- ttl: 1e3 * 60 * 5
3476
- // 5 minutes
3477
- });
3478
- var priceClient;
3479
- async function getPriceByTypeOrSymbol(date, coinId, options) {
3480
- if (!priceClient) {
3481
- priceClient = getPriceClient();
3482
- }
3483
- return getPriceByTypeOrSymbolInternal(priceClient, date, coinId, options);
3484
- }
3485
- __name(getPriceByTypeOrSymbol, "getPriceByTypeOrSymbol");
3486
- async function getPriceByTypeOrSymbolInternal(priceClient2, date, coinId, options) {
3487
- const dateStr = dateString(date);
3488
- const todayDateString = dateString(/* @__PURE__ */ new Date());
3489
- let key;
3490
- if (coinId.symbol) {
3491
- key = `${coinId.symbol}-${dateStr}`;
3492
- } else {
3493
- key = `${coinId.address?.address}-${coinId.address?.chain}-${dateStr}`;
3494
- }
3495
- let price = priceMap.get(key);
3496
- if (price) {
3497
- return price;
3498
- }
3499
- processMetrics.process_pricecall_count.add(1);
3500
- const response = priceClient2.getPrice({
3501
- timestamp: date,
3502
- coinIdSymbol: coinId.symbol,
3503
- coinIdAddressAddress: coinId.address?.address,
3504
- coinIdAddressChain: coinId.address?.chain
3505
- });
3506
- price = response.then((res) => {
3507
- if (res.timestamp) {
3508
- const responseDateString = dateString(res.timestamp);
3509
- if (responseDateString === todayDateString) {
3510
- priceMap.delete(key);
3511
- } else {
3512
- const diff = Math.abs(res.timestamp.getTime() - date.getTime());
3513
- const daysDiff = diff / (1e3 * 60 * 60 * 24);
3514
- const tolerance = options?.toleranceInDays || 2;
3515
- if (daysDiff > tolerance) {
3516
- priceMap.delete(key);
3517
- return void 0;
3518
- }
3519
- }
3520
- } else {
3521
- priceMap.delete(key);
3522
- }
3523
- return res.price;
3524
- }).catch((e) => {
3525
- setTimeout(() => {
3526
- priceMap.delete(key);
3527
- }, 1e3);
3528
- if (e.response?.status === 404) {
3529
- console.error("price not found for ", JSON.stringify(coinId), " at ", dateStr);
3530
- return void 0;
3531
- }
3532
- priceMap.delete(key);
3533
- throw e;
3534
- });
3535
- priceMap.set(key, price);
3536
- return price;
3537
- }
3538
- __name(getPriceByTypeOrSymbolInternal, "getPriceByTypeOrSymbolInternal");
3539
- async function getPriceByType(chainId, coinType, date, options) {
3540
- return getPriceByTypeOrSymbol(
3541
- date,
3542
- {
3543
- address: {
3544
- chain: chainId,
3545
- address: coinType
3546
- }
3547
- },
3548
- options
3549
- );
3550
- }
3551
- __name(getPriceByType, "getPriceByType");
3552
- async function getPriceBySymbol(symbol, date, options) {
3553
- return getPriceByTypeOrSymbol(date, { symbol }, options);
3554
- }
3555
- __name(getPriceBySymbol, "getPriceBySymbol");
3556
- function dateString(date) {
3557
- return [date.getHours(), date.getUTCDate(), date.getUTCMonth() + 1, date.getUTCFullYear()].join("-");
3558
- }
3559
- __name(dateString, "dateString");
3560
- async function getCoinsThatHasPrice(chainId) {
3561
- if (!priceClient) {
3562
- priceClient = getPriceClient();
3563
- }
3564
- const response = await priceClient.priceListCoins({
3565
- chain: chainId,
3566
- limit: 1e3
3567
- });
3568
- if (!response.coinAddressesInChain) {
3569
- return [];
3570
- }
3571
- return Object.entries(response.coinAddressesInChain).map(([symbol, coin]) => {
3572
- coin.symbol = symbol;
3573
- return coin;
3574
- });
3575
- }
3576
- __name(getCoinsThatHasPrice, "getCoinsThatHasPrice");
3577
- import("node:process").then((p) => p.stdout.write(""));
3578
-
3579
- // src/utils/call.ts
3580
- async function ignoreEthCallException(promise, logError = false) {
3581
- try {
3582
- return await promise;
3583
- } catch (err) {
3584
- if (err instanceof SimpleEthersError || err.code === "CALL_EXCEPTION" || err.code === "BAD_DATA") {
3585
- if (logError) {
3586
- console.error("eth call exception, return undefined", err);
3587
- }
3588
- return void 0;
3589
- }
3590
- throw err;
3591
- }
3592
- }
3593
- __name(ignoreEthCallException, "ignoreEthCallException");
3594
- import("node:process").then((p) => p.stdout.write(""));
3595
-
3596
- // src/utils/index.ts
3597
- import("node:process").then((p) => p.stdout.write(""));
3598
-
3599
- export {
3600
- estimateBlockNumberAtDate,
3601
- bytesToBigInt,
3602
- token_exports,
3603
- PriceUnit,
3604
- getPackageRoot,
3605
- EthereumDexPrice,
3606
- SepoliaDexPrice,
3607
- getPriceClient,
3608
- getPriceByType,
3609
- getPriceBySymbol,
3610
- getCoinsThatHasPrice,
3611
- ignoreEthCallException
3612
- };
3613
- //# sourceMappingURL=chunk-AZFMPZRN.js.map