import assert from 'node:assert/strict' import { afterEach, describe, it } from 'node:test' import { DEFAULT_EMAIL_CONTEXT_MAX_BODY_CHARS, GmailContextError, decodeGmailViewToken, extractMessageBody, parseAddressList, resolveEmailContextAccounts, resolveEmailContextTarget, trimQuotedText, } from './gmail-context.ts' import gmail, { getEmailContext } from './gmail.ts' const b64url = (text: string, encoding: BufferEncoding = 'utf8') => Buffer.from(text, encoding).toString('base64url') type Call = { method: string; path: string; search: URLSearchParams; credential: string } type Route = (call: Call) => { status: number; body?: unknown } | undefined function mockFetch(route: Route) { const calls: Call[] = [] ;(globalThis as { __kodyTestFetch?: unknown }).__kodyTestFetch = async (input: string, init: RequestInit = {}, credential: string) => { const url = new URL(String(input)) const call = { method: String(init.method ?? 'GET'), path: url.pathname, search: url.searchParams, credential } calls.push(call) const result = route(call) ?? { status: 404, body: { error: { code: 404, message: 'Requested entity was not found.' } } } return new Response(result.body === undefined ? null : JSON.stringify(result.body), { status: result.status, headers: { 'content-type': 'application/json' }, }) } return calls } afterEach(() => { delete (globalThis as { __kodyTestFetch?: unknown }).__kodyTestFetch }) function headers(map: Record) { return Object.entries(map).map(([name, value]) => ({ name, value })) } const THREAD_ID = '1a17f2eb6b61c9c3' const SECOND_ID = '1a17f3000000abcd' function threadFixture() { return { id: THREAD_ID, messages: [ { id: THREAD_ID, threadId: THREAD_ID, labelIds: ['INBOX', 'Label_7'], internalDate: '1761600000000', snippet: 'Hi Kent, here's the plan', payload: { mimeType: 'multipart/mixed', headers: headers({ From: '"Ada Lovelace" ', To: 'Kent C. Dodds , "Doe, Jane" ', Cc: 'ada@example.com', Subject: 'Plan \u2013 caf\u00e9 \ud83c\udf89', }), parts: [ { mimeType: 'multipart/alternative', parts: [ { mimeType: 'text/plain', headers: headers({ 'Content-Type': 'text/plain; charset="UTF-8"' }), body: { data: b64url('Hi Kent \u2013 caf\u00e9 \ud83c\udf89\n\nSee attached.') } }, { mimeType: 'text/html', headers: headers({ 'Content-Type': 'text/html; charset="UTF-8"' }), body: { data: b64url('
ignored html
') } }, ], }, { mimeType: 'application/pdf', filename: 'plan.pdf', headers: headers({ 'Content-Disposition': 'attachment; filename="plan.pdf"' }), body: { attachmentId: 'att-1', size: 1234 } }, ], }, }, { id: SECOND_ID, threadId: THREAD_ID, labelIds: ['INBOX', 'SENT'], internalDate: '1761603600000', snippet: 'Sounds good', payload: { mimeType: 'text/html', headers: headers({ From: 'Kent C. Dodds ', To: 'Ada ', Subject: 'Re: Plan' }), body: { data: b64url('

Sounds good & thanks!

On Mon, Ada wrote:
old stuff
'), }, }, }, ], } } const labelsFixture = { labels: [{ id: 'INBOX', name: 'INBOX' }, { id: 'SENT', name: 'SENT' }, { id: 'Label_7', name: 'Projects/Alpha' }] } describe('resolveEmailContextTarget URL forms', () => { it('parses authuser + #all/', () => { assert.deepEqual(resolveEmailContextTarget('https://mail.google.com/mail?authuser=me@kentcdodds.com#all/1a17f2eb6b61c9c3'), { id: THREAD_ID, threadId: THREAD_ID, messageId: null, authuser: 'me@kentcdodds.com', }) }) it('parses /u/0/ #inbox, #label, #search, and thread/message forms', () => { assert.equal(resolveEmailContextTarget('https://mail.google.com/mail/u/0/#inbox/1a17f2eb6b61c9c3').id, THREAD_ID) assert.equal(resolveEmailContextTarget('https://mail.google.com/mail/u/1/#label/Projects%2FAlpha/1a17f2eb6b61c9c3').id, THREAD_ID) assert.equal(resolveEmailContextTarget('https://mail.google.com/mail/u/0/#search/from%3Aada/1a17f2eb6b61c9c3').id, THREAD_ID) const both = resolveEmailContextTarget('https://mail.google.com/mail/u/0/#inbox/1a17f2eb6b61c9c3/1a17f3000000abcd') assert.deepEqual([both.threadId, both.messageId], [THREAD_ID, SECOND_ID]) }) it('accepts bare hex ids and query-string forms', () => { assert.equal(resolveEmailContextTarget(' 1A17F2EB6B61C9C3 ').id, THREAD_ID) assert.equal(resolveEmailContextTarget('https://mail.google.com/mail/u/0/?th=1a17f2eb6b61c9c3').id, THREAD_ID) const perm = resolveEmailContextTarget('https://mail.google.com/mail/u/0/?view=pt&permthid=thread-f:' + BigInt('0x' + THREAD_ID) + '&simpl=msg-f:' + BigInt('0x' + SECOND_ID)) assert.deepEqual([perm.threadId, perm.messageId], [THREAD_ID, SECOND_ID]) }) it('decodes legacy reduced-charset view tokens', () => { assert.deepEqual(decodeGmailViewToken('QgrcJHrhvXXVhMKdgvFSRvHcMBTKbNVfRtL'), { threadId: '120a32474e2064ce', messageId: null }) assert.equal(resolveEmailContextTarget('https://mail.google.com/mail/u/0/#inbox/QgrcJHrhvXXVhMKdgvFSRvHcMBTKbNVfRtL').id, '120a32474e2064ce') }) it('throws url errors for FMfcgz sync ids, other hosts, and links without ids', () => { const step = (fn: () => unknown, expected: string) => assert.throws(fn, (error: unknown) => error instanceof GmailContextError && error.step === expected) step(() => resolveEmailContextTarget('https://mail.google.com/mail/u/0/#inbox/FMfcgzQgLjNPlfJCVRfnNkPGkLhWClCW'), 'url') step(() => resolveEmailContextTarget('FMfcgzQgLjNPlfJCVRfnNkPGkLhWClCW'), 'url') step(() => resolveEmailContextTarget('https://example.com/#all/1a17f2eb6b61c9c3'), 'url') step(() => resolveEmailContextTarget('https://mail.google.com/mail/u/0/#inbox'), 'url') step(() => resolveEmailContextTarget('not a link'), 'url') step(() => resolveEmailContextTarget(''), 'input') }) }) describe('resolveEmailContextAccounts', () => { it('maps authuser emails, lets account override, and falls back to every Gmail account', () => { assert.deepEqual(resolveEmailContextAccounts(undefined, 'me@kentcdodds.com'), ['business']) assert.deepEqual(resolveEmailContextAccounts(undefined, 'Kent.C.Dodds@gmail.com'), ['personal']) assert.deepEqual(resolveEmailContextAccounts('personal', 'me@kentcdodds.com'), ['personal']) assert.deepEqual(resolveEmailContextAccounts(undefined, '0'), ['business', 'personal']) assert.throws(() => resolveEmailContextAccounts('nope', null), (e: unknown) => e instanceof GmailContextError && e.step === 'account') }) }) describe('MIME body extraction', () => { it('decodes UTF-8 text/plain and prefers it over HTML', () => { const out = extractMessageBody(threadFixture().messages[0].payload) assert.equal(out.source, 'text/plain') assert.equal(out.body, 'Hi Kent \u2013 caf\u00e9 \ud83c\udf89\n\nSee attached.') }) it('honors a non-UTF-8 charset', () => { const out = extractMessageBody({ mimeType: 'text/plain', headers: headers({ 'Content-Type': 'text/plain; charset=iso-8859-1' }), body: { data: b64url('caf\u00e9', 'latin1') } }) assert.equal(out.body, 'caf\u00e9') }) it('falls back to HTML converted to text and trims a gmail_quote block', () => { const out = extractMessageBody(threadFixture().messages[1].payload) assert.deepEqual(out, { body: 'Sounds good & thanks!', source: 'text/html', quotedTrimmed: true }) }) it('trims simple plain-text quotes but keeps text that is only a quote', () => { assert.deepEqual(trimQuotedText('Thanks!\n\nOn Mon, Oct 26, 2026 at 9:00 AM Ada wrote:\n> hello'), { text: 'Thanks!', trimmed: true }) assert.deepEqual(trimQuotedText('Yes.\n\nOn Mon, Oct 26, 2026 at 9:00 AM Ada Lovelace <\nada@example.com> wrote:\n> hi'), { text: 'Yes.', trimmed: true }) assert.deepEqual(trimQuotedText('Inline > not a quote\n> quoted\n> more'), { text: 'Inline > not a quote', trimmed: true }) assert.deepEqual(trimQuotedText('> only quoted'), { text: '> only quoted', trimmed: false }) assert.deepEqual(trimQuotedText('a\n> inline answer\nb'), { text: 'a\n> inline answer\nb', trimmed: false }) }) it('parses address lists with quoted commas', () => { assert.deepEqual(parseAddressList('"Doe, Jane" , bob@example.com'), [ { name: 'Doe, Jane', email: 'jane@example.com' }, { name: null, email: 'bob@example.com' }, ]) }) }) describe('getEmailContext', () => { it('returns compact thread context for a link (read-only GETs on the authuser account)', async () => { const calls = mockFetch(({ path }) => { if (path === '/gmail/v1/users/me/threads/' + THREAD_ID) return { status: 200, body: threadFixture() } if (path === '/gmail/v1/users/me/labels') return { status: 200, body: labelsFixture } }) const context = await getEmailContext({ url: 'https://mail.google.com/mail?authuser=me@kentcdodds.com#all/' + THREAD_ID }) assert.ok(calls.every((call) => call.method === 'GET' && call.credential === 'google-business')) assert.equal(calls[0].search.get('format'), 'full') assert.equal(context.account, 'business') assert.equal(context.threadId, THREAD_ID) assert.equal(context.requestedMessageId, null) assert.equal(context.link, 'https://mail.google.com/mail/?authuser=me@kentcdodds.com#all/' + THREAD_ID) assert.equal(context.subject, 'Plan \u2013 caf\u00e9 \ud83c\udf89') assert.equal(context.messageCount, 2) assert.deepEqual(context.labels, ['INBOX', 'Projects/Alpha', 'SENT']) assert.deepEqual(context.participants, [ { name: 'Ada Lovelace', email: 'ada@example.com' }, { name: 'Kent C. Dodds', email: 'me@kentcdodds.com' }, { name: 'Doe, Jane', email: 'jane@example.com' }, ]) const [first, second] = context.messages assert.equal(first.date, new Date(1761600000000).toISOString()) assert.equal(first.from, 'Ada Lovelace ') assert.deepEqual(first.to, ['Kent C. Dodds ', 'Doe, Jane ']) assert.deepEqual(first.cc, ['ada@example.com']) assert.equal(first.snippet, "Hi Kent, here's the plan") assert.equal(first.truncated, false) assert.deepEqual(first.attachments, [{ filename: 'plan.pdf', mimeType: 'application/pdf', size: 1234, attachmentId: 'att-1' }]) assert.equal(second.body, 'Sounds good & thanks!') assert.equal(second.quotedTrimmed, true) assert.equal(gmail().getEmailContext, getEmailContext) assert.equal(DEFAULT_EMAIL_CONTEXT_MAX_BODY_CHARS, 4000) }) it('truncates bodies to maxBodyChars', async () => { mockFetch(({ path }) => { if (path.endsWith('/threads/' + THREAD_ID)) return { status: 200, body: threadFixture() } if (path.endsWith('/labels')) return { status: 200, body: labelsFixture } }) const context = await getEmailContext({ url: THREAD_ID, account: 'business', maxBodyChars: 7 }) assert.equal(context.messages[0].body, 'Hi Kent') assert.equal(context.messages[0].truncated, true) assert.equal(context.messages[0].bodyLength, 'Hi Kent \u2013 caf\u00e9 \ud83c\udf89\n\nSee attached.'.length) }) it('falls back from thread id to message id', async () => { const calls = mockFetch(({ path }) => { if (path.endsWith('/threads/' + SECOND_ID)) return { status: 404, body: { error: { message: 'Requested entity was not found.' } } } if (path.endsWith('/messages/' + SECOND_ID)) return { status: 200, body: { id: SECOND_ID, threadId: THREAD_ID } } if (path.endsWith('/threads/' + THREAD_ID)) return { status: 200, body: threadFixture() } if (path.endsWith('/labels')) return { status: 200, body: labelsFixture } }) const context = await getEmailContext({ url: 'https://mail.google.com/mail/u/0/#inbox/' + SECOND_ID, account: 'personal' }) assert.equal(context.threadId, THREAD_ID) assert.equal(context.requestedMessageId, SECOND_ID) assert.equal(context.link, 'https://mail.google.com/mail/?authuser=kent.c.dodds@gmail.com#all/' + THREAD_ID) assert.deepEqual(calls.map((c) => c.path.split('/').slice(-2).join('/')), ['threads/' + SECOND_ID, 'messages/' + SECOND_ID, 'threads/' + THREAD_ID, 'me/labels']) assert.equal(calls[1].search.get('format'), 'minimal') }) it('tries each Gmail account when the link has no authuser email', async () => { const calls = mockFetch(({ path, credential }) => { if (credential !== 'google') return undefined if (path.endsWith('/threads/' + THREAD_ID)) return { status: 200, body: threadFixture() } if (path.endsWith('/labels')) return { status: 200, body: labelsFixture } }) const context = await getEmailContext({ url: 'https://mail.google.com/mail/u/0/#all/' + THREAD_ID }) assert.equal(context.account, 'personal') assert.deepEqual([...new Set(calls.map((c) => c.credential))], ['google-business', 'google']) }) it('throws not_found, auth, and request errors with the failing step', async () => { mockFetch(() => undefined) await assert.rejects(getEmailContext({ url: THREAD_ID, account: 'business' }), (e: unknown) => e instanceof GmailContextError && e.step === 'not_found' && /no thread or message/.test(e.message)) mockFetch(() => ({ status: 401, body: { error: { message: 'Invalid Credentials' } } })) await assert.rejects(getEmailContext({ url: THREAD_ID }), (e: unknown) => e instanceof GmailContextError && e.step === 'auth' && /business/.test(e.message) && /personal/.test(e.message)) mockFetch(() => ({ status: 500, body: { error: { message: 'Backend Error' } } })) await assert.rejects(getEmailContext({ url: THREAD_ID, account: 'business' }), (e: unknown) => e instanceof GmailContextError && e.step === 'request' && e.status === 500) await assert.rejects(getEmailContext({ url: THREAD_ID, maxBodyChars: -1 }), (e: unknown) => e instanceof GmailContextError && e.step === 'input') }) })