@waku/core 0.0.5 → 0.0.7

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 (129) hide show
  1. package/CHANGELOG.md +51 -3
  2. package/bundle/index.js +31146 -26342
  3. package/bundle/lib/message/topic_only_message.js +33 -0
  4. package/bundle/lib/message/version_0.js +133 -0
  5. package/bundle/lib/predefined_bootstrap_nodes.js +24 -4
  6. package/bundle/{message-049c8b67.js → peer_exchange-53df2b11.js} +3579 -1007
  7. package/dist/index.d.ts +14 -13
  8. package/dist/index.js +11 -10
  9. package/dist/index.js.map +1 -1
  10. package/dist/lib/{waku_filter → filter}/filter_rpc.d.ts +1 -1
  11. package/dist/lib/{waku_filter → filter}/filter_rpc.js +1 -1
  12. package/dist/lib/filter/filter_rpc.js.map +1 -0
  13. package/dist/lib/filter/index.d.ts +25 -0
  14. package/dist/lib/{waku_filter → filter}/index.js +14 -9
  15. package/dist/lib/filter/index.js.map +1 -0
  16. package/dist/lib/light_push/index.d.ts +22 -0
  17. package/dist/lib/{waku_light_push → light_push}/index.js +14 -9
  18. package/dist/lib/light_push/index.js.map +1 -0
  19. package/dist/lib/{waku_light_push → light_push}/push_rpc.d.ts +1 -1
  20. package/dist/lib/{waku_light_push → light_push}/push_rpc.js +1 -1
  21. package/dist/lib/light_push/push_rpc.js.map +1 -0
  22. package/dist/lib/message/topic_only_message.d.ts +16 -0
  23. package/dist/lib/{waku_message → message}/topic_only_message.js +2 -1
  24. package/dist/lib/message/topic_only_message.js.map +1 -0
  25. package/dist/lib/message/version_0.d.ts +54 -0
  26. package/dist/lib/{waku_message → message}/version_0.js +41 -6
  27. package/dist/lib/message/version_0.js.map +1 -0
  28. package/dist/lib/predefined_bootstrap_nodes.d.ts +1 -2
  29. package/dist/lib/predefined_bootstrap_nodes.js +0 -2
  30. package/dist/lib/predefined_bootstrap_nodes.js.map +1 -1
  31. package/dist/lib/{waku_relay → relay}/constants.d.ts +0 -0
  32. package/dist/lib/{waku_relay → relay}/constants.js +0 -0
  33. package/dist/lib/relay/constants.js.map +1 -0
  34. package/dist/lib/relay/index.d.ts +24 -0
  35. package/dist/lib/{waku_relay → relay}/index.js +9 -6
  36. package/dist/lib/relay/index.js.map +1 -0
  37. package/dist/lib/{waku_store → store}/history_rpc.d.ts +1 -1
  38. package/dist/lib/{waku_store → store}/history_rpc.js +1 -1
  39. package/dist/lib/store/history_rpc.js.map +1 -0
  40. package/dist/lib/store/index.d.ts +68 -0
  41. package/dist/lib/{waku_store → store}/index.js +41 -16
  42. package/dist/lib/store/index.js.map +1 -0
  43. package/dist/lib/to_proto_message.d.ts +3 -3
  44. package/dist/lib/to_proto_message.js +1 -0
  45. package/dist/lib/to_proto_message.js.map +1 -1
  46. package/dist/lib/wait_for_remote_peer.js +14 -5
  47. package/dist/lib/wait_for_remote_peer.js.map +1 -1
  48. package/dist/lib/waku.d.ts +17 -15
  49. package/dist/lib/waku.js +49 -41
  50. package/dist/lib/waku.js.map +1 -1
  51. package/package.json +28 -31
  52. package/src/index.ts +25 -14
  53. package/src/lib/{waku_filter → filter}/filter_rpc.ts +1 -2
  54. package/src/lib/{waku_filter → filter}/index.ts +51 -30
  55. package/src/lib/{waku_light_push → light_push}/index.ts +38 -19
  56. package/src/lib/{waku_light_push → light_push}/push_rpc.ts +1 -2
  57. package/src/lib/{waku_message → message}/topic_only_message.ts +12 -7
  58. package/src/lib/{waku_message → message}/version_0.ts +59 -18
  59. package/src/lib/predefined_bootstrap_nodes.ts +2 -6
  60. package/src/lib/{waku_relay → relay}/constants.ts +0 -0
  61. package/src/lib/{waku_relay → relay}/index.ts +30 -26
  62. package/src/lib/{waku_store → store}/history_rpc.ts +1 -2
  63. package/src/lib/{waku_store → store}/index.ts +93 -28
  64. package/src/lib/to_proto_message.ts +5 -5
  65. package/src/lib/wait_for_remote_peer.ts +19 -7
  66. package/src/lib/waku.ts +78 -51
  67. package/bundle/browser-1e1a2f27.js +0 -722
  68. package/bundle/events-158407bb.js +0 -1929
  69. package/bundle/index-64ce43f0.js +0 -69
  70. package/bundle/index-8710041d.js +0 -2962
  71. package/bundle/index-a67d7136.js +0 -4059
  72. package/bundle/lib/peer_discovery_static_list.js +0 -89
  73. package/bundle/lib/wait_for_remote_peer.js +0 -326
  74. package/bundle/lib/waku_message/topic_only_message.js +0 -3
  75. package/bundle/lib/waku_message/version_0.js +0 -317
  76. package/bundle/random_subset-75d1c511.js +0 -26
  77. package/bundle/topic_only_message-5ad3a869.js +0 -82
  78. package/dist/lib/multiaddr_to_peer_info.d.ts +0 -3
  79. package/dist/lib/multiaddr_to_peer_info.js +0 -15
  80. package/dist/lib/multiaddr_to_peer_info.js.map +0 -1
  81. package/dist/lib/peer_discovery_static_list.d.ts +0 -44
  82. package/dist/lib/peer_discovery_static_list.js +0 -72
  83. package/dist/lib/peer_discovery_static_list.js.map +0 -1
  84. package/dist/lib/select_connection.d.ts +0 -2
  85. package/dist/lib/select_connection.js +0 -19
  86. package/dist/lib/select_connection.js.map +0 -1
  87. package/dist/lib/select_peer.d.ts +0 -15
  88. package/dist/lib/select_peer.js +0 -59
  89. package/dist/lib/select_peer.js.map +0 -1
  90. package/dist/lib/waku_filter/filter_rpc.js.map +0 -1
  91. package/dist/lib/waku_filter/index.d.ts +0 -50
  92. package/dist/lib/waku_filter/index.js.map +0 -1
  93. package/dist/lib/waku_light_push/index.d.ts +0 -38
  94. package/dist/lib/waku_light_push/index.js.map +0 -1
  95. package/dist/lib/waku_light_push/push_rpc.js.map +0 -1
  96. package/dist/lib/waku_message/topic_only_message.d.ts +0 -15
  97. package/dist/lib/waku_message/topic_only_message.js.map +0 -1
  98. package/dist/lib/waku_message/version_0.d.ts +0 -27
  99. package/dist/lib/waku_message/version_0.js.map +0 -1
  100. package/dist/lib/waku_relay/constants.js.map +0 -1
  101. package/dist/lib/waku_relay/index.d.ts +0 -66
  102. package/dist/lib/waku_relay/index.js.map +0 -1
  103. package/dist/lib/waku_store/history_rpc.js.map +0 -1
  104. package/dist/lib/waku_store/index.d.ts +0 -126
  105. package/dist/lib/waku_store/index.js.map +0 -1
  106. package/dist/proto/filter.d.ts +0 -65
  107. package/dist/proto/filter.js +0 -425
  108. package/dist/proto/filter.js.map +0 -1
  109. package/dist/proto/light_push.d.ts +0 -57
  110. package/dist/proto/light_push.js +0 -369
  111. package/dist/proto/light_push.js.map +0 -1
  112. package/dist/proto/message.d.ts +0 -29
  113. package/dist/proto/message.js +0 -215
  114. package/dist/proto/message.js.map +0 -1
  115. package/dist/proto/store.d.ts +0 -104
  116. package/dist/proto/store.js +0 -602
  117. package/dist/proto/store.js.map +0 -1
  118. package/dist/proto/topic_only_message.d.ts +0 -10
  119. package/dist/proto/topic_only_message.js +0 -46
  120. package/dist/proto/topic_only_message.js.map +0 -1
  121. package/src/lib/multiaddr_to_peer_info.ts +0 -17
  122. package/src/lib/peer_discovery_static_list.ts +0 -118
  123. package/src/lib/select_connection.ts +0 -24
  124. package/src/lib/select_peer.ts +0 -77
  125. package/src/proto/filter.ts +0 -602
  126. package/src/proto/light_push.ts +0 -526
  127. package/src/proto/message.ts +0 -304
  128. package/src/proto/store.ts +0 -844
  129. package/src/proto/topic_only_message.ts +0 -67
