Suite of AT Protocol TypeScript libraries built on web standards
1import * as base10 from "multiformats/bases/base10";
2import * as base16 from "multiformats/bases/base16";
3import * as base2 from "multiformats/bases/base2";
4import * as base256emoji from "multiformats/bases/base256emoji";
5import * as base32 from "multiformats/bases/base32";
6import * as base36 from "multiformats/bases/base36";
7import * as base58 from "multiformats/bases/base58";
8import * as base64 from "multiformats/bases/base64";
9import * as base8 from "multiformats/bases/base8";
10import * as identityBase from "multiformats/bases/identity";
11import type { MultibaseCodec } from "multiformats";
12import { allocUnsafe } from "./alloc.ts";
13
14function createCodec(
15 name: string,
16 prefix: string,
17 encode: (buf: Uint8Array) => string,
18 decode: (str: string) => Uint8Array,
19): MultibaseCodec<string> {
20 return {
21 name,
22 prefix,
23 encoder: {
24 name,
25 prefix,
26 encode,
27 },
28 decoder: {
29 decode,
30 },
31 };
32}
33
34const string = createCodec("utf8", "u", (buf) => {
35 const decoder = new TextDecoder("utf8");
36 return "u" + decoder.decode(buf);
37}, (str) => {
38 const encoder = new TextEncoder();
39 return encoder.encode(str.substring(1));
40});
41
42const ascii = createCodec("ascii", "a", (buf) => {
43 let string = "a";
44
45 for (let i = 0; i < buf.length; i++) {
46 string += String.fromCharCode(buf[i]);
47 }
48 return string;
49}, (str) => {
50 str = str.substring(1);
51 const buf = allocUnsafe(str.length);
52
53 for (let i = 0; i < str.length; i++) {
54 buf[i] = str.charCodeAt(i);
55 }
56
57 return buf;
58});
59
60const bases = {
61 ...identityBase,
62 ...base2,
63 ...base8,
64 ...base10,
65 ...base16,
66 ...base32,
67 ...base36,
68 ...base58,
69 ...base64,
70 ...base256emoji,
71};
72
73/** Supported base encodings */
74export type SupportedEncodings =
75 | "utf8"
76 | "utf-8"
77 | "hex"
78 | "latin1"
79 | "ascii"
80 | "binary"
81 | keyof typeof bases;
82
83const BASES: Record<SupportedEncodings, MultibaseCodec<string>> = {
84 utf8: string,
85 "utf-8": string,
86 hex: bases.base16,
87 latin1: ascii,
88 ascii,
89 binary: ascii,
90
91 ...bases,
92};
93
94/** Supported base encoding multibase codecs */
95export default BASES;
96
97/**
98 * To guarantee Uint8Array semantics, convert nodejs Buffers
99 * into vanilla Uint8Arrays
100 */
101export function asUint8Array(buf: Uint8Array): Uint8Array {
102 return buf;
103}