import { GOOGLE_ACCOUNTS, resolveGoogleAccount, type GoogleAccountAlias } from './accounts.ts' import { requestGoogle } from './core.ts' import { decodeBase64UrlToBytes, decodeUtf8Base64Url } from './gmail-mime.ts' import { GMAIL_HEX_ID, parseGmailUrl } from './gmail-url.ts' import type { JsonObject } from './types.ts' export type GetEmailContextParams = { /** Gmail web link (any `mail.google.com` form with a thread or message id), or a bare thread / message id. */ url: string /** Account alias. Overrides the account implied by the link's `authuser`. */ account?: string /** Max characters of body text per message. Defaults to 4000. */ maxBodyChars?: number } export type EmailContextParticipant = { name: string | null; email: string } export type EmailContextAttachment = { filename: string; mimeType: string; size: number; attachmentId: string } export type EmailContextMessage = { id: string date: string | null from: string | null to: string[] cc: string[] subject: string snippet: string /** Plain text body. Falls back to HTML converted to text. */ body: string bodySource: 'text/plain' | 'text/html' | 'none' /** Full body length (after quote trimming) before truncation. */ bodyLength: number truncated: boolean /** True when a trailing quoted reply was removed from the body. */ quotedTrimmed: boolean attachments: EmailContextAttachment[] } export type EmailContext = { account: GoogleAccountAlias threadId: string /** Message id the input pointed at, when it was a message rather than a thread. */ requestedMessageId: string | null link: string subject: string participants: EmailContextParticipant[] labels: string[] messageCount: number messages: EmailContextMessage[] } export type GmailContextErrorStep = 'input' | 'url' | 'account' | 'auth' | 'not_found' | 'request' /** Thrown by `getEmailContext`. `step` names the stage that failed. */ export class GmailContextError extends Error { step: GmailContextErrorStep status?: number constructor(step: GmailContextErrorStep, message: string, details: { status?: number; cause?: unknown } = {}) { super('getEmailContext failed at ' + step + ': ' + message) this.name = 'GmailContextError' this.step = step if (details.status !== undefined) this.status = details.status if (details.cause !== undefined) (this as { cause?: unknown }).cause = details.cause } } export const DEFAULT_EMAIL_CONTEXT_MAX_BODY_CHARS = 4000 const GMAIL_ACCOUNT_ORDER: GoogleAccountAlias[] = ['business', 'personal'] const REDUCED_CHARSET = 'BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz' const BASE64_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' const REDUCED_TOKEN = /^[BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz]{16,}$/ export type EmailContextTarget = { /** Id to try as a thread first, then as a message. */ id: string /** Known thread id (when the link carried both thread and message ids). */ threadId: string | null /** Known message id. */ messageId: string | null /** `authuser` from the link (email or index), when present. */ authuser: string | null } function rebase(token: string, from: string, to: string): string { let n = 0n const fromBase = BigInt(from.length) const toBase = BigInt(to.length) for (const char of token) n = n * fromBase + BigInt(from.indexOf(char)) let out = '' while (n > 0n) { out = to[Number(n % toBase)] + out n /= toBase } return out } /** * Decode a legacy reduced-charset Gmail view token (for example `QgrcJ...` or * `Ktbx...`) into a hex Gmail API id. Returns null when the token does not * decode to a thread or message reference. `FMfcgz...` sync ids are keyed per * account on Google's side and never decode here. */ export function decodeGmailViewToken(token: string): { threadId: string | null; messageId: string | null } | null { if (!REDUCED_TOKEN.test(token) || token.startsWith('FMfcg')) return null try { const b64 = rebase(token, REDUCED_CHARSET, BASE64_CHARSET) const text = decodeUtf8Base64Url(b64) const toHex = (match: RegExpExecArray | null) => (match ? BigInt(match[1]).toString(16) : null) const messageId = toHex(/msg-[af]:r?-?(\d{6,})/.exec(text)) // A leading "thread-" can be lost to leading zeros, so accept a bare "f:" / "a:r-" reference too. const threadId = toHex(/thread-[af]:r?-?(\d{6,})/.exec(text)) ?? (messageId ? null : toHex(/[af]:r?-?(\d{6,})/.exec(text))) if (!threadId && !messageId) return null return { threadId, messageId } } catch { return null } } function fmfcgError(): GmailContextError { return new GmailContextError( 'url', 'this link uses a Gmail "FMfcgz..." sync id, which Google encrypts per account and the Gmail API cannot resolve. Use a link with a hex id (for example .../#all/) or pass the Gmail thread or message id.', ) } function lastHashToken(url: URL): string | null { const hash = url.hash.replace(/^#/, '').split('?')[0] const segments = hash.split('/').filter(Boolean) return segments.length > 1 ? decodeURIComponent(segments[segments.length - 1]) : null } /** Resolve a Gmail link or bare id into the id to look up plus any `authuser`. */ export function resolveEmailContextTarget(input: string): EmailContextTarget { const raw = String(input ?? '').trim() if (!raw) throw new GmailContextError('input', 'url is required (a Gmail link or a thread / message id).') if (GMAIL_HEX_ID.test(raw)) return { id: raw.toLowerCase(), threadId: null, messageId: null, authuser: null } if (/^FMfcg/.test(raw)) throw fmfcgError() if (REDUCED_TOKEN.test(raw)) { const decoded = decodeGmailViewToken(raw) if (decoded) return fromDecoded(decoded, null) } let parsedUrl: URL try { parsedUrl = new URL(raw) } catch { throw new GmailContextError('url', 'not a Gmail link or Gmail id: "' + raw.slice(0, 200) + '".') } if (!(parsedUrl.hostname === 'mail.google.com' || parsedUrl.hostname.endsWith('.mail.google.com'))) { throw new GmailContextError('url', 'expected a mail.google.com link, got host "' + parsedUrl.hostname + '".') } const info = parseGmailUrl(raw) const authuser = info.authuser ?? null if ((info.kind === 'thread' || info.kind === 'message') && info.id) { return { id: info.id.toLowerCase(), threadId: info.threadId ? info.threadId.toLowerCase() : null, messageId: info.kind === 'message' && info.messageId ? info.messageId.toLowerCase() : null, authuser, } } // Query-string forms: ?th=, ?permthid=thread-f:, ?permmsgid= or ?simpl=msg-f: const th = parsedUrl.searchParams.get('th') if (th && GMAIL_HEX_ID.test(th)) return { id: th.toLowerCase(), threadId: null, messageId: null, authuser } const decimal = (value: string | null) => { const match = value ? /[af]:r?-?(\d{6,})/.exec(value) : null return match ? BigInt(match[1]).toString(16) : null } const permThread = decimal(parsedUrl.searchParams.get('permthid')) const permMessage = decimal(parsedUrl.searchParams.get('permmsgid') ?? parsedUrl.searchParams.get('simpl')) if (permThread || permMessage) return fromDecoded({ threadId: permThread, messageId: permMessage }, authuser) const token = lastHashToken(parsedUrl) if (token && /^FMfcg/.test(token)) throw fmfcgError() if (token) { const decoded = decodeGmailViewToken(token) if (decoded) return fromDecoded(decoded, authuser) } throw new GmailContextError('url', 'could not find a thread or message id in "' + raw.slice(0, 200) + '".') } function fromDecoded(decoded: { threadId: string | null; messageId: string | null }, authuser: string | null): EmailContextTarget { const id = (decoded.messageId ?? decoded.threadId) as string return { id, threadId: decoded.threadId, messageId: decoded.messageId, authuser } } function gmailAccounts(): GoogleAccountAlias[] { return GMAIL_ACCOUNT_ORDER.filter((alias) => GOOGLE_ACCOUNTS[alias].products.includes('gmail')) } /** Accounts to try, in order. Explicit account wins, then a known `authuser` email, then every Gmail account. */ export function resolveEmailContextAccounts(account: string | undefined, authuser: string | null): GoogleAccountAlias[] { if (account) { try { return [resolveGoogleAccount(account).account] } catch (error) { throw new GmailContextError('account', error instanceof Error ? error.message : String(error)) } } if (authuser && authuser.includes('@')) { const match = gmailAccounts().find((alias) => GOOGLE_ACCOUNTS[alias].emailHint?.toLowerCase() === authuser.toLowerCase()) if (match) return [match] } return gmailAccounts() } // --------------------------------------------------------------------------- // MIME / text helpers // --------------------------------------------------------------------------- type GmailPart = { partId?: string mimeType?: string filename?: string headers?: Array<{ name?: string; value?: string }> body?: { data?: string; size?: number; attachmentId?: string } parts?: GmailPart[] } function partHeader(part: GmailPart, name: string): string { const lower = name.toLowerCase() return (part.headers ?? []).find((h) => String(h.name ?? '').toLowerCase() === lower)?.value ?? '' } function isAttachmentPart(part: GmailPart): boolean { if (part.filename) return true return /^\s*attachment/i.test(partHeader(part, 'Content-Disposition')) } /** Decode a Gmail Base64URL part body using its declared charset (UTF-8 by default). */ export function decodePartBody(part: GmailPart): string { const data = part.body?.data if (!data) return '' const charset = (/charset\s*=\s*"?([^";\s]+)"?/i.exec(partHeader(part, 'Content-Type'))?.[1] ?? 'utf-8').toLowerCase() if (charset === 'utf-8' || charset === 'utf8' || charset === 'us-ascii') return decodeUtf8Base64Url(data) try { return new TextDecoder(charset).decode(decodeBase64UrlToBytes(data)) } catch { return decodeUtf8Base64Url(data) } } function collectTextParts(part: GmailPart | undefined, mimeType: string, out: GmailPart[]): void { if (!part) return if (part.mimeType === mimeType && !isAttachmentPart(part) && part.body?.data) out.push(part) for (const child of part.parts ?? []) collectTextParts(child, mimeType, out) } export function collectAttachments(part: GmailPart | undefined, out: EmailContextAttachment[] = []): EmailContextAttachment[] { if (!part) return out if (part.body?.attachmentId && part.filename) { out.push({ filename: part.filename, mimeType: part.mimeType ?? 'application/octet-stream', size: Number(part.body.size ?? 0), attachmentId: part.body.attachmentId, }) } for (const child of part.parts ?? []) collectAttachments(child, out) return out } const NAMED_ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d', hellip: '\u2026', copy: '\u00a9', reg: '\u00ae', trade: '\u2122', bull: '\u2022', middot: '\u00b7', zwnj: '', zwj: '', shy: '', } export function decodeHtmlEntities(text: string): string { return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, entity: string) => { if (entity[0] === '#') { const code = entity[1] === 'x' || entity[1] === 'X' ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10) try { return Number.isFinite(code) ? String.fromCodePoint(code) : whole } catch { return whole } } const named = NAMED_ENTITIES[entity.toLowerCase()] return named === undefined ? whole : named }) } /** Convert an HTML body to readable plain text. */ export function htmlToText(html: string): string { const text = html .replace(//g, '') .replace(/<(head|style|script|title)\b[^>]*>[\s\S]*?<\/\1>/gi, '') .replace(//gi, '\n') .replace(/]*>/gi, '\n- ') .replace(/<\/(p|div|tr|li|ul|ol|table|h[1-6]|blockquote|section|article|header|footer)>/gi, '\n') .replace(/<(p|h[1-6])\b[^>]*>/gi, '\n') .replace(/<\/t[dh]>/gi, ' ') .replace(/<[^>]+>/g, '') return normalizeWhitespace(decodeHtmlEntities(text)) } function normalizeWhitespace(text: string): string { return text .replace(/\r\n?/g, '\n') .split('\n') .map((line) => line.replace(/[ \t\u00a0]+/g, ' ').trimEnd()) .join('\n') .replace(/\n{3,}/g, '\n\n') .trim() } const HTML_QUOTE_MARKERS = [/]*class="?[^">]*gmail_quote/i, /]*type="?cite/i, /]*id="?appendonsend/i, /]*id="?divRplyFwdMsg/i] /** Remove a trailing quoted reply from HTML when a well-known marker is present. */ export function trimQuotedHtml(html: string): { html: string; trimmed: boolean } { let cut = -1 for (const marker of HTML_QUOTE_MARKERS) { const match = marker.exec(html) if (match && (cut === -1 || match.index < cut)) cut = match.index } if (cut <= 0) return { html, trimmed: false } const kept = html.slice(0, cut) if (!htmlToText(kept)) return { html, trimmed: false } return { html: kept, trimmed: true } } /** Remove a trailing quoted reply from plain text when a well-known marker is present. */ export function trimQuotedText(text: string): { text: string; trimmed: boolean } { const lines = text.replace(/\r\n?/g, '\n').split('\n') let cut = -1 for (let i = 0; i < lines.length; i++) { const line = lines[i].trim() const next = (lines[i + 1] ?? '').trim() if (/^On\b.{0,300}\bwrote:$/.test(line) || (/^On\b/.test(line) && !/wrote:$/.test(line) && /wrote:$/.test(next) && (line + ' ' + next).length < 400)) { cut = i; break } if (/^-{2,}\s*Original Message\s*-{2,}$/i.test(line)) { cut = i; break } if (/^_{10,}$/.test(line) && /^From:/i.test(next)) { cut = i; break } if (line.startsWith('>') && lines.slice(i).every((rest) => !rest.trim() || rest.trim().startsWith('>'))) { cut = i; break } } if (cut <= 0) return { text, trimmed: false } const kept = lines.slice(0, cut).join('\n').trim() if (!kept) return { text, trimmed: false } return { text: kept, trimmed: true } } /** Extract a message body as plain text, preferring text/plain and falling back to HTML. */ export function extractMessageBody(payload: GmailPart | undefined): { body: string; source: 'text/plain' | 'text/html' | 'none'; quotedTrimmed: boolean } { const plainParts: GmailPart[] = [] collectTextParts(payload, 'text/plain', plainParts) if (plainParts.length > 0) { const plain = normalizeWhitespace(plainParts.map(decodePartBody).join('\n\n')) if (plain) { const trimmed = trimQuotedText(plain) return { body: trimmed.text, source: 'text/plain', quotedTrimmed: trimmed.trimmed } } } const htmlParts: GmailPart[] = [] collectTextParts(payload, 'text/html', htmlParts) if (htmlParts.length > 0) { const html = htmlParts.map(decodePartBody).join('\n') const trimmed = trimQuotedHtml(html) return { body: htmlToText(trimmed.html), source: 'text/html', quotedTrimmed: trimmed.trimmed } } return { body: '', source: 'none', quotedTrimmed: false } } /** Split an address header on commas that are outside quotes and angle brackets. */ export function parseAddressList(header: string): EmailContextParticipant[] { const out: EmailContextParticipant[] = [] let current = '' let inQuotes = false let inAngle = false const flush = () => { const entry = current.trim() current = '' if (!entry) return const angle = /^(.*?)<([^>]+)>\s*$/.exec(entry) if (angle) { const name = angle[1].trim().replace(/^"|"$/g, '').replace(/\\"/g, '"').trim() out.push({ name: name || null, email: angle[2].trim() }) } else if (entry.includes('@')) { out.push({ name: null, email: entry.replace(/^"|"$/g, '') }) } } for (let i = 0; i < header.length; i++) { const char = header[i] if (char === '\\' && inQuotes) { current += char + (header[i + 1] ?? ''); i++; continue } if (char === '"') inQuotes = !inQuotes else if (char === '<' && !inQuotes) inAngle = true else if (char === '>' && !inQuotes) inAngle = false if (char === ',' && !inQuotes && !inAngle) { flush(); continue } current += char } flush() return out } function formatParticipant(p: EmailContextParticipant): string { return p.name ? p.name + ' <' + p.email + '>' : p.email } function messageDate(message: JsonObject, payload: GmailPart | undefined): string | null { const internal = Number(message.internalDate) if (Number.isFinite(internal) && internal > 0) return new Date(internal).toISOString() const parsed = Date.parse(payload ? partHeader(payload, 'Date') : '') return Number.isNaN(parsed) ? null : new Date(parsed).toISOString() } export function summarizeMessage(message: JsonObject, maxBodyChars: number): EmailContextMessage { const payload = message.payload as GmailPart | undefined const header = (name: string) => (payload ? partHeader(payload, name) : '') const fromList = parseAddressList(header('From')) const extracted = extractMessageBody(payload) const truncated = extracted.body.length > maxBodyChars return { id: String(message.id ?? ''), date: messageDate(message, payload), from: fromList[0] ? formatParticipant(fromList[0]) : header('From') || null, to: parseAddressList(header('To')).map(formatParticipant), cc: parseAddressList(header('Cc')).map(formatParticipant), subject: header('Subject'), snippet: decodeHtmlEntities(String(message.snippet ?? '')), body: truncated ? extracted.body.slice(0, maxBodyChars) : extracted.body, bodySource: extracted.source, bodyLength: extracted.body.length, truncated, quotedTrimmed: extracted.quotedTrimmed, attachments: collectAttachments(payload), } } function collectParticipants(messages: JsonObject[]): EmailContextParticipant[] { const byEmail = new Map() for (const message of messages) { const payload = message.payload as GmailPart | undefined if (!payload) continue for (const name of ['From', 'To', 'Cc']) { for (const p of parseAddressList(partHeader(payload, name))) { const key = p.email.toLowerCase() const existing = byEmail.get(key) if (!existing) byEmail.set(key, { name: p.name, email: p.email }) else if (!existing.name && p.name) existing.name = p.name } } } return [...byEmail.values()] } function buildLink(threadId: string, account: GoogleAccountAlias, authuser: string | null): string { const user = authuser && authuser.includes('@') ? authuser : GOOGLE_ACCOUNTS[account].emailHint return 'https://mail.google.com/mail/' + (user ? '?authuser=' + encodeURIComponent(user).replace(/%40/g, '@') : 'u/0/') + '#all/' + threadId } // --------------------------------------------------------------------------- // Fetching // --------------------------------------------------------------------------- function errorStatus(error: unknown): number | undefined { const status = (error as { status?: unknown } | null)?.status return typeof status === 'number' ? status : undefined } function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error) } function isAuthError(error: unknown): boolean { const status = errorStatus(error) if (status === 401 || status === 403) return true return status === undefined && /authenticat|oauth|credential|integration/i.test(errorMessage(error)) } function isMissing(error: unknown): boolean { const status = errorStatus(error) return status === 404 || status === 400 } type GmailGet = (path: string, query?: Record) => Promise async function loadThread(get: GmailGet, target: EmailContextTarget): Promise<{ thread: JsonObject; requestedMessageId: string | null } | null> { const getThread = (id: string) => get('/gmail/v1/users/me/threads/' + encodeURIComponent(id), { format: 'full' }) const threadFirst = target.threadId ?? target.id try { const thread = await getThread(threadFirst) return { thread, requestedMessageId: target.messageId } } catch (error) { if (!isMissing(error)) throw error } const messageId = target.messageId ?? target.id let message: JsonObject try { message = await get('/gmail/v1/users/me/messages/' + encodeURIComponent(messageId), { format: 'minimal' }) } catch (error) { if (isMissing(error)) return null throw error } const threadId = typeof message.threadId === 'string' ? message.threadId : null if (!threadId) return null return { thread: await getThread(threadId), requestedMessageId: messageId } } async function labelNames(get: GmailGet, ids: string[]): Promise { if (ids.length === 0) return [] try { const listed = (await get('/gmail/v1/users/me/labels')) as { labels?: Array<{ id?: string; name?: string }> } const names = new Map((listed.labels ?? []).map((label) => [String(label.id), String(label.name ?? label.id)])) return ids.map((id) => names.get(id) ?? id) } catch { return ids } } /** * Read-only: resolve a Gmail web link (or a bare thread / message id) to compact * thread context in one call. Tries the id as a thread first, then as a message id. * Account comes from `account`, else the link's `authuser` email, else each Gmail * account in turn. Throws {@link GmailContextError} with `step` set to `input`, * `url`, `account`, `auth`, `not_found`, or `request`. * @param params.url - Gmail link (`#all/`, `#inbox/`, `#label/x/`, `/u/0/` forms, legacy view tokens) or a hex id. * @param params.account - Optional account alias that overrides the link's `authuser`. * @param params.maxBodyChars - Max body characters per message (default 4000). `truncated` marks cut bodies. * @example * import { getEmailContext } from 'kody:@kentcdodds/google/gmail' * const context = await getEmailContext({ url: 'https://mail.google.com/mail/u/0/#inbox/1a2b3c4d5e6f7a8b' }) * // => { account, threadId, link, subject, participants, labels, messageCount, messages: [{ id, date, from, to, cc, subject, snippet, body, truncated, attachments }] } */ export async function getEmailContext(params: GetEmailContextParams): Promise { if (!params || typeof params !== 'object') throw new GmailContextError('input', 'pass { url, account?, maxBodyChars? }.') const maxBodyChars = params.maxBodyChars ?? DEFAULT_EMAIL_CONTEXT_MAX_BODY_CHARS if (typeof maxBodyChars !== 'number' || !Number.isFinite(maxBodyChars) || maxBodyChars < 0) { throw new GmailContextError('input', 'maxBodyChars must be a non-negative number.') } const target = resolveEmailContextTarget(params.url) const accounts = resolveEmailContextAccounts(params.account, target.authuser) const authFailures: string[] = [] for (const account of accounts) { const get: GmailGet = async (path, query) => (await requestGoogle({ account, api: 'gmail', path, query })) as JsonObject let loaded: Awaited> try { loaded = await loadThread(get, target) } catch (error) { if (isAuthError(error)) { authFailures.push(account + ': ' + errorMessage(error)) continue } throw new GmailContextError('request', 'Gmail request failed for account "' + account + '": ' + errorMessage(error), { status: errorStatus(error), cause: error }) } if (!loaded) continue const { thread, requestedMessageId } = loaded const messages = (Array.isArray(thread.messages) ? thread.messages : []) as JsonObject[] const threadId = String(thread.id ?? messages[0]?.threadId ?? target.id) const labelIds: string[] = [] for (const message of messages) { for (const id of (message.labelIds ?? []) as string[]) if (!labelIds.includes(id)) labelIds.push(id) } const summaries = messages.map((message) => summarizeMessage(message, maxBodyChars)) return { account, threadId, requestedMessageId, link: buildLink(threadId, account, target.authuser), subject: summaries[0]?.subject ?? '', participants: collectParticipants(messages), labels: await labelNames(get, labelIds), messageCount: messages.length, messages: summaries, } } if (authFailures.length === accounts.length) { throw new GmailContextError('auth', 'could not read Gmail (' + authFailures.join('; ') + '). Reconnect the OAuth integration at /connect/oauth.') } throw new GmailContextError( 'not_found', 'no thread or message "' + target.id + '" in account(s) ' + accounts.filter((a) => !authFailures.some((f) => f.startsWith(a + ':'))).join(', ') + (authFailures.length ? ' (auth failed for ' + authFailures.join('; ') + ')' : '') + (params.account ? '' : '. Pass account to pick one explicitly.'), ) }