-
Notifications
You must be signed in to change notification settings - Fork 38
/
Text.ts
37 lines (32 loc) · 955 Bytes
/
Text.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { ContentTypeId, ContentCodec, EncodedContent } from '../MessageContent'
// xmtp.org/text
//
// This content type is used for a plain text content represented by a simple string
export const ContentTypeText = new ContentTypeId({
authorityId: 'xmtp.org',
typeId: 'text',
versionMajor: 1,
versionMinor: 0,
})
export enum Encoding {
utf8 = 'UTF-8',
}
export class TextCodec implements ContentCodec<string> {
get contentType(): ContentTypeId {
return ContentTypeText
}
encode(content: string): EncodedContent {
return {
type: ContentTypeText,
parameters: { encoding: Encoding.utf8 },
content: new TextEncoder().encode(content),
}
}
decode(content: EncodedContent): string {
const encoding = content.parameters.encoding
if (encoding && encoding !== Encoding.utf8) {
throw new Error(`unrecognized encoding ${encoding}`)
}
return new TextDecoder().decode(content.content)
}
}