@pezkuwi/rpc-provider 16.5.8 → 16.5.9

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 (212) hide show
  1. package/cjs/packageInfo.js +1 -1
  2. package/package.json +12 -12
  3. package/packageInfo.js +1 -1
  4. package/build/LICENSE +0 -201
  5. package/build/README.md +0 -68
  6. package/build/bizinikiwi-connect/Health.d.ts +0 -7
  7. package/build/bizinikiwi-connect/Health.js +0 -259
  8. package/build/bizinikiwi-connect/index.d.ts +0 -22
  9. package/build/bizinikiwi-connect/index.js +0 -319
  10. package/build/bizinikiwi-connect/types.d.ts +0 -12
  11. package/build/bizinikiwi-connect/types.js +0 -1
  12. package/build/bundle.d.ts +0 -5
  13. package/build/bundle.js +0 -5
  14. package/build/cjs/bizinikiwi-connect/Health.d.ts +0 -7
  15. package/build/cjs/bizinikiwi-connect/Health.js +0 -264
  16. package/build/cjs/bizinikiwi-connect/index.d.ts +0 -22
  17. package/build/cjs/bizinikiwi-connect/index.js +0 -323
  18. package/build/cjs/bizinikiwi-connect/types.d.ts +0 -12
  19. package/build/cjs/bizinikiwi-connect/types.js +0 -2
  20. package/build/cjs/bundle.d.ts +0 -5
  21. package/build/cjs/bundle.js +0 -14
  22. package/build/cjs/coder/error.d.ts +0 -29
  23. package/build/cjs/coder/error.js +0 -53
  24. package/build/cjs/coder/index.d.ts +0 -8
  25. package/build/cjs/coder/index.js +0 -63
  26. package/build/cjs/defaults.d.ts +0 -5
  27. package/build/cjs/defaults.js +0 -8
  28. package/build/cjs/http/index.d.ts +0 -81
  29. package/build/cjs/http/index.js +0 -196
  30. package/build/cjs/http/types.d.ts +0 -7
  31. package/build/cjs/http/types.js +0 -2
  32. package/build/cjs/index.d.ts +0 -2
  33. package/build/cjs/index.js +0 -5
  34. package/build/cjs/lru.d.ts +0 -15
  35. package/build/cjs/lru.js +0 -150
  36. package/build/cjs/mock/index.d.ts +0 -35
  37. package/build/cjs/mock/index.js +0 -196
  38. package/build/cjs/mock/mockHttp.d.ts +0 -9
  39. package/build/cjs/mock/mockHttp.js +0 -17
  40. package/build/cjs/mock/mockWs.d.ts +0 -26
  41. package/build/cjs/mock/mockWs.js +0 -47
  42. package/build/cjs/mock/types.d.ts +0 -23
  43. package/build/cjs/mock/types.js +0 -2
  44. package/build/cjs/package.json +0 -3
  45. package/build/cjs/packageDetect.d.ts +0 -1
  46. package/build/cjs/packageDetect.js +0 -6
  47. package/build/cjs/packageInfo.d.ts +0 -6
  48. package/build/cjs/packageInfo.js +0 -4
  49. package/build/cjs/types.d.ts +0 -85
  50. package/build/cjs/types.js +0 -2
  51. package/build/cjs/ws/errors.d.ts +0 -1
  52. package/build/cjs/ws/errors.js +0 -41
  53. package/build/cjs/ws/index.d.ts +0 -121
  54. package/build/cjs/ws/index.js +0 -529
  55. package/build/coder/error.d.ts +0 -29
  56. package/build/coder/error.js +0 -50
  57. package/build/coder/index.d.ts +0 -8
  58. package/build/coder/index.js +0 -58
  59. package/build/defaults.d.ts +0 -5
  60. package/build/defaults.js +0 -6
  61. package/build/http/index.d.ts +0 -81
  62. package/build/http/index.js +0 -191
  63. package/build/http/types.d.ts +0 -7
  64. package/build/http/types.js +0 -1
  65. package/build/index.d.ts +0 -2
  66. package/build/index.js +0 -2
  67. package/build/lru.d.ts +0 -15
  68. package/build/lru.js +0 -146
  69. package/build/mock/index.d.ts +0 -35
  70. package/build/mock/index.js +0 -191
  71. package/build/mock/mockHttp.d.ts +0 -9
  72. package/build/mock/mockHttp.js +0 -12
  73. package/build/mock/mockWs.d.ts +0 -26
  74. package/build/mock/mockWs.js +0 -43
  75. package/build/mock/types.d.ts +0 -23
  76. package/build/mock/types.js +0 -1
  77. package/build/package.json +0 -344
  78. package/build/packageDetect.d.ts +0 -1
  79. package/build/packageDetect.js +0 -4
  80. package/build/packageInfo.d.ts +0 -6
  81. package/build/packageInfo.js +0 -1
  82. package/build/types.d.ts +0 -85
  83. package/build/types.js +0 -1
  84. package/build/ws/errors.d.ts +0 -1
  85. package/build/ws/errors.js +0 -38
  86. package/build/ws/index.d.ts +0 -121
  87. package/build/ws/index.js +0 -524
  88. package/build-deno/README.md +0 -66
  89. package/build-deno/bizinikiwi-connect/Health.ts +0 -323
  90. package/build-deno/bizinikiwi-connect/index.ts +0 -417
  91. package/build-deno/bizinikiwi-connect/types.ts +0 -14
  92. package/build-deno/bundle.ts +0 -6
  93. package/build-deno/coder/error.ts +0 -64
  94. package/build-deno/coder/index.ts +0 -86
  95. package/build-deno/defaults.ts +0 -8
  96. package/build-deno/http/index.ts +0 -236
  97. package/build-deno/http/types.ts +0 -9
  98. package/build-deno/index.ts +0 -4
  99. package/build-deno/lru.ts +0 -189
  100. package/build-deno/mock/index.ts +0 -257
  101. package/build-deno/mock/mockHttp.ts +0 -33
  102. package/build-deno/mock/mockWs.ts +0 -87
  103. package/build-deno/mock/types.ts +0 -34
  104. package/build-deno/mod.ts +0 -2
  105. package/build-deno/packageDetect.ts +0 -8
  106. package/build-deno/packageInfo.ts +0 -3
  107. package/build-deno/types.ts +0 -99
  108. package/build-deno/ws/errors.ts +0 -38
  109. package/build-deno/ws/index.ts +0 -650
  110. package/build-tsc/bizinikiwi-connect/Health.d.ts +0 -7
  111. package/build-tsc/bizinikiwi-connect/index.d.ts +0 -22
  112. package/build-tsc/bizinikiwi-connect/types.d.ts +0 -12
  113. package/build-tsc/bundle.d.ts +0 -5
  114. package/build-tsc/coder/error.d.ts +0 -29
  115. package/build-tsc/coder/index.d.ts +0 -8
  116. package/build-tsc/defaults.d.ts +0 -5
  117. package/build-tsc/http/index.d.ts +0 -81
  118. package/build-tsc/http/types.d.ts +0 -7
  119. package/build-tsc/index.d.ts +0 -2
  120. package/build-tsc/lru.d.ts +0 -15
  121. package/build-tsc/mock/index.d.ts +0 -35
  122. package/build-tsc/mock/mockHttp.d.ts +0 -9
  123. package/build-tsc/mock/mockWs.d.ts +0 -26
  124. package/build-tsc/mock/types.d.ts +0 -23
  125. package/build-tsc/packageDetect.d.ts +0 -1
  126. package/build-tsc/packageInfo.d.ts +0 -6
  127. package/build-tsc/types.d.ts +0 -85
  128. package/build-tsc/ws/errors.d.ts +0 -1
  129. package/build-tsc/ws/index.d.ts +0 -121
  130. package/build-tsc-cjs/bizinikiwi-connect/Health.js +0 -264
  131. package/build-tsc-cjs/bizinikiwi-connect/index.js +0 -323
  132. package/build-tsc-cjs/bizinikiwi-connect/types.js +0 -2
  133. package/build-tsc-cjs/bundle.js +0 -14
  134. package/build-tsc-cjs/coder/error.js +0 -53
  135. package/build-tsc-cjs/coder/index.js +0 -63
  136. package/build-tsc-cjs/defaults.js +0 -8
  137. package/build-tsc-cjs/http/index.js +0 -196
  138. package/build-tsc-cjs/http/types.js +0 -2
  139. package/build-tsc-cjs/index.js +0 -5
  140. package/build-tsc-cjs/lru.js +0 -150
  141. package/build-tsc-cjs/mock/index.js +0 -196
  142. package/build-tsc-cjs/mock/mockHttp.js +0 -17
  143. package/build-tsc-cjs/mock/mockWs.js +0 -47
  144. package/build-tsc-cjs/mock/types.js +0 -2
  145. package/build-tsc-cjs/packageDetect.js +0 -6
  146. package/build-tsc-cjs/packageInfo.js +0 -4
  147. package/build-tsc-cjs/types.js +0 -2
  148. package/build-tsc-cjs/ws/errors.js +0 -41
  149. package/build-tsc-cjs/ws/index.js +0 -529
  150. package/build-tsc-esm/bizinikiwi-connect/Health.js +0 -259
  151. package/build-tsc-esm/bizinikiwi-connect/index.js +0 -319
  152. package/build-tsc-esm/bizinikiwi-connect/types.js +0 -1
  153. package/build-tsc-esm/bundle.js +0 -5
  154. package/build-tsc-esm/coder/error.js +0 -50
  155. package/build-tsc-esm/coder/index.js +0 -58
  156. package/build-tsc-esm/defaults.js +0 -6
  157. package/build-tsc-esm/http/index.js +0 -191
  158. package/build-tsc-esm/http/types.js +0 -1
  159. package/build-tsc-esm/index.js +0 -2
  160. package/build-tsc-esm/lru.js +0 -146
  161. package/build-tsc-esm/mock/index.js +0 -191
  162. package/build-tsc-esm/mock/mockHttp.js +0 -12
  163. package/build-tsc-esm/mock/mockWs.js +0 -43
  164. package/build-tsc-esm/mock/types.js +0 -1
  165. package/build-tsc-esm/packageDetect.js +0 -4
  166. package/build-tsc-esm/packageInfo.js +0 -1
  167. package/build-tsc-esm/types.js +0 -1
  168. package/build-tsc-esm/ws/errors.js +0 -38
  169. package/build-tsc-esm/ws/index.js +0 -524
  170. package/src/bizinikiwi-connect/Health.ts +0 -325
  171. package/src/bizinikiwi-connect/index.spec.ts +0 -671
  172. package/src/bizinikiwi-connect/index.ts +0 -427
  173. package/src/bizinikiwi-connect/types.ts +0 -16
  174. package/src/bundle.ts +0 -8
  175. package/src/coder/decodeResponse.spec.ts +0 -70
  176. package/src/coder/encodeJson.spec.ts +0 -20
  177. package/src/coder/encodeObject.spec.ts +0 -25
  178. package/src/coder/error.spec.ts +0 -111
  179. package/src/coder/error.ts +0 -66
  180. package/src/coder/index.ts +0 -88
  181. package/src/defaults.ts +0 -10
  182. package/src/http/index.spec.ts +0 -72
  183. package/src/http/index.ts +0 -238
  184. package/src/http/send.spec.ts +0 -61
  185. package/src/http/types.ts +0 -11
  186. package/src/index.ts +0 -6
  187. package/src/lru.spec.ts +0 -74
  188. package/src/lru.ts +0 -197
  189. package/src/mock/index.ts +0 -259
  190. package/src/mock/mockHttp.ts +0 -35
  191. package/src/mock/mockWs.ts +0 -92
  192. package/src/mock/on.spec.ts +0 -43
  193. package/src/mock/send.spec.ts +0 -38
  194. package/src/mock/subscribe.spec.ts +0 -81
  195. package/src/mock/types.ts +0 -36
  196. package/src/mock/unsubscribe.spec.ts +0 -57
  197. package/src/mod.ts +0 -4
  198. package/src/packageDetect.ts +0 -12
  199. package/src/packageInfo.ts +0 -6
  200. package/src/types.ts +0 -101
  201. package/src/ws/connect.spec.ts +0 -167
  202. package/src/ws/errors.ts +0 -41
  203. package/src/ws/index.spec.ts +0 -97
  204. package/src/ws/index.ts +0 -652
  205. package/src/ws/send.spec.ts +0 -126
  206. package/src/ws/state.spec.ts +0 -20
  207. package/src/ws/subscribe.spec.ts +0 -68
  208. package/src/ws/unsubscribe.spec.ts +0 -100
  209. package/tsconfig.build.json +0 -17
  210. package/tsconfig.build.tsbuildinfo +0 -1
  211. package/tsconfig.spec.json +0 -18
  212. package/tsconfig.spec.tsbuildinfo +0 -1
