@pezkuwi/rpc-provider 16.5.20 → 16.5.21

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 (210) hide show
  1. package/package.json +9 -9
  2. package/build/LICENSE +0 -201
  3. package/build/README.md +0 -68
  4. package/build/bizinikiwi-connect/Health.js +0 -259
  5. package/build/bizinikiwi-connect/index.js +0 -319
  6. package/build/bizinikiwi-connect/types.js +0 -1
  7. package/build/bundle.js +0 -5
  8. package/build/cjs/bizinikiwi-connect/Health.d.ts +0 -7
  9. package/build/cjs/bizinikiwi-connect/Health.js +0 -264
  10. package/build/cjs/bizinikiwi-connect/index.d.ts +0 -22
  11. package/build/cjs/bizinikiwi-connect/index.js +0 -323
  12. package/build/cjs/bizinikiwi-connect/types.d.ts +0 -12
  13. package/build/cjs/bizinikiwi-connect/types.js +0 -2
  14. package/build/cjs/bundle.d.ts +0 -5
  15. package/build/cjs/bundle.js +0 -14
  16. package/build/cjs/coder/error.js +0 -53
  17. package/build/cjs/coder/index.js +0 -63
  18. package/build/cjs/defaults.js +0 -8
  19. package/build/cjs/http/index.js +0 -196
  20. package/build/cjs/http/types.js +0 -2
  21. package/build/cjs/index.js +0 -5
  22. package/build/cjs/lru.js +0 -150
  23. package/build/cjs/mock/index.js +0 -196
  24. package/build/cjs/mock/mockHttp.js +0 -17
  25. package/build/cjs/mock/mockWs.js +0 -47
  26. package/build/cjs/mock/types.js +0 -2
  27. package/build/cjs/packageInfo.js +0 -4
  28. package/build/cjs/types.js +0 -2
  29. package/build/cjs/ws/errors.js +0 -41
  30. package/build/cjs/ws/index.js +0 -529
  31. package/build/coder/error.d.ts +0 -29
  32. package/build/coder/error.js +0 -50
  33. package/build/coder/index.d.ts +0 -8
  34. package/build/coder/index.js +0 -58
  35. package/build/defaults.d.ts +0 -5
  36. package/build/defaults.js +0 -6
  37. package/build/http/index.d.ts +0 -81
  38. package/build/http/index.js +0 -191
  39. package/build/http/types.d.ts +0 -7
  40. package/build/http/types.js +0 -1
  41. package/build/index.d.ts +0 -2
  42. package/build/index.js +0 -2
  43. package/build/lru.d.ts +0 -15
  44. package/build/lru.js +0 -146
  45. package/build/mock/index.d.ts +0 -35
  46. package/build/mock/index.js +0 -191
  47. package/build/mock/mockHttp.d.ts +0 -9
  48. package/build/mock/mockHttp.js +0 -12
  49. package/build/mock/mockWs.d.ts +0 -26
  50. package/build/mock/mockWs.js +0 -43
  51. package/build/mock/types.d.ts +0 -23
  52. package/build/mock/types.js +0 -1
  53. package/build/package.json +0 -344
  54. package/build/packageDetect.d.ts +0 -1
  55. package/build/packageDetect.js +0 -4
  56. package/build/packageInfo.d.ts +0 -6
  57. package/build/packageInfo.js +0 -1
  58. package/build/types.d.ts +0 -85
  59. package/build/types.js +0 -1
  60. package/build/ws/errors.d.ts +0 -1
  61. package/build/ws/errors.js +0 -38
  62. package/build/ws/index.d.ts +0 -121
  63. package/build/ws/index.js +0 -524
  64. package/build-deno/README.md +0 -66
  65. package/build-deno/bizinikiwi-connect/Health.ts +0 -323
  66. package/build-deno/bizinikiwi-connect/index.ts +0 -417
  67. package/build-deno/bizinikiwi-connect/types.ts +0 -14
  68. package/build-deno/bundle.ts +0 -6
  69. package/build-deno/coder/error.ts +0 -64
  70. package/build-deno/coder/index.ts +0 -86
  71. package/build-deno/defaults.ts +0 -8
  72. package/build-deno/http/index.ts +0 -236
  73. package/build-deno/http/types.ts +0 -9
  74. package/build-deno/index.ts +0 -4
  75. package/build-deno/lru.ts +0 -189
  76. package/build-deno/mock/index.ts +0 -257
  77. package/build-deno/mock/mockHttp.ts +0 -33
  78. package/build-deno/mock/mockWs.ts +0 -87
  79. package/build-deno/mock/types.ts +0 -34
  80. package/build-deno/mod.ts +0 -2
  81. package/build-deno/packageDetect.ts +0 -8
  82. package/build-deno/packageInfo.ts +0 -3
  83. package/build-deno/types.ts +0 -99
  84. package/build-deno/ws/errors.ts +0 -38
  85. package/build-deno/ws/index.ts +0 -650
  86. package/build-tsc-cjs/packageDetect.js +0 -6
  87. package/src/bizinikiwi-connect/Health.ts +0 -325
  88. package/src/bizinikiwi-connect/index.spec.ts +0 -675
  89. package/src/bizinikiwi-connect/index.ts +0 -427
  90. package/src/bizinikiwi-connect/types.ts +0 -16
  91. package/src/bundle.ts +0 -8
  92. package/src/coder/decodeResponse.spec.ts +0 -70
  93. package/src/coder/encodeJson.spec.ts +0 -20
  94. package/src/coder/encodeObject.spec.ts +0 -25
  95. package/src/coder/error.spec.ts +0 -111
  96. package/src/coder/error.ts +0 -66
  97. package/src/coder/index.ts +0 -88
  98. package/src/defaults.ts +0 -10
  99. package/src/http/index.spec.ts +0 -72
  100. package/src/http/index.ts +0 -238
  101. package/src/http/send.spec.ts +0 -61
  102. package/src/http/types.ts +0 -11
  103. package/src/index.ts +0 -6
  104. package/src/lru.spec.ts +0 -74
  105. package/src/lru.ts +0 -197
  106. package/src/mock/index.ts +0 -259
  107. package/src/mock/mockHttp.ts +0 -35
  108. package/src/mock/mockWs.ts +0 -92
  109. package/src/mock/on.spec.ts +0 -43
  110. package/src/mock/send.spec.ts +0 -38
  111. package/src/mock/subscribe.spec.ts +0 -81
  112. package/src/mock/types.ts +0 -36
  113. package/src/mock/unsubscribe.spec.ts +0 -57
  114. package/src/mod.ts +0 -4
  115. package/src/packageDetect.ts +0 -12
  116. package/src/packageInfo.ts +0 -6
  117. package/src/types.ts +0 -101
  118. package/src/ws/connect.spec.ts +0 -167
  119. package/src/ws/errors.ts +0 -41
  120. package/src/ws/index.spec.ts +0 -97
  121. package/src/ws/index.ts +0 -652
  122. package/src/ws/send.spec.ts +0 -126
  123. package/src/ws/state.spec.ts +0 -20
  124. package/src/ws/subscribe.spec.ts +0 -68
  125. package/src/ws/unsubscribe.spec.ts +0 -100
  126. package/tsconfig.build.json +0 -17
  127. package/tsconfig.build.tsbuildinfo +0 -1
  128. package/tsconfig.spec.json +0 -18
  129. package/tsconfig.spec.tsbuildinfo +0 -1
  130. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/Health.d.ts +0 -0
  131. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/Health.js +0 -0
  132. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/index.d.ts +0 -0
  133. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/index.js +0 -0
  134. /package/{build-tsc/bizinikiwi-connect → bizinikiwi-connect}/types.d.ts +0 -0
  135. /package/{build-tsc-esm/bizinikiwi-connect → bizinikiwi-connect}/types.js +0 -0
  136. /package/{build-tsc/bundle.d.ts → bundle.d.ts} +0 -0
  137. /package/{build-tsc-esm/bundle.js → bundle.js} +0 -0
  138. /package/{build → cjs}/bizinikiwi-connect/Health.d.ts +0 -0
  139. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/Health.js +0 -0
  140. /package/{build → cjs}/bizinikiwi-connect/index.d.ts +0 -0
  141. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/index.js +0 -0
  142. /package/{build → cjs}/bizinikiwi-connect/types.d.ts +0 -0
  143. /package/{build-tsc-cjs → cjs}/bizinikiwi-connect/types.js +0 -0
  144. /package/{build → cjs}/bundle.d.ts +0 -0
  145. /package/{build-tsc-cjs → cjs}/bundle.js +0 -0
  146. /package/{build-tsc → cjs}/coder/error.d.ts +0 -0
  147. /package/{build-tsc-cjs → cjs}/coder/error.js +0 -0
  148. /package/{build-tsc → cjs}/coder/index.d.ts +0 -0
  149. /package/{build-tsc-cjs → cjs}/coder/index.js +0 -0
  150. /package/{build-tsc → cjs}/defaults.d.ts +0 -0
  151. /package/{build-tsc-cjs → cjs}/defaults.js +0 -0
  152. /package/{build-tsc → cjs}/http/index.d.ts +0 -0
  153. /package/{build-tsc-cjs → cjs}/http/index.js +0 -0
  154. /package/{build-tsc → cjs}/http/types.d.ts +0 -0
  155. /package/{build-tsc-cjs → cjs}/http/types.js +0 -0
  156. /package/{build-tsc → cjs}/index.d.ts +0 -0
  157. /package/{build-tsc-cjs → cjs}/index.js +0 -0
  158. /package/{build-tsc → cjs}/lru.d.ts +0 -0
  159. /package/{build-tsc-cjs → cjs}/lru.js +0 -0
  160. /package/{build-tsc → cjs}/mock/index.d.ts +0 -0
  161. /package/{build-tsc-cjs → cjs}/mock/index.js +0 -0
  162. /package/{build-tsc → cjs}/mock/mockHttp.d.ts +0 -0
  163. /package/{build-tsc-cjs → cjs}/mock/mockHttp.js +0 -0
  164. /package/{build-tsc → cjs}/mock/mockWs.d.ts +0 -0
  165. /package/{build-tsc-cjs → cjs}/mock/mockWs.js +0 -0
  166. /package/{build-tsc → cjs}/mock/types.d.ts +0 -0
  167. /package/{build-tsc-cjs → cjs}/mock/types.js +0 -0
  168. /package/{build/cjs → cjs}/package.json +0 -0
  169. /package/{build-tsc → cjs}/packageDetect.d.ts +0 -0
  170. /package/{build/cjs → cjs}/packageDetect.js +0 -0
  171. /package/{build-tsc → cjs}/packageInfo.d.ts +0 -0
  172. /package/{build-tsc-cjs → cjs}/packageInfo.js +0 -0
  173. /package/{build-tsc → cjs}/types.d.ts +0 -0
  174. /package/{build-tsc-cjs → cjs}/types.js +0 -0
  175. /package/{build-tsc → cjs}/ws/errors.d.ts +0 -0
  176. /package/{build-tsc-cjs → cjs}/ws/errors.js +0 -0
  177. /package/{build-tsc → cjs}/ws/index.d.ts +0 -0
  178. /package/{build-tsc-cjs → cjs}/ws/index.js +0 -0
  179. /package/{build/cjs/coder → coder}/error.d.ts +0 -0
  180. /package/{build-tsc-esm/coder → coder}/error.js +0 -0
  181. /package/{build/cjs/coder → coder}/index.d.ts +0 -0
  182. /package/{build-tsc-esm/coder → coder}/index.js +0 -0
  183. /package/{build/cjs/defaults.d.ts → defaults.d.ts} +0 -0
  184. /package/{build-tsc-esm/defaults.js → defaults.js} +0 -0
  185. /package/{build/cjs/http → http}/index.d.ts +0 -0
  186. /package/{build-tsc-esm/http → http}/index.js +0 -0
  187. /package/{build/cjs/http → http}/types.d.ts +0 -0
  188. /package/{build-tsc-esm/http → http}/types.js +0 -0
  189. /package/{build/cjs/index.d.ts → index.d.ts} +0 -0
  190. /package/{build-tsc-esm/index.js → index.js} +0 -0
  191. /package/{build/cjs/lru.d.ts → lru.d.ts} +0 -0
  192. /package/{build-tsc-esm/lru.js → lru.js} +0 -0
  193. /package/{build/cjs/mock → mock}/index.d.ts +0 -0
  194. /package/{build-tsc-esm/mock → mock}/index.js +0 -0
  195. /package/{build/cjs/mock → mock}/mockHttp.d.ts +0 -0
  196. /package/{build-tsc-esm/mock → mock}/mockHttp.js +0 -0
  197. /package/{build/cjs/mock → mock}/mockWs.d.ts +0 -0
  198. /package/{build-tsc-esm/mock → mock}/mockWs.js +0 -0
  199. /package/{build/cjs/mock → mock}/types.d.ts +0 -0
  200. /package/{build-tsc-esm/mock → mock}/types.js +0 -0
  201. /package/{build/cjs/packageDetect.d.ts → packageDetect.d.ts} +0 -0
  202. /package/{build-tsc-esm/packageDetect.js → packageDetect.js} +0 -0
  203. /package/{build/cjs/packageInfo.d.ts → packageInfo.d.ts} +0 -0
  204. /package/{build-tsc-esm/packageInfo.js → packageInfo.js} +0 -0
  205. /package/{build/cjs/types.d.ts → types.d.ts} +0 -0
  206. /package/{build-tsc-esm/types.js → types.js} +0 -0
  207. /package/{build/cjs/ws → ws}/errors.d.ts +0 -0
  208. /package/{build-tsc-esm/ws → ws}/errors.js +0 -0
  209. /package/{build/cjs/ws → ws}/index.d.ts +0 -0
  210. /package/{build-tsc-esm/ws → ws}/index.js +0 -0