@@ -1,4059 +0,0 @@
1
- import { d as debug } from './browser-1e1a2f27.js';
2
- import { i as createCodec, C as CODEC_TYPES, m as message, j as encodeMessage, k as decodeMessage } from './message-049c8b67.js';
3
- import { e as errCode } from './index-64ce43f0.js';
4
-
5
- /**
6
- * DefaultPubSubTopic is the default gossipsub topic to use for Waku.
7
- */
8
- const DefaultPubSubTopic = "/waku/2/default-waku/proto";
9
-
10
- function enumeration(v) {
11
- function findValue(val) {
12
- // Use the reverse mapping to look up the enum key for the stored value
13
- // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
14
- if (v[val.toString()] == null) {
15
- throw new Error('Invalid enum value');
16
- }
17
- return v[val];
18
- }
19
- const encode = function enumEncode(val, writer) {
20
- const enumValue = findValue(val);
21
- writer.int32(enumValue);
22
- };
23
- const decode = function enumDecode(reader) {
24
- const val = reader.uint32();
25
- return findValue(val);
26
- };
27
- // @ts-expect-error yeah yeah
28
- return createCodec('enum', CODEC_TYPES.VARINT, encode, decode);
29
- }
30
-
31
- var Protocols;
32
- (function (Protocols) {
33
- Protocols["Relay"] = "relay";
34
- Protocols["Store"] = "store";
35
- Protocols["LightPush"] = "lightpush";
36
- Protocols["Filter"] = "filter";
37
- })(Protocols || (Protocols = {}));
38
- var PageDirection$1;
39
- (function (PageDirection) {
40
- PageDirection["BACKWARD"] = "backward";
41
- PageDirection["FORWARD"] = "forward";
42
- })(PageDirection$1 || (PageDirection$1 = {}));
43
-
44
- /**
45
- * Collects all values from an (async) iterable into an array and returns it.
46
- *
47
- * @template T
48
- * @param {AsyncIterable<T>|Iterable<T>} source
49
- */
50
- const all = async (source) => {
51
- const arr = [];
52
-
53
- for await (const entry of source) {
54
- arr.push(entry);
55
- }
56
-
57
- return arr
58
- };
59
-
60
- var itAll = all;
61
-
62
- /**
63
- * To guarantee Uint8Array semantics, convert nodejs Buffers
64
- * into vanilla Uint8Arrays
65
- */
66
- function asUint8Array$1(buf) {
67
- if (globalThis.Buffer != null) {
68
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
69
- }
70
- return buf;
71
- }
72
-
73
- /**
74
- * Returns a `Uint8Array` of the requested size. Referenced memory will
75
- * be initialized to 0.
76
- */
77
- function alloc(size = 0) {
78
- if (globalThis.Buffer?.alloc != null) {
79
- return asUint8Array$1(globalThis.Buffer.alloc(size));
80
- }
81
- return new Uint8Array(size);
82
- }
83
- /**
84
- * Where possible returns a Uint8Array of the requested size that references
85
- * uninitialized memory. Only use if you are certain you will immediately
86
- * overwrite every value in the returned `Uint8Array`.
87
- */
88
- function allocUnsafe$2(size = 0) {
89
- if (globalThis.Buffer?.allocUnsafe != null) {
90
- return asUint8Array$1(globalThis.Buffer.allocUnsafe(size));
91
- }
92
- return new Uint8Array(size);
93
- }
94
-
95
- /**
96
- * Returns a new Uint8Array created by concatenating the passed ArrayLikes
97
- */
98
- function concat(arrays, length) {
99
- if (length == null) {
100
- length = arrays.reduce((acc, curr) => acc + curr.length, 0);
101
- }
102
- const output = allocUnsafe$2(length);
103
- let offset = 0;
104
- for (const arr of arrays) {
105
- output.set(arr, offset);
106
- offset += arr.length;
107
- }
108
- return asUint8Array$1(output);
109
- }
110
-
111
- /**
112
- * Returns true if the two passed Uint8Arrays have the same content
113
- */
114
- function equals(a, b) {
115
- if (a === b) {
116
- return true;
117
- }
118
- if (a.byteLength !== b.byteLength) {
119
- return false;
120
- }
121
- for (let i = 0; i < a.byteLength; i++) {
122
- if (a[i] !== b[i]) {
123
- return false;
124
- }
125
- }
126
- return true;
127
- }
128
-
129
- const symbol = Symbol.for('@achingbrain/uint8arraylist');
130
- function findBufAndOffset(bufs, index) {
131
- if (index == null || index < 0) {
132
- throw new RangeError('index is out of bounds');
133
- }
134
- let offset = 0;
135
- for (const buf of bufs) {
136
- const bufEnd = offset + buf.byteLength;
137
- if (index < bufEnd) {
138
- return {
139
- buf,
140
- index: index - offset
141
- };
142
- }
143
- offset = bufEnd;
144
- }
145
- throw new RangeError('index is out of bounds');
146
- }
147
- /**
148
- * Check if object is a CID instance
149
- */
150
- function isUint8ArrayList(value) {
151
- return Boolean(value?.[symbol]);
152
- }
153
- class Uint8ArrayList {
154
- constructor(...data) {
155
- // Define symbol
156
- Object.defineProperty(this, symbol, { value: true });
157
- this.bufs = [];
158
- this.length = 0;
159
- if (data.length > 0) {
160
- this.appendAll(data);
161
- }
162
- }
163
- *[Symbol.iterator]() {
164
- yield* this.bufs;
165
- }
166
- get byteLength() {
167
- return this.length;
168
- }
169
- /**
170
- * Add one or more `bufs` to the end of this Uint8ArrayList
171
- */
172
- append(...bufs) {
173
- this.appendAll(bufs);
174
- }
175
- /**
176
- * Add all `bufs` to the end of this Uint8ArrayList
177
- */
178
- appendAll(bufs) {
179
- let length = 0;
180
- for (const buf of bufs) {
181
- if (buf instanceof Uint8Array) {
182
- length += buf.byteLength;
183
- this.bufs.push(buf);
184
- }
185
- else if (isUint8ArrayList(buf)) {
186
- length += buf.byteLength;
187
- this.bufs.push(...buf.bufs);
188
- }
189
- else {
190
- throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList');
191
- }
192
- }
193
- this.length += length;
194
- }
195
- /**
196
- * Add one or more `bufs` to the start of this Uint8ArrayList
197
- */
198
- prepend(...bufs) {
199
- this.prependAll(bufs);
200
- }
201
- /**
202
- * Add all `bufs` to the start of this Uint8ArrayList
203
- */
204
- prependAll(bufs) {
205
- let length = 0;
206
- for (const buf of bufs.reverse()) {
207
- if (buf instanceof Uint8Array) {
208
- length += buf.byteLength;
209
- this.bufs.unshift(buf);
210
- }
211
- else if (isUint8ArrayList(buf)) {
212
- length += buf.byteLength;
213
- this.bufs.unshift(...buf.bufs);
214
- }
215
- else {
216
- throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList');
217
- }
218
- }
219
- this.length += length;
220
- }
221
- /**
222
- * Read the value at `index`
223
- */
224
- get(index) {
225
- const res = findBufAndOffset(this.bufs, index);
226
- return res.buf[res.index];
227
- }
228
- /**
229
- * Set the value at `index` to `value`
230
- */
231
- set(index, value) {
232
- const res = findBufAndOffset(this.bufs, index);
233
- res.buf[res.index] = value;
234
- }
235
- /**
236
- * Copy bytes from `buf` to the index specified by `offset`
237
- */
238
- write(buf, offset = 0) {
239
- if (buf instanceof Uint8Array) {
240
- for (let i = 0; i < buf.length; i++) {
241
- this.set(offset + i, buf[i]);
242
- }
243
- }
244
- else if (isUint8ArrayList(buf)) {
245
- for (let i = 0; i < buf.length; i++) {
246
- this.set(offset + i, buf.get(i));
247
- }
248
- }
249
- else {
250
- throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList');
251
- }
252
- }
253
- /**
254
- * Remove bytes from the front of the pool
255
- */
256
- consume(bytes) {
257
- // first, normalize the argument, in accordance with how Buffer does it
258
- bytes = Math.trunc(bytes);
259
- // do nothing if not a positive number
260
- if (Number.isNaN(bytes) || bytes <= 0) {
261
- return;
262
- }
263
- while (this.bufs.length > 0) {
264
- if (bytes >= this.bufs[0].byteLength) {
265
- bytes -= this.bufs[0].byteLength;
266
- this.length -= this.bufs[0].byteLength;
267
- this.bufs.shift();
268
- }
269
- else {
270
- this.bufs[0] = this.bufs[0].subarray(bytes);
271
- this.length -= bytes;
272
- break;
273
- }
274
- }
275
- }
276
- /**
277
- * Extracts a section of an array and returns a new array.
278
- *
279
- * This is a copy operation as it is with Uint8Arrays and Arrays
280
- * - note this is different to the behaviour of Node Buffers.
281
- */
282
- slice(beginInclusive, endExclusive) {
283
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
284
- return concat(bufs, length);
285
- }
286
- /**
287
- * Returns a alloc from the given start and end element index.
288
- *
289
- * In the best case where the data extracted comes from a single Uint8Array
290
- * internally this is a no-copy operation otherwise it is a copy operation.
291
- */
292
- subarray(beginInclusive, endExclusive) {
293
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
294
- if (bufs.length === 1) {
295
- return bufs[0];
296
- }
297
- return concat(bufs, length);
298
- }
299
- /**
300
- * Returns a allocList from the given start and end element index.
301
- *
302
- * This is a no-copy operation.
303
- */
304
- sublist(beginInclusive, endExclusive) {
305
- const { bufs, length } = this._subList(beginInclusive, endExclusive);
306
- const list = new Uint8ArrayList();
307
- list.length = length;
308
- // don't loop, just set the bufs
309
- list.bufs = bufs;
310
- return list;
311
- }
312
- _subList(beginInclusive, endExclusive) {
313
- beginInclusive = beginInclusive ?? 0;
314
- endExclusive = endExclusive ?? this.length;
315
- if (beginInclusive < 0) {
316
- beginInclusive = this.length + beginInclusive;
317
- }
318
- if (endExclusive < 0) {
319
- endExclusive = this.length + endExclusive;
320
- }
321
- if (beginInclusive < 0 || endExclusive > this.length) {
322
- throw new RangeError('index is out of bounds');
323
- }
324
- if (beginInclusive === endExclusive) {
325
- return { bufs: [], length: 0 };
326
- }
327
- if (beginInclusive === 0 && endExclusive === this.length) {
328
- return { bufs: [...this.bufs], length: this.length };
329
- }
330
- const bufs = [];
331
- let offset = 0;
332
- for (let i = 0; i < this.bufs.length; i++) {
333
- const buf = this.bufs[i];
334
- const bufStart = offset;
335
- const bufEnd = bufStart + buf.byteLength;
336
- // for next loop
337
- offset = bufEnd;
338
- if (beginInclusive >= bufEnd) {
339
- // start after this buf
340
- continue;
341
- }
342
- const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;
343
- const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;
344
- if (sliceStartInBuf && sliceEndsInBuf) {
345
- // slice is wholly contained within this buffer
346
- if (beginInclusive === bufStart && endExclusive === bufEnd) {
347
- // requested whole buffer
348
- bufs.push(buf);
349
- break;
350
- }
351
- // requested part of buffer
352
- const start = beginInclusive - bufStart;
353
- bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));
354
- break;
355
- }
356
- if (sliceStartInBuf) {
357
- // slice starts in this buffer
358
- if (beginInclusive === 0) {
359
- // requested whole buffer
360
- bufs.push(buf);
361
- continue;
362
- }
363
- // requested part of buffer
364
- bufs.push(buf.subarray(beginInclusive - bufStart));
365
- continue;
366
- }
367
- if (sliceEndsInBuf) {
368
- if (endExclusive === bufEnd) {
369
- // requested whole buffer
370
- bufs.push(buf);
371
- break;
372
- }
373
- // requested part of buffer
374
- bufs.push(buf.subarray(0, endExclusive - bufStart));
375
- break;
376
- }
377
- // slice started before this buffer and ends after it
378
- bufs.push(buf);
379
- }
380
- return { bufs, length: endExclusive - beginInclusive };
381
- }
382
- getInt8(byteOffset) {
383
- const buf = this.subarray(byteOffset, byteOffset + 1);
384
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
385
- return view.getInt8(0);
386
- }
387
- setInt8(byteOffset, value) {
388
- const buf = allocUnsafe$2(1);
389
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
390
- view.setInt8(0, value);
391
- this.write(buf, byteOffset);
392
- }
393
- getInt16(byteOffset, littleEndian) {
394
- const buf = this.subarray(byteOffset, byteOffset + 2);
395
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
396
- return view.getInt16(0, littleEndian);
397
- }
398
- setInt16(byteOffset, value, littleEndian) {
399
- const buf = alloc(2);
400
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
401
- view.setInt16(0, value, littleEndian);
402
- this.write(buf, byteOffset);
403
- }
404
- getInt32(byteOffset, littleEndian) {
405
- const buf = this.subarray(byteOffset, byteOffset + 4);
406
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
407
- return view.getInt32(0, littleEndian);
408
- }
409
- setInt32(byteOffset, value, littleEndian) {
410
- const buf = alloc(4);
411
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
412
- view.setInt32(0, value, littleEndian);
413
- this.write(buf, byteOffset);
414
- }
415
- getBigInt64(byteOffset, littleEndian) {
416
- const buf = this.subarray(byteOffset, byteOffset + 8);
417
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
418
- return view.getBigInt64(0, littleEndian);
419
- }
420
- setBigInt64(byteOffset, value, littleEndian) {
421
- const buf = alloc(8);
422
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
423
- view.setBigInt64(0, value, littleEndian);
424
- this.write(buf, byteOffset);
425
- }
426
- getUint8(byteOffset) {
427
- const buf = this.subarray(byteOffset, byteOffset + 1);
428
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
429
- return view.getUint8(0);
430
- }
431
- setUint8(byteOffset, value) {
432
- const buf = allocUnsafe$2(1);
433
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
434
- view.setUint8(0, value);
435
- this.write(buf, byteOffset);
436
- }
437
- getUint16(byteOffset, littleEndian) {
438
- const buf = this.subarray(byteOffset, byteOffset + 2);
439
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
440
- return view.getUint16(0, littleEndian);
441
- }
442
- setUint16(byteOffset, value, littleEndian) {
443
- const buf = alloc(2);
444
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
445
- view.setUint16(0, value, littleEndian);
446
- this.write(buf, byteOffset);
447
- }
448
- getUint32(byteOffset, littleEndian) {
449
- const buf = this.subarray(byteOffset, byteOffset + 4);
450
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
451
- return view.getUint32(0, littleEndian);
452
- }
453
- setUint32(byteOffset, value, littleEndian) {
454
- const buf = alloc(4);
455
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
456
- view.setUint32(0, value, littleEndian);
457
- this.write(buf, byteOffset);
458
- }
459
- getBigUint64(byteOffset, littleEndian) {
460
- const buf = this.subarray(byteOffset, byteOffset + 8);
461
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
462
- return view.getBigUint64(0, littleEndian);
463
- }
464
- setBigUint64(byteOffset, value, littleEndian) {
465
- const buf = alloc(8);
466
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
467
- view.setBigUint64(0, value, littleEndian);
468
- this.write(buf, byteOffset);
469
- }
470
- getFloat32(byteOffset, littleEndian) {
471
- const buf = this.subarray(byteOffset, byteOffset + 4);
472
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
473
- return view.getFloat32(0, littleEndian);
474
- }
475
- setFloat32(byteOffset, value, littleEndian) {
476
- const buf = alloc(4);
477
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
478
- view.setFloat32(0, value, littleEndian);
479
- this.write(buf, byteOffset);
480
- }
481
- getFloat64(byteOffset, littleEndian) {
482
- const buf = this.subarray(byteOffset, byteOffset + 8);
483
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
484
- return view.getFloat64(0, littleEndian);
485
- }
486
- setFloat64(byteOffset, value, littleEndian) {
487
- const buf = alloc(8);
488
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
489
- view.setFloat64(0, value, littleEndian);
490
- this.write(buf, byteOffset);
491
- }
492
- equals(other) {
493
- if (other == null) {
494
- return false;
495
- }
496
- if (!(other instanceof Uint8ArrayList)) {
497
- return false;
498
- }
499
- if (other.bufs.length !== this.bufs.length) {
500
- return false;
501
- }
502
- for (let i = 0; i < this.bufs.length; i++) {
503
- if (!equals(this.bufs[i], other.bufs[i])) {
504
- return false;
505
- }
506
- }
507
- return true;
508
- }
509
- /**
510
- * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this
511
- * method if you know the total size of all the Uint8Arrays ahead of time.
512
- */
513
- static fromUint8Arrays(bufs, length) {
514
- const list = new Uint8ArrayList();
515
- list.bufs = bufs;
516
- if (length == null) {
517
- length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);
518
- }
519
- list.length = length;
520
- return list;
521
- }
522
- }
523
-
524
- function accessor(buf) {
525
- if (buf instanceof Uint8Array) {
526
- return {
527
- get(index) {
528
- return buf[index];
529
- },
530
- set(index, value) {
531
- buf[index] = value;
532
- }
533
- };
534
- }
535
- return {
536
- get(index) {
537
- return buf.get(index);
538
- },
539
- set(index, value) {
540
- buf.set(index, value);
541
- }
542
- };
543
- }
544
-
545
- const TWO_32 = 4294967296;
546
- class LongBits {
547
- constructor(hi = 0, lo = 0) {
548
- this.hi = hi;
549
- this.lo = lo;
550
- }
551
- /**
552
- * Returns these hi/lo bits as a BigInt
553
- */
554
- toBigInt(unsigned) {
555
- if (unsigned === true) {
556
- return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
557
- }
558
- if ((this.hi >>> 31) !== 0) {
559
- const lo = ~this.lo + 1 >>> 0;
560
- let hi = ~this.hi >>> 0;
561
- if (lo === 0) {
562
- hi = hi + 1 >>> 0;
563
- }
564
- return -(BigInt(lo) + (BigInt(hi) << 32n));
565
- }
566
- return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
567
- }
568
- /**
569
- * Returns these hi/lo bits as a Number - this may overflow, toBigInt
570
- * should be preferred
571
- */
572
- toNumber(unsigned) {
573
- return Number(this.toBigInt(unsigned));
574
- }
575
- /**
576
- * ZigZag decode a LongBits object
577
- */
578
- zzDecode() {
579
- const mask = -(this.lo & 1);
580
- const lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
581
- const hi = (this.hi >>> 1 ^ mask) >>> 0;
582
- return new LongBits(hi, lo);
583
- }
584
- /**
585
- * ZigZag encode a LongBits object
586
- */
587
- zzEncode() {
588
- const mask = this.hi >> 31;
589
- const hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
590
- const lo = (this.lo << 1 ^ mask) >>> 0;
591
- return new LongBits(hi, lo);
592
- }
593
- /**
594
- * Encode a LongBits object as a varint byte array
595
- */
596
- toBytes(buf, offset = 0) {
597
- const access = accessor(buf);
598
- while (this.hi > 0) {
599
- access.set(offset++, this.lo & 127 | 128);
600
- this.lo = (this.lo >>> 7 | this.hi << 25) >>> 0;
601
- this.hi >>>= 7;
602
- }
603
- while (this.lo > 127) {
604
- access.set(offset++, this.lo & 127 | 128);
605
- this.lo = this.lo >>> 7;
606
- }
607
- access.set(offset++, this.lo);
608
- }
609
- /**
610
- * Parse a LongBits object from a BigInt
611
- */
612
- static fromBigInt(value) {
613
- if (value === 0n) {
614
- return new LongBits();
615
- }
616
- const negative = value < 0;
617
- if (negative) {
618
- value = -value;
619
- }
620
- let hi = Number(value >> 32n) | 0;
621
- let lo = Number(value - (BigInt(hi) << 32n)) | 0;
622
- if (negative) {
623
- hi = ~hi >>> 0;
624
- lo = ~lo >>> 0;
625
- if (++lo > TWO_32) {
626
- lo = 0;
627
- if (++hi > TWO_32) {
628
- hi = 0;
629
- }
630
- }
631
- }
632
- return new LongBits(hi, lo);
633
- }
634
- /**
635
- * Parse a LongBits object from a Number
636
- */
637
- static fromNumber(value) {
638
- if (value === 0) {
639
- return new LongBits();
640
- }
641
- const sign = value < 0;
642
- if (sign) {
643
- value = -value;
644
- }
645
- let lo = value >>> 0;
646
- let hi = (value - lo) / 4294967296 >>> 0;
647
- if (sign) {
648
- hi = ~hi >>> 0;
649
- lo = ~lo >>> 0;
650
- if (++lo > 4294967295) {
651
- lo = 0;
652
- if (++hi > 4294967295) {
653
- hi = 0;
654
- }
655
- }
656
- }
657
- return new LongBits(hi, lo);
658
- }
659
- /**
660
- * Parse a LongBits object from a varint byte array
661
- */
662
- static fromBytes(buf, offset = 0) {
663
- const access = accessor(buf);
664
- // tends to deopt with local vars for octet etc.
665
- const bits = new LongBits();
666
- let i = 0;
667
- if (buf.length - offset > 4) { // fast route (lo)
668
- for (; i < 4; ++i) {
669
- // 1st..4th
670
- bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0;
671
- if (access.get(offset++) < 128) {
672
- return bits;
673
- }
674
- }
675
- // 5th
676
- bits.lo = (bits.lo | (access.get(offset) & 127) << 28) >>> 0;
677
- bits.hi = (bits.hi | (access.get(offset) & 127) >> 4) >>> 0;
678
- if (access.get(offset++) < 128) {
679
- return bits;
680
- }
681
- i = 0;
682
- }
683
- else {
684
- for (; i < 4; ++i) {
685
- /* istanbul ignore if */
686
- if (offset >= buf.length) {
687
- throw RangeError(`index out of range: ${offset} > ${buf.length}`);
688
- }
689
- // 1st..4th
690
- bits.lo = (bits.lo | (access.get(offset) & 127) << i * 7) >>> 0;
691
- if (access.get(offset++) < 128) {
692
- return bits;
693
- }
694
- }
695
- }
696
- if (buf.length - offset > 4) { // fast route (hi)
697
- for (; i < 5; ++i) {
698
- // 6th..10th
699
- bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0;
700
- if (access.get(offset++) < 128) {
701
- return bits;
702
- }
703
- }
704
- }
705
- else if (offset < buf.byteLength) {
706
- for (; i < 5; ++i) {
707
- /* istanbul ignore if */
708
- if (offset >= buf.length) {
709
- throw RangeError(`index out of range: ${offset} > ${buf.length}`);
710
- }
711
- // 6th..10th
712
- bits.hi = (bits.hi | (access.get(offset) & 127) << i * 7 + 3) >>> 0;
713
- if (access.get(offset++) < 128) {
714
- return bits;
715
- }
716
- }
717
- }
718
- /* istanbul ignore next */
719
- throw RangeError('invalid varint encoding');
720
- }
721
- }
722
-
723
- /**
724
- * To guarantee Uint8Array semantics, convert nodejs Buffers
725
- * into vanilla Uint8Arrays
726
- */
727
- function asUint8Array(buf) {
728
- if (globalThis.Buffer != null) {
729
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
730
- }
731
- return buf;
732
- }
733
-
734
- /**
735
- * Where possible returns a Uint8Array of the requested size that references
736
- * uninitialized memory. Only use if you are certain you will immediately
737
- * overwrite every value in the returned `Uint8Array`.
738
- */
739
- function allocUnsafe$1(size = 0) {
740
- if (globalThis.Buffer?.allocUnsafe != null) {
741
- return asUint8Array(globalThis.Buffer.allocUnsafe(size));
742
- }
743
- return new Uint8Array(size);
744
- }
745
-
746
- const N1 = Math.pow(2, 7);
747
- const N2 = Math.pow(2, 14);
748
- const N3 = Math.pow(2, 21);
749
- const N4 = Math.pow(2, 28);
750
- const N5 = Math.pow(2, 35);
751
- const N6 = Math.pow(2, 42);
752
- const N7 = Math.pow(2, 49);
753
- const N8 = Math.pow(2, 56);
754
- const N9 = Math.pow(2, 63);
755
- const unsigned = {
756
- encodingLength(value) {
757
- if (value < N1) {
758
- return 1;
759
- }
760
- if (value < N2) {
761
- return 2;
762
- }
763
- if (value < N3) {
764
- return 3;
765
- }
766
- if (value < N4) {
767
- return 4;
768
- }
769
- if (value < N5) {
770
- return 5;
771
- }
772
- if (value < N6) {
773
- return 6;
774
- }
775
- if (value < N7) {
776
- return 7;
777
- }
778
- if (value < N8) {
779
- return 8;
780
- }
781
- if (value < N9) {
782
- return 9;
783
- }
784
- return 10;
785
- },
786
- encode(value, buf, offset = 0) {
787
- if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {
788
- throw new RangeError('Could not encode varint');
789
- }
790
- if (buf == null) {
791
- buf = allocUnsafe$1(unsigned.encodingLength(value));
792
- }
793
- LongBits.fromNumber(value).toBytes(buf, offset);
794
- return buf;
795
- },
796
- decode(buf, offset = 0) {
797
- return LongBits.fromBytes(buf, offset).toNumber(true);
798
- }
799
- };
800
-
801
- function allocUnsafe(len) {
802
- if (globalThis?.Buffer?.allocUnsafe != null) {
803
- return globalThis.Buffer.allocUnsafe(len);
804
- }
805
- return new Uint8Array(len);
806
- }
807
-
808
- const defaultEncoder = (length) => {
809
- const lengthLength = unsigned.encodingLength(length);
810
- const lengthBuf = allocUnsafe(lengthLength);
811
- unsigned.encode(length, lengthBuf);
812
- defaultEncoder.bytes = lengthLength;
813
- return lengthBuf;
814
- };
815
- defaultEncoder.bytes = 0;
816
- function encode(options) {
817
- options = options ?? {};
818
- const encodeLength = options.lengthEncoder ?? defaultEncoder;
819
- const encoder = async function* (source) {
820
- for await (const chunk of source) {
821
- // length + data
822
- const length = encodeLength(chunk.byteLength);
823
- // yield only Uint8Arrays
824
- if (length instanceof Uint8Array) {
825
- yield length;
826
- }
827
- else {
828
- yield* length;
829
- }
830
- // yield only Uint8Arrays
831
- if (chunk instanceof Uint8Array) {
832
- yield chunk;
833
- }
834
- else {
835
- yield* chunk;
836
- }
837
- }
838
- };
839
- return encoder;
840
- }
841
- encode.single = (chunk, options) => {
842
- options = options ?? {};
843
- const encodeLength = options.lengthEncoder ?? defaultEncoder;
844
- return new Uint8ArrayList(encodeLength(chunk.byteLength), chunk);
845
- };
846
-
847
- /* eslint max-depth: ["error", 6] */
848
- // Maximum length of the length section of the message
849
- const MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length
850
- // Maximum length of the data section of the message
851
- const MAX_DATA_LENGTH = 1024 * 1024 * 4;
852
- var ReadMode;
853
- (function (ReadMode) {
854
- ReadMode[ReadMode["LENGTH"] = 0] = "LENGTH";
855
- ReadMode[ReadMode["DATA"] = 1] = "DATA";
856
- })(ReadMode || (ReadMode = {}));
857
- const defaultDecoder = (buf) => {
858
- const length = unsigned.decode(buf);
859
- defaultDecoder.bytes = unsigned.encodingLength(length);
860
- return length;
861
- };
862
- defaultDecoder.bytes = 0;
863
- function decode(options) {
864
- const decoder = async function* (source) {
865
- const buffer = new Uint8ArrayList();
866
- let mode = ReadMode.LENGTH;
867
- let dataLength = -1;
868
- const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;
869
- const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;
870
- const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;
871
- for await (const buf of source) {
872
- buffer.append(buf);
873
- while (buffer.byteLength > 0) {
874
- if (mode === ReadMode.LENGTH) {
875
- // read length, ignore errors for short reads
876
- try {
877
- dataLength = lengthDecoder(buffer);
878
- if (dataLength < 0) {
879
- throw errCode(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH');
880
- }
881
- if (dataLength > maxDataLength) {
882
- throw errCode(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG');
883
- }
884
- const dataLengthLength = lengthDecoder.bytes;
885
- buffer.consume(dataLengthLength);
886
- if (options?.onLength != null) {
887
- options.onLength(dataLength);
888
- }
889
- mode = ReadMode.DATA;
890
- }
891
- catch (err) {
892
- if (err instanceof RangeError) {
893
- if (buffer.byteLength > maxLengthLength) {
894
- throw errCode(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG');
895
- }
896
- break;
897
- }
898
- throw err;
899
- }
900
- }
901
- if (mode === ReadMode.DATA) {
902
- if (buffer.byteLength < dataLength) {
903
- // not enough data, wait for more
904
- break;
905
- }
906
- const data = buffer.sublist(0, dataLength);
907
- buffer.consume(dataLength);
908
- if (options?.onData != null) {
909
- options.onData(data);
910
- }
911
- yield data;
912
- mode = ReadMode.LENGTH;
913
- }
914
- }
915
- }
916
- if (buffer.byteLength > 0) {
917
- throw errCode(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');
918
- }
919
- };
920
- return decoder;
921
- }
922
- /**
923
- * @param {*} reader
924
- * @param {import('./types').DecoderOptions} [options]
925
- * @returns
926
- */
927
- decode.fromReader = (reader, options) => {
928
- let byteLength = 1; // Read single byte chunks until the length is known
929
- const varByteSource = (async function* () {
930
- while (true) {
931
- try {
932
- const { done, value } = await reader.next(byteLength);
933
- if (done === true) {
934
- return;
935
- }
936
- if (value != null) {
937
- yield value;
938
- }
939
- }
940
- catch (err) {
941
- if (err.code === 'ERR_UNDER_READ') {
942
- return { done: true, value: null };
943
- }
944
- throw err;
945
- }
946
- finally {
947
- // Reset the byteLength so we continue to check for varints
948
- byteLength = 1;
949
- }
950
- }
951
- }());
952
- /**
953
- * Once the length has been parsed, read chunk for that length
954
- */
955
- const onLength = (l) => { byteLength = l; };
956
- return decode({
957
- ...(options ?? {}),
958
- onLength
959
- })(varByteSource);
960
- };
961
-
962
- // ported from https://www.npmjs.com/package/fast-fifo
963
- class FixedFIFO$1 {
964
- constructor(hwm) {
965
- if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {
966
- throw new Error('Max size for a FixedFIFO should be a power of two');
967
- }
968
- this.buffer = new Array(hwm);
969
- this.mask = hwm - 1;
970
- this.top = 0;
971
- this.btm = 0;
972
- this.next = null;
973
- }
974
- push(data) {
975
- if (this.buffer[this.top] !== undefined) {
976
- return false;
977
- }
978
- this.buffer[this.top] = data;
979
- this.top = (this.top + 1) & this.mask;
980
- return true;
981
- }
982
- shift() {
983
- const last = this.buffer[this.btm];
984
- if (last === undefined) {
985
- return undefined;
986
- }
987
- this.buffer[this.btm] = undefined;
988
- this.btm = (this.btm + 1) & this.mask;
989
- return last;
990
- }
991
- isEmpty() {
992
- return this.buffer[this.btm] === undefined;
993
- }
994
- }
995
- class FIFO$1 {
996
- constructor(options = {}) {
997
- this.hwm = options.splitLimit ?? 16;
998
- this.head = new FixedFIFO$1(this.hwm);
999
- this.tail = this.head;
1000
- this.size = 0;
1001
- }
1002
- calculateSize(obj) {
1003
- if (obj?.byteLength != null) {
1004
- return obj.byteLength;
1005
- }
1006
- return 1;
1007
- }
1008
- push(val) {
1009
- if (val?.value != null) {
1010
- this.size += this.calculateSize(val.value);
1011
- }
1012
- if (!this.head.push(val)) {
1013
- const prev = this.head;
1014
- this.head = prev.next = new FixedFIFO$1(2 * this.head.buffer.length);
1015
- this.head.push(val);
1016
- }
1017
- }
1018
- shift() {
1019
- let val = this.tail.shift();
1020
- if (val === undefined && (this.tail.next != null)) {
1021
- const next = this.tail.next;
1022
- this.tail.next = null;
1023
- this.tail = next;
1024
- val = this.tail.shift();
1025
- }
1026
- if (val?.value != null) {
1027
- this.size -= this.calculateSize(val.value);
1028
- }
1029
- return val;
1030
- }
1031
- isEmpty() {
1032
- return this.head.isEmpty();
1033
- }
1034
- }
1035
-
1036
- function pushable$1(options = {}) {
1037
- const getNext = (buffer) => {
1038
- const next = buffer.shift();
1039
- if (next == null) {
1040
- return { done: true };
1041
- }
1042
- if (next.error != null) {
1043
- throw next.error;
1044
- }
1045
- return {
1046
- done: next.done === true,
1047
- // @ts-expect-error
1048
- value: next.value
1049
- };
1050
- };
1051
- return _pushable(getNext, options);
1052
- }
1053
- function _pushable(getNext, options) {
1054
- options = options ?? {};
1055
- let onEnd = options.onEnd;
1056
- let buffer = new FIFO$1();
1057
- let pushable;
1058
- let onNext;
1059
- let ended;
1060
- const waitNext = async () => {
1061
- if (!buffer.isEmpty()) {
1062
- return getNext(buffer);
1063
- }
1064
- if (ended) {
1065
- return { done: true };
1066
- }
1067
- return await new Promise((resolve, reject) => {
1068
- onNext = (next) => {
1069
- onNext = null;
1070
- buffer.push(next);
1071
- try {
1072
- resolve(getNext(buffer));
1073
- }
1074
- catch (err) {
1075
- reject(err);
1076
- }
1077
- return pushable;
1078
- };
1079
- });
1080
- };
1081
- const bufferNext = (next) => {
1082
- if (onNext != null) {
1083
- return onNext(next);
1084
- }
1085
- buffer.push(next);
1086
- return pushable;
1087
- };
1088
- const bufferError = (err) => {
1089
- buffer = new FIFO$1();
1090
- if (onNext != null) {
1091
- return onNext({ error: err });
1092
- }
1093
- buffer.push({ error: err });
1094
- return pushable;
1095
- };
1096
- const push = (value) => {
1097
- if (ended) {
1098
- return pushable;
1099
- }
1100
- // @ts-expect-error `byteLength` is not declared on PushType
1101
- if (options?.objectMode !== true && value?.byteLength == null) {
1102
- throw new Error('objectMode was not true but tried to push non-Uint8Array value');
1103
- }
1104
- return bufferNext({ done: false, value });
1105
- };
1106
- const end = (err) => {
1107
- if (ended)
1108
- return pushable;
1109
- ended = true;
1110
- return (err != null) ? bufferError(err) : bufferNext({ done: true });
1111
- };
1112
- const _return = () => {
1113
- buffer = new FIFO$1();
1114
- end();
1115
- return { done: true };
1116
- };
1117
- const _throw = (err) => {
1118
- end(err);
1119
- return { done: true };
1120
- };
1121
- pushable = {
1122
- [Symbol.asyncIterator]() { return this; },
1123
- next: waitNext,
1124
- return: _return,
1125
- throw: _throw,
1126
- push,
1127
- end,
1128
- get readableLength() {
1129
- return buffer.size;
1130
- }
1131
- };
1132
- if (onEnd == null) {
1133
- return pushable;
1134
- }
1135
- const _pushable = pushable;
1136
- pushable = {
1137
- [Symbol.asyncIterator]() { return this; },
1138
- next() {
1139
- return _pushable.next();
1140
- },
1141
- throw(err) {
1142
- _pushable.throw(err);
1143
- if (onEnd != null) {
1144
- onEnd(err);
1145
- onEnd = undefined;
1146
- }
1147
- return { done: true };
1148
- },
1149
- return() {
1150
- _pushable.return();
1151
- if (onEnd != null) {
1152
- onEnd();
1153
- onEnd = undefined;
1154
- }
1155
- return { done: true };
1156
- },
1157
- push,
1158
- end(err) {
1159
- _pushable.end(err);
1160
- if (onEnd != null) {
1161
- onEnd(err);
1162
- onEnd = undefined;
1163
- }
1164
- return pushable;
1165
- },
1166
- get readableLength() {
1167
- return _pushable.readableLength;
1168
- }
1169
- };
1170
- return pushable;
1171
- }
1172
-
1173
- var fixedSize = class FixedFIFO {
1174
- constructor (hwm) {
1175
- if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
1176
- this.buffer = new Array(hwm);
1177
- this.mask = hwm - 1;
1178
- this.top = 0;
1179
- this.btm = 0;
1180
- this.next = null;
1181
- }
1182
-
1183
- push (data) {
1184
- if (this.buffer[this.top] !== undefined) return false
1185
- this.buffer[this.top] = data;
1186
- this.top = (this.top + 1) & this.mask;
1187
- return true
1188
- }
1189
-
1190
- shift () {
1191
- const last = this.buffer[this.btm];
1192
- if (last === undefined) return undefined
1193
- this.buffer[this.btm] = undefined;
1194
- this.btm = (this.btm + 1) & this.mask;
1195
- return last
1196
- }
1197
-
1198
- peek () {
1199
- return this.buffer[this.btm]
1200
- }
1201
-
1202
- isEmpty () {
1203
- return this.buffer[this.btm] === undefined
1204
- }
1205
- };
1206
-
1207
- const FixedFIFO = fixedSize;
1208
-
1209
- var fastFifo = class FastFIFO {
1210
- constructor (hwm) {
1211
- this.hwm = hwm || 16;
1212
- this.head = new FixedFIFO(this.hwm);
1213
- this.tail = this.head;
1214
- }
1215
-
1216
- push (val) {
1217
- if (!this.head.push(val)) {
1218
- const prev = this.head;
1219
- this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
1220
- this.head.push(val);
1221
- }
1222
- }
1223
-
1224
- shift () {
1225
- const val = this.tail.shift();
1226
- if (val === undefined && this.tail.next) {
1227
- const next = this.tail.next;
1228
- this.tail.next = null;
1229
- this.tail = next;
1230
- return this.tail.shift()
1231
- }
1232
- return val
1233
- }
1234
-
1235
- peek () {
1236
- return this.tail.peek()
1237
- }
1238
-
1239
- isEmpty () {
1240
- return this.head.isEmpty()
1241
- }
1242
- };
1243
-
1244
- const FIFO = fastFifo;
1245
-
1246
- var itPushable = (options) => {
1247
- options = options || {};
1248
- let onEnd;
1249
-
1250
- if (typeof options === 'function') {
1251
- onEnd = options;
1252
- options = {};
1253
- } else {
1254
- onEnd = options.onEnd;
1255
- }
1256
-
1257
- let buffer = new FIFO();
1258
- let pushable, onNext, ended;
1259
-
1260
- const waitNext = () => {
1261
- if (!buffer.isEmpty()) {
1262
- if (options.writev) {
1263
- let next;
1264
- const values = [];
1265
- while (!buffer.isEmpty()) {
1266
- next = buffer.shift();
1267
- if (next.error) throw next.error
1268
- values.push(next.value);
1269
- }
1270
- return { done: next.done, value: values }
1271
- }
1272
-
1273
- const next = buffer.shift();
1274
- if (next.error) throw next.error
1275
- return next
1276
- }
1277
-
1278
- if (ended) return { done: true }
1279
-
1280
- return new Promise((resolve, reject) => {
1281
- onNext = next => {
1282
- onNext = null;
1283
- if (next.error) {
1284
- reject(next.error);
1285
- } else {
1286
- if (options.writev && !next.done) {
1287
- resolve({ done: next.done, value: [next.value] });
1288
- } else {
1289
- resolve(next);
1290
- }
1291
- }
1292
- return pushable
1293
- };
1294
- })
1295
- };
1296
-
1297
- const bufferNext = next => {
1298
- if (onNext) return onNext(next)
1299
- buffer.push(next);
1300
- return pushable
1301
- };
1302
-
1303
- const bufferError = err => {
1304
- buffer = new FIFO();
1305
- if (onNext) return onNext({ error: err })
1306
- buffer.push({ error: err });
1307
- return pushable
1308
- };
1309
-
1310
- const push = value => {
1311
- if (ended) return pushable
1312
- return bufferNext({ done: false, value })
1313
- };
1314
- const end = err => {
1315
- if (ended) return pushable
1316
- ended = true;
1317
- return err ? bufferError(err) : bufferNext({ done: true })
1318
- };
1319
- const _return = () => {
1320
- buffer = new FIFO();
1321
- end();
1322
- return { done: true }
1323
- };
1324
- const _throw = err => {
1325
- end(err);
1326
- return { done: true }
1327
- };
1328
-
1329
- pushable = {
1330
- [Symbol.asyncIterator] () { return this },
1331
- next: waitNext,
1332
- return: _return,
1333
- throw: _throw,
1334
- push,
1335
- end
1336
- };
1337
-
1338
- if (!onEnd) return pushable
1339
-
1340
- const _pushable = pushable;
1341
-
1342
- pushable = {
1343
- [Symbol.asyncIterator] () { return this },
1344
- next () {
1345
- return _pushable.next()
1346
- },
1347
- throw (err) {
1348
- _pushable.throw(err);
1349
- if (onEnd) {
1350
- onEnd(err);
1351
- onEnd = null;
1352
- }
1353
- return { done: true }
1354
- },
1355
- return () {
1356
- _pushable.return();
1357
- if (onEnd) {
1358
- onEnd();
1359
- onEnd = null;
1360
- }
1361
- return { done: true }
1362
- },
1363
- push,
1364
- end (err) {
1365
- _pushable.end(err);
1366
- if (onEnd) {
1367
- onEnd(err);
1368
- onEnd = null;
1369
- }
1370
- return pushable
1371
- }
1372
- };
1373
-
1374
- return pushable
1375
- };
1376
-
1377
- const pushable = itPushable;
1378
-
1379
- /**
1380
- * Treat one or more iterables as a single iterable.
1381
- *
1382
- * Nb. sources are iterated over in parallel so the
1383
- * order of emitted items is not guaranteed.
1384
- *
1385
- * @template T
1386
- * @param {...AsyncIterable<T>|Iterable<T>} sources
1387
- * @returns {AsyncIterable<T>}
1388
- */
1389
- const merge = async function * (...sources) {
1390
- const output = pushable();
1391
-
1392
- setTimeout(async () => {
1393
- try {
1394
- await Promise.all(
1395
- sources.map(async (source) => {
1396
- for await (const item of source) {
1397
- output.push(item);
1398
- }
1399
- })
1400
- );
1401
-
1402
- output.end();
1403
- } catch (/** @type {any} */ err) {
1404
- output.end(err);
1405
- }
1406
- }, 0);
1407
-
1408
- yield * output;
1409
- };
1410
-
1411
- var itMerge = merge;
1412
-
1413
- const rawPipe = (...fns) => {
1414
- let res;
1415
- while (fns.length > 0) {
1416
- res = fns.shift()(res);
1417
- }
1418
- return res;
1419
- };
1420
- const isIterable = (obj) => {
1421
- return obj != null && (typeof obj[Symbol.asyncIterator] === 'function' ||
1422
- typeof obj[Symbol.iterator] === 'function' ||
1423
- typeof obj.next === 'function' // Probably, right?
1424
- );
1425
- };
1426
- const isDuplex = (obj) => {
1427
- return obj != null && typeof obj.sink === 'function' && isIterable(obj.source);
1428
- };
1429
- const duplexPipelineFn = (duplex) => {
1430
- return (source) => {
1431
- const p = duplex.sink(source);
1432
- if (p.then != null) {
1433
- const stream = pushable$1({
1434
- objectMode: true
1435
- });
1436
- p.then(() => {
1437
- stream.end();
1438
- }, (err) => {
1439
- stream.end(err);
1440
- });
1441
- const sourceWrap = async function* () {
1442
- yield* duplex.source;
1443
- stream.end();
1444
- };
1445
- return itMerge(stream, sourceWrap());
1446
- }
1447
- return duplex.source;
1448
- };
1449
- };
1450
- function pipe(first, ...rest) {
1451
- // Duplex at start: wrap in function and return duplex source
1452
- if (isDuplex(first)) {
1453
- const duplex = first;
1454
- first = () => duplex.source;
1455
- // Iterable at start: wrap in function
1456
- }
1457
- else if (isIterable(first)) {
1458
- const source = first;
1459
- first = () => source;
1460
- }
1461
- const fns = [first, ...rest];
1462
- if (fns.length > 1) {
1463
- // Duplex at end: use duplex sink
1464
- if (isDuplex(fns[fns.length - 1])) {
1465
- fns[fns.length - 1] = fns[fns.length - 1].sink;
1466
- }
1467
- }
1468
- if (fns.length > 2) {
1469
- // Duplex in the middle, consume source with duplex sink and return duplex source
1470
- for (let i = 1; i < fns.length - 1; i++) {
1471
- if (isDuplex(fns[i])) {
1472
- fns[i] = duplexPipelineFn(fns[i]);
1473
- }
1474
- }
1475
- }
1476
- return rawPipe(...fns);
1477
- }
1478
-
1479
- function groupByContentTopic(values) {
1480
- const groupedDecoders = new Map();
1481
- values.forEach((value) => {
1482
- let decs = groupedDecoders.get(value.contentTopic);
1483
- if (!decs) {
1484
- groupedDecoders.set(value.contentTopic, []);
1485
- decs = groupedDecoders.get(value.contentTopic);
1486
- }
1487
- decs.push(value);
1488
- });
1489
- return groupedDecoders;
1490
- }
1491
-
1492
- function selectConnection(connections) {
1493
- if (!connections.length)
1494
- return;
1495
- if (connections.length === 1)
1496
- return connections[0];
1497
- let latestConnection;
1498
- connections.forEach((connection) => {
1499
- if (connection.stat.status === "OPEN") {
1500
- if (!latestConnection) {
1501
- latestConnection = connection;
1502
- }
1503
- else if (connection.stat.timeline.open > latestConnection.stat.timeline.open) {
1504
- latestConnection = connection;
1505
- }
1506
- }
1507
- });
1508
- return latestConnection;
1509
- }
1510
-
1511
- const log$3 = debug("waku:select-peer");
1512
- /**
1513
- * Returns a pseudo-random peer that supports the given protocol.
1514
- * Useful for protocols such as store and light push
1515
- */
1516
- function selectRandomPeer(peers) {
1517
- if (peers.length === 0)
1518
- return;
1519
- const index = Math.round(Math.random() * (peers.length - 1));
1520
- return peers[index];
1521
- }
1522
- /**
1523
- * Returns the list of peers that supports the given protocol.
1524
- */
1525
- async function getPeersForProtocol(peerStore, protocols) {
1526
- const peers = [];
1527
- await peerStore.forEach((peer) => {
1528
- for (let i = 0; i < protocols.length; i++) {
1529
- if (peer.protocols.includes(protocols[i])) {
1530
- peers.push(peer);
1531
- break;
1532
- }
1533
- }
1534
- });
1535
- return peers;
1536
- }
1537
- async function selectPeerForProtocol(peerStore, protocols, peerId) {
1538
- let peer;
1539
- if (peerId) {
1540
- peer = await peerStore.get(peerId);
1541
- if (!peer) {
1542
- log$3(`Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`);
1543
- return;
1544
- }
1545
- }
1546
- else {
1547
- const peers = await getPeersForProtocol(peerStore, protocols);
1548
- peer = selectRandomPeer(peers);
1549
- if (!peer) {
1550
- log$3("Failed to find known peer that registers protocols", protocols);
1551
- return;
1552
- }
1553
- }
1554
- let protocol;
1555
- for (const codec of protocols) {
1556
- if (peer.protocols.includes(codec)) {
1557
- protocol = codec;
1558
- // Do not break as we want to keep the last value
1559
- }
1560
- }
1561
- log$3(`Using codec ${protocol}`);
1562
- if (!protocol) {
1563
- log$3(`Peer does not register required protocols: ${peer.id.toString()}`, protocols);
1564
- return;
1565
- }
1566
- return { peer, protocol };
1567
- }
1568
-
1569
- const EmptyMessage = {
1570
- payload: undefined,
1571
- contentTopic: undefined,
1572
- version: undefined,
1573
- timestamp: undefined,
1574
- rateLimitProof: undefined,
1575
- };
1576
- function toProtoMessage(wire) {
1577
- return { ...EmptyMessage, ...wire };
1578
- }
1579
-
1580
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
1581
- // require the crypto API and do not support built-in fallback to lower quality random number
1582
- // generators (like Math.random()).
1583
- var getRandomValues;
1584
- var rnds8 = new Uint8Array(16);
1585
- function rng() {
1586
- // lazy load so that environments that need to polyfill have a chance to do so
1587
- if (!getRandomValues) {
1588
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
1589
- // find the complete implementation of crypto (msCrypto) on IE11.
1590
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
1591
-
1592
- if (!getRandomValues) {
1593
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
1594
- }
1595
- }
1596
-
1597
- return getRandomValues(rnds8);
1598
- }
1599
-
1600
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1601
-
1602
- function validate(uuid) {
1603
- return typeof uuid === 'string' && REGEX.test(uuid);
1604
- }
1605
-
1606
- /**
1607
- * Convert array of 16 byte values to UUID string format of the form:
1608
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1609
- */
1610
-
1611
- var byteToHex = [];
1612
-
1613
- for (var i = 0; i < 256; ++i) {
1614
- byteToHex.push((i + 0x100).toString(16).substr(1));
1615
- }
1616
-
1617
- function stringify(arr) {
1618
- var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1619
- // Note: Be careful editing this code! It's been tuned for performance
1620
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
1621
- var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
1622
- // of the following:
1623
- // - One or more input array values don't map to a hex octet (leading to
1624
- // "undefined" in the uuid)
1625
- // - Invalid input values for the RFC `version` or `variant` fields
1626
-
1627
- if (!validate(uuid)) {
1628
- throw TypeError('Stringified UUID is invalid');
1629
- }
1630
-
1631
- return uuid;
1632
- }
1633
-
1634
- function parse(uuid) {
1635
- if (!validate(uuid)) {
1636
- throw TypeError('Invalid UUID');
1637
- }
1638
-
1639
- var v;
1640
- var arr = new Uint8Array(16); // Parse ########-....-....-....-............
1641
-
1642
- arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
1643
- arr[1] = v >>> 16 & 0xff;
1644
- arr[2] = v >>> 8 & 0xff;
1645
- arr[3] = v & 0xff; // Parse ........-####-....-....-............
1646
-
1647
- arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
1648
- arr[5] = v & 0xff; // Parse ........-....-####-....-............
1649
-
1650
- arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
1651
- arr[7] = v & 0xff; // Parse ........-....-....-####-............
1652
-
1653
- arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
1654
- arr[9] = v & 0xff; // Parse ........-....-....-....-############
1655
- // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
1656
-
1657
- arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
1658
- arr[11] = v / 0x100000000 & 0xff;
1659
- arr[12] = v >>> 24 & 0xff;
1660
- arr[13] = v >>> 16 & 0xff;
1661
- arr[14] = v >>> 8 & 0xff;
1662
- arr[15] = v & 0xff;
1663
- return arr;
1664
- }
1665
-
1666
- function stringToBytes(str) {
1667
- str = unescape(encodeURIComponent(str)); // UTF8 escape
1668
-
1669
- var bytes = [];
1670
-
1671
- for (var i = 0; i < str.length; ++i) {
1672
- bytes.push(str.charCodeAt(i));
1673
- }
1674
-
1675
- return bytes;
1676
- }
1677
-
1678
- var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
1679
- var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
1680
- function v35 (name, version, hashfunc) {
1681
- function generateUUID(value, namespace, buf, offset) {
1682
- if (typeof value === 'string') {
1683
- value = stringToBytes(value);
1684
- }
1685
-
1686
- if (typeof namespace === 'string') {
1687
- namespace = parse(namespace);
1688
- }
1689
-
1690
- if (namespace.length !== 16) {
1691
- throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
1692
- } // Compute hash of namespace and value, Per 4.3
1693
- // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
1694
- // hashfunc([...namespace, ... value])`
1695
-
1696
-
1697
- var bytes = new Uint8Array(16 + value.length);
1698
- bytes.set(namespace);
1699
- bytes.set(value, namespace.length);
1700
- bytes = hashfunc(bytes);
1701
- bytes[6] = bytes[6] & 0x0f | version;
1702
- bytes[8] = bytes[8] & 0x3f | 0x80;
1703
-
1704
- if (buf) {
1705
- offset = offset || 0;
1706
-
1707
- for (var i = 0; i < 16; ++i) {
1708
- buf[offset + i] = bytes[i];
1709
- }
1710
-
1711
- return buf;
1712
- }
1713
-
1714
- return stringify(bytes);
1715
- } // Function#name is not settable on some platforms (#270)
1716
-
1717
-
1718
- try {
1719
- generateUUID.name = name; // eslint-disable-next-line no-empty
1720
- } catch (err) {} // For CommonJS default export support
1721
-
1722
-
1723
- generateUUID.DNS = DNS;
1724
- generateUUID.URL = URL;
1725
- return generateUUID;
1726
- }
1727
-
1728
- /*
1729
- * Browser-compatible JavaScript MD5
1730
- *
1731
- * Modification of JavaScript MD5
1732
- * https://github.com/blueimp/JavaScript-MD5
1733
- *
1734
- * Copyright 2011, Sebastian Tschan
1735
- * https://blueimp.net
1736
- *
1737
- * Licensed under the MIT license:
1738
- * https://opensource.org/licenses/MIT
1739
- *
1740
- * Based on
1741
- * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
1742
- * Digest Algorithm, as defined in RFC 1321.
1743
- * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
1744
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
1745
- * Distributed under the BSD License
1746
- * See http://pajhome.org.uk/crypt/md5 for more info.
1747
- */
1748
- function md5(bytes) {
1749
- if (typeof bytes === 'string') {
1750
- var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
1751
-
1752
- bytes = new Uint8Array(msg.length);
1753
-
1754
- for (var i = 0; i < msg.length; ++i) {
1755
- bytes[i] = msg.charCodeAt(i);
1756
- }
1757
- }
1758
-
1759
- return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
1760
- }
1761
- /*
1762
- * Convert an array of little-endian words to an array of bytes
1763
- */
1764
-
1765
-
1766
- function md5ToHexEncodedArray(input) {
1767
- var output = [];
1768
- var length32 = input.length * 32;
1769
- var hexTab = '0123456789abcdef';
1770
-
1771
- for (var i = 0; i < length32; i += 8) {
1772
- var x = input[i >> 5] >>> i % 32 & 0xff;
1773
- var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
1774
- output.push(hex);
1775
- }
1776
-
1777
- return output;
1778
- }
1779
- /**
1780
- * Calculate output length with padding and bit length
1781
- */
1782
-
1783
-
1784
- function getOutputLength(inputLength8) {
1785
- return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
1786
- }
1787
- /*
1788
- * Calculate the MD5 of an array of little-endian words, and a bit length.
1789
- */
1790
-
1791
-
1792
- function wordsToMd5(x, len) {
1793
- /* append padding */
1794
- x[len >> 5] |= 0x80 << len % 32;
1795
- x[getOutputLength(len) - 1] = len;
1796
- var a = 1732584193;
1797
- var b = -271733879;
1798
- var c = -1732584194;
1799
- var d = 271733878;
1800
-
1801
- for (var i = 0; i < x.length; i += 16) {
1802
- var olda = a;
1803
- var oldb = b;
1804
- var oldc = c;
1805
- var oldd = d;
1806
- a = md5ff(a, b, c, d, x[i], 7, -680876936);
1807
- d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
1808
- c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
1809
- b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
1810
- a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
1811
- d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
1812
- c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
1813
- b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
1814
- a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
1815
- d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
1816
- c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
1817
- b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
1818
- a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
1819
- d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
1820
- c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
1821
- b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
1822
- a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
1823
- d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
1824
- c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
1825
- b = md5gg(b, c, d, a, x[i], 20, -373897302);
1826
- a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
1827
- d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
1828
- c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
1829
- b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
1830
- a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
1831
- d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
1832
- c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
1833
- b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
1834
- a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
1835
- d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
1836
- c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
1837
- b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
1838
- a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
1839
- d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
1840
- c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
1841
- b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
1842
- a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
1843
- d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
1844
- c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
1845
- b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
1846
- a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
1847
- d = md5hh(d, a, b, c, x[i], 11, -358537222);
1848
- c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
1849
- b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
1850
- a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
1851
- d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
1852
- c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
1853
- b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
1854
- a = md5ii(a, b, c, d, x[i], 6, -198630844);
1855
- d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
1856
- c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
1857
- b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
1858
- a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
1859
- d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
1860
- c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
1861
- b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
1862
- a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
1863
- d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
1864
- c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
1865
- b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
1866
- a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
1867
- d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
1868
- c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
1869
- b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
1870
- a = safeAdd(a, olda);
1871
- b = safeAdd(b, oldb);
1872
- c = safeAdd(c, oldc);
1873
- d = safeAdd(d, oldd);
1874
- }
1875
-
1876
- return [a, b, c, d];
1877
- }
1878
- /*
1879
- * Convert an array bytes to an array of little-endian words
1880
- * Characters >255 have their high-byte silently ignored.
1881
- */
1882
-
1883
-
1884
- function bytesToWords(input) {
1885
- if (input.length === 0) {
1886
- return [];
1887
- }
1888
-
1889
- var length8 = input.length * 8;
1890
- var output = new Uint32Array(getOutputLength(length8));
1891
-
1892
- for (var i = 0; i < length8; i += 8) {
1893
- output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
1894
- }
1895
-
1896
- return output;
1897
- }
1898
- /*
1899
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
1900
- * to work around bugs in some JS interpreters.
1901
- */
1902
-
1903
-
1904
- function safeAdd(x, y) {
1905
- var lsw = (x & 0xffff) + (y & 0xffff);
1906
- var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1907
- return msw << 16 | lsw & 0xffff;
1908
- }
1909
- /*
1910
- * Bitwise rotate a 32-bit number to the left.
1911
- */
1912
-
1913
-
1914
- function bitRotateLeft(num, cnt) {
1915
- return num << cnt | num >>> 32 - cnt;
1916
- }
1917
- /*
1918
- * These functions implement the four basic operations the algorithm uses.
1919
- */
1920
-
1921
-
1922
- function md5cmn(q, a, b, x, s, t) {
1923
- return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
1924
- }
1925
-
1926
- function md5ff(a, b, c, d, x, s, t) {
1927
- return md5cmn(b & c | ~b & d, a, b, x, s, t);
1928
- }
1929
-
1930
- function md5gg(a, b, c, d, x, s, t) {
1931
- return md5cmn(b & d | c & ~d, a, b, x, s, t);
1932
- }
1933
-
1934
- function md5hh(a, b, c, d, x, s, t) {
1935
- return md5cmn(b ^ c ^ d, a, b, x, s, t);
1936
- }
1937
-
1938
- function md5ii(a, b, c, d, x, s, t) {
1939
- return md5cmn(c ^ (b | ~d), a, b, x, s, t);
1940
- }
1941
-
1942
- v35('v3', 0x30, md5);
1943
-
1944
- function v4(options, buf, offset) {
1945
- options = options || {};
1946
- var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1947
-
1948
- rnds[6] = rnds[6] & 0x0f | 0x40;
1949
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
1950
-
1951
- if (buf) {
1952
- offset = offset || 0;
1953
-
1954
- for (var i = 0; i < 16; ++i) {
1955
- buf[offset + i] = rnds[i];
1956
- }
1957
-
1958
- return buf;
1959
- }
1960
-
1961
- return stringify(rnds);
1962
- }
1963
-
1964
- // Adapted from Chris Veness' SHA1 code at
1965
- // http://www.movable-type.co.uk/scripts/sha1.html
1966
- function f(s, x, y, z) {
1967
- switch (s) {
1968
- case 0:
1969
- return x & y ^ ~x & z;
1970
-
1971
- case 1:
1972
- return x ^ y ^ z;
1973
-
1974
- case 2:
1975
- return x & y ^ x & z ^ y & z;
1976
-
1977
- case 3:
1978
- return x ^ y ^ z;
1979
- }
1980
- }
1981
-
1982
- function ROTL(x, n) {
1983
- return x << n | x >>> 32 - n;
1984
- }
1985
-
1986
- function sha1(bytes) {
1987
- var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
1988
- var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
1989
-
1990
- if (typeof bytes === 'string') {
1991
- var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
1992
-
1993
- bytes = [];
1994
-
1995
- for (var i = 0; i < msg.length; ++i) {
1996
- bytes.push(msg.charCodeAt(i));
1997
- }
1998
- } else if (!Array.isArray(bytes)) {
1999
- // Convert Array-like to Array
2000
- bytes = Array.prototype.slice.call(bytes);
2001
- }
2002
-
2003
- bytes.push(0x80);
2004
- var l = bytes.length / 4 + 2;
2005
- var N = Math.ceil(l / 16);
2006
- var M = new Array(N);
2007
-
2008
- for (var _i = 0; _i < N; ++_i) {
2009
- var arr = new Uint32Array(16);
2010
-
2011
- for (var j = 0; j < 16; ++j) {
2012
- arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
2013
- }
2014
-
2015
- M[_i] = arr;
2016
- }
2017
-
2018
- M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
2019
- M[N - 1][14] = Math.floor(M[N - 1][14]);
2020
- M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
2021
-
2022
- for (var _i2 = 0; _i2 < N; ++_i2) {
2023
- var W = new Uint32Array(80);
2024
-
2025
- for (var t = 0; t < 16; ++t) {
2026
- W[t] = M[_i2][t];
2027
- }
2028
-
2029
- for (var _t = 16; _t < 80; ++_t) {
2030
- W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
2031
- }
2032
-
2033
- var a = H[0];
2034
- var b = H[1];
2035
- var c = H[2];
2036
- var d = H[3];
2037
- var e = H[4];
2038
-
2039
- for (var _t2 = 0; _t2 < 80; ++_t2) {
2040
- var s = Math.floor(_t2 / 20);
2041
- var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
2042
- e = d;
2043
- d = c;
2044
- c = ROTL(b, 30) >>> 0;
2045
- b = a;
2046
- a = T;
2047
- }
2048
-
2049
- H[0] = H[0] + a >>> 0;
2050
- H[1] = H[1] + b >>> 0;
2051
- H[2] = H[2] + c >>> 0;
2052
- H[3] = H[3] + d >>> 0;
2053
- H[4] = H[4] + e >>> 0;
2054
- }
2055
-
2056
- return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
2057
- }
2058
-
2059
- v35('v5', 0x50, sha1);
2060
-
2061
- /* eslint-disable import/export */
2062
- var FilterRequest;
2063
- (function (FilterRequest) {
2064
- (function (ContentFilter) {
2065
- let _codec;
2066
- ContentFilter.codec = () => {
2067
- if (_codec == null) {
2068
- _codec = message((obj, writer, opts = {}) => {
2069
- if (opts.lengthDelimited !== false) {
2070
- writer.fork();
2071
- }
2072
- if (obj.contentTopic != null) {
2073
- writer.uint32(10);
2074
- writer.string(obj.contentTopic);
2075
- }
2076
- if (opts.lengthDelimited !== false) {
2077
- writer.ldelim();
2078
- }
2079
- }, (reader, length) => {
2080
- const obj = {};
2081
- const end = length == null ? reader.len : reader.pos + length;
2082
- while (reader.pos < end) {
2083
- const tag = reader.uint32();
2084
- switch (tag >>> 3) {
2085
- case 1:
2086
- obj.contentTopic = reader.string();
2087
- break;
2088
- default:
2089
- reader.skipType(tag & 7);
2090
- break;
2091
- }
2092
- }
2093
- return obj;
2094
- });
2095
- }
2096
- return _codec;
2097
- };
2098
- ContentFilter.encode = (obj) => {
2099
- return encodeMessage(obj, ContentFilter.codec());
2100
- };
2101
- ContentFilter.decode = (buf) => {
2102
- return decodeMessage(buf, ContentFilter.codec());
2103
- };
2104
- })(FilterRequest.ContentFilter || (FilterRequest.ContentFilter = {}));
2105
- let _codec;
2106
- FilterRequest.codec = () => {
2107
- if (_codec == null) {
2108
- _codec = message((obj, writer, opts = {}) => {
2109
- if (opts.lengthDelimited !== false) {
2110
- writer.fork();
2111
- }
2112
- if (obj.subscribe != null) {
2113
- writer.uint32(8);
2114
- writer.bool(obj.subscribe);
2115
- }
2116
- if (obj.topic != null) {
2117
- writer.uint32(18);
2118
- writer.string(obj.topic);
2119
- }
2120
- if (obj.contentFilters != null) {
2121
- for (const value of obj.contentFilters) {
2122
- writer.uint32(26);
2123
- FilterRequest.ContentFilter.codec().encode(value, writer);
2124
- }
2125
- }
2126
- else {
2127
- throw new Error('Protocol error: required field "contentFilters" was not found in object');
2128
- }
2129
- if (opts.lengthDelimited !== false) {
2130
- writer.ldelim();
2131
- }
2132
- }, (reader, length) => {
2133
- const obj = {
2134
- contentFilters: [],
2135
- };
2136
- const end = length == null ? reader.len : reader.pos + length;
2137
- while (reader.pos < end) {
2138
- const tag = reader.uint32();
2139
- switch (tag >>> 3) {
2140
- case 1:
2141
- obj.subscribe = reader.bool();
2142
- break;
2143
- case 2:
2144
- obj.topic = reader.string();
2145
- break;
2146
- case 3:
2147
- obj.contentFilters.push(FilterRequest.ContentFilter.codec().decode(reader, reader.uint32()));
2148
- break;
2149
- default:
2150
- reader.skipType(tag & 7);
2151
- break;
2152
- }
2153
- }
2154
- return obj;
2155
- });
2156
- }
2157
- return _codec;
2158
- };
2159
- FilterRequest.encode = (obj) => {
2160
- return encodeMessage(obj, FilterRequest.codec());
2161
- };
2162
- FilterRequest.decode = (buf) => {
2163
- return decodeMessage(buf, FilterRequest.codec());
2164
- };
2165
- })(FilterRequest || (FilterRequest = {}));
2166
- var MessagePush;
2167
- (function (MessagePush) {
2168
- let _codec;
2169
- MessagePush.codec = () => {
2170
- if (_codec == null) {
2171
- _codec = message((obj, writer, opts = {}) => {
2172
- if (opts.lengthDelimited !== false) {
2173
- writer.fork();
2174
- }
2175
- if (obj.messages != null) {
2176
- for (const value of obj.messages) {
2177
- writer.uint32(10);
2178
- WakuMessage$2.codec().encode(value, writer);
2179
- }
2180
- }
2181
- else {
2182
- throw new Error('Protocol error: required field "messages" was not found in object');
2183
- }
2184
- if (opts.lengthDelimited !== false) {
2185
- writer.ldelim();
2186
- }
2187
- }, (reader, length) => {
2188
- const obj = {
2189
- messages: [],
2190
- };
2191
- const end = length == null ? reader.len : reader.pos + length;
2192
- while (reader.pos < end) {
2193
- const tag = reader.uint32();
2194
- switch (tag >>> 3) {
2195
- case 1:
2196
- obj.messages.push(WakuMessage$2.codec().decode(reader, reader.uint32()));
2197
- break;
2198
- default:
2199
- reader.skipType(tag & 7);
2200
- break;
2201
- }
2202
- }
2203
- return obj;
2204
- });
2205
- }
2206
- return _codec;
2207
- };
2208
- MessagePush.encode = (obj) => {
2209
- return encodeMessage(obj, MessagePush.codec());
2210
- };
2211
- MessagePush.decode = (buf) => {
2212
- return decodeMessage(buf, MessagePush.codec());
2213
- };
2214
- })(MessagePush || (MessagePush = {}));
2215
- var FilterRPC$1;
2216
- (function (FilterRPC) {
2217
- let _codec;
2218
- FilterRPC.codec = () => {
2219
- if (_codec == null) {
2220
- _codec = message((obj, writer, opts = {}) => {
2221
- if (opts.lengthDelimited !== false) {
2222
- writer.fork();
2223
- }
2224
- if (obj.requestId != null) {
2225
- writer.uint32(10);
2226
- writer.string(obj.requestId);
2227
- }
2228
- if (obj.request != null) {
2229
- writer.uint32(18);
2230
- FilterRequest.codec().encode(obj.request, writer);
2231
- }
2232
- if (obj.push != null) {
2233
- writer.uint32(26);
2234
- MessagePush.codec().encode(obj.push, writer);
2235
- }
2236
- if (opts.lengthDelimited !== false) {
2237
- writer.ldelim();
2238
- }
2239
- }, (reader, length) => {
2240
- const obj = {};
2241
- const end = length == null ? reader.len : reader.pos + length;
2242
- while (reader.pos < end) {
2243
- const tag = reader.uint32();
2244
- switch (tag >>> 3) {
2245
- case 1:
2246
- obj.requestId = reader.string();
2247
- break;
2248
- case 2:
2249
- obj.request = FilterRequest.codec().decode(reader, reader.uint32());
2250
- break;
2251
- case 3:
2252
- obj.push = MessagePush.codec().decode(reader, reader.uint32());
2253
- break;
2254
- default:
2255
- reader.skipType(tag & 7);
2256
- break;
2257
- }
2258
- }
2259
- return obj;
2260
- });
2261
- }
2262
- return _codec;
2263
- };
2264
- FilterRPC.encode = (obj) => {
2265
- return encodeMessage(obj, FilterRPC.codec());
2266
- };
2267
- FilterRPC.decode = (buf) => {
2268
- return decodeMessage(buf, FilterRPC.codec());
2269
- };
2270
- })(FilterRPC$1 || (FilterRPC$1 = {}));
2271
- var RateLimitProof$2;
2272
- (function (RateLimitProof) {
2273
- let _codec;
2274
- RateLimitProof.codec = () => {
2275
- if (_codec == null) {
2276
- _codec = message((obj, writer, opts = {}) => {
2277
- if (opts.lengthDelimited !== false) {
2278
- writer.fork();
2279
- }
2280
- if (obj.proof != null) {
2281
- writer.uint32(10);
2282
- writer.bytes(obj.proof);
2283
- }
2284
- else {
2285
- throw new Error('Protocol error: required field "proof" was not found in object');
2286
- }
2287
- if (obj.merkleRoot != null) {
2288
- writer.uint32(18);
2289
- writer.bytes(obj.merkleRoot);
2290
- }
2291
- else {
2292
- throw new Error('Protocol error: required field "merkleRoot" was not found in object');
2293
- }
2294
- if (obj.epoch != null) {
2295
- writer.uint32(26);
2296
- writer.bytes(obj.epoch);
2297
- }
2298
- else {
2299
- throw new Error('Protocol error: required field "epoch" was not found in object');
2300
- }
2301
- if (obj.shareX != null) {
2302
- writer.uint32(34);
2303
- writer.bytes(obj.shareX);
2304
- }
2305
- else {
2306
- throw new Error('Protocol error: required field "shareX" was not found in object');
2307
- }
2308
- if (obj.shareY != null) {
2309
- writer.uint32(42);
2310
- writer.bytes(obj.shareY);
2311
- }
2312
- else {
2313
- throw new Error('Protocol error: required field "shareY" was not found in object');
2314
- }
2315
- if (obj.nullifier != null) {
2316
- writer.uint32(50);
2317
- writer.bytes(obj.nullifier);
2318
- }
2319
- else {
2320
- throw new Error('Protocol error: required field "nullifier" was not found in object');
2321
- }
2322
- if (obj.rlnIdentifier != null) {
2323
- writer.uint32(58);
2324
- writer.bytes(obj.rlnIdentifier);
2325
- }
2326
- else {
2327
- throw new Error('Protocol error: required field "rlnIdentifier" was not found in object');
2328
- }
2329
- if (opts.lengthDelimited !== false) {
2330
- writer.ldelim();
2331
- }
2332
- }, (reader, length) => {
2333
- const obj = {
2334
- proof: new Uint8Array(0),
2335
- merkleRoot: new Uint8Array(0),
2336
- epoch: new Uint8Array(0),
2337
- shareX: new Uint8Array(0),
2338
- shareY: new Uint8Array(0),
2339
- nullifier: new Uint8Array(0),
2340
- rlnIdentifier: new Uint8Array(0),
2341
- };
2342
- const end = length == null ? reader.len : reader.pos + length;
2343
- while (reader.pos < end) {
2344
- const tag = reader.uint32();
2345
- switch (tag >>> 3) {
2346
- case 1:
2347
- obj.proof = reader.bytes();
2348
- break;
2349
- case 2:
2350
- obj.merkleRoot = reader.bytes();
2351
- break;
2352
- case 3:
2353
- obj.epoch = reader.bytes();
2354
- break;
2355
- case 4:
2356
- obj.shareX = reader.bytes();
2357
- break;
2358
- case 5:
2359
- obj.shareY = reader.bytes();
2360
- break;
2361
- case 6:
2362
- obj.nullifier = reader.bytes();
2363
- break;
2364
- case 7:
2365
- obj.rlnIdentifier = reader.bytes();
2366
- break;
2367
- default:
2368
- reader.skipType(tag & 7);
2369
- break;
2370
- }
2371
- }
2372
- if (obj.proof == null) {
2373
- throw new Error('Protocol error: value for required field "proof" was not found in protobuf');
2374
- }
2375
- if (obj.merkleRoot == null) {
2376
- throw new Error('Protocol error: value for required field "merkleRoot" was not found in protobuf');
2377
- }
2378
- if (obj.epoch == null) {
2379
- throw new Error('Protocol error: value for required field "epoch" was not found in protobuf');
2380
- }
2381
- if (obj.shareX == null) {
2382
- throw new Error('Protocol error: value for required field "shareX" was not found in protobuf');
2383
- }
2384
- if (obj.shareY == null) {
2385
- throw new Error('Protocol error: value for required field "shareY" was not found in protobuf');
2386
- }
2387
- if (obj.nullifier == null) {
2388
- throw new Error('Protocol error: value for required field "nullifier" was not found in protobuf');
2389
- }
2390
- if (obj.rlnIdentifier == null) {
2391
- throw new Error('Protocol error: value for required field "rlnIdentifier" was not found in protobuf');
2392
- }
2393
- return obj;
2394
- });
2395
- }
2396
- return _codec;
2397
- };
2398
- RateLimitProof.encode = (obj) => {
2399
- return encodeMessage(obj, RateLimitProof.codec());
2400
- };
2401
- RateLimitProof.decode = (buf) => {
2402
- return decodeMessage(buf, RateLimitProof.codec());
2403
- };
2404
- })(RateLimitProof$2 || (RateLimitProof$2 = {}));
2405
- var WakuMessage$2;
2406
- (function (WakuMessage) {
2407
- let _codec;
2408
- WakuMessage.codec = () => {
2409
- if (_codec == null) {
2410
- _codec = message((obj, writer, opts = {}) => {
2411
- if (opts.lengthDelimited !== false) {
2412
- writer.fork();
2413
- }
2414
- if (obj.payload != null) {
2415
- writer.uint32(10);
2416
- writer.bytes(obj.payload);
2417
- }
2418
- if (obj.contentTopic != null) {
2419
- writer.uint32(18);
2420
- writer.string(obj.contentTopic);
2421
- }
2422
- if (obj.version != null) {
2423
- writer.uint32(24);
2424
- writer.uint32(obj.version);
2425
- }
2426
- if (obj.timestampDeprecated != null) {
2427
- writer.uint32(33);
2428
- writer.double(obj.timestampDeprecated);
2429
- }
2430
- if (obj.timestamp != null) {
2431
- writer.uint32(80);
2432
- writer.sint64(obj.timestamp);
2433
- }
2434
- if (obj.rateLimitProof != null) {
2435
- writer.uint32(170);
2436
- RateLimitProof$2.codec().encode(obj.rateLimitProof, writer);
2437
- }
2438
- if (opts.lengthDelimited !== false) {
2439
- writer.ldelim();
2440
- }
2441
- }, (reader, length) => {
2442
- const obj = {};
2443
- const end = length == null ? reader.len : reader.pos + length;
2444
- while (reader.pos < end) {
2445
- const tag = reader.uint32();
2446
- switch (tag >>> 3) {
2447
- case 1:
2448
- obj.payload = reader.bytes();
2449
- break;
2450
- case 2:
2451
- obj.contentTopic = reader.string();
2452
- break;
2453
- case 3:
2454
- obj.version = reader.uint32();
2455
- break;
2456
- case 4:
2457
- obj.timestampDeprecated = reader.double();
2458
- break;
2459
- case 10:
2460
- obj.timestamp = reader.sint64();
2461
- break;
2462
- case 21:
2463
- obj.rateLimitProof = RateLimitProof$2.codec().decode(reader, reader.uint32());
2464
- break;
2465
- default:
2466
- reader.skipType(tag & 7);
2467
- break;
2468
- }
2469
- }
2470
- return obj;
2471
- });
2472
- }
2473
- return _codec;
2474
- };
2475
- WakuMessage.encode = (obj) => {
2476
- return encodeMessage(obj, WakuMessage.codec());
2477
- };
2478
- WakuMessage.decode = (buf) => {
2479
- return decodeMessage(buf, WakuMessage.codec());
2480
- };
2481
- })(WakuMessage$2 || (WakuMessage$2 = {}));
2482
-
2483
- /**
2484
- * FilterRPC represents a message conforming to the Waku Filter protocol
2485
- */
2486
- class FilterRPC {
2487
- constructor(proto) {
2488
- this.proto = proto;
2489
- }
2490
- static createRequest(topic, contentFilters, requestId, subscribe = true) {
2491
- return new FilterRPC({
2492
- requestId: requestId || v4(),
2493
- request: {
2494
- subscribe,
2495
- topic,
2496
- contentFilters,
2497
- },
2498
- push: undefined,
2499
- });
2500
- }
2501
- /**
2502
- *
2503
- * @param bytes Uint8Array of bytes from a FilterRPC message
2504
- * @returns FilterRPC
2505
- */
2506
- static decode(bytes) {
2507
- const res = FilterRPC$1.decode(bytes);
2508
- return new FilterRPC(res);
2509
- }
2510
- /**
2511
- * Encode the current FilterRPC request to bytes
2512
- * @returns Uint8Array
2513
- */
2514
- encode() {
2515
- return FilterRPC$1.encode(this.proto);
2516
- }
2517
- get push() {
2518
- return this.proto.push;
2519
- }
2520
- get requestId() {
2521
- return this.proto.requestId;
2522
- }
2523
- }
2524
-
2525
- const FilterCodec = "/vac/waku/filter/2.0.0-beta1";
2526
- const log$2 = debug("waku:filter");
2527
- /**
2528
- * Implements client side of the [Waku v2 Filter protocol](https://rfc.vac.dev/spec/12/).
2529
- *
2530
- * Note this currently only works in NodeJS when the Waku node is listening on a port, see:
2531
- * - https://github.com/status-im/go-waku/issues/245
2532
- * - https://github.com/status-im/nwaku/issues/948
2533
- */
2534
- class WakuFilter {
2535
- constructor(libp2p, options) {
2536
- this.libp2p = libp2p;
2537
- this.subscriptions = new Map();
2538
- this.decoders = new Map();
2539
- this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;
2540
- this.libp2p
2541
- .handle(FilterCodec, this.onRequest.bind(this))
2542
- .catch((e) => log$2("Failed to register filter protocol", e));
2543
- }
2544
- /**
2545
- * @param decoders Array of Decoders to use to decode messages, it also specifies the content topics.
2546
- * @param callback A function that will be called on each message returned by the filter.
2547
- * @param opts The FilterSubscriptionOpts used to narrow which messages are returned, and which peer to connect to.
2548
- * @returns Unsubscribe function that can be used to end the subscription.
2549
- */
2550
- async subscribe(decoders, callback, opts) {
2551
- const topic = opts?.pubSubTopic ?? this.pubSubTopic;
2552
- const groupedDecoders = groupByContentTopic(decoders);
2553
- const contentTopics = Array.from(groupedDecoders.keys());
2554
- const contentFilters = contentTopics.map((contentTopic) => ({
2555
- contentTopic,
2556
- }));
2557
- const request = FilterRPC.createRequest(topic, contentFilters, undefined, true);
2558
- const requestId = request.requestId;
2559
- if (!requestId)
2560
- throw new Error("Internal error: createRequest expected to set `requestId`");
2561
- const peer = await this.getPeer(opts?.peerId);
2562
- const stream = await this.newStream(peer);
2563
- try {
2564
- const res = await pipe([request.encode()], encode(), stream, decode(), async (source) => await itAll(source));
2565
- log$2("response", res);
2566
- }
2567
- catch (e) {
2568
- log$2("Error subscribing to peer ", peer.id.toString(), "for content topics", contentTopics, ": ", e);
2569
- throw e;
2570
- }
2571
- this.addDecoders(groupedDecoders);
2572
- this.addCallback(requestId, callback);
2573
- return async () => {
2574
- await this.unsubscribe(topic, contentFilters, requestId, peer);
2575
- this.deleteDecoders(groupedDecoders);
2576
- this.deleteCallback(requestId);
2577
- };
2578
- }
2579
- onRequest(streamData) {
2580
- log$2("Receiving message push");
2581
- try {
2582
- pipe(streamData.stream, decode(), async (source) => {
2583
- for await (const bytes of source) {
2584
- const res = FilterRPC.decode(bytes.slice());
2585
- if (res.requestId && res.push?.messages?.length) {
2586
- await this.pushMessages(res.requestId, res.push.messages);
2587
- }
2588
- }
2589
- }).then(() => {
2590
- log$2("Receiving pipe closed.");
2591
- }, (e) => {
2592
- log$2("Error with receiving pipe", e);
2593
- });
2594
- }
2595
- catch (e) {
2596
- log$2("Error decoding message", e);
2597
- }
2598
- }
2599
- async pushMessages(requestId, messages) {
2600
- const callback = this.subscriptions.get(requestId);
2601
- if (!callback) {
2602
- log$2(`No callback registered for request ID ${requestId}`);
2603
- return;
2604
- }
2605
- for (const protoMessage of messages) {
2606
- const contentTopic = protoMessage.contentTopic;
2607
- if (!contentTopic) {
2608
- log$2("Message has no content topic, skipping");
2609
- return;
2610
- }
2611
- const decoders = this.decoders.get(contentTopic);
2612
- if (!decoders) {
2613
- log$2("No decoder for", contentTopic);
2614
- return;
2615
- }
2616
- let msg;
2617
- // We don't want to wait for decoding failure, just attempt to decode
2618
- // all messages and do the call back on the one that works
2619
- // noinspection ES6MissingAwait
2620
- decoders.forEach(async (dec) => {
2621
- if (msg)
2622
- return;
2623
- const decoded = await dec.fromProtoObj(toProtoMessage(protoMessage));
2624
- if (!decoded) {
2625
- log$2("Not able to decode message");
2626
- return;
2627
- }
2628
- // This is just to prevent more decoding attempt
2629
- // TODO: Could be better if we were to abort promises
2630
- msg = decoded;
2631
- await callback(decoded);
2632
- });
2633
- }
2634
- }
2635
- addCallback(requestId, callback) {
2636
- this.subscriptions.set(requestId, callback);
2637
- }
2638
- deleteCallback(requestId) {
2639
- this.subscriptions.delete(requestId);
2640
- }
2641
- addDecoders(decoders) {
2642
- decoders.forEach((decoders, contentTopic) => {
2643
- const currDecs = this.decoders.get(contentTopic);
2644
- if (!currDecs) {
2645
- this.decoders.set(contentTopic, new Set(decoders));
2646
- }
2647
- else {
2648
- this.decoders.set(contentTopic, new Set([...currDecs, ...decoders]));
2649
- }
2650
- });
2651
- }
2652
- deleteDecoders(decoders) {
2653
- decoders.forEach((decoders, contentTopic) => {
2654
- const currDecs = this.decoders.get(contentTopic);
2655
- if (currDecs) {
2656
- decoders.forEach((dec) => {
2657
- currDecs.delete(dec);
2658
- });
2659
- }
2660
- });
2661
- }
2662
- async unsubscribe(topic, contentFilters, requestId, peer) {
2663
- const unsubscribeRequest = FilterRPC.createRequest(topic, contentFilters, requestId, false);
2664
- const stream = await this.newStream(peer);
2665
- try {
2666
- await pipe([unsubscribeRequest.encode()], encode(), stream.sink);
2667
- }
2668
- catch (e) {
2669
- log$2("Error unsubscribing", e);
2670
- throw e;
2671
- }
2672
- }
2673
- async newStream(peer) {
2674
- const connections = this.libp2p.connectionManager.getConnections(peer.id);
2675
- const connection = selectConnection(connections);
2676
- if (!connection) {
2677
- throw new Error("Failed to get a connection to the peer");
2678
- }
2679
- return connection.newStream(FilterCodec);
2680
- }
2681
- async getPeer(peerId) {
2682
- const res = await selectPeerForProtocol(this.libp2p.peerStore, [FilterCodec], peerId);
2683
- if (!res) {
2684
- throw new Error(`Failed to select peer for ${FilterCodec}`);
2685
- }
2686
- return res.peer;
2687
- }
2688
- async peers() {
2689
- return getPeersForProtocol(this.libp2p.peerStore, [FilterCodec]);
2690
- }
2691
- async randomPeer() {
2692
- return selectRandomPeer(await this.peers());
2693
- }
2694
- }
2695
-
2696
- var index$2 = /*#__PURE__*/Object.freeze({
2697
- __proto__: null,
2698
- FilterCodec: FilterCodec,
2699
- WakuFilter: WakuFilter
2700
- });
2701
-
2702
- /* eslint-disable import/export */
2703
- var PushRequest;
2704
- (function (PushRequest) {
2705
- let _codec;
2706
- PushRequest.codec = () => {
2707
- if (_codec == null) {
2708
- _codec = message((obj, writer, opts = {}) => {
2709
- if (opts.lengthDelimited !== false) {
2710
- writer.fork();
2711
- }
2712
- if (obj.pubSubTopic != null) {
2713
- writer.uint32(10);
2714
- writer.string(obj.pubSubTopic);
2715
- }
2716
- if (obj.message != null) {
2717
- writer.uint32(18);
2718
- WakuMessage$1.codec().encode(obj.message, writer);
2719
- }
2720
- if (opts.lengthDelimited !== false) {
2721
- writer.ldelim();
2722
- }
2723
- }, (reader, length) => {
2724
- const obj = {};
2725
- const end = length == null ? reader.len : reader.pos + length;
2726
- while (reader.pos < end) {
2727
- const tag = reader.uint32();
2728
- switch (tag >>> 3) {
2729
- case 1:
2730
- obj.pubSubTopic = reader.string();
2731
- break;
2732
- case 2:
2733
- obj.message = WakuMessage$1.codec().decode(reader, reader.uint32());
2734
- break;
2735
- default:
2736
- reader.skipType(tag & 7);
2737
- break;
2738
- }
2739
- }
2740
- return obj;
2741
- });
2742
- }
2743
- return _codec;
2744
- };
2745
- PushRequest.encode = (obj) => {
2746
- return encodeMessage(obj, PushRequest.codec());
2747
- };
2748
- PushRequest.decode = (buf) => {
2749
- return decodeMessage(buf, PushRequest.codec());
2750
- };
2751
- })(PushRequest || (PushRequest = {}));
2752
- var PushResponse;
2753
- (function (PushResponse) {
2754
- let _codec;
2755
- PushResponse.codec = () => {
2756
- if (_codec == null) {
2757
- _codec = message((obj, writer, opts = {}) => {
2758
- if (opts.lengthDelimited !== false) {
2759
- writer.fork();
2760
- }
2761
- if (obj.isSuccess != null) {
2762
- writer.uint32(8);
2763
- writer.bool(obj.isSuccess);
2764
- }
2765
- if (obj.info != null) {
2766
- writer.uint32(18);
2767
- writer.string(obj.info);
2768
- }
2769
- if (opts.lengthDelimited !== false) {
2770
- writer.ldelim();
2771
- }
2772
- }, (reader, length) => {
2773
- const obj = {};
2774
- const end = length == null ? reader.len : reader.pos + length;
2775
- while (reader.pos < end) {
2776
- const tag = reader.uint32();
2777
- switch (tag >>> 3) {
2778
- case 1:
2779
- obj.isSuccess = reader.bool();
2780
- break;
2781
- case 2:
2782
- obj.info = reader.string();
2783
- break;
2784
- default:
2785
- reader.skipType(tag & 7);
2786
- break;
2787
- }
2788
- }
2789
- return obj;
2790
- });
2791
- }
2792
- return _codec;
2793
- };
2794
- PushResponse.encode = (obj) => {
2795
- return encodeMessage(obj, PushResponse.codec());
2796
- };
2797
- PushResponse.decode = (buf) => {
2798
- return decodeMessage(buf, PushResponse.codec());
2799
- };
2800
- })(PushResponse || (PushResponse = {}));
2801
- var PushRPC$1;
2802
- (function (PushRPC) {
2803
- let _codec;
2804
- PushRPC.codec = () => {
2805
- if (_codec == null) {
2806
- _codec = message((obj, writer, opts = {}) => {
2807
- if (opts.lengthDelimited !== false) {
2808
- writer.fork();
2809
- }
2810
- if (obj.requestId != null) {
2811
- writer.uint32(10);
2812
- writer.string(obj.requestId);
2813
- }
2814
- if (obj.request != null) {
2815
- writer.uint32(18);
2816
- PushRequest.codec().encode(obj.request, writer);
2817
- }
2818
- if (obj.response != null) {
2819
- writer.uint32(26);
2820
- PushResponse.codec().encode(obj.response, writer);
2821
- }
2822
- if (opts.lengthDelimited !== false) {
2823
- writer.ldelim();
2824
- }
2825
- }, (reader, length) => {
2826
- const obj = {};
2827
- const end = length == null ? reader.len : reader.pos + length;
2828
- while (reader.pos < end) {
2829
- const tag = reader.uint32();
2830
- switch (tag >>> 3) {
2831
- case 1:
2832
- obj.requestId = reader.string();
2833
- break;
2834
- case 2:
2835
- obj.request = PushRequest.codec().decode(reader, reader.uint32());
2836
- break;
2837
- case 3:
2838
- obj.response = PushResponse.codec().decode(reader, reader.uint32());
2839
- break;
2840
- default:
2841
- reader.skipType(tag & 7);
2842
- break;
2843
- }
2844
- }
2845
- return obj;
2846
- });
2847
- }
2848
- return _codec;
2849
- };
2850
- PushRPC.encode = (obj) => {
2851
- return encodeMessage(obj, PushRPC.codec());
2852
- };
2853
- PushRPC.decode = (buf) => {
2854
- return decodeMessage(buf, PushRPC.codec());
2855
- };
2856
- })(PushRPC$1 || (PushRPC$1 = {}));
2857
- var RateLimitProof$1;
2858
- (function (RateLimitProof) {
2859
- let _codec;
2860
- RateLimitProof.codec = () => {
2861
- if (_codec == null) {
2862
- _codec = message((obj, writer, opts = {}) => {
2863
- if (opts.lengthDelimited !== false) {
2864
- writer.fork();
2865
- }
2866
- if (obj.proof != null) {
2867
- writer.uint32(10);
2868
- writer.bytes(obj.proof);
2869
- }
2870
- else {
2871
- throw new Error('Protocol error: required field "proof" was not found in object');
2872
- }
2873
- if (obj.merkleRoot != null) {
2874
- writer.uint32(18);
2875
- writer.bytes(obj.merkleRoot);
2876
- }
2877
- else {
2878
- throw new Error('Protocol error: required field "merkleRoot" was not found in object');
2879
- }
2880
- if (obj.epoch != null) {
2881
- writer.uint32(26);
2882
- writer.bytes(obj.epoch);
2883
- }
2884
- else {
2885
- throw new Error('Protocol error: required field "epoch" was not found in object');
2886
- }
2887
- if (obj.shareX != null) {
2888
- writer.uint32(34);
2889
- writer.bytes(obj.shareX);
2890
- }
2891
- else {
2892
- throw new Error('Protocol error: required field "shareX" was not found in object');
2893
- }
2894
- if (obj.shareY != null) {
2895
- writer.uint32(42);
2896
- writer.bytes(obj.shareY);
2897
- }
2898
- else {
2899
- throw new Error('Protocol error: required field "shareY" was not found in object');
2900
- }
2901
- if (obj.nullifier != null) {
2902
- writer.uint32(50);
2903
- writer.bytes(obj.nullifier);
2904
- }
2905
- else {
2906
- throw new Error('Protocol error: required field "nullifier" was not found in object');
2907
- }
2908
- if (obj.rlnIdentifier != null) {
2909
- writer.uint32(58);
2910
- writer.bytes(obj.rlnIdentifier);
2911
- }
2912
- else {
2913
- throw new Error('Protocol error: required field "rlnIdentifier" was not found in object');
2914
- }
2915
- if (opts.lengthDelimited !== false) {
2916
- writer.ldelim();
2917
- }
2918
- }, (reader, length) => {
2919
- const obj = {
2920
- proof: new Uint8Array(0),
2921
- merkleRoot: new Uint8Array(0),
2922
- epoch: new Uint8Array(0),
2923
- shareX: new Uint8Array(0),
2924
- shareY: new Uint8Array(0),
2925
- nullifier: new Uint8Array(0),
2926
- rlnIdentifier: new Uint8Array(0),
2927
- };
2928
- const end = length == null ? reader.len : reader.pos + length;
2929
- while (reader.pos < end) {
2930
- const tag = reader.uint32();
2931
- switch (tag >>> 3) {
2932
- case 1:
2933
- obj.proof = reader.bytes();
2934
- break;
2935
- case 2:
2936
- obj.merkleRoot = reader.bytes();
2937
- break;
2938
- case 3:
2939
- obj.epoch = reader.bytes();
2940
- break;
2941
- case 4:
2942
- obj.shareX = reader.bytes();
2943
- break;
2944
- case 5:
2945
- obj.shareY = reader.bytes();
2946
- break;
2947
- case 6:
2948
- obj.nullifier = reader.bytes();
2949
- break;
2950
- case 7:
2951
- obj.rlnIdentifier = reader.bytes();
2952
- break;
2953
- default:
2954
- reader.skipType(tag & 7);
2955
- break;
2956
- }
2957
- }
2958
- if (obj.proof == null) {
2959
- throw new Error('Protocol error: value for required field "proof" was not found in protobuf');
2960
- }
2961
- if (obj.merkleRoot == null) {
2962
- throw new Error('Protocol error: value for required field "merkleRoot" was not found in protobuf');
2963
- }
2964
- if (obj.epoch == null) {
2965
- throw new Error('Protocol error: value for required field "epoch" was not found in protobuf');
2966
- }
2967
- if (obj.shareX == null) {
2968
- throw new Error('Protocol error: value for required field "shareX" was not found in protobuf');
2969
- }
2970
- if (obj.shareY == null) {
2971
- throw new Error('Protocol error: value for required field "shareY" was not found in protobuf');
2972
- }
2973
- if (obj.nullifier == null) {
2974
- throw new Error('Protocol error: value for required field "nullifier" was not found in protobuf');
2975
- }
2976
- if (obj.rlnIdentifier == null) {
2977
- throw new Error('Protocol error: value for required field "rlnIdentifier" was not found in protobuf');
2978
- }
2979
- return obj;
2980
- });
2981
- }
2982
- return _codec;
2983
- };
2984
- RateLimitProof.encode = (obj) => {
2985
- return encodeMessage(obj, RateLimitProof.codec());
2986
- };
2987
- RateLimitProof.decode = (buf) => {
2988
- return decodeMessage(buf, RateLimitProof.codec());
2989
- };
2990
- })(RateLimitProof$1 || (RateLimitProof$1 = {}));
2991
- var WakuMessage$1;
2992
- (function (WakuMessage) {
2993
- let _codec;
2994
- WakuMessage.codec = () => {
2995
- if (_codec == null) {
2996
- _codec = message((obj, writer, opts = {}) => {
2997
- if (opts.lengthDelimited !== false) {
2998
- writer.fork();
2999
- }
3000
- if (obj.payload != null) {
3001
- writer.uint32(10);
3002
- writer.bytes(obj.payload);
3003
- }
3004
- if (obj.contentTopic != null) {
3005
- writer.uint32(18);
3006
- writer.string(obj.contentTopic);
3007
- }
3008
- if (obj.version != null) {
3009
- writer.uint32(24);
3010
- writer.uint32(obj.version);
3011
- }
3012
- if (obj.timestampDeprecated != null) {
3013
- writer.uint32(33);
3014
- writer.double(obj.timestampDeprecated);
3015
- }
3016
- if (obj.timestamp != null) {
3017
- writer.uint32(80);
3018
- writer.sint64(obj.timestamp);
3019
- }
3020
- if (obj.rateLimitProof != null) {
3021
- writer.uint32(170);
3022
- RateLimitProof$1.codec().encode(obj.rateLimitProof, writer);
3023
- }
3024
- if (opts.lengthDelimited !== false) {
3025
- writer.ldelim();
3026
- }
3027
- }, (reader, length) => {
3028
- const obj = {};
3029
- const end = length == null ? reader.len : reader.pos + length;
3030
- while (reader.pos < end) {
3031
- const tag = reader.uint32();
3032
- switch (tag >>> 3) {
3033
- case 1:
3034
- obj.payload = reader.bytes();
3035
- break;
3036
- case 2:
3037
- obj.contentTopic = reader.string();
3038
- break;
3039
- case 3:
3040
- obj.version = reader.uint32();
3041
- break;
3042
- case 4:
3043
- obj.timestampDeprecated = reader.double();
3044
- break;
3045
- case 10:
3046
- obj.timestamp = reader.sint64();
3047
- break;
3048
- case 21:
3049
- obj.rateLimitProof = RateLimitProof$1.codec().decode(reader, reader.uint32());
3050
- break;
3051
- default:
3052
- reader.skipType(tag & 7);
3053
- break;
3054
- }
3055
- }
3056
- return obj;
3057
- });
3058
- }
3059
- return _codec;
3060
- };
3061
- WakuMessage.encode = (obj) => {
3062
- return encodeMessage(obj, WakuMessage.codec());
3063
- };
3064
- WakuMessage.decode = (buf) => {
3065
- return decodeMessage(buf, WakuMessage.codec());
3066
- };
3067
- })(WakuMessage$1 || (WakuMessage$1 = {}));
3068
-
3069
- class PushRPC {
3070
- constructor(proto) {
3071
- this.proto = proto;
3072
- }
3073
- static createRequest(message, pubSubTopic) {
3074
- return new PushRPC({
3075
- requestId: v4(),
3076
- request: {
3077
- message: message,
3078
- pubSubTopic: pubSubTopic,
3079
- },
3080
- response: undefined,
3081
- });
3082
- }
3083
- static decode(bytes) {
3084
- const res = PushRPC$1.decode(bytes);
3085
- return new PushRPC(res);
3086
- }
3087
- encode() {
3088
- return PushRPC$1.encode(this.proto);
3089
- }
3090
- get query() {
3091
- return this.proto.request;
3092
- }
3093
- get response() {
3094
- return this.proto.response;
3095
- }
3096
- }
3097
-
3098
- const log$1 = debug("waku:light-push");
3099
- const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
3100
- /**
3101
- * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
3102
- */
3103
- class WakuLightPush {
3104
- constructor(libp2p, options) {
3105
- this.libp2p = libp2p;
3106
- this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;
3107
- }
3108
- async push(encoder, message, opts) {
3109
- const pubSubTopic = opts?.pubSubTopic ? opts.pubSubTopic : this.pubSubTopic;
3110
- const res = await selectPeerForProtocol(this.libp2p.peerStore, [LightPushCodec], opts?.peerId);
3111
- if (!res) {
3112
- throw new Error("Failed to get a peer");
3113
- }
3114
- const { peer } = res;
3115
- const connections = this.libp2p.connectionManager.getConnections(peer.id);
3116
- const connection = selectConnection(connections);
3117
- if (!connection)
3118
- throw "Failed to get a connection to the peer";
3119
- const stream = await connection.newStream(LightPushCodec);
3120
- const recipients = [];
3121
- try {
3122
- const protoMessage = await encoder.toProtoObj(message);
3123
- if (!protoMessage) {
3124
- log$1("Failed to encode to protoMessage, aborting push");
3125
- return { recipients };
3126
- }
3127
- const query = PushRPC.createRequest(protoMessage, pubSubTopic);
3128
- const res = await pipe([query.encode()], encode(), stream, decode(), async (source) => await itAll(source));
3129
- try {
3130
- const bytes = new Uint8ArrayList();
3131
- res.forEach((chunk) => {
3132
- bytes.append(chunk);
3133
- });
3134
- const response = PushRPC.decode(bytes).response;
3135
- if (!response) {
3136
- log$1("No response in PushRPC");
3137
- return { recipients };
3138
- }
3139
- if (response.isSuccess) {
3140
- recipients.push(peer.id);
3141
- }
3142
- }
3143
- catch (err) {
3144
- log$1("Failed to decode push reply", err);
3145
- }
3146
- }
3147
- catch (err) {
3148
- log$1("Failed to send waku light push request", err);
3149
- }
3150
- return { recipients };
3151
- }
3152
- /**
3153
- * Returns known peers from the address book (`libp2p.peerStore`) that support
3154
- * light push protocol. Waku may or may not be currently connected to these
3155
- * peers.
3156
- */
3157
- async peers() {
3158
- return getPeersForProtocol(this.libp2p.peerStore, [LightPushCodec]);
3159
- }
3160
- /**
3161
- * Returns a random peer that supports light push protocol from the address
3162
- * book (`libp2p.peerStore`). Waku may or may not be currently connected to
3163
- * this peer.
3164
- */
3165
- async randomPeer() {
3166
- return selectRandomPeer(await this.peers());
3167
- }
3168
- }
3169
-
3170
- var index$1 = /*#__PURE__*/Object.freeze({
3171
- __proto__: null,
3172
- LightPushCodec: LightPushCodec,
3173
- get PushResponse () { return PushResponse; },
3174
- WakuLightPush: WakuLightPush
3175
- });
3176
-
3177
- /* eslint-disable import/export */
3178
- var Index;
3179
- (function (Index) {
3180
- let _codec;
3181
- Index.codec = () => {
3182
- if (_codec == null) {
3183
- _codec = message((obj, writer, opts = {}) => {
3184
- if (opts.lengthDelimited !== false) {
3185
- writer.fork();
3186
- }
3187
- if (obj.digest != null) {
3188
- writer.uint32(10);
3189
- writer.bytes(obj.digest);
3190
- }
3191
- if (obj.receivedTime != null) {
3192
- writer.uint32(16);
3193
- writer.sint64(obj.receivedTime);
3194
- }
3195
- if (obj.senderTime != null) {
3196
- writer.uint32(24);
3197
- writer.sint64(obj.senderTime);
3198
- }
3199
- if (obj.pubsubTopic != null) {
3200
- writer.uint32(34);
3201
- writer.string(obj.pubsubTopic);
3202
- }
3203
- if (opts.lengthDelimited !== false) {
3204
- writer.ldelim();
3205
- }
3206
- }, (reader, length) => {
3207
- const obj = {};
3208
- const end = length == null ? reader.len : reader.pos + length;
3209
- while (reader.pos < end) {
3210
- const tag = reader.uint32();
3211
- switch (tag >>> 3) {
3212
- case 1:
3213
- obj.digest = reader.bytes();
3214
- break;
3215
- case 2:
3216
- obj.receivedTime = reader.sint64();
3217
- break;
3218
- case 3:
3219
- obj.senderTime = reader.sint64();
3220
- break;
3221
- case 4:
3222
- obj.pubsubTopic = reader.string();
3223
- break;
3224
- default:
3225
- reader.skipType(tag & 7);
3226
- break;
3227
- }
3228
- }
3229
- return obj;
3230
- });
3231
- }
3232
- return _codec;
3233
- };
3234
- Index.encode = (obj) => {
3235
- return encodeMessage(obj, Index.codec());
3236
- };
3237
- Index.decode = (buf) => {
3238
- return decodeMessage(buf, Index.codec());
3239
- };
3240
- })(Index || (Index = {}));
3241
- var PagingInfo;
3242
- (function (PagingInfo) {
3243
- (function (Direction) {
3244
- Direction["DIRECTION_BACKWARD_UNSPECIFIED"] = "DIRECTION_BACKWARD_UNSPECIFIED";
3245
- Direction["DIRECTION_FORWARD"] = "DIRECTION_FORWARD";
3246
- })(PagingInfo.Direction || (PagingInfo.Direction = {}));
3247
- let __DirectionValues;
3248
- (function (__DirectionValues) {
3249
- __DirectionValues[__DirectionValues["DIRECTION_BACKWARD_UNSPECIFIED"] = 0] = "DIRECTION_BACKWARD_UNSPECIFIED";
3250
- __DirectionValues[__DirectionValues["DIRECTION_FORWARD"] = 1] = "DIRECTION_FORWARD";
3251
- })(__DirectionValues || (__DirectionValues = {}));
3252
- (function (Direction) {
3253
- Direction.codec = () => {
3254
- return enumeration(__DirectionValues);
3255
- };
3256
- })(PagingInfo.Direction || (PagingInfo.Direction = {}));
3257
- let _codec;
3258
- PagingInfo.codec = () => {
3259
- if (_codec == null) {
3260
- _codec = message((obj, writer, opts = {}) => {
3261
- if (opts.lengthDelimited !== false) {
3262
- writer.fork();
3263
- }
3264
- if (obj.pageSize != null) {
3265
- writer.uint32(8);
3266
- writer.uint64(obj.pageSize);
3267
- }
3268
- if (obj.cursor != null) {
3269
- writer.uint32(18);
3270
- Index.codec().encode(obj.cursor, writer);
3271
- }
3272
- if (obj.direction != null) {
3273
- writer.uint32(24);
3274
- PagingInfo.Direction.codec().encode(obj.direction, writer);
3275
- }
3276
- if (opts.lengthDelimited !== false) {
3277
- writer.ldelim();
3278
- }
3279
- }, (reader, length) => {
3280
- const obj = {};
3281
- const end = length == null ? reader.len : reader.pos + length;
3282
- while (reader.pos < end) {
3283
- const tag = reader.uint32();
3284
- switch (tag >>> 3) {
3285
- case 1:
3286
- obj.pageSize = reader.uint64();
3287
- break;
3288
- case 2:
3289
- obj.cursor = Index.codec().decode(reader, reader.uint32());
3290
- break;
3291
- case 3:
3292
- obj.direction = PagingInfo.Direction.codec().decode(reader);
3293
- break;
3294
- default:
3295
- reader.skipType(tag & 7);
3296
- break;
3297
- }
3298
- }
3299
- return obj;
3300
- });
3301
- }
3302
- return _codec;
3303
- };
3304
- PagingInfo.encode = (obj) => {
3305
- return encodeMessage(obj, PagingInfo.codec());
3306
- };
3307
- PagingInfo.decode = (buf) => {
3308
- return decodeMessage(buf, PagingInfo.codec());
3309
- };
3310
- })(PagingInfo || (PagingInfo = {}));
3311
- var ContentFilter;
3312
- (function (ContentFilter) {
3313
- let _codec;
3314
- ContentFilter.codec = () => {
3315
- if (_codec == null) {
3316
- _codec = message((obj, writer, opts = {}) => {
3317
- if (opts.lengthDelimited !== false) {
3318
- writer.fork();
3319
- }
3320
- if (obj.contentTopic != null) {
3321
- writer.uint32(10);
3322
- writer.string(obj.contentTopic);
3323
- }
3324
- if (opts.lengthDelimited !== false) {
3325
- writer.ldelim();
3326
- }
3327
- }, (reader, length) => {
3328
- const obj = {};
3329
- const end = length == null ? reader.len : reader.pos + length;
3330
- while (reader.pos < end) {
3331
- const tag = reader.uint32();
3332
- switch (tag >>> 3) {
3333
- case 1:
3334
- obj.contentTopic = reader.string();
3335
- break;
3336
- default:
3337
- reader.skipType(tag & 7);
3338
- break;
3339
- }
3340
- }
3341
- return obj;
3342
- });
3343
- }
3344
- return _codec;
3345
- };
3346
- ContentFilter.encode = (obj) => {
3347
- return encodeMessage(obj, ContentFilter.codec());
3348
- };
3349
- ContentFilter.decode = (buf) => {
3350
- return decodeMessage(buf, ContentFilter.codec());
3351
- };
3352
- })(ContentFilter || (ContentFilter = {}));
3353
- var HistoryQuery;
3354
- (function (HistoryQuery) {
3355
- let _codec;
3356
- HistoryQuery.codec = () => {
3357
- if (_codec == null) {
3358
- _codec = message((obj, writer, opts = {}) => {
3359
- if (opts.lengthDelimited !== false) {
3360
- writer.fork();
3361
- }
3362
- if (obj.pubSubTopic != null) {
3363
- writer.uint32(18);
3364
- writer.string(obj.pubSubTopic);
3365
- }
3366
- if (obj.contentFilters != null) {
3367
- for (const value of obj.contentFilters) {
3368
- writer.uint32(26);
3369
- ContentFilter.codec().encode(value, writer);
3370
- }
3371
- }
3372
- else {
3373
- throw new Error('Protocol error: required field "contentFilters" was not found in object');
3374
- }
3375
- if (obj.pagingInfo != null) {
3376
- writer.uint32(34);
3377
- PagingInfo.codec().encode(obj.pagingInfo, writer);
3378
- }
3379
- if (obj.startTime != null) {
3380
- writer.uint32(40);
3381
- writer.sint64(obj.startTime);
3382
- }
3383
- if (obj.endTime != null) {
3384
- writer.uint32(48);
3385
- writer.sint64(obj.endTime);
3386
- }
3387
- if (opts.lengthDelimited !== false) {
3388
- writer.ldelim();
3389
- }
3390
- }, (reader, length) => {
3391
- const obj = {
3392
- contentFilters: [],
3393
- };
3394
- const end = length == null ? reader.len : reader.pos + length;
3395
- while (reader.pos < end) {
3396
- const tag = reader.uint32();
3397
- switch (tag >>> 3) {
3398
- case 2:
3399
- obj.pubSubTopic = reader.string();
3400
- break;
3401
- case 3:
3402
- obj.contentFilters.push(ContentFilter.codec().decode(reader, reader.uint32()));
3403
- break;
3404
- case 4:
3405
- obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32());
3406
- break;
3407
- case 5:
3408
- obj.startTime = reader.sint64();
3409
- break;
3410
- case 6:
3411
- obj.endTime = reader.sint64();
3412
- break;
3413
- default:
3414
- reader.skipType(tag & 7);
3415
- break;
3416
- }
3417
- }
3418
- return obj;
3419
- });
3420
- }
3421
- return _codec;
3422
- };
3423
- HistoryQuery.encode = (obj) => {
3424
- return encodeMessage(obj, HistoryQuery.codec());
3425
- };
3426
- HistoryQuery.decode = (buf) => {
3427
- return decodeMessage(buf, HistoryQuery.codec());
3428
- };
3429
- })(HistoryQuery || (HistoryQuery = {}));
3430
- var HistoryResponse;
3431
- (function (HistoryResponse) {
3432
- (function (HistoryError) {
3433
- HistoryError["ERROR_NONE_UNSPECIFIED"] = "ERROR_NONE_UNSPECIFIED";
3434
- HistoryError["ERROR_INVALID_CURSOR"] = "ERROR_INVALID_CURSOR";
3435
- })(HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));
3436
- let __HistoryErrorValues;
3437
- (function (__HistoryErrorValues) {
3438
- __HistoryErrorValues[__HistoryErrorValues["ERROR_NONE_UNSPECIFIED"] = 0] = "ERROR_NONE_UNSPECIFIED";
3439
- __HistoryErrorValues[__HistoryErrorValues["ERROR_INVALID_CURSOR"] = 1] = "ERROR_INVALID_CURSOR";
3440
- })(__HistoryErrorValues || (__HistoryErrorValues = {}));
3441
- (function (HistoryError) {
3442
- HistoryError.codec = () => {
3443
- return enumeration(__HistoryErrorValues);
3444
- };
3445
- })(HistoryResponse.HistoryError || (HistoryResponse.HistoryError = {}));
3446
- let _codec;
3447
- HistoryResponse.codec = () => {
3448
- if (_codec == null) {
3449
- _codec = message((obj, writer, opts = {}) => {
3450
- if (opts.lengthDelimited !== false) {
3451
- writer.fork();
3452
- }
3453
- if (obj.messages != null) {
3454
- for (const value of obj.messages) {
3455
- writer.uint32(18);
3456
- WakuMessage.codec().encode(value, writer);
3457
- }
3458
- }
3459
- else {
3460
- throw new Error('Protocol error: required field "messages" was not found in object');
3461
- }
3462
- if (obj.pagingInfo != null) {
3463
- writer.uint32(26);
3464
- PagingInfo.codec().encode(obj.pagingInfo, writer);
3465
- }
3466
- if (obj.error != null) {
3467
- writer.uint32(32);
3468
- HistoryResponse.HistoryError.codec().encode(obj.error, writer);
3469
- }
3470
- if (opts.lengthDelimited !== false) {
3471
- writer.ldelim();
3472
- }
3473
- }, (reader, length) => {
3474
- const obj = {
3475
- messages: [],
3476
- };
3477
- const end = length == null ? reader.len : reader.pos + length;
3478
- while (reader.pos < end) {
3479
- const tag = reader.uint32();
3480
- switch (tag >>> 3) {
3481
- case 2:
3482
- obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32()));
3483
- break;
3484
- case 3:
3485
- obj.pagingInfo = PagingInfo.codec().decode(reader, reader.uint32());
3486
- break;
3487
- case 4:
3488
- obj.error = HistoryResponse.HistoryError.codec().decode(reader);
3489
- break;
3490
- default:
3491
- reader.skipType(tag & 7);
3492
- break;
3493
- }
3494
- }
3495
- return obj;
3496
- });
3497
- }
3498
- return _codec;
3499
- };
3500
- HistoryResponse.encode = (obj) => {
3501
- return encodeMessage(obj, HistoryResponse.codec());
3502
- };
3503
- HistoryResponse.decode = (buf) => {
3504
- return decodeMessage(buf, HistoryResponse.codec());
3505
- };
3506
- })(HistoryResponse || (HistoryResponse = {}));
3507
- var HistoryRPC$1;
3508
- (function (HistoryRPC) {
3509
- let _codec;
3510
- HistoryRPC.codec = () => {
3511
- if (_codec == null) {
3512
- _codec = message((obj, writer, opts = {}) => {
3513
- if (opts.lengthDelimited !== false) {
3514
- writer.fork();
3515
- }
3516
- if (obj.requestId != null) {
3517
- writer.uint32(10);
3518
- writer.string(obj.requestId);
3519
- }
3520
- if (obj.query != null) {
3521
- writer.uint32(18);
3522
- HistoryQuery.codec().encode(obj.query, writer);
3523
- }
3524
- if (obj.response != null) {
3525
- writer.uint32(26);
3526
- HistoryResponse.codec().encode(obj.response, writer);
3527
- }
3528
- if (opts.lengthDelimited !== false) {
3529
- writer.ldelim();
3530
- }
3531
- }, (reader, length) => {
3532
- const obj = {};
3533
- const end = length == null ? reader.len : reader.pos + length;
3534
- while (reader.pos < end) {
3535
- const tag = reader.uint32();
3536
- switch (tag >>> 3) {
3537
- case 1:
3538
- obj.requestId = reader.string();
3539
- break;
3540
- case 2:
3541
- obj.query = HistoryQuery.codec().decode(reader, reader.uint32());
3542
- break;
3543
- case 3:
3544
- obj.response = HistoryResponse.codec().decode(reader, reader.uint32());
3545
- break;
3546
- default:
3547
- reader.skipType(tag & 7);
3548
- break;
3549
- }
3550
- }
3551
- return obj;
3552
- });
3553
- }
3554
- return _codec;
3555
- };
3556
- HistoryRPC.encode = (obj) => {
3557
- return encodeMessage(obj, HistoryRPC.codec());
3558
- };
3559
- HistoryRPC.decode = (buf) => {
3560
- return decodeMessage(buf, HistoryRPC.codec());
3561
- };
3562
- })(HistoryRPC$1 || (HistoryRPC$1 = {}));
3563
- var RateLimitProof;
3564
- (function (RateLimitProof) {
3565
- let _codec;
3566
- RateLimitProof.codec = () => {
3567
- if (_codec == null) {
3568
- _codec = message((obj, writer, opts = {}) => {
3569
- if (opts.lengthDelimited !== false) {
3570
- writer.fork();
3571
- }
3572
- if (obj.proof != null) {
3573
- writer.uint32(10);
3574
- writer.bytes(obj.proof);
3575
- }
3576
- else {
3577
- throw new Error('Protocol error: required field "proof" was not found in object');
3578
- }
3579
- if (obj.merkleRoot != null) {
3580
- writer.uint32(18);
3581
- writer.bytes(obj.merkleRoot);
3582
- }
3583
- else {
3584
- throw new Error('Protocol error: required field "merkleRoot" was not found in object');
3585
- }
3586
- if (obj.epoch != null) {
3587
- writer.uint32(26);
3588
- writer.bytes(obj.epoch);
3589
- }
3590
- else {
3591
- throw new Error('Protocol error: required field "epoch" was not found in object');
3592
- }
3593
- if (obj.shareX != null) {
3594
- writer.uint32(34);
3595
- writer.bytes(obj.shareX);
3596
- }
3597
- else {
3598
- throw new Error('Protocol error: required field "shareX" was not found in object');
3599
- }
3600
- if (obj.shareY != null) {
3601
- writer.uint32(42);
3602
- writer.bytes(obj.shareY);
3603
- }
3604
- else {
3605
- throw new Error('Protocol error: required field "shareY" was not found in object');
3606
- }
3607
- if (obj.nullifier != null) {
3608
- writer.uint32(50);
3609
- writer.bytes(obj.nullifier);
3610
- }
3611
- else {
3612
- throw new Error('Protocol error: required field "nullifier" was not found in object');
3613
- }
3614
- if (obj.rlnIdentifier != null) {
3615
- writer.uint32(58);
3616
- writer.bytes(obj.rlnIdentifier);
3617
- }
3618
- else {
3619
- throw new Error('Protocol error: required field "rlnIdentifier" was not found in object');
3620
- }
3621
- if (opts.lengthDelimited !== false) {
3622
- writer.ldelim();
3623
- }
3624
- }, (reader, length) => {
3625
- const obj = {
3626
- proof: new Uint8Array(0),
3627
- merkleRoot: new Uint8Array(0),
3628
- epoch: new Uint8Array(0),
3629
- shareX: new Uint8Array(0),
3630
- shareY: new Uint8Array(0),
3631
- nullifier: new Uint8Array(0),
3632
- rlnIdentifier: new Uint8Array(0),
3633
- };
3634
- const end = length == null ? reader.len : reader.pos + length;
3635
- while (reader.pos < end) {
3636
- const tag = reader.uint32();
3637
- switch (tag >>> 3) {
3638
- case 1:
3639
- obj.proof = reader.bytes();
3640
- break;
3641
- case 2:
3642
- obj.merkleRoot = reader.bytes();
3643
- break;
3644
- case 3:
3645
- obj.epoch = reader.bytes();
3646
- break;
3647
- case 4:
3648
- obj.shareX = reader.bytes();
3649
- break;
3650
- case 5:
3651
- obj.shareY = reader.bytes();
3652
- break;
3653
- case 6:
3654
- obj.nullifier = reader.bytes();
3655
- break;
3656
- case 7:
3657
- obj.rlnIdentifier = reader.bytes();
3658
- break;
3659
- default:
3660
- reader.skipType(tag & 7);
3661
- break;
3662
- }
3663
- }
3664
- if (obj.proof == null) {
3665
- throw new Error('Protocol error: value for required field "proof" was not found in protobuf');
3666
- }
3667
- if (obj.merkleRoot == null) {
3668
- throw new Error('Protocol error: value for required field "merkleRoot" was not found in protobuf');
3669
- }
3670
- if (obj.epoch == null) {
3671
- throw new Error('Protocol error: value for required field "epoch" was not found in protobuf');
3672
- }
3673
- if (obj.shareX == null) {
3674
- throw new Error('Protocol error: value for required field "shareX" was not found in protobuf');
3675
- }
3676
- if (obj.shareY == null) {
3677
- throw new Error('Protocol error: value for required field "shareY" was not found in protobuf');
3678
- }
3679
- if (obj.nullifier == null) {
3680
- throw new Error('Protocol error: value for required field "nullifier" was not found in protobuf');
3681
- }
3682
- if (obj.rlnIdentifier == null) {
3683
- throw new Error('Protocol error: value for required field "rlnIdentifier" was not found in protobuf');
3684
- }
3685
- return obj;
3686
- });
3687
- }
3688
- return _codec;
3689
- };
3690
- RateLimitProof.encode = (obj) => {
3691
- return encodeMessage(obj, RateLimitProof.codec());
3692
- };
3693
- RateLimitProof.decode = (buf) => {
3694
- return decodeMessage(buf, RateLimitProof.codec());
3695
- };
3696
- })(RateLimitProof || (RateLimitProof = {}));
3697
- var WakuMessage;
3698
- (function (WakuMessage) {
3699
- let _codec;
3700
- WakuMessage.codec = () => {
3701
- if (_codec == null) {
3702
- _codec = message((obj, writer, opts = {}) => {
3703
- if (opts.lengthDelimited !== false) {
3704
- writer.fork();
3705
- }
3706
- if (obj.payload != null) {
3707
- writer.uint32(10);
3708
- writer.bytes(obj.payload);
3709
- }
3710
- if (obj.contentTopic != null) {
3711
- writer.uint32(18);
3712
- writer.string(obj.contentTopic);
3713
- }
3714
- if (obj.version != null) {
3715
- writer.uint32(24);
3716
- writer.uint32(obj.version);
3717
- }
3718
- if (obj.timestampDeprecated != null) {
3719
- writer.uint32(33);
3720
- writer.double(obj.timestampDeprecated);
3721
- }
3722
- if (obj.timestamp != null) {
3723
- writer.uint32(80);
3724
- writer.sint64(obj.timestamp);
3725
- }
3726
- if (obj.rateLimitProof != null) {
3727
- writer.uint32(170);
3728
- RateLimitProof.codec().encode(obj.rateLimitProof, writer);
3729
- }
3730
- if (opts.lengthDelimited !== false) {
3731
- writer.ldelim();
3732
- }
3733
- }, (reader, length) => {
3734
- const obj = {};
3735
- const end = length == null ? reader.len : reader.pos + length;
3736
- while (reader.pos < end) {
3737
- const tag = reader.uint32();
3738
- switch (tag >>> 3) {
3739
- case 1:
3740
- obj.payload = reader.bytes();
3741
- break;
3742
- case 2:
3743
- obj.contentTopic = reader.string();
3744
- break;
3745
- case 3:
3746
- obj.version = reader.uint32();
3747
- break;
3748
- case 4:
3749
- obj.timestampDeprecated = reader.double();
3750
- break;
3751
- case 10:
3752
- obj.timestamp = reader.sint64();
3753
- break;
3754
- case 21:
3755
- obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32());
3756
- break;
3757
- default:
3758
- reader.skipType(tag & 7);
3759
- break;
3760
- }
3761
- }
3762
- return obj;
3763
- });
3764
- }
3765
- return _codec;
3766
- };
3767
- WakuMessage.encode = (obj) => {
3768
- return encodeMessage(obj, WakuMessage.codec());
3769
- };
3770
- WakuMessage.decode = (buf) => {
3771
- return decodeMessage(buf, WakuMessage.codec());
3772
- };
3773
- })(WakuMessage || (WakuMessage = {}));
3774
-
3775
- const OneMillion = BigInt(1000000);
3776
- var PageDirection;
3777
- (function (PageDirection) {
3778
- PageDirection["BACKWARD"] = "backward";
3779
- PageDirection["FORWARD"] = "forward";
3780
- })(PageDirection || (PageDirection = {}));
3781
- class HistoryRPC {
3782
- constructor(proto) {
3783
- this.proto = proto;
3784
- }
3785
- get query() {
3786
- return this.proto.query;
3787
- }
3788
- get response() {
3789
- return this.proto.response;
3790
- }
3791
- /**
3792
- * Create History Query.
3793
- */
3794
- static createQuery(params) {
3795
- const contentFilters = params.contentTopics.map((contentTopic) => {
3796
- return { contentTopic };
3797
- });
3798
- const direction = directionToProto(params.pageDirection);
3799
- const pagingInfo = {
3800
- pageSize: BigInt(params.pageSize),
3801
- cursor: params.cursor,
3802
- direction,
3803
- };
3804
- let startTime, endTime;
3805
- if (params.startTime) {
3806
- // milliseconds 10^-3 to nanoseconds 10^-9
3807
- startTime = BigInt(params.startTime.valueOf()) * OneMillion;
3808
- }
3809
- if (params.endTime) {
3810
- // milliseconds 10^-3 to nanoseconds 10^-9
3811
- endTime = BigInt(params.endTime.valueOf()) * OneMillion;
3812
- }
3813
- return new HistoryRPC({
3814
- requestId: v4(),
3815
- query: {
3816
- pubSubTopic: params.pubSubTopic,
3817
- contentFilters,
3818
- pagingInfo,
3819
- startTime,
3820
- endTime,
3821
- },
3822
- response: undefined,
3823
- });
3824
- }
3825
- decode(bytes) {
3826
- const res = HistoryRPC$1.decode(bytes);
3827
- return new HistoryRPC(res);
3828
- }
3829
- encode() {
3830
- return HistoryRPC$1.encode(this.proto);
3831
- }
3832
- }
3833
- function directionToProto(pageDirection) {
3834
- switch (pageDirection) {
3835
- case PageDirection.BACKWARD:
3836
- return PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;
3837
- case PageDirection.FORWARD:
3838
- return PagingInfo.Direction.DIRECTION_FORWARD;
3839
- default:
3840
- return PagingInfo.Direction.DIRECTION_BACKWARD_UNSPECIFIED;
3841
- }
3842
- }
3843
-
3844
- var HistoryError = HistoryResponse.HistoryError;
3845
- const log = debug("waku:store");
3846
- const StoreCodec = "/vac/waku/store/2.0.0-beta4";
3847
- const DefaultPageSize = 10;
3848
- /**
3849
- * Implements the [Waku v2 Store protocol](https://rfc.vac.dev/spec/13/).
3850
- *
3851
- * The Waku Store protocol can be used to retrieved historical messages.
3852
- */
3853
- class WakuStore {
3854
- constructor(libp2p, options) {
3855
- this.libp2p = libp2p;
3856
- this.pubSubTopic = options?.pubSubTopic ?? DefaultPubSubTopic;
3857
- }
3858
- /**
3859
- * Do a query to a Waku Store to retrieve historical/missed messages.
3860
- *
3861
- * The callback function takes a `WakuMessage` in input,
3862
- * messages are processed in order:
3863
- * - oldest to latest if `options.pageDirection` == { @link PageDirection.FORWARD }
3864
- * - latest to oldest if `options.pageDirection` == { @link PageDirection.BACKWARD }
3865
- *
3866
- * The ordering may affect performance.
3867
- * The ordering depends on the behavior of the remote store node.
3868
- * If strong ordering is needed, you may need to handle this at application level
3869
- * and set your own timestamps too (the WakuMessage timestamps are not certified).
3870
- *
3871
- * @throws If not able to reach a Waku Store peer to query,
3872
- * or if an error is encountered when processing the reply,
3873
- * or if two decoders with the same content topic are passed.
3874
- */
3875
- async queryOrderedCallback(decoders, callback, options) {
3876
- let abort = false;
3877
- for await (const promises of this.queryGenerator(decoders, options)) {
3878
- if (abort)
3879
- break;
3880
- const messagesOrUndef = await Promise.all(promises);
3881
- let messages = messagesOrUndef.filter(isDefined);
3882
- // Messages in pages are ordered from oldest (first) to most recent (last).
3883
- // https://github.com/vacp2p/rfc/issues/533
3884
- if (typeof options?.pageDirection === "undefined" ||
3885
- options?.pageDirection === PageDirection.BACKWARD) {
3886
- messages = messages.reverse();
3887
- }
3888
- await Promise.all(messages.map(async (msg) => {
3889
- if (msg && !abort) {
3890
- abort = Boolean(await callback(msg));
3891
- }
3892
- }));
3893
- }
3894
- }
3895
- /**
3896
- * Do a query to a Waku Store to retrieve historical/missed messages.
3897
- *
3898
- * The callback function takes a `Promise<WakuMessage>` in input,
3899
- * useful if messages needs to be decrypted and performance matters.
3900
- *
3901
- * The order of the messages passed to the callback is as follows:
3902
- * - within a page, messages are expected to be ordered from oldest to most recent
3903
- * - pages direction depends on { @link QueryOptions.pageDirection }
3904
- *
3905
- * Do note that the resolution of the `Promise<WakuMessage | undefined` may
3906
- * break the order as it may rely on the browser decryption API, which in turn,
3907
- * may have a different speed depending on the type of decryption.
3908
- *
3909
- * @throws If not able to reach a Waku Store peer to query,
3910
- * or if an error is encountered when processing the reply,
3911
- * or if two decoders with the same content topic are passed.
3912
- */
3913
- async queryCallbackOnPromise(decoders, callback, options) {
3914
- let abort = false;
3915
- let promises = [];
3916
- for await (const page of this.queryGenerator(decoders, options)) {
3917
- const _promises = page.map(async (msg) => {
3918
- if (!abort) {
3919
- abort = Boolean(await callback(msg));
3920
- }
3921
- });
3922
- promises = promises.concat(_promises);
3923
- }
3924
- await Promise.all(promises);
3925
- }
3926
- /**
3927
- * Do a query to a Waku Store to retrieve historical/missed messages.
3928
- *
3929
- * This is a generator, useful if you want most control on how messages
3930
- * are processed.
3931
- *
3932
- * The order of the messages returned by the remote Waku node SHOULD BE
3933
- * as follows:
3934
- * - within a page, messages SHOULD be ordered from oldest to most recent
3935
- * - pages direction depends on { @link QueryOptions.pageDirection }
3936
- *
3937
- * However, there is no way to guarantee the behavior of the remote node.
3938
- *
3939
- * @throws If not able to reach a Waku Store peer to query,
3940
- * or if an error is encountered when processing the reply,
3941
- * or if two decoders with the same content topic are passed.
3942
- */
3943
- async *queryGenerator(decoders, options) {
3944
- let startTime, endTime;
3945
- if (options?.timeFilter) {
3946
- startTime = options.timeFilter.startTime;
3947
- endTime = options.timeFilter.endTime;
3948
- }
3949
- const decodersAsMap = new Map();
3950
- decoders.forEach((dec) => {
3951
- if (decodersAsMap.has(dec.contentTopic)) {
3952
- throw new Error("API does not support different decoder per content topic");
3953
- }
3954
- decodersAsMap.set(dec.contentTopic, dec);
3955
- });
3956
- const contentTopics = decoders.map((dec) => dec.contentTopic);
3957
- const queryOpts = Object.assign({
3958
- pubSubTopic: this.pubSubTopic,
3959
- pageDirection: PageDirection.BACKWARD,
3960
- pageSize: DefaultPageSize,
3961
- }, options, { contentTopics, startTime, endTime });
3962
- log("Querying history with the following options", {
3963
- peerId: options?.peerId?.toString(),
3964
- ...options,
3965
- });
3966
- const res = await selectPeerForProtocol(this.libp2p.peerStore, [StoreCodec], options?.peerId);
3967
- if (!res) {
3968
- throw new Error("Failed to get a peer");
3969
- }
3970
- const { peer, protocol } = res;
3971
- const connections = this.libp2p.connectionManager.getConnections(peer.id);
3972
- const connection = selectConnection(connections);
3973
- if (!connection)
3974
- throw "Failed to get a connection to the peer";
3975
- for await (const messages of paginate(connection, protocol, queryOpts, decodersAsMap)) {
3976
- yield messages;
3977
- }
3978
- }
3979
- /**
3980
- * Returns known peers from the address book (`libp2p.peerStore`) that support
3981
- * store protocol. Waku may or may not be currently connected to these peers.
3982
- */
3983
- async peers() {
3984
- return getPeersForProtocol(this.libp2p.peerStore, [StoreCodec]);
3985
- }
3986
- }
3987
- async function* paginate(connection, protocol, queryOpts, decoders) {
3988
- if (queryOpts.contentTopics.toString() !==
3989
- Array.from(decoders.keys()).toString()) {
3990
- throw new Error("Internal error, the decoders should match the query's content topics");
3991
- }
3992
- let cursor = undefined;
3993
- while (true) {
3994
- queryOpts = Object.assign(queryOpts, { cursor });
3995
- const stream = await connection.newStream(protocol);
3996
- const historyRpcQuery = HistoryRPC.createQuery(queryOpts);
3997
- log("Querying store peer", connection.remoteAddr.toString(), `for (${queryOpts.pubSubTopic})`, queryOpts.contentTopics);
3998
- const res = await pipe([historyRpcQuery.encode()], encode(), stream, decode(), async (source) => await itAll(source));
3999
- const bytes = new Uint8ArrayList();
4000
- res.forEach((chunk) => {
4001
- bytes.append(chunk);
4002
- });
4003
- const reply = historyRpcQuery.decode(bytes);
4004
- if (!reply.response) {
4005
- log("Stopping pagination due to store `response` field missing");
4006
- break;
4007
- }
4008
- const response = reply.response;
4009
- if (response.error &&
4010
- response.error !== HistoryError.ERROR_NONE_UNSPECIFIED) {
4011
- throw "History response contains an Error: " + response.error;
4012
- }
4013
- if (!response.messages || !response.messages.length) {
4014
- log("Stopping pagination due to store `response.messages` field missing or empty");
4015
- break;
4016
- }
4017
- log(`${response.messages.length} messages retrieved from store`);
4018
- yield response.messages.map((protoMsg) => {
4019
- const contentTopic = protoMsg.contentTopic;
4020
- if (typeof contentTopic !== "undefined") {
4021
- const decoder = decoders.get(contentTopic);
4022
- if (decoder) {
4023
- return decoder.fromProtoObj(toProtoMessage(protoMsg));
4024
- }
4025
- }
4026
- return Promise.resolve(undefined);
4027
- });
4028
- cursor = response.pagingInfo?.cursor;
4029
- if (typeof cursor === "undefined") {
4030
- // If the server does not return cursor then there is an issue,
4031
- // Need to abort, or we end up in an infinite loop
4032
- log("Stopping pagination due to `response.pagingInfo.cursor` missing from store response");
4033
- break;
4034
- }
4035
- const responsePageSize = response.pagingInfo?.pageSize;
4036
- const queryPageSize = historyRpcQuery.query?.pagingInfo?.pageSize;
4037
- if (
4038
- // Response page size smaller than query, meaning this is the last page
4039
- responsePageSize &&
4040
- queryPageSize &&
4041
- responsePageSize < queryPageSize) {
4042
- break;
4043
- }
4044
- }
4045
- }
4046
- function isDefined(msg) {
4047
- return !!msg;
4048
- }
4049
-
4050
- var index = /*#__PURE__*/Object.freeze({
4051
- __proto__: null,
4052
- StoreCodec: StoreCodec,
4053
- DefaultPageSize: DefaultPageSize,
4054
- get PageDirection () { return PageDirection; },
4055
- WakuStore: WakuStore,
4056
- isDefined: isDefined
4057
- });
4058
-
4059
- export { DefaultPubSubTopic as D, FilterCodec as F, LightPushCodec as L, Protocols as P, StoreCodec as S, Uint8ArrayList as U, WakuFilter as W, pipe as a, index$1 as b, WakuLightPush as c, decode as d, encode as e, PushResponse as f, index as g, PageDirection as h, index$2 as i, WakuStore as j, pushable$1 as p, unsigned as u };