@@ -1,196 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpProvider = void 0;
4
- const tslib_1 = require("tslib");
5
- const util_1 = require("@pezkuwi/util");
6
- const x_fetch_1 = require("@pezkuwi/x-fetch");
7
- const index_js_1 = require("../coder/index.js");
8
- const defaults_js_1 = tslib_1.__importDefault(require("../defaults.js"));
9
- const lru_js_1 = require("../lru.js");
10
- const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
11
- const l = (0, util_1.logger)('api-http');
12
- /**
13
- * # @pezkuwi/rpc-provider
14
- *
15
- * @name HttpProvider
16
- *
17
- * @description The HTTP Provider allows sending requests using HTTP to a HTTP RPC server TCP port. It does not support subscriptions so you won't be able to listen to events such as new blocks or balance changes. It is usually preferable using the [[WsProvider]].
18
- *
19
- * @example
20
- * <BR>
21
- *
22
- * ```javascript
23
- * import Api from '@pezkuwi/api/promise';
24
- * import { HttpProvider } from '@pezkuwi/rpc-provider';
25
- *
26
- * const provider = new HttpProvider('http://127.0.0.1:9933');
27
- * const api = new Api(provider);
28
- * ```
29
- *
30
- * @see [[WsProvider]]
31
- */
32
- class HttpProvider {
33
- #callCache;
34
- #cacheCapacity;
35
- #coder;
36
- #endpoint;
37
- #headers;
38
- #stats;
39
- #ttl;
40
- /**
41
- * @param {string} endpoint The endpoint url starting with http://
42
- * @param {Record<string, string>} headers The headers provided to the underlying Http Endpoint
43
- * @param {number} [cacheCapacity] Custom size of the HttpProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
44
- * @param {number} [cacheTtl] Custom TTL of the HttpProvider LRUCache. Determines how long an object can live in the cache. Defaults to `DEFAULT_TTL` (30000)
45
- */
46
- constructor(endpoint = defaults_js_1.default.HTTP_URL, headers = {}, cacheCapacity, cacheTtl) {
47
- if (!/^(https|http):\/\//.test(endpoint)) {
48
- throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
49
- }
50
- this.#coder = new index_js_1.RpcCoder();
51
- this.#endpoint = endpoint;
52
- this.#headers = headers;
53
- this.#cacheCapacity = cacheCapacity === 0 ? 0 : cacheCapacity || lru_js_1.DEFAULT_CAPACITY;
54
- const ttl = cacheTtl === undefined ? lru_js_1.DEFAULT_TTL : cacheTtl;
55
- this.#callCache = new lru_js_1.LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || lru_js_1.DEFAULT_CAPACITY, ttl);
56
- this.#ttl = cacheTtl;
57
- this.#stats = {
58
- active: { requests: 0, subscriptions: 0 },
59
- total: { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 }
60
- };
61
- }
62
- /**
63
- * @summary `true` when this provider supports subscriptions
64
- */
65
- get hasSubscriptions() {
66
- return !!false;
67
- }
68
- /**
69
- * @description Returns a clone of the object
70
- */
71
- clone() {
72
- return new HttpProvider(this.#endpoint, this.#headers);
73
- }
74
- /**
75
- * @description Manually connect from the connection
76
- */
77
- async connect() {
78
- // noop
79
- }
80
- /**
81
- * @description Manually disconnect from the connection
82
- */
83
- async disconnect() {
84
- // noop
85
- }
86
- /**
87
- * @description Returns the connection stats
88
- */
89
- get stats() {
90
- return this.#stats;
91
- }
92
- /**
93
- * @description Returns the connection stats
94
- */
95
- get ttl() {
96
- return this.#ttl;
97
- }
98
- /**
99
- * @summary `true` when this provider supports clone()
100
- */
101
- get isClonable() {
102
- return !!true;
103
- }
104
- /**
105
- * @summary Whether the node is connected or not.
106
- * @return {boolean} true if connected
107
- */
108
- get isConnected() {
109
- return !!true;
110
- }
111
- /**
112
- * @summary Events are not supported with the HttpProvider, see [[WsProvider]].
113
- * @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
114
- */
115
- on(_type, _sub) {
116
- l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
117
- return util_1.noop;
118
- }
119
- /**
120
- * @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
121
- */
122
- async send(method, params, isCacheable) {
123
- this.#stats.total.requests++;
124
- const [, body] = this.#coder.encodeJson(method, params);
125
- if (this.#cacheCapacity === 0) {
126
- return this.#send(body);
127
- }
128
- const cacheKey = isCacheable ? `${method}::${(0, util_1.stringify)(params)}` : '';
129
- let resultPromise = isCacheable
130
- ? this.#callCache.get(cacheKey)
131
- : null;
132
- if (!resultPromise) {
133
- resultPromise = this.#send(body);
134
- if (isCacheable) {
135
- this.#callCache.set(cacheKey, resultPromise);
136
- }
137
- }
138
- else {
139
- this.#stats.total.cached++;
140
- }
141
- return resultPromise;
142
- }
143
- async #send(body) {
144
- this.#stats.active.requests++;
145
- this.#stats.total.bytesSent += body.length;
146
- try {
147
- const response = await (0, x_fetch_1.fetch)(this.#endpoint, {
148
- body,
149
- headers: {
150
- Accept: 'application/json',
151
- 'Content-Length': `${body.length}`,
152
- 'Content-Type': 'application/json',
153
- ...this.#headers
154
- },
155
- method: 'POST'
156
- });
157
- if (!response.ok) {
158
- throw new Error(`[${response.status}]: ${response.statusText}`);
159
- }
160
- const result = await response.text();
161
- this.#stats.total.bytesRecv += result.length;
162
- const decoded = this.#coder.decodeResponse(JSON.parse(result));
163
- this.#stats.active.requests--;
164
- return decoded;
165
- }
166
- catch (e) {
167
- this.#stats.active.requests--;
168
- this.#stats.total.errors++;
169
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
170
- const { method, params } = JSON.parse(body);
171
- const rpcError = e;
172
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
173
- const failedRequest = `\nFailed HTTP Request: ${JSON.stringify({ method, params })}`;
174
- // Provide HTTP Request alongside the error
175
- rpcError.message = `${rpcError.message}${failedRequest}`;
176
- throw rpcError;
177
- }
178
- }
179
- /**
180
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
181
- */
182
- // eslint-disable-next-line @typescript-eslint/require-await
183
- async subscribe(_types, _method, _params, _cb) {
184
- l.error(ERROR_SUBSCRIBE);
185
- throw new Error(ERROR_SUBSCRIBE);
186
- }
187
- /**
188
- * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
189
- */
190
- // eslint-disable-next-line @typescript-eslint/require-await
191
- async unsubscribe(_type, _method, _id) {
192
- l.error(ERROR_SUBSCRIBE);
193
- throw new Error(ERROR_SUBSCRIBE);
194
- }
195
- }
196
- exports.HttpProvider = HttpProvider;
@@ -1,7 +0,0 @@
1
- import type { Logger } from '@pezkuwi/util/types';
2
- import type { RpcCoder } from '../coder/index.js';
3
- export interface HttpState {
4
- coder: RpcCoder;
5
- endpoint: string;
6
- l: Logger;
7
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- import './packageDetect.js';
2
- export * from './bundle.js';
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- require("./packageDetect.js");
5
- tslib_1.__exportStar(require("./bundle.js"), exports);
@@ -1,15 +0,0 @@
1
- export declare const DEFAULT_CAPACITY = 1024;
2
- export declare const DEFAULT_TTL = 30000;
3
- export declare class LRUCache {
4
- #private;
5
- readonly capacity: number;
6
- constructor(capacity?: number, ttl?: number | null);
7
- get ttl(): number | null;
8
- get length(): number;
9
- get lengthData(): number;
10
- get lengthRefs(): number;
11
- entries(): [string, unknown][];
12
- keys(): string[];
13
- get<T>(key: string): T | null;
14
- set<T>(key: string, value: T): void;
15
- }
package/build/cjs/lru.js DELETED
@@ -1,150 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LRUCache = exports.DEFAULT_TTL = exports.DEFAULT_CAPACITY = void 0;
4
- exports.DEFAULT_CAPACITY = 1024;
5
- exports.DEFAULT_TTL = 30000; // 30 seconds
6
- const MAX_TTL = 1800_000; // 30 minutes
7
- const DISABLED_TTL = 31_536_000_000;
8
- class LRUNode {
9
- key;
10
- #expires;
11
- #ttl;
12
- createdAt;
13
- next;
14
- prev;
15
- constructor(key, ttl) {
16
- this.key = key;
17
- this.#ttl = ttl;
18
- this.#expires = Date.now() + ttl;
19
- this.createdAt = Date.now();
20
- this.next = this.prev = this;
21
- }
22
- refresh() {
23
- this.#expires = Date.now() + this.#ttl;
24
- }
25
- get expiry() {
26
- return this.#expires;
27
- }
28
- }
29
- class LRUCache {
30
- capacity;
31
- #data = new Map();
32
- #refs = new Map();
33
- #length = 0;
34
- #head;
35
- #tail;
36
- #ttl;
37
- constructor(capacity = exports.DEFAULT_CAPACITY, ttl = exports.DEFAULT_TTL) {
38
- // Validate capacity
39
- if (!Number.isInteger(capacity) || capacity < 0) {
40
- throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`);
41
- }
42
- // Validate ttl
43
- if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) {
44
- throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`);
45
- }
46
- this.capacity = capacity;
47
- ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL;
48
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
49
- }
50
- get ttl() {
51
- return this.#ttl;
52
- }
53
- get length() {
54
- return this.#length;
55
- }
56
- get lengthData() {
57
- return this.#data.size;
58
- }
59
- get lengthRefs() {
60
- return this.#refs.size;
61
- }
62
- entries() {
63
- const keys = this.keys();
64
- const count = keys.length;
65
- const entries = new Array(count);
66
- for (let i = 0; i < count; i++) {
67
- const key = keys[i];
68
- entries[i] = [key, this.#data.get(key)];
69
- }
70
- return entries;
71
- }
72
- keys() {
73
- const keys = [];
74
- if (this.#length) {
75
- let curr = this.#head;
76
- while (curr !== this.#tail) {
77
- keys.push(curr.key);
78
- curr = curr.next;
79
- }
80
- keys.push(curr.key);
81
- }
82
- return keys;
83
- }
84
- get(key) {
85
- const data = this.#data.get(key);
86
- if (data) {
87
- this.#toHead(key);
88
- // Evict TTL once data is refreshed
89
- this.#evictTTL();
90
- return data;
91
- }
92
- this.#evictTTL();
93
- return null;
94
- }
95
- set(key, value) {
96
- if (this.#data.has(key)) {
97
- this.#toHead(key);
98
- }
99
- else {
100
- const node = new LRUNode(key, this.#ttl);
101
- this.#refs.set(node.key, node);
102
- if (this.length === 0) {
103
- this.#head = this.#tail = node;
104
- }
105
- else {
106
- this.#head.prev = node;
107
- node.next = this.#head;
108
- this.#head = node;
109
- }
110
- if (this.#length === this.capacity) {
111
- this.#data.delete(this.#tail.key);
112
- this.#refs.delete(this.#tail.key);
113
- this.#tail = this.#tail.prev;
114
- this.#tail.next = this.#head;
115
- }
116
- else {
117
- this.#length += 1;
118
- }
119
- }
120
- // Evict TTL once data is refreshed or added
121
- this.#evictTTL();
122
- this.#data.set(key, value);
123
- }
124
- #evictTTL() {
125
- // Find last node to keep
126
- // traverse map to find the expired nodes
127
- while (this.#tail.expiry && this.#tail.expiry < Date.now() && this.#length > 0) {
128
- this.#refs.delete(this.#tail.key);
129
- this.#data.delete(this.#tail.key);
130
- this.#length -= 1;
131
- this.#tail = this.#tail.prev;
132
- this.#tail.next = this.#head;
133
- }
134
- if (this.#length === 0) {
135
- this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
136
- }
137
- }
138
- #toHead(key) {
139
- const ref = this.#refs.get(key);
140
- if (ref && ref !== this.#head) {
141
- ref.refresh();
142
- ref.prev.next = ref.next;
143
- ref.next.prev = ref.prev;
144
- ref.next = this.#head;
145
- this.#head.prev = ref;
146
- this.#head = ref;
147
- }
148
- }
149
- }
150
- exports.LRUCache = LRUCache;
@@ -1,35 +0,0 @@
1
- import type { Registry } from '@pezkuwi/types/types';
2
- import type { ProviderInterface, ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '../types.js';
3
- import type { MockStateSubscriptions } from './types.js';
4
- /**
5
- * A mock provider mainly used for testing.
6
- * @return {ProviderInterface} The mock provider
7
- * @internal
8
- */
9
- export declare class MockProvider implements ProviderInterface {
10
- private db;
11
- private emitter;
12
- private intervalId?;
13
- isUpdating: boolean;
14
- private registry;
15
- private prevNumber;
16
- private requests;
17
- subscriptions: MockStateSubscriptions;
18
- private subscriptionId;
19
- private subscriptionMap;
20
- constructor(registry: Registry);
21
- get hasSubscriptions(): boolean;
22
- clone(): MockProvider;
23
- connect(): Promise<void>;
24
- disconnect(): Promise<void>;
25
- get isClonable(): boolean;
26
- get isConnected(): boolean;
27
- on(type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
28
- send<T = any>(method: string, params: unknown[]): Promise<T>;
29
- subscribe(_type: string, method: string, ...params: unknown[]): Promise<number>;
30
- unsubscribe(_type: string, _method: string, id: number): Promise<boolean>;
31
- private init;
32
- private makeBlockHeader;
33
- private setStateBn;
34
- private updateSubs;
35
- }
@@ -1,196 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MockProvider = void 0;
4
- const tslib_1 = require("tslib");
5
- const eventemitter3_1 = require("eventemitter3");
6
- const testing_1 = require("@pezkuwi/keyring/testing");
7
- const types_1 = require("@pezkuwi/types");
8
- const jsonrpc_1 = tslib_1.__importDefault(require("@pezkuwi/types/interfaces/jsonrpc"));
9
- const Header_004_json_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/json/Header.004.json"));
10
- const SignedBlock_004_immortal_json_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/json/SignedBlock.004.immortal.json"));
11
- const static_bizinikiwi_1 = tslib_1.__importDefault(require("@pezkuwi/types-support/metadata/static-bizinikiwi"));
12
- const util_1 = require("@pezkuwi/util");
13
- const util_crypto_1 = require("@pezkuwi/util-crypto");
14
- const INTERVAL = 1000;
15
- const SUBSCRIPTIONS = Array.prototype.concat.apply([], Object.values(jsonrpc_1.default).map((section) => Object
16
- .values(section)
17
- .filter(({ isSubscription }) => isSubscription)
18
- .map(({ jsonrpc }) => jsonrpc)
19
- .concat('chain_subscribeNewHead')));
20
- const keyring = (0, testing_1.createTestKeyring)({ type: 'ed25519' });
21
- const l = (0, util_1.logger)('api-mock');
22
- /**
23
- * A mock provider mainly used for testing.
24
- * @return {ProviderInterface} The mock provider
25
- * @internal
26
- */
27
- class MockProvider {
28
- db = {};
29
- emitter = new eventemitter3_1.EventEmitter();
30
- intervalId;
31
- isUpdating = true;
32
- registry;
33
- prevNumber = new util_1.BN(-1);
34
- requests = {
35
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
36
- chain_getBlock: () => this.registry.createType('SignedBlock', SignedBlock_004_immortal_json_1.default.result).toJSON(),
37
- chain_getBlockHash: () => '0x1234000000000000000000000000000000000000000000000000000000000000',
38
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
39
- chain_getFinalizedHead: () => this.registry.createType('Header', Header_004_json_1.default.result).hash,
40
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
41
- chain_getHeader: () => this.registry.createType('Header', Header_004_json_1.default.result).toJSON(),
42
- rpc_methods: () => this.registry.createType('RpcMethods').toJSON(),
43
- state_getKeys: () => [],
44
- state_getKeysPaged: () => [],
45
- state_getMetadata: () => static_bizinikiwi_1.default,
46
- state_getRuntimeVersion: () => this.registry.createType('RuntimeVersion').toHex(),
47
- state_getStorage: (storage, [key]) => (0, util_1.u8aToHex)(storage[key]),
48
- system_chain: () => 'mockChain',
49
- system_health: () => ({}),
50
- system_name: () => 'mockClient',
51
- system_properties: () => ({ ss58Format: 42 }),
52
- system_upgradedToTripleRefCount: () => this.registry.createType('bool', true),
53
- system_version: () => '9.8.7',
54
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return, sort-keys
55
- dev_echo: (_, params) => params
56
- };
57
- subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
58
- subs[name] = {
59
- callbacks: {},
60
- lastValue: null
61
- };
62
- return subs;
63
- }, {});
64
- subscriptionId = 0;
65
- subscriptionMap = {};
66
- constructor(registry) {
67
- this.registry = registry;
68
- this.init();
69
- }
70
- get hasSubscriptions() {
71
- return !!true;
72
- }
73
- clone() {
74
- throw new Error('Unimplemented');
75
- }
76
- async connect() {
77
- // noop
78
- }
79
- // eslint-disable-next-line @typescript-eslint/require-await
80
- async disconnect() {
81
- if (this.intervalId) {
82
- clearInterval(this.intervalId);
83
- this.intervalId = null;
84
- }
85
- }
86
- get isClonable() {
87
- return !!false;
88
- }
89
- get isConnected() {
90
- return !!true;
91
- }
92
- on(type, sub) {
93
- this.emitter.on(type, sub);
94
- return () => {
95
- this.emitter.removeListener(type, sub);
96
- };
97
- }
98
- // eslint-disable-next-line @typescript-eslint/require-await
99
- async send(method, params) {
100
- l.debug(() => ['send', method, params]);
101
- if (!this.requests[method]) {
102
- throw new Error(`provider.send: Invalid method '${method}'`);
103
- }
104
- return this.requests[method](this.db, params);
105
- }
106
- // eslint-disable-next-line @typescript-eslint/require-await
107
- async subscribe(_type, method, ...params) {
108
- l.debug(() => ['subscribe', method, params]);
109
- if (!this.subscriptions[method]) {
110
- throw new Error(`provider.subscribe: Invalid method '${method}'`);
111
- }
112
- const callback = params.pop();
113
- const id = ++this.subscriptionId;
114
- this.subscriptions[method].callbacks[id] = callback;
115
- this.subscriptionMap[id] = method;
116
- if (this.subscriptions[method].lastValue !== null) {
117
- callback(null, this.subscriptions[method].lastValue);
118
- }
119
- return id;
120
- }
121
- // eslint-disable-next-line @typescript-eslint/require-await
122
- async unsubscribe(_type, _method, id) {
123
- const sub = this.subscriptionMap[id];
124
- l.debug(() => ['unsubscribe', id, sub]);
125
- if (!sub) {
126
- throw new Error(`Unable to find subscription for ${id}`);
127
- }
128
- delete this.subscriptionMap[id];
129
- delete this.subscriptions[sub].callbacks[id];
130
- return true;
131
- }
132
- init() {
133
- const emitEvents = ['connected', 'disconnected'];
134
- let emitIndex = 0;
135
- let newHead = this.makeBlockHeader();
136
- let counter = -1;
137
- const metadata = new types_1.Metadata(this.registry, static_bizinikiwi_1.default);
138
- this.registry.setMetadata(metadata);
139
- const query = (0, types_1.decorateStorage)(this.registry, metadata.asLatest, metadata.version);
140
- // Do something every 1 seconds
141
- this.intervalId = setInterval(() => {
142
- if (!this.isUpdating) {
143
- return;
144
- }
145
- // create a new header (next block)
146
- newHead = this.makeBlockHeader();
147
- // increment the balances and nonce for each account
148
- keyring.getPairs().forEach(({ publicKey }, index) => {
149
- this.setStateBn(query['system']['account'](publicKey), newHead.number.toBn().addn(index));
150
- });
151
- // set the timestamp for the current block
152
- this.setStateBn(query['timestamp']['now'](), Math.floor(Date.now() / 1000));
153
- this.updateSubs('chain_subscribeNewHead', newHead);
154
- // We emit connected/disconnected at intervals
155
- if (++counter % 2 === 1) {
156
- if (++emitIndex === emitEvents.length) {
157
- emitIndex = 0;
158
- }
159
- this.emitter.emit(emitEvents[emitIndex]);
160
- }
161
- }, INTERVAL);
162
- }
163
- makeBlockHeader() {
164
- const blockNumber = this.prevNumber.addn(1);
165
- const header = this.registry.createType('Header', {
166
- digest: {
167
- logs: []
168
- },
169
- extrinsicsRoot: (0, util_crypto_1.randomAsU8a)(),
170
- number: blockNumber,
171
- parentHash: blockNumber.isZero()
172
- ? new Uint8Array(32)
173
- : (0, util_1.bnToU8a)(this.prevNumber, { bitLength: 256, isLe: false }),
174
- stateRoot: (0, util_1.bnToU8a)(blockNumber, { bitLength: 256, isLe: false })
175
- });
176
- this.prevNumber = blockNumber;
177
- return header;
178
- }
179
- setStateBn(key, value) {
180
- this.db[(0, util_1.u8aToHex)(key)] = (0, util_1.bnToU8a)(value, { bitLength: 64, isLe: true });
181
- }
182
- updateSubs(method, value) {
183
- this.subscriptions[method].lastValue = value;
184
- Object
185
- .values(this.subscriptions[method].callbacks)
186
- .forEach((cb) => {
187
- try {
188
- cb(null, value.toJSON());
189
- }
190
- catch (error) {
191
- l.error(`Error on '${method}' subscription`, error);
192
- }
193
- });
194
- }
195
- }
196
- exports.MockProvider = MockProvider;
@@ -1,9 +0,0 @@
1
- import type { Mock } from './types.js';
2
- interface Request {
3
- code?: number;
4
- method: string;
5
- reply?: Record<string, unknown>;
6
- }
7
- export declare const TEST_HTTP_URL = "http://localhost:9944";
8
- export declare function mockHttp(requests: Request[]): Mock;
9
- export {};
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TEST_HTTP_URL = void 0;
4
- exports.mockHttp = mockHttp;
5
- const tslib_1 = require("tslib");
6
- const nock_1 = tslib_1.__importDefault(require("nock"));
7
- exports.TEST_HTTP_URL = 'http://localhost:9944';
8
- function mockHttp(requests) {
9
- nock_1.default.cleanAll();
10
- return requests.reduce((scope, request) => scope
11
- .post('/')
12
- .reply(request.code || 200, (_uri, body) => {
13
- scope.body = scope.body || {};
14
- scope.body[request.method] = body;
15
- return Object.assign({ id: body.id, jsonrpc: '2.0' }, request.reply || {});
16
- }), (0, nock_1.default)(exports.TEST_HTTP_URL));
17
- }
@@ -1,26 +0,0 @@
1
- import { Server } from 'mock-socket';
2
- interface Scope {
3
- body: Record<string, Record<string, unknown>>;
4
- requests: number;
5
- server: Server;
6
- done: any;
7
- }
8
- interface ErrorDef {
9
- id: number;
10
- error: {
11
- code: number;
12
- message: string;
13
- };
14
- }
15
- interface ReplyDef {
16
- id: number;
17
- reply: {
18
- result: unknown;
19
- };
20
- }
21
- export type Request = {
22
- method: string;
23
- } & (ErrorDef | ReplyDef);
24
- export declare const TEST_WS_URL = "ws://localhost:9955";
25
- export declare function mockWs(requests: Request[], wsUrl?: string): Scope;
26
- export {};