@decryption/base 0.2.0

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.
package/esm/index.js ADDED
@@ -0,0 +1,1056 @@
1
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ function isBytes(a) {
3
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The
4
+ // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized
5
+ // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the
6
+ // fallback on byte-oriented views.
7
+ return (a instanceof Uint8Array ||
8
+ (ArrayBuffer.isView(a) &&
9
+ a.constructor.name === 'Uint8Array' &&
10
+ 'BYTES_PER_ELEMENT' in a &&
11
+ a.BYTES_PER_ELEMENT === 1));
12
+ }
13
+ /** Asserts something is Uint8Array. */
14
+ function abytes(b) {
15
+ if (!isBytes(b))
16
+ throw new TypeError('Uint8Array expected');
17
+ }
18
+ function isArrayOf(isString, arr) {
19
+ if (!Array.isArray(arr))
20
+ return false;
21
+ if (arr.length === 0)
22
+ return true;
23
+ if (isString) {
24
+ return arr.every((item) => typeof item === 'string');
25
+ }
26
+ else {
27
+ return arr.every((item) => Number.isSafeInteger(item));
28
+ }
29
+ }
30
+ function afn(input) {
31
+ if (typeof input !== 'function')
32
+ throw new TypeError('function expected');
33
+ return true;
34
+ }
35
+ function astr(label, input) {
36
+ if (typeof input !== 'string')
37
+ throw new TypeError(`${label}: string expected`);
38
+ return true;
39
+ }
40
+ function anumber(n) {
41
+ if (typeof n !== 'number')
42
+ throw new TypeError(`number expected, got ${typeof n}`);
43
+ if (!Number.isSafeInteger(n))
44
+ throw new RangeError(`invalid integer: ${n}`);
45
+ }
46
+ function aArr(input) {
47
+ if (!Array.isArray(input))
48
+ throw new TypeError('array expected');
49
+ }
50
+ function astrArr(label, input) {
51
+ if (!isArrayOf(true, input))
52
+ throw new TypeError(`${label}: array of strings expected`);
53
+ }
54
+ function anumArr(label, input) {
55
+ if (!isArrayOf(false, input))
56
+ throw new TypeError(`${label}: array of numbers expected`);
57
+ }
58
+ /**
59
+ * @__NO_SIDE_EFFECTS__
60
+ */
61
+ function chain(...args) {
62
+ const id = (a) => a;
63
+ // Wrap call in closure so JIT can inline calls
64
+ const wrap = (a, b) => (c) => a(b(c));
65
+ // Construct chain of args[-1].encode(args[-2].encode([...]))
66
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
67
+ // Construct chain of args[0].decode(args[1].decode(...))
68
+ const decode = args.map((x) => x.decode).reduce(wrap, id);
69
+ return { encode, decode };
70
+ }
71
+ /**
72
+ * Encodes integer radix representation to array of strings using alphabet and back.
73
+ * Could also be array of strings.
74
+ * @__NO_SIDE_EFFECTS__
75
+ */
76
+ function alphabet(letters) {
77
+ // mapping 1 to "b"
78
+ const lettersA = typeof letters === 'string' ? letters.split('') : letters;
79
+ const len = lettersA.length;
80
+ astrArr('alphabet', lettersA);
81
+ // mapping "b" to 1
82
+ const indexes = new Map(lettersA.map((l, i) => [l, i]));
83
+ return {
84
+ encode: (digits) => {
85
+ aArr(digits);
86
+ return digits.map((i) => {
87
+ if (!Number.isSafeInteger(i) || i < 0 || i >= len)
88
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
89
+ return lettersA[i];
90
+ });
91
+ },
92
+ decode: (input) => {
93
+ aArr(input);
94
+ return input.map((letter) => {
95
+ astr('alphabet.decode', letter);
96
+ const i = indexes.get(letter);
97
+ if (i === undefined)
98
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
99
+ return i;
100
+ });
101
+ },
102
+ };
103
+ }
104
+ /**
105
+ * @__NO_SIDE_EFFECTS__
106
+ */
107
+ function join(separator = '') {
108
+ astr('join', separator);
109
+ // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.
110
+ // Multi-character tokens need a separator that cannot appear inside the chunks.
111
+ return {
112
+ encode: (from) => {
113
+ astrArr('join.decode', from);
114
+ return from.join(separator);
115
+ },
116
+ decode: (to) => {
117
+ astr('join.decode', to);
118
+ return to.split(separator);
119
+ },
120
+ };
121
+ }
122
+ /**
123
+ * Pad strings array so it has integer number of bits
124
+ * @__NO_SIDE_EFFECTS__
125
+ */
126
+ function padding(bits, chr = '=') {
127
+ anumber(bits);
128
+ astr('padding', chr);
129
+ return {
130
+ encode(data) {
131
+ astrArr('padding.encode', data);
132
+ // Mutates the intermediate token array in place while appending pad chars.
133
+ // utils.padding callers that need to preserve their input should pass a copy.
134
+ while ((data.length * bits) % 8)
135
+ data.push(chr);
136
+ return data;
137
+ },
138
+ decode(input) {
139
+ astrArr('padding.decode', input);
140
+ let end = input.length;
141
+ if ((end * bits) % 8)
142
+ throw new Error('padding: invalid, string should have whole number of bytes');
143
+ for (; end > 0 && input[end - 1] === chr; end--) {
144
+ const last = end - 1;
145
+ const byte = last * bits;
146
+ if (byte % 8 === 0)
147
+ throw new Error('padding: invalid, string has too much padding');
148
+ }
149
+ return input.slice(0, end);
150
+ },
151
+ };
152
+ }
153
+ /**
154
+ * @__NO_SIDE_EFFECTS__
155
+ */
156
+ function normalize(fn) {
157
+ afn(fn);
158
+ return { encode: (from) => from, decode: (to) => fn(to) };
159
+ }
160
+ /**
161
+ * Slow: O(n^2) time complexity
162
+ */
163
+ function convertRadix(data, from, to) {
164
+ // base 1 is impossible
165
+ if (from < 2)
166
+ throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);
167
+ if (to < 2)
168
+ throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);
169
+ aArr(data);
170
+ if (!data.length)
171
+ return [];
172
+ let pos = 0;
173
+ const res = [];
174
+ const digits = Array.from(data, (d) => {
175
+ anumber(d);
176
+ if (d < 0 || d >= from)
177
+ throw new Error(`invalid integer: ${d}`);
178
+ return d;
179
+ });
180
+ const dlen = digits.length;
181
+ while (true) {
182
+ let carry = 0;
183
+ let done = true;
184
+ for (let i = pos; i < dlen; i++) {
185
+ const digit = digits[i];
186
+ const fromCarry = from * carry;
187
+ const digitBase = fromCarry + digit;
188
+ if (!Number.isSafeInteger(digitBase) ||
189
+ fromCarry / from !== carry ||
190
+ digitBase - digit !== fromCarry) {
191
+ throw new Error('convertRadix: carry overflow');
192
+ }
193
+ const div = digitBase / to;
194
+ carry = digitBase % to;
195
+ const rounded = Math.floor(div);
196
+ digits[i] = rounded;
197
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
198
+ throw new Error('convertRadix: carry overflow');
199
+ if (!done)
200
+ continue;
201
+ else if (!rounded)
202
+ pos = i;
203
+ else
204
+ done = false;
205
+ }
206
+ res.push(carry);
207
+ if (done)
208
+ break;
209
+ }
210
+ // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.
211
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
212
+ res.push(0);
213
+ return res.reverse();
214
+ }
215
+ const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
216
+ // Maximum carry width before the `pos` cycle repeats.
217
+ // Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).
218
+ const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
219
+ const powers = /* @__PURE__ */ (() => {
220
+ let res = [];
221
+ for (let i = 0; i < 40; i++)
222
+ res.push(2 ** i);
223
+ return res;
224
+ })();
225
+ /**
226
+ * Implemented with numbers, because BigInt is 5x slower
227
+ */
228
+ function convertRadix2(data, from, to, padding) {
229
+ aArr(data);
230
+ if (from <= 0 || from > 32)
231
+ throw new RangeError(`convertRadix2: wrong from=${from}`);
232
+ if (to <= 0 || to > 32)
233
+ throw new RangeError(`convertRadix2: wrong to=${to}`);
234
+ if (radix2carry(from, to) > 32) {
235
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
236
+ }
237
+ let carry = 0;
238
+ let pos = 0; // bitwise position in current element
239
+ const max = powers[from];
240
+ const mask = powers[to] - 1;
241
+ const res = [];
242
+ for (const n of data) {
243
+ anumber(n);
244
+ if (n >= max)
245
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
246
+ carry = (carry << from) | n;
247
+ if (pos + from > 32)
248
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
249
+ pos += from;
250
+ for (; pos >= to; pos -= to)
251
+ res.push(((carry >> (pos - to)) & mask) >>> 0);
252
+ const pow = powers[pos];
253
+ if (pow === undefined)
254
+ throw new Error('invalid carry');
255
+ carry &= pow - 1; // clean carry, otherwise it will cause overflow
256
+ }
257
+ carry = (carry << (to - pos)) & mask;
258
+ // Canonical decode paths reject leftover whole input words and non-zero pad bits.
259
+ // For Bech32 5->8 regrouping, this is the "4 bits or less, all zeroes" tail rule.
260
+ if (!padding && pos >= from)
261
+ throw new Error('Excess padding');
262
+ if (!padding && carry > 0)
263
+ throw new Error(`Non-zero padding: ${carry}`);
264
+ if (padding && pos > 0)
265
+ res.push(carry >>> 0);
266
+ return res;
267
+ }
268
+ /**
269
+ * @__NO_SIDE_EFFECTS__
270
+ */
271
+ function radix(num) {
272
+ anumber(num);
273
+ const _256 = 2 ** 8;
274
+ // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.
275
+ return {
276
+ encode: (bytes) => {
277
+ if (!isBytes(bytes))
278
+ throw new TypeError('radix.encode input should be Uint8Array');
279
+ return convertRadix(Array.from(bytes), _256, num);
280
+ },
281
+ decode: (digits) => {
282
+ anumArr('radix.decode', digits);
283
+ return Uint8Array.from(convertRadix(digits, num, _256));
284
+ },
285
+ };
286
+ }
287
+ /**
288
+ * If both bases are power of same number (like `2**8 <-> 2**64`),
289
+ * there is a linear algorithm. For now we have implementation for power-of-two bases only.
290
+ * @__NO_SIDE_EFFECTS__
291
+ */
292
+ function radix2(bits, revPadding = false) {
293
+ anumber(bits);
294
+ if (bits <= 0 || bits > 32)
295
+ throw new RangeError('radix2: bits should be in (0..32]');
296
+ if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
297
+ throw new RangeError('radix2: carry overflow');
298
+ // revPadding flips which direction allows a partial zero tail.
299
+ // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.
300
+ return {
301
+ encode: (bytes) => {
302
+ if (!isBytes(bytes))
303
+ throw new TypeError('radix2.encode input should be Uint8Array');
304
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
305
+ },
306
+ decode: (digits) => {
307
+ anumArr('radix2.decode', digits);
308
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
309
+ },
310
+ };
311
+ }
312
+ function unsafeWrapper(fn) {
313
+ afn(fn);
314
+ return function (...args) {
315
+ // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.
316
+ // Do not wrap code that needs to preserve exception details.
317
+ try {
318
+ return fn.apply(null, args);
319
+ }
320
+ catch (e) { }
321
+ };
322
+ }
323
+ function checksum(len, fn) {
324
+ anumber(len);
325
+ // Reject degenerate zero-byte checksums up front so callers don't accidentally
326
+ // build a no-op checksum stage.
327
+ if (len <= 0)
328
+ throw new RangeError(`checksum length must be positive: ${len}`);
329
+ afn(fn);
330
+ const _fn = fn;
331
+ // Uses the first `len` bytes of fn(data) in both directions.
332
+ // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.
333
+ return {
334
+ encode(data) {
335
+ if (!isBytes(data))
336
+ throw new TypeError('checksum.encode: input should be Uint8Array');
337
+ const sum = _fn(data).slice(0, len);
338
+ const res = new Uint8Array(data.length + len);
339
+ res.set(data);
340
+ res.set(sum, data.length);
341
+ return res;
342
+ },
343
+ decode(data) {
344
+ if (!isBytes(data))
345
+ throw new TypeError('checksum.decode: input should be Uint8Array');
346
+ const payload = data.slice(0, -len);
347
+ const oldChecksum = data.slice(-len);
348
+ const newChecksum = _fn(payload).slice(0, len);
349
+ for (let i = 0; i < len; i++)
350
+ if (newChecksum[i] !== oldChecksum[i])
351
+ throw new Error('Invalid checksum');
352
+ return payload;
353
+ },
354
+ };
355
+ }
356
+ // prettier-ignore
357
+ /**
358
+ * Low-level building blocks used by the exported codecs.
359
+ * @example
360
+ * Build a radix-32 coder from the low-level helpers.
361
+ * ```ts
362
+ * import { utils } from '@decryption/base';
363
+ * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));
364
+ * ```
365
+ */
366
+ export const utils = /* @__PURE__ */ Object.freeze({
367
+ alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
368
+ });
369
+ // RFC 4648 aka RFC 3548
370
+ // ---------------------
371
+ /**
372
+ * base16 encoding from RFC 4648.
373
+ * This codec uses RFC 4648 Table 5's uppercase alphabet directly.
374
+ * RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here.
375
+ * Use `hex` for case-insensitive hex decoding.
376
+ * @example
377
+ * ```js
378
+ * base16.encode(Uint8Array.from([0x12, 0xab]));
379
+ * // => '12AB'
380
+ * ```
381
+ */
382
+ export const base16 = /* @__PURE__ */ Object.freeze(chain(radix2(4), alphabet('0123456789ABCDEF'), join('')));
383
+ /**
384
+ * base32 encoding from RFC 4648. Has padding.
385
+ * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose
386
+ * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.
387
+ * Use `base32nopad` for unpadded version.
388
+ * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
389
+ * @example
390
+ * ```js
391
+ * base32.encode(Uint8Array.from([0x12, 0xab]));
392
+ * // => 'CKVQ===='
393
+ * base32.decode('CKVQ====');
394
+ * // => Uint8Array.from([0x12, 0xab])
395
+ * ```
396
+ */
397
+ export const base32 = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')));
398
+ /**
399
+ * base32 encoding from RFC 4648. No padding.
400
+ * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.
401
+ * Use `base32` for padded version.
402
+ * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
403
+ * @example
404
+ * ```js
405
+ * base32nopad.encode(Uint8Array.from([0x12, 0xab]));
406
+ * // => 'CKVQ'
407
+ * base32nopad.decode('CKVQ');
408
+ * // => Uint8Array.from([0x12, 0xab])
409
+ * ```
410
+ */
411
+ export const base32nopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')));
412
+ /**
413
+ * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
414
+ * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.
415
+ * Use `base32hexnopad` for unpadded version.
416
+ * @example
417
+ * ```js
418
+ * base32hex.encode(Uint8Array.from([0x12, 0xab]));
419
+ * // => '2ALG===='
420
+ * base32hex.decode('2ALG====');
421
+ * // => Uint8Array.from([0x12, 0xab])
422
+ * ```
423
+ */
424
+ export const base32hex = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')));
425
+ /**
426
+ * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
427
+ * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.
428
+ * Use `base32hex` for padded version.
429
+ * @example
430
+ * ```js
431
+ * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
432
+ * // => '2ALG'
433
+ * base32hexnopad.decode('2ALG');
434
+ * // => Uint8Array.from([0x12, 0xab])
435
+ * ```
436
+ */
437
+ export const base32hexnopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')));
438
+ /**
439
+ * base32 encoding from RFC 4648. Doug Crockford's version.
440
+ * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.
441
+ * @example
442
+ * ```js
443
+ * base32crockford.encode(Uint8Array.from([0x12, 0xab]));
444
+ * // => '2ANG'
445
+ * base32crockford.decode('2ANG');
446
+ * // => Uint8Array.from([0x12, 0xab])
447
+ * ```
448
+ */
449
+ export const base32crockford = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))));
450
+ // Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
451
+ // Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.
452
+ // prettier-ignore
453
+ const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
454
+ typeof Uint8Array.fromBase64 === 'function')();
455
+ // Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.
456
+ // Reject them first so the native base64 path still follows RFC 4648 §3.3.
457
+ // ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE
458
+ const ASCII_WHITESPACE = /[\t\n\f\r ]/;
459
+ const decodeBase64Builtin = (s, isUrl) => {
460
+ astr('base64', s);
461
+ const alphabet = isUrl ? 'base64url' : 'base64';
462
+ // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace
463
+ // And checking just for whitespace makes decoding about 3x faster than a full range check.
464
+ // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.
465
+ if (s.length > 0 && ASCII_WHITESPACE.test(s))
466
+ throw new Error('invalid base64');
467
+ return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
468
+ };
469
+ /**
470
+ * base64 from RFC 4648. Padded.
471
+ * Use `base64nopad` for unpadded version.
472
+ * Also check out `base64url`, `base64urlnopad`.
473
+ * Falls back to built-in function, when available.
474
+ * @example
475
+ * ```js
476
+ * base64.encode(Uint8Array.from([0x12, 0xab]));
477
+ * // => 'Eqs='
478
+ * base64.decode('Eqs=');
479
+ * // => Uint8Array.from([0x12, 0xab])
480
+ * ```
481
+ */
482
+ // prettier-ignore
483
+ export const base64 = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {
484
+ encode(b) { abytes(b); return b.toBase64(); },
485
+ decode(s) { return decodeBase64Builtin(s, false); },
486
+ } : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')));
487
+ /**
488
+ * base64 from RFC 4648. No padding.
489
+ * Use `base64` for padded version.
490
+ * @example
491
+ * ```js
492
+ * base64nopad.encode(Uint8Array.from([0x12, 0xab]));
493
+ * // => 'Eqs'
494
+ * base64nopad.decode('Eqs');
495
+ * // => Uint8Array.from([0x12, 0xab])
496
+ * ```
497
+ */
498
+ export const base64nopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')));
499
+ /**
500
+ * base64 from RFC 4648, using URL-safe alphabet. Padded.
501
+ * Use `base64urlnopad` for unpadded version.
502
+ * Falls back to built-in function, when available.
503
+ * @example
504
+ * ```js
505
+ * base64url.encode(Uint8Array.from([0x12, 0xab]));
506
+ * // => 'Eqs='
507
+ * base64url.decode('Eqs=');
508
+ * // => Uint8Array.from([0x12, 0xab])
509
+ * ```
510
+ */
511
+ // prettier-ignore
512
+ export const base64url = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {
513
+ encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
514
+ decode(s) { return decodeBase64Builtin(s, true); },
515
+ } : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')));
516
+ /**
517
+ * base64 from RFC 4648, using URL-safe alphabet. No padding.
518
+ * Use `base64url` for padded version.
519
+ * @example
520
+ * ```js
521
+ * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
522
+ * // => 'Eqs'
523
+ * base64urlnopad.decode('Eqs');
524
+ * // => Uint8Array.from([0x12, 0xab])
525
+ * ```
526
+ */
527
+ export const base64urlnopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')));
528
+ // base58 code
529
+ // -----------
530
+ const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
531
+ /**
532
+ * base58: base64 without ambigous characters +, /, 0, O, I, l.
533
+ * Quadratic (O(n^2)) - so, can't be used on large inputs.
534
+ * @example
535
+ * ```js
536
+ * const text = base58.encode(Uint8Array.from([0, 1, 2]));
537
+ * base58.decode(text);
538
+ * // => Uint8Array.from([0, 1, 2])
539
+ * ```
540
+ */
541
+ export const base58 = /* @__PURE__ */ Object.freeze(genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));
542
+ /**
543
+ * base58: flickr version. Check out `base58`.
544
+ * @example
545
+ * Round-trip bytes with the Flickr alphabet.
546
+ * ```ts
547
+ * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));
548
+ * base58flickr.decode(text);
549
+ * ```
550
+ */
551
+ export const base58flickr = /* @__PURE__ */ Object.freeze(genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));
552
+ /**
553
+ * base58: XRP version. Check out `base58`.
554
+ * @example
555
+ * Round-trip bytes with the XRP alphabet.
556
+ * ```ts
557
+ * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));
558
+ * base58xrp.decode(text);
559
+ * ```
560
+ */
561
+ export const base58xrp = /* @__PURE__ */ Object.freeze(genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));
562
+ // Data len (index) -> encoded block len.
563
+ // Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.
564
+ const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
565
+ /**
566
+ * base58: XMR version. Check out `base58`.
567
+ * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
568
+ * Block encoding significantly reduces quadratic complexity of base58.
569
+ * @example
570
+ * Round-trip bytes with the Monero block codec.
571
+ * ```ts
572
+ * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));
573
+ * base58xmr.decode(text);
574
+ * ```
575
+ */
576
+ export const base58xmr = /* @__PURE__ */ Object.freeze({
577
+ encode(data) {
578
+ abytes(data);
579
+ let res = '';
580
+ for (let i = 0; i < data.length; i += 8) {
581
+ const block = data.subarray(i, i + 8);
582
+ res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
583
+ }
584
+ return res;
585
+ },
586
+ decode(str) {
587
+ astr('base58xmr.decode', str);
588
+ let res = [];
589
+ for (let i = 0; i < str.length; i += 11) {
590
+ const slice = str.slice(i, i + 11);
591
+ const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
592
+ const block = base58.decode(slice);
593
+ for (let j = 0; j < block.length - blockLen; j++) {
594
+ if (block[j] !== 0)
595
+ throw new Error('base58xmr: wrong padding');
596
+ }
597
+ res = res.concat(Array.from(block.slice(block.length - blockLen)));
598
+ }
599
+ return Uint8Array.from(res);
600
+ },
601
+ });
602
+ /**
603
+ * Method, which creates base58check encoder.
604
+ * Requires function, calculating sha256.
605
+ * Callers must include any version bytes in `data`; this helper only applies the
606
+ * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.
607
+ * @param sha256 - Function used to calculate the checksum hash.
608
+ * @returns base58check codec using 4 checksum bytes.
609
+ * @throws On wrong argument types. {@link TypeError}
610
+ * @example
611
+ * Create a base58check codec from a SHA-256 implementation.
612
+ * ```ts
613
+ * import { createBase58check } from '@decryption/base';
614
+ * import { sha256 } from '@decryption/hashes/sha2';
615
+ * const coder = createBase58check(sha256);
616
+ * coder.encode(Uint8Array.from([1, 2, 3]));
617
+ * ```
618
+ */
619
+ export const createBase58check = (sha256) => {
620
+ // Validate the hash function at construction time so wrong inputs fail before returning a coder.
621
+ afn(sha256);
622
+ const _sha256 = sha256;
623
+ return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);
624
+ };
625
+ /**
626
+ * Use `createBase58check` instead.
627
+ * @deprecated Use {@link createBase58check} instead.
628
+ * Callers must include any version bytes in `data`; this alias keeps the same
629
+ * 4-byte double-SHA256 checksum behavior as `createBase58check`.
630
+ * @param sha256 - Function used to calculate the checksum hash.
631
+ * @returns base58check codec using 4 checksum bytes.
632
+ * @example
633
+ * Create a base58check codec with the deprecated alias.
634
+ * ```ts
635
+ * import { base58check } from '@decryption/base';
636
+ * import { sha256 } from '@decryption/hashes/sha2';
637
+ * const coder = base58check(sha256);
638
+ * coder.encode(Uint8Array.from([1, 2, 3]));
639
+ * ```
640
+ */
641
+ export const base58check = createBase58check;
642
+ // BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.
643
+ const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
644
+ // BIP 173 `bech32_polymod` GEN coefficients.
645
+ const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
646
+ // BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.
647
+ function bech32Polymod(pre) {
648
+ const b = pre >> 25;
649
+ let chk = (pre & 0x1ffffff) << 5;
650
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
651
+ if (((b >> i) & 1) === 1)
652
+ chk ^= POLYMOD_GENERATORS[i];
653
+ }
654
+ return chk;
655
+ }
656
+ function bechChecksum(prefix, words, encodingConst = 1) {
657
+ const len = prefix.length;
658
+ let chk = 1;
659
+ for (let i = 0; i < len; i++) {
660
+ const c = prefix.charCodeAt(i);
661
+ if (c < 33 || c > 126)
662
+ throw new Error(`Invalid prefix (${prefix})`);
663
+ chk = bech32Polymod(chk) ^ (c >> 5);
664
+ }
665
+ chk = bech32Polymod(chk);
666
+ for (let i = 0; i < len; i++)
667
+ chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
668
+ for (let v of words)
669
+ chk = bech32Polymod(chk) ^ v;
670
+ for (let i = 0; i < 6; i++)
671
+ chk = bech32Polymod(chk);
672
+ // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.
673
+ chk ^= encodingConst;
674
+ return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
675
+ }
676
+ /**
677
+ * @__NO_SIDE_EFFECTS__
678
+ */
679
+ function genBech32(encoding) {
680
+ // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.
681
+ const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
682
+ const _words = radix2(5);
683
+ const fromWords = _words.decode;
684
+ const toWords = _words.encode;
685
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
686
+ function encode(prefix, words, limit = 90) {
687
+ astr('bech32.encode prefix', prefix);
688
+ if (isBytes(words))
689
+ words = Array.from(words);
690
+ anumArr('bech32.encode', words);
691
+ const plen = prefix.length;
692
+ if (plen === 0)
693
+ throw new TypeError(`Invalid prefix length ${plen}`);
694
+ // Total output is hrp + `1` separator + payload words + 6 checksum chars.
695
+ const actualLength = plen + 7 + words.length;
696
+ if (limit !== false && actualLength > limit)
697
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
698
+ const lowered = prefix.toLowerCase();
699
+ const sum = bechChecksum(lowered, words, ENCODING_CONST);
700
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
701
+ }
702
+ function decode(str, limit = 90) {
703
+ astr('bech32.decode input', str);
704
+ const slen = str.length;
705
+ // Minimum length is 1-char hrp + `1` separator + 6-char checksum.
706
+ if (slen < 8 || (limit !== false && slen > limit))
707
+ throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
708
+ // don't allow mixed case
709
+ const lowered = str.toLowerCase();
710
+ if (str !== lowered && str !== str.toUpperCase())
711
+ throw new Error(`String must be lowercase or uppercase`);
712
+ const sepIndex = lowered.lastIndexOf('1');
713
+ if (sepIndex === 0 || sepIndex === -1)
714
+ throw new Error(`Letter "1" must be present between prefix and data only`);
715
+ const prefix = lowered.slice(0, sepIndex);
716
+ const data = lowered.slice(sepIndex + 1);
717
+ if (data.length < 6)
718
+ throw new Error('Data must be at least 6 characters long');
719
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
720
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
721
+ if (!data.endsWith(sum))
722
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
723
+ return { prefix, words };
724
+ }
725
+ const decodeUnsafe = unsafeWrapper(decode);
726
+ function decodeToBytes(str) {
727
+ // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).
728
+ const { prefix, words } = decode(str, false);
729
+ return {
730
+ prefix,
731
+ words,
732
+ bytes: fromWords(words),
733
+ };
734
+ }
735
+ function encodeFromBytes(prefix, bytes) {
736
+ // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).
737
+ return encode(prefix, toWords(bytes));
738
+ }
739
+ return {
740
+ encode,
741
+ decode,
742
+ encodeFromBytes,
743
+ decodeToBytes,
744
+ decodeUnsafe,
745
+ fromWords,
746
+ fromWordsUnsafe,
747
+ toWords,
748
+ };
749
+ }
750
+ /**
751
+ * bech32 from BIP 173. Operates on words.
752
+ * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
753
+ * @example
754
+ * Convert bytes to words, encode them, then decode back.
755
+ * ```ts
756
+ * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));
757
+ * const text = bech32.encode('bc', words);
758
+ * bech32.decode(text);
759
+ * ```
760
+ */
761
+ export const bech32 = /* @__PURE__ */ Object.freeze(genBech32('bech32'));
762
+ /**
763
+ * bech32m from BIP 350. Operates on words.
764
+ * It was to mitigate `bech32` weaknesses.
765
+ * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
766
+ * @example
767
+ * Convert bytes to words, encode them with bech32m, then decode back.
768
+ * ```ts
769
+ * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));
770
+ * const text = bech32m.encode('bc', words);
771
+ * bech32m.decode(text);
772
+ * ```
773
+ */
774
+ export const bech32m = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));
775
+ /**
776
+ * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.
777
+ * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.
778
+ * @example
779
+ * ```js
780
+ * const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ])
781
+ * const str = ascii.encode(b); // "ABC"
782
+ * ```
783
+ */
784
+ export const ascii = /* @__PURE__ */ Object.freeze({
785
+ encode(data) {
786
+ abytes(data);
787
+ let res = '';
788
+ for (let i = 0; i < data.length; i++) {
789
+ const byte = data[i];
790
+ // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to
791
+ // Latin-1/UTF-8.
792
+ if (byte > 127)
793
+ throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);
794
+ res += String.fromCharCode(byte);
795
+ }
796
+ return res;
797
+ },
798
+ decode(str) {
799
+ if (typeof str !== 'string')
800
+ throw new TypeError('ascii string expected, got ' + typeof str);
801
+ const res = new Uint8Array(str.length);
802
+ for (let i = 0; i < str.length; i++) {
803
+ // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps
804
+ // exact error positions.
805
+ const charCode = str.charCodeAt(i);
806
+ if (charCode > 127) {
807
+ throw new RangeError(`string contains non-ASCII character "${str[i]}" with code ${charCode} at position ${i}`);
808
+ }
809
+ res[i] = charCode;
810
+ }
811
+ return res;
812
+ },
813
+ });
814
+ const _isWellFormedShim = (str) => {
815
+ // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native
816
+ // isWellFormed on our tests/fuzz corpus.
817
+ try {
818
+ return encodeURI(str) !== null;
819
+ }
820
+ catch {
821
+ return false;
822
+ }
823
+ };
824
+ const _isWellFormed = /* @__PURE__ */ (() =>
825
+ // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.
826
+ typeof ''.isWellFormed === 'function'
827
+ ? (str) => str.isWellFormed()
828
+ : _isWellFormedShim)();
829
+ // This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed
830
+ // UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform
831
+ // text codecs.
832
+ const utf8Fallback = /* @__PURE__ */ Object.freeze({
833
+ encode(data) {
834
+ abytes(data);
835
+ let res = '';
836
+ for (let i = 0; i < data.length;) {
837
+ const a = data[i++];
838
+ if (a < 0b1000_0000) {
839
+ res += String.fromCharCode(a);
840
+ continue;
841
+ }
842
+ if (a < 0b1100_0010 || i >= data.length)
843
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
844
+ const b = data[i++];
845
+ if ((b & 0b1100_0000) !== 0b1000_0000)
846
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
847
+ let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);
848
+ if (a >= 0b1110_0000) {
849
+ if (i >= data.length)
850
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
851
+ const c = data[i++];
852
+ if ((c & 0b1100_0000) !== 0b1000_0000 ||
853
+ (a === 0b1110_0000 && b < 0b1010_0000) ||
854
+ (a === 0xed && b >= 0b1010_0000))
855
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
856
+ cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);
857
+ if (a >= 0b1111_0000) {
858
+ if (i >= data.length)
859
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
860
+ const d = data[i++];
861
+ if (a > 0b1111_0100 ||
862
+ (d & 0b1100_0000) !== 0b1000_0000 ||
863
+ (a === 0b1111_0000 && b < 0b1001_0000) ||
864
+ (a === 0b1111_0100 && b >= 0b1001_0000))
865
+ throw new TypeError(`invalid utf8 at byte ${i - 1}`);
866
+ cp =
867
+ ((a & 7) << 18) |
868
+ ((b & 0b0011_1111) << 12) |
869
+ ((c & 0b0011_1111) << 6) |
870
+ (d & 0b0011_1111);
871
+ }
872
+ }
873
+ if (cp < 0x10000)
874
+ res += String.fromCharCode(cp);
875
+ else {
876
+ cp -= 0x10000;
877
+ res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);
878
+ }
879
+ }
880
+ return res;
881
+ },
882
+ decode(str) {
883
+ astr('utf8', str);
884
+ if (!_isWellFormed(str))
885
+ throw new TypeError('utf8 expected well-formed string');
886
+ // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and
887
+ // large Node inputs.
888
+ const res = new Uint8Array(str.length * 3);
889
+ let pos = 0;
890
+ for (let i = 0; i < str.length; i++) {
891
+ let c = str.charCodeAt(i);
892
+ if (c < 0b1000_0000) {
893
+ res[pos++] = c;
894
+ continue;
895
+ }
896
+ if (c >= 0xd800 && c <= 0xdfff) {
897
+ const d = str.charCodeAt(++i);
898
+ c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;
899
+ }
900
+ if (c >= 0x10000) {
901
+ res[pos++] = (c >> 18) | 0b1111_0000;
902
+ res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;
903
+ }
904
+ else if (c >= 0x800)
905
+ res[pos++] = (c >> 12) | 0b1110_0000;
906
+ else
907
+ res[pos++] = (c >> 6) | 0b1100_0000;
908
+ if (c >= 0x800)
909
+ res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;
910
+ res[pos++] = (c & 0b0011_1111) | 0b1000_0000;
911
+ }
912
+ return res.subarray(0, pos);
913
+ },
914
+ });
915
+ /**
916
+ * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.
917
+ * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and
918
+ * `decode(string)` returns bytes.
919
+ * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and
920
+ * throws on invalid UTF-8 bytes.
921
+ * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with
922
+ * lone surrogates.
923
+ * @example
924
+ * ```js
925
+ * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
926
+ * const str = utf8.encode(b); // "hey"
927
+ * ```
928
+ */
929
+ export const utf8 = /* @__PURE__ */ (() => {
930
+ let _utf8Encoder;
931
+ let _utf8Decoder;
932
+ const utf8Builtin = {
933
+ // ignoreBOM preserves an explicit leading U+FEFF;
934
+ // fatal rejects invalid UTF-8 bytes instead of replacing them.
935
+ encode(data) {
936
+ abytes(data);
937
+ return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);
938
+ },
939
+ decode(str) {
940
+ astr('utf8', str);
941
+ if (!_isWellFormed(str))
942
+ throw new TypeError('utf8 expected well-formed string');
943
+ return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);
944
+ },
945
+ };
946
+ return Object.freeze({
947
+ // Select each direction once at module init, since
948
+ // TextEncoder and TextDecoder can exist independently.
949
+ encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,
950
+ decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,
951
+ });
952
+ })();
953
+ // Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.
954
+ export const __TESTS = /* @__PURE__ */ Object.freeze({
955
+ utf8Fallback: utf8Fallback,
956
+ _isWellFormedShim: _isWellFormedShim,
957
+ });
958
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
959
+ // prettier-ignore
960
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
961
+ // Require both directions before enabling the native hex path so encode/decode stay symmetric.
962
+ typeof Uint8Array.from([]).toHex === 'function' &&
963
+ typeof Uint8Array.fromHex === 'function')();
964
+ // prettier-ignore
965
+ const hexBuiltin = {
966
+ // Keep local type guards so the native path preserves library-level input errors.
967
+ // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.
968
+ encode(data) { abytes(data); return data.toHex(); },
969
+ // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.
970
+ decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
971
+ };
972
+ /**
973
+ * hex string decoder. Uses built-in function, when available.
974
+ * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.
975
+ * @example
976
+ * ```js
977
+ * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
978
+ * const str = hex.encode(b); // "0102ff"
979
+ * ```
980
+ */
981
+ export const hex = /* @__PURE__ */ Object.freeze(hasHexBuiltin
982
+ ? hexBuiltin
983
+ : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
984
+ if (typeof s !== 'string' || s.length % 2 !== 0)
985
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
986
+ return s.toLowerCase();
987
+ })));
988
+ // prettier-ignore
989
+ // Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.
990
+ const CODERS = {
991
+ utf8, hex, base16, base32, base64, base64url, base58, base58xmr
992
+ };
993
+ const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
994
+ /**
995
+ * Encodes bytes with one of the built-in codecs.
996
+ * @deprecated Use the codec directly, for example `hex.encode(bytes)`.
997
+ * @param type - Codec name.
998
+ * @param bytes - Bytes to encode.
999
+ * @returns Encoded string.
1000
+ * @throws On wrong argument types. {@link TypeError}
1001
+ * @example
1002
+ * ```ts
1003
+ * bytesToString('hex', Uint8Array.from([1, 2, 255]));
1004
+ * ```
1005
+ */
1006
+ export const bytesToString = (type, bytes) => {
1007
+ if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
1008
+ throw new TypeError(coderTypeError);
1009
+ if (!isBytes(bytes))
1010
+ throw new TypeError('bytesToString() expects Uint8Array');
1011
+ return CODERS[type].encode(bytes);
1012
+ };
1013
+ /**
1014
+ * Alias for `bytesToString`.
1015
+ * @deprecated Use {@link bytesToString} or the codec directly instead.
1016
+ * @param type - Codec name.
1017
+ * @param bytes - Bytes to encode.
1018
+ * @returns Encoded string.
1019
+ * @example
1020
+ * ```ts
1021
+ * str('hex', Uint8Array.from([1, 2, 255]));
1022
+ * ```
1023
+ */
1024
+ export const str = bytesToString; // as in python, but for bytes only
1025
+ /**
1026
+ * Decodes a string with one of the built-in codecs.
1027
+ * @deprecated Use the codec directly, for example `hex.decode(text)`.
1028
+ * @param type - Codec name.
1029
+ * @param str - Encoded string.
1030
+ * @returns Decoded bytes.
1031
+ * @throws On wrong argument types. {@link TypeError}
1032
+ * @example
1033
+ * ```ts
1034
+ * stringToBytes('hex', '0102ff');
1035
+ * ```
1036
+ */
1037
+ export const stringToBytes = (type, str) => {
1038
+ // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.
1039
+ if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
1040
+ throw new TypeError(coderTypeError);
1041
+ if (typeof str !== 'string')
1042
+ throw new TypeError('stringToBytes() expects string');
1043
+ return CODERS[type].decode(str);
1044
+ };
1045
+ /**
1046
+ * Alias for `stringToBytes`.
1047
+ * @deprecated Use {@link stringToBytes} or the codec directly instead.
1048
+ * @param type - Codec name.
1049
+ * @param str - Encoded string.
1050
+ * @returns Decoded bytes.
1051
+ * @example
1052
+ * ```ts
1053
+ * bytes('hex', '0102ff');
1054
+ * ```
1055
+ */
1056
+ export const bytes = stringToBytes;