@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,2962 +0,0 @@
1
- import { e as errCode } from './index-64ce43f0.js';
2
-
3
- /* eslint-disable @typescript-eslint/no-unsafe-return */
4
- class Parser {
5
- index = 0;
6
- input = "";
7
- new(input) {
8
- this.index = 0;
9
- this.input = input;
10
- return this;
11
- }
12
- /** Run a parser, and restore the pre-parse state if it fails. */
13
- readAtomically(fn) {
14
- const index = this.index;
15
- const result = fn();
16
- if (result === undefined) {
17
- this.index = index;
18
- }
19
- return result;
20
- }
21
- /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */
22
- parseWith(fn) {
23
- const result = fn();
24
- if (this.index !== this.input.length) {
25
- return undefined;
26
- }
27
- return result;
28
- }
29
- /** Peek the next character from the input */
30
- peekChar() {
31
- if (this.index >= this.input.length) {
32
- return undefined;
33
- }
34
- return this.input[this.index];
35
- }
36
- /** Read the next character from the input */
37
- readChar() {
38
- if (this.index >= this.input.length) {
39
- return undefined;
40
- }
41
- return this.input[this.index++];
42
- }
43
- /** Read the next character from the input if it matches the target. */
44
- readGivenChar(target) {
45
- return this.readAtomically(() => {
46
- const char = this.readChar();
47
- if (char !== target) {
48
- return undefined;
49
- }
50
- return char;
51
- });
52
- }
53
- /**
54
- * Helper for reading separators in an indexed loop. Reads the separator
55
- * character iff index > 0, then runs the parser. When used in a loop,
56
- * the separator character will only be read on index > 0 (see
57
- * readIPv4Addr for an example)
58
- */
59
- readSeparator(sep, index, inner) {
60
- return this.readAtomically(() => {
61
- if (index > 0) {
62
- if (this.readGivenChar(sep) === undefined) {
63
- return undefined;
64
- }
65
- }
66
- return inner();
67
- });
68
- }
69
- /**
70
- * Read a number off the front of the input in the given radix, stopping
71
- * at the first non-digit character or eof. Fails if the number has more
72
- * digits than max_digits or if there is no number.
73
- */
74
- readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {
75
- return this.readAtomically(() => {
76
- let result = 0;
77
- let digitCount = 0;
78
- const leadingChar = this.peekChar();
79
- if (leadingChar === undefined) {
80
- return undefined;
81
- }
82
- const hasLeadingZero = leadingChar === "0";
83
- const maxValue = 2 ** (8 * maxBytes) - 1;
84
- // eslint-disable-next-line no-constant-condition
85
- while (true) {
86
- const digit = this.readAtomically(() => {
87
- const char = this.readChar();
88
- if (char === undefined) {
89
- return undefined;
90
- }
91
- const num = Number.parseInt(char, radix);
92
- if (Number.isNaN(num)) {
93
- return undefined;
94
- }
95
- return num;
96
- });
97
- if (digit === undefined) {
98
- break;
99
- }
100
- result *= radix;
101
- result += digit;
102
- if (result > maxValue) {
103
- return undefined;
104
- }
105
- digitCount += 1;
106
- if (maxDigits !== undefined) {
107
- if (digitCount > maxDigits) {
108
- return undefined;
109
- }
110
- }
111
- }
112
- if (digitCount === 0) {
113
- return undefined;
114
- }
115
- else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {
116
- return undefined;
117
- }
118
- else {
119
- return result;
120
- }
121
- });
122
- }
123
- /** Read an IPv4 address. */
124
- readIPv4Addr() {
125
- return this.readAtomically(() => {
126
- const out = new Uint8Array(4);
127
- for (let i = 0; i < out.length; i++) {
128
- const ix = this.readSeparator(".", i, () => this.readNumber(10, 3, false, 1));
129
- if (ix === undefined) {
130
- return undefined;
131
- }
132
- out[i] = ix;
133
- }
134
- return out;
135
- });
136
- }
137
- /** Read an IPv6 Address. */
138
- readIPv6Addr() {
139
- /**
140
- * Read a chunk of an IPv6 address into `groups`. Returns the number
141
- * of groups read, along with a bool indicating if an embedded
142
- * trailing IPv4 address was read. Specifically, read a series of
143
- * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
144
- * trailing embedded IPv4 address.
145
- */
146
- const readGroups = (groups) => {
147
- for (let i = 0; i < groups.length / 2; i++) {
148
- const ix = i * 2;
149
- // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.
150
- if (i < groups.length - 3) {
151
- const ipv4 = this.readSeparator(":", i, () => this.readIPv4Addr());
152
- if (ipv4 !== undefined) {
153
- groups[ix] = ipv4[0];
154
- groups[ix + 1] = ipv4[1];
155
- groups[ix + 2] = ipv4[2];
156
- groups[ix + 3] = ipv4[3];
157
- return [ix + 4, true];
158
- }
159
- }
160
- const group = this.readSeparator(":", i, () => this.readNumber(16, 4, true, 2));
161
- if (group === undefined) {
162
- return [ix, false];
163
- }
164
- groups[ix] = group >> 8;
165
- groups[ix + 1] = group & 255;
166
- }
167
- return [groups.length, false];
168
- };
169
- return this.readAtomically(() => {
170
- // Read the front part of the address; either the whole thing, or up to the first ::
171
- const head = new Uint8Array(16);
172
- const [headSize, headIp4] = readGroups(head);
173
- if (headSize === 16) {
174
- return head;
175
- }
176
- // IPv4 part is not allowed before `::`
177
- if (headIp4) {
178
- return undefined;
179
- }
180
- // Read `::` if previous code parsed less than 8 groups.
181
- // `::` indicates one or more groups of 16 bits of zeros.
182
- if (this.readGivenChar(":") === undefined) {
183
- return undefined;
184
- }
185
- if (this.readGivenChar(":") === undefined) {
186
- return undefined;
187
- }
188
- // Read the back part of the address. The :: must contain at least one
189
- // set of zeroes, so our max length is 7.
190
- const tail = new Uint8Array(14);
191
- const limit = 16 - (headSize + 2);
192
- const [tailSize] = readGroups(tail.subarray(0, limit));
193
- // Concat the head and tail of the IP address
194
- head.set(tail.subarray(0, tailSize), 16 - tailSize);
195
- return head;
196
- });
197
- }
198
- /** Read an IP Address, either IPv4 or IPv6. */
199
- readIPAddr() {
200
- return this.readIPv4Addr() ?? this.readIPv6Addr();
201
- }
202
- }
203
-
204
- // See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address
205
- const MAX_IPV6_LENGTH = 45;
206
- const MAX_IPV4_LENGTH = 15;
207
- const parser = new Parser();
208
- /** Parse `input` into IPv4 bytes. */
209
- function parseIPv4(input) {
210
- if (input.length > MAX_IPV4_LENGTH) {
211
- return undefined;
212
- }
213
- return parser.new(input).parseWith(() => parser.readIPv4Addr());
214
- }
215
- /** Parse `input` into IPv6 bytes. */
216
- function parseIPv6(input) {
217
- if (input.length > MAX_IPV6_LENGTH) {
218
- return undefined;
219
- }
220
- return parser.new(input).parseWith(() => parser.readIPv6Addr());
221
- }
222
- /** Parse `input` into IPv4 or IPv6 bytes. */
223
- function parseIP(input) {
224
- if (input.length > MAX_IPV6_LENGTH) {
225
- return undefined;
226
- }
227
- return parser.new(input).parseWith(() => parser.readIPAddr());
228
- }
229
-
230
- /** Check if `input` is IPv4. */
231
- function isIPv4(input) {
232
- return Boolean(parseIPv4(input));
233
- }
234
- /** Check if `input` is IPv6. */
235
- function isIPv6(input) {
236
- return Boolean(parseIPv6(input));
237
- }
238
- /** Check if `input` is IPv4 or IPv6. */
239
- function isIP(input) {
240
- return Boolean(parseIP(input));
241
- }
242
-
243
- // base-x encoding / decoding
244
- // Copyright (c) 2018 base-x contributors
245
- // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
246
- // Distributed under the MIT software license, see the accompanying
247
- // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
248
- function base (ALPHABET, name) {
249
- if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
250
- var BASE_MAP = new Uint8Array(256);
251
- for (var j = 0; j < BASE_MAP.length; j++) {
252
- BASE_MAP[j] = 255;
253
- }
254
- for (var i = 0; i < ALPHABET.length; i++) {
255
- var x = ALPHABET.charAt(i);
256
- var xc = x.charCodeAt(0);
257
- if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
258
- BASE_MAP[xc] = i;
259
- }
260
- var BASE = ALPHABET.length;
261
- var LEADER = ALPHABET.charAt(0);
262
- var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
263
- var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
264
- function encode (source) {
265
- if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
266
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
267
- } else if (Array.isArray(source)) {
268
- source = Uint8Array.from(source);
269
- }
270
- if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
271
- if (source.length === 0) { return '' }
272
- // Skip & count leading zeroes.
273
- var zeroes = 0;
274
- var length = 0;
275
- var pbegin = 0;
276
- var pend = source.length;
277
- while (pbegin !== pend && source[pbegin] === 0) {
278
- pbegin++;
279
- zeroes++;
280
- }
281
- // Allocate enough space in big-endian base58 representation.
282
- var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
283
- var b58 = new Uint8Array(size);
284
- // Process the bytes.
285
- while (pbegin !== pend) {
286
- var carry = source[pbegin];
287
- // Apply "b58 = b58 * 256 + ch".
288
- var i = 0;
289
- for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
290
- carry += (256 * b58[it1]) >>> 0;
291
- b58[it1] = (carry % BASE) >>> 0;
292
- carry = (carry / BASE) >>> 0;
293
- }
294
- if (carry !== 0) { throw new Error('Non-zero carry') }
295
- length = i;
296
- pbegin++;
297
- }
298
- // Skip leading zeroes in base58 result.
299
- var it2 = size - length;
300
- while (it2 !== size && b58[it2] === 0) {
301
- it2++;
302
- }
303
- // Translate the result into a string.
304
- var str = LEADER.repeat(zeroes);
305
- for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
306
- return str
307
- }
308
- function decodeUnsafe (source) {
309
- if (typeof source !== 'string') { throw new TypeError('Expected String') }
310
- if (source.length === 0) { return new Uint8Array() }
311
- var psz = 0;
312
- // Skip leading spaces.
313
- if (source[psz] === ' ') { return }
314
- // Skip and count leading '1's.
315
- var zeroes = 0;
316
- var length = 0;
317
- while (source[psz] === LEADER) {
318
- zeroes++;
319
- psz++;
320
- }
321
- // Allocate enough space in big-endian base256 representation.
322
- var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
323
- var b256 = new Uint8Array(size);
324
- // Process the characters.
325
- while (source[psz]) {
326
- // Decode character
327
- var carry = BASE_MAP[source.charCodeAt(psz)];
328
- // Invalid character
329
- if (carry === 255) { return }
330
- var i = 0;
331
- for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
332
- carry += (BASE * b256[it3]) >>> 0;
333
- b256[it3] = (carry % 256) >>> 0;
334
- carry = (carry / 256) >>> 0;
335
- }
336
- if (carry !== 0) { throw new Error('Non-zero carry') }
337
- length = i;
338
- psz++;
339
- }
340
- // Skip trailing spaces.
341
- if (source[psz] === ' ') { return }
342
- // Skip leading zeroes in b256.
343
- var it4 = size - length;
344
- while (it4 !== size && b256[it4] === 0) {
345
- it4++;
346
- }
347
- var vch = new Uint8Array(zeroes + (size - it4));
348
- var j = zeroes;
349
- while (it4 !== size) {
350
- vch[j++] = b256[it4++];
351
- }
352
- return vch
353
- }
354
- function decode (string) {
355
- var buffer = decodeUnsafe(string);
356
- if (buffer) { return buffer }
357
- throw new Error(`Non-${name} character`)
358
- }
359
- return {
360
- encode: encode,
361
- decodeUnsafe: decodeUnsafe,
362
- decode: decode
363
- }
364
- }
365
- var src = base;
366
-
367
- var _brrp__multiformats_scope_baseX = src;
368
-
369
- /**
370
- * @param {Uint8Array} aa
371
- * @param {Uint8Array} bb
372
- */
373
- const equals$2 = (aa, bb) => {
374
- if (aa === bb) return true
375
- if (aa.byteLength !== bb.byteLength) {
376
- return false
377
- }
378
-
379
- for (let ii = 0; ii < aa.byteLength; ii++) {
380
- if (aa[ii] !== bb[ii]) {
381
- return false
382
- }
383
- }
384
-
385
- return true
386
- };
387
-
388
- /**
389
- * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
390
- * @returns {Uint8Array}
391
- */
392
- const coerce = o => {
393
- if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
394
- if (o instanceof ArrayBuffer) return new Uint8Array(o)
395
- if (ArrayBuffer.isView(o)) {
396
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
397
- }
398
- throw new Error('Unknown type, must be binary type')
399
- };
400
-
401
- /**
402
- * @param {string} str
403
- * @returns {Uint8Array}
404
- */
405
- const fromString$2 = str => (new TextEncoder()).encode(str);
406
-
407
- /**
408
- * @param {Uint8Array} b
409
- * @returns {string}
410
- */
411
- const toString$2 = b => (new TextDecoder()).decode(b);
412
-
413
- /**
414
- * Class represents both BaseEncoder and MultibaseEncoder meaning it
415
- * can be used to encode to multibase or base encode without multibase
416
- * prefix.
417
- *
418
- * @class
419
- * @template {string} Base
420
- * @template {string} Prefix
421
- * @implements {API.MultibaseEncoder<Prefix>}
422
- * @implements {API.BaseEncoder}
423
- */
424
- class Encoder {
425
- /**
426
- * @param {Base} name
427
- * @param {Prefix} prefix
428
- * @param {(bytes:Uint8Array) => string} baseEncode
429
- */
430
- constructor (name, prefix, baseEncode) {
431
- this.name = name;
432
- this.prefix = prefix;
433
- this.baseEncode = baseEncode;
434
- }
435
-
436
- /**
437
- * @param {Uint8Array} bytes
438
- * @returns {API.Multibase<Prefix>}
439
- */
440
- encode (bytes) {
441
- if (bytes instanceof Uint8Array) {
442
- return `${this.prefix}${this.baseEncode(bytes)}`
443
- } else {
444
- throw Error('Unknown type, must be binary type')
445
- }
446
- }
447
- }
448
-
449
- /**
450
- * @template {string} Prefix
451
- */
452
- /**
453
- * Class represents both BaseDecoder and MultibaseDecoder so it could be used
454
- * to decode multibases (with matching prefix) or just base decode strings
455
- * with corresponding base encoding.
456
- *
457
- * @class
458
- * @template {string} Base
459
- * @template {string} Prefix
460
- * @implements {API.MultibaseDecoder<Prefix>}
461
- * @implements {API.UnibaseDecoder<Prefix>}
462
- * @implements {API.BaseDecoder}
463
- */
464
- class Decoder {
465
- /**
466
- * @param {Base} name
467
- * @param {Prefix} prefix
468
- * @param {(text:string) => Uint8Array} baseDecode
469
- */
470
- constructor (name, prefix, baseDecode) {
471
- this.name = name;
472
- this.prefix = prefix;
473
- /* c8 ignore next 3 */
474
- if (prefix.codePointAt(0) === undefined) {
475
- throw new Error('Invalid prefix character')
476
- }
477
- /** @private */
478
- this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0));
479
- this.baseDecode = baseDecode;
480
- }
481
-
482
- /**
483
- * @param {string} text
484
- */
485
- decode (text) {
486
- if (typeof text === 'string') {
487
- if (text.codePointAt(0) !== this.prefixCodePoint) {
488
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
489
- }
490
- return this.baseDecode(text.slice(this.prefix.length))
491
- } else {
492
- throw Error('Can only multibase decode strings')
493
- }
494
- }
495
-
496
- /**
497
- * @template {string} OtherPrefix
498
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
499
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
500
- */
501
- or (decoder) {
502
- return or(this, decoder)
503
- }
504
- }
505
-
506
- /**
507
- * @template {string} Prefix
508
- * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
509
- */
510
-
511
- /**
512
- * @template {string} Prefix
513
- * @implements {API.MultibaseDecoder<Prefix>}
514
- * @implements {API.CombobaseDecoder<Prefix>}
515
- */
516
- class ComposedDecoder {
517
- /**
518
- * @param {Decoders<Prefix>} decoders
519
- */
520
- constructor (decoders) {
521
- this.decoders = decoders;
522
- }
523
-
524
- /**
525
- * @template {string} OtherPrefix
526
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
527
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
528
- */
529
- or (decoder) {
530
- return or(this, decoder)
531
- }
532
-
533
- /**
534
- * @param {string} input
535
- * @returns {Uint8Array}
536
- */
537
- decode (input) {
538
- const prefix = /** @type {Prefix} */ (input[0]);
539
- const decoder = this.decoders[prefix];
540
- if (decoder) {
541
- return decoder.decode(input)
542
- } else {
543
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
544
- }
545
- }
546
- }
547
-
548
- /**
549
- * @template {string} L
550
- * @template {string} R
551
- * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
552
- * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
553
- * @returns {ComposedDecoder<L|R>}
554
- */
555
- const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
556
- ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
557
- ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
558
- }));
559
-
560
- /**
561
- * @class
562
- * @template {string} Base
563
- * @template {string} Prefix
564
- * @implements {API.MultibaseCodec<Prefix>}
565
- * @implements {API.MultibaseEncoder<Prefix>}
566
- * @implements {API.MultibaseDecoder<Prefix>}
567
- * @implements {API.BaseCodec}
568
- * @implements {API.BaseEncoder}
569
- * @implements {API.BaseDecoder}
570
- */
571
- class Codec {
572
- /**
573
- * @param {Base} name
574
- * @param {Prefix} prefix
575
- * @param {(bytes:Uint8Array) => string} baseEncode
576
- * @param {(text:string) => Uint8Array} baseDecode
577
- */
578
- constructor (name, prefix, baseEncode, baseDecode) {
579
- this.name = name;
580
- this.prefix = prefix;
581
- this.baseEncode = baseEncode;
582
- this.baseDecode = baseDecode;
583
- this.encoder = new Encoder(name, prefix, baseEncode);
584
- this.decoder = new Decoder(name, prefix, baseDecode);
585
- }
586
-
587
- /**
588
- * @param {Uint8Array} input
589
- */
590
- encode (input) {
591
- return this.encoder.encode(input)
592
- }
593
-
594
- /**
595
- * @param {string} input
596
- */
597
- decode (input) {
598
- return this.decoder.decode(input)
599
- }
600
- }
601
-
602
- /**
603
- * @template {string} Base
604
- * @template {string} Prefix
605
- * @param {object} options
606
- * @param {Base} options.name
607
- * @param {Prefix} options.prefix
608
- * @param {(bytes:Uint8Array) => string} options.encode
609
- * @param {(input:string) => Uint8Array} options.decode
610
- * @returns {Codec<Base, Prefix>}
611
- */
612
- const from$1 = ({ name, prefix, encode, decode }) =>
613
- new Codec(name, prefix, encode, decode);
614
-
615
- /**
616
- * @template {string} Base
617
- * @template {string} Prefix
618
- * @param {object} options
619
- * @param {Base} options.name
620
- * @param {Prefix} options.prefix
621
- * @param {string} options.alphabet
622
- * @returns {Codec<Base, Prefix>}
623
- */
624
- const baseX = ({ prefix, name, alphabet }) => {
625
- const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
626
- return from$1({
627
- prefix,
628
- name,
629
- encode,
630
- /**
631
- * @param {string} text
632
- */
633
- decode: text => coerce(decode(text))
634
- })
635
- };
636
-
637
- /**
638
- * @param {string} string
639
- * @param {string} alphabet
640
- * @param {number} bitsPerChar
641
- * @param {string} name
642
- * @returns {Uint8Array}
643
- */
644
- const decode$5 = (string, alphabet, bitsPerChar, name) => {
645
- // Build the character lookup table:
646
- /** @type {Record<string, number>} */
647
- const codes = {};
648
- for (let i = 0; i < alphabet.length; ++i) {
649
- codes[alphabet[i]] = i;
650
- }
651
-
652
- // Count the padding bytes:
653
- let end = string.length;
654
- while (string[end - 1] === '=') {
655
- --end;
656
- }
657
-
658
- // Allocate the output:
659
- const out = new Uint8Array((end * bitsPerChar / 8) | 0);
660
-
661
- // Parse the data:
662
- let bits = 0; // Number of bits currently in the buffer
663
- let buffer = 0; // Bits waiting to be written out, MSB first
664
- let written = 0; // Next byte to write
665
- for (let i = 0; i < end; ++i) {
666
- // Read one character from the string:
667
- const value = codes[string[i]];
668
- if (value === undefined) {
669
- throw new SyntaxError(`Non-${name} character`)
670
- }
671
-
672
- // Append the bits to the buffer:
673
- buffer = (buffer << bitsPerChar) | value;
674
- bits += bitsPerChar;
675
-
676
- // Write out some bits if the buffer has a byte's worth:
677
- if (bits >= 8) {
678
- bits -= 8;
679
- out[written++] = 0xff & (buffer >> bits);
680
- }
681
- }
682
-
683
- // Verify that we have received just enough bits:
684
- if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
685
- throw new SyntaxError('Unexpected end of data')
686
- }
687
-
688
- return out
689
- };
690
-
691
- /**
692
- * @param {Uint8Array} data
693
- * @param {string} alphabet
694
- * @param {number} bitsPerChar
695
- * @returns {string}
696
- */
697
- const encode$4 = (data, alphabet, bitsPerChar) => {
698
- const pad = alphabet[alphabet.length - 1] === '=';
699
- const mask = (1 << bitsPerChar) - 1;
700
- let out = '';
701
-
702
- let bits = 0; // Number of bits currently in the buffer
703
- let buffer = 0; // Bits waiting to be written out, MSB first
704
- for (let i = 0; i < data.length; ++i) {
705
- // Slurp data into the buffer:
706
- buffer = (buffer << 8) | data[i];
707
- bits += 8;
708
-
709
- // Write out as much as we can:
710
- while (bits > bitsPerChar) {
711
- bits -= bitsPerChar;
712
- out += alphabet[mask & (buffer >> bits)];
713
- }
714
- }
715
-
716
- // Partial character:
717
- if (bits) {
718
- out += alphabet[mask & (buffer << (bitsPerChar - bits))];
719
- }
720
-
721
- // Add padding characters until we hit a byte boundary:
722
- if (pad) {
723
- while ((out.length * bitsPerChar) & 7) {
724
- out += '=';
725
- }
726
- }
727
-
728
- return out
729
- };
730
-
731
- /**
732
- * RFC4648 Factory
733
- *
734
- * @template {string} Base
735
- * @template {string} Prefix
736
- * @param {object} options
737
- * @param {Base} options.name
738
- * @param {Prefix} options.prefix
739
- * @param {string} options.alphabet
740
- * @param {number} options.bitsPerChar
741
- */
742
- const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
743
- return from$1({
744
- prefix,
745
- name,
746
- encode (input) {
747
- return encode$4(input, alphabet, bitsPerChar)
748
- },
749
- decode (input) {
750
- return decode$5(input, alphabet, bitsPerChar, name)
751
- }
752
- })
753
- };
754
-
755
- // @ts-check
756
-
757
- const identity$2 = from$1({
758
- prefix: '\x00',
759
- name: 'identity',
760
- encode: (buf) => toString$2(buf),
761
- decode: (str) => fromString$2(str)
762
- });
763
-
764
- var identityBase = /*#__PURE__*/Object.freeze({
765
- __proto__: null,
766
- identity: identity$2
767
- });
768
-
769
- // @ts-check
770
-
771
- const base2 = rfc4648({
772
- prefix: '0',
773
- name: 'base2',
774
- alphabet: '01',
775
- bitsPerChar: 1
776
- });
777
-
778
- var base2$1 = /*#__PURE__*/Object.freeze({
779
- __proto__: null,
780
- base2: base2
781
- });
782
-
783
- // @ts-check
784
-
785
- const base8 = rfc4648({
786
- prefix: '7',
787
- name: 'base8',
788
- alphabet: '01234567',
789
- bitsPerChar: 3
790
- });
791
-
792
- var base8$1 = /*#__PURE__*/Object.freeze({
793
- __proto__: null,
794
- base8: base8
795
- });
796
-
797
- const base10 = baseX({
798
- prefix: '9',
799
- name: 'base10',
800
- alphabet: '0123456789'
801
- });
802
-
803
- var base10$1 = /*#__PURE__*/Object.freeze({
804
- __proto__: null,
805
- base10: base10
806
- });
807
-
808
- // @ts-check
809
-
810
- const base16 = rfc4648({
811
- prefix: 'f',
812
- name: 'base16',
813
- alphabet: '0123456789abcdef',
814
- bitsPerChar: 4
815
- });
816
-
817
- const base16upper = rfc4648({
818
- prefix: 'F',
819
- name: 'base16upper',
820
- alphabet: '0123456789ABCDEF',
821
- bitsPerChar: 4
822
- });
823
-
824
- var base16$1 = /*#__PURE__*/Object.freeze({
825
- __proto__: null,
826
- base16: base16,
827
- base16upper: base16upper
828
- });
829
-
830
- const base32 = rfc4648({
831
- prefix: 'b',
832
- name: 'base32',
833
- alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
834
- bitsPerChar: 5
835
- });
836
-
837
- const base32upper = rfc4648({
838
- prefix: 'B',
839
- name: 'base32upper',
840
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
841
- bitsPerChar: 5
842
- });
843
-
844
- const base32pad = rfc4648({
845
- prefix: 'c',
846
- name: 'base32pad',
847
- alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
848
- bitsPerChar: 5
849
- });
850
-
851
- const base32padupper = rfc4648({
852
- prefix: 'C',
853
- name: 'base32padupper',
854
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
855
- bitsPerChar: 5
856
- });
857
-
858
- const base32hex = rfc4648({
859
- prefix: 'v',
860
- name: 'base32hex',
861
- alphabet: '0123456789abcdefghijklmnopqrstuv',
862
- bitsPerChar: 5
863
- });
864
-
865
- const base32hexupper = rfc4648({
866
- prefix: 'V',
867
- name: 'base32hexupper',
868
- alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
869
- bitsPerChar: 5
870
- });
871
-
872
- const base32hexpad = rfc4648({
873
- prefix: 't',
874
- name: 'base32hexpad',
875
- alphabet: '0123456789abcdefghijklmnopqrstuv=',
876
- bitsPerChar: 5
877
- });
878
-
879
- const base32hexpadupper = rfc4648({
880
- prefix: 'T',
881
- name: 'base32hexpadupper',
882
- alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
883
- bitsPerChar: 5
884
- });
885
-
886
- const base32z = rfc4648({
887
- prefix: 'h',
888
- name: 'base32z',
889
- alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
890
- bitsPerChar: 5
891
- });
892
-
893
- var base32$1 = /*#__PURE__*/Object.freeze({
894
- __proto__: null,
895
- base32: base32,
896
- base32upper: base32upper,
897
- base32pad: base32pad,
898
- base32padupper: base32padupper,
899
- base32hex: base32hex,
900
- base32hexupper: base32hexupper,
901
- base32hexpad: base32hexpad,
902
- base32hexpadupper: base32hexpadupper,
903
- base32z: base32z
904
- });
905
-
906
- const base36 = baseX({
907
- prefix: 'k',
908
- name: 'base36',
909
- alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
910
- });
911
-
912
- const base36upper = baseX({
913
- prefix: 'K',
914
- name: 'base36upper',
915
- alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
916
- });
917
-
918
- var base36$1 = /*#__PURE__*/Object.freeze({
919
- __proto__: null,
920
- base36: base36,
921
- base36upper: base36upper
922
- });
923
-
924
- const base58btc = baseX({
925
- name: 'base58btc',
926
- prefix: 'z',
927
- alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
928
- });
929
-
930
- const base58flickr = baseX({
931
- name: 'base58flickr',
932
- prefix: 'Z',
933
- alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
934
- });
935
-
936
- var base58 = /*#__PURE__*/Object.freeze({
937
- __proto__: null,
938
- base58btc: base58btc,
939
- base58flickr: base58flickr
940
- });
941
-
942
- // @ts-check
943
-
944
- const base64 = rfc4648({
945
- prefix: 'm',
946
- name: 'base64',
947
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
948
- bitsPerChar: 6
949
- });
950
-
951
- const base64pad = rfc4648({
952
- prefix: 'M',
953
- name: 'base64pad',
954
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
955
- bitsPerChar: 6
956
- });
957
-
958
- const base64url = rfc4648({
959
- prefix: 'u',
960
- name: 'base64url',
961
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
962
- bitsPerChar: 6
963
- });
964
-
965
- const base64urlpad = rfc4648({
966
- prefix: 'U',
967
- name: 'base64urlpad',
968
- alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
969
- bitsPerChar: 6
970
- });
971
-
972
- var base64$1 = /*#__PURE__*/Object.freeze({
973
- __proto__: null,
974
- base64: base64,
975
- base64pad: base64pad,
976
- base64url: base64url,
977
- base64urlpad: base64urlpad
978
- });
979
-
980
- const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
981
- const alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])));
982
- const alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])));
983
-
984
- /**
985
- * @param {Uint8Array} data
986
- * @returns {string}
987
- */
988
- function encode$3 (data) {
989
- return data.reduce((p, c) => {
990
- p += alphabetBytesToChars[c];
991
- return p
992
- }, '')
993
- }
994
-
995
- /**
996
- * @param {string} str
997
- * @returns {Uint8Array}
998
- */
999
- function decode$4 (str) {
1000
- const byts = [];
1001
- for (const char of str) {
1002
- const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))];
1003
- if (byt === undefined) {
1004
- throw new Error(`Non-base256emoji character: ${char}`)
1005
- }
1006
- byts.push(byt);
1007
- }
1008
- return new Uint8Array(byts)
1009
- }
1010
-
1011
- const base256emoji = from$1({
1012
- prefix: '🚀',
1013
- name: 'base256emoji',
1014
- encode: encode$3,
1015
- decode: decode$4
1016
- });
1017
-
1018
- var base256emoji$1 = /*#__PURE__*/Object.freeze({
1019
- __proto__: null,
1020
- base256emoji: base256emoji
1021
- });
1022
-
1023
- var encode_1$1 = encode$2;
1024
-
1025
- var MSB$2 = 0x80
1026
- , REST$2 = 0x7F
1027
- , MSBALL$1 = ~REST$2
1028
- , INT$1 = Math.pow(2, 31);
1029
-
1030
- function encode$2(num, out, offset) {
1031
- out = out || [];
1032
- offset = offset || 0;
1033
- var oldOffset = offset;
1034
-
1035
- while(num >= INT$1) {
1036
- out[offset++] = (num & 0xFF) | MSB$2;
1037
- num /= 128;
1038
- }
1039
- while(num & MSBALL$1) {
1040
- out[offset++] = (num & 0xFF) | MSB$2;
1041
- num >>>= 7;
1042
- }
1043
- out[offset] = num | 0;
1044
-
1045
- encode$2.bytes = offset - oldOffset + 1;
1046
-
1047
- return out
1048
- }
1049
-
1050
- var decode$3 = read$1;
1051
-
1052
- var MSB$1$1 = 0x80
1053
- , REST$1$1 = 0x7F;
1054
-
1055
- function read$1(buf, offset) {
1056
- var res = 0
1057
- , offset = offset || 0
1058
- , shift = 0
1059
- , counter = offset
1060
- , b
1061
- , l = buf.length;
1062
-
1063
- do {
1064
- if (counter >= l) {
1065
- read$1.bytes = 0;
1066
- throw new RangeError('Could not decode varint')
1067
- }
1068
- b = buf[counter++];
1069
- res += shift < 28
1070
- ? (b & REST$1$1) << shift
1071
- : (b & REST$1$1) * Math.pow(2, shift);
1072
- shift += 7;
1073
- } while (b >= MSB$1$1)
1074
-
1075
- read$1.bytes = counter - offset;
1076
-
1077
- return res
1078
- }
1079
-
1080
- var N1$1 = Math.pow(2, 7);
1081
- var N2$1 = Math.pow(2, 14);
1082
- var N3$1 = Math.pow(2, 21);
1083
- var N4$1 = Math.pow(2, 28);
1084
- var N5$1 = Math.pow(2, 35);
1085
- var N6$1 = Math.pow(2, 42);
1086
- var N7$1 = Math.pow(2, 49);
1087
- var N8$1 = Math.pow(2, 56);
1088
- var N9$1 = Math.pow(2, 63);
1089
-
1090
- var length$1 = function (value) {
1091
- return (
1092
- value < N1$1 ? 1
1093
- : value < N2$1 ? 2
1094
- : value < N3$1 ? 3
1095
- : value < N4$1 ? 4
1096
- : value < N5$1 ? 5
1097
- : value < N6$1 ? 6
1098
- : value < N7$1 ? 7
1099
- : value < N8$1 ? 8
1100
- : value < N9$1 ? 9
1101
- : 10
1102
- )
1103
- };
1104
-
1105
- var varint$1 = {
1106
- encode: encode_1$1
1107
- , decode: decode$3
1108
- , encodingLength: length$1
1109
- };
1110
-
1111
- var _brrp_varint = varint$1;
1112
-
1113
- /**
1114
- * @param {Uint8Array} data
1115
- * @param {number} [offset=0]
1116
- * @returns {[number, number]}
1117
- */
1118
- const decode$2 = (data, offset = 0) => {
1119
- const code = _brrp_varint.decode(data, offset);
1120
- return [code, _brrp_varint.decode.bytes]
1121
- };
1122
-
1123
- /**
1124
- * @param {number} int
1125
- * @param {Uint8Array} target
1126
- * @param {number} [offset=0]
1127
- */
1128
- const encodeTo = (int, target, offset = 0) => {
1129
- _brrp_varint.encode(int, target, offset);
1130
- return target
1131
- };
1132
-
1133
- /**
1134
- * @param {number} int
1135
- * @returns {number}
1136
- */
1137
- const encodingLength = (int) => {
1138
- return _brrp_varint.encodingLength(int)
1139
- };
1140
-
1141
- /**
1142
- * Creates a multihash digest.
1143
- *
1144
- * @template {number} Code
1145
- * @param {Code} code
1146
- * @param {Uint8Array} digest
1147
- */
1148
- const create = (code, digest) => {
1149
- const size = digest.byteLength;
1150
- const sizeOffset = encodingLength(code);
1151
- const digestOffset = sizeOffset + encodingLength(size);
1152
-
1153
- const bytes = new Uint8Array(digestOffset + size);
1154
- encodeTo(code, bytes, 0);
1155
- encodeTo(size, bytes, sizeOffset);
1156
- bytes.set(digest, digestOffset);
1157
-
1158
- return new Digest(code, size, digest, bytes)
1159
- };
1160
-
1161
- /**
1162
- * Turns bytes representation of multihash digest into an instance.
1163
- *
1164
- * @param {Uint8Array} multihash
1165
- * @returns {MultihashDigest}
1166
- */
1167
- const decode$1 = (multihash) => {
1168
- const bytes = coerce(multihash);
1169
- const [code, sizeOffset] = decode$2(bytes);
1170
- const [size, digestOffset] = decode$2(bytes.subarray(sizeOffset));
1171
- const digest = bytes.subarray(sizeOffset + digestOffset);
1172
-
1173
- if (digest.byteLength !== size) {
1174
- throw new Error('Incorrect length')
1175
- }
1176
-
1177
- return new Digest(code, size, digest, bytes)
1178
- };
1179
-
1180
- /**
1181
- * @param {MultihashDigest} a
1182
- * @param {unknown} b
1183
- * @returns {b is MultihashDigest}
1184
- */
1185
- const equals$1 = (a, b) => {
1186
- if (a === b) {
1187
- return true
1188
- } else {
1189
- const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b);
1190
-
1191
- return (
1192
- a.code === data.code &&
1193
- a.size === data.size &&
1194
- data.bytes instanceof Uint8Array &&
1195
- equals$2(a.bytes, data.bytes)
1196
- )
1197
- }
1198
- };
1199
-
1200
- /**
1201
- * @typedef {import('./interface.js').MultihashDigest} MultihashDigest
1202
- */
1203
-
1204
- /**
1205
- * Represents a multihash digest which carries information about the
1206
- * hashing alogrithm and an actual hash digest.
1207
- *
1208
- * @template {number} Code
1209
- * @template {number} Size
1210
- * @class
1211
- * @implements {MultihashDigest}
1212
- */
1213
- class Digest {
1214
- /**
1215
- * Creates a multihash digest.
1216
- *
1217
- * @param {Code} code
1218
- * @param {Size} size
1219
- * @param {Uint8Array} digest
1220
- * @param {Uint8Array} bytes
1221
- */
1222
- constructor (code, size, digest, bytes) {
1223
- this.code = code;
1224
- this.size = size;
1225
- this.digest = digest;
1226
- this.bytes = bytes;
1227
- }
1228
- }
1229
-
1230
- /**
1231
- * @template {string} Name
1232
- * @template {number} Code
1233
- * @param {object} options
1234
- * @param {Name} options.name
1235
- * @param {Code} options.code
1236
- * @param {(input: Uint8Array) => Await<Uint8Array>} options.encode
1237
- */
1238
- const from = ({ name, code, encode }) => new Hasher(name, code, encode);
1239
-
1240
- /**
1241
- * Hasher represents a hashing algorithm implementation that produces as
1242
- * `MultihashDigest`.
1243
- *
1244
- * @template {string} Name
1245
- * @template {number} Code
1246
- * @class
1247
- * @implements {MultihashHasher<Code>}
1248
- */
1249
- class Hasher {
1250
- /**
1251
- *
1252
- * @param {Name} name
1253
- * @param {Code} code
1254
- * @param {(input: Uint8Array) => Await<Uint8Array>} encode
1255
- */
1256
- constructor (name, code, encode) {
1257
- this.name = name;
1258
- this.code = code;
1259
- this.encode = encode;
1260
- }
1261
-
1262
- /**
1263
- * @param {Uint8Array} input
1264
- * @returns {Await<Digest.Digest<Code, number>>}
1265
- */
1266
- digest (input) {
1267
- if (input instanceof Uint8Array) {
1268
- const result = this.encode(input);
1269
- return result instanceof Uint8Array
1270
- ? create(this.code, result)
1271
- /* c8 ignore next 1 */
1272
- : result.then(digest => create(this.code, digest))
1273
- } else {
1274
- throw Error('Unknown type, must be binary type')
1275
- /* c8 ignore next 1 */
1276
- }
1277
- }
1278
- }
1279
-
1280
- /**
1281
- * @template {number} Alg
1282
- * @typedef {import('./interface.js').MultihashHasher} MultihashHasher
1283
- */
1284
-
1285
- /**
1286
- * @template T
1287
- * @typedef {Promise<T>|T} Await
1288
- */
1289
-
1290
- /* global crypto */
1291
-
1292
- /**
1293
- * @param {AlgorithmIdentifier} name
1294
- */
1295
- const sha = name =>
1296
- /**
1297
- * @param {Uint8Array} data
1298
- */
1299
- async data => new Uint8Array(await crypto.subtle.digest(name, data));
1300
-
1301
- const sha256 = from({
1302
- name: 'sha2-256',
1303
- code: 0x12,
1304
- encode: sha('SHA-256')
1305
- });
1306
-
1307
- const sha512 = from({
1308
- name: 'sha2-512',
1309
- code: 0x13,
1310
- encode: sha('SHA-512')
1311
- });
1312
-
1313
- var sha2 = /*#__PURE__*/Object.freeze({
1314
- __proto__: null,
1315
- sha256: sha256,
1316
- sha512: sha512
1317
- });
1318
-
1319
- const code = 0x0;
1320
- const name = 'identity';
1321
-
1322
- /** @type {(input:Uint8Array) => Uint8Array} */
1323
- const encode$1 = coerce;
1324
-
1325
- /**
1326
- * @param {Uint8Array} input
1327
- * @returns {Digest.Digest<typeof code, number>}
1328
- */
1329
- const digest = (input) => create(code, encode$1(input));
1330
-
1331
- const identity = { code, name, encode: encode$1, digest };
1332
-
1333
- var identity$1 = /*#__PURE__*/Object.freeze({
1334
- __proto__: null,
1335
- identity: identity
1336
- });
1337
-
1338
- // @ts-check
1339
-
1340
- /**
1341
- * @template T
1342
- * @typedef {import('./interface.js').ByteView<T>} ByteView
1343
- */
1344
-
1345
- new TextEncoder();
1346
- new TextDecoder();
1347
-
1348
- /**
1349
- * @template {API.Link<unknown, number, number, API.Version>} T
1350
- * @template {string} Prefix
1351
- * @param {T} link
1352
- * @param {API.MultibaseEncoder<Prefix>} [base]
1353
- * @returns {API.ToString<T, Prefix>}
1354
- */
1355
- const format = (link, base) => {
1356
- const { bytes, version } = link;
1357
- switch (version) {
1358
- case 0:
1359
- return toStringV0(
1360
- bytes,
1361
- baseCache(link),
1362
- /** @type {API.MultibaseEncoder<"z">} */ (base) || base58btc.encoder
1363
- )
1364
- default:
1365
- return toStringV1(
1366
- bytes,
1367
- baseCache(link),
1368
- /** @type {API.MultibaseEncoder<Prefix>} */ (base || base32.encoder)
1369
- )
1370
- }
1371
- };
1372
-
1373
- /** @type {WeakMap<API.UnknownLink, Map<string, string>>} */
1374
- const cache = new WeakMap();
1375
-
1376
- /**
1377
- * @param {API.UnknownLink} cid
1378
- * @returns {Map<string, string>}
1379
- */
1380
- const baseCache = cid => {
1381
- const baseCache = cache.get(cid);
1382
- if (baseCache == null) {
1383
- const baseCache = new Map();
1384
- cache.set(cid, baseCache);
1385
- return baseCache
1386
- }
1387
- return baseCache
1388
- };
1389
-
1390
- /**
1391
- * @template {unknown} [Data=unknown]
1392
- * @template {number} [Format=number]
1393
- * @template {number} [Alg=number]
1394
- * @template {API.Version} [Version=API.Version]
1395
- * @implements {API.Link<Data, Format, Alg, Version>}
1396
- */
1397
-
1398
- class CID {
1399
- /**
1400
- * @param {Version} version - Version of the CID
1401
- * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1402
- * @param {API.MultihashDigest<Alg>} multihash - (Multi)hash of the of the content.
1403
- * @param {Uint8Array} bytes
1404
- *
1405
- */
1406
- constructor (version, code, multihash, bytes) {
1407
- /** @readonly */
1408
- this.code = code;
1409
- /** @readonly */
1410
- this.version = version;
1411
- /** @readonly */
1412
- this.multihash = multihash;
1413
- /** @readonly */
1414
- this.bytes = bytes;
1415
-
1416
- // flag to serializers that this is a CID and
1417
- // should be treated specially
1418
- /** @readonly */
1419
- this['/'] = bytes;
1420
- }
1421
-
1422
- /**
1423
- * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
1424
- * please either use `CID.asCID(cid)` or switch to new signalling mechanism
1425
- *
1426
- * @deprecated
1427
- */
1428
- get asCID () {
1429
- return this
1430
- }
1431
-
1432
- // ArrayBufferView
1433
- get byteOffset () {
1434
- return this.bytes.byteOffset
1435
- }
1436
-
1437
- // ArrayBufferView
1438
- get byteLength () {
1439
- return this.bytes.byteLength
1440
- }
1441
-
1442
- /**
1443
- * @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
1444
- */
1445
- toV0 () {
1446
- switch (this.version) {
1447
- case 0: {
1448
- return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (this)
1449
- }
1450
- case 1: {
1451
- const { code, multihash } = this;
1452
-
1453
- if (code !== DAG_PB_CODE) {
1454
- throw new Error('Cannot convert a non dag-pb CID to CIDv0')
1455
- }
1456
-
1457
- // sha2-256
1458
- if (multihash.code !== SHA_256_CODE) {
1459
- throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')
1460
- }
1461
-
1462
- return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (
1463
- CID.createV0(
1464
- /** @type {API.MultihashDigest<API.SHA_256>} */ (multihash)
1465
- )
1466
- )
1467
- }
1468
- default: {
1469
- throw Error(
1470
- `Can not convert CID version ${this.version} to version 0. This is a bug please report`
1471
- )
1472
- }
1473
- }
1474
- }
1475
-
1476
- /**
1477
- * @returns {CID<Data, Format, Alg, 1>}
1478
- */
1479
- toV1 () {
1480
- switch (this.version) {
1481
- case 0: {
1482
- const { code, digest } = this.multihash;
1483
- const multihash = create(code, digest);
1484
- return /** @type {CID<Data, Format, Alg, 1>} */ (
1485
- CID.createV1(this.code, multihash)
1486
- )
1487
- }
1488
- case 1: {
1489
- return /** @type {CID<Data, Format, Alg, 1>} */ (this)
1490
- }
1491
- default: {
1492
- throw Error(
1493
- `Can not convert CID version ${this.version} to version 1. This is a bug please report`
1494
- )
1495
- }
1496
- }
1497
- }
1498
-
1499
- /**
1500
- * @param {unknown} other
1501
- * @returns {other is CID<Data, Format, Alg, Version>}
1502
- */
1503
- equals (other) {
1504
- return CID.equals(this, other)
1505
- }
1506
-
1507
- /**
1508
- * @template {unknown} Data
1509
- * @template {number} Format
1510
- * @template {number} Alg
1511
- * @template {API.Version} Version
1512
- * @param {API.Link<Data, Format, Alg, Version>} self
1513
- * @param {unknown} other
1514
- * @returns {other is CID}
1515
- */
1516
- static equals (self, other) {
1517
- const unknown =
1518
- /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (
1519
- other
1520
- );
1521
- return (
1522
- unknown &&
1523
- self.code === unknown.code &&
1524
- self.version === unknown.version &&
1525
- equals$1(self.multihash, unknown.multihash)
1526
- )
1527
- }
1528
-
1529
- /**
1530
- * @param {API.MultibaseEncoder<string>} [base]
1531
- * @returns {string}
1532
- */
1533
- toString (base) {
1534
- return format(this, base)
1535
- }
1536
-
1537
- toJSON () {
1538
- return {
1539
- code: this.code,
1540
- version: this.version,
1541
- hash: this.multihash.bytes
1542
- }
1543
- }
1544
-
1545
- link () {
1546
- return this
1547
- }
1548
-
1549
- get [Symbol.toStringTag] () {
1550
- return 'CID'
1551
- }
1552
-
1553
- // Legacy
1554
-
1555
- [Symbol.for('nodejs.util.inspect.custom')] () {
1556
- return `CID(${this.toString()})`
1557
- }
1558
-
1559
- /**
1560
- * Takes any input `value` and returns a `CID` instance if it was
1561
- * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
1562
- * it will return value back. If `value` is not instance of this CID
1563
- * class, but is compatible CID it will return new instance of this
1564
- * `CID` class. Otherwise returs null.
1565
- *
1566
- * This allows two different incompatible versions of CID library to
1567
- * co-exist and interop as long as binary interface is compatible.
1568
- *
1569
- * @template {unknown} Data
1570
- * @template {number} Format
1571
- * @template {number} Alg
1572
- * @template {API.Version} Version
1573
- * @template {unknown} U
1574
- * @param {API.Link<Data, Format, Alg, Version>|U} input
1575
- * @returns {CID<Data, Format, Alg, Version>|null}
1576
- */
1577
- static asCID (input) {
1578
- if (input == null) {
1579
- return null
1580
- }
1581
-
1582
- const value = /** @type {any} */ (input);
1583
- if (value instanceof CID) {
1584
- // If value is instance of CID then we're all set.
1585
- return value
1586
- } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
1587
- // If value isn't instance of this CID class but `this.asCID === this` or
1588
- // `value['/'] === value.bytes` is true it is CID instance coming from a
1589
- // different implementation (diff version or duplicate). In that case we
1590
- // rebase it to this `CID` implementation so caller is guaranteed to get
1591
- // instance with expected API.
1592
- const { version, code, multihash, bytes } = value;
1593
- return new CID(
1594
- version,
1595
- code,
1596
- /** @type {API.MultihashDigest<Alg>} */ (multihash),
1597
- bytes || encodeCID(version, code, multihash.bytes)
1598
- )
1599
- } else if (value[cidSymbol] === true) {
1600
- // If value is a CID from older implementation that used to be tagged via
1601
- // symbol we still rebase it to the this `CID` implementation by
1602
- // delegating that to a constructor.
1603
- const { version, multihash, code } = value;
1604
- const digest =
1605
- /** @type {API.MultihashDigest<Alg>} */
1606
- (decode$1(multihash));
1607
- return CID.create(version, code, digest)
1608
- } else {
1609
- // Otherwise value is not a CID (or an incompatible version of it) in
1610
- // which case we return `null`.
1611
- return null
1612
- }
1613
- }
1614
-
1615
- /**
1616
- *
1617
- * @template {unknown} Data
1618
- * @template {number} Format
1619
- * @template {number} Alg
1620
- * @template {API.Version} Version
1621
- * @param {Version} version - Version of the CID
1622
- * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1623
- * @param {API.MultihashDigest<Alg>} digest - (Multi)hash of the of the content.
1624
- * @returns {CID<Data, Format, Alg, Version>}
1625
- */
1626
- static create (version, code, digest) {
1627
- if (typeof code !== 'number') {
1628
- throw new Error('String codecs are no longer supported')
1629
- }
1630
-
1631
- if (!(digest.bytes instanceof Uint8Array)) {
1632
- throw new Error('Invalid digest')
1633
- }
1634
-
1635
- switch (version) {
1636
- case 0: {
1637
- if (code !== DAG_PB_CODE) {
1638
- throw new Error(
1639
- `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`
1640
- )
1641
- } else {
1642
- return new CID(version, code, digest, digest.bytes)
1643
- }
1644
- }
1645
- case 1: {
1646
- const bytes = encodeCID(version, code, digest.bytes);
1647
- return new CID(version, code, digest, bytes)
1648
- }
1649
- default: {
1650
- throw new Error('Invalid version')
1651
- }
1652
- }
1653
- }
1654
-
1655
- /**
1656
- * Simplified version of `create` for CIDv0.
1657
- *
1658
- * @template {unknown} [T=unknown]
1659
- * @param {API.MultihashDigest<typeof SHA_256_CODE>} digest - Multihash.
1660
- * @returns {CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0>}
1661
- */
1662
- static createV0 (digest) {
1663
- return CID.create(0, DAG_PB_CODE, digest)
1664
- }
1665
-
1666
- /**
1667
- * Simplified version of `create` for CIDv1.
1668
- *
1669
- * @template {unknown} Data
1670
- * @template {number} Code
1671
- * @template {number} Alg
1672
- * @param {Code} code - Content encoding format code.
1673
- * @param {API.MultihashDigest<Alg>} digest - Miltihash of the content.
1674
- * @returns {CID<Data, Code, Alg, 1>}
1675
- */
1676
- static createV1 (code, digest) {
1677
- return CID.create(1, code, digest)
1678
- }
1679
-
1680
- /**
1681
- * Decoded a CID from its binary representation. The byte array must contain
1682
- * only the CID with no additional bytes.
1683
- *
1684
- * An error will be thrown if the bytes provided do not contain a valid
1685
- * binary representation of a CID.
1686
- *
1687
- * @template {unknown} Data
1688
- * @template {number} Code
1689
- * @template {number} Alg
1690
- * @template {API.Version} Ver
1691
- * @param {API.ByteView<API.Link<Data, Code, Alg, Ver>>} bytes
1692
- * @returns {CID<Data, Code, Alg, Ver>}
1693
- */
1694
- static decode (bytes) {
1695
- const [cid, remainder] = CID.decodeFirst(bytes);
1696
- if (remainder.length) {
1697
- throw new Error('Incorrect length')
1698
- }
1699
- return cid
1700
- }
1701
-
1702
- /**
1703
- * Decoded a CID from its binary representation at the beginning of a byte
1704
- * array.
1705
- *
1706
- * Returns an array with the first element containing the CID and the second
1707
- * element containing the remainder of the original byte array. The remainder
1708
- * will be a zero-length byte array if the provided bytes only contained a
1709
- * binary CID representation.
1710
- *
1711
- * @template {unknown} T
1712
- * @template {number} C
1713
- * @template {number} A
1714
- * @template {API.Version} V
1715
- * @param {API.ByteView<API.Link<T, C, A, V>>} bytes
1716
- * @returns {[CID<T, C, A, V>, Uint8Array]}
1717
- */
1718
- static decodeFirst (bytes) {
1719
- const specs = CID.inspectBytes(bytes);
1720
- const prefixSize = specs.size - specs.multihashSize;
1721
- const multihashBytes = coerce(
1722
- bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
1723
- );
1724
- if (multihashBytes.byteLength !== specs.multihashSize) {
1725
- throw new Error('Incorrect length')
1726
- }
1727
- const digestBytes = multihashBytes.subarray(
1728
- specs.multihashSize - specs.digestSize
1729
- );
1730
- const digest = new Digest(
1731
- specs.multihashCode,
1732
- specs.digestSize,
1733
- digestBytes,
1734
- multihashBytes
1735
- );
1736
- const cid =
1737
- specs.version === 0
1738
- ? CID.createV0(/** @type {API.MultihashDigest<API.SHA_256>} */ (digest))
1739
- : CID.createV1(specs.codec, digest);
1740
- return [/** @type {CID<T, C, A, V>} */(cid), bytes.subarray(specs.size)]
1741
- }
1742
-
1743
- /**
1744
- * Inspect the initial bytes of a CID to determine its properties.
1745
- *
1746
- * Involves decoding up to 4 varints. Typically this will require only 4 to 6
1747
- * bytes but for larger multicodec code values and larger multihash digest
1748
- * lengths these varints can be quite large. It is recommended that at least
1749
- * 10 bytes be made available in the `initialBytes` argument for a complete
1750
- * inspection.
1751
- *
1752
- * @template {unknown} T
1753
- * @template {number} C
1754
- * @template {number} A
1755
- * @template {API.Version} V
1756
- * @param {API.ByteView<API.Link<T, C, A, V>>} initialBytes
1757
- * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}
1758
- */
1759
- static inspectBytes (initialBytes) {
1760
- let offset = 0;
1761
- const next = () => {
1762
- const [i, length] = decode$2(initialBytes.subarray(offset));
1763
- offset += length;
1764
- return i
1765
- };
1766
-
1767
- let version = /** @type {V} */ (next());
1768
- let codec = /** @type {C} */ (DAG_PB_CODE);
1769
- if (/** @type {number} */(version) === 18) {
1770
- // CIDv0
1771
- version = /** @type {V} */ (0);
1772
- offset = 0;
1773
- } else {
1774
- codec = /** @type {C} */ (next());
1775
- }
1776
-
1777
- if (version !== 0 && version !== 1) {
1778
- throw new RangeError(`Invalid CID version ${version}`)
1779
- }
1780
-
1781
- const prefixSize = offset;
1782
- const multihashCode = /** @type {A} */ (next()); // multihash code
1783
- const digestSize = next(); // multihash length
1784
- const size = offset + digestSize;
1785
- const multihashSize = size - prefixSize;
1786
-
1787
- return { version, codec, multihashCode, digestSize, multihashSize, size }
1788
- }
1789
-
1790
- /**
1791
- * Takes cid in a string representation and creates an instance. If `base`
1792
- * decoder is not provided will use a default from the configuration. It will
1793
- * throw an error if encoding of the CID is not compatible with supplied (or
1794
- * a default decoder).
1795
- *
1796
- * @template {string} Prefix
1797
- * @template {unknown} Data
1798
- * @template {number} Code
1799
- * @template {number} Alg
1800
- * @template {API.Version} Ver
1801
- * @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
1802
- * @param {API.MultibaseDecoder<Prefix>} [base]
1803
- * @returns {CID<Data, Code, Alg, Ver>}
1804
- */
1805
- static parse (source, base) {
1806
- const [prefix, bytes] = parseCIDtoBytes(source, base);
1807
-
1808
- const cid = CID.decode(bytes);
1809
-
1810
- // Cache string representation to avoid computing it on `this.toString()`
1811
- baseCache(cid).set(prefix, source);
1812
-
1813
- return cid
1814
- }
1815
- }
1816
-
1817
- /**
1818
- * @template {string} Prefix
1819
- * @template {unknown} Data
1820
- * @template {number} Code
1821
- * @template {number} Alg
1822
- * @template {API.Version} Ver
1823
- * @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
1824
- * @param {API.MultibaseDecoder<Prefix>} [base]
1825
- * @returns {[Prefix, API.ByteView<API.Link<Data, Code, Alg, Ver>>]}
1826
- */
1827
- const parseCIDtoBytes = (source, base) => {
1828
- switch (source[0]) {
1829
- // CIDv0 is parsed differently
1830
- case 'Q': {
1831
- const decoder = base || base58btc;
1832
- return [
1833
- /** @type {Prefix} */ (base58btc.prefix),
1834
- decoder.decode(`${base58btc.prefix}${source}`)
1835
- ]
1836
- }
1837
- case base58btc.prefix: {
1838
- const decoder = base || base58btc;
1839
- return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]
1840
- }
1841
- case base32.prefix: {
1842
- const decoder = base || base32;
1843
- return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]
1844
- }
1845
- default: {
1846
- if (base == null) {
1847
- throw Error(
1848
- 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'
1849
- )
1850
- }
1851
- return [/** @type {Prefix} */(source[0]), base.decode(source)]
1852
- }
1853
- }
1854
- };
1855
-
1856
- /**
1857
- *
1858
- * @param {Uint8Array} bytes
1859
- * @param {Map<string, string>} cache
1860
- * @param {API.MultibaseEncoder<'z'>} base
1861
- */
1862
- const toStringV0 = (bytes, cache, base) => {
1863
- const { prefix } = base;
1864
- if (prefix !== base58btc.prefix) {
1865
- throw Error(`Cannot string encode V0 in ${base.name} encoding`)
1866
- }
1867
-
1868
- const cid = cache.get(prefix);
1869
- if (cid == null) {
1870
- const cid = base.encode(bytes).slice(1);
1871
- cache.set(prefix, cid);
1872
- return cid
1873
- } else {
1874
- return cid
1875
- }
1876
- };
1877
-
1878
- /**
1879
- * @template {string} Prefix
1880
- * @param {Uint8Array} bytes
1881
- * @param {Map<string, string>} cache
1882
- * @param {API.MultibaseEncoder<Prefix>} base
1883
- */
1884
- const toStringV1 = (bytes, cache, base) => {
1885
- const { prefix } = base;
1886
- const cid = cache.get(prefix);
1887
- if (cid == null) {
1888
- const cid = base.encode(bytes);
1889
- cache.set(prefix, cid);
1890
- return cid
1891
- } else {
1892
- return cid
1893
- }
1894
- };
1895
-
1896
- const DAG_PB_CODE = 0x70;
1897
- const SHA_256_CODE = 0x12;
1898
-
1899
- /**
1900
- * @param {API.Version} version
1901
- * @param {number} code
1902
- * @param {Uint8Array} multihash
1903
- * @returns {Uint8Array}
1904
- */
1905
- const encodeCID = (version, code, multihash) => {
1906
- const codeOffset = encodingLength(version);
1907
- const hashOffset = codeOffset + encodingLength(code);
1908
- const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1909
- encodeTo(version, bytes, 0);
1910
- encodeTo(code, bytes, codeOffset);
1911
- bytes.set(multihash, hashOffset);
1912
- return bytes
1913
- };
1914
-
1915
- const cidSymbol = Symbol.for('@ipld/js-cid/CID');
1916
-
1917
- // @ts-check
1918
-
1919
- const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
1920
- ({ ...sha2, ...identity$1 });
1921
-
1922
- /**
1923
- * To guarantee Uint8Array semantics, convert nodejs Buffers
1924
- * into vanilla Uint8Arrays
1925
- */
1926
- function asUint8Array(buf) {
1927
- if (globalThis.Buffer != null) {
1928
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1929
- }
1930
- return buf;
1931
- }
1932
-
1933
- /**
1934
- * Where possible returns a Uint8Array of the requested size that references
1935
- * uninitialized memory. Only use if you are certain you will immediately
1936
- * overwrite every value in the returned `Uint8Array`.
1937
- */
1938
- function allocUnsafe(size = 0) {
1939
- if (globalThis.Buffer?.allocUnsafe != null) {
1940
- return asUint8Array(globalThis.Buffer.allocUnsafe(size));
1941
- }
1942
- return new Uint8Array(size);
1943
- }
1944
-
1945
- function createCodec(name, prefix, encode, decode) {
1946
- return {
1947
- name,
1948
- prefix,
1949
- encoder: {
1950
- name,
1951
- prefix,
1952
- encode
1953
- },
1954
- decoder: {
1955
- decode
1956
- }
1957
- };
1958
- }
1959
- const string = createCodec('utf8', 'u', (buf) => {
1960
- const decoder = new TextDecoder('utf8');
1961
- return 'u' + decoder.decode(buf);
1962
- }, (str) => {
1963
- const encoder = new TextEncoder();
1964
- return encoder.encode(str.substring(1));
1965
- });
1966
- const ascii = createCodec('ascii', 'a', (buf) => {
1967
- let string = 'a';
1968
- for (let i = 0; i < buf.length; i++) {
1969
- string += String.fromCharCode(buf[i]);
1970
- }
1971
- return string;
1972
- }, (str) => {
1973
- str = str.substring(1);
1974
- const buf = allocUnsafe(str.length);
1975
- for (let i = 0; i < str.length; i++) {
1976
- buf[i] = str.charCodeAt(i);
1977
- }
1978
- return buf;
1979
- });
1980
- const BASES = {
1981
- utf8: string,
1982
- 'utf-8': string,
1983
- hex: bases.base16,
1984
- latin1: ascii,
1985
- ascii: ascii,
1986
- binary: ascii,
1987
- ...bases
1988
- };
1989
-
1990
- /**
1991
- * Turns a `Uint8Array` into a string.
1992
- *
1993
- * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
1994
- *
1995
- * Also `ascii` which is similar to node's 'binary' encoding.
1996
- */
1997
- function toString$1(array, encoding = 'utf8') {
1998
- const base = BASES[encoding];
1999
- if (base == null) {
2000
- throw new Error(`Unsupported encoding "${encoding}"`);
2001
- }
2002
- if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
2003
- return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
2004
- }
2005
- // strip multibase prefix
2006
- return base.encoder.encode(array).substring(1);
2007
- }
2008
-
2009
- const isV4 = isIPv4;
2010
- const isV6 = isIPv6;
2011
- // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7
2012
- // but with buf/offset args removed because we don't use them
2013
- const toBytes = function (ip) {
2014
- let offset = 0;
2015
- ip = ip.toString().trim();
2016
- if (isV4(ip)) {
2017
- const bytes = new Uint8Array(offset + 4);
2018
- ip.split(/\./g).forEach((byte) => {
2019
- bytes[offset++] = parseInt(byte, 10) & 0xff;
2020
- });
2021
- return bytes;
2022
- }
2023
- if (isV6(ip)) {
2024
- const sections = ip.split(':', 8);
2025
- let i;
2026
- for (i = 0; i < sections.length; i++) {
2027
- const isv4 = isV4(sections[i]);
2028
- let v4Buffer;
2029
- if (isv4) {
2030
- v4Buffer = toBytes(sections[i]);
2031
- sections[i] = toString$1(v4Buffer.slice(0, 2), 'base16');
2032
- }
2033
- if (v4Buffer != null && ++i < 8) {
2034
- sections.splice(i, 0, toString$1(v4Buffer.slice(2, 4), 'base16'));
2035
- }
2036
- }
2037
- if (sections[0] === '') {
2038
- while (sections.length < 8)
2039
- sections.unshift('0');
2040
- }
2041
- else if (sections[sections.length - 1] === '') {
2042
- while (sections.length < 8)
2043
- sections.push('0');
2044
- }
2045
- else if (sections.length < 8) {
2046
- for (i = 0; i < sections.length && sections[i] !== ''; i++)
2047
- ;
2048
- const argv = [i, 1];
2049
- for (i = 9 - sections.length; i > 0; i--) {
2050
- argv.push('0');
2051
- }
2052
- sections.splice.apply(sections, argv);
2053
- }
2054
- const bytes = new Uint8Array(offset + 16);
2055
- for (i = 0; i < sections.length; i++) {
2056
- const word = parseInt(sections[i], 16);
2057
- bytes[offset++] = (word >> 8) & 0xff;
2058
- bytes[offset++] = word & 0xff;
2059
- }
2060
- return bytes;
2061
- }
2062
- throw new Error('invalid ip address');
2063
- };
2064
- // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
2065
- const toString = function (buf, offset = 0, length) {
2066
- offset = ~~offset;
2067
- length = length ?? (buf.length - offset);
2068
- const view = new DataView(buf.buffer);
2069
- if (length === 4) {
2070
- const result = [];
2071
- // IPv4
2072
- for (let i = 0; i < length; i++) {
2073
- result.push(buf[offset + i]);
2074
- }
2075
- return result.join('.');
2076
- }
2077
- if (length === 16) {
2078
- const result = [];
2079
- // IPv6
2080
- for (let i = 0; i < length; i += 2) {
2081
- result.push(view.getUint16(offset + i).toString(16));
2082
- }
2083
- return result.join(':')
2084
- .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')
2085
- .replace(/:{3,4}/, '::');
2086
- }
2087
- return '';
2088
- };
2089
-
2090
- const V = -1;
2091
- const names = {};
2092
- const codes = {};
2093
- const table = [
2094
- [4, 32, 'ip4'],
2095
- [6, 16, 'tcp'],
2096
- [33, 16, 'dccp'],
2097
- [41, 128, 'ip6'],
2098
- [42, V, 'ip6zone'],
2099
- [53, V, 'dns', true],
2100
- [54, V, 'dns4', true],
2101
- [55, V, 'dns6', true],
2102
- [56, V, 'dnsaddr', true],
2103
- [132, 16, 'sctp'],
2104
- [273, 16, 'udp'],
2105
- [275, 0, 'p2p-webrtc-star'],
2106
- [276, 0, 'p2p-webrtc-direct'],
2107
- [277, 0, 'p2p-stardust'],
2108
- [280, 0, 'webrtc'],
2109
- [290, 0, 'p2p-circuit'],
2110
- [301, 0, 'udt'],
2111
- [302, 0, 'utp'],
2112
- [400, V, 'unix', false, true],
2113
- // `ipfs` is added before `p2p` for legacy support.
2114
- // All text representations will default to `p2p`, but `ipfs` will
2115
- // still be supported
2116
- [421, V, 'ipfs'],
2117
- // `p2p` is the preferred name for 421, and is now the default
2118
- [421, V, 'p2p'],
2119
- [443, 0, 'https'],
2120
- [444, 96, 'onion'],
2121
- [445, 296, 'onion3'],
2122
- [446, V, 'garlic64'],
2123
- [460, 0, 'quic'],
2124
- [465, 0, 'webtransport'],
2125
- [466, V, 'certhash'],
2126
- [477, 0, 'ws'],
2127
- [478, 0, 'wss'],
2128
- [479, 0, 'p2p-websocket-star'],
2129
- [480, 0, 'http'],
2130
- [777, V, 'memory']
2131
- ];
2132
- // populate tables
2133
- table.forEach(row => {
2134
- const proto = createProtocol(...row);
2135
- codes[proto.code] = proto;
2136
- names[proto.name] = proto;
2137
- });
2138
- function createProtocol(code, size, name, resolvable, path) {
2139
- return {
2140
- code,
2141
- size,
2142
- name,
2143
- resolvable: Boolean(resolvable),
2144
- path: Boolean(path)
2145
- };
2146
- }
2147
- function getProtocol(proto) {
2148
- if (typeof proto === 'number') {
2149
- if (codes[proto] != null) {
2150
- return codes[proto];
2151
- }
2152
- throw new Error(`no protocol with code: ${proto}`);
2153
- }
2154
- else if (typeof proto === 'string') {
2155
- if (names[proto] != null) {
2156
- return names[proto];
2157
- }
2158
- throw new Error(`no protocol with name: ${proto}`);
2159
- }
2160
- throw new Error(`invalid protocol id type: ${typeof proto}`);
2161
- }
2162
-
2163
- var encode_1 = encode;
2164
-
2165
- var MSB$1 = 0x80
2166
- , REST$1 = 0x7F
2167
- , MSBALL = ~REST$1
2168
- , INT = Math.pow(2, 31);
2169
-
2170
- function encode(num, out, offset) {
2171
- if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
2172
- encode.bytes = 0;
2173
- throw new RangeError('Could not encode varint')
2174
- }
2175
- out = out || [];
2176
- offset = offset || 0;
2177
- var oldOffset = offset;
2178
-
2179
- while(num >= INT) {
2180
- out[offset++] = (num & 0xFF) | MSB$1;
2181
- num /= 128;
2182
- }
2183
- while(num & MSBALL) {
2184
- out[offset++] = (num & 0xFF) | MSB$1;
2185
- num >>>= 7;
2186
- }
2187
- out[offset] = num | 0;
2188
-
2189
- encode.bytes = offset - oldOffset + 1;
2190
-
2191
- return out
2192
- }
2193
-
2194
- var decode = read;
2195
-
2196
- var MSB = 0x80
2197
- , REST = 0x7F;
2198
-
2199
- function read(buf, offset) {
2200
- var res = 0
2201
- , offset = offset || 0
2202
- , shift = 0
2203
- , counter = offset
2204
- , b
2205
- , l = buf.length;
2206
-
2207
- do {
2208
- if (counter >= l || shift > 49) {
2209
- read.bytes = 0;
2210
- throw new RangeError('Could not decode varint')
2211
- }
2212
- b = buf[counter++];
2213
- res += shift < 28
2214
- ? (b & REST) << shift
2215
- : (b & REST) * Math.pow(2, shift);
2216
- shift += 7;
2217
- } while (b >= MSB)
2218
-
2219
- read.bytes = counter - offset;
2220
-
2221
- return res
2222
- }
2223
-
2224
- var N1 = Math.pow(2, 7);
2225
- var N2 = Math.pow(2, 14);
2226
- var N3 = Math.pow(2, 21);
2227
- var N4 = Math.pow(2, 28);
2228
- var N5 = Math.pow(2, 35);
2229
- var N6 = Math.pow(2, 42);
2230
- var N7 = Math.pow(2, 49);
2231
- var N8 = Math.pow(2, 56);
2232
- var N9 = Math.pow(2, 63);
2233
-
2234
- var length = function (value) {
2235
- return (
2236
- value < N1 ? 1
2237
- : value < N2 ? 2
2238
- : value < N3 ? 3
2239
- : value < N4 ? 4
2240
- : value < N5 ? 5
2241
- : value < N6 ? 6
2242
- : value < N7 ? 7
2243
- : value < N8 ? 8
2244
- : value < N9 ? 9
2245
- : 10
2246
- )
2247
- };
2248
-
2249
- var varint = {
2250
- encode: encode_1
2251
- , decode: decode
2252
- , encodingLength: length
2253
- };
2254
-
2255
- /**
2256
- * Create a `Uint8Array` from the passed string
2257
- *
2258
- * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
2259
- *
2260
- * Also `ascii` which is similar to node's 'binary' encoding.
2261
- */
2262
- function fromString$1(string, encoding = 'utf8') {
2263
- const base = BASES[encoding];
2264
- if (base == null) {
2265
- throw new Error(`Unsupported encoding "${encoding}"`);
2266
- }
2267
- if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
2268
- return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
2269
- }
2270
- // add multibase prefix
2271
- return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
2272
- }
2273
-
2274
- /**
2275
- * Returns a new Uint8Array created by concatenating the passed ArrayLikes
2276
- */
2277
- function concat(arrays, length) {
2278
- if (length == null) {
2279
- length = arrays.reduce((acc, curr) => acc + curr.length, 0);
2280
- }
2281
- const output = allocUnsafe(length);
2282
- let offset = 0;
2283
- for (const arr of arrays) {
2284
- output.set(arr, offset);
2285
- offset += arr.length;
2286
- }
2287
- return asUint8Array(output);
2288
- }
2289
-
2290
- /**
2291
- * Convert [code,Uint8Array] to string
2292
- */
2293
- function convertToString(proto, buf) {
2294
- const protocol = getProtocol(proto);
2295
- switch (protocol.code) {
2296
- case 4: // ipv4
2297
- case 41: // ipv6
2298
- return bytes2ip(buf);
2299
- case 6: // tcp
2300
- case 273: // udp
2301
- case 33: // dccp
2302
- case 132: // sctp
2303
- return bytes2port(buf).toString();
2304
- case 53: // dns
2305
- case 54: // dns4
2306
- case 55: // dns6
2307
- case 56: // dnsaddr
2308
- case 400: // unix
2309
- case 777: // memory
2310
- return bytes2str(buf);
2311
- case 421: // ipfs
2312
- return bytes2mh(buf);
2313
- case 444: // onion
2314
- return bytes2onion(buf);
2315
- case 445: // onion3
2316
- return bytes2onion(buf);
2317
- case 466: // certhash
2318
- return bytes2mb(buf);
2319
- default:
2320
- return toString$1(buf, 'base16'); // no clue. convert to hex
2321
- }
2322
- }
2323
- function convertToBytes(proto, str) {
2324
- const protocol = getProtocol(proto);
2325
- switch (protocol.code) {
2326
- case 4: // ipv4
2327
- return ip2bytes(str);
2328
- case 41: // ipv6
2329
- return ip2bytes(str);
2330
- case 6: // tcp
2331
- case 273: // udp
2332
- case 33: // dccp
2333
- case 132: // sctp
2334
- return port2bytes(parseInt(str, 10));
2335
- case 53: // dns
2336
- case 54: // dns4
2337
- case 55: // dns6
2338
- case 56: // dnsaddr
2339
- case 400: // unix
2340
- case 777: // memory
2341
- return str2bytes(str);
2342
- case 421: // ipfs
2343
- return mh2bytes(str);
2344
- case 444: // onion
2345
- return onion2bytes(str);
2346
- case 445: // onion3
2347
- return onion32bytes(str);
2348
- case 466: // certhash
2349
- return mb2bytes(str);
2350
- default:
2351
- return fromString$1(str, 'base16'); // no clue. convert from hex
2352
- }
2353
- }
2354
- const decoders = Object.values(bases).map((c) => c.decoder);
2355
- const anybaseDecoder = (function () {
2356
- let acc = decoders[0].or(decoders[1]);
2357
- decoders.slice(2).forEach((d) => (acc = acc.or(d)));
2358
- return acc;
2359
- })();
2360
- function ip2bytes(ipString) {
2361
- if (!isIP(ipString)) {
2362
- throw new Error('invalid ip address');
2363
- }
2364
- return toBytes(ipString);
2365
- }
2366
- function bytes2ip(ipBuff) {
2367
- const ipString = toString(ipBuff, 0, ipBuff.length);
2368
- if (ipString == null) {
2369
- throw new Error('ipBuff is required');
2370
- }
2371
- if (!isIP(ipString)) {
2372
- throw new Error('invalid ip address');
2373
- }
2374
- return ipString;
2375
- }
2376
- function port2bytes(port) {
2377
- const buf = new ArrayBuffer(2);
2378
- const view = new DataView(buf);
2379
- view.setUint16(0, port);
2380
- return new Uint8Array(buf);
2381
- }
2382
- function bytes2port(buf) {
2383
- const view = new DataView(buf.buffer);
2384
- return view.getUint16(buf.byteOffset);
2385
- }
2386
- function str2bytes(str) {
2387
- const buf = fromString$1(str);
2388
- const size = Uint8Array.from(varint.encode(buf.length));
2389
- return concat([size, buf], size.length + buf.length);
2390
- }
2391
- function bytes2str(buf) {
2392
- const size = varint.decode(buf);
2393
- buf = buf.slice(varint.decode.bytes);
2394
- if (buf.length !== size) {
2395
- throw new Error('inconsistent lengths');
2396
- }
2397
- return toString$1(buf);
2398
- }
2399
- function mh2bytes(hash) {
2400
- let mh;
2401
- if (hash[0] === 'Q' || hash[0] === '1') {
2402
- mh = decode$1(base58btc.decode(`z${hash}`)).bytes;
2403
- }
2404
- else {
2405
- mh = CID.parse(hash).multihash.bytes;
2406
- }
2407
- // the address is a varint prefixed multihash string representation
2408
- const size = Uint8Array.from(varint.encode(mh.length));
2409
- return concat([size, mh], size.length + mh.length);
2410
- }
2411
- function mb2bytes(mbstr) {
2412
- const mb = anybaseDecoder.decode(mbstr);
2413
- const size = Uint8Array.from(varint.encode(mb.length));
2414
- return concat([size, mb], size.length + mb.length);
2415
- }
2416
- function bytes2mb(buf) {
2417
- const size = varint.decode(buf);
2418
- const hash = buf.slice(varint.decode.bytes);
2419
- if (hash.length !== size) {
2420
- throw new Error('inconsistent lengths');
2421
- }
2422
- return 'u' + toString$1(hash, 'base64url');
2423
- }
2424
- /**
2425
- * Converts bytes to bas58btc string
2426
- */
2427
- function bytes2mh(buf) {
2428
- const size = varint.decode(buf);
2429
- const address = buf.slice(varint.decode.bytes);
2430
- if (address.length !== size) {
2431
- throw new Error('inconsistent lengths');
2432
- }
2433
- return toString$1(address, 'base58btc');
2434
- }
2435
- function onion2bytes(str) {
2436
- const addr = str.split(':');
2437
- if (addr.length !== 2) {
2438
- throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
2439
- }
2440
- if (addr[0].length !== 16) {
2441
- throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);
2442
- }
2443
- // onion addresses do not include the multibase prefix, add it before decoding
2444
- const buf = base32.decode('b' + addr[0]);
2445
- // onion port number
2446
- const port = parseInt(addr[1], 10);
2447
- if (port < 1 || port > 65536) {
2448
- throw new Error('Port number is not in range(1, 65536)');
2449
- }
2450
- const portBuf = port2bytes(port);
2451
- return concat([buf, portBuf], buf.length + portBuf.length);
2452
- }
2453
- function onion32bytes(str) {
2454
- const addr = str.split(':');
2455
- if (addr.length !== 2) {
2456
- throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
2457
- }
2458
- if (addr[0].length !== 56) {
2459
- throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);
2460
- }
2461
- // onion addresses do not include the multibase prefix, add it before decoding
2462
- const buf = base32.decode(`b${addr[0]}`);
2463
- // onion port number
2464
- const port = parseInt(addr[1], 10);
2465
- if (port < 1 || port > 65536) {
2466
- throw new Error('Port number is not in range(1, 65536)');
2467
- }
2468
- const portBuf = port2bytes(port);
2469
- return concat([buf, portBuf], buf.length + portBuf.length);
2470
- }
2471
- function bytes2onion(buf) {
2472
- const addrBytes = buf.slice(0, buf.length - 2);
2473
- const portBytes = buf.slice(buf.length - 2);
2474
- const addr = toString$1(addrBytes, 'base32');
2475
- const port = bytes2port(portBytes);
2476
- return `${addr}:${port}`;
2477
- }
2478
-
2479
- /**
2480
- * string -> [[str name, str addr]... ]
2481
- */
2482
- function stringToStringTuples(str) {
2483
- const tuples = [];
2484
- const parts = str.split('/').slice(1); // skip first empty elem
2485
- if (parts.length === 1 && parts[0] === '') {
2486
- return [];
2487
- }
2488
- for (let p = 0; p < parts.length; p++) {
2489
- const part = parts[p];
2490
- const proto = getProtocol(part);
2491
- if (proto.size === 0) {
2492
- tuples.push([part]);
2493
- continue;
2494
- }
2495
- p++; // advance addr part
2496
- if (p >= parts.length) {
2497
- throw ParseError('invalid address: ' + str);
2498
- }
2499
- // if it's a path proto, take the rest
2500
- if (proto.path === true) {
2501
- tuples.push([
2502
- part,
2503
- // TODO: should we need to check each path part to see if it's a proto?
2504
- // This would allow for other protocols to be added after a unix path,
2505
- // however it would have issues if the path had a protocol name in the path
2506
- cleanPath(parts.slice(p).join('/'))
2507
- ]);
2508
- break;
2509
- }
2510
- tuples.push([part, parts[p]]);
2511
- }
2512
- return tuples;
2513
- }
2514
- /**
2515
- * [[str name, str addr]... ] -> string
2516
- */
2517
- function stringTuplesToString(tuples) {
2518
- const parts = [];
2519
- tuples.map((tup) => {
2520
- const proto = protoFromTuple(tup);
2521
- parts.push(proto.name);
2522
- if (tup.length > 1 && tup[1] != null) {
2523
- parts.push(tup[1]);
2524
- }
2525
- return null;
2526
- });
2527
- return cleanPath(parts.join('/'));
2528
- }
2529
- /**
2530
- * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]
2531
- */
2532
- function stringTuplesToTuples(tuples) {
2533
- return tuples.map((tup) => {
2534
- if (!Array.isArray(tup)) {
2535
- tup = [tup];
2536
- }
2537
- const proto = protoFromTuple(tup);
2538
- if (tup.length > 1) {
2539
- return [proto.code, convertToBytes(proto.code, tup[1])];
2540
- }
2541
- return [proto.code];
2542
- });
2543
- }
2544
- /**
2545
- * Convert tuples to string tuples
2546
- *
2547
- * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]
2548
- */
2549
- function tuplesToStringTuples(tuples) {
2550
- return tuples.map(tup => {
2551
- const proto = protoFromTuple(tup);
2552
- if (tup[1] != null) {
2553
- return [proto.code, convertToString(proto.code, tup[1])];
2554
- }
2555
- return [proto.code];
2556
- });
2557
- }
2558
- /**
2559
- * [[int code, Uint8Array ]... ] -> Uint8Array
2560
- */
2561
- function tuplesToBytes(tuples) {
2562
- return fromBytes(concat(tuples.map((tup) => {
2563
- const proto = protoFromTuple(tup);
2564
- let buf = Uint8Array.from(varint.encode(proto.code));
2565
- if (tup.length > 1 && tup[1] != null) {
2566
- buf = concat([buf, tup[1]]); // add address buffer
2567
- }
2568
- return buf;
2569
- })));
2570
- }
2571
- function sizeForAddr(p, addr) {
2572
- if (p.size > 0) {
2573
- return p.size / 8;
2574
- }
2575
- else if (p.size === 0) {
2576
- return 0;
2577
- }
2578
- else {
2579
- const size = varint.decode(addr);
2580
- return size + varint.decode.bytes;
2581
- }
2582
- }
2583
- function bytesToTuples(buf) {
2584
- const tuples = [];
2585
- let i = 0;
2586
- while (i < buf.length) {
2587
- const code = varint.decode(buf, i);
2588
- const n = varint.decode.bytes;
2589
- const p = getProtocol(code);
2590
- const size = sizeForAddr(p, buf.slice(i + n));
2591
- if (size === 0) {
2592
- tuples.push([code]);
2593
- i += n;
2594
- continue;
2595
- }
2596
- const addr = buf.slice(i + n, i + n + size);
2597
- i += (size + n);
2598
- if (i > buf.length) { // did not end _exactly_ at buffer.length
2599
- throw ParseError('Invalid address Uint8Array: ' + toString$1(buf, 'base16'));
2600
- }
2601
- // ok, tuple seems good.
2602
- tuples.push([code, addr]);
2603
- }
2604
- return tuples;
2605
- }
2606
- /**
2607
- * Uint8Array -> String
2608
- */
2609
- function bytesToString(buf) {
2610
- const a = bytesToTuples(buf);
2611
- const b = tuplesToStringTuples(a);
2612
- return stringTuplesToString(b);
2613
- }
2614
- /**
2615
- * String -> Uint8Array
2616
- */
2617
- function stringToBytes(str) {
2618
- str = cleanPath(str);
2619
- const a = stringToStringTuples(str);
2620
- const b = stringTuplesToTuples(a);
2621
- return tuplesToBytes(b);
2622
- }
2623
- /**
2624
- * String -> Uint8Array
2625
- */
2626
- function fromString(str) {
2627
- return stringToBytes(str);
2628
- }
2629
- /**
2630
- * Uint8Array -> Uint8Array
2631
- */
2632
- function fromBytes(buf) {
2633
- const err = validateBytes(buf);
2634
- if (err != null) {
2635
- throw err;
2636
- }
2637
- return Uint8Array.from(buf); // copy
2638
- }
2639
- function validateBytes(buf) {
2640
- try {
2641
- bytesToTuples(buf); // try to parse. will throw if breaks
2642
- }
2643
- catch (err) {
2644
- return err;
2645
- }
2646
- }
2647
- function cleanPath(str) {
2648
- return '/' + str.trim().split('/').filter((a) => a).join('/');
2649
- }
2650
- function ParseError(str) {
2651
- return new Error('Error parsing address: ' + str);
2652
- }
2653
- function protoFromTuple(tup) {
2654
- const proto = getProtocol(tup[0]);
2655
- return proto;
2656
- }
2657
-
2658
- /**
2659
- * Returns true if the two passed Uint8Arrays have the same content
2660
- */
2661
- function equals(a, b) {
2662
- if (a === b) {
2663
- return true;
2664
- }
2665
- if (a.byteLength !== b.byteLength) {
2666
- return false;
2667
- }
2668
- for (let i = 0; i < a.byteLength; i++) {
2669
- if (a[i] !== b[i]) {
2670
- return false;
2671
- }
2672
- }
2673
- return true;
2674
- }
2675
-
2676
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2677
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2678
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
2679
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2680
- };
2681
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2682
- if (kind === "m") throw new TypeError("Private method is not writable");
2683
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2684
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
2685
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2686
- };
2687
- var _DefaultMultiaddr_string, _DefaultMultiaddr_tuples, _DefaultMultiaddr_stringTuples, _a;
2688
- const inspect = Symbol.for('nodejs.util.inspect.custom');
2689
- const DNS_CODES = [
2690
- getProtocol('dns').code,
2691
- getProtocol('dns4').code,
2692
- getProtocol('dns6').code,
2693
- getProtocol('dnsaddr').code
2694
- ];
2695
- const P2P_CODES = [
2696
- getProtocol('p2p').code,
2697
- getProtocol('ipfs').code
2698
- ];
2699
- const resolvers = new Map();
2700
- const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');
2701
- /**
2702
- * Check if object is a CID instance
2703
- */
2704
- function isMultiaddr(value) {
2705
- return Boolean(value?.[symbol]);
2706
- }
2707
- /**
2708
- * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from
2709
- * a Uint8Array, String or another Multiaddr instance
2710
- * public key.
2711
- *
2712
- */
2713
- class DefaultMultiaddr {
2714
- /**
2715
- * @example
2716
- * ```js
2717
- * new Multiaddr('/ip4/127.0.0.1/tcp/4001')
2718
- * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>
2719
- * ```
2720
- *
2721
- * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
2722
- */
2723
- constructor(addr) {
2724
- _DefaultMultiaddr_string.set(this, void 0);
2725
- _DefaultMultiaddr_tuples.set(this, void 0);
2726
- _DefaultMultiaddr_stringTuples.set(this, void 0);
2727
- this[_a] = true;
2728
- // default
2729
- if (addr == null) {
2730
- addr = '';
2731
- }
2732
- if (addr instanceof Uint8Array) {
2733
- this.bytes = fromBytes(addr);
2734
- }
2735
- else if (typeof addr === 'string') {
2736
- if (addr.length > 0 && addr.charAt(0) !== '/') {
2737
- throw new Error(`multiaddr "${addr}" must start with a "/"`);
2738
- }
2739
- this.bytes = fromString(addr);
2740
- }
2741
- else if (isMultiaddr(addr)) { // Multiaddr
2742
- this.bytes = fromBytes(addr.bytes); // validate + copy buffer
2743
- }
2744
- else {
2745
- throw new Error('addr must be a string, Buffer, or another Multiaddr');
2746
- }
2747
- }
2748
- toString() {
2749
- if (__classPrivateFieldGet(this, _DefaultMultiaddr_string, "f") == null) {
2750
- __classPrivateFieldSet(this, _DefaultMultiaddr_string, bytesToString(this.bytes), "f");
2751
- }
2752
- return __classPrivateFieldGet(this, _DefaultMultiaddr_string, "f");
2753
- }
2754
- toJSON() {
2755
- return this.toString();
2756
- }
2757
- toOptions() {
2758
- const codes = this.protoCodes();
2759
- const parts = this.toString().split('/').slice(1);
2760
- let transport;
2761
- let port;
2762
- if (parts.length > 2) {
2763
- // default to https when protocol & port are omitted from DNS addrs
2764
- if (DNS_CODES.includes(codes[0]) && P2P_CODES.includes(codes[1])) {
2765
- transport = getProtocol('tcp').name;
2766
- port = 443;
2767
- }
2768
- else {
2769
- transport = getProtocol(parts[2]).name;
2770
- port = parseInt(parts[3]);
2771
- }
2772
- }
2773
- else if (DNS_CODES.includes(codes[0])) {
2774
- transport = getProtocol('tcp').name;
2775
- port = 443;
2776
- }
2777
- else {
2778
- throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');
2779
- }
2780
- const opts = {
2781
- family: (codes[0] === 41 || codes[0] === 55) ? 6 : 4,
2782
- host: parts[1],
2783
- transport,
2784
- port
2785
- };
2786
- return opts;
2787
- }
2788
- protos() {
2789
- return this.protoCodes().map(code => Object.assign({}, getProtocol(code)));
2790
- }
2791
- protoCodes() {
2792
- const codes = [];
2793
- const buf = this.bytes;
2794
- let i = 0;
2795
- while (i < buf.length) {
2796
- const code = varint.decode(buf, i);
2797
- const n = varint.decode.bytes;
2798
- const p = getProtocol(code);
2799
- const size = sizeForAddr(p, buf.slice(i + n));
2800
- i += (size + n);
2801
- codes.push(code);
2802
- }
2803
- return codes;
2804
- }
2805
- protoNames() {
2806
- return this.protos().map(proto => proto.name);
2807
- }
2808
- tuples() {
2809
- if (__classPrivateFieldGet(this, _DefaultMultiaddr_tuples, "f") == null) {
2810
- __classPrivateFieldSet(this, _DefaultMultiaddr_tuples, bytesToTuples(this.bytes), "f");
2811
- }
2812
- return __classPrivateFieldGet(this, _DefaultMultiaddr_tuples, "f");
2813
- }
2814
- stringTuples() {
2815
- if (__classPrivateFieldGet(this, _DefaultMultiaddr_stringTuples, "f") == null) {
2816
- __classPrivateFieldSet(this, _DefaultMultiaddr_stringTuples, tuplesToStringTuples(this.tuples()), "f");
2817
- }
2818
- return __classPrivateFieldGet(this, _DefaultMultiaddr_stringTuples, "f");
2819
- }
2820
- encapsulate(addr) {
2821
- addr = new DefaultMultiaddr(addr);
2822
- return new DefaultMultiaddr(this.toString() + addr.toString());
2823
- }
2824
- decapsulate(addr) {
2825
- const addrString = addr.toString();
2826
- const s = this.toString();
2827
- const i = s.lastIndexOf(addrString);
2828
- if (i < 0) {
2829
- throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);
2830
- }
2831
- return new DefaultMultiaddr(s.slice(0, i));
2832
- }
2833
- decapsulateCode(code) {
2834
- const tuples = this.tuples();
2835
- for (let i = tuples.length - 1; i >= 0; i--) {
2836
- if (tuples[i][0] === code) {
2837
- return new DefaultMultiaddr(tuplesToBytes(tuples.slice(0, i)));
2838
- }
2839
- }
2840
- return this;
2841
- }
2842
- getPeerId() {
2843
- try {
2844
- const tuples = this.stringTuples().filter((tuple) => {
2845
- if (tuple[0] === names.ipfs.code) {
2846
- return true;
2847
- }
2848
- return false;
2849
- });
2850
- // Get the last ipfs tuple ['ipfs', 'peerid string']
2851
- const tuple = tuples.pop();
2852
- if (tuple?.[1] != null) {
2853
- const peerIdStr = tuple[1];
2854
- // peer id is base58btc encoded string but not multibase encoded so add the `z`
2855
- // prefix so we can validate that it is correctly encoded
2856
- if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {
2857
- return toString$1(base58btc.decode(`z${peerIdStr}`), 'base58btc');
2858
- }
2859
- // try to parse peer id as CID
2860
- return toString$1(CID.parse(peerIdStr).multihash.bytes, 'base58btc');
2861
- }
2862
- return null;
2863
- }
2864
- catch (e) {
2865
- return null;
2866
- }
2867
- }
2868
- getPath() {
2869
- let path = null;
2870
- try {
2871
- path = this.stringTuples().filter((tuple) => {
2872
- const proto = getProtocol(tuple[0]);
2873
- if (proto.path === true) {
2874
- return true;
2875
- }
2876
- return false;
2877
- })[0][1];
2878
- if (path == null) {
2879
- path = null;
2880
- }
2881
- }
2882
- catch {
2883
- path = null;
2884
- }
2885
- return path;
2886
- }
2887
- equals(addr) {
2888
- return equals(this.bytes, addr.bytes);
2889
- }
2890
- async resolve(options) {
2891
- const resolvableProto = this.protos().find((p) => p.resolvable);
2892
- // Multiaddr is not resolvable?
2893
- if (resolvableProto == null) {
2894
- return [this];
2895
- }
2896
- const resolver = resolvers.get(resolvableProto.name);
2897
- if (resolver == null) {
2898
- throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER');
2899
- }
2900
- const addresses = await resolver(this, options);
2901
- return addresses.map((a) => new DefaultMultiaddr(a));
2902
- }
2903
- nodeAddress() {
2904
- const options = this.toOptions();
2905
- if (options.transport !== 'tcp' && options.transport !== 'udp') {
2906
- throw new Error(`multiaddr must have a valid format - no protocol with name: "${options.transport}". Must have a valid transport protocol: "{tcp, udp}"`);
2907
- }
2908
- return {
2909
- family: options.family,
2910
- address: options.host,
2911
- port: options.port
2912
- };
2913
- }
2914
- isThinWaistAddress(addr) {
2915
- const protos = (addr ?? this).protos();
2916
- if (protos.length !== 2) {
2917
- return false;
2918
- }
2919
- if (protos[0].code !== 4 && protos[0].code !== 41) {
2920
- return false;
2921
- }
2922
- if (protos[1].code !== 6 && protos[1].code !== 273) {
2923
- return false;
2924
- }
2925
- return true;
2926
- }
2927
- /**
2928
- * Returns Multiaddr as a human-readable string.
2929
- * For post Node.js v10.0.0.
2930
- * https://nodejs.org/api/deprecations.html#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect
2931
- *
2932
- * @example
2933
- * ```js
2934
- * console.log(new Multiaddr('/ip4/127.0.0.1/tcp/4001'))
2935
- * // '<Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>'
2936
- * ```
2937
- */
2938
- [(_DefaultMultiaddr_string = new WeakMap(), _DefaultMultiaddr_tuples = new WeakMap(), _DefaultMultiaddr_stringTuples = new WeakMap(), _a = symbol, inspect)]() {
2939
- return this.inspect();
2940
- }
2941
- inspect() {
2942
- return '<Multiaddr ' +
2943
- toString$1(this.bytes, 'base16') + ' - ' +
2944
- bytesToString(this.bytes) + '>';
2945
- }
2946
- }
2947
- /**
2948
- * Static factory
2949
- *
2950
- * @example
2951
- * ```js
2952
- * new Multiaddr('/ip4/127.0.0.1/tcp/4001')
2953
- * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>
2954
- * ```
2955
- *
2956
- * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
2957
- */
2958
- function multiaddr(addr) {
2959
- return new DefaultMultiaddr(addr);
2960
- }
2961
-
2962
- export { multiaddr as m };