import pMap from "p-map" import * as z from "zod" import { defineAction } from "../../../automation/actions" import { getGmailApi, getGmailMessage, } from "@automate.ax/integration-contracts/gmail" import { GMAIL_READ_REQUIREMENT } from "../lib/scopes" import { THREAD_SCHEMA } from "@automate.ax/integration-contracts/gmail" /** Retrieves one Gmail thread with every message fully parsed. */ export const getGmailThread = defineAction("Get Gmail thread") .describe("Gets a Gmail thread with parsed messages and attachments.") .account("google", GMAIL_READ_REQUIREMENT) .input( z.object({ /** Immutable Gmail thread ID. */ threadId: z.string().min(1), }), ) .output(THREAD_SCHEMA) .retry({ replaySafety: "safe" }) .handler(async ({ account, input }) => { const gmailApi = getGmailApi(account.secret) const { data: thread } = await gmailApi.users.threads.get({ format: "minimal", id: input.threadId, userId: "me", }) if (!thread.id) throw new Error("Gmail returned an incomplete thread.") return { historyId: thread.historyId ?? undefined, messages: await pMap( thread.messages ?? [], async ({ id }) => { if (!id) throw new Error("Gmail returned an incomplete thread message.") return getGmailMessage( ( await gmailApi.users.messages.get({ format: "raw", id, userId: "me", }) ).data, ) }, { concurrency: 20 }, ), threadId: thread.id, } })