@@ -1,323 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ScProvider = void 0;
4
- const eventemitter3_1 = require("eventemitter3");
5
- const util_1 = require("@pezkuwi/util");
6
- const index_js_1 = require("../coder/index.js");
7
- const Health_js_1 = require("./Health.js");
8
- const l = (0, util_1.logger)('api-bizinikiwi-connect');
9
- const subscriptionUnsubscriptionMethods = new Map([
10
- ['author_submitAndWatchExtrinsic', 'author_unwatchExtrinsic'],
11
- ['chain_subscribeAllHeads', 'chain_unsubscribeAllHeads'],
12
- ['chain_subscribeFinalizedHeads', 'chain_unsubscribeFinalizedHeads'],
13
- ['chain_subscribeFinalisedHeads', 'chain_subscribeFinalisedHeads'],
14
- ['chain_subscribeNewHeads', 'chain_unsubscribeNewHeads'],
15
- ['chain_subscribeNewHead', 'chain_unsubscribeNewHead'],
16
- ['chain_subscribeRuntimeVersion', 'chain_unsubscribeRuntimeVersion'],
17
- ['subscribe_newHead', 'unsubscribe_newHead'],
18
- ['state_subscribeRuntimeVersion', 'state_unsubscribeRuntimeVersion'],
19
- ['state_subscribeStorage', 'state_unsubscribeStorage']
20
- ]);
21
- const scClients = new WeakMap();
22
- class ScProvider {
23
- #Sc;
24
- #coder = new index_js_1.RpcCoder();
25
- #spec;
26
- #sharedSandbox;
27
- #subscriptions = new Map();
28
- #resubscribeMethods = new Map();
29
- #requests = new Map();
30
- #wellKnownChains;
31
- #eventemitter = new eventemitter3_1.EventEmitter();
32
- #chain = null;
33
- #isChainReady = false;
34
- constructor(Sc, spec, sharedSandbox) {
35
- if (!(0, util_1.isObject)(Sc) || !(0, util_1.isObject)(Sc.WellKnownChain) || !(0, util_1.isFunction)(Sc.createScClient)) {
36
- throw new Error('Expected an @bizinikiwi/connect interface as first parameter to ScProvider');
37
- }
38
- this.#Sc = Sc;
39
- this.#spec = spec;
40
- this.#sharedSandbox = sharedSandbox;
41
- this.#wellKnownChains = new Set(Object.values(Sc.WellKnownChain));
42
- }
43
- get hasSubscriptions() {
44
- // Indicates that subscriptions are supported
45
- return !!true;
46
- }
47
- get isClonable() {
48
- return !!false;
49
- }
50
- get isConnected() {
51
- return !!this.#chain && this.#isChainReady;
52
- }
53
- clone() {
54
- throw new Error('clone() is not supported.');
55
- }
56
- // Config details can be found in @bizinikiwi/connect repo following the link:
57
- // https://github.com/pezkuwichain/bizinikiwi-connect/blob/main/packages/connect/src/connector/index.ts
58
- async connect(config, checkerFactory = Health_js_1.healthChecker) {
59
- if (this.isConnected) {
60
- throw new Error('Already connected!');
61
- }
62
- // it could happen that after emitting `disconnected` due to the fact that
63
- // smoldot is syncing, the consumer tries to reconnect after a certain amount
64
- // of time... In which case we want to make sure that we don't create a new
65
- // chain.
66
- if (this.#chain) {
67
- await this.#chain;
68
- return;
69
- }
70
- if (this.#sharedSandbox && !this.#sharedSandbox.isConnected) {
71
- await this.#sharedSandbox.connect();
72
- }
73
- const client = this.#sharedSandbox
74
- ? scClients.get(this.#sharedSandbox)
75
- : this.#Sc.createScClient(config);
76
- if (!client) {
77
- throw new Error('Unknown ScProvider!');
78
- }
79
- scClients.set(this, client);
80
- const hc = checkerFactory();
81
- const onResponse = (res) => {
82
- const hcRes = hc.responsePassThrough(res);
83
- if (!hcRes) {
84
- return;
85
- }
86
- const response = JSON.parse(hcRes);
87
- let decodedResponse;
88
- try {
89
- decodedResponse = this.#coder.decodeResponse(response);
90
- }
91
- catch (e) {
92
- decodedResponse = e;
93
- }
94
- // It's not a subscription message, but rather a standar RPC response
95
- if (response.params?.subscription === undefined || !response.method) {
96
- return this.#requests.get(response.id)?.(decodedResponse);
97
- }
98
- // We are dealing with a subscription message
99
- const subscriptionId = `${response.method}::${response.params.subscription}`;
100
- const callback = this.#subscriptions.get(subscriptionId)?.[0];
101
- callback?.(decodedResponse);
102
- };
103
- const addChain = this.#sharedSandbox
104
- ? (async (...args) => {
105
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
106
- const source = this.#sharedSandbox;
107
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
108
- return (await source.#chain).addChain(...args);
109
- })
110
- : this.#wellKnownChains.has(this.#spec)
111
- ? client.addWellKnownChain
112
- : client.addChain;
113
- this.#chain = addChain(this.#spec).then((chain) => {
114
- hc.setSendJsonRpc(chain.sendJsonRpc);
115
- // Start async response processing loop
116
- // This replaces the callback-based API from older @substrate/connect versions
117
- (async () => {
118
- try {
119
- for await (const res of chain.jsonRpcResponses) {
120
- onResponse(res);
121
- }
122
- }
123
- catch {
124
- // Chain was removed or connection closed - this is expected
125
- }
126
- })();
127
- this.#isChainReady = false;
128
- const cleanup = () => {
129
- // If there are any callbacks left, we have to reject/error them.
130
- // Otherwise, that would cause a memory leak.
131
- const disconnectionError = new Error('Disconnected');
132
- this.#requests.forEach((cb) => cb(disconnectionError));
133
- this.#subscriptions.forEach(([cb]) => cb(disconnectionError));
134
- this.#subscriptions.clear();
135
- };
136
- const staleSubscriptions = [];
137
- const killStaleSubscriptions = () => {
138
- if (staleSubscriptions.length === 0) {
139
- return;
140
- }
141
- const stale = staleSubscriptions.pop();
142
- if (!stale) {
143
- throw new Error('Unable to get stale subscription');
144
- }
145
- const { id, unsubscribeMethod } = stale;
146
- Promise
147
- .race([
148
- this.send(unsubscribeMethod, [id]).catch(util_1.noop),
149
- new Promise((resolve) => setTimeout(resolve, 500))
150
- ])
151
- .then(killStaleSubscriptions)
152
- .catch(util_1.noop);
153
- };
154
- hc.start((health) => {
155
- const isReady = !health.isSyncing && (health.peers > 0 || !health.shouldHavePeers);
156
- // if it's the same as before, then nothing has changed and we are done
157
- if (this.#isChainReady === isReady) {
158
- return;
159
- }
160
- this.#isChainReady = isReady;
161
- if (!isReady) {
162
- // If we've reached this point, that means that the chain used to be "ready"
163
- // and now we are about to emit `disconnected`.
164
- //
165
- // This will cause the PezkuwiJs API think that the connection is
166
- // actually dead. In reality the smoldot chain is not dead, of course.
167
- // However, we have to cleanup all the existing callbacks because when
168
- // the smoldot chain stops syncing, then we will emit `connected` and
169
- // the PezkuwiJs API will try to re-create the previous
170
- // subscriptions and requests. Although, now is not a good moment
171
- // to be sending unsubscription messages to the smoldot chain, we
172
- // should wait until is no longer syncing to send the unsubscription
173
- // messages from the stale subscriptions of the previous connection.
174
- //
175
- // That's why -before we perform the cleanup of `this.#subscriptions`-
176
- // we keep the necessary information that we will need later on to
177
- // kill the stale subscriptions.
178
- [...this.#subscriptions.values()].forEach((s) => {
179
- staleSubscriptions.push(s[1]);
180
- });
181
- cleanup();
182
- this.#eventemitter.emit('disconnected');
183
- }
184
- else {
185
- killStaleSubscriptions();
186
- this.#eventemitter.emit('connected');
187
- if (this.#resubscribeMethods.size) {
188
- this.#resubscribe();
189
- }
190
- }
191
- });
192
- return (0, util_1.objectSpread)({}, chain, {
193
- remove: () => {
194
- hc.stop();
195
- chain.remove();
196
- cleanup();
197
- },
198
- sendJsonRpc: hc.sendJsonRpc.bind(hc)
199
- });
200
- });
201
- try {
202
- await this.#chain;
203
- }
204
- catch (e) {
205
- this.#chain = null;
206
- this.#eventemitter.emit('error', e);
207
- throw e;
208
- }
209
- }
210
- #resubscribe = () => {
211
- const promises = [];
212
- this.#resubscribeMethods.forEach((subDetails) => {
213
- // only re-create subscriptions which are not in author (only area where
214
- // transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic'
215
- // are not included (and will not be re-broadcast)
216
- if (subDetails.type.startsWith('author_')) {
217
- return;
218
- }
219
- try {
220
- const promise = new Promise((resolve) => {
221
- this.subscribe(subDetails.type, subDetails.method, subDetails.params, subDetails.callback).catch((error) => console.log(error));
222
- resolve();
223
- });
224
- promises.push(promise);
225
- }
226
- catch (error) {
227
- l.error(error);
228
- }
229
- });
230
- Promise.all(promises).catch((err) => l.log(err));
231
- };
232
- async disconnect() {
233
- if (!this.#chain) {
234
- return;
235
- }
236
- const chain = await this.#chain;
237
- this.#chain = null;
238
- this.#isChainReady = false;
239
- try {
240
- chain.remove();
241
- }
242
- catch (_) { }
243
- this.#eventemitter.emit('disconnected');
244
- }
245
- on(type, sub) {
246
- // It's possible. Although, quite unlikely, that by the time that pezkuwi
247
- // subscribes to the `connected` event, the Provider is already connected.
248
- // In that case, we must emit to let the consumer know that we are connected.
249
- if (type === 'connected' && this.isConnected) {
250
- sub();
251
- }
252
- this.#eventemitter.on(type, sub);
253
- return () => {
254
- this.#eventemitter.removeListener(type, sub);
255
- };
256
- }
257
- async send(method, params) {
258
- if (!this.isConnected || !this.#chain) {
259
- throw new Error('Provider is not connected');
260
- }
261
- const chain = await this.#chain;
262
- const [id, json] = this.#coder.encodeJson(method, params);
263
- const result = new Promise((resolve, reject) => {
264
- this.#requests.set(id, (response) => {
265
- ((0, util_1.isError)(response) ? reject : resolve)(response);
266
- });
267
- try {
268
- chain.sendJsonRpc(json);
269
- }
270
- catch (e) {
271
- this.#chain = null;
272
- try {
273
- chain.remove();
274
- }
275
- catch (_) { }
276
- this.#eventemitter.emit('error', e);
277
- }
278
- });
279
- try {
280
- return await result;
281
- }
282
- finally {
283
- // let's ensure that once the Promise is resolved/rejected, then we remove
284
- // remove its entry from the internal #requests
285
- this.#requests.delete(id);
286
- }
287
- }
288
- async subscribe(type, method, params, callback) {
289
- if (!subscriptionUnsubscriptionMethods.has(method)) {
290
- throw new Error(`Unsupported subscribe method: ${method}`);
291
- }
292
- const id = await this.send(method, params);
293
- const subscriptionId = `${type}::${id}`;
294
- const cb = (response) => {
295
- if (response instanceof Error) {
296
- callback(response, undefined);
297
- }
298
- else {
299
- callback(null, response);
300
- }
301
- };
302
- const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method);
303
- if (!unsubscribeMethod) {
304
- throw new Error('Invalid unsubscribe method found');
305
- }
306
- this.#resubscribeMethods.set(subscriptionId, { callback, method, params, type });
307
- this.#subscriptions.set(subscriptionId, [cb, { id, unsubscribeMethod }]);
308
- return id;
309
- }
310
- unsubscribe(type, method, id) {
311
- if (!this.isConnected) {
312
- throw new Error('Provider is not connected');
313
- }
314
- const subscriptionId = `${type}::${id}`;
315
- if (!this.#subscriptions.has(subscriptionId)) {
316
- return Promise.reject(new Error(`Unable to find active subscription=${subscriptionId}`));
317
- }
318
- this.#resubscribeMethods.delete(subscriptionId);
319
- this.#subscriptions.delete(subscriptionId);
320
- return this.send(method, [id]);
321
- }
322
- }
323
- exports.ScProvider = ScProvider;
@@ -1,12 +0,0 @@
1
- export interface SmoldotHealth {
2
- isSyncing: boolean;
3
- peers: number;
4
- shouldHavePeers: boolean;
5
- }
6
- export interface HealthChecker {
7
- setSendJsonRpc(sendRequest: (request: string) => void): void;
8
- start(healthCallback: (health: SmoldotHealth) => void): void;
9
- stop(): void;
10
- sendJsonRpc(request: string): void;
11
- responsePassThrough(response: string): string | null;
12
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,5 +0,0 @@
1
- export { ScProvider } from './bizinikiwi-connect/index.js';
2
- export { HttpProvider } from './http/index.js';
3
- export { DEFAULT_CAPACITY, LRUCache } from './lru.js';
4
- export { packageInfo } from './packageInfo.js';
5
- export { WsProvider } from './ws/index.js';
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WsProvider = exports.packageInfo = exports.LRUCache = exports.DEFAULT_CAPACITY = exports.HttpProvider = exports.ScProvider = void 0;
4
- var index_js_1 = require("./bizinikiwi-connect/index.js");
5
- Object.defineProperty(exports, "ScProvider", { enumerable: true, get: function () { return index_js_1.ScProvider; } });
6
- var index_js_2 = require("./http/index.js");
7
- Object.defineProperty(exports, "HttpProvider", { enumerable: true, get: function () { return index_js_2.HttpProvider; } });
8
- var lru_js_1 = require("./lru.js");
9
- Object.defineProperty(exports, "DEFAULT_CAPACITY", { enumerable: true, get: function () { return lru_js_1.DEFAULT_CAPACITY; } });
10
- Object.defineProperty(exports, "LRUCache", { enumerable: true, get: function () { return lru_js_1.LRUCache; } });
11
- var packageInfo_js_1 = require("./packageInfo.js");
12
- Object.defineProperty(exports, "packageInfo", { enumerable: true, get: function () { return packageInfo_js_1.packageInfo; } });
13
- var index_js_3 = require("./ws/index.js");
14
- Object.defineProperty(exports, "WsProvider", { enumerable: true, get: function () { return index_js_3.WsProvider; } });
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const util_1 = require("@pezkuwi/util");
4
- const UNKNOWN = -99999;
5
- function extend(that, name, value) {
6
- Object.defineProperty(that, name, {
7
- configurable: true,
8
- enumerable: false,
9
- value
10
- });
11
- }
12
- /**
13
- * @name RpcError
14
- * @summary Extension to the basic JS Error.
15
- * @description
16
- * The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object.
17
- * @example
18
- * <BR>
19
- *
20
- * ```javascript
21
- * const { RpcError } from '@pezkuwi/util');
22
- *
23
- * throw new RpcError('some message', RpcError.CODES.METHOD_NOT_FOUND); // => error.code = -32601
24
- * ```
25
- */
26
- class RpcError extends Error {
27
- code;
28
- data;
29
- message;
30
- name;
31
- stack;
32
- constructor(message = '', code = UNKNOWN, data) {
33
- super();
34
- extend(this, 'message', String(message));
35
- extend(this, 'name', this.constructor.name);
36
- extend(this, 'data', data);
37
- extend(this, 'code', code);
38
- if ((0, util_1.isFunction)(Error.captureStackTrace)) {
39
- Error.captureStackTrace(this, this.constructor);
40
- }
41
- else {
42
- const { stack } = new Error(message);
43
- stack && extend(this, 'stack', stack);
44
- }
45
- }
46
- static CODES = {
47
- ASSERT: -90009,
48
- INVALID_JSONRPC: -99998,
49
- METHOD_NOT_FOUND: -32601, // Rust client
50
- UNKNOWN
51
- };
52
- }
53
- exports.default = RpcError;
@@ -1,63 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RpcCoder = void 0;
4
- const tslib_1 = require("tslib");
5
- const util_1 = require("@pezkuwi/util");
6
- const error_js_1 = tslib_1.__importDefault(require("./error.js"));
7
- function formatErrorData(data) {
8
- if ((0, util_1.isUndefined)(data)) {
9
- return '';
10
- }
11
- const formatted = `: ${(0, util_1.isString)(data)
12
- ? data.replace(/Error\("/g, '').replace(/\("/g, '(').replace(/"\)/g, ')').replace(/\(/g, ', ').replace(/\)/g, '')
13
- : (0, util_1.stringify)(data)}`;
14
- // We need some sort of cut-off here since these can be very large and
15
- // very nested, pick a number and trim the result display to it
16
- return formatted.length <= 256
17
- ? formatted
18
- : `${formatted.substring(0, 255)}…`;
19
- }
20
- function checkError(error) {
21
- if (error) {
22
- const { code, data, message } = error;
23
- throw new error_js_1.default(`${code}: ${message}${formatErrorData(data)}`, code, data);
24
- }
25
- }
26
- /** @internal */
27
- class RpcCoder {
28
- #id = 0;
29
- decodeResponse(response) {
30
- if (!response || response.jsonrpc !== '2.0') {
31
- throw new Error('Invalid jsonrpc field in decoded object');
32
- }
33
- const isSubscription = !(0, util_1.isUndefined)(response.params) && !(0, util_1.isUndefined)(response.method);
34
- if (!(0, util_1.isNumber)(response.id) &&
35
- (!isSubscription || (!(0, util_1.isNumber)(response.params.subscription) &&
36
- !(0, util_1.isString)(response.params.subscription)))) {
37
- throw new Error('Invalid id field in decoded object');
38
- }
39
- checkError(response.error);
40
- if (response.result === undefined && !isSubscription) {
41
- throw new Error('No result found in jsonrpc response');
42
- }
43
- if (isSubscription) {
44
- checkError(response.params.error);
45
- return response.params.result;
46
- }
47
- return response.result;
48
- }
49
- encodeJson(method, params) {
50
- const [id, data] = this.encodeObject(method, params);
51
- return [id, (0, util_1.stringify)(data)];
52
- }
53
- encodeObject(method, params) {
54
- const id = ++this.#id;
55
- return [id, {
56
- id,
57
- jsonrpc: '2.0',
58
- method,
59
- params
60
- }];
61
- }
62
- }
63
- exports.RpcCoder = RpcCoder;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const HTTP_URL = 'http://127.0.0.1:9933';
4
- const WS_URL = 'ws://127.0.0.1:9944';
5
- exports.default = {
6
- HTTP_URL,
7
- WS_URL
8
- };
@@ -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;