@1outres/dsh-bot-connector-google 0.0.0-stage → 0.3.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.
@@ -0,0 +1,128 @@
1
+ import type { gmail_v1 } from "@googleapis/gmail"
2
+
3
+ /** A received message as the tools read it: its headers, text and attachments. */
4
+ export interface ReadMessage {
5
+ readonly id: string
6
+ readonly threadId: string
7
+ readonly labelIds: readonly string[]
8
+ readonly from?: string
9
+ readonly to?: string
10
+ readonly cc?: string
11
+ readonly replyTo?: string
12
+ readonly subject?: string
13
+ readonly date?: string
14
+ readonly messageId?: string
15
+ readonly references?: string
16
+ readonly snippet: string
17
+ readonly internalDate?: number
18
+ /** Its text: the text/plain part, else its HTML part as text. */
19
+ readonly text: string
20
+ readonly attachments: readonly ReadAttachment[]
21
+ }
22
+
23
+ export interface ReadAttachment {
24
+ readonly attachmentId: string
25
+ readonly filename: string
26
+ readonly mimeType: string
27
+ readonly size: number
28
+ }
29
+
30
+ type Part = gmail_v1.Schema$MessagePart
31
+
32
+ function header(part: Part | undefined, name: string): string | undefined {
33
+ const value = part?.headers?.find(
34
+ (item) => item.name?.toLowerCase() === name.toLowerCase(),
35
+ )?.value
36
+ return value === null || value === undefined ? undefined : value
37
+ }
38
+
39
+ function decode(data: string | null | undefined, charset: string | undefined): string {
40
+ if (data === null || data === undefined) return ""
41
+ const bytes = Buffer.from(data, "base64url")
42
+ try {
43
+ return new TextDecoder(charset ?? "utf-8").decode(bytes)
44
+ } catch {
45
+ return new TextDecoder("utf-8").decode(bytes)
46
+ }
47
+ }
48
+
49
+ function charsetOf(part: Part): string | undefined {
50
+ return /charset="?([^";]+)"?/i.exec(header(part, "Content-Type") ?? "")?.[1]
51
+ }
52
+
53
+ function walk(part: Part | undefined, visit: (part: Part) => void) {
54
+ if (part === undefined) return
55
+ visit(part)
56
+ for (const child of part.parts ?? []) walk(child, visit)
57
+ }
58
+
59
+ /** HTML as plain text: tags out, entities read, never rendered. */
60
+ export function htmlText(html: string): string {
61
+ return html
62
+ .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, "")
63
+ .replace(/<br\s*\/?>/gi, "\n")
64
+ .replace(/<\/(p|div|li|tr|h[1-6])>/gi, "\n")
65
+ .replace(/<[^>]+>/g, "")
66
+ .replace(/&nbsp;/g, " ")
67
+ .replace(/&lt;/g, "<")
68
+ .replace(/&gt;/g, ">")
69
+ .replace(/&quot;/g, '"')
70
+ .replace(/&#39;/g, "'")
71
+ .replace(/&amp;/g, "&")
72
+ .replace(/\n{3,}/g, "\n\n")
73
+ .trim()
74
+ }
75
+
76
+ export function readMessage(message: gmail_v1.Schema$Message): ReadMessage {
77
+ let plain: string | undefined
78
+ let html: string | undefined
79
+ const attachments: ReadAttachment[] = []
80
+ walk(message.payload ?? undefined, (part) => {
81
+ const type = (part.mimeType ?? "").toLowerCase()
82
+ const attachmentId = part.body?.attachmentId
83
+ if (part.filename && attachmentId) {
84
+ attachments.push({
85
+ attachmentId,
86
+ filename: part.filename,
87
+ mimeType: part.mimeType ?? "application/octet-stream",
88
+ size: part.body?.size ?? 0,
89
+ })
90
+ return
91
+ }
92
+ if (type === "text/plain" && plain === undefined)
93
+ plain = decode(part.body?.data, charsetOf(part))
94
+ if (type === "text/html" && html === undefined) html = decode(part.body?.data, charsetOf(part))
95
+ })
96
+ const top = message.payload ?? undefined
97
+ const optional = (name: string, value: string | undefined) =>
98
+ value === undefined ? {} : { [name]: value }
99
+ return {
100
+ id: message.id ?? "",
101
+ threadId: message.threadId ?? "",
102
+ labelIds: message.labelIds ?? [],
103
+ ...optional("from", header(top, "From")),
104
+ ...optional("to", header(top, "To")),
105
+ ...optional("cc", header(top, "Cc")),
106
+ ...optional("replyTo", header(top, "Reply-To")),
107
+ ...optional("subject", header(top, "Subject")),
108
+ ...optional("date", header(top, "Date")),
109
+ ...optional("messageId", header(top, "Message-ID") ?? header(top, "Message-Id")),
110
+ ...optional("references", header(top, "References")),
111
+ snippet: message.snippet ?? "",
112
+ ...(message.internalDate ? { internalDate: Number(message.internalDate) } : {}),
113
+ text: plain ?? (html === undefined ? "" : htmlText(html)),
114
+ attachments,
115
+ }
116
+ }
117
+
118
+ /** A message's headers in one line each, for summaries and search results. */
119
+ export function headline(message: ReadMessage): string {
120
+ return [
121
+ `From: ${message.from ?? "(unknown)"}`,
122
+ `Subject: ${message.subject ?? "(no subject)"}`,
123
+ ...(message.date === undefined ? [] : [`Date: ${message.date}`]),
124
+ ].join(" · ")
125
+ }
126
+
127
+ /** The headers a metadata read asks for. */
128
+ export const METADATA_HEADERS = ["From", "To", "Cc", "Subject", "Date", "Message-ID"]
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The MIME message the connector sends, built by hand (RFC 5322, 2045,
3
+ * 2047, 2231): what the preview shows is what is sent, nothing is added.
4
+ * Text is UTF-8 `text/plain` only, sent base64; attachments go in a
5
+ * `multipart/mixed` whose boundary is derived from the content.
6
+ */
7
+ import { createHash } from "node:crypto"
8
+ import type { Mailbox } from "./addresses"
9
+
10
+ export interface MimeAttachment {
11
+ readonly filename: string
12
+ readonly mimeType: string
13
+ readonly data: Uint8Array
14
+ }
15
+
16
+ export interface MimeMessage {
17
+ readonly from: Mailbox
18
+ readonly to: readonly Mailbox[]
19
+ readonly cc: readonly Mailbox[]
20
+ readonly bcc: readonly Mailbox[]
21
+ readonly subject: string
22
+ readonly body: string
23
+ readonly inReplyTo?: string
24
+ readonly references?: readonly string[]
25
+ readonly attachments: readonly MimeAttachment[]
26
+ }
27
+
28
+ const CRLF = "\r\n"
29
+ const ASCII_TEXT = /^[\x20-\x7e]*$/
30
+ const ATOM_TEXT = /^[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~ ]*$/
31
+ const MESSAGE_ID = /^<[^<>\s]+>$/
32
+ const MEDIA_TYPE = /^[A-Za-z0-9][\w!#$&^.+-]*\/[A-Za-z0-9][\w!#$&^.+-]*$/
33
+
34
+ function base64Lines(data: Uint8Array): string {
35
+ const text = Buffer.from(data).toString("base64")
36
+ const lines: string[] = []
37
+ for (let index = 0; index < text.length; index += 76) lines.push(text.slice(index, index + 76))
38
+ return lines.join(CRLF)
39
+ }
40
+
41
+ /** RFC 2047 encoded words of at most 45 bytes each, never splitting a character. */
42
+ function encodedWords(text: string): string {
43
+ const words: string[] = []
44
+ let chunk = ""
45
+ for (const char of text) {
46
+ if (Buffer.byteLength(chunk + char) > 45) {
47
+ words.push(chunk)
48
+ chunk = ""
49
+ }
50
+ chunk += char
51
+ }
52
+ if (chunk !== "" || words.length === 0) words.push(chunk)
53
+ return words.map((word) => `=?UTF-8?B?${Buffer.from(word).toString("base64")}?=`).join(`${CRLF} `)
54
+ }
55
+
56
+ /** Unstructured header text (Subject): as is when plain ASCII, else encoded. */
57
+ export function headerText(text: string): string {
58
+ return ASCII_TEXT.test(text) && text.length <= 900 ? text : encodedWords(text)
59
+ }
60
+
61
+ function displayName(name: string): string {
62
+ if (!ASCII_TEXT.test(name)) return encodedWords(name)
63
+ return ATOM_TEXT.test(name) ? name : `"${name.replace(/(["\\])/g, "\\$1")}"`
64
+ }
65
+
66
+ export function mailboxHeader(mailbox: Mailbox): string {
67
+ return mailbox.name === undefined
68
+ ? mailbox.address
69
+ : `${displayName(mailbox.name)} <${mailbox.address}>`
70
+ }
71
+
72
+ function addressHeader(name: string, list: readonly Mailbox[]): string[] {
73
+ return list.length === 0 ? [] : [`${name}: ${list.map(mailboxHeader).join(`,${CRLF} `)}`]
74
+ }
75
+
76
+ /** RFC 2231 parameter value of a file name. */
77
+ function fileParameter(name: string, filename: string): string {
78
+ if (ASCII_TEXT.test(filename) && !/["\\]/.test(filename)) return `${name}="${filename}"`
79
+ return `${name}*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)}`
80
+ }
81
+
82
+ const textPart = (body: string) =>
83
+ [
84
+ 'Content-Type: text/plain; charset="UTF-8"',
85
+ "Content-Transfer-Encoding: base64",
86
+ "",
87
+ base64Lines(Buffer.from(body.replace(/\r?\n/g, CRLF), "utf8")),
88
+ ].join(CRLF)
89
+
90
+ function attachmentPart(attachment: MimeAttachment): string {
91
+ if (!MEDIA_TYPE.test(attachment.mimeType)) {
92
+ throw new Error(`"${attachment.mimeType}" is not a media type`)
93
+ }
94
+ return [
95
+ `Content-Type: ${attachment.mimeType}; ${fileParameter("name", attachment.filename)}`,
96
+ `Content-Disposition: attachment; ${fileParameter("filename", attachment.filename)}`,
97
+ "Content-Transfer-Encoding: base64",
98
+ "",
99
+ base64Lines(attachment.data),
100
+ ].join(CRLF)
101
+ }
102
+
103
+ /** The message as sent (CRLF line ends). */
104
+ export function buildMime(message: MimeMessage): string {
105
+ for (const id of [message.inReplyTo, ...(message.references ?? [])]) {
106
+ if (id !== undefined && !MESSAGE_ID.test(id)) throw new Error(`"${id}" is not a Message-ID`)
107
+ }
108
+ const headers = [
109
+ `From: ${mailboxHeader(message.from)}`,
110
+ ...addressHeader("To", message.to),
111
+ ...addressHeader("Cc", message.cc),
112
+ ...addressHeader("Bcc", message.bcc),
113
+ `Subject: ${headerText(message.subject)}`,
114
+ ...(message.inReplyTo === undefined ? [] : [`In-Reply-To: ${message.inReplyTo}`]),
115
+ ...(message.references === undefined || message.references.length === 0
116
+ ? []
117
+ : [`References: ${message.references.join(`${CRLF} `)}`]),
118
+ "MIME-Version: 1.0",
119
+ ]
120
+ if (message.attachments.length === 0) return [...headers, textPart(message.body)].join(CRLF)
121
+ const digest = createHash("sha256").update(message.body)
122
+ for (const attachment of message.attachments)
123
+ digest.update(attachment.filename).update(attachment.data)
124
+ const boundary = `=_dsh_${digest.digest("hex").slice(0, 32)}`
125
+ const parts = [textPart(message.body), ...message.attachments.map(attachmentPart)]
126
+ return [
127
+ ...headers,
128
+ `Content-Type: multipart/mixed; boundary="${boundary}"`,
129
+ "",
130
+ ...parts.flatMap((part) => [`--${boundary}`, part]),
131
+ `--${boundary}--`,
132
+ "",
133
+ ].join(CRLF)
134
+ }
135
+
136
+ /** base64url without padding, as Gmail's `raw` takes a message. */
137
+ export function rawOf(mime: string): string {
138
+ return Buffer.from(mime, "utf8").toString("base64url")
139
+ }