@waku/core 0.0.26-7eb3375.0 → 0.0.27

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 (68) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/bundle/base_protocol-LhsIWF3-.js +308 -0
  3. package/bundle/{browser-9a6558bb.js → browser-BQyFvtq6.js} +579 -699
  4. package/bundle/index-8YyfzF9R.js +650 -0
  5. package/bundle/index.js +3076 -21759
  6. package/bundle/lib/base_protocol.js +3 -3
  7. package/bundle/lib/message/version_0.js +3 -3
  8. package/bundle/lib/predefined_bootstrap_nodes.js +1 -1
  9. package/bundle/{version_0-7190df43.js → version_0-FXfzO8Km.js} +1368 -2459
  10. package/dist/.tsbuildinfo +1 -1
  11. package/dist/index.d.ts +2 -5
  12. package/dist/index.js +2 -5
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/base_protocol.d.ts +14 -10
  15. package/dist/lib/base_protocol.js +38 -16
  16. package/dist/lib/base_protocol.js.map +1 -1
  17. package/dist/lib/connection_manager.d.ts +2 -2
  18. package/dist/lib/connection_manager.js +16 -6
  19. package/dist/lib/connection_manager.js.map +1 -1
  20. package/dist/lib/filter/index.d.ts +1 -1
  21. package/dist/lib/filter/index.js +146 -85
  22. package/dist/lib/filter/index.js.map +1 -1
  23. package/dist/lib/filterPeers.d.ts +8 -5
  24. package/dist/lib/filterPeers.js +12 -5
  25. package/dist/lib/filterPeers.js.map +1 -1
  26. package/dist/lib/keep_alive_manager.d.ts +2 -3
  27. package/dist/lib/keep_alive_manager.js +2 -2
  28. package/dist/lib/keep_alive_manager.js.map +1 -1
  29. package/dist/lib/light_push/index.js +3 -7
  30. package/dist/lib/light_push/index.js.map +1 -1
  31. package/dist/lib/message/version_0.d.ts +3 -3
  32. package/dist/lib/message/version_0.js +5 -6
  33. package/dist/lib/message/version_0.js.map +1 -1
  34. package/dist/lib/metadata/index.d.ts +3 -0
  35. package/dist/lib/metadata/index.js +81 -0
  36. package/dist/lib/metadata/index.js.map +1 -0
  37. package/dist/lib/predefined_bootstrap_nodes.js.map +1 -1
  38. package/dist/lib/store/history_rpc.js.map +1 -1
  39. package/dist/lib/store/index.js +1 -4
  40. package/dist/lib/store/index.js.map +1 -1
  41. package/dist/lib/stream_manager.d.ts +2 -2
  42. package/dist/lib/stream_manager.js.map +1 -1
  43. package/dist/lib/wait_for_remote_peer.d.ts +1 -1
  44. package/dist/lib/wait_for_remote_peer.js +40 -10
  45. package/dist/lib/wait_for_remote_peer.js.map +1 -1
  46. package/package.json +129 -1
  47. package/src/index.ts +3 -6
  48. package/src/lib/base_protocol.ts +71 -24
  49. package/src/lib/connection_manager.ts +17 -10
  50. package/src/lib/filter/index.ts +237 -139
  51. package/src/lib/filterPeers.ts +15 -7
  52. package/src/lib/keep_alive_manager.ts +4 -5
  53. package/src/lib/light_push/index.ts +11 -11
  54. package/src/lib/message/version_0.ts +16 -8
  55. package/src/lib/metadata/index.ts +142 -0
  56. package/src/lib/store/index.ts +3 -7
  57. package/src/lib/stream_manager.ts +2 -3
  58. package/src/lib/wait_for_remote_peer.ts +58 -12
  59. package/bundle/base_protocol-46017f51.js +0 -468
  60. package/bundle/index-7581d519.js +0 -31
  61. package/dist/lib/constants.d.ts +0 -4
  62. package/dist/lib/constants.js +0 -5
  63. package/dist/lib/constants.js.map +0 -1
  64. package/dist/lib/waku.d.ts +0 -57
  65. package/dist/lib/waku.js +0 -124
  66. package/dist/lib/waku.js.map +0 -1
  67. package/src/lib/constants.ts +0 -4
  68. package/src/lib/waku.ts +0 -204
@@ -0,0 +1,650 @@
1
+ import { i as identityBase, b as base2, c as base8, d as base10, e as base16, f as base32, h as base36, j as base58, k as base64, l as base256emoji, m as debug } from './browser-BQyFvtq6.js';
2
+
3
+ /**
4
+ * To guarantee Uint8Array semantics, convert nodejs Buffers
5
+ * into vanilla Uint8Arrays
6
+ */
7
+ function asUint8Array(buf) {
8
+ if (globalThis.Buffer != null) {
9
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
10
+ }
11
+ return buf;
12
+ }
13
+
14
+ /**
15
+ * Returns a `Uint8Array` of the requested size. Referenced memory will
16
+ * be initialized to 0.
17
+ */
18
+ function alloc(size = 0) {
19
+ if (globalThis.Buffer?.alloc != null) {
20
+ return asUint8Array(globalThis.Buffer.alloc(size));
21
+ }
22
+ return new Uint8Array(size);
23
+ }
24
+ /**
25
+ * Where possible returns a Uint8Array of the requested size that references
26
+ * uninitialized memory. Only use if you are certain you will immediately
27
+ * overwrite every value in the returned `Uint8Array`.
28
+ */
29
+ function allocUnsafe(size = 0) {
30
+ if (globalThis.Buffer?.allocUnsafe != null) {
31
+ return asUint8Array(globalThis.Buffer.allocUnsafe(size));
32
+ }
33
+ return new Uint8Array(size);
34
+ }
35
+
36
+ const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };
37
+
38
+ function createCodec(name, prefix, encode, decode) {
39
+ return {
40
+ name,
41
+ prefix,
42
+ encoder: {
43
+ name,
44
+ prefix,
45
+ encode
46
+ },
47
+ decoder: {
48
+ decode
49
+ }
50
+ };
51
+ }
52
+ const string = createCodec('utf8', 'u', (buf) => {
53
+ const decoder = new TextDecoder('utf8');
54
+ return 'u' + decoder.decode(buf);
55
+ }, (str) => {
56
+ const encoder = new TextEncoder();
57
+ return encoder.encode(str.substring(1));
58
+ });
59
+ const ascii = createCodec('ascii', 'a', (buf) => {
60
+ let string = 'a';
61
+ for (let i = 0; i < buf.length; i++) {
62
+ string += String.fromCharCode(buf[i]);
63
+ }
64
+ return string;
65
+ }, (str) => {
66
+ str = str.substring(1);
67
+ const buf = allocUnsafe(str.length);
68
+ for (let i = 0; i < str.length; i++) {
69
+ buf[i] = str.charCodeAt(i);
70
+ }
71
+ return buf;
72
+ });
73
+ const BASES = {
74
+ utf8: string,
75
+ 'utf-8': string,
76
+ hex: bases.base16,
77
+ latin1: ascii,
78
+ ascii,
79
+ binary: ascii,
80
+ ...bases
81
+ };
82
+
83
+ /**
84
+ * Create a `Uint8Array` from the passed string
85
+ *
86
+ * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
87
+ *
88
+ * Also `ascii` which is similar to node's 'binary' encoding.
89
+ */
90
+ function fromString(string, encoding = 'utf8') {
91
+ const base = BASES[encoding];
92
+ if (base == null) {
93
+ throw new Error(`Unsupported encoding "${encoding}"`);
94
+ }
95
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
96
+ return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
97
+ }
98
+ // add multibase prefix
99
+ return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
100
+ }
101
+
102
+ // copied from utils
103
+ function isBytes$1(a) {
104
+ return (a instanceof Uint8Array ||
105
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
106
+ }
107
+ function bytes(b, ...lengths) {
108
+ if (!isBytes$1(b))
109
+ throw new Error('Expected Uint8Array');
110
+ if (lengths.length > 0 && !lengths.includes(b.length))
111
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
112
+ }
113
+ function exists(instance, checkFinished = true) {
114
+ if (instance.destroyed)
115
+ throw new Error('Hash instance has been destroyed');
116
+ if (checkFinished && instance.finished)
117
+ throw new Error('Hash#digest() has already been called');
118
+ }
119
+ function output(out, instance) {
120
+ bytes(out);
121
+ const min = instance.outputLen;
122
+ if (out.length < min) {
123
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
124
+ }
125
+ }
126
+
127
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
128
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
129
+ // node.js versions earlier than v19 don't declare it in global scope.
130
+ // For node.js, package.json#exports field mapping rewrites import
131
+ // from `crypto` to `cryptoNode`, which imports native module.
132
+ // Makes the utils un-importable in browsers without a bundler.
133
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
134
+ function isBytes(a) {
135
+ return (a instanceof Uint8Array ||
136
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
137
+ }
138
+ // Cast array to view
139
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
140
+ // The rotate right (circular right shift) operation for uint32
141
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
142
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
143
+ // early-throw an error because we don't support BE yet.
144
+ // Other libraries would silently corrupt the data instead of throwing an error,
145
+ // when they don't support it.
146
+ const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
147
+ if (!isLE)
148
+ throw new Error('Non little-endian hardware is not supported');
149
+ /**
150
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
151
+ */
152
+ function utf8ToBytes$1(str) {
153
+ if (typeof str !== 'string')
154
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
155
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
156
+ }
157
+ /**
158
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
159
+ * Warning: when Uint8Array is passed, it would NOT get copied.
160
+ * Keep in mind for future mutable operations.
161
+ */
162
+ function toBytes(data) {
163
+ if (typeof data === 'string')
164
+ data = utf8ToBytes$1(data);
165
+ if (!isBytes(data))
166
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
167
+ return data;
168
+ }
169
+ // For runtime check if class implements interface
170
+ class Hash {
171
+ // Safe version that clones internal state
172
+ clone() {
173
+ return this._cloneInto();
174
+ }
175
+ }
176
+ function wrapConstructor(hashCons) {
177
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
178
+ const tmp = hashCons();
179
+ hashC.outputLen = tmp.outputLen;
180
+ hashC.blockLen = tmp.blockLen;
181
+ hashC.create = () => hashCons();
182
+ return hashC;
183
+ }
184
+
185
+ // Polyfill for Safari 14
186
+ function setBigUint64(view, byteOffset, value, isLE) {
187
+ if (typeof view.setBigUint64 === 'function')
188
+ return view.setBigUint64(byteOffset, value, isLE);
189
+ const _32n = BigInt(32);
190
+ const _u32_max = BigInt(0xffffffff);
191
+ const wh = Number((value >> _32n) & _u32_max);
192
+ const wl = Number(value & _u32_max);
193
+ const h = isLE ? 4 : 0;
194
+ const l = isLE ? 0 : 4;
195
+ view.setUint32(byteOffset + h, wh, isLE);
196
+ view.setUint32(byteOffset + l, wl, isLE);
197
+ }
198
+ // Base SHA2 class (RFC 6234)
199
+ class SHA2 extends Hash {
200
+ constructor(blockLen, outputLen, padOffset, isLE) {
201
+ super();
202
+ this.blockLen = blockLen;
203
+ this.outputLen = outputLen;
204
+ this.padOffset = padOffset;
205
+ this.isLE = isLE;
206
+ this.finished = false;
207
+ this.length = 0;
208
+ this.pos = 0;
209
+ this.destroyed = false;
210
+ this.buffer = new Uint8Array(blockLen);
211
+ this.view = createView(this.buffer);
212
+ }
213
+ update(data) {
214
+ exists(this);
215
+ const { view, buffer, blockLen } = this;
216
+ data = toBytes(data);
217
+ const len = data.length;
218
+ for (let pos = 0; pos < len;) {
219
+ const take = Math.min(blockLen - this.pos, len - pos);
220
+ // Fast path: we have at least one block in input, cast it to view and process
221
+ if (take === blockLen) {
222
+ const dataView = createView(data);
223
+ for (; blockLen <= len - pos; pos += blockLen)
224
+ this.process(dataView, pos);
225
+ continue;
226
+ }
227
+ buffer.set(data.subarray(pos, pos + take), this.pos);
228
+ this.pos += take;
229
+ pos += take;
230
+ if (this.pos === blockLen) {
231
+ this.process(view, 0);
232
+ this.pos = 0;
233
+ }
234
+ }
235
+ this.length += data.length;
236
+ this.roundClean();
237
+ return this;
238
+ }
239
+ digestInto(out) {
240
+ exists(this);
241
+ output(out, this);
242
+ this.finished = true;
243
+ // Padding
244
+ // We can avoid allocation of buffer for padding completely if it
245
+ // was previously not allocated here. But it won't change performance.
246
+ const { buffer, view, blockLen, isLE } = this;
247
+ let { pos } = this;
248
+ // append the bit '1' to the message
249
+ buffer[pos++] = 0b10000000;
250
+ this.buffer.subarray(pos).fill(0);
251
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
252
+ if (this.padOffset > blockLen - pos) {
253
+ this.process(view, 0);
254
+ pos = 0;
255
+ }
256
+ // Pad until full block byte with zeros
257
+ for (let i = pos; i < blockLen; i++)
258
+ buffer[i] = 0;
259
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
260
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
261
+ // So we just write lowest 64 bits of that value.
262
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
263
+ this.process(view, 0);
264
+ const oview = createView(out);
265
+ const len = this.outputLen;
266
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
267
+ if (len % 4)
268
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
269
+ const outLen = len / 4;
270
+ const state = this.get();
271
+ if (outLen > state.length)
272
+ throw new Error('_sha2: outputLen bigger than state');
273
+ for (let i = 0; i < outLen; i++)
274
+ oview.setUint32(4 * i, state[i], isLE);
275
+ }
276
+ digest() {
277
+ const { buffer, outputLen } = this;
278
+ this.digestInto(buffer);
279
+ const res = buffer.slice(0, outputLen);
280
+ this.destroy();
281
+ return res;
282
+ }
283
+ _cloneInto(to) {
284
+ to || (to = new this.constructor());
285
+ to.set(...this.get());
286
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
287
+ to.length = length;
288
+ to.pos = pos;
289
+ to.finished = finished;
290
+ to.destroyed = destroyed;
291
+ if (length % blockLen)
292
+ to.buffer.set(buffer);
293
+ return to;
294
+ }
295
+ }
296
+
297
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
298
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
299
+ // Choice: a ? b : c
300
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
301
+ // Majority function, true if any two inpust is true
302
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
303
+ // Round constants:
304
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
305
+ // prettier-ignore
306
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
307
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
308
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
309
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
310
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
311
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
312
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
313
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
314
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
315
+ ]);
316
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
317
+ // prettier-ignore
318
+ const IV = /* @__PURE__ */ new Uint32Array([
319
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
320
+ ]);
321
+ // Temporary buffer, not used to store anything between runs
322
+ // Named this way because it matches specification.
323
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
324
+ class SHA256 extends SHA2 {
325
+ constructor() {
326
+ super(64, 32, 8, false);
327
+ // We cannot use array here since array allows indexing by variable
328
+ // which means optimizer/compiler cannot use registers.
329
+ this.A = IV[0] | 0;
330
+ this.B = IV[1] | 0;
331
+ this.C = IV[2] | 0;
332
+ this.D = IV[3] | 0;
333
+ this.E = IV[4] | 0;
334
+ this.F = IV[5] | 0;
335
+ this.G = IV[6] | 0;
336
+ this.H = IV[7] | 0;
337
+ }
338
+ get() {
339
+ const { A, B, C, D, E, F, G, H } = this;
340
+ return [A, B, C, D, E, F, G, H];
341
+ }
342
+ // prettier-ignore
343
+ set(A, B, C, D, E, F, G, H) {
344
+ this.A = A | 0;
345
+ this.B = B | 0;
346
+ this.C = C | 0;
347
+ this.D = D | 0;
348
+ this.E = E | 0;
349
+ this.F = F | 0;
350
+ this.G = G | 0;
351
+ this.H = H | 0;
352
+ }
353
+ process(view, offset) {
354
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
355
+ for (let i = 0; i < 16; i++, offset += 4)
356
+ SHA256_W[i] = view.getUint32(offset, false);
357
+ for (let i = 16; i < 64; i++) {
358
+ const W15 = SHA256_W[i - 15];
359
+ const W2 = SHA256_W[i - 2];
360
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
361
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
362
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
363
+ }
364
+ // Compression function main loop, 64 rounds
365
+ let { A, B, C, D, E, F, G, H } = this;
366
+ for (let i = 0; i < 64; i++) {
367
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
368
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
369
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
370
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
371
+ H = G;
372
+ G = F;
373
+ F = E;
374
+ E = (D + T1) | 0;
375
+ D = C;
376
+ C = B;
377
+ B = A;
378
+ A = (T1 + T2) | 0;
379
+ }
380
+ // Add the compressed chunk to the current hash value
381
+ A = (A + this.A) | 0;
382
+ B = (B + this.B) | 0;
383
+ C = (C + this.C) | 0;
384
+ D = (D + this.D) | 0;
385
+ E = (E + this.E) | 0;
386
+ F = (F + this.F) | 0;
387
+ G = (G + this.G) | 0;
388
+ H = (H + this.H) | 0;
389
+ this.set(A, B, C, D, E, F, G, H);
390
+ }
391
+ roundClean() {
392
+ SHA256_W.fill(0);
393
+ }
394
+ destroy() {
395
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
396
+ this.buffer.fill(0);
397
+ }
398
+ }
399
+ /**
400
+ * SHA2-256 hash function
401
+ * @param message - data that would be hashed
402
+ */
403
+ const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
404
+
405
+ /**
406
+ * DefaultPubsubTopic is the default gossipsub topic to use for Waku.
407
+ */
408
+ const DefaultPubsubTopic = "/waku/2/default-waku/proto";
409
+ /**
410
+ * The default cluster ID for The Waku Network
411
+ */
412
+ const DEFAULT_CLUSTER_ID = 1;
413
+
414
+ /**
415
+ * Turns a `Uint8Array` into a string.
416
+ *
417
+ * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
418
+ *
419
+ * Also `ascii` which is similar to node's 'binary' encoding.
420
+ */
421
+ function toString(array, encoding = 'utf8') {
422
+ const base = BASES[encoding];
423
+ if (base == null) {
424
+ throw new Error(`Unsupported encoding "${encoding}"`);
425
+ }
426
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
427
+ return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
428
+ }
429
+ // strip multibase prefix
430
+ return base.encoder.encode(array).substring(1);
431
+ }
432
+
433
+ /**
434
+ * Decode byte array to utf-8 string.
435
+ */
436
+ const bytesToUtf8 = (b) => toString(b, "utf8");
437
+ /**
438
+ * Encode utf-8 string to byte array.
439
+ */
440
+ const utf8ToBytes = (s) => fromString(s, "utf8");
441
+ /**
442
+ * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
443
+ */
444
+ function concat(byteArrays, totalLength) {
445
+ const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
446
+ const res = new Uint8Array(len);
447
+ let offset = 0;
448
+ for (const bytes of byteArrays) {
449
+ res.set(bytes, offset);
450
+ offset += bytes.length;
451
+ }
452
+ return res;
453
+ }
454
+
455
+ const singleShardInfoToPubsubTopic = (shardInfo) => {
456
+ if (shardInfo.clusterId === undefined || shardInfo.shard === undefined)
457
+ throw new Error("Invalid shard");
458
+ return `/waku/2/rs/${shardInfo.clusterId}/${shardInfo.shard}`;
459
+ };
460
+ const shardInfoToPubsubTopics = (shardInfo) => {
461
+ if ("contentTopics" in shardInfo && shardInfo.contentTopics) {
462
+ // Autosharding: explicitly defined content topics
463
+ return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));
464
+ }
465
+ else if ("shards" in shardInfo) {
466
+ // Static sharding
467
+ if (shardInfo.shards === undefined)
468
+ throw new Error("Invalid shard");
469
+ return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${index}`)));
470
+ }
471
+ else if ("application" in shardInfo && "version" in shardInfo) {
472
+ // Autosharding: single shard from application and version
473
+ return [
474
+ contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`)
475
+ ];
476
+ }
477
+ else {
478
+ throw new Error("Missing required configuration in shard parameters");
479
+ }
480
+ };
481
+ const pubsubTopicToSingleShardInfo = (pubsubTopics) => {
482
+ const parts = pubsubTopics.split("/");
483
+ if (parts.length != 6 ||
484
+ parts[1] !== "waku" ||
485
+ parts[2] !== "2" ||
486
+ parts[3] !== "rs")
487
+ throw new Error("Invalid pubsub topic");
488
+ const clusterId = parseInt(parts[4]);
489
+ const shard = parseInt(parts[5]);
490
+ if (isNaN(clusterId) || isNaN(shard))
491
+ throw new Error("Invalid clusterId or shard");
492
+ return {
493
+ clusterId,
494
+ shard
495
+ };
496
+ };
497
+ function ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {
498
+ if (!configuredTopics.includes(pubsubTopic)) {
499
+ throw new Error(`Pubsub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);
500
+ }
501
+ }
502
+ /**
503
+ * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/
504
+ * @param contentTopic String to validate
505
+ * @returns Object with each content topic field as an attribute
506
+ */
507
+ function ensureValidContentTopic(contentTopic) {
508
+ const parts = contentTopic.split("/");
509
+ if (parts.length < 5 || parts.length > 6) {
510
+ throw Error("Content topic format is invalid");
511
+ }
512
+ // Validate generation field if present
513
+ let generation = 0;
514
+ if (parts.length == 6) {
515
+ generation = parseInt(parts[1]);
516
+ if (isNaN(generation)) {
517
+ throw new Error("Invalid generation field in content topic");
518
+ }
519
+ if (generation > 0) {
520
+ throw new Error("Generation greater than 0 is not supported");
521
+ }
522
+ }
523
+ // Validate remaining fields
524
+ const fields = parts.splice(-4);
525
+ // Validate application field
526
+ if (fields[0].length == 0) {
527
+ throw new Error("Application field cannot be empty");
528
+ }
529
+ // Validate version field
530
+ if (fields[1].length == 0) {
531
+ throw new Error("Version field cannot be empty");
532
+ }
533
+ // Validate topic name field
534
+ if (fields[2].length == 0) {
535
+ throw new Error("Topic name field cannot be empty");
536
+ }
537
+ // Validate encoding field
538
+ if (fields[3].length == 0) {
539
+ throw new Error("Encoding field cannot be empty");
540
+ }
541
+ return {
542
+ generation,
543
+ application: fields[0],
544
+ version: fields[1],
545
+ topicName: fields[2],
546
+ encoding: fields[3]
547
+ };
548
+ }
549
+ /**
550
+ * Given a string, determines which autoshard index to use for its pubsub topic.
551
+ * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm
552
+ */
553
+ function contentTopicToShardIndex(contentTopic, networkShards = 8) {
554
+ const { application, version } = ensureValidContentTopic(contentTopic);
555
+ const digest = sha256(concat([utf8ToBytes(application), utf8ToBytes(version)]));
556
+ const dataview = new DataView(digest.buffer.slice(-8));
557
+ return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));
558
+ }
559
+ function contentTopicToPubsubTopic(contentTopic, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {
560
+ const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);
561
+ return `/waku/2/rs/${clusterId}/${shardIndex}`;
562
+ }
563
+ /**
564
+ * Used when creating encoders/decoders to determine which pubsub topic to use
565
+ */
566
+ function determinePubsubTopic(contentTopic, pubsubTopicShardInfo = DefaultPubsubTopic) {
567
+ if (typeof pubsubTopicShardInfo == "string") {
568
+ return pubsubTopicShardInfo;
569
+ }
570
+ else {
571
+ return pubsubTopicShardInfo
572
+ ? pubsubTopicShardInfo.shard
573
+ ? singleShardInfoToPubsubTopic(pubsubTopicShardInfo)
574
+ : contentTopicToPubsubTopic(contentTopic, pubsubTopicShardInfo.clusterId)
575
+ : DefaultPubsubTopic;
576
+ }
577
+ }
578
+ /**
579
+ * Validates sharding configuration and sets defaults where possible.
580
+ * @returns Validated sharding parameters, with any missing values set to defaults
581
+ */
582
+ const ensureShardingConfigured = (shardInfo) => {
583
+ const clusterId = shardInfo.clusterId ?? DEFAULT_CLUSTER_ID;
584
+ const shards = "shards" in shardInfo ? shardInfo.shards : [];
585
+ const contentTopics = "contentTopics" in shardInfo ? shardInfo.contentTopics : [];
586
+ const [application, version] = "application" in shardInfo && "version" in shardInfo
587
+ ? [shardInfo.application, shardInfo.version]
588
+ : [undefined, undefined];
589
+ const isShardsConfigured = shards && shards.length > 0;
590
+ const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;
591
+ const isApplicationVersionConfigured = application && version;
592
+ if (isShardsConfigured) {
593
+ return {
594
+ shardingParams: { clusterId, shards },
595
+ shardInfo: { clusterId, shards },
596
+ pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })
597
+ };
598
+ }
599
+ if (isContentTopicsConfigured) {
600
+ const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));
601
+ const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));
602
+ return {
603
+ shardingParams: { clusterId, contentTopics },
604
+ shardInfo: { clusterId, shards },
605
+ pubsubTopics
606
+ };
607
+ }
608
+ if (isApplicationVersionConfigured) {
609
+ const pubsubTopic = contentTopicToPubsubTopic(`/${application}/${version}/default/default`);
610
+ return {
611
+ shardingParams: { clusterId, application, version },
612
+ shardInfo: {
613
+ clusterId,
614
+ shards: [pubsubTopicToSingleShardInfo(pubsubTopic).shard]
615
+ },
616
+ pubsubTopics: [pubsubTopic]
617
+ };
618
+ }
619
+ throw new Error("Missing minimum required configuration options for static sharding or autosharding.");
620
+ };
621
+
622
+ const APP_NAME = "waku";
623
+ class Logger {
624
+ _info;
625
+ _warn;
626
+ _error;
627
+ static createDebugNamespace(level, prefix) {
628
+ return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;
629
+ }
630
+ constructor(prefix) {
631
+ this._info = debug(Logger.createDebugNamespace("info", prefix));
632
+ this._warn = debug(Logger.createDebugNamespace("warn", prefix));
633
+ this._error = debug(Logger.createDebugNamespace("error", prefix));
634
+ }
635
+ get info() {
636
+ return this._info;
637
+ }
638
+ get warn() {
639
+ return this._warn;
640
+ }
641
+ get error() {
642
+ return this._error;
643
+ }
644
+ log(level, ...args) {
645
+ const logger = this[level];
646
+ logger(...args);
647
+ }
648
+ }
649
+
650
+ export { DefaultPubsubTopic as D, Logger as L, asUint8Array as a, bytesToUtf8 as b, concat as c, allocUnsafe as d, alloc as e, singleShardInfoToPubsubTopic as f, ensurePubsubTopicIsConfigured as g, shardInfoToPubsubTopics as h, fromString as i, determinePubsubTopic as j, ensureShardingConfigured as k, pubsubTopicToSingleShardInfo as p, sha256 as s, utf8ToBytes as